utlc/lambda design
Design goal
utlc/lambda is the untyped lambda calculus written as directly as possible
on top of the shared layers: named terms from syntax,
capture-avoiding substitution from substitution, and a
strategy from eval. It is meant to be obviously right rather
than fast, so that faster normalizers (debruijn,
utlc/nbe) and the typed calculus stlc can be checked
against it.
Constraints
- Obviously right. The calculus is the reference that faster normalizers are tested against, so it reuses the shared substitution and strategies instead of reimplementing them.
- Shared syntax. Terms are
Term[T], so domain values ride along and every analysis of syntax applies.
Mathematical background
Lambda terms are , encoded as
Value, Variable, Apply(t, [u]) and Bind(x, t); an n-ary
Apply(f, [a_1, …, a_n]) denotes the curried spine .
Terms are taken modulo .
Beta and eta
Both are closed under all contexts, including under (the rule). The side condition of eta is essential: without it would turn a closed term into an open one and identify functions that behave differently. Eta expresses extensionality: in the presence of , it is equivalent to the rule “if for a fresh then ”, because
Classical properties
- Confluence. and are Church–Rosser, so a term has at most one normal form up to .11 Barendregt, The Lambda Calculus, Theorems 3.2.8 and 3.3.9.
- Normalization. If a term has a beta normal form, the leftmost-outermost strategy reaches it (normalization theorem, see the eval design).
- Eta postponement. Every reduction can be rearranged so that all steps precede all steps; consequently a term has a normal form iff it has a normal form.22 Barendregt, The Lambda Calculus, §15.1.
- Undecidability. Whether a term has a normal form is undecidable, which is why the normalizer takes a step limit.
Design decisions
Beta through the shared substitution
beta_rule calls Substitution::singleton(x, a).apply(b). All capture
avoidance is therefore in one place, proved once in the
substitution design. For the redex
:
Alpha-invariance of substitution (Lemma 3 of the substitution design) is what makes beta well defined on alpha classes. The substitution lemma (Barendregt 2.1.16, derived there as well) makes beta commute with substitution, , which the confluence proofs rely on.
Spines are contracted one argument at a time
A redex is Apply(Bind(x, b), [a, ..rest]). It contracts with the first
argument only and keeps the rest:
. This is beta on the
curried reading of the spine, so every step is a single beta step and the
step count equals the length of the corresponding curried reduction. The De
Bruijn reducer makes the same choice, which keeps the two step by step
comparable.
The redex is a prefix of the spine but is reported at
the spine’s position, the only position the n-ary tree has for it. The
strategies of eval account for this, so each of them takes the
same steps on Apply(f, [a1, a2]) and on Apply(Apply(f, [a1]), [a2]); in
particular, applicative order contracts the prefix before any redex inside
a2.
Eta only on unary applications
eta_rule matches Bind(x, Apply(f, [Variable(x)])). On the curried
reading, (written Apply(f, [a, x])) is also an eta
redex, but recognising it would require splitting the spine and rebuilding
Apply(f, [a]). The rule stays syntactic; callers who build spines n-ary and
need eta can normalize spines to unary form first.
Rules with a bounded host stack
Problem. The rules look below the root of a term in two places: through
empty applications Apply(h, []) around a head, a body or an argument, and
into the function of an eta redex to decide
. A deep , or a long chain of empty
applications, must not overflow the js, wasm and wasm-gc stacks (issue #13).
Choice. Stripping empty applications is a loop. The side condition of eta is decided by a search instead of computing : a heap array holds the subterms still to be searched, and the search answers “free” at the first occurrence of that is not under a binder of . It computes the same answer, because
and the search unfolds exactly this disjunction: it pushes the head and the
arguments of an application, and the body of a binder unless the binder is
. The order in which the disjuncts are tried does not matter, since the
search has no other effect; stopping at the first occurrence also avoids
building the set. Beta substitutes with the stack-safe
substitution, and normalize runs the stack-safe
normal-order search of eval, so every function of the package
uses a constant host stack depth.
Normal order with one combined rule
normalize runs beta_eta_rule with the NormalOrder strategy, so each step
contracts the leftmost-outermost redex of either kind. The combined rule has
one name, "beta_eta"; traces show positions but not which of the two rules
fired. Because beta and eta redexes have different root constructors, the
priority inside beta_eta_rule never changes the outcome of a step.
Beta then eta versus normalize
Problem. A caller may compute the beta normal form first, with
@eval.evaluate(t, _, beta_rule, NormalOrder, _), and then its eta normal
form , with eta_rule. Does agree with the result of
normalize(t, _)?
Not literally. The rules read Apply(h, []) as when they match a
redex, but no rule removes the node. On
, where is
Apply(Variable(z), []), beta alone gives , and
is no eta redex because its body is not an application
to ; so . normalize instead contracts the eta redex at the root
first, reading the argument as , and returns
. and are not alpha-equivalent.
Agreement modulo empty applications. Let erase every empty application:
Call a term unary when each of its Apply nodes has at most one argument;
terms built with application are unary. On a unary term,
gives an ordinary lambda term with binary
application.
Theorem. Let be unary. If
@eval.evaluate(t, _, beta_rule, NormalOrder, _) returns NormalForm(N, _),
@eval.evaluate(N, _, eta_rule, NormalOrder, _) returns NormalForm(M, _),
and normalize(t, _) returns NormalForm(L, _), then
.
Proof. (1) Unary terms are closed under the rules. Beta on a unary
redex Apply(h, [a]) returns with no remaining spine;
substitution copies the unary term into the unary term ; eta returns
a subterm. (2) Erasure is a step-by-step simulation on unary terms.
Erasure keeps every name, so it commutes with capture-avoiding substitution
up to :
.
beta_rule fires on Apply(h, [a]) exactly when is a Bind wrapped in
empty applications, that is, when
is a beta redex, and the contractum erases to its contractum. eta_rule
fires on Bind(x, B) exactly when is Apply(f, [a]) up to empty
applications with a wrapped Variable(x) and ,
that is, when
is an eta redex. No rule fires on an empty application itself, and the
redexes of are the images of the redexes of , where an
empty application contributes the redexes of its head. Hence a rule step
is a step of the same
kind up to , and a term with no redex for the rules erases to a
term with no redex.
(3) By (2), with
beta-normal, then
with
eta-normal. Eta steps keep a term beta-normal: a new beta redex would need
or in the term,
both beta redexes already. So is beta-eta normal and
. Likewise
with
beta-eta normal. By confluence of the
two normal forms are alpha-equivalent.
On the example, and
. Equivalently, and are equal in
the least congruence containing and Apply(h, []) ; in
particular their nameless, spine-flattened forms are equal.
The unary hypothesis is needed for eta only. On the curried reading,
Bind(x, Apply(f, [a, Variable(x)])) is the eta redex
, which eta_rule does not recognise (see “Eta
only on unary applications” above), so for terms with longer spines step (2)
fails and no agreement is claimed.
Correctness and invariants
beta_rule(t) = Some(u)implies at the root;eta_rulelikewise for , with the side condition decided by a search for a free occurrence (above).normalizereturnsNormalForm(u, n)only for with no (unary) or redex anywhere (rewrite normal-form lemma).- By confluence of beta, the beta normal forms computed by
@eval.evaluatewithbeta_rule, by debruijn and by utlc/nbe coincide after conversion and spine flattening. The test “named and debruijn beta reduction agree modulo alpha” checks a step that requires renaming. - Every strategy of eval with
beta_ruletakes the same steps on a term and on its curried form, up to alpha-equivalence; the test “every strategy takes the same steps on a term and its curried form” checks this on 1000 random terms. normalizereturns a beta-eta normal form, which is in general not the beta normal form of the other normalizers: is beta-normal and normalizes to here. The two are related by eta alone, but only modulo empty applications and for unary spines, as the theorem in “Beta then eta versusnormalize” above states.- The rules and
normalizeuse a constant host stack depth; terms nested 100 000 levels deep are handled on every backend (src/utlc/lambda/deep_test.mbt). - With beta and eta combined, normal order is used as the strategy; that it reaches the normal form of every normalizing term rests on the normalization theorem for beta and eta postponement, and is checked by tests rather than proved here.
Alternatives rejected
- A separate lambda AST. Using
Term[T]keeps the calculus inside the shared substrate: the same analyses, substitution and traces apply, and domain values ride along unchanged. - Separate beta and eta normalizers. Offered indirectly: pass
beta_ruleoreta_ruleto@eval.evaluatewith any strategy. - Iterated substitution in beta. Beta substitutes once; the argument is not re-substituted, as the calculus requires.
Boundaries
- No types: ill-behaved terms such as are accepted and end with
StepLimitReached. - No sharing: a duplicated argument is reduced once per copy. Use utlc/nbe for efficient normalization.
- Eta recognises unary applications only.
- An empty application
Apply(h, [])is read as when a redex is matched, but it is not removed from the term (see the eval design). Results of different reduction orders, such as beta then eta andnormalize, therefore agree only after empty applications are erased. - Constants (
Value) have no reduction rules here; add domain rules with rewrite or eval.