Documentation

ReflectiveSubsystems.CodePacking

The interpreter's configuration layer, as explicit codes #

The small-step interpreter reads and builds configurations. This file realizes the part of that work which needs no arithmetic — the projections out of a configuration or a frame, and the constructors that assemble one — as codes over Nat.Partrec.Code, each proved to agree with the function the mathematical layer uses.

The split, and why it falls here #

The configuration layout nests Nat.pair, so every accessor is a composition of left and right and every constructor a nest of pair: no bounded recursion is involved, and these codes cost a number of steps independent of their input. The stack cell layout is different — it concatenates bits behind a unary header, so reading or building one needs bit-length, powers, division and remainder. That half is built on the arithmetic layer and is not here; this file stays on the arithmetic-free side of that boundary.

Reading a configuration #

Reading a frame #

Building a configuration #

Each constructor takes its components already packed, in the order the step function supplies them: a returning configuration from ⟨v, k⟩, a descending one from ⟨c, ⟨n, k⟩⟩, a frame from ⟨tag, payload⟩.

A descending configuration, from ⟨c, ⟨n, k⟩⟩.

Equations
  • One or more equations did not get rendered due to their size.
Instances For

    The halt value #

    haltVal is the current object of a halted configuration, so it is the same projection as cCfCur. The halt test compares the mode and the stack against constants and so belongs with the arithmetic layer, not here.

    The stack cell's packing #

    A cell concatenates a unary header, the frame and the tail, so building or reading one needs the arithmetic layer: bit-length for the header's width, powers of two for the shifts, division and remainder to undo them. Every code below is a composition of the arithmetic layer with the projections above, and every value law is the corresponding BoundedInterp definition.

    A stack cell, from ⟨f, k⟩.

    Equations
    • One or more equations did not get rendered due to their size.
    Instances For

      The header's length #

      The fold raises its accumulator while the bottom acc + 1 bits are all ones, which trailOnes_lt_iff identifies with acc < trailOnes n. So the fold computes min (trailOnes n) m, exactly as the bit-length fold does.

      The header fold's step: raise the accumulator while the bottom bits are all ones.

      Equations
      • One or more equations did not get rendered due to their size.
      Instances For

        Reading a cell #

        The tail of a stack cell.

        Equations
        • One or more equations did not get rendered due to their size.
        Instances For

          The frame of a stack cell.

          Equations
          • One or more equations did not get rendered due to their size.
          Instances For

            The cell test: does this numeral re-pack to itself?

            Equations
            • One or more equations did not get rendered due to their size.
            Instances For

              The halt test #

              Has the machine finished?

              Equations
              • One or more equations did not get rendered due to their size.
              Instances For

                The dispatch seam #

                stepUFn decides which constructor it is looking at by decoding a numeral into a Code and matching on it. A realization cannot match on a Code — it has only arithmetic — so it reads the constructor off the numeral instead. The two dispatches agree, and this is where that is proved.

                For c < 4 the numeral is the constructor. For c ≥ 4, writing n = c - 4, the constructor is determined by n % 4 and the children's numerals are the two halves of n / 4:

                n % 4constructor
                0pair
                1prec
                2comp
                3rfind' (one child, the whole of n / 4)

                Mathlib's decoder branches on the low two bits through Nat.bodd and Nat.div2; the content of the lemma is that those are the same two bits n % 4 names.

                The dispatch table's leaves #

                Below four the numeral names its constructor outright, so these complete the table ofNat_dispatch starts. Together the five are the whole of what a realization needs to know about decoding: which constructor, and where its children's numerals are.

                The descending step, arithmetically #

                stepDescend decides its branch by decoding. stepDescendArith decides the same branch from the numeral, using the dispatch table above, and stepDescendArith_eq says the two agree. Splitting the work this way applies the seam once rather than once per branch: what is left for the realization is a selection tree over the arithmetic layer, with no decoding in it.

                The descending step, realized #

                A selection tree over the arithmetic layer. There is no decoding in it: stepDescendArith already turned the constructor dispatch into numeral arithmetic, so what is left is eight branches chosen by equality tests on the numeral and on its tag.

                Selection: run x when the guard is nonzero, y when it is zero.

                Equations
                Instances For

                  The guard "this code's value is the constant j".

                  Equations
                  Instances For

                    The descending step's slots, read from ⟨c, ⟨n, k⟩⟩ #

                    The eight branches #

                    pair's branch.

                    Equations
                    • One or more equations did not get rendered due to their size.
                    Instances For

                      prec's branch.

                      Equations
                      • One or more equations did not get rendered due to their size.
                      Instances For

                        comp's branch.

                        Equations
                        • One or more equations did not get rendered due to their size.
                        Instances For

                          rfind''s branch.

                          Equations
                          • One or more equations did not get rendered due to their size.
                          Instances For

                            Each branch's value, computed once #

                            Reducing the branches separately keeps the tree's proof to a case analysis over already-reduced arms; folding them all into one simp call runs the elaborator out of heartbeats.

                            The descending step as a code.

                            Equations
                            • One or more equations did not get rendered due to their size.
                            Instances For

                              The returning step, arithmetically #

                              stepReturn dispatches on frTag f, which is already an accessor — no decoding, and so no seam. stepReturnArith writes the same dispatch as explicit tag comparisons, and stepReturnArith_eq is its agreement. The two inner ifs (the loop's "turns left" test at tag 3 and the search's "found" test at tag 4) carry over unchanged.

                              The returning step, realized #

                              A selection tree over the tag, with the two inner tests (loop's "turns left", search's "found") as their own selections. Same recipe as the descending step: per-branch @[simp] value lemmas by explicit rw, the wide branch codes made local irreducible so the tree's proof never descends into them. The input is ⟨v, ⟨f, k⟩⟩.

                              Payload slots. The digits after rPay spell the projection path into the frame's payload, read left to right: 1 takes a pair's first component, 2 its second. So rPay221 is "second, second, first". Each is built from the slot one digit shorter, and its value on ⟨v, ⟨f, k⟩⟩ is the matching unpair chain on f.unpair.2 (val_rPay1 and below).

                              The frames' branches #

                              Tag 0 — a pair's left value.

                              Equations
                              • One or more equations did not get rendered due to their size.
                              Instances For

                                Tag 3's else — the loop takes another turn.

                                Equations
                                • One or more equations did not get rendered due to their size.
                                Instances For

                                  Tag 4's else — the search probes again.

                                  Equations
                                  • One or more equations did not get rendered due to their size.
                                  Instances For

                                    Each frame branch's value #

                                    The two inner selections, then the tag tree #

                                    Tag 3's branch: the loop, done or turning.

                                    Equations
                                    • One or more equations did not get rendered due to their size.
                                    Instances For

                                      Tag 4's branch: the search, found or probing.

                                      Equations
                                      • One or more equations did not get rendered due to their size.
                                      Instances For

                                        The returning step as a code.

                                        Equations
                                        • One or more equations did not get rendered due to their size.
                                        Instances For

                                          The step function, assembled #

                                          Three outer tests and two group codes. The capstone's proof is a five-way composition — halt, mode, cell test, and the two group laws — rather than a walk over sixteen leaves; that reduction is what splitting the step into stepDescendU and stepReturnU bought.

                                          The interpreter's step function, as a code.

                                          Equations
                                          • One or more equations did not get rendered due to their size.
                                          Instances For

                                            The capstone value law. The code computes the mathematical layer's step function, on every numeral — halted and stuck configurations included.

                                            Nothing in the step searches. The realization is built from bounded recursion and the constructors alone, so it lies in the fragment on which the workspace account is total.

                                            Workspace: the shape a bound can take #

                                            The target shape for one step is "the wider of the input and the output, plus a constant" — the form TimeCost.spaceCost_prec_le receives. SpaceIO c K names it.

                                            Whether a composite meets it is not automatic. TimeCost.spaceCost_comp charges a composition the workspace of the intermediate value as well, and an intermediate is bounded by neither the input nor the output in general. What rescues a composition is that its intermediates are no larger than its input — Shrinking names that — or that they are sub-objects of its output.

                                            A code whose workspace is the wider of its input and output, plus K.

                                            Equations
                                            Instances For

                                              The projection group #

                                              Every configuration and frame accessor is a composition of left and right, so each shrinks and each meets the shape with no constant at all.

                                              Where the shape breaks: forming a pair #

                                              The projection group meets the shape because everything it computes is a piece of what it was given. The arithmetic layer does not, and the reason is visible in the smallest possible instance.

                                              TimeCost.spaceCost_pair charges a pair node the width of the pair it forms, and Cantor pairing of a value with itself is twice as wide as the value. cDbl — doubling, the shortest arithmetic code there is — forms ⟨n, n⟩ on the way to producing 2 * n. Its input is n bits wide, its output one bit more, and its workspace is 2n bits: no constant closes that gap, because the gap grows with the input.

                                              not_spaceIO_cDbl proves it. Every arithmetic code above cDbl inherits the problem — cMul's bounded-recursion step forms ⟨x, acc⟩, cStkCons forms the pairs feeding its shifts — so the workspace of the realized step is bounded by a multiple of the wider of its input and output, not by that width plus a constant. The multiple is absolute (the code is fixed, so its pair-nesting depth is), but it is a multiple.

                                              The shape fails already at doubling. For every constant K there is an input on which cDbl's workspace exceeds the wider of its input and output by more than K — because forming ⟨n, n⟩ costs twice n's width while the output costs one bit more than it.

                                              The prec-free builders #

                                              spaceCost is a maximum over the widths of the values a code's nodes touch, so a bound on those widths is the workspace bound. For the codes that only take a configuration apart and put one back together, every value touched is a piece either of the input or of the output — so the shape holds with no constant.

                                              Selection is strict: both arms are charged #

                                              A selection is comp cIte (pair b (pair x y)). The arithmetic that picks a branch runs after the triple ⟨guard, ⟨then, else⟩⟩ has been built, so building it evaluates both arms. There is no laziness to exploit: the workspace of a selection is at least the workspace of each arm, taken and untaken alike.

                                              That is load-bearing for the total. The interpreter's step evaluates all sixteen of its branches on every input, including the ones whose guard is false — a returning configuration still runs the descending code on whatever its slots happen to hold. Those runs compute nonsense, but they compute it from pieces of the input, so their widths are still bounded in terms of the input's; the bound survives, and the constant has to cover them.

                                              The bounded-recursion projections #

                                              Both projections a fold's step uses read their whole input, so each costs exactly the input's width and nothing more — the first place a value bound is exact rather than estimated.

                                              Width arithmetic for the folds #

                                              The additive fold #

                                              Addition's fold holds ⟨x, ⟨counter, accumulator⟩⟩. Two pairings sit between the accumulator and that triple, so the widest value the fold touches is four times the wider operand, plus a constant for the carry. That factor of four is a property of how the fold's step reads its argument, not of how big the numbers are — the same four will appear in every fold below.

                                              The predecessor chain, and subtraction #

                                              Subtraction counts predecessors, so its bound rests on the predecessor's, which in turn rests on the re-shaping code that hands a one-argument value to a fold. Each layer adds a pairing, and each pairing doubles — the same accounting as addition, one level deeper.

                                              Multiplication #

                                              Multiplication counts additions, so its fold carries an accumulator as wide as the product — the first place the accumulator is genuinely wider than either operand. The bound is stated in the sum of the operands' widths rather than their maximum, because that is what a product costs.

                                              Doubling and powers of two #

                                              A power of two is exponentially wider than its exponent, so there is no bound on cPow2 in terms of its input's width: the honest statement is in terms of the exponent's value. That is not a weakness — every call site in the packing layer applies cPow2 to a width (frameBits f, or a shift exponent built from it), so the value-shaped bound is exactly what composes there.

                                              The bit gates #

                                              The Boolean layer's folds carry a {0,1} accumulator, so their step inputs are narrow: the width comes entirely from the argument being tested, two pairings deep as before.

                                              Disjunction and conjunction #

                                              Both gates thread {0,1} values, so every pair they form is one of four tiny numerals. The width of a bit gate's workspace therefore comes only from the argument being tested — the gate's own plumbing is constant.

                                              Selection's own cost #

                                              cIte multiplies each arm by an indicator and adds. Both products are formed, so both arms' widths are charged — the arithmetic counterpart of cSel's strictness. The indicators are bits, so each product is no wider than its arm.

                                              The shape layer #

                                              Every code in this development is comp and pair nested over leaves. Reducing such a term with simp only is what went wrong before: a pair of a pair has no stable normal form, so an outer rewrite re-expands the inner one and the composite bounds stop matching.

                                              The fix is to stop rewriting. Each lemma below takes bounds on the parts and returns a bound on the whole, so it is applied rather than unfolded — an outer application never touches an inner one, and a walk down a code is a walk down a proof term of the same shape. This is the recipe that worked for selection, as infrastructure.

                                              A guard-rail for widths comes with it: state size facts through size n ≤ n (size_le_self, from CodeLayer.Code.SizeArith) where a zero case exists. The max-form route (size (m+1) ≤ max (size m) (size 1) + 1) is unprovable at zero.

                                              The bit-length fold #

                                              The first walk carried out entirely on the shape layer: the guard block below is one bound application per node, with no rewriting of a composite by its parts, and the selection tail is discharged in a single spaceCost_iteAdvance_bound — the combinator every counter-advancing fold shares. The hypothesis m ≤ Nat.size a is what keeps the exponentiation affordable — cPow2 costs linearly in its argument, so the fold's counter must stay inside the answer's width.

                                              The division fold #

                                              Same walk, one level deeper: the guard is a conjunction of two tests, one of which multiplies. The accumulator hypothesis m ≤ n is what bounds the product's width — the quotient never exceeds the dividend, so the trial multiple stays inside the input's width plus one.

                                              The stack cell's workspace #

                                              The cell constructor is where the interpreter's absolute constant is actually set: it is the widest composition the step runs, and every one of its parts is charged. The three shift codes each carry a bit-length call, so bit-length's own bound is what dominates — which is why the constant below is the same 32 that bit-length pays, rather than a product of the nesting depth.

                                              Reading a cell's workspace #

                                              The readers pay twice what building one does: undoing the frame's shift needs the divisor 2 ^ (2 * stkLen s + 1), which on a numeral that is not a well-formed cell can be about twice as wide as the numeral itself. That doubling is real, so it is carried rather than assumed away.

                                              Growth bounds #

                                              The walks so far bounded one code at a time. The branches cannot be done that way — there are fourteen of them, each a nest of pairings over slots — so the bound is made compositional instead.

                                              A growth bound records two things about g: the workspace it uses, and the width of the value it returns. Both are needed, because a pair node's cost is exactly the width of the pair it forms, so bounding cost alone is not closed under pairing.

                                              They are recorded separately. Division costs thirty-two times its argument's width yet returns something no wider than its argument; carrying one figure for both would let that thirty-two enter the width, and a nest of pairings would then double it at every level for no reason. Keeping the two apart is what holds the coefficients down.

                                              The leaves #

                                              The composite codes #

                                              Each entry pairs a workspace bound already proved above with a width fact. The width facts are the cheap half — most of these codes return something no wider than what they were given — and keeping them out of the cost column is exactly what stops the coefficients compounding.

                                              The slots #

                                              The dispatch's slots read parts of the input, so none of them grows what it was given. The projections cost nothing beyond their argument's width; the three arithmetic slots pay for the subtraction and division that split a code numeral into its tag and children, but still return something no wider than the input, which is what the branches above them need.

                                              The fourteen branches #

                                              Each branch is now a single composition term: the proof mirrors the code's own tree, and the coefficients follow from the laws rather than from a hand walk. They are then brought to one common pair of columns, which is what the selection laws consume.

                                              The common figures are set by prec's descending branch and by the loop's returning branch, the two deepest: both build a stack cell over a payload that is itself four pairings deep.

                                              The trees #

                                              Selection in growth-bound form. The point of the law is visible in the arithmetic: the width columns pass through unchanged, so the cost columns stop climbing after the first selection and the seven nested ones cost exactly what one does. Both arms are charged at every level.

                                              The step #

                                              The configuration's accessors, the two arms, and the outer selection tree.

                                              The columns the whole step sits in: the four GrowBound figures every step variant is brought to, so that a step's bound composes with the next without the coefficients climbing. Workspace is stepC * size I + stepD, output width stepW * size I + stepE.

                                              The interpreter's workspace law #

                                              The step runs in workspace a fixed multiple of the wider of its input and its output, with both the multiple and the offset absolute — independent of the code being interpreted, of the input, and of how far the run has progressed. That independence is the whole content: it is what lets a bound on one step become a bound on a whole run.

                                              The constants are the honest output of the walk above, and they are far larger than the individual codes' own figures. Nothing about the interpreter demands that; it is the price of the two bounds the method leans on. Nat.pair is a squaring pairing, so a pair is charged twice its wider component, and the branches nest pairings six deep over a stack cell that is itself charged three times its frame; a selection is then charged thirty-two times its arms' width. Those factors multiply where the true widths would add. The figures below are upper bounds, and are not claimed to be tight.

                                              The bounded interpreter's step is workspace-bounded by an absolute constant.

                                              Selection #

                                              Selection is where a multiplicative bound would go badly wrong. Composing the growth laws through the descending step's seven nested selections multiplies the coefficient seven times over, for a figure with no bearing on what the code does.

                                              The reason is that the laws above charge a selection as a composition, and so let its output width grow with its cost. It does not: a selection returns one of its arms unchanged. Stating the two separately — every arm inside one budget B, every arm's value inside one width W — makes nesting free, since the conclusion is again B and W. Both arms are charged in B, selection being strict; there is no laziness discount anywhere in this development.

                                              The run #

                                              The step's law becomes the run's. The run is the bounded recursor whose step is the interpreter's step, so the iterate is a prec over a counter, starting from the initial configuration.

                                              Two things about the shape below are worth stating plainly, because the obvious form of this theorem is not the one that is true.

                                              The workspace figure is a hypothesis, not a derived quantity. The natural reading — bound the run by codeDepth · (2F + 2) for a frame width F read off the invariant — does not survive contact with what the invariant says. StackOK charges each cell framePend + stkDepth + 1 ≤ D: both summands are depths, and framePend is itself a codeDepth. It constrains how deeply the machine can still descend. It says nothing whatever about Nat.size of any frame, and no theorem here bounds stkMaxFrame along a run. Nor could one: a frame stores the values a recursion has accumulated, and those are outputs of the computation being simulated, not functions of the code's shape. So the width enters as a named hypothesis on the run, which is where the honest content is.

                                              The iteration count cannot be absent. It appears as Nat.size τ — logarithmically — because the recursor carries its own counter, and the workspace measure charges the width of every value a node touches. What is absent, and is the point, is any dependence of the leading term on how far the run has gone.

                                              The run: iterate the step, from the initial configuration, a stated number of times.

                                              Equations
                                              Instances For

                                                The run computes the mathematical layer's iterate.

                                                theorem ReflectiveSubsystems.spaceCost_runU_le (p x W τ : ℕ) :
                                                (∀ σ ≤ τ, (stepUFn^[σ] (initConfig p x)).size ≤ W) → TimeCost.spaceCost runU (Nat.pair (Nat.pair p x) τ) ≤ 524288 * W + 131120 + 4 * (Nat.pair p x).size + 4 * τ.size + 4 * W

                                                The run's workspace is bounded by the step's constant times the widest configuration it passes through, plus the width of the argument and of the counter — with no dependence of the leading term on how many steps were taken.

                                                W is the run's own width bound, supplied as a hypothesis for the reason given above: nothing in the invariant bounds a frame's width, only how deep the machine may still descend.

                                                The constants are inherited from the step's law and carry its looseness; they are upper bounds and are not claimed to be tight.