Programs, lowering and the wrapper

Register machines have increment, decrement-or-branch and halt instructions. A primitive program halts only at its last instruction; it accepts when it halts with every register zero.

DefinitionRegister machines#✓

Instructions. An instruction is \(\mathrm{inc}(j,x)\) (increment register \(j\), go to state \(x\)), \(\mathrm{dec}(j,x,y)\) (if register \(j\) is positive, decrement it and go to \(x\); otherwise go to \(y\)) or \(\mathrm{halt}\). Registers are indexed by \(\mathbb N\) and hold natural numbers; a register file is a map \(\rho:\mathbb N\to\mathbb N\).

Machines and virtual halting. A machine is a map \(\mu:\mathbb N\to\) instructions. A configuration is a pair \((i,\rho)\) of a state and a register file; the step relation executes \(\mu(i)\) and is undefined at a halt instruction. The run of \(\mu\) from \((0,\rho_0)\) halts if it reaches, after finitely many steps, a state \(i\) with \(\mu(i)=\mathrm{halt}\).

Primitive programs. A primitive program is a list \(p=(p_0,\dots,p_{m-1})\), \(m\ge1\), of instructions. It is valid for \(r\) registers if \(p_{m-1}=\mathrm{halt}\), no other instruction is a halt, every register index is below \(r\) and every target is below \(m\). It induces the machine with \(\mu(i)=p_i\) for \(i<m\) and \(\mu(i)=\mathrm{halt}\) for \(i\ge m\). For \(k\le r\) and inputs \(a\in\mathbb N^k\) the initial file has \(\rho_0(i)=a_i\) for \(i<k\) and \(0\) otherwise. A valid \(p\)

  • halts on \(a\) if its run from \((0,\rho_0)\) reaches the final state \(m-1\);
  • accepts \(a\) if its run reaches the final state \(m-1\) with every register zero.

The number of add instructions (increments), sub instructions (decrements) and registers \(r\) are the shape of \(p\). Since a valid program halts only at its final state, a run reaches it at most once and then stops.

This is a definition. Acceptance is the convention of the packed compiler; halting is the convention of the universal numbering; a cleanup stage that clears every register before the final halt converts the second into the first.

inductive Instr
  /-- Increment register `j` and go to state `x`. -/
  | inc (j x : ℕ)
  /-- If register `j` is positive, decrement it and go to `x`; otherwise go to `y`. -/
  | dec (j x y : ℕ)
  /-- Stop. -/
  | halt
  deriving DecidableEq, Repr
abbrev Machine : Type := ℕ → Instr
structure Config where
  /-- The current state. -/
  state : ℕ
  /-- The register file. -/
  regs : ℕ → ℕ
Used by 13

The precision program is written in an ideal register language with natural arithmetic and structured control, whose semantics is a statement about terminating executions, not about a budgeted simulator. Lowering replaces each operation by a primitive block with fresh auxiliary registers; acceptance enters cleanup and rejection a permanent self-loop.

DefinitionThe ideal register language#✓

The ideal register language has registers indexed by \(\mathbb N\) holding natural numbers. Its statements are:

  • assignments \(x\leftarrow k\) (a natural constant), \(x\leftarrow y\), \(x\leftarrow y+z\), \(x\leftarrow y\mathbin{\dot-}z\) (truncated subtraction), \(x\leftarrow y\cdot z\), \(x\leftarrow\lfloor y/z\rfloor\) and \(x\leftarrow y\bmod z\) (with \(\lfloor y/0\rfloor=0\) and \(y\bmod0=y\)), where \(x,y,z\) are registers that may coincide;
  • sequencing \(S_1;S_2\), the conditionals \(\mathbf{if}\ y<z\ \mathbf{then}\ S_1\ \mathbf{else}\ S_2\) and \(\mathbf{if}\ y=z\ \mathbf{then}\ S_1\ \mathbf{else}\ S_2\), the loop \(\mathbf{while}\ y<z\ \mathbf{do}\ S\), and the terminal statements \(\mathbf{accept}\) and \(\mathbf{reject}\).

The big-step semantics is the inductive relation \(\langle S,\rho\rangle\Downarrow o\) between a statement, a register file and an outcome \(o\in\{\mathrm{normal}(\rho'),\mathrm{accept},\mathrm{reject}\}\), with the usual rules (assignments update one register with the exact value; a terminal outcome of \(S_1\) skips \(S_2\); a loop iterates while its test holds). A derivation exists only for terminating executions. A program is a statement \(S\) with a register bound \(\rho_S\) (all registers occurring in \(S\) are below \(\rho_S\)) and \(k\le\rho_S\) input registers; it accepts \(a\in\mathbb N^k\) if \(\langle S,\rho_0(a)\rangle\Downarrow\mathrm{accept}\) for the initial file \(\rho_0(a)\) (inputs in registers \(0,\dots,k-1\), all others \(0\)), and it is total if for every \(a\) some outcome is derivable. The language is deterministic: each statement and file have at most one outcome.

This is a definition. It is the ideal intermediate representation of the manuscript (S22): correctness is a statement about this ideal semantics, not about a budgeted simulator.

inductive Op
  | const (k : ℕ)
  | copy (y : ℕ)
  | add (y z : ℕ)
  | sub (y z : ℕ)
  | mul (y z : ℕ)
  | div (y z : ℕ)
  | mod (y z : ℕ)
  deriving DecidableEq, Repr
inductive Stmt
  | assign (x : ℕ) (o : Op)
  | seq (s t : Stmt)
  | ifLt (y z : ℕ) (s t : Stmt)
  | ifEq (y z : ℕ) (s t : Stmt)
  | whileLt (y z : ℕ) (s : Stmt)
  | accept
  | reject
  deriving DecidableEq, Repr
inductive Outcome
  | normal (ρ : ℕ → ℕ)
  | accept
  | reject
Used by 5

DefinitionLowering to primitive programs#✓

For a program \(S\) of the ideal register language with register bound \(\rho_S\), the lowering \(\mathrm{low}(S)\) is the primitive program built as follows.

  1. Layout. Registers below \(\rho_S\) keep their meaning; register \(J=\rho_S\) is the reserved jump register (always \(0\) at block boundaries, so \(\mathrm{dec}(J,x,x)\) is an unconditional jump to \(x\)); the six registers \(J+1,\dots,J+6\) are auxiliary registers shared by all primitive blocks, each block starting and ending with them zero.
  2. Primitive blocks. Every block for an assignment to \(x\) first snapshots each source \(y\): it moves \(y\) into two fresh auxiliary registers \(a,a'\) (decrement \(y\), increment \(a\) and \(a'\), until \(y=0\)) and moves \(a\) back into \(y\), so that \(y\) is restored and \(a'\) holds its value. Only after all sources are snapshot is \(x\) cleared (a loop of decrements) and written; hence aliasing of \(x\) with \(y\) or \(z\), and \(y=z\), are safe. Then: \(x\leftarrow k\) increments \(x\) \(k\) times; \(x\leftarrow y\) and \(x\leftarrow y+z\) move the snapshots into \(x\); \(x\leftarrow y\mathbin{\dot-}z\) moves the snapshot of \(y\) into \(x\) and then, once per unit of the snapshot of \(z\), decrements \(x\) if it is positive (saturating decrement); \(x\leftarrow y\cdot z\) adds the snapshot of \(y\) into \(x\) (restoring it through a further auxiliary register) once per unit of the snapshot of \(z\), then clears the snapshot of \(y\); \(x\leftarrow\lfloor y/z\rfloor\) and \(x\leftarrow y\bmod z\) test the snapshot of \(z\) for zero (giving \(0\), respectively the snapshot of \(y\)) and otherwise move the snapshot \(r\) of \(y\) one unit at a time into a counter \(m\), keeping a quotient \(q\) and a register \(c=z-m\ge1\): each unit decrements \(c\), and when \(c\) reaches \(0\) the counter \(m\) is cleared, \(q\) is incremented and \(c\) is refilled with \(z\). This maintains \(y=r+qz+m\) with \(0\le m<z\), so at exit (\(r=0\)) \(q=\lfloor y/z\rfloor\) and \(m=y\bmod z\), and \(q\) or \(m\) is moved into \(x\). Every block ends with its auxiliary registers zero and every register below \(\rho_S\) other than \(x\) unchanged.
  3. Control. Sequencing concatenates blocks; a test \(y<z\) or \(y=z\) is a comparison loop on snapshots of \(y\) and \(z\) that branches directly to the two targets; a loop jumps back to its test.
  4. Termination. \(\mathbf{accept}\) jumps to a final cleanup stage that clears every register used by the program and then reaches the final halt; \(\mathbf{reject}\) and normal completion of \(S\) jump to a permanent self-loop \(\mathrm{dec}(J,i,i)\) at its own state \(i\).

Items 1-3 produce the open code \(\mathrm{code}(S)\) of a statement, a list of instructions with one entry state and one normal exit (the state after its last block), parameterized by its start state; item 4 closes it into the primitive program \(\mathrm{low}(S)\), valid for its register count \(r=J+7\), with all targets absolute.

This is a definition. The manuscript's lowering (S22) is described only at this level; the exact block layout is fixed by the Lean definition.

def assignB (J x : ℕ) : Op → ℕ → List Instr
  | .const k, s => clearB x s ++ incs x k s
  | .copy y, s => snap J y (aux J 0) (aux J 1) s ++ clearB x (s + 7) ++ transfer1 J (aux J 0) x (s + 8)
  | .add y z, s => snap2 J y z s ++ clearB x (s + 14) ++ transfer1 J (aux J 0) x (s + 15) ++
      transfer1 J (aux J 2) x (s + 18)
  | .sub y z, s => snap2 J y z s ++ clearB x (s + 14) ++ transfer1 J (aux J 0) x (s + 15) ++
      [.dec (aux J 2) (s + 19) (s + 20), .dec x (s + 18) (s + 18)]
  | .mul y z, s => snap2 J y z s ++ clearB x (s + 14) ++ [.dec (aux J 2) (s + 16) (s + 24)] ++
      transfer2 J (aux J 0) x (aux J 1) (s + 16) ++ transfer1 J (aux J 1) (aux J 0) (s + 20) ++
      [jmp J (s + 15)] ++ clearB (aux J 0) (s + 24)
  | .div y z, s => divModB J x y z true s
  | .mod y z, s => divModB J x y z false s
def ltTest (J y z s th el : ℕ) : List Instr :=
  snap2 J y z s ++
    [.dec (aux J 2) (s + 15) (s + 18), .dec (aux J 0) (s + 14) (s + 16),
      .dec (aux J 2) (s + 16) (s + 17), jmp J th,
      .dec (aux J 0) (s + 18) (s + 19), jmp J el]
def eqTest (J y z s th el : ℕ) : List Instr :=
  snap2 J y z s ++
    [.dec (aux J 2) (s + 15) (s + 16), .dec (aux J 0) (s + 14) (s + 17),
      .dec (aux J 0) (s + 19) (s + 21),
      .dec (aux J 2) (s + 17) (s + 18), jmp J el,
      .dec (aux J 0) (s + 19) (s + 20), jmp J el,
      jmp J th]
Uses 2 · Used by 3

TheoremCorrectness of the lowering#✓

Let \(S\) be a program of the ideal register language with \(k\) inputs, register bound \(\rho_S\) and lowering \(\mathrm{low}(S)\) with \(r\) registers.

  1. (Open code) Say that a machine file \(\sigma\) simulates a file \(\rho\) if \(\sigma(i)=\rho(i)\) for \(i<\rho_S\) and \(\sigma(i)=0\) for \(i\ge\rho_S\) (in particular the jump register and the auxiliary registers are zero). Let \(S'\) be a statement of \(S\) and let \(\sigma\) simulate \(\rho\). If \(\langle S',\rho\rangle\Downarrow\mathrm{normal}(\rho')\), the run from the entry of \(\mathrm{code}(S')\) with file \(\sigma\) reaches its normal exit with a file simulating \(\rho'\); if the outcome is \(\mathrm{accept}\), it reaches the cleanup entry with every register \(i\ge\rho_S\) zero; if it is \(\mathrm{reject}\), it reaches the self-loop. Conversely, if the run from the entry with file \(\sigma\) reaches a halt instruction after \(t\) steps, then either \(\langle S',\rho\rangle\Downarrow\mathrm{accept}\); or \(\langle S',\rho\rangle\Downarrow\mathrm{normal}(\rho')\) and the run from the normal exit, with some file simulating \(\rho'\), reaches a halt instruction within \(t\) steps; or \(\langle S',\rho\rangle\Downarrow\mathrm{reject}\) and the run from the self-loop reaches a halt instruction within \(t\) steps.

For every \(a\in\mathbb N^k\):

  1. if \(\langle S,\rho_0(a)\rangle\Downarrow\mathrm{accept}\), then \(\mathrm{low}(S)\) accepts \(a\) (it reaches its final halt with every register zero);
  2. if \(\mathrm{low}(S)\) halts on \(a\) (reaches its final halt), then \(\langle S,\rho_0(a)\rangle\Downarrow\mathrm{accept}\).

Hence \(\mathrm{low}(S)\) halts on \(a\) iff it accepts \(a\) iff \(S\) accepts \(a\); for a total program that rejects \(a\), the run of \(\mathrm{low}(S)\) never halts.

Proof sketch. Blocks. Each primitive block, entered with the jump register and its auxiliary registers in the state required at block boundaries, reaches its exit after finitely many steps with the register below \(\rho_S\) updated to the exact value and every other register restored (copies restore their source; snapshots make aliased operands safe; saturating decrement is truncated subtraction; repeated addition is multiplication; division maintains \(y=r+qz+m\) with \(0\le m<z\) while it moves the dividend unit by unit). Statements. By induction on the derivation of \(\langle S',\rho\rangle\Downarrow o\), the run from the entry of the code of \(S'\) with a file simulating \(\rho\) reaches its normal exit with a file simulating \(\rho'\), the cleanup entry, or the self-loop, according to \(o\); loops by induction on completed iterations. Cleanup clears all registers and halts. (2) The run is deterministic and the final halt is reachable only through cleanup, which is entered only from the code of \(\mathbf{accept}\). By induction on the statement and, for loops, strong induction on the length of the run fragment from the entry, a fragment reaching a halt yields one of the three alternatives of (0) for that statement (the fragment is a sequence of block executions mirroring the semantics, so for a loop it contains finitely many iterations). At the top level the second and third alternatives are impossible, since the run from the self-loop never halts, so \(\langle S,\rho_0(a)\rangle\Downarrow\mathrm{accept}\).

theorem code_forward {J : ℕ} {S : Stmt} {ρ : ℕ → ℕ} {o : Outcome} (h : BigStep S ρ o) :
    S.RegsBelow J → ∀ {μ : Machine} {s acc rej : ℕ}, Embedded μ s (code J S s acc rej) →
      ∀ σ, Sim J ρ σ → FwdOK J μ s S.len acc rej σ o
theorem code_backward {J : ℕ} {μ : Machine} {F : ℕ} (hF : μ F = .halt) :
    ∀ (S : Stmt), S.RegsBelow J → ∀ {s acc rej : ℕ}, Embedded μ s (code J S s acc rej) →
      ∀ t ρ σ, Sim J ρ σ → HaltsIn μ F t ⟨s, σ⟩ → BwdOK J μ F S s rej t ρ
theorem lower_accepts_of_accepts (hP : P.WF) (a : Fin P.inputs → ℕ) (h : P.Accepts a) :
    (lower P).Accepts a
Sources
Uses 3 · Used by 2

The precision program is built from verified routines for normalized signed integers, quadratic-field pairs, Jacobian points and capped arithmetic. It follows the decision program step by step.

TheoremSigned integer routines#✓

An integer \(z\) is represented by a pair of registers \((\sigma,\mu)\) when \(\mu=|z|\) and \(\sigma=[z<0]\); the representation is normalized: zero has \(\sigma=0\), so each integer has exactly one representation. There are statements of the ideal register language, parameterized by the registers of their operands and results and by a temporary base \(t\) (they use the registers \(t,t+1,\dots\) as temporaries), for: decoding a natural \(c\) into the representation of \(\operatorname{dec}(c)\) (\(\sigma=c\bmod2\), \(\mu=\lfloor(c+\sigma)/2\rfloor\)); an integer constant; copying; negation; absolute value; addition; subtraction; multiplication; the natural quotient \(\lfloor|z_1|/|z_2|\rfloor\) and remainder \(|z_1|\bmod|z_2|\); an assignment with natural value (such as \(|z_1|\cdot|z_2|\)) written into a signed result; and the flags \([z_1<z_2]\) and \([z_1=z_2]\). For each routine with a signed result: if the operand and result registers lie below \(t\), the two result registers are distinct, and in the starting file the operand pairs represent integers \(z_1,z_2\), the statement terminates normally, the result pair represents the corresponding integer (\(\operatorname{dec}(c)\), \(z_1\), \(-z_1\), \(|z_1|\), \(z_1+z_2\), \(z_1-z_2\), \(z_1z_2\), ...), and every register below \(t\) other than the two result registers is unchanged. Results may alias operands. For the flags: if the flag register differs from the operand registers, the statement terminates normally with the flag equal to \(1\) if the relation holds and \(0\) otherwise, and every other register unchanged.

These routines compile statements over integer variables (assignments of the operations above, conditionals on \(z_1<z_2\) or \(z_1=z_2\), which compute the flag into a temporary and branch on it, conditionals on \(|z_1|<|z_2|\) or \(|z_1|=|z_2|\), which branch on the magnitude registers, loops while \(|z_1|<|z_2|\), \(\mathbf{accept}\) and \(\mathbf{reject}\)), integer variable \(k\) being held in the pair \((o+2k,o+2k+1)\) for an offset \(o\): if every variable occurring is below \(K\) and \(o+2K\le t\), and the pairs of the variables below \(K\) represent an integer environment, the compiled statement has the outcome of the integer statement, and on normal termination the pairs represent the final environment.

Proof sketch. Each routine is a case split on the signs with natural arithmetic on the magnitudes: for addition, equal signs add magnitudes, opposite signs subtract the smaller magnitude from the larger and take the sign of the larger, and a zero result gets \(\sigma=0\); multiplication multiplies magnitudes and sets \(\sigma=\sigma_1\oplus\sigma_2\) unless the product is zero. Each case is verified by the big-step rules and arithmetic in \(\mathbb Z\); aliasing is handled by computing into temporaries first.

structure SInt where
  /-- The sign register `σ = [z < 0]`. -/
  sign : ℕ
  /-- The magnitude register `μ = |z|`. -/
  mag : ℕ
  deriving DecidableEq, Repr
def ReprInt (ρ : ℕ → ℕ) (x : SInt) (z : ℤ) : Prop :=
  ρ x.sign = (if z < 0 then 1 else 0) ∧ ρ x.mag = z.natAbs
def sConst (o : SInt) (c : ℤ) : Stmt :=
  asg o.sign (.const (if c < 0 then 1 else 0)) ;; asg o.mag (.const c.natAbs)
Uses 2 · Used by 3

TheoremQuadratic-field routines#✓

An element \(\alpha=g+hs\in\mathbb Z[s]\) is represented by two consecutive integer variables holding \(g\) and \(h\) (two signed integer pairs, four registers). There are statements over integer variables (compiled into the ideal register language by the signed integer routines), using temporaries from a base \(T\) on, that compute:

  • the value, into a result pair, of every field expression built from pairs, integer variables (as \(g+0s\)), constants of \(\mathbb Z[s]\), addition, subtraction, negation, multiplication \((g+hs)(g'+h's)=(gg'+2hh')+(gh'+hg')s\) and conjugation \(g+hs\mapsto g-hs\) (in particular multiplication by an integer);
  • the value, into a result variable, of every integer expression built from integer variables, integer constants, addition, subtraction, multiplication, negation and absolute value (in particular the norm \(\operatorname N(g+hs)=g^2-2h^2\) and the rational component \(g\));
  • an integer constant (by Horner's rule in base \(64\));
  • the flag \([\alpha=0]\), and a guard that executes \(\mathbf{reject}\) when \(\alpha=0\).

If the variables of the expression and the result lie below \(T\) (for the direct code of a field expression, all variables of the expression lie below the result pair; for a single product of two pairs, the result pair is disjoint from both operands), the statement terminates normally with the exact value in the result, and every variable below \(T\) other than the result is unchanged. Likewise the flag, in a variable distinct from \(T\) and from the pair, with \(T\) outside the pair, is computed exactly, changing only the flag and \(T\). The guard on a pair below \(T\) executes \(\mathbf{reject}\) if \(\alpha=0\), and otherwise terminates normally changing only \(T\) and \(T+1\).

Proof sketch. Compositions of the integer operations, verified componentwise and by induction on the expression; an operand that is not a variable is first evaluated into its own slot of temporaries.

inductive FExpr
  | var (w : ℕ)
  | int (w : ℕ)
  | const (a b : ℤ)
  | add (e f : FExpr)
  | sub (e f : FExpr)
  | mul (e f : FExpr)
  | neg (e : FExpr)
  | conj (e : FExpr)
  deriving DecidableEq, Repr
ZInQ.Compiler.IR.FExpr.code · 16 lines
def FExpr.code : FExpr → ℕ → ℕ → ZStmt
  | var w, d, _ => .assign d (.copy w) ;;; .assign (d + 1) (.copy (w + 1))
  | int w, d, _ => .assign d (.copy w) ;;; .assign (d + 1) (.const 0)
  | const a b, d, T => intConst d a T ;;; intConst (d + 1) b T
  | add e f, d, T => FExpr.arg e (e.code T (T + 4)) ;;; FExpr.arg f (f.code (T + 2) (T + 4)) ;;;
      .assign d (.add (e.loc T) (f.loc (T + 2))) ;;;
      .assign (d + 1) (.add (e.loc T + 1) (f.loc (T + 2) + 1))
  | sub e f, d, T => FExpr.arg e (e.code T (T + 4)) ;;; FExpr.arg f (f.code (T + 2) (T + 4)) ;;;
      .assign d (.sub (e.loc T) (f.loc (T + 2))) ;;;
      .assign (d + 1) (.sub (e.loc T + 1) (f.loc (T + 2) + 1))
  | mul e f, d, T => FExpr.arg e (e.code T (T + 4)) ;;; FExpr.arg f (f.code (T + 2) (T + 4)) ;;;
      fMul d (e.loc T) (f.loc (T + 2)) (T + 4)
  | neg e, d, T => FExpr.arg e (e.code T (T + 4)) ;;;
      .assign d (.neg (e.loc T)) ;;; .assign (d + 1) (.neg (e.loc T + 1))
  | conj e, d, T => FExpr.arg e (e.code T (T + 4)) ;;;
      .assign d (.copy (e.loc T)) ;;; .assign (d + 1) (.neg (e.loc T + 1))
def fMul (d a b T : ℕ) : ZStmt :=
  .assign d (.mul a b) ;;; .assign T (.mul (a + 1) (b + 1)) ;;; .assign T (.add T T) ;;;
    .assign d (.add d T) ;;; .assign (d + 1) (.mul a (b + 1)) ;;; .assign T (.mul (a + 1) b) ;;;
    .assign (d + 1) (.add (d + 1) T)
Sources
Uses 2 · Used by 3

TheoremPoint routines#✓

A Jacobian triple \((X,Y,Z)\in\mathbb Z[s]^3\) is represented by three field representations in six consecutive integer variables (twelve registers). There are statements over integer variables (compiled into the ideal register language by the signed integer routines), using temporaries from a base \(T\) on, computing: the constant triples \(P^{\rm J}_0\) and \(O=(1,1,0)\); the plain Jacobian doubling; the branching addition \(\oplus\) and the doubling \(\mathrm{dbl}^\ast\) of the scalar-multiplication statement, including the cases \(Z=0\), equal abscissas (\(H=0\)) with equal or opposite ordinates, and zero ordinate; and the halving loop computing \(\mathrm{mul}(k)\) for an integer variable \(k\) (negating \(Y\) at the end when \(k<0\)). Each, started with its operand and result triples (and \(k\)) below \(T\), and, for the addition, the result triple equal to or disjoint from each operand triple, terminates normally with the exact triple of the Jacobian formulas in the result triple and every variable below \(T\) outside the result triple unchanged; the halving loop terminates because its counter halves.

Proof sketch. Straight-line compositions of the field routines implementing the displayed formulas, with branches on the zero tests of \(Z_1\), \(Z_2\), \(H\), \(\Lambda\), \(Y\); the loop is verified with the invariant of the scalar-multiplication statement, the measure being the counter.

def jdblCode (p q T : ℕ) : ZStmt :=
  let X := FExpr.var p
  let Y := FExpr.var (p + 2)
  let Z := FExpr.var (p + 4)
  let M := FExpr.var T
  let S := FExpr.var (T + 2)
  let X3 := FExpr.var (T + 4)
  FExpr.assign T (.add (.mul (fN 3) (.mul X X)) (.mul fA (.mul (.mul Z Z) (.mul Z Z)))) (T + 10) ;;;
  FExpr.assign (T + 2) (.mul (.mul (fN 4) X) (.mul Y Y)) (T + 10) ;;;
  FExpr.assign (T + 4) (.sub (.mul M M) (.mul (fN 2) S)) (T + 10) ;;;
  FExpr.assign (T + 6) (.sub (.mul M (.sub S X3)) (.mul (fN 8) (.mul (.mul Y Y) (.mul Y Y))))
    (T + 10) ;;;
  FExpr.assign (T + 8) (.mul (.mul (fN 2) Y) Z) (T + 10) ;;;
  copyPt q (T + 4)
def jdblBCode (p q T : ℕ) : ZStmt :=
  zeroFlag T (p + 4) (T + 1) ;;; zeroFlag (T + 1) (p + 2) (T + 2) ;;;
    .assign T (.nadd T (T + 1)) ;;; .assign (T + 1) (.const 0) ;;;
    .ite (.neq T (T + 1)) (jdblCode p q (T + 2)) (setO q)
ZInQ.Compiler.IR.jaddBCode · 39 lines
def jaddBCode (p q r T : ℕ) : ZStmt :=
  let B := T + 3
  let W := B + 29
  let X1 := FExpr.var p
  let Y1 := FExpr.var (p + 2)
  let Z1 := FExpr.var (p + 4)
  let X2 := FExpr.var q
  let Y2 := FExpr.var (q + 2)
  let Z2 := FExpr.var (q + 4)
  let Z1s := FExpr.var B
  let Z2s := FExpr.var (B + 2)
  let U1 := FExpr.var (B + 4)
  let U2 := FExpr.var (B + 6)
  let S1 := FExpr.var (B + 8)
  let S2 := FExpr.var (B + 10)
  let H := FExpr.var (B + 12)
  let L := FExpr.var (B + 14)
  let HH := FExpr.var (B + 19)
  let HHH := FExpr.var (B + 21)
  let X3 := FExpr.var (B + 23)
  let generic : ZStmt :=
    FExpr.assign B (.mul Z1 Z1) W ;;; FExpr.assign (B + 2) (.mul Z2 Z2) W ;;;
    FExpr.assign (B + 4) (.mul X1 Z2s) W ;;; FExpr.assign (B + 6) (.mul X2 Z1s) W ;;;
    FExpr.assign (B + 8) (.mul Y1 (.mul Z2s Z2)) W ;;; FExpr.assign (B + 10) (.mul Y2 (.mul Z1s Z1)) W ;;;
    FExpr.assign (B + 12) (.sub U2 U1) W ;;; FExpr.assign (B + 14) (.sub S2 S1) W ;;;
    zeroFlag (B + 16) (B + 12) (B + 17) ;;; .assign (B + 17) (.const 0) ;;;
    .ite (.neq (B + 16) (B + 17))
      (FExpr.assign (B + 19) (.mul H H) W ;;; FExpr.assign (B + 21) (.mul HH H) W ;;;
        FExpr.assign (B + 23) (.sub (.sub (.mul L L) HHH) (.mul (fN 2) (.mul U1 HH))) W ;;;
        FExpr.assign (B + 25) (.sub (.mul L (.sub (.mul U1 HH) X3)) (.mul S1 HHH)) W ;;;
        FExpr.assign (B + 27) (.mul (.mul H Z1) Z2) W ;;;
        copyPt r (B + 23))
      (zeroFlag (B + 18) (B + 14) (B + 19) ;;;
        .ite (.neq (B + 18) (B + 17)) (setO r) (jdblBCode p r (B + 19)))
  zeroFlag T (p + 4) (T + 1) ;;; .assign (T + 1) (.const 0) ;;;
    .ite (.neq T (T + 1))
      (zeroFlag (T + 2) (q + 4) (T + 1) ;;; .assign (T + 1) (.const 0) ;;;
        .ite (.neq (T + 2) (T + 1)) generic (copyPt r p))
      (copyPt r q)
Uses 2 · Used by 2

TheoremCapped arithmetic routines#✓

Fix an integer variable holding a cap \(L\) (in the precision program \(L\ge1\)). There are statements over integer variables (compiled into the ideal register language by the signed integer routines), using temporaries from a base \(T\) on, computing on natural operands the saturation \(\sigma_L(x)=\min(x,L+1)\), the saturated sum \(\sigma_L(x+y)\), the capped product \(\mathrm{cmul}_L\), the saturated maximum, the capped power \(\mathrm{cpow}_L(x,e)\) (a loop of \(e\) capped multiplications), the saturated factorial \(\sigma_L(n!)\) (a loop of \(n\) capped multiplications), the capped value \(\langle e_A\rangle_L\) of the precision height constant, the capped bound \(\beta\) of the capped precision test, and the division-by-four loop \(x\mapsto\lfloor x/4\rfloor\) repeated \(\beta\) times. Each, started with its operands, the cap and the result below \(T\) (for the division loop, \(x\ne\beta\)), terminates normally with the value prescribed by the corresponding mathematical definition in the result and every variable below \(T\) other than the result unchanged.

Proof sketch. Each statement is a direct transcription of its definition; loops are verified by their invariants (the power loop by \(\sigma_L(x^i)\) after \(i\) steps, the factorial loop by induction on the counter, the division loop by \(x_i=\lfloor x/4^i\rfloor\)), with termination by the increasing counter, which stops at the exponent, at \(n\) and at \(\beta\) respectively.

def satCode (Lv d x T : ℕ) : ZStmt :=
  .assign (T + 1) (.const 1) ;;; .assign T (.nadd Lv (T + 1)) ;;;
    .ite (.nlt T x) (.assign d (.copy T)) (.assign d (.nmul x (T + 1)))
def cmulCode (Lv d a b T : ℕ) : ZStmt :=
  .assign T (.const 0) ;;;
    .ite (.neq a T) (.assign d (.const 0))
      (.ite (.neq b T) (.assign d (.const 0))
        (.assign (T + 1) (.div Lv b) ;;;
          .ite (.nlt (T + 1) a) (.assign (T + 2) (.const 1) ;;; .assign d (.nadd Lv (T + 2)))
            (.assign d (.nmul a b))))
def cpowCode (Lv d x e T : ℕ) : ZStmt :=
  .assign T (.const 1) ;;; .assign (T + 1) (.const 0) ;;; .assign (T + 2) (.const 1) ;;;
    .loop (T + 1) e (cmulCode Lv T T x (T + 3) ;;; .assign (T + 1) (.nadd (T + 1) (T + 2))) ;;;
    .assign d (.copy T)
Uses 3 · Used by 2

DefinitionThe precision program#✓

The precision program \(S_{\rm prec}\) is the program of the ideal register language with \(5\) inputs (the natural numbers \(c_0,\dots,c_4\) in registers \(0,\dots,4\)) that performs the steps of the exact decision program in order, using the routines: decode the five inputs into signed pairs; perform the early tests and execute \(\mathbf{reject}\) when one fails; compute the three Jacobian representatives with the point routines and reject on a zero third or second coordinate; form \(\nu_k\), \(N_k\), \(U\), \(V\), \(\theta\), \(\delta\) with the field and signed routines and reject unless the closeness inequality holds; compute \(L=\lfloor(V-1)/(4U)\rfloor\), reject if \(L=0\), compute \(M=|\kappa F(n)|\), then \(\beta\) with the capped routines, run the division-by-four loop, and execute \(\mathbf{accept}\) if its final value is at least \(1\) and \(\mathbf{reject}\) otherwise. All other registers start at \(0\); the routines take their temporaries from a common region above all named quantities.

This is a definition. The manuscript's IR S22 is not available in this repository; this program is specified from the description of S21 and S22 in Section 10, and its exact register allocation is fixed by the Lean definition.

def precisionZ : ZStmt :=
  .assign 5 (.const 0) ;;; .assign 6 (.const 1) ;;; .assign 7 (.const 3) ;;; .assign 8 (.const 4) ;;;
    earlyCode ;;; jmul3Code ;;; testCode
def precisionProgram : Program where
  body := decodeInputs precRegT ;; precisionZ.compile precOff precRegT
  bound := precRegT + precisionZ.temps + 8
  inputs := 5
theorem precisionProgram_wf : precisionProgram.WF
Uses 6 · Used by 2

TheoremCorrectness of the precision program#✓

The precision program is total, and for every \(c\in\mathbb N^5\) it accepts \(c\) if and only if \(\mathrm{decide}(c)=\mathrm{true}\), if and only if \(\operatorname{accepts}(c)\). Its outcome on an input that fails an early test is \(\mathbf{reject}\).

Proof sketch. Compose the routine contracts along the program: after each routine the registers represent exactly the quantities of the corresponding step of the decision program, every branch agrees with the corresponding test, and every loop terminates (the halving scalar loop, the bounded factorial and capped-power loops, and the division loop of at most \(L+1\) steps). Hence the derivable outcome is \(\mathbf{accept}\) exactly when the decision program returns true, and the correctness of the decision program gives the relation.

theorem precisionZ_spec (E : ℕ → ℤ) :
    ZBigStep precisionZ E (if decideInt (E 0) (E 1) (E 2) (E 3) (E 4) then .accept else .reject)
theorem precisionProgram_bigStep (c : Fin 5 → ℕ) :
    BigStep precisionProgram.body (RM.initFile c) (if decide5 c then .accept else .reject)
theorem precisionProgram_total : precisionProgram.Total
Uses 7 · Used by 1

TheoremThe precision machine halts exactly on acceptance#✓

Let \(M_{\rm prec}=\mathrm{low}(S_{\rm prec})\), a primitive program valid for its register count \(r_{\rm prec}\), with \(5\) inputs. For every \(c\in\mathbb N^5\): $\(M_{\rm prec}\text{ halts on }c\iff M_{\rm prec}\text{ accepts }c\iff\operatorname{accepts}(c).\)$ When \(\operatorname{accepts}(c)\) fails, the run of \(M_{\rm prec}\) never halts, although the ideal program is total.

Proof sketch. Correctness of the lowering applied to the total program \(S_{\rm prec}\), followed by the correctness of the precision program. When \(\operatorname{accepts}(c)\) fails, the outcome of \(S_{\rm prec}\) on \(c\) is \(\mathbf{reject}\) and the run of \(M_{\rm prec}\) reaches the permanent self-loop of the lowering.

def precisionMachine : RM.Program := lower precisionProgram
def precRegs : ℕ := precisionProgram.regCount
theorem precisionMachine_halts_iff (c : Fin 5 → ℕ) :
    precisionMachine.HaltsOn c ↔ accepts c
Sources
Uses 5 · Used by 2

The wrapper receives the five inputs as one Cantor code, inverts four pairs into registers zero to four with scratch above the precision machine's registers, and runs the relocated precision machine.

DefinitionCantor pairing and its decoder#✓

The pairing of natural numbers is $\(\operatorname{pair}(a,b)=\frac{(a+b)(a+b+1)}2+b,\)$ and the five-fold right-nested encoding is $\(\operatorname{enc}_5(c_0,c_1,c_2,c_3,c_4)=\operatorname{pair}(c_0,\operatorname{pair}(c_1,\operatorname{pair}(c_2,\operatorname{pair}(c_3,c_4)))).\)$ The decoder runs the loop on states \((s,\varrho)\) starting at \((0,x)\): while \(s<\varrho\), replace \((s,\varrho)\) by \((s+1,\varrho-(s+1))\); at exit return \((a,b)=(s-\varrho,\varrho)\). Write \(\operatorname{unpair}(x)\) for the result, and \(\operatorname{dec}_5(x)\) for the five numbers obtained by applying \(\operatorname{unpair}\) four times to successive second components (the last second component is the fifth number).

This is a definition. The loop maintains \(\varrho=x-s(s+1)/2\) and terminates because \(\varrho\) decreases.

@[expose] def pair (a b : Nat) : Nat :=
  (a + b) * (a + b + 1) / 2 + b
@[expose] def decode (x : Nat) : Nat × Nat := loop 0 x
@[expose] def encode5 (a b c d e : Nat) : Nat :=
  pair a (pair b (pair c (pair d e)))
Used by 4

TheoremUnique Cantor unpairing#✓

  1. For all natural \(a,b\): \(2\operatorname{pair}(a,b)=(a+b)(a+b+1)+2b\), and \(\frac{(a+b)(a+b+1)}2\le\operatorname{pair}(a,b)<\frac{(a+b+1)(a+b+2)}2\) (triangular intervals). Hence \(\operatorname{pair}\) is a bijection \(\mathbb N^2\to\mathbb N\).
  2. \(\operatorname{unpair}(\operatorname{pair}(a,b))=(a,b)\) and \(\operatorname{pair}(\operatorname{unpair}(x))=x\); likewise \(\operatorname{dec}_5\circ\operatorname{enc}_5=\mathrm{id}\) and \(\operatorname{enc}_5\circ\operatorname{dec}_5=\mathrm{id}\).
  3. For natural \(a,b,t\): \(2t-(a+b)(a+b+1)-2b=0\) (in \(\mathbb Z\)) if and only if \(t=\operatorname{pair}(a,b)\).
  4. Consequently, for \(c\in\mathbb N^5\) and \(t_4=c_4\), the four pairing equations $\(2t_i=(c_i+t_{i+1})(c_i+t_{i+1}+1)+2t_{i+1}\qquad(0\le i<4)\)$ have exactly one natural solution \((t_0,t_1,t_2,t_3)\), namely \(t_i=\operatorname{pair}(c_i,t_{i+1})\), and then \(t_0=\operatorname{enc}_5(c)\).

Proof sketch. (1) \((a+b)(a+b+1)\) is even; the interval bounds follow from \(0\le b\le a+b\), and disjointness of consecutive intervals gives injectivity (equal pairs have equal \(a+b\), then equal \(b\)); surjectivity from (2). (2) The loop invariant \(\operatorname{pair}(\mathrm{loop}(s,\varrho))=s(s+1)/2+\varrho\), by strong induction on \(\varrho\); at exit \(0\le\varrho\le s\), so \(b=\varrho\) and \(a=s-b\) lie on diagonal \(s\). (3) Divide by two. (4) Solve from \(i=3\) down to \(i=0\) with (3).

theorem cantor_pair_props :
    (∀ a b, 2 * pair a b = (a + b) * (a + b + 1) + 2 * b) ∧
    (∀ a b, (a + b) * (a + b + 1) / 2 ≤ pair a b) ∧
    (∀ a b, pair a b < (a + b + 1) * (a + b + 2) / 2) ∧
    Function.Bijective (fun p : ℕ × ℕ => pair p.1 p.2)
theorem cantor_unpair_props :
    (∀ a b, decode (pair a b) = (a, b)) ∧ (∀ x, pair (decode x).1 (decode x).2 = x) ∧
    (∀ a b c d e, decode5 (encode5 a b c d e) = (a, b, c, d, e)) ∧
    (∀ x, encode5 (decode5 x).1 (decode5 x).2.1 (decode5 x).2.2.1 (decode5 x).2.2.2.1
      (decode5 x).2.2.2.2 = x)
theorem cantor_pairing_equation (a b t : ℕ) :
    (2 * (t : ℤ) - ((a : ℤ) + b) * ((a : ℤ) + b + 1) - 2 * (b : ℤ) = 0) ↔ t = pair a b
Uses 1 · Used by 2

DefinitionThe wrapper program#✓

Let \(M_{\rm prec}\) have \(m_{\rm prec}\) instructions and register count \(r_{\rm prec}\). The wrapper \(\mathcal W\) is the primitive program $\(\mathcal W=\Pi\ \|\ (M_{\rm prec}\text{ with every target increased by }|\Pi|),\)$ where the prefix \(\Pi\) is the open code (the lowering without its termination stage) of the following program of the ideal register language, with all its registers other than \(0,\dots,4\) (working registers, auxiliary registers and its own jump register) at indices at least \(r_{\rm prec}\): starting with the input \(x\) in register \(0\), compute \((c_0,y_1)=\operatorname{unpair}(x)\), \((c_1,y_2)=\operatorname{unpair}(y_1)\), \((c_2,y_3)=\operatorname{unpair}(y_2)\), \((c_3,c_4)=\operatorname{unpair}(y_3)\) by the decoder loop (subtract \(s+1\) from the remainder while \(s\) is below it), place \(c_i\) in register \(i\) for \(i\le4\), clear every register it used at index at least \(r_{\rm prec}\), after which the normal exit of \(\Pi\) is the first state of the relocated \(M_{\rm prec}\). Registers of \(M_{\rm prec}\) are not renamed; only its targets are relocated by \(|\Pi|\), and its final halt is the final halt of \(\mathcal W\).

This is a definition. \(\mathcal W\) is valid for \(\max(r_{\rm prec},r_\Pi)\) registers and has one input.

def unpairProgram : Program where
  body := unpairBody precRegs
  bound := precRegs + 3
  inputs := 1
def wrapperPrefix : List Instr := code unpairProgram.bound unpairProgram.body 0 0 0
def relocate (d : ℕ) : Instr → Instr
  | .inc j x => .inc j (x + d)
  | .dec j x y => .dec j (x + d) (y + d)
  | .halt => .halt
Uses 3 · Used by 4

TheoremCorrectness of the wrapper#✓

For every \(x\in\mathbb N\), the wrapper halts on the input \(x\) (reaches its final halt from the file with \(x\) in register \(0\) and all other registers zero) if and only if \(\operatorname{accepts}(\operatorname{dec}_5(x))\). In particular, for every \(c\in\mathbb N^5\), $\(\mathcal W\text{ halts on }\operatorname{enc}_5(c)\iff\operatorname{accepts}(c).\)$

Proof sketch. The prefix terminates (each decoder loop decreases its remainder) and reaches the first relocated state with \(c_0,\dots,c_4\) in registers \(0,\dots,4\), every auxiliary register cleared, and every other register below \(r_{\rm prec}\) still zero (the prefix touches only registers \(0,\dots,4\) and registers at least \(r_{\rm prec}\)). This is the initial file of \(M_{\rm prec}\) on \((c_0,\dots,c_4)\), extended by zeros. Relocation by \(|\Pi|\) is a bijection between the runs of \(M_{\rm prec}\) and the runs of the suffix of \(\mathcal W\) that preserves the final halt; registers at least \(r_{\rm prec}\) are never read by \(M_{\rm prec}\). Hence \(\mathcal W\) halts on \(x\) iff \(M_{\rm prec}\) halts on \(\operatorname{dec}_5(x)\), iff \(\operatorname{accepts}(\operatorname{dec}_5(x))\); and \(\operatorname{dec}_5(\operatorname{enc}_5(c))=c\).

theorem wrapper_halts_iff_machine (x : ℕ) :
    wrapper.HaltsOn ![x] ↔ precisionMachine.HaltsOn (dec5 x)
theorem wrapper_halts_iff (x : ℕ) : wrapper.HaltsOn ![x] ↔ accepts (dec5 x)
theorem wrapper_halts_encode (c : Fin 5 → ℕ) :
    wrapper.HaltsOn ![encode5 (c 0) (c 1) (c 2) (c 3) (c 4)] ↔ accepts c
Uses 6 · Used by 1
15 fully proved

The dependency explorer needs JavaScript and its graph data.

Download the complete graph data.