syntax design
Design goal
syntax gives Luna Flow one definition of “syntax with binders” that is
small enough for any symbolic AST to adopt, yet precise enough to prove the
usual laws of free variables, alpha-equivalence and renaming. It serves two
audiences: the lambda calculus packages, which use the concrete Term[T],
and downstream ASTs, which keep their own types and reach the same
algorithms through BindingSyntax.
Constraints
- One trait. A downstream AST should reach every binding algorithm by implementing a single trait. MoonBit has no higher-kinded types, so the trait cannot be a generic traversal over an arbitrary functor.
- Opaque constants. The constant type
Tis arbitrary and must not need a trait of its own. - No conventions. Inputs come from users and other algorithms, so no operation may assume that bound names are distinct from free ones.
Mathematical background
Terms
Fix the set of names of the core design and a set of domain values. Terms are generated by
matching the constructors Value, Variable, Apply and Bind. The binder
is generic: the lambda calculus reads it as , a
polynomial library may read it as a local scope. Values are atoms: they
contain no names.
Free variables and names
is defined by the same equations except
; it is the set
all_names returns, and .
Alpha-equivalence
For write for with every free occurrence of replaced by . Because occurs nowhere in , no occurrence can be captured. Alpha-equivalence is the least congruence on terms such that
All the operations of this library are invariant under , and the lambda calculi are defined on alpha-equivalence classes.11 H. P. Barendregt, The Lambda Calculus: Its Syntax and Semantics, North-Holland 1984, §2.1. The library does not rely on the “variable convention” of that book; every operation renames explicitly when needed.
Design decisions
One generic term type with an opaque payload
Problem. Every symbolic package needs variables and binders, but each has its own constants: numbers, operators, typed constants.
Options. A fixed lambda calculus with an extensible constant type; a separate term type per package; one term type parameterised by the constants.
Choice. Term[T] is parameterised by its constants, and T is opaque:
the algorithms never look inside a Value. This is sound only if constants
contain no variables, which is the stated contract (“T is a closed atom”).
An AST whose constants do contain variables must implement BindingSyntax
instead (next section). Application is n-ary because most symbolic ASTs apply
an operator to several arguments; the lambda calculi read it as a curried
spine.
A view trait instead of a fixed AST
Problem. Downstream repositories already have ASTs. Converting them to
Term[T] and back for every substitution costs time and loses structure.
Choice. BindingSyntax describes a node through a one-layer view. In
categorical terms, define the signature functor
BindingView[N] is , project is a coalgebra
, and variable, apply, bind form an algebra on the three
non-opaque summands. Every generic algorithm is a structural recursion that
calls project, works on the children, and rebuilds with the constructors.
The laws an implementation owes are listed in the
adapter design; for Term[T] they hold by construction, since
project is a bijection between non-Value terms and non-Opaque views.
Consequence. For Term[T], each generic function computes the same
result as its specialised version:
and generic_alpha_rename_bound agrees with Term::alpha_rename_bound. The
proof is a direct induction: in each case the two functions have the same
equation, because project returns exactly the constructor’s fields.
Deciding alpha-equivalence with binder levels
Problem. Deciding directly from the definition requires searching for renamings.
Choice. alpha_equal walks both terms in lockstep with two binder
environments that map each bound name to the level (binder
depth, counting from the root) at which it was bound; a later binding of the
same name shadows an earlier one. Writing for the level of the last
binding of in , for the current depth, and for the
relation on computed by T’s ==:
The relation is whatever T’s == computes; nothing forces
it to be an equivalence. To state exactly what alpha_equal decides, let
be the De Bruijn translation of the
debruijn design, which replaces a bound occurrence at depth
whose binder sits at level by the index , and
keeps free names and values. For a relation on , its lifting
relates two nameless terms when they have the same shape, the
same index or free name at each variable position, and payloads related by
at each value position:
and no other pairs are related.
Theorem. alpha_equal(t, u) holds iff
.
In particular, if is the identity of , then
alpha_equal(t, u) holds iff .
Proof sketch. Both traversals visit the same positions at the same depth , so for bound occurrences
free occurrences are compared by name in both, and values by in
both. This is the first claim. If is the identity, then
is the identity of nameless terms, so alpha_equal(t, u)
iff . The classical theorem
that two named terms are alpha-equivalent iff their De Bruijn translations are
identical22 N. G. de Bruijn, “Lambda calculus notation with nameless dummies”, Indagationes Mathematicae 34, 1972. completes the proof.
Corollary. Each of reflexivity, symmetry and transitivity holds for
alpha_equal on Term[T] iff it holds for . Hence alpha_equal
is an equivalence relation iff T’s == is one.
Proof. () Two terms related by have the same
shape, so a chain
compares the payloads at each value position through
, and identities at every other
position. Reflexivity, symmetry and transitivity of therefore give the
same property of position by position. The theorem pulls each
property back along the function .
() With empty environments the first rule gives
alpha_equal(Value(a), Value(b)) , so a counterexample
for is a counterexample Value(a), Value(b),
Value(c) for alpha_equal.
For Int or String, == is the identity and alpha_equal is exactly
. When == is an equivalence coarser than the identity,
alpha_equal is alpha-equivalence modulo : the least congruence
containing and for . For Double,
== is IEEE 754 equality,33 IEEE Std 754-2019, IEEE Standard for Floating-Point Arithmetic, §5.11: every NaN compares unordered with everything, itself included, and . which is symmetric and transitive but
not reflexive: . So alpha_equal on
Term[Double] is symmetric and transitive, reflexive exactly on the terms
without a NaN payload, and it identifies Value(0.0) with Value(-0.0).
Each node is visited once. The environments are persistent hash maps, so a variable lookup and the extension at a binder are one map operation each, the extension shares the outer environment instead of copying it, and the comparison costs map operations for terms of size .
Capture-avoiding renaming of free variables
Problem. Applying a renaming under a binder can capture: renaming in naively gives .
Choice. rename_free implements
with .
Lemma (free variables of a renaming). .
The only interesting case is the binder without freshening. Let with . By induction , so
The second step uses for : either and , which excludes , or . In the freshened case the same computation applies to and , since is outside and so neither a source nor a target. The lemma says exactly that no free variable was captured.
The test is conservative: it also renames the binder when the offending entry’s source does not occur in . The result is still alpha-equivalent to the minimal one. The lemma shows that no variable is captured; that the result is the intended term up to follows from the translation lemma of the substitution design, which covers renamings as well.
Checked bound renaming
alpha_rename_bound(t, x, y) computes , the body of the
alpha step above, and returns None unless (or
). Under that side condition the alpha axiom gives directly
The check is stronger than necessary (an occurrence of under an inner binder for would be harmless), but it is cheap and it is all the substitution algorithms need, because they always call it with a name chosen fresh for the body.
Traversal with an explicit work stack
Problem. Every definition above is a structural recursion. Run as host
recursion, a term nested levels deep (a chain of Apply heads, of
Apply arguments, or of binders) needs host frames. The js, wasm and
wasm-gc stacks overflow after a few thousand levels, native at levels
in the tests, and nothing in the definitions bounds the nesting depth of an input.
Choice. Every operation of the package is a loop over a heap Array of
pending work. The host stack depth is constant in the nesting depth, and the
heap holds pending items for a term of size . There are two
schemes, one for folds and one for rebuilds.
Folds. free_variables, all_names, == and alpha_equal have the form
where lists the children of with the context
the recursive call receives (the bound set , extended to
under ; for alpha_equal, the environments and the depth),
is the contribution of the node itself, and is for the name
sets and for the comparisons; for a comparison a node is a pair of
subterms, and a mismatch of constructors, names or arities makes
false. Both operations are associative and commutative with a unit
(, true). The loop keeps an accumulator and a multiset
of pending pairs, with the invariant
It holds initially with the unit and . Taking
out of , adding to and putting
into unfolds one equation of , so the
invariant is preserved; every pair is put into once, so the loop stops,
and then . For the loop returns as soon as
is false, because . The contexts
are persistent values (HashSet, HashMap), so pushing the children of a
node shares the context instead of copying it.
Rebuilds. map_values, rename_free, alpha_rename_bound and the
substitutions of the substitution design have the form
with given directly on values and variables. A private rebuild runs it
with a stack of tasks and a stack of results. Visit(t, c) of a leaf pushes
its result. Visit of an application pushes BuildApply(n), then Visit of
the arguments from last to first, then Visit of the head; Visit of a
binder calls and pushes BuildBind(x') and
Visit(t', c'). BuildApply(n) pops results and pushes their
application, and BuildBind(x') wraps the top result in a binder.
Lemma (rebuild). Started on a result stack , the tasks that a
Visit(t, c) puts on the task stack leave when they are
done, and leave the task stack below them unchanged.
Proof. By induction on . A leaf pushes . For an application,
the tasks run in the order Visit(t), Visit(u_1), …, Visit(u_n),
BuildApply(n); by induction they leave
before BuildApply(n),
which turns the top results into . A
binder is the same with one child.
Applied to the root, the lemma gives the result stack . The
callbacks run in the order of the recursive definition: project, the
binder step and map_values’s function in pre-order, head first and then
the arguments from left to right, and the constructors of BindingSyntax in
post-order. So the result is the recursive one, even for an impure function
passed to map_values.
Equality. A derived Eq is itself a structural recursion, so Term
implements Eq by hand as a fold with : the same constructors, the
same names, the same arities, and payloads related by T’s ==. It has no
shortcut for physically equal subterms, because the derived == has none: a
term with a NaN payload is not == to itself in either.
The tests in src/syntax/stack_safety_wbtest.mbt run every operation on the
three chains and a mixture of them, 100 000 levels deep, on every backend.
Correctness and invariants
- ;
map_valuespreserves both. alpha_equaldecides the lifting ofT’s==to nameless terms, and coincides with when that==is the identity (theorem above). It is reflexive, symmetric and transitive exactly when==is (corollary above). Reflexivity forIntpayloads is checked by a QuickCheck property insrc/syntax/syntax_wbtest.mbt, and a test there records that aNaNpayload is not alpha-equal to itself.rename_freesatisfies and is invariant under : alpha-equivalent inputs give alpha-equivalent outputs.alpha_rename_bound(t, x, y) = Some(t')implies .- On
Term[T]everygeneric_*function equals its specialised counterpart. - Every operation,
==included, uses a constant amount of host stack in the nesting depth of its input (traversal with an explicit work stack, above).
Cost: free_variables and all_names make hash-set insertions for
a term of size .
alpha_rename_bound adds one traversal to all_names. rename_free removes
one entry and computes the targets of the renaming at every binder, so it
costs when no binder is renamed; each freshened binder
adds all_names and one renaming traversal of its body.
Alternatives rejected
- Variables inside values. Letting
Tcontain names would require a traversal trait onTas well. Such ASTs implementBindingSyntaxdirectly, which covers the same need with one trait. - Multi-variable binders. A binder for several names at once is expressed
as nested
Bindnodes. This keeps the view small and the proofs per binder. - Unchecked bound renaming. A version without the
Nonecase would make a capture silent. The checked form makes the precondition visible in the type. - Alpha-equivalence by conversion. Converting both terms to De Bruijn form and comparing would allocate two new terms; the lockstep algorithm is the same comparison without the allocation.
Boundaries
Valuepayloads are never inspected. A payload that contains variables is outside the contract.==on terms is structural, not alpha-equivalence.Debugon terms (@debug.to_string,Repr, the messages ofassert_eqandinspect) is derived and recursive, so formatting a term nested tens of thousands of levels deep can still overflow the host stack.- The generic algorithms are stack-safe when the
BindingSyntaxmethods of the downstream type are:projectand the three constructors should look at one layer of a node and not recurse into it. alpha_equalcompares payloads withT’s==and adds no reflexivity of its own: with a non-reflexive==(such asDoubleandNaN) a term can fail to be alpha-equal to itself.- No sorts, scopes or types: every name is a term variable of the same kind.
- The package does not check that a
BindingSyntaximplementation obeys its laws; adapter describes how to test them. - Substitution lives in substitution, traversal and rewriting in rewrite.
Footnotes
-
H. P. Barendregt, The Lambda Calculus: Its Syntax and Semantics, North-Holland 1984, §2.1. The library does not rely on the “variable convention” of that book; every operation renames explicitly when needed. ↩
-
N. G. de Bruijn, “Lambda calculus notation with nameless dummies”, Indagationes Mathematicae 34, 1972. ↩
-
IEEE Std 754-2019, IEEE Standard for Floating-Point Arithmetic, §5.11: every NaN compares unordered with everything, itself included, and . ↩