Algorithm Search⌘K

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

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(CC). A new object of class CC with no own properties.
  • SET(oo, xx, vv). Give oo the own property xx with value vv, adding it if it is not there.
  • DELETE(oo, xx). Remove the own property xx from oo.
  • GET(oo, xx). The value of the own property xx of oo if there is one, and otherwise the method xx found through the chain of classes of oo, or "missing".
  • SHAPE(oo). The hidden class of oo, or none.
  • LOAD(site, oo). GET(oo, xx) for the fixed name xx 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 SS is an immutable record with:

  • class(S)\mathit{class}(S), the class of the objects that have it;
  • parent(S)\mathit{parent}(S) and key(S)\mathit{key}(S): the shape it came from and the name added, both empty for a root shape;
  • offsets(S)\mathit{offsets}(S): a hash table from each property name to a slot number, equal to offsets(parent(S))\mathit{offsets}(\mathit{parent}(S)) plus key(S)↦∣offsets(parent(S))∣\mathit{key}(S) \mapsto |\mathit{offsets}(\mathit{parent}(S))|;
  • transitions(S)\mathit{transitions}(S): a table from a name xx to the child shape that adds xx. 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 SS, read from the root down, are the order in which they were added, and offsets(S)\mathit{offsets}(S) maps them to 0,1,…0, 1, \dots in that order.

An object oo holds its class, a shape shape(o)\mathit{shape}(o), and an array slots(o)\mathit{slots}(o). 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 xx is a polymorphic inline cache keyed by shapes. Each entry is one of:

  • (S,field,i)(S, \text{field}, i): objects of shape SS hold xx at slot ii;
  • (S,class,a)(S, \text{class}, a): objects of shape SS have no own xx, and the class chain of class(S)\mathit{class}(S) gives the answer aa.

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 DD removes the class entries (S,class,a)(S, \text{class}, a) whose class(S)\mathit{class}(S) has DD 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, then y = 4;
  • q: y = 5, then x = 6;
  • r: x = 7, then y = 8.

The shape tree under the root S0S_0 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 S1S_1 and S2S_2, q creates S3S_3 and S4S_4, and r follows the transitions that p made and creates nothing. So p and r share S2S_2, with slots [3,4][3, 4] and [7,8][7, 8], and q has S4S_4 with slots [5,6][5, 6]. 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 S2S_2 miss add (S2,field,0)(S_2, \text{field}, 0) 3
q.x S4S_4 miss add (S4,field,1)(S_4, \text{field}, 1) 6
r.x S2S_2 hit (S2,field,0)(S_2, \text{field}, 0) 7
p.x S2S_2 hit (S2,field,0)(S_2, \text{field}, 0) 3

The site ends polymorphic, with 2 hits and 2 misses. The entry for S2S_2 answers for r although it was made for p, because both have the same layout. A site o.norm gets the entries (S2,class,Point.norm)(S_2, \text{class}, \text{Point.norm}) and (S4,class,Point.norm)(S_4, \text{class}, \text{Point.norm}), 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 {x:6}\{x: 6\}, and no load cache stores anything for it.

Correctness

The full proof is in the proof file. Its main steps:

  1. 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 offsets(S)\mathit{offsets}(S) is a one-to-one map from the names of SS onto 0,…,∣S∣−10, \dots, |S| - 1.
  2. Object invariant. For an object oo not in dictionary mode, the own property names of oo are exactly the names of shape(o)\mathit{shape}(o), the value of each name yy is slots(o)[offsets(shape(o))[y]]\mathit{slots}(o)[\mathit{offsets}(\mathit{shape}(o))[y]], and the class of the shape is the class of oo. Lines L5 and L6 keep it, and line L8 copies the exact properties into the private table before the shape is dropped.
  3. 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.
  4. GET and LOAD. GET is right by the object invariant. A field entry (S,field,i)(S, \text{field}, i) stays right forever, because SS is immutable and every object of shape SS holds xx at slot ii. 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 oo, a dictionary own(o)\mathit{own}(o) of its own properties, changed by SET and DELETE in the obvious way, and answers GET∗(o,x)=own(o)[x]\mathrm{GET}^*(o, x) = \mathit{own}(o)[x] if x∈own(o)x \in \mathit{own}(o), and LOOKUP(class(o),x)\mathrm{LOOKUP}(\mathit{class}(o), x) otherwise. LOOKUP walks the chain of parent classes as on the page of the polymorphic inline cache. Let order(o)\mathit{order}(o) be the list of the names in own(o)\mathit{own}(o) in the order in which they were first added. For a shape SS, let names(S)\mathit{names}(S) be the list of keys on the path from the root to SS, from the top down, with names(S)=()\mathit{names}(S) = () for a root.

Lemma 1 (shapes). Every shape SS, once created, never changes its class, parent, key or offsets. Its offsets satisfy: the keys of offsets(S)\mathit{offsets}(S) are the elements of names(S)\mathit{names}(S), these are distinct, and the jj-th name, counting from 0, has offset jj. Also class(S)=class(parent(S))\mathit{class}(S) = \mathit{class}(\mathit{parent}(S)) 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 transitions\mathit{transitions}. The statement on offsets is by induction on the order of creation. A root has empty offsets and no names. A shape S′S' created at line L2 from SS with key xx gets offsets(S)\mathit{offsets}(S) plus x↦∣offsets(S)∣x \mapsto |\mathit{offsets}(S)|, the class of SS, and names(S′)=names(S)\mathit{names}(S') = \mathit{names}(S) followed by xx. TRANSITION is called only from line L6, when xx is not in offsets(shape(o))\mathit{offsets}(\mathit{shape}(o)), and S=shape(o)S = \mathit{shape}(o) there. So xx is new, the names stay distinct, and xx is the name at position ∣names(S)∣|\mathit{names}(S)| with that offset. □\square

Lemma 2 (object invariant). At every point of a run, for every object oo:

  1. if oo is in dictionary mode, then o.dict=own(o)o.\mathit{dict} = \mathit{own}(o);
  2. otherwise class(shape(o))=class(o)\mathit{class}(\mathit{shape}(o)) = \mathit{class}(o), names(shape(o))=order(o)\mathit{names}(\mathit{shape}(o)) = \mathit{order}(o), ∣slots(o)∣=∣own(o)∣|\mathit{slots}(o)| = |\mathit{own}(o)|, and slots(o)[offsets(shape(o))[y]]=own(o)[y]\mathit{slots}(o)[\mathit{offsets}(\mathit{shape}(o))[y]] = \mathit{own}(o)[y] for each yy in own(o)\mathit{own}(o).

Proof. By induction on the steps. Line L1 gives the root shape of CC, no slots, and an empty dictionary in the model, which satisfies part 2. Steps on other objects do not touch oo, and shapes do not change by Lemma 1. Consider SET(oo, xx, vv). In dictionary mode, line L4 makes the same change as the model. Otherwise, if xx is already in the offsets, then by part 2 and Lemma 1 xx is in own(o)\mathit{own}(o), the model only changes its value, and line L5 writes the slot of xx, so part 2 holds again. If xx is not in the offsets, then xx is not in own(o)\mathit{own}(o); the model adds xx at the end of order(o)\mathit{order}(o), and line L6 moves oo to a shape S′S' with names(S′)=order(o)\mathit{names}(S') = \mathit{order}(o), the same class, and the new offset ∣slots(o)∣|\mathit{slots}(o)| for xx, at which line L6 appends vv. Consider DELETE(oo, xx). If oo is not in dictionary mode and xx is not an own property, nothing changes in either model. If oo is not in dictionary mode and xx is own, line L8 builds o.dicto.\mathit{dict} from the pairs (y,slots(o)[offsets(shape(o))[y]])(y, \mathit{slots}(o)[\mathit{offsets}(\mathit{shape}(o))[y]]), which is own(o)\mathit{own}(o) by part 2, and line L9 then removes xx from both. In dictionary mode, line L9 removes xx from both. □\square

Theorem 1 (GET). GET(oo, xx) =GET∗(o,x)= \mathrm{GET}^*(o, x) at every point of a run.

Proof. In dictionary mode, line L10 returns o.dict[x]=own(o)[x]o.\mathit{dict}[x] = \mathit{own}(o)[x] when xx is own, by part 1 of Lemma 2, and otherwise line L12 returns LOOKUP, as the model does. Not in dictionary mode, xx is in the offsets exactly when x∈own(o)x \in \mathit{own}(o), by Lemma 1 and part 2. Then line L11 returns own(o)[x]\mathit{own}(o)[x]. Otherwise line L12 returns LOOKUP(class(o),x)\mathrm{LOOKUP}(\mathit{class}(o), x). □\square

Theorem 2 (sharing). Let o1o_1 and o2o_2 be objects that are not in dictionary mode. Then shape(o1)=shape(o2)\mathit{shape}(o_1) = \mathit{shape}(o_2) if and only if class(o1)=class(o2)\mathit{class}(o_1) = \mathit{class}(o_2) and order(o1)=order(o2)\mathit{order}(o_1) = \mathit{order}(o_2).

Proof. For a class CC and a list of distinct names w=(w1,…,wt)w = (w_1, \dots, w_t), write τ(C,w)\tau(C, w) for the shape reached from the root of CC by following the transitions labelled w1,…,wtw_1, \dots, w_t, if they exist. Each shape has at most one child per name, and transitions are never removed or replaced, so τ(C,w)\tau(C, w) is a single shape once it exists and stays the same forever. By induction on the steps, shape(o)=τ(class(o),order(o))\mathit{shape}(o) = \tau(\mathit{class}(o), \mathit{order}(o)) for every object not in dictionary mode: it holds after line L1, line L5 changes neither side, and line L6 extends order(o)\mathit{order}(o) by xx and moves oo along the transition labelled xx. 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. □\square

Load caches. A load cache at a site with name xx has entries (S,field,i)(S, \text{field}, i) and (S,class,a)(S, \text{class}, a) with distinct shapes, at most kk of them, and a megamorphic flag. When a method table or a parent of a class DD changes, the runtime first removes every class entry whose class(S)\mathit{class}(S) has DD in its chain. Let JJ be the invariant: for each field entry, offsets(S)[x]=i\mathit{offsets}(S)[x] = i; for each class entry, xx is not in offsets(S)\mathit{offsets}(S) and a=LOOKUP(class(S),x)a = \mathrm{LOOKUP}(\mathit{class}(S), x) under the current classes.

Lemma 3. JJ holds at every point of a run.

Proof. It holds for an empty cache. Line L16 adds an entry for S=shape(o)S = \mathit{shape}(o) as computed at lines L11 and L12: a field entry with i=offsets(S)[x]i = \mathit{offsets}(S)[x], or, when xx is not in the offsets, a class entry with a=LOOKUP(class(o),x)a = \mathrm{LOOKUP}(\mathit{class}(o), x), and class(o)=class(S)\mathit{class}(o) = \mathit{class}(S) by Lemma 2. A field entry depends only on offsets(S)\mathit{offsets}(S), which never changes by Lemma 1. A class entry also depends on the class chain. If a class DD changes, the entries whose class has DD in its chain are removed first, and for the others the chain does not hold DD, 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. □\square

Theorem 3 (LOAD). LOAD(site, oo) =GET∗(o,x)= \mathrm{GET}^*(o, x) at every point of a run.

Proof. If the site is megamorphic or oo is in dictionary mode, line L13 returns GET(oo, xx), which is right by Theorem 1. Otherwise, on a hit at line L14 the entry has S=shape(o)S = \mathit{shape}(o). For a field entry, offsets(shape(o))[x]=i\mathit{offsets}(\mathit{shape}(o))[x] = i by JJ, so line L15 returns slots(o)[i]\mathit{slots}(o)[i], which is own(o)[x]\mathit{own}(o)[x] by Lemma 2. For a class entry, xx is not in the offsets of shape(o)\mathit{shape}(o), so x∉own(o)x \notin \mathit{own}(o) by Lemma 2, and a=LOOKUP(class(S),x)=LOOKUP(class(o),x)a = \mathrm{LOOKUP}(\mathit{class}(S), x) = \mathrm{LOOKUP}(\mathit{class}(o), x) by JJ and Lemma 2. On a miss, line L16 returns the answer of lines L11 and L12, which is right by Theorem 1. □\square

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 O(1)O(1) 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 O(1)O(1) expected time, and costs O(p)O(p) once, when it creates a new shape, to copy the offsets. A load cache hit costs at most kk 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 O(Tp)O(T p) 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 TT 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.

hidden_classes.pyI0RawGitHub
# 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

  1. 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
  2. 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
  3. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.cached-load
  • a full proof of time.get
  • a full proof of time.new-shape
  • a full proof of time.set
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/S7XDVF/text.yaml