substitution design
Design goal
Substitution is the operation every other part of the library is built on:
beta reduction substitutes an argument for a parameter, rewriting rules
instantiate their variables, and partial evaluation in downstream packages
replaces known variables by values. substitution provides one
capture-avoiding, simultaneous substitution for Term[T] and the same
algorithm for any BindingSyntax AST, with laws that hold up to
alpha-equivalence.
Constraints
- Arbitrary input. Terms come from users and from other algorithms, so substitution must be correct without assuming that bound and free names are distinct.
- Determinism and readability. Fresh names are reproducible and stay close to the original names; binders are renamed only when necessary.
- One algorithm.
Term[T]and everyBindingSyntaxAST use the same definition, so one proof covers both.
Mathematical background
Terms, , and are those of the syntax design.
Substitutions
A substitution is a map from names to terms that is the identity outside a finite domain . Its support is , and removes from the domain. For a set of names , the relevant range of on is
Capture-avoiding simultaneous substitution
Substitution::apply computes by
where and is the checked bound renaming of the syntax design. The case split is exact: the binder is renamed only when a replacement that is actually inserted into mentions free.
Design decisions
Simultaneous, one pass
Problem. Should applied to give or ?
Options. Sequential substitution (apply the entries one after another), iterated substitution (repeat until nothing changes), or simultaneous substitution (every variable is looked up once in the original term).
Choice. Simultaneous. The variable case looks up once and never visits the inserted term again:
Simultaneous substitution is the one with an algebra (composition below), it
always terminates, and it expresses swaps such as
directly. Sequential application is still available as composition with
then, and iteration to a fixed point is a policy of the caller. The
generic version is called apply_once to make this explicit.
Rename binders only when needed
Problem. Capture happens when a binder lies above an inserted replacement in which is free. Renaming every binder avoids it but makes results unreadable.
Choice. Rename only when , and then choose the fresh name with the hint . The fresh name must avoid three sets, each for its own reason:
- of the relevant replacements, or the renamed binder would capture them again;
- , or the occurrences that were renamed from to would themselves be substituted (regression test “fresh binders avoid the substitution domain”);
- , so that the checked bound renaming cannot fail, and the renamed variable cannot be confused with an inner binder of the same name.
covers the first two sets. The abort in the
implementation is therefore unreachable: by the freshness lemma
, which is exactly the side condition of
alpha_rename_bound.
Composition as a first-class operation
then builds with
so that sequential application can be expressed as one simultaneous substitution, which is cheaper (one traversal) and has the laws below.
Correctness and invariants
Substitution and GenericSubstitution are abstract types: only the
functions of the package build them, each of those keeps at most one entry
per name, and to_array returns a copy of the entries. So every value
denotes a map and keeps denoting the same map. The
replacement terms are shared, not copied; the laws assume, as the whole
library does, that terms are not changed in place.
The laws below are proved through the nameless reading of terms. The direct argument by induction on named terms is the classical one, but its binder case has to compare results whose fresh names differ, and that comparison is exactly what the nameless reading makes trivial.
The nameless reading
Let be @debruijn.from_named(t), the translation of
the debruijn design: bound occurrences become indices, free
names stay names. It is computed by closing each binder’s variable. For a
nameless term , let replace every free name under
inner binders by the index ; then
This is the same as the environment-based definition of from_named: the
occurrences of that are still free in are exactly
those whose nearest binder is this one. Translations are locally closed:
every index points at a binder inside the term. Two facts are used below.
- (T1) (de Bruijn’s theorem, see the syntax design).
- (T2) If , then . The free name occurs in exactly where occurs free in , because occurs nowhere in , so closing in the one gives the same indices as closing in the other.
On nameless terms, substitution for free names is plain replacement. For a substitution write for with every free name replaced by . No binder is renamed and no index is shifted: the inserted terms are locally closed, so they mean the same under any number of binders.
The translation lemma
Lemma 0. for every term and substitution .
By induction on the size of , for all at once. Values, variables and applications are immediate. For let . Closing commutes with replacement under two conditions, checked occurrence by occurrence:
The first condition holds because was removed. The free names of are , so the second is exactly . Hence, without renaming,
and with renaming to , which lies outside ,
Everything else follows from Lemma 0, because replacement on locally closed nameless terms is a homomorphism with no side conditions.
Free variables
Lemma 1. .
The free names of are those of the inserted for the free names of , that is for (with outside the domain).
Corollary (no capture). A variable free in an inserted replacement , , is free in .
Only the free variables matter
Lemma 2. , where
is restrict(S). More generally, if
for every , then .
consults only at the free names of , and only through , which (T1) makes invariant under . Equal translations mean alpha-equivalent terms by (T1). The two sides need not be equal as values, because the fresh binder names avoid the support of different substitutions.
Alpha-invariance
Lemma 3. If then .
By (T1), , so by Lemma 0, and (T1) again gives the claim.
Substitution is therefore well defined on alpha-equivalence classes, and the choice of fresh names never matters semantically.
Composition
Lemma 4. .
By Lemma 0 on both sides it suffices to show for a nameless . Replacement is homomorphic, so only a free name needs checking, and it splits as in the definition of :
Corollary (substitution lemma). For and ,
By Lemma 4 each side is one simultaneous substitution applied to . The left is . The right is , and by Lemma 2, because and the empty substitution is the identity. The two substitutions agree up to at every name, so Lemma 2 makes the results alpha-equivalent.11 Barendregt, The Lambda Calculus, Lemma 2.1.16. This is the lemma that makes beta reduction commute with substitution in the lambda calculus packages: implies up to .
Renamings embed into substitutions
Term::rename_free obeys the analogue of Lemma 0,
, with the
same proof: its test implies
the second condition of (C), and its fresh name avoids
. For a list of
names , from_renaming(L, ρ) is
(as
variables). It agrees with on , so
. The two results may still differ as values:
rename_free freshens a binder whenever it is a target of the renaming,
while apply freshens it only when an inserted variable would be captured.
Cost
apply computes the free variables of every replacement once. At each
binder it removes one entry from the substitution and looks for entries
whose replacement has the binder free; only if there is one does it compute
the free variables of the body (see the capture test below). So a term of
size costs besides the free variables of the
replacements, and each binder that is a candidate for capture adds one
traversal of its body, each renamed binder one more. then costs one
apply and one set per entry of self, so entry copies for
entries besides the applications.
Generic substitution
GenericSubstitution::apply_once is the same definition with every
constructor replaced by its BindingSyntax counterpart. Reading a node
through its view gives a named term, so Lemmas 0–3 hold for any
implementation that satisfies the view laws of the
adapter design. On Term[T] the two algorithms coincide.
Traversal with an explicit work stack
Problem. The definition of is a structural recursion, and run as host recursion it overflows the js, wasm and wasm-gc stacks on terms nested a few thousand levels deep.
Choice. Substitution::apply and GenericSubstitution::apply_once are
one private loop, substitute, over the view of the generic substitution
above. It is an instance of the rebuild scheme of the
syntax design with the context and
with and as in the definition. By the
rebuild lemma the loop computes exactly , the same term and the
same fresh names as the recursion, using a constant amount of host stack;
the analyses it calls (, and the checked bound
renaming) are stack-safe as well. On Term[T], Value and the variables
outside the domain are returned as they are instead of being rebuilt, which
gives an equal term.
The capture test. The condition is decided in a cheaper order. Unfolding ,
where is the set of candidates. The sets are computed once per call, and since as a set of entries they serve every binder. If the condition is false without looking at ; otherwise is computed once. The boolean is the same, so the result is too, but a chain of binders none of which can capture now costs instead of .
The tests in src/substitution/stack_safety_test.mbt run substitution,
freshening at the outermost binder, deep replacements, composition and the
generic substitution on terms nested 100 000 levels deep, on every backend.
Alternatives rejected
- The Barendregt variable convention. Assuming that bound names are distinct from all free names would remove the renaming case, but terms come from users and from other algorithms, and the convention is not preserved by reduction. The library renames explicitly instead.
- Substitution on De Bruijn terms only. Index-based substitution needs no renaming and is provided by debruijn, but the shared interface for downstream ASTs is named, so named substitution must be correct on its own.
- Iterated substitution. Repeating until no domain variable occurs can diverge () and has no composition law. Callers that want a fixed point iterate explicitly.
Boundaries
- No unification, matching or occurs check: substitutions are given, not solved for.
GenericSubstitutionhas nothenorrestrict; compose generic substitutions by applying them in turn.- Results are equal to the textbook definition only up to ; use
@syntax.alpha_equalto compare them. - Stack safety is in the nesting depth, not in the cost: a chain of binders every one of which is renamed still costs , because each renaming traverses the body below it.
- Values are never entered, so a
Valuepayload that contains variables is not substituted into.
Footnotes
-
Barendregt, The Lambda Calculus, Lemma 2.1.16. ↩