utlc/nbe design
Design goal
Small-step normalization repeats a search from the root for every beta step and copies the term each time. Normalization by evaluation (NbE) instead interprets a term as a value of the host language, where beta reduction is just function application, and reads the value back as a normal form. This package provides NbE for the untyped calculus on De Bruijn terms: fast, but bounded by fuel, because untyped terms need not normalize. The operational reducers remain the reference semantics; NbE is checked against them.
Constraints
- Divergence. Untyped terms need not normalize, so every phase must be
bounded, and only by the budget: a divergent run must end with
FuelExhaustedon every backend, whatever the size of the host stack. - Reproducibility. The outcome must not depend on anything but the input and the budget, and the reported cost must be exact.
- Encapsulation. Callers must not be able to build semantic values that break the evaluator’s scope invariant.
Mathematical background
The semantic domain
Values are given by the following grammar, where is an environment (a list of values, index first), a De Bruijn term, a free name and a level:
is the value of in ; is an argument not yet evaluated; neutral values are computations stuck on a variable. In the implementation, also arises when is a constant, since a constant applied to an argument is stuck as well.
Evaluation
evaluates to weak head form:
Arguments are delayed, so evaluation is call by name: an argument that is never used is never evaluated. There is no memoization; a delayed argument used twice is evaluated twice.
Readback
reads back under binders:
A closure is read back by applying it to a fresh variable. That variable is
represented by its level , which does not change while the value is
carried under further binders, and converted to the index at
the occurrence (see levels in the debruijn design).
normalize(t) is for closed .
Design decisions
Untyped NbE needs a budget
Problem. For , evaluation unfolds forever. In the typed setting termination is a theorem (stlc design); here it is false.
Choice. Every evaluation of a node, every force and every readback
step costs one unit of fuel, and running out yields FuelExhausted with the
amount consumed. The budget is threaded through all phases, so the cost of
reading back under binders, which may evaluate closure bodies, is included.
Determinism in the budget. The computation does not inspect the fuel
except to stop, so a run with fuel that ends with a normal form after
consuming units performs exactly the same computation with any fuel
. The fuel is only tested by fuel <= 0, and every test that
passes is followed by spending one unit. If units have been spent before
some test of the original run, that test is followed by at least one more
unit, so ; with fuel the test sees
and passes as well. Every test of the original run
therefore passes again, the run takes the same path, and it stops with the
same result. With the last test sees and fails. Results are
therefore reproducible, and consumed is the exact minimum budget for that
result.
A bounded host stack
Problem. Written as host functions, the equations of evaluation and
readback are mutually recursive, and every call whose result is still
needed keeps a host stack frame. On , applying
evaluates , which applies the closure
again, and none of these calls returns before the fuel runs out: the host
stack grows with the fuel spent. The js, wasm and wasm-gc stacks are much
smaller than a budget of a few million units needs, so such a run overflowed
the stack instead of ending with FuelExhausted, against the constraint
that every phase is bounded. Readback has the same problem on a term with an
infinite normal form, such as ,
whose readback nests one call of per argument.
Choice. Evaluation runs as an abstract machine whose continuation is an explicit stack of frames in the heap: the recursive evaluator in continuation-passing style with the continuations defunctionalized, in the manner of the CEK machine.11 M. Felleisen and D. P. Friedman, “Control operators, the SECD-machine, and the λ-calculus”, 1986, for the CEK machine; M. S. Ager, D. Biernacki, O. Danvy and J. Midtgaard, “A functional correspondence between evaluators and abstract machines”, PPDP 2003, for deriving it from an evaluator by CPS transformation and defunctionalization. A state consists of a control , a continuation (a list of frames, top first) and the remaining fuel :
and are calls of and
; passes a value to the top frame.
, for the arguments
of an application node, waits for the value to
apply to ;
waits for a forced function to apply to . In the code
these are EvalControl (Evaluate, Force, Return) and EvalFrame
(ApplyArguments, ApplyTo). The rules for and
apply when ; with the machine stops with
FuelExhausted, and an index outside stops it with ScopeFailure:
where if and otherwise. An empty application steps to . The machine starts in (or ) and returns with units left when it reaches .
Same values. Read a continuation as the function it still has to apply,
and a state as with , and . Every rule turns a state into one with the same reading, by one of the evaluation equations above: the first seven rules are the equations of and , the rule unfolds the leftmost application of the spine, starting it as the implementation does by forcing the function, and the two rules are the two equations of . When no frame for the remaining arguments is needed, since reads as . By induction on the number of steps, a run that stops at computes .
Same fuel. Units are tested and spent exactly in the
and rules, that is on entry to
and , where the recursive
functions test and spend them; the rules spend nothing, like
returning from a host call and dispatching on its result. The machine makes
the calls in the order of the recursive definition (it is that definition
with its host stack made explicit), so every test sees the same remaining
fuel. Results, consumed, and the determinism argument above are therefore
unchanged; the tests pin exact costs from before the change.
Bounded stacks. The machine is a single loop, so its host stack depth is constant. The frame stack grows only in the rule, which spends a unit, and in the rule, which replaces one frame by at most two and is followed by a step that spends a unit or stops. Hence, at every step,
and the pending work lives in the heap, bounded by the initial budget . On the stack never holds more than one frame: applying the closure to the last argument of the spine leaves nothing below the frame, and the rule pops it before the body is evaluated, so this tail call runs in constant space. A term that grows, such as , keeps one frame per unfolding for its last argument; its stack grows in the heap, within the bound.
Readback is transformed in the same way, with controls (read back under binders) and (pass a term to the top frame) and frames
(QuoteControl and QuoteFrame in the code). A step
spends one unit and forces to ; a constant, a
free name or a level emits the corresponding term, an application
continues with under the frame
, and a closure evaluates in
to and continues with
under . An emitted meets its
frame:
These are the readback equations above, with the head of a neutral read before its argument as before. The forcing and the evaluation inside an step run the evaluation machine to its end and return to the readback loop, so the host stack holds at most the two loops, and , like , is bounded by the units spent.
Deep input terms. The same machines make the host stack independent of
the nesting depth of the input. The rule for
pushes a frame and continues with the head, so a long chain of applications
in head position grows , not the host stack; arguments are delayed, and
a chain nested in argument position is evaluated one level per
step, when readback forces the argument. A binder is a
closure, and readback opens it with one frame. Every frame
is paid for by a unit, so the bound above covers deep
input as well. Before evaluating, eval and normalize validate the input
with @debruijn.validate, which keeps its pending subterms on a heap stack
(see the debruijn design). On every backend, the depth of
the input therefore costs fuel and heap, not host stack.
Shared environments. Opening a binder extends an environment: evaluates in , and readback of under binders evaluates in . Copying for each extension makes a term with nested binders cost
element copies, tens of seconds for . Environments are therefore persistent lists stored in shared arrays: an environment is a pair of an array and a length, with , outermost entry first. No environment ever changes , so
leaves every other environment that shares unchanged: they read only their own prefixes, which the push does not touch. A chain of binders extends each environment once, at the end of its array, so it costs ; lookup stays ; an environment extended twice, as when one closure is applied to two arguments, copies as before. Values, the order of the steps and the fuel spent are the same as with copied environments.
Laziness without sharing
Problem. Strict evaluation (call by value) diverges on , although the term has the normal form .
Choice. Arguments are delayed. Together with readback, which evaluates the head of every neutral first and its arguments afterwards, and enters closures only after their head is known, this realizes normal-order (leftmost-outermost) reduction, the normalizing strategy of the eval design. Call by need would share delayed results; it is not used because it needs mutable thunks, and the budget keeps the cost of recomputation bounded and visible.
Opaque semantic values
Semantic[T] is a struct around a private enum. Callers can create neutral
values (reflect_free, reflect_level), evaluate, and quote, but cannot
build closures with ill-scoped environments. This keeps the invariant that
every closure environment matches the scope of its body, which is why eval
validates its input once and can then trust every index lookup.
Unary applications in normal forms
Readback produces as a unary
Apply, so the spine is returned as Apply(Apply(f, [a]), [b]).
The small-step reducer keeps the n-ary Apply(f, [a, b]) of its input. Both
denote the same curried application; comparisons between the two normalizers
must flatten spines first.
Correctness and invariants
Theorem (soundness). If normalize(t, fuel) returns NormalForm(u, _),
then is beta-normal and (up to spine flattening).
Sketch. Define the denotation of a value under binders as the term it stands for: , , , and so on, where substitutes the denotations of for the free indices of . By induction on evaluation, : the only non-trivial case is , which is the beta step (substitution lemma of the debruijn attachment). Readback inserts only beta steps under binders, so . For normality: produces only from closures, and applications only from , whose head is a neutral or a constant, never a closure (application of a closure is evaluated, not stored). Hence the output follows the grammar
which contains no redex .
Completeness (sketch). If has a beta normal form, normalize
returns it for sufficient fuel. Evaluation computes the weak head normal form
by call by name, and readback recursively normalizes the body of a closure
and the arguments of a neutral after its head: this is the leftmost-outermost
strategy decomposed into head and arguments. By the normalization theorem
(Barendregt 13.2.2) this strategy terminates on every term with a normal
form, and by confluence the normal form is unique.22 For untyped NbE see K. Aehlig and F. Joachimski, “Operational aspects of untyped normalisation by evaluation”, Mathematical Structures in Computer Science 14, 2004; for strong reduction by evaluation, B. Grégoire and X. Leroy, “A compiled implementation of strong reduction”, ICFP 2002.
Agreement with small-step reduction. By soundness and confluence,
whenever both @nbe.normalize and @debruijn.normalize return a normal form
for the same well-scoped term, the two normal forms are equal after spine
flattening, which merges nested applications and drops empty ones. Both read
Apply(h, []) as : evaluation erases the node, and the small-step reducer
looks through it when it matches a redex (see the
eval design). The
tests in src/utlc/nbe/nbe_test.mbt check this, laziness on
, fuel exhaustion on , and that quote turns
levels back into indices. Further tests run , a divergent term whose
head grows, and two terms with infinite normal forms with budgets of thirty
million units on every backend, and pin the exact cost of Church numeral
arithmetic together with its reproducibility at consumed and
consumed - 1. The tests in src/utlc/nbe/deep_test.mbt evaluate, read
back and normalize terms nested to depth 100 000, normal and with redexes,
on every backend.
Other invariants:
- With positive fuel,
evalandnormalizereject ill-scoped input withScopeFailureandconsumed=0before doing any work; with fuel<= 0they returnFuelExhausted(consumed=0)without looking at the term. quote(value, n, _)returnsScopeFailureonly when or a level variable is not below . Values produced byevalcontain no level variables, so quoting them at any level never fails this way.- Fuel:
consumednever exceeds the fuel given; the determinism property above holds. - Stack: validation, evaluation and readback use a constant depth of host stack, whatever the budget and the nesting depth of the input; their frame stacks live in the heap and are bounded by the budget (validation’s by the size of the input).
Alternatives rejected
- Typed or eta-long readback. Untyped readback cannot know where to eta-expand; eta-long normal forms are provided for typed terms by stlc.
- Host-language closures (HOAS). Representing as a MoonBit function would be faster but makes fuel accounting and inspection of values impossible, and the values could not be quoted without a fresh-variable trick on the host side. A first-order closure keeps everything observable.
- Named environments. Indexing the environment by De Bruijn index makes lookup positional and needs no fresh names during evaluation.
- Direct recursion with a larger stack. The js and wasm hosts fix the stack size, and any fixed stack is exhausted by some budget, so the outcome would depend on the backend.
- Trampolining through host closures. Returning a closure for the rest of the computation also bounds the stack, but allocates a host function per step and hides the pending work. First-order frames keep the machine observable, for the same reason as first-order semantic closures.
Boundaries
- Beta only: no eta, no reduction of constants.
- Not total:
FuelExhaustedis the expected outcome for divergent terms and does not prove divergence. - No sharing of delayed arguments.
- The derived
DebugofNbeResultrecurses over the term it contains, so printing a deeply nested normal form can overflow the host stack on js, wasm and wasm-gc;==handles any depth. - Normal forms use unary applications.
- Input must be De Bruijn syntax; convert named terms with
@debruijn.from_namedand results back with@debruijn.to_named.
Footnotes
-
M. Felleisen and D. P. Friedman, “Control operators, the SECD-machine, and the λ-calculus”, 1986, for the CEK machine; M. S. Ager, D. Biernacki, O. Danvy and J. Midtgaard, “A functional correspondence between evaluators and abstract machines”, PPDP 2003, for deriving it from an evaluator by CPS transformation and defunctionalization. ↩
-
For untyped NbE see K. Aehlig and F. Joachimski, “Operational aspects of untyped normalisation by evaluation”, Mathematical Structures in Computer Science 14, 2004; for strong reduction by evaluation, B. Grégoire and X. Leroy, “A compiled implementation of strong reduction”, ICFP 2002. ↩