debruijn design
Design goal
Named syntax needs fresh names and renaming in every binder-crossing
operation. debruijn provides a representation in which alpha-equivalence is
syntactic equality and beta reduction needs no renaming at all, together with
exact translations to and from named syntax. It is the kernel representation
of the untyped NbE in utlc/nbe and a reference reducer against
which the named calculus in utlc/lambda is tested.
Constraints
- Exact translations. Converting to indices and back must lose nothing but binder names.
- Errors are values. An ill-scoped index is reported as a
ScopeError, never by an abort or a silently wrong term where the operation can detect it. - Open terms. Free variables come from users and downstream ASTs, so they stay names instead of needing a global numbering.
Mathematical background
Indices
In a term with nameless binders, a bound occurrence is a number , its
De Bruijn index: the number of binders between the occurrence and the
binder it refers to.11 N. G. de Bruijn, “Lambda calculus notation with nameless dummies”, Indagationes Mathematicae 34, 1972. With for Bind and juxtaposition for
Apply:
The same variable has different indices at different depths (here is
and then ). Free variables stay named (Free(x)), a “locally nameless”
choice for the free part that keeps translations simple.
A term is well scoped at depth when every index under binders is
smaller than ; it is well scoped when it is well scoped at depth .
validate decides this.
Levels
The level of a binder is its depth counted from the root. An occurrence under binders with index refers to the binder at level
When a term is moved under one more binder (weakening: the context grows at its inner end), the indices of its free variables must be shifted by one, but their levels do not change. The NbE evaluator therefore uses levels for the variables it invents while going under binders, so that semantic values can be moved deeper without shifting, and converts back with when quoting.
Shifting
adds to every index of that is free relative to cutoff :
The shift is defined when no index crosses its cutoff: there is no index with , where is the cutoff at that occurrence. Such an index would be captured by an enclosing binder, or become negative. A shift with is always defined.
shift(t, d, c) implements it by carrying the binder depth and testing
, which unfolds the recursion on . A negative is outside
the domain: it would count indices bound inside as free, so shift
rejects it with NegativeCutoff before looking at .
Substitution of an index
replaces the free index by :
substitute_bound unfolds the binder case: under binders it replaces
index by . The two agree because shifts with the
same cutoff compose (Lemma 1 below):
.
Beta reduction
The argument is shifted up because it moves under the binder of ; after
the substitution the binder is removed, so all remaining free indices of the
body are shifted down. This is instantiate(t, s).22 B. C. Pierce, Types and Programming Languages, MIT Press 2002, §6.2–6.3.
Design decisions
Shifting is checked, not assumed
Problem. A downward shift can move a free index below its cutoff. Below zero the index refers to nothing; between zero and the cutoff it is captured by an enclosing binder. Either way the result is a silently wrong term.
Choice. shift returns Err(NegativeShift) when a free index would cross
its cutoff and Err(NegativeCutoff) for a negative cutoff, and shift,
substitute_bound, instantiate, validate and to_named report
NegativeIndex for any negative index they meet. The lemmas below show that
the error cases are unreachable from well-scoped input, so the Result costs
nothing for correct callers and turns a silent corruption into data for
incorrect ones. This follows the library rule that expected failures at
public boundaries are structured values.
The index operations work on open terms, so they cannot tell a dangling
(too large) index from one that points at a binder outside the term:
instantiate shifts it like a free index. The reducers work on whole terms
and validate them. reduce_once runs validate before searching and
returns its error as ScopeFailure; normalize validates its input once,
and Lemma 2 below shows that the later terms need no check. The search
itself is a private function that is also applied to binder bodies, whose
indices may point at enclosing binders.
Instantiation never fails on well-scoped input
Lemma 1 (shift composition). For : , and .
On an index relative to the current cutoff: if both sides leave it; if then , so
The binder case raises the cutoff on both sides alike.
Lemma 2 (safety of the downward shift). Let and be well scoped at depth . Then every free index of lies in , so succeeds and is well scoped at depth .
The body is well scoped at depth , so its free indices lie in . Follow a free occurrence in under inner binders:
No free index remains. Under binders the shift by has cutoff and moves the index with to , so no index crosses its cutoff, and the root-relative free indices are mapped .
Hence instantiate and reduce_once return no ScopeError on well-scoped
input, and a reduct of a well-scoped term is well scoped (subject reduction
for scope). Together with the validation of the input, normalize returns
ScopeFailure exactly when its input is ill scoped, and then with
steps=0: Bind(Bound(-1)) gives NegativeIndex(index=-1) and (λ. 5) 1
gives UnboundIndex(index=5, depth=1).
The detailed proofs, including the commutation of shifts with different cutoffs and the De Bruijn substitution lemma, are in the attachment:
Exact translations
from_named keeps a stack of binder names and translates an occurrence of
to the distance to the nearest binder of , or to Free(x) if there is
none. to_named invents a binder name with fresh_name("x", U), where
contains the free names of the term and the names of the enclosing binders.
Theorem (round trips).
- for every named .
- for every well-scoped .
- .
For (2): along any path from the root, the names chosen by to_named are
pairwise distinct and distinct from all free names, because each is chosen
fresh for a set that contains the free names and every enclosing binder name.
An occurrence of index under binders becomes the name of the binder at
level ; translating back, the nearest binder with that name is that
same binder (no other enclosing binder has the name), at distance . A
Free(x) becomes , which is not the name of any binder on the path, so it
translates back to Free(x). (3) is de Bruijn’s theorem; (1) follows from (2)
and (3), since .
Named and nameless beta agree
For named terms, beta is with the capture-avoiding substitution of substitution. Write for the translation of with as the innermost binder. Then
by induction on : an occurrence of under inner binders has index
and receives , which is the
translation of placed under those binders; at the root has
no free indices, so the shift changes nothing. Renaming of binders by the
named substitution is invisible after translation by (3), and the translation
lemma of the substitution design makes this induction
precise. Since the translation also preserves the shape of terms, the
beta-only named reducer (@eval.evaluate with @lambda.beta_rule and
NormalOrder) and reduce_once choose the same leftmost-outermost redex, and
one step commutes with translation up to . (@lambda.normalize
also contracts eta redexes, so its normal forms can be eta-shorter.) The test “named and debruijn beta reduction agree modulo alpha”
checks an instance that needs renaming on the named side.
Spines and reduction order
Apply(head, args) is a curried spine: Apply(Bind(t), [a, ..rest]) is the
redex applied to rest, and a step contracts only the first
argument. An empty spine Apply(h, []) stands for itself, so empty
applications around the Bind are looked through when a redex is matched. reduce_once searches root, head, arguments, and enters binders: it
is the normal-order strategy of the eval design on nameless terms,
so the normalization theorem applies to normalize.
Explicit stacks instead of host recursion
Problem. Every operation above is defined by structural recursion on the term, and a direct implementation keeps one host stack frame per level of nesting. Terms from users and downstream ASTs can be deep (a long spine , a long chain of binders), and the js, wasm and wasm-gc stacks overflow at a depth of a few thousand, so the same call returned a result on native and crashed on the other backends.
Choice. Each operation runs as a loop over an explicit stack in a heap array, and visits the subterms in exactly the order of its recursive definition, so its results, including the error it reports, are unchanged. The host stack depth is constant; the heap stacks hold at most one entry per node of the term.
Checks. validate and == keep a stack of the subterms (or pairs of
subterms) still to visit. Write for the nodes of in
pre-order, head before arguments and arguments from left to right:
and for a leaf . The loop pops the top entry, checks it if it is a leaf, and otherwise pushes its children, first and the head last. With the stack (top first) it maintains
since popping and pushing its children replaces
by its tail. So the leaves are checked in pre-order.
The recursive validate returns the first error of its head, else of its
arguments from left to right, which by induction is also the first error in
pre-order. Both return the same error. An index is checked against the
number of binders above it, which the stack stores with each entry.
Translations. shift, substitute_bound (both through one rebuilding
traversal that applies a function to each Bound(i) and its binder count),
from_named and to_named produce a term. They keep a stack of tasks,
and / ,
and a stack of results. Visiting a leaf pushes its translation; visiting
pushes and above it the visits of
; pops the translations
and pushes the application of the first to the others. By induction on ,
running the tasks pushed for pushes exactly one
result, the recursive translation of under binders, and leaves the
rest of both stacks untouched. Leaves are visited in pre-order as above;
errors arise only at leaves, and both versions stop at the first one, so
they return the same Err. In substitute_bound the replacement at an
occurrence is shifted by the same loop, run to its end before the
traversal continues.
from_named keeps, for each name, the levels of the enclosing binders of
that name, and maps an occurrence under binders to for
the innermost level , the index of the nearest binder of that name.
to_named names a binder with the first name of that
is neither free in the term () nor the name of an enclosing binder. Let
be the names of that sequence not in . By induction on
the level, the enclosing binders of a binder at level are named
, so it gets : the name depends only on the level
and is computed once. Both translations are therefore linear in the size of
the term (up to hashing), where a copy of the binder stack at each binder
and a rescan of the candidate names made a chain of binders cost
.
Reduction. The recursive search of reduce_once tries a node, then its
head, then its arguments from left to right, and enters binder bodies, and
it contracts the first redex it meets: the first redex in pre-order. The
loop walks the term in pre-order and keeps the path from the root, each
ancestor with the child it descended into; when a leaf ends a branch it
returns to the nearest application with an argument left. When it meets a
redex it contracts it, then rebuilds the ancestors from the innermost
outwards and prepends one frame per ancestor to the reduction path, which is
the order in which the recursive calls return. The steps, their paths and
their counts in normalize are therefore unchanged.
The tests in src/debruijn/deep_test.mbt run every operation on terms
nested to depth 100 000 (application chains in head and in argument
position, binder chains with indices that reach the outermost binder, and
mixtures of these, well scoped and ill scoped) on every backend; before the
change each of them overflowed the stack on js, wasm and wasm-gc.
Correctness and invariants
validate(from_named(t)) == Ok(())for every named .- Round trips (1)–(3) above;
==on well-scopedDbTermis alpha-equivalence. - Lemma 2: on well-scoped input
instantiatesucceeds and preserves scope;reduce_oncenever returnsScopeFailure, and every reduct is well scoped. On ill-scoped inputreduce_onceandnormalizereturnScopeFailurewith the errorvalidatereports. reduce_oncesatisfies the one-redex contract of rewrite, with rule name"beta".shift(t, 0, c) == Ok(t)for everytwithout negative indices, and shifts with one cutoff compose (Lemma 1).shiftnever turns a free index into a bound one: if a free index would fall below its cutoff, it returnsErr(NegativeShift), and it rejects a negative cutoff, which would free bound indices, withErr(NegativeCutoff).
Cost: shift, validate, from_named and to_named are linear in the term
size (the translations up to hashing of names). substitute_bound
costs for occurrences of the index, because each
inserted copy is shifted. A reduce_once step costs one search plus one
instantiate, plus building the reduction path, which has one frame per
ancestor of the redex and is built with @rewrite.ReductionPath::prepend.
Stack: every operation uses a constant depth of host stack, whatever the nesting depth of the term; its pending work is kept in heap arrays with at most one entry per node.
Alternatives rejected
- Levels instead of indices in syntax. Levels make weakening free but substitution under binders more complex; indices are the standard for syntax, and levels are used where they help (NbE).
- Fully nameless free variables. Free variables are kept as names so that
open terms from users and downstream ASTs need no global variable
numbering, and so that
to_namedcan restore them exactly. - Explicit substitutions. A calculus with suspended substitutions avoids repeated shifting but complicates every consumer; the NbE package provides the efficient path instead.
Boundaries
- Binder names are not preserved:
to_namedchoosesx,x_1, …. shift,substitute_boundandinstantiateoperate on open terms and do not detect dangling indices; the reducers andvalidatedo.- An empty application
Apply(h, [])is read ashwhen a redex is matched, so it never hides a redex, butreduce_onceleaves the node in place, whereas utlc/nbe drops it from its normal forms. - Only beta is implemented; there is no eta rule for De Bruijn terms.
- Values are opaque; their contents are never shifted.
- The derived
DebugofDbTerm(and of the result types that contain one) recurses over the term, so printing a deeply nested term can overflow the host stack on js, wasm and wasm-gc. Every other operation,==included, handles any nesting depth.