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 T is 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 N\mathcal{N} of the core design and a set VV of domain values. Terms are generated by

t,u  ::=  v  ∣  x  ∣  t(u1,…,un)  ∣  βx. t(v∈V, x∈N, n≥0),t, u \;::=\; v \;\mid\; x \;\mid\; t(u_1, \dots, u_n) \;\mid\; \beta x.\, t \qquad (v \in V,\ x \in \mathcal{N},\ n \ge 0),

matching the constructors Value, Variable, Apply and Bind. The binder βx. t\beta x.\,t is generic: the lambda calculus reads it as λx. t\lambda x.\,t, a polynomial library may read it as a local scope. Values are atoms: they contain no names.

Free variables and names

FV(v)=∅,FV(x)={x},FV(t(u1,…,un))=FV(t)∪⋃iFV(ui),FV(βx. t)=FV(t)∖{x}.\begin{aligned} \mathrm{FV}(v) &= \varnothing, & \mathrm{FV}(x) &= \{x\}, \\ \mathrm{FV}(t(u_1,\dots,u_n)) &= \mathrm{FV}(t) \cup \textstyle\bigcup_i \mathrm{FV}(u_i), & \mathrm{FV}(\beta x.\,t) &= \mathrm{FV}(t) \setminus \{x\}. \end{aligned}

names(t)\mathrm{names}(t) is defined by the same equations except names(βx. t)=names(t)∪{x}\mathrm{names}(\beta x.\,t) = \mathrm{names}(t) \cup \{x\}; it is the set all_names returns, and FV(t)⊆names(t)\mathrm{FV}(t) \subseteq \mathrm{names}(t).

Alpha-equivalence

For y∉names(t)y \notin \mathrm{names}(t) write t{x↦y}t\{x \mapsto y\} for tt with every free occurrence of xx replaced by yy. Because yy occurs nowhere in tt, no occurrence can be captured. Alpha-equivalence =α=_\alpha is the least congruence on terms such that

βx. t  =α  βy. t{x↦y}whenever y∉names(t).\beta x.\, t \;=_\alpha\; \beta y.\, t\{x \mapsto y\} \qquad \text{whenever } y \notin \mathrm{names}(t).

All the operations of this library are invariant under =α=_\alpha, 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

F(X)=1  +  N  +  X×X∗  +  N×X.F(X) = 1 \;+\; \mathcal{N} \;+\; X \times X^{*} \;+\; \mathcal{N} \times X .

BindingView[N] is F(N)F(N), project is a coalgebra N→F(N)N \to F(N), 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:

generic_free_variables(t)=FV(t),generic_all_names(t)=names(t),\texttt{generic\_free\_variables}(t) = \mathrm{FV}(t), \qquad \texttt{generic\_all\_names}(t) = \mathrm{names}(t),

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 =α=_\alpha directly from the definition requires searching for renamings.

Choice. alpha_equal walks both terms in lockstep with two binder environments EL,ERE_L, E_R 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 E(x)E(x) for the level of the last binding of xx in EE, dd for the current depth, and ≈T\approx_T for the relation on VV computed by T’s ==:

EL,ER⊢dv∼v′  ⟺  v≈Tv′,EL,ER⊢dx∼y  ⟺  {EL(x)=ER(y)if both are bound,x=yif both are free,falseotherwise,EL,ER⊢dt(uˉ)∼t′(uˉ′)  ⟺  ∣uˉ∣=∣uˉ′∣∧t∼t′∧⋀iui∼ui′,EL,ER⊢dβx. t∼βy. t′  ⟺  EL[x↦d],ER[y↦d]⊢d+1t∼t′.\begin{aligned} E_L, E_R \vdash_d v \sim v' &\iff v \approx_T v', \\ E_L, E_R \vdash_d x \sim y &\iff \begin{cases} E_L(x) = E_R(y) & \text{if both are bound},\\ x = y & \text{if both are free},\\ \text{false} & \text{otherwise}, \end{cases}\\ E_L, E_R \vdash_d t(\bar u) \sim t'(\bar u') &\iff |\bar u| = |\bar u'| \wedge t \sim t' \wedge \textstyle\bigwedge_i u_i \sim u'_i, \\ E_L, E_R \vdash_d \beta x.\,t \sim \beta y.\,t' &\iff E_L[x \mapsto d], E_R[y \mapsto d] \vdash_{d+1} t \sim t'. \end{aligned}

The relation ≈T\approx_T is whatever T’s == computes; nothing forces it to be an equivalence. To state exactly what alpha_equal decides, let ⌜t⌝\ulcorner t \urcorner be the De Bruijn translation of the debruijn design, which replaces a bound occurrence at depth dd whose binder sits at level ℓ\ell by the index i=d−1−ℓi = d - 1 - \ell, and keeps free names and values. For a relation RR on VV, its lifting R^\widehat{R} relates two nameless terms when they have the same shape, the same index or free name at each variable position, and payloads related by RR at each value position:

vR^v′  ⟺  vRv′,iR^j  ⟺  i=j,xR^y  ⟺  x=y,s(aˉ)R^s′(aˉ′)  ⟺  ∣aˉ∣=∣aˉ′∣∧sR^s′∧⋀iaiR^ai′,λ. sR^λ. s′  ⟺  sR^s′,\begin{aligned} v \mathrel{\widehat{R}} v' &\iff v \mathrel{R} v', \qquad i \mathrel{\widehat{R}} j \iff i = j, \qquad x \mathrel{\widehat{R}} y \iff x = y, \\ s(\bar a) \mathrel{\widehat{R}} s'(\bar a') &\iff |\bar a| = |\bar a'| \wedge s \mathrel{\widehat{R}} s' \wedge \textstyle\bigwedge_i a_i \mathrel{\widehat{R}} a'_i, \qquad \lambda.\,s \mathrel{\widehat{R}} \lambda.\,s' \iff s \mathrel{\widehat{R}} s', \end{aligned}

and no other pairs are related.

Theorem. alpha_equal(t, u) holds iff ⌜t⌝≈T^⌜u⌝\ulcorner t \urcorner \mathrel{\widehat{\approx_T}} \ulcorner u \urcorner. In particular, if ≈T\approx_T is the identity of VV, then alpha_equal(t, u) holds iff t=αut =_\alpha u.

Proof sketch. Both traversals visit the same positions at the same depth dd, so for bound occurrences

ℓL=ℓR  ⟺  d−1−ℓL=d−1−ℓR  ⟺  iL=iR,\ell_L = \ell_R \iff d - 1 - \ell_L = d - 1 - \ell_R \iff i_L = i_R ,

free occurrences are compared by name in both, and values by ≈T\approx_T in both. This is the first claim. If ≈T\approx_T is the identity, then ≈T^\widehat{\approx_T} is the identity of nameless terms, so alpha_equal(t, u) iff ⌜t⌝=⌜u⌝\ulcorner t \urcorner = \ulcorner u \urcorner. 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. □\square

Corollary. Each of reflexivity, symmetry and transitivity holds for alpha_equal on Term[T] iff it holds for ≈T\approx_T. Hence alpha_equal is an equivalence relation iff T’s == is one.

Proof. (⇐\Leftarrow) Two terms related by R^\widehat{R} have the same shape, so a chain aR^bR^ca \mathrel{\widehat{R}} b \mathrel{\widehat{R}} c compares the payloads ap,bp,cpa_p, b_p, c_p at each value position pp through apRbpRcpa_p \mathrel{R} b_p \mathrel{R} c_p, and identities at every other position. Reflexivity, symmetry and transitivity of RR therefore give the same property of R^\widehat{R} position by position. The theorem pulls each property back along the function t↦⌜t⌝t \mapsto \ulcorner t \urcorner. (⇒\Rightarrow) With empty environments the first rule gives alpha_equal(Value(a), Value(b)) =(a≈Tb)= (a \approx_T b), so a counterexample a,b,ca, b, c for ≈T\approx_T is a counterexample Value(a), Value(b), Value(c) for alpha_equal. □\square

For Int or String, == is the identity and alpha_equal is exactly =α=_\alpha. When == is an equivalence coarser than the identity, alpha_equal is alpha-equivalence modulo ≈T\approx_T: the least congruence containing =α=_\alpha and v∼v′v \sim v' for v≈Tv′v \approx_T v'. 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 +0=−0+0 = -0. which is symmetric and transitive but not reflexive: NaN̸≈TNaN\mathrm{NaN} \not\approx_T \mathrm{NaN}. 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 O(n)O(n) map operations for terms of size nn.

Capture-avoiding renaming of free variables

Problem. Applying a renaming ρ\rho under a binder can capture: renaming x↦yx \mapsto y in βy. x\beta y.\,x naively gives βy. y\beta y.\,y.

Choice. rename_free implements

xρ=ρ(x),vρ=v,t(uˉ)ρ=(tρ)(uρ‾),(βx. t)ρ={βx.  t(ρ∖x)if x∉tgt⁡(ρ∖x),βx′.  (t{x↦x′})(ρ∖x)otherwise,\begin{aligned} x\rho &= \rho(x), \qquad v\rho = v, \qquad t(\bar u)\rho = (t\rho)(\overline{u\rho}),\\ (\beta x.\,t)\rho &= \begin{cases} \beta x.\; t(\rho \setminus x) & \text{if } x \notin \operatorname{tgt}(\rho \setminus x),\\ \beta x'.\; \big(t\{x \mapsto x'\}\big)(\rho \setminus x) & \text{otherwise,} \end{cases} \end{aligned}

with x′=fresh⁡(x, names(t)∪supp⁡(ρ∖x)∪{x})x' = \operatorname{fresh}(x,\ \mathrm{names}(t) \cup \operatorname{supp}(\rho \setminus x) \cup \{x\}).

Lemma (free variables of a renaming). FV(tρ)=ρ(FV(t))\mathrm{FV}(t\rho) = \rho(\mathrm{FV}(t)).

The only interesting case is the binder without freshening. Let ρ′=ρ∖x\rho' = \rho \setminus x with x∉tgt⁡ρ′x \notin \operatorname{tgt}\rho'. By induction FV(tρ′)=ρ′(FV(t))\mathrm{FV}(t\rho') = \rho'(\mathrm{FV}(t)), so

FV((βx. t)ρ)={ρ′(n)∣n∈FV(t)}∖{x}={ρ(n)∣n∈FV(t), n≠x}ρ′(x)=x, ρ′(n)=ρ(n)≠x for n≠x=ρ(FV(βx. t)).\begin{aligned} \mathrm{FV}\big((\beta x.\,t)\rho\big) &= \{\rho'(n) \mid n \in \mathrm{FV}(t)\} \setminus \{x\} \\ &= \{\rho(n) \mid n \in \mathrm{FV}(t),\ n \ne x\} && \rho'(x) = x,\ \rho'(n) = \rho(n) \ne x \text{ for } n \ne x \\ &= \rho(\mathrm{FV}(\beta x.\,t)). \end{aligned}

The second step uses ρ(n)≠x\rho(n) \ne x for n≠xn \ne x: either n∈dom⁡ρ′n \in \operatorname{dom}\rho' and ρ(n)∈tgt⁡ρ′\rho(n) \in \operatorname{tgt}\rho', which excludes xx, or ρ(n)=n≠x\rho(n) = n \ne x. In the freshened case the same computation applies to t{x↦x′}t\{x \mapsto x'\} and x′x', since x′x' is outside supp⁡ρ′\operatorname{supp}\rho' and so neither a source nor a target. The lemma says exactly that no free variable was captured.

The test x∉tgt⁡(ρ∖x)x \notin \operatorname{tgt}(\rho \setminus x) is conservative: it also renames the binder when the offending entry’s source does not occur in tt. 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 =α=_\alpha follows from the translation lemma of the substitution design, which covers renamings as well.

Checked bound renaming

alpha_rename_bound(t, x, y) computes t{x↦y}t\{x \mapsto y\}, the body of the alpha step above, and returns None unless y∉names(t)y \notin \mathrm{names}(t) (or x=yx = y). Under that side condition the alpha axiom gives directly

βx. t  =α  βy. t{x↦y}.\beta x.\, t \;=_\alpha\; \beta y.\, t\{x \mapsto y\}.

The check is stronger than necessary (an occurrence of yy under an inner binder for yy 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 nn levels deep (a chain of Apply heads, of Apply arguments, or of binders) needs nn host frames. The js, wasm and wasm-gc stacks overflow after a few thousand levels, native at 10510^5 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 O(n)O(n) pending items for a term of size nn. There are two schemes, one for folds and one for rebuilds.

Folds. free_variables, all_names, == and alpha_equal have the form

F(t,c)  =  ℓ(t,c)  ⊕  ⨁(t′,c′)∈ch⁡(t,c)F(t′,c′),F(t, c) \;=\; \ell(t, c) \;\oplus\; \bigoplus_{(t', c') \in \operatorname{ch}(t, c)} F(t', c'),

where ch⁡(t,c)\operatorname{ch}(t, c) lists the children of tt with the context the recursive call receives (the bound set BB, extended to B∪{x}B \cup \{x\} under βx\beta x; for alpha_equal, the environments and the depth), ℓ\ell is the contribution of the node itself, and ⊕\oplus is ∪\cup for the name sets and ∧\wedge for the comparisons; for a comparison a node is a pair of subterms, and a mismatch of constructors, names or arities makes ℓ\ell false. Both operations are associative and commutative with a unit (∅\varnothing, true). The loop keeps an accumulator AA and a multiset WW of pending pairs, with the invariant

F(t0,c0)  =  A  ⊕  ⨁(t,c)∈WF(t,c).F(t_0, c_0) \;=\; A \;\oplus\; \bigoplus_{(t, c) \in W} F(t, c).

It holds initially with AA the unit and W={(t0,c0)}W = \{(t_0, c_0)\}. Taking (t,c)(t, c) out of WW, adding ℓ(t,c)\ell(t, c) to AA and putting ch⁡(t,c)\operatorname{ch}(t, c) into WW unfolds one equation of FF, so the invariant is preserved; every pair is put into WW once, so the loop stops, and then A=F(t0,c0)A = F(t_0, c_0). For ∧\wedge the loop returns as soon as AA is false, because false∧b=false\text{false} \wedge b = \text{false}. 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

R(t(u1,…,un),c)=R(t,c)(R(u1,c),…,R(un,c)),R(βx. t,c)=βx′. R(t′,c′)where (x′,t′,c′)=binder⁡(x,t,c),\begin{aligned} R(t(u_1, \dots, u_n), c) &= R(t, c)\big(R(u_1, c), \dots, R(u_n, c)\big), \\ R(\beta x.\, t, c) &= \beta x'.\, R(t', c') \quad\text{where } (x', t', c') = \operatorname{binder}(x, t, c), \end{aligned}

with RR 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 binder⁡\operatorname{binder} and pushes BuildBind(x') and Visit(t', c'). BuildApply(n) pops n+1n + 1 results and pushes their application, and BuildBind(x') wraps the top result in a binder.

Lemma (rebuild). Started on a result stack SS, the tasks that a Visit(t, c) puts on the task stack leave S⋅R(t,c)S \cdot R(t, c) when they are done, and leave the task stack below them unchanged.

Proof. By induction on tt. A leaf pushes R(t,c)R(t, c). For an application, the tasks run in the order Visit(t), Visit(u_1), …, Visit(u_n), BuildApply(n); by induction they leave S⋅R(t,c)⋅R(u1,c)⋯R(un,c)S \cdot R(t, c) \cdot R(u_1, c) \cdots R(u_n, c) before BuildApply(n), which turns the top n+1n + 1 results into R(t,c)(R(u1,c),… )R(t, c)(R(u_1, c), \dots). A binder is the same with one child. □\square

Applied to the root, the lemma gives the result stack [R(t0,c0)][R(t_0, c_0)]. 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 ∧\wedge: 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

  • FV(t)⊆names(t)\mathrm{FV}(t) \subseteq \mathrm{names}(t); map_values preserves both.
  • alpha_equal decides the lifting of T’s == to nameless terms, and coincides with =α=_\alpha when that == is the identity (theorem above). It is reflexive, symmetric and transitive exactly when == is (corollary above). Reflexivity for Int payloads is checked by a QuickCheck property in src/syntax/syntax_wbtest.mbt, and a test there records that a NaN payload is not alpha-equal to itself.
  • rename_free satisfies FV(tρ)=ρ(FV(t))\mathrm{FV}(t\rho) = \rho(\mathrm{FV}(t)) and is invariant under =α=_\alpha: alpha-equivalent inputs give alpha-equivalent outputs.
  • alpha_rename_bound(t, x, y) = Some(t') implies βx. t=αβy. t′\beta x.\,t =_\alpha \beta y.\,t'.
  • On Term[T] every generic_* 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 O(n)O(n) hash-set insertions for a term of size nn. 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 O(n⋅∣ρ∣)O(n \cdot |\rho|) when no binder is renamed; each freshened binder adds all_names and one renaming traversal of its body.

Alternatives rejected

  • Variables inside values. Letting T contain names would require a traversal trait on T as well. Such ASTs implement BindingSyntax directly, which covers the same need with one trait.
  • Multi-variable binders. A binder for several names at once is expressed as nested Bind nodes. This keeps the view small and the proofs per binder.
  • Unchecked bound renaming. A version without the None case 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

  • Value payloads are never inspected. A payload that contains variables is outside the contract.
  • == on terms is structural, not alpha-equivalence.
  • Debug on terms (@debug.to_string, Repr, the messages of assert_eq and inspect) 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 BindingSyntax methods of the downstream type are: project and the three constructors should look at one layer of a node and not recurse into it.
  • alpha_equal compares payloads with T’s == and adds no reflexivity of its own: with a non-reflexive == (such as Double and NaN) 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 BindingSyntax implementation obeys its laws; adapter describes how to test them.
  • Substitution lives in substitution, traversal and rewriting in rewrite.

Footnotes

  1. 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. ↩

  2. N. G. de Bruijn, “Lambda calculus notation with nameless dummies”, Indagationes Mathematicae 34, 1972. ↩

  3. IEEE Std 754-2019, IEEE Standard for Floating-Point Arithmetic, §5.11: every NaN compares unordered with everything, itself included, and +0=−0+0 = -0. ↩