A small-step interpreter for Nat.Partrec.Code, on configuration numerals #
Provenance: [Decoupling] §4.5 (the evaluator a general representation functor must carry) and §6.3 (the bounded checker that runs inside a capacity). Both want a universal evaluator that is structurally presented — built from constructors, so that its resource use can be read off — rather than obtained as an existence witness.
What is here, and what is not #
This module is the machine's mathematics: the encoding of configurations as numerals, the
small-step function as a plain Lean definition, and its agreement with Nat.Partrec.Code.eval. The
realization of that step function as an actual Nat.Partrec.Code, and the workspace and step-count
laws that realization carries, are deliberately absent — they are a separate construction on top
of this one. Nothing below prices anything; stepUFn is a function ℕ → ℕ, not a code.
The definitions are nevertheless written so that the realization can mirror them: every case of
stepUFn is a tag test, an unpair, a Nat.pair, or a bounded dispatch on a decoded constructor.
No case iterates.
Two further things a resource account would want are not established here, and the reason is recorded rather than left to be discovered:
- a bound on the number of steps a computation takes.
machine_completegives the run existentially; pinning an explicit budget means carrying an inequality through every composition rather than an iterate count, and its bounded-recursion contribution is a sum over counters, each bounded by the fuel the evaluator needed. That is a quantitative refinement of a settled result, not an open question about the machine.
The configuration layout #
A configuration is one numeral. Layouts are fixed here once, because the realization must reproduce them exactly.
| object | numeral |
|---|---|
| configuration | Nat.pair mode (Nat.pair current stack) |
mode 0 — descend | current = Nat.pair c n: evaluate the code numbered c at input n |
mode 1 — return | current = v: the value v is being handed back to the stack |
| stack, empty | 0 |
| stack, non-empty | 2 * (hdr + frame * 2 ^ (L + 1) + rest * 2 ^ (2 * L + 1)) + 1 |
| — its header | hdr = 2 ^ L - 1, i.e. L low bits of 1, where L = frameBits frame |
| frame | Nat.pair tag payload |
Two levels, two packings, and the difference is the point. A configuration wraps a fixed number
of components, so nesting Nat.pair there costs a constant factor. The stack spine nests once
per pending frame, so it is packed by concatenation instead: a cell writes its frame's bits and its
tail's bits side by side, prefixed by a unary header giving the frame's width. A cell therefore
costs the sum of its parts (size_stkCons_le), and a stack of depth d is linear in d
(size_stack_le) — where a nested pairing would make each cell at least the square of its tail,
and the depth cost bits exponentially.
The low bit of 1 separates a cell from the empty stack 0. The header is unary because it must
be self-delimiting: a fixed-width length field would cap the frames a cell can hold, and frames
carry code numerals of unbounded size. Reading it (trailOnes) scans the header's bits, so it is
the one accessor that is not a constant number of operations — its cost is linear in the frame's
width. Everything else is a shift.
stkIsCons asks whether a numeral is what packing its own head and tail produces. Stating the test
as a round-trip makes reassembly hold by definition, and gives the termination fact
(stkTail_lt: a cell exceeds its tail) that makes the stack's denotation well-founded on every
numeral, well-formed or not.
The five frames, with their payloads and their meaning as "what to do with the value v that is
about to be returned":
| tag | payload | on return of v |
|---|---|---|
0 | Nat.pair cg n | v is a pair's left value: evaluate cg at n, remembering v |
1 | w | v is a pair's right value: return Nat.pair w v |
2 | cf | v is a composition's inner value: evaluate cf at v |
3 | ⟨cg, ⟨a, ⟨y, r⟩⟩⟩ | the bounded-recursion loop (below) |
4 | Nat.pair cf (Nat.pair a m) | if v = 0 return m, else probe cf at ⟨a, m+1⟩ |
The loop frame (tag 3) is how bounded recursion is evaluated: y is the counter reached so far
and r the turns remaining. On return of the accumulator v, if r = 0 the loop is done and v
goes to the tail; otherwise cg runs at ⟨a, ⟨y, v⟩⟩ and comes back with y + 1 and r - 1,
replacing the same cell. So bounded recursion climbs from the base case under one stack cell
rather than unrolling its counter onto the stack — one cell per node, whatever the counter
(stkDepth_prec_descend), which is also how TimeCost.spaceCost prices it.
Unbounded search is a frame like any other (tag 4), so the machine interprets all of
Nat.Partrec.Code — there is no fragment restriction anywhere below.
What the workspace account gets #
The packing is additive (size_stkCons_le), a well-formed stack of depth d costs O(d) bits
(size_stack_le), bounded recursion costs one cell whatever its counter
(stkDepth_prec_descend), and along any run the stack holds at most codeDepth (ofNat p) cells
(stkDepth_run_le). Together: a run of the code numbered p occupies at most
codeDepth (ofNat p) * (2F + 2) bits of stack, F the widest frame it holds.
The depth bound is not a numeric measure — the obvious one is refuted
(runMeasure_not_antitone) — but a per-frame invariant, StackOK, charging each cell for the code
it stores together with the cells beneath it.
Agreement, in both directions #
machine_sound and machine_complete together pin the machine's semantics to Code.eval on all of
Nat.Partrec.Code: it halts with a value exactly when the code has that value. Soundness needs no
fuel and no fragment restriction; completeness goes through the fuelled evaluator as its induction
principle only, never as the statement.
How agreement is proved #
Not by tracking the machine forward, but by giving every configuration a denotation — the value
the whole remaining computation would produce — and showing one step never changes it
(step_denote). Halting configurations are fixed points of the step function, so the invariance
extends to any number of steps by a bare induction (denote_iterate). Soundness is then immediate:
the initial configuration denotes eval (ofNat p) x, a halted one denotes its own answer, and the
two are equal.
The stack's denotation is where the frames earn their meanings: stackDenote k v is what the
machine finally returns if the value v is handed to the stack k. Configurations whose stack is
not a well-formed cell denote nothing, and the step function leaves them alone, so the invariance
holds on all numerals without a well-formedness hypothesis.
One auxiliary fact about Nat.Partrec.Code.eval is proved on the way and is of independent use:
eval_rfind'_unfold, which turns Mathlib's rfind' clause — stated through Nat.rfind over an
offset — into the one-probe recurrence the machine actually implements.
The stack: bit-concatenation with a self-delimiting length header #
A cell lays its three parts side by side in binary rather than nesting them in a pairing function.
Low to high: a unary length header for the frame (frameBits f ones, then a zero), then the
frame's own frameBits f bits, then the tail. The whole is shifted up one place and given a low
bit of 1, which is what distinguishes a cell from the empty stack 0.
Concatenation is the point: a cell's bit-length is the sum of its parts' bit-lengths plus a header
proportional to the frame alone (size_stkCons_le), so a stack of depth d is linear in d, not
exponential. The header is unary because it must be self-delimiting — a fixed-width field would cap
the frames a cell can hold, and the machine's frames carry code numerals of unbounded size.
Decoding is arithmetic: stkBody drops the flag bit, trailOnes reads the header, and the frame
and tail come out by division and remainder at powers of two.
The number of consecutive 1 bits at the bottom of a numeral — the unary header's reader.
Equations
- ReflectiveSubsystems.trailOnes 0 = 0
- ReflectiveSubsystems.trailOnes n.succ = if (n + 1) % 2 = 1 then ReflectiveSubsystems.trailOnes ((n + 1) / 2) + 1 else 0
Instances For
The header's length, in closed form. trailOnes n is the least L at which the bottom
L + 1 bits of n are not all ones — equivalently, L is below it exactly when they are.
Stated as this equivalence rather than as a description of the minimum because that is the form a
bounded fold consumes: a fold that raises its accumulator while the test holds computes
min (trailOnes n) m, with no separate minimality argument.
The induction is on the numeral, halving: an odd numeral's bottom bits are one more than its half's, an even one has none, and zero has none.
The packing arithmetic #
The number of bits a frame occupies in a cell.
Equations
Instances For
A non-empty stack cell. Low to high: the unary header 1^L 0 for L = frameBits f, the
frame's L bits, then the tail — all shifted up one place, with a low bit of 1 marking the cell
apart from the empty stack.
Equations
- One or more equations did not get rendered due to their size.
Instances For
The frame width a cell declares, read off its unary header.
Equations
Instances For
The tail of a stack cell: everything above the header and the frame.
Equations
Instances For
Is this numeral a stack cell? Exactly when it is what packing its own head and tail produces.
Stating the test as a round-trip makes stkCons_head_tail hold by definition, which is what the
denotation's recursion needs on numerals that were never built by stkCons.
Equations
Instances For
Frames and configurations #
A frame: a tag and a payload.
Equations
- ReflectiveSubsystems.frame tag pay = Nat.pair tag pay
Instances For
A configuration: a mode, the current object, and the stack.
Equations
- ReflectiveSubsystems.config mode cur stk = Nat.pair mode (Nat.pair cur stk)
Instances For
The configuration's mode (0 descend, 1 return).
Equations
- ReflectiveSubsystems.cfMode s = (Nat.unpair s).1
Instances For
The configuration's current object.
Equations
- ReflectiveSubsystems.cfCur s = (Nat.unpair (Nat.unpair s).2).1
Instances For
The configuration's stack.
Equations
- ReflectiveSubsystems.cfStk s = (Nat.unpair (Nat.unpair s).2).2
Instances For
A descending configuration: evaluate the code numbered c at input n.
Equations
- ReflectiveSubsystems.descend c n k = ReflectiveSubsystems.config 0 (Nat.pair c n) k
Instances For
A returning configuration: hand the value v back to the stack.
Equations
Instances For
The initial configuration: evaluate the code numbered p at input x, with nothing pending.
Equations
Instances For
Has the machine finished? It has when it is returning a value to the empty stack.
Equations
Instances For
The answer of a halted configuration.
Equations
Instances For
The step function #
One step from a descending configuration: decode the constructor and either answer outright, or push the frame that records what remains to be done. Bounded recursion at a positive counter steps down by one and pushes a frame; unbounded search probes its predicate and pushes a search frame.
Equations
- One or more equations did not get rendered due to their size.
Instances For
One step from a returning configuration, dispatching on the top frame's tag.
Equations
- One or more equations did not get rendered due to their size.
Instances For
The small-step function. Total on all numerals. A halted configuration is a fixed point, as is any configuration whose stack is neither empty nor a well-formed cell — so the machine is never undefined and never falls off its own encoding.
Equations
- One or more equations did not get rendered due to their size.
Instances For
Bounded recursion as an upward loop #
The denotation of a stack, and of a configuration #
Unbounded search, as a one-probe recurrence #
The rfind' recurrence. Mathlib defines eval (rfind' cf) through Nat.rfind over an
offset; the machine instead probes once and either answers or moves the offset up by one. The two
agree: searching from m is probing at m and, if the probe is non-zero, searching from m + 1.
This is the only fact about Code.eval proved here rather than imported, and it is what lets the
search frame be an ordinary frame instead of a nested loop.
One step does not change the denotation #
Soundness #
Soundness. If the machine halts, its answer is a genuine value of the code it was given.
Exact, with no fragment restriction and no fuel: the initial configuration denotes
eval (ofNat p) x, a halted configuration denotes its own answer, and denote_iterate identifies
the two.
Well-formed stacks, their depth, and the size bound the packing buys #
A stack is well formed when it is the empty stack or a cell whose tail is well formed. Its depth
is the number of cells, and its frame width the widest frame it holds. size_stack_le is what
the additive packing was for: a well-formed stack of depth d whose frames are at most F bits
occupies at most d · (2F + 2) bits — linear in the depth, with the constant 2 on F being the
unary header (a frame pays for its own length in bits) and the + 2 the flag and the header's
terminating zero.
This is the shape a workspace account for the machine consumes: the run's workspace is the widest configuration it holds, and a configuration is a bounded wrapper around its stack.
A well-formed stack: the empty stack, or a cell whose tail is well formed.
Equations
- ReflectiveSubsystems.IsStack s = if _h : ReflectiveSubsystems.stkIsCons s = true then ReflectiveSubsystems.IsStack (ReflectiveSubsystems.stkTail s) else s = 0
Instances For
The number of cells in a stack.
Equations
- ReflectiveSubsystems.stkDepth s = if _h : ReflectiveSubsystems.stkIsCons s = true then ReflectiveSubsystems.stkDepth (ReflectiveSubsystems.stkTail s) + 1 else 0
Instances For
The widest frame a stack holds, in bits.
Equations
- One or more equations did not get rendered due to their size.
Instances For
The stack is linear in its depth. A well-formed stack of depth d whose frames are at most
F bits wide occupies at most d · (2F + 2) bits. The factor 2 on F is the unary header, the
+ 2 the flag bit and the header's terminator; neither depends on how deep the stack already is,
which is exactly what the additive packing buys and a nested pairing cannot.
The depth of a code #
The AST depth of a code, with leaves at 1 so that the depth of any code is positive and a bound
stated as a multiple of it never degenerates.
The AST depth of a code: leaves count 1, an internal node one more than its deepest child.
Equations
- ReflectiveSubsystems.codeDepth Nat.Partrec.Code.zero = 1
- ReflectiveSubsystems.codeDepth Nat.Partrec.Code.succ = 1
- ReflectiveSubsystems.codeDepth Nat.Partrec.Code.left = 1
- ReflectiveSubsystems.codeDepth Nat.Partrec.Code.right = 1
- ReflectiveSubsystems.codeDepth (cf.pair cg) = 1 + max (ReflectiveSubsystems.codeDepth cf) (ReflectiveSubsystems.codeDepth cg)
- ReflectiveSubsystems.codeDepth (cf.comp cg) = 1 + max (ReflectiveSubsystems.codeDepth cf) (ReflectiveSubsystems.codeDepth cg)
- ReflectiveSubsystems.codeDepth (cf.prec cg) = 1 + max (ReflectiveSubsystems.codeDepth cf) (ReflectiveSubsystems.codeDepth cg)
- ReflectiveSubsystems.codeDepth cf.rfind' = 1 + ReflectiveSubsystems.codeDepth cf
Instances For
Well-formedness is preserved along a run #
The stack stays well formed along any run. The invariant the run's workspace account
consumes for the stack side: every configuration reachable from initConfig has a well-formed
stack, so size_stack_le applies to it.
How deep the stack goes: bounded recursion costs one cell #
With the loop, every constructor pushes at most one cell per AST node and pops it when that node's evaluation finishes. Bounded recursion is no longer the exception: it pushes its loop cell on the way in, replaces that same cell on each turn of the loop, and pops it on the way out — one cell, whatever the counter. The two facts below are the per-case account.
This is also the coherence the cost model already asserted: TimeCost.spaceCost prices bounded
recursion with the counter inside a max rather than a sum, and the machine now computes the way
that account counts.
Bounded recursion costs one stack cell, whatever its counter. Entering prec cf cg at any
counter pushes exactly one loop cell and descends into the base case.
The candidate run measure, and why it does not settle the depth bound #
With the loop in place the stack finally holds one cell per currently active AST node, so the
bound stkDepth ≤ codeDepth is no longer refuted by bounded recursion. It is still not proved by
the obvious measure. runMeasure — the depth of the code about to be entered plus the stack's
depth — is non-increasing on every descending transition, but it rises on the transitions where
a frame is popped and the machine descends into the code that frame had stored: the second
component of a pair, the outer code of a composition, the step code of the loop. Those codes are
pending work that the measure does not see while it sits on the stack.
runMeasure_not_antitone exhibits it: a composition frame holding a code of depth two, returned to
over an empty stack, takes the measure from one to two.
What the bound needs instead is a per-frame invariant rather than a numeric measure — each frame charged for the code it stores and for the frames beneath it:
StackOK k D := at every cell, codeDepth (stored code) + stkDepth (tail) + 1 ≤ D
together with pendingDepth + stkDepth ≤ D. Pushing a cell leaves the older cells' obligations
untouched (they are stated against the frames below them, which do not move), and a return
discharges exactly the popped cell's obligation into the new pending depth. That is StackOK, in
the next section, and it settles the bound.
The candidate run measure: the depth of the code still to be entered, plus the stack's depth.
Equations
- One or more equations did not get rendered due to their size.
Instances For
The candidate measure is not non-increasing. Returning into a frame that has stored a code
makes that code pending, and its depth enters the measure from nowhere. So runMeasure cannot
witness the depth bound, however the machine evaluates bounded recursion — the obstruction is the
storing of codes in frames, not the shape of any one constructor's rule.
The per-frame invariant, and the depth bound #
Each stack cell is charged for the code it has stored and for the cells beneath it: at every cell,
framePend (frame) + stkDepth (tail) + 1 ≤ D. Paired with pendingDepth + stkDepth ≤ D this is
preserved by every step, and it settles the depth bound the run measure could not.
Why it works where a numeric measure does not: a cell's obligation is stated against the frames beneath it, which never move, so pushing leaves every older obligation untouched. And a return discharges exactly the popped cell's obligation into the new pending depth — the code that was stored becomes the code that is pending, and its charge was already paid for.
The stack never goes deeper than the code. Along any run from initConfig p x, the stack
holds at most codeDepth (ofNat p) cells — one per active node of the code being interpreted, with
bounded recursion contributing one apiece however large its counters.
With size_stack_le this bounds the workspace a run occupies: a stack of at most codeDepth cells
whose frames are at most F bits wide costs at most codeDepth * (2F + 2) bits.
Runs: composing the machine's transitions #
Reaches s t says the machine gets from s to t in some number of steps. Runs compose by adding
iterate counts, which is all the algebra the completeness argument needs: each constructor's run is
a step, a sub-run, a step, a sub-run, and so on.
The transition lemmas below are the machine's rules in the form a run-composition proof uses — one per descending constructor and one per frame, with the frame payloads already destructured.
The descending transitions #
The returning transitions #
Transition rules, stated at codes #
Facts about the fuelled evaluator's bounded recursion #
Two facts about Mathlib's evaln at prec, with no machine content. They reconcile the two
directions in which bounded recursion can be computed: the fuelled evaluator descends from the
counter, spending a level of fuel each time, while a stack machine that keeps one loop frame climbs
from the base case. What the climb needs is the chain of intermediate values, and these recover it —
the clause at counter y + 1 names the value at y, and fuel monotonicity lifts it back.
The loop, run #
Completeness #
Completeness. Every value the code produces is reached by the machine: if x ∈ eval c n
then some number of steps from initConfig halts with x.
With machine_sound this closes the machine's semantics against Code.eval — the two directions
together, on all of Nat.Partrec.Code, with no fragment restriction.
Realizing the step function: what the toolkit charges #
stepUFn is a function on numerals. Turning it into a Nat.Partrec.Code raises a question the
mathematical layer never had to answer — what the eight constructors actually charge for the
operations it performs. The inventory, taken against the definitions above:
Available directly, as compositions of left, right, pair, succ and zero, with a step
count independent of the input: the configuration accessors (cfMode, cfCur, cfStk), the frame
accessors (frTag, frPay), the constructors descend, ret, frame, the four-deep unpair
chains that read a loop or search payload, and the successor on a counter.
Not available, at any cost, without bounded recursion: Nat.Partrec.Code has eight
constructors and no arithmetic primitive beyond succ. Addition of two variables, multiplication,
truncated subtraction, division, remainder, powers with a variable exponent, Nat.size,
trailOnes, and every equality or comparison test must each be built from prec. That covers the
whole of the stack's packing (stkCons, stkBody, stkLen, stkHead, stkTail, stkIsCons),
the halt test, every branch condition, and the arithmetic form of the constructor dispatch.
Why this matters for cost, and not only for size. PrecFree.tc_const below makes the premise
exact: a code built without bounded recursion or search charges a number of steps that does not
depend on its input at all. That is what would license an absolute constant for one step of the
machine. Bounded recursion breaks it in a specific way — TimeCost.tc_prec_le charges
(B + 1) * n for a counter n, linear in the value of the counter rather than in its
bit-length. So a realization that builds addition from prec pays a number of steps proportional
to the numbers it is adding, not to how many bits they occupy.
The workspace side is untouched by this: TimeCost.spaceCost_prec_le bounds bounded recursion by a
max rather than a sum, so a realization can still occupy workspace proportional to the
configuration it holds while taking astronomically many steps. That contrast is already recorded
elsewhere in this development for the bounded checker; it applies here for the same reason.
Codes built without bounded recursion or unbounded search.
Equations
- ReflectiveSubsystems.PrecFree Nat.Partrec.Code.zero = True
- ReflectiveSubsystems.PrecFree Nat.Partrec.Code.succ = True
- ReflectiveSubsystems.PrecFree Nat.Partrec.Code.left = True
- ReflectiveSubsystems.PrecFree Nat.Partrec.Code.right = True
- ReflectiveSubsystems.PrecFree (cf.pair cg) = (ReflectiveSubsystems.PrecFree cf ∧ ReflectiveSubsystems.PrecFree cg)
- ReflectiveSubsystems.PrecFree (cf.comp cg) = (ReflectiveSubsystems.PrecFree cf ∧ ReflectiveSubsystems.PrecFree cg)
- ReflectiveSubsystems.PrecFree (cf.prec cg) = False
- ReflectiveSubsystems.PrecFree cf.rfind' = False
Instances For
A code without bounded recursion takes the same number of steps on every input. Its step
count is a property of its syntax alone: leaves cost one, pair and comp add their parts' costs
and one more, and no clause consults the value flowing through.
This is the exact content of "a fixed constructor-free-of-recursion skeleton costs an absolute constant per step" — and, read the other way, it is what a realization gives up the moment it needs bounded recursion to add two numbers.