Data structureadvanced
Hidden classes
Also called object maps, object shapes.
Shared descriptors of object layout for dynamic languages, so that objects with the same fields have fixed offsets for fast access.
- Time
- O(k) cached-loadO(1) get · setO(p) new-shape
- Space
- O(T p) extra
- Where
- T = the number of shapes created; k = the bound of a load cache; p = the number of own properties of an object
- Model
- Word RAM
- Evidence
- Proof sketchCode in 1 languages
A hidden class, also called a map or a shape, is a descriptor of the layout of an object in a dynamic language: which properties the object has and at which offset each value is stored. Many objects share one hidden class, so each object stores only a pointer to it and an array of values. A program never sees hidden classes. The runtime makes them as the program adds properties: adding a property to an object moves it from its hidden class to a child hidden class along a transition, and objects that got the same properties in the same order end at the same hidden class. With that, a property read becomes a check of the hidden class and a load at a fixed offset, which an inline cache can remember. SELF introduced maps in 1989 for objects made by cloning, and JavaScript engines such as V8 build them by transitions.
In plain words
In JavaScript or Python, an object is like a small dictionary: you can add a field at any time, and each object can have different fields. If every object keeps its own table of field names, a read like p.x must search that table each time, and every object pays for its own table.
Hidden classes share the tables. All objects that got the fields x and then y point to one shared description that says "x is in slot 0, y is in slot 1". The object itself keeps only the values. When a field is added, the object moves to the next description in a tree of descriptions, and the tree remembers each step so that other objects reuse it. A read can then check "is this object's description the one I saw last time?" and, if yes, take slot 0 at once.
The abstract type
A runtime has classes, each with a method table and an optional parent, as in the model of the polymorphic inline cache. An object belongs to a class and has a set of own properties, each a name with a value. The operations are:
- NEW(). A new object of class with no own properties.
- SET(, , ). Give the own property with value , adding it if it is not there.
- DELETE(, ). Remove the own property from .
- GET(, ). The value of the own property of if there is one, and otherwise the method found through the chain of classes of , or "missing".
- SHAPE(). The hidden class of , or none.
- LOAD(site, ). GET(, ) for the fixed name of a site, through a load cache.
The required result is that GET and LOAD give the same answer as a plain dictionary per object plus a full method lookup, for every sequence of operations.
Representation
A shape is an immutable record with:
- , the class of the objects that have it;
- and : the shape it came from and the name added, both empty for a root shape;
- : a hash table from each property name to a slot number, equal to plus ;
- : a table from a name to the child shape that adds . Entries are added, never removed.
Each class has one root shape. The shapes and transitions form a tree under each root, with an edge labelled by a property name, which is a trie of the orders in which properties were added. The names of , read from the root down, are the order in which they were added, and maps them to in that order.
An object holds its class, a shape , and an array . After a deletion it moves to dictionary mode: its shape is empty and it holds its own properties in a private hash table.
A load cache at a site that reads the name is a polymorphic inline cache keyed by shapes. Each entry is one of:
- : objects of shape hold at slot ;
- : objects of shape have no own , and the class chain of gives the answer .
Operations
NEW(C)
L1 return an object with class C, shape root(C), empty slots
TRANSITION(S, x)
L2 if x is not in transitions(S) then transitions(S)[x] ← a new shape with parent S and key x
L3 return transitions(S)[x]
SET(o, x, v)
L4 if o is in dictionary mode then o.dict[x] ← v; return
L5 if x is in offsets(shape(o)) then slots(o)[offsets(shape(o))[x]] ← v
L6 else shape(o) ← TRANSITION(shape(o), x); append v to slots(o)
DELETE(o, x)
L7 if o is not in dictionary mode and x is in offsets(shape(o)) then
L8 o.dict ← the pairs (y, slots(o)[i]) for (y, i) in offsets(shape(o)); shape(o) ← none
L9 if o is in dictionary mode then remove x from o.dict
GET(o, x)
L10 if o is in dictionary mode and x is in o.dict then return o.dict[x]
L11 if o is not in dictionary mode and x is in offsets(shape(o)) then return slots(o)[offsets(shape(o))[x]]
L12 return LOOKUP(class(o), x) ▷ walk the class chain
LOAD(site, o)
L13 if site is megamorphic or o is in dictionary mode then return GET(o, x)
L14 for each entry (S, kind, d) of the site: if S = shape(o) then
L15 if kind = field then return slots(o)[d] else return d
L16 compute the entry for shape(o) as in L11 and L12, add it as in a polymorphic inline cache, and return the answer
Changing a method of a class removes the class entries whose has in its chain, exactly as for a polymorphic inline cache. Field entries never need invalidation, because a shape never changes: an object that gets a new property moves to another shape instead.
Example
Take a class Point, child of Object, with a method norm. Make three objects and add properties in these orders:
p:x = 3, theny = 4;q:y = 5, thenx = 6;r:x = 7, theny = 8.
The shape tree under the root of Point grows to
S0 {}
├── x → S1 {x: 0}
│ └── y → S2 {x: 0, y: 1}
└── y → S3 {y: 0}
└── x → S4 {y: 0, x: 1}
p creates and , q creates and , and r follows the transitions that p made and creates nothing. So p and r share , with slots and , and q has with slots . With the root shape of Object, the runtime has made 6 shapes in total.
A load site o.x with bound 2 reads p, q, r, p:
| read | shape | result | entry used or added | answer |
|---|---|---|---|---|
p.x |
miss | add | 3 | |
q.x |
miss | add | 6 | |
r.x |
hit | 7 | ||
p.x |
hit | 3 |
The site ends polymorphic, with 2 hits and 2 misses. The entry for answers for r although it was made for p, because both have the same layout. A site o.norm gets the entries and , and loses both if a method norm is added to Point or changed in Object.
If the program now deletes y from q, then q goes to dictionary mode with the table , and no load cache stores anything for it.
Correctness
The full proof is in the proof file. Its main steps:
- Shapes are immutable and describe exact layouts. By line L2, a new shape has its parent's offsets plus one new name at the next slot, and line L6 calls TRANSITION only for a name that is not in the offsets yet. So is a one-to-one map from the names of onto .
- Object invariant. For an object not in dictionary mode, the own property names of are exactly the names of , the value of each name is , and the class of the shape is the class of . Lines L5 and L6 keep it, and line L8 copies the exact properties into the private table before the shape is dropped.
- Sharing. The shape of an object not in dictionary mode is found from the root of its class by following the transitions for its names in the order of addition. Transitions are deterministic and never removed, so objects of the same class with the same order have the same shape, and a shape determines the class and the order, so different classes or orders give different shapes.
- GET and LOAD. GET is right by the object invariant. A field entry stays right forever, because is immutable and every object of shape holds at slot . A class entry depends on the class chain, and the invalidation keeps it right by the same locality argument as for the polymorphic inline cache.
Proof: Reads through hidden classes and load caches equal a dictionary lookupfull
We use lines L1 to L16 from the page. The reference model keeps, for each object , a dictionary of its own properties, changed by SET and DELETE in the obvious way, and answers if , and otherwise. LOOKUP walks the chain of parent classes as on the page of the polymorphic inline cache. Let be the list of the names in in the order in which they were first added. For a shape , let be the list of keys on the path from the root to , from the top down, with for a root.
Lemma 1 (shapes). Every shape , once created, never changes its class, parent, key or offsets. Its offsets satisfy: the keys of are the elements of , these are distinct, and the -th name, counting from 0, has offset . Also for a shape that is not a root.
Proof. No line writes the class, parent, key or offsets of an existing shape; line L2 only adds an entry to . The statement on offsets is by induction on the order of creation. A root has empty offsets and no names. A shape created at line L2 from with key gets plus , the class of , and followed by . TRANSITION is called only from line L6, when is not in , and there. So is new, the names stay distinct, and is the name at position with that offset.
Lemma 2 (object invariant). At every point of a run, for every object :
- if is in dictionary mode, then ;
- otherwise , , , and for each in .
Proof. By induction on the steps. Line L1 gives the root shape of , no slots, and an empty dictionary in the model, which satisfies part 2. Steps on other objects do not touch , and shapes do not change by Lemma 1. Consider SET(, , ). In dictionary mode, line L4 makes the same change as the model. Otherwise, if is already in the offsets, then by part 2 and Lemma 1 is in , the model only changes its value, and line L5 writes the slot of , so part 2 holds again. If is not in the offsets, then is not in ; the model adds at the end of , and line L6 moves to a shape with , the same class, and the new offset for , at which line L6 appends . Consider DELETE(, ). If is not in dictionary mode and is not an own property, nothing changes in either model. If is not in dictionary mode and is own, line L8 builds from the pairs , which is by part 2, and line L9 then removes from both. In dictionary mode, line L9 removes from both.
Theorem 1 (GET). GET(, ) at every point of a run.
Proof. In dictionary mode, line L10 returns when is own, by part 1 of Lemma 2, and otherwise line L12 returns LOOKUP, as the model does. Not in dictionary mode, is in the offsets exactly when , by Lemma 1 and part 2. Then line L11 returns . Otherwise line L12 returns .
Theorem 2 (sharing). Let and be objects that are not in dictionary mode. Then if and only if and .
Proof. For a class and a list of distinct names , write for the shape reached from the root of by following the transitions labelled , if they exist. Each shape has at most one child per name, and transitions are never removed or replaced, so is a single shape once it exists and stays the same forever. By induction on the steps, for every object not in dictionary mode: it holds after line L1, line L5 changes neither side, and line L6 extends by and moves along the transition labelled . So equal class and order give equal shapes. Conversely, a shape determines its class and its names, and by Lemma 2 these are the class and order of every object that has it. So equal shapes give equal class and order.
Load caches. A load cache at a site with name has entries and with distinct shapes, at most of them, and a megamorphic flag. When a method table or a parent of a class changes, the runtime first removes every class entry whose has in its chain. Let be the invariant: for each field entry, ; for each class entry, is not in and under the current classes.
Lemma 3. holds at every point of a run.
Proof. It holds for an empty cache. Line L16 adds an entry for as computed at lines L11 and L12: a field entry with , or, when is not in the offsets, a class entry with , and by Lemma 2. A field entry depends only on , which never changes by Lemma 1. A class entry also depends on the class chain. If a class changes, the entries whose class has in its chain are removed first, and for the others the chain does not hold , so the lookup result is unchanged by the locality lemma (Lemma 1 of the proof for the polymorphic inline cache). Changes of objects do not touch entries.
Theorem 3 (LOAD). LOAD(site, ) at every point of a run.
Proof. If the site is megamorphic or is in dictionary mode, line L13 returns GET(, ), which is right by Theorem 1. Otherwise, on a hit at line L14 the entry has . For a field entry, by , so line L15 returns , which is by Lemma 2. For a class entry, is not in the offsets of , so by Lemma 2, and by and Lemma 2. On a miss, line L16 returns the answer of lines L11 and L12, which is right by Theorem 1.
The state machine of the load cache, uninitialized, monomorphic, polymorphic up to the bound and megamorphic, is the one proved for the polymorphic inline cache, with shapes in place of classes, since lines L13 to L16 add and remove entries by the same rules.
Complexity
GET, and SET of an existing property, cost one hash-table look-up in the offsets, so expected, plus the walk of the class chain when the name is not an own property. SET of a new property follows a transition in expected time, and costs once, when it creates a new shape, to copy the offsets. A load cache hit costs at most comparisons of shape pointers and one array access, with no hashing at all, which is the reason for the whole design.
The space for shapes is with copied offset tables. Engines lower it by sharing one array of property descriptors between a shape and its descendants on the same path. Each object costs one pointer and its values, instead of a hash table of its own. The number of shapes is the number of distinct pairs of a class and an order of addition that the program creates, counted with all their prefixes. A program that adds properties in many orders makes many shapes.
Variants
- SELF maps. In SELF, objects are made by cloning a prototype, and all clones share the map of the prototype. A map also holds the constant slots, such as methods, so they are not stored in each object.
- The prototype in the shape. In V8 the prototype of an object is part of its hidden class, so objects with the same properties but different prototypes have different shapes. Ahn and others show that this causes extra polymorphism at inline caches in real web code.
- Dictionary mode. After a deletion, or with very many properties, an engine gives up on shapes for the object and uses a private hash table, as in lines L7 to L9.
- Field types in the shape. A shape can also record that a field has always held a small integer or a double, so that compiled code can skip a type check. When a store breaks that, the engine makes a new shape and must deoptimize code that relied on the old one.
- In-object slack. An engine can reserve a few slots inside each new object, guessed from the constructor, so that the first properties need no separate array.
- Hidden classes for arrays. The kind of elements of an array, such as only small integers, can be part of its hidden class in the same way.
When to use it
Use hidden classes in the runtime of a language whose objects can gain properties at any time, when many objects in fact get the same properties in the same order, as objects made by one constructor do. They pay off together with inline caches and a JIT compiler, which turn a cached shape check into a compare and a load. For a language with fixed records declared ahead, a static layout is simpler. For objects used as general dictionaries with many keys, a plain hash table is better, which is why engines have dictionary mode.
Pitfalls
- Order matters.
{x, y}and{y, x}are different shapes. Code that adds properties in a different order on different paths makes sites polymorphic. Constructors that set all fields in a fixed order avoid that. - Deletion. Deleting a property moves an object to dictionary mode, where load caches do not help. Setting a property to an empty value instead keeps the shape.
- Forgetting the class part. A cached method entry depends on the class chain, not only on the shape. It needs invalidation when a method in the chain changes, while a field entry does not.
- Mutating a shape. Shapes are shared. Changing one in place, for example to add a property to one object, changes the layout of every object that has it. Always move the object to a new shape.
- Too many shapes. Properties named by data, such as keys read from input, make one shape per distinct order. Engines limit the number of transitions per shape and switch such objects to dictionary mode.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hidden-classes/. The authors are listed in prov/S7XDVF.jsonl.
"""Hidden classes (shapes) for a small dynamic object model.
An object has a class, for methods, and its own properties, which can be
added at any time. The layout of the own properties is described by a shape.
Shapes form a tree: each class has a root shape with no properties, and adding
a property follows, or creates, a transition to a child shape. Objects that
got the same properties in the same order share one shape and store their
values at the same offsets. Deleting a property moves the object to
dictionary mode, where it has no shape.
A load inline cache keyed by shapes caches, per site, either the offset of an
own property or the method found through the class chain.
"""
from __future__ import annotations
from dataclasses import dataclass, field
UNINITIALIZED = "uninitialized"
MONOMORPHIC = "monomorphic"
POLYMORPHIC = "polymorphic"
MEGAMORPHIC = "megamorphic"
MISSING = ("missing",)
@dataclass(frozen=True)
class Method:
owner: str
name: str
ident: int
@dataclass(eq=False)
class Klass:
name: str
parent: Klass | None = None
methods: dict[str, Method] = field(default_factory=dict)
root: Shape | None = None
def chain(self) -> list[Klass]:
out: list[Klass] = []
k: Klass | None = self
while k is not None:
out.append(k)
k = k.parent
return out
class Shape:
"""An immutable layout: the class, and the own property names with their offsets."""
__slots__ = ("klass", "parent", "key", "offsets", "transitions", "ident")
def __init__(self, klass: Klass, parent: Shape | None, key: str | None, ident: int) -> None:
self.klass = klass
self.parent = parent
self.key = key
self.ident = ident
self.offsets: dict[str, int] = dict(parent.offsets) if parent is not None else {}
if key is not None:
self.offsets[key] = len(self.offsets)
self.transitions: dict[str, Shape] = {}
def names(self) -> list[str]:
"""The property names in the order in which they were added."""
out: list[str] = []
s: Shape | None = self
while s is not None and s.key is not None:
out.append(s.key)
s = s.parent
return out[::-1]
class Obj:
__slots__ = ("klass", "shape", "slots", "dictionary")
def __init__(self, klass: Klass) -> None:
self.klass = klass
self.shape: Shape | None = klass.root
self.slots: list[object] = []
self.dictionary: dict[str, object] | None = None
class Runtime:
def __init__(self) -> None:
self.classes: dict[str, Klass] = {}
self.sites: list[LoadIC] = []
self.shape_count = 0
self._next = 0
def _new_shape(self, klass: Klass, parent: Shape | None, key: str | None) -> Shape:
self.shape_count += 1
return Shape(klass, parent, key, self.shape_count)
def define_class(self, name: str, parent: str | None = None) -> Klass:
if name in self.classes:
raise ValueError("class already defined: " + name)
k = Klass(name, self.classes[parent] if parent is not None else None)
k.root = self._new_shape(k, None, None)
self.classes[name] = k
return k
def _changed(self, d: Klass) -> None:
for site in self.sites:
site.invalidate(d)
def set_method(self, cls: str, name: str) -> Method:
d = self.classes[cls]
self._changed(d)
self._next += 1
m = Method(cls, name, self._next)
d.methods[name] = m
return m
def remove_method(self, cls: str, name: str) -> None:
d = self.classes[cls]
if name in d.methods:
self._changed(d)
del d.methods[name]
def new(self, cls: str) -> Obj:
return Obj(self.classes[cls])
def transition(self, shape: Shape, key: str) -> Shape:
child = shape.transitions.get(key)
if child is None:
child = self._new_shape(shape.klass, shape, key)
shape.transitions[key] = child
return child
def set(self, o: Obj, key: str, value: object) -> None:
if o.dictionary is not None:
o.dictionary[key] = value
return
assert o.shape is not None
i = o.shape.offsets.get(key)
if i is not None:
o.slots[i] = value
else:
o.shape = self.transition(o.shape, key)
o.slots.append(value)
def delete(self, o: Obj, key: str) -> None:
"""Remove an own property. The object leaves the shape tree for dictionary mode."""
if o.dictionary is None:
assert o.shape is not None
if key not in o.shape.offsets:
return
o.dictionary = {k: o.slots[i] for k, i in o.shape.offsets.items()}
o.shape = None
o.slots = []
o.dictionary.pop(key, None)
def own(self, o: Obj) -> dict[str, object]:
if o.dictionary is not None:
return dict(o.dictionary)
assert o.shape is not None
return {k: o.slots[i] for k, i in o.shape.offsets.items()}
def lookup_method(self, k: Klass, name: str) -> Method | tuple[str]:
for d in k.chain():
m = d.methods.get(name)
if m is not None:
return m
return MISSING
def get(self, o: Obj, key: str) -> object:
"""The full lookup: an own property first, then a method of the class chain."""
if o.dictionary is not None:
if key in o.dictionary:
return o.dictionary[key]
else:
assert o.shape is not None
i = o.shape.offsets.get(key)
if i is not None:
return o.slots[i]
return self.lookup_method(o.klass, key)
def site(self, key: str, bound: int = 4) -> LoadIC:
s = LoadIC(self, key, bound)
self.sites.append(s)
return s
class LoadIC:
"""A polymorphic inline cache for the read o.key, keyed by shape.
An entry (shape, "field", offset) says that objects of this shape hold key
at that offset. An entry (shape, "class", answer) says that they have no
own key and that the class chain gives answer. Shapes never change, so
only "class" entries need invalidation, when a class in the chain changes.
Objects in dictionary mode are not cached.
"""
def __init__(self, rt: Runtime, key: str, bound: int = 4) -> None:
if bound < 1:
raise ValueError("bound must be at least 1")
self.rt = rt
self.key = key
self.bound = bound
self.entries: list[tuple[Shape, str, object]] = []
self.megamorphic = False
self.hits = 0
self.misses = 0
self.history: list[str] = [UNINITIALIZED]
@property
def state(self) -> str:
if self.megamorphic:
return MEGAMORPHIC
if not self.entries:
return UNINITIALIZED
return MONOMORPHIC if len(self.entries) == 1 else POLYMORPHIC
def _record(self) -> None:
if self.history[-1] != self.state:
self.history.append(self.state)
def load(self, o: Obj) -> object:
if self.megamorphic or o.shape is None:
self.misses += 1
return self.rt.get(o, self.key)
for s, kind, data in self.entries:
if s is o.shape:
self.hits += 1
if kind == "field":
assert isinstance(data, int)
return o.slots[data]
return data
self.misses += 1
i = o.shape.offsets.get(self.key)
if i is not None:
entry: tuple[Shape, str, object] = (o.shape, "field", i)
result = o.slots[i]
else:
result = self.rt.lookup_method(o.klass, self.key)
entry = (o.shape, "class", result)
if len(self.entries) < self.bound:
self.entries.append(entry)
else:
self.entries = []
self.megamorphic = True
self._record()
return result
def invalidate(self, d: Klass) -> None:
kept = [e for e in self.entries if e[1] == "field" or d not in e[0].klass.chain()]
if len(kept) != len(self.entries):
self.entries = kept
self._record()
def example() -> dict[str, object]:
"""The worked example of the page."""
rt = Runtime()
rt.define_class("Object")
rt.define_class("Point", "Object")
norm = rt.set_method("Point", "norm")
p, q, r = rt.new("Point"), rt.new("Point"), rt.new("Point")
rt.set(p, "x", 3)
rt.set(p, "y", 4)
rt.set(q, "y", 5)
rt.set(q, "x", 6)
rt.set(r, "x", 7)
rt.set(r, "y", 8)
site = rt.site("x", bound=2)
reads = [site.load(o) for o in (p, q, r, p)]
nsite = rt.site("norm", bound=2)
nreads = [nsite.load(o) for o in (p, q)]
return {
"shapes": rt.shape_count,
"p_is_r": p.shape is r.shape,
"p_is_q": p.shape is q.shape,
"p_offsets": dict(p.shape.offsets) if p.shape else None,
"q_offsets": dict(q.shape.offsets) if q.shape else None,
"reads": reads,
"hits": site.hits,
"misses": site.misses,
"state": site.state,
"norm": all(m == norm for m in nreads),
}
if __name__ == "__main__":
for k, v in example().items():
print(k, v)
test_hidden_classes.py 228 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hidden-classes/. The authors are listed in prov/S7XDVF.jsonl.
import random
import pytest
from hidden_classes import (
MEGAMORPHIC,
MISSING,
MONOMORPHIC,
POLYMORPHIC,
UNINITIALIZED,
Runtime,
example,
)
def test_example():
assert example() == {
"shapes": 6,
"p_is_r": True,
"p_is_q": False,
"p_offsets": {"x": 0, "y": 1},
"q_offsets": {"y": 0, "x": 1},
"reads": [3, 6, 7, 3],
"hits": 2,
"misses": 2,
"state": POLYMORPHIC,
"norm": True,
}
def ref_lookup(parent, methods, cls, key):
while cls is not None:
if key in methods[cls]:
return methods[cls][key]
cls = parent[cls]
return MISSING
def random_run(seed):
rng = random.Random(seed)
rt = Runtime()
parent = {}
methods = {}
cnames = ["C%d" % i for i in range(rng.randint(1, 4))]
for i, c in enumerate(cnames):
p = rng.choice(cnames[:i]) if i > 0 and rng.random() < 0.7 else None
rt.define_class(c, p)
parent[c] = p
methods[c] = {}
keys = ["a", "b", "c", "d", "e"]
for _ in range(rng.randint(0, 4)):
c, k = rng.choice(cnames), rng.choice(keys)
methods[c][k] = rt.set_method(c, k)
objs = []
ref = []
order = []
deleted = []
prefixes = set()
for _ in range(rng.randint(4, 12)):
c = rng.choice(cnames)
objs.append(rt.new(c))
ref.append({})
order.append([])
deleted.append(False)
sites = [rt.site(rng.choice(keys), rng.randint(1, 4)) for _ in range(4)]
reads = 0
for _ in range(250):
r = rng.random()
i = rng.randrange(len(objs))
o = objs[i]
if r < 0.35:
k = rng.choice(keys[: rng.randint(1, len(keys))])
v = rng.randrange(1000)
rt.set(o, k, v)
if k not in ref[i]:
order[i].append(k)
ref[i][k] = v
elif r < 0.38:
k = rng.choice(keys)
rt.delete(o, k)
if k in ref[i]:
deleted[i] = True
del ref[i][k]
order[i].remove(k)
elif r < 0.42:
c, k = rng.choice(cnames), rng.choice(keys)
if rng.random() < 0.7:
methods[c][k] = rt.set_method(c, k)
else:
rt.remove_method(c, k)
methods[c].pop(k, None)
else:
site = rng.choice(sites)
before = (site.megamorphic, len(site.entries))
hits = site.hits
got = site.load(o)
want = ref[i][site.key] if site.key in ref[i] else ref_lookup(parent, methods, o.klass.name, site.key)
assert got == want
assert rt.get(o, site.key) == want
reads += 1
if before[0]:
assert site.megamorphic
elif site.hits > hits or o.shape is None:
assert (site.megamorphic, len(site.entries)) == before
elif before[1] < site.bound:
assert len(site.entries) == before[1] + 1
else:
assert site.megamorphic and not site.entries
for j, oj in enumerate(objs):
assert rt.own(oj) == ref[j]
for k in keys:
want = ref[j][k] if k in ref[j] else ref_lookup(parent, methods, oj.klass.name, k)
assert rt.get(oj, k) == want
if deleted[j]:
assert oj.shape is None
continue
s = oj.shape
assert s is not None and s.klass is oj.klass
assert s.names() == order[j]
assert len(oj.slots) == len(s.offsets)
for k, off in s.offsets.items():
assert oj.slots[off] == ref[j][k]
for n in range(len(order[j]) + 1):
prefixes.add((oj.klass.name, tuple(order[j][:n])))
for site in sites:
shapes = [e[0] for e in site.entries]
assert len(shapes) == len({id(s) for s in shapes}) <= site.bound
for s, kind, data in site.entries:
if kind == "field":
assert s.offsets[site.key] == data
else:
assert site.key not in s.offsets
assert data == ref_lookup(parent, methods, s.klass.name, site.key)
live = [j for j in range(len(objs)) if not deleted[j]]
for a in live:
for b in live:
same = (objs[a].klass is objs[b].klass) and order[a] == order[b]
assert (objs[a].shape is objs[b].shape) == same
assert rt.shape_count == len(prefixes | {(c, ()) for c in cnames})
return reads
def test_random_programs():
total = 0
for seed in range(120):
total += random_run(seed)
assert total > 15000
def test_same_order_shares_shape_different_order_does_not():
rng = random.Random(7)
rt = Runtime()
rt.define_class("A")
names = ["p%d" % i for i in range(6)]
by_order = {}
for _ in range(300):
seq = rng.sample(names, rng.randint(0, 6))
o = rt.new("A")
for k in seq:
rt.set(o, k, k.upper())
by_order.setdefault(tuple(seq), set()).add(id(o.shape))
assert {k: o.slots[i] for k, i in o.shape.offsets.items()} == {k: k.upper() for k in seq}
assert all(len(v) == 1 for v in by_order.values())
all_shapes = [next(iter(v)) for v in by_order.values()]
assert len(set(all_shapes)) == len(all_shapes)
@pytest.mark.parametrize("bound", [1, 2, 4])
def test_load_ic_state_machine(bound):
rt = Runtime()
rt.define_class("A")
objs = []
for j in range(bound + 2):
o = rt.new("A")
for i in range(j):
rt.set(o, "pad%d" % i, i)
rt.set(o, "x", j)
objs.append(o)
for j in range(1, bound + 3):
site = rt.site("x", bound)
for o in objs[:j] * 2:
assert site.load(o) == objs.index(o)
if j <= bound:
assert len(site.entries) == j and site.hits == j
assert site.state == (MONOMORPHIC if j == 1 else POLYMORPHIC)
else:
assert site.state == MEGAMORPHIC
full = [UNINITIALIZED, MONOMORPHIC, POLYMORPHIC, MEGAMORPHIC]
if bound == 1:
full = [UNINITIALIZED, MONOMORPHIC, MEGAMORPHIC]
assert site.history == full[: len(site.history)]
def test_class_entries_invalidated_field_entries_kept():
rt = Runtime()
rt.define_class("Base")
rt.define_class("A", "Base")
m1 = rt.set_method("Base", "f")
a1 = rt.new("A")
a2 = rt.new("A")
rt.set(a2, "f", 99)
site = rt.site("f", bound=4)
assert site.load(a1) == m1
assert site.load(a2) == 99
assert [e[1] for e in site.entries] == ["class", "field"]
m2 = rt.set_method("A", "f")
assert [e[1] for e in site.entries] == ["field"]
assert site.load(a1) == m2
assert site.load(a2) == 99
def test_dictionary_mode_is_not_cached():
rt = Runtime()
rt.define_class("A")
o = rt.new("A")
rt.set(o, "x", 1)
rt.set(o, "y", 2)
rt.delete(o, "x")
assert o.shape is None and rt.own(o) == {"y": 2}
site = rt.site("y")
assert site.load(o) == 2 and site.load(o) == 2
assert site.state == UNINITIALIZED and site.misses == 2
assert site.load(o) == 2
rt.set(o, "x", 5)
assert rt.get(o, "x") == 5
History
Chambers, Ungar and Lee introduced maps in their 1989 implementation of SELF, a language with prototypes and no classes. All clones of a prototype share one map, which gives the compiler and the inline caches something that behaves like a class. Hölzle, Chambers and Ungar used maps as the types in polymorphic inline caches in 1991. JavaScript engines took up the idea for a language where objects are often built by adding properties one at a time. V8 builds its hidden classes by transitions from an empty root, and Ahn and others described this design in 2014 when they studied its effect on inline caches.
References
- Craig Chambers, David Ungar and Elgin Lee, An efficient implementation of SELF, a dynamically-typed object-oriented language based on prototypes, OOPSLA 1989, 49-70, the section on maps, where clones of the same prototype share one map that describes the names and layout of their slots, so each object stores only the values of its assignable slots
- Wonsun Ahn, Jiho Choi, Thomas Shull, María J. Garzarán and Josep Torrellas, Improving JavaScript performance by deconstructing the type system, PLDI 2014, 496-507, the description of hidden classes in the V8 engine, their transitions when properties are added, their use as the key of inline caches, and the extra polymorphism that comes from the prototype being part of the hidden class
- Urs Hölzle, Craig Chambers and David Ungar, Optimizing dynamically-typed object-oriented languages with polymorphic inline caches, ECOOP 1991, LNCS 512, 21-38, the use of SELF maps as the receiver types tested by inline caches and polymorphic inline caches
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag S7XDVF Edit this page History Report an error Markdown