Skip to content

Scopes

The reference machine keeps the values of the locals in scope in a Scope, a persistent map. Binding a local returns a new scope that shares the old one's nodes, so a pending frame keeps its environment without a copy. Binding and lookup walk one path of the trie and scan only the entries that share the key's full hash. For well-distributed hashes, the path length grows logarithmically with the number of locals.

scope

Persistent environments of the reference machine.

A run of the machine binds a local at every Bind, every call and every case branch, and keeps the environment of each pending frame so the frame can continue under it. A copied dictionary makes every bind cost the size of the scope, so a program of n binds runs in time quadratic in n. Scope is a persistent map instead: binding returns a new scope that shares all but one path of the old one, so a frame keeps its environment without a copy.

The map is a hash array mapped trie of branching 32. Binding and lookup walk one path of the trie, whose depth is at most ceil(64 / 5) = 13 and, for a scope of n locals with well-spread hashes, about log_32 n; each step makes at most one node of at most 32 entries. Two locals whose 64-bit hashes are equal share a bucket, scanned in full.

Scope

Scope(entries: Mapping[K, V] | Iterable[tuple[K, V]] = ())

Bases: Mapping[K, V]

A persistent map from locals to the values they are bound to.

A scope never changes: bind and extend return a new scope sharing the old one's nodes, so a frame that keeps a scope keeps it at no cost. Each operation walks one path and inspects the entries sharing the key's full hash. With well-distributed hashes, binding and lookup take time logarithmic in the scope's size.

PARAMETER DESCRIPTION
entries

The bindings to start from; none for the empty scope.

TYPE: Mapping or iterable of pairs DEFAULT: ()

Source code in src/quivers/qiec/scope.py
def __init__(self, entries: Mapping[K, V] | Iterable[tuple[K, V]] = ()) -> None:
    self._root = _EMPTY
    self._size = 0
    pairs = entries.items() if isinstance(entries, Mapping) else entries
    for key, value in pairs:
        self._root, added = _bound(self._root, 0, _Leaf(_code(key), key, value))
        self._size += added

of classmethod

of(entries: Mapping[K, V] | Iterable[tuple[K, V]]) -> Scope[K, V]

A scope with given bindings, reusing one that is already a scope.

PARAMETER DESCRIPTION
entries

The bindings.

TYPE: Mapping or iterable of pairs

RETURNS DESCRIPTION
Scope

entries itself when it is a scope, else a new one.

Source code in src/quivers/qiec/scope.py
@classmethod
def of(cls, entries: Mapping[K, V] | Iterable[tuple[K, V]]) -> Scope[K, V]:
    """A scope with given bindings, reusing one that is already a scope.

    Parameters
    ----------
    entries : Mapping or iterable of pairs
        The bindings.

    Returns
    -------
    Scope
        ``entries`` itself when it is a scope, else a new one.
    """
    if isinstance(entries, Scope):
        return cast("Scope[K, V]", entries)
    return cls(entries)

bind

bind(key: K, value: V) -> Scope[K, V]

This scope with one local bound, or rebound.

PARAMETER DESCRIPTION
key

The local.

TYPE: K

value

Its value.

TYPE: V

RETURNS DESCRIPTION
Scope

The new scope; this one is unchanged.

Source code in src/quivers/qiec/scope.py
def bind(self, key: K, value: V) -> Scope[K, V]:
    """This scope with one local bound, or rebound.

    Parameters
    ----------
    key : K
        The local.
    value : V
        Its value.

    Returns
    -------
    Scope
        The new scope; this one is unchanged.
    """
    root, added = _bound(self._root, 0, _Leaf(_code(key), key, value))
    return self._with(root, self._size + added)

extend

extend(pairs: Iterable[tuple[K, V]]) -> Scope[K, V]

This scope with several locals bound in order.

PARAMETER DESCRIPTION
pairs

The bindings; a later one of a key replaces an earlier.

TYPE: iterable of (K, V)

RETURNS DESCRIPTION
Scope

The new scope; this one is unchanged.

Source code in src/quivers/qiec/scope.py
def extend(self, pairs: Iterable[tuple[K, V]]) -> Scope[K, V]:
    """This scope with several locals bound in order.

    Parameters
    ----------
    pairs : iterable of (K, V)
        The bindings; a later one of a key replaces an earlier.

    Returns
    -------
    Scope
        The new scope; this one is unchanged.
    """
    root = self._root
    size = self._size
    for key, value in pairs:
        root, added = _bound(root, 0, _Leaf(_code(key), key, value))
        size += added
    return self._with(root, size)

__getitem__

__getitem__(key: K) -> V

The value a local is bound to.

PARAMETER DESCRIPTION
key

The local.

TYPE: K

RETURNS DESCRIPTION
V

Its value.

RAISES DESCRIPTION
KeyError

If the local is not bound.

Source code in src/quivers/qiec/scope.py
def __getitem__(self, key: K) -> V:
    """The value a local is bound to.

    Parameters
    ----------
    key : K
        The local.

    Returns
    -------
    V
        Its value.

    Raises
    ------
    KeyError
        If the local is not bound.
    """
    code = _code(key)
    node = self._root
    shift = 0
    while True:
        if isinstance(node, _Branch):
            bit = 1 << ((code >> shift) & _MASK)
            if not node.bitmap & bit:
                raise KeyError(key)
            node = node.children[(node.bitmap & (bit - 1)).bit_count()]
            shift += _BITS
            continue
        if isinstance(node, _Leaf):
            if node.code == code and node.key == key:
                return node.value  # type: ignore[return-value]
            raise KeyError(key)
        if node.code == code:
            for leaf in node.leaves:
                if leaf.key == key:
                    return leaf.value  # type: ignore[return-value]
        raise KeyError(key)

__iter__

__iter__() -> Iterator[K]

Every bound local.

RETURNS DESCRIPTION
Iterator[K]

The locals, in an order fixed by their hashes.

Source code in src/quivers/qiec/scope.py
def __iter__(self) -> Iterator[K]:
    """Every bound local.

    Returns
    -------
    Iterator[K]
        The locals, in an order fixed by their hashes.
    """
    return (leaf.key for leaf in _leaves(self._root))  # type: ignore[misc]

__len__

__len__() -> int

The number of bound locals.

RETURNS DESCRIPTION
int

The number.

Source code in src/quivers/qiec/scope.py
def __len__(self) -> int:
    """The number of bound locals.

    Returns
    -------
    int
        The number.
    """
    return self._size

__repr__

__repr__() -> str

The bindings, as a dictionary shows them.

RETURNS DESCRIPTION
str

The representation.

Source code in src/quivers/qiec/scope.py
def __repr__(self) -> str:
    """The bindings, as a dictionary shows them.

    Returns
    -------
    str
        The representation.
    """
    return f"Scope({dict(self.items())!r})"