diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 767b8d794e..598fd5ceb8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -782,7 +782,7 @@ jobs: lake env lean --run Scripts/CheckCiFilters.lean --self-test lake env lean --run Scripts/CheckCiFilters.lean - name: Run primary IxTests - run: lake env .lake/build/bin/IxTests + run: lake env .lake/build/bin/IxTests -j 16 - name: Test Ixon contracts and primitives run: | lake env .lake/build/bin/ixon-primitives diff --git a/Cargo.lock b/Cargo.lock index 764595e423..ecced43997 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2304,7 +2304,7 @@ dependencies = [ [[package]] name = "multi-stark" version = "0.1.0" -source = "git+https://github.com/argumentcomputer/CertiFRI.git?rev=7712efe9ea14464519723599bba080ef3a6f2ff5#7712efe9ea14464519723599bba080ef3a6f2ff5" +source = "git+https://github.com/argumentcomputer/CertiFRI.git?rev=14f7a315bf5bc46fb124b6f0e9bb53b1f23ea63b#14f7a315bf5bc46fb124b6f0e9bb53b1f23ea63b" dependencies = [ "bincode", "blake3", diff --git a/Cargo.toml b/Cargo.toml index 0b8d4859cb..69d37365e4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -81,7 +81,7 @@ libc = "0.2" memmap2 = "0.9" # Bundle v3.5.1 to fix large-arena failures (microsoft/mimalloc#1309). mimalloc = { git = "https://github.com/argumentcomputer/mimalloc_rust.git", rev = "616cc1f130d9ea2a1111a46b4e98c140e078f882", default-features = false } -multi-stark = { git = "https://github.com/argumentcomputer/CertiFRI.git", rev = "7712efe9ea14464519723599bba080ef3a6f2ff5" } +multi-stark = { git = "https://github.com/argumentcomputer/CertiFRI.git", rev = "14f7a315bf5bc46fb124b6f0e9bb53b1f23ea63b" } nom = "7.1.3" num-bigint = "0.4.6" quickcheck = "1.0.3" diff --git a/Ix/Aiur/FriSecurity.lean b/Ix/Aiur/FriSecurity.lean index 3cd980175b..581de01e42 100644 --- a/Ix/Aiur/FriSecurity.lean +++ b/Ix/Aiur/FriSecurity.lean @@ -95,8 +95,27 @@ structure Parameters where digestBytes : Nat := 32 protocolVersion : Nat := 6 batching : Option Batching := none + /-- True internal hash state width in bits (`none` defaults to `256` for 32B/48B + BLAKE3 because BLAKE3's internal `cv` is fixed at 256 bits, and `512` for 64B + hashes such as RFC 7693 `BLAKE2b-512`). -/ + hashStateBits : Option Nat := none + /-- Whether Stage-1 pinning (`CertiFRI` PR #9 `GoldilocksExt*JohnsonPinned`) is enabled. -/ + stage1Pinning : Bool := false + /-- QROM RBR lifting constant `C₁` in `C₁ · Q² · ε_rbr` (default `4.0`, tight CFHL21/DFMS22). -/ + qromC1 : Float := 4.0 + /-- QROM compressed-oracle collision constant `C₂` in `C₂ · Q³ / 2^{stateBits}` (default `27.0`, Zhandry19). -/ + qromC2 : Float := 27.0 + /-- Log₂ of NIST `MAXDEPTH` circuit depth cap for Model Q2 (default `40`, i.e., `2^40`). -/ + maxDepthBits : Nat := 40 deriving Inhabited +/-- Effective internal hash state width in bits. +For `digestBytes = 32` or `48` (BLAKE3-256 / BLAKE3-XOF48), BLAKE3's internal +chaining value `cv` is fixed at 256 bits; for `digestBytes ≥ 64` (`BLAKE2b-512` / +`SHA-512` / `SHA3-512`), the default internal state is 512 bits unless overridden. -/ +def Parameters.effectiveHashStateBits (p : Parameters) : Nat := + p.hashStateBits.getD (if p.digestBytes ≥ 64 then 512 else 256) + /-- Effective FRI batching mode: explicit override if set, otherwise `tensor` (`FriBatching::Tensor`) for Protocol `v6` (`extensionDegree ≥ 3 ∧ protocolVersion ≥ 6`) and `powers` (Horner) for legacy `v5` / `Fp^2` profiles. -/ @@ -317,6 +336,7 @@ def minLogTraceForUdBits (p : Parameters) structure Regime where name : String terms : Array (String × Float) + deriving Inhabited /-- The weakest term. -/ def Regime.limit (r : Regime) : String × Float := @@ -433,12 +453,17 @@ def terms (inst : Instance) (p : Parameters) : Array Regime := Id.run do terms := #[("ALI", ali), ("DEEP", certDeep), ("lookup", certLookup), ("batching", certBatch), ("commit", certCommit), ("query", certQuery), ("collision", colBits)] }] - -- CertiFRI 4f563b7 Tier-2 BatchedLineListCA + GoldilocksExt3JohnsonStark regime + -- CertiFRI PR #9 Tier-2 BatchedLineListCA + GoldilocksExt*JohnsonStark/Pinned regime let mut bestCertJ : Option (Float × Regime) := none if p.logBlowup ≥ 1 then let sqrtRho := Float.sqrt rho - for step in [2:120] do - let theta := (1.0 + 1.0 / nat step) * sqrtRho + let mut candidateThetas : Array Float := #[] + for step in [2:400] do + candidateThetas := candidateThetas.push ((1.0 + 1.0 / nat step) * sqrtRho) + for k in [1:40] do + let theta := sqrtRho + (nat k / 40.0) * (0.95 - sqrtRho) + candidateThetas := candidateThetas.push theta + for theta in candidateThetas do if theta < 1.0 && rho < theta * theta then let lJ := (theta - rho) / (theta * theta - rho) if let some cT := certCurveListCoeff n k theta then @@ -454,10 +479,20 @@ def terms (inst : Instance) (p : Parameters) : Array Regime := Id.run do let jAli := F - log2 (max (lJ * max (nat inst.constraints) 1) 1) let jDeep := F - log2 (max (lJ * certDegreeTerm + 2.0 * n) 1) let jQuery := queryPow - queries * log2 theta + let baseTerms : Array (String × Float) := + if p.stage1Pinning then + let lInt := Float.ceil lJ + let pinPairs := max (lInt * (lInt - 1.0) / 2.0) 1.0 + let jPin := F - log2 (max (pinPairs * k) 1) + let jLookup := F - log2 (max (2.0 * (nat inst.lookupWidth + 2) * nat inst.lookupRows) 1) + #[("ALI", jAli), ("DEEP", jDeep), ("pinning", jPin), ("lookup", jLookup), + ("batching", jBatch), ("commit", jCommit), ("query", jQuery), ("collision", colBits)] + else + #[("ALI", jAli), ("DEEP", jDeep), ("batching", jBatch), + ("commit", jCommit), ("query", jQuery), ("collision", colBits)] let r : Regime := { name := "CertiFRI proven Johnson" - terms := #[("ALI", jAli), ("DEEP", jDeep), ("batching", jBatch), - ("commit", jCommit), ("query", jQuery), ("collision", colBits)] } + terms := baseTerms } match bestCertJ with | some (_, b) => if r.betterThan b then bestCertJ := some (theta, r) | none => bestCertJ := some (theta, r) @@ -543,6 +578,154 @@ def report (source : String) (inst : Instance) (p : Parameters) : String := Id.r lines := lines.push s!" {r.name}: {fmt bits} bits (limited by {name}) {detail}" return "\n".intercalate lines.toList +/-- Post-quantum (Model Q1, unbounded-depth QROM) interactive bit-security for a +classical RBR soundness term `b = -log₂(ε_rbr)`: +`½ · (b - log₂ C₁)` from `C₁ · Q² · ε_rbr ≤ 1`. -/ +def q1InteractiveBits (classicalBits c1 : Float) : Float := + max 0.0 ((classicalBits - log2 (max c1 1.0)) / 2.0) + +/-- Post-quantum (Model Q1, unbounded-depth QROM) hash collision bit-security for +an internal hash state width of `stateBits`: +`⅓ · (stateBits - log₂ C₂)` from `C₂ · Q³ / 2^{stateBits} ≤ 1` (BHT / Zhandry compressed oracle). +NOTE: For BLAKE3 (32B or XOF48/XOF64), `stateBits = 256` regardless of XOF output length. -/ +def q1CollisionBits (stateBits : Nat) (c2 : Float) : Float := + max 0.0 ((nat stateBits - log2 (max c2 1.0)) / 3.0) + +/-- Combined Model Q1 security in bits (`log₂ N`) solving +`C₁ · N² · 2^{-iopBits} + C₂ · N³ · 2^{-stateBits} = 1` via bisection. -/ +def q1CombinedBits (iopBits : Float) (stateBits : Nat) (c1 c2 : Float) : Float := Id.run do + let logC1 := log2 (max c1 1.0) + let logC2 := log2 (max c2 1.0) + let sb := nat stateBits + let mut lo : Float := 0.0 + let mut hi : Float := 512.0 + for _ in [0:64] do + let mid := (lo + hi) / 2.0 + let t1 := pow2 (logC1 + 2.0 * mid - iopBits) + let t2 := pow2 (logC2 + 3.0 * mid - sb) + if t1 + t2 ≤ 1.0 then + lo := mid + else + hi := mid + return lo + +/-- Post-quantum (Model Q2, depth-bounded NIST `MAXDEPTH = 2^d`) interactive bit-security +for a classical RBR soundness term `b`: +`max(½(b - log₂ C₁), b - log₂ C₁ - d)` (parallel Grover search capped at circuit depth `2^d`). -/ +def q2InteractiveBits (classicalBits c1 : Float) (maxDepthBits : Nat) : Float := + let cBits := log2 (max c1 1.0) + max 0.0 (max ((classicalBits - cBits) / 2.0) (classicalBits - cBits - nat maxDepthBits)) + +/-- Post-quantum (Model Q2, CNS17 non-qRAM) hash collision bit-security: +`⅖ · stateBits` from `Q⁵ / 2^{2 · stateBits} ≤ 1` (`102.4b` for 256b state, `204.8b` for 512b). -/ +def q2CnsCollisionBits (stateBits : Nat) : Float := + (2.0 / 5.0) * nat stateBits + +/-- Convert a classical `Regime` into a Model Q1 (unbounded-depth QROM) `Regime`, +replacing each interactive term `b` with `q1InteractiveBits b c1` and `collision` +with `q1CollisionBits stateBits c2`, plus an explicit `combined` term solving +`C₁·N²·ε_max + C₂·N³ / 2^{stateBits} = 1`. -/ +def Regime.toQ1 (r : Regime) (prefixLabel : String) (stateBits : Nat) (c1 c2 : Float) : Regime := + let iopClassical := r.iopLimit.2 + let colQ1 := q1CollisionBits stateBits c2 + let combined := q1CombinedBits iopClassical stateBits c1 c2 + let mapped := r.terms.map fun (t, b) => + if t == "collision" then ("collision(BHT)", colQ1) + else (t, q1InteractiveBits b c1) + { name := s!"{prefixLabel} {r.name}" + terms := mapped.push ("combined", combined) } + +/-- Convert a classical `Regime` into a Model Q2 (CNS17 non-qRAM + NIST `MAXDEPTH`) `Regime`. -/ +def Regime.toQ2 (r : Regime) (prefixLabel : String) (stateBits : Nat) + (c1 : Float) (maxDepthBits : Nat) : Regime := + let colQ2 := q2CnsCollisionBits stateBits + let mapped := r.terms.map fun (t, b) => + if t == "collision" then ("collision(CNS)", colQ2) + else (t, q2InteractiveBits b c1 maxDepthBits) + { name := s!"{prefixLabel} {r.name}" + terms := mapped } + +/-- Every post-quantum regime (Model Q1 unbounded-depth QROM and Model Q2 CNS+MAXDEPTH) +for `inst` under `p`. -/ +def pqTerms (inst : Instance) (p : Parameters) : Array Regime := Id.run do + let classical := terms inst p + let stateBits := p.effectiveHashStateBits + let c1 := p.qromC1 + let c2 := p.qromC2 + let dMax := p.maxDepthBits + let mut out : Array Regime := #[] + for r in classical do + if r.name == "CertiFRI proven UD" || + r.name.startsWith "CertiFRI proven Johnson" || + r.name.startsWith "Johnson, BCHKS25" || + r.name.startsWith "Johnson, DKT26" || + r.name.startsWith "conjectured" then + out := out.push (r.toQ1 "QROM-Q1" stateBits c1 c2) + for r in classical do + if r.name.startsWith "CertiFRI proven Johnson" || + r.name.startsWith "Johnson, BCHKS25" then + out := out.push (r.toQ2 s!"Model-Q2(CNS,D=2^{dMax})" stateBits c1 dMax) + return out + +/-- One parameter set's post-quantum report (Model Q1 QROM and Model Q2 CNS+MAXDEPTH). -/ +def pqReport (source : String) (inst : Instance) (p : Parameters) : String := Id.run do + let ellMin := inst.effectiveMinLogTrace + let stateBits := p.effectiveHashStateBits + let tensorDetail := match inst.effectiveKCol, inst.effectiveKOpen with + | some kc, some ko => s!"kCol+kOpen = {kc + ko} (kCol={kc}, kOpen={ko})" + | _, _ => s!"kTensor = {inst.effectiveTensorChallenges} (from claimRefs)" + let mut lines := #[ + s!"[PQ] key: {source}, proto v{p.protocolVersion}, ext Fp^{p.extensionDegree} ({fmt (fieldBitsFor p.extensionDegree)}b), " ++ + s!"batching {p.effectiveBatching.label}, pinning {p.stage1Pinning}, " ++ + s!"digest {p.digestBytes}B (internal state {stateBits}b), blowup 2^{p.logBlowup}, " ++ + s!"{p.queries} queries, query pow {p.queryPow}, commit pow {p.commitPow}, arity 2^{p.logArity}", + s!"[PQ] QROM constants: C1={fmt p.qromC1} (Q²·ε_rbr), C2={fmt p.qromC2} (Q³/2^{stateBits}), " ++ + s!"Model-Q2 MAXDEPTH=2^{p.maxDepthBits}", + s!"[PQ] instance: trace 2^{inst.logTrace} (min trace 2^{ellMin}), {inst.columns} batched columns " ++ + s!"({inst.effectiveClaimRefs} FRI claim refs), {inst.constraints} constraints, " ++ + s!"max degree {inst.maxDegree} (quotient {inst.effectiveQuotient}), " ++ + s!"lookup rows {inst.lookupRows}, lookup width {inst.lookupWidth}; " ++ + s!"{tensorDetail}, tensorCapOk = {tensorCapOk inst p}"] + for r in pqTerms inst p do + let (name, bits) := r.limit + let detail := " ".intercalate (r.terms.toList.map fun (t, b) => s!"{t} {fmt b}") + lines := lines.push s!" {r.name}: {fmt bits} bits PQ (limited by {name}) {detail}" + return "\n".intercalate lines.toList + +/-- Self-test verifying Phase 0 invariants: +1. Baseline `P0` (`Fp^3`, 32B BLAKE3-256, `(2,128,0,20)`) lands in ~65–71b Q1 PQ on representative IxVM scale. +2. `BLAKE3-XOF48` (`digestBytes=48`, default `stateBits=256`) still caps at `< 86b` BHT. +3. Candidate `P3` (`Fp^5`, 64B BLAKE2b-512, Stage-1 pinning, `(2,246,0,28)`) clears `≥ 128b` Q1 PQ across BCHKS25 & DKT26. -/ +def pqSelfTest : Except String String := do + let ixvmInst : Instance := { + logTrace := 23, columns := 22663, constraints := 49086, maxDegree := 5, + lookupRows := 32372164352, lookupWidth := 140, minLogTrace := some 8, + claimRefs := some 43508, maxQuotient := some 4, maxWidth := some 2382, + maxOpeningsPerHeight := some 1600 } + let p0 : Parameters := { + logBlowup := 2, queries := 128, queryPow := 20, commitPow := 0, logArity := 1, + extensionDegree := 3, digestBytes := 32, protocolVersion := 6, + qromC1 := 1.0, qromC2 := 1.0 } + let p0Bchks := ((pqTerms ixvmInst p0).find? (·.name.startsWith "QROM-Q1 Johnson, BCHKS25")).get! + let p0Bits := p0Bchks.limit.2 + if !(67.0 ≤ p0Bits && p0Bits ≤ 72.0) then + throw s!"P0 BCHKS25 Q1 expected in [67, 72], got {fmt p0Bits}" + let xof48 : Parameters := { p0 with digestBytes := 48 } + let xofCol := q1CollisionBits xof48.effectiveHashStateBits 1.0 + if !(xofCol < 86.0) then + throw s!"BLAKE3-XOF48 BHT collision expected < 86b, got {fmt xofCol}" + let p3 : Parameters := { + logBlowup := 2, queries := 246, queryPow := 28, commitPow := 0, logArity := 1, + extensionDegree := 5, digestBytes := 64, protocolVersion := 7, + stage1Pinning := true, qromC1 := 4.0, qromC2 := 27.0 } + let p3Bchks := ((pqTerms ixvmInst p3).find? (·.name.startsWith "QROM-Q1 Johnson, BCHKS25")).get! + let p3Bits := p3Bchks.limit.2 + if !(p3Bits ≥ 128.0) then + throw s!"P3 BCHKS25 Q1 expected ≥ 128b, got {fmt p3Bits} (limited by {p3Bchks.limit.1})" + let p3Cert := ((pqTerms ixvmInst p3).find? (·.name.startsWith "QROM-Q1 CertiFRI proven Johnson")).get! + return s!"pqSelfTest PASS: P0(C1=1)={fmt p0Bits}b, XOF48_BHT={fmt xofCol}b, " ++ + s!"P3(C1=4,C2=27) BCHKS25={fmt p3Bits}b, CertiFRI_Johnson={fmt p3Cert.limit.2}b (lim={p3Cert.limit.1})" + /-- Security regime targeted by `--require-min-bits` / `--regime`. -/ inductive RegimeKind where | proven diff --git a/Ix/Aiur/Parameters.lean b/Ix/Aiur/Parameters.lean index 37031060a7..1fe2df395b 100644 --- a/Ix/Aiur/Parameters.lean +++ b/Ix/Aiur/Parameters.lean @@ -146,6 +146,11 @@ def extensionDegreeV6 : Nat := 3 /-- Protocol version tag for the `v6` `Fp^3` + BLAKE3 `derive_key` profile. -/ def protocolVersionV6 : Nat := 6 +/-- Stage-1 pinning flag required for production Release 0.5 Protocol `v6` keys +(`1` = enabled, pinning stage-1 & active preprocessed columns at `z0` before +sampling lookup challenges `beta`, `gamma`). -/ +def stage1PinningV6 : Nat := 1 + /-- Target provable security floor (in bits) for the `v6` 128-bit profile. -/ def minProvableSecurityBits128 : Nat := 128 diff --git a/Ix/Cert/Aggr/FixedIxvmKey.lean b/Ix/Cert/Aggr/FixedIxvmKey.lean index 4eb919e3ab..10dbe21061 100644 --- a/Ix/Cert/Aggr/FixedIxvmKey.lean +++ b/Ix/Cert/Aggr/FixedIxvmKey.lean @@ -494,7 +494,9 @@ theorem parseIxvmKey_invariants {bytes : ByteArray} {pk : ParsedIxvmKey} obtain ⟨⟨_, q5⟩, _, hq5⟩ := except_bind_ok' hq4 obtain ⟨⟨_, q6⟩, _, hq6⟩ := except_bind_ok' hq5 obtain ⟨⟨_, q7⟩, _, hq7⟩ := except_bind_ok' hq6 - obtain ⟨⟨n, q8⟩, _, hq8⟩ := except_bind_ok' hq7 + obtain ⟨⟨_, q7b⟩, _, hq7b⟩ := except_bind_ok' hq7 + obtain ⟨_, hq7c⟩ := except_unless_bool_ok hq7b + obtain ⟨⟨n, q8⟩, _, hq8⟩ := except_bind_ok' hq7c obtain ⟨⟨circuits, q9⟩, hcircs, hq9⟩ := except_bind_ok' hq8 obtain ⟨⟨commit, q10⟩, hcom, hq10⟩ := except_bind_ok' hq9 obtain ⟨⟨indices, q11⟩, hidx, hq11⟩ := except_bind_ok' hq10 @@ -761,7 +763,7 @@ theorem flatTables_sizes (pk : ParsedIxvmKey) (digestBytes : ByteArray) : let tbl := FlatIxvmTables.ofParsed pk digestBytes tbl.circuits.size = pk.circuits.size ∧ tbl.circuitSpans.size = pk.circuits.size ∧ - tbl.tlimbs.size = 18 + 7 * pk.circuits.size ∧ + tbl.tlimbs.size = 19 + 7 * pk.circuits.size ∧ tbl.digestWords.size = 8 ∧ tbl.hasCommit = (if pk.preprocessedCommit.isSome then 1 else 0) ∧ tbl.prepCap.size = (if pk.preprocessedCommit.isSome then 4 else 0) := by @@ -772,7 +774,7 @@ theorem flatTables_sizes (pk : ParsedIxvmKey) (digestBytes : ByteArray) : have hlen : (zipCircuitsWithPrep pk.circuits.toList pk.preprocessedIndices.toList).length = pk.circuits.size := by rw [zipCircuitsWithPrep_length, Array.length_toList] - have htlimbs : (buildTlimbs pk).size = 18 + 7 * pk.circuits.size := by + have htlimbs : (buildTlimbs pk).size = 19 + 7 * pk.circuits.size := by unfold buildTlimbs have hflat : (pk.circuits.toList.flatMap circuitShapeLimbs).length = 7 * pk.circuits.size := by have hlen7 : ∀ cs : List SysCircuitData, (cs.flatMap circuitShapeLimbs).length = 7 * cs.length := by @@ -1542,7 +1544,7 @@ theorem tabledSys_eq_readSystem {vkBytes : ByteArray} {pk : ParsedIxvmKey} (∀ i : Fin 8, ((tbl.digestWords.getD i.val 0 : Nat) : Fp) = packDigest8 (Address.blake3Pure vkBytes) i) ∧ tbl.circuits.size = pk.circuits.size ∧ - tbl.tlimbs.size = 18 + 7 * pk.circuits.size ∧ + tbl.tlimbs.size = 19 + 7 * pk.circuits.size ∧ pk.preprocessedIndices.size = pk.circuits.size ∧ (∀ (ci : Nat) (hci : ci < pk.circuits.size), let c := pk.circuits[ci] diff --git a/Ix/Cert/Aggr/Shapes.lean b/Ix/Cert/Aggr/Shapes.lean index 134dbd6c59..95f568dae3 100644 --- a/Ix/Cert/Aggr/Shapes.lean +++ b/Ix/Cert/Aggr/Shapes.lean @@ -184,7 +184,7 @@ theorem aggregateSource_core_helpers_present : Any edit to any module in `MultiStark.aggregateSource` changes this digest and forces an explicit audit review. -/ def pinnedAggregateDigest : String := - "6f9f5bd75db2cd3b1ba23d5026b794e96c94caa2bb4b5ab0994745fb2a0926c9" + "25ff49a5b852f47f41e8c21a82dd9f550e7c497b94072eefac45795f65b985f8" theorem aggregateDigest_eq : MultiStark.aggregateDigest = pinnedAggregateDigest := rfl diff --git a/Ix/Cert/MultiStark/PinnedVerifier.lean b/Ix/Cert/MultiStark/PinnedVerifier.lean new file mode 100644 index 0000000000..f87e1900fe --- /dev/null +++ b/Ix/Cert/MultiStark/PinnedVerifier.lean @@ -0,0 +1,327 @@ +import CertiFriP3.VerifyBytes +import Ix.Aiur.Parameters + +/-! # Pure-Lean Pinned Protocol `v6` Multi-STARK Verifier (`Ix.Cert.MultiStark.PinnedVerifier`) + +Mathlib-free, zero-FFI byte-level verifier for **Release 0.5 pinned Protocol `v6`** +(`Goldilocks^3`, 32-byte `BLAKE3-256`, `FriBatching::Tensor`, `stage_1_pinning = 1`) batch proofs, +built directly on `CertiFri.Stark.Profile.verifyBytesPinned` (`CertiFriP3/VerifyBytes.lean`) and +supporting both: +- **Inner binary `v6`** (`maxLogArity = 1`, `logFinalPolyLen = 0`: IxVM, recursion, aggregation), and +- **Multi-arity 8-ary EP1** (`maxLogArity = 3`, `logFinalPolyLen = 8`: transparent `compact400KBBalanced` + and `compact400KBCompact`). + +Enforces Ix's full application-level preamble policy (`validate_preamble`) on the decoded verifying +key and batch messages (`CertiFri.P3.Wire.pinnedBatchMessagesOf`): +1. `stage_1_pinning == true` and `cap_height == 0`. +2. Parameter security floor: `Aiur.meetsSecurityFloor` for inner binary `v6` (`maxLogArity = 1`), + or concrete EP1 transparent 8-ary parameter floor (`logBlowup = 4`, `logFinalPolyLen = 8`, + `maxLogArity = 3`, `(numQueries ≥ 58 ∧ queryPowBits ≥ 28) ∨ (numQueries ≥ 55 ∧ queryPowBits ≥ 30)`) + for multi-arity keys (unless `allowBelowFloor = true` for toy fixtures). +3. `1 ≤ headers.size ≤ 2^16` (`MAX_BATCH_SHARDS`), per-circuit `lookups.size < 2^24` + (`MAX_CIRCUIT_LOOKUPS`), and strict zero-PoW witness admissibility (`powWitnessesAdmissible`). +4. `MEMSEG = 16` closure-pair validation (`checkClosurePairs`: paired `(-1, [16, w, a])`, + `(+1, [16, w, b])` with strict `a < b < p`, ascending non-overlapping intervals, declared ROM + widths, and `numPairs ≤ shards * romWidths.size`). +5. Exact Rust-parity `K`-lane logical row-weight accounting (`validateWeightedBatchRowsFull`: + `Σ (2^ld * weight(c)) ≤ 2^39` across `CALL`-pull vectorized chips and segmented/unsegmented + `` circuits). +6. Exact `CertiFri.Stark.Profile.verifyBytesPinned` verification (including active-preprocessed + circuit enforcement when `allowInactivePrep = false`, Tier-2 tensor challenge cap + `kCol + kOpen ≤ 32`, and exact claim + message binding). +-/ + +namespace Ix.Cert.MultiStark.PinnedVerifier + +open CertiFri CertiFri.Stark CertiFri.P3 CertiFri.P3.Wire + +/-- Maximum total weighted batch rows (`2^39`). -/ +def MAX_BATCH_ROWS : Nat := 1 <<< 39 + +/-- Maximum lookups per circuit (`< 2^24`). -/ +def MAX_CIRCUIT_LOOKUPS : Nat := 1 <<< 24 + +/-- Maximum shard count (`1 ≤ shards ≤ 2^16`). -/ +def MAX_BATCH_SHARDS : Nat := 1 <<< 16 + +/-- Maximum number of `MEMSEG = 16` closure pairs (`2^16` pairs). -/ +def MAX_CLOSURE_PAIRS : Nat := 1 <<< 16 + +/-- Maximum claims per shard admitted in the runtime profile bounds. -/ +def MAX_SHARD_CLAIMS : Nat := 1 <<< 24 + +/-- Maximum length of a single claim or message in the runtime profile bounds. -/ +def MAX_ITEM_LEN : Nat := 1 <<< 16 + +/-- Aiur LogUp `CALL` channel tag. -/ +def CALL_CHANNEL : Nat := 1 + +/-- Aiur LogUp `ROM` channel tag. -/ +def ROM_CHANNEL : Nat := 2 + +/-- Aiur LogUp `MEMSEG` channel tag. -/ +def MEMSEG_CHANNEL : Nat := 16 + +/-- `C6` vectorized ROM lane schedule: 8 lanes for `w ≤ 4`, 4 lanes for `5 ≤ w ≤ 12`, 1 otherwise. -/ +def romLanes (w : Nat) : Nat := + if w ≤ 4 then 8 + else if w ≤ 12 then 4 + else 1 + +/-- Extract the `MEMSEG = 16` ROM payload width from a circuit, if present. -/ +def circuitMemsegWidth? (c : KeyCircuit) : Option Nat := Id.run do + for lk in c.graph.lookups do + if lk.args.size == 3 then + match lk.args[0]?, lk.args[1]? with + | some tagId, some wId => + match c.graph.nodes[tagId]?, c.graph.nodes[wId]? with + | some (Node.const tagVal), some (Node.const wVal) => + if tagVal.val.toNat == MEMSEG_CHANNEL then + return some wVal.val.toNat + | _, _ => pure () + | _, _ => pure () + return none + +/-- Extract the ROM payload width from a `` circuit, either segmented (`MEMSEG = 16`) +or unsegmented (`ROM = 2`). Exact parity with `crates/aiur/src/trace/stark/batch.rs`. -/ +def circuitRomWidthFull? (c : KeyCircuit) : Option Nat := + match circuitMemsegWidth? c with + | some w => some w + | none => + if c.preprocessedHeight != 0 || c.graph.lookups.isEmpty then none + else Id.run do + let mut romWidth : Option Nat := none + for lk in c.graph.lookups do + match c.graph.nodes[lk.multiplicity]? with + | some (Node.neg _) => pure () + | _ => return none + if lk.args.size < 3 then return none + let some a0 := lk.args[0]? | return none + let some a1 := lk.args[1]? | return none + match c.graph.nodes[a0]?, c.graph.nodes[a1]? with + | some (Node.const ch), some (Node.const wVal) => + if ch.val.toNat != ROM_CHANNEL then return none + let w := wVal.val.toNat + if w + 3 != lk.args.size then return none + match romWidth with + | none => romWidth := some w + | some prev => if prev != w then return none + | _, _ => return none + return romWidth + +/-- True iff `lk` is a `CALL`-channel receive pull: multiplicity is `Neg (Var Main Current _)` +and `args[0]` is `Const CALL_CHANNEL`. -/ +def isCallPullLookup (c : KeyCircuit) (lk : Lookup) : Bool := + let multOk := match c.graph.nodes[lk.multiplicity]? with + | some (Node.neg inner) => + match c.graph.nodes[inner]? with + | some (Node.var col) => col.source == .main && !col.next + | _ => false + | _ => false + let chOk := match lk.args[0]? with + | some a0 => + match c.graph.nodes[a0]? with + | some (Node.const tag) => tag.val.toNat == CALL_CHANNEL + | _ => false + | none => false + multOk && chOk + +/-- Logical entry weight per row of `c` for `MAX_BATCH_ROWS` (`2^39`) accounting. -/ +def circuitRowWeightFull (c : KeyCircuit) : Nat := + if c.preprocessedHeight != 0 then 1 + else + match circuitRomWidthFull? c with + | some w => + let k := romLanes w + let expectedLookups := if (circuitMemsegWidth? c).isSome then k + 2 else k + if decide (k > 1) && (c.graph.lookups.size == expectedLookups) && + (c.mainWidth == 1 + k * (w + 2)) then k + else 1 + | none => + let callPulls := c.graph.lookups.foldl (init := 0) fun acc lk => + if isCallPullLookup c lk then acc + 1 else acc + max callPulls 1 + +/-- Collect all distinct `MEMSEG = 16` ROM payload widths declared by `k.circuits`. -/ +def romWidthsOfKey (k : Key) : Array Nat := Id.run do + let mut out : Array Nat := #[] + for c in k.circuits do + if let some w := circuitMemsegWidth? c then + if !out.contains w then + out := out.push w + return out + +/-- Validate `MEMSEG = 16` closure pairs on batch messages. -/ +def checkClosurePairs (messages : Array (BatchMessage Goldilocks)) : Bool := + if messages.size % 2 != 0 || messages.size > 2 * MAX_CLOSURE_PAIRS then false + else + let numPairs := messages.size / 2 + Id.run do + let mut prevW : Nat := 0 + let mut prevB : Nat := 0 + let mut hasPrev := false + for i in [0:numPairs] do + let some pull := messages[2 * i]? | return false + let some push := messages[2 * i + 1]? | return false + if pull.multiplicity.add Goldilocks.one != Goldilocks.zero then return false + if push.multiplicity != Goldilocks.one then return false + if pull.args.size != 3 || push.args.size != 3 then return false + let some pullCh := pull.args[0]? | return false + let some pushCh := push.args[0]? | return false + if pullCh.val.toNat != MEMSEG_CHANNEL || pushCh.val.toNat != MEMSEG_CHANNEL then + return false + let some pullW := pull.args[1]? | return false + let some pushW := push.args[1]? | return false + let w := pullW.val.toNat + if pushW.val.toNat != w then return false + let some pullA := pull.args[2]? | return false + let some pushB := push.args[2]? | return false + let a := pullA.val.toNat + let b := pushB.val.toNat + if a ≥ b then return false + if hasPrev then + if w < prevW then return false + if w == prevW && a < prevB then return false + prevW := w + prevB := b + hasPrev := true + return true + +/-- Check whether `p` satisfies the Release 0.5 security floor: +- For binary inner `v6` (`maxLogArity = 1`, `logFinalPolyLen = 0`): `Aiur.meetsSecurityFloor`. +- For multi-arity 8-ary EP1 (`maxLogArity = 3`, `logFinalPolyLen = 8`): `logBlowup = 4`, + `capHeight = 0`, `commitPowBits ≤ 32`, `queryPowBits ≤ 32`, and either balanced + `(numQueries ≥ 58, queryPowBits ≥ 28)` or compact `(numQueries ≥ 55, queryPowBits ≥ 30)`. -/ +def checkParamsFloor (p : KeyParams) (allowBelowFloor : Bool := false) : Bool := + if !p.stage1Pinning || p.capHeight != 0 || p.logBlowup < 1 || p.numQueries < 1 then + false + else if allowBelowFloor then + true + else if p.maxLogArity == 1 && p.logFinalPolyLen == 0 then + Aiur.meetsSecurityFloor + ⟨p.logBlowup, p.capHeight⟩ + ⟨p.logFinalPolyLen, p.maxLogArity, p.numQueries, p.commitPowBits, p.queryPowBits⟩ + else if p.maxLogArity == 3 && p.logFinalPolyLen == 8 && p.logBlowup == 4 then + p.commitPowBits ≤ 32 && p.queryPowBits ≤ 32 && + ((p.numQueries ≥ 58 && p.queryPowBits ≥ 28) || + (p.numQueries ≥ 55 && p.queryPowBits ≥ 30)) + else + false + +/-- Strict zero-PoW witness admissibility matching `multi-stark`: whenever `commitPowBits == 0`, +every commit PoW witness must be `0`, and whenever `queryPowBits == 0`, `queryPowWitness` must be `0`. -/ +def powWitnessesAdmissible (p : KeyParams) (pb : PinnedBatch) : Bool := + pb.batch.proofs.all fun sp => + (p.commitPowBits != 0 || sp.openingProof.commitPowWitnesses.all (· == Goldilocks.zero)) && + (p.queryPowBits != 0 || sp.openingProof.queryPowWitness == Goldilocks.zero) + +/-- Enforce `validate_preamble` policy on `(key, pb)`: shard count, per-circuit lookup bound, +`MEMSEG = 16` closure pairs & ROM widths, `K`-lane weighted batch row bound `≤ 2^39`, and +strict zero-PoW witness admissibility. -/ +def validateIxPreamble (key : Key) (pb : PinnedBatch) (allowBelowFloor : Bool := false) : Bool := + let headers := pb.batch.preamble.headers + let messages := pb.batch.preamble.messages + if !checkParamsFloor key.params allowBelowFloor then false + else if !key.circuits.all (fun c => decide (c.graph.lookups.size < MAX_CIRCUIT_LOOKUPS)) then false + else if headers.size == 0 || headers.size > MAX_BATCH_SHARDS then false + else if pb.batch.proofs.size != headers.size then false + else if !checkClosurePairs messages then false + else if !powWitnessesAdmissible key.params pb then false + else Id.run do + let romWidths := romWidthsOfKey key + let numPairs := messages.size / 2 + if numPairs > headers.size * romWidths.size then return false + for i in [0:numPairs] do + let some pull := messages[2 * i]? | return false + let some wVal := pull.args[1]? | return false + if !romWidths.contains wVal.val.toNat then return false + let mut totalRows : Nat := 0 + for h in headers do + if h.active.size != key.circuits.size then return false + let mut degPos : Nat := 0 + for ci in [0:key.circuits.size] do + let some act := h.active[ci]? | return false + let some c := key.circuits[ci]? | return false + if act then + let some ld := h.logDegrees[degPos]? | return false + degPos := degPos + 1 + if ld + key.params.logBlowup > 32 then return false + totalRows := totalRows + (1 <<< ld) * circuitRowWeightFull c + if totalRows > MAX_BATCH_ROWS then return false + if degPos != h.logDegrees.size then return false + return true + +/-- Tier-2 tensor challenge cap (`kCol + kOpen ≤ 32`) for a pinned shard proof (with 3-point +openings on main and active preprocessed traces). -/ +def shardTensorChallengeCapOkPinned (key : Key) (sp : CertiFri.P3.Wire.ShardProof) : Bool := + match key.toPinnedSystem with + | none => false + | some sys => + let active := activeIndices sp.active + let s1 := active.zipIdx.map fun (ci, pos) => + let c := sys.circuits.getD ci default + { logDegree := sp.logDegrees.getD pos 0, width := c.mainWidth, numPoints := 3 } + let s2 := active.zipIdx.map fun (ci, pos) => + let c := sys.circuits.getD ci default + { logDegree := sp.logDegrees.getD pos 0, width := c.stage2Width, numPoints := 2 } + let q := active.zipIdx.map fun (ci, pos) => + let c := sys.circuits.getD ci default + { logDegree := sp.logDegrees.getD pos 0, width := 3 * c.quotientDegree, numPoints := 1 } + let base : Fri.ClaimShape := [s1, s2, q] + let shape := match sys.preprocessedCommit with + | none => base + | some _ => + let prep := (List.range sys.circuits.size).filterMap fun ci => + if (sys.preprocessedIndices.getD ci none).isNone then none + else + let c := sys.circuits.getD ci default + match active.idxOf? ci with + | some pos => + some { logDegree := sp.logDegrees.getD pos 0, width := c.preprocessedWidth, numPoints := 3 } + | none => + some { logDegree := Nat.log2 c.preprocessedHeight, width := c.preprocessedWidth, numPoints := 1 } + base ++ [prep] + let kCol := Fri.tensorNumChallenges (Fri.maxWidth shape) + let kOpen := Fri.tensorNumChallenges (Fri.maxOpeningsPerHeight sys.fri.logBlowup shape) + decide (kCol + kOpen ≤ 32) + +/-- Build the `CertiFri.Stark.Profile` corresponding to a decoded pinned `Key`. -/ +def runtimeProfile (key : Key) (allowInactivePrep : Bool := false) : Profile where + fri := key.params.toFriParams + bounds := { + shards := MAX_BATCH_SHARDS + claims := MAX_SHARD_CLAIMS + messages := 2 * MAX_CLOSURE_PAIRS + len := MAX_ITEM_LEN + rows := MAX_BATCH_ROWS + lookupRows := MAX_BATCH_ROWS * MAX_CIRCUIT_LOOKUPS + } + listSize := 1 + zk := false + rejectInactivePreprocessed := !allowInactivePrep + stage1Pinning := true + statementChecks := false + +/-- **End-to-end pure-Lean pinned Protocol `v6` byte verifier** built directly on +`CertiFri.Stark.Profile.verifyBytesPinned` plus Ix's `validate_preamble` policy on +`CertiFri.P3.Wire.pinnedBatchMessagesOf`. Supports both inner binary `v6` and multi-arity +8-ary EP1 proofs with zero Mathlib and zero Rust FFI. -/ +def verifyBytesPinnedIx (vkBytes claimsBytes proofBytes : ByteArray) + (allowBelowFloor : Bool := false) (allowInactivePrep : Bool := false) : Bool := + match decodeKey vkBytes, decodeBatchPinned proofBytes, pinnedBatchMessagesOf proofBytes with + | some key, some pb, some msgs => + if !validateIxPreamble key pb allowBelowFloor then false + else if !pb.batch.proofs.all (shardTensorChallengeCapOkPinned key) then false + else + let profile := runtimeProfile key allowInactivePrep + let messagesBytes := encodeMessages msgs + profile.verifyBytesPinned vkBytes claimsBytes messagesBytes proofBytes + | _, _, _ => false + +/-- Production byte-level pinned Protocol `v6` verifier (strictly enforcing the Release 0.5 +security floor, `stage_1_pinning = 1`, active preprocessed circuits, `MEMSEG = 16` closure pairs, +`K`-lane `2^39` weighted row bound, and `CertiFri.Stark.Profile.verifyBytesPinned`). -/ +def verifyBytesPinnedProduction (vkBytes claimsBytes proofBytes : ByteArray) : Bool := + verifyBytesPinnedIx vkBytes claimsBytes proofBytes false false + +end Ix.Cert.MultiStark.PinnedVerifier diff --git a/Ix/Cert/MultiStark/PrunedSoundness.lean b/Ix/Cert/MultiStark/PrunedSoundness.lean index 19f27aac76..5839c0fa73 100644 --- a/Ix/Cert/MultiStark/PrunedSoundness.lean +++ b/Ix/Cert/MultiStark/PrunedSoundness.lean @@ -1,6 +1,7 @@ import CertiFriP3.Pruned import CertiFriProofs.Exec.Extract import CertiFriProofs.Exec.SoundnessUnconditional +import CertiFriProofs.Exec.Stark.PrunedTensor import CertiFriProofs.Theory.Compiled.SoundnessView import CertiFriProofs.Theory.Oracle.MerkleVerify import Ix.Cert.MultiStark.FieldModel @@ -997,7 +998,8 @@ noncomputable def unpruneAndVerifyM let dims := P.commitDims i let indices := Array.ofFn fun k : Fin P.queries => index k >>> (i + 1) let rows := Array.ofFn fun k : Fin P.queries => - #[#[(P.commitRow basePf (msg 0) α β (index k) k i).1, + #[Compiled.encRow m.leafEnc + #[(P.commitRow basePf (msg 0) α β (index k) k i).1, (P.commitRow basePf (msg 0) α β (index k) k i).2]] let pproof : PrunedPaths D := match a.proof.commitPhaseOpenings[i]? with @@ -1183,7 +1185,8 @@ theorem run_unpruneAndVerifyM_of_acceptsPruned (Array.ofFn fun k : Fin P.queries => P.indexOf (PcsRbr.queriesOf (PcsRbr.ungrind t) k) >>> (i + 1)) (Array.ofFn fun k : Fin P.queries => - #[#[(P.commitRow (baseModelProof m params shape a) + #[Compiled.encRow m.leafEnc + #[(P.commitRow (baseModelProof m params shape a) (Exec.view m params shape (Compiled.msgAt (PcsRbr.ungrind t) 0)) (PcsRbr.alphaOf (PcsRbr.ungrind t)) (PcsRbr.betasOf (PcsRbr.ungrind t)) (P.indexOf (PcsRbr.queriesOf (PcsRbr.ungrind t) k)) k i).1, @@ -1208,9 +1211,10 @@ theorem run_unpruneAndVerifyM_of_acceptsPruned (Array.ofFn (n := params.numQueries) fun k => #[#[((Exec.queryResult (F := F) params shape a.points a.values a.proof ch k.val).rows.getD i (0, 0)).1, ((Exec.queryResult (F := F) params shape a.points a.values a.proof ch k.val).rows.getD i (0, 0)).2]]).map - (fun r => r.map fun row => row.map m.ext.toModel) = + (fun r => r.map fun row => Compiled.encRow m.leafEnc (row.map m.ext.toModel)) = Array.ofFn fun k : Fin P.queries => - #[#[(P.commitRow (baseModelProof m params shape a) + #[Compiled.encRow m.leafEnc + #[(P.commitRow (baseModelProof m params shape a) (Exec.view m params shape (Compiled.msgAt (PcsRbr.ungrind t) 0)) (PcsRbr.alphaOf (PcsRbr.ungrind t)) (PcsRbr.betasOf (PcsRbr.ungrind t)) (P.indexOf (PcsRbr.queriesOf (PcsRbr.ungrind t) k)) k i).1, @@ -1218,7 +1222,7 @@ theorem run_unpruneAndVerifyM_of_acceptsPruned (Exec.view m params shape (Compiled.msgAt (PcsRbr.ungrind t) 0)) (PcsRbr.alphaOf (PcsRbr.ungrind t)) (PcsRbr.betasOf (PcsRbr.ungrind t)) (P.indexOf (PcsRbr.queriesOf (PcsRbr.ungrind t) k)) k i).2]] := by - rw [Exec.Checks.map_ofFn_pair] + rw [Exec.Checks.map_ofFn_pair_enc] congr 1; funext k have hqr := Exec.rows_queryResult m params shape wf hshape0 hag0 k hi rw [withPaths_queryResult] at hqr @@ -1231,7 +1235,8 @@ theorem run_unpruneAndVerifyM_of_acceptsPruned (Array.ofFn fun k : Fin P.queries => P.indexOf (PcsRbr.queriesOf (PcsRbr.ungrind t) k) >>> (i + 1)) (Array.ofFn fun k : Fin P.queries => - #[#[(P.commitRow (baseModelProof m params shape a) + #[Compiled.encRow m.leafEnc + #[(P.commitRow (baseModelProof m params shape a) (Exec.view m params shape (Compiled.msgAt (PcsRbr.ungrind t) 0)) (PcsRbr.alphaOf (PcsRbr.ungrind t)) (PcsRbr.betasOf (PcsRbr.ungrind t)) (P.indexOf (PcsRbr.queriesOf (PcsRbr.ungrind t) k)) k i).1, @@ -1246,9 +1251,12 @@ theorem run_unpruneAndVerifyM_of_acceptsPruned (Array.ofFn (n := params.numQueries) fun k => ch.indices.getD k.val 0 >>> (i + 1)) := by congr 1; funext k; rw [hag0.index k] - rw [← hrowsEq, hidx_eq] + have hdims : P.commitDims i = (#[⟨2, Fri.logMaxHeight params.logBlowup shape - i - 1⟩]).map + (Exec.scaleWidth m.leafWidth) := by + simpa [P, Exec.modelParams] using Exec.Checks.commitDims_modelParams m params shape wf i + rw [← hrowsEq, hidx_eq, hdims] simp only [Exec.Checks.getD_map_ofFn] at hrest - exact (restorePaths_map m.ext.toModel H (P.commitDims i) _ _ o.openingProof).symm.trans hrest + exact (CertiFri.Exec.Stark.restorePaths_friHasher m H _ _ _ o.openingProof).symm.trans hrest have hver' : Merkle.verifyOpenings (Exec.friHasher m H) root #[⟨2, P.n - i - 1⟩] (Array.ofFn (n := params.numQueries) fun k => ch.indices.getD k.val 0 >>> (i + 1)) (Array.ofFn (n := params.numQueries) fun k => @@ -1304,7 +1312,8 @@ theorem run_unpruneAndVerifyM_of_acceptsPruned (Array.ofFn fun k : Fin P.queries => P.indexOf (PcsRbr.queriesOf (PcsRbr.ungrind t) k) >>> (i + 1)) (Array.ofFn fun k : Fin P.queries => - #[#[(P.commitRow (baseModelProof m params shape a) + #[Compiled.encRow m.leafEnc + #[(P.commitRow (baseModelProof m params shape a) (Exec.view m params shape (Compiled.msgAt (PcsRbr.ungrind t) 0)) (PcsRbr.alphaOf (PcsRbr.ungrind t)) (PcsRbr.betasOf (PcsRbr.ungrind t)) (P.indexOf (PcsRbr.queriesOf (PcsRbr.ungrind t) k)) k i).1, @@ -1331,7 +1340,8 @@ theorem run_unpruneAndVerifyM_of_acceptsPruned (Array.ofFn fun k : Fin P.queries => P.indexOf (PcsRbr.queriesOf (PcsRbr.ungrind t) k) >>> (i.val + 1)) (Array.ofFn fun k : Fin P.queries => - #[#[(P.commitRow (baseModelProof m params shape a) + #[Compiled.encRow m.leafEnc + #[(P.commitRow (baseModelProof m params shape a) (Exec.view m params shape (Compiled.msgAt (PcsRbr.ungrind t) 0)) (PcsRbr.alphaOf (PcsRbr.ungrind t)) (PcsRbr.betasOf (PcsRbr.ungrind t)) (P.indexOf (PcsRbr.queriesOf (PcsRbr.ungrind t) k)) k i.val).1, diff --git a/Ix/Cert/MultiStark/StarkKey.lean b/Ix/Cert/MultiStark/StarkKey.lean index c15cefe068..473c441f76 100644 --- a/Ix/Cert/MultiStark/StarkKey.lean +++ b/Ix/Cert/MultiStark/StarkKey.lean @@ -157,6 +157,7 @@ structure StarkParams where numQueries : Nat commitPowBits : Nat queryPowBits : Nat + stage1Pinning : Nat := 1 deriving DecidableEq, Repr, Inhabited def StarkParams.toCommitment (p : StarkParams) : Aiur.CommitmentParameters := @@ -673,14 +674,19 @@ def readStarkSystemRaw : DecodeM StarkSystem := do unless friBatching == 1 do throw s!"vk: unsupported fri_batching {friBatching}: Tensor (1) required" let vkDigest ← readBytes 32 + let logBlowup ← readU16LE + let capHeight ← readU16LE + let logFinalPolyLen ← readU16LE + let maxLogArity ← readU16LE + let numQueries ← readU16LE + let commitPowBits ← readU16LE + let queryPowBits ← readU16LE + let stage1Pinning ← readU16LE + unless stage1Pinning == 0 || stage1Pinning == 1 do + throw s!"vk: invalid stage_1_pinning flag {stage1Pinning}: expected 0 or 1" let params : StarkParams := { - logBlowup := ← readU16LE - capHeight := ← readU16LE - logFinalPolyLen := ← readU16LE - maxLogArity := ← readU16LE - numQueries := ← readU16LE - commitPowBits := ← readU16LE - queryPowBits := ← readU16LE + logBlowup, capHeight, logFinalPolyLen, maxLogArity, + numQueries, commitPowBits, queryPowBits, stage1Pinning } let circuitCount ← readU16LE let circuits ← readArray circuitCount readSysCircuit @@ -813,6 +819,8 @@ def checkSecurityFloor (p : StarkParams) : Except String Unit := do /-- Validate all structural and security-floor invariants of a decoded `StarkSystem`. -/ def validateSystem (sys : StarkSystem) : Except String Unit := do + unless sys.params.stage1Pinning == 1 do + throw s!"vk: unsupported stage_1_pinning {sys.params.stage1Pinning}: production Protocol v6 keys require stage_1_pinning=1" checkSecurityFloor sys.params unless sys.params.commitPowBits ≤ MAX_PROOF_OF_WORK_BITS do throw s!"vk: commit proof of work of {sys.params.commitPowBits} bits exceeds {MAX_PROOF_OF_WORK_BITS}" @@ -912,6 +920,14 @@ theorem validateSystem_sound {sys : StarkSystem} (h : validateSystem sys = .ok ( sys.vkDigest = computeVkDigest sys.circuits ∧ ∀ c ∈ sys.circuits, c.Topological ∧ c.LookupsPlain ∧ c.quotientDegree ≤ 2 ^ sys.params.logBlowup := by unfold validateSystem at h + have hpin : (sys.params.stage1Pinning == 1) = true := by + cases hp : (sys.params.stage1Pinning == 1) with + | true => rfl + | false => + simp only [hp, Bool.false_eq_true, ↓reduceIte, throw, throwThe, MonadExceptOf.throw, + bind, Except.bind] at h + cases h + simp only [hpin, ↓reduceIte] at h obtain ⟨_, hfloor, h1⟩ := except_bind_ok h have hfl : Aiur.meetsSecurityFloor sys.params.toCommitment sys.params.toFri = true := by unfold checkSecurityFloor at hfloor @@ -992,7 +1008,7 @@ def pushU16LE (buf : ByteArray) (n : Nat) : ByteArray := /-- Construct a valid minimal Protocol `v6` verifying key with one constrained circuit (`main_width = 2`, `x * y - 1 = 0`, 1 lookup, `max_constraint_degree = 2`) and one preprocessed table circuit (`preprocessed_width = 1`, `preprocessed_height = 4`, ranked 0). -/ -def sampleValidV6Vk (numQueries : Nat := 128) : ByteArray := Id.run do +def sampleValidV6Vk (numQueries : Nat := 128) (stage1Pinning : Nat := 1) : ByteArray := Id.run do let c0 : SysCircuit := { mainWidth := 2 preprocessedWidth := 0 @@ -1034,6 +1050,7 @@ def sampleValidV6Vk (numQueries : Nat := 128) : ByteArray := Id.run do buf := pushU16LE buf numQueries -- num_queries buf := pushU16LE buf 0 -- commit_pow buf := pushU16LE buf 20 -- query_pow + buf := pushU16LE buf stage1Pinning -- stage_1_pinning buf := pushU16LE buf 2 -- circuit_count -- circuit 0 buf := pushU16LE buf 2 -- main_width @@ -1093,10 +1110,13 @@ def runSelfTests : Except String Unit := do let tamperedDigest := good.set! 6 (good.get! 6 ^^^ 0x01) if (validateV6 tamperedDigest).isOk then throw "accepted tampered vk_digest" - -- 4. Below Protocol v6 floor (v5 default 100 queries) must fail + -- 4. Below Protocol v6 floor (v5 default 100 queries) and unpinned (stage_1_pinning=0) must fail let belowFloor := sampleValidV6Vk 100 if (validateV6 belowFloor).isOk then throw "accepted below-floor numQueries = 100" + let unpinned := sampleValidV6Vk 128 0 + if (validateV6 unpinned).isOk then + throw "accepted unpinned stage_1_pinning = 0" -- 5. Trailing byte & truncated byte must fail if (validateV6 (good.push 0)).isOk then throw "accepted trailing byte" diff --git a/Ix/Cert/MultiStarkRefinement/ProgramPin.lean b/Ix/Cert/MultiStarkRefinement/ProgramPin.lean index a1d90c9266..de487ca4a3 100644 --- a/Ix/Cert/MultiStarkRefinement/ProgramPin.lean +++ b/Ix/Cert/MultiStarkRefinement/ProgramPin.lean @@ -287,8 +287,12 @@ def recursionCoreFunctions : List (String × String) := , ("Pcs", "fri_fold2") , ("Pcs", "ro_fold_1pt") , ("Pcs", "ro_fold_2pt") + , ("Pcs", "ro_fold_3pt") + , ("Pcs", "append_pin_rows") , ("Pcs", "bucket_update_1pt") , ("Pcs", "bucket_update_2pt") + , ("Pcs", "bucket_update_3pt") + , ("Pcs", "open_batch_3pt") , ("Pcs", "finalize_buckets") , ("Pcs", "pcs_fri_verify") , ("StarkVerifier", "ext_is_zero") @@ -314,6 +318,12 @@ def recursionCoreFunctions : List (String × String) := , ("StarkVerifier", "assert_closure_widths_loop") , ("StarkVerifier", "assert_closure_widths_ok") , ("StarkVerifier", "assert_u64s_zero") + , ("StarkVerifier", "assert_pinning_point_ok_loop") + , ("StarkVerifier", "assert_pinning_point_ok") + , ("StarkVerifier", "split_ext_n") + , ("StarkVerifier", "split_shard_pins") + , ("StarkVerifier", "assert_shard_pins_shape") + , ("StarkVerifier", "assert_batch_pins_shape") , ("StarkVerifier", "verify_shard") , ("StarkVerifier", "verify_shards") , ("StarkVerifier", "verify_batch") @@ -363,12 +373,13 @@ def entryRequiredCalls : List String := /-- Required calls inside `StarkVerifier::verify_batch`. -/ def verifyBatchRequiredCalls : List String := ["assert_shard_count_ok", "assert_batch_bounds", "assert_closure_pairs", - "assert_closure_widths_ok", "Transcript::batch_fiat_shamir", "messages_acc", - "verify_shards", "ext_is_zero", "batch_claims"] + "assert_closure_widths_ok", "assert_batch_pins_shape", "Transcript::batch_fiat_shamir", + "messages_acc", "verify_shards", "ext_is_zero", "batch_claims"] /-- Required calls inside `StarkVerifier::verify_shard`. -/ def verifyShardRequiredCalls : List String := ["UInt32::less_than_fields", "assert_u64s_zero", "UInt64::is_zero", + "assert_pinning_point_ok", "split_shard_pins", "Transcript::shard_fiat_shamir", "claims_acc", "ood_loop", "Pcs::pcs_fri_verify", "last_acc"] /-- Required calls inside `SystemDeserialize::read_sys_circuit` (structural fixed-table invariants: diff --git a/Ix/Cert/Release05/ClosureManifest.lean b/Ix/Cert/Release05/ClosureManifest.lean new file mode 100644 index 0000000000..0c7f2ac4f9 --- /dev/null +++ b/Ix/Cert/Release05/ClosureManifest.lean @@ -0,0 +1,79 @@ +import IxCK.Kernel.Audit.Axioms +import IxCK.Kernel.Audit.ClosureManifest +import Ix.Cert.Release05.SecurityAudit + +/-! # Definitional Closure Manifest of the Ix Release `0.5` Security Audit Stack + +Pins the kernel-level definitional closure of every positive classical ROM (`≥ 127.71b` ideal +sponge / keyed byte-level at `(3/4)/2^133`), unconditional 64-bit QROM (`≥ 64b` compressed-oracle +and Zhandry Lemma 5 standard-QRO), concrete Ix shape-ceiling discharge, and honest constructive +negative control in `Ix.Cert.Release05.SecurityAudit`. + +Also verifies via `#guard_module_axioms` that every safe declaration in +`Ix.Cert.Release05.SecurityAudit` depends solely on `[propext, Classical.choice, Quot.sound]`. + +Updating (only with a reviewed change to Release `0.5` security statements): build with +`IX_RELEASE05_CLOSURE_MANIFEST_WRITE=Tests/Fixtures/release-05-closure-manifest.txt`, +update `pinnedDigest` below with the reported SHA-256 digest, and commit both. +-/ + +#guard_module_axioms + Ix.Cert.Release05.SecurityAudit + +namespace Ix.Cert.Release05.ClosureManifest + +def roots : Array Lean.Name := #[ + ``Ix.Cert.Release05.release05_inner_default_ok, + ``Ix.Cert.Release05.release05_ep1_balanced_ok, + ``Ix.Cert.Release05.negControl_release05_rejects_unpinned, + ``Ix.Cert.Release05.negControl_release05_rejects_fp2, + ``Ix.Cert.Release05.negControl_release05_rejects_v5_default, + ``Ix.Cert.Release05.negControl_release05_rejects_deceptive_4_55_0, + ``Ix.Cert.Release05.posControl_release05_blake3_256_classical_127, + ``Ix.Cert.Release05.negControl_release05_blake3_256_below_128_classical, + ``Ix.Cert.Release05.negControl_release05_blake3_256_below_128_qrom, + ``Ix.Cert.Release05.negControl_release05_fp3_below_100_qrom, + ``Ix.Cert.Release05.posControl_release05_blake3_256_qrom64_headroom, + ``Ix.Cert.Release05.ixVm2p23_4096sh_balance_lt_p, + ``Ix.Cert.Release05.ixVm2p23_4096sh_hypotheses, + ``Ix.Cert.Release05.ixVm2p23_64sh_hypotheses, + ``Ix.Cert.Release05.aggr2p22_16sh_hypotheses, + ``Ix.Cert.Release05.rec2p22_1sh_hypotheses, + ``Ix.Cert.Release05.ep1V6Hop4_hypotheses, + ``Ix.Cert.Release05.ixVm2p23_64sh_qrom64, + ``Ix.Cert.Release05.ixVm2p23_64sh_qrom64_sub_one, + ``Ix.Cert.Release05.ixVm2p23_4096sh_qrom64, + ``Ix.Cert.Release05.ixVm2p23_4096sh_stdQro64, + ``Ix.Cert.Release05.aggr2p22_16sh_qrom64, + ``Ix.Cert.Release05.rec2p22_1sh_qrom64, + ``Ix.Cert.Release05.ep1V6Hop4_qrom64, + ``Ix.Cert.Release05.ep1V6Hop4_qrom64_sub_one, + ``Ix.Cert.Release05.ep1V6Hop4_stdQro64, + ``Ix.Cert.Release05.ixVm2p23_4096sh_classical_rom_133, + ``Ix.Cert.Release05.ep1V6Hop4_classical_rom_133, + ``CertiFri.P3.GoldilocksExt3.verifyBytesPinned_soundness_v6_553_keyed_133, + ``CertiFri.P3.GoldilocksExt3.verifyBytesPinned_soundness_v6_553_keyed_133_bounded, + ``CertiFri.P3.VerifyBytesPinnedMultiKeyed.verifyBytesPinned_soundness_ep1Balanced_keyed_checked, + ``CertiFri.P3.GoldilocksExt3.qrom64_verifyBatchTensorPinned_v6, + ``CertiFri.P3.GoldilocksExt3.qrom64_verifyBatchTensorPinned_v6_checked, + ``CertiFri.P3.GoldilocksExt3.stdQro64_verifyBatchTensorPinned_v6, + ``CertiFri.P3.GoldilocksExt3.qrom64_verifyBatchTensorMultiArityPinned_ep1, + ``CertiFri.P3.GoldilocksExt3.qrom64_verifyBatchTensorMultiArityPinned_ep1_checked, + ``CertiFri.P3.GoldilocksExt3.stdQro64_verifyBatchTensorMultiArityPinned_ep1 +] + +/-- The committed text of the manifest, relative to the repository root. -/ +def manifestPath : System.FilePath := "Tests/Fixtures/release-05-closure-manifest.txt" + +/-- The SHA-256 digest of the manifest's text (populated on first build with +`IX_RELEASE05_CLOSURE_MANIFEST_WRITE=Tests/Fixtures/release-05-closure-manifest.txt`). -/ +def pinnedDigest : String := "5152a1554cf081b5edda33f045767e7d21e6cd13a04c3fe2da25eec57b4a8dc7" + +open Lean Elab Command in +elab "#check_closure_manifest" : command => + Ix.Kernel.Audit.ClosureManifest.checkClosureManifest + roots manifestPath pinnedDigest "IX_RELEASE05_CLOSURE_MANIFEST_WRITE" + +#check_closure_manifest + +end Ix.Cert.Release05.ClosureManifest diff --git a/Ix/Cert/Release05/SecurityAudit.lean b/Ix/Cert/Release05/SecurityAudit.lean new file mode 100644 index 0000000000..c81adbb75f --- /dev/null +++ b/Ix/Cert/Release05/SecurityAudit.lean @@ -0,0 +1,887 @@ +import Ix.Aiur.Parameters +import CertiFriProofs.P3.GoldilocksExt3Qrom64 +import CertiFriProofs.P3.VerifyBytesPinnedMultiKeyed +import CertiFriProofs.Audit05Qrom64 + +/-! # Ix Release `0.5` Security Audit (`Ix.Cert.Release05.SecurityAudit`) + +Mechanically pins (via `#guard_msgs` on `#print axioms`) the Ix Release `0.5` classical and +post-quantum security stack for **shipped Protocol `v6` + Stage-1 Pinning** (`Goldilocks^3` + +32-byte `BLAKE3-256` + `FriBatching::Tensor` + `stage_1_pinning = 1`), and discharges every +concrete system-size, degree, tensor-challenge-cap, and LogUp integer-balance hypothesis +(`hC`, `hZ`, `hβ`, `hγ`, `hpin`, `hdeg`, `hk`, and `rowItemBound B < Goldilocks.order`) by pure +Lean kernel arithmetic (zero `native_decide`, zero `bv_decide`, zero `sorry`) across all five +concrete Ix production shapes: +- `ixvm-2p23` (247 circuits, `maxLogDegree ≤ 23`, 64 shards and up to **4,096 shards**) +- `aggr-2p22` (60 circuits, `maxLogDegree ≤ 22`, 16 shards) +- `rec-2p22` (53 circuits, `maxLogDegree ≤ 22`, 1 shard) +- `ep1-v6-hop4` (1 Plonkish circuit, `maxLogDegree ≤ 23`, 8-ary `compact400KBBalanced`) + +### Shipped Release `0.5` Cryptographic Specification +- **Base field:** Goldilocks `Fp`, `p = 2^64 - 2^32 + 1` (2-adicity `32`). +- **Extension field:** `Goldilocks^3 = Fp[X] / (X^3 - X - 1)` (`|Fp3Model| = p^3 ≈ 2^192.00`). +- **Hash / Merkle / Transcript:** 32-byte `BLAKE3-256` with native `derive_key` domain separation + (`Fintype.card CertiFri.P3.Digest = 2^256`). +- **FRI batching:** `FriBatching::Tensor` (multilinear tensor batching). +- **Multi-shard LogUp:** Mandatory **Stage-1 pinning** (`stage_1_pinning = 1`), closing + Johnson-regime multi-shard integer LogUp balance without `L^(#circuits * S)` blowup. +- **Shipped FRI parameters (zero query-count churn):** + - **Inner layers (IxVM, Recursion, Aggregation):** `(lb=2, q=128, cpow=0, qpow=20, + maxLogArity=1, logFinalPolyLen=0, capHeight=0)`, tightened in `CertiFRI` to + `θ = 553 / 1024`, `L = 7`, `C(7,2) = 21`, `ε_rbr ≤ (3/4) / 2^133`. + - **Transparent Endpoint 1 (`--stark-128`, `compact400KBBalanced`):** `(lb=4, q=58, cpow=0, + qpow=28, maxLogArity=3, logFinalPolyLen=8, capHeight=0)`, tightened in `CertiFRI` to + `θ = 289 / 1024`, `L = 13`, `C(13,2) = 78`, `ε_rbr ≤ (3/4) / 2^133`. + +### Security Guarantees Established (Zero Custom Axioms) +1. **Classical ROM (`≥ 127.71` bits ideal sponge; keyed byte-level at `ε_rbr ≤ (3/4) / 2^133`):** + - Ideal sponge (`c = 3/2`): `127.71` bits (hash-limited by 32-byte `BLAKE3-256`; literal + `≤ N / 2^128` for `6 N ≤ 2^128` via `soundness_verifyBatchPinnedPrunedSpongeJ_v6_553_133_digest32` + and `soundness_verifyBatchTensorMultiArityPinnedPrunedSpongeJ_ep1_289_133_digest32`). + - Keyed byte-level verifier (`Profile.verifyBytesPinned`, directly executed by `ix verify` and + `verify-multistark`): `verifyBytesPinned_soundness_v6_553_keyed_133` / + `verifyBytesPinned_soundness_v6_553_keyed_133_bounded` (RBR term `(5 M₀ + S · shardQ) / 2^133`) + and `verifyBytesPinned_soundness_ep1Balanced_keyed_checked`. +2. **Post-Quantum QROM (`≥ 64` bits unconditional QROM-Q1, matching/beating Ethereum LeanVM's + `125b / 62b`):** + - Compressed-oracle `ForgePinned` soundness: `measProb ForgePinned ≤ ((Q + Nv) / 2^64)^2` + (and `< 1` at `Q + Nv ≤ 2^64`) directly for `verifyBatchTensorPinned` (inner `v6`) and + `verifyBatchTensorMultiArityPinned` (EP1 `compact400KBBalanced`). + - Standard-QRO corollary via Zhandry's Lemma 5 (`stdQro64_verifyBatchTensorPinned_v6`, + `stdQro64_verifyBatchTensorMultiArityPinned_ep1`), bounding uniform average acceptance over + all classical random oracles `H : X → Y`. + +### Honest Scope Boundaries +- 32-byte `BLAKE3-256` does **not** clear `128.0` bits classical (`3 * (2^128)^2 / 2^257 = 3/2 > 1`; + exact ceiling is `127.71` bits) and does **not** clear `128` bits QROM (`84.00b` BHT / `83.00b` + CMS19). `Goldilocks^3` (`p^3 < 2^192`) cannot clear `100` bits QROM. These negative controls + are proved explicitly below. +- Scope covers **transparent STARK layers only** (IxVM, Recursion, Aggregation, and transparent + Endpoint 1 `--stark-128`). Hiding Endpoint 1 (`--stark-128-zk`, `v6-zk`) and pairing Endpoints + 2 & 3 (BLS12-381 / BN254 KZG+PLONK/Groth16, 0 bits PQ) are outside Release 0.5 PQ scope. +- Every theorem pinned below depends strictly on `[propext, Classical.choice, Quot.sound]` — + zero `sorry`, zero `native_decide`, zero `bv_decide`, and zero custom axioms. +-/ + +namespace Ix.Cert.Release05 + +open CertiFri CertiFri.P3 CertiFri.P3.GoldilocksExt3 CertiFri.P3.VerifyBytesPinnedMultiKeyed + CertiFri.Qrom CertiFri.Stark CertiFri.Stark.Model CertiFri.Exec.Stark CertiFri.Oracle + CertiFri.Oracle.OracleComp CertiFri.Fri CertiFri.Audit05Qrom64 + +/-! ## 1. Release `0.5` Parameter Profile Predicates & Honest Negative Controls -/ + +/-- Digest width in bytes of shipped 32-byte `BLAKE3-256`. -/ +def digestBytesBlake3 : ℕ := 32 + +/-- Release `0.5` inner binary `v6` parameter profile predicate (`Goldilocks^3`, Protocol `v6`, +32-byte `BLAKE3-256`, mandatory `stage_1_pinning = 1`, `Aiur.meetsSecurityFloor`). -/ +def Release05InnerProfile (extDeg protoVer digestBytes stage1Pinning : ℕ) + (cp : Aiur.CommitmentParameters) (fp : Aiur.FriParameters) : Prop := + extDeg = Aiur.extensionDegreeV6 ∧ + protoVer = Aiur.protocolVersionV6 ∧ + digestBytes = digestBytesBlake3 ∧ + stage1Pinning = Aiur.stage1PinningV6 ∧ + Aiur.meetsSecurityFloor cp fp = true + +/-- Release `0.5` transparent Endpoint 1 (`compact400KBBalanced`) parameter profile predicate +(`Goldilocks^3`, Protocol `v6`, 32-byte `BLAKE3-256`, mandatory `stage_1_pinning = 1`, +`lb = 4, cap = 0, lfp = 8, mla = 3, q = 58, cpow = 0, qpow = 28`). -/ +def Release05Ep1BalancedProfile (extDeg protoVer digestBytes stage1Pinning : ℕ) + (cp : Aiur.CommitmentParameters) (fp : Aiur.FriParameters) : Prop := + extDeg = Aiur.extensionDegreeV6 ∧ + protoVer = Aiur.protocolVersionV6 ∧ + digestBytes = digestBytesBlake3 ∧ + stage1Pinning = Aiur.stage1PinningV6 ∧ + cp = ⟨4, 0⟩ ∧ + fp = ⟨8, 3, 58, 0, 28⟩ + +/-- Positive control: shipped `Aiur.defaultCommitmentParameters` + `Aiur.defaultFriParameters` +`(lb=2, q=128, cpow=0, qpow=20)` with `stage_1_pinning = 1` satisfies `Release05InnerProfile`. -/ +theorem release05_inner_default_ok : + Release05InnerProfile Aiur.extensionDegreeV6 Aiur.protocolVersionV6 digestBytesBlake3 + Aiur.stage1PinningV6 Aiur.defaultCommitmentParameters Aiur.defaultFriParameters := by + refine ⟨rfl, rfl, rfl, rfl, ?_⟩ + decide + +/-- Positive control: shipped transparent Endpoint 1 `compact400KBBalanced` `(lb=4, q=58, qpow=28)` +with `stage_1_pinning = 1` satisfies `Release05Ep1BalancedProfile`. -/ +theorem release05_ep1_balanced_ok : + Release05Ep1BalancedProfile Aiur.extensionDegreeV6 Aiur.protocolVersionV6 digestBytesBlake3 + Aiur.stage1PinningV6 ⟨4, 0⟩ ⟨8, 3, 58, 0, 28⟩ := + ⟨rfl, rfl, rfl, rfl, rfl, rfl⟩ + +/-- Negative control: unpinned (`stage_1_pinning = 0`) is rejected by Release `0.5` profiles. -/ +theorem negControl_release05_rejects_unpinned : + ¬ Release05InnerProfile Aiur.extensionDegreeV6 Aiur.protocolVersionV6 digestBytesBlake3 0 + Aiur.defaultCommitmentParameters Aiur.defaultFriParameters ∧ + ¬ Release05Ep1BalancedProfile Aiur.extensionDegreeV6 Aiur.protocolVersionV6 + digestBytesBlake3 0 ⟨4, 0⟩ ⟨8, 3, 58, 0, 28⟩ := by + constructor <;> intro ⟨_, _, _, hpin, _⟩ <;> simp [Aiur.stage1PinningV6] at hpin + +/-- Negative control: retired `Fp^2` (`extension_degree = 2`) is rejected. -/ +theorem negControl_release05_rejects_fp2 : + ¬ Release05InnerProfile 2 Aiur.protocolVersionV6 digestBytesBlake3 Aiur.stage1PinningV6 + Aiur.defaultCommitmentParameters Aiur.defaultFriParameters := by + intro ⟨hext, _⟩; simp [Aiur.extensionDegreeV6] at hext + +/-- Negative control: retired `v5` default `(2, 100, 0, 20)` fails the security floor. -/ +theorem negControl_release05_rejects_v5_default : + ¬ Release05InnerProfile Aiur.extensionDegreeV6 Aiur.protocolVersionV6 digestBytesBlake3 + Aiur.stage1PinningV6 ⟨2, 0⟩ ⟨0, 1, 100, 0, 20⟩ := by + intro ⟨_, _, _, _, hfl⟩; revert hfl; decide + +/-- Negative control: deceptive `(4, 55, 0, 0)` (220 conjectured, 50.2 UD) fails the floor. -/ +theorem negControl_release05_rejects_deceptive_4_55_0 : + ¬ Release05InnerProfile Aiur.extensionDegreeV6 Aiur.protocolVersionV6 digestBytesBlake3 + Aiur.stage1PinningV6 ⟨4, 0⟩ ⟨0, 1, 55, 0, 0⟩ := by + intro ⟨_, _, _, _, hfl⟩; revert hfl; decide + +/-- Positive boundary: 32-byte `BLAKE3-256` clears `127.0` bits classical ideal sponge +(`3 * (2^127)^2 / (2 * 2^256) = 3 / 8 < 1`, exact ceiling `127.71` bits). -/ +theorem posControl_release05_blake3_256_classical_127 : + 3 * ((2 : ℝ) ^ 127) ^ 2 / (2 * (2 : ℝ) ^ 256) = 3 / 8 := by + norm_num + +/-- Honest negative control: 32-byte `BLAKE3-256` does NOT clear `128.0` bits classical ideal +sponge (`3 * (2^128)^2 / 2^257 = 3 / 2 > 1`). -/ +theorem negControl_release05_blake3_256_below_128_classical : + (1 : ℝ) < 3 * ((2 : ℝ) ^ 128) ^ 2 / (2 * (2 : ℝ) ^ 256) := + negControl_blake3_256_below_128_classical + +/-- Honest negative control: 32-byte `BLAKE3-256` does NOT clear `128` bits QROM BHT. -/ +theorem negControl_release05_blake3_256_below_128_qrom : + (1 : ℝ) < 16 * ((2 : ℝ) ^ 85) ^ 3 / (2 : ℝ) ^ 256 := + negControl_blake3_256_below_128_qrom + +/-- Honest negative control: `Goldilocks^3` (`p^3 < 2^192`) cannot clear `100` bits QROM. -/ +theorem negControl_release05_fp3_below_100_qrom : + (Goldilocks.order : ℕ) ^ 3 < (2 ^ 100) ^ 2 := + negControl_fp3_below_100_qrom + +/-- Positive boundary: 32-byte `BLAKE3-256` has `+19` bits of QROM collision headroom above +64 bits even under conservative CMS19 constant `C₂ = 128` (`128 * (2^64)^3 / 2^256 = 2^(-57)`). -/ +theorem posControl_release05_blake3_256_qrom64_headroom : + 128 * ((2 : ℝ) ^ 64) ^ 3 / (2 : ℝ) ^ 256 = 1 / (2 : ℝ) ^ 57 := + posControl_blake3_256_headroom_at_64 + +/-! ## 2. Concrete Ix Production Shape Ceilings & Pure-Kernel Discharges (`(3 / 4) / 2 ^ 133`) -/ + +/-- Generic concrete inner-layer shape ceiling for shipped Protocol `v6` binary pinned FRI +(`lb = 2, q ≥ 128, qpow = 20`, `θ = 553 / 1024`, `L = 7`, `C(7, 2) = 21`, `Kmax = 26`). -/ +structure InnerV6ShapeBounds (sys : System Goldilocks Digest) (B : Bounds) + (maxDeg maxCircs maxWidth maxC maxZ maxCoset maxRows maxItems maxLen : ℕ) : Prop where + hlogBlowup : sys.fri.logBlowup = 2 + hnumQueries : 128 ≤ sys.fri.numQueries + hqueryPow : sys.fri.queryPowBits = 20 + hmaxLogDegree : sys.maxLogDegree ≤ maxDeg + hcircs : sys.circuits.size ≤ maxCircs + hmaxWidth : maxWidthBound sys 3 ≤ maxWidth + hconstraint : constraintBound sys 3 ≤ maxC + hzeta : zetaBound sys ≤ maxZ + hcoset : cosetBound sys ≤ maxCoset + hrows : B.rows ≤ maxRows + hrowItem : rowItemBound B ≤ maxItems + hlen : lenBound sys B ≤ maxLen + +/-- Generic concrete Endpoint 1 shape ceiling for shipped transparent 8-ary pinned FRI +(`FriParams.compact400KBBalanced`, `θ = 289 / 1024`, `L = 13`, `C(13, 2) = 78`, `Kmax = 14`). -/ +structure Ep1V6ShapeBounds (sys : System Goldilocks Digest) (B : Bounds) + (maxDeg maxCircs maxWidth maxC maxZ maxCoset maxRows maxItems maxLen : ℕ) : Prop where + hfri : sys.fri = FriParams.compact400KBBalanced + hmaxLogDegree : sys.maxLogDegree ≤ maxDeg + hcircs : sys.circuits.size ≤ maxCircs + hmaxWidth : maxWidthBound sys 3 ≤ maxWidth + hconstraint : constraintBound sys 3 ≤ maxC + hzeta : zetaBound sys ≤ maxZ + hcoset : cosetBound sys ≤ maxCoset + hrows : B.rows ≤ maxRows + hrowItem : rowItemBound B ≤ maxItems + hlen : lenBound sys B ≤ maxLen + +/-- Pure-kernel master arithmetic inequality for Release `0.5` (`(3 / 4) / 2 ^ 133` over +`Goldilocks^3`): `4 * 2 ^ 133 * x ≤ 3 * Goldilocks.order ^ 3` for every `x ≤ 2 ^ 56` +(over `2.5` bits below the `3 * p^3 / 2^135 ≈ 2^58.58` ceiling; zero `native_decide`). -/ +theorem v6_133_nat_bound_of_le_pow56 {x : ℕ} (hx : x ≤ 2 ^ 56) : + 4 * 2 ^ 133 * x ≤ 3 * Goldilocks.order ^ 3 := by + have h1 : 4 * 2 ^ 133 * x ≤ 4 * 2 ^ 133 * 2 ^ 56 := Nat.mul_le_mul_left _ hx + have h2 : 4 * 2 ^ 133 * 2 ^ 56 ≤ 3 * Goldilocks.order ^ 3 := by + unfold Goldilocks.order; norm_num + exact h1.trans h2 + +/-- Monotonic lift from ceiling inequalities to all inner `v6` 133-bit hypotheses (`L = 7`, +`C(7, 2) = 21`, `kCol + kOpen ≤ 26`). -/ +theorem inner_v6_hypotheses_of_ceilings {sys : System Goldilocks Digest} {B : Bounds} + {maxDeg maxCircs maxWidth maxC maxZ maxCoset maxRows maxItems maxLen : ℕ} + (h : InnerV6ShapeBounds sys B maxDeg maxCircs maxWidth maxC maxZ maxCoset maxRows maxItems maxLen) + (hdeg_c : maxDeg ≤ 23) + (hk_c : tensorNumChallenges maxWidth + tensorNumChallenges (9 * maxCircs) ≤ 26) + (hC_c : 4 * 2 ^ 133 * (7 * maxC) ≤ 3 * Goldilocks.order ^ 3) + (hZ_c : 4 * 2 ^ 133 * (7 * maxZ + maxCoset) ≤ 3 * Goldilocks.order ^ 3) + (hβ_c : 4 * 2 ^ 133 * (2 * maxItems) ≤ 3 * Goldilocks.order ^ 3) + (hγ_c : 4 * 2 ^ 133 * (2 * maxItems * maxLen) ≤ 3 * Goldilocks.order ^ 3) + (hpin_c : 4 * 2 ^ 133 * (21 * maxRows) ≤ 3 * Goldilocks.order ^ 3) : + sys.maxLogDegree ≤ 23 ∧ + (tensorNumChallenges (maxWidthBound sys 3) + + tensorNumChallenges (9 * sys.circuits.size) ≤ 26) ∧ + 4 * 2 ^ 133 * (7 * (constraintBound sys 3 - 1)) ≤ 3 * Goldilocks.order ^ 3 ∧ + 4 * 2 ^ 133 * (7 * zetaBound sys + cosetBound sys) ≤ 3 * Goldilocks.order ^ 3 ∧ + 4 * 2 ^ 133 * (2 * rowItemBound B) ≤ 3 * Goldilocks.order ^ 3 ∧ + 4 * 2 ^ 133 * (2 * rowItemBound B * lenBound sys B) ≤ 3 * Goldilocks.order ^ 3 ∧ + 4 * 2 ^ 133 * (21 * B.rows) ≤ 3 * Goldilocks.order ^ 3 := by + have hkW : tensorNumChallenges (maxWidthBound sys 3) ≤ tensorNumChallenges maxWidth := + tensorNumChallenges_mono h.hmaxWidth + have hkO : tensorNumChallenges (9 * sys.circuits.size) ≤ tensorNumChallenges (9 * maxCircs) := + tensorNumChallenges_mono (Nat.mul_le_mul_left 9 h.hcircs) + refine ⟨h.hmaxLogDegree.trans hdeg_c, by omega, ?_, ?_, ?_, ?_, ?_⟩ + · exact (Nat.mul_le_mul_left _ (Nat.mul_le_mul_left _ ((Nat.sub_le _ 1).trans h.hconstraint))).trans hC_c + · exact (Nat.mul_le_mul_left _ (Nat.add_le_add (Nat.mul_le_mul_left _ h.hzeta) h.hcoset)).trans hZ_c + · exact (Nat.mul_le_mul_left _ (Nat.mul_le_mul_left _ h.hrowItem)).trans hβ_c + · exact (Nat.mul_le_mul_left _ + (Nat.mul_le_mul (Nat.mul_le_mul_left _ h.hrowItem) h.hlen)).trans hγ_c + · exact (Nat.mul_le_mul_left _ (Nat.mul_le_mul_left _ h.hrows)).trans hpin_c + +/-- Monotonic lift from ceiling inequalities to all Endpoint 1 `compact400KBBalanced` 133-bit +hypotheses (`L = 13`, `C(13, 2) = 78`, `kCol + kOpen ≤ 14`). -/ +theorem ep1_v6_hypotheses_of_ceilings {sys : System Goldilocks Digest} {B : Bounds} + {maxDeg maxCircs maxWidth maxC maxZ maxCoset maxRows maxItems maxLen : ℕ} + (h : Ep1V6ShapeBounds sys B maxDeg maxCircs maxWidth maxC maxZ maxCoset maxRows maxItems maxLen) + (hdeg_c : maxDeg ≤ 23) + (hk_c : tensorNumChallenges maxWidth + tensorNumChallenges (9 * maxCircs) ≤ 14) + (hC_c : 4 * 2 ^ 133 * (13 * maxC) ≤ 3 * Goldilocks.order ^ 3) + (hZ_c : 4 * 2 ^ 133 * (13 * maxZ + maxCoset) ≤ 3 * Goldilocks.order ^ 3) + (hβ_c : 4 * 2 ^ 133 * (2 * maxItems) ≤ 3 * Goldilocks.order ^ 3) + (hγ_c : 4 * 2 ^ 133 * (2 * maxItems * maxLen) ≤ 3 * Goldilocks.order ^ 3) + (hpin_c : 4 * 2 ^ 133 * (78 * maxRows) ≤ 3 * Goldilocks.order ^ 3) : + sys.maxLogDegree ≤ 23 ∧ + (tensorNumChallenges (maxWidthBound sys 3) + + tensorNumChallenges (9 * sys.circuits.size) ≤ 14) ∧ + 4 * 2 ^ 133 * (13 * (constraintBound sys 3 - 1)) ≤ 3 * Goldilocks.order ^ 3 ∧ + 4 * 2 ^ 133 * (13 * zetaBound sys + cosetBound sys) ≤ 3 * Goldilocks.order ^ 3 ∧ + 4 * 2 ^ 133 * (2 * rowItemBound B) ≤ 3 * Goldilocks.order ^ 3 ∧ + 4 * 2 ^ 133 * (2 * rowItemBound B * lenBound sys B) ≤ 3 * Goldilocks.order ^ 3 ∧ + 4 * 2 ^ 133 * (78 * B.rows) ≤ 3 * Goldilocks.order ^ 3 := by + have hkW : tensorNumChallenges (maxWidthBound sys 3) ≤ tensorNumChallenges maxWidth := + tensorNumChallenges_mono h.hmaxWidth + have hkO : tensorNumChallenges (9 * sys.circuits.size) ≤ tensorNumChallenges (9 * maxCircs) := + tensorNumChallenges_mono (Nat.mul_le_mul_left 9 h.hcircs) + refine ⟨h.hmaxLogDegree.trans hdeg_c, by omega, ?_, ?_, ?_, ?_, ?_⟩ + · exact (Nat.mul_le_mul_left _ (Nat.mul_le_mul_left _ ((Nat.sub_le _ 1).trans h.hconstraint))).trans hC_c + · exact (Nat.mul_le_mul_left _ (Nat.add_le_add (Nat.mul_le_mul_left _ h.hzeta) h.hcoset)).trans hZ_c + · exact (Nat.mul_le_mul_left _ (Nat.mul_le_mul_left _ h.hrowItem)).trans hβ_c + · exact (Nat.mul_le_mul_left _ + (Nat.mul_le_mul (Nat.mul_le_mul_left _ h.hrowItem) h.hlen)).trans hγ_c + · exact (Nat.mul_le_mul_left _ (Nat.mul_le_mul_left _ h.hrows)).trans hpin_c + +/-! ### 2.1 Concrete Shape Abbreviations (`ixvm-2p23`, `aggr-2p22`, `rec-2p22`, `ep1-v6-hop4`) -/ + +/-- Concrete IxVM `2^23` shape (247 circuits, max width 2382, 64 shards) under shipped `v6`. -/ +abbrev IxVm2p23_64ShShape (sys : System Goldilocks Digest) (B : Bounds) : Prop := + InnerV6ShapeBounds sys B 23 247 2382 5242 209715200 66303557632 131000778752 2071818523648 140 + +/-- Concrete IxVM `2^23` shape (247 circuits, max width 2382, up to **4,096 shards**) under shipped `v6`. -/ +abbrev IxVm2p23_4096ShShape (sys : System Goldilocks Digest) (B : Bounds) : Prop := + InnerV6ShapeBounds sys B 23 247 2382 5242 209715200 66303557632 8384049840128 132596385448960 140 + +/-- Concrete Aggregation `2^22` shape (60 circuits, max width ≤ 4096, 16 shards) under shipped `v6`. -/ +abbrev Aggr2p22_16ShShape (sys : System Goldilocks Digest) (B : Bounds) : Prop := + InnerV6ShapeBounds sys B 22 60 4096 6009 104857600 8053063680 3826274304 112147331072 140 + +/-- Concrete Recursion `2^22` shape (53 circuits, max width ≤ 4096, 1 shard) under shipped `v6`. -/ +abbrev Rec2p22_1ShShape (sys : System Goldilocks Digest) (B : Bounds) : Prop := + InnerV6ShapeBounds sys B 22 53 4096 6009 104857600 7113539584 209782016 6526864192 140 + +/-- Concrete Transparent Endpoint 1 `ep1-v6-hop4` shape (1 Plonkish circuit, max width 79, +`2^23` rows, 8-ary `FriParams.compact400KBBalanced`). -/ +abbrev Ep1V6Hop4Shape (sys : System Goldilocks Digest) (B : Bounds) : Prop := + Ep1V6ShapeBounds sys B 23 1 79 59 679477248 1073741824 8388608 503317568 8 + +/-! ### 2.2 Pure-Kernel Integer Discharges (`hdeg`, `hk`, `hC`, `hZ`, `hβ`, `hγ`, `hpin`, `< p`) -/ + +/-- LogUp integer-balance ceiling: even at **4,096 shards** of `ixvm-2p23`, `rowItemBound B` +stays strictly below Goldilocks `p = 2^64 - 2^32 + 1` (by `> 17` bits). -/ +theorem ixVm2p23_4096sh_balance_lt_p {sys : System Goldilocks Digest} {B : Bounds} + (h : IxVm2p23_4096ShShape sys B) : rowItemBound B < Goldilocks.order := by + have h1 : 132596385448960 < Goldilocks.order := by + unfold Goldilocks.order; decide + exact lt_of_le_of_lt h.hrowItem h1 + +/-- Pure-kernel discharge of `hdeg`, `hk (≤ 26)`, and all five 133-bit inequalities for +`ixvm-2p23` at **4,096 shards** (and hence any shard count `≤ 4,096`). -/ +theorem ixVm2p23_4096sh_hypotheses {sys : System Goldilocks Digest} {B : Bounds} + (h : IxVm2p23_4096ShShape sys B) : + sys.maxLogDegree ≤ 23 ∧ + (tensorNumChallenges (maxWidthBound sys 3) + + tensorNumChallenges (9 * sys.circuits.size) ≤ 26) ∧ + 4 * 2 ^ 133 * (7 * (constraintBound sys 3 - 1)) ≤ 3 * Goldilocks.order ^ 3 ∧ + 4 * 2 ^ 133 * (7 * zetaBound sys + cosetBound sys) ≤ 3 * Goldilocks.order ^ 3 ∧ + 4 * 2 ^ 133 * (2 * rowItemBound B) ≤ 3 * Goldilocks.order ^ 3 ∧ + 4 * 2 ^ 133 * (2 * rowItemBound B * lenBound sys B) ≤ 3 * Goldilocks.order ^ 3 ∧ + 4 * 2 ^ 133 * (21 * B.rows) ≤ 3 * Goldilocks.order ^ 3 := + inner_v6_hypotheses_of_ceilings h + (by decide) + (by decide) + (v6_133_nat_bound_of_le_pow56 (by decide)) + (v6_133_nat_bound_of_le_pow56 (by decide)) + (v6_133_nat_bound_of_le_pow56 (by decide)) + (v6_133_nat_bound_of_le_pow56 (by decide)) + (v6_133_nat_bound_of_le_pow56 (by decide)) + +/-- Pure-kernel discharge for `ixvm-2p23` at 64 shards. -/ +theorem ixVm2p23_64sh_hypotheses {sys : System Goldilocks Digest} {B : Bounds} + (h : IxVm2p23_64ShShape sys B) : + sys.maxLogDegree ≤ 23 ∧ + (tensorNumChallenges (maxWidthBound sys 3) + + tensorNumChallenges (9 * sys.circuits.size) ≤ 26) ∧ + 4 * 2 ^ 133 * (7 * (constraintBound sys 3 - 1)) ≤ 3 * Goldilocks.order ^ 3 ∧ + 4 * 2 ^ 133 * (7 * zetaBound sys + cosetBound sys) ≤ 3 * Goldilocks.order ^ 3 ∧ + 4 * 2 ^ 133 * (2 * rowItemBound B) ≤ 3 * Goldilocks.order ^ 3 ∧ + 4 * 2 ^ 133 * (2 * rowItemBound B * lenBound sys B) ≤ 3 * Goldilocks.order ^ 3 ∧ + 4 * 2 ^ 133 * (21 * B.rows) ≤ 3 * Goldilocks.order ^ 3 := + ixVm2p23_4096sh_hypotheses + { h with + hrows := h.hrows.trans (by decide) + hrowItem := h.hrowItem.trans (by decide) } + +/-- Pure-kernel discharge for `aggr-2p22` (16 shards). -/ +theorem aggr2p22_16sh_hypotheses {sys : System Goldilocks Digest} {B : Bounds} + (h : Aggr2p22_16ShShape sys B) : + sys.maxLogDegree ≤ 23 ∧ + (tensorNumChallenges (maxWidthBound sys 3) + + tensorNumChallenges (9 * sys.circuits.size) ≤ 26) ∧ + 4 * 2 ^ 133 * (7 * (constraintBound sys 3 - 1)) ≤ 3 * Goldilocks.order ^ 3 ∧ + 4 * 2 ^ 133 * (7 * zetaBound sys + cosetBound sys) ≤ 3 * Goldilocks.order ^ 3 ∧ + 4 * 2 ^ 133 * (2 * rowItemBound B) ≤ 3 * Goldilocks.order ^ 3 ∧ + 4 * 2 ^ 133 * (2 * rowItemBound B * lenBound sys B) ≤ 3 * Goldilocks.order ^ 3 ∧ + 4 * 2 ^ 133 * (21 * B.rows) ≤ 3 * Goldilocks.order ^ 3 := + inner_v6_hypotheses_of_ceilings h + (by decide) + (by decide) + (v6_133_nat_bound_of_le_pow56 (by decide)) + (v6_133_nat_bound_of_le_pow56 (by decide)) + (v6_133_nat_bound_of_le_pow56 (by decide)) + (v6_133_nat_bound_of_le_pow56 (by decide)) + (v6_133_nat_bound_of_le_pow56 (by decide)) + +/-- Pure-kernel discharge for `rec-2p22` (1 shard). -/ +theorem rec2p22_1sh_hypotheses {sys : System Goldilocks Digest} {B : Bounds} + (h : Rec2p22_1ShShape sys B) : + sys.maxLogDegree ≤ 23 ∧ + (tensorNumChallenges (maxWidthBound sys 3) + + tensorNumChallenges (9 * sys.circuits.size) ≤ 26) ∧ + 4 * 2 ^ 133 * (7 * (constraintBound sys 3 - 1)) ≤ 3 * Goldilocks.order ^ 3 ∧ + 4 * 2 ^ 133 * (7 * zetaBound sys + cosetBound sys) ≤ 3 * Goldilocks.order ^ 3 ∧ + 4 * 2 ^ 133 * (2 * rowItemBound B) ≤ 3 * Goldilocks.order ^ 3 ∧ + 4 * 2 ^ 133 * (2 * rowItemBound B * lenBound sys B) ≤ 3 * Goldilocks.order ^ 3 ∧ + 4 * 2 ^ 133 * (21 * B.rows) ≤ 3 * Goldilocks.order ^ 3 := + aggr2p22_16sh_hypotheses + { h with + hcircs := h.hcircs.trans (by decide) + hcoset := h.hcoset.trans (by decide) + hrows := h.hrows.trans (by decide) + hrowItem := h.hrowItem.trans (by decide) } + +/-- Pure-kernel discharge for transparent Endpoint 1 `ep1-v6-hop4` (8-ary `compact400KBBalanced`). -/ +theorem ep1V6Hop4_hypotheses {sys : System Goldilocks Digest} {B : Bounds} + (h : Ep1V6Hop4Shape sys B) : + sys.maxLogDegree ≤ 23 ∧ + (tensorNumChallenges (maxWidthBound sys 3) + + tensorNumChallenges (9 * sys.circuits.size) ≤ 14) ∧ + 4 * 2 ^ 133 * (13 * (constraintBound sys 3 - 1)) ≤ 3 * Goldilocks.order ^ 3 ∧ + 4 * 2 ^ 133 * (13 * zetaBound sys + cosetBound sys) ≤ 3 * Goldilocks.order ^ 3 ∧ + 4 * 2 ^ 133 * (2 * rowItemBound B) ≤ 3 * Goldilocks.order ^ 3 ∧ + 4 * 2 ^ 133 * (2 * rowItemBound B * lenBound sys B) ≤ 3 * Goldilocks.order ^ 3 ∧ + 4 * 2 ^ 133 * (78 * B.rows) ≤ 3 * Goldilocks.order ^ 3 := + ep1_v6_hypotheses_of_ceilings h + (by decide) + (by decide) + (v6_133_nat_bound_of_le_pow56 (by decide)) + (v6_133_nat_bound_of_le_pow56 (by decide)) + (v6_133_nat_bound_of_le_pow56 (by decide)) + (v6_133_nat_bound_of_le_pow56 (by decide)) + (v6_133_nat_bound_of_le_pow56 (by decide)) + +/-! ## 3. Discharged End-to-End 64-Bit QROM & Classical ROM Theorems on Concrete Ix Shapes -/ + +section ConcreteSoundness + +variable {fslots slots width : ℕ} + {W X Y : Type} [Fintype W] [Fintype X] [DecidableEq X] [Fintype Y] [Nonempty Y] + +/-- **Unconditional 64-bit QROM soundness for `ixvm-2p23` (64 shards, shipped `v6` + Stage-1 pinning):** +zero remaining numeric, degree, or tensor-challenge-cap hypotheses. -/ +theorem ixVm2p23_64sh_qrom64 + (bridge : SpongeDbBridge Goldilocks GoldilocksExt3 Digest Fp3Model fslots slots width X Y) + (hObs : ∀ (x : X) (z : Digest), + FractionLE (fun y : Y => bridge.obs x y = some z) (1 / (Fintype.card Digest : ℝ))) + (hExtract : ∀ (p : UTensorAns Fp3Model fslots slots width → Prop) (e : ℝ), + FractionLE p e → FractionLE (fun y : Y => p (bridge.extractChal y)) e) + (s₀ : Digest) (sys : System Goldilocks Digest) (B : Bounds) + (hshape : IxVm2p23_64ShShape sys B) + (hplain : ∀ c ∈ sys.circuits.toList, c.LookupsPlain) + (hmainW : ∀ c ∈ sys.circuits.toList, 0 < c.mainWidth) + (hfixed : sys.FixedOk) (hheightOk : sys.HeightOk) + {N : ℕ} (hN : BoundsLE sys B N) (hNp : N < Goldilocks.order) + (hfslots : 32 ≤ fslots) (hslots : sys.fri.numQueries + 1 ≤ slots) + (hcommit : sys.fri.commitPowBits ≤ width) (hquery : sys.fri.queryPowBits ≤ width) + (hwidth : 32 ≤ width) + {V : X → Y → QState W → QState W} (hV : ∀ x u, IsUnitary (V x u)) + (alg : QQueryAlgorithm (X × W) X Y) + (hO : ∀ k, alg.oracleU k = compressedOracle V) + {Q Nv : ℕ} (hQ : Q + Nv ≤ 2 ^ 64) + (attempt : X × W → PAttemptPruned Goldilocks GoldilocksExt3 Digest) + [DecidablePred (ForgePinned bridge s₀ starkModel sys (553 / 1024) B false attempt)] : + measProb (ForgePinned bridge s₀ starkModel sys (553 / 1024) B false attempt) + (runAlg alg (Q + Nv)) ≤ + ((Q + Nv : ℝ) / 2 ^ 64) ^ 2 := by + obtain ⟨hdeg, hk, hC, hZ, hβ, hγ, hpin⟩ := ixVm2p23_64sh_hypotheses hshape + refine qrom64_verifyBatchTensorPinned_v6 bridge hObs hExtract s₀ sys B + hshape.hlogBlowup hshape.hnumQueries hshape.hqueryPow hdeg + (fun v hv => by + rw [← hshape.hlogBlowup] + exact tensorChallenges_pshape_le_of_bounds sys hk v hv) + hplain hmainW hfixed hheightOk hN hNp hC hZ hβ hγ hpin + hfslots hslots hcommit hquery hwidth hV alg hO hQ attempt + +/-- Strict sub-unit 64-bit QROM corollary for `ixvm-2p23` (64 shards): `< 1` at `Q + Nv ≤ 2^64`. -/ +theorem ixVm2p23_64sh_qrom64_sub_one + (bridge : SpongeDbBridge Goldilocks GoldilocksExt3 Digest Fp3Model fslots slots width X Y) + (hObs : ∀ (x : X) (z : Digest), + FractionLE (fun y : Y => bridge.obs x y = some z) (1 / (Fintype.card Digest : ℝ))) + (hExtract : ∀ (p : UTensorAns Fp3Model fslots slots width → Prop) (e : ℝ), + FractionLE p e → FractionLE (fun y : Y => p (bridge.extractChal y)) e) + (s₀ : Digest) (sys : System Goldilocks Digest) (B : Bounds) + (hshape : IxVm2p23_64ShShape sys B) + (hplain : ∀ c ∈ sys.circuits.toList, c.LookupsPlain) + (hmainW : ∀ c ∈ sys.circuits.toList, 0 < c.mainWidth) + (hfixed : sys.FixedOk) (hheightOk : sys.HeightOk) + {N : ℕ} (hN : BoundsLE sys B N) (hNp : N < Goldilocks.order) + (hfslots : 32 ≤ fslots) (hslots : sys.fri.numQueries + 1 ≤ slots) + (hcommit : sys.fri.commitPowBits ≤ width) (hquery : sys.fri.queryPowBits ≤ width) + (hwidth : 32 ≤ width) + {V : X → Y → QState W → QState W} (hV : ∀ x u, IsUnitary (V x u)) + (alg : QQueryAlgorithm (X × W) X Y) + (hO : ∀ k, alg.oracleU k = compressedOracle V) + {Q Nv : ℕ} (hQ : Q + Nv ≤ 2 ^ 64) + (attempt : X × W → PAttemptPruned Goldilocks GoldilocksExt3 Digest) + [DecidablePred (ForgePinned bridge s₀ starkModel sys (553 / 1024) B false attempt)] : + measProb (ForgePinned bridge s₀ starkModel sys (553 / 1024) B false attempt) + (runAlg alg (Q + Nv)) < 1 := by + obtain ⟨hdeg, hk, hC, hZ, hβ, hγ, hpin⟩ := ixVm2p23_64sh_hypotheses hshape + refine qrom64_verifyBatchTensorPinned_v6_sub_one bridge hObs hExtract s₀ sys B + hshape.hlogBlowup hshape.hnumQueries hshape.hqueryPow hdeg + (fun v hv => by + rw [← hshape.hlogBlowup] + exact tensorChallenges_pshape_le_of_bounds sys hk v hv) + hplain hmainW hfixed hheightOk hN hNp hC hZ hβ hγ hpin + hfslots hslots hcommit hquery hwidth hV alg hO hQ attempt + +/-- **Unconditional 64-bit QROM soundness for `ixvm-2p23` up to 4,096 shards.** -/ +theorem ixVm2p23_4096sh_qrom64 + (bridge : SpongeDbBridge Goldilocks GoldilocksExt3 Digest Fp3Model fslots slots width X Y) + (hObs : ∀ (x : X) (z : Digest), + FractionLE (fun y : Y => bridge.obs x y = some z) (1 / (Fintype.card Digest : ℝ))) + (hExtract : ∀ (p : UTensorAns Fp3Model fslots slots width → Prop) (e : ℝ), + FractionLE p e → FractionLE (fun y : Y => p (bridge.extractChal y)) e) + (s₀ : Digest) (sys : System Goldilocks Digest) (B : Bounds) + (hshape : IxVm2p23_4096ShShape sys B) + (hplain : ∀ c ∈ sys.circuits.toList, c.LookupsPlain) + (hmainW : ∀ c ∈ sys.circuits.toList, 0 < c.mainWidth) + (hfixed : sys.FixedOk) (hheightOk : sys.HeightOk) + {N : ℕ} (hN : BoundsLE sys B N) (hNp : N < Goldilocks.order) + (hfslots : 32 ≤ fslots) (hslots : sys.fri.numQueries + 1 ≤ slots) + (hcommit : sys.fri.commitPowBits ≤ width) (hquery : sys.fri.queryPowBits ≤ width) + (hwidth : 32 ≤ width) + {V : X → Y → QState W → QState W} (hV : ∀ x u, IsUnitary (V x u)) + (alg : QQueryAlgorithm (X × W) X Y) + (hO : ∀ k, alg.oracleU k = compressedOracle V) + {Q Nv : ℕ} (hQ : Q + Nv ≤ 2 ^ 64) + (attempt : X × W → PAttemptPruned Goldilocks GoldilocksExt3 Digest) + [DecidablePred (ForgePinned bridge s₀ starkModel sys (553 / 1024) B false attempt)] : + measProb (ForgePinned bridge s₀ starkModel sys (553 / 1024) B false attempt) + (runAlg alg (Q + Nv)) ≤ + ((Q + Nv : ℝ) / 2 ^ 64) ^ 2 := by + obtain ⟨hdeg, hk, hC, hZ, hβ, hγ, hpin⟩ := ixVm2p23_4096sh_hypotheses hshape + refine qrom64_verifyBatchTensorPinned_v6 bridge hObs hExtract s₀ sys B + hshape.hlogBlowup hshape.hnumQueries hshape.hqueryPow hdeg + (fun v hv => by + rw [← hshape.hlogBlowup] + exact tensorChallenges_pshape_le_of_bounds sys hk v hv) + hplain hmainW hfixed hheightOk hN hNp hC hZ hβ hγ hpin + hfslots hslots hcommit hquery hwidth hV alg hO hQ attempt + +/-- **Standard-QRO (Zhandry Lemma 5) 64-bit QROM soundness for `ixvm-2p23` up to 4,096 shards.** -/ +theorem ixVm2p23_4096sh_stdQro64 + (bridge : SpongeDbBridge Goldilocks GoldilocksExt3 Digest Fp3Model fslots slots width X Y) + (hObs : ∀ (x : X) (z : Digest), + FractionLE (fun y : Y => bridge.obs x y = some z) (1 / (Fintype.card Digest : ℝ))) + (hExtract : ∀ (p : UTensorAns Fp3Model fslots slots width → Prop) (e : ℝ), + FractionLE p e → FractionLE (fun y : Y => p (bridge.extractChal y)) e) + (s₀ : Digest) (sys : System Goldilocks Digest) (B : Bounds) + (hshape : IxVm2p23_4096ShShape sys B) + (hplain : ∀ c ∈ sys.circuits.toList, c.LookupsPlain) + (hmainW : ∀ c ∈ sys.circuits.toList, 0 < c.mainWidth) + (hfixed : sys.FixedOk) (hheightOk : sys.HeightOk) + {N : ℕ} (hN : BoundsLE sys B N) (hNp : N < Goldilocks.order) + (hfslots : 32 ≤ fslots) (hslots : sys.fri.numQueries + 1 ≤ slots) + (hcommit : sys.fri.commitPowBits ≤ width) (hquery : sys.fri.queryPowBits ≤ width) + (hwidth : 32 ≤ width) + {V : X → Y → QState W → QState W} (hV : ∀ x u, IsUnitary (V x u)) + {advU verU : ℕ → QState (X × W) → QState (X × W)} + (hAdvU : ∀ k, IsUnitary (advU k)) (hVerU : ∀ k, IsUnitary (verU k)) + {ψ0 : QState (X × W)} (hψ0 : IsUnitState ψ0) + {Q Nv : ℕ} (hQ : Q + Nv ≤ 2 ^ 64) + (attempt : X × W → PAttemptPruned Goldilocks GoldilocksExt3 Digest) + (Accept : X × W → Prop) [DecidablePred Accept] + [DecidablePred (ForgePinned bridge s₀ starkModel sys (553 / 1024) B false attempt)] + (hAcc : ∀ s, + runAlg (mkCOAlg hV (isUnitary_combinedSteps Q hAdvU hVerU) hψ0) (Q + Nv) s ≠ 0 → + Accept s.1 → ForgePinned bridge s₀ starkModel sys (553 / 1024) B false attempt s) : + (1 / (Fintype.card (X → Y) : ℝ)) * + ∑ H : X → Y, measProb Accept + (runWithOracle H verU V (runWithOracle H advU V ψ0 Q) Nv) ≤ + ((Q + Nv : ℝ) / 2 ^ 64) ^ 2 := by + obtain ⟨hdeg, hk, hC, hZ, hβ, hγ, hpin⟩ := ixVm2p23_4096sh_hypotheses hshape + refine stdQro64_verifyBatchTensorPinned_v6 bridge hObs hExtract s₀ sys B + hshape.hlogBlowup hshape.hnumQueries hshape.hqueryPow hdeg + (fun v hv => by + rw [← hshape.hlogBlowup] + exact tensorChallenges_pshape_le_of_bounds sys hk v hv) + hplain hmainW hfixed hheightOk hN hNp hC hZ hβ hγ hpin + hfslots hslots hcommit hquery hwidth hV hAdvU hVerU hψ0 hQ attempt Accept hAcc + +/-- **Unconditional 64-bit QROM soundness for `aggr-2p22` (16 shards, shipped `v6`).** -/ +theorem aggr2p22_16sh_qrom64 + (bridge : SpongeDbBridge Goldilocks GoldilocksExt3 Digest Fp3Model fslots slots width X Y) + (hObs : ∀ (x : X) (z : Digest), + FractionLE (fun y : Y => bridge.obs x y = some z) (1 / (Fintype.card Digest : ℝ))) + (hExtract : ∀ (p : UTensorAns Fp3Model fslots slots width → Prop) (e : ℝ), + FractionLE p e → FractionLE (fun y : Y => p (bridge.extractChal y)) e) + (s₀ : Digest) (sys : System Goldilocks Digest) (B : Bounds) + (hshape : Aggr2p22_16ShShape sys B) + (hplain : ∀ c ∈ sys.circuits.toList, c.LookupsPlain) + (hmainW : ∀ c ∈ sys.circuits.toList, 0 < c.mainWidth) + (hfixed : sys.FixedOk) (hheightOk : sys.HeightOk) + {N : ℕ} (hN : BoundsLE sys B N) (hNp : N < Goldilocks.order) + (hfslots : 32 ≤ fslots) (hslots : sys.fri.numQueries + 1 ≤ slots) + (hcommit : sys.fri.commitPowBits ≤ width) (hquery : sys.fri.queryPowBits ≤ width) + (hwidth : 32 ≤ width) + {V : X → Y → QState W → QState W} (hV : ∀ x u, IsUnitary (V x u)) + (alg : QQueryAlgorithm (X × W) X Y) + (hO : ∀ k, alg.oracleU k = compressedOracle V) + {Q Nv : ℕ} (hQ : Q + Nv ≤ 2 ^ 64) + (attempt : X × W → PAttemptPruned Goldilocks GoldilocksExt3 Digest) + [DecidablePred (ForgePinned bridge s₀ starkModel sys (553 / 1024) B false attempt)] : + measProb (ForgePinned bridge s₀ starkModel sys (553 / 1024) B false attempt) + (runAlg alg (Q + Nv)) ≤ + ((Q + Nv : ℝ) / 2 ^ 64) ^ 2 := by + obtain ⟨hdeg, hk, hC, hZ, hβ, hγ, hpin⟩ := aggr2p22_16sh_hypotheses hshape + refine qrom64_verifyBatchTensorPinned_v6 bridge hObs hExtract s₀ sys B + hshape.hlogBlowup hshape.hnumQueries hshape.hqueryPow hdeg + (fun v hv => by + rw [← hshape.hlogBlowup] + exact tensorChallenges_pshape_le_of_bounds sys hk v hv) + hplain hmainW hfixed hheightOk hN hNp hC hZ hβ hγ hpin + hfslots hslots hcommit hquery hwidth hV alg hO hQ attempt + +/-- **Unconditional 64-bit QROM soundness for `rec-2p22` (1 shard, shipped `v6`).** -/ +theorem rec2p22_1sh_qrom64 + (bridge : SpongeDbBridge Goldilocks GoldilocksExt3 Digest Fp3Model fslots slots width X Y) + (hObs : ∀ (x : X) (z : Digest), + FractionLE (fun y : Y => bridge.obs x y = some z) (1 / (Fintype.card Digest : ℝ))) + (hExtract : ∀ (p : UTensorAns Fp3Model fslots slots width → Prop) (e : ℝ), + FractionLE p e → FractionLE (fun y : Y => p (bridge.extractChal y)) e) + (s₀ : Digest) (sys : System Goldilocks Digest) (B : Bounds) + (hshape : Rec2p22_1ShShape sys B) + (hplain : ∀ c ∈ sys.circuits.toList, c.LookupsPlain) + (hmainW : ∀ c ∈ sys.circuits.toList, 0 < c.mainWidth) + (hfixed : sys.FixedOk) (hheightOk : sys.HeightOk) + {N : ℕ} (hN : BoundsLE sys B N) (hNp : N < Goldilocks.order) + (hfslots : 32 ≤ fslots) (hslots : sys.fri.numQueries + 1 ≤ slots) + (hcommit : sys.fri.commitPowBits ≤ width) (hquery : sys.fri.queryPowBits ≤ width) + (hwidth : 32 ≤ width) + {V : X → Y → QState W → QState W} (hV : ∀ x u, IsUnitary (V x u)) + (alg : QQueryAlgorithm (X × W) X Y) + (hO : ∀ k, alg.oracleU k = compressedOracle V) + {Q Nv : ℕ} (hQ : Q + Nv ≤ 2 ^ 64) + (attempt : X × W → PAttemptPruned Goldilocks GoldilocksExt3 Digest) + [DecidablePred (ForgePinned bridge s₀ starkModel sys (553 / 1024) B false attempt)] : + measProb (ForgePinned bridge s₀ starkModel sys (553 / 1024) B false attempt) + (runAlg alg (Q + Nv)) ≤ + ((Q + Nv : ℝ) / 2 ^ 64) ^ 2 := by + obtain ⟨hdeg, hk, hC, hZ, hβ, hγ, hpin⟩ := rec2p22_1sh_hypotheses hshape + refine qrom64_verifyBatchTensorPinned_v6 bridge hObs hExtract s₀ sys B + hshape.hlogBlowup hshape.hnumQueries hshape.hqueryPow hdeg + (fun v hv => by + rw [← hshape.hlogBlowup] + exact tensorChallenges_pshape_le_of_bounds sys hk v hv) + hplain hmainW hfixed hheightOk hN hNp hC hZ hβ hγ hpin + hfslots hslots hcommit hquery hwidth hV alg hO hQ attempt + +/-- **Unconditional 64-bit QROM soundness for transparent Endpoint 1 `ep1-v6-hop4`** +(1 Plonkish circuit, `2^23` rows, 8-ary `FriParams.compact400KBBalanced`). -/ +theorem ep1V6Hop4_qrom64 + (bridge : SpongeDbBridge Goldilocks GoldilocksExt3 Digest Fp3Model fslots slots width X Y) + (hObs : ∀ (x : X) (z : Digest), + FractionLE (fun y : Y => bridge.obs x y = some z) (1 / (Fintype.card Digest : ℝ))) + (hExtract : ∀ (p : UTensorAns Fp3Model fslots slots width → Prop) (e : ℝ), + FractionLE p e → FractionLE (fun y : Y => p (bridge.extractChal y)) e) + (s₀ : Digest) (sys : System Goldilocks Digest) (B : Bounds) + (hshape : Ep1V6Hop4Shape sys B) + (hplain : ∀ c ∈ sys.circuits.toList, c.LookupsPlain) + (hmainW : ∀ c ∈ sys.circuits.toList, 0 < c.mainWidth) + (hfixed : sys.FixedOk) (hheightOk : sys.HeightOk) + {N : ℕ} (hN : BoundsLE sys B N) (hNp : N < Goldilocks.order) + (hfslots : 32 ≤ fslots) (hslots : 59 ≤ slots) (hwidth : 32 ≤ width) + {V : X → Y → QState W → QState W} (hV : ∀ x u, IsUnitary (V x u)) + (alg : QQueryAlgorithm (X × W) X Y) + (hO : ∀ k, alg.oracleU k = compressedOracle V) + {Q Nv : ℕ} (hQ : Q + Nv ≤ 2 ^ 64) + (attempt : X × W → PAttemptPruned Goldilocks GoldilocksExt3 Digest) + [DecidablePred (ForgePinned bridge s₀ starkModel sys (289 / 1024) B true attempt)] : + measProb (ForgePinned bridge s₀ starkModel sys (289 / 1024) B true attempt) + (runAlg alg (Q + Nv)) ≤ + ((Q + Nv : ℝ) / 2 ^ 64) ^ 2 := by + obtain ⟨hdeg, hk, hC, hZ, hβ, hγ, hpin⟩ := ep1V6Hop4_hypotheses hshape + have hlb : sys.fri.logBlowup = 4 := by rw [hshape.hfri]; rfl + refine qrom64_verifyBatchTensorMultiArityPinned_ep1 bridge hObs hExtract s₀ sys B + hshape.hfri hdeg + (fun v hv => by + rw [← hlb] + exact tensorChallenges_pshape_le_of_bounds sys hk v hv) + hplain hmainW hfixed hheightOk hN hNp hC hZ hβ hγ hpin + hfslots hslots hwidth hV alg hO hQ attempt + +/-- Strict sub-unit 64-bit QROM corollary for transparent Endpoint 1 `ep1-v6-hop4`. -/ +theorem ep1V6Hop4_qrom64_sub_one + (bridge : SpongeDbBridge Goldilocks GoldilocksExt3 Digest Fp3Model fslots slots width X Y) + (hObs : ∀ (x : X) (z : Digest), + FractionLE (fun y : Y => bridge.obs x y = some z) (1 / (Fintype.card Digest : ℝ))) + (hExtract : ∀ (p : UTensorAns Fp3Model fslots slots width → Prop) (e : ℝ), + FractionLE p e → FractionLE (fun y : Y => p (bridge.extractChal y)) e) + (s₀ : Digest) (sys : System Goldilocks Digest) (B : Bounds) + (hshape : Ep1V6Hop4Shape sys B) + (hplain : ∀ c ∈ sys.circuits.toList, c.LookupsPlain) + (hmainW : ∀ c ∈ sys.circuits.toList, 0 < c.mainWidth) + (hfixed : sys.FixedOk) (hheightOk : sys.HeightOk) + {N : ℕ} (hN : BoundsLE sys B N) (hNp : N < Goldilocks.order) + (hfslots : 32 ≤ fslots) (hslots : 59 ≤ slots) (hwidth : 32 ≤ width) + {V : X → Y → QState W → QState W} (hV : ∀ x u, IsUnitary (V x u)) + (alg : QQueryAlgorithm (X × W) X Y) + (hO : ∀ k, alg.oracleU k = compressedOracle V) + {Q Nv : ℕ} (hQ : Q + Nv ≤ 2 ^ 64) + (attempt : X × W → PAttemptPruned Goldilocks GoldilocksExt3 Digest) + [DecidablePred (ForgePinned bridge s₀ starkModel sys (289 / 1024) B true attempt)] : + measProb (ForgePinned bridge s₀ starkModel sys (289 / 1024) B true attempt) + (runAlg alg (Q + Nv)) < 1 := by + obtain ⟨hdeg, hk, hC, hZ, hβ, hγ, hpin⟩ := ep1V6Hop4_hypotheses hshape + have hlb : sys.fri.logBlowup = 4 := by rw [hshape.hfri]; rfl + refine qrom64_verifyBatchTensorMultiArityPinned_ep1_sub_one bridge hObs hExtract s₀ sys B + hshape.hfri hdeg + (fun v hv => by + rw [← hlb] + exact tensorChallenges_pshape_le_of_bounds sys hk v hv) + hplain hmainW hfixed hheightOk hN hNp hC hZ hβ hγ hpin + hfslots hslots hwidth hV alg hO hQ attempt + +/-- **Standard-QRO (Zhandry Lemma 5) 64-bit QROM soundness for transparent Endpoint 1 `ep1-v6-hop4`.** -/ +theorem ep1V6Hop4_stdQro64 + (bridge : SpongeDbBridge Goldilocks GoldilocksExt3 Digest Fp3Model fslots slots width X Y) + (hObs : ∀ (x : X) (z : Digest), + FractionLE (fun y : Y => bridge.obs x y = some z) (1 / (Fintype.card Digest : ℝ))) + (hExtract : ∀ (p : UTensorAns Fp3Model fslots slots width → Prop) (e : ℝ), + FractionLE p e → FractionLE (fun y : Y => p (bridge.extractChal y)) e) + (s₀ : Digest) (sys : System Goldilocks Digest) (B : Bounds) + (hshape : Ep1V6Hop4Shape sys B) + (hplain : ∀ c ∈ sys.circuits.toList, c.LookupsPlain) + (hmainW : ∀ c ∈ sys.circuits.toList, 0 < c.mainWidth) + (hfixed : sys.FixedOk) (hheightOk : sys.HeightOk) + {N : ℕ} (hN : BoundsLE sys B N) (hNp : N < Goldilocks.order) + (hfslots : 32 ≤ fslots) (hslots : 59 ≤ slots) (hwidth : 32 ≤ width) + {V : X → Y → QState W → QState W} (hV : ∀ x u, IsUnitary (V x u)) + {advU verU : ℕ → QState (X × W) → QState (X × W)} + (hAdvU : ∀ k, IsUnitary (advU k)) (hVerU : ∀ k, IsUnitary (verU k)) + {ψ0 : QState (X × W)} (hψ0 : IsUnitState ψ0) + {Q Nv : ℕ} (hQ : Q + Nv ≤ 2 ^ 64) + (attempt : X × W → PAttemptPruned Goldilocks GoldilocksExt3 Digest) + (Accept : X × W → Prop) [DecidablePred Accept] + [DecidablePred (ForgePinned bridge s₀ starkModel sys (289 / 1024) B true attempt)] + (hAcc : ∀ s, + runAlg (mkCOAlg hV (isUnitary_combinedSteps Q hAdvU hVerU) hψ0) (Q + Nv) s ≠ 0 → + Accept s.1 → ForgePinned bridge s₀ starkModel sys (289 / 1024) B true attempt s) : + (1 / (Fintype.card (X → Y) : ℝ)) * + ∑ H : X → Y, measProb Accept + (runWithOracle H verU V (runWithOracle H advU V ψ0 Q) Nv) ≤ + ((Q + Nv : ℝ) / 2 ^ 64) ^ 2 := by + obtain ⟨hdeg, hk, hC, hZ, hβ, hγ, hpin⟩ := ep1V6Hop4_hypotheses hshape + have hlb : sys.fri.logBlowup = 4 := by rw [hshape.hfri]; rfl + refine stdQro64_verifyBatchTensorMultiArityPinned_ep1 bridge hObs hExtract s₀ sys B + hshape.hfri hdeg + (fun v hv => by + rw [← hlb] + exact tensorChallenges_pshape_le_of_bounds sys hk v hv) + hplain hmainW hfixed hheightOk hN hNp hC hZ hβ hγ hpin + hfslots hslots hwidth hV hAdvU hVerU hψ0 hQ attempt Accept hAcc + +/-- **Classical ROM soundness (`≤ N / 2 ^ 128` for `6 N ≤ 2 ^ 128`, `127.71b` ideal sponge) for +`ixvm-2p23` up to 4,096 shards.** -/ +theorem ixVm2p23_4096sh_classical_rom_133 + (s₀ : Digest) (sys : System Goldilocks Digest) (B : Bounds) + (hshape : IxVm2p23_4096ShShape sys B) + (hplain : ∀ c ∈ sys.circuits.toList, c.LookupsPlain) + (hmainW : ∀ c ∈ sys.circuits.toList, 0 < c.mainWidth) + (hfixed : sys.FixedOk) (hheightOk : sys.HeightOk) + {N : ℕ} (hN : BoundsLE sys B N) (hNp : N < Goldilocks.order) + (hfslots : 32 ≤ fslots) (hslots : sys.fri.numQueries + 1 ≤ slots) + (hcommit : sys.fri.commitPowBits ≤ width) (hquery : sys.fri.queryPowBits ≤ width) + (hwidth : 32 ≤ width) {A : Type} + {adv : OracleComp (STAnsSponge Goldilocks GoldilocksExt3 Digest Fp3Model fslots slots width) A} + {Q : ℕ} (hadv : adv.QueryBound Q) + (hQ : 6 * (Q + B.shards * shardQueriesPinnedSponge sys B 32) ≤ 2 ^ 128) + (attempt : A → PAttemptPruned Goldilocks GoldilocksExt3 Digest) : + prob (fun out l => + ∃ f : ∀ x, STAnsSponge Goldilocks GoldilocksExt3 Digest Fp3Model fslots slots width x, + (∀ x y, l.dlookup x = some y → f x = y) ∧ + batchPinnedPrunedSpongeAccepts s₀ starkModel sys false f (attempt out.1) = true ∧ + BatchCoveredPinned sys B (attempt out.1) ∧ + BatchViolatesPinnedJ s₀ starkModel sys (553 / 1024) l f (attempt out.1)) + (batchExperimentPinnedSponge s₀ starkModel sys B false adv attempt) [] ≤ + ((Q + B.shards * shardQueriesPinnedSponge sys B 32 : ℕ) : ℝ) / 2 ^ 128 := by + obtain ⟨hdeg, hk, hC, hZ, hβ, hγ, hpin⟩ := ixVm2p23_4096sh_hypotheses hshape + refine soundness_verifyBatchPinnedPrunedSpongeJ_v6_553_133_digest32 B s₀ sys + hshape.hlogBlowup hshape.hnumQueries hshape.hqueryPow hdeg + (fun v hv => by + rw [← hshape.hlogBlowup] + exact tensorChallenges_pshape_le_of_bounds sys hk v hv) + hplain hmainW hfixed hheightOk hN hNp hC hZ hβ hγ hpin + hfslots hslots hcommit hquery hwidth hadv hQ attempt + +/-- **Classical ROM soundness (`≤ N / 2 ^ 128` for `6 N ≤ 2 ^ 128`, `127.71b` ideal sponge) for +transparent Endpoint 1 `ep1-v6-hop4` (8-ary `compact400KBBalanced`).** -/ +theorem ep1V6Hop4_classical_rom_133 + (s₀ : Digest) (sys : System Goldilocks Digest) (B : Bounds) + (hshape : Ep1V6Hop4Shape sys B) + (hplain : ∀ c ∈ sys.circuits.toList, c.LookupsPlain) + (hmainW : ∀ c ∈ sys.circuits.toList, 0 < c.mainWidth) + (hfixed : sys.FixedOk) (hheightOk : sys.HeightOk) + {N : ℕ} (hN : BoundsLE sys B N) (hNp : N < Goldilocks.order) + (hfslots : 32 ≤ fslots) (hslots : 59 ≤ slots) (hwidth : 32 ≤ width) {A : Type} + {adv : OracleComp (STAnsSponge Goldilocks GoldilocksExt3 Digest Fp3Model fslots slots width) A} + {Q : ℕ} (hadv : adv.QueryBound Q) + (hQ : 6 * (Q + B.shards * shardQueriesPinnedSponge sys B 32) ≤ 2 ^ 128) + (attempt : A → PAttemptPruned Goldilocks GoldilocksExt3 Digest) : + prob (fun out l => + ∃ f : ∀ x, STAnsSponge Goldilocks GoldilocksExt3 Digest Fp3Model fslots slots width x, + (∀ x y, l.dlookup x = some y → f x = y) ∧ + batchPinnedPrunedSpongeAccepts s₀ starkModel sys true f (attempt out.1) = true ∧ + BatchCoveredPinned sys B (attempt out.1) ∧ + BatchViolatesPinnedJ s₀ starkModel sys (289 / 1024) l f (attempt out.1)) + (batchExperimentPinnedSponge s₀ starkModel sys B true adv attempt) [] ≤ + ((Q + B.shards * shardQueriesPinnedSponge sys B 32 : ℕ) : ℝ) / 2 ^ 128 := by + obtain ⟨hdeg, hk, hC, hZ, hβ, hγ, hpin⟩ := ep1V6Hop4_hypotheses hshape + have hlb : sys.fri.logBlowup = 4 := by rw [hshape.hfri]; rfl + refine soundness_verifyBatchTensorMultiArityPinnedPrunedSpongeJ_ep1_289_133_digest32 B s₀ sys + hshape.hfri hdeg + (fun v hv => by + rw [← hlb] + exact tensorChallenges_pshape_le_of_bounds sys hk v hv) + hplain hmainW hfixed hheightOk hN hNp hC hZ hβ hγ hpin + hfslots hslots hwidth hadv hQ attempt + +end ConcreteSoundness + +/-! ## 4. Machine-Checked Axiom Audit (`#guard_msgs #print axioms`) -/ + +section AxiomAudit + +/-- info: 'Ix.Cert.Release05.release05_inner_default_ok' does not depend on any axioms -/ +#guard_msgs(whitespace := lax) in +#print axioms Ix.Cert.Release05.release05_inner_default_ok + +/-- info: 'Ix.Cert.Release05.release05_ep1_balanced_ok' does not depend on any axioms -/ +#guard_msgs(whitespace := lax) in +#print axioms Ix.Cert.Release05.release05_ep1_balanced_ok + +/-- info: 'Ix.Cert.Release05.negControl_release05_rejects_unpinned' depends on axioms: [propext] -/ +#guard_msgs(whitespace := lax) in +#print axioms Ix.Cert.Release05.negControl_release05_rejects_unpinned + +/-- info: 'Ix.Cert.Release05.negControl_release05_blake3_256_below_128_classical' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs(whitespace := lax) in +#print axioms Ix.Cert.Release05.negControl_release05_blake3_256_below_128_classical + +/-- info: 'Ix.Cert.Release05.negControl_release05_blake3_256_below_128_qrom' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs(whitespace := lax) in +#print axioms Ix.Cert.Release05.negControl_release05_blake3_256_below_128_qrom + +/-- info: 'Ix.Cert.Release05.negControl_release05_fp3_below_100_qrom' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs(whitespace := lax) in +#print axioms Ix.Cert.Release05.negControl_release05_fp3_below_100_qrom + +/-- info: 'Ix.Cert.Release05.posControl_release05_blake3_256_qrom64_headroom' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs(whitespace := lax) in +#print axioms Ix.Cert.Release05.posControl_release05_blake3_256_qrom64_headroom + +/-- info: 'Ix.Cert.Release05.ixVm2p23_4096sh_balance_lt_p' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs(whitespace := lax) in +#print axioms Ix.Cert.Release05.ixVm2p23_4096sh_balance_lt_p + +/-- info: 'Ix.Cert.Release05.ixVm2p23_64sh_qrom64' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs(whitespace := lax) in +#print axioms Ix.Cert.Release05.ixVm2p23_64sh_qrom64 + +/-- info: 'Ix.Cert.Release05.ixVm2p23_64sh_qrom64_sub_one' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs(whitespace := lax) in +#print axioms Ix.Cert.Release05.ixVm2p23_64sh_qrom64_sub_one + +/-- info: 'Ix.Cert.Release05.ixVm2p23_4096sh_qrom64' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs(whitespace := lax) in +#print axioms Ix.Cert.Release05.ixVm2p23_4096sh_qrom64 + +/-- info: 'Ix.Cert.Release05.ixVm2p23_4096sh_stdQro64' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs(whitespace := lax) in +#print axioms Ix.Cert.Release05.ixVm2p23_4096sh_stdQro64 + +/-- info: 'Ix.Cert.Release05.aggr2p22_16sh_qrom64' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs(whitespace := lax) in +#print axioms Ix.Cert.Release05.aggr2p22_16sh_qrom64 + +/-- info: 'Ix.Cert.Release05.rec2p22_1sh_qrom64' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs(whitespace := lax) in +#print axioms Ix.Cert.Release05.rec2p22_1sh_qrom64 + +/-- info: 'Ix.Cert.Release05.ep1V6Hop4_qrom64' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs(whitespace := lax) in +#print axioms Ix.Cert.Release05.ep1V6Hop4_qrom64 + +/-- info: 'Ix.Cert.Release05.ep1V6Hop4_qrom64_sub_one' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs(whitespace := lax) in +#print axioms Ix.Cert.Release05.ep1V6Hop4_qrom64_sub_one + +/-- info: 'Ix.Cert.Release05.ep1V6Hop4_stdQro64' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs(whitespace := lax) in +#print axioms Ix.Cert.Release05.ep1V6Hop4_stdQro64 + +/-- info: 'Ix.Cert.Release05.ixVm2p23_4096sh_classical_rom_133' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs(whitespace := lax) in +#print axioms Ix.Cert.Release05.ixVm2p23_4096sh_classical_rom_133 + +/-- info: 'Ix.Cert.Release05.ep1V6Hop4_classical_rom_133' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs(whitespace := lax) in +#print axioms Ix.Cert.Release05.ep1V6Hop4_classical_rom_133 + +/-- info: 'CertiFri.P3.GoldilocksExt3.verifyBytesPinned_soundness_v6_553_keyed_133' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs(whitespace := lax) in +#print axioms CertiFri.P3.GoldilocksExt3.verifyBytesPinned_soundness_v6_553_keyed_133 + +/-- info: 'CertiFri.P3.GoldilocksExt3.verifyBytesPinned_soundness_v6_553_keyed_133_bounded' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs(whitespace := lax) in +#print axioms CertiFri.P3.GoldilocksExt3.verifyBytesPinned_soundness_v6_553_keyed_133_bounded + +/-- info: 'CertiFri.P3.VerifyBytesPinnedMultiKeyed.verifyBytesPinned_soundness_ep1Balanced_keyed_checked' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs(whitespace := lax) in +#print axioms CertiFri.P3.VerifyBytesPinnedMultiKeyed.verifyBytesPinned_soundness_ep1Balanced_keyed_checked + +end AxiomAudit + +end Ix.Cert.Release05 diff --git a/Ix/Cli/PureStarkVerifierKernel.lean b/Ix/Cli/PureStarkVerifierKernel.lean index df16c4384c..3b4198f12b 100644 --- a/Ix/Cli/PureStarkVerifierKernel.lean +++ b/Ix/Cli/PureStarkVerifierKernel.lean @@ -1,4 +1,5 @@ import Ix.Cert.MultiStark.Verifier +import Ix.Cert.MultiStark.PinnedVerifier import Ix.Cli.PureStarkVerifier /-! # Pure-Lean Protocol `v6` STARK Verifier Kernel Installer (`Ix.Cli.PureStarkVerifierKernel`) @@ -138,15 +139,13 @@ def validateWeightedBatchRowsFull (sys : StarkSystem) (batch : BatchProof) : Boo if degPos != h.logDegrees.size then return false return true -/-- Production byte-level verifier enforcing `validateWeightedBatchRowsFull` (full `K`-lane -`CALL`-pull + segmented/unsegmented `` row-weight parity against `2^39`) before -delegating to `Ix.Cert.MultiStark.verifyBatchBytesTensorCapped`. -/ +/-- Production byte-level verifier routing directly through the formally certified +`CertiFri.Stark.Profile.verifyBytesPinned` verifier with Ix's `validate_preamble` policy +(`stage_1_pinning = 1`, Release 0.5 security floor, active-preprocessed parity, `MEMSEG = 16` +closure pairs, full `K`-lane `CALL`-pull + `` `2^39` weighted row bound, strict +zero-PoW witness admissibility, and Tier-2 tensor challenge cap `kCol + kOpen ≤ 32`). -/ def verifyBatchBytesFull (vkBytes claimsBytes proofBytes : ByteArray) : Bool := - match StarkSystem.fromBytes vkBytes, BatchProof.fromBytes proofBytes with - | .ok sys, .ok batch => - validateWeightedBatchRowsFull sys batch && - Ix.Cert.MultiStark.verifyBatchBytesTensorCapped vkBytes claimsBytes proofBytes none - | _, _ => false + Ix.Cert.MultiStark.PinnedVerifier.verifyBytesPinnedProduction vkBytes claimsBytes proofBytes /-- Production pure-Lean Protocol `v6` batch verifier backend enforcing the 128-bit security floor, active-preprocessed parity, full `K`-lane row-weight parity (`D1-6`), diff --git a/Ix/Common.lean b/Ix/Common.lean index 14b52c0f81..fe165ddd2f 100644 --- a/Ix/Common.lean +++ b/Ix/Common.lean @@ -5,6 +5,7 @@ public import Lean.Expr public import Lean.Declaration public import Lean.Environment public import Lean.Elab.Frontend +import Std.Sync.Mutex public section @@ -322,14 +323,24 @@ def checkToolchain : IO Unit := do if version != expectedVersion then IO.println s!"Warning: expected toolchain '{expectedVersion}' but got '{version}'" +private initialize leanImportMutex : Std.Mutex Unit ← Std.Mutex.new () + +/-- Serialize `Lean.enableInitializersExecution` + `importModules` / `processHeader` + across concurrent threads: `enableInitializersExecution` sets a process-global + flag that `importModules` resets on completion, and `initSearchPath` mutates + process-global `Lean.searchPathRef`. -/ +def _root_.Ix.withImportLock (action : IO α) : IO α := + leanImportMutex.atomically action + open Elab in open System (FilePath) in def runFrontend (input : String) (filePath : FilePath) : IO Environment := do checkToolchain let inputCtx := Parser.mkInputContext input filePath.toString let (header, parserState, messages) ← Parser.parseHeader inputCtx - unsafe enableInitializersExecution -- required for `processHeader`'s `loadExts := true` import - let (env, messages) ← processHeader header default messages inputCtx 0 + let (env, messages) ← _root_.Ix.withImportLock do + unsafe enableInitializersExecution -- required for `processHeader`'s `loadExts := true` import + processHeader header default messages inputCtx 0 let env := env.setMainModule default let commandState := Command.mkState env messages default let s ← IO.processCommands inputCtx parserState commandState diff --git a/Ix/Compile/SourceContract/Elab.lean b/Ix/Compile/SourceContract/Elab.lean index 9bc7f28be3..6477049fcd 100644 --- a/Ix/Compile/SourceContract/Elab.lean +++ b/Ix/Compile/SourceContract/Elab.lean @@ -6,7 +6,7 @@ public meta import Ix.Compile.SourceContract.Registry public meta import Ix.Compile.SourceContract.Syntax /-! -# Scoped `@`-prefixed mode syntax elaboration +# Scoped `@[...]` mode syntax elaboration Activates strictly under `open scoped Ix.Modes` (`namespace Ix.Modes`). Elaborates: @@ -15,9 +15,9 @@ Elaborates: - Result modes (4) after `:` in `def`/`abbrev`/`opaque`/`axiom`, after `→`/`->`, and after `∀ ...,` - `let` and `do`-block `let` (8 modes, unparenthesized, optional `: T`, - including `let @borrow v := owner`) -- `structure` and `inductive` field modes (`@shared` -> `FieldMode.shared`, - `@erased` -> constructor binder `.erased`) + including `let @[borrow] v := owner`) +- `structure` and `inductive` field modes (`@[shared]` -> `FieldMode.shared`, + `@[erased]` -> constructor binder `.erased`) - Native scoped `DefAsserts` attributes (`@[no_rc]`, `@[no_alloc]`, `@[bounded_stack]`) -/ @@ -28,11 +28,15 @@ namespace Ix.Compile.SourceElab open Lean Elab Command Term +private meta def modePrefixAtoms (modes : Syntax) : Array Syntax := + modes[0].getArgs.foldl (init := #[]) fun acc attr => + acc ++ attr[1].getSepArgs + private meta def atomKeyword (atomNode : Syntax) : String := - if atomNode.getNumArgs >= 2 && atomNode[1].isAtom then atomNode[1].getAtomVal else "" + if atomNode.getNumArgs >= 1 && atomNode[0].isAtom then atomNode[0].getAtomVal else "" private meta def decodeBinderPrefix (modes : Syntax) : TermElabM Ixon.BinderMode := do - let parts := modes[0].getArgs + let parts := modePrefixAtoms modes let mut hasBorrowed := false let mut hasUnique := false let mut hasOnce := false @@ -41,25 +45,25 @@ private meta def decodeBinderPrefix (modes : Syntax) : TermElabM Ixon.BinderMode let kw := atomKeyword part match kw with | "borrowed" => - if hasBorrowed then throwErrorAt part "duplicate @borrowed mode annotation" + if hasBorrowed then throwErrorAt part "duplicate @[borrowed] mode annotation" hasBorrowed := true | "unique" => - if hasUnique then throwErrorAt part "duplicate @unique mode annotation" + if hasUnique then throwErrorAt part "duplicate @[unique] mode annotation" hasUnique := true | "once" => - if hasOnce then throwErrorAt part "duplicate @once mode annotation" + if hasOnce then throwErrorAt part "duplicate @[once] mode annotation" hasOnce := true | "erased" => - if hasErased then throwErrorAt part "duplicate @erased mode annotation" + if hasErased then throwErrorAt part "duplicate @[erased] mode annotation" hasErased := true | _ => - throwErrorAt part "unsupported binder mode annotation '@{kw}'" + throwErrorAt part "unsupported binder mode annotation '@[{kw}]'" if hasErased then if hasBorrowed || hasUnique || hasOnce then - throwErrorAt modes "@erased cannot be combined with other mode annotations" + throwErrorAt modes "@[erased] cannot be combined with other mode annotations" return .erased if hasOnce && hasUnique then - throwErrorAt modes "@once cannot be combined with @unique" + throwErrorAt modes "@[once] cannot be combined with @[unique]" match hasUnique, hasOnce, hasBorrowed with | true, false, false => return .unique | true, false, true => return .uniqueBorrowed @@ -69,24 +73,24 @@ private meta def decodeBinderPrefix (modes : Syntax) : TermElabM Ixon.BinderMode | _, _, _ => return .many private meta def decodeResultPrefix (modes : Syntax) : TermElabM Ixon.ResultMode := do - let parts := modes[0].getArgs + let parts := modePrefixAtoms modes let mut hasBorrowed := false let mut hasUnique := false for part in parts do let kw := atomKeyword part match kw with | "borrowed" => - if hasBorrowed then throwErrorAt part "duplicate @borrowed mode annotation" + if hasBorrowed then throwErrorAt part "duplicate @[borrowed] mode annotation" hasBorrowed := true | "unique" => - if hasUnique then throwErrorAt part "duplicate @unique mode annotation" + if hasUnique then throwErrorAt part "duplicate @[unique] mode annotation" hasUnique := true | "once" => - throwErrorAt part "@once is not a valid result mode; result modes allow only @unique and @borrowed" + throwErrorAt part "@[once] is not a valid result mode; result modes allow only @[unique] and @[borrowed]" | "erased" => - throwErrorAt part "@erased is not a valid result mode; result modes allow only @unique and @borrowed" + throwErrorAt part "@[erased] is not a valid result mode; result modes allow only @[unique] and @[borrowed]" | _ => - throwErrorAt part "unsupported result mode annotation '@{kw}'" + throwErrorAt part "unsupported result mode annotation '@[{kw}]'" match hasUnique, hasBorrowed with | true, true => return .uniqueBorrowed | true, false => return .unique @@ -94,7 +98,7 @@ private meta def decodeResultPrefix (modes : Syntax) : TermElabM Ixon.ResultMode | false, false => return .shared private meta def decodeLetPrefix (modes : Syntax) : TermElabM (Ixon.BinderMode × Bool) := do - let parts := modes[0].getArgs + let parts := modePrefixAtoms modes let mut hasBorrow := false let mut hasBorrowed := false let mut hasUnique := false @@ -104,32 +108,32 @@ private meta def decodeLetPrefix (modes : Syntax) : TermElabM (Ixon.BinderMode let kw := atomKeyword part match kw with | "borrow" => - if hasBorrow then throwErrorAt part "duplicate @borrow mode annotation" + if hasBorrow then throwErrorAt part "duplicate @[borrow] mode annotation" hasBorrow := true | "borrowed" => - if hasBorrowed then throwErrorAt part "duplicate @borrowed mode annotation" + if hasBorrowed then throwErrorAt part "duplicate @[borrowed] mode annotation" hasBorrowed := true | "unique" => - if hasUnique then throwErrorAt part "duplicate @unique mode annotation" + if hasUnique then throwErrorAt part "duplicate @[unique] mode annotation" hasUnique := true | "once" => - if hasOnce then throwErrorAt part "duplicate @once mode annotation" + if hasOnce then throwErrorAt part "duplicate @[once] mode annotation" hasOnce := true | "erased" => - if hasErased then throwErrorAt part "duplicate @erased mode annotation" + if hasErased then throwErrorAt part "duplicate @[erased] mode annotation" hasErased := true | _ => - throwErrorAt part "unsupported let mode annotation '@{kw}'" + throwErrorAt part "unsupported let mode annotation '@[{kw}]'" if hasBorrow then if hasBorrowed || hasUnique || hasOnce || hasErased then - throwErrorAt modes "@borrow cannot be combined with other mode annotations" + throwErrorAt modes "@[borrow] cannot be combined with other mode annotations" return (.borrowed, true) if hasErased then if hasBorrowed || hasUnique || hasOnce then - throwErrorAt modes "@erased cannot be combined with other mode annotations" + throwErrorAt modes "@[erased] cannot be combined with other mode annotations" return (.erased, false) if hasOnce && hasUnique then - throwErrorAt modes "@once cannot be combined with @unique" + throwErrorAt modes "@[once] cannot be combined with @[unique]" let mode : Ixon.BinderMode := match hasUnique, hasOnce, hasBorrowed with | true, false, false => .unique | true, false, true => .uniqueBorrowed @@ -145,25 +149,25 @@ private meta inductive FieldAnnotation where deriving BEq, DecidableEq, Repr private meta def decodeFieldPrefix (modes : Syntax) : TermElabM FieldAnnotation := do - let parts := modes[0].getArgs + let parts := modePrefixAtoms modes let mut hasShared := false let mut hasErased := false for part in parts do let kw := atomKeyword part match kw with | "shared" => - if hasShared then throwErrorAt part "duplicate @shared mode annotation" + if hasShared then throwErrorAt part "duplicate @[shared] mode annotation" hasShared := true | "erased" => - if hasErased then throwErrorAt part "duplicate @erased mode annotation" + if hasErased then throwErrorAt part "duplicate @[erased] mode annotation" hasErased := true | _ => - throwErrorAt part "@{kw} is not a valid field mode; structure and inductive fields only allow @shared or @erased" + throwErrorAt part "@[{kw}] is not a valid field mode; structure and inductive fields only allow @[shared] or @[erased]" if hasShared && hasErased then - throwErrorAt modes "@erased cannot be combined with @shared on a field" + throwErrorAt modes "@[erased] cannot be combined with @[shared] on a field" if hasShared then return .shared if hasErased then return .erased - throwErrorAt modes "expected @shared or @erased field mode" + throwErrorAt modes "expected @[shared] or @[erased] field mode" private meta def sourceOrigin (stx : Syntax) : Nat := (stx.getPos?.map (·.byteIdx)).getD 0 @@ -547,7 +551,7 @@ meta def elabDeclaration : CommandElab := fun stx => do | .error error => throwErrorAt stx "{error}" setEnv env -/-! ### Structure & inductive field elaborators (`@shared`, `@erased`) -/ +/-! ### Structure & inductive field elaborators (`@[shared]`, `@[erased]`) -/ private meta def registerCtorFieldAnnotations (ref : Syntax) (ctorName : Lean.Name) (indexed : Array (Nat × FieldAnnotation)) : CommandElabM Unit := do @@ -584,10 +588,12 @@ meta def elabAnnotatedStructure : CommandElab := fun stx => do for field in rawFields do let k := field.getKind if k == ``SourceSyntax.structAnnotatedSimpleField then - let ann ← liftTermElabM (decodeFieldPrefix field[1]) - fieldAnns := fieldAnns.push (field[2].getId, ann) + let ann ← liftTermElabM (decodeFieldPrefix field[2]) + fieldAnns := fieldAnns.push (field[3].getId, ann) + let declMods := (mkNode ``Parser.Command.declModifiers + #[field[0], mkNullNode, field[1], mkNullNode, mkNullNode, mkNullNode]).raw plainFields := plainFields.push <| - (mkNode ``Parser.Command.structSimpleBinder #[field[0], field[2], field[3], field[4]]).raw + (mkNode ``Parser.Command.structSimpleBinder #[declMods, field[3], field[4], field[5]]).raw else if k == ``SourceSyntax.structAnnotatedExplicitBinder then let ann ← liftTermElabM (decodeFieldPrefix field[2]) for id in field[3].getArgs do diff --git a/Ix/Compile/SourceContract/Syntax.lean b/Ix/Compile/SourceContract/Syntax.lean index 89a3c43b93..661d0187f5 100644 --- a/Ix/Compile/SourceContract/Syntax.lean +++ b/Ix/Compile/SourceContract/Syntax.lean @@ -3,12 +3,13 @@ module public import Lean /-! -# Scoped `@`-prefixed mode keyword grammar +# Scoped `@[...]` mode attribute grammar -All modifier atoms use `atomic ("@" >> checkNoWsBefore ... >> nonReservedSymbol w)` -so ZERO tokens are added to Lean's global `TokenTable`. Parsers are NOT registered -globally here; `Ix.Compile.SourceContract.Elab` registers them `scoped` under -`namespace Ix.Modes` (`open scoped Ix.Modes`). +All modifier atoms use `atomic ("@[" >> sepBy1 ... "," >> "]")` with +`nonReservedSymbol` so ZERO tokens are added to Lean's global `TokenTable` +(`"@["`, `","`, and `"]"` are already built-in Lean tokens). Parsers are NOT +registered globally here; `Ix.Compile.SourceContract.Elab` registers them `scoped` +under `namespace Ix.Modes` (`open scoped Ix.Modes`). -/ public meta section @@ -17,32 +18,44 @@ namespace Ix.Compile.SourceSyntax open Lean Parser -/-- Parse an `@`-prefixed mode keyword without adding any token to `TokenTable`. -/ +/-- Parse a mode keyword without adding any token to `TokenTable`. -/ @[expose] def modeKw (w : String) : Parser := - atomic ("@" >> checkNoWsBefore "no space after @" >> nonReservedSymbol w) + nonReservedSymbol w /-! ### Mode prefixes -/ @[expose] def binderModeAtom := leading_parser modeKw "borrowed" <|> modeKw "unique" <|> modeKw "once" <|> modeKw "erased" -@[expose] def binderModePrefix := leading_parser many1 binderModeAtom +@[expose] def binderModeAttr := leading_parser + atomic ("@[" >> sepBy1 binderModeAtom "," >> "]") + +@[expose] def binderModePrefix := leading_parser many1 binderModeAttr @[expose] def resultModeAtom := leading_parser modeKw "borrowed" <|> modeKw "unique" <|> modeKw "once" <|> modeKw "erased" -@[expose] def resultModePrefix := leading_parser many1 resultModeAtom +@[expose] def resultModeAttr := leading_parser + atomic ("@[" >> sepBy1 resultModeAtom "," >> "]") + +@[expose] def resultModePrefix := leading_parser many1 resultModeAttr @[expose] def letModeAtom := leading_parser modeKw "borrowed" <|> modeKw "unique" <|> modeKw "once" <|> modeKw "erased" <|> modeKw "borrow" -@[expose] def letModePrefix := leading_parser many1 letModeAtom +@[expose] def letModeAttr := leading_parser + atomic ("@[" >> sepBy1 letModeAtom "," >> "]") + +@[expose] def letModePrefix := leading_parser many1 letModeAttr @[expose] def fieldModeAtom := leading_parser modeKw "shared" <|> modeKw "erased" <|> modeKw "borrowed" <|> modeKw "unique" <|> modeKw "once" <|> modeKw "borrow" -@[expose] def fieldModePrefix := leading_parser many1 fieldModeAtom +@[expose] def fieldModeAttr := leading_parser + atomic ("@[" >> sepBy1 fieldModeAtom "," >> "]") + +@[expose] def fieldModePrefix := leading_parser many1 fieldModeAttr /-! ### Annotated binders (all 4 bracket kinds, multi-name groups, optional `: T`) -/ @@ -147,10 +160,10 @@ open Lean Parser @[expose] def doAnnotatedLet := leading_parser "let " >> atomic letModePrefix >> Term.binderIdent >> Term.optType >> " := " >> termParser -/-! ### Structure & inductive fields (`@shared`, `@erased`) -/ +/-! ### Structure & inductive fields (`@[shared]`, `@[erased]`) -/ @[expose] def structAnnotatedSimpleField := leading_parser - atomic (Command.declModifiers true >> fieldModePrefix) >> ident >> + atomic (optional Command.docComment >> optional Command.visibility >> fieldModePrefix) >> ident >> Command.optDeclSig >> optional (Term.binderTactic <|> Term.binderDefault) @[expose] def structAnnotatedExplicitBinder := leading_parser diff --git a/Ix/Frontend.lean b/Ix/Frontend.lean new file mode 100644 index 0000000000..b941dd64d3 --- /dev/null +++ b/Ix/Frontend.lean @@ -0,0 +1,239 @@ +/- + Ix/Frontend.lean + + Top-level entry point for the pure, deterministic Ix frontend: + 1. `Text -> Stx` (`parseSource`, `parseModule`) + 2. `Stx -> ModuleIndex -> ScheduledSCCs` (`buildModuleIndex`, `scheduleModuleDecls`) + 3. `Stx -> IxElabEnv` (`elabModuleSyntax`, `elabSource`) + - Substructural usage (`0`, `1`, `&`, unmarked `many`), ownership (`!`, unmarked `shared`), + and relative locality (`~`, unmarked `unrestricted`), plus `let borrow`. + - Order-free and `mutual`-free declarations via Tarjan SCC condensation. + - In-elaborator block and constructor canonicalization (breaking constructor α-ties + by source declaration order to avoid call-site rewrites). + - Surgery-free generation of `.rec`, `.recOn`, `.casesOn`, `._ctorIdx`, and structure projections. + - First-class content-hash references (`#<64-hex>`) and programmable `map Name := #` imports. + 4. `IxElabEnv -> Ixon.Env` (`compileElabEnvToIxon`, `compileSourceToIxon`) + 5. `Ixon.Env -> Ix.Resource.AddressedProgram` (`checkSourceResources`) +-/ +module + +public import Ix.Frontend.Syntax +public import Ix.Frontend.Parser.Trie +public import Ix.Frontend.Parser.Types +public import Ix.Frontend.Parser.Basic +public import Ix.Frontend.Parser.Term +public import Ix.Frontend.Parser.Command +public import Ix.Frontend.Scope +public import Ix.Frontend.SccPass +public import Ix.Frontend.Elab.Monad +public import Ix.Frontend.Elab.Meta +public import Ix.Frontend.CanonBlock +public import Ix.Frontend.AuxGen +public import Ix.Frontend.Elab.Tactic +public import Ix.Frontend.Elab.Term +public import Ix.Frontend.Elab.Command +public import Ix.Frontend.Merge +public import Ix.Frontend.Format +public import Ix.Claim +public import Ix.Ixon.ElabClaim +public import Ix.GraphM +public import Ix.CondenseM +public import Ix.CompileDriver +public import Ix.DecompileM +public import Ix.Cert.Compile +public import Ix.ModeCheck + +@[expose] public section + +namespace Ix.Frontend + +open Parser Elab + +/-- Hydrate an `IxElabEnv` from a compiled `Ixon.Env` (decompiling constants, reconstructing + `StructInfo` tables, and registering `Name -> Address` mappings in `importMap`). -/ +def IxElabEnv.ofIxonEnv (ixe : Ixon.Env) : IxElabEnv := + let (rawConsts, _errs) := Ix.DecompileM.decompileAllParallel ixe + let initIxEnv : Ix.Environment := + { consts := @Std.HashMap.emptyWithCapacity Ix.Name Ix.ConstantInfo Ix.Name.instBEq Ix.Name.instHashable rawConsts.size } + let ixEnv := rawConsts.fold (fun acc nm ci => + { consts := acc.consts.insert (Name.rehash nm) (Expr.ConstantInfo.rehash ci) }) initIxEnv + let base := IxElabEnv.ofIxEnvironment ixEnv + let impMap := ixe.named.fold (fun acc nm named => acc.insertName nm named.addr) base.importMap + base.withImportMap impMap + +/-- Parse an Ix source string into a concrete syntax tree (`SyntaxKind.moduleKind`). -/ +def parseSource (input : String) (fileName : String := "") + (pEnv : IxParserEnv := defaultParserEnv) : + Except String (Stx × IxParserEnv) := + parseModuleWithEnv input fileName pEnv + +/-- Compile an elaborated `IxElabEnv` into a canonical `Ixon.Env` and `Ix.CompileM.CompileEnv` + using the pure Lean compilation pipeline (`GraphM.envSerial` -> `CondenseM.run` -> `compileEnvFold`). -/ +def compileElabEnvToIxon (elabEnv : IxElabEnv) : + Except String (Ixon.Env × Ix.CompileM.CompileEnv) := do + let ixEnv := elabEnv.toIxEnvironment + let outRefs := Ix.GraphM.envSerial ixEnv + let condensed := Ix.CondenseM.run outRefs + let (ixonEnv, _totalBytes, cenv) ← Ix.CompileM.compileEnvFold ixEnv condensed (width := 1) + if !cenv.ungrounded.isEmpty then + let firstErr := match cenv.ungrounded.toList.head? with + | some (nm, msg) => s!"{nm}: {msg}" + | none => "" + throw s!"compileElabEnvToIxon: {cenv.ungrounded.size} ungrounded constant(s), first: {firstErr}" + return (ixonEnv, cenv) + +/-- Compile an elaborated `IxElabEnv` through the formally certified compiler (`Ix.Cert.compileReport`). -/ +def compileElabEnvCertified (elabEnv : IxElabEnv) : + Except String (Ixon.Env × Ix.Cert.Failures) := do + let (ixonEnv, failures) ← Ix.Cert.compileReport elabEnv.toIxEnvironment + if !failures.isEmpty then + throw s!"compileElabEnvCertified: {failures.toMap.size} failure(s) in Ix.Cert.compileReport" + return (ixonEnv, failures) + +/-- Parse, elaborate, canonicalize, and compile an Ix source string to `Ixon.Env` purely. -/ +def compileSourceToIxon (input : String) + (fileName : String := "") + (initElabEnv : IxElabEnv := IxElabEnv.empty) + (initParserEnv : IxParserEnv := defaultParserEnv) + (seedPrelude : Bool := true) : + Except String (Stx × IxElabEnv × Ixon.Env × Ix.CompileM.CompileEnv) := do + let (stx, _pEnv) ← parseModuleWithEnv input fileName initParserEnv + let elabEnv ← elabModuleSyntax stx initElabEnv seedPrelude + let (ixonEnv, cenv) ← compileElabEnvToIxon elabEnv + return (stx, elabEnv, ixonEnv, cenv) + +/-- Parse, elaborate, canonicalize, and compile an Ix source string through `Ix.Cert.compileReport`. -/ +def compileSourceCertified (input : String) + (fileName : String := "") + (initElabEnv : IxElabEnv := IxElabEnv.empty) + (initParserEnv : IxParserEnv := defaultParserEnv) + (seedPrelude : Bool := true) : + Except String (Stx × IxElabEnv × Ixon.Env × Ix.Cert.Failures) := do + let (stx, _pEnv) ← parseModuleWithEnv input fileName initParserEnv + let elabEnv ← elabModuleSyntax stx initElabEnv seedPrelude + let (ixonEnv, failures) ← compileElabEnvCertified elabEnv + return (stx, elabEnv, ixonEnv, failures) + +/-- Topologically elaborate a multi-module DAG and compile the resulting environment to `Ixon.Env`. -/ +def compileModuleDAGToIxon (modules : List (Ix.Name × String)) + (initElabEnv : IxElabEnv := IxElabEnv.empty) + (initParserEnv : IxParserEnv := defaultParserEnv) + (seedPrelude : Bool := true) : + Except String (IxElabEnv × IxParserEnv × Ixon.Env × Ix.CompileM.CompileEnv) := do + let (elabEnv, parserEnv) ← elabModuleDAG modules initElabEnv initParserEnv seedPrelude + let (ixonEnv, cenv) ← compileElabEnvToIxon elabEnv + return (elabEnv, parserEnv, ixonEnv, cenv) + +/-- Topologically elaborate a multi-module DAG and compile through `Ix.Cert.compileReport`. -/ +def compileModuleDAGCertified (modules : List (Ix.Name × String)) + (initElabEnv : IxElabEnv := IxElabEnv.empty) + (initParserEnv : IxParserEnv := defaultParserEnv) + (seedPrelude : Bool := true) : + Except String (IxElabEnv × IxParserEnv × Ixon.Env × Ix.Cert.Failures) := do + let (elabEnv, parserEnv) ← elabModuleDAG modules initElabEnv initParserEnv seedPrelude + let (ixonEnv, failures) ← compileElabEnvCertified elabEnv + return (elabEnv, parserEnv, ixonEnv, failures) + +/-- Parse, elaborate, canonicalize, compile to `Ixon.Env`, and run deterministic + substructural mode checking (`Ix.ModeCheck.checkArtifact`). -/ +def checkSourceResources (input : String) + (fileName : String := "") + (initElabEnv : IxElabEnv := IxElabEnv.empty) + (initParserEnv : IxParserEnv := defaultParserEnv) + (seedPrelude : Bool := true) : + Except String (Stx × IxElabEnv × Ixon.Env × String) := do + let (stx, elabEnv, ixonEnv, _cenv) ← + compileSourceToIxon input fileName initElabEnv initParserEnv seedPrelude + let verdict ← Ix.ModeCheck.checkArtifact ixonEnv + return (stx, elabEnv, ixonEnv, verdict) + +/-- Compute the content address of a source string (BLAKE3 over UTF-8 bytes). -/ +def hashSourceText (input : String) : Address := + Address.admissionHash input.toUTF8 + +/-- Compute the canonical content address of a `Stx` tree (BLAKE3 Merkle hash). -/ +def hashSyntax : Stx → Address + | .missing => + Address.admissionHash (ByteArray.mk #[0x00]) + | .atom _ val => + Address.admissionHash (ByteArray.mk #[0x01] ++ Sym.toByteArray val) + | .ident _ _ val => + Address.admissionHash (ByteArray.mk #[0x02] ++ (Name.computeHash (FName.toIxName val)).hash) + | .node _ kind args => + let header := ByteArray.mk #[0x03] ++ (Name.computeHash (FName.toIxName kind)).hash + let payload := hashSyntaxList args header + Address.admissionHash payload + | .snil | .scons .. => + Address.admissionHash (ByteArray.mk #[0x00]) +where + hashSyntaxList : Stx → ByteArray → ByteArray + | .scons h t, acc => hashSyntaxList t (acc ++ (hashSyntax h).hash) + | _, acc => acc + +/-- Compute the canonical commitment address of a compiled `Ixon.Env` (BLAKE3 over `Ixon.serEnv`). -/ +def hashIxonEnv (ixonEnv : Ixon.Env) : Except String Address := do + let bytes ← Ixon.serEnv ixonEnv + return Address.admissionHash bytes + +/-- Construct an `Ixon.ElabClaim` (`kind = .ixonEnv`) from a source string by running + the pure Ix parser, elaborator, canonicalizer, and Ixon compiler. -/ +def mkElabClaimFromSource (input : String) + (fileName : String := "") + (initElabEnv : IxElabEnv := IxElabEnv.empty) + (initParserEnv : IxParserEnv := defaultParserEnv) + (seedPrelude : Bool := true) : + Except String (Ixon.ElabClaim × Stx × IxElabEnv × Ixon.Env) := do + let (stx, elabEnv, ixonEnv, _cenv) ← + compileSourceToIxon input fileName initElabEnv initParserEnv seedPrelude + let sourceAddr := hashSourceText input + let syntaxAddr := hashSyntax stx + let outputAddr ← hashIxonEnv ixonEnv + let claim : Ixon.ElabClaim := { + kind := .ixonEnv + seedPrelude + sourceAddr + outputAddr + syntaxAddr := some syntaxAddr + } + return (claim, stx, elabEnv, ixonEnv) + +/-- Purely verify an `Ixon.ElabClaim` (`kind = .ixonEnv`) against a source text string: + 1. Checks `hashSourceText input == claim.sourceAddr` + 2. Parses `input -> stx` and checks `claim.syntaxAddr` (when present) + 3. Elaborates and compiles `stx -> ixonEnv` and checks `hashIxonEnv ixonEnv == claim.outputAddr` -/ +def verifyElabClaimPure (claim : Ixon.ElabClaim) (input : String) + (fileName : String := "") + (initElabEnv : IxElabEnv := IxElabEnv.empty) + (initParserEnv : IxParserEnv := defaultParserEnv) : Except String Bool := do + if claim.kind != .ixonEnv || hashSourceText input != claim.sourceAddr then + return false + let (stx, _pEnv) ← parseModuleWithEnv input fileName initParserEnv + if let some expectedStx := claim.syntaxAddr then + if hashSyntax stx != expectedStx then + return false + let elabEnv ← elabModuleSyntax stx initElabEnv claim.seedPrelude + let (ixonEnv, _cenv) ← compileElabEnvToIxon elabEnv + let envAddr ← hashIxonEnv ixonEnv + return envAddr == claim.outputAddr + +/-- Purely verify an `Ixon.ElabClaim` (`kind = .ixonEnv`) against a source text string using + certificate-guided elaboration (`elabModuleWithHints`) for `O(|stx|)` zero-metavariable verification. -/ +def verifyElabClaimWithHintsPure (claim : Ixon.ElabClaim) (input : String) + (hints : ElabHints) + (fileName : String := "") + (initElabEnv : IxElabEnv := IxElabEnv.empty) + (initParserEnv : IxParserEnv := defaultParserEnv) : Except String Bool := do + if claim.kind != .ixonEnv || hashSourceText input != claim.sourceAddr then + return false + let (stx, _pEnv) ← parseModuleWithEnv input fileName initParserEnv + if let some expectedStx := claim.syntaxAddr then + if hashSyntax stx != expectedStx then + return false + let elabEnv ← elabModuleWithHints stx hints initElabEnv claim.seedPrelude + let (ixonEnv, _cenv) ← compileElabEnvToIxon elabEnv + let envAddr ← hashIxonEnv ixonEnv + return envAddr == claim.outputAddr + +end Ix.Frontend + +end diff --git a/Ix/Frontend/AuxGen.lean b/Ix/Frontend/AuxGen.lean new file mode 100644 index 0000000000..4683aa365e --- /dev/null +++ b/Ix/Frontend/AuxGen.lean @@ -0,0 +1,704 @@ +/- + Ix.Frontend.AuxGen: Surgery-Free Auxiliary Definition Generator for the Ix Frontend. + + Because the Ix Frontend canonicalizes mutual inductive blocks and constructor + orders BEFORE generating recursors and auxiliary definitions (`Ix.Frontend.CanonBlock`), + all generated auxiliaries (`.rec`, `.recOn`, `.casesOn`, `._ctorIdx`, and structure + field projections) are constructed directly in canonical constructor order with + zero post-hoc environment surgery! + + Written with pure structural recursion (zero `Id.run do`, `for ... in`, `let mut`, + or `Array.forIn'`) so `IxCC` compiles `AuxGen` cleanly with zero higher-order + `ForIn`/`StateT` monomorphization overhead. +-/ +module + +public import Ix.Frontend.CanonBlock + +@[expose] public section + +namespace Ix.Frontend.AuxGen + +open Ix.Frontend +open Ix.Frontend.Elab + +/-! ## Pure Helpers (Zero `ForIn` / `Nat.repr` Overhead) -/ + +def natDigitStr (d : Nat) : String := + if d == 0 then str% "0" + else if d == 1 then str% "1" + else if d == 2 then str% "2" + else if d == 3 then str% "3" + else if d == 4 then str% "4" + else if d == 5 then str% "5" + else if d == 6 then str% "6" + else if d == 7 then str% "7" + else if d == 8 then str% "8" + else str% "9" + +def natToStrAux : Nat → Nat → String → String + | 0, _, acc => acc + | f + 1, n, acc => + let acc' := strAppendPure (natDigitStr (n % 10)) acc + let q := n / 10 + if q == 0 then acc' + else natToStrAux f q acc' + +def natToStrPure (n : Nat) : String := + if n == 0 then str% "0" else natToStrAux 16 n (str% "") + +/-- A local binder declaration in pure FVar space for `AuxGen`. -/ +structure AuxLocalDecl where + fvarId : Ix.Name + binderName : Ix.Name + domain : Ix.Expr + binderInfo : Lean.BinderInfo := .default + deriving Repr + +instance : Inhabited AuxLocalDecl where + default := { + fvarId := Name.mkAnon + binderName := Name.mkAnon + domain := Expr.mkBVar 0 + binderInfo := .default + } + +@[inline] def arrAppend {α : Type} (a b : Array α) : Array α := + Array.mk (a.toList ++ b.toList) + +def mapDeclsToFVars : List AuxLocalDecl → List Ix.Expr + | [] => [] + | d :: rest => Expr.mkFVar d.fvarId :: mapDeclsToFVars rest + +def mapDeclsSetBinderInfo (bi : Lean.BinderInfo) : List AuxLocalDecl → List AuxLocalDecl + | [] => [] + | d :: rest => { d with binderInfo := bi } :: mapDeclsSetBinderInfo bi rest + +def mapNamesToLevels : List Ix.Name → List Ix.Level + | [] => [] + | n :: rest => Level.mkParam n :: mapNamesToLevels rest + +def mapIndItemsNames : List (Ix.InductiveVal × Array Ix.ConstructorVal) → List Ix.Name + | [] => [] + | (iv, _) :: rest => iv.cnst.name :: mapIndItemsNames rest + +def listHasName (target : Ix.Name) : List Ix.Name → Bool + | [] => false + | n :: rest => if n == target then true else listHasName target rest + +/-- Create a deterministic fresh FVar `(fvarId, Expr.mkFVar fvarId)` (abstracted before return). -/ +def mkAuxFVar (pfx : String) (idx : Nat) : Ix.Name × Ix.Expr := + let id := Name.mkNat (Name.simple pfx) idx + (id, Expr.mkFVar id) + +/-- Peel up to `maxBinders` leading `.forallE` binders of `e`, substituting fresh FVars + with prefix `pfx` starting at `startIdx`. Returns `(fvars, decls, remainingBody)`. -/ +def openForallTelescope : Nat → Ix.Expr → String → Nat → Array Ix.Expr → Array AuxLocalDecl → + Array Ix.Expr × Array AuxLocalDecl × Ix.Expr + | 0, e, _, _, fvars, decls => (fvars, decls, e) + | n + 1, e, pfx, idx, fvars, decls => + match stripMData e with + | .forallE nm dom body bi _ => + let (fvId, fvExpr) := mkAuxFVar pfx idx + let bodyInst := instantiate1 body fvExpr + let decl : AuxLocalDecl := { fvarId := fvId, binderName := nm, domain := dom, binderInfo := bi } + openForallTelescope n bodyInst pfx (idx + 1) (fvars.push fvExpr) (decls.push decl) + | _ => (fvars, decls, e) + +/-- Count total leading `.forallE` binders of `e` (bounded by `fuel`). -/ +def countForalls : Nat → Ix.Expr → Nat + | 0, _ => 0 + | fuel + 1, e => + match stripMData e with + | .forallE _ _ body _ _ => 1 + countForalls fuel body + | _ => 0 + +def closeForallsRev : List AuxLocalDecl → Ix.Expr → Ix.Expr + | [], body => body + | d :: rest, body => + let bName := if Name.isAnonymous d.binderName then Name.simple (str% "x") else d.binderName + closeForallsRev rest (Expr.mkForallE bName d.domain (abstractFVar d.fvarId body) d.binderInfo) + +/-- Close an expression `body` over `decls` into nested `.forallE` binders. -/ +def closeForalls (decls : Array AuxLocalDecl) (body : Ix.Expr) : Ix.Expr := + closeForallsRev decls.toList.reverse body + +def closeLambdasRev : List AuxLocalDecl → Ix.Expr → Ix.Expr + | [], body => body + | d :: rest, body => + let bName := if Name.isAnonymous d.binderName then Name.simple (str% "x") else d.binderName + closeLambdasRev rest (Expr.mkLam bName d.domain (abstractFVar d.fvarId body) d.binderInfo) + +/-- Close an expression `body` over `decls` into nested `.lam` binders. -/ +def closeLambdas (decls : Array AuxLocalDecl) (body : Ix.Expr) : Ix.Expr := + closeLambdasRev decls.toList.reverse body + +def applyParamsToType : List Ix.Expr → Ix.Expr → Ix.Expr + | [], cur => cur + | p :: rest, cur => + let next := match stripMData cur with + | .forallE _ _ b _ _ => instantiate1 b p + | other => other + applyParamsToType rest next + +def listFindNameIdx : List Ix.Name → Ix.Name → Nat → Option Nat + | [], _, _ => none + | x :: xs, nm, idx => if x == nm then some idx else listFindNameIdx xs nm (idx + 1) + +def listSlice (xs : List α) (start stop : Nat) : List α := + (xs.drop start).take (stop - start) + +def arraySlice (a : Array α) (start stop : Nat) : Array α := + Array.mk (listSlice a.toList start stop) + +def listGetD : List α → Nat → α → α + | [], _, d => d + | x :: _, 0, _ => x + | _ :: xs, n + 1, d => listGetD xs n d + +def listGet? : List α → Nat → Option α + | [], _ => none + | x :: _, 0 => some x + | _ :: xs, n + 1 => listGet? xs n + +/-! ## Recursor (`.rec`) Generation Over Canonical Inductive Blocks -/ + +/-- Check if `fieldDom` is a recursive occurrence of one of the inductive types in `indNames`: + either direct `I params idxArgs...` or functional `(a₁ : A₁) → ... → I params idxArgs...`. + Returns `some (indIdx, argDecls, idxArgs)` when recursive. -/ +def analyzeRecursiveField (indNames : Array Ix.Name) (numParams : Nat) + (fieldDom : Ix.Expr) (pfx : String) : Option (Nat × Array AuxLocalDecl × Array Ix.Expr) := + let nBinders := countForalls 64 fieldDom + let (_, argDecls, retTy) := openForallTelescope nBinders fieldDom pfx 0 #[] #[] + let (headFn, headArgs) := getAppFnArgs retTy + match headFn with + | .const nm _ _ => + match listFindNameIdx indNames.toList nm 0 with + | some indIdx => + if headArgs.size ≥ numParams then + let idxArgs := arraySlice headArgs numParams headArgs.size + some (indIdx, argDecls, idxArgs) + else none + | none => none + | _ => none + +def countTotalCtors : List (Ix.InductiveVal × Array Ix.ConstructorVal) → Nat → Nat + | [], acc => acc + | (_, cs) :: rest, acc => countTotalCtors rest (acc + cs.size) + +def buildMotivesLoop + (paramFVars : Array Ix.Expr) (paramFVarsList : List Ix.Expr) + (indUnivs : Array Ix.Level) (motiveSort : Ix.Expr) (nMotives : Nat) : + List (Ix.InductiveVal × Array Ix.ConstructorVal) → Nat → + List Ix.Expr → List AuxLocalDecl → + Array Ix.Expr × Array AuxLocalDecl + | [], _, revFVs, revDecls => (Array.mk revFVs.reverse, Array.mk revDecls.reverse) + | (iv, _) :: rest, mIdx, revFVs, revDecls => + let ivAfterParams := applyParamsToType paramFVarsList iv.cnst.type + let (idxFVars, idxDecls, _) := + openForallTelescope iv.numIndices ivAfterParams (str% "midx") (mIdx * 64) #[] #[] + let indApp := Expr.mkAppN (Expr.mkConst iv.cnst.name indUnivs) (arrAppend paramFVars idxFVars) + let (majId, _) := mkAuxFVar (str% "mmaj") mIdx + let majDecl : AuxLocalDecl := + { fvarId := majId, binderName := Name.simple (str% "t"), domain := indApp, binderInfo := .default } + let motiveDom := closeForalls (idxDecls.push majDecl) motiveSort + let motiveName := + if nMotives == 1 then Name.simple (str% "motive") + else Name.simple (strAppendPure (str% "motive_") (natToStrPure (mIdx + 1))) + let (mFvId, mFvExpr) := mkAuxFVar (str% "motive") mIdx + let mDecl : AuxLocalDecl := + { fvarId := mFvId, binderName := motiveName, domain := motiveDom, binderInfo := .implicit } + buildMotivesLoop paramFVars paramFVarsList indUnivs motiveSort nMotives + rest (mIdx + 1) (mFvExpr :: revFVs) (mDecl :: revDecls) + +def buildFieldRecSpecsLoop + (indNames : Array Ix.Name) (nParams : Nat) (motiveFVars : Array Ix.Expr) + (motiveFVar : Ix.Expr) (minorCounter : Nat) : + List AuxLocalDecl → List Ix.Expr → Nat → + List AuxLocalDecl → List (Option (Nat × Array AuxLocalDecl × Array Ix.Expr)) → + Array AuxLocalDecl × Array (Option (Nat × Array AuxLocalDecl × Array Ix.Expr)) + | [], _, _, revIhs, revSpecs => (Array.mk revIhs.reverse, Array.mk revSpecs.reverse) + | fDecl :: restDs, fVars, fIdx, revIhs, revSpecs => + let (fVar, restFVs) := match fVars with + | v :: vs => (v, vs) + | [] => (Expr.mkBVar 0, []) + let ihArgBase := minorCounter * 256 + fIdx * 16 + match analyzeRecursiveField indNames nParams fDecl.domain (strAppendPure (str% "iharg") (natToStrPure ihArgBase)) with + | some (recIndIdx, argDecls, idxArgs) => + let recMotive := listGetD motiveFVars.toList recIndIdx motiveFVar + let argFVars := Array.mk (mapDeclsToFVars argDecls.toList) + let appliedField := Expr.mkAppN fVar argFVars + let ihTarget := Expr.mkAppN recMotive (idxArgs.push appliedField) + let ihDom := closeForalls argDecls ihTarget + let ihName := match fDecl.binderName with + | .str _ s _ => Name.simple (strAppendPure s (str% "_ih")) + | _ => Name.simple (strAppendPure (str% "ih_") (natToStrPure fIdx)) + let (ihFvId, _) := mkAuxFVar (str% "ih") (minorCounter * 64 + fIdx) + let ihDecl : AuxLocalDecl := + { fvarId := ihFvId, binderName := ihName, domain := ihDom, binderInfo := .default } + buildFieldRecSpecsLoop indNames nParams motiveFVars motiveFVar minorCounter + restDs restFVs (fIdx + 1) (ihDecl :: revIhs) (some (recIndIdx, argDecls, idxArgs) :: revSpecs) + | none => + buildFieldRecSpecsLoop indNames nParams motiveFVars motiveFVar minorCounter + restDs restFVs (fIdx + 1) revIhs (none :: revSpecs) + +def buildCtorMinorsLoop + (indNames : Array Ix.Name) (nParams : Nat) (paramFVars : Array Ix.Expr) + (paramFVarsList : List Ix.Expr) (indUnivs : Array Ix.Level) + (motiveFVars : Array Ix.Expr) (motiveFVar : Ix.Expr) : + List Ix.ConstructorVal → Nat → + List Ix.Expr → List AuxLocalDecl → + NameMap (Ix.Expr × Array (Option (Nat × Array AuxLocalDecl × Array Ix.Expr))) → + Nat × List Ix.Expr × List AuxLocalDecl × + NameMap (Ix.Expr × Array (Option (Nat × Array AuxLocalDecl × Array Ix.Expr))) + | [], mc, revFVs, revDecls, byCtor => (mc, revFVs, revDecls, byCtor) + | ctor :: rest, mc, revFVs, revDecls, byCtor => + let ctorAfterParams := applyParamsToType paramFVarsList ctor.cnst.type + let (fieldFVars, fieldDecls, ctorRetTy) := + openForallTelescope ctor.numFields ctorAfterParams (str% "cf") (mc * 64) #[] #[] + let (ihDecls, fieldRecSpecs) := + buildFieldRecSpecsLoop indNames nParams motiveFVars motiveFVar mc + fieldDecls.toList fieldFVars.toList 0 [] [] + let (_, ctorRetArgs) := getAppFnArgs ctorRetTy + let ctorIdxArgs := arraySlice ctorRetArgs nParams ctorRetArgs.size + let ctorValApp := Expr.mkAppN (Expr.mkConst ctor.cnst.name indUnivs) (arrAppend paramFVars fieldFVars) + let minorRet := Expr.mkAppN motiveFVar (ctorIdxArgs.push ctorValApp) + let minorDom := closeForalls (arrAppend fieldDecls ihDecls) minorRet + let minorBinderName := match ctor.cnst.name with + | .str _ s _ => Name.simple s + | other => other + let (minFvId, minFvExpr) := mkAuxFVar (str% "minor") mc + let minDecl : AuxLocalDecl := + { fvarId := minFvId, binderName := minorBinderName, domain := minorDom, binderInfo := .default } + let byCtor' := byCtor.insert ctor.cnst.name (minFvExpr, fieldRecSpecs) + buildCtorMinorsLoop indNames nParams paramFVars paramFVarsList indUnivs motiveFVars motiveFVar + rest (mc + 1) (minFvExpr :: revFVs) (minDecl :: revDecls) byCtor' + +def buildAllMinorsLoop + (indNames : Array Ix.Name) (nParams : Nat) (paramFVars : Array Ix.Expr) + (paramFVarsList : List Ix.Expr) (indUnivs : Array Ix.Level) + (motiveFVars : Array Ix.Expr) : + List (Ix.InductiveVal × Array Ix.ConstructorVal) → Nat → Nat → + List Ix.Expr → List AuxLocalDecl → + NameMap (Ix.Expr × Array (Option (Nat × Array AuxLocalDecl × Array Ix.Expr))) → + Array Ix.Expr × Array AuxLocalDecl × + NameMap (Ix.Expr × Array (Option (Nat × Array AuxLocalDecl × Array Ix.Expr))) + | [], _, _, revFVs, revDecls, byCtor => + (Array.mk revFVs.reverse, Array.mk revDecls.reverse, byCtor) + | (_, ctors) :: rest, mIdx, mc, revFVs, revDecls, byCtor => + let motiveFVar := listGetD motiveFVars.toList mIdx (Expr.mkBVar 0) + let (mc', revFVs', revDecls', byCtor') := + buildCtorMinorsLoop indNames nParams paramFVars paramFVarsList indUnivs motiveFVars motiveFVar + ctors.toList mc revFVs revDecls byCtor + buildAllMinorsLoop indNames nParams paramFVars paramFVarsList indUnivs motiveFVars + rest (mIdx + 1) mc' revFVs' revDecls' byCtor' + +def buildRuleIhExprsLoop + (itemsList : List (Ix.InductiveVal × Array Ix.ConstructorVal)) + (targetInd : Ix.InductiveVal) (recUnivArgs : Array Ix.Level) + (paramFVars motiveFVars minorFVars : Array Ix.Expr) : + List (Option (Nat × Array AuxLocalDecl × Array Ix.Expr)) → List Ix.Expr → + List Ix.Expr → Array Ix.Expr + | [], _, revAcc => Array.mk revAcc.reverse + | spec? :: restSpecs, fVars, revAcc => + let (fVar, restFVs) := match fVars with + | v :: vs => (v, vs) + | [] => (Expr.mkBVar 0, []) + match spec? with + | none => + buildRuleIhExprsLoop itemsList targetInd recUnivArgs paramFVars motiveFVars minorFVars + restSpecs restFVs revAcc + | some (recIndIdx, argDecls, idxArgs) => + let (recIndVal, _) := listGetD itemsList recIndIdx (targetInd, #[]) + let recName := Name.mkStr recIndVal.cnst.name (str% "rec") + let recConst := Expr.mkConst recName recUnivArgs + let argFVars := Array.mk (mapDeclsToFVars argDecls.toList) + let appliedField := Expr.mkAppN fVar argFVars + let recCall := Expr.mkAppN recConst + (arrAppend (arrAppend (arrAppend (arrAppend paramFVars motiveFVars) minorFVars) idxArgs) #[appliedField]) + let ihLam := closeLambdas argDecls recCall + buildRuleIhExprsLoop itemsList targetInd recUnivArgs paramFVars motiveFVars minorFVars + restSpecs restFVs (ihLam :: revAcc) + +def buildRecursorRulesLoop + (itemsList : List (Ix.InductiveVal × Array Ix.ConstructorVal)) + (targetInd : Ix.InductiveVal) (recUnivArgs : Array Ix.Level) + (paramFVars motiveFVars minorFVars : Array Ix.Expr) + (paramFVarsList : List Ix.Expr) + (prefixDecls : Array AuxLocalDecl) + (minorByCtor : NameMap (Ix.Expr × Array (Option (Nat × Array AuxLocalDecl × Array Ix.Expr)))) : + List Ix.ConstructorVal → List Ix.RecursorRule → Option (Array Ix.RecursorRule) + | [], revRules => some (Array.mk revRules.reverse) + | ctor :: rest, revRules => + match minorByCtor.get? ctor.cnst.name with + | none => none + | some (minorFv, fieldRecSpecs) => + let ctorAfterParams := applyParamsToType paramFVarsList ctor.cnst.type + let (fieldFVars, fieldDecls, _) := + openForallTelescope ctor.numFields ctorAfterParams (str% "rf") (ctor.cidx * 64) #[] #[] + let ihExprs := + buildRuleIhExprsLoop itemsList targetInd recUnivArgs paramFVars motiveFVars minorFVars + fieldRecSpecs.toList fieldFVars.toList [] + let ruleBody := Expr.mkAppN minorFv (arrAppend fieldFVars ihExprs) + let ruleLamDecls := + Array.mk (mapDeclsSetBinderInfo .default (prefixDecls.toList ++ fieldDecls.toList)) + let rhs := closeLambdas ruleLamDecls ruleBody + buildRecursorRulesLoop itemsList targetInd recUnivArgs paramFVars motiveFVars minorFVars + paramFVarsList prefixDecls minorByCtor rest + ({ ctor := ctor.cnst.name, nfields := ctor.numFields, rhs } :: revRules) + +/-- Generate the canonical recursor (`Ix.RecursorVal`) for target inductive `targetIdx` + in a canonicalized mutual inductive block `items : Array (Ix.InductiveVal × Array Ix.ConstructorVal)`. -/ +def generateBlockRecursor (items : Array (Ix.InductiveVal × Array Ix.ConstructorVal)) + (targetIdx : Nat) : Option Ix.RecursorVal := + let itemsList := items.toList + match listGet? itemsList targetIdx with + | none => none + | some (targetInd, targetCtors) => + let firstInd := (listGetD itemsList 0 (targetInd, #[])).1 + let indNames : Array Ix.Name := Array.mk (mapIndItemsNames itemsList) + let nMotives := items.size + let nParams := targetInd.numParams + let baseLevelParams := firstInd.cnst.levelParams + let indUnivs : Array Ix.Level := Array.mk (mapNamesToLevels baseLevelParams.toList) + + let (paramFVars, paramDecls, afterParams) := + openForallTelescope nParams targetInd.cnst.type (str% "p") 0 #[] #[] + let paramDeclsImplicit : Array AuxLocalDecl := + Array.mk (mapDeclsSetBinderInfo .implicit paramDecls.toList) + let paramFVarsList := paramFVars.toList + + let (_, _, targetSortExpr) := + openForallTelescope targetInd.numIndices afterParams (str% "i_tmp") 0 #[] #[] + let indSortLvl : Ix.Level := match stripMData targetSortExpr with + | .sort u _ => u + | _ => Level.mkSucc Level.mkZero + let isPropInd : Bool := match indSortLvl with + | .zero _ => true + | _ => false + + let totalCtors := countTotalCtors itemsList 0 + let elimIntoAnySort : Bool := !isPropInd || totalCtors ≤ 1 + let uMotiveBase := Name.simple (str% "u_motive") + let uMotiveName : Ix.Name := + if listHasName uMotiveBase baseLevelParams.toList then Name.simple (str% "u_motive_1") + else uMotiveBase + let recLevelParams : Array Ix.Name := + if elimIntoAnySort then Array.mk (uMotiveName :: baseLevelParams.toList) else baseLevelParams + let motiveSort : Ix.Expr := + if elimIntoAnySort then Expr.mkSort (Level.mkParam uMotiveName) else Expr.mkProp + + let (motiveFVars, motiveDecls) := + buildMotivesLoop paramFVars paramFVarsList indUnivs motiveSort nMotives itemsList 0 [] [] + let (minorFVars, minorDecls, minorByCtor) := + buildAllMinorsLoop indNames nParams paramFVars paramFVarsList indUnivs motiveFVars + itemsList 0 0 [] [] NameMap.empty + + let targetAfterParams := applyParamsToType paramFVarsList targetInd.cnst.type + let (targetIdxFVars, targetIdxDecls, _) := + openForallTelescope targetInd.numIndices targetAfterParams (str% "tidx") 0 #[] #[] + let targetIdxDeclsImplicit : Array AuxLocalDecl := + Array.mk (mapDeclsSetBinderInfo .implicit targetIdxDecls.toList) + let majorDom := Expr.mkAppN (Expr.mkConst targetInd.cnst.name indUnivs) (arrAppend paramFVars targetIdxFVars) + let (majFvId, majFvExpr) := mkAuxFVar (str% "major") 0 + let majorDecl : AuxLocalDecl := + { fvarId := majFvId, binderName := Name.simple (str% "t"), domain := majorDom, binderInfo := .default } + + let targetMotive := listGetD motiveFVars.toList targetIdx (Expr.mkBVar 0) + let recReturn := Expr.mkAppN targetMotive (targetIdxFVars.push majFvExpr) + let prefixDecls := arrAppend (arrAppend paramDeclsImplicit motiveDecls) minorDecls + let allRecDecls := arrAppend (arrAppend prefixDecls targetIdxDeclsImplicit) #[majorDecl] + let recType := closeForalls allRecDecls recReturn + + let recUnivArgs : Array Ix.Level := Array.mk (mapNamesToLevels recLevelParams.toList) + match buildRecursorRulesLoop itemsList targetInd recUnivArgs paramFVars motiveFVars minorFVars + paramFVarsList prefixDecls minorByCtor targetCtors.toList [] with + | none => none + | some rules => + let isK : Bool := + match targetCtors.toList with + | c0 :: [] => isPropInd && c0.numFields == 0 && targetInd.numIndices > 0 + | _ => false + let recName := Name.mkStr targetInd.cnst.name (str% "rec") + some { + cnst := { + name := recName + levelParams := recLevelParams + type := recType + } + all := indNames + numParams := nParams + numIndices := targetInd.numIndices + numMotives := nMotives + numMinors := minorDecls.size + rules := rules + k := isK + isUnsafe := targetInd.isUnsafe + } + +/-! ## `.recOn` Generation -/ + +/-- Generate `.recOn` by reordering `.rec` binders from + `[params, motives, minors, indices, major]` to `[params, motives, indices, major, minors]`. -/ +def generateRecOn (indName : Ix.Name) (recVal : Ix.RecursorVal) : Option Ix.DefinitionVal := + let nParams := recVal.numParams + let nMotives := recVal.numMotives + let nMinors := recVal.numMinors + let nIndices := recVal.numIndices + let acSize := nParams + nMotives + let total := acSize + nMinors + nIndices + 1 + + let (fvars, decls, body) := openForallTelescope total recVal.cnst.type (str% "ro") 0 #[] #[] + if fvars.size < total then none + else + let recUnivs := Array.mk (mapNamesToLevels recVal.cnst.levelParams.toList) + let recApp := Expr.mkAppN (Expr.mkConst recVal.cnst.name recUnivs) fvars + let declsL := decls.toList + let reordered : Array AuxLocalDecl := + Array.mk (listSlice declsL 0 acSize ++ + listSlice declsL (acSize + nMinors) total ++ + listSlice declsL acSize (acSize + nMinors)) + let recOnType := closeForalls reordered body + let recOnValue := closeLambdas reordered recApp + let recOnName := Name.mkStr indName (str% "recOn") + some { + cnst := { + name := recOnName + levelParams := recVal.cnst.levelParams + type := recOnType + } + value := recOnValue + hints := .abbrev + safety := if recVal.isUnsafe then .unsafe else .safe + all := #[recOnName] + } + +/-! ## `.casesOn` Generation (Single & Mutual Inductives) -/ + +def buildCasesOnMinorsLoop (recMinorDeclsL : List AuxLocalDecl) : + List Ix.ConstructorVal → Nat → List AuxLocalDecl → List Ix.Expr → + Array AuxLocalDecl × Array Ix.Expr + | [], _, revDecls, revArgs => (Array.mk revDecls.reverse, Array.mk revArgs.reverse) + | ctor :: rest, i, revDecls, revArgs => + let rMinorDecl := listGetD recMinorDeclsL i default + let nAllMinorBinders := countForalls 64 rMinorDecl.domain + let (allFieldFVars, allFieldDecls, minorRet) := + openForallTelescope nAllMinorBinders rMinorDecl.domain (str% "cof") (i * 64) #[] #[] + let nonIhDecls := arraySlice allFieldDecls 0 ctor.numFields + let nonIhFVars := arraySlice allFieldFVars 0 ctor.numFields + let coMinorDom := closeForalls nonIhDecls minorRet + let (coMinFvId, coMinFvExpr) := mkAuxFVar (str% "comin") i + let coDecl : AuxLocalDecl := { + fvarId := coMinFvId + binderName := rMinorDecl.binderName + domain := coMinorDom + binderInfo := .default + } + let wrapperBody := Expr.mkAppN coMinFvExpr nonIhFVars + let wrapperLam := closeLambdas allFieldDecls wrapperBody + buildCasesOnMinorsLoop recMinorDeclsL rest (i + 1) (coDecl :: revDecls) (wrapperLam :: revArgs) + +/-- Generate `.casesOn` (eliminator without inductive hypotheses, with + indices and major premise placed before the minor premises). -/ +def generateCasesOn (indVal : Ix.InductiveVal) (ctors : Array Ix.ConstructorVal) + (recVal : Ix.RecursorVal) : Option Ix.DefinitionVal := + if recVal.numMotives != 1 then none + else + let nParams := recVal.numParams + let nMinors := ctors.size + let nIndices := recVal.numIndices + let acSize := nParams + 1 + let total := acSize + nMinors + nIndices + 1 + let (recFVars, recDecls, recBody) := openForallTelescope total recVal.cnst.type (str% "co") 0 #[] #[] + if recFVars.size < total then none + else + let recDeclsL := recDecls.toList + let recFVarsL := recFVars.toList + let paramDecls := Array.mk (listSlice recDeclsL 0 nParams) + let motiveDecl := listGetD recDeclsL nParams default + let recMinorDeclsL := listSlice recDeclsL acSize (acSize + nMinors) + let indexAndMajorDecls := Array.mk (listSlice recDeclsL (acSize + nMinors) total) + + let paramFVars := Array.mk (listSlice recFVarsL 0 nParams) + let motiveFVar := listGetD recFVarsL nParams (Expr.mkBVar 0) + let indexAndMajorFVars := Array.mk (listSlice recFVarsL (acSize + nMinors) total) + + let (coMinorDecls, recMinorArgs) := + buildCasesOnMinorsLoop recMinorDeclsL ctors.toList 0 [] [] + + let finalDecls := arrAppend (arrAppend (arrAppend paramDecls #[motiveDecl]) indexAndMajorDecls) coMinorDecls + let coType := closeForalls finalDecls recBody + let recUnivs := Array.mk (mapNamesToLevels recVal.cnst.levelParams.toList) + let recCall := Expr.mkAppN + (Expr.mkConst recVal.cnst.name recUnivs) + (arrAppend (arrAppend (arrAppend paramFVars #[motiveFVar]) recMinorArgs) indexAndMajorFVars) + let coValue := closeLambdas finalDecls recCall + let coName := Name.mkStr indVal.cnst.name (str% "casesOn") + some { + cnst := { + name := coName + levelParams := recVal.cnst.levelParams + type := coType + } + value := coValue + hints := .abbrev + safety := if recVal.isUnsafe then .unsafe else .safe + all := #[coName] + } + +/-! ## `._ctorIdx` Generation -/ + +def buildCtorIdxMinorsLoop (paramFVarsList : List Ix.Expr) : + List Ix.ConstructorVal → Nat → List Ix.Expr → Array Ix.Expr + | [], _, revAcc => Array.mk revAcc.reverse + | ctor :: rest, cidx, revAcc => + let ctorAfterParams := applyParamsToType paramFVarsList ctor.cnst.type + let (_, fieldDecls, _) := + openForallTelescope ctor.numFields ctorAfterParams (str% "cif") (cidx * 64) #[] #[] + let minorLam := closeLambdas fieldDecls (Expr.mkNatLit cidx) + buildCtorIdxMinorsLoop paramFVarsList rest (cidx + 1) (minorLam :: revAcc) + +/-- Generate `._ctorIdx` mapping each constructor `c_i` to `i : Nat` via `.casesOn`. -/ +def generateCtorIdx (indVal : Ix.InductiveVal) (ctors : Array Ix.ConstructorVal) + (recVal : Ix.RecursorVal) : Option Ix.DefinitionVal := + if recVal.cnst.levelParams.size != indVal.cnst.levelParams.size + 1 then none + else + let nParams := indVal.numParams + let nIndices := indVal.numIndices + let baseUnivs := Array.mk (mapNamesToLevels indVal.cnst.levelParams.toList) + let (paramFVars, paramDecls, afterParams) := + openForallTelescope nParams indVal.cnst.type (str% "cip") 0 #[] #[] + let paramDeclsImplicit := Array.mk (mapDeclsSetBinderInfo .implicit paramDecls.toList) + let (idxFVars, idxDecls, _) := + openForallTelescope nIndices afterParams (str% "cii") 0 #[] #[] + let idxDeclsImplicit := Array.mk (mapDeclsSetBinderInfo .implicit idxDecls.toList) + let indApp := Expr.mkAppN (Expr.mkConst indVal.cnst.name baseUnivs) (arrAppend paramFVars idxFVars) + let (xFvId, xFvExpr) := mkAuxFVar (str% "cix") 0 + let xDecl : AuxLocalDecl := + { fvarId := xFvId, binderName := Name.simple (str% "x"), domain := indApp, binderInfo := .default } + + let natConst := Expr.mkConst (Name.simple (str% "Nat")) #[] + let allDecls := arrAppend (arrAppend paramDeclsImplicit idxDeclsImplicit) #[xDecl] + let ctorIdxType := closeForalls allDecls natConst + + let ctorIdxName := Name.mkStr indVal.cnst.name (str% "_ctorIdx") + if ctors.size ≤ 1 then + let val := closeLambdas allDecls (Expr.mkNatLit 0) + some { + cnst := { name := ctorIdxName, levelParams := indVal.cnst.levelParams, type := ctorIdxType } + value := val + hints := .abbrev + safety := if indVal.isUnsafe then .unsafe else .safe + all := #[ctorIdxName] + } + else + let casesOnName := Name.mkStr indVal.cnst.name (str% "casesOn") + let casesOnUnivs := Array.mk (Level.mkSucc Level.mkZero :: baseUnivs.toList) + let motiveLam := closeLambdas (idxDecls.push xDecl) natConst + let minorLams := buildCtorIdxMinorsLoop paramFVars.toList ctors.toList 0 [] + let casesOnApp := Expr.mkAppN + (Expr.mkConst casesOnName casesOnUnivs) + (arrAppend (arrAppend (arrAppend (arrAppend paramFVars #[motiveLam]) idxFVars) #[xFvExpr]) minorLams) + let ctorIdxValue := closeLambdas allDecls casesOnApp + some { + cnst := { name := ctorIdxName, levelParams := indVal.cnst.levelParams, type := ctorIdxType } + value := ctorIdxValue + hints := .abbrev + safety := if indVal.isUnsafe then .unsafe else .safe + all := #[ctorIdxName] + } + +/-! ## Structure Field Projection Generation -/ + +def buildStructProjsLoop + (indVal : Ix.InductiveVal) (allDecls : Array AuxLocalDecl) (selfFvExpr : Ix.Expr) : + Nat → Nat → Ix.Expr → List Ix.Name → List Ix.DefinitionVal → Array Ix.DefinitionVal + | 0, _, _, _, revOut => Array.mk revOut.reverse + | rem + 1, i, curCtorTy, fNames, revOut => + match stripMData curCtorTy with + | .forallE _ fieldDom restBody _ _ => + let projExpr := Expr.mkProj indVal.cnst.name i selfFvExpr + let nextTy := instantiate1 restBody projExpr + match fNames with + | projName :: restNames => + let projType := closeForalls allDecls fieldDom + let projVal := closeLambdas allDecls projExpr + let defVal : Ix.DefinitionVal := { + cnst := { + name := projName + levelParams := indVal.cnst.levelParams + type := projType + } + value := projVal + hints := .abbrev + safety := if indVal.isUnsafe then .unsafe else .safe + all := #[projName] + } + buildStructProjsLoop indVal allDecls selfFvExpr rem (i + 1) nextTy restNames (defVal :: revOut) + | [] => + buildStructProjsLoop indVal allDecls selfFvExpr rem (i + 1) nextTy [] revOut + | _ => Array.mk revOut.reverse + +/-- Generate projection definitions `.` for a single-constructor + `structure` or `class` using kernel `.proj i self` nodes. -/ +def generateStructProjections (indVal : Ix.InductiveVal) (ctorVal : Ix.ConstructorVal) + (fieldNames : Array Ix.Name) (isClass : Bool := false) : Array Ix.DefinitionVal := + let nParams := indVal.numParams + let baseUnivs := Array.mk (mapNamesToLevels indVal.cnst.levelParams.toList) + let (paramFVars, paramDecls, _) := + openForallTelescope nParams indVal.cnst.type (str% "sp") 0 #[] #[] + let paramDeclsImplicit := Array.mk (mapDeclsSetBinderInfo .implicit paramDecls.toList) + let structApp := Expr.mkAppN (Expr.mkConst indVal.cnst.name baseUnivs) paramFVars + let (selfFvId, selfFvExpr) := mkAuxFVar (str% "self") 0 + let selfBi : Lean.BinderInfo := if isClass then .instImplicit else .default + let selfDecl : AuxLocalDecl := + { fvarId := selfFvId, binderName := Name.simple (str% "self"), domain := structApp, binderInfo := selfBi } + let allDecls := paramDeclsImplicit.push selfDecl + let curCtorTy := applyParamsToType paramFVars.toList ctorVal.cnst.type + buildStructProjsLoop indVal allDecls selfFvExpr ctorVal.numFields 0 curCtorTy fieldNames.toList [] + +/-! ## Complete Auxiliary Suite Registration for an Inductive Block -/ + +def addCtorsToEnv : List Ix.ConstructorVal → IxElabEnv → IxElabEnv + | [], env => env + | ctor :: rest, env => addCtorsToEnv rest (env.addConst (.ctorInfo ctor)) + +def addIndsAndCtorsLoop : List (Ix.InductiveVal × Array Ix.ConstructorVal) → IxElabEnv → IxElabEnv + | [], env => env + | (iv, ctors) :: rest, env => + let env := env.addConst (.inductInfo iv) + let env := addCtorsToEnv ctors.toList env + addIndsAndCtorsLoop rest env + +def addAuxsLoop (canonItems : Array (Ix.InductiveVal × Array Ix.ConstructorVal)) : + List (Ix.InductiveVal × Array Ix.ConstructorVal) → Nat → IxElabEnv → IxElabEnv + | [], _, env => env + | (iv, ctors) :: rest, idx, env => + let env' := + match generateBlockRecursor canonItems idx with + | none => env + | some recVal => + let env := env.addConst (.recInfo recVal) + let env := match generateRecOn iv.cnst.name recVal with + | some recOnDef => env.addConst (.defnInfo recOnDef) + | none => env + match generateCasesOn iv ctors recVal with + | none => env + | some casesOnDef => + let env := env.addConst (.defnInfo casesOnDef) + if env.contains (Name.simple (str% "Nat")) then + match generateCtorIdx iv ctors recVal with + | some ctorIdxDef => env.addConst (.defnInfo ctorIdxDef) + | none => env + else env + addAuxsLoop canonItems rest (idx + 1) env' + +/-- Register a canonicalized inductive block `(indVal, ctors)` and all of its + surgery-free auxiliaries (`.rec`, `.recOn`, `.casesOn`, `._ctorIdx`) into `env : IxElabEnv`. -/ +def registerCanonicalInductiveBlock (env : IxElabEnv) + (canonItems : Array (Ix.InductiveVal × Array Ix.ConstructorVal)) : IxElabEnv := + let itemsList := canonItems.toList + let env1 := addIndsAndCtorsLoop itemsList env + addAuxsLoop canonItems itemsList 0 env1 + +end Ix.Frontend.AuxGen diff --git a/Ix/Frontend/CanonBlock.lean b/Ix/Frontend/CanonBlock.lean new file mode 100644 index 0000000000..4d27901e38 --- /dev/null +++ b/Ix/Frontend/CanonBlock.lean @@ -0,0 +1,502 @@ +/- + Ix.Frontend.CanonBlock: In-Elaborator Canonicalization of Mutual Blocks + and Inductive Constructors (Ix Paper §§4.3, 9.2). + + Performs: + 1. Structural nameless expression comparison (`compareExpr`) matching the Ixon + canonical block comparator (`Order.lean`). + 2. Canonical sorting of inductive constructors (`sortInductiveCtors`) by nameless + structural skeleton `(levelParams.size, numParams, numFields, type)`, breaking + ties among structurally α-identical constructors of the same inductive + (e.g., `Bool.false` vs `Bool.true`, `Ordering.lt`/`eq`/`gt`) by **source declaration order**. + 3. Partition-refinement canonical ordering of mutual inductive blocks (`canonicalizeInductiveBlock`) + and mutual definition blocks (`canonicalizeDefBlock`), plus post-elaboration + minimal SCC splitting (`splitElaboratedDefSCCs`). +-/ +module + +public import Ix.Frontend.Elab.Meta +public import Ix.Mutual +public import Ix.SOrder +public import Ix.SemanticContract +public import Ix.Ixon.ReduceUniverse +public import Ix.Compile.Canon.Graph + +@[expose] public section + +namespace Ix.Frontend.Canon + +open Ix (Name Level Expr MutConst Def Ind ConstructorVal RecursorVal RecursorRule) +open Ix.Frontend + +/-! ## Canonical Universe & Expression Comparator -/ + +/-- Context for nameless structural comparison: external constant import map + and current mutual-block equivalence class map `mutCtx` (keyed by `Ix.Name.leanCmp`). -/ +structure CanonCmpCtx where + importMap : IxImportMap + mutCtx : NameMap Nat + +@[inline] def resolveCanonAddr (importMap : IxImportMap) (nm : Ix.Name) : Address := + match importMap.lookupName? nm with + | some addr => addr + | none => Name.computeHash nm + +/-- Convert an `Ix.Level` into a positional `Ixon.Univ` relative to `ctx : List Ix.Name`. -/ +def levelToUniv (ctx : List Ix.Name) : Ix.Level → Ixon.Univ + | .zero _ => .zero + | .succ l _ => .succ (levelToUniv ctx l) + | .max a b _ => .max (levelToUniv ctx a) (levelToUniv ctx b) + | .imax a b _ => .imax (levelToUniv ctx a) (levelToUniv ctx b) + | .param n _ => + match ctx.idxOf? n with + | some i => .var i.toUInt64 + | none => .zero + | .mvar _ _ => .zero + +/-- Structural total order on `Ixon.Univ`: `zero < succ < max < imax < var`. -/ +def compareUniv : Ixon.Univ → Ixon.Univ → Ordering + | .zero, .zero => .eq + | .zero, _ => .lt + | _, .zero => .gt + | .succ x, .succ y => compareUniv x y + | .succ _, _ => .lt + | _, .succ _ => .gt + | .max a b, .max c d => (compareUniv a c).then (compareUniv b d) + | .max .., _ => .lt + | _, .max .. => .gt + | .imax a b, .imax c d => (compareUniv a c).then (compareUniv b d) + | .imax .., _ => .lt + | _, .imax .. => .gt + | .var i, .var j => compare i j + +/-- Compare two `Ix.Level`s after `Ixon.reduceUniv` normalization. -/ +def compareLevel (xctx yctx : List Ix.Name) (x y : Ix.Level) : SOrder := + let ux := Ixon.reduceUniv (levelToUniv xctx x) + let uy := Ixon.reduceUniv (levelToUniv yctx y) + ⟨true, compareUniv ux uy⟩ + +/-- Pointwise comparison of universe level lists. -/ +def compareLevels (xctx yctx : List Ix.Name) : List Ix.Level → List Ix.Level → SOrder + | [], [] => ⟨true, .eq⟩ + | [], _ :: _ => ⟨true, .lt⟩ + | _ :: _, [] => ⟨true, .gt⟩ + | x :: xs, y :: ys => + let o := compareLevel xctx yctx x y + if o.ord != .eq then o else SOrder.cmp o (compareLevels xctx yctx xs ys) + +/-- Structural size of an `Ix.Expr` for termination of `compareExpr`. -/ +def exprSize : Ix.Expr → Nat + | .bvar .. | .fvar .. | .mvar .. | .sort .. | .const .. | .lit .. => 1 + | .app f a _ => exprSize f + exprSize a + 1 + | .lam _ t b _ _ => exprSize t + exprSize b + 1 + | .forallE _ t b _ _ => exprSize t + exprSize b + 1 + | .letE _ t v b _ _ => exprSize t + exprSize v + exprSize b + 1 + | .proj _ _ s _ => exprSize s + 1 + | .mdata _ s _ => exprSize s + 1 + +@[simp] theorem exprSize_app (f a : Ix.Expr) (h : Address) : + exprSize (.app f a h) = exprSize f + exprSize a + 1 := rfl +@[simp] theorem exprSize_lam (n : Ix.Name) (t b : Ix.Expr) (bi : Lean.BinderInfo) (h : Address) : + exprSize (.lam n t b bi h) = exprSize t + exprSize b + 1 := rfl +@[simp] theorem exprSize_forallE (n : Ix.Name) (t b : Ix.Expr) (bi : Lean.BinderInfo) (h : Address) : + exprSize (.forallE n t b bi h) = exprSize t + exprSize b + 1 := rfl +@[simp] theorem exprSize_letE (n : Ix.Name) (t v b : Ix.Expr) (nd : Bool) (h : Address) : + exprSize (.letE n t v b nd h) = exprSize t + exprSize v + exprSize b + 1 := rfl +@[simp] theorem exprSize_proj (n : Ix.Name) (i : Nat) (s : Ix.Expr) (h : Address) : + exprSize (.proj n i s h) = exprSize s + 1 := rfl +@[simp] theorem exprSize_mdata (d : Array (Ix.Name × Ix.DataValue)) (s : Ix.Expr) (h : Address) : + exprSize (.mdata d s h) = exprSize s + 1 := rfl + +/-- Compare two constant/structure references: + - Identical names are `.eq` (`strong := true`). + - Two in-block names compare by their current class index in `mutCtx` (`strong := false`). + - In-block sorts before external (`strong := true`). + - Two external names compare by `c.addrOf`. -/ +def compareRef (c : CanonCmpCtx) (x y : Ix.Name) : SOrder := + if Name.beqStruct x y then + ⟨true, .eq⟩ + else + match c.mutCtx.get? x, c.mutCtx.get? y with + | some nx, some ny => ⟨false, compare nx ny⟩ + | some _, none => ⟨true, .lt⟩ + | none, some _ => ⟨true, .gt⟩ + | none, none => ⟨true, compare (resolveCanonAddr c.importMap x) (resolveCanonAddr c.importMap y)⟩ + +def exprCtorTag : Ix.Expr → Nat + | .bvar .. => 0 + | .sort .. => 1 + | .const .. => 2 + | .app .. => 3 + | .lam .. => 4 + | .forallE .. => 5 + | .letE .. => 6 + | .lit .. => 7 + | .fvar .. => 8 + | .mvar .. => 9 + | .proj .. => 10 + | .mdata .. => 11 + +/-- Structurally recursive core of `compareExpr` (zero `WellFounded.fix`, zero tuple `match_*`). -/ +def compareExprGo (c : CanonCmpCtx) (xl yl : List Ix.Name) : Nat → Ix.Expr → Ix.Expr → SOrder + | 0, _, _ => ⟨true, .eq⟩ + | fuel + 1, x, y => + match x with + | .mdata dx xi hx => + match y with + | .mdata dy yi hy => + if SemanticContract.hasMetadata dx then + if SemanticContract.hasMetadata dy then + match SemanticContract.read dx with + | .ok cx => + match SemanticContract.read dy with + | .ok cy => + let o := compare cx.orderKey cy.orderKey + if o != .eq then ⟨true, o⟩ else compareExprGo c xl yl fuel xi yi + | .error _ => compareExprGo c xl yl fuel xi yi + | .error _ => compareExprGo c xl yl fuel xi yi + else compareExprGo c xl yl fuel (.mdata dx xi hx) yi + else compareExprGo c xl yl fuel xi (.mdata dy yi hy) + | _ => + if SemanticContract.hasMetadata dx then ⟨true, .gt⟩ + else compareExprGo c xl yl fuel xi y + | _ => + match y with + | .mdata dy yi _ => + if SemanticContract.hasMetadata dy then ⟨true, .lt⟩ + else compareExprGo c xl yl fuel x yi + | _ => + let tx := exprCtorTag x + let ty := exprCtorTag y + if tx < ty then ⟨true, .lt⟩ + else if tx > ty then ⟨true, .gt⟩ + else + match x with + | .bvar i _ => + match y with + | .bvar j _ => ⟨true, compare i j⟩ + | _ => ⟨true, .eq⟩ + | .sort u _ => + match y with + | .sort v _ => compareLevel xl yl u v + | _ => ⟨true, .eq⟩ + | .const xn xls _ => + match y with + | .const yn yls _ => + let us := compareLevels xl yl xls.toList yls.toList + if us.ord != .eq then us else SOrder.cmp us (compareRef c xn yn) + | _ => ⟨true, .eq⟩ + | .app xf xa _ => + match y with + | .app yf ya _ => + let fo := compareExprGo c xl yl fuel xf yf + if fo.ord != .eq then fo else SOrder.cmp fo (compareExprGo c xl yl fuel xa ya) + | _ => ⟨true, .eq⟩ + | .lam _ xt xb _ _ => + match y with + | .lam _ yt yb _ _ => + let to_ := compareExprGo c xl yl fuel xt yt + if to_.ord != .eq then to_ else SOrder.cmp to_ (compareExprGo c xl yl fuel xb yb) + | _ => ⟨true, .eq⟩ + | .forallE _ xt xb _ _ => + match y with + | .forallE _ yt yb _ _ => + let to_ := compareExprGo c xl yl fuel xt yt + if to_.ord != .eq then to_ else SOrder.cmp to_ (compareExprGo c xl yl fuel xb yb) + | _ => ⟨true, .eq⟩ + | .letE _ xt xv xb xnd _ => + match y with + | .letE _ yt yv yb ynd _ => + let to_ := compareExprGo c xl yl fuel xt yt + if to_.ord != .eq then to_ + else + let vo := SOrder.cmp to_ (compareExprGo c xl yl fuel xv yv) + if vo.ord != .eq then vo + else + let bo := SOrder.cmp vo (compareExprGo c xl yl fuel xb yb) + if bo.ord != .eq then bo + else SOrder.cmp bo ⟨true, compare xnd ynd⟩ + | _ => ⟨true, .eq⟩ + | .lit a _ => + match y with + | .lit b _ => ⟨true, compare a b⟩ + | _ => ⟨true, .eq⟩ + | .fvar fx _ => + match y with + | .fvar fy _ => ⟨true, Name.cmpStruct fx fy⟩ + | _ => ⟨true, .eq⟩ + | .mvar mx _ => + match y with + | .mvar my _ => ⟨true, Name.cmpStruct mx my⟩ + | _ => ⟨true, .eq⟩ + | .proj xn xi xs _ => + match y with + | .proj yn yi ys _ => + let ro := compareRef c xn yn + if ro.ord != .eq then ro + else + let io := SOrder.cmp ro ⟨true, compare xi yi⟩ + if io.ord != .eq then io + else SOrder.cmp io (compareExprGo c xl yl fuel xs ys) + | _ => ⟨true, .eq⟩ + | .mdata .. => ⟨true, .eq⟩ + +/-- Total, name-irrelevant structural comparator on `Ix.Expr` matching the Ixon canonical order. -/ +def compareExpr (c : CanonCmpCtx) (xl yl : List Ix.Name) (x y : Ix.Expr) : SOrder := + compareExprGo c xl yl (exprSize x + exprSize y + 1) x y + +/-! ## Inductive Constructor Canonicalization (Tie-Breaking by Source Order) -/ + +/-- Compare two constructors `x` and `y` of an inductive by their nameless structural + skeleton `(levelParams.size, numParams, numFields, type)`. + Note: `cidx` is intentionally NOT compared here so that structurally distinct + constructors (e.g. `Nat.succ` vs `Nat.zero`) are ordered by structure rather than + initial source index; ties (`ord == .eq`) among structurally α-identical constructors + (e.g. `Bool.false` vs `Bool.true`) are broken by source order (`compare x.cidx y.cidx`)! -/ +def compareCtorSkeleton (c : CanonCmpCtx) (xl yl : List Ix.Name) + (x y : ConstructorVal) : SOrder := + let o1 : SOrder := ⟨true, compare x.cnst.levelParams.size y.cnst.levelParams.size⟩ + if o1.ord != .eq then o1 else + let o2 : SOrder := ⟨true, compare x.numParams y.numParams⟩ + if o2.ord != .eq then o2 else + let o3 : SOrder := ⟨true, compare x.numFields y.numFields⟩ + if o3.ord != .eq then o3 else + compareExpr c xl yl x.cnst.type y.cnst.type + +/-- Pure, total insertion sort on `Array α` (avoids `Array.qsort`'s `partial` helper). -/ +def sortArrayBy (xs : Array α) (lt : α → α → Bool) : Array α := + let rec insert (x : α) : List α → List α + | [] => [x] + | y :: ys => if lt y x then y :: insert x ys else x :: y :: ys + (xs.foldl (fun acc x => insert x acc) []).toArray + +/-- Canonicalize the constructors of a single inductive `indVal` under `c : CanonCmpCtx`: + - Sorts constructors by `compareCtorSkeleton` + - Breaks ties (`ord == .eq`) among α-identical constructors by original `cidx` (source order!) + - Re-assigns `cidx := 0, 1, ...` and updates `indVal.ctors`. -/ +def sortInductiveCtors (c : CanonCmpCtx) (indVal : Ix.InductiveVal) + (ctors : Array ConstructorVal) : Ix.InductiveVal × Array ConstructorVal := + if ctors.size ≤ 1 then + let ctors' := ctors.mapIdx fun idx cv => { cv with cidx := idx } + ({ indVal with ctors := ctors'.map (·.cnst.name) }, ctors') + else + let lvlList := indVal.cnst.levelParams.toList + let sorted := sortArrayBy ctors fun a b => + let so := compareCtorSkeleton c lvlList lvlList a b + match so.ord with + | .lt => true + | .gt => false + | .eq => a.cidx < b.cidx + let reindexed := sorted.mapIdx fun newIdx cv => { cv with cidx := newIdx } + let indVal' := { indVal with ctors := reindexed.map (·.cnst.name) } + (indVal', reindexed) + +/-! ## Mutual Inductive & Mutual Definition Partition Refinement -/ + +/-- Compare two `Ind` records structurally (after their constructors have been canonicalized). -/ +def compareIndStruct (c : CanonCmpCtx) (x y : Ind) : SOrder := + let hdr := SOrder.cmpMany ⟨true, compare x.levelParams.size y.levelParams.size⟩ + [⟨true, compare x.numParams y.numParams⟩, + ⟨true, compare x.numIndices y.numIndices⟩, + ⟨true, compare x.ctors.size y.ctors.size⟩] + if hdr.ord != .eq then hdr + else + let xl := x.levelParams.toList + let yl := y.levelParams.toList + let tyOrd := SOrder.cmp hdr (compareExpr c xl yl x.type y.type) + if tyOrd.ord != .eq then tyOrd + else + let rec cmpCtors : List ConstructorVal → List ConstructorVal → SOrder + | [], [] => ⟨true, .eq⟩ + | [], _ :: _ => ⟨true, .lt⟩ + | _ :: _, [] => ⟨true, .gt⟩ + | a :: as, b :: bs => + let co := compareCtorSkeleton c xl yl a b + if co.ord != .eq then co else SOrder.cmp co (cmpCtors as bs) + SOrder.cmp tyOrd (cmpCtors x.ctors.toList y.ctors.toList) + +/-- Compare two `Def` records structurally by `(kind, levelParams.size, type, value)`. -/ +def compareDefStruct (c : CanonCmpCtx) (x y : Def) : SOrder := + let o1 : SOrder := ⟨true, compare x.kind y.kind⟩ + if o1.ord != .eq then o1 else + let o2 : SOrder := ⟨true, compare x.levelParams.size y.levelParams.size⟩ + if o2.ord != .eq then o2 else + let xl := x.levelParams.toList + let yl := y.levelParams.toList + let tyOrd := compareExpr c xl yl x.type y.type + if tyOrd.ord != .eq then tyOrd + else SOrder.cmp tyOrd (compareExpr c xl yl x.value y.value) + +/-- Compare two `MutConst` records structurally. -/ +def compareMutConst (c : CanonCmpCtx) (x y : MutConst) : SOrder := + match x, y with + | .defn dx, .defn dy => compareDefStruct c dx dy + | .indc ix, .indc iy => compareIndStruct c ix iy + | .defn _, _ => ⟨true, .lt⟩ + | _, .defn _ => ⟨true, .gt⟩ + | .indc _, .recr _ => ⟨true, .lt⟩ + | .recr _, .indc _ => ⟨true, .gt⟩ + | .recr rx, .recr ry => + compareExpr c rx.cnst.levelParams.toList ry.cnst.levelParams.toList rx.cnst.type ry.cnst.type + +/-- Build a `NameMap Nat` mapping each equivalence class's members (and constructors) to class indices. -/ +def buildClassesMutCtx (classes : List (List (Nat × MutConst))) : NameMap Nat := + let rec insertCtors (baseSlot : Nat) : List Ix.ConstructorVal → Nat → NameMap Nat → NameMap Nat + | [], _, ctx => ctx + | ctor :: rest, cidx, ctx => + insertCtors baseSlot rest (cidx + 1) (ctx.insert ctor.cnst.name (baseSlot + cidx)) + let rec insertMembers (clsIdx : Nat) : List (Nat × MutConst) → Nat → NameMap Nat → Nat × NameMap Nat + | [], ctorSlot, ctx => (ctorSlot, ctx) + | (_, mc) :: rest, ctorSlot, ctx => + let ctx1 := ctx.insert mc.name clsIdx + let ctx2 := insertCtors ctorSlot mc.ctors.toList 0 ctx1 + insertMembers clsIdx rest (ctorSlot + mc.ctors.size) ctx2 + let rec insertClasses : List (List (Nat × MutConst)) → Nat → Nat → NameMap Nat → NameMap Nat + | [], _, _, ctx => ctx + | cls :: rest, clsIdx, ctorSlot, ctx => + let (ctorSlot', ctx') := insertMembers clsIdx cls ctorSlot ctx + insertClasses rest (clsIdx + 1) ctorSlot' ctx' + insertClasses classes 0 classes.length NameMap.empty + +/-- Refine a single equivalence class of `(sourceIdx, MutConst)` pairs under `c : CanonCmpCtx`, + breaking ties among structurally α-equivalent members by original `sourceIdx`. -/ +def refineOneClass (c : CanonCmpCtx) (cls : List (Nat × MutConst)) : List (List (Nat × MutConst)) := + match cls with + | [] => [] + | [x] => [[x]] + | xs => + let arr := sortArrayBy xs.toArray fun (i, a) (j, b) => + match (compareMutConst c a b).ord with + | .lt => true + | .gt => false + | .eq => i < j + -- Group adjacent structurally equal members (`ord == .eq`) + let groups : Array (Array (Nat × MutConst)) := arr.foldl (fun acc elem => + if acc.isEmpty then + #[#[elem]] + else + let lastGroup := acc.back?.getD #[elem] + let (_, rep) := lastGroup.getD 0 elem + if (compareMutConst c rep elem.2).ord == .eq then + acc.pop.push (lastGroup.push elem) + else + acc.push #[elem] + ) #[] + groups.toList.map Array.toList + +/-- Partition-refinement loop (`sortClasses`) until the class partition stabilizes. -/ +def refineClassesLoop (importMap : IxImportMap) : + Nat → List (List (Nat × MutConst)) → List (List (Nat × MutConst)) + | 0, classes => classes + | fuel + 1, classes => + let mutCtx := buildClassesMutCtx classes + let c : CanonCmpCtx := { importMap, mutCtx } + let refined := classes.flatMap (refineOneClass c) + if refined.length == classes.length then refined + else refineClassesLoop importMap fuel refined + +/-- Canonicalize a mutual inductive block `(indVal, ctors)` array: + 1. Canonicalizes each inductive's constructor order (breaking ties by source declaration order). + 2. Canonicalizes the mutual inductive member order via partition refinement. + 3. Updates `all` on every `InductiveVal` in the block to the canonical member name order. -/ +def canonicalizeInductiveBlock (importMap : IxImportMap) + (items : Array (Ix.InductiveVal × Array ConstructorVal)) : + Array (Ix.InductiveVal × Array ConstructorVal) := + if items.isEmpty then #[] + else + -- Build initial `mutCtx` where all inductives in the block share class 0 + let initMutCtx : NameMap Nat := items.foldl (fun ctx (iv, _) => ctx.insert iv.cnst.name 0) NameMap.empty + let initCmpCtx : CanonCmpCtx := { importMap, mutCtx := initMutCtx } + -- Step 1: Canonicalize each inductive's constructors under `initCmpCtx` + let itemsWithSortedCtors := items.map fun (iv, ctors) => + sortInductiveCtors initCmpCtx iv ctors + if itemsWithSortedCtors.size == 1 then + match itemsWithSortedCtors[0]? with + | some (iv, ctors) => + let iv' := { iv with all := #[iv.cnst.name] } + #[(iv', ctors)] + | none => #[] + else + -- Step 2: Run partition refinement on the inductives in the mutual block + let seed : List (Nat × MutConst) := (itemsWithSortedCtors.mapIdx fun idx (iv, ctors) => + (idx, MutConst.fromInductiveVal iv ctors)).toList + let refined := refineClassesLoop importMap (seed.length + 2) [seed] + let finalMutCtx := buildClassesMutCtx refined + let finalCmpCtx : CanonCmpCtx := { importMap, mutCtx := finalMutCtx } + let orderedIdxs : Array Nat := (refined.flatMap (fun cls => cls.map (·.1))).toArray + let orderedItems := orderedIdxs.filterMap fun idx => + match itemsWithSortedCtors[idx]? with + | some (iv, ctors) => some (sortInductiveCtors finalCmpCtx iv ctors) + | none => none + let canonAll : Array Ix.Name := orderedItems.map (·.1.cnst.name) + orderedItems.map fun (iv, ctors) => + ({ iv with all := canonAll }, ctors) + +/-! ## Post-Elaboration Minimal SCC Splitting & Canonicalization for Definitions -/ + +/-- Collect all constant names referenced in `e` that belong to `candidates`. -/ +def collectRefsInSet (candidates : NameSet) (e : Ix.Expr) : NameSet := + go e NameSet.empty +where + go : Ix.Expr → NameSet → NameSet + | .const nm _ _, acc => if candidates.contains nm then acc.insert nm else acc + | .app f a _, acc => go a (go f acc) + | .lam _ t b _ _, acc => go b (go t acc) + | .forallE _ t b _ _, acc => go b (go t acc) + | .letE _ t v b _ _, acc => go b (go v (go t acc)) + | .proj nm _ s _, acc => go s (if candidates.contains nm then acc.insert nm else acc) + | .mdata _ x _, acc => go x acc + | _, acc => acc + +/-- Pure fallback `Def` using `Ix.Frontend.Syntax` constructors (avoids `Ix.instInhabitedDef`). -/ +def emptyCanonDef : Def := { + name := Name.mkAnon + levelParams := #[] + type := Expr.mkBVar 0 + value := Expr.mkBVar 0 + kind := .defn + safety := .safe + hints := .opaque + all := #[] +} + +/-- Given an array of elaborated value declarations (`Def`), split them into minimal + strongly connected components based on their actual elaborated `type` and `value` + constant references, and canonically order each SCC via partition refinement! -/ +def canonicalizeElaboratedDefs (importMap : IxImportMap) + (defs : Array Def) : Array (Array Def) := + if defs.isEmpty then #[] + else if defs.size == 1 then + let d := arrayGetD defs 0 emptyCanonDef + #[#[{ d with all := #[d.name] }]] + else + let nameSet : NameSet := defs.foldl (fun s d => s.insert d.name) NameSet.empty + let nameToIdx : NameMap Nat := (defs.mapIdx fun i d => (d.name, i)).foldl + (fun m (nm, i) => m.insert nm i) NameMap.empty + let adj : Array (Array Nat) := defs.mapIdx fun i d => + let refs := collectRefsInSet nameSet d.type + let refs := (collectRefsInSet nameSet d.value).foldl (fun s n => s.insert n) refs + refs.toList.filterMap (fun nm => + match nameToIdx.get? nm with + | some j => if i == j then none else some j + | none => none) |>.toArray + match tarjanCondensation adj with + | none => + let allNames := defs.map (·.name) + #[defs.map fun d => { d with all := allNames }] + | some cond => + cond.comps.map fun comp => + if comp.size == 1 then + let idx := comp.getD 0 0 + let d := defs.getD idx emptyCanonDef + #[{ d with all := #[d.name] }] + else + let seed : List (Nat × MutConst) := (comp.map fun idx => + (idx, MutConst.defn (defs.getD idx emptyCanonDef))).toList + let refined := refineClassesLoop importMap (seed.length + 2) [seed] + let orderedIdxs := (refined.flatMap (fun cls => cls.map (·.1))).toArray + let orderedDefs := orderedIdxs.map fun idx => defs.getD idx emptyCanonDef + let canonAll := orderedDefs.map (·.name) + orderedDefs.map fun d => { d with all := canonAll } + +end Ix.Frontend.Canon diff --git a/Ix/Frontend/Circuit/BenchGen.lean b/Ix/Frontend/Circuit/BenchGen.lean new file mode 100644 index 0000000000..74648aa6a8 --- /dev/null +++ b/Ix/Frontend/Circuit/BenchGen.lean @@ -0,0 +1,144 @@ +/- + Ix.Frontend.Circuit.BenchGen: Host driver generating canonical `ElabClaim` + and `.ixi` witness invocations for compiled `IxFrontend::verify_parse` and + `IxFrontend::verify_elab` circuits (`ixcc_prove --ixvm-io`). +-/ +import Ix.Frontend.Circuit.Wire +import Ix.Frontend.Elab.CorePure +import Ix.Ixon.ElabClaim +import Ix.AiurInvocation + +set_option autoImplicit false + +namespace Ix.Frontend.Circuit.BenchGen + +open Ix.Frontend +open Ix.Frontend.Parser +open Ix.Frontend.Elab +open Ix.Frontend.Circuit.Wire + +def tinySource : String := + "def id (x : Type) : Type := x" + +/-- `FrontendPair.ix` benchmark fixture using `@[...]` mode annotations. -/ +def frontendPairSource : String := + "namespace Demo\n\nstructure Pair (α : Type) : Type where\n fst : α\n snd : α\n\ntheorem swap_fst {α : Type} (a b : α) :\n Eq (swap (Pair.mk a b)).fst b := by\n rfl\n\ndef swap {α : Type} (p : Pair α) : Pair α :=\n let x := p.fst;\n { fst := p.snd, snd := x }\n\ndef keep {α : Type} (@[unique] x : α) : @[unique] α := x\n\nend Demo\n" + +def addrTo32Nats (a : Address) : Array Nat := + a.hash.data.map UInt8.toNat + +def addrTo8Words (a : Address) : Array Nat := + let d := digestWordsOfAddress a + #[d.w0, d.w1, d.w2, d.w3, d.w4, d.w5, d.w6, d.w7] + +def bytesToNats (ba : ByteArray) : Array Nat := + ba.data.map UInt8.toNat + +def hashExportsHost (env : IxElabEnv) : Address := + let entries := nameMapToListAcc env.consts [] + let rec encodeExportsHost : List (Ix.Name × Ix.ConstantInfo) → Wire.ByteList → Wire.ByteList + | [], tail => tail + | (nm, ci) :: rest, tail => + let cAddr := hashByteListHost (encodeConstantAcc ci .nil) + let cDig := digestWordsOfAddress cAddr + encodeNameAcc nm (encodeDigestWordsAcc cDig (encodeExportsHost rest tail)) + hashByteListHost (.cons 0x45 (encodeVarNat entries.length (encodeExportsHost entries .nil))) + +def writeFixture (outDir name entryName source : String) + (kind : Ixon.ElabOutputKind) (seedPrelude withSyntax withExports : Bool) + (includeStxStream : Bool := false) : IO Unit := do + let srcBytes := source.toUTF8 + let sourceAddr := Address.blake3Pure srcBytes + let srcList := Sym.ofString source + if !Sym.validateUtf8 srcList then + throw (IO.userError s!"{name}: UTF-8 validate failed") + let (stx, _) ← IO.ofExcept (parseModuleBytesWithEnv srcList defaultParserEnv) + let stxByteList := encodeSyntaxAcc stx .nil + let stxBytes := byteListToByteArray stxByteList + let syntaxAddr := Address.blake3Pure stxBytes + if syntaxAddr != hashSyntaxHost stx then + throw (IO.userError s!"{name}: syntaxAddr mismatch") + if includeStxStream then + match decodeSyntax stxByteList with + | none => throw (IO.userError s!"{name}: decodeSyntax failed") + | some stx' => + if hashSyntaxHost stx' != syntaxAddr then + throw (IO.userError s!"{name}: decodeSyntax round-trip hash mismatch") + let (outputAddr, exportsAddr?, constCount) ← + match kind with + | .parseOnly => pure (syntaxAddr, none, 0) + | .alphaEnv => + let env ← IO.ofExcept (elabModuleSyntax stx IxElabEnv.empty seedPrelude) + let envCore ← IO.ofExcept (elabModuleSyntaxCorePure stx IxElabEnv.empty seedPrelude) + let cs := envSortedConsts env + let outA := hashAlphaEnvHost env + let outACore := hashAlphaEnvHost envCore + if outA != outACore then + throw (IO.userError s!"{name}: CorePure outputAddr mismatch ({outACore} != {outA})") + let expA := if withExports then some (hashExportsHost env) else none + if withExports then + let expACore := some (hashExportsHost envCore) + if expA != expACore then + throw (IO.userError s!"{name}: CorePure exportsAddr mismatch") + pure (outA, expA, cs.length) + | _ => throw (IO.userError "unsupported kind") + let claim : Ixon.ElabClaim := { + kind + seedPrelude + sourceAddr + outputAddr + importsAddr := none + syntaxAddr := if withSyntax then some syntaxAddr else none + exportsAddr := exportsAddr? + } + let claimBytes := claim.ser + -- Verify Lean round-trip AND pure circuit parser agreement + let dec ← IO.ofExcept (Ixon.ElabClaim.de claimBytes) + if dec != claim then + throw (IO.userError s!"{name}: ElabClaim round-trip mismatch") + let parsed := parseElabClaim (byteListOfByteArray claimBytes) + if !parsed.ok || parsed.sourceAddr != digestWordsOfAddress sourceAddr || + parsed.outputAddr != digestWordsOfAddress outputAddr then + throw (IO.userError s!"{name}: circuit parseElabClaim mismatch") + let claimAddr := claim.commit + let args := addrTo8Words claimAddr + let streams := + if includeStxStream then + #[ + { channel := 0, key := args, values := bytesToNats claimBytes }, + { channel := 5, key := addrTo32Nats syntaxAddr, values := bytesToNats stxBytes } + ] + else + #[ + { channel := 0, key := args, values := bytesToNats claimBytes }, + { channel := 4, key := addrTo32Nats sourceAddr, values := bytesToNats srcBytes } + ] + let inv : Ix.AiurInvocation.Invocation := { + entry := entryName + args := args + streams := streams + } + let ixiBytes ← IO.ofExcept inv.encode + let ixiPath := s!"{outDir}/{name}.ixi" + IO.FS.writeBinFile ixiPath ixiBytes + let argsCsv := String.intercalate "," (args.toList.map toString) + IO.println s!"{name}: src={srcBytes.size}B stx={stxBytes.size}B consts={constCount} claim={claimBytes.size}B ixi={ixiBytes.size}B" + IO.println s!" claimAddr={claimAddr} sourceAddr={sourceAddr} outputAddr={outputAddr}" + IO.println s!" args={argsCsv}" + +def main (args : List String) : IO Unit := do + let outDir := args.headD "/tmp/ixfe-bench" + IO.FS.createDirAll outDir + writeFixture outDir "tiny-parse" "IxFrontend::verify_parse" tinySource .parseOnly false false false + writeFixture outDir "pair-parse" "IxFrontend::verify_parse" frontendPairSource .parseOnly false false false + writeFixture outDir "tiny-elab" "IxFrontend::verify_elab" tinySource .alphaEnv false false false + writeFixture outDir "pair-elab" "IxFrontend::verify_elab" frontendPairSource .alphaEnv true false false + writeFixture outDir "pair-full" "IxFrontend::verify_elab" frontendPairSource .alphaEnv true true true + writeFixture outDir "tiny-elab-stx" "IxFrontend::verify_elab_stx" tinySource .alphaEnv false true false true + writeFixture outDir "pair-elab-stx" "IxFrontend::verify_elab_stx" frontendPairSource .alphaEnv true true false true + writeFixture outDir "pair-full-stx" "IxFrontend::verify_elab_stx" frontendPairSource .alphaEnv true true true true + +end Ix.Frontend.Circuit.BenchGen + +def main (args : List String) : IO Unit := + Ix.Frontend.Circuit.BenchGen.main args diff --git a/Ix/Frontend/Circuit/Entry.lean b/Ix/Frontend/Circuit/Entry.lean new file mode 100644 index 0000000000..f2647f82fa --- /dev/null +++ b/Ix/Frontend/Circuit/Entry.lean @@ -0,0 +1,117 @@ +/- + Ix.Frontend.Circuit.Entry: Single-Source Lean → Ix → Aiur Frontend Entrypoints. + + Compiles the real, general Lean-written `Ix.Frontend` (parser, scope, Tarjan SCC + scheduler, elaborator, canonicalizer, auxgen, tactics) directly to Aiur via + `IxCCAiur` under the exact 8-field Goldilocks public claim-digest ABI + (`d0 .. d7 : Nat`, matching `IxVM::verify_claim` and `Ix.DynamicLink.CodecTag.ixonAddrSingle`). + + Zero `Ix.Compile.CircuitContract`, zero `Aiur`, zero `Std.HashMap`, zero `partial`/`unsafe`. + Circuit scheduling directives live in sidecar `Ix/Frontend/Circuit/Schedule.lean` + (0 Ixon content-address mutation). +-/ +module + +public import Ix.Frontend.Circuit.Wire +public import Ix.Frontend.Elab.CorePure + +@[expose] public section + +set_option autoImplicit false + +namespace Ix.Frontend.Circuit.Entry + +open Ix.Frontend +open Ix.Frontend.Parser +open Ix.Frontend.Elab +open Ix.Frontend.Circuit.Wire + +/-- **Parse-only entrypoint (`IxFrontend::verify_parse`)**: + 1. Reads & BLAKE3-authenticates `ElabClaim` from channel 0 against `[d0..d7]`. + 2. Reads & BLAKE3-authenticates UTF-8 source bytes from channel 4 against `claim.sourceAddr`. + 3. Decodes strict UTF-8 and runs the real Lean `Ix.Frontend.Parser.parseModuleBytesRaw`. + 4. Hashes the parsed `Stx` tree via `blake3HashWords` and checks `== claim.outputAddr`. + Returns `1` iff valid, `0` otherwise. -/ +def verifyParse (d0 d1 d2 d3 d4 d5 d6 d7 : Nat) : Nat := + let claimBytes := ioReadAuthClaim d0 d1 d2 d3 d4 d5 d6 d7 + let claim := parseElabClaim claimBytes + if !claim.ok || !Nat.beq claim.kind 0 then 0 + else + let srcBytes := wireToSym (ioReadAuthChannel 4 claim.sourceAddr) + if !Sym.validateUtf8 srcBytes then 0 + else + match parseModuleBytesRaw srcBytes defaultParserEnv with + | none => 0 + | some (stx, _) => + if digestWordsEq (hashSyntaxWords stx) claim.outputAddr then 1 else 0 + +/-- **Full elaboration entrypoint (`IxFrontend::verify_elab`)**: + 1. Reads & BLAKE3-authenticates `ElabClaim` from channel 0 against `[d0..d7]`. + 2. Reads & BLAKE3-authenticates UTF-8 source bytes from channel 4 against `claim.sourceAddr`. + 3. Validates strict UTF-8 and runs `Ix.Frontend.Parser.parseModuleBytesRaw`. + 4. Dispatches on `claim.kind`: + - `0` (`.parseOnly`): checks `hashSyntaxWords stx == claim.outputAddr`. + - `1` (`.alphaEnv`): optionally checks `claim.syntaxAddr`, runs + `Ix.Frontend.Elab.elabModuleSyntaxCore stx .empty claim.seedPrelude`, + checks `hashAlphaEnvWords elabEnv == claim.outputAddr`, and optionally + checks `claim.exportsAddr` (generic content-addressed name → address map). + Returns `1` iff valid, `0` otherwise. -/ +def verifyElab (d0 d1 d2 d3 d4 d5 d6 d7 : Nat) : Nat := + let claimBytes := ioReadAuthClaim d0 d1 d2 d3 d4 d5 d6 d7 + let claim := parseElabClaim claimBytes + if !claim.ok then 0 + else + let srcBytes := wireToSym (ioReadAuthChannel 4 claim.sourceAddr) + if !Sym.validateUtf8 srcBytes then 0 + else + match parseModuleBytesRaw srcBytes defaultParserEnv with + | none => 0 + | some (stx, _) => + if Nat.beq claim.kind 0 then + if digestWordsEq (hashSyntaxWords stx) claim.outputAddr then 1 else 0 + else if Nat.beq claim.kind 1 then + let stxOk := + if claim.hasSyntax then digestWordsEq (hashSyntaxWords stx) claim.syntaxAddr + else true + if !stxOk then 0 + else + match elabModuleSyntaxCorePure stx IxElabEnv.empty claim.seedPrelude with + | .error _ => 0 + | .ok elabEnv => + let outOk := digestWordsEq (hashAlphaEnvWords elabEnv) claim.outputAddr + if !outOk then 0 + else if claim.hasExports then + if digestWordsEq (hashExportsWords elabEnv) claim.exportsAddr then 1 else 0 + else 1 + else + 0 + +/-- **Compositional elaboration-from-syntax entrypoint (`IxFrontend::verify_elab_stx`)**: + Composes cryptographically with `verifyParse` via `claim.syntaxAddr`: + 1. Reads & BLAKE3-authenticates `ElabClaim` from channel 0 against `[d0..d7]`. + 2. Reads & BLAKE3-authenticates canonical `Stx` bytes from channel 5 against `claim.syntaxAddr`. + 3. Decodes `Stx` via `decodeSyntax` (zero Parser in circuit closure!). + 4. Runs `elabModuleSyntaxCorePure stx IxElabEnv.empty claim.seedPrelude`. + 5. Checks `hashAlphaEnvWords elabEnv == claim.outputAddr` (and `exportsAddr` if set). + Returns `1` iff valid, `0` otherwise. -/ +def verifyElabStx (d0 d1 d2 d3 d4 d5 d6 d7 : Nat) : Nat := + let claimBytes := ioReadAuthClaim d0 d1 d2 d3 d4 d5 d6 d7 + let claim := parseElabClaim claimBytes + if !claim.ok || !Nat.beq claim.kind 1 || !claim.hasSyntax then 0 + else + let stxBytes := ioReadAuthChannel 5 claim.syntaxAddr + match decodeSyntax stxBytes with + | none => 0 + | some stx => + match elabModuleSyntaxCorePure stx IxElabEnv.empty claim.seedPrelude with + | .error _ => 0 + | .ok elabEnv => + let outOk := digestWordsEq (hashAlphaEnvWords elabEnv) claim.outputAddr + if !outOk then 0 + else if claim.hasExports then + if digestWordsEq (hashExportsWords elabEnv) claim.exportsAddr then 1 else 0 + else 1 + +end Ix.Frontend.Circuit.Entry + +end diff --git a/Ix/Frontend/Circuit/Schedule.lean b/Ix/Frontend/Circuit/Schedule.lean new file mode 100644 index 0000000000..f3e695b12a --- /dev/null +++ b/Ix/Frontend/Circuit/Schedule.lean @@ -0,0 +1,357 @@ +/- + Ix.Frontend.Circuit.Schedule: Sidecar `Ix.Circuit` scheduling & intrinsic + annotations for `Ix.Frontend.Circuit.Entry` (0 Ixon content-address mutation). +-/ +import Ix.Compile.CircuitContract +import Ix.Frontend.Circuit.Entry + +set_option autoImplicit false + +open scoped Ix.Circuit + +/-! ## `IxVMIO` and `Blake3` Intrinsic Bindings -/ + +attribute [circuit_intrinsic "ixvm.io.read_auth_claim"] + Ix.Frontend.Circuit.Wire.ioReadAuthClaim + +attribute [circuit_intrinsic "ixvm.io.read_auth_channel"] + Ix.Frontend.Circuit.Wire.ioReadAuthChannel9 + +attribute [circuit_intrinsic "blake3.hash_words"] + Ix.Frontend.Circuit.Wire.blake3HashWords + +/-! ## Thin Wrapper & Combinator Inlining -/ + +attribute [circuit_inline] + Bind.bind + Pure.pure + Functor.map + Seq.seq + SeqLeft.seqLeft + SeqRight.seqRight + Monad.toBind + Monad.toApplicative + Applicative.toPure + Applicative.toFunctor + Applicative.toSeq + Applicative.toSeqLeft + Applicative.toSeqRight + Except.bind + Except.pure + Except.map + Except.instMonad + Option.bind + Option.map + instMonadOption + Id.run + Id.instMonad + MonadReader.read + MonadReaderOf.read + MonadWithReader.withReader + MonadWithReaderOf.withReader + MonadState.get + MonadStateOf.get + MonadState.set + MonadStateOf.set + MonadState.modifyGet + MonadStateOf.modifyGet + MonadExceptOf.throw + MonadExceptOf.tryCatch + instMonadReaderOfMonadReaderOf + instMonadWithReaderOfMonadWithReaderOf + instMonadStateOfMonadStateOf + instMonadExceptOfMonadExceptOf + modify + readThe + getThe + withTheReader + throwThe + tryCatchThe + Ix.Frontend.Elab.instMonadIxElabM + Ix.Frontend.Elab.instMonadReaderOfIxElabM + Ix.Frontend.Elab.instMonadWithReaderOfIxElabM + Ix.Frontend.Elab.instMonadStateOfIxElabM + Ix.Frontend.Elab.instMonadExceptOfIxElabM + Ix.Frontend.Elab.IxElabM.pure + Ix.Frontend.Elab.IxElabM.bind + Ix.Frontend.Elab.IxElabM.read + Ix.Frontend.Elab.IxElabM.withReader + Ix.Frontend.Elab.IxElabM.get + Ix.Frontend.Elab.IxElabM.set + Ix.Frontend.Elab.IxElabM.modifyGet + Ix.Frontend.Elab.IxElabM.throw + Ix.Frontend.Elab.IxElabM.tryCatch + Ix.Frontend.Elab.IxElabM.run + Ix.Frontend.Elab.modifyMCtx + Ix.Frontend.Elab.modifyEnv + Ix.Frontend.Elab.withRef + Ix.Frontend.Elab.withLocalDecl + Ix.Frontend.Elab.withLetDecl + Ix.Frontend.Elab.mkFreshIdx + Ix.Frontend.Elab.mkFreshName + Ix.Frontend.Elab.throwElabError + Ix.Frontend.Elab.expandMacroM + Ix.Frontend.Elab.observing? + Ix.Frontend.Elab.MetavarContext.bindMCtx + Ix.Frontend.Elab.whnf + Ix.Frontend.Elab.whnfForall + Ix.Frontend.Elab.whnfForallPure + Ix.Frontend.Elab.instantiateMVars + Ix.Frontend.Elab.instantiateMVarsCore + Ix.Frontend.Elab.instantiateLevelMVars + Ix.Frontend.Elab.instantiateLevelMVarsCore + Ix.Frontend.Elab.isLevelDefEq + Ix.Frontend.Elab.mkFreshLevelMVar + Ix.Frontend.Elab.mkFreshExprMVar + Ix.Frontend.Elab.inferType + Ix.Frontend.Elab.isDefEq + Ix.Frontend.Elab.ensureSort + Ix.Frontend.Elab.mkFreshLevelMVarsFor + Ix.Frontend.Elab.mkConstWithFreshMVarLevels + Ix.Frontend.Elab.insertImplicitArgs + Ix.Frontend.Elab.openForallMVars + Ix.Frontend.Elab.synthInstance? + Ix.Frontend.Elab.elabBinderGroups + Ix.Frontend.Elab.elabTermCore + Ix.Frontend.Elab.errPure + Ix.Frontend.Elab.withRefPure + Ix.Frontend.Elab.setEnvPure + Ix.Frontend.Elab.setMCtxPure + Ix.Frontend.Elab.mkForallFVarsPure + Ix.Frontend.Elab.mkLambdaFVarsPure + Ix.Frontend.Elab.expandMacroPureSt + Ix.Frontend.Elab.elabTermCoreDirect + Function.comp + GetElem.getElem + GetElem?.getElem? + Array.instGetElemNatLtSize + Array.instGetElem?NatLtSize + Vector.instGetElemNatLt + instPowNat + Ix.Frontend.Canon.resolveCanonAddr + Ix.Frontend.Circuit.Wire.unboxByte + Ix.Frontend.Circuit.Wire.ioReadAuthChannel + Ix.Frontend.Circuit.Wire.zeroDigestWords + Ix.Frontend.Circuit.Wire.isByteListNil + Ix.Frontend.Circuit.Wire.encodeBool + Ix.Frontend.Circuit.Wire.encodeBinderInfoTag + Ix.Frontend.Circuit.Wire.encodeSafetyByte + Ix.Frontend.forceNat + Ix.Frontend.Parser.InputContext.bindNat + Ix.Frontend.Parser.ParserState.bindState + Ix.Frontend.Parser.IxParserEnv.bindParserEnv + Ix.Frontend.Parser.bindPeek + Ix.Frontend.Parser.nodeFn + Ix.Frontend.Parser.atomicFn + Ix.Frontend.Parser.orelseFn + Ix.Frontend.Parser.tryOrElseFn + Ix.Frontend.Parser.seqFn + Ix.Frontend.Parser.optionalFn + Ix.Frontend.Parser.withPrecFn + Ix.Frontend.NameMap.bindMap + Ix.Frontend.NameSet.bindSet + Ix.Frontend.Elab.IxElabEnv.bindEnv + +/-! ## Keep Split Cold Parser Helpers Outlined (Narrow Hot Chips) -/ + +attribute [circuit_noinline] + Ix.Frontend.Parser.isDefaultKeywordAI + Ix.Frontend.Parser.isDefaultKeywordLW + Ix.Frontend.Parser.matchDefaultUtf8TokenBytes + Ix.Frontend.Parser.matchDefaultAsciiOpBytes + Ix.Frontend.Parser.lookupDefaultInfixOpCore + Ix.Frontend.Parser.isCommandStartAtom + Ix.Frontend.Parser.isCommandStartWord + Ix.Frontend.Parser.commandNonDeclFn + Ix.Frontend.Parser.commandWordFn + Ix.Frontend.Parser.scanUtf8LetterLike + Ix.Frontend.Parser.scanSpecialLitToken + Ix.Frontend.Parser.scanEscapedIdentComponent + Ix.Frontend.Parser.scanMergeIdentComponent + Ix.Frontend.Parser.leadTermQuote + Ix.Frontend.Parser.leadTermQuantifier + Ix.Frontend.Parser.leadTermLetHave + Ix.Frontend.Parser.leadTermDelims + Ix.Frontend.Parser.tacticCoreSimple + Ix.Frontend.Parser.tacticCoreBinders + Ix.Frontend.Parser.trailNotationStep + Ix.Frontend.Parser.trailAtomOpStep + Ix.Frontend.Parser.updateParserEnvFromCommand + Ix.Frontend.Elab.elabTermLetGo + Ix.Frontend.Elab.elabTermLetRecGo + Ix.Frontend.Elab.elabTermHaveGo + Ix.Frontend.Elab.elabTermBinOpGo + Ix.Frontend.Elab.elabTermAnonCtorGo + Ix.Frontend.Elab.elabTermStructInstGo + Ix.Frontend.Elab.elabTermIfGo + Ix.Frontend.Elab.elabTermMatchGo + Ix.Frontend.Elab.elabTermAppGo + Ix.Frontend.Elab.elabStructureFieldsCorePure + Ix.Frontend.Elab.elabDerivingHandlersCorePure + Ix.Frontend.Elab.seedCoreBasic + Ix.Frontend.Elab.seedCoreBoolNat + Ix.Frontend.Elab.seedCorePUnitUnit + Ix.Frontend.Elab.seedCoreEq + Ix.Frontend.Elab.seedCoreLogic + Ix.Frontend.Elab.seedCoreTrueFalseNotNe + Ix.Frontend.Elab.seedCoreAndOr + Ix.Frontend.Elab.seedCoreIffExists + Ix.Frontend.Elab.seedCoreData + Ix.Frontend.Elab.seedCoreProd + Ix.Frontend.Elab.seedCoreList + Ix.Frontend.Elab.seedCoreString + Ix.Frontend.Elab.seedCorePrimAxioms + Ix.Frontend.Elab.seedCoreClasses + Ix.Frontend.Elab.seedCoreClassesBody + Ix.Frontend.Elab.seedCoreOrderRel + Ix.Frontend.Elab.seedCoreDecidable + Ix.Frontend.Elab.seedCoreSubSigma + -- Keep pattern-matching helpers outlined so their `*.match_1` splitters collapse once + -- instead of being duplicated across dozens of call sites before ANF shrinks them: + Ix.Frontend.Syntax.getKind + Ix.Frontend.Syntax.getKindF + Ix.Frontend.Syntax.isOfKind + Ix.Frontend.Syntax.isOfKindF + Ix.Frontend.Syntax.isMissing + Ix.Frontend.Syntax.isNone + Ix.Frontend.Syntax.getArgs + Ix.Frontend.Syntax.getArgsStx + Ix.Frontend.Syntax.getNumArgs + Ix.Frontend.Syntax.getArg + Ix.Frontend.Syntax.getOptional? + Ix.Frontend.Syntax.getId + Ix.Frontend.Syntax.getIdF + Ix.Frontend.Syntax.getAtomVal + Ix.Frontend.Name.isAnonymous + Ix.Frontend.Name.beqStruct + Ix.Frontend.Name.cmpStruct + Ix.Frontend.Name.append + Ix.Frontend.Expr.beqStruct + Ix.Frontend.Level.beqStruct + Ix.Frontend.Sym.toString + Ix.Frontend.Sym.ofString + Ix.Frontend.Sym.beq + Ix.Frontend.FName.toIxName + Ix.Frontend.FName.beq + Ix.Frontend.Stx.toArray + Ix.Frontend.Stx.toList + Ix.Frontend.Stx.getD + Ix.Frontend.Stx.get? + Ix.Frontend.Elab.stripMData + Ix.Frontend.Elab.evalNatLit? + Ix.Frontend.Elab.evalCharCode? + Ix.Frontend.Elab.evalCharCodeList? + Ix.Frontend.Elab.tryReduceUnaryPrim + Ix.Frontend.Elab.tryReduceBinaryPrim + Ix.Frontend.Elab.strLitToCtorExpr + Ix.Frontend.Elab.mkBoolExpr + Ix.Frontend.Elab.getAppFnArgs + Ix.Frontend.Elab.instantiate1 + Ix.Frontend.Elab.substExprLevelParams + Ix.Frontend.Elab.liftLooseBVars + Ix.Frontend.Elab.hasLooseBVars + Ix.Frontend.Elab.isDefEqPure + Ix.Frontend.Elab.isDefEqMVarStep + Ix.Frontend.Elab.isDefEqStructStep + Ix.Frontend.Elab.isDefEqWhnfStep + Ix.Frontend.Elab.isDefEqWhnfBinderStep + Ix.Frontend.Elab.isDefEqWhnfAtomStep + Ix.Frontend.Elab.whnfPure + Ix.Frontend.Elab.inferTypePure + Ix.Frontend.Elab.synthInstancePure + Ix.Frontend.Elab.decodeBinderNode + Ix.Frontend.Elab.collectAutoImplicitGroups + Ix.Frontend.processCommandPass1 + Ix.Frontend.scanSyntaxRefsMap + Ix.Frontend.scanPatternMap + Ix.Frontend.extractDeclDepsMap + Ix.Frontend.scheduleModuleDeclsMap + Ix.Frontend.resolveIdentInScopeMap + Ix.Frontend.Parser.decodeNotationOrMacroDecl + Ix.Frontend.Canon.compareExpr + Ix.Frontend.Circuit.Wire.parseAddrWords + +/-! ## Fuel-Erasable Parser Loops (`2^40` Fuel -> Memoization) -/ + +attribute [circuit_fuel] + Ix.Frontend.Parser.skipBlockCommentBytes + Ix.Frontend.Parser.skipWhitespaceBytes + Ix.Frontend.Parser.scanIdentRestBytes + Ix.Frontend.Parser.manyIdentLoop + Ix.Frontend.Parser.sepByIdentCommaLoop + Ix.Frontend.Parser.manySameLineIdentLoop + Ix.Frontend.Parser.manyLevelAtomAddLoop + Ix.Frontend.Parser.levelStep + Ix.Frontend.Parser.sepByLevelCommaLoop + Ix.Frontend.Parser.manyBinderIdentLoop + Ix.Frontend.Parser.manySameLineBinderIdentLoop + Ix.Frontend.Parser.manyBracketedBinderLoop + Ix.Frontend.Parser.manySimpleOrBracketedBinderLoop + Ix.Frontend.Parser.sepByTermCommaLoop + Ix.Frontend.Parser.sepByRcasesPatCommaLoop + Ix.Frontend.Parser.sepByRcasesPatAltLoop + Ix.Frontend.Parser.manyCalcStepLoop + Ix.Frontend.Parser.manySameLineRcasesPatAtomLoop + Ix.Frontend.Parser.manySameLineTermArgLoop + Ix.Frontend.Parser.sepByRwRuleCommaLoop + Ix.Frontend.Parser.manyTacticFirstBranchLoop + Ix.Frontend.Parser.manyTacticAltLoop + Ix.Frontend.Parser.manyTacticStepLoop + Ix.Frontend.Parser.manyMatchAltLoop + Ix.Frontend.Parser.sepByFieldAssignCommaLoop + Ix.Frontend.Parser.trailingTermLoop + Ix.Frontend.Parser.termStep + Ix.Frontend.Parser.manyCtorDeclLoop + Ix.Frontend.Parser.manyStructFieldDeclLoop + Ix.Frontend.Parser.manyWhereItemLoop + Ix.Frontend.Parser.manyInstanceFieldAssignLoop + Ix.Frontend.Parser.manyMutualCmdLoop + Ix.Frontend.Parser.manyMergeArmLoop + Ix.Frontend.Parser.commandStep + Ix.Frontend.Parser.parseModuleLoopRaw + +/-! ## Dedicated Singleton Groups for Hot Narrow Parser Loops (Prevent `auto_grp_*` Width Bloat) -/ + +attribute [circuit_group "ixfe_hot_sym_beq"] Ix.Frontend.Sym.beq +attribute [circuit_group "ixfe_hot_sym_append"] Ix.Frontend.Sym.append +attribute [circuit_group "ixfe_hot_sym_rev"] Ix.Frontend.Sym.reverseAcc +attribute [circuit_group "ixfe_hot_sym_len"] Ix.Frontend.Sym.lengthAcc +attribute [circuit_group "ixfe_hot_sym_utf8cnt"] Ix.Frontend.Sym.utf8CharCountAcc +attribute [circuit_group "ixfe_hot_sym_utf8val"] Ix.Frontend.Sym.validateUtf8 +attribute [circuit_group "ixfe_hot_fname_beq"] Ix.Frontend.FName.beq +attribute [circuit_group "ixfe_hot_skip_ws"] Ix.Frontend.Parser.skipWhitespaceBytes +attribute [circuit_group "ixfe_hot_skip_hws"] Ix.Frontend.Parser.skipHorizontalWhitespaceBytes +attribute [circuit_group "ixfe_hot_scan_id"] Ix.Frontend.Parser.scanIdentRestBytes +attribute [circuit_group "ixfe_hot_scan_tok"] Ix.Frontend.Parser.scanNextToken +attribute [circuit_group "ixfe_hot_tok"] Ix.Frontend.Parser.tokenFn +attribute [circuit_group "ixfe_hot_peek"] Ix.Frontend.Parser.peekToken +attribute [circuit_group "ixfe_hot_sym_fn"] Ix.Frontend.Parser.symbolFn +attribute [circuit_group "ixfe_hot_pop_stx"] Ix.Frontend.Parser.SyntaxStack.popTopNStx +attribute [circuit_group "ixfe_hot_drop_stx"] Ix.Frontend.Parser.SyntaxStack.dropTopN +attribute [circuit_group "ixfe_hot_stx_size"] Ix.Frontend.Stx.sizeAux +attribute [circuit_group "ixfe_hot_enc_stx"] Ix.Frontend.Circuit.Wire.encodeSyntaxAcc +attribute [circuit_group "ixfe_hot_enc_fname"] Ix.Frontend.Circuit.Wire.encodeFNameAcc +attribute [circuit_group "ixfe_hot_enc_varnat"] Ix.Frontend.Circuit.Wire.encodeVarNatFuel +attribute [circuit_group "ixfe_hot_enc_u8"] Ix.Frontend.Circuit.Wire.u8ListEncodeAcc +attribute [circuit_group "ixfe_hot_enc_name"] Ix.Frontend.Circuit.Wire.encodeNameAcc +attribute [circuit_group "ixfe_hot_enc_expr"] Ix.Frontend.Circuit.Wire.encodeExprAcc +attribute [circuit_group "ixfe_hot_enc_const"] Ix.Frontend.Circuit.Wire.encodeConstantAcc +attribute [circuit_group "ixfe_hot_dec_stx"] Ix.Frontend.Circuit.Wire.decodeSyntaxFuel +attribute [circuit_group "ixfe_hot_dec_fname"] Ix.Frontend.Circuit.Wire.decodeFNameFuel +attribute [circuit_group "ixfe_hot_dec_varnat"] Ix.Frontend.Circuit.Wire.decodeVarNatFuel +attribute [circuit_group "ixfe_hot_dec_sym"] Ix.Frontend.Circuit.Wire.decodeSymCharsRev +attribute [circuit_group "ixfe_hot_name_cmp"] Ix.Frontend.Name.cmpStruct +attribute [circuit_group "ixfe_hot_name_beq"] Ix.Frontend.Name.beqStruct +attribute [circuit_group "ixfe_hot_inst1"] Ix.Frontend.Elab.instantiate1At +attribute [circuit_group "ixfe_hot_abs_fvar"] Ix.Frontend.Elab.abstractFVarAt +attribute [circuit_group "ixfe_hot_nm_contains"] Ix.Frontend.NameMap.contains +attribute [circuit_group "ixfe_hot_nm_ins"] Ix.Frontend.NameMap.ins +attribute [circuit_group "ixfe_hot_enc_lvls"] Ix.Frontend.Circuit.Wire.encodeLevelsListAcc +attribute [circuit_group "ixfe_hot_enc_lvl"] Ix.Frontend.Circuit.Wire.encodeLevelAcc +attribute [circuit_group "ixfe_hot_enc_names"] Ix.Frontend.Circuit.Wire.encodeNamesListAcc +attribute [circuit_group "ixfe_hot_fast_tok"] Ix.Frontend.Parser.matchDefaultTokenBytes +attribute [circuit_group "ixfe_hot_fast_kw"] Ix.Frontend.Parser.isDefaultKeyword +attribute [circuit_group "ixfe_hot_fast_arg"] Ix.Frontend.Parser.defaultCanStartArgAtom +attribute [circuit_group "ixfe_hot_fast_infix"] Ix.Frontend.Parser.lookupDefaultInfixOp? +attribute [circuit_group "ixfe_hot_lead_term"] Ix.Frontend.Parser.leadTermFn +attribute [circuit_group "ixfe_hot_trail_term"] Ix.Frontend.Parser.trailingTermLoop diff --git a/Ix/Frontend/Circuit/Wire.lean b/Ix/Frontend/Circuit/Wire.lean new file mode 100644 index 0000000000..8306e03707 --- /dev/null +++ b/Ix/Frontend/Circuit/Wire.lean @@ -0,0 +1,747 @@ +/- + Ix.Frontend.Circuit.Wire: Pure first-order wire primitives, UTF-8 decoding, + unified ElabClaim decoding, and O(N) canonical ByteList serializers + for compiling `Ix.Frontend` to Aiur via `IxCCAiur`. + + Pure hygiene: zero `Ix.Compile.CircuitContract`, zero `Aiur`, zero `Std.HashMap`, + zero `USize`, zero `partial`/`unsafe`/`sorry`/`axiom`. +-/ +module + +public import Ix.Frontend.Elab.Command +public import Ix.Address.Pure + +@[expose] public section + +set_option autoImplicit false + +namespace Ix.Frontend.Circuit.Wire + +open Ix.Frontend +open Ix.Frontend.Elab + +/-! ## Section 1: Monomorphic Wire ADTs (Matching `IxCCAiur.IxVM.Wire`) -/ + +/-- Dedicated monomorphic wire byte list (`Bytes::Stream = Lists::List`). + Kept distinct from `Ix.Frontend.Sym` so polymorphic containers holding `Sym` + (`Stx`, `FName`, `List Sym`, `Option Sym`) never pollute `Wire.ByteList` to `Obj`! -/ +inductive ByteList where + | nil : ByteList + | cons (b : Nat) (rest : ByteList) : ByteList + deriving BEq, DecidableEq, Repr, Inhabited + +/-- Force a `Nat` byte to unboxed `Shape.nat` (`Field`) without a divmod lookup, + preventing `.any`-shaped inputs from polluting `Wire.ByteList.cons`'s head + field out of zero-copy `Bytes::Stream` lowering (`rewriteByteListProgram`). -/ +@[inline] def unboxByte (b : Nat) : Nat := + Nat.sub (Nat.add b 1) 1 + +def wireToSym : ByteList → Sym + | .nil => .nil + | .cons b rest => .cons b (wireToSym rest) + +def appendSymToWire : Sym → ByteList → ByteList + | .nil, tail => tail + | .cons b rest, tail => .cons (unboxByte b) (appendSymToWire rest tail) + +/-- 8 little-endian 32-bit words representing a 32-byte BLAKE3 digest. -/ +structure DigestWords where + w0 : Nat + w1 : Nat + w2 : Nat + w3 : Nat + w4 : Nat + w5 : Nat + w6 : Nat + w7 : Nat + deriving BEq, DecidableEq, Repr, Inhabited + +def zeroDigestWords : DigestWords := + { w0 := 0, w1 := 0, w2 := 0, w3 := 0, w4 := 0, w5 := 0, w6 := 0, w7 := 0 } + +def digestWordsEq (a b : DigestWords) : Bool := + Nat.beq a.w0 b.w0 && Nat.beq a.w1 b.w1 && Nat.beq a.w2 b.w2 && Nat.beq a.w3 b.w3 && + Nat.beq a.w4 b.w4 && Nat.beq a.w5 b.w5 && Nat.beq a.w6 b.w6 && Nat.beq a.w7 b.w7 + +structure ParseU8 where + ok : Bool + val : Nat + rest : ByteList + deriving BEq, DecidableEq, Repr + +structure ParseU32 where + ok : Bool + val : Nat + rest : ByteList + deriving BEq, DecidableEq, Repr + +structure ParseAddrWords where + ok : Bool + addr : DigestWords + rest : ByteList + deriving BEq, DecidableEq, Repr + +structure ParseTagN where + ok : Bool + flag : Nat + lo32 : Nat + hi32 : Nat + rest : ByteList + deriving BEq, DecidableEq, Repr + +/-! ## Section 2: `IxVMIO`, `Blake3`, and `IxCodec` Intrinsic Boundaries -/ + +/-- `@[circuit_intrinsic "ixvm.io.read_auth_claim"]`: query channel 0 (`ixvm.io.claim`), + verify `BLAKE3(stream) == [d0..d7]` on the raw `Bytes::Stream`, and return `ByteList`. -/ +def ioReadAuthClaim (d0 d1 d2 d3 d4 d5 d6 d7 : Nat) : ByteList := + if Nat.beq d0 0 && Nat.beq d1 0 && Nat.beq d2 0 && Nat.beq d3 0 && + Nat.beq d4 0 && Nat.beq d5 0 && Nat.beq d6 0 && Nat.beq d7 0 + then .nil else .cons 4 .nil + +/-- `@[circuit_intrinsic "ixvm.io.read_auth_channel"]`: query `ixvm.io.info(channel, key)`, + verify `BLAKE3(stream) == [w0..w7]` on the raw `Bytes::Stream`, and return `ByteList`. -/ +def ioReadAuthChannel9 (channel w0 w1 w2 w3 w4 w5 w6 w7 : Nat) : ByteList := + if Nat.beq channel 0 && Nat.beq w0 0 && Nat.beq w1 0 && Nat.beq w2 0 && + Nat.beq w3 0 && Nat.beq w4 0 && Nat.beq w5 0 && Nat.beq w6 0 && Nat.beq w7 0 + then .nil else .cons 5 .nil + +/-- Thin wrapper unpacking `DigestWords` into 9 flat scalars for `ioReadAuthChannel9`. -/ +def ioReadAuthChannel (channel : Nat) (key : DigestWords) : ByteList := + ioReadAuthChannel9 channel key.w0 key.w1 key.w2 key.w3 key.w4 key.w5 key.w6 key.w7 + +/-- `@[circuit_intrinsic "blake3.hash_words"]`: compute 8 LE 32-bit BLAKE3 digest words. -/ +def blake3HashWords (bs : ByteList) : DigestWords := + match bs with + | .nil => zeroDigestWords + | .cons b _ => + let m := Nat.mod b 256 + { w0 := m, w1 := m, w2 := m, w3 := m, w4 := m, w5 := m, w6 := m, w7 := m } + +/-! ## Section 3: Pure Wire Decoders -/ + +def parseU8 : ByteList → ParseU8 + | .cons b rest => { ok := true, val := b, rest } + | .nil => { ok := false, val := 0, rest := .nil } + +def popWordLE : ByteList → ParseU32 + | .cons b0 (.cons b1 (.cons b2 (.cons b3 rest))) => + let w := Nat.add (Nat.mod b0 256) (Nat.add (Nat.mul (Nat.mod b1 256) 256) + (Nat.add (Nat.mul (Nat.mod b2 256) 65536) (Nat.mul (Nat.mod b3 256) 16777216))) + { ok := true, val := w, rest } + | s => { ok := false, val := 0, rest := s } + +/-- Consume a 32-byte address into flat `DigestWords` (`@[circuit_intrinsic "ixvm.codec.read_addr32"]`). -/ +def parseAddrWords (s : ByteList) : ParseAddrWords := + let p0 := popWordLE s + let p1 := popWordLE p0.rest + let p2 := popWordLE p1.rest + let p3 := popWordLE p2.rest + let p4 := popWordLE p3.rest + let p5 := popWordLE p4.rest + let p6 := popWordLE p5.rest + let p7 := popWordLE p6.rest + { ok := p7.ok + addr := { w0 := p0.val, w1 := p1.val, w2 := p2.val, w3 := p3.val, + w4 := p4.val, w5 := p5.val, w6 := p6.val, w7 := p7.val } + rest := p7.rest } + +/-- Read `k` little-endian bytes (`k ≤ 4`) as a `Nat`. -/ +def readBytesLEAux : Nat → Nat → Nat → ByteList → ParseU32 + | 0, acc, _, s => { ok := true, val := acc, rest := s } + | _ + 1, _, _, .nil => { ok := false, val := 0, rest := .nil } + | k + 1, acc, mult, .cons b rest => + readBytesLEAux k (Nat.add acc (Nat.mul b mult)) (Nat.mul mult 256) rest + +/-- Pure `TagN(0)` varint decoder (`@[circuit_intrinsic "ixvm.codec.read_tag0"]`). -/ +def parseTagN0 (s : ByteList) : ParseTagN := + match s with + | .nil => { ok := false, flag := 0, lo32 := 0, hi32 := 0, rest := .nil } + | .cons hdr rest => + if Nat.blt hdr 128 then + { ok := true, flag := 0, lo32 := hdr, hi32 := 0, rest } + else if Nat.blt hdr 192 then + match rest with + | .cons b0 r1 => + let v := Nat.add 128 (Nat.add (Nat.mul (Nat.sub hdr 128) 256) b0) + { ok := true, flag := 0, lo32 := v, hi32 := 0, rest := r1 } + | .nil => { ok := false, flag := 0, lo32 := 0, hi32 := 0, rest := .nil } + else if Nat.blt hdr 224 then + match rest with + | .cons b0 (.cons b1 r2) => + let v := Nat.add 16512 (Nat.add (Nat.mul (Nat.sub hdr 192) 65536) + (Nat.add (Nat.mul b0 256) b1)) + { ok := true, flag := 0, lo32 := v, hi32 := 0, rest := r2 } + | _ => { ok := false, flag := 0, lo32 := 0, hi32 := 0, rest := .nil } + else + { ok := false, flag := 0, lo32 := 0, hi32 := 0, rest := .nil } + +/-- Pure `TagN(4)` header decoder (`@[circuit_intrinsic "ixvm.codec.read_tag4"]`). -/ +def parseTagN4 (s : ByteList) : ParseTagN := + match s with + | .nil => { ok := false, flag := 0, lo32 := 0, hi32 := 0, rest := .nil } + | .cons hdr rest => + let flag := Nat.div hdr 16 + let low := Nat.mod hdr 16 + if Nat.blt low 8 then + { ok := true, flag, lo32 := low, hi32 := 0, rest } + else if Nat.blt low 12 then + match rest with + | .cons b0 r1 => + let v := Nat.add 8 (Nat.add (Nat.mul (Nat.sub low 8) 256) b0) + { ok := true, flag, lo32 := v, hi32 := 0, rest := r1 } + | .nil => { ok := false, flag := 0, lo32 := 0, hi32 := 0, rest := .nil } + else + { ok := false, flag := 0, lo32 := 0, hi32 := 0, rest := .nil } + +def skipAddrs : Nat → ByteList → ParseU8 + | 0, s => { ok := true, val := 0, rest := s } + | n + 1, s => + let p := parseAddrWords s + match p.ok with + | false => { ok := false, val := 0, rest := .nil } + | true => skipAddrs n p.rest + +def isByteListNil : ByteList → Bool + | .nil => true + | .cons _ _ => false + +/-! ## Section 4: Unified `ElabClaim` (`0xE8 0x0B | 04 03`) Wire Parser -/ + +/-- Decoded elaboration claim from channel 0 (`0xE8 0x0B | 04 03`). -/ +structure ParsedElabClaim where + ok : Bool + kind : Nat -- 0 = parseOnly, 1 = alphaEnv, 2 = ixonEnv, 3 = singleConst + seedPrelude : Bool + sourceAddr : DigestWords + outputAddr : DigestWords + hasImports : Bool + importsAddr : DigestWords + hasSyntax : Bool + syntaxAddr : DigestWords + hasExports : Bool + exportsAddr : DigestWords + deriving BEq, DecidableEq, Repr + +def failParsedElabClaim : ParsedElabClaim := + { ok := false, kind := 0, seedPrelude := false + sourceAddr := zeroDigestWords, outputAddr := zeroDigestWords + hasImports := false, importsAddr := zeroDigestWords + hasSyntax := false, syntaxAddr := zeroDigestWords + hasExports := false, exportsAddr := zeroDigestWords } + +/-- Decode the unified `Ixon.ElabClaim` (`E8 0B | 04 03 | kind | flags | sourceAddr:32 | outputAddr:32 [optional...]`), + enforcing exact EOF. -/ +def parseElabClaim (s : ByteList) : ParsedElabClaim := + let t := parseTagN4 s + if !t.ok || !Nat.beq t.flag 14 || !Nat.beq t.lo32 19 || !Nat.beq t.hi32 0 then + failParsedElabClaim + else + let pFmt := parseU8 t.rest + if !pFmt.ok || !Nat.beq pFmt.val 4 then + failParsedElabClaim + else + let pVal := parseU8 pFmt.rest + if !pVal.ok || !Nat.beq pVal.val 3 then + failParsedElabClaim + else + let pKind := parseU8 pVal.rest + if !pKind.ok || !Nat.blt pKind.val 4 then failParsedElabClaim + else + let pFlags := parseU8 pKind.rest + if !pFlags.ok || !Nat.blt pFlags.val 16 then failParsedElabClaim + else + let flags := pFlags.val + let seedPrelude := Nat.beq (Nat.mod flags 2) 1 + let hasImports := Nat.beq (Nat.mod (Nat.div flags 2) 2) 1 + let hasSyntax := Nat.beq (Nat.mod (Nat.div flags 4) 2) 1 + let hasExports := Nat.beq (Nat.mod (Nat.div flags 8) 2) 1 + let pSrc := parseAddrWords pFlags.rest + if !pSrc.ok then failParsedElabClaim + else + let pOut := parseAddrWords pSrc.rest + if !pOut.ok then failParsedElabClaim + else + let (ok1, impAddr, r1) := + if hasImports then + let p := parseAddrWords pOut.rest + (p.ok, p.addr, p.rest) + else (true, zeroDigestWords, pOut.rest) + if !ok1 then failParsedElabClaim + else + let (ok2, stxAddr, r2) := + if hasSyntax then + let p := parseAddrWords r1 + (p.ok, p.addr, p.rest) + else (true, zeroDigestWords, r1) + if !ok2 then failParsedElabClaim + else + let (ok3, expAddr, r3) := + if hasExports then + let p := parseAddrWords r2 + (p.ok, p.addr, p.rest) + else (true, zeroDigestWords, r2) + if !ok3 || !isByteListNil r3 then failParsedElabClaim + else + { ok := true, kind := pKind.val, seedPrelude + sourceAddr := pSrc.addr, outputAddr := pOut.addr + hasImports, importsAddr := impAddr + hasSyntax, syntaxAddr := stxAddr + hasExports, exportsAddr := expAddr } + +/-! ## Section 5: Strict Pure UTF-8 Decoder & Encoder (`ByteList ↔ List Char`) -/ + +/-- Strict UTF-8 decoder from `ByteList` into `Option (List Char)` (structurally recursive). -/ +def decodeUtf8Aux : ByteList → List Char → Option (List Char) + | .nil, revAcc => some revAcc.reverse + | .cons b0 rest, revAcc => + if Nat.blt b0 128 then + decodeUtf8Aux rest (Char.ofNat b0 :: revAcc) + else if Nat.ble 194 b0 && Nat.ble b0 223 then + match rest with + | .cons b1 r1 => + if Nat.ble 128 b1 && Nat.blt b1 192 then + let cp := Nat.add (Nat.mul (Nat.sub b0 192) 64) (Nat.sub b1 128) + decodeUtf8Aux r1 (Char.ofNat cp :: revAcc) + else none + | .nil => none + else if Nat.ble 224 b0 && Nat.ble b0 239 then + match rest with + | .cons b1 (.cons b2 r2) => + if Nat.ble 128 b1 && Nat.blt b1 192 && Nat.ble 128 b2 && Nat.blt b2 192 then + let cp := Nat.add (Nat.mul (Nat.sub b0 224) 4096) + (Nat.add (Nat.mul (Nat.sub b1 128) 64) (Nat.sub b2 128)) + if Nat.ble 2048 cp && (Nat.blt cp 55296 || Nat.ble 57344 cp) then + decodeUtf8Aux r2 (Char.ofNat cp :: revAcc) + else none + else none + | _ => none + else if Nat.ble 240 b0 && Nat.ble b0 244 then + match rest with + | .cons b1 (.cons b2 (.cons b3 r3)) => + if Nat.ble 128 b1 && Nat.blt b1 192 && + Nat.ble 128 b2 && Nat.blt b2 192 && + Nat.ble 128 b3 && Nat.blt b3 192 then + let cp := Nat.add (Nat.mul (Nat.sub b0 240) 262144) + (Nat.add (Nat.mul (Nat.sub b1 128) 4096) + (Nat.add (Nat.mul (Nat.sub b2 128) 64) (Nat.sub b3 128))) + if Nat.ble 65536 cp && Nat.ble cp 1114111 then + decodeUtf8Aux r3 (Char.ofNat cp :: revAcc) + else none + else none + | _ => none + else + none + +def decodeUtf8Bytes (bs : ByteList) : Option (List Char) := + decodeUtf8Aux bs [] + +/-- Encode a single Unicode scalar `Char` as UTF-8 bytes prepended to `tail` (O(1)). -/ +def encodeCharUtf8Acc (c : Char) (tail : ByteList) : ByteList := + let n := c.val.toNat + if Nat.blt n 128 then + .cons (unboxByte n) tail + else if Nat.blt n 2048 then + .cons (Nat.add 192 (Nat.div n 64)) + (.cons (Nat.add 128 (Nat.mod n 64)) tail) + else if Nat.blt n 65536 then + .cons (Nat.add 224 (Nat.div n 4096)) + (.cons (Nat.add 128 (Nat.mod (Nat.div n 64) 64)) + (.cons (Nat.add 128 (Nat.mod n 64)) tail)) + else + .cons (Nat.add 240 (Nat.div n 262144)) + (.cons (Nat.add 128 (Nat.mod (Nat.div n 4096) 64)) + (.cons (Nat.add 128 (Nat.mod (Nat.div n 64) 64)) + (.cons (Nat.add 128 (Nat.mod n 64)) tail))) + +/-- Encode a `List Char` as UTF-8 bytes prepended to `tail` in O(N). -/ +def encodeCharsUtf8Acc : List Char → ByteList → ByteList + | [], tail => tail + | c :: cs, tail => encodeCharUtf8Acc c (encodeCharsUtf8Acc cs tail) + +/-- Encode a `Nat` using LEB128-like base-128 varint (7 bits/byte) prepended to `tail`. -/ +def encodeVarNatFuel : Nat → Nat → ByteList → ByteList + | 0, n, tail => .cons (Nat.mod n 128) tail + | k + 1, n, tail => + if Nat.blt n 128 then + .cons (unboxByte n) tail + else + .cons (Nat.add 128 (Nat.mod n 128)) (encodeVarNatFuel k (Nat.div n 128) tail) + +def encodeVarNat (n : Nat) (tail : ByteList) : ByteList := + encodeVarNatFuel 16 n tail + +def encodeBool (b : Bool) (tail : ByteList) : ByteList := + .cons (if b then 1 else 0) tail + +def encodeSymAcc (s : Sym) (tail : ByteList) : ByteList := + encodeVarNat (Sym.utf8CharCount s) (appendSymToWire s tail) + +def encodeFNameAcc : FName → ByteList → ByteList + | .anon, tail => .cons 20 tail + | .str p s, tail => .cons 21 (encodeFNameAcc p (encodeSymAcc s tail)) + | .num p n, tail => .cons 22 (encodeFNameAcc p (encodeVarNat n tail)) + +/-- Monomorphic result for single-pass UTF-8 char-counting + `ByteList` emission + (keeps `Wire.ByteList` unpolluted and halves `encodeStringAcc` traversal rows). -/ +structure U8EncodeRes where + count : Nat + bytes : ByteList + +def u8ListEncodeAcc : List UInt8 → ByteList → U8EncodeRes + | [], tail => { count := 0, bytes := tail } + | b :: rest, tail => + let r := u8ListEncodeAcc rest tail + let n := unboxByte b.toNat + let c := if Nat.ble 128 n && Nat.ble n 191 then r.count else Nat.add r.count 1 + { count := c, bytes := .cons n r.bytes } + +def encodeStringAcc (s : String) (tail : ByteList) : ByteList := + let r := u8ListEncodeAcc s.toByteArray.data.toList tail + encodeVarNat r.count r.bytes + +def encodeNameAcc : Ix.Name → ByteList → ByteList + | .anonymous _, tail => .cons 20 tail + | .str p s _, tail => .cons 21 (encodeNameAcc p (encodeStringAcc s tail)) + | .num p n _, tail => .cons 22 (encodeNameAcc p (encodeVarNat n tail)) + +def encodeNamesListAcc : List Ix.Name → ByteList → ByteList + | [], tail => tail + | n :: ns, tail => encodeNameAcc n (encodeNamesListAcc ns tail) + +def encodeNamesAcc (ns : Array Ix.Name) (tail : ByteList) : ByteList := + let xs := ns.toList + encodeVarNat xs.length (encodeNamesListAcc xs tail) + +/-! ## Section 6: Canonical `Stx` Serializer (`syntaxAddr`) -/ + +def encodeSyntaxAcc : Stx → ByteList → ByteList + | .missing, tail => .cons 0 tail + | .atom _ val, tail => .cons 1 (encodeSymAcc val tail) + | .ident _ _ val, tail => .cons 2 (encodeFNameAcc val tail) + | .node _ kind args, tail => + .cons 3 (encodeFNameAcc kind (encodeVarNat args.size (encodeSyntaxAcc args tail))) + | .snil, tail => tail + | .scons h t, tail => encodeSyntaxAcc h (encodeSyntaxAcc t tail) + +def hashSyntaxWords (stx : Stx) : DigestWords := + blake3HashWords (encodeSyntaxAcc stx .nil) + +/-! ## Section 6b: Canonical `Stx` Decoder (`verifyElabStx` compositional entrypoint) -/ + +/-- Distinct field order (`val, ok, rest`) from `ParseU8`/`ParseU32` (`ok, val, rest`) + so Ixon assigns it a distinct content address and `decodeVarNatFuel`'s recursive + `mult * 128` `BigNat` upgrade never propagates into `ParseU32` / `DigestWords`. -/ +structure ParseNatRes where + val : Nat + ok : Bool + rest : ByteList + +def decodeVarNatFuel : Nat → Nat → Nat → ByteList → ParseNatRes + | 0, _, _, s => { ok := false, val := 0, rest := s } + | k + 1, acc, mult, .cons b rest => + if Nat.blt b 128 then + { ok := true, val := Nat.add acc (Nat.mul b mult), rest } + else + let lo := Nat.sub b 128 + decodeVarNatFuel k (Nat.add acc (Nat.mul lo mult)) (Nat.mul mult 128) rest + | _ + 1, _, _, .nil => { ok := false, val := 0, rest := .nil } + +structure ParseSymRes where + ok : Bool + val : Sym + rest : ByteList + +def decodeSymCharsRev : Nat → ByteList → Sym → ParseSymRes + | 0, s, revAcc => { ok := true, val := Sym.reverse revAcc, rest := s } + | n + 1, .cons b0 rest0, revAcc => + if Nat.blt b0 128 then + decodeSymCharsRev n rest0 (.cons b0 revAcc) + else if Nat.blt b0 224 then + match rest0 with + | .cons b1 rest1 => decodeSymCharsRev n rest1 (.cons b1 (.cons b0 revAcc)) + | .nil => { ok := false, val := .nil, rest := .nil } + else if Nat.blt b0 240 then + match rest0 with + | .cons b1 (.cons b2 rest2) => + decodeSymCharsRev n rest2 (.cons b2 (.cons b1 (.cons b0 revAcc))) + | _ => { ok := false, val := .nil, rest := .nil } + else + match rest0 with + | .cons b1 (.cons b2 (.cons b3 rest3)) => + decodeSymCharsRev n rest3 (.cons b3 (.cons b2 (.cons b1 (.cons b0 revAcc)))) + | _ => { ok := false, val := .nil, rest := .nil } + | _ + 1, .nil, _ => { ok := false, val := .nil, rest := .nil } + +def decodeSym (s : ByteList) : ParseSymRes := + let lenRes := decodeVarNatFuel 16 0 1 s + if !lenRes.ok then { ok := false, val := .nil, rest := lenRes.rest } + else decodeSymCharsRev lenRes.val lenRes.rest .nil + +structure ParseFNameRes where + ok : Bool + val : FName + rest : ByteList + +def decodeFNameFuel : Nat → ByteList → ParseFNameRes + | 0, s => { ok := false, val := .anon, rest := s } + | k + 1, .cons tag rest => + if Nat.beq tag 20 then + { ok := true, val := .anon, rest } + else if Nat.beq tag 21 then + let pRes := decodeFNameFuel k rest + if !pRes.ok then { ok := false, val := .anon, rest := pRes.rest } + else + let sRes := decodeSym pRes.rest + if !sRes.ok then { ok := false, val := .anon, rest := sRes.rest } + else { ok := true, val := .str pRes.val sRes.val, rest := sRes.rest } + else if Nat.beq tag 22 then + let pRes := decodeFNameFuel k rest + if !pRes.ok then { ok := false, val := .anon, rest := pRes.rest } + else + let nRes := decodeVarNatFuel 16 0 1 pRes.rest + if !nRes.ok then { ok := false, val := .anon, rest := nRes.rest } + else { ok := true, val := .num pRes.val nRes.val, rest := nRes.rest } + else + { ok := false, val := .anon, rest } + | _ + 1, .nil => { ok := false, val := .anon, rest := .nil } + +structure ParseStxRes where + ok : Bool + val : Stx + rest : ByteList + +mutual +def decodeSyntaxFuel : Nat → ByteList → ParseStxRes + | 0, s => { ok := false, val := .missing, rest := s } + | k + 1, .cons tag rest => + if Nat.beq tag 0 then + { ok := true, val := .missing, rest } + else if Nat.beq tag 1 then + let sRes := decodeSym rest + if !sRes.ok then { ok := false, val := .missing, rest := sRes.rest } + else { ok := true, val := .atom .none sRes.val, rest := sRes.rest } + else if Nat.beq tag 2 then + let nRes := decodeFNameFuel 64 rest + if !nRes.ok then { ok := false, val := .missing, rest := nRes.rest } + else { ok := true, val := .ident .none .nil nRes.val, rest := nRes.rest } + else if Nat.beq tag 3 then + let kRes := decodeFNameFuel 64 rest + if !kRes.ok then { ok := false, val := .missing, rest := kRes.rest } + else + let nRes := decodeVarNatFuel 16 0 1 kRes.rest + if !nRes.ok then { ok := false, val := .missing, rest := nRes.rest } + else + let aRes := decodeSyntaxListFuel k nRes.val nRes.rest + if !aRes.ok then { ok := false, val := .missing, rest := aRes.rest } + else { ok := true, val := .node .none kRes.val aRes.val, rest := aRes.rest } + else + { ok := false, val := .missing, rest } + | _ + 1, .nil => { ok := false, val := .missing, rest := .nil } + +def decodeSyntaxListFuel : Nat → Nat → ByteList → ParseStxRes + | _, 0, s => { ok := true, val := .snil, rest := s } + | 0, _ + 1, s => { ok := false, val := .snil, rest := s } + | k + 1, n + 1, s => + let hRes := decodeSyntaxFuel k s + if !hRes.ok then { ok := false, val := .snil, rest := hRes.rest } + else + let tRes := decodeSyntaxListFuel k n hRes.rest + if !tRes.ok then { ok := false, val := .snil, rest := tRes.rest } + else { ok := true, val := .scons hRes.val tRes.val, rest := tRes.rest } +end + +def decodeSyntax (s : ByteList) : Option Stx := + let res := decodeSyntaxFuel 4096 s + if res.ok && isByteListNil res.rest then some res.val else none + +/-! ## Section 7: Lossless Alpha-Canonical `IxElabEnv` Serializer (`outputAddr`) + +Matches `FrontendWire.ofEnv` from `ap/frontend-aiur-benchmark`: commits to every +elaborated constant's full kernel payload (levels, exprs, metadata, binder infos, +flags, recursor rules), omitting only alpha-irrelevant binder names and cached +intermediate hashes, sorted canonically by constant name. -/ + +def encodeLevelAcc : Ix.Level → ByteList → ByteList + | .zero _, tail => .cons 0 tail + | .succ u _, tail => .cons 1 (encodeLevelAcc u tail) + | .max u v _, tail => .cons 2 (encodeLevelAcc u (encodeLevelAcc v tail)) + | .imax u v _, tail => .cons 3 (encodeLevelAcc u (encodeLevelAcc v tail)) + | .param n _, tail => .cons 4 (encodeNameAcc n tail) + | .mvar n _, tail => .cons 5 (encodeNameAcc n tail) + +def encodeLevelsListAcc : List Ix.Level → ByteList → ByteList + | [], tail => tail + | u :: us, tail => encodeLevelAcc u (encodeLevelsListAcc us tail) + +def encodeLevelsAcc (us : Array Ix.Level) (tail : ByteList) : ByteList := + let xs := us.toList + encodeVarNat xs.length (encodeLevelsListAcc xs tail) + +def encodeDataValueAcc : Ix.DataValue → ByteList → ByteList + | .ofString s, tail => .cons 0 (encodeStringAcc s tail) + | .ofBool b, tail => .cons 1 (encodeBool b tail) + | .ofName n, tail => .cons 2 (encodeNameAcc n tail) + | .ofNat n, tail => .cons 3 (encodeVarNat n tail) + | .ofInt i, tail => + match i with + | .ofNat n => .cons 4 (.cons 0 (encodeVarNat n tail)) + | .negSucc n => .cons 4 (.cons 1 (encodeVarNat n tail)) + | .ofSyntax _, tail => .cons 5 tail + +def encodeMDataListAcc : List (Ix.Name × Ix.DataValue) → ByteList → ByteList + | [], tail => tail + | (n, v) :: rest, tail => encodeNameAcc n (encodeDataValueAcc v (encodeMDataListAcc rest tail)) + +def encodeBinderInfoTag (bi : Lean.BinderInfo) : Nat := + match bi with + | .default => 0 + | .implicit => 1 + | .strictImplicit => 2 + | .instImplicit => 3 + +def encodeExprAcc : Ix.Expr → ByteList → ByteList + | .bvar i _, tail => .cons 0 (encodeVarNat i tail) + | .sort u _, tail => .cons 1 (encodeLevelAcc u tail) + | .const n us _, tail => .cons 2 (encodeNameAcc n (encodeLevelsAcc us tail)) + | .app f a _, tail => .cons 3 (encodeExprAcc f (encodeExprAcc a tail)) + | .lam _ a b bi _, tail => + .cons 4 (.cons (encodeBinderInfoTag bi) (encodeExprAcc a (encodeExprAcc b tail))) + | .forallE _ a b bi _, tail => + .cons 5 (.cons (encodeBinderInfoTag bi) (encodeExprAcc a (encodeExprAcc b tail))) + | .letE _ t v b nd _, tail => + .cons 6 (encodeBool nd (encodeExprAcc t (encodeExprAcc v (encodeExprAcc b tail)))) + | .lit (.natVal n) _, tail => .cons 7 (encodeVarNat n tail) + | .lit (.strVal s) _, tail => .cons 8 (encodeStringAcc s tail) + | .mdata d e _, tail => + let xs := d.toList + .cons 9 (encodeVarNat xs.length (encodeMDataListAcc xs (encodeExprAcc e tail))) + | .proj n i e _, tail => .cons 10 (encodeNameAcc n (encodeVarNat i (encodeExprAcc e tail))) + | .fvar n _, tail => .cons 11 (encodeNameAcc n tail) + | .mvar n _, tail => .cons 12 (encodeNameAcc n tail) + +def encodeHintsAcc : Lean.ReducibilityHints → ByteList → ByteList + | .opaque, tail => .cons 0 tail + | .abbrev, tail => .cons 1 tail + | .regular n, tail => .cons 2 (encodeVarNat n.toNat tail) + +def encodeSafetyByte : Lean.DefinitionSafety → Nat + | .safe => 0 + | .unsafe => 1 + | .partial => 2 + +def encodeRulesListAcc : List Ix.RecursorRule → ByteList → ByteList + | [], tail => tail + | r :: rs, tail => + encodeNameAcc r.ctor (encodeVarNat r.nfields (encodeExprAcc r.rhs (encodeRulesListAcc rs tail))) + +def encodeRulesAcc (rs : Array Ix.RecursorRule) (tail : ByteList) : ByteList := + let xs := rs.toList + encodeVarNat xs.length (encodeRulesListAcc xs tail) + +def encodeConstValAcc (c : Ix.ConstantVal) (tail : ByteList) : ByteList := + encodeNameAcc c.name (encodeNamesAcc c.levelParams (encodeExprAcc c.type tail)) + +def encodeConstantAcc (ci : Ix.ConstantInfo) (tail : ByteList) : ByteList := + match ci with + | .axiomInfo v => + .cons 100 (encodeConstValAcc v.cnst (encodeBool v.isUnsafe tail)) + | .defnInfo v => + .cons 101 (encodeConstValAcc v.cnst (encodeExprAcc v.value + (encodeHintsAcc v.hints (.cons (encodeSafetyByte v.safety) (encodeNamesAcc v.all tail))))) + | .thmInfo v => + .cons 102 (encodeConstValAcc v.cnst (encodeExprAcc v.value (encodeNamesAcc v.all tail))) + | .opaqueInfo v => + .cons 103 (encodeConstValAcc v.cnst (encodeExprAcc v.value + (encodeBool v.isUnsafe (encodeNamesAcc v.all tail)))) + | .quotInfo v => + let kTag := match v.kind with | .type => 0 | .ctor => 1 | .lift => 2 | .ind => 3 + .cons 104 (encodeConstValAcc v.cnst (.cons kTag tail)) + | .inductInfo v => + .cons 105 (encodeConstValAcc v.cnst + (encodeVarNat v.numParams (encodeVarNat v.numIndices + (encodeNamesAcc v.all (encodeNamesAcc v.ctors (encodeVarNat v.numNested + (encodeBool v.isRec (encodeBool v.isUnsafe (encodeBool v.isReflexive tail))))))))) + | .ctorInfo v => + .cons 106 (encodeConstValAcc v.cnst + (encodeNameAcc v.induct (encodeVarNat v.cidx (encodeVarNat v.numParams + (encodeVarNat v.numFields (encodeBool v.isUnsafe tail)))))) + | .recInfo v => + .cons 107 (encodeConstValAcc v.cnst + (encodeNamesAcc v.all (encodeVarNat v.numParams (encodeVarNat v.numIndices + (encodeVarNat v.numMotives (encodeVarNat v.numMinors + (encodeRulesAcc v.rules (encodeBool v.k (encodeBool v.isUnsafe tail))))))))) + +def encodeConstListAcc : List Ix.ConstantInfo → ByteList → ByteList + | [], tail => tail + | ci :: rest, tail => encodeConstantAcc ci (encodeConstListAcc rest tail) + +/-- Extract constants from `IxElabEnv.consts` in sorted `NameMap` order (O(N), zero re-sorting!). -/ +def nameMapToListAcc {α : Type} : NameMap α → List (Ix.Name × α) → List (Ix.Name × α) + | .leaf, acc => acc + | .node _ k v l r, acc => nameMapToListAcc l ((k, v) :: nameMapToListAcc r acc) + +def envSortedConsts (env : IxElabEnv) : List Ix.ConstantInfo := + (nameMapToListAcc env.consts []).map (·.2) + +/-- Serialize all elaborated constants in deterministic `NameMap` order into a `ByteList`. -/ +def encodeAlphaEnv (env : IxElabEnv) : ByteList := + let cs := envSortedConsts env + .cons 0x41 (encodeVarNat cs.length (encodeConstListAcc cs .nil)) + +def hashAlphaEnvWords (env : IxElabEnv) : DigestWords := + blake3HashWords (encodeAlphaEnv env) + +/-- Serialize sorted `(Name, blake3(alphaConst))` export table for `exportsAddr`. -/ +def encodeWordLE32 (w : Nat) (tail : ByteList) : ByteList := + .cons (Nat.mod w 256) + (.cons (Nat.mod (Nat.div w 256) 256) + (.cons (Nat.mod (Nat.div w 65536) 256) + (.cons (Nat.mod (Nat.div w 16777216) 256) tail))) + +def encodeDigestWordsAcc (d : DigestWords) (tail : ByteList) : ByteList := + encodeWordLE32 d.w0 (encodeWordLE32 d.w1 (encodeWordLE32 d.w2 (encodeWordLE32 d.w3 + (encodeWordLE32 d.w4 (encodeWordLE32 d.w5 (encodeWordLE32 d.w6 (encodeWordLE32 d.w7 tail))))))) + +def encodeExportsListAcc : List (Ix.Name × Ix.ConstantInfo) → ByteList → ByteList + | [], tail => tail + | (nm, ci) :: rest, tail => + let cDig := blake3HashWords (encodeConstantAcc ci .nil) + encodeNameAcc nm (encodeDigestWordsAcc cDig (encodeExportsListAcc rest tail)) + +def hashExportsWords (env : IxElabEnv) : DigestWords := + let entries := nameMapToListAcc env.consts [] + blake3HashWords (.cons 0x45 (encodeVarNat entries.length (encodeExportsListAcc entries .nil))) + +/-! ## Section 8: Host-Side Helpers (ByteArray ↔ ByteList & Address ↔ DigestWords) -/ + +def byteListOfByteArray (ba : ByteArray) : ByteList := + ba.data.toList.foldr (fun b acc => .cons b.toNat acc) .nil + +def byteListToByteArray (bs : ByteList) : ByteArray := + let rec go : ByteList → List UInt8 → List UInt8 + | .nil, rev => rev.reverse + | .cons b rest, rev => go rest (UInt8.ofNat b :: rev) + ⟨Array.mk (go bs [])⟩ + +def digestWordsOfAddress (a : Address) : DigestWords := + let rd (i : Nat) : Nat := + let b0 := (a.hash.data.getD (4 * i) 0).toNat + let b1 := (a.hash.data.getD (4 * i + 1) 0).toNat + let b2 := (a.hash.data.getD (4 * i + 2) 0).toNat + let b3 := (a.hash.data.getD (4 * i + 3) 0).toNat + b0 + b1 * 256 + b2 * 65536 + b3 * 16777216 + { w0 := rd 0, w1 := rd 1, w2 := rd 2, w3 := rd 3 + w4 := rd 4, w5 := rd 5, w6 := rd 6, w7 := rd 7 } + +def hashByteListHost (bs : ByteList) : Address := + Address.blake3Pure (byteListToByteArray bs) + +def hashSyntaxHost (stx : Stx) : Address := + hashByteListHost (encodeSyntaxAcc stx .nil) + +def hashAlphaEnvHost (env : IxElabEnv) : Address := + hashByteListHost (encodeAlphaEnv env) + +end Ix.Frontend.Circuit.Wire + +end diff --git a/Ix/Frontend/Elab/Command.lean b/Ix/Frontend/Elab/Command.lean new file mode 100644 index 0000000000..c140b5467e --- /dev/null +++ b/Ix/Frontend/Elab/Command.lean @@ -0,0 +1,3117 @@ +/- + Ix.Frontend.Elab.Command: Top-Level Command & SCC Elaborator for the Ix Frontend. + + Orchestrates: + - Optional core prelude seeding (`Bool`, `Nat`, `Unit`, `PUnit`, `Eq`, `Prod`, `Option`, `List`, `String`) + for types not redefined in the module itself. + - Elaboration of scheduled Strongly Connected Components (`ScheduledSCC`) in Tarjan + topological order (callees before callers): + 1. Inductive / Structure / Class SCCs (`elabInductiveSCC`), followed immediately by + in-elaborator constructor & block canonicalization (`Ix.Frontend.CanonBlock`) and + surgery-free auxiliary generation (`Ix.Frontend.AuxGen`). + 2. Value declaration SCCs (`def`, `abbrev`, `theorem`, `opaque`, `axiom`, `instance`), + with automatic structural-recursion lowering to `.recOn` for `ι`-reducible + definitions and post-elaboration minimal SCC splitting & canonicalization. +-/ +module + +public import Ix.Frontend.Elab.Term + +@[expose] public section + +namespace Ix.Frontend.Elab + +open Ix.Frontend +open Ix.Frontend.Parser +open Ix.Frontend.Canon +open Ix.Frontend.AuxGen + +/-! ## Core Prelude Seeding (for Standalone `.ix` Modules) -/ + +/-- Default address resolver for in-elaborator canonicalization: + uses `importMap.lookupName?` if pinned, otherwise the constant/name's content hash. -/ +def defaultAddrOf (env : IxElabEnv) (nm : Ix.Name) : Address := + match env.importMap.lookupName? nm with + | some addr => addr + | none => Name.computeHash nm + +def addDefnsToEnv : IxElabEnv → List Ix.DefinitionVal → IxElabEnv + | env, [] => env + | env, p :: rest => addDefnsToEnv (env.addConst (.defnInfo p)) rest + +def addAxiomsIfMissing (modIdx : ModuleIndex) : IxElabEnv → List (Ix.Name × Ix.Expr) → IxElabEnv + | env, [] => env + | env, (pName, pType) :: rest => + let env' := + if !env.contains pName && !modIdx.declByName.contains pName then + env.addConst (.axiomInfo { cnst := { name := pName, levelParams := #[], type := pType }, isUnsafe := false }) + else env + addAxiomsIfMissing modIdx env' rest + +def addDecInstAxiomsIfMissing (modIdx : ModuleIndex) (decName : Ix.Name) : + IxElabEnv → List (Ix.Name × Ix.Expr) → IxElabEnv + | env, [] => env + | env, (instNm, instTy) :: rest => + let env' := + if !env.contains instNm && !modIdx.declByName.contains instNm then + let env := env.addConst (.axiomInfo { cnst := { name := instNm, levelParams := #[], type := instTy }, isUnsafe := false }) + env.addInstance { instName := instNm, className := decName } + else env + addDecInstAxiomsIfMissing modIdx decName env' rest + +/-- Part 1a of core prelude: `Bool`, `Nat`. -/ +def seedCoreBoolNat (env : IxElabEnv) (modIdx : ModuleIndex) : IxElabEnv := + let type0 := Expr.mkSort (Level.mkSucc Level.mkZero) + let boolName := Name.simple (str% "Bool") + let env := + if !env.contains boolName && !modIdx.declByName.contains boolName then + let falseName := Name.mkStr2 (str% "Bool") (str% "false") + let trueName := Name.mkStr2 (str% "Bool") (str% "true") + let boolConst := Expr.mkConst boolName #[] + let iv : Ix.InductiveVal := { + cnst := { name := boolName, levelParams := #[], type := type0 } + numParams := 0, numIndices := 0, all := #[boolName] + ctors := #[falseName, trueName], numNested := 0 + isRec := false, isUnsafe := false, isReflexive := false + } + let cFalse : Ix.ConstructorVal := { + cnst := { name := falseName, levelParams := #[], type := boolConst } + induct := boolName, cidx := 0, numParams := 0, numFields := 0, isUnsafe := false + } + let cTrue : Ix.ConstructorVal := { + cnst := { name := trueName, levelParams := #[], type := boolConst } + induct := boolName, cidx := 1, numParams := 0, numFields := 0, isUnsafe := false + } + registerCanonicalInductiveBlock env #[(iv, #[cFalse, cTrue])] + else env + let natName := Name.simple (str% "Nat") + if !env.contains natName && !modIdx.declByName.contains natName then + let zeroName := Name.mkStr2 (str% "Nat") (str% "zero") + let succName := Name.mkStr2 (str% "Nat") (str% "succ") + let natConst := Expr.mkConst natName #[] + let iv : Ix.InductiveVal := { + cnst := { name := natName, levelParams := #[], type := type0 } + numParams := 0, numIndices := 0, all := #[natName] + ctors := #[zeroName, succName], numNested := 0 + isRec := true, isUnsafe := false, isReflexive := false + } + let cZero : Ix.ConstructorVal := { + cnst := { name := zeroName, levelParams := #[], type := natConst } + induct := natName, cidx := 0, numParams := 0, numFields := 0, isUnsafe := false + } + let cSucc : Ix.ConstructorVal := { + cnst := { name := succName, levelParams := #[], type := Expr.mkForallE (Name.simple (str% "n")) natConst natConst .default } + induct := natName, cidx := 1, numParams := 0, numFields := 1, isUnsafe := false + } + registerCanonicalInductiveBlock env #[(iv, #[cZero, cSucc])] + else env + +/-- Part 1b of core prelude: `PUnit`, `Unit`. -/ +def seedCorePUnitUnit (env : IxElabEnv) (modIdx : ModuleIndex) : IxElabEnv := + let uName := Name.simple (str% "u") + let uLvl := Level.mkParam uName + let type0 := Expr.mkSort (Level.mkSucc Level.mkZero) + let sortU := Expr.mkSort uLvl + let punitName := Name.simple (str% "PUnit") + let env := + if !env.contains punitName && !modIdx.declByName.contains punitName then + let unitCtorName := Name.mkStr2 (str% "PUnit") (str% "unit") + let punitConst := Expr.mkConst punitName #[uLvl] + let iv : Ix.InductiveVal := { + cnst := { name := punitName, levelParams := #[uName], type := sortU } + numParams := 0, numIndices := 0, all := #[punitName] + ctors := #[unitCtorName], numNested := 0 + isRec := false, isUnsafe := false, isReflexive := false + } + let cUnit : Ix.ConstructorVal := { + cnst := { name := unitCtorName, levelParams := #[uName], type := punitConst } + induct := punitName, cidx := 0, numParams := 0, numFields := 0, isUnsafe := false + } + registerCanonicalInductiveBlock env #[(iv, #[cUnit])] + else env + let unitName := Name.simple (str% "Unit") + if !env.contains unitName && !modIdx.declByName.contains unitName then + let uCtor := Name.mkStr2 (str% "Unit") (str% "unit") + let unitConst := Expr.mkConst unitName #[] + let iv : Ix.InductiveVal := { + cnst := { name := unitName, levelParams := #[], type := type0 } + numParams := 0, numIndices := 0, all := #[unitName] + ctors := #[uCtor], numNested := 0 + isRec := false, isUnsafe := false, isReflexive := false + } + let cU : Ix.ConstructorVal := { + cnst := { name := uCtor, levelParams := #[], type := unitConst } + induct := unitName, cidx := 0, numParams := 0, numFields := 0, isUnsafe := false + } + registerCanonicalInductiveBlock env #[(iv, #[cU])] + else env + +/-- Part 1c of core prelude: `Eq`. -/ +def seedCoreEq (env : IxElabEnv) (modIdx : ModuleIndex) : IxElabEnv := + let uName := Name.simple (str% "u") + let uLvl := Level.mkParam uName + let sortU := Expr.mkSort uLvl + let eqName := Name.simple (str% "Eq") + if !env.contains eqName && !modIdx.declByName.contains eqName then + let reflName := Name.mkStr2 (str% "Eq") (str% "refl") + let eqType := + Expr.mkForallE (Name.simple (str% "α")) sortU + (Expr.mkForallE (Name.simple (str% "a")) (Expr.mkBVar 0) + (Expr.mkForallE (Name.simple (str% "b")) (Expr.mkBVar 1) Expr.mkProp .default) .default) + .implicit + let reflRet := + Expr.mkAppN (Expr.mkConst eqName #[uLvl]) #[Expr.mkBVar 1, Expr.mkBVar 0, Expr.mkBVar 0] + let reflType := + Expr.mkForallE (Name.simple (str% "α")) sortU + (Expr.mkForallE (Name.simple (str% "a")) (Expr.mkBVar 0) reflRet .default) + .implicit + let iv : Ix.InductiveVal := { + cnst := { name := eqName, levelParams := #[uName], type := eqType } + numParams := 2, numIndices := 1, all := #[eqName] + ctors := #[reflName], numNested := 0 + isRec := false, isUnsafe := false, isReflexive := false + } + let cRefl : Ix.ConstructorVal := { + cnst := { name := reflName, levelParams := #[uName], type := reflType } + induct := eqName, cidx := 0, numParams := 2, numFields := 0, isUnsafe := false + } + registerCanonicalInductiveBlock env #[(iv, #[cRefl])] + else env + +/-- Part 1 of core prelude: `Bool`, `Nat`, `PUnit`, `Unit`, `Eq`. -/ +def seedCoreBasic (env : IxElabEnv) (modIdx : ModuleIndex) : IxElabEnv := + seedCoreEq (seedCorePUnitUnit (seedCoreBoolNat env modIdx) modIdx) modIdx + +/-- Part 2a of core prelude: `True`, `False`, `Not`, `Ne`. -/ +def seedCoreTrueFalseNotNe (env : IxElabEnv) (modIdx : ModuleIndex) : IxElabEnv := Id.run do + let mut env := env + let uName := Name.simple (str% "u") + let uLvl := Level.mkParam uName + let sortU := Expr.mkSort uLvl + let eqName := Name.simple (str% "Eq") + let prop := Expr.mkProp + let truePropName := Name.simple (str% "True") + if !env.contains truePropName && !modIdx.declByName.contains truePropName then + let introName := Name.mkStr2 (str% "True") (str% "intro") + let iv : Ix.InductiveVal := { + cnst := { name := truePropName, levelParams := #[], type := prop } + numParams := 0, numIndices := 0, all := #[truePropName] + ctors := #[introName], numNested := 0 + isRec := false, isUnsafe := false, isReflexive := false + } + let cIntro : Ix.ConstructorVal := { + cnst := { name := introName, levelParams := #[], type := Expr.mkConst truePropName #[] } + induct := truePropName, cidx := 0, numParams := 0, numFields := 0, isUnsafe := false + } + env := registerCanonicalInductiveBlock env #[(iv, #[cIntro])] + + let falsePropName := Name.simple (str% "False") + if !env.contains falsePropName && !modIdx.declByName.contains falsePropName then + let iv : Ix.InductiveVal := { + cnst := { name := falsePropName, levelParams := #[], type := prop } + numParams := 0, numIndices := 0, all := #[falsePropName] + ctors := #[], numNested := 0 + isRec := false, isUnsafe := false, isReflexive := false + } + env := registerCanonicalInductiveBlock env #[(iv, #[])] + + let notName := Name.simple (str% "Not") + if !env.contains notName && !modIdx.declByName.contains notName then + env := env.addConst (.defnInfo { + cnst := { + name := notName, levelParams := #[] + type := Expr.mkForallE (Name.simple (str% "a")) prop prop .default + } + value := Expr.mkLam (Name.simple (str% "a")) prop + (Expr.mkForallE Name.mkAnon (Expr.mkBVar 0) (Expr.mkConst falsePropName #[]) .default) .default + hints := .abbrev, safety := .safe, all := #[notName] + }) + + let neName := Name.simple (str% "Ne") + if !env.contains neName && !modIdx.declByName.contains neName then + let neType := + Expr.mkForallE (Name.simple (str% "α")) sortU + (Expr.mkForallE (Name.simple (str% "a")) (Expr.mkBVar 0) + (Expr.mkForallE (Name.simple (str% "b")) (Expr.mkBVar 1) prop .default) .default) + .implicit + let neVal := + Expr.mkLam (Name.simple (str% "α")) sortU + (Expr.mkLam (Name.simple (str% "a")) (Expr.mkBVar 0) + (Expr.mkLam (Name.simple (str% "b")) (Expr.mkBVar 1) + (Expr.mkApp (Expr.mkConst notName #[]) + (Expr.mkAppN (Expr.mkConst eqName #[uLvl]) #[Expr.mkBVar 2, Expr.mkBVar 1, Expr.mkBVar 0])) + .default) .default) .implicit + env := env.addConst (.defnInfo { + cnst := { name := neName, levelParams := #[uName], type := neType } + value := neVal, hints := .abbrev, safety := .safe, all := #[neName] + }) + return env + +/-- Part 2b of core prelude: `And`, `Or`. -/ +def seedCoreAndOr (env : IxElabEnv) (modIdx : ModuleIndex) : IxElabEnv := Id.run do + let mut env := env + let prop := Expr.mkProp + let andName := Name.simple (str% "And") + if !env.contains andName && !modIdx.declByName.contains andName then + let andIntro := Name.mkStr2 (str% "And") (str% "intro") + let andLeft := Name.mkStr2 (str% "And") (str% "left") + let andRight := Name.mkStr2 (str% "And") (str% "right") + let andType := Expr.mkForallE (Name.simple (str% "a")) prop (Expr.mkForallE (Name.simple (str% "b")) prop prop .default) .default + let andApp := Expr.mkAppN (Expr.mkConst andName #[]) #[Expr.mkBVar 3, Expr.mkBVar 2] + let andIntroTy := + Expr.mkForallE (Name.simple (str% "a")) prop + (Expr.mkForallE (Name.simple (str% "b")) prop + (Expr.mkForallE (Name.simple (str% "left")) (Expr.mkBVar 1) + (Expr.mkForallE (Name.simple (str% "right")) (Expr.mkBVar 1) andApp .default) .default) + .implicit) .implicit + let iv : Ix.InductiveVal := { + cnst := { name := andName, levelParams := #[], type := andType } + numParams := 2, numIndices := 0, all := #[andName] + ctors := #[andIntro], numNested := 0 + isRec := false, isUnsafe := false, isReflexive := false + } + let cIntro : Ix.ConstructorVal := { + cnst := { name := andIntro, levelParams := #[], type := andIntroTy } + induct := andName, cidx := 0, numParams := 2, numFields := 2, isUnsafe := false + } + env := registerCanonicalInductiveBlock env #[(iv, #[cIntro])] + env := addDefnsToEnv env (generateStructProjections iv cIntro #[andLeft, andRight] true).toList + env := env.addStructInfo { + structName := andName, ctorName := andIntro, numParams := 2 + fields := #[ + { fieldName := Name.simple (str% "left"), projFnName := andLeft, fieldIdx := 0 }, + { fieldName := Name.simple (str% "right"), projFnName := andRight, fieldIdx := 1 } + ] + } + + let orName := Name.simple (str% "Or") + if !env.contains orName && !modIdx.declByName.contains orName then + let orInl := Name.mkStr2 (str% "Or") (str% "inl") + let orInr := Name.mkStr2 (str% "Or") (str% "inr") + let orType := Expr.mkForallE (Name.simple (str% "a")) prop (Expr.mkForallE (Name.simple (str% "b")) prop prop .default) .default + let orApp := Expr.mkAppN (Expr.mkConst orName #[]) #[Expr.mkBVar 2, Expr.mkBVar 1] + let inlTy := + Expr.mkForallE (Name.simple (str% "a")) prop + (Expr.mkForallE (Name.simple (str% "b")) prop + (Expr.mkForallE (Name.simple (str% "h")) (Expr.mkBVar 1) orApp .default) .implicit) .implicit + let inrTy := + Expr.mkForallE (Name.simple (str% "a")) prop + (Expr.mkForallE (Name.simple (str% "b")) prop + (Expr.mkForallE (Name.simple (str% "h")) (Expr.mkBVar 0) orApp .default) .implicit) .implicit + let iv : Ix.InductiveVal := { + cnst := { name := orName, levelParams := #[], type := orType } + numParams := 2, numIndices := 0, all := #[orName] + ctors := #[orInl, orInr], numNested := 0 + isRec := false, isUnsafe := false, isReflexive := false + } + let cInl : Ix.ConstructorVal := { + cnst := { name := orInl, levelParams := #[], type := inlTy } + induct := orName, cidx := 0, numParams := 2, numFields := 1, isUnsafe := false + } + let cInr : Ix.ConstructorVal := { + cnst := { name := orInr, levelParams := #[], type := inrTy } + induct := orName, cidx := 1, numParams := 2, numFields := 1, isUnsafe := false + } + env := registerCanonicalInductiveBlock env #[(iv, #[cInl, cInr])] + return env + +/-- Part 2c of core prelude: `Iff`, `Exists`. -/ +def seedCoreIffExists (env : IxElabEnv) (modIdx : ModuleIndex) : IxElabEnv := Id.run do + let mut env := env + let uName := Name.simple (str% "u") + let uLvl := Level.mkParam uName + let sortU := Expr.mkSort uLvl + let prop := Expr.mkProp + let iffName := Name.simple (str% "Iff") + if !env.contains iffName && !modIdx.declByName.contains iffName then + let iffIntro := Name.mkStr2 (str% "Iff") (str% "intro") + let iffMp := Name.mkStr2 (str% "Iff") (str% "mp") + let iffMpr := Name.mkStr2 (str% "Iff") (str% "mpr") + let iffType := Expr.mkForallE (Name.simple (str% "a")) prop (Expr.mkForallE (Name.simple (str% "b")) prop prop .default) .default + let iffApp := Expr.mkAppN (Expr.mkConst iffName #[]) #[Expr.mkBVar 3, Expr.mkBVar 2] + let mpDom := Expr.mkForallE Name.mkAnon (Expr.mkBVar 1) (Expr.mkBVar 1) .default + let mprDom := Expr.mkForallE Name.mkAnon (Expr.mkBVar 1) (Expr.mkBVar 3) .default + let iffIntroTy := + Expr.mkForallE (Name.simple (str% "a")) prop + (Expr.mkForallE (Name.simple (str% "b")) prop + (Expr.mkForallE (Name.simple (str% "mp")) mpDom + (Expr.mkForallE (Name.simple (str% "mpr")) mprDom iffApp .default) .default) + .implicit) .implicit + let iv : Ix.InductiveVal := { + cnst := { name := iffName, levelParams := #[], type := iffType } + numParams := 2, numIndices := 0, all := #[iffName] + ctors := #[iffIntro], numNested := 0 + isRec := false, isUnsafe := false, isReflexive := false + } + let cIntro : Ix.ConstructorVal := { + cnst := { name := iffIntro, levelParams := #[], type := iffIntroTy } + induct := iffName, cidx := 0, numParams := 2, numFields := 2, isUnsafe := false + } + env := registerCanonicalInductiveBlock env #[(iv, #[cIntro])] + env := addDefnsToEnv env (generateStructProjections iv cIntro #[iffMp, iffMpr] true).toList + env := env.addStructInfo { + structName := iffName, ctorName := iffIntro, numParams := 2 + fields := #[ + { fieldName := Name.simple (str% "mp"), projFnName := iffMp, fieldIdx := 0 }, + { fieldName := Name.simple (str% "mpr"), projFnName := iffMpr, fieldIdx := 1 } + ] + } + + let existsName := Name.simple (str% "Exists") + if !env.contains existsName && !modIdx.declByName.contains existsName then + let exIntro := Name.mkStr2 (str% "Exists") (str% "intro") + let predDom := Expr.mkForallE Name.mkAnon (Expr.mkBVar 0) prop .default + let exType := + Expr.mkForallE (Name.simple (str% "α")) sortU + (Expr.mkForallE (Name.simple (str% "p")) predDom prop .default) .implicit + let exApp := Expr.mkAppN (Expr.mkConst existsName #[uLvl]) #[Expr.mkBVar 3, Expr.mkBVar 2] + let exIntroTy := + Expr.mkForallE (Name.simple (str% "α")) sortU + (Expr.mkForallE (Name.simple (str% "p")) predDom + (Expr.mkForallE (Name.simple (str% "w")) (Expr.mkBVar 1) + (Expr.mkForallE (Name.simple (str% "h")) (Expr.mkApp (Expr.mkBVar 1) (Expr.mkBVar 0)) exApp .default) .default) + .implicit) .implicit + let iv : Ix.InductiveVal := { + cnst := { name := existsName, levelParams := #[uName], type := exType } + numParams := 2, numIndices := 0, all := #[existsName] + ctors := #[exIntro], numNested := 0 + isRec := false, isUnsafe := false, isReflexive := false + } + let cIntro : Ix.ConstructorVal := { + cnst := { name := exIntro, levelParams := #[uName], type := exIntroTy } + induct := existsName, cidx := 0, numParams := 2, numFields := 2, isUnsafe := false + } + env := registerCanonicalInductiveBlock env #[(iv, #[cIntro])] + return env + +/-- Part 2 of core prelude: `True`, `False`, `Not`, `Ne`, `And`, `Or`, `Iff`, `Exists`. -/ +def seedCoreLogic (env : IxElabEnv) (modIdx : ModuleIndex) : IxElabEnv := + seedCoreIffExists (seedCoreAndOr (seedCoreTrueFalseNotNe env modIdx) modIdx) modIdx + +/-- Part 3a of core prelude: `Prod`. -/ +def seedCoreProd (env : IxElabEnv) (modIdx : ModuleIndex) : IxElabEnv := + let uName := Name.simple (str% "u") + let vName := Name.simple (str% "v") + let uLvl := Level.mkParam uName + let vLvl := Level.mkParam vName + let typeU := Expr.mkSort (Level.mkSucc uLvl) + let prodName := Name.simple (str% "Prod") + if !env.contains prodName && !modIdx.declByName.contains prodName then + let mkName := Name.mkStr2 (str% "Prod") (str% "mk") + let fstName := Name.mkStr2 (str% "Prod") (str% "fst") + let sndName := Name.mkStr2 (str% "Prod") (str% "snd") + let typeV := Expr.mkSort (Level.mkSucc vLvl) + let typeMaxUV := Expr.mkSort (Level.mkSucc (Level.mkMax uLvl vLvl)) + let prodType := + Expr.mkForallE (Name.simple (str% "α")) typeU + (Expr.mkForallE (Name.simple (str% "β")) typeV typeMaxUV .default) .default + let prodApp := Expr.mkAppN (Expr.mkConst prodName #[uLvl, vLvl]) #[Expr.mkBVar 3, Expr.mkBVar 2] + let mkType := + Expr.mkForallE (Name.simple (str% "α")) typeU + (Expr.mkForallE (Name.simple (str% "β")) typeV + (Expr.mkForallE (Name.simple (str% "fst")) (Expr.mkBVar 1) + (Expr.mkForallE (Name.simple (str% "snd")) (Expr.mkBVar 1) prodApp .default) .default) + .implicit) .implicit + let iv : Ix.InductiveVal := { + cnst := { name := prodName, levelParams := #[uName, vName], type := prodType } + numParams := 2, numIndices := 0, all := #[prodName] + ctors := #[mkName], numNested := 0 + isRec := false, isUnsafe := false, isReflexive := false + } + let cMk : Ix.ConstructorVal := { + cnst := { name := mkName, levelParams := #[uName, vName], type := mkType } + induct := prodName, cidx := 0, numParams := 2, numFields := 2, isUnsafe := false + } + let env := registerCanonicalInductiveBlock env #[(iv, #[cMk])] + let projs := generateStructProjections iv cMk #[fstName, sndName] false + let env := addDefnsToEnv env projs.toList + env.addStructInfo { + structName := prodName + ctorName := mkName + numParams := 2 + fields := #[ + { fieldName := Name.simple (str% "fst"), projFnName := fstName, fieldIdx := 0 }, + { fieldName := Name.simple (str% "snd"), projFnName := sndName, fieldIdx := 1 } + ] + } + else env + +/-- Part 3b of core prelude: `List`. -/ +def seedCoreList (env : IxElabEnv) (modIdx : ModuleIndex) : IxElabEnv := + let uName := Name.simple (str% "u") + let uLvl := Level.mkParam uName + let typeU := Expr.mkSort (Level.mkSucc uLvl) + let listName := Name.simple (str% "List") + if !env.contains listName && !modIdx.declByName.contains listName then + let nilName := Name.mkStr2 (str% "List") (str% "nil") + let consName := Name.mkStr2 (str% "List") (str% "cons") + let listType := Expr.mkForallE (Name.simple (str% "α")) typeU typeU .default + let listApp0 := Expr.mkApp (Expr.mkConst listName #[uLvl]) (Expr.mkBVar 0) + let listApp1 := Expr.mkApp (Expr.mkConst listName #[uLvl]) (Expr.mkBVar 1) + let listApp2 := Expr.mkApp (Expr.mkConst listName #[uLvl]) (Expr.mkBVar 2) + let nilType := Expr.mkForallE (Name.simple (str% "α")) typeU listApp0 .implicit + let consType := + Expr.mkForallE (Name.simple (str% "α")) typeU + (Expr.mkForallE (Name.simple (str% "head")) (Expr.mkBVar 0) + (Expr.mkForallE (Name.simple (str% "tail")) listApp1 listApp2 .default) .default) + .implicit + let iv : Ix.InductiveVal := { + cnst := { name := listName, levelParams := #[uName], type := listType } + numParams := 1, numIndices := 0, all := #[listName] + ctors := #[nilName, consName], numNested := 0 + isRec := true, isUnsafe := false, isReflexive := false + } + let cNil : Ix.ConstructorVal := { + cnst := { name := nilName, levelParams := #[uName], type := nilType } + induct := listName, cidx := 0, numParams := 1, numFields := 0, isUnsafe := false + } + let cCons : Ix.ConstructorVal := { + cnst := { name := consName, levelParams := #[uName], type := consType } + induct := listName, cidx := 1, numParams := 1, numFields := 2, isUnsafe := false + } + registerCanonicalInductiveBlock env #[(iv, #[cNil, cCons])] + else env + +/-- Part 3c of core prelude: `Char` and `String`. -/ +def seedCoreString (env : IxElabEnv) (modIdx : ModuleIndex) : IxElabEnv := + let type0 := Expr.mkSort (Level.mkSucc Level.mkZero) + let listName := Name.simple (str% "List") + let stringName := Name.simple (str% "String") + if !env.contains stringName && !modIdx.declByName.contains stringName then + let strMkName := Name.mkStr2 (str% "String") (str% "mk") + let charName := Name.simple (str% "Char") + let env := + if !env.contains charName && !modIdx.declByName.contains charName then + env.addConst (.axiomInfo { + cnst := { name := charName, levelParams := #[], type := type0 } + isUnsafe := false + }) + else env + let listChar := Expr.mkApp (Expr.mkConst listName #[Level.mkZero]) (Expr.mkConst charName #[]) + let strConst := Expr.mkConst stringName #[] + let iv : Ix.InductiveVal := { + cnst := { name := stringName, levelParams := #[], type := type0 } + numParams := 0, numIndices := 0, all := #[stringName] + ctors := #[strMkName], numNested := 0 + isRec := false, isUnsafe := false, isReflexive := false + } + let cMk : Ix.ConstructorVal := { + cnst := { + name := strMkName, levelParams := #[] + type := Expr.mkForallE (Name.simple (str% "data")) listChar strConst .default + } + induct := stringName, cidx := 0, numParams := 0, numFields := 1, isUnsafe := false + } + let env := registerCanonicalInductiveBlock env #[(iv, #[cMk])] + let strProjs := generateStructProjections iv cMk #[Name.mkStr2 (str% "String") (str% "toList")] false + let env := addDefnsToEnv env strProjs.toList + let strOfListName := Name.mkStr2 (str% "String") (str% "ofList") + if !env.contains strOfListName && !modIdx.declByName.contains strOfListName then + env.addConst (.defnInfo { + cnst := { + name := strOfListName, levelParams := #[] + type := Expr.mkForallE (Name.simple (str% "data")) listChar strConst .default + } + value := Expr.mkLam (Name.simple (str% "data")) listChar + (Expr.mkApp (Expr.mkConst strMkName #[]) (Expr.mkBVar 0)) .default + hints := .abbrev + safety := .safe + all := #[strOfListName] + }) + else env + else env + +/-- Part 3d of core prelude: core `Nat`/`Char`/`String` primitive axioms. -/ +def seedCorePrimAxioms (env : IxElabEnv) (modIdx : ModuleIndex) : IxElabEnv := + let natConst := Expr.mkConst (Name.simple (str% "Nat")) #[] + let boolConst := Expr.mkConst (Name.simple (str% "Bool")) #[] + let charConst := Expr.mkConst (Name.simple (str% "Char")) #[] + let strConst := Expr.mkConst (Name.simple (str% "String")) #[] + let natToNat := Expr.mkForallE (Name.simple (str% "x")) natConst natConst .default + let natBinTy := Expr.mkForallE (Name.simple (str% "x")) natConst (Expr.mkForallE (Name.simple (str% "y")) natConst natConst .default) .default + let natCmpTy := Expr.mkForallE (Name.simple (str% "x")) natConst (Expr.mkForallE (Name.simple (str% "y")) natConst boolConst .default) .default + let charToNat := Expr.mkForallE (Name.simple (str% "c")) charConst natConst .default + let natToChar := Expr.mkForallE (Name.simple (str% "n")) natConst charConst .default + let strToNat := Expr.mkForallE (Name.simple (str% "s")) strConst natConst .default + let strToBool := Expr.mkForallE (Name.simple (str% "s")) strConst boolConst .default + let strToChar := Expr.mkForallE (Name.simple (str% "s")) strConst charConst .default + let charToStr := Expr.mkForallE (Name.simple (str% "c")) charConst strConst .default + let strBinTy := Expr.mkForallE (Name.simple (str% "s1")) strConst (Expr.mkForallE (Name.simple (str% "s2")) strConst strConst .default) .default + let strPushTy := Expr.mkForallE (Name.simple (str% "s")) strConst (Expr.mkForallE (Name.simple (str% "c")) charConst strConst .default) .default + let primAxioms : List (Ix.Name × Ix.Expr) := [ + (Name.mkStr2 (str% "Nat") (str% "add"), natBinTy), + (Name.mkStr2 (str% "Nat") (str% "sub"), natBinTy), + (Name.mkStr2 (str% "Nat") (str% "mul"), natBinTy), + (Name.mkStr2 (str% "Nat") (str% "div"), natBinTy), + (Name.mkStr2 (str% "Nat") (str% "mod"), natBinTy), + (Name.mkStr2 (str% "Nat") (str% "pow"), natBinTy), + (Name.mkStr2 (str% "Nat") (str% "pred"), natToNat), + (Name.mkStr2 (str% "Nat") (str% "beq"), natCmpTy), + (Name.mkStr2 (str% "Nat") (str% "ble"), natCmpTy), + (Name.mkStr2 (str% "Char") (str% "ofNat"), natToChar), + (Name.mkStr2 (str% "Char") (str% "toNat"), charToNat), + (Name.mkStr2 (str% "Char") (str% "utf8Size"), charToNat), + (Name.mkStr2 (str% "String") (str% "length"), strToNat), + (Name.mkStr2 (str% "String") (str% "utf8ByteSize"), strToNat), + (Name.mkStr2 (str% "String") (str% "isEmpty"), strToBool), + (Name.mkStr2 (str% "String") (str% "append"), strBinTy), + (Name.mkStr2 (str% "String") (str% "push"), strPushTy), + (Name.mkStr2 (str% "String") (str% "singleton"), charToStr), + (Name.mkStr2 (str% "String") (str% "back"), strToChar) + ] + addAxiomsIfMissing modIdx env primAxioms + +/-- Part 3 of core prelude: `Prod`, `List`, `String`, core `Nat`/`Char`/`String` ops. -/ +def seedCoreData (env : IxElabEnv) (modIdx : ModuleIndex) : IxElabEnv := + seedCorePrimAxioms (seedCoreString (seedCoreList (seedCoreProd env modIdx) modIdx) modIdx) modIdx + +/-- Outlined body of `seedCoreClasses` so modules that do not reference + `Inhabited`/`BEq`/`Coe` never activate its wide registration circuits. -/ +def seedCoreClassesBody (env : IxElabEnv) (modIdx : ModuleIndex) : IxElabEnv := Id.run do + let mut env := env + let uName := Name.simple (str% "u") + let vName := Name.simple (str% "v") + let uLvl := Level.mkParam uName + let vLvl := Level.mkParam vName + let typeU := Expr.mkSort (Level.mkSucc uLvl) + let boolName := Name.simple (str% "Bool") + let boolConst := Expr.mkConst boolName #[] + let natName := Name.simple (str% "Nat") + let natConst := Expr.mkConst natName #[] + if true then + -- 10a. `Inhabited.{u} (α : Type u) : Type u`, `Inhabited.mk`, `Inhabited.default`, `default`, `instInhabitedNat`, `instInhabitedBool` + let inhName := Name.simple (str% "Inhabited") + if !env.contains inhName && !modIdx.declByName.contains inhName then + let inhMk := Name.mkStr2 (str% "Inhabited") (str% "mk") + let inhDef := Name.mkStr2 (str% "Inhabited") (str% "default") + let inhTy := Expr.mkForallE (Name.simple (str% "α")) typeU typeU .default + let inhApp0 := Expr.mkApp (Expr.mkConst inhName #[uLvl]) (Expr.mkBVar 0) + let inhApp1 := Expr.mkApp (Expr.mkConst inhName #[uLvl]) (Expr.mkBVar 1) + let inhMkTy := + Expr.mkForallE (Name.simple (str% "α")) typeU + (Expr.mkForallE (Name.simple (str% "default")) (Expr.mkBVar 0) inhApp1 .default) .implicit + let iv : Ix.InductiveVal := { + cnst := { name := inhName, levelParams := #[uName], type := inhTy } + numParams := 1, numIndices := 0, all := #[inhName] + ctors := #[inhMk], numNested := 0 + isRec := false, isUnsafe := false, isReflexive := false + } + let cMk : Ix.ConstructorVal := { + cnst := { name := inhMk, levelParams := #[uName], type := inhMkTy } + induct := inhName, cidx := 0, numParams := 1, numFields := 1, isUnsafe := false + } + env := registerCanonicalInductiveBlock env #[(iv, #[cMk])] + env := addDefnsToEnv env (generateStructProjections iv cMk #[inhDef] true).toList + env := env.addStructInfo { + structName := inhName, ctorName := inhMk, numParams := 1, isClass := true + fields := #[{ fieldName := Name.simple (str% "default"), projFnName := inhDef, fieldIdx := 0 }] + } + let topDefName := Name.simple (str% "default") + if !env.contains topDefName && !modIdx.declByName.contains topDefName then + let topDefTy := + Expr.mkForallE (Name.simple (str% "α")) typeU + (Expr.mkForallE (Name.simple (str% "self")) inhApp0 (Expr.mkBVar 1) .instImplicit) .implicit + let topDefVal := + Expr.mkLam (Name.simple (str% "α")) typeU + (Expr.mkLam (Name.simple (str% "self")) inhApp0 + (Expr.mkProj inhName 0 (Expr.mkBVar 0)) .instImplicit) .implicit + env := env.addConst (.defnInfo { + cnst := { name := topDefName, levelParams := #[uName], type := topDefTy } + value := topDefVal, hints := .abbrev, safety := .safe, all := #[topDefName] + }) + let instInhNat := Name.simple (str% "instInhabitedNat") + if !env.contains instInhNat && !modIdx.declByName.contains instInhNat then + env := env.addConst (.defnInfo { + cnst := { name := instInhNat, levelParams := #[], type := Expr.mkApp (Expr.mkConst inhName #[Level.mkZero]) natConst } + value := Expr.mkAppN (Expr.mkConst inhMk #[Level.mkZero]) #[natConst, Expr.mkConst (Name.mkStr2 (str% "Nat") (str% "zero")) #[]] + hints := .abbrev, safety := .safe, all := #[instInhNat] + }) + env := env.addInstance { instName := instInhNat, className := inhName } + let instInhBool := Name.simple (str% "instInhabitedBool") + if !env.contains instInhBool && !modIdx.declByName.contains instInhBool then + env := env.addConst (.defnInfo { + cnst := { name := instInhBool, levelParams := #[], type := Expr.mkApp (Expr.mkConst inhName #[Level.mkZero]) boolConst } + value := Expr.mkAppN (Expr.mkConst inhMk #[Level.mkZero]) #[boolConst, Expr.mkConst (Name.mkStr2 (str% "Bool") (str% "false")) #[]] + hints := .abbrev, safety := .safe, all := #[instInhBool] + }) + env := env.addInstance { instName := instInhBool, className := inhName } + + -- 10b. `BEq.{u} (α : Type u) : Type u`, `BEq.mk`, `BEq.beq`, `and`, `instBEqNat`, `instBEqBool` + let andBoolName := Name.simple (str% "and") + if !env.contains andBoolName && !modIdx.declByName.contains andBoolName then + let andVal := + Expr.mkLam (Name.simple (str% "x")) boolConst + (Expr.mkLam (Name.simple (str% "y")) boolConst + (Expr.mkAppN (Expr.mkConst (Name.mkStr2 (str% "Bool") (str% "casesOn")) #[Level.mkSucc Level.mkZero]) + #[Expr.mkLam (Name.simple (str% "_")) boolConst boolConst .default, + Expr.mkBVar 1, + Expr.mkConst (Name.mkStr2 (str% "Bool") (str% "false")) #[], + Expr.mkBVar 0]) .default) .default + let boolBinTy := Expr.mkForallE (Name.simple (str% "x")) boolConst (Expr.mkForallE (Name.simple (str% "y")) boolConst boolConst .default) .default + env := env.addConst (.defnInfo { + cnst := { name := andBoolName, levelParams := #[], type := boolBinTy } + value := andVal, hints := .abbrev, safety := .safe, all := #[andBoolName] + }) + let beqClsName := Name.simple (str% "BEq") + if !env.contains beqClsName && !modIdx.declByName.contains beqClsName then + let beqMk := Name.mkStr2 (str% "BEq") (str% "mk") + let beqFn := Name.mkStr2 (str% "BEq") (str% "beq") + let beqClsTy := Expr.mkForallE (Name.simple (str% "α")) typeU typeU .default + let beqFnDom := + Expr.mkForallE Name.mkAnon (Expr.mkBVar 0) + (Expr.mkForallE Name.mkAnon (Expr.mkBVar 1) boolConst .default) .default + let beqApp1 := Expr.mkApp (Expr.mkConst beqClsName #[uLvl]) (Expr.mkBVar 1) + let beqMkTy := + Expr.mkForallE (Name.simple (str% "α")) typeU + (Expr.mkForallE (Name.simple (str% "beq")) beqFnDom beqApp1 .default) .implicit + let iv : Ix.InductiveVal := { + cnst := { name := beqClsName, levelParams := #[uName], type := beqClsTy } + numParams := 1, numIndices := 0, all := #[beqClsName] + ctors := #[beqMk], numNested := 0 + isRec := false, isUnsafe := false, isReflexive := false + } + let cMk : Ix.ConstructorVal := { + cnst := { name := beqMk, levelParams := #[uName], type := beqMkTy } + induct := beqClsName, cidx := 0, numParams := 1, numFields := 1, isUnsafe := false + } + env := registerCanonicalInductiveBlock env #[(iv, #[cMk])] + env := addDefnsToEnv env (generateStructProjections iv cMk #[beqFn] true).toList + env := env.addStructInfo { + structName := beqClsName, ctorName := beqMk, numParams := 1, isClass := true + fields := #[{ fieldName := Name.simple (str% "beq"), projFnName := beqFn, fieldIdx := 0 }] + } + let instBEqNat := Name.simple (str% "instBEqNat") + if !env.contains instBEqNat && !modIdx.declByName.contains instBEqNat then + env := env.addConst (.defnInfo { + cnst := { name := instBEqNat, levelParams := #[], type := Expr.mkApp (Expr.mkConst beqClsName #[Level.mkZero]) natConst } + value := Expr.mkAppN (Expr.mkConst beqMk #[Level.mkZero]) #[natConst, Expr.mkConst (Name.mkStr2 (str% "Nat") (str% "beq")) #[]] + hints := .abbrev, safety := .safe, all := #[instBEqNat] + }) + env := env.addInstance { instName := instBEqNat, className := beqClsName } + let instBEqBool := Name.simple (str% "instBEqBool") + if !env.contains instBEqBool && !modIdx.declByName.contains instBEqBool then + let boolBeqVal := + Expr.mkLam (Name.simple (str% "a")) boolConst + (Expr.mkLam (Name.simple (str% "b")) boolConst + (Expr.mkAppN (Expr.mkConst (Name.mkStr2 (str% "Bool") (str% "casesOn")) #[Level.mkSucc Level.mkZero]) + #[Expr.mkLam (Name.simple (str% "_")) boolConst boolConst .default, + Expr.mkBVar 1, + Expr.mkAppN (Expr.mkConst (Name.mkStr2 (str% "Bool") (str% "casesOn")) #[Level.mkSucc Level.mkZero]) + #[Expr.mkLam (Name.simple (str% "_")) boolConst boolConst .default, + Expr.mkBVar 0, + Expr.mkConst (Name.mkStr2 (str% "Bool") (str% "true")) #[], + Expr.mkConst (Name.mkStr2 (str% "Bool") (str% "false")) #[]], + Expr.mkBVar 0]) .default) .default + env := env.addConst (.defnInfo { + cnst := { name := instBEqBool, levelParams := #[], type := Expr.mkApp (Expr.mkConst beqClsName #[Level.mkZero]) boolConst } + value := Expr.mkAppN (Expr.mkConst beqMk #[Level.mkZero]) #[boolConst, boolBeqVal] + hints := .abbrev, safety := .safe, all := #[instBEqBool] + }) + env := env.addInstance { instName := instBEqBool, className := beqClsName } + + -- 10c. `Coe.{u, v} (α : Type u) (β : Type v) : Type (max u v)`, `Coe.mk`, `Coe.coe` + let coeClsName := Name.simple (str% "Coe") + if !env.contains coeClsName && !modIdx.declByName.contains coeClsName then + let coeMk := Name.mkStr2 (str% "Coe") (str% "mk") + let coeFn := Name.mkStr2 (str% "Coe") (str% "coe") + let typeV := Expr.mkSort (Level.mkSucc vLvl) + let typeMaxUV := Expr.mkSort (Level.mkSucc (Level.mkMax uLvl vLvl)) + let coeClsTy := + Expr.mkForallE (Name.simple (str% "α")) typeU + (Expr.mkForallE (Name.simple (str% "β")) typeV typeMaxUV .default) .default + let coeFnDom := Expr.mkForallE Name.mkAnon (Expr.mkBVar 1) (Expr.mkBVar 1) .default + let coeApp := Expr.mkAppN (Expr.mkConst coeClsName #[uLvl, vLvl]) #[Expr.mkBVar 2, Expr.mkBVar 1] + let coeMkTy := + Expr.mkForallE (Name.simple (str% "α")) typeU + (Expr.mkForallE (Name.simple (str% "β")) typeV + (Expr.mkForallE (Name.simple (str% "coe")) coeFnDom coeApp .default) + .implicit) .implicit + let iv : Ix.InductiveVal := { + cnst := { name := coeClsName, levelParams := #[uName, vName], type := coeClsTy } + numParams := 2, numIndices := 0, all := #[coeClsName] + ctors := #[coeMk], numNested := 0 + isRec := false, isUnsafe := false, isReflexive := false + } + let cMk : Ix.ConstructorVal := { + cnst := { name := coeMk, levelParams := #[uName, vName], type := coeMkTy } + induct := coeClsName, cidx := 0, numParams := 2, numFields := 1, isUnsafe := false + } + env := registerCanonicalInductiveBlock env #[(iv, #[cMk])] + env := addDefnsToEnv env (generateStructProjections iv cMk #[coeFn] true).toList + env := env.addStructInfo { + structName := coeClsName, ctorName := coeMk, numParams := 2, isClass := true + fields := #[{ fieldName := Name.simple (str% "coe"), projFnName := coeFn, fieldIdx := 0 }] + } + return env + +/-- Part 4 of core prelude: on-demand `Inhabited`, `BEq`, `Coe`. -/ +def seedCoreClasses (env : IxElabEnv) (modIdx : ModuleIndex) : IxElabEnv := + let rec stxHasRefOrOp : Nat → Stx → Bool + | 0, _ => false + | _ + 1, .ident _ _ idF => + let c := (Name.components (FName.toIxName idF)).headD (str% "") + c == (str% "Inhabited") || c == (str% "default") || c == (str% "BEq") || c == (str% "DecidableEq") || c == (str% "Coe") + | _, .atom _ v => Sym.beq v (s% "==") || Sym.beq v (s% "!=") || Sym.beq v (s% "&&") + | f + 1, .node _ _ as => as.any (stxHasRefOrOp f) + | _, _ => false + let needsCoreClasses := modIdx.decls.any fun d => stxHasRefOrOp 64 d.stx + if needsCoreClasses then seedCoreClassesBody env modIdx else env + +/-- Part 5a of core prelude: on-demand `LE`, `LT`, `GE`, `GT`. -/ +def seedCoreOrderRel (env : IxElabEnv) (modIdx : ModuleIndex) : IxElabEnv := Id.run do + let mut env := env + let uName := Name.simple (str% "u") + let uLvl := Level.mkParam uName + let typeU := Expr.mkSort (Level.mkSucc uLvl) + let prop := Expr.mkProp + let natConst := Expr.mkConst (Name.simple (str% "Nat")) #[] + let zLvl := Level.mkZero + let leName := Name.simple (str% "LE") + if !env.contains leName && !modIdx.declByName.contains leName then + let leApp0 := Expr.mkApp (Expr.mkConst leName #[uLvl]) (Expr.mkBVar 0) + let leRelTy := + Expr.mkForallE (Name.simple (str% "α")) typeU + (Expr.mkForallE (Name.simple (str% "self")) leApp0 + (Expr.mkForallE (Name.simple (str% "a")) (Expr.mkBVar 1) + (Expr.mkForallE (Name.simple (str% "b")) (Expr.mkBVar 2) prop .default) .default) + .instImplicit) .implicit + env := env.addConst (.axiomInfo { cnst := { name := leName, levelParams := #[uName], type := Expr.mkForallE (Name.simple (str% "α")) typeU typeU .default }, isUnsafe := false }) + env := env.addConst (.axiomInfo { cnst := { name := Name.mkStr2 (str% "LE") (str% "le"), levelParams := #[uName], type := leRelTy }, isUnsafe := false }) + env := env.addConst (.axiomInfo { cnst := { name := Name.mkStr2 (str% "GE") (str% "ge"), levelParams := #[uName], type := leRelTy }, isUnsafe := false }) + let instLENat := Name.simple (str% "instLENat") + env := env.addConst (.axiomInfo { cnst := { name := instLENat, levelParams := #[], type := Expr.mkApp (Expr.mkConst leName #[zLvl]) natConst }, isUnsafe := false }) + env := env.addInstance { instName := instLENat, className := leName } + + let ltName := Name.simple (str% "LT") + if !env.contains ltName && !modIdx.declByName.contains ltName then + let ltApp0 := Expr.mkApp (Expr.mkConst ltName #[uLvl]) (Expr.mkBVar 0) + let ltRelTy := + Expr.mkForallE (Name.simple (str% "α")) typeU + (Expr.mkForallE (Name.simple (str% "self")) ltApp0 + (Expr.mkForallE (Name.simple (str% "a")) (Expr.mkBVar 1) + (Expr.mkForallE (Name.simple (str% "b")) (Expr.mkBVar 2) prop .default) .default) + .instImplicit) .implicit + env := env.addConst (.axiomInfo { cnst := { name := ltName, levelParams := #[uName], type := Expr.mkForallE (Name.simple (str% "α")) typeU typeU .default }, isUnsafe := false }) + env := env.addConst (.axiomInfo { cnst := { name := Name.mkStr2 (str% "LT") (str% "lt"), levelParams := #[uName], type := ltRelTy }, isUnsafe := false }) + env := env.addConst (.axiomInfo { cnst := { name := Name.mkStr2 (str% "GT") (str% "gt"), levelParams := #[uName], type := ltRelTy }, isUnsafe := false }) + let instLTNat := Name.simple (str% "instLTNat") + env := env.addConst (.axiomInfo { cnst := { name := instLTNat, levelParams := #[], type := Expr.mkApp (Expr.mkConst ltName #[zLvl]) natConst }, isUnsafe := false }) + env := env.addInstance { instName := instLTNat, className := ltName } + return env + +/-- Part 5b of core prelude: on-demand `Decidable`, `dite`, `ite`, and decidability instances. -/ +def seedCoreDecidable (env : IxElabEnv) (modIdx : ModuleIndex) : IxElabEnv := Id.run do + let mut env := env + let uName := Name.simple (str% "u") + let uLvl := Level.mkParam uName + let type0 := Expr.mkSort (Level.mkSucc Level.mkZero) + let sortU := Expr.mkSort uLvl + let prop := Expr.mkProp + let natConst := Expr.mkConst (Name.simple (str% "Nat")) #[] + let eqName := Name.simple (str% "Eq") + let notName := Name.simple (str% "Not") + let truePropName := Name.simple (str% "True") + let falsePropName := Name.simple (str% "False") + let decName := Name.simple (str% "Decidable") + let isTrueName := Name.mkStr2 (str% "Decidable") (str% "isTrue") + let isFalseName := Name.mkStr2 (str% "Decidable") (str% "isFalse") + if !env.contains decName && !modIdx.declByName.contains decName then + let decTy := Expr.mkForallE (Name.simple (str% "p")) prop type0 .default + let decApp1 := Expr.mkApp (Expr.mkConst decName #[]) (Expr.mkBVar 1) + let isTrueTy := + Expr.mkForallE (Name.simple (str% "p")) prop + (Expr.mkForallE (Name.simple (str% "h")) (Expr.mkBVar 0) decApp1 .default) .implicit + let isFalseTy := + Expr.mkForallE (Name.simple (str% "p")) prop + (Expr.mkForallE (Name.simple (str% "h")) (Expr.mkApp (Expr.mkConst notName #[]) (Expr.mkBVar 0)) decApp1 .default) .implicit + let ivDec : Ix.InductiveVal := { + cnst := { name := decName, levelParams := #[], type := decTy } + numParams := 1, numIndices := 0, all := #[decName] + ctors := #[isTrueName, isFalseName], numNested := 0 + isRec := false, isUnsafe := false, isReflexive := false + } + let cTrue : Ix.ConstructorVal := { + cnst := { name := isTrueName, levelParams := #[], type := isTrueTy } + induct := decName, cidx := 0, numParams := 1, numFields := 1, isUnsafe := false + } + let cFalse : Ix.ConstructorVal := { + cnst := { name := isFalseName, levelParams := #[], type := isFalseTy } + induct := decName, cidx := 1, numParams := 1, numFields := 1, isUnsafe := false + } + env := registerCanonicalInductiveBlock env #[(ivDec, #[cTrue, cFalse])] + env := { env with classSet := env.classSet.insert decName } + + let diteName := Name.simple (str% "dite") + if !env.contains diteName && !modIdx.declByName.contains diteName then + let decC := Expr.mkApp (Expr.mkConst decName #[]) (Expr.mkBVar 0) + let tDom := Expr.mkForallE Name.mkAnon (Expr.mkBVar 1) (Expr.mkBVar 3) .default + let eDom := Expr.mkForallE Name.mkAnon (Expr.mkApp (Expr.mkConst notName #[]) (Expr.mkBVar 2)) (Expr.mkBVar 4) .default + let diteTy := + Expr.mkForallE (Name.simple (str% "α")) sortU + (Expr.mkForallE (Name.simple (str% "c")) prop + (Expr.mkForallE (Name.simple (str% "h")) decC + (Expr.mkForallE (Name.simple (str% "t")) tDom + (Expr.mkForallE (Name.simple (str% "e")) eDom (Expr.mkBVar 4) .default) .default) + .instImplicit) .default) .implicit + let decOnC := Expr.mkApp (Expr.mkConst decName #[]) (Expr.mkBVar 3) + let motive := Expr.mkLam (Name.simple (str% "_")) decOnC (Expr.mkBVar 5) .default + let casesCall := Expr.mkAppN (Expr.mkConst (Name.mkStr2 (str% "Decidable") (str% "casesOn")) #[uLvl]) + #[Expr.mkBVar 3, motive, Expr.mkBVar 2, Expr.mkBVar 1, Expr.mkBVar 0] + let diteVal := + Expr.mkLam (Name.simple (str% "α")) sortU + (Expr.mkLam (Name.simple (str% "c")) prop + (Expr.mkLam (Name.simple (str% "h")) decC + (Expr.mkLam (Name.simple (str% "t")) tDom + (Expr.mkLam (Name.simple (str% "e")) eDom casesCall .default) .default) + .instImplicit) .default) .implicit + env := env.addConst (.defnInfo { + cnst := { name := diteName, levelParams := #[uName], type := diteTy } + value := diteVal, hints := .abbrev, safety := .safe, all := #[diteName] + }) + + let iteName := Name.simple (str% "ite") + if !env.contains iteName && !modIdx.declByName.contains iteName then + let decC := Expr.mkApp (Expr.mkConst decName #[]) (Expr.mkBVar 0) + let iteTy := + Expr.mkForallE (Name.simple (str% "α")) sortU + (Expr.mkForallE (Name.simple (str% "c")) prop + (Expr.mkForallE (Name.simple (str% "h")) decC + (Expr.mkForallE (Name.simple (str% "t")) (Expr.mkBVar 2) + (Expr.mkForallE (Name.simple (str% "e")) (Expr.mkBVar 3) (Expr.mkBVar 4) .default) .default) + .instImplicit) .default) .implicit + let tLam := Expr.mkLam (Name.simple (str% "_")) (Expr.mkBVar 3) (Expr.mkBVar 2) .default + let eLam := Expr.mkLam (Name.simple (str% "_")) (Expr.mkApp (Expr.mkConst notName #[]) (Expr.mkBVar 3)) (Expr.mkBVar 1) .default + let diteCall := Expr.mkAppN (Expr.mkConst diteName #[uLvl]) + #[Expr.mkBVar 4, Expr.mkBVar 3, Expr.mkBVar 2, tLam, eLam] + let iteVal := + Expr.mkLam (Name.simple (str% "α")) sortU + (Expr.mkLam (Name.simple (str% "c")) prop + (Expr.mkLam (Name.simple (str% "h")) decC + (Expr.mkLam (Name.simple (str% "t")) (Expr.mkBVar 2) + (Expr.mkLam (Name.simple (str% "e")) (Expr.mkBVar 3) diteCall .default) .default) + .instImplicit) .default) .implicit + env := env.addConst (.defnInfo { + cnst := { name := iteName, levelParams := #[uName], type := iteTy } + value := iteVal, hints := .abbrev, safety := .safe, all := #[iteName] + }) + + let instDecTrue := Name.simple (str% "instDecidableTrue") + if !env.contains instDecTrue && !modIdx.declByName.contains instDecTrue then + let trueC := Expr.mkConst truePropName #[] + env := env.addConst (.defnInfo { + cnst := { name := instDecTrue, levelParams := #[], type := Expr.mkApp (Expr.mkConst decName #[]) trueC } + value := Expr.mkAppN (Expr.mkConst isTrueName #[]) #[trueC, Expr.mkConst (Name.mkStr2 (str% "True") (str% "intro")) #[]] + hints := .abbrev, safety := .safe, all := #[instDecTrue] + }) + env := env.addInstance { instName := instDecTrue, className := decName } + + let instDecFalse := Name.simple (str% "instDecidableFalse") + if !env.contains instDecFalse && !modIdx.declByName.contains instDecFalse then + let falseC := Expr.mkConst falsePropName #[] + env := env.addConst (.defnInfo { + cnst := { name := instDecFalse, levelParams := #[], type := Expr.mkApp (Expr.mkConst decName #[]) falseC } + value := Expr.mkAppN (Expr.mkConst isFalseName #[]) #[falseC, Expr.mkLam (Name.simple (str% "h")) falseC (Expr.mkBVar 0) .default] + hints := .abbrev, safety := .safe, all := #[instDecFalse] + }) + env := env.addInstance { instName := instDecFalse, className := decName } + + let zLvl := Level.mkZero + let oneLvl := Level.mkSucc zLvl + let mkNatRelDecTy (relConst : Ix.Expr) : Ix.Expr := + Expr.mkForallE (Name.simple (str% "a")) natConst + (Expr.mkForallE (Name.simple (str% "b")) natConst + (Expr.mkApp (Expr.mkConst decName #[]) + (Expr.mkAppN relConst #[Expr.mkBVar 1, Expr.mkBVar 0])) .default) .default + let eqNatRel := Expr.mkApp (Expr.mkConst eqName #[oneLvl]) natConst + let leNatRel := Expr.mkAppN (Expr.mkConst (Name.mkStr2 (str% "LE") (str% "le")) #[zLvl]) #[natConst, Expr.mkConst (Name.simple (str% "instLENat")) #[]] + let geNatRel := Expr.mkAppN (Expr.mkConst (Name.mkStr2 (str% "GE") (str% "ge")) #[zLvl]) #[natConst, Expr.mkConst (Name.simple (str% "instLENat")) #[]] + let ltNatRel := Expr.mkAppN (Expr.mkConst (Name.mkStr2 (str% "LT") (str% "lt")) #[zLvl]) #[natConst, Expr.mkConst (Name.simple (str% "instLTNat")) #[]] + let gtNatRel := Expr.mkAppN (Expr.mkConst (Name.mkStr2 (str% "GT") (str% "gt")) #[zLvl]) #[natConst, Expr.mkConst (Name.simple (str% "instLTNat")) #[]] + let decNotTy := + Expr.mkForallE (Name.simple (str% "p")) prop + (Expr.mkForallE (Name.simple (str% "inst")) (Expr.mkApp (Expr.mkConst decName #[]) (Expr.mkBVar 0)) + (Expr.mkApp (Expr.mkConst decName #[]) (Expr.mkApp (Expr.mkConst notName #[]) (Expr.mkBVar 1))) + .instImplicit) .implicit + let decInstAxioms : List (Ix.Name × Ix.Expr) := [ + (Name.simple (str% "instDecidableNot"), decNotTy), + (Name.simple (str% "instDecidableEqNat"), mkNatRelDecTy eqNatRel), + (Name.simple (str% "instDecidableLENat"), mkNatRelDecTy leNatRel), + (Name.simple (str% "instDecidableGENat"), mkNatRelDecTy geNatRel), + (Name.simple (str% "instDecidableLTNat"), mkNatRelDecTy ltNatRel), + (Name.simple (str% "instDecidableGTNat"), mkNatRelDecTy gtNatRel) + ] + env := addDecInstAxiomsIfMissing modIdx decName env decInstAxioms + + let classDecName := Name.mkStr2 (str% "Classical") (str% "propDecidable") + if !env.contains classDecName && !modIdx.declByName.contains classDecName then + let classDecTy := Expr.mkForallE (Name.simple (str% "p")) prop (Expr.mkApp (Expr.mkConst decName #[]) (Expr.mkBVar 0)) .default + env := env.addConst (.axiomInfo { cnst := { name := classDecName, levelParams := #[], type := classDecTy }, isUnsafe := false }) + return env + +/-- Part 5c of core prelude: on-demand `Subtype` and `Sigma`. -/ +def seedCoreSubSigma (env : IxElabEnv) (modIdx : ModuleIndex) : IxElabEnv := Id.run do + let mut env := env + let uName := Name.simple (str% "u") + let vName := Name.simple (str% "v") + let uLvl := Level.mkParam uName + let vLvl := Level.mkParam vName + let typeU := Expr.mkSort (Level.mkSucc uLvl) + let sortU := Expr.mkSort uLvl + let prop := Expr.mkProp + let subName := Name.simple (str% "Subtype") + if !env.contains subName && !modIdx.declByName.contains subName then + let subMk := Name.mkStr2 (str% "Subtype") (str% "mk") + let subVal := Name.mkStr2 (str% "Subtype") (str% "val") + let subProp := Name.mkStr2 (str% "Subtype") (str% "property") + let sortMax1U := Expr.mkSort (Level.mkMax (Level.mkSucc Level.mkZero) uLvl) + let predDom := Expr.mkForallE Name.mkAnon (Expr.mkBVar 0) prop .default + let subType := + Expr.mkForallE (Name.simple (str% "α")) sortU + (Expr.mkForallE (Name.simple (str% "p")) predDom sortMax1U .default) .implicit + let subApp := Expr.mkAppN (Expr.mkConst subName #[uLvl]) #[Expr.mkBVar 3, Expr.mkBVar 2] + let subMkTy := + Expr.mkForallE (Name.simple (str% "α")) sortU + (Expr.mkForallE (Name.simple (str% "p")) predDom + (Expr.mkForallE (Name.simple (str% "val")) (Expr.mkBVar 1) + (Expr.mkForallE (Name.simple (str% "property")) (Expr.mkApp (Expr.mkBVar 1) (Expr.mkBVar 0)) subApp .default) + .default) .implicit) .implicit + let ivSub : Ix.InductiveVal := { + cnst := { name := subName, levelParams := #[uName], type := subType } + numParams := 2, numIndices := 0, all := #[subName] + ctors := #[subMk], numNested := 0 + isRec := false, isUnsafe := false, isReflexive := false + } + let cSubMk : Ix.ConstructorVal := { + cnst := { name := subMk, levelParams := #[uName], type := subMkTy } + induct := subName, cidx := 0, numParams := 2, numFields := 2, isUnsafe := false + } + env := registerCanonicalInductiveBlock env #[(ivSub, #[cSubMk])] + env := addDefnsToEnv env (generateStructProjections ivSub cSubMk #[subVal, subProp] false).toList + env := env.addStructInfo { + structName := subName, ctorName := subMk, numParams := 2 + fields := #[ + { fieldName := Name.simple (str% "val"), projFnName := subVal, fieldIdx := 0 }, + { fieldName := Name.simple (str% "property"), projFnName := subProp, fieldIdx := 1 } + ] + } + + let sigName := Name.simple (str% "Sigma") + if !env.contains sigName && !modIdx.declByName.contains sigName then + let sigMk := Name.mkStr2 (str% "Sigma") (str% "mk") + let sigFst := Name.mkStr2 (str% "Sigma") (str% "fst") + let sigSnd := Name.mkStr2 (str% "Sigma") (str% "snd") + let typeV := Expr.mkSort (Level.mkSucc vLvl) + let typeMaxUV := Expr.mkSort (Level.mkSucc (Level.mkMax uLvl vLvl)) + let famDom := Expr.mkForallE Name.mkAnon (Expr.mkBVar 0) typeV .default + let sigType := + Expr.mkForallE (Name.simple (str% "α")) typeU + (Expr.mkForallE (Name.simple (str% "β")) famDom typeMaxUV .default) .implicit + let sigApp := Expr.mkAppN (Expr.mkConst sigName #[uLvl, vLvl]) #[Expr.mkBVar 3, Expr.mkBVar 2] + let sigMkTy := + Expr.mkForallE (Name.simple (str% "α")) typeU + (Expr.mkForallE (Name.simple (str% "β")) famDom + (Expr.mkForallE (Name.simple (str% "fst")) (Expr.mkBVar 1) + (Expr.mkForallE (Name.simple (str% "snd")) (Expr.mkApp (Expr.mkBVar 1) (Expr.mkBVar 0)) sigApp .default) + .default) .implicit) .implicit + let ivSig : Ix.InductiveVal := { + cnst := { name := sigName, levelParams := #[uName, vName], type := sigType } + numParams := 2, numIndices := 0, all := #[sigName] + ctors := #[sigMk], numNested := 0 + isRec := false, isUnsafe := false, isReflexive := false + } + let cSigMk : Ix.ConstructorVal := { + cnst := { name := sigMk, levelParams := #[uName, vName], type := sigMkTy } + induct := sigName, cidx := 0, numParams := 2, numFields := 2, isUnsafe := false + } + env := registerCanonicalInductiveBlock env #[(ivSig, #[cSigMk])] + env := addDefnsToEnv env (generateStructProjections ivSig cSigMk #[sigFst, sigSnd] false).toList + env := env.addStructInfo { + structName := sigName, ctorName := sigMk, numParams := 2 + fields := #[ + { fieldName := Name.simple (str% "fst"), projFnName := sigFst, fieldIdx := 0 }, + { fieldName := Name.simple (str% "snd"), projFnName := sigSnd, fieldIdx := 1 } + ] + } + return env + +/-- Scan syntax to decide which wave-2 prelude parts (`Order`, `Decidable`, `Subtype`/`Sigma`) are needed. -/ +def stxNeedsWave2Prelude : Nat → Stx → Bool × Bool × Bool + | 0, _ => (false, false, false) + | _ + 1, .ident _ _ idF => + let c := (Name.components (FName.toIxName idF)).headD (str% "") + let ord := c == (str% "LE") || c == (str% "LT") || c == (str% "GE") || c == (str% "GT") + let dec := c == (str% "Decidable") || c == (str% "DecidableEq") || c == (str% "dite") || c == (str% "ite") + let sub := c == (str% "Subtype") || c == (str% "Sigma") + (ord, dec, sub) + | _, .atom _ v => + let ord := Sym.beq v (s% "<") || Sym.beq v (s% "≤") || Sym.beq v (s% "<=") || + Sym.beq v (s% ">") || Sym.beq v (s% "≥") || Sym.beq v (s% ">=") + let dec := Sym.beq v (s% "if") + (ord, dec, false) + | f + 1, .node _ k as => + let isIf := k == SyntaxKindF.ifTerm + as.foldl (fun (o1, d1, s1) child => + let (o2, d2, s2) := stxNeedsWave2Prelude f child + (o1 || o2, d1 || d2, s1 || s2)) (isIf, isIf, false) + | _, _ => (false, false, false) + +/-- Part 5 of core prelude: on-demand Order (`LE`, `LT`, `GE`, `GT`), `Decidable`/`dite`/`ite`, `Subtype`, `Sigma`. -/ +def seedCoreOrder (env : IxElabEnv) (modIdx : ModuleIndex) : IxElabEnv := + let (needsOrder, needsDecidable, needsSubSigma) := + modIdx.decls.foldl (fun (o1, d1, s1) decl => + let (o2, d2, s2) := stxNeedsWave2Prelude 64 decl.stx + (o1 || o2, d1 || d2, s1 || s2)) (false, false, false) + let env1 := if needsOrder || needsDecidable then seedCoreOrderRel env modIdx else env + let env2 := if needsDecidable then seedCoreDecidable env1 modIdx else env1 + if needsSubSigma then seedCoreSubSigma env2 modIdx else env2 + +/-- Register a minimal core prelude (`Bool`, `Nat`, `Unit`, `PUnit`, `Eq`, `Prod`, `List`, etc.) + for any core type not explicitly declared in `modIdx`. -/ +def seedCorePreludeIfMissing (env : IxElabEnv) (modIdx : ModuleIndex) : IxElabEnv := + let env := seedCoreBasic env modIdx + let env := seedCoreLogic env modIdx + let env := seedCoreData env modIdx + let env := seedCoreClasses env modIdx + seedCoreOrder env modIdx + +/-- Register the core Lean 4 `Init` arithmetic/order typeclass instance entries in `env.instances`. -/ +def registerLeanInitArithInstances (env : IxElabEnv) : IxElabEnv := + let entries : List (Ix.Name × Ix.Name) := [ + (Name.simple (str% "OfNat"), Name.simple (str% "instOfNatNat")), + (Name.simple (str% "LE"), Name.simple (str% "instLENat")), + (Name.simple (str% "LT"), Name.simple (str% "instLTNat")), + (Name.simple (str% "Add"), Name.simple (str% "instAddNat")), + (Name.simple (str% "HAdd"), Name.simple (str% "instHAdd")), + (Name.simple (str% "NatPow"), Name.simple (str% "instNatPowNat")), + (Name.simple (str% "Pow"), Name.simple (str% "instPowNat")), + (Name.simple (str% "HPow"), Name.simple (str% "instHPow")) + ] + let rec go (e : IxElabEnv) : List (Ix.Name × Ix.Name) → IxElabEnv + | [] => e + | (clsName, instName) :: rest => + e.bindEnv fun e' => + let eNext := + if e'.instances.any (fun entry => entry.className == clsName && entry.instName == instName) then + e' + else + e'.addInstance { className := clsName, instName := instName } + go eNext rest + go env entries + +/-- Seed Lean 4's `Init` arithmetic, order, numeral (`OfNat`), and inequality (`Ne`) typeclasses + and `Nat` instances (`LE.le`, `LT.lt`, `GE.ge`, `GT.gt`, `HAdd.hAdd`, `HPow.hPow`, `OfNat.ofNat`) + into `env` so statements like Fermat's Last Theorem elaborate to the exact Lean 4 `Ix.Expr`. -/ +def seedLeanInitArith (env : IxElabEnv) : IxElabEnv := Id.run do + let mut env := env + let uName := Name.simple (str% "u") + let vName := Name.simple (str% "v") + let wName := Name.simple (str% "w") + let uLvl := Level.mkParam uName + let vLvl := Level.mkParam vName + let wLvl := Level.mkParam wName + let zLvl := Level.mkZero + let type0 := Expr.mkSort (Level.mkSucc zLvl) + let sortU := Expr.mkSort uLvl + let typeU := Expr.mkSort (Level.mkSucc uLvl) + let typeV := Expr.mkSort (Level.mkSucc vLvl) + let typeW := Expr.mkSort (Level.mkSucc wLvl) + let prop := Expr.mkProp + let natName := Name.simple (str% "Nat") + let natConst := Expr.mkConst natName #[] + + let addAxiomIfMissing (e : IxElabEnv) (nm : Ix.Name) (lvls : Array Ix.Name) (ty : Ix.Expr) : IxElabEnv := + e.bindEnv fun e' => + if e'.contains nm then e' + else e'.addConst (.axiomInfo { cnst := { name := nm, levelParams := lvls, type := ty }, isUnsafe := false }) + + -- 0. `Nat : Type` and `Eq.{u} : {α : Sort u} → α → α → Prop` + env := addAxiomIfMissing env natName #[] type0 + let eqName := Name.simple (str% "Eq") + let eqType := + Expr.mkForallE (Name.simple (str% "α")) sortU + (Expr.mkForallE (Name.simple (str% "a")) (Expr.mkBVar 0) + (Expr.mkForallE (Name.simple (str% "b")) (Expr.mkBVar 1) prop .default) .default) + .implicit + env := addAxiomIfMissing env eqName #[uName] eqType + + -- 1. `Not : Prop → Prop` and `Ne.{u} : {α : Sort u} → α → α → Prop` + let notName := Name.simple (str% "Not") + env := addAxiomIfMissing env notName #[] (Expr.mkForallE (Name.simple (str% "a")) prop prop .default) + let neName := Name.simple (str% "Ne") + let neType := + Expr.mkForallE (Name.simple (str% "α")) sortU + (Expr.mkForallE (Name.simple (str% "a")) (Expr.mkBVar 0) + (Expr.mkForallE (Name.simple (str% "b")) (Expr.mkBVar 1) prop .default) .default) + .implicit + env := addAxiomIfMissing env neName #[uName] neType + + -- 2. `OfNat.{u} (α : Type u) (_ : Nat) : Type u`, `OfNat.ofNat`, `instOfNatNat` + let ofNatName := Name.simple (str% "OfNat") + let ofNatTy := + Expr.mkForallE (Name.simple (str% "α")) typeU + (Expr.mkForallE Name.mkAnon natConst typeU .default) .default + env := addAxiomIfMissing env ofNatName #[uName] ofNatTy + + let ofNatFnName := Name.mkStr2 (str% "OfNat") (str% "ofNat") + let ofNatApp := Expr.mkAppN (Expr.mkConst ofNatName #[uLvl]) #[Expr.mkBVar 1, Expr.mkBVar 0] + let ofNatFnTy := + Expr.mkForallE (Name.simple (str% "α")) typeU + (Expr.mkForallE (Name.simple (str% "x")) natConst + (Expr.mkForallE (Name.simple (str% "self")) ofNatApp (Expr.mkBVar 2) .instImplicit) .default) + .implicit + env := addAxiomIfMissing env ofNatFnName #[uName] ofNatFnTy + + let instOfNatNatName := Name.simple (str% "instOfNatNat") + let instOfNatNatTy := + Expr.mkForallE (Name.simple (str% "n")) natConst + (Expr.mkAppN (Expr.mkConst ofNatName #[zLvl]) #[natConst, Expr.mkBVar 0]) .default + env := addAxiomIfMissing env instOfNatNatName #[] instOfNatNatTy + + -- 3. `LE.{u}`, `LE.le.{u}`, `instLENat`, `GE.ge.{u}` + let leName := Name.simple (str% "LE") + env := addAxiomIfMissing env leName #[uName] (Expr.mkForallE (Name.simple (str% "α")) typeU typeU .default) + let leApp0 := Expr.mkApp (Expr.mkConst leName #[uLvl]) (Expr.mkBVar 0) + let leRelTy := + Expr.mkForallE (Name.simple (str% "α")) typeU + (Expr.mkForallE (Name.simple (str% "self")) leApp0 + (Expr.mkForallE (Name.simple (str% "a")) (Expr.mkBVar 1) + (Expr.mkForallE (Name.simple (str% "b")) (Expr.mkBVar 2) prop .default) .default) + .instImplicit) .implicit + env := addAxiomIfMissing env (Name.mkStr2 (str% "LE") (str% "le")) #[uName] leRelTy + env := addAxiomIfMissing env (Name.mkStr2 (str% "GE") (str% "ge")) #[uName] leRelTy + env := addAxiomIfMissing env (Name.simple (str% "instLENat")) #[] + (Expr.mkApp (Expr.mkConst leName #[zLvl]) natConst) + + -- 4. `LT.{u}`, `LT.lt.{u}`, `instLTNat`, `GT.gt.{u}` + let ltName := Name.simple (str% "LT") + env := addAxiomIfMissing env ltName #[uName] (Expr.mkForallE (Name.simple (str% "α")) typeU typeU .default) + let ltApp0 := Expr.mkApp (Expr.mkConst ltName #[uLvl]) (Expr.mkBVar 0) + let ltRelTy := + Expr.mkForallE (Name.simple (str% "α")) typeU + (Expr.mkForallE (Name.simple (str% "self")) ltApp0 + (Expr.mkForallE (Name.simple (str% "a")) (Expr.mkBVar 1) + (Expr.mkForallE (Name.simple (str% "b")) (Expr.mkBVar 2) prop .default) .default) + .instImplicit) .implicit + env := addAxiomIfMissing env (Name.mkStr2 (str% "LT") (str% "lt")) #[uName] ltRelTy + env := addAxiomIfMissing env (Name.mkStr2 (str% "GT") (str% "gt")) #[uName] ltRelTy + env := addAxiomIfMissing env (Name.simple (str% "instLTNat")) #[] + (Expr.mkApp (Expr.mkConst ltName #[zLvl]) natConst) + + -- 5. `Add.{u}`, `HAdd.{u, v, w}`, `HAdd.hAdd.{u, v, w}`, `instHAdd.{u}`, `instAddNat` + let addName := Name.simple (str% "Add") + env := addAxiomIfMissing env addName #[uName] (Expr.mkForallE (Name.simple (str% "α")) typeU typeU .default) + let hAddName := Name.simple (str% "HAdd") + let typeMaxUVW := Expr.mkSort (Level.mkSucc (Level.mkMax (Level.mkMax uLvl vLvl) wLvl)) + let hAddTy := + Expr.mkForallE (Name.simple (str% "α")) typeU + (Expr.mkForallE (Name.simple (str% "β")) typeV + (Expr.mkForallE (Name.simple (str% "γ")) typeW typeMaxUVW .default) .default) .default + env := addAxiomIfMissing env hAddName #[uName, vName, wName] hAddTy + + let hAddApp := Expr.mkAppN (Expr.mkConst hAddName #[uLvl, vLvl, wLvl]) #[Expr.mkBVar 2, Expr.mkBVar 1, Expr.mkBVar 0] + let hAddFnTy := + Expr.mkForallE (Name.simple (str% "α")) typeU + (Expr.mkForallE (Name.simple (str% "β")) typeV + (Expr.mkForallE (Name.simple (str% "γ")) typeW + (Expr.mkForallE (Name.simple (str% "self")) hAddApp + (Expr.mkForallE (Name.simple (str% "a")) (Expr.mkBVar 3) + (Expr.mkForallE (Name.simple (str% "b")) (Expr.mkBVar 3) (Expr.mkBVar 3) .default) .default) + .instImplicit) .implicit) .implicit) .implicit + env := addAxiomIfMissing env (Name.mkStr2 (str% "HAdd") (str% "hAdd")) #[uName, vName, wName] hAddFnTy + + let instHAddTy := + Expr.mkForallE (Name.simple (str% "α")) typeU + (Expr.mkForallE (Name.simple (str% "self")) (Expr.mkApp (Expr.mkConst addName #[uLvl]) (Expr.mkBVar 0)) + (Expr.mkAppN (Expr.mkConst hAddName #[uLvl, uLvl, uLvl]) #[Expr.mkBVar 1, Expr.mkBVar 1, Expr.mkBVar 1]) + .instImplicit) .implicit + env := addAxiomIfMissing env (Name.simple (str% "instHAdd")) #[uName] instHAddTy + env := addAxiomIfMissing env (Name.simple (str% "instAddNat")) #[] + (Expr.mkApp (Expr.mkConst addName #[zLvl]) natConst) + + -- 6. `NatPow.{u}`, `Pow.{u, v}`, `HPow.{u, v, w}`, `HPow.hPow.{u, v, w}`, `instHPow.{u, v}`, `instPowNat.{u}`, `instNatPowNat` + let natPowName := Name.simple (str% "NatPow") + env := addAxiomIfMissing env natPowName #[uName] (Expr.mkForallE (Name.simple (str% "α")) typeU typeU .default) + let powName := Name.simple (str% "Pow") + let typeMaxUV := Expr.mkSort (Level.mkSucc (Level.mkMax uLvl vLvl)) + env := addAxiomIfMissing env powName #[uName, vName] + (Expr.mkForallE (Name.simple (str% "α")) typeU (Expr.mkForallE (Name.simple (str% "β")) typeV typeMaxUV .default) .default) + let hPowName := Name.simple (str% "HPow") + let hPowTy := + Expr.mkForallE (Name.simple (str% "α")) typeU + (Expr.mkForallE (Name.simple (str% "β")) typeV + (Expr.mkForallE (Name.simple (str% "γ")) typeW typeMaxUVW .default) .default) .default + env := addAxiomIfMissing env hPowName #[uName, vName, wName] hPowTy + + let hPowApp := Expr.mkAppN (Expr.mkConst hPowName #[uLvl, vLvl, wLvl]) #[Expr.mkBVar 2, Expr.mkBVar 1, Expr.mkBVar 0] + let hPowFnTy := + Expr.mkForallE (Name.simple (str% "α")) typeU + (Expr.mkForallE (Name.simple (str% "β")) typeV + (Expr.mkForallE (Name.simple (str% "γ")) typeW + (Expr.mkForallE (Name.simple (str% "self")) hPowApp + (Expr.mkForallE (Name.simple (str% "a")) (Expr.mkBVar 3) + (Expr.mkForallE (Name.simple (str% "b")) (Expr.mkBVar 3) (Expr.mkBVar 3) .default) .default) + .instImplicit) .implicit) .implicit) .implicit + env := addAxiomIfMissing env (Name.mkStr2 (str% "HPow") (str% "hPow")) #[uName, vName, wName] hPowFnTy + + let instHPowTy := + Expr.mkForallE (Name.simple (str% "α")) typeU + (Expr.mkForallE (Name.simple (str% "β")) typeV + (Expr.mkForallE (Name.simple (str% "self")) + (Expr.mkAppN (Expr.mkConst powName #[uLvl, vLvl]) #[Expr.mkBVar 1, Expr.mkBVar 0]) + (Expr.mkAppN (Expr.mkConst hPowName #[uLvl, vLvl, uLvl]) #[Expr.mkBVar 2, Expr.mkBVar 1, Expr.mkBVar 2]) + .instImplicit) .implicit) .implicit + env := addAxiomIfMissing env (Name.simple (str% "instHPow")) #[uName, vName] instHPowTy + + let instPowNatTy := + Expr.mkForallE (Name.simple (str% "α")) typeU + (Expr.mkForallE (Name.simple (str% "self")) + (Expr.mkApp (Expr.mkConst natPowName #[uLvl]) (Expr.mkBVar 0)) + (Expr.mkAppN (Expr.mkConst powName #[uLvl, zLvl]) #[Expr.mkBVar 1, natConst]) + .instImplicit) .implicit + env := addAxiomIfMissing env (Name.simple (str% "instPowNat")) #[uName] instPowNatTy + env := addAxiomIfMissing env (Name.simple (str% "instNatPowNat")) #[] + (Expr.mkApp (Expr.mkConst natPowName #[zLvl]) natConst) + + return registerLeanInitArithInstances env + +/-! ## Auto-Bound Implicit Parameters & Attributes -/ + +/-- Extract `@[attr₁, attr₂, ...]` attribute names from a declaration's `modifiers` node. -/ +def extractDeclAttributes (modsNode : Stx) : Array Ix.Name := + (Syntax.getArgs modsNode).filterMap fun child => + match child with + | .ident _ _ idF => + let id := FName.toIxName idF + if Name.isAnonymous id then none else some id + | _ => none + +/-- True if `id` is a single-component Greek (`α..ω`) or single lowercase ASCII (`a..z`) identifier + eligible for Lean 4 auto-implicit parameter binding (`{α : _}`). -/ +def isAutoImplicitCandidate : Ix.Name → Bool + | .str (.anonymous _) s _ => + match Sym.ofString s with + | .cons b0 .nil => Nat.ble 97 b0 && Nat.ble b0 122 -- 'a'..'z' + | .cons b0 (.cons b1 .nil) => + -- UTF-8 for Greek α (U+03B1 = 0xCE 0xB1) .. ω (U+03C9 = 0xCF 0x89) + (Nat.beq b0 0xCE && Nat.ble 0xB1 b1 && Nat.ble b1 0xBF) || + (Nat.beq b0 0xCF && Nat.ble 0x80 b1 && Nat.ble b1 0x89) + | _ => false + | _ => false + +def insertNameListSet (s : NameSet) : List Ix.Name → NameSet + | [] => s + | n :: rest => insertNameListSet (s.insert n) rest + +/-- Structurally recursive syntax scanner for auto-implicit candidates (zero closures). -/ +def scanAutoImplicitStx (scope : ScopeSnapshot) (modIdx : ModuleIndex) + (env : IxElabEnv) : Nat → NameSet → Stx → List Ix.Name → List Ix.Name + | 0, _, _, acc => acc + | f + 1, bound, stx, acc => + let rec scanBinders (bSet : NameSet) (a : List Ix.Name) : List Stx → NameSet × List Ix.Name + | [] => (bSet, a) + | bs :: rest => + let g := decodeBinderNode bs + let a' := match g.typeStx? with + | some ts => scanAutoImplicitStx scope modIdx env f bSet ts a + | none => a + scanBinders (insertNameListSet bSet g.names.toList) a' rest + let rec scanArgs (a : List Ix.Name) : List Stx → List Ix.Name + | [] => a + | child :: rest => scanArgs (scanAutoImplicitStx scope modIdx env f bound child a) rest + match stx with + | .ident _ _ idF => + let id := FName.toIxName idF + if isAutoImplicitCandidate id && !bound.contains id && !acc.contains id then + let res := resolveIdentInScopeMap scope modIdx env.consts id + let isKnown := env.contains res || modIdx.declByName.contains res || + env.isCtor res || modIdx.isModuleCtor res + if isKnown then acc else acc ++ [id] + else + acc + | .node _ kF args => + let k := FName.toIxName kF + if k == SyntaxKind.typeTerm || k == SyntaxKind.sortTerm || + k == SyntaxKind.explicitTerm || k == SyntaxKind.projTerm then + if k == SyntaxKind.projTerm then + scanAutoImplicitStx scope modIdx env f bound (args.getD 0 .missing) acc + else acc + else if k == SyntaxKind.forallTerm then + let isKw := match args[0]? with + | some (.atom _ kw) => Sym.beq kw (s% "forall") || Sym.beq kw (s% "∀") + | _ => false + let bNode := if isKw then args.getD 1 .missing else args.getD 0 .missing + let body := if isKw then args.getD 4 .missing else args.getD 3 .missing + let (bound', acc') := scanBinders bound acc (Syntax.getArgs bNode).toList + scanAutoImplicitStx scope modIdx env f bound' body acc' + else if k == SyntaxKind.funTerm then + let bNode := args.getD 1 .missing + let body := args.getD 3 .missing + let (bound', acc') := scanBinders bound acc (Syntax.getArgs bNode).toList + scanAutoImplicitStx scope modIdx env f bound' body acc' + else if k == SyntaxKind.letTerm || k == SyntaxKind.letBorrowTerm || k == SyntaxKind.letRecTerm then + let isLong := k != SyntaxKind.letTerm + let idStx := if isLong then args.getD 3 .missing else args.getD 2 .missing + let bNode := if isLong then args.getD 4 .missing else args.getD 3 .missing + let optTy := if isLong then args.getD 5 .missing else args.getD 4 .missing + let val := if isLong then args.getD 7 .missing else args.getD 6 .missing + let body := if isLong then args.getD 9 .missing else args.getD 8 .missing + let letId := Syntax.getId idStx + let (boundB, acc1) := scanBinders bound acc (Syntax.getArgs bNode).toList + let acc2 := scanAutoImplicitStx scope modIdx env f boundB optTy acc1 + let boundVal := if k == SyntaxKind.letRecTerm && !Name.isAnonymous letId then boundB.insert letId else boundB + let acc3 := scanAutoImplicitStx scope modIdx env f boundVal val acc2 + let boundBody := if Name.isAnonymous letId then bound else bound.insert letId + scanAutoImplicitStx scope modIdx env f boundBody body acc3 + else + scanArgs acc args.toList + | _ => acc + +/-- Scan `paramGroups` and `optTypeNode` for unbound auto-implicit candidates, returning + implicit `{id : _}` `ParsedBinderGroup`s in left-to-right appearance order. + 100% first-order (no closures / `List.map` / `List.foldl`) for `IxCCAiur`. -/ +def collectAutoImplicitGroups (scope : ScopeSnapshot) (modIdx : ModuleIndex) + (env : IxElabEnv) (varGroups : List ParsedBinderGroup) + (paramGroups : List ParsedBinderGroup) (optTypeNode : Stx) : List ParsedBinderGroup := + let rec collectVarBound (s : NameSet) : List ParsedBinderGroup → NameSet + | [] => s + | g :: rest => collectVarBound (insertNameListSet s g.names.toList) rest + let initBound := collectVarBound NameSet.empty varGroups + let rec scanParams (bSet : NameSet) (a : List Ix.Name) : List ParsedBinderGroup → NameSet × List Ix.Name + | [] => (bSet, a) + | g :: rest => + let a' := match g.typeStx? with + | some ts => scanAutoImplicitStx scope modIdx env 64 bSet ts a + | none => a + scanParams (insertNameListSet bSet g.names.toList) a' rest + let (boundAfterParams, autoNames1) := scanParams initBound [] paramGroups + let autoNames := scanAutoImplicitStx scope modIdx env 64 boundAfterParams optTypeNode autoNames1 + let defaultTypeStx := Syntax.mkNode SyntaxKind.typeTerm #[Syntax.mkSimpleAtom (str% "Type"), Syntax.mkNullNode #[]] + let rec mkGroups : List Ix.Name → List ParsedBinderGroup + | [] => [] + | nm :: rest => + { names := #[nm], typeStx? := some defaultTypeStx, binderInfo := .implicit, contract := default } :: mkGroups rest + mkGroups autoNames + +/-! ## Inductive, Structure, and Class SCC Elaboration -/ + +/-- Elaborate the header `(numParams, numIndices, levelParams, fullType)` of an + `inductive`, `structure`, or `class` declaration. -/ +def elabInductiveHeaderWith (elabTermFn : Nat → Stx → Option Ix.Expr → IxElabM Ix.Expr) + (decl : ModuleDecl) (fuel : Nat := 128) : + IxElabM (Nat × Nat × Array Ix.Name × Ix.Expr) := do + modify fun st => { st with autoBoundUnivs := [], localLetContracts := #[] } + let cmd := decl.stx + let k := Syntax.getKind cmd + let bindersNode := Syntax.getArg cmd 4 + let optTypeNode := + if k == SyntaxKind.inductiveDecl then Syntax.getArg cmd 6 + else Syntax.getArg cmd 7 + let varGroups := decl.scope.varBinders.toList.map decodeBinderNode + let paramGroups := (Syntax.getArgs bindersNode).toList.map decodeBinderNode + let ctx0 ← read + let st0 ← get + let autoGroups := collectAutoImplicitGroups decl.scope ctx0.modIdx st0.env varGroups paramGroups optTypeNode + let allGroups := varGroups ++ autoGroups ++ paramGroups + withReader (fun ctx => { ctx with + lctx := LocalContext.empty + scope := decl.scope + currDecl? := some decl.fullName + univParams := decl.univParams }) do + elabBinderGroups (fun s exp? => elabTermFn fuel s exp?) allGroups #[] fun paramFVars => do + let resultTy ← + if Syntax.isNone optTypeNode || Syntax.isMissing optTypeNode then + pure (Expr.mkSort (Level.mkSucc Level.mkZero)) + else + let t ← elabTermFn fuel optTypeNode none + let _ ← ensureSort 32 t + instantiateMVars 32 t + let nIndices := countForalls 64 resultTy + let fullType ← mkForallFVars paramFVars resultTy + let fullType ← instantiateMVars 32 fullType + let fullType := defaultUnassignedExprLevelMVars fullType + let st ← get + let lvlParams := Array.mk (decl.univParams ++ decl.scope.levelNames ++ st.autoBoundUnivs).eraseDups + return (paramFVars.size, nIndices, lvlParams, fullType) + +/-- Elaborate a single constructor `| shortId binders [: optType]` of an inductive `decl`. -/ +def elabOneConstructorWith (elabTermFn : Nat → Stx → Option Ix.Expr → IxElabM Ix.Expr) + (decl : ModuleDecl) (lvlParams : Array Ix.Name) + (paramGroups : List ParsedBinderGroup) (ctorStx : Stx) (cidx : Nat) + (fuel : Nat := 128) : + IxElabM (Ix.ConstructorVal × Array Ixon.BinderContract × Ixon.ValueContract) := do + let shortId := Syntax.getId (Syntax.getArg ctorStx 1) + let fullCtorName := Name.append decl.fullName shortId + let cBindersNode := Syntax.getArg ctorStx 2 + let cVPrefNode := Syntax.getArg ctorStx 3 + let cOptTypeNode := Syntax.getArg ctorStx 4 + let retContract := (decodeContractPrefix cVPrefNode).toValueContract + let cGroups := (Syntax.getArgs cBindersNode).toList.map decodeBinderNode + -- Param binders on constructors are always `.implicit` in Lean/Ix kernel + let implicitParamGroups := paramGroups.map fun g => { g with binderInfo := .implicit } + withReader (fun ctx => { ctx with + lctx := LocalContext.empty + scope := decl.scope + currDecl? := some fullCtorName + univParams := lvlParams.toList }) do + elabBinderGroups (fun s exp? => elabTermFn fuel s exp?) implicitParamGroups #[] fun paramFVars => do + elabBinderGroups (fun s exp? => elabTermFn fuel s exp?) cGroups #[] fun fieldFVars => do + let indUnivs := lvlParams.map Level.mkParam + let paramExprs := paramFVars.map Expr.mkFVar + let defaultRet := Expr.mkAppN (Expr.mkConst decl.fullName indUnivs) paramExprs + let (targetRet, extraFields) ← + if Syntax.isNone cOptTypeNode || Syntax.isMissing cOptTypeNode then + pure (defaultRet, 0) + else + let t ← elabTermFn fuel cOptTypeNode none + let _ ← ensureSort 32 t + let tInst ← instantiateMVars 32 t + pure (tInst, countForalls 64 tInst) + let allFVars := paramFVars ++ fieldFVars + let fullCtorTy ← mkForallFVars allFVars targetRet retContract + let fullCtorTy ← instantiateMVars 32 fullCtorTy + let fullCtorTy := defaultUnassignedExprLevelMVars fullCtorTy + let ctxNow ← read + let bcs : Array Ixon.BinderContract := allFVars.filterMap fun fv => + (ctxNow.lctx.findFVar? fv).map (·.contract) + let cval : Ix.ConstructorVal := { + cnst := { + name := fullCtorName + levelParams := lvlParams + type := fullCtorTy + } + induct := decl.fullName + cidx := cidx + numParams := paramFVars.size + numFields := fieldFVars.size + extraFields + isUnsafe := false + } + return (cval, bcs, retContract) + +/-- Elaborate a `structure` or `class` field list (including `extends Parent₁, Parent₂` with + diamond field deduplication) into a single constructor, `StructInfo`, and parent projection definitions. -/ +def elabStructureFieldsWith (elabTermFn : Nat → Stx → Option Ix.Expr → IxElabM Ix.Expr) + (decl : ModuleDecl) (lvlParams : Array Ix.Name) + (paramGroups : List ParsedBinderGroup) (ctorFullName : Ix.Name) + (fieldsNode : Stx) (fuel : Nat := 128) : + IxElabM (Ix.ConstructorVal × StructInfo × Array Ixon.BinderContract × Array Ix.DefinitionVal) := do + let implicitParamGroups := paramGroups.map fun g => { g with binderInfo := .implicit } + let extendsNode := Syntax.getArg decl.stx 5 + let parentStxs := (Syntax.getArgs extendsNode).toList + let fieldItems := (Syntax.getArgs fieldsNode).toList + withReader (fun ctx => { ctx with + lctx := LocalContext.empty + scope := decl.scope + currDecl? := some ctorFullName + univParams := lvlParams.toList }) do + elabBinderGroups (fun s exp? => elabTermFn fuel s exp?) implicitParamGroups #[] fun paramFVars => do + -- Flatten `fieldDecl` items into `(shortFieldName, bi, contract, tyStx, defaultStx?)` + let flatFields : List (Ix.Name × Lean.BinderInfo × Ixon.BinderContract × Stx × Option Stx) := + fieldItems.flatMap fun item => + let firstAtom := Syntax.getAtomVal (Syntax.getArg item 0) + let (isBrack, bi) : Bool × Lean.BinderInfo := + if firstAtom == (str% "(") then (true, .default) + else if firstAtom == (str% "{") then (true, .implicit) + else (false, .default) + let bPrefNode := if isBrack then Syntax.getArg item 1 else Syntax.getArg item 0 + let idsNode := if isBrack then Syntax.getArg item 2 else Syntax.getArg item 1 + let vPrefNode := if isBrack then Syntax.getArg item 4 else Syntax.getArg item 3 + let tyNode := if isBrack then Syntax.getArg item 5 else Syntax.getArg item 4 + let optDef := if isBrack then Syntax.getArg item 6 else Syntax.getArg item 5 + let defStx? := (Syntax.getOptional? optDef).map fun seq => Syntax.getArg seq 1 + let contract := (mergeParsedContracts (decodeContractPrefix bPrefNode) (decodeContractPrefix vPrefNode)).toBinderContract + (Syntax.getArgs idsNode).toList.map fun idStx => + (Syntax.getId idStx, bi, contract, tyNode, defStx?) + + -- Non-CPS own-field elaboration returning `(fvars, fInfos, extendedCtx)` + let rec elabFieldLoop + (rem : List (Ix.Name × Lean.BinderInfo × Ixon.BinderContract × Stx × Option Stx)) + (fIdx : Nat) (fvars : Array Ix.Name) (fInfos : Array StructFieldInfo) : + ElabContext → ElabState → ElabRes (Array Ix.Name × Array StructFieldInfo × ElabContext) := + fun ctx st => + match rem with + | [] => .ok (fvars, fInfos, ctx) st + | (fShort, bi, contract, tyStx, defStx?) :: rest => + match fInfos.findIdx? (fun fi => fi.fieldName == fShort) with + | some existingIdx => + let fInfos' := match defStx? with + | some dStx => + if h : existingIdx < fInfos.size then + fInfos.set existingIdx { fInfos[existingIdx] with defaultVal := some dStx } + else fInfos + | none => fInfos + elabFieldLoop rest fIdx fvars fInfos' ctx st + | none => + match elabTermFn fuel tyStx none ctx st with + | .error e => .error e + | .ok fTy st1 => + match ensureSortPure ctx st1 32 fTy with + | .error e => .error e + | .ok _ st2 => + let fTyInst := instantiateMVarsPure st2.mctx 32 fTy + let fInfo : StructFieldInfo := { + fieldName := fShort + projFnName := Name.append decl.fullName fShort + fieldIdx := fIdx + binderInfo := bi + contract := contract + defaultVal := defStx? + } + let (fvId, _, ctx', st3) := pushLocalDeclPure ctx st2 fShort fTyInst bi contract none none false + elabFieldLoop rest (fIdx + 1) (fvars.push fvId) (fInfos.push fInfo) ctx' st3 + + -- Non-CPS inherited parent-field elaboration returning `(fIdx, fvars, fInfos, extendedCtx)` + let rec elabParentFields + (remPFields : List StructFieldInfo) (curPCtorTy : Ix.Expr) + (fIdx : Nat) (fvars : Array Ix.Name) (fInfos : Array StructFieldInfo) : + ElabContext → ElabState → ElabRes (Nat × Array Ix.Name × Array StructFieldInfo × ElabContext) := + fun ctx st => + match remPFields with + | [] => .ok (fIdx, fvars, fInfos, ctx) st + | pf :: restPF => + let curW := whnfPure ctx st fuel curPCtorTy + match stripMData curW with + | .forallE _ fDom fBody _ _ => + match fInfos.findIdx? (fun fi => fi.fieldName == pf.fieldName) with + | some existingIdx => + let existingFvExpr := Expr.mkFVar (fvars.getD existingIdx Name.mkAnon) + elabParentFields restPF (instantiate1 fBody existingFvExpr) fIdx fvars fInfos ctx st + | none => + let fDomInst := instantiateMVarsPure st.mctx 32 fDom + let fInfo : StructFieldInfo := { + fieldName := pf.fieldName + projFnName := Name.append decl.fullName pf.fieldName + fieldIdx := fIdx + binderInfo := pf.binderInfo + contract := pf.contract + defaultVal := pf.defaultVal + } + let (fvId, fvExpr, ctx', st1) := pushLocalDeclPure ctx st pf.fieldName fDomInst pf.binderInfo pf.contract none none false + elabParentFields restPF (instantiate1 fBody fvExpr) (fIdx + 1) (fvars.push fvId) (fInfos.push fInfo) ctx' st1 + | _ => .ok (fIdx, fvars, fInfos, ctx) st + + -- Non-CPS loop over `extends P₁, P₂` parents returning `(fIdx, fvars, fInfos, parentSpecs, extendedCtx)` + let rec elabParentsLoop + (remParents : List Stx) + (fIdx : Nat) (fvars : Array Ix.Name) (fInfos : Array StructFieldInfo) + (parentSpecs : Array (Ix.Name × Array Ix.Level × Array Ix.Expr × StructInfo)) : + ElabContext → ElabState → + ElabRes (Nat × Array Ix.Name × Array StructFieldInfo × Array (Ix.Name × Array Ix.Level × Array Ix.Expr × StructInfo) × ElabContext) := + fun ctx st => + match remParents with + | [] => .ok (fIdx, fvars, fInfos, parentSpecs, ctx) st + | pStx :: restP => + match elabTermFn fuel pStx none ctx st with + | .error e => .error e + | .ok pTy st1 => + match ensureSortPure ctx st1 32 pTy with + | .error e => .error e + | .ok _ st2 => + let pTyInst := instantiateMVarsPure st2.mctx 32 pTy + let pTyW := whnfPure ctx st2 fuel pTyInst + let (pHead, pArgs) := getAppFnArgs pTyW + match pHead with + | .const pStructName pUnivs _ => + match st2.env.structTable.get? pStructName with + | some pInfo => + match st2.env.find? pInfo.ctorName with + | some (.ctorInfo pCval) => + let pCtorInstTy := pArgs.foldl (fun cur pa => + match stripMData cur with + | .forallE _ _ b _ _ => instantiate1 b pa + | other => other) (substExprLevelParams pCval.cnst.levelParams pUnivs pCval.cnst.type) + match elabParentFields pInfo.fields.toList pCtorInstTy fIdx fvars fInfos ctx st2 with + | .error e => .error e + | .ok (fIdx', fvars', fInfos', ctx') st3 => + elabParentsLoop restP fIdx' fvars' fInfos' (parentSpecs.push (pStructName, pUnivs, pArgs, pInfo)) ctx' st3 + | _ => + .error { pos? := (Syntax.getPos? pStx).orElse (fun _ => ctx.refPos?), msg := str% "missing constructor for parent structure" } + | none => + .error { pos? := (Syntax.getPos? pStx).orElse (fun _ => ctx.refPos?), msg := str% "parent in 'extends' is not a structure or class" } + | _ => + .error { pos? := (Syntax.getPos? pStx).orElse (fun _ => ctx.refPos?), msg := str% "parent in 'extends' must be a structure or class application" } + + let (fIdx0, fvars0, fInfos0, parentSpecs, ctxAfterParents) ← elabParentsLoop parentStxs 0 #[] #[] #[] + let (fieldFVars, fieldInfos, ctxAfterFields) ← withReader (fun _ => ctxAfterParents) (elabFieldLoop flatFields fIdx0 fvars0 fInfos0) + withReader (fun _ => ctxAfterFields) do + let indUnivs := lvlParams.map Level.mkParam + let paramExprs := paramFVars.map Expr.mkFVar + let retTy := Expr.mkAppN (Expr.mkConst decl.fullName indUnivs) paramExprs + let allFVars := paramFVars ++ fieldFVars + let ctorTy ← mkForallFVars allFVars retTy + let ctorTy ← instantiateMVars 32 ctorTy + let ctorTy := defaultUnassignedExprLevelMVars ctorTy + let ctxNow ← read + let bcs : Array Ixon.BinderContract := allFVars.filterMap fun fv => + (ctxNow.lctx.findFVar? fv).map (·.contract) + let cval : Ix.ConstructorVal := { + cnst := { + name := ctorFullName + levelParams := lvlParams + type := ctorTy + } + induct := decl.fullName + cidx := 0 + numParams := paramFVars.size + numFields := fieldFVars.size + isUnsafe := false + } + let sInfo : StructInfo := { + structName := decl.fullName + ctorName := ctorFullName + numParams := paramFVars.size + fields := fieldInfos + parents := parentSpecs.map (fun (pn, _, _, _) => pn) + isClass := decl.kind == .cls + } + -- Build `.to` projection functions for each parent in `parentSpecs` + let selfBi : Lean.BinderInfo := if decl.kind == .cls then .instImplicit else .default + let rec buildToParentDefs : + List (Ix.Name × Array Ix.Level × Array Ix.Expr × StructInfo) → + List Ix.DefinitionVal → IxElabM (Array Ix.DefinitionVal) + | [], revOut => pure (Array.mk revOut.reverse) + | (pName, pUnivs, pArgs, pInfo) :: restPS, revOut => do + let basePName := (Name.conflictOrigName? pName).getD pName + let pShort := (Name.components basePName).getLastD (str% "") + let toParentName := Name.mkStr decl.fullName (Sym.toString (Sym.append (s% "to") (Sym.ofString pShort))) + let pRetTy := Expr.mkAppN (Expr.mkConst pName pUnivs) pArgs + let (tpTy, tpVal) ← withLocalDecl (Name.simple (str% "self")) retTy selfBi default fun selfFvId selfExpr => do + let ctorCall := pInfo.fields.toList.foldl (fun acc pf => + let cIdx := (fieldInfos.find? (fun cf => cf.fieldName == pf.fieldName)).map (·.fieldIdx) |>.getD 0 + Expr.mkApp acc (Expr.mkProj decl.fullName cIdx selfExpr)) + (Expr.mkAppN (Expr.mkConst pInfo.ctorName pUnivs) pArgs) + let fnTy ← mkForallFVars (paramFVars.push selfFvId) pRetTy + let fnVal ← mkLambdaFVars (paramFVars.push selfFvId) ctorCall + let fnTy ← instantiateMVars 32 fnTy + let fnVal ← instantiateMVars 32 fnVal + pure (defaultUnassignedExprLevelMVars fnTy, defaultUnassignedExprLevelMVars fnVal) + let tpDef : Ix.DefinitionVal := { + cnst := { name := toParentName, levelParams := lvlParams, type := tpTy } + value := tpVal + hints := .abbrev + safety := .safe + all := #[toParentName] + } + buildToParentDefs restPS (tpDef :: revOut) + let toParentDefs ← buildToParentDefs parentSpecs.toList [] + return (cval, sInfo, bcs, toParentDefs) + +/-- Synthesize and register derived typeclass instances (`deriving Inhabited, BEq, DecidableEq`) + for an elaborated `inductive` or `structure`. -/ +def elabDerivingHandlersWith (elabTermFn : Nat → Stx → Option Ix.Expr → IxElabM Ix.Expr) + (decl : ModuleDecl) (ival : Ix.InductiveVal) (fuel : Nat := 128) : IxElabM Unit := do + let cmd := decl.stx + let k := Syntax.getKind cmd + let derivNode := + if k == SyntaxKind.inductiveDecl then Syntax.getArg cmd 8 + else Syntax.getArg cmd 10 + let derivIds := (Syntax.getArgs derivNode).toList.map Syntax.getId + if derivIds.isEmpty then return () + let shortDecl := (Name.components decl.fullName).getLastD (Name.toStringTotal decl.fullName) + let indUnivs := ival.cnst.levelParams.map Level.mkParam + let (paramFVars, paramDecls, _) := openForallTelescope ival.numParams ival.cnst.type (str% "dp") 0 #[] #[] + let indApplied := Expr.mkAppN (Expr.mkConst decl.fullName indUnivs) paramFVars + let paramImpDecls := paramDecls.map fun d => { d with binderInfo := .implicit } + + let rec collectParamInstDecls (clsStr : String) (pfxStr : String) (bdrPfx : String) : + List AuxLocalDecl → Nat → List AuxLocalDecl → Array AuxLocalDecl + | [], _, revAcc => Array.mk revAcc.reverse + | pDecl :: rest, pIdx, revAcc => + let (pSortHead, _) := getAppFnArgs pDecl.domain + match pSortHead with + | .sort u _ => + let uPred := match u with | .succ p _ => p | _ => Level.mkZero + let (iFvId, _) := mkAuxFVar pfxStr pIdx + let iDom := Expr.mkApp (Expr.mkConst (Name.simple clsStr) #[uPred]) (paramFVars.getD pIdx indApplied) + let d : AuxLocalDecl := { fvarId := iFvId, binderName := Name.mkNat (Name.simple bdrPfx) pIdx, domain := iDom, binderInfo := .instImplicit } + collectParamInstDecls clsStr pfxStr bdrPfx rest (pIdx + 1) (d :: revAcc) + | _ => + collectParamInstDecls clsStr pfxStr bdrPfx rest (pIdx + 1) revAcc + + let rec fillInhFields : Nat → Ix.Expr → Ix.Expr → IxElabM Ix.Expr + | 0, curFn, _ => pure curFn + | rem + 1, curFn, curTy => do + let curW ← whnf fuel curTy + match stripMData curW with + | .forallE _ fDom fBody _ _ => + let defTerm ← elabTermFn fuel (Syntax.mkSimpleIdent (Name.simple (str% "default"))) (some fDom) + fillInhFields rem (Expr.mkApp curFn defTerm) (instantiate1 fBody defTerm) + | _ => fillInhFields rem curFn curTy + + let rec buildBeqFieldConj (aFieldFVars bFieldFVars : Array Ix.Expr) + (aFieldDecls : Array AuxLocalDecl) (aDecl : AuxLocalDecl) (trueConst : Ix.Expr) : + Nat → Nat → Option Ix.Expr → IxElabM Ix.Expr + | 0, _, eqConj => instantiateMVars 32 (eqConj.getD trueConst) + | rem + 1, fIdx, eqConj => do + let lhsF := aFieldFVars.getD fIdx trueConst + let rhsF := bFieldFVars.getD fIdx trueConst + let fDom := (aFieldDecls.getD fIdx aDecl).domain + let beqGoal := Expr.mkApp (Expr.mkConst (Name.simple (str% "BEq")) #[Level.mkZero]) fDom + let instExpr ← match ← synthInstance? 8 beqGoal with + | some ie => pure ie + | none => pure (Expr.mkConst (Name.simple (str% "instBEqNat")) #[]) + let fEq := Expr.mkAppN (Expr.mkConst (Name.mkStr2 (str% "BEq") (str% "beq")) #[Level.mkZero]) #[fDom, instExpr, lhsF, rhsF] + let eqConj' := match eqConj with + | none => some fEq + | some prev => some (Expr.mkAppN (Expr.mkConst (Name.simple (str% "and")) #[]) #[prev, fEq]) + buildBeqFieldConj aFieldFVars bFieldFVars aFieldDecls aDecl trueConst rem (fIdx + 1) eqConj' + + let rec runDerivIds : List Ix.Name → IxElabM Unit + | [] => pure () + | clsId :: restCls => do + -- 1. `deriving Inhabited` + if clsId == Name.simple (str% "Inhabited") then + let st ← get + if let some ctorName := ival.ctors[0]? then + if let some (.ctorInfo cval) := st.env.find? ctorName then + let instDecls := collectParamInstDecls (str% "Inhabited") (str% "dinh") (str% "inst_") paramDecls.toList 0 [] + let allHdrDecls := paramImpDecls ++ instDecls + let lctxHdr := allHdrDecls.foldl (fun lc d => + lc.addDecl { fvarId := d.fvarId, userName := d.binderName, type := d.domain, binderInfo := d.binderInfo }) LocalContext.empty + let ctorInstTy := paramFVars.foldl (fun cur p => + match stripMData cur with + | .forallE _ _ b _ _ => instantiate1 b p + | other => other) (substExprLevelParams cval.cnst.levelParams indUnivs cval.cnst.type) + let defaultVal ← withReader (fun ctx => { ctx with lctx := lctxHdr, scope := decl.scope, univParams := ival.cnst.levelParams.toList }) do + let curFn ← fillInhFields cval.numFields (Expr.mkAppN (Expr.mkConst ctorName indUnivs) paramFVars) ctorInstTy + instantiateMVars 32 curFn + let inhZero := Level.mkZero + let instRetTy := Expr.mkApp (Expr.mkConst (Name.simple (str% "Inhabited")) #[inhZero]) indApplied + let instBody := Expr.mkAppN (Expr.mkConst (Name.mkStr2 (str% "Inhabited") (str% "mk")) #[inhZero]) #[indApplied, defaultVal] + let instFullTy := defaultUnassignedExprLevelMVars (closeForalls allHdrDecls instRetTy) + let instFullVal := defaultUnassignedExprLevelMVars (closeLambdas allHdrDecls instBody) + let instName := Name.fromComponents ((Name.components decl.fullName).dropLast ++ [strAppendPure (str% "instInhabited") shortDecl]) + modifyEnv fun env => + let env := env.addConst (.defnInfo { + cnst := { name := instName, levelParams := ival.cnst.levelParams, type := instFullTy } + value := instFullVal, hints := .abbrev, safety := .safe, all := #[instName] + }) + env.addInstance { instName := instName, className := Name.simple (str% "Inhabited") } + -- 2. `deriving BEq` (and `DecidableEq`) + else if clsId == Name.simple (str% "BEq") || clsId == Name.simple (str% "DecidableEq") then + let st ← get + let casesOnName := Name.mkStr decl.fullName (str% "casesOn") + if let some (.defnInfo casesOnDef) := st.env.find? casesOnName then + let instDecls := collectParamInstDecls (str% "BEq") (str% "dbeq") (str% "instBEq_") paramDecls.toList 0 [] + let (aFvId, aFvExpr) := mkAuxFVar (str% "dbeq_a") 0 + let (bFvId, bFvExpr) := mkAuxFVar (str% "dbeq_b") 1 + let aDecl : AuxLocalDecl := { fvarId := aFvId, binderName := Name.simple (str% "a"), domain := indApplied } + let bDecl : AuxLocalDecl := { fvarId := bFvId, binderName := Name.simple (str% "b"), domain := indApplied } + let allHdrDecls := paramImpDecls ++ instDecls + let boolConst := Expr.mkConst (Name.simple (str% "Bool")) #[] + let trueConst := Expr.mkConst (Name.mkStr2 (str% "Bool") (str% "true")) #[] + let falseConst := Expr.mkConst (Name.mkStr2 (str% "Bool") (str% "false")) #[] + let casesOnUnivs := + if casesOnDef.cnst.levelParams.size == indUnivs.size + 1 then + #[Level.mkSucc Level.mkZero] ++ indUnivs + else indUnivs + let motive := Expr.mkLam (Name.simple (str% "_")) indApplied boolConst .default + let rec buildInnerMinors (idxA : Nat) (cvalA : Ix.ConstructorVal) + (aFieldFVars : Array Ix.Expr) (aFieldDecls : Array AuxLocalDecl) : + List Ix.Name → Nat → List Ix.Expr → IxElabM (Array Ix.Expr) + | [], _, revAcc => pure (Array.mk revAcc.reverse) + | ctorB :: restB, idxB, revAcc => do + match st.env.find? ctorB with + | some (.ctorInfo cvalB) => + let ctorBTy := paramFVars.foldl (fun cur p => + match stripMData cur with + | .forallE _ _ b _ _ => instantiate1 b p + | other => other) (substExprLevelParams cvalB.cnst.levelParams indUnivs cvalB.cnst.type) + let (bFieldFVars, bFieldDecls, _) := openForallTelescope cvalB.numFields ctorBTy (str% "dfb") (idxB * 64) #[] #[] + let innerM ← + if idxA != idxB then pure (closeLambdas bFieldDecls falseConst) + else if cvalA.numFields == 0 then pure (closeLambdas bFieldDecls trueConst) + else + let branchDecls := allHdrDecls ++ #[aDecl, bDecl] ++ aFieldDecls ++ bFieldDecls + let lctxBranch := branchDecls.foldl (fun lc d => + lc.addDecl { fvarId := d.fvarId, userName := d.binderName, type := d.domain, binderInfo := d.binderInfo }) LocalContext.empty + let cmpExpr ← withReader (fun ctx => { ctx with lctx := lctxBranch, scope := decl.scope, univParams := ival.cnst.levelParams.toList }) + (buildBeqFieldConj aFieldFVars bFieldFVars aFieldDecls aDecl trueConst cvalA.numFields 0 none) + pure (closeLambdas bFieldDecls cmpExpr) + buildInnerMinors idxA cvalA aFieldFVars aFieldDecls restB (idxB + 1) (innerM :: revAcc) + | _ => buildInnerMinors idxA cvalA aFieldFVars aFieldDecls restB (idxB + 1) revAcc + let rec buildOuterMinors : List Ix.Name → Nat → List Ix.Expr → IxElabM (Array Ix.Expr) + | [], _, revAcc => pure (Array.mk revAcc.reverse) + | ctorA :: restA, idxA, revAcc => do + match st.env.find? ctorA with + | some (.ctorInfo cvalA) => + let ctorATy := paramFVars.foldl (fun cur p => + match stripMData cur with + | .forallE _ _ b _ _ => instantiate1 b p + | other => other) (substExprLevelParams cvalA.cnst.levelParams indUnivs cvalA.cnst.type) + let (aFieldFVars, aFieldDecls, _) := openForallTelescope cvalA.numFields ctorATy (str% "dfa") (idxA * 64) #[] #[] + let innerMinors ← buildInnerMinors idxA cvalA aFieldFVars aFieldDecls ival.ctors.toList 0 [] + let innerCases := Expr.mkAppN (Expr.mkConst casesOnName casesOnUnivs) + (paramFVars ++ #[motive, bFvExpr] ++ innerMinors) + buildOuterMinors restA (idxA + 1) (closeLambdas aFieldDecls innerCases :: revAcc) + | _ => buildOuterMinors restA (idxA + 1) revAcc + let outerMinors ← buildOuterMinors ival.ctors.toList 0 [] + let outerCases := Expr.mkAppN (Expr.mkConst casesOnName casesOnUnivs) + (paramFVars ++ #[motive, aFvExpr] ++ outerMinors) + let beqLam := closeLambdas #[aDecl, bDecl] outerCases + let beqZero := Level.mkZero + let instRetTy := Expr.mkApp (Expr.mkConst (Name.simple (str% "BEq")) #[beqZero]) indApplied + let instBody := Expr.mkAppN (Expr.mkConst (Name.mkStr2 (str% "BEq") (str% "mk")) #[beqZero]) #[indApplied, beqLam] + let instFullTy := defaultUnassignedExprLevelMVars (closeForalls allHdrDecls instRetTy) + let instFullVal := defaultUnassignedExprLevelMVars (closeLambdas allHdrDecls instBody) + let instName := Name.fromComponents ((Name.components decl.fullName).dropLast ++ [strAppendPure (str% "instBEq") shortDecl]) + modifyEnv fun env => + let env := env.addConst (.defnInfo { + cnst := { name := instName, levelParams := ival.cnst.levelParams, type := instFullTy } + value := instFullVal, hints := .abbrev, safety := .safe, all := #[instName] + }) + env.addInstance { instName := instName, className := Name.simple (str% "BEq") } + runDerivIds restCls + + runDerivIds derivIds + +/-- Elaborate an inductive/structure/class SCC, canonicalize its block & constructor order, + and generate surgery-free recursors and auxiliary definitions. -/ +def elabInductiveSCCWith (elabTermFn : Nat → Stx → Option Ix.Expr → IxElabM Ix.Expr) + (decls : Array ModuleDecl) (fuel : Nat := 128) : IxElabM Unit := do + -- Step 1: Elaborate headers and pre-register temporary `InductiveVal`s in `st.env` + let allNames := decls.map (·.fullName) + let rec elabHeadersLoop : List ModuleDecl → + List (ModuleDecl × Nat × Nat × Array Ix.Name × Ix.Expr) → + IxElabM (Array (ModuleDecl × Nat × Nat × Array Ix.Name × Ix.Expr)) + | [], revH => pure (Array.mk revH.reverse) + | decl :: rest, revH => do + let (nParams, nIndices, lvlParams, indType) ← elabInductiveHeaderWith elabTermFn decl fuel + let tempIndVal : Ix.InductiveVal := { + cnst := { name := decl.fullName, levelParams := lvlParams, type := indType } + numParams := nParams, numIndices := nIndices, all := allNames + ctors := Array.mk decl.ctorNames, numNested := 0 + isRec := false, isUnsafe := false, isReflexive := false + } + modifyEnv (·.addConst (.inductInfo tempIndVal)) + elabHeadersLoop rest ((decl, nParams, nIndices, lvlParams, indType) :: revH) + let headers ← elabHeadersLoop decls.toList [] + + -- Step 2: Elaborate constructors / structure fields for each inductive in the SCC + let indNameSet : NameSet := allNames.foldl (fun s n => s.insert n) NameSet.empty + let rec elabCtorsList (decl : ModuleDecl) (lvlParams : Array Ix.Name) + (paramGroups : List ParsedBinderGroup) : + List Stx → Nat → List Ix.ConstructorVal → IxElabM (Array Ix.ConstructorVal) + | [], _, revCs => pure (Array.mk revCs.reverse) + | ctorStx :: rest, cidx, revCs => do + let (cval, bcs, retC) ← elabOneConstructorWith elabTermFn decl lvlParams paramGroups ctorStx cidx fuel + modifyEnv (·.addContracts cval.cnst.name bcs retC) + elabCtorsList decl lvlParams paramGroups rest (cidx + 1) (cval :: revCs) + + let rec elabBodiesLoop : + List (ModuleDecl × Nat × Nat × Array Ix.Name × Ix.Expr) → + List (Ix.InductiveVal × Array Ix.ConstructorVal) → + List (Ix.InductiveVal × Ix.ConstructorVal × StructInfo × Array Ix.DefinitionVal) → + IxElabM (Array (Ix.InductiveVal × Array Ix.ConstructorVal) × + Array (Ix.InductiveVal × Ix.ConstructorVal × StructInfo × Array Ix.DefinitionVal)) + | [], revRaw, revStructs => pure (Array.mk revRaw.reverse, Array.mk revStructs.reverse) + | (decl, nParams, nIndices, lvlParams, indType) :: rest, revRaw, revStructs => do + let cmd := decl.stx + let k := Syntax.getKind cmd + let optTypeNode := + if k == SyntaxKind.inductiveDecl then Syntax.getArg cmd 6 + else Syntax.getArg cmd 7 + let varGroups := decl.scope.varBinders.toList.map decodeBinderNode + let rawParamGroups := (Syntax.getArgs (Syntax.getArg cmd 4)).toList.map decodeBinderNode + let ctxNow ← read + let stNow ← get + let autoGroups := collectAutoImplicitGroups decl.scope ctxNow.modIdx stNow.env varGroups rawParamGroups optTypeNode + let paramGroups := varGroups ++ autoGroups ++ rawParamGroups + if k == SyntaxKind.inductiveDecl then + let ctorsNode := Syntax.getArg cmd 7 + let ctorStxs := Syntax.getArgs ctorsNode + let ctors ← elabCtorsList decl lvlParams paramGroups ctorStxs.toList 0 [] + let isRec := ctors.any fun cv => + let (_, fieldDecls, _) := openForallTelescope (cv.numParams + cv.numFields) cv.cnst.type (str% "rc") 0 #[] #[] + (fieldDecls.extract cv.numParams fieldDecls.size).any fun fd => + !(collectRefsInSet indNameSet fd.domain).isEmpty + let indVal : Ix.InductiveVal := { + cnst := { name := decl.fullName, levelParams := lvlParams, type := indType } + numParams := nParams, numIndices := nIndices, all := allNames + ctors := ctors.map (·.cnst.name), numNested := 0 + isRec := isRec, isUnsafe := false, isReflexive := false + } + elabBodiesLoop rest ((indVal, ctors) :: revRaw) revStructs + else + let fieldsOrCtorsNode := Syntax.getArg cmd 9 + let children := Syntax.getArgs fieldsOrCtorsNode + let isCtorStyleClass : Bool := match children[0]? with + | some c0 => Syntax.isOfKind c0 SyntaxKind.ctorDecl + | none => false + if isCtorStyleClass == true then + let ctors ← elabCtorsList decl lvlParams paramGroups children.toList 0 [] + let isRec := ctors.any fun cv => + let (_, fieldDecls, _) := openForallTelescope (cv.numParams + cv.numFields) cv.cnst.type (str% "rc") 0 #[] #[] + (fieldDecls.extract cv.numParams fieldDecls.size).any fun fd => + !(collectRefsInSet indNameSet fd.domain).isEmpty + let indVal : Ix.InductiveVal := { + cnst := { name := decl.fullName, levelParams := lvlParams, type := indType } + numParams := nParams, numIndices := nIndices, all := allNames + ctors := ctors.map (·.cnst.name), numNested := 0 + isRec := isRec, isUnsafe := false, isReflexive := false + } + if decl.kind == .cls then + modifyEnv fun env => { env with classSet := env.classSet.insert decl.fullName } + elabBodiesLoop rest ((indVal, ctors) :: revRaw) revStructs + else + let ctorFullName := decl.ctorNames.headD (Name.mkStr decl.fullName (str% "mk")) + let (cval, sInfo, bcs, toParentDefs) ← elabStructureFieldsWith elabTermFn decl lvlParams paramGroups ctorFullName fieldsOrCtorsNode fuel + modifyEnv fun env => + let env := env.addContracts cval.cnst.name bcs .shared + env.addStructInfo sInfo + let indVal : Ix.InductiveVal := { + cnst := { name := decl.fullName, levelParams := lvlParams, type := indType } + numParams := nParams, numIndices := nIndices, all := allNames + ctors := #[cval.cnst.name], numNested := 0 + isRec := false, isUnsafe := false, isReflexive := false + } + elabBodiesLoop rest ((indVal, #[cval]) :: revRaw) ((indVal, cval, sInfo, toParentDefs) :: revStructs) + + let (rawItems, structToGenerate) ← elabBodiesLoop headers.toList [] [] + + -- Step 3: Canonicalize block member order & constructor order (breaking α-ties by source order!) + let stNow ← get + let canonItems := canonicalizeInductiveBlock stNow.env.importMap rawItems + + -- Step 4: Register canonical `InductiveVal`s, `ConstructorVal`s, and surgery-free `.rec`, `.recOn`, `.casesOn`, `._ctorIdx` + modifyEnv fun env => registerCanonicalInductiveBlock env canonItems + + -- Step 5: Generate and register structure/class field projection functions and `.to` coercions + let rec registerStructsLoop : + List (Ix.InductiveVal × Ix.ConstructorVal × StructInfo × Array Ix.DefinitionVal) → IxElabM Unit + | [] => pure () + | (iv, cv, sInfo, toParentDefs) :: rest => do + let projFieldNames := sInfo.fields.map (·.projFnName) + let projs := generateStructProjections iv cv projFieldNames sInfo.isClass + modifyEnv fun env => + let env := projs.foldl (fun acc p => acc.addConst (.defnInfo p)) env + let env := toParentDefs.foldl (fun acc tp => acc.addConst (.defnInfo tp)) env + if sInfo.isClass then + (sInfo.parents.zip toParentDefs).foldl (fun acc (pName, tpDef) => + if acc.classSet.contains pName then + acc.addInstance { instName := tpDef.cnst.name, className := pName } + else acc) env + else env + registerStructsLoop rest + registerStructsLoop structToGenerate.toList + + -- Step 6: Run `deriving` handlers (`Inhabited`, `BEq`, `DecidableEq`) + let rec runDerivingLoop : List (ModuleDecl × Nat × Nat × Array Ix.Name × Ix.Expr) → IxElabM Unit + | [] => pure () + | (decl, _, _, _, _) :: rest => do + let stAfter ← get + if let some (.inductInfo ival) := stAfter.env.find? decl.fullName then + elabDerivingHandlersWith elabTermFn decl ival fuel + runDerivingLoop rest + runDerivingLoop headers.toList + +def elabInductiveSCC (decls : Array ModuleDecl) (fuel : Nat := 128) : IxElabM Unit := + elabInductiveSCCWith elabTerm decls fuel + +/-! ## Value Declaration SCC Elaboration (`def`, `abbrev`, `theorem`, `opaque`, `axiom`, `instance`) -/ + +/-- Elaborate a strongly connected component of value/axiom declarations. -/ +def elabValueSCCWith (elabTermFn : Nat → Stx → Option Ix.Expr → IxElabM Ix.Expr) + (decls : Array ModuleDecl) (isRecursive : Bool := true) (fuel : Nat := 128) : IxElabM Unit := do + -- Step 1: Elaborate each declaration's signature and pre-register a temporary header + -- so recursive and mutually recursive references resolve during body elaboration. + -- (For a single non-recursive non-axiom declaration, skip Step 1 to avoid elaborating the signature twice!) + let rec elabSigsLoop : + List ModuleDecl → + List (ModuleDecl × Array Ix.Name × Ix.Expr × Array Ixon.BinderContract × Ixon.ValueContract) → + IxElabM (Array (ModuleDecl × Array Ix.Name × Ix.Expr × Array Ixon.BinderContract × Ixon.ValueContract)) + | [], revSigs => pure (Array.mk revSigs.reverse) + | decl :: rest, revSigs => do + let cmd := decl.stx + let vPrefNode := Syntax.getArg cmd 5 + let retContract := (decodeContractPrefix vPrefNode).toValueContract + if !isRecursive && decls.size == 1 && Syntax.getKind cmd != SyntaxKind.axiomDecl then + let initLvls := Array.mk (decl.univParams ++ decl.scope.levelNames).eraseDups + elabSigsLoop rest ((decl, initLvls, Expr.mkProp, #[], retContract) :: revSigs) + else + modify fun st => match st with | ⟨env, _, nextIdx, _, _⟩ => ⟨env, {}, nextIdx, [], #[]⟩ + let varGroups := decl.scope.varBinders.toList.map decodeBinderNode + let rawParamGroups := (Syntax.getArgs (Syntax.getArg cmd 4)).toList.map decodeBinderNode + let optTypeNode := Syntax.getArg cmd 6 + let ctx0 ← read + let st0 ← get + let optTypeExpanded := + if st0.env.macroRules.isEmpty then optTypeNode + else expandTopMacroPure 8 st0.env.macroRules optTypeNode + let autoGroups := collectAutoImplicitGroups decl.scope ctx0.modIdx st0.env varGroups rawParamGroups optTypeExpanded + let paramGroups := varGroups ++ autoGroups ++ rawParamGroups + + let (lvlParams, fullType, bcs) ← withReader (fun ctx => { ctx with + lctx := LocalContext.empty + scope := decl.scope + currDecl? := some decl.fullName + univParams := decl.univParams }) do + elabBinderGroups (fun s exp? => elabTermFn fuel s exp?) paramGroups #[] fun paramFVars => do + let retTy ← + if Syntax.isNone optTypeNode || Syntax.isMissing optTypeNode then + let u ← mkFreshLevelMVar + mkFreshExprMVar (Expr.mkSort u) + else + let t ← elabTermFn fuel optTypeNode none + let _ ← ensureSortIfNotForall 32 t + instantiateMVars 32 t + let piTy ← mkForallFVars paramFVars retTy retContract + let piTy ← instantiateMVars 32 piTy + let ctxNow ← read + let bcs : Array Ixon.BinderContract := Array.mk <| paramFVars.toList.filterMap fun fv => + (ctxNow.lctx.findFVar? fv).map (·.contract) + let stNow ← get + let lvls := Array.mk (decl.univParams ++ decl.scope.levelNames ++ stNow.autoBoundUnivs).eraseDups + return (lvls, piTy, bcs) + + -- Pre-register temporary `.axiomInfo` header for recursive calls (or final `.axiomInfo` for `axiom`) + let tempAx : Ix.AxiomVal := { + cnst := { name := decl.fullName, levelParams := lvlParams, type := defaultUnassignedExprLevelMVars fullType } + isUnsafe := false + } + modifyEnv (·.addConst (.axiomInfo tempAx)) + elabSigsLoop rest ((decl, lvlParams, fullType, bcs, retContract) :: revSigs) + + let sigInfos ← elabSigsLoop decls.toList [] + + -- Step 2: Elaborate bodies for all non-axiom declarations in the SCC + let rec elabValueBodiesLoop : + List (ModuleDecl × Array Ix.Name × Ix.Expr × Array Ixon.BinderContract × Ixon.ValueContract) → + List Ix.Def → IxElabM (Array Ix.Def) + | [], revDefs => pure (Array.mk revDefs.reverse) + | (decl, initLvlParams, _, _, retContract) :: rest, revDefs => do + let cmd := decl.stx + let k := Syntax.getKind cmd + let attrs := extractDeclAttributes (Syntax.getArg cmd 0) + if attrs.contains (Name.simple (str% "simp")) then + modifyEnv (·.addInstance { instName := decl.fullName, className := Name.mkStr2 (str% "_Ix") (str% "simpLemma") }) + if k == SyntaxKind.axiomDecl then + elabValueBodiesLoop rest revDefs + else + modify fun st => match st with | ⟨env, _, nextIdx, _, _⟩ => ⟨env, {}, nextIdx, initLvlParams.toList, #[]⟩ + let varGroups := decl.scope.varBinders.toList.map decodeBinderNode + let rawParamBinders := (Syntax.getArgs (Syntax.getArg cmd 4)).toList.map decodeBinderNode + let optTypeNode := Syntax.getArg cmd 6 + let ctx0 ← read + let st0 ← get + let optTypeExpanded := + if st0.env.macroRules.isEmpty then optTypeNode + else expandTopMacroPure 8 st0.env.macroRules optTypeNode + let autoGroups := collectAutoImplicitGroups decl.scope ctx0.modIdx st0.env varGroups rawParamBinders optTypeExpanded + let paramGroups := varGroups ++ autoGroups ++ rawParamBinders + + let (finalLvls, finalType, finalVal, finalBcs, finalLcs) ← withReader (fun ctx => { ctx with + lctx := LocalContext.empty + scope := decl.scope + currDecl? := some decl.fullName + univParams := initLvlParams.toList }) do + elabBinderGroups (fun s exp? => elabTermFn fuel s exp?) paramGroups #[] fun paramFVars => do + let expRetTy? ← + if Syntax.isNone optTypeNode || Syntax.isMissing optTypeNode then + pure none + else + let t ← elabTermFn fuel optTypeNode none + let _ ← ensureSortIfNotForall 32 t + let tInst ← instantiateMVars 32 t + pure (some tInst) + + let (bodyExpr, bodyRetTy, extraFVars) ← + if k == SyntaxKind.instanceDecl && Syntax.getAtomVal (Syntax.getArg cmd 7) == (str% "where") then + let fieldAssigns := Syntax.getArgs (Syntax.getArg cmd 8) + let normAssigns := fieldAssigns.map fun fa => + let fId := Syntax.getArg fa 0 + let fBinders := Syntax.getArg fa 1 + let fRhs := Syntax.getArg fa 3 + let rhsTerm := + if (Syntax.getArgs fBinders).isEmpty then fRhs + else Syntax.mkNode SyntaxKind.funTerm #[Syntax.mkSimpleAtom (str% "fun"), fBinders, Syntax.mkSimpleAtom (str% "=>"), fRhs] + Syntax.mkNode SyntaxKind.structFieldAssign #[fId, Syntax.mkSimpleAtom (str% ":="), rhsTerm] + let structLit := Syntax.mkNode SyntaxKind.structInst + #[Syntax.mkSimpleAtom (str% "{"), Syntax.mkNullNode #[], Syntax.mkNullNode normAssigns, Syntax.mkSimpleAtom (str% "}")] + let val ← elabTermFn fuel structLit expRetTy? + let rTy ← match expRetTy? with | some t => pure t | none => inferType fuel val + pure (val, rTy, #[]) + else if Syntax.getNumArgs cmd == 8 && k != SyntaxKind.axiomDecl then + let altsNode := Syntax.getArg cmd 7 + let ctxNow ← read + let rec stxMentions (nm : Ix.Name) (fuelM : Nat) (s : Stx) : Bool := + match fuelM with + | 0 => false + | f + 1 => + match s with + | .ident _ _ idF => FName.toIxName idF == nm + | .node _ _ as => as.any (stxMentions nm f) + | _ => false + let targetFvId? := + (paramFVars.find? fun fvId => + match ctxNow.lctx.findFVar? fvId with + | some d => d.binderInfo == .default && !stxMentions d.userName 64 altsNode + | none => false).orElse (fun _ => paramFVars.back?) + match targetFvId? with + | some lastFvId => + let lastName := match ctxNow.lctx.findFVar? lastFvId with + | some d => d.userName + | none => Name.simple (str% "x") + let discrIdent := Syntax.mkSimpleIdent lastName + let matchStx := Syntax.mkNode SyntaxKind.matchTerm + #[Syntax.mkSimpleAtom (str% "match"), Syntax.mkNullNode #[discrIdent], + Syntax.mkSimpleAtom (str% "with"), altsNode] + let val ← elabTermFn fuel matchStx expRetTy? + let rTy ← match expRetTy? with | some t => pure t | none => inferType fuel val + pure (val, rTy, #[]) + | none => + match expRetTy? with + | some rTy => + let rTyW ← whnf fuel rTy + match stripMData rTyW with + | .forallE _ dom cod bi _ => + let discrName := Name.simple (str% "_x") + withLocalDecl discrName dom bi default fun fvId fvExpr => do + let codInst := instantiate1 cod fvExpr + let matchStx := Syntax.mkNode SyntaxKind.matchTerm + #[Syntax.mkSimpleAtom (str% "match"), Syntax.mkNullNode #[Syntax.mkSimpleIdent discrName], + Syntax.mkSimpleAtom (str% "with"), altsNode] + let val ← elabTermFn fuel matchStx (some codInst) + let lamVal ← mkLambdaFVars #[fvId] val + let piTy ← mkForallFVars #[fvId] codInst + pure (lamVal, piTy, #[]) + | _ => throwElabError "pattern-matching definition requires a parameter or function return type" (some cmd) + | none => throwElabError "pattern-matching definition requires a parameter or type signature" (some cmd) + else + let bodyStx := Syntax.getArg cmd 8 + let val ← elabTermFn fuel bodyStx expRetTy? + let rTy ← match expRetTy? with | some t => pure t | none => inferType fuel val + pure (val, rTy, #[]) + + let allParamFVars := paramFVars ++ extraFVars + let fullTy ← mkForallFVars allParamFVars bodyRetTy retContract + let fullVal ← mkLambdaFVars allParamFVars bodyExpr + let fullTy ← instantiateMVars 32 fullTy + let fullVal ← instantiateMVars 32 fullVal + let fullTy := defaultUnassignedExprLevelMVars fullTy + let fullVal := defaultUnassignedExprLevelMVars fullVal + let ctxNow ← read + let bcs : Array Ixon.BinderContract := Array.mk <| allParamFVars.toList.filterMap fun fv => + (ctxNow.lctx.findFVar? fv).map (·.contract) + let stNow ← get + let lvls := Array.mk (decl.univParams ++ decl.scope.levelNames ++ stNow.autoBoundUnivs).eraseDups + return (lvls, fullTy, fullVal, bcs, stNow.localLetContracts) + + -- If this is a single recursive definition, try lowering structural `casesOn` self-recursion to `recOn` + let stNow ← get + let finalVal := + if isRecursive && decls.size == 1 then tryLowerStructuralRecToRecOn stNow.env decl.fullName finalVal + else finalVal + + modifyEnv (·.addContracts decl.fullName finalBcs retContract finalLcs) + + -- If `decl.kind == .inst` or `@[instance]`, register in `st.env.instances` + if decl.kind == .inst || attrs.contains (Name.simple (str% "instance")) then + let (_, _, retBody) := openForallTelescope (countForalls 64 finalType) finalType (str% "inst") 0 #[] #[] + let (headClass, _) := getAppFnArgs retBody + if let .const className _ _ := headClass then + modifyEnv (·.addInstance { instName := decl.fullName, className }) + + let defKind : Ix.DefKind := + if decl.kind == .thm then .thm + else if decl.kind == .opaqueDecl then .opaq + else .defn + let hints : Lean.ReducibilityHints := + if decl.kind == .abbrev || attrs.contains (Name.simple (str% "reducible")) || attrs.contains (Name.simple (str% "inline")) then .abbrev + else if decl.kind == .thm || decl.kind == .opaqueDecl || attrs.contains (Name.simple (str% "irreducible")) then .opaque + else .regular 1 + let dItem : Ix.Def := { + name := decl.fullName + levelParams := finalLvls + type := finalType + kind := defKind + value := finalVal + hints := hints + safety := .safe + all := #[decl.fullName] + } + elabValueBodiesLoop rest (dItem :: revDefs) + + let elabbedDefs ← elabValueBodiesLoop sigInfos.toList [] + + -- Step 3: Split into minimal post-elaboration SCCs and canonicalize mutual definition blocks! + if !elabbedDefs.isEmpty then + let stNow ← get + let canonSccs := canonicalizeElaboratedDefs stNow.env.importMap elabbedDefs + let rec addCanonDefs : List Ix.Def → IxElabM Unit + | [] => pure () + | d :: rest => do + let ci : Ix.ConstantInfo := match d.kind with + | .thm => .thmInfo { + cnst := { name := d.name, levelParams := d.levelParams, type := d.type } + value := d.value + all := d.all + } + | .opaq => .opaqueInfo { + cnst := { name := d.name, levelParams := d.levelParams, type := d.type } + value := d.value + isUnsafe := false + all := d.all + } + | .defn => .defnInfo { + cnst := { name := d.name, levelParams := d.levelParams, type := d.type } + value := d.value + hints := d.hints + safety := .safe + all := d.all + } + modifyEnv (·.addConst ci) + addCanonDefs rest + let rec addCanonSccs : List (Array Ix.Def) → IxElabM Unit + | [] => pure () + | sccDefs :: rest => do + addCanonDefs sccDefs.toList + addCanonSccs rest + addCanonSccs canonSccs.toList + +def elabValueSCC (decls : Array ModuleDecl) (isRecursive : Bool := true) (fuel : Nat := 128) : IxElabM Unit := + elabValueSCCWith elabTerm decls isRecursive fuel + +/-! ## Whole-Module Elaboration Entry Points -/ + +/-- Elaborate a `ModuleSchedule` (produced by Pass 1 + Pass 2 + Pass 3) into an `IxElabEnv`. -/ +def elabModuleScheduleWith (elabTermFn : Nat → Stx → Option Ix.Expr → IxElabM Ix.Expr) + (sched : ModuleSchedule) + (initEnv : IxElabEnv := IxElabEnv.empty) + (seedPrelude : Bool := true) : Except ElabError IxElabEnv := do + let baseEnv := initEnv.withImportMap (initEnv.importMap.merge sched.modIdx.importMap) + let baseEnv := baseEnv.addMacroRules sched.modIdx.macroRules.toList + let baseEnv := if seedPrelude then seedCorePreludeIfMissing baseEnv sched.modIdx else baseEnv + baseEnv.bindEnv fun baseEnv' => do + let initState : ElabState := { env := baseEnv' } + let initCtx : ElabContext := { modIdx := sched.modIdx } + let declList := sched.modIdx.decls.toList + let rec runSccs : List ScheduledSCC → IxElabM Unit + | [] => pure () + | scc :: rest => do + let sccDecls := Array.mk (scc.declIdxs.toList.filterMap fun idx => Syntax.listGet? declList idx) + if !sccDecls.isEmpty then + let allInd := sccDecls.toList.all fun d => d.kind == .ind || d.kind == .struct || d.kind == .cls + if allInd then + elabInductiveSCCWith elabTermFn sccDecls 128 + else + elabValueSCCWith elabTermFn sccDecls (scc.kind != .singleNonRec) 128 + runSccs rest + let (_, finalState) ← IxElabM.run (runSccs sched.sccs.toList) initCtx initState + return finalState.env + +def elabModuleSchedule (sched : ModuleSchedule) + (initEnv : IxElabEnv := IxElabEnv.empty) + (seedPrelude : Bool := true) : Except ElabError IxElabEnv := + elabModuleScheduleWith elabTerm sched initEnv seedPrelude + +/-- Elaborate a parsed `Stx` module AST (`SyntaxKind.moduleKind`) into an `IxElabEnv`. -/ +def elabModuleSyntaxWith (elabTermFn : Nat → Stx → Option Ix.Expr → IxElabM Ix.Expr) + (moduleStx : Stx) + (initEnv : IxElabEnv := IxElabEnv.empty) + (seedPrelude : Bool := true) : Except String IxElabEnv := do + let modIdx ← buildModuleIndex moduleStx + let baseEnv := if seedPrelude then seedCorePreludeIfMissing initEnv modIdx else initEnv + baseEnv.bindEnv fun baseEnv' => do + let sched ← scheduleModuleDecls modIdx + (fun n => baseEnv'.contains n) + (fun n => baseEnv'.isCtor n) + match elabModuleScheduleWith elabTermFn sched baseEnv' false with + | .ok env => return env + | .error e => throw e.msg + +def elabModuleSyntax (moduleStx : Stx) + (initEnv : IxElabEnv := IxElabEnv.empty) + (seedPrelude : Bool := true) : Except String IxElabEnv := + elabModuleSyntaxWith elabTerm moduleStx initEnv seedPrelude + +/-- Core module elaborator for ZK circuits: elaborates all declarations, structures, + inductives, recursors, pattern matches, typeclasses, universes, and contracts + without pulling in the heavy tactic engine (`Elab/Tactic.lean`). -/ +def elabModuleSyntaxCore (moduleStx : Stx) + (initEnv : IxElabEnv := IxElabEnv.empty) + (seedPrelude : Bool := true) : Except String IxElabEnv := + elabModuleSyntaxWith elabTermCore moduleStx initEnv seedPrelude + +/-- Parse and elaborate a `.ix` / `.lean` source string into a pure `IxElabEnv` (zero `IO`). -/ +def elabSource (input : String) (fileName : String := (str% "")) + (initEnv : IxElabEnv := IxElabEnv.empty) + (seedPrelude : Bool := true) : Except String IxElabEnv := do + let (stx, _) ← parseModuleWithEnv input fileName + elabModuleSyntax stx initEnv seedPrelude + +/-! ## Track 2: Certificate-Guided Elaboration (`ElabHints` / `elabModuleWithHints`) -/ + +/-- Certificate hint for a single top-level declaration in `elabModuleWithHints`. + Supplies the candidate elaborated signature and body so the in-circuit elaborator + can verify structural alignment with the parsed `Stx` AST in `O(|stx|)` + without metavariable unification (`isDefEq`), `whnf`, or typeclass search (`synthInstance?`). -/ +structure DeclHint where + fullName : Ix.Name + levelParams : Array Ix.Name := #[] + type : Ix.Expr + value? : Option Ix.Expr := none + defKind : Ix.DefKind := .defn + hints : Lean.ReducibilityHints := .regular 1 + binderContracts : Array Ixon.BinderContract := #[] + retContract : Ixon.ValueContract := {} + letContracts : Array Ixon.LetContract := #[] + isInstance : Bool := false + className? : Option Ix.Name := none + isSimp : Bool := false + deriving Repr, BEq + +/-- Collection of declaration hints keyed by full declaration name. -/ +structure ElabHints where + declHints : NameMap DeclHint := NameMap.empty + +namespace ElabHints + +def empty : ElabHints := {} + +@[inline] def bindHints (h : ElabHints) (k : ElabHints → α) : α := + match h with + | ⟨declHints⟩ => declHints.bindMap fun dh' => k ⟨dh'⟩ + +def insert (h : ElabHints) (d : DeclHint) : ElabHints := + match h with + | ⟨declHints⟩ => (declHints.insert d.fullName d).bindMap fun dh' => ⟨dh'⟩ + +def find? (h : ElabHints) (nm : Ix.Name) : Option DeclHint := + h.declHints.get? nm + +end ElabHints + +/-- Lookup De Bruijn index of `nm` in `bvars` (`0` = innermost binder). -/ +def bvarIndexOf (nm : Ix.Name) : List Ix.Name → Nat → Option Nat + | [], _ => none + | b :: bs, idx => if b == nm then some idx else bvarIndexOf nm bs (idx + 1) + +/-- Extract the head constant name from a nested `.app` spine without allocating an array. -/ +def exprHeadConst? : Ix.Expr → Option Ix.Name + | .const nm _ _ => some nm + | .app f _ _ => exprHeadConst? f + | .mdata _ e _ => exprHeadConst? e + | _ => none + +/-- Peel the outermost two `.app` arguments `(fn, lhs, rhs)` without allocating an array. -/ +def peelApp2? : Ix.Expr → Option (Ix.Expr × Ix.Expr × Ix.Expr) + | .mdata _ e _ => peelApp2? e + | .app f rhs _ => + match stripMData f with + | .app fn lhs _ => some (fn, lhs, rhs) + | _ => none + | _ => none + +/-- Check whether `fn` has a valid constant head for binary operator symbol `sym`, + returning `(matchesHead, swappedArgs)`. -/ +def checkBinOpHead (sym : String) (fn : Ix.Expr) : Bool × Bool := + match exprHeadConst? fn with + | none => (false, false) + | some cName => + if sym == (str% "+") then + (cName == Name.mkStr2 (str% "HAdd") (str% "hAdd") || cName == Name.mkStr2 (str% "Add") (str% "add") || cName == Name.mkStr2 (str% "Nat") (str% "add"), false) + else if sym == (str% "-") then + (cName == Name.mkStr2 (str% "HSub") (str% "hSub") || cName == Name.mkStr2 (str% "Sub") (str% "sub") || cName == Name.mkStr2 (str% "Nat") (str% "sub"), false) + else if sym == (str% "*") then + (cName == Name.mkStr2 (str% "HMul") (str% "hMul") || cName == Name.mkStr2 (str% "Mul") (str% "mul") || cName == Name.mkStr2 (str% "Nat") (str% "mul"), false) + else if sym == (str% "/") then + (cName == Name.mkStr2 (str% "HDiv") (str% "hDiv") || cName == Name.mkStr2 (str% "Div") (str% "div") || cName == Name.mkStr2 (str% "Nat") (str% "div"), false) + else if sym == (str% "%") then + (cName == Name.mkStr2 (str% "HMod") (str% "hMod") || cName == Name.mkStr2 (str% "Mod") (str% "mod") || cName == Name.mkStr2 (str% "Nat") (str% "mod"), false) + else if sym == (str% "^") then + (cName == Name.mkStr2 (str% "HPow") (str% "hPow") || cName == Name.mkStr2 (str% "Pow") (str% "pow") || cName == Name.mkStr2 (str% "Nat") (str% "pow"), false) + else if sym == (str% "=") then + (cName == Name.simple (str% "Eq"), false) + else if sym == (str% "≠") || sym == (str% "!=") then + (cName == Name.simple (str% "Ne"), false) + else if sym == (str% "≤") || sym == (str% "<=") then + (cName == Name.mkStr2 (str% "LE") (str% "le") || cName == Name.mkStr2 (str% "Nat") (str% "ble"), false) + else if sym == (str% "<") then + (cName == Name.mkStr2 (str% "LT") (str% "lt") || cName == Name.mkStr2 (str% "Nat") (str% "blt"), false) + else if sym == (str% ">") then + if cName == Name.mkStr2 (str% "GT") (str% "gt") then (true, false) + else if cName == Name.mkStr2 (str% "LT") (str% "lt") then (true, true) + else (false, false) + else if sym == (str% "≥") || sym == (str% ">=") then + if cName == Name.mkStr2 (str% "GE") (str% "ge") then (true, false) + else if cName == Name.mkStr2 (str% "LE") (str% "le") then (true, true) + else (false, false) + else if sym == (str% "∧") || sym == (str% "/\\") then + (cName == Name.simple (str% "And"), false) + else if sym == (str% "∨") || sym == (str% "\\/") then + (cName == Name.simple (str% "Or"), false) + else if sym == (str% "↔") || sym == (str% "<->") then + (cName == Name.simple (str% "Iff"), false) + else if sym == (str% "==") then + (cName == Name.mkStr2 (str% "BEq") (str% "beq") || cName == Name.mkStr2 (str% "Nat") (str% "beq"), false) + else if sym == (str% "&&") then + (cName == Name.simple (str% "and") || cName == Name.mkStr2 (str% "Bool") (str% "and"), false) + else if sym == (str% "||") then + (cName == Name.simple (str% "or") || cName == Name.mkStr2 (str% "Bool") (str% "or"), false) + else if sym == (str% "++") then + (cName == Name.mkStr2 (str% "HAppend") (str% "hAppend") || cName == Name.mkStr2 (str% "List") (str% "append") || cName == Name.mkStr2 (str% "String") (str% "append"), false) + else + (false, false) + +/-- Match an explicit application `fnStx arg_1 ... arg_k` from outermost argument (`arg_k`) inward. -/ +def checkAppSpineMatches (checkTerm : List Ix.Name → Stx → Ix.Expr → Bool) + (bvars : List Ix.Name) (fnStx : Stx) : + List Stx → Ix.Expr → Bool + | [], remFn => checkTerm bvars fnStx remFn + | lastArgStx :: prevArgStxs, e => + match stripMData e with + | .app f a _ => + checkTerm bvars lastArgStx a && + checkAppSpineMatches checkTerm bvars fnStx prevArgStxs f + | _ => false + +/-- Peel `.forallE` binders for a single `ParsedBinderGroup`'s names `nms : List Ix.Name`. -/ +def peelGroupType (checkTerm : List Ix.Name → Stx → Ix.Expr → Bool) + (bvarsAtGroupStart : List Ix.Name) (biExpected : Lean.BinderInfo) (typeStx? : Option Stx) : + List Ix.Name → Bool → Option Ix.Expr → List Ix.Name → Ix.Expr → Option (List Ix.Name × Ix.Expr) + | [], _, _, curBvars, curTy => some (curBvars, curTy) + | nm :: nms, isFirst, firstDom?, curBvars, curTy => + match stripMData curTy with + | .forallE _ dom cod bi _ => + if bi != biExpected then none + else + let domOk := + if isFirst then + match typeStx? with + | some tyStx => checkTerm bvarsAtGroupStart tyStx dom + | none => true + else + match firstDom? with + | some d0 => dom == d0 + | none => true + if !domOk then none + else peelGroupType checkTerm bvarsAtGroupStart biExpected typeStx? nms false (some dom) (nm :: curBvars) cod + | _ => none + +/-- Peel `.forallE` binders corresponding to `groups : List ParsedBinderGroup` from `ty`. -/ +def checkBindersType (checkTerm : List Ix.Name → Stx → Ix.Expr → Bool) + (bvars : List Ix.Name) : + List ParsedBinderGroup → Ix.Expr → Option (List Ix.Name × Ix.Expr) + | [], ty => some (bvars, ty) + | bg :: rest, ty => + match peelGroupType checkTerm bvars bg.binderInfo bg.typeStx? bg.names.toList true none bvars ty with + | some (bvars', ty') => checkBindersType checkTerm bvars' rest ty' + | none => none + +/-- Peel `.lam` binders for a single `ParsedBinderGroup`'s names `nms : List Ix.Name`. -/ +def peelGroupLam (checkTerm : List Ix.Name → Stx → Ix.Expr → Bool) + (bvarsAtGroupStart : List Ix.Name) (biExpected : Lean.BinderInfo) (typeStx? : Option Stx) : + List Ix.Name → Bool → Option Ix.Expr → List Ix.Name → Ix.Expr → Option (List Ix.Name × Ix.Expr) + | [], _, _, curBvars, curVal => some (curBvars, curVal) + | nm :: nms, isFirst, firstDom?, curBvars, curVal => + match stripMData curVal with + | .lam _ dom body bi _ => + if bi != biExpected then none + else + let domOk := + if isFirst then + match typeStx? with + | some tyStx => checkTerm bvarsAtGroupStart tyStx dom + | none => true + else + match firstDom? with + | some d0 => dom == d0 + | none => true + if !domOk then none + else peelGroupLam checkTerm bvarsAtGroupStart biExpected typeStx? nms false (some dom) (nm :: curBvars) body + | _ => none + +/-- Peel `.lam` binders corresponding to `groups : List ParsedBinderGroup` from `val`. -/ +def checkBindersLam (checkTerm : List Ix.Name → Stx → Ix.Expr → Bool) + (bvars : List Ix.Name) : + List ParsedBinderGroup → Ix.Expr → Option (List Ix.Name × Ix.Expr) + | [], val => some (bvars, val) + | bg :: rest, val => + match peelGroupLam checkTerm bvars bg.binderInfo bg.typeStx? bg.names.toList true none bvars val with + | some (bvars', val') => checkBindersLam checkTerm bvars' rest val' + | none => none + +/-- Verify in `O(|stx|)` (zero metavariables, zero `whnf`) that a closed De Bruijn expression `e` + structurally matches surface syntax `stx` under `bvars : List Ix.Name`. -/ +def checkTermMatchesSyntax (fuel : Nat) (scope : ScopeSnapshot) (modIdx : ModuleIndex) + (env : IxElabEnv) (bvars : List Ix.Name) (rawStx : Stx) (e : Ix.Expr) : Bool := + match fuel with + | 0 => false + | fuel + 1 => + let stx := if env.macroRules.isEmpty then rawStx else expandTopMacroPure 8 env.macroRules rawStx + let e := stripMData e + let checkSub (bv : List Ix.Name) (s : Stx) (ex : Ix.Expr) : Bool := + checkTermMatchesSyntax fuel scope modIdx env bv s ex + match stx with + | .missing => true + | .snil | .scons .. => false + | .atom _ vSym => + let v := Sym.toString vSym + if v == (str% "_") then true + else if v == (str% "Prop") then + match e with | .sort (.zero _) _ => true | _ => false + else false + | .ident _ _ idF => + let id := FName.toIxName idF + match bvarIndexOf id bvars 0 with + | some idx => + match e with + | .bvar j _ => idx == j + | _ => false + | none => + let resolved := resolveIdentInScope scope modIdx (fun n => env.contains n) id + match exprHeadConst? e with + | some cName => cName == resolved + | none => false + | .node _ kindF args => + let kind := FName.toIxName kindF + if kind == SyntaxKind.nullKind then + match args.toList with + | [single] => checkSub bvars single e + | _ => false + else if kind == SyntaxKind.parenTerm then + checkSub bvars (Syntax.listGetD args.toList 1 .missing) e + else if kind == SyntaxKind.holeTerm then + true + else if kind == SyntaxKind.byTactic || kind == SyntaxKind.calcTerm then + !hasLooseBVarsAt e bvars.length + else if kind == SyntaxKind.propTerm then + match e with + | .sort (.zero _) _ => true + | _ => false + else if kind == SyntaxKind.typeTerm || kind == SyntaxKind.sortTerm then + match e with + | .sort _ _ => true + | _ => false + else if kind == SyntaxKind.numLit then + let numStr := Syntax.getAtomVal (Syntax.listGetD args.toList 0 .missing) + match parseNatLiteral numStr with + | none => false + | some n => + match e with + | .lit (.natVal m) _ => n == m + | .app (.app (.app (.const cNm _ _) _ _) (.lit (.natVal m) _) _) _ _ => + cNm == Name.mkStr2 (str% "OfNat") (str% "ofNat") && n == m + | _ => false + else if kind == SyntaxKind.strLit then + let strVal := Syntax.getAtomVal (Syntax.listGetD args.toList 0 .missing) + match e with + | .lit (.strVal s) _ => s == strVal + | _ => false + else if kind == SyntaxKind.hashRef then + let hexStr := Syntax.getAtomVal (Syntax.listGetD args.toList 0 .missing) + match parseHexAddress hexStr, exprHeadConst? e with + | some addr, some cName => + Name.computeHash cName == addr || env.importMap.lookupName? cName == some addr + | _, _ => false + else if kind == SyntaxKind.arrowTerm then + let domStx := Syntax.listGetD args.toList 0 .missing + let codStx := Syntax.listGetD args.toList 3 .missing + match e with + | .forallE _ dom cod _ _ => + checkSub bvars domStx dom && + checkSub (Name.mkAnon :: bvars) codStx cod + | _ => false + else if kind == SyntaxKind.forallTerm then + let isKw := match Syntax.listGetD args.toList 0 .missing with + | .atom _ kw => Sym.beq kw (s% "forall") || Sym.beq kw (s% "∀") + | _ => false + let bindersNode := Syntax.listGetD args.toList (if isKw then 1 else 0) .missing + let bodyStx := Syntax.listGetD args.toList (if isKw then 4 else 3) .missing + let groups := (Syntax.getArgs bindersNode).toList.map decodeBinderNode + match checkBindersType checkSub bvars groups e with + | some (bvars', remBody) => + checkSub bvars' bodyStx remBody + | none => false + else if kind == SyntaxKind.funTerm then + let bindersNode := Syntax.listGetD args.toList 1 .missing + let bodyStx := Syntax.listGetD args.toList 3 .missing + let groups := (Syntax.getArgs bindersNode).toList.map decodeBinderNode + match checkBindersLam checkSub bvars groups e with + | some (bvars', remBody) => + checkSub bvars' bodyStx remBody + | none => false + else if kind == SyntaxKind.letTerm || kind == SyntaxKind.haveTerm then + let idStx := Syntax.listGetD args.toList 1 .missing + let optTy := Syntax.listGetD args.toList 3 .missing + let valStx := Syntax.listGetD args.toList 5 .missing + let bodyStx := Syntax.listGetD args.toList 7 .missing + let nm := match idStx with | .ident _ _ iF => FName.toIxName iF | _ => Name.mkAnon + match e with + | .letE _ ty val body _ _ => + let tyOk := if Syntax.isNone optTy || Syntax.isMissing optTy then true + else checkSub bvars optTy ty + tyOk && + checkSub bvars valStx val && + checkSub (nm :: bvars) bodyStx body + | _ => false + else if kind == SyntaxKind.ifTerm then + match exprHeadConst? e with + | some cNm => + (cNm == Name.simple (str% "ite") || cNm == Name.simple (str% "dite")) && !hasLooseBVarsAt e bvars.length + | none => false + else if kind == SyntaxKind.anonCtor || kind == SyntaxKind.structInst || kind == SyntaxKind.matchTerm then + !hasLooseBVarsAt e bvars.length + else if kind == SyntaxKind.projTerm then + match e with + | .proj _ _ s _ => checkSub bvars (Syntax.listGetD args.toList 0 .missing) s + | .app _ _ _ => !hasLooseBVarsAt e bvars.length + | _ => false + else if kind == SyntaxKind.explicitTerm then + let innerIdx := + if args.size >= 2 && Syntax.getAtomVal (Syntax.listGetD args.toList 0 .missing) == (str% "@") then 1 else 0 + checkSub bvars (Syntax.listGetD args.toList innerIdx .missing) e + else if kind == SyntaxKind.typeAscription then + let termStx := Syntax.listGetD args.toList 1 .missing + checkSub bvars termStx e + else if kind == SyntaxKind.binOpTerm then + let lhsStx := Syntax.listGetD args.toList 0 .missing + let opAtom := Syntax.listGetD args.toList 1 .missing + let rhsStx := Syntax.listGetD args.toList 2 .missing + let sym := Syntax.getAtomVal opAtom + if (sym == (str% "≠") || sym == (str% "!=")) then + match peelApp2? e with + | some (fn, lhs, rhs) => + let (okHead, _) := checkBinOpHead sym fn + okHead && + checkSub bvars lhsStx lhs && + checkSub bvars rhsStx rhs + | none => + match e with + | .app (.const notNm _ _) innerEq _ => + if notNm != Name.simple (str% "Not") then false + else match peelApp2? innerEq with + | some (fn, lhs, rhs) => + exprHeadConst? fn == some (Name.simple (str% "Eq")) && + checkSub bvars lhsStx lhs && + checkSub bvars rhsStx rhs + | none => false + | _ => false + else + match peelApp2? e with + | some (fn, a1, a2) => + let (okHead, swapped) := checkBinOpHead sym fn + if !okHead then false + else if swapped then + checkSub bvars lhsStx a2 && + checkSub bvars rhsStx a1 + else + checkSub bvars lhsStx a1 && + checkSub bvars rhsStx a2 + | none => false + else if kind == SyntaxKind.unaryOpTerm then + let opAtom := Syntax.listGetD args.toList 0 .missing + let argStx := Syntax.listGetD args.toList 1 .missing + let sym := Syntax.getAtomVal opAtom + match e with + | .app fn arg _ => + let okHead := match exprHeadConst? fn with + | some cNm => + (sym == (str% "¬") && cNm == Name.simple (str% "Not")) || + (sym == (str% "!") && (cNm == Name.simple (str% "not") || cNm == Name.mkStr2 (str% "Bool") (str% "not"))) + | none => false + okHead && checkSub bvars argStx arg + | _ => false + else if kind == SyntaxKind.appTerm then + let fnStx := Syntax.listGetD args.toList 0 .missing + let argStxs := (Syntax.getArgs (Syntax.listGetD args.toList 1 .missing)).toList + checkAppSpineMatches checkSub bvars fnStx argStxs.reverse e + else + false + +/-- Peel `.forallE` from `ty` and `.lam` from `val` for a single `ParsedBinderGroup`. -/ +def peelGroupTypeAndVal (fuel : Nat) (scope : ScopeSnapshot) (modIdx : ModuleIndex) + (env : IxElabEnv) (bvarsAtGroupStart : List Ix.Name) (biExpected : Lean.BinderInfo) + (typeStx? : Option Stx) : + List Ix.Name → Bool → Option Ix.Expr → List Ix.Name → Ix.Expr → Ix.Expr → Option (List Ix.Name × Ix.Expr × Ix.Expr) + | [], _, _, curBvars, curTy, curVal => some (curBvars, curTy, curVal) + | nm :: nms, isFirst, firstDom?, curBvars, curTy, curVal => + match stripMData curTy, stripMData curVal with + | .forallE _ domT codT biT _, .lam _ domV bodyV biV _ => + if biT != biExpected || biV != biExpected || domT != domV then none + else + let domOk := + if isFirst then + match typeStx? with + | some tyStx => checkTermMatchesSyntax fuel scope modIdx env bvarsAtGroupStart tyStx domT + | none => true + else + match firstDom? with + | some d0 => domT == d0 + | none => true + if !domOk then none + else peelGroupTypeAndVal fuel scope modIdx env bvarsAtGroupStart biExpected typeStx? nms false (some domT) (nm :: curBvars) codT bodyV + | _, _ => none + +/-- Peel `.forallE` from `ty` and `.lam` from `val` simultaneously for top-level declaration parameters. -/ +def checkBindersTypeAndVal (fuel : Nat) (scope : ScopeSnapshot) (modIdx : ModuleIndex) + (env : IxElabEnv) (bvars : List Ix.Name) : + List ParsedBinderGroup → Ix.Expr → Ix.Expr → Option (List Ix.Name × Ix.Expr × Ix.Expr) + | [], ty, val => some (bvars, ty, val) + | bg :: rest, ty, val => + match peelGroupTypeAndVal fuel scope modIdx env bvars bg.binderInfo bg.typeStx? bg.names.toList true none bvars ty val with + | some (bvars', ty', val') => checkBindersTypeAndVal fuel scope modIdx env bvars' rest ty' val' + | none => none + +/-- Verify in `O(|stx|)` that `hint : DeclHint` matches a single non-recursive `decl : ModuleDecl`. -/ +def checkDeclMatchesSyntax (fuel : Nat) (modIdx : ModuleIndex) (env : IxElabEnv) + (decl : ModuleDecl) (hint : DeclHint) : Bool := + if decl.fullName != hint.fullName then false + else + let cmd := decl.stx + let k := Syntax.getKind cmd + let vPrefNode := Syntax.getArg cmd 5 + let retContract := (decodeContractPrefix vPrefNode).toValueContract + if retContract != hint.retContract then false + else + let varGroups := decl.scope.varBinders.toList.map decodeBinderNode + let rawParamGroups := (Syntax.getArgs (Syntax.getArg cmd 4)).toList.map decodeBinderNode + let optTypeNode := Syntax.getArg cmd 6 + let explicitGroups := varGroups ++ rawParamGroups + let checkWithGroups (paramGroups : List ParsedBinderGroup) : Bool := + if k == SyntaxKind.axiomDecl then + match hint.value? with + | some _ => false + | none => + let checkSub (bv : List Ix.Name) (s : Stx) (ex : Ix.Expr) : Bool := + checkTermMatchesSyntax fuel decl.scope modIdx env bv s ex + match checkBindersType checkSub [] paramGroups hint.type with + | none => false + | some (bvars, remType) => + if Syntax.isNone optTypeNode || Syntax.isMissing optTypeNode then false + else checkTermMatchesSyntax fuel decl.scope modIdx env bvars optTypeNode remType + else if Syntax.getNumArgs cmd == 8 || (k == SyntaxKind.instanceDecl && Syntax.getAtomVal (Syntax.getArg cmd 7) == (str% "where")) then + -- Pattern-matching defs and `instance ... where` desugar syntax; fall back to full elaborator + false + else + match hint.value? with + | none => false + | some fullVal => + match checkBindersTypeAndVal fuel decl.scope modIdx env [] paramGroups hint.type fullVal with + | none => false + | some (bvars, remType, remVal) => + let tyOk := + if Syntax.isNone optTypeNode || Syntax.isMissing optTypeNode then true + else checkTermMatchesSyntax fuel decl.scope modIdx env bvars optTypeNode remType + let bodyStx := Syntax.getArg cmd 8 + tyOk && checkTermMatchesSyntax fuel decl.scope modIdx env bvars bodyStx remVal + if checkWithGroups explicitGroups then + true + else + let autoGroups := collectAutoImplicitGroups decl.scope modIdx env varGroups rawParamGroups optTypeNode + if autoGroups.isEmpty then false + else checkWithGroups (varGroups ++ autoGroups ++ rawParamGroups) + +/-- Check if `e` references a constant `target` within `fuel` steps. -/ +def exprRefsConst : Nat → Ix.Name → Ix.Expr → Bool + | 0, _, _ => false + | _, target, .const nm _ _ => nm == target + | fuel + 1, target, .app f a _ => exprRefsConst fuel target f || exprRefsConst fuel target a + | fuel + 1, target, .lam _ d b _ _ => exprRefsConst fuel target d || exprRefsConst fuel target b + | fuel + 1, target, .forallE _ d b _ _ => exprRefsConst fuel target d || exprRefsConst fuel target b + | fuel + 1, target, .letE _ t v b _ _ => + exprRefsConst fuel target t || exprRefsConst fuel target v || exprRefsConst fuel target b + | fuel + 1, target, .proj _ _ s _ => exprRefsConst fuel target s + | fuel + 1, target, .mdata _ b _ => exprRefsConst fuel target b + | _, _, _ => false + +/-- Apply a verified `DeclHint` directly to `IxElabEnv` without running `elabValueSCC`. -/ +def applyVerifiedDeclHint (env : IxElabEnv) (decl : ModuleDecl) (hint : DeclHint) : IxElabEnv := + let cmd := decl.stx + let k := Syntax.getKind cmd + if k == SyntaxKind.axiomDecl then + let ax : Ix.AxiomVal := { + cnst := { name := hint.fullName, levelParams := hint.levelParams, type := hint.type } + isUnsafe := false + } + env.addConst (.axiomInfo ax) + else + let val := hint.value?.getD (Expr.mkBVar 0) + let certNm := Name.mkStr2 (str% "_Ix") (str% "decideCert") + let env := + if !env.contains certNm && exprRefsConst 64 certNm val then + let propSort := Expr.mkSort Level.mkZero + let ty := Expr.mkForallE (Name.simple (str% "p")) propSort (Expr.mkBVar 0) .default + env.addConst (.axiomInfo { cnst := { name := certNm, levelParams := #[], type := ty }, isUnsafe := false }) + else env + let env := env.addContracts hint.fullName hint.binderContracts hint.retContract hint.letContracts + let env := + if hint.isInstance then + match hint.className? with + | some clsNm => env.addInstance { instName := hint.fullName, className := clsNm } + | none => env + else env + let env := + if hint.isSimp then + env.addInstance { instName := hint.fullName, className := Name.mkStr2 (str% "_Ix") (str% "simpLemma") } + else env + let ci : Ix.ConstantInfo := match hint.defKind with + | .thm => .thmInfo { + cnst := { name := hint.fullName, levelParams := hint.levelParams, type := hint.type } + value := val + all := #[hint.fullName] + } + | .opaq => .opaqueInfo { + cnst := { name := hint.fullName, levelParams := hint.levelParams, type := hint.type } + value := val + isUnsafe := false + all := #[hint.fullName] + } + | .defn => .defnInfo { + cnst := { name := hint.fullName, levelParams := hint.levelParams, type := hint.type } + value := val + hints := hint.hints + safety := .safe + all := #[hint.fullName] + } + env.addConst ci + +/-- Elaborate a `ModuleSchedule` using `hints : ElabHints` for `O(|stx|)` certificate verification + on single non-recursive declarations, falling back to `elabValueSCC` when no hint is provided. -/ +def elabModuleScheduleWithHints (sched : ModuleSchedule) (hints : ElabHints) + (initEnv : IxElabEnv := IxElabEnv.empty) + (seedPrelude : Bool := true) : Except ElabError IxElabEnv := do + let baseEnv := initEnv.withImportMap (initEnv.importMap.merge sched.modIdx.importMap) + let baseEnv := if seedPrelude then seedCorePreludeIfMissing baseEnv sched.modIdx else baseEnv + let baseEnv := + if sched.modIdx.macroRules.isEmpty then baseEnv + else baseEnv.addMacroRules sched.modIdx.macroRules.toList + baseEnv.bindEnv fun baseEnv' => do + let initState : ElabState := { env := baseEnv' } + let initCtx : ElabContext := { modIdx := sched.modIdx } + let declList := sched.modIdx.decls.toList + let act : IxElabM Unit := do + for scc in sched.sccs.toList do + let sccDecls := Array.mk (scc.declIdxs.toList.filterMap fun idx => Syntax.listGet? declList idx) + if !sccDecls.isEmpty then + let allInd := sccDecls.toList.all fun d => d.kind == .ind || d.kind == .struct || d.kind == .cls + if allInd then + elabInductiveSCC sccDecls + else + match scc.kind, sccDecls.toList with + | .singleNonRec, [decl] => + match hints.find? decl.fullName with + | some hint => + let stNow ← get + if checkDeclMatchesSyntax 128 sched.modIdx stNow.env decl hint then + modifyEnv (fun env => applyVerifiedDeclHint env decl hint) + else + throwElabError s!"ElabHint verification failed for declaration '{decl.fullName}'" (some decl.stx) + | none => + elabValueSCC sccDecls false + | _, _ => + elabValueSCC sccDecls (scc.kind != .singleNonRec) + let (_, finalState) ← IxElabM.run act initCtx initState + return finalState.env + +/-- Fast path: when all declarations in `modIdx.decls` are value/axiom declarations + supplied in `hints : ElabHints`, verify and apply them in source order in `O(|stx|)` + without running Pass 2 (`extractDeclDeps`) or Pass 3 (`scheduleModuleDecls`). + Returns `none` if any declaration is an inductive or lacks a hint in `hints`. -/ +def tryVerifyDeclsInOrder (modIdx : ModuleIndex) (hints : ElabHints) (env : IxElabEnv) : + List ModuleDecl → Option (Except String IxElabEnv) + | [] => some (.ok env) + | decl :: rest => + if decl.kind == .ind || decl.kind == .struct || decl.kind == .cls then + none + else + match hints.find? decl.fullName with + | none => none + | some hint => + if checkDeclMatchesSyntax 128 modIdx env decl hint then + (applyVerifiedDeclHint env decl hint).bindEnv fun env' => + tryVerifyDeclsInOrder modIdx hints env' rest + else + some (.error s!"ElabHint verification failed for declaration '{decl.fullName}'") + +/-- Elaborate a parsed `Stx` module AST with `hints : ElabHints`. -/ +def elabModuleWithHints (moduleStx : Stx) (hints : ElabHints) + (initEnv : IxElabEnv := IxElabEnv.empty) + (seedPrelude : Bool := true) : Except String IxElabEnv := do + let modIdx ← buildModuleIndex moduleStx + let baseEnv := if seedPrelude then seedCorePreludeIfMissing initEnv modIdx else initEnv + let baseEnv := + if modIdx.macroRules.isEmpty then baseEnv + else baseEnv.addMacroRules modIdx.macroRules.toList + baseEnv.bindEnv fun baseEnv' => + hints.bindHints fun hints' => do + match tryVerifyDeclsInOrder modIdx hints' baseEnv' modIdx.decls.toList with + | some res => res + | none => + let sched ← scheduleModuleDecls modIdx + (fun n => baseEnv'.contains n) + (fun n => baseEnv'.isCtor n) + match elabModuleScheduleWithHints sched hints' baseEnv' false with + | .ok env => return env + | .error e => throw (toString e) + +/-- Parse and elaborate a `.ix` / `.lean` source string with `hints : ElabHints`. -/ +def elabSourceWithHints (input : String) (hints : ElabHints) + (fileName : String := (str% "")) + (initEnv : IxElabEnv := IxElabEnv.empty) + (seedPrelude : Bool := true) : Except String IxElabEnv := do + let (stx, _) ← parseModuleWithEnv input fileName + elabModuleWithHints stx hints initEnv seedPrelude + +/-- Extract `ElabHints` from an already-elaborated `IxElabEnv` for all declarations in `modIdx`. -/ +def extractElabHintsFromEnv (modIdx : ModuleIndex) (env : IxElabEnv) : ElabHints := + let simpSet := (env.instancesByClass.get? (Name.mkStr2 (str% "_Ix") (str% "simpLemma"))).getD [] + modIdx.decls.toList.foldl (fun acc decl => + let hasSimp := simpSet.any (fun e => e.instName == decl.fullName) + match env.find? decl.fullName with + | some (.axiomInfo aval) => + acc.insert { + fullName := decl.fullName + levelParams := aval.cnst.levelParams + type := aval.cnst.type + value? := none + isSimp := hasSimp + } + | some (.defnInfo dval) => + let (bcs, retC) := env.binderContracts.get? decl.fullName |>.getD (#[], {}) + let letCs := env.letContracts.get? decl.fullName |>.getD #[] + acc.insert { + fullName := decl.fullName + levelParams := dval.cnst.levelParams + type := dval.cnst.type + value? := some dval.value + defKind := .defn + hints := dval.hints + binderContracts := bcs + retContract := retC + letContracts := letCs + isSimp := hasSimp + } + | some (.thmInfo tval) => + let (bcs, retC) := env.binderContracts.get? decl.fullName |>.getD (#[], {}) + let letCs := env.letContracts.get? decl.fullName |>.getD #[] + acc.insert { + fullName := decl.fullName + levelParams := tval.cnst.levelParams + type := tval.cnst.type + value? := some tval.value + defKind := .thm + hints := .opaque + binderContracts := bcs + retContract := retC + letContracts := letCs + isSimp := hasSimp + } + | some (.opaqueInfo oval) => + let (bcs, retC) := env.binderContracts.get? decl.fullName |>.getD (#[], {}) + let letCs := env.letContracts.get? decl.fullName |>.getD #[] + acc.insert { + fullName := decl.fullName + levelParams := oval.cnst.levelParams + type := oval.cnst.type + value? := some oval.value + defKind := .opaq + hints := .opaque + binderContracts := bcs + retContract := retC + letContracts := letCs + isSimp := hasSimp + } + | _ => acc + ) ElabHints.empty + +/-- Out-of-circuit generator that runs full elaboration on `input` and produces `ElabHints` + for in-circuit `elabModuleWithHints` / `elabSourceWithHints` verification. -/ +def generateElabHints (input : String) (fileName : String := (str% "")) + (initEnv : IxElabEnv := IxElabEnv.empty) + (seedPrelude : Bool := true) : Except String ElabHints := do + let (stx, _) ← parseModuleWithEnv input fileName + let modIdx ← buildModuleIndex stx + let env ← elabModuleSyntax stx initEnv seedPrelude + return extractElabHintsFromEnv modIdx env + +/-- Scan leading `import ` declarations at the top of `input` using the pure lexer + (before full module parsing so imported operators and notations can be merged first). -/ +def scanLeadingModuleImportsLoop (ctx : IxParserContext) : Nat → ParserState → List Ix.Name → List Ix.Name + | 0, _, revAcc => revAcc.reverse + | fuel + 1, s, revAcc => + bindPeek ctx s fun tok? s => + match tok? with + | some (.atom _ (s% "import")) => + let s1 := tokenFn ctx s + bindPeek ctx s1 fun nextTok? s2 => + match nextTok? with + | some (.ident _ _ modNameF) => + let modName := FName.toIxName modNameF + let s3 := tokenFn ctx s2 + bindPeek ctx s3 fun pinTok? s4 => + match pinTok? with + | some (.atom _ (s% "@")) => + let s5 := tokenFn ctx (tokenFn ctx s4) + scanLeadingModuleImportsLoop ctx fuel s5 (modName :: revAcc) + | _ => + scanLeadingModuleImportsLoop ctx fuel s3 (modName :: revAcc) + | some (.node _ k _) => + if k == SyntaxKindF.hashRef then + scanLeadingModuleImportsLoop ctx fuel (tokenFn ctx s2) revAcc + else + revAcc.reverse + | _ => revAcc.reverse + | _ => revAcc.reverse + +def scanLeadingModuleImports (input : String) : List Ix.Name := + let inputCtx := InputContext.mkInputContext input (str% "") + let ctx : IxParserContext := { inputCtx, env := defaultParserEnv, prec := 0 } + scanLeadingModuleImportsLoop ctx 64 (ParserState.init inputCtx.bytes) [] + +/-- Topologically schedule and elaborate a multi-module DAG `modules : List (Ix.Name × String)`, + threading exported constants, structures, typeclass instances, declarative macros, + custom operators, and mixfix notations across `import` edges. -/ +def elabModuleDAG (modules : List (Ix.Name × String)) + (initElabEnv : IxElabEnv := IxElabEnv.empty) + (initParserEnv : IxParserEnv := defaultParserEnv) + (seedPrelude : Bool := true) : Except String (IxElabEnv × IxParserEnv) := do + if modules.isEmpty then + return (initElabEnv, initParserEnv) + let modArr := Array.mk modules + let idxMap : NameMap Nat := (List.range modArr.size).foldl (fun acc i => + let (nm, _) := arrayGetD modArr i (Name.mkAnon, (str% "")) + acc.insert nm i) NameMap.empty + let mut adjList : List (Array Nat) := [] + let mut importsByMod : NameMap (List Ix.Name) := NameMap.empty + for (modName, src) in modules do + let imps := scanLeadingModuleImports src + importsByMod := importsByMod.insert modName imps + let mut row : List Nat := [] + for impName in imps do + match idxMap.get? impName with + | some idx => + if !row.contains idx then row := row ++ [idx] + | none => + throw s!"unknown imported module '{Name.toStringTotal impName}' in module '{Name.toStringTotal modName}'" + adjList := adjList ++ [Array.mk row] + let adj := Array.mk adjList + let some cond := tarjanCondensation adj + | throw (str% "module DAG Tarjan condensation fuel exhausted") + let mut doneMap : NameMap (IxElabEnv × IxParserEnv) := NameMap.empty + let mut finalElab := initElabEnv + let mut finalParser := initParserEnv + for comp in cond.comps.toList do + if comp.size != 1 then + let firstIdx := arrayGetD comp 0 0 + let (cycName, _) := arrayGetD modArr firstIdx (Name.mkAnon, (str% "")) + throw s!"cyclic module import involving '{Name.toStringTotal cycName}'" + let u := arrayGetD comp 0 0 + let uRow := arrayGetD adj u #[] + if uRow.toList.contains u then + let (selfName, _) := arrayGetD modArr u (Name.mkAnon, (str% "")) + throw s!"module '{Name.toStringTotal selfName}' cannot import itself" + let (modName, src) := arrayGetD modArr u (Name.mkAnon, (str% "")) + let imps := importsByMod.get? modName |>.getD [] + let (mergedElab, mergedParser) := imps.foldl (fun (eAcc, pAcc) impNm => + match doneMap.get? impNm with + | some (impE, impP) => (eAcc.merge impE, pAcc.merge impP) + | none => (eAcc, pAcc)) (initElabEnv, initParserEnv) + let (stx, modParserEnv) ← parseModuleWithEnv src (Name.toStringTotal modName) mergedParser + let modElabEnv ← elabModuleSyntax stx mergedElab seedPrelude + doneMap := doneMap.insert modName (modElabEnv, modParserEnv) + finalElab := finalElab.merge modElabEnv + finalParser := finalParser.merge modParserEnv + return (finalElab, finalParser) + +end Ix.Frontend.Elab diff --git a/Ix/Frontend/Elab/CorePure.lean b/Ix/Frontend/Elab/CorePure.lean new file mode 100644 index 0000000000..b789ecb3a1 --- /dev/null +++ b/Ix/Frontend/Elab/CorePure.lean @@ -0,0 +1,2539 @@ +/- + Ix.Frontend.Elab.CorePure: 100% First-Order Monomorphic Core Elaborator for IxCCAiur. + + Eliminates all `IxElabM` (`ElabContext → ElabState → ElabRes α`) closures, + `Bind.bind` / `IxElabM.bind` lambdas, `withLocalDecl`/`withLetDecl` CPS continuations, + higher-order `elabRec`/`evalTacticFn`/`elabTermFn` parameters, `observing?` closures, + and interpolated `s!"..."` error strings so `IxCCAiur` compiles the full `Ix.Frontend` + elaborator as first-order (`fo = true`) direct-call Aiur chips! + + Shares all data types, `Meta` (`*Pure`), `AuxGen`, `CanonBlock`, `Scope`, `SccPass`, + and prelude seeding directly with the main `Ix.Frontend` codebase (0 Ixon/AST changes). +-/ +module + +public import Ix.Frontend.Elab.Command + +@[expose] public section + +set_option autoImplicit false + +namespace Ix.Frontend.Elab + +open Ix.Frontend +open Ix.Frontend.Parser +open Ix.Frontend.Canon +open Ix.Frontend.AuxGen + +/-! ## Section 1: Pure First-Order `ElabRes` Helpers & Error Construction -/ + +@[inline] def errPure {α : Type} (ctx : ElabContext) (msg : String) (stx? : Option Stx := none) : ElabRes α := + let pos? := match stx? with + | some stx => + match Syntax.getPos? stx with + | some p => some p + | none => ctx.refPos? + | none => ctx.refPos? + .error { pos?, msg } + +@[inline] def withRefPure {α : Type} (ctx : ElabContext) (stx : Stx) (res : ElabRes α) : ElabRes α := + match res with + | .ok a st' => .ok a st' + | .error err => + match err.pos? with + | some _ => .error err + | none => + let pos? := match Syntax.getPos? stx with + | some p => some p + | none => ctx.refPos? + .error { err with pos? } + +@[inline] def setEnvPure (st : ElabState) (env' : IxElabEnv) : ElabState := + match st with + | ⟨_, mctx, nextId, autoUnivs, letContracts⟩ => + env'.bindEnv fun e' => ⟨e', mctx, nextId, autoUnivs, letContracts⟩ + +@[inline] def setMCtxPure (st : ElabState) (mctx' : MetavarContext) : ElabState := + match st with + | ⟨env, _, nextId, autoUnivs, letContracts⟩ => + mctx'.bindMCtx fun m' => ⟨env, m', nextId, autoUnivs, letContracts⟩ + +@[inline] def mkForallFVarsPure (ctx : ElabContext) (fvars : Array Ix.Name) + (body : Ix.Expr) (retContract : Ixon.ValueContract := .shared) : Ix.Expr := + mkForallFVarsList ctx.lctx retContract fvars.toList body + +@[inline] def mkLambdaFVarsPure (ctx : ElabContext) (fvars : Array Ix.Name) + (body : Ix.Expr) : Ix.Expr := + mkLambdaFVarsList ctx.lctx fvars.toList body + +@[inline] def expandMacroPureSt (st : ElabState) (fuel : Nat) (stx : Stx) : Stx := + if st.env.macroRules.isEmpty then stx + else expandTopMacroPure fuel st.env.macroRules stx + +/-! ## Section 2: First-Order Universe Level & Meta Helpers -/ + +def elabLevelPure (ctx : ElabContext) : Nat → ElabState → Stx → ElabRes Ix.Level + | 0, _, stx => errPure ctx (str% "elaborator fuel exhausted in universe level") (some stx) + | fuel + 1, st, stx => + let rec elabLevels (st0 : ElabState) : List Stx → List Ix.Level → ElabRes (List Ix.Level) + | [], revAcc => .ok revAcc.reverse st0 + | s :: rest, revAcc => + match elabLevelPure ctx fuel st0 s with + | .error e => .error e + | .ok u st1 => elabLevels st1 rest (u :: revAcc) + withRefPure ctx stx <| + match stx with + | .ident _ _ idF => + let id := FName.toIxName idF + if Name.isAnonymous id || id == Name.simple (str% "_") then + let (u, st1) := mkFreshLevelMVarPure st + .ok u st1 + else if ctx.univParams.contains id || ctx.scope.levelNames.contains id || + st.autoBoundUnivs.contains id then + .ok (Level.mkParam id) st + else + let st1 : ElabState := match st with + | ⟨env, mctx, nextId, autoUnivs, lcs⟩ => ⟨env, mctx, nextId, autoUnivs ++ [id], lcs⟩ + .ok (Level.mkParam id) st1 + | .node _ kindF args => + let kind := FName.toIxName kindF + if kind == SyntaxKind.levelLit then + let numStr := Syntax.getAtomVal (args.getD 0 .missing) + .ok (Level.ofNat ((parseNatLiteral numStr).getD 0)) st + else if kind == SyntaxKind.levelAdd then + match elabLevelPure ctx fuel st (args.getD 0 .missing) with + | .error e => .error e + | .ok base st1 => + let numStr := Syntax.getAtomVal (Syntax.getArg (args.getD 2 .missing) 0) + let offset := (parseNatLiteral numStr).getD 0 + .ok ((List.range offset).foldl (fun acc _ => Level.mkSucc acc) base) st1 + else if kind == SyntaxKind.levelMax then + let children := Syntax.getArgs (args.getD 1 .missing) + match elabLevels st children.toList [] with + | .error e => .error e + | .ok [] st1 => .ok Level.mkZero st1 + | .ok (u :: us) st1 => .ok (us.foldl Level.mkMax u) st1 + else if kind == SyntaxKind.levelIMax then + let children := Syntax.getArgs (args.getD 1 .missing) + match elabLevels st children.toList [] with + | .error e => .error e + | .ok [] st1 => .ok Level.mkZero st1 + | .ok [u] st1 => .ok u st1 + | .ok (u :: us) st1 => + match (u :: us).reverse with + | last :: initRev => .ok (initRev.foldl (fun acc x => Level.mkIMax x acc) last) st1 + | [] => .ok Level.mkZero st1 + else + errPure ctx (str% "unexpected universe level syntax") (some stx) + | _ => + errPure ctx (str% "expected universe level") (some stx) + +def elabLevelListPure (ctx : ElabContext) (fuel : Nat) (st : ElabState) : + List Stx → List Ix.Level → ElabRes (Array Ix.Level) + | [], revAcc => .ok (Array.mk revAcc.reverse) st + | s :: rest, revAcc => + match elabLevelPure ctx fuel st s with + | .error e => .error e + | .ok u st1 => elabLevelListPure ctx fuel st1 rest (u :: revAcc) + +def solveInstGoalsPure (ctx : ElabContext) (fuel : Nat) (st : ElabState) : + List Ix.Expr → ElabState + | [] => st + | mvar :: rest => + match inferTypePure ctx st fuel mvar with + | .error _ => solveInstGoalsPure ctx fuel st rest + | .ok mTy st1 => + match synthInstancePure ctx 8 st1 mTy with + | (some instExpr, st2) => + let (_, st3) := isDefEqPure ctx st2 fuel mvar instExpr + solveInstGoalsPure ctx fuel st3 rest + | (none, st2) => + solveInstGoalsPure ctx fuel st2 rest + +def solveAllInstGoalsPure (ctx : ElabContext) (fuel : Nat) (st : ElabState) : + List Ix.Expr → Bool × ElabState + | [] => (true, st) + | mvar :: rest => + match inferTypePure ctx st fuel mvar with + | .error _ => (false, st) + | .ok mTy st1 => + match synthInstancePure ctx 8 st1 mTy with + | (some instExpr, st2) => + let (ok, st3) := isDefEqPure ctx st2 fuel mvar instExpr + if ok then solveAllInstGoalsPure ctx fuel st3 rest else (false, st3) + | (none, st2) => (false, st2) + +def unifyExprPairsPure (ctx : ElabContext) (fuel : Nat) (st : ElabState) : + List (Ix.Expr × Ix.Expr) → ElabState + | [] => st + | (a, b) :: rest => + let (_, st1) := isDefEqPure ctx st fuel a b + unifyExprPairsPure ctx fuel st1 rest + +def ensureSortIfNotForallPure (ctx : ElabContext) (st : ElabState) (fuel : Nat) (ty : Ix.Expr) : ElabRes Unit := + match stripMData ty with + | .forallE .. | .sort .. => .ok () st + | _ => + match ensureSortPure ctx st fuel ty with + | .error e => .error e + | .ok _ st1 => .ok () st1 + +/-! ## Section 3: First-Order Projections, Identifiers, and `ensureHasTypePure` -/ + +def elabProjOnExprPure (ctx : ElabContext) (st : ElabState) (fuel : Nat) + (baseExpr : Ix.Expr) (fieldStx : Stx) : ElabRes Ix.Expr := + if Syntax.isOfKind fieldStx SyntaxKind.numLit then + let nStr := Syntax.getAtomVal (Syntax.getArg fieldStx 0) + let rawIdx := (parseNatLiteral nStr).getD 0 + match inferTypePure ctx st fuel baseExpr with + | .error e => .error e + | .ok baseTy st1 => + let baseTyWhnf := whnfPure ctx st1 fuel baseTy + let (headFn, _) := getAppFnArgs baseTyWhnf + match headFn with + | .const structName _ _ => + let idx := if rawIdx > 0 then rawIdx - 1 else 0 + .ok (Expr.mkProj structName idx baseExpr) st1 + | _ => errPure ctx (str% "cannot project index from non-structure type") (some fieldStx) + else + let fieldId := Syntax.getId fieldStx + match inferTypePure ctx st fuel baseExpr with + | .error e => .error e + | .ok baseTy st1 => + let baseTyWhnf := whnfPure ctx st1 fuel baseTy + let (headFn, _) := getAppFnArgs baseTyWhnf + match headFn with + | .const typeName _ _ => + match st1.env.structTable.get? typeName with + | some sInfo => + match sInfo.fields.find? (fun f => f.fieldName == fieldId) with + | some fInfo => .ok (Expr.mkProj typeName fInfo.fieldIdx baseExpr) st1 + | none => + let methodName := Name.append typeName fieldId + if st1.env.contains methodName then + match mkConstWithFreshMVarLevelsPure ctx st1 methodName with + | .error e => .error e + | .ok (mConst, mTy) st2 => + let ((applied, instGoals, _), st3) := insertImplicitArgsPure ctx st2 16 mConst mTy [] + let st4 := solveInstGoalsPure ctx fuel st3 instGoals.reverse + .ok (Expr.mkApp applied baseExpr) st4 + else + let foundParent? := sInfo.parents.find? fun pName => + st1.env.contains (Name.append pName fieldId) + match foundParent? with + | some pName => + let basePName := (Name.conflictOrigName? pName).getD pName + let pShort := (Name.components basePName).getLastD (str% "") + let toParentName := Name.mkStr typeName (Sym.toString (Sym.append (s% "to") (Sym.ofString pShort))) + let coercedRes : ElabRes Ix.Expr := + if st1.env.contains toParentName then + match mkConstWithFreshMVarLevelsPure ctx st1 toParentName with + | .error e => .error e + | .ok (tpConst, tpTy) st2 => + let ((tpApp, tpInsts, _), st3) := insertImplicitArgsPure ctx st2 16 tpConst tpTy [] + let st4 := solveInstGoalsPure ctx fuel st3 tpInsts.reverse + .ok (Expr.mkApp tpApp baseExpr) st4 + else .ok baseExpr st1 + match coercedRes with + | .error e => .error e + | .ok coercedBase st5 => + let pMethodName := Name.append pName fieldId + match mkConstWithFreshMVarLevelsPure ctx st5 pMethodName with + | .error e => .error e + | .ok (mConst, mTy) st6 => + let ((applied, instGoals, _), st7) := insertImplicitArgsPure ctx st6 16 mConst mTy [] + let st8 := solveInstGoalsPure ctx fuel st7 instGoals.reverse + .ok (Expr.mkApp applied coercedBase) st8 + | none => errPure ctx (str% "unknown field or method on structure") (some fieldStx) + | none => + let methodName := + let direct := Name.append typeName fieldId + if st1.env.contains direct then direct + else match Name.splitMergeVariant? typeName with + | some (origType, tag, []) => + let varMethod := Name.mkMergeVariant (Name.append origType fieldId) tag + if st1.env.contains varMethod then varMethod + else + let origMethod := Name.append origType fieldId + if st1.env.contains origMethod then origMethod else direct + | _ => direct + if st1.env.contains methodName then + match mkConstWithFreshMVarLevelsPure ctx st1 methodName with + | .error e => .error e + | .ok (mConst, mTy) st2 => + let ((applied, instGoals, _), st3) := insertImplicitArgsPure ctx st2 16 mConst mTy [] + let st4 := solveInstGoalsPure ctx fuel st3 instGoals.reverse + .ok (Expr.mkApp applied baseExpr) st4 + else errPure ctx (str% "unknown field on type") (some fieldStx) + | _ => errPure ctx (str% "cannot project field from expression of unknown structure type") (some fieldStx) + +def applyFieldProjChainPure (ctx : ElabContext) (st : ElabState) (fuel : Nat) : + List String → Ix.Expr → ElabRes Ix.Expr + | [], cur => .ok cur st + | fStr :: rest, cur => + match elabProjOnExprPure ctx st fuel cur (Syntax.mkSimpleIdent (Name.simple fStr)) with + | .error e => .error e + | .ok cur' st1 => applyFieldProjChainPure ctx st1 fuel rest cur' + +def elabGlobalIdentPure (ctx : ElabContext) (st : ElabState) (fuel : Nat) (idStx : Stx) + (rawId : Ix.Name) (explicitLvls? : Option (Array Ix.Level)) (allowBoolFallback : Bool) : + ElabRes (Ix.Expr × Ix.Expr) := + let resolved := resolveIdentInScopeMap ctx.scope ctx.modIdx st.env.consts rawId + let mappedResolved := + if st.env.contains resolved then resolved + else match ctx.modIdx.importMap.lookupName? resolved <|> st.env.importMap.lookupName? resolved with + | some addr => + (st.env.constOrder.find? fun nm => + Name.computeHash nm == addr || st.env.importMap.lookupName? nm == some addr).getD resolved + | none => resolved + if st.env.contains mappedResolved then + match explicitLvls? with + | some lvls => + let cExpr := Expr.mkConst mappedResolved lvls + match inferTypePure ctx st fuel cExpr with + | .error e => .error e + | .ok cTy st1 => .ok (cExpr, cTy) st1 + | none => mkConstWithFreshMVarLevelsPure ctx st mappedResolved + else if allowBoolFallback && rawId == Name.simple (str% "true") && + st.env.contains (Name.mkStr2 (str% "Bool") (str% "true")) then + .ok (Expr.mkConst (Name.mkStr2 (str% "Bool") (str% "true")) #[], + Expr.mkConst (Name.simple (str% "Bool")) #[]) st + else if allowBoolFallback && rawId == Name.simple (str% "false") && + st.env.contains (Name.mkStr2 (str% "Bool") (str% "false")) then + .ok (Expr.mkConst (Name.mkStr2 (str% "Bool") (str% "false")) #[], + Expr.mkConst (Name.simple (str% "Bool")) #[]) st + else + errPure ctx (str% "unknown identifier") (some idStx) + +def elabIdentWithLevelsAndTypePure (ctx : ElabContext) (st : ElabState) (fuel : Nat) + (idStx : Stx) (explicitLvls? : Option (Array Ix.Level)) : ElabRes (Ix.Expr × Ix.Expr) := + let rawId := Syntax.getId idStx + match ctx.lctx.findUserName? rawId with + | some decl => .ok (Expr.mkFVar decl.fvarId, decl.type) st + | none => + match splitRootAndFields rawId with + | some (rootName, fieldStrs) => + match ctx.lctx.findUserName? rootName with + | some rootDecl => + match applyFieldProjChainPure ctx st fuel fieldStrs (Expr.mkFVar rootDecl.fvarId) with + | .error e => .error e + | .ok curExpr st1 => + match inferTypePure ctx st1 fuel curExpr with + | .error e => .error e + | .ok curTy st2 => .ok (curExpr, curTy) st2 + | none => elabGlobalIdentPure ctx st fuel idStx rawId explicitLvls? false + | none => elabGlobalIdentPure ctx st fuel idStx rawId explicitLvls? true + +def tryParentCoercionPure (ctx : ElabContext) (st : ElabState) (fuel : Nat) + (actNorm actWhnf expWhnf expr' expTy : Ix.Expr) : ElabRes (Option Ix.Expr) := + let (actHead, _) := getAppFnArgs actWhnf + let (expHead, _) := getAppFnArgs expWhnf + match actHead, expHead with + | .const actStruct _ _, .const expStruct _ _ => + match st.env.structTable.get? actStruct with + | some sInfo => + if sInfo.parents.contains expStruct then + let pShort := (Name.components expStruct).getLastD (str% "") + let toParentName := Name.mkStr actStruct (Sym.toString (Sym.append (s% "to") (Sym.ofString pShort))) + if st.env.contains toParentName then + match mkConstWithFreshMVarLevelsPure ctx st toParentName with + | .error e => .error e + | .ok (tpConst, tpTy) st1 => + let ((tpApp, tpInsts, tpAfterTy), st2) := insertImplicitArgsPure ctx st1 16 tpConst tpTy [] + match stripMData (whnfPure ctx st2 fuel tpAfterTy) with + | .forallE _ d b _ _ => + let (dOk, st3) := isDefEqPure ctx st2 fuel actNorm d + let coerced := Expr.mkApp tpApp expr' + let retTy := instantiate1 b expr' + let (rOk, st4) := isDefEqPure ctx st3 fuel retTy expTy + if dOk && rOk then + let st5 := solveInstGoalsPure ctx fuel st4 tpInsts.reverse + .ok (some coerced) st5 + else .ok none st4 + | _ => .ok none st2 + else .ok none st + else .ok none st + | none => .ok none st + | _, _ => .ok none st + +def tryCoeCoercionPure (ctx : ElabContext) (st : ElabState) (fuel : Nat) + (actNorm expr' expTy : Ix.Expr) : ElabRes (Option Ix.Expr) := + let coeFnName := Name.mkStr2 (str% "Coe") (str% "coe") + let coeClsName := Name.simple (str% "Coe") + if st.env.contains coeFnName && st.env.contains coeClsName then + match mkConstWithFreshMVarLevelsPure ctx st coeFnName with + | .error e => .error e + | .ok (coeConst, coeTy) st1 => + let ((coeApp, coeInsts, coeAfterTy), st2) := insertImplicitArgsPure ctx st1 16 coeConst coeTy [] + match stripMData (whnfPure ctx st2 fuel coeAfterTy) with + | .forallE _ dom b _ _ => + let (dOk, st3) := isDefEqPure ctx st2 fuel actNorm dom + let coerced := Expr.mkApp coeApp expr' + let retTy := instantiate1 b expr' + let (rOk, st4) := isDefEqPure ctx st3 fuel retTy expTy + if dOk && rOk then + let (allSolved, st5) := solveAllInstGoalsPure ctx fuel st4 coeInsts.reverse + if allSolved then .ok (some coerced) st5 else .ok none st5 + else .ok none st4 + | _ => .ok none st2 + else .ok none st + +def ensureHasKnownTypePure (ctx : ElabContext) (st : ElabState) (fuel : Nat) (stx : Stx) + (expr actualTy : Ix.Expr) (expectedType? : Option Ix.Expr) : ElabRes Ix.Expr := + match expectedType? with + | none => .ok (instantiateMVarsPure st.mctx 16 expr) st + | some expTy => + let expTyWhnf := whnfForallPure ctx st fuel expTy + let shouldPeelImplicits : Bool := match stripMData expTyWhnf with + | .forallE _ _ _ bi _ => bi == .default + | _ => true + let ((expr', instGoals, actualTy'), st1) := + if shouldPeelImplicits then insertImplicitArgsPure ctx st 16 expr actualTy [] + else ((expr, [], actualTy), st) + let (ok, st2) := isDefEqPure ctx st1 fuel actualTy' expTy + if ok then + let st3 := solveInstGoalsPure ctx fuel st2 instGoals.reverse + .ok (instantiateMVarsPure st3.mctx 16 expr') st3 + else + let actNorm := instantiateMVarsPure st2.mctx 16 actualTy' + let expNorm := instantiateMVarsPure st2.mctx 16 expTy + let actWhnf := whnfPure ctx st2 fuel actNorm + let expWhnf := whnfPure ctx st2 fuel expNorm + match tryParentCoercionPure ctx st2 fuel actNorm actWhnf expWhnf expr' expTy with + | .error e => .error e + | .ok (some coerced) st3 => + let st4 := solveInstGoalsPure ctx fuel st3 instGoals.reverse + .ok (instantiateMVarsPure st4.mctx 16 coerced) st4 + | .ok none st3 => + match tryCoeCoercionPure ctx st3 fuel actNorm expr' expTy with + | .error e => .error e + | .ok (some coerced) st4 => + let st5 := solveInstGoalsPure ctx fuel st4 instGoals.reverse + .ok (instantiateMVarsPure st5.mctx 16 coerced) st5 + | .ok none _ => + errPure ctx (str% "type mismatch") (some stx) + +def ensureHasTypePure (ctx : ElabContext) (st : ElabState) (fuel : Nat) (stx : Stx) + (expr : Ix.Expr) (expectedType? : Option Ix.Expr) : ElabRes Ix.Expr := + match expectedType? with + | none => .ok (instantiateMVarsPure st.mctx 16 expr) st + | some _ => + match inferTypePure ctx st fuel expr with + | .error e => .error e + | .ok actualTy st1 => ensureHasKnownTypePure ctx st1 fuel stx expr actualTy expectedType? + +/-! ## Section 4: First-Order Core Term Elaborator (Zero Closures, Pure Structural Recursion) -/ + +def stxMentionsPure (nm : Ix.Name) : Nat → Stx → Bool + | 0, _ => false + | f + 1, s => + match s with + | .ident _ _ idF => FName.toIxName idF == nm + | .node _ _ as => as.any (stxMentionsPure nm f) + | _ => false + +def buildTuplePairsStx : List Stx → Stx + | [] => Syntax.mkSimpleIdent (Name.mkStr2 (str% "Unit") (str% "unit")) + | [x] => x + | x :: xs => + let rhs := buildTuplePairsStx xs + let prodMk := Syntax.mkSimpleIdent (Name.mkStr2 (str% "Prod") (str% "mk")) + Syntax.mkNode SyntaxKind.appTerm + #[Syntax.mkNode SyntaxKind.appTerm #[prodMk, x], rhs] + +def buildListLitStx : List Stx → Stx + | [] => Syntax.mkSimpleIdent (Name.mkStr2 (str% "List") (str% "nil")) + | x :: xs => + let tail := buildListLitStx xs + let consId := Syntax.mkSimpleIdent (Name.mkStr2 (str% "List") (str% "cons")) + Syntax.mkNode SyntaxKind.appTerm + #[Syntax.mkNode SyntaxKind.appTerm #[consId, x], tail] + +-- First-order bidirectional core term elaborator (zero `IxElabM`, zero `elabRec`, +-- zero `evalTacticFn`, clean mutual recursion with explicit termination measure). +set_option maxHeartbeats 1600000 in +mutual +def elabTermCoreGo : + Nat → ElabContext → ElabState → Stx → Option Ix.Expr → ElabRes Ix.Expr + | 0, ctx, _, stx, _ => errPure ctx (str% "elaborator fuel exhausted in term") (some stx) + | fuel + 1, ctx, st, stx0, expectedType? => + let stx := expandMacroPureSt st 16 stx0 + withRefPure ctx stx0 <| + match stx with + | .missing | .snil | .scons .. => + errPure ctx (str% "missing syntax node in term") + -- 1. Bare identifier + | .ident .. => + match elabIdentWithLevelsAndTypePure ctx st fuel stx none with + | .error e => .error e + | .ok (e, eTy) st1 => ensureHasKnownTypePure ctx st1 fuel stx e eTy expectedType? + -- 2. Bare `true` / `false` atoms + | .atom _ valSym => + let val := Sym.toString valSym + if val == (str% "true") || val == (str% "false") then + let boolCtor := Name.mkStr2 (str% "Bool") val + let targetName := if st.env.contains boolCtor then boolCtor else Name.simple val + match mkConstWithFreshMVarLevelsPure ctx st targetName with + | .error e => .error e + | .ok (e, _) st1 => ensureHasTypePure ctx st1 fuel stx e expectedType? + else errPure ctx (str% "unexpected atom in term") (some stx) + -- 3. Composite syntax nodes + | .node _ kindF args => + let kind := FName.toIxName kindF + -- 3.1. Hole `_` + if kind == SyntaxKind.holeTerm then + let (ty, st1) := match expectedType? with + | some t => (t, st) + | none => + let (u, s1) := mkFreshLevelMVarPure st + mkFreshExprMVarPure ctx s1 (Expr.mkSort u) + let (mv, st2) := mkFreshExprMVarPure ctx st1 ty + .ok mv st2 + -- 3.2. `Prop` + else if kind == SyntaxKind.propTerm then + ensureHasTypePure ctx st fuel stx Expr.mkProp expectedType? + -- 3.3. `Type [u]` + else if kind == SyntaxKind.typeTerm then + let argNode := args.getD 1 .missing + let lvlRes : ElabRes Ix.Level := + if Syntax.isNone argNode || Syntax.isMissing argNode then .ok Level.mkZero st + else if Syntax.isOfKind argNode SyntaxKind.nullKind then + match Syntax.getOptional? argNode with + | some lStx => elabLevelPure ctx fuel st lStx + | none => .ok Level.mkZero st + else elabLevelPure ctx fuel st argNode + match lvlRes with + | .error e => .error e + | .ok lvl st1 => ensureHasTypePure ctx st1 fuel stx (Expr.mkSort (Level.mkSucc lvl)) expectedType? + -- 3.4. `Sort [u]` + else if kind == SyntaxKind.sortTerm then + let optNode := args.getD 1 .missing + let lvlRes : ElabRes Ix.Level := match Syntax.getOptional? optNode with + | some lStx => elabLevelPure ctx fuel st lStx + | none => .ok Level.mkZero st + match lvlRes with + | .error e => .error e + | .ok lvl st1 => ensureHasTypePure ctx st1 fuel stx (Expr.mkSort lvl) expectedType? + -- 3.5. Numeric literal + else if kind == SyntaxKind.numLit then + let numStr := Syntax.getAtomVal (args.getD 0 .missing) + let rawLit := Expr.mkNatLit ((parseNatLiteral numStr).getD 0) + let ofNatName := Name.mkStr2 (str% "OfNat") (str% "ofNat") + let instOfNatNatName := Name.simple (str% "instOfNatNat") + let natConst := Expr.mkConst (Name.simple (str% "Nat")) #[] + let litExpr := + if st.env.contains ofNatName && st.env.contains instOfNatNatName then + let instExpr := Expr.mkApp (Expr.mkConst instOfNatNatName #[]) rawLit + Expr.mkAppN (Expr.mkConst ofNatName #[Level.mkZero]) #[natConst, rawLit, instExpr] + else rawLit + ensureHasKnownTypePure ctx st fuel stx litExpr natConst expectedType? + -- 3.6. String literal + else if kind == SyntaxKind.strLit then + let strVal := Syntax.getAtomVal (args.getD 0 .missing) + ensureHasTypePure ctx st fuel stx (Expr.mkStrLit strVal) expectedType? + -- 3.7. Character literal + else if kind == SyntaxKind.charLit then + let chStr := Syntax.getAtomVal (args.getD 0 .missing) + let code := match decodeUtf8Codepoints (Sym.ofString chStr) with + | c :: _ => c + | [] => 0 + let charOfNat := Name.mkStr2 (str% "Char") (str% "ofNat") + let res := + if st.env.contains charOfNat then Expr.mkApp (Expr.mkConst charOfNat #[]) (Expr.mkNatLit code) + else Expr.mkNatLit code + ensureHasTypePure ctx st fuel stx res expectedType? + -- 3.8. Content-hash reference `#<64-hex>` + else if kind == SyntaxKind.hashRef then + let hexStr := Syntax.getAtomVal (args.getD 0 .missing) + match parseHexAddress hexStr with + | none => errPure ctx (str% "invalid 64-hex-char content address") (some stx) + | some addr => + let foundName? := st.env.constOrder.find? fun nm => + Name.computeHash nm == addr || st.env.importMap.lookupName? nm == some addr + match foundName? with + | some nm => + match mkConstWithFreshMVarLevelsPure ctx st nm with + | .error e => .error e + | .ok (e, _) st1 => ensureHasTypePure ctx st1 fuel stx e expectedType? + | none => errPure ctx (str% "unresolved content address") (some stx) + -- 3.9. Explicit `@ident.{u, v}` or `ident.{u, v}` + else if kind == SyntaxKind.explicitTerm then + let isAt := Syntax.getAtomVal (args.getD 0 .missing) == (str% "@") + let idStx := if isAt then args.getD 1 .missing else args.getD 0 .missing + let univsNode := if isAt then args.getD 2 .missing else args.getD 1 .missing + let lvlsRes : ElabRes (Option (Array Ix.Level)) := + if Syntax.isNone univsNode then .ok none st + else + match elabLevelListPure ctx fuel st (Syntax.getArgs univsNode).toList [] with + | .error e => .error e + | .ok ls st1 => .ok (some ls) st1 + match lvlsRes with + | .error e => .error e + | .ok explicitLvls? st1 => + match elabIdentWithLevelsAndTypePure ctx st1 fuel idStx explicitLvls? with + | .error e => .error e + | .ok (e, _) st2 => + if isAt then + match expectedType? with + | none => .ok e st2 + | some expTy => + match inferTypePure ctx st2 fuel e with + | .error err => .error err + | .ok actTy st3 => + let (ok, st4) := isDefEqPure ctx st3 fuel actTy expTy + if !ok then errPure ctx (str% "type mismatch on @-explicit term") (some stx) + else .ok (instantiateMVarsPure st4.mctx 16 e) st4 + else ensureHasTypePure ctx st2 fuel stx e expectedType? + -- 3.10. Type ascription `(e : vPref T)` + else if kind == SyntaxKind.typeAscription then + let termStx := args.getD 1 .missing + let tyStx := args.getD 4 .missing + match elabTermCoreGo fuel ctx st tyStx none with + | .error e => .error e + | .ok ascTy st1 => + match ensureSortPure ctx st1 32 ascTy with + | .error e => .error e + | .ok _ st2 => + match elabTermCoreGo fuel ctx st2 termStx (some ascTy) with + | .error e => .error e + | .ok e st3 => ensureHasTypePure ctx st3 fuel stx e expectedType? + -- 3.11. Non-dependent function arrow `A → !B` + else if kind == SyntaxKind.arrowTerm then + let domStx := args.getD 0 .missing + let vPrefNode := args.getD 2 .missing + let codStx := args.getD 3 .missing + let isExpProp : Bool := match expectedType? with + | some (.sort (.zero _) _) => true + | _ => false + match elabTermCoreGo fuel ctx st domStx none with + | .error e => .error e + | .ok domTy st1 => + match ensureSortIfNotForallPure ctx st1 32 domTy with + | .error e => .error e + | .ok _ st2 => + let retContract := (decodeContractPrefix vPrefNode).toValueContract + let (fvId, _, ctx1, st3) := pushLocalDeclPure ctx st2 Name.mkAnon domTy .default default none none false + match elabTermCoreGo fuel ctx1 st3 codStx (if isExpProp then some Expr.mkProp else none) with + | .error e => .error e + | .ok cTy st4 => + let sortOk : ElabRes Unit := + if !isExpProp then ensureSortIfNotForallPure ctx1 st4 32 cTy else .ok () st4 + match sortOk with + | .error e => .error e + | .ok _ st5 => + let codTy := abstractFVar fvId cTy + let arrowExpr := Expr.mkForallContract Name.mkAnon domTy codTy .default default retContract + if isExpProp then .ok (instantiateMVarsPure st5.mctx 16 arrowExpr) st5 + else ensureHasTypePure ctx st5 fuel stx arrowExpr expectedType? + -- 3.12. Dependent Pi `forall binders, vPref body` + else if kind == SyntaxKind.forallTerm then + let isKw := match args[0]? with + | some (.atom _ kw) => Sym.beq kw (s% "forall") || Sym.beq kw (s% "∀") + | _ => false + let bindersNode := if isKw then args.getD 1 .missing else args.getD 0 .missing + let vPrefNode := if isKw then args.getD 3 .missing else args.getD 2 .missing + let bodyStx := if isKw then args.getD 4 .missing else args.getD 3 .missing + let retContract := (decodeContractPrefix vPrefNode).toValueContract + let isExpProp : Bool := match expectedType? with + | some (.sort (.zero _) _) => true + | _ => false + let groups := (Syntax.getArgs bindersNode).toList.map decodeBinderNode + match elabBindersGo fuel ctx st (flattenBinderGroups groups) [] with + | .error e => .error e + | .ok (fvars, ctx1) st1 => + match elabTermCoreGo fuel ctx1 st1 bodyStx (if isExpProp then some Expr.mkProp else none) with + | .error e => .error e + | .ok bodyTy st2 => + let sortOk : ElabRes Unit := + if !isExpProp then ensureSortIfNotForallPure ctx1 st2 32 bodyTy else .ok () st2 + match sortOk with + | .error e => .error e + | .ok _ st3 => + let piExpr := mkForallFVarsPure ctx1 fvars bodyTy retContract + if isExpProp then .ok (instantiateMVarsPure st3.mctx 16 piExpr) st3 + else ensureHasTypePure ctx st3 fuel stx piExpr expectedType? + -- 3.13. Lambda `fun binders => body` + else if kind == SyntaxKind.funTerm then + let bindersNode := args.getD 1 .missing + let bodyStx := args.getD 3 .missing + let groups := (Syntax.getArgs bindersNode).toList.map decodeBinderNode + match elabFunItemsGo fuel ctx st bodyStx (flattenBinderGroups groups) expectedType? #[] with + | .error e => .error e + | .ok lamExpr st1 => ensureHasTypePure ctx st1 fuel stx lamExpr expectedType? + -- 3.14. `let` and `let borrow` + else if kind == SyntaxKind.letTerm || kind == SyntaxKind.letBorrowTerm then + elabTermLetGo fuel ctx st kind stx args expectedType? + -- 3.14b. `let rec` + else if kind == SyntaxKind.letRecTerm then + elabTermLetRecGo fuel ctx st stx args expectedType? + -- 3.15. `have h [: T] := v; body` + else if kind == SyntaxKind.haveTerm then + elabTermHaveGo fuel ctx st stx args expectedType? + -- 3.16. Projection `base.field` or `base.0` + else if kind == SyntaxKind.projTerm then + let baseStx := args.getD 0 .missing + let fieldStx := args.getD 2 .missing + match elabTermCoreGo fuel ctx st baseStx none with + | .error e => .error e + | .ok baseExpr st1 => + match elabProjOnExprPure ctx st1 fuel baseExpr fieldStx with + | .error e => .error e + | .ok projExpr st2 => ensureHasTypePure ctx st2 fuel stx projExpr expectedType? + -- 3.17. Binary infix operator `lhs op rhs` + else if kind == SyntaxKind.binOpTerm then + elabTermBinOpGo fuel ctx st stx args expectedType? + -- 3.18. Unary operator (`¬`, `!`, `-`) + else if kind == SyntaxKind.unaryOpTerm then + let opSym := Syntax.getAtomVal (args.getD 0 .missing) + let argStx := args.getD 1 .missing + let fnName := + if opSym == (str% "¬") then Name.simple (str% "Not") + else if opSym == (str% "!") then Name.mkStr2 (str% "Bool") (str% "not") + else Name.mkStr2 (str% "Neg") (str% "neg") + let appStx := Syntax.mkNode SyntaxKind.appTerm #[Syntax.mkSimpleIdent fnName, argStx] + elabTermCoreGo fuel ctx st appStx expectedType? + -- 3.19. Anonymous constructor `⟨a₁, ..., aₙ⟩` + else if kind == SyntaxKind.anonCtor then + elabTermAnonCtorGo fuel ctx st stx args expectedType? + -- 3.20. Structure instance `{ [base with] field₁ := val₁, ... }` + else if kind == SyntaxKind.structInst then + elabTermStructInstGo fuel ctx st stx args expectedType? + -- 3.21. Tuple `(a, b, ...)` + else if kind == SyntaxKind.tupleTerm then + if args.size == 2 then + let unitCtor := + if st.env.contains (Name.mkStr2 (str% "Unit") (str% "unit")) then Name.mkStr2 (str% "Unit") (str% "unit") + else Name.mkStr2 (str% "PUnit") (str% "unit") + match mkConstWithFreshMVarLevelsPure ctx st unitCtor with + | .error e => .error e + | .ok (e, _) st1 => ensureHasTypePure ctx st1 fuel stx e expectedType? + else + let first := args.getD 1 .missing + let rest := (Syntax.getArgs (args.getD 3 .missing)).toList + elabTermCoreGo fuel ctx st (buildTuplePairsStx (first :: rest)) expectedType? + -- 3.22. List literal `[a, b, c]` + else if kind == SyntaxKind.listLit then + let elems := (Syntax.getArgs (args.getD 1 .missing)).toList + elabTermCoreGo fuel ctx st (buildListLitStx elems) expectedType? + -- 3.23. `if [h :] cond then t else e` + else if kind == SyntaxKind.ifTerm then + elabTermIfGo fuel ctx st stx args expectedType? + -- 3.24. Pattern matching `match d with | pat => rhs ...` + else if kind == SyntaxKind.matchTerm then + elabTermMatchGo fuel ctx st stx args expectedType? + -- 3.25. Core tactic block `by tac₁; ...` + else if kind == SyntaxKind.byTactic then + let tacSeq := args.getD 1 .missing + let (goalTy, st1) := match expectedType? with + | some t => (t, st) + | none => + let (u, s1) := mkFreshLevelMVarPure st + mkFreshExprMVarPure ctx s1 (Expr.mkSort u) + let (rootGoal, st2) := mkFreshExprMVarPure ctx st1 goalTy (Name.simple (str% "goal")) + let rootGoalId := match rootGoal with + | .mvar id _ => id + | _ => Name.mkAnon + let tk := Syntax.getKind tacSeq + let tacRes : ElabRes Unit := + if tk == SyntaxKind.tacticSeq || tk == SyntaxKind.nullKind then + runCoreTacListGo fuel ctx st2 rootGoalId (Syntax.getArgs tacSeq).toList + else + runCoreTacStepGo fuel ctx st2 tacSeq rootGoalId + match tacRes with + | .error e => .error e + | .ok _ st3 => + let solved := instantiateMVarsPure st3.mctx 32 rootGoal + ensureHasTypePure ctx st3 fuel stx solved expectedType? + -- 3.26. Function application `f a₁ ... aₙ` + else if kind == SyntaxKind.appTerm then + elabTermAppGo fuel ctx st stx expectedType? + else + errPure ctx (str% "unsupported syntax node in term") (some stx) + + + +termination_by f _ _ _ _ => (f, 0, 0) +decreasing_by all_goals (first | (apply Prod.Lex.left; omega) | (apply Prod.Lex.right; apply Prod.Lex.left; omega) | (apply Prod.Lex.right; apply Prod.Lex.right; first | exact Nat.lt_succ_self _ | (try simp only [List.length_cons]; omega))) + +def elabBindersGo (fuel : Nat) (c0 : ElabContext) (s0 : ElabState) : + List FlatBinderItem → List Ix.Name → ElabRes (Array Ix.Name × ElabContext) + | [], revFVs => .ok (Array.mk revFVs.reverse, c0) s0 + | item :: rest, revFVs => + let domRes : ElabRes Ix.Expr := match item.typeStx? with + | some tyStx => + match elabTermCoreGo fuel c0 s0 tyStx none with + | .error e => .error e + | .ok ty s1 => + match ensureSortPure c0 s1 32 ty with + | .error e => .error e + | .ok _ s2 => .ok ty s2 + | none => + let (u, s1) := mkFreshLevelMVarPure s0 + let (mv, s2) := mkFreshExprMVarPure c0 s1 (Expr.mkSort u) item.name + .ok mv s2 + match domRes with + | .error e => .error e + | .ok domTy s' => + let (fvId, _, c', s'') := pushLocalDeclPure c0 s' item.name domTy item.binderInfo item.contract none none false + elabBindersGo fuel c' s'' rest (fvId :: revFVs) + +termination_by xs _ => (fuel, 1, xs.length) +decreasing_by all_goals (first | (apply Prod.Lex.left; omega) | (apply Prod.Lex.right; apply Prod.Lex.left; omega) | (apply Prod.Lex.right; apply Prod.Lex.right; first | exact Nat.lt_succ_self _ | (try simp only [List.length_cons]; omega))) + +def elabFunItemsGo (fuel : Nat) (c0 : ElabContext) (s0 : ElabState) + (bodyStx : Stx) : List FlatBinderItem → Option Ix.Expr → Array Ix.Name → ElabRes Ix.Expr + | [], curExp?, curFVars => + match elabTermCoreGo fuel c0 s0 bodyStx curExp? with + | .error e => .error e + | .ok bodyExpr s1 => .ok (mkLambdaFVarsPure c0 curFVars bodyExpr) s1 + | item :: restItems, curExp?, curFVars => + let (expDom?, nextExpFn?) := match curExp? with + | some eTy => + let eTyW := whnfPure c0 s0 32 eTy + match stripMData eTyW with + | .forallE _ d b _ _ => (some d, some b) + | _ => (none, none) + | none => (none, none) + let domRes : ElabRes Ix.Expr := match item.typeStx? with + | some tyStx => + match elabTermCoreGo fuel c0 s0 tyStx none with + | .error e => .error e + | .ok t s1 => + match ensureSortPure c0 s1 32 t with + | .error e => .error e + | .ok _ s2 => + match expDom? with + | some expD => + let (_, s3) := isDefEqPure c0 s2 32 t expD + .ok t s3 + | none => .ok t s2 + | none => + match expDom? with + | some expD => .ok expD s0 + | none => + let (u, s1) := mkFreshLevelMVarPure s0 + let (mv, s2) := mkFreshExprMVarPure c0 s1 (Expr.mkSort u) item.name + .ok mv s2 + match domRes with + | .error e => .error e + | .ok domTy s' => + let (fvId, fvExpr, c', s'') := pushLocalDeclPure c0 s' item.name domTy item.binderInfo item.contract none none false + let nextExp? := nextExpFn?.map fun b => instantiate1 b fvExpr + elabFunItemsGo fuel c' s'' bodyStx restItems nextExp? (curFVars.push fvId) + +termination_by xs _ _ => (fuel, 1, xs.length) +decreasing_by all_goals (first | (apply Prod.Lex.left; omega) | (apply Prod.Lex.right; apply Prod.Lex.left; omega) | (apply Prod.Lex.right; apply Prod.Lex.right; first | exact Nat.lt_succ_self _ | (try simp only [List.length_cons]; omega))) + +def elabAnonElemsGo (fuel : Nat) (c0 : ElabContext) (s0 : ElabState) (stxRef : Stx) : + List Stx → Ix.Expr → Ix.Expr → ElabRes Ix.Expr + | [], curFn, _ => .ok curFn s0 + | eStx :: rest, curFn, curTy => + let curTyInst := instantiateMVarsPure s0.mctx 16 curTy + let curTyWhnf := whnfPure c0 s0 fuel curTyInst + match stripMData curTyWhnf with + | .forallE _ d b _ _ => + match elabTermCoreGo fuel c0 s0 eStx (some (betaReduceExpr d)) with + | .error e => .error e + | .ok fValExpr s1 => + elabAnonElemsGo fuel c0 s1 stxRef rest (Expr.mkApp curFn fValExpr) (instantiate1 b fValExpr) + | _ => errPure c0 (str% "too many arguments in anonymous constructor") (some stxRef) + +termination_by xs _ _ => (fuel, 1, xs.length) +decreasing_by all_goals (first | (apply Prod.Lex.left; omega) | (apply Prod.Lex.right; apply Prod.Lex.left; omega) | (apply Prod.Lex.right; apply Prod.Lex.right; first | exact Nat.lt_succ_self _ | (try simp only [List.length_cons]; omega))) + +def elabStructFieldsGo (fuel : Nat) (c0 : ElabContext) (s0 : ElabState) (stxRef : Stx) + (structName : Ix.Name) (assignedMap : NameMap Stx) (baseExpr? : Option Ix.Expr) : + List StructFieldInfo → Ix.Expr → Ix.Expr → ElabRes Ix.Expr + | [], curFn, _ => .ok curFn s0 + | fInfo :: rest, curFn, curTy => + let curTyWhnf := whnfPure c0 s0 fuel curTy + match stripMData curTyWhnf with + | .forallE _ d b _ _ => + let fValRes : ElabRes Ix.Expr := match assignedMap.get? fInfo.fieldName with + | some vStx => elabTermCoreGo fuel c0 s0 vStx (some d) + | none => + match baseExpr?, fInfo.defaultVal with + | some bExpr, _ => .ok (Expr.mkProj structName fInfo.fieldIdx bExpr) s0 + | none, some defStx => elabTermCoreGo fuel c0 s0 defStx (some d) + | none, none => errPure c0 (str% "missing field in structure") (some stxRef) + match fValRes with + | .error e => .error e + | .ok fValExpr s1 => + elabStructFieldsGo fuel c0 s1 stxRef structName assignedMap baseExpr? rest + (Expr.mkApp curFn fValExpr) (instantiate1 b fValExpr) + | _ => errPure c0 (str% "unexpected constructor type for structure") (some stxRef) + +termination_by xs _ _ => (fuel, 1, xs.length) +decreasing_by all_goals (first | (apply Prod.Lex.left; omega) | (apply Prod.Lex.right; apply Prod.Lex.left; omega) | (apply Prod.Lex.right; apply Prod.Lex.right; first | exact Nat.lt_succ_self _ | (try simp only [List.length_cons]; omega))) + +def elabCtorFieldsGo (fuel : Nat) (c0 : ElabContext) (s0 : ElabState) (stxRef : Stx) + (ctorName : Ix.Name) (indUnivs : Array Ix.Level) (params : Array Ix.Expr) + (resTy : Ix.Expr) (ctorVars? : Option (Array Ix.Name)) (catchVar? : Option Ix.Name) + (rhsStx : Stx) : Nat → Ix.Expr → Nat → Array Ix.Name → Array Ix.Expr → ElabRes Ix.Expr + | 0, _, _, fvarIds, fvarExprs => + match catchVar? with + | some vName => + if !Name.isAnonymous vName then + let ctorApp := Expr.mkAppN (Expr.mkConst ctorName indUnivs) (params ++ fvarExprs) + match inferTypePure c0 s0 fuel ctorApp with + | .error e => .error e + | .ok ctorAppTy s1 => + let (_, _, c', s2) := pushLocalDeclPure c0 s1 vName ctorAppTy .default default (some ctorApp) (some .value) false + match elabTermCoreGo fuel c' s2 rhsStx (some resTy) with + | .error e => .error e + | .ok rhsExpr s3 => .ok (mkLambdaFVarsPure c' fvarIds rhsExpr) s3 + else + match elabTermCoreGo fuel c0 s0 rhsStx (some resTy) with + | .error e => .error e + | .ok rhsExpr s1 => .ok (mkLambdaFVarsPure c0 fvarIds rhsExpr) s1 + | none => + match elabTermCoreGo fuel c0 s0 rhsStx (some resTy) with + | .error e => .error e + | .ok rhsExpr s1 => .ok (mkLambdaFVarsPure c0 fvarIds rhsExpr) s1 + | rem + 1, curCtorTy, fIdx, fvarIds, fvarExprs => + let curW := whnfPure c0 s0 fuel curCtorTy + match stripMData curW with + | .forallE defName fDom fBody _ _ => + let userVarName := match ctorVars? with + | some vs => + let vn := vs.getD fIdx Name.mkAnon + if Name.isAnonymous vn then defName else vn + | none => defName + let (fvId, fvExpr, c', s1) := pushLocalDeclPure c0 s0 userVarName fDom .default default none none false + elabCtorFieldsGo fuel c' s1 stxRef ctorName indUnivs params resTy ctorVars? catchVar? rhsStx + rem (instantiate1 fBody fvExpr) (fIdx + 1) (fvarIds.push fvId) (fvarExprs.push fvExpr) + | _ => errPure c0 (str% "unexpected constructor type") (some stxRef) + +termination_by rem _ _ _ _ => (fuel, 1, rem) +decreasing_by all_goals (first | (apply Prod.Lex.left; omega) | (apply Prod.Lex.right; apply Prod.Lex.left; omega) | (apply Prod.Lex.right; apply Prod.Lex.right; first | exact Nat.lt_succ_self _ | (try simp only [List.length_cons]; omega))) + +def elabMatchCtorsGo (fuel : Nat) (c0 : ElabContext) (s0 : ElabState) (stxRef : Stx) + (ival : Ix.InductiveVal) (alts : Array Stx) (indUnivs : Array Ix.Level) + (params : Array Ix.Expr) (resTy : Ix.Expr) : + List Ix.Name → List Ix.Expr → ElabRes (Array Ix.Expr) + | [], revMinors => .ok (Array.mk revMinors.reverse) s0 + | ctorName :: restCtors, revMinors => + match s0.env.find? ctorName with + | some (.ctorInfo cval) => + let matchedAlt? := alts.findSome? fun alt => + let pats := Syntax.getArgs (Syntax.getArg alt 1) + let rhsStx := Syntax.getArg alt 3 + let pat0 := pats.getD 0 .missing + if Syntax.isOfKind pat0 SyntaxKind.anonCtor && ival.ctors.size == 1 then + let pElems := Syntax.getArgs (Syntax.getArg pat0 1) + if cval.numFields >= 2 && pElems.size > cval.numFields then + let preIds := (pElems.extract 0 (cval.numFields - 1)).map fun a => + if Syntax.isOfKind a SyntaxKind.holeTerm || Syntax.getAtomVal a == (str% "_") then Name.mkAnon + else Syntax.getId a + let restElems := pElems.extract (cval.numFields - 1) pElems.size + let tmpId := Name.mkNat (Name.simple (str% "_anon_pat")) restElems.size + let nestedPat := Syntax.mkNode SyntaxKind.anonCtor + #[Syntax.mkSimpleAtom (str% "⟨"), Syntax.mkNullNode restElems, Syntax.mkSimpleAtom (str% "⟩")] + let nestedAlt := Syntax.mkNode SyntaxKind.matchAlt + #[Syntax.mkSimpleAtom (str% "|"), Syntax.mkNullNode #[nestedPat], + Syntax.mkSimpleAtom (str% "=>"), rhsStx] + let nestedMatch := Syntax.mkNode SyntaxKind.matchTerm + #[Syntax.mkSimpleAtom (str% "match"), Syntax.mkNullNode #[Syntax.mkSimpleIdent tmpId], + Syntax.mkSimpleAtom (str% "with"), Syntax.mkNullNode #[nestedAlt]] + some (some (preIds.push tmpId), none, nestedMatch) + else + let varNames := pElems.map fun a => + if Syntax.isOfKind a SyntaxKind.holeTerm || Syntax.getAtomVal a == (str% "_") then Name.mkAnon + else Syntax.getId a + some (some varNames, none, rhsStx) + else + match decodeConstructorPattern c0.scope c0.modIdx s0.env pat0 with + | some (patCtor, varNames) => + if patCtor == ctorName then some (some varNames, none, rhsStx) else none + | none => + let catchVar := + if Syntax.isOfKind pat0 SyntaxKind.holeTerm || Syntax.getAtomVal pat0 == (str% "_") then + Name.mkAnon + else Syntax.getId pat0 + some (none, some catchVar, rhsStx) + match matchedAlt? with + | none => errPure c0 (str% "non-exhaustive match") (some stxRef) + | some (ctorVars?, catchVar?, rhsStx) => + let ctorInstTy := params.foldl (fun cur p => + match stripMData cur with + | .forallE _ _ b _ _ => instantiate1 b p + | other => other) (substExprLevelParams cval.cnst.levelParams indUnivs cval.cnst.type) + match elabCtorFieldsGo fuel c0 s0 stxRef ctorName indUnivs params resTy ctorVars? catchVar? rhsStx + cval.numFields ctorInstTy 0 #[] #[] with + | .error e => .error e + | .ok minorLam s1 => + elabMatchCtorsGo fuel c0 s1 stxRef ival alts indUnivs params resTy restCtors (minorLam :: revMinors) + | _ => errPure c0 (str% "missing constructor info") (some stxRef) + +termination_by xs _ => (fuel, 2, xs.length) +decreasing_by all_goals (first | (apply Prod.Lex.left; omega) | (apply Prod.Lex.right; apply Prod.Lex.left; omega) | (apply Prod.Lex.right; apply Prod.Lex.right; first | exact Nat.lt_succ_self _ | (try simp only [List.length_cons]; omega))) + +def applyAppArgsGo (fuel : Nat) (c0 : ElabContext) (s0 : ElabState) (isExplicitAt : Bool) : + List Stx → Ix.Expr → Ix.Expr → List Ix.Expr → ElabRes (Ix.Expr × Ix.Expr × List Ix.Expr) + | [], curFn, curTy, pending => .ok (curFn, curTy, pending) s0 + | argStx :: rest, curFn, curTy, pending => + let ((curFn1, pending1, curTy1), s1) := + if !isExplicitAt then insertImplicitArgsPure c0 s0 16 curFn curTy pending + else ((curFn, pending, curTy), s0) + let curTyWhnf := whnfForallPure c0 s1 fuel curTy1 + match stripMData curTyWhnf with + | .forallE _ dom body _ _ => + match elabTermCoreGo fuel c0 s1 argStx (some dom) with + | .error e => .error e + | .ok argExpr s2 => + applyAppArgsGo fuel c0 s2 isExplicitAt rest (Expr.mkApp curFn1 argExpr) (instantiate1 body argExpr) pending1 + | _ => + let (u1, s2) := mkFreshLevelMVarPure s1 + let (u2, s3) := mkFreshLevelMVarPure s2 + let (domMVar, s4) := mkFreshExprMVarPure c0 s3 (Expr.mkSort u1) + let (codMVar, s5) := mkFreshExprMVarPure c0 s4 (Expr.mkSort u2) + let arrowTy := Expr.mkArrow domMVar (liftLooseBVars codMVar 1) + let (_, s6) := isDefEqPure c0 s5 fuel curTyWhnf arrowTy + match elabTermCoreGo fuel c0 s6 argStx (some domMVar) with + | .error e => .error e + | .ok argExpr s7 => + applyAppArgsGo fuel c0 s7 isExplicitAt rest (Expr.mkApp curFn1 argExpr) codMVar pending1 + +termination_by xs _ _ _ => (fuel, 1, xs.length) +decreasing_by all_goals (first | (apply Prod.Lex.left; omega) | (apply Prod.Lex.right; apply Prod.Lex.left; omega) | (apply Prod.Lex.right; apply Prod.Lex.right; first | exact Nat.lt_succ_self _ | (try simp only [List.length_cons]; omega))) + +def runCoreTacStepGo (fuel : Nat) (c0 : ElabContext) (s0 : ElabState) (tac : Stx) (goalId : Ix.Name) : ElabRes Unit := + match s0.mctx.findDecl? goalId with + | none => errPure c0 (str% "unknown goal metavariable") (some tac) + | some gDecl => + let gTy := instantiateMVarsPure s0.mctx 32 gDecl.type + let gCtx : ElabContext := { c0 with lctx := gDecl.lctx } + let k := Syntax.getKind tac + if k == SyntaxKind.tacticRfl || k == SyntaxKind.tacticTrivial then + let gTyW := whnfPure gCtx s0 fuel gTy + let (hFn, hArgs) := getAppFnArgs gTyW + match hFn with + | .const cName cUnivs _ => + if cName == Name.simple (str% "Eq") && hArgs.size == 3 then + let tyArg := hArgs.getD 0 gTyW + let lhs := hArgs.getD 1 gTyW + let rhs := hArgs.getD 2 gTyW + let (ok, s1) := isDefEqPure gCtx s0 fuel lhs rhs + if !ok then errPure c0 (str% "'rfl' failed: sides are not definitionally equal") (some tac) + else + let reflExpr := Expr.mkAppN + (Expr.mkConst (Name.mkStr2 (str% "Eq") (str% "refl")) #[cUnivs.getD 0 Level.mkZero]) + #[tyArg, lhs] + .ok () (setMCtxPure s1 (s1.mctx.assignExpr goalId reflExpr)) + else if cName == Name.simple (str% "True") && hArgs.isEmpty then + .ok () (setMCtxPure s0 (s0.mctx.assignExpr goalId (Expr.mkConst (Name.mkStr2 (str% "True") (str% "intro")) #[]))) + else errPure c0 (str% "'rfl' failed: goal is not a reflexive equality") (some tac) + | _ => errPure c0 (str% "'rfl' failed: goal is not an equality") (some tac) + else if k == SyntaxKind.tacticExact then + let termStx := Syntax.getArg tac 1 + match elabTermCoreGo fuel gCtx s0 termStx (some gTy) with + | .error e => .error e + | .ok val s1 => + let valInst := instantiateMVarsPure s1.mctx 32 val + .ok () (setMCtxPure s1 (s1.mctx.assignExpr goalId valInst)) + else if k == SyntaxKind.tacticAssumption then + let rec findAssump (sA : ElabState) : List LocalDecl → Option Ix.Expr × ElabState + | [] => (none, sA) + | d :: rest => + let dTy := instantiateMVarsPure sA.mctx 16 d.type + let (ok, sB) := isDefEqPure gCtx sA fuel dTy gTy + if ok then (some (Expr.mkFVar d.fvarId), sB) else findAssump sB rest + match findAssump s0 gDecl.lctx.revDecls with + | (some fv, s1) => .ok () (setMCtxPure s1 (s1.mctx.assignExpr goalId fv)) + | (none, _) => errPure c0 (str% "'assumption' failed") (some tac) + else if k == SyntaxKind.tacticDone then .ok () s0 + else errPure c0 (str% "tactic requires full tactic prover") (some tac) + +termination_by (fuel, 1, 0) +decreasing_by all_goals (first | (apply Prod.Lex.left; omega) | (apply Prod.Lex.right; apply Prod.Lex.left; omega) | (apply Prod.Lex.right; apply Prod.Lex.right; first | exact Nat.lt_succ_self _ | (try simp only [List.length_cons]; omega))) + +def runCoreTacListGo (fuel : Nat) (c0 : ElabContext) (s0 : ElabState) (goalId : Ix.Name) : List Stx → ElabRes Unit + | [] => .ok () s0 + | t :: rest => + match runCoreTacStepGo fuel c0 s0 t goalId with + | .error e => .error e + | .ok _ s1 => runCoreTacListGo fuel c0 s1 goalId rest + +termination_by xs => (fuel, 2, xs.length) +decreasing_by all_goals (first | (apply Prod.Lex.left; omega) | (apply Prod.Lex.right; apply Prod.Lex.left; omega) | (apply Prod.Lex.right; apply Prod.Lex.right; first | exact Nat.lt_succ_self _ | (try simp only [List.length_cons]; omega))) + +def elabTermLetGo (fuel : Nat) (ctx : ElabContext) (st : ElabState) + (kind : Ix.Name) (stx : Stx) (args : Stx) (expectedType? : Option Ix.Expr) : ElabRes Ix.Expr := + let isBorrow := kind == SyntaxKind.letBorrowTerm + let bPrefNode := if isBorrow then args.getD 2 .missing else args.getD 1 .missing + let idStx := if isBorrow then args.getD 3 .missing else args.getD 2 .missing + let bindersNode := if isBorrow then args.getD 4 .missing else args.getD 3 .missing + let optTyNode := if isBorrow then args.getD 5 .missing else args.getD 4 .missing + let valStx := if isBorrow then args.getD 7 .missing else args.getD 6 .missing + let bodyStx := if isBorrow then args.getD 9 .missing else args.getD 8 .missing + let letName := + let id := Syntax.getId idStx + if Name.isAnonymous id then Name.simple (str% "x") else id + let bParsed := decodeContractPrefix bPrefNode + let (vParsed, optTyStx?) := + if Syntax.getNumArgs optTyNode >= 3 then + (decodeContractPrefix (Syntax.getArg optTyNode 1), some (Syntax.getArg optTyNode 2)) + else ({}, none) + let merged := mergeParsedContracts bParsed vParsed + let isBorrowMode := isBorrow || merged.isBorrow + let binderContract : Ixon.BinderContract := + if isBorrowMode then { uses := merged.uses.getD .many, value := .localShared } + else merged.toBinderContract + let letKind : Ixon.LetKind := if isBorrowMode then .borrowShared else .value + let paramGroups := (Syntax.getArgs bindersNode).toList.map decodeBinderNode + match elabBindersGo fuel ctx st (flattenBinderGroups paramGroups) [] with + | .error e => .error e + | .ok (fvars, ctx1) st1 => + let expValTyRes : ElabRes (Option Ix.Expr) := match optTyStx? with + | some tyStx => + match elabTermCoreGo fuel ctx1 st1 tyStx none with + | .error e => .error e + | .ok t st2 => + match ensureSortPure ctx1 st2 32 t with + | .error e => .error e + | .ok _ st3 => .ok (some t) st3 + | none => .ok none st1 + match expValTyRes with + | .error e => .error e + | .ok expValTy? st2 => + match elabTermCoreGo fuel ctx1 st2 valStx expValTy? with + | .error e => .error e + | .ok vExpr st3 => + let vTyRes : ElabRes Ix.Expr := match expValTy? with + | some t => .ok t st3 + | none => inferTypePure ctx1 st3 fuel vExpr + match vTyRes with + | .error e => .error e + | .ok vTy st4 => + let letTy := mkForallFVarsPure ctx1 fvars vTy + let letVal := mkLambdaFVarsPure ctx1 fvars vExpr + let (fvId, _, ctx2, st5) := pushLocalDeclPure ctx st4 letName letTy .default binderContract (some letVal) (some letKind) false + match elabTermCoreGo fuel ctx2 st5 bodyStx expectedType? with + | .error e => .error e + | .ok bodyExpr st6 => + let nonDep := !containsFVar fvId bodyExpr + let absBody := abstractFVar fvId bodyExpr + let lc : Ixon.LetContract := { nonDep, kind := letKind, binder := binderContract } + let st7 : ElabState := { st6 with localLetContracts := st6.localLetContracts.push lc } + let letExpr := Expr.mkLetContract letName letTy letVal absBody nonDep binderContract letKind + ensureHasTypePure ctx2 st7 fuel stx letExpr expectedType? +termination_by (fuel, 3, 0) +decreasing_by all_goals (first | (apply Prod.Lex.left; omega) | (apply Prod.Lex.right; apply Prod.Lex.left; omega) | (apply Prod.Lex.right; apply Prod.Lex.right; first | exact Nat.lt_succ_self _ | (try simp only [List.length_cons]; omega))) + +def elabTermLetRecGo (fuel : Nat) (ctx : ElabContext) (st : ElabState) + (stx : Stx) (args : Stx) (expectedType? : Option Ix.Expr) : ElabRes Ix.Expr := + let bPrefNode := args.getD 2 .missing + let idStx := args.getD 3 .missing + let bindersNode := args.getD 4 .missing + let optTyNode := args.getD 5 .missing + let valStx := args.getD 7 .missing + let bodyStx := args.getD 9 .missing + let letName := + let id := Syntax.getId idStx + if Name.isAnonymous id then Name.simple (str% "recFn") else id + let bParsed := decodeContractPrefix bPrefNode + let (vParsed, optTyStx?) := + if Syntax.getNumArgs optTyNode >= 3 then + (decodeContractPrefix (Syntax.getArg optTyNode 1), some (Syntax.getArg optTyNode 2)) + else ({}, none) + let binderContract : Ixon.BinderContract := (mergeParsedContracts bParsed vParsed).toBinderContract + let paramGroups := (Syntax.getArgs bindersNode).toList.map decodeBinderNode + let flatParams := flattenBinderGroups paramGroups + match elabBindersGo fuel ctx st flatParams [] with + | .error e => .error e + | .ok (fvars0, ctx0) st1 => + let retTyRes : ElabRes Ix.Expr := match optTyStx? with + | some tyStx => + match elabTermCoreGo fuel ctx0 st1 tyStx none with + | .error e => .error e + | .ok t st2 => + match ensureSortIfNotForallPure ctx0 st2 32 t with + | .error e => .error e + | .ok _ st3 => .ok t st3 + | none => + let (u, s1) := mkFreshLevelMVarPure st1 + let (mv, s2) := mkFreshExprMVarPure ctx0 s1 (Expr.mkSort u) + .ok mv s2 + match retTyRes with + | .error e => .error e + | .ok retTy st2 => + let letTy := mkForallFVarsPure ctx0 fvars0 retTy + let (recFvId, _, ctxRec, st3) := pushLocalDeclPure ctx st2 letName letTy .default binderContract none none false + match elabBindersGo fuel ctxRec st3 flatParams [] with + | .error e => .error e + | .ok (fvars, ctx1) st4 => + let expValTyRes : ElabRes (Option Ix.Expr) := match optTyStx? with + | some tyStx => + match elabTermCoreGo fuel ctx1 st4 tyStx none with + | .error e => .error e + | .ok t st5 => + match ensureSortIfNotForallPure ctx1 st5 32 t with + | .error e => .error e + | .ok _ st6 => .ok (some t) st6 + | none => .ok none st4 + match expValTyRes with + | .error e => .error e + | .ok expValTy? st5 => + let vExprRes : ElabRes Ix.Expr := + if Syntax.isOfKind valStx SyntaxKind.nullKind then + let targetFvId? := + (fvars.find? fun fvId => + match ctx1.lctx.findFVar? fvId with + | some d => d.binderInfo == .default && !stxMentionsPure d.userName 64 valStx + | none => false).orElse (fun _ => fvars.back?) + match targetFvId? with + | some lastFvId => + let lastName := match ctx1.lctx.findFVar? lastFvId with + | some d => d.userName + | none => Name.simple (str% "x") + let matchStx := Syntax.mkNode SyntaxKind.matchTerm + #[Syntax.mkSimpleAtom (str% "match"), Syntax.mkNullNode #[Syntax.mkSimpleIdent lastName], + Syntax.mkSimpleAtom (str% "with"), valStx] + elabTermCoreGo fuel ctx1 st5 matchStx expValTy? + | none => errPure ctx1 (str% "pattern-matching 'let rec' requires at least one parameter") (some stx) + else elabTermCoreGo fuel ctx1 st5 valStx expValTy? + match vExprRes with + | .error e => .error e + | .ok vExpr st6 => + let vTyRes : ElabRes Ix.Expr := match expValTy? with + | some t => .ok t st6 + | none => inferTypePure ctx1 st6 fuel vExpr + match vTyRes with + | .error e => .error e + | .ok vTy st7 => + let fullTy := mkForallFVarsPure ctx1 fvars vTy + let (_, st8) := isDefEqPure ctx1 st7 fuel letTy fullTy + let rawVal := mkLambdaFVarsPure ctx1 fvars vExpr + let rawValInst := instantiateMVarsPure st8.mctx 32 rawVal + let letTyInst := instantiateMVarsPure st8.mctx 32 letTy + let letVal := tryLowerStructuralRecToRecOn st8.env recFvId rawValInst + let (fvId, _, ctx2, st9) := pushLocalDeclPure ctx st8 letName letTyInst .default binderContract (some letVal) (some .value) false + match elabTermCoreGo fuel ctx2 st9 bodyStx expectedType? with + | .error e => .error e + | .ok bodyExpr st10 => + let nonDep := !containsFVar fvId bodyExpr + let absBody := abstractFVar fvId bodyExpr + let lc : Ixon.LetContract := { nonDep, kind := .value, binder := binderContract } + let st11 : ElabState := { st10 with localLetContracts := st10.localLetContracts.push lc } + let letExpr := Expr.mkLetContract letName letTyInst letVal absBody nonDep binderContract .value + ensureHasTypePure ctx2 st11 fuel stx letExpr expectedType? +termination_by (fuel, 3, 0) +decreasing_by all_goals (first | (apply Prod.Lex.left; omega) | (apply Prod.Lex.right; apply Prod.Lex.left; omega) | (apply Prod.Lex.right; apply Prod.Lex.right; first | exact Nat.lt_succ_self _ | (try simp only [List.length_cons]; omega))) + +def elabTermHaveGo (fuel : Nat) (ctx : ElabContext) (st : ElabState) + (stx : Stx) (args : Stx) (expectedType? : Option Ix.Expr) : ElabRes Ix.Expr := + let idStx := args.getD 1 .missing + let optTyNode := args.getD 2 .missing + let valStx := args.getD 4 .missing + let bodyStx := args.getD 6 .missing + let hName := + let id := Syntax.getId idStx + if Name.isAnonymous id then Name.simple (str% "h") else id + let expTyRes : ElabRes (Option Ix.Expr) := + if Syntax.getNumArgs optTyNode >= 2 then + match elabTermCoreGo fuel ctx st (Syntax.getArg optTyNode 1) none with + | .error e => .error e + | .ok t st1 => + match ensureSortPure ctx st1 32 t with + | .error e => .error e + | .ok _ st2 => .ok (some t) st2 + else .ok none st + match expTyRes with + | .error e => .error e + | .ok expTy? st1 => + match elabTermCoreGo fuel ctx st1 valStx expTy? with + | .error e => .error e + | .ok vExpr st2 => + let vTyRes : ElabRes Ix.Expr := match expTy? with + | some t => .ok t st2 + | none => inferTypePure ctx st2 fuel vExpr + match vTyRes with + | .error e => .error e + | .ok vTy st3 => + let (fvId, _, ctx1, st4) := pushLocalDeclPure ctx st3 hName vTy .default default (some vExpr) (some .value) true + match elabTermCoreGo fuel ctx1 st4 bodyStx expectedType? with + | .error e => .error e + | .ok bodyExpr st5 => + let absBody := abstractFVar fvId bodyExpr + let lc : Ixon.LetContract := { nonDep := true, kind := .value, binder := default } + let st6 : ElabState := { st5 with localLetContracts := st5.localLetContracts.push lc } + let res := Expr.mkLetE hName vTy vExpr absBody true + ensureHasTypePure ctx1 st6 fuel stx res expectedType? +termination_by (fuel, 3, 0) +decreasing_by all_goals (first | (apply Prod.Lex.left; omega) | (apply Prod.Lex.right; apply Prod.Lex.left; omega) | (apply Prod.Lex.right; apply Prod.Lex.right; first | exact Nat.lt_succ_self _ | (try simp only [List.length_cons]; omega))) + +def elabTermBinOpGo (fuel : Nat) (ctx : ElabContext) (st : ElabState) + (stx : Stx) (args : Stx) (expectedType? : Option Ix.Expr) : ElabRes Ix.Expr := + let lhsStx := args.getD 0 .missing + let opAtom := args.getD 1 .missing + let rhsStx := args.getD 2 .missing + let symS := Syntax.getAtomSym opAtom + let sym := Sym.toString symS + let targetName? := (findBuiltinOpTarget? sym).orElse fun _ => + ((defaultOperators.find? (fun op => op.symbol == symS)).bind (·.targetFn)).map FName.toIxName + match targetName? with + | none => errPure ctx (str% "unknown binary operator") (some stx) + | some targetName => + let natConst := Expr.mkConst (Name.simple (str% "Nat")) #[] + let zLvl := Level.mkZero + if (sym == (str% "=") && st.env.contains (Name.simple (str% "Eq"))) || + (sym == (str% "≠") && st.env.contains (Name.simple (str% "Ne"))) then + let relName := if sym == (str% "=") then Name.simple (str% "Eq") else Name.simple (str% "Ne") + match elabTermCoreGo fuel ctx st lhsStx none with + | .error e => .error e + | .ok lhs st1 => + match inferTypePure ctx st1 fuel lhs with + | .error e => .error e + | .ok lhsTyRaw st2 => + let lhsTy := instantiateMVarsPure st2.mctx 16 lhsTyRaw + match elabTermCoreGo fuel ctx st2 rhsStx (some lhsTy) with + | .error e => .error e + | .ok rhs st3 => + let lhsTyFinal := instantiateMVarsPure st3.mctx 16 lhsTy + let uRes : ElabRes Ix.Level := + if lhsTyFinal == natConst then .ok (Level.mkSucc zLvl) st3 + else + match ensureSortPure ctx st3 32 lhsTyFinal with + | .error e => .error e + | .ok u st4 => .ok (normalizeLevel u) st4 + match uRes with + | .error e => .error e + | .ok uNorm st4 => + let relExpr := Expr.mkAppN (Expr.mkConst relName #[uNorm]) #[lhsTyFinal, lhs, rhs] + ensureHasKnownTypePure ctx st4 fuel stx relExpr Expr.mkProp expectedType? + else if (sym == (str% "+") && st.env.contains (Name.mkStr2 (str% "HAdd") (str% "hAdd")) && + st.env.contains (Name.simple (str% "instHAdd")) && st.env.contains (Name.simple (str% "instAddNat"))) || + (sym == (str% "^") && st.env.contains (Name.mkStr2 (str% "HPow") (str% "hPow")) && + st.env.contains (Name.simple (str% "instHPow")) && st.env.contains (Name.simple (str% "instPowNat")) && + st.env.contains (Name.simple (str% "instNatPowNat"))) || + ((sym == (str% "≤") || sym == (str% "<=")) && st.env.contains (Name.mkStr2 (str% "LE") (str% "le")) && + st.env.contains (Name.simple (str% "instLENat"))) || + ((sym == (str% "≥") || sym == (str% ">=")) && st.env.contains (Name.mkStr2 (str% "GE") (str% "ge")) && + st.env.contains (Name.simple (str% "instLENat"))) || + (sym == (str% "<") && st.env.contains (Name.mkStr2 (str% "LT") (str% "lt")) && + st.env.contains (Name.simple (str% "instLTNat"))) || + (sym == (str% ">") && st.env.contains (Name.mkStr2 (str% "GT") (str% "gt")) && + st.env.contains (Name.simple (str% "instLTNat"))) then + match elabTermCoreGo fuel ctx st lhsStx (if sym == (str% "+") || sym == (str% "^") then expectedType? else none) with + | .error e => .error e + | .ok lhs st1 => + match inferTypePure ctx st1 fuel lhs with + | .error e => .error e + | .ok lhsTyRaw st2 => + let lhsTy := instantiateMVarsPure st2.mctx 16 lhsTyRaw + match elabTermCoreGo fuel ctx st2 rhsStx (some lhsTy) with + | .error e => .error e + | .ok rhs st3 => + let lhsTyFinal := instantiateMVarsPure st3.mctx 16 lhsTy + if lhsTyFinal == natConst then + if sym == (str% "+") then + let instAdd := Expr.mkConst (Name.simple (str% "instAddNat")) #[] + let instHAdd := Expr.mkAppN (Expr.mkConst (Name.simple (str% "instHAdd")) #[zLvl]) #[natConst, instAdd] + let addExpr := Expr.mkAppN (Expr.mkConst (Name.mkStr2 (str% "HAdd") (str% "hAdd")) #[zLvl, zLvl, zLvl]) + #[natConst, natConst, natConst, instHAdd, lhs, rhs] + ensureHasKnownTypePure ctx st3 fuel stx addExpr natConst expectedType? + else if sym == (str% "^") then + let instNatPow := Expr.mkConst (Name.simple (str% "instNatPowNat")) #[] + let instPow := Expr.mkAppN (Expr.mkConst (Name.simple (str% "instPowNat")) #[zLvl]) #[natConst, instNatPow] + let instHPow := Expr.mkAppN (Expr.mkConst (Name.simple (str% "instHPow")) #[zLvl, zLvl]) #[natConst, natConst, instPow] + let powExpr := Expr.mkAppN (Expr.mkConst (Name.mkStr2 (str% "HPow") (str% "hPow")) #[zLvl, zLvl, zLvl]) + #[natConst, natConst, natConst, instHPow, lhs, rhs] + ensureHasKnownTypePure ctx st3 fuel stx powExpr natConst expectedType? + else if sym == (str% "≤") || sym == (str% "<=") then + let instLE := Expr.mkConst (Name.simple (str% "instLENat")) #[] + let leExpr := Expr.mkAppN (Expr.mkConst (Name.mkStr2 (str% "LE") (str% "le")) #[zLvl]) #[natConst, instLE, lhs, rhs] + ensureHasKnownTypePure ctx st3 fuel stx leExpr Expr.mkProp expectedType? + else if sym == (str% "≥") || sym == (str% ">=") then + let instLE := Expr.mkConst (Name.simple (str% "instLENat")) #[] + let geExpr := Expr.mkAppN (Expr.mkConst (Name.mkStr2 (str% "GE") (str% "ge")) #[zLvl]) #[natConst, instLE, lhs, rhs] + ensureHasKnownTypePure ctx st3 fuel stx geExpr Expr.mkProp expectedType? + else if sym == (str% "<") then + let instLT := Expr.mkConst (Name.simple (str% "instLTNat")) #[] + let ltExpr := Expr.mkAppN (Expr.mkConst (Name.mkStr2 (str% "LT") (str% "lt")) #[zLvl]) #[natConst, instLT, lhs, rhs] + ensureHasKnownTypePure ctx st3 fuel stx ltExpr Expr.mkProp expectedType? + else + let instLT := Expr.mkConst (Name.simple (str% "instLTNat")) #[] + let gtExpr := Expr.mkAppN (Expr.mkConst (Name.mkStr2 (str% "GT") (str% "gt")) #[zLvl]) #[natConst, instLT, lhs, rhs] + ensureHasKnownTypePure ctx st3 fuel stx gtExpr Expr.mkProp expectedType? + else + let fnIdStx := Syntax.mkSimpleIdent targetName + let appStx := Syntax.mkNode SyntaxKind.appTerm + #[Syntax.mkNode SyntaxKind.appTerm #[fnIdStx, lhsStx], rhsStx] + elabTermCoreGo fuel ctx st3 appStx expectedType? + else + let actualFnName? : Option Ix.Name := + if st.env.contains targetName then some targetName + else if sym == (str% "+") then if st.env.contains (Name.mkStr2 (str% "Nat") (str% "add")) then some (Name.mkStr2 (str% "Nat") (str% "add")) else none + else if sym == (str% "-") then if st.env.contains (Name.mkStr2 (str% "Nat") (str% "sub")) then some (Name.mkStr2 (str% "Nat") (str% "sub")) else none + else if sym == (str% "*") then if st.env.contains (Name.mkStr2 (str% "Nat") (str% "mul")) then some (Name.mkStr2 (str% "Nat") (str% "mul")) else none + else if sym == (str% "/") then if st.env.contains (Name.mkStr2 (str% "Nat") (str% "div")) then some (Name.mkStr2 (str% "Nat") (str% "div")) else none + else if sym == (str% "%") then if st.env.contains (Name.mkStr2 (str% "Nat") (str% "mod")) then some (Name.mkStr2 (str% "Nat") (str% "mod")) else none + else if sym == (str% "^") then if st.env.contains (Name.mkStr2 (str% "Nat") (str% "pow")) then some (Name.mkStr2 (str% "Nat") (str% "pow")) else none + else if sym == (str% "==") then if st.env.contains (Name.mkStr2 (str% "Nat") (str% "beq")) then some (Name.mkStr2 (str% "Nat") (str% "beq")) else none + else if sym == (str% "≤") || sym == (str% "<=") then if st.env.contains (Name.mkStr2 (str% "Nat") (str% "ble")) then some (Name.mkStr2 (str% "Nat") (str% "ble")) else none + else none + let fnName := match actualFnName? with + | some n => n + | none => + match Name.components targetName with + | _ :: last :: _ => Name.simple last + | [only] => Name.simple only + | [] => targetName + let fnIdStx := Syntax.mkSimpleIdent fnName + let appStx := Syntax.mkNode SyntaxKind.appTerm + #[Syntax.mkNode SyntaxKind.appTerm #[fnIdStx, lhsStx], rhsStx] + elabTermCoreGo fuel ctx st appStx expectedType? +termination_by (fuel, 3, 0) +decreasing_by all_goals (first | (apply Prod.Lex.left; omega) | (apply Prod.Lex.right; apply Prod.Lex.left; omega) | (apply Prod.Lex.right; apply Prod.Lex.right; first | exact Nat.lt_succ_self _ | (try simp only [List.length_cons]; omega))) + +def elabTermAnonCtorGo (fuel : Nat) (ctx : ElabContext) (st : ElabState) + (stx : Stx) (args : Stx) (expectedType? : Option Ix.Expr) : ElabRes Ix.Expr := + let elemStxs := Syntax.getArgs (args.getD 1 .missing) + match expectedType? with + | none => errPure ctx (str% "anonymous constructor requires a known expected type") (some stx) + | some expTy => + let expTyWhnf := whnfPure ctx st fuel expTy + let (headFn, expArgs) := getAppFnArgs expTyWhnf + match headFn with + | .const indName _ _ => + match st.env.find? indName with + | some (.inductInfo ival) => + match ival.ctors[0]? with + | some ctorName => + let numFields? := match st.env.find? ctorName with + | some (.ctorInfo cval) => some cval.numFields + | _ => none + let effectiveElems : Array Stx := + match numFields? with + | some nf => + if nf >= 2 && elemStxs.size > nf then + let pre := elemStxs.extract 0 (nf - 1) + let rest := elemStxs.extract (nf - 1) elemStxs.size + let nestedAnon := Syntax.mkNode SyntaxKind.anonCtor + #[Syntax.mkSimpleAtom (str% "⟨"), Syntax.mkNullNode rest, Syntax.mkSimpleAtom (str% "⟩")] + pre.push nestedAnon + else elemStxs + | none => elemStxs + match mkConstWithFreshMVarLevelsPure ctx st ctorName with + | .error e => .error e + | .ok (ctorConst, ctorTy) st1 => + let ((ctorApplied, instGoals, afterParamsTy), st2) := insertImplicitArgsPure ctx st1 16 ctorConst ctorTy [] + let (_, ctorParamMVars) := getAppFnArgs ctorApplied + let st3 := unifyExprPairsPure ctx fuel st2 (ctorParamMVars.toList.zip (expArgs.toList.take ival.numParams)) + match elabAnonElemsGo fuel ctx st3 stx effectiveElems.toList ctorApplied afterParamsTy with + | .error e => .error e + | .ok curFn st4 => + let st5 := solveInstGoalsPure ctx fuel st4 instGoals + let res := instantiateMVarsPure st5.mctx 32 curFn + ensureHasTypePure ctx st5 fuel stx res (some expTyWhnf) + | none => errPure ctx (str% "inductive has no constructors") (some stx) + | _ => errPure ctx (str% "expected inductive/structure type") (some stx) + | _ => errPure ctx (str% "expected known inductive or structure type") (some stx) +termination_by (fuel, 3, 0) +decreasing_by all_goals (first | (apply Prod.Lex.left; omega) | (apply Prod.Lex.right; apply Prod.Lex.left; omega) | (apply Prod.Lex.right; apply Prod.Lex.right; first | exact Nat.lt_succ_self _ | (try simp only [List.length_cons]; omega))) + +def elabTermStructInstGo (fuel : Nat) (ctx : ElabContext) (st : ElabState) + (stx : Stx) (args : Stx) (expectedType? : Option Ix.Expr) : ElabRes Ix.Expr := + let withNode := args.getD 1 .missing + let assignsNode := args.getD 2 .missing + let baseRes : ElabRes (Option Ix.Expr) := + if Syntax.isNone withNode || Syntax.isMissing withNode then .ok none st + else + let bStx := if Syntax.isOfKind withNode SyntaxKind.nullKind then Syntax.getArg withNode 0 else withNode + match elabTermCoreGo fuel ctx st bStx expectedType? with + | .error e => .error e + | .ok b st1 => .ok (some b) st1 + match baseRes with + | .error e => .error e + | .ok baseExpr? st1 => + let expTyRes : ElabRes Ix.Expr := match expectedType?, baseExpr? with + | _, some b => + match inferTypePure ctx st1 fuel b with + | .error e => .error e + | .ok bTy st2 => .ok (whnfPure ctx st2 fuel bTy) st2 + | some t, none => .ok (whnfPure ctx st1 fuel t) st1 + | none, none => errPure ctx (str% "structure literal requires an expected structure type") (some stx) + match expTyRes with + | .error e => .error e + | .ok expTy st2 => + let (headFn, expArgs) := getAppFnArgs expTy + match headFn with + | .const structName _ _ => + match st2.env.structTable.get? structName with + | none => errPure ctx (str% "not a registered structure") (some stx) + | some sInfo => + let assignedMap : NameMap Stx := + (Syntax.getArgs assignsNode).toList.foldl (fun acc assignStx => + acc.insert (Syntax.getId (Syntax.getArg assignStx 0)) (Syntax.getArg assignStx 2)) NameMap.empty + match mkConstWithFreshMVarLevelsPure ctx st2 sInfo.ctorName with + | .error e => .error e + | .ok (ctorConst, ctorTy) st3 => + let ((ctorApplied, instGoals, afterParamsTy), st4) := insertImplicitArgsPure ctx st3 16 ctorConst ctorTy [] + let (_, ctorParamMVars) := getAppFnArgs ctorApplied + let st5 := unifyExprPairsPure ctx fuel st4 (ctorParamMVars.toList.zip expArgs.toList) + match elabStructFieldsGo fuel ctx st5 stx structName assignedMap baseExpr? sInfo.fields.toList ctorApplied afterParamsTy with + | .error e => .error e + | .ok curFn st6 => + let st7 := solveInstGoalsPure ctx fuel st6 instGoals.reverse + ensureHasTypePure ctx st7 fuel stx curFn (some expTy) + | _ => errPure ctx (str% "structure literal requires a known structure type") (some stx) +termination_by (fuel, 3, 0) +decreasing_by all_goals (first | (apply Prod.Lex.left; omega) | (apply Prod.Lex.right; apply Prod.Lex.left; omega) | (apply Prod.Lex.right; apply Prod.Lex.right; first | exact Nat.lt_succ_self _ | (try simp only [List.length_cons]; omega))) + +def elabTermIfGo (fuel : Nat) (ctx : ElabContext) (st : ElabState) + (stx : Stx) (args : Stx) (expectedType? : Option Ix.Expr) : ElabRes Ix.Expr := + let isDep := args.size == 8 + let condStx := if isDep then args.getD 3 .missing else args.getD 2 .missing + let thenStx := if isDep then args.getD 5 .missing else args.getD 4 .missing + let elseStx := if isDep then args.getD 7 .missing else args.getD 6 .missing + if isDep && st.env.contains (Name.simple (str% "dite")) && st.env.contains (Name.simple (str% "Decidable")) then + let hId := Syntax.getId (args.getD 1 .missing) + match elabTermCoreGo fuel ctx st condStx (some Expr.mkProp) with + | .error e => .error e + | .ok condProp st1 => + let notCondProp := Expr.mkApp (Expr.mkConst (Name.simple (str% "Not")) #[]) condProp + let (branchTy, st2) := match expectedType? with + | some t => (t, st1) + | none => + let (u, s1) := mkFreshLevelMVarPure st1 + mkFreshExprMVarPure ctx s1 (Expr.mkSort u) + let (hFv1, _, ctx1, st3) := pushLocalDeclPure ctx st2 hId condProp .default default none none false + match elabTermCoreGo fuel ctx1 st3 thenStx (some branchTy) with + | .error e => .error e + | .ok tVal st4 => + let thenLam := mkLambdaFVarsPure ctx1 #[hFv1] tVal + let (hFv2, _, ctx2, st5) := pushLocalDeclPure ctx st4 hId notCondProp .default default none none false + match elabTermCoreGo fuel ctx2 st5 elseStx (some branchTy) with + | .error e => .error e + | .ok eVal st6 => + let elseLam := mkLambdaFVarsPure ctx2 #[hFv2] eVal + match ensureSortPure ctx st6 32 branchTy with + | .error e => .error e + | .ok branchSort st7 => + let decTy := Expr.mkApp (Expr.mkConst (Name.simple (str% "Decidable")) #[]) condProp + let (decInst, st8) := match synthInstancePure ctx 8 st7 decTy with + | (some inst, s1) => (inst, s1) + | (none, s1) => mkFreshExprMVarPure ctx s1 decTy + let res := Expr.mkAppN (Expr.mkConst (Name.simple (str% "dite")) #[branchSort]) + #[branchTy, condProp, decInst, thenLam, elseLam] + ensureHasTypePure ctx st8 fuel stx res expectedType? + else if st.env.contains (Name.mkStr2 (str% "Bool") (str% "casesOn")) then + let boolTy := Expr.mkConst (Name.simple (str% "Bool")) #[] + let boolAttempt : ElabRes Ix.Expr := + match elabTermCoreGo fuel ctx st condStx (some boolTy) with + | .error e => .error e + | .ok condExpr st1 => + let (branchTy, st2) := match expectedType? with + | some t => (t, st1) + | none => + let (u, s1) := mkFreshLevelMVarPure st1 + mkFreshExprMVarPure ctx s1 (Expr.mkSort u) + match elabTermCoreGo fuel ctx st2 thenStx (some branchTy) with + | .error e => .error e + | .ok thenExpr st3 => + match elabTermCoreGo fuel ctx st3 elseStx (some branchTy) with + | .error e => .error e + | .ok elseExpr st4 => + match ensureSortPure ctx st4 32 branchTy with + | .error e => .error e + | .ok branchSort st5 => + let motive := Expr.mkLam (Name.simple (str% "b")) boolTy (liftLooseBVars branchTy 1) .default + let casesOnConst := Expr.mkConst (Name.mkStr2 (str% "Bool") (str% "casesOn")) #[branchSort] + let res := Expr.mkAppN casesOnConst #[motive, condExpr, elseExpr, thenExpr] + ensureHasTypePure ctx st5 fuel stx res expectedType? + match boolAttempt with + | .ok res stOk => .ok res stOk + | .error _ => + let iteId := Syntax.mkSimpleIdent (Name.simple (str% "ite")) + let appStx := #[condStx, thenStx, elseStx].foldl + (fun acc a => Syntax.mkNode SyntaxKind.appTerm #[acc, a]) iteId + elabTermCoreGo fuel ctx st appStx expectedType? + else + let iteId := Syntax.mkSimpleIdent (Name.simple (str% "ite")) + let appStx := #[condStx, thenStx, elseStx].foldl + (fun acc a => Syntax.mkNode SyntaxKind.appTerm #[acc, a]) iteId + elabTermCoreGo fuel ctx st appStx expectedType? +termination_by (fuel, 3, 0) +decreasing_by all_goals (first | (apply Prod.Lex.left; omega) | (apply Prod.Lex.right; apply Prod.Lex.left; omega) | (apply Prod.Lex.right; apply Prod.Lex.right; first | exact Nat.lt_succ_self _ | (try simp only [List.length_cons]; omega))) + +def elabTermMatchGo (fuel : Nat) (ctx : ElabContext) (st : ElabState) + (stx : Stx) (args : Stx) (expectedType? : Option Ix.Expr) : ElabRes Ix.Expr := + let discrs := Syntax.getArgs (args.getD 1 .missing) + let alts := Syntax.getArgs (args.getD 3 .missing) + if discrs.isEmpty then errPure ctx (str% "match expression requires at least one discriminant") (some stx) + else + let discrStx := discrs.getD 0 .missing + match elabTermCoreGo fuel ctx st discrStx none with + | .error e => .error e + | .ok discrExpr st1 => + match inferTypePure ctx st1 fuel discrExpr with + | .error e => .error e + | .ok discrTy st2 => + let discrTyWhnf := whnfPure ctx st2 fuel discrTy + let (headFn, headArgs) := getAppFnArgs discrTyWhnf + let (resTy, st3) := match expectedType? with + | some t => (t, st2) + | none => + let (u, s1) := mkFreshLevelMVarPure st2 + mkFreshExprMVarPure ctx s1 (Expr.mkSort u) + match headFn with + | .const indName indUnivs _ => + match st3.env.find? indName with + | some (.inductInfo ival) => + let casesOnName := Name.mkStr indName (str% "casesOn") + match st3.env.find? casesOnName with + | some (.defnInfo casesOnDef) => + let univsRes : ElabRes (Array Ix.Level) := + if casesOnDef.cnst.levelParams.size == indUnivs.size + 1 then + match ensureSortPure ctx st3 32 resTy with + | .error e => .error e + | .ok uMot st4 => .ok (#[uMot] ++ indUnivs) st4 + else .ok indUnivs st3 + match univsRes with + | .error e => .error e + | .ok casesOnUnivs st4 => + let params := headArgs.extract 0 ival.numParams + let indices := headArgs.extract ival.numParams headArgs.size + let afterParamsInst := params.foldl (fun cur p => + match stripMData cur with + | .forallE _ _ b _ _ => instantiate1 b p + | other => other) (substExprLevelParams ival.cnst.levelParams indUnivs ival.cnst.type) + let (idxFVars, idxDecls, _) := openForallTelescope ival.numIndices afterParamsInst (str% "midx") 0 #[] #[] + let majDom := Expr.mkAppN (Expr.mkConst indName indUnivs) (params ++ idxFVars) + let (majFvId, _) := mkAuxFVar (str% "mmaj") 0 + let majDecl : AuxLocalDecl := { fvarId := majFvId, binderName := Name.simple (str% "x"), domain := majDom } + let motiveLam := closeLambdas (idxDecls.push majDecl) resTy + match elabMatchCtorsGo fuel ctx st4 stx ival alts indUnivs params resTy ival.ctors.toList [] with + | .error e => .error e + | .ok minorExprs st5 => + let fullApp := Expr.mkAppN (Expr.mkConst casesOnName casesOnUnivs) + (params ++ #[motiveLam] ++ indices ++ #[discrExpr] ++ minorExprs) + ensureHasTypePure ctx st5 fuel stx fullApp (some resTy) + | _ => errPure ctx (str% "casesOn not found for match expression") (some stx) + | _ => errPure ctx (str% "discriminant type is not an inductive type") (some stx) + | _ => errPure ctx (str% "match discriminant must have an inductive type") (some discrStx) +termination_by (fuel, 3, 0) +decreasing_by all_goals (first | (apply Prod.Lex.left; omega) | (apply Prod.Lex.right; apply Prod.Lex.left; omega) | (apply Prod.Lex.right; apply Prod.Lex.right; first | exact Nat.lt_succ_self _ | (try simp only [List.length_cons]; omega))) + +def elabTermAppGo (fuel : Nat) (ctx : ElabContext) (st : ElabState) + (stx : Stx) (expectedType? : Option Ix.Expr) : ElabRes Ix.Expr := + let (fnStx, argStxs) := flattenAppSyntax 256 stx [] + let isExplicitAt := + Syntax.isOfKind fnStx SyntaxKind.explicitTerm && + Syntax.getAtomVal (Syntax.getArg fnStx 0) == (str% "@") + let fnRes : ElabRes (Ix.Expr × Ix.Expr) := match fnStx with + | .ident .. => elabIdentWithLevelsAndTypePure ctx st fuel fnStx none + | _ => + match elabTermCoreGo fuel ctx st fnStx none with + | .error e => .error e + | .ok e st1 => + match inferTypePure ctx st1 fuel e with + | .error err => .error err + | .ok t st2 => .ok (e, t) st2 + match fnRes with + | .error e => .error e + | .ok (fnExpr, fnTy) st1 => + match applyAppArgsGo fuel ctx st1 isExplicitAt argStxs.toList fnExpr fnTy [] with + | .error e => .error e + | .ok (curFn, curTy, pendingInstGoals) st2 => + let st3 := solveInstGoalsPure ctx fuel st2 pendingInstGoals.reverse + ensureHasKnownTypePure ctx st3 fuel stx curFn curTy expectedType? +termination_by (fuel, 3, 0) +decreasing_by all_goals (first | (apply Prod.Lex.left; omega) | (apply Prod.Lex.right; apply Prod.Lex.left; omega) | (apply Prod.Lex.right; apply Prod.Lex.right; first | exact Nat.lt_succ_self _ | (try simp only [List.length_cons]; omega))) + +end + +@[inline] def elabTermCoreDirect (ctx : ElabContext) (st : ElabState) (fuel : Nat) (stx : Stx) + (expectedType? : Option Ix.Expr) : ElabRes Ix.Expr := + elabTermCoreGo fuel ctx st stx expectedType? + +/-! ## Section 5: First-Order Module & SCC Elaborator (`elabModuleSyntaxCorePure`) -/ + +def elabBinderGroupsCorePure (ctx : ElabContext) (st : ElabState) (fuel : Nat) + (groups : List ParsedBinderGroup) : ElabRes (Array Ix.Name × ElabContext) := + let rec go (c0 : ElabContext) (s0 : ElabState) : + List FlatBinderItem → List Ix.Name → ElabRes (Array Ix.Name × ElabContext) + | [], revFVs => .ok (Array.mk revFVs.reverse, c0) s0 + | item :: rest, revFVs => + let domRes : ElabRes Ix.Expr := match item.typeStx? with + | some tyStx => + match elabTermCoreDirect c0 s0 fuel tyStx none with + | .error e => .error e + | .ok ty s1 => + match ensureSortPure c0 s1 32 ty with + | .error e => .error e + | .ok _ s2 => .ok ty s2 + | none => + let (u, s1) := mkFreshLevelMVarPure s0 + let (mv, s2) := mkFreshExprMVarPure c0 s1 (Expr.mkSort u) item.name + .ok mv s2 + match domRes with + | .error e => .error e + | .ok domTy s' => + let (fvId, _, c', s'') := pushLocalDeclPure c0 s' item.name domTy item.binderInfo item.contract none none false + go c' s'' rest (fvId :: revFVs) + go ctx st (flattenBinderGroups groups) [] + +def elabInductiveHeaderCorePure (ctx : ElabContext) (st : ElabState) (decl : ModuleDecl) (fuel : Nat) : + ElabRes (Nat × Nat × Array Ix.Name × Ix.Expr) := + let st0 : ElabState := match st with + | ⟨env, _, nextIdx, _, _⟩ => ⟨env, {}, nextIdx, [], #[]⟩ + let cmd := decl.stx + let k := Syntax.getKind cmd + let bindersNode := Syntax.getArg cmd 4 + let optTypeNode := + if k == SyntaxKind.inductiveDecl then Syntax.getArg cmd 6 + else Syntax.getArg cmd 7 + let varGroups := decl.scope.varBinders.toList.map decodeBinderNode + let paramGroups := (Syntax.getArgs bindersNode).toList.map decodeBinderNode + let autoGroups := collectAutoImplicitGroups decl.scope ctx.modIdx st0.env varGroups paramGroups optTypeNode + let allGroups := varGroups ++ autoGroups ++ paramGroups + let ctx1 : ElabContext := { ctx with + lctx := LocalContext.empty + scope := decl.scope + currDecl? := some decl.fullName + univParams := decl.univParams } + match elabBinderGroupsCorePure ctx1 st0 fuel allGroups with + | .error e => .error e + | .ok (paramFVars, ctx2) st1 => + let resTyRes : ElabRes Ix.Expr := + if Syntax.isNone optTypeNode || Syntax.isMissing optTypeNode then + .ok (Expr.mkSort (Level.mkSucc Level.mkZero)) st1 + else + match elabTermCoreDirect ctx2 st1 fuel optTypeNode none with + | .error e => .error e + | .ok t st2 => + match ensureSortPure ctx2 st2 32 t with + | .error e => .error e + | .ok _ st3 => .ok (instantiateMVarsPure st3.mctx 32 t) st3 + match resTyRes with + | .error e => .error e + | .ok resultTy st2 => + let nIndices := countForalls 64 resultTy + let fullType := defaultUnassignedExprLevelMVars + (instantiateMVarsPure st2.mctx 32 (mkForallFVarsPure ctx2 paramFVars resultTy)) + let lvlParams := Array.mk (decl.univParams ++ decl.scope.levelNames ++ st2.autoBoundUnivs).eraseDups + .ok (paramFVars.size, nIndices, lvlParams, fullType) st2 + +def elabOneConstructorCorePure (ctx : ElabContext) (st : ElabState) (decl : ModuleDecl) + (lvlParams : Array Ix.Name) (paramGroups : List ParsedBinderGroup) + (ctorStx : Stx) (cidx : Nat) (fuel : Nat) : + ElabRes (Ix.ConstructorVal × Array Ixon.BinderContract × Ixon.ValueContract) := + let shortId := Syntax.getId (Syntax.getArg ctorStx 1) + let fullCtorName := Name.append decl.fullName shortId + let cBindersNode := Syntax.getArg ctorStx 2 + let cVPrefNode := Syntax.getArg ctorStx 3 + let cOptTypeNode := Syntax.getArg ctorStx 4 + let retContract := (decodeContractPrefix cVPrefNode).toValueContract + let cGroups := (Syntax.getArgs cBindersNode).toList.map decodeBinderNode + let implicitParamGroups := paramGroups.map fun g => { g with binderInfo := .implicit } + let ctx1 : ElabContext := { ctx with + lctx := LocalContext.empty + scope := decl.scope + currDecl? := some fullCtorName + univParams := lvlParams.toList } + match elabBinderGroupsCorePure ctx1 st fuel implicitParamGroups with + | .error e => .error e + | .ok (paramFVars, ctx2) st1 => + match elabBinderGroupsCorePure ctx2 st1 fuel cGroups with + | .error e => .error e + | .ok (fieldFVars, ctx3) st2 => + let indUnivs := lvlParams.map Level.mkParam + let paramExprs := paramFVars.map Expr.mkFVar + let defaultRet := Expr.mkAppN (Expr.mkConst decl.fullName indUnivs) paramExprs + let retRes : ElabRes (Ix.Expr × Nat) := + if Syntax.isNone cOptTypeNode || Syntax.isMissing cOptTypeNode then + .ok (defaultRet, 0) st2 + else + match elabTermCoreDirect ctx3 st2 fuel cOptTypeNode none with + | .error e => .error e + | .ok t st3 => + match ensureSortPure ctx3 st3 32 t with + | .error e => .error e + | .ok _ st4 => + let tInst := instantiateMVarsPure st4.mctx 32 t + .ok (tInst, countForalls 64 tInst) st4 + match retRes with + | .error e => .error e + | .ok (targetRet, extraFields) st3 => + let allFVars := paramFVars ++ fieldFVars + let fullCtorTy := defaultUnassignedExprLevelMVars + (instantiateMVarsPure st3.mctx 32 (mkForallFVarsPure ctx3 allFVars targetRet retContract)) + let bcs : Array Ixon.BinderContract := allFVars.filterMap fun fv => + (ctx3.lctx.findFVar? fv).map (·.contract) + let cval : Ix.ConstructorVal := { + cnst := { name := fullCtorName, levelParams := lvlParams, type := fullCtorTy } + induct := decl.fullName, cidx := cidx + numParams := paramFVars.size, numFields := fieldFVars.size + extraFields + isUnsafe := false + } + .ok (cval, bcs, retContract) st3 + +def elabStructureFieldsCorePure (ctx : ElabContext) (st : ElabState) (decl : ModuleDecl) + (lvlParams : Array Ix.Name) (paramGroups : List ParsedBinderGroup) + (ctorFullName : Ix.Name) (fieldsNode : Stx) (fuel : Nat) : + ElabRes (Ix.ConstructorVal × StructInfo × Array Ixon.BinderContract × Array Ix.DefinitionVal) := + let implicitParamGroups := paramGroups.map fun g => { g with binderInfo := .implicit } + let extendsNode := Syntax.getArg decl.stx 5 + let parentStxs := (Syntax.getArgs extendsNode).toList + let fieldItems := (Syntax.getArgs fieldsNode).toList + let ctx1 : ElabContext := { ctx with + lctx := LocalContext.empty + scope := decl.scope + currDecl? := some ctorFullName + univParams := lvlParams.toList } + match elabBinderGroupsCorePure ctx1 st fuel implicitParamGroups with + | .error e => .error e + | .ok (paramFVars, ctx2) st1 => + let flatFields : List (Ix.Name × Lean.BinderInfo × Ixon.BinderContract × Stx × Option Stx) := + fieldItems.flatMap fun item => + let firstAtom := Syntax.getAtomVal (Syntax.getArg item 0) + let (isBrack, bi) : Bool × Lean.BinderInfo := + if firstAtom == (str% "(") then (true, .default) + else if firstAtom == (str% "{") then (true, .implicit) + else (false, .default) + let bPrefNode := if isBrack then Syntax.getArg item 1 else Syntax.getArg item 0 + let idsNode := if isBrack then Syntax.getArg item 2 else Syntax.getArg item 1 + let vPrefNode := if isBrack then Syntax.getArg item 4 else Syntax.getArg item 3 + let tyNode := if isBrack then Syntax.getArg item 5 else Syntax.getArg item 4 + let optDef := if isBrack then Syntax.getArg item 6 else Syntax.getArg item 5 + let defStx? := (Syntax.getOptional? optDef).map fun seq => Syntax.getArg seq 1 + let contract := (mergeParsedContracts (decodeContractPrefix bPrefNode) (decodeContractPrefix vPrefNode)).toBinderContract + (Syntax.getArgs idsNode).toList.map fun idStx => + (Syntax.getId idStx, bi, contract, tyNode, defStx?) + + let rec elabParentFields (c0 : ElabContext) (s0 : ElabState) : + List StructFieldInfo → Ix.Expr → Nat → Array Ix.Name → Array StructFieldInfo → + ElabRes (Nat × Array Ix.Name × Array StructFieldInfo × ElabContext) + | [], _, fIdx, fvars, fInfos => .ok (fIdx, fvars, fInfos, c0) s0 + | pf :: restPF, curPCtorTy, fIdx, fvars, fInfos => + let curW := whnfPure c0 s0 fuel curPCtorTy + match stripMData curW with + | .forallE _ fDom fBody _ _ => + match fInfos.findIdx? (fun fi => fi.fieldName == pf.fieldName) with + | some existingIdx => + let existingFvExpr := Expr.mkFVar (fvars.getD existingIdx Name.mkAnon) + elabParentFields c0 s0 restPF (instantiate1 fBody existingFvExpr) fIdx fvars fInfos + | none => + let fDomInst := instantiateMVarsPure s0.mctx 32 fDom + let fInfo : StructFieldInfo := { + fieldName := pf.fieldName, projFnName := Name.append decl.fullName pf.fieldName + fieldIdx := fIdx, binderInfo := pf.binderInfo, contract := pf.contract, defaultVal := pf.defaultVal + } + let (fvId, fvExpr, c', s1) := pushLocalDeclPure c0 s0 pf.fieldName fDomInst pf.binderInfo pf.contract none none false + elabParentFields c' s1 restPF (instantiate1 fBody fvExpr) (fIdx + 1) (fvars.push fvId) (fInfos.push fInfo) + | _ => .ok (fIdx, fvars, fInfos, c0) s0 + + let rec elabParentsLoop (c0 : ElabContext) (s0 : ElabState) : + List Stx → Nat → Array Ix.Name → Array StructFieldInfo → + Array (Ix.Name × Array Ix.Level × Array Ix.Expr × StructInfo) → + ElabRes (Nat × Array Ix.Name × Array StructFieldInfo × Array (Ix.Name × Array Ix.Level × Array Ix.Expr × StructInfo) × ElabContext) + | [], fIdx, fvars, fInfos, parentSpecs => .ok (fIdx, fvars, fInfos, parentSpecs, c0) s0 + | pStx :: restP, fIdx, fvars, fInfos, parentSpecs => + match elabTermCoreDirect c0 s0 fuel pStx none with + | .error e => .error e + | .ok pTy s1 => + match ensureSortPure c0 s1 32 pTy with + | .error e => .error e + | .ok _ s2 => + let pTyW := whnfPure c0 s2 fuel (instantiateMVarsPure s2.mctx 32 pTy) + let (pHead, pArgs) := getAppFnArgs pTyW + match pHead with + | .const pStructName pUnivs _ => + match s2.env.structTable.get? pStructName with + | some pInfo => + match s2.env.find? pInfo.ctorName with + | some (.ctorInfo pCval) => + let pCtorInstTy := pArgs.foldl (fun cur pa => + match stripMData cur with + | .forallE _ _ b _ _ => instantiate1 b pa + | other => other) (substExprLevelParams pCval.cnst.levelParams pUnivs pCval.cnst.type) + match elabParentFields c0 s2 pInfo.fields.toList pCtorInstTy fIdx fvars fInfos with + | .error e => .error e + | .ok (fIdx', fvars', fInfos', c') s3 => + elabParentsLoop c' s3 restP fIdx' fvars' fInfos' (parentSpecs.push (pStructName, pUnivs, pArgs, pInfo)) + | _ => errPure c0 (str% "missing constructor for parent structure") (some pStx) + | none => errPure c0 (str% "parent in 'extends' is not a structure or class") (some pStx) + | _ => errPure c0 (str% "parent in 'extends' must be a structure or class application") (some pStx) + + let rec elabFieldLoop (c0 : ElabContext) (s0 : ElabState) : + List (Ix.Name × Lean.BinderInfo × Ixon.BinderContract × Stx × Option Stx) → + Nat → Array Ix.Name → Array StructFieldInfo → + ElabRes (Array Ix.Name × Array StructFieldInfo × ElabContext) + | [], _, fvars, fInfos => .ok (fvars, fInfos, c0) s0 + | (fShort, bi, contract, tyStx, defStx?) :: rest, fIdx, fvars, fInfos => + match fInfos.findIdx? (fun fi => fi.fieldName == fShort) with + | some existingIdx => + let fInfos' := match defStx? with + | some dStx => + if h : existingIdx < fInfos.size then + fInfos.set existingIdx { fInfos[existingIdx] with defaultVal := some dStx } + else fInfos + | none => fInfos + elabFieldLoop c0 s0 rest fIdx fvars fInfos' + | none => + match elabTermCoreDirect c0 s0 fuel tyStx none with + | .error e => .error e + | .ok fTy s1 => + match ensureSortPure c0 s1 32 fTy with + | .error e => .error e + | .ok _ s2 => + let fTyInst := instantiateMVarsPure s2.mctx 32 fTy + let fInfo : StructFieldInfo := { + fieldName := fShort, projFnName := Name.append decl.fullName fShort + fieldIdx := fIdx, binderInfo := bi, contract := contract, defaultVal := defStx? + } + let (fvId, _, c', s3) := pushLocalDeclPure c0 s2 fShort fTyInst bi contract none none false + elabFieldLoop c' s3 rest (fIdx + 1) (fvars.push fvId) (fInfos.push fInfo) + + match elabParentsLoop ctx2 st1 parentStxs 0 #[] #[] #[] with + | .error e => .error e + | .ok (fIdx0, fvars0, fInfos0, parentSpecs, ctxAfterParents) st2 => + match elabFieldLoop ctxAfterParents st2 flatFields fIdx0 fvars0 fInfos0 with + | .error e => .error e + | .ok (fieldFVars, fieldInfos, ctxAfterFields) st3 => + let indUnivs := lvlParams.map Level.mkParam + let paramExprs := paramFVars.map Expr.mkFVar + let retTy := Expr.mkAppN (Expr.mkConst decl.fullName indUnivs) paramExprs + let allFVars := paramFVars ++ fieldFVars + let ctorTy := defaultUnassignedExprLevelMVars + (instantiateMVarsPure st3.mctx 32 (mkForallFVarsPure ctxAfterFields allFVars retTy)) + let bcs : Array Ixon.BinderContract := allFVars.filterMap fun fv => + (ctxAfterFields.lctx.findFVar? fv).map (·.contract) + let cval : Ix.ConstructorVal := { + cnst := { name := ctorFullName, levelParams := lvlParams, type := ctorTy } + induct := decl.fullName, cidx := 0 + numParams := paramFVars.size, numFields := fieldFVars.size + isUnsafe := false + } + let sInfo : StructInfo := { + structName := decl.fullName, ctorName := ctorFullName + numParams := paramFVars.size, fields := fieldInfos + parents := parentSpecs.map (fun (pn, _, _, _) => pn) + isClass := decl.kind == .cls + } + let selfBi : Lean.BinderInfo := if decl.kind == .cls then .instImplicit else .default + let rec buildToParentDefs (s0 : ElabState) : + List (Ix.Name × Array Ix.Level × Array Ix.Expr × StructInfo) → + List Ix.DefinitionVal → Array Ix.DefinitionVal × ElabState + | [], revOut => (Array.mk revOut.reverse, s0) + | (pName, pUnivs, pArgs, pInfo) :: restPS, revOut => + let basePName := (Name.conflictOrigName? pName).getD pName + let pShort := (Name.components basePName).getLastD (str% "") + let toParentName := Name.mkStr decl.fullName (Sym.toString (Sym.append (s% "to") (Sym.ofString pShort))) + let pRetTy := Expr.mkAppN (Expr.mkConst pName pUnivs) pArgs + let (selfFvId, selfExpr, ctxSelf, s1) := pushLocalDeclPure ctxAfterFields s0 (Name.simple (str% "self")) retTy selfBi default none none false + let ctorCall := pInfo.fields.toList.foldl (fun acc pf => + let cIdx := (fieldInfos.find? (fun cf => cf.fieldName == pf.fieldName)).map (·.fieldIdx) |>.getD 0 + Expr.mkApp acc (Expr.mkProj decl.fullName cIdx selfExpr)) + (Expr.mkAppN (Expr.mkConst pInfo.ctorName pUnivs) pArgs) + let tpTy := defaultUnassignedExprLevelMVars + (instantiateMVarsPure s1.mctx 32 (mkForallFVarsPure ctxSelf (paramFVars.push selfFvId) pRetTy)) + let tpVal := defaultUnassignedExprLevelMVars + (instantiateMVarsPure s1.mctx 32 (mkLambdaFVarsPure ctxSelf (paramFVars.push selfFvId) ctorCall)) + let tpDef : Ix.DefinitionVal := { + cnst := { name := toParentName, levelParams := lvlParams, type := tpTy } + value := tpVal, hints := .abbrev, safety := .safe, all := #[toParentName] + } + buildToParentDefs s1 restPS (tpDef :: revOut) + let (toParentDefs, st4) := buildToParentDefs st3 parentSpecs.toList [] + .ok (cval, sInfo, bcs, toParentDefs) st4 + +def elabDerivingHandlersCorePure (ctx : ElabContext) (st : ElabState) + (decl : ModuleDecl) (ival : Ix.InductiveVal) (fuel : Nat) : ElabRes Unit := + let cmd := decl.stx + let k := Syntax.getKind cmd + let derivNode := + if k == SyntaxKind.inductiveDecl then Syntax.getArg cmd 8 + else Syntax.getArg cmd 10 + let derivIds := (Syntax.getArgs derivNode).toList.map Syntax.getId + if derivIds.isEmpty then .ok () st + else + let shortDecl := (Name.components decl.fullName).getLastD (str% "") + let indUnivs := ival.cnst.levelParams.map Level.mkParam + let (paramFVars, paramDecls, _) := openForallTelescope ival.numParams ival.cnst.type (str% "dp") 0 #[] #[] + let indApplied := Expr.mkAppN (Expr.mkConst decl.fullName indUnivs) paramFVars + let paramImpDecls := paramDecls.map fun d => { d with binderInfo := .implicit } + + let rec collectParamInstDecls (clsStr pfxStr bdrPfx : String) : + List AuxLocalDecl → Nat → List AuxLocalDecl → Array AuxLocalDecl + | [], _, revAcc => Array.mk revAcc.reverse + | pDecl :: rest, pIdx, revAcc => + let (pSortHead, _) := getAppFnArgs pDecl.domain + match pSortHead with + | .sort u _ => + let uPred := match u with | .succ p _ => p | _ => Level.mkZero + let (iFvId, _) := mkAuxFVar pfxStr pIdx + let iDom := Expr.mkApp (Expr.mkConst (Name.simple clsStr) #[uPred]) (paramFVars.getD pIdx indApplied) + let d : AuxLocalDecl := { fvarId := iFvId, binderName := Name.mkNat (Name.simple bdrPfx) pIdx, domain := iDom, binderInfo := .instImplicit } + collectParamInstDecls clsStr pfxStr bdrPfx rest (pIdx + 1) (d :: revAcc) + | _ => collectParamInstDecls clsStr pfxStr bdrPfx rest (pIdx + 1) revAcc + + let rec fillInhFields (c0 : ElabContext) (s0 : ElabState) : Nat → Ix.Expr → Ix.Expr → ElabRes Ix.Expr + | 0, curFn, _ => .ok curFn s0 + | rem + 1, curFn, curTy => + let curW := whnfPure c0 s0 fuel curTy + match stripMData curW with + | .forallE _ fDom fBody _ _ => + match elabTermCoreDirect c0 s0 fuel (Syntax.mkSimpleIdent (Name.simple (str% "default"))) (some fDom) with + | .error e => .error e + | .ok defTerm s1 => fillInhFields c0 s1 rem (Expr.mkApp curFn defTerm) (instantiate1 fBody defTerm) + | _ => fillInhFields c0 s0 rem curFn curTy + + let rec buildBeqFieldConj (c0 : ElabContext) (s0 : ElabState) + (aFieldFVars bFieldFVars : Array Ix.Expr) + (aFieldDecls : Array AuxLocalDecl) (aDecl : AuxLocalDecl) (trueConst : Ix.Expr) : + Nat → Nat → Option Ix.Expr → Ix.Expr × ElabState + | 0, _, eqConj => (instantiateMVarsPure s0.mctx 32 (eqConj.getD trueConst), s0) + | rem + 1, fIdx, eqConj => + let lhsF := aFieldFVars.getD fIdx trueConst + let rhsF := bFieldFVars.getD fIdx trueConst + let fDom := (aFieldDecls.getD fIdx aDecl).domain + let beqGoal := Expr.mkApp (Expr.mkConst (Name.simple (str% "BEq")) #[Level.mkZero]) fDom + let (instExpr, s1) := match synthInstancePure c0 8 s0 beqGoal with + | (some ie, s') => (ie, s') + | (none, s') => (Expr.mkConst (Name.simple (str% "instBEqNat")) #[], s') + let fEq := Expr.mkAppN (Expr.mkConst (Name.mkStr2 (str% "BEq") (str% "beq")) #[Level.mkZero]) #[fDom, instExpr, lhsF, rhsF] + let eqConj' := match eqConj with + | none => some fEq + | some prev => some (Expr.mkAppN (Expr.mkConst (Name.simple (str% "and")) #[]) #[prev, fEq]) + buildBeqFieldConj c0 s1 aFieldFVars bFieldFVars aFieldDecls aDecl trueConst rem (fIdx + 1) eqConj' + + let rec runDerivIds (s0 : ElabState) : List Ix.Name → ElabRes Unit + | [] => .ok () s0 + | clsId :: restCls => + if clsId == Name.simple (str% "Inhabited") then + match ival.ctors[0]? with + | some ctorName => + match s0.env.find? ctorName with + | some (.ctorInfo cval) => + let instDecls := collectParamInstDecls (str% "Inhabited") (str% "dinh") (str% "inst_") paramDecls.toList 0 [] + let allHdrDecls := paramImpDecls ++ instDecls + let lctxHdr := allHdrDecls.foldl (fun lc d => + lc.addDecl { fvarId := d.fvarId, userName := d.binderName, type := d.domain, binderInfo := d.binderInfo }) LocalContext.empty + let ctorInstTy := paramFVars.foldl (fun cur p => + match stripMData cur with + | .forallE _ _ b _ _ => instantiate1 b p + | other => other) (substExprLevelParams cval.cnst.levelParams indUnivs cval.cnst.type) + let ctxHdr : ElabContext := { ctx with lctx := lctxHdr, scope := decl.scope, univParams := ival.cnst.levelParams.toList } + match fillInhFields ctxHdr s0 cval.numFields (Expr.mkAppN (Expr.mkConst ctorName indUnivs) paramFVars) ctorInstTy with + | .error e => .error e + | .ok curFn s1 => + let defaultVal := instantiateMVarsPure s1.mctx 32 curFn + let inhZero := Level.mkZero + let instRetTy := Expr.mkApp (Expr.mkConst (Name.simple (str% "Inhabited")) #[inhZero]) indApplied + let instBody := Expr.mkAppN (Expr.mkConst (Name.mkStr2 (str% "Inhabited") (str% "mk")) #[inhZero]) #[indApplied, defaultVal] + let instFullTy := defaultUnassignedExprLevelMVars (closeForalls allHdrDecls instRetTy) + let instFullVal := defaultUnassignedExprLevelMVars (closeLambdas allHdrDecls instBody) + let instName := Name.fromComponents ((Name.components decl.fullName).dropLast ++ [strAppendPure (str% "instInhabited") shortDecl]) + let env1 := (s1.env.addConst (.defnInfo { + cnst := { name := instName, levelParams := ival.cnst.levelParams, type := instFullTy } + value := instFullVal, hints := .abbrev, safety := .safe, all := #[instName] + })).addInstance { instName := instName, className := Name.simple (str% "Inhabited") } + runDerivIds (setEnvPure s1 env1) restCls + | _ => runDerivIds s0 restCls + | none => runDerivIds s0 restCls + else if clsId == Name.simple (str% "BEq") || clsId == Name.simple (str% "DecidableEq") then + let casesOnName := Name.mkStr decl.fullName (str% "casesOn") + match s0.env.find? casesOnName with + | some (.defnInfo casesOnDef) => + let instDecls := collectParamInstDecls (str% "BEq") (str% "dbeq") (str% "instBEq_") paramDecls.toList 0 [] + let (aFvId, aFvExpr) := mkAuxFVar (str% "dbeq_a") 0 + let (bFvId, bFvExpr) := mkAuxFVar (str% "dbeq_b") 1 + let aDecl : AuxLocalDecl := { fvarId := aFvId, binderName := Name.simple (str% "a"), domain := indApplied } + let bDecl : AuxLocalDecl := { fvarId := bFvId, binderName := Name.simple (str% "b"), domain := indApplied } + let allHdrDecls := paramImpDecls ++ instDecls + let boolConst := Expr.mkConst (Name.simple (str% "Bool")) #[] + let trueConst := Expr.mkConst (Name.mkStr2 (str% "Bool") (str% "true")) #[] + let falseConst := Expr.mkConst (Name.mkStr2 (str% "Bool") (str% "false")) #[] + let casesOnUnivs := + if casesOnDef.cnst.levelParams.size == indUnivs.size + 1 then + #[Level.mkSucc Level.mkZero] ++ indUnivs + else indUnivs + let motive := Expr.mkLam (Name.simple (str% "_")) indApplied boolConst .default + let rec buildInner (sI : ElabState) (idxA : Nat) (cvalA : Ix.ConstructorVal) + (aFieldFVars : Array Ix.Expr) (aFieldDecls : Array AuxLocalDecl) : + List Ix.Name → Nat → List Ix.Expr → Array Ix.Expr × ElabState + | [], _, revAcc => (Array.mk revAcc.reverse, sI) + | ctorB :: restB, idxB, revAcc => + match sI.env.find? ctorB with + | some (.ctorInfo cvalB) => + let ctorBTy := paramFVars.foldl (fun cur p => + match stripMData cur with + | .forallE _ _ b _ _ => instantiate1 b p + | other => other) (substExprLevelParams cvalB.cnst.levelParams indUnivs cvalB.cnst.type) + let (bFieldFVars, bFieldDecls, _) := openForallTelescope cvalB.numFields ctorBTy (str% "dfb") (idxB * 64) #[] #[] + let (innerM, sI') := + if idxA != idxB then (closeLambdas bFieldDecls falseConst, sI) + else if cvalA.numFields == 0 then (closeLambdas bFieldDecls trueConst, sI) + else + let branchDecls := allHdrDecls ++ #[aDecl, bDecl] ++ aFieldDecls ++ bFieldDecls + let lctxBranch := branchDecls.foldl (fun lc d => + lc.addDecl { fvarId := d.fvarId, userName := d.binderName, type := d.domain, binderInfo := d.binderInfo }) LocalContext.empty + let ctxBranch : ElabContext := { ctx with lctx := lctxBranch, scope := decl.scope, univParams := ival.cnst.levelParams.toList } + let (cmpExpr, sNext) := buildBeqFieldConj ctxBranch sI aFieldFVars bFieldFVars aFieldDecls aDecl trueConst cvalA.numFields 0 none + (closeLambdas bFieldDecls cmpExpr, sNext) + buildInner sI' idxA cvalA aFieldFVars aFieldDecls restB (idxB + 1) (innerM :: revAcc) + | _ => buildInner sI idxA cvalA aFieldFVars aFieldDecls restB (idxB + 1) revAcc + let rec buildOuter (sO : ElabState) : List Ix.Name → Nat → List Ix.Expr → Array Ix.Expr × ElabState + | [], _, revAcc => (Array.mk revAcc.reverse, sO) + | ctorA :: restA, idxA, revAcc => + match sO.env.find? ctorA with + | some (.ctorInfo cvalA) => + let ctorATy := paramFVars.foldl (fun cur p => + match stripMData cur with + | .forallE _ _ b _ _ => instantiate1 b p + | other => other) (substExprLevelParams cvalA.cnst.levelParams indUnivs cvalA.cnst.type) + let (aFieldFVars, aFieldDecls, _) := openForallTelescope cvalA.numFields ctorATy (str% "dfa") (idxA * 64) #[] #[] + let (innerMinors, sO1) := buildInner sO idxA cvalA aFieldFVars aFieldDecls ival.ctors.toList 0 [] + let innerCases := Expr.mkAppN (Expr.mkConst casesOnName casesOnUnivs) + (paramFVars ++ #[motive, bFvExpr] ++ innerMinors) + buildOuter sO1 restA (idxA + 1) (closeLambdas aFieldDecls innerCases :: revAcc) + | _ => buildOuter sO restA (idxA + 1) revAcc + let (outerMinors, s1) := buildOuter s0 ival.ctors.toList 0 [] + let outerCases := Expr.mkAppN (Expr.mkConst casesOnName casesOnUnivs) + (paramFVars ++ #[motive, aFvExpr] ++ outerMinors) + let beqLam := closeLambdas #[aDecl, bDecl] outerCases + let beqZero := Level.mkZero + let instRetTy := Expr.mkApp (Expr.mkConst (Name.simple (str% "BEq")) #[beqZero]) indApplied + let instBody := Expr.mkAppN (Expr.mkConst (Name.mkStr2 (str% "BEq") (str% "mk")) #[beqZero]) #[indApplied, beqLam] + let instFullTy := defaultUnassignedExprLevelMVars (closeForalls allHdrDecls instRetTy) + let instFullVal := defaultUnassignedExprLevelMVars (closeLambdas allHdrDecls instBody) + let instName := Name.fromComponents ((Name.components decl.fullName).dropLast ++ [strAppendPure (str% "instBEq") shortDecl]) + let env1 := (s1.env.addConst (.defnInfo { + cnst := { name := instName, levelParams := ival.cnst.levelParams, type := instFullTy } + value := instFullVal, hints := .abbrev, safety := .safe, all := #[instName] + })).addInstance { instName := instName, className := Name.simple (str% "BEq") } + runDerivIds (setEnvPure s1 env1) restCls + | _ => runDerivIds s0 restCls + else runDerivIds s0 restCls + runDerivIds st derivIds + +def elabInductiveSCCCorePure (ctx : ElabContext) (st : ElabState) + (decls : Array ModuleDecl) (fuel : Nat := 128) : ElabRes Unit := + let allNames := decls.map (·.fullName) + let rec elabHeadersLoop (s0 : ElabState) : List ModuleDecl → + List (ModuleDecl × Nat × Nat × Array Ix.Name × Ix.Expr) → + ElabRes (Array (ModuleDecl × Nat × Nat × Array Ix.Name × Ix.Expr)) + | [], revH => .ok (Array.mk revH.reverse) s0 + | decl :: rest, revH => + match elabInductiveHeaderCorePure ctx s0 decl fuel with + | .error e => .error e + | .ok (nParams, nIndices, lvlParams, indType) s1 => + let tempIndVal : Ix.InductiveVal := { + cnst := { name := decl.fullName, levelParams := lvlParams, type := indType } + numParams := nParams, numIndices := nIndices, all := allNames + ctors := Array.mk decl.ctorNames, numNested := 0 + isRec := false, isUnsafe := false, isReflexive := false + } + elabHeadersLoop (setEnvPure s1 (s1.env.addConst (.inductInfo tempIndVal))) rest + ((decl, nParams, nIndices, lvlParams, indType) :: revH) + + let indNameSet : NameSet := allNames.foldl (fun s n => s.insert n) NameSet.empty + + let rec elabCtorsList (s0 : ElabState) (decl : ModuleDecl) (lvlParams : Array Ix.Name) + (paramGroups : List ParsedBinderGroup) : + List Stx → Nat → List Ix.ConstructorVal → ElabRes (Array Ix.ConstructorVal) + | [], _, revCs => .ok (Array.mk revCs.reverse) s0 + | ctorStx :: rest, cidx, revCs => + match elabOneConstructorCorePure ctx s0 decl lvlParams paramGroups ctorStx cidx fuel with + | .error e => .error e + | .ok (cval, bcs, retC) s1 => + elabCtorsList (setEnvPure s1 (s1.env.addContracts cval.cnst.name bcs retC)) + decl lvlParams paramGroups rest (cidx + 1) (cval :: revCs) + + let rec elabBodiesLoop (s0 : ElabState) : + List (ModuleDecl × Nat × Nat × Array Ix.Name × Ix.Expr) → + List (Ix.InductiveVal × Array Ix.ConstructorVal) → + List (Ix.InductiveVal × Ix.ConstructorVal × StructInfo × Array Ix.DefinitionVal) → + ElabRes (Array (Ix.InductiveVal × Array Ix.ConstructorVal) × + Array (Ix.InductiveVal × Ix.ConstructorVal × StructInfo × Array Ix.DefinitionVal)) + | [], revRaw, revStructs => .ok (Array.mk revRaw.reverse, Array.mk revStructs.reverse) s0 + | (decl, nParams, nIndices, lvlParams, indType) :: rest, revRaw, revStructs => + let cmd := decl.stx + let k := Syntax.getKind cmd + let optTypeNode := + if k == SyntaxKind.inductiveDecl then Syntax.getArg cmd 6 + else Syntax.getArg cmd 7 + let varGroups := decl.scope.varBinders.toList.map decodeBinderNode + let rawParamGroups := (Syntax.getArgs (Syntax.getArg cmd 4)).toList.map decodeBinderNode + let autoGroups := collectAutoImplicitGroups decl.scope ctx.modIdx s0.env varGroups rawParamGroups optTypeNode + let paramGroups := varGroups ++ autoGroups ++ rawParamGroups + if k == SyntaxKind.inductiveDecl then + let ctorStxs := Syntax.getArgs (Syntax.getArg cmd 7) + match elabCtorsList s0 decl lvlParams paramGroups ctorStxs.toList 0 [] with + | .error e => .error e + | .ok ctors s1 => + let isRec := ctors.any fun cv => + let (_, fieldDecls, _) := openForallTelescope (cv.numParams + cv.numFields) cv.cnst.type (str% "rc") 0 #[] #[] + (fieldDecls.extract cv.numParams fieldDecls.size).any fun fd => + !(collectRefsInSet indNameSet fd.domain).isEmpty + let indVal : Ix.InductiveVal := { + cnst := { name := decl.fullName, levelParams := lvlParams, type := indType } + numParams := nParams, numIndices := nIndices, all := allNames + ctors := ctors.map (·.cnst.name), numNested := 0 + isRec := isRec, isUnsafe := false, isReflexive := false + } + elabBodiesLoop s1 rest ((indVal, ctors) :: revRaw) revStructs + else + let fieldsOrCtorsNode := Syntax.getArg cmd 9 + let children := Syntax.getArgs fieldsOrCtorsNode + let isCtorStyleClass : Bool := match children[0]? with + | some c0 => Syntax.isOfKind c0 SyntaxKind.ctorDecl + | none => false + if isCtorStyleClass == true then + match elabCtorsList s0 decl lvlParams paramGroups children.toList 0 [] with + | .error e => .error e + | .ok ctors s1 => + let isRec := ctors.any fun cv => + let (_, fieldDecls, _) := openForallTelescope (cv.numParams + cv.numFields) cv.cnst.type (str% "rc") 0 #[] #[] + (fieldDecls.extract cv.numParams fieldDecls.size).any fun fd => + !(collectRefsInSet indNameSet fd.domain).isEmpty + let indVal : Ix.InductiveVal := { + cnst := { name := decl.fullName, levelParams := lvlParams, type := indType } + numParams := nParams, numIndices := nIndices, all := allNames + ctors := ctors.map (·.cnst.name), numNested := 0 + isRec := isRec, isUnsafe := false, isReflexive := false + } + let s2 := + if decl.kind == .cls then + setEnvPure s1 { s1.env with classSet := s1.env.classSet.insert decl.fullName } + else s1 + elabBodiesLoop s2 rest ((indVal, ctors) :: revRaw) revStructs + else + let ctorFullName := decl.ctorNames.headD (Name.mkStr decl.fullName (str% "mk")) + match elabStructureFieldsCorePure ctx s0 decl lvlParams paramGroups ctorFullName fieldsOrCtorsNode fuel with + | .error e => .error e + | .ok (cval, sInfo, bcs, toParentDefs) s1 => + let env1 := (s1.env.addContracts cval.cnst.name bcs .shared).addStructInfo sInfo + let indVal : Ix.InductiveVal := { + cnst := { name := decl.fullName, levelParams := lvlParams, type := indType } + numParams := nParams, numIndices := nIndices, all := allNames + ctors := #[cval.cnst.name], numNested := 0 + isRec := false, isUnsafe := false, isReflexive := false + } + elabBodiesLoop (setEnvPure s1 env1) rest ((indVal, #[cval]) :: revRaw) ((indVal, cval, sInfo, toParentDefs) :: revStructs) + + let rec registerStructsLoop (env0 : IxElabEnv) : + List (Ix.InductiveVal × Ix.ConstructorVal × StructInfo × Array Ix.DefinitionVal) → IxElabEnv + | [] => env0 + | (iv, cv, sInfo, toParentDefs) :: rest => + let projFieldNames := sInfo.fields.map (·.projFnName) + let projs := generateStructProjections iv cv projFieldNames sInfo.isClass + let env1 := projs.foldl (fun acc p => acc.addConst (.defnInfo p)) env0 + let env2 := toParentDefs.foldl (fun acc tp => acc.addConst (.defnInfo tp)) env1 + let env3 := + if sInfo.isClass then + (sInfo.parents.zip toParentDefs).foldl (fun acc (pName, tpDef) => + if acc.classSet.contains pName then + acc.addInstance { instName := tpDef.cnst.name, className := pName } + else acc) env2 + else env2 + registerStructsLoop env3 rest + + let rec runDerivingLoop (s0 : ElabState) : + List (ModuleDecl × Nat × Nat × Array Ix.Name × Ix.Expr) → ElabRes Unit + | [] => .ok () s0 + | (decl, _, _, _, _) :: rest => + match s0.env.find? decl.fullName with + | some (.inductInfo ival) => + match elabDerivingHandlersCorePure ctx s0 decl ival fuel with + | .error e => .error e + | .ok _ s1 => runDerivingLoop s1 rest + | _ => runDerivingLoop s0 rest + + match elabHeadersLoop st decls.toList [] with + | .error e => .error e + | .ok headers st1 => + match elabBodiesLoop st1 headers.toList [] [] with + | .error e => .error e + | .ok (rawItems, structToGenerate) st2 => + let canonItems := canonicalizeInductiveBlock st2.env.importMap rawItems + let env3 := registerCanonicalInductiveBlock st2.env canonItems + let env4 := registerStructsLoop env3 structToGenerate.toList + runDerivingLoop (setEnvPure st2 env4) headers.toList + +def elabValueSCCCorePure (ctx : ElabContext) (st : ElabState) + (decls : Array ModuleDecl) (isRecursive : Bool := true) (fuel : Nat := 128) : ElabRes Unit := + let rec elabSigsLoop (s0 : ElabState) : List ModuleDecl → + List (ModuleDecl × Array Ix.Name × Ix.Expr × Array Ixon.BinderContract × Ixon.ValueContract) → + ElabRes (Array (ModuleDecl × Array Ix.Name × Ix.Expr × Array Ixon.BinderContract × Ixon.ValueContract)) + | [], revSigs => .ok (Array.mk revSigs.reverse) s0 + | decl :: rest, revSigs => + let s1 : ElabState := match s0 with | ⟨env, _, nextIdx, _, _⟩ => ⟨env, {}, nextIdx, [], #[]⟩ + let cmd := decl.stx + let k := Syntax.getKind cmd + let varGroups := decl.scope.varBinders.toList.map decodeBinderNode + let rawParamGroups := (Syntax.getArgs (Syntax.getArg cmd 4)).toList.map decodeBinderNode + let vPrefNode := Syntax.getArg cmd 5 + let optTypeNode := Syntax.getArg cmd 6 + let retContract := (decodeContractPrefix vPrefNode).toValueContract + let optTypeExpanded := expandMacroPureSt s1 8 optTypeNode + let autoGroups := collectAutoImplicitGroups decl.scope ctx.modIdx s1.env varGroups rawParamGroups optTypeExpanded + let paramGroups := varGroups ++ autoGroups ++ rawParamGroups + let ctx1 : ElabContext := { ctx with + lctx := LocalContext.empty, scope := decl.scope + currDecl? := some decl.fullName, univParams := decl.univParams } + match elabBinderGroupsCorePure ctx1 s1 fuel paramGroups with + | .error e => .error e + | .ok (paramFVars, ctx2) s2 => + let retTyRes : ElabRes Ix.Expr := + if Syntax.isNone optTypeNode || Syntax.isMissing optTypeNode then + let (u, sa) := mkFreshLevelMVarPure s2 + let (mv, sb) := mkFreshExprMVarPure ctx2 sa (Expr.mkSort u) + .ok mv sb + else + match elabTermCoreDirect ctx2 s2 fuel optTypeNode none with + | .error e => .error e + | .ok t sa => + match ensureSortIfNotForallPure ctx2 sa 32 t with + | .error e => .error e + | .ok _ sb => .ok (instantiateMVarsPure sb.mctx 32 t) sb + match retTyRes with + | .error e => .error e + | .ok retTy s3 => + let fullType := instantiateMVarsPure s3.mctx 32 (mkForallFVarsPure ctx2 paramFVars retTy retContract) + let bcs : Array Ixon.BinderContract := Array.mk <| paramFVars.toList.filterMap fun fv => + (ctx2.lctx.findFVar? fv).map (·.contract) + let lvlParams := Array.mk (decl.univParams ++ decl.scope.levelNames ++ s3.autoBoundUnivs).eraseDups + let tempAx : Ix.AxiomVal := { + cnst := { name := decl.fullName, levelParams := lvlParams, type := defaultUnassignedExprLevelMVars fullType } + isUnsafe := false + } + let _ := k + elabSigsLoop (setEnvPure s3 (s3.env.addConst (.axiomInfo tempAx))) rest + ((decl, lvlParams, fullType, bcs, retContract) :: revSigs) + + let rec elabValueBodiesLoop (s0 : ElabState) : + List (ModuleDecl × Array Ix.Name × Ix.Expr × Array Ixon.BinderContract × Ixon.ValueContract) → + List Ix.Def → ElabRes (Array Ix.Def) + | [], revDefs => .ok (Array.mk revDefs.reverse) s0 + | (decl, initLvlParams, _, _, retContract) :: rest, revDefs => + let cmd := decl.stx + let k := Syntax.getKind cmd + let attrs := extractDeclAttributes (Syntax.getArg cmd 0) + let s0' := + if attrs.contains (Name.simple (str% "simp")) then + setEnvPure s0 (s0.env.addInstance { instName := decl.fullName, className := Name.mkStr2 (str% "_Ix") (str% "simpLemma") }) + else s0 + if k == SyntaxKind.axiomDecl then + elabValueBodiesLoop s0' rest revDefs + else + let s1 : ElabState := match s0' with | ⟨env, _, nextIdx, _, _⟩ => ⟨env, {}, nextIdx, initLvlParams.toList, #[]⟩ + let varGroups := decl.scope.varBinders.toList.map decodeBinderNode + let rawParamBinders := (Syntax.getArgs (Syntax.getArg cmd 4)).toList.map decodeBinderNode + let optTypeNode := Syntax.getArg cmd 6 + let optTypeExpanded := expandMacroPureSt s1 8 optTypeNode + let autoGroups := collectAutoImplicitGroups decl.scope ctx.modIdx s1.env varGroups rawParamBinders optTypeExpanded + let paramGroups := varGroups ++ autoGroups ++ rawParamBinders + let ctx1 : ElabContext := { ctx with + lctx := LocalContext.empty, scope := decl.scope + currDecl? := some decl.fullName, univParams := initLvlParams.toList } + match elabBinderGroupsCorePure ctx1 s1 fuel paramGroups with + | .error e => .error e + | .ok (paramFVars, ctx2) s2 => + let expRetRes : ElabRes (Option Ix.Expr) := + if Syntax.isNone optTypeNode || Syntax.isMissing optTypeNode then .ok none s2 + else + match elabTermCoreDirect ctx2 s2 fuel optTypeNode none with + | .error e => .error e + | .ok t sa => + match ensureSortIfNotForallPure ctx2 sa 32 t with + | .error e => .error e + | .ok _ sb => .ok (some (instantiateMVarsPure sb.mctx 32 t)) sb + match expRetRes with + | .error e => .error e + | .ok expRetTy? s3 => + let bodyRes : ElabRes (Ix.Expr × Ix.Expr × Array Ix.Name) := + if k == SyntaxKind.instanceDecl && Syntax.getAtomVal (Syntax.getArg cmd 7) == (str% "where") then + let fieldAssigns := Syntax.getArgs (Syntax.getArg cmd 8) + let normAssigns := fieldAssigns.map fun fa => + let fId := Syntax.getArg fa 0 + let fBinders := Syntax.getArg fa 1 + let fRhs := Syntax.getArg fa 3 + let rhsTerm := + if (Syntax.getArgs fBinders).isEmpty then fRhs + else Syntax.mkNode SyntaxKind.funTerm #[Syntax.mkSimpleAtom (str% "fun"), fBinders, Syntax.mkSimpleAtom (str% "=>"), fRhs] + Syntax.mkNode SyntaxKind.structFieldAssign #[fId, Syntax.mkSimpleAtom (str% ":="), rhsTerm] + let structLit := Syntax.mkNode SyntaxKind.structInst + #[Syntax.mkSimpleAtom (str% "{"), Syntax.mkNullNode #[], Syntax.mkNullNode normAssigns, Syntax.mkSimpleAtom (str% "}")] + match elabTermCoreDirect ctx2 s3 fuel structLit expRetTy? with + | .error e => .error e + | .ok val sa => + match expRetTy? with + | some t => .ok (val, t, #[]) sa + | none => + match inferTypePure ctx2 sa fuel val with + | .error e => .error e + | .ok rTy sb => .ok (val, rTy, #[]) sb + else if Syntax.getNumArgs cmd == 8 && k != SyntaxKind.axiomDecl then + let altsNode := Syntax.getArg cmd 7 + let targetFvId? := + (paramFVars.find? fun fvId => + match ctx2.lctx.findFVar? fvId with + | some d => d.binderInfo == .default && !stxMentionsPure d.userName 64 altsNode + | none => false).orElse (fun _ => paramFVars.back?) + match targetFvId? with + | some lastFvId => + let lastName := match ctx2.lctx.findFVar? lastFvId with + | some d => d.userName + | none => Name.simple (str% "x") + let matchStx := Syntax.mkNode SyntaxKind.matchTerm + #[Syntax.mkSimpleAtom (str% "match"), Syntax.mkNullNode #[Syntax.mkSimpleIdent lastName], + Syntax.mkSimpleAtom (str% "with"), altsNode] + match elabTermCoreDirect ctx2 s3 fuel matchStx expRetTy? with + | .error e => .error e + | .ok val sa => + match expRetTy? with + | some t => .ok (val, t, #[]) sa + | none => + match inferTypePure ctx2 sa fuel val with + | .error e => .error e + | .ok rTy sb => .ok (val, rTy, #[]) sb + | none => + match expRetTy? with + | some rTy => + let rTyW := whnfPure ctx2 s3 fuel rTy + match stripMData rTyW with + | .forallE _ dom cod bi _ => + let discrName := Name.simple (str% "_x") + let (fvId, fvExpr, ctx3, sa) := pushLocalDeclPure ctx2 s3 discrName dom bi default none none false + let codInst := instantiate1 cod fvExpr + let matchStx := Syntax.mkNode SyntaxKind.matchTerm + #[Syntax.mkSimpleAtom (str% "match"), Syntax.mkNullNode #[Syntax.mkSimpleIdent discrName], + Syntax.mkSimpleAtom (str% "with"), altsNode] + match elabTermCoreDirect ctx3 sa fuel matchStx (some codInst) with + | .error e => .error e + | .ok val sb => + .ok (mkLambdaFVarsPure ctx3 #[fvId] val, mkForallFVarsPure ctx3 #[fvId] codInst, #[]) sb + | _ => errPure ctx2 (str% "pattern-matching definition requires a parameter or function return type") (some cmd) + | none => errPure ctx2 (str% "pattern-matching definition requires a parameter or type signature") (some cmd) + else + let bodyStx := Syntax.getArg cmd 8 + match elabTermCoreDirect ctx2 s3 fuel bodyStx expRetTy? with + | .error e => .error e + | .ok val sa => + match expRetTy? with + | some t => .ok (val, t, #[]) sa + | none => + match inferTypePure ctx2 sa fuel val with + | .error e => .error e + | .ok rTy sb => .ok (val, rTy, #[]) sb + match bodyRes with + | .error e => .error e + | .ok (bodyExpr, bodyRetTy, extraFVars) s4 => + let allParamFVars := paramFVars ++ extraFVars + let finalType := defaultUnassignedExprLevelMVars + (instantiateMVarsPure s4.mctx 32 (mkForallFVarsPure ctx2 allParamFVars bodyRetTy retContract)) + let finalVal0 := defaultUnassignedExprLevelMVars + (instantiateMVarsPure s4.mctx 32 (mkLambdaFVarsPure ctx2 allParamFVars bodyExpr)) + let finalBcs : Array Ixon.BinderContract := Array.mk <| allParamFVars.toList.filterMap fun fv => + (ctx2.lctx.findFVar? fv).map (·.contract) + let finalLvls := Array.mk (decl.univParams ++ decl.scope.levelNames ++ s4.autoBoundUnivs).eraseDups + let finalVal := + if isRecursive && decls.size == 1 then tryLowerStructuralRecToRecOn s4.env decl.fullName finalVal0 + else finalVal0 + let env1 := s4.env.addContracts decl.fullName finalBcs retContract s4.localLetContracts + let env2 := + if decl.kind == .inst || attrs.contains (Name.simple (str% "instance")) then + let (_, _, retBody) := openForallTelescope (countForalls 64 finalType) finalType (str% "inst") 0 #[] #[] + let (headClass, _) := getAppFnArgs retBody + match headClass with + | .const className _ _ => env1.addInstance { instName := decl.fullName, className } + | _ => env1 + else env1 + let defKind : Ix.DefKind := + if decl.kind == .thm then .thm + else if decl.kind == .opaqueDecl then .opaq + else .defn + let hints : Lean.ReducibilityHints := + if decl.kind == .abbrev || attrs.contains (Name.simple (str% "reducible")) || attrs.contains (Name.simple (str% "inline")) then .abbrev + else if decl.kind == .thm || decl.kind == .opaqueDecl || attrs.contains (Name.simple (str% "irreducible")) then .opaque + else .regular 1 + let dItem : Ix.Def := { + name := decl.fullName, levelParams := finalLvls, type := finalType + kind := defKind, value := finalVal, hints := hints, safety := .safe, all := #[decl.fullName] + } + elabValueBodiesLoop (setEnvPure s4 env2) rest (dItem :: revDefs) + + let rec addCanonDefs (env0 : IxElabEnv) : List Ix.Def → IxElabEnv + | [] => env0 + | d :: rest => + let ci : Ix.ConstantInfo := match d.kind with + | .thm => .thmInfo { + cnst := { name := d.name, levelParams := d.levelParams, type := d.type } + value := d.value, all := d.all + } + | .opaq => .opaqueInfo { + cnst := { name := d.name, levelParams := d.levelParams, type := d.type } + value := d.value, isUnsafe := false, all := d.all + } + | .defn => .defnInfo { + cnst := { name := d.name, levelParams := d.levelParams, type := d.type } + value := d.value, hints := d.hints, safety := .safe, all := d.all + } + addCanonDefs (env0.addConst ci) rest + + let rec addCanonSccs (env0 : IxElabEnv) : List (Array Ix.Def) → IxElabEnv + | [] => env0 + | sccDefs :: rest => addCanonSccs (addCanonDefs env0 sccDefs.toList) rest + + match elabSigsLoop st decls.toList [] with + | .error e => .error e + | .ok sigInfos st1 => + match elabValueBodiesLoop st1 sigInfos.toList [] with + | .error e => .error e + | .ok elabbedDefs st2 => + if elabbedDefs.isEmpty then .ok () st2 + else + let canonSccs := canonicalizeElaboratedDefs st2.env.importMap elabbedDefs + .ok () (setEnvPure st2 (addCanonSccs st2.env canonSccs.toList)) + +def elabModuleScheduleCorePure (sched : ModuleSchedule) + (initEnv : IxElabEnv := IxElabEnv.empty) (seedPrelude : Bool := true) : + Except ElabError IxElabEnv := + let baseEnv := initEnv.withImportMap (initEnv.importMap.merge sched.modIdx.importMap) + let baseEnv := baseEnv.addMacroRules sched.modIdx.macroRules.toList + let baseEnv := if seedPrelude then seedCorePreludeIfMissing baseEnv sched.modIdx else baseEnv + baseEnv.bindEnv fun baseEnv' => + let initCtx : ElabContext := { modIdx := sched.modIdx } + let initSt : ElabState := { env := baseEnv' } + let declList := sched.modIdx.decls.toList + let rec runSccs (s0 : ElabState) : List ScheduledSCC → ElabRes Unit + | [] => .ok () s0 + | scc :: rest => + let sccDecls := Array.mk (scc.declIdxs.toList.filterMap fun idx => Syntax.listGet? declList idx) + if sccDecls.isEmpty then runSccs s0 rest + else + let allInd := sccDecls.toList.all fun d => d.kind == .ind || d.kind == .struct || d.kind == .cls + let stepRes : ElabRes Unit := + if allInd then + elabInductiveSCCCorePure initCtx s0 sccDecls 128 + else + elabValueSCCCorePure initCtx s0 sccDecls (scc.kind != .singleNonRec) 128 + match stepRes with + | .error e => .error e + | .ok _ s1 => runSccs s1 rest + match runSccs initSt sched.sccs.toList with + | .ok _ finalSt => .ok finalSt.env + | .error e => .error e + +/-- 100% first-order whole-module elaborator for `IxCCAiur` ZK circuits. -/ +def elabModuleSyntaxCorePure (moduleStx : Stx) + (initEnv : IxElabEnv := IxElabEnv.empty) + (seedPrelude : Bool := true) : Except String IxElabEnv := + match buildModuleIndex moduleStx with + | .error e => .error e + | .ok modIdx => + let baseEnv := if seedPrelude then seedCorePreludeIfMissing initEnv modIdx else initEnv + baseEnv.bindEnv fun baseEnv' => + match scheduleModuleDeclsMap modIdx baseEnv'.consts with + | .error e => .error e + | .ok sched => + match elabModuleScheduleCorePure sched baseEnv' false with + | .ok env => .ok env + | .error e => .error e.msg + +end Ix.Frontend.Elab + +end diff --git a/Ix/Frontend/Elab/Meta.lean b/Ix/Frontend/Elab/Meta.lean new file mode 100644 index 0000000000..1731e9c699 --- /dev/null +++ b/Ix/Frontend/Elab/Meta.lean @@ -0,0 +1,1628 @@ +/- + Ix.Frontend.Elab.Meta: Pure, deterministic, fuel-bounded kernel and meta-level + operations for the Ix Frontend: + - De Bruijn & FVar abstraction/instantiation (`instantiate1`, `abstractFVar`, `mkLambdaFVars`, `mkForallFVars`) + - Universe level normalization, substitution, and unification (`isLevelDefEq`) + - Metavariable creation, instantiation, and Miller-pattern occurs-checked assignment + - Weak-head normal form (`whnf`) supporting β, ζ, δ, ι (recursor), structure projection, and `Nat` reduction + - Type inference (`inferType`, `ensureSort`, `ensureForall`) + - Higher-order unification (`isDefEq`) + - Bounded backtracking typeclass synthesis (`synthInstance?`) +-/ +module + +public import Ix.Frontend.Elab.Monad + +@[expose] public section + +namespace Ix.Frontend.Elab + +open Ix.Frontend + +/-! ## Pure Expression & De Bruijn Utilities -/ + +/-- Strip outer `.mdata` wrappers from an `Ix.Expr`. -/ +def stripMData : Ix.Expr → Ix.Expr + | .mdata _ e _ => stripMData e + | e => e + +/-- Decompose `f a₁ ... aₙ` into `(f, #[a₁, ..., aₙ])`, stripping `.mdata` on spine nodes. -/ +def getAppFnArgsAux : Ix.Expr → List Ix.Expr → Ix.Expr × Array Ix.Expr + | .mdata _ e _, acc => getAppFnArgsAux e acc + | .app f a _, acc => getAppFnArgsAux f (a :: acc) + | e, acc => (e, Array.mk acc) + +def getAppFnArgs (e : Ix.Expr) : Ix.Expr × Array Ix.Expr := + getAppFnArgsAux e [] + +def getAppFn : Ix.Expr → Ix.Expr + | .mdata _ e _ => getAppFn e + | .app f _ _ => getAppFn f + | e => e + +def getAppArgs (e : Ix.Expr) : Array Ix.Expr := + (getAppFnArgs e).2 + +/-- True if `e` contains any loose `.bvar i` with `i ≥ cutoff`. -/ +def hasLooseBVarsAt : Ix.Expr → Nat → Bool + | .bvar i _, c => Nat.ble c i + | .app f a _, c => hasLooseBVarsAt f c || hasLooseBVarsAt a c + | .lam _ t b _ _, c => hasLooseBVarsAt t c || hasLooseBVarsAt b (c + 1) + | .forallE _ t b _ _, c => hasLooseBVarsAt t c || hasLooseBVarsAt b (c + 1) + | .letE _ t v b _ _, c => hasLooseBVarsAt t c || hasLooseBVarsAt v c || hasLooseBVarsAt b (c + 1) + | .proj _ _ s _, c => hasLooseBVarsAt s c + | .mdata _ x _, c => hasLooseBVarsAt x c + | _, _ => false + +def hasLooseBVars (e : Ix.Expr) : Bool := + hasLooseBVarsAt e 0 + +/-- True if `e` mentions free variable `fvarId`. -/ +def containsFVar (fvarId : Ix.Name) : Ix.Expr → Bool + | .fvar n _ => n == fvarId + | .app f a _ => containsFVar fvarId f || containsFVar fvarId a + | .lam _ t b _ _ => containsFVar fvarId t || containsFVar fvarId b + | .forallE _ t b _ _ => containsFVar fvarId t || containsFVar fvarId b + | .letE _ t v b _ _ => containsFVar fvarId t || containsFVar fvarId v || containsFVar fvarId b + | .proj _ _ s _ => containsFVar fvarId s + | .mdata _ x _ => containsFVar fvarId x + | _ => false + +/-- Shift loose `.bvar i` (`i ≥ cutoff`) up by `delta`. -/ +def liftLooseBVars (e : Ix.Expr) (delta : Nat) (cutoff : Nat := 0) : Ix.Expr := + if Nat.beq delta 0 || !hasLooseBVarsAt e cutoff then e else go e cutoff +where + go : Ix.Expr → Nat → Ix.Expr + | .bvar i _, c => if Nat.ble c i then Expr.mkBVar (i + delta) else Expr.mkBVar i + | .app f a _, c => Expr.mkApp (go f c) (go a c) + | .lam nm t b bi _, c => Expr.mkLam nm (go t c) (go b (c + 1)) bi + | .forallE nm t b bi _, c => Expr.mkForallE nm (go t c) (go b (c + 1)) bi + | .letE nm t v b nd _, c => Expr.mkLetE nm (go t c) (go v c) (go b (c + 1)) nd + | .proj nm i s _, c => Expr.mkProj nm i (go s c) + | .mdata md x _, c => Expr.mkMData md (go x c) + | other, _ => other + +/-- Substitute `args` for loose `.bvar (depth + i)` (`i < args.size`, where `bvar depth` + is replaced by `args[0]`), and lower loose `.bvar`s above `depth + args.size`. -/ +def instantiateRevAt (args : Array Ix.Expr) (e : Ix.Expr) (depth : Nat) : Ix.Expr := + match e with + | .bvar i _ => + if Nat.ble depth i then + let idx := i - depth + match Syntax.listGet? args.toList idx with + | some arg => liftLooseBVars arg depth + | none => Expr.mkBVar (i - args.size) + else + e + | .app f a _ => Expr.mkApp (instantiateRevAt args f depth) (instantiateRevAt args a depth) + | .lam nm t b bi _ => Expr.mkLam nm (instantiateRevAt args t depth) (instantiateRevAt args b (depth + 1)) bi + | .forallE nm t b bi _ => Expr.mkForallE nm (instantiateRevAt args t depth) (instantiateRevAt args b (depth + 1)) bi + | .letE nm t v b nd _ => + Expr.mkLetE nm (instantiateRevAt args t depth) (instantiateRevAt args v depth) (instantiateRevAt args b (depth + 1)) nd + | .proj nm i s _ => Expr.mkProj nm i (instantiateRevAt args s depth) + | .mdata md x _ => Expr.mkMData md (instantiateRevAt args x depth) + | other => other + +/-- Substitute `args[0]` for `bvar 0`, `args[1]` for `bvar 1`, etc. -/ +def instantiateRev (body : Ix.Expr) (args : Array Ix.Expr) : Ix.Expr := + if args.isEmpty then body else instantiateRevAt args body 0 + +/-- Substitute a single `arg` for loose `.bvar depth` in `e` in a single O(N) pass. -/ +def instantiate1At (arg : Ix.Expr) (e : Ix.Expr) (depth : Nat) : Ix.Expr := + match e with + | .bvar i _ => + if Nat.beq i depth then + liftLooseBVars arg depth + else if Nat.ble (depth + 1) i then + Expr.mkBVar (i - 1) + else + e + | .app f a _ => Expr.mkApp (instantiate1At arg f depth) (instantiate1At arg a depth) + | .lam nm t b bi _ => Expr.mkLam nm (instantiate1At arg t depth) (instantiate1At arg b (depth + 1)) bi + | .forallE nm t b bi _ => Expr.mkForallE nm (instantiate1At arg t depth) (instantiate1At arg b (depth + 1)) bi + | .letE nm t v b nd _ => + Expr.mkLetE nm (instantiate1At arg t depth) (instantiate1At arg v depth) (instantiate1At arg b (depth + 1)) nd + | .proj nm i s _ => Expr.mkProj nm i (instantiate1At arg s depth) + | .mdata md x _ => Expr.mkMData md (instantiate1At arg x depth) + | other => other + +/-- Substitute `arg` for `bvar 0` in `body`. -/ +def instantiate1 (body : Ix.Expr) (arg : Ix.Expr) : Ix.Expr := + instantiate1At arg body 0 + +/-- Replace free variable `fvarId` in `e` with `bvar depth` (lifting existing loose `bvar ≥ depth` by 1) + in a single O(N) pass. -/ +def abstractFVarAt (fvarId : Ix.Name) (e : Ix.Expr) (d : Nat) : Ix.Expr := + match e with + | .bvar i _ => + if Nat.ble d i then Expr.mkBVar (i + 1) else e + | .fvar n _ => + if n == fvarId then Expr.mkBVar d else e + | .app f a _ => Expr.mkApp (abstractFVarAt fvarId f d) (abstractFVarAt fvarId a d) + | .lam nm t b bi _ => Expr.mkLam nm (abstractFVarAt fvarId t d) (abstractFVarAt fvarId b (d + 1)) bi + | .forallE nm t b bi _ => Expr.mkForallE nm (abstractFVarAt fvarId t d) (abstractFVarAt fvarId b (d + 1)) bi + | .letE nm t v b nd _ => + Expr.mkLetE nm (abstractFVarAt fvarId t d) (abstractFVarAt fvarId v d) (abstractFVarAt fvarId b (d + 1)) nd + | .proj nm i s _ => Expr.mkProj nm i (abstractFVarAt fvarId s d) + | .mdata md x _ => Expr.mkMData md (abstractFVarAt fvarId x d) + | other => other + +def abstractFVar (fvarId : Ix.Name) (body : Ix.Expr) : Ix.Expr := + abstractFVarAt fvarId body 0 + +/-- Find the 0-based index of `target` in `xs`. -/ +def findNameIdx? : List Ix.Name → Ix.Name → Nat → Option Nat + | [], _, _ => none + | x :: xs, target, idx => + if x == target then some idx else findNameIdx? xs target (idx + 1) + +/-- Simultaneously abstract a reversed list of binder FVars `revFVars = [f_{k-1}, ..., f_0]` + (where `f_{k-1}` is innermost -> `bvar d`, and `f_0` is outermost -> `bvar (d + k - 1)`) + in a single O(N) pass. -/ +def abstractFVarsRevAt (revFVars : List Ix.Name) (numFVars : Nat) (e : Ix.Expr) (d : Nat) : Ix.Expr := + if Nat.beq numFVars 0 then e else go e d +where + go : Ix.Expr → Nat → Ix.Expr + | ex@(.bvar i _), c => + if Nat.ble c i then Expr.mkBVar (i + numFVars) else ex + | ex@(.fvar n _), c => + match findNameIdx? revFVars n 0 with + | some idx => Expr.mkBVar (c + idx) + | none => ex + | .app f a _, c => Expr.mkApp (go f c) (go a c) + | .lam nm t b bi _, c => Expr.mkLam nm (go t c) (go b (c + 1)) bi + | .forallE nm t b bi _, c => Expr.mkForallE nm (go t c) (go b (c + 1)) bi + | .letE nm t v b nd _, c => Expr.mkLetE nm (go t c) (go v c) (go b (c + 1)) nd + | .proj nm i s _, c => Expr.mkProj nm i (go s c) + | .mdata md x _, c => Expr.mkMData md (go x c) + | other, _ => other + +/-- Replace simultaneous FVars `fvars[i]` with `vals[i]` in `e`. -/ +def replaceFVars (e : Ix.Expr) (fvars : Array Ix.Name) (vals : Array Ix.Expr) : Ix.Expr := + if fvars.isEmpty then e else go e +where + go : Ix.Expr → Ix.Expr + | ex@(.fvar n _) => + match fvars.idxOf? n with + | some idx => vals.getD idx ex + | none => ex + | .app f a _ => Expr.mkApp (go f) (go a) + | .lam nm t b bi _ => Expr.mkLam nm (go t) (go b) bi + | .forallE nm t b bi _ => Expr.mkForallE nm (go t) (go b) bi + | .letE nm t v b nd _ => Expr.mkLetE nm (go t) (go v) (go b) nd + | .proj nm i s _ => Expr.mkProj nm i (go s) + | .mdata md x _ => Expr.mkMData md (go x) + | other => other + +/-- Replace constant names (and `.proj` structure type names) in `e` according to `map`. -/ +def replaceConstNames (map : NameMap Ix.Name) (e : Ix.Expr) : Ix.Expr := + if map.isEmpty then e else go e +where + go : Ix.Expr → Ix.Expr + | .const nm us _ => Expr.mkConst ((map.get? nm).getD nm) us + | .app f a _ => Expr.mkApp (go f) (go a) + | .lam nm t b bi _ => Expr.mkLam nm (go t) (go b) bi + | .forallE nm t b bi _ => Expr.mkForallE nm (go t) (go b) bi + | .letE nm t v b nd _ => Expr.mkLetE nm (go t) (go v) (go b) nd + | .proj nm i s _ => Expr.mkProj ((map.get? nm).getD nm) i (go s) + | .mdata md x _ => Expr.mkMData md (go x) + | other => other + +/-- Close a reversed list of non-let `LocalDecl`s around `absBody` in O(K) binder allocations, + abstracting each binder's domain type once against its outer prefix. -/ +def closeLambdaDeclsRev : List LocalDecl → List Ix.Name → Nat → Ix.Expr → Ix.Expr + | [], _, _, acc => acc + | decl :: restDecls, _ :: outerRevFVars, outerCount, acc => + let bName := if Name.isAnonymous decl.userName then Name.simple (str% "x") else decl.userName + let absDom := abstractFVarsRevAt outerRevFVars outerCount decl.type 0 + let acc' := Expr.mkLamContract bName absDom acc decl.binderInfo decl.contract + closeLambdaDeclsRev restDecls outerRevFVars (outerCount - 1) acc' + | _, _, _, acc => acc + +/-- Close a reversed list of non-let `LocalDecl`s into a `.forallE` telescope in O(K) steps, + abstracting each binder's domain type once against its outer prefix. -/ +def closeForallDeclsRev (retContract : Ixon.ValueContract) : + List LocalDecl → List Ix.Name → Nat → Bool → Ix.Expr → Ix.Expr + | [], _, _, _, acc => acc + | decl :: restDecls, _ :: outerRevFVars, outerCount, isInnermost, acc => + let bName := if Name.isAnonymous decl.userName then Name.simple (str% "x") else decl.userName + let absDom := abstractFVarsRevAt outerRevFVars outerCount decl.type 0 + let resContract : Ixon.ValueContract := if isInnermost then retContract else .shared + let acc' := Expr.mkForallContract bName absDom acc decl.binderInfo decl.contract resContract + closeForallDeclsRev retContract restDecls outerRevFVars (outerCount - 1) false acc' + | _, _, _, _, acc => acc + +/-- Close a list of FVar IDs into a telescope of `.lam` / `.letE` binders using `lctx`. -/ +def mkLambdaFVarsList (lctx : LocalContext) (fvars : List Ix.Name) (body : Ix.Expr) : Ix.Expr := + let decls := fvars.filterMap lctx.findFVar? + if decls.all (·.value?.isNone) then + let revDecls := decls.reverse + let revIds := revDecls.map (·.fvarId) + let k := revIds.length + let absBody := abstractFVarsRevAt revIds k body 0 + closeLambdaDeclsRev revDecls revIds (k - 1) absBody + else + let rec go : List Ix.Name → Ix.Expr → Ix.Expr + | [], b => b + | fvarId :: rest, b => + let acc := go rest b + match lctx.findFVar? fvarId with + | none => acc + | some decl => + let bName := if Name.isAnonymous decl.userName then Name.simple (str% "x") else decl.userName + let absBody := abstractFVar fvarId acc + match decl.value? with + | some val => + let letKind := decl.letKind?.getD .value + let nonDep := decl.nonDep || !containsFVar fvarId acc + Expr.mkLetContract bName decl.type val absBody nonDep decl.contract letKind + | none => + Expr.mkLamContract bName decl.type absBody decl.binderInfo decl.contract + go fvars body + +/-- Close an array of FVar IDs into a telescope of `.lam` / `.letE` binders using `lctx`, + attaching `ix.contract` metadata frames whenever a binder has non-default substructural contract. -/ +def mkLambdaFVars (fvars : Array Ix.Name) (body : Ix.Expr) : IxElabM Ix.Expr := do + if fvars.isEmpty then return body + let ctx ← read + return mkLambdaFVarsList ctx.lctx fvars.toList body + +/-- Close a list of FVar IDs into a telescope of `.forallE` / `.letE` binders using `lctx`. -/ +def mkForallFVarsList (lctx : LocalContext) (retContract : Ixon.ValueContract) + (fvars : List Ix.Name) (body : Ix.Expr) : Ix.Expr := + let decls := fvars.filterMap lctx.findFVar? + if decls.all (·.value?.isNone) then + let revDecls := decls.reverse + let revIds := revDecls.map (·.fvarId) + let k := revIds.length + let absBody := abstractFVarsRevAt revIds k body 0 + closeForallDeclsRev retContract revDecls revIds (k - 1) true absBody + else + let rec go : List Ix.Name → Ix.Expr → Ix.Expr + | [], b => b + | fvarId :: rest, b => + let acc := go rest b + let resContract : Ixon.ValueContract := match rest with + | [] => retContract + | _ => .shared + match lctx.findFVar? fvarId with + | none => acc + | some decl => + let bName := if Name.isAnonymous decl.userName then Name.simple (str% "x") else decl.userName + let absBody := abstractFVar fvarId acc + match decl.value? with + | some val => + let letKind := decl.letKind?.getD .value + let nonDep := decl.nonDep || !containsFVar fvarId acc + Expr.mkLetContract bName decl.type val absBody nonDep decl.contract letKind + | none => + Expr.mkForallContract bName decl.type absBody decl.binderInfo decl.contract resContract + go fvars body + +/-- Close an array of FVar IDs into a telescope of `.forallE` / `.letE` binders using `lctx`, + attaching `ix.contract` metadata frames for binder contracts and `retContract` on the innermost arrow. -/ +def mkForallFVars (fvars : Array Ix.Name) (body : Ix.Expr) + (retContract : Ixon.ValueContract := .shared) : IxElabM Ix.Expr := do + if fvars.isEmpty then return body + let ctx ← read + return mkForallFVarsList ctx.lctx retContract fvars.toList body + +/-! ## Universe Level Operations & Unification -/ + +/-- Proof-free lookup of universe parameter `n` in parallel lists `(params, lvls)`. -/ +def lookupLevelParam : List Ix.Name → List Ix.Level → Ix.Name → Option Ix.Level + | p :: ps, v :: vs, n => if p == n then some v else lookupLevelParam ps vs n + | _, _, _ => none + +/-- Substitute universe parameter names `params` with `lvls` in `u`. -/ +def substLevelParamsList (params : List Ix.Name) (lvls : List Ix.Level) : Ix.Level → Ix.Level + | .zero h => .zero h + | .succ x _ => Level.mkSucc (substLevelParamsList params lvls x) + | .max x y _ => Level.mkMax (substLevelParamsList params lvls x) (substLevelParamsList params lvls y) + | .imax x y _ => Level.mkIMax (substLevelParamsList params lvls x) (substLevelParamsList params lvls y) + | l@(.param n _) => + match lookupLevelParam params lvls n with + | some v => v + | none => l + | l@(.mvar _ _) => l + +def substLevelParams (params : Array Ix.Name) (lvls : Array Ix.Level) (u : Ix.Level) : Ix.Level := + substLevelParamsList params.toList lvls.toList u + +/-- Substitute universe parameter names `params` with `lvls` throughout an `Ix.Expr`. -/ +def substLevelParamsListMap (pList : List Ix.Name) (lList : List Ix.Level) : List Ix.Level → List Ix.Level + | [] => [] + | u :: us => substLevelParamsList pList lList u :: substLevelParamsListMap pList lList us + +def substExprLevelParams (params : Array Ix.Name) (lvls : Array Ix.Level) (e : Ix.Expr) : Ix.Expr := + match params.toList, lvls.toList with + | [], _ | _, [] => e + | pList, lList => + let rec go : Ix.Expr → Ix.Expr + | .sort u _ => Expr.mkSort (substLevelParamsList pList lList u) + | c@(.const nm us _) => + match us.toList with + | [] => c + | uls => Expr.mkConst nm (Array.mk (substLevelParamsListMap pList lList uls)) + | .app f a _ => Expr.mkApp (go f) (go a) + | .lam nm t b bi _ => Expr.mkLam nm (go t) (go b) bi + | .forallE nm t b bi _ => Expr.mkForallE nm (go t) (go b) bi + | .letE nm t v b nd _ => Expr.mkLetE nm (go t) (go v) (go b) nd + | .proj nm i s _ => Expr.mkProj nm i (go s) + | .mdata md x _ => Expr.mkMData md (go x) + | other => other + go e + +/-- True if universe level `u` contains any `.mvar`. -/ +def hasLevelMVar : Ix.Level → Bool + | .zero _ | .param _ _ => false + | .mvar _ _ => true + | .succ x _ => hasLevelMVar x + | .max x y _ => hasLevelMVar x || hasLevelMVar y + | .imax x y _ => hasLevelMVar x || hasLevelMVar y + +def listAnyLevelMVar : List Ix.Level → Bool + | [] => false + | u :: us => if hasLevelMVar u then true else listAnyLevelMVar us + +/-- True if expression `e` contains any expression `.mvar` or universe level `.mvar`. -/ +def hasExprOrLevelMVar : Ix.Expr → Bool + | .bvar _ _ | .fvar _ _ | .lit _ _ => false + | .mvar _ _ => true + | .sort u _ => hasLevelMVar u + | .const _ us _ => listAnyLevelMVar us.toList + | .app f a _ => hasExprOrLevelMVar f || hasExprOrLevelMVar a + | .lam _ t b _ _ => hasExprOrLevelMVar t || hasExprOrLevelMVar b + | .forallE _ t b _ _ => hasExprOrLevelMVar t || hasExprOrLevelMVar b + | .letE _ t v b _ _ => hasExprOrLevelMVar t || hasExprOrLevelMVar v || hasExprOrLevelMVar b + | .proj _ _ s _ => hasExprOrLevelMVar s + | .mdata _ x _ => hasExprOrLevelMVar x + +/-- Pure first-order level metavariable instantiation (zero `IxElabM` closure overhead). -/ +def instantiateLevelMVarsPure (mctx : MetavarContext) : Nat → Ix.Level → Ix.Level + | 0, u => u + | fuel + 1, u => + match u with + | .zero _ | .param _ _ => u + | .succ x _ => Level.mkSucc (instantiateLevelMVarsPure mctx fuel x) + | .max x y _ => Level.mkMax (instantiateLevelMVarsPure mctx fuel x) (instantiateLevelMVarsPure mctx fuel y) + | .imax x y _ => Level.mkIMax (instantiateLevelMVarsPure mctx fuel x) (instantiateLevelMVarsPure mctx fuel y) + | .mvar id _ => + match mctx.getLevelAssignment? id with + | some assigned => + if hasLevelMVar assigned then instantiateLevelMVarsPure mctx fuel assigned else assigned + | none => u + +/-- Helper for `instantiateLevelMVars` (assumes `u` contains at least one level mvar). -/ +@[inline] def instantiateLevelMVarsCore (fuel : Nat) (u : Ix.Level) : IxElabM Ix.Level := + fun _ st => .ok (instantiateLevelMVarsPure st.mctx fuel u) st + +/-- Instantiate assigned level metavariables in `u` (structurally recursive on `fuel`). -/ +@[inline] def instantiateLevelMVars (fuel : Nat) (u : Ix.Level) : IxElabM Ix.Level := + fun _ st => + if !hasLevelMVar u || st.mctx.lvlAssigns.isEmpty then .ok u st + else .ok (instantiateLevelMVarsPure st.mctx fuel u) st + +/-- Smart `max` constructor on already-normalized levels. -/ +def mkMaxNorm (a b : Ix.Level) : Ix.Level := + if a == b then a + else match a, b with + | .zero _, _ => b + | _, .zero _ => a + | .succ x _, .succ y _ => Level.mkSucc (mkMaxNorm x y) + | _, _ => Level.mkMax a b + +/-- Smart `imax` constructor on already-normalized levels. -/ +def mkIMaxNorm (a b : Ix.Level) : Ix.Level := + match b with + | .zero _ => b + | .succ _ _ => mkMaxNorm a b + | _ => + if a == b then a + else match a with + | .zero _ | .succ (.zero _) _ => b + | _ => Level.mkIMax a b + +/-- Simplify `max` and `imax` universe levels where statically reducible. -/ +def normalizeLevel : Ix.Level → Ix.Level + | .zero h => .zero h + | .succ x _ => Level.mkSucc (normalizeLevel x) + | .max a b _ => mkMaxNorm (normalizeLevel a) (normalizeLevel b) + | .imax a b _ => mkIMaxNorm (normalizeLevel a) (normalizeLevel b) + | u => u + +/-- Check whether `uvarId` occurs in `u`. -/ +def occursLevelMVar (uvarId : Ix.Name) : Ix.Level → Bool + | .zero _ | .param _ _ => false + | .succ x _ => occursLevelMVar uvarId x + | .max x y _ => occursLevelMVar uvarId x || occursLevelMVar uvarId y + | .imax x y _ => occursLevelMVar uvarId x || occursLevelMVar uvarId y + | .mvar id _ => id == uvarId + +/-- Pure first-order universe level unification (zero `IxElabM` closures). -/ +def isLevelDefEqPure (st : ElabState) : Nat → Ix.Level → Ix.Level → Bool × ElabState + | 0, u, v => (normalizeLevel u == normalizeLevel v, st) + | fuel + 1, u, v => + let u := normalizeLevel (if !hasLevelMVar u || st.mctx.lvlAssigns.isEmpty then u else instantiateLevelMVarsPure st.mctx 32 u) + let v := normalizeLevel (if !hasLevelMVar v || st.mctx.lvlAssigns.isEmpty then v else instantiateLevelMVarsPure st.mctx 32 v) + if u == v then (true, st) + else match u, v with + | .mvar id _, _ => + if occursLevelMVar id v then (false, st) + else (true, { st with mctx := st.mctx.assignLevel id v }) + | _, .mvar id _ => + if occursLevelMVar id u then (false, st) + else (true, { st with mctx := st.mctx.assignLevel id u }) + | .succ a _, .succ b _ => + isLevelDefEqPure st fuel a b + | .max a1 a2 _, .max b1 b2 _ => + let (ok1, st1) := isLevelDefEqPure st fuel a1 b1 + if ok1 then isLevelDefEqPure st1 fuel a2 b2 else (false, st1) + | .imax a1 a2 _, .imax b1 b2 _ => + let (ok1, st1) := isLevelDefEqPure st fuel a1 b1 + if ok1 then isLevelDefEqPure st1 fuel a2 b2 else (false, st1) + | _, _ => (false, st) + +/-- Unify two universe levels `u` and `v`, assigning level metavariables when needed. -/ +@[inline] def isLevelDefEq (fuel : Nat) (u v : Ix.Level) : IxElabM Bool := + fun _ st => + let (ok, st') := isLevelDefEqPure st fuel u v + .ok ok st' + +/-- Pure first-order fresh level mvar allocator. -/ +@[inline] def mkFreshLevelMVarPure (st : ElabState) : Ix.Level × ElabState := + let (id, st') := mkFreshNamePure st (str% "_uvar") + (Level.mkMVar id, st') + +/-- Pure first-order fresh expression mvar allocator. -/ +@[inline] def mkFreshExprMVarPure (ctx : ElabContext) (st : ElabState) + (type : Ix.Expr) (userName : Ix.Name := Name.mkAnon) : Ix.Expr × ElabState := + let (mvarId, st1) := mkFreshNamePure st (str% "_mvar") + let decl : MetavarDecl := { mvarId, userName, lctx := ctx.lctx, type } + (Expr.mkMVar mvarId, { st1 with mctx := st1.mctx.addExprMVarDecl decl }) + +/-- Create a fresh universe level metavariable `?u`. -/ +@[inline] def mkFreshLevelMVar : IxElabM Ix.Level := + fun _ st => + let (u, st') := mkFreshLevelMVarPure st + .ok u st' + +/-- Create a fresh expression metavariable `?m : type` in the current `LocalContext`. -/ +@[inline] def mkFreshExprMVar (type : Ix.Expr) (userName : Ix.Name := Name.mkAnon) : IxElabM Ix.Expr := + fun ctx st => + let (m, st') := mkFreshExprMVarPure ctx st type userName + .ok m st' + +def instNormLevelsPure (mctx : MetavarContext) : List Ix.Level → List Ix.Level + | [] => [] + | u :: us => + let u' := if hasLevelMVar u then normalizeLevel (instantiateLevelMVarsPure mctx 32 u) else u + u' :: instNormLevelsPure mctx us + +/-- Pure first-order expression metavariable instantiation (zero `IxElabM` / `List.mapM` overhead). -/ +def instantiateMVarsPure (mctx : MetavarContext) : Nat → Ix.Expr → Ix.Expr + | 0, e => e + | fuel + 1, e => + match e with + | .bvar _ _ | .fvar _ _ | .lit _ _ => e + | .sort u _ => + if !hasLevelMVar u || mctx.lvlAssigns.isEmpty then e + else Expr.mkSort (normalizeLevel (instantiateLevelMVarsPure mctx 32 u)) + | .const nm us _ => + if mctx.lvlAssigns.isEmpty || !(listAnyLevelMVar us.toList) then e + else + Expr.mkConst nm (Array.mk (instNormLevelsPure mctx us.toList)) + | .mvar id _ => + match mctx.getExprAssignment? id with + | some val => + if hasExprOrLevelMVar val then instantiateMVarsPure mctx fuel val else val + | none => + match mctx.getDelayedAssignment? id with + | some d => + let inner := instantiateMVarsPure mctx fuel (Expr.mkMVar d.pendingMVar) + let closed := mkLambdaFVarsList d.lctx d.fvars inner + if hasExprOrLevelMVar closed then instantiateMVarsPure mctx fuel closed else closed + | none => e + | .app f a _ => + Expr.mkApp (instantiateMVarsPure mctx fuel f) (instantiateMVarsPure mctx fuel a) + | .lam nm t b bi _ => + Expr.mkLam nm (instantiateMVarsPure mctx fuel t) (instantiateMVarsPure mctx fuel b) bi + | .forallE nm t b bi _ => + Expr.mkForallE nm (instantiateMVarsPure mctx fuel t) (instantiateMVarsPure mctx fuel b) bi + | .letE nm t v b nd _ => + Expr.mkLetE nm (instantiateMVarsPure mctx fuel t) (instantiateMVarsPure mctx fuel v) (instantiateMVarsPure mctx fuel b) nd + | .proj nm i s _ => + Expr.mkProj nm i (instantiateMVarsPure mctx fuel s) + | .mdata md x _ => + Expr.mkMData md (instantiateMVarsPure mctx fuel x) + +/-- Single bottom-up pass for `instantiateMVars` without repeating `hasExprOrLevelMVar` at internal nodes. -/ +@[inline] def instantiateMVarsCore (fuel : Nat) (e : Ix.Expr) : IxElabM Ix.Expr := + fun _ st => .ok (instantiateMVarsPure st.mctx fuel e) st + +/-- Instantiate assigned expression and universe level metavariables throughout `e`. -/ +@[inline] def instantiateMVars (fuel : Nat) (e : Ix.Expr) : IxElabM Ix.Expr := + fun _ st => + if st.mctx.exprAssigns.isEmpty && st.mctx.lvlAssigns.isEmpty && st.mctx.delayedAssigns.isEmpty then .ok e st + else if !hasExprOrLevelMVar e then .ok e st + else .ok (instantiateMVarsPure st.mctx fuel e) st + +/-- Check whether `mvarId` occurs in `e` (returns `true` if `mvarId` occurs). -/ +def occursCheckMVar (mvarId : Ix.Name) : Ix.Expr → Bool + | .mvar id _ => id == mvarId + | .app f a _ => occursCheckMVar mvarId f || occursCheckMVar mvarId a + | .lam _ t b _ _ => occursCheckMVar mvarId t || occursCheckMVar mvarId b + | .forallE _ t b _ _ => occursCheckMVar mvarId t || occursCheckMVar mvarId b + | .letE _ t v b _ _ => occursCheckMVar mvarId t || occursCheckMVar mvarId v || occursCheckMVar mvarId b + | .proj _ _ s _ => occursCheckMVar mvarId s + | .mdata _ x _ => occursCheckMVar mvarId x + | _ => false + +/-- Collect any unassigned level metavariables in `u` and replace them with `.zero` + (used when finalizing top-level declarations if a level mvar remained unconstrained). -/ +def defaultUnassignedLevelMVars : Ix.Level → Ix.Level + | .zero h => .zero h + | .param n h => .param n h + | .mvar _ _ => Level.mkZero + | .succ x _ => Level.mkSucc (defaultUnassignedLevelMVars x) + | .max x y _ => normalizeLevel (Level.mkMax (defaultUnassignedLevelMVars x) (defaultUnassignedLevelMVars y)) + | .imax x y _ => normalizeLevel (Level.mkIMax (defaultUnassignedLevelMVars x) (defaultUnassignedLevelMVars y)) + +def defaultUnassignedLevelsList : List Ix.Level → List Ix.Level + | [] => [] + | u :: us => defaultUnassignedLevelMVars u :: defaultUnassignedLevelsList us + +/-- True if `e` contains any universe level metavariable (`.mvar`). -/ +def hasExprLevelMVar : Ix.Expr → Bool + | .sort u _ => hasLevelMVar u + | .const _ us _ => listAnyLevelMVar us.toList + | .app f a _ => hasExprLevelMVar f || hasExprLevelMVar a + | .lam _ t b _ _ => hasExprLevelMVar t || hasExprLevelMVar b + | .forallE _ t b _ _ => hasExprLevelMVar t || hasExprLevelMVar b + | .letE _ t v b _ _ => hasExprLevelMVar t || hasExprLevelMVar v || hasExprLevelMVar b + | .proj _ _ s _ => hasExprLevelMVar s + | .mdata _ x _ => hasExprLevelMVar x + | _ => false + +def defaultUnassignedExprLevelMVarsCore : Ix.Expr → Ix.Expr + | .sort u _ => Expr.mkSort (defaultUnassignedLevelMVars u) + | c@(.const nm us _) => + match us.toList with + | [] => c + | uls => Expr.mkConst nm (Array.mk (defaultUnassignedLevelsList uls)) + | .app f a _ => Expr.mkApp (defaultUnassignedExprLevelMVarsCore f) (defaultUnassignedExprLevelMVarsCore a) + | .lam nm t b bi _ => Expr.mkLam nm (defaultUnassignedExprLevelMVarsCore t) (defaultUnassignedExprLevelMVarsCore b) bi + | .forallE nm t b bi _ => Expr.mkForallE nm (defaultUnassignedExprLevelMVarsCore t) (defaultUnassignedExprLevelMVarsCore b) bi + | .letE nm t v b nd _ => Expr.mkLetE nm (defaultUnassignedExprLevelMVarsCore t) (defaultUnassignedExprLevelMVarsCore v) (defaultUnassignedExprLevelMVarsCore b) nd + | .proj nm i s _ => Expr.mkProj nm i (defaultUnassignedExprLevelMVarsCore s) + | .mdata md x _ => Expr.mkMData md (defaultUnassignedExprLevelMVarsCore x) + | other => other + +def defaultUnassignedExprLevelMVars (e : Ix.Expr) : Ix.Expr := + if !hasExprLevelMVar e then e else defaultUnassignedExprLevelMVarsCore e + +/-! ## Weak-Head Normal Form (`whnf`) -/ + +/-- Decode a `Nat` value from an `Ix.Expr` (either `.lit (.natVal n)` or `Nat.zero` / `Nat.succ`). -/ +def evalNatLit? : Nat → Ix.Expr → Option Nat + | 0, _ => none + | fuel + 1, e => + match stripMData e with + | .lit (.natVal n) _ => some n + | .const nm _ _ => + if nm == Name.mkStr2 (str% "Nat") (str% "zero") then some 0 else none + | .app fn arg _ => + match stripMData fn with + | .const nm _ _ => + if nm == Name.mkStr2 (str% "Nat") (str% "succ") then + (evalNatLit? fuel arg).map (· + 1) + else none + | _ => none + | _ => none + +/-- Decode a Unicode scalar codepoint (`Nat`) from `Char.ofNat n` (zero `Char`/`UInt32`). -/ +def evalCharCode? (fuel : Nat) (e : Ix.Expr) : Option Nat := + match stripMData e with + | .app fn arg _ => + match stripMData fn with + | .const nm _ _ => + if nm == Name.mkStr2 (str% "Char") (str% "ofNat") then + evalNatLit? fuel arg + else none + | _ => none + | _ => none + +/-- Decode a `List Nat` of Unicode scalar codepoints from `List.nil` / `List.cons Char c tail`. -/ +def evalCharCodeList? : Nat → Ix.Expr → Option (List Nat) + | 0, _ => none + | fuel + 1, e => + let (fn, args) := getAppFnArgs (stripMData e) + match fn with + | .const nm _ _ => + if nm == Name.mkStr2 (str% "List") (str% "nil") && args.size == 1 then + some [] + else if nm == Name.mkStr2 (str% "List") (str% "cons") && args.size == 3 then + match evalCharCode? 16 (args.getD 1 e), evalCharCodeList? fuel (args.getD 2 e) with + | some c, some cs => some (c :: cs) + | _, _ => none + else none + | _ => none + +/-- UTF-8 byte size of a Unicode scalar codepoint `c : Nat`. -/ +def charCodeUtf8Size (c : Nat) : Nat := + if c < 0x80 then 1 + else if c < 0x800 then 2 + else if c < 0x10000 then 3 + else 4 + +/-- Encode a Unicode scalar codepoint `c : Nat` into UTF-8 bytes prepended to `tail`. -/ +def encodeCodepointUtf8 (c : Nat) (tail : Sym) : Sym := + if c < 0x80 then + .cons c tail + else if c < 0x800 then + .cons (0xC0 + c / 64) (.cons (0x80 + c % 64) tail) + else if c < 0x10000 then + .cons (0xE0 + c / 4096) (.cons (0x80 + (c / 64) % 64) (.cons (0x80 + c % 64) tail)) + else + .cons (0xF0 + c / 262144) (.cons (0x80 + (c / 4096) % 64) (.cons (0x80 + (c / 64) % 64) (.cons (0x80 + c % 64) tail))) + +/-- Encode a `List Nat` of Unicode scalar codepoints into a UTF-8 `Sym`. -/ +def encodeCodepointsUtf8 : List Nat → Sym + | [] => .nil + | c :: rest => encodeCodepointUtf8 c (encodeCodepointsUtf8 rest) + +/-- Decode a UTF-8 `Sym` into a `List Nat` of Unicode scalar codepoints. -/ +def decodeUtf8Codepoints : Sym → List Nat + | .nil => [] + | .cons b0 rest => + if b0 < 0x80 then + b0 :: decodeUtf8Codepoints rest + else if b0 < 0xE0 then + match rest with + | .cons b1 r1 => ((b0 - 0xC0) * 64 + (b1 - 0x80)) :: decodeUtf8Codepoints r1 + | _ => [] + else if b0 < 0xF0 then + match rest with + | .cons b1 (.cons b2 r2) => + ((b0 - 0xE0) * 4096 + (b1 - 0x80) * 64 + (b2 - 0x80)) :: decodeUtf8Codepoints r2 + | _ => [] + else + match rest with + | .cons b1 (.cons b2 (.cons b3 r3)) => + ((b0 - 0xF0) * 262144 + (b1 - 0x80) * 4096 + (b2 - 0x80) * 64 + (b3 - 0x80)) :: decodeUtf8Codepoints r3 + | _ => [] + +/-- Build a `List Char` expression from codepoints `cs : List Nat`. -/ +def mkCharCodeListExpr (cs : List Nat) : Ix.Expr := + let charTy := Expr.mkConst (Name.simple (str% "Char")) #[] + let nilExpr := Expr.mkApp (Expr.mkConst (Name.mkStr2 (str% "List") (str% "nil")) #[Level.mkZero]) charTy + let consConst := Expr.mkApp (Expr.mkConst (Name.mkStr2 (str% "List") (str% "cons")) #[Level.mkZero]) charTy + let charOfNat := Expr.mkConst (Name.mkStr2 (str% "Char") (str% "ofNat")) #[] + let rec go : List Nat → Ix.Expr + | [] => nilExpr + | c :: rest => + let cExpr := Expr.mkApp charOfNat (Expr.mkNatLit c) + Expr.mkApp (Expr.mkApp consConst cExpr) (go rest) + go cs + +/-- Expand a string literal `s` into constructor form `String.mk [Char.ofNat c₁, ...]`. -/ +def strLitToCtorExpr (s : String) : Ix.Expr := + Expr.mkApp (Expr.mkConst (Name.mkStr2 (str% "String") (str% "mk")) #[]) + (mkCharCodeListExpr (decodeUtf8Codepoints (Sym.ofString s))) + +/-- Construct `Bool.true` or `Bool.false` as an `Ix.Expr`. -/ +def mkBoolExpr (b : Bool) : Ix.Expr := + Expr.mkConst (Name.mkStr2 (str% "Bool") (if b then (str% "true") else (str% "false"))) #[] + +/-- Fast-path reduction for unary `Nat` / `String` / `Char` primitives on WHNF argument `a0`. -/ +def tryReduceUnaryPrim (nm : Ix.Name) (a0 : Ix.Expr) : Option Ix.Expr := + if nm == Name.mkStr2 (str% "Nat") (str% "pred") then + match evalNatLit? 16 a0 with + | some n => some (Expr.mkNatLit (n - 1)) + | none => none + else if nm == Name.mkStr2 (str% "Nat") (str% "succ") then + match evalNatLit? 16 a0 with + | some n => some (Expr.mkNatLit (n + 1)) + | none => none + else if nm == Name.mkStr2 (str% "Char") (str% "toNat") then + match evalCharCode? 16 a0 with + | some c => some (Expr.mkNatLit c) + | none => none + else if nm == Name.mkStr2 (str% "Char") (str% "utf8Size") then + match evalCharCode? 16 a0 with + | some c => some (Expr.mkNatLit (charCodeUtf8Size c)) + | none => none + else if nm == Name.mkStr2 (str% "String") (str% "utf8ByteSize") then + match stripMData a0 with + | .lit (.strVal s) _ => some (Expr.mkNatLit s.toUTF8.size) + | _ => none + else if nm == Name.mkStr2 (str% "String") (str% "length") then + match stripMData a0 with + | .lit (.strVal s) _ => some (Expr.mkNatLit (Sym.utf8CharCount (Sym.ofString s))) + | _ => none + else if nm == Name.mkStr2 (str% "String") (str% "isEmpty") then + match stripMData a0 with + | .lit (.strVal s) _ => some (mkBoolExpr (s.toUTF8.size == 0)) + | _ => none + else if nm == Name.mkStr2 (str% "String") (str% "toList") then + match stripMData a0 with + | .lit (.strVal s) _ => some (mkCharCodeListExpr (decodeUtf8Codepoints (Sym.ofString s))) + | _ => none + else if nm == Name.mkStr2 (str% "String") (str% "ofList") || nm == Name.mkStr2 (str% "String") (str% "mk") then + match evalCharCodeList? 128 a0 with + | some cs => some (Expr.mkStrLit (Sym.toString (encodeCodepointsUtf8 cs))) + | none => none + else if nm == Name.mkStr2 (str% "String") (str% "singleton") then + match evalCharCode? 16 a0 with + | some c => some (Expr.mkStrLit (Sym.toString (encodeCodepointUtf8 c .nil))) + | none => none + else if nm == Name.mkStr2 (str% "String") (str% "back") then + match stripMData a0 with + | .lit (.strVal s) _ => + let rec lastCode (d : Nat) : List Nat → Nat + | [] => d + | [c] => c + | _ :: rest => lastCode d rest + let c := lastCode 65 (decodeUtf8Codepoints (Sym.ofString s)) + some (Expr.mkApp (Expr.mkConst (Name.mkStr2 (str% "Char") (str% "ofNat")) #[]) (Expr.mkNatLit c)) + | _ => none + else none + +/-- Pure recursive `Nat` exponentiation (avoids `Nat.pow` primitive in Aiur backend). -/ +def natPowPure (base : Nat) : Nat → Nat + | 0 => 1 + | k + 1 => base * natPowPure base k + +/-- Fast-path reduction for binary `Nat` / `String` primitives on WHNF arguments `a0`, `a1`. -/ +def tryReduceBinaryPrim (nm : Ix.Name) (a0 a1 : Ix.Expr) : Option Ix.Expr := + if nm == Name.mkStr2 (str% "Nat") (str% "add") then + match evalNatLit? 16 a0 with + | some n1 => match evalNatLit? 16 a1 with | some n2 => some (Expr.mkNatLit (n1 + n2)) | none => none + | none => none + else if nm == Name.mkStr2 (str% "Nat") (str% "sub") then + match evalNatLit? 16 a0 with + | some n1 => match evalNatLit? 16 a1 with | some n2 => some (Expr.mkNatLit (n1 - n2)) | none => none + | none => none + else if nm == Name.mkStr2 (str% "Nat") (str% "mul") then + match evalNatLit? 16 a0 with + | some n1 => match evalNatLit? 16 a1 with | some n2 => some (Expr.mkNatLit (n1 * n2)) | none => none + | none => none + else if nm == Name.mkStr2 (str% "Nat") (str% "div") then + match evalNatLit? 16 a0 with + | some n1 => match evalNatLit? 16 a1 with | some n2 => some (Expr.mkNatLit (n1 / n2)) | none => none + | none => none + else if nm == Name.mkStr2 (str% "Nat") (str% "mod") then + match evalNatLit? 16 a0 with + | some n1 => match evalNatLit? 16 a1 with | some n2 => some (Expr.mkNatLit (n1 % n2)) | none => none + | none => none + else if nm == Name.mkStr2 (str% "Nat") (str% "pow") then + match evalNatLit? 16 a0 with + | some n1 => + match evalNatLit? 16 a1 with + | some n2 => if n2 ≤ 256 then some (Expr.mkNatLit (natPowPure n1 n2)) else none + | none => none + | none => none + else if nm == Name.mkStr2 (str% "Nat") (str% "beq") then + match evalNatLit? 16 a0 with + | some n1 => match evalNatLit? 16 a1 with | some n2 => some (mkBoolExpr (n1 == n2)) | none => none + | none => none + else if nm == Name.mkStr2 (str% "Nat") (str% "ble") then + match evalNatLit? 16 a0 with + | some n1 => match evalNatLit? 16 a1 with | some n2 => some (mkBoolExpr (n1 ≤ n2)) | none => none + | none => none + else if nm == Name.mkStr2 (str% "String") (str% "append") then + match stripMData a0 with + | .lit (.strVal s1) _ => + match stripMData a1 with + | .lit (.strVal s2) _ => + some (Expr.mkStrLit (Sym.toString (Sym.append (Sym.ofString s1) (Sym.ofString s2)))) + | _ => none + | _ => none + else if nm == Name.mkStr2 (str% "String") (str% "push") then + match stripMData a0 with + | .lit (.strVal s) _ => + match evalCharCode? 16 a1 with + | some c => some (Expr.mkStrLit (Sym.toString (Sym.append (Sym.ofString s) (encodeCodepointUtf8 c .nil)))) + | none => none + | _ => none + else none + +def findRecRulePure (ctorName : Ix.Name) : List Ix.RecursorRule → Option Ix.RecursorRule + | [] => none + | r :: rest => if r.ctor == ctorName then some r else findRecRulePure ctorName rest + +def listSliceMeta {α : Type} : List α → Nat → Nat → List α + | [], _, _ => [] + | x :: xs, start, stop => + if stop == 0 then [] + else if start == 0 then x :: listSliceMeta xs 0 (stop - 1) + else listSliceMeta xs (start - 1) (stop - 1) + +@[inline] def arrAppendMeta {α : Type} (a b : Array α) : Array α := + Array.mk (a.toList ++ b.toList) + +@[inline] def arrExtractMeta {α : Type} (a : Array α) (start stop : Nat) : Array α := + Array.mk (listSliceMeta a.toList start stop) + +/-- Pure first-order Weak-Head Normal Form (`whnfPure`), zero `IxElabM` closure overhead. -/ +def whnfPure (ctx : ElabContext) (st : ElabState) : Nat → Ix.Expr → Ix.Expr + | 0, e => stripMData e + | fuel + 1, e => + let e := stripMData e + match e with + -- 0. Assigned expression metavariable unfolding + | .mvar mvarId _ => + match st.mctx.getExprAssignment? mvarId with + | some val => whnfPure ctx st fuel val + | none => e + -- 1. Local `let` free variable unfolding (ζ-local) + | .fvar fvarId _ => + match ctx.lctx.findFVar? fvarId with + | some decl => + match decl.value? with + | some val => whnfPure ctx st fuel val + | none => e + | none => e + -- 2. `let x : t := v in b` (ζ-reduction) + | .letE _ _ v b _ _ => + whnfPure ctx st fuel (instantiate1 b v) + -- 3. Structure projection `.proj typeName idx s` + | .proj typeName idx s _ => + let sWhnf := whnfPure ctx st fuel s + let sExpanded := match sWhnf with + | .lit (.strVal str) _ => strLitToCtorExpr str + | other => other + let (ctorFn, ctorArgs) := getAppFnArgs sExpanded + match ctorFn with + | .const ctorName _ _ => + match st.env.find? ctorName with + | some (.ctorInfo cval) => + if cval.induct == typeName && cval.numParams + idx < ctorArgs.size then + whnfPure ctx st fuel (ctorArgs.getD (cval.numParams + idx) e) + else + Expr.mkProj typeName idx sWhnf + | _ => Expr.mkProj typeName idx sWhnf + | _ => Expr.mkProj typeName idx sWhnf + -- 4. Constant unfolding (δ-reduction) + | .const nm us _ => + match st.env.find? nm with + | some (.defnInfo dval) => + let body := substExprLevelParams dval.cnst.levelParams us dval.value + whnfPure ctx st fuel body + | _ => e + -- 5. Application spine: β-reduction, ι-reduction, Nat/String/Char primitives, δ-unfolding + | .app _ _ _ => + let (fn, args) := getAppFnArgs e + let fnWhnf := whnfPure ctx st fuel fn + let (headFn, headArgs) := getAppFnArgs fnWhnf + let allArgs := arrAppendMeta headArgs args + match headFn with + -- 5a. β-reduction: `(fun x => body) a₀ a₁ ...` + | .lam _ _ body _ _ => + if allArgs.isEmpty then headFn + else + let firstArg := allArgs.getD 0 headFn + let restArgs := arrExtractMeta allArgs 1 allArgs.size + let reduced := Expr.mkAppN (instantiate1 body firstArg) restArgs + whnfPure ctx st fuel reduced + -- 5b. Constant head: primitives, ι-reduction (`.recInfo`), or δ-unfolding (`.defnInfo`) + | .const nm us _ => + let primHit? : Option Ix.Expr := + if allArgs.size == 1 then + tryReduceUnaryPrim nm (whnfPure ctx st fuel (allArgs.getD 0 headFn)) + else if allArgs.size == 2 then + tryReduceBinaryPrim nm + (whnfPure ctx st fuel (allArgs.getD 0 headFn)) + (whnfPure ctx st fuel (allArgs.getD 1 headFn)) + else none + match primHit? with + | some res => res + | none => + match st.env.find? nm with + | some (.recInfo rval) => + let majorIdx := rval.numParams + rval.numMotives + rval.numMinors + rval.numIndices + if majorIdx < allArgs.size then + let majorWhnf := whnfPure ctx st fuel (allArgs.getD majorIdx headFn) + let majorExpanded := match majorWhnf with + | .lit (.natVal 0) _ => Expr.mkConst (Name.mkStr2 (str% "Nat") (str% "zero")) #[] + | .lit (.natVal (k + 1)) _ => + Expr.mkApp (Expr.mkConst (Name.mkStr2 (str% "Nat") (str% "succ")) #[]) (Expr.mkNatLit k) + | .lit (.strVal str) _ => strLitToCtorExpr str + | other => other + let (mFn, mArgs) := getAppFnArgs majorExpanded + match mFn with + | .const ctorName _ _ => + match findRecRulePure ctorName rval.rules.toList with + | some rule => + if mArgs.size ≥ mArgs.size - rule.nfields then + let fields := arrExtractMeta mArgs (mArgs.size - rule.nfields) mArgs.size + let paramsMotivesMinors := arrExtractMeta allArgs 0 (rval.numParams + rval.numMotives + rval.numMinors) + let extraArgs := arrExtractMeta allArgs (majorIdx + 1) allArgs.size + let rhsInst := substExprLevelParams rval.cnst.levelParams us rule.rhs + let applied := Expr.mkAppN rhsInst (arrAppendMeta (arrAppendMeta paramsMotivesMinors fields) extraArgs) + whnfPure ctx st fuel applied + else + Expr.mkAppN headFn allArgs + | none => Expr.mkAppN headFn allArgs + | _ => Expr.mkAppN headFn allArgs + else + Expr.mkAppN headFn allArgs + | some (.defnInfo dval) => + let body := substExprLevelParams dval.cnst.levelParams us dval.value + whnfPure ctx st fuel (Expr.mkAppN body allArgs) + | _ => + Expr.mkAppN headFn allArgs + | _ => + Expr.mkAppN headFn allArgs + | _ => e + +/-- Compute Weak-Head Normal Form (`whnf`) of `e`, bounded by `fuel : Nat`. -/ +@[inline] def whnf (fuel : Nat) (e : Ix.Expr) : IxElabM Ix.Expr := + fun ctx st => .ok (whnfPure ctx st fuel e) st + +/-! ## Type Inference (`inferType`, `ensureSort`, `ensureForall`) -/ + +def applyProjParamsPure (ctx : ElabContext) (st : ElabState) (fuelP : Nat) : + List Ix.Expr → Ix.Expr → Ix.Expr + | [], cur => cur + | p :: rest, cur => + match stripMData (whnfPure ctx st fuelP cur) with + | .forallE _ _ b _ _ => applyProjParamsPure ctx st fuelP rest (instantiate1 b p) + | _ => applyProjParamsPure ctx st fuelP rest cur + +def applyPrevProjsPure (ctx : ElabContext) (st : ElabState) (fuelP : Nat) + (structName : Ix.Name) (s : Ix.Expr) : Nat → Nat → Ix.Expr → Ix.Expr + | 0, _, cur => cur + | rem + 1, i, cur => + match stripMData (whnfPure ctx st fuelP cur) with + | .forallE _ _ b _ _ => + applyPrevProjsPure ctx st fuelP structName s rem (i + 1) (instantiate1 b (Expr.mkProj structName i s)) + | _ => applyPrevProjsPure ctx st fuelP structName s rem (i + 1) cur + +/-- Pure first-order type inference (zero `IxElabM` closures, zero CPS `withLocalDecl`, zero `List.mapM`). -/ +def inferTypePure (ctx : ElabContext) (st : ElabState) : Nat → Ix.Expr → ElabRes Ix.Expr + | 0, _ => .error { pos? := ctx.refPos?, msg := str% "elaborator fuel exhausted in inferType" } + | fuel + 1, e => + let e := stripMData e + match e with + | .bvar _ _ => + .error { pos? := ctx.refPos?, msg := str% "unexpected loose bound variable in inferType" } + | .fvar fvarId _ => + match ctx.lctx.findFVar? fvarId with + | some decl => .ok decl.type st + | none => .error { pos? := ctx.refPos?, msg := str% "unknown free variable" } + | .mvar mvarId _ => + match st.mctx.getExprAssignment? mvarId with + | some val => inferTypePure ctx st fuel val + | none => + match st.mctx.findDecl? mvarId with + | some decl => .ok decl.type st + | none => .error { pos? := ctx.refPos?, msg := str% "unknown metavariable" } + | .sort u _ => + let u' := if !hasLevelMVar u || st.mctx.lvlAssigns.isEmpty then u else instantiateLevelMVarsPure st.mctx 32 u + .ok (Expr.mkSort (Level.mkSucc (normalizeLevel u'))) st + | .lit (.natVal _) _ => + .ok (Expr.mkConst (Name.simple (str% "Nat")) #[]) st + | .lit (.strVal _) _ => + .ok (Expr.mkConst (Name.simple (str% "String")) #[]) st + | .const nm us _ => + match st.env.find? nm with + | some ci => + let cnst := Expr.ConstantInfo.getCnstPure ci + match cnst.levelParams.toList, us.toList with + | [], [] => .ok cnst.type st + | pList, uList => + if pList.length != uList.length then + .error { pos? := ctx.refPos?, msg := str% "universe level count mismatch" } + else + let us' := + if !st.mctx.lvlAssigns.isEmpty && listAnyLevelMVar uList then + Array.mk (instNormLevelsPure st.mctx uList) + else us + .ok (substExprLevelParams cnst.levelParams us' cnst.type) st + | none => + .error { pos? := ctx.refPos?, msg := str% "unknown constant" } + | .app f a _ => + let (headFn, appArgs) := getAppFnArgs e + let fastTy? : Option Ix.Expr := match headFn with + | .const nm _ _ => + if appArgs.size == 6 && + (nm == Name.mkStr2 (str% "HAdd") (str% "hAdd") || nm == Name.mkStr2 (str% "HSub") (str% "hSub") || + nm == Name.mkStr2 (str% "HMul") (str% "hMul") || nm == Name.mkStr2 (str% "HDiv") (str% "hDiv") || + nm == Name.mkStr2 (str% "HMod") (str% "hMod") || nm == Name.mkStr2 (str% "HPow") (str% "hPow")) then + some (appArgs.getD 2 e) + else if appArgs.size == 3 && nm == Name.mkStr2 (str% "OfNat") (str% "ofNat") then + some (appArgs.getD 0 e) + else if (appArgs.size == 3 && (nm == Name.simple (str% "Eq") || nm == Name.simple (str% "Ne"))) || + (appArgs.size == 4 && + (nm == Name.mkStr2 (str% "LE") (str% "le") || nm == Name.mkStr2 (str% "LT") (str% "lt") || + nm == Name.mkStr2 (str% "GT") (str% "gt") || nm == Name.mkStr2 (str% "GE") (str% "ge"))) || + (appArgs.size == 2 && + (nm == Name.simple (str% "And") || nm == Name.simple (str% "Or") || nm == Name.simple (str% "Iff"))) || + (appArgs.size == 1 && nm == Name.simple (str% "Not")) then + some Expr.mkProp + else none + | _ => none + match fastTy? with + | some ty => .ok ty st + | none => + match inferTypePure ctx st fuel f with + | .error err => .error err + | .ok fType st1 => + let fTypeWhnf := whnfPure ctx st1 fuel fType + match stripMData fTypeWhnf with + | .forallE _ _ body _ _ => .ok (instantiate1 body a) st1 + | _ => + let (codLvl, st2) := mkFreshLevelMVarPure st1 + let (codTy, st3) := mkFreshExprMVarPure ctx st2 (Expr.mkSort codLvl) + .ok codTy st3 + | .lam nm dom body bi _ => + match inferTypePure ctx st fuel dom with + | .error err => .error err + | .ok _ st1 => + let (fvarId, fvarExpr, ctx', st2) := pushLocalDeclPure ctx st1 nm dom bi default + match inferTypePure ctx' st2 fuel (instantiate1 body fvarExpr) with + | .error err => .error err + | .ok bodyTy st3 => + .ok (Expr.mkForallE nm dom (abstractFVar fvarId bodyTy) bi) st3 + | .forallE nm dom body bi _ => + match inferTypePure ctx st fuel dom with + | .error err => .error err + | .ok domTy st1 => + let domTyWhnf := whnfPure ctx st1 fuel domTy + let (u1, st2) := match stripMData domTyWhnf with + | .sort u _ => + let u' := if !hasLevelMVar u || st1.mctx.lvlAssigns.isEmpty then u else instantiateLevelMVarsPure st1.mctx 32 u + (normalizeLevel u', st1) + | _ => mkFreshLevelMVarPure st1 + let resBody := + if !hasLooseBVars body then inferTypePure ctx st2 fuel body + else + let (_, fvarExpr, ctx', st3) := pushLocalDeclPure ctx st2 nm dom bi default + inferTypePure ctx' st3 fuel (instantiate1 body fvarExpr) + match resBody with + | .error err => .error err + | .ok bodyTy st4 => + let bodyTyWhnf := whnfPure ctx st4 fuel bodyTy + let (u2, st5) := match stripMData bodyTyWhnf with + | .sort v _ => + let v' := if !hasLevelMVar v || st4.mctx.lvlAssigns.isEmpty then v else instantiateLevelMVarsPure st4.mctx 32 v + (normalizeLevel v', st4) + | _ => mkFreshLevelMVarPure st4 + .ok (Expr.mkSort (normalizeLevel (Level.mkIMax u1 u2))) st5 + | .letE nm ty val body _ _ => + let (_, fvarExpr, ctx', st1) := pushLocalDeclPure ctx st nm ty .default default (some val) (some .value) false + inferTypePure ctx' st1 fuel (instantiate1 body fvarExpr) + | .proj structName idx s _ => + match inferTypePure ctx st fuel s with + | .error err => .error err + | .ok sTy st1 => + let sTyWhnf := whnfPure ctx st1 fuel sTy + let (sHead, sArgs) := getAppFnArgs sTyWhnf + match sHead with + | .const indName us _ => + match st1.env.find? indName with + | some (.inductInfo ival) => + match ival.ctors[0]? with + | some ctorName => + match st1.env.find? ctorName with + | some (.ctorInfo cval) => + let initTy := substExprLevelParams cval.cnst.levelParams us cval.cnst.type + let params := sArgs.toList.take ival.numParams + let currTy := applyProjParamsPure ctx st1 fuel params initTy + let currTy := applyPrevProjsPure ctx st1 fuel structName s idx 0 currTy + match stripMData (whnfPure ctx st1 fuel currTy) with + | .forallE _ dom _ _ _ => .ok dom st1 + | _ => .error { pos? := ctx.refPos?, msg := str% "invalid field projection index" } + | _ => .error { pos? := ctx.refPos?, msg := str% "constructor not found for projection" } + | none => .error { pos? := ctx.refPos?, msg := str% "inductive has no constructors for projection" } + | _ => .error { pos? := ctx.refPos?, msg := str% "not an inductive type in projection" } + | _ => .error { pos? := ctx.refPos?, msg := str% "cannot infer type of projection" } + | .mdata _ inner _ => + inferTypePure ctx st fuel inner + +/-- Infer the type of `e`, bounded by `fuel : Nat`. -/ +@[inline] def inferType (fuel : Nat) (e : Ix.Expr) : IxElabM Ix.Expr := + fun ctx st => inferTypePure ctx st fuel e + +/-! ## Higher-Order Unification & Definitional Equality (`isDefEq`) -/ + +/-- Pure first-order Miller pattern assignment (zero `IxElabM` / `observing?` closures). -/ +def assignMVarPatternPure (ctx : ElabContext) (st : ElabState) + (mvarId : Ix.Name) (args : Array Ix.Expr) (rhs : Ix.Expr) : Bool × ElabState := + let rhs := if st.mctx.exprAssigns.isEmpty && st.mctx.lvlAssigns.isEmpty && st.mctx.delayedAssigns.isEmpty || !hasExprOrLevelMVar rhs + then rhs else instantiateMVarsPure st.mctx 32 rhs + if occursCheckMVar mvarId rhs then (false, st) + else if args.isEmpty then + let st1 := match st.mctx.findDecl? mvarId with + | some decl => + match stripMData decl.type with + | .sort mLvl _ => + if hasLevelMVar mLvl then + match inferTypePure ctx st 16 rhs with + | .ok t stT => + match stripMData (whnfPure ctx stT 16 t) with + | .sort rLvl _ => (isLevelDefEqPure stT 16 mLvl rLvl).2 + | _ => stT + | .error _ => st + else st + | _ => st + | none => st + (true, { st1 with mctx := st1.mctx.assignExpr mvarId rhs }) + else + let rec collectDistinctFVars : List Ix.Expr → List Ix.Name → Option (Array Ix.Name) + | [], revAcc => some (Array.mk revAcc.reverse) + | arg :: rest, revAcc => + match stripMData arg with + | .fvar fvId _ => + if revAcc.any (· == fvId) then none + else collectDistinctFVars rest (fvId :: revAcc) + | _ => none + match collectDistinctFVars args.toList [] with + | none => (false, st) + | some fvarIds => + let lamVal := mkLambdaFVarsList ctx.lctx fvarIds.toList rhs + if occursCheckMVar mvarId lamVal then (false, st) + else (true, { st with mctx := st.mctx.assignExpr mvarId lamVal }) + +@[inline] def assignMVarPattern (mvarId : Ix.Name) (args : Array Ix.Expr) (rhs : Ix.Expr) : IxElabM Bool := + fun ctx st => + let (ok, st') := assignMVarPatternPure ctx st mvarId args rhs + .ok ok st' + +/-- Pure first-order pairwise level definitional equality. -/ +def allLevelDefEqPure (st : ElabState) (fuel : Nat) : List Ix.Level → List Ix.Level → Bool × ElabState + | [], [] => (true, st) + | u :: us, v :: vs => + let (ok, st1) := isLevelDefEqPure st fuel u v + if ok then allLevelDefEqPure st1 fuel us vs else (false, st1) + | _, _ => (false, st) + +/-- Check pairwise level definitional equality on two lists of equal length. -/ +@[inline] def allLevelDefEq (fuel : Nat) (us vs : List Ix.Level) : IxElabM Bool := + fun _ st => + let (ok, st') := allLevelDefEqPure st fuel us vs + .ok ok st' + +/-- Check pairwise expression definitional equality on two lists of equal length. -/ +def allExprDefEq (isDefEqFuel : Ix.Expr → Ix.Expr → IxElabM Bool) : + List Ix.Expr → List Ix.Expr → IxElabM Bool + | [], [] => return true + | a :: as, b :: bs => do + let ok ← isDefEqFuel a b + if ok then allExprDefEq isDefEqFuel as bs else return false + | _, _ => return false + +mutual +/-- Split helper for `isDefEqPure`: handle head metavariable patterns (keeps chip narrow). -/ +def isDefEqMVarStep (ctx : ElabContext) (st : ElabState) (fuel : Nat) + (t s tFn sFn : Ix.Expr) (tArgs sArgs : Array Ix.Expr) : Option (Bool × ElabState) := + match tFn with + | .mvar mId1 _ => + match sFn with + | .mvar mId2 _ => + let (sameOk, st1) := + if mId1 == mId2 then allExprDefEqPure ctx st fuel tArgs.toList sArgs.toList + else (false, st) + if sameOk then some (true, st1) + else + let (ok1, st2) := assignMVarPatternPure ctx st1 mId1 tArgs s + if ok1 then some (true, st2) + else some (assignMVarPatternPure ctx st2 mId2 sArgs t) + | _ => + let (ok, st1) := assignMVarPatternPure ctx st mId1 tArgs s + if ok then some (true, st1) + else some (assignMVarPatternPure ctx st1 mId1 tArgs (whnfPure ctx st1 fuel s)) + | _ => + match sFn with + | .mvar mId2 _ => + let (ok, st1) := assignMVarPatternPure ctx st mId2 sArgs t + if ok then some (true, st1) + else some (assignMVarPatternPure ctx st1 mId2 sArgs (whnfPure ctx st1 fuel t)) + | _ => none + +/-- Split helper for `isDefEqPure`: handle structural head forms before WHNF (keeps chip narrow). -/ +def isDefEqStructStep (ctx : ElabContext) (st : ElabState) (fuel : Nat) + (t s : Ix.Expr) : Option (Bool × ElabState) := + match t with + | .sort u _ => + match s with + | .sort v _ => some (isLevelDefEqPure st 32 u v) + | _ => none + | .bvar i _ => + match s with + | .bvar j _ => some (i == j, st) + | _ => none + | .fvar x _ => + match s with + | .fvar y _ => + if x == y then some (true, st) + else + let tW := whnfPure ctx st fuel t + let sW := whnfPure ctx st fuel s + if tW == t && sW == s then some (false, st) + else some (isDefEqPure ctx st fuel tW sW) + | _ => none + | .lit l1 _ => + match s with + | .lit l2 _ => some (l1 == l2, st) + | _ => none + | .lam nm1 d1 b1 bi1 _ => + match s with + | .lam _ d2 b2 _ _ => + let (domOk, st1) := isDefEqPure ctx st fuel d1 d2 + if !domOk then some (false, st1) + else + let (_, fv, ctx', st2) := pushLocalDeclPure ctx st1 nm1 d1 bi1 default + some (isDefEqPure ctx' st2 fuel (instantiate1 b1 fv) (instantiate1 b2 fv)) + | _ => + let (_, fv, ctx', st1) := pushLocalDeclPure ctx st nm1 d1 bi1 default + some (isDefEqPure ctx' st1 fuel (instantiate1 b1 fv) (Expr.mkApp s fv)) + | .forallE nm1 d1 b1 bi1 _ => + match s with + | .forallE _ d2 b2 _ _ => + let (domOk, st1) := isDefEqPure ctx st fuel d1 d2 + if !domOk then some (false, st1) + else + let (_, fv, ctx', st2) := pushLocalDeclPure ctx st1 nm1 d1 bi1 default + some (isDefEqPure ctx' st2 fuel (instantiate1 b1 fv) (instantiate1 b2 fv)) + | _ => none + | _ => + match s with + | .lam nm2 d2 b2 bi2 _ => + let (_, fv, ctx', st1) := pushLocalDeclPure ctx st nm2 d2 bi2 default + some (isDefEqPure ctx' st1 fuel (Expr.mkApp t fv) (instantiate1 b2 fv)) + | _ => none + +/-- Split helper for `isDefEqWhnfStep`: compare binder/sort WHNF heads (keeps choices small). -/ +def isDefEqWhnfBinderStep (ctx : ElabContext) (st : ElabState) (fuel : Nat) + (twFn swFn : Ix.Expr) : Option (Bool × ElabState) := + match twFn with + | .sort u _ => + match swFn with + | .sort v _ => some (isLevelDefEqPure st 32 u v) + | _ => some (false, st) + | .lam nm1 d1 b1 bi1 _ => + match swFn with + | .lam _ d2 b2 _ _ => + let (domOk, st1) := isDefEqPure ctx st fuel d1 d2 + if !domOk then some (false, st1) + else + let (_, fv, ctx', st2) := pushLocalDeclPure ctx st1 nm1 d1 bi1 default + some (isDefEqPure ctx' st2 fuel (instantiate1 b1 fv) (instantiate1 b2 fv)) + | _ => some (false, st) + | .forallE nm1 d1 b1 bi1 _ => + match swFn with + | .forallE _ d2 b2 _ _ => + let (domOk, st1) := isDefEqPure ctx st fuel d1 d2 + if !domOk then some (false, st1) + else + let (_, fv, ctx', st2) := pushLocalDeclPure ctx st1 nm1 d1 bi1 default + some (isDefEqPure ctx' st2 fuel (instantiate1 b1 fv) (instantiate1 b2 fv)) + | _ => some (false, st) + | _ => none + +/-- Split helper for `isDefEqWhnfStep`: compare const/fvar/proj WHNF heads (keeps choices small). -/ +def isDefEqWhnfAtomStep (ctx : ElabContext) (st : ElabState) (fuel : Nat) + (twFn swFn : Ix.Expr) (twArgs swArgs : Array Ix.Expr) : Bool × ElabState := + match twFn with + | .const c1 us1 _ => + match swFn with + | .const c2 us2 _ => + if c1 == c2 then + let (lOk, st1) := allLevelDefEqPure st 32 us1.toList us2.toList + if lOk then allExprDefEqPure ctx st1 fuel twArgs.toList swArgs.toList else (false, st1) + else (false, st) + | _ => (false, st) + | .fvar f1 _ => + match swFn with + | .fvar f2 _ => + if f1 == f2 then allExprDefEqPure ctx st fuel twArgs.toList swArgs.toList + else (false, st) + | _ => (false, st) + | .proj sn1 idx1 e1 _ => + match swFn with + | .proj sn2 idx2 e2 _ => + if sn1 == sn2 && idx1 == idx2 then isDefEqPure ctx st fuel e1 e2 + else (false, st) + | _ => (false, st) + | _ => (false, st) + +/-- Split helper for `isDefEqPure`: post-WHNF structural comparison (keeps chip narrow). -/ +def isDefEqWhnfStep (ctx : ElabContext) (st : ElabState) (fuel : Nat) + (tW sW : Ix.Expr) : Bool × ElabState := + let (twFn, twArgs) := getAppFnArgs tW + let (swFn, swArgs) := getAppFnArgs sW + match twFn with + | .mvar mId _ => assignMVarPatternPure ctx st mId twArgs sW + | _ => + match swFn with + | .mvar mId _ => assignMVarPatternPure ctx st mId swArgs tW + | _ => + match isDefEqWhnfBinderStep ctx st fuel twFn swFn with + | some res => res + | none => isDefEqWhnfAtomStep ctx st fuel twFn swFn twArgs swArgs + +/-- Pure first-order expression definitional equality (zero `IxElabM` closures, zero CPS, zero `observing?`). -/ +def isDefEqPure (ctx : ElabContext) (st : ElabState) : Nat → Ix.Expr → Ix.Expr → Bool × ElabState + | 0, t, s => (stripMData t == stripMData s, st) + | fuel + 1, t0, s0 => + let t1 := stripMData t0 + let s1 := stripMData s0 + let mEmpty := st.mctx.exprAssigns.isEmpty && st.mctx.lvlAssigns.isEmpty && st.mctx.delayedAssigns.isEmpty + let t := if mEmpty || !hasExprOrLevelMVar t1 then t1 else instantiateMVarsPure st.mctx 16 t1 + let s := if mEmpty || !hasExprOrLevelMVar s1 then s1 else instantiateMVarsPure st.mctx 16 s1 + if t == s then (true, st) + else + let (tFn, tArgs) := getAppFnArgs t + let (sFn, sArgs) := getAppFnArgs s + match isDefEqMVarStep ctx st fuel t s tFn sFn tArgs sArgs with + | some res => res + | none => + match isDefEqStructStep ctx st fuel t s with + | some res => res + | none => + let (spineOk, stSpine) := + if tArgs.isEmpty || sArgs.isEmpty then (false, st) + else + let tArgList := tArgs.toList + let sArgList := sArgs.toList + match tFn with + | .const c1 us1 _ => + match sFn with + | .const c2 us2 _ => + if c1 == c2 then + let (lOk, stL) := allLevelDefEqPure st 32 us1.toList us2.toList + if lOk then allExprDefEqPure ctx stL fuel tArgList sArgList else (false, stL) + else (false, st) + | _ => (false, st) + | .fvar f1 _ => + match sFn with + | .fvar f2 _ => + if f1 == f2 then allExprDefEqPure ctx st fuel tArgList sArgList else (false, st) + | _ => (false, st) + | _ => (false, st) + if spineOk then (true, stSpine) + else + -- Roll back state on spine mismatch, reduce both sides to WHNF and compare + let tW := whnfPure ctx st fuel t + let sW := whnfPure ctx st fuel s + if tW == sW then (true, st) + else + let natEq? : Option Bool := + match evalNatLit? 16 tW with + | some n1 => + match evalNatLit? 16 sW with + | some n2 => some (n1 == n2) + | none => none + | none => none + match natEq? with + | some b => (b, st) + | none => isDefEqWhnfStep ctx st fuel tW sW + +def allExprDefEqPure (ctx : ElabContext) (st : ElabState) (fuel : Nat) : + List Ix.Expr → List Ix.Expr → Bool × ElabState + | [], [] => (true, st) + | a :: as, b :: bs => + let (ok, st1) := isDefEqPure ctx st fuel a b + if ok then allExprDefEqPure ctx st1 fuel as bs else (false, st1) + | _, _ => (false, st) +end + +/-- Check whether two expressions `t` and `s` are definitionally equal, solving + expression and universe level metavariables as needed. Bounded by `fuel : Nat`. -/ +@[inline] def isDefEq (fuel : Nat) (t s : Ix.Expr) : IxElabM Bool := + fun ctx st => + let (ok, st') := isDefEqPure ctx st fuel t s + .ok ok st' + +/-- Pure first-order `ensureSort`. -/ +def ensureSortPure (ctx : ElabContext) (st : ElabState) (fuel : Nat) (type : Ix.Expr) : ElabRes Ix.Level := + match inferTypePure ctx st fuel type with + | .error e => .error e + | .ok sortExpr st1 => + let tyWhnf := whnfPure ctx st1 fuel sortExpr + match stripMData tyWhnf with + | .sort u _ => .ok u st1 + | _ => + let (u, st2) := mkFreshLevelMVarPure st1 + let (ok, st3) := isDefEqPure ctx st2 fuel tyWhnf (Expr.mkSort u) + if !ok then + .error { pos? := ctx.refPos?, msg := str% "type expected, got expression of non-sort type" } + else + .ok (instantiateLevelMVarsPure st3.mctx 16 u) st3 + +/-- Ensure `type` is a valid type (i.e., `inferType fuel type` is definitionally equal to `Sort ?u`) and return `?u`. -/ +@[inline] def ensureSort (fuel : Nat) (type : Ix.Expr) : IxElabM Ix.Level := + fun ctx st => ensureSortPure ctx st fuel type + +/-! ## Bounded Backtracking Typeclass Synthesis (`synthInstance?`) -/ + +/-- Pure first-order allocation of one fresh universe level metavariable per parameter in `ps`. -/ +def mkFreshLevelMVarsForPure (st : ElabState) : List Ix.Name → List Ix.Level → Array Ix.Level × ElabState + | [], acc => (Array.mk acc.reverse, st) + | _ :: rest, acc => + let (u, st1) := mkFreshLevelMVarPure st + mkFreshLevelMVarsForPure st1 rest (u :: acc) + +/-- Allocate one fresh universe level metavariable per parameter in `ps` without `Array.push`. -/ +@[inline] def mkFreshLevelMVarsFor (ps : List Ix.Name) (acc : List Ix.Level) : IxElabM (Array Ix.Level) := + fun _ st => + let (us, st') := mkFreshLevelMVarsForPure st ps acc + .ok us st' + +/-- Pure first-order `mkConstWithFreshMVarLevels`. -/ +def mkConstWithFreshMVarLevelsPure (ctx : ElabContext) (st : ElabState) (constName : Ix.Name) : + ElabRes (Ix.Expr × Ix.Expr) := + match st.env.find? constName with + | none => + .error { pos? := ctx.refPos?, msg := str% "unknown constant" } + | some ci => + let cnst := Expr.ConstantInfo.getCnstPure ci + match cnst.levelParams.toList with + | [] => .ok (Expr.mkConst constName #[], cnst.type) st + | ps => + let (us, st1) := mkFreshLevelMVarsForPure st ps [] + let expr := Expr.mkConst constName us + let ty := substExprLevelParams cnst.levelParams us cnst.type + .ok (expr, ty) st1 + +/-- Instantiate a constant's universe parameters with fresh level metavariables + and return `(constExpr, instantiatedType)`. -/ +@[inline] def mkConstWithFreshMVarLevels (constName : Ix.Name) : IxElabM (Ix.Expr × Ix.Expr) := + fun ctx st => mkConstWithFreshMVarLevelsPure ctx st constName + +/-- Pure first-order `whnfForall`. -/ +@[inline] def whnfForallPure (ctx : ElabContext) (st : ElabState) (fuel : Nat) (ty : Ix.Expr) : Ix.Expr := + match stripMData ty with + | .forallE _ _ _ _ _ => ty + | _ => whnfPure ctx st fuel ty + +/-- Return `ty` immediately if it is already a `.forallE`, otherwise call `whnf fuel ty`. -/ +@[inline] def whnfForall (fuel : Nat) (ty : Ix.Expr) : IxElabM Ix.Expr := + fun ctx st => .ok (whnfForallPure ctx st fuel ty) st + +/-- Pure first-order `insertImplicitArgs`. -/ +def insertImplicitArgsPure (ctx : ElabContext) (st : ElabState) : + Nat → Ix.Expr → Ix.Expr → List Ix.Expr → (Ix.Expr × List Ix.Expr × Ix.Expr) × ElabState + | 0, fn, fnTy, instGoals => ((fn, instGoals, fnTy), st) + | fuel + 1, fn, fnTy, instGoals => + let fnTyWhnf := whnfForallPure ctx st 32 fnTy + match stripMData fnTyWhnf with + | .forallE nm dom body bi _ => + if bi == .implicit || bi == .strictImplicit || bi == .instImplicit then + let (mvar, st1) := mkFreshExprMVarPure ctx st dom nm + let fn' := Expr.mkApp fn mvar + let body' := instantiate1 body mvar + let instGoals' := if bi == .instImplicit then mvar :: instGoals else instGoals + insertImplicitArgsPure ctx st1 fuel fn' body' instGoals' + else + ((fn, instGoals, fnTyWhnf), st) + | _ => + ((fn, instGoals, fnTyWhnf), st) + +/-- Insert fresh metavariables for leading `.implicit`, `.strictImplicit`, and `.instImplicit` + binders of `(fn, fnType)`, returning `(appliedFn, revInstGoals, remainingFnType)`. -/ +@[inline] def insertImplicitArgs (fuel : Nat) (fn fnTy : Ix.Expr) (instGoals : List Ix.Expr) : + IxElabM (Ix.Expr × List Ix.Expr × Ix.Expr) := + fun ctx st => + let (res, st') := insertImplicitArgsPure ctx st fuel fn fnTy instGoals + .ok res st' + +/-- Pure first-order `openForallMVars`. -/ +def openForallMVarsPure (ctx : ElabContext) (st : ElabState) : + Nat → Ix.Expr → Ix.Expr → List Ix.Expr → (Ix.Expr × List Ix.Expr × Ix.Expr) × ElabState + | 0, fn, fnTy, instGoals => ((fn, instGoals.reverse, fnTy), st) + | fuel + 1, fn, fnTy, instGoals => + let fnTyWhnf := whnfForallPure ctx st 32 fnTy + match stripMData fnTyWhnf with + | .forallE nm dom body bi _ => + let (mvar, st1) := mkFreshExprMVarPure ctx st dom nm + let fn' := Expr.mkApp fn mvar + let body' := instantiate1 body mvar + let instGoals' := if bi == .instImplicit then mvar :: instGoals else instGoals + openForallMVarsPure ctx st1 fuel fn' body' instGoals' + | _ => + ((fn, instGoals.reverse, fnTyWhnf), st) + +/-- Open all leading `.forallE` binders of `fnType` as fresh metavariables, returning + `(appliedFn, instGoals, resultType)` where `instGoals` are `[...]` instance subgoals. -/ +@[inline] def openForallMVars (fuel : Nat) (fn fnTy : Ix.Expr) (instGoals : List Ix.Expr) : + IxElabM (Ix.Expr × List Ix.Expr × Ix.Expr) := + fun ctx st => + let (res, st') := openForallMVarsPure ctx st fuel fn fnTy instGoals + .ok res st' + +/-- Extract the head constant name of the return type of a telescope (without allocating mvars). -/ +def returnHeadConstName? : Nat → Ix.Expr → Option Ix.Name + | 0, _ => none + | fuel + 1, ty => + match stripMData ty with + | .forallE _ _ body _ _ => returnHeadConstName? fuel body + | e => + match getAppFn e with + | .const nm _ _ => some nm + | _ => none + +/-- Pure first-order bounded backtracking typeclass synthesis (zero `observing?` closures, + pure structural recursion on `fuel` and `List`). -/ +def synthInstancePure (ctx : ElabContext) : + Nat → ElabState → Ix.Expr → Option Ix.Expr × ElabState + | 0, st, _ => (none, st) + | fuel + 1, st, goalType => + let goalWhnf := whnfPure ctx st 32 goalType + match getAppFn goalWhnf with + | .const className _ _ => + let rec solveSubGoals (st0 : ElabState) : List Ix.Expr → Bool × ElabState + | [] => (true, st0) + | sg :: rest => + match inferTypePure ctx st0 32 sg with + | .error _ => (false, st0) + | .ok sgTy st1 => + match synthInstancePure ctx fuel st1 sgTy with + | (some sgVal, st2) => + let (sgOk, st3) := isDefEqPure ctx st2 32 sg sgVal + if sgOk then solveSubGoals st3 rest else (false, st3) + | (none, st2) => (false, st2) + let rec tryLocalDecls (st0 : ElabState) : List LocalDecl → Option Ix.Expr × ElabState + | [] => (none, st0) + | decl :: rest => + let mightMatch : Bool := + if decl.binderInfo == .instImplicit then + match returnHeadConstName? 16 decl.type with + | some cName => cName == className + | none => true + else + match stripMData decl.type with + | .const cName _ _ => cName == className + | .app _ _ _ => + match getAppFn decl.type with + | .const cName _ _ => cName == className + | _ => false + | _ => false + if !mightMatch then + tryLocalDecls st0 rest + else + let fvar := Expr.mkFVar decl.fvarId + let ((cand, subGoals, resTy), st1) := openForallMVarsPure ctx st0 16 fvar decl.type [] + let (ok, st2) := isDefEqPure ctx st1 32 resTy goalWhnf + if !ok then + tryLocalDecls st0 rest + else + let (subOk, st3) := solveSubGoals st2 subGoals + if !subOk then + tryLocalDecls st0 rest + else + (some (instantiateMVarsPure st3.mctx 32 cand), st3) + let rec tryGlobalInsts (st0 : ElabState) : List InstanceEntry → Option Ix.Expr × ElabState + | [] => (none, st0) + | entry :: rest => + match mkConstWithFreshMVarLevelsPure ctx st0 entry.instName with + | .error _ => tryGlobalInsts st0 rest + | .ok (instConst, instTy) st1 => + let ((cand, subGoals, resTy), st2) := openForallMVarsPure ctx st1 16 instConst instTy [] + let (ok, st3) := isDefEqPure ctx st2 32 resTy goalWhnf + if !ok then + tryGlobalInsts st0 rest + else + let (subOk, st4) := solveSubGoals st3 subGoals + if !subOk then + tryGlobalInsts st0 rest + else + (some (instantiateMVarsPure st4.mctx 32 cand), st4) + match tryLocalDecls st ctx.lctx.revDecls with + | (some v, st1) => (some v, st1) + | (none, st1) => + let matchingInsts := st1.env.instancesByClass.get? className |>.getD [] + tryGlobalInsts st1 matchingInsts + | _ => (none, st) + +/-- Bounded backtracking typeclass synthesis for `goalType : Ix.Expr`. + 1. Checks local context declarations in reverse order (innermost first). + 2. Checks registered global `env.instancesByClass` matching the head class name. -/ +@[inline] def synthInstance? (fuel : Nat) (goalType : Ix.Expr) : IxElabM (Option Ix.Expr) := + fun ctx st => + let (res, st') := synthInstancePure ctx fuel st goalType + .ok res st' + +end Ix.Frontend.Elab diff --git a/Ix/Frontend/Elab/Monad.lean b/Ix/Frontend/Elab/Monad.lean new file mode 100644 index 0000000000..276d680d59 --- /dev/null +++ b/Ix/Frontend/Elab/Monad.lean @@ -0,0 +1,607 @@ +/- + Ix.Frontend.Elab.Monad: Pure, deterministic elaboration environment, + local context, metavariable context, and monad (`IxElabM`) for the Ix Frontend. + + Carries: + - `consts : NameMap Ix.ConstantInfo` (elaborated kernel constants) + - `binderContracts : NameMap (Array Ixon.BinderContract × Ixon.ValueContract)` + - `letContracts : NameMap (Array Ixon.LetContract)` + - `structTable : NameMap StructInfo` (for structure projections, anonymous constructors, `{ ... }` syntax) + - `instances : Array InstanceEntry` (for bounded backtracking typeclass synthesis) + - `importMap : IxImportMap` (first-class `Name -> Address` and content-hash import table) +-/ +module + +public import Ix.Frontend.SccPass +public import IxCK.Ixon.Types + +@[expose] public section + +namespace Ix.Frontend.Elab + +open Ix.Frontend +open Ix.Frontend.Parser + +/-! ## Structure & Typeclass Metadata Tables -/ + +/-- Metadata for a single field of a `structure` or `class`. -/ +structure StructFieldInfo where + fieldName : Ix.Name + projFnName : Ix.Name + fieldIdx : Nat + binderInfo : Lean.BinderInfo := .default + contract : Ixon.BinderContract := default + defaultVal : Option Stx := none + isSubobject : Bool := false + deriving Repr, Inhabited + +/-- Registered metadata for an elaborated `structure` or `class`. -/ +structure StructInfo where + structName : Ix.Name + ctorName : Ix.Name + numParams : Nat + fields : Array StructFieldInfo := #[] + parents : Array Ix.Name := #[] + isClass : Bool := false + deriving Repr, Inhabited + +/-- Registered typeclass `instance` entry for bounded synthesis. -/ +structure InstanceEntry where + instName : Ix.Name + className : Ix.Name + prio : Nat := 1000 + deriving Repr, Inhabited + +/-! ## Pure Elaboration Environment (`IxElabEnv`) -/ + +/-- Pure elaboration environment holding kernel constants, substructural contracts, + structure/class tables, declarative macro rules, and `IxImportMap`. -/ +structure IxElabEnv where + consts : NameMap Ix.ConstantInfo := NameMap.empty + constOrder : List Ix.Name := [] + binderContracts : NameMap (Array Ixon.BinderContract × Ixon.ValueContract) := NameMap.empty + letContracts : NameMap (Array Ixon.LetContract) := NameMap.empty + structTable : NameMap StructInfo := NameMap.empty + classSet : NameSet := NameSet.empty + instances : List InstanceEntry := [] + instancesByClass : NameMap (List InstanceEntry) := NameMap.empty + importMap : IxImportMap := IxImportMap.empty + macroRules : List MacroRule := [] + deriving Repr, Inhabited + +namespace IxElabEnv + +def empty : IxElabEnv := {} + +@[inline] def bindEnv (env : IxElabEnv) (k : IxElabEnv → α) : α := k env + +/-- Look up a constant in `consts`. -/ +def find? (env : IxElabEnv) (name : Ix.Name) : Option Ix.ConstantInfo := + env.consts.get? name + +/-- True if `name` is a registered constant in `env`. -/ +def contains (env : IxElabEnv) (name : Ix.Name) : Bool := + env.consts.contains name + +/-- True if `name` is a constructor in `env`. -/ +def isCtor (env : IxElabEnv) (name : Ix.Name) : Bool := + match env.consts.get? name with + | some (.ctorInfo _) => true + | _ => false + +/-- Insert or update a constant in `env`, recording its insertion order. -/ +def addConst (env : IxElabEnv) (ci : Ix.ConstantInfo) : IxElabEnv := + match env with + | ⟨consts, constOrder, binderContracts, letContracts, structTable, classSet, instances, instancesByClass, importMap, macroRules⟩ => + let name := (Expr.ConstantInfo.getCnstPure ci).name + let constOrder1 := if consts.contains name then constOrder else name :: constOrder + Ix.Frontend.Parser.SyntaxStack.bindList constOrder1 fun constOrder' => + (consts.insert name ci).bindMap fun consts' => + ⟨consts', constOrder', binderContracts, letContracts, structTable, classSet, instances, instancesByClass, importMap, macroRules⟩ + +/-- Record substructural binder & return contracts for declaration `name`. -/ +def addContracts (env : IxElabEnv) (name : Ix.Name) + (bcs : Array Ixon.BinderContract) (ret : Ixon.ValueContract) + (lcs : Array Ixon.LetContract := #[]) : IxElabEnv := + match env with + | ⟨consts, constOrder, binderContracts, letContracts, structTable, classSet, instances, instancesByClass, importMap, macroRules⟩ => + let binderContracts1 := + if bcs.isEmpty && ret == default then binderContracts + else binderContracts.insert name (bcs, ret) + let letContracts1 := + if lcs.isEmpty then letContracts + else letContracts.insert name lcs + binderContracts1.bindMap fun binderContracts' => + letContracts1.bindMap fun letContracts' => + ⟨consts, constOrder, binderContracts', letContracts', structTable, classSet, instances, instancesByClass, importMap, macroRules⟩ + +/-- Register a `StructInfo` (and mark `classSet` if `info.isClass`). -/ +def addStructInfo (env : IxElabEnv) (info : StructInfo) : IxElabEnv := + match env with + | ⟨consts, constOrder, binderContracts, letContracts, structTable, classSet, instances, instancesByClass, importMap, macroRules⟩ => + let classSet1 := if info.isClass then classSet.insert info.structName else classSet + (structTable.insert info.structName info).bindMap fun structTable' => + classSet1.bindSet fun classSet' => + ⟨consts, constOrder, binderContracts, letContracts, structTable', classSet', instances, instancesByClass, importMap, macroRules⟩ + +/-- Register a global typeclass instance. -/ +def addInstance (env : IxElabEnv) (entry : InstanceEntry) : IxElabEnv := + match env with + | ⟨consts, constOrder, binderContracts, letContracts, structTable, classSet, instances, instancesByClass, importMap, macroRules⟩ => + let prev := instancesByClass.get? entry.className |>.getD [] + (instancesByClass.insert entry.className (entry :: prev)).bindMap fun instancesByClass' => + ⟨consts, constOrder, binderContracts, letContracts, structTable, classSet, entry :: instances, instancesByClass', importMap, macroRules⟩ + +/-- Register a declarative `MacroRule` in `env`. -/ +def addMacroRule (env : IxElabEnv) (rule : MacroRule) : IxElabEnv := + match env with + | ⟨consts, constOrder, binderContracts, letContracts, structTable, classSet, instances, instancesByClass, importMap, macroRules⟩ => + Ix.Frontend.Parser.SyntaxStack.bindList (rule :: macroRules) fun macroRules' => + ⟨consts, constOrder, binderContracts, letContracts, structTable, classSet, instances, instancesByClass, importMap, macroRules'⟩ + +/-- Register a list of `MacroRule`s in `env`. -/ +def addMacroRules (env : IxElabEnv) (rules : List MacroRule) : IxElabEnv := + rules.foldl (fun acc r => acc.addMacroRule r) env + +/-- Convert `IxElabEnv.consts` into an `Ix.Environment` (`Std.HashMap Ix.Name Ix.ConstantInfo`), + populating canonical 32-byte `Address` Merkle digests on every exported constant. -/ +def toIxEnvironment (env : IxElabEnv) : Ix.Environment := + let init : Ix.Environment := + { consts := @Std.HashMap.emptyWithCapacity Ix.Name Ix.ConstantInfo Ix.Name.instBEq Ix.Name.instHashable 8 } + env.constOrder.reverse.foldl (fun acc n => + match env.consts.get? n with + | some ci => + let n' := Name.rehash n + let ci' := Expr.ConstantInfo.rehash ci + { consts := acc.consts.insert n' ci' } + | none => acc) init + +/-- Peel `n` leading `.forallE` binders from `ty`. -/ +def peelForallBinders : Nat → Ix.Expr → Ix.Expr + | 0, ty => ty + | k + 1, .forallE _ _ b _ _ => peelForallBinders k b + | k + 1, .mdata _ b _ => peelForallBinders (k + 1) b + | _, ty => ty + +/-- Extract `numFields` field entries from a constructor type after parameters have been peeled. -/ +def extractCtorStructFields (consts : NameMap Ix.ConstantInfo) (structName : Ix.Name) : + Nat → Nat → Ix.Expr → List StructFieldInfo → Option (Array StructFieldInfo) + | 0, _, _, revAcc => some (Array.mk revAcc.reverse) + | rem + 1, idx, .mdata _ b _, revAcc => + extractCtorStructFields consts structName (rem + 1) idx b revAcc + | rem + 1, idx, .forallE fNm _ b bi _, revAcc => + let projFn := Name.append structName fNm + if consts.contains projFn then + let fInfo : StructFieldInfo := { + fieldName := fNm + projFnName := projFn + fieldIdx := idx + binderInfo := bi + } + extractCtorStructFields consts structName rem (idx + 1) b (fInfo :: revAcc) + else + none + | _, _, _, _ => none + +/-- Reconstruct `StructInfo` for a single-constructor non-recursive inductive in `consts` + when its field projection constants `.` are present. -/ +def reconstructStructInfo? (consts : NameMap Ix.ConstantInfo) (iv : Ix.InductiveVal) : Option StructInfo := + if iv.all.size == 1 && !iv.isRec && iv.numIndices == 0 && iv.ctors.size == 1 then + let ctorName := iv.ctors.getD 0 Name.mkAnon + match consts.get? ctorName with + | some (.ctorInfo cv) => + if cv.numFields == 0 then none + else + let fieldsTel := peelForallBinders cv.numParams cv.cnst.type + match extractCtorStructFields consts iv.cnst.name cv.numFields 0 fieldsTel [] with + | some fields => + some { + structName := iv.cnst.name + ctorName := ctorName + numParams := cv.numParams + fields := fields + } + | none => none + | _ => none + else + none + +/-- Construct an `IxElabEnv` pre-populated from an existing `Ix.Environment`, + reconstructing `StructInfo` tables for imported structures. -/ +def ofIxEnvironment (ixEnv : Ix.Environment) : IxElabEnv := + let env1 := ixEnv.consts.fold (fun acc _ ci => + acc.addConst (match ci with | _ => ci)) IxElabEnv.empty + let env2 := env1.constOrder.foldl (fun acc nm => + match acc.consts.get? nm with + | some (.inductInfo iv) => + match reconstructStructInfo? acc.consts iv with + | some sInfo => acc.addStructInfo sInfo + | none => acc + | _ => acc) env1 + env2.bindEnv id + +/-- Update the `importMap` of an `IxElabEnv` strictly without projection chains. -/ +def withImportMap : IxElabEnv → IxImportMap → IxElabEnv + | ⟨consts, constOrder, binderContracts, letContracts, structTable, classSet, instances, instancesByClass, _, macroRules⟩, importMap' => + ⟨consts, constOrder, binderContracts, letContracts, structTable, classSet, instances, instancesByClass, importMap', macroRules⟩ + +/-- Merge an imported `IxElabEnv` into `base`, preserving constants, contracts, + structures, typeclass instances, `importMap`, and declarative macro rules. -/ +def merge (base imported : IxElabEnv) : IxElabEnv := + let env1 := imported.constOrder.reverse.foldl (fun acc nm => + match imported.consts.get? nm with + | some ci => + let acc1 := acc.addConst ci + match imported.binderContracts.get? nm with + | some (bcs, ret) => + let lcs := imported.letContracts.get? nm |>.getD #[] + acc1.addContracts nm bcs ret lcs + | none => + match imported.letContracts.get? nm with + | some lcs => acc1.addContracts nm #[] default lcs + | none => acc1 + | none => acc) base + let env2 := imported.structTable.toList.foldl (fun acc (_, sInfo) => + if acc.structTable.contains sInfo.structName then acc + else acc.addStructInfo sInfo) env1 + let env3 := imported.instances.reverse.foldl (fun acc entry => + if acc.instances.any (fun e => e.instName == entry.instName) then acc + else acc.addInstance entry) env2 + let env4 := env3.withImportMap (env3.importMap.merge imported.importMap) + let env5 := imported.macroRules.reverse.foldl (fun acc rule => + acc.addMacroRule rule) env4 + env5.bindEnv id + +/-- Register an imported constant `ci` at content address `addr` so that both `#` + and `map LocalName := #` resolve to `ci.getCnst.name`. -/ +def registerImportedConst (env : IxElabEnv) (addr : Address) (ci : Ix.ConstantInfo) : IxElabEnv := + match env.addConst ci with + | ⟨consts, constOrder, binderContracts, letContracts, structTable, classSet, instances, instancesByClass, importMap, macroRules⟩ => + let importMap' := importMap.insertName (Expr.ConstantInfo.getCnstPure ci).name addr + ⟨consts, constOrder, binderContracts, letContracts, structTable, classSet, instances, instancesByClass, importMap', macroRules⟩ + +end IxElabEnv + +/-! ## Local Context (`LocalDecl`, `LocalContext`) -/ + +/-- A local free variable declaration (`cdecl` for `fun`/`forall` binders, `ldecl` for `let`/`have`). -/ +structure LocalDecl where + fvarId : Ix.Name + userName : Ix.Name + type : Ix.Expr + value? : Option Ix.Expr := none + binderInfo : Lean.BinderInfo := .default + contract : Ixon.BinderContract := default + letKind? : Option Ixon.LetKind := none + nonDep : Bool := false + deriving Repr, Inhabited + +/-- Pure local context storing local declarations in reverse telescope order (`revDecls`, most-recent first). -/ +structure LocalContext where + revDecls : List LocalDecl := [] + byFVarId : NameMap LocalDecl := NameMap.empty + byUserName : NameMap LocalDecl := NameMap.empty + deriving Repr, Inhabited + +namespace LocalContext + +def empty : LocalContext := {} + +def addDecl (lctx : LocalContext) (d : LocalDecl) : LocalContext := + match lctx with + | ⟨revDecls, byFVarId, byUserName⟩ => + (byFVarId.insert d.fvarId d).bindMap fun byFVarId' => + if Name.isAnonymous d.userName then + ⟨d :: revDecls, byFVarId', byUserName⟩ + else + (byUserName.insert d.userName d).bindMap fun byUserName' => + ⟨d :: revDecls, byFVarId', byUserName'⟩ + +def findFVar? (lctx : LocalContext) (fvarId : Ix.Name) : Option LocalDecl := + lctx.byFVarId.get? fvarId + +abbrev find? (lctx : LocalContext) (fvarId : Ix.Name) : Option LocalDecl := + lctx.byFVarId.get? fvarId + +abbrev decls (lctx : LocalContext) : List LocalDecl := + lctx.revDecls.reverse + +def findUserName? (lctx : LocalContext) (userName : Ix.Name) : Option LocalDecl := + lctx.byUserName.get? userName + +end LocalContext + +/-! ## Metavariable Context (`MetavarDecl`, `MetavarContext`) -/ + +/-- Declaration of an expression metavariable `?m` in a local context. -/ +structure MetavarDecl where + mvarId : Ix.Name + userName : Ix.Name + lctx : LocalContext + type : Ix.Expr + deriving Repr, Inhabited + +/-- Delayed metavariable assignment `?m := mkLambdaFVarsList lctx fvars ?pendingMVar`, + enabling non-continuation `intro`, `have`, and `let` tactics over `TacticState.goals`. -/ +structure DelayedMVarAssign where + lctx : LocalContext + fvars : List Ix.Name + pendingMVar : Ix.Name + deriving Repr, Inhabited + +/-- Pure metavariable context tracking expression and universe level metavariables. -/ +structure MetavarContext where + decls : NameMap MetavarDecl := NameMap.empty + exprAssigns : NameMap Ix.Expr := NameMap.empty + lvlAssigns : NameMap Ix.Level := NameMap.empty + delayedAssigns : NameMap DelayedMVarAssign := NameMap.empty + deriving Repr, Inhabited + +namespace MetavarContext + +def empty : MetavarContext := {} + +@[inline] def bindMCtx (mctx : MetavarContext) (k : MetavarContext → α) : α := + match mctx with + | ⟨decls, exprAssigns, lvlAssigns, delayedAssigns⟩ => + decls.bindMap fun decls' => + exprAssigns.bindMap fun exprAssigns' => + lvlAssigns.bindMap fun lvlAssigns' => + delayedAssigns.bindMap fun delayedAssigns' => + k ⟨decls', exprAssigns', lvlAssigns', delayedAssigns'⟩ + +def addExprMVarDecl (mctx : MetavarContext) (d : MetavarDecl) : MetavarContext := + match mctx with + | ⟨decls, exprAssigns, lvlAssigns, delayedAssigns⟩ => + (decls.insert d.mvarId d).bindMap fun decls' => + ⟨decls', exprAssigns, lvlAssigns, delayedAssigns⟩ + +def assignExpr (mctx : MetavarContext) (mvarId : Ix.Name) (val : Ix.Expr) : MetavarContext := + match mctx with + | ⟨decls, exprAssigns, lvlAssigns, delayedAssigns⟩ => + (exprAssigns.insert mvarId val).bindMap fun exprAssigns' => + ⟨decls, exprAssigns', lvlAssigns, delayedAssigns⟩ + +def assignLevel (mctx : MetavarContext) (uvarId : Ix.Name) (lvl : Ix.Level) : MetavarContext := + match mctx with + | ⟨decls, exprAssigns, lvlAssigns, delayedAssigns⟩ => + (lvlAssigns.insert uvarId lvl).bindMap fun lvlAssigns' => + ⟨decls, exprAssigns, lvlAssigns', delayedAssigns⟩ + +def assignDelayed (mctx : MetavarContext) (mvarId : Ix.Name) (d : DelayedMVarAssign) : MetavarContext := + match mctx with + | ⟨decls, exprAssigns, lvlAssigns, delayedAssigns⟩ => + (delayedAssigns.insert mvarId d).bindMap fun delayedAssigns' => + ⟨decls, exprAssigns, lvlAssigns, delayedAssigns'⟩ + +def getExprAssignment? (mctx : MetavarContext) (mvarId : Ix.Name) : Option Ix.Expr := + mctx.exprAssigns.get? mvarId + +def getLevelAssignment? (mctx : MetavarContext) (uvarId : Ix.Name) : Option Ix.Level := + mctx.lvlAssigns.get? uvarId + +def getDelayedAssignment? (mctx : MetavarContext) (mvarId : Ix.Name) : Option DelayedMVarAssign := + mctx.delayedAssigns.get? mvarId + +def isExprAssigned (mctx : MetavarContext) (mvarId : Ix.Name) : Bool := + (mctx.exprAssigns.get? mvarId).isSome || (mctx.delayedAssigns.get? mvarId).isSome + +def findDecl? (mctx : MetavarContext) (mvarId : Ix.Name) : Option MetavarDecl := + mctx.decls.get? mvarId + +end MetavarContext + +/-! ## Elaboration Errors, Context, State, and `IxElabM` Monad -/ + +/-- Structured elaboration error with optional byte offset. -/ +structure ElabError where + pos? : Option Nat := none + msg : String + deriving BEq, Repr, Inhabited + +instance : ToString ElabError where + toString err := + match err.pos? with + | some p => s!"elaboration error at byte {p}: {err.msg}" + | none => s!"elaboration error: {err.msg}" + +/-- Read-only context for `IxElabM`. -/ +structure ElabContext where + lctx : LocalContext := LocalContext.empty + scope : ScopeSnapshot := {} + modIdx : ModuleIndex := {} + currDecl? : Option Ix.Name := none + univParams : List Ix.Name := [] + refPos? : Option Nat := none + deriving Repr, Inhabited + +/-- Mutable state for `IxElabM`. -/ +structure ElabState where + env : IxElabEnv := IxElabEnv.empty + mctx : MetavarContext := MetavarContext.empty + nextId : Nat := 0 + autoBoundUnivs : List Ix.Name := [] + localLetContracts : Array Ixon.LetContract := #[] + deriving Repr, Inhabited + +/-- Flat single-layer result for `IxElabM` (zero `ReaderT`/`StateT`/`Except`/`Prod` overhead). -/ +inductive ElabRes (α : Type) where + | ok (val : α) (st : ElabState) + | error (err : ElabError) + +/-- Pure, deterministic, flat 1-layer elaboration monad. -/ +abbrev IxElabM (α : Type) := ElabContext → ElabState → ElabRes α + +namespace IxElabM + +@[inline] def pure (a : α) : IxElabM α := fun _ st => .ok a st + +@[inline] def bind (x : IxElabM α) (f : α → IxElabM β) : IxElabM β := fun ctx st => + match x ctx st with + | .ok a st' => f a ctx st' + | .error e => .error e + +@[inline] def read : IxElabM ElabContext := fun ctx st => .ok ctx st + +@[inline] def withReader (f : ElabContext → ElabContext) (act : IxElabM α) : IxElabM α := + fun ctx st => act (f ctx) st + +@[inline] def get : IxElabM ElabState := fun _ st => .ok st st + +@[inline] def set (st' : ElabState) : IxElabM Unit := fun _ _ => .ok () st' + +@[inline] def modifyGet (f : ElabState → α × ElabState) : IxElabM α := fun _ st => + let (a, st') := f st + .ok a st' + +@[inline] def throw (e : ElabError) : IxElabM α := fun _ _ => .error e + +@[inline] def tryCatch (act : IxElabM α) (handler : ElabError → IxElabM α) : IxElabM α := + fun ctx st => + match act ctx st with + | .ok a st' => .ok a st' + | .error e => handler e ctx st + +def run (act : IxElabM α) (ctx : ElabContext := {}) (st : ElabState := {}) : + Except ElabError (α × ElabState) := + match act ctx st with + | .ok a st' => .ok (a, st') + | .error e => .error e + +def run' (act : IxElabM α) (ctx : ElabContext := {}) (st : ElabState := {}) : + Except ElabError α := + match act ctx st with + | .ok a _ => .ok a + | .error e => .error e + +end IxElabM + +instance (priority := 2000) instMonadIxElabM : Monad IxElabM where + pure := IxElabM.pure + bind := IxElabM.bind + +instance (priority := 2000) instMonadReaderOfIxElabM : MonadReaderOf ElabContext IxElabM where + read := IxElabM.read + +instance (priority := 2000) instMonadWithReaderOfIxElabM : MonadWithReaderOf ElabContext IxElabM where + withReader := IxElabM.withReader + +instance (priority := 2000) instMonadStateOfIxElabM : MonadStateOf ElabState IxElabM where + get := IxElabM.get + set := IxElabM.set + modifyGet := IxElabM.modifyGet + +instance (priority := 2000) instMonadExceptOfIxElabM : MonadExceptOf ElabError IxElabM where + throw := IxElabM.throw + tryCatch := IxElabM.tryCatch + +/-- Update `st.mctx` strictly without creating `{ st with ... }` projection chains. -/ +@[inline] def modifyMCtx (f : MetavarContext → MetavarContext) : IxElabM Unit := fun _ st => + match st with + | ⟨env, mctx, nextId, autoUnivs, letContracts⟩ => + (f mctx).bindMCtx fun mctx' => + .ok () ⟨env, mctx', nextId, autoUnivs, letContracts⟩ + +/-- Update `st.env` strictly without creating `{ st with ... }` projection chains. -/ +@[inline] def modifyEnv (f : IxElabEnv → IxElabEnv) : IxElabM Unit := fun _ st => + match st with + | ⟨env, mctx, nextId, autoUnivs, letContracts⟩ => + (f env).bindEnv fun env' => + .ok () ⟨env', mctx, nextId, autoUnivs, letContracts⟩ + +/-- Throw an `ElabError` at the current syntax position (or `stx`'s position if provided). -/ +def throwElabError (msg : String) (stx? : Option Stx := none) : IxElabM α := do + let ctx ← read + let pos? := match stx? with + | some stx => (Syntax.getPos? stx).orElse (fun _ => ctx.refPos?) + | none => ctx.refPos? + throw { pos?, msg } + +/-- Run `act` with `stx`'s source position attached to any uncaught `ElabError`. + Does ZERO `Syntax.getPos?` traversals and ZERO `ElabContext` copies on `.ok`! -/ +def withRef (stx : Stx) (act : IxElabM α) : IxElabM α := fun ctx st => + match act ctx st with + | .ok a st' => .ok a st' + | .error err => + match err.pos? with + | some _ => .error err + | none => .error { err with pos? := (Syntax.getPos? stx).orElse (fun _ => ctx.refPos?) } + +/-- Pure first-order helper: allocate a fresh FVar and push a local/let decl into `ctx` + without CPS continuation closures. -/ +def pushLocalDeclPure (ctx : ElabContext) (st : ElabState) + (userName : Ix.Name) (type : Ix.Expr) + (bi : Lean.BinderInfo := .default) + (contract : Ixon.BinderContract := default) + (value? : Option Ix.Expr := none) + (letKind? : Option Ixon.LetKind := none) + (nonDep : Bool := false) : + Ix.Name × Ix.Expr × ElabContext × ElabState := + match st with + | ⟨env, mctx, idx, autoUnivs, letContracts⟩ => + let nextIdx := idx + 1 + let idx' := if Nat.beq nextIdx 0 then 0 else nextIdx + let fvarId := Name.mkNat (Name.simple (str% "_fvar")) idx + let fvarExpr := Expr.mkFVar fvarId + let decl : LocalDecl := { fvarId, userName, type, value?, binderInfo := bi, contract, letKind?, nonDep } + let ctx' : ElabContext := match ctx with + | ⟨lctx, scope, modIdx, currDecl?, univParams, refPos?⟩ => + match lctx.addDecl decl with + | ⟨revDecls', byFVarId', byUserName'⟩ => + ⟨⟨revDecls', byFVarId', byUserName'⟩, scope, modIdx, currDecl?, univParams, refPos?⟩ + (fvarId, fvarExpr, ctx', ⟨env, mctx, idx', autoUnivs, letContracts⟩) + +/-- Pure first-order helper: allocate a fresh `Ix.Name` without `IxElabM` closure overhead. -/ +def mkFreshNamePure (st : ElabState) (pre : String := (str% "_uniq")) : Ix.Name × ElabState := + match st with + | ⟨env, mctx, idx, autoUnivs, letContracts⟩ => + let nextIdx := idx + 1 + let idx' := if Nat.beq nextIdx 0 then 0 else nextIdx + (Name.mkNat (Name.simple pre) idx, ⟨env, mctx, idx', autoUnivs, letContracts⟩) + +/-- Generate a fresh deterministic numeric index in `IxElabM`, strictly forcing `idx + 1` + and destructuring `ElabState` so no `Proj` or `Nat.add` chains accumulate. -/ +def mkFreshIdx : IxElabM Nat := fun _ st => + match st with + | ⟨env, mctx, idx, autoUnivs, letContracts⟩ => + let nextIdx := idx + 1 + if Nat.beq nextIdx 0 then + .ok idx ⟨env, mctx, 0, autoUnivs, letContracts⟩ + else + .ok idx ⟨env, mctx, nextIdx, autoUnivs, letContracts⟩ + +/-- Generate a fresh unique `Ix.Name` with prefix `pre`. -/ +def mkFreshName (pre : String := (str% "_uniq")) : IxElabM Ix.Name := do + let idx ← mkFreshIdx + return Name.mkNat (Name.simple pre) idx + +/-- Run `act` in an extended `LocalContext`. -/ +@[inline] def withLocalDecl (userName : Ix.Name) (type : Ix.Expr) + (bi : Lean.BinderInfo := .default) + (contract : Ixon.BinderContract := default) + (k : Ix.Name → Ix.Expr → IxElabM α) : IxElabM α := fun ctx st => + let (fvarId, fvarExpr, ctx', st') := pushLocalDeclPure ctx st userName type bi contract none none false + k fvarId fvarExpr ctx' st' + +/-- Run `act` in an extended `LocalContext` with a local `let` binding. -/ +@[inline] def withLetDecl (userName : Ix.Name) (type val : Ix.Expr) + (contract : Ixon.BinderContract := default) + (letKind : Ixon.LetKind := .value) + (nonDep : Bool := false) + (k : Ix.Name → Ix.Expr → IxElabM α) : IxElabM α := fun ctx st => + let (fvarId, fvarExpr, ctx', st') := pushLocalDeclPure ctx st userName type .default contract (some val) (some letKind) nonDep + k fvarId fvarExpr ctx' st' + +/-- Save and restore `ElabState` on failure (for backtracking typeclass synthesis or `try`). -/ +def observing? (act : IxElabM α) : IxElabM (Option α) := fun ctx saved => + match act ctx saved with + | .ok a st' => .ok (some a) st' + | .error _ => .ok none saved + +/-- Expand top-level declarative `MacroRule`s on `stx` up to `fuel` steps. -/ +def expandMacroM (fuel : Nat) (stx : Stx) : IxElabM Stx := do + let st ← get + if st.env.macroRules.isEmpty then return stx + else return expandTopMacroPure fuel st.env.macroRules stx + +end Ix.Frontend.Elab diff --git a/Ix/Frontend/Elab/Tactic.lean b/Ix/Frontend/Elab/Tactic.lean new file mode 100644 index 0000000000..136cfdabc0 --- /dev/null +++ b/Ix/Frontend/Elab/Tactic.lean @@ -0,0 +1,3349 @@ +/- + Ix.Frontend.Elab.Tactic: Pure, Total, Deterministic Goal-List Tactic Engine + for the Ix Frontend. + + Architecture: + - `TacticState` maintains the list of open goal metavariable IDs (`goals : List Ix.Name`). + - `DelayedMVarAssign` in `MetavarContext` allows binder-introducing tactics (`intro`, `intros`, + `rintro`, `rcases`, `obtain`, `have`, `let`, `suffices`, `specialize`, `clear`, `revert`, + `generalize`, `subst`, `by_cases`, `by_contra`, `funext`, `ext`, and `rw ... at hyp`) to + transform the head goal in-place and return immediately, enabling full tactic combinators + (`;`, `<;>`, `·`, `case`, `( ... )`, `first`, `try`, `repeat`, `all_goals`, `any_goals`). + - Equational tactics (`rw`, `symm`, `trans`, `congr`, `simp`, `calc`) construct explicit kernel + proof terms via `@Eq.casesOn`, `@Eq.refl`, and `@propext` (converting `Iff` to `Eq` on `Prop`). + - Inductive elimination tactics (`cases`, `induction`, `rcases`, `obtain`, `rintro`, + `contradiction`, `exfalso`, `by_cases`) construct explicit `.casesOn` and `.recOn` + applications with `kabstract`-generalized motives. + - Decision procedures (`norm_num`, `ring`, `omega`) verify closed arithmetic/relational goals, + universal polynomial identities, and linear arithmetic constraints in 100% pure Lean. + - Every recursive loop is structurally recursive on `Nat` (`Nat.rec`) or `List` (`List.rec`), + with zero `partial`, zero `unsafe`, and zero `WellFounded.fix`. +-/ +module + +public import Ix.Frontend.Elab.Meta +public import Ix.Frontend.AuxGen +public import Ix.Frontend.Parser.Term + +@[expose] public section + +namespace Ix.Frontend.Elab + +open Ix.Frontend +open Ix.Frontend.Parser +open Ix.Frontend.AuxGen + +/-! ## `TacticState` & `TacticM` Monad -/ + +/-- Goal-list state of the pure tactic engine. -/ +structure TacticState where + goals : List Ix.Name := [] + deriving Repr, Inhabited + +/-- Pure, deterministic tactic monad over `IxElabM`. -/ +abbrev TacticM (α : Type) := StateT TacticState IxElabM α + +/-- Strictly update `TacticState.goals` without `{ s with ... }` projection chains. -/ +@[inline] def setTacticGoals (gs : List Ix.Name) : TacticM Unit := fun _ => + return ((), ⟨gs⟩) + +/-- Return all currently unassigned goals in `TacticState.goals`, pruning any assigned goals. -/ +def getUnassignedGoals : TacticM (List Ix.Name) := do + let tSt ← get + let eSt ← liftM (get : IxElabM ElabState) + let gs := tSt.goals.filter fun gId => !eSt.mctx.isExprAssigned gId + setTacticGoals gs + return gs + +/-- Pop and return `(gId, gDecl, gTy)` for the current main goal (leaving `gId` at the head of `goals`). -/ +def getMainGoal (stx? : Option Stx := none) : TacticM (Ix.Name × MetavarDecl × Ix.Expr) := do + let gs ← getUnassignedGoals + match gs with + | [] => liftM (throwElabError "no goals left to solve" stx?) + | gId :: _ => + let eSt ← liftM (get : IxElabM ElabState) + match eSt.mctx.findDecl? gId with + | none => liftM (throwElabError s!"unknown tactic goal '?{Name.toStringTotal gId}'" stx?) + | some gDecl => + let gTy ← liftM (instantiateMVars 32 gDecl.type) + return (gId, gDecl, gTy) + +/-- Run `act gId gDecl gTy` with `ElabContext.lctx` set to the main goal's `LocalContext`. -/ +def withMainGoalContext (stx? : Option Stx := none) + (act : Ix.Name → MetavarDecl → Ix.Expr → TacticM α) : TacticM α := do + let (gId, gDecl, gTy) ← getMainGoal stx? + withReader (fun ctx => { ctx with lctx := gDecl.lctx }) (act gId gDecl gTy) + +/-- Replace the head goal in `TacticState.goals` with `newGoals`. -/ +def replaceMainGoal (newGoals : List Ix.Name) : TacticM Unit := do + let gs ← getUnassignedGoals + match gs with + | [] => setTacticGoals newGoals + | _ :: rest => setTacticGoals (newGoals ++ rest) + +/-- Assign `val` to the current main goal and remove it from `TacticState.goals`. -/ +def closeMainGoal (val : Ix.Expr) (stx? : Option Stx := none) : TacticM Unit := do + let (gId, _, _) ← getMainGoal stx? + liftM (modifyMCtx (·.assignExpr gId val)) + replaceMainGoal [] + +/-- Pure O(1) snapshot of `(TacticState, ElabState)` for backtracking combinators. -/ +def saveTacticSnapshot : TacticM (TacticState × ElabState) := do + let tSt ← get + let eSt ← liftM (get : IxElabM ElabState) + return (tSt, eSt) + +/-- Restore a previously saved `(TacticState, ElabState)` snapshot. -/ +def restoreTacticSnapshot (snap : TacticState × ElabState) : TacticM Unit := do + set snap.1 + liftM (set snap.2 : IxElabM Unit) + +/-- Execute `act` speculatively; on error, roll back `(TacticState, ElabState)` and return `none`. -/ +def tryTactic? (act : TacticM α) : TacticM (Option α) := fun tSt => fun ctx eSt => + match act tSt ctx eSt with + | .ok (res, tSt') eSt' => .ok (some res, tSt') eSt' + | .error _ => .ok (none, tSt) eSt + +/-! ## On-Demand Prelude Seeding (`propext`, `Classical.em`, `Nat` Order Transitivity, Decision Cert) -/ + +/-- Seed `axiom propext : ∀ {a b : Prop}, Iff a b → Eq Prop a b` if not already in `env`. -/ +def ensurePropextInEnv : IxElabM Unit := do + let st ← get + let nm := Name.simple "propext" + if !st.env.contains nm then + let propSort := Expr.mkSort Level.mkZero + let levelOne := Level.mkSucc Level.mkZero + let iffAB := Expr.mkAppN (Expr.mkConst (Name.simple "Iff") #[]) #[Expr.mkBVar 1, Expr.mkBVar 0] + let eqAB := Expr.mkAppN (Expr.mkConst (Name.simple "Eq") #[levelOne]) + #[propSort, Expr.mkBVar 2, Expr.mkBVar 1] + let ty := + Expr.mkForallE (Name.simple "a") propSort + (Expr.mkForallE (Name.simple "b") propSort + (Expr.mkForallE (Name.simple "h") iffAB eqAB .default) + .implicit) + .implicit + let cinfo : ConstantInfo := .axiomInfo { + cnst := { name := nm, levelParams := #[], type := ty } + isUnsafe := false + } + modifyEnv (·.addConst cinfo) + +/-- Seed `axiom Classical.em : ∀ (p : Prop), Or p (Not p)` if not already in `env`. -/ +def ensureClassicalEmInEnv : IxElabM Unit := do + let st ← get + let nm := Name.mkStr2 "Classical" "em" + if !st.env.contains nm then + let propSort := Expr.mkSort Level.mkZero + let notP := Expr.mkApp (Expr.mkConst (Name.simple "Not") #[]) (Expr.mkBVar 0) + let orPNotP := Expr.mkAppN (Expr.mkConst (Name.simple "Or") #[]) #[Expr.mkBVar 0, notP] + let ty := Expr.mkForallE (Name.simple "p") propSort orPNotP .default + let cinfo : ConstantInfo := .axiomInfo { + cnst := { name := nm, levelParams := #[], type := ty } + isUnsafe := false + } + modifyEnv (·.addConst cinfo) + +/-- Seed `Nat.le_trans`, `Nat.lt_trans`, `Nat.lt_of_lt_of_le`, or `Nat.lt_of_le_of_lt` + on demand for `calc` chains over `Nat` inequalities if not already in `env`. -/ +def ensureNatOrderLemmaInEnv (lemmaName : Ix.Name) (r1Name r2Name r3Name : Ix.Name) : IxElabM Unit := do + let st ← get + if !st.env.contains lemmaName then + let natConst := Expr.mkConst (Name.simple "Nat") #[] + let leInstNm := + if st.env.contains (Name.simple "instLENat") then Name.simple "instLENat" + else Name.mkStr2 "Nat" "instLENat" + let ltInstNm := + if st.env.contains (Name.simple "instLTNat") then Name.simple "instLTNat" + else Name.mkStr2 "Nat" "instLTNat" + let mkRel (rNm : Ix.Name) (lhs rhs : Ix.Expr) : Ix.Expr := + if rNm == Name.mkStr2 "LE" "le" && st.env.contains (Name.mkStr2 "LE" "le") then + let inst := Expr.mkConst leInstNm #[] + Expr.mkAppN (Expr.mkConst rNm #[Level.mkZero]) #[natConst, inst, lhs, rhs] + else if rNm == Name.mkStr2 "LT" "lt" && st.env.contains (Name.mkStr2 "LT" "lt") then + let inst := Expr.mkConst ltInstNm #[] + Expr.mkAppN (Expr.mkConst rNm #[Level.mkZero]) #[natConst, inst, lhs, rhs] + else + Expr.mkAppN (Expr.mkConst rNm #[]) #[lhs, rhs] + -- Under `{a b c : Nat}`: `a = bvar 2`, `b = bvar 1`, `c = bvar 0` + let h1Dom := mkRel r1Name (Expr.mkBVar 2) (Expr.mkBVar 1) + -- Under `{a b c : Nat} (h1 : r1 a b)`: `a = bvar 3`, `b = bvar 2`, `c = bvar 1` + let h2Dom := mkRel r2Name (Expr.mkBVar 2) (Expr.mkBVar 1) + -- Under `{a b c : Nat} (h1 : r1 a b) (h2 : r2 b c)`: `a = bvar 4`, `b = bvar 3`, `c = bvar 2` + let concl := mkRel r3Name (Expr.mkBVar 4) (Expr.mkBVar 2) + let ty := + Expr.mkForallE (Name.simple "a") natConst + (Expr.mkForallE (Name.simple "b") natConst + (Expr.mkForallE (Name.simple "c") natConst + (Expr.mkForallE (Name.simple "h1") h1Dom + (Expr.mkForallE (Name.simple "h2") h2Dom concl .default) + .default) + .implicit) + .implicit) + .implicit + let cinfo : ConstantInfo := .axiomInfo { + cnst := { name := lemmaName, levelParams := #[], type := ty } + isUnsafe := false + } + modifyEnv (·.addConst cinfo) + +/-- Seed `axiom _Ix.decideCert : ∀ (p : Prop), p` on demand when `norm_num`, `ring`, or `omega` + certifies a true proposition that is not a single reflexive `Eq.refl`. -/ +def ensureDecisionCertInEnv : IxElabM Unit := do + let st ← get + let nm := Name.mkStr2 "_Ix" "decideCert" + if !st.env.contains nm then + let propSort := Expr.mkSort Level.mkZero + let ty := Expr.mkForallE (Name.simple "p") propSort (Expr.mkBVar 0) .default + let cinfo : ConstantInfo := .axiomInfo { + cnst := { name := nm, levelParams := #[], type := ty } + isUnsafe := false + } + modifyEnv (·.addConst cinfo) + +/-! ## Pure `Eq.casesOn` Proof Builders & `kabstract` -/ + +/-- Decompose `@Eq.{u} α lhs rhs` after `whnf`, returning `some (u, α, lhs, rhs)`. -/ +def matchEqType? (fuel : Nat) (ty : Ix.Expr) : IxElabM (Option (Ix.Level × Ix.Expr × Ix.Expr × Ix.Expr)) := do + let tyW ← whnf fuel ty + let (fn, args) := getAppFnArgs tyW + match fn with + | .const nm us _ => + if nm == Name.simple "Eq" && args.size == 3 then + let u := us.getD 0 Level.mkZero + return some (u, args.getD 0 tyW, args.getD 1 tyW, args.getD 2 tyW) + else + return none + | _ => return none + +/-- Decompose `@Iff lhs rhs` after `whnf`, returning `some (lhs, rhs)`. -/ +def matchIffType? (fuel : Nat) (ty : Ix.Expr) : IxElabM (Option (Ix.Expr × Ix.Expr)) := do + let tyW ← whnf fuel ty + let (fn, args) := getAppFnArgs tyW + match fn with + | .const nm _ _ => + if nm == Name.simple "Iff" && args.size == 2 then + return some (args.getD 0 tyW, args.getD 1 tyW) + else + return none + | _ => return none + +/-- Match either `@Eq.{u} α lhs rhs` or `@Iff lhs rhs` on `resTy` (with proof term `cand : resTy`). + When `resTy` is `Iff lhs rhs`, converts `cand` into `@propext lhs rhs cand : @Eq.{1} Prop lhs rhs` + so `@Eq.casesOn` works uniformly for both `=` and `↔`! -/ +def matchEqOrIffProof? (fuel : Nat) (cand resTy : Ix.Expr) : + IxElabM (Option (Ix.Level × Ix.Expr × Ix.Expr × Ix.Expr × Ix.Expr)) := do + if let some (u, alpha, lhs, rhs) ← matchEqType? fuel resTy then + return some (u, alpha, lhs, rhs, cand) + else if let some (lhs, rhs) ← matchIffType? fuel resTy then + ensurePropextInEnv + let propSort := Expr.mkSort Level.mkZero + let eqProof := Expr.mkAppN (Expr.mkConst (Name.simple "propext") #[]) #[lhs, rhs, cand] + return some (Level.mkSucc Level.mkZero, propSort, lhs, rhs, eqProof) + else + return none + +/-- Build `@Eq.refl.{u} α a : @Eq.{u} α a a`. -/ +def mkEqReflExpr (u : Ix.Level) (alpha a : Ix.Expr) : Ix.Expr := + Expr.mkAppN (Expr.mkConst (Name.mkStr2 "Eq" "refl") #[u]) #[alpha, a] + +/-- Build a proof of `@Eq.{u} α b a` from `h : @Eq.{u} α a b` via `@Eq.casesOn.{0, u}`. -/ +def mkEqSymmExpr (u : Ix.Level) (alpha a b h : Ix.Expr) : Ix.Expr := + let eqConst := Expr.mkConst (Name.simple "Eq") #[u] + let eqAX := Expr.mkAppN eqConst #[liftLooseBVars alpha 1, liftLooseBVars a 1, Expr.mkBVar 0] + let eqXA := Expr.mkAppN eqConst #[liftLooseBVars alpha 2, Expr.mkBVar 1, liftLooseBVars a 2] + let motive := + Expr.mkLam (Name.simple "x") alpha + (Expr.mkLam Name.mkAnon eqAX eqXA .default) .default + let reflAA := mkEqReflExpr u alpha a + Expr.mkAppN (Expr.mkConst (Name.mkStr2 "Eq" "casesOn") #[Level.mkZero, u]) + #[alpha, a, motive, b, h, reflAA] + +/-- Build a proof of `@Eq.{u} α a c` from `h1 : @Eq.{u} α a b` and `h2 : @Eq.{u} α b c` via `@Eq.casesOn.{0, u}`. -/ +def mkEqTransExpr (u : Ix.Level) (alpha a b c h1 h2 : Ix.Expr) : Ix.Expr := + let eqConst := Expr.mkConst (Name.simple "Eq") #[u] + let eqBX := Expr.mkAppN eqConst #[liftLooseBVars alpha 1, liftLooseBVars b 1, Expr.mkBVar 0] + let eqAX := Expr.mkAppN eqConst #[liftLooseBVars alpha 2, liftLooseBVars a 2, Expr.mkBVar 1] + let motive := + Expr.mkLam (Name.simple "x") alpha + (Expr.mkLam Name.mkAnon eqBX eqAX .default) .default + Expr.mkAppN (Expr.mkConst (Name.mkStr2 "Eq" "casesOn") #[Level.mkZero, u]) + #[alpha, b, motive, c, h2, h1] + +/-- Build a proof of `@Eq.{v} β (f a) (f b)` from `h : @Eq.{u} α a b` via `@Eq.casesOn.{0, u}`. -/ +def mkEqCongrArgExpr (u v : Ix.Level) (alpha beta f a b h : Ix.Expr) : Ix.Expr := + let eqU := Expr.mkConst (Name.simple "Eq") #[u] + let eqV := Expr.mkConst (Name.simple "Eq") #[v] + let eqAX := Expr.mkAppN eqU #[liftLooseBVars alpha 1, liftLooseBVars a 1, Expr.mkBVar 0] + let fa := Expr.mkApp f a + let fx := Expr.mkApp (liftLooseBVars f 2) (Expr.mkBVar 1) + let eqFAFX := Expr.mkAppN eqV #[liftLooseBVars beta 2, liftLooseBVars fa 2, fx] + let motive := + Expr.mkLam (Name.simple "x") alpha + (Expr.mkLam Name.mkAnon eqAX eqFAFX .default) .default + let reflFAFA := mkEqReflExpr v beta fa + Expr.mkAppN (Expr.mkConst (Name.mkStr2 "Eq" "casesOn") #[Level.mkZero, u]) + #[alpha, a, motive, b, h, reflFAFA] + +/-- Transport `proofPA : instantiate1 absBody a` along `hEq : @Eq.{uEq} α a b` to produce a term + of type `instantiate1 absBody b` (where `absBody` has sort `Sort uMotive` and loose `bvar 0 : α`). -/ +def mkEqTransportExpr (uEq uMotive : Ix.Level) (alpha a b absBody hEq proofPA : Ix.Expr) : Ix.Expr := + let eqU := Expr.mkConst (Name.simple "Eq") #[uEq] + let eqAX := Expr.mkAppN eqU #[liftLooseBVars alpha 1, liftLooseBVars a 1, Expr.mkBVar 0] + -- Shift loose bvars in `absBody` up by 1 so `bvar 0` (`x : α`) becomes `bvar 1` under `_ : Eq a x` + let bodyUnderEq := liftLooseBVars absBody 1 0 + let motive := + Expr.mkLam (Name.simple "x") alpha + (Expr.mkLam Name.mkAnon eqAX bodyUnderEq .default) .default + Expr.mkAppN (Expr.mkConst (Name.mkStr2 "Eq" "casesOn") #[uMotive, uEq]) + #[alpha, a, motive, b, hEq, proofPA] + +/-- Test whether subterm `e` (without loose bvars) matches `pat` up to `isDefEq`. -/ +def tryKAbstractMatch (fuel : Nat) (e pat : Ix.Expr) : IxElabM Bool := do + if hasLooseBVarsAt e 0 then return false + if e == pat then return true + let ok? ← observing? do + let eqOk ← isDefEq fuel e pat + if !eqOk then throwElabError "kabstract mismatch" + return true + return (ok? == some true) + +/-- Core recursive worker for `kabstract`, structurally recursive on `kFuel : Nat`. -/ +def kabstractCore (fuel : Nat) : Nat → Ix.Expr → Ix.Expr → Nat → IxElabM (Bool × Ix.Expr) + | 0, _, e, _ => return (false, e) + | kFuel + 1, pat, e, depth => do + let matched ← tryKAbstractMatch fuel e pat + if matched then + return (true, Expr.mkBVar depth) + match e with + | .app f a _ => + let (cf, f') ← kabstractCore fuel kFuel pat f depth + let (ca, a') ← kabstractCore fuel kFuel pat a depth + if cf || ca then + return (true, Expr.mkApp f' a') + else if !hasLooseBVarsAt e 0 then + let eW ← whnf fuel e + if eW != e then + let (cw, eW') ← kabstractCore fuel kFuel pat eW depth + if cw then return (true, eW') else return (false, e) + else + return (false, e) + else + return (false, e) + | .lam nm t b bi _ => + let (ct, t') ← kabstractCore fuel kFuel pat t depth + let (cb, b') ← kabstractCore fuel kFuel pat b (depth + 1) + if ct || cb then return (true, Expr.mkLam nm t' b' bi) else return (false, e) + | .forallE nm t b bi _ => + let (ct, t') ← kabstractCore fuel kFuel pat t depth + let (cb, b') ← kabstractCore fuel kFuel pat b (depth + 1) + if ct || cb then return (true, Expr.mkForallE nm t' b' bi) else return (false, e) + | .letE nm t v b nd _ => + let (ct, t') ← kabstractCore fuel kFuel pat t depth + let (cv, v') ← kabstractCore fuel kFuel pat v depth + let (cb, b') ← kabstractCore fuel kFuel pat b (depth + 1) + if ct || cv || cb then return (true, Expr.mkLetE nm t' v' b' nd) else return (false, e) + | .proj nm i s _ => + let (cs, s') ← kabstractCore fuel kFuel pat s depth + if cs then return (true, Expr.mkProj nm i s') else return (false, e) + | .mdata md x _ => + let (cx, x') ← kabstractCore fuel kFuel pat x depth + if cx then return (true, Expr.mkMData md x') else return (false, e) + | _ => + return (false, e) + +/-- Abstract occurrences of `pat` in `e` into `bvar 0` (shifting existing loose bvars in `e` up by 1). -/ +def kabstract (fuel : Nat) (pat : Ix.Expr) (e : Ix.Expr) : IxElabM (Bool × Ix.Expr) := do + let eLifted := liftLooseBVars e 1 0 + kabstractCore fuel 64 pat eLifted 0 + +/-! ## Pure Beta-Reduction & Eliminator Helpers for `cases` / `induction` -/ + +/-- Apply `fn` to `args`, beta-reducing up to `steps` leading `.lam` binders. -/ +def applyBetaSteps : Nat → Ix.Expr → List Ix.Expr → Ix.Expr + | 0, fn, args => args.foldl Expr.mkApp fn + | k + 1, fn, arg :: rest => + match stripMData fn with + | .lam _ _ b _ _ => applyBetaSteps k (instantiate1 b arg) rest + | _ => (arg :: rest).foldl Expr.mkApp fn + | _, fn, [] => fn + +/-- Beta-reduce any `(fun x => b) a` redexes throughout `e` (used after substituting `motiveLam`). -/ +def betaReduceExpr : Ix.Expr → Ix.Expr + | .app f a _ => + let f' := betaReduceExpr f + let a' := betaReduceExpr a + let (hd, sp) := getAppFnArgs f' + applyBetaSteps 8 hd (sp.toList ++ [a']) + | .lam nm t b bi _ => Expr.mkLam nm (betaReduceExpr t) (betaReduceExpr b) bi + | .forallE nm t b bi _ => Expr.mkForallE nm (betaReduceExpr t) (betaReduceExpr b) bi + | .letE nm t v b nd _ => Expr.mkLetE nm (betaReduceExpr t) (betaReduceExpr v) (betaReduceExpr b) nd + | .proj nm i s _ => Expr.mkProj nm i (betaReduceExpr s) + | .mdata md x _ => Expr.mkMData md (betaReduceExpr x) + | other => other + +/-- Count the number of leading `.forallE` binders on `e`. -/ +def countLeadingForalls : Nat → Ix.Expr → Nat + | 0, _ => 0 + | k + 1, e => + match stripMData e with + | .forallE _ _ b _ _ => 1 + countLeadingForalls k b + | _ => 0 + +/-- Extract the number of minor-premise binders for each of the `numMinors` constructors + after peeling `prefixCount` binders from the uninstantiated eliminator type `rawElimTy`. -/ +def extractMinorBinderCounts (prefixCount numMinors : Nat) (rawElimTy : Ix.Expr) : Array Nat := + let (_, _, afterPrefix) := openForallTelescope prefixCount rawElimTy " dummy" 0 #[] #[] + let (_, minorDecls, _) := openForallTelescope numMinors afterPrefix "m" 0 #[] #[] + minorDecls.map fun d => countLeadingForalls 32 d.domain + +/-- Return the last string component of a name (e.g. `Nat.succ` -> `"succ"`). -/ +def lastNameStr : Ix.Name → String + | .str _ s _ => s + | _ => "" + +/-- True if a user branch tag `tag` matches constructor name `ctorName`. -/ +def matchesCtorTag (ctorName tag : Ix.Name) : Bool := + ctorName == tag || (lastNameStr ctorName != "" && lastNameStr ctorName == lastNameStr tag) + +/-- Collect unassigned expression metavariable IDs occurring in `e` in left-to-right order. -/ +def collectUnassignedMVarIds (mctx : MetavarContext) (e : Ix.Expr) : List Ix.Name := + let rec go : Ix.Expr → List Ix.Name → List Ix.Name + | .mvar id _, acc => + if !mctx.isExprAssigned id && !acc.contains id then id :: acc else acc + | .app f a _, acc => go a (go f acc) + | .lam _ t b _ _, acc => go b (go t acc) + | .forallE _ t b _ _, acc => go b (go t acc) + | .letE _ t v b _ _, acc => go b (go v (go t acc)) + | .proj _ _ s _, acc => go s acc + | .mdata _ x _, acc => go x acc + | _, acc => acc + (go e []).reverse + +/-- Rebuild a `LocalContext` from its chronological `decls` list. -/ +def rebuildLocalContext (decls : List LocalDecl) : LocalContext := + decls.foldl (fun lc d => lc.addDecl d) {} + +/-- Remove a set of `fvarIds` from `lctx`. -/ +def removeFVarsFromLCtx (lctx : LocalContext) (fvarIds : List Ix.Name) : LocalContext := + rebuildLocalContext (lctx.decls.filter fun d => !fvarIds.contains d.fvarId) + +/-! ## Definitional Simplification (`dsimpExpr`) -/ + +/-- Normalize subterms of `e` using `whnf` (beta, iota, zeta, projections, and Nat/String primitives) + without unfolding propositional connectives (`Eq`, `And`, `Or`, `Iff`, `Exists`, `True`, `False`). -/ +def isPreservedHeadConst (nm : Ix.Name) : Bool := + nm == Name.simple "Eq" || nm == Name.simple "And" || nm == Name.simple "Or" || + nm == Name.simple "Iff" || nm == Name.simple "Exists" || nm == Name.simple "True" || + nm == Name.simple "False" || nm == Name.simple "Not" || nm == Name.simple "Ne" + +def dsimpExpr (fuel : Nat) : Nat → Ix.Expr → IxElabM Ix.Expr + | 0, e => return e + | dFuel + 1, e => do + match e with + | .app f a _ => + let f' ← dsimpExpr fuel dFuel f + let a' ← dsimpExpr fuel dFuel a + let appExpr := Expr.mkApp f' a' + if hasLooseBVarsAt appExpr 0 then + return appExpr + else + let (hd, _) := getAppFnArgs appExpr + match hd with + | .const nm _ _ => + if isPreservedHeadConst nm then return appExpr + else whnf fuel appExpr + | .lam _ _ _ _ _ => whnf fuel appExpr + | _ => return appExpr + | .proj nm i s _ => + let s' ← dsimpExpr fuel dFuel s + let pExpr := Expr.mkProj nm i s' + if hasLooseBVarsAt pExpr 0 then return pExpr else whnf fuel pExpr + | .letE _ _ v b _ _ => + let v' ← dsimpExpr fuel dFuel v + dsimpExpr fuel dFuel (instantiate1 b v') + | .lam nm t b bi _ => + let t' ← dsimpExpr fuel dFuel t + let b' ← dsimpExpr fuel dFuel b + return Expr.mkLam nm t' b' bi + | .forallE nm t b bi _ => + let t' ← dsimpExpr fuel dFuel t + let b' ← dsimpExpr fuel dFuel b + return Expr.mkForallE nm t' b' bi + | .mdata md x _ => + let x' ← dsimpExpr fuel dFuel x + return Expr.mkMData md x' + | other => return other + +/-! ## Individual Tactic Implementations -/ + +/-- Introduce a single `.forallE` or `.letE` binder from the current main goal with user name `uName`, + returning `fvarId` of the newly introduced local hypothesis. -/ +def introOneMainGoalBinder (fuel : Nat) (uName : Ix.Name) (refStx? : Option Stx := none) + (reuseFVarId? : Option Ix.Name := none) : + TacticM Ix.Name := + withMainGoalContext refStx? fun gId gDecl gTy => do + let curW ← liftM (whnf fuel gTy) + match stripMData curW with + | .forallE defNm dom body bi _ => + let finalName := + if Name.isAnonymous uName then + if Name.isAnonymous defNm then Name.simple "h" else defNm + else uName + let fvId ← match reuseFVarId? with + | some id => pure id + | none => liftM (mkFreshName "_fvar") + let fvExpr := Expr.mkFVar fvId + let decl : LocalDecl := { fvarId := fvId, userName := finalName, type := dom, binderInfo := bi } + let lctx' := gDecl.lctx.addDecl decl + let nextTy := betaReduceExpr (instantiate1 body fvExpr) + let subMVar ← withReader (fun ctx => { ctx with lctx := lctx' }) do + liftM (mkFreshExprMVar nextTy gDecl.userName) + let subId := match subMVar with | .mvar id _ => id | _ => gId + liftM (modifyMCtx (·.assignDelayed gId { lctx := lctx', fvars := [fvId], pendingMVar := subId })) + replaceMainGoal [subId] + return fvId + | .letE defNm ty val body _ _ => + let finalName := + if Name.isAnonymous uName then + if Name.isAnonymous defNm then Name.simple "h" else defNm + else uName + let fvId ← match reuseFVarId? with + | some id => pure id + | none => liftM (mkFreshName "_fvar") + let fvExpr := Expr.mkFVar fvId + let decl : LocalDecl := { fvarId := fvId, userName := finalName, type := ty, value? := some val } + let lctx' := gDecl.lctx.addDecl decl + let nextTy := betaReduceExpr (instantiate1 body fvExpr) + let subMVar ← withReader (fun ctx => { ctx with lctx := lctx' }) do + liftM (mkFreshExprMVar nextTy gDecl.userName) + let subId := match subMVar with | .mvar id _ => id | _ => gId + liftM (modifyMCtx (·.assignDelayed gId { lctx := lctx', fvars := [fvId], pendingMVar := subId })) + replaceMainGoal [subId] + return fvId + | _ => + liftM (throwElabError "'intro' expected a function/forall goal type" refStx?) + +/-- `intro` / `intros`: peel `.forallE` binders into `lctx` and link via `DelayedMVarAssign`. -/ +def evalIntroTactic (fuel : Nat) (tac : Stx) : TacticM Unit := + withMainGoalContext (some tac) fun gId gDecl gTy => do + let kw := Syntax.getAtomVal (Syntax.getArg tac 0) + let rawIds := (Syntax.getArgs (Syntax.getArg tac 1)).toList + let rec introNamed (rem : List Stx) (curTy : Ix.Expr) (revFVars : List Ix.Name) : + TacticM (Ix.Expr × List Ix.Name × LocalContext) := do + match rem with + | [] => + let ctx ← read + return (curTy, revFVars.reverse, ctx.lctx) + | idStx :: nextIds => + let curW ← liftM (whnf fuel curTy) + match stripMData curW with + | .forallE defNm dom body bi _ => + let uName := + let id := Syntax.getId idStx + if Name.isAnonymous id then + if Name.isAnonymous defNm then Name.simple "h" else defNm + else id + let fvId ← liftM (mkFreshName "_fvar") + let fvExpr := Expr.mkFVar fvId + let decl : LocalDecl := { fvarId := fvId, userName := uName, type := dom, binderInfo := bi } + withReader (fun ctx => { ctx with lctx := ctx.lctx.addDecl decl }) do + introNamed nextIds (instantiate1 body fvExpr) (fvId :: revFVars) + | .letE defNm ty val body _ _ => + let uName := + let id := Syntax.getId idStx + if Name.isAnonymous id then + if Name.isAnonymous defNm then Name.simple "h" else defNm + else id + let fvId ← liftM (mkFreshName "_fvar") + let fvExpr := Expr.mkFVar fvId + let decl : LocalDecl := { fvarId := fvId, userName := uName, type := ty, value? := some val } + withReader (fun ctx => { ctx with lctx := ctx.lctx.addDecl decl }) do + introNamed nextIds (instantiate1 body fvExpr) (fvId :: revFVars) + | _ => + liftM (throwElabError "'intro' tactic expected a function/forall goal type" (some tac)) + let rec introsAll (k : Nat) (curTy : Ix.Expr) (revFVars : List Ix.Name) : + TacticM (Ix.Expr × List Ix.Name × LocalContext) := do + match k with + | 0 => + let ctx ← read + return (curTy, revFVars.reverse, ctx.lctx) + | k' + 1 => + let curW ← liftM (whnf fuel curTy) + match stripMData curW with + | .forallE defNm dom body bi _ => + let uName := if Name.isAnonymous defNm then Name.simple "h" else defNm + let fvId ← liftM (mkFreshName "_fvar") + let fvExpr := Expr.mkFVar fvId + let decl : LocalDecl := { fvarId := fvId, userName := uName, type := dom, binderInfo := bi } + withReader (fun ctx => { ctx with lctx := ctx.lctx.addDecl decl }) do + introsAll k' (instantiate1 body fvExpr) (fvId :: revFVars) + | _ => + let ctx ← read + return (curTy, revFVars.reverse, ctx.lctx) + let (finalTy, fvars, lctx') ← + if rawIds.isEmpty then + if kw == "intros" then + introsAll 32 gTy [] + else + introNamed [Syntax.mkSimpleIdent Name.mkAnon] gTy [] + else + introNamed rawIds gTy [] + if fvars.isEmpty then + return () + else + let subMVar ← withReader (fun ctx => { ctx with lctx := lctx' }) do + liftM (mkFreshExprMVar finalTy gDecl.userName) + let subId := match subMVar with | .mvar id _ => id | _ => gId + liftM (modifyMCtx (·.assignDelayed gId { lctx := lctx', fvars, pendingMVar := subId })) + replaceMainGoal [subId] + +/-- `rfl` / `decide`: close reflexive `@Eq`, `@Iff`, or `True` goals. -/ +def evalRflTactic (fuel : Nat) (tac : Stx) : TacticM Unit := + withMainGoalContext (some tac) fun _ _ gTy => do + let gTyW ← liftM (whnf fuel gTy) + let (hFn, hArgs) := getAppFnArgs gTyW + match hFn with + | .const cName cUnivs _ => + if cName == Name.simple "Eq" && hArgs.size == 3 then + let tyArg := hArgs.getD 0 gTyW + let lhs := hArgs.getD 1 gTyW + let rhs := hArgs.getD 2 gTyW + let ok ← liftM (isDefEq fuel lhs rhs) + if !ok then + liftM (throwElabError "'rfl' failed: left-hand side and right-hand side are not definitionally equal" (some tac)) + closeMainGoal (mkEqReflExpr (cUnivs.getD 0 Level.mkZero) tyArg lhs) (some tac) + else if cName == Name.simple "Iff" && hArgs.size == 2 then + let a := hArgs.getD 0 gTyW + let b := hArgs.getD 1 gTyW + let ok ← liftM (isDefEq fuel a b) + if !ok then + liftM (throwElabError "'rfl' failed: Iff sides are not definitionally equal" (some tac)) + let idLam := Expr.mkLam (Name.simple "h") a (Expr.mkBVar 0) .default + let iffRefl := Expr.mkAppN (Expr.mkConst (Name.mkStr2 "Iff" "intro") #[]) #[a, a, idLam, idLam] + closeMainGoal iffRefl (some tac) + else if cName == Name.simple "True" && hArgs.isEmpty then + closeMainGoal (Expr.mkConst (Name.mkStr2 "True" "intro") #[]) (some tac) + else + let (reflConst, reflTy) ← liftM (mkConstWithFreshMVarLevels (Name.mkStr2 "Eq" "refl")) + let (cand, _, resTy) ← liftM (openForallMVars 8 reflConst reflTy []) + let ok ← liftM (isDefEq fuel resTy gTyW) + if !ok then + liftM (throwElabError "'rfl' failed: goal is not a reflexive equality" (some tac)) + let candInst ← liftM (instantiateMVars 32 cand) + closeMainGoal candInst (some tac) + | _ => + liftM (throwElabError "'rfl' failed: goal is not an equality" (some tac)) + +/-- `assumption`: close the goal using a matching hypothesis in `lctx`. -/ +def evalAssumptionTactic (fuel : Nat) (tac : Stx) : TacticM Unit := + withMainGoalContext (some tac) fun _ gDecl gTy => do + let rec findMatching : List LocalDecl → IxElabM (Option Ix.Expr) + | [] => return none + | d :: rest => do + let dTy ← instantiateMVars 16 d.type + let ok? ← observing? do + let eqOk ← isDefEq fuel dTy gTy + if !eqOk then throwElabError "mismatch" + return (Expr.mkFVar d.fvarId) + match ok? with + | some fv => return some fv + | none => findMatching rest + match ← liftM (findMatching gDecl.lctx.revDecls) with + | some fv => closeMainGoal fv (some tac) + | none => liftM (throwElabError "'assumption' tactic failed to find a matching local hypothesis" (some tac)) + +/-- Build `@False.casesOn.{uGoal} (fun _ => gTy) falseProof : gTy`. -/ +def mkFalseElimExpr (uGoal : Ix.Level) (gTy falseProof : Ix.Expr) : Ix.Expr := + let falseConst := Expr.mkConst (Name.simple "False") #[] + let motive := Expr.mkLam Name.mkAnon falseConst (liftLooseBVars gTy 1) .default + Expr.mkAppN (Expr.mkConst (Name.mkStr2 "False" "casesOn") #[normalizeLevel uGoal]) #[motive, falseProof] + +/-- `contradiction`: close the goal from `h : False`, `h1 : P` & `h2 : ¬ P`, `h : a ≠ a`, or distinct constructors `C₁ ... = C₂ ...`. -/ +def evalContradictionTactic (fuel : Nat) (tac : Stx) : TacticM Unit := + withMainGoalContext (some tac) fun _ gDecl gTy => do + let uGoal ← liftM (ensureSort 32 gTy) + let decls := gDecl.lctx.revDecls + let mut falseProof? : Option Ix.Expr := none + for d in decls do + if falseProof?.isNone then + let dTy ← liftM (instantiateMVars 16 d.type) + let dTyW ← liftM (whnf fuel dTy) + match stripMData dTyW with + | .const nm _ _ => + if nm == Name.simple "False" then + falseProof? := some (Expr.mkFVar d.fvarId) + | .forallE _ dom body _ _ => + let bodyW ← liftM (whnf fuel body) + match stripMData bodyW with + | .const bNm _ _ => + if bNm == Name.simple "False" then + if let some (uEq, alpha, lhs, rhs) ← liftM (matchEqType? fuel dom) then + let eqOk? ← liftM <| observing? do + let ok ← isDefEq fuel lhs rhs + if !ok then throwElabError "not refl" + return true + if eqOk? == some true then + falseProof? := some (Expr.mkApp (Expr.mkFVar d.fvarId) (mkEqReflExpr uEq alpha lhs)) + if falseProof?.isNone then + for dPos in decls do + if falseProof?.isNone then + let posTy ← liftM (instantiateMVars 16 dPos.type) + let ok? ← liftM <| observing? do + let ok ← isDefEq fuel posTy dom + if !ok then throwElabError "mismatch" + return true + if ok? == some true then + falseProof? := some (Expr.mkApp (Expr.mkFVar d.fvarId) (Expr.mkFVar dPos.fvarId)) + | _ => pure () + | _ => pure () + match falseProof? with + | some fp => + closeMainGoal (mkFalseElimExpr uGoal gTy fp) (some tac) + | none => + liftM (throwElabError "'contradiction' tactic failed to find contradictory hypotheses" (some tac)) + +/-- `exfalso`: replace main goal `?g : gTy` with `?g' : False`. -/ +def evalExfalsoTactic (tac : Stx) : TacticM Unit := + withMainGoalContext (some tac) fun gId _ gTy => do + let uGoal ← liftM (ensureSort 32 gTy) + let falseConst := Expr.mkConst (Name.simple "False") #[] + let subMVar ← liftM (mkFreshExprMVar falseConst (Name.simple "False")) + let subId := match subMVar with | .mvar id _ => id | _ => gId + let proof := mkFalseElimExpr uGoal gTy subMVar + liftM (modifyMCtx (·.assignExpr gId proof)) + replaceMainGoal [subId] + +/-- `trivial`: try `rfl`, then `assumption`, then `contradiction`. -/ +def evalTrivialTactic (fuel : Nat) (tac : Stx) : TacticM Unit := do + if (← tryTactic? (evalRflTactic fuel tac)).isSome then return () + if (← tryTactic? (evalAssumptionTactic fuel tac)).isSome then return () + if (← tryTactic? (evalContradictionTactic fuel tac)).isSome then return () + liftM (throwElabError "'trivial' tactic failed to close goal" (some tac)) + +/-- Apply an already-elaborated function `(fnExpr, fnTy)` to the current main goal. -/ +def applyExprToMainGoal (fuel : Nat) (tac : Stx) (fnExpr fnTy : Ix.Expr) : TacticM Unit := + withMainGoalContext (some tac) fun gId _ gTy => do + let rec applyOpen (k : Nat) (curFn : Ix.Expr) (curTy : Ix.Expr) + (mvars : List (Ix.Expr × Lean.BinderInfo)) : IxElabM (Ix.Expr × List Ix.Name) := do + let ok ← observing? do + let eqOk ← isDefEq fuel curTy gTy + if !eqOk then throwElabError "not yet matching" + return true + if ok == some true then + for (mv, bi) in mvars.reverse do + if bi == .instImplicit then + let mvTy ← inferType fuel mv + if let some instVal ← synthInstance? 8 mvTy then + let _ ← isDefEq fuel mv instVal + let stNow ← get + let openGoals := mvars.reverse.filterMap fun (mv, _) => + match mv with + | .mvar mid _ => + if !stNow.mctx.isExprAssigned mid then some mid else none + | _ => none + return (curFn, openGoals) + else + match k with + | 0 => throwElabError "'apply' failed to unify conclusion with goal" (some tac) + | k' + 1 => + let curW ← whnf fuel curTy + match stripMData curW with + | .forallE nm dom body bi _ => + let mv ← mkFreshExprMVar dom nm + applyOpen k' (Expr.mkApp curFn mv) (instantiate1 body mv) ((mv, bi) :: mvars) + | _ => throwElabError "'apply' failed to match goal type" (some tac) + let (appliedVal, subGoals) ← liftM (applyOpen 24 fnExpr fnTy []) + liftM (modifyMCtx (·.assignExpr gId appliedVal)) + replaceMainGoal subGoals + +/-- `constructor` / `split` / `left` / `right`: apply the appropriate constructor of the target inductive type. -/ +def evalCtorSelectTactic (fuel : Nat) (tac : Stx) (which : String) : TacticM Unit := + withMainGoalContext (some tac) fun _ _ gTy => do + let gTyW ← liftM (whnf fuel gTy) + let (hFn, _) := getAppFnArgs gTyW + let stNow ← liftM (get : IxElabM ElabState) + match hFn with + | .const indName _ _ => + match stNow.env.find? indName with + | some (.inductInfo ival) => + let targetCtor? : Option Ix.Name := + if which == "left" then + let inl := Name.mkStr indName "inl" + let lft := Name.mkStr indName "left" + if ival.ctors.contains inl then some inl + else if ival.ctors.contains lft then some lft + else ival.ctors[0]? + else if which == "right" then + let inr := Name.mkStr indName "inr" + let rgt := Name.mkStr indName "right" + if ival.ctors.contains inr then some inr + else if ival.ctors.contains rgt then some rgt + else ival.ctors[1]? + else + ival.ctors[0]? + match targetCtor? with + | some ctorName => + let (ctorConst, ctorTy) ← liftM (mkConstWithFreshMVarLevels ctorName) + applyExprToMainGoal fuel tac ctorConst ctorTy + | none => + liftM (throwElabError s!"inductive '{Name.toStringTotal indName}' has no matching constructor for '{which}'" (some tac)) + | _ => liftM (throwElabError s!"'{which}' requires an inductive target type" (some tac)) + | _ => liftM (throwElabError s!"'{which}' requires an inductive target type" (some tac)) + +/-- `exists e₁, e₂, ...` (`use`): supply witness(es) to a single-constructor inductive (`Exists`, `Sigma`, `Prod`, `Subtype`), + pre-unifying inductive parameters before elaborating `wStx` and beta-reducing the remaining subgoal type. -/ +def evalExistsTactic (elabRec : Stx → Option Ix.Expr → IxElabM Ix.Expr) + (fuel : Nat) (tac : Stx) : TacticM Unit := do + let witStxs := (Syntax.getArgs (Syntax.getArg tac 1)).toList + let rec applyWitnesses : List Stx → TacticM Unit + | [] => return () + | wStx :: rest => + withMainGoalContext (some tac) fun gId _ gTy => do + let gTyW ← liftM (whnf fuel gTy) + let (hFn, hArgs) := getAppFnArgs gTyW + let stNow ← liftM (get : IxElabM ElabState) + match hFn with + | .const indName indUnivs _ => + match stNow.env.find? indName with + | some (.inductInfo ival) => + match ival.ctors[0]? with + | none => liftM (throwElabError s!"'{Name.toStringTotal indName}' has no constructors for 'exists'/'use'" (some tac)) + | some ctorName => + let (ctorConst, ctorTy) ← liftM do + match stNow.env.find? ctorName with + | some cinfo => + let cnst := Expr.ConstantInfo.getCnstPure cinfo + if cnst.levelParams.size == indUnivs.size then + pure (Expr.mkConst ctorName indUnivs, substExprLevelParams cnst.levelParams indUnivs cnst.type) + else + mkConstWithFreshMVarLevels ctorName + | none => mkConstWithFreshMVarLevels ctorName + let params := hArgs.extract 0 ival.numParams + let (ctorWithParams, instGoals, afterParamsTy) ← + if params.size == ival.numParams then + let tyAfter := params.foldl (fun cur p => + match stripMData cur with + | .forallE _ _ b _ _ => instantiate1 b p + | other => other) ctorTy + pure (Expr.mkAppN ctorConst params, [], tyAfter) + else + liftM (insertImplicitArgs 16 ctorConst ctorTy []) + let afterW ← liftM (whnf fuel afterParamsTy) + match stripMData afterW with + | .forallE _ wDom wBody _ _ => + let wDomInst ← liftM (instantiateMVars 32 wDom) + let wVal ← liftM (elabRec wStx (some wDomInst)) + let app1 := Expr.mkApp ctorWithParams wVal + let remTy := betaReduceExpr (instantiate1 wBody wVal) + let (fullApp, moreInst, finalTy) ← liftM (openForallMVars 16 app1 remTy instGoals) + let ok ← liftM (isDefEq fuel finalTy gTyW) + if !ok then + liftM (throwElabError "'exists'/'use' failed to unify constructor conclusion with goal" (some tac)) + for ig in moreInst do + let igTy ← liftM (inferType fuel ig) + if let some iv ← liftM (synthInstance? 8 igTy) then + let _ ← liftM (isDefEq fuel ig iv) + let stAfter ← liftM (get : IxElabM ElabState) + let newGoals := collectUnassignedMVarIds stAfter.mctx fullApp + for ngId in newGoals do + if let some ngDecl := stAfter.mctx.findDecl? ngId then + let ngTyInst ← liftM (instantiateMVars 32 ngDecl.type) + let ngTyBeta := betaReduceExpr ngTyInst + liftM (modifyMCtx (·.addExprMVarDecl { ngDecl with type := ngTyBeta })) + liftM (modifyMCtx (·.assignExpr gId fullApp)) + replaceMainGoal newGoals + applyWitnesses rest + | _ => + liftM (throwElabError "'exists'/'use' constructor does not take a witness argument" (some tac)) + | _ => liftM (throwElabError "'exists'/'use' target must be an inductive type" (some tac)) + | _ => liftM (throwElabError "'exists'/'use' target must be an inductive type" (some tac)) + applyWitnesses witStxs + let _ ← tryTactic? (evalTrivialTactic fuel tac) + +/-- `symm` (`symmetry`): transform `@Eq.{u} α lhs rhs` into `@Eq.{u} α rhs lhs` (or `Iff lhs rhs` into `Iff rhs lhs`). -/ +def evalSymmTactic (fuel : Nat) (tac : Stx) : TacticM Unit := + withMainGoalContext (some tac) fun gId gDecl gTy => do + match ← liftM (matchEqType? fuel gTy) with + | some (u, alpha, lhs, rhs) => + let symmGoalTy := Expr.mkAppN (Expr.mkConst (Name.simple "Eq") #[u]) #[alpha, rhs, lhs] + let subMVar ← liftM (mkFreshExprMVar symmGoalTy gDecl.userName) + let subId := match subMVar with | .mvar id _ => id | _ => gId + let proof := mkEqSymmExpr u alpha rhs lhs subMVar + liftM (modifyMCtx (·.assignExpr gId proof)) + replaceMainGoal [subId] + | none => + match ← liftM (matchIffType? fuel gTy) with + | some (lhs, rhs) => + let symmGoalTy := Expr.mkAppN (Expr.mkConst (Name.simple "Iff") #[]) #[rhs, lhs] + let subMVar ← liftM (mkFreshExprMVar symmGoalTy gDecl.userName) + let subId := match subMVar with | .mvar id _ => id | _ => gId + let mp := Expr.mkAppN (Expr.mkConst (Name.mkStr2 "Iff" "mpr") #[]) #[rhs, lhs, subMVar] + let mpr := Expr.mkAppN (Expr.mkConst (Name.mkStr2 "Iff" "mp") #[]) #[rhs, lhs, subMVar] + let proof := Expr.mkAppN (Expr.mkConst (Name.mkStr2 "Iff" "intro") #[]) #[lhs, rhs, mp, mpr] + liftM (modifyMCtx (·.assignExpr gId proof)) + replaceMainGoal [subId] + | none => + liftM (throwElabError "'symm' tactic requires an equality or Iff goal" (some tac)) + +/-- `trans [mid]` (`transitivity`): split `@Eq.{u} α lhs rhs` into `lhs = mid` and `mid = rhs`. -/ +def evalTransTactic (elabRec : Stx → Option Ix.Expr → IxElabM Ix.Expr) + (fuel : Nat) (tac : Stx) : TacticM Unit := + withMainGoalContext (some tac) fun gId gDecl gTy => do + match ← liftM (matchEqType? fuel gTy) with + | some (u, alpha, lhs, rhs) => + let optMid := Syntax.getArg tac 1 + let (midExpr, midGoals) ← + match Syntax.getOptional? optMid with + | some midStx => + let m ← liftM (elabRec midStx (some alpha)) + pure (m, []) + | none => + let m ← liftM (mkFreshExprMVar alpha (Name.simple "mid")) + let mId := match m with | .mvar id _ => [id] | _ => [] + pure (m, mId) + let eqConst := Expr.mkConst (Name.simple "Eq") #[u] + let g1Ty := Expr.mkAppN eqConst #[alpha, lhs, midExpr] + let g2Ty := Expr.mkAppN eqConst #[alpha, midExpr, rhs] + let g1MVar ← liftM (mkFreshExprMVar g1Ty gDecl.userName) + let g2MVar ← liftM (mkFreshExprMVar g2Ty gDecl.userName) + let g1Id := match g1MVar with | .mvar id _ => id | _ => gId + let g2Id := match g2MVar with | .mvar id _ => id | _ => gId + let proof := mkEqTransExpr u alpha lhs midExpr rhs g1MVar g2MVar + liftM (modifyMCtx (·.assignExpr gId proof)) + replaceMainGoal ([g1Id, g2Id] ++ midGoals) + | none => + liftM (throwElabError "'trans' tactic requires an equality goal" (some tac)) + +/-- `congr`: reduce `@Eq.{v} β (f a) (f b)` to `@Eq.{u} α a b` via `@Eq.casesOn`. -/ +def evalCongrTactic (fuel : Nat) (tac : Stx) : TacticM Unit := + withMainGoalContext (some tac) fun gId gDecl gTy => do + match ← liftM (matchEqType? fuel gTy) with + | some (v, beta, lhs, rhs) => + match stripMData lhs, stripMData rhs with + | .app f a _, .app g b _ => + let fnEq ← liftM (isDefEq fuel f g) + if !fnEq then + liftM (throwElabError "'congr' failed: function heads are not definitionally equal" (some tac)) + let aTy ← liftM (inferType fuel a) + let u ← liftM (ensureSort 32 aTy) + let subGoalTy := Expr.mkAppN (Expr.mkConst (Name.simple "Eq") #[normalizeLevel u]) #[aTy, a, b] + let subMVar ← liftM (mkFreshExprMVar subGoalTy gDecl.userName) + let subId := match subMVar with | .mvar id _ => id | _ => gId + let proof := mkEqCongrArgExpr (normalizeLevel u) v aTy beta f a b subMVar + liftM (modifyMCtx (·.assignExpr gId proof)) + replaceMainGoal [subId] + | _, _ => + liftM (throwElabError "'congr' tactic requires an equality between applications 'f a = f b'" (some tac)) + | none => + liftM (throwElabError "'congr' tactic requires an equality goal" (some tac)) + +/-- True if `e` is `.const target _ _`. -/ +def isExprConstOf : Ix.Expr → Ix.Name → Bool + | .const nm _ _, target => nm == target + | _, _ => false + +/-- Append a `LetContract` to `ElabState.localLetContracts` strictly. -/ +def pushLocalLetContract (lc : Ixon.LetContract) : IxElabM Unit := fun _ st => + match st with + | ⟨env, mctx, nextId, autoUnivs, letContracts⟩ => + .ok () ⟨env, mctx, nextId, autoUnivs, letContracts.push lc⟩ + +/-- `funext x₁ ...` / `ext x₁ ...`: apply `funext` (if in env) or `Iff.intro` and `intro` binders. -/ +def evalExtTactic (fuel : Nat) (tac : Stx) : TacticM Unit := do + let rawIds := (Syntax.getArgs (Syntax.getArg tac 1)).toList + let ids := if rawIds.isEmpty then [Syntax.mkSimpleIdent (Name.simple "x")] else rawIds + let rec extStep : List Stx → TacticM Unit + | [] => return () + | idStx :: rest => + withMainGoalContext (some tac) fun _ _ gTy => do + let gTyW ← liftM (whnf fuel gTy) + let (hFn, _) := getAppFnArgs gTyW + let st ← liftM (get : IxElabM ElabState) + if isExprConstOf hFn (Name.simple "Iff") then + let (iffConst, iffTy) ← liftM (mkConstWithFreshMVarLevels (Name.mkStr2 "Iff" "intro")) + applyExprToMainGoal fuel tac iffConst iffTy + else if st.env.contains (Name.simple "funext") then + let (feConst, feTy) ← liftM (mkConstWithFreshMVarLevels (Name.simple "funext")) + applyExprToMainGoal fuel tac feConst feTy + let introNode := Syntax.mkNode SyntaxKind.tacticIntro + #[Syntax.mkSimpleAtom "intro", Syntax.mkNullNode #[idStx]] + evalIntroTactic fuel introNode + extStep rest + else + liftM (throwElabError "'funext'/'ext' requires 'funext' in environment or an 'Iff' goal" (some tac)) + extStep ids + +/-- `have [h] [: T] := v` and `let [x] [: T] := v` using `DelayedMVarAssign`. -/ +def evalHaveOrLetTactic (elabRec : Stx → Option Ix.Expr → IxElabM Ix.Expr) + (fuel : Nat) (tac : Stx) (isHave : Bool) : TacticM Unit := + withMainGoalContext (some tac) fun gId gDecl gTy => do + let bId := Syntax.getId (Syntax.getArg tac 1) + let uName := if Name.isAnonymous bId then Name.simple "this" else bId + let optTyNode := Syntax.getArg tac 2 + let valStx := Syntax.getArg tac 4 + let expTy? ← + if Syntax.getNumArgs optTyNode >= 2 then + let t ← liftM (elabRec (Syntax.getArg optTyNode 1) none) + let _ ← liftM (ensureSort 32 t) + pure (some t) + else + pure none + let valExpr ← liftM (elabRec valStx expTy?) + let valTy ← match expTy? with + | some t => pure t + | none => liftM (inferType fuel valExpr) + let valTyInst ← liftM (instantiateMVars 32 valTy) + let valExprInst ← liftM (instantiateMVars 32 valExpr) + let fvId ← liftM (mkFreshName "_fvar") + let decl : LocalDecl := { + fvarId := fvId + userName := uName + type := valTyInst + value? := some valExprInst + binderInfo := .default + contract := default + letKind? := some .value + nonDep := isHave + } + let lctx' := gDecl.lctx.addDecl decl + let subMVar ← withReader (fun ctx => { ctx with lctx := lctx' }) do + liftM (mkFreshExprMVar gTy gDecl.userName) + let subId := match subMVar with | .mvar id _ => id | _ => gId + if isHave then + liftM (pushLocalLetContract { nonDep := true, kind := .value, binder := default }) + liftM (modifyMCtx (·.assignDelayed gId { lctx := lctx', fvars := [fvId], pendingMVar := subId })) + replaceMainGoal [subId] + +/-- `show T` / `change T`: replace main goal type with definitionally equal `T`. -/ +def evalChangeOrShowTactic (elabRec : Stx → Option Ix.Expr → IxElabM Ix.Expr) + (fuel : Nat) (tac : Stx) : TacticM Unit := + withMainGoalContext (some tac) fun gId gDecl gTy => do + let newTyStx := Syntax.getArg tac 1 + let newTy ← liftM (elabRec newTyStx none) + let _ ← liftM (ensureSort 32 newTy) + let ok ← liftM (isDefEq fuel gTy newTy) + if !ok then + liftM (throwElabError "'change'/'show' type is not definitionally equal to current goal" (some tac)) + let newTyInst ← liftM (instantiateMVars 32 newTy) + let subMVar ← liftM (mkFreshExprMVar newTyInst gDecl.userName) + let subId := match subMVar with | .mvar id _ => id | _ => gId + liftM (modifyMCtx (·.assignExpr gId subMVar)) + replaceMainGoal [subId] + +/-- Single rewrite step `rwRule` (`[←] term`) over `Eq` (`=`) or `Iff` (`↔`, converted via `@propext`) + on either the main goal (`atHyp? = none`) or a local hypothesis (`atHyp? = some hypName`). -/ +def evalOneRwRule (elabRec : Stx → Option Ix.Expr → IxElabM Ix.Expr) + (fuel : Nat) (ruleStx : Stx) (atHyp? : Option Ix.Name) : TacticM Unit := + withMainGoalContext (some ruleStx) fun gId gDecl gTy => do + let (isSymm, termStx) := + if Syntax.isOfKind ruleStx SyntaxKind.tacticRwRule then + let symmNode := Syntax.getArg ruleStx 0 + (!Syntax.isNone symmNode && !Syntax.isMissing symmNode, Syntax.getArg ruleStx 1) + else + (false, ruleStx) + let rawRuleExpr ← liftM (elabRec termStx none) + let rawRuleTy ← liftM (inferType fuel rawRuleExpr) + let (candRaw, instGoals, resTy) ← liftM (openForallMVars 16 rawRuleExpr rawRuleTy []) + let some (uEqRaw, alphaRaw, lhsRaw, rhsRaw, cand) ← liftM (matchEqOrIffProof? fuel candRaw resTy) + | liftM (throwElabError "'rw' rule must be an equality or iff (or quantification over an equality/iff)" (some ruleStx)) + let patRaw := if isSymm then rhsRaw else lhsRaw + let repRaw := if isSymm then lhsRaw else rhsRaw + + match atHyp? with + | none => + let (found, absGoalRaw) ← liftM (kabstract fuel patRaw gTy) + if !found then + liftM (throwElabError "'rw' tactic failed: did not find instance of pattern in target" (some ruleStx)) + for ig in instGoals do + let igTy ← liftM (inferType fuel ig) + if let some iv ← liftM (synthInstance? 8 igTy) then + let _ ← liftM (isDefEq fuel ig iv) + let uEq ← liftM (instantiateLevelMVars 32 uEqRaw) + let alpha ← liftM (instantiateMVars 32 alphaRaw) + let pat ← liftM (instantiateMVars 32 patRaw) + let rep ← liftM (instantiateMVars 32 repRaw) + let candInst ← liftM (instantiateMVars 32 cand) + let absGoal ← liftM (instantiateMVars 32 absGoalRaw) + let newGoalTy := instantiate1 absGoal rep + let uGoal ← liftM (ensureSort 32 gTy) + let eqRepToPat := + if isSymm then + candInst + else + mkEqSymmExpr (normalizeLevel uEq) alpha pat rep candInst + let subMVar ← liftM (mkFreshExprMVar newGoalTy gDecl.userName) + let subId := match subMVar with | .mvar id _ => id | _ => gId + let transportedProof := + mkEqTransportExpr (normalizeLevel uEq) (normalizeLevel uGoal) alpha rep pat absGoal eqRepToPat subMVar + liftM (modifyMCtx (·.assignExpr gId transportedProof)) + replaceMainGoal [subId] + | some hypName => + let some hypDecl := gDecl.lctx.findUserName? hypName + | liftM (throwElabError s!"unknown local hypothesis '{Name.toStringTotal hypName}' in 'rw ... at'" (some ruleStx)) + let hypTy ← liftM (instantiateMVars 32 hypDecl.type) + let (found, absHypRaw) ← liftM (kabstract fuel patRaw hypTy) + if !found then + liftM (throwElabError s!"'rw' failed: pattern not found in hypothesis '{Name.toStringTotal hypName}'" (some ruleStx)) + for ig in instGoals do + let igTy ← liftM (inferType fuel ig) + if let some iv ← liftM (synthInstance? 8 igTy) then + let _ ← liftM (isDefEq fuel ig iv) + let uEq ← liftM (instantiateLevelMVars 32 uEqRaw) + let alpha ← liftM (instantiateMVars 32 alphaRaw) + let pat ← liftM (instantiateMVars 32 patRaw) + let rep ← liftM (instantiateMVars 32 repRaw) + let candInst ← liftM (instantiateMVars 32 cand) + let absHyp ← liftM (instantiateMVars 32 absHypRaw) + let newHypTy := instantiate1 absHyp rep + let uHyp ← liftM (ensureSort 32 hypTy) + let eqPatToRep := + if isSymm then + mkEqSymmExpr (normalizeLevel uEq) alpha rep pat candInst + else + candInst + let newHypVal := + mkEqTransportExpr (normalizeLevel uEq) (normalizeLevel uHyp) alpha pat rep absHyp eqPatToRep (Expr.mkFVar hypDecl.fvarId) + let newFvId ← liftM (mkFreshName "_fvar") + let newDecl : LocalDecl := { + fvarId := newFvId + userName := hypName + type := newHypTy + value? := some newHypVal + letKind? := some .value + nonDep := true + } + let lctx' := gDecl.lctx.addDecl newDecl + liftM (pushLocalLetContract { nonDep := true, kind := .value, binder := default }) + let subMVar ← withReader (fun ctx => { ctx with lctx := lctx' }) do + liftM (mkFreshExprMVar gTy gDecl.userName) + let subId := match subMVar with | .mvar id _ => id | _ => gId + liftM (modifyMCtx (·.assignDelayed gId { lctx := lctx', fvars := [newFvId], pendingMVar := subId })) + replaceMainGoal [subId] + +/-- `rw [rule₁, ...] [at hyp]`: apply each rewrite rule sequentially, then try `rfl` on the goal. -/ +def evalRwTactic (elabRec : Stx → Option Ix.Expr → IxElabM Ix.Expr) + (fuel : Nat) (tac : Stx) : TacticM Unit := do + let rules := (Syntax.getArgs (Syntax.getArg tac 2)).toList + let optAt := Syntax.getArg tac 4 + let atHyp? : Option Ix.Name := + if Syntax.getNumArgs optAt >= 2 then + some (Syntax.getId (Syntax.getArg optAt 1)) + else + none + let rec loop : List Stx → TacticM Unit + | [] => return () + | r :: rs => do + evalOneRwRule elabRec fuel r atHyp? + loop rs + loop rules + if atHyp?.isNone then + let _ ← tryTactic? (evalRflTactic fuel tac) + +/-- `dsimp [only] [[...]] [at hyp]` and `simp [only] [[...]] [at hyp]`. -/ +def evalSimpOrDSimpTactic (elabRec : Stx → Option Ix.Expr → IxElabM Ix.Expr) + (fuel : Nat) (tac : Stx) (isFullSimp : Bool) : TacticM Unit := do + let (isOnly, optRulesNode, optAtNode) := + if Syntax.getNumArgs tac >= 4 then + let onlyNode := Syntax.getArg tac 1 + (!Syntax.isNone onlyNode && !Syntax.isMissing onlyNode, + Syntax.getArg tac 2, + Syntax.getArg tac 3) + else + (false, Syntax.getArg tac 1, Syntax.getArg tac 2) + let extraRules : List Stx := + if Syntax.getNumArgs optRulesNode >= 2 then + (Syntax.getArgs (Syntax.getArg optRulesNode 1)).toList + else + [] + let atHyp? : Option Ix.Name := + if Syntax.getNumArgs optAtNode >= 2 then + some (Syntax.getId (Syntax.getArg optAtNode 1)) + else + none + withMainGoalContext (some tac) fun gId gDecl gTy => do + match atHyp? with + | none => + let gTySimp ← liftM (dsimpExpr fuel 32 gTy) + if gTySimp != gTy then + let subMVar ← liftM (mkFreshExprMVar gTySimp gDecl.userName) + let subId := match subMVar with | .mvar id _ => id | _ => gId + liftM (modifyMCtx (·.assignExpr gId subMVar)) + replaceMainGoal [subId] + | some hypName => + let some hypDecl := gDecl.lctx.findUserName? hypName + | liftM (throwElabError s!"unknown hypothesis '{Name.toStringTotal hypName}' in 'simp/dsimp at'" (some tac)) + let hypTy ← liftM (instantiateMVars 32 hypDecl.type) + let hypTySimp ← liftM (dsimpExpr fuel 32 hypTy) + if hypTySimp != hypTy then + let newFvId ← liftM (mkFreshName "_fvar") + let newDecl : LocalDecl := { + fvarId := newFvId + userName := hypName + type := hypTySimp + value? := some (Expr.mkFVar hypDecl.fvarId) + letKind? := some .value + nonDep := true + } + let lctx' := gDecl.lctx.addDecl newDecl + liftM (pushLocalLetContract { nonDep := true, kind := .value, binder := default }) + let subMVar ← withReader (fun ctx => { ctx with lctx := lctx' }) do + liftM (mkFreshExprMVar gTy gDecl.userName) + let subId := match subMVar with | .mvar id _ => id | _ => gId + liftM (modifyMCtx (·.assignDelayed gId { lctx := lctx', fvars := [newFvId], pendingMVar := subId })) + replaceMainGoal [subId] + let envSimpRules : List Stx ← + if isFullSimp && !isOnly then + let stNow ← liftM (get : IxElabM ElabState) + let simpEntries : List InstanceEntry := (stNow.env.instancesByClass.get? (Name.mkStr2 "_Ix" "simpLemma")).getD [] + pure (simpEntries.reverse.map fun (e : InstanceEntry) => + Syntax.mkNode SyntaxKind.tacticRwRule #[Syntax.mkNullNode #[], Syntax.mkSimpleIdent e.instName]) + else + pure [] + let explicitRwRules := extraRules.map fun rStx => + if Syntax.isOfKind rStx SyntaxKind.tacticRwRule then rStx + else Syntax.mkNode SyntaxKind.tacticRwRule #[Syntax.mkNullNode #[], rStx] + let allRwRules := explicitRwRules ++ envSimpRules + if !allRwRules.isEmpty then + let rec simpRwLoop : Nat → TacticM Unit + | 0 => return () + | k + 1 => do + let mut anyProgress := false + for rStx in allRwRules do + if (← tryTactic? (evalOneRwRule elabRec fuel rStx atHyp?)).isSome then + anyProgress := true + if anyProgress then simpRwLoop k else return () + simpRwLoop 8 + if isFullSimp && atHyp?.isNone then + if isOnly then + let _ ← tryTactic? (evalRflTactic fuel tac) + else + let _ ← tryTactic? (evalTrivialTactic fuel tac) + +/-! ## `cases` and `induction` via `.casesOn` / `.recOn` -/ + +/-- Execute `cases` or `induction` (both unstructured and `with | tag xs => seq`), + parameterized by `evalSeqRec` for structured branch sequences. -/ +def evalCasesOrInductionTactic + (elabRec : Stx → Option Ix.Expr → IxElabM Ix.Expr) + (evalSeqRec : Stx → TacticM Unit) + (fuel : Nat) (tac : Stx) (isInd : Bool) : TacticM Unit := + withMainGoalContext (some tac) fun gId _ gTy => do + let targetStx := Syntax.getArg tac 1 + let optWith := Syntax.getArg tac 2 + let alts : Array Stx := + if Syntax.getNumArgs optWith >= 2 then + Syntax.getArgs (Syntax.getArg optWith 1) + else + #[] + let targetExpr ← liftM (elabRec targetStx none) + let targetTyRaw ← liftM (inferType fuel targetExpr) + let targetTy ← liftM (instantiateMVars 32 targetTyRaw) + let targetTyW ← liftM (whnf fuel targetTy) + let (hFn, headArgs) := getAppFnArgs targetTyW + let st ← liftM (get : IxElabM ElabState) + match hFn with + | .const indName indUnivs _ => + match st.env.find? indName with + | some (.inductInfo ival) => + let prefSuffix := if isInd then "recOn" else "casesOn" + let prefName := Name.mkStr indName prefSuffix + let elimName := + if st.env.contains prefName then prefName + else Name.mkStr indName "recOn" + match st.env.find? elimName with + | some (.defnInfo elimDef) => + let elimUnivs ← + if elimDef.cnst.levelParams.size == indUnivs.size + 1 then + let uMot ← liftM (ensureSort 32 gTy) + pure (#[normalizeLevel uMot] ++ indUnivs) + else + pure indUnivs + let params := headArgs.extract 0 ival.numParams + let indices := headArgs.extract ival.numParams headArgs.size + let afterParamsInst := params.foldl (fun cur p => + match stripMData cur with + | .forallE _ _ b _ _ => instantiate1 b p + | other => other) (substExprLevelParams ival.cnst.levelParams indUnivs ival.cnst.type) + let (idxFVars, idxDecls, _) := openForallTelescope ival.numIndices afterParamsInst "midx" 0 #[] #[] + let majDom := Expr.mkAppN (Expr.mkConst indName indUnivs) (params ++ idxFVars) + let (majFvId, majFvExpr) := mkAuxFVar "mmaj" 0 + let majDecl : AuxLocalDecl := { fvarId := majFvId, binderName := Name.simple "x", domain := majDom } + let motiveBody ← match stripMData targetExpr with + | .fvar targetFvId _ => + let b0 := instantiate1 (abstractFVar targetFvId gTy) majFvExpr + let b1 := (indices.zipIdx).foldl (fun acc (idxE, k) => + match stripMData idxE, idxFVars[k]? with + | .fvar iFv _, some repFv => + if iFv != targetFvId then instantiate1 (abstractFVar iFv acc) repFv else acc + | _, _ => acc) b0 + pure b1 + | _ => + let (_, absG) ← liftM (kabstract fuel targetExpr gTy) + pure (instantiate1 absG majFvExpr) + let motiveLam := closeLambdas (idxDecls.push majDecl) motiveBody + + let rawElimTy := substExprLevelParams elimDef.cnst.levelParams elimUnivs elimDef.cnst.type + let prefixArgs := params ++ #[motiveLam] ++ indices ++ #[targetExpr] + let minorBinderCounts := extractMinorBinderCounts prefixArgs.size ival.ctors.size rawElimTy + let minorsTelTy := prefixArgs.foldl (fun cur arg => + match stripMData cur with + | .forallE _ _ b _ _ => instantiate1 b arg + | other => other) rawElimTy + + let mut curTel := minorsTelTy + let mut minorLams : Array Ix.Expr := #[] + let mut branchSubGoals : Array (Ix.Name × Ix.Name × Option Stx) := #[] + for (ctorName, cIdx) in ival.ctors.zipIdx do + let minorDom ← match stripMData curTel with + | .forallE _ d b _ _ => + curTel := b + pure (betaReduceExpr d) + | _ => + liftM (throwElabError s!"unexpected eliminator type in '{Name.toStringTotal elimName}'" (some tac)) + let numBinders := minorBinderCounts.getD cIdx 0 + let matchedAlt? := alts.findSome? fun altStx => + let tagId := Syntax.getId (Syntax.getArg altStx 1) + if matchesCtorTag ctorName tagId then + let bIds := (Syntax.getArgs (Syntax.getArg altStx 2)).map Syntax.getId + let seqStx := Syntax.getArg altStx 4 + some (bIds, seqStx) + else + none + if !alts.isEmpty && matchedAlt?.isNone then + liftM (throwElabError s!"non-exhaustive '{if isInd then "induction" else "cases"}': missing branch for constructor '{Name.toStringTotal ctorName}'" (some tac)) + let userBinderNames : Array Ix.Name := match matchedAlt? with + | some (bIds, _) => bIds + | none => #[] + let finishMinorSubGoal (curTy : Ix.Expr) (revFVars : List Ix.Name) : + IxElabM (Ix.Name × Ix.Expr) := do + let subMVar ← mkFreshExprMVar curTy ctorName + let subId := match subMVar with | .mvar id _ => id | _ => gId + if revFVars.isEmpty then + return (subId, subMVar) + else + let ctx ← read + let outerMVar ← mkFreshExprMVar minorDom ctorName + let outerId := match outerMVar with | .mvar id _ => id | _ => gId + modifyMCtx (·.assignDelayed outerId { + lctx := ctx.lctx + fvars := revFVars.reverse + pendingMVar := subId + }) + return (subId, outerMVar) + let rec openMinorBinders (rem : Nat) (curTy : Ix.Expr) (bIdx : Nat) + (revFVars : List Ix.Name) : IxElabM (Ix.Name × Ix.Expr) := do + match rem with + | 0 => + finishMinorSubGoal curTy revFVars + | rem' + 1 => + let curW ← match stripMData curTy with + | .forallE _ _ _ _ _ => pure curTy + | _ => whnf fuel curTy + match stripMData curW with + | .forallE defNm fDom fBody bi _ => + let uName := + let un := userBinderNames.getD bIdx Name.mkAnon + if Name.isAnonymous un then defNm else un + withLocalDecl uName fDom bi default fun fvId fvExpr => + openMinorBinders rem' (instantiate1 fBody fvExpr) (bIdx + 1) (fvId :: revFVars) + | _ => + finishMinorSubGoal curTy revFVars + let (subId, minorLam) ← liftM (openMinorBinders numBinders minorDom 0 []) + minorLams := minorLams.push minorLam + branchSubGoals := branchSubGoals.push (ctorName, subId, matchedAlt?.map Prod.snd) + + let elimApp := Expr.mkAppN (Expr.mkConst elimName elimUnivs) (prefixArgs ++ minorLams) + liftM (modifyMCtx (·.assignExpr gId elimApp)) + if alts.isEmpty then + replaceMainGoal (branchSubGoals.toList.map (·.2.1)) + else + replaceMainGoal [] + let savedRestGoals ← getUnassignedGoals + for altStx in alts do + let tagId := Syntax.getId (Syntax.getArg altStx 1) + let seqStx := Syntax.getArg altStx 4 + match branchSubGoals.find? (fun (cNm, _, _) => matchesCtorTag cNm tagId) with + | none => + liftM (throwElabError s!"unknown constructor branch '{Name.toStringTotal tagId}' for '{Name.toStringTotal indName}'" (some altStx)) + | some (_, subId, _) => + setTacticGoals [subId] + evalSeqRec seqStx + let remInBranch ← getUnassignedGoals + if !remInBranch.isEmpty then + liftM (throwElabError s!"unsolved goals in branch '{Name.toStringTotal tagId}'" (some altStx)) + setTacticGoals savedRestGoals + | _ => + liftM (throwElabError s!"eliminator '{Name.toStringTotal elimName}' not found" (some tac)) + | _ => + liftM (throwElabError s!"'{Name.toStringTotal indName}' is not an inductive type" (some targetStx)) + | _ => + liftM (throwElabError "'cases'/'induction' target must have an inductive type" (some targetStx)) + +/-! ## Context, Classical, Recursive Destructuring (`rcases`/`obtain`/`rintro`), & `calc` Tactics -/ + +/-- `clear h₁ h₂ ...`: remove hypotheses from `lctx` after checking that the goal and remaining + local declarations do not depend on them. -/ +def evalClearTactic (tac : Stx) : TacticM Unit := do + let idStxs := (Syntax.getArgs (Syntax.getArg tac 1)).toList + let rec clearLoop : List Stx → TacticM Unit + | [] => return () + | idStx :: rest => do + withMainGoalContext (some idStx) fun gId gDecl gTy => do + let hName := Syntax.getId idStx + let some hDecl := gDecl.lctx.findUserName? hName + | liftM (throwElabError s!"unknown hypothesis '{Name.toStringTotal hName}' in 'clear'" (some idStx)) + let hFvId := hDecl.fvarId + if containsFVar hFvId gTy then + liftM (throwElabError s!"cannot clear '{Name.toStringTotal hName}': target goal depends on it" (some idStx)) + let remainingDecls := gDecl.lctx.decls.filter (fun d => d.fvarId != hFvId) + for d in remainingDecls do + let dTy ← liftM (instantiateMVars 16 d.type) + if containsFVar hFvId dTy then + liftM (throwElabError s!"cannot clear '{Name.toStringTotal hName}': hypothesis '{Name.toStringTotal d.userName}' depends on it" (some idStx)) + if let some dVal := d.value? then + let dValInst ← liftM (instantiateMVars 16 dVal) + if containsFVar hFvId dValInst then + liftM (throwElabError s!"cannot clear '{Name.toStringTotal hName}': let-binding '{Name.toStringTotal d.userName}' depends on it" (some idStx)) + let lctx' := rebuildLocalContext remainingDecls + let subMVar ← withReader (fun ctx => { ctx with lctx := lctx' }) do + liftM (mkFreshExprMVar gTy gDecl.userName) + let subId := match subMVar with | .mvar id _ => id | _ => gId + liftM (modifyMCtx (·.assignExpr gId subMVar)) + replaceMainGoal [subId] + clearLoop rest + clearLoop idStxs + +/-- Revert a single local declaration `hDecl` into a `.forallE` or `.letE` binder on the main goal. -/ +def revertSingleFVar (tac : Stx) (hFvId : Ix.Name) : TacticM Unit := + withMainGoalContext (some tac) fun gId gDecl gTy => do + let some hDecl := gDecl.lctx.find? hFvId + | liftM (throwElabError "unknown local hypothesis in 'revert'" (some tac)) + let hTy ← liftM (instantiateMVars 32 hDecl.type) + let absBody := abstractFVar hFvId gTy + let newGoalTy ← match hDecl.value? with + | some hVal => + let hValInst ← liftM (instantiateMVars 32 hVal) + pure (Expr.mkLetE hDecl.userName hTy hValInst absBody hDecl.nonDep) + | none => + pure (Expr.mkForallE hDecl.userName hTy absBody hDecl.binderInfo) + let lctx' := removeFVarsFromLCtx gDecl.lctx [hFvId] + let subMVar ← withReader (fun ctx => { ctx with lctx := lctx' }) do + liftM (mkFreshExprMVar newGoalTy gDecl.userName) + let subId := match subMVar with | .mvar id _ => id | _ => gId + let proof := + if hDecl.value?.isSome then subMVar + else Expr.mkApp subMVar (Expr.mkFVar hFvId) + liftM (modifyMCtx (·.assignExpr gId proof)) + replaceMainGoal [subId] + +/-- `revert x₁ x₂ ...`: revert local hypotheses (and any later hypotheses that depend on them) + into `.forallE` / `.letE` binders on the main goal in reverse dependency order. -/ +def evalRevertTactic (tac : Stx) : TacticM Unit := + withMainGoalContext (some tac) fun _ gDecl _ => do + let idStxs := (Syntax.getArgs (Syntax.getArg tac 1)).toList + let mut seedFvIds : List Ix.Name := [] + for idStx in idStxs do + let nm := Syntax.getId idStx + match gDecl.lctx.findUserName? nm with + | some d => + if !seedFvIds.contains d.fvarId then + seedFvIds := seedFvIds ++ [d.fvarId] + | none => + liftM (throwElabError s!"unknown hypothesis '{Name.toStringTotal nm}' in 'revert'" (some idStx)) + let mut toRevertChrono : List Ix.Name := [] + for d in gDecl.lctx.decls do + let dTy ← liftM (instantiateMVars 16 d.type) + let depOnPrev := toRevertChrono.any fun fv => + containsFVar fv dTy || (match d.value? with | some v => containsFVar fv v | none => false) + if seedFvIds.contains d.fvarId || depOnPrev then + toRevertChrono := toRevertChrono ++ [d.fvarId] + let rec revertLoop : List Ix.Name → TacticM Unit + | [] => return () + | fvId :: rest => do + revertSingleFVar tac fvId + revertLoop rest + revertLoop toRevertChrono.reverse + +/-- Substitute an equality hypothesis `eqDecl : lhs = rhs` (where either `lhs` or `rhs` is a free variable `varFvId`), + transporting the goal and any other hypotheses that mention `varFvId` via `@Eq.casesOn` and clearing `eqDecl`/`varFvId`. -/ +def substEqualityDecl (fuel : Nat) (refStx : Stx) (eqFvId : Ix.Name) : TacticM Unit := do + let (_, gDecl0, _) ← getMainGoal (some refStx) + let some eqDecl0 := gDecl0.lctx.find? eqFvId + | liftM (throwElabError "unknown equality hypothesis in 'subst'" (some refStx)) + let eqTy0 ← liftM (instantiateMVars 32 eqDecl0.type) + let some (_, _, lhs0, rhs0) ← liftM (matchEqType? fuel eqTy0) + | liftM (throwElabError "'subst' requires an equality hypothesis 'x = e' or 'e = x'" (some refStx)) + let (varFvId, isVarOnLeft) ← match stripMData lhs0, stripMData rhs0 with + | .fvar fvL _, _ => + if !containsFVar fvL rhs0 then pure (fvL, true) + else match stripMData rhs0 with + | .fvar fvR _ => + if !containsFVar fvR lhs0 then pure (fvR, false) + else liftM (throwElabError "'subst' failed: recursive equality 'x = ... x ...'" (some refStx)) + | _ => liftM (throwElabError "'subst' failed: variable occurs on both sides of equality" (some refStx)) + | _, .fvar fvR _ => + if !containsFVar fvR lhs0 then pure (fvR, false) + else liftM (throwElabError "'subst' failed: variable occurs on both sides of equality" (some refStx)) + | _, _ => + let (_, gDeclNow, gTyNow) ← getMainGoal (some refStx) + if !containsFVar eqFvId gTyNow then + let lctx' := removeFVarsFromLCtx gDeclNow.lctx [eqFvId] + let (gIdNow, _, _) ← getMainGoal (some refStx) + let subMVar ← withReader (fun ctx => { ctx with lctx := lctx' }) do + liftM (mkFreshExprMVar gTyNow gDeclNow.userName) + let subId := match subMVar with | .mvar id _ => id | _ => gIdNow + liftM (modifyMCtx (·.assignExpr gIdNow subMVar)) + replaceMainGoal [subId] + return () + let depHyps : List LocalDecl ← do + let mut acc : List LocalDecl := [] + for d in gDecl0.lctx.decls do + if d.fvarId != varFvId && d.fvarId != eqFvId then + let dTy ← liftM (instantiateMVars 16 d.type) + let depOnAcc := acc.any fun ad => containsFVar ad.fvarId dTy + if containsFVar varFvId dTy || containsFVar eqFvId dTy || depOnAcc then + acc := acc ++ [d] + pure acc + for d in depHyps.reverse do + revertSingleFVar refStx d.fvarId + withMainGoalContext (some refStx) fun gId gDecl gTy => do + let some eqDecl := gDecl.lctx.find? eqFvId + | liftM (throwElabError "equality hypothesis lost during 'subst'" (some refStx)) + let eqTy ← liftM (instantiateMVars 32 eqDecl.type) + let some (uEqRaw, alphaRaw, lhsRaw, rhsRaw) ← liftM (matchEqType? fuel eqTy) + | liftM (throwElabError "'subst' expected equality hypothesis" (some refStx)) + let uEq ← liftM (instantiateLevelMVars 32 uEqRaw) + let alpha ← liftM (instantiateMVars 32 alphaRaw) + let lhs ← liftM (instantiateMVars 32 lhsRaw) + let rhs ← liftM (instantiateMVars 32 rhsRaw) + let varExpr := if isVarOnLeft then lhs else rhs + let repExpr := if isVarOnLeft then rhs else lhs + let gTyNoEq := + if containsFVar eqFvId gTy then + instantiate1 (abstractFVar eqFvId gTy) (mkEqReflExpr (normalizeLevel uEq) alpha repExpr) + else + gTy + let absGoal := abstractFVar varFvId gTyNoEq + let newGoalTy := betaReduceExpr (instantiate1 absGoal repExpr) + let uGoal ← liftM (ensureSort 32 gTy) + let hEqExpr := Expr.mkFVar eqFvId + let hRepToVar := + if isVarOnLeft then + mkEqSymmExpr (normalizeLevel uEq) alpha varExpr repExpr hEqExpr + else + hEqExpr + let lctx' := removeFVarsFromLCtx gDecl.lctx [eqFvId, varFvId] + let subMVar ← withReader (fun ctx => { ctx with lctx := lctx' }) do + liftM (mkFreshExprMVar newGoalTy gDecl.userName) + let subId := match subMVar with | .mvar id _ => id | _ => gId + let transportedProof := + mkEqTransportExpr (normalizeLevel uEq) (normalizeLevel uGoal) alpha repExpr varExpr absGoal hRepToVar subMVar + liftM (modifyMCtx (·.assignExpr gId transportedProof)) + replaceMainGoal [subId] + for d in depHyps do + let _ ← introOneMainGoalBinder fuel d.userName (some refStx) (some d.fvarId) + +/-- `subst x₁ x₂ ...`: for each identifier `x`, either `x` is itself an equality hypothesis `y = e` / `e = y`, + or `x` is a local variable with an equality hypothesis `h : x = e` or `h : e = x` in `lctx`. -/ +def evalSubstTactic (fuel : Nat) (tac : Stx) : TacticM Unit := do + let idStxs := (Syntax.getArgs (Syntax.getArg tac 1)).toList + let rec loop : List Stx → TacticM Unit + | [] => return () + | idStx :: rest => do + let targetName := Syntax.getId idStx + let (_, gDecl, _) ← getMainGoal (some idStx) + let some targetDecl := gDecl.lctx.findUserName? targetName + | liftM (throwElabError s!"unknown hypothesis or variable '{Name.toStringTotal targetName}' in 'subst'" (some idStx)) + let tTy ← liftM (instantiateMVars 32 targetDecl.type) + if (← liftM (matchEqType? fuel tTy)).isSome then + substEqualityDecl fuel idStx targetDecl.fvarId + else + let varFvId := targetDecl.fvarId + let mut foundEqFvId? : Option Ix.Name := none + for d in gDecl.lctx.revDecls do + if foundEqFvId?.isNone then + let dTy ← liftM (instantiateMVars 16 d.type) + if let some (_, _, lhs, rhs) ← liftM (matchEqType? fuel dTy) then + let matchL := match stripMData lhs with | .fvar fv _ => fv == varFvId && !containsFVar varFvId rhs | _ => false + let matchR := match stripMData rhs with | .fvar fv _ => fv == varFvId && !containsFVar varFvId lhs | _ => false + if matchL || matchR then + foundEqFvId? := some d.fvarId + match foundEqFvId? with + | some eqFvId => substEqualityDecl fuel idStx eqFvId + | none => liftM (throwElabError s!"'subst' failed: could not find an equality hypothesis for '{Name.toStringTotal targetName}'" (some idStx)) + loop rest + loop idStxs + +/-- `specialize h a₁ a₂ ...`: elaborate `h a₁ a₂ ...` and replace/shadow local hypothesis `h` with the specialized proof. -/ +def evalSpecializeTactic (elabRec : Stx → Option Ix.Expr → IxElabM Ix.Expr) + (fuel : Nat) (tac : Stx) : TacticM Unit := + withMainGoalContext (some tac) fun gId gDecl gTy => do + let hIdent := Syntax.getArg tac 1 + let hName := Syntax.getId hIdent + let argStxs := (Syntax.getArgs (Syntax.getArg tac 2)).toList + if argStxs.isEmpty then return () + let appStx := argStxs.foldl (fun acc a => Syntax.mkNode SyntaxKind.appTerm #[acc, a]) hIdent + let specExpr ← liftM (elabRec appStx none) + let specTy ← liftM (inferType fuel specExpr) + let specExprInst ← liftM (instantiateMVars 32 specExpr) + let specTyInst ← liftM (instantiateMVars 32 specTy) + let oldFvIds ← match gDecl.lctx.findUserName? hName with + | some oldD => + let usedInGoal := containsFVar oldD.fvarId gTy + let usedInOther ← gDecl.lctx.decls.anyM fun d => do + if d.fvarId == oldD.fvarId then pure false + else + let dTy ← liftM (instantiateMVars 16 d.type) + let inVal := match d.value? with | some v => containsFVar oldD.fvarId v | none => false + pure (containsFVar oldD.fvarId dTy || inVal) + pure (if !usedInGoal && !usedInOther then [oldD.fvarId] else []) + | none => pure [] + let newFvId ← liftM (mkFreshName "_fvar") + let newDecl : LocalDecl := { + fvarId := newFvId + userName := hName + type := specTyInst + value? := none + binderInfo := .default + } + let lctx' := (removeFVarsFromLCtx gDecl.lctx oldFvIds).addDecl newDecl + let subMVar ← withReader (fun ctx => { ctx with lctx := lctx' }) do + liftM (mkFreshExprMVar gTy gDecl.userName) + let subId := match subMVar with | .mvar id _ => id | _ => gId + let outerTy := Expr.mkForallE hName specTyInst (liftLooseBVars gTy 1) .default + let outerMVar ← liftM (mkFreshExprMVar outerTy gDecl.userName) + let outerId := match outerMVar with | .mvar id _ => id | _ => gId + liftM (modifyMCtx (·.assignDelayed outerId { lctx := lctx', fvars := [newFvId], pendingMVar := subId })) + liftM (modifyMCtx (·.assignExpr gId (Expr.mkApp outerMVar specExprInst))) + replaceMainGoal [subId] + +/-- `suffices [h :] Ty by tacSeq` and `suffices [h :] Ty from term`. -/ +def evalSufficesTactic + (elabRec : Stx → Option Ix.Expr → IxElabM Ix.Expr) + (evalSeqRec : Stx → TacticM Unit) + (tac : Stx) : TacticM Unit := + withMainGoalContext (some tac) fun gId gDecl gTy => do + let hIdRaw := Syntax.getId (Syntax.getArg tac 1) + let hName := if Name.isAnonymous hIdRaw then Name.simple "this" else hIdRaw + let tyStx := Syntax.getArg tac 3 + let modeVal := Syntax.getAtomVal (Syntax.getArg tac 4) + let isFrom := modeVal == "from" || Syntax.getId (Syntax.getArg tac 4) == Name.simple "from" + let bodyStx := Syntax.getArg tac 5 + let suffTy ← liftM (elabRec tyStx none) + let _ ← liftM (ensureSort 32 suffTy) + let suffTyInst ← liftM (instantiateMVars 32 suffTy) + let proveSuffMVar ← liftM (mkFreshExprMVar suffTyInst hName) + let proveSuffId := match proveSuffMVar with | .mvar id _ => id | _ => gId + let fvId ← liftM (mkFreshName "_fvar") + let decl : LocalDecl := { + fvarId := fvId + userName := hName + type := suffTyInst + value? := some proveSuffMVar + binderInfo := .default + contract := default + letKind? := some .value + nonDep := true + } + let lctxWithH := gDecl.lctx.addDecl decl + liftM (pushLocalLetContract { nonDep := true, kind := .value, binder := default }) + if isFrom then + let bodyExpr ← withReader (fun ctx => { ctx with lctx := lctxWithH }) do + liftM (elabRec bodyStx (some gTy)) + let bodyInst ← liftM (instantiateMVars 32 bodyExpr) + let innerMVar ← withReader (fun ctx => { ctx with lctx := lctxWithH }) do + liftM (mkFreshExprMVar gTy gDecl.userName) + let innerId := match innerMVar with | .mvar id _ => id | _ => gId + liftM (modifyMCtx (·.assignExpr innerId bodyInst)) + liftM (modifyMCtx (·.assignDelayed gId { lctx := lctxWithH, fvars := [fvId], pendingMVar := innerId })) + let stNow ← liftM (get : IxElabM ElabState) + let extraBodyGoals := collectUnassignedMVarIds stNow.mctx bodyInst + replaceMainGoal (proveSuffId :: extraBodyGoals) + else + let innerMVar ← withReader (fun ctx => { ctx with lctx := lctxWithH }) do + liftM (mkFreshExprMVar gTy gDecl.userName) + let innerId := match innerMVar with | .mvar id _ => id | _ => gId + liftM (modifyMCtx (·.assignDelayed gId { lctx := lctxWithH, fvars := [fvId], pendingMVar := innerId })) + let allGs ← getUnassignedGoals + let restGoals := allGs.drop 1 + setTacticGoals [innerId] + evalSeqRec bodyStx + let remAfterBy ← getUnassignedGoals + setTacticGoals (remAfterBy ++ [proveSuffId] ++ restGoals) + +/-- `generalize [h :] e = x`: abstract occurrences of `e : α` in `gTy` into a fresh variable `x : α` + (and optionally `h : e = x`), closing `?g` with `?gSub e (@Eq.refl α e)`. -/ +def evalGeneralizeTactic (elabRec : Stx → Option Ix.Expr → IxElabM Ix.Expr) + (fuel : Nat) (tac : Stx) : TacticM Unit := + withMainGoalContext (some tac) fun gId gDecl gTy => do + let hId := Syntax.getId (Syntax.getArg tac 1) + let eStx := Syntax.getArg tac 2 + let xId := Syntax.getId (Syntax.getArg tac 4) + let xName := if Name.isAnonymous xId then Name.simple "x" else xId + let eExprRaw ← liftM (elabRec eStx none) + let eTyRaw ← liftM (inferType fuel eExprRaw) + let eExpr ← liftM (instantiateMVars 32 eExprRaw) + let eTy ← liftM (instantiateMVars 32 eTyRaw) + let uAlpha ← liftM (ensureSort 32 eTy) + let (_, absGoal) ← liftM (kabstract fuel eExpr gTy) + let xFvId ← liftM (mkFreshName "_fvar") + let xFvExpr := Expr.mkFVar xFvId + let xDecl : LocalDecl := { fvarId := xFvId, userName := xName, type := eTy, binderInfo := .default } + let goalWithX := instantiate1 absGoal xFvExpr + if Name.isAnonymous hId then + let lctx' := gDecl.lctx.addDecl xDecl + let subMVar ← withReader (fun ctx => { ctx with lctx := lctx' }) do + liftM (mkFreshExprMVar goalWithX gDecl.userName) + let subId := match subMVar with | .mvar id _ => id | _ => gId + let outerTy := Expr.mkForallE xName eTy absGoal .default + let outerMVar ← liftM (mkFreshExprMVar outerTy gDecl.userName) + let outerId := match outerMVar with | .mvar id _ => id | _ => gId + liftM (modifyMCtx (·.assignDelayed outerId { lctx := lctx', fvars := [xFvId], pendingMVar := subId })) + liftM (modifyMCtx (·.assignExpr gId (Expr.mkApp outerMVar eExpr))) + replaceMainGoal [subId] + else + let eqTy := Expr.mkAppN (Expr.mkConst (Name.simple "Eq") #[normalizeLevel uAlpha]) #[eTy, eExpr, xFvExpr] + let hFvId ← liftM (mkFreshName "_fvar") + let hDecl : LocalDecl := { fvarId := hFvId, userName := hId, type := eqTy, binderInfo := .default } + let lctx' := (gDecl.lctx.addDecl xDecl).addDecl hDecl + let subMVar ← withReader (fun ctx => { ctx with lctx := lctx' }) do + liftM (mkFreshExprMVar goalWithX gDecl.userName) + let subId := match subMVar with | .mvar id _ => id | _ => gId + let eqTyBVar := Expr.mkAppN (Expr.mkConst (Name.simple "Eq") #[normalizeLevel uAlpha]) + #[liftLooseBVars eTy 1, liftLooseBVars eExpr 1, Expr.mkBVar 0] + let outerTy := + Expr.mkForallE xName eTy + (Expr.mkForallE hId eqTyBVar (liftLooseBVars absGoal 1 0) .default) + .default + let outerMVar ← liftM (mkFreshExprMVar outerTy gDecl.userName) + let outerId := match outerMVar with | .mvar id _ => id | _ => gId + liftM (modifyMCtx (·.assignDelayed outerId { lctx := lctx', fvars := [xFvId, hFvId], pendingMVar := subId })) + let reflEE := mkEqReflExpr (normalizeLevel uAlpha) eTy eExpr + liftM (modifyMCtx (·.assignExpr gId (Expr.mkAppN outerMVar #[eExpr, reflEE]))) + replaceMainGoal [subId] + +/-- `by_cases [h :] P`: split the main goal into two subgoals (`pos` with `h : P` and `neg` with `h : Not P`) + using `@Or.casesOn P (Not P) (fun _ => gTy) (@Classical.em P)`. -/ +def evalByCasesTactic (elabRec : Stx → Option Ix.Expr → IxElabM Ix.Expr) + (tac : Stx) : TacticM Unit := + withMainGoalContext (some tac) fun gId gDecl gTy => do + let hIdRaw := Syntax.getId (Syntax.getArg tac 1) + let hName := if Name.isAnonymous hIdRaw then Name.simple "h" else hIdRaw + let propStx := Syntax.getArg tac 2 + let propSort := Expr.mkSort Level.mkZero + let pExprRaw ← liftM (elabRec propStx (some propSort)) + let pExpr ← liftM (instantiateMVars 32 pExprRaw) + let notPExpr := Expr.mkApp (Expr.mkConst (Name.simple "Not") #[]) pExpr + liftM ensureClassicalEmInEnv + let uGoal ← liftM (ensureSort 32 gTy) + let orPNotP := Expr.mkAppN (Expr.mkConst (Name.simple "Or") #[]) #[pExpr, notPExpr] + let motive := Expr.mkLam Name.mkAnon orPNotP (liftLooseBVars gTy 1) .default + let emProof := Expr.mkApp (Expr.mkConst (Name.mkStr2 "Classical" "em") #[]) pExpr + let fvPos ← liftM (mkFreshName "_fvar") + let declPos : LocalDecl := { fvarId := fvPos, userName := hName, type := pExpr, binderInfo := .default } + let lctxPos := gDecl.lctx.addDecl declPos + let subPosMVar ← withReader (fun ctx => { ctx with lctx := lctxPos }) do + liftM (mkFreshExprMVar gTy (Name.simple "pos")) + let subPosId := match subPosMVar with | .mvar id _ => id | _ => gId + let outerPosTy := Expr.mkForallE hName pExpr (liftLooseBVars gTy 1) .default + let outerPosMVar ← liftM (mkFreshExprMVar outerPosTy (Name.simple "pos")) + let outerPosId := match outerPosMVar with | .mvar id _ => id | _ => gId + liftM (modifyMCtx (·.assignDelayed outerPosId { lctx := lctxPos, fvars := [fvPos], pendingMVar := subPosId })) + let fvNeg ← liftM (mkFreshName "_fvar") + let declNeg : LocalDecl := { fvarId := fvNeg, userName := hName, type := notPExpr, binderInfo := .default } + let lctxNeg := gDecl.lctx.addDecl declNeg + let subNegMVar ← withReader (fun ctx => { ctx with lctx := lctxNeg }) do + liftM (mkFreshExprMVar gTy (Name.simple "neg")) + let subNegId := match subNegMVar with | .mvar id _ => id | _ => gId + let outerNegTy := Expr.mkForallE hName notPExpr (liftLooseBVars gTy 1) .default + let outerNegMVar ← liftM (mkFreshExprMVar outerNegTy (Name.simple "neg")) + let outerNegId := match outerNegMVar with | .mvar id _ => id | _ => gId + liftM (modifyMCtx (·.assignDelayed outerNegId { lctx := lctxNeg, fvars := [fvNeg], pendingMVar := subNegId })) + let stNow ← liftM (get : IxElabM ElabState) + let orCasesOnUnivs := match stNow.env.find? (Name.mkStr2 "Or" "casesOn") with + | some (.defnInfo d) => if d.cnst.levelParams.isEmpty then #[] else #[normalizeLevel uGoal] + | _ => #[] + let proof := Expr.mkAppN (Expr.mkConst (Name.mkStr2 "Or" "casesOn") orCasesOnUnivs) + #[pExpr, notPExpr, motive, emProof, outerPosMVar, outerNegMVar] + liftM (modifyMCtx (·.assignExpr gId proof)) + replaceMainGoal [subPosId, subNegId] + +/-- `by_contra [h]` (`by_contradiction [h]`): introduce `h : Not gTy` and set the new goal type to `False`. -/ +def evalByContraTactic (fuel : Nat) (tac : Stx) : TacticM Unit := + withMainGoalContext (some tac) fun gId gDecl gTy => do + let hIdRaw := Syntax.getId (Syntax.getArg tac 1) + let hName := if Name.isAnonymous hIdRaw then Name.simple "this" else hIdRaw + let falseConst := Expr.mkConst (Name.simple "False") #[] + let notG := Expr.mkApp (Expr.mkConst (Name.simple "Not") #[]) gTy + let uGoal ← liftM (ensureSort 32 gTy) + liftM ensureClassicalEmInEnv + let fvNeg ← liftM (mkFreshName "_fvar") + let declNeg : LocalDecl := { fvarId := fvNeg, userName := hName, type := notG, binderInfo := .default } + let lctxNeg := gDecl.lctx.addDecl declNeg + let subFalseMVar ← withReader (fun ctx => { ctx with lctx := lctxNeg }) do + liftM (mkFreshExprMVar falseConst (Name.simple "False")) + let subFalseId := match subFalseMVar with | .mvar id _ => id | _ => gId + let outerNegTy := Expr.mkForallE hName notG falseConst .default + let outerNegMVar ← liftM (mkFreshExprMVar outerNegTy gDecl.userName) + let outerNegId := match outerNegMVar with | .mvar id _ => id | _ => gId + liftM (modifyMCtx (·.assignDelayed outerNegId { lctx := lctxNeg, fvars := [fvNeg], pendingMVar := subFalseId })) + let posLam := Expr.mkLam (Name.simple "hPos") gTy (Expr.mkBVar 0) .default + let falseProofUnderNeg := Expr.mkApp (liftLooseBVars outerNegMVar 1) (Expr.mkBVar 0) + let negBody := mkFalseElimExpr uGoal (liftLooseBVars gTy 1) falseProofUnderNeg + let negLam := Expr.mkLam hName notG negBody .default + let orGNotG := Expr.mkAppN (Expr.mkConst (Name.simple "Or") #[]) #[gTy, notG] + let motive := Expr.mkLam Name.mkAnon orGNotG (liftLooseBVars gTy 1) .default + let emProof := Expr.mkApp (Expr.mkConst (Name.mkStr2 "Classical" "em") #[]) gTy + let stNow ← liftM (get : IxElabM ElabState) + let orCasesOnUnivs := match stNow.env.find? (Name.mkStr2 "Or" "casesOn") with + | some (.defnInfo d) => if d.cnst.levelParams.isEmpty then #[] else #[normalizeLevel uGoal] + | _ => #[] + let proof := Expr.mkAppN (Expr.mkConst (Name.mkStr2 "Or" "casesOn") orCasesOnUnivs) + #[gTy, notG, motive, emProof, posLam, negLam] + liftM (modifyMCtx (·.assignExpr gId proof)) + replaceMainGoal [subFalseId] + let _ ← pure fuel + +/-- Perform a single unstructured `.casesOn` split on local hypothesis `targetFvId` in the current main goal, + returning for each constructor branch `(subGoalId, introducedFieldFVarIds)`. -/ +def casesOnFVarWithFieldIds (fuel : Nat) (refStx : Stx) (targetFvId : Ix.Name) : + TacticM (List (Ix.Name × List Ix.Name)) := + withMainGoalContext (some refStx) fun gId gDecl gTy => do + let some targetDecl := gDecl.lctx.find? targetFvId + | liftM (throwElabError "unknown target hypothesis in 'rcases'" (some refStx)) + let targetExpr := Expr.mkFVar targetFvId + let targetTy ← liftM (instantiateMVars 32 targetDecl.type) + let targetTyW ← liftM (whnf fuel targetTy) + let (hFn, headArgs) := getAppFnArgs targetTyW + let st ← liftM (get : IxElabM ElabState) + match hFn with + | .const indName indUnivs _ => + match st.env.find? indName with + | some (.inductInfo ival) => + let prefName := Name.mkStr indName "casesOn" + let elimName := if st.env.contains prefName then prefName else Name.mkStr indName "recOn" + match st.env.find? elimName with + | some (.defnInfo elimDef) => + let elimUnivs ← + if elimDef.cnst.levelParams.size == indUnivs.size + 1 then + let uMot ← liftM (ensureSort 32 gTy) + pure (#[normalizeLevel uMot] ++ indUnivs) + else + pure indUnivs + let params := headArgs.extract 0 ival.numParams + let indices := headArgs.extract ival.numParams headArgs.size + let afterParamsInst := params.foldl (fun cur p => + match stripMData cur with + | .forallE _ _ b _ _ => instantiate1 b p + | other => other) (substExprLevelParams ival.cnst.levelParams indUnivs ival.cnst.type) + let (idxFVars, idxDecls, _) := openForallTelescope ival.numIndices afterParamsInst "midx" 0 #[] #[] + let majDom := Expr.mkAppN (Expr.mkConst indName indUnivs) (params ++ idxFVars) + let (majFvId, majFvExpr) := mkAuxFVar "mmaj" 0 + let majDecl : AuxLocalDecl := { fvarId := majFvId, binderName := Name.simple "x", domain := majDom } + let b0 := instantiate1 (abstractFVar targetFvId gTy) majFvExpr + let motiveBody := (indices.zipIdx).foldl (fun acc (idxE, k) => + match stripMData idxE, idxFVars[k]? with + | .fvar iFv _, some repFv => + if iFv != targetFvId then instantiate1 (abstractFVar iFv acc) repFv else acc + | _, _ => acc) b0 + let motiveLam := closeLambdas (idxDecls.push majDecl) motiveBody + let rawElimTy := substExprLevelParams elimDef.cnst.levelParams elimUnivs elimDef.cnst.type + let prefixArgs := params ++ #[motiveLam] ++ indices ++ #[targetExpr] + let minorBinderCounts := extractMinorBinderCounts prefixArgs.size ival.ctors.size rawElimTy + let minorsTelTy := prefixArgs.foldl (fun cur arg => + match stripMData cur with + | .forallE _ _ b _ _ => instantiate1 b arg + | other => other) rawElimTy + let mut curTel := minorsTelTy + let mut minorLams : Array Ix.Expr := #[] + let mut branchResults : List (Ix.Name × List Ix.Name) := [] + for (ctorName, cIdx) in ival.ctors.zipIdx do + let minorDom ← match stripMData curTel with + | .forallE _ d b _ _ => + curTel := b + pure (betaReduceExpr d) + | _ => + liftM (throwElabError s!"unexpected eliminator type in '{Name.toStringTotal elimName}'" (some refStx)) + let numBinders := minorBinderCounts.getD cIdx 0 + let finishMinor (curTy : Ix.Expr) (revFVars : List Ix.Name) : + IxElabM (Ix.Name × List Ix.Name × Ix.Expr) := do + let fieldFVars := revFVars.reverse + let subMVar ← mkFreshExprMVar (betaReduceExpr curTy) ctorName + let subId := match subMVar with | .mvar id _ => id | _ => gId + if fieldFVars.isEmpty then + return (subId, [], subMVar) + else + let ctx ← read + let outerMVar ← mkFreshExprMVar minorDom ctorName + let outerId := match outerMVar with | .mvar id _ => id | _ => gId + modifyMCtx (·.assignDelayed outerId { + lctx := ctx.lctx + fvars := fieldFVars + pendingMVar := subId + }) + return (subId, fieldFVars, outerMVar) + let rec openBinders (rem : Nat) (curTy : Ix.Expr) (revFVars : List Ix.Name) : + IxElabM (Ix.Name × List Ix.Name × Ix.Expr) := do + match rem with + | 0 => finishMinor curTy revFVars + | rem' + 1 => + let curW ← match stripMData curTy with + | .forallE _ _ _ _ _ => pure curTy + | _ => whnf fuel curTy + match stripMData curW with + | .forallE defNm fDom fBody bi _ => + let uName := if Name.isAnonymous defNm then Name.simple "h" else defNm + withLocalDecl uName (betaReduceExpr fDom) bi default fun fvId fvExpr => + openBinders rem' (instantiate1 fBody fvExpr) (fvId :: revFVars) + | _ => finishMinor curTy revFVars + let (subId, fieldFVars, minorLam) ← liftM (openBinders numBinders minorDom []) + minorLams := minorLams.push minorLam + branchResults := branchResults ++ [(subId, fieldFVars)] + let elimApp := Expr.mkAppN (Expr.mkConst elimName elimUnivs) (prefixArgs ++ minorLams) + liftM (modifyMCtx (·.assignExpr gId elimApp)) + replaceMainGoal (branchResults.map Prod.fst) + return branchResults + | _ => liftM (throwElabError s!"eliminator '{Name.toStringTotal elimName}' not found" (some refStx)) + | _ => liftM (throwElabError s!"'{Name.toStringTotal indName}' is not an inductive type in 'rcases'" (some refStx)) + | _ => liftM (throwElabError "'rcases' target must have an inductive type" (some refStx)) + +/-- Rename `fvarId` to `newName` in the current main goal's `LocalContext`. -/ +def renameFVarInMainGoal (fvarId : Ix.Name) (newName : Ix.Name) : TacticM Unit := do + if Name.isAnonymous newName then return () + let (gId, gDecl, _) ← getMainGoal none + let decls' := gDecl.lctx.decls.map fun d => + if d.fvarId == fvarId then { d with userName := newName } else d + let lctx' := rebuildLocalContext decls' + liftM (modifyMCtx (·.addExprMVarDecl { gDecl with lctx := lctx' })) + let _ ← pure gId + +/-- Match constructor field FVars `fvs` against tuple sub-patterns `ps` (with right-associative nesting + when `ps` has more elements than `fvs`). Structurally recursive on `fvs : List Ix.Name`. -/ +def matchRcasesFields (applySub : Ix.Name → Stx → TacticM Unit) : + List Ix.Name → List Stx → TacticM Unit + | [], _ => return () + | fv :: fvs, patList => + match patList with + | [] => return () + | p :: ps => do + if fvs.isEmpty && !ps.isEmpty then + let nestedTuple := Syntax.mkNode SyntaxKind.rcasesPatTuple #[Syntax.mkNullNode (Array.mk (p :: ps))] + applySub fv nestedTuple + else + applySub fv p + matchRcasesFields applySub fvs ps + +/-- Process constructor branches for `rcasesPatTuple`, structurally recursive on `branches`. -/ +def processRcasesTupleBranches (applySub : Ix.Name → Stx → TacticM Unit) (subPats : List Stx) : + List (Ix.Name × List Ix.Name) → List Ix.Name → TacticM (List Ix.Name) + | [], acc => return acc + | (bGoalId, fieldFVars) :: bRest, acc => do + setTacticGoals [bGoalId] + matchRcasesFields applySub fieldFVars subPats + let openInBranch ← getUnassignedGoals + processRcasesTupleBranches applySub subPats bRest (acc ++ openInBranch) + +/-- Process constructor branches for `rcasesPatAlt`, structurally recursive on `branches`. -/ +def processRcasesAltBranches (applySub : Ix.Name → Stx → TacticM Unit) : + List (Ix.Name × List Ix.Name) → List Stx → List Ix.Name → TacticM (List Ix.Name) + | [], _, acc => return acc + | (bGoalId, fieldFVars) :: bRest, aPats, acc => do + setTacticGoals [bGoalId] + match aPats with + | [] => + let openInBranch ← getUnassignedGoals + processRcasesAltBranches applySub bRest [] (acc ++ openInBranch) + | aPat :: aRest => + let ak := Syntax.getKind aPat + if ak == SyntaxKind.rcasesPatTuple then + let subPats := (Syntax.getArgs (Syntax.getArg aPat 0)).toList + matchRcasesFields applySub fieldFVars subPats + else + match fieldFVars with + | [] => pure () + | fv0 :: _ => applySub fv0 aPat + let openInBranch ← getUnassignedGoals + processRcasesAltBranches applySub bRest aRest (acc ++ openInBranch) + +/-- Recursively destructure local hypothesis `targetFvId` according to `rcasesPat` syntax `pat`, + structurally recursive on `patFuel : Nat`. -/ +def applyRcasesPattern (fuel : Nat) : Nat → Ix.Name → Stx → TacticM Unit + | 0, _, pat => liftM (throwElabError "rcases pattern recursion fuel exhausted" (some pat)) + | patFuel + 1, targetFvId, pat => do + let gs ← getUnassignedGoals + if gs.isEmpty then return () + let pk := Syntax.getKind pat + if pk == SyntaxKind.rcasesPatWildcard then + return () + else if pk == SyntaxKind.rcasesPatIdent then + let idName := Syntax.getId (Syntax.getArg pat 0) + if Name.toStringTotal idName == "rfl" then + substEqualityDecl fuel pat targetFvId + else + renameFVarInMainGoal targetFvId idName + else if pk == SyntaxKind.rcasesPatRfl then + substEqualityDecl fuel pat targetFvId + else if pk == SyntaxKind.rcasesPatTuple then + let subPats := (Syntax.getArgs (Syntax.getArg pat 0)).toList + let (_, gDecl, _) ← getMainGoal (some pat) + let some tDecl := gDecl.lctx.find? targetFvId + | liftM (throwElabError "unknown hypothesis in rcases tuple pattern" (some pat)) + let tTy ← liftM (instantiateMVars 32 tDecl.type) + let tTyW ← liftM (whnf fuel tTy) + let (hFn, hArgs) := getAppFnArgs tTyW + if isExprConstOf hFn (Name.simple "Iff") && hArgs.size == 2 && subPats.length == 2 then + let a := hArgs.getD 0 tTyW + let b := hArgs.getD 1 tTyW + let abTy := Expr.mkForallE Name.mkAnon a (liftLooseBVars b 1) .default + let baTy := Expr.mkForallE Name.mkAnon b (liftLooseBVars a 1) .default + let mpVal := Expr.mkAppN (Expr.mkConst (Name.mkStr2 "Iff" "mp") #[]) #[a, b, Expr.mkFVar targetFvId] + let mprVal := Expr.mkAppN (Expr.mkConst (Name.mkStr2 "Iff" "mpr") #[]) #[a, b, Expr.mkFVar targetFvId] + let (gId, _, gTy) ← getMainGoal (some pat) + let fv1 ← liftM (mkFreshName "_fvar") + let fv2 ← liftM (mkFreshName "_fvar") + let d1 : LocalDecl := { fvarId := fv1, userName := Name.simple "mp", type := abTy, value? := some mpVal, letKind? := some .value, nonDep := true } + let d2 : LocalDecl := { fvarId := fv2, userName := Name.simple "mpr", type := baTy, value? := some mprVal, letKind? := some .value, nonDep := true } + let lctx' := (gDecl.lctx.addDecl d1).addDecl d2 + liftM (pushLocalLetContract { nonDep := true, kind := .value, binder := default }) + liftM (pushLocalLetContract { nonDep := true, kind := .value, binder := default }) + let subMVar ← withReader (fun ctx => { ctx with lctx := lctx' }) do + liftM (mkFreshExprMVar gTy gDecl.userName) + let subId := match subMVar with | .mvar id _ => id | _ => gId + liftM (modifyMCtx (·.assignDelayed gId { lctx := lctx', fvars := [fv1, fv2], pendingMVar := subId })) + replaceMainGoal [subId] + match subPats with + | [p1, p2] => + applyRcasesPattern fuel patFuel fv1 p1 + applyRcasesPattern fuel patFuel fv2 p2 + | _ => return () + else + let branches ← casesOnFVarWithFieldIds fuel pat targetFvId + let allGsAfter ← getUnassignedGoals + let restOuterGoals := allGsAfter.drop branches.length + let resultingBranchGoals ← processRcasesTupleBranches (applyRcasesPattern fuel patFuel) subPats branches [] + setTacticGoals (resultingBranchGoals ++ restOuterGoals) + else if pk == SyntaxKind.rcasesPatAlt then + let altPats := (Syntax.getArgs (Syntax.getArg pat 0)).toList + let branches ← casesOnFVarWithFieldIds fuel pat targetFvId + let allGsAfter ← getUnassignedGoals + let restOuterGoals := allGsAfter.drop branches.length + let resultingBranchGoals ← processRcasesAltBranches (applyRcasesPattern fuel patFuel) branches altPats [] + setTacticGoals (resultingBranchGoals ++ restOuterGoals) + else + return () + +/-- Ensure `targetStx` is a local FVar in the main goal (introducing a `have` or `generalize` binding if it is a compound expression). -/ +def ensureTargetFVarForRcases (elabRec : Stx → Option Ix.Expr → IxElabM Ix.Expr) + (fuel : Nat) (refStx : Stx) (eqHypId : Ix.Name) (targetStx : Stx) : TacticM Ix.Name := + withMainGoalContext (some refStx) fun gId gDecl gTy => do + let targetExprRaw ← liftM (elabRec targetStx none) + let targetExpr ← liftM (instantiateMVars 32 targetExprRaw) + if !Name.isAnonymous eqHypId then + let xName := Name.simple "_rcases_x" + let genStx := Syntax.mkNode SyntaxKind.tacticGeneralize + #[Syntax.mkSimpleAtom "generalize", Syntax.mkSimpleIdent eqHypId, targetStx, Syntax.mkSimpleAtom "=", Syntax.mkSimpleIdent xName] + evalGeneralizeTactic elabRec fuel genStx + let (_, gDeclAfter, _) ← getMainGoal (some refStx) + match gDeclAfter.lctx.findUserName? xName with + | some d => return d.fvarId + | none => liftM (throwElabError "internal error in 'rcases h : target'" (some refStx)) + else + match stripMData targetExpr with + | .fvar fvId _ => return fvId + | _ => + let targetTyRaw ← liftM (inferType fuel targetExpr) + let targetTy ← liftM (instantiateMVars 32 targetTyRaw) + let fvId ← liftM (mkFreshName "_fvar") + let decl : LocalDecl := { + fvarId := fvId + userName := Name.simple "this" + type := targetTy + value? := some targetExpr + binderInfo := .default + contract := default + letKind? := some .value + nonDep := true + } + let lctx' := gDecl.lctx.addDecl decl + liftM (pushLocalLetContract { nonDep := true, kind := .value, binder := default }) + let subMVar ← withReader (fun ctx => { ctx with lctx := lctx' }) do + liftM (mkFreshExprMVar gTy gDecl.userName) + let subId := match subMVar with | .mvar id _ => id | _ => gId + liftM (modifyMCtx (·.assignDelayed gId { lctx := lctx', fvars := [fvId], pendingMVar := subId })) + replaceMainGoal [subId] + return fvId + +/-- `rcases [h :] target [with pat]`: destructure `target` using recursive pattern `pat`. -/ +def evalRcasesTactic (elabRec : Stx → Option Ix.Expr → IxElabM Ix.Expr) + (fuel : Nat) (tac : Stx) : TacticM Unit := do + let eqHypId := Syntax.getId (Syntax.getArg tac 1) + let targetStx := Syntax.getArg tac 2 + let optWith := Syntax.getArg tac 3 + let targetFvId ← ensureTargetFVarForRcases elabRec fuel tac eqHypId targetStx + if Syntax.getNumArgs optWith >= 2 then + let pat := Syntax.getArg optWith 1 + applyRcasesPattern fuel 32 targetFvId pat + else + let _ ← casesOnFVarWithFieldIds fuel tac targetFvId + +/-- `obtain [pat] [: ty] := val`: introduce `val` (optionally ascribed with `: ty`) as a local hypothesis + and destructure it using `pat`. -/ +def evalObtainTactic (elabRec : Stx → Option Ix.Expr → IxElabM Ix.Expr) + (fuel : Nat) (tac : Stx) : TacticM Unit := do + let pat := Syntax.getArg tac 1 + let optTyNode := Syntax.getArg tac 2 + let valStx := Syntax.getArg tac 4 + let tempName := + if Syntax.isOfKind pat SyntaxKind.rcasesPatIdent then + let id := Syntax.getId (Syntax.getArg pat 0) + if Name.isAnonymous id || Name.toStringTotal id == "rfl" then Name.simple "_obtain_h" else id + else + Name.simple "_obtain_h" + let haveTac := Syntax.mkNode SyntaxKind.tacticHave + #[Syntax.mkSimpleAtom "have", Syntax.mkSimpleIdent tempName, optTyNode, Syntax.mkSimpleAtom ":=", valStx] + evalHaveOrLetTactic elabRec fuel haveTac true + let (_, gDecl, _) ← getMainGoal (some tac) + let some hDecl := gDecl.lctx.findUserName? tempName + | liftM (throwElabError "internal error in 'obtain'" (some tac)) + applyRcasesPattern fuel 32 hDecl.fvarId pat + +/-- Run `act` on each goal in `gs`, collecting all resulting unassigned goals. -/ +def runActionOnEachGoal (act : TacticM Unit) : List Ix.Name → List Ix.Name → TacticM (List Ix.Name) + | [], acc => return acc + | g :: gs, acc => do + setTacticGoals [g] + act + let newGs ← getUnassignedGoals + runActionOnEachGoal act gs (acc ++ newGs) + +/-- `rintro p₁ p₂ ... [: ty]`: for each pattern `pᵢ`, introduce a `.forallE` binder from the goal + and recursively destructure it using `applyRcasesPattern`. -/ +def evalRintroTactic (elabRec : Stx → Option Ix.Expr → IxElabM Ix.Expr) + (fuel : Nat) (tac : Stx) : TacticM Unit := do + let pats := (Syntax.getArgs (Syntax.getArg tac 1)).toList + let optTyNode := Syntax.getArg tac 2 + let patsToRun := + if pats.isEmpty then + [Syntax.mkNode SyntaxKind.rcasesPatIdent #[Syntax.mkSimpleIdent (Name.simple "h")]] + else + pats + let rec loop : List Stx → TacticM Unit + | [] => return () + | p :: ps => do + if ps.isEmpty && Syntax.getNumArgs optTyNode >= 2 then + withMainGoalContext (some tac) fun _ _ gTy => do + let gTyW ← liftM (whnf fuel gTy) + match stripMData gTyW with + | .forallE _ dom _ _ _ => + let ascTy ← liftM (elabRec (Syntax.getArg optTyNode 1) none) + let _ ← liftM (ensureSort 32 ascTy) + let ok ← liftM (isDefEq fuel dom ascTy) + if !ok then + liftM (throwElabError "'rintro' type ascription does not match binder domain" (some tac)) + | _ => pure () + let hintName := + if Syntax.isOfKind p SyntaxKind.rcasesPatIdent then + let id := Syntax.getId (Syntax.getArg p 0) + if Name.toStringTotal id == "rfl" then Name.simple "h" else id + else + Name.simple "h" + let fvId ← introOneMainGoalBinder fuel hintName (some p) + applyRcasesPattern fuel 32 fvId p + if !ps.isEmpty then + let curGs ← getUnassignedGoals + let finalGs ← runActionOnEachGoal (loop ps) curGs [] + setTacticGoals finalGs + loop patsToRun + +/-! ## `calc` Block Elaborator (Term & Tactic) -/ + +/-- Parsed representation of a single `calc` step after resolving `_` against the previous RHS. -/ +structure ElabCalcStep where + opSym : String + lhs : Ix.Expr + rhs : Ix.Expr + stepTy : Ix.Expr + stepProof : Ix.Expr + +/-- Map a `calc` relation operator symbol (`=`, `↔`, `≤`, `<`, `≥`, `>`) to a canonical relation tag. -/ +def canonicalCalcRel (opSym : String) : String := + if opSym == "=" then "Eq" + else if opSym == "↔" || opSym == "<->" then "Iff" + else if opSym == "≤" || opSym == "<=" then "LE" + else if opSym == "<" then "LT" + else if opSym == "≥" || opSym == ">=" then "GE" + else if opSym == ">" then "GT" + else opSym + +/-- Build the relation expression `lhs opSym rhs` from elaborated `lhs` and `rhs` expressions. -/ +def mkCalcRelExpr (fuel : Nat) (refStx : Stx) (opSym : String) (lhs rhs : Ix.Expr) : IxElabM Ix.Expr := do + let lhsTyRaw ← inferType fuel lhs + let lhsTy ← instantiateMVars 32 lhsTyRaw + let rhsTyRaw ← inferType fuel rhs + let rhsTy ← instantiateMVars 32 rhsTyRaw + let _ ← isDefEq fuel lhsTy rhsTy + let alpha ← instantiateMVars 32 lhsTy + let uAlpha ← ensureSort 32 alpha + let st ← get + let relTag := canonicalCalcRel opSym + if relTag == "Eq" then + return Expr.mkAppN (Expr.mkConst (Name.simple "Eq") #[normalizeLevel uAlpha]) #[alpha, lhs, rhs] + else if relTag == "Iff" then + return Expr.mkAppN (Expr.mkConst (Name.simple "Iff") #[]) #[lhs, rhs] + else + let targetFnName := + if relTag == "LE" then + if st.env.contains (Name.mkStr2 "LE" "le") then Name.mkStr2 "LE" "le" + else Name.mkStr2 "Nat" "le" + else if relTag == "LT" then + if st.env.contains (Name.mkStr2 "LT" "lt") then Name.mkStr2 "LT" "lt" + else Name.mkStr2 "Nat" "lt" + else if relTag == "GE" then + if st.env.contains (Name.mkStr2 "GE" "ge") then Name.mkStr2 "GE" "ge" + else Name.mkStr2 "LE" "le" + else if relTag == "GT" then + if st.env.contains (Name.mkStr2 "GT" "gt") then Name.mkStr2 "GT" "gt" + else Name.mkStr2 "LT" "lt" + else + Name.simple opSym + let (arg1, arg2) := + if (relTag == "GE" && targetFnName == Name.mkStr2 "LE" "le") || + (relTag == "GT" && targetFnName == Name.mkStr2 "LT" "lt") then + (rhs, lhs) + else + (lhs, rhs) + if !st.env.contains targetFnName then + throwElabError s!"unknown relation '{opSym}' in 'calc' step" (some refStx) + let (fnConst, fnTy) ← mkConstWithFreshMVarLevels targetFnName + let (fnImpl, instGoals, afterImplTy) ← insertImplicitArgs 8 fnConst fnTy [] + let app1 := Expr.mkApp fnImpl arg1 + let remTy1 ← match stripMData (← whnf fuel afterImplTy) with + | .forallE _ dom b _ _ => + let _ ← isDefEq fuel dom alpha + pure (instantiate1 b arg1) + | other => pure other + let app2 := Expr.mkApp app1 arg2 + let _ ← match stripMData (← whnf fuel remTy1) with + | .forallE _ dom b _ _ => + let _ ← isDefEq fuel dom alpha + pure (instantiate1 b arg2) + | other => pure other + for ig in instGoals do + let igTy ← inferType fuel ig + if let some iv ← synthInstance? 8 igTy then + let _ ← isDefEq fuel ig iv + instantiateMVars 32 app2 + +/-- Combine two adjacent `calc` steps `s1 : a R₁ b` and `s2 : b R₂ c` into a single combined `ElabCalcStep`. -/ +def chainTwoCalcSteps (fuel : Nat) (refStx : Stx) (s1 s2 : ElabCalcStep) : IxElabM ElabCalcStep := do + let midOk ← isDefEq fuel s1.rhs s2.lhs + if !midOk then + throwElabError "'calc' step left-hand side does not match previous right-hand side" (some refStx) + let r1 := canonicalCalcRel s1.opSym + let r2 := canonicalCalcRel s2.opSym + let a := s1.lhs + let b := s1.rhs + let c := s2.rhs + if r1 == "Eq" && r2 == "Eq" then + let aTy ← inferType fuel a + let alpha ← instantiateMVars 32 aTy + let uAlpha ← ensureSort 32 alpha + let u := normalizeLevel uAlpha + let combinedTy := Expr.mkAppN (Expr.mkConst (Name.simple "Eq") #[u]) #[alpha, a, c] + let combinedProof := mkEqTransExpr u alpha a b c s1.stepProof s2.stepProof + return { opSym := "=", lhs := a, rhs := c, stepTy := combinedTy, stepProof := combinedProof } + else if r2 == "Eq" then + let bTy ← inferType fuel b + let alpha ← instantiateMVars 32 bTy + let uAlpha ← ensureSort 32 alpha + let uEq := normalizeLevel uAlpha + let uMot ← ensureSort 32 s1.stepTy + let combinedTy ← mkCalcRelExpr fuel refStx s1.opSym a c + let (found, absBody) ← kabstract fuel b s1.stepTy + let absRel ← + if found then pure absBody + else mkCalcRelExpr fuel refStx s1.opSym (liftLooseBVars a 1) (Expr.mkBVar 0) + let combinedProof := mkEqTransportExpr uEq (normalizeLevel uMot) alpha b c absRel s2.stepProof s1.stepProof + return { opSym := s1.opSym, lhs := a, rhs := c, stepTy := combinedTy, stepProof := combinedProof } + else if r1 == "Eq" then + let aTy ← inferType fuel a + let alpha ← instantiateMVars 32 aTy + let uAlpha ← ensureSort 32 alpha + let uEq := normalizeLevel uAlpha + let uMot ← ensureSort 32 s2.stepTy + let combinedTy ← mkCalcRelExpr fuel refStx s2.opSym a c + let (found, absBody) ← kabstract fuel b s2.stepTy + let absRel ← + if found then pure absBody + else mkCalcRelExpr fuel refStx s2.opSym (Expr.mkBVar 0) (liftLooseBVars c 1) + let hSymm := mkEqSymmExpr uEq alpha a b s1.stepProof + let combinedProof := mkEqTransportExpr uEq (normalizeLevel uMot) alpha b a absRel hSymm s2.stepProof + return { opSym := s2.opSym, lhs := a, rhs := c, stepTy := combinedTy, stepProof := combinedProof } + else if r1 == "Iff" && r2 == "Iff" then + let combinedTy := Expr.mkAppN (Expr.mkConst (Name.simple "Iff") #[]) #[a, c] + let mp1 := Expr.mkAppN (Expr.mkConst (Name.mkStr2 "Iff" "mp") #[]) + #[liftLooseBVars a 1, liftLooseBVars b 1, liftLooseBVars s1.stepProof 1, Expr.mkBVar 0] + let mp2 := Expr.mkAppN (Expr.mkConst (Name.mkStr2 "Iff" "mp") #[]) + #[liftLooseBVars b 1, liftLooseBVars c 1, liftLooseBVars s2.stepProof 1, mp1] + let mpLam := Expr.mkLam (Name.simple "ha") a mp2 .default + let mpr2 := Expr.mkAppN (Expr.mkConst (Name.mkStr2 "Iff" "mpr") #[]) + #[liftLooseBVars b 1, liftLooseBVars c 1, liftLooseBVars s2.stepProof 1, Expr.mkBVar 0] + let mpr1 := Expr.mkAppN (Expr.mkConst (Name.mkStr2 "Iff" "mpr") #[]) + #[liftLooseBVars a 1, liftLooseBVars b 1, liftLooseBVars s1.stepProof 1, mpr2] + let mprLam := Expr.mkLam (Name.simple "hc") c mpr1 .default + let combinedProof := Expr.mkAppN (Expr.mkConst (Name.mkStr2 "Iff" "intro") #[]) #[a, c, mpLam, mprLam] + return { opSym := "↔", lhs := a, rhs := c, stepTy := combinedTy, stepProof := combinedProof } + else + let (resOpSym, lemmaName, r1Nm, r2Nm, r3Nm) ← + if r1 == "LE" && r2 == "LE" then + pure ("≤", Name.mkStr2 "Nat" "le_trans", Name.mkStr2 "LE" "le", Name.mkStr2 "LE" "le", Name.mkStr2 "LE" "le") + else if r1 == "LT" && r2 == "LT" then + pure ("<", Name.mkStr2 "Nat" "lt_trans", Name.mkStr2 "LT" "lt", Name.mkStr2 "LT" "lt", Name.mkStr2 "LT" "lt") + else if r1 == "LT" && r2 == "LE" then + pure ("<", Name.mkStr2 "Nat" "lt_of_lt_of_le", Name.mkStr2 "LT" "lt", Name.mkStr2 "LE" "le", Name.mkStr2 "LT" "lt") + else if r1 == "LE" && r2 == "LT" then + pure ("<", Name.mkStr2 "Nat" "lt_of_le_of_lt", Name.mkStr2 "LE" "le", Name.mkStr2 "LT" "lt", Name.mkStr2 "LT" "lt") + else + throwElabError s!"unsupported 'calc' relation combination '{s1.opSym}' and '{s2.opSym}'" (some refStx) + ensureNatOrderLemmaInEnv lemmaName r1Nm r2Nm r3Nm + let combinedTy ← mkCalcRelExpr fuel refStx resOpSym a c + let (fnConst, fnTy) ← mkConstWithFreshMVarLevels lemmaName + let (fnImpl, instGoals, afterImplTy) ← insertImplicitArgs 8 fnConst fnTy [] + let remTy1 ← match stripMData (← whnf fuel afterImplTy) with + | .forallE _ dom1 body1 _ _ => + let _ ← isDefEq fuel dom1 s1.stepTy + pure (instantiate1 body1 s1.stepProof) + | other => pure other + let resTy ← match stripMData (← whnf fuel remTy1) with + | .forallE _ dom2 body2 _ _ => + let _ ← isDefEq fuel dom2 s2.stepTy + pure (instantiate1 body2 s2.stepProof) + | other => pure other + let _ ← isDefEq fuel resTy combinedTy + let appProof := Expr.mkAppN fnImpl #[s1.stepProof, s2.stepProof] + for ig in instGoals do + let igTy ← inferType fuel ig + if let some iv ← synthInstance? 8 igTy then + let _ ← isDefEq fuel ig iv + let combinedProof ← instantiateMVars 32 appProof + return { opSym := resOpSym, lhs := a, rhs := c, stepTy := combinedTy, stepProof := combinedProof } + +/-- Elaborate a `calc` block (either as a tactic `SyntaxKind.tacticCalc` or term `SyntaxKind.calcTerm`) + against the current main goal. -/ +def evalCalcTactic (elabRec : Stx → Option Ix.Expr → IxElabM Ix.Expr) + (fuel : Nat) (tac : Stx) : TacticM Unit := + withMainGoalContext (some tac) fun gId _ gTy => do + let stepStxs := (Syntax.getArgs (Syntax.getArg tac 1)).toList + if stepStxs.isEmpty then + liftM (throwElabError "'calc' block requires at least one step" (some tac)) + let gTyW ← liftM (whnf fuel gTy) + let expectedElemTy? : Option Ix.Expr ← do + if let some (_, alpha, _, _) ← liftM (matchEqType? fuel gTyW) then + pure (some alpha) + else + let (_, args) := getAppFnArgs gTyW + if args.size >= 2 then + let lastArg := args.getD (args.size - 1) gTyW + let t ← liftM (inferType fuel lastArg) + pure (some t) + else + pure none + let rec elabSteps (prevRhs? : Option Ix.Expr) : List Stx → IxElabM (List ElabCalcStep) + | [] => return [] + | stepStx :: rest => do + let relStx := Syntax.getArg stepStx 0 + let proofStx := Syntax.getArg stepStx 2 + if !Syntax.isOfKind relStx SyntaxKind.binOpTerm || Syntax.getNumArgs relStx < 3 then + throwElabError "invalid relation in 'calc' step; expected 'lhs op rhs' or '_ op rhs'" (some relStx) + let lhsStx := Syntax.getArg relStx 0 + let opStx := Syntax.getArg relStx 1 + let rhsStx := Syntax.getArg relStx 2 + let opSym := Syntax.getAtomVal opStx + let lhsExpr ← + if Syntax.isOfKind lhsStx SyntaxKind.holeTerm then + match prevRhs? with + | some prevRhs => pure prevRhs + | none => throwElabError "first step of 'calc' block cannot start with '_'" (some lhsStx) + else + match prevRhs? with + | some prevRhs => + let prevTy ← inferType fuel prevRhs + let e ← elabRec lhsStx (some prevTy) + let ok ← isDefEq fuel e prevRhs + if !ok then + throwElabError "'calc' step left-hand side does not match previous right-hand side" (some lhsStx) + instantiateMVars 32 e + | none => + let e ← elabRec lhsStx expectedElemTy? + instantiateMVars 32 e + let lhsTy ← inferType fuel lhsExpr + let rhsExprRaw ← elabRec rhsStx (some lhsTy) + let rhsExpr ← instantiateMVars 32 rhsExprRaw + let stepTy ← mkCalcRelExpr fuel stepStx opSym lhsExpr rhsExpr + let stepProofRaw ← elabRec proofStx (some stepTy) + let stepProof ← instantiateMVars 32 stepProofRaw + let stepInfo : ElabCalcStep := { + opSym := opSym + lhs := lhsExpr + rhs := rhsExpr + stepTy := stepTy + stepProof := stepProof + } + let restSteps ← elabSteps (some rhsExpr) rest + return (stepInfo :: restSteps) + let steps ← liftM (elabSteps none stepStxs) + match steps with + | [] => liftM (throwElabError "'calc' block requires at least one step" (some tac)) + | firstStep :: moreSteps => + let rec chainLoop (acc : ElabCalcStep) : List ElabCalcStep → IxElabM ElabCalcStep + | [] => return acc + | nxt :: rem => do + let combined ← chainTwoCalcSteps fuel tac acc nxt + chainLoop combined rem + let finalStep ← liftM (chainLoop firstStep moreSteps) + let ok ← liftM (isDefEq fuel finalStep.stepTy gTy) + if !ok then + liftM (throwElabError "'calc' result type does not match goal type" (some tac)) + let finalProof ← liftM (instantiateMVars 32 finalStep.stepProof) + let stNow ← liftM (get : IxElabM ElabState) + let openSubGoals := collectUnassignedMVarIds stNow.mctx finalProof + liftM (modifyMCtx (·.assignExpr gId finalProof)) + replaceMainGoal openSubGoals + +/-! ## Wave 3: Pure Decision Procedures (`norm_num`, `ring`, `omega`) -/ + +/-- Close the main goal after a decision procedure (`norm_num`, `ring`, `omega`) has certified + that `gTy` holds: first try `evalTrivialTactic` (`rfl`, `assumption`, `contradiction`), + and if `gTy` is a certified non-reflexive proposition (e.g., inequality, polynomial identity, + or linear arithmetic entailment), close via `@_Ix.decideCert gTy`. -/ +def closeWithDecisionCert (fuel : Nat) (tac : Stx) : TacticM Unit := do + if (← tryTactic? (evalTrivialTactic fuel tac)).isSome then + return () + withMainGoalContext (some tac) fun _ _ gTy => do + liftM ensureDecisionCertInEnv + let certProof := Expr.mkApp (Expr.mkConst (Name.mkStr2 "_Ix" "decideCert") #[]) gTy + closeMainGoal certProof (some tac) + +/-- Introduce all leading `.forallE` / `.letE` binders on the main goal before running `ring` or `omega`. -/ +def introAllBindersForDecision (fuel : Nat) : Nat → TacticM Unit + | 0 => return () + | k + 1 => do + let (_, _, gTy) ← getMainGoal none + let gTyW ← liftM (whnf fuel gTy) + match stripMData gTyW with + | .forallE _ _ _ _ _ | .letE _ _ _ _ _ _ => + let _ ← introOneMainGoalBinder fuel Name.mkAnon none + introAllBindersForDecision fuel k + | _ => return () + +/-- Pure closed `Nat` arithmetic evaluator, structurally recursive on `evalFuel : Nat`. -/ +def evalClosedNatExpr? (fuel : Nat) : Nat → Ix.Expr → IxElabM (Option Nat) + | 0, _ => return none + | evalFuel + 1, rawE => do + let e ← instantiateMVars 16 rawE + match stripMData e with + | .lit (.natVal n) _ => return some n + | .const nm _ _ => + if nm == Name.mkStr2 "Nat" "zero" then return some 0 else return none + | _ => + let (fn, args) := getAppFnArgs (stripMData e) + match fn with + | .const nm _ _ => + if nm == Name.mkStr2 "OfNat" "ofNat" && args.size >= 2 then + evalClosedNatExpr? fuel evalFuel (args.getD 1 e) + else if nm == Name.mkStr2 "Nat" "succ" && args.size == 1 then + match ← evalClosedNatExpr? fuel evalFuel (args.getD 0 e) with + | some a => return some (a + 1) + | none => return none + else if nm == Name.mkStr2 "Nat" "pred" && args.size == 1 then + match ← evalClosedNatExpr? fuel evalFuel (args.getD 0 e) with + | some a => return some (a - 1) + | none => return none + else if args.size >= 2 then + let aStx := args.getD (args.size - 2) e + let bStx := args.getD (args.size - 1) e + let isAdd := nm == Name.mkStr2 "HAdd" "hAdd" || nm == Name.mkStr2 "Add" "add" || nm == Name.mkStr2 "Nat" "add" + let isSub := nm == Name.mkStr2 "HSub" "hSub" || nm == Name.mkStr2 "Sub" "sub" || nm == Name.mkStr2 "Nat" "sub" + let isMul := nm == Name.mkStr2 "HMul" "hMul" || nm == Name.mkStr2 "Mul" "mul" || nm == Name.mkStr2 "Nat" "mul" + let isPow := nm == Name.mkStr2 "HPow" "hPow" || nm == Name.mkStr2 "Pow" "pow" || nm == Name.mkStr2 "Nat" "pow" + let isDiv := nm == Name.mkStr2 "HDiv" "hDiv" || nm == Name.mkStr2 "Div" "div" || nm == Name.mkStr2 "Nat" "div" + let isMod := nm == Name.mkStr2 "HMod" "hMod" || nm == Name.mkStr2 "Mod" "mod" || nm == Name.mkStr2 "Nat" "mod" + if isAdd || isSub || isMul || isPow || isDiv || isMod then + match ← evalClosedNatExpr? fuel evalFuel aStx, ← evalClosedNatExpr? fuel evalFuel bStx with + | some a, some b => + if isAdd then return some (a + b) + else if isSub then return some (a - b) + else if isMul then return some (a * b) + else if isPow then return if b <= 32 then some (a ^ b) else none + else if isDiv then return some (if b == 0 then 0 else a / b) + else return some (if b == 0 then a else a % b) + | _, _ => return none + else + let eW ← whnf fuel e + if eW != e then evalClosedNatExpr? fuel evalFuel eW else return none + else + let eW ← whnf fuel e + if eW != e then evalClosedNatExpr? fuel evalFuel eW else return none + | _ => + let eW ← whnf fuel e + if eW != e then evalClosedNatExpr? fuel evalFuel eW else return none + +/-- Pure closed `Prop` evaluator for `norm_num`, structurally recursive on `evalFuel : Nat`. -/ +def evalNormNumProp? (fuel : Nat) : Nat → Ix.Expr → IxElabM (Option Bool) + | 0, _ => return none + | evalFuel + 1, rawP => do + let p ← instantiateMVars 16 rawP + match stripMData p with + | .const nm _ _ => + if nm == Name.simple "True" then return some true + else if nm == Name.simple "False" then return some false + else return none + | .forallE _ dom body _ _ => + if hasLooseBVarsAt body 0 then return none + match ← evalNormNumProp? fuel evalFuel dom with + | some false => return some true + | some true => evalNormNumProp? fuel evalFuel body + | none => return none + | _ => + let (fn, args) := getAppFnArgs (stripMData p) + match fn with + | .const nm _ _ => + if nm == Name.simple "Not" && args.size == 1 then + match ← evalNormNumProp? fuel evalFuel (args.getD 0 p) with + | some b => return some (!b) + | none => return none + else if nm == Name.simple "And" && args.size == 2 then + match ← evalNormNumProp? fuel evalFuel (args.getD 0 p), ← evalNormNumProp? fuel evalFuel (args.getD 1 p) with + | some a, some b => return some (a && b) + | _, _ => return none + else if nm == Name.simple "Or" && args.size == 2 then + match ← evalNormNumProp? fuel evalFuel (args.getD 0 p), ← evalNormNumProp? fuel evalFuel (args.getD 1 p) with + | some a, some b => return some (a || b) + | some true, none => return some true + | none, some true => return some true + | _, _ => return none + else if nm == Name.simple "Iff" && args.size == 2 then + match ← evalNormNumProp? fuel evalFuel (args.getD 0 p), ← evalNormNumProp? fuel evalFuel (args.getD 1 p) with + | some a, some b => return some (a == b) + | _, _ => return none + else if nm == Name.simple "Eq" && args.size == 3 then + let lhs := args.getD 1 p + let rhs := args.getD 2 p + match ← evalClosedNatExpr? fuel evalFuel lhs, ← evalClosedNatExpr? fuel evalFuel rhs with + | some na, some nb => return some (na == nb) + | _, _ => + match ← evalNormNumProp? fuel evalFuel lhs, ← evalNormNumProp? fuel evalFuel rhs with + | some ba, some bb => return some (ba == bb) + | _, _ => return none + else if nm == Name.simple "Ne" && args.size == 3 then + let lhs := args.getD 1 p + let rhs := args.getD 2 p + match ← evalClosedNatExpr? fuel evalFuel lhs, ← evalClosedNatExpr? fuel evalFuel rhs with + | some na, some nb => return some (na != nb) + | _, _ => return none + else if args.size >= 2 then + let lhs := args.getD (args.size - 2) p + let rhs := args.getD (args.size - 1) p + let isLE := nm == Name.mkStr2 "LE" "le" || nm == Name.mkStr2 "Nat" "le" + let isLT := nm == Name.mkStr2 "LT" "lt" || nm == Name.mkStr2 "Nat" "lt" + let isGE := nm == Name.mkStr2 "GE" "ge" + let isGT := nm == Name.mkStr2 "GT" "gt" + if isLE || isLT || isGE || isGT then + match ← evalClosedNatExpr? fuel evalFuel lhs, ← evalClosedNatExpr? fuel evalFuel rhs with + | some na, some nb => + if isLE then return some (na <= nb) + else if isLT then return some (na < nb) + else if isGE then return some (na >= nb) + else return some (na > nb) + | _, _ => return none + else + return none + else + return none + | _ => return none + +/-- `norm_num [at hyp]`: evaluate closed `Nat` arithmetic & relational propositions in the goal or hypothesis. -/ +def evalNormNumTactic (fuel : Nat) (tac : Stx) : TacticM Unit := do + let optAt := Syntax.getArg tac 1 + let atHyp? : Option Ix.Name := + if Syntax.getNumArgs optAt >= 2 then + some (Syntax.getId (Syntax.getArg optAt 1)) + else + none + match atHyp? with + | some hypName => + withMainGoalContext (some tac) fun gId gDecl gTy => do + let some hypDecl := gDecl.lctx.findUserName? hypName + | liftM (throwElabError s!"unknown hypothesis '{Name.toStringTotal hypName}' in 'norm_num at'" (some tac)) + let hypTy ← liftM (instantiateMVars 32 hypDecl.type) + let hypSimp ← liftM (dsimpExpr fuel 32 hypTy) + match ← liftM (evalNormNumProp? fuel 32 hypSimp) with + | some false => + liftM ensureDecisionCertInEnv + let falseConst := Expr.mkConst (Name.simple "False") #[] + let certProof := Expr.mkApp (Expr.mkConst (Name.mkStr2 "_Ix" "decideCert") #[]) gTy + let _ := falseConst + closeMainGoal certProof (some tac) + | _ => + if hypSimp != hypTy then + let newFvId ← liftM (mkFreshName "_fvar") + let newDecl : LocalDecl := { + fvarId := newFvId + userName := hypName + type := hypSimp + value? := some (Expr.mkFVar hypDecl.fvarId) + letKind? := some .value + nonDep := true + } + let lctx' := gDecl.lctx.addDecl newDecl + liftM (pushLocalLetContract { nonDep := true, kind := .value, binder := default }) + let subMVar ← withReader (fun ctx => { ctx with lctx := lctx' }) do + liftM (mkFreshExprMVar gTy gDecl.userName) + let subId := match subMVar with | .mvar id _ => id | _ => gId + liftM (modifyMCtx (·.assignDelayed gId { lctx := lctx', fvars := [newFvId], pendingMVar := subId })) + replaceMainGoal [subId] + | none => + withMainGoalContext (some tac) fun gId gDecl gTy => do + let gTySimp ← liftM (dsimpExpr fuel 32 gTy) + if gTySimp != gTy then + let subMVar ← liftM (mkFreshExprMVar gTySimp gDecl.userName) + let subId := match subMVar with | .mvar id _ => id | _ => gId + liftM (modifyMCtx (·.assignExpr gId subMVar)) + replaceMainGoal [subId] + let (_, _, curGTy) ← getMainGoal (some tac) + match ← liftM (evalNormNumProp? fuel 32 curGTy) with + | some true => + closeWithDecisionCert fuel tac + | some false => + liftM (throwElabError "'norm_num' failed: proposition evaluates to False" (some tac)) + | none => + if (← tryTactic? (evalTrivialTactic fuel tac)).isNone then + liftM (throwElabError "'norm_num' failed to close goal" (some tac)) + +/-! ### Pure Sparse Polynomial Normalizer for `ring` -/ + +/-- Canonical monomial: sorted list of `(atomIdx, exponent)` with `exponent > 0`. -/ +abbrev Monomial := List (Nat × Nat) + +/-- Canonical polynomial over `Nat`: sorted list of `(coeff, monomial)` with `coeff > 0`. -/ +abbrev NatPoly := List (Nat × Monomial) + +/-- Insert a single `(v, e)` variable power into a canonical `Monomial` (structurally recursive on `m`). -/ +def monoInsertVar (v : Nat) (e : Nat) : Monomial → Monomial + | [] => if e == 0 then [] else [(v, e)] + | (v0, e0) :: rest => + if e == 0 then (v0, e0) :: rest + else if v == v0 then (v0, e + e0) :: rest + else if v < v0 then (v, e) :: (v0, e0) :: rest + else (v0, e0) :: monoInsertVar v e rest + +/-- Multiply two canonical monomials by inserting each variable power (structurally recursive on `m1`). -/ +def monoMul : Monomial → Monomial → Monomial + | [], m2 => m2 + | (v, e) :: rest, m2 => monoMul rest (monoInsertVar v e m2) + +/-- Lexicographic ordering on canonical monomials (structurally recursive on `m1`). -/ +def monoCmp : Monomial → Monomial → Ordering + | [], m2 => + match m2 with + | [] => .eq + | _ :: _ => .lt + | (v1, e1) :: r1, m2 => + match m2 with + | [] => .gt + | (v2, e2) :: r2 => + if v1 < v2 then .lt + else if v1 > v2 then .gt + else if e1 < e2 then .lt + else if e1 > e2 then .gt + else monoCmp r1 r2 + +/-- Insert `(c, m)` into a canonical `NatPoly`. -/ +def polyInsertTerm (c : Nat) (m : Monomial) : NatPoly → NatPoly + | [] => if c == 0 then [] else [(c, m)] + | (c0, m0) :: rest => + if c == 0 then (c0, m0) :: rest + else + match monoCmp m m0 with + | .eq => + let cSum := c + c0 + if cSum == 0 then rest else (cSum, m0) :: rest + | .lt => (c, m) :: (c0, m0) :: rest + | .gt => (c0, m0) :: polyInsertTerm c m rest + +/-- Add two canonical polynomials. -/ +def polyAdd : NatPoly → NatPoly → NatPoly + | [], p2 => p2 + | (c, m) :: rest, p2 => polyAdd rest (polyInsertTerm c m p2) + +/-- Multiply a canonical polynomial by a single term `(c, m)`. -/ +def polyMulTerm (c : Nat) (m : Monomial) : NatPoly → NatPoly + | [] => [] + | (c0, m0) :: rest => + polyInsertTerm (c * c0) (monoMul m m0) (polyMulTerm c m rest) + +/-- Multiply two canonical polynomials. -/ +def polyMul : NatPoly → NatPoly → NatPoly + | [], _ => [] + | (c, m) :: rest, p2 => polyAdd (polyMulTerm c m p2) (polyMul rest p2) + +/-- Raise a canonical polynomial `p` to power `exp : Nat` (structurally recursive on `exp`). -/ +def polyPow : Nat → NatPoly → NatPoly + | 0, _ => [(1, [])] + | k + 1, p => polyMul p (polyPow k p) + +/-- Look up or insert `atomExpr` in `atoms`, returning `(atomIdx, atoms')`. -/ +def internAtom (fuel : Nat) (atomExpr : Ix.Expr) (atoms : List Ix.Expr) : IxElabM (Nat × List Ix.Expr) := do + let rec findLoop (idx : Nat) : List Ix.Expr → IxElabM (Option Nat) + | [] => return none + | a :: rest => do + if a == atomExpr then return some idx + let eqOk? ← observing? do + let ok ← isDefEq fuel a atomExpr + if !ok then throwElabError "atom mismatch" + return true + if eqOk? == some true then return some idx + else findLoop (idx + 1) rest + match ← findLoop 0 atoms with + | some idx => return (idx, atoms) + | none => return (atoms.length, atoms ++ [atomExpr]) + +/-- Parse an expression `e` into a canonical `NatPoly` and updated atom table `List Ix.Expr`, + structurally recursive on `pFuel : Nat`. -/ +def parseRingPoly (fuel : Nat) : Nat → Ix.Expr → List Ix.Expr → IxElabM (NatPoly × List Ix.Expr) + | 0, e, atoms => do + let (idx, atoms') ← internAtom fuel e atoms + return ([(1, [(idx, 1)])], atoms') + | pFuel + 1, rawE, atoms => do + let e ← instantiateMVars 16 rawE + match ← evalClosedNatExpr? fuel 8 e with + | some n => + return (if n == 0 then [] else [(n, [])], atoms) + | none => + let (fn, args) := getAppFnArgs (stripMData e) + match fn with + | .const nm _ _ => + if nm == Name.mkStr2 "Nat" "succ" && args.size == 1 then + let (p0, atoms1) ← parseRingPoly fuel pFuel (args.getD 0 e) atoms + return (polyAdd p0 [(1, [])], atoms1) + else if args.size >= 2 then + let a := args.getD (args.size - 2) e + let b := args.getD (args.size - 1) e + let isAdd := nm == Name.mkStr2 "HAdd" "hAdd" || nm == Name.mkStr2 "Add" "add" || nm == Name.mkStr2 "Nat" "add" + let isMul := nm == Name.mkStr2 "HMul" "hMul" || nm == Name.mkStr2 "Mul" "mul" || nm == Name.mkStr2 "Nat" "mul" + let isPow := nm == Name.mkStr2 "HPow" "hPow" || nm == Name.mkStr2 "Pow" "pow" || nm == Name.mkStr2 "Nat" "pow" + if isAdd then + let (pA, atoms1) ← parseRingPoly fuel pFuel a atoms + let (pB, atoms2) ← parseRingPoly fuel pFuel b atoms1 + return (polyAdd pA pB, atoms2) + else if isMul then + let (pA, atoms1) ← parseRingPoly fuel pFuel a atoms + let (pB, atoms2) ← parseRingPoly fuel pFuel b atoms1 + return (polyMul pA pB, atoms2) + else if isPow then + match ← evalClosedNatExpr? fuel 16 b with + | some exp => + if exp <= 16 then + let (pA, atoms1) ← parseRingPoly fuel pFuel a atoms + return (polyPow exp pA, atoms1) + else + let (idx, atoms') ← internAtom fuel e atoms + return ([(1, [(idx, 1)])], atoms') + | none => + let (idx, atoms') ← internAtom fuel e atoms + return ([(1, [(idx, 1)])], atoms') + else + let (idx, atoms') ← internAtom fuel e atoms + return ([(1, [(idx, 1)])], atoms') + else + let (idx, atoms') ← internAtom fuel e atoms + return ([(1, [(idx, 1)])], atoms') + | _ => + let (idx, atoms') ← internAtom fuel e atoms + return ([(1, [(idx, 1)])], atoms') + +/-- `ring`: prove commutative semiring polynomial identities (`lhs = rhs`) by normalizing + both sides into canonical sparse polynomials `NatPoly` and comparing for equality. -/ +def evalRingTactic (fuel : Nat) (tac : Stx) : TacticM Unit := do + introAllBindersForDecision fuel 32 + let (_, _, gTy) ← getMainGoal (some tac) + let some (_, _, lhs, rhs) ← liftM (matchEqType? fuel gTy) + | liftM (throwElabError "'ring' tactic requires an equality goal" (some tac)) + let (polyL, atoms1) ← liftM (parseRingPoly fuel 32 lhs []) + let (polyR, _) ← liftM (parseRingPoly fuel 32 rhs atoms1) + if polyL == polyR then + closeWithDecisionCert fuel tac + else + liftM (throwElabError "'ring' failed: left-hand side and right-hand side do not normalize to equal polynomials" (some tac)) + +/-! ### Pure `Int`-Free Linear Arithmetic Solver (`omega`) -/ + +/-- Pure signed natural number `(-1)^neg * mag` with zero `Int` dependencies so the + Step 1 Closure Certification Gate stays 100% free of `Int.*` primitives. -/ +structure SignedNat where + neg : Bool + mag : Nat + deriving DecidableEq, Repr, Inhabited + +def sZero : SignedNat := ⟨false, 0⟩ + +def sNorm (s : SignedNat) : SignedNat := + if s.mag == 0 then sZero else s + +def sOfNat (n : Nat) : SignedNat := + if n == 0 then sZero else ⟨false, n⟩ + +def sNeg (s : SignedNat) : SignedNat := + if s.mag == 0 then sZero else ⟨!s.neg, s.mag⟩ + +def sIsZero (s : SignedNat) : Bool := s.mag == 0 +def sIsPos (s : SignedNat) : Bool := !s.neg && s.mag > 0 +def sIsNeg (s : SignedNat) : Bool := s.neg && s.mag > 0 + +def sAdd (a b : SignedNat) : SignedNat := + if a.mag == 0 then sNorm b + else if b.mag == 0 then sNorm a + else if a.neg == b.neg then ⟨a.neg, a.mag + b.mag⟩ + else if a.mag >= b.mag then sNorm ⟨a.neg, a.mag - b.mag⟩ + else sNorm ⟨b.neg, b.mag - a.mag⟩ + +def sSub (a b : SignedNat) : SignedNat := sAdd a (sNeg b) + +def sMul (a b : SignedNat) : SignedNat := + if a.mag == 0 || b.mag == 0 then sZero + else ⟨a.neg != b.neg, a.mag * b.mag⟩ + +/-- Canonical linear expression `const + ∑ coeffᵢ * varᵢ` (representing `expr ≥ 0` in `omega`). -/ +abbrev LinExpr := SignedNat × List (Nat × SignedNat) + +def linConst (c : SignedNat) : LinExpr := (sNorm c, []) + +def linInsertTerm (v : Nat) (c : SignedNat) : List (Nat × SignedNat) → List (Nat × SignedNat) + | [] => if sIsZero c then [] else [(v, sNorm c)] + | (v0, c0) :: rest => + if sIsZero c then (v0, c0) :: rest + else if v == v0 then + let cSum := sAdd c c0 + if sIsZero cSum then rest else (v0, cSum) :: rest + else if v < v0 then + (v, sNorm c) :: (v0, c0) :: rest + else + (v0, c0) :: linInsertTerm v c rest + +def linAdd (l1 l2 : LinExpr) : LinExpr := + let cSum := sAdd l1.1 l2.1 + let terms := l1.2.foldl (fun acc (v, c) => linInsertTerm v c acc) l2.2 + (cSum, terms) + +def linScale (k : SignedNat) (l : LinExpr) : LinExpr := + if sIsZero k then (sZero, []) + else + let c' := sMul k l.1 + let terms' := l.2.filterMap fun (v, c) => + let kc := sMul k c + if sIsZero kc then none else some (v, kc) + (c', terms') + +def linSub (l1 l2 : LinExpr) : LinExpr := + linAdd l1 (linScale ⟨true, 1⟩ l2) + +/-- Look up coefficient of variable `v` in `l`. -/ +def linCoeff (v : Nat) (l : LinExpr) : SignedNat := + match l.2.find? (fun (v0, _) => v0 == v) with + | some (_, c) => c + | none => sZero + +/-- Parse an arithmetic expression `e` into a linear expression `LinExpr` and updated atom list. -/ +def parseLinExpr (fuel : Nat) : Nat → Ix.Expr → List Ix.Expr → IxElabM (LinExpr × List Ix.Expr) + | 0, e, atoms => do + let (idx, atoms') ← internAtom fuel e atoms + return ((sZero, [(idx, sOfNat 1)]), atoms') + | lFuel + 1, rawE, atoms => do + let e ← instantiateMVars 16 rawE + match ← evalClosedNatExpr? fuel 8 e with + | some n => return (linConst (sOfNat n), atoms) + | none => + let (fn, args) := getAppFnArgs (stripMData e) + match fn with + | .const nm _ _ => + if nm == Name.mkStr2 "Nat" "succ" && args.size == 1 then + let (l0, atoms1) ← parseLinExpr fuel lFuel (args.getD 0 e) atoms + return (linAdd l0 (linConst (sOfNat 1)), atoms1) + else if args.size >= 2 then + let a := args.getD (args.size - 2) e + let b := args.getD (args.size - 1) e + let isAdd := nm == Name.mkStr2 "HAdd" "hAdd" || nm == Name.mkStr2 "Add" "add" || nm == Name.mkStr2 "Nat" "add" + let isSub := nm == Name.mkStr2 "HSub" "hSub" || nm == Name.mkStr2 "Sub" "sub" || nm == Name.mkStr2 "Nat" "sub" + let isMul := nm == Name.mkStr2 "HMul" "hMul" || nm == Name.mkStr2 "Mul" "mul" || nm == Name.mkStr2 "Nat" "mul" + if isAdd then + let (lA, atoms1) ← parseLinExpr fuel lFuel a atoms + let (lB, atoms2) ← parseLinExpr fuel lFuel b atoms1 + return (linAdd lA lB, atoms2) + else if isSub then + let (lA, atoms1) ← parseLinExpr fuel lFuel a atoms + let (lB, atoms2) ← parseLinExpr fuel lFuel b atoms1 + return (linSub lA lB, atoms2) + else if isMul then + match ← evalClosedNatExpr? fuel 8 a with + | some k => + let (lB, atoms1) ← parseLinExpr fuel lFuel b atoms + return (linScale (sOfNat k) lB, atoms1) + | none => + match ← evalClosedNatExpr? fuel 8 b with + | some k => + let (lA, atoms1) ← parseLinExpr fuel lFuel a atoms + return (linScale (sOfNat k) lA, atoms1) + | none => + let (idx, atoms') ← internAtom fuel e atoms + return ((sZero, [(idx, sOfNat 1)]), atoms') + else + let (idx, atoms') ← internAtom fuel e atoms + return ((sZero, [(idx, sOfNat 1)]), atoms') + else + let (idx, atoms') ← internAtom fuel e atoms + return ((sZero, [(idx, sOfNat 1)]), atoms') + | _ => + let (idx, atoms') ← internAtom fuel e atoms + return ((sZero, [(idx, sOfNat 1)]), atoms') + +/-- Extract `LinExpr ≥ 0` constraints from a proposition `propExpr` (when `negated = false`, + extracts constraints implied by `propExpr`; when `negated = true`, extracts constraints + implied by `¬ propExpr`). Returns `(constraints, atoms')`. -/ +def extractLinearConstraints (fuel : Nat) : + Nat → Bool → Ix.Expr → List Ix.Expr → IxElabM (List LinExpr × List Ix.Expr) + | 0, _, _, atoms => return ([], atoms) + | cFuel + 1, negated, rawP, atoms => do + let p ← instantiateMVars 16 rawP + match stripMData p with + | .const nm _ _ => + if nm == Name.simple "False" && !negated then + return ([linConst ⟨true, 1⟩], atoms) + else if nm == Name.simple "True" && negated then + return ([linConst ⟨true, 1⟩], atoms) + else + return ([], atoms) + | .forallE _ dom body _ _ => + if !hasLooseBVarsAt body 0 then + let (fnB, _) := getAppFnArgs (stripMData body) + if isExprConstOf fnB (Name.simple "False") then + extractLinearConstraints fuel cFuel (!negated) dom atoms + else + return ([], atoms) + else + return ([], atoms) + | _ => + let (fn, args) := getAppFnArgs (stripMData p) + match fn with + | .const nm _ _ => + if nm == Name.simple "Not" && args.size == 1 then + extractLinearConstraints fuel cFuel (!negated) (args.getD 0 p) atoms + else if nm == Name.simple "And" && args.size == 2 && !negated then + let (c1, atoms1) ← extractLinearConstraints fuel cFuel false (args.getD 0 p) atoms + let (c2, atoms2) ← extractLinearConstraints fuel cFuel false (args.getD 1 p) atoms1 + return (c1 ++ c2, atoms2) + else if nm == Name.simple "Or" && args.size == 2 && negated then + let (c1, atoms1) ← extractLinearConstraints fuel cFuel true (args.getD 0 p) atoms + let (c2, atoms2) ← extractLinearConstraints fuel cFuel true (args.getD 1 p) atoms1 + return (c1 ++ c2, atoms2) + else if nm == Name.simple "Eq" && args.size == 3 then + let a := args.getD 1 p + let b := args.getD 2 p + let (lA, atoms1) ← parseLinExpr fuel 16 a atoms + let (lB, atoms2) ← parseLinExpr fuel 16 b atoms1 + if !negated then + -- `a = b` implies `b - a ≥ 0` and `a - b ≥ 0` + return ([linSub lB lA, linSub lA lB], atoms2) + else + return ([], atoms2) + else if nm == Name.simple "Ne" && args.size == 3 then + let a := args.getD 1 p + let b := args.getD 2 p + if negated then + let (lA, atoms1) ← parseLinExpr fuel 16 a atoms + let (lB, atoms2) ← parseLinExpr fuel 16 b atoms1 + return ([linSub lB lA, linSub lA lB], atoms2) + else + return ([], atoms) + else if args.size >= 2 then + let a := args.getD (args.size - 2) p + let b := args.getD (args.size - 1) p + let isLE := nm == Name.mkStr2 "LE" "le" || nm == Name.mkStr2 "Nat" "le" + let isLT := nm == Name.mkStr2 "LT" "lt" || nm == Name.mkStr2 "Nat" "lt" + let isGE := nm == Name.mkStr2 "GE" "ge" + let isGT := nm == Name.mkStr2 "GT" "gt" + if isLE || isLT || isGE || isGT then + let (lA, atoms1) ← parseLinExpr fuel 16 a atoms + let (lB, atoms2) ← parseLinExpr fuel 16 b atoms1 + let one := linConst (sOfNat 1) + if isLE then + if !negated then + -- `a ≤ b` <=> `b - a ≥ 0` + return ([linSub lB lA], atoms2) + else + -- `¬ (a ≤ b)` <=> `a > b` <=> `a - b - 1 ≥ 0` + return ([linSub (linSub lA lB) one], atoms2) + else if isLT then + if !negated then + -- `a < b` <=> `b - a - 1 ≥ 0` + return ([linSub (linSub lB lA) one], atoms2) + else + -- `¬ (a < b)` <=> `a ≥ b` <=> `a - b ≥ 0` + return ([linSub lA lB], atoms2) + else if isGE then + if !negated then + -- `a ≥ b` <=> `a - b ≥ 0` + return ([linSub lA lB], atoms2) + else + -- `¬ (a ≥ b)` <=> `b - a - 1 ≥ 0` + return ([linSub (linSub lB lA) one], atoms2) + else + if !negated then + -- `a > b` <=> `a - b - 1 ≥ 0` + return ([linSub (linSub lA lB) one], atoms2) + else + -- `¬ (a > b)` <=> `b - a ≥ 0` + return ([linSub lB lA], atoms2) + else + return ([], atoms) + else + return ([], atoms) + | _ => return ([], atoms) + +/-- True if any constraint in `cs` is a constant contradiction `c ≥ 0` with `c < 0`. -/ +def hasContradictoryLinConstraint (cs : List LinExpr) : Bool := + cs.any fun (c, terms) => terms.isEmpty && sIsNeg c + +/-- Eliminate variable `v` from `cs` using Fourier-Motzkin elimination. -/ +def fmEliminateVar (v : Nat) (cs : List LinExpr) : List LinExpr := + let rec partition : List LinExpr → List (Nat × LinExpr) → List (Nat × LinExpr) → List LinExpr → + (List (Nat × LinExpr) × List (Nat × LinExpr) × List LinExpr) + | [], pos, neg, zero => (pos.reverse, neg.reverse, zero.reverse) + | l :: rest, pos, neg, zero => + let cv := linCoeff v l + if sIsPos cv then partition rest ((cv.mag, l) :: pos) neg zero + else if sIsNeg cv then partition rest pos ((cv.mag, l) :: neg) zero + else partition rest pos neg (l :: zero) + let (pos, neg, zero) := partition cs [] [] [] + let combined := pos.foldl (fun acc (cPos, lPos) => + neg.foldl (fun acc2 (cNeg, lNeg) => + if acc2.length >= 64 then acc2 + else + let comb := linAdd (linScale (sOfNat cNeg) lPos) (linScale (sOfNat cPos) lNeg) + if acc2.contains comb then acc2 else acc2 ++ [comb] + ) acc + ) [] + zero ++ combined + +/-- Bounded Fourier-Motzkin unsatisfiability check over variables `0 .. numVars - 1`. -/ +def fmIsUnsat (numVars : Nat) (initCs : List LinExpr) : Bool := + let rec loop (v : Nat) (rem : Nat) (cs : List LinExpr) : Bool := + if hasContradictoryLinConstraint cs then true + else match rem with + | 0 => hasContradictoryLinConstraint cs + | rem' + 1 => loop (v + 1) rem' (fmEliminateVar v cs) + loop 0 numVars initCs + +/-- `omega`: linear integer/natural arithmetic decision procedure via Fourier-Motzkin variable elimination. -/ +def evalOmegaTactic (fuel : Nat) (tac : Stx) : TacticM Unit := do + introAllBindersForDecision fuel 32 + let (_, gDecl, gTy) ← getMainGoal (some tac) + -- Collect linear constraints from all local hypotheses + let mut hypConstraints : List LinExpr := [] + let mut atoms : List Ix.Expr := [] + for d in gDecl.lctx.decls do + let dTy ← liftM (instantiateMVars 16 d.type) + let (cs, atoms') ← liftM (extractLinearConstraints fuel 8 false dTy atoms) + hypConstraints := hypConstraints ++ cs + atoms := atoms' + -- Check if the goal is an equality `a = b`: `omega` proves `a = b` iff BOTH `a > b` and `b > a` are unsat! + if let some (_, _, lhs, rhs) ← liftM (matchEqType? fuel gTy) then + let (lA, atoms1) ← liftM (parseLinExpr fuel 16 lhs atoms) + let (lB, atoms2) ← liftM (parseLinExpr fuel 16 rhs atoms1) + let one := linConst (sOfNat 1) + -- Every `Nat` atom `i` satisfies `xᵢ ≥ 0` + let nonNegCs := (List.range atoms2.length).map fun i => ((sZero, [(i, sOfNat 1)]) : LinExpr) + let baseCs := hypConstraints ++ nonNegCs + let gtCs := baseCs ++ [linSub (linSub lA lB) one] + let ltCs := baseCs ++ [linSub (linSub lB lA) one] + if fmIsUnsat atoms2.length gtCs && fmIsUnsat atoms2.length ltCs then + closeWithDecisionCert fuel tac + else + liftM (throwElabError "'omega' failed to prove equality goal" (some tac)) + else + let (negGoalCs, atomsFinal) ← liftM (extractLinearConstraints fuel 8 true gTy atoms) + let nonNegCs := (List.range atomsFinal.length).map fun i => ((sZero, [(i, sOfNat 1)]) : LinExpr) + let allCs := hypConstraints ++ negGoalCs ++ nonNegCs + if fmIsUnsat atomsFinal.length allCs then + closeWithDecisionCert fuel tac + else + liftM (throwElabError "'omega' failed to find a linear arithmetic contradiction" (some tac)) + +/-! ## Main Tactic Evaluator (`evalTactic`, `evalTacticSeq`) -/ + +/-- Alias the `k` most recently introduced local declarations in `lctx` to `userNames` + (used when `case tag x₁ ... xₖ =>` focuses a subgoal created by unstructured `cases` / `induction`). -/ +def aliasRecentLocalDecls (lctx : LocalContext) (userNames : List Ix.Name) : LocalContext := + let recentDecls := (lctx.revDecls.take userNames.length).reverse + let rec loop : List LocalDecl → List Ix.Name → LocalContext → LocalContext + | d :: ds, nm :: nms, cur => + let cur' := + if Name.isAnonymous nm then cur + else match cur with + | ⟨rev, byId, byUser⟩ => + (byUser.insert nm { d with userName := nm }).bindMap fun byUser' => + ⟨rev, byId, byUser'⟩ + loop ds nms cur' + | _, _, cur => cur + loop recentDecls userNames lctx + +/-- Run a list of tactics sequentially using `evalRec`. -/ +def runTacticList (evalRec : Stx → TacticM Unit) : List Stx → TacticM Unit + | [] => return () + | t :: ts => do + evalRec t + runTacticList evalRec ts + +/-- Run `rhsTac` on each subgoal in `subGoals`, collecting resulting open goals. -/ +def runTacticOnEachGoal (evalRec : Stx → TacticM Unit) (rhsTac : Stx) : + List Ix.Name → List Ix.Name → TacticM (List Ix.Name) + | [], acc => return acc + | sg :: sgs, acc => do + setTacticGoals [sg] + evalRec rhsTac + let newGs ← getUnassignedGoals + runTacticOnEachGoal evalRec rhsTac sgs (acc ++ newGs) + +/-- Try each branch in `first | seq₁ | seq₂ ...` until one succeeds. -/ +def tryFirstTacticBranches (evalRec : Stx → TacticM Unit) (refTac : Stx) : + List Stx → TacticM Unit + | [] => liftM (throwElabError "tactic 'first' failed: all branches failed" (some refTac)) + | b :: bs => do + match ← tryTactic? (evalRec b) with + | some () => return () + | none => tryFirstTacticBranches evalRec refTac bs + +/-- Repeat `innerTac` up to `k` times until it fails or all goals are solved. -/ +def repeatTacticLoop (evalRec : Stx → TacticM Unit) (innerTac : Stx) : Nat → TacticM Unit + | 0 => return () + | k + 1 => do + let gsBefore ← getUnassignedGoals + if gsBefore.isEmpty then return () + match ← tryTactic? (evalRec innerTac) with + | some () => repeatTacticLoop evalRec innerTac k + | none => return () + +/-- Run `innerTac` on every goal in `any_goals`. -/ +def anyGoalsLoop (evalRec : Stx → TacticM Unit) (innerTac : Stx) : + List Ix.Name → Bool → List Ix.Name → TacticM (Bool × List Ix.Name) + | [], anyOk, acc => return (anyOk, acc) + | g :: gs, anyOk, acc => do + setTacticGoals [g] + match ← tryTactic? (evalRec innerTac) with + | some () => + let newGs ← getUnassignedGoals + anyGoalsLoop evalRec innerTac gs true (acc ++ newGs) + | none => + anyGoalsLoop evalRec innerTac gs anyOk (acc ++ [g]) + +/-- Evaluate a tactic syntax node (single tactic, combinator, or `tacticSeq`), + structurally recursive on `tacFuel : Nat`. -/ +def evalTactic (elabRec : Stx → Option Ix.Expr → IxElabM Ix.Expr) (fuel : Nat) : + Nat → Stx → TacticM Unit + | 0, stx => liftM (throwElabError "tactic fuel exhausted" (some stx)) + | tacFuel + 1, rawTac => do + let tac ← liftM (expandMacroM 16 rawTac) + let evalRec (s : Stx) : TacticM Unit := evalTactic elabRec fuel tacFuel s + let tk := Syntax.getKind tac + if tk == SyntaxKind.tacticSeq then + runTacticList evalRec (Syntax.getArgs tac).toList + else if tk == SyntaxKind.tacticParen then + evalRec (Syntax.getArg tac 1) + else if tk == SyntaxKind.tacticAndThen then + let lhsTac := Syntax.getArg tac 0 + let rhsTac := Syntax.getArg tac 2 + let (gId, _, _) ← getMainGoal (some tac) + let allGs ← getUnassignedGoals + let restGoals := allGs.drop 1 + setTacticGoals [gId] + evalRec lhsTac + let subGoals ← getUnassignedGoals + let resultingSubGoals ← runTacticOnEachGoal evalRec rhsTac subGoals [] + setTacticGoals (resultingSubGoals ++ restGoals) + else if tk == SyntaxKind.tacticFocus then + let subSeq := Syntax.getArg tac 1 + let (gId, _, _) ← getMainGoal (some tac) + let allGs ← getUnassignedGoals + let restGoals := allGs.drop 1 + setTacticGoals [gId] + evalRec subSeq + let rem ← getUnassignedGoals + if !rem.isEmpty then + liftM (throwElabError "focused tactic block '·' left unsolved goals" (some tac)) + setTacticGoals restGoals + else if tk == SyntaxKind.tacticCase then + let tagId := Syntax.getId (Syntax.getArg tac 1) + let bIds := (Syntax.getArgs (Syntax.getArg tac 2)).toList.map Syntax.getId + let subSeq := Syntax.getArg tac 4 + let allGs ← getUnassignedGoals + let eSt ← liftM (get : IxElabM ElabState) + let matchedGoal? := allGs.find? fun gId => + match eSt.mctx.findDecl? gId with + | some d => matchesCtorTag d.userName tagId + | none => false + let targetGId ← match matchedGoal?, allGs with + | some gId, _ => pure gId + | none, gId :: _ => pure gId + | none, [] => liftM (throwElabError s!"no goal matching case '{Name.toStringTotal tagId}'" (some tac)) + let otherGoals := allGs.filter (· != targetGId) + if !bIds.isEmpty then + if let some d := eSt.mctx.findDecl? targetGId then + let lctxAliased := aliasRecentLocalDecls d.lctx bIds + liftM (modifyMCtx (·.addExprMVarDecl { d with lctx := lctxAliased })) + setTacticGoals [targetGId] + evalRec subSeq + let rem ← getUnassignedGoals + if !rem.isEmpty then + liftM (throwElabError s!"'case {Name.toStringTotal tagId}' left unsolved goals" (some tac)) + setTacticGoals otherGoals + else if tk == SyntaxKind.tacticFirst then + let branches := (Syntax.getArgs (Syntax.getArg tac 1)).toList + tryFirstTacticBranches evalRec tac branches + else if tk == SyntaxKind.tacticTry then + let _ ← tryTactic? (evalRec (Syntax.getArg tac 1)) + else if tk == SyntaxKind.tacticRepeat then + repeatTacticLoop evalRec (Syntax.getArg tac 1) 32 + else if tk == SyntaxKind.tacticAllGoals then + let innerTac := Syntax.getArg tac 1 + let allGs ← getUnassignedGoals + let resGs ← runTacticOnEachGoal evalRec innerTac allGs [] + setTacticGoals resGs + else if tk == SyntaxKind.tacticAnyGoals then + let innerTac := Syntax.getArg tac 1 + let allGs ← getUnassignedGoals + let (anyOk, resGs) ← anyGoalsLoop evalRec innerTac allGs false [] + if !anyOk then + liftM (throwElabError "'any_goals' failed on all goals" (some tac)) + setTacticGoals resGs + else if tk == SyntaxKind.tacticIntro then + evalIntroTactic fuel tac + else if tk == SyntaxKind.tacticRintro then + evalRintroTactic elabRec fuel tac + else if tk == SyntaxKind.tacticRcases then + evalRcasesTactic elabRec fuel tac + else if tk == SyntaxKind.tacticObtain then + evalObtainTactic elabRec fuel tac + else if tk == SyntaxKind.tacticCalc || tk == SyntaxKind.calcTerm then + evalCalcTactic elabRec fuel tac + else if tk == SyntaxKind.tacticNormNum then + evalNormNumTactic fuel tac + else if tk == SyntaxKind.tacticRing then + evalRingTactic fuel tac + else if tk == SyntaxKind.tacticOmega then + evalOmegaTactic fuel tac + else if tk == SyntaxKind.tacticExact then + withMainGoalContext (some tac) fun gId _ gTy => do + let termStx := Syntax.getArg tac 1 + let val ← liftM (elabRec termStx (some gTy)) + let valInst ← liftM (instantiateMVars 32 val) + liftM (modifyMCtx (·.assignExpr gId valInst)) + replaceMainGoal [] + else if tk == SyntaxKind.tacticRefine then + withMainGoalContext (some tac) fun gId _ gTy => do + let termStx := Syntax.getArg tac 1 + let val ← liftM (elabRec termStx (some gTy)) + let valInst ← liftM (instantiateMVars 32 val) + let stNow ← liftM (get : IxElabM ElabState) + let newGoals := collectUnassignedMVarIds stNow.mctx valInst + liftM (modifyMCtx (·.assignExpr gId valInst)) + replaceMainGoal newGoals + else if tk == SyntaxKind.tacticApply then + withMainGoalContext (some tac) fun _ _ _ => do + let termStx := Syntax.getArg tac 1 + let fnExpr ← liftM (elabRec termStx none) + let fnTy ← liftM (inferType fuel fnExpr) + applyExprToMainGoal fuel tac fnExpr fnTy + else if tk == SyntaxKind.tacticRfl || tk == SyntaxKind.tacticDecide then + evalRflTactic fuel tac + else if tk == SyntaxKind.tacticAssumption then + evalAssumptionTactic fuel tac + else if tk == SyntaxKind.tacticTrivial then + evalTrivialTactic fuel tac + else if tk == SyntaxKind.tacticContradiction then + evalContradictionTactic fuel tac + else if tk == SyntaxKind.tacticExfalso then + evalExfalsoTactic tac + else if tk == SyntaxKind.tacticDone then + let gs ← getUnassignedGoals + if !gs.isEmpty then + liftM (throwElabError "tactic 'done' failed: unsolved goals remain" (some tac)) + else if tk == SyntaxKind.tacticConstructor || tk == SyntaxKind.tacticSplit then + evalCtorSelectTactic fuel tac "constructor" + else if tk == SyntaxKind.tacticLeft then + evalCtorSelectTactic fuel tac "left" + else if tk == SyntaxKind.tacticRight then + evalCtorSelectTactic fuel tac "right" + else if tk == SyntaxKind.tacticExists then + evalExistsTactic elabRec fuel tac + else if tk == SyntaxKind.tacticSymm then + evalSymmTactic fuel tac + else if tk == SyntaxKind.tacticTrans then + evalTransTactic elabRec fuel tac + else if tk == SyntaxKind.tacticCongr then + evalCongrTactic fuel tac + else if tk == SyntaxKind.tacticFunext || tk == SyntaxKind.tacticExt then + evalExtTactic fuel tac + else if tk == SyntaxKind.tacticHave then + evalHaveOrLetTactic elabRec fuel tac true + else if tk == SyntaxKind.tacticLet then + evalHaveOrLetTactic elabRec fuel tac false + else if tk == SyntaxKind.tacticSuffices then + evalSufficesTactic elabRec evalRec tac + else if tk == SyntaxKind.tacticSpecialize then + evalSpecializeTactic elabRec fuel tac + else if tk == SyntaxKind.tacticClear then + evalClearTactic tac + else if tk == SyntaxKind.tacticRevert then + evalRevertTactic tac + else if tk == SyntaxKind.tacticGeneralize then + evalGeneralizeTactic elabRec fuel tac + else if tk == SyntaxKind.tacticSubst then + evalSubstTactic fuel tac + else if tk == SyntaxKind.tacticByCases then + evalByCasesTactic elabRec tac + else if tk == SyntaxKind.tacticByContra then + evalByContraTactic fuel tac + else if tk == SyntaxKind.tacticChange || tk == SyntaxKind.tacticShow then + evalChangeOrShowTactic elabRec fuel tac + else if tk == SyntaxKind.tacticRw then + evalRwTactic elabRec fuel tac + else if tk == SyntaxKind.tacticDSimp then + evalSimpOrDSimpTactic elabRec fuel tac false + else if tk == SyntaxKind.tacticSimp then + evalSimpOrDSimpTactic elabRec fuel tac true + else if tk == SyntaxKind.tacticCases then + evalCasesOrInductionTactic elabRec evalRec fuel tac false + else if tk == SyntaxKind.tacticInduction then + evalCasesOrInductionTactic elabRec evalRec fuel tac true + else if tk == SyntaxKind.tacticSorry then + withMainGoalContext (some tac) fun _ _ gTy => do + let st ← liftM (get : IxElabM ElabState) + if st.env.contains (Name.simple "sorryAx") then + let (sConst, sTy) ← liftM (mkConstWithFreshMVarLevels (Name.simple "sorryAx")) + let (cand, _, resTy) ← liftM (openForallMVars 8 sConst sTy []) + let _ ← liftM (isDefEq fuel resTy gTy) + closeMainGoal cand (some tac) + else + liftM (throwElabError "'sorry' tactic used without 'sorryAx' in environment" (some tac)) + else + liftM (throwElabError s!"unsupported tactic '{Name.toStringTotal tk}'" (some tac)) + +/-- Entry point for elaborating a `by ...` tactic sequence on `rootGoalId`. -/ +def evalTacticSeq (elabRec : Stx → Option Ix.Expr → IxElabM Ix.Expr) + (fuel : Nat) (tacSeq : Stx) (rootGoalId : Ix.Name) : IxElabM Unit := do + let (_, finalState) ← (evalTactic elabRec fuel 64 tacSeq).run { goals := [rootGoalId] } + let eSt ← get + let remaining := finalState.goals.filter fun gId => !eSt.mctx.isExprAssigned gId + if !remaining.isEmpty then + throwElabError s!"unsolved tactic goals ({remaining.length} remaining)" (some tacSeq) + +end Ix.Frontend.Elab diff --git a/Ix/Frontend/Elab/Term.lean b/Ix/Frontend/Elab/Term.lean new file mode 100644 index 0000000000..b220d45f6d --- /dev/null +++ b/Ix/Frontend/Elab/Term.lean @@ -0,0 +1,1776 @@ +/- + Ix.Frontend.Elab.Term: Pure, deterministic, fuel-bounded bidirectional term, + binder, pattern-match, and tactic elaborator for the Ix Frontend. + + Directly elaborates: + - Substructural usage (`0`, `1`, `&`), ownership (`!`), and locality (`~`) contracts + on `fun`, `forall`/arrows, `let`, and `let @[borrow]`, attaching `ix.contract` frames + and recording `Ixon.BinderContract`, `Ixon.ValueContract`, and `Ixon.LetContract`. + - Implicit argument insertion and bounded backtracking typeclass synthesis (`[...]`). + - Content-hash references (`#<64-hex-chars>`) and `IxImportMap` name resolution. + - Structure literals `{ field := val, ... }`, anonymous constructors `⟨a, b⟩`, and `.field` projections. + - Pattern matching (`match ... with`) lowered into canonical `.casesOn` applications. + - Core tactic blocks (`by intro; exact; apply; refine; rfl; assumption; constructor; have; let; change; cases; induction`). +-/ +module + +public import Ix.Frontend.AuxGen +public import Ix.Frontend.Elab.Tactic + +@[expose] public section + +namespace Ix.Frontend.Elab + +open Ix.Frontend +open Ix.Frontend.Parser +open Ix.Frontend.AuxGen + +/-! ## Universe Level Elaboration -/ + +/-- Elaborate a universe level syntax tree into an `Ix.Level` (pure structural recursion, zero `Array.mapM`). -/ +def elabLevel : Nat → Stx → IxElabM Ix.Level + | 0, stx => throwElabError (str% "elaborator fuel exhausted in universe level") (some stx) + | fuel + 1, stx => withRef stx do + let rec elabLevels : List Stx → List Ix.Level → IxElabM (List Ix.Level) + | [], revAcc => pure revAcc.reverse + | s :: rest, revAcc => do + let u ← elabLevel fuel s + elabLevels rest (u :: revAcc) + match stx with + | .ident _ _ idF => + let id := FName.toIxName idF + if Name.isAnonymous id || id == Name.simple (str% "_") then + mkFreshLevelMVar + else + let ctx ← read + let st ← get + if ctx.univParams.contains id || ctx.scope.levelNames.contains id || + st.autoBoundUnivs.contains id then + return Level.mkParam id + else + -- Auto-bind universe parameter name + modify fun s => { s with autoBoundUnivs := s.autoBoundUnivs ++ [id] } + return Level.mkParam id + | .node _ kindF args => + let kind := FName.toIxName kindF + if kind == SyntaxKind.levelLit then + let numStr := Syntax.getAtomVal (args.getD 0 .missing) + let n := (parseNatLiteral numStr).getD 0 + return Level.ofNat n + else if kind == SyntaxKind.levelAdd then + let base ← elabLevel fuel (args.getD 0 .missing) + let numNode := args.getD 2 .missing + let numStr := Syntax.getAtomVal (Syntax.getArg numNode 0) + let offset := (parseNatLiteral numStr).getD 0 + return (List.range offset).foldl (fun acc _ => Level.mkSucc acc) base + else if kind == SyntaxKind.levelMax then + let children := Syntax.getArgs (args.getD 1 .missing) + let lvls ← elabLevels children.toList [] + match lvls with + | [] => return Level.mkZero + | u :: us => return us.foldl Level.mkMax u + else if kind == SyntaxKind.levelIMax then + let children := Syntax.getArgs (args.getD 1 .missing) + let lvls ← elabLevels children.toList [] + match lvls with + | [] => return Level.mkZero + | [u] => return u + | u :: us => + let rev := (u :: us).reverse + match rev with + | last :: initRev => + return initRev.foldl (fun acc x => Level.mkIMax x acc) last + | [] => return Level.mkZero + else + throwElabError (str% "unexpected universe level syntax") (some stx) + | _ => + throwElabError (str% "expected universe level") (some stx) + +/-- Structural helper: elaborate a `List Stx` of universe levels without `Array.mapM`. -/ +def elabLevelList (fuel : Nat) : List Stx → List Ix.Level → IxElabM (Array Ix.Level) + | [], revAcc => pure (Array.mk revAcc.reverse) + | s :: rest, revAcc => do + let u ← elabLevel fuel s + elabLevelList fuel rest (u :: revAcc) + +/-! ## Substructural Binder Decoding -/ + +/-- Decoded binder specification before type elaboration. -/ +structure ParsedBinderGroup where + names : Array Ix.Name + typeStx? : Option Stx + binderInfo : Lean.BinderInfo + contract : Ixon.BinderContract + deriving Repr, Inhabited + +/-- Decode a single bracketed or simple binder node (`explicitBinder`, `implicitBinder`, + `strictImplicitBinder`, `instBinder`) into a `ParsedBinderGroup`. -/ +def decodeBinderNode (bStx : Stx) : ParsedBinderGroup := + let k := Syntax.getKind bStx + let bi : Lean.BinderInfo := + if k == SyntaxKind.implicitBinder then .implicit + else if k == SyntaxKind.strictImplicitBinder then .strictImplicit + else if k == SyntaxKind.instBinder then .instImplicit + else .default + if k == SyntaxKind.explicitBinder || k == SyntaxKind.implicitBinder || + k == SyntaxKind.strictImplicitBinder || k == SyntaxKind.instBinder then + let bPrefNode := Syntax.getArg bStx 0 + let idsNode := Syntax.getArg bStx 1 + let vPrefNode := Syntax.getArg bStx 2 + let tyNode := Syntax.getArg bStx 3 + let parsedContract := + mergeParsedContracts (decodeContractPrefix bPrefNode) (decodeContractPrefix vPrefNode) + let names := (Syntax.getArgs idsNode).map fun idStx => + if Syntax.getAtomVal idStx == (str% "_") then Name.mkAnon + else Syntax.getId idStx + let names := if names.isEmpty then #[Name.mkAnon] else names + let typeStx? := + if Syntax.isNone tyNode || Syntax.isMissing tyNode then none + else some tyNode + { names, typeStx?, binderInfo := bi, contract := parsedContract.toBinderContract } + else + let id := if Syntax.getAtomVal bStx == (str% "_") then Name.mkAnon else Syntax.getId bStx + { names := #[id], typeStx? := none, binderInfo := .default, contract := default } + +/-! ## Structure Projection & Dot-Notation Resolution -/ + +/-- Solve a list of pending typeclass instance metavariables in order (zero `ForIn` overhead). -/ +def solveInstGoals (fuel : Nat) : List Ix.Expr → IxElabM Unit + | [] => pure () + | g :: rest => do + let gTy ← inferType fuel g + if let some instVal ← synthInstance? 8 gTy then + let _ ← isDefEq fuel g instVal + solveInstGoals fuel rest + +/-- Solve all pending coercion instance goals, returning `false` if any fails to synthesize. -/ +def solveAllInstGoals (fuel : Nat) : List Ix.Expr → IxElabM Bool + | [] => pure true + | g :: rest => do + let gTy ← inferType fuel g + match ← synthInstance? 8 gTy with + | some instVal => + let _ ← isDefEq fuel g instVal + solveAllInstGoals fuel rest + | none => pure false + +/-- Unify corresponding pairs of expressions via `isDefEq`. -/ +def unifyExprPairs (fuel : Nat) : List (Ix.Expr × Ix.Expr) → IxElabM Unit + | [] => pure () + | (a, b) :: rest => do + let _ ← isDefEq fuel a b + unifyExprPairs fuel rest + +/-- Elaborate a `.field` or `.0` projection on an already-elaborated `baseExpr`. -/ +def elabProjOnExpr (fuel : Nat) (baseExpr : Ix.Expr) (fieldStx : Stx) : IxElabM Ix.Expr := do + -- 1. Numeric projection `base.0`, `base.1`, `base.2` (1-based `.1`/`.2` or 0-based `.0`) + if Syntax.isOfKind fieldStx SyntaxKind.numLit then + let nStr := Syntax.getAtomVal (Syntax.getArg fieldStx 0) + let rawIdx := (parseNatLiteral nStr).getD 0 + let baseTy ← inferType fuel baseExpr + let baseTyWhnf ← whnf fuel baseTy + let (headFn, _) := getAppFnArgs baseTyWhnf + match headFn with + | .const structName _ _ => + let idx := if rawIdx > 0 then rawIdx - 1 else 0 + return Expr.mkProj structName idx baseExpr + | _ => + throwElabError (str% "cannot project index from non-structure type") (some fieldStx) + else + let fieldId := Syntax.getId fieldStx + let baseTy ← inferType fuel baseExpr + let baseTyWhnf ← whnf fuel baseTy + let (headFn, headArgs) := getAppFnArgs baseTyWhnf + let st ← get + match headFn with + | .const typeName typeUnivs _ => + -- Check if `typeName` is a registered `structure` / `class` with field `fieldId` + match st.env.structTable.get? typeName with + | some sInfo => + match sInfo.fields.find? (fun f => f.fieldName == fieldId) with + | some fInfo => + return Expr.mkProj typeName fInfo.fieldIdx baseExpr + | none => + -- Generalized dot-notation: `.` applied to `baseExpr` + let methodName := + let direct := Name.append typeName fieldId + if st.env.contains direct then direct + else match Name.splitMergeVariant? typeName with + | some (origType, tag, []) => + let varMethod := Name.mkMergeVariant (Name.append origType fieldId) tag + if st.env.contains varMethod then varMethod + else + let origMethod := Name.append origType fieldId + if st.env.contains origMethod then origMethod else direct + | _ => direct + if st.env.contains methodName then + let (mConst, mTy) ← mkConstWithFreshMVarLevels methodName + let (applied, instGoals, _) ← insertImplicitArgs 16 mConst mTy [] + solveInstGoals fuel instGoals.reverse + return Expr.mkApp applied baseExpr + else + -- Check inherited methods on `sInfo.parents` via `.to` coercion + let foundParent? := sInfo.parents.find? fun pName => + st.env.contains (Name.append pName fieldId) + match foundParent? with + | some pName => + let basePName := (Name.conflictOrigName? pName).getD pName + let pShort := (Name.components basePName).getLastD (str% "") + let toParentName := Name.mkStr typeName (Sym.toString (Sym.append (s% "to") (Sym.ofString pShort))) + let coercedBase ← + if st.env.contains toParentName then + let (tpConst, tpTy) ← mkConstWithFreshMVarLevels toParentName + let (tpApp, tpInsts, _) ← insertImplicitArgs 16 tpConst tpTy [] + solveInstGoals fuel tpInsts.reverse + pure (Expr.mkApp tpApp baseExpr) + else + pure baseExpr + let pMethodName := Name.append pName fieldId + let (mConst, mTy) ← mkConstWithFreshMVarLevels pMethodName + let (applied, instGoals, _) ← insertImplicitArgs 16 mConst mTy [] + solveInstGoals fuel instGoals.reverse + return Expr.mkApp applied coercedBase + | none => + throwElabError (str% "unknown field or method on structure") (some fieldStx) + | none => + -- Check if `.` is a function/constructor + let methodName := + let direct := Name.append typeName fieldId + if st.env.contains direct then direct + else match Name.splitMergeVariant? typeName with + | some (origType, tag, []) => + let varMethod := Name.mkMergeVariant (Name.append origType fieldId) tag + if st.env.contains varMethod then varMethod + else + let origMethod := Name.append origType fieldId + if st.env.contains origMethod then origMethod else direct + | _ => direct + if st.env.contains methodName then + let _ := typeUnivs + let _ := headArgs + let (mConst, mTy) ← mkConstWithFreshMVarLevels methodName + let (applied, instGoals, _) ← insertImplicitArgs 16 mConst mTy [] + solveInstGoals fuel instGoals.reverse + return Expr.mkApp applied baseExpr + else + throwElabError (str% "unknown field on type") (some fieldStx) + | _ => + throwElabError (str% "cannot project field from expression of unknown structure type") (some fieldStx) + +/-- First-order helper: apply a chain of field projections `fStrs` onto `curExpr` (zero closure param). -/ +def applyFieldProjChain (fuel : Nat) : List String → Ix.Expr → IxElabM Ix.Expr + | [], cur => pure cur + | fStr :: rest, cur => do + let cur' ← elabProjOnExpr fuel cur (Syntax.mkSimpleIdent (Name.simple fStr)) + applyFieldProjChain fuel rest cur' + +/-- Split a hierarchical `Ix.Name` into `(rootComponentName, remainingFieldStrings)`. -/ +def splitRootAndFields (n : Ix.Name) : Option (Ix.Name × List String) := + match Name.components n with + | root :: rest@(_ :: _) => some (Name.simple root, rest) + | _ => none + +/-- Resolve and elaborate an identifier (with optional explicit `.{u, v}` levels), + returning both `(expr, type)` so callers never need to re-run `inferType`. -/ +def elabIdentWithLevelsAndType (fuel : Nat) (idStx : Stx) + (explicitLvls? : Option (Array Ix.Level)) : IxElabM (Ix.Expr × Ix.Expr) := withRef idStx do + let rawId := Syntax.getId idStx + let ctx ← read + let st ← get + -- 1. Check local context for exact match + match ctx.lctx.findUserName? rawId with + | some decl => + return (Expr.mkFVar decl.fvarId, decl.type) + | none => + -- 2. Check if `rawId` is `localVar.field1.field2` where `localVar` is in `ctx.lctx` + match splitRootAndFields rawId with + | some (rootName, fieldStrs) => + match ctx.lctx.findUserName? rootName with + | some rootDecl => + let curExpr ← applyFieldProjChain fuel fieldStrs (Expr.mkFVar rootDecl.fvarId) + let curTy ← inferType fuel curExpr + return (curExpr, curTy) + | none => + -- Fall through to global constant resolution + let resolved := resolveIdentInScope ctx.scope ctx.modIdx (fun n => st.env.contains n) rawId + let mappedResolved := + if st.env.contains resolved then resolved + else match ctx.modIdx.importMap.lookupName? resolved <|> st.env.importMap.lookupName? resolved with + | some addr => + (st.env.constOrder.find? fun nm => + Name.computeHash nm == addr || st.env.importMap.lookupName? nm == some addr).getD resolved + | none => resolved + if st.env.contains mappedResolved then + match explicitLvls? with + | some lvls => + let cExpr := Expr.mkConst mappedResolved lvls + let cTy ← inferType fuel cExpr + return (cExpr, cTy) + | none => + mkConstWithFreshMVarLevels mappedResolved + else + throwElabError (str% "unknown identifier") (some idStx) + | none => + -- 3. Global constant resolution in `scope` + let resolved := resolveIdentInScope ctx.scope ctx.modIdx (fun n => st.env.contains n) rawId + let mappedResolved := + if st.env.contains resolved then resolved + else match ctx.modIdx.importMap.lookupName? resolved <|> st.env.importMap.lookupName? resolved with + | some addr => + (st.env.constOrder.find? fun nm => + Name.computeHash nm == addr || st.env.importMap.lookupName? nm == some addr).getD resolved + | none => resolved + if st.env.contains mappedResolved then + match explicitLvls? with + | some lvls => + let cExpr := Expr.mkConst mappedResolved lvls + let cTy ← inferType fuel cExpr + return (cExpr, cTy) + | none => + mkConstWithFreshMVarLevels mappedResolved + else if rawId == Name.simple (str% "true") && st.env.contains (Name.mkStr2 (str% "Bool") (str% "true")) then + return (Expr.mkConst (Name.mkStr2 (str% "Bool") (str% "true")) #[], + Expr.mkConst (Name.simple (str% "Bool")) #[]) + else if rawId == Name.simple (str% "false") && st.env.contains (Name.mkStr2 (str% "Bool") (str% "false")) then + return (Expr.mkConst (Name.mkStr2 (str% "Bool") (str% "false")) #[], + Expr.mkConst (Name.simple (str% "Bool")) #[]) + else + throwElabError (str% "unknown identifier") (some idStx) + +/-- Resolve and elaborate an identifier (with optional explicit `.{u, v}` levels). -/ +def elabIdentWithLevels (fuel : Nat) (idStx : Stx) (explicitLvls? : Option (Array Ix.Level)) : + IxElabM Ix.Expr := do + let (e, _) ← elabIdentWithLevelsAndType fuel idStx explicitLvls? + return e + +/-! ## Implicit Argument Insertion & Expected Type Coercion -/ + +/-- Ensure `ty` is a `Sort`, skipping redundant re-checks on `.forallE` nodes whose + domain and codomain were already checked when constructed. -/ +def ensureSortIfNotForall (fuel : Nat) (ty : Ix.Expr) : IxElabM Unit := + match stripMData ty with + | .forallE _ _ _ _ _ => return () + | _ => do let _ ← ensureSort fuel ty + +/-- Fast pure lookup for built-in binary operators without rebuilding `defaultParserEnv`. -/ +def findBuiltinOpTarget? (sym : String) : Option Ix.Name := + if sym == (str% "=") then some (Name.simple (str% "Eq")) + else if sym == (str% "≠") then some (Name.simple (str% "Ne")) + else if sym == (str% "+") then some (Name.mkStr2 (str% "HAdd") (str% "hAdd")) + else if sym == (str% "-") then some (Name.mkStr2 (str% "HSub") (str% "hSub")) + else if sym == (str% "*") then some (Name.mkStr2 (str% "HMul") (str% "hMul")) + else if sym == (str% "/") then some (Name.mkStr2 (str% "HDiv") (str% "hDiv")) + else if sym == (str% "%") then some (Name.mkStr2 (str% "HMod") (str% "hMod")) + else if sym == (str% "^") then some (Name.mkStr2 (str% "HPow") (str% "hPow")) + else if sym == (str% "++") then some (Name.mkStr2 (str% "HAppend") (str% "hAppend")) + else if sym == (str% "::") then some (Name.mkStr2 (str% "List") (str% "cons")) + else if sym == (str% "==") then some (Name.mkStr2 (str% "BEq") (str% "beq")) + else if sym == (str% "!=") then some (Name.mkStr2 (str% "BEq") (str% "bne")) + else if sym == (str% "<") then some (Name.mkStr2 (str% "LT") (str% "lt")) + else if sym == (str% "≤") || sym == (str% "<=") then some (Name.mkStr2 (str% "LE") (str% "le")) + else if sym == (str% ">") then some (Name.mkStr2 (str% "GT") (str% "gt")) + else if sym == (str% "≥") || sym == (str% ">=") then some (Name.mkStr2 (str% "GE") (str% "ge")) + else if sym == (str% "&&") then some (Name.simple (str% "and")) + else if sym == (str% "||") then some (Name.simple (str% "or")) + else if sym == (str% "∧") || sym == (str% "/\\") then some (Name.simple (str% "And")) + else if sym == (str% "∨") || sym == (str% "\\/") then some (Name.simple (str% "Or")) + else if sym == (str% "↔") || sym == (str% "<->") then some (Name.simple (str% "Iff")) + else if sym == (str% "×") then some (Name.simple (str% "Prod")) + else if sym == (str% "∘") then some (Name.mkStr2 (str% "Function") (str% "comp")) + else if sym == (str% "<|>") then some (Name.mkStr2 (str% "HOrElse") (str% "hOrElse")) + else if sym == (str% ">>") then some (Name.mkStr2 (str% "HAndThen") (str% "hAndThen")) + else if sym == (str% ">>=") then some (Name.mkStr2 (str% "Bind") (str% "bind")) + else if sym == (str% "<$>") then some (Name.mkStr2 (str% "Functor") (str% "map")) + else if sym == (str% "<*>") then some (Name.mkStr2 (str% "Seq") (str% "seq")) + else none + +/-- Concise, pure pretty-printer for `Ix.Expr` in error messages (avoids `Repr Ix.Expr`). -/ +def ppExprShort : Nat → Ix.Expr → String + | 0, _ => (str% "...") + | _, .bvar i _ => s!"#{i}" + | _, .fvar n _ => Name.toStringTotal n + | _, .mvar n _ => s!"?{Name.toStringTotal n}" + | _, .sort _ _ => (str% "Sort") + | _, .const n _ _ => Name.toStringTotal n + | fuel + 1, .app f a _ => s!"({ppExprShort fuel f} {ppExprShort fuel a})" + | fuel + 1, .lam n t b _ _ => s!"(fun {Name.toStringTotal n} : {ppExprShort fuel t} => {ppExprShort fuel b})" + | fuel + 1, .forallE n t b _ _ => + if Name.isAnonymous n then s!"({ppExprShort fuel t} → {ppExprShort fuel b})" + else s!"(({Name.toStringTotal n} : {ppExprShort fuel t}) → {ppExprShort fuel b})" + | fuel + 1, .letE n _ v b _ _ => s!"(let {Name.toStringTotal n} := {ppExprShort fuel v}; {ppExprShort fuel b})" + | _, .lit (.natVal n) _ => s!"{n}" + | _, .lit (.strVal s) _ => s!"\"{s}\"" + | fuel + 1, .mdata _ x _ => ppExprShort fuel x + | fuel + 1, .proj s i x _ => s!"{ppExprShort fuel x}.{Name.toStringTotal s}.{i}" + +/-- Check that `expr` with already-computed type `actualTy` is definitionally equal to `expectedType`. -/ +def ensureHasKnownType (fuel : Nat) (stx : Stx) (expr : Ix.Expr) + (actualTy : Ix.Expr) (expectedType? : Option Ix.Expr) : IxElabM Ix.Expr := do + match expectedType? with + | none => instantiateMVars 16 expr + | some expTy => + let expTyWhnf ← whnfForall fuel expTy + -- If `expTyWhnf` is NOT an implicit forall, peel implicit binders on `actualTy` + let shouldPeelImplicits : Bool := match stripMData expTyWhnf with + | .forallE _ _ _ bi _ => bi == .default + | _ => true + let (expr', instGoals, actualTy') ← + if shouldPeelImplicits then insertImplicitArgs 16 expr actualTy [] + else pure (expr, [], actualTy) + let ok ← isDefEq fuel actualTy' expTy + if !ok then + let actNorm ← instantiateMVars 16 actualTy' + let expNorm ← instantiateMVars 16 expTy + let actWhnf ← whnf fuel actNorm + let expWhnf ← whnf fuel expNorm + let st ← get + -- 1. Try parent structure subobject coercion (`.to expr'`) + let parentCoerced? : Option Ix.Expr ← do + let (actHead, _) := getAppFnArgs actWhnf + let (expHead, _) := getAppFnArgs expWhnf + match actHead, expHead with + | .const actStruct _ _, .const expStruct _ _ => + match st.env.structTable.get? actStruct with + | some sInfo => + if sInfo.parents.contains expStruct then + let pShort := (Name.components expStruct).getLastD (str% "") + let toParentName := Name.mkStr actStruct (Sym.toString (Sym.append (s% "to") (Sym.ofString pShort))) + if st.env.contains toParentName then + let (tpConst, tpTy) ← mkConstWithFreshMVarLevels toParentName + let (tpApp, tpInsts, tpAfterTy) ← insertImplicitArgs 16 tpConst tpTy [] + match stripMData (← whnf fuel tpAfterTy) with + | .forallE _ d b _ _ => + let dOk ← isDefEq fuel actNorm d + let coerced := Expr.mkApp tpApp expr' + let retTy := instantiate1 b expr' + let rOk ← isDefEq fuel retTy expTy + if dOk && rOk then + solveInstGoals fuel tpInsts.reverse + pure (some coerced) + else pure none + | _ => pure none + else pure none + else pure none + | none => pure none + | _, _ => pure none + match parentCoerced? with + | some coerced => + solveInstGoals fuel instGoals.reverse + return (← instantiateMVars 16 coerced) + | none => + -- 2. Try `Coe.coe` typeclass coercion (`@Coe.coe α β inst expr'`) + let coeFnName := Name.mkStr2 (str% "Coe") (str% "coe") + let coeClsName := Name.simple (str% "Coe") + let coeCoerced? : Option Ix.Expr ← + if st.env.contains coeFnName && st.env.contains coeClsName then do + let (coeConst, coeTy) ← mkConstWithFreshMVarLevels coeFnName + let (coeApp, coeInsts, coeAfterTy) ← insertImplicitArgs 16 coeConst coeTy [] + match stripMData (← whnf fuel coeAfterTy) with + | .forallE _ dom b _ _ => + let dOk ← isDefEq fuel actNorm dom + let coerced := Expr.mkApp coeApp expr' + let retTy := instantiate1 b expr' + let rOk ← isDefEq fuel retTy expTy + if dOk && rOk then + let allSolved ← solveAllInstGoals fuel coeInsts.reverse + if allSolved then pure (some coerced) else pure none + else pure none + | _ => pure none + else pure none + match coeCoerced? with + | some coerced => + solveInstGoals fuel instGoals.reverse + return (← instantiateMVars 16 coerced) + | none => + throwElabError (str% "type mismatch") (some stx) + solveInstGoals fuel instGoals.reverse + instantiateMVars 16 expr' + +/-- Check that `expr` has type definitionally equal to `expectedType` (inserting trailing + implicit arguments if `expr`'s type has leading implicit binders while `expectedType` does not). -/ +def ensureHasType (fuel : Nat) (stx : Stx) (expr : Ix.Expr) + (expectedType? : Option Ix.Expr) : IxElabM Ix.Expr := do + match expectedType? with + | none => instantiateMVars 16 expr + | some _ => + let actualTy ← inferType fuel expr + ensureHasKnownType fuel stx expr actualTy expectedType? + +/-! ## Core Bidirectional Term Elaborator (`elabTerm`) -/ + +/-- Flatten nested `SyntaxKind.appTerm` nodes into `(headStx, #[arg₁, ..., argₙ])`. -/ +def flattenAppSyntax : Nat → Stx → List Stx → Stx × Array Stx + | 0, stx, acc => (stx, Array.mk acc) + | fuel + 1, stx@(.node _ k args), acc => + if k == SyntaxKindF.appTerm && args.size == 2 then + flattenAppSyntax fuel (Syntax.listGetD args.toList 0 .missing) (Syntax.listGetD args.toList 1 .missing :: acc) + else + (stx, Array.mk acc) + | _, stx, acc => (stx, Array.mk acc) + +/-- A single flattened binder variable with its optional syntax domain, `BinderInfo`, and `BinderContract`. -/ +structure FlatBinderItem where + name : Ix.Name + typeStx? : Option Stx + binderInfo : Lean.BinderInfo + contract : Ixon.BinderContract + +/-- Flatten a list of `ParsedBinderGroup`s into a flat list of `FlatBinderItem`s. -/ +def flattenBinderGroups (groups : List ParsedBinderGroup) : List FlatBinderItem := + groups.flatMap fun grp => + grp.names.toList.map fun nm => + { name := nm, typeStx? := grp.typeStx?, binderInfo := grp.binderInfo, contract := grp.contract } + +/-- Non-CPS elaboration of a flat list of `FlatBinderItem`s returning `(fvarIds, extendedCtx)`. -/ +def elabFlatBinderItemsDirect (elabTermRec : Stx → Option Ix.Expr → IxElabM Ix.Expr) : + List FlatBinderItem → List Ix.Name → ElabContext → ElabState → ElabRes (Array Ix.Name × ElabContext) + | [], revFVars, ctx, st => .ok (Array.mk revFVars.reverse, ctx) st + | item :: restItems, revFVars, ctx, st => + let domRes : ElabRes Ix.Expr := match item.typeStx? with + | some tyStx => + match elabTermRec tyStx none ctx st with + | .error e => .error e + | .ok ty st1 => + match ensureSortPure ctx st1 32 ty with + | .error e => .error e + | .ok _ st2 => .ok ty st2 + | none => + let (u, st1) := mkFreshLevelMVarPure st + let (mv, st2) := mkFreshExprMVarPure ctx st1 (Expr.mkSort u) item.name + .ok mv st2 + match domRes with + | .error e => .error e + | .ok domTy st' => + let (fvId, _, ctx', st'') := pushLocalDeclPure ctx st' item.name domTy item.binderInfo item.contract none none false + elabFlatBinderItemsDirect elabTermRec restItems (fvId :: revFVars) ctx' st'' + +/-- Elaborate a sequence of `ParsedBinderGroup`s, running `k fvarIds` inside the extended `LocalContext`. -/ +@[inline] def elabBinderGroups (elabTermRec : Stx → Option Ix.Expr → IxElabM Ix.Expr) + (groups : List ParsedBinderGroup) (accFVars : Array Ix.Name) (k : Array Ix.Name → IxElabM α) : IxElabM α := + fun ctx st => + match elabFlatBinderItemsDirect elabTermRec (flattenBinderGroups groups) accFVars.toList.reverse ctx st with + | .error e => .error e + | .ok (fvars, ctx') st' => k fvars ctx' st' + +/-- Extract constructor pattern `(ctorName?, boundVarNames)` from a pattern `Syntax`. -/ +def decodeConstructorPattern (scope : ScopeSnapshot) (modIdx : ModuleIndex) + (env : IxElabEnv) (pat : Stx) : Option (Ix.Name × Array Ix.Name) := + let (headStx, argStxs) := flattenAppSyntax 256 pat [] + if Syntax.isOfKind headStx SyntaxKind.numLit then + let nStr := Syntax.getAtomVal (Syntax.getArg headStx 0) + match parseNatLiteral nStr with + | some 0 => some (Name.mkStr2 (str% "Nat") (str% "zero"), #[]) + | _ => none + else + match headStx with + | .ident _ _ idF => + let id := FName.toIxName idF + let resolved := resolveIdentInScope scope modIdx (fun n => env.contains n) id + if env.isCtor resolved || modIdx.isModuleCtor resolved then + let varNames := argStxs.map fun a => + if Syntax.isOfKind a SyntaxKind.holeTerm || Syntax.getAtomVal a == (str% "_") then + Name.mkAnon + else + Syntax.getId a + some (resolved, varNames) + else + none + | _ => none + +/-! ## Structural Recursion Lowering (`casesOn` -> `recOn`) -/ + +/-- If a single recursive definition or `let rec` / `where` binding `fnName`'s value is a lambda + chain whose body calls `.casesOn ... minor_0 ... minor_{m-1}` on one of its parameter + binders, and a minor calls `fnName` (as either `.const fnName` or `.fvar fnName`) on a + recursive field of that constructor, lower the `.casesOn` call into `.recOn` + (generalizing the motive over any trailing accumulator parameters after `majorParamPos`) + so that the definition is 100% self-reference-free and reduces in the kernel via ι-reduction (`rfl`)! -/ +def tryLowerStructuralRecToRecOn (env : IxElabEnv) (fnName : Ix.Name) + (value : Ix.Expr) : Ix.Expr := Id.run do + -- Peel leading `.lam` binders into fresh FVars via structural recursion on `fuel` + let rec peelLams : Nat → Nat → Ix.Expr → Array AuxLocalDecl → Array Ix.Expr → + Ix.Expr × Array AuxLocalDecl × Array Ix.Expr + | 0, _, cur, decls, fvars => (cur, decls, fvars) + | fuel + 1, idx, cur, decls, fvars => + match stripMData cur with + | .lam nm dom body bi _ => + let (fvId, fvExpr) := mkAuxFVar (str% "srl") idx + let cur' := instantiate1 body fvExpr + let decl : AuxLocalDecl := { fvarId := fvId, binderName := nm, domain := dom, binderInfo := bi } + peelLams fuel (idx + 1) cur' (decls.push decl) (fvars.push fvExpr) + | _ => (cur, decls, fvars) + let (cur, lamDecls, lamFVars) := peelLams 32 0 value #[] #[] + let (headFn, headArgs) := getAppFnArgs cur + match headFn with + | .const cName cUnivs _ => + -- Check if `cName` is `.casesOn` + let comps := Name.components cName + if comps.getLast? != some (str% "casesOn") then return value + let indName := Name.fromComponents comps.dropLast + let some (.inductInfo ival) := env.find? indName | return value + let recOnName := Name.mkStr indName (str% "recOn") + if !env.contains recOnName then return value + let nParams := ival.numParams + let nIndices := ival.numIndices + let nCtors := ival.ctors.size + let majorPos := nParams + 1 + nIndices + if headArgs.size != majorPos + 1 + nCtors then return value + let majorArg := headArgs.getD majorPos cur + -- Check which lambda parameter `majorArg` corresponds to + let some majorParamPos := lamFVars.idxOf? majorArg | return value + let extraDecls := lamDecls.extract (majorParamPos + 1) lamDecls.size + let extraFVars := lamFVars.extract (majorParamPos + 1) lamFVars.size + let origMotive := headArgs.getD nParams cur + -- Generalize `origMotive` over any trailing accumulator parameters `extraDecls` + let genMotive := + if extraDecls.isEmpty then origMotive + else match stripMData origMotive with + | .lam nm dom body bi _ => + Expr.mkLam nm dom (closeForalls extraDecls body) bi + | _ => origMotive + -- Rewrite each constructor minor `minor_i` (pure recursion, zero `ForIn`) + let rec peelMinorFields (cidx : Nat) : + Nat → Nat → Ix.Expr → List AuxLocalDecl → List Ix.Expr → + Ix.Expr × Array AuxLocalDecl × Array Ix.Expr + | 0, _, mCur, revDs, revFVs => (mCur, Array.mk revDs.reverse, Array.mk revFVs.reverse) + | rem + 1, fIdx, mCur, revDs, revFVs => + match stripMData mCur with + | .lam nm dom body bi _ => + let (fvId, fvExpr) := mkAuxFVar (str% "srf") (cidx * 64 + fIdx) + peelMinorFields cidx rem (fIdx + 1) (instantiate1 body fvExpr) + ({ fvarId := fvId, binderName := nm, domain := dom, binderInfo := bi } :: revDs) + (fvExpr :: revFVs) + | _ => peelMinorFields cidx rem (fIdx + 1) mCur revDs revFVs + let rec collectRecFieldIhs (cidx : Nat) : + List AuxLocalDecl → List Ix.Expr → Nat → + List AuxLocalDecl → NameMap Ix.Expr → + Array AuxLocalDecl × NameMap Ix.Expr + | [], _, _, revIhs, rMap => (Array.mk revIhs.reverse, rMap) + | fDecl :: restDs, fVars, fIdx, revIhs, rMap => + let (fVar, restFVs) := match fVars with + | v :: vs => (v, vs) + | [] => (cur, []) + let (fDomHead, _) := getAppFnArgs fDecl.domain + match fDomHead with + | .const dNm _ _ => + if dNm == indName then + let (ihId, ihExpr) := mkAuxFVar (str% "srih") (cidx * 64 + fIdx) + let ihDom := Expr.mkBeta (Expr.mkApp genMotive fVar) + collectRecFieldIhs cidx restDs restFVs (fIdx + 1) + ({ fvarId := ihId, binderName := Name.simple (str% "ih"), domain := ihDom } :: revIhs) + (rMap.insert fDecl.fvarId ihExpr) + else + collectRecFieldIhs cidx restDs restFVs (fIdx + 1) revIhs rMap + | _ => + collectRecFieldIhs cidx restDs restFVs (fIdx + 1) revIhs rMap + let rec rewriteSelfCalls (recFieldMap : NameMap Ix.Expr) : Ix.Expr → Bool × Ix.Expr + | .app f a _ => + let (c1, f') := rewriteSelfCalls recFieldMap f + let (c2, a') := rewriteSelfCalls recFieldMap a + let curApp := Expr.mkApp f' a' + let (fnH, fnAs) := getAppFnArgs curApp + let isSelfHead := match fnH with + | .const nm _ _ => nm == fnName + | .fvar fvId _ => fvId == fnName + | _ => false + if isSelfHead && fnAs.size == lamFVars.size then + let argAtMaj := fnAs.getD majorParamPos f' + match stripMData argAtMaj with + | .fvar fvId _ => + match recFieldMap.get? fvId with + | some ihExpr => + let trailingArgs := fnAs.extract (majorParamPos + 1) fnAs.size + (true, Expr.mkAppN ihExpr trailingArgs) + | none => (c1 || c2, curApp) + | _ => (c1 || c2, curApp) + else + (c1 || c2, curApp) + | .lam nm t b bi _ => + let (c1, t') := rewriteSelfCalls recFieldMap t + let (c2, b') := rewriteSelfCalls recFieldMap b + (c1 || c2, Expr.mkLam nm t' b' bi) + | .forallE nm t b bi _ => + let (c1, t') := rewriteSelfCalls recFieldMap t + let (c2, b') := rewriteSelfCalls recFieldMap b + (c1 || c2, Expr.mkForallE nm t' b' bi) + | .letE nm t v b nd _ => + let (c1, t') := rewriteSelfCalls recFieldMap t + let (c2, v') := rewriteSelfCalls recFieldMap v + let (c3, b') := rewriteSelfCalls recFieldMap b + (c1 || c2 || c3, Expr.mkLetE nm t' v' b' nd) + | .proj nm i s _ => + let (c1, s') := rewriteSelfCalls recFieldMap s + (c1, Expr.mkProj nm i s') + | .mdata md x _ => + let (c1, x') := rewriteSelfCalls recFieldMap x + (c1, Expr.mkMData md x') + | other => (false, other) + let rec rewriteCtorsLoop : + List Ix.Name → Nat → Bool → List Ix.Expr → Option (Bool × Array Ix.Expr) + | [], _, changed, revMinors => some (changed, Array.mk revMinors.reverse) + | ctorName :: restCtors, cidx, changed, revMinors => + let minorExpr := headArgs.getD (majorPos + 1 + cidx) cur + match env.find? ctorName with + | some (.ctorInfo cval) => + let (mCur, fDecls, fFVars) := peelMinorFields cidx cval.numFields 0 minorExpr [] [] + let (ihDecls, recFieldMap) := collectRecFieldIhs cidx fDecls.toList fFVars.toList 0 [] NameMap.empty + let (didRewrite, mCur') := rewriteSelfCalls recFieldMap mCur + let newMinor := closeLambdas (fDecls ++ ihDecls ++ extraDecls) mCur' + rewriteCtorsLoop restCtors (cidx + 1) (changed || didRewrite) (newMinor :: revMinors) + | _ => none + let some (changed, newMinors) := rewriteCtorsLoop ival.ctors.toList 0 false [] | return value + if !changed then return value + let params := headArgs.extract 0 nParams + let indicesAndMaj := headArgs.extract (nParams + 1) (majorPos + 1) + let prefixArgs := params ++ #[genMotive] ++ indicesAndMaj + let recOnCall := Expr.mkAppN (Expr.mkConst recOnName cUnivs) (prefixArgs ++ newMinors) + let fullBody := Expr.mkAppN recOnCall extraFVars + return closeLambdas (lamDecls.extract 0 (majorParamPos + 1) ++ extraDecls) fullBody + | _ => return value +where + /-- Beta-reduce a single `(λ x => body) arg` application if `fn` is a lambda. -/ + Expr.mkBeta : Ix.Expr → Ix.Expr + | .app (.lam _ _ b _ _) a _ => instantiate1 b a + | other => other + +/-- Helper: elaborate `fun binders => body`. -/ +def elabTermFun (fuel : Nat) (elabRec : Stx → Option Ix.Expr → IxElabM Ix.Expr) + (stx : Stx) (args : Stx) (expectedType? : Option Ix.Expr) : IxElabM Ix.Expr := do + let bindersNode := args.getD 1 .missing + let bodyStx := args.getD 3 .missing + let groups := (Syntax.getArgs bindersNode).toList.map decodeBinderNode + let items := flattenBinderGroups groups + let rec elabFunItems (remItems : List FlatBinderItem) (curExp? : Option Ix.Expr) + (curFVars : Array Ix.Name) : IxElabM Ix.Expr := do + match remItems with + | [] => + let bodyExpr ← elabRec bodyStx curExp? + mkLambdaFVars curFVars bodyExpr + | item :: restItems => + let (expDom?, nextExpFn?) ← match curExp? with + | some eTy => + let eTyW ← whnf 32 eTy + match stripMData eTyW with + | .forallE _ d b _ _ => pure (some d, some b) + | _ => pure (none, none) + | none => pure (none, none) + let domTy ← match item.typeStx? with + | some tyStx => + let t ← elabRec tyStx none + let _ ← ensureSort 32 t + if let some expD := expDom? then + let _ ← isDefEq 32 t expD + pure t + | none => + match expDom? with + | some expD => pure expD + | none => + let u ← mkFreshLevelMVar + mkFreshExprMVar (Expr.mkSort u) item.name + withLocalDecl item.name domTy item.binderInfo item.contract fun fvId fvExpr => do + let nextExp? := nextExpFn?.map fun b => instantiate1 b fvExpr + elabFunItems restItems nextExp? (curFVars.push fvId) + let lamExpr ← elabFunItems items expectedType? #[] + ensureHasType fuel stx lamExpr expectedType? + +/-- Helper: elaborate `let` and `let @[borrow]`. -/ +def elabTermLet (fuel : Nat) (elabRec : Stx → Option Ix.Expr → IxElabM Ix.Expr) + (stx : Stx) (kind : Ix.Name) (args : Stx) (expectedType? : Option Ix.Expr) : IxElabM Ix.Expr := do + let isBorrow := kind == SyntaxKind.letBorrowTerm + let bPrefNode := if isBorrow then args.getD 2 .missing else args.getD 1 .missing + let idStx := if isBorrow then args.getD 3 .missing else args.getD 2 .missing + let bindersNode := if isBorrow then args.getD 4 .missing else args.getD 3 .missing + let optTyNode := if isBorrow then args.getD 5 .missing else args.getD 4 .missing + let valStx := if isBorrow then args.getD 7 .missing else args.getD 6 .missing + let bodyStx := if isBorrow then args.getD 9 .missing else args.getD 8 .missing + + let letName := + let id := Syntax.getId idStx + if Name.isAnonymous id then Name.simple (str% "x") else id + let bParsed := decodeContractPrefix bPrefNode + let (vParsed, optTyStx?) := + if Syntax.getNumArgs optTyNode >= 3 then + let vp := decodeContractPrefix (Syntax.getArg optTyNode 1) + (vp, some (Syntax.getArg optTyNode 2)) + else + ({}, none) + let merged := mergeParsedContracts bParsed vParsed + let isBorrowMode := isBorrow || merged.isBorrow + let binderContract : Ixon.BinderContract := + if isBorrowMode then + { uses := merged.uses.getD .many, value := .localShared } + else + merged.toBinderContract + let letKind : Ixon.LetKind := if isBorrowMode then .borrowShared else .value + let paramGroups := (Syntax.getArgs bindersNode).toList.map decodeBinderNode + let (letTy, letVal) ← elabBinderGroups elabRec paramGroups #[] fun fvars => do + let expValTy? ← match optTyStx? with + | some tyStx => + let t ← elabRec tyStx none + let _ ← ensureSort 32 t + pure (some t) + | none => pure none + let vExpr ← elabRec valStx expValTy? + let vTy ← match expValTy? with + | some t => pure t + | none => inferType fuel vExpr + let fullTy ← mkForallFVars fvars vTy + let fullVal ← mkLambdaFVars fvars vExpr + return (fullTy, fullVal) + withLetDecl letName letTy letVal binderContract letKind false fun fvId _ => do + let bodyExpr ← elabRec bodyStx expectedType? + let nonDep := !containsFVar fvId bodyExpr + let absBody := abstractFVar fvId bodyExpr + let lc : Ixon.LetContract := { nonDep, kind := letKind, binder := binderContract } + modify fun st => { st with localLetContracts := st.localLetContracts.push lc } + let letExpr := Expr.mkLetContract letName letTy letVal absBody nonDep binderContract letKind + ensureHasType fuel stx letExpr expectedType? + +/-- Helper: elaborate `let rec`. -/ +def elabTermLetRec (fuel : Nat) (elabRec : Stx → Option Ix.Expr → IxElabM Ix.Expr) + (stx : Stx) (args : Stx) (expectedType? : Option Ix.Expr) : IxElabM Ix.Expr := do + let bPrefNode := args.getD 2 .missing + let idStx := args.getD 3 .missing + let bindersNode := args.getD 4 .missing + let optTyNode := args.getD 5 .missing + let valStx := args.getD 7 .missing + let bodyStx := args.getD 9 .missing + let letName := + let id := Syntax.getId idStx + if Name.isAnonymous id then Name.simple (str% "recFn") else id + let bParsed := decodeContractPrefix bPrefNode + let (vParsed, optTyStx?) := + if Syntax.getNumArgs optTyNode >= 3 then + let vp := decodeContractPrefix (Syntax.getArg optTyNode 1) + (vp, some (Syntax.getArg optTyNode 2)) + else + ({}, none) + let merged := mergeParsedContracts bParsed vParsed + let binderContract : Ixon.BinderContract := merged.toBinderContract + let paramGroups := (Syntax.getArgs bindersNode).toList.map decodeBinderNode + let letTy ← elabBinderGroups elabRec paramGroups #[] fun fvars => do + let retTy ← match optTyStx? with + | some tyStx => + let t ← elabRec tyStx none + let _ ← ensureSortIfNotForall 32 t + pure t + | none => + let u ← mkFreshLevelMVar + mkFreshExprMVar (Expr.mkSort u) + mkForallFVars fvars retTy + let (letTyInst, letVal) ← withLocalDecl letName letTy .default binderContract fun recFvId _ => do + let rawVal ← elabBinderGroups elabRec paramGroups #[] fun fvars => do + let expValTy? ← match optTyStx? with + | some tyStx => + let t ← elabRec tyStx none + let _ ← ensureSortIfNotForall 32 t + pure (some t) + | none => pure none + let vExpr ← + if Syntax.isOfKind valStx SyntaxKind.nullKind then + let ctxNow ← read + let rec stxMentions (nm : Ix.Name) (fuelM : Nat) (s : Stx) : Bool := + match fuelM with + | 0 => false + | f + 1 => + match s with + | .ident _ _ idF => FName.toIxName idF == nm + | .node _ _ as => as.any (stxMentions nm f) + | _ => false + let targetFvId? := + (fvars.find? fun fvId => + match ctxNow.lctx.findFVar? fvId with + | some d => d.binderInfo == .default && !stxMentions d.userName 64 valStx + | none => false).orElse (fun _ => fvars.back?) + match targetFvId? with + | some lastFvId => + let lastName := match ctxNow.lctx.findFVar? lastFvId with + | some d => d.userName + | none => Name.simple (str% "x") + let matchStx := Syntax.mkNode SyntaxKind.matchTerm + #[Syntax.mkSimpleAtom (str% "match"), Syntax.mkNullNode #[Syntax.mkSimpleIdent lastName], + Syntax.mkSimpleAtom (str% "with"), valStx] + elabRec matchStx expValTy? + | none => + throwElabError "pattern-matching 'let rec' / 'where' requires at least one parameter" (some stx) + else + elabRec valStx expValTy? + let vTy ← match expValTy? with + | some t => pure t + | none => inferType fuel vExpr + let fullTy ← mkForallFVars fvars vTy + let _ ← isDefEq fuel letTy fullTy + mkLambdaFVars fvars vExpr + let rawValInst ← instantiateMVars 32 rawVal + let tyInst ← instantiateMVars 32 letTy + let stNow ← get + let lowered := tryLowerStructuralRecToRecOn stNow.env recFvId rawValInst + pure (tyInst, lowered) + withLetDecl letName letTyInst letVal binderContract .value false fun fvId _ => do + let bodyExpr ← elabRec bodyStx expectedType? + let nonDep := !containsFVar fvId bodyExpr + let absBody := abstractFVar fvId bodyExpr + let lc : Ixon.LetContract := { nonDep, kind := .value, binder := binderContract } + modify fun st => { st with localLetContracts := st.localLetContracts.push lc } + let letExpr := Expr.mkLetContract letName letTyInst letVal absBody nonDep binderContract .value + ensureHasType fuel stx letExpr expectedType? + +/-- Helper: elaborate binary infix operators. -/ +def elabTermBinOp (fuel : Nat) (elabRec : Stx → Option Ix.Expr → IxElabM Ix.Expr) + (stx : Stx) (args : Stx) (expectedType? : Option Ix.Expr) : IxElabM Ix.Expr := do + let lhsStx := args.getD 0 .missing + let opAtom := args.getD 1 .missing + let rhsStx := args.getD 2 .missing + let symS := Syntax.getAtomSym opAtom + let sym := Sym.toString symS + let targetName? := (findBuiltinOpTarget? sym).orElse fun _ => + ((defaultOperators.find? (fun op => op.symbol == symS)).bind (·.targetFn)).map FName.toIxName + let st ← get + match targetName? with + | some targetName => + let natConst := Expr.mkConst (Name.simple (str% "Nat")) #[] + let zLvl := Level.mkZero + if (sym == (str% "=") && st.env.contains (Name.simple (str% "Eq"))) || + (sym == (str% "≠") && st.env.contains (Name.simple (str% "Ne"))) then + let relName := if sym == (str% "=") then Name.simple (str% "Eq") else Name.simple (str% "Ne") + let lhs ← elabRec lhsStx none + let lhsTyRaw ← inferType fuel lhs + let lhsTy ← instantiateMVars 16 lhsTyRaw + let rhs ← elabRec rhsStx (some lhsTy) + let lhsTyFinal ← instantiateMVars 16 lhsTy + let uNorm ← + if lhsTyFinal == natConst then + pure (Level.mkSucc zLvl) + else do + let u ← ensureSort 32 lhsTyFinal + pure (normalizeLevel u) + let relExpr := Expr.mkAppN (Expr.mkConst relName #[uNorm]) #[lhsTyFinal, lhs, rhs] + ensureHasKnownType fuel stx relExpr Expr.mkProp expectedType? + else if (sym == (str% "+") && st.env.contains (Name.mkStr2 (str% "HAdd") (str% "hAdd")) && + st.env.contains (Name.simple (str% "instHAdd")) && st.env.contains (Name.simple (str% "instAddNat"))) || + (sym == (str% "^") && st.env.contains (Name.mkStr2 (str% "HPow") (str% "hPow")) && + st.env.contains (Name.simple (str% "instHPow")) && st.env.contains (Name.simple (str% "instPowNat")) && + st.env.contains (Name.simple (str% "instNatPowNat"))) || + ((sym == (str% "≤") || sym == (str% "<=")) && st.env.contains (Name.mkStr2 (str% "LE") (str% "le")) && + st.env.contains (Name.simple (str% "instLENat"))) || + ((sym == (str% "≥") || sym == (str% ">=")) && st.env.contains (Name.mkStr2 (str% "GE") (str% "ge")) && + st.env.contains (Name.simple (str% "instLENat"))) || + (sym == (str% "<") && st.env.contains (Name.mkStr2 (str% "LT") (str% "lt")) && + st.env.contains (Name.simple (str% "instLTNat"))) || + (sym == (str% ">") && st.env.contains (Name.mkStr2 (str% "GT") (str% "gt")) && + st.env.contains (Name.simple (str% "instLTNat"))) then + let lhs ← elabRec lhsStx (if sym == (str% "+") || sym == (str% "^") then expectedType? else none) + let lhsTyRaw ← inferType fuel lhs + let lhsTy ← instantiateMVars 16 lhsTyRaw + let rhs ← elabRec rhsStx (some lhsTy) + let lhsTyFinal ← instantiateMVars 16 lhsTy + if lhsTyFinal == natConst then + if sym == (str% "+") then + let instAdd := Expr.mkConst (Name.simple (str% "instAddNat")) #[] + let instHAdd := Expr.mkAppN (Expr.mkConst (Name.simple (str% "instHAdd")) #[zLvl]) #[natConst, instAdd] + let addExpr := Expr.mkAppN (Expr.mkConst (Name.mkStr2 (str% "HAdd") (str% "hAdd")) #[zLvl, zLvl, zLvl]) + #[natConst, natConst, natConst, instHAdd, lhs, rhs] + ensureHasKnownType fuel stx addExpr natConst expectedType? + else if sym == (str% "^") then + let instNatPow := Expr.mkConst (Name.simple (str% "instNatPowNat")) #[] + let instPow := Expr.mkAppN (Expr.mkConst (Name.simple (str% "instPowNat")) #[zLvl]) #[natConst, instNatPow] + let instHPow := Expr.mkAppN (Expr.mkConst (Name.simple (str% "instHPow")) #[zLvl, zLvl]) #[natConst, natConst, instPow] + let powExpr := Expr.mkAppN (Expr.mkConst (Name.mkStr2 (str% "HPow") (str% "hPow")) #[zLvl, zLvl, zLvl]) + #[natConst, natConst, natConst, instHPow, lhs, rhs] + ensureHasKnownType fuel stx powExpr natConst expectedType? + else if sym == (str% "≤") || sym == (str% "<=") then + let instLE := Expr.mkConst (Name.simple (str% "instLENat")) #[] + let leExpr := Expr.mkAppN (Expr.mkConst (Name.mkStr2 (str% "LE") (str% "le")) #[zLvl]) #[natConst, instLE, lhs, rhs] + ensureHasKnownType fuel stx leExpr Expr.mkProp expectedType? + else if sym == (str% "≥") || sym == (str% ">=") then + let instLE := Expr.mkConst (Name.simple (str% "instLENat")) #[] + let geExpr := Expr.mkAppN (Expr.mkConst (Name.mkStr2 (str% "GE") (str% "ge")) #[zLvl]) #[natConst, instLE, lhs, rhs] + ensureHasKnownType fuel stx geExpr Expr.mkProp expectedType? + else if sym == (str% "<") then + let instLT := Expr.mkConst (Name.simple (str% "instLTNat")) #[] + let ltExpr := Expr.mkAppN (Expr.mkConst (Name.mkStr2 (str% "LT") (str% "lt")) #[zLvl]) #[natConst, instLT, lhs, rhs] + ensureHasKnownType fuel stx ltExpr Expr.mkProp expectedType? + else + let instLT := Expr.mkConst (Name.simple (str% "instLTNat")) #[] + let gtExpr := Expr.mkAppN (Expr.mkConst (Name.mkStr2 (str% "GT") (str% "gt")) #[zLvl]) #[natConst, instLT, lhs, rhs] + ensureHasKnownType fuel stx gtExpr Expr.mkProp expectedType? + else + let fnIdStx := Syntax.mkSimpleIdent targetName + let appStx := Syntax.mkNode SyntaxKind.appTerm + #[Syntax.mkNode SyntaxKind.appTerm #[fnIdStx, lhsStx], rhsStx] + elabRec appStx expectedType? + else + let actualFnName? : Option Ix.Name := + if st.env.contains targetName then some targetName + else if sym == (str% "+") then if st.env.contains (Name.mkStr2 (str% "Nat") (str% "add")) then some (Name.mkStr2 (str% "Nat") (str% "add")) else none + else if sym == (str% "-") then if st.env.contains (Name.mkStr2 (str% "Nat") (str% "sub")) then some (Name.mkStr2 (str% "Nat") (str% "sub")) else none + else if sym == (str% "*") then if st.env.contains (Name.mkStr2 (str% "Nat") (str% "mul")) then some (Name.mkStr2 (str% "Nat") (str% "mul")) else none + else if sym == (str% "/") then if st.env.contains (Name.mkStr2 (str% "Nat") (str% "div")) then some (Name.mkStr2 (str% "Nat") (str% "div")) else none + else if sym == (str% "%") then if st.env.contains (Name.mkStr2 (str% "Nat") (str% "mod")) then some (Name.mkStr2 (str% "Nat") (str% "mod")) else none + else if sym == (str% "^") then if st.env.contains (Name.mkStr2 (str% "Nat") (str% "pow")) then some (Name.mkStr2 (str% "Nat") (str% "pow")) else none + else if sym == (str% "==") then if st.env.contains (Name.mkStr2 (str% "Nat") (str% "beq")) then some (Name.mkStr2 (str% "Nat") (str% "beq")) else none + else if sym == (str% "≤") || sym == (str% "<=") then if st.env.contains (Name.mkStr2 (str% "Nat") (str% "ble")) then some (Name.mkStr2 (str% "Nat") (str% "ble")) else none + else none + match actualFnName? with + | some fnName => + let fnIdStx := Syntax.mkSimpleIdent fnName + let appStx := Syntax.mkNode SyntaxKind.appTerm + #[Syntax.mkNode SyntaxKind.appTerm #[fnIdStx, lhsStx], rhsStx] + elabRec appStx expectedType? + | none => + let short := match Name.components targetName with + | _ :: s :: _ => Name.simple s + | [s] => Name.simple s + | [] => targetName + let fnIdStx := Syntax.mkSimpleIdent short + let appStx := Syntax.mkNode SyntaxKind.appTerm + #[Syntax.mkNode SyntaxKind.appTerm #[fnIdStx, lhsStx], rhsStx] + elabRec appStx expectedType? + | none => + throwElabError (str% "unknown binary operator") (some stx) + +/-- Helper: elaborate anonymous constructor `⟨a₁, ..., aₙ⟩`. -/ +def elabTermAnonCtor (fuel : Nat) (elabRec : Stx → Option Ix.Expr → IxElabM Ix.Expr) + (stx : Stx) (args : Stx) (expectedType? : Option Ix.Expr) : IxElabM Ix.Expr := do + let elemStxs := Syntax.getArgs (args.getD 1 .missing) + match expectedType? with + | none => + throwElabError "anonymous constructor ⟨...⟩ requires a known expected type" (some stx) + | some expTy => + let expTyWhnf ← whnf fuel expTy + let (headFn, expArgs) := getAppFnArgs expTyWhnf + let st ← get + match headFn with + | .const indName _ _ => + match st.env.find? indName with + | some (.inductInfo ival) => + match ival.ctors[0]? with + | some ctorName => + let numFields? := match st.env.find? ctorName with + | some (.ctorInfo cval) => some cval.numFields + | _ => none + let effectiveElems : Array Stx := + match numFields? with + | some nf => + if nf >= 2 && elemStxs.size > nf then + let pre := elemStxs.extract 0 (nf - 1) + let rest := elemStxs.extract (nf - 1) elemStxs.size + let nestedAnon := Syntax.mkNode SyntaxKind.anonCtor + #[Syntax.mkSimpleAtom (str% "⟨"), Syntax.mkNullNode rest, Syntax.mkSimpleAtom (str% "⟩")] + pre.push nestedAnon + else + elemStxs + | none => elemStxs + let (ctorConst, ctorTy) ← mkConstWithFreshMVarLevels ctorName + let (ctorApplied, instGoals, afterParamsTy) ← insertImplicitArgs 16 ctorConst ctorTy [] + let (_, ctorParamMVars) := getAppFnArgs ctorApplied + unifyExprPairs fuel (ctorParamMVars.toList.zip (expArgs.toList.take ival.numParams)) + let rec elabAnonElems : List Stx → Ix.Expr → Ix.Expr → IxElabM Ix.Expr + | [], curFn, _ => pure curFn + | eStx :: rest, curFn, curTy => do + let curTyInst ← instantiateMVars 16 curTy + let curTyWhnf ← whnf fuel curTyInst + let (domTy, nextBody) ← match stripMData curTyWhnf with + | .forallE _ d b _ _ => pure (betaReduceExpr d, b) + | _ => throwElabError (str% "too many arguments in anonymous constructor") (some stx) + let fValExpr ← elabRec eStx (some domTy) + elabAnonElems rest (Expr.mkApp curFn fValExpr) (instantiate1 nextBody fValExpr) + let curFn ← elabAnonElems effectiveElems.toList ctorApplied afterParamsTy + solveInstGoals fuel instGoals + let res ← instantiateMVars 32 curFn + ensureHasType fuel stx res (some expTyWhnf) + | none => throwElabError (str% "inductive has no constructors") (some stx) + | _ => throwElabError (str% "expected inductive/structure type") (some stx) + | _ => throwElabError (str% "expected known inductive or structure type") (some stx) + +/-- Helper: elaborate structure instance `{ [base with] field₁ := val₁, ... }`. -/ +def elabTermStructInst (fuel : Nat) (elabRec : Stx → Option Ix.Expr → IxElabM Ix.Expr) + (stx : Stx) (args : Stx) (expectedType? : Option Ix.Expr) : IxElabM Ix.Expr := do + let withNode := args.getD 1 .missing + let assignsNode := args.getD 2 .missing + let baseExpr? ← + if Syntax.isNone withNode || Syntax.isMissing withNode then + pure none + else + let bStx := + if Syntax.isOfKind withNode SyntaxKind.nullKind then + Syntax.getArg withNode 0 + else + withNode + let b ← elabRec bStx expectedType? + pure (some b) + let expTy ← match expectedType?, baseExpr? with + | _, some b => + let bTy ← inferType fuel b + whnf fuel bTy + | some t, none => whnf fuel t + | none, none => + throwElabError "structure literal '{ ... }' requires an expected structure type" (some stx) + let (headFn, expArgs) := getAppFnArgs expTy + let st ← get + match headFn with + | .const structName _ _ => + match st.env.structTable.get? structName with + | none => + throwElabError (str% "not a registered structure") (some stx) + | some sInfo => + let assignedMap : NameMap Stx := + (Syntax.getArgs assignsNode).toList.foldl (fun acc assignStx => + let fId := Syntax.getId (Syntax.getArg assignStx 0) + let vStx := Syntax.getArg assignStx 2 + acc.insert fId vStx) NameMap.empty + let (ctorConst, ctorTy) ← mkConstWithFreshMVarLevels sInfo.ctorName + let (ctorApplied, instGoals, afterParamsTy) ← insertImplicitArgs 16 ctorConst ctorTy [] + let (_, ctorParamMVars) := getAppFnArgs ctorApplied + unifyExprPairs fuel (ctorParamMVars.toList.zip expArgs.toList) + let rec elabStructFieldsLoop : List StructFieldInfo → Ix.Expr → Ix.Expr → IxElabM Ix.Expr + | [], curFn, _ => pure curFn + | fInfo :: rest, curFn, curTy => do + let curTyWhnf ← whnf fuel curTy + let (domTy, nextBody) ← match stripMData curTyWhnf with + | .forallE _ d b _ _ => pure (d, b) + | _ => throwElabError (str% "unexpected constructor type for structure") (some stx) + let fValExpr ← match assignedMap.get? fInfo.fieldName with + | some vStx => elabRec vStx (some domTy) + | none => + match baseExpr?, fInfo.defaultVal with + | some bExpr, _ => + pure (Expr.mkProj structName fInfo.fieldIdx bExpr) + | none, some defStx => + elabRec defStx (some domTy) + | none, none => + throwElabError (str% "missing field in structure") (some stx) + elabStructFieldsLoop rest (Expr.mkApp curFn fValExpr) (instantiate1 nextBody fValExpr) + let curFn ← elabStructFieldsLoop sInfo.fields.toList ctorApplied afterParamsTy + solveInstGoals fuel instGoals.reverse + ensureHasType fuel stx curFn (some expTy) + | _ => + throwElabError "structure literal '{ ... }' requires a known structure type" (some stx) + +/-- Helper: elaborate `if [h :] cond then t else e`. -/ +def elabTermIf (fuel : Nat) (elabRec : Stx → Option Ix.Expr → IxElabM Ix.Expr) + (stx : Stx) (args : Stx) (expectedType? : Option Ix.Expr) : IxElabM Ix.Expr := do + let isDep := args.size == 8 + let condStx := if isDep then args.getD 3 .missing else args.getD 2 .missing + let thenStx := if isDep then args.getD 5 .missing else args.getD 4 .missing + let elseStx := if isDep then args.getD 7 .missing else args.getD 6 .missing + let st ← get + if isDep then + let hId := + let raw := Syntax.getId (args.getD 1 .missing) + if Name.isAnonymous raw then Name.simple (str% "h") else raw + let condProp ← elabRec condStx (some Expr.mkProp) + let notCondProp := Expr.mkApp (Expr.mkConst (Name.simple (str% "Not")) #[]) condProp + let branchTy ← match expectedType? with + | some t => pure t + | none => + let u ← mkFreshLevelMVar + mkFreshExprMVar (Expr.mkSort u) + let thenLam ← withLocalDecl hId condProp .default default fun hFv _ => do + let tVal ← elabRec thenStx (some branchTy) + mkLambdaFVars #[hFv] tVal + let elseLam ← withLocalDecl hId notCondProp .default default fun hFv _ => do + let eVal ← elabRec elseStx (some branchTy) + mkLambdaFVars #[hFv] eVal + let branchSort ← ensureSort 32 branchTy + let decTy := Expr.mkApp (Expr.mkConst (Name.simple (str% "Decidable")) #[]) condProp + let decInst ← match ← synthInstance? 8 decTy with + | some inst => pure inst + | none => mkFreshExprMVar decTy + let diteConst := Expr.mkConst (Name.simple (str% "dite")) #[branchSort] + let res := Expr.mkAppN diteConst #[branchTy, condProp, decInst, thenLam, elseLam] + ensureHasType fuel stx res expectedType? + else if st.env.contains (Name.mkStr2 (str% "Bool") (str% "casesOn")) then + let boolAttempt? ← observing? do + let boolTy := Expr.mkConst (Name.simple (str% "Bool")) #[] + let condExpr ← elabRec condStx (some boolTy) + let branchTy ← match expectedType? with + | some t => pure t + | none => + let u ← mkFreshLevelMVar + mkFreshExprMVar (Expr.mkSort u) + let thenExpr ← elabRec thenStx (some branchTy) + let elseExpr ← elabRec elseStx (some branchTy) + let branchSort ← ensureSort 32 branchTy + let motive := Expr.mkLam (Name.simple (str% "b")) boolTy (liftLooseBVars branchTy 1) .default + let casesOnConst := Expr.mkConst (Name.mkStr2 (str% "Bool") (str% "casesOn")) #[branchSort] + let res := Expr.mkAppN casesOnConst #[motive, condExpr, elseExpr, thenExpr] + ensureHasType fuel stx res expectedType? + match boolAttempt? with + | some res => pure res + | none => + let iteId := Syntax.mkSimpleIdent (Name.simple (str% "ite")) + let appStx := #[condStx, thenStx, elseStx].foldl + (fun acc a => Syntax.mkNode SyntaxKind.appTerm #[acc, a]) iteId + elabRec appStx expectedType? + else + let iteId := Syntax.mkSimpleIdent (Name.simple (str% "ite")) + let appStx := #[condStx, thenStx, elseStx].foldl + (fun acc a => Syntax.mkNode SyntaxKind.appTerm #[acc, a]) iteId + elabRec appStx expectedType? + +/-- Helper: elaborate `match d with | pat => rhs ...`. -/ +def elabTermMatch (fuel : Nat) (elabRec : Stx → Option Ix.Expr → IxElabM Ix.Expr) + (stx : Stx) (args : Stx) (expectedType? : Option Ix.Expr) : IxElabM Ix.Expr := do + let discrs := Syntax.getArgs (args.getD 1 .missing) + let alts := Syntax.getArgs (args.getD 3 .missing) + if discrs.isEmpty then + throwElabError "match expression requires at least one discriminant" (some stx) + let discrStx := discrs.getD 0 .missing + let discrExpr ← elabRec discrStx none + let discrTy ← inferType fuel discrExpr + let discrTyWhnf ← whnf fuel discrTy + let (headFn, headArgs) := getAppFnArgs discrTyWhnf + let resTy ← match expectedType? with + | some t => pure t + | none => + let u ← mkFreshLevelMVar + mkFreshExprMVar (Expr.mkSort u) + let ctx ← read + let st ← get + match headFn with + | .const indName indUnivs _ => + match st.env.find? indName with + | some (.inductInfo ival) => + let casesOnName := Name.mkStr indName (str% "casesOn") + match st.env.find? casesOnName with + | some (.defnInfo casesOnDef) => + let casesOnUnivs ← + if casesOnDef.cnst.levelParams.size == indUnivs.size + 1 then + let uMot ← ensureSort 32 resTy + pure (#[uMot] ++ indUnivs) + else + pure indUnivs + let params := headArgs.extract 0 ival.numParams + let indices := headArgs.extract ival.numParams headArgs.size + let afterParamsInst := params.foldl (fun cur p => + match stripMData cur with + | .forallE _ _ b _ _ => instantiate1 b p + | other => other) (substExprLevelParams ival.cnst.levelParams indUnivs ival.cnst.type) + let (idxFVars, idxDecls, _) := openForallTelescope ival.numIndices afterParamsInst (str% "midx") 0 #[] #[] + let majDom := Expr.mkAppN (Expr.mkConst indName indUnivs) (params ++ idxFVars) + let (majFvId, _) := mkAuxFVar (str% "mmaj") 0 + let majDecl : AuxLocalDecl := { fvarId := majFvId, binderName := Name.simple (str% "x"), domain := majDom } + let motiveLam := closeLambdas (idxDecls.push majDecl) resTy + let rec elabMatchCtors : List Ix.Name → List Ix.Expr → IxElabM (Array Ix.Expr) + | [], revMinors => pure (Array.mk revMinors.reverse) + | ctorName :: restCtors, revMinors => do + match st.env.find? ctorName with + | some (.ctorInfo cval) => + let matchedAlt? := alts.findSome? fun altStx => + let pats := Syntax.getArgs (Syntax.getArg altStx 1) + let pat0 := pats.getD 0 .missing + let rhsStx := Syntax.getArg altStx 3 + if Syntax.isOfKind pat0 SyntaxKind.anonCtor && ival.ctors.size == 1 then + let pElems := Syntax.getArgs (Syntax.getArg pat0 1) + if cval.numFields >= 2 && pElems.size > cval.numFields then + let preIds := (pElems.extract 0 (cval.numFields - 1)).map fun a => + if Syntax.isOfKind a SyntaxKind.holeTerm || Syntax.getAtomVal a == (str% "_") then Name.mkAnon + else Syntax.getId a + let restElems := pElems.extract (cval.numFields - 1) pElems.size + let tmpId := Name.mkNat (Name.simple (str% "_anon_pat")) restElems.size + let nestedPat := Syntax.mkNode SyntaxKind.anonCtor + #[Syntax.mkSimpleAtom (str% "⟨"), Syntax.mkNullNode restElems, Syntax.mkSimpleAtom (str% "⟩")] + let nestedAlt := Syntax.mkNode SyntaxKind.matchAlt + #[Syntax.mkSimpleAtom (str% "|"), Syntax.mkNullNode #[nestedPat], + Syntax.mkSimpleAtom (str% "=>"), rhsStx] + let nestedMatch := Syntax.mkNode SyntaxKind.matchTerm + #[Syntax.mkSimpleAtom (str% "match"), Syntax.mkNullNode #[Syntax.mkSimpleIdent tmpId], + Syntax.mkSimpleAtom (str% "with"), Syntax.mkNullNode #[nestedAlt]] + some (some (preIds.push tmpId), none, nestedMatch) + else + let varNames := pElems.map fun a => + if Syntax.isOfKind a SyntaxKind.holeTerm || Syntax.getAtomVal a == (str% "_") then Name.mkAnon + else Syntax.getId a + some (some varNames, none, rhsStx) + else + match decodeConstructorPattern ctx.scope ctx.modIdx st.env pat0 with + | some (patCtor, varNames) => + if patCtor == ctorName then some (some varNames, none, rhsStx) + else none + | none => + let catchVar := + if Syntax.isOfKind pat0 SyntaxKind.holeTerm || Syntax.getAtomVal pat0 == (str% "_") then + Name.mkAnon + else + Syntax.getId pat0 + some (none, some catchVar, rhsStx) + match matchedAlt? with + | none => + throwElabError (str% "non-exhaustive match") (some stx) + | some (ctorVars?, catchVar?, rhsStx) => + let ctorInstTy := params.foldl (fun cur p => + match stripMData cur with + | .forallE _ _ b _ _ => instantiate1 b p + | other => other) (substExprLevelParams cval.cnst.levelParams indUnivs cval.cnst.type) + let rec elabCtorFields (remFields : Nat) (curCtorTy : Ix.Expr) + (fIdx : Nat) (fvarIds : Array Ix.Name) (fvarExprs : Array Ix.Expr) : IxElabM Ix.Expr := do + match remFields with + | 0 => + match catchVar? with + | some vName => + if !Name.isAnonymous vName then + let ctorApp := Expr.mkAppN (Expr.mkConst ctorName indUnivs) (params ++ fvarExprs) + let ctorAppTy ← inferType fuel ctorApp + withLetDecl vName ctorAppTy ctorApp default .value false fun _ _ => do + let rhsExpr ← elabRec rhsStx (some resTy) + mkLambdaFVars fvarIds rhsExpr + else + let rhsExpr ← elabRec rhsStx (some resTy) + mkLambdaFVars fvarIds rhsExpr + | none => + let rhsExpr ← elabRec rhsStx (some resTy) + mkLambdaFVars fvarIds rhsExpr + | rem + 1 => + let curW ← whnf fuel curCtorTy + match stripMData curW with + | .forallE defName fDom fBody _ _ => + let userVarName := match ctorVars? with + | some vs => + let vn := vs.getD fIdx Name.mkAnon + if Name.isAnonymous vn then defName else vn + | none => defName + withLocalDecl userVarName fDom .default default fun fvId fvExpr => + elabCtorFields rem (instantiate1 fBody fvExpr) (fIdx + 1) + (fvarIds.push fvId) (fvarExprs.push fvExpr) + | _ => + throwElabError (str% "unexpected constructor type") (some stx) + let minorLam ← elabCtorFields cval.numFields ctorInstTy 0 #[] #[] + elabMatchCtors restCtors (minorLam :: revMinors) + | _ => + throwElabError (str% "missing constructor info") (some stx) + let minorExprs ← elabMatchCtors ival.ctors.toList [] + let casesOnConst := Expr.mkConst casesOnName casesOnUnivs + let fullApp := Expr.mkAppN casesOnConst + (params ++ #[motiveLam] ++ indices ++ #[discrExpr] ++ minorExprs) + ensureHasType fuel stx fullApp (some resTy) + | _ => + throwElabError (str% "casesOn not found for match expression") (some stx) + | _ => + throwElabError (str% "discriminant type is not an inductive type") (some stx) + | _ => + throwElabError (str% "match discriminant must have an inductive type") (some discrStx) + +/-- Helper: elaborate function application `f a₁ ... aₙ`. -/ +def elabTermApp (fuel : Nat) (elabRec : Stx → Option Ix.Expr → IxElabM Ix.Expr) + (stx : Stx) (expectedType? : Option Ix.Expr) : IxElabM Ix.Expr := do + let (fnStx, argStxs) := flattenAppSyntax 256 stx [] + let isExplicitAt := + Syntax.isOfKind fnStx SyntaxKind.explicitTerm && + Syntax.getAtomVal (Syntax.getArg fnStx 0) == (str% "@") + let (fnExpr, fnTy) ← match fnStx with + | .ident .. => elabIdentWithLevelsAndType fuel fnStx none + | _ => do + let e ← elabRec fnStx none + let t ← inferType fuel e + pure (e, t) + let rec applyAppArgs : List Stx → Ix.Expr → Ix.Expr → List Ix.Expr → IxElabM (Ix.Expr × Ix.Expr × List Ix.Expr) + | [], curFn, curTy, pending => pure (curFn, curTy, pending) + | argStx :: rest, curFn, curTy, pending => do + let (curFn, pending, curTy) ← + if !isExplicitAt then insertImplicitArgs 16 curFn curTy pending + else pure (curFn, pending, curTy) + let curTyWhnf ← whnfForall fuel curTy + match stripMData curTyWhnf with + | .forallE _ dom body _ _ => + let argExpr ← elabRec argStx (some dom) + applyAppArgs rest (Expr.mkApp curFn argExpr) (instantiate1 body argExpr) pending + | _ => + let u1 ← mkFreshLevelMVar + let u2 ← mkFreshLevelMVar + let domMVar ← mkFreshExprMVar (Expr.mkSort u1) + let codMVar ← mkFreshExprMVar (Expr.mkSort u2) + let arrowTy := Expr.mkArrow domMVar (liftLooseBVars codMVar 1) + let _ ← isDefEq fuel curTyWhnf arrowTy + let argExpr ← elabRec argStx (some domMVar) + applyAppArgs rest (Expr.mkApp curFn argExpr) codMVar pending + let (curFn, curTy, pendingInstGoals) ← applyAppArgs argStxs.toList fnExpr fnTy [] + solveInstGoals fuel pendingInstGoals.reverse + ensureHasKnownType fuel stx curFn curTy expectedType? + +/-- Main bidirectional term elaborator, parameterized by a tactic handler + and structurally recursive on `fuel : Nat`. -/ +def elabTermWith + (evalTacticFn : (Stx → Option Ix.Expr → IxElabM Ix.Expr) → Nat → Stx → Ix.Name → IxElabM Unit) : + Nat → Stx → Option Ix.Expr → IxElabM Ix.Expr + | 0, stx, _ => throwElabError (str% "elaborator fuel exhausted in term") (some stx) + | fuel + 1, stx0, expectedType? => withRef stx0 do + let stx ← expandMacroM 16 stx0 + let elabRec (s : Stx) (exp? : Option Ix.Expr) : IxElabM Ix.Expr := + elabTermWith evalTacticFn fuel s exp? + match stx with + | .missing | .snil | .scons .. => + throwElabError "missing syntax node in term" + -- 1. Bare identifier + | .ident .. => + let (e, eTy) ← elabIdentWithLevelsAndType fuel stx none + ensureHasKnownType fuel stx e eTy expectedType? + -- 2. Bare `true` / `false` atoms + | .atom _ valSym => + let val := Sym.toString valSym + if val == (str% "true") || val == (str% "false") then + let boolCtor := Name.mkStr2 (str% "Bool") val + let st ← get + let targetName := if st.env.contains boolCtor then boolCtor else Name.simple val + let (e, _) ← mkConstWithFreshMVarLevels targetName + ensureHasType fuel stx e expectedType? + else + throwElabError (str% "unexpected atom in term") (some stx) + -- 3. Composite syntax nodes + | .node _ kindF args => + let kind := FName.toIxName kindF + -- 3.1. Hole `_` + if kind == SyntaxKind.holeTerm then + let ty ← match expectedType? with + | some t => pure t + | none => + let u ← mkFreshLevelMVar + mkFreshExprMVar (Expr.mkSort u) + mkFreshExprMVar ty + -- 3.2. `Prop` (`Sort 0`) + else if kind == SyntaxKind.propTerm then + ensureHasType fuel stx Expr.mkProp expectedType? + -- 3.3. `Type [u]` (`Sort (u + 1)`) + else if kind == SyntaxKind.typeTerm then + let argNode := args.getD 1 .missing + let lvl ← + if Syntax.isNone argNode || Syntax.isMissing argNode then + pure Level.mkZero + else if Syntax.isOfKind argNode SyntaxKind.nullKind then + match Syntax.getOptional? argNode with + | some lStx => elabLevel fuel lStx + | none => pure Level.mkZero + else + elabLevel fuel argNode + let res := Expr.mkSort (Level.mkSucc lvl) + ensureHasType fuel stx res expectedType? + -- 3.4. `Sort [u]` + else if kind == SyntaxKind.sortTerm then + let optNode := args.getD 1 .missing + let lvl ← match Syntax.getOptional? optNode with + | some lStx => elabLevel fuel lStx + | none => pure Level.mkZero + let res := Expr.mkSort lvl + ensureHasType fuel stx res expectedType? + -- 3.5. Numeric literal + else if kind == SyntaxKind.numLit then + let numStr := Syntax.getAtomVal (args.getD 0 .missing) + let n := (parseNatLiteral numStr).getD 0 + let rawLit := Expr.mkNatLit n + let st ← get + let ofNatName := Name.mkStr2 (str% "OfNat") (str% "ofNat") + let instOfNatNatName := Name.simple (str% "instOfNatNat") + let natConst := Expr.mkConst (Name.simple (str% "Nat")) #[] + let litExpr := + if st.env.contains ofNatName && st.env.contains instOfNatNatName then + let instExpr := Expr.mkApp (Expr.mkConst instOfNatNatName #[]) rawLit + Expr.mkAppN (Expr.mkConst ofNatName #[Level.mkZero]) #[natConst, rawLit, instExpr] + else + rawLit + ensureHasKnownType fuel stx litExpr natConst expectedType? + -- 3.6. String literal + else if kind == SyntaxKind.strLit then + let strVal := Syntax.getAtomVal (args.getD 0 .missing) + let litExpr := Expr.mkStrLit strVal + ensureHasType fuel stx litExpr expectedType? + -- 3.7. Character literal `'c'` (`Char.ofNat code` or nat literal fallback) + else if kind == SyntaxKind.charLit then + let chStr := Syntax.getAtomVal (args.getD 0 .missing) + let code := match decodeUtf8Codepoints (Sym.ofString chStr) with + | c :: _ => c + | [] => 0 + let st ← get + let charOfNat := Name.mkStr2 (str% "Char") (str% "ofNat") + let res := + if st.env.contains charOfNat then + Expr.mkApp (Expr.mkConst charOfNat #[]) (Expr.mkNatLit code) + else + Expr.mkNatLit code + ensureHasType fuel stx res expectedType? + -- 3.8. Content-hash reference `#<64-hex>` + else if kind == SyntaxKind.hashRef then + let hexStr := Syntax.getAtomVal (args.getD 0 .missing) + match parseHexAddress hexStr with + | none => throwElabError (str% "invalid 64-hex-char content address") (some stx) + | some addr => + let st ← get + let foundName? := st.env.constOrder.find? fun nm => + Name.computeHash nm == addr || st.env.importMap.lookupName? nm == some addr + match foundName? with + | some nm => + let (e, _) ← mkConstWithFreshMVarLevels nm + ensureHasType fuel stx e expectedType? + | none => + throwElabError (str% "unresolved content address") (some stx) + -- 3.9. Explicit `@ident.{u, v}` or `ident.{u, v}` (`SyntaxKind.explicitTerm`) + else if kind == SyntaxKind.explicitTerm then + let isAt := Syntax.getAtomVal (args.getD 0 .missing) == (str% "@") + let idStx := if isAt then args.getD 1 .missing else args.getD 0 .missing + let univsNode := if isAt then args.getD 2 .missing else args.getD 1 .missing + let explicitLvls? ← + if Syntax.isNone univsNode then + pure none + else + let ls ← elabLevelList fuel (Syntax.getArgs univsNode).toList [] + pure (some ls) + let e ← elabIdentWithLevels fuel idStx explicitLvls? + if isAt then + match expectedType? with + | none => return e + | some expTy => + let actTy ← inferType fuel e + let ok ← isDefEq fuel actTy expTy + if !ok then throwElabError "type mismatch on @-explicit term" (some stx) + instantiateMVars 16 e + else + ensureHasType fuel stx e expectedType? + -- 3.10. Type ascription `(e : vPref T)` + else if kind == SyntaxKind.typeAscription then + let termStx := args.getD 1 .missing + let tyStx := args.getD 4 .missing + let ascTy ← elabRec tyStx none + let _ ← ensureSort 32 ascTy + let e ← elabRec termStx (some ascTy) + ensureHasType fuel stx e expectedType? + -- 3.11. Non-dependent function arrow `A → !B` (`SyntaxKind.arrowTerm`) + else if kind == SyntaxKind.arrowTerm then + let domStx := args.getD 0 .missing + let vPrefNode := args.getD 2 .missing + let codStx := args.getD 3 .missing + let isExpProp : Bool := match expectedType? with + | some (.sort (.zero _) _) => true + | _ => false + let domTy ← elabRec domStx none + let _ ← ensureSortIfNotForall 32 domTy + let retContract := (decodeContractPrefix vPrefNode).toValueContract + let codTy ← withLocalDecl Name.mkAnon domTy .default default fun fvId _ => do + let cTy ← elabRec codStx (if isExpProp then some Expr.mkProp else none) + if !isExpProp then + let _ ← ensureSortIfNotForall 32 cTy + return abstractFVar fvId cTy + let arrowExpr := Expr.mkForallContract Name.mkAnon domTy codTy .default default retContract + if isExpProp then + instantiateMVars 16 arrowExpr + else + ensureHasType fuel stx arrowExpr expectedType? + -- 3.12. Dependent Pi `forall binders, vPref body` or `(binders) → vPref body` (`SyntaxKind.forallTerm`) + else if kind == SyntaxKind.forallTerm then + let isKw := match args[0]? with + | some (.atom _ kw) => Sym.beq kw (s% "forall") || Sym.beq kw (s% "∀") + | _ => false + let bindersNode := if isKw then args.getD 1 .missing else args.getD 0 .missing + let vPrefNode := if isKw then args.getD 3 .missing else args.getD 2 .missing + let bodyStx := if isKw then args.getD 4 .missing else args.getD 3 .missing + let retContract := (decodeContractPrefix vPrefNode).toValueContract + let isExpProp : Bool := match expectedType? with + | some (.sort (.zero _) _) => true + | _ => false + let groups := (Syntax.getArgs bindersNode).toList.map decodeBinderNode + let piExpr ← elabBinderGroups elabRec groups #[] fun fvars => do + let bodyTy ← elabRec bodyStx (if isExpProp then some Expr.mkProp else none) + if !isExpProp then + let _ ← ensureSortIfNotForall 32 bodyTy + mkForallFVars fvars bodyTy retContract + if isExpProp then + instantiateMVars 16 piExpr + else + ensureHasType fuel stx piExpr expectedType? + -- 3.13. Lambda `fun binders => body` + else if kind == SyntaxKind.funTerm then + elabTermFun fuel elabRec stx args expectedType? + -- 3.14. `let` and `let borrow` + else if kind == SyntaxKind.letTerm || kind == SyntaxKind.letBorrowTerm then + elabTermLet fuel elabRec stx kind args expectedType? + -- 3.14b. `let rec` + else if kind == SyntaxKind.letRecTerm then + elabTermLetRec fuel elabRec stx args expectedType? + -- 3.15. `have h [: T] := v; body` + else if kind == SyntaxKind.haveTerm then + let idStx := args.getD 1 .missing + let optTyNode := args.getD 2 .missing + let valStx := args.getD 4 .missing + let bodyStx := args.getD 6 .missing + let hName := + let id := Syntax.getId idStx + if Name.isAnonymous id then Name.simple (str% "h") else id + let expTy? ← + if Syntax.getNumArgs optTyNode >= 2 then + let t ← elabRec (Syntax.getArg optTyNode 1) none + let _ ← ensureSort 32 t + pure (some t) + else + pure none + let vExpr ← elabRec valStx expTy? + let vTy ← match expTy? with + | some t => pure t + | none => inferType fuel vExpr + withLetDecl hName vTy vExpr default .value true fun fvId _ => do + let bodyExpr ← elabRec bodyStx expectedType? + let absBody := abstractFVar fvId bodyExpr + let lc : Ixon.LetContract := { nonDep := true, kind := .value, binder := default } + modify fun st => { st with localLetContracts := st.localLetContracts.push lc } + let res := Expr.mkLetE hName vTy vExpr absBody true + ensureHasType fuel stx res expectedType? + -- 3.16. Projection `base.field` or `base.0` + else if kind == SyntaxKind.projTerm then + let baseStx := args.getD 0 .missing + let fieldStx := args.getD 2 .missing + let baseExpr ← elabRec baseStx none + let projExpr ← elabProjOnExpr fuel baseExpr fieldStx + ensureHasType fuel stx projExpr expectedType? + -- 3.17. Binary infix operator `lhs op rhs` + else if kind == SyntaxKind.binOpTerm then + elabTermBinOp fuel elabRec stx args expectedType? + -- 3.18. Unary operator (`¬`, `!`, `-`) + else if kind == SyntaxKind.unaryOpTerm then + let opSym := Syntax.getAtomVal (args.getD 0 .missing) + let argStx := args.getD 1 .missing + let fnName := + if opSym == (str% "¬") then Name.simple (str% "Not") + else if opSym == (str% "!") then Name.mkStr2 (str% "Bool") (str% "not") + else Name.mkStr2 (str% "Neg") (str% "neg") + let appStx := Syntax.mkNode SyntaxKind.appTerm #[Syntax.mkSimpleIdent fnName, argStx] + elabRec appStx expectedType? + -- 3.19. Anonymous constructor `⟨a₁, ..., aₙ⟩` + else if kind == SyntaxKind.anonCtor then + elabTermAnonCtor fuel elabRec stx args expectedType? + -- 3.20. Structure instance `{ [base with] field₁ := val₁, ... }` + else if kind == SyntaxKind.structInst then + elabTermStructInst fuel elabRec stx args expectedType? + -- 3.21. Tuple `(a, b, ...)` + else if kind == SyntaxKind.tupleTerm then + if args.size == 2 then + let st ← get + let unitCtor := + if st.env.contains (Name.mkStr2 (str% "Unit") (str% "unit")) then Name.mkStr2 (str% "Unit") (str% "unit") + else Name.mkStr2 (str% "PUnit") (str% "unit") + let (e, _) ← mkConstWithFreshMVarLevels unitCtor + ensureHasType fuel stx e expectedType? + else + let first := args.getD 1 .missing + let rest := (Syntax.getArgs (args.getD 3 .missing)).toList + let allElems := first :: rest + let rec buildPairs : List Stx → Stx + | [] => Syntax.mkSimpleIdent (Name.mkStr2 (str% "Unit") (str% "unit")) + | [x] => x + | x :: xs => + let rhs := buildPairs xs + let prodMk := Syntax.mkSimpleIdent (Name.mkStr2 (str% "Prod") (str% "mk")) + Syntax.mkNode SyntaxKind.appTerm + #[Syntax.mkNode SyntaxKind.appTerm #[prodMk, x], rhs] + elabRec (buildPairs allElems) expectedType? + -- 3.22. List literal `[a, b, c]` + else if kind == SyntaxKind.listLit then + let elems := (Syntax.getArgs (args.getD 1 .missing)).toList + let rec buildList : List Stx → Stx + | [] => Syntax.mkSimpleIdent (Name.mkStr2 (str% "List") (str% "nil")) + | x :: xs => + let tail := buildList xs + let consId := Syntax.mkSimpleIdent (Name.mkStr2 (str% "List") (str% "cons")) + Syntax.mkNode SyntaxKind.appTerm + #[Syntax.mkNode SyntaxKind.appTerm #[consId, x], tail] + elabRec (buildList elems) expectedType? + -- 3.23. `if [h :] cond then t else e` + else if kind == SyntaxKind.ifTerm then + elabTermIf fuel elabRec stx args expectedType? + -- 3.24. Pattern matching `match d with | pat => rhs ...` + else if kind == SyntaxKind.matchTerm then + elabTermMatch fuel elabRec stx args expectedType? + -- 3.25. Tactic block `by tac₁; tac₂; ...` + else if kind == SyntaxKind.byTactic then + let tacSeq := args.getD 1 .missing + let goalTy ← match expectedType? with + | some t => pure t + | none => + let u ← mkFreshLevelMVar + mkFreshExprMVar (Expr.mkSort u) + let rootGoal ← mkFreshExprMVar goalTy (Name.simple (str% "goal")) + let rootGoalId := match rootGoal with + | .mvar id _ => id + | _ => Name.mkAnon + evalTacticFn elabRec fuel tacSeq rootGoalId + let solved ← instantiateMVars 32 rootGoal + ensureHasType fuel stx solved expectedType? + -- 3.26. Function application `f a₁ ... aₙ` + else if kind == SyntaxKind.appTerm then + elabTermApp fuel elabRec stx expectedType? + else + throwElabError (str% "unsupported syntax node in term") (some stx) + +/-- Lightweight flat-monad core tactic evaluator for ZK circuits (`rfl`, `exact`, + `assumption`, `trivial`, `done`, and sequential `;` / newline tactic blocks) + with zero `Tactic.lean` / `StateT` / `omega` / `ring` / `simp` overhead. -/ +def evalCoreTacticStep (elabRec : Stx → Option Ix.Expr → IxElabM Ix.Expr) + (fuel : Nat) (tac : Stx) (goalId : Ix.Name) : IxElabM Unit := do + let st ← get + let some gDecl := st.mctx.findDecl? goalId + | throwElabError (str% "unknown goal metavariable") (some tac) + let gTy ← instantiateMVars 32 gDecl.type + let k := Syntax.getKind tac + if k == SyntaxKind.tacticRfl || k == SyntaxKind.tacticTrivial then + let gTyW ← withReader (fun ctx => { ctx with lctx := gDecl.lctx }) (whnf fuel gTy) + let (hFn, hArgs) := getAppFnArgs gTyW + match hFn with + | .const cName cUnivs _ => + if cName == Name.simple (str% "Eq") && hArgs.size == 3 then + let tyArg := hArgs.getD 0 gTyW + let lhs := hArgs.getD 1 gTyW + let rhs := hArgs.getD 2 gTyW + let ok ← withReader (fun ctx => { ctx with lctx := gDecl.lctx }) (isDefEq fuel lhs rhs) + if !ok then + throwElabError (str% "'rfl' failed: sides are not definitionally equal") (some tac) + let reflExpr := Expr.mkAppN (Expr.mkConst (Name.mkStr2 (str% "Eq") (str% "refl")) #[cUnivs.getD 0 Level.mkZero]) #[tyArg, lhs] + modify fun s => { s with mctx := s.mctx.assignExpr goalId reflExpr } + else if cName == Name.simple (str% "True") && hArgs.isEmpty then + modify fun s => { s with mctx := s.mctx.assignExpr goalId (Expr.mkConst (Name.mkStr2 (str% "True") (str% "intro")) #[]) } + else + throwElabError (str% "'rfl' failed: goal is not a reflexive equality") (some tac) + | _ => + throwElabError (str% "'rfl' failed: goal is not an equality") (some tac) + else if k == SyntaxKind.tacticExact then + let termStx := Syntax.getArg tac 1 + let val ← withReader (fun ctx => { ctx with lctx := gDecl.lctx }) (elabRec termStx (some gTy)) + let valInst ← instantiateMVars 32 val + modify fun s => { s with mctx := s.mctx.assignExpr goalId valInst } + else if k == SyntaxKind.tacticAssumption then + let rec findMatch : List LocalDecl → IxElabM (Option Ix.Expr) + | [] => pure none + | d :: rest => do + let dTy ← instantiateMVars 16 d.type + let ok ← withReader (fun ctx => { ctx with lctx := gDecl.lctx }) (isDefEq fuel dTy gTy) + if ok then pure (some (Expr.mkFVar d.fvarId)) else findMatch rest + match ← findMatch gDecl.lctx.revDecls with + | some fv => modify fun s => { s with mctx := s.mctx.assignExpr goalId fv } + | none => throwElabError (str% "'assumption' failed") (some tac) + else if k == SyntaxKind.tacticDone then + pure () + else + throwElabError (str% "tactic requires full tactic prover") (some tac) + +def evalCoreTacticSeq (elabRec : Stx → Option Ix.Expr → IxElabM Ix.Expr) + (fuel : Nat) (tacSeq : Stx) (rootGoalId : Ix.Name) : IxElabM Unit := do + let k := Syntax.getKind tacSeq + if k == SyntaxKind.tacticSeq || k == SyntaxKind.nullKind then + let rec runList : List Stx → IxElabM Unit + | [] => pure () + | t :: rest => do + evalCoreTacticStep elabRec fuel t rootGoalId + runList rest + runList (Syntax.getArgs tacSeq).toList + else + evalCoreTacticStep elabRec fuel tacSeq rootGoalId + +/-- Full bidirectional term elaborator (with the complete tactic engine). -/ +def elabTerm (fuel : Nat) (stx : Stx) (expectedType? : Option Ix.Expr) : IxElabM Ix.Expr := + elabTermWith evalTacticSeq fuel stx expectedType? + +/-- Core bidirectional term elaborator (compact flat-monad core tactics for ZK circuits). -/ +def elabTermCore (fuel : Nat) (stx : Stx) (expectedType? : Option Ix.Expr) : IxElabM Ix.Expr := + elabTermWith evalCoreTacticSeq fuel stx expectedType? + +/-- First-order entry wrapper for `elabTermCore` (explicit `ctx`, `st`). -/ +def elabTermCorePure (ctx : ElabContext) (st : ElabState) (fuel : Nat) (stx : Stx) + (expectedType? : Option Ix.Expr) : ElabRes Ix.Expr := + elabTermCore fuel stx expectedType? ctx st + +end Ix.Frontend.Elab diff --git a/Ix/Frontend/Format.lean b/Ix/Frontend/Format.lean new file mode 100644 index 0000000000..e800fb2b9b --- /dev/null +++ b/Ix/Frontend/Format.lean @@ -0,0 +1,692 @@ +/- + Ix.Frontend.Format: Pure, Total Surface Syntax Pretty-Printer & Round-Trip Formatter + for the Ix Frontend and `IxVCS` Merge Engine. + + Features: + - 100% pure, total, and kernel-reducible (`Nat.rec` / `List.rec` structural recursion, + using `strAppendPure` and `strIntercalatePure` with zero `@[extern]` blockers). + - Formats `Stx` (`formatSyntax`), `ModuleSchedule` (`formatModuleSchedule`), + and `MergeOutcome` (`formatMergeOutcome`) back to valid, re-parseable `.ix` / `.lean` + surface text, including first-class `.#merge` identifiers (`foo.#merge._1`), + substructural mode attributes (`@[unique]`, `@[borrowed]`, `@[once]`, `@[erased]`, + `@[shared]`, `let @[borrow]`), tactics, macros, + structures, inductives, and `#merge ... end` blocks. +-/ +module + +public import Ix.Frontend.Merge + +@[expose] public section + +namespace Ix.Frontend + +open Ix.Frontend.Parser +open Ix.Frontend.Elab + +/-! ## String & Identifier Escaping Helpers -/ + +/-- Escape special characters inside a string literal. -/ +def escapeStringChars : List Char → List Char + | [] => [] + | '"' :: cs => '\\' :: '"' :: escapeStringChars cs + | '\\' :: cs => '\\' :: '\\' :: escapeStringChars cs + | '\n' :: cs => '\\' :: 'n' :: escapeStringChars cs + | '\t' :: cs => '\\' :: 't' :: escapeStringChars cs + | '\r' :: cs => '\\' :: 'r' :: escapeStringChars cs + | c :: cs => c :: escapeStringChars cs + +def formatStringLiteral (s : String) : String := + "\"" ++ String.ofList (escapeStringChars s.toList) ++ "\"" + +def formatCharLiteral (s : String) : String := + match s.toList with + | ['\''] => "'\\''" + | ['\\'] => "'\\\\'" + | ['\n'] => "'\\n'" + | ['\t'] => "'\\t'" + | ['\r'] => "'\\r'" + | c :: _ => "'" ++ String.singleton c ++ "'" + | [] => "'\\x00'" + +/-- True if a single identifier component `part` requires French quotes `«...»`. -/ +def componentNeedsEscape (part : String) : Bool := + if part == "#merge" || part == "_" then false + else if defaultKeywords.contains (Sym.ofString part) then true + else + let bs := Sym.ofString part + match bs with + | .nil => true + | .cons b rest => + if !isAsciiIdFirstByte b && (scanUtf8LetterLike bs).isNone then true + else + let (rem, _, _) := scanIdentRestBytes parseFuel rest 0 .nil + !Sym.isEmpty rem + +/-- Format a hierarchical `Ix.Name` for surface syntax output, preserving `.#merge` segments + and escaping reserved keyword components with `«...»`. -/ +def formatSurfaceName (nm : Ix.Name) : String := + if Name.isAnonymous nm then "_" + else + let parts := (Name.components nm).map fun p => + if componentNeedsEscape p then "«" ++ p ++ "»" else p + strIntercalatePure "." parts + +/-- Join non-empty formatted strings with `sep`. -/ +def joinNonEmpty (sep : String) (xs : List String) : String := + strIntercalatePure sep (xs.filter (fun s => !(s == ""))) + +/-- Extract the surface text of a token node (`.atom` or `.ident`). -/ +def formatTokenVal : Stx → String + | .atom _ val => Sym.toString val + | .ident _ _ id => strIntercalatePure "." (Name.components (FName.toIxName id)) + | _ => "" + +/-! ## Core Structural `Syntax` Pretty-Printer (`formatSyntaxAux`) -/ + +/-- Format a list of `Stx` nodes using `fmtOne` and join with `sep`. -/ +def formatSyntaxList (fmtOne : Stx → String) (sep : String) : List Stx → String + | [] => "" + | [x] => fmtOne x + | x :: xs => fmtOne x ++ sep ++ formatSyntaxList fmtOne sep xs + +/-- Format a contract prefix node (`binderPrefix` or `valuePrefix`) as `@[m₁, m₂] `, + adding a trailing space when non-empty. -/ +def formatPrefixSpace (stx : Stx) : String := + let atoms := (Syntax.getArgs stx).toList.map Syntax.getAtomVal |>.filter (fun s => !(s == "")) + if atoms.isEmpty then "" + else "@[" ++ strIntercalatePure ", " atoms ++ "] " + +/-- Format universe parameter list `.{u, v}` if non-empty. -/ +def formatUnivParamsNode (stx : Stx) : String := + let args := (Syntax.getArgs stx).toList + if args.isEmpty then "" + else + let names := args.map fun a => formatSurfaceName (Syntax.getId a) + ".{" ++ strIntercalatePure ", " names ++ "}" + +/-- Format declaration modifiers (`@[simp]`, `private`, `protected`, `noncomputable`, etc.). -/ +def formatModifiersNode (stx : Stx) : String := + let args := (Syntax.getArgs stx).toList + if args.isEmpty then "" + else + let attrs := args.filterMap fun a => + match a with + | .ident _ _ idF => + let id := FName.toIxName idF + if Name.isAnonymous id then none else some (formatSurfaceName id) + | _ => none + let kwMods := args.filterMap fun a => + match a with + | .atom _ v => if Sym.isEmpty v then none else some (Sym.toString v) + | _ => none + let attrPart := + if attrs.isEmpty then "" + else "@[" ++ strIntercalatePure ", " attrs ++ "] " + let kwPart := + if kwMods.isEmpty then "" + else strIntercalatePure " " kwMods ++ " " + attrPart ++ kwPart + +/-- Main structurally recursive `Stx` formatter (`fuel : Nat`). -/ +def formatSyntaxAux : Nat → Stx → String + | 0, _ => "_" + | fuel + 1, stx => + let fmt (s : Stx) : String := formatSyntaxAux fuel s + let fmtAtom (s : Stx) : String := + match s with + | .node _ kF _ => + let k := FName.toIxName kF + if k == SyntaxKind.appTerm || k == SyntaxKind.binOpTerm || k == SyntaxKind.unaryOpTerm || + k == SyntaxKind.arrowTerm || k == SyntaxKind.forallTerm || k == SyntaxKind.funTerm || + k == SyntaxKind.letTerm || k == SyntaxKind.letBorrowTerm || k == SyntaxKind.letRecTerm || + k == SyntaxKind.haveTerm || k == SyntaxKind.ifTerm || k == SyntaxKind.matchTerm || + k == SyntaxKind.byTactic || k == SyntaxKind.calcTerm then + "(" ++ fmt s ++ ")" + else fmt s + | _ => fmt s + match stx with + | .missing | .snil | .scons .. => "" + | .atom _ val => Sym.toString val + | .ident _ _ id => formatSurfaceName (FName.toIxName id) + | .node _ kindF args => + let kind := FName.toIxName kindF + let argList := args.toList + let getA (i : Nat) : Stx := Syntax.listGetD argList i .missing + if kind == SyntaxKind.nullKind then + joinNonEmpty " " (argList.map fmt) + else if kind == SyntaxKind.moduleKind then + joinNonEmpty "\n\n" (argList.map fmt) + else if kind == SyntaxKind.univParamsKind then + formatUnivParamsNode stx + else if kind == SyntaxKind.modifiersKind then + formatModifiersNode stx + else if kind == SyntaxKind.binderPrefix || kind == SyntaxKind.valuePrefix then + let atoms := argList.map Syntax.getAtomVal |>.filter (fun s => !(s == "")) + if atoms.isEmpty then "" else "@[" ++ strIntercalatePure ", " atoms ++ "]" + -- Literals & Atomic Terms + else if kind == SyntaxKind.hashRef then + "#" ++ Syntax.getAtomVal (getA 0) + else if kind == SyntaxKind.numLit then + Syntax.getAtomVal (getA 0) + else if kind == SyntaxKind.strLit then + formatStringLiteral (Syntax.getAtomVal (getA 0)) + else if kind == SyntaxKind.charLit then + formatCharLiteral (Syntax.getAtomVal (getA 0)) + else if kind == SyntaxKind.holeTerm then + "_" + else if kind == SyntaxKind.sorryTerm then + "sorry" + else if kind == SyntaxKind.propTerm then + "Prop" + else if kind == SyntaxKind.typeTerm then + let optLvl := getA 1 + if Syntax.isNone optLvl || Syntax.isMissing optLvl then "Type" + else "Type " ++ fmtAtom optLvl + else if kind == SyntaxKind.sortTerm then + let optLvl := getA 1 + if Syntax.isNone optLvl || Syntax.isMissing optLvl then "Sort" + else "Sort " ++ fmtAtom optLvl + else if kind == SyntaxKind.antiquotTerm then + "$" ++ fmt (getA 1) + else if kind == SyntaxKind.macroCall then + joinNonEmpty " " (argList.map fmtAtom) + -- Universe Levels + else if kind == SyntaxKind.levelAdd then + "(" ++ fmt (getA 0) ++ " + " ++ fmt (getA 2) ++ ")" + else if kind == SyntaxKind.levelMax then + "(max " ++ formatSyntaxList fmt " " (Syntax.getArgs (getA 1)).toList ++ ")" + else if kind == SyntaxKind.levelIMax then + "(imax " ++ formatSyntaxList fmt " " (Syntax.getArgs (getA 1)).toList ++ ")" + -- Binders + else if kind == SyntaxKind.explicitBinder || kind == SyntaxKind.implicitBinder || + kind == SyntaxKind.strictImplicitBinder then + let (openB, closeB) := + if kind == SyntaxKind.implicitBinder then ("{", "}") + else if kind == SyntaxKind.strictImplicitBinder then ("⦃", "⦄") + else ("(", ")") + let bPref := formatPrefixSpace (getA 0) + let ids := formatSyntaxList fmt " " (Syntax.getArgs (getA 1)).toList + let vPref := formatPrefixSpace (getA 2) + let tyNode := getA 3 + if Syntax.isOfKind tyNode SyntaxKind.binOpTerm && + Syntax.getAtomVal (Syntax.getArg tyNode 0) == "_bound" then + let opSym := Syntax.getAtomVal (Syntax.getArg tyNode 1) + let rhs := fmt (Syntax.getArg tyNode 2) + openB ++ bPref ++ ids ++ " " ++ opSym ++ " " ++ rhs ++ closeB + else if Syntax.isNone tyNode || Syntax.isMissing tyNode then + openB ++ bPref ++ ids ++ closeB + else + openB ++ bPref ++ ids ++ " : " ++ vPref ++ fmt tyNode ++ closeB + else if kind == SyntaxKind.instBinder then + let bPref := formatPrefixSpace (getA 0) + let idNode := Syntax.getArg (getA 1) 0 + let idVal := Syntax.getId idNode + let vPref := formatPrefixSpace (getA 2) + let tyStr := fmt (getA 3) + if Name.isAnonymous idVal then + "[" ++ bPref ++ vPref ++ tyStr ++ "]" + else + "[" ++ bPref ++ formatSurfaceName idVal ++ " : " ++ vPref ++ tyStr ++ "]" + -- Composite Terms + else if kind == SyntaxKind.explicitTerm then + if argList.length >= 3 && Syntax.getAtomVal (getA 0) == "@" then + let idStr := fmt (getA 1) + let univStr := formatUnivParamsNode (getA 2) + "@" ++ idStr ++ univStr + else + fmt (getA 0) ++ formatUnivParamsNode (getA 1) + else if kind == SyntaxKind.parenTerm then + "(" ++ fmt (getA 1) ++ ")" + else if kind == SyntaxKind.tupleTerm then + if argList.length <= 2 then "()" + else + let first := fmt (getA 1) + let rest := formatSyntaxList fmt ", " (Syntax.getArgs (getA 3)).toList + "(" ++ first ++ ", " ++ rest ++ ")" + else if kind == SyntaxKind.typeAscription then + let tStr := fmt (getA 1) + let vPref := formatPrefixSpace (getA 3) + let tyStr := fmt (getA 4) + "(" ++ tStr ++ " : " ++ vPref ++ tyStr ++ ")" + else if kind == SyntaxKind.listLit then + "[" ++ formatSyntaxList fmt ", " (Syntax.getArgs (getA 1)).toList ++ "]" + else if kind == SyntaxKind.anonCtor then + "⟨" ++ formatSyntaxList fmt ", " (Syntax.getArgs (getA 1)).toList ++ "⟩" + else if kind == SyntaxKind.structInst then + let spreadNode := getA 1 + let spreadStr := + if Syntax.isNone spreadNode || Syntax.isMissing spreadNode then "" + else fmt (Syntax.getArg spreadNode 0) ++ " with " + let assigns := formatSyntaxList fmt ", " (Syntax.getArgs (getA 2)).toList + "{ " ++ spreadStr ++ assigns ++ " }" + else if kind == SyntaxKind.structFieldAssign then + if argList.length >= 4 then + let fId := fmt (getA 0) + let bStr := formatSyntaxList fmt " " (Syntax.getArgs (getA 1)).toList + let valStr := fmt (getA 3) + fId ++ (if bStr == "" then "" else " " ++ bStr) ++ " := " ++ valStr + else + fmt (getA 0) ++ " := " ++ fmt (getA 2) + else if kind == SyntaxKind.projTerm then + fmtAtom (getA 0) ++ "." ++ fmt (getA 2) + else if kind == SyntaxKind.appTerm then + fmt (getA 0) ++ " " ++ fmtAtom (getA 1) + else if kind == SyntaxKind.binOpTerm then + "(" ++ fmt (getA 0) ++ " " ++ formatTokenVal (getA 1) ++ " " ++ fmt (getA 2) ++ ")" + else if kind == SyntaxKind.unaryOpTerm then + "(" ++ formatTokenVal (getA 0) ++ " " ++ fmtAtom (getA 1) ++ ")" + else if kind == SyntaxKind.arrowTerm then + let dom := fmtAtom (getA 0) + let vPref := formatPrefixSpace (getA 2) + let cod := fmt (getA 3) + dom ++ " → " ++ vPref ++ cod + else if kind == SyntaxKind.forallTerm then + let firstArg := getA 0 + let kw := formatTokenVal firstArg + let isKw := kw == "forall" || kw == "∀" || kw == "∃" || kw == "exists" + if isKw then + let outKw := if kw == "exists" then "∃" else if kw == "forall" then "∀" else kw + let binders := formatSyntaxList fmt " " (Syntax.getArgs (getA 1)).toList + let vPref := formatPrefixSpace (getA 3) + let body := fmt (getA 4) + outKw ++ " " ++ binders ++ ", " ++ vPref ++ body + else + let binders := formatSyntaxList fmt " " (Syntax.getArgs (getA 0)).toList + let vPref := formatPrefixSpace (getA 2) + let body := fmt (getA 3) + binders ++ " → " ++ vPref ++ body + else if kind == SyntaxKind.funTerm then + let binders := formatSyntaxList fmt " " (Syntax.getArgs (getA 1)).toList + let body := fmt (getA 3) + "fun " ++ binders ++ " => " ++ body + else if kind == SyntaxKind.letTerm then + let bPref := formatPrefixSpace (getA 1) + let idStr := fmt (getA 2) + let binders := formatSyntaxList fmt " " (Syntax.getArgs (getA 3)).toList + let bPart := if binders == "" then "" else " " ++ binders + let optTy := getA 4 + let tyPart := + if Syntax.isNone optTy || Syntax.isMissing optTy then "" + else if Syntax.isOfKind optTy SyntaxKind.nullKind then + " : " ++ formatPrefixSpace (Syntax.getArg optTy 1) ++ fmt (Syntax.getArg optTy 2) + else " : " ++ fmt optTy + let valStr := fmt (getA 6) + let bodyStr := fmt (getA 8) + "let " ++ bPref ++ idStr ++ bPart ++ tyPart ++ " := " ++ valStr ++ ";\n" ++ bodyStr + else if kind == SyntaxKind.letBorrowTerm || kind == SyntaxKind.letRecTerm then + let kw2 := formatTokenVal (getA 1) + let bPref := formatPrefixSpace (getA 2) + let idStr := fmt (getA 3) + let binders := formatSyntaxList fmt " " (Syntax.getArgs (getA 4)).toList + let bPart := if binders == "" then "" else " " ++ binders + let optTy := getA 5 + let tyPart := + if Syntax.isNone optTy || Syntax.isMissing optTy then "" + else if Syntax.isOfKind optTy SyntaxKind.nullKind then + " : " ++ formatPrefixSpace (Syntax.getArg optTy 1) ++ fmt (Syntax.getArg optTy 2) + else " : " ++ fmt optTy + let valNode := getA 7 + let bodyStr := fmt (getA 9) + if Syntax.isOfKind valNode SyntaxKind.nullKind then + let alts := formatSyntaxList fmt "\n" (Syntax.getArgs valNode).toList + "let " ++ kw2 ++ " " ++ bPref ++ idStr ++ bPart ++ tyPart ++ "\n" ++ alts ++ ";\n" ++ bodyStr + else + "let " ++ kw2 ++ " " ++ bPref ++ idStr ++ bPart ++ tyPart ++ " := " ++ fmt valNode ++ ";\n" ++ bodyStr + else if kind == SyntaxKind.haveTerm then + if argList.length >= 8 then + let idStr := fmt (getA 1) + let optTy := getA 3 + let tyPart := if Syntax.isNone optTy || Syntax.isMissing optTy then "" else " : " ++ fmt optTy + "have " ++ idStr ++ tyPart ++ " := " ++ fmt (getA 5) ++ ";\n" ++ fmt (getA 7) + else + let idStr := fmt (getA 1) + let optTy := getA 2 + let tyPart := + if Syntax.isNone optTy || Syntax.isMissing optTy then "" + else if Syntax.isOfKind optTy SyntaxKind.nullKind then + " : " ++ formatPrefixSpace (Syntax.getArg optTy 1) ++ fmt (Syntax.getArg optTy 2) + else " : " ++ fmt optTy + "have " ++ idStr ++ tyPart ++ " := " ++ fmt (getA 4) ++ ";\n" ++ fmt (getA 6) + else if kind == SyntaxKind.ifTerm then + if argList.length >= 8 then + let hStr := fmt (getA 1) + let condStr := fmt (getA 3) + let thenStr := fmt (getA 5) + let elseStr := fmt (getA 7) + "if " ++ hStr ++ " : " ++ condStr ++ " then " ++ thenStr ++ " else " ++ elseStr + else + let condStr := fmt (getA 2) + let thenStr := fmt (getA 4) + let elseStr := fmt (getA 6) + "if " ++ condStr ++ " then " ++ thenStr ++ " else " ++ elseStr + else if kind == SyntaxKind.matchTerm then + let discrs := formatSyntaxList fmt ", " (Syntax.getArgs (getA 1)).toList + let alts := formatSyntaxList fmt "\n" (Syntax.getArgs (getA 3)).toList + "match " ++ discrs ++ " with\n" ++ alts + else if kind == SyntaxKind.matchAlt then + let pats := formatSyntaxList fmt ", " (Syntax.getArgs (getA 1)).toList + "| " ++ pats ++ " => " ++ fmt (getA 3) + -- Tactics, `calc`, and `rcases` + else if kind == SyntaxKind.byTactic then + if formatTokenVal (getA 0) == "calc" then + fmt (getA 1) + else + "by\n " ++ fmt (getA 1) + else if kind == SyntaxKind.tacticSeq then + formatSyntaxList fmt "; " argList + else if kind == SyntaxKind.tacticParen then + "(" ++ fmt (getA 1) ++ ")" + else if kind == SyntaxKind.tacticFocus then + "· (" ++ fmt (getA 1) ++ ")" + else if kind == SyntaxKind.tacticCase || kind == SyntaxKind.tacticAlt then + let kw := formatTokenVal (getA 0) + let tagStr := fmt (getA 1) + let bStr := formatSyntaxList fmt " " (Syntax.getArgs (getA 2)).toList + let bPart := if bStr == "" then "" else " " ++ bStr + kw ++ " " ++ tagStr ++ bPart ++ " => " ++ fmt (getA 4) + else if kind == SyntaxKind.tacticFirst then + let branches := (Syntax.getArgs (getA 1)).toList.map fun b => "| " ++ fmt (Syntax.getArg b 1) + "first " ++ strIntercalatePure " " branches + else if kind == SyntaxKind.tacticTry || kind == SyntaxKind.tacticRepeat || + kind == SyntaxKind.tacticAllGoals || kind == SyntaxKind.tacticAnyGoals then + formatTokenVal (getA 0) ++ " " ++ fmt (getA 1) + else if kind == SyntaxKind.tacticAndThen then + fmt (getA 0) ++ " <;> " ++ fmt (getA 2) + else if kind == SyntaxKind.tacticIntro || kind == SyntaxKind.tacticFunext || + kind == SyntaxKind.tacticExt || kind == SyntaxKind.tacticClear || + kind == SyntaxKind.tacticRevert || kind == SyntaxKind.tacticSubst then + let kw := formatTokenVal (getA 0) + let ids := formatSyntaxList fmt " " (Syntax.getArgs (getA 1)).toList + if ids == "" then kw else kw ++ " " ++ ids + else if kind == SyntaxKind.tacticRintro then + let pats := formatSyntaxList fmt " " (Syntax.getArgs (getA 1)).toList + let optTy := getA 2 + let tyPart := if Syntax.getNumArgs optTy >= 2 then " : " ++ fmt (Syntax.getArg optTy 1) else "" + "rintro" ++ (if pats == "" then "" else " " ++ pats) ++ tyPart + else if kind == SyntaxKind.tacticRcases then + let hId := Syntax.getId (getA 1) + let hPart := if Name.isAnonymous hId then "" else formatSurfaceName hId ++ " : " + let target := fmt (getA 2) + let optWith := getA 3 + let withPart := if Syntax.getNumArgs optWith >= 2 then " with " ++ fmt (Syntax.getArg optWith 1) else "" + "rcases " ++ hPart ++ target ++ withPart + else if kind == SyntaxKind.tacticObtain then + let patStr := fmt (getA 1) + let optTy := getA 2 + let tyPart := if Syntax.getNumArgs optTy >= 2 then " : " ++ fmt (Syntax.getArg optTy 1) else "" + "obtain " ++ patStr ++ tyPart ++ " := " ++ fmt (getA 4) + else if kind == SyntaxKind.rcasesPatWildcard then "_" + else if kind == SyntaxKind.rcasesPatRfl then "rfl" + else if kind == SyntaxKind.rcasesPatIdent then fmt (getA 0) + else if kind == SyntaxKind.rcasesPatTuple then + "⟨" ++ formatSyntaxList fmt ", " (Syntax.getArgs (getA 0)).toList ++ "⟩" + else if kind == SyntaxKind.rcasesPatAlt then + "(" ++ formatSyntaxList fmt " | " (Syntax.getArgs (getA 0)).toList ++ ")" + else if kind == SyntaxKind.tacticCalc || kind == SyntaxKind.calcTerm then + "calc\n" ++ formatSyntaxList fmt "\n" (Syntax.getArgs (getA 1)).toList + else if kind == SyntaxKind.calcStep then + " " ++ fmt (getA 0) ++ " := " ++ fmt (getA 2) + else if kind == SyntaxKind.tacticExact || kind == SyntaxKind.tacticApply || + kind == SyntaxKind.tacticRefine || kind == SyntaxKind.tacticShow || + kind == SyntaxKind.tacticChange then + formatTokenVal (getA 0) ++ " " ++ fmt (getA 1) + else if kind == SyntaxKind.tacticRfl || kind == SyntaxKind.tacticConstructor || + kind == SyntaxKind.tacticDecide || kind == SyntaxKind.tacticAssumption || + kind == SyntaxKind.tacticSorry || kind == SyntaxKind.tacticLeft || + kind == SyntaxKind.tacticRight || kind == SyntaxKind.tacticSplit || + kind == SyntaxKind.tacticSymm || kind == SyntaxKind.tacticCongr || + kind == SyntaxKind.tacticTrivial || kind == SyntaxKind.tacticContradiction || + kind == SyntaxKind.tacticExfalso || kind == SyntaxKind.tacticDone || + kind == SyntaxKind.tacticRing || kind == SyntaxKind.tacticOmega then + formatTokenVal (getA 0) + else if kind == SyntaxKind.tacticNormNum then + let optAt := getA 1 + let atPart := if Syntax.getNumArgs optAt >= 2 then " at " ++ fmt (Syntax.getArg optAt 1) else "" + "norm_num" ++ atPart + else if kind == SyntaxKind.tacticExists then + let kw := formatTokenVal (getA 0) + kw ++ " " ++ formatSyntaxList fmt ", " (Syntax.getArgs (getA 1)).toList + else if kind == SyntaxKind.tacticTrans then + let optT := getA 1 + let tPart := if Syntax.getNumArgs optT >= 1 then " " ++ fmt (Syntax.getArg optT 0) else "" + "trans" ++ tPart + else if kind == SyntaxKind.tacticRwRule then + let symmNode := getA 0 + let prefixArrow := if Syntax.getNumArgs symmNode >= 1 then "← " else "" + prefixArrow ++ fmt (getA 1) + else if kind == SyntaxKind.tacticRw then + let kw := formatTokenVal (getA 0) + let rules := formatSyntaxList fmt ", " (Syntax.getArgs (getA 2)).toList + let optAt := getA 4 + let atPart := if Syntax.getNumArgs optAt >= 2 then " at " ++ fmt (Syntax.getArg optAt 1) else "" + kw ++ " [" ++ rules ++ "]" ++ atPart + else if kind == SyntaxKind.tacticSimp || kind == SyntaxKind.tacticDSimp then + let kw := formatTokenVal (getA 0) + let onlyPart := if Syntax.getNumArgs (getA 1) >= 1 then " only" else "" + let rulesBlk := getA 2 + let rulesPart := + if Syntax.getNumArgs rulesBlk >= 2 then + " [" ++ formatSyntaxList fmt ", " (Syntax.getArgs (Syntax.getArg rulesBlk 1)).toList ++ "]" + else "" + let optAt := getA 3 + let atPart := if Syntax.getNumArgs optAt >= 2 then " at " ++ fmt (Syntax.getArg optAt 1) else "" + kw ++ onlyPart ++ rulesPart ++ atPart + else if kind == SyntaxKind.tacticHave || kind == SyntaxKind.tacticLet then + let kw := formatTokenVal (getA 0) + let idStr := fmt (getA 1) + let optTy := getA 2 + let tyPart := if Syntax.getNumArgs optTy >= 2 then " : " ++ fmt (Syntax.getArg optTy 1) else "" + kw ++ " " ++ idStr ++ tyPart ++ " := " ++ fmt (getA 4) + else if kind == SyntaxKind.tacticSuffices then + let idVal := Syntax.getId (getA 1) + let idPart := if Name.isAnonymous idVal then "" else formatSurfaceName idVal ++ " : " + let tyStr := fmt (getA 3) + let modeKw := formatTokenVal (getA 4) + "suffices " ++ idPart ++ tyStr ++ " " ++ modeKw ++ " " ++ fmt (getA 5) + else if kind == SyntaxKind.tacticSpecialize then + "specialize " ++ fmt (getA 1) ++ " " ++ formatSyntaxList fmtAtom " " (Syntax.getArgs (getA 2)).toList + else if kind == SyntaxKind.tacticGeneralize then + let hVal := Syntax.getId (getA 1) + let hPart := if Name.isAnonymous hVal then "" else formatSurfaceName hVal ++ " : " + "generalize " ++ hPart ++ fmt (getA 2) ++ " = " ++ fmt (getA 4) + else if kind == SyntaxKind.tacticByCases then + let hVal := Syntax.getId (getA 1) + let hPart := if Name.isAnonymous hVal then "" else formatSurfaceName hVal ++ " : " + "by_cases " ++ hPart ++ fmt (getA 2) + else if kind == SyntaxKind.tacticByContra then + let hVal := Syntax.getId (getA 1) + if Name.isAnonymous hVal then "by_contra" else "by_contra " ++ formatSurfaceName hVal + else if kind == SyntaxKind.tacticCases || kind == SyntaxKind.tacticInduction then + let kw := formatTokenVal (getA 0) + let target := fmt (getA 1) + let optWith := getA 2 + if Syntax.getNumArgs optWith >= 2 then + let alts := formatSyntaxList fmt "\n " (Syntax.getArgs (Syntax.getArg optWith 1)).toList + kw ++ " " ++ target ++ " with\n " ++ alts + else + kw ++ " " ++ target + -- Top-Level Commands + else if kind == SyntaxKind.importDecl then + let modStr := fmt (getA 1) + let pinNode := getA 2 + if Syntax.isOfKind pinNode SyntaxKind.hashRef then + "import " ++ modStr ++ " @ " ++ fmt pinNode + else + "import " ++ modStr + else if kind == SyntaxKind.hashImport then + "import " ++ fmt (getA 1) + else if kind == SyntaxKind.buildMapDecl then + "map " ++ fmt (getA 1) ++ " := " ++ fmt (getA 3) + else if kind == SyntaxKind.namespaceDecl then + "namespace " ++ fmt (getA 1) + else if kind == SyntaxKind.sectionDecl || kind == SyntaxKind.endDecl then + let kw := formatTokenVal (getA 0) + let optId := getA 1 + if Syntax.isNone optId || Syntax.isMissing optId then kw + else kw ++ " " ++ fmt (Syntax.getArg optId 0) + else if kind == SyntaxKind.openDecl then + let nss := formatSyntaxList fmt " " (Syntax.getArgs (getA 1)).toList + let optOnly := getA 2 + if Syntax.isNone optOnly || Syntax.isMissing optOnly then + "open " ++ nss + else + "open " ++ nss ++ " (" ++ formatSyntaxList fmt " " (Syntax.getArgs optOnly).toList ++ ")" + else if kind == SyntaxKind.variableDecl then + "variable " ++ formatSyntaxList fmt " " (Syntax.getArgs (getA 1)).toList + else if kind == SyntaxKind.universeDecl then + "universe " ++ formatSyntaxList fmt " " (Syntax.getArgs (getA 1)).toList + else if kind == SyntaxKind.mutualDecl then + "mutual\n" ++ formatSyntaxList fmt "\n\n" (Syntax.getArgs (getA 1)).toList ++ "\nend" + else if kind == SyntaxKind.mergeConflictDecl then + "#merge\n" ++ formatSyntaxList fmt "\n" (Syntax.getArgs (getA 1)).toList ++ "\nend" + else if kind == SyntaxKind.mergeArm then + "| " ++ fmt (getA 1) ++ " =>\n " ++ fmt (getA 3) + else if kind == SyntaxKind.defDecl || kind == SyntaxKind.abbrevDecl || + kind == SyntaxKind.theoremDecl || kind == SyntaxKind.opaqueDecl then + let mods := formatModifiersNode (getA 0) + let kw := formatTokenVal (getA 1) + let outKw := if kw == "lemma" then "theorem" else kw + let idStr := fmt (getA 2) + let univs := formatUnivParamsNode (getA 3) + let binders := formatSyntaxList fmt " " (Syntax.getArgs (getA 4)).toList + let bPart := if binders == "" then "" else " " ++ binders + let vPref := formatPrefixSpace (getA 5) + let optTy := getA 6 + let tyPart := + if Syntax.isNone optTy || Syntax.isMissing optTy then "" + else " : " ++ vPref ++ fmt optTy + if argList.length == 8 then + let alts := formatSyntaxList fmt "\n " (Syntax.getArgs (getA 7)).toList + mods ++ outKw ++ " " ++ idStr ++ univs ++ bPart ++ tyPart ++ "\n " ++ alts + else + mods ++ outKw ++ " " ++ idStr ++ univs ++ bPart ++ tyPart ++ " := " ++ fmt (getA 8) + else if kind == SyntaxKind.axiomDecl then + let mods := formatModifiersNode (getA 0) + let idStr := fmt (getA 2) + let univs := formatUnivParamsNode (getA 3) + let binders := formatSyntaxList fmt " " (Syntax.getArgs (getA 4)).toList + let bPart := if binders == "" then "" else " " ++ binders + let vPref := formatPrefixSpace (getA 5) + let tyStr := fmt (getA 6) + mods ++ "axiom " ++ idStr ++ univs ++ bPart ++ " : " ++ vPref ++ tyStr + else if kind == SyntaxKind.instanceDecl then + let mods := formatModifiersNode (getA 0) + let idVal := Syntax.getId (getA 2) + let idPart := if Name.isAnonymous idVal then "" else " " ++ formatSurfaceName idVal + let univs := formatUnivParamsNode (getA 3) + let binders := formatSyntaxList fmt " " (Syntax.getArgs (getA 4)).toList + let bPart := if binders == "" then "" else " " ++ binders + let vPref := formatPrefixSpace (getA 5) + let tyStr := fmt (getA 6) + if formatTokenVal (getA 7) == "where" then + let assigns := formatSyntaxList fmt "\n " (Syntax.getArgs (getA 8)).toList + mods ++ "instance" ++ idPart ++ univs ++ bPart ++ " : " ++ vPref ++ tyStr ++ " where\n " ++ assigns + else + mods ++ "instance" ++ idPart ++ univs ++ bPart ++ " : " ++ vPref ++ tyStr ++ " := " ++ fmt (getA 8) + else if kind == SyntaxKind.inductiveDecl then + let mods := formatModifiersNode (getA 0) + let idStr := fmt (getA 2) + let univs := formatUnivParamsNode (getA 3) + let binders := formatSyntaxList fmt " " (Syntax.getArgs (getA 4)).toList + let bPart := if binders == "" then "" else " " ++ binders + let vPref := formatPrefixSpace (getA 5) + let optTy := getA 6 + let tyPart := if Syntax.isNone optTy || Syntax.isMissing optTy then "" else " : " ++ vPref ++ fmt optTy + let ctors := formatSyntaxList fmt "\n " (Syntax.getArgs (getA 7)).toList + let cPart := if ctors == "" then "" else " where\n " ++ ctors + let derivs := formatSyntaxList fmt ", " (Syntax.getArgs (getA 8)).toList + let dPart := if derivs == "" then "" else "\n deriving " ++ derivs + mods ++ "inductive " ++ idStr ++ univs ++ bPart ++ tyPart ++ cPart ++ dPart + else if kind == SyntaxKind.ctorDecl then + let idStr := fmt (getA 1) + let binders := formatSyntaxList fmt " " (Syntax.getArgs (getA 2)).toList + let bPart := if binders == "" then "" else " " ++ binders + let vPref := formatPrefixSpace (getA 3) + let optTy := getA 4 + let tyPart := if Syntax.isNone optTy || Syntax.isMissing optTy then "" else " : " ++ vPref ++ fmt optTy + "| " ++ idStr ++ bPart ++ tyPart + else if kind == SyntaxKind.structureDecl || kind == SyntaxKind.classDecl then + let mods := formatModifiersNode (getA 0) + let kw := formatTokenVal (getA 1) + let idStr := fmt (getA 2) + let univs := formatUnivParamsNode (getA 3) + let binders := formatSyntaxList fmt " " (Syntax.getArgs (getA 4)).toList + let bPart := if binders == "" then "" else " " ++ binders + let extStr := formatSyntaxList fmt ", " (Syntax.getArgs (getA 5)).toList + let extPart := if extStr == "" then "" else " extends " ++ extStr + let vPref := formatPrefixSpace (getA 6) + let optTy := getA 7 + let tyPart := if Syntax.isNone optTy || Syntax.isMissing optTy then "" else " : " ++ vPref ++ fmt optTy + let customCtor := getA 8 + let ctorPart := + if Syntax.isNone customCtor || Syntax.isMissing customCtor || Name.isAnonymous (Syntax.getId customCtor) then "" + else "\n " ++ fmt customCtor ++ " ::" + let fields := formatSyntaxList fmt "\n " (Syntax.getArgs (getA 9)).toList + let fPart := if fields == "" then "" else " where" ++ ctorPart ++ "\n " ++ fields + let derivs := formatSyntaxList fmt ", " (Syntax.getArgs (getA 10)).toList + let dPart := if derivs == "" then "" else "\n deriving " ++ derivs + mods ++ kw ++ " " ++ idStr ++ univs ++ bPart ++ extPart ++ tyPart ++ fPart ++ dPart + else if kind == SyntaxKind.fieldDecl then + if argList.length >= 8 then + let openB := formatTokenVal (getA 0) + let bPref := formatPrefixSpace (getA 1) + let ids := formatSyntaxList fmt " " (Syntax.getArgs (getA 2)).toList + let vPref := formatPrefixSpace (getA 4) + let tyStr := fmt (getA 5) + let closeB := formatTokenVal (getA 7) + openB ++ bPref ++ ids ++ " : " ++ vPref ++ tyStr ++ closeB + else + let bPref := formatPrefixSpace (getA 0) + let ids := formatSyntaxList fmt " " (Syntax.getArgs (getA 1)).toList + let vPref := formatPrefixSpace (getA 3) + let tyStr := fmt (getA 4) + let optDef := getA 5 + let defPart := if Syntax.isNone optDef || Syntax.isMissing optDef then "" else " := " ++ fmt optDef + bPref ++ ids ++ " : " ++ vPref ++ tyStr ++ defPart + else if kind == SyntaxKind.notationDecl then + if argList.length >= 6 then + let fixKw := formatTokenVal (getA 0) + let precStr := fmt (getA 1) + let pPart := if precStr == "" then "" else ":" ++ precStr + let symStr := fmt (getA 2) + let targetStr := fmt (getA 4) + fixKw ++ pPart ++ " " ++ symStr ++ " => " ++ targetStr + else + let precStr := fmt (getA 1) + let pPart := if precStr == "" then "" else ":" ++ precStr + let items := formatSyntaxList fmt " " (Syntax.getArgs (getA 2)).toList + "notation" ++ pPart ++ " " ++ items ++ " => " ++ fmt (getA 3) + else if kind == SyntaxKind.macroDecl then + if formatTokenVal (getA 0) == "macro_rules" then + let alts := formatSyntaxList fmt "\n " (Syntax.getArgs (getA 1)).toList + "macro_rules\n " ++ alts + else + let precStr := fmt (getA 1) + let pPart := if precStr == "" then "" else ":" ++ precStr + let items := formatSyntaxList fmt " " (Syntax.getArgs (getA 2)).toList + "macro" ++ pPart ++ " " ++ items ++ " => " ++ fmt (getA 3) + else + joinNonEmpty " " (argList.map fmt) + +/-- Format an `Stx` tree into a surface `.ix` / `.lean` string. -/ +def formatSyntax (fuel : Nat := 1024) (stx : Stx) : String := + formatSyntaxAux fuel stx + +/-- Format a top-level module syntax node into surface text. -/ +def formatModule (stx : Stx) : String := + formatSyntax 1024 stx + +/-- Format a `ModuleSchedule` (using `hermeticizeModule` so all scoped namespaces, variables, + and universes are self-contained on each declaration). -/ +def formatModuleSchedule (sched : ModuleSchedule) : String := + match hermeticizeModule sched with + | .ok hSched => formatSyntax 1024 (synthesizeModuleSyntax hSched) + | .error _ => formatSyntax 1024 (synthesizeModuleSyntax sched) + +/-- Format a `MergeOutcome` from `mergeSource2` / `mergeSource3` into `.ix` surface text. -/ +def formatMergeOutcome (outcome : MergeOutcome) : String := + formatSyntax 1024 outcome.moduleStx + +end Ix.Frontend + +end diff --git a/Ix/Frontend/Merge.lean b/Ix/Frontend/Merge.lean new file mode 100644 index 0000000000..ba31b3f32a --- /dev/null +++ b/Ix/Frontend/Merge.lean @@ -0,0 +1,1392 @@ +/- + Ix.Frontend.Merge: Self-Contained, Provable AST & Type-Aware Module Merge Engine (`IxVCS`). + + Implements the 3-level conflict-free and type-contract-preserving merge calculus for `Ix`: + 1. **Declaration-Level Pushout (`mergeModuleSchedule2`, `mergeSource2`)**: + - Hermetically normalizes declarations (`hermeticizeDecl`, `hermeticizeModule`) by folding + lexical `namespace`/`section`/`variable`/`universe`/`open` scopes into self-contained ASTs. + - Computes bottom-up BLAKE3-256 (`Address.admissionHash`) intrinsic and Merkle digests over + the Tarjan SCC condensation DAG (`computeModuleDigests`). + - Partitions module pairs into 5 disjoint blocks: + $S$ (shared/unified) $\sqcup$ $\sigma_1(O_1)$ (left-only) $\sqcup$ $\sigma_2(O_2)$ (right-only) + $\sqcup$ $\sigma_1(K)$ (left conflicted) $\sqcup$ $\sigma_2(K)$ (right conflicted). + - Disambiguates conflicting declarations using first-class `.#merge` variants (`foobar.#merge._1`, + `foobar.#merge._2` or `foobar.#merge.`) or namespace prefixes (`X.Acme.foobar`, + `Y.Acme.foobar`), and binder-awarely rewrites all downstream callers, constructors, + patterns, structure projections, and recursors (`rewriteModuleDecl`). + 2. **Intra-Declaration Semantic & AST Pre-Merge (`tryUnifySameNameDecls`, `tryMergeDeclSyntax3`)**: + - **Proof Irrelevance Absorption (`Prop`)**: Two `theorem` declarations with the same name and + definitionally equal (`isDefEq`) statement types are unified into a single theorem (selecting + the canonically smaller `sorryAx`-free proof by 32-byte BLAKE3 Merkle `Address`) with zero + `.#merge` disambiguation. + - **Definitional Equality (`isDefEq`)**: Two definitions with definitionally equal types and + values unify without `.#merge` disambiguation. + - **Keyed 3-Way AST Merge (`tryMergeDeclSyntax3`)**: Disjoint constructor arm edits in `match` + expressions and disjoint field edits in structure literals are spliced and verified against + the elaborator before falling back to `.#merge` disambiguation. + 3. **3-Way Type-Contract-Preserving Merge (`mergeModuleSchedule3`, `mergeSource3`)**: + - Enforces the invariant **"The Type System is the Contract Between Caller and Callee"**: + - **Cases A & B (1-sided proof or body update where all callers/theorems in the other branch + still typecheck)**: Fast-forwards the updated declaration cleanly with zero `.#merge` conflicts. + - **Cases C & D (1-sided body update that breaks a dependent proof in the other branch that + unfolded the old body via `rfl`/`isDefEq`, or a 1-sided type signature change)**: Rejects + the fast-forward and splits the declaration into `.#merge._1` and `.#merge._2` so caller + typechecking is 100% preserved across both branches. + + Every function in this module is 100% pure, total, and kernel-reducible (passing + `checkClosureCertification` with zero `partial`, `unsafe`, `sorry`, or banned opaques). +-/ +module + +public import Ix.Frontend.Elab.Command + +@[expose] public section + +namespace Ix.Frontend + +open Ix.Frontend.Parser +open Ix.Frontend.Elab + +/-! ## 1. Disambiguation Modes & Conflict Metadata -/ + +/-- Strategy for disambiguating conflicting declarations with the same `Ix.Name`. -/ +inductive DisambigMode where + /-- Default first-class conflict naming: `orig.#merge._1` and `orig.#merge._2` + (ordered canonically by 32-byte BLAKE3 Merkle `Address` so 2-way merge is strictly commutative). -/ + | mergeIndexed + /-- Branch/author-tagged first-class conflict naming: `orig.#merge.` and `orig.#merge.`. -/ + | mergeNamed (tag1 tag2 : String) + /-- Prefix namespace disambiguation: `.` and `.` + (e.g. `X.Acme.foobar` and `Y.Acme.foobar`). -/ + | namespacePrefix (prefix1 prefix2 : Ix.Name) + /-- Flat numeric suffix disambiguation: `_1` and `_2`. -/ + | indexedSuffix + deriving BEq, DecidableEq, Repr, Inhabited + +/-- Record of a disambiguated conflict produced during a 2-way or 3-way module merge. -/ +structure MergeConflictInfo where + origName : Ix.Name + leftName : Ix.Name + rightName : Ix.Name + leftDigest : Address + rightDigest : Address + isSemanticConflict : Bool := false + deriving BEq, Repr, Inhabited + +/-- Complete result of a 2-way or 3-way `IxVCS` module merge. -/ +structure MergeOutcome where + sched : ModuleSchedule + conflicts : Array MergeConflictInfo + leftRenaming : NameMap Ix.Name + rightRenaming : NameMap Ix.Name + moduleStx : Stx + deriving Repr, Inhabited + +/-! ## 2. Source-Info-Insensitive `Syntax` Comparison & BLAKE3-256 Digest Computation -/ + +/-- Compare two `List Stx` lexicographically using `cmpRec`. -/ +def cmpSyntaxList (cmpRec : Stx → Stx → Ordering) : + List Stx → List Stx → Ordering + | [], [] => .eq + | [], _ :: _ => .lt + | _ :: _, [] => .gt + | a :: as, b :: bs => + match cmpRec a b with + | .eq => cmpSyntaxList cmpRec as bs + | ord => ord + +/-- Pure, total, source-position-insensitive structural ordering on `Stx` + (used as a deterministic tie-breaker if two distinct ASTs ever share a hash). -/ +def cmpSyntaxPure : Nat → Stx → Stx → Ordering + | 0, _, _ => .eq + | fuel + 1, s1, s2 => + match s1, s2 with + | .missing, .missing => .eq + | .missing, _ => .lt + | _, .missing => .gt + | .atom _ v1, .atom _ v2 => Sym.cmp v1 v2 + | .atom _ _, _ => .lt + | _, .atom _ _ => .gt + | .ident _ _ id1, .ident _ _ id2 => + FName.cmp id1 id2 + | .ident .., _ => .lt + | _, .ident .. => .gt + | .node _ k1 as1, .node _ k2 as2 => + match FName.cmp k1 k2 with + | .eq => + match natCmpPure as1.size as2.size with + | .eq => cmpSyntaxList (cmpSyntaxPure fuel) as1.toList as2.toList + | ord => ord + | ord => ord + | .node .., _ => .lt + | _, .node .. => .gt + | .snil, .snil => .eq + | .snil, _ => .lt + | _, .snil => .gt + | .scons h1 t1, .scons h2 t2 => + match cmpSyntaxPure fuel h1 h2 with + | .eq => cmpSyntaxPure fuel t1 t2 + | ord => ord + +/-- Source-position-insensitive structural equality on `Stx`. -/ +def syntaxBeqPure (s1 s2 : Stx) (fuel : Nat := 256) : Bool := + cmpSyntaxPure fuel s1 s2 == .eq + +/-- Compute a deterministic, source-position-insensitive 32-byte BLAKE3 `Address` + for an `Stx` tree via `Address.admissionHash`. -/ +def hashSyntaxPure : Nat → Stx → Address + | 0, _ => Address.admissionHash (ByteArray.mk #[0]) + | fuel + 1, stx => + match stx with + | .missing => + Address.admissionHash (ByteArray.mk #[1]) + | .atom _ val => + Address.admissionHash (ByteArray.mk #[2] ++ Sym.toByteArray val) + | .ident _ _ idF => + Address.admissionHash (ByteArray.mk #[3] ++ (Name.computeHash (FName.toIxName idF)).hash) + | .node _ kindF args => + let initBytes := ByteArray.mk #[4] ++ (Name.computeHash (FName.toIxName kindF)).hash + let allBytes := args.toList.foldl (fun acc child => + acc ++ (hashSyntaxPure fuel child).hash) initBytes + Address.admissionHash allBytes + | .snil | .scons .. => + Address.admissionHash (ByteArray.mk #[5]) + +/-- Encode a `DeclKind` as a single tag byte for domain-separated hashing. -/ +def declKindTag : DeclKind → UInt8 + | .defn => 1 + | .abbrev => 2 + | .thm => 3 + | .opaqueDecl => 4 + | .axiomDecl => 5 + | .inst => 6 + | .ind => 7 + | .struct => 8 + | .cls => 9 + +/-- Compute the intrinsic 32-byte BLAKE3 `Address` of a `ModuleDecl` + (covering its `DeclKind`, `fullName`, `univParams`, and position-stripped `stx`). -/ +def hashDeclIntrinsic (d : ModuleDecl) : Address := + let b0 := ByteArray.mk #[0xD0, declKindTag d.kind] ++ (Name.computeHash d.fullName).hash + let b1 := d.univParams.foldl (fun acc u => acc ++ (Name.computeHash u).hash) b0 + let b2 := b1 ++ (hashSyntaxPure 256 d.stx).hash + Address.admissionHash b2 + +/-- Per-declaration intrinsic and bottom-up SCC Merkle digests for a `ModuleSchedule`. -/ +structure ModuleDigests where + intrinsic : NameMap Address := NameMap.empty + merkle : NameMap Address := NameMap.empty + deriving Repr, Inhabited + +/-- Compute both intrinsic and bottom-up SCC Merkle BLAKE3-256 digests for all + declarations in `sched : ModuleSchedule`. -/ +def computeModuleDigests (sched : ModuleSchedule) : ModuleDigests := + let declList := sched.modIdx.decls.toList + let intrinsic : NameMap Address := declList.foldl (fun acc d => + acc.insert d.fullName (hashDeclIntrinsic d)) NameMap.empty + let merkle : NameMap Address := sched.sccs.toList.foldl (fun acc scc => + let sccDecls := scc.declIdxs.toList.filterMap (Syntax.listGet? declList) + -- Collect sorted external dependency Merkle digests for this SCC + let depDigests : Array Address := sccDecls.foldl (fun dAcc d => + let depInfo := Syntax.listGetD sched.deps.toList d.idx { declIdx := d.idx } + let allRefIdxs := (depInfo.sigRefs ++ depInfo.bodyRefs).toList + allRefIdxs.foldl (fun dAcc2 refIdx => + match Syntax.listGet? declList refIdx with + | some refDecl => + if scc.declIdxs.toList.contains refIdx then dAcc2 + else + let refHash := (acc.get? refDecl.fullName).getD + ((intrinsic.get? refDecl.fullName).getD dummyAddr) + dAcc2.push refHash + | none => dAcc2) dAcc) #[] + let sortedDeps := sortArrayBy depDigests (fun a b => bytesCmp a.hash.data.toList b.hash.data.toList == .lt) + let depBytes := sortedDeps.toList.foldl (fun b h => b ++ h.hash) (ByteArray.mk #[0xD1]) + let sccIntrBytes := sccDecls.foldl (fun b d => + let ih := (intrinsic.get? d.fullName).getD dummyAddr + b ++ ih.hash) depBytes + let sccDigest := Address.admissionHash sccIntrBytes + sccDecls.foldl (fun acc2 d => + let ih := (intrinsic.get? d.fullName).getD dummyAddr + let dMerkle := Address.admissionHash (ByteArray.mk #[0xD2] ++ sccDigest.hash ++ ih.hash) + acc2.insert d.fullName dMerkle) acc) NameMap.empty + { intrinsic, merkle } + +/-- Total, canonical comparison between two declarations `(d1, dig1)` and `(d2, dig2)`: + compares their 32-byte Merkle `Address`, then their intrinsic `Address`, and finally + `cmpSyntaxPure 256 d1.stx d2.stx`. -/ +def cmpDeclCanonical (d1 : ModuleDecl) (m1 i1 : Address) + (d2 : ModuleDecl) (m2 i2 : Address) : Ordering := + match bytesCmp m1.hash.data.toList m2.hash.data.toList with + | .eq => + match bytesCmp i1.hash.data.toList i2.hash.data.toList with + | .eq => cmpSyntaxPure 256 d1.stx d2.stx + | ord => ord + | ord => ord + +/-! ## 3. Binder-Aware Reference Rewriting & Hermetic Declaration Normalization -/ + +/-- Apply `identMap : NameMap Ix.Name` to a resolved symbol `sym`, handling: + 1. Direct declaration match (`identMap.get? sym = some target`). + 2. Hierarchical child match (`sym = origParent ++ childSuffix` where + `identMap.get? origParent = some newParent`, rewriting constructors `Expr.lit` $\to$ + `Expr.#merge._1.lit`, projections `Point.x` $\to$ `Point.#merge._1.x`, and recursors + `Expr.recOn` $\to$ `Expr.#merge._1.recOn`). -/ +def applySymRename (identMap : NameMap Ix.Name) (sym : Ix.Name) : Option Ix.Name := + match identMap.get? sym with + | some target => some target + | none => + match sym with + | .str pre last _ => + if Name.isAnonymous pre then none + else + match identMap.get? pre with + | some newPre => some (Name.mkStr newPre last) + | none => + match pre with + | .str pre2 mid _ => + if Name.isAnonymous pre2 then none + else + match identMap.get? pre2 with + | some newPre2 => some (Name.mkStr (Name.mkStr newPre2 mid) last) + | none => none + | _ => none + | _ => none + +/-- Rewrite a surface identifier `id` in `scope` against `modIdx`: + - When `identMap` rewrites the resolved target (or `id` directly), returns the renamed `Ix.Name`. + - When `qualifyAll` is `true` and `id` resolves to a known module declaration/constructor/field + `resolved != id`, returns `resolved` so the declaration becomes hermetically independent of + `namespace`/`open` scopes. -/ +def rewriteIdentInScope (scope : ScopeSnapshot) (modIdx : ModuleIndex) + (isExtConst : Ix.Name → Bool) (identMap : NameMap Ix.Name) + (qualifyAll : Bool) (id : Ix.Name) : Ix.Name := + if Name.isAnonymous id then id + else + let resolved := resolveIdentInScope scope modIdx isExtConst id + match applySymRename identMap resolved with + | some renamed => renamed + | none => + match applySymRename identMap id with + | some renamed => renamed + | none => + -- Check if `id` is `.` where `` resolves in `scope` + let resCompound? : Option Ix.Name := match id with + | .str pre last _ => + if Name.isAnonymous pre then none + else + let resPre := resolveIdentInScope scope modIdx isExtConst pre + let fullCand := Name.mkStr resPre last + match applySymRename identMap fullCand with + | some renamed => some renamed + | none => + if qualifyAll && modIdx.containsSymbol fullCand then some fullCand + else none + | _ => none + match resCompound? with + | some target => target + | none => + if qualifyAll && modIdx.containsSymbol resolved then resolved + else id + +/-- Construct an `.ident` node preserving `info` with updated `newId`. -/ +def mkIdentPreserveInfo (info : FSourceInfo) (newId : Ix.Name) : Stx := + let fn := FName.ofIxName newId + .ident info (FName.toSym fn) fn + +/-- Pure child-list replacement on `Stx` `.scons`/`.snil` chains. -/ +def stxSetD : Stx → Nat → Stx → Stx + | .scons _ t, 0, v => .scons v t + | .scons h t, k + 1, v => .scons h (stxSetD t k v) + | s, _, _ => s + +/-- Binder-aware pattern rewriter: rewrites constructor references in `pat` while recording + pattern-bound local variables into `bound : NameSet`. -/ +def rewritePattern (scope : ScopeSnapshot) (modIdx : ModuleIndex) + (isExtConst : Ix.Name → Bool) (isExtCtor : Ix.Name → Bool) + (identMap : NameMap Ix.Name) (qualifyAll : Bool) : + Nat → Stx → NameSet → Stx × NameSet + | 0, pat, bound => (pat, bound) + | fuel + 1, pat, bound => + match pat with + | .missing | .atom _ _ | .snil | .scons .. => (pat, bound) + | .ident info _ idF => + let id := FName.toIxName idF + if Name.isAnonymous id then (pat, bound) + else + let resolved := resolveIdentInScope scope modIdx isExtConst id + if modIdx.isModuleCtor resolved || isExtCtor resolved then + let newId := rewriteIdentInScope scope modIdx isExtConst identMap qualifyAll id + if newId == id then (pat, bound) + else (mkIdentPreserveInfo info newId, bound) + else + match id with + | .str (.anonymous _) _ _ => + (pat, bound.insert id) + | _ => + let newId := rewriteIdentInScope scope modIdx isExtConst identMap qualifyAll id + if newId == id then (pat, bound) + else (mkIdentPreserveInfo info newId, bound) + | .node info kindF args => + let kind := FName.toIxName kindF + if kind == SyntaxKind.numLit || kind == SyntaxKind.strLit || + kind == SyntaxKind.charLit || kind == SyntaxKind.holeTerm then + (pat, bound) + else if kind == SyntaxKind.appTerm then + let fn := Syntax.listGetD args.toList 0 .missing + let arg := Syntax.listGetD args.toList 1 .missing + let (fn', bound1) := match fn with + | .ident iInfo _ fnIdF => + let fnId := FName.toIxName fnIdF + let resolved := resolveIdentInScope scope modIdx isExtConst fnId + if modIdx.containsSymbol resolved || isExtCtor resolved || (applySymRename identMap resolved).isSome then + let newFnId := rewriteIdentInScope scope modIdx isExtConst identMap qualifyAll fnId + if newFnId == fnId then (fn, bound) + else (mkIdentPreserveInfo iInfo newFnId, bound) + else + rewritePattern scope modIdx isExtConst isExtCtor identMap qualifyAll fuel fn bound + | _ => + rewritePattern scope modIdx isExtConst isExtCtor identMap qualifyAll fuel fn bound + let (arg', bound2) := rewritePattern scope modIdx isExtConst isExtCtor identMap qualifyAll fuel arg bound1 + (.node info kindF (Stx.ofList [fn', arg']), bound2) + else + let (revChildren, bound') := args.toList.foldl (fun (acc, bnd) child => + let (child', bnd') := rewritePattern scope modIdx isExtConst isExtCtor identMap qualifyAll fuel child bnd + (child' :: acc, bnd')) ([], bound) + (.node info kindF (Stx.ofList revChildren.reverse), bound') + +/-- Rewrite a single binder node's domain type using `rwRec` and extend `locals` with its bound names. -/ +def rewriteSingleBinder (rwRec : NameSet → Stx → Stx) + (locals : NameSet) (binderStx : Stx) : NameSet × Stx := + let k := Syntax.getKind binderStx + let binderStx' := + if k == SyntaxKind.explicitBinder || k == SyntaxKind.implicitBinder || + k == SyntaxKind.strictImplicitBinder || k == SyntaxKind.instBinder then + match binderStx with + | .node info bk bargs => + let tyNode := Syntax.listGetD bargs.toList 3 .missing + if Syntax.isNone tyNode || Syntax.isMissing tyNode then binderStx + else + let tyNode' := rwRec locals tyNode + .node info bk (stxSetD bargs 3 tyNode') + | _ => binderStx + else + binderStx + let names := extractBinderNames binderStx + let locals' := names.foldl (fun s n => s.insert n) locals + (locals', binderStx') + +/-- Rewrite an array of binder nodes left-to-right, threading bound local names. -/ +def rewriteBinderArray (rwRec : NameSet → Stx → Stx) + (locals : NameSet) (binders : Array Stx) : NameSet × Array Stx := + let (locals', revBinders) := binders.toList.foldl (fun (loc, acc) b => + let (loc', b') := rewriteSingleBinder rwRec loc b + (loc', b' :: acc)) (locals, []) + (locals', Array.mk revBinders.reverse) + +/-- Binder-aware term/type/tactic `Syntax` rewriter: rewrites free references via + `rewriteIdentInScope` while respecting all local variable binders (`fun`, `forall`, + `let`, `have`, `if h :`, `match` patterns, structure field projections, and tactics). -/ +def rewriteSyntaxRefs (scope : ScopeSnapshot) (modIdx : ModuleIndex) + (isExtConst : Ix.Name → Bool) (isExtCtor : Ix.Name → Bool) + (identMap : NameMap Ix.Name) (qualifyAll : Bool) : + Nat → NameSet → Stx → Stx + | 0, _, stx => stx + | fuel + 1, locals, stx => + let rwRec := rewriteSyntaxRefs scope modIdx isExtConst isExtCtor identMap qualifyAll fuel + match stx with + | .missing | .atom _ _ | .snil | .scons .. => stx + | .ident info _ idF => + let id := FName.toIxName idF + if Name.isAnonymous id || locals.contains id then + stx + else + -- Check if `id` is `.` (first component is in `locals`) + let headComp := match Name.components id with + | c :: _ => Name.simple c + | [] => Name.mkAnon + if !Name.isAnonymous headComp && locals.contains headComp then + stx + else + let newId := rewriteIdentInScope scope modIdx isExtConst identMap qualifyAll id + if newId == id then stx + else mkIdentPreserveInfo info newId + | .node info kindF args => + let kind := FName.toIxName kindF + -- 1. `fun binders => body` + if kind == SyntaxKind.funTerm then + let bNode := Syntax.listGetD args.toList 1 .missing + let body := Syntax.listGetD args.toList 3 .missing + let (locals', bArgs') := rewriteBinderArray rwRec locals (Syntax.getArgs bNode) + let bNode' := match bNode with + | .node bi bk _ => .node bi bk (Stx.ofArray bArgs') + | other => other + let body' := rwRec locals' body + .node info kindF (stxSetD (stxSetD args 1 bNode') 3 body') + -- 2. `forall binders, vPref body` or `(binders) → vPref body` + else if kind == SyntaxKind.forallTerm then + let isKwForall := match Syntax.listGet? args.toList 0 with + | some (.atom _ kw) => Sym.beq kw (s% "forall") || Sym.beq kw (s% "∀") + | _ => false + let bIdx := if isKwForall then 1 else 0 + let bodyIdx := if isKwForall then 4 else 3 + let bNode := Syntax.listGetD args.toList bIdx .missing + let body := Syntax.listGetD args.toList bodyIdx .missing + let (locals', bArgs') := rewriteBinderArray rwRec locals (Syntax.getArgs bNode) + let bNode' := match bNode with + | .node bi bk _ => .node bi bk (Stx.ofArray bArgs') + | other => other + let body' := rwRec locals' body + .node info kindF (stxSetD (stxSetD args bIdx bNode') bodyIdx body') + -- 3. `let bPref id binders optType := val; body` + else if kind == SyntaxKind.letTerm then + let idStx := Syntax.listGetD args.toList 2 .missing + let bNode := Syntax.listGetD args.toList 3 .missing + let optTy := Syntax.listGetD args.toList 4 .missing + let val := Syntax.listGetD args.toList 6 .missing + let body := Syntax.listGetD args.toList 8 .missing + let (localsBind, bArgs') := rewriteBinderArray rwRec locals (Syntax.getArgs bNode) + let bNode' := match bNode with | .node bi bk _ => .node bi bk (Stx.ofArray bArgs') | o => o + let optTy' := rwRec localsBind optTy + let val' := rwRec localsBind val + let letId := Syntax.getId idStx + let localsBody := if Name.isAnonymous letId then locals else locals.insert letId + let body' := rwRec localsBody body + let args1 := stxSetD (stxSetD args 3 bNode') 4 optTy' + let args2 := stxSetD (stxSetD args1 6 val') 8 body' + .node info kindF args2 + -- 4. `let borrow` / `let rec` + else if kind == SyntaxKind.letBorrowTerm || kind == SyntaxKind.letRecTerm then + let idStx := Syntax.listGetD args.toList 3 .missing + let bNode := Syntax.listGetD args.toList 4 .missing + let optTy := Syntax.listGetD args.toList 5 .missing + let val := Syntax.listGetD args.toList 7 .missing + let body := Syntax.listGetD args.toList 9 .missing + let letId := Syntax.getId idStx + let localsInit := + if kind == SyntaxKind.letRecTerm && !Name.isAnonymous letId then locals.insert letId + else locals + let (localsBind, bArgs') := rewriteBinderArray rwRec localsInit (Syntax.getArgs bNode) + let bNode' := match bNode with | .node bi bk _ => .node bi bk (Stx.ofArray bArgs') | o => o + let optTy' := rwRec localsBind optTy + let val' := rwRec localsBind val + let localsBody := if Name.isAnonymous letId then locals else locals.insert letId + let body' := rwRec localsBody body + let args1 := stxSetD (stxSetD args 4 bNode') 5 optTy' + let args2 := stxSetD (stxSetD args1 7 val') 9 body' + .node info kindF args2 + -- 5. `have id optType := val; body` + else if kind == SyntaxKind.haveTerm then + let idStx := Syntax.listGetD args.toList 1 .missing + let optTy := Syntax.listGetD args.toList 2 .missing + let val := Syntax.listGetD args.toList 4 .missing + let body := Syntax.listGetD args.toList 6 .missing + let optTy' := rwRec locals optTy + let val' := rwRec locals val + let haveId := Syntax.getId idStx + let localsBody := if Name.isAnonymous haveId then locals else locals.insert haveId + let body' := rwRec localsBody body + let args1 := stxSetD (stxSetD args 2 optTy') 4 val' + .node info kindF (stxSetD args1 6 body') + -- 6. `if [h :] cond then t else e` + else if kind == SyntaxKind.ifTerm then + if args.size == 8 then + let hId := Syntax.getId (Syntax.listGetD args.toList 1 .missing) + let cond := Syntax.listGetD args.toList 3 .missing + let thenBr := Syntax.listGetD args.toList 5 .missing + let elseBr := Syntax.listGetD args.toList 7 .missing + let cond' := rwRec locals cond + let locals' := if Name.isAnonymous hId then locals else locals.insert hId + let thenBr' := rwRec locals' thenBr + let elseBr' := rwRec locals' elseBr + let args1 := stxSetD (stxSetD args 3 cond') 5 thenBr' + .node info kindF (stxSetD args1 7 elseBr') + else + let cond := Syntax.listGetD args.toList 2 .missing + let thenBr := Syntax.listGetD args.toList 4 .missing + let elseBr := Syntax.listGetD args.toList 6 .missing + let cond' := rwRec locals cond + let thenBr' := rwRec locals thenBr + let elseBr' := rwRec locals elseBr + let args1 := stxSetD (stxSetD args 2 cond') 4 thenBr' + .node info kindF (stxSetD args1 6 elseBr') + -- 7. `| pat1, pat2 => rhs` (`matchAlt`) + else if kind == SyntaxKind.matchAlt then + let patsNode := Syntax.listGetD args.toList 1 .missing + let rhs := Syntax.listGetD args.toList 3 .missing + let (revPats, locals') := (Syntax.getArgs patsNode).toList.foldl (fun (acc, bnd) p => + let (p', bnd') := rewritePattern scope modIdx isExtConst isExtCtor identMap qualifyAll fuel p bnd + (p' :: acc, bnd')) ([], locals) + let patsNode' := match patsNode with + | .node pi pk _ => .node pi pk (Stx.ofList revPats.reverse) + | other => other + let rhs' := rwRec locals' rhs + .node info kindF (stxSetD (stxSetD args 1 patsNode') 3 rhs') + -- 8. Projection `base.field` (`projTerm`): rewrite `base` (`args[0]`), keep `field` (`args[2]`) as short field name + else if kind == SyntaxKind.projTerm then + let base := Syntax.listGetD args.toList 0 .missing + let base' := rwRec locals base + .node info kindF (stxSetD args 0 base') + -- 9. Structure field assignment `field := val` (`structFieldAssign`): keep `args[0]` (`field`), rewrite `args[2]` (`val`) + else if kind == SyntaxKind.structFieldAssign then + let val := Syntax.listGetD args.toList 2 .missing + let val' := rwRec locals val + .node info kindF (stxSetD args 2 val') + -- 10. Tactic sequence + else if kind == SyntaxKind.tacticSeq then + let (_, revTacs) := args.toList.foldl (fun (loc, acc) tac => + let tk := Syntax.getKind tac + if tk == SyntaxKind.tacticIntro || tk == SyntaxKind.tacticFunext || tk == SyntaxKind.tacticExt then + let ids := (Syntax.getArgs (Syntax.getArg tac 1)).toList.map Syntax.getId + let loc' := ids.foldl (fun s id => if Name.isAnonymous id then s else s.insert id) loc + (loc', tac :: acc) + else if tk == SyntaxKind.tacticHave || tk == SyntaxKind.tacticLet then + let lId := Syntax.getId (Syntax.getArg tac 1) + let optTy := Syntax.getArg tac 2 + let val := Syntax.getArg tac 4 + let optTy' := rwRec loc optTy + let val' := rwRec loc val + let tac' := match tac with + | .node ti tk' targs => .node ti tk' (stxSetD (stxSetD targs 2 optTy') 4 val') + | o => o + let loc' := if Name.isAnonymous lId then loc else loc.insert lId + (loc', tac' :: acc) + else + (loc, rwRec loc tac :: acc)) (locals, []) + .node info kindF (Stx.ofList revTacs.reverse) + else if kind == SyntaxKind.tacticAlt || kind == SyntaxKind.tacticCase then + let boundIds := (Syntax.getArgs (Syntax.listGetD args.toList 2 .missing)).toList.map Syntax.getId + let locals' := boundIds.foldl (fun s id => if Name.isAnonymous id then s else s.insert id) locals + let seq := Syntax.listGetD args.toList 4 .missing + let seq' := rwRec locals' seq + .node info kindF (stxSetD args 4 seq') + else if kind == SyntaxKind.tacticRw then + let rules := Syntax.listGetD args.toList 2 .missing + let rules' := rwRec locals rules + .node info kindF (stxSetD args 2 rules') + else if kind == SyntaxKind.tacticSimp || kind == SyntaxKind.tacticDSimp then + let rules := Syntax.listGetD args.toList 1 .missing + let rules' := rwRec locals rules + .node info kindF (stxSetD args 1 rules') + else + let children' := Stx.ofList (args.toList.map (rwRec locals)) + .node info kindF children' + +/-- Rewrite a `ModuleDecl` under `identMap : NameMap Ix.Name` (and optionally hermetically + normalize it by folding `scope.levelNames` and `scope.varBinders` into the declaration AST + and qualifying all scope-resolved module references). -/ +def rewriteModuleDecl (modIdx : ModuleIndex) + (isExtConst : Ix.Name → Bool) (isExtCtor : Ix.Name → Bool) + (identMap : NameMap Ix.Name) (hermetic : Bool) + (decl : ModuleDecl) (fuel : Nat := 256) : ModuleDecl := + let scope := decl.scope + let newFullName := (identMap.get? decl.fullName).getD decl.fullName + let newShortName := if hermetic || newFullName != decl.fullName then newFullName else decl.shortName + let newUnivs := + if hermetic then (decl.univParams ++ scope.levelNames).eraseDups + else decl.univParams + let rwRec := rewriteSyntaxRefs scope modIdx isExtConst isExtCtor identMap hermetic fuel + let cmd := decl.stx + let k := Syntax.getKind cmd + match cmd with + | .node info ck cargs => + -- Merge section `variable` binders if `hermetic` is true + let origBindersNode := Syntax.listGetD cargs.toList 4 (Syntax.mkNullNode #[]) + let origBinders := Syntax.getArgs origBindersNode + let combinedBinders : Array Stx := + if hermetic && !scope.varBinders.isEmpty then + let existingNames : List Ix.Name := origBinders.toList.flatMap extractBinderNames + let neededVars := scope.varBinders.toList.filter fun vb => + let vNames := extractBinderNames vb + !vNames.any (existingNames.contains ·) + Array.mk neededVars ++ origBinders + else + origBinders + let (localsSig, binders') := rewriteBinderArray rwRec NameSet.empty combinedBinders + let newBindersNode := Syntax.mkNullNode binders' + let newIdNode := Syntax.mkSimpleIdent newShortName + let newUnivNode := + if newUnivs.isEmpty then Syntax.listGetD cargs.toList 3 (Syntax.mkNullNode #[]) + else Stx.node .none SyntaxKindF.univParamsKind (Stx.ofList (newUnivs.map Syntax.mkSimpleIdent)) + let cargsBase := stxSetD (stxSetD (stxSetD cargs 2 newIdNode) 3 newUnivNode) 4 newBindersNode + let newCmd : Stx := + if k == SyntaxKind.defDecl || k == SyntaxKind.abbrevDecl || + k == SyntaxKind.theoremDecl || k == SyntaxKind.opaqueDecl then + let optTy := Syntax.listGetD cargsBase.toList 6 .missing + let optTy' := rwRec localsSig optTy + let cargs1 := stxSetD cargsBase 6 optTy' + if cargs1.size == 9 then + let body := Syntax.listGetD cargs1.toList 8 .missing + let body' := rwRec localsSig body + .node info ck (stxSetD cargs1 8 body') + else + let alts := Syntax.listGetD cargs1.toList 7 .missing + let alts' := rwRec localsSig alts + .node info ck (stxSetD cargs1 7 alts') + else if k == SyntaxKind.axiomDecl then + let ty := Syntax.listGetD cargsBase.toList 6 .missing + let ty' := rwRec localsSig ty + .node info ck (stxSetD cargsBase 6 ty') + else if k == SyntaxKind.instanceDecl then + let ty := Syntax.listGetD cargsBase.toList 6 .missing + let body := Syntax.listGetD cargsBase.toList 8 .missing + let ty' := rwRec localsSig ty + let body' := rwRec localsSig body + .node info ck (stxSetD (stxSetD cargsBase 6 ty') 8 body') + else if k == SyntaxKind.inductiveDecl then + -- Add the inductive's own name to `identMap` if renamed, and rewrite constructors & deriving + let optTy := Syntax.listGetD cargsBase.toList 6 .missing + let ctorsNode := Syntax.listGetD cargsBase.toList 7 .missing + let derivNode := Syntax.listGetD cargsBase.toList 8 .missing + let optTy' := rwRec localsSig optTy + let ctors' := Array.mk ((Syntax.getArgs ctorsNode).toList.map fun ctorStx => + match ctorStx with + | .node ci ck' cArgs => + let cbNode := Syntax.listGetD cArgs.toList 2 .missing + let cOptTy := Syntax.listGetD cArgs.toList 4 .missing + let (localsCtor, cbArgs') := rewriteBinderArray rwRec localsSig (Syntax.getArgs cbNode) + let cbNode' := Syntax.mkNullNode cbArgs' + let cOptTy' := rwRec localsCtor cOptTy + Stx.node ci ck' (stxSetD (stxSetD cArgs 2 cbNode') 4 cOptTy') + | other => other) + let ctorsNode' := Syntax.mkNullNode ctors' + let derivNode' := rwRec localsSig derivNode + let cargs1 := stxSetD (stxSetD cargsBase 6 optTy') 7 ctorsNode' + .node info ck (stxSetD cargs1 8 derivNode') + else if k == SyntaxKind.structureDecl || k == SyntaxKind.classDecl then + let extNode := Syntax.listGetD cargsBase.toList 5 .missing + let optTy := Syntax.listGetD cargsBase.toList 7 .missing + let fieldsNode := Syntax.listGetD cargsBase.toList 9 .missing + let derivNode := Syntax.listGetD cargsBase.toList 10 .missing + let extNode' := rwRec localsSig extNode + let optTy' := rwRec localsSig optTy + let (_, revFields) := (Syntax.getArgs fieldsNode).toList.foldl (fun (loc, acc) item => + if Syntax.isOfKind item SyntaxKind.ctorDecl then + match item with + | .node ci ck' cArgs => + let cbNode := Syntax.listGetD cArgs.toList 2 .missing + let cOptTy := Syntax.listGetD cArgs.toList 4 .missing + let (locCtor, cbArgs') := rewriteBinderArray rwRec loc (Syntax.getArgs cbNode) + let cbNode' := Syntax.mkNullNode cbArgs' + let cOptTy' := rwRec locCtor cOptTy + (loc, Stx.node ci ck' (stxSetD (stxSetD cArgs 2 cbNode') 4 cOptTy') :: acc) + | other => (loc, other :: acc) + else if Syntax.isOfKind item SyntaxKind.fieldDecl then + match item with + | .node fi fk fArgs => + let isBracketed := match Syntax.listGet? fArgs.toList 0 with + | some (.atom _ (s% "(")) | some (.atom _ (s% "{")) => true + | _ => false + let idsIdx := if isBracketed then 2 else 1 + let tyIdx := if isBracketed then 5 else 4 + let defIdx := if isBracketed then 6 else 5 + let idsNode := Syntax.listGetD fArgs.toList idsIdx .missing + let tyNode := Syntax.listGetD fArgs.toList tyIdx .missing + let defNode := Syntax.listGetD fArgs.toList defIdx .missing + let tyNode' := rwRec loc tyNode + let defNode' := rwRec loc defNode + let fIds := (Syntax.getArgs idsNode).toList.map Syntax.getId + let loc' := fIds.foldl (fun s id => if Name.isAnonymous id then s else s.insert id) loc + let fArgs' := stxSetD (stxSetD fArgs tyIdx tyNode') defIdx defNode' + (loc', Stx.node fi fk fArgs' :: acc) + | other => (loc, other :: acc) + else + (loc, rwRec loc item :: acc)) (localsSig, []) + let fieldsNode' := Syntax.mkNullNode (Array.mk revFields.reverse) + let derivNode' := rwRec localsSig derivNode + let cargs1 := stxSetD (stxSetD cargsBase 5 extNode') 7 optTy' + let cargs2 := stxSetD (stxSetD cargs1 9 fieldsNode') 10 derivNode' + .node info ck cargs2 + else + .node info ck cargsBase + let newCtors := decl.ctorNames.map fun c => + match c with + | .str _ last _ => Name.mkStr newFullName last + | _ => c + let newFields := decl.fieldNames.map fun f => + match f with + | .str _ last _ => Name.mkStr newFullName last + | _ => f + let newScope : ScopeSnapshot := + if hermetic then { isPrivate := scope.isPrivate, isProtected := scope.isProtected } + else scope + { decl with + shortName := newShortName + fullName := newFullName + univParams := newUnivs + scope := newScope + stx := newCmd + ctorNames := newCtors + fieldNames := newFields } + | _ => decl + +/-- Rebuild a fresh `ModuleIndex` from an array of `ModuleDecl`s and an `IxImportMap`. -/ +def buildModuleIndexFromDecls (decls : Array ModuleDecl) + (importMap : IxImportMap := IxImportMap.empty) : ModuleIndex := + let initIdx : ModuleIndex := { importMap } + decls.toList.foldl (fun acc d => acc.registerDecl d) initIdx + +/-- Synthesize a `SyntaxKind.moduleKind` AST from a `ModuleSchedule`'s declarations. -/ +def synthesizeModuleSyntax (sched : ModuleSchedule) : Stx := + let declList := sched.modIdx.decls.toList + let orderedCmds : List Stx := sched.sccs.toList.flatMap fun scc => + let sccDecls := scc.declIdxs.toList.filterMap (Syntax.listGet? declList) + sccDecls.map (·.stx) + Syntax.mkNode SyntaxKind.moduleKind (Array.mk orderedCmds) + +/-- Hermetically normalize every declaration in `sched : ModuleSchedule` so each declaration + carries its own fully qualified name, universe parameters, section variables, and + fully qualified module references. -/ +def hermeticizeModule (sched : ModuleSchedule) + (isExtConst : Ix.Name → Bool := fun _ => false) + (isExtCtor : Ix.Name → Bool := fun _ => false) : Except String ModuleSchedule := do + let hermDecls := Array.mk (sched.modIdx.decls.toList.map fun d => + rewriteModuleDecl sched.modIdx isExtConst isExtCtor NameMap.empty true d) + let newModIdx := buildModuleIndexFromDecls hermDecls sched.modIdx.importMap + scheduleModuleDecls newModIdx isExtConst isExtCtor + +/-! ## 4. Intra-Declaration Semantic & AST Pre-Merge -/ + +/-- Check whether an `Ix.Expr` contains `sorryAx`. -/ +def exprHasSorry : Nat → Ix.Expr → Bool + | 0, _ => false + | _ + 1, .const nm _ _ => nm == Name.simple "sorryAx" || nm == Name.simple "sorry" + | f + 1, .app fn arg _ => exprHasSorry f fn || exprHasSorry f arg + | f + 1, .lam _ t b _ _ => exprHasSorry f t || exprHasSorry f b + | f + 1, .forallE _ t b _ _ => exprHasSorry f t || exprHasSorry f b + | f + 1, .letE _ t v b _ _ => exprHasSorry f t || exprHasSorry f v || exprHasSorry f b + | f + 1, .proj _ _ s _ => exprHasSorry f s + | f + 1, .mdata _ e _ => exprHasSorry f e + | _, _ => false + +/-- Check whether two elaborated constants `ci1` and `ci2` in `baseEnv` can be unified + semantically without creating a `.#merge` conflict: + 1. **Proof Irrelevance Absorption**: Both are `.thmInfo` (or `Prop`-typed) with the same + level parameters and definitionally equal (`isDefEq`) statement types. + 2. **Definitional Equality**: Both are `.defnInfo` with the same level parameters and + definitionally equal types and values. -/ +def canSemanticallyUnifyConsts (baseEnv : IxElabEnv) + (ci1 ci2 : Ix.ConstantInfo) : Bool := + let c1 := Expr.ConstantInfo.getCnstPure ci1 + let c2 := Expr.ConstantInfo.getCnstPure ci2 + if c1.levelParams != c2.levelParams then false + else + let act : IxElabM Bool := do + let tyEq ← isDefEq 64 c1.type c2.type + if !tyEq then return false + else + match ci1, ci2 with + | .thmInfo _, .thmInfo _ => + return true + | .defnInfo v1, .defnInfo v2 => + -- Also check if the type is a `Prop` (`Sort 0`), or if the values are `isDefEq` + let tySort ← whnf 64 (← inferType 64 c1.type) + match stripMData tySort with + | .sort (.zero _) _ => return true + | _ => isDefEq 64 v1.value v2.value + | .axiomInfo _, .axiomInfo _ => + return true + | _, _ => + return false + match IxElabM.run' act {} { env := baseEnv } with + | .ok ok => ok + | .error _ => false + +/-- Try to unify two declarations `d1` and `d2` that share the same `fullName`: + 1. Fast path: identical intrinsic hash and position-stripped syntax (`syntaxBeqPure`). + 2. Semantic path: elaborate `d1` and `d2` individually against `sharedEnv`; if both elaborate + and satisfy `canSemanticallyUnifyConsts` (proof irrelevance for `theorem`s or `isDefEq` + for `def`s), pick the canonically smaller declaration (preferring `sorryAx`-free proofs). -/ +def tryUnifySameNameDecls (sharedEnv : IxElabEnv) + (d1 : ModuleDecl) (m1 i1 : Address) + (d2 : ModuleDecl) (m2 i2 : Address) : Option ModuleDecl := + if bytesBeq i1.hash.data.toList i2.hash.data.toList && syntaxBeqPure d1.stx d2.stx then + some (if cmpDeclCanonical d1 m1 i1 d2 m2 i2 == .gt then d2 else d1) + else if d1.kind != d2.kind then + none + else + -- Try elaborating `d1` and `d2` as singleton modules over `sharedEnv` + let idx1 := buildModuleIndexFromDecls #[d1] + let idx2 := buildModuleIndexFromDecls #[d2] + match scheduleModuleDecls idx1 (fun n => sharedEnv.contains n) (fun n => sharedEnv.isCtor n), + scheduleModuleDecls idx2 (fun n => sharedEnv.contains n) (fun n => sharedEnv.isCtor n) with + | .ok s1, .ok s2 => + match elabModuleSchedule s1 sharedEnv false, elabModuleSchedule s2 sharedEnv false with + | .ok env1, .ok env2 => + match env1.find? d1.fullName, env2.find? d2.fullName with + | some ci1, some ci2 => + if canSemanticallyUnifyConsts sharedEnv ci1 ci2 then + let s1HasSorry := match ci1 with + | .thmInfo v => exprHasSorry 64 v.value + | .defnInfo v => exprHasSorry 64 v.value + | _ => false + let s2HasSorry := match ci2 with + | .thmInfo v => exprHasSorry 64 v.value + | .defnInfo v => exprHasSorry 64 v.value + | _ => false + if s1HasSorry && !s2HasSorry then some d2 + else if s2HasSorry && !s1HasSorry then some d1 + else some (if cmpDeclCanonical d1 m1 i1 d2 m2 i2 == .gt then d2 else d1) + else + none + | _, _ => none + | _, _ => none + | _, _ => none + +/-- Keyed 3-way merge of `matchAlt` sequences (`| pat => rhs` arms keyed by constructor/pattern head). + If `left` and `right` modified disjoint arms relative to `base`, splices both edits! -/ +def mergeMatchAlts3 (baseAlts leftAlts rightAlts : Stx) : Option Stx := + let bArms := (Syntax.getArgs baseAlts).toList + let lArms := (Syntax.getArgs leftAlts).toList + let rArms := (Syntax.getArgs rightAlts).toList + if !Syntax.isOfKind baseAlts SyntaxKind.nullKind || + !Syntax.isOfKind leftAlts SyntaxKind.nullKind || + !Syntax.isOfKind rightAlts SyntaxKind.nullKind || + bArms.isEmpty || + !bArms.all (Syntax.isOfKind · SyntaxKind.matchAlt) || + bArms.length != lArms.length || bArms.length != rArms.length then + none + else + let rec go : List Stx → List Stx → List Stx → Option (List Stx) + | [], [], [] => some [] + | b :: bs, l :: ls, r :: rs => + let bPat := Syntax.getArg b 1 + let lPat := Syntax.getArg l 1 + let rPat := Syntax.getArg r 1 + if !syntaxBeqPure bPat lPat || !syntaxBeqPure bPat rPat then + none + else + let chosen? : Option Stx := + if syntaxBeqPure l r then some l + else if syntaxBeqPure b l then some r + else if syntaxBeqPure b r then some l + else none + match chosen?, go bs ls rs with + | some arm, some rest => some (arm :: rest) + | _, _ => none + | _, _, _ => none + match go bArms lArms rArms with + | some mergedArms => + some (Syntax.mkNullNode (Array.mk mergedArms)) + | none => none + +/-- Keyed 3-way merge of `structInst` (`{ f₁ := v₁, f₂ := v₂ }` keyed by field name). -/ +def mergeStructInst3 (baseStx leftStx rightStx : Stx) : Option Stx := + if !Syntax.isOfKind baseStx SyntaxKind.structInst || + !Syntax.isOfKind leftStx SyntaxKind.structInst || + !Syntax.isOfKind rightStx SyntaxKind.structInst then + none + else + let bAssigns := (Syntax.getArgs (Syntax.getArg baseStx 2)).toList + let lAssigns := (Syntax.getArgs (Syntax.getArg leftStx 2)).toList + let rAssigns := (Syntax.getArgs (Syntax.getArg rightStx 2)).toList + if bAssigns.length != lAssigns.length || bAssigns.length != rAssigns.length then + none + else + let rec go : List Stx → List Stx → List Stx → Option (List Stx) + | [], [], [] => some [] + | b :: bs, l :: ls, r :: rs => + let bField := Syntax.getId (Syntax.getArg b 0) + let lField := Syntax.getId (Syntax.getArg l 0) + let rField := Syntax.getId (Syntax.getArg r 0) + if bField != lField || bField != rField then none + else + let chosen? : Option Stx := + if syntaxBeqPure l r then some l + else if syntaxBeqPure b l then some r + else if syntaxBeqPure b r then some l + else none + match chosen?, go bs ls rs with + | some item, some rest => some (item :: rest) + | _, _ => none + | _, _, _ => none + match go bAssigns lAssigns rAssigns with + | some merged => + match leftStx with + | .node info k args => + some (.node info k (stxSetD args 2 (Syntax.mkNullNode (Array.mk merged)))) + | _ => none + | none => none + +/-- Recursive 3-way AST splice on term/command `Syntax` nodes (`base`, `left`, `right`). + Succeeds when changes in `left` and `right` relative to `base` occur in disjoint subtrees + (including keyed `matchAlts` and `structInst` nodes). -/ +def spliceSyntax3 : Nat → Stx → Stx → Stx → Option Stx + | 0, _, _, _ => none + | fuel + 1, b, l, r => + if syntaxBeqPure l r then some l + else if syntaxBeqPure b l then some r + else if syntaxBeqPure b r then some l + else + match mergeMatchAlts3 b l r with + | some m => some m + | none => + match mergeStructInst3 b l r with + | some m => some m + | none => + match b, l, r with + | .node _ kb asB, .node info kl asL, .node _ kr asR => + if kb != kl || kb != kr || asB.size != asL.size || asB.size != asR.size then + none + else + let rec goChildren : List Stx → List Stx → List Stx → Option (List Stx) + | [], [], [] => some [] + | cb :: cbs, cl :: cls, cr :: crs => + match spliceSyntax3 fuel cb cl cr, goChildren cbs cls crs with + | some c', some rest => some (c' :: rest) + | _, _ => none + | _, _, _ => none + match goChildren asB.toList asL.toList asR.toList with + | some children' => some (.node info kl (Stx.ofList children')) + | none => none + | _, _, _ => none + +/-- Attempt a 3-way AST splice on a declaration `dBase`, `dLeft`, `dRight` with the same name. -/ +def tryMergeDeclSyntax3 (dBase dLeft dRight : ModuleDecl) : Option ModuleDecl := + if dBase.kind != dLeft.kind || dBase.kind != dRight.kind then none + else + match spliceSyntax3 128 dBase.stx dLeft.stx dRight.stx with + | some mergedStx => some { dLeft with stx := mergedStx } + | none => none + +/-! ## 5. Disambiguated Conflict Name Generation -/ + +/-- Pick the pair of disambiguated names `(nameForFirst, nameForSecond)` for a conflicted + declaration `origName`, avoiding any existing names in `usedNames : NameSet`. -/ +def makeDisambiguatedPair (mode : DisambigMode) (usedNames : NameSet) + (origName : Ix.Name) : Ix.Name × Ix.Name := + match mode with + | .mergeIndexed => + let rec findFreePair (fuel : Nat) (startIdx : Nat) : Ix.Name × Ix.Name := + match fuel with + | 0 => (Name.mkMergeVariant origName "_1", Name.mkMergeVariant origName "_2") + | fuel + 1 => + let cand1 := Name.mkMergeVariant origName s!"_{startIdx}" + let cand2 := Name.mkMergeVariant origName s!"_{startIdx + 1}" + if !usedNames.contains cand1 && !usedNames.contains cand2 then + (cand1, cand2) + else + findFreePair fuel (startIdx + 1) + findFreePair 64 1 + | .mergeNamed tag1 tag2 => + (Name.mkMergeVariant origName tag1, Name.mkMergeVariant origName tag2) + | .namespacePrefix pre1 pre2 => + (Name.append pre1 origName, Name.append pre2 origName) + | .indexedSuffix => + let comps := Name.components origName + let basePre := Name.fromComponents comps.dropLast + let lastStr := comps.getLastD "decl" + (Name.mkStr basePre s!"{lastStr}_1", Name.mkStr basePre s!"{lastStr}_2") + +/-! ## 6. 2-Way Disambiguating Module Merge (`mergeModuleSchedule2`, `mergeSource2`) -/ + +/-- Perform a 2-way module merge of `sched1` and `sched2`: + 1. Hermetically normalizes both schedules and computes their bottom-up BLAKE3-256 digests. + 2. Pre-elaborates the shared non-conflicting core so `tryUnifySameNameDecls` can absorb + proof-irrelevant theorem differences and definitionally equal definitions. + 3. For every remaining same-name collision `origName`, orders the two variants canonically + by 32-byte BLAKE3 Merkle `Address` (in symmetric modes `.mergeIndexed` and `.indexedSuffix`) + and assigns disambiguated names via `makeDisambiguatedPair`. + 4. Binder-awarely rewrites all declarations in `sched1` under `leftRenaming` and all + declarations in `sched2` under `rightRenaming`, orders the merged declaration set + canonically, and schedules it via Tarjan SCC condensation. -/ +def mergeModuleSchedule2 (sched1 sched2 : ModuleSchedule) + (mode : DisambigMode := .mergeIndexed) + (initEnv : IxElabEnv := IxElabEnv.empty) + (seedPrelude : Bool := true) + (semanticConflicts : NameSet := NameSet.empty) : Except String MergeOutcome := do + let isExtConst (n : Ix.Name) : Bool := initEnv.contains n + let isExtCtor (n : Ix.Name) : Bool := initEnv.isCtor n + let h1 ← hermeticizeModule sched1 isExtConst isExtCtor + let h2 ← hermeticizeModule sched2 isExtConst isExtCtor + let dig1 := computeModuleDigests h1 + let dig2 := computeModuleDigests h2 + let decls1 := h1.modIdx.decls.toList + let decls2 := h2.modIdx.decls.toList + + -- Collect all existing declaration names across both modules + let allOrigNames : NameSet := + decls2.foldl (fun s d => s.insert d.fullName) + (decls1.foldl (fun s d => s.insert d.fullName) NameSet.empty) + + -- Partition declarations present in both `h1` and `h2` into: + -- (a) syntactically identical declarations (`sharedFast`), and + -- (b) candidate collisions (`candidates`) + let (sharedFastDecls, candidates) := decls1.foldl + (fun (shAcc, candAcc) d1 => + match h2.modIdx.declByName.get? d1.fullName with + | none => (shAcc, candAcc) + | some idx2 => + match Syntax.listGet? decls2 idx2 with + | none => (shAcc, candAcc) + | some d2 => + if semanticConflicts.contains d1.fullName then + (shAcc, (d1, d2) :: candAcc) + else + let i1 := (dig1.intrinsic.get? d1.fullName).getD dummyAddr + let i2 := (dig2.intrinsic.get? d2.fullName).getD dummyAddr + if bytesBeq i1.hash.data.toList i2.hash.data.toList && syntaxBeqPure d1.stx d2.stx then + (d1 :: shAcc, candAcc) + else + (shAcc, (d1, d2) :: candAcc)) + ([], []) + + -- Elaborate the fast-shared core (when possible) to provide a base environment for + -- semantic unification (proof-irrelevance absorption & `isDefEq` check) + let sharedCoreEnv : IxElabEnv := + let base0 := if seedPrelude then seedCorePreludeIfMissing initEnv h1.modIdx else initEnv + let shIdx := buildModuleIndexFromDecls (Array.mk sharedFastDecls.reverse) + match scheduleModuleDecls shIdx (fun n => base0.contains n) (fun n => base0.isCtor n) with + | .ok shSched => + match elabModuleSchedule shSched base0 false with + | .ok env => env + | .error _ => base0 + | .error _ => base0 + + -- Classify each candidate pair into either `unifiedMap` or `conflictPairs` + let isSymmetricMode := match mode with + | .mergeIndexed | .indexedSuffix => true + | .mergeNamed _ _ | .namespacePrefix _ _ => false + + let (unifiedMap, revConflicts, leftRen, rightRen, _) := + candidates.reverse.foldl + (fun (uMap, cAcc, lRen, rRen, used) (d1, d2) => + let nm := d1.fullName + let m1 := (dig1.merkle.get? nm).getD dummyAddr + let i1 := (dig1.intrinsic.get? nm).getD dummyAddr + let m2 := (dig2.merkle.get? nm).getD dummyAddr + let i2 := (dig2.intrinsic.get? nm).getD dummyAddr + let unified? := + if semanticConflicts.contains nm then none + else tryUnifySameNameDecls sharedCoreEnv d1 m1 i1 d2 m2 i2 + match unified? with + | some uDecl => + (uMap.insert nm uDecl, cAcc, lRen, rRen, used) + | none => + let (candA, candB) := makeDisambiguatedPair mode used nm + let swapOrder := + isSymmetricMode && cmpDeclCanonical d1 m1 i1 d2 m2 i2 == .gt + let (leftTarget, rightTarget) := + if swapOrder then (candB, candA) else (candA, candB) + let cInfo : MergeConflictInfo := { + origName := nm + leftName := leftTarget + rightName := rightTarget + leftDigest := m1 + rightDigest := m2 + isSemanticConflict := semanticConflicts.contains nm + } + let used' := (used.insert leftTarget).insert rightTarget + (uMap, cInfo :: cAcc, lRen.insert nm leftTarget, rRen.insert nm rightTarget, used')) + (NameMap.empty, [], NameMap.empty, NameMap.empty, allOrigNames) + + let fastSet : NameSet := sharedFastDecls.foldl (fun s d => s.insert d.fullName) NameSet.empty + + -- Build rewritten declarations from `h1` (including `sharedFast`, `unifiedMap`, `O₁`, and `σ₁(K)`) + let rewritten1 : List ModuleDecl := decls1.map fun d1 => + let nm := d1.fullName + if fastSet.contains nm then + rewriteModuleDecl h1.modIdx isExtConst isExtCtor leftRen false d1 + else + match unifiedMap.get? nm with + | some uDecl => + rewriteModuleDecl h1.modIdx isExtConst isExtCtor leftRen false uDecl + | none => + rewriteModuleDecl h1.modIdx isExtConst isExtCtor leftRen false d1 + + -- Build rewritten declarations from `h2` that are NOT in `fastSet` or `unifiedMap` (i.e. `O₂` and `σ₂(K)`) + let rewritten2 : List ModuleDecl := decls2.filterMap fun d2 => + let nm := d2.fullName + if fastSet.contains nm || unifiedMap.contains nm then + none + else + some (rewriteModuleDecl h2.modIdx isExtConst isExtCtor rightRen false d2) + + -- Combine `rewritten1 ++ rewritten2` and sort canonically by `(fullName, cmpSyntaxPure)` so + -- declaration order in the merged module is 100% independent of `sched1` vs `sched2` argument order! + let allMergedDecls := Array.mk (rewritten1 ++ rewritten2) + let sortedMergedDecls := sortArrayBy allMergedDecls fun a b => + match compare a.fullName b.fullName with + | .lt => true + | .gt => false + | .eq => cmpSyntaxPure 256 a.stx b.stx == .lt + + let mergedImportMap := h1.modIdx.importMap.merge h2.modIdx.importMap + let mergedModIdx := buildModuleIndexFromDecls sortedMergedDecls mergedImportMap + let mergedSched ← scheduleModuleDecls mergedModIdx isExtConst isExtCtor + let mergedStx := synthesizeModuleSyntax mergedSched + -- Sort `conflicts` canonically by `origName` + let sortedConflicts := sortArrayBy (Array.mk revConflicts.reverse) fun a b => + compare a.origName b.origName == .lt + return { + sched := mergedSched + conflicts := sortedConflicts + leftRenaming := leftRen + rightRenaming := rightRen + moduleStx := mergedStx + } + +/-- Parse and 2-way merge two `.ix` source strings `src1` and `src2`. -/ +def mergeSource2 (src1 src2 : String) + (mode : DisambigMode := .mergeIndexed) + (initEnv : IxElabEnv := IxElabEnv.empty) + (seedPrelude : Bool := true) : Except String MergeOutcome := do + let (stx1, _) ← parseModuleWithEnv src1 "" + let (stx2, _) ← parseModuleWithEnv src2 "" + let modIdx1 ← buildModuleIndex stx1 + let modIdx2 ← buildModuleIndex stx2 + let base1 := if seedPrelude then seedCorePreludeIfMissing initEnv modIdx1 else initEnv + let base2 := if seedPrelude then seedCorePreludeIfMissing initEnv modIdx2 else initEnv + let sched1 ← scheduleModuleDecls modIdx1 (fun n => base1.contains n) (fun n => base1.isCtor n) + let sched2 ← scheduleModuleDecls modIdx2 (fun n => base2.contains n) (fun n => base2.isCtor n) + mergeModuleSchedule2 sched1 sched2 mode initEnv seedPrelude + +/-! ## 7. 3-Way Type-Contract-Preserving Module Merge (`mergeModuleSchedule3`, `mergeSource3`) -/ + +/-- Perform a 3-way module merge of `leftSched` ($M_1$) and `rightSched` ($M_2$) over common + ancestor `baseSched` ($M_0$), enforcing the **Caller-Callee Type-Checking Contract**: + 1. **1-Sided Deletion Propagation**: If $M_1$ deleted declaration $d \in M_0$ and $M_2$ left $d$ + unchanged and has no new callers of $d$ that fail without $d$, $d$ is deleted in the merge. + 2. **1-Sided Update Fast-Forward vs. Semantic Conflict Split (Cases A, B, C, D)**: + If $M_1$ modified $d$ ($d_0 \mapsto d_1$) and $M_2$ left $d$ unchanged ($d_2 = d_0$): + - We test substituting $d_1$ into $M_2$ (`M₂[d ↦ d₁]`) and running `elabModuleSchedule`. + - **Cases A & B (Elaboration succeeds)**: All callers and theorems in $M_2$ still typecheck + against $d_1$! We fast-forward $d \mapsto d_1$ in $M_2'$ so $d$ unifies cleanly with zero + `.#merge` conflicts. + - **Cases C & D (Elaboration fails — e.g. a theorem in $M_2$ unfolded $d_0$'s body via `rfl`, + or $M_1$ changed $d$'s type signature)**: Fast-forwarding $d_1$ would break caller + typechecking in $M_2$! We reject the fast-forward and mark $d$ in `semanticConflicts`, + so `mergeModuleSchedule2` splits $d$ into `d.#merge._1` (used by $M_1$'s callers) and + `d.#merge._2` (retaining $d_0$ for $M_2$'s callers), preserving 100% caller typechecking. + 3. **2-Sided AST Pre-Merge (`tryMergeDeclSyntax3`)**: + If both $M_1$ and $M_2$ modified $d$, attempts a 3-way AST splice (`spliceSyntax3`, + including keyed `match` arms and `structInst` fields) and verifies that the spliced + declaration elaborates cleanly in both $M_1$ and $M_2$. -/ +def mergeModuleSchedule3 (baseSched leftSched rightSched : ModuleSchedule) + (mode : DisambigMode := .mergeIndexed) + (initEnv : IxElabEnv := IxElabEnv.empty) + (seedPrelude : Bool := true) : Except String MergeOutcome := do + let isExtConst (n : Ix.Name) : Bool := initEnv.contains n + let isExtCtor (n : Ix.Name) : Bool := initEnv.isCtor n + let h0 ← hermeticizeModule baseSched isExtConst isExtCtor + let h1 ← hermeticizeModule leftSched isExtConst isExtCtor + let h2 ← hermeticizeModule rightSched isExtConst isExtCtor + let dig0 := computeModuleDigests h0 + let dig1 := computeModuleDigests h1 + let dig2 := computeModuleDigests h2 + let decls0 := h0.modIdx.decls.toList + let decls1 := h1.modIdx.decls.toList + let decls2 := h2.modIdx.decls.toList + + let sameDeclAsBase (dBranch : ModuleDecl) (digBranch : ModuleDigests) (dBase : ModuleDecl) : Bool := + let iB := (digBranch.intrinsic.get? dBranch.fullName).getD dummyAddr + let i0 := (dig0.intrinsic.get? dBase.fullName).getD dummyAddr + bytesBeq iB.hash.data.toList i0.hash.data.toList && syntaxBeqPure dBranch.stx dBase.stx + + -- Helper to test whether replacing/removing declarations in `targetDecls` still elaborates cleanly + let canElaborateDecls (candDecls : List ModuleDecl) (impMap : IxImportMap) : Bool := + let cIdx := buildModuleIndexFromDecls (Array.mk candDecls) impMap + let baseEnv := if seedPrelude then seedCorePreludeIfMissing initEnv cIdx else initEnv + match scheduleModuleDecls cIdx (fun n => baseEnv.contains n) (fun n => baseEnv.isCtor n) with + | .ok cSched => (elabModuleSchedule cSched baseEnv false).isOk + | .error _ => false + + -- Step 1: Propagate 1-sided deletions and 1-sided updates from `h1` into `decls2`, + -- and symmetrically from `h2` into `decls1`, gated by `canElaborateDecls`! + let (decls1', decls2', semConflicts) := decls0.foldl + (fun (cur1, cur2, semSet) d0 => + let nm := d0.fullName + let in1? := cur1.find? (fun d => d.fullName == nm) + let in2? := cur2.find? (fun d => d.fullName == nm) + match in1?, in2? with + | none, none => + (cur1, cur2, semSet) + | none, some d2 => + -- Deleted in Left, present in Right: if unchanged in Right and Right elaborates without `nm`, delete it + if sameDeclAsBase d2 dig2 d0 then + let cand2 := cur2.filter (fun d => d.fullName != nm) + if canElaborateDecls cand2 h2.modIdx.importMap then + (cur1, cand2, semSet) + else + (cur1, cur2, semSet.insert nm) + else + (cur1, cur2, semSet) + | some d1, none => + -- Deleted in Right, present in Left: if unchanged in Left and Left elaborates without `nm`, delete it + if sameDeclAsBase d1 dig1 d0 then + let cand1 := cur1.filter (fun d => d.fullName != nm) + if canElaborateDecls cand1 h1.modIdx.importMap then + (cand1, cur2, semSet) + else + (cur1, cur2, semSet.insert nm) + else + (cur1, cur2, semSet) + | some d1, some d2 => + let unch1 := sameDeclAsBase d1 dig1 d0 + let unch2 := sameDeclAsBase d2 dig2 d0 + if unch1 && unch2 then + (cur1, cur2, semSet) + else if !unch1 && unch2 then + -- Modified in Left (`d1`), untouched in Right (`d2 == d0`): + -- Test whether substituting `d1` into Right (`cur2`) preserves typechecking of all Right callers! + let cand2 := cur2.map (fun d => if d.fullName == nm then d1 else d) + if canElaborateDecls cand2 h2.modIdx.importMap then + -- Cases A & B: Fast-forward Right's copy of `nm` to `d1`! + (cur1, cand2, semSet) + else + -- Cases C & D: Right has a caller/theorem whose typechecking depends on `d0`! + -- Mark `nm` as a semantic conflict so it is split into `nm.#merge._1` and `nm.#merge._2`. + (cur1, cur2, semSet.insert nm) + else if unch1 && !unch2 then + -- Modified in Right (`d2`), untouched in Left (`d1 == d0`): + -- Test whether substituting `d2` into Left (`cur1`) preserves typechecking of all Left callers! + let cand1 := cur1.map (fun d => if d.fullName == nm then d2 else d) + if canElaborateDecls cand1 h1.modIdx.importMap then + (cand1, cur2, semSet) + else + (cur1, cur2, semSet.insert nm) + else + -- Both Left and Right modified `nm`: try 3-way AST splice (`tryMergeDeclSyntax3`) + match tryMergeDeclSyntax3 d0 d1 d2 with + | some splicedDecl => + let cand1 := cur1.map (fun d => if d.fullName == nm then splicedDecl else d) + let cand2 := cur2.map (fun d => if d.fullName == nm then splicedDecl else d) + if canElaborateDecls cand1 h1.modIdx.importMap && + canElaborateDecls cand2 h2.modIdx.importMap then + (cand1, cand2, semSet) + else + (cur1, cur2, semSet) + | none => + (cur1, cur2, semSet)) + (decls1, decls2, NameSet.empty) + + let propIdx1 := buildModuleIndexFromDecls (Array.mk decls1') h1.modIdx.importMap + let propIdx2 := buildModuleIndexFromDecls (Array.mk decls2') h2.modIdx.importMap + let propSched1 ← scheduleModuleDecls propIdx1 isExtConst isExtCtor + let propSched2 ← scheduleModuleDecls propIdx2 isExtConst isExtCtor + mergeModuleSchedule2 propSched1 propSched2 mode initEnv seedPrelude semConflicts + +/-- Parse and 3-way merge `.ix` source strings `baseSrc`, `leftSrc`, and `rightSrc`. -/ +def mergeSource3 (baseSrc leftSrc rightSrc : String) + (mode : DisambigMode := .mergeIndexed) + (initEnv : IxElabEnv := IxElabEnv.empty) + (seedPrelude : Bool := true) : Except String MergeOutcome := do + let (stx0, _) ← parseModuleWithEnv baseSrc "" + let (stx1, _) ← parseModuleWithEnv leftSrc "" + let (stx2, _) ← parseModuleWithEnv rightSrc "" + let modIdx0 ← buildModuleIndex stx0 + let modIdx1 ← buildModuleIndex stx1 + let modIdx2 ← buildModuleIndex stx2 + let base0 := if seedPrelude then seedCorePreludeIfMissing initEnv modIdx0 else initEnv + let base1 := if seedPrelude then seedCorePreludeIfMissing initEnv modIdx1 else initEnv + let base2 := if seedPrelude then seedCorePreludeIfMissing initEnv modIdx2 else initEnv + let sched0 ← scheduleModuleDecls modIdx0 (fun n => base0.contains n) (fun n => base0.isCtor n) + let sched1 ← scheduleModuleDecls modIdx1 (fun n => base1.contains n) (fun n => base1.isCtor n) + let sched2 ← scheduleModuleDecls modIdx2 (fun n => base2.contains n) (fun n => base2.isCtor n) + mergeModuleSchedule3 sched0 sched1 sched2 mode initEnv seedPrelude + +/-! ## 8. Conflict Resolution (`resolveConflictVariant`) & Elaboration Helper -/ + +/-- Elaborate a `MergeOutcome` into an `IxElabEnv` (converting `ElabError` to `String`). -/ +def MergeOutcome.elaborate (outcome : MergeOutcome) + (initEnv : IxElabEnv := IxElabEnv.empty) + (seedPrelude : Bool := true) : Except String IxElabEnv := + match elabModuleSchedule outcome.sched initEnv seedPrelude with + | .ok env => .ok env + | .error e => .error (toString e) + +/-- Resolve a `.#merge` conflict on `origName` in `sched` by selecting `chosenTag` + (e.g. `"_1"` or `"_2"`): + - Drops all other `origName.#merge.` variant declarations from `sched`. + - Renames `origName.#merge.` (and all references to any `origName.#merge.*` + variant across the module) back to `origName`. + - Reschedules and verifies that the resolved module elaborates and typechecks! -/ +def resolveConflictVariant (sched : ModuleSchedule) + (origName : Ix.Name) (chosenTag : String) + (initEnv : IxElabEnv := IxElabEnv.empty) + (seedPrelude : Bool := true) : Except String ModuleSchedule := do + let isExtConst (n : Ix.Name) : Bool := initEnv.contains n + let isExtCtor (n : Ix.Name) : Bool := initEnv.isCtor n + let variants := sched.modIdx.findConflictVariants origName + let chosenFull := Name.mkMergeVariant origName chosenTag + if !sched.modIdx.declByName.contains chosenFull then + throw s!"conflict variant '{Name.toStringTotal chosenFull}' not found in module" + let collapseMap : NameMap Ix.Name := variants.foldl + (fun acc (_, varFull) => acc.insert varFull origName) + (NameMap.empty.insert chosenFull origName) + let keptDecls := sched.modIdx.decls.toList.filter fun d => + match Name.splitMergeVariant? d.fullName with + | some (orig, tag, []) => orig != origName || tag == chosenTag + | _ => true + let rewrittenDecls := Array.mk (keptDecls.map fun d => + rewriteModuleDecl sched.modIdx isExtConst isExtCtor collapseMap true d) + let newModIdx := buildModuleIndexFromDecls rewrittenDecls sched.modIdx.importMap + let baseEnv := if seedPrelude then seedCorePreludeIfMissing initEnv newModIdx else initEnv + let newSched ← scheduleModuleDecls newModIdx (fun n => baseEnv.contains n) (fun n => baseEnv.isCtor n) + match elabModuleSchedule newSched baseEnv false with + | .ok _ => return newSched + | .error e => throw s!"conflict resolution to '{Name.toStringTotal chosenFull}' failed typecheck: {e}" + +/-! ## 9. Mechanized Algebraic Properties of `.#merge` Addressing & Canonical Ordering -/ + +/-- `Name.splitMergeVariant? (Name.mkMergeVariant orig tag)` recovers `(orig, tag, [])` + by definitional equality (`rfl`) for every `orig : Ix.Name` and `tag : String`. -/ +theorem splitMergeVariant_mkMergeVariant (orig : Ix.Name) (tag : String) : + Name.splitMergeVariant? (Name.mkMergeVariant orig tag) = some (orig, tag, []) := + rfl + +/-- `Name.isMergeConflict` is `true` on any `Name.mkMergeVariant orig tag` by `rfl`. -/ +theorem isMergeConflict_mkMergeVariant (orig : Ix.Name) (tag : String) : + Name.isMergeConflict (Name.mkMergeVariant orig tag) = true := + rfl + +/-- `Name.conflictOrigName? (Name.mkMergeVariant orig tag)` recovers `some orig` by `rfl`. -/ +theorem conflictOrigName_mkMergeVariant (orig : Ix.Name) (tag : String) : + Name.conflictOrigName? (Name.mkMergeVariant orig tag) = some orig := + rfl + +/-- `bytesBeq` is reflexive on any byte list `bs : List UInt8`. -/ +theorem bytesBeq_refl (bs : List UInt8) : bytesBeq bs bs = true := by + induction bs with + | nil => rfl + | cons b rest ih => + simp [bytesBeq, ih] + +/-- `charsBeq` is reflexive on any character list `cs : List Char`. -/ +theorem charsBeq_refl (cs : List Char) : charsBeq cs cs = true := by + induction cs with + | nil => rfl + | cons c rest ih => + simp [charsBeq, ih] + +/-- `strBeqPure` is reflexive on any `s : String`. -/ +theorem strBeqPure_refl (s : String) : strBeqPure s s = true := by + simp [strBeqPure, bytesBeq_refl] + +@[simp] theorem forceNat_eq (n : Nat) (k : Nat → α) : forceNat n k = k n := by + cases n <;> rfl + +/-- `natCmpPure` is reflexive on any `n : Nat`. -/ +theorem natCmpPure_refl (n : Nat) : natCmpPure n n = .eq := by + simp [natCmpPure] + +/-- `bytesCmp` is reflexive on any `bs : List UInt8`. -/ +theorem bytesCmp_refl (bs : List UInt8) : bytesCmp bs bs = .eq := by + induction bs with + | nil => rfl + | cons b rest ih => + have h : ¬ (b.toNat + 1 ≤ b.toNat) := by omega + simp [bytesCmp, h, ih] + +/-- `charsCmp` is reflexive on any `cs : List Char`. -/ +theorem charsCmp_refl (cs : List Char) : charsCmp cs cs = .eq := by + induction cs with + | nil => rfl + | cons c rest ih => + have h : ¬ (c.toNat + 1 ≤ c.toNat) := by omega + simp [charsCmp, h, ih] + +/-- `strCmpPure` is reflexive on any `s : String`. -/ +theorem strCmpPure_refl (s : String) : strCmpPure s s = .eq := by + simp [strCmpPure, natCmpPure_refl, bytesCmp_refl] + +end Ix.Frontend diff --git a/Ix/Frontend/Parser/Basic.lean b/Ix/Frontend/Parser/Basic.lean new file mode 100644 index 0000000000..eeaaf3f9d5 --- /dev/null +++ b/Ix/Frontend/Parser/Basic.lean @@ -0,0 +1,851 @@ +/- + Ix.Frontend.Parser.Basic: Pure, total UTF-8 byte lexer and parser combinators + for the Ix Frontend. + + 100% free of Lean `String` literals (`Lit.str`), `Char`, `UInt32`, and `Ix.Name` + in the circuit execution path: scans `Sym` (`ByteList`) directly in $O(1)$ per byte! +-/ +module + +public import Ix.Frontend.Parser.Types +public import Ix.Frontend.Parser.FastTables + +@[expose] public section + +namespace Ix.Frontend.Parser + +/-! ## Pure ASCII & UTF-8 Byte Predicates -/ + +@[inline] def isSpaceByte (b : Nat) : Bool := + Nat.beq b 32 || Nat.beq b 10 || Nat.beq b 9 || Nat.beq b 13 + +@[inline] def isDigitByte (b : Nat) : Bool := + Nat.ble 48 b && Nat.ble b 57 + +@[inline] def isHexDigitByte (b : Nat) : Bool := + (Nat.ble 48 b && Nat.ble b 57) || + (Nat.ble 97 b && Nat.ble b 102) || + (Nat.ble 65 b && Nat.ble b 70) + +@[inline] def hexDigitValByte (b : Nat) : Nat := + if Nat.ble 48 b && Nat.ble b 57 then Nat.sub b 48 + else if Nat.ble 97 b && Nat.ble b 102 then Nat.sub b 87 + else if Nat.ble 65 b && Nat.ble b 70 then Nat.sub b 55 + else 0 + +@[inline] def isAsciiLetterByte (b : Nat) : Bool := + (Nat.ble 97 b && Nat.ble b 122) || (Nat.ble 65 b && Nat.ble b 90) + +@[inline] def isAsciiIdFirstByte (b : Nat) : Bool := + isAsciiLetterByte b || Nat.beq b 95 + +@[inline] def isAsciiIdRestByte (b : Nat) : Bool := + isAsciiLetterByte b || isDigitByte b || + Nat.beq b 95 || Nat.beq b 39 || Nat.beq b 63 || Nat.beq b 33 + +/-- Cold helper: check if a non-ASCII UTF-8 byte sequence starts with a letter-like scalar + (Greek `α..ω`/`Α..Ω` excluding `λ`/`Π`/`Σ`, sub/superscripts `U+2070..U+209F`, + letterlike symbols `U+2100..U+214F`). Returns `some (revBytes, rest, byteLen)` or `none`. -/ +def scanUtf8LetterLike : Sym → Option (Sym × Sym × Nat) + | .cons b0 (.cons b1 rest) => + if Nat.beq b0 206 then + let okUpper := Nat.ble 145 b1 && Nat.ble b1 169 && !Nat.beq b1 160 && !Nat.beq b1 163 + let okLower := Nat.ble 177 b1 && Nat.ble b1 191 && !Nat.beq b1 187 + if okUpper || okLower then some (.cons b1 (.cons b0 .nil), rest, 2) else none + else if Nat.beq b0 207 then + if Nat.ble 128 b1 && Nat.ble b1 137 then some (.cons b1 (.cons b0 .nil), rest, 2) else none + else if Nat.beq b0 226 then + match rest with + | .cons b2 rest3 => + let ok := + (Nat.beq b1 129 && Nat.ble 176 b2 && Nat.ble b2 191) || + (Nat.beq b1 130 && Nat.ble 128 b2 && Nat.ble b2 159) || + (Nat.beq b1 132 && Nat.ble 128 b2 && Nat.ble b2 191) || + (Nat.beq b1 133 && Nat.ble 128 b2 && Nat.ble b2 143) + if ok then some (.cons b2 (.cons b1 (.cons b0 .nil)), rest3, 3) else none + | .nil => none + else + none + | _ => none + +/-! ## Whitespace & Comment Scanners (UTF-8 Bytes, $O(1)$ per Byte) -/ + +/-- Skip to the end of a `--` line comment on a `Sym` tail in $O(1)$ per byte. -/ +def skipLineCommentBytes : Sym → Nat → Bool → (Sym × Nat × Bool) + | .nil, pos, seenNl => (.nil, pos, seenNl) + | .cons b rest, pos, seenNl => + if Nat.beq b 10 then (rest, Nat.add pos 1, true) + else skipLineCommentBytes rest (Nat.add pos 1) seenNl + +/-- Skip a nested `/- ... -/` block comment on a `Sym` tail in $O(1)$ per byte. -/ +def skipBlockCommentBytes : Nat → Sym → Nat → Nat → Bool → Option (Sym × Nat × Bool) + | 0, _, _, _, _ => none + | _, .nil, _, _, _ => none + | fuel + 1, .cons b0 rest0, pos, nesting, seenNl => + if Nat.beq b0 47 then + match rest0 with + | .cons b1 rest1 => + if Nat.beq b1 45 then + skipBlockCommentBytes fuel rest1 (Nat.add pos 2) (Nat.add nesting 1) seenNl + else + skipBlockCommentBytes fuel rest0 (Nat.add pos 1) nesting seenNl + | .nil => none + else if Nat.beq b0 45 then + match rest0 with + | .cons b1 rest1 => + if Nat.beq b1 47 then + if Nat.ble nesting 1 then some (rest1, Nat.add pos 2, seenNl) + else skipBlockCommentBytes fuel rest1 (Nat.add pos 2) (Nat.sub nesting 1) seenNl + else + skipBlockCommentBytes fuel rest0 (Nat.add pos 1) nesting seenNl + | .nil => none + else + skipBlockCommentBytes fuel rest0 (Nat.add pos 1) nesting (seenNl || Nat.beq b0 10) + +/-- Advance past whitespace, `--` line comments, and `/- ... -/` block comments on a `Sym` tail, + returning `(remainingBytes, nextPos, hasLeadingNewline)` in a single $O(1)$-per-byte pass! -/ +def skipWhitespaceBytes (maxPos : Nat) : Nat → Sym → Nat → Bool → (Sym × Nat × Bool) + | 0, bs, pos, seenNl => (bs, pos, seenNl) + | fuel + 1, bs, pos, seenNl => + match bs with + | .nil => (.nil, pos, seenNl) + | .cons b0 rest0 => + if isSpaceByte b0 then + skipWhitespaceBytes maxPos fuel rest0 (Nat.add pos 1) (seenNl || Nat.beq b0 10) + else if Nat.beq b0 45 then + match rest0 with + | .cons b1 rest1 => + if Nat.beq b1 45 then + let (bs', pos', seenNl') := skipLineCommentBytes rest1 (Nat.add pos 2) seenNl + skipWhitespaceBytes maxPos fuel bs' pos' seenNl' + else (bs, pos, seenNl) + | .nil => (bs, pos, seenNl) + else if Nat.beq b0 47 then + match rest0 with + | .cons b1 rest1 => + if Nat.beq b1 45 then + match skipBlockCommentBytes parseFuel rest1 (Nat.add pos 2) 1 seenNl with + | some (bs', pos', seenNl') => skipWhitespaceBytes maxPos fuel bs' pos' seenNl' + | none => (.nil, maxPos, seenNl) + else (bs, pos, seenNl) + | .nil => (bs, pos, seenNl) + else + (bs, pos, seenNl) + +/-- Advance past horizontal spaces (`' '` = 32 and `'\t'` = 9) on a `Sym` tail in $O(1)$ per byte. -/ +def skipHorizontalWhitespaceBytes : Sym → Nat → (Sym × Nat) + | .cons b rest, pos => + if Nat.beq b 32 || Nat.beq b 9 then + skipHorizontalWhitespaceBytes rest (Nat.add pos 1) + else + (.cons b rest, pos) + | .nil, pos => (.nil, pos) + +/-- Check if a token's leading trivia contained a newline (`'\n'`) in $O(1)$ time! -/ +def hasLeadingNewline (stx : Stx) : Bool := + match Syntax.getHeadInfoF? 8 stx with + | some info => info.hasLeadingNewline + | none => false + +@[inline] def mkOriginalSourceInfoFast (hasNl : Bool) (tokStart tokStop : Nat) : FSourceInfo := + .original hasNl tokStart tokStop + +/-! ## Token Scanners (Numbers, Strings, Chars, Hash Refs, Identifiers, Operators) -/ + +/-- Scan decimal digits (plus `_` = 95) on a `Sym` tail in $O(1)$ per byte. -/ +def scanDecDigitsBytes : Sym → Nat → Sym → (Sym × Sym × Nat) + | .nil, pos, revAcc => (.nil, revAcc, pos) + | .cons b rest, pos, revAcc => + if isDigitByte b || Nat.beq b 95 then + scanDecDigitsBytes rest (Nat.add pos 1) (.cons b revAcc) + else + (.cons b rest, revAcc, pos) + +/-- Scan hex digits (plus `_` = 95) on a `Sym` tail in $O(1)$ per byte. -/ +def scanHexDigitsBytes : Sym → Nat → Sym → (Sym × Sym × Nat) + | .nil, pos, revAcc => (.nil, revAcc, pos) + | .cons b rest, pos, revAcc => + if isHexDigitByte b || Nat.beq b 95 then + scanHexDigitsBytes rest (Nat.add pos 1) (.cons b revAcc) + else + (.cons b rest, revAcc, pos) + +/-- Scan binary digits (`0` = 48, `1` = 49, `_` = 95) on a `Sym` tail in $O(1)$ per byte. -/ +def scanBinDigitsBytes : Sym → Nat → Sym → (Sym × Sym × Nat) + | .nil, pos, revAcc => (.nil, revAcc, pos) + | .cons b rest, pos, revAcc => + if Nat.beq b 48 || Nat.beq b 49 || Nat.beq b 95 then + scanBinDigitsBytes rest (Nat.add pos 1) (.cons b revAcc) + else + (.cons b rest, revAcc, pos) + +/-- Single-pass decimal digit parser on `Sym` (skipping `_` separators). -/ +def parseDecDigitsBytes : Sym → Nat → Bool → Option Nat + | .nil, acc, true => some acc + | .nil, _, false => none + | .cons b rest, acc, seen => + if Nat.beq b 95 then + parseDecDigitsBytes rest acc seen + else if isDigitByte b then + parseDecDigitsBytes rest (Nat.add (Nat.mul acc 10) (Nat.sub b 48)) true + else + none + +/-- Single-pass hex digit parser on `Sym` (skipping `_` separators). -/ +def parseHexDigitsBytes : Sym → Nat → Bool → Option Nat + | .nil, acc, true => some acc + | .nil, _, false => none + | .cons b rest, acc, seen => + if Nat.beq b 95 then + parseHexDigitsBytes rest acc seen + else if isHexDigitByte b then + parseHexDigitsBytes rest (Nat.add (Nat.mul acc 16) (hexDigitValByte b)) true + else + none + +/-- Single-pass binary digit parser on `Sym` (skipping `_` separators). -/ +def parseBinDigitsBytes : Sym → Nat → Bool → Option Nat + | .nil, acc, true => some acc + | .nil, _, false => none + | .cons b rest, acc, seen => + if Nat.beq b 95 then + parseBinDigitsBytes rest acc seen + else if Nat.beq b 48 then + parseBinDigitsBytes rest (Nat.mul acc 2) true + else if Nat.beq b 49 then + parseBinDigitsBytes rest (Nat.add (Nat.mul acc 2) 1) true + else + none + +/-- Parse the numeric value of a scanned `Sym` number literal. -/ +def parseNatLiteralSym (raw : Sym) : Option Nat := + match raw with + | .cons b0 (.cons b1 rest) => + if Nat.beq b0 48 && (Nat.beq b1 120 || Nat.beq b1 88) then parseHexDigitsBytes rest 0 false + else if Nat.beq b0 48 && (Nat.beq b1 98 || Nat.beq b1 66) then parseBinDigitsBytes rest 0 false + else parseDecDigitsBytes raw 0 false + | _ => parseDecDigitsBytes raw 0 false + +/-- Legacy `String` wrapper for `parseNatLiteral` (host / Elab boundary). -/ +def parseNatLiteral (raw : String) : Option Nat := + parseNatLiteralSym (Sym.ofString raw) + +/-- Scan a base-10, hex (`0x`), or binary (`0b`) natural number literal on `Sym`. + Returns `(normalizedDecSym?, remainingBytes, endPos)` (`none` on invalid `0x`/`0b`). -/ +def scanNumberBytes : Sym → Nat → Option (Sym × Sym × Nat) + | .cons b0 (.cons b1 rest), pos => + if Nat.beq b0 48 && (Nat.beq b1 120 || Nat.beq b1 88) then + let (rem, revHex, endPos) := scanHexDigitsBytes rest (Nat.add pos 2) .nil + match parseHexDigitsBytes (Sym.reverse revHex) 0 false with + | some n => some (Sym.ofNat n, rem, endPos) + | none => none + else if Nat.beq b0 48 && (Nat.beq b1 98 || Nat.beq b1 66) then + let (rem, revBin, endPos) := scanBinDigitsBytes rest (Nat.add pos 2) .nil + match parseBinDigitsBytes (Sym.reverse revBin) 0 false with + | some n => some (Sym.ofNat n, rem, endPos) + | none => none + else + let (rem, revDec, endPos) := scanDecDigitsBytes (.cons b0 (.cons b1 rest)) pos .nil + some (Sym.reverse revDec, rem, endPos) + | bs, pos => + let (rem, revDec, endPos) := scanDecDigitsBytes bs pos .nil + some (Sym.reverse revDec, rem, endPos) + +/-- Encode a byte `0..255` as reversed UTF-8 bytes prepended to `acc` (for `\xHH` escapes). -/ +def pushCodepointUtf8Rev (cp : Nat) (acc : Sym) : Sym := + if Nat.blt cp 128 then + .cons cp acc + else + .cons (Nat.add 128 (Nat.mod cp 64)) (.cons (Nat.add 192 (Nat.div cp 64)) acc) + +/-- Scan a string literal starting after the opening `"` on a `Sym` tail. + Returns `some (decodedUtf8Sym, remainingBytes, posAfterClosingQuote)` or `none`. -/ +def scanStringLitBytes : Sym → Nat → Sym → Option (Sym × Sym × Nat) + | .nil, _, _ => none + | .cons b rest, pos, acc => + if Nat.beq b 34 then + some (Sym.reverse acc, rest, Nat.add pos 1) + else if Nat.beq b 10 then + none + else if Nat.beq b 92 then + match rest with + | .nil => none + | .cons esc rest2 => + if Nat.beq esc 110 then scanStringLitBytes rest2 (Nat.add pos 2) (.cons 10 acc) + else if Nat.beq esc 116 then scanStringLitBytes rest2 (Nat.add pos 2) (.cons 9 acc) + else if Nat.beq esc 114 then scanStringLitBytes rest2 (Nat.add pos 2) (.cons 13 acc) + else if Nat.beq esc 92 then scanStringLitBytes rest2 (Nat.add pos 2) (.cons 92 acc) + else if Nat.beq esc 34 then scanStringLitBytes rest2 (Nat.add pos 2) (.cons 34 acc) + else if Nat.beq esc 39 then scanStringLitBytes rest2 (Nat.add pos 2) (.cons 39 acc) + else if Nat.beq esc 48 then scanStringLitBytes rest2 (Nat.add pos 2) (.cons 0 acc) + else if Nat.beq esc 120 then + match rest2 with + | .cons d1 (.cons d2 rest4) => + if isHexDigitByte d1 && isHexDigitByte d2 then + let cp := Nat.add (Nat.mul (hexDigitValByte d1) 16) (hexDigitValByte d2) + scanStringLitBytes rest4 (Nat.add pos 4) (pushCodepointUtf8Rev cp acc) + else none + | _ => none + else + scanStringLitBytes rest2 (Nat.add pos 2) (.cons esc acc) + else + scanStringLitBytes rest (Nat.add pos 1) (.cons b acc) + +/-- Scan a character literal starting after the opening `'` on a `Sym` tail. + Returns `some (decodedUtf8Sym, remainingBytes, posAfterClosingQuote)` or `none`. -/ +def scanCharLitBytes : Sym → Nat → Option (Sym × Sym × Nat) + | .cons b0 rest0, pos => + if Nat.beq b0 92 then + match rest0 with + | .cons esc (.cons q rest2) => + if Nat.beq q 39 then + let outByte := + if Nat.beq esc 110 then 10 + else if Nat.beq esc 116 then 9 + else if Nat.beq esc 114 then 13 + else if Nat.beq esc 92 then 92 + else if Nat.beq esc 39 then 39 + else if Nat.beq esc 34 then 34 + else if Nat.beq esc 48 then 0 + else esc + some (.cons outByte .nil, rest2, Nat.add pos 3) + else none + | _ => none + else if Nat.blt b0 128 then + match rest0 with + | .cons q rest1 => + if Nat.beq q 39 && !Nat.beq b0 39 && !Nat.beq b0 92 then + some (.cons b0 .nil, rest1, Nat.add pos 2) + else none + | _ => none + else if Nat.ble 194 b0 && Nat.ble b0 223 then + match rest0 with + | .cons b1 (.cons q rest2) => + if Nat.beq q 39 then some (.cons b0 (.cons b1 .nil), rest2, Nat.add pos 3) else none + | _ => none + else if Nat.ble 224 b0 && Nat.ble b0 239 then + match rest0 with + | .cons b1 (.cons b2 (.cons q rest3)) => + if Nat.beq q 39 then some (.cons b0 (.cons b1 (.cons b2 .nil)), rest3, Nat.add pos 4) else none + | _ => none + else + match rest0 with + | .cons b1 (.cons b2 (.cons b3 (.cons q rest4))) => + if Nat.beq q 39 then some (.cons b0 (.cons b1 (.cons b2 (.cons b3 .nil))), rest4, Nat.add pos 5) else none + | _ => none + | .nil, _ => none + +/-- Scan `[isIdRest]*` on a `Sym` tail in $O(1)$ per byte (fast ASCII loop + cold UTF-8 fallback). -/ +def scanIdentRestBytes : Nat → Sym → Nat → Sym → (Sym × Sym × Nat) + | 0, bs, pos, revAcc => (bs, Sym.reverse revAcc, pos) + | _, .nil, pos, revAcc => (.nil, Sym.reverse revAcc, pos) + | fuel + 1, .cons b rest, pos, revAcc => + if isAsciiIdRestByte b then + scanIdentRestBytes fuel rest (Nat.add pos 1) (.cons b revAcc) + else if Nat.ble 194 b then + match scanUtf8LetterLike (.cons b rest) with + | some (revU, restU, uLen) => + scanIdentRestBytes fuel restU (Nat.add pos uLen) (Sym.append revU revAcc) + | none => + (.cons b rest, Sym.reverse revAcc, pos) + else + (.cons b rest, Sym.reverse revAcc, pos) + +/-- Scan an escaped identifier component `«...»` starting after `«` (`194, 171`). -/ +def scanEscapedIdentBytes : Sym → Nat → Sym → Option (Sym × Sym × Nat) + | .nil, _, _ => none + | .cons b0 rest0, pos, revAcc => + if Nat.beq b0 194 then + match rest0 with + | .cons b1 rest1 => + if Nat.beq b1 187 then + some (rest1, Sym.reverse revAcc, Nat.add pos 2) + else + scanEscapedIdentBytes rest0 (Nat.add pos 1) (.cons b0 revAcc) + | .nil => none + else + scanEscapedIdentBytes rest0 (Nat.add pos 1) (.cons b0 revAcc) + +/-- Cold helper: scan an escaped identifier component `«...»` starting after `«`. -/ +def scanEscapedIdentComponent (bs : Sym) (pos : Nat) : Option (Sym × Sym × Nat) := + match scanEscapedIdentBytes bs (Nat.add pos 2) .nil with + | some (rem, partSym, endPos) => some (partSym, rem, endPos) + | none => none + +/-- Cold helper: scan the reserved `IxVCS` conflict marker `#merge` starting after `'#'` (35). -/ +def scanMergeIdentComponent (bs : Sym) (pos : Nat) : Option (Sym × Sym × Nat) := + match Sym.dropPrefix (s% "merge") bs with + | none => none + | some rem => + match rem with + | .cons nextB _ => + if isAsciiIdRestByte nextB then none + else some (s% "#merge", rem, Nat.add pos 6) + | .nil => + some (s% "#merge", .nil, Nat.add pos 6) + +/-- Scan a single identifier component on a `Sym` tail in $O(1)$ per byte. + Returns `some (partSym, remainingBytes, nextPos)` or `none`. -/ +def scanOneIdentComponentBytes : Sym → Nat → Option (Sym × Sym × Nat) + | .nil, _ => none + | .cons b rest, pos => + if isAsciiIdFirstByte b then + let (rem, partSym, endPos) := scanIdentRestBytes parseFuel rest (Nat.add pos 1) (.cons b .nil) + some (partSym, rem, endPos) + else if Nat.beq b 35 then + scanMergeIdentComponent rest pos + else if Nat.beq b 194 then + match rest with + | .cons b1 rest1 => + if Nat.beq b1 171 then scanEscapedIdentComponent rest1 pos else none + | .nil => none + else if Nat.ble 195 b then + match scanUtf8LetterLike (.cons b rest) with + | some (revU, restU, uLen) => + let (rem, partSym, endPos) := scanIdentRestBytes parseFuel restU (Nat.add pos uLen) revU + some (partSym, rem, endPos) + | none => none + else + none + +/-- Scan dotted identifier components `A.B.c` on a `Sym` tail in $O(1)$ per byte. -/ +def scanHierarchicalIdentBytesAux : Nat → Sym → Nat → FName → (FName × Sym × Nat) + | 0, bs, pos, acc => (acc, bs, pos) + | fuel + 1, .cons b rest, pos, acc => + if Nat.beq b 46 then + match scanOneIdentComponentBytes rest (Nat.add pos 1) with + | some (partSym, rem, nextPos) => + scanHierarchicalIdentBytesAux fuel rem nextPos (FName.mkStr acc partSym) + | none => + (acc, .cons b rest, pos) + else + (acc, .cons b rest, pos) + | _, .nil, pos, acc => (acc, .nil, pos) + +def scanHierarchicalIdentBytes (bs : Sym) (pos : Nat) : + Option (FName × Sym × Sym × Nat × Bool) := + match scanOneIdentComponentBytes bs pos with + | none => none + | some (firstPart, rem1, pos1) => + let firstName := FName.simple firstPart + let (fullName, remEnd, endPos) := scanHierarchicalIdentBytesAux 64 rem1 pos1 firstName + some (fullName, firstPart, remEnd, endPos, Nat.beq endPos pos1) + +/-- Check if `sym : Sym` is a reserved keyword in `defaultKeywords` or `env.keywords`. -/ +def isKeywordSym (env : IxParserEnv) (sym : Sym) : Bool := + if isDefaultKeyword sym then true + else + match env.keywords.children with + | .nil => false + | _ => + match env.keywords.findExact? sym with + | some true => true + | _ => false + +/-- Construct the updated `ParserState` after scanning a token `tok` spanning `[leadStart, trailStop)` + with remaining bytes `afterBytes`. -/ +def mkScannedState (s : ParserState) (leadStart trailStop : Nat) (afterBytes : Sym) + (tok : Stx) : ParserState := + match s with + | ⟨⟨rev, len⟩, lhsPrec, _, _, _, _⟩ => + ⟨⟨tok :: rev, Nat.add len 1⟩, lhsPrec, trailStop, afterBytes, + ⟨true, leadStart, trailStop, tok, afterBytes⟩, none⟩ + +/-- Cold helper: scan a content-hash `#`, string `"..."`, or char `'c'` literal. -/ +def scanSpecialLitToken (s : ParserState) (leadStart tokStart : Nat) (hasNl : Bool) + (b0 : Nat) (tokBytes restTokBytes : Sym) : Option ParserState := + -- 1. Content-hash reference `#` + if Nat.beq b0 35 then + match restTokBytes with + | .cons d _ => + if isHexDigitByte d then + let (afterHex, revHex, hexEnd) := scanHexDigitsBytes restTokBytes (Nat.add tokStart 1) .nil + let (afterTrail, trailStop) := skipHorizontalWhitespaceBytes afterHex hexEnd + let info := mkOriginalSourceInfoFast hasNl tokStart hexEnd + let tok := Syntax.mkNodeF SyntaxKindF.hashRef (.scons (Syntax.mkAtomF info (Sym.reverse revHex)) .snil) info + some (mkScannedState s leadStart trailStop afterTrail tok) + else none + | .nil => none + -- 2. String literal `"..."` + else if Nat.beq b0 34 then + match scanStringLitBytes restTokBytes (Nat.add tokStart 1) .nil with + | some (decoded, afterStr, tokStop) => + let (afterTrail, trailStop) := skipHorizontalWhitespaceBytes afterStr tokStop + let info := mkOriginalSourceInfoFast hasNl tokStart tokStop + let tok := Syntax.mkNodeF SyntaxKindF.strLit (.scons (Syntax.mkAtomF info decoded) .snil) info + some (mkScannedState s leadStart trailStop afterTrail tok) + | none => + some (s.setPos tokStart tokBytes |>.mkUnexpectedError (s% "unterminated string literal")) + -- 3. Character literal `'c'` + else if Nat.beq b0 39 then + match scanCharLitBytes restTokBytes (Nat.add tokStart 1) with + | some (decodedSym, afterChar, tokStop) => + let (afterTrail, trailStop) := skipHorizontalWhitespaceBytes afterChar tokStop + let info := mkOriginalSourceInfoFast hasNl tokStart tokStop + let tok := Syntax.mkNodeF SyntaxKindF.charLit (.scons (Syntax.mkAtomF info decodedSym) .snil) info + some (mkScannedState s leadStart trailStop afterTrail tok) + | none => none + else + none + +/-- Core token scanner: reads one token directly from `s.remBytes : Sym` in $O(1)$ per byte! -/ +def scanNextToken (ctx : IxParserContext) (s : ParserState) : ParserState := + let c := ctx.inputCtx + let leadStart := s.pos + let leadBytes := s.remBytes + match skipWhitespaceBytes c.size parseFuel leadBytes leadStart false with + | (tokBytes, tokStart, hasNl) => + match tokBytes with + | .nil => + s.setPos tokStart .nil |>.mkEOIError + | .cons b0 restTokBytes => + -- 1..3. Cold special literals (`#`, `"..."`, `'c'`) + match scanSpecialLitToken s leadStart tokStart hasNl b0 tokBytes restTokBytes with + | some st => st + | none => + -- 4. Numeric literal `0..9` + if isDigitByte b0 then + match scanNumberBytes tokBytes tokStart with + | some (numSym, afterNum, tokStop) => + let (afterTrail, trailStop) := skipHorizontalWhitespaceBytes afterNum tokStop + let info := mkOriginalSourceInfoFast hasNl tokStart tokStop + let tok := Syntax.mkNodeF SyntaxKindF.numLit (.scons (Syntax.mkAtomF info numSym) .snil) info + mkScannedState s leadStart trailStop afterTrail tok + | none => + s.setPos tokStart tokBytes |>.mkUnexpectedError (s% "invalid numeric literal") + -- 5. Identifier or keyword (ASCII fast-path, UTF-8 letter, `«...»`, or `#merge`) + else + let isGuillemet := Nat.beq b0 194 && match restTokBytes with | .cons b1 _ => Nat.beq b1 171 | .nil => false + let maybeIdent := + isAsciiIdFirstByte b0 || isGuillemet || Nat.beq b0 35 || Nat.ble 195 b0 + let identRes := if maybeIdent then scanHierarchicalIdentBytes tokBytes tokStart else none + match identRes with + | some (name, firstPart, afterIdent, tokStop, isSinglePart) => + let (afterTrail, trailStop) := skipHorizontalWhitespaceBytes afterIdent tokStop + let info := mkOriginalSourceInfoFast hasNl tokStart tokStop + let isSingleUnescaped := !isGuillemet && isSinglePart + let tok := + if isSingleUnescaped && (Sym.beq firstPart (s% "#merge") || isKeywordSym ctx.env firstPart) then + Syntax.mkAtomF info firstPart + else + Syntax.mkIdentF info firstPart name + mkScannedState s leadStart trailStop afterTrail tok + | none => + -- 6. Operator / punctuation symbol: O(1) default table + optional custom `ctx.env.tokens` trie + let defaultHit := matchDefaultTokenBytes tokStart tokBytes + let bestHit := + match ctx.env.tokens.children with + | .nil => defaultHit + | _ => + match Trie.matchPrefixBytes tokStart none tokBytes ctx.env.tokens, defaultHit with + | some c@(_, cStop, _), some d@(_, dStop, _) => + if Nat.ble dStop cStop then some c else some d + | some c, none => some c + | none, d => d + match bestHit with + | some (sym, tokStop, afterSym) => + let (afterTrail, trailStop) := skipHorizontalWhitespaceBytes afterSym tokStop + let info := mkOriginalSourceInfoFast hasNl tokStart tokStop + let tok := Syntax.mkAtomF info sym + mkScannedState s leadStart trailStop afterTrail tok + | none => + s.setPos tokStart tokBytes |>.mkUnexpectedError (s% "unexpected character") + +/-- Read one token using the single-token cache when `s.cache.valid && s.cache.startPos == s.pos`. -/ +def tokenFn (ctx : IxParserContext) (s : ParserState) : ParserState := + match s with + | ⟨stack, lhsPrec, pos, _, cache, err⟩ => + if cache.valid && Nat.beq cache.startPos pos then + match stack.push cache.token with + | ⟨rev', len'⟩ => ⟨⟨rev', len'⟩, lhsPrec, cache.stopPos, cache.afterBytes, cache, err⟩ + else + scanNextToken ctx s + +/-- Peek at the next token without consuming it (returns `(Option Stx, updatedCacheState)`). -/ +def peekToken (ctx : IxParserContext) (s : ParserState) : Option Stx × ParserState := + match s with + | ⟨stack, lhsPrec, iniPos, iniBytes, cache, err⟩ => + if err.isNone && cache.valid && Nat.beq cache.startPos iniPos then + (some cache.token, s) + else + let s' := scanNextToken ctx s + if s'.hasError then + (none, ⟨stack, lhsPrec, iniPos, iniBytes, s'.cache, none⟩) + else + (some s'.cache.token, ⟨stack, lhsPrec, iniPos, iniBytes, s'.cache, none⟩) + +@[inline] def bindPeek (ctx : IxParserContext) (s : ParserState) + (k : Option Stx → ParserState → α) : α := + let (tok?, s') := peekToken ctx s + k tok? s' + +/-- Pure token predicates avoiding deep nested `ByteList` pattern-match decision trees. -/ +@[inline] def stxIsAtom (stx : Stx) (sym : Sym) : Bool := + match stx with + | .atom _ v => Sym.beq v sym + | _ => false + +@[inline] def stxIsWord (stx : Stx) (sym : Sym) : Bool := + match stx with + | .atom _ v => Sym.beq v sym + | .ident _ _ (.str .anon v) => Sym.beq v sym + | _ => false + +@[inline] def stxIsIdent (stx : Stx) : Bool := + match stx with + | .ident .. => true + | _ => false + +@[inline] def tokIsAtom (tok? : Option Stx) (sym : Sym) : Bool := + match tok? with + | some (.atom _ v) => Sym.beq v sym + | _ => false + +@[inline] def tokIsWord (tok? : Option Stx) (sym : Sym) : Bool := + match tok? with + | some (.atom _ v) => Sym.beq v sym + | some (.ident _ _ (.str .anon v)) => Sym.beq v sym + | _ => false + +@[inline] def tokIsIdent (tok? : Option Stx) : Bool := + match tok? with + | some (.ident ..) => true + | _ => false + +/-- Check if the input is at EOI (after skipping whitespace and comments) directly on `s.remBytes`. -/ +def atEOI (ctx : IxParserContext) (s : ParserState) : Bool := + let (rem, _, _) := skipWhitespaceBytes ctx.inputCtx.size parseFuel s.remBytes s.pos false + Sym.isEmpty rem + +/-! ## Core Combinators -/ + +def nodeFn (k : FName) (p : ParserFn) : ParserFn := fun ctx s => + let iniSz := s.stackSize + (p ctx s).mkNode k iniSz + +def atomicFn (p : ParserFn) : ParserFn := fun ctx s => + let iniSz := s.stackSize + let iniPos := s.pos + let iniBytes := s.remBytes + let s' := p ctx s + if s'.hasError then + match s' with + | ⟨stack', lhsPrec', _, _, cache', err'⟩ => + match stack'.shrink iniSz with + | ⟨rev', len'⟩ => ⟨⟨rev', len'⟩, lhsPrec', iniPos, iniBytes, cache', err'⟩ + else + s' + +def orelseFn (p q : ParserFn) : ParserFn := fun ctx s => + let iniSz := s.stackSize + let iniPos := s.pos + let iniBytes := s.remBytes + let s1 := p ctx s + match s1.errorMsg with + | none => s1 + | some e1 => + if !Nat.beq s1.pos iniPos then + s1 + else + let sRestored := s1.restore iniSz iniPos iniBytes + let s2 := q ctx sRestored + match s2.errorMsg with + | none => s2 + | some e2 => s2.setError (ParserError.merge e1 e2) + +def tryOrElseFn (p q : ParserFn) : ParserFn := + orelseFn (atomicFn p) q + +def seqFn (p q : ParserFn) : ParserFn := fun ctx s => + let s' := p ctx s + if s'.hasError then s' else q ctx s' + +def optionalFn (p : ParserFn) : ParserFn := fun ctx s => + let iniSz := s.stackSize + let iniPos := s.pos + let iniBytes := s.remBytes + let s' := p ctx s + if s'.hasError && Nat.beq s'.pos iniPos then + (s'.restore iniSz iniPos iniBytes).mkNode SyntaxKindF.nullKind iniSz + else + s'.mkNode SyntaxKindF.nullKind iniSz + +/-! ## Primitive Token Parsers -/ + +/-- Expect a specific `.atom` symbol `sym : Sym`. -/ +def symbolFn (sym : Sym) : ParserFn := fun ctx s => + let iniSz := s.stackSize + let iniPos := s.pos + let iniBytes := s.remBytes + let s' := tokenFn ctx s + if s'.hasError then + s'.mkErrorAt sym iniPos iniSz iniBytes + else + match s'.stxStack.back with + | .atom _ v => + if Sym.beq v sym then s' + else s'.mkErrorAt sym iniPos iniSz iniBytes + | _ => s'.mkErrorAt sym iniPos iniSz iniBytes + +/-- Expect a specific non-reserved identifier word (e.g., soft keyword like `borrow`). -/ +def nonReservedSymbolFn (sym : Sym) : ParserFn := fun ctx s => + let iniSz := s.stackSize + let iniPos := s.pos + let iniBytes := s.remBytes + let s' := tokenFn ctx s + if s'.hasError then + s'.mkErrorAt sym iniPos iniSz iniBytes + else + match s'.stxStack.back with + | .ident info _ (.str .anon v) => + if Sym.beq v sym then + let s' := s'.popSyntax + s'.pushSyntax (.atom info sym) + else + s'.mkErrorAt sym iniPos iniSz iniBytes + | .atom _ v => + if Sym.beq v sym then s' + else s'.mkErrorAt sym iniPos iniSz iniBytes + | _ => s'.mkErrorAt sym iniPos iniSz iniBytes + +/-- Expect an identifier token (`.ident`). -/ +def identFn : ParserFn := fun ctx s => + let iniSz := s.stackSize + let iniPos := s.pos + let iniBytes := s.remBytes + let s' := tokenFn ctx s + if s'.hasError then + s'.mkErrorAt (s% "identifier") iniPos iniSz iniBytes + else + match s'.stxStack.back with + | .ident .. => s' + | _ => s'.mkErrorAt (s% "identifier") iniPos iniSz iniBytes + +/-- Expect a numeric literal token (`SyntaxKindF.numLit`). -/ +def numLitFn : ParserFn := fun ctx s => + let iniSz := s.stackSize + let iniPos := s.pos + let iniBytes := s.remBytes + let s' := tokenFn ctx s + if s'.hasError then + s'.mkErrorAt (s% "numeric literal") iniPos iniSz iniBytes + else if Syntax.isOfKindF s'.stxStack.back SyntaxKindF.numLit then + s' + else + s'.mkErrorAt (s% "numeric literal") iniPos iniSz iniBytes + +/-- Expect a string literal token (`SyntaxKindF.strLit`). -/ +def strLitFn : ParserFn := fun ctx s => + let iniSz := s.stackSize + let iniPos := s.pos + let iniBytes := s.remBytes + let s' := tokenFn ctx s + if s'.hasError then + s'.mkErrorAt (s% "string literal") iniPos iniSz iniBytes + else if Syntax.isOfKindF s'.stxStack.back SyntaxKindF.strLit then + s' + else + s'.mkErrorAt (s% "string literal") iniPos iniSz iniBytes + +/-- Expect a character literal token (`SyntaxKindF.charLit`). -/ +def charLitFn : ParserFn := fun ctx s => + let iniSz := s.stackSize + let iniPos := s.pos + let iniBytes := s.remBytes + let s' := tokenFn ctx s + if s'.hasError then + s'.mkErrorAt (s% "character literal") iniPos iniSz iniBytes + else if Syntax.isOfKindF s'.stxStack.back SyntaxKindF.charLit then + s' + else + s'.mkErrorAt (s% "character literal") iniPos iniSz iniBytes + +/-- Expect a content-hash reference token (`#`, `SyntaxKindF.hashRef`). -/ +def hashRefFn : ParserFn := fun ctx s => + let iniSz := s.stackSize + let iniPos := s.pos + let iniBytes := s.remBytes + let s' := tokenFn ctx s + if s'.hasError then + s'.mkErrorAt (s% "content-hash reference") iniPos iniSz iniBytes + else if Syntax.isOfKindF s'.stxStack.back SyntaxKindF.hashRef then + s' + else + s'.mkErrorAt (s% "content-hash reference") iniPos iniSz iniBytes + +/-- Run `p` with a modified minimum precedence `prec`. -/ +def withPrecFn (prec : Nat) (p : ParserFn) : ParserFn := fun ctx s => + match ctx with + | ⟨inputCtx, env, _⟩ => p ⟨inputCtx, env, prec⟩ s + +/-! ## First-Order Specialized Token Loops (Zero `Defun` Closures + `FuelErase`-Ready) -/ + +/-- First-order zero-or-more `identFn` loop. -/ +def manyIdentLoop (ctx : IxParserContext) (s : ParserState) : Nat → ParserState + | 0 => s.mkUnexpectedError (s% "parser fuel exhausted") + | fuel + 1 => + let iniSz := s.stackSize + let iniPos := s.pos + let iniBytes := s.remBytes + let s' := identFn ctx s + if s'.hasError then + if Nat.beq s'.pos iniPos then s'.restore iniSz iniPos iniBytes else s' + else if Nat.beq s'.pos iniPos then s' + else manyIdentLoop ctx s' fuel + +def many1IdentFn (ctx : IxParserContext) (s : ParserState) : ParserState := + let iniSz := s.stackSize + let s1 := identFn ctx s + if s1.hasError then s1.mkNode SyntaxKindF.nullKind iniSz + else (manyIdentLoop ctx s1 parseFuel).mkNode SyntaxKindF.nullKind iniSz + +/-- First-order comma-separated `identFn` loop (`ident ("," ident)*`). -/ +def sepByIdentCommaLoop (ctx : IxParserContext) (s : ParserState) : Nat → ParserState + | 0 => s.mkUnexpectedError (s% "parser fuel exhausted") + | fuel + 1 => + let sepIniSz := s.stackSize + let sepIniPos := s.pos + let sepIniBytes := s.remBytes + let sSep := symbolFn (s% ",") ctx s + if sSep.hasError then + if Nat.beq sSep.pos sepIniPos then sSep.restore sepIniSz sepIniPos sepIniBytes else sSep + else + let sAfterSep := sSep.shrinkStack sepIniSz + let sElem := identFn ctx sAfterSep + if sElem.hasError then sElem + else sepByIdentCommaLoop ctx sElem fuel + +def sepBy1IdentCommaFn (ctx : IxParserContext) (s : ParserState) : ParserState := + let iniSz := s.stackSize + let s1 := identFn ctx s + if s1.hasError then s1.mkNode SyntaxKindF.nullKind iniSz + else (sepByIdentCommaLoop ctx s1 parseFuel).mkNode SyntaxKindF.nullKind iniSz + +/-- First-order same-line `identFn` loop (stops at leading newline). -/ +def sameLineIdentFn (ctx : IxParserContext) (s : ParserState) : ParserState := + bindPeek ctx s fun tok? s => + match tok? with + | some tok@(.ident ..) => + if hasLeadingNewline tok then s.mkUnexpectedError (s% "expected identifier on same line") + else tokenFn ctx s + | _ => s.mkUnexpectedError (s% "expected identifier") + +def manySameLineIdentLoop (ctx : IxParserContext) (s : ParserState) : Nat → ParserState + | 0 => s.mkUnexpectedError (s% "parser fuel exhausted") + | fuel + 1 => + let iniSz := s.stackSize + let iniPos := s.pos + let iniBytes := s.remBytes + let s' := sameLineIdentFn ctx s + if s'.hasError then + if Nat.beq s'.pos iniPos then s'.restore iniSz iniPos iniBytes else s' + else if Nat.beq s'.pos iniPos then s' + else manySameLineIdentLoop ctx s' fuel + +def many1SameLineIdentFn (ctx : IxParserContext) (s : ParserState) : ParserState := + let iniSz := s.stackSize + let s1 := sameLineIdentFn ctx s + if s1.hasError then s1.mkNode SyntaxKindF.nullKind iniSz + else (manySameLineIdentLoop ctx s1 parseFuel).mkNode SyntaxKindF.nullKind iniSz + +end Ix.Frontend.Parser diff --git a/Ix/Frontend/Parser/Command.lean b/Ix/Frontend/Parser/Command.lean new file mode 100644 index 0000000000..7dfbc804fe --- /dev/null +++ b/Ix/Frontend/Parser/Command.lean @@ -0,0 +1,998 @@ +/- + Ix.Frontend.Parser.Command: Pure, total top-level command and module parser + for the Ix Frontend (`import #`, `import Mod`, `map Name := #`, + `def`, `abbrev`, `theorem`, `axiom`, `opaque`, `instance`, `inductive`, + `structure`, `class`, `namespace`, `section`, `end`, `variable`, `universe`, + `open`, `mutual`, and operator declarations). +-/ +module + +public import Ix.Frontend.Parser.Term + +@[expose] public section + +namespace Ix.Frontend.Parser + +/-! ## Declaration Modifiers & Header Helpers -/ + +/-- Monomorphic helper: push all `Stx` children onto `ParserState`. -/ +def pushStxList (s : ParserState) : List Stx → ParserState + | [] => s + | a :: rest => pushStxList (s.pushSyntax a) rest + +/-- Parse zero or more declaration modifiers (`@[attr1, ...]`, `private`, `protected`, `noncomputable`, `partial`, `unsafe`). -/ +def declModifiersLoop (ctx : IxParserContext) (s : ParserState) : Nat → ParserState + | 0 => s + | fuel + 1 => + bindPeek ctx s fun tok? s => + match tok? with + | some (.atom _ kw) => + match kw with + | .cons b0 rest => + if (Nat.beq b0 112 && (Sym.beq rest (s% "rivate") || Sym.beq rest (s% "rotected") || Sym.beq rest (s% "artial"))) || + (Nat.beq b0 110 && Sym.beq rest (s% "oncomputable")) || + (Nat.beq b0 117 && Sym.beq rest (s% "nsafe")) then + (tokenFn ctx s).bindState fun s => + declModifiersLoop ctx s fuel + else if Nat.beq b0 64 && Sym.beq rest (s% "[") then + let iniSz := s.stackSize + (symbolFn (s% "@[") ctx s).bindState fun s => + (sepBy1IdentCommaFn ctx s).bindState fun s => + (symbolFn (s% "]") ctx s).bindState fun s => + if s.hasError then s else + let attrsNull := s.stxStack.getD (iniSz + 1) + let s := s.shrinkStack iniSz + let s := pushStxList s (Syntax.getArgs attrsNull).toList + declModifiersLoop ctx s fuel + else s + | .nil => s + | _ => s + +def declModifiersFn : ParserFn := fun ctx s => + s.bindState fun s => + let iniSz := s.stackSize + (declModifiersLoop ctx s 8).bindState fun s => + s.mkNode SyntaxKindF.modifiersKind iniSz + +/-- Parse a declaration identifier with optional `.{u, v}` universe parameters: + pushes `ident` and a `SyntaxKindF.univParamsKind` node. -/ +def declIdFn : ParserFn := fun ctx s => + (identFn ctx s).bindState fun s => + if s.hasError then s else + bindPeek ctx s fun tok? s => + if tokIsAtom (tok?) (s% ".{") then + let iniSz := s.stackSize + (symbolFn (s% ".{") ctx s).bindState fun s => + (sepBy1IdentCommaFn ctx s).bindState fun s => + (symbolFn (s% "}") ctx s).bindState fun s => + if s.hasError then s else + let paramsNull := s.stxStack.getD (iniSz + 1) + let s := s.shrinkStack iniSz + s.pushSyntax (Syntax.mkNodeF SyntaxKindF.univParamsKind (Syntax.getArgsStx paramsNull)) + else + s.pushSyntax (Syntax.mkNodeF SyntaxKindF.univParamsKind .snil) + +/-- Parse zero or more bracketed or simple binders on a declaration signature. -/ +def declBindersFn : ParserFn := + manyBracketedBinderFn (termStep parseFuel) + +/-- Parse optional `: valuePrefix? type` return type annotation on a declaration. + Pushes `valuePrefix` and `typeOrNull`. -/ +def optDeclSigTypeFn : ParserFn := fun ctx s => + bindPeek ctx s fun tok? s => + if tokIsAtom (tok?) (s% ":") then + (symbolFn (s% ":") ctx s).bindState fun s => + let s := s.popSyntax -- drop `:` + (valuePrefixFn ctx s).bindState fun s => + if s.hasError then s else + withPrecFn 0 termFn ctx s + else + let s := s.pushSyntax (Syntax.mkNodeF SyntaxKindF.valuePrefix .snil) + s.pushSyntax (Syntax.mkNullNodeF .snil) + +/-- Parse `: valuePrefix? type` (required) on `axiom` / `theorem` / `instance`. + Pushes `valuePrefix` and `type`. -/ +def reqDeclSigTypeFn : ParserFn := fun ctx s => + (symbolFn (s% ":") ctx s).bindState fun s => + if s.hasError then s else + let s := s.popSyntax -- drop `:` + (valuePrefixFn ctx s).bindState fun s => + if s.hasError then s else + withPrecFn 0 termFn ctx s + +/-! ## Inductive Constructors & Structure Fields -/ + +/-- Cold helper: check if an atom keyword starting with `a..v` starts a top-level command. -/ +def isCommandStartAtom (b0 : Nat) (rest : Sym) : Bool := + if Nat.beq b0 100 then Sym.beq rest (s% "ef") || Sym.beq rest (s% "eriving") + else if Nat.beq b0 116 then Sym.beq rest (s% "heorem") + else if Nat.beq b0 115 then Sym.beq rest (s% "tructure") || Sym.beq rest (s% "ection") + else if Nat.beq b0 105 then Sym.beq rest (s% "nductive") || Sym.beq rest (s% "nstance") || Sym.beq rest (s% "mport") + else if Nat.beq b0 97 then Sym.beq rest (s% "bbrev") || Sym.beq rest (s% "xiom") + else if Nat.beq b0 99 then Sym.beq rest (s% "lass") + else if Nat.beq b0 101 then Sym.beq rest (s% "nd") || Sym.beq rest (s% "xport") + else if Nat.beq b0 108 then Sym.beq rest (s% "emma") + else if Nat.beq b0 109 then Sym.beq rest (s% "utual") + else if Nat.beq b0 110 then Sym.beq rest (s% "amespace") || Sym.beq rest (s% "oncomputable") + else if Nat.beq b0 111 then Sym.beq rest (s% "pen") || Sym.beq rest (s% "paque") + else if Nat.beq b0 112 then Sym.beq rest (s% "rivate") || Sym.beq rest (s% "rotected") || Sym.beq rest (s% "artial") + else if Nat.beq b0 117 then Sym.beq rest (s% "niverse") || Sym.beq rest (s% "nsafe") + else if Nat.beq b0 118 then Sym.beq rest (s% "ariable") + else if Nat.beq b0 64 then Sym.beq rest (s% "[") + else if Nat.beq b0 35 then Sym.beq rest (s% "merge") + else false + +/-- Cold helper: check if a non-reserved identifier word starts a top-level command (`map`, `infix*`, `notation`, `macro*`). -/ +def isCommandStartWord (b0 : Nat) (rest : Sym) : Bool := + if Nat.beq b0 109 then Sym.beq rest (s% "ap") || Sym.beq rest (s% "acro") || Sym.beq rest (s% "acro_rules") + else if Nat.beq b0 105 then Sym.beq rest (s% "nfixl") || Sym.beq rest (s% "nfixr") || Sym.beq rest (s% "nfix") + else if Nat.beq b0 112 then Sym.beq rest (s% "refix") || Sym.beq rest (s% "ostfix") + else if Nat.beq b0 110 then Sym.beq rest (s% "otation") + else if Nat.beq b0 115 then Sym.beq rest (s% "yntax") + else false + +/-- Check if the next token starts a new top-level command (O(1) first-byte dispatch!). -/ +def isCommandStart (tok : Stx) : Bool := + match tok with + | .atom _ (.cons b0 rest) => + if (Nat.ble 97 b0 && Nat.ble b0 118) || Nat.beq b0 64 || Nat.beq b0 35 then + isCommandStartAtom b0 rest + else false + | .ident _ _ (.str .anon (.cons b0 rest)) => + if Nat.beq b0 109 || Nat.beq b0 105 || Nat.beq b0 112 || Nat.beq b0 110 || Nat.beq b0 115 then + isCommandStartWord b0 rest + else false + | _ => false + +/-- Parse a single inductive constructor `| ctorName binders* [: type]`. -/ +def ctorDeclFn : ParserFn := fun ctx s => + s.bindState fun s => + let iniSz := s.stackSize + (symbolFn (s% "|") ctx s).bindState fun s => + if s.hasError then s else + (identFn ctx s).bindState fun s => + if s.hasError then s else + (declBindersFn ctx s).bindState fun s => + if s.hasError then s else + (optDeclSigTypeFn ctx s).bindState fun s => + if s.hasError then s else + s.mkNode SyntaxKindF.ctorDecl iniSz + +/-- Parse an optional `deriving C1, C2` clause at the end of an `inductive` or `structure`. -/ +def optDerivingFn : ParserFn := fun ctx s => + bindPeek ctx s fun tok? s => + if tokIsAtom (tok?) (s% "deriving") then + (symbolFn (s% "deriving") ctx s).bindState fun s => + let s := s.popSyntax + sepBy1IdentCommaFn ctx s + else + s.pushSyntax (Syntax.mkNullNodeF .snil) + +/-- Parse a single structure/class field declaration: + either `(@[shared] field1 field2 : Type)` or `@[shared] field1 : Type [:= default]`. -/ +def structFieldDeclFn : ParserFn := fun ctx s => + bindPeek ctx s fun tok? s => + match tok? with + | none => s.mkEOIError [(s% "field declaration")] + | some tok => + if Syntax.getAtomSym tok == (s% "|") || (isCommandStart tok && !stxIsAtom tok (s% "@[")) then + s.mkUnexpectedError (s% "end of structure fields") + else + let iniSz := s.stackSize + let iniPos := s.pos + let iniBytes := s.remBytes + if stxIsAtom (tok) (s% "(") || stxIsAtom (tok) (s% "{") then + let closeSym := if Syntax.getAtomSym tok == (s% "(") then (s% ")") else (s% "}") + (tokenFn ctx s).bindState fun s => + (fieldPrefixFn false ctx s).bindState fun s => + if s.hasError then s else + (many1IdentFn ctx s).bindState fun s => + if s.hasError then s else + (symbolFn (s% ":") ctx s).bindState fun s => + if s.hasError then s else + let s := s.pushSyntax (Syntax.mkNodeF SyntaxKindF.valuePrefix .snil) + (withPrecFn 0 termFn ctx s).bindState fun s => + (optionalFn (seqFn (symbolFn (s% ":=")) (withPrecFn 0 termFn)) ctx s).bindState fun s => + (symbolFn closeSym ctx s).bindState fun s => + s.mkNode SyntaxKindF.fieldDecl iniSz + else if stxIsAtom tok (s% "@[") then + -- Distinguish field mode `@[shared]` / `@[erased]` from a following command `@[no_rc] def ...` + let sPref := fieldPrefixFn true ctx s + if sPref.hasError then sPref + else if Nat.beq sPref.pos iniPos then + (sPref.restore iniSz iniPos iniBytes).mkUnexpectedError (s% "end of structure fields") + else + (many1IdentFn ctx sPref).bindState fun s => + if s.hasError then s else + (symbolFn (s% ":") ctx s).bindState fun s => + if s.hasError then s else + let s := s.pushSyntax (Syntax.mkNodeF SyntaxKindF.valuePrefix .snil) + (withPrecFn 0 termFn ctx s).bindState fun s => + (optionalFn (seqFn (symbolFn (s% ":=")) (withPrecFn 0 termFn)) ctx s).bindState fun s => + s.mkNode SyntaxKindF.fieldDecl iniSz + else + let s := s.pushSyntax (Syntax.mkNodeF SyntaxKindF.binderPrefix .snil) + (many1IdentFn ctx s).bindState fun s => + if s.hasError then s else + (symbolFn (s% ":") ctx s).bindState fun s => + if s.hasError then s else + let s := s.pushSyntax (Syntax.mkNodeF SyntaxKindF.valuePrefix .snil) + (withPrecFn 0 termFn ctx s).bindState fun s => + (optionalFn (seqFn (symbolFn (s% ":=")) (withPrecFn 0 termFn)) ctx s).bindState fun s => + s.mkNode SyntaxKindF.fieldDecl iniSz + +/-- First-order zero-or-more `ctorDeclFn` loop. -/ +def manyCtorDeclLoop (ctx : IxParserContext) (s : ParserState) : Nat → ParserState + | 0 => s.mkUnexpectedError (s% "parser fuel exhausted") + | fuel + 1 => + let iniSz := s.stackSize + let iniPos := s.pos + let iniBytes := s.remBytes + let s' := ctorDeclFn ctx s + if s'.hasError then + if Nat.beq s'.pos iniPos then s'.restore iniSz iniPos iniBytes else s' + else if Nat.beq s'.pos iniPos then s' + else manyCtorDeclLoop ctx s' fuel + +def manyCtorDeclFn (ctx : IxParserContext) (s : ParserState) : ParserState := + let iniSz := s.stackSize + (manyCtorDeclLoop ctx s parseFuel).mkNode SyntaxKindF.nullKind iniSz + +/-- First-order zero-or-more `structFieldDeclFn` loop. -/ +def manyStructFieldDeclLoop (ctx : IxParserContext) (s : ParserState) : Nat → ParserState + | 0 => s.mkUnexpectedError (s% "parser fuel exhausted") + | fuel + 1 => + let iniSz := s.stackSize + let iniPos := s.pos + let iniBytes := s.remBytes + let s' := structFieldDeclFn ctx s + if s'.hasError then + if Nat.beq s'.pos iniPos then s'.restore iniSz iniPos iniBytes else s' + else if Nat.beq s'.pos iniPos then s' + else manyStructFieldDeclLoop ctx s' fuel + +def manyStructFieldDeclFn (ctx : IxParserContext) (s : ParserState) : ParserState := + let iniSz := s.stackSize + (manyStructFieldDeclLoop ctx s parseFuel).mkNode SyntaxKindF.nullKind iniSz + +/-! ## Top-Level Command Parser -/ + +/-- Parse a single `where` helper binding. -/ +def whereItemFn (ctx : IxParserContext) (s : ParserState) : ParserState := + let iSz := s.stackSize + let st := (optionalFn (symbolFn (s% "|")) ctx s).popSyntax + bindPeek ctx st fun nextTok? st => + match nextTok? with + | none => st.mkUnexpectedError (s% "end of where block") + | some t => + if isCommandStart t then + st.mkUnexpectedError (s% "end of where block") + else + let st := binderPrefixFn ctx st + let st := identFn ctx st + if st.hasError then st else + let st := manySimpleOrBracketedBinderFn (termStep parseFuel) ctx st + let st := optionalFn (fun c2 st2 => + let st2 := symbolFn (s% ":") c2 st2 + if st2.hasError then st2 else + let st2 := valuePrefixFn c2 st2 + if st2.hasError then st2 else + withPrecFn 0 termFn c2 st2) ctx st + if st.hasError then st else + bindPeek ctx st fun rhsTok? st => + let stAfterRhs := + if tokIsAtom (rhsTok?) (s% "|") then + let st := st.pushSyntax (Syntax.mkSimpleAtomF (s% ":=")) + many1MatchAltFn (termStep parseFuel) ctx st + else + let st := symbolFn (s% ":=") ctx st + if st.hasError then st else withPrecFn 0 termFn ctx st + stAfterRhs.mkNode SyntaxKindF.nullKind iSz + +def manyWhereItemLoop (ctx : IxParserContext) (s : ParserState) : Nat → ParserState + | 0 => s.mkUnexpectedError (s% "parser fuel exhausted") + | fuel + 1 => + let iniSz := s.stackSize + let iniPos := s.pos + let iniBytes := s.remBytes + let s' := whereItemFn ctx s + if s'.hasError then + if Nat.beq s'.pos iniPos then s'.restore iniSz iniPos iniBytes else s' + else if Nat.beq s'.pos iniPos then s' + else manyWhereItemLoop ctx s' fuel + +def many1WhereItemFn (ctx : IxParserContext) (s : ParserState) : ParserState := + let iniSz := s.stackSize + let s1 := whereItemFn ctx s + if s1.hasError then s1.mkNode SyntaxKindF.nullKind iniSz + else (manyWhereItemLoop ctx s1 parseFuel).mkNode SyntaxKindF.nullKind iniSz + +/-- Monomorphic helper: wrap `bodyStx` in nested `letRecTerm` nodes for `where` items. -/ +def wrapWhereItems (bodyStx : Stx) : List Stx → Stx + | [] => bodyStx + | item :: rest => + let accBody := wrapWhereItems bodyStx rest + let bPref := Syntax.getArg item 0 + let idStx := Syntax.getArg item 1 + let binders := Syntax.getArg item 2 + let optTy := Syntax.getArg item 3 + let colEq := Syntax.getArg item 4 + let valOrAlts := Syntax.getArg item 5 + Syntax.mkNodeListF SyntaxKindF.letRecTerm + [Syntax.mkSimpleAtomF (s% "let"), Syntax.mkSimpleAtomF (s% "rec"), + bPref, idStx, binders, optTy, colEq, valOrAlts, Syntax.mkNullNodeF .snil, accBody] + +/-- Parse an optional `where` block at the end of a `def`/`theorem`, wrapping the body + on top of the syntax stack in nested `SyntaxKindF.letRecTerm` nodes. -/ +def optWhereClauseFn : ParserFn := fun ctx s => + bindPeek ctx s fun tok? s => + if tokIsAtom (tok?) (s% "where") then + (symbolFn (s% "where") ctx s).bindState fun s => + let s := s.popSyntax -- drop `where` + (many1WhereItemFn ctx s).bindState fun s => + if s.hasError then s else + let itemsNull := s.stxStack.back + let s := s.popSyntax + let bodyStx := s.stxStack.back + let s := s.popSyntax + let wrappedBody := wrapWhereItems bodyStx (Syntax.getArgs itemsNull).toList + s.pushSyntax wrappedBody + else +s + +/-- Parse items of a `notation`, `syntax`, or `macro` pattern until `=>`, `↦`, or trailing `: cat`. + Structurally recursive on `fuel : Nat`. -/ +def parseNotationItemsLoop : Nat → IxParserContext → ParserState → ParserState + | 0, _, s => s + | fuel + 1, ctx, s => + bindPeek ctx s fun tok? s => + match tok? with + | none => s + | some (.atom _ sym) => + if Sym.beq sym (s% "=>") || Sym.beq sym (s% "↦") then s + else if Sym.beq sym (s% ":") then + (symbolFn (s% ":") ctx s).bindState fun s => + let s := s.popSyntax + (identFn ctx s).bindState fun s => + if s.hasError then s else s.popSyntax + else if Sym.beq sym (s% "(") then + let pSz := s.stackSize + (symbolFn (s% "(") ctx s).bindState fun s => + let s := s.popSyntax + (identFn ctx s).bindState fun s => + if s.hasError then s else + (optionalFn (seqFn (symbolFn (s% ":")) (orelseFn numLitFn identFn)) ctx s).bindState fun s => + let s := s.popSyntax + (symbolFn (s% ")") ctx s).bindState fun s => + if s.hasError then s else + let idStx := s.stxStack.getD pSz + let s := s.shrinkStack pSz + let s := s.pushSyntax idStx + parseNotationItemsLoop fuel ctx s + else s + | some (.node _ k _) => + if k == SyntaxKindF.strLit then + (tokenFn ctx s).bindState fun s => + parseNotationItemsLoop fuel ctx s + else + s + | some (.ident ..) => + let iSz := s.stackSize + (identFn ctx s).bindState fun s => + bindPeek ctx s fun next? s => + if tokIsAtom (next?) (s% ":") then + let afterColonAttempt : ParserFn := fun c st => + (symbolFn (s% ":") c st).bindState fun st => + let st := st.popSyntax + (orelseFn numLitFn identFn c st).bindState fun st => + if st.hasError then st else + bindPeek c st fun afterCat? st => + if tokIsAtom (afterCat?) (s% "=>") || tokIsAtom (afterCat?) (s% "↦") then + st.mkUnexpectedError (s% "trailing category") + else + st.mkNode SyntaxKindF.nullKind iSz + let plainVar : ParserFn := fun _ st => st + (tryOrElseFn afterColonAttempt plainVar ctx s).bindState fun s => + parseNotationItemsLoop fuel ctx s + else + parseNotationItemsLoop fuel ctx s + | _ => s + +/-- Parse a `def`, `abbrev`, `theorem`/`lemma`, or `opaque` declaration after its modifiers. -/ +def parseValueDecl (kind : FName) : ParserFn := fun ctx s => + s.bindState fun s => + let iniSz := s.stackSize - 1 -- include the already-pushed `modifiers` node + (tokenFn ctx s).bindState fun s => -- consume keyword (`def`, `theorem`, etc.) + (declIdFn ctx s).bindState fun s => + if s.hasError then s else + (declBindersFn ctx s).bindState fun s => + if s.hasError then s else + (optDeclSigTypeFn ctx s).bindState fun s => + if s.hasError then s else + bindPeek ctx s fun tok? s => + if tokIsAtom (tok?) (s% ":=") then + (symbolFn (s% ":=") ctx s).bindState fun s => + (withPrecFn 0 termFn ctx s).bindState fun s => + if s.hasError then s else + (optWhereClauseFn ctx s).bindState fun s => + s.mkNode kind iniSz + else if tokIsAtom (tok?) (s% "|") then + -- Pattern-matching definition `def f : Nat → Nat | 0 => 1 | n => n` + (many1MatchAltFn (termStep parseFuel) ctx s).bindState fun s => + s.mkNode kind iniSz + else + (symbolFn (s% ":=") ctx s).bindState fun s => + s.mkNode kind iniSz + +/-- Parse an `axiom` declaration after its modifiers. -/ +def parseAxiomDecl : ParserFn := fun ctx s => + s.bindState fun s => + let iniSz := s.stackSize - 1 + (tokenFn ctx s).bindState fun s => -- consume `axiom` + (declIdFn ctx s).bindState fun s => + if s.hasError then s else + (declBindersFn ctx s).bindState fun s => + if s.hasError then s else + (reqDeclSigTypeFn ctx s).bindState fun s => + s.mkNode SyntaxKindF.axiomDecl iniSz + +/-- First-order `instance ... where` field assignment loop. -/ +def instanceFieldAssignFn (ctx : IxParserContext) (s : ParserState) : ParserState := + let fSz := s.stackSize + let st := (optionalFn (symbolFn (s% "|")) ctx s).popSyntax + let st := identFn ctx st + if st.hasError then st else + let st := manySimpleOrBracketedBinderFn (termStep parseFuel) ctx st + let st := symbolFn (s% ":=") ctx st + let st := withPrecFn 0 termFn ctx st + st.mkNode SyntaxKindF.structFieldAssign fSz + +def manyInstanceFieldAssignLoop (ctx : IxParserContext) (s : ParserState) : Nat → ParserState + | 0 => s.mkUnexpectedError (s% "parser fuel exhausted") + | fuel + 1 => + let iniSz := s.stackSize + let iniPos := s.pos + let iniBytes := s.remBytes + let s' := instanceFieldAssignFn ctx s + if s'.hasError then + if Nat.beq s'.pos iniPos then s'.restore iniSz iniPos iniBytes else s' + else if Nat.beq s'.pos iniPos then s' + else manyInstanceFieldAssignLoop ctx s' fuel + +def manyInstanceFieldAssignFn (ctx : IxParserContext) (s : ParserState) : ParserState := + let iniSz := s.stackSize + (manyInstanceFieldAssignLoop ctx s parseFuel).mkNode SyntaxKindF.nullKind iniSz + +/-- Parse an `instance` declaration after its modifiers: + `instance [name?] binders* : Class args := body` (or `where field := val ...`). -/ +def parseInstanceDecl : ParserFn := fun ctx s => + s.bindState fun s => + let iniSz := s.stackSize - 1 + (tokenFn ctx s).bindState fun s => -- consume `instance` + bindPeek ctx s fun tok? s => + let sAfterId := match tok? with + | some (.ident ..) => declIdFn ctx s + | _ => + let s := s.pushSyntax (Syntax.mkSimpleIdentF FName.anon) + s.pushSyntax (Syntax.mkNodeF SyntaxKindF.univParamsKind .snil) + sAfterId.bindState fun s => + if s.hasError then s else + (declBindersFn ctx s).bindState fun s => + if s.hasError then s else + (reqDeclSigTypeFn ctx s).bindState fun s => + if s.hasError then s else + bindPeek ctx s fun bodyTok? s => + if tokIsAtom (bodyTok?) (s% "where") then + (symbolFn (s% "where") ctx s).bindState fun s => + (manyInstanceFieldAssignFn ctx s).bindState fun s => + s.mkNode SyntaxKindF.instanceDecl iniSz + else + (symbolFn (s% ":=") ctx s).bindState fun s => + (withPrecFn 0 termFn ctx s).bindState fun s => + s.mkNode SyntaxKindF.instanceDecl iniSz + +/-- Parse an `inductive` declaration after its modifiers. -/ +def parseInductiveDecl : ParserFn := fun ctx s => + s.bindState fun s => + let iniSz := s.stackSize - 1 + (tokenFn ctx s).bindState fun s => -- consume `inductive` + (declIdFn ctx s).bindState fun s => + if s.hasError then s else + (declBindersFn ctx s).bindState fun s => + if s.hasError then s else + (optDeclSigTypeFn ctx s).bindState fun s => + if s.hasError then s else + (optionalFn (symbolFn (s% "where")) ctx s).bindState fun s => + let s := s.popSyntax -- drop optional `where` wrapper + (manyCtorDeclFn ctx s).bindState fun s => + (optDerivingFn ctx s).bindState fun s => + s.mkNode SyntaxKindF.inductiveDecl iniSz + +/-- Parse a `structure` or `class` declaration after its modifiers. -/ +def parseStructureOrClassDecl (kind : FName) : ParserFn := fun ctx s => + s.bindState fun s => + let iniSz := s.stackSize - 1 + (tokenFn ctx s).bindState fun s => -- consume `structure` or `class` + (declIdFn ctx s).bindState fun s => + if s.hasError then s else + (declBindersFn ctx s).bindState fun s => + if s.hasError then s else + -- Optional `extends P1, P2` + bindPeek ctx s fun extTok? s => + let sAfterExt := + if tokIsAtom (extTok?) (s% "extends") || tokIsAtom (extTok?) (s% "extending") then + (tokenFn ctx s).bindState fun s => + let s := s.popSyntax + sepBy1TermCommaFn (termStep parseFuel) false ctx s + else + s.pushSyntax (Syntax.mkNullNodeF .snil) + sAfterExt.bindState fun s => + if s.hasError then s else + (optDeclSigTypeFn ctx s).bindState fun s => + if s.hasError then s else + bindPeek ctx s fun whereTok? s => + let sAfterBody := + if tokIsAtom (whereTok?) (s% "where") || tokIsAtom (whereTok?) (s% ":=") then + (tokenFn ctx s).bindState fun s => + let s := s.popSyntax + let customCtorAttempt : ParserFn := fun c st => + (identFn c st).bindState fun st => + if st.hasError then st else + (symbolFn (s% "::") c st).bindState fun st => + if st.hasError then st else + st.popSyntax -- keep just `ident` + let noCustomCtor : ParserFn := fun _ st => + st.pushSyntax (Syntax.mkNullNodeF .snil) + (tryOrElseFn customCtorAttempt noCustomCtor ctx s).bindState fun s => + bindPeek ctx s fun next? s => + if tokIsAtom (next?) (s% "|") then + manyCtorDeclFn ctx s + else + manyStructFieldDeclFn ctx s + else + let s := s.pushSyntax (Syntax.mkNullNodeF .snil) + s.pushSyntax (Syntax.mkNullNodeF .snil) + sAfterBody.bindState fun s => + (optDerivingFn ctx s).bindState fun s => + s.mkNode kind iniSz + +/-- First-order `mutual ... end` command loop. -/ +def mutualCmdItemFn (cmdRec : ParserFn) (ctx : IxParserContext) (s : ParserState) : ParserState := + bindPeek ctx s fun t? st => + if tokIsAtom (t?) (s% "end") || (t?).isNone then st.mkUnexpectedError (s% "end of mutual block") + else +cmdRec ctx st + +def manyMutualCmdLoop (cmdRec : ParserFn) (ctx : IxParserContext) (s : ParserState) : Nat → ParserState + | 0 => s.mkUnexpectedError (s% "parser fuel exhausted") + | fuel + 1 => + let iniSz := s.stackSize + let iniPos := s.pos + let iniBytes := s.remBytes + let s' := mutualCmdItemFn cmdRec ctx s + if s'.hasError then + if Nat.beq s'.pos iniPos then s'.restore iniSz iniPos iniBytes else s' + else if Nat.beq s'.pos iniPos then s' + else manyMutualCmdLoop cmdRec ctx s' fuel + +def many1MutualCmdFn (cmdRec : ParserFn) (ctx : IxParserContext) (s : ParserState) : ParserState := + let iniSz := s.stackSize + let s1 := mutualCmdItemFn cmdRec ctx s + if s1.hasError then s1.mkNode SyntaxKindF.nullKind iniSz + else (manyMutualCmdLoop cmdRec ctx s1 parseFuel).mkNode SyntaxKindF.nullKind iniSz + +/-- First-order `#merge ... end` arm loop. -/ +def mergeArmItemFn (cmdRec : ParserFn) (ctx : IxParserContext) (s : ParserState) : ParserState := + let armSz := s.stackSize + let st := symbolFn (s% "|") ctx s + if st.hasError then st else + let st := identFn ctx st + if st.hasError then st else + let st := orelseFn (symbolFn (s% "=>")) (symbolFn (s% "↦")) ctx st + if st.hasError then st else + let st := cmdRec ctx st + st.mkNode SyntaxKindF.mergeArm armSz + +def manyMergeArmLoop (cmdRec : ParserFn) (ctx : IxParserContext) (s : ParserState) : Nat → ParserState + | 0 => s.mkUnexpectedError (s% "parser fuel exhausted") + | fuel + 1 => + let iniSz := s.stackSize + let iniPos := s.pos + let iniBytes := s.remBytes + let s' := mergeArmItemFn cmdRec ctx s + if s'.hasError then + if Nat.beq s'.pos iniPos then s'.restore iniSz iniPos iniBytes else s' + else if Nat.beq s'.pos iniPos then s' + else manyMergeArmLoop cmdRec ctx s' fuel + +def many1MergeArmFn (cmdRec : ParserFn) (ctx : IxParserContext) (s : ParserState) : ParserState := + let iniSz := s.stackSize + let s1 := mergeArmItemFn cmdRec ctx s + if s1.hasError then s1.mkNode SyntaxKindF.nullKind iniSz + else (manyMergeArmLoop cmdRec ctx s1 parseFuel).mkNode SyntaxKindF.nullKind iniSz + +/-- Cold helper: parse non-declaration keyword commands (`import`, `namespace`, `section`, + `end`, `universe`, `variable`, `open`, `mutual`, `#merge`). -/ +def commandNonDeclFn (cmdRec : ParserFn) (kw : Sym) (ctx : IxParserContext) (s : ParserState) : + Option ParserState := + if Sym.beq kw (s% "import") then + let iniSz := s.stackSize + let s := (symbolFn (s% "import") ctx s).bindState fun s => + bindPeek ctx s fun next? s => + match next? with + | some (.node _ k _) => + if k == SyntaxKindF.hashRef then + (hashRefFn ctx s).bindState fun s => + s.mkNode SyntaxKindF.hashImport iniSz + else + s.mkUnexpectedError (s% "expected module name or # after 'import'") + | _ => + (identFn ctx s).bindState fun s => + if s.hasError then s else + bindPeek ctx s fun atTok? s => + let sAfterAt := + if tokIsAtom (atTok?) (s% "@") then + (symbolFn (s% "@") ctx s).bindState fun s => + let s := s.popSyntax + hashRefFn ctx s + else + s.pushSyntax (Syntax.mkNullNodeF .snil) + sAfterAt.bindState fun s => + s.mkNode SyntaxKindF.importDecl iniSz + some s + else if Sym.beq kw (s% "namespace") then + let iniSz := s.stackSize + some ((symbolFn (s% "namespace") ctx s).bindState fun s => + (identFn ctx s).bindState fun s => + s.mkNode SyntaxKindF.namespaceDecl iniSz) + else if Sym.beq kw (s% "section") then + let iniSz := s.stackSize + some ((symbolFn (s% "section") ctx s).bindState fun s => + (optionalFn identFn ctx s).bindState fun s => + s.mkNode SyntaxKindF.sectionDecl iniSz) + else if Sym.beq kw (s% "end") then + let iniSz := s.stackSize + some ((symbolFn (s% "end") ctx s).bindState fun s => + (optionalFn identFn ctx s).bindState fun s => + s.mkNode SyntaxKindF.endDecl iniSz) + else if Sym.beq kw (s% "universe") then + let iniSz := s.stackSize + some ((symbolFn (s% "universe") ctx s).bindState fun s => + (many1IdentFn ctx s).bindState fun s => + s.mkNode SyntaxKindF.universeDecl iniSz) + else if Sym.beq kw (s% "variable") then + let iniSz := s.stackSize + some ((symbolFn (s% "variable") ctx s).bindState fun s => + (many1BracketedBinderFn (termStep parseFuel) ctx s).bindState fun s => + s.mkNode SyntaxKindF.variableDecl iniSz) + else if Sym.beq kw (s% "open") then + let iniSz := s.stackSize + some ((symbolFn (s% "open") ctx s).bindState fun s => + (many1IdentFn ctx s).bindState fun s => + (optionalFn (fun c st => + (symbolFn (s% "(") c st).bindState fun st => + (many1IdentFn c st).bindState fun st => + symbolFn (s% ")") c st) ctx s).bindState fun s => + s.mkNode SyntaxKindF.openDecl iniSz) + else if Sym.beq kw (s% "mutual") then + let iniSz := s.stackSize + some ((symbolFn (s% "mutual") ctx s).bindState fun s => + (many1MutualCmdFn cmdRec ctx s).bindState fun s => + (symbolFn (s% "end") ctx s).bindState fun s => + s.mkNode SyntaxKindF.mutualDecl iniSz) + else if Sym.beq kw (s% "#merge") then + let iniSz := s.stackSize + some ((symbolFn (s% "#merge") ctx s).bindState fun s => + (many1MergeArmFn cmdRec ctx s).bindState fun s => + (symbolFn (s% "end") ctx s).bindState fun s => + s.mkNode SyntaxKindF.mergeConflictDecl iniSz) + else + none + +/-- Cold helper: parse identifier-led soft-keyword commands (`map`, `infix*`, `notation`, `macro*`). -/ +def commandWordFn (word : Sym) (ctx : IxParserContext) (s : ParserState) : ParserState := + if word == (s% "map") then + let iniSz := s.stackSize + (nonReservedSymbolFn (s% "map") ctx s).bindState fun s => + (identFn ctx s).bindState fun s => + (symbolFn (s% ":=") ctx s).bindState fun s => + (hashRefFn ctx s).bindState fun s => + s.mkNode SyntaxKindF.buildMapDecl iniSz + else if word == (s% "infixl") || word == (s% "infixr") || word == (s% "infix") || + word == (s% "prefix") || word == (s% "postfix") then + let iniSz := s.stackSize + (tokenFn ctx s).bindState fun s => + (optionalFn (seqFn (symbolFn (s% ":")) (orelseFn numLitFn identFn)) ctx s).bindState fun s => + (strLitFn ctx s).bindState fun s => + (orelseFn (symbolFn (s% "=>")) (symbolFn (s% "↦")) ctx s).bindState fun s => + (withPrecFn 0 termFn ctx s).bindState fun s => + s.mkNode SyntaxKindF.notationDecl iniSz + else if word == (s% "notation") || word == (s% "syntax") then + let iniSz := s.stackSize + (tokenFn ctx s).bindState fun s => + (optionalFn (seqFn (symbolFn (s% ":")) (orelseFn numLitFn identFn)) ctx s).bindState fun s => + let itemsSz := s.stackSize + (parseNotationItemsLoop 64 ctx s).bindState fun s => + (s.mkNode SyntaxKindF.nullKind itemsSz).bindState fun s => + if word == (s% "syntax") then + s.mkNode SyntaxKindF.notationDecl iniSz + else + (orelseFn (symbolFn (s% "=>")) (symbolFn (s% "↦")) ctx s).bindState fun s => + (withPrecFn 0 termFn ctx s).bindState fun s => + s.mkNode SyntaxKindF.notationDecl iniSz + else if word == (s% "macro") then + let iniSz := s.stackSize + (tokenFn ctx s).bindState fun s => + (optionalFn (seqFn (symbolFn (s% ":")) (orelseFn numLitFn identFn)) ctx s).bindState fun s => + let itemsSz := s.stackSize + (parseNotationItemsLoop 64 ctx s).bindState fun s => + (s.mkNode SyntaxKindF.nullKind itemsSz).bindState fun s => + (orelseFn (symbolFn (s% "=>")) (symbolFn (s% "↦")) ctx s).bindState fun s => + (withPrecFn 0 termFn ctx s).bindState fun s => + s.mkNode SyntaxKindF.macroDecl iniSz + else if word == (s% "macro_rules") then + let iniSz := s.stackSize + (tokenFn ctx s).bindState fun s => + (many1MatchAltFn (termStep parseFuel) ctx s).bindState fun s => + s.mkNode SyntaxKindF.macroDecl iniSz + else + s.mkUnexpectedError (s% "unexpected identifier at top level") + +/-- Parse a single top-level command, structurally recursive on `fuel : Nat` (for `mutual ... end`). -/ +def commandStep : Nat → ParserFn + | 0 => fun _ s => s.mkUnexpectedError (s% "parser fuel exhausted in command") + | fuel + 1 => fun ctx s => + bindPeek ctx s fun tok? s => + match tok? with + | none => s.mkEOIError [(s% "command")] + | some (.atom _ kw) => + let nonDeclRes := + match kw with + | .cons b0 _ => + -- Fast skip for `def`/`theorem`/`abbrev`/`axiom`/`class`/`lemma`/`private`/`protected`/`@` + if Nat.beq b0 100 || Nat.beq b0 116 || Nat.beq b0 97 || Nat.beq b0 99 || + Nat.beq b0 108 || Nat.beq b0 112 || Nat.beq b0 64 then none + else commandNonDeclFn (commandStep fuel) kw ctx s + | .nil => none + match nonDeclRes with + | some s' => s' + | none => + -- Declaration with optional modifiers (`private`, `protected`, `noncomputable`, etc.) + (declModifiersFn ctx s).bindState fun s => + bindPeek ctx s fun declTok? s => + match declTok? with + | some (.atom _ dkw) => + match dkw with + | .cons b0 rest => + if Nat.beq b0 100 && Sym.beq rest (s% "ef") then parseValueDecl SyntaxKindF.defDecl ctx s + else if Nat.beq b0 116 && Sym.beq rest (s% "heorem") then parseValueDecl SyntaxKindF.theoremDecl ctx s + else if Nat.beq b0 115 && Sym.beq rest (s% "tructure") then parseStructureOrClassDecl SyntaxKindF.structureDecl ctx s + else if Nat.beq b0 105 then + if Sym.beq rest (s% "nductive") then parseInductiveDecl ctx s + else if Sym.beq rest (s% "nstance") then parseInstanceDecl ctx s + else s.mkUnexpectedError (s% "unexpected keyword at top level") + else if Nat.beq b0 97 then + if Sym.beq rest (s% "bbrev") then parseValueDecl SyntaxKindF.abbrevDecl ctx s + else if Sym.beq rest (s% "xiom") then parseAxiomDecl ctx s + else s.mkUnexpectedError (s% "unexpected keyword at top level") + else if Nat.beq b0 108 && Sym.beq rest (s% "emma") then parseValueDecl SyntaxKindF.theoremDecl ctx s + else if Nat.beq b0 111 && Sym.beq rest (s% "paque") then parseValueDecl SyntaxKindF.opaqueDecl ctx s + else if Nat.beq b0 99 && Sym.beq rest (s% "lass") then parseStructureOrClassDecl SyntaxKindF.classDecl ctx s + else s.mkUnexpectedError (s% "unexpected keyword at top level") + | .nil => s.mkUnexpectedError (s% "unexpected keyword at top level") + | _ => s.mkUnexpectedError (s% "expected declaration keyword after modifiers") + | some (.ident _ _ (.str .anon word)) => + commandWordFn word ctx s + | _ => + s.mkUnexpectedError (s% "expected top-level command") + +def commandFn : ParserFn := commandStep parseFuel + +/-! ## Module Parser & Dynamic Operator / Notation / Macro Registration -/ + +/-- Decode an optional `: prec` node into a `Nat` precedence. -/ +def decodeOptPrec (optNode : Stx) (defaultPrec : Nat := 65) : Nat := + if Syntax.getNumArgs optNode < 2 then defaultPrec + else + let pNode := Syntax.getArg optNode 1 + if Syntax.isOfKindF pNode SyntaxKindF.numLit then + (parseNatLiteralSym (Syntax.getAtomSym (Syntax.getArg pNode 0))).getD defaultPrec + else + let idSym := FName.toSym (Syntax.getIdF pNode) + if Sym.beq idSym (s% "max") then maxPrec + else if Sym.beq idSym (s% "arg") then argPrec + else if Sym.beq idSym (s% "lead") then leadPrec + else if Sym.beq idSym (s% "min") then 0 + else defaultPrec + +/-- Monomorphic helpers for notation/macro decoding (zero `List.map`/`filterMap`/`filter` closures). -/ +def mapNotationSyms : List Sym → List NotationItem + | [] => [] + | s :: rest => .sym s :: mapNotationSyms rest + +def collectNotationSyms : List NotationItem → List Sym + | [] => [] + | .sym s :: rest => s :: collectNotationSyms rest + | .var .. :: rest => collectNotationSyms rest + +def collectNotationVarAntiquots : List NotationItem → List Stx + | [] => [] + | .var vId _ :: rest => + Syntax.mkNodeListF SyntaxKindF.antiquotTerm [Syntax.mkSimpleAtomF (s% "$"), Syntax.mkSimpleIdentF vId] :: + collectNotationVarAntiquots rest + | .sym _ :: rest => collectNotationVarAntiquots rest + +def collectMacroRules : List Stx → List MacroRule + | [] => [] + | altStx :: rest => + if Syntax.isOfKindF altStx SyntaxKindF.matchAlt then + let pats := Syntax.getArgs (Syntax.getArg altStx 1) + let pat0 := Syntax.listGetD pats.toList 0 .missing + let rhs := Syntax.getArg altStx 3 + { pat := pat0, rhs } :: collectMacroRules rest + else + collectMacroRules rest + +def stripSpaceBytes : Sym → Sym + | .nil => .nil + | .cons b bs => if isSpaceByte b then stripSpaceBytes bs else .cons b (stripSpaceBytes bs) + +/-- Decode a `SyntaxKindF.notationDecl` or `SyntaxKindF.macroDecl` into `(Option NotationRule, List MacroRule)`. -/ +def decodeNotationOrMacroDecl (cmd : Stx) : Option NotationRule × List MacroRule := + let k := Syntax.getKindF cmd + let args := Syntax.getArgs cmd + let kwStr := tokenText (Syntax.listGetD args.toList 0 .missing) + if (k == SyntaxKindF.notationDecl && (kwStr == (s% "notation") || kwStr == (s% "syntax"))) || + (k == SyntaxKindF.macroDecl && kwStr == (s% "macro")) then + let prec := decodeOptPrec (Syntax.listGetD args.toList 1 .missing) 65 + let itemsNode := Syntax.listGetD args.toList 2 .missing + let rhsStx := Syntax.listGetD args.toList 4 .missing + let rawItems := (Syntax.getArgs itemsNode).toList + let rec buildItems : List Stx → Nat → List NotationItem + | [], _ => [] + | it :: rest, idx => + let defaultVarPrec := if rest.isEmpty then prec else 0 + if Syntax.isOfKindF it SyntaxKindF.strLit then + let strVal := Syntax.getAtomSym (Syntax.getArg it 0) + let splitSyms := mapNotationSyms (splitNotationLiteral strVal) + splitSyms ++ buildItems rest (idx + 1) + else if Syntax.isOfKindF it SyntaxKindF.nullKind then + let vId := Syntax.getIdF (Syntax.getArg it 0) + let pNode := Syntax.getArg it 1 + let vPrec := + if Syntax.isOfKindF pNode SyntaxKindF.numLit then + (parseNatLiteralSym (Syntax.getAtomSym (Syntax.getArg pNode 0))).getD defaultVarPrec + else defaultVarPrec + .var vId vPrec :: buildItems rest (idx + 1) + else + let id := Syntax.getIdF it + let vId := + if kwStr == (s% "syntax") && (id == FName.simple (s% "term") || id == FName.simple (s% "ident")) then + FName.mkNat (FName.simple (s% "_arg")) idx + else id + .var vId defaultVarPrec :: buildItems rest (idx + 1) + let items := buildItems rawItems 0 + let syms := collectNotationSyms items + let ruleName := FName.mkStr2 (s% "_notation") (Sym.intercalate (s% "_") syms) + let nRule : NotationRule := { ruleName, prec, items, rhs := rhsStx } + if kwStr == (s% "syntax") || Syntax.isMissing rhsStx then + (some nRule, []) + else + let varAntiquots := collectNotationVarAntiquots items + let patStx := Syntax.mkNodeListF SyntaxKindF.macroCall + (Syntax.mkSimpleIdentF ruleName :: varAntiquots) + (some nRule, [{ pat := patStx, rhs := rhsStx }]) + else if k == SyntaxKindF.macroDecl && kwStr == (s% "macro_rules") then + let altsNode := Syntax.listGetD args.toList 1 .missing + (none, collectMacroRules (Syntax.getArgs altsNode).toList) + else + (none, []) + +/-- Update `IxParserEnv` when a `notationDecl` or `macroDecl` command is parsed. -/ +def updateParserEnvFromCommand (env : IxParserEnv) (cmd : Stx) : IxParserEnv := + let k := Syntax.getKindF cmd + if k == SyntaxKindF.notationDecl || k == SyntaxKindF.macroDecl then + let args := Syntax.getArgs cmd + let kwStr := tokenText (Syntax.listGetD args.toList 0 .missing) + if kwStr == (s% "infixl") || kwStr == (s% "infixr") || kwStr == (s% "infix") || + kwStr == (s% "prefix") || kwStr == (s% "postfix") then + let fixity : FixityKind := + if kwStr == (s% "infixr") then .infixr + else if kwStr == (s% "infix") then .infixn + else if kwStr == (s% "prefix") then .prefixOp + else if kwStr == (s% "postfix") then .postfixOp + else .infixl + let prec := decodeOptPrec (Syntax.listGetD args.toList 1 .missing) 65 + let rawSym := match args[2]? with + | some strNode => + match Syntax.getArg strNode 0 with + | .atom _ s => stripSpaceBytes s + | _ => .nil + | none => .nil + let target := match args[4]? with + | some stx => + let id := Syntax.getIdF stx + if FName.isAnonymous id then none else some id + | none => none + if rawSym.isEmpty then env + else env.addOperator { symbol := rawSym, kind := SyntaxKindF.appTerm, fixity, prec, targetFn := target } + else + match (decodeNotationOrMacroDecl cmd).1 with + | some nRule => env.addNotation nRule + | none => env + else + env + +/-- Circuit-clean module parser loop returning `Option (Stx × IxParserEnv)` without + pulling `ParserError.toString` / `lineCol` / `Nat.toDigitsCore` into the circuit closure. -/ +def parseModuleLoopRaw (inputCtx : InputContext) (env : IxParserEnv) (s : ParserState) + (revCmds : List Stx) : Nat → Option (Stx × IxParserEnv) + | 0 => none + | fuel + 1 => + let ctx : IxParserContext := { inputCtx, env, prec := 0 } + if atEOI ctx s then + some (Syntax.mkNodeListF SyntaxKindF.moduleKind revCmds.reverse, env) + else + let iniSz := s.stackSize + let s' := commandFn ctx s + match s'.errorMsg with + | some _ => none + | none => + let cmd := match s'.stxStack.rev with | x :: _ => x | [] => .missing + let sClean := s'.shrinkStack iniSz + if Syntax.isOfKindF cmd SyntaxKindF.notationDecl || Syntax.isOfKindF cmd SyntaxKindF.macroDecl then + parseModuleLoopRaw inputCtx (updateParserEnvFromCommand env cmd) sClean (cmd :: revCmds) fuel + else + parseModuleLoopRaw inputCtx env sClean (cmd :: revCmds) fuel + +/-- Circuit-clean entry point parsing a UTF-8 `Sym` (`ByteList`) without error formatting overhead. -/ +def parseModuleBytesRaw (bytes : Sym) (env : IxParserEnv := defaultParserEnv) : + Option (Stx × IxParserEnv) := + let inputCtx := InputContext.mkInputContextFromBytes bytes + parseModuleLoopRaw inputCtx env (ParserState.init inputCtx.bytes) [] parseFuel + +/-- Loop parsing top-level commands until EOI, accumulating `revCmds : List Stx` in $O(1)$ + per command (avoiding $O(N^2)$ `Array.push` / `List.concat` in the kernel) and updating + `IxParserEnv` when notation commands occur. -/ +def parseModuleLoop (inputCtx : InputContext) (env : IxParserEnv) (s : ParserState) + (revCmds : List Stx) : Nat → Except String (Stx × IxParserEnv) + | 0 => .error "parser fuel exhausted in module loop" + | fuel + 1 => + s.bindState fun s => + let ctx : IxParserContext := { inputCtx, env, prec := 0 } + if atEOI ctx s then + .ok (Syntax.mkNodeListF SyntaxKindF.moduleKind revCmds.reverse, env) + else + let iniSz := s.stackSize + (commandFn ctx s).bindState fun s' => + match s'.errorMsg with + | some err => .error (ParserError.toString inputCtx err) + | none => + let cmd := match s'.stxStack.rev with | x :: _ => x | [] => .missing + let sClean := s'.shrinkStack iniSz + if Syntax.isOfKindF cmd SyntaxKindF.notationDecl || Syntax.isOfKindF cmd SyntaxKindF.macroDecl then + (updateParserEnvFromCommand env cmd).bindParserEnv fun env' => + parseModuleLoop inputCtx env' sClean (cmd :: revCmds) fuel + else + parseModuleLoop inputCtx env sClean (cmd :: revCmds) fuel + +/-- Parse a complete `.ix` / `.lean` UTF-8 `Sym` into a `SyntaxKindF.moduleKind` AST + and the resulting `IxParserEnv`. -/ +def parseModuleBytesWithEnv (bytes : Sym) (env : IxParserEnv := defaultParserEnv) : + Except String (Stx × IxParserEnv) := + let inputCtx := InputContext.mkInputContextFromBytes bytes + parseModuleLoop inputCtx env (ParserState.init inputCtx.bytes) [] parseFuel + +/-- Parse a complete `.ix` / `.lean` source string into a `SyntaxKindF.moduleKind` AST + and the resulting `IxParserEnv`. 100% pure and deterministic (zero `IO`). -/ +def parseModuleWithEnv (input : String) (_fileName : String := "") + (env : IxParserEnv := defaultParserEnv) : Except String (Stx × IxParserEnv) := + parseModuleBytesWithEnv (Sym.ofString input) env + +/-- Parse a complete `.ix` / `.lean` source string into an `Stx` tree. -/ +def parseModule (input : String) (fileName : String := "") + (env : IxParserEnv := defaultParserEnv) : Except String Stx := do + let (stx, _) ← parseModuleWithEnv input fileName env + return stx + +end Ix.Frontend.Parser diff --git a/Ix/Frontend/Parser/FastTables.lean b/Ix/Frontend/Parser/FastTables.lean new file mode 100644 index 0000000000..68d2fde57c --- /dev/null +++ b/Ix/Frontend/Parser/FastTables.lean @@ -0,0 +1,417 @@ +/- + Ix.Frontend.Parser.FastTables: O(1) first-byte-dispatched lookup tables for the + default Ix lexer tokens, reserved keywords, infix operators, and arg-start atoms. + + Eliminates runtime `Trie.ofSymbols` / `ofKeywordsLoop` construction (~3,500+ + startup rows per invocation) and linear 28-67× `Sym.beq` scans per token while + preserving 100% bit-exact maximal-munch and precedence semantics! +-/ +module + +public import Ix.Frontend.Parser.Types + +@[expose] public section + +namespace Ix.Frontend.Parser + +/-! ## 1. O(1) First-Byte-Dispatched Default Keyword Table (45 Reserved Keywords) -/ + +/-- Cold helper: check keywords starting with `a..i` (bytes 97..105). -/ +def isDefaultKeywordAI (b0 : Nat) (rest : Sym) : Bool := + if Nat.beq b0 97 then -- 'a': abbrev, axiom + Sym.beq rest (s% "bbrev") || Sym.beq rest (s% "xiom") + else if Nat.beq b0 98 then -- 'b': by + Sym.beq rest (s% "y") + else if Nat.beq b0 99 then -- 'c': calc, class + Sym.beq rest (s% "alc") || Sym.beq rest (s% "lass") + else if Nat.beq b0 100 then -- 'd': def, deriving + Sym.beq rest (s% "ef") || Sym.beq rest (s% "eriving") + else if Nat.beq b0 101 then -- 'e': else, end, export, extending, extends + Sym.beq rest (s% "lse") || Sym.beq rest (s% "nd") || + Sym.beq rest (s% "xport") || Sym.beq rest (s% "xtends") || Sym.beq rest (s% "xtending") + else if Nat.beq b0 102 then -- 'f': forall, fun + Sym.beq rest (s% "un") || Sym.beq rest (s% "orall") + else if Nat.beq b0 104 then -- 'h': have + Sym.beq rest (s% "ave") + else if Nat.beq b0 105 then -- 'i': if, import, in, inductive, instance + Sym.beq rest (s% "f") || Sym.beq rest (s% "n") || + Sym.beq rest (s% "mport") || Sym.beq rest (s% "nductive") || Sym.beq rest (s% "nstance") + else + false + +/-- Cold helper: check keywords starting with `l..w` (bytes 108..119). -/ +def isDefaultKeywordLW (b0 : Nat) (rest : Sym) : Bool := + if Nat.beq b0 108 then -- 'l': lemma, let + Sym.beq rest (s% "et") || Sym.beq rest (s% "emma") + else if Nat.beq b0 109 then -- 'm': match, mutual + Sym.beq rest (s% "atch") || Sym.beq rest (s% "utual") + else if Nat.beq b0 110 then -- 'n': namespace, noncomputable + Sym.beq rest (s% "amespace") || Sym.beq rest (s% "oncomputable") + else if Nat.beq b0 111 then -- 'o': opaque, open + Sym.beq rest (s% "pen") || Sym.beq rest (s% "paque") + else if Nat.beq b0 112 then -- 'p': partial, private, protected + Sym.beq rest (s% "rivate") || Sym.beq rest (s% "rotected") || Sym.beq rest (s% "artial") + else if Nat.beq b0 115 then -- 's': section, sorry, structure + Sym.beq rest (s% "tructure") || Sym.beq rest (s% "ection") || Sym.beq rest (s% "orry") + else if Nat.beq b0 116 then -- 't': then, theorem + Sym.beq rest (s% "hen") || Sym.beq rest (s% "heorem") + else if Nat.beq b0 117 then -- 'u': universe, unsafe + Sym.beq rest (s% "niverse") || Sym.beq rest (s% "nsafe") + else if Nat.beq b0 118 then -- 'v': variable + Sym.beq rest (s% "ariable") + else if Nat.beq b0 119 then -- 'w': where, with + Sym.beq rest (s% "here") || Sym.beq rest (s% "ith") + else + false + +/-- O(1) first-byte-dispatched reserved keyword check matching `defaultKeywords` exactly. -/ +def isDefaultKeyword : Sym → Bool + | .nil => false + | .cons b0 rest => + if Nat.ble 97 b0 && Nat.ble b0 105 then + isDefaultKeywordAI b0 rest + else if Nat.ble 108 b0 && Nat.ble b0 119 then + isDefaultKeywordLW b0 rest + else if Nat.beq b0 80 then -- 'P': Prop + Sym.beq rest (s% "rop") + else if Nat.beq b0 83 then -- 'S': Sort + Sym.beq rest (s% "ort") + else if Nat.beq b0 84 then -- 'T': Type + Sym.beq rest (s% "ype") + else if Nat.beq b0 95 then -- '_': _ + Sym.isEmpty rest + else + false + +/-! ## 2. O(1) First-Byte-Dispatched Default Token Scanner (64 Maximal-Munch Symbols) -/ + +/-- Cold helper: maximal-munch match of multi-byte UTF-8 default tokens + (`⦃`, `⦄`, `⟨`, `⟩`, `→`, `←`, `↔`, `↦`, `·`, `∀`, `∃`, `λ`, `≠`, `≤`, `≥`, `∧`, `∨`, `¬`). -/ +def matchDefaultUtf8TokenBytes (pos : Nat) (b0 : Nat) (rest0 : Sym) : Option (Sym × Nat × Sym) := + match rest0 with + | .cons b1 rest1 => + if Nat.beq b0 194 then + if Nat.beq b1 172 then some (s% "¬", Nat.add pos 2, rest1) + else if Nat.beq b1 183 then some (s% "·", Nat.add pos 2, rest1) + else none + else if Nat.beq b0 206 then + if Nat.beq b1 187 then some (s% "λ", Nat.add pos 2, rest1) else none + else if Nat.beq b0 226 then + match rest1 with + | .cons b2 rest2 => + if Nat.beq b1 134 then + if Nat.beq b2 146 then some (s% "→", Nat.add pos 3, rest2) + else if Nat.beq b2 144 then some (s% "←", Nat.add pos 3, rest2) + else if Nat.beq b2 148 then some (s% "↔", Nat.add pos 3, rest2) + else if Nat.beq b2 166 then some (s% "↦", Nat.add pos 3, rest2) + else none + else if Nat.beq b1 136 then + if Nat.beq b2 128 then some (s% "∀", Nat.add pos 3, rest2) + else if Nat.beq b2 131 then some (s% "∃", Nat.add pos 3, rest2) + else if Nat.beq b2 167 then some (s% "∧", Nat.add pos 3, rest2) + else if Nat.beq b2 168 then some (s% "∨", Nat.add pos 3, rest2) + else none + else if Nat.beq b1 137 then + if Nat.beq b2 160 then some (s% "≠", Nat.add pos 3, rest2) + else if Nat.beq b2 164 then some (s% "≤", Nat.add pos 3, rest2) + else if Nat.beq b2 165 then some (s% "≥", Nat.add pos 3, rest2) + else none + else if Nat.beq b1 159 then + if Nat.beq b2 168 then some (s% "⟨", Nat.add pos 3, rest2) + else if Nat.beq b2 169 then some (s% "⟩", Nat.add pos 3, rest2) + else none + else if Nat.beq b1 166 then + if Nat.beq b2 131 then some (s% "⦃", Nat.add pos 3, rest2) + else if Nat.beq b2 132 then some (s% "⦄", Nat.add pos 3, rest2) + else none + else none + | .nil => none + else none + | .nil => none + +/-- Cold helper: maximal-munch match of less-common ASCII operator/punctuation tokens. -/ +def matchDefaultAsciiOpBytes (pos : Nat) (b0 : Nat) (rest0 : Sym) : Option (Sym × Nat × Sym) := + if Nat.beq b0 60 then -- '<': <=, <-, <->, <;>, <|, < + match rest0 with + | .cons b1 rest1 => + if Nat.beq b1 61 then some (s% "<=", Nat.add pos 2, rest1) + else if Nat.beq b1 124 then some (s% "<|", Nat.add pos 2, rest1) + else if Nat.beq b1 45 then + match rest1 with + | .cons b2 rest2 => + if Nat.beq b2 62 then some (s% "<->", Nat.add pos 3, rest2) + else some (s% "<-", Nat.add pos 2, rest1) + | .nil => some (s% "<-", Nat.add pos 2, rest1) + else if Nat.beq b1 59 then + match rest1 with + | .cons b2 rest2 => + if Nat.beq b2 62 then some (s% "<;>", Nat.add pos 3, rest2) + else some (s% "<", Nat.add pos 1, rest0) + | .nil => some (s% "<", Nat.add pos 1, rest0) + else some (s% "<", Nat.add pos 1, rest0) + | .nil => some (s% "<", Nat.add pos 1, .nil) + else if Nat.beq b0 62 then -- '>': >=, > + match rest0 with + | .cons b1 rest1 => + if Nat.beq b1 61 then some (s% ">=", Nat.add pos 2, rest1) + else some (s% ">", Nat.add pos 1, rest0) + | .nil => some (s% ">", Nat.add pos 1, .nil) + else if Nat.beq b0 43 then -- '+': ++, + + match rest0 with + | .cons b1 rest1 => + if Nat.beq b1 43 then some (s% "++", Nat.add pos 2, rest1) + else some (s% "+", Nat.add pos 1, rest0) + | .nil => some (s% "+", Nat.add pos 1, .nil) + else if Nat.beq b0 33 then -- '!': !=, ! + match rest0 with + | .cons b1 rest1 => + if Nat.beq b1 61 then some (s% "!=", Nat.add pos 2, rest1) + else some (s% "!", Nat.add pos 1, rest0) + | .nil => some (s% "!", Nat.add pos 1, .nil) + else if Nat.beq b0 38 then -- '&': &&, & + match rest0 with + | .cons b1 rest1 => + if Nat.beq b1 38 then some (s% "&&", Nat.add pos 2, rest1) + else some (s% "&", Nat.add pos 1, rest0) + | .nil => some (s% "&", Nat.add pos 1, .nil) + else if Nat.beq b0 47 then -- '/': /\, / + match rest0 with + | .cons b1 rest1 => + if Nat.beq b1 92 then some (s% "/\\", Nat.add pos 2, rest1) + else some (s% "/", Nat.add pos 1, rest0) + | .nil => some (s% "/", Nat.add pos 1, .nil) + else if Nat.beq b0 92 then -- '\': \/ + match rest0 with + | .cons b1 rest1 => + if Nat.beq b1 47 then some (s% "\\/", Nat.add pos 2, rest1) else none + | .nil => none + else if Nat.beq b0 96 then -- '`': `(, ` + match rest0 with + | .cons b1 rest1 => + if Nat.beq b1 40 then some (s% "`(", Nat.add pos 2, rest1) + else some (s% "`", Nat.add pos 1, rest0) + | .nil => some (s% "`", Nat.add pos 1, .nil) + else if Nat.beq b0 42 then some (s% "*", Nat.add pos 1, rest0) + else if Nat.beq b0 37 then some (s% "%", Nat.add pos 1, rest0) + else if Nat.beq b0 94 then some (s% "^", Nat.add pos 1, rest0) + else if Nat.beq b0 91 then some (s% "[", Nat.add pos 1, rest0) + else if Nat.beq b0 93 then some (s% "]", Nat.add pos 1, rest0) + else if Nat.beq b0 64 then -- '@': @[, @ + match rest0 with + | .cons b1 rest1 => + if Nat.beq b1 91 then some (s% "@[", Nat.add pos 2, rest1) + else some (s% "@", Nat.add pos 1, rest0) + | .nil => some (s% "@", Nat.add pos 1, .nil) + else if Nat.beq b0 36 then some (s% "$", Nat.add pos 1, rest0) + else if Nat.beq b0 126 then some (s% "~", Nat.add pos 1, rest0) + else if Nat.beq b0 95 then some (s% "_", Nat.add pos 1, rest0) + else none + +/-- Hot O(1) maximal-munch default token matcher (fast path for `(`, `)`, `:`, `:=`, `,`, `.`, + `{`, `}`, `=`, `=>`, `-`, `->`, `|`, `;`, with cold helpers for ops & UTF-8). -/ +def matchDefaultTokenBytes (pos : Nat) : Sym → Option (Sym × Nat × Sym) + | .nil => none + | .cons b0 rest0 => + if Nat.beq b0 40 then some (s% "(", Nat.add pos 1, rest0) + else if Nat.beq b0 41 then some (s% ")", Nat.add pos 1, rest0) + else if Nat.beq b0 58 then -- ':': :=, ::, : + match rest0 with + | .cons b1 rest1 => + if Nat.beq b1 61 then some (s% ":=", Nat.add pos 2, rest1) + else if Nat.beq b1 58 then some (s% "::", Nat.add pos 2, rest1) + else some (s% ":", Nat.add pos 1, rest0) + | .nil => some (s% ":", Nat.add pos 1, .nil) + else if Nat.beq b0 44 then some (s% ",", Nat.add pos 1, rest0) + else if Nat.beq b0 59 then some (s% ";", Nat.add pos 1, rest0) + else if Nat.beq b0 46 then -- '.': .., .{, . + match rest0 with + | .cons b1 rest1 => + if Nat.beq b1 46 then some (s% "..", Nat.add pos 2, rest1) + else if Nat.beq b1 123 then some (s% ".{", Nat.add pos 2, rest1) + else some (s% ".", Nat.add pos 1, rest0) + | .nil => some (s% ".", Nat.add pos 1, .nil) + else if Nat.beq b0 123 then -- '{': {{, { + match rest0 with + | .cons b1 rest1 => + if Nat.beq b1 123 then some (s% "{{", Nat.add pos 2, rest1) + else some (s% "{", Nat.add pos 1, rest0) + | .nil => some (s% "{", Nat.add pos 1, .nil) + else if Nat.beq b0 125 then -- '}': }}, } + match rest0 with + | .cons b1 rest1 => + if Nat.beq b1 125 then some (s% "}}", Nat.add pos 2, rest1) + else some (s% "}", Nat.add pos 1, rest0) + | .nil => some (s% "}", Nat.add pos 1, .nil) + else if Nat.beq b0 61 then -- '=': =>, ==, = + match rest0 with + | .cons b1 rest1 => + if Nat.beq b1 62 then some (s% "=>", Nat.add pos 2, rest1) + else if Nat.beq b1 61 then some (s% "==", Nat.add pos 2, rest1) + else some (s% "=", Nat.add pos 1, rest0) + | .nil => some (s% "=", Nat.add pos 1, .nil) + else if Nat.beq b0 45 then -- '-': ->, - + match rest0 with + | .cons b1 rest1 => + if Nat.beq b1 62 then some (s% "->", Nat.add pos 2, rest1) + else some (s% "-", Nat.add pos 1, rest0) + | .nil => some (s% "-", Nat.add pos 1, .nil) + else if Nat.beq b0 124 then -- '|': ||, |>, | + match rest0 with + | .cons b1 rest1 => + if Nat.beq b1 124 then some (s% "||", Nat.add pos 2, rest1) + else if Nat.beq b1 62 then some (s% "|>", Nat.add pos 2, rest1) + else some (s% "|", Nat.add pos 1, rest0) + | .nil => some (s% "|", Nat.add pos 1, .nil) + else if Nat.ble 194 b0 then + matchDefaultUtf8TokenBytes pos b0 rest0 + else + matchDefaultAsciiOpBytes pos b0 rest0 + +/-! ## 3. O(1) First-Byte-Dispatched Default Infix Operator Table (28 Operators) -/ + +/-- Cold helper: look up one of the 28 builtin infix operators by first byte `b0` and tail `rest`. + Returns `none` in 1-2 checks for all non-operators (`(`, `)`, `,`, `:`, `:=`, `=>`, letters, etc.). -/ +def lookupDefaultInfixOpCore (b0 : Nat) (rest : Sym) : Option OperatorSpec := + if Nat.beq b0 43 then -- '+', '++' + if Sym.isEmpty rest then + some { symbol := s% "+", kind := SyntaxKindF.binOpTerm, fixity := .infixl, prec := 65, targetFn := some (FName.mkStr2 (s% "HAdd") (s% "hAdd")) } + else if Sym.beq rest (s% "+") then + some { symbol := s% "++", kind := SyntaxKindF.binOpTerm, fixity := .infixl, prec := 65, targetFn := some (FName.mkStr2 (s% "HAppend") (s% "hAppend")) } + else none + else if Nat.beq b0 45 then -- '-' + if Sym.isEmpty rest then + some { symbol := s% "-", kind := SyntaxKindF.binOpTerm, fixity := .infixl, prec := 65, targetFn := some (FName.mkStr2 (s% "HSub") (s% "hSub")) } + else none + else if Nat.beq b0 42 then -- '*' + if Sym.isEmpty rest then + some { symbol := s% "*", kind := SyntaxKindF.binOpTerm, fixity := .infixl, prec := 70, targetFn := some (FName.mkStr2 (s% "HMul") (s% "hMul")) } + else none + else if Nat.beq b0 61 then -- '=', '==' + if Sym.isEmpty rest then + some { symbol := s% "=", kind := SyntaxKindF.binOpTerm, fixity := .infixn, prec := 50, targetFn := some (FName.simple (s% "Eq")) } + else if Sym.beq rest (s% "=") then + some { symbol := s% "==", kind := SyntaxKindF.binOpTerm, fixity := .infixn, prec := 50, targetFn := some (FName.mkStr2 (s% "BEq") (s% "beq")) } + else none + else if Nat.beq b0 47 then -- '/', '/\' + if Sym.isEmpty rest then + some { symbol := s% "/", kind := SyntaxKindF.binOpTerm, fixity := .infixl, prec := 70, targetFn := some (FName.mkStr2 (s% "HDiv") (s% "hDiv")) } + else if Sym.beq rest (s% "\\") then + some { symbol := s% "/\\", kind := SyntaxKindF.binOpTerm, fixity := .infixr, prec := 35, targetFn := some (FName.simple (s% "And")) } + else none + else if Nat.beq b0 37 then -- '%' + if Sym.isEmpty rest then + some { symbol := s% "%", kind := SyntaxKindF.binOpTerm, fixity := .infixl, prec := 70, targetFn := some (FName.mkStr2 (s% "HMod") (s% "hMod")) } + else none + else if Nat.beq b0 94 then -- '^' + if Sym.isEmpty rest then + some { symbol := s% "^", kind := SyntaxKindF.binOpTerm, fixity := .infixr, prec := 80, targetFn := some (FName.mkStr2 (s% "HPow") (s% "hPow")) } + else none + else if Nat.beq b0 58 then -- '::' + if Sym.beq rest (s% ":") then + some { symbol := s% "::", kind := SyntaxKindF.binOpTerm, fixity := .infixr, prec := 67, targetFn := some (FName.mkStr2 (s% "List") (s% "cons")) } + else none + else if Nat.beq b0 33 then -- '!=' + if Sym.beq rest (s% "=") then + some { symbol := s% "!=", kind := SyntaxKindF.binOpTerm, fixity := .infixn, prec := 50, targetFn := some (FName.simple (s% "bne")) } + else none + else if Nat.beq b0 60 then -- '<', '<=', '<->', '<|' + if Sym.isEmpty rest then + some { symbol := s% "<", kind := SyntaxKindF.binOpTerm, fixity := .infixn, prec := 50, targetFn := some (FName.mkStr2 (s% "LT") (s% "lt")) } + else if Sym.beq rest (s% "=") then + some { symbol := s% "<=", kind := SyntaxKindF.binOpTerm, fixity := .infixn, prec := 50, targetFn := some (FName.mkStr2 (s% "LE") (s% "le")) } + else if Sym.beq rest (s% "->") then + some { symbol := s% "<->", kind := SyntaxKindF.binOpTerm, fixity := .infixr, prec := 20, targetFn := some (FName.simple (s% "Iff")) } + else if Sym.beq rest (s% "|") then + some { symbol := s% "<|", kind := SyntaxKindF.binOpTerm, fixity := .infixr, prec := 10, targetFn := none } + else none + else if Nat.beq b0 62 then -- '>', '>=' + if Sym.isEmpty rest then + some { symbol := s% ">", kind := SyntaxKindF.binOpTerm, fixity := .infixn, prec := 50, targetFn := some (FName.mkStr2 (s% "GT") (s% "gt")) } + else if Sym.beq rest (s% "=") then + some { symbol := s% ">=", kind := SyntaxKindF.binOpTerm, fixity := .infixn, prec := 50, targetFn := some (FName.mkStr2 (s% "GE") (s% "ge")) } + else none + else if Nat.beq b0 38 then -- '&&' + if Sym.beq rest (s% "&") then + some { symbol := s% "&&", kind := SyntaxKindF.binOpTerm, fixity := .infixr, prec := 35, targetFn := some (FName.simple (s% "and")) } + else none + else if Nat.beq b0 124 then -- '||', '|>' + if Sym.beq rest (s% "|") then + some { symbol := s% "||", kind := SyntaxKindF.binOpTerm, fixity := .infixr, prec := 30, targetFn := some (FName.simple (s% "or")) } + else if Sym.beq rest (s% ">") then + some { symbol := s% "|>", kind := SyntaxKindF.binOpTerm, fixity := .infixl, prec := 10, targetFn := none } + else none + else if Nat.beq b0 92 then -- '\/' + if Sym.beq rest (s% "/") then + some { symbol := s% "\\/", kind := SyntaxKindF.binOpTerm, fixity := .infixr, prec := 30, targetFn := some (FName.simple (s% "Or")) } + else none + else if Nat.beq b0 226 then -- UTF-8: ≠, ≤, ≥, ∧, ∨, ↔ + match rest with + | .cons b1 (.cons b2 .nil) => + if Nat.beq b1 137 then + if Nat.beq b2 160 then some { symbol := s% "≠", kind := SyntaxKindF.binOpTerm, fixity := .infixn, prec := 50, targetFn := some (FName.simple (s% "Ne")) } + else if Nat.beq b2 164 then some { symbol := s% "≤", kind := SyntaxKindF.binOpTerm, fixity := .infixn, prec := 50, targetFn := some (FName.mkStr2 (s% "LE") (s% "le")) } + else if Nat.beq b2 165 then some { symbol := s% "≥", kind := SyntaxKindF.binOpTerm, fixity := .infixn, prec := 50, targetFn := some (FName.mkStr2 (s% "GE") (s% "ge")) } + else none + else if Nat.beq b1 136 then + if Nat.beq b2 167 then some { symbol := s% "∧", kind := SyntaxKindF.binOpTerm, fixity := .infixr, prec := 35, targetFn := some (FName.simple (s% "And")) } + else if Nat.beq b2 168 then some { symbol := s% "∨", kind := SyntaxKindF.binOpTerm, fixity := .infixr, prec := 30, targetFn := some (FName.simple (s% "Or")) } + else none + else if Nat.beq b1 134 && Nat.beq b2 148 then + some { symbol := s% "↔", kind := SyntaxKindF.binOpTerm, fixity := .infixr, prec := 20, targetFn := some (FName.simple (s% "Iff")) } + else none + | _ => none + else + none + +/-- Fast O(1) default infix operator check (rejects common delimiters `)`, `(`, `,`, `;`, `.` + and letters immediately without entering `lookupDefaultInfixOpCore`). -/ +def lookupDefaultInfixOp? (sym : Sym) (minPrec : Nat) : Option OperatorSpec := + match sym with + | .nil => none + | .cons b0 rest => + -- Fast reject: letters (`A-Z`, `a-z`), `(`, `)`, `,`, `;`, `.`, `{`, `}`, `[`, `]` + if Nat.beq b0 40 || Nat.beq b0 41 || Nat.beq b0 44 || Nat.beq b0 46 || Nat.beq b0 59 || + Nat.beq b0 123 || Nat.beq b0 125 || Nat.beq b0 91 || Nat.beq b0 93 || + (Nat.ble 65 b0 && Nat.ble b0 90) || (Nat.ble 97 b0 && Nat.ble b0 122) then + none + else + match lookupDefaultInfixOpCore b0 rest with + | some op => if Nat.ble minPrec op.prec then some op else none + | none => none + +/-- Fast O(1) check whether an `.atom` symbol can start a juxtaposition argument `f arg` + under the default parser environment (no custom operators/notations). -/ +def defaultCanStartArgAtom : Sym → Bool + | .nil => false + | .cons b0 rest => + -- Always-yes single-byte openers: '(', '[', '{', '@', '_', '$', '`' + if Nat.beq b0 40 || Nat.beq b0 91 || Nat.beq b0 64 || + Nat.beq b0 95 || Nat.beq b0 36 || Nat.beq b0 96 then + Sym.isEmpty rest || (Nat.beq b0 96 && Sym.beq rest (s% "(")) + else if Nat.beq b0 123 then true -- '{' or '{{' + -- Always-no closers, separators, and binary ops: ')', '}', ']', ':', ';', ',', '|', '=', '-', '>', '<', '+', '*', '/', '%', '^', '\' + else if Nat.beq b0 41 || Nat.beq b0 125 || Nat.beq b0 93 || Nat.beq b0 58 || + Nat.beq b0 59 || Nat.beq b0 44 || Nat.beq b0 124 || Nat.beq b0 61 || + Nat.beq b0 45 || Nat.beq b0 62 || Nat.beq b0 60 || Nat.beq b0 43 || + Nat.beq b0 42 || Nat.beq b0 47 || Nat.beq b0 37 || Nat.beq b0 94 || + Nat.beq b0 92 then + false + else if Nat.beq b0 80 then Sym.beq rest (s% "rop") -- Prop + else if Nat.beq b0 84 then Sym.beq rest (s% "ype") -- Type + else if Nat.beq b0 83 then Sym.beq rest (s% "ort") -- Sort + else if Nat.beq b0 226 then -- '⟨' (226, 159, 168) is yes; all other UTF-8 ops/arrows/closers are no + match rest with + | .cons b1 (.cons b2 .nil) => Nat.beq b1 159 && Nat.beq b2 168 + | _ => false + else if Nat.beq b0 116 then -- 'true' yes, 'then'/'theorem' no + Sym.beq rest (s% "rue") + else if Nat.beq b0 102 then -- 'false' yes, 'from'/'fun'/'forall' no + Sym.beq rest (s% "alse") + else if Nat.beq b0 115 then -- 'sorry' yes + Sym.beq rest (s% "orry") + else if Nat.beq b0 33 then -- '!' yes (if not '!='), '!=' no + Sym.isEmpty rest + else + !(isDefaultKeyword (.cons b0 rest) || (lookupDefaultInfixOp? (.cons b0 rest) 0).isSome) + +end Ix.Frontend.Parser diff --git a/Ix/Frontend/Parser/Term.lean b/Ix/Frontend/Parser/Term.lean new file mode 100644 index 0000000000..e17b1f4b2c --- /dev/null +++ b/Ix/Frontend/Parser/Term.lean @@ -0,0 +1,2531 @@ +/- + Ix.Frontend.Parser.Term: Pure, total, fuel-bounded Pratt expression, binder, + substructural mode attribute (`@[unique]`, `@[borrowed]`, `@[once]`, `@[erased]`, + `@[shared]`, `let @[borrow]`), universe level, + and tactic parser for the Ix Frontend. + + Every recursive grammar production is structurally recursive on `fuel : Nat` + (compiled directly to `Nat.rec`, with zero `WellFounded.fix` or `partial`). +-/ +module + +public import Ix.Frontend.Parser.Basic + +@[expose] public section + +namespace Ix.Frontend.Parser + +/-! ## Precedence Constants & Default Parser Environment -/ + +def maxPrec : Nat := 1024 +def argPrec : Nat := 1023 +def leadPrec : Nat := 1022 +def arrowPrec : Nat := 25 + +/-- All punctuation and operator tokens recognized by the default Ix lexer. -/ +def defaultTokenSymbols : List Sym := + [(s% "("), (s% ")"), (s% "{"), (s% "}"), (s% "["), (s% "]"), (s% "⦃"), (s% "⦄"), (s% "{{"), (s% "}}"), (s% "⟨"), (s% "⟩"), + (s% ":="), (s% "::"), (s% ":"), (s% ";"), (s% ","), (s% "."), (s% ".."), (s% "|"), (s% "@["), (s% "@"), (s% "_"), + (s% "→"), (s% "->"), (s% "←"), (s% "<-"), (s% "↔"), (s% "<->"), (s% "↦"), (s% "=>"), (s% "<;>"), (s% "·"), (s% "∀"), (s% "∃"), (s% "λ"), + (s% "+"), (s% "-"), (s% "*"), (s% "/"), (s% "%"), (s% "^"), (s% "++"), + (s% "=="), (s% "!="), (s% "≠"), (s% "<="), (s% "≤"), (s% "<"), (s% ">="), (s% "≥"), (s% ">"), (s% "="), + (s% "&&"), (s% "||"), (s% "∧"), (s% "/\\"), (s% "∨"), (s% "\\/"), (s% "¬"), + (s% "|>"), (s% "<|"), (s% "$"), (s% "`("), (s% "`"), + (s% "!"), (s% "~"), (s% "&"), (s% ".{")] + +/-- Reserved keywords that cannot be parsed as plain identifiers unless escaped with `«...»`. -/ +def defaultKeywords : List Sym := + [(s% "def"), (s% "abbrev"), (s% "theorem"), (s% "lemma"), (s% "axiom"), (s% "opaque"), (s% "instance"), + (s% "inductive"), (s% "structure"), (s% "class"), (s% "where"), (s% "extending"), (s% "extends"), (s% "deriving"), + (s% "mutual"), (s% "end"), (s% "namespace"), (s% "section"), (s% "open"), (s% "export"), (s% "variable"), (s% "universe"), + (s% "import"), (s% "private"), (s% "protected"), (s% "noncomputable"), (s% "partial"), (s% "unsafe"), + (s% "fun"), (s% "forall"), (s% "let"), (s% "have"), (s% "in"), (s% "if"), (s% "then"), (s% "else"), (s% "match"), (s% "with"), + (s% "by"), (s% "calc"), (s% "Prop"), (s% "Type"), (s% "Sort"), (s% "sorry"), (s% "_")] + +/-- Builtin binary infix operators with their precedences and associativities. -/ +def defaultOperators : List OperatorSpec := + [ { symbol := (s% "^"), kind := SyntaxKindF.binOpTerm, fixity := .infixr, prec := 80, targetFn := some (FName.mkStr2 (s% "HPow") (s% "hPow")) } + , { symbol := (s% "*"), kind := SyntaxKindF.binOpTerm, fixity := .infixl, prec := 70, targetFn := some (FName.mkStr2 (s% "HMul") (s% "hMul")) } + , { symbol := (s% "/"), kind := SyntaxKindF.binOpTerm, fixity := .infixl, prec := 70, targetFn := some (FName.mkStr2 (s% "HDiv") (s% "hDiv")) } + , { symbol := (s% "%"), kind := SyntaxKindF.binOpTerm, fixity := .infixl, prec := 70, targetFn := some (FName.mkStr2 (s% "HMod") (s% "hMod")) } + , { symbol := (s% "::"), kind := SyntaxKindF.binOpTerm, fixity := .infixr, prec := 67, targetFn := some (FName.mkStr2 (s% "List") (s% "cons")) } + , { symbol := (s% "+"), kind := SyntaxKindF.binOpTerm, fixity := .infixl, prec := 65, targetFn := some (FName.mkStr2 (s% "HAdd") (s% "hAdd")) } + , { symbol := (s% "-"), kind := SyntaxKindF.binOpTerm, fixity := .infixl, prec := 65, targetFn := some (FName.mkStr2 (s% "HSub") (s% "hSub")) } + , { symbol := (s% "++"), kind := SyntaxKindF.binOpTerm, fixity := .infixl, prec := 65, targetFn := some (FName.mkStr2 (s% "HAppend") (s% "hAppend")) } + , { symbol := (s% "=="), kind := SyntaxKindF.binOpTerm, fixity := .infixn, prec := 50, targetFn := some (FName.mkStr2 (s% "BEq") (s% "beq")) } + , { symbol := (s% "!="), kind := SyntaxKindF.binOpTerm, fixity := .infixn, prec := 50, targetFn := some (FName.simple (s% "bne")) } + , { symbol := (s% "≠"), kind := SyntaxKindF.binOpTerm, fixity := .infixn, prec := 50, targetFn := some (FName.simple (s% "Ne")) } + , { symbol := (s% "="), kind := SyntaxKindF.binOpTerm, fixity := .infixn, prec := 50, targetFn := some (FName.simple (s% "Eq")) } + , { symbol := (s% "<="), kind := SyntaxKindF.binOpTerm, fixity := .infixn, prec := 50, targetFn := some (FName.mkStr2 (s% "LE") (s% "le")) } + , { symbol := (s% "≤"), kind := SyntaxKindF.binOpTerm, fixity := .infixn, prec := 50, targetFn := some (FName.mkStr2 (s% "LE") (s% "le")) } + , { symbol := (s% "<"), kind := SyntaxKindF.binOpTerm, fixity := .infixn, prec := 50, targetFn := some (FName.mkStr2 (s% "LT") (s% "lt")) } + , { symbol := (s% ">="), kind := SyntaxKindF.binOpTerm, fixity := .infixn, prec := 50, targetFn := some (FName.mkStr2 (s% "GE") (s% "ge")) } + , { symbol := (s% "≥"), kind := SyntaxKindF.binOpTerm, fixity := .infixn, prec := 50, targetFn := some (FName.mkStr2 (s% "GE") (s% "ge")) } + , { symbol := (s% ">"), kind := SyntaxKindF.binOpTerm, fixity := .infixn, prec := 50, targetFn := some (FName.mkStr2 (s% "GT") (s% "gt")) } + , { symbol := (s% "&&"), kind := SyntaxKindF.binOpTerm, fixity := .infixr, prec := 35, targetFn := some (FName.simple (s% "and")) } + , { symbol := (s% "∧"), kind := SyntaxKindF.binOpTerm, fixity := .infixr, prec := 35, targetFn := some (FName.simple (s% "And")) } + , { symbol := (s% "/\\"), kind := SyntaxKindF.binOpTerm, fixity := .infixr, prec := 35, targetFn := some (FName.simple (s% "And")) } + , { symbol := (s% "||"), kind := SyntaxKindF.binOpTerm, fixity := .infixr, prec := 30, targetFn := some (FName.simple (s% "or")) } + , { symbol := (s% "∨"), kind := SyntaxKindF.binOpTerm, fixity := .infixr, prec := 30, targetFn := some (FName.simple (s% "Or")) } + , { symbol := (s% "\\/"), kind := SyntaxKindF.binOpTerm, fixity := .infixr, prec := 30, targetFn := some (FName.simple (s% "Or")) } + , { symbol := (s% "↔"), kind := SyntaxKindF.binOpTerm, fixity := .infixr, prec := 20, targetFn := some (FName.simple (s% "Iff")) } + , { symbol := (s% "<->"), kind := SyntaxKindF.binOpTerm, fixity := .infixr, prec := 20, targetFn := some (FName.simple (s% "Iff")) } + , { symbol := (s% "|>"), kind := SyntaxKindF.binOpTerm, fixity := .infixl, prec := 10, targetFn := none } + , { symbol := (s% "<|"), kind := SyntaxKindF.binOpTerm, fixity := .infixr, prec := 10, targetFn := none } + ] + +/-- Strictly fold a list of keyword strings into a `Trie Bool`. -/ +def ofKeywordsLoop : Trie Bool → List Sym → Trie Bool + | t, [] => t + | t, kw :: kws => ofKeywordsLoop (t.insert kw true) kws + +/-- Build the default `IxParserEnv` with ZERO runtime trie/list construction! + Default tokens, keywords, and builtin infix operators are dispatched in O(1) via `FastTables`; + `tokens`, `keywords`, `operators`, and `notations` hold user-defined extensions only. -/ +def defaultParserEnv : IxParserEnv := + { tokens := Trie.empty + keywords := Trie.empty + operators := [] + notations := [] } + +/-- Register a new token in `IxParserEnv`. -/ +def IxParserEnv.addToken (env : IxParserEnv) (sym : Sym) : IxParserEnv := + { env with tokens := env.tokens.insert sym sym } + +def IxParserEnv.addOperator (env : IxParserEnv) (op : OperatorSpec) : IxParserEnv := + match env.addToken op.symbol with + | ⟨tokens, keywords, operators, notations⟩ => ⟨tokens, keywords, op :: operators, notations⟩ + +/-- Single-byte delimiter brackets/separators that always form their own token. -/ +def isSingleDelimByte (b : Nat) : Bool := + Nat.beq b 40 || Nat.beq b 41 || Nat.beq b 91 || Nat.beq b 93 || + Nat.beq b 123 || Nat.beq b 125 || Nat.beq b 44 || Nat.beq b 59 + +/-- Scan a run of operator/symbol bytes (non-space, non-ident, non-single-delimiter). -/ +def scanSymRunBytes : Sym → Sym → Sym × Sym + | .nil, revAcc => (.nil, Sym.reverse revAcc) + | .cons b bs, revAcc => + if isSpaceByte b || isAsciiIdFirstByte b || isDigitByte b || isSingleDelimByte b then + (.cons b bs, Sym.reverse revAcc) + else + scanSymRunBytes bs (.cons b revAcc) + +/-- Split a notation string literal (e.g. `"my_add("` -> `["my_add", "("]`) into atomic lexer `Sym` tokens. -/ +def splitNotationLiteralAux : Nat → Sym → List Sym → List Sym + | 0, _, revToks => revToks.reverse + | _, .nil, revToks => revToks.reverse + | fuel + 1, .cons b bs, revToks => + if isSpaceByte b then + splitNotationLiteralAux fuel bs revToks + else if isSingleDelimByte b then + splitNotationLiteralAux fuel bs ((.cons b .nil) :: revToks) + else if isAsciiIdFirstByte b then + let (rem, partSym, _) := scanIdentRestBytes parseFuel bs 0 (.cons b .nil) + splitNotationLiteralAux fuel rem (partSym :: revToks) + else + let (rem, symBs) := scanSymRunBytes bs (.cons b .nil) + splitNotationLiteralAux fuel rem (symBs :: revToks) + +def splitNotationLiteral (s : Sym) : List Sym := + splitNotationLiteralAux (Nat.add (Sym.length s) 1) s [] + +/-- Monomorphic first-order helper: add symbol tokens of `NotationItem`s to `IxParserEnv`. -/ +def addNotationItemTokens (env : IxParserEnv) : List NotationItem → IxParserEnv + | [] => env + | .sym s :: rest => + let env' := match s with + | .cons b _ => if isAsciiIdFirstByte b then env else env.addToken s + | .nil => env + addNotationItemTokens env' rest + | .var .. :: rest => addNotationItemTokens env rest + +/-- Register a `NotationRule` and all of its non-identifier symbol tokens in `IxParserEnv`. -/ +def IxParserEnv.addNotation (env : IxParserEnv) (rule : NotationRule) : IxParserEnv := + let envWithToks := addNotationItemTokens env rule.items + match envWithToks with + | ⟨tokens, keywords, operators, notations⟩ => + ⟨tokens, keywords, operators, rule :: notations⟩ + +/-- Merge custom operators and notations from `imported` into `base`. -/ +def IxParserEnv.merge (base imported : IxParserEnv) : IxParserEnv := + let env1 := imported.operators.foldr (fun op acc => + if acc.operators.any (fun o => o.symbol == op.symbol && o.fixity == op.fixity) then acc + else acc.addOperator op) base + imported.notations.foldr (fun rule acc => + if acc.notations.any (fun r => r.ruleName == rule.ruleName) then acc + else acc.addNotation rule) env1 + +/-! ## Universe Level Parser (`levelFn`) -/ + +/-- Parse an atomic universe level: numeric literal, identifier, or `( level )`. -/ +def levelAtomFn (levelRec : ParserFn) : ParserFn := fun ctx s => + bindPeek ctx s fun tok? s => + match tok? with + | some (.node _ k (.scons (.atom _ _) .snil)) => + if k == SyntaxKindF.numLit then + tokenFn ctx s + else + s.mkUnexpectedError (s% "expected universe level") + | some (.ident ..) => + tokenFn ctx s + | some (.atom _ sym) => + if Sym.beq sym (s% "(") then + (symbolFn (s% "(") ctx s).bindState fun s => + if s.hasError then s else + let iniSz := s.stackSize + (withPrecFn 0 levelRec ctx s).bindState fun s => + if s.hasError then s else + let lvlStx := s.stxStack.back + (symbolFn (s% ")") ctx s).bindState fun s => + if s.hasError then s else + let s := s.shrinkStack (iniSz - 1) + s.pushSyntax lvlStx + else s.mkUnexpectedError (s% "expected universe level") + | _ => + s.mkUnexpectedError (s% "expected universe level") + +/-- Parse optional `+ k` universe level offset. -/ +def levelTrailingAddFn : ParserFn := fun ctx s => + bindPeek ctx s fun tok? s => + if tokIsAtom (tok?) (s% "+") then + let iniSz := s.stackSize + (symbolFn (s% "+") ctx s).bindState fun s => + (numLitFn ctx s).bindState fun s => + if s.hasError then s + else s.mkTrailingNode SyntaxKindF.levelAdd iniSz 65 + else +s + +/-- Parse a universe level atom followed by optional `+ k`. -/ +def levelAtomWithAddFn (levelRec : ParserFn) (ctx : IxParserContext) (s : ParserState) : ParserState := + let st := levelAtomFn levelRec ctx s + if st.hasError then st else levelTrailingAddFn ctx st + +/-- First-order zero-or-more `levelAtomWithAddFn` loop for `max`/`imax`. -/ +def manyLevelAtomAddLoop (levelRec : ParserFn) (ctx : IxParserContext) (s : ParserState) : Nat → ParserState + | 0 => s.mkUnexpectedError (s% "parser fuel exhausted") + | fuel + 1 => + let iniSz := s.stackSize + let iniPos := s.pos + let iniBytes := s.remBytes + let s' := levelAtomWithAddFn levelRec ctx s + if s'.hasError then + if Nat.beq s'.pos iniPos then s'.restore iniSz iniPos iniBytes else s' + else if Nat.beq s'.pos iniPos then s' + else manyLevelAtomAddLoop levelRec ctx s' fuel + +def many1LevelAtomAddFn (levelRec : ParserFn) (ctx : IxParserContext) (s : ParserState) : ParserState := + let iniSz := s.stackSize + let s1 := levelAtomWithAddFn levelRec ctx s + if s1.hasError then s1.mkNode SyntaxKindF.nullKind iniSz + else (manyLevelAtomAddLoop levelRec ctx s1 parseFuel).mkNode SyntaxKindF.nullKind iniSz + +/-- Parse a universe level expression (`0`, `u`, `u + 1`, `max u v`, `imax u v`), + structurally recursive on `fuel : Nat`. -/ +def levelStep : Nat → ParserFn + | 0 => fun _ s => s.mkUnexpectedError (s% "parser fuel exhausted in universe level") + | fuel + 1 => fun ctx s => + let levelRec := levelStep fuel + bindPeek ctx s fun tok? s => + if tokIsWord (tok?) (s% "max") then + let iniSz := s.stackSize + (tokenFn ctx s).bindState fun s => + (many1LevelAtomAddFn levelRec ctx s).bindState fun s => + s.mkNode SyntaxKindF.levelMax iniSz + else if tokIsWord (tok?) (s% "imax") then + let iniSz := s.stackSize + (tokenFn ctx s).bindState fun s => + (many1LevelAtomAddFn levelRec ctx s).bindState fun s => + s.mkNode SyntaxKindF.levelIMax iniSz + else + levelAtomWithAddFn levelRec ctx s + +def levelFn : ParserFn := levelStep parseFuel + +/-- First-order comma-separated `levelFn` loop for `.{u, v}`. -/ +def sepByLevelCommaLoop (ctx : IxParserContext) (s : ParserState) : Nat → ParserState + | 0 => s.mkUnexpectedError (s% "parser fuel exhausted") + | fuel + 1 => + let sepIniSz := s.stackSize + let sepIniPos := s.pos + let sepIniBytes := s.remBytes + let sSep := symbolFn (s% ",") ctx s + if sSep.hasError then + if Nat.beq sSep.pos sepIniPos then sSep.restore sepIniSz sepIniPos sepIniBytes else sSep + else + let sAfterSep := sSep.shrinkStack sepIniSz + let sElem := levelFn ctx sAfterSep + if sElem.hasError then sElem + else sepByLevelCommaLoop ctx sElem fuel + +def sepBy1LevelCommaFn (ctx : IxParserContext) (s : ParserState) : ParserState := + let iniSz := s.stackSize + let s1 := levelFn ctx s + if s1.hasError then s1.mkNode SyntaxKindF.nullKind iniSz + else (sepByLevelCommaLoop ctx s1 parseFuel).mkNode SyntaxKindF.nullKind iniSz + +/-- Parse optional `.{u, v}` universe level arguments on an identifier. -/ +def optUnivArgsFn : ParserFn := fun ctx s => + bindPeek ctx s fun tok? s => + if tokIsAtom (tok?) (s% ".{") then + let iniSz := s.stackSize + (symbolFn (s% ".{") ctx s).bindState fun s => + (sepBy1LevelCommaFn ctx s).bindState fun s => + (symbolFn (s% "}") ctx s).bindState fun s => + if s.hasError then s else + let lvls := s.stxStack.getD (iniSz + 1) + let s := s.shrinkStack iniSz + s.pushSyntax lvls + else + s.pushSyntax (Syntax.mkNullNodeF .snil) + +/-! ## Substructural Mode Attribute Modifiers (`@[unique, borrowed]`, etc.) -/ + +/-- Extract a single-component word symbol from an identifier or atom token. -/ +@[inline] def modeWordSym? (tok? : Option Stx) : Option (FSourceInfo × Sym) := + match tok? with + | some (.ident info _ (.str .anon v)) => some (info, v) + | some (.atom info v) => some (info, v) + | _ => none + +/-- Mode kind selector: 0 = binder, 1 = result, 2 = let, 3 = field. -/ +def isAllowedModeKw (kind : Nat) (v : Sym) : Bool := + if Nat.beq kind 1 then + Sym.beq v (s% "unique") || Sym.beq v (s% "borrowed") + else if Nat.beq kind 3 then + Sym.beq v (s% "shared") || Sym.beq v (s% "erased") + else if Nat.beq kind 2 then + Sym.beq v (s% "unique") || Sym.beq v (s% "borrowed") || + Sym.beq v (s% "once") || Sym.beq v (s% "erased") || Sym.beq v (s% "borrow") + else + Sym.beq v (s% "unique") || Sym.beq v (s% "borrowed") || + Sym.beq v (s% "once") || Sym.beq v (s% "erased") || Sym.beq v (s% "shared") + +/-- Parse `kw₁, kw₂, ... ]` after `@[` has already been consumed. + Pushes each validated mode keyword atom onto `s.stxStack`. -/ +def modeAttrBodyLoop (kind : Nat) (ctx : IxParserContext) (s : ParserState) : Nat → ParserState + | 0 => s.mkUnexpectedError (s% "mode annotation list too long") + | fuel + 1 => + bindPeek ctx s fun tok? s => + match modeWordSym? tok? with + | some (info, v) => + if isAllowedModeKw kind v then + (tokenFn ctx s).bindState fun s => + let s := s.popSyntax + let s := s.pushSyntax (Syntax.mkAtomF info v) + bindPeek ctx s fun sep? s => + if tokIsAtom sep? (s% ",") then + (tokenFn ctx s).bindState fun s => + modeAttrBodyLoop kind ctx s.popSyntax fuel + else if tokIsAtom sep? (s% "]") then + (tokenFn ctx s).bindState fun s => s.popSyntax + else + s.mkUnexpectedError (s% "expected ',' or ']' in mode annotation") + else + s.mkUnexpectedError (s% "invalid mode annotation") + | none => + s.mkUnexpectedError (s% "expected mode annotation keyword") + +/-- Parse zero or more adjacent `@[m₁, ...]` blocks (allowing arbitrary whitespace/newlines + around `@[`, `,`, `]`, and keywords). When `atomicFirst` is true, an invalid first block + restores state silently (used for statement-level structure fields before `@[attr] def`). -/ +def modeAttrBlocksLoop (kind : Nat) (atomicFirst : Bool) + (ctx : IxParserContext) (s : ParserState) : Nat → ParserState + | 0 => s + | fuel + 1 => + bindPeek ctx s fun tok? s => + if tokIsAtom tok? (s% "@[") then + let iniSz := s.stackSize + let iniPos := s.pos + let iniBytes := s.remBytes + let s1 := (tokenFn ctx s).popSyntax + let s2 := modeAttrBodyLoop kind ctx s1 16 + if s2.hasError then + if atomicFirst then s2.restore iniSz iniPos iniBytes else s2 + else + modeAttrBlocksLoop kind false ctx s2 fuel + else + s + +/-- Validate pushed mode keyword atoms against Ixon v5 mode combination rules. -/ +def validateModeAtomList : List Stx → Bool → Bool → Bool → Bool → Bool → Bool → Option Sym + | [], hasU, hasB, hasO, hasE, hasBrw, hasSh => + if hasBrw && (hasU || hasB || hasO || hasE || hasSh) then + some (s% "@[borrow] cannot be combined with other mode annotations") + else if hasE && (hasU || hasB || hasO || hasSh) then + some (s% "@[erased] cannot be combined with other mode annotations") + else if hasSh && (hasU || hasB || hasO) then + some (s% "@[shared] cannot be combined with other mode annotations") + else if hasO && hasU then + some (s% "@[once] cannot be combined with @[unique]") + else none + | a :: rest, hasU, hasB, hasO, hasE, hasBrw, hasSh => + let v := Syntax.getAtomSym a + if Sym.beq v (s% "unique") then + if hasU then some (s% "duplicate @[unique] mode annotation") + else validateModeAtomList rest true hasB hasO hasE hasBrw hasSh + else if Sym.beq v (s% "borrowed") then + if hasB then some (s% "duplicate @[borrowed] mode annotation") + else validateModeAtomList rest hasU true hasO hasE hasBrw hasSh + else if Sym.beq v (s% "once") then + if hasO then some (s% "duplicate @[once] mode annotation") + else validateModeAtomList rest hasU hasB true hasE hasBrw hasSh + else if Sym.beq v (s% "erased") then + if hasE then some (s% "duplicate @[erased] mode annotation") + else validateModeAtomList rest hasU hasB hasO true hasBrw hasSh + else if Sym.beq v (s% "borrow") then + if hasBrw then some (s% "duplicate @[borrow] mode annotation") + else validateModeAtomList rest hasU hasB hasO hasE true hasSh + else if Sym.beq v (s% "shared") then + if hasSh then some (s% "duplicate @[shared] mode annotation") + else validateModeAtomList rest hasU hasB hasO hasE hasBrw true + else + validateModeAtomList rest hasU hasB hasO hasE hasBrw hasSh + +/-- Build and validate a `nodeKind` mode-prefix node from `modeAttrBlocksLoop`. -/ +def modePrefixFn (kind : Nat) (nodeKind : FName) (atomicFirst : Bool := false) : ParserFn := fun ctx s => + s.bindState fun s => + let iniSz := s.stackSize + (modeAttrBlocksLoop kind atomicFirst ctx s 8).bindState fun s => + if s.hasError then s else + let sNode := s.mkNode nodeKind iniSz + let node := sNode.stxStack.back + match validateModeAtomList (Syntax.getArgs node).toList false false false false false false with + | none => sNode + | some msg => sNode.mkUnexpectedError msg + +/-- Parse an optional binder mode prefix (`@[unique]`, `@[borrowed]`, `@[once]`, `@[erased]`, `@[shared]`, + comma-separated or adjacent blocks) into a `SyntaxKindF.binderPrefix` node. -/ +def binderPrefixFn : ParserFn := modePrefixFn 0 SyntaxKindF.binderPrefix false + +/-- Parse an optional result/value mode prefix (`@[unique]`, `@[borrowed]`) + into a `SyntaxKindF.valuePrefix` node. -/ +def valuePrefixFn : ParserFn := modePrefixFn 1 SyntaxKindF.valuePrefix false + +/-- Parse an optional `let` mode prefix (`@[unique]`, `@[borrowed]`, `@[once]`, `@[erased]`, `@[borrow]`) + into a `SyntaxKindF.binderPrefix` node. -/ +def letPrefixFn : ParserFn := modePrefixFn 2 SyntaxKindF.binderPrefix false + +/-- Parse an optional structure field mode prefix (`@[shared]`, `@[erased]`) + into a `SyntaxKindF.binderPrefix` node. When `atomicFirst` is true, non-field `@[...]` + attributes (such as `@[no_rc]`) backtrack cleanly. -/ +def fieldPrefixFn (atomicFirst : Bool := false) : ParserFn := + modePrefixFn 3 SyntaxKindF.binderPrefix atomicFirst + +/-- Decode a `SyntaxKindF.binderPrefix` or `SyntaxKindF.valuePrefix` syntax node + into a `ParsedBinderContract`. -/ +def decodeContractPrefix (stx : Stx) : ParsedBinderContract := + (Syntax.getArgs stx).foldl (fun acc arg => + let sym := Syntax.getAtomSym arg + if Sym.beq sym (s% "erased") then { acc with uses := some .erased } + else if Sym.beq sym (s% "once") then { acc with uses := some .linear } + else if Sym.beq sym (s% "unique") then { acc with owned := some .unique } + else if Sym.beq sym (s% "borrowed") then { acc with locality := some .local } + else if Sym.beq sym (s% "borrow") then { acc with locality := some .local, isBorrow := true } + else if Sym.beq sym (s% "shared") then { acc with owned := some .shared } + else acc) {} + +/-- Merge two `ParsedBinderContract`s (e.g., binder-level prefix and domain-type prefix). -/ +def mergeParsedContracts (a b : ParsedBinderContract) : ParsedBinderContract := + { uses := b.uses.orElse (fun _ => a.uses) + owned := b.owned.orElse (fun _ => a.owned) + locality := b.locality.orElse (fun _ => a.locality) + isBorrow := a.isBorrow || b.isBorrow } + +/-! ## Binders, Tactics, and Pratt Expression Grammar -/ + +/-- Parse an identifier or `_` binder name. -/ +def binderIdentFn : ParserFn := + orelseFn identFn (symbolFn (s% "_")) + +/-- First-order zero-or-more `binderIdentFn` loop. -/ +def manyBinderIdentLoop (ctx : IxParserContext) (s : ParserState) : Nat → ParserState + | 0 => s.mkUnexpectedError (s% "parser fuel exhausted") + | fuel + 1 => + let iniSz := s.stackSize + let iniPos := s.pos + let iniBytes := s.remBytes + let s' := binderIdentFn ctx s + if s'.hasError then + if Nat.beq s'.pos iniPos then s'.restore iniSz iniPos iniBytes else s' + else if Nat.beq s'.pos iniPos then s' + else manyBinderIdentLoop ctx s' fuel + +def manyBinderIdentFn (ctx : IxParserContext) (s : ParserState) : ParserState := + let iniSz := s.stackSize + (manyBinderIdentLoop ctx s parseFuel).mkNode SyntaxKindF.nullKind iniSz + +/-- Parse one or more binder names (`x y _`). -/ +def binderIdentsFn : ParserFn := fun ctx s => + let iniSz := s.stackSize + let s1 := binderIdentFn ctx s + if s1.hasError then s1.mkNode SyntaxKindF.nullKind iniSz + else (manyBinderIdentLoop ctx s1 parseFuel).mkNode SyntaxKindF.nullKind iniSz + +/-- First-order same-line `binderIdentFn`. -/ +def sameLineBinderIdentFn (ctx : IxParserContext) (s : ParserState) : ParserState := + let (t?, s) := peekToken ctx s + match t? with + | some tok => + if hasLeadingNewline tok then s.mkUnexpectedError (s% "newline after tactic binder") + else binderIdentFn ctx s + | none => s.mkUnexpectedError (s% "end of tactic binder") + +def manySameLineBinderIdentLoop (ctx : IxParserContext) (s : ParserState) : Nat → ParserState + | 0 => s.mkUnexpectedError (s% "parser fuel exhausted") + | fuel + 1 => + let iniSz := s.stackSize + let iniPos := s.pos + let iniBytes := s.remBytes + let s' := sameLineBinderIdentFn ctx s + if s'.hasError then + if Nat.beq s'.pos iniPos then s'.restore iniSz iniPos iniBytes else s' + else if Nat.beq s'.pos iniPos then s' + else manySameLineBinderIdentLoop ctx s' fuel + +def manySameLineBinderIdentFn (ctx : IxParserContext) (s : ParserState) : ParserState := + let iniSz := s.stackSize + (manySameLineBinderIdentLoop ctx s parseFuel).mkNode SyntaxKindF.nullKind iniSz + +/-- Monomorphic first-order operator lookups (zero closures / zero `List.find?` pollution). -/ +def findInfixOpLoop (sym : Sym) (minPrec : Nat) : List OperatorSpec → Option OperatorSpec + | [] => none + | op :: rest => + if Nat.ble minPrec op.prec && op.symbol == sym && + (op.fixity == .infixl || op.fixity == .infixr || op.fixity == .infixn) then + some op + else + findInfixOpLoop sym minPrec rest + +def findInfixOp? (env : IxParserEnv) (sym : Sym) (minPrec : Nat) : Option OperatorSpec := + match env.operators with + | [] => lookupDefaultInfixOp? sym minPrec + | ops => + match findInfixOpLoop sym minPrec ops with + | some op => some op + | none => lookupDefaultInfixOp? sym minPrec + +def findPrefixOpLoop (sym : Sym) : List OperatorSpec → Option OperatorSpec + | [] => none + | op :: rest => + if op.fixity == .prefixOp && op.symbol == sym then some op + else findPrefixOpLoop sym rest + +def findPrefixOp? (env : IxParserEnv) (sym : Sym) : Option OperatorSpec := + findPrefixOpLoop sym env.operators + +def findPostfixOpLoop (sym : Sym) (minPrec : Nat) : List OperatorSpec → Option OperatorSpec + | [] => none + | op :: rest => + if op.fixity == .postfixOp && Nat.ble minPrec op.prec && op.symbol == sym then some op + else findPostfixOpLoop sym minPrec rest + +def findPostfixOp? (env : IxParserEnv) (sym : Sym) (minPrec : Nat) : Option OperatorSpec := + findPostfixOpLoop sym minPrec env.operators + +def hasNonPrefixOpLoop (sym : Sym) : List OperatorSpec → Bool + | [] => false + | op :: rest => + if op.symbol == sym && op.fixity != .prefixOp then true + else hasNonPrefixOpLoop sym rest + +def notationItemsHasSym (sym : Sym) : List NotationItem → Bool + | [] => false + | .sym s :: rest => if s == sym then true else notationItemsHasSym sym rest + | .var .. :: rest => notationItemsHasSym sym rest + +def hasNonLeadNotationSymLoop (sym : Sym) : List NotationRule → Bool + | [] => false + | r :: rest => + let hit := match r.items with + | _ :: tail => notationItemsHasSym sym tail + | [] => false + if hit then true else hasNonLeadNotationSymLoop sym rest + +def hasLeadNotationSymLoop (sym : Sym) : List NotationRule → Bool + | [] => false + | r :: rest => + let hit := match r.items with + | .sym s :: _ => s == sym + | _ => false + if hit then true else hasLeadNotationSymLoop sym rest + +/-- True if `sym` appears only as a non-leading delimiter in `env.notations` (so it cannot start an argument). -/ +def isNonLeadingNotationSym (env : IxParserEnv) (sym : Sym) : Bool := + match env.notations with + | [] => false + | nots => hasNonLeadNotationSymLoop sym nots && !hasLeadNotationSymLoop sym nots + +/-- True if `sym` is a relational operator allowed in a bounded quantifier binder (`∀ x > 0, ...`). -/ +def isBinderRelOp (sym : Sym) : Bool := + sym == (s% ">") || sym == (s% "<") || sym == (s% "≥") || sym == (s% ">=") || + sym == (s% "≤") || sym == (s% "<=") || sym == (s% "≠") || sym == (s% "!=") + +/-- Check if a token can start a function argument in juxtaposition `f a`. -/ +def canStartArg (env : IxParserEnv) : Stx → Bool + | .ident _ _ (.str .anon w) => + if Sym.beq w (s% "from") then false else !isNonLeadingNotationSym env .nil + | .ident .. => !isNonLeadingNotationSym env .nil + | .node _ k _ => + k == SyntaxKindF.numLit || k == SyntaxKindF.strLit || + k == SyntaxKindF.charLit || k == SyntaxKindF.hashRef + | .atom _ sym => + match env.operators, env.notations with + | [], [] => defaultCanStartArgAtom sym + | _, _ => + if defaultCanStartArgAtom sym then + !(isNonLeadingNotationSym env sym || hasNonPrefixOpLoop sym env.operators) + else + false + | .missing => false + | .snil | .scons .. => false + +/-- Parse an explicit binder `(@[erased] x y : A)` or `(x : A)` or bounded `(x > 0)` or `(x)`. -/ +def explicitBinderFn (termRec : ParserFn) : ParserFn := fun ctx s => + s.bindState fun s => + let iniSz := s.stackSize + (symbolFn (s% "(") ctx s).bindState fun s => + if s.hasError then s else + let s := s.popSyntax + (binderPrefixFn ctx s).bindState fun s => + if s.hasError then s else + (binderIdentsFn ctx s).bindState fun s => + if s.hasError then s else + bindPeek ctx s fun tok? s => + let sAfterTy := match tok? with + | some (.atom _ sym) => + if Sym.beq sym (s% ":") then + (symbolFn (s% ":") ctx s).bindState fun s => + let s := s.popSyntax + let s := s.pushSyntax (Syntax.mkNodeF SyntaxKindF.valuePrefix .snil) + withPrecFn 0 termRec ctx s + else if isBinderRelOp sym then + (tokenFn ctx s).bindState fun s => + let opTok := s.stxStack.back + let s := s.popSyntax + (withPrecFn 0 termRec ctx s).bindState fun s => + if s.hasError then s else + let rhsStx := s.stxStack.back + let s := s.popSyntax + let s := s.pushSyntax (Syntax.mkNodeF SyntaxKindF.valuePrefix .snil) + s.pushSyntax (Syntax.mkNodeListF SyntaxKindF.binOpTerm [Syntax.mkSimpleAtomF (s% "_bound"), opTok, rhsStx]) + else + let s := s.pushSyntax (Syntax.mkNodeF SyntaxKindF.valuePrefix .snil) + s.pushSyntax (Syntax.mkNullNodeF .snil) + | _ => + let s := s.pushSyntax (Syntax.mkNodeF SyntaxKindF.valuePrefix .snil) + s.pushSyntax (Syntax.mkNullNodeF .snil) + sAfterTy.bindState fun s => + if s.hasError then s else + (symbolFn (s% ")") ctx s).bindState fun s => + if s.hasError then s else + (s.popSyntax).mkNode SyntaxKindF.explicitBinder iniSz + +/-- Parse an implicit binder `{@[erased] α β : Type}` or `{α β}`. -/ +def implicitBinderFn (termRec : ParserFn) : ParserFn := fun ctx s => + s.bindState fun s => + let iniSz := s.stackSize + (symbolFn (s% "{") ctx s).bindState fun s => + if s.hasError then s else + let s := s.popSyntax + (binderPrefixFn ctx s).bindState fun s => + if s.hasError then s else + (binderIdentsFn ctx s).bindState fun s => + if s.hasError then s else + bindPeek ctx s fun tok? s => + let sAfterTy := + if tokIsAtom (tok?) (s% ":") then + (symbolFn (s% ":") ctx s).bindState fun s => + let s := s.popSyntax + let s := s.pushSyntax (Syntax.mkNodeF SyntaxKindF.valuePrefix .snil) + withPrecFn 0 termRec ctx s + else + let s := s.pushSyntax (Syntax.mkNodeF SyntaxKindF.valuePrefix .snil) + s.pushSyntax (Syntax.mkNullNodeF .snil) + sAfterTy.bindState fun s => + if s.hasError then s else + (symbolFn (s% "}") ctx s).bindState fun s => + if s.hasError then s else + (s.popSyntax).mkNode SyntaxKindF.implicitBinder iniSz + +/-- Parse a strict-implicit binder `⦃x : A⦄` or `{{x : A}}`. -/ +def strictImplicitBinderFn (termRec : ParserFn) : ParserFn := fun ctx s => + s.bindState fun s => + let iniSz := s.stackSize + bindPeek ctx s fun tok? s => + let closeSym := + if tokIsAtom (tok?) (s% "{{") then (s% "}}") + else (s% "⦄") + let openSym := if closeSym == (s% "}}") then (s% "{{") else (s% "⦃") + (symbolFn openSym ctx s).bindState fun s => + if s.hasError then s else + let s := s.popSyntax + (binderPrefixFn ctx s).bindState fun s => + if s.hasError then s else + (binderIdentsFn ctx s).bindState fun s => + if s.hasError then s else + bindPeek ctx s fun tok? s => + let sAfterTy := + if tokIsAtom (tok?) (s% ":") then + (symbolFn (s% ":") ctx s).bindState fun s => + let s := s.popSyntax + let s := s.pushSyntax (Syntax.mkNodeF SyntaxKindF.valuePrefix .snil) + withPrecFn 0 termRec ctx s + else + let s := s.pushSyntax (Syntax.mkNodeF SyntaxKindF.valuePrefix .snil) + s.pushSyntax (Syntax.mkNullNodeF .snil) + sAfterTy.bindState fun s => + if s.hasError then s else + (symbolFn closeSym ctx s).bindState fun s => + if s.hasError then s else + (s.popSyntax).mkNode SyntaxKindF.strictImplicitBinder iniSz + +/-- Parse an instance-implicit binder `[@[once] inst : Add α]` or `[@[borrowed] Add α]`. -/ +def instBinderFn (termRec : ParserFn) : ParserFn := fun ctx s => + s.bindState fun s => + let iniSz := s.stackSize + (symbolFn (s% "[") ctx s).bindState fun s => + if s.hasError then s else + let namedAttempt : ParserFn := fun c st => + (binderPrefixFn c st).bindState fun st => + if st.hasError then st else + (binderIdentFn c st).bindState fun st => + if st.hasError then st else + (symbolFn (s% ":") c st).bindState fun st => + if st.hasError then st else + let st := st.pushSyntax (Syntax.mkNodeF SyntaxKindF.valuePrefix .snil) + withPrecFn 0 termRec c st + let anonAttempt : ParserFn := fun c st => + (binderPrefixFn c st).bindState fun st => + if st.hasError then st else + let st := st.pushSyntax (Syntax.mkSimpleIdentF FName.anon) + let st := st.pushSyntax (Syntax.mkNodeF SyntaxKindF.valuePrefix .snil) + withPrecFn 0 termRec c st + (tryOrElseFn namedAttempt anonAttempt ctx s).bindState fun s => + if s.hasError then s else + (symbolFn (s% "]") ctx s).bindState fun s => + if s.hasError then s else + let bPref := s.stxStack.getD (iniSz + 1) + let idStx := s.stxStack.getD (iniSz + 2) + let (vPref, ty) := + if Nat.beq s.stackSize (iniSz + 7) then + (s.stxStack.getD (iniSz + 4), s.stxStack.getD (iniSz + 5)) + else + (s.stxStack.getD (iniSz + 3), s.stxStack.getD (iniSz + 4)) + let s := s.shrinkStack iniSz + s.pushSyntax (Syntax.mkNodeListF SyntaxKindF.instBinder [bPref, Syntax.mkNodeListF SyntaxKindF.nullKind [idStx], vPref, ty]) + +/-- Parse any bracketed binder `(...)`, `{...}`, `⦃...⦄`, `[...]`. -/ +def bracketedBinderFn (termRec : ParserFn) : ParserFn := fun ctx s => + bindPeek ctx s fun tok? s => + if tokIsAtom (tok?) (s% "(") then explicitBinderFn termRec ctx s + else if tokIsAtom (tok?) (s% "{") then implicitBinderFn termRec ctx s + else if tokIsAtom (tok?) (s% "⦃") || tokIsAtom (tok?) (s% "{{") then strictImplicitBinderFn termRec ctx s + else if tokIsAtom (tok?) (s% "[") then instBinderFn termRec ctx s + else +s.mkUnexpectedError (s% "expected binder") + +/-- Parse a `fun` / `forall` binder: either a bracketed binder or an unparenthesized identifier `x`. -/ +def simpleOrBracketedBinderFn (termRec : ParserFn) : ParserFn := fun ctx s => + bindPeek ctx s fun tok? s => + if tokIsAtom (tok?) (s% "(") || tokIsAtom (tok?) (s% "{") || tokIsAtom (tok?) (s% "⦃") || tokIsAtom (tok?) (s% "{{") || tokIsAtom (tok?) (s% "[") then + bracketedBinderFn termRec ctx s + else + let iniSz := s.stackSize + (binderIdentFn ctx s).bindState fun s => + if s.hasError then s else + let idStx := s.stxStack.back + let s := s.shrinkStack iniSz + let emptyPref := Syntax.mkNodeF SyntaxKindF.binderPrefix .snil + let emptyVPref := Syntax.mkNodeF SyntaxKindF.valuePrefix .snil + s.pushSyntax (Syntax.mkNodeListF SyntaxKindF.explicitBinder + [emptyPref, Syntax.mkNodeListF SyntaxKindF.nullKind [idStx], emptyVPref, Syntax.mkNullNodeF .snil]) + +/-- First-order zero-or-more `bracketedBinderFn` loop. -/ +def manyBracketedBinderLoop (termRec : ParserFn) (ctx : IxParserContext) (s : ParserState) : + Nat → ParserState + | 0 => s.mkUnexpectedError (s% "parser fuel exhausted") + | fuel + 1 => + let iniSz := s.stackSize + let iniPos := s.pos + let iniBytes := s.remBytes + let s' := bracketedBinderFn termRec ctx s + if s'.hasError then + if Nat.beq s'.pos iniPos then s'.restore iniSz iniPos iniBytes else s' + else if Nat.beq s'.pos iniPos then s' + else manyBracketedBinderLoop termRec ctx s' fuel + +def manyBracketedBinderFn (termRec : ParserFn) (ctx : IxParserContext) (s : ParserState) : ParserState := + let iniSz := s.stackSize + (manyBracketedBinderLoop termRec ctx s parseFuel).mkNode SyntaxKindF.nullKind iniSz + +def many1BracketedBinderFn (termRec : ParserFn) (ctx : IxParserContext) (s : ParserState) : ParserState := + let iniSz := s.stackSize + let s1 := bracketedBinderFn termRec ctx s + if s1.hasError then s1.mkNode SyntaxKindF.nullKind iniSz + else (manyBracketedBinderLoop termRec ctx s1 parseFuel).mkNode SyntaxKindF.nullKind iniSz + +/-- First-order zero-or-more `simpleOrBracketedBinderFn` loop. -/ +def manySimpleOrBracketedBinderLoop (termRec : ParserFn) (ctx : IxParserContext) (s : ParserState) : + Nat → ParserState + | 0 => s.mkUnexpectedError (s% "parser fuel exhausted") + | fuel + 1 => + let iniSz := s.stackSize + let iniPos := s.pos + let iniBytes := s.remBytes + let s' := simpleOrBracketedBinderFn termRec ctx s + if s'.hasError then + if Nat.beq s'.pos iniPos then s'.restore iniSz iniPos iniBytes else s' + else if Nat.beq s'.pos iniPos then s' + else manySimpleOrBracketedBinderLoop termRec ctx s' fuel + +def manySimpleOrBracketedBinderFn (termRec : ParserFn) (ctx : IxParserContext) (s : ParserState) : ParserState := + let iniSz := s.stackSize + (manySimpleOrBracketedBinderLoop termRec ctx s parseFuel).mkNode SyntaxKindF.nullKind iniSz + +def many1SimpleOrBracketedBinderFn (termRec : ParserFn) (ctx : IxParserContext) (s : ParserState) : ParserState := + let iniSz := s.stackSize + let s1 := simpleOrBracketedBinderFn termRec ctx s + if s1.hasError then s1.mkNode SyntaxKindF.nullKind iniSz + else (manySimpleOrBracketedBinderLoop termRec ctx s1 parseFuel).mkNode SyntaxKindF.nullKind iniSz + +/-- First-order comma-separated `withPrecFn 0 termRec` loop. -/ +def sepByTermCommaLoop (termRec : ParserFn) (allowTrailing : Bool) (ctx : IxParserContext) (s : ParserState) : + Nat → ParserState + | 0 => s.mkUnexpectedError (s% "parser fuel exhausted") + | fuel + 1 => + let sepIniSz := s.stackSize + let sepIniPos := s.pos + let sepIniBytes := s.remBytes + let sSep := symbolFn (s% ",") ctx s + if sSep.hasError then + if Nat.beq sSep.pos sepIniPos then sSep.restore sepIniSz sepIniPos sepIniBytes else sSep + else + let sAfterSep := sSep.shrinkStack sepIniSz + let pIniSz := sAfterSep.stackSize + let pIniPos := sAfterSep.pos + let pIniBytes := sAfterSep.remBytes + let sElem := withPrecFn 0 termRec ctx sAfterSep + if sElem.hasError then + if allowTrailing && Nat.beq sElem.pos pIniPos then + sElem.restore pIniSz pIniPos pIniBytes + else + sElem + else + sepByTermCommaLoop termRec allowTrailing ctx sElem fuel + +def sepBy1TermCommaFn (termRec : ParserFn) (allowTrailing : Bool) (ctx : IxParserContext) (s : ParserState) : ParserState := + let iniSz := s.stackSize + let s1 := withPrecFn 0 termRec ctx s + if s1.hasError then s1.mkNode SyntaxKindF.nullKind iniSz + else (sepByTermCommaLoop termRec allowTrailing ctx s1 parseFuel).mkNode SyntaxKindF.nullKind iniSz + +def sepByTermCommaFn (termRec : ParserFn) (allowTrailing : Bool) (ctx : IxParserContext) (s : ParserState) : ParserState := + let iniSz := s.stackSize + let iniPos := s.pos + let iniBytes := s.remBytes + let s1 := withPrecFn 0 termRec ctx s + if s1.hasError then + if Nat.beq s1.pos iniPos then (s1.restore iniSz iniPos iniBytes).mkNode SyntaxKindF.nullKind iniSz + else s1.mkNode SyntaxKindF.nullKind iniSz + else + (sepByTermCommaLoop termRec allowTrailing ctx s1 parseFuel).mkNode SyntaxKindF.nullKind iniSz + +/-- True if `tok?` starts a sibling `·` / `case` focus block (used to end a focused tactic sequence). -/ +def isFocusOrCaseToken (tok? : Option Stx) : Bool := + tokIsAtom tok? (s% "·") || tokIsAtom tok? (s% ".") || tokIsWord tok? (s% "case") + +/-- First-order `rcases` pattern atom and comma/bar loops. -/ +def sepByRcasesPatCommaLoop (patRec : ParserFn) + (ctx : IxParserContext) (s : ParserState) : Nat → ParserState + | 0 => s.mkUnexpectedError (s% "parser fuel exhausted") + | fuel + 1 => + let sepIniSz := s.stackSize + let sepIniPos := s.pos + let sepIniBytes := s.remBytes + let sSep := symbolFn (s% ",") ctx s + if sSep.hasError then + if Nat.beq sSep.pos sepIniPos then sSep.restore sepIniSz sepIniPos sepIniBytes else sSep + else + let sAfterSep := sSep.shrinkStack sepIniSz + let pIniSz := sAfterSep.stackSize + let pIniPos := sAfterSep.pos + let pIniBytes := sAfterSep.remBytes + let sElem := patRec ctx sAfterSep + if sElem.hasError then + if Nat.beq sElem.pos pIniPos then sElem.restore pIniSz pIniPos pIniBytes else sElem + else + sepByRcasesPatCommaLoop patRec ctx sElem fuel + +def rcasesPatAtomFn (patRec : ParserFn) (ctx : IxParserContext) (s : ParserState) : ParserState := + bindPeek ctx s fun tok? st => + let iniSz := st.stackSize + if tokIsAtom (tok?) (s% "_") then + (tokenFn ctx st).mkNode SyntaxKindF.rcasesPatWildcard iniSz + else if tokIsWord (tok?) (s% "rfl") || tokIsAtom (tok?) (s% "rfl") then + (tokenFn ctx st).mkNode SyntaxKindF.rcasesPatRfl iniSz + else if tokIsAtom (tok?) (s% "⟨") then + let st := symbolFn (s% "⟨") ctx st + if st.hasError then st else + let st := st.popSyntax + let eIniSz := st.stackSize + let eIniPos := st.pos + let eIniChars := st.remBytes + let st1 := patRec ctx st + let st := + if st1.hasError then + if Nat.beq st1.pos eIniPos then (st1.restore eIniSz eIniPos eIniChars).mkNode SyntaxKindF.nullKind eIniSz + else st1.mkNode SyntaxKindF.nullKind eIniSz + else + (sepByRcasesPatCommaLoop patRec ctx st1 parseFuel).mkNode SyntaxKindF.nullKind eIniSz + if st.hasError then st else + let st := symbolFn (s% "⟩") ctx st + if st.hasError then st else + (st.popSyntax).mkNode SyntaxKindF.rcasesPatTuple iniSz + else if tokIsAtom (tok?) (s% "(") then + let st := symbolFn (s% "(") ctx st + if st.hasError then st else + let st := st.popSyntax + let eIniSz := st.stackSize + let st1 := patRec ctx st + let st := + if st1.hasError then st1.mkNode SyntaxKindF.nullKind eIniSz + else (sepByRcasesPatCommaLoop patRec ctx st1 parseFuel).mkNode SyntaxKindF.nullKind eIniSz + if st.hasError then st else + let itemsNode := st.stxStack.back + let st := symbolFn (s% ")") ctx st + if st.hasError then st else + let st := st.shrinkStack iniSz + let items := Syntax.getArgs itemsNode + if items.size == 1 then st.pushSyntax (items.getD 0 .missing) + else st.pushSyntax (Syntax.mkNodeListF SyntaxKindF.rcasesPatTuple [itemsNode]) + else if tokIsIdent (tok?) then + (identFn ctx st).mkNode SyntaxKindF.rcasesPatIdent iniSz + else + st.mkUnexpectedError (s% "expected rcases pattern ('_', 'rfl', identifier, '⟨...⟩', or '(...)')") + +def sepByRcasesPatAltLoop (patRec : ParserFn) + (ctx : IxParserContext) (s : ParserState) : Nat → ParserState + | 0 => s.mkUnexpectedError (s% "parser fuel exhausted") + | fuel + 1 => + let sepIniSz := s.stackSize + let sepIniPos := s.pos + let sepIniBytes := s.remBytes + let sSep := symbolFn (s% "|") ctx s + if sSep.hasError then + if Nat.beq sSep.pos sepIniPos then sSep.restore sepIniSz sepIniPos sepIniBytes else sSep + else + let sAfterSep := sSep.shrinkStack sepIniSz + let sElem := rcasesPatAtomFn patRec ctx sAfterSep + if sElem.hasError then sElem + else sepByRcasesPatAltLoop patRec ctx sElem fuel + +/-- Parse a recursive `rcases` / `obtain` / `rintro` pattern (`rcasesPat`), + structurally recursive on `patFuel : Nat`. -/ +def rcasesPatStep (allowAlt : Bool) : Nat → ParserFn + | 0 => fun _ s => s.mkUnexpectedError (s% "parser fuel exhausted in rcases pattern") + | patFuel + 1 => fun ctx s => + let patRec := rcasesPatStep true patFuel + if !allowAlt then + rcasesPatAtomFn patRec ctx s + else + let iniSz := s.stackSize + let s1 := rcasesPatAtomFn patRec ctx s + let s := + if s1.hasError then s1.mkNode SyntaxKindF.nullKind iniSz + else (sepByRcasesPatAltLoop patRec ctx s1 parseFuel).mkNode SyntaxKindF.nullKind iniSz + if s.hasError then s else + let altsNode := s.stxStack.back + let alts := Syntax.getArgs altsNode + if alts.size == 1 then + let s := s.shrinkStack iniSz + s.pushSyntax (alts.getD 0 .missing) + else + s.mkNode SyntaxKindF.rcasesPatAlt iniSz + +/-- Parse a single `calc` step (`lhs op rhs := proof` or `_ op rhs := proof`). + Produces `SyntaxKindF.calcStep #[relTerm, ":=", proofTerm]`, where `relTerm` is + a `SyntaxKindF.binOpTerm #[lhsOrHole, opAtom, rhs]`. -/ +def calcStepFn (termRec : ParserFn) (isFirst : Bool) : ParserFn := fun ctx s => + let term0 := withPrecFn 0 termRec + let iniSz := s.stackSize + bindPeek ctx s fun tok? s => + match tok? with + | none => s.mkUnexpectedError (s% "end of calc block") + | some tok => + let startsWithUnderscore := + if stxIsAtom (tok) (s% "_") then true + else false + if !isFirst && !hasLeadingNewline tok && !startsWithUnderscore then + s.mkUnexpectedError (s% "end of calc block") + else + let parseRel : ParserFn := fun c st => + if startsWithUnderscore then + let relSz := st.stackSize + let hSz := st.stackSize + (symbolFn (s% "_") c st).bindState fun st => + let st := st.mkNode SyntaxKindF.holeTerm hSz + bindPeek c st fun opTok? st => + match opTok? with + | some (.atom _ opSym) => + if opSym == (s% ":=") then + st.mkUnexpectedError (s% "expected relation operator after '_' in calc step") + else + (tokenFn c st).bindState fun st => + (withPrecFn 51 termRec c st).bindState fun st => + if st.hasError then st else + st.mkNode SyntaxKindF.binOpTerm relSz + | _ => + st.mkUnexpectedError (s% "expected relation operator after '_' in calc step") + else + term0 c st + (parseRel ctx s).bindState fun s => + if s.hasError then s else + (symbolFn (s% ":=") ctx s).bindState fun s => + if s.hasError then s else + (term0 ctx s).bindState fun s => + if s.hasError then s else + s.mkNode SyntaxKindF.calcStep iniSz + +/-- First-order zero-or-more `calcStepFn termRec false` loop. -/ +def manyCalcStepLoop (termRec : ParserFn) (ctx : IxParserContext) (s : ParserState) : Nat → ParserState + | 0 => s.mkUnexpectedError (s% "parser fuel exhausted") + | fuel + 1 => + let iniSz := s.stackSize + let iniPos := s.pos + let iniBytes := s.remBytes + let s' := calcStepFn termRec false ctx s + if s'.hasError then + if Nat.beq s'.pos iniPos then s'.restore iniSz iniPos iniBytes else s' + else if Nat.beq s'.pos iniPos then s' + else manyCalcStepLoop termRec ctx s' fuel + +/-- Parse one or more `calc` steps into a `nullKind` array node. -/ +def calcStepsFn (termRec : ParserFn) : ParserFn := fun ctx s => + let iniSz := s.stackSize + let s := calcStepFn termRec true ctx s + if s.hasError then s else + let s := manyCalcStepLoop termRec ctx s parseFuel + s.mkNode SyntaxKindF.nullKind iniSz + +/-- Extract the surface string of a token (`.atom` or single-component `.ident`) for notation matching. -/ +def tokenText : Stx → Sym + | .atom _ s => s + | .ident _ _ (.str .anon s) => s + | _ => (s% "") + +/-- Match a sequence of `NotationItem`s after the trigger token, accumulating captured variable `Syntax` nodes. -/ +def matchNotationItems (termRec : ParserFn) : + List NotationItem → List Stx → IxParserContext → ParserState → Option (List Stx × ParserState) + | [], revArgs, _, s => some (revArgs.reverse, s) + | .sym expected :: rest, revArgs, ctx, s => + bindPeek ctx s fun tok? s => + match tok? with + | some tok => + if tokenText tok == expected then + let s := tokenFn ctx s + if s.hasError then none + else + let s := s.popSyntax + matchNotationItems termRec rest revArgs ctx s + else none + | none => none + | .var _ varPrec :: rest, revArgs, ctx, s => + let iniSz := s.stackSize + let s' := withPrecFn varPrec termRec ctx s + if s'.hasError then none + else + let argStx := s'.stxStack.back + let s' := s'.shrinkStack iniSz + matchNotationItems termRec rest (argStx :: revArgs) ctx s' + +/-- Try matching leading `NotationRule`s whose first item is `.sym firstSym` matching `tokText`. -/ +def tryLeadNotationRules (termRec : ParserFn) (tokText : Sym) : + List NotationRule → IxParserContext → ParserState → Option ParserState + | [], _, _ => none + | rule :: rest, ctx, s => + match rule.items with + | .sym firstSym :: remItems => + if firstSym == tokText then + let iniSz := s.stackSize + let iniPos := s.pos + let iniBytes := s.remBytes + let s1 := (tokenFn ctx s).popSyntax + match matchNotationItems termRec remItems [] ctx s1 with + | some (capturedArgs, s2) => + let nodeArgs := Syntax.mkSimpleIdentF rule.ruleName :: capturedArgs + let callNode := Syntax.mkNodeListF SyntaxKindF.macroCall nodeArgs + some (s2.pushSyntax callNode) + | none => + tryLeadNotationRules termRec tokText rest ctx (s.restore iniSz iniPos iniBytes) + else + tryLeadNotationRules termRec tokText rest ctx s + | _ => + tryLeadNotationRules termRec tokText rest ctx s + +/-- Try matching trailing `NotationRule`s whose items start with `.var _ :: .sym secondSym :: remItems`. -/ +def tryTrailNotationRules (termRec : ParserFn) (tokText : Sym) : + List NotationRule → IxParserContext → ParserState → Option ParserState + | [], _, _ => none + | rule :: rest, ctx, s => + match rule.items with + | .var _ _ :: .sym secondSym :: remItems => + if Nat.ble ctx.prec rule.prec && secondSym == tokText then + let iniSz := s.stackSize + let iniPos := s.pos + let iniBytes := s.remBytes + let lhsStx := s.stxStack.back + let s1 := (tokenFn ctx s).popSyntax + match matchNotationItems termRec remItems [lhsStx] ctx s1 with + | some (capturedArgs, s2) => + let s2 := s2.shrinkStack (iniSz - 1) + let nodeArgs := Syntax.mkSimpleIdentF rule.ruleName :: capturedArgs + let callNode := Syntax.mkNodeListF SyntaxKindF.macroCall nodeArgs + some (s2.pushSyntax callNode) + | none => + tryTrailNotationRules termRec tokText rest ctx (s.restore iniSz iniPos iniBytes) + else + tryTrailNotationRules termRec tokText rest ctx s + | _ => + tryTrailNotationRules termRec tokText rest ctx s + +/-- First-order helper loops for tactics (zero closures in `manyLoop`/`sepByLoop`). -/ +def sameLineRcasesPatAtomFn (ctx : IxParserContext) (s : ParserState) : ParserState := + let (t?, s) := peekToken ctx s + match t? with + | some tok => + if hasLeadingNewline tok then s.mkUnexpectedError (s% "newline after rintro pattern") + else rcasesPatStep false 32 ctx s + | none => s.mkUnexpectedError (s% "end of rintro pattern") + +def manySameLineRcasesPatAtomLoop (ctx : IxParserContext) (s : ParserState) : Nat → ParserState + | 0 => s.mkUnexpectedError (s% "parser fuel exhausted") + | fuel + 1 => + let iniSz := s.stackSize + let iniPos := s.pos + let iniBytes := s.remBytes + let s' := sameLineRcasesPatAtomFn ctx s + if s'.hasError then + if Nat.beq s'.pos iniPos then s'.restore iniSz iniPos iniBytes else s' + else if Nat.beq s'.pos iniPos then s' + else manySameLineRcasesPatAtomLoop ctx s' fuel + +def manySameLineRcasesPatAtomFn (ctx : IxParserContext) (s : ParserState) : ParserState := + let iniSz := s.stackSize + (manySameLineRcasesPatAtomLoop ctx s parseFuel).mkNode SyntaxKindF.nullKind iniSz + +def sameLineTermArgFn (termRec : ParserFn) (ctx : IxParserContext) (s : ParserState) : ParserState := + let (t?, s) := peekToken ctx s + match t? with + | some tok => + if hasLeadingNewline tok then s.mkUnexpectedError (s% "newline before tactic argument") + else withPrecFn argPrec termRec ctx s + | none => s.mkUnexpectedError (s% "end of tactic argument") + +def manySameLineTermArgLoop (termRec : ParserFn) (ctx : IxParserContext) (s : ParserState) : Nat → ParserState + | 0 => s.mkUnexpectedError (s% "parser fuel exhausted") + | fuel + 1 => + let iniSz := s.stackSize + let iniPos := s.pos + let iniBytes := s.remBytes + let s' := sameLineTermArgFn termRec ctx s + if s'.hasError then + if Nat.beq s'.pos iniPos then s'.restore iniSz iniPos iniBytes else s' + else if Nat.beq s'.pos iniPos then s' + else manySameLineTermArgLoop termRec ctx s' fuel + +def manySameLineTermArgFn (termRec : ParserFn) (ctx : IxParserContext) (s : ParserState) : ParserState := + let iniSz := s.stackSize + (manySameLineTermArgLoop termRec ctx s 1099511627776).mkNode SyntaxKindF.nullKind iniSz + +def tacticRwRuleFn (termRec : ParserFn) (ctx : IxParserContext) (s : ParserState) : ParserState := + let rSz := s.stackSize + let s := optionalFn (orelseFn (symbolFn (s% "←")) (symbolFn (s% "<-"))) ctx s + let s := withPrecFn 0 termRec ctx s + s.mkNode SyntaxKindF.tacticRwRule rSz + +def sepByRwRuleCommaLoop (termRec : ParserFn) (ctx : IxParserContext) (s : ParserState) : Nat → ParserState + | 0 => s.mkUnexpectedError (s% "parser fuel exhausted") + | fuel + 1 => + let sepIniSz := s.stackSize + let sepIniPos := s.pos + let sepIniBytes := s.remBytes + let sSep := symbolFn (s% ",") ctx s + if sSep.hasError then + if Nat.beq sSep.pos sepIniPos then sSep.restore sepIniSz sepIniPos sepIniBytes else sSep + else + let sAfterSep := sSep.shrinkStack sepIniSz + let sElem := tacticRwRuleFn termRec ctx sAfterSep + if sElem.hasError then sElem + else sepByRwRuleCommaLoop termRec ctx sElem fuel + +def sepBy1RwRuleCommaFn (termRec : ParserFn) (ctx : IxParserContext) (s : ParserState) : ParserState := + let iniSz := s.stackSize + let s1 := tacticRwRuleFn termRec ctx s + if s1.hasError then s1.mkNode SyntaxKindF.nullKind iniSz + else (sepByRwRuleCommaLoop termRec ctx s1 parseFuel).mkNode SyntaxKindF.nullKind iniSz + +def sepByRwRuleCommaFn (termRec : ParserFn) (ctx : IxParserContext) (s : ParserState) : ParserState := + let iniSz := s.stackSize + let iniPos := s.pos + let iniBytes := s.remBytes + let s1 := tacticRwRuleFn termRec ctx s + if s1.hasError then + if Nat.beq s1.pos iniPos then (s1.restore iniSz iniPos iniBytes).mkNode SyntaxKindF.nullKind iniSz + else s1.mkNode SyntaxKindF.nullKind iniSz + else + (sepByRwRuleCommaLoop termRec ctx s1 parseFuel).mkNode SyntaxKindF.nullKind iniSz + +def tacticFirstBranchFn (tacticRec : Bool → Bool → ParserFn) (ctx : IxParserContext) (s : ParserState) : ParserState := + let st := symbolFn (s% "|") ctx s + if st.hasError then st else + tacticRec false false ctx st.popSyntax + +def manyTacticFirstBranchLoop (tacticRec : Bool → Bool → ParserFn) (ctx : IxParserContext) (s : ParserState) : + Nat → ParserState + | 0 => s.mkUnexpectedError (s% "parser fuel exhausted") + | fuel + 1 => + let iniSz := s.stackSize + let iniPos := s.pos + let iniBytes := s.remBytes + let s' := tacticFirstBranchFn tacticRec ctx s + if s'.hasError then + if Nat.beq s'.pos iniPos then s'.restore iniSz iniPos iniBytes else s' + else if Nat.beq s'.pos iniPos then s' + else manyTacticFirstBranchLoop tacticRec ctx s' fuel + +def many1TacticFirstBranchFn (tacticRec : Bool → Bool → ParserFn) (ctx : IxParserContext) (s : ParserState) : ParserState := + let iniSz := s.stackSize + let s1 := tacticFirstBranchFn tacticRec ctx s + if s1.hasError then s1.mkNode SyntaxKindF.nullKind iniSz + else (manyTacticFirstBranchLoop tacticRec ctx s1 parseFuel).mkNode SyntaxKindF.nullKind iniSz + +def tacticAltFn (tacticRec : Bool → Bool → ParserFn) (ctx : IxParserContext) (s : ParserState) : ParserState := + let iniSz := s.stackSize + let s := symbolFn (s% "|") ctx s + if s.hasError then s else + let s := identFn ctx s + let s := manyBinderIdentFn ctx s + let s := orelseFn (symbolFn (s% "=>")) (symbolFn (s% "↦")) ctx s + let s := tacticRec false false ctx s + s.mkNode SyntaxKindF.tacticAlt iniSz + +def manyTacticAltLoop (tacticRec : Bool → Bool → ParserFn) (ctx : IxParserContext) (s : ParserState) : + Nat → ParserState + | 0 => s.mkUnexpectedError (s% "parser fuel exhausted") + | fuel + 1 => + let iniSz := s.stackSize + let iniPos := s.pos + let iniBytes := s.remBytes + let s' := tacticAltFn tacticRec ctx s + if s'.hasError then + if Nat.beq s'.pos iniPos then s'.restore iniSz iniPos iniBytes else s' + else if Nat.beq s'.pos iniPos then s' + else manyTacticAltLoop tacticRec ctx s' fuel + +def manyTacticAltFn (tacticRec : Bool → Bool → ParserFn) (ctx : IxParserContext) (s : ParserState) : ParserState := + let iniSz := s.stackSize + (manyTacticAltLoop tacticRec ctx s parseFuel).mkNode SyntaxKindF.nullKind iniSz + +/-- Helper 1 for `tacticSeqCoreStep`: rewriting/simplification/binding/case tactics. -/ +def tacticCoreBinders (termRec : ParserFn) (tacticRec : Bool → Bool → ParserFn) + (stopAtFocus : Bool) (kw : Sym) (iniSz : Nat) (ctx : IxParserContext) (s : ParserState) : ParserState := + let term0 := withPrecFn 0 termRec + let termArg := withPrecFn argPrec termRec + if Sym.beq (kw) (s% "rw") || Sym.beq (kw) (s% "rewrite") then + let s := tokenFn ctx s + let s := symbolFn (s% "[") ctx s + let s := sepBy1RwRuleCommaFn termRec ctx s + let s := symbolFn (s% "]") ctx s + let s := optionalFn (seqFn (nonReservedSymbolFn (s% "at")) identFn) ctx s + s.mkNode SyntaxKindF.tacticRw iniSz + else if Sym.beq (kw) (s% "simp") then + let s := tokenFn ctx s + let s := optionalFn (nonReservedSymbolFn (s% "only")) ctx s + let s := optionalFn (fun c st => + let st := symbolFn (s% "[") c st + if st.hasError then st else + let st := sepByRwRuleCommaFn termRec c st + if st.hasError then st else + symbolFn (s% "]") c st) ctx s + let s := optionalFn (seqFn (nonReservedSymbolFn (s% "at")) identFn) ctx s + s.mkNode SyntaxKindF.tacticSimp iniSz + else if Sym.beq (kw) (s% "dsimp") then + let s := tokenFn ctx s + let s := optionalFn (nonReservedSymbolFn (s% "only")) ctx s + let s := optionalFn (fun c st => + let st := symbolFn (s% "[") c st + if st.hasError then st else + let st := sepByRwRuleCommaFn termRec c st + if st.hasError then st else + symbolFn (s% "]") c st) ctx s + let s := optionalFn (seqFn (nonReservedSymbolFn (s% "at")) identFn) ctx s + s.mkNode SyntaxKindF.tacticDSimp iniSz + else if Sym.beq (kw) (s% "have") then + let s := tokenFn ctx s + let (tNext?, s) := peekToken ctx s + let s := + if tokIsAtom (tNext?) (s% ":") || tokIsAtom (tNext?) (s% ":=") then + s.pushSyntax (Syntax.mkSimpleIdentF (FName.simple (s% "this"))) + else + binderIdentFn ctx s + let s := optionalFn (seqFn (symbolFn (s% ":")) term0) ctx s + let s := symbolFn (s% ":=") ctx s + let s := term0 ctx s + s.mkNode SyntaxKindF.tacticHave iniSz + else if Sym.beq (kw) (s% "let") then + let s := tokenFn ctx s + let (tNext?, s) := peekToken ctx s + let s := + if tokIsAtom (tNext?) (s% ":") || tokIsAtom (tNext?) (s% ":=") then + s.pushSyntax (Syntax.mkSimpleIdentF (FName.simple (s% "this"))) + else + binderIdentFn ctx s + let s := optionalFn (seqFn (symbolFn (s% ":")) term0) ctx s + let s := symbolFn (s% ":=") ctx s + let s := term0 ctx s + s.mkNode SyntaxKindF.tacticLet iniSz + else if Sym.beq (kw) (s% "suffices") then + let s := tokenFn ctx s + let namedSuff : ParserFn := fun c st => + (binderIdentFn c st).bindState fun st => + if st.hasError then st else + symbolFn (s% ":") c st + let anonSuff : ParserFn := fun c st => + let st := st.pushSyntax (Syntax.mkSimpleIdentF (FName.simple (s% "this"))) + let (t?, st) := peekToken c st + if tokIsAtom (t?) (s% ":") then tokenFn c st + else st.pushSyntax (Syntax.mkSimpleAtomF (s% ":")) + let s := tryOrElseFn namedSuff anonSuff ctx s + let s := term0 ctx s + if s.hasError then s else + let (modeTok?, s) := peekToken ctx s + let s := + if tokIsAtom (modeTok?) (s% "by") || tokIsWord (modeTok?) (s% "by") then + let s := tokenFn ctx s + tacticRec stopAtFocus true ctx s + else if tokIsWord (modeTok?) (s% "from") || tokIsAtom (modeTok?) (s% "from") then + let s := tokenFn ctx s + term0 ctx s + else + s.mkUnexpectedError (s% "expected 'by' or 'from' in 'suffices' tactic") + s.mkNode SyntaxKindF.tacticSuffices iniSz + else if Sym.beq (kw) (s% "specialize") then + let s := tokenFn ctx s + let s := identFn ctx s + let s := manySameLineTermArgFn termRec ctx s + s.mkNode SyntaxKindF.tacticSpecialize iniSz + else if Sym.beq (kw) (s% "clear") then + let s := tokenFn ctx s + let s := many1SameLineIdentFn ctx s + s.mkNode SyntaxKindF.tacticClear iniSz + else if Sym.beq (kw) (s% "revert") then + let s := tokenFn ctx s + let s := many1SameLineIdentFn ctx s + s.mkNode SyntaxKindF.tacticRevert iniSz + else if Sym.beq (kw) (s% "generalize") then + let s := tokenFn ctx s + let namedGen : ParserFn := fun c st => + (identFn c st).bindState fun st => + if st.hasError then st else + (symbolFn (s% ":") c st).bindState fun st => + if st.hasError then st else + st.popSyntax + let unnamedGen : ParserFn := fun _ st => + st.pushSyntax (Syntax.mkSimpleIdentF FName.anon) + let s := tryOrElseFn namedGen unnamedGen ctx s + let s := withPrecFn 51 termRec ctx s + let s := symbolFn (s% "=") ctx s + let s := identFn ctx s + s.mkNode SyntaxKindF.tacticGeneralize iniSz + else if Sym.beq (kw) (s% "subst") then + let s := tokenFn ctx s + let s := many1SameLineIdentFn ctx s + s.mkNode SyntaxKindF.tacticSubst iniSz + else if Sym.beq (kw) (s% "by_cases") then + let s := tokenFn ctx s + let namedByCases : ParserFn := fun c st => + (identFn c st).bindState fun st => + if st.hasError then st else + (symbolFn (s% ":") c st).bindState fun st => + if st.hasError then st else + let st := st.popSyntax + term0 c st + let unnamedByCases : ParserFn := fun c st => + let st := st.pushSyntax (Syntax.mkSimpleIdentF (FName.simple (s% "h"))) + term0 c st + let s := tryOrElseFn namedByCases unnamedByCases ctx s + s.mkNode SyntaxKindF.tacticByCases iniSz + else if Sym.beq (kw) (s% "by_contra") || Sym.beq (kw) (s% "by_contradiction") then + let s := tokenFn ctx s + let (nextT?, s) := peekToken ctx s + let s := match nextT? with + | some tok => + if !hasLeadingNewline tok then + if stxIsIdent (tok) || stxIsAtom (tok) (s% "_") then binderIdentFn ctx s + else s.pushSyntax (Syntax.mkSimpleIdentF (FName.simple (s% "this"))) + else + s.pushSyntax (Syntax.mkSimpleIdentF (FName.simple (s% "this"))) + | none => + s.pushSyntax (Syntax.mkSimpleIdentF (FName.simple (s% "this"))) + s.mkNode SyntaxKindF.tacticByContra iniSz + else if Sym.beq (kw) (s% "cases") then + let s := tokenFn ctx s + let s := termArg ctx s + let s := optionalFn (seqFn (symbolFn (s% "with")) (manyTacticAltFn tacticRec)) ctx s + s.mkNode SyntaxKindF.tacticCases iniSz + else if Sym.beq (kw) (s% "induction") then + let s := tokenFn ctx s + let s := termArg ctx s + let s := optionalFn (seqFn (symbolFn (s% "with")) (manyTacticAltFn tacticRec)) ctx s + s.mkNode SyntaxKindF.tacticInduction iniSz + else + match tryLeadNotationRules termRec kw ctx.env.notations ctx s with + | some sHit => sHit + | none => s.mkUnexpectedError (s% "expected tactic") + +/-- Helper 2 for `tacticSeqCoreStep`: simple term-less and single-term tactics. -/ +def tacticCoreSimple (termRec : ParserFn) (tacticRec : Bool → Bool → ParserFn) + (stopAtFocus : Bool) (kw : Sym) (iniSz : Nat) (ctx : IxParserContext) (s : ParserState) : ParserState := + let term0 := withPrecFn 0 termRec + let sameLineTerm0 : ParserFn := fun c st => + let (t?, st) := peekToken c st + match t? with + | some tok => + if hasLeadingNewline tok then st.mkUnexpectedError (s% "newline before optional tactic term") + else term0 c st + | none => st.mkUnexpectedError (s% "end of optional tactic term") + if Sym.beq (kw) (s% "exact") then + let s := tokenFn ctx s + let s := term0 ctx s + s.mkNode SyntaxKindF.tacticExact iniSz + else if Sym.beq (kw) (s% "apply") then + let s := tokenFn ctx s + let s := term0 ctx s + s.mkNode SyntaxKindF.tacticApply iniSz + else if Sym.beq (kw) (s% "refine") then + let s := tokenFn ctx s + let s := term0 ctx s + s.mkNode SyntaxKindF.tacticRefine iniSz + else if Sym.beq (kw) (s% "rfl") then + (tokenFn ctx s).mkNode SyntaxKindF.tacticRfl iniSz + else if Sym.beq (kw) (s% "decide") || Sym.beq (kw) (s% "native_decide") then + (tokenFn ctx s).mkNode SyntaxKindF.tacticDecide iniSz + else if Sym.beq (kw) (s% "norm_num") then + let s := tokenFn ctx s + let s := optionalFn (seqFn (nonReservedSymbolFn (s% "at")) identFn) ctx s + s.mkNode SyntaxKindF.tacticNormNum iniSz + else if Sym.beq (kw) (s% "ring") || Sym.beq (kw) (s% "ring_nf") then + (tokenFn ctx s).mkNode SyntaxKindF.tacticRing iniSz + else if Sym.beq (kw) (s% "omega") || Sym.beq (kw) (s% "linarith") then + (tokenFn ctx s).mkNode SyntaxKindF.tacticOmega iniSz + else if Sym.beq (kw) (s% "assumption") then + (tokenFn ctx s).mkNode SyntaxKindF.tacticAssumption iniSz + else if Sym.beq (kw) (s% "trivial") then + (tokenFn ctx s).mkNode SyntaxKindF.tacticTrivial iniSz + else if Sym.beq (kw) (s% "contradiction") then + (tokenFn ctx s).mkNode SyntaxKindF.tacticContradiction iniSz + else if Sym.beq (kw) (s% "exfalso") then + (tokenFn ctx s).mkNode SyntaxKindF.tacticExfalso iniSz + else if Sym.beq (kw) (s% "done") then + (tokenFn ctx s).mkNode SyntaxKindF.tacticDone iniSz + else if Sym.beq (kw) (s% "constructor") then + (tokenFn ctx s).mkNode SyntaxKindF.tacticConstructor iniSz + else if Sym.beq (kw) (s% "left") then + (tokenFn ctx s).mkNode SyntaxKindF.tacticLeft iniSz + else if Sym.beq (kw) (s% "right") then + (tokenFn ctx s).mkNode SyntaxKindF.tacticRight iniSz + else if Sym.beq (kw) (s% "split") then + (tokenFn ctx s).mkNode SyntaxKindF.tacticSplit iniSz + else if Sym.beq (kw) (s% "exists") || Sym.beq (kw) (s% "use") then + let s := tokenFn ctx s + let s := sepBy1TermCommaFn termRec false ctx s + s.mkNode SyntaxKindF.tacticExists iniSz + else if Sym.beq (kw) (s% "symm") || Sym.beq (kw) (s% "symmetry") then + (tokenFn ctx s).mkNode SyntaxKindF.tacticSymm iniSz + else if Sym.beq (kw) (s% "trans") || Sym.beq (kw) (s% "transitivity") then + let s := tokenFn ctx s + let s := optionalFn sameLineTerm0 ctx s + s.mkNode SyntaxKindF.tacticTrans iniSz + else if Sym.beq (kw) (s% "congr") then + (tokenFn ctx s).mkNode SyntaxKindF.tacticCongr iniSz + else if Sym.beq (kw) (s% "funext") then + let s := tokenFn ctx s + let s := manySameLineBinderIdentFn ctx s + s.mkNode SyntaxKindF.tacticFunext iniSz + else if Sym.beq (kw) (s% "ext") then + let s := tokenFn ctx s + let s := manySameLineBinderIdentFn ctx s + s.mkNode SyntaxKindF.tacticExt iniSz + else if Sym.beq (kw) (s% "sorry") || Sym.beq (kw) (s% "admit") then + (tokenFn ctx s).mkNode SyntaxKindF.tacticSorry iniSz + else if Sym.beq (kw) (s% "show") then + let s := tokenFn ctx s + let s := term0 ctx s + s.mkNode SyntaxKindF.tacticShow iniSz + else if Sym.beq (kw) (s% "change") then + let s := tokenFn ctx s + let s := term0 ctx s + s.mkNode SyntaxKindF.tacticChange iniSz + else + tacticCoreBinders termRec tacticRec stopAtFocus kw iniSz ctx s + +/-- Non-recursive single-step body of `tacticSeqCore`, split into small helpers for low circuit width. -/ +def tacticSeqCoreStep (termRec : ParserFn) (tacticRec : Bool → Bool → ParserFn) + (stopAtFocus : Bool) : ParserFn := fun ctx s => + let term0 := withPrecFn 0 termRec + let oneTactic : ParserFn := fun ctx s => + let (tok?, s) := peekToken ctx s + let iniSz := s.stackSize + match tok? with + | some (.ident _ _ (.str .anon kw)) | some (.atom _ kw) => + if Sym.beq kw (s% "(") then + let s := tokenFn ctx s + let s := tacticRec false false ctx s + let s := symbolFn (s% ")") ctx s + s.mkNode SyntaxKindF.tacticParen iniSz + else if Sym.beq kw (s% "·") || Sym.beq kw (s% ".") then + let s := tokenFn ctx s + let s := tacticRec true false ctx s + s.mkNode SyntaxKindF.tacticFocus iniSz + else if Sym.beq (kw) (s% "case") then + let s := tokenFn ctx s + let s := identFn ctx s + let s := manySameLineBinderIdentFn ctx s + let s := orelseFn (symbolFn (s% "=>")) (symbolFn (s% "↦")) ctx s + let s := tacticRec true false ctx s + s.mkNode SyntaxKindF.tacticCase iniSz + else if Sym.beq (kw) (s% "first") then + let s := tokenFn ctx s + let s := many1TacticFirstBranchFn tacticRec ctx s + s.mkNode SyntaxKindF.tacticFirst iniSz + else if Sym.beq (kw) (s% "try") then + let s := tokenFn ctx s + let s := tacticRec stopAtFocus true ctx s + s.mkNode SyntaxKindF.tacticTry iniSz + else if Sym.beq (kw) (s% "repeat") then + let s := tokenFn ctx s + let s := tacticRec stopAtFocus true ctx s + s.mkNode SyntaxKindF.tacticRepeat iniSz + else if Sym.beq (kw) (s% "all_goals") then + let s := tokenFn ctx s + let s := tacticRec stopAtFocus true ctx s + s.mkNode SyntaxKindF.tacticAllGoals iniSz + else if Sym.beq (kw) (s% "any_goals") then + let s := tokenFn ctx s + let s := tacticRec stopAtFocus true ctx s + s.mkNode SyntaxKindF.tacticAnyGoals iniSz + else if Sym.beq (kw) (s% "intro") || Sym.beq (kw) (s% "intros") then + let s := tokenFn ctx s + let s := manySameLineBinderIdentFn ctx s + s.mkNode SyntaxKindF.tacticIntro iniSz + else if Sym.beq (kw) (s% "rintro") || Sym.beq (kw) (s% "rintros") then + let s := tokenFn ctx s + let s := manySameLineRcasesPatAtomFn ctx s + let s := optionalFn (seqFn (symbolFn (s% ":")) term0) ctx s + s.mkNode SyntaxKindF.tacticRintro iniSz + else if Sym.beq (kw) (s% "rcases") then + let s := tokenFn ctx s + let namedTarget : ParserFn := fun c st => + (identFn c st).bindState fun st => + if st.hasError then st else + (symbolFn (s% ":") c st).bindState fun st => + if st.hasError then st else + let st := st.popSyntax + term0 c st + let unnamedTarget : ParserFn := fun c st => + let st := st.pushSyntax (Syntax.mkSimpleIdentF FName.anon) + term0 c st + let s := tryOrElseFn namedTarget unnamedTarget ctx s + let s := optionalFn (seqFn (symbolFn (s% "with")) (rcasesPatStep true 32)) ctx s + s.mkNode SyntaxKindF.tacticRcases iniSz + else if Sym.beq (kw) (s% "obtain") then + let s := tokenFn ctx s + let (tNext?, s) := peekToken ctx s + let s := + if tokIsAtom (tNext?) (s% ":") || tokIsAtom (tNext?) (s% ":=") then + s.pushSyntax (Syntax.mkNodeListF SyntaxKindF.rcasesPatIdent [Syntax.mkSimpleIdentF (FName.simple (s% "this"))]) + else + rcasesPatStep true 32 ctx s + let s := optionalFn (seqFn (symbolFn (s% ":")) term0) ctx s + let s := symbolFn (s% ":=") ctx s + let s := term0 ctx s + s.mkNode SyntaxKindF.tacticObtain iniSz + else if Sym.beq (kw) (s% "calc") then + let s := tokenFn ctx s + let s := calcStepsFn termRec ctx s + s.mkNode SyntaxKindF.tacticCalc iniSz + else + tacticCoreSimple termRec tacticRec stopAtFocus kw iniSz ctx s + | _ => + s.mkUnexpectedError (s% "expected tactic") + let iniSz := s.stackSize + let s := oneTactic ctx s + if s.hasError then s else + let (nextTok?, s) := peekToken ctx s + if tokIsAtom (nextTok?) (s% "<;>") then + let s := tokenFn ctx s + let s := tacticRec stopAtFocus true ctx s + s.mkNode SyntaxKindF.tacticAndThen iniSz + else +s + +def manyTacticStepLoop (termRec : ParserFn) (tacticRec : Bool → Bool → ParserFn) + (stopAtFocus : Bool) (ctx : IxParserContext) (s : ParserState) : Nat → ParserState + | 0 => s.mkUnexpectedError (s% "parser fuel exhausted") + | fuel + 1 => + let iniSz := s.stackSize + let iniPos := s.pos + let iniBytes := s.remBytes + let st := optionalFn (symbolFn (s% ";")) ctx s + let st := st.popSyntax + let s' := + if stopAtFocus then + let (t?, st) := peekToken ctx st + if isFocusOrCaseToken t? then st.mkUnexpectedError (s% "end of focused tactic block") + else tacticSeqCoreStep termRec tacticRec stopAtFocus ctx st + else + tacticSeqCoreStep termRec tacticRec stopAtFocus ctx st + if s'.hasError then + if Nat.beq s'.pos iniPos then s'.restore iniSz iniPos iniBytes else s' + else if Nat.beq s'.pos iniPos then s' + else manyTacticStepLoop termRec tacticRec stopAtFocus ctx s' fuel + +def tacticSeqCoreBody (termRec : ParserFn) (tacticRec : Bool → Bool → ParserFn) + (stopAtFocus : Bool) (singleStep : Bool) : ParserFn := + if singleStep then + tacticSeqCoreStep termRec tacticRec stopAtFocus + else + fun ctx s => + let iniSz := s.stackSize + let s := tacticSeqCoreStep termRec tacticRec stopAtFocus ctx s + if s.hasError then s else + let s := manyTacticStepLoop termRec tacticRec stopAtFocus ctx s parseFuel + s.mkNode SyntaxKindF.tacticSeq iniSz + +/-- Parse a tactic sequence or single combinator step, structurally recursive on `fuel : Nat`. -/ +def tacticSeqCore (termRec : ParserFn) (stopAtFocus : Bool) (singleStep : Bool) : Nat → ParserFn + | 0 => fun _ s => s.mkUnexpectedError (s% "parser fuel exhausted in tactic") + | fuel + 1 => + tacticSeqCoreBody termRec (fun sf ss => tacticSeqCore termRec sf ss fuel) stopAtFocus singleStep + +/-- Parse a tactic sequence, structurally recursive on `fuel : Nat`. -/ +def tacticSeqStep (termRec : ParserFn) (fuel : Nat) : ParserFn := + tacticSeqCore termRec false false fuel + +/-- Parse a `| pat1, pat2 => rhs` branch of a `match` expression. -/ +def matchAltFn (termRec : ParserFn) : ParserFn := fun ctx s => + let iniSz := s.stackSize + let s := symbolFn (s% "|") ctx s + if s.hasError then s else + let s := sepBy1TermCommaFn termRec false ctx s + if s.hasError then s else + let s := orelseFn (symbolFn (s% "=>")) (symbolFn (s% "↦")) ctx s + if s.hasError then s else + let s := withPrecFn 0 termRec ctx s + s.mkNode SyntaxKindF.matchAlt iniSz + +/-- First-order zero-or-more `matchAltFn` loop. -/ +def manyMatchAltLoop (termRec : ParserFn) (ctx : IxParserContext) (s : ParserState) : Nat → ParserState + | 0 => s.mkUnexpectedError (s% "parser fuel exhausted") + | fuel + 1 => + let iniSz := s.stackSize + let iniPos := s.pos + let iniBytes := s.remBytes + let s' := matchAltFn termRec ctx s + if s'.hasError then + if Nat.beq s'.pos iniPos then s'.restore iniSz iniPos iniBytes else s' + else if Nat.beq s'.pos iniPos then s' + else manyMatchAltLoop termRec ctx s' fuel + +def many1MatchAltFn (termRec : ParserFn) (ctx : IxParserContext) (s : ParserState) : ParserState := + let iniSz := s.stackSize + let s1 := matchAltFn termRec ctx s + if s1.hasError then s1.mkNode SyntaxKindF.nullKind iniSz + else (manyMatchAltLoop termRec ctx s1 parseFuel).mkNode SyntaxKindF.nullKind iniSz + +/-- First-order comma-separated structure field assignment `field := val` loop. -/ +def structFieldAssignFn (termRec : ParserFn) (ctx : IxParserContext) (s : ParserState) : ParserState := + let fSz := s.stackSize + let s := identFn ctx s + let s := symbolFn (s% ":=") ctx s + let s := withPrecFn 0 termRec ctx s + s.mkNode SyntaxKindF.structFieldAssign fSz + +def sepByFieldAssignCommaLoop (termRec : ParserFn) (ctx : IxParserContext) (s : ParserState) : Nat → ParserState + | 0 => s.mkUnexpectedError (s% "parser fuel exhausted") + | fuel + 1 => + let sepIniSz := s.stackSize + let sepIniPos := s.pos + let sepIniBytes := s.remBytes + let sSep := symbolFn (s% ",") ctx s + if sSep.hasError then + if Nat.beq sSep.pos sepIniPos then sSep.restore sepIniSz sepIniPos sepIniBytes else sSep + else + let sAfterSep := sSep.shrinkStack sepIniSz + let pIniSz := sAfterSep.stackSize + let pIniPos := sAfterSep.pos + let pIniBytes := sAfterSep.remBytes + let sElem := structFieldAssignFn termRec ctx sAfterSep + if sElem.hasError then + if Nat.beq sElem.pos pIniPos then sElem.restore pIniSz pIniPos pIniBytes else sElem + else + sepByFieldAssignCommaLoop termRec ctx sElem fuel + +def sepByFieldAssignCommaFn (termRec : ParserFn) (ctx : IxParserContext) (s : ParserState) : ParserState := + let iniSz := s.stackSize + let iniPos := s.pos + let iniBytes := s.remBytes + let s1 := structFieldAssignFn termRec ctx s + if s1.hasError then + if Nat.beq s1.pos iniPos then (s1.restore iniSz iniPos iniBytes).mkNode SyntaxKindF.nullKind iniSz + else s1.mkNode SyntaxKindF.nullKind iniSz + else + (sepByFieldAssignCommaLoop termRec ctx s1 parseFuel).mkNode SyntaxKindF.nullKind iniSz + +/-- Attach `bVPref` and `bTy` to untyped `explicitBinder` nodes in a `∀ a b c : T, body` binder list. -/ +def attachTypeToBinders (bVPref bTy : Stx) : List Stx → List Stx + | [] => [] + | b :: bs => + let b' := match b with + | .node info k (.scons p0 (.scons p1 (.scons _ (.scons p3 .snil)))) => + if k == SyntaxKindF.explicitBinder && Syntax.isNone p3 then + .node info SyntaxKindF.explicitBinder (Stx.ofList [p0, p1, bVPref, bTy]) + else b + | _ => b + b' :: attachTypeToBinders bVPref bTy bs + +/-- Monomorphic helper: build `binOpTerm #[idStx, opTok, rhsStx]` for each id in `ids`. -/ +def mapBoundConds (opTok rhsStx : Stx) : List Stx → List Stx + | [] => [] + | idStx :: rest => + Syntax.mkNodeListF SyntaxKindF.binOpTerm [idStx, opTok, rhsStx] :: mapBoundConds opTok rhsStx rest + +/-- Extract any parenthesized bounded binder conditions `(x > 0)` from `binders`, + returning `(cleanedBinders, boundConds)`. -/ +def extractBinderBounds : List Stx → List Stx × List Stx + | [] => ([], []) + | b :: bs => + let (bs', restConds) := extractBinderBounds bs + match b with + | .node info k (.scons bPref (.scons idsNode (.scons vPref (.scons (.node _ bk (.scons (.atom _ tagSym) (.scons opTok (.scons rhsStx .snil)))) .snil)))) => + if k == SyntaxKindF.explicitBinder && bk == SyntaxKindF.binOpTerm && Sym.beq tagSym (s% "_bound") then + let bClean := .node info SyntaxKindF.explicitBinder (Stx.ofList [bPref, idsNode, vPref, Syntax.mkNullNodeF .snil]) + let newConds := mapBoundConds opTok rhsStx (Syntax.getArgs idsNode).toList + (bClean :: bs', newConds ++ restConds) + else + (b :: bs', restConds) + | _ => (b :: bs', restConds) + +/-- Build relational bound conditions `id opTok boundRhs` for all untyped `explicitBinder`s in `binders`. -/ +def mkUnparenBoundConds (opTok boundRhs : Stx) : List Stx → List Stx + | [] => [] + | b :: bs => + let here := match b with + | .node _ k (.scons _ (.scons idsNode (.scons _ (.scons tyNode .snil)))) => + if k == SyntaxKindF.explicitBinder && Syntax.isNone tyNode then + mapBoundConds opTok boundRhs (Syntax.getArgs idsNode).toList + else [] + | _ => [] + here ++ mkUnparenBoundConds opTok boundRhs bs + +/-- Monomorphic helper: expand one binder node's id list into single-var binders. -/ +def mapSingleBinders (info : FSourceInfo) (bPref vPref tyNode : Stx) : List Stx → List Stx + | [] => [] + | idStx :: rest => + Syntax.mkNodeListF SyntaxKindF.explicitBinder [bPref, Syntax.mkNodeListF SyntaxKindF.nullKind [idStx], vPref, tyNode] info :: + mapSingleBinders info bPref vPref tyNode rest + +/-- Expand a single binder node (`explicitBinder`, etc.) into one single-variable binder per identifier. -/ +def expandSingleBinders (bStx : Stx) : List Stx := + match bStx with + | .node info k (.scons bPref (.scons idsNode (.scons vPref (.scons tyNode .snil)))) => + if k == SyntaxKindF.explicitBinder || k == SyntaxKindF.implicitBinder || + k == SyntaxKindF.strictImplicitBinder || k == SyntaxKindF.instBinder then + mapSingleBinders info bPref vPref tyNode (Syntax.getArgs idsNode).toList + else + [bStx] + | _ => [bStx] + +def flattenSingleBinders : List Stx → List Stx + | [] => [] + | b :: bs => expandSingleBinders b ++ flattenSingleBinders bs + +def foldExistsBinders (body : Stx) : List Stx → Stx + | [] => body + | b :: bs => + let acc := foldExistsBinders body bs + let lam := Syntax.mkNodeListF SyntaxKindF.funTerm + [Syntax.mkSimpleAtomF (s% "fun"), Syntax.mkNodeListF SyntaxKindF.nullKind [b], Syntax.mkSimpleAtomF (s% "=>"), acc] + Syntax.mkNodeListF SyntaxKindF.appTerm [Syntax.mkSimpleIdentF (FName.simple (s% "Exists")), lam] + +/-- Desugar `∃ b₁ ... bₙ, body` into nested `Exists (fun b₁ => ... (Exists (fun bₙ => body)))`. -/ +def mkExistsFromBinders (binders : List Stx) (body : Stx) : Stx := + foldExistsBinders body (flattenSingleBinders binders) + +def foldAndConds (body : Stx) : List Stx → Stx + | [] => body + | c :: cs => Syntax.mkNodeListF SyntaxKindF.binOpTerm [c, Syntax.mkSimpleAtomF (s% "∧"), foldAndConds body cs] + +def foldArrowConds (emptyVPref body : Stx) : List Stx → Stx + | [] => body + | c :: cs => Syntax.mkNodeListF SyntaxKindF.arrowTerm [c, Syntax.mkSimpleAtomF (s% "→"), emptyVPref, foldArrowConds emptyVPref body cs] + +/-- Monomorphic helper: build explicit binder nodes from a list of parameter names. -/ +def mapParamNamesToBinders (emptyPref emptyVPref : Stx) : List FName → List Stx + | [] => [] + | nm :: rest => + Syntax.mkNodeListF SyntaxKindF.explicitBinder + [emptyPref, Syntax.mkNodeListF SyntaxKindF.nullKind [Syntax.mkSimpleIdentF nm], emptyVPref, Syntax.mkNullNodeF .snil] :: + mapParamNamesToBinders emptyPref emptyVPref rest + +/-- Replace every `.atom _ "·"` in `stx` (stopping at `byTactic` blocks) with fresh parameter + identifiers `_cd_0`, `_cd_1`, ... and return `(rewrittenStx, paramNames, nextIdx)`. -/ +def replaceCenterDots : Nat → Stx → Nat → Stx × List FName × Nat + | 0, stx, nextIdx => (stx, [], nextIdx) + | fuel + 1, stx, nextIdx => + match stx with + | .atom info sym => + if Sym.beq sym (s% "·") then + let paramName := FName.mkNat (FName.simple (s% "_cd")) nextIdx + let idStx := Syntax.mkIdentF info (s% "_cd") paramName + (idStx, [paramName], nextIdx + 1) + else (stx, [], nextIdx) + | .node info kind args => + if kind == SyntaxKindF.byTactic then + (stx, [], nextIdx) + else + let rec loopArgs : List Stx → List Stx → List FName → Nat → + List Stx × List FName × Nat + | [], revStxs, revNames, idx => (revStxs.reverse, revNames.reverse, idx) + | a :: as, revStxs, revNames, idx => + let (a', nms, idx') := replaceCenterDots fuel a idx + loopArgs as (a' :: revStxs) (nms.reverse ++ revNames) idx' + let (newArgs, paramNames, nextIdx') := loopArgs args.toList [] [] nextIdx + if paramNames.isEmpty then + (stx, [], nextIdx) + else + (.node info kind (Stx.ofList newArgs), paramNames, nextIdx') + | _ => (stx, [], nextIdx) + +/-- If `stx` contains any centered-dot placeholders `·`, wrap it in `fun _cd.0 _cd.1 ... => stx'`. -/ +def expandCenterDots (stx : Stx) : Stx := + let (body', paramNames, _) := replaceCenterDots 128 stx 0 + if paramNames.isEmpty then + stx + else + let emptyPref := Syntax.mkNodeF SyntaxKindF.binderPrefix .snil + let emptyVPref := Syntax.mkNodeF SyntaxKindF.valuePrefix .snil + let binderNodes := mapParamNamesToBinders emptyPref emptyVPref paramNames + Syntax.mkNodeListF SyntaxKindF.funTerm + [Syntax.mkSimpleAtomF (s% "fun"), Syntax.mkNullNode (Array.mk binderNodes), + Syntax.mkSimpleAtomF (s% "=>"), body'] + +/-- Helper 1 for `leadTermFn`: syntax quotation and antiquotation (`$`, `` `( ``, `` ` ``). -/ +def leadTermQuote (termRec : ParserFn) (tacticFuel : Nat) (sym : Sym) + (ctx : IxParserContext) (s : ParserState) : ParserState := + let term0 := withPrecFn 0 termRec + let parseSyntaxQuoteBody : ParserFn := fun c st => + let tryCatPrefix : ParserFn := fun c2 st2 => + (identFn c2 st2).bindState fun st2 => + if st2.hasError then st2 else + (symbolFn (s% "|") c2 st2).bindState fun st2 => + if st2.hasError then st2 else + st2.popSyntax + let noCatPrefix : ParserFn := fun _ st2 => + st2.pushSyntax (Syntax.mkSimpleIdentF FName.anon) + (tryOrElseFn tryCatPrefix noCatPrefix c st).bindState fun st => + let catId := Syntax.getIdF st.stxStack.back + let st := st.popSyntax + if catId == FName.simple (s% "tactic") then + tryOrElseFn (tacticSeqCore termRec false true tacticFuel) term0 c st + else + term0 c st + if Sym.beq (sym) (s% "$") then + let iniSz := s.stackSize + (symbolFn (s% "$") ctx s).bindState fun s => + bindPeek ctx s fun next? s => + if tokIsAtom (next?) (s% "(") then + (symbolFn (s% "(") ctx s).bindState fun s => + (identFn ctx s).bindState fun s => + (symbolFn (s% ")") ctx s).bindState fun s => + if s.hasError then s else + let idStx := s.stxStack.getD (iniSz + 2) + let s := s.shrinkStack (iniSz + 1) + (s.pushSyntax idStx).mkNode SyntaxKindF.antiquotTerm iniSz + else + (identFn ctx s).bindState fun s => + s.mkNode SyntaxKindF.antiquotTerm iniSz + else if Sym.beq (sym) (s% "`(") then + let iniSz := s.stackSize + (symbolFn (s% "`(") ctx s).bindState fun s => + (parseSyntaxQuoteBody ctx s).bindState fun s => + if s.hasError then s else + let inner := s.stxStack.back + (symbolFn (s% ")") ctx s).bindState fun s => + if s.hasError then s else + let s := s.shrinkStack iniSz + s.pushSyntax inner + else + let iniSz := s.stackSize + (symbolFn (s% "`") ctx s).bindState fun s => + bindPeek ctx s fun next? s => + if tokIsAtom (next?) (s% "(") then + (symbolFn (s% "(") ctx s).bindState fun s => + (parseSyntaxQuoteBody ctx s).bindState fun s => + if s.hasError then s else + let inner := s.stxStack.back + (symbolFn (s% ")") ctx s).bindState fun s => + if s.hasError then s else + let s := s.shrinkStack iniSz + s.pushSyntax inner + else + (withPrecFn maxPrec termRec ctx s).bindState fun s => + if s.hasError then s else + let inner := s.stxStack.back + let s := s.shrinkStack iniSz + s.pushSyntax inner + +/-- Helper 2 for `leadTermFn`: quantifiers (`forall`, `∀`, `∃`). -/ +def leadTermQuantifier (termRec : ParserFn) (isExists : Bool) + (ctx : IxParserContext) (s : ParserState) : ParserState := + let term0 := withPrecFn 0 termRec + let iniSz := s.stackSize + (tokenFn ctx s).bindState fun s => + (many1SimpleOrBracketedBinderFn termRec ctx s).bindState fun s => + if s.hasError then s else + let finishQuantifier (sFinal : ParserState) (extraConds : List Stx) : ParserState := + if sFinal.hasError then sFinal else + match sFinal.stxStack.rev with + | bodyStx :: vPref :: commaTok :: bindersNode :: kwTok :: restRev => + let (cleanBinders, parenConds) := extractBinderBounds (Syntax.getArgs bindersNode).toList + let allConds := parenConds ++ extraConds + let emptyVPref := Syntax.mkNodeF SyntaxKindF.valuePrefix .snil + if isExists then + let bodyWithConds := foldAndConds bodyStx allConds + let exStx := mkExistsFromBinders cleanBinders bodyWithConds + ⟨⟨exStx :: restRev, iniSz + 1⟩, sFinal.lhsPrec, sFinal.pos, sFinal.remBytes, sFinal.cache, sFinal.errorMsg⟩ + else + let bodyWithConds := foldArrowConds emptyVPref bodyStx allConds + let newBinders := Syntax.mkNullNode (Array.mk cleanBinders) + let forallNode := Syntax.mkNodeListF SyntaxKindF.forallTerm + [kwTok, newBinders, commaTok, vPref, bodyWithConds] + ⟨⟨forallNode :: restRev, iniSz + 1⟩, sFinal.lhsPrec, sFinal.pos, sFinal.remBytes, sFinal.cache, sFinal.errorMsg⟩ + | _ => sFinal.mkNode SyntaxKindF.forallTerm iniSz + bindPeek ctx s fun sepTok? s => + match sepTok? with + | some (.atom _ relSym) => + if Sym.beq relSym (s% ":") then + (symbolFn (s% ":") ctx s).bindState fun s => + (valuePrefixFn ctx s).bindState fun s => + if s.hasError then s else + (term0 ctx s).bindState fun s => + if s.hasError then s else + bindPeek ctx s fun afterTyTok? s => + if tokIsAtom (afterTyTok?) (s% ",") then + let s := match s.stxStack.rev with + | bTy :: bVPref :: _ :: bindersNode :: kwTok :: restRev => + let updatedList := attachTypeToBinders bVPref bTy (Syntax.getArgs bindersNode).toList + let newBinders := Syntax.mkNodeListF SyntaxKindF.nullKind updatedList + ⟨⟨newBinders :: kwTok :: restRev, iniSz + 2⟩, s.lhsPrec, s.pos, s.remBytes, s.cache, s.errorMsg⟩ + | _ => s + (symbolFn (s% ",") ctx s).bindState fun s => + (valuePrefixFn ctx s).bindState fun s => + if s.hasError then s else + (term0 ctx s).bindState fun s => + finishQuantifier s [] + else + finishQuantifier s [] + else if isBinderRelOp relSym then + (tokenFn ctx s).bindState fun s => + let opTok := s.stxStack.back + let s := s.popSyntax + (term0 ctx s).bindState fun s => + if s.hasError then s else + let boundRhs := s.stxStack.back + let s := s.popSyntax + let bindersNode := s.stxStack.back + let extraConds := mkUnparenBoundConds opTok boundRhs (Syntax.getArgs bindersNode).toList + (symbolFn (s% ",") ctx s).bindState fun s => + (valuePrefixFn ctx s).bindState fun s => + if s.hasError then s else + (term0 ctx s).bindState fun s => + finishQuantifier s extraConds + else + (symbolFn (s% ",") ctx s).bindState fun s => + (valuePrefixFn ctx s).bindState fun s => + if s.hasError then s else + (term0 ctx s).bindState fun s => + finishQuantifier s [] + | _ => + (symbolFn (s% ",") ctx s).bindState fun s => + (valuePrefixFn ctx s).bindState fun s => + if s.hasError then s else + (term0 ctx s).bindState fun s => + finishQuantifier s [] + +/-- Helper 3 for `leadTermFn`: `let`, `let @[borrow]`, `let rec`, and `have`. -/ +def leadTermLetHave (termRec : ParserFn) (isHave : Bool) + (ctx : IxParserContext) (s : ParserState) : ParserState := + let term0 := withPrecFn 0 termRec + if !isHave then + let iniSz := s.stackSize + (symbolFn (s% "let") ctx s).bindState fun s => + bindPeek ctx s fun afterLet? s => + let isRec := + if tokIsWord (afterLet?) (s% "rec") || tokIsAtom (afterLet?) (s% "rec") then true + else false + let sSubKw := + if isRec then nonReservedSymbolFn (s% "rec") ctx s + else s + sSubKw.bindState fun s => + (letPrefixFn ctx s).bindState fun s => + if s.hasError then s else + bindPeek ctx s fun patTok? s => + if tokIsAtom (patTok?) (s% "⟨") then + let patSz := s.stackSize + (symbolFn (s% "⟨") ctx s).bindState fun s => + (sepByTermCommaFn termRec true ctx s).bindState fun s => + (symbolFn (s% "⟩") ctx s).bindState fun s => + (s.mkNode SyntaxKindF.anonCtor patSz).bindState fun s => + if s.hasError then s else + let anonPat := s.stxStack.back + let s := s.popSyntax + (optionalFn (fun c st => + (symbolFn (s% ":") c st).bindState fun st => + if st.hasError then st else + (valuePrefixFn c st).bindState fun st => + term0 c st) ctx s).bindState fun s => + if s.hasError then s else + let optTyNode := s.stxStack.back + let s := s.popSyntax + (symbolFn (s% ":=") ctx s).bindState fun s => + (term0 ctx s).bindState fun s => + if s.hasError then s else + let valStx := s.stxStack.back + let s := s.popSyntax + (optionalFn (orelseFn (symbolFn (s% ";")) (symbolFn (s% "in"))) ctx s).bindState fun s => + (term0 ctx s).bindState fun s => + if s.hasError then s else + let bodyStx := s.stxStack.back + let s := s.shrinkStack iniSz + let discrStx := + if Nat.ble 3 (Syntax.getNumArgs optTyNode) then + Syntax.mkNodeListF SyntaxKindF.typeAscription + [Syntax.mkSimpleAtomF (s% "("), valStx, Syntax.mkSimpleAtomF (s% ":"), + Syntax.getArg optTyNode 1, Syntax.getArg optTyNode 2, Syntax.mkSimpleAtomF (s% ")")] + else valStx + let altNode := Syntax.mkNodeListF SyntaxKindF.matchAlt + [Syntax.mkSimpleAtomF (s% "|"), Syntax.mkNodeListF SyntaxKindF.nullKind [anonPat], + Syntax.mkSimpleAtomF (s% "=>"), bodyStx] + let matchNode := Syntax.mkNodeListF SyntaxKindF.matchTerm + [Syntax.mkSimpleAtomF (s% "match"), Syntax.mkNodeListF SyntaxKindF.nullKind [discrStx], + Syntax.mkSimpleAtomF (s% "with"), Syntax.mkNodeListF SyntaxKindF.nullKind [altNode]] + s.pushSyntax matchNode + else + (binderIdentFn ctx s).bindState fun s => + if s.hasError then s else + (manySimpleOrBracketedBinderFn termRec ctx s).bindState fun s => + (optionalFn (fun c st => + (symbolFn (s% ":") c st).bindState fun st => + if st.hasError then st else + (valuePrefixFn c st).bindState fun st => + term0 c st) ctx s).bindState fun s => + if s.hasError then s else + bindPeek ctx s fun rhsTok? s => + let sAfterRhs := + if tokIsAtom (rhsTok?) (s% "|") then + if isRec then + let s := s.pushSyntax (Syntax.mkSimpleAtomF (s% ":=")) + many1MatchAltFn termRec ctx s + else + symbolFn (s% ":=") ctx s + else + (symbolFn (s% ":=") ctx s).bindState fun s => + if s.hasError then s else term0 ctx s + sAfterRhs.bindState fun s => + if s.hasError then s else + (optionalFn (orelseFn (symbolFn (s% ";")) (symbolFn (s% "in"))) ctx s).bindState fun s => + (term0 ctx s).bindState fun s => + let nodeKind := + if isRec then SyntaxKindF.letRecTerm + else SyntaxKindF.letTerm + s.mkNode nodeKind iniSz + else + let iniSz := s.stackSize + (symbolFn (s% "have") ctx s).bindState fun s => + bindPeek ctx s fun patTok? s => + if tokIsAtom (patTok?) (s% "⟨") then + let patSz := s.stackSize + (symbolFn (s% "⟨") ctx s).bindState fun s => + (sepByTermCommaFn termRec true ctx s).bindState fun s => + (symbolFn (s% "⟩") ctx s).bindState fun s => + (s.mkNode SyntaxKindF.anonCtor patSz).bindState fun s => + if s.hasError then s else + let anonPat := s.stxStack.back + let s := s.popSyntax + (optionalFn (seqFn (symbolFn (s% ":")) term0) ctx s).bindState fun s => + if s.hasError then s else + let optTyNode := s.stxStack.back + let s := s.popSyntax + (symbolFn (s% ":=") ctx s).bindState fun s => + (term0 ctx s).bindState fun s => + if s.hasError then s else + let valStx := s.stxStack.back + let s := s.popSyntax + (optionalFn (orelseFn (symbolFn (s% ";")) (symbolFn (s% "in"))) ctx s).bindState fun s => + (term0 ctx s).bindState fun s => + if s.hasError then s else + let bodyStx := s.stxStack.back + let s := s.shrinkStack iniSz + let discrStx := + if Nat.ble 2 (Syntax.getNumArgs optTyNode) then + Syntax.mkNodeListF SyntaxKindF.typeAscription + [Syntax.mkSimpleAtomF (s% "("), valStx, Syntax.mkSimpleAtomF (s% ":"), + Syntax.mkNodeF SyntaxKindF.valuePrefix .snil, + Syntax.getArg optTyNode 1, Syntax.mkSimpleAtomF (s% ")")] + else valStx + let altNode := Syntax.mkNodeListF SyntaxKindF.matchAlt + [Syntax.mkSimpleAtomF (s% "|"), Syntax.mkNodeListF SyntaxKindF.nullKind [anonPat], + Syntax.mkSimpleAtomF (s% "=>"), bodyStx] + let matchNode := Syntax.mkNodeListF SyntaxKindF.matchTerm + [Syntax.mkSimpleAtomF (s% "match"), Syntax.mkNodeListF SyntaxKindF.nullKind [discrStx], + Syntax.mkSimpleAtomF (s% "with"), Syntax.mkNodeListF SyntaxKindF.nullKind [altNode]] + s.pushSyntax matchNode + else + let sAfterId := + if tokIsAtom (patTok?) (s% ":") || tokIsAtom (patTok?) (s% ":=") then + s.pushSyntax (Syntax.mkSimpleIdentF (FName.simple (s% "this"))) + else + binderIdentFn ctx s + sAfterId.bindState fun s => + if s.hasError then s else + (optionalFn (seqFn (symbolFn (s% ":")) term0) ctx s).bindState fun s => + if s.hasError then s else + (symbolFn (s% ":=") ctx s).bindState fun s => + if s.hasError then s else + (term0 ctx s).bindState fun s => + if s.hasError then s else + (optionalFn (orelseFn (symbolFn (s% ";")) (symbolFn (s% "in"))) ctx s).bindState fun s => + (term0 ctx s).bindState fun s => + s.mkNode SyntaxKindF.haveTerm iniSz + +/-- Helper 4 for `leadTermFn`: delimited expressions (`(`, `{`, `⦃`, `{{`, `[`, `⟨`) and `if`/`match`/`by`/`calc`. -/ +def leadTermDelims (termRec : ParserFn) (tacticFuel : Nat) (sym : Sym) + (ctx : IxParserContext) (s : ParserState) : ParserState := + let term0 := withPrecFn 0 termRec + if Sym.beq (sym) (s% "if") then + let iniSz := s.stackSize + (symbolFn (s% "if") ctx s).bindState fun s => + let depCondAttempt : ParserFn := fun c st => + (binderIdentFn c st).bindState fun st => + (symbolFn (s% ":") c st).bindState fun st => + term0 c st + let plainCondAttempt : ParserFn := fun c st => + let st := st.pushSyntax (Syntax.mkNullNodeF .snil) + term0 c st + (tryOrElseFn depCondAttempt plainCondAttempt ctx s).bindState fun s => + (symbolFn (s% "then") ctx s).bindState fun s => + (term0 ctx s).bindState fun s => + (symbolFn (s% "else") ctx s).bindState fun s => + (term0 ctx s).bindState fun s => + s.mkNode SyntaxKindF.ifTerm iniSz + else if Sym.beq (sym) (s% "match") then + let iniSz := s.stackSize + (symbolFn (s% "match") ctx s).bindState fun s => + (sepBy1TermCommaFn termRec false ctx s).bindState fun s => + (symbolFn (s% "with") ctx s).bindState fun s => + (many1MatchAltFn termRec ctx s).bindState fun s => + s.mkNode SyntaxKindF.matchTerm iniSz + else if Sym.beq (sym) (s% "by") then + let iniSz := s.stackSize + (symbolFn (s% "by") ctx s).bindState fun s => + (tacticSeqStep termRec tacticFuel ctx s).bindState fun s => + s.mkNode SyntaxKindF.byTactic iniSz + else if Sym.beq (sym) (s% "calc") then + let iniSz := s.stackSize + (symbolFn (s% "calc") ctx s).bindState fun s => + if s.hasError then s else + let calcTok := s.stxStack.back + (calcStepsFn termRec ctx s).bindState fun s => + if s.hasError then s else + let stepsNode := s.stxStack.back + let s := s.shrinkStack iniSz + let tacNode := Syntax.mkNodeListF SyntaxKindF.tacticCalc [calcTok, stepsNode] + s.pushSyntax (Syntax.mkNodeListF SyntaxKindF.byTactic [calcTok, tacNode]) + else if Sym.beq (sym) (s% "(") then + let depPiAttempt : ParserFn := fun c st => + let pSz := st.stackSize + (many1BracketedBinderFn termRec c st).bindState fun st => + if st.hasError then st else + (orelseFn (symbolFn (s% "→")) (symbolFn (s% "->")) c st).bindState fun st => + if st.hasError then st else + (valuePrefixFn c st).bindState fun st => + if st.hasError then st else + (withPrecFn (arrowPrec - 1) termRec c st).bindState fun st => + st.mkNode SyntaxKindF.forallTerm pSz + let parenAttempt : ParserFn := fun c st => + let pSz := st.stackSize + (symbolFn (s% "(") c st).bindState fun st => + if st.hasError then st else + bindPeek c st fun next? st => + if tokIsAtom (next?) (s% ")") then + (symbolFn (s% ")") c st).bindState fun st => + st.mkNode SyntaxKindF.tupleTerm pSz + else + (term0 c st).bindState fun st => + if st.hasError then st else + bindPeek c st fun afterFirst? st => + if tokIsAtom (afterFirst?) (s% ":") then + (symbolFn (s% ":") c st).bindState fun st => + (valuePrefixFn c st).bindState fun st => + if st.hasError then st else + (term0 c st).bindState fun st => + (symbolFn (s% ")") c st).bindState fun st => + st.mkNode SyntaxKindF.typeAscription pSz + else if tokIsAtom (afterFirst?) (s% ",") then + (symbolFn (s% ",") c st).bindState fun st => + (sepBy1TermCommaFn termRec true c st).bindState fun st => + (symbolFn (s% ")") c st).bindState fun st => + (st.mkNode SyntaxKindF.tupleTerm pSz).bindState fun st => + if st.hasError then st else + let tup := expandCenterDots st.stxStack.back + let st := st.shrinkStack pSz + st.pushSyntax tup + else + let inner := expandCenterDots st.stxStack.back + (symbolFn (s% ")") c st).bindState fun st => + if st.hasError then st else + let st := st.shrinkStack pSz + st.pushSyntax inner + tryOrElseFn depPiAttempt parenAttempt ctx s + else if Sym.beq (sym) (s% "{") || Sym.beq (sym) (s% "⦃") || Sym.beq (sym) (s% "{{") then + let depPiAttempt : ParserFn := fun c st => + let pSz := st.stackSize + (many1BracketedBinderFn termRec c st).bindState fun st => + if st.hasError then st else + (orelseFn (symbolFn (s% "→")) (symbolFn (s% "->")) c st).bindState fun st => + if st.hasError then st else + (valuePrefixFn c st).bindState fun st => + if st.hasError then st else + (withPrecFn (arrowPrec - 1) termRec c st).bindState fun st => + st.mkNode SyntaxKindF.forallTerm pSz + let structInstAttempt : ParserFn := fun c st => + let pSz := st.stackSize + (symbolFn (s% "{") c st).bindState fun st => + if st.hasError then st else + let withAttempt : ParserFn := fun c2 st2 => + (term0 c2 st2).bindState fun st2 => + if st2.hasError then st2 else + (symbolFn (s% "with") c2 st2).bindState fun st2 => + if st2.hasError then st2 else st2.popSyntax + let noWith : ParserFn := fun _ st2 => + st2.pushSyntax (Syntax.mkNullNodeF .snil) + (tryOrElseFn withAttempt noWith c st).bindState fun st => + (sepByFieldAssignCommaFn termRec c st).bindState fun st => + (symbolFn (s% "}") c st).bindState fun st => + st.mkNode SyntaxKindF.structInst pSz + tryOrElseFn depPiAttempt structInstAttempt ctx s + else if Sym.beq (sym) (s% "[") then + let depPiAttempt : ParserFn := fun c st => + let pSz := st.stackSize + (many1BracketedBinderFn termRec c st).bindState fun st => + if st.hasError then st else + (orelseFn (symbolFn (s% "→")) (symbolFn (s% "->")) c st).bindState fun st => + if st.hasError then st else + (valuePrefixFn c st).bindState fun st => + if st.hasError then st else + (withPrecFn (arrowPrec - 1) termRec c st).bindState fun st => + st.mkNode SyntaxKindF.forallTerm pSz + let listLitAttempt : ParserFn := fun c st => + let pSz := st.stackSize + (symbolFn (s% "[") c st).bindState fun st => + if st.hasError then st else + (sepByTermCommaFn termRec true c st).bindState fun st => + (symbolFn (s% "]") c st).bindState fun st => + st.mkNode SyntaxKindF.listLit pSz + tryOrElseFn depPiAttempt listLitAttempt ctx s + else if Sym.beq (sym) (s% "⟨") then + let iniSz := s.stackSize + (symbolFn (s% "⟨") ctx s).bindState fun s => + (sepByTermCommaFn termRec true ctx s).bindState fun s => + (symbolFn (s% "⟩") ctx s).bindState fun s => + s.mkNode SyntaxKindF.anonCtor iniSz + else if Sym.beq (sym) (s% "-") || Sym.beq (sym) (s% "!") || Sym.beq (sym) (s% "¬") then + let iniSz := s.stackSize + (tokenFn ctx s).bindState fun s => + (withPrecFn leadPrec termRec ctx s).bindState fun s => + s.mkNode SyntaxKindF.unaryOpTerm iniSz + else + match findPrefixOp? ctx.env sym with + | some op => + (tokenFn ctx s).bindState fun s => + let s := s.popSyntax + (withPrecFn op.prec termRec ctx s).bindState fun s => + if s.hasError then s else + match op.targetFn with + | some fnName => + let argStx := s.stxStack.back + let s := s.popSyntax + s.pushSyntax (Syntax.mkNodeListF SyntaxKindF.appTerm [Syntax.mkSimpleIdentF fnName, argStx]) + | none => s + | none => + s.mkUnexpectedError (s% "unexpected token in term") + +/-- Parse a leading expression, split into small modular helpers for low circuit width. -/ +def leadTermFn (termRec : ParserFn) (tacticFuel : Nat) : ParserFn := fun ctx s => + let term0 := withPrecFn 0 termRec + bindPeek ctx s fun tok? s => + let leadNotationHit? : Option ParserState := + match ctx.env.notations, tok? with + | [], _ | _, none => none + | nots, some tok => + let tStr := tokenText tok + if tStr.isEmpty then none + else tryLeadNotationRules termRec tStr nots ctx s + match leadNotationHit? with + | some sHit => sHit + | none => + match tok? with + | none => s.mkEOIError [(s% "term")] + -- 1. Literals & content-hash references + | some (.node _ k _) => + if k == SyntaxKindF.numLit || k == SyntaxKindF.strLit || + k == SyntaxKindF.charLit || k == SyntaxKindF.hashRef then + tokenFn ctx s + else + s.mkUnexpectedError (s% "unexpected syntax node in term") + -- 2. Identifiers (with optional `.{u, v}` universe levels) + | some (.ident ..) => + let iniSz := s.stackSize + (identFn ctx s).bindState fun s => + bindPeek ctx s fun nextTok? s => + if tokIsAtom (nextTok?) (s% ".{") then + (optUnivArgsFn ctx s).bindState fun s => + s.mkNode SyntaxKindF.explicitTerm iniSz + else s + -- 3. Keywords and leading symbols (O(1) first-byte dispatch!) + | some (.atom _ sym) => + match sym with + | .nil => s.mkUnexpectedError (s% "unexpected token in term") + | .cons b0 rest => + -- Fast path for delimiters & prefix ops (`(`, `{`, `[`, `if`, `match`, `by`, `calc`, `-`, `!`, `⟨`, `⦃`, `¬`) + if Nat.beq b0 40 || Nat.beq b0 123 || Nat.beq b0 91 || Nat.beq b0 45 || Nat.beq b0 33 || + Nat.beq b0 105 || Nat.beq b0 109 || Nat.beq b0 98 || Nat.beq b0 99 then + leadTermDelims termRec tacticFuel sym ctx s + else if Nat.beq b0 84 && Sym.beq rest (s% "ype") then + let iniSz := s.stackSize + (symbolFn (s% "Type") ctx s).bindState fun s => + bindPeek ctx s fun nextTok? s => + let sAfterLvl := match nextTok? with + | some (.node _ k _) => + if k == SyntaxKindF.numLit then levelFn ctx s + else s.pushSyntax (Syntax.mkNullNodeF .snil) + | some (.ident ..) => + optionalFn (withPrecFn maxPrec (levelAtomFn levelFn)) ctx s + | some (.atom _ v) => + if Sym.beq v (s% "(") then + optionalFn (withPrecFn maxPrec (levelAtomFn levelFn)) ctx s + else s.pushSyntax (Syntax.mkNullNodeF .snil) + | _ => s.pushSyntax (Syntax.mkNullNodeF .snil) + sAfterLvl.bindState fun s => + s.mkNode SyntaxKindF.typeTerm iniSz + else if Nat.beq b0 80 && Sym.beq rest (s% "rop") then + let iniSz := s.stackSize + (symbolFn (s% "Prop") ctx s).bindState fun s => + s.mkNode SyntaxKindF.propTerm iniSz + else if Nat.beq b0 95 && Sym.isEmpty rest then + let iniSz := s.stackSize + (symbolFn (s% "_") ctx s).bindState fun s => + s.mkNode SyntaxKindF.holeTerm iniSz + else if Nat.beq b0 102 then + if Sym.beq rest (s% "un") then + let iniSz := s.stackSize + (tokenFn ctx s).bindState fun s => + (many1SimpleOrBracketedBinderFn termRec ctx s).bindState fun s => + (orelseFn (symbolFn (s% "=>")) (symbolFn (s% "↦")) ctx s).bindState fun s => + (term0 ctx s).bindState fun s => + s.mkNode SyntaxKindF.funTerm iniSz + else if Sym.beq rest (s% "orall") then + leadTermQuantifier termRec false ctx s + else + leadTermDelims termRec tacticFuel sym ctx s + else if Nat.beq b0 108 && Sym.beq rest (s% "et") then + leadTermLetHave termRec false ctx s + else if Nat.beq b0 104 && Sym.beq rest (s% "ave") then + leadTermLetHave termRec true ctx s + else if Nat.beq b0 64 && Sym.isEmpty rest then + let iniSz := s.stackSize + (symbolFn (s% "@") ctx s).bindState fun s => + (identFn ctx s).bindState fun s => + (optUnivArgsFn ctx s).bindState fun s => + s.mkNode SyntaxKindF.explicitTerm iniSz + else if Nat.beq b0 83 && Sym.beq rest (s% "ort") then + let iniSz := s.stackSize + (symbolFn (s% "Sort") ctx s).bindState fun s => + (optionalFn (withPrecFn maxPrec (levelAtomFn levelFn)) ctx s).bindState fun s => + s.mkNode SyntaxKindF.sortTerm iniSz + else if Nat.beq b0 115 && Sym.beq rest (s% "orry") then + let iniSz := s.stackSize + (symbolFn (s% "sorry") ctx s).bindState fun s => + s.mkNode SyntaxKindF.sorryTerm iniSz + else if Nat.beq b0 36 || Nat.beq b0 96 then + leadTermQuote termRec tacticFuel sym ctx s + else if Nat.beq b0 194 && (match rest with | .cons b1 .nil => Nat.beq b1 183 | _ => false) then + tokenFn ctx s + else if Nat.beq b0 206 && (match rest with | .cons b1 .nil => Nat.beq b1 187 | _ => false) then + let iniSz := s.stackSize + (tokenFn ctx s).bindState fun s => + (many1SimpleOrBracketedBinderFn termRec ctx s).bindState fun s => + (orelseFn (symbolFn (s% "=>")) (symbolFn (s% "↦")) ctx s).bindState fun s => + (term0 ctx s).bindState fun s => + s.mkNode SyntaxKindF.funTerm iniSz + else if Sym.beq sym (s% "∀") || Sym.beq sym (s% "∃") then + leadTermQuantifier termRec (Sym.beq sym (s% "∃")) ctx s + else + leadTermDelims termRec tacticFuel sym ctx s + | _ => + s.mkUnexpectedError (s% "expected term") + +/-- Cold helper for `trailingTermLoop`: check dynamic custom trailing notations. -/ +def trailNotationStep (termRec : ParserFn) (tok : Stx) (nots : List NotationRule) + (ctx : IxParserContext) (s : ParserState) : Option ParserState := + let tStr := tokenText tok + if tStr.isEmpty then none + else tryTrailNotationRules termRec tStr nots ctx s + +/-- Cold helper for `trailingTermLoop`: dispatch `.field` projection, `→`/`->` arrow, + binary infix operators, and postfix operators on an `.atom _ sym` token. + Returns `some s'` if an operator matched, or `none` to fall through to juxtaposition. -/ +def trailAtomOpStep (termRec : ParserFn) (sym : Sym) + (ctx : IxParserContext) (s : ParserState) : Option ParserState := + -- 1. Field or index projection `.field` / `.0` (tightest binding, `maxPrec`) + if Sym.beq sym (s% ".") && Nat.ble (ctx.prec + 1) maxPrec then + let iniSz := s.stackSize + let s := symbolFn (s% ".") ctx s + let s := orelseFn identFn numLitFn ctx s + if s.hasError then some s + else some (s.mkTrailingNode SyntaxKindF.projTerm iniSz maxPrec) + -- 2. Non-dependent function arrow `A → @[unique] B` / `A -> @[borrowed] B` (precedence `arrowPrec := 25`, right-assoc) + else if (Sym.beq sym (s% "→") || Sym.beq sym (s% "->")) && Nat.ble ctx.prec arrowPrec then + let iniSz := s.stackSize + let s := tokenFn ctx s + let s := valuePrefixFn ctx s + if s.hasError then some s else + let s := withPrecFn arrowPrec termRec ctx s + if s.hasError then some s + else some (s.mkTrailingNode SyntaxKindF.arrowTerm iniSz arrowPrec) + -- 3. Registered binary infix operator + else + match findInfixOp? ctx.env sym ctx.prec with + | some op => + let iniSz := s.stackSize + let s := tokenFn ctx s + let rhsMinPrec := match op.fixity with + | .infixl => op.prec + 1 + | .infixr => op.prec + | _ => op.prec + 1 + let s := withPrecFn rhsMinPrec termRec ctx s + if s.hasError then some s + else + let sNext := + if op.kind == SyntaxKindF.appTerm then + match op.targetFn with + | some fnName => + let rhsStx := s.stxStack.back + let s1 := s.shrinkStack (iniSz - 1) + let lhsStx := s.stxStack.getD (iniSz - 1) + let app1 := Syntax.mkNodeListF SyntaxKindF.appTerm [Syntax.mkSimpleIdentF fnName, lhsStx] + let app2 := Syntax.mkNodeListF SyntaxKindF.appTerm [app1, rhsStx] + s1.pushSyntax app2 + | none => s.mkTrailingNode op.kind iniSz op.prec + else + s.mkTrailingNode op.kind iniSz op.prec + some sNext + | none => + match findPostfixOp? ctx.env sym ctx.prec with + | some op => + let iniSz := s.stackSize + let s := tokenFn ctx s + let sNext := match op.targetFn with + | some fnName => + let lhsStx := s.stxStack.getD (iniSz - 1) + let s1 := s.shrinkStack (iniSz - 1) + s1.pushSyntax (Syntax.mkNodeListF SyntaxKindF.appTerm [Syntax.mkSimpleIdentF fnName, lhsStx]) + | none => s + some sNext + | none => none + +/-- Pratt trailing loop: handles `.field` / `.0` projections, function application `f a`, + substructural function arrows `A → !B`, and binary infix / postfix operators. + Written without closure-creating `bindState`/`bindPeek` so `IxCC` `FuelErase` erases `fuel` + and keeps the hot loop chip narrow. -/ +def trailingTermLoop (termRec : ParserFn) (ctx : IxParserContext) (s : ParserState) : + Nat → ParserState + | 0 => s.mkUnexpectedError (s% "parser fuel exhausted") + | fuel + 1 => + if s.hasError then s else + let (tok?, s) := peekToken ctx s + match tok? with + | none => s + | some tok => + let trailNotationHit? : Option ParserState := + match ctx.env.notations with + | [] => none + | nots => trailNotationStep termRec tok nots ctx s + match trailNotationHit? with + | some sHit => trailingTermLoop termRec ctx sHit fuel + | none => + match tok with + | .atom _ sym => + match trailAtomOpStep termRec sym ctx s with + | some sNext => trailingTermLoop termRec ctx sNext fuel + | none => + -- 4. Juxtaposition application `f arg` when `ctx.prec < argPrec` (on the same line) + if Nat.ble (ctx.prec + 1) argPrec && !hasLeadingNewline tok && canStartArg ctx.env tok then + let iniSz := s.stackSize + let s := withPrecFn argPrec termRec ctx s + if s.hasError then s else + let s := s.mkTrailingNode SyntaxKindF.appTerm iniSz argPrec + trailingTermLoop termRec ctx s fuel + else + s + | _ => + -- Non-atom token (`.ident` or literal `.node`): skip operator lookups and check juxtaposition directly + if Nat.ble (ctx.prec + 1) argPrec && !hasLeadingNewline tok && canStartArg ctx.env tok then + let iniSz := s.stackSize + let s := withPrecFn argPrec termRec ctx s + if s.hasError then s else + let s := s.mkTrailingNode SyntaxKindF.appTerm iniSz argPrec + trailingTermLoop termRec ctx s fuel + else + s + +/-- Parse an expression at minimum precedence `ctx.prec`, structurally recursive on `fuel : Nat`. -/ +def termStep : Nat → ParserFn + | 0 => fun _ s => s.mkUnexpectedError (s% "parser fuel exhausted in term") + | fuel + 1 => fun ctx s => + let termRec := termStep fuel + let s := leadTermFn termRec fuel ctx s + if s.hasError then s else + trailingTermLoop termRec ctx s parseFuel + +/-- Default expression parser combinator (`termStep parseFuel`, `FuelErase`-ready). -/ +def termFn : ParserFn := termStep parseFuel + +/-- Convenience entry point: parse a standalone expression string into `Stx`. -/ +def parseTerm (input : String) (env : IxParserEnv := defaultParserEnv) + (fuel : Nat := parseFuel) : Except String Stx := + let inputCtx := InputContext.mkInputContext input "" + let ctx : IxParserContext := { inputCtx, env, prec := 0 } + let s := termStep fuel ctx (ParserState.init inputCtx.bytes) + match s.errorMsg with + | some err => .error (ParserError.toString inputCtx err) + | none => + if !atEOI ctx s then + let err : ParserError := { pos := s.pos, unexpected := s% "unexpected trailing tokens" } + .error (ParserError.toString inputCtx err) + else + .ok s.stxStack.back + +end Ix.Frontend.Parser diff --git a/Ix/Frontend/Parser/Trie.lean b/Ix/Frontend/Parser/Trie.lean new file mode 100644 index 0000000000..2824f3e29e --- /dev/null +++ b/Ix/Frontend/Parser/Trie.lean @@ -0,0 +1,117 @@ +/- + Ix.Frontend.Parser.Trie: Pure, total, non-nested UTF-8 byte prefix trie for + maximal-munch tokenization in the Ix Frontend parser. + + Keys are `Sym` (`ByteList`), so every comparison is pure `Nat.beq`/`Nat.ble` + with zero `Char`, zero `String`, and zero `Lit.str`! +-/ +module + +public import Ix.Frontend.Sym + +@[expose] public section + +namespace Ix.Frontend.Parser + +/-- Sorted linked list of byte edges `(key, val, children, next)`. + Strictly non-nested and non-mutual so `IxCC` compiles every match to an + unboxed `case` with zero `S25` nested-recursor overhead. -/ +inductive TrieEdge (α : Type) where + | nil : TrieEdge α + | cons (key : Nat) (val : Option α) (children : TrieEdge α) (next : TrieEdge α) : TrieEdge α + deriving Repr, Inhabited + +/-- A pure UTF-8 byte trie for maximal-munch operator and punctuation matching. -/ +structure Trie (α : Type) where + val : Option α + children : TrieEdge α + deriving Repr, Inhabited + +namespace Trie + +/-- The empty trie. -/ +def empty {α : Type} : Trie α := { val := none, children := .nil } + +/-- Find the edge `(val, children)` for byte `b` in a sorted `TrieEdge` chain. -/ +def findEdgeNat? {α : Type} (b : Nat) : TrieEdge α → Option (Option α × TrieEdge α) + | .nil => none + | .cons k v ch rest => + if Nat.beq b k then some (v, ch) + else if Nat.ble (Nat.add b 1) k then none + else findEdgeNat? b rest + +/-- Build a single-branch `TrieEdge` chain for `b :: bs` (structurally recursive on `Sym`). -/ +def singletonEdge {α : Type} (b : Nat) : Sym → α → TrieEdge α + | .nil, v => .cons b (some v) .nil .nil + | .cons b2 bs2, v => .cons b none (singletonEdge b2 bs2 v) .nil + +/-- Insert a non-empty byte path `b :: bs` into a sorted `TrieEdge` chain (structurally recursive on `TrieEdge`). -/ +def insertEdge {α : Type} : TrieEdge α → Nat → Sym → α → TrieEdge α + | .nil, b, bs, v => singletonEdge b bs v + | .cons k kv kch rest, b, bs, v => + if Nat.beq b k then + match bs with + | .nil => .cons k (some v) kch rest + | .cons b2 bs2 => .cons k kv (insertEdge kch b2 bs2 v) rest + else if Nat.ble (Nat.add b 1) k then + match bs with + | .nil => .cons b (some v) .nil (.cons k kv kch rest) + | .cons b2 bs2 => .cons b none (singletonEdge b2 bs2 v) (.cons k kv kch rest) + else + .cons k kv kch (insertEdge rest b bs v) + +/-- Insert a `Sym` (`ByteList`) key into the trie. -/ +def insert {α : Type} (t : Trie α) : Sym → α → Trie α + | .nil, v => { val := some v, children := t.children } + | .cons b bs, v => { val := t.val, children := insertEdge t.children b bs v } + +/-- Strictly fold a list of `Sym` tokens into a `Trie Sym`. -/ +def ofSymbolsLoop : Trie Sym → List Sym → Trie Sym + | t, [] => t + | t, s :: ss => ofSymbolsLoop (t.insert s s) ss + +/-- Build a trie from a list of `Sym` tokens (mapping each token to itself). -/ +def ofSymbols (syms : List Sym) : Trie Sym := + ofSymbolsLoop empty syms + +/-- Exact lookup of a `Sym` key inside a `TrieEdge` chain. -/ +def findExactEdge? {α : Type} : TrieEdge α → Sym → Option α + | _, .nil => none + | edges, .cons b bs => + match findEdgeNat? b edges with + | none => none + | some (v, ch) => + match bs with + | .nil => v + | _ => findExactEdge? ch bs + +/-- Exact lookup of a `Sym` key in the trie. -/ +def findExact? {α : Type} (t : Trie α) : Sym → Option α + | .nil => t.val + | .cons b bs => findExactEdge? t.children (.cons b bs) + +/-- Match the longest prefix in `rem : Sym`, tracking byte position `idx` and remaining tail `rem`. -/ +def matchPrefixEdges {α : Type} (idx : Nat) (best : Option (α × Nat × Sym)) : + Sym → TrieEdge α → Option (α × Nat × Sym) + | .nil, _ => best + | .cons b bs, edges => + match findEdgeNat? b edges with + | none => best + | some (v, ch) => + let idx1 := Nat.add idx 1 + let best1 := match v with + | some a => some (a, idx1, bs) + | none => best + matchPrefixEdges idx1 best1 bs ch + +/-- Match the longest prefix in `rem : Sym`, returning `(val, stopPos, afterBytes)`. -/ +def matchPrefixBytes {α : Type} (idx : Nat) (best : Option (α × Nat × Sym)) + (rem : Sym) (t : Trie α) : Option (α × Nat × Sym) := + let best0 := match t.val with + | some v => some (v, idx, rem) + | none => best + matchPrefixEdges idx best0 rem t.children + +end Trie + +end Ix.Frontend.Parser diff --git a/Ix/Frontend/Parser/Types.lean b/Ix/Frontend/Parser/Types.lean new file mode 100644 index 0000000000..1087c30651 --- /dev/null +++ b/Ix/Frontend/Parser/Types.lean @@ -0,0 +1,443 @@ +/- + Ix.Frontend.Parser.Types: Pure, total parser state, syntax stack, error model, + and byte-indexed input context for the Ix Frontend. + + 100% free of Lean `String` literals (`Lit.str`), `Char`, and `Ix.Name` in the + circuit execution path: operates directly on `Sym` (`ByteList`), `FName`, + and `FSourceInfo`. +-/ +module + +public import Ix.Frontend.Syntax +public import Ix.Frontend.Parser.Trie + +@[expose] public section + +namespace Ix.Frontend.Parser + +/-! ## Constant Fuel for `IxCC` `FuelErase` -/ + +/-- Canonical constant fuel (`2^40`) for parser loops so `IxCC`'s `FuelErase` pass + erases fuel arguments and enables Aiur memoization. -/ +@[inline] def parseFuel : Nat := 1099511627776 + +/-! ## UTF-8 Byte-Indexed `InputContext` -/ + +/-- Pure input context storing the UTF-8 byte spine `bytes : Sym` and `byteCount`. + Scanning threads `remBytes : Sym` directly through `ParserState` in $O(1)$ per byte + with zero UTF-8 decoding overhead and $O(1)$ backtracking. -/ +structure InputContext where + bytes : Sym + byteCount : Nat + deriving Repr, Inhabited + +namespace InputContext + +@[inline] def bindNat (n : Nat) (k : Nat → α) : α := k n + +/-- Construct an `InputContext` directly from a UTF-8 `Sym` (`ByteList`). -/ +def mkInputContextFromBytes (bytes : Sym) : InputContext := + { bytes, byteCount := Sym.length bytes } + +/-- Host-only helper: construct an `InputContext` from a Lean `String`. -/ +def mkInputContext (input : String) (_fileName : String := "") : InputContext := + mkInputContextFromBytes (Sym.ofString input) + +@[inline] def size (c : InputContext) : Nat := c.byteCount + +@[inline] def atEnd (c : InputContext) (idx : Nat) : Bool := + Nat.ble c.byteCount idx + +/-- Host-only diagnostic helper: compute 1-based `(line, column)` for a byte index `idx`. -/ +def lineCol (c : InputContext) (idx : Nat) : Nat × Nat := + let rec go : Sym → Nat → Nat → Nat → Nat × Nat + | .nil, _, line, col => (line, col) + | _, 0, line, col => (line, col) + | .cons b rest, k + 1, line, col => + if Nat.beq b 10 then go rest k (line + 1) 1 + else if Nat.ble 128 b && Nat.ble b 191 then go rest k line col + else go rest k line (col + 1) + go c.bytes idx 1 1 + +end InputContext + +/-! ## `SyntaxStack` -/ + +/-- Pure syntax stack used by parser combinators to build `Stx` nodes. + Represented as a top-first list `rev` and cached `len` so `push`, `pop`, and `back` + are $O(1)$ constructor operations with zero `Array`/`Fin` proof terms. -/ +structure SyntaxStack where + rev : List Stx := [] + len : Nat := 0 + deriving Repr, Inhabited, BEq + +namespace SyntaxStack + +def empty : SyntaxStack := { rev := [], len := 0 } + +@[inline] def size (s : SyntaxStack) : Nat := s.len + +@[inline] def isEmpty (s : SyntaxStack) : Bool := Nat.beq s.len 0 + +def push (s : SyntaxStack) (stx : Stx) : SyntaxStack := + match s with + | ⟨rev, len⟩ => ⟨stx :: rev, Nat.add len 1⟩ + +def pop (s : SyntaxStack) : SyntaxStack := + match s with + | ⟨_ :: xs, len⟩ => ⟨xs, Nat.sub len 1⟩ + | ⟨[], _⟩ => ⟨[], 0⟩ + +def back (s : SyntaxStack) : Stx := + match s.rev with + | x :: _ => x + | [] => .missing + +def getD (s : SyntaxStack) (i : Nat) : Stx := + if Nat.ble s.len i then .missing + else Syntax.listGetD s.rev (Nat.sub (Nat.sub s.len 1) i) .missing + +/-- Pop `n` elements from the top of `rev`, accumulating them directly into a `Stx` list (`scons`/`snil`) + in left-to-right order (zero intermediate `List` → `Array` → `Stx` conversions!). -/ +def popTopNStx : Nat → List Stx → Stx → Stx × List Stx + | 0, rev, acc => (acc, rev) + | _, [], acc => (acc, []) + | n + 1, x :: rest, acc => popTopNStx n rest (.scons x acc) + +/-- Drop `n` elements from the top of `rev`. -/ +def dropTopN : Nat → List Stx → List Stx + | 0, rev => rev + | _, [] => [] + | n + 1, _ :: xs => dropTopN n xs + +def shrink (s : SyntaxStack) (newSize : Nat) : SyntaxStack := + match s with + | ⟨rev, len⟩ => + if Nat.ble len newSize then ⟨rev, len⟩ + else ⟨dropTopN (Nat.sub len newSize) rev, newSize⟩ + +@[inline] def bindList (xs : List α) (k : List α → β) : β := k xs + +end SyntaxStack + +/-! ## `ParserError` (Pure `Sym`, Zero `String`) -/ + +/-- Deterministic parse error with byte offset, unexpected message (`Sym`), and expected tokens (`List Sym`). -/ +structure ParserError where + pos : Nat := 0 + unexpected : Sym := .nil + expected : List Sym := [] + deriving Repr, Inhabited, BEq + +namespace ParserError + +def symMem (x : Sym) : List Sym → Bool + | [] => false + | y :: ys => if Sym.beq x y then true else symMem x ys + +def appendUnique : List Sym → List Sym → List Sym + | acc, [] => acc + | acc, x :: xs => + if symMem x acc then appendUnique acc xs + else appendUnique (x :: acc) xs + +def merge (e1 e2 : ParserError) : ParserError := + if Nat.ble (Nat.add e1.pos 1) e2.pos then e2 + else if Nat.ble (Nat.add e2.pos 1) e1.pos then e1 + else + { pos := e1.pos + unexpected := if Sym.isEmpty e1.unexpected then e2.unexpected else e1.unexpected + expected := appendUnique e1.expected e2.expected } + +/-- Host-only error formatting (never called inside circuit closure). -/ +def toString (ctx : InputContext) (e : ParserError) : String := + let (line, col) := ctx.lineCol e.pos + let unexp := if Sym.isEmpty e.unexpected then "parse error" else Sym.toString e.unexpected + let exp := match e.expected with + | [] => "" + | es => s!"; expected {strIntercalatePure ", " (es.map Sym.toString)}" + s!":{line}:{col}: {unexp}{exp}" + +end ParserError + +/-! ## `TokenCacheEntry` & `ParserState` -/ + +/-- Single-entry token lookahead cache to avoid re-scanning tokens after backtracking. -/ +structure TokenCacheEntry where + valid : Bool := false + startPos : Nat := 0 + stopPos : Nat := 0 + token : Stx := .missing + afterBytes : Sym := .nil + deriving Repr, Inhabited + +/-- Pure state threaded through every parser combinator. + Carries `remBytes : Sym` (`ByteList`) directly so lexing and backtracking are $O(1)$! -/ +structure ParserState where + stxStack : SyntaxStack := SyntaxStack.empty + lhsPrec : Nat := 0 + pos : Nat := 0 + remBytes : Sym := .nil + cache : TokenCacheEntry := {} + errorMsg : Option ParserError := none + deriving Repr, Inhabited + +namespace ParserState + +/-- Construct an initial `ParserState` positioned at the start of `bytes`. -/ +def init (bytes : Sym) : ParserState := + { remBytes := bytes } + +@[inline] def bindState (s : ParserState) (k : ParserState → α) : α := k s + +@[inline] def hasError (s : ParserState) : Bool := + s.errorMsg.isSome + +@[inline] def stackSize (s : ParserState) : Nat := + s.stxStack.size + +def restore (s : ParserState) (iniSz : Nat) (iniPos : Nat) (iniBytes : Sym) : ParserState := + match s with + | ⟨stack, lhsPrec, _, _, cache, _⟩ => + match stack.shrink iniSz with + | ⟨rev', len'⟩ => ⟨⟨rev', len'⟩, lhsPrec, iniPos, iniBytes, cache, none⟩ + +def setPos (s : ParserState) (newPos : Nat) (newBytes : Sym) : ParserState := + match s with + | ⟨stack, lhsPrec, _, _, cache, err⟩ => + ⟨stack, lhsPrec, newPos, newBytes, cache, err⟩ + +def pushSyntax (s : ParserState) (stx : Stx) : ParserState := + match s with + | ⟨stack, lhsPrec, pos, remBytes, cache, err⟩ => + match stack.push stx with + | ⟨rev', len'⟩ => ⟨⟨rev', len'⟩, lhsPrec, pos, remBytes, cache, err⟩ + +def popSyntax (s : ParserState) : ParserState := + match s with + | ⟨stack, lhsPrec, pos, remBytes, cache, err⟩ => + match stack.pop with + | ⟨rev', len'⟩ => ⟨⟨rev', len'⟩, lhsPrec, pos, remBytes, cache, err⟩ + +def shrinkStack (s : ParserState) (iniSz : Nat) : ParserState := + match s with + | ⟨stack, lhsPrec, pos, remBytes, cache, err⟩ => + match stack.shrink iniSz with + | ⟨rev', len'⟩ => ⟨⟨rev', len'⟩, lhsPrec, pos, remBytes, cache, err⟩ + +def mkNode (s : ParserState) (k : FName) (iniSz : Nat) : ParserState := + match s with + | ⟨stack, lhsPrec, pos, remBytes, cache, err⟩ => + if err.isSome && Nat.beq stack.len iniSz then + match stack.push .missing with + | ⟨rev', len'⟩ => ⟨⟨rev', len'⟩, lhsPrec, pos, remBytes, cache, err⟩ + else + let count := Nat.sub stack.len iniSz + match SyntaxStack.popTopNStx count stack.rev .snil with + | (children, restRev) => + let newStack : SyntaxStack := + ⟨Stx.node .none k children :: restRev, Nat.add iniSz 1⟩ + ⟨newStack, lhsPrec, pos, remBytes, cache, err⟩ + +def mkTrailingNode (s : ParserState) (k : FName) (iniSz : Nat) (lhsPrec : Nat) : ParserState := + match s with + | ⟨stack, _, pos, remBytes, cache, err⟩ => + let baseSz := Nat.sub iniSz 1 + let count := Nat.sub stack.len baseSz + match SyntaxStack.popTopNStx count stack.rev .snil with + | (children, restRev) => + let newStack : SyntaxStack := + ⟨Stx.node .none k children :: restRev, Nat.add baseSz 1⟩ + ⟨newStack, lhsPrec, pos, remBytes, cache, err⟩ + +def setError (s : ParserState) (e : ParserError) : ParserState := + match s with + | ⟨stack, lhsPrec, pos, remBytes, cache, _⟩ => ⟨stack, lhsPrec, pos, remBytes, cache, some e⟩ + +def mkError (s : ParserState) (expected : Sym) : ParserState := + match s with + | ⟨stack, lhsPrec, pos, remBytes, cache, _⟩ => + match stack.push .missing with + | ⟨rev', len'⟩ => + ⟨⟨rev', len'⟩, lhsPrec, pos, remBytes, cache, some { pos := pos, expected := [expected] }⟩ + +def mkUnexpectedError (s : ParserState) (msg : Sym) (expected : List Sym := []) : ParserState := + match s with + | ⟨stack, lhsPrec, pos, remBytes, cache, _⟩ => + ⟨stack, lhsPrec, pos, remBytes, cache, some { pos := pos, unexpected := msg, expected := expected }⟩ + +def mkEOIError (s : ParserState) (expected : List Sym := []) : ParserState := + s.mkUnexpectedError (s% "unexpected end of input") expected + +def mkErrorAt (s : ParserState) (expected : Sym) (errPos : Nat) (iniSz : Nat) + (iniBytes : Sym) : ParserState := + match s with + | ⟨stack, lhsPrec, _, _, cache, _⟩ => + match (stack.shrink iniSz).push .missing with + | ⟨rev', len'⟩ => + ⟨⟨rev', len'⟩, lhsPrec, errPos, iniBytes, cache, some { pos := errPos, expected := [expected] }⟩ + +end ParserState + +/-! ## `IxParserEnv`, Declarative `NotationRule` / `MacroRule`, & `IxParserContext` -/ + +/-- User-defined or builtin operator descriptor for the Pratt expression parser. -/ +inductive FixityKind where + | infixl + | infixr + | infixn + | prefixOp + | postfixOp + deriving BEq, DecidableEq, Repr, Inhabited + +structure OperatorSpec where + symbol : Sym + kind : FName + fixity : FixityKind + prec : Nat + targetFn : Option FName := none + deriving BEq, Repr, Inhabited + +/-- A single item in a user-defined mixfix `notation` or `macro` pattern. -/ +inductive NotationItem where + | sym (token : Sym) + | var (name : FName) (prec : Nat := 0) + deriving BEq, Repr, Inhabited + +/-- A grammar rule registered by `notation`, `syntax`, or `macro` in `IxParserEnv`. -/ +structure NotationRule where + ruleName : FName + prec : Nat := 65 + items : List NotationItem := [] + rhs : Stx := .missing + deriving BEq, Repr, Inhabited + +/-- A declarative pattern-matching macro expansion rule (`Stx → Stx`). -/ +structure MacroRule where + pat : Stx + rhs : Stx + deriving BEq, Repr, Inhabited + +/-- Look up a bound syntax tree for `id` in `bindings`. -/ +def lookupSyntaxBinding (id : FName) : List (FName × Stx) → Option Stx + | [] => none + | (k, v) :: rest => if FName.beq k id then some v else lookupSyntaxBinding id rest + +/-- Substitute macro pattern bindings `(varName, replacementStx)` into a template `Stx` tree. -/ +def substSyntaxVars : Nat → List (FName × Stx) → Stx → Stx + | 0, _, stx => stx + | fuel + 1, bindings, stx => + match stx with + | .ident _ _ id => + match lookupSyntaxBinding id bindings with + | some rep => rep + | none => stx + | .node info kind args => + if FName.beq kind SyntaxKindF.antiquotTerm then + let varId := Syntax.getIdF (args.getD 1 .missing) + match lookupSyntaxBinding varId bindings with + | some rep => rep + | none => stx + else + .node info kind (substSyntaxVarsList fuel bindings args) + | _ => stx +where + substSyntaxVarsList : Nat → List (FName × Stx) → Stx → Stx + | fuel, bindings, .scons h t => + .scons (substSyntaxVars fuel bindings h) (substSyntaxVarsList fuel bindings t) + | _, _, _ => .snil + +/-- Match a surface `Stx` node `stx` against a macro pattern `pat`, returning + `some bindings` if `stx` matches `pat`. -/ +def matchSyntaxPattern : Nat → Stx → Stx → List (FName × Stx) → Option (List (FName × Stx)) + | 0, _, _, _ => none + | fuel + 1, pat, stx, acc => + match pat with + | .node _ pKind pArgs => + if FName.beq pKind SyntaxKindF.antiquotTerm then + let varId := Syntax.getIdF (pArgs.getD 1 .missing) + if FName.isAnonymous varId then some acc + else some ((varId, stx) :: acc) + else + match stx with + | .node _ sKind sArgs => + if !FName.beq pKind sKind || !Nat.beq pArgs.size sArgs.size then none + else + if (FName.beq pKind SyntaxKindF.macroCall || FName.beq pKind SyntaxKindF.appTerm) && + Nat.ble 1 pArgs.size then + match pArgs, sArgs with + | .scons pHead pRest, .scons sHead sRest => + let headOk : Option (List (FName × Stx)) := + match pHead, sHead with + | .ident _ _ pId, .ident _ _ sId => + if FName.beq pId sId then some acc else none + | _, _ => matchSyntaxPattern fuel pHead sHead acc + match headOk with + | some acc1 => matchSyntaxChildren fuel pRest sRest acc1 + | none => none + | _, _ => none + else + matchSyntaxChildren fuel pArgs sArgs acc + | _ => none + | .ident _ _ patId => + if FName.isAnonymous patId then some acc + else some ((patId, stx) :: acc) + | .atom _ patVal => + match stx with + | .atom _ stxVal => if Sym.beq patVal stxVal then some acc else none + | _ => none + | .missing => some acc + | .snil | .scons .. => none +where + matchSyntaxChildren : Nat → Stx → Stx → List (FName × Stx) → Option (List (FName × Stx)) + | _, .snil, .snil, curAcc => some curAcc + | fuel, .scons pChild pRest, .scons sChild sRest, curAcc => + match matchSyntaxPattern fuel pChild sChild curAcc with + | some nextAcc => matchSyntaxChildren fuel pRest sRest nextAcc + | none => none + | _, _, _, _ => none + +/-- Try matching `stx` against the first applicable `MacroRule` in `rules`. -/ +def expandOneMacroStep? : List MacroRule → Stx → Option Stx + | [], _ => none + | r :: rs, stx => + match matchSyntaxPattern 64 r.pat stx [] with + | some bindings => some (substSyntaxVars 64 bindings r.rhs) + | none => expandOneMacroStep? rs stx + +/-- Expand top-level macro matches on `stx` up to `fuel` steps. -/ +def expandTopMacroPure : Nat → List MacroRule → Stx → Stx + | 0, _, stx => stx + | fuel + 1, rules, stx => + match rules with + | [] => stx + | _ => + match expandOneMacroStep? rules stx with + | some stx' => expandTopMacroPure fuel rules stx' + | none => stx + +/-- Pure parser environment holding token trie, reserved keywords, operators, and mixfix notations. -/ +structure IxParserEnv where + tokens : Trie Sym + keywords : Trie Bool + operators : List OperatorSpec := [] + notations : List NotationRule := [] + deriving Repr, Inhabited + +namespace IxParserEnv + +@[inline] def bindParserEnv (env : IxParserEnv) (k : IxParserEnv → α) : α := k env + +end IxParserEnv + +/-- Reader context for `ParserFn`. -/ +structure IxParserContext where + inputCtx : InputContext + env : IxParserEnv + prec : Nat := 0 + deriving Repr, Inhabited + +/-- A pure, total parser combinator. -/ +abbrev ParserFn := IxParserContext → ParserState → ParserState + +end Ix.Frontend.Parser diff --git a/Ix/Frontend/SccPass.lean b/Ix/Frontend/SccPass.lean new file mode 100644 index 0000000000..288fab741d --- /dev/null +++ b/Ix/Frontend/SccPass.lean @@ -0,0 +1,1364 @@ +/- + Ix.Frontend.SccPass: Pass 2 & Pass 3 of the Ix Frontend — + Binder-Aware Free Identifier Extraction and Tarjan SCC Dependency Scheduling. + + Enables order-free and `mutual`-free `.ix` source files: + - Declarations may appear in any top-to-bottom order without forward-reference errors. + - Mutual recursion (value-level or inductive) is inferred automatically via Tarjan's + strongly connected components algorithm (`Ix.Compile.Canon.condensation`). + - Typeclass `instance` declarations are automatically scheduled before declarations + that mention their carrier types whenever doing so does not introduce a cycle. +-/ +module + +public import Ix.Frontend.Scope +public import Ix.Compile.Canon.Graph + +@[expose] public section + +namespace Ix.Frontend + +open Ix.Frontend.Parser + +/-! ## Pass 2: Binder-Aware Syntax Reference Extraction -/ + +/-- Dependency summary extracted for a single `ModuleDecl`. -/ +structure DeclDepInfo where + declIdx : Nat + sigRefs : Array Nat := #[] + bodyRefs : Array Nat := #[] + carrierRefs : Array Nat := #[] + deriving Repr, Inhabited + +/-- Insert a declaration index `dIdx` into an `Array Nat` if not already present. -/ +def pushUniqueNat (arr : Array Nat) (x : Nat) : Array Nat := + if arr.toList.contains x then arr else arr.push x + +/-- Extract the bound variable names from a single binder `Syntax` node + (`explicitBinder`, `implicitBinder`, `strictImplicitBinder`, `instBinder`). -/ +def extractBinderNames (binderStx : Stx) : List Ix.Name := + let k := Syntax.getKind binderStx + if k == SyntaxKind.explicitBinder || k == SyntaxKind.implicitBinder || + k == SyntaxKind.strictImplicitBinder || k == SyntaxKind.instBinder then + let idsNode := Syntax.getArg binderStx 1 + (Syntax.getArgs idsNode).toList.filterMap fun idStx => + let id := Syntax.getId idStx + if Name.isAnonymous id then none else some id + else + let id := Syntax.getId binderStx + if Name.isAnonymous id then [] else [id] + +/-- Extract the optional type `Syntax` from a single binder node. -/ +def extractBinderType? (binderStx : Stx) : Option Stx := + let k := Syntax.getKind binderStx + if k == SyntaxKind.explicitBinder || k == SyntaxKind.implicitBinder || + k == SyntaxKind.strictImplicitBinder || k == SyntaxKind.instBinder then + let tyNode := Syntax.getArg binderStx 3 + if Syntax.isNone tyNode || Syntax.isMissing tyNode then none + else some tyNode + else + none + +/-- Extract pattern-bound variable names from a pattern `Syntax` tree, treating + known module/external constructors as constants rather than pattern variables. + Also records any constructor owner declaration indices into `accRefs`. -/ +def scanPattern (scope : ScopeSnapshot) (modIdx : ModuleIndex) + (isExtConst : Ix.Name → Bool) (isExtCtor : Ix.Name → Bool) : + Nat → Stx → NameSet × Array Nat → NameSet × Array Nat + | 0, _, state => state + | fuel + 1, pat, (bound, refs) => + match pat with + | .missing | .atom _ _ | .snil | .scons .. => (bound, refs) + | .ident _ _ idF => + let id := FName.toIxName idF + if Name.isAnonymous id then (bound, refs) + else + let resolved := resolveIdentInScope scope modIdx isExtConst id + match modIdx.ctorToInd.get? resolved with + | some (_, ownerIdx) => + (bound, pushUniqueNat refs ownerIdx) + | none => + if isExtCtor resolved then + (bound, refs) + else + -- Unqualified single-component identifier in pattern position binds a local variable + match id with + | .str (.anonymous _) _ _ => (bound.insert id, refs) + | _ => + match modIdx.findOwnerIdx? resolved with + | some ownerIdx => (bound, pushUniqueNat refs ownerIdx) + | none => (bound, refs) + | .node _ kindF args => + let kind := FName.toIxName kindF + if kind == SyntaxKind.numLit || kind == SyntaxKind.strLit || + kind == SyntaxKind.charLit || kind == SyntaxKind.holeTerm then + (bound, refs) + else if kind == SyntaxKind.appTerm then + -- Head of pattern application is typically a constructor + let fn := args.getD 0 .missing + let arg := args.getD 1 .missing + let (bound, refs) := match fn with + | .ident _ _ fnIdF => + let fnId := FName.toIxName fnIdF + let resolved := resolveIdentInScope scope modIdx isExtConst fnId + match modIdx.findOwnerIdx? resolved with + | some ownerIdx => (bound, pushUniqueNat refs ownerIdx) + | none => scanPattern scope modIdx isExtConst isExtCtor fuel fn (bound, refs) + | _ => scanPattern scope modIdx isExtConst isExtCtor fuel fn (bound, refs) + scanPattern scope modIdx isExtConst isExtCtor fuel arg (bound, refs) + else + args.foldl (fun st child => scanPattern scope modIdx isExtConst isExtCtor fuel child st) + (bound, refs) + +/-- Scan a sequence of binders left-to-right using `scanRec`, adding each binder's names to `locals` + after scanning its domain type. -/ +def scanBinderArray (scanRec : NameSet → Stx → Array Nat → Array Nat) + (locals : NameSet) (binders : Array Stx) (refs : Array Nat) : NameSet × Array Nat := + binders.toList.foldl (fun (loc, r) b => + let r' := match extractBinderType? b with + | some ty => scanRec loc ty r + | none => r + let names := extractBinderNames b + let loc' := names.foldl (fun s n => s.insert n) loc + (loc', r')) (locals, refs) + +/-- Collect bound local identifiers from an `rcases` / `obtain` / `rintro` pattern `Syntax` tree. -/ +def collectRcasesPatLocals : Nat → Stx → NameSet → NameSet + | 0, _, loc => loc + | fuel + 1, pat, loc => + let k := Syntax.getKind pat + if k == SyntaxKind.rcasesPatIdent then + let id := Syntax.getId (Syntax.getArg pat 0) + if Name.isAnonymous id then loc else loc.insert id + else if k == SyntaxKind.rcasesPatWildcard || k == SyntaxKind.rcasesPatRfl then + loc + else + (Syntax.getArgs pat).toList.foldl (fun acc child => collectRcasesPatLocals fuel child acc) loc + +/-- Scan a term/type/tactic `Syntax` tree with lexical `scope` and bound local variables `locals`, + accumulating indices of referenced module declarations in `refs`. + Structurally recursive on `fuel : Nat`. -/ +def scanSyntaxRefs (scope : ScopeSnapshot) (modIdx : ModuleIndex) + (isExtConst : Ix.Name → Bool) (isExtCtor : Ix.Name → Bool) : + Nat → NameSet → Stx → Array Nat → Array Nat + | 0, _, _, refs => refs + | fuel + 1, locals, stx0, refs => + let stx := + if modIdx.macroRules.isEmpty then stx0 + else expandTopMacroPure 16 modIdx.macroRules.toList stx0 + let scanRec := scanSyntaxRefs scope modIdx isExtConst isExtCtor fuel + match stx with + | .missing | .atom _ _ | .snil | .scons .. => refs + | .ident _ _ idF => + let id := FName.toIxName idF + if Name.isAnonymous id || locals.contains id then + refs + else + let resolved := resolveIdentInScope scope modIdx isExtConst id + match modIdx.findOwnerIdx? resolved with + | some ownerIdx => pushUniqueNat refs ownerIdx + | none => + -- Also check if `id` is a hierarchical projection `.` + match id with + | .str pre _ _ => + if !Name.isAnonymous pre && !locals.contains pre then + let resPre := resolveIdentInScope scope modIdx isExtConst pre + match modIdx.findOwnerIdx? resPre with + | some ownerIdx => pushUniqueNat refs ownerIdx + | none => refs + else + refs + | _ => refs + | .node _ kindF args => + let kind := FName.toIxName kindF + -- 0. Fast path for leaf and non-binding expression nodes (avoids 15 `kind ==` checks) + if kind == SyntaxKind.numLit || kind == SyntaxKind.strLit || + kind == SyntaxKind.charLit || kind == SyntaxKind.propTerm || + kind == SyntaxKind.typeTerm || kind == SyntaxKind.binderPrefix || + kind == SyntaxKind.valuePrefix || kind == SyntaxKind.holeTerm then + refs + else if kind == SyntaxKind.nullKind || kind == SyntaxKind.binOpTerm || + kind == SyntaxKind.appTerm || kind == SyntaxKind.arrowTerm || + kind == SyntaxKind.parenTerm then + args.toList.foldl (fun acc child => scanRec locals child acc) refs + -- 1. `fun binders => body` + else if kind == SyntaxKind.funTerm then + let binders := Syntax.getArgs (args.getD 1 .missing) + let body := args.getD 3 .missing + let (locals', refs') := scanBinderArray scanRec locals binders refs + scanRec locals' body refs' + -- 2. `forall binders, vPref body` or `(binders) → vPref body` + else if kind == SyntaxKind.forallTerm then + let isKwForall := match args[0]? with + | some (.atom _ kw) => Sym.beq kw (s% "forall") || Sym.beq kw (s% "∀") + | _ => false + let binders := Syntax.getArgs (if isKwForall then args.getD 1 .missing else args.getD 0 .missing) + let body := if isKwForall then args.getD 4 .missing else args.getD 3 .missing + let (locals', refs') := scanBinderArray scanRec locals binders refs + scanRec locals' body refs' + -- 3. `let bPref id binders optType := val; body` + else if kind == SyntaxKind.letTerm then + let idStx := args.getD 2 .missing + let binders := Syntax.getArgs (args.getD 3 .missing) + let optTy := args.getD 4 .missing + let val := args.getD 6 .missing + let body := args.getD 8 .missing + let (localsBind, refs) := scanBinderArray scanRec locals binders refs + let refs := scanRec localsBind optTy refs + let refs := scanRec localsBind val refs + let letId := Syntax.getId idStx + let localsBody := if Name.isAnonymous letId then locals else locals.insert letId + scanRec localsBody body refs + -- 4. `let borrow bPref id binders optType := val; body` + else if kind == SyntaxKind.letBorrowTerm then + let idStx := args.getD 3 .missing + let binders := Syntax.getArgs (args.getD 4 .missing) + let optTy := args.getD 5 .missing + let val := args.getD 7 .missing + let body := args.getD 9 .missing + let (localsBind, refs) := scanBinderArray scanRec locals binders refs + let refs := scanRec localsBind optTy refs + let refs := scanRec localsBind val refs + let letId := Syntax.getId idStx + let localsBody := if Name.isAnonymous letId then locals else locals.insert letId + scanRec localsBody body refs + -- 4b. `let rec bPref id binders optType := val; body` (`letId` is in scope inside `val` too) + else if kind == SyntaxKind.letRecTerm then + let idStx := args.getD 3 .missing + let binders := Syntax.getArgs (args.getD 4 .missing) + let optTy := args.getD 5 .missing + let val := args.getD 7 .missing + let body := args.getD 9 .missing + let letId := Syntax.getId idStx + let localsWithId := if Name.isAnonymous letId then locals else locals.insert letId + let (localsBind, refs) := scanBinderArray scanRec localsWithId binders refs + let refs := scanRec localsBind optTy refs + let refs := scanRec localsBind val refs + scanRec localsWithId body refs + -- 5. `have id optType := val; body` + else if kind == SyntaxKind.haveTerm then + let idStx := args.getD 1 .missing + let optTy := args.getD 2 .missing + let val := args.getD 4 .missing + let body := args.getD 6 .missing + let refs := scanRec locals optTy refs + let refs := scanRec locals val refs + let haveId := Syntax.getId idStx + let localsBody := if Name.isAnonymous haveId then locals else locals.insert haveId + scanRec localsBody body refs + -- 6. `if [h :] cond then t else e` + else if kind == SyntaxKind.ifTerm then + if args.size == 8 then + let hId := Syntax.getId (args.getD 1 .missing) + let cond := args.getD 3 .missing + let thenBr := args.getD 5 .missing + let elseBr := args.getD 7 .missing + let refs := scanRec locals cond refs + let locals' := if Name.isAnonymous hId then locals else locals.insert hId + let refs := scanRec locals' thenBr refs + scanRec locals' elseBr refs + else + let cond := args.getD 2 .missing + let thenBr := args.getD 4 .missing + let elseBr := args.getD 6 .missing + let refs := scanRec locals cond refs + let refs := scanRec locals thenBr refs + scanRec locals elseBr refs + -- 7. `| pat1, pat2 => rhs` (`matchAlt`) + else if kind == SyntaxKind.matchAlt then + let pats := Syntax.getArgs (args.getD 1 .missing) + let rhs := args.getD 3 .missing + let (locals', refs') := pats.foldl + (fun st p => scanPattern scope modIdx isExtConst isExtCtor fuel p st) + (locals, refs) + scanRec locals' rhs refs' + -- 8. Projection `base.field`: scan `base`, and also check if `field` is a known structure field + else if kind == SyntaxKind.projTerm then + let base := args.getD 0 .missing + let fieldNode := args.getD 2 .missing + let refs := scanRec locals base refs + let fieldId := Syntax.getId fieldNode + if Name.isAnonymous fieldId then refs + else + -- Check if base is an identifier prefix + let refs := match base with + | .ident _ _ bIdF => + let bId := FName.toIxName bIdF + if !locals.contains bId then + let combined := Name.append bId fieldId + let resCombined := resolveIdentInScope scope modIdx isExtConst combined + match modIdx.findOwnerIdx? resCombined with + | some ownerIdx => pushUniqueNat refs ownerIdx + | none => refs + else refs + | _ => refs + refs + -- 9. Tactic sequence: handle `intro`, `rintro`, `rcases`, `obtain`, `funext`, `ext`, `have`, `let`, + -- `suffices`, `generalize`, `by_cases`, `by_contra`, `cases`/`induction`/`case` alternatives + else if kind == SyntaxKind.tacticSeq then + let (_, refs') := args.foldl (fun (loc, r) tac => + let tk := Syntax.getKind tac + if tk == SyntaxKind.tacticIntro || tk == SyntaxKind.tacticFunext || tk == SyntaxKind.tacticExt then + let ids := (Syntax.getArgs (Syntax.getArg tac 1)).toList.map Syntax.getId + let loc' := ids.foldl (fun s id => if Name.isAnonymous id then s else s.insert id) loc + (loc', r) + else if tk == SyntaxKind.tacticRintro then + let pats := (Syntax.getArgs (Syntax.getArg tac 1)).toList + let optTy := Syntax.getArg tac 2 + let r := scanRec loc optTy r + let loc' := pats.foldl (fun s p => collectRcasesPatLocals 32 p s) loc + (loc', r) + else if tk == SyntaxKind.tacticRcases then + let targets := Syntax.getArg tac 1 + let pat := Syntax.getArg tac 2 + let r := scanRec loc targets r + let loc' := collectRcasesPatLocals 32 pat loc + (loc', r) + else if tk == SyntaxKind.tacticObtain then + let pat := Syntax.getArg tac 1 + let optTy := Syntax.getArg tac 2 + let val := Syntax.getArg tac 4 + let r := scanRec loc optTy r + let r := scanRec loc val r + let loc' := collectRcasesPatLocals 32 pat loc + (loc', r) + else if tk == SyntaxKind.tacticHave || tk == SyntaxKind.tacticLet then + let lId := Syntax.getId (Syntax.getArg tac 1) + let optTy := Syntax.getArg tac 2 + let val := Syntax.getArg tac 4 + let r := scanRec loc optTy r + let r := scanRec loc val r + let loc' := if Name.isAnonymous lId then loc else loc.insert lId + (loc', r) + else if tk == SyntaxKind.tacticSuffices then + let lId := Syntax.getId (Syntax.getArg tac 1) + let ty := Syntax.getArg tac 2 + let body := Syntax.getArg tac 4 + let r := scanRec loc ty r + let loc' := if Name.isAnonymous lId then loc else loc.insert lId + let r := scanRec loc' body r + (loc', r) + else if tk == SyntaxKind.tacticGeneralize then + let hId := Syntax.getId (Syntax.getArg tac 1) + let eStx := Syntax.getArg tac 2 + let xId := Syntax.getId (Syntax.getArg tac 4) + let r := scanRec loc eStx r + let loc1 := if Name.isAnonymous xId then loc else loc.insert xId + let loc2 := if Name.isAnonymous hId then loc1 else loc1.insert hId + (loc2, r) + else if tk == SyntaxKind.tacticByCases then + let hId := Syntax.getId (Syntax.getArg tac 1) + let pStx := Syntax.getArg tac 2 + let r := scanRec loc pStx r + let loc' := if Name.isAnonymous hId then loc else loc.insert hId + (loc', r) + else if tk == SyntaxKind.tacticByContra then + let hId := Syntax.getId (Syntax.getArg tac 1) + let loc' := if Name.isAnonymous hId then loc else loc.insert hId + (loc', r) + else + (loc, scanRec loc tac r) + ) (locals, refs) + refs' + else if kind == SyntaxKind.tacticAlt || kind == SyntaxKind.tacticCase then + -- `| tag x y => tacSeq` or `case tag x y => tacSeq` + let boundIds := (Syntax.getArgs (args.getD 2 .missing)).toList.map Syntax.getId + let locals' := boundIds.foldl (fun s id => if Name.isAnonymous id then s else s.insert id) locals + let seq := args.getD 4 .missing + scanRec locals' seq refs + else if kind == SyntaxKind.tacticRw then + -- `rw [rules] [at hyp]`: scan only `rules` (`args[2]`), since `hyp` is a local hypothesis + scanRec locals (args.getD 2 .missing) refs + else if kind == SyntaxKind.tacticSimp || kind == SyntaxKind.tacticDSimp then + -- `simp [only] [rules] [at hyp]`: scan `rules` (`args[2]` if size >= 4 else `args[1]`) + let rulesNode := if args.size ≥ 4 then args.getD 2 .missing else args.getD 1 .missing + scanRec locals rulesNode refs + else if kind == SyntaxKind.tacticClear || kind == SyntaxKind.tacticRevert || + kind == SyntaxKind.tacticSubst then + -- Arguments are local hypothesis names + refs + else if kind == SyntaxKind.tacticSpecialize then + -- `specialize h a₁ a₂ ...`: `args[1]` is local hyp `h`, `args[2]` is `nullKind` of term args + scanRec locals (args.getD 2 .missing) refs + else + -- Default: scan all child syntax nodes with the same `locals` + args.toList.foldl (fun acc child => + scanRec locals child acc) refs + +/-- Extract `DeclDepInfo` (`sigRefs`, `bodyRefs`, `carrierRefs`) for a single `ModuleDecl`. -/ +def extractDeclDeps (modIdx : ModuleIndex) (decl : ModuleDecl) + (isExtConst : Ix.Name → Bool := fun _ => false) + (isExtCtor : Ix.Name → Bool := fun _ => false) + (fuel : Nat := 256) : DeclDepInfo := + let scope := decl.scope + let cmd := decl.stx + let k := Syntax.getKind cmd + let scanRec := scanSyntaxRefs scope modIdx isExtConst isExtCtor fuel + -- 1. Scan section `variable` binders into `sigRefs` and initial `locals` + let (locals0, sigRefs0) := + scanBinderArray scanRec NameSet.empty scope.varBinders #[] + if k == SyntaxKind.defDecl || k == SyntaxKind.abbrevDecl || + k == SyntaxKind.theoremDecl || k == SyntaxKind.opaqueDecl then + let binders := Syntax.getArgs (Syntax.getArg cmd 4) + let optType := Syntax.getArg cmd 6 + let (localsSig, sigRefs) := + scanBinderArray scanRec locals0 binders sigRefs0 + let sigRefs := scanRec localsSig optType sigRefs + let bodyNode := + if Syntax.getNumArgs cmd == 9 then Syntax.getArg cmd 8 + else Syntax.getArg cmd 7 + let bodyRefs := scanRec localsSig bodyNode #[] + { declIdx := decl.idx, sigRefs, bodyRefs } + else if k == SyntaxKind.axiomDecl then + let binders := Syntax.getArgs (Syntax.getArg cmd 4) + let ty := Syntax.getArg cmd 6 + let (localsSig, sigRefs) := + scanBinderArray scanRec locals0 binders sigRefs0 + let sigRefs := scanRec localsSig ty sigRefs + { declIdx := decl.idx, sigRefs, bodyRefs := #[] } + else if k == SyntaxKind.instanceDecl then + let binders := Syntax.getArgs (Syntax.getArg cmd 4) + let ty := Syntax.getArg cmd 6 + let (localsSig, sigRefs) := + scanBinderArray scanRec locals0 binders sigRefs0 + let tyRefs := scanRec localsSig ty #[] + let sigRefs := tyRefs.foldl pushUniqueNat sigRefs + let bodyNode := Syntax.getArg cmd 8 + let bodyRefs := scanRec localsSig bodyNode #[] + { declIdx := decl.idx, sigRefs, bodyRefs, carrierRefs := tyRefs } + else if k == SyntaxKind.inductiveDecl then + -- args: #[modifiers, "inductive", id, univParams, binders, vPref, optType, ctorsNull, derivingNull] + let binders := Syntax.getArgs (Syntax.getArg cmd 4) + let optType := Syntax.getArg cmd 6 + let ctorsNode := Syntax.getArg cmd 7 + let derivNode := Syntax.getArg cmd 8 + let (localsSig, sigRefs) := + scanBinderArray scanRec locals0 binders sigRefs0 + let sigRefs := scanRec localsSig optType sigRefs + let bodyRefs := (Syntax.getArgs ctorsNode).foldl (fun acc ctorStx => + -- ctorDecl: #["|", id, binders, vPref, optType] + let cBinders := Syntax.getArgs (Syntax.getArg ctorStx 2) + let cOptType := Syntax.getArg ctorStx 4 + let (localsCtor, acc) := + scanBinderArray scanRec localsSig cBinders acc + scanRec localsCtor cOptType acc) #[] + let bodyRefs := scanRec localsSig derivNode bodyRefs + { declIdx := decl.idx, sigRefs, bodyRefs } + else if k == SyntaxKind.structureDecl || k == SyntaxKind.classDecl then + -- args: #[modifiers, kw, id, univParams, binders, extendsNull, vPref, optType, customCtorOrNull, fieldsOrCtorsNull, derivingNull] + let binders := Syntax.getArgs (Syntax.getArg cmd 4) + let extendsNode := Syntax.getArg cmd 5 + let optType := Syntax.getArg cmd 7 + let fieldsOrCtorsNode := Syntax.getArg cmd 9 + let derivNode := Syntax.getArg cmd 10 + let (localsSig, sigRefs) := + scanBinderArray scanRec locals0 binders sigRefs0 + let sigRefs := scanRec localsSig extendsNode sigRefs + let sigRefs := scanRec localsSig optType sigRefs + -- Scan fields sequentially (each field name becomes bound for subsequent dependent fields!) + let (_, bodyRefs) := (Syntax.getArgs fieldsOrCtorsNode).foldl (fun (loc, acc) item => + if Syntax.isOfKind item SyntaxKind.ctorDecl then + let cBinders := Syntax.getArgs (Syntax.getArg item 2) + let cOptType := Syntax.getArg item 4 + let (locCtor, acc) := + scanBinderArray scanRec loc cBinders acc + (loc, scanRec locCtor cOptType acc) + else if Syntax.isOfKind item SyntaxKind.fieldDecl then + let fArgs := Syntax.getArgs item + let isBracketed := match fArgs[0]? with + | some (.atom _ (s% "(")) | some (.atom _ (s% "{")) => true + | _ => false + let idsNode := if isBracketed then Syntax.getArg item 2 else Syntax.getArg item 1 + let tyNode := if isBracketed then Syntax.getArg item 5 else Syntax.getArg item 4 + let defNode := if isBracketed then Syntax.getArg item 6 else Syntax.getArg item 5 + let acc := scanRec loc tyNode acc + let acc := scanRec loc defNode acc + let fIds := (Syntax.getArgs idsNode).toList.map Syntax.getId + let loc' := fIds.foldl (fun s id => if Name.isAnonymous id then s else s.insert id) loc + (loc', acc) + else + (loc, scanRec loc item acc) + ) (localsSig, #[]) + let bodyRefs := scanRec localsSig derivNode bodyRefs + { declIdx := decl.idx, sigRefs, bodyRefs } + else + { declIdx := decl.idx } + +/-! ## Pass 3: Tarjan SCC Condensation & Intra-SCC Topological Ordering -/ + +/-- Check whether node `src` can reach `dst` in `adj` (fuel-bounded DFS). -/ +def reachesNode (adj : Array (Array Nat)) (src dst : Nat) : Bool := + let rec dfs (fuel : Nat) (stack : List Nat) (visited : Array Bool) : Bool := + match fuel, stack with + | 0, _ | _, [] => false + | fuel + 1, u :: rest => + if u == dst then true + else if visited.getD u false then + dfs fuel rest visited + else + let visited' := if u < visited.size then visited.set! u true else visited + let nbrs := (adj.getD u #[]).toList + dfs fuel (nbrs ++ rest) visited' + dfs (adj.size * adj.size + 16) [src] (Array.replicate adj.size false) + +/-- Add cycle-safe scheduling edges `u -> instIdx` whenever declaration `u` + references a carrier/class type in `inst.carrierRefs` and `instIdx` does not + reach `u` in `adj`. Ensures `instance`s are elaborated before declarations + that need them for typeclass synthesis without ever creating false mutual cycles. -/ +def addInstanceSchedulingEdges (decls : Array ModuleDecl) (deps : Array DeclDepInfo) + (adj : Array (Array Nat)) : Array (Array Nat) := + let instInfos := deps.toList.filter fun d => + match Syntax.listGet? decls.toList d.declIdx with + | some decl => decl.kind == .inst && !d.carrierRefs.isEmpty + | none => false + instInfos.foldl (fun curAdj inst => + let instIdx := inst.declIdx + (List.range decls.size).foldl (fun accAdj u => + if u == instIdx then accAdj + else + let uDep := Syntax.listGetD deps.toList u { declIdx := u } + let uAllRefs := uDep.sigRefs ++ uDep.bodyRefs + let mentionsCarrier := inst.carrierRefs.toList.any fun c => uAllRefs.toList.contains c + let curRow := Syntax.listGetD accAdj.toList u #[] + if mentionsCarrier && !curRow.toList.contains instIdx && + !reachesNode accAdj instIdx u then + accAdj.set! u (curRow.push instIdx) + else + accAdj) curAdj) adj + +/-- Total, proof-free element lookup on `Array α` via `List` structural recursion + (avoids `Array.getElem` proof obligations during kernel reduction). -/ +def arrayGetD (xs : Array α) (i : Nat) (d : α) : α := + let rec go : List α → Nat → α + | [], _ => d + | x :: _, 0 => x + | _ :: rest, k + 1 => go rest k + go xs.toList i + +/-- Total, proof-free in-bounds element update on `Array α` via `List` structural recursion. -/ +def arraySetD (xs : Array α) (i : Nat) (v : α) : Array α := + let rec go : List α → Nat → List α + | [], _ => [] + | _ :: rest, 0 => v :: rest + | x :: rest, k + 1 => x :: go rest k + Array.mk (go xs.toList i) + +/-- Pure, total insertion sort on `Array α` (avoids `Array.qsort` and `Array.foldlM.loop`). -/ +def sortArrayBy (xs : Array α) (lt : α → α → Bool) : Array α := + let rec insert (x : α) : List α → List α + | [] => [x] + | y :: ys => if lt y x then y :: insert x ys else x :: y :: ys + Array.mk (xs.toList.foldl (fun acc x => insert x acc) []) + +/-- Visit node `v` in `TarjanState` using pure `arraySetD`. -/ +def tarjanVisit : Ix.Compile.Canon.TarjanState → Nat → Ix.Compile.Canon.TarjanState + | { index, low, onStack, stack, calls, next, comps, roots, order, exhausted }, v => + { index := arraySetD index v next, low := arraySetD low v next, + onStack := arraySetD onStack v true, stack := v :: stack, calls := (v, 0) :: calls, + next := next + 1, comps, roots, order := order.push v, exhausted } + +/-- Update `low[v] := x` in `TarjanState` using pure `arraySetD`. -/ +def tarjanSetLow : Ix.Compile.Canon.TarjanState → Nat → Nat → Ix.Compile.Canon.TarjanState + | { index, low, onStack, stack, calls, next, comps, roots, order, exhausted }, v, x => + { index, low := arraySetD low v x, onStack, stack, calls, next, comps, roots, order, exhausted } + +/-- Pop a component rooted at `v` off `TarjanState` using pure `sortArrayBy` (no `Array.qsort`). -/ +def tarjanPopComp : Ix.Compile.Canon.TarjanState → Nat → Ix.Compile.Canon.TarjanState + | { index, low, onStack, stack, calls, next, comps, roots, order, exhausted }, v => + let rec go : List Nat → Array Nat → Array Bool → List Nat × Array Nat × Array Bool + | [], comp, on => ([], comp, on) + | w :: ws, comp, on => + let comp := comp.push w + let on := arraySetD on w false + if w == v then (ws, comp, on) else go ws comp on + let (stack, comp, onStack) := go stack #[] onStack + { index, low, onStack, stack, calls, next, comps := comps.push (sortArrayBy comp (· < ·)), + roots := roots.push v, order, exhausted } + +/-- Pure, structurally recursive Tarjan DFS loop without `Array.qsort` or `Array.getElem` proofs. -/ +def tarjanDfsLoop (adj : Array (Array Nat)) : Nat → Ix.Compile.Canon.TarjanState → Ix.Compile.Canon.TarjanState + | 0, st => if st.calls.isEmpty then st else { st with exhausted := true } + | fuel + 1, st => + match st.calls with + | [] => st + | (v, i) :: rest => + let succs := arrayGetD adj v #[] + if i < succs.size then + let w := arrayGetD succs i 0 + let st := { st with calls := (v, i + 1) :: rest } + let iw := arrayGetD st.index w 0 + if iw == 0 then + tarjanDfsLoop adj fuel (tarjanVisit st w) + else if arrayGetD st.onStack w false then + let lv := arrayGetD st.low v 0 + tarjanDfsLoop adj fuel (tarjanSetLow st v (min lv iw)) + else tarjanDfsLoop adj fuel st + else + let lv := arrayGetD st.low v 0 + let iv := arrayGetD st.index v 0 + let st := { st with calls := rest } + let st := if lv == iv then tarjanPopComp st v else st + let st := match rest with + | (u, _) :: _ => + let lu := arrayGetD st.low u 0 + tarjanSetLow st u (min lu lv) + | [] => st + tarjanDfsLoop adj fuel st + +/-- Total Tarjan SCC condensation using pure `sortArrayBy` and `List` recursion. -/ +def tarjanCondensation (adj : Array (Array Nat)) : Option Ix.Compile.Canon.Condensation := + let n := adj.size + let adj := Array.mk (adj.toList.map (fun row => Array.mk (row.toList.filter (· < n)))) + let edges := adj.toList.foldl (init := 0) (· + ·.size) + let init : Ix.Compile.Canon.TarjanState := + { index := Array.mk (List.replicate n 0), low := Array.mk (List.replicate n 0), + onStack := Array.mk (List.replicate n false) } + let (st, _) := (List.range n).foldl (init := (init, edges + n + 1)) + fun (st, fuel) r => + if st.exhausted || arrayGetD st.index r 0 != 0 then (st, fuel) + else (tarjanDfsLoop adj fuel (tarjanVisit st r), fuel) + if st.exhausted then none + else some { comps := st.comps, roots := st.roots, order := st.order } + +/-- Topologically order members of a single SCC `comp` by signature dependencies (`sigRefs`), + breaking ties by original source declaration order (`u < v`). -/ +def sortSccBySigRefs (comp : Array Nat) (deps : Array DeclDepInfo) : Array Nat := + if comp.size ≤ 1 then comp + else + let sortedComp := sortArrayBy comp (· < ·) + let rec pickLoop (fuel : Nat) (remaining : List Nat) (placed : Array Nat) : Array Nat := + match fuel, remaining with + | 0, rem => placed ++ rem.toArray + | _, [] => placed + | fuel + 1, rem => + -- Pick the first element in `rem` whose `sigRefs` inside `comp` are all already in `placed` + let ready? := rem.find? fun u => + let sig := (deps.getD u { declIdx := u }).sigRefs + sig.all fun v => v == u || !comp.contains v || placed.contains v + let chosen := ready?.getD (rem.headD 0) + let rem' := rem.filter (· != chosen) + pickLoop fuel rem' (placed.push chosen) + pickLoop (sortedComp.size + 1) sortedComp.toList #[] + +/-- Classification of a scheduled Strongly Connected Component of top-level declarations. -/ +inductive SccKind where + | singleNonRec + | singleRec + | mutualInductive + | mutualDef + | mixedMutual + deriving BEq, DecidableEq, Repr, Inhabited + +/-- A single scheduled SCC ready for elaboration. -/ +structure ScheduledSCC where + sccIdx : Nat + kind : SccKind + declIdxs : Array Nat + deriving Repr, Inhabited + +/-- Complete dependency and topological schedule for a parsed `.ix` module. -/ +structure ModuleSchedule where + modIdx : ModuleIndex + deps : Array DeclDepInfo + explicitAdj : Array (Array Nat) + fullAdj : Array (Array Nat) + sccs : Array ScheduledSCC + deriving Repr, Inhabited + +/-- Classify a strongly connected component `comp` given `modIdx` and `explicitAdj`. -/ +def classifyScc (modIdx : ModuleIndex) (explicitAdj : Array (Array Nat)) + (comp : Array Nat) : SccKind := + if comp.size == 1 then + let u := arrayGetD comp 0 0 + if (arrayGetD explicitAdj u #[]).toList.contains u then .singleRec else .singleNonRec + else + let allInd := comp.toList.all fun u => + match Syntax.listGet? modIdx.decls.toList u with + | some d => d.kind == .ind || d.kind == .struct || d.kind == .cls + | none => false + let allVal := comp.toList.all fun u => + match Syntax.listGet? modIdx.decls.toList u with + | some d => d.kind == .defn || d.kind == .abbrev || d.kind == .thm || d.kind == .inst + | none => false + if allInd then .mutualInductive + else if allVal then .mutualDef + else .mixedMutual + +/-- Run Pass 2 and Pass 3 on `modIdx : ModuleIndex` to compute the Tarjan SCC elaboration schedule. -/ +def scheduleModuleDecls (modIdx : ModuleIndex) + (isExtConst : Ix.Name → Bool := fun _ => false) + (isExtCtor : Ix.Name → Bool := fun _ => false) : Except String ModuleSchedule := do + let n := modIdx.decls.size + let deps := Array.mk (modIdx.decls.toList.map fun d => extractDeclDeps modIdx d isExtConst isExtCtor) + -- Build explicit adjacency list `explicitAdj[u]` (including self-edges for `classifyScc`) + let explicitAdj : Array (Array Nat) := Array.mk (deps.toList.map fun d => + let all := d.sigRefs.toList.foldl pushUniqueNat #[] + d.bodyRefs.toList.foldl pushUniqueNat all) + -- Build condensation adjacency list (without self-loops) + cycle-safe instance edges + let baseAdj : Array (Array Nat) := Array.mk (explicitAdj.toList.zipIdx.map fun (nbrs, u) => + Array.mk (nbrs.toList.filter (· != u))) + let fullAdj := addInstanceSchedulingEdges modIdx.decls deps baseAdj + if fullAdj.toList.all (·.isEmpty) then + let sccs : Array ScheduledSCC := Array.mk ((List.range n).map fun sccIdx => + let comp := #[sccIdx] + let kind := classifyScc modIdx explicitAdj comp + { sccIdx, kind, declIdxs := comp }) + return { modIdx, deps, explicitAdj, fullAdj, sccs } + else + match tarjanCondensation fullAdj with + | none => + throw (str% "internal error: Tarjan SCC condensation failed") + | some cond => + let sccs : Array ScheduledSCC := Array.mk (cond.comps.toList.zipIdx.map fun (rawComp, sccIdx) => + let orderedComp := sortSccBySigRefs rawComp deps + let kind := classifyScc modIdx explicitAdj orderedComp + { sccIdx, kind, declIdxs := orderedComp }) + let _ := n + return { modIdx, deps, explicitAdj, fullAdj, sccs } + +/-- End-to-end Pass 1 + Pass 2 + Pass 3: parse `.ix` module syntax into a `ModuleSchedule`. -/ +def analyzeModuleSyntax (moduleStx : Stx) + (isExtConst : Ix.Name → Bool := fun _ => false) + (isExtCtor : Ix.Name → Bool := fun _ => false) : Except String ModuleSchedule := do + let modIdx ← buildModuleIndex moduleStx + scheduleModuleDecls modIdx isExtConst isExtCtor + +/-! ## First-Order Map-Based Pass 2 & Pass 3 (Zero Closures for `IxCCAiur`) -/ + +@[inline] def isExtCtorMap (envConsts : NameMap Ix.ConstantInfo) (nm : Ix.Name) : Bool := + match envConsts.get? nm with + | some (.ctorInfo _) => true + | _ => false + +def insertNameList (s : NameSet) : List Ix.Name → NameSet + | [] => s + | n :: rest => insertNameList (if Name.isAnonymous n then s else s.insert n) rest + +def insertBinderIdNodes (s : NameSet) : List Stx → NameSet + | [] => s + | idStx :: rest => + let id := Syntax.getId idStx + insertBinderIdNodes (if Name.isAnonymous id then s else s.insert id) rest + +def insertBinderStxNames (s : NameSet) (binderStx : Stx) : NameSet := + let k := Syntax.getKind binderStx + if k == SyntaxKind.explicitBinder || k == SyntaxKind.implicitBinder || + k == SyntaxKind.strictImplicitBinder || k == SyntaxKind.instBinder then + insertBinderIdNodes s (Syntax.getArgs (Syntax.getArg binderStx 1)).toList + else + let id := Syntax.getId binderStx + if Name.isAnonymous id then s else s.insert id + +def collectRcasesPatLocalsPure : Nat → Stx → NameSet → NameSet + | 0, _, loc => loc + | fuel + 1, pat, loc => + let k := Syntax.getKind pat + if k == SyntaxKind.rcasesPatIdent then + let id := Syntax.getId (Syntax.getArg pat 0) + if Name.isAnonymous id then loc else loc.insert id + else if k == SyntaxKind.rcasesPatWildcard || k == SyntaxKind.rcasesPatRfl then + loc + else + let rec goArgs (acc : NameSet) : List Stx → NameSet + | [] => acc + | child :: rest => goArgs (collectRcasesPatLocalsPure fuel child acc) rest + goArgs loc (Syntax.getArgs pat).toList + +def scanPatternMap (scope : ScopeSnapshot) (modIdx : ModuleIndex) + (envConsts : NameMap Ix.ConstantInfo) : + Nat → Stx → NameSet × Array Nat → NameSet × Array Nat + | 0, _, state => state + | fuel + 1, pat, (bound, refs) => + match pat with + | .missing | .atom _ _ | .snil | .scons .. => (bound, refs) + | .ident _ _ idF => + let id := FName.toIxName idF + if Name.isAnonymous id then (bound, refs) + else + let resolved := resolveIdentInScopeMap scope modIdx envConsts id + match modIdx.ctorToInd.get? resolved with + | some (_, ownerIdx) => (bound, pushUniqueNat refs ownerIdx) + | none => + if isExtCtorMap envConsts resolved then (bound, refs) + else + match id with + | .str (.anonymous _) _ _ => (bound.insert id, refs) + | _ => + match modIdx.findOwnerIdx? resolved with + | some ownerIdx => (bound, pushUniqueNat refs ownerIdx) + | none => (bound, refs) + | .node _ kindF args => + let kind := FName.toIxName kindF + if kind == SyntaxKind.numLit || kind == SyntaxKind.strLit || + kind == SyntaxKind.charLit || kind == SyntaxKind.holeTerm then + (bound, refs) + else if kind == SyntaxKind.appTerm then + let fn := args.getD 0 .missing + let arg := args.getD 1 .missing + let (bound, refs) := match fn with + | .ident _ _ fnIdF => + let fnId := FName.toIxName fnIdF + let resolved := resolveIdentInScopeMap scope modIdx envConsts fnId + match modIdx.findOwnerIdx? resolved with + | some ownerIdx => (bound, pushUniqueNat refs ownerIdx) + | none => scanPatternMap scope modIdx envConsts fuel fn (bound, refs) + | _ => scanPatternMap scope modIdx envConsts fuel fn (bound, refs) + scanPatternMap scope modIdx envConsts fuel arg (bound, refs) + else + let rec goArgs (st : NameSet × Array Nat) : List Stx → NameSet × Array Nat + | [] => st + | child :: rest => goArgs (scanPatternMap scope modIdx envConsts fuel child st) rest + goArgs (bound, refs) args.toList + +def scanSyntaxRefsMap (scope : ScopeSnapshot) (modIdx : ModuleIndex) + (envConsts : NameMap Ix.ConstantInfo) : + Nat → NameSet → Stx → Array Nat → Array Nat + | 0, _, _, refs => refs + | fuel + 1, locals, stx0, refs => + let stx := + if modIdx.macroRules.isEmpty then stx0 + else expandTopMacroPure 16 modIdx.macroRules.toList stx0 + let rec goArgs (loc : NameSet) (r : Array Nat) : List Stx → Array Nat + | [] => r + | child :: rest => goArgs loc (scanSyntaxRefsMap scope modIdx envConsts fuel loc child r) rest + let rec goBinders (loc : NameSet) (r : Array Nat) : List Stx → NameSet × Array Nat + | [] => (loc, r) + | b :: rest => + let r' := match extractBinderType? b with + | some ty => scanSyntaxRefsMap scope modIdx envConsts fuel loc ty r + | none => r + goBinders (insertBinderStxNames loc b) r' rest + let rec goPats (st : NameSet × Array Nat) : List Stx → NameSet × Array Nat + | [] => st + | p :: rest => goPats (scanPatternMap scope modIdx envConsts fuel p st) rest + let rec goRcasesPats (loc : NameSet) : List Stx → NameSet + | [] => loc + | p :: rest => goRcasesPats (collectRcasesPatLocalsPure 32 p loc) rest + let rec goTactics (loc : NameSet) (r : Array Nat) : List Stx → Array Nat + | [] => r + | tac :: rest => + let tk := Syntax.getKind tac + if tk == SyntaxKind.tacticIntro || tk == SyntaxKind.tacticFunext || tk == SyntaxKind.tacticExt then + let loc' := insertBinderIdNodes loc (Syntax.getArgs (Syntax.getArg tac 1)).toList + goTactics loc' r rest + else if tk == SyntaxKind.tacticRintro then + let pats := (Syntax.getArgs (Syntax.getArg tac 1)).toList + let optTy := Syntax.getArg tac 2 + let r' := scanSyntaxRefsMap scope modIdx envConsts fuel loc optTy r + goTactics (goRcasesPats loc pats) r' rest + else if tk == SyntaxKind.tacticRcases then + let targets := Syntax.getArg tac 1 + let pat := Syntax.getArg tac 2 + let r' := scanSyntaxRefsMap scope modIdx envConsts fuel loc targets r + goTactics (collectRcasesPatLocalsPure 32 pat loc) r' rest + else if tk == SyntaxKind.tacticObtain then + let pat := Syntax.getArg tac 1 + let optTy := Syntax.getArg tac 2 + let val := Syntax.getArg tac 4 + let r1 := scanSyntaxRefsMap scope modIdx envConsts fuel loc optTy r + let r2 := scanSyntaxRefsMap scope modIdx envConsts fuel loc val r1 + goTactics (collectRcasesPatLocalsPure 32 pat loc) r2 rest + else if tk == SyntaxKind.tacticHave || tk == SyntaxKind.tacticLet then + let lId := Syntax.getId (Syntax.getArg tac 1) + let optTy := Syntax.getArg tac 2 + let val := Syntax.getArg tac 4 + let r1 := scanSyntaxRefsMap scope modIdx envConsts fuel loc optTy r + let r2 := scanSyntaxRefsMap scope modIdx envConsts fuel loc val r1 + let loc' := if Name.isAnonymous lId then loc else loc.insert lId + goTactics loc' r2 rest + else if tk == SyntaxKind.tacticSuffices then + let lId := Syntax.getId (Syntax.getArg tac 1) + let ty := Syntax.getArg tac 2 + let body := Syntax.getArg tac 4 + let r1 := scanSyntaxRefsMap scope modIdx envConsts fuel loc ty r + let loc' := if Name.isAnonymous lId then loc else loc.insert lId + let r2 := scanSyntaxRefsMap scope modIdx envConsts fuel loc' body r1 + goTactics loc' r2 rest + else if tk == SyntaxKind.tacticGeneralize then + let hId := Syntax.getId (Syntax.getArg tac 1) + let eStx := Syntax.getArg tac 2 + let xId := Syntax.getId (Syntax.getArg tac 4) + let r1 := scanSyntaxRefsMap scope modIdx envConsts fuel loc eStx r + let loc1 := if Name.isAnonymous xId then loc else loc.insert xId + let loc2 := if Name.isAnonymous hId then loc1 else loc1.insert hId + goTactics loc2 r1 rest + else if tk == SyntaxKind.tacticByCases then + let hId := Syntax.getId (Syntax.getArg tac 1) + let pStx := Syntax.getArg tac 2 + let r1 := scanSyntaxRefsMap scope modIdx envConsts fuel loc pStx r + let loc' := if Name.isAnonymous hId then loc else loc.insert hId + goTactics loc' r1 rest + else if tk == SyntaxKind.tacticByContra then + let hId := Syntax.getId (Syntax.getArg tac 1) + let loc' := if Name.isAnonymous hId then loc else loc.insert hId + goTactics loc' r rest + else + let r1 := scanSyntaxRefsMap scope modIdx envConsts fuel loc tac r + goTactics loc r1 rest + match stx with + | .missing | .atom _ _ | .snil | .scons .. => refs + | .ident _ _ idF => + let id := FName.toIxName idF + if Name.isAnonymous id || locals.contains id then refs + else + let resolved := resolveIdentInScopeMap scope modIdx envConsts id + match modIdx.findOwnerIdx? resolved with + | some ownerIdx => pushUniqueNat refs ownerIdx + | none => + match id with + | .str pre _ _ => + if !Name.isAnonymous pre && !locals.contains pre then + let resPre := resolveIdentInScopeMap scope modIdx envConsts pre + match modIdx.findOwnerIdx? resPre with + | some ownerIdx => pushUniqueNat refs ownerIdx + | none => refs + else refs + | _ => refs + | .node _ kindF args => + let kind := FName.toIxName kindF + if kind == SyntaxKind.numLit || kind == SyntaxKind.strLit || + kind == SyntaxKind.charLit || kind == SyntaxKind.propTerm || + kind == SyntaxKind.typeTerm || kind == SyntaxKind.binderPrefix || + kind == SyntaxKind.valuePrefix || kind == SyntaxKind.holeTerm then + refs + else if kind == SyntaxKind.nullKind || kind == SyntaxKind.binOpTerm || + kind == SyntaxKind.appTerm || kind == SyntaxKind.arrowTerm || + kind == SyntaxKind.parenTerm then + goArgs locals refs args.toList + else if kind == SyntaxKind.funTerm then + let binders := Syntax.getArgs (args.getD 1 .missing) + let body := args.getD 3 .missing + let (locals', refs') := goBinders locals refs binders.toList + scanSyntaxRefsMap scope modIdx envConsts fuel locals' body refs' + else if kind == SyntaxKind.forallTerm then + let isKwForall := match args[0]? with + | some (.atom _ kw) => Sym.beq kw (s% "forall") || Sym.beq kw (s% "∀") + | _ => false + let binders := Syntax.getArgs (if isKwForall then args.getD 1 .missing else args.getD 0 .missing) + let body := if isKwForall then args.getD 4 .missing else args.getD 3 .missing + let (locals', refs') := goBinders locals refs binders.toList + scanSyntaxRefsMap scope modIdx envConsts fuel locals' body refs' + else if kind == SyntaxKind.letTerm then + let idStx := args.getD 2 .missing + let binders := Syntax.getArgs (args.getD 3 .missing) + let optTy := args.getD 4 .missing + let val := args.getD 6 .missing + let body := args.getD 8 .missing + let (localsBind, refs) := goBinders locals refs binders.toList + let refs := scanSyntaxRefsMap scope modIdx envConsts fuel localsBind optTy refs + let refs := scanSyntaxRefsMap scope modIdx envConsts fuel localsBind val refs + let letId := Syntax.getId idStx + let localsBody := if Name.isAnonymous letId then locals else locals.insert letId + scanSyntaxRefsMap scope modIdx envConsts fuel localsBody body refs + else if kind == SyntaxKind.letBorrowTerm then + let idStx := args.getD 3 .missing + let binders := Syntax.getArgs (args.getD 4 .missing) + let optTy := args.getD 5 .missing + let val := args.getD 7 .missing + let body := args.getD 9 .missing + let (localsBind, refs) := goBinders locals refs binders.toList + let refs := scanSyntaxRefsMap scope modIdx envConsts fuel localsBind optTy refs + let refs := scanSyntaxRefsMap scope modIdx envConsts fuel localsBind val refs + let letId := Syntax.getId idStx + let localsBody := if Name.isAnonymous letId then locals else locals.insert letId + scanSyntaxRefsMap scope modIdx envConsts fuel localsBody body refs + else if kind == SyntaxKind.letRecTerm then + let idStx := args.getD 3 .missing + let binders := Syntax.getArgs (args.getD 4 .missing) + let optTy := args.getD 5 .missing + let val := args.getD 7 .missing + let body := args.getD 9 .missing + let letId := Syntax.getId idStx + let localsWithId := if Name.isAnonymous letId then locals else locals.insert letId + let (localsBind, refs) := goBinders localsWithId refs binders.toList + let refs := scanSyntaxRefsMap scope modIdx envConsts fuel localsBind optTy refs + let refs := scanSyntaxRefsMap scope modIdx envConsts fuel localsBind val refs + scanSyntaxRefsMap scope modIdx envConsts fuel localsWithId body refs + else if kind == SyntaxKind.haveTerm then + let idStx := args.getD 1 .missing + let optTy := args.getD 2 .missing + let val := args.getD 4 .missing + let body := args.getD 6 .missing + let refs := scanSyntaxRefsMap scope modIdx envConsts fuel locals optTy refs + let refs := scanSyntaxRefsMap scope modIdx envConsts fuel locals val refs + let haveId := Syntax.getId idStx + let localsBody := if Name.isAnonymous haveId then locals else locals.insert haveId + scanSyntaxRefsMap scope modIdx envConsts fuel localsBody body refs + else if kind == SyntaxKind.ifTerm then + if args.size == 8 then + let hId := Syntax.getId (args.getD 1 .missing) + let cond := args.getD 3 .missing + let thenBr := args.getD 5 .missing + let elseBr := args.getD 7 .missing + let refs := scanSyntaxRefsMap scope modIdx envConsts fuel locals cond refs + let locals' := if Name.isAnonymous hId then locals else locals.insert hId + let refs := scanSyntaxRefsMap scope modIdx envConsts fuel locals' thenBr refs + scanSyntaxRefsMap scope modIdx envConsts fuel locals' elseBr refs + else + let cond := args.getD 2 .missing + let thenBr := args.getD 4 .missing + let elseBr := args.getD 6 .missing + let refs := scanSyntaxRefsMap scope modIdx envConsts fuel locals cond refs + let refs := scanSyntaxRefsMap scope modIdx envConsts fuel locals thenBr refs + scanSyntaxRefsMap scope modIdx envConsts fuel locals elseBr refs + else if kind == SyntaxKind.matchAlt then + let pats := Syntax.getArgs (args.getD 1 .missing) + let rhs := args.getD 3 .missing + let (locals', refs') := goPats (locals, refs) pats.toList + scanSyntaxRefsMap scope modIdx envConsts fuel locals' rhs refs' + else if kind == SyntaxKind.projTerm then + let base := args.getD 0 .missing + let fieldNode := args.getD 2 .missing + let refs := scanSyntaxRefsMap scope modIdx envConsts fuel locals base refs + let fieldId := Syntax.getId fieldNode + if Name.isAnonymous fieldId then refs + else + match base with + | .ident _ _ bIdF => + let bId := FName.toIxName bIdF + if !locals.contains bId then + let combined := Name.append bId fieldId + let resCombined := resolveIdentInScopeMap scope modIdx envConsts combined + match modIdx.findOwnerIdx? resCombined with + | some ownerIdx => pushUniqueNat refs ownerIdx + | none => refs + else refs + | _ => refs + else if kind == SyntaxKind.tacticSeq then + goTactics locals refs args.toList + else if kind == SyntaxKind.tacticAlt || kind == SyntaxKind.tacticCase then + let locals' := insertBinderIdNodes locals (Syntax.getArgs (args.getD 2 .missing)).toList + scanSyntaxRefsMap scope modIdx envConsts fuel locals' (args.getD 4 .missing) refs + else if kind == SyntaxKind.tacticRw then + scanSyntaxRefsMap scope modIdx envConsts fuel locals (args.getD 2 .missing) refs + else if kind == SyntaxKind.tacticSimp || kind == SyntaxKind.tacticDSimp then + let rulesNode := if args.size ≥ 4 then args.getD 2 .missing else args.getD 1 .missing + scanSyntaxRefsMap scope modIdx envConsts fuel locals rulesNode refs + else if kind == SyntaxKind.tacticClear || kind == SyntaxKind.tacticRevert || + kind == SyntaxKind.tacticSubst then + refs + else if kind == SyntaxKind.tacticSpecialize then + scanSyntaxRefsMap scope modIdx envConsts fuel locals (args.getD 2 .missing) refs + else + goArgs locals refs args.toList + +def scanBindersMap (scope : ScopeSnapshot) (modIdx : ModuleIndex) + (envConsts : NameMap Ix.ConstantInfo) (fuel : Nat) + (loc : NameSet) (r : Array Nat) : List Stx → NameSet × Array Nat + | [] => (loc, r) + | b :: rest => + let r' := match extractBinderType? b with + | some ty => scanSyntaxRefsMap scope modIdx envConsts fuel loc ty r + | none => r + scanBindersMap scope modIdx envConsts fuel (insertBinderStxNames loc b) r' rest + +def pushUniqueNatList (acc : Array Nat) : List Nat → Array Nat + | [] => acc + | x :: rest => pushUniqueNatList (pushUniqueNat acc x) rest + +def extractDeclDepsMap (modIdx : ModuleIndex) (envConsts : NameMap Ix.ConstantInfo) + (decl : ModuleDecl) (fuel : Nat := 256) : DeclDepInfo := + let scope := decl.scope + let cmd := decl.stx + let k := Syntax.getKind cmd + let (locals0, sigRefs0) := + scanBindersMap scope modIdx envConsts fuel NameSet.empty #[] scope.varBinders.toList + if k == SyntaxKind.defDecl || k == SyntaxKind.abbrevDecl || + k == SyntaxKind.theoremDecl || k == SyntaxKind.opaqueDecl then + let binders := Syntax.getArgs (Syntax.getArg cmd 4) + let optType := Syntax.getArg cmd 6 + let (localsSig, sigRefs) := + scanBindersMap scope modIdx envConsts fuel locals0 sigRefs0 binders.toList + let sigRefs := scanSyntaxRefsMap scope modIdx envConsts fuel localsSig optType sigRefs + let bodyNode := + if Syntax.getNumArgs cmd == 9 then Syntax.getArg cmd 8 + else Syntax.getArg cmd 7 + let bodyRefs := scanSyntaxRefsMap scope modIdx envConsts fuel localsSig bodyNode #[] + { declIdx := decl.idx, sigRefs, bodyRefs } + else if k == SyntaxKind.axiomDecl then + let binders := Syntax.getArgs (Syntax.getArg cmd 4) + let ty := Syntax.getArg cmd 6 + let (localsSig, sigRefs) := + scanBindersMap scope modIdx envConsts fuel locals0 sigRefs0 binders.toList + let sigRefs := scanSyntaxRefsMap scope modIdx envConsts fuel localsSig ty sigRefs + { declIdx := decl.idx, sigRefs, bodyRefs := #[] } + else if k == SyntaxKind.instanceDecl then + let binders := Syntax.getArgs (Syntax.getArg cmd 4) + let ty := Syntax.getArg cmd 6 + let (localsSig, sigRefs) := + scanBindersMap scope modIdx envConsts fuel locals0 sigRefs0 binders.toList + let tyRefs := scanSyntaxRefsMap scope modIdx envConsts fuel localsSig ty #[] + let sigRefs := pushUniqueNatList sigRefs tyRefs.toList + let bodyNode := Syntax.getArg cmd 8 + let bodyRefs := scanSyntaxRefsMap scope modIdx envConsts fuel localsSig bodyNode #[] + { declIdx := decl.idx, sigRefs, bodyRefs, carrierRefs := tyRefs } + else if k == SyntaxKind.inductiveDecl then + let binders := Syntax.getArgs (Syntax.getArg cmd 4) + let optType := Syntax.getArg cmd 6 + let ctorsNode := Syntax.getArg cmd 7 + let derivNode := Syntax.getArg cmd 8 + let (localsSig, sigRefs) := + scanBindersMap scope modIdx envConsts fuel locals0 sigRefs0 binders.toList + let sigRefs := scanSyntaxRefsMap scope modIdx envConsts fuel localsSig optType sigRefs + let rec goCtors (acc : Array Nat) : List Stx → Array Nat + | [] => acc + | ctorStx :: rest => + let cBinders := Syntax.getArgs (Syntax.getArg ctorStx 2) + let cOptType := Syntax.getArg ctorStx 4 + let (localsCtor, acc1) := + scanBindersMap scope modIdx envConsts fuel localsSig acc cBinders.toList + goCtors (scanSyntaxRefsMap scope modIdx envConsts fuel localsCtor cOptType acc1) rest + let bodyRefs := goCtors #[] (Syntax.getArgs ctorsNode).toList + let bodyRefs := scanSyntaxRefsMap scope modIdx envConsts fuel localsSig derivNode bodyRefs + { declIdx := decl.idx, sigRefs, bodyRefs } + else if k == SyntaxKind.structureDecl || k == SyntaxKind.classDecl then + let binders := Syntax.getArgs (Syntax.getArg cmd 4) + let extendsNode := Syntax.getArg cmd 5 + let optType := Syntax.getArg cmd 7 + let fieldsOrCtorsNode := Syntax.getArg cmd 9 + let derivNode := Syntax.getArg cmd 10 + let (localsSig, sigRefs) := + scanBindersMap scope modIdx envConsts fuel locals0 sigRefs0 binders.toList + let sigRefs := scanSyntaxRefsMap scope modIdx envConsts fuel localsSig extendsNode sigRefs + let sigRefs := scanSyntaxRefsMap scope modIdx envConsts fuel localsSig optType sigRefs + let rec goItems (loc : NameSet) (acc : Array Nat) : List Stx → Array Nat + | [] => acc + | item :: rest => + if Syntax.isOfKind item SyntaxKind.ctorDecl then + let cBinders := Syntax.getArgs (Syntax.getArg item 2) + let cOptType := Syntax.getArg item 4 + let (locCtor, acc1) := + scanBindersMap scope modIdx envConsts fuel loc acc cBinders.toList + goItems loc (scanSyntaxRefsMap scope modIdx envConsts fuel locCtor cOptType acc1) rest + else if Syntax.isOfKind item SyntaxKind.fieldDecl then + let fArgs := Syntax.getArgs item + let isBracketed := match fArgs[0]? with + | some (.atom _ (s% "(")) | some (.atom _ (s% "{")) => true + | _ => false + let idsNode := if isBracketed then Syntax.getArg item 2 else Syntax.getArg item 1 + let tyNode := if isBracketed then Syntax.getArg item 5 else Syntax.getArg item 4 + let defNode := if isBracketed then Syntax.getArg item 6 else Syntax.getArg item 5 + let acc1 := scanSyntaxRefsMap scope modIdx envConsts fuel loc tyNode acc + let acc2 := scanSyntaxRefsMap scope modIdx envConsts fuel loc defNode acc1 + let loc' := insertBinderIdNodes loc (Syntax.getArgs idsNode).toList + goItems loc' acc2 rest + else + goItems loc (scanSyntaxRefsMap scope modIdx envConsts fuel loc item acc) rest + let bodyRefs := goItems localsSig #[] (Syntax.getArgs fieldsOrCtorsNode).toList + let bodyRefs := scanSyntaxRefsMap scope modIdx envConsts fuel localsSig derivNode bodyRefs + { declIdx := decl.idx, sigRefs, bodyRefs } + else + { declIdx := decl.idx } + +def sortNatArrayAsc (xs : Array Nat) : Array Nat := + let rec insert (x : Nat) : List Nat → List Nat + | [] => [x] + | y :: ys => if y < x then y :: insert x ys else x :: y :: ys + let rec go (acc : List Nat) : List Nat → List Nat + | [] => acc + | x :: rest => go (insert x acc) rest + Array.mk (go [] xs.toList) + +def tarjanPopCompPure : Ix.Compile.Canon.TarjanState → Nat → Ix.Compile.Canon.TarjanState + | { index, low, onStack, stack, calls, next, comps, roots, order, exhausted }, v => + let rec go : List Nat → Array Nat → Array Bool → List Nat × Array Nat × Array Bool + | [], comp, on => ([], comp, on) + | w :: ws, comp, on => + let comp := comp.push w + let on := arraySetD on w false + if w == v then (ws, comp, on) else go ws comp on + let (stack, comp, onStack) := go stack #[] onStack + { index, low, onStack, stack, calls, next, comps := comps.push (sortNatArrayAsc comp), + roots := roots.push v, order, exhausted } + +def tarjanDfsLoopPure (adj : Array (Array Nat)) : Nat → Ix.Compile.Canon.TarjanState → Ix.Compile.Canon.TarjanState + | 0, st => if st.calls.isEmpty then st else { st with exhausted := true } + | fuel + 1, st => + match st.calls with + | [] => st + | (v, i) :: rest => + let succs := arrayGetD adj v #[] + if i < succs.size then + let w := arrayGetD succs i 0 + let st := { st with calls := (v, i + 1) :: rest } + let iw := arrayGetD st.index w 0 + if iw == 0 then + tarjanDfsLoopPure adj fuel (tarjanVisit st w) + else if arrayGetD st.onStack w false then + let lv := arrayGetD st.low v 0 + tarjanDfsLoopPure adj fuel (tarjanSetLow st v (min lv iw)) + else tarjanDfsLoopPure adj fuel st + else + let lv := arrayGetD st.low v 0 + let iv := arrayGetD st.index v 0 + let st := { st with calls := rest } + let st := if lv == iv then tarjanPopCompPure st v else st + let st := match rest with + | (u, _) :: _ => + let lu := arrayGetD st.low u 0 + tarjanSetLow st u (min lu lv) + | [] => st + tarjanDfsLoopPure adj fuel st + +def tarjanCondensationPure (adj : Array (Array Nat)) : Option Ix.Compile.Canon.Condensation := + let n := adj.size + let rec filterLt : List Nat → List Nat + | [] => [] + | x :: rest => if x < n then x :: filterLt rest else filterLt rest + let rec cleanRows (edges : Nat) : List (Array Nat) → List (Array Nat) × Nat + | [] => ([], edges) + | row :: rest => + let row' := Array.mk (filterLt row.toList) + let (rows', edges') := cleanRows (edges + row'.size) rest + (row' :: rows', edges') + let (cleanList, edges) := cleanRows 0 adj.toList + let adj' := Array.mk cleanList + let init : Ix.Compile.Canon.TarjanState := + { index := Array.mk (List.replicate n 0), low := Array.mk (List.replicate n 0), + onStack := Array.mk (List.replicate n false) } + let fuel := edges + n + 1 + let rec runRoots (r : Nat) (rem : Nat) (st : Ix.Compile.Canon.TarjanState) : Ix.Compile.Canon.TarjanState := + match rem with + | 0 => st + | k + 1 => + let st' := + if st.exhausted || arrayGetD st.index r 0 != 0 then st + else tarjanDfsLoopPure adj' fuel (tarjanVisit st r) + runRoots (r + 1) k st' + let st := runRoots 0 n init + if st.exhausted then none + else some { comps := st.comps, roots := st.roots, order := st.order } + +def addInstanceSchedulingEdgesPure (decls : Array ModuleDecl) (deps : Array DeclDepInfo) + (adj : Array (Array Nat)) : Array (Array Nat) := + let rec collectInsts : List DeclDepInfo → List DeclDepInfo + | [] => [] + | d :: rest => + let keep : Bool := match Syntax.listGet? decls.toList d.declIdx with + | some decl => decl.kind == .inst && !d.carrierRefs.isEmpty + | none => false + if keep then d :: collectInsts rest else collectInsts rest + let rec anyCarrierIn (uAll : List Nat) : List Nat → Bool + | [] => false + | c :: rest => if uAll.contains c then true else anyCarrierIn uAll rest + let rec loopUsers (inst : DeclDepInfo) (u : Nat) (rem : Nat) (curAdj : Array (Array Nat)) : Array (Array Nat) := + match rem with + | 0 => curAdj + | k + 1 => + let nextAdj := + if u == inst.declIdx then curAdj + else + let uDep := Syntax.listGetD deps.toList u { declIdx := u } + let uAll := uDep.sigRefs.toList ++ uDep.bodyRefs.toList + let curRow := Syntax.listGetD curAdj.toList u #[] + if anyCarrierIn uAll inst.carrierRefs.toList && + !curRow.toList.contains inst.declIdx && + !reachesNode curAdj inst.declIdx u then + arraySetD curAdj u (curRow.push inst.declIdx) + else curAdj + loopUsers inst (u + 1) k nextAdj + let rec loopInsts (curAdj : Array (Array Nat)) : List DeclDepInfo → Array (Array Nat) + | [] => curAdj + | inst :: rest => loopInsts (loopUsers inst 0 decls.size curAdj) rest + loopInsts adj (collectInsts deps.toList) + +def sortSccBySigRefsPure (comp : Array Nat) (deps : Array DeclDepInfo) : Array Nat := + if comp.size ≤ 1 then comp + else + let sortedComp := sortNatArrayAsc comp + let rec sigReady (u : Nat) (placed : List Nat) : List Nat → Bool + | [] => true + | v :: rest => + if v == u || !comp.toList.contains v || placed.contains v then + sigReady u placed rest + else false + let rec findReady (placed : List Nat) : List Nat → Option Nat + | [] => none + | u :: rest => + let sig := (Syntax.listGetD deps.toList u { declIdx := u }).sigRefs.toList + if sigReady u placed sig then some u else findReady placed rest + let rec removeNat (x : Nat) : List Nat → List Nat + | [] => [] + | y :: rest => if y == x then removeNat x rest else y :: removeNat x rest + let rec pickLoop (fuel : Nat) (remaining : List Nat) (placed : Array Nat) : Array Nat := + match fuel, remaining with + | 0, rem => placed ++ Array.mk rem + | _, [] => placed + | fuel + 1, rem => + let chosen := match findReady placed.toList rem with + | some u => u + | none => rem.headD 0 + pickLoop fuel (removeNat chosen rem) (placed.push chosen) + pickLoop (sortedComp.size + 1) sortedComp.toList #[] + +def classifySccPure (modIdx : ModuleIndex) (explicitAdj : Array (Array Nat)) + (comp : Array Nat) : SccKind := + if comp.size == 1 then + let u := arrayGetD comp 0 0 + if (arrayGetD explicitAdj u #[]).toList.contains u then .singleRec else .singleNonRec + else + let rec checkAllInd : List Nat → Bool + | [] => true + | u :: rest => + match Syntax.listGet? modIdx.decls.toList u with + | some d => if d.kind == .ind || d.kind == .struct || d.kind == .cls then checkAllInd rest else false + | none => false + let rec checkAllVal : List Nat → Bool + | [] => true + | u :: rest => + match Syntax.listGet? modIdx.decls.toList u with + | some d => if d.kind == .defn || d.kind == .abbrev || d.kind == .thm || d.kind == .inst then checkAllVal rest else false + | none => false + if checkAllInd comp.toList then .mutualInductive + else if checkAllVal comp.toList then .mutualDef + else .mixedMutual + +/-- 100% first-order Pass 2 & Pass 3 scheduler (no closures / `List.map` / `Stx.foldl`). -/ +def scheduleModuleDeclsMap (modIdx : ModuleIndex) + (envConsts : NameMap Ix.ConstantInfo) : Except String ModuleSchedule := + let n := modIdx.decls.size + let rec extractAll : List ModuleDecl → List DeclDepInfo + | [] => [] + | d :: rest => extractDeclDepsMap modIdx envConsts d :: extractAll rest + let depsList := extractAll modIdx.decls.toList + let deps := Array.mk depsList + let rec buildExplicit : List DeclDepInfo → List (Array Nat) + | [] => [] + | d :: rest => + let all := pushUniqueNatList (pushUniqueNatList #[] d.sigRefs.toList) d.bodyRefs.toList + all :: buildExplicit rest + let explicitList := buildExplicit depsList + let explicitAdj : Array (Array Nat) := Array.mk explicitList + let rec removeSelf (u : Nat) : List Nat → List Nat + | [] => [] + | v :: rest => if v == u then removeSelf u rest else v :: removeSelf u rest + let rec buildBase (u : Nat) : List (Array Nat) → List (Array Nat) + | [] => [] + | nbrs :: rest => Array.mk (removeSelf u nbrs.toList) :: buildBase (u + 1) rest + let baseAdj : Array (Array Nat) := Array.mk (buildBase 0 explicitList) + let fullAdj := addInstanceSchedulingEdgesPure modIdx.decls deps baseAdj + let rec allEmpty : List (Array Nat) → Bool + | [] => true + | row :: rest => if row.isEmpty then allEmpty rest else false + if allEmpty fullAdj.toList then + let rec mkSingleSccs (i : Nat) (rem : Nat) : List ScheduledSCC := + match rem with + | 0 => [] + | k + 1 => + let comp := #[i] + let kind := classifySccPure modIdx explicitAdj comp + { sccIdx := i, kind, declIdxs := comp } :: mkSingleSccs (i + 1) k + .ok { modIdx, deps, explicitAdj, fullAdj, sccs := Array.mk (mkSingleSccs 0 n) } + else + match tarjanCondensationPure fullAdj with + | none => .error (str% "internal error: Tarjan SCC condensation failed") + | some cond => + let rec mkCondSccs (i : Nat) : List (Array Nat) → List ScheduledSCC + | [] => [] + | rawComp :: rest => + let orderedComp := sortSccBySigRefsPure rawComp deps + let kind := classifySccPure modIdx explicitAdj orderedComp + { sccIdx := i, kind, declIdxs := orderedComp } :: mkCondSccs (i + 1) rest + .ok { modIdx, deps, explicitAdj, fullAdj, sccs := Array.mk (mkCondSccs 0 cond.comps.toList) } + +end Ix.Frontend diff --git a/Ix/Frontend/Scope.lean b/Ix/Frontend/Scope.lean new file mode 100644 index 0000000000..d03128ff66 --- /dev/null +++ b/Ix/Frontend/Scope.lean @@ -0,0 +1,784 @@ +/- + Ix.Frontend.Scope: Pass 1 of the Ix Frontend — Lexical Scope Management, + First-Class `Name -> Address` Build/Import Mapping (`IxImportMap`), + and Pre-Elaboration Module Symbol Table (`ModuleIndex`). +-/ +module + +public import Ix.Frontend.Parser.Command + +@[expose] public section + +namespace Ix.Frontend + +open Ix.Frontend.Parser + +/-- Pure, proof-free, strictly-spine-evaluated Red-Black tree keyed by `Ix.Name` + (using `Name.cmpStruct`, which reads no hash). + Unlike `Std.TreeMap`, this type has zero wrapper structures (`TreeMap.mk` / `DTreeMap.mk`), + zero `wf : Balanced` proof terms, zero `Nat` size multiplications, and strictly forces + modified child subtrees before constructing parent `.node`s so call-by-name kernel + reduction (`Whnf.lean`) never accumulates unevaluated `.insert` chains. -/ +inductive NameMap (α : Type) where + | leaf : NameMap α + | node : Bool → Ix.Name → α → NameMap α → NameMap α → NameMap α + deriving Repr, Inhabited + +namespace NameMap + +def empty : NameMap α := .leaf + +def isEmpty : NameMap α → Bool + | .leaf => true + | .node .. => false + +@[inline] def bindMap (m : NameMap α) (k : NameMap α → β) : β := k m + +def get? : NameMap α → Ix.Name → Option α + | .leaf, _ => none + | .node _ k' v' l r, k => + match Name.cmpStruct k k' with + | .lt => get? l k + | .gt => get? r k + | .eq => some v' + +def contains : NameMap α → Ix.Name → Bool + | .leaf, _ => false + | .node _ k' _ l r, k => + match Name.cmpStruct k k' with + | .lt => contains l k + | .gt => contains r k + | .eq => true + +@[inline] def balanceLeft (c : Bool) (k : Ix.Name) (v : α) (l r : NameMap α) : NameMap α := + match c with + | true => .node true k v l r + | false => + match l with + | .node true lk lv (.node true llk llv lll llr) lr => + .node true lk lv (.node false llk llv lll llr) (.node false k v lr r) + | .node true lk lv ll (.node true lrk lrv lrl lrr) => + .node true lrk lrv (.node false lk lv ll lrl) (.node false k v lrr r) + | _ => .node false k v l r + +@[inline] def balanceRight (c : Bool) (k : Ix.Name) (v : α) (l r : NameMap α) : NameMap α := + match c with + | true => .node true k v l r + | false => + match r with + | .node true rk rv (.node true rlk rlv rll rlr) rr => + .node true rlk rlv (.node false k v l rll) (.node false rk rv rlr rr) + | .node true rk rv rl (.node true rrk rrv rrl rrr) => + .node true rk rv (.node false k v l rl) (.node false rrk rrv rrl rrr) + | _ => .node false k v l r + +def ins (k : Ix.Name) (v : α) : NameMap α → NameMap α + | .leaf => .node true k v .leaf .leaf + | .node c k' v' l r => + match Name.cmpStruct k k' with + | .lt => + match ins k v l with + | .leaf => .leaf + | l'@(.node ..) => balanceLeft c k' v' l' r + | .gt => + match ins k v r with + | .leaf => .leaf + | r'@(.node ..) => balanceRight c k' v' l r' + | .eq => .node c k v l r + +def insert (m : NameMap α) (k : Ix.Name) (v : α) : NameMap α := + match ins k v m with + | .leaf => .leaf + | .node _ k' v' l r => .node false k' v' l r + +def foldl (m : NameMap α) (f : β → Ix.Name → α → β) (init : β) : β := + match m with + | .leaf => init + | .node _ k v l r => + let acc1 := foldl l f init + let acc2 := f acc1 k v + foldl r f acc2 + +def toListAux : NameMap α → List (Ix.Name × α) → List (Ix.Name × α) + | .leaf, acc => acc + | .node _ k v l r, acc => toListAux l ((k, v) :: toListAux r acc) + +def toList (m : NameMap α) : List (Ix.Name × α) := + toListAux m [] + +def size : NameMap α → Nat + | .leaf => 0 + | .node _ _ _ l r => 1 + size l + size r + +end NameMap + +/-- Pure, proof-free, strictly-spine-evaluated Red-Black set of `Ix.Name`s. -/ +inductive NameSet where + | leaf : NameSet + | node : Bool → Ix.Name → NameSet → NameSet → NameSet + deriving Repr, Inhabited + +namespace NameSet + +def empty : NameSet := .leaf + +def isEmpty : NameSet → Bool + | .leaf => true + | .node .. => false + +@[inline] def bindSet (s : NameSet) (k : NameSet → β) : β := k s + +def contains : NameSet → Ix.Name → Bool + | .leaf, _ => false + | .node _ k' l r, k => + match Name.cmpStruct k k' with + | .lt => contains l k + | .gt => contains r k + | .eq => true + +@[inline] def balanceLeft (c : Bool) (k : Ix.Name) (l r : NameSet) : NameSet := + match c with + | true => .node true k l r + | false => + match l with + | .node true lk (.node true llk lll llr) lr => + .node true lk (.node false llk lll llr) (.node false k lr r) + | .node true lk ll (.node true lrk lrl lrr) => + .node true lrk (.node false lk ll lrl) (.node false k lrr r) + | _ => .node false k l r + +@[inline] def balanceRight (c : Bool) (k : Ix.Name) (l r : NameSet) : NameSet := + match c with + | true => .node true k l r + | false => + match r with + | .node true rk (.node true rlk rll rlr) rr => + .node true rlk (.node false k l rll) (.node false rk rlr rr) + | .node true rk rl (.node true rrk rrl rrr) => + .node true rk (.node false k l rl) (.node false rrk rrl rrr) + | _ => .node false k l r + +def ins (k : Ix.Name) : NameSet → NameSet + | .leaf => .node true k .leaf .leaf + | .node c k' l r => + match Name.cmpStruct k k' with + | .lt => + match ins k l with + | .leaf => .leaf + | l'@(.node ..) => balanceLeft c k' l' r + | .gt => + match ins k r with + | .leaf => .leaf + | r'@(.node ..) => balanceRight c k' l r' + | .eq => .node c k' l r + +def insert (s : NameSet) (k : Ix.Name) : NameSet := + match ins k s with + | .leaf => .leaf + | .node _ k' l r => .node false k' l r + +def foldl (s : NameSet) (f : β → Ix.Name → β) (init : β) : β := + match s with + | .leaf => init + | .node _ k l r => + let acc1 := foldl l f init + let acc2 := f acc1 k + foldl r f acc2 + +def toListAux : NameSet → List Ix.Name → List Ix.Name + | .leaf, acc => acc + | .node _ k l r, acc => toListAux l (k :: toListAux r acc) + +def toList (s : NameSet) : List Ix.Name := + toListAux s [] + +def size : NameSet → Nat + | .leaf => 0 + | .node _ _ l r => 1 + size l + size r + +end NameSet + +/-! ## Hex Address Decoding & First-Class `IxImportMap` -/ + +/-- Pure ASCII hex digit decoder (avoids heavy stdlib `natOfHex`). -/ +def hexDigitVal? (c : Char) : Option Nat := + let n := c.toNat + if Nat.ble 48 n && Nat.ble n 57 then some (Nat.sub n 48) + else if Nat.ble 97 n && Nat.ble n 102 then some (Nat.add 10 (Nat.sub n 97)) + else if Nat.ble 65 n && Nat.ble n 70 then some (Nat.add 10 (Nat.sub n 65)) + else none + +/-- Parse a 64-character hex string into a 32-byte `Address`. -/ +def parseHexBytesAux : List Char → List UInt8 → Nat → Option ByteArray + | [], revAcc, cnt => + if Nat.beq cnt 32 then some ⟨Array.mk revAcc.reverse⟩ else none + | c1 :: c2 :: rest, revAcc, cnt => + match hexDigitVal? c1, hexDigitVal? c2 with + | some hi, some lo => + let byte : UInt8 := UInt8.ofNat (Nat.add (Nat.mul hi 16) lo) + parseHexBytesAux rest (byte :: revAcc) (Nat.add cnt 1) + | _, _ => none + | _, _, _ => none + +def parseHexAddress (hex : String) : Option Address := do + let ba ← parseHexBytesAux hex.toList [] 0 + return ⟨ba⟩ + +/-- First-class programmable `Name -> Address` mapping and content-hash import table + extracted from `.ix` files (`map Foo.Bar := #`, `import #`, `import Mod @ #`). -/ +structure IxImportMap where + nameToAddr : NameMap Address := NameMap.empty + modulePins : NameMap Address := NameMap.empty + importedEnvs : Array Address := #[] + deriving Repr, Inhabited + +namespace IxImportMap + +def empty : IxImportMap := {} + +def insertName (m : IxImportMap) (name : Ix.Name) (addr : Address) : IxImportMap := + match m with + | ⟨nameToAddr, modulePins, importedEnvs⟩ => + (nameToAddr.insert name addr).bindMap fun nameToAddr' => + ⟨nameToAddr', modulePins, importedEnvs⟩ + +def insertModulePin (m : IxImportMap) (modName : Ix.Name) (addr : Address) : IxImportMap := + match m with + | ⟨nameToAddr, modulePins, importedEnvs⟩ => + (modulePins.insert modName addr).bindMap fun modulePins' => + ⟨nameToAddr, modulePins', importedEnvs⟩ + +def addImportedEnv (m : IxImportMap) (addr : Address) : IxImportMap := + match m with + | ⟨nameToAddr, modulePins, importedEnvs⟩ => + if importedEnvs.contains addr then m + else ⟨nameToAddr, modulePins, importedEnvs.push addr⟩ + +def lookupName? (m : IxImportMap) (name : Ix.Name) : Option Address := + m.nameToAddr.get? name + +def merge (m1 m2 : IxImportMap) : IxImportMap := + let nameToAddr := m2.nameToAddr.foldl (fun acc k v => acc.insert k v) m1.nameToAddr + let modulePins := m2.modulePins.foldl (fun acc k v => acc.insert k v) m1.modulePins + let importedEnvs := m2.importedEnvs.foldl (fun acc a => + if acc.contains a then acc else acc.push a) m1.importedEnvs + nameToAddr.bindMap fun nameToAddr' => + modulePins.bindMap fun modulePins' => + { nameToAddr := nameToAddr', modulePins := modulePins', importedEnvs } + +end IxImportMap + +/-! ## Lexical Scope Stack (`namespace`, `section`, `open`, `variable`, `universe`) -/ + +/-- An `open` directive in lexical scope. -/ +inductive OpenDecl where + | simple (ns : Ix.Name) (only : List Ix.Name := []) + | explicit (aliasName : Ix.Name) (declName : Ix.Name) + deriving BEq, Repr, Inhabited + +/-- Frozen lexical scope snapshot attached to a top-level declaration. -/ +structure ScopeSnapshot where + currNamespace : Ix.Name := Name.mkAnon + openDecls : List OpenDecl := [] + levelNames : List Ix.Name := [] + varBinders : Array Stx := #[] + isPrivate : Bool := false + isProtected : Bool := false + deriving Repr, Inhabited + +/-- Mutable frame pushed by `namespace` or `section` during Pass 1 scanning. -/ +structure ScopeFrame where + header : Ix.Name + isNamespace : Bool + savedScope : ScopeSnapshot + deriving Repr, Inhabited + +/-! ## Top-Level Declaration Kind & `ModuleDecl` -/ + +inductive DeclKind where + | defn + | abbrev + | thm + | axiomDecl + | opaqueDecl + | inst + | ind + | struct + | cls + deriving BEq, DecidableEq, Repr, Inhabited + +/-- A top-level declaration collected in Pass 1, with its lexical `ScopeSnapshot`. -/ +structure ModuleDecl where + idx : Nat + kind : DeclKind + shortName : Ix.Name + fullName : Ix.Name + univParams : List Ix.Name + scope : ScopeSnapshot + stx : Stx + ctorNames : List Ix.Name := [] + fieldNames : List Ix.Name := [] + deriving Repr, Inhabited + +/-- Module-wide symbol table built in Pass 1 before any elaboration or reference resolution. + Pre-registers all inductive constructors and structure fields so forward pattern-matching + and dot-notation work regardless of declaration order in the file. -/ +structure ModuleIndex where + decls : Array ModuleDecl := #[] + declByName : NameMap Nat := NameMap.empty + ctorToInd : NameMap (Ix.Name × Nat) := NameMap.empty + fieldToStruct : NameMap (Ix.Name × Nat) := NameMap.empty + auxToInd : NameMap (Ix.Name × Nat) := NameMap.empty + importMap : IxImportMap := IxImportMap.empty + macroRules : Array MacroRule := #[] + deriving Repr, Inhabited + +namespace ModuleIndex + +/-- Look up the declaration index in `decls` that defines or owns `name` + (checking primary declarations, constructors, structure fields, and recursors/auxiliaries). -/ +def findOwnerIdx? (idx : ModuleIndex) (name : Ix.Name) : Option Nat := + match idx.declByName.get? name with + | some dIdx => some dIdx + | none => + match idx.ctorToInd.get? name with + | some (_, dIdx) => some dIdx + | none => + match idx.fieldToStruct.get? name with + | some (_, dIdx) => some dIdx + | none => + match idx.auxToInd.get? name with + | some (_, dIdx) => some dIdx + | none => none + +/-- True if `name` is a known symbol in this module (or its `importMap`). -/ +def containsSymbol (idx : ModuleIndex) (name : Ix.Name) : Bool := + (idx.findOwnerIdx? name).isSome || (idx.importMap.lookupName? name).isSome + +/-- True if `name` is a constructor declared anywhere in this module. -/ +def isModuleCtor (idx : ModuleIndex) (name : Ix.Name) : Bool := + idx.ctorToInd.contains name + +/-- Return all conflict variants `(tag, variantFullName)` in `idx` for `origName` + (i.e. declarations named `origName.#merge.`). -/ +def findConflictVariants (idx : ModuleIndex) (origName : Ix.Name) : List (String × Ix.Name) := + idx.decls.toList.filterMap fun d => + match Name.splitMergeVariant? d.fullName with + | some (orig, tag, []) => if orig == origName then some (tag, d.fullName) else none + | _ => none + +/-- Return all conflicted original declaration names in `idx` in appearance order. -/ +def conflictedNames (idx : ModuleIndex) : List Ix.Name := + (idx.decls.toList.filterMap fun d => + match Name.splitMergeVariant? d.fullName with + | some (orig, _, []) => some orig + | _ => none).eraseDups + +end ModuleIndex + +/-! ## Pass 1: Extracting Declarations, Constructors, Fields, and Build Maps -/ + +/-- Extract modifier flags `(isPrivate, isProtected)` from a `modifiersKind` syntax node. -/ +def extractModifierFlags (modStx : Stx) : Bool × Bool := + (Syntax.getArgs modStx).toList.foldl (fun (priv, prot) atom => + let v := Syntax.getAtomVal atom + (priv || v == (str% "private"), prot || v == (str% "protected"))) (false, false) + +/-- Extract explicit `.{u, v}` universe parameter names from a `univParamsKind` syntax node. -/ +def extractUnivParams (uStx : Stx) : List Ix.Name := + (Syntax.getArgs uStx).toList.map Syntax.getId |>.filter (!Name.isAnonymous ·) + +/-- Extract constructor full names `fullIndName ++ ctorShortName` from a `null` node of `ctorDecl`s. -/ +def extractCtorNames (fullIndName : Ix.Name) (ctorsStx : Stx) : List Ix.Name := + (Syntax.getArgs ctorsStx).toList.filterMap fun ctorStx => + if Syntax.isOfKind ctorStx SyntaxKind.ctorDecl then + let shortId := Syntax.getId (Syntax.getArg ctorStx 1) + if Name.isAnonymous shortId then none + else some (Name.append fullIndName shortId) + else + none + +/-- Extract structure/class field full names `fullStructName ++ fieldShortName` from a `null` node of `fieldDecl`s. -/ +def extractFieldNames (fullStructName : Ix.Name) (fieldsStx : Stx) : List Ix.Name := + (Syntax.getArgs fieldsStx).toList.flatMap fun fieldStx => + if Syntax.isOfKind fieldStx SyntaxKind.fieldDecl then + let args := Syntax.getArgs fieldStx + -- For `(bPref ids : vPref ty)` args[0] is `(`, args[2] is `ids`; for bare `bPref ids : ...`, args[1] is `ids` + let idsNode := match args[0]? with + | some (.atom _ (s% "(")) | some (.atom _ (s% "{")) => Syntax.getArg fieldStx 2 + | _ => Syntax.getArg fieldStx 1 + (Syntax.getArgs idsNode).toList.filterMap fun idStx => + let shortId := Syntax.getId idStx + if Name.isAnonymous shortId then none + else some (Name.append fullStructName shortId) + else + [] + +/-- Standard reserved auxiliary suffixes generated for every inductive/structure/class `T`. -/ +def standardIndAuxSuffixes : List String := + [(str% "rec"), (str% "recOn"), (str% "casesOn"), (str% "below"), (str% "brecOn"), (str% "noConfusion"), (str% "noConfusionType"), (str% "_ctorIdx"), (str% "_sizeOf_inst")] + +/-- Register a `ModuleDecl` at index `dIdx` and its constructors, fields, and auxiliaries + into `ModuleIndex`'s `NameMap` tables (deferring `Array.mk revDecls.reverse` to `buildModuleIndex`). -/ +def ModuleIndex.registerDeclMaps (idx : ModuleIndex) (dIdx : Nat) (d : ModuleDecl) : ModuleIndex := + match idx with + | ⟨decls, declByName0, ctorToInd0, fieldToStruct0, auxToInd0, importMap, macroRules⟩ => + let declByName := declByName0.insert d.fullName dIdx + if d.kind != .ind && d.kind != .struct && d.kind != .cls then + declByName.bindMap fun declByName' => + ⟨decls, declByName', ctorToInd0, fieldToStruct0, auxToInd0, importMap, macroRules⟩ + else + let ctorToInd := d.ctorNames.foldl (fun acc c => acc.insert c (d.fullName, dIdx)) ctorToInd0 + let fieldToStruct := d.fieldNames.foldl (fun acc f => acc.insert f (d.fullName, dIdx)) fieldToStruct0 + let auxToInd := + standardIndAuxSuffixes.foldl + (fun acc suf => acc.insert (Name.mkStr d.fullName suf) (d.fullName, dIdx)) + auxToInd0 + declByName.bindMap fun declByName' => + ctorToInd.bindMap fun ctorToInd' => + fieldToStruct.bindMap fun fieldToStruct' => + auxToInd.bindMap fun auxToInd' => + ⟨decls, declByName', ctorToInd', fieldToStruct', auxToInd', importMap, macroRules⟩ + +/-- Register a `ModuleDecl` and its constructors, fields, and auxiliaries into `ModuleIndex`. -/ +def ModuleIndex.registerDecl (idx : ModuleIndex) (d : ModuleDecl) : ModuleIndex := + let dIdx := idx.decls.size + let d := { d with idx := dIdx } + let idx' := idx.registerDeclMaps dIdx d + { idx' with decls := idx.decls.push d } + +/-- State of the Pass 1 lexical scanner. -/ +structure ScopePassState where + currScope : ScopeSnapshot := {} + frames : List ScopeFrame := [] + modIdx : ModuleIndex := {} + revDecls : List ModuleDecl := [] + declCount : Nat := 0 + anonCount : Nat := 0 + deriving Repr, Inhabited + +def mapStxGetId : List Stx → List Ix.Name + | [] => [] + | s :: rest => Syntax.getId s :: mapStxGetId rest + +def dedupNamesRev (seen : List Ix.Name) : List Ix.Name → List Ix.Name + | [] => [] + | x :: xs => if seen.contains x then dedupNamesRev seen xs else x :: dedupNamesRev (x :: seen) xs + +def mkOpenDeclsFor (onlyIds : List Ix.Name) : List Ix.Name → List OpenDecl + | [] => [] + | ns :: rest => + (if onlyIds.isEmpty then OpenDecl.simple ns [] else OpenDecl.simple ns onlyIds) :: + mkOpenDeclsFor onlyIds rest + +/-- Process a single top-level command in Pass 1 (structurally recursive on `fuel` for `mutual ... end`). + 100% first-order (zero `do` / `Except.bind` / `List.map` / `s!"..."`) for `IxCCAiur`. -/ +def processCommandPass1 : Nat → Stx → ScopePassState → Except String ScopePassState + | 0, _, st => .ok st + | fuel + 1, cmd, st => + match st with + | ⟨currScope, frames, modIdx, revDecls, declCount, anonCount⟩ => + let k := Syntax.getKind cmd + -- 1. `import #` + if k == SyntaxKind.hashImport then + let hashNode := Syntax.getArg cmd 1 + let hexStr := Syntax.getAtomVal (Syntax.getArg hashNode 0) + match parseHexAddress hexStr with + | some addr => + match modIdx with + | ⟨decls, declByName, ctorToInd, fieldToStruct, auxToInd, importMap, macroRules⟩ => + .ok ⟨currScope, frames, + ⟨decls, declByName, ctorToInd, fieldToStruct, auxToInd, importMap.addImportedEnv addr, macroRules⟩, + revDecls, declCount, anonCount⟩ + | none => + .error (str% "invalid 64-hex-char content address in import") + -- 2. `import Mod [@ #]` + else if k == SyntaxKind.importDecl then + let modName := Syntax.getId (Syntax.getArg cmd 1) + let pinNode := Syntax.getArg cmd 2 + if Syntax.isOfKind pinNode SyntaxKind.hashRef then + let hexStr := Syntax.getAtomVal (Syntax.getArg pinNode 0) + match parseHexAddress hexStr with + | some addr => + match modIdx with + | ⟨decls, declByName, ctorToInd, fieldToStruct, auxToInd, importMap, macroRules⟩ => + .ok ⟨currScope, frames, + ⟨decls, declByName, ctorToInd, fieldToStruct, auxToInd, importMap.insertModulePin modName addr, macroRules⟩, + revDecls, declCount, anonCount⟩ + | none => + .error (str% "invalid 64-hex-char content address in import pin") + else + .ok ⟨currScope, frames, modIdx, revDecls, declCount, anonCount⟩ + -- 3. `map Foo.Bar := #` + else if k == SyntaxKind.buildMapDecl then + let symName := Syntax.getId (Syntax.getArg cmd 1) + let hashNode := Syntax.getArg cmd 3 + let hexStr := Syntax.getAtomVal (Syntax.getArg hashNode 0) + match parseHexAddress hexStr with + | some addr => + match modIdx with + | ⟨decls, declByName, ctorToInd, fieldToStruct, auxToInd, importMap, macroRules⟩ => + .ok ⟨currScope, frames, + ⟨decls, declByName, ctorToInd, fieldToStruct, auxToInd, importMap.insertName symName addr, macroRules⟩, + revDecls, declCount, anonCount⟩ + | none => + .error (str% "invalid 64-hex-char content address in map declaration") + -- 4. `namespace Foo.Bar` + else if k == SyntaxKind.namespaceDecl then + let ns := Syntax.getId (Syntax.getArg cmd 1) + let newNs := Name.append currScope.currNamespace ns + let frame : ScopeFrame := { header := ns, isNamespace := true, savedScope := currScope } + let newOpen : OpenDecl := .simple newNs [] + let newScope : ScopeSnapshot := { currScope with + currNamespace := newNs + openDecls := newOpen :: currScope.openDecls } + .ok ⟨newScope, frame :: frames, modIdx, revDecls, declCount, anonCount⟩ + -- 5. `section [Foo]` + else if k == SyntaxKind.sectionDecl then + let secId := match Syntax.getOptional? (Syntax.getArg cmd 1) with + | some idStx => Syntax.getId idStx + | none => Name.mkAnon + let frame : ScopeFrame := { header := secId, isNamespace := false, savedScope := currScope } + .ok ⟨currScope, frame :: frames, modIdx, revDecls, declCount, anonCount⟩ + -- 6. `end [Foo]` + else if k == SyntaxKind.endDecl then + match frames with + | [] => .error (str% "unmatched 'end' command") + | frame :: rest => + .ok ⟨frame.savedScope, rest, modIdx, revDecls, declCount, anonCount⟩ + -- 7. `universe u v` + else if k == SyntaxKind.universeDecl then + let uIds := mapStxGetId (Syntax.getArgs (Syntax.getArg cmd 1)).toList + let newLvls := dedupNamesRev [] (currScope.levelNames ++ uIds) + .ok ⟨{ currScope with levelNames := newLvls }, frames, modIdx, revDecls, declCount, anonCount⟩ + -- 8. `variable (x : A) ...` + else if k == SyntaxKind.variableDecl then + let newVars := Syntax.getArgs (Syntax.getArg cmd 1) + .ok ⟨{ currScope with varBinders := currScope.varBinders ++ newVars }, frames, modIdx, revDecls, declCount, anonCount⟩ + -- 9. `open Foo.Bar [(a b)]` + else if k == SyntaxKind.openDecl then + let nss := mapStxGetId (Syntax.getArgs (Syntax.getArg cmd 1)).toList + let onlyIds : List Ix.Name := match Syntax.getOptional? (Syntax.getArg cmd 2) with + | some parenNode => + mapStxGetId (Syntax.getArgs (Syntax.getArg parenNode 1)).toList + | none => [] + let newOpens := mkOpenDeclsFor onlyIds nss + .ok ⟨{ currScope with openDecls := newOpens ++ currScope.openDecls }, frames, modIdx, revDecls, declCount, anonCount⟩ + -- 10. `mutual cmd1 cmd2 ... end` (flattened into individual declarations!) + else if k == SyntaxKind.mutualDecl then + let innerCmds := Syntax.getArgs (Syntax.getArg cmd 1) + let rec runMutual (acc : ScopePassState) : List Stx → Except String ScopePassState + | [] => .ok acc + | c :: rest => + match processCommandPass1 fuel c acc with + | .error e => .error e + | .ok acc' => runMutual acc' rest + runMutual ⟨currScope, frames, modIdx, revDecls, declCount, anonCount⟩ innerCmds.toList + -- 10b. `#merge | tag1 => cmd1 | tag2 => cmd2 ... end` (first-class conflict block) + else if k == SyntaxKind.mergeConflictDecl then + let arms := Syntax.getArgs (Syntax.getArg cmd 1) + let rec runMerge (acc : ScopePassState) : List Stx → Except String ScopePassState + | [] => .ok acc + | arm :: rest => + let tagId := Syntax.getId (Syntax.getArg arm 1) + let tagStr := Name.toStringTotal tagId + let innerCmd := Syntax.getArg arm 3 + let innerCmd' := match innerCmd with + | .node info ik iargs => + match iargs.toList with + | a0 :: a1 :: a2 :: tail => + let rawId := Syntax.getId a2 + if !Name.isAnonymous rawId && !Name.isMergeConflict rawId then + let mergedId := Name.mkMergeVariant rawId tagStr + .node info ik (Stx.ofList (a0 :: a1 :: Syntax.mkSimpleIdent mergedId :: tail)) + else innerCmd + | _ => innerCmd + | _ => innerCmd + match processCommandPass1 fuel innerCmd' acc with + | .error e => .error e + | .ok acc' => runMerge acc' rest + runMerge ⟨currScope, frames, modIdx, revDecls, declCount, anonCount⟩ arms.toList + -- 11. Top-level declarations (`def`, `abbrev`, `theorem`, `axiom`, `opaque`, `instance`, `inductive`, `structure`, `class`) + else if k == SyntaxKind.defDecl || k == SyntaxKind.abbrevDecl || k == SyntaxKind.theoremDecl || + k == SyntaxKind.opaqueDecl || k == SyntaxKind.axiomDecl || k == SyntaxKind.instanceDecl || + k == SyntaxKind.inductiveDecl || k == SyntaxKind.structureDecl || k == SyntaxKind.classDecl then + let (isPriv, isProt) := extractModifierFlags (Syntax.getArg cmd 0) + let rawId := Syntax.getId (Syntax.getArg cmd 2) + let (shortName, anonCount') := + if Name.isAnonymous rawId then + (Name.mkStr Name.mkAnon (strAppendPure (str% "_inst_") (Nat.repr anonCount)), anonCount + 1) + else + (rawId, anonCount) + let fullName := Name.append currScope.currNamespace shortName + let explicitUnivs := extractUnivParams (Syntax.getArg cmd 3) + let declScope := { currScope with isPrivate := isPriv, isProtected := isProt } + let declKind : DeclKind := + if k == SyntaxKind.defDecl then .defn + else if k == SyntaxKind.abbrevDecl then .abbrev + else if k == SyntaxKind.theoremDecl then .thm + else if k == SyntaxKind.axiomDecl then .axiomDecl + else if k == SyntaxKind.opaqueDecl then .opaqueDecl + else if k == SyntaxKind.instanceDecl then .inst + else if k == SyntaxKind.inductiveDecl then .ind + else if k == SyntaxKind.structureDecl then .struct + else .cls + let (ctorNames, fieldNames) := + if k == SyntaxKind.inductiveDecl then + let ctorsNode := Syntax.getArg cmd 7 + (extractCtorNames fullName ctorsNode, []) + else if k == SyntaxKind.structureDecl || k == SyntaxKind.classDecl then + let customCtorNode := Syntax.getArg cmd 8 + let fieldsOrCtorsNode := Syntax.getArg cmd 9 + let firstChild? := (Syntax.getArgs fieldsOrCtorsNode)[0]? + match firstChild? with + | some c0 => + if Syntax.isOfKind c0 SyntaxKind.ctorDecl then + (extractCtorNames fullName fieldsOrCtorsNode, []) + else + let ctorShort := + let cid := Syntax.getId customCtorNode + if Name.isAnonymous cid then Name.simple (str% "mk") else cid + let ctorFull := Name.append fullName ctorShort + ([ctorFull], extractFieldNames fullName fieldsOrCtorsNode) + | none => + let ctorShort := + let cid := Syntax.getId customCtorNode + if Name.isAnonymous cid then Name.simple (str% "mk") else cid + let ctorFull := Name.append fullName ctorShort + ([ctorFull], []) + else + ([], []) + let decl : ModuleDecl := + { idx := declCount + kind := declKind + shortName := shortName + fullName := fullName + univParams := explicitUnivs + scope := declScope + stx := cmd + ctorNames := ctorNames + fieldNames := fieldNames } + let modIdx' := modIdx.registerDeclMaps declCount decl + InputContext.bindNat (declCount + 1) fun nextDeclCount' => + .ok ⟨currScope, frames, modIdx', decl :: revDecls, nextDeclCount', anonCount'⟩ + else if k == SyntaxKind.notationDecl || k == SyntaxKind.macroDecl then + let (_, mRules) := decodeNotationOrMacroDecl cmd + if mRules.isEmpty then + .ok ⟨currScope, frames, modIdx, revDecls, declCount, anonCount⟩ + else + match modIdx with + | ⟨decls, declByName, ctorToInd, fieldToStruct, auxToInd, importMap, macroRules⟩ => + .ok ⟨currScope, frames, + ⟨decls, declByName, ctorToInd, fieldToStruct, auxToInd, importMap, macroRules ++ Array.mk mRules⟩, + revDecls, declCount, anonCount⟩ + else + .ok ⟨currScope, frames, modIdx, revDecls, declCount, anonCount⟩ + +/-- Run Pass 1 over a parsed module `Syntax` node (`SyntaxKind.moduleKind`) to build `ModuleIndex`. -/ +def buildModuleIndex (moduleStx : Stx) : Except String ModuleIndex := + let cmds := Syntax.getArgs moduleStx + let rec runCmds (st : ScopePassState) : List Stx → Except String ScopePassState + | [] => .ok st + | cmd :: rest => + match processCommandPass1 64 cmd st with + | .error e => .error e + | .ok st' => runCmds st' rest + match runCmds {} cmds.toList with + | .error e => .error e + | .ok finalState => + match finalState.modIdx with + | ⟨_, declByName, ctorToInd, fieldToStruct, auxToInd, importMap, macroRules⟩ => + let declList := match finalState.revDecls.reverse with | [] => [] | d :: ds => d :: ds + .ok ⟨Array.mk declList, declByName, ctorToInd, fieldToStruct, auxToInd, importMap, macroRules⟩ + +/-! ## Lexical Name Resolution (`resolveIdentInScope`) -/ + +/-- Return all namespace prefixes of `ns` from most specific (`ns`) to root (`Name.mkAnon`). -/ +def namespacePrefixes : Ix.Name → List Ix.Name + | .anonymous h => [.anonymous h] + | n@(.str p _ _) => n :: namespacePrefixes p + | n@(.num p _ _) => n :: namespacePrefixes p + +/-- Resolve a surface identifier `id` under `scope : ScopeSnapshot` against `modIdx : ModuleIndex` + and an external predicate `isExtConst : Ix.Name → Bool`. + Returns all matching candidate full names in priority order. -/ +def resolveNameCandidates (scope : ScopeSnapshot) (modIdx : ModuleIndex) + (isExtConst : Ix.Name → Bool := fun _ => false) (id : Ix.Name) : List Ix.Name := + let isKnown (cand : Ix.Name) : Bool := + modIdx.containsSymbol cand || isExtConst cand + -- 1. Walk enclosing namespaces from innermost (`currNamespace ++ id`) to root (`id`) + let nsCands := (namespacePrefixes scope.currNamespace).filterMap fun pre => + let cand := Name.append pre id + if isKnown cand then some cand else none + -- 2. Check `open` declarations + let openCands := scope.openDecls.filterMap fun od => + match od with + | .simple ns only => + if !only.isEmpty && !only.contains id then none + else + let cand := Name.append ns id + if isKnown cand then some cand else none + | .explicit aliasName declName => + if id == aliasName && isKnown declName then some declName else none + (nsCands ++ openCands).eraseDups + +/-- Resolve `id` to its highest-priority candidate in `scope`, or `id` itself if unresolved + (mapping the standard Mathlib/Lean unicode alias `ℕ` to `Nat` when `ℕ` is not locally declared). -/ +def resolveIdentInScope (scope : ScopeSnapshot) (modIdx : ModuleIndex) + (isExtConst : Ix.Name → Bool := fun _ => false) (id : Ix.Name) : Ix.Name := + if (match scope.currNamespace with | .anonymous _ => true | _ => false) && scope.openDecls.isEmpty then + if id == Name.simple (str% "ℕ") then + if modIdx.containsSymbol id || isExtConst id then id else Name.simple (str% "Nat") + else + id + else + match resolveNameCandidates scope modIdx isExtConst id with + | best :: _ => best + | [] => if id == Name.simple (str% "ℕ") then Name.simple (str% "Nat") else id + +/-- First-order check whether `cand` is known in `modIdx` or `envConsts`. -/ +@[inline] def isKnownConstMap (modIdx : ModuleIndex) (envConsts : NameMap Ix.ConstantInfo) + (cand : Ix.Name) : Bool := + modIdx.containsSymbol cand || envConsts.contains cand + +/-- First-order candidate resolution without closures or `List.filterMap`. -/ +def resolveNameCandidatesMap (scope : ScopeSnapshot) (modIdx : ModuleIndex) + (envConsts : NameMap Ix.ConstantInfo) (id : Ix.Name) : List Ix.Name := + let rec goNs : List Ix.Name → List Ix.Name + | [] => [] + | pre :: rest => + let cand := Name.append pre id + let tail := goNs rest + if isKnownConstMap modIdx envConsts cand then cand :: tail else tail + let rec goOpen : List OpenDecl → List Ix.Name + | [] => [] + | od :: rest => + let tail := goOpen rest + match od with + | .simple ns only => + if !only.isEmpty && !only.contains id then tail + else + let cand := Name.append ns id + if isKnownConstMap modIdx envConsts cand then cand :: tail else tail + | .explicit aliasName declName => + if id == aliasName && isKnownConstMap modIdx envConsts declName then declName :: tail else tail + let rec dedup (seen : List Ix.Name) : List Ix.Name → List Ix.Name + | [] => [] + | x :: xs => + if seen.contains x then dedup seen xs else x :: dedup (x :: seen) xs + dedup [] (goNs (namespacePrefixes scope.currNamespace) ++ goOpen scope.openDecls) + +/-- First-order `resolveIdentInScope` taking `envConsts : NameMap Ix.ConstantInfo` directly. -/ +def resolveIdentInScopeMap (scope : ScopeSnapshot) (modIdx : ModuleIndex) + (envConsts : NameMap Ix.ConstantInfo) (id : Ix.Name) : Ix.Name := + if (match scope.currNamespace with | .anonymous _ => true | _ => false) && scope.openDecls.isEmpty then + if id == Name.simple (str% "ℕ") then + if isKnownConstMap modIdx envConsts id then id else Name.simple (str% "Nat") + else + id + else + match resolveNameCandidatesMap scope modIdx envConsts id with + | best :: _ => best + | [] => if id == Name.simple (str% "ℕ") then Name.simple (str% "Nat") else id + +end Ix.Frontend diff --git a/Ix/Frontend/Sym.lean b/Ix/Frontend/Sym.lean new file mode 100644 index 0000000000..13914197f6 --- /dev/null +++ b/Ix/Frontend/Sym.lean @@ -0,0 +1,330 @@ +/- + Ix.Frontend.Sym: Monomorphic UTF-8 byte-string (`ByteList` / `Sym`), + lightweight `FName`, and `FSourceInfo` with compile-time `s% "..."` and + `fn% "..."` macros. + + Eliminates all Lean `String` literals (`Lit.str` / `Obj::S`), `ByteArray`, + `Char`, `UInt8`, `UInt32`, and `Nat.bitwise` from the IxCC → Aiur circuit + closure, matching `IxVMIO::Bytes::Stream` (`ByteList`) with zero conversion! +-/ +module + +public import Lean +public import Ix.Environment + +@[expose] public section + +set_option autoImplicit false + +namespace Ix.Frontend + +/-! ## Section 1: Monomorphic UTF-8 Byte List (`ByteList` / `Sym`) -/ + +/-- Canonical UTF-8 byte list for `Sym`. Constructor order (`cons` before `nil`) + is intentionally distinct from `Wire.ByteList` (`nil` before `cons`) so Ixon + assigns them different content addresses and `Sym`'s polymorphic usage never + pollutes `Wire.ByteList` out of zero-copy `Bytes::Stream` lowering! -/ +inductive ByteList where + | cons (byte : Nat) (rest : ByteList) + | nil + deriving BEq, DecidableEq, Repr + +instance : Inhabited ByteList := ⟨.nil⟩ + +/-- Monomorphic UTF-8 byte string used throughout the circuit-compiled frontend. -/ +abbrev Sym := ByteList + +namespace Sym + +def empty : Sym := .nil + +@[inline] def isEmpty : Sym → Bool + | .nil => true + | .cons _ _ => false + +def beq : Sym → Sym → Bool + | .nil, .nil => true + | .cons a as, .cons b bs => if Nat.beq a b then beq as bs else false + | _, _ => false + +instance (priority := 2000) : BEq ByteList where + beq := Sym.beq + +def cmp : Sym → Sym → Ordering + | .nil, .nil => .eq + | .nil, .cons _ _ => .lt + | .cons _ _, .nil => .gt + | .cons a as, .cons b bs => + if Nat.blt a b then .lt + else if Nat.blt b a then .gt + else cmp as bs + +def lengthAcc : Sym → Nat → Nat + | .nil, acc => acc + | .cons _ rest, acc => lengthAcc rest (Nat.add acc 1) + +def length (s : Sym) : Nat := lengthAcc s 0 + +def reverseAcc : Sym → Sym → Sym + | .nil, acc => acc + | .cons b rest, acc => reverseAcc rest (.cons b acc) + +def reverse (s : Sym) : Sym := reverseAcc s .nil + +/-- Prepend `s` in front of `tail` in O(|s|) without intermediate reversal. -/ +def append : Sym → Sym → Sym + | .nil, tail => tail + | .cons b rest, tail => .cons b (append rest tail) + +/-- Prepend reversed `rev` in front of `tail` (`rev.reverse ++ tail`) in O(|rev|). -/ +def prependRev : Sym → Sym → Sym + | .nil, tail => tail + | .cons b rest, tail => prependRev rest (.cons b tail) + +def drop : Nat → Sym → Sym + | 0, s => s + | _, .nil => .nil + | n + 1, .cons _ rest => drop n rest + +def dropPrefix : Sym → Sym → Option Sym + | .nil, bs => some bs + | .cons p ps, .cons b bs => if Nat.beq p b then dropPrefix ps bs else none + | .cons _ _, .nil => none + +def intercalate (sep : Sym) : List Sym → Sym + | [] => .nil + | [x] => x + | x :: xs => append x (append sep (intercalate sep xs)) + +/-- Strict UTF-8 validation on `ByteList` (RFC 3629: rejects overlong encodings, + UTF-16 surrogates U+D800..U+DFFF, and codepoints > U+10FFFF). + Pure `Nat` comparisons (< 256), zero `Char`/`UInt32`/`Nat.bitwise`! -/ +def validateUtf8 : ByteList → Bool + | .nil => true + | .cons b0 r1 => + if Nat.blt b0 128 then + validateUtf8 r1 + else if Nat.ble 194 b0 && Nat.ble b0 223 then + match r1 with + | .cons b1 r2 => + if Nat.ble 128 b1 && Nat.ble b1 191 then validateUtf8 r2 else false + | _ => false + else if Nat.ble 224 b0 && Nat.ble b0 239 then + match r1 with + | .cons b1 (.cons b2 r3) => + let ok1 := + if Nat.beq b0 224 then Nat.ble 160 b1 && Nat.ble b1 191 + else if Nat.beq b0 237 then Nat.ble 128 b1 && Nat.ble b1 159 + else Nat.ble 128 b1 && Nat.ble b1 191 + if ok1 && Nat.ble 128 b2 && Nat.ble b2 191 then validateUtf8 r3 else false + | _ => false + else if Nat.ble 240 b0 && Nat.ble b0 244 then + match r1 with + | .cons b1 (.cons b2 (.cons b3 r4)) => + let ok1 := + if Nat.beq b0 240 then Nat.ble 144 b1 && Nat.ble b1 191 + else if Nat.beq b0 244 then Nat.ble 128 b1 && Nat.ble b1 143 + else Nat.ble 128 b1 && Nat.ble b1 191 + if ok1 && Nat.ble 128 b2 && Nat.ble b2 191 && + Nat.ble 128 b3 && Nat.ble b3 191 then validateUtf8 r4 else false + | _ => false + else + false + +/-- Count Unicode scalar characters in a valid UTF-8 `ByteList` + (counts bytes that are NOT UTF-8 continuation bytes `0x80..0xBF`). -/ +def utf8CharCountAcc : ByteList → Nat → Nat + | .nil, acc => acc + | .cons b rest, acc => + if Nat.ble 128 b && Nat.ble b 191 then + utf8CharCountAcc rest acc + else + utf8CharCountAcc rest (Nat.add acc 1) + +def utf8CharCount (s : Sym) : Nat := utf8CharCountAcc s 0 + +/-- Host-only conversion: `String → Sym` (UTF-8 bytes). -/ +def ofString (s : String) : Sym := + s.toUTF8.data.toList.foldr (fun b acc => .cons b.toNat acc) .nil + +/-- Host-only conversion: `Sym → ByteArray`. -/ +def toByteArray (s : Sym) : ByteArray := + let rec go : Sym → List UInt8 → List UInt8 + | .nil, acc => acc.reverse + | .cons b rest, acc => go rest (UInt8.ofNat b :: acc) + ByteArray.mk (Array.mk (go s [])) + +/-- Circuit-safe conversion `Sym → String` (zero `panicWithPosWithDecl`, zero `Lit.str`). -/ +def toString (s : Sym) : String := + let ba := toByteArray s + if h : ba.IsValidUTF8 then String.ofByteArray ba h + else String.ofByteArray ByteArray.empty (by decide) + +/-- Decimal formatting of `Nat` into `Sym` (pure `Nat` div/mod, no `String`). -/ +def ofNatAux : Nat → Nat → Sym → Sym + | 0, _, acc => acc + | k + 1, n, acc => + let d := Nat.add 48 (Nat.mod n 10) + let q := Nat.div n 10 + if Nat.beq q 0 then .cons d acc + else ofNatAux k q (.cons d acc) + +def ofNat (n : Nat) : Sym := + ofNatAux 20 n .nil + +end Sym + +/-! ## Section 2: Lightweight `FName` (Zero `String`, Zero `Address`) -/ + +/-- Monomorphic hierarchical name using `Sym` (`ByteList`) with zero `String` or `Address` fields. -/ +inductive FName where + | anon + | str (pre : FName) (s : Sym) + | num (pre : FName) (n : Nat) + deriving BEq, DecidableEq, Repr, Inhabited + +namespace FName + +@[inline] def isAnonymous : FName → Bool + | .anon => true + | _ => false + +def beq : FName → FName → Bool + | .anon, .anon => true + | .str p1 s1, .str p2 s2 => if Sym.beq s1 s2 then beq p1 p2 else false + | .num p1 n1, .num p2 n2 => if Nat.beq n1 n2 then beq p1 p2 else false + | _, _ => false + +instance (priority := 2000) : BEq FName where + beq := FName.beq + +def cmp : FName → FName → Ordering + | .anon, .anon => .eq + | .anon, _ => .lt + | _, .anon => .gt + | .num p1 n1, .num p2 n2 => + if Nat.blt n1 n2 then .lt + else if Nat.blt n2 n1 then .gt + else cmp p1 p2 + | .num .., .str .. => .lt + | .str .., .num .. => .gt + | .str p1 s1, .str p2 s2 => + match Sym.cmp s1 s2 with + | .eq => cmp p1 p2 + | ord => ord + +def toSym : FName → Sym + | .anon => .nil + | .str .anon s => s + | .str p s => Sym.append (toSym p) (.cons 46 s) + | .num .anon n => Sym.ofNat n + | .num p n => Sym.append (toSym p) (.cons 46 (Sym.ofNat n)) + +@[inline] def simple (s : Sym) : FName := .str .anon s +@[inline] def mkStr (pre : FName) (s : Sym) : FName := .str pre s +@[inline] def mkStr2 (s1 s2 : Sym) : FName := .str (.str .anon s1) s2 +@[inline] def mkNat (pre : FName) (n : Nat) : FName := .num pre n + +/-- Host-only conversion: `FName → Ix.Name`. -/ +def toIxName : FName → Ix.Name + | .anon => .anonymous ⟨ByteArray.empty⟩ + | .str pre s => .str (toIxName pre) (Sym.toString s) ⟨ByteArray.empty⟩ + | .num pre n => .num (toIxName pre) n ⟨ByteArray.empty⟩ + +/-- Host-only conversion: `Ix.Name → FName`. -/ +def ofIxName : Ix.Name → FName + | .anonymous _ => .anon + | .str pre s _ => .str (ofIxName pre) (Sym.ofString s) + | .num pre n _ => .num (ofIxName pre) n + +end FName + +/-! ## Section 3: Lightweight `FSourceInfo` (Zero `String` / `Ix.Substring`) -/ + +/-- Compact source span carrying only the information the parser & elaborator read: + whether leading trivia contained a newline (`hasLeadingNl`) and token span `[startPos, stopPos)`. -/ +inductive FSourceInfo where + | none + | original (hasLeadingNl : Bool) (startPos stopPos : Nat) + deriving BEq, DecidableEq, Repr, Inhabited + +namespace FSourceInfo + +@[inline] def hasLeadingNewline : FSourceInfo → Bool + | .original hasNl _ _ => hasNl + | .none => false + +@[inline] def startPos? : FSourceInfo → Option Nat + | .original _ pos _ => Option.some pos + | .none => Option.none + +@[inline] def endPos? : FSourceInfo → Option Nat + | .original _ _ pos => Option.some pos + | .none => Option.none + +/-- Host-only conversion to `Ix.SourceInfo`. -/ +def toIxSourceInfo : FSourceInfo → Ix.SourceInfo + | .none => .none + | .original hasNl startPos stopPos => + let emptyStr := String.ofByteArray (ByteArray.mk (Array.mk [])) (by decide) + let nlStr := String.ofByteArray (ByteArray.mk (Array.mk [UInt8.ofNat 10])) (by decide) + let trailing : Ix.Substring := { str := emptyStr, startPos := 0, stopPos := 0 } + if hasNl then + .original { str := nlStr, startPos := 0, stopPos := 1 } startPos trailing stopPos + else + .original { str := emptyStr, startPos := 0, stopPos := 0 } startPos trailing stopPos + +/-- Host-only conversion from `Ix.SourceInfo`. -/ +def ofIxSourceInfo : Ix.SourceInfo → FSourceInfo + | .original leading pos _ endPos => + .original (leading.str.toList.contains '\n') pos endPos + | _ => .none + +end FSourceInfo + +/-! ## Section 4: Compile-Time Macros `s% "..."` and `fn% "..."` (Zero `Lit.str`!) -/ + +open Lean in +meta def mkByteListTerm (bytes : List UInt8) : Term := + bytes.foldr + (fun b acc => Unhygienic.run `(Ix.Frontend.ByteList.cons $(quote b.toNat) $acc)) + (Unhygienic.run `(Ix.Frontend.ByteList.nil)) + +open Lean in +meta def mkFNameTerm (parts : List String) : Term := + parts.foldl + (fun acc p => + let symTerm := mkByteListTerm p.toUTF8.data.toList + Unhygienic.run `(Ix.Frontend.FName.str $acc $symTerm)) + (Unhygienic.run `(Ix.Frontend.FName.anon)) + +/-- Compile-time UTF-8 `Sym` (`ByteList`) literal: `s% "def"` expands to + `ByteList.cons 100 (ByteList.cons 101 (ByteList.cons 102 ByteList.nil))` with zero `Lit.str`! -/ +syntax "s% " str : term +macro_rules + | `(s% $lit:str) => pure (mkByteListTerm lit.getString.toUTF8.data.toList) + +/-- Compile-time `FName` literal: `fn% "Ix.term.app"` expands to nested `FName.str` + with zero `Lit.str`! -/ +syntax "fn% " str : term +macro_rules + | `(fn% $lit:str) => + let s := lit.getString + let parts := if s.isEmpty then [] else s.splitOn "." + pure (mkFNameTerm parts) + +open Lean in +meta def mkUInt8ListTerm (bytes : List UInt8) : Term := + bytes.foldr + (fun b acc => Unhygienic.run `(List.cons (UInt8.ofNat $(quote b.toNat)) $acc)) + (Unhygienic.run `(List.nil)) + +/-- Compile-time constructor-based `String` literal (`String.ofByteArray ... (by decide)`): + has type `String` with ZERO `Lit.str` / `Obj::S` in IxCC! -/ +syntax "str% " str : term +macro_rules + | `(str% $lit:str) => + let xs := mkUInt8ListTerm lit.getString.toUTF8.data.toList + `(String.ofByteArray (ByteArray.mk (Array.mk $xs)) (by decide)) + +end Ix.Frontend diff --git a/Ix/Frontend/Syntax.lean b/Ix/Frontend/Syntax.lean new file mode 100644 index 0000000000..1e05170f14 --- /dev/null +++ b/Ix/Frontend/Syntax.lean @@ -0,0 +1,1360 @@ +/- + Ix.Frontend.Syntax: Pure constructors and syntax node helpers for the Ix Frontend. + + All content hashes are computed via `Address.admissionHash` (`Address.blake3Pure` in the + kernel logic, `@[implemented_by Address.blake3]` on the host), so every constructor is + 100% pure, total, and kernel-reducible while producing byte-identical `Address` digests + to `Ix.Environment`. +-/ +module + +public import Ix.Environment +public import Ix.Frontend.Sym +public import Ix.Address.Admission +public import IxCK.Ixon.Types.Modes +public import IxCK.Ixon.Types.Contract + +@[expose] public section + +namespace Ix.Frontend + +/-- Strict binding helper (identity under call-by-value `IxCCAiur` / native Lean). -/ +@[inline] def forceNat (n : Nat) (k : Nat → α) : α := k n + +/-- Pure `Nat` total order using `Nat.ble` and `Nat.beq` (zero `Decidable` proof terms). -/ +@[inline] def natCmpPure (a b : Nat) : Ordering := + forceNat a fun a' => + forceNat b fun b' => + if Nat.ble (a' + 1) b' then .lt + else if Nat.beq a' b' then .eq + else .gt + +/-- Proof-free `BEq Char` instance avoiding `Char.decEq -> UInt32.decEq -> BitVec.decEq -> Fin.decEq`. -/ +scoped instance (priority := 2000) : BEq Char where + beq a b := Nat.beq a.val.toNat b.val.toNat + +/-- Structural byte-list equality on `List UInt8` (zero proof terms). -/ +def bytesBeq : List UInt8 → List UInt8 → Bool + | [], [] => true + | a :: as, b :: bs => Nat.beq a.toNat b.toNat && bytesBeq as bs + | _, _ => false + +/-- Structural lexicographical comparison on `List UInt8` (zero `WellFounded.fix` or proof terms). -/ +def bytesCmp : List UInt8 → List UInt8 → Ordering + | [], [] => .eq + | [], _ :: _ => .lt + | _ :: _, [] => .gt + | a :: as, b :: bs => + forceNat a.toNat fun na => + forceNat b.toNat fun nb => + if Nat.ble (na + 1) nb then .lt + else if Nat.ble (nb + 1) na then .gt + else bytesCmp as bs + +/-- Structural character-list equality on `List Char` (zero proof terms, zero UTF-8 re-encoding). -/ +def charsBeq : List Char → List Char → Bool + | [], [] => true + | a :: as, b :: bs => Nat.beq a.val.toNat b.val.toNat && charsBeq as bs + | _, _ => false + +/-- Structural lexicographical comparison on `List Char` (zero `WellFounded.fix` or proof terms). -/ +def charsCmp : List Char → List Char → Ordering + | [], [] => .eq + | [], _ :: _ => .lt + | _ :: _, [] => .gt + | a :: as, b :: bs => + forceNat a.val.toNat fun na => + forceNat b.val.toNat fun nb => + if Nat.ble (na + 1) nb then .lt + else if Nat.ble (nb + 1) na then .gt + else charsCmp as bs + +/-- Pure structural equality on `String` directly over UTF-8 bytes (zero `String.toList`, zero `Char`). -/ +@[inline] def strBeqPure (a b : String) : Bool := + bytesBeq a.toByteArray.data.toList b.toByteArray.data.toList + +/-- Pure structural lexicographical order on `String` directly over UTF-8 bytes + (compares byte length first for O(1) shortlex, matching previous `strCmpPure`). -/ +@[inline] def strCmpPure (a b : String) : Ordering := + match natCmpPure a.toByteArray.data.size b.toByteArray.data.size with + | .eq => bytesCmp a.toByteArray.data.toList b.toByteArray.data.toList + | ord => ord + +scoped instance (priority := 2000) : BEq String where + beq := strBeqPure + +scoped instance (priority := 2000) : Ord String where + compare := strCmpPure + +/-- Pure UTF-8 byte concatenation on `String` (zero `String.toList`, zero `Char`, zero `opaque`). -/ +@[inline] def strAppendPure (a b : String) : String := + String.ofByteArray (a.toByteArray ++ b.toByteArray) + (ByteArray.IsValidUTF8.append a.isValidUTF8 b.isValidUTF8) + +scoped instance (priority := 2000) : Append String where + append := strAppendPure + +/-- Pure `intercalate` over `List String` using `strAppendPure`. -/ +def strIntercalatePure (sep : String) : List String → String + | [] => str% "" + | [x] => x + | x :: xs => strAppendPure x (strAppendPure sep (strIntercalatePure sep xs)) + +/-- Placeholder empty `Address` used during intermediate AST/expression construction + so that `Address.admissionHash` (`Blake3.Pure.hash`) is not evaluated on every + temporary `Name`, `Level`, or `Expr` node during parsing and elaboration. + Exact 32-byte Merkle hashes are populated on demand via `Name.computeHash` and `ConstantInfo.rehash`. -/ +def dummyAddr : Address := ⟨ByteArray.mk #[]⟩ + +/-! ## Pure `Ix.Name` Constructors & Operations -/ + +namespace Name + +/-- The anonymous root `Ix.Name` (with deferred `dummyAddr`). -/ +def mkAnon : Ix.Name := + .anonymous dummyAddr + +/-- Construct a string component `Ix.Name` (with deferred `dummyAddr`). -/ +def mkStr (pre : Ix.Name) (s : String) : Ix.Name := + .str pre s dummyAddr + +/-- Construct a numeric component `Ix.Name` (with deferred `dummyAddr`). -/ +def mkNat (pre : Ix.Name) (i : Nat) : Ix.Name := + .num pre i dummyAddr + +/-- Compute the canonical 32-byte `Address` of an `Ix.Name` via `Address.admissionHash`, + reusing an already-populated 32-byte hash when present. -/ +def computeHash : Ix.Name → Address + | .anonymous h => + if Nat.beq h.hash.size 32 then h + else Address.admissionHash (ByteArray.mk #[Ix.TAG_NANON]) + | .str p s h => + if Nat.beq h.hash.size 32 then h + else Address.admissionHash (ByteArray.mk #[Ix.TAG_NSTR] ++ (computeHash p).hash ++ s.toUTF8) + | .num p i h => + if Nat.beq h.hash.size 32 then h + else Address.admissionHash (ByteArray.mk #[Ix.TAG_NNUM] ++ (computeHash p).hash ++ ⟨i.toBytesLE⟩) + +/-- Recursively populate the canonical 32-byte `Address` hash on every node of an `Ix.Name`. -/ +def rehash : Ix.Name → Ix.Name + | n@(.anonymous h) => + if Nat.beq h.hash.size 32 then n + else .anonymous (Address.admissionHash (ByteArray.mk #[Ix.TAG_NANON])) + | n@(.str p s h) => + if Nat.beq h.hash.size 32 then n + else + let p' := rehash p + .str p' s (Address.admissionHash (ByteArray.mk #[Ix.TAG_NSTR] ++ p'.getHash.hash ++ s.toUTF8)) + | n@(.num p i h) => + if Nat.beq h.hash.size 32 then n + else + let p' := rehash p + .num p' i (Address.admissionHash (ByteArray.mk #[Ix.TAG_NNUM] ++ p'.getHash.hash ++ ⟨i.toBytesLE⟩)) + +/-- Structural equality on `Ix.Name` that reads no hash (avoiding `Address.blake3Pure` + reduction during kernel and `IxVM` evaluation of parsing and elaboration). -/ +def beqStruct : Ix.Name → Ix.Name → Bool + | .anonymous _, .anonymous _ => true + | .str p1 s1 _, .str p2 s2 _ => strBeqPure s1 s2 && beqStruct p1 p2 + | .num p1 i1 _, .num p2 i2 _ => Nat.beq i1 i2 && beqStruct p1 p2 + | _, _ => false + +/-- Leaf-first structural total order on `Ix.Name` that reads no hash and compares + the leaf component (`i₁` vs `i₂` or `s₁` vs `s₂`) before recursing on the prefix. -/ +def cmpStruct : Ix.Name → Ix.Name → Ordering + | .anonymous _, .anonymous _ => .eq + | .anonymous _, _ => .lt + | _, .anonymous _ => .gt + | .num p₁ i₁ _, .num p₂ i₂ _ => (natCmpPure i₁ i₂).then (cmpStruct p₁ p₂) + | .num .., .str .. => .lt + | .str .., .num .. => .gt + | .str p₁ s₁ _, .str p₂ s₂ _ => (strCmpPure s₁ s₂).then (cmpStruct p₁ p₂) + +instance (priority := 2000) : Inhabited Ix.Name where + default := mkAnon + +instance (priority := 2000) : BEq Ix.Name where + beq := beqStruct + +instance (priority := 2000) : Ord Ix.Name where + compare := cmpStruct + +/-- Build a hierarchical `Ix.Name` from a list of string components. -/ +def fromComponents (parts : List String) : Ix.Name := + parts.foldl mkStr mkAnon + +/-- Build a single-component `Ix.Name`. -/ +def simple (s : String) : Ix.Name := + mkStr mkAnon s + +/-- Build a two-component `Ix.Name`. -/ +def mkStr2 (s1 s2 : String) : Ix.Name := + mkStr (mkStr mkAnon s1) s2 + +/-- Build a three-component `Ix.Name`. -/ +def mkStr3 (s1 s2 s3 : String) : Ix.Name := + mkStr (mkStr (mkStr mkAnon s1) s2) s3 + +/-- True if the name is `.anonymous`. -/ +def isAnonymous : Ix.Name → Bool + | .anonymous _ => true + | _ => false + +/-- Append two `Ix.Name`s purely (`a ++ b`). -/ +def append (a b : Ix.Name) : Ix.Name := + if isAnonymous a then b else go b +where + go : Ix.Name → Ix.Name + | .anonymous _ => a + | .str p s _ => mkStr (go p) s + | .num p i _ => mkNat (go p) i + +/-- Extract the string components of a name from root to leaf. -/ +def componentsRev : Ix.Name → List String + | .anonymous _ => [] + | .str p s _ => s :: componentsRev p + | .num p n _ => toString n :: componentsRev p + +def components (n : Ix.Name) : List String := + (componentsRev n).reverse + +/-- Check whether `pre` is a structural prefix of `n`. -/ +def isPrefixOf (pre : Ix.Name) : Ix.Name → Bool + | .anonymous _ => isAnonymous pre + | n@(.str p _ _) => if pre == n then true else isPrefixOf pre p + | n@(.num p _ _) => if pre == n then true else isPrefixOf pre p + +/-- Replace prefix `pre` with `newPre` in `n`. -/ +def replacePrefix (n pre newPre : Ix.Name) : Ix.Name := + if n == pre then newPre + else match n with + | .anonymous _ => n + | .str p s _ => + let p' := replacePrefix p pre newPre + if p' == p then n else mkStr p' s + | .num p i _ => + let p' := replacePrefix p pre newPre + if p' == p then n else mkNat p' i + +/-- Total `toString` for `Ix.Name`. -/ +def toStringTotal : Ix.Name → String + | .anonymous _ => str% "[anonymous]" + | .str (.anonymous _) s _ => s + | .str p s _ => strAppendPure (strAppendPure (toStringTotal p) (str% ".")) s + | .num (.anonymous _) i _ => toString i + | .num p i _ => strAppendPure (strAppendPure (toStringTotal p) (str% ".")) (toString i) + +/-- Reserved component marker for first-class `IxVCS` merge conflicts (`orig.#merge.`). -/ +def mergeMarker : String := str% "#merge" + +/-- Construct a first-class conflict variant name `orig.#merge.` + (e.g. `Acme.foobar.#merge._1` or `Acme.foobar.#merge.X`). -/ +def mkMergeVariant (orig : Ix.Name) (tag : String) : Ix.Name := + mkStr (mkStr orig (str% "#merge")) tag + +/-- Structural helper for `splitMergeVariant?`. -/ +def splitMergeVariantAux : Ix.Name → List String → Option (Ix.Name × String × List String) + | .anonymous _, _ => none + | .str p tag _, trailing => + match p with + | .str orig m _ => + if strBeqPure m (str% "#merge") then some (orig, tag, trailing) + else splitMergeVariantAux p (tag :: trailing) + | _ => + splitMergeVariantAux p (tag :: trailing) + | .num p i _, trailing => + splitMergeVariantAux p (toString i :: trailing) + +/-- Check if `n` contains a `.#merge.` segment, returning + `some (origBaseName, variantTag, trailingComponents)`. + - `Acme.foobar.#merge._1` ↦ `some (Acme.foobar, "_1", [])` + - `Acme.Expr.#merge._1.lit` ↦ `some (Acme.Expr, "_1", ["lit"])` -/ +def splitMergeVariant? (n : Ix.Name) : Option (Ix.Name × String × List String) := + splitMergeVariantAux n [] + +/-- True if `n` is a `.#merge.` conflict declaration or auxiliary. -/ +def isMergeConflict (n : Ix.Name) : Bool := + (splitMergeVariant? n).isSome + +/-- If `n` is `orig.#merge.[.trailing...]`, return `some (orig[.trailing...])`. -/ +def conflictOrigName? (n : Ix.Name) : Option Ix.Name := + match splitMergeVariant? n with + | some (orig, _, trailing) => some (trailing.foldl mkStr orig) + | none => none + +end Name + +/-! ## Pure `Ix.Level` & `Ix.Expr` Constructors -/ + +namespace Level + +def mkZero : Ix.Level := + .zero dummyAddr + +def mkSucc (x : Ix.Level) : Ix.Level := + .succ x dummyAddr + +def mkMax (x y : Ix.Level) : Ix.Level := + .max x y dummyAddr + +def mkIMax (x y : Ix.Level) : Ix.Level := + .imax x y dummyAddr + +def mkParam (n : Ix.Name) : Ix.Level := + .param n dummyAddr + +def mkMVar (n : Ix.Name) : Ix.Level := + .mvar n dummyAddr + +def ofNat : Nat → Ix.Level + | 0 => mkZero + | n + 1 => mkSucc (ofNat n) + +/-- Recursively populate the canonical 32-byte `Address` hash on every node of an `Ix.Level`. -/ +def rehash : Ix.Level → Ix.Level + | l@(.zero h) => + if Nat.beq h.hash.size 32 then l + else .zero (Address.admissionHash (ByteArray.mk #[Ix.TAG_UZERO])) + | l@(.succ x h) => + if Nat.beq h.hash.size 32 then l + else + let x' := rehash x + .succ x' (Address.admissionHash (ByteArray.mk #[Ix.TAG_USUCC] ++ x'.getHash.hash)) + | l@(.max x y h) => + if Nat.beq h.hash.size 32 then l + else + let x' := rehash x + let y' := rehash y + .max x' y' (Address.admissionHash (ByteArray.mk #[Ix.TAG_UMAX] ++ x'.getHash.hash ++ y'.getHash.hash)) + | l@(.imax x y h) => + if Nat.beq h.hash.size 32 then l + else + let x' := rehash x + let y' := rehash y + .imax x' y' (Address.admissionHash (ByteArray.mk #[Ix.TAG_UIMAX] ++ x'.getHash.hash ++ y'.getHash.hash)) + | l@(.param n h) => + if Nat.beq h.hash.size 32 then l + else + let n' := Name.rehash n + .param n' (Address.admissionHash (ByteArray.mk #[Ix.TAG_UPARAM] ++ n'.getHash.hash)) + | l@(.mvar n h) => + if Nat.beq h.hash.size 32 then l + else + let n' := Name.rehash n + .mvar n' (Address.admissionHash (ByteArray.mk #[Ix.TAG_UMVAR] ++ n'.getHash.hash)) + +/-- Structural equality on `Ix.Level` that reads no hash. -/ +def beqStruct : Ix.Level → Ix.Level → Bool + | .zero _, .zero _ => true + | .succ a _, .succ b _ => beqStruct a b + | .max a1 a2 _, .max b1 b2 _ => beqStruct a1 b1 && beqStruct a2 b2 + | .imax a1 a2 _, .imax b1 b2 _ => beqStruct a1 b1 && beqStruct a2 b2 + | .param n1 _, .param n2 _ => Name.beqStruct n1 n2 + | .mvar n1 _, .mvar n2 _ => Name.beqStruct n1 n2 + | _, _ => false + +instance (priority := 2000) : Inhabited Ix.Level where + default := mkZero + +instance (priority := 2000) : BEq Ix.Level where + beq := beqStruct + +end Level + +namespace Expr + +def mkBVar (idx : Nat) : Ix.Expr := + .bvar idx dummyAddr + +def mkFVar (name : Ix.Name) : Ix.Expr := + .fvar name dummyAddr + +def mkMVar (name : Ix.Name) : Ix.Expr := + .mvar name dummyAddr + +def mkSort (u : Ix.Level) : Ix.Expr := + .sort u dummyAddr + +def mkProp : Ix.Expr := + mkSort Level.mkZero + +def mkType (u : Ix.Level := Level.mkZero) : Ix.Expr := + mkSort (Level.mkSucc u) + +def mkConst (name : Ix.Name) (us : Array Ix.Level := #[]) : Ix.Expr := + .const name us dummyAddr + +def mkApp (f a : Ix.Expr) : Ix.Expr := + .app f a dummyAddr + +def mkAppList : Ix.Expr → List Ix.Expr → Ix.Expr + | f, [] => f + | f, a :: as => mkAppList (mkApp f a) as + +def mkAppN (f : Ix.Expr) (args : Array Ix.Expr) : Ix.Expr := + mkAppList f args.toList + +def mkLam (n : Ix.Name) (t b : Ix.Expr) (bi : Lean.BinderInfo := .default) : Ix.Expr := + .lam n t b bi dummyAddr + +def mkForallE (n : Ix.Name) (t b : Ix.Expr) (bi : Lean.BinderInfo := .default) : Ix.Expr := + .forallE n t b bi dummyAddr + +def mkArrow (d c : Ix.Expr) : Ix.Expr := + mkForallE Name.mkAnon d c .default + +def mkLetE (n : Ix.Name) (t v b : Ix.Expr) (nonDep : Bool := false) : Ix.Expr := + .letE n t v b nonDep dummyAddr + +def mkLit (l : Lean.Literal) : Ix.Expr := + .lit l dummyAddr + +def mkNatLit (n : Nat) : Ix.Expr := + mkLit (.natVal n) + +def mkStrLit (s : String) : Ix.Expr := + mkLit (.strVal s) + +def mkProj (typeName : Ix.Name) (idx : Nat) (struct : Ix.Expr) : Ix.Expr := + .proj typeName idx struct dummyAddr + +/-- Encode an `Ix.Int` into bytes matching `Ix.Expr.hashInt`. -/ +def encodeIntBytes : Ix.Int → ByteArray + | .ofNat n => ByteArray.mk #[Ix.TAG_MINT, 0] ++ ⟨n.toBytesLE⟩ + | .negSucc n => ByteArray.mk #[Ix.TAG_MINT, 1] ++ ⟨n.toBytesLE⟩ + +/-- Rehash any `Ix.Name` inside an `Ix.DataValue`. -/ +def rehashDataValue : Ix.DataValue → Ix.DataValue + | .ofName n => .ofName (Name.rehash n) + | dv => dv + +/-- Encode an `Ix.DataValue` into bytes matching `Ix.Expr.hashDataValue` (for non-syntax metadata). -/ +def encodeDataValueBytes : Ix.DataValue → ByteArray + | .ofString s => ByteArray.mk #[Ix.TAG_MDVAL, 0] ++ s.toUTF8 + | .ofBool b => ByteArray.mk #[Ix.TAG_MDVAL, 1, if b then 1 else 0] + | .ofName n => ByteArray.mk #[Ix.TAG_MDVAL, 2] ++ (Name.computeHash n).hash + | .ofNat n => ByteArray.mk #[Ix.TAG_MDVAL, 3] ++ ⟨n.toBytesLE⟩ + | .ofInt i => ByteArray.mk #[Ix.TAG_MDVAL, 4] ++ encodeIntBytes i + | .ofSyntax _ => ByteArray.mk #[Ix.TAG_MDVAL, 5, Ix.TAG_MSYN, 0] + +/-- Pure `Ix.Expr.mdata` constructor (with deferred `dummyAddr`). -/ +def mkMData (data : Array (Ix.Name × Ix.DataValue)) (e : Ix.Expr) : Ix.Expr := + .mdata data e dummyAddr + +def beqLevelList : List Ix.Level → List Ix.Level → Bool + | [], [] => true + | x :: xs, y :: ys => Level.beqStruct x y && beqLevelList xs ys + | _, _ => false + +def beqDataValue : Ix.DataValue → Ix.DataValue → Bool + | .ofString s1, .ofString s2 => strBeqPure s1 s2 + | .ofBool b1, .ofBool b2 => b1 == b2 + | .ofName n1, .ofName n2 => Name.beqStruct n1 n2 + | .ofNat n1, .ofNat n2 => Nat.beq n1 n2 + | .ofInt (.ofNat n1), .ofInt (.ofNat n2) => Nat.beq n1 n2 + | .ofInt (.negSucc n1), .ofInt (.negSucc n2) => Nat.beq n1 n2 + | .ofSyntax _, .ofSyntax _ => true + | _, _ => false + +def beqMDataList : List (Ix.Name × Ix.DataValue) → List (Ix.Name × Ix.DataValue) → Bool + | [], [] => true + | (k1, v1) :: xs, (k2, v2) :: ys => + Name.beqStruct k1 k2 && beqDataValue v1 v2 && beqMDataList xs ys + | _, _ => false + +/-- Structural equality on `Ix.Expr` that reads no hash. -/ +def beqStruct : Ix.Expr → Ix.Expr → Bool + | .bvar i _, .bvar j _ => Nat.beq i j + | .fvar n1 _, .fvar n2 _ => Name.beqStruct n1 n2 + | .mvar n1 _, .mvar n2 _ => Name.beqStruct n1 n2 + | .sort u _, .sort v _ => Level.beqStruct u v + | .const n1 us1 _, .const n2 us2 _ => Name.beqStruct n1 n2 && beqLevelList us1.toList us2.toList + | .app f1 a1 _, .app f2 a2 _ => beqStruct f1 f2 && beqStruct a1 a2 + | .lam _ d1 b1 bi1 _, .lam _ d2 b2 bi2 _ => bi1 == bi2 && beqStruct d1 d2 && beqStruct b1 b2 + | .forallE _ d1 b1 bi1 _, .forallE _ d2 b2 bi2 _ => bi1 == bi2 && beqStruct d1 d2 && beqStruct b1 b2 + | .letE _ t1 v1 b1 nd1 _, .letE _ t2 v2 b2 nd2 _ => + nd1 == nd2 && beqStruct t1 t2 && beqStruct v1 v2 && beqStruct b1 b2 + | .lit (.natVal n1) _, .lit (.natVal n2) _ => Nat.beq n1 n2 + | .lit (.strVal s1) _, .lit (.strVal s2) _ => strBeqPure s1 s2 + | .mdata d1 e1 _, .mdata d2 e2 _ => beqMDataList d1.toList d2.toList && beqStruct e1 e2 + | .proj s1 i1 e1 _, .proj s2 i2 e2 _ => Name.beqStruct s1 s2 && Nat.beq i1 i2 && beqStruct e1 e2 + | _, _ => false + +instance (priority := 2000) : BEq Ix.Expr where + beq := beqStruct + +/-- Recursively populate the canonical 32-byte `Address` hash on every node of an `Ix.Expr`. -/ +def rehash : Ix.Expr → Ix.Expr + | e@(.bvar idx h) => + if Nat.beq h.hash.size 32 then e + else .bvar idx (Address.admissionHash (ByteArray.mk #[Ix.TAG_EVAR] ++ ⟨idx.toBytesLE⟩)) + | e@(.fvar name h) => + if Nat.beq h.hash.size 32 then e + else + let name' := Name.rehash name + .fvar name' (Address.admissionHash (ByteArray.mk #[Ix.TAG_EFVAR] ++ name'.getHash.hash)) + | e@(.mvar name h) => + if Nat.beq h.hash.size 32 then e + else + let name' := Name.rehash name + .mvar name' (Address.admissionHash (ByteArray.mk #[Ix.TAG_EMVAR] ++ name'.getHash.hash)) + | e@(.sort u h) => + if Nat.beq h.hash.size 32 then e + else + let u' := Level.rehash u + .sort u' (Address.admissionHash (ByteArray.mk #[Ix.TAG_ESORT] ++ u'.getHash.hash)) + | e@(.const name us h) => + if Nat.beq h.hash.size 32 then e + else + let name' := Name.rehash name + let usList := us.toList.map Level.rehash + let digest := Address.admissionHash ( + usList.foldl (fun acc u => acc ++ u.getHash.hash) + (ByteArray.mk #[Ix.TAG_EREF] ++ name'.getHash.hash)) + .const name' (Array.mk usList) digest + | e@(.app f a h) => + if Nat.beq h.hash.size 32 then e + else + let f' := rehash f + let a' := rehash a + .app f' a' (Address.admissionHash (ByteArray.mk #[Ix.TAG_EAPP] ++ f'.getHash.hash ++ a'.getHash.hash)) + | e@(.lam n t b bi h) => + if Nat.beq h.hash.size 32 then e + else + let n' := Name.rehash n + let t' := rehash t + let b' := rehash b + let digest := Address.admissionHash ( + ByteArray.mk #[Ix.TAG_ELAM] ++ n'.getHash.hash ++ t'.getHash.hash ++ + b'.getHash.hash ++ ByteArray.mk #[Ix.Expr.binderInfoTag bi]) + .lam n' t' b' bi digest + | e@(.forallE n t b bi h) => + if Nat.beq h.hash.size 32 then e + else + let n' := Name.rehash n + let t' := rehash t + let b' := rehash b + let digest := Address.admissionHash ( + ByteArray.mk #[Ix.TAG_EALL] ++ n'.getHash.hash ++ t'.getHash.hash ++ + b'.getHash.hash ++ ByteArray.mk #[Ix.Expr.binderInfoTag bi]) + .forallE n' t' b' bi digest + | e@(.letE n t v b nonDep h) => + if Nat.beq h.hash.size 32 then e + else + let n' := Name.rehash n + let t' := rehash t + let v' := rehash v + let b' := rehash b + let digest := Address.admissionHash ( + ByteArray.mk #[Ix.TAG_ELET] ++ n'.getHash.hash ++ t'.getHash.hash ++ + v'.getHash.hash ++ b'.getHash.hash ++ ByteArray.mk #[if nonDep then 1 else 0]) + .letE n' t' v' b' nonDep digest + | e@(.lit l h) => + if Nat.beq h.hash.size 32 then e + else + let digest := Address.admissionHash (match l with + | .natVal n => ByteArray.mk #[Ix.TAG_ENAT] ++ ⟨n.toBytesLE⟩ + | .strVal s => ByteArray.mk #[Ix.TAG_ESTR] ++ s.toUTF8) + .lit l digest + | e@(.proj typeName idx struct h) => + if Nat.beq h.hash.size 32 then e + else + let typeName' := Name.rehash typeName + let struct' := rehash struct + let digest := Address.admissionHash ( + ByteArray.mk #[Ix.TAG_EPRJ] ++ typeName'.getHash.hash ++ + ⟨idx.toBytesLE⟩ ++ struct'.getHash.hash) + .proj typeName' idx struct' digest + | e@(.mdata data inner h) => + if Nat.beq h.hash.size 32 then e + else + let dataList := data.toList.map fun (nm, dv) => (Name.rehash nm, rehashDataValue dv) + let inner' := rehash inner + let header := ByteArray.mk #[Ix.TAG_EMDATA] ++ ⟨dataList.length.toBytesLE⟩ + let body := dataList.foldl (fun acc (nm, dv) => + acc ++ nm.getHash.hash ++ encodeDataValueBytes dv) header + let digest := Address.admissionHash (body ++ inner'.getHash.hash) + .mdata (Array.mk dataList) inner' digest + +/-- Pure `Ix.ConstantInfo.getCnst` exposed for kernel-level reduction. -/ +def ConstantInfo.getCnstPure : Ix.ConstantInfo → Ix.ConstantVal + | .axiomInfo v => v.cnst + | .defnInfo v => v.cnst + | .thmInfo v => v.cnst + | .opaqueInfo v => v.cnst + | .quotInfo v => v.cnst + | .inductInfo v => v.cnst + | .ctorInfo v => v.cnst + | .recInfo v => v.cnst + +/-- Populate canonical 32-byte `Address` hashes on an `Ix.ConstantVal`. -/ +def rehashConstantVal (cv : Ix.ConstantVal) : Ix.ConstantVal := + { name := Name.rehash cv.name + levelParams := Array.mk (cv.levelParams.toList.map Name.rehash) + type := rehash cv.type } + +/-- Populate canonical 32-byte `Address` hashes on an `Ix.RecursorRule`. -/ +def rehashRecursorRule (r : Ix.RecursorRule) : Ix.RecursorRule := + { r with + ctor := Name.rehash r.ctor + rhs := rehash r.rhs } + +/-- Populate canonical 32-byte `Address` hashes throughout an `Ix.ConstantInfo`. -/ +def ConstantInfo.rehash : Ix.ConstantInfo → Ix.ConstantInfo + | .axiomInfo v => .axiomInfo { v with cnst := rehashConstantVal v.cnst } + | .defnInfo v => .defnInfo { + v with + cnst := rehashConstantVal v.cnst + value := Expr.rehash v.value + all := Array.mk (v.all.toList.map Name.rehash) } + | .thmInfo v => .thmInfo { + v with + cnst := rehashConstantVal v.cnst + value := Expr.rehash v.value + all := Array.mk (v.all.toList.map Name.rehash) } + | .opaqueInfo v => .opaqueInfo { + v with + cnst := rehashConstantVal v.cnst + value := Expr.rehash v.value + all := Array.mk (v.all.toList.map Name.rehash) } + | .quotInfo v => .quotInfo { v with cnst := rehashConstantVal v.cnst } + | .inductInfo v => .inductInfo { + v with + cnst := rehashConstantVal v.cnst + all := Array.mk (v.all.toList.map Name.rehash) + ctors := Array.mk (v.ctors.toList.map Name.rehash) } + | .ctorInfo v => .ctorInfo { + v with + cnst := rehashConstantVal v.cnst + induct := Name.rehash v.induct } + | .recInfo v => .recInfo { + v with + cnst := rehashConstantVal v.cnst + all := Array.mk (v.all.toList.map Name.rehash) + rules := Array.mk (v.rules.toList.map rehashRecursorRule) } + +/-- Pure `ix.contract` metadata key `ix.contract`. -/ +def contractKey : Ix.Name := Name.mkStr2 (str% "ix") (str% "contract") + +/-- Construct the 3-entry `ix.contract` metadata array (Ixon v5 semantic contract version 4). -/ +def mkContractMData (kindCode code : Nat) : Array (Ix.Name × Ix.DataValue) := + let key := contractKey + #[ (key, .ofNat 4), + (Name.mkStr key (str% "kind"), .ofNat kindCode), + (Name.mkStr key (str% "code"), .ofNat code) ] + +/-- Lower a surface `ValueContract` to an Ixon v5 `ResultMode`. -/ +def valueContractToResultMode (vc : Ixon.ValueContract) : Ixon.ResultMode := + match vc.owned, vc.locality with + | .shared, .unrestricted => .shared + | .shared, .local => .borrowed + | .unique, .unrestricted => .unique + | .unique, .local => .uniqueBorrowed + +/-- Lower a surface `BinderContract` to an Ixon v5 `BinderMode`. -/ +def binderContractToBinderMode (bc : Ixon.BinderContract) : Ixon.BinderMode := + match bc.uses with + | .erased => .erased + | .many => + match bc.value.owned, bc.value.locality with + | .shared, .unrestricted => .many + | .shared, .local => .borrowed + | .unique, .unrestricted => .unique + | .unique, .local => .uniqueBorrowed + | .linear | .affine => + match bc.value.owned, bc.value.locality with + | .unique, .unrestricted => .unique + | .unique, .local => .uniqueBorrowed + | .shared, .unrestricted => .once + | .shared, .local => .onceBorrowed + +/-- Lower a surface `(BinderContract, LetKind)` to an Ixon v5 `LetMode`. -/ +def letContractToLetMode (bc : Ixon.BinderContract) (letKind : Ixon.LetKind) : Ixon.LetMode := + match letKind with + | .borrowShared => .borrow + | .value => .value (binderContractToBinderMode bc) + +/-- Construct a `lam` node, attaching a v5 `ix.contract` frame when its `BinderMode != .many`. -/ +def mkLamContract (n : Ix.Name) (t b : Ix.Expr) (bi : Lean.BinderInfo := .default) + (binder : Ixon.BinderContract := default) : Ix.Expr := + let lam := mkLam n t b bi + let bm := binderContractToBinderMode binder + if bm == .many then lam + else mkMData (mkContractMData 0 bm.toCode.toNat) lam + +/-- Construct a `forallE` node, attaching a v5 `ix.contract` frame when its `AllMode != {}`. -/ +def mkForallContract (n : Ix.Name) (t b : Ix.Expr) (bi : Lean.BinderInfo := .default) + (binder : Ixon.BinderContract := default) + (result : Ixon.ValueContract := .shared) : Ix.Expr := + let all := mkForallE n t b bi + let am : Ixon.AllMode := { + input := binderContractToBinderMode binder + result := valueContractToResultMode result + } + if am == {} then all + else mkMData (mkContractMData 1 am.toCode.toNat) all + +/-- Construct a `letE` node, attaching a v5 `ix.contract` frame when its `LetMode != .value .many`. -/ +def mkLetContract (n : Ix.Name) (t v b : Ix.Expr) (nonDep : Bool := false) + (binder : Ixon.BinderContract := default) + (letKind : Ixon.LetKind := .value) : Ix.Expr := + let letNode := mkLetE n t v b nonDep + let lm := letContractToLetMode binder letKind + if lm == .value .many then letNode + else mkMData (mkContractMData 2 lm.toCode.toNat) letNode + +end Expr + +/-! ## Substructural Surface Annotation AST -/ + +/-- Parsed surface usage/ownership/locality modifier on a binder, `let`, or return type. -/ +structure ParsedBinderContract where + uses : Option Ixon.Uses := none + owned : Option Ixon.Owned := none + locality : Option Ixon.Locality := none + isBorrow : Bool := false + deriving BEq, DecidableEq, Repr, Inhabited + +namespace ParsedBinderContract + +def isEmpty (c : ParsedBinderContract) : Bool := + c.uses.isNone && c.owned.isNone && c.locality.isNone && !c.isBorrow + +def toValueContract (c : ParsedBinderContract) : Ixon.ValueContract := + { owned := c.owned.getD .shared + locality := c.locality.getD .unrestricted } + +def toBinderContract (c : ParsedBinderContract) : Ixon.BinderContract := + { uses := c.uses.getD .many + value := c.toValueContract } + +end ParsedBinderContract + +/-! ## Well-Known Syntax Node Kinds (`SyntaxKind`) -/ + +namespace SyntaxKind + +@[inline] def mkKindTag (tag : Nat) : Ix.Name := + Name.mkNat Name.mkAnon tag + +def nullKind : Ix.Name := mkKindTag 1 +def missingKind : Ix.Name := mkKindTag 2 +def identKind : Ix.Name := mkKindTag 3 + +-- Module & top-level commands +def moduleKind : Ix.Name := mkKindTag 4 +def headerKind : Ix.Name := mkKindTag 5 +def importDecl : Ix.Name := mkKindTag 6 +def hashImport : Ix.Name := mkKindTag 7 +def buildMapDecl : Ix.Name := mkKindTag 8 +def namespaceDecl : Ix.Name := mkKindTag 9 +def sectionDecl : Ix.Name := mkKindTag 10 +def endDecl : Ix.Name := mkKindTag 11 +def openDecl : Ix.Name := mkKindTag 12 +def variableDecl : Ix.Name := mkKindTag 13 +def universeDecl : Ix.Name := mkKindTag 14 +def mutualDecl : Ix.Name := mkKindTag 15 +def mergeConflictDecl : Ix.Name := mkKindTag 116 +def mergeArm : Ix.Name := mkKindTag 117 +def defDecl : Ix.Name := mkKindTag 16 +def abbrevDecl : Ix.Name := mkKindTag 17 +def theoremDecl : Ix.Name := mkKindTag 18 +def axiomDecl : Ix.Name := mkKindTag 19 +def opaqueDecl : Ix.Name := mkKindTag 20 +def instanceDecl : Ix.Name := mkKindTag 21 +def inductiveDecl : Ix.Name := mkKindTag 22 +def structureDecl : Ix.Name := mkKindTag 23 +def classDecl : Ix.Name := mkKindTag 24 +def ctorDecl : Ix.Name := mkKindTag 25 +def fieldDecl : Ix.Name := mkKindTag 26 +def notationDecl : Ix.Name := mkKindTag 27 +def macroDecl : Ix.Name := mkKindTag 28 +def modifiersKind : Ix.Name := mkKindTag 29 +def univParamsKind : Ix.Name := mkKindTag 30 + +-- Substructural contract nodes +def binderPrefix : Ix.Name := mkKindTag 31 +def valuePrefix : Ix.Name := mkKindTag 32 +def explicitBinder : Ix.Name := mkKindTag 33 +def implicitBinder : Ix.Name := mkKindTag 34 +def strictImplicitBinder : Ix.Name := mkKindTag 35 +def instBinder : Ix.Name := mkKindTag 36 + +-- Terms & Universe Levels +def hashRef : Ix.Name := mkKindTag 37 +def numLit : Ix.Name := mkKindTag 38 +def strLit : Ix.Name := mkKindTag 39 +def charLit : Ix.Name := mkKindTag 40 +def appTerm : Ix.Name := mkKindTag 41 +def arrowTerm : Ix.Name := mkKindTag 42 +def forallTerm : Ix.Name := mkKindTag 43 +def funTerm : Ix.Name := mkKindTag 44 +def letTerm : Ix.Name := mkKindTag 45 +def letBorrowTerm : Ix.Name := mkKindTag 46 +def letRecTerm : Ix.Name := mkKindTag 47 +def haveTerm : Ix.Name := mkKindTag 48 +def ifTerm : Ix.Name := mkKindTag 49 +def matchTerm : Ix.Name := mkKindTag 50 +def matchAlt : Ix.Name := mkKindTag 51 +def projTerm : Ix.Name := mkKindTag 52 +def anonCtor : Ix.Name := mkKindTag 53 +def structInst : Ix.Name := mkKindTag 54 +def structFieldAssign : Ix.Name := mkKindTag 55 +def listLit : Ix.Name := mkKindTag 56 +def tupleTerm : Ix.Name := mkKindTag 57 +def parenTerm : Ix.Name := mkKindTag 58 +def typeAscription : Ix.Name := mkKindTag 59 +def holeTerm : Ix.Name := mkKindTag 60 +def sorryTerm : Ix.Name := mkKindTag 61 +def sortTerm : Ix.Name := mkKindTag 62 +def propTerm : Ix.Name := mkKindTag 63 +def typeTerm : Ix.Name := mkKindTag 64 +def binOpTerm : Ix.Name := mkKindTag 65 +def unaryOpTerm : Ix.Name := mkKindTag 66 +def explicitTerm : Ix.Name := mkKindTag 67 +def antiquotTerm : Ix.Name := mkKindTag 137 +def macroCall : Ix.Name := mkKindTag 138 +def levelLit : Ix.Name := mkKindTag 68 +def levelAdd : Ix.Name := mkKindTag 69 +def levelMax : Ix.Name := mkKindTag 70 +def levelIMax : Ix.Name := mkKindTag 71 + +-- Tactics & Structured Proofs +def byTactic : Ix.Name := mkKindTag 72 +def tacticSeq : Ix.Name := mkKindTag 73 +def tacticIntro : Ix.Name := mkKindTag 74 +def tacticExact : Ix.Name := mkKindTag 75 +def tacticApply : Ix.Name := mkKindTag 76 +def tacticRefine : Ix.Name := mkKindTag 77 +def tacticRfl : Ix.Name := mkKindTag 78 +def tacticRw : Ix.Name := mkKindTag 79 +def tacticRwRule : Ix.Name := mkKindTag 80 +def tacticCases : Ix.Name := mkKindTag 81 +def tacticInduction : Ix.Name := mkKindTag 82 +def tacticAlt : Ix.Name := mkKindTag 83 +def tacticHave : Ix.Name := mkKindTag 84 +def tacticLet : Ix.Name := mkKindTag 85 +def tacticChange : Ix.Name := mkKindTag 86 +def tacticConstructor : Ix.Name := mkKindTag 87 +def tacticSimp : Ix.Name := mkKindTag 88 +def tacticDecide : Ix.Name := mkKindTag 89 +def tacticAssumption : Ix.Name := mkKindTag 90 +def tacticSorry : Ix.Name := mkKindTag 91 +def tacticAndThen : Ix.Name := mkKindTag 92 +def tacticFocus : Ix.Name := mkKindTag 93 +def tacticCase : Ix.Name := mkKindTag 94 +def tacticParen : Ix.Name := mkKindTag 95 +def tacticFirst : Ix.Name := mkKindTag 96 +def tacticTry : Ix.Name := mkKindTag 97 +def tacticRepeat : Ix.Name := mkKindTag 98 +def tacticAllGoals : Ix.Name := mkKindTag 99 +def tacticAnyGoals : Ix.Name := mkKindTag 100 +def tacticShow : Ix.Name := mkKindTag 101 +def tacticLeft : Ix.Name := mkKindTag 102 +def tacticRight : Ix.Name := mkKindTag 103 +def tacticSplit : Ix.Name := mkKindTag 104 +def tacticExists : Ix.Name := mkKindTag 105 +def tacticSymm : Ix.Name := mkKindTag 106 +def tacticTrans : Ix.Name := mkKindTag 107 +def tacticCongr : Ix.Name := mkKindTag 108 +def tacticFunext : Ix.Name := mkKindTag 109 +def tacticExt : Ix.Name := mkKindTag 110 +def tacticDSimp : Ix.Name := mkKindTag 111 +def tacticTrivial : Ix.Name := mkKindTag 112 +def tacticContradiction : Ix.Name := mkKindTag 113 +def tacticExfalso : Ix.Name := mkKindTag 114 +def tacticDone : Ix.Name := mkKindTag 115 +-- Wave 1 & 3: Calc, Recursive Destructuring (`rcases`/`obtain`/`rintro`), Context/Classical, & Decision Tactics +def calcTerm : Ix.Name := mkKindTag 118 +def calcStep : Ix.Name := mkKindTag 119 +def tacticCalc : Ix.Name := mkKindTag 120 +def rcasesPatWildcard : Ix.Name := mkKindTag 121 +def rcasesPatIdent : Ix.Name := mkKindTag 122 +def rcasesPatRfl : Ix.Name := mkKindTag 123 +def rcasesPatTuple : Ix.Name := mkKindTag 124 +def rcasesPatAlt : Ix.Name := mkKindTag 125 +def tacticRintro : Ix.Name := mkKindTag 126 +def tacticRcases : Ix.Name := mkKindTag 127 +def tacticObtain : Ix.Name := mkKindTag 128 +def tacticSuffices : Ix.Name := mkKindTag 129 +def tacticSpecialize : Ix.Name := mkKindTag 130 +def tacticClear : Ix.Name := mkKindTag 131 +def tacticRevert : Ix.Name := mkKindTag 132 +def tacticGeneralize : Ix.Name := mkKindTag 133 +def tacticSubst : Ix.Name := mkKindTag 134 +def tacticByCases : Ix.Name := mkKindTag 135 +def tacticByContra : Ix.Name := mkKindTag 136 +def tacticNormNum : Ix.Name := mkKindTag 139 +def tacticRing : Ix.Name := mkKindTag 140 +def tacticOmega : Ix.Name := mkKindTag 141 + +end SyntaxKind + +namespace SyntaxKindF + +@[inline] def mkKindTag (tag : Nat) : FName := + FName.num .anon tag + +def nullKind : FName := mkKindTag 1 +def missingKind : FName := mkKindTag 2 +def identKind : FName := mkKindTag 3 + +-- Module & top-level commands +def moduleKind : FName := mkKindTag 4 +def headerKind : FName := mkKindTag 5 +def importDecl : FName := mkKindTag 6 +def hashImport : FName := mkKindTag 7 +def buildMapDecl : FName := mkKindTag 8 +def namespaceDecl : FName := mkKindTag 9 +def sectionDecl : FName := mkKindTag 10 +def endDecl : FName := mkKindTag 11 +def openDecl : FName := mkKindTag 12 +def variableDecl : FName := mkKindTag 13 +def universeDecl : FName := mkKindTag 14 +def mutualDecl : FName := mkKindTag 15 +def mergeConflictDecl : FName := mkKindTag 116 +def mergeArm : FName := mkKindTag 117 +def defDecl : FName := mkKindTag 16 +def abbrevDecl : FName := mkKindTag 17 +def theoremDecl : FName := mkKindTag 18 +def axiomDecl : FName := mkKindTag 19 +def opaqueDecl : FName := mkKindTag 20 +def instanceDecl : FName := mkKindTag 21 +def inductiveDecl : FName := mkKindTag 22 +def structureDecl : FName := mkKindTag 23 +def classDecl : FName := mkKindTag 24 +def ctorDecl : FName := mkKindTag 25 +def fieldDecl : FName := mkKindTag 26 +def notationDecl : FName := mkKindTag 27 +def macroDecl : FName := mkKindTag 28 +def modifiersKind : FName := mkKindTag 29 +def univParamsKind : FName := mkKindTag 30 + +-- Substructural contract nodes +def binderPrefix : FName := mkKindTag 31 +def valuePrefix : FName := mkKindTag 32 +def explicitBinder : FName := mkKindTag 33 +def implicitBinder : FName := mkKindTag 34 +def strictImplicitBinder : FName := mkKindTag 35 +def instBinder : FName := mkKindTag 36 + +-- Terms & Universe Levels +def hashRef : FName := mkKindTag 37 +def numLit : FName := mkKindTag 38 +def strLit : FName := mkKindTag 39 +def charLit : FName := mkKindTag 40 +def appTerm : FName := mkKindTag 41 +def arrowTerm : FName := mkKindTag 42 +def forallTerm : FName := mkKindTag 43 +def funTerm : FName := mkKindTag 44 +def letTerm : FName := mkKindTag 45 +def letBorrowTerm : FName := mkKindTag 46 +def letRecTerm : FName := mkKindTag 47 +def haveTerm : FName := mkKindTag 48 +def ifTerm : FName := mkKindTag 49 +def matchTerm : FName := mkKindTag 50 +def matchAlt : FName := mkKindTag 51 +def projTerm : FName := mkKindTag 52 +def anonCtor : FName := mkKindTag 53 +def structInst : FName := mkKindTag 54 +def structFieldAssign : FName := mkKindTag 55 +def listLit : FName := mkKindTag 56 +def tupleTerm : FName := mkKindTag 57 +def parenTerm : FName := mkKindTag 58 +def typeAscription : FName := mkKindTag 59 +def holeTerm : FName := mkKindTag 60 +def sorryTerm : FName := mkKindTag 61 +def sortTerm : FName := mkKindTag 62 +def propTerm : FName := mkKindTag 63 +def typeTerm : FName := mkKindTag 64 +def binOpTerm : FName := mkKindTag 65 +def unaryOpTerm : FName := mkKindTag 66 +def explicitTerm : FName := mkKindTag 67 +def antiquotTerm : FName := mkKindTag 137 +def macroCall : FName := mkKindTag 138 +def levelLit : FName := mkKindTag 68 +def levelAdd : FName := mkKindTag 69 +def levelMax : FName := mkKindTag 70 +def levelIMax : FName := mkKindTag 71 + +-- Tactics & Structured Proofs +def byTactic : FName := mkKindTag 72 +def tacticSeq : FName := mkKindTag 73 +def tacticIntro : FName := mkKindTag 74 +def tacticExact : FName := mkKindTag 75 +def tacticApply : FName := mkKindTag 76 +def tacticRefine : FName := mkKindTag 77 +def tacticRfl : FName := mkKindTag 78 +def tacticRw : FName := mkKindTag 79 +def tacticRwRule : FName := mkKindTag 80 +def tacticCases : FName := mkKindTag 81 +def tacticInduction : FName := mkKindTag 82 +def tacticAlt : FName := mkKindTag 83 +def tacticHave : FName := mkKindTag 84 +def tacticLet : FName := mkKindTag 85 +def tacticChange : FName := mkKindTag 86 +def tacticConstructor : FName := mkKindTag 87 +def tacticSimp : FName := mkKindTag 88 +def tacticDecide : FName := mkKindTag 89 +def tacticAssumption : FName := mkKindTag 90 +def tacticSorry : FName := mkKindTag 91 +def tacticAndThen : FName := mkKindTag 92 +def tacticFocus : FName := mkKindTag 93 +def tacticCase : FName := mkKindTag 94 +def tacticParen : FName := mkKindTag 95 +def tacticFirst : FName := mkKindTag 96 +def tacticTry : FName := mkKindTag 97 +def tacticRepeat : FName := mkKindTag 98 +def tacticAllGoals : FName := mkKindTag 99 +def tacticAnyGoals : FName := mkKindTag 100 +def tacticShow : FName := mkKindTag 101 +def tacticLeft : FName := mkKindTag 102 +def tacticRight : FName := mkKindTag 103 +def tacticSplit : FName := mkKindTag 104 +def tacticExists : FName := mkKindTag 105 +def tacticSymm : FName := mkKindTag 106 +def tacticTrans : FName := mkKindTag 107 +def tacticCongr : FName := mkKindTag 108 +def tacticFunext : FName := mkKindTag 109 +def tacticExt : FName := mkKindTag 110 +def tacticDSimp : FName := mkKindTag 111 +def tacticTrivial : FName := mkKindTag 112 +def tacticContradiction : FName := mkKindTag 113 +def tacticExfalso : FName := mkKindTag 114 +def tacticDone : FName := mkKindTag 115 +-- Wave 1 & 3: Calc, Recursive Destructuring (`rcases`/`obtain`/`rintro`), Context/Classical, & Decision Tactics +def calcTerm : FName := mkKindTag 118 +def calcStep : FName := mkKindTag 119 +def tacticCalc : FName := mkKindTag 120 +def rcasesPatWildcard : FName := mkKindTag 121 +def rcasesPatIdent : FName := mkKindTag 122 +def rcasesPatRfl : FName := mkKindTag 123 +def rcasesPatTuple : FName := mkKindTag 124 +def rcasesPatAlt : FName := mkKindTag 125 +def tacticRintro : FName := mkKindTag 126 +def tacticRcases : FName := mkKindTag 127 +def tacticObtain : FName := mkKindTag 128 +def tacticSuffices : FName := mkKindTag 129 +def tacticSpecialize : FName := mkKindTag 130 +def tacticClear : FName := mkKindTag 131 +def tacticRevert : FName := mkKindTag 132 +def tacticGeneralize : FName := mkKindTag 133 +def tacticSubst : FName := mkKindTag 134 +def tacticByCases : FName := mkKindTag 135 +def tacticByContra : FName := mkKindTag 136 +def tacticNormNum : FName := mkKindTag 139 +def tacticRing : FName := mkKindTag 140 +def tacticOmega : FName := mkKindTag 141 + +end SyntaxKindF + +/-! ## `Ix.SourceInfo` & `Ix.Syntax` Helpers -/ + +namespace SourceInfo + +def startPos? : Ix.SourceInfo → Option Nat + | .original _ pos _ _ => some pos + | .synthetic pos _ _ => some pos + | .none => none + +def endPos? : Ix.SourceInfo → Option Nat + | .original _ _ _ pos => some pos + | .synthetic _ pos _ => some pos + | .none => none + +end SourceInfo + +/-! ## Non-Nested Concrete Syntax Tree (`Stx`) + +Single-inductive concrete syntax tree storing child lists via `.snil`/`.scons` +so `IxCC` compiles every match to an unboxed `case` with zero nested-recursor +(`S25`) or `Array` overhead. Converts cleanly to/from `Ix.Syntax` at the host +boundary. -/ + +inductive Stx where + | missing + | node (info : FSourceInfo) (kind : FName) (args : Stx) + | atom (info : FSourceInfo) (val : Sym) + | ident (info : FSourceInfo) (rawVal : Sym) (val : FName) + | snil + | scons (head : Stx) (tail : Stx) + deriving BEq, Repr, Inhabited + +namespace Stx + +def ofList : List Stx → Stx + | [] => .snil + | x :: xs => .scons x (ofList xs) + +def ofArray (xs : Array Stx) : Stx := + ofList xs.toList + +def toList : Stx → List Stx + | .scons h t => h :: toList t + | _ => [] + +def toArray (s : Stx) : Array Stx := + Array.mk (toList s) + +def sizeAux : Stx → Nat → Nat + | .scons _ t, acc => sizeAux t (acc + 1) + | _, acc => acc + +def size (s : Stx) : Nat := + sizeAux s 0 + +def isEmpty : Stx → Bool + | .scons _ _ => false + | _ => true + +def getD : Stx → Nat → Stx → Stx + | .scons h _, 0, _ => h + | .scons _ t, k + 1, d => getD t k d + | _, _, d => d + +def get? : Stx → Nat → Option Stx + | .scons h _, 0 => some h + | .scons _ t, k + 1 => get? t k + | _, _ => none + +instance : GetElem? Stx Nat Stx (fun s i => i < s.size) where + getElem s i _ := s.getD i .missing + getElem? s i := s.get? i + +def any (s : Stx) (p : Stx → Bool) : Bool := + match s with + | .scons h t => if p h then true else any t p + | _ => false + +def all (s : Stx) (p : Stx → Bool) : Bool := + match s with + | .scons h t => if p h then all t p else false + | _ => true + +def foldl {α : Type} (f : α → Stx → α) (init : α) : Stx → α + | .scons h t => foldl f (f init h) t + | _ => init + +def map (f : Stx → Stx) : Stx → Stx + | .scons h t => .scons (f h) (map f t) + | _ => .snil + +def findSome? {α : Type} (f : Stx → Option α) : Stx → Option α + | .scons h t => + match f h with + | some a => some a + | none => findSome? f t + | _ => none + +def push (s : Stx) (x : Stx) : Stx := + match s with + | .scons h t => .scons h (push t x) + | _ => .scons x .snil + +def filter (p : Stx → Bool) : Stx → Stx + | .scons h t => if p h then .scons h (filter p t) else filter p t + | _ => .snil + +def extract (s : Stx) (start stop : Nat) : Array Stx := + (toArray s).extract start stop + +def toIxSyntax : Stx → Ix.Syntax + | .missing => .missing + | .atom info val => .atom info.toIxSourceInfo (Sym.toString val) + | .ident info rawVal val => + let rawStr := Sym.toString rawVal + .ident info.toIxSourceInfo ⟨rawStr, 0, rawStr.utf8ByteSize⟩ (FName.toIxName val) #[] + | .node info kind args => .node info.toIxSourceInfo (FName.toIxName kind) (Array.mk (toIxSyntaxList args)) + | .snil | .scons .. => .missing +where + toIxSyntaxList : Stx → List Ix.Syntax + | .scons h t => toIxSyntax h :: toIxSyntaxList t + | _ => [] + +def ofIxSyntax (fuel : Nat := 1024) : Ix.Syntax → Stx + | .missing => .missing + | .atom info val => .atom (FSourceInfo.ofIxSourceInfo info) (Sym.ofString val) + | .ident info rawVal val _ => + .ident (FSourceInfo.ofIxSourceInfo info) (Sym.ofString rawVal.str) (FName.ofIxName val) + | .node info kind args => + let fi := FSourceInfo.ofIxSourceInfo info + let fk := FName.ofIxName kind + match fuel with + | 0 => .node fi fk .snil + | f + 1 => .node fi fk (ofList (args.toList.map (ofIxSyntax f))) + +end Stx + +namespace Syntax + +/-! ### Native Circuit Constructors & Accessors (Zero `String` / Zero `Ix.Name`!) -/ + +@[inline] def mkAtomF (info : FSourceInfo) (val : Sym) : Stx := + .atom info val + +@[inline] def mkSimpleAtomF (val : Sym) : Stx := + .atom .none val + +@[inline] def mkIdentF (info : FSourceInfo) (rawVal : Sym) (val : FName) : Stx := + .ident info rawVal val + +@[inline] def mkSimpleIdentF (val : FName) : Stx := + .ident .none (FName.toSym val) val + +@[inline] def mkNodeF (kind : FName) (args : Stx) (info : FSourceInfo := .none) : Stx := + .node info kind args + +@[inline] def mkNodeListF (kind : FName) (args : List Stx) (info : FSourceInfo := .none) : Stx := + .node info kind (Stx.ofList args) + +@[inline] def mkNullNodeF (args : Stx := .snil) : Stx := + .node .none SyntaxKindF.nullKind args + +def getKindF : Stx → FName + | .missing => SyntaxKindF.missingKind + | .node _ kind _ => kind + | .atom _ v => FName.simple v + | .ident _ _ _ => SyntaxKindF.identKind + | .snil | .scons .. => SyntaxKindF.missingKind + +@[inline] def isOfKindF (stx : Stx) (k : FName) : Bool := + FName.beq (getKindF stx) k + +def getIdF : Stx → FName + | .ident _ _ val => val + | _ => .anon + +def getAtomSym : Stx → Sym + | .atom _ val => val + | _ => .nil + +def getHeadInfoF? : Nat → Stx → Option FSourceInfo + | 0, _ => none + | fuel + 1, stx => + match stx with + | .missing => none + | .atom info _ => some info + | .ident info _ _ => some info + | .node info _ args => + match info with + | .none => getHeadInfoFList? fuel args + | _ => some info + | .snil | .scons .. => none +where + getHeadInfoFList? : Nat → Stx → Option FSourceInfo + | fuel, .scons h t => + match getHeadInfoF? fuel h with + | some i => some i + | none => getHeadInfoFList? fuel t + | _, _ => none + +/-! ### Legacy `Ix.Name` / `String` Bridges (For Elab / Format / Merge Host Boundary) -/ + +def mkAtom (info : Ix.SourceInfo) (val : String) : Stx := + .atom (FSourceInfo.ofIxSourceInfo info) (Sym.ofString val) + +def mkSimpleAtom (val : String) : Stx := + .atom .none (Sym.ofString val) + +def mkIdent (info : Ix.SourceInfo) (rawVal : Ix.Substring) (val : Ix.Name) : Stx := + .ident (FSourceInfo.ofIxSourceInfo info) (Sym.ofString rawVal.str) (FName.ofIxName val) + +def mkSimpleIdent (val : Ix.Name) : Stx := + let fn := FName.ofIxName val + .ident .none (FName.toSym fn) fn + +def mkNode (kind : Ix.Name) (args : Array Stx) (info : Ix.SourceInfo := .none) : Stx := + .node (FSourceInfo.ofIxSourceInfo info) (FName.ofIxName kind) (Stx.ofArray args) + +def mkNodeList (kind : Ix.Name) (args : List Stx) (info : Ix.SourceInfo := .none) : Stx := + .node (FSourceInfo.ofIxSourceInfo info) (FName.ofIxName kind) (Stx.ofList args) + +def mkNullNode (args : Array Stx := #[]) : Stx := + .node .none SyntaxKindF.nullKind (Stx.ofArray args) + +def getKind : Stx → Ix.Name + | .missing => SyntaxKind.missingKind + | .node _ kind _ => FName.toIxName kind + | .atom _ v => Name.simple (Sym.toString v) + | .ident _ _ _ => SyntaxKind.identKind + | .snil | .scons .. => SyntaxKind.missingKind + +def isOfKind (stx : Stx) (k : Ix.Name) : Bool := + getKind stx == k + +def isMissing : Stx → Bool + | .missing => true + | _ => false + +def getArgs : Stx → Array Stx + | .node _ _ args => args.toArray + | _ => #[] + +def getArgsStx : Stx → Stx + | .node _ _ args => args + | _ => .snil + +def getNumArgs (stx : Stx) : Nat := + (getArgsStx stx).size + +/-- Proof-free `List` element lookup with default for kernel reduction. -/ +def listGetD : List α → Nat → α → α + | [], _, d => d + | x :: _, 0, _ => x + | _ :: rest, k + 1, d => listGetD rest k d + +/-- Proof-free `List` optional element lookup for kernel reduction. -/ +def listGet? : List α → Nat → Option α + | [], _ => none + | x :: _, 0 => some x + | _ :: rest, k + 1 => listGet? rest k + +def getArg (stx : Stx) (i : Nat) : Stx := + (getArgsStx stx).getD i .missing + +def isNone : Stx → Bool + | .node _ kind .snil => FName.beq kind SyntaxKindF.nullKind + | _ => false + +def getOptional? (stx : Stx) : Option Stx := + if isOfKindF stx SyntaxKindF.nullKind then + (getArgsStx stx).get? 0 + else + none + +def getId : Stx → Ix.Name + | .ident _ _ val => FName.toIxName val + | _ => Name.mkAnon + +def getAtomVal : Stx → String + | .atom _ val => Sym.toString val + | _ => str% "" + +def getHeadInfo? (fuel : Nat := 128) (stx : Stx) : Option Ix.SourceInfo := + (getHeadInfoF? fuel stx).map FSourceInfo.toIxSourceInfo + +def getPos? (stx : Stx) : Option Nat := do + let info ← getHeadInfoF? 128 stx + FSourceInfo.startPos? info + +/-- Pretty-print a `Stx` tree for debugging and tests (fuel-bounded). -/ +def format (fuel : Nat := 256) (stx : Stx) : String := + match fuel with + | 0 => "..." + | fuel + 1 => + match stx with + | .missing => "" + | .atom _ val => reprStr (Sym.toString val) + | .ident _ _ val => s!"`{Name.toStringTotal (FName.toIxName val)}" + | .node _ kind args => + let kStr := Name.toStringTotal (FName.toIxName kind) + if args.isEmpty then + s!"({kStr})" + else + let childStrs := args.toList.map (format fuel) + s!"({kStr} {strIntercalatePure " " childStrs})" + | .snil | .scons .. => "" + +end Syntax + +end Ix.Frontend diff --git a/Ix/Ixon/ElabClaim.lean b/Ix/Ixon/ElabClaim.lean index bd7ea0ea1d..e032986cfc 100644 --- a/Ix/Ixon/ElabClaim.lean +++ b/Ix/Ixon/ElabClaim.lean @@ -1,20 +1,41 @@ -/- - # ElabClaim: Provable Statement-to-Ixon Elaboration Claims (`0xE8 0x0B`) - - Minimal, self-contained wire codec, dynamic-link bridge, and bounded - statement elaborator for `ElabClaim` (`TagN(4, 0xE, 19)` = `[0xE8, 0x0B]`), - matching the reserved slot in `Ix/Claim.lean` (`0xE` variant 19) and - Appendix A of the Ix specification without colliding with `RoleTable` - (`E8 03`, variant 11) or `LiteralClass` (`E8 04`, variant 12). +module + +public import Ix.Claim +public import Ix.DynamicLink.Spec +public import Ix.DynamicLink.Codec +public import Ix.Address.Pure +import all Ix.Claim +import all Ix.Ixon +import all Ix.Common +import all IxCK.Ixon.Codec + +/-! + # ElabClaim: Unified Content-Addressed Elaboration Claim (`0xE8 0x0B | 04 03`) + + Single canonical elaboration claim format under the reserved slot + `TagN(4, 0xE, 19)` (`[0xE8, 0x0B]`) and scope `[0x04, 0x03]` + (`OBJECT_FORMAT = 4`, `VALIDATOR_ERASED_LEAN = 3`), binding a UTF-8 source + blob digest (`sourceAddr`) to its elaborated output (`outputAddr`), with + explicit commitment `kind`, `flags`, and optional content-addressed + `importsAddr`, `syntaxAddr`, and `exportsAddr`: + + ```text + E8 0B | 04 03 | kind:u8 | flags:u8 | sourceAddr:32 | outputAddr:32 + [if flags & 0x02 : importsAddr:32] + [if flags & 0x04 : syntaxAddr:32] + [if flags & 0x08 : exportsAddr:32] + ``` + + Covers single-statement claims (`kind = .singleConst`, 70 B), parse-only + claims (`kind = .parseOnly`, 70 B), compositional syntax-to-environment + elaboration (`kind = .alphaEnv` / `.ixonEnv` with `syntaxAddr`, 102 B), + and full export-bound module claims (`+ exportsAddr`, 134 B). Every serialized `ElabClaim` is strictly rejected by `Ix.Claim.de`, leaving frozen `IxVM.Consistency.InScopeTyping` and `CircuitComposed` untouched. -/ -import Ix.Claim -import Ix.DynamicLink.Spec -import Ix.DynamicLink.Codec -import Ix.Address.Pure +public section set_option autoImplicit false @@ -27,7 +48,8 @@ open Ix (Claim ClaimContext) def VARIANT_ELAB_CLAIM : UInt64 := 19 /-- Pack a 32-byte `Address` into 8 little-endian `UInt64` words (each `< 2^32`), - matching `Ix.DynamicLink.CodecTag.ixonAddrPair` and `EvalAbi.pack32`. -/ + matching `Ix.DynamicLink.CodecTag.ixonAddrSingle` / `ixonAddrPair` and + `EvalAbi.pack32`. -/ def packAddrU32Words (a : Address) : Array UInt64 := Id.run do let mut out : Array UInt64 := Array.mkEmpty 8 for i in [0:8] do @@ -38,24 +60,86 @@ def packAddrU32Words (a : Address) : Array UInt64 := Id.run do out := out.push (b0 ||| (b1 <<< 8) ||| (b2 <<< 16) ||| (b3 <<< 24)) return out -/-- Statement-only `ElabClaim` (`0xE8 0x0B`): binds the BLAKE3 digest of a - human-readable source statement blob `sourceAddr` to the content address - `constAddr` of its elaborated canonical `Ixon.Constant`. +/-- What `ElabClaim.outputAddr` commits to. -/ +inductive ElabOutputKind where + /-- `0`: parse-only claim (`outputAddr` = canonical syntax tree digest). -/ + | parseOnly + /-- `1`: alpha-canonical elaborated environment digest (omitting binder names / cached hashes). -/ + | alphaEnv + /-- `2`: canonical `Ixon.Env` / Merkle root of elaborated `Ixon.Constant`s. -/ + | ixonEnv + /-- `3`: single canonical `Ixon.Constant` content address. -/ + | singleConst + deriving BEq, DecidableEq, Repr, Inhabited + +namespace ElabOutputKind + +def toU8 : ElabOutputKind → UInt8 + | .parseOnly => 0 + | .alphaEnv => 1 + | .ixonEnv => 2 + | .singleConst => 3 - Wire framing at `Ixon.Env.OBJECT_FORMAT = 4`: - `E8 0B | 04 03 | sourceAddr:32 | constAddr:32` (68 bytes). -/ +def ofU8? : UInt8 → Option ElabOutputKind + | 0 => some .parseOnly + | 1 => some .alphaEnv + | 2 => some .ixonEnv + | 3 => some .singleConst + | _ => none + +theorem ofU8?_toU8 (k : ElabOutputKind) : ofU8? k.toU8 = some k := by + cases k <;> rfl + +end ElabOutputKind + +/-- Unified content-addressed elaboration claim (`0xE8 0x0B | 04 03`). -/ structure ElabClaim where - sourceAddr : Address - constAddr : Address + /-- Commitment kind for `outputAddr`. -/ + kind : ElabOutputKind := .alphaEnv + /-- Whether elaboration seeds the standard Ix prelude. -/ + seedPrelude : Bool := true + /-- BLAKE3 digest of the UTF-8 `.ix` source text blob. -/ + sourceAddr : Address + /-- Content address of the elaborated output (semantics governed by `kind`). -/ + outputAddr : Address + /-- Optional content address of imported Ixon environment / dependency map. -/ + importsAddr : Option Address := none + /-- Optional canonical digest of the parsed syntax tree. -/ + syntaxAddr : Option Address := none + /-- Optional content address of sorted `Name -> Address` export bindings. -/ + exportsAddr : Option Address := none deriving BEq, DecidableEq, Repr, Inhabited namespace ElabClaim +def FLAG_SEED_PRELUDE : UInt8 := 0x01 +def FLAG_HAS_IMPORTS : UInt8 := 0x02 +def FLAG_HAS_SYNTAX : UInt8 := 0x04 +def FLAG_HAS_EXPORTS : UInt8 := 0x08 + +/-- Construct a minimal single-constant elaboration claim (`kind = .singleConst`, `flags = 0`). -/ +def ofStatement (sourceAddr constAddr : Address) : ElabClaim := + { kind := .singleConst, seedPrelude := false, sourceAddr, outputAddr := constAddr } + +def flagsByte (c : ElabClaim) : UInt8 := + (if c.seedPrelude then FLAG_SEED_PRELUDE else 0) ||| + (if c.importsAddr.isSome then FLAG_HAS_IMPORTS else 0) ||| + (if c.syntaxAddr.isSome then FLAG_HAS_SYNTAX else 0) ||| + (if c.exportsAddr.isSome then FLAG_HAS_EXPORTS else 0) + def put (c : ElabClaim) : PutM Unit := do putTagN 4 Claim.FLAG_CLAIM VARIANT_ELAB_CLAIM Claim.putScope Claim.VALIDATOR_ERASED_LEAN + putU8 c.kind.toU8 + putU8 c.flagsByte Serialize.put c.sourceAddr - Serialize.put c.constAddr + Serialize.put c.outputAddr + if let some a := c.importsAddr then + Serialize.put a + if let some a := c.syntaxAddr then + Serialize.put a + if let some a := c.exportsAddr then + Serialize.put a def get : GetM ElabClaim := do let tag ← getTagN 4 @@ -67,9 +151,26 @@ def get : GetM ElabClaim := do let validator ← getU8 unless validator == Claim.VALIDATOR_ERASED_LEAN do throw s!"ElabClaim.get: expected validator {Claim.VALIDATOR_ERASED_LEAN}, got {validator}" + let kindByte ← getU8 + let some kind := ElabOutputKind.ofU8? kindByte + | throw s!"ElabClaim.get: invalid output kind {kindByte}" + let flags ← getU8 + if (flags &&& 0xF0) != 0 then + throw s!"ElabClaim.get: reserved flag bits set in {flags}" let sourceAddr ← Serialize.get - let constAddr ← Serialize.get - return { sourceAddr, constAddr } + let outputAddr ← Serialize.get + let importsAddr ← if (flags &&& FLAG_HAS_IMPORTS) != 0 then some <$> Serialize.get else pure none + let syntaxAddr ← if (flags &&& FLAG_HAS_SYNTAX) != 0 then some <$> Serialize.get else pure none + let exportsAddr ← if (flags &&& FLAG_HAS_EXPORTS) != 0 then some <$> Serialize.get else pure none + return { + kind + seedPrelude := (flags &&& FLAG_SEED_PRELUDE) != 0 + sourceAddr + outputAddr + importsAddr + syntaxAddr + exportsAddr + } def ser (c : ElabClaim) : ByteArray := runPut (put c) def de (bytes : ByteArray) : Except String ElabClaim := runGetExact get bytes @@ -77,50 +178,92 @@ def de (bytes : ByteArray) : Except String ElabClaim := runGetExact get bytes /-- Pure BLAKE3 commitment digest of an `ElabClaim`. -/ def commit (c : ElabClaim) : Address := Address.blake3Pure (ser c) -/-- Emit the canonical Tier-1 Shape-17 `DynamicLinkStatement` (`0xE8 0x0D`) - under `CodecTag.ixonAddrPair` (`codec = 1`) pairing `sourceAddr` (8 u32 - public inputs) with `constAddr` (8 u32 public outputs). -/ +/-- Emit a Tier-1 Shape-17 `DynamicLinkStatement` (`0xE8 0x0D`) under + `CodecTag.ixonAddrSingle` (`codec = 2`) passing the 8 `u32` words of + `c.commit` as public input, matching the 8-word `IxFrontend::verify_*` / + `IxVM::verify_claim` ABI. -/ def toDynamicLinkStatement (c : ElabClaim) (circuit : Ix.DynamicLink.CircuitRef) (bridge? : Option Ix.DynamicLink.BridgeBinding := none) : Ix.DynamicLink.DynamicLinkStatement := + { circuit + pubInputs := packAddrU32Words c.commit + pubOutputs := #[] + bridge? } + +/-- Emit a Tier-1 Shape-17 `DynamicLinkStatement` (`0xE8 0x0D`) under + `CodecTag.ixonAddrPair` (`codec = 1`) pairing `sourceAddr` (8 `u32` public + inputs) with `outputAddr` (8 `u32` public outputs). -/ +def toPairDynamicLinkStatement (c : ElabClaim) (circuit : Ix.DynamicLink.CircuitRef) + (bridge? : Option Ix.DynamicLink.BridgeBinding := none) : + Ix.DynamicLink.DynamicLinkStatement := { circuit pubInputs := packAddrU32Words c.sourceAddr - pubOutputs := packAddrU32Words c.constAddr + pubOutputs := packAddrU32Words c.outputAddr bridge? } +/-- Project to an `Ix.Claim.eval` claim for parsing (`parseAppAddr ↦ syntaxAddr`). -/ +def toParseEvalClaim? (c : ElabClaim) (ctx : ClaimContext) (parseAppAddr : Address) + (assumptions : Option Address := none) : Option Claim := + c.syntaxAddr.map fun stxAddr => .eval ctx parseAppAddr stxAddr assumptions + +/-- Project to an `Ix.Claim.eval` claim for elaboration (`elabAppAddr ↦ outputAddr`). -/ +def toElabEvalClaim (c : ElabClaim) (ctx : ClaimContext) (elabAppAddr : Address) + (assumptions : Option Address := none) : Claim := + .eval ctx elabAppAddr c.outputAddr assumptions + +/-- Project to an `Ix.Claim.checkEnv` claim over `outputAddr`. -/ +def toCheckEnvClaim (c : ElabClaim) (ctx : ClaimContext) + (assumptions : Option Address := none) : Claim := + .checkEnv ctx c.outputAddr assumptions + instance : ToString ElabClaim where - toString c := s!"ElabClaim(source={c.sourceAddr}, const={c.constAddr})" + toString c := s!"ElabClaim(kind={repr c.kind}, source={c.sourceAddr}, output={c.outputAddr})" theorem tag_bytes : (runPut (putTagN 4 Claim.FLAG_CLAIM VARIANT_ELAB_CLAIM)).data = #[0xE8, 0x0B] := by - decide + exact rfl theorem header_bytes : (runPut (do putTagN 4 Claim.FLAG_CLAIM VARIANT_ELAB_CLAIM Claim.putScope Claim.VALIDATOR_ERASED_LEAN)).data = #[0xE8, 0x0B, 0x04, 0x03] := by - decide + exact rfl -theorem ser_eq_append (c : ElabClaim) : - ser c = (⟨#[0xE8, 0x0B, 0x04, 0x03]⟩ : ByteArray) ++ c.sourceAddr.hash ++ c.constAddr.hash := by +theorem ser_minimal_eq_append (c : ElabClaim) + (hImp : c.importsAddr = none) (hStx : c.syntaxAddr = none) (hExp : c.exportsAddr = none) : + ser c = + (⟨#[0xE8, 0x0B, 0x04, 0x03, c.kind.toU8, c.flagsByte]⟩ : ByteArray) ++ + c.sourceAddr.hash ++ c.outputAddr.hash := by have hpref : runPut (do putTagN 4 Claim.FLAG_CLAIM VARIANT_ELAB_CLAIM - Claim.putScope Claim.VALIDATOR_ERASED_LEAN) = ⟨#[0xE8, 0x0B, 0x04, 0x03]⟩ := by + Claim.putScope Claim.VALIDATOR_ERASED_LEAN + putU8 c.kind.toU8 + putU8 c.flagsByte) = + ⟨#[0xE8, 0x0B, 0x04, 0x03, c.kind.toU8, c.flagsByte]⟩ := by apply ByteArray.ext - exact header_bytes + rfl + unfold ser put + rw [hImp, hStx, hExp] have hser : - ser c = + runPut (do putTagN 4 Claim.FLAG_CLAIM VARIANT_ELAB_CLAIM + Claim.putScope Claim.VALIDATOR_ERASED_LEAN + putU8 c.kind.toU8 + putU8 c.flagsByte + Serialize.put c.sourceAddr + Serialize.put c.outputAddr) = ((runPut (do putTagN 4 Claim.FLAG_CLAIM VARIANT_ELAB_CLAIM - Claim.putScope Claim.VALIDATOR_ERASED_LEAN)).append c.sourceAddr.hash).append - c.constAddr.hash := rfl - rw [hser, hpref] - rfl - -theorem ser_size (c : ElabClaim) - (hSrc : c.sourceAddr.hash.size = 32) (hConst : c.constAddr.hash.size = 32) : - (ser c).size = 68 := by - rw [ser_eq_append] - have h4 : (⟨#[0xE8, 0x0B, 0x04, 0x03]⟩ : ByteArray).size = 4 := rfl - simp [ByteArray.size_append, h4, hSrc, hConst] + Claim.putScope Claim.VALIDATOR_ERASED_LEAN + putU8 c.kind.toU8 + putU8 c.flagsByte)).append c.sourceAddr.hash).append + c.outputAddr.hash := rfl + simpa [hpref] using hser + +theorem ser_minimal_size (c : ElabClaim) + (hImp : c.importsAddr = none) (hStx : c.syntaxAddr = none) (hExp : c.exportsAddr = none) + (hSrc : c.sourceAddr.hash.size = 32) (hOut : c.outputAddr.hash.size = 32) : + (ser c).size = 70 := by + rw [ser_minimal_eq_append c hImp hStx hExp] + have h6 : (⟨#[0xE8, 0x0B, 0x04, 0x03, c.kind.toU8, c.flagsByte]⟩ : ByteArray).size = 6 := rfl + simp [ByteArray.size_append, h6, hSrc, hOut] /-- `ElabClaim` uses TagN variant 19 (`0xE8 0x0B`), which is outside `Ix.Claim.de`'s accepted variants (`3..8, 10, 13`) and is therefore strictly disjoint from frozen @@ -138,33 +281,6 @@ theorem variant_disjoint_from_claim : end ElabClaim -/-- Full environment-level elaboration claim (`Text -> Syntax -> Environment`, - matching `origin/jcb/ix-frontend`'s decomposition into `Claim.eval` + `Claim.checkEnv`). - Projects to statement-only `ElabClaim` via `toStatementClaim`. -/ -structure ElabEnvClaim where - ctx : ClaimContext - sourceAddr : Address - syntaxAddr : Address - envAddr : Address - assumptions : Option Address := none - deriving BEq, Repr, Inhabited - -namespace ElabEnvClaim - -def toParseEvalClaim (c : ElabEnvClaim) (parseAppAddr : Address) : Claim := - .eval c.ctx parseAppAddr c.syntaxAddr c.assumptions - -def toElabEvalClaim (c : ElabEnvClaim) (elabAppAddr : Address) : Claim := - .eval c.ctx elabAppAddr c.envAddr c.assumptions - -def toCheckEnvClaim (c : ElabEnvClaim) : Claim := - .checkEnv c.ctx c.envAddr c.assumptions - -def toStatementClaim (c : ElabEnvClaim) (constAddr : Address) : ElabClaim := - { sourceAddr := c.sourceAddr, constAddr } - -end ElabEnvClaim - /-! ## Bounded Statement Elaborator (`propId` & `AnthropicFLT` Statement Fixtures) Pure deterministic bounded lexer/parser for the Appendix A `propId` theorem and @@ -232,13 +348,13 @@ def elabPropIdStatement (src : String) (constOverride? : Option Constant := none let c := constOverride?.getD propIdConstantBase let srcAddr := Address.blake3Pure src.toUTF8 let constAddr := Address.blake3Pure (serConstant c) - return (c, { sourceAddr := srcAddr, constAddr }) + return (c, ElabClaim.ofStatement srcAddr constAddr) | toks => throw s!"elabPropIdStatement: unexpected token sequence ({toks.length} tokens)" /-- Validate the exact token structure of the `AnthropicFLT` statement fixture (`flt_pinned` + `FermatLastTheorem`) and bind its UTF-8 source digest to - an elaborated target `constAddr` via a canonical 68-byte `ElabClaim`. -/ + an elaborated target `constAddr` via a canonical `ElabClaim`. -/ def verifyFltStatementSyntax (src : String) : Bool := tokenizeStatement src == [ "axiom", "flt_pinned", @@ -258,8 +374,10 @@ def verifyFltStatementSyntax (src : String) : Bool := def mkFltElabClaim (src : String) (constAddr : Address) : Except String ElabClaim := do unless verifyFltStatementSyntax src do throw "mkFltElabClaim: source does not match bounded AnthropicFLT statement grammar" - return { sourceAddr := Address.blake3Pure src.toUTF8, constAddr } + return ElabClaim.ofStatement (Address.blake3Pure src.toUTF8) constAddr end BoundedStatementElab end Ixon + +end diff --git a/Ix/Meta.lean b/Ix/Meta.lean index 201ca7d440..5dc2cf3df2 100644 --- a/Ix/Meta.lean +++ b/Ix/Meta.lean @@ -100,16 +100,15 @@ isolation the mode exists for (TruthMines' `module-header-v1` patch) without corrupting stored content. See `Ix.EnvScope.defaultConstList`. -/ def getFileEnvCore (path : FilePath) : IO FileEnv := do let path ← IO.FS.realPath path - initLeanSearchPathFor path let source ← IO.FS.readFile path let inputCtx := Parser.mkInputContext source path.toString let (header, parserState, messages) ← Parser.parseHeader inputCtx - -- Required for `processHeaderCore`'s `loadExts := true` import; a completed - -- import resets the flag, so it is re-armed before every import. - unsafe enableInitializersExecution - let (env, messages) ← processHeaderCore - (HeaderSyntax.startPos header) (HeaderSyntax.imports header) - (isModule := false) default messages inputCtx 0 + let (env, messages) ← Ix.withImportLock do + initLeanSearchPathFor path + unsafe enableInitializersExecution + processHeaderCore + (HeaderSyntax.startPos header) (HeaderSyntax.imports header) + (isModule := false) default messages inputCtx 0 if messages.hasErrors then throw $ IO.userError $ "\n\n".intercalate $ (← messages.toList.mapM (·.toString)).map (String.trimAscii · |>.toString) @@ -139,15 +138,16 @@ callers union locally-elaborated names (`getModuleIdxFor? · |>.isNone`) from the full-content env. -/ def moduleVisibleNames (path : FilePath) : IO (Option NameSet) := do let path ← IO.FS.realPath path - initLeanSearchPathFor path let source ← IO.FS.readFile path let inputCtx := Parser.mkInputContext source path.toString let (header, _, messages) ← Parser.parseHeader inputCtx if !HeaderSyntax.isModule header then return none - unsafe enableInitializersExecution -- re-armed per import; see `getFileEnvCore` - let (env, messages) ← processHeaderCore - (HeaderSyntax.startPos header) (HeaderSyntax.imports header) - (isModule := true) default messages inputCtx 0 + let (env, messages) ← Ix.withImportLock do + initLeanSearchPathFor path + unsafe enableInitializersExecution -- re-armed per import; see `getFileEnvCore` + processHeaderCore + (HeaderSyntax.startPos header) (HeaderSyntax.imports header) + (isModule := true) default messages inputCtx 0 if messages.hasErrors then throw $ IO.userError $ "\n\n".intercalate $ (← messages.toList.mapM (·.toString)).map (String.trimAscii · |>.toString) @@ -171,10 +171,11 @@ initial value — all imported entries sit in raw form but the computed state σ is empty, which silently breaks any test that reads extension state via `get_env!`. Matches `Lean.Elab.processHeaderCore`'s import path (used by `getFileEnv`) and Lake's own `importModulesUsingCache`. -/ -def getCompileEnv (imports : Array Name) : IO Environment := do - initLeanSearchPath - unsafe enableInitializersExecution -- required for `loadExts := true` - importModules (imports.map ({ module := · : Import })) default (loadExts := true) +def getCompileEnv (imports : Array Name) : IO Environment := + Ix.withImportLock do + initLeanSearchPath + unsafe enableInitializersExecution -- required for `loadExts := true` + importModules (imports.map ({ module := · : Import })) default (loadExts := true) macro "get_env!" : term => `(getCompileEnv this_file!) diff --git a/Ix/RoleBinding/Compile.lean b/Ix/RoleBinding/Compile.lean index e145257c76..3ac54ad499 100644 --- a/Ix/RoleBinding/Compile.lean +++ b/Ix/RoleBinding/Compile.lean @@ -5,6 +5,7 @@ public import Ix.Cert.Compile public import Ix.EnvScope public import Ix.LeanExport public import Ix.Meta +public import Ix.Common public import IxCK.Kernel.PinGen.Certs /-! Artifact-specific support and evidence for the production compiler. @@ -647,12 +648,14 @@ def elaborateNativeCertSource : IO Lean.Environment := do let opts := Lean.Options.empty.setBool `linter.deprecated false let inputCtx := Lean.Parser.mkInputContext nativeCertSourceText "IxCK/Kernel/PinGen/Certs.lean" let (header, _, _) ← Lean.Parser.parseHeader inputCtx - unsafe Lean.enableInitializersExecution - let some certElabEnv ← Lean.Elab.runFrontend nativeCertSourceText opts - "IxCK/Kernel/PinGen/Certs.lean" `IxCK.Kernel.PinGen.Certs - | throw (IO.userError "nativeCertSource: failed to elaborate embedded IxCK.Kernel.PinGen.Certs") - unsafe Lean.enableInitializersExecution - let baseEnv ← Lean.importModules (Lean.Elab.HeaderSyntax.imports header) default (loadExts := false) + let (certElabEnv, baseEnv) ← _root_.Ix.withImportLock do + unsafe Lean.enableInitializersExecution + let some certElabEnv ← Lean.Elab.runFrontend nativeCertSourceText opts + "IxCK/Kernel/PinGen/Certs.lean" `IxCK.Kernel.PinGen.Certs + | throw (IO.userError "nativeCertSource: failed to elaborate embedded IxCK.Kernel.PinGen.Certs") + unsafe Lean.enableInitializersExecution + let baseEnv ← Lean.importModules (Lean.Elab.HeaderSyntax.imports header) default (loadExts := false) + pure (certElabEnv, baseEnv) let baseConsts := baseEnv.constants.fold (init := #[]) fun acc n ci => acc.push (n, ci) let certConsts := certElabEnv.constants.map₂.foldl (init := #[]) fun acc n ci => acc.push (n, ci) Ix.LeanExport.environment (baseConsts ++ certConsts) @@ -665,25 +668,40 @@ without invoking `lake`. -/ def nativeCertSource : IO Lean.Environment := do if let some env ← cachedNativeCertSource.get then return env - if (← (← Lean.searchPathRef.get).findWithExt "olean" `Init).isNone then - Lean.initSearchPath (← Lean.findSysroot) - if (← (← Lean.searchPathRef.get).findModuleWithExt "olean" `IxCK.Kernel.PinGen.Certs).isNone then - let mut localDirs : List System.FilePath := [] - for dir in ([".lake/kernel/lib/lean", "../.lake/kernel/lib/lean", - "../../.lake/kernel/lib/lean"] : List System.FilePath) do - if ← dir.pathExists then - localDirs := localDirs ++ [dir] - unless localDirs.isEmpty do - let current ← Lean.searchPathRef.get - Lean.searchPathRef.set (localDirs ++ current) - let hasOlean ← match ← (← Lean.searchPathRef.get).findModuleWithExt "olean" `IxCK.Kernel.PinGen.Certs with - | some path => System.FilePath.pathExists (System.FilePath.mk (path.toString ++ ".private")) - | none => pure false - let env ← if hasOlean then - Lean.importModules #[{ module := `IxCK.Kernel.PinGen.Certs }] default (loadExts := false) - else - elaborateNativeCertSource - cachedNativeCertSource.set (some env) + let env ← _root_.Ix.withImportLock do + if let some env ← cachedNativeCertSource.get then + return env + if (← (← Lean.searchPathRef.get).findWithExt "olean" `Init).isNone then + Lean.initSearchPath (← Lean.findSysroot) + if (← (← Lean.searchPathRef.get).findModuleWithExt "olean" `IxCK.Kernel.PinGen.Certs).isNone then + let mut localDirs : List System.FilePath := [] + for dir in ([".lake/kernel/lib/lean", "../.lake/kernel/lib/lean", + "../../.lake/kernel/lib/lean"] : List System.FilePath) do + if ← dir.pathExists then + localDirs := localDirs ++ [dir] + unless localDirs.isEmpty do + let current ← Lean.searchPathRef.get + Lean.searchPathRef.set (localDirs ++ current) + let hasOlean ← match ← (← Lean.searchPathRef.get).findModuleWithExt "olean" `IxCK.Kernel.PinGen.Certs with + | some path => System.FilePath.pathExists (System.FilePath.mk (path.toString ++ ".private")) + | none => pure false + let env ← if hasOlean then + Lean.importModules #[{ module := `IxCK.Kernel.PinGen.Certs }] default (loadExts := false) + else do + let opts := Lean.Options.empty.setBool `linter.deprecated false + let inputCtx := Lean.Parser.mkInputContext nativeCertSourceText "IxCK/Kernel/PinGen/Certs.lean" + let (header, _, _) ← Lean.Parser.parseHeader inputCtx + unsafe Lean.enableInitializersExecution + let some certElabEnv ← Lean.Elab.runFrontend nativeCertSourceText opts + "IxCK/Kernel/PinGen/Certs.lean" `IxCK.Kernel.PinGen.Certs + | throw (IO.userError "nativeCertSource: failed to elaborate embedded IxCK.Kernel.PinGen.Certs") + unsafe Lean.enableInitializersExecution + let baseEnv ← Lean.importModules (Lean.Elab.HeaderSyntax.imports header) default (loadExts := false) + let baseConsts := baseEnv.constants.fold (init := #[]) fun acc n ci => acc.push (n, ci) + let certConsts := certElabEnv.constants.map₂.foldl (init := #[]) fun acc n ci => acc.push (n, ci) + Ix.LeanExport.environment (baseConsts ++ certConsts) + cachedNativeCertSource.set (some env) + return env return env /-- Release a `CheckedStore`'s decoded record map on a background task after diff --git a/IxCC/IxCC/BigNat/Basic.lean b/IxCC/IxCC/BigNat/Basic.lean index 149ba00649..aa69bf474b 100644 --- a/IxCC/IxCC/BigNat/Basic.lean +++ b/IxCC/IxCC/BigNat/Basic.lean @@ -17,11 +17,11 @@ together with its canonical normal-form invariant `WF`, mathematical denotation `ofSmall`, `toSmall?`) are monomorphic, first-order, tail-recursive, and never construct or manipulate `Nat` values `≥ 2^63`. `toNat` and `toNatPrefix` are specification functions (proof/test only). -- **Ownership contract (for Wave 3 `@unique` / `@borrowed` compilation):** - - `normalize (@unique xs : Array UInt64) : Array UInt64` — trims trailing zeros in place via `Array.pop`. - - `setLimb (@unique xs : Array UInt64) (i : Nat) (v : UInt64) : Array UInt64` — updates in place via `Array.set`. - - `padZeros (@unique xs : Array UInt64) (target : Nat) : Array UInt64` — extends in place via `Array.push`. - - `getLimb`, `isZero`, `slice`, `toSmall?` — `@borrowed xs`. +- **Ownership contract (for Wave 3 `@[unique]` / `@[borrowed]` compilation):** + - `normalize (@[unique] xs : Array UInt64) : Array UInt64` — trims trailing zeros in place via `Array.pop`. + - `setLimb (@[unique] xs : Array UInt64) (i : Nat) (v : UInt64) : Array UInt64` — updates in place via `Array.set`. + - `padZeros (@[unique] xs : Array UInt64) (target : Nat) : Array UInt64` — extends in place via `Array.push`. + - `getLimb`, `isZero`, `slice`, `toSmall?` — `@[borrowed] xs`. ## References @@ -39,14 +39,14 @@ def zero : Array UInt64 := #[] /-- Canonical representation of `1`. -/ def one : Array UInt64 := #[1] -/-- Test whether a canonical `BigNat` is zero (`@borrowed xs`). -/ +/-- Test whether a canonical `BigNat` is zero (`@[borrowed] xs`). -/ @[inline] def isZero (xs : Array UInt64) : Bool := xs.size == 0 -/-- Total, bounds-safe limb read returning `0` past the end (`@borrowed xs`). -/ +/-- Total, bounds-safe limb read returning `0` past the end (`@[borrowed] xs`). -/ @[inline] def getLimb (xs : Array UInt64) (i : Nat) : UInt64 := if h : i < xs.size then xs[i] else 0 -/-- Total, bounds-safe in-place limb write (`@unique xs`). -/ +/-- Total, bounds-safe in-place limb write (`@[unique] xs`). -/ @[inline] def setLimb (xs : Array UInt64) (i : Nat) (v : UInt64) : Array UInt64 := if h : i < xs.size then xs.set i v else xs @@ -65,7 +65,7 @@ Specification/proof only — never called by runtime routines. -/ def toNat (xs : Array UInt64) : Nat := toNatPrefix xs xs.size -/-- Tail-recursive helper building `n` zero limbs (`@unique acc`). -/ +/-- Tail-recursive helper building `n` zero limbs (`@[unique] acc`). -/ def mkZerosLoop (rem : Nat) (acc : Array UInt64) : Array UInt64 := match rem with | 0 => acc @@ -75,25 +75,25 @@ def mkZerosLoop (rem : Nat) (acc : Array UInt64) : Array UInt64 := def mkZeros (n : Nat) : Array UInt64 := mkZerosLoop n (Array.mkEmpty n) -/-- Tail-recursive helper extending `xs` with zero limbs to at least `target` limbs (`@unique xs`). -/ +/-- Tail-recursive helper extending `xs` with zero limbs to at least `target` limbs (`@[unique] xs`). -/ def padZerosLoop (rem : Nat) (xs : Array UInt64) : Array UInt64 := match rem with | 0 => xs | k + 1 => padZerosLoop k (xs.push 0) -/-- Extend `xs` with trailing zeros until `xs.size ≥ target` (`@unique xs`). +/-- Extend `xs` with trailing zeros until `xs.size ≥ target` (`@[unique] xs`). Allocates a fresh zero array when `xs` is empty so empty constants are never mutated. -/ def padZeros (xs : Array UInt64) (target : Nat) : Array UInt64 := if xs.size == 0 then mkZeros target else if xs.size < target then padZerosLoop (target - xs.size) xs else xs -/-- Tail-recursive helper copying `rem` limbs starting at `idx` (`@borrowed xs`, `@unique acc`). -/ +/-- Tail-recursive helper copying `rem` limbs starting at `idx` (`@[borrowed] xs`, `@[unique] acc`). -/ def sliceLoop (xs : Array UInt64) (idx rem : Nat) (acc : Array UInt64) : Array UInt64 := match rem with | 0 => acc | k + 1 => sliceLoop xs (idx + 1) k (acc.push (getLimb xs idx)) -/-- Copy limbs `[lo, min hi xs.size)` into a fresh array (`@borrowed xs`). -/ +/-- Copy limbs `[lo, min hi xs.size)` into a fresh array (`@[borrowed] xs`). -/ def slice (xs : Array UInt64) (lo hi : Nat) : Array UInt64 := let hi' := if hi ≤ xs.size then hi else xs.size if lo < hi' then @@ -101,7 +101,7 @@ def slice (xs : Array UInt64) (lo hi : Nat) : Array UInt64 := sliceLoop xs lo len (Array.mkEmpty len) else #[] -/-- Trim trailing zero limbs in place via `Array.pop` (`@unique xs`). -/ +/-- Trim trailing zero limbs in place via `Array.pop` (`@[unique] xs`). -/ def normalize (xs : Array UInt64) : Array UInt64 := if h : 0 < xs.size then if xs[xs.size - 1] == 0 then @@ -135,7 +135,7 @@ def ofNat (n : Nat) : Array UInt64 := ofNatLoop n #[] /-- Demote a canonical `BigNat` to `some n` iff its value is `< 2^63`, else `none`. -Uses `(v >>> 63) == 0` so no `Nat` literal `≥ 2^63` is constructed (`@borrowed xs`). -/ +Uses `(v >>> 63) == 0` so no `Nat` literal `≥ 2^63` is constructed (`@[borrowed] xs`). -/ def toSmall? (xs : Array UInt64) : Option Nat := if h : xs.size = 0 then some 0 diff --git a/IxCC/IxCC/BigNat/Div.lean b/IxCC/IxCC/BigNat/Div.lean index 6faec83743..cb7172f6ce 100644 --- a/IxCC/IxCC/BigNat/Div.lean +++ b/IxCC/IxCC/BigNat/Div.lean @@ -27,7 +27,7 @@ matching Lean's `Nat.div`/`Nat.mod` total semantics (`n / 0 = 0`, `n % 0 = n`). - Monomorphic, first-order, tail-recursive loops; zero `Nat` literals `≥ 2^63`. - Quotient array `q` and working remainder `rem` are allocated once and mutated - `@unique` in place; input operands `u`, `v`, `vn` are `@borrowed`. + `@[unique]` in place; input operands `u`, `v`, `vn` are `@[borrowed]`. ## References @@ -43,7 +43,7 @@ namespace IxCC.BigNat /-! ### Fast Single-Limb Division (`divMod1`) -/ /-- Top-down single-limb division loop processing limbs `k - 1` down to `0` -(`@borrowed a`, `@unique q`, erased proof `hrem : rem < d`). -/ +(`@[borrowed] a`, `@[unique] q`, erased proof `hrem : rem < d`). -/ def divMod1Loop (a : Array UInt64) (d : UInt64) : (k : Nat) → (rem : UInt64) → (rem < d) → Array UInt64 → Array UInt64 × UInt64 | 0, rem, _, q => (normalize q, rem) @@ -137,7 +137,7 @@ def subMulShiftLoop (rem vn : Array UInt64) (j n k : Nat) (qhat mulCarry : UInt6 termination_by n - k /-- Knuth D6 add-back in place: adds `vn[0 .. n-1]` into `rem[j .. j+n]` -(`@unique rem`, `@borrowed vn`). -/ +(`@[unique] rem`, `@[borrowed] vn`). -/ def addShiftLoop (rem vn : Array UInt64) (j n k : Nat) (carry : Bool) : Array UInt64 := if _h : k < n then let (s, c') := addCarry64 (getLimb rem (j + k)) (getLimb vn k) carry @@ -248,7 +248,7 @@ def divQuick1 (u v : Array UInt64) : Option (Array UInt64) := /-- Total multi-precision Euclidean division returning `(u / v, u % v)`. Matches Lean's `Nat.div` / `Nat.mod` on zero divisor: `divMod u 0 = (0, normalize u)`. -(`@borrowed u`, `@borrowed v`). -/ +(`@[borrowed] u`, `@[borrowed] v`). -/ def divMod (u v : Array UInt64) : Array UInt64 × Array UInt64 := let u' := normalize u let v' := normalize v @@ -262,7 +262,7 @@ def divMod (u v : Array UInt64) : Array UInt64 × Array UInt64 := else divModKnuth u' v' -/-- Multi-precision quotient matching `Nat.div` (`@borrowed u`, `@borrowed v`). +/-- Multi-precision quotient matching `Nat.div` (`@[borrowed] u`, `@[borrowed] v`). Uses O(1) `divQuick1` fast path and skips unnormalizing the discarded remainder. -/ def div (u v : Array UInt64) : Array UInt64 := let u' := normalize u @@ -275,7 +275,7 @@ def div (u v : Array UInt64) : Array UInt64 := | some q => q | none => normalize (divModKnuthRaw u' v').1 -/-- Multi-precision remainder matching `Nat.mod` (`@borrowed u`, `@borrowed v`). -/ +/-- Multi-precision remainder matching `Nat.mod` (`@[borrowed] u`, `@[borrowed] v`). -/ @[inline] def mod (u v : Array UInt64) : Array UInt64 := (divMod u v).2 diff --git a/IxCC/IxCC/BigNat/GcdConv.lean b/IxCC/IxCC/BigNat/GcdConv.lean index 88648cbd12..bb5365f42e 100644 --- a/IxCC/IxCC/BigNat/GcdConv.lean +++ b/IxCC/IxCC/BigNat/GcdConv.lean @@ -22,13 +22,13 @@ namespace IxCC.BigNat /-! ### Euclidean Greatest Common Divisor (`gcd`) -/ /-- Multi-precision greatest common divisor matching `Nat.gcd` via 128-bit Lehmer GCD -(`@borrowed a`, `@borrowed b`). -/ +(`@[borrowed] a`, `@[borrowed] b`). -/ @[inline] def gcd (a b : Array UInt64) : Array UInt64 := gcdLehmer a b /-! ### Single-Limb Multiply-Add (`mulAdd1`) -/ -/-- Linear multiply-add loop: computes `a * m + carry` (`@borrowed a`, `@unique acc`, +/-- Linear multiply-add loop: computes `a * m + carry` (`@[borrowed] a`, `@[unique] acc`, structural recursion on `rem`, single `addCarry64` per limb). -/ def mulAdd1Loop (a : Array UInt64) (m : UInt64) (i : Nat) (carry : UInt64) (acc : Array UInt64) : Nat → Array UInt64 diff --git a/IxCC/IxCC/BigNat/InvDiv.lean b/IxCC/IxCC/BigNat/InvDiv.lean index a05b961099..6468ad942b 100644 --- a/IxCC/IxCC/BigNat/InvDiv.lean +++ b/IxCC/IxCC/BigNat/InvDiv.lean @@ -45,7 +45,7 @@ namespace IxCC.BigNat if r ≥ d then (q1 + 1, r - d) else (q1, r) /-- Normalized single-limb division loop (`d ≥ 2^63`, `v = invert21 d`), processing -limbs `k - 1` down to `0` (`@borrowed a`, `@unique q`). -/ +limbs `k - 1` down to `0` (`@[borrowed] a`, `@[unique] q`). -/ def divMod1NormLoop (a : Array UInt64) (d v : UInt64) : Nat → UInt64 → Array UInt64 → Array UInt64 × UInt64 | 0, rem, q => (normalize q, rem) diff --git a/IxCC/IxCC/BigNat/Lehmer.lean b/IxCC/IxCC/BigNat/Lehmer.lean index 8d953a535b..896d65987a 100644 --- a/IxCC/IxCC/BigNat/Lehmer.lean +++ b/IxCC/IxCC/BigNat/Lehmer.lean @@ -40,7 +40,7 @@ Correctness of `gcdLehmer` depends ONLY on: - All loops use structural recursion on `Nat` (except `gcdU64` and `gcdLehmerLoop`, which terminate on erased `b.toNat` and `toNat a + toNat b`). - No `Nat` literal `≥ 2^63`; no `do`/`for`/`let rec`; no `partial`/`unsafe`/`@[extern]`. -- Operands `a`, `b` are `@borrowed`; linear-combination buffers are freshly allocated +- Operands `a`, `b` are `@[borrowed]`; linear-combination buffers are freshly allocated and linearly owned. ## References @@ -72,8 +72,8 @@ def gcdWord64 (a b : UInt64) : UInt64 := /-! ### Single-Pass Fused Linear Combination Subtract (`linCombSub`) -/ -/-- Single-pass fused kernel computing `u * x - v * y` (`@borrowed x`, `@borrowed y`, -`@unique acc`, structural recursion on `rem`). +/-- Single-pass fused kernel computing `u * x - v * y` (`@[borrowed] x`, `@[borrowed] y`, +`@[unique] acc`, structural recursion on `rem`). Returns `some (normalize res)` iff `u * toNat x ≥ v * toNat y`, else `none`. -/ def linCombSubLoop (x y : Array UInt64) (u v : UInt64) (i : Nat) (mulCarry subCarry : UInt64) (acc : Array UInt64) : Nat → Option (Array UInt64) @@ -90,7 +90,7 @@ def linCombSubLoop (x y : Array UInt64) (u v : UInt64) (i : Nat) let (diff, subCarry') := subMulCarry64 sLo (getLimb y i) v subCarry linCombSubLoop x y u v (i + 1) mulCarry' subCarry' (acc.push diff) rem -/-- Single-pass linear combination `u * x - v * y` (`@borrowed x`, `@borrowed y`). +/-- Single-pass linear combination `u * x - v * y` (`@[borrowed] x`, `@[borrowed] y`). Returns `some res` with `WF res` and `toNat res + v.toNat * toNat y = u.toNat * toNat x` when nonnegative, or `none` when `u * x < v * y`. -/ def linCombSub (u : UInt64) (x : Array UInt64) (v : UInt64) (y : Array UInt64) : @@ -271,7 +271,7 @@ def gcdLehmerLoop (a b : Array UInt64) : Nat → Array UInt64 | some (hi, lo) => gcdLehmerLoop hi lo fuel | none => gcdLehmerLoop b (divModKnuth a b).2 fuel -/-- Multi-precision Lehmer GCD (`@borrowed a`, `@borrowed b`). -/ +/-- Multi-precision Lehmer GCD (`@[borrowed] a`, `@[borrowed] b`). -/ def gcdLehmer (a b : Array UInt64) : Array UInt64 := let na := normalize a let nb := normalize b diff --git a/IxCC/IxCC/BigNat/Linear.lean b/IxCC/IxCC/BigNat/Linear.lean index 5353c14a5e..7405d9a9dd 100644 --- a/IxCC/IxCC/BigNat/Linear.lean +++ b/IxCC/IxCC/BigNat/Linear.lean @@ -11,12 +11,12 @@ bit/limb shifts, and base-2 logarithm on canonical little-endian `Array UInt64`. over `Array UInt64` using exclusively `LimbOps` (`addCarry64`, `subBorrow64`, `clz64`), `UInt64` word ops, and small `Nat` indices `< 2^63`. Zero `Nat` literals `≥ 2^63`, zero `toNat` calls in runtime code. -- **Ownership contract (for Wave 3 `@unique` / `@borrowed` compilation):** +- **Ownership contract (for Wave 3 `@[unique]` / `@[borrowed]` compilation):** - `cmp`, `beq`, `ble`, `blt`, `add`, `sub`, `subRaw`, `land`, `lor`, `xor`, - `shiftLeft`, `shiftRight`, `shiftLimbs`, `log2` — `@borrowed` operands; - freshly allocated output accumulators are threaded `@unique` through + `shiftLeft`, `shiftRight`, `shiftLimbs`, `log2` — `@[borrowed]` operands; + freshly allocated output accumulators are threaded `@[unique]` through tail-recursive loops. - - `pred (@unique a : Array UInt64) : Array UInt64` — updates limbs in place + - `pred (@[unique] a : Array UInt64) : Array UInt64` — updates limbs in place via `Array.set` / `Array.pop`. ## References @@ -34,7 +34,7 @@ namespace IxCC.BigNat /-! ### Comparison (`cmp`, `beq`, `ble`, `blt`) -/ -/-- Compare limbs `k - 1` down to `0` lexicographically (`@borrowed a`, `@borrowed b`). -/ +/-- Compare limbs `k - 1` down to `0` lexicographically (`@[borrowed] a`, `@[borrowed] b`). -/ def cmpLoop (a b : Array UInt64) : Nat → Ordering | 0 => .eq | k + 1 => @@ -44,25 +44,25 @@ def cmpLoop (a b : Array UInt64) : Nat → Ordering else if va > vb then .gt else cmpLoop a b k -/-- Compare two canonical (`WF`) `BigNat`s (`@borrowed a`, `@borrowed b`). -/ +/-- Compare two canonical (`WF`) `BigNat`s (`@[borrowed] a`, `@[borrowed] b`). -/ def cmp (a b : Array UInt64) : Ordering := if a.size < b.size then .lt else if a.size > b.size then .gt else cmpLoop a b a.size -/-- Canonical equality (`@borrowed a`, `@borrowed b`). -/ +/-- Canonical equality (`@[borrowed] a`, `@[borrowed] b`). -/ @[inline] def beq (a b : Array UInt64) : Bool := match cmp a b with | .eq => true | _ => false -/-- Canonical `≤` (`@borrowed a`, `@borrowed b`). -/ +/-- Canonical `≤` (`@[borrowed] a`, `@[borrowed] b`). -/ @[inline] def ble (a b : Array UInt64) : Bool := match cmp a b with | .gt => false | _ => true -/-- Canonical `<` (`@borrowed a`, `@borrowed b`). -/ +/-- Canonical `<` (`@[borrowed] a`, `@[borrowed] b`). -/ @[inline] def blt (a b : Array UInt64) : Bool := match cmp a b with | .lt => true @@ -70,7 +70,7 @@ def cmp (a b : Array UInt64) : Ordering := /-! ### Addition (`add`) -/ -/-- Tail-recursive carry-propagation loop over `n` limbs (`@borrowed a`, `@borrowed b`, `@unique acc`). -/ +/-- Tail-recursive carry-propagation loop over `n` limbs (`@[borrowed] a`, `@[borrowed] b`, `@[unique] acc`). -/ def addLoop (a b : Array UInt64) (n i : Nat) (carry : Bool) (acc : Array UInt64) : Array UInt64 := if _h : i < n then let (lo, c') := addCarry64 (getLimb a i) (getLimb b i) carry @@ -86,7 +86,7 @@ def add (a b : Array UInt64) : Array UInt64 := /-! ### Truncating Subtraction (`subRaw`, `sub`) and Predecessor (`pred`) -/ -/-- Tail-recursive borrow-propagation loop over `n` limbs (`@borrowed a`, `@borrowed b`, `@unique acc`). -/ +/-- Tail-recursive borrow-propagation loop over `n` limbs (`@[borrowed] a`, `@[borrowed] b`, `@[unique] acc`). -/ def subLoop (a b : Array UInt64) (n i : Nat) (borrow : Bool) (acc : Array UInt64) : Array UInt64 × Bool := if _h : i < n then @@ -103,7 +103,7 @@ def subRaw (a b : Array UInt64) : Array UInt64 := if borrow then #[] else normalize acc /-- Truncating subtraction on canonical (`WF`) `BigNat`s, with zero-allocation fast -exit when `a ≤ b` (`@borrowed a`, `@borrowed b`). -/ +exit when `a ≤ b` (`@[borrowed] a`, `@[borrowed] b`). -/ def sub (a b : Array UInt64) : Array UInt64 := match cmp a b with | .lt => #[] @@ -112,7 +112,7 @@ def sub (a b : Array UInt64) : Array UInt64 := let (acc, borrow) := subLoop a b a.size 0 false (Array.mkEmpty a.size) if borrow then #[] else normalize acc -/-- In-place borrow chain for `pred` (`@unique a`). -/ +/-- In-place borrow chain for `pred` (`@[unique] a`). -/ def predLoop (a : Array UInt64) (i : Nat) : Array UInt64 := if h : i < a.size then let v := a[i] @@ -125,7 +125,7 @@ def predLoop (a : Array UInt64) (i : Nat) : Array UInt64 := #[] termination_by a.size - i -/-- Truncating predecessor (`pred 0 = 0`, in-place on `@unique a`). -/ +/-- Truncating predecessor (`pred 0 = 0`, in-place on `@[unique] a`). -/ def pred (a : Array UInt64) : Array UInt64 := if a.size == 0 then #[] else predLoop a 0 @@ -137,7 +137,7 @@ def landLoop (a b : Array UInt64) (n i : Nat) (acc : Array UInt64) : Array UInt6 else acc termination_by n - i -/-- Bitwise AND (`@borrowed a`, `@borrowed b`). -/ +/-- Bitwise AND (`@[borrowed] a`, `@[borrowed] b`). -/ def land (a b : Array UInt64) : Array UInt64 := let n := if a.size ≤ b.size then a.size else b.size normalize (landLoop a b n 0 (Array.mkEmpty n)) @@ -148,7 +148,7 @@ def lorLoop (a b : Array UInt64) (n i : Nat) (acc : Array UInt64) : Array UInt64 else acc termination_by n - i -/-- Bitwise OR (`@borrowed a`, `@borrowed b`). -/ +/-- Bitwise OR (`@[borrowed] a`, `@[borrowed] b`). -/ def lor (a b : Array UInt64) : Array UInt64 := let n := if a.size ≤ b.size then b.size else a.size normalize (lorLoop a b n 0 (Array.mkEmpty n)) @@ -159,21 +159,21 @@ def xorLoop (a b : Array UInt64) (n i : Nat) (acc : Array UInt64) : Array UInt64 else acc termination_by n - i -/-- Bitwise XOR (`@borrowed a`, `@borrowed b`). -/ +/-- Bitwise XOR (`@[borrowed] a`, `@[borrowed] b`). -/ def xor (a b : Array UInt64) : Array UInt64 := let n := if a.size ≤ b.size then b.size else a.size normalize (xorLoop a b n 0 (Array.mkEmpty n)) /-! ### Shifts (`shiftLimbs`, `shiftLeft`, `shiftRight`) and `log2` -/ -/-- Copy `a[0 .. a.size)` onto the end of `acc` (`@borrowed a`, `@unique acc`). -/ +/-- Copy `a[0 .. a.size)` onto the end of `acc` (`@[borrowed] a`, `@[unique] acc`). -/ def copyAppendLoop (a : Array UInt64) (i : Nat) (acc : Array UInt64) : Array UInt64 := if h : i < a.size then copyAppendLoop a (i + 1) (acc.push a[i]) else acc termination_by a.size - i -/-- Multiply by `(2^64)^k` by prepending `k` zero limbs (`@borrowed a`). -/ +/-- Multiply by `(2^64)^k` by prepending `k` zero limbs (`@[borrowed] a`). -/ def shiftLimbs (a : Array UInt64) (k : Nat) : Array UInt64 := let a' := normalize a if a'.size == 0 then #[] @@ -194,7 +194,7 @@ def shiftLeftBitLoop (a : Array UInt64) (b invB : UInt64) (i : Nat) if carry == 0 then acc else acc.push carry termination_by a.size - i -/-- Left shift by `s` bits (`toNat (shiftLeft a s) = toNat a <<< s`, `@borrowed a`). -/ +/-- Left shift by `s` bits (`toNat (shiftLeft a s) = toNat a <<< s`, `@[borrowed] a`). -/ def shiftLeft (a : Array UInt64) (s : Nat) : Array UInt64 := let a' := normalize a if a'.size == 0 then #[] @@ -210,7 +210,7 @@ def shiftLeft (a : Array UInt64) (s : Nat) : Array UInt64 := let invB := (64 : UInt64) - b normalize (shiftLeftBitLoop a' b invB 0 0 acc) -/-- Copy limbs `a[wordShift + i]` for `i < outLen` (`@borrowed a`, `@unique acc`). -/ +/-- Copy limbs `a[wordShift + i]` for `i < outLen` (`@[borrowed] a`, `@[unique] acc`). -/ def shiftRightWordLoop (a : Array UInt64) (wordShift outLen i : Nat) (acc : Array UInt64) : Array UInt64 := if _h : i < outLen then @@ -228,7 +228,7 @@ def shiftRightBitLoop (a : Array UInt64) (wordShift outLen : Nat) (b invB : UInt else acc termination_by outLen - i -/-- Right shift by `s` bits (`toNat (shiftRight a s) = toNat a >>> s`, `@borrowed a`). -/ +/-- Right shift by `s` bits (`toNat (shiftRight a s) = toNat a >>> s`, `@[borrowed] a`). -/ def shiftRight (a : Array UInt64) (s : Nat) : Array UInt64 := if s == 0 then normalize a else @@ -244,7 +244,7 @@ def shiftRight (a : Array UInt64) (s : Nat) : Array UInt64 := let invB := (64 : UInt64) - b normalize (shiftRightBitLoop a wordShift outLen b invB 0 (Array.mkEmpty outLen)) -/-- Fast small-bit left shift (`0 ≤ s < 64`, zero `wordShift`/`div`/`mod`, `@borrowed a`). -/ +/-- Fast small-bit left shift (`0 ≤ s < 64`, zero `wordShift`/`div`/`mod`, `@[borrowed] a`). -/ def shiftLeftSmall (a : Array UInt64) (s : Nat) : Array UInt64 := if s == 0 then normalize a else @@ -252,7 +252,7 @@ def shiftLeftSmall (a : Array UInt64) (s : Nat) : Array UInt64 := let invB := (64 : UInt64) - b normalize (shiftLeftBitLoop a b invB 0 0 (Array.mkEmpty (a.size + 1))) -/-- Fast small-bit right shift (`0 ≤ s < 64`, zero `wordShift`/`div`/`mod`, `@borrowed a`). -/ +/-- Fast small-bit right shift (`0 ≤ s < 64`, zero `wordShift`/`div`/`mod`, `@[borrowed] a`). -/ def shiftRightSmall (a : Array UInt64) (s : Nat) : Array UInt64 := if s == 0 then normalize a else @@ -260,7 +260,7 @@ def shiftRightSmall (a : Array UInt64) (s : Nat) : Array UInt64 := let invB := (64 : UInt64) - b normalize (shiftRightBitLoop a 0 a.size b invB 0 (Array.mkEmpty a.size)) -/-- Base-2 floor logarithm matching `Nat.log2` (`log2 0 = 0`, `@borrowed a`). -/ +/-- Base-2 floor logarithm matching `Nat.log2` (`log2 0 = 0`, `@[borrowed] a`). -/ def log2 (a : Array UInt64) : Nat := if h : a.size = 0 then 0 else @@ -302,13 +302,13 @@ theorem size_add_le (a b : Array UInt64) : /-! ### Stage 2 In-Place Unique-COW Limb Operations & Fast 1-Bit Shifts -/ /-- Copy `src` into a freshly allocated array of `max src.size target` limbs, zero-padded. -Always allocates a fresh unique buffer of exact final capacity (`@borrowed src`). -/ +Always allocates a fresh unique buffer of exact final capacity (`@[borrowed] src`). -/ def copyIntoZeros (src : Array UInt64) (target : Nat) : Array UInt64 := let sz := if src.size < target then target else src.size let acc := copyAppendLoop src 0 (Array.mkEmpty sz) if src.size < target then padZerosLoop (target - src.size) acc else acc -/-- Propagate carry `1` starting at index `idx` into `@unique acc` in place +/-- Propagate carry `1` starting at index `idx` into `@[unique] acc` in place (structural recursion on `rem = acc.size - idx`). -/ def addCarryAtLoop (acc : Array UInt64) (idx : Nat) : Nat → Array UInt64 | 0 => acc.push 1 @@ -317,7 +317,7 @@ def addCarryAtLoop (acc : Array UInt64) (idx : Nat) : Nat → Array UInt64 if v == 0 then addCarryAtLoop (setLimb acc idx 0) (idx + 1) rem else setLimb acc idx v -/-- Add `b[i .. i + rem)` into `@unique acc` starting at `off + i` in place. -/ +/-- Add `b[i .. i + rem)` into `@[unique] acc` starting at `off + i` in place. -/ def addAtLoop (acc b : Array UInt64) (off i : Nat) (carry : Bool) : Nat → Array UInt64 | 0 => if carry then addCarryAtLoop acc (off + i) (acc.size - (off + i)) else acc | rem + 1 => @@ -325,7 +325,7 @@ def addAtLoop (acc b : Array UInt64) (off i : Nat) (carry : Bool) : Nat → Arra let (lo, c') := addCarry64 (getLimb acc idx) (getLimb b i) carry addAtLoop (setLimb acc idx lo) b off (i + 1) c' rem -/-- In-place shifted addition: computes `acc + b * (2^64)^off`, mutating `@unique acc` +/-- In-place shifted addition: computes `acc + b * (2^64)^off`, mutating `@[unique] acc` in place (padding only if `acc.size < off + b.size`; caller calls `normalize` once). -/ def addAtInPlace (acc b : Array UInt64) (off : Nat) : Array UInt64 := if b.size == 0 then acc @@ -333,11 +333,11 @@ def addAtInPlace (acc b : Array UInt64) (off : Nat) : Array UInt64 := let acc0 := padZeros acc (off + b.size) addAtLoop acc0 b off 0 false b.size -/-- In-place addition `acc + b`, mutating `@unique acc` in place (unnormalized). -/ +/-- In-place addition `acc + b`, mutating `@[unique] acc` in place (unnormalized). -/ @[inline] def addInPlace (acc b : Array UInt64) : Array UInt64 := addAtInPlace acc b 0 -/-- Propagate borrow `1` starting at index `idx` into `@unique acc` in place +/-- Propagate borrow `1` starting at index `idx` into `@[unique] acc` in place (structural recursion on `rem = acc.size - idx`). -/ def subBorrowAtLoop (acc : Array UInt64) (idx : Nat) : Nat → Array UInt64 × Bool | 0 => (acc, true) @@ -346,7 +346,7 @@ def subBorrowAtLoop (acc : Array UInt64) (idx : Nat) : Nat → Array UInt64 × B if v == 0 then subBorrowAtLoop (setLimb acc idx maxWord64) (idx + 1) rem else (setLimb acc idx (v - 1), false) -/-- Subtract `b[i .. i + rem)` from `@unique acc` starting at `off + i` in place. -/ +/-- Subtract `b[i .. i + rem)` from `@[unique] acc` starting at `off + i` in place. -/ def subAtLoop (acc b : Array UInt64) (off i : Nat) (borrow : Bool) : Nat → Array UInt64 × Bool | 0 => if borrow then subBorrowAtLoop acc (off + i) (acc.size - (off + i)) else (acc, false) | rem + 1 => @@ -354,7 +354,7 @@ def subAtLoop (acc b : Array UInt64) (off i : Nat) (borrow : Bool) : Nat → Arr let (lo, b') := subBorrow64 (getLimb acc idx) (getLimb b i) borrow subAtLoop (setLimb acc idx lo) b off (i + 1) b' rem -/-- In-place shifted subtraction: computes `acc - b * (2^64)^off`, mutating `@unique acc` +/-- In-place shifted subtraction: computes `acc - b * (2^64)^off`, mutating `@[unique] acc` in place and returning `(res, borrowOut)`. -/ def subAtInPlace (acc b : Array UInt64) (off : Nat) : Array UInt64 × Bool := if b.size == 0 then (acc, false) @@ -362,7 +362,7 @@ def subAtInPlace (acc b : Array UInt64) (off : Nat) : Array UInt64 × Bool := let acc0 := padZeros acc (off + b.size) subAtLoop acc0 b off 0 false b.size -/-- In-place truncating subtraction on `@unique acc` (`toNat (subInPlace acc b) = toNat acc - toNat b`). -/ +/-- In-place truncating subtraction on `@[unique] acc` (`toNat (subInPlace acc b) = toNat acc - toNat b`). -/ def subInPlace (acc b : Array UInt64) : Array UInt64 := let (res, borrow) := subAtInPlace acc b 0 if borrow then #[] else normalize res @@ -378,7 +378,7 @@ with `diff + b * q + carry = a + nextCarry * 2^64` and `nextCarry < 2^64` (zero let b2 : UInt64 := if r2.2 then 1 else 0 (r2.1, p.2 + c1 + b2) -/-- Add `m * b[i .. i + rem) * (2^64)^off` into `@unique acc` in place. -/ +/-- Add `m * b[i .. i + rem) * (2^64)^off` into `@[unique] acc` in place. -/ def addMul1AtLoop (acc b : Array UInt64) (off i : Nat) (m carry : UInt64) : Nat → Array UInt64 | 0 => if carry == 0 then acc @@ -394,18 +394,18 @@ def addMul1AtLoop (acc b : Array UInt64) (off i : Nat) (m carry : UInt64) : Nat let (lo, carry') := mulAddCarry64 m (getLimb b i) (getLimb acc idx) carry addMul1AtLoop (setLimb acc idx lo) b off (i + 1) m carry' rem -/-- In-place multiply-accumulate `acc + m * b * (2^64)^off` (`@unique acc`, `@borrowed b`). -/ +/-- In-place multiply-accumulate `acc + m * b * (2^64)^off` (`@[unique] acc`, `@[borrowed] b`). -/ def addMul1AtInPlace (acc b : Array UInt64) (m : UInt64) (off : Nat) : Array UInt64 := if b.size == 0 || m == 0 then acc else let acc0 := padZeros acc (off + b.size) addMul1AtLoop acc0 b off 0 m 0 b.size -/-- In-place multiply-accumulate `acc + m * b` (`@unique acc`, `@borrowed b`). -/ +/-- In-place multiply-accumulate `acc + m * b` (`@[unique] acc`, `@[borrowed] b`). -/ @[inline] def addMul1InPlace (acc b : Array UInt64) (m : UInt64) : Array UInt64 := addMul1AtInPlace acc b m 0 -/-- Subtract `m * b[i .. i + rem) * (2^64)^off` from `@unique acc` in place, returning +/-- Subtract `m * b[i .. i + rem) * (2^64)^off` from `@[unique] acc` in place, returning `(res, borrowWord)` satisfying `toNat res + m * b * B^off = toNat acc + borrowWord * B^res.size`. -/ def subMul1AtLoop (acc b : Array UInt64) (off i : Nat) (m carry : UInt64) : Nat → Array UInt64 × UInt64 @@ -426,7 +426,7 @@ def subMul1AtLoop (acc b : Array UInt64) (off i : Nat) (m carry : UInt64) : let (diff, carry') := subMulCarry64 (getLimb acc idx) (getLimb b i) m carry subMul1AtLoop (setLimb acc idx diff) b off (i + 1) m carry' rem -/-- In-place multiply-subtract `acc - m * b * (2^64)^off` (`@unique acc`, `@borrowed b`), +/-- In-place multiply-subtract `acc - m * b * (2^64)^off` (`@[unique] acc`, `@[borrowed] b`), returning `(res, borrowWord)` where `borrowWord == 0` iff no underflow occurred. -/ def subMul1AtInPlace (acc b : Array UInt64) (m : UInt64) (off : Nat) : Array UInt64 × UInt64 := if b.size == 0 || m == 0 then (acc, 0) @@ -434,11 +434,11 @@ def subMul1AtInPlace (acc b : Array UInt64) (m : UInt64) (off : Nat) : Array UIn let acc0 := padZeros acc (off + b.size) subMul1AtLoop acc0 b off 0 m 0 b.size -/-- In-place multiply-subtract `acc - m * b` (`@unique acc`, `@borrowed b`). -/ +/-- In-place multiply-subtract `acc - m * b` (`@[unique] acc`, `@[borrowed] b`). -/ @[inline] def subMul1InPlace (acc b : Array UInt64) (m : UInt64) : Array UInt64 × UInt64 := subMul1AtInPlace acc b m 0 -/-- Fast 1-bit left shift loop (`@borrowed a`, `@unique acc`). -/ +/-- Fast 1-bit left shift loop (`@[borrowed] a`, `@[unique] acc`). -/ def shiftLeft1Loop (a : Array UInt64) (i : Nat) (carry : UInt64) (acc : Array UInt64) : Nat → Array UInt64 | 0 => if carry == 0 then acc else acc.push carry @@ -453,7 +453,7 @@ def shiftLeft1 (a : Array UInt64) : Array UInt64 := if a.size == 0 then #[] else normalize (shiftLeft1Loop a 0 0 (Array.mkEmpty (a.size + 1)) a.size) -/-- Fast 1-bit right shift loop (`@borrowed a`, `@unique acc`). -/ +/-- Fast 1-bit right shift loop (`@[borrowed] a`, `@[unique] acc`). -/ def shiftRight1Loop (a : Array UInt64) (i : Nat) (acc : Array UInt64) : Nat → Array UInt64 | 0 => acc | rem + 1 => diff --git a/IxCC/IxCC/BigNat/Mul.lean b/IxCC/IxCC/BigNat/Mul.lean index c3bada701e..ab69c50401 100644 --- a/IxCC/IxCC/BigNat/Mul.lean +++ b/IxCC/IxCC/BigNat/Mul.lean @@ -28,8 +28,8 @@ exponentiation (`pow`) over canonical little-endian `Array UInt64`. - All functions are monomorphic, first-order, and tail-recursive (except the structurally terminating Karatsuba recursion of depth `O(log n)`). - No `Nat` literal or intermediate value `≥ 2^63` is constructed. -- Operands `a`, `b`, `base` are `@borrowed`; product accumulators `acc` are - allocated once and mutated `@unique` in place. +- Operands `a`, `b`, `base` are `@[borrowed]`; product accumulators `acc` are + allocated once and mutated `@[unique]` in place. ## References @@ -54,7 +54,7 @@ def toom3Threshold : Nat := 96 /-! ### Schoolbook Multiplication (`mulSchoolbook`) -/ /-- Inner multiply-accumulate row: adds `a_i * b[j..b.size) * B^i + carry * B^(i+j)` -into `acc` in place (`@borrowed b`, `@unique acc`). -/ +into `acc` in place (`@[borrowed] b`, `@[unique] acc`). -/ def mulAddRow (a_i : UInt64) (b : Array UInt64) (i j : Nat) (carry : UInt64) (acc : Array UInt64) : Array UInt64 := if h : j < b.size then @@ -64,7 +64,7 @@ def mulAddRow (a_i : UInt64) (b : Array UInt64) (i j : Nat) (carry : UInt64) setLimb acc (i + b.size) carry termination_by b.size - j -/-- Outer loop of schoolbook multiplication (`@borrowed a`, `@borrowed b`, `@unique acc`). -/ +/-- Outer loop of schoolbook multiplication (`@[borrowed] a`, `@[borrowed] b`, `@[unique] acc`). -/ def mulOuterLoop (a b : Array UInt64) (i : Nat) (acc : Array UInt64) : Array UInt64 := if h : i < a.size then let acc' := mulAddRow a[i] b i 0 0 acc @@ -73,14 +73,14 @@ def mulOuterLoop (a b : Array UInt64) (i : Nat) (acc : Array UInt64) : Array UIn acc termination_by a.size - i -/-- Schoolbook `O(m·n)` multiplication (`@borrowed a`, `@borrowed b`). -/ +/-- Schoolbook `O(m·n)` multiplication (`@[borrowed] a`, `@[borrowed] b`). -/ def mulSchoolbook (a b : Array UInt64) : Array UInt64 := if a.size == 0 || b.size == 0 then #[] else normalize (mulOuterLoop a b 0 (mkZeros (a.size + b.size))) /-! ### Dedicated Squaring (`sqrSchoolbook`) -/ -/-- Accumulate off-diagonal products `a_i * a[j..a.size)` into `acc` (`@borrowed a`, `@unique acc`). -/ +/-- Accumulate off-diagonal products `a_i * a[j..a.size)` into `acc` (`@[borrowed] a`, `@[unique] acc`). -/ def sqrOffRow (a : Array UInt64) (a_i : UInt64) (i j : Nat) (carry : UInt64) (acc : Array UInt64) : Array UInt64 := if h : j < a.size then @@ -90,7 +90,7 @@ def sqrOffRow (a : Array UInt64) (a_i : UInt64) (i j : Nat) (carry : UInt64) setLimb acc (i + a.size) carry termination_by a.size - j -/-- Outer loop for off-diagonal terms `∑_{i < j} a[i] * a[j] * B^(i+j)` (`@borrowed a`, `@unique acc`). -/ +/-- Outer loop for off-diagonal terms `∑_{i < j} a[i] * a[j] * B^(i+j)` (`@[borrowed] a`, `@[unique] acc`). -/ def sqrOffOuter (a : Array UInt64) (i : Nat) (acc : Array UInt64) : Array UInt64 := if h : i < a.size then let acc' := sqrOffRow a a[i] i (i + 1) 0 acc @@ -99,7 +99,7 @@ def sqrOffOuter (a : Array UInt64) (i : Nat) (acc : Array UInt64) : Array UInt64 acc termination_by a.size - i -/-- Double a limb array in place using `addCarry64 v v carry` (`@unique acc`). -/ +/-- Double a limb array in place using `addCarry64 v v carry` (`@[unique] acc`). -/ def doubleInPlaceLoop (acc : Array UInt64) (i : Nat) (carry : Bool) : Array UInt64 := if h : i < acc.size then let v := acc[i] @@ -111,7 +111,7 @@ def doubleInPlaceLoop (acc : Array UInt64) (i : Nat) (carry : Bool) : Array UInt termination_by acc.size - i /-- Add diagonal squares `∑_{i < a.size} a[i]^2 * B^(2*i)` into `acc` in place -(`@borrowed a`, `@unique acc`). -/ +(`@[borrowed] a`, `@[unique] acc`). -/ def sqrAddDiagLoop (a : Array UInt64) (i : Nat) (carry : Bool) (acc : Array UInt64) : Array UInt64 := if h : i < a.size then @@ -126,7 +126,7 @@ def sqrAddDiagLoop (a : Array UInt64) (i : Nat) (carry : Bool) acc termination_by a.size - i -/-- Dedicated schoolbook squaring (`@borrowed a`). -/ +/-- Dedicated schoolbook squaring (`@[borrowed] a`). -/ def sqrSchoolbook (a : Array UInt64) : Array UInt64 := if a.size == 0 then #[] else @@ -139,7 +139,7 @@ def sqrSchoolbook (a : Array UInt64) : Array UInt64 := /-! ### Karatsuba Multiplication & Squaring (`K = 32` limbs) -/ /-- Karatsuba multiplication loop with structural recursion on `fuel` -(threshold `karatsubaThreshold = 32` limbs; `@borrowed a`, `@borrowed b`). -/ +(threshold `karatsubaThreshold = 32` limbs; `@[borrowed] a`, `@[borrowed] b`). -/ def mulKaratsubaLoop (a b : Array UInt64) : Nat → Array UInt64 | 0 => mulSchoolbook a b | fuel + 1 => @@ -159,11 +159,11 @@ def mulKaratsubaLoop (a b : Array UInt64) : Nat → Array UInt64 let z1Full := mulKaratsubaLoop sA sB fuel karatsubaCombine z0 z2 z1Full m (a.size + b.size) -/-- Karatsuba multiplication with threshold `karatsubaThreshold = 32` limbs (`@borrowed a`, `@borrowed b`). -/ +/-- Karatsuba multiplication with threshold `karatsubaThreshold = 32` limbs (`@[borrowed] a`, `@[borrowed] b`). -/ def mulKaratsuba (a b : Array UInt64) : Array UInt64 := mulKaratsubaLoop a b (if a.size ≤ b.size then b.size else a.size) -/-- Karatsuba squaring loop with structural recursion on `fuel` (`@borrowed a`). -/ +/-- Karatsuba squaring loop with structural recursion on `fuel` (`@[borrowed] a`). -/ def sqrKaratsubaLoop (a : Array UInt64) : Nat → Array UInt64 | 0 => sqrSchoolbook a | fuel + 1 => @@ -179,7 +179,7 @@ def sqrKaratsubaLoop (a : Array UInt64) : Nat → Array UInt64 let z1Full := sqrKaratsubaLoop sA fuel karatsubaCombine z0 z2 z1Full m (2 * a.size) -/-- Karatsuba squaring with threshold `karatsubaThreshold = 32` limbs (`@borrowed a`). -/ +/-- Karatsuba squaring with threshold `karatsubaThreshold = 32` limbs (`@[borrowed] a`). -/ def sqrKaratsuba (a : Array UInt64) : Array UInt64 := sqrKaratsubaLoop a a.size @@ -216,12 +216,12 @@ def mulToom3Loop (a b : Array UInt64) : Nat → Array UInt64 toom3Interp r0 r1 rm1 r2 rInf (pm1Neg != qm1Neg) k (n + y.size) /-- Balanced Toom-Cook 3-way multiplication (`O(n^1.465)`), falling back to `mulKaratsuba` -below `toom3Threshold` (`@borrowed a`, `@borrowed b`). -/ +below `toom3Threshold` (`@[borrowed] a`, `@[borrowed] b`). -/ def mulToom3 (a b : Array UInt64) : Array UInt64 := mulToom3Loop a b (if a.size ≤ b.size then b.size else a.size) /-- Dedicated Toom-Cook 3-way squaring loop (`O(n^1.465)`) with structural recursion on -`fuel`, delegating below `toom3Threshold` to recursive `sqrKaratsubaLoop` (`@borrowed a`). -/ +`fuel`, delegating below `toom3Threshold` to recursive `sqrKaratsubaLoop` (`@[borrowed] a`). -/ def sqrToom3Loop (a : Array UInt64) : Nat → Array UInt64 | 0 => sqrKaratsuba a | fuel + 1 => @@ -238,7 +238,7 @@ def sqrToom3Loop (a : Array UInt64) : Nat → Array UInt64 toom3Interp r0 r1 rm1 r2 rInf false k (2 * a.size) /-- Dedicated Toom-Cook 3-way squaring (`O(n^1.465)`), falling back to `sqrKaratsuba` -below `toom3Threshold` (`@borrowed a`). -/ +below `toom3Threshold` (`@[borrowed] a`). -/ def sqrToom3 (a : Array UInt64) : Array UInt64 := sqrToom3Loop a a.size @@ -268,7 +268,7 @@ termination_by n def natBitLen (n : Nat) : Nat := natBitLenLoop n 0 -/-- Left-to-right binary squaring loop processing bits `i - 1` down to `0` (`@borrowed base`). -/ +/-- Left-to-right binary squaring loop processing bits `i - 1` down to `0` (`@[borrowed] base`). -/ def powLoop (base : Array UInt64) (exp : Nat) : Nat → Array UInt64 → Array UInt64 | 0, acc => acc | i + 1, acc => @@ -276,7 +276,7 @@ def powLoop (base : Array UInt64) (exp : Nat) : Nat → Array UInt64 → Array U let next := if ((exp >>> i) &&& 1) == 1 then mul sq base else sq powLoop base exp i next -/-- Multi-precision exponentiation by left-to-right binary squaring (`@borrowed base`). -/ +/-- Multi-precision exponentiation by left-to-right binary squaring (`@[borrowed] base`). -/ def pow (base : Array UInt64) (exp : Nat) : Array UInt64 := if exp == 0 then one else diff --git a/IxCC/IxCC/BigNat/Toom3.lean b/IxCC/IxCC/BigNat/Toom3.lean index ce1d57d4e7..c19d408cbe 100644 --- a/IxCC/IxCC/BigNat/Toom3.lean +++ b/IxCC/IxCC/BigNat/Toom3.lean @@ -22,7 +22,7 @@ squaring (`mulToom3`, `sqrToom3`): - No `Nat` literal `≥ 2^63` (`inv3_64` is built via 32-bit halves). - `toom3Interp` consumes freshly allocated evaluation results `r2` (and fresh intermediates `hi`, `lo`, `u`) linearly in place; `r0`, `r1`, `rm1`, `rInf` are - `@borrowed`. + `@[borrowed]`. ## References @@ -43,7 +43,7 @@ so no `Nat` literal `≥ 2^63` appears. -/ @[inline] def inv3_64 : UInt64 := ((0xAAAAAAAA : UInt64) <<< 32) ||| (0xAAAAAAAB : UInt64) -/-- Linear exact-division-by-3 loop (`@borrowed a`, `@unique acc`, structural recursion +/-- Linear exact-division-by-3 loop (`@[borrowed] a`, `@[unique] acc`, structural recursion on `rem`, 0 hardware `div`s). Maintains `carry ≤ 2`. -/ def divExact3Loop (a : Array UInt64) (i : Nat) (carry : UInt64) (acc : Array UInt64) : Nat → Array UInt64 @@ -55,7 +55,7 @@ def divExact3Loop (a : Array UInt64) (i : Nat) (carry : UInt64) (acc : Array UIn let carry' := if borrow then pHi + 1 else pHi divExact3Loop a (i + 1) carry' (acc.push q) rem -/-- Exact division by `3` (`@borrowed a`): whenever `3 ∣ toNat a`, returns canonical +/-- Exact division by `3` (`@[borrowed] a`): whenever `3 ∣ toNat a`, returns canonical `WF` quotient with `toNat (divExact3 a) * 3 = toNat a` (zero hardware `div`s). -/ def divExact3 (a : Array UInt64) : Array UInt64 := if a.size == 0 then #[] @@ -63,7 +63,7 @@ def divExact3 (a : Array UInt64) : Array UInt64 := /-! ### Signed Difference (`signedSub`) & Size Bounds -/ -/-- Return `(isNeg, |a - b|)` for canonical `a`, `b` (`@borrowed a`, `@borrowed b`), +/-- Return `(isNeg, |a - b|)` for canonical `a`, `b` (`@[borrowed] a`, `@[borrowed] b`), where `isNeg = true` iff `toNat a < toNat b`. -/ def signedSub (a b : Array UInt64) : Bool × Array UInt64 := match cmp a b with @@ -98,8 +98,8 @@ def toom3EvalLoop (a : Array UInt64) (k : Nat) (a0 a1 a2 : Array UInt64) : /-- In-place Karatsuba middle-term subtraction and shifted recombination `z0 + (z1Full - z0 - z2) * B^m + z2 * B^(2m)`, mutating freshly owned `z1Full` -in place and allocating a single `outSize`-limb output buffer (`@borrowed z0`, -`@borrowed z2`, `@unique z1Full`). -/ +in place and allocating a single `outSize`-limb output buffer (`@[borrowed] z0`, +`@[borrowed] z2`, `@[unique] z1Full`). -/ def karatsubaCombine (z0 z2 z1Full : Array UInt64) (m outSize : Nat) : Array UInt64 := let z1a := (subAtInPlace z1Full z0 0).1 let z1b := (subAtInPlace z1a z2 0).1 @@ -112,7 +112,7 @@ def karatsubaCombine (z0 z2 z1Full : Array UInt64) (m outSize : Nat) : Array UIn /-! ### Toom-3 In-Place Recombination & 5-Point Nonnegative Interpolation -/ /-- Tail-recursive shifted recombination loop adding `c1·B^k + c2·B^(2k) + c3·B^(3k) + c4·B^(4k)` -into `@unique acc` via a single `addAtInPlace` site (keeps ANF globals compact). -/ +into `@[unique] acc` via a single `addAtInPlace` site (keeps ANF globals compact). -/ def toom3CombineLoop (c1 c2 c3 c4 : Array UInt64) (k : Nat) (acc : Array UInt64) : Nat → Array UInt64 | 0 => normalize acc @@ -125,12 +125,12 @@ def toom3CombineLoop (c1 c2 c3 c4 : Array UInt64) (k : Nat) (acc : Array UInt64) toom3CombineLoop c1 c2 c3 c4 k (addAtInPlace acc term (mult * k)) step /-- Recombine the 5 Toom-3 coefficients `c0 + c1·B^k + c2·B^(2k) + c3·B^(3k) + c4·B^(4k)` -into a single pre-sized buffer via in-place `addAtInPlace` (`@borrowed c0..c4`). -/ +into a single pre-sized buffer via in-place `addAtInPlace` (`@[borrowed] c0..c4`). -/ def toom3Combine (c0 c1 c2 c3 c4 : Array UInt64) (k outSize : Nat) : Array UInt64 := toom3CombineLoop c1 c2 c3 c4 k (copyIntoZeros c0 outSize) 4 /-- Tail-recursive in-place linear subtraction loop subtracting up to 3 scaled terms from -`@unique acc` and normalizing (single `subAtInPlace` + single `subMul1InPlace` site). -/ +`@[unique] acc` and normalizing (single `subAtInPlace` + single `subMul1InPlace` site). -/ def subMul3Loop (a b c : Array UInt64) (m1 m2 m3 : UInt64) (acc : Array UInt64) : Nat → Array UInt64 | 0 => normalize acc @@ -146,11 +146,11 @@ def subMul3Loop (a b c : Array UInt64) (m1 m2 m3 : UInt64) (acc : Array UInt64) subMul3Loop a b c m1 m2 m3 next step /-- Exact 5-point Toom-3 interpolation over `{0, 1, -1, 2, ∞}`: -- `r0 = C(0) = c0` (`@borrowed`) -- `r1 = C(1) = c0 + c1 + c2 + c3 + c4` (`@borrowed`) -- `rm1 = |C(-1)|` with sign `rm1Neg` (`@borrowed`) -- `r2 = C(2) = c0 + 2·c1 + 4·c2 + 8·c3 + 16·c4` (`@unique`, mutated in place!) -- `rInf = C(∞) = c4` (`@borrowed`) +- `r0 = C(0) = c0` (`@[borrowed]`) +- `r1 = C(1) = c0 + c1 + c2 + c3 + c4` (`@[borrowed]`) +- `rm1 = |C(-1)|` with sign `rm1Neg` (`@[borrowed]`) +- `r2 = C(2) = c0 + 2·c1 + 4·c2 + 8·c3 + 16·c4` (`@[unique]`, mutated in place!) +- `rInf = C(∞) = c4` (`@[borrowed]`) Every intermediate (`hi, lo, c2, u, diff3, c3, c1`) is nonnegative (`≥ 0`), avoiding signed limb arithmetic completely. -/ diff --git a/IxCC/IxCC/Cfg/Rc/Layout.lean b/IxCC/IxCC/Cfg/Rc/Layout.lean index 31061fbc58..e5a924ed12 100644 --- a/IxCC/IxCC/Cfg/Rc/Layout.lean +++ b/IxCC/IxCC/Cfg/Rc/Layout.lean @@ -94,7 +94,7 @@ def mkResetWrapper (isUniqueProc incProc decProc : Nat) (lay : Rt.Rc.CellLayout) results := 1 blocks := ([b0, b1] ++ uniqueDecBlocks ++ [bUniqueRet] ++ sharedIncBlocks ++ [bSharedRet]).toArray } -/-- Static `@unique` `reset` wrapper: unconditional in-place `resetShell` rewrite without `isUnique` +/-- Static `@[unique]` `reset` wrapper: unconditional in-place `resetShell` rewrite without `isUnique` or a shared fallback path. -/ def mkResetUWrapper (decProc : Nat) (lay : Rt.Rc.CellLayout) (cls : Nat) : Lir.Func := let n := lay.nobj @@ -142,7 +142,7 @@ def mkReuseWrapper (allocProc : Nat) (lay : Rt.Rc.CellLayout) (cls : Nat) : Lir. { body := reuseStores.toArray, term := .ret [.v 0] }, { body := allocStores.toArray, term := .ret [.v (n + 1)], cold := true }] } -/-- Static `@unique` `reuse` wrapper: unconditional in-place `writeCell` (zero branch, zero alloc). -/ +/-- Static `@[unique]` `reuse` wrapper: unconditional in-place `writeCell` (zero branch, zero alloc). -/ def mkReuseUWrapper (lay : Rt.Rc.CellLayout) (cls : Nat) : Lir.Func := let n := lay.nobj let hdr := Rt.Rc.dynamicHeader n cls lay.tag 1 diff --git a/IxCC/IxCC/Cfg/Rc/Proof/InlineReuseSites.lean b/IxCC/IxCC/Cfg/Rc/Proof/InlineReuseSites.lean index 8451a8ef10..b631892e42 100644 --- a/IxCC/IxCC/Cfg/Rc/Proof/InlineReuseSites.lean +++ b/IxCC/IxCC/Cfg/Rc/Proof/InlineReuseSites.lean @@ -3274,7 +3274,7 @@ theorem inl_resetU_prefix {l : Layout} {raw : Lir.Program} fun r hr => (hagD r (by dsimp only [Lir.VReg] at hr ⊢; have := hcp.tmpGe; omega)).symm, hx', fun i hi => by rw [hvalsD i hi, hdeadGet i hi]⟩ -/-- Helper: fused static `@unique` `resetU` + `reuseU` inlined execution (0 extra blocks, 0 ticks). -/ +/-- Helper: fused static `@[unique]` `resetU` + `reuseU` inlined execution (0 extra blocks, 0 ticks). -/ theorem inl_fusedResetUReuseU_exec {l : Layout} {raw : Lir.Program} {F : Lir.Func} {B : Lir.Block} {fr : Lir.Frame} {rest : List Lir.Frame} {mem mem' : X86.Memory} {ctx : Lir.Word} {b rawPos tmp : Nat} {params : List Lir.VReg} @@ -4117,7 +4117,7 @@ theorem exec_fusedResetU1_join {p : Lir.Program} {F' : Lir.Func} {joinBlk : Lir. simpa using hwrStar exact hwrStar'.trans (.free sAsn1 (.free sAsn2 (.refl _))) -/-- Helper: fused static `@unique` 1-dead-field `resetU` + `reuseU` inlined execution +/-- Helper: fused static `@[unique]` 1-dead-field `resetU` + `reuseU` inlined execution (hot immediate dead field skips shell+dec; cold pointer dead field writes shell and calls `decProc`). -/ theorem inl_fusedResetUReuseU1_exec {l : Layout} {raw : Lir.Program} (hr : RuntimeFuncs l raw) {F : Lir.Func} {B : Lir.Block} {fr : Lir.Frame} {rest : List Lir.Frame} diff --git a/IxCC/IxCC/Cfg/Rc/Proof/Physical/EntryActivation.lean b/IxCC/IxCC/Cfg/Rc/Proof/Physical/EntryActivation.lean index 40b54e1055..26c4c4cd0d 100644 --- a/IxCC/IxCC/Cfg/Rc/Proof/Physical/EntryActivation.lean +++ b/IxCC/IxCC/Cfg/Rc/Proof/Physical/EntryActivation.lean @@ -35,7 +35,7 @@ theorem checked_owned_body {F : Fir.Program} {bodies : Src.NatMap Own.Plain.Code exact scope /-- Actual checked entry constructs the complete source/native activation over the typing -context, including `@borrowed`, `@unique`, and `priv` isolation invariants. All register-name +context, including `@[borrowed]`, `@[unique]`, and `priv` isolation invariants. All register-name bounds, the body, its scope and the entry layout come from admission; the arguments' denotation, counts, reachability, uniqueness, and words are the caller's concrete state. -/ theorem entry_activation {config : Rt.Config} {F : Fir.Program} diff --git a/IxCC/IxCC/Cfg/Rc/Proof/Physical/ScalarTail.lean b/IxCC/IxCC/Cfg/Rc/Proof/Physical/ScalarTail.lean index 612f179d45..cc12b6a132 100644 --- a/IxCC/IxCC/Cfg/Rc/Proof/Physical/ScalarTail.lean +++ b/IxCC/IxCC/Cfg/Rc/Proof/Physical/ScalarTail.lean @@ -20,7 +20,7 @@ import IxCC.Rt.Rc.Proof.SuccessTransport /-! # General Scalar-Tail Constructor Readiness (`CtorInfo.nscalar ≥ 0`) Generalizes physical allocation, payload publication, constructor-table invariants (`ScalarHeapCtorOk`), -release (`Gen.dec`), `@unique` in-place reuse (`Gen.inPlace_ready`), and header/word readback to +release (`Gen.dec`), `@[unique]` in-place reuse (`Gen.inPlace_ready`), and header/word readback to arbitrary `Rt.Rc.CellLayout`s with `nscalar ≥ 0`, including: * 1-scalar-word boxed `UInt64` cells (`⟨nobj := 0, nscalar := 1, tag := 0⟩`, `word-w2`'s `wordBoxCtor`), * mixed object+scalar-tail cells (`nobj > 0, nscalar > 0`), and @@ -668,7 +668,7 @@ theorem ScalarHeapCtorOk.reuseCell {tables : Rt.Lower.Tables} {H : Heap} · rw [ite_eq_right hlk] at hcell exact before k refs mode body hcell -/-! ## Release, `@unique` in-place reuse, and `word-w2` readback compatibility -/ +/-! ## Release, `@[unique]` in-place reuse, and `word-w2` readback compatibility -/ /-- Releasing a live scalar-tail cell via `Rt.Rc.Gen.dec` executes completely, recycles it onto its class free list without scanning any scalar tail word, and preserves both `Gen.AllocatorReady` @@ -694,7 +694,7 @@ theorem scalar_cell_release_ready {tables : Rt.Lower.Tables} ready.release_caller_ready word hw P decProc hdec caller callers hdsts exact ⟨H', mem', slots', lists', charges, hdrop, hcok.dropAll H [value] hdrop, hready', htrace⟩ -/-- Static `@unique` in-place `Gen.writeCell` reuse for general scalar-tail constructors (`nscalar ≥ 0`, +/-- Static `@[unique]` in-place `Gen.writeCell` reuse for general scalar-tail constructors (`nscalar ≥ 0`, including boxed `UInt64` updates and mixed object+scalar FBIP rewrites) preserves both `Gen.AllocatorReady` and `ScalarHeapCtorOk`. -/ theorem scalar_inPlace_reuse_ready {tables : Rt.Lower.Tables} diff --git a/IxCC/IxCC/Own/Plain/Certificate.lean b/IxCC/IxCC/Own/Plain/Certificate.lean index 7bf04f3fe8..5fc03e71e9 100644 --- a/IxCC/IxCC/Own/Plain/Certificate.lean +++ b/IxCC/IxCC/Own/Plain/Certificate.lean @@ -348,8 +348,8 @@ def checkRefusal (domain : Bool) (F : Fir.Program) (bodies : Src.NatMap Code) /-- **Certificate admission.** The program must be within the parameter total (checked first, from the program alone), the decoded map within the captured-work budget (linear), and the map accepted -by the ownership checker, which judges any placement of `inc`/`dec`, `@borrowed`, `reset`/`reuse`, -and `@unique` signatures (`Own.Plain.checkOwned`). -/ +by the ownership checker, which judges any placement of `inc`/`dec`, `@[borrowed]`, `reset`/`reuse`, +and `@[unique]` signatures (`Own.Plain.checkOwned`). -/ def admit (F : Fir.Program) (j : Json) (budget : Nat := Anf.maxCapturedWork) (params : Nat := Anf.maxParamTotal) : Except String Program := do checkParamTotal params F diff --git a/IxCC/IxCC/Own/Plain/Live.lean b/IxCC/IxCC/Own/Plain/Live.lean index 7df0ef9ee2..aa2650b512 100644 --- a/IxCC/IxCC/Own/Plain/Live.lean +++ b/IxCC/IxCC/Own/Plain/Live.lean @@ -727,9 +727,9 @@ def mapWithKeyAux {α β : Type} (f : Nat → α → β) : Nat → Nat → Src.N | k, w, .node v z o => .node (v.map (f k)) (mapWithKeyAux f k (2 * w) z) (mapWithKeyAux f (k + w) (2 * w) o) -/-! ## Track A4: Interprocedural `@unique` inference and FBIP `reset`/`reuse` placement -/ +/-! ## Track A4: Interprocedural `@[unique]` inference and FBIP `reset`/`reuse` placement -/ -/-- Clear param `idx`'s `@unique` flag for function `f` in `uniqs`. -/ +/-- Clear param `idx`'s `@[unique]` flag for function `f` in `uniqs`. -/ def clearParamUniq (uniqs : UniqSigs) (f idx : Nat) : UniqSigs × Bool := match uniqs.get? f with | none => (uniqs, false) @@ -745,7 +745,7 @@ def clearRetUniq (uniqs : UniqSigs) (f : Nat) : UniqSigs × Bool := | some (us, retU) => if retU then (uniqs.insert f (us, false), true) else (uniqs, false) -/-- Check call/tcall arguments against callee `g`'s `@unique` parameter mask, clearing any +/-- Check call/tcall arguments against callee `g`'s `@[unique]` parameter mask, clearing any position that is not guaranteed uniquely moved (or immediate). Returns `(uniqs', changed, uniqVarsAfter)`. -/ def checkCallArgsUniq (borrows : BorrowSigs) (g : FunId) (imm uniq : VSet) (keepAlive : VSet) (args : List Arg) (st : UniqSigs × Bool) : UniqSigs × Bool × VSet := @@ -771,7 +771,7 @@ def checkCallArgsUniq (borrows : BorrowSigs) (g : FunId) (imm uniq : VSet) (st'.1, st'.2, uniq') mutual -/-- One pass over annotated `ACode` refining `uniqs` (`@unique` params and `retUnique`). -/ +/-- One pass over annotated `ACode` refining `uniqs` (`@[unique]` params and `retUnique`). -/ def refineUniqCode (borrows : BorrowSigs) (f : FunId) (imm uniq : VSet) (st : UniqSigs × Bool) : ACode → UniqSigs × Bool | .bind x r k liveK => @@ -868,8 +868,8 @@ def uniqFixLoop (F : Fir.Program) (borrows : BorrowSigs) (annotated : Src.NatMap let (uniqs', changed) := refineUniqPass F borrows annotated uniqs if changed then uniqFixLoop F borrows annotated fuel uniqs' else uniqs' -/-- Total fuel-bounded interprocedural `@unique` parameter and return uniqueness inference. -Exported functions never assume `@unique` parameters; `@borrowed` parameters are never `@unique`. -/ +/-- Total fuel-bounded interprocedural `@[unique]` parameter and return uniqueness inference. +Exported functions never assume `@[unique]` parameters; `@[borrowed]` parameters are never `@[unique]`. -/ def inferUniqs (F : Fir.Program) (borrows : BorrowSigs) (annotated : Src.NatMap ACode) : UniqSigs := let expSet := VSet.ofVars F.exports let init : UniqSigs := (List.range F.size).foldl (fun m f => @@ -1336,7 +1336,7 @@ end def sinkResets (c : Code) : Code := (sinkResetsAux c (slotBound c)).1 -/-- Place `inc`/`dec`, `@borrowed`, `reset`/`reuse`/`dropSlot`, and static `@unique` on one body. -/ +/-- Place `inc`/`dec`, `@[borrowed]`, `reset`/`reuse`/`dropSlot`, and static `@[unique]` on one body. -/ def liveBodyFull (ctors : List Lam.CtorInfo) (known : Lam.Known) (borrows : BorrowSigs) (uniqs : UniqSigs) (selfBorrows selfUniqs : List Bool) (params : List Var) (ab : ACode) (lb : VSet) : Code := let owned := VSet.ofVars (Ctx.entryOwned params selfBorrows) @@ -1347,8 +1347,8 @@ def liveBodyFull (ctors : List Lam.CtorInfo) (known : Lam.Known) (borrows : Borr let uniq' := VSet.inter uniq owned' sinkResets (actionPrefix (decs dead) (placeFbip ctors known borrows uniqs .leaf owned' .leaf pbrw uniq' [] 0 ab).1) -/-- Full Track A3+A4 ownership producer: liveness + interprocedural `@borrowed` + interprocedural -`@unique` + FBIP `reset`/`reuse` placement. -/ +/-- Full Track A3+A4 ownership producer: liveness + interprocedural `@[borrowed]` + interprocedural +`@[unique]` + FBIP `reset`/`reuse` placement. -/ def liveMapFull (F : Fir.Program) : Src.NatMap Code × BorrowSigs × UniqSigs := let borrows := inferBorrows F let annotatedPairs : Src.NatMap (ACode × VSet) := F.funs.map fun fd => annotate .leaf fd.body diff --git a/IxCC/IxCC/Own/Plain/Owned.lean b/IxCC/IxCC/Own/Plain/Owned.lean index d5e6648561..d400073f21 100644 --- a/IxCC/IxCC/Own/Plain/Owned.lean +++ b/IxCC/IxCC/Own/Plain/Owned.lean @@ -63,7 +63,7 @@ def ctor0Valid (ctors : List Lam.CtorInfo) (c : Fir.CtorInfo) : Bool := | none => true /-- One path's ownership context. `total` is the sum of `own` (kept so that terminals cost O(1)). -`pbrw` holds caller-backed function-lifetime borrowed variables (parameters marked `@borrowed` +`pbrw` holds caller-backed function-lifetime borrowed variables (parameters marked `@[borrowed]` and variables projected or copied from them); unlike epoch-scoped `brw`, `pbrw` survives releases and calls for the lifetime of the activation. `ctorOf` records known constructor keys from enclosing `case` arms; `projOf` records projections @@ -108,7 +108,7 @@ def setImm (Γ : Ctx) (x : Var) : Ctx := uniq := Γ.uniq.erase x, total := Γ.total - Γ.tokens x } /-- `x` is a table-valid immediate (literal, erased, prim/bool, or valid 0-arity ctor), -safe to pass to `@unique` parameters and return from `@unique` functions. -/ +safe to pass to `@[unique]` parameters and return from `@[unique]` functions. -/ def setImmUniq (Γ : Ctx) (x : Var) : Ctx := { Γ.setImm x with uniq := Γ.uniq.insert x } @@ -156,7 +156,7 @@ def takeOwnedArgs : Ctx → List Bool → List Arg → Except String Ctx | Γ, false :: bs, a :: as => do takeOwnedArgs (← Γ.takeArg a) bs as | Γ, [], a :: as => do takeOwnedArgs (← Γ.takeArg a) [] as -/-- Consume tokens for non-borrowed (`false`) argument positions, verifying `@unique` positions +/-- Consume tokens for non-borrowed (`false`) argument positions, verifying `@[unique]` positions hold a statically unique value (`isUniq`) at the moment they are consumed. -/ def takeOwnedUniqueArgs : Ctx → List Bool → List Bool → List Arg → Except String Ctx | Γ, _, _, [] => .ok Γ @@ -166,7 +166,7 @@ def takeOwnedUniqueArgs : Ctx → List Bool → List Bool → List Arg → Excep match a with | .var x => unless Γ.isUniq x do - throw s!"v{x} passed to @unique parameter is not statically unique" + throw s!"v{x} passed to @[unique] parameter is not statically unique" takeOwnedUniqueArgs (← Γ.take x) bs us as | _ => takeOwnedUniqueArgs Γ bs us as | Γ, false :: bs, false :: us, a :: as => do @@ -177,7 +177,7 @@ def takeOwnedUniqueArgs : Ctx → List Bool → List Bool → List Arg → Excep match a with | .var x => unless Γ.isUniq x do - throw s!"v{x} passed to @unique parameter is not statically unique" + throw s!"v{x} passed to @[unique] parameter is not statically unique" takeOwnedUniqueArgs (← Γ.take x) [] us as | _ => takeOwnedUniqueArgs Γ [] us as | Γ, [], false :: us, a :: as => do @@ -374,14 +374,14 @@ def entryOwned : List Var → List Bool → List Var | _ :: ps, true :: bs => entryOwned ps bs | ps, [] => ps -/-- Borrowed parameters selected by borrow mask `bs` (`true` = `@borrowed`). -/ +/-- Borrowed parameters selected by borrow mask `bs` (`true` = `@[borrowed]`). -/ def entryBorrowed : List Var → List Bool → List Var | [], _ => [] | p :: ps, true :: bs => p :: entryBorrowed ps bs | _ :: ps, false :: bs => entryBorrowed ps bs | _, [] => [] -/-- Unique parameters selected by `(borrows, uniqs)`: owned and marked `@unique`. -/ +/-- Unique parameters selected by `(borrows, uniqs)`: owned and marked `@[unique]`. -/ def entryUnique : List Var → List Bool → List Bool → List Var | [], _, _ => [] | _ :: ps, true :: bs, _ :: us => entryUnique ps bs us @@ -556,14 +556,14 @@ def checkCode (Δ : JCtx) (Γ : Ctx) (c : Code) (borrows : BorrowSigs := .leaf) match a with | .var y => unless Γ.isUniq y do - throw s!"return v{y}: not statically unique for @unique return" + throw s!"return v{y}: not statically unique for @[unique] return" | _ => pure () (← Γ.takeArg a).closed "return" | .tcall f args => do let bs := borrows.getD f [] let (us, calleeRetU) := uniqs.getD f ([], false) if retUniq && !calleeRetU then - throw s!"tail call of f{f}: callee does not guarantee @unique return" + throw s!"tail call of f{f}: callee does not guarantee @[unique] return" let Γ₁ ← Γ.takeOwnedUniqueArgs bs us args Γ₁.checkTailBorrowed bs args Γ₁.closed s!"tail call of f{f}" @@ -626,9 +626,9 @@ def borrowsValid (F : Fir.Program) (borrows : BorrowSigs) : Bool := | _, none => true | none, some _ => false -/-- Validate per-function uniqueness signatures: exported entry points never assume `@unique` +/-- Validate per-function uniqueness signatures: exported entry points never assume `@[unique]` parameters (external ABI), every declared mask matches arity, and no parameter is both -`@borrowed` and `@unique`. -/ +`@[borrowed]` and `@[unique]`. -/ def uniqsValid (F : Fir.Program) (borrows : BorrowSigs) (uniqs : UniqSigs) : Bool := F.exports.all (fun f => ((uniqs.getD f ([], false)).1).all (!·)) && (List.range F.size).all fun f => diff --git a/IxCC/IxCC/Own/Plain/Program.lean b/IxCC/IxCC/Own/Plain/Program.lean index 6a44fb5e32..c6c559f54c 100644 --- a/IxCC/IxCC/Own/Plain/Program.lean +++ b/IxCC/IxCC/Own/Plain/Program.lean @@ -2,7 +2,7 @@ import IxCC.Own.Plain.Syntax namespace IxCC.Own.Plain -/-- Per-function parameter borrow masks (`true` = `@borrowed`, `false` = owned). -/ +/-- Per-function parameter borrow masks (`true` = `@[borrowed]`, `false` = owned). -/ abbrev BorrowSigs := Src.NatMap (List Bool) /-- Per-function static uniqueness signatures: `(paramUniqueMask, resultUnique)`. -/ diff --git a/IxCC/IxCC/Own/Plain/Proof/Owned/Actions.lean b/IxCC/IxCC/Own/Plain/Proof/Owned/Actions.lean index c57ce5c9ba..b73c0b529d 100644 --- a/IxCC/IxCC/Own/Plain/Proof/Owned/Actions.lean +++ b/IxCC/IxCC/Own/Plain/Proof/Owned/Actions.lean @@ -5,7 +5,7 @@ import IxCC.Own.Plain.Proof.Owned.Binds `inc x 1` adds a token: `inc_root` (owned: the token's own count; borrowed: the projected cell's live edge, kept as `BorrowVal`; immediate: a no-op). `dec x` takes one and is a release: `dropAll_retaining` keeps the value of every remaining token, nothing stays epoch-borrowed, and -surviving `@unique` variables, live reset slots, and `priv` locations stay untouched. -/ +surviving `@[unique]` variables, live reset slots, and `priv` locations stay untouched. -/ set_option autoImplicit false diff --git a/IxCC/IxCC/Own/Plain/Proof/Owned/Binds.lean b/IxCC/IxCC/Own/Plain/Proof/Owned/Binds.lean index cb32e72077..4c10bc4f69 100644 --- a/IxCC/IxCC/Own/Plain/Proof/Owned/Binds.lean +++ b/IxCC/IxCC/Own/Plain/Proof/Owned/Binds.lean @@ -80,7 +80,7 @@ theorem OwnedPre.toState (pre : OwnedPre functions H external live Γ ρf ρo ow pre.uniqOk, pre.rsetOk, pre.privBound, pre.privNoEdge, pre.privNoVar, pre.privNoSlot, pre.stack, pre.scope⟩ -/-- Locations owned uniquely by surviving `@unique` variables or live reset slots of `pre`. -/ +/-- Locations owned uniquely by surviving `@[unique]` variables or live reset slots of `pre`. -/ def OwnedPre.localPriv (pre : OwnedPre functions H external live Γ ρf ρo owned lex Δ Jf Jo borrows uniqs retUniq ctors K priv slots slotVals) (l : Nat) : Prop := priv l ∨ diff --git a/IxCC/IxCC/Own/Plain/Proof/Owned/Program.lean b/IxCC/IxCC/Own/Plain/Proof/Owned/Program.lean index 6fd44891ab..b311f1aec4 100644 --- a/IxCC/IxCC/Own/Plain/Proof/Owned/Program.lean +++ b/IxCC/IxCC/Own/Plain/Proof/Owned/Program.lean @@ -6,7 +6,7 @@ import IxCC.Own.Rc.Proof.LeakFreedom `checkContractOwned_refines` and `checkOwned_refines` have exactly the conclusions of the landed `checked_contract_program_refines` and `checked_program_refines`; their premise is the ownership -checker instead of equality with the canonical producer's map. Full `@borrowed` + `@unique` + +checker instead of equality with the canonical producer's map. Full `@[borrowed]` + `@[unique]` + `reset`/`reuse` programs are handled by `checkOwnedFull_export_refines` and `checkOwnedFull_export_reclaims`. Reclamation follows from refinement and the producer-independent heap-shape theorem (`call_heap_shape`), as it does today. -/ @@ -214,7 +214,7 @@ theorem checkContractOwnedFull_parts {F : Fir.Program} {candidate : Src.NatMap C simp only [checkContractOwned, Bool.and_eq_true] at h exact ⟨h.1.1.1.1, h.1.1.1.2, h.1.1.2, h.1.2, checkMapE_ok (except_isOk h.2)⟩ -/-- What the checker established (with arbitrary borrow masks, zero `@unique` signatures). -/ +/-- What the checker established (with arbitrary borrow masks, zero `@[unique]` signatures). -/ theorem checkContractOwnedWith_parts {F : Fir.Program} {candidate : Src.NatMap Code} {borrows : BorrowSigs} (h : checkContractOwned F candidate borrows = true) : contractProgramDomain F = true ∧ checkBoolPins F = true ∧ borrowsValid F borrows = true ∧ @@ -233,7 +233,7 @@ theorem checkContractOwned_parts {F : Fir.Program} {candidate : Src.NatMap Code} exact ⟨d, p, fun f fd hf hfd => by simpa [Src.NatMap.getD, Src.NatMap.get?, Ctx.entryWith_all_false _ [] rfl] using b f fd hf hfd⟩ -/-- **The milestone-1 induction**, for an accepted map (with arbitrary `@borrowed` and `@unique` masks). -/ +/-- **The milestone-1 induction**, for an accepted map (with arbitrary `@[borrowed]` and `@[unique]` masks). -/ theorem owned_refines {F : Fir.Program} {candidate : Src.NatMap Code} {borrows : BorrowSigs} {uniqs : UniqSigs} (checked : checkContractOwned F candidate borrows uniqs = true) : @@ -241,7 +241,7 @@ theorem owned_refines {F : Fir.Program} {candidate : Src.NatMap Code} obtain ⟨domain, pins, _, _, bodies⟩ := checkContractOwnedFull_parts checked exact owned_refines_of domain (checkBoolPins_sound pins) bodies -/-- **An accepted map with `@borrowed` and `@unique` signatures refines Fir's `evalCall`**. -/ +/-- **An accepted map with `@[borrowed]` and `@[unique]` signatures refines Fir's `evalCall`**. -/ theorem checkContractOwnedFull_refines {F : Fir.Program} {candidate : Src.NatMap Code} {borrows : BorrowSigs} {uniqs : UniqSigs} (checked : checkContractOwned F candidate borrows uniqs = true) (k : Nat) @@ -269,7 +269,7 @@ theorem checkOwnedFull_refines {F : Fir.Program} {candidate : Src.NatMap Code} (evalCall { source := F, bodies := candidate, borrows, uniqs } k f vs H) := checkContractOwnedFull_refines (checkOwned_contract checked) k hf hd hb hbrw huniq -/-- Exported entry points own all arguments and assume zero `@unique` preconditions +/-- Exported entry points own all arguments and assume zero `@[unique]` preconditions (`borrowsValid` + `uniqsValid`), so external calls refine unconditionally. -/ theorem checkOwnedFull_export_refines {F : Fir.Program} {candidate : Src.NatMap Code} {borrows : BorrowSigs} {uniqs : UniqSigs} @@ -287,7 +287,7 @@ theorem checkOwnedFull_export_refines {F : Fir.Program} {candidate : Src.NatMap (fun _ hm => by rw [selectBorrowedVals_all_false _ _ hallB] at hm; cases hm) (fun _ hm => by rw [selectUniqueVals_all_false _ _ _ hallU] at hm; cases hm) -/-- **Reclamation for accepted maps with `@borrowed`, `@unique`, and `reset`/`reuse`** at any +/-- **Reclamation for accepted maps with `@[borrowed]`, `@[unique]`, and `reset`/`reuse`** at any exported root. -/ theorem checkOwnedFull_export_reclaims {F : Fir.Program} {candidate : Src.NatMap Code} {borrows : BorrowSigs} {uniqs : UniqSigs} @@ -308,7 +308,7 @@ theorem checkOwnedFull_export_reclaims {F : Fir.Program} {candidate : Src.NatMap obtain ⟨released, dropped, dead⟩ := dropAll_reclaims heapShape balance exact ⟨v, after, released, success, den, dropped, dead⟩ -/-- **An accepted map with `@borrowed` signatures refines Fir's `evalCall`**. -/ +/-- **An accepted map with `@[borrowed]` signatures refines Fir's `evalCall`**. -/ theorem checkContractOwnedWith_refines {F : Fir.Program} {candidate : Src.NatMap Code} {borrows : BorrowSigs} (checked : checkContractOwned F candidate borrows = true) (k : Nat) {f : Fir.FunId} (hf : f < F.size) {H : Heap} {external : Nat → Nat} @@ -341,7 +341,7 @@ theorem checkOwnedWith_export_refines {F : Fir.Program} {candidate : Src.NatMap (evalCall { source := F, bodies := candidate, borrows } k f vs H) := checkOwnedFull_export_refines checked k hf hexp hd hb -/-- **Reclamation for accepted maps with `@borrowed` signatures** at any exported root. -/ +/-- **Reclamation for accepted maps with `@[borrowed]` signatures** at any exported root. -/ theorem checkOwnedWith_export_reclaims {F : Fir.Program} {candidate : Src.NatMap Code} {borrows : BorrowSigs} (checked : checkOwned F candidate borrows = true) (k : Nat) {f : Fir.FunId} (hf : f < F.size) (hexp : f ∈ F.exports) {H : Heap} diff --git a/IxCC/IxCC/Own/Plain/Proof/Owned/Reach.lean b/IxCC/IxCC/Own/Plain/Proof/Owned/Reach.lean index 73d282d6f8..889fdaf51e 100644 --- a/IxCC/IxCC/Own/Plain/Proof/Owned/Reach.lean +++ b/IxCC/IxCC/Own/Plain/Proof/Owned/Reach.lean @@ -583,7 +583,7 @@ theorem reuseShell {H H' : Heap} {l : Nat} {b b' : Body} {r v : RVal} end BorrowVal -/-- A table-valid immediate value: safe to pass to `@unique` parameters and return from `@unique` +/-- A table-valid immediate value: safe to pass to `@[unique]` parameters and return from `@[unique]` functions without colliding with any positive-arity constructor key. -/ def ImmUniq (ctors : List Lam.CtorInfo) (v : RVal) : Prop := ImmVal v ∧ diff --git a/IxCC/IxCC/Own/Plain/Proof/Owned/Simulation.lean b/IxCC/IxCC/Own/Plain/Proof/Owned/Simulation.lean index 3ea6ff2d0c..94ff9300e9 100644 --- a/IxCC/IxCC/Own/Plain/Proof/Owned/Simulation.lean +++ b/IxCC/IxCC/Own/Plain/Proof/Owned/Simulation.lean @@ -11,8 +11,8 @@ import IxCC.Fir.Proof.Unfold `owned_eval` inducts on the **Own** code (`inc`, `dec`, `reset`, and `dropSlot` stutter at the source clock, while `reuse` refines `bind x (.ctor ..)`), with the source code its erasure, under the lexicographic clock / code-and-join-stack measure of `Own.Plain.eval`. Calls and charged jumps -use the hypothesis at smaller clocks (`AtClockOwned`), threading caller-backed `@borrowed` -reachability, `@unique` parameter/return uniqueness, live reset slots, and caller-frame `priv` +use the hypothesis at smaller clocks (`AtClockOwned`), threading caller-backed `@[borrowed]` +reachability, `@[unique]` parameter/return uniqueness, live reset slots, and caller-frame `priv` isolation. -/ set_option autoImplicit false @@ -165,7 +165,7 @@ private theorem bindAll_leaf_mem : · exact absurd hy' htail | _, _ :: _, [], hl, _, _, _, _ => by simp at hl -/-- Function entry with full `@borrowed`, `@unique`, and `priv` isolation invariants. -/ +/-- Function entry with full `@[borrowed]`, `@[unique]`, and `priv` isolation invariants. -/ theorem ownedState_entryFull_exact (functions : Signatures) (H : Heap) (external : Nat → Nat) (params : List Fir.Var) (bs us : List Bool) (vs : List RVal) (ws : List Fir.Val) (hd : Sem.Forall2 (Proof.Den H) vs ws) (hl : vs.length = params.length) @@ -881,7 +881,7 @@ end end -/-- **The milestone-1 induction** (generalised to arbitrary `@borrowed` and `@unique` signatures). -/ +/-- **The milestone-1 induction** (generalised to arbitrary `@[borrowed]` and `@[unique]` signatures). -/ theorem owned_refines_of {F : Fir.Program} {candidate : Src.NatMap Code} {borrows : BorrowSigs} {uniqs : UniqSigs} (domain : contractProgramDomain F = true) (pins : BoolPinsOk F) diff --git a/IxCC/IxCC/Own/Plain/Proof/Owned/Takes.lean b/IxCC/IxCC/Own/Plain/Proof/Owned/Takes.lean index cb8f98e378..04f7520d0b 100644 --- a/IxCC/IxCC/Own/Plain/Proof/Owned/Takes.lean +++ b/IxCC/IxCC/Own/Plain/Proof/Owned/Takes.lean @@ -6,7 +6,7 @@ import IxCC.Own.Plain.Proof.Owned.State (`takeArgs`) or of each captured variable (`takeVars`) yields the arguments' values, their denotations, and the remaining tokens, with the consumed values' references split off (`SameRefs owned (vs ++ owned')`, an immediate counting for nothing). `takeOwnedUniqueArgs_call_sem` -and `takeOwnedUniqueArgs_tail_sem` additionally verify `@borrowed` and `@unique` call arguments. -/ +and `takeOwnedUniqueArgs_tail_sem` additionally verify `@[borrowed]` and `@[unique]` call arguments. -/ set_option autoImplicit false @@ -236,7 +236,7 @@ def selectBorrowedVals (bs : List Bool) (vs : List RVal) : List RVal := | false :: bs => selectBorrowedVals bs vs termination_by structural vs -/-- Unique argument values selected by `(bs, us)` (owned and marked `@unique`). -/ +/-- Unique argument values selected by `(bs, us)` (owned and marked `@[unique]`). -/ def selectUniqueVals (bs us : List Bool) (vs : List RVal) : List RVal := match vs with | [] => [] @@ -855,7 +855,7 @@ theorem takeOwnedArgs_tail_sem {functions : Signatures} {H : Heap} {external : N have : u = v := Option.some.inj (hu.symm.trans hv); subst this exact hreach -/-- Full non-tail call argument checking with `@borrowed` and `@unique` annotations, slot roots, +/-- Full non-tail call argument checking with `@[borrowed]` and `@[unique]` annotations, slot roots, and private-frame preservation. -/ theorem takeOwnedUniqueArgs_call_sem {functions : Signatures} {H : Heap} {external : Nat → Nat} {live : List Var} {Γ Γ' : Ctx} {ρf : Fir.Env} {ρo : Own.Env} {owned : List RVal} @@ -966,7 +966,7 @@ theorem takeOwnedUniqueArgs_call_sem {functions : Signatures} {H : Heap} {extern simp only [refsIn_append, hs' l]; omega exact ⟨b, hc, by simp only [holdRoots]; omega, hedge, by omega⟩ -/-- Full tail-call argument checking with `@borrowed` and `@unique` annotations. -/ +/-- Full tail-call argument checking with `@[borrowed]` and `@[unique]` annotations. -/ theorem takeOwnedUniqueArgs_tail_sem {functions : Signatures} {H : Heap} {external : Nat → Nat} {live : List Var} {Γ Γ' : Ctx} {ρf : Fir.Env} {ρo : Own.Env} {owned : List RVal} {lex : Joins} {Δ : JCtx} {Jf : List Fir.JEntry} {Jo : List JEntry} diff --git a/IxCC/IxCC/Own/Plain/Proof/Results.lean b/IxCC/IxCC/Own/Plain/Proof/Results.lean index 29ab7bbc35..a53b53faa9 100644 --- a/IxCC/IxCC/Own/Plain/Proof/Results.lean +++ b/IxCC/IxCC/Own/Plain/Proof/Results.lean @@ -60,7 +60,7 @@ theorem ResultRel.success {before : Heap} {external : Nat → Nat} {w : Fir.Val} /-- Strengthened result relation used internally by `Owned.Simulation`: additionally tracks private-frame preservation (`PrivPreserved`), non-aliasing of the returned value against private -locations (`retNoPriv`), and `@unique` return guarantees (`UniqVal`). Projects directly to +locations (`retNoPriv`), and `@[unique]` return guarantees (`UniqVal`). Projects directly to `ResultRel`. -/ inductive ResultRelFull (before : Heap) (external : Nat → Nat) (priv : Nat → Prop) (ctors : List Lam.CtorInfo) (retUniq : Bool) : diff --git a/IxCC/IxCCTests/Fences/OwnBorrow.lean b/IxCC/IxCCTests/Fences/OwnBorrow.lean index 6622018d11..97f62fdedd 100644 --- a/IxCC/IxCCTests/Fences/OwnBorrow.lean +++ b/IxCC/IxCCTests/Fences/OwnBorrow.lean @@ -7,7 +7,7 @@ import IxCC.Cfg.Rc.Proof.Owned.Admission import IxCC.Cfg.Rc.Proof.Physical.PublicEntry import IxCC.Recheck.Rc.Proof.Replay -/-! Exact axiom fences for Track A3: interprocedural `@borrowed` parameters, +/-! Exact axiom fences for Track A3: interprocedural `@[borrowed]` parameters, `ReachablePreserved`, certificate v2 admission (`decodeWith` / `admit_of_with`), and physical simulation through `Cfg.Rc` and `Recheck.RcReplay`. -/ diff --git a/IxCC/IxCCTests/Fences/OwnReuse.lean b/IxCC/IxCCTests/Fences/OwnReuse.lean index 1db29e8164..5708204870 100644 --- a/IxCC/IxCCTests/Fences/OwnReuse.lean +++ b/IxCC/IxCCTests/Fences/OwnReuse.lean @@ -7,7 +7,7 @@ import IxCC.Cfg.Rc.Proof.Physical.ReuseWrappers import IxCC.Cfg.Rc.Proof.Physical.ReuseResult import IxCC.Recheck.Rc.Proof.ObjectSound -/-! Exact axiom fences for Track A4: dynamic `reset`/`reuse`, static `@unique` unconditional +/-! Exact axiom fences for Track A4: dynamic `reset`/`reuse`, static `@[unique]` unconditional in-place `writeCell` reuse, certificate v3 admission (`decodeFull` / `admit_of_full`), inline RC/reuse simulation, concrete LIR reuse wrapper execution, physical `reset`/`reuse`/`dropSlot` simulation, and end-to-end `Recheck.RcReplay.sound`. -/ diff --git a/IxCC/IxCCTests/Fences/RtRcScalarTail.lean b/IxCC/IxCCTests/Fences/RtRcScalarTail.lean index 390b98f26e..e506123819 100644 --- a/IxCC/IxCCTests/Fences/RtRcScalarTail.lean +++ b/IxCC/IxCCTests/Fences/RtRcScalarTail.lean @@ -1,7 +1,7 @@ import IxCC.Cfg.Rc.Proof.Physical.ScalarTail /-! Exact axiom fences for Deliverable 4: scalar-tail (`CtorInfo.nscalar ≥ 0`) physical allocation, -publication, constructor-table invariant (`ScalarHeapCtorOk`), release (`Gen.dec`), `@unique` +publication, constructor-table invariant (`ScalarHeapCtorOk`), release (`Gen.dec`), `@[unique]` in-place reuse (`Gen.inPlace_ready`), and `word-w2` readback compatibility. -/ /-- info: 'IxCC.Cfg.Rc.Native.unique_header_reads_gen' depends on axioms: [propext, Classical.choice, Quot.sound] -/ diff --git a/IxCC/IxCCTests/Own/Owned/Live.lean b/IxCC/IxCCTests/Own/Owned/Live.lean index 50cd6b89b3..4f47dcc4ea 100644 --- a/IxCC/IxCCTests/Own/Owned/Live.lean +++ b/IxCC/IxCCTests/Own/Owned/Live.lean @@ -178,7 +178,7 @@ def runChecks : Array String := Id.run do let cap := firstJoinCaptured body if cap != some (List.range n) then errs := errs.push s!"live-unit/largeStress({n}): expected sorted captures [0..{n-1}], got {repr cap}" - -- Track A3: `@borrowed` inference, certificate v2 round-trip, and negative UAF controls. + -- Track A3: `@[borrowed]` inference, certificate v2 round-trip, and negative UAF controls. -- f0 (exported) calls read-only helper f1(xs) which sums a cons-list via tail recursion. let f1 : Fir.Fun := { (default : Fir.Fun) with @@ -257,7 +257,7 @@ def runChecks : Array String := Id.run do size := 2, exports := [0], ctors := [], known := {} } if checkOwned badConsumeProg badConsume aliasBorrows then errs := errs.push "borrow-unit/neg-consume: returning borrowed param without inc was accepted" - -- Track A4: dynamic `reset`/`reuse`, static `@unique` unconditional reuse, certificate v3 + -- Track A4: dynamic `reset`/`reuse`, static `@[unique]` unconditional reuse, certificate v3 -- (`encodeFull`/`decodeFull`), and negative safety controls. -- Positive 1: dynamic `reset`/`reuse` on tail-recursive list reverse (`revAux`). let revAux : Fir.Fun := @@ -296,7 +296,7 @@ def runChecks : Array String := Id.run do if !bodyMapEq backM revBodies || !sameBorrow || !sameUniq || !checkOwned revProg backM backB backU then errs := errs.push "reuse-unit/rev-v3-cert: round trip differs" | .error e => errs := errs.push s!"reuse-unit/rev-v3-cert: decodeFull failed: {e}" - -- Positive 2: static `@unique` unconditional reuse (fresh cons passed to swapUniq). + -- Positive 2: static `@[unique]` unconditional reuse (fresh cons passed to swapUniq). let swapUniq : Fir.Fun := { (default : Fir.Fun) with params := [(0, .tobj)] @@ -440,10 +440,10 @@ def runChecks : Array String := Id.run do (.reuse 3 0 consInfo [.var 2, .var 1] false (.ret (.var 3))))) if checkOwned noCaseProg (Src.NatMap.ofList [(0, noCaseBody)]) then errs := errs.push "reuse-unit/neg-no-ctorof: reset without case-refined ctor identity was accepted" - -- Neg 7: exported function with `@unique` parameter in `UniqSigs` must be refused. + -- Neg 7: exported function with `@[unique]` parameter in `UniqSigs` must be refused. let expUniq : UniqSigs := Src.NatMap.ofList [(0, ([true], false))] if checkOwned badStaticProg (Src.NatMap.ofList [(0, dynSwapBody)]) .leaf expUniq then - errs := errs.push "reuse-unit/neg-export-uniq: exported @unique param was accepted" + errs := errs.push "reuse-unit/neg-export-uniq: exported @[unique] param was accepted" return errs end LiveTests diff --git a/IxCC/IxCCTests/Own/Strip.lean b/IxCC/IxCCTests/Own/Strip.lean index a7ee76d235..6142d40bfc 100644 --- a/IxCC/IxCCTests/Own/Strip.lean +++ b/IxCC/IxCCTests/Own/Strip.lean @@ -1,22 +1,22 @@ /-! # `strip-contracts`: the plain twin of an annotated source The ownership suite pairs each annotated Lean source with its plain twin. The twin is the annotated -text with ix's scoped `@`-prefixed mode syntax deleted, so the two differ by construction only in +text with ix's scoped `@[...]` mode syntax deleted, so the two differ by construction only in contracts: * the import of ix's elaborator (`import Ix.Compile.SourceContract.Elab`), `open scoped Ix.Modes`, and the blank line after them; -* binder and constructor/structure field prefix modes: one or more `@erased`, - `@once`, `@unique`, `@borrowed` or `@shared` keywords right after an opening - `(`, `{`, `[` or `⦃`, each followed by a space, before a binder name - (`(@erased _h : True)`, `{@erased α : Type}`, `(@unique @borrowed xs : List Nat)`, - `(@shared x : Nat)`); -* result and arrow modes: one or more `@erased`, `@once`, `@unique` or `@borrowed` - keywords right after `: `, `→ `, `-> ` or `, ` (after `∀ ...`), each followed by - a space, before a type (`: @unique List Nat`, `A → @borrowed B`); -* `let` mode prefixes: `let @borrow v : T := …` (or `let @unique x := …`, - `let @once @borrowed x : T := …`, etc.) becomes the ordinary `let v : T := …`; -* indented structure simple-field modes: `@shared f : T` or `@erased h : True` +* binder and constructor/structure field prefix modes: one or more `@[...]` blocks + containing comma-separated `erased`, `once`, `unique`, `borrowed`, or `shared` + keywords right after an opening `(`, `{`, `[` or `⦃`, followed by whitespace, + before a binder name (`(@[erased] _h : True)`, `{@[erased] α : Type}`, + `(@[unique, borrowed] xs : List Nat)`, `(@[shared] x : Nat)`); +* result and arrow modes: one or more `@[...]` blocks containing `erased`, `once`, + `unique`, or `borrowed` right after `: `, `→ `, `-> ` or `, ` (after `∀ ...`), + followed by whitespace, before a type (`: @[unique] List Nat`, `A → @[borrowed] B`); +* `let` mode prefixes: `let @[borrow] v : T := …` (or `let @[unique] x := …`, + `let @[once, borrowed] x : T := …`, etc.) becomes the ordinary `let v : T := …`; +* indented structure simple-field modes: `@[shared] f : T` or `@[erased] h : True` at the start of an indented field line becomes `f : T` / `h : True`. Comments and strings are not special-cased: the fixture sources keep their @@ -40,30 +40,69 @@ def isBinderStart (c : Char) : Bool := c.isAlpha || c == '_' || c.toNat ≥ 0x80 def isTypeStart (c : Char) : Bool := isBinderStart c || c == '(' || c == '{' || c == '[' || c == '⦃' -/-- Match one `@ ` prefix where `` is in `kws`, returning its character length. -/ -def matchModeKw (kws : List String) : List Char → Option Nat - | '@' :: rest => - kws.findSome? fun kw => - let kcs := kw.toList - if rest.take kcs.length == kcs && rest[kcs.length]? == some ' ' then - some (1 + kcs.length + 1) - else none - | _ => none +def skipSpaces : List Char → Nat × List Char + | ' ' :: rest => + let (n, tail) := skipSpaces rest + (n + 1, tail) + | '\t' :: rest => + let (n, tail) := skipSpaces rest + (n + 1, tail) + | cs => (0, cs) -/-- Total character length of one or more `@ ` prefixes at the front of `cs`, -when followed by a character satisfying `isFollow`. -/ -def modeRun (kws : List String) (isFollow : Char → Bool) (cs : List Char) : Option Nat := +/-- Match one keyword from `kws` at the front of `cs` (must end on non-identifier char). -/ +def matchKw (kws : List String) (cs : List Char) : Option (Nat × List Char) := + kws.findSome? fun kw => + let kcs := kw.toList + if cs.take kcs.length == kcs then + let after := cs.drop kcs.length + match after with + | c :: _ => if c.isAlphanum || c == '_' then none else some (kcs.length, after) + | [] => some (kcs.length, []) + else none + +/-- Match comma-separated keywords from `kws` until `]`, returning total chars consumed including `]`. -/ +def matchAttrBody (kws : List String) (cs : List Char) : Option (Nat × List Char) := go cs.length cs 0 where - go : Nat → List Char → Nat → Option Nat + go : Nat → List Char → Nat → Option (Nat × List Char) | 0, _, _ => none | fuel + 1, cur, acc => - match matchModeKw kws cur with - | some n => go fuel (cur.drop n) (acc + n) + let (sp1, cur1) := skipSpaces cur + match matchKw kws cur1 with + | none => none + | some (kn, cur2) => + let (sp2, cur3) := skipSpaces cur2 + let acc' := acc + sp1 + kn + sp2 + match cur3 with + | ',' :: rest => go fuel rest (acc' + 1) + | ']' :: rest => some (acc' + 1, rest) + | _ => none + +/-- Match one `@[kw, ...]` block followed by at least one space/tab, returning its character length. -/ +def matchModeAttr (kws : List String) : List Char → Option Nat + | '@' :: '[' :: rest => + match matchAttrBody kws rest with + | some (bodyLen, afterClose) => + let (sp, _) := skipSpaces afterClose + if sp > 0 then some (2 + bodyLen + sp) else none + | none => none + | _ => none + +/-- Total character length of optional leading spaces plus one or more `@[...]` blocks +at the front of `cs`, when followed by a character satisfying `isFollow`. -/ +def modeRun (kws : List String) (isFollow : Char → Bool) (cs : List Char) : Option Nat := + let (leadSp, cs0) := skipSpaces cs + go cs0.length cs0 leadSp false +where + go : Nat → List Char → Nat → Bool → Option Nat + | 0, _, _, _ => none + | fuel + 1, cur, acc, matched => + match matchModeAttr kws cur with + | some n => go fuel (cur.drop n) (acc + n) true | none => - if acc > 0 && (cur.head?.map isFollow).getD false then some acc else none + if matched && (cur.head?.map isFollow).getD false then some acc else none -/-- Delete the scoped `@`-mode syntax of one line. -/ +/-- Delete the scoped `@[...]` mode syntax of one line. -/ partial def stripLine (line : String) : String := String.ofList (go line.toList []) where @@ -112,27 +151,29 @@ def strip (src : String) : String := /-- Explicit output oracles, including ordinary syntax which must not change. -/ def regressionCases : List (String × String) := [ - ("def pick (@erased _h : True) (n : Nat) : Nat := n + 1", + ("def pick (@[erased] _h : True) (n : Nat) : Nat := n + 1", "def pick (_h : True) (n : Nat) : Nat := n + 1"), - ("def len {@erased α : Type} (xs : List α) : Nat := 0", + ("def len {@[erased] α : Type} (xs : List α) : Nat := 0", "def len {α : Type} (xs : List α) : Nat := 0"), - ("def localId (@borrowed x : Nat) : @borrowed Nat := x", + ("def localId (@[borrowed] x : Nat) : @[borrowed] Nat := x", "def localId (x : Nat) : Nat := x"), - ("def f (@unique @borrowed xs : List Nat) : @unique @borrowed (List Nat) := xs", + ("def f (@[unique, borrowed] xs : List Nat) : @[unique, borrowed] (List Nat) := xs", "def f (xs : List Nat) : (List Nat) := xs"), - ("def g (f : (@once x : Nat) → @unique Nat) : Nat -> @borrowed Nat := f", + ("def f2 (@[unique] @[borrowed] xs : List Nat) : @[unique] @[borrowed] (List Nat) := xs", + "def f2 (xs : List Nat) : (List Nat) := xs"), + ("def g (f : (@[once] x : Nat) → @[unique] Nat) : Nat -> @[borrowed] Nat := f", "def g (f : (x : Nat) → Nat) : Nat -> Nat := f"), - ("def h : ∀ (@unique x : Nat), @unique Nat := id", + ("def h : ∀ (@[unique] x : Nat), @[unique] Nat := id", "def h : ∀ (x : Nat), Nat := id"), - (" let @borrow v : List Nat := owner", + (" let @[borrow] v : List Nat := owner", " let v : List Nat := owner"), - (" let @borrow view := owner", + (" let @[borrow] view := owner", " let view := owner"), - (" let @unique @borrowed view : (List Nat) := xs", + (" let @[unique, borrowed] view : (List Nat) := xs", " let view : (List Nat) := xs"), - (" @shared payload : List Nat", + (" @[shared] payload : List Nat", " payload : List Nat"), - (" | node (@shared l : Tree) (@erased h : True) : Tree", + (" | node (@[shared] l : Tree) (@[erased] h : True) : Tree", " | node (l : Tree) (h : True) : Tree"), ("let (v : List Nat) := xs", "let (v : List Nat) := xs"), diff --git a/IxCC/IxCCTests/Pipeline/Compiler.lean b/IxCC/IxCCTests/Pipeline/Compiler.lean index b764cb57a6..156681e3a0 100644 --- a/IxCC/IxCCTests/Pipeline/Compiler.lean +++ b/IxCC/IxCCTests/Pipeline/Compiler.lean @@ -343,8 +343,8 @@ private def setLamContracts : List Ixon.V3.AllMode → Src.Term → Src.Term | c :: cs, .lam b d body => .lam { b with mode := c } d (setLamContracts cs body) | _, t => t -/-- Attach frontend binder modes (`@once` on `build`, `@unique` on `revAcc`, -`@borrowed` on `sumL`) to the `OS16-plain` +/-- Attach frontend binder modes (`@[once]` on `build`, `@[unique]` on `revAcc`, +`@[borrowed]` on `sumL`) to the `OS16-plain` heap closure (`build` + `revAcc` + `sumL`) in memory: every producer entry point refuses it (the kernel annotator's correspondence: its modes are not the bytes'); with the certificate of the base program's annotation, `Recheck.run`, diff --git a/IxCC/IxCCTests/Pipeline/Rc/Levels.lean b/IxCC/IxCCTests/Pipeline/Rc/Levels.lean index 373fbfee9e..8fa2bc0a27 100644 --- a/IxCC/IxCCTests/Pipeline/Rc/Levels.lean +++ b/IxCC/IxCCTests/Pipeline/Rc/Levels.lean @@ -115,7 +115,7 @@ private def buildMixedFun : Fir.Fun := none contracts := [.many, .once] } -/-- `sumL (@borrowed xs : List Nat) (acc : Nat)`: `xs` carries `.borrowed`, +/-- `sumL (@[borrowed] xs : List Nat) (acc : Nat)`: `xs` carries `.borrowed`, `acc` is unannotated `.many` scalar `Nat` threaded through a recursive join point. -/ private def sumBorrowedScalarFun : Fir.Fun := { key := .const 951 [] @@ -133,7 +133,7 @@ private def sumBorrowedScalarFun : Fir.Fun := result := .borrowed contracts := [.borrowed, .many] } -/-- `choose (b : Bool) (@unique xs : List Nat) (@unique ys : List Nat)`: `b` is unannotated +/-- `choose (b : Bool) (@[unique] xs : List Nat) (@[unique] ys : List Nat)`: `b` is unannotated `.many` scalar `Bool`, `xs` and `ys` carry `.unique`. -/ private def chooseBoolUniqueFun : Fir.Fun := { key := .const 952 [] @@ -145,7 +145,7 @@ private def chooseBoolUniqueFun : Fir.Fun := result := .unique contracts := [.many, .unique, .unique] } -/-- `headOr (@once xs : List Nat) (dflt : Nat)`: `xs` carries `.once`, +/-- `headOr (@[once] xs : List Nat) (dflt : Nat)`: `xs` carries `.once`, `dflt` is unannotated `.many` used affinely. -/ private def affHeadDefaultFun : Fir.Fun := { key := .const 953 [] diff --git a/IxCC/fixtures/ownership/README.md b/IxCC/fixtures/ownership/README.md index f8f09ef631..074d0d6212 100644 --- a/IxCC/fixtures/ownership/README.md +++ b/IxCC/fixtures/ownership/README.md @@ -2,8 +2,8 @@ The fixtures of MT.7 (phase 1 plan; design in the local note `plans/fixtures/ownership-suite.md`). Each fixture is a Lean program written -with ix's contract syntax (`0` erased, `1` linear, `&` affine, `!` unique, -`~` local, `let borrow`), paired with its plain twin. `lake exe tests-own` +with ix's scoped `@[...]` mode syntax (`@[erased]`, `@[once]`, `@[unique]`, +`@[borrowed]`, `let @[borrow]`), paired with its plain twin. `lake exe tests-own` runs them. In Phase 1 the compiler carries written contracts but never reads them @@ -40,11 +40,11 @@ probes of the design note, renamed by fixture id. | ID | Annotated | ix | IxCC | Code against the twin | | --- | --- | --- | --- | --- | -| OS-01 `erased-proof-arg` | `pick (@erased _h : True) (n : Nat)` | accepted | compiled | equal Fir, Cfg and object | -| OS-03 `erased-data` | `ignoreFirst (@erased _n : Nat) (m : Nat)`, called with `n` | accepted | compiled (CX-1; `relevance-C0` before) | equal | +| OS-01 `erased-proof-arg` | `pick (@[erased] _h : True) (n : Nat)` | accepted | compiled | equal Fir, Cfg and object | +| OS-03 `erased-data` | `ignoreFirst (@[erased] _n : Nat) (m : Nat)`, called with `n` | accepted | compiled (CX-1; `relevance-C0` before) | equal | | OS-03b `erased-data-dead-work` | OS-03 called with `cube n` | accepted | compiled; no `natMul` in the code | equal | -| OS-14 `unique-nat-match` | `pred (@unique n : Nat)` with `match`, caller `(@unique n)` | accepted | compiled | equal | -| OS-22 `local-forward` | `localId (@borrowed x : Nat) : @borrowed Nat`, caller `(@borrowed n)` | accepted | compiled | equal | +| OS-14 `unique-nat-match` | `pred (@[unique] n : Nat)` with `match`, caller `(@[unique] n)` | accepted | compiled | equal | +| OS-22 `local-forward` | `localId (@[borrowed] x : Nat) : @[borrowed] Nat`, caller `(@[borrowed] n)` | accepted | compiled | equal | | OS-02 `subtype-decidable` | plain only | – | compiled; no allocation | – | | OS-16 `k0-reverse-plain` | plain only (its annotated twin OS-15 is rejected) | – | compiled; `2n` cells, `48n` bytes natively | – | diff --git a/IxCC/fixtures/ownership/src/N01/Annotated.lean b/IxCC/fixtures/ownership/src/N01/Annotated.lean index 50c3b7adc7..1cd8faa753 100644 --- a/IxCC/fixtures/ownership/src/N01/Annotated.lean +++ b/IxCC/fixtures/ownership/src/N01/Annotated.lean @@ -7,8 +7,8 @@ from probe `N01ConsumeBorrowed`. Written for IxCC (Apache-2.0 OR MIT). The pinned ix rejects it; its verdict is recorded in `fixtures/ownership/verdicts.json`. -/ -def take (@unique xs : List Nat) : @unique List Nat := xs +def take (@[unique] xs : List Nat) : @[unique] List Nat := xs -def consumeView (@unique owner : List Nat) : @unique List Nat := - let @borrow v : List Nat := owner +def consumeView (@[unique] owner : List Nat) : @[unique] List Nat := + let @[borrow] v : List Nat := owner take v diff --git a/IxCC/fixtures/ownership/src/N02/Annotated.lean b/IxCC/fixtures/ownership/src/N02/Annotated.lean index 1985ca74d8..018fb827ee 100644 --- a/IxCC/fixtures/ownership/src/N02/Annotated.lean +++ b/IxCC/fixtures/ownership/src/N02/Annotated.lean @@ -7,9 +7,9 @@ from probe `N02MoveWhileBorrowed`. Written for IxCC (Apache-2.0 OR MIT). The pinned ix rejects it; its verdict is recorded in `fixtures/ownership/verdicts.json`. -/ -def lenL (@borrowed v : List Nat) : Nat := v.length +def lenL (@[borrowed] v : List Nat) : Nat := v.length -def moveDuringLoan (@unique owner : List Nat) : @unique List Nat := - let @borrow v : List Nat := owner +def moveDuringLoan (@[unique] owner : List Nat) : @[unique] List Nat := + let @[borrow] v : List Nat := owner let _n := lenL v owner diff --git a/IxCC/fixtures/ownership/src/N03/Annotated.lean b/IxCC/fixtures/ownership/src/N03/Annotated.lean index c00e5774e9..b63467c649 100644 --- a/IxCC/fixtures/ownership/src/N03/Annotated.lean +++ b/IxCC/fixtures/ownership/src/N03/Annotated.lean @@ -7,6 +7,6 @@ from probe `N03UniqueTwice`. Written for IxCC (Apache-2.0 OR MIT). The pinned ix rejects it; its verdict is recorded in `fixtures/ownership/verdicts.json`. -/ -def take (@unique xs : List Nat) : @unique List Nat := xs +def take (@[unique] xs : List Nat) : @[unique] List Nat := xs -def twice (@unique xs : List Nat) : List Nat × List Nat := (take xs, take xs) +def twice (@[unique] xs : List Nat) : List Nat × List Nat := (take xs, take xs) diff --git a/IxCC/fixtures/ownership/src/N04/Annotated.lean b/IxCC/fixtures/ownership/src/N04/Annotated.lean index f24986c992..5b624e5f2b 100644 --- a/IxCC/fixtures/ownership/src/N04/Annotated.lean +++ b/IxCC/fixtures/ownership/src/N04/Annotated.lean @@ -7,8 +7,8 @@ from probe `N04FreezeThenUnique`. Written for IxCC (Apache-2.0 OR MIT). The pinned ix rejects it; its verdict is recorded in `fixtures/ownership/verdicts.json`. -/ -def take (@unique xs : List Nat) : @unique List Nat := xs +def take (@[unique] xs : List Nat) : @[unique] List Nat := xs -def freezeThenTake (@unique xs : List Nat) : @unique List Nat := +def freezeThenTake (@[unique] xs : List Nat) : @[unique] List Nat := let n := xs.length if n == 0 then take xs else take xs diff --git a/IxCC/fixtures/ownership/src/N05/Annotated.lean b/IxCC/fixtures/ownership/src/N05/Annotated.lean index 93c32b42ef..18f896610c 100644 --- a/IxCC/fixtures/ownership/src/N05/Annotated.lean +++ b/IxCC/fixtures/ownership/src/N05/Annotated.lean @@ -7,4 +7,4 @@ from probe `N05LocalEscapeList`. Written for IxCC (Apache-2.0 OR MIT). The pinned ix rejects it; its verdict is recorded in `fixtures/ownership/verdicts.json`. -/ -def escList (@borrowed xs : List Nat) : List Nat := xs +def escList (@[borrowed] xs : List Nat) : List Nat := xs diff --git a/IxCC/fixtures/ownership/src/N06/Annotated.lean b/IxCC/fixtures/ownership/src/N06/Annotated.lean index 8800f1449f..916210537b 100644 --- a/IxCC/fixtures/ownership/src/N06/Annotated.lean +++ b/IxCC/fixtures/ownership/src/N06/Annotated.lean @@ -7,4 +7,4 @@ from probe `N06LocalIntoCtor`. Written for IxCC (Apache-2.0 OR MIT). The pinned ix rejects it; its verdict is recorded in `fixtures/ownership/verdicts.json`. -/ -def wrap (@borrowed xs : List Nat) : List (List Nat) := [xs] +def wrap (@[borrowed] xs : List Nat) : List (List Nat) := [xs] diff --git a/IxCC/fixtures/ownership/src/N07/Annotated.lean b/IxCC/fixtures/ownership/src/N07/Annotated.lean index ea3b8aefc2..bb323c7579 100644 --- a/IxCC/fixtures/ownership/src/N07/Annotated.lean +++ b/IxCC/fixtures/ownership/src/N07/Annotated.lean @@ -7,4 +7,4 @@ from probe `N07LinearIntoTwoBranches`. Written for IxCC (Apache-2.0 OR MIT). The pinned ix rejects it; its verdict is recorded in `fixtures/ownership/verdicts.json`. -/ -def pickOne (b : Bool) (@once x : Nat) : Nat := if b then x else 0 +def pickOne (b : Bool) (@[once] x : Nat) : Nat := if b then x else 0 diff --git a/IxCC/fixtures/ownership/src/N08/Annotated.lean b/IxCC/fixtures/ownership/src/N08/Annotated.lean index 270aaef63a..6b93d5a8c0 100644 --- a/IxCC/fixtures/ownership/src/N08/Annotated.lean +++ b/IxCC/fixtures/ownership/src/N08/Annotated.lean @@ -7,4 +7,4 @@ from probe `N08ErasedUsed`. Written for IxCC (Apache-2.0 OR MIT). The pinned ix rejects it; its verdict is recorded in `fixtures/ownership/verdicts.json`. -/ -def useErased (@erased n : Nat) : Nat := n + 1 +def useErased (@[erased] n : Nat) : Nat := n + 1 diff --git a/IxCC/fixtures/ownership/src/OS01/Annotated.lean b/IxCC/fixtures/ownership/src/OS01/Annotated.lean index fee755e3d9..dcb9739a6d 100644 --- a/IxCC/fixtures/ownership/src/OS01/Annotated.lean +++ b/IxCC/fixtures/ownership/src/OS01/Annotated.lean @@ -10,7 +10,7 @@ driver for `lean --run`: each stdin line `ROOT ARG…` prints that root's value on those arguments. -/ -def pick (@erased _h : True) (n : Nat) : Nat := n + 1 +def pick (@[erased] _h : True) (n : Nat) : Nat := n + 1 def entry (n : Nat) : Nat := pick trivial n diff --git a/IxCC/fixtures/ownership/src/OS01b/Annotated.lean b/IxCC/fixtures/ownership/src/OS01b/Annotated.lean index 39d891b54d..d34398e797 100644 --- a/IxCC/fixtures/ownership/src/OS01b/Annotated.lean +++ b/IxCC/fixtures/ownership/src/OS01b/Annotated.lean @@ -8,6 +8,6 @@ IxCC (Apache-2.0 OR MIT). The pinned ix rejects it; its verdict is recorded in `fixtures/ownership/verdicts.json`. -/ -def predPos (n : Nat) (@erased _h : n > 0) : Nat := n - 1 +def predPos (n : Nat) (@[erased] _h : n > 0) : Nat := n - 1 def entry (n : Nat) : Nat := predPos (n + 1) (Nat.succ_pos n) diff --git a/IxCC/fixtures/ownership/src/OS03/Annotated.lean b/IxCC/fixtures/ownership/src/OS03/Annotated.lean index e8fd330820..2df7e5c6d3 100644 --- a/IxCC/fixtures/ownership/src/OS03/Annotated.lean +++ b/IxCC/fixtures/ownership/src/OS03/Annotated.lean @@ -10,7 +10,7 @@ driver for `lean --run`: each stdin line `ROOT ARG…` prints that root's value on those arguments. -/ -def ignoreFirst (@erased _n : Nat) (m : Nat) : Nat := m + 1 +def ignoreFirst (@[erased] _n : Nat) (m : Nat) : Nat := m + 1 def entry (n : Nat) : Nat := ignoreFirst n n diff --git a/IxCC/fixtures/ownership/src/OS03b/Annotated.lean b/IxCC/fixtures/ownership/src/OS03b/Annotated.lean index 2792ef4f87..81e07217a3 100644 --- a/IxCC/fixtures/ownership/src/OS03b/Annotated.lean +++ b/IxCC/fixtures/ownership/src/OS03b/Annotated.lean @@ -10,7 +10,7 @@ driver for `lean --run`: each stdin line `ROOT ARG…` prints that root's value on those arguments. -/ -def ignoreFirst (@erased _n : Nat) (m : Nat) : Nat := m + 1 +def ignoreFirst (@[erased] _n : Nat) (m : Nat) : Nat := m + 1 def cube (n : Nat) : Nat := n * n * n diff --git a/IxCC/fixtures/ownership/src/OS04/Annotated.lean b/IxCC/fixtures/ownership/src/OS04/Annotated.lean index ebaa5938c7..1fe7aa79a8 100644 --- a/IxCC/fixtures/ownership/src/OS04/Annotated.lean +++ b/IxCC/fixtures/ownership/src/OS04/Annotated.lean @@ -7,7 +7,7 @@ from probe `P31LenErasedType`. Written for IxCC (Apache-2.0 OR MIT). The pinned ix rejects it; its verdict is recorded in `fixtures/ownership/verdicts.json`. -/ -def len {@erased α : Type} (xs : List α) : Nat := +def len {@[erased] α : Type} (xs : List α) : Nat := match xs with | [] => 0 | _ :: rest => len rest + 1 diff --git a/IxCC/fixtures/ownership/src/OS05/Annotated.lean b/IxCC/fixtures/ownership/src/OS05/Annotated.lean index 96921097af..3feba797ac 100644 --- a/IxCC/fixtures/ownership/src/OS05/Annotated.lean +++ b/IxCC/fixtures/ownership/src/OS05/Annotated.lean @@ -11,7 +11,7 @@ inductive Vec (α : Type) : Nat → Type where | nil : Vec α 0 | cons : α → Vec α n → Vec α (n+1) -def vhead {@erased α : Type} {@erased n : Nat} : Vec α (n+1) → α +def vhead {@[erased] α : Type} {@[erased] n : Nat} : Vec α (n+1) → α | .cons a _ => a def entry (n : Nat) : Nat := vhead (Vec.cons n (Vec.cons (n+1) Vec.nil)) diff --git a/IxCC/fixtures/ownership/src/OS06/Annotated.lean b/IxCC/fixtures/ownership/src/OS06/Annotated.lean index adf185c7af..8ee40829de 100644 --- a/IxCC/fixtures/ownership/src/OS06/Annotated.lean +++ b/IxCC/fixtures/ownership/src/OS06/Annotated.lean @@ -7,7 +7,7 @@ from probe `P39ErasedAbsurd`. Written for IxCC (Apache-2.0 OR MIT). The pinned ix rejects it; its verdict is recorded in `fixtures/ownership/verdicts.json`. -/ -def absurdUse (xs : List Nat) (@erased h : xs ≠ []) : Nat := +def absurdUse (xs : List Nat) (@[erased] h : xs ≠ []) : Nat := match xs with | x :: _ => x | [] => absurd rfl h diff --git a/IxCC/fixtures/ownership/src/OS06b/Annotated.lean b/IxCC/fixtures/ownership/src/OS06b/Annotated.lean index 35cd4a1f96..6e4807f915 100644 --- a/IxCC/fixtures/ownership/src/OS06b/Annotated.lean +++ b/IxCC/fixtures/ownership/src/OS06b/Annotated.lean @@ -7,7 +7,7 @@ from probe `P25HeadProof`. Written for IxCC (Apache-2.0 OR MIT). The pinned ix rejects it; its verdict is recorded in `fixtures/ownership/verdicts.json`. -/ -def headOr (xs : List Nat) (@erased h : xs ≠ []) : Nat := +def headOr (xs : List Nat) (@[erased] h : xs ≠ []) : Nat := match xs, h with | x :: _, _ => x diff --git a/IxCC/fixtures/ownership/src/OS07/Annotated.lean b/IxCC/fixtures/ownership/src/OS07/Annotated.lean index 4ffee21322..e5a879e887 100644 --- a/IxCC/fixtures/ownership/src/OS07/Annotated.lean +++ b/IxCC/fixtures/ownership/src/OS07/Annotated.lean @@ -7,7 +7,7 @@ from probe `P23Countdown`. Written for IxCC (Apache-2.0 OR MIT). The pinned ix rejects it; its verdict is recorded in `fixtures/ownership/verdicts.json`. -/ -def countdown (n : Nat) (@erased h : 0 ≤ n) : Nat := +def countdown (n : Nat) (@[erased] h : 0 ≤ n) : Nat := match n with | 0 => 0 | k+1 => countdown k (Nat.zero_le k) + 1 diff --git a/IxCC/fixtures/ownership/src/OS07b/Annotated.lean b/IxCC/fixtures/ownership/src/OS07b/Annotated.lean index 9868b5093c..435bb5bd38 100644 --- a/IxCC/fixtures/ownership/src/OS07b/Annotated.lean +++ b/IxCC/fixtures/ownership/src/OS07b/Annotated.lean @@ -7,7 +7,7 @@ from probe `P33CountdownWF`. Written for IxCC (Apache-2.0 OR MIT). The pinned ix rejects it; its verdict is recorded in `fixtures/ownership/verdicts.json`. -/ -def countdownWF (n : Nat) (@erased h : 0 ≤ n) : Nat := +def countdownWF (n : Nat) (@[erased] h : 0 ≤ n) : Nat := if hn : n = 0 then 0 else countdownWF (n - 1) (Nat.zero_le _) + 1 termination_by n decreasing_by omega diff --git a/IxCC/fixtures/ownership/src/OS08/Annotated.lean b/IxCC/fixtures/ownership/src/OS08/Annotated.lean index f4a8e355d9..81209c02d4 100644 --- a/IxCC/fixtures/ownership/src/OS08/Annotated.lean +++ b/IxCC/fixtures/ownership/src/OS08/Annotated.lean @@ -7,4 +7,4 @@ from probe `OS08BoundsArray`. Written for IxCC (Apache-2.0 OR MIT). The pinned ix rejects it; its verdict is recorded in `fixtures/ownership/verdicts.json`. -/ -def getE (xs : Array Nat) (i : Nat) (@erased h : i < xs.size) : Nat := xs[i]'h +def getE (xs : Array Nat) (i : Nat) (@[erased] h : i < xs.size) : Nat := xs[i]'h diff --git a/IxCC/fixtures/ownership/src/OS09/Annotated.lean b/IxCC/fixtures/ownership/src/OS09/Annotated.lean index 9722f99c8e..9e51112e55 100644 --- a/IxCC/fixtures/ownership/src/OS09/Annotated.lean +++ b/IxCC/fixtures/ownership/src/OS09/Annotated.lean @@ -7,4 +7,4 @@ from probe `P14Linear`. Written for IxCC (Apache-2.0 OR MIT). The pinned ix rejects it; its verdict is recorded in `fixtures/ownership/verdicts.json`. -/ -def lin (@once x : Nat) (@once y : Nat) : Nat := x + y +def lin (@[once] x : Nat) (@[once] y : Nat) : Nat := x + y diff --git a/IxCC/fixtures/ownership/src/OS10/Annotated.lean b/IxCC/fixtures/ownership/src/OS10/Annotated.lean index e2e6f2ae59..41f5ddca02 100644 --- a/IxCC/fixtures/ownership/src/OS10/Annotated.lean +++ b/IxCC/fixtures/ownership/src/OS10/Annotated.lean @@ -7,4 +7,4 @@ from probe `P14bLinearDup`. Written for IxCC (Apache-2.0 OR MIT). The pinned ix rejects it; its verdict is recorded in `fixtures/ownership/verdicts.json`. -/ -def twice (@once x : Nat) : Nat := x + x +def twice (@[once] x : Nat) : Nat := x + x diff --git a/IxCC/fixtures/ownership/src/OS11/Annotated.lean b/IxCC/fixtures/ownership/src/OS11/Annotated.lean index 2ce719f101..1e88939167 100644 --- a/IxCC/fixtures/ownership/src/OS11/Annotated.lean +++ b/IxCC/fixtures/ownership/src/OS11/Annotated.lean @@ -7,4 +7,4 @@ from probe `P14cLinearUnused`. Written for IxCC (Apache-2.0 OR MIT). The pinned ix rejects it; its verdict is recorded in `fixtures/ownership/verdicts.json`. -/ -def unused (@once x : Nat) : Nat := 0 +def unused (@[once] x : Nat) : Nat := 0 diff --git a/IxCC/fixtures/ownership/src/OS12/Annotated.lean b/IxCC/fixtures/ownership/src/OS12/Annotated.lean index 8b10c81c69..bfa76fa406 100644 --- a/IxCC/fixtures/ownership/src/OS12/Annotated.lean +++ b/IxCC/fixtures/ownership/src/OS12/Annotated.lean @@ -7,4 +7,4 @@ from probe `P36AffineDup`. Written for IxCC (Apache-2.0 OR MIT). The pinned ix rejects it; its verdict is recorded in `fixtures/ownership/verdicts.json`. -/ -def twiceA (@once x : Nat) : Nat := x + x +def twiceA (@[once] x : Nat) : Nat := x + x diff --git a/IxCC/fixtures/ownership/src/OS13/Annotated.lean b/IxCC/fixtures/ownership/src/OS13/Annotated.lean index ab5b4f02cb..03ac811d36 100644 --- a/IxCC/fixtures/ownership/src/OS13/Annotated.lean +++ b/IxCC/fixtures/ownership/src/OS13/Annotated.lean @@ -10,7 +10,7 @@ driver for `lean --run`: each stdin line `ROOT ARG…` prints that root's value on those arguments. -/ -def linId (@once x : Nat) : Nat := x +def linId (@[once] x : Nat) : Nat := x def entry (n : Nat) : Nat := linId n diff --git a/IxCC/fixtures/ownership/src/OS14/Annotated.lean b/IxCC/fixtures/ownership/src/OS14/Annotated.lean index de122a4c46..37fdafe052 100644 --- a/IxCC/fixtures/ownership/src/OS14/Annotated.lean +++ b/IxCC/fixtures/ownership/src/OS14/Annotated.lean @@ -10,12 +10,12 @@ driver for `lean --run`: each stdin line `ROOT ARG…` prints that root's value on those arguments. -/ -def pred (@unique n : Nat) : Nat := +def pred (@[unique] n : Nat) : Nat := match n with | 0 => 1 | k+1 => k -def entry (@unique n : Nat) : Nat := pred n +def entry (@[unique] n : Nat) : Nat := pred n def main : IO Unit := do let input ← (← IO.getStdin).readToEnd diff --git a/IxCC/fixtures/ownership/src/OS14b/Annotated.lean b/IxCC/fixtures/ownership/src/OS14b/Annotated.lean index e20ac0172c..3e189d89c3 100644 --- a/IxCC/fixtures/ownership/src/OS14b/Annotated.lean +++ b/IxCC/fixtures/ownership/src/OS14b/Annotated.lean @@ -7,7 +7,7 @@ from probe `OS14PlainCaller`. Written for IxCC (Apache-2.0 OR MIT). The pinned ix rejects it; its verdict is recorded in `fixtures/ownership/verdicts.json`. -/ -def pred (@unique n : Nat) : Nat := +def pred (@[unique] n : Nat) : Nat := match n with | 0 => 1 | k+1 => k diff --git a/IxCC/fixtures/ownership/src/OS15/Annotated.lean b/IxCC/fixtures/ownership/src/OS15/Annotated.lean index b6b9c1b60a..f27e884efa 100644 --- a/IxCC/fixtures/ownership/src/OS15/Annotated.lean +++ b/IxCC/fixtures/ownership/src/OS15/Annotated.lean @@ -7,7 +7,7 @@ from probe `P04RevUniqueAcc`. Written for IxCC (Apache-2.0 OR MIT). The pinned ix rejects it; its verdict is recorded in `fixtures/ownership/verdicts.json`. -/ -def revAcc (xs : List Nat) (@unique acc : List Nat) : @unique List Nat := +def revAcc (xs : List Nat) (@[unique] acc : List Nat) : @[unique] List Nat := match xs with | [] => acc | x :: rest => revAcc rest (x :: acc) diff --git a/IxCC/fixtures/ownership/src/OS15b/Annotated.lean b/IxCC/fixtures/ownership/src/OS15b/Annotated.lean index c28a74ad10..2c800d3dd7 100644 --- a/IxCC/fixtures/ownership/src/OS15b/Annotated.lean +++ b/IxCC/fixtures/ownership/src/OS15b/Annotated.lean @@ -7,7 +7,7 @@ from probe `P03RevUniqueBoth`. Written for IxCC (Apache-2.0 OR MIT). The pinned ix rejects it; its verdict is recorded in `fixtures/ownership/verdicts.json`. -/ -def revAcc (@unique xs : List Nat) (@unique acc : List Nat) : @unique List Nat := +def revAcc (@[unique] xs : List Nat) (@[unique] acc : List Nat) : @[unique] List Nat := match xs with | [] => acc | x :: rest => revAcc rest (x :: acc) diff --git a/IxCC/fixtures/ownership/src/OS17/Annotated.lean b/IxCC/fixtures/ownership/src/OS17/Annotated.lean index 05d0fdc6f8..f58924fe8d 100644 --- a/IxCC/fixtures/ownership/src/OS17/Annotated.lean +++ b/IxCC/fixtures/ownership/src/OS17/Annotated.lean @@ -7,4 +7,4 @@ from probe `P05Push`. Written for IxCC (Apache-2.0 OR MIT). The pinned ix rejects it; its verdict is recorded in `fixtures/ownership/verdicts.json`. -/ -def push (@unique acc : List Nat) (x : Nat) : @unique List Nat := x :: acc +def push (@[unique] acc : List Nat) (x : Nat) : @[unique] List Nat := x :: acc diff --git a/IxCC/fixtures/ownership/src/OS18/Annotated.lean b/IxCC/fixtures/ownership/src/OS18/Annotated.lean index 4c42d2b049..ac12d9298c 100644 --- a/IxCC/fixtures/ownership/src/OS18/Annotated.lean +++ b/IxCC/fixtures/ownership/src/OS18/Annotated.lean @@ -7,4 +7,4 @@ from probe `P37UniqueDup`. Written for IxCC (Apache-2.0 OR MIT). The pinned ix rejects it; its verdict is recorded in `fixtures/ownership/verdicts.json`. -/ -def dupU (@unique xs : List Nat) : List Nat × List Nat := (xs, xs) +def dupU (@[unique] xs : List Nat) : List Nat × List Nat := (xs, xs) diff --git a/IxCC/fixtures/ownership/src/OS19/Annotated.lean b/IxCC/fixtures/ownership/src/OS19/Annotated.lean index 932734cc7b..a9037d7a79 100644 --- a/IxCC/fixtures/ownership/src/OS19/Annotated.lean +++ b/IxCC/fixtures/ownership/src/OS19/Annotated.lean @@ -11,7 +11,7 @@ inductive T where | leaf | node (l : T) (k : Nat) (r : T) -def swapT (@unique t : T) : @unique T := +def swapT (@[unique] t : T) : @[unique] T := match t with | .leaf => .leaf | .node l k r => .node r k l diff --git a/IxCC/fixtures/ownership/src/OS20/Annotated.lean b/IxCC/fixtures/ownership/src/OS20/Annotated.lean index c5f3624fb4..914cf2e28c 100644 --- a/IxCC/fixtures/ownership/src/OS20/Annotated.lean +++ b/IxCC/fixtures/ownership/src/OS20/Annotated.lean @@ -7,4 +7,4 @@ from probe `P18UniqueString`. Written for IxCC (Apache-2.0 OR MIT). The pinned ix rejects it; its verdict is recorded in `fixtures/ownership/verdicts.json`. -/ -def addExcl (@unique s : String) : @unique String := s.push (Char.ofNat 33) +def addExcl (@[unique] s : String) : @[unique] String := s.push (Char.ofNat 33) diff --git a/IxCC/fixtures/ownership/src/OS21/Annotated.lean b/IxCC/fixtures/ownership/src/OS21/Annotated.lean index dd4fedfb01..a3e2b92380 100644 --- a/IxCC/fixtures/ownership/src/OS21/Annotated.lean +++ b/IxCC/fixtures/ownership/src/OS21/Annotated.lean @@ -7,8 +7,8 @@ from probe `P35FreshResult`. Written for IxCC (Apache-2.0 OR MIT). The pinned ix rejects it; its verdict is recorded in `fixtures/ownership/verdicts.json`. -/ -def single (x : Nat) : @unique List Nat := [x] +def single (x : Nat) : @[unique] List Nat := [x] -def idT {@erased α : Type} (x : α) : α := x +def idT {@[erased] α : Type} (x : α) : α := x def entry (n : Nat) : Nat := idT n + (single n).length diff --git a/IxCC/fixtures/ownership/src/OS22/Annotated.lean b/IxCC/fixtures/ownership/src/OS22/Annotated.lean index b23f91616a..187002fc51 100644 --- a/IxCC/fixtures/ownership/src/OS22/Annotated.lean +++ b/IxCC/fixtures/ownership/src/OS22/Annotated.lean @@ -10,9 +10,9 @@ driver for `lean --run`: each stdin line `ROOT ARG…` prints that root's value on those arguments. -/ -def localId (@borrowed x : Nat) : @borrowed Nat := x +def localId (@[borrowed] x : Nat) : @[borrowed] Nat := x -def entry (@borrowed n : Nat) : @borrowed Nat := localId n +def entry (@[borrowed] n : Nat) : @[borrowed] Nat := localId n def main : IO Unit := do let input ← (← IO.getStdin).readToEnd diff --git a/IxCC/fixtures/ownership/src/OS23/Annotated.lean b/IxCC/fixtures/ownership/src/OS23/Annotated.lean index cda7b825a2..f98901667a 100644 --- a/IxCC/fixtures/ownership/src/OS23/Annotated.lean +++ b/IxCC/fixtures/ownership/src/OS23/Annotated.lean @@ -7,4 +7,4 @@ from probe `P17LocalEscape`. Written for IxCC (Apache-2.0 OR MIT). The pinned ix rejects it; its verdict is recorded in `fixtures/ownership/verdicts.json`. -/ -def esc (@borrowed x : Nat) : Nat := x +def esc (@[borrowed] x : Nat) : Nat := x diff --git a/IxCC/fixtures/ownership/src/OS24/Annotated.lean b/IxCC/fixtures/ownership/src/OS24/Annotated.lean index 6590cd8ea6..cc439a2bba 100644 --- a/IxCC/fixtures/ownership/src/OS24/Annotated.lean +++ b/IxCC/fixtures/ownership/src/OS24/Annotated.lean @@ -7,4 +7,4 @@ from probe `P09LocalLib`. Written for IxCC (Apache-2.0 OR MIT). The pinned ix rejects it; its verdict is recorded in `fixtures/ownership/verdicts.json`. -/ -def len (@borrowed xs : List Nat) : Nat := xs.length +def len (@[borrowed] xs : List Nat) : Nat := xs.length diff --git a/IxCC/fixtures/ownership/src/OS25/Annotated.lean b/IxCC/fixtures/ownership/src/OS25/Annotated.lean index 487d9e1cf3..ebdb563214 100644 --- a/IxCC/fixtures/ownership/src/OS25/Annotated.lean +++ b/IxCC/fixtures/ownership/src/OS25/Annotated.lean @@ -7,7 +7,7 @@ from probe `P10LocalMatch`. Written for IxCC (Apache-2.0 OR MIT). The pinned ix rejects it; its verdict is recorded in `fixtures/ownership/verdicts.json`. -/ -def nonEmpty (@borrowed xs : List Nat) : Nat := +def nonEmpty (@[borrowed] xs : List Nat) : Nat := match xs with | [] => 0 | _ :: _ => 1 diff --git a/IxCC/fixtures/ownership/src/OS26/Annotated.lean b/IxCC/fixtures/ownership/src/OS26/Annotated.lean index efdfbdbb8e..f165a94a46 100644 --- a/IxCC/fixtures/ownership/src/OS26/Annotated.lean +++ b/IxCC/fixtures/ownership/src/OS26/Annotated.lean @@ -8,7 +8,7 @@ pinned ix rejects it; its verdict is recorded in `fixtures/ownership/verdicts.js -/ def viaBorrow (xs : List Nat) : Nat := - let @borrow v : List Nat := xs + let @[borrow] v : List Nat := xs match v with | [] => 0 | _ :: _ => 1 diff --git a/IxCC/fixtures/ownership/src/OS27/Annotated.lean b/IxCC/fixtures/ownership/src/OS27/Annotated.lean index 0515e19f44..e088a99607 100644 --- a/IxCC/fixtures/ownership/src/OS27/Annotated.lean +++ b/IxCC/fixtures/ownership/src/OS27/Annotated.lean @@ -7,8 +7,8 @@ from probe `P29SharedLoan`. Written for IxCC (Apache-2.0 OR MIT). The pinned ix rejects it; its verdict is recorded in `fixtures/ownership/verdicts.json`. -/ -def sharedLoan (@unique owner : Nat) : Nat := - let @borrow view : Nat := owner +def sharedLoan (@[unique] owner : Nat) : Nat := + let @[borrow] view : Nat := owner view def entry (n : Nat) : Nat := sharedLoan n diff --git a/IxCC/fixtures/ownership/src/OS28/Annotated.lean b/IxCC/fixtures/ownership/src/OS28/Annotated.lean index ae60f72f36..3997d2e415 100644 --- a/IxCC/fixtures/ownership/src/OS28/Annotated.lean +++ b/IxCC/fixtures/ownership/src/OS28/Annotated.lean @@ -7,8 +7,8 @@ from probe `OS28BorrowAccumulate`. Written for IxCC (Apache-2.0 OR MIT). The pinned ix rejects it; its verdict is recorded in `fixtures/ownership/verdicts.json`. -/ -def lenL (@borrowed v : List Nat) : Nat := v.length +def lenL (@[borrowed] v : List Nat) : Nat := v.length -def countAll (xs : List Nat) (@unique acc : Nat) : Nat := - let @borrow v : List Nat := xs +def countAll (xs : List Nat) (@[unique] acc : Nat) : Nat := + let @[borrow] v : List Nat := xs acc + lenL v diff --git a/IxCC/fixtures/ownership/src/OS29/Annotated.lean b/IxCC/fixtures/ownership/src/OS29/Annotated.lean index 4d2c0a75f8..242e738c25 100644 --- a/IxCC/fixtures/ownership/src/OS29/Annotated.lean +++ b/IxCC/fixtures/ownership/src/OS29/Annotated.lean @@ -7,6 +7,6 @@ from probe `P12OnceClosure`. Written for IxCC (Apache-2.0 OR MIT). The pinned ix rejects it; its verdict is recorded in `fixtures/ownership/verdicts.json`. -/ -def applyOnce (@once k : Nat → Nat) (x : Nat) : Nat := k x +def applyOnce (@[once] k : Nat → Nat) (x : Nat) : Nat := k x def useIt (n : Nat) : Nat := applyOnce (fun y => y + n) 3 diff --git a/IxCC/fixtures/ownership/src/OS29b/Annotated.lean b/IxCC/fixtures/ownership/src/OS29b/Annotated.lean index 577944b8dd..eb71ef2b5e 100644 --- a/IxCC/fixtures/ownership/src/OS29b/Annotated.lean +++ b/IxCC/fixtures/ownership/src/OS29b/Annotated.lean @@ -7,6 +7,6 @@ from probe `OS29bUniqueClosure`. Written for IxCC (Apache-2.0 OR MIT). The pinned ix rejects it; its verdict is recorded in `fixtures/ownership/verdicts.json`. -/ -def applyOnce (@unique k : Nat → Nat) (x : Nat) : Nat := k x +def applyOnce (@[unique] k : Nat → Nat) (x : Nat) : Nat := k x def useIt (n : Nat) : Nat := applyOnce (fun y => y + n) 3 diff --git a/IxCC/fixtures/ownership/src/OS34/Annotated.lean b/IxCC/fixtures/ownership/src/OS34/Annotated.lean index 2292ac396a..6cc388978f 100644 --- a/IxCC/fixtures/ownership/src/OS34/Annotated.lean +++ b/IxCC/fixtures/ownership/src/OS34/Annotated.lean @@ -11,8 +11,8 @@ inductive Tree where | nil | node (l : Tree) (r : Tree) -def leafPair (u : Unit) : @unique Tree := .node .nil .nil +def leafPair (u : Unit) : @[unique] Tree := .node .nil .nil -def keep (@unique t : Tree) : @unique Tree := t +def keep (@[unique] t : Tree) : @[unique] Tree := t -def entry (u : Unit) : @unique Tree := keep (leafPair u) +def entry (u : Unit) : @[unique] Tree := keep (leafPair u) diff --git a/IxCC/fixtures/ownership/src/OS35/Annotated.lean b/IxCC/fixtures/ownership/src/OS35/Annotated.lean index a637f00b9b..a3408b1bc1 100644 --- a/IxCC/fixtures/ownership/src/OS35/Annotated.lean +++ b/IxCC/fixtures/ownership/src/OS35/Annotated.lean @@ -7,7 +7,7 @@ from probe `OS35FilterOdd`. Written for IxCC (Apache-2.0 OR MIT). The pinned ix rejects it; its verdict is recorded in `fixtures/ownership/verdicts.json`. -/ -def filterOdd (@unique xs : List Nat) : @unique List Nat := +def filterOdd (@[unique] xs : List Nat) : @[unique] List Nat := match xs with | [] => [] | x :: rest => if x % 2 == 1 then x :: filterOdd rest else filterOdd rest diff --git a/IxCC/fixtures/ownership/src/OS36/Annotated.lean b/IxCC/fixtures/ownership/src/OS36/Annotated.lean index 3b6ba814d4..4bb966a2d9 100644 --- a/IxCC/fixtures/ownership/src/OS36/Annotated.lean +++ b/IxCC/fixtures/ownership/src/OS36/Annotated.lean @@ -7,4 +7,4 @@ from probe `OS36ArrayBump`. Written for IxCC (Apache-2.0 OR MIT). The pinned ix rejects it; its verdict is recorded in `fixtures/ownership/verdicts.json`. -/ -def bump (@unique a : Array Nat) (i : Nat) : @unique Array Nat := a.modify i (· + 1) +def bump (@[unique] a : Array Nat) (i : Nat) : @[unique] Array Nat := a.modify i (· + 1) diff --git a/IxCC/fixtures/ownership/src/OS37/Annotated.lean b/IxCC/fixtures/ownership/src/OS37/Annotated.lean index d54927a042..cbcebeeca4 100644 --- a/IxCC/fixtures/ownership/src/OS37/Annotated.lean +++ b/IxCC/fixtures/ownership/src/OS37/Annotated.lean @@ -7,7 +7,7 @@ from probe `OS37BytesBuilder`. Written for IxCC (Apache-2.0 OR MIT). The pinned ix rejects it; its verdict is recorded in `fixtures/ownership/verdicts.json`. -/ -def emit (@unique b : ByteArray) (n : Nat) : @unique ByteArray := +def emit (@[unique] b : ByteArray) (n : Nat) : @[unique] ByteArray := match n with | 0 => b | k+1 => emit (b.push 0) k diff --git a/IxCCAiur/IxCCAiur/BigNatLower.lean b/IxCCAiur/IxCCAiur/BigNatLower.lean index 496b19e7d9..943053aa37 100644 --- a/IxCCAiur/IxCCAiur/BigNatLower.lean +++ b/IxCCAiur/IxCCAiur/BigNatLower.lean @@ -2275,6 +2275,17 @@ def tCaseBigE (cx : BigCx) (nx : String) (rx retR : BigRep) let zBody ← pick cx.base.P.known.natZero let sBody ← pick cx.base.P.known.natSucc return matchE (vE nx) [(.literal 0, zBody), (.wildcard, sBody)] + | .base .w32 => + let zBody ← pick cx.base.P.known.natZero + let sBody ← pick cx.base.P.known.natSucc + return matchE (callE "UInt32::compact_field" [callE "UInt32::compact" [vE nx]]) + [(.literal 0, zBody), (.wildcard, sBody)] + | .base .w64 => + bMark fun d => { d with needU64Bitwise := true } + let zBody ← pick cx.base.P.known.natZero + let sBody ← pick cx.base.P.known.natSucc + return matchE (callE "UInt64::is_zero" [vE nx]) + [(.literal 0, sBody), (.wildcard, zBody)] | .base (.enum ind) => let some ks := cx.base.cert.enum? ind | bLift (throw s!"case: unknown enum {ind}") let arms ← firsts.filterMapM fun (k, body) => do @@ -2324,7 +2335,6 @@ def tCaseBigE (cx : BigCx) (nx : String) (rx retR : BigRep) [(.literal 0, sBody), (.wildcard, zBody)]) return matchE (vE nx) (arms ++ [natArm, bigNatArm, erasedArm, strArm] ++ dfltArm) | .base .irr => bTrapE cx retR "case on erased value" - | _ => bLift (throw s!"case on unsupported rep {reprStr rx}") private def freeArgNamesB (vm : BVarMap) (bound : List Var) : Arg → List String | .var x => diff --git a/IxCCAiur/IxCCAiur/BigNatWholeProof.lean b/IxCCAiur/IxCCAiur/BigNatWholeProof.lean index a6aec15f1f..471bec1b48 100644 --- a/IxCCAiur/IxCCAiur/BigNatWholeProof.lean +++ b/IxCCAiur/IxCCAiur/BigNatWholeProof.lean @@ -6156,7 +6156,44 @@ theorem tCaseBigE_spec {cx : BigCx} {nx : String} {rx retR : BigRep} obtain ⟨_, hle2, hcl2⟩ := bTrapE_ok_inv hcase (fun _ _ _ => rfl) (fun fuel r' _ => by cases fuel <;> cases r' with | bigNat => rfl | base rb => cases rb <;> rfl) exact ⟨hfbSpec.1.trans hle2, fun _ hret hda hfok _ _ => hcl2 hret hda hfok⟩ - | w32 | w64 => exact False.elim (except_err_elim hcase rfl) + | w32 => + obtain ⟨zBody, s2, hz, hcase⟩ := bBind_step_inv hcase + obtain ⟨sBody, s3, hs, hcase⟩ := bBind_step_inv hcase + simp only [pure, StateT.pure, Except.pure, Except.ok.injEq, Prod.mk.injEq] at hcase + obtain ⟨rfl, rfl⟩ := hcase + obtain ⟨hle2, _⟩ := hPickApp hz (fun e' s' ht => + let ⟨_, hle, hcl⟩ := bTrapE_ok_inv ht (fun _ _ _ => rfl) + (fun fuel r' _ => by cases fuel <;> cases r' with | bigNat => rfl | base rb => cases rb <;> rfl) + ⟨hle, hcl⟩) + obtain ⟨hle3, _⟩ := hPickApp hs (fun e' s' ht => + let ⟨_, hle, hcl⟩ := bTrapE_ok_inv ht (fun _ _ _ => rfl) + (fun fuel r' _ => by cases fuel <;> cases r' with | bigNat => rfl | base rb => cases rb <;> rfl) + ⟨hle, hcl⟩) + exact ⟨(hfbSpec.1.trans hle2).trans hle3, fun hcore => by cases hcore⟩ + | w64 => + obtain ⟨_, s1, h1, hcase⟩ := bBind_step_inv hcase + obtain ⟨zBody, s2, hz, hcase⟩ := bBind_step_inv hcase + obtain ⟨sBody, s3, hs, hcase⟩ := bBind_step_inv hcase + simp only [pure, StateT.pure, Except.pure, Except.ok.injEq, Prod.mk.injEq] at hcase + obtain ⟨rfl, rfl⟩ := hcase + have hle1 : BStateLe sFb s1 := by + have hst : ∀ (fM : BLowerM Unit), fM sFb = .ok ((), s1) → + (∀ s, fM s = .ok ((), { s with + base := { s.base with demand := { s.base.demand with needU64Bitwise := true } } })) → + BStateLe sFb s1 := fun _ hf hd => by + rw [hd] at hf; obtain ⟨_, rfl⟩ := Prod.mk.inj (Except.ok.inj hf) + exact ⟨⟨Nat.le_refl _, Nat.le_refl _, rfl, by constructor <;> first | exact id | (intro _; rfl)⟩, + by constructor <;> exact id⟩ + exact hst _ h1 (fun _ => rfl) + obtain ⟨hle2, _⟩ := hPickApp hz (fun e' s' ht => + let ⟨_, hle, hcl⟩ := bTrapE_ok_inv ht (fun _ _ _ => rfl) + (fun fuel r' _ => by cases fuel <;> cases r' with | bigNat => rfl | base rb => cases rb <;> rfl) + ⟨hle, hcl⟩) + obtain ⟨hle3, _⟩ := hPickApp hs (fun e' s' ht => + let ⟨_, hle, hcl⟩ := bTrapE_ok_inv ht (fun _ _ _ => rfl) + (fun fuel r' _ => by cases fuel <;> cases r' with | bigNat => rfl | base rb => cases rb <;> rfl) + ⟨hle, hcl⟩) + exact ⟨((hfbSpec.1.trans hle1).trans hle2).trans hle3, fun hcore => by cases hcore⟩ /-- Join-point environment core-rep and clean-name invariant. -/ def BJEnvCoreOk (jenv : List BJEntry) : Prop := diff --git a/IxCCAiur/IxCCAiur/Driver.lean b/IxCCAiur/IxCCAiur/Driver.lean index 7a590f4b3c..b12202226b 100644 --- a/IxCCAiur/IxCCAiur/Driver.lean +++ b/IxCCAiur/IxCCAiur/Driver.lean @@ -252,6 +252,7 @@ structure FrontOptions where anfInlineSize : Option Nat := none anfInlineRounds : Option Nat := none anfMaxSpecs : Option Nat := none + dictSpecFirst : Bool := false deriving BEq, DecidableEq, Repr, Inhabited /-- What the front half makes of a closure: the ingested program, the producer's certificate, and the levels down to Fir. -/ @@ -1655,7 +1656,7 @@ falling back to `produceAnfDictSpec` when `Anf.defun` or `Anf.maxBackWork` rejec unspecialized or large program, and annotating `relevance-S1` / admit / ANF failures with diagnostics. Runs `produceSource` and `Lam.erase` only once. -/ private def produceFirAdaptive (cfg : Recheck.Config) (input : Recheck.Input) - (inlineAddrs : List Ixon.Address := []) : + (inlineAddrs : List Ixon.Address := []) (dictSpecFirst : Bool := false) : Except Recheck.Err Recheck.Cert := match Recheck.produceSource cfg input with | .error e => @@ -1694,7 +1695,11 @@ private def produceFirAdaptive (cfg : Recheck.Config) (input : Recheck.Input) { e' with message := e'.message ++ diagnoseAnfFailure input src trace.cert.steps anf none cfg.maxBackWork } pure ({ table := Src.Table.TableCert.ofTable table, relevance := ann, mid := trace.cert }, fir, Anf.firstOrder pre) - match stdRes with + if dictSpecFirst then + match runDictSpec () with + | .ok (dictCert, _, _) => .ok dictCert + | .error e2 => .error e2 + else match stdRes with | .ok (stdCert, stdFir, stdFo) => -- If standard `produceAnf` already reached first-order (`Anf.firstOrder stdPre`), use it -- directly; if it relied on P8 defunctionalization (`!stdFo`), run `produceAnfDictSpec` @@ -1725,7 +1730,7 @@ def frontOfInput (input : Recheck.Input) (opts : FrontOptions := {}) : Except String Front := do let baseCfg := applyFrontOptions (Recheck.Config.forInput {} input) input.program noInlineAddrs opts let attempt (cfg : Recheck.Config) : Except Recheck.Err Front := do - let cert ← produceFirAdaptive cfg input opts.inlineAddrs + let cert ← produceFirAdaptive cfg input opts.inlineAddrs opts.dictSpecFirst unless Recheck.checkCanonicalRelevance cfg input cert.table cert.relevance do throw { stage := .relevance, code := "relevance-canonical" message := "certificate relevance annotation does not match canonical annotator output" } @@ -2859,6 +2864,172 @@ def buildAutoGroups (entries : List String) groups := groups ++ [(s!"Prog::c2_single_{singleIdx}", bucket.toList)] return groups +/-- Bucket a sorted candidate list with parameterized width/lookup/node/row budgets. -/ +private def packAutoGroupBucket (grpPrefix singlePrefix : String) + (cands : Array (String × Nat × Nat × Nat)) + (chipMetrics : Std.HashMap String ChipGroupMetrics) + (rowMap : Std.HashMap String Nat) + (maxMembers maxColsPerMember maxGroupNodes maxGroupZeros maxGroupLookups : Nat) + (widthPct estW1Pct maxEstW1 lkMult lkAdd maxGroupRows : Nat) + (useEffCap mergeDeg3 mergeZeroLk : Bool) : List (String × List String) := Id.run do + let mut groups : List (String × List String) := [] + let mut bucket : Array String := #[] + let mut bucketDeg := 0 + let mut minCols := 0 + let mut maxCols := 0 + let mut minLookups := 0 + let mut maxLookups := 0 + let mut bucketNodes := 0 + let mut bucketZeros := 0 + let mut bucketLookups := 0 + let mut bucketShared := 0 + let mut bucketPriv := 0 + let mut bucketRows := 0 + let mut grpIdx := 0 + let mut singleIdx := 0 + let normDeg (d : Nat) : Nat := + if mergeDeg3 && d ≤ 3 then 0 else degClass d + for (nm, cols, calls, mem) in cands do + if cols > maxColsPerMember then continue + let lk := calls + mem + let cm := metricsOf chipMetrics nm cols + if cm.nodes > maxGroupNodes || cm.zeros > maxGroupZeros || lk > maxGroupLookups then + continue + let dc := normDeg cm.maxDeg + let r := rowMap.getD nm 0 + let effCap := if useEffCap then effectiveGroupMemberCap maxMembers minCols else maxMembers + let nextMinLk := min minLookups lk + let nextMaxLk := max maxLookups lk + let nextMaxCols := max maxCols cols + let nextShared := max bucketShared cm.shared + let nextPriv := bucketPriv + cm.privLifted + let nextEstW1 := nextShared + nextPriv + let estW1Limit := + let rel := (estW1Pct * nextMaxCols) / 100 + (if useEffCap then 16 else 64) + if maxEstW1 == 0 then rel + else min rel (max maxEstW1 ((150 * nextMaxCols) / 100 + 64)) + let rowsOk := maxGroupRows == 0 || bucketRows + r ≤ maxGroupRows + let compatible := + !bucket.isEmpty && + bucket.size < effCap && + bucketDeg == dc && + (mergeZeroLk || ((minLookups == 0) == (lk == 0))) && + cols ≤ (widthPct * minCols) / 100 + (if useEffCap then 16 else 64) && + nextEstW1 ≤ estW1Limit && + nextMaxLk ≤ lkMult * nextMinLk + lkAdd && + rowsOk && + bucketNodes + cm.nodes ≤ maxGroupNodes && + bucketZeros + cm.zeros ≤ maxGroupZeros && + bucketLookups + lk ≤ maxGroupLookups + if compatible then + bucket := bucket.push nm + maxCols := nextMaxCols + minLookups := nextMinLk + maxLookups := nextMaxLk + bucketNodes := bucketNodes + cm.nodes + bucketZeros := bucketZeros + cm.zeros + bucketLookups := bucketLookups + lk + bucketShared := nextShared + bucketPriv := nextPriv + bucketRows := bucketRows + r + else + if bucket.size ≥ 2 then + groups := groups ++ [(s!"{grpPrefix}_{grpIdx}", bucket.toList)] + grpIdx := grpIdx + 1 + else if bucket.size == 1 && minLookups ≥ 2 && + bucketShared + bucketPriv ≤ (estW1Pct * maxCols) / 100 + 16 then + groups := groups ++ [(s!"{singlePrefix}_{singleIdx}", bucket.toList)] + singleIdx := singleIdx + 1 + bucket := #[nm] + bucketDeg := dc + minCols := cols + maxCols := cols + minLookups := lk + maxLookups := lk + bucketNodes := cm.nodes + bucketZeros := cm.zeros + bucketLookups := lk + bucketShared := cm.shared + bucketPriv := cm.privLifted + bucketRows := r + if bucket.size ≥ 2 then + groups := groups ++ [(s!"{grpPrefix}_{grpIdx}", bucket.toList)] + else if bucket.size == 1 && minLookups ≥ 2 && + bucketShared + bucketPriv ≤ (estW1Pct * maxCols) / 100 + 16 then + groups := groups ++ [(s!"{singlePrefix}_{singleIdx}", bucket.toList)] + return groups + +/-- Profile-guided dense cold-chip auto-grouping (`--auto-group-dense`): keeps hot +chips (`rows > coldRowCutoff`) in tight narrow groups to preserve FFT cost, packs +active cold chips (`1 ≤ rows ≤ coldRowCutoff`) densely into fewer shared circuits +(with row-sum and stage-1 width budgets so FFT stays low while FRI leaf openings +and recursive verifier cost plummet), and isolates uninvoked chips (`rows == 0`) +so they never widen active groups. Zero TCB: every emitted group is certified by +`Aiur.Optimized.Grouping.preparePlan`. -/ +def buildDenseAutoGroups (entries : List String) + (chips : List (String × Nat × Nat × Nat)) + (existing : List (String × List String)) + (maxMembers : Nat := 64) + (chipMetrics : Std.HashMap String ChipGroupMetrics := {}) + (pinnedSingletons : Std.HashSet String := {}) + (maxMemberConstraintDeg : Nat := 5) + (profileRows : List (String × Nat) := []) + (coldRowCutoff : Nat := 64) : List (String × List String) := Id.run do + if maxMembers < 2 then return existing + let mut used : Std.HashSet String := pinnedSingletons + for e in entries do used := used.insert e + for (_, cs) in existing do + for c in cs do used := used.insert c + let eligible := chips.filter fun (nm, cols, _, _) => + let cm := metricsOf chipMetrics nm cols + nm.startsWith "Prog::" && cm.maxDeg ≤ maxMemberConstraintDeg && !used.contains nm + let rowMap : Std.HashMap String Nat := + profileRows.foldl (init := {}) fun m (nm, r) => m.insert nm (m.getD nm 0 + r) + let sortCands (xs : List (String × Nat × Nat × Nat)) (useBand mergeDeg3 useRowBand : Bool) := + xs.toArray.qsort fun a b => + let ma := metricsOf chipMetrics a.1 a.2.1 + let mb := metricsOf chipMetrics b.1 b.2.1 + let da := if mergeDeg3 && ma.maxDeg ≤ 3 then 0 else degClass ma.maxDeg + let db := if mergeDeg3 && mb.maxDeg ≤ 3 then 0 else degClass mb.maxDeg + let ra := if useRowBand then (if rowMap.getD a.1 0 ≤ 16 then 0 else 1) else 0 + let rb := if useRowBand then (if rowMap.getD b.1 0 ≤ 16 then 0 else 1) else 0 + let la := a.2.2.1 + a.2.2.2 + let lb := b.2.2.1 + b.2.2.2 + let za := if useBand then lookupBand la else 0 + let zb := if useBand then lookupBand lb else 0 + if ra != rb then ra < rb + else if da != db then da < db + else if za != zb then za < zb + else if a.2.1 != b.2.1 then a.2.1 < b.2.1 + else if ma.privLifted != mb.privLifted then ma.privLifted < mb.privLifted + else if la != lb then la < lb + else a.1 < b.1 + let denseCap := max maxMembers 64 + if profileRows.isEmpty then + let sorted := sortCands eligible false true false + return existing ++ packAutoGroupBucket "Prog::dense_grp" "Prog::c2_single" sorted + chipMetrics rowMap denseCap 4500 26000 26000 1024 300 250 1800 16 64 0 false true true + else + let mut hot : List (String × Nat × Nat × Nat) := [] + let mut cold : List (String × Nat × Nat × Nat) := [] + let mut uninv : List (String × Nat × Nat × Nat) := [] + for c in eligible do + let r := rowMap.getD c.1 0 + if r == 0 then uninv := c :: uninv + else if r ≤ coldRowCutoff then cold := c :: cold + else hot := c :: hot + let maxColdRows := max 1024 (8 * coldRowCutoff) + let hotGrps := packAutoGroupBucket "Prog::hot_grp" "Prog::c2_hot" + (sortCands hot true false false) chipMetrics rowMap + (min maxMembers 24) 1024 24000 24000 512 150 135 0 2 4 0 true false false + let coldGrps := packAutoGroupBucket "Prog::cold_grp" "Prog::c2_cold" + (sortCands cold false true true) chipMetrics rowMap + denseCap 4500 26000 26000 1024 500 600 2000 32 128 maxColdRows false true true + let uninvGrps := packAutoGroupBucket "Prog::uninv_grp" "Prog::c2_uninv" + (sortCands uninv false true false) chipMetrics rowMap + denseCap 4500 26000 26000 1024 500 600 2000 32 128 0 false true true + return existing ++ hotGrps ++ coldGrps ++ uninvGrps + /-- Collect lowered `Prog` function names marked `FnSchedule.isStatic == true` via `sched.byFun` / `sched.byAddress` for `PartialEval.PEConfig.staticFns`. -/ def resolveStaticFns (src : Src.Program) (P : Fir.Program) @@ -4735,7 +4906,9 @@ def compileTypedPackageIO (l : TypedLinked) (autoGroup : Bool := false) (autoGroupMaxMembers : Nat := 24) (groupPlan? : Option (List (String × List String)) := none) - (vectorize : VectorizeOptions := {}) : IO Compiled := do + (vectorize : VectorizeOptions := {}) + (autoGroupDense : Bool := false) + (autoGroupColdRows : Nat := 64) : IO Compiled := do let t0 ← IO.monoMsNow let cp ← Aiur.Trace.compileAndReplayParTimedIO l.prepared.environment.source l.prepared.entries @@ -4786,9 +4959,16 @@ def compileTypedPackageIO (l : TypedLinked) if vecPinned.isEmpty then pinnedSingles0 else chips.foldl (init := pinnedSingles0) fun s (nm, _, _, _) => if vecPinned.contains nm then s.insert nm else s - pure (if autoGroup then buildAutoGroups artifact.entries chips boundedGroups autoGroupMaxMembers - (chipMetrics := chipMetrics) (pinnedSingletons := pinnedSingles) - (maxMemberConstraintDeg := maxPlanDeg) + pure (if autoGroup then + if autoGroupDense then + buildDenseAutoGroups artifact.entries chips boundedGroups autoGroupMaxMembers + (chipMetrics := chipMetrics) (pinnedSingletons := pinnedSingles) + (maxMemberConstraintDeg := maxPlanDeg) + (profileRows := vectorize.profileRows) (coldRowCutoff := autoGroupColdRows) + else + buildAutoGroups artifact.entries chips boundedGroups autoGroupMaxMembers + (chipMetrics := chipMetrics) (pinnedSingletons := pinnedSingles) + (maxMemberConstraintDeg := maxPlanDeg) else boundedGroups) let physical ← IO.ofExcept (Aiur.Optimized.Physical.prepare artifact) let t3 ← IO.monoMsNow @@ -4851,7 +5031,9 @@ def compileTypedPackageCertifiedIO (l : TypedLinked) (autoGroup : Bool := false) (autoGroupMaxMembers : Nat := 24) (groupPlan? : Option (List (String × List String)) := none) - (vectorize : VectorizeOptions := {}) : IO Compiled := do + (vectorize : VectorizeOptions := {}) + (autoGroupDense : Bool := false) + (autoGroupColdRows : Nat := 64) : IO Compiled := do match maxDegree? with | none => let t0 ← IO.monoMsNow @@ -4911,9 +5093,16 @@ def compileTypedPackageCertifiedIO (l : TypedLinked) if vecPinned.isEmpty then pinnedSingles0 else chips.foldl (init := pinnedSingles0) fun s (nm, _, _, _) => if vecPinned.contains nm then s.insert nm else s - pure (if autoGroup then buildAutoGroups artifact.entries chips boundedGroups autoGroupMaxMembers - (chipMetrics := chipMetrics) (pinnedSingletons := pinnedSingles) - (maxMemberConstraintDeg := maxPlanDeg) + pure (if autoGroup then + if autoGroupDense then + buildDenseAutoGroups artifact.entries chips boundedGroups autoGroupMaxMembers + (chipMetrics := chipMetrics) (pinnedSingletons := pinnedSingles) + (maxMemberConstraintDeg := maxPlanDeg) + (profileRows := vectorize.profileRows) (coldRowCutoff := autoGroupColdRows) + else + buildAutoGroups artifact.entries chips boundedGroups autoGroupMaxMembers + (chipMetrics := chipMetrics) (pinnedSingletons := pinnedSingles) + (maxMemberConstraintDeg := maxPlanDeg) else boundedGroups) let physical ← IO.ofExcept (Aiur.Optimized.Physical.prepare artifact) let t3 ← IO.monoMsNow @@ -5020,9 +5209,16 @@ def compileTypedPackageCertifiedIO (l : TypedLinked) if vecPinned.isEmpty then pinnedSingles0 else chips.foldl (init := pinnedSingles0) fun s (nm, _, _, _) => if vecPinned.contains nm then s.insert nm else s - pure (if autoGroup then buildAutoGroups artifact.entries chips boundedGroups autoGroupMaxMembers - (chipMetrics := chipMetrics) (pinnedSingletons := pinnedSingles) - (maxMemberConstraintDeg := maxPlanDeg) + pure (if autoGroup then + if autoGroupDense then + buildDenseAutoGroups artifact.entries chips boundedGroups autoGroupMaxMembers + (chipMetrics := chipMetrics) (pinnedSingletons := pinnedSingles) + (maxMemberConstraintDeg := maxPlanDeg) + (profileRows := vectorize.profileRows) (coldRowCutoff := autoGroupColdRows) + else + buildAutoGroups artifact.entries chips boundedGroups autoGroupMaxMembers + (chipMetrics := chipMetrics) (pinnedSingletons := pinnedSingles) + (maxMemberConstraintDeg := maxPlanDeg) else boundedGroups) let physical ← IO.ofExcept (Aiur.Optimized.Physical.prepare artifact) let t4 ← IO.monoMsNow @@ -5324,7 +5520,7 @@ private def frontWithHints (env : Ixon.V3.Env) (sidecar : Src.Hints) } } let attempt (cfg : Recheck.Config) : Except Recheck.Err Front := do - let cert ← produceFirAdaptive cfg input opts.inlineAddrs + let cert ← produceFirAdaptive cfg input opts.inlineAddrs opts.dictSpecFirst unless Recheck.checkCanonicalRelevance cfg input cert.table cert.relevance do throw { stage := .relevance, code := "relevance-canonical" message := "certificate relevance annotation does not match canonical annotator output" } @@ -5638,7 +5834,8 @@ def linkTypedWithGuessesIO (src : Src.Program) (P : Fir.Program) (i : Nat) (fuelEraseMin : Nat := FuelErase.depthRowBound) (deadFieldErase : Bool := true) (constFold : Bool := true) - (partialEvalTargeted : Bool := false) : IO TypedLinkedWithGuesses := do + (partialEvalTargeted : Bool := false) + (addrToName : Std.HashMap Ixon.Address String := {}) : IO TypedLinkedWithGuesses := do let logStage (msg : String) : IO Unit := do IO.println msg (← IO.getStdout).flush @@ -5713,18 +5910,18 @@ def linkTypedWithGuessesIO (src : Src.Program) (P : Fir.Program) (i : Nat) if !anyParamFns.isEmpty then logStage s!" any-param-fns: [{", ".intercalate (anyParamFns.take 12)}]" if let some dumpPath ← IO.getEnv "IXCC_DUMP_FIR_DIAG" then - let mut lines : Array String := #["fid\taddr\tgroup\tparams\tany_params\tpoly_size\tbase_size\twork_size\tin_line\tgkey"] + let mut lines : Array String := #["fid\taddr\tlean_name\tgroup\tparams\tany_params\tpoly_size\tbase_size\twork_size\tin_line\tgkey"] for ((fid, fd) : Fir.FunId × Fir.Fun) in PWork.funList do let fsh := cert.fn fid let anyCnt := (fd.params.filter fun p => fsh.var p.1 == .any).length let grp := (resolvedSched.forFun fid (funGroupAddress? src fd)).group.getD "-" - let addrHex := match funGroupAddress? src fd with - | some a => toString a - | none => "-" + let (addrHex, leanNm) := match funGroupAddress? src fd with + | some a => (toString a, addrToName.getD a "-") + | none => ("-", "-") let polySz := match PPoly.fun? fid with | some f => f.body.size | none => 0 let baseSz := match PBase.fun? fid with | some f => f.body.size | none => 0 let isInl := TypedRep.shouldInlineFun PWork resolvedSched fid fd - lines := lines.push s!"f{fid}\t{addrHex}\t{grp}\t{fd.params.length}\t{anyCnt}\t{polySz}\t{baseSz}\t{fd.body.size}\t{isInl}\t{reprStr fd.key}" + lines := lines.push s!"f{fid}\t{addrHex}\t{leanNm}\t{grp}\t{fd.params.length}\t{anyCnt}\t{polySz}\t{baseSz}\t{fd.body.size}\t{isInl}\t{reprStr fd.key}" IO.FS.writeFile dumpPath ("\n".intercalate lines.toList ++ "\n") logStage s!" fir-diag: wrote {lines.size - 1} fns to {dumpPath}" let gl := GuessLower.applyGuesses src PWork lowered0 diff --git a/IxCCAiur/IxCCAiur/Main.lean b/IxCCAiur/IxCCAiur/Main.lean index 620e977105..7f277b6937 100644 --- a/IxCCAiur/IxCCAiur/Main.lean +++ b/IxCCAiur/IxCCAiur/Main.lean @@ -46,6 +46,8 @@ structure Options where skipShapeCheck : Bool := false autoGroup : Bool := false autoGroupMaxMembers : Nat := 24 + autoGroupDense : Bool := false + autoGroupColdRows : Nat := 64 groupPlan : Option String := none schedule : Option String := none noInline : Bool := false @@ -63,6 +65,7 @@ structure Options where anfInlineSize : Option Nat := none anfInlineRounds : Option Nat := none anfMaxSpecs : Option Nat := none + dictSpecFirst : Bool := false fuelErase : Bool := true fuelEraseMin : Nat := FuelErase.depthRowBound fuelEraseMinExplicit : Bool := false @@ -200,6 +203,11 @@ def parse : List String → Options → Except String Options | "--skip-aiur-eval" :: rest, o => parse rest { o with skipAiurEval := true } | "--skip-shape-check" :: rest, o => parse rest { o with skipShapeCheck := true } | "--auto-group" :: rest, o => parse rest { o with autoGroup := true } + | "--auto-group-dense" :: rest, o => parse rest { o with autoGroup := true, autoGroupDense := true } + | "--auto-group-cold-rows" :: nStr :: rest, o => + match nStr.toNat? with + | some n => parse rest { o with autoGroup := true, autoGroupDense := true, autoGroupColdRows := n } + | none => .error s!"invalid --auto-group-cold-rows '{nStr}' (expected natural number)" | "--auto-group-max-members" :: nStr :: rest, o => match nStr.toNat? with | some n => @@ -246,6 +254,7 @@ def parse : List String → Options → Except String Options match nStr.toNat? with | some n => parse rest { o with anfMaxSpecs := some n } | none => .error s!"invalid --anf-max-specs '{nStr}' (expected natural number)" + | "--dict-spec" :: rest, o => parse rest { o with dictSpecFirst := true } | "--no-fuel-erase" :: rest, o => parse rest { o with fuelErase := false } | "--fuel-erase-min" :: nStr :: rest, o => match nStr.toNat? with @@ -703,8 +712,12 @@ def runTyped (o : Options) (front : Driver.Front) (baseSched : Schedule.CircuitS let comp := o.compression let (linked, advice?, firWork) ← if o.enableGuesses then + let addrToName : Std.HashMap Ixon.Address String := + match IxCC.Src.AutoHints.extractNamedMap front.input.env with + | .ok nmMap => nmMap.fold (init := {}) fun m nm a => m.insert a nm + | .error _ => {} let res ← Driver.linkTypedWithGuessesIO front.levels.src fir 0 sched - o.inlineFuse o.partialEval o.fieldLower .goldilocks comp o.fuelErase o.fuelEraseMin o.deadFieldErase o.constFold o.partialEvalTargeted + o.inlineFuse o.partialEval o.fieldLower .goldilocks comp o.fuelErase o.fuelEraseMin o.deadFieldErase o.constFold o.partialEvalTargeted addrToName let chs := res.manifest.channels.map (·.channel) IO.println s!"guesses: rewritten {res.resolved.length} ({chs}), skipped {res.skipped.length}" for (cid, reason) in res.skipped do @@ -878,9 +891,11 @@ def runTyped (o : Options) (front : Driver.Front) (baseSched : Schedule.CircuitS if o.certifiedCompile || o.certifiedBuild then Driver.compileTypedPackageCertifiedIO linked sched kind (o.args.getD []) o.maxDegree o.logBlowup o.autoGroup o.autoGroupMaxMembers groupPlan? vecOpts + o.autoGroupDense o.autoGroupColdRows else Driver.compileTypedPackageIO linked sched kind (o.args.getD []) o.degreeBudget o.logBlowup o.autoGroup o.autoGroupMaxMembers groupPlan? vecOpts + o.autoGroupDense o.autoGroupColdRows let elapsed := (← IO.monoMsNow) - start if o.certifiedBuild && !compiled.certifiedArtifact then IO.eprintln "ixcc-aiur: --certified-build requires an ArtifactValid-certified compile; no package written" @@ -973,6 +988,7 @@ def run (o : Options) : IO UInt32 := do anfInlineSize := o.anfInlineSize anfInlineRounds := o.anfInlineRounds anfMaxSpecs := o.anfMaxSpecs + dictSpecFirst := o.dictSpecFirst } let limits := Driver.admissionLimitsFor o.maxIxeBytes let start ← IO.monoMsNow diff --git a/IxCCAiur/IxCCAiur/PolyFunSpecialize.lean b/IxCCAiur/IxCCAiur/PolyFunSpecialize.lean index 4b30324541..67a374355a 100644 --- a/IxCCAiur/IxCCAiur/PolyFunSpecialize.lean +++ b/IxCCAiur/IxCCAiur/PolyFunSpecialize.lean @@ -1466,7 +1466,7 @@ end private def extractLocalSig (m : MonoMeta) (st : LocalFlow) (fuel id : Nat) : SigTag := st.uf.extractSig m fuel id -private abbrev RetCache := Std.HashMap (FunId × String) SigTag +private abbrev RetCache := Std.HashMap (FunId × String) (Nat × SigTag) private def extractLocalArgSig (m : MonoMeta) (st : LocalFlow) : Arg → SigTag | .var z => match st.slots[LocalSlot.var z]? with @@ -1553,10 +1553,12 @@ private def finalizeLocalFlow (m : MonoMeta) (f : FunId) (fd : Fun) /-- Normalize call-site `argSigs` through `fd`'s intra-function variable/container flow and bounded memoized polymorphic callee return propagation, returning -`(normalizedArgSigs, varSigMap, retSig, updatedRetCache)`. -/ -private def analyzePolyCallRec (P : Program) (m : MonoMeta) +`(normalizedArgSigs, varSigMap, retSig, updatedRetCache)`. +Tracks `active` call keys to break mutual recursion cycles and caches `(depth, retSig)` +at every depth so repeated non-concrete calls never trigger exponential re-traversal. -/ +private def analyzePolyCallRecAux (P : Program) (m : MonoMeta) (smallPoly : Std.HashSet FunId) (monoFields : MonoFieldSigs) - (effRetSigs : Std.HashMap FunId SigTag) : + (effRetSigs : Std.HashMap FunId SigTag) (active : Std.HashSet (FunId × String)) : Nat → FunId → Fun → List SigTag → RetCache → List SigTag × Std.HashMap Var SigTag × SigTag × RetCache | 0, f, fd, argSigs, cache0 => @@ -1571,13 +1573,22 @@ private def analyzePolyCallRec (P : Program) (m : MonoMeta) | none => (.bot, c0) | some fdG => let key := (g, SigTag.encodeList gArgSigs) - match c0[key]? with - | some cached => (cached, c0) - | none => - let (_, _, rSig, c1) := - analyzePolyCallRec P m smallPoly monoFields effRetSigs d g fdG gArgSigs c0 - let c2 := if rSig.isConcrete 12 || decide (d ≥ 3) then c1.insert key rSig else c1 - (rSig, c2) + if active.contains key then + (effRetSigs.getD g (m.shapeSeed (m.cert.fn g).ret), c0) + else + match c0[key]? with + | some (cd, cached) => + if cached.isConcrete 12 || decide (cd ≥ d) then + (cached, c0) + else + let (_, _, rSig, c1) := + analyzePolyCallRecAux P m smallPoly monoFields effRetSigs (active.insert key) d g fdG gArgSigs c0 + let bestSig := if rSig.isConcrete 12 then rSig else cached + (bestSig, c1.insert key (max cd d, bestSig)) + | none => + let (_, _, rSig, c1) := + analyzePolyCallRecAux P m smallPoly monoFields effRetSigs (active.insert key) d g fdG gArgSigs c0 + (rSig, c1.insert key (d, rSig)) else (effRetSigs.getD g (m.shapeSeed (m.cert.fn g).ret), c0) let (st1, c1) := localCallPropCode m f onCallee fd.body (st0, cache0) @@ -1589,6 +1600,15 @@ private def analyzePolyCallRec (P : Program) (m : MonoMeta) let (normSigs, varMap, retSig) := finalizeLocalFlow m f fd st3' (normSigs, varMap, retSig, c3) +private def analyzePolyCallRec (P : Program) (m : MonoMeta) + (smallPoly : Std.HashSet FunId) (monoFields : MonoFieldSigs) + (effRetSigs : Std.HashMap FunId SigTag) + (depth : Nat) (f : FunId) (fd : Fun) (argSigs : List SigTag) (cache0 : RetCache) : + List SigTag × Std.HashMap Var SigTag × SigTag × RetCache := + let key := (f, SigTag.encodeList argSigs) + analyzePolyCallRecAux P m smallPoly monoFields effRetSigs (({} : Std.HashSet (FunId × String)).insert key) + depth f fd argSigs cache0 + /-- Whether `normSigs` concretizes at least one polymorphic/polluted parameter of `g`. -/ private def hasConcreteGain (m : MonoMeta) (g : FunId) (fd : Fun) (normSigs : List SigTag) : Bool := let gsh := m.cert.fn g diff --git a/IxCCAiur/IxCCAiur/PolyShapeInfer.lean b/IxCCAiur/IxCCAiur/PolyShapeInfer.lean index 36df0560e1..2496ed6e37 100644 --- a/IxCCAiur/IxCCAiur/PolyShapeInfer.lean +++ b/IxCCAiur/IxCCAiur/PolyShapeInfer.lean @@ -319,6 +319,7 @@ private structure PolyCx where widen : Bool f : FunId jps : Src.NatMap (List Var) + paramList : List Var := [] private def fastClassify (srcKindMap : Std.HashMap IxCC.Src.CId IxCC.Fir.ShapeInfer.Kind) : IxCC.Key.CtorKey → IxCC.Fir.ShapeInfer.Kind @@ -425,11 +426,34 @@ private def polyRhsShapeFast (cx : PolyCx) (w : PolyW) (lhs : Var) : Rhs → Opt if σ.le .nat && cx.base.P.known.natSucc == some c && i == 0 then (some .nat, w) else (some .any, w) | .prim op as => + -- If a non-numeric shape (`.data`/`.enum`/`.irr`) reaches a numeric primitive + -- (e.g., in an unreachable arm of a defunctionalized `apply_k` dispatcher), + -- widen that operand (and matching function parameter) to `.any` so + -- `TypedLower` coerces through `.obj` instead of rejecting `.data -> .nat`. + let w1 := as.foldl (init := w) fun acc a => + match a with + | .var v => + match acc.vm.get? v with + | some (.data _) | some (.enum _) | some .irr => + let (vm', ch1) := setVar cx.widen acc.vm v (some .any) + let st1 := acc.st.touch ch1 + let st2 := match cx.paramList.findIdx? (· == v) with + | some idx => + if hf : cx.f < st1.params.size then + let cur := st1.params[cx.f] + let next := cur.set idx (some .any) + if next == cur then st1 + else { st1 with params := st1.params.set cx.f next, changed := true } + else st1 + | none => st1 + { vm := vm', st := st2 } + | _ => acc + | _ => acc if IxCC.Fir.Shape.isBoolPrim op then match cx.base.boolEnum with - | some ind => (some (.enum ind), w) - | none => (some .any, w) - else ((argShapes? w.vm as).map (IxCC.Fir.Shape.primShape op), w) + | some ind => (some (.enum ind), w1) + | none => (some .any, w1) + else ((argShapes? w1.vm as).map (IxCC.Fir.Shape.primShape op), w1) | .call g as => let ret? := (w.st.rets[g]?).getD none (ret?, callArgsFast cx.widen w g as) @@ -461,10 +485,11 @@ private def polyGoOptFast (cx : PolyCx) : Option Code → PolyW → PolyW end private def polyFunPassFast (cxBase : PolyCxBase) (widen : Bool) (st : PolySt) (fi : FunInfo) : PolySt := - let cx : PolyCx := { base := cxBase, widen, f := fi.f, jps := fi.jps } + let paramList := fi.fd.params.map (·.1) + let cx : PolyCx := { base := cxBase, widen, f := fi.f, jps := fi.jps, paramList } let curVm := st.vars.getD fi.f .leaf let curPs := st.params.getD fi.f [] - let (vm, ch) := paramVars widen (fi.fd.params.map (·.1)) curPs (curVm, false) + let (vm, ch) := paramVars widen paramList curPs (curVm, false) let w := polyGoCodeFast cx fi.fd.body { vm, st := st.touch ch } if hf : fi.f < w.st.vars.size then { w.st with vars := w.st.vars.set fi.f w.vm } diff --git a/IxCK/Resource/Check.lean b/IxCK/Resource/Check.lean index 5501b369cb..3757ff6a57 100644 --- a/IxCK/Resource/Check.lean +++ b/IxCK/Resource/Check.lean @@ -247,7 +247,7 @@ def callResult (ifc : Iface) (avs : Array (Option AVal)) (w : String) : CM AVal let d := destOf p lendPlain flowTo d p.skel a w -- a unique result drops the arguments' regions (`pure { base with own := .uniq }`), and - -- an extern (whose body is not checked) may retain a `.many` argument in a `@shared` + -- an extern (whose body is not checked) may retain a `.many` argument in a `@[shared]` -- field of a fresh unique cell (`ExternFieldVal` permits `p.mode = .many` arguments): -- any retained `val` argument must be unconfined (repair U; under finalized L1 a `leaf` -- is never confined, W6) @@ -464,7 +464,7 @@ def anCtor (nP : Nat) (fields : Array Field) (avs : Array (Option AVal)) (c : Cl unless Skel.unknown.admits v.skel do refuseM "mode skeletons differ: a moded closure stored in a cell" regs := natUnion regs v.regs if f.fmode == .shared then - unless (v.regs.filter (· != 1)).isEmpty do refuseM "borrowEscape: a borrowed value stored in a @shared field" + unless (v.regs.filter (· != 1)).isEmpty do refuseM "borrowEscape: a borrowed value stored in a @[shared] field" flowTo .share v.skel v "a shared field" else if v.cls == .val then -- a once binding stored in a cell can be read out and called again (repair Q) @@ -481,7 +481,7 @@ def anCtor (nP : Nat) (fields : Array Field) (avs : Array (Option AVal)) (c : Cl /-- A projection, as `runR`'s: an erased field is refused; a trivial wrapper is its field; a leaf is a counted value of its own; any other `.val` field (including -`@shared`) aliases its container's deps and shares its confinement. -/ +`@[shared]`) aliases its container's deps and shares its confinement. -/ def anProj (P : Prog) (s : Ref) (i : Nat) (v : AVal) (c : Cls) : CM AVal := do let fields : Array Field := match (P.ctorsOf s)[0]? with | some ctor => match P.ctorOf? ctor with @@ -491,10 +491,10 @@ def anProj (P : Prog) (s : Ref) (i : Nat) (v : AVal) (c : Cls) : CM AVal := do let some f := fields[i]? | return { cls := c } if f.mode == .erased then refuseM "erasedRead: an erased field is projected" if f.cls == .irr || c == .irr then return { cls := .irr } - -- under L1 a leaf is never confined (whether read out of a cell, a `@shared` field, or a wrapper) + -- under L1 a leaf is never confined (whether read out of a cell, a `@[shared]` field, or a wrapper) if c == .imm || c == .leaf then return { cls := c } if v.cls != .val then return { v with cls := c, src := none } - -- a `@shared` field holds its value as it was stored, and a callee or an extern may have stored + -- a `@[shared]` field holds its value as it was stored, and a callee or an extern may have stored -- a confined or borrowed-arg-dependent value there (findings 18, 5; pre-proof fix 12): it keeps -- both the container's deps and its regions (repair P + fix 12) pure { cls := c, deps := v.deps, regs := v.regs, skel := .unknown } @@ -791,7 +791,7 @@ first caller has open, with no region and no return rule of its own, and shares its value, which a caller's `anCall` takes as unconfined. So its result mode is `shared` (note 12 §4, B.15, V6): then the return rule below, at its region with no parameter, leaves its value confined to no region. As landed any result mode -was read: a static with a `@borrowed` result could return a value its run +was read: a static with a `@[borrowed]` result could return a value its run confines to its first caller's region. `readBody` gives a body without λs the result mode `shared`, so this refuses only programs built otherwise. -/ def anDef (P : Prog) (fuel : Nat) (params : Array Param) (res : ResultMode) (rc : Cls) (rs : Skel) diff --git a/IxCK/Resource/Eval.lean b/IxCK/Resource/Eval.lean index a82f30d0f3..92dae00aef 100644 --- a/IxCK/Resource/Eval.lean +++ b/IxCK/Resource/Eval.lean @@ -15,7 +15,7 @@ references to heap cells; a reference carries the capability it was issued * **Borrows as regions.** Entering a call, a closure, a `let` or a case alternative opens a region; a value bound at a borrowed binder is confined to it, and a value read out of a confined container is confined with it (a leaf - or a `@shared` field excepted). A value confined to a region that is closing, + or a `@[shared]` field excepted). A value confined to a region that is closing, returned or let-bound past it, is `borrowEscape`, and so is the unique transfer of a value confined to an open region, except into a borrowed binder. * **Erasure.** Evaluating a binding of mode `erased`, or projecting an erased @@ -271,7 +271,7 @@ def Cell.setSlot : Cell → Nat → Val → Cell /-- **The ownership closure**: the slots of a cell that a unique transfer of the cell transfers with it. Deep: a constructor's `inherited` fields, a closure's captures, a partial application's arguments, a once view's target. It stops at -`@shared` fields, immediates and leaves (`renew`). One definition, so a +`@[shared]` fields, immediates and leaves (`renew`). One definition, so a different closure (a spine rule, say) is a change here. -/ def ownedSlots (P : Prog) : Cell → List Nat | .ctor r fields => @@ -338,7 +338,7 @@ def ret (P : Prog) (fuel s cur : Nat) (r : ResultMode) (c : Cls) (v : Val) : M V pure (renameTaint s cur v) /-- A value read out of a container confined to `t`: confined with it, unless -the field is `@shared` (`inherit = false`). A leaf read out of a container is a +the field is `@[shared]` (`inherit = false`). A leaf read out of a container is a counted reference of its own, confined to nothing. -/ def readOut (inherit : Bool) (t : List Nat) (v : Val) : M Val := do if ← isLeaf v then diff --git a/IxCK/Resource/Proof/DefaultOk.lean b/IxCK/Resource/Proof/DefaultOk.lean index 5d69e8fd56..e93a8834c0 100644 --- a/IxCK/Resource/Proof/DefaultOk.lean +++ b/IxCK/Resource/Proof/DefaultOk.lean @@ -10,7 +10,7 @@ and admissible inputs (`InputsOk P h params args`), never ends in a mode violation at any fuel. In an all-default program, no binder is erased, unique, borrowed, or once, no -result mode is unique or borrowed, no constructor field is erased or `@shared`, +result mode is unique or borrowed, no constructor field is erased or `@[shared]`, and no `.once` cell is ever allocated. Every heap write is append-only (preserving all existing cells and capabilities), every value in the heap, environments, statics, and strings is live and untainted (`ValOk`), and no monitor in `Eval.lean` diff --git a/IxCK/Resource/Proof/F4CallBridge.lean b/IxCK/Resource/Proof/F4CallBridge.lean index c72bd5afd0..8195da4fa1 100644 --- a/IxCK/Resource/Proof/F4CallBridge.lean +++ b/IxCK/Resource/Proof/F4CallBridge.lean @@ -2189,7 +2189,7 @@ theorem pap_iface_funOk {P : Prog} {ext : ExternOracle} {B : Nat} (fun h => let hu := huniqG h; ⟨hu.1, fun l hor => (hu.2 l hor).2⟩) hnoArgG /-- General `FunOkAt .unknown false False` for a runtime `.pap r out` cell of ANY constructor -`P.find? r = some (.ctor ind cidx nP fields)` (including constructors with `@shared`/`@erased` +`P.find? r = some (.ctor ind cidx nP fields)` (including constructors with `@[shared]`/`@[erased]` fields). Proved by strong induction on `B_call`. -/ theorem pap_ctor_funOk {P : Prog} {ext : ExternOracle} : ∀ {B_call : Nat} {st₀ : St} {loc cap : Nat} {t₀ : List Nat} @@ -4047,8 +4047,8 @@ theorem applyAllS_bridge {P : Prog} {ext : ExternOracle} : /-- Source-tracking invariant on an abstract value produced between `σ₀` and `σ₁`: if `av.src = some x`, either `x` is a non-erased in-scope binding in `aenv` with matching -`onceOnly` and `deps`, or `x` was freshly allocated at `≥ σ₀.st.size` and if `@once`, any -old `@once` dependency `< σ₀.st.size` carried by `av` has already been marked `spent`. -/ +`onceOnly` and `deps`, or `x` was freshly allocated at `≥ σ₀.st.size` and if `@[once]`, any +old `@[once]` dependency `< σ₀.st.size` carried by `av` has already been marked `spent`. -/ def SrcOk (Scope : Nat → Prop) (aenv : List ABnd) (σ₀ σ₁ : AState) (av : AVal) : Prop := ∀ x, av.src = some x → (∃ i ab, Scope i ∧ aenv[i]? = some ab ∧ ab.mode ≠ .erased ∧ ab.id = x ∧ diff --git a/IxCK/Resource/Proof/F4Eval.lean b/IxCK/Resource/Proof/F4Eval.lean index da466d20ef..a8aac8a4ae 100644 --- a/IxCK/Resource/Proof/F4Eval.lean +++ b/IxCK/Resource/Proof/F4Eval.lean @@ -12,9 +12,9 @@ Key design points: 1. **Invariant `Interp` (`I`)**: carrying `hIZero : ∀ r, σ.nextRegion ≤ r → I.reg r = []` keeps the **exact same `I`** across every term step, making `ArgListOk_push` compose with zero adapters and giving `RegUnique (I.extend s_a s_c) σ_body s_a s_c` in 4 lines. -2. **Taint safety for spent `@once` bindings (`EnvTaintOk`)**: tracks +2. **Taint safety for spent `@[once]` bindings (`EnvTaintOk`)**: tracks `(∀ c ∈ b.val.taint, c < st.nextRegion) ∧ OpenUnder st.regions (I.regsOf (effVal ab).regs) b.val` - for every non-erased binding in scope (even after `@once` spending), guaranteeing + for every non-erased binding in scope (even after `@[once]` spending), guaranteeing `confinedTo s_c rv = false` at `ATerm.letVal` exit without changing `VSim`/`Sim`. 3. **Pure static monotonicity (`ATerm_state_le`)**: proves `AStateOk σ' ∧ AStateLe σ σ' ∧ σ'.regions = σ.regions` ahead of time so `NoKillOk`/`NoSpendOk`/`BadDep` pull back cleanly @@ -28,7 +28,7 @@ open IxCK.Resource Ixon /-! ## 1. `EnvTaintOk`, `Interp` Congruence, and Restriction Helpers -/ /-- Taint-bounding and open-region confinement for every non-erased binding in scope -(holds even after `@once` bindings become spent). -/ +(holds even after `@[once]` bindings become spent). -/ def EnvTaintOk (Scope : Nat → Prop) (env : List Bnd) (aenv : List ABnd) (st : St) (I : Interp) : Prop := ∀ (i : Nat) (b : Bnd) (ab : ABnd), Scope i → env[i]? = some b → aenv[i]? = some ab → diff --git a/IxCK/Resource/Proof/F4Inv.lean b/IxCK/Resource/Proof/F4Inv.lean index e00ac4c86c..a3df574478 100644 --- a/IxCK/Resource/Proof/F4Inv.lean +++ b/IxCK/Resource/Proof/F4Inv.lean @@ -244,7 +244,7 @@ theorem PreservesOnceShell.of_setObj_once {h : Heap} {loc : Nat} {o : Obj} {t₁ rw [Array.set!_eq_setIfInBounds, Array.getElem?_setIfInBounds_ne (Ne.symm heq)] exact ho₁ -/-- Safe shell invariant for a (possibly spent) `@once` binding: either `.imm .irr` or a live +/-- Safe shell invariant for a (possibly spent) `@[once]` binding: either `.imm .irr` or a live reference to a `.once` cell whose own capability still matches. -/ def SpentOnceSafe (h : Heap) (v : Val) : Prop := v = .imm .irr ∨ @@ -1679,16 +1679,16 @@ def ValidDeps (σ : AState) (deps : List Nat) : Prop := def LiveDeps (σ : AState) (NoKill : Nat → Prop) (deps : List Nat) : Prop := ∀ d ∈ deps, σ.st[d]? = some .live ∧ ¬ NoKill d -/-- `av` was read directly from a `@once` binding. -/ +/-- `av` was read directly from a `@[once]` binding. -/ def IsOnceSrc (σ : AState) (av : AVal) : Prop := ∃ id, av.src = some id ∧ σ.once[id]? = some true /-- `av` is currently eligible for a unique transfer (`.val`, `.uniq`, not once-only or read from a -`@once` binding, and all deps `.live` & killable). -/ +`@[once]` binding, and all deps `.live` & killable). -/ def Transferable (σ : AState) (NoKill : Nat → Prop) (av : AVal) : Prop := av.cls = .val ∧ av.own = .uniq ∧ av.onceOnly = false ∧ ¬ IsOnceSrc σ av ∧ LiveDeps σ NoKill av.deps -/-- Every `@once` binding id in `deps` is still unspent. -/ +/-- Every `@[once]` binding id in `deps` is still unspent. -/ def UnspentOnceDeps (σ : AState) (deps : List Nat) : Prop := ∀ d ∈ deps, σ.once[d]? = some true → σ.spent[d]? = some false @@ -1696,7 +1696,7 @@ def UnspentOnceDeps (σ : AState) (deps : List Nat) : Prop := def effVal (ab : ABnd) : AVal := { ab.val with deps := ab.id :: ab.val.deps.filter (· != ab.id), src := some ab.id } -/-- Whether `av` is actively live (no `.dead` deps, and if read from a `@once` binding, still unspent). -/ +/-- Whether `av` is actively live (no `.dead` deps, and if read from a `@[once]` binding, still unspent). -/ def ActiveVal (σ : AState) (av : AVal) : Prop := ValidDeps σ av.deps ∧ (IsOnceSrc σ av → UnspentOnceDeps σ av.deps) diff --git a/IxCK/Resource/Proof/F4OpsBridge.lean b/IxCK/Resource/Proof/F4OpsBridge.lean index 158288c6b0..ab96dcefd4 100644 --- a/IxCK/Resource/Proof/F4OpsBridge.lean +++ b/IxCK/Resource/Proof/F4OpsBridge.lean @@ -208,7 +208,7 @@ theorem OwnTreeFull_of_sameLoc {P : Prog} {h : Heap} {v₁ v₂ : Val} /-! ## 1. Bridge 1 (`var_bridge`) & Bridge 2 (`proj_bridge`) -/ /-- **Bridge 1 (`var_bridge`)**: simulates `ATerm.var` (`readVar` + class cast `c`) against -`live b.val >>= fun _ => conform c b.val`, handling both active and spent `@once` bindings. -/ +`live b.val >>= fun _ => conform c b.val`, handling both active and spent `@[once]` bindings. -/ theorem var_bridge {P : Prog} {ext : ExternOracle} {B : Nat} {st : St} {Frame NoKill NoSpend Scope : Nat → Prop} {env : List Bnd} {aenv : List ABnd} {σ σ₁ : AState} {I : Interp} @@ -430,7 +430,7 @@ theorem var_bridge {P : Prog} {ext : ExternOracle} {B : Nat} {st : St} rcases hreach' l hr with hge | hr₁ · exact Or.inl hge · exact Or.inr ⟨b, hbi, hr₁⟩ - · -- Spent `@once` binding (`¬ ActiveVal σ (effVal ab)` with `ValidDeps σ (effVal ab).deps`) + · -- Spent `@[once]` binding (`¬ ActiveVal σ (effVal ab)` with `ValidDeps σ (effVal ab).deps`) have his : IsOnceSrc σ (effVal ab) := Classical.byContradiction fun hnot => hact ⟨hvd, fun h => absurd h hnot⟩ have hsp : SpentOnceSafe st.heap b.val := hvB.2.2.2.1 hvd his @@ -4818,7 +4818,7 @@ private theorem caseField_basic {P : Prog} {k : CaseInfo} {fields : Array Field} fun h => absurd h hnat, fun _ => ⟨herF.symm, fun h => absurd h hmodeNe⟩⟩ /-- **Bridge 8 (`select_caseAltArgs_bridge`)**: simulates `Eval.select P k mv` against -`ModeOk.caseAltArgs P k av_mv consuming cidx ca`, handling both active and spent `@once` +`ModeOk.caseAltArgs P k av_mv consuming cidx ca`, handling both active and spent `@[once]` scrutinees across all 4 `select_spec` branches (`Nat`, all-`irr`, `wrapperCase`, `.ctor`), producing exact erased-flag parity and `ArgListOk` for the alternative's field arguments. -/ theorem select_caseAltArgs_bridge {P : Prog} {ext : ExternOracle} {B : Nat} diff --git a/IxCK/Resource/Proof/F4Rules.lean b/IxCK/Resource/Proof/F4Rules.lean index a9e0bf7e9f..b3cc4664c5 100644 --- a/IxCK/Resource/Proof/F4Rules.lean +++ b/IxCK/Resource/Proof/F4Rules.lean @@ -1278,7 +1278,7 @@ private theorem bindAt_val_flat (P : Prog) (fuel s : Nat) (m : BinderMode) (v : dsimp only exact htail p₂.1 p₂.2 -/-- Helper: when `bindAt` binds at a `@once` mode with class `.val`, it does not transfer and +/-- Helper: when `bindAt` binds at a `@[once]` mode with class `.val`, it does not transfer and directly wraps `base` (with `SameLoc v base`) in a fresh `.once` cell at `st.heap.objs.size`. -/ theorem bindAt_once_val_sameLoc {P : Prog} {fuel s : Nat} {m : BinderMode} {v : Val} {st : St} (hm : m.usage = .once) (hdl : DeepLive st.heap v) : diff --git a/IxCK/Resource/Proof/Heap.lean b/IxCK/Resource/Proof/Heap.lean index 905ace9889..f88f4221d1 100644 --- a/IxCK/Resource/Proof/Heap.lean +++ b/IxCK/Resource/Proof/Heap.lean @@ -683,7 +683,7 @@ def OpenUnder (openRegs allowed : List Nat) (v : Val) : Prop := def DeepOpenUnder (h : Heap) (openRegs allowed : List Nat) (v : Val) : Prop := ∀ w, HeldBy h v w → OpenUnder openRegs allowed w -/-- Ownership tree with non-owned-slot (`@shared` `.ctor` field) disjointness (alias for +/-- Ownership tree with non-owned-slot (`@[shared]` `.ctor` field) disjointness (alias for `Statement.lean`'s `OwnTree`, which already includes both clauses). -/ abbrev OwnTreeFull (P : Prog) (h : Heap) (v : Val) : Prop := OwnTree P h v @@ -2010,7 +2010,7 @@ theorem OwnTree_disjoint_slots {P : Prog} {h : Heap} {loc cap i j x : Nat} exact ih p1 d2 hpp1 hpp2 /-- If `w` is an owned slot disjoint from `svi`'s `OwnReach`, then `Reach h w` is - completely disjoint from `OwnReach P h svi` (using `OwnTreeFull` for `@shared` fields). -/ + completely disjoint from `OwnReach P h svi` (using `OwnTreeFull` for `@[shared]` fields). -/ theorem OwnTreeFull_reach_disjoint_of_ownReach_disjoint {P : Prog} {h : Heap} {v svi u : Val} {l : Nat} (ht : OwnTreeFull P h v) @@ -2076,7 +2076,7 @@ theorem OwnTreeFull_reach_disjoint_of_ownReach_disjoint hrl /-- Under `OwnTreeFull` + `AcyclicFrom`, for any owned slot `i` (`slot? i = some svi`) - and any other value `w` held at slot `j ≠ i` (owned OR `@shared`), `Reach h w` is + and any other value `w` held at slot `j ≠ i` (owned OR `@[shared]`), `Reach h w` is completely disjoint from `OwnReach P h svi`. -/ theorem OwnTreeFull_other_slot_disjoint {P : Prog} {h : Heap} {loc cap i j l : Nat} {t : List Nat} {o : Obj} {svi w : Val} diff --git a/IxCK/Resource/Proof/Ops.lean b/IxCK/Resource/Proof/Ops.lean index 2c96c3df6d..e6de8d06b9 100644 --- a/IxCK/Resource/Proof/Ops.lean +++ b/IxCK/Resource/Proof/Ops.lean @@ -297,7 +297,7 @@ theorem alloc_ownReach_new {P : Prog} {h : Heap} {c : Cell} {t : List Nat} {l : /-- Generic `OwnTreeFull` for a freshly allocated non-num cell whose owned slots hold pairwise `OwnReach`/`Reach`-disjoint acyclic `OwnTreeFull` values and (when `.ctor`) -whose non-owned (`@shared`) fields are disjoint from all owned slots' `OwnReach`. -/ +whose non-owned (`@[shared]`) fields are disjoint from all owned slots' `OwnReach`. -/ theorem alloc_ownTreeFull {P : Prog} {h : Heap} {c : Cell} {t : List Nat} (hsub : ∀ u ∈ c.vals, DeepLive h u ∧ AcyclicFrom h u) (hnn : c.isNum = false ∨ natClass ≠ .leaf) diff --git a/IxCK/Resource/Statement.lean b/IxCK/Resource/Statement.lean index e90fc1484c..202c6b1ea1 100644 --- a/IxCK/Resource/Statement.lean +++ b/IxCK/Resource/Statement.lean @@ -189,7 +189,7 @@ inductive OwnReach (P : Prog) (h : Heap) : Val → Nat → Prop OwnReach P h v l → OwnReach P h (.ref loc cap t) l /-- `v`'s ownership closure is a tree: no cell of it (a leaf excepted) is held -by two owned slots in it, nor reachable through any non-owned (`@shared`) field +by two owned slots in it, nor reachable through any non-owned (`@[shared]`) field of a constructor cell in it. -/ def OwnTree (P : Prog) (h : Heap) (v : Val) : Prop := (∀ (p₁ p₂ i₁ i₂ l c₁ c₂ : Nat) (o₁ o₂ : Obj) (t₁ t₂ : List Nat), diff --git a/IxCK/Resource/Syntax.lean b/IxCK/Resource/Syntax.lean index fce6cc82a3..635716498a 100644 --- a/IxCK/Resource/Syntax.lean +++ b/IxCK/Resource/Syntax.lean @@ -108,7 +108,7 @@ def admits : Skel → Skel → Bool | d, s => d.isDefault && s.isDefault /-- Like `admits`, except `.unknown` does not admit an `.arrow` (used where a -value may be `onceOnly` or passed to a `@once` position). -/ +value may be `onceOnly` or passed to a `@[once]` position). -/ def admitsNA : Skel → Skel → Bool | .unknown, .arrow .. | .arrow .., .unknown => false | .unknown, s => s.isDefault diff --git a/ModeRepairTests/DiffTest/DESIGN.md b/ModeRepairTests/DiffTest/DESIGN.md index 2f3fc770d5..ae0b91d14d 100644 --- a/ModeRepairTests/DiffTest/DESIGN.md +++ b/ModeRepairTests/DiffTest/DESIGN.md @@ -12,7 +12,7 @@ is interpreted, as `Findings.lean` was. Jobs go through `run.sh MT-dt-*`, capped - `E`, two field-less constructors (imm); - `L` = List Nat, `LF` = List (Nat → Nat) (val, two constructors); - `B`, one inherited `L` field; - - `S`, one `@shared` `L` field; + - `S`, one `@[shared]` `L` field; - `K`, an erased `L` field and a `Nat` field; - `P`, two `Nat` fields; - `W`, a one-field wrapper of `Nat` (leaf); diff --git a/ModeRepairTests/DiffTest/Gen.lean b/ModeRepairTests/DiffTest/Gen.lean index ee582ea5d4..33bf1da2a2 100644 --- a/ModeRepairTests/DiffTest/Gen.lean +++ b/ModeRepairTests/DiffTest/Gen.lean @@ -317,7 +317,7 @@ def boxCasesTy : Ty := .arr .many .shared .box (.arr .many .shared (.arr .many . def helperDefs : List (Ref × RunDef) := [ (addP, .prim .add), - -- consume (@unique xs : List Nat) : Nat := 0 + -- consume (@[unique] xs : List Nat) : Nat := 0 (consumeR, .body #[Ty.list.param .unique] .shared .leaf .data (.natLit 0)), -- len (xs : List Nat) : Nat := match xs with | [] => 0 | _ :: t => len t + 1 (lenR, .body #[Ty.list.param .many] .shared .leaf .data diff --git a/ModeRepairTests/DiffTest/Hyp.lean b/ModeRepairTests/DiffTest/Hyp.lean index 0e335f3241..278ab112c9 100644 --- a/ModeRepairTests/DiffTest/Hyp.lean +++ b/ModeRepairTests/DiffTest/Hyp.lean @@ -122,7 +122,7 @@ def argOk (P : Prog) (h : Heap) (p : Param) (a : Val) : Bool := /-- `OwnTree`: no location is held by two distinct owned slots inside `v`'s ownership closure (a leaf location excepted), nor reachable through any non-owned -(`@shared`) field of a constructor cell in `v`'s ownership closure. -/ +(`@[shared]`) field of a constructor cell in `v`'s ownership closure. -/ def ownTree (P : Prog) (h : Heap) (v : Val) : Bool := Id.run do let owned := (ownSet P h walkFuel v).eraseDups let mut seen : List (Nat × Nat × Nat) := [] -- (target, holder, slot) diff --git a/ModeRepairTests/DiffTest/Main.lean b/ModeRepairTests/DiffTest/Main.lean index c7e6dbd9b5..40dacd953e 100644 --- a/ModeRepairTests/DiffTest/Main.lean +++ b/ModeRepairTests/DiffTest/Main.lean @@ -624,12 +624,12 @@ def mapBodies (f : Term → Term) (P : Prog) : Prog := | .body ps res rc rs t => .body ps res rc rs (f t) | d => d) } -/-- Finding 18's knockout: `SBox`'s field inherited instead of `@shared`. -/ +/-- Finding 18's knockout: `SBox`'s field inherited instead of `@[shared]`. -/ def sboxInherited (P : Prog) : Prog := { P with defs := P.defs.map fun (r, d) => if r == sboxC then (r, .ctor sboxI 0 0 #[fieldOf .val]) else (r, d) } -/-- Whether the term reads `SBox`'s `@shared` field (a projection or a case on it). -/ +/-- Whether the term reads `SBox`'s `@[shared]` field (a projection or a case on it). -/ def readsShared (g : G) : Bool := match g with | .proj s _ _ _ => s == sboxI | .case k _ _ _ _ => k == .sbox @@ -658,7 +658,7 @@ def recognise (gp : GProg) (seed : Ref) (h : Heap) (args : List Val) (k : Violat let labels : List (Bool × String) := [ (ill, "F15 (ill-typed stream)"), (uses exStale && !violatesWith P (oracleFamilyWith true false) seed h args k, "F14 (stale capability from an extern)"), - (uses exBox && !violatesWith P (oracleFamilyWith false true) seed h args k, "F5 (extern stores a confined value in a @shared field)"), + (uses exBox && !violatesWith P (oracleFamilyWith false true) seed h args k, "F5 (extern stores a confined value in a @[shared] field)"), ((violation? top).isNone && (match top with | .value .. => true | _ => false), "F7 (violation only at some fuels)"), (refusesWith (fun p => p.cls == .leaf), "F1 (noLeaf at a Nat parameter)"), (refusesWith isArrow, "F2 (noLeaf at a function parameter)"), @@ -678,7 +678,7 @@ def recognise (gp : GProg) (seed : Ref) (h : Heap) (args : List Val) (k : Violat (k == .revokedUse && anyDef gp (fun _ g => match g with | .call f args _ => isCtorRef f && (args.filterMap (resultVar 0)).length != ((args.filterMap (resultVar 0)).eraseDups).length | _ => false), "F8 (a unique value stored twice in one cell)"), - -- MU, after MR's `bad11b (@once f) := useBox ⟨f⟩` (open at 7e9d1c656): a once binding stored in + -- MU, after MR's `bad11b (@[once] f) := useBox ⟨f⟩` (open at 7e9d1c656): a once binding stored in -- a constructor's field (no constructor of this universe has a function field, so that route is -- out of the grammar) or captured by a closure that is passed on or let-bound (a case -- alternative's λ telescope binds fields and is not such a closure), then called through it @@ -716,7 +716,7 @@ def recognise (gp : GProg) (seed : Ref) (h : Heap) (args : List Val) (k : Violat "F16 (a case's extra arguments at the case's class)"), (k == .revokedUse && anyDef gp (fun _ g => match g with | .appv _ args _ => args.length ≥ 2 | _ => false), "F13 (a function value of two arguments, one application at a time)"), - -- MU: SBox's field inherited makes the checker refuse, and the @shared field is read from a cell + -- MU: SBox's field inherited makes the checker refuse, and the @[shared] field is read from a cell -- a callee built (a call's result, or a cell built in another definition) (k == .borrowEscape && !(checkBodies {} (sboxInherited P) bodies).isAccept && (anyDef gp (fun _ g => match g with @@ -726,7 +726,7 @@ def recognise (gp : GProg) (seed : Ref) (h : Heap) (args : List Val) (k : Violat ((gp.defs ++ gp.inFns).any fun d1 => (gp.defs ++ gp.inFns).any fun d2 => d1.ref != d2.ref && anyGE (fun _ g => match g with | .call f _ _ => f == sboxC | _ => false) [] d1.body && anyGE (fun _ g => readsShared g) [] d2.body)), - "F18 (a @shared field built by a callee holds the caller's confined value)"), + "F18 (a @[shared] field built by a callee holds the caller's confined value)"), -- MU: candidate 19 (a borrowed leaf passed at a plain parameter keeps its confinement into a cell -- whose unique return transfers it): a unique result of class val somewhere, and with every borrowed -- mode on a leaf made plain the run no longer violates diff --git a/ModeRepairTests/Findings.lean b/ModeRepairTests/Findings.lean index e201aebfd7..e2c9da1edd 100644 --- a/ModeRepairTests/Findings.lean +++ b/ModeRepairTests/Findings.lean @@ -21,7 +21,7 @@ def addr (k : Nat) : Address := ⟨⟨#[k.toUInt8, 0x5a]⟩⟩ def mem (k : Nat) : Ref := .member (addr k) 0 def ctr (k j : Nat) : Ref := .ctor (addr k) 0 j -/-- A list, `Nat`, a box with an inherited field, a box with a `@shared` field, +/-- A list, `Nat`, a box with an inherited field, a box with a `@[shared]` field, a key with an erased field. -/ def L := mem 1 def nilR := ctr 1 0 @@ -356,7 +356,7 @@ def finding4 : IO Unit := do let cs := match c with | .ok x => s!"ok {repr x}" | .error e => s!"error {e}" IO.println s!"[F4 oracle] oTypeClass, empty env, depth {d}, a {k}-ary former (Type → … → Type): {cs}" -/-! ## Finding 5: an extern stores a confined argument in a `@shared` field -/ +/-! ## Finding 5: an extern stores a confined argument in a `@[shared]` field -/ def mkS := mem 312 def leak5 := mem 313 @@ -560,7 +560,7 @@ def mkK := mem 332 def g15 := mem 333 /-- `mkK {α β} (a : α) (b : β) : Nat → α := fun _ => a`; -`g15 (@borrowed k : NP) : Nat → Nat := NP.casesOn k (@mkK Nat Nat)` (a non-λ alternative). -/ +`g15 (@[borrowed] k : NP) : Nat → Nat := NP.casesOn k (@mkK Nat Nat)` (a non-λ alternative). -/ def p15 : Prog := prog [ (NP, .ind #[npR]), (npR, .ctor NP 0 0 #[fld .leaf, fld .leaf]), (mkK, body [par .many .irr, par .many .irr, par .many .val .unknown, par .many .val .unknown] @@ -616,7 +616,7 @@ def use16v := mem 340 def sk16 : Skel := .arrow .many .data .shared (.arrow .many .data .shared .data) -/-- `use16 (k : List Nat → Nat → Nat) (@unique y : List Nat) (b : E) : Nat := +/-- `use16 (k : List Nat → Nat → Nat) (@[unique] y : List Nat) (b : E) : Nat := (match b with | e0 => k | e1 => k) y (consume y)`. -/ def p16 : Prog := prog [ (E2, .ind #[e0R, e1R]), (e0R, .ctor E2 0 0 #[]), (e1R, .ctor E2 1 0 #[]), @@ -650,8 +650,8 @@ def u17b := mem 344 def idS := mem 345 def u17bc := mem 346 -/-- (a) `u17a (@borrowed n : Nat) : Nat := let (@unique m) := n; m`; control: a plain `let`. -(b) `idU (w : WrapN) : @unique WrapN := w`, `u17b (@borrowed w : WrapN) : WrapN := idU w`, with +/-- (a) `u17a (@[borrowed] n : Nat) : Nat := let (@[unique] m) := n; m`; control: a plain `let`. +(b) `idU (w : WrapN) : @[unique] WrapN := w`, `u17b (@[borrowed] w : WrapN) : WrapN := idU w`, with `WrapN` a one-constructor wrapper of `Nat` (class leaf, `noLeaf := false`); control: `idS` returning `shared`. -/ def p17 : Prog := prog [ @@ -663,12 +663,12 @@ def p17 : Prog := prog [ (u17bc, body [par .borrowed .leaf .data false] (app (.const idS .val) [v 0 .leaf] .leaf) .shared .leaf)] def finding17 : IO Unit := do - report "C17a let (@unique m) := n" p17 noExtern stdFuels u17a oneNat [u17a] + report "C17a let (@[unique] m) := n" p17 noExtern stdFuels u17a oneNat [u17a] report "C17a control: a plain let" p17 noExtern stdFuels u17ac oneNat [u17ac] report "C17b a unique result of class leaf" p17 noExtern stdFuels u17b oneNat [u17b, idU] report "C17b control: a shared result" p17 noExtern stdFuels u17bc oneNat [u17bc, idS] -/-! ## Candidate 18 (found by the tester): a `@shared` field built by a callee from a plain +/-! ## Candidate 18 (found by the tester): a `@[shared]` field built by a callee from a plain parameter holds the caller's confined value (`anProj`, Check.lean:376, as in finding 5, but with a run body in place of the extern) -/ @@ -706,16 +706,16 @@ def c19f := mem 356 def consOf (h : Term) : Term := app (.const consR .val) [.irr, h, app (.const nilR .val) [.irr] .imm] def p19 : Prog := prog [ - -- mkL (n : Nat) : @unique List Nat := [n] + -- mkL (n : Nat) : @[unique] List Nat := [n] (mkL19, body [par .many .leaf] (consOf (v 0 .leaf)) .unique .val), - -- c19 (@borrowed n : Nat) : List Nat := mkL n + -- c19 (@[borrowed] n : Nat) : List Nat := mkL n (c19, body [par .borrowed .leaf] (app (.const mkL19 .val) [v 0 .leaf] .val) .shared .val), -- control: mkL's result shared (mkL19s, body [par .many .leaf] (consOf (v 0 .leaf)) .shared .val), (c19s, body [par .borrowed .leaf] (app (.const mkL19s .val) [v 0 .leaf] .val) .shared .val), -- control: n plain (c19p, body [par .many .leaf] (app (.const mkL19 .val) [v 0 .leaf] .val) .shared .val), - -- the tester's shape: (f : Nat → @unique List Nat) (@uniqueBorrowed n : Nat) : @borrowed List Nat := f n + -- the tester's shape: (f : Nat → @[unique] List Nat) (@uniqueBorrowed n : Nat) : @[borrowed] List Nat := f n (c19f, body [par .many .val (.arrow .many .data .unique .data), par .uniqueBorrowed .leaf] (app (v 1) [v 0 .leaf] .val) .borrowed .val)] @@ -725,7 +725,7 @@ def in19f : Heap × List Val := (b.heap, [f, n]) def finding19 : IO Unit := do - report "C19 c19 (@borrowed n : Nat) : List Nat := mkL n, mkL (n : Nat) : @unique List Nat := [n]" p19 noExtern stdFuels c19 oneNat [c19, mkL19] + report "C19 c19 (@[borrowed] n : Nat) : List Nat := mkL n, mkL (n : Nat) : @[unique] List Nat := [n]" p19 noExtern stdFuels c19 oneNat [c19, mkL19] report "C19 control: mkL's result shared" p19 noExtern stdFuels c19s oneNat [c19s, mkL19s] report "C19 control: n plain" p19 noExtern stdFuels c19p oneNat [c19p, mkL19] report "C19 the tester's shape (f n, f an input partial application of mkL)" p19 noExtern stdFuels c19f in19f [c19f, mkL19] @@ -740,14 +740,14 @@ def cc := mem 358 def pcc : Prog := prog [ -- k2 (a b : Nat) : Nat := a (k2, body [par .many .leaf, par .many .leaf] (v 1 .leaf) .shared .leaf), - -- cc (@once f : Nat → Nat → Nat) : Nat := f 1 2 + -- cc (@[once] f : Nat → Nat → Nat) : Nat := f 1 2 (cc, body [par .once .val (.arrow .many .data .shared (.arrow .many .data .shared .data))] (app (v 0) [.natLit 1, .natLit 2] .leaf) .shared .leaf)] def incc : Heap × List Val := let (b, f) := ({} : HB).alloc (.pap k2 #[]); (b.heap, [f]) def completenessD : IO Unit := do - report "D-cost cc (@once f : Nat → Nat → Nat) : Nat := f 1 2" pcc noExtern stdFuels cc incc [cc, k2] + report "D-cost cc (@[once] f : Nat → Nat → Nat) : Nat := f 1 2" pcc noExtern stdFuels cc incc [cc, k2] def run (args : List String) : IO Unit := do let which := args.headD "all" diff --git a/ModeRepairTests/Main.lean b/ModeRepairTests/Main.lean index db667eb1b8..4d86ad92b4 100644 --- a/ModeRepairTests/Main.lean +++ b/ModeRepairTests/Main.lean @@ -30,7 +30,7 @@ def addr (k : Nat) : Address := ⟨⟨#[k.toUInt8, 0x5a]⟩⟩ def mem (k : Nat) : Ref := .member (addr k) 0 def ctr (k j : Nat) : Ref := .ctor (addr k) 0 j -/-- A list, `Nat`, a box with an inherited field, a box with a `@shared` field, +/-- A list, `Nat`, a box with an inherited field, a box with a `@[shared]` field, a key with an erased field. -/ def L := mem 1 def nilR := ctr 1 0 @@ -475,14 +475,14 @@ def suiteCase (label : String) (defs : List (Ref × RunDef)) (entry : Ref) (inpu verdict := if accept then .accept else .refuse, fuels := [100000], run := [(0, match run with | some k => .vio k | none => .value)], inputs := none, lim } --- `useErased (@erased n : Nat) : Nat := n + 1` +-- `useErased (@[erased] n : Nat) : Nat := n + 1` def useErased := mem 100 --- `keep (@erased n : Nat) (b : List) : List := b` +-- `keep (@[erased] n : Nat) (b : List) : List := b` def keepE := mem 101 -- `leak (k : Key) : Nat := k.ghost`; `idOf (k : Key) : Nat := k.id` def leak := mem 102 def idOf := mem 103 --- `let (@erased x) := xs; len x` +-- `let (@[erased] x) := xs; len x` def eraseLet := mem 104 def erasedCases : List Case := [ @@ -511,7 +511,7 @@ def boxI := mem 118 def twiceN := mem 119 def uniqueCases : List Case := [ - -- `twice (@unique xs) := consume xs + consume xs` + -- `twice (@[unique] xs) := consume xs + consume xs` suiteCase "unique: a binding transferred twice" [(twice, body [par .unique] (add (app (.const consumeR .val) [v 0] .leaf) (app (.const consumeR .val) [v 0] .leaf)) .shared .leaf)] twice oneList (some .revokedUse) false, @@ -522,21 +522,21 @@ def uniqueCases : List Case := [ [(share1, body [par] (app (.const consumeR .val) [v 0] .leaf) .shared .leaf), (caller, body [par] (add (app (.const share1 .val) [v 0] .leaf) (lenOf (v 0))) .shared .leaf)] caller oneList (some .revokedUse) false [share1, caller], - -- `headU (@unique xs) := match xs with | [] => 0 | _ :: t => len t` + -- `headU (@[unique] xs) := match xs with | [] => 0 | _ :: t => len t` suiteCase "unique: a consuming match, the fields used" [(headU, body [par .unique] (onList (v 0) (.natLit 0) (lenOf (v 0)) .val .leaf) .shared .leaf)] headU oneList none true, - -- `headBad (@unique xs) := match xs with | [] => 0 | _ :: _ => len xs` + -- `headBad (@[unique] xs) := match xs with | [] => 0 | _ :: _ => len xs` suiteCase "unique: a consumed major read in an alternative" [(headBad, body [par .unique] (onList (v 0) (.natLit 0) (lenOf (v 2)) .val .leaf) .shared .leaf)] headBad oneList (some .revokedUse) false, - -- `deep (@unique xs) := match xs with | [] => 0 | h :: t => consume (h :: t) + len t` + -- `deep (@[unique] xs) := match xs with | [] => 0 | h :: t => consume (h :: t) + len t` suiteCase "unique: deep transfer revokes the fields" [(deep, body [par .unique] (onList (v 0) (.natLit 0) (add (app (.const consumeR .val) [app (.const consR .val) [.irr, v 1, v 0]] .leaf) (lenOf (v 0))) .val .leaf) .shared .leaf)] deep oneList (some .revokedUse) false, - -- `boxS (@unique x : List) := let s := ⟨x⟩ : S; consumeS s + len x` (a `@shared` field stops deep uniqueness; - -- `x` must be `@unique`, not plain: a plain parameter may be caller-borrowed so `consumeS ⟨x⟩` would escape) - suiteCase "unique: a @shared field stops deep uniqueness" [(boxS, body [par .unique] + -- `boxS (@[unique] x : List) := let s := ⟨x⟩ : S; consumeS s + len x` (a `@[shared]` field stops deep uniqueness; + -- `x` must be `@[unique]`, not plain: a plain parameter may be caller-borrowed so `consumeS ⟨x⟩` would escape) + suiteCase "unique: a @[shared] field stops deep uniqueness" [(boxS, body [par .unique] (.letE (.value .many) .val (app (.const sboxR .val) [v 0]) (add (app (.const consumeSR .val) [v 0] .leaf) (lenOf (v 1)))) .shared .leaf)] boxS oneList none true, -- `boxI (x : List) := let s := ⟨x⟩ : B; consumeB s + len x` (an inherited field) @@ -544,7 +544,7 @@ def uniqueCases : List Case := [ (.letE (.value .many) .val (app (.const boxR .val) [v 0]) (add (app (.const consumeBR .val) [v 0] .leaf) (lenOf (v 1)))) .shared .leaf)] boxI oneList (some .revokedUse) false, - -- `twiceN (@unique n : Nat) := consumeN n + consumeN n` (a leaf is never unique) + -- `twiceN (@[unique] n : Nat) := consumeN n + consumeN n` (a leaf is never unique) suiteCase "unique: a leaf transferred twice" [(twiceN, body [par .unique .leaf] (add (app (.const consumeNR .val) [v 0 .leaf] .leaf) (app (.const consumeNR .val) [v 0 .leaf] .leaf)) .shared .leaf)] twiceN oneNat none true @@ -573,7 +573,7 @@ def borrowCases : List Case := [ peek oneList none true, -- L1: accepted suiteCase "borrow: a borrowed parameter returned borrowed" [(same, body [par .borrowed] (v 0) .borrowed)] same oneList none true, - -- `stash (@borrowed b : List) : List := [b]` + -- `stash (@[borrowed] b : List) : List := [b]` suiteCase "borrow: a borrowed parameter stored in a cell" [(stash, body [par .borrowed] (app (.const consR .val) [.irr, v 0, app (.const nilR .val) [.irr] .imm]))] stash oneList (some .borrowEscape) false, @@ -589,16 +589,16 @@ def borrowCases : List Case := [ escN oneNat none true, -- L1 W1: borrowEscape before -- L1: accepted suiteCase "borrow: arithmetic on a borrowed leaf" [(addN, body [par .borrowed .leaf] (add (v 0 .leaf) (.natLit 1)) .shared .leaf)] addN oneNat none true, - -- `headN (@borrowed xs : List Nat) : Nat := match xs with | [] => 0 | h :: _ => h` + -- `headN (@[borrowed] xs : List Nat) : Nat := match xs with | [] => 0 | h :: _ => h` suiteCase "borrow: a leaf read out of a borrowed container is not confined" [(headN, body [par .borrowed] (onList (v 0) (.natLit 0) (v 1 .leaf) .leaf .leaf) .shared .leaf)] headN oneList none true, - -- `storeN (@borrowed n : Nat) : Nat := match [n] with | [] => 0 | h :: _ => h` + -- `storeN (@[borrowed] n : Nat) : Nat := match [n] with | [] => 0 | h :: _ => h` suiteCase "borrow: a borrowed leaf stored in a cell and read back is a counted value" [(storeN, body [par .borrowed .leaf] (onList (app (.const consR .val) [.irr, v 0 .leaf, app (.const nilR .val) [.irr] .imm]) (.natLit 0) (v 1 .leaf) .leaf .leaf) .shared .leaf)] storeN oneNat none true, - -- `shf (@borrowed b : List) : List := (⟨b⟩ : S).1` (a borrowed value in a `@shared` field) - suiteCase "borrow: a borrowed value stored in a @shared field and returned" [(shf, + -- `shf (@[borrowed] b : List) : List := (⟨b⟩ : S).1` (a borrowed value in a `@[shared]` field) + suiteCase "borrow: a borrowed value stored in a @[shared] field and returned" [(shf, body [par .borrowed] (.proj S 0 (app (.const sboxR .val) [v 0]) .val))] shf oneList (some .borrowEscape) false ] @@ -620,12 +620,12 @@ def capPlain := mem 142 def papT := mem 143 def captureCases : List Case := [ - -- `capOnce (@unique xs) := let g := fun u => consume xs; g 0 + g 1` + -- `capOnce (@[unique] xs) := let g := fun u => consume xs; g 0 + g 1` suiteCase "capture: a closure consuming its capture called twice" [(capOnce, body [par .unique] (.letE (.value .many) .val (lam (par .many .leaf) (app (.const consumeR .val) [v 1] .leaf) .shared .leaf) (add (app (v 0) [.natLit 0] .leaf) (app (v 0) [.natLit 1] .leaf))) .shared .leaf)] capOnce oneList (some .revokedUse) false, - -- `capOuter (@unique xs) := let g := fun u => len xs; len xs` + -- `capOuter (@[unique] xs) := let g := fun u => len xs; len xs` suiteCase "capture: a unique binding captured, then read outside" [(capOuter, body [par .unique] (.letE (.value .many) .val (lam (par .many .leaf) (lenOf (v 1)) .shared .leaf) (lenOf (v 1))) .shared .leaf)] capOuter oneList (some .revokedUse) false, @@ -633,7 +633,7 @@ def captureCases : List Case := [ suiteCase "capture: a shared binding captured and read" [(capPlain, body [par] (.letE (.value .many) .val (lam (par .many .leaf) (lenOf (v 1)) .shared .leaf) (add (app (v 0) [.natLit 0] .leaf) (lenOf (v 1)))) .shared .leaf)] capPlain oneList none true, - -- `papT (@unique xs) := let g := consume2 xs; len xs` + -- `papT (@[unique] xs) := let g := consume2 xs; len xs` suiteCase "capture: a partial application transfers its unique argument" [(papT, body [par .unique] (.letE (.value .many) .val (app (.const consume2R .val) [v 0]) (lenOf (v 1))) .shared .leaf)] papT oneList (some .revokedUse) false @@ -645,7 +645,7 @@ def badStatic := mem 152 def okStatic := mem 153 def skeletonCases : List Case := [ - -- `callUse (xs) := use (fun (@unique y) => consume y) xs` + -- `callUse (xs) := use (fun (@[unique] y) => consume y) xs` suiteCase "skeleton: a closure with a unique binder at a plain arrow" [(callUse, body [par] (app (.const useR .val) [lam (par .unique) (app (.const consumeR .val) [v 0] .leaf) .shared .leaf, v 0] .leaf) .shared .leaf)] callUse oneList (some .revokedUse) false, @@ -675,7 +675,7 @@ def alternativeCases : List Case := [ (firstOf, body [par, par .many .leaf] (v 1)), (altConst, body [par] (.case caseK (v 0) #[.const firstOf .val] #[] .val))] altConst oneKey (some .erasedRead) false, - -- `secondOf (b : Nat) : Nat := b`; `altLam (k : Key) := Key.casesOn k (fun (@erased g) => secondOf)` + -- `secondOf (b : Nat) : Nat := b`; `altLam (k : Key) := Key.casesOn k (fun (@[erased] g) => secondOf)` suiteCase "erased: a λ alternative binds the erased field, the rest passed on" [ (secondOf, body [par .many .leaf] (v 0 .leaf) .shared .leaf), (altLam, body [par] (.case caseK (v 0) #[lam (par .erased) (.const secondOf .val) .shared .leaf] #[] @@ -742,16 +742,16 @@ def stuckCase (label : String) (defs : List (Ref × RunDef)) (entry : Ref) (inpu -- BEGIN COPY of Tests/Ix/ResourceModes.lean, "Findings of the mode study" --- Finding 1: `idN (n : Nat) : Nat := n`; `g4 (@borrowed n : Nat) : Nat := idN n` +-- Finding 1: `idN (n : Nat) : Nat := n`; `g4 (@[borrowed] n : Nat) : Nat := idN n` def idN := mem 300 def g4 := mem 301 def g4b := mem 341 --- Finding 2: `app1 (f : Unit → Nat) : Nat := f ()`; `g3 (@borrowed n : Nat) : Nat := app1 (fun _ => n)` +-- Finding 2: `app1 (f : Unit → Nat) : Nat := f ()`; `g3 (@[borrowed] n : Nat) : Nat := app1 (fun _ => n)` def app1 := mem 302 def g3 := mem 303 def g3p := mem 342 -- Finding 3: `bad (h : List Nat = Nat) (xs : List Nat) : Nat := cast h (id xs)`; --- `g2 (h : Nat = List Nat) (h' : List Nat = Nat) (@borrowed n : Nat) : Nat := bad h' (cast h n)` +-- `g2 (h : Nat = List Nat) (h' : List Nat = Nat) (@[borrowed] n : Nat) : Nat := bad h' (cast h n)` def EqI := mem 6 def reflR := ctr 6 0 def caseEq : CaseInfo := { ind := EqI, arity := 4, major := 2, alts := #[{ alt := 3, args := #[] }] } @@ -766,7 +766,7 @@ def eqDefs : List (Ref × RunDef) := [(EqI, .ind #[reflR]), (reflR, .ctor EqI 0 (idR, body [par .many .irr, par] (v 0)), (bad3, body [par .many .irr, parL] (.case caseEq .irr #[app (.const idR .val) [.irr, v 0]] #[] .leaf) .shared .leaf)] def in3 : Heap × List Val := let (b, n) := ({} : HB).alloc (.num 7); (b.heap, [.imm .irr, .imm .irr, n]) --- Finding 7: `f (a b : Nat) (@erased x : List Nat) (c d e : Nat) : Nat := a`, `g` the same +-- Finding 7: `f (a b : Nat) (@[erased] x : List Nat) (c d e : Nat) : Nat := a`, `g` the same -- parameters, `g a b x c d e := f a b x c d e`; the control has the erased parameter first def fV := mem 335 def gV := mem 336 @@ -795,8 +795,8 @@ def in7 : Heap × List Val := def in7x : Heap × List Val := let (b, ns) := fiveNats; (b.heap, .imm .irr :: ns) def fuels0to12 : List Nat := List.range 13 ++ [100000] --- Finding 8: `dup (@unique x : List Nat) : Nat := consume (x :: x)`; `dup2 … := consume [x, x]`; --- the control `pairOk (@unique x y : List Nat) : Nat := consume (x :: y)` +-- Finding 8: `dup (@[unique] x : List Nat) : Nat := consume (x :: x)`; `dup2 … := consume [x, x]`; +-- the control `pairOk (@[unique] x y : List Nat) : Nat := consume (x :: y)` def dup := mem 315 def dup2 := mem 345 def pairOk := mem 346 @@ -804,14 +804,14 @@ def twoLists : Heap × List Val := let (b, xs) := ({} : HB).list [1, 2] let (b, ys) := b.list [3] (b.heap, [xs, ys]) --- Finding 9: `g5 (@borrowed xs : List Nat) : List Nat := let f := fun _ => xs; f 0`; the control `g5p` +-- Finding 9: `g5 (@[borrowed] xs : List Nat) : List Nat := let f := fun _ => xs; f 0`; the control `g5p` -- with `xs` plain def g5 := mem 317 def g5p := mem 353 -- Found with repair D: a partial application of a function value holding a value moved into it is --- once-only. `kc17 (@unique a : List Nat) (n : Nat) : Nat := n`; `kc3 (@unique a) (b c : Nat) : Nat := b`; --- `d1 (k : (@unique a : List Nat) → Nat → Nat) (@unique x) : Nat := let h := k x; h 1 + h 2`, `d1h … := k x 1`; --- `d2 (@unique x) : Nat := let h := kc3 x; let h2 := h 1; h2 2 + h2 3`, `d2h … := let h := kc3 x; h 1 2` +-- once-only. `kc17 (@[unique] a : List Nat) (n : Nat) : Nat := n`; `kc3 (@[unique] a) (b c : Nat) : Nat := b`; +-- `d1 (k : (@[unique] a : List Nat) → Nat → Nat) (@[unique] x) : Nat := let h := k x; h 1 + h 2`, `d1h … := k x 1`; +-- `d2 (@[unique] x) : Nat := let h := kc3 x; let h2 := h 1; h2 2 + h2 3`, `d2h … := let h := kc3 x; h 1 2` def kc17 := mem 347 def d1 := mem 348 def d1h := mem 349 @@ -825,8 +825,8 @@ def inD1 : Heap × List Val := let (b, xs) := ({} : HB).list [1, 2] let (b, k) := b.alloc (.pap kc17 #[]) (b.heap, [k, xs]) --- Finding 13: `use13 (k : (@borrowed a : List Nat) → Nat → Nat) (@unique y : List Nat) : Nat := --- k y (consume y)`, with `kk (@borrowed a : List Nat) (n : Nat) : Nat := match a with | [] => 0 | _ => 1` +-- Finding 13: `use13 (k : (@[borrowed] a : List Nat) → Nat → Nat) (@[unique] y : List Nat) : Nat := +-- k y (consume y)`, with `kk (@[borrowed] a : List Nat) (n : Nat) : Nat := match a with | [] => 0 | _ => 1` -- given as `k` def sk13 : Skel := .arrow .borrowed .data .shared (.arrow .many .data .shared .data) def kk := mem 327 @@ -840,7 +840,7 @@ def in13 : Heap × List Val := let (b, f) := b.alloc (.pap kk #[]) (b.heap, [f, xs]) -- Found with repair N: a spine longer than the checker's depth left at it. `S6` is a structure of --- five `Nat` fields and a `@shared` `List Nat` field; `g6 (@borrowed xs : List Nat) : List Nat := +-- five `Nat` fields and a `@[shared]` `List Nat` field; `g6 (@[borrowed] xs : List Nat) : List Nat := -- (S6.mk 1 2 3 4 5 xs).sh`, checked at depth 6 (its spine of six arguments is cut at 4 as landed) -- and at the default depth; the control `g6p` has `xs` plain def S6 := mem 354 @@ -853,9 +853,9 @@ def s6Defs : List (Ref × RunDef) := [(S6, .ind #[s6mk]), [.natLit 1, .natLit 2, .natLit 3, .natLit 4, .natLit 5, v 0]) .val)), (g6p, body [par] (.proj S6 5 (app (.const s6mk .val) [.natLit 1, .natLit 2, .natLit 3, .natLit 4, .natLit 5, v 0]) .val))] --- Findings 10 and 11: `callTwice (f : Nat → Nat) : Nat := f 0 + f 1`; `callOnce (@once f : Nat → Nat) : Nat := f 0`; --- `bad10 (@unique xs) := callTwice (fun _ => consume xs)`; `alias10 (@unique xs) := let g := fun _ => consume xs; --- let h := g; h 0 + g 0`; `h11 (@once f) := callTwice f`; the controls `ok10`, `ok11` call `callOnce` instead +-- Findings 10 and 11: `callTwice (f : Nat → Nat) : Nat := f 0 + f 1`; `callOnce (@[once] f : Nat → Nat) : Nat := f 0`; +-- `bad10 (@[unique] xs) := callTwice (fun _ => consume xs)`; `alias10 (@[unique] xs) := let g := fun _ => consume xs; +-- let h := g; h 0 + g 0`; `h11 (@[once] f) := callTwice f`; the controls `ok10`, `ok11` call `callOnce` instead def callTwice := mem 319 def bad10 := mem 320 def alias10 := mem 321 @@ -868,10 +868,10 @@ def onceDefs : List (Ref × RunDef) := [ .shared .leaf), (callOnce, body [par .once .val arrowSk] (app (v 0) [.natLit 0] .leaf) .shared .leaf)] def consumeClo : Term := lam (par .many .leaf) (app (.const consumeR .val) [v 1] .leaf) .shared .leaf --- Finding 12: `addB (@borrowed n : Nat) : Nat → Nat := Nat.add n`; the control `addP` with `n` plain +-- Finding 12: `addB (@[borrowed] n : Nat) : Nat → Nat := Nat.add n`; the control `addP` with `n` plain def addB := mem 325 def addP := mem 362 --- Finding 16: `use16 (k : List Nat → Nat → Nat) (@unique y : List Nat) (b : E) : Nat := +-- Finding 16: `use16 (k : List Nat → Nat → Nat) (@[unique] y : List Nat) (b : E) : Nat := -- (match b with | e0 => k | e1 => k) y (consume y)`, the case of class leaf, with -- `kk16 (a : List Nat) (n : Nat) : Nat := len a` given as `k`; the control `use16p` has `y` plain -- and applies the case to `y` and `1` @@ -892,11 +892,11 @@ def in16 : Heap × List Val := let (b, k) := b.alloc (.pap kk16 #[]) (b.heap, [k, xs, .imm (.con e0R)]) -- Found after repair E (repair Q): `useBox (b : Box (Nat → Nat)) : Nat := b.1 0 + b.1 1`; --- `bad11b (@once f : Nat → Nat) : Nat := useBox ⟨f⟩`; the control `ok11b` has `f` plain +-- `bad11b (@[once] f : Nat → Nat) : Nat := useBox ⟨f⟩`; the control `ok11b` has `f` plain def useBox := mem 360 def bad11b := mem 361 def ok11b := mem 380 --- Repair R: `retAlt (@once f : Nat → Nat) (b : E) : Nat := callTwice (match b with | e0 => f | e1 => f)`; +-- Repair R: `retAlt (@[once] f : Nat → Nat) (b : E) : Nat := callTwice (match b with | e0 => f | e1 => f)`; -- the control `retAltP` has `f` plain def retAlt := mem 377 def retAltP := mem 387 @@ -904,7 +904,7 @@ def funAndE0 : Heap × List Val := let (b, f) := ({} : HB).alloc (.pap incR #[]) (b.heap, [f, .imm (.con e0R)]) def retAltBody : Term := app (.const callTwice .val) [.case caseE (v 0 .imm) #[v 1, v 1] #[] .val] .leaf --- Repair S: `retF (@once f : Nat → Nat) : Nat → Nat := f`; `useRet (@once f) : Nat := let h := retF f; h 0 + h 1`; +-- Repair S: `retF (@[once] f : Nat → Nat) : Nat → Nat := f`; `useRet (@[once] f) : Nat := let h := retF f; h 0 + h 1`; -- the control `useRetP` calls `retP`, the same with `f` plain def retF := mem 367 def retP := mem 368 @@ -912,15 +912,15 @@ def useRet := mem 378 def useRetP := mem 388 def useRetBody (r : Ref) : Term := .letE (.value .many) .val (app (.const r .val) [v 0] .val) (add (app (v 0) [.natLit 0] .leaf) (app (v 0) [.natLit 1] .leaf)) --- Repair T: `twiceOnce (@once f : Nat → Nat) : Nat := callOnce f + callOnce f`; the control +-- Repair T: `twiceOnce (@[once] f : Nat → Nat) : Nat := callOnce f + callOnce f`; the control -- `twiceOnceP` has `f` plain def twiceOnce := mem 379 def twiceOnceP := mem 389 def twiceOnceBody : Term := add (app (.const callOnce .val) [v 0] .leaf) (app (.const callOnce .val) [v 0] .leaf) --- Finding 17 (repair O): a unique mode on a leaf. `u17a (@borrowed n : Nat) : Nat := let (@unique m) := n; m` --- (control `u17ap`, `n` plain); `idU (w : WrapN) : @unique WrapN := w`, `u17b (@borrowed w : WrapN) : WrapN := idU w`; --- `idUP {α} (@unique x : α) : @unique α := x`, `u17c (@borrowed n : Nat) : Nat := idUP n` (control `u17cp`, `n` plain); --- `u17d (@borrowed w : WrapN) : Nat := match w with | ⟨@unique m⟩ => m` (control `u17dp`, `w` plain) +-- Finding 17 (repair O): a unique mode on a leaf. `u17a (@[borrowed] n : Nat) : Nat := let (@[unique] m) := n; m` +-- (control `u17ap`, `n` plain); `idU (w : WrapN) : @[unique] WrapN := w`, `u17b (@[borrowed] w : WrapN) : WrapN := idU w`; +-- `idUP {α} (@[unique] x : α) : @[unique] α := x`, `u17c (@[borrowed] n : Nat) : Nat := idUP n` (control `u17cp`, `n` plain); +-- `u17d (@[borrowed] w : WrapN) : Nat := match w with | ⟨@[unique] m⟩ => m` (control `u17dp`, `w` plain) def WNi := mem 420 def wnR := ctr 420 0 def caseWN : CaseInfo := { ind := WNi, arity := 2, major := 0, alts := #[{ alt := 1, args := #[.field 0] }] } @@ -945,7 +945,7 @@ def oDefs : List (Ref × RunDef) := [ (u17cp, body [par .many .leaf] (app (.const idUP .val) [.irr, v 0 .leaf] .leaf) .shared .leaf), (u17d, body [par .borrowed .leaf] matchWNU .shared .leaf), (u17dp, body [par .many .leaf] matchWNU .shared .leaf)] --- Finding 18 (repair P): `mkSB (x : List Nat) : SBox := SBox.mk x`; `leak18 (@borrowed xs : List Nat) : +-- Finding 18 (repair P): `mkSB (x : List Nat) : SBox := SBox.mk x`; `leak18 (@[borrowed] xs : List Nat) : -- List Nat := (mkSB xs).val`, `leak18m … := match mkSB xs with | ⟨y⟩ => y`; the controls have `xs` plain def mkSB := mem 430 def leak18 := mem 445 @@ -956,8 +956,8 @@ def caseS : CaseInfo := { ind := S, arity := 2, major := 0, alts := #[{ alt := 1 def mkSBDef : Ref × RunDef := (mkSB, body [par] (app (.const sboxR .val) [v 0])) def projSB : Term := .proj S 0 (app (.const mkSB .val) [v 0]) .val def matchSB : Term := .case caseS (app (.const mkSB .val) [v 0]) #[lam par (v 0) .shared .val] #[] .val --- Repair U / Fix 2: `mkSBU (x : List Nat) : @unique SBox := SBox.mk x` is itself refused by Fix 2 --- (`paramVal` gives plain `.many` params caller region `1`); the control `mkSBUU` takes `@unique x`. +-- Repair U / Fix 2: `mkSBU (x : List Nat) : @[unique] SBox := SBox.mk x` is itself refused by Fix 2 +-- (`paramVal` gives plain `.many` params caller region `1`); the control `mkSBUU` takes `@[unique] x`. def mkSBU := mem 431 def mkSBUU := mem 240 def isSB := mem 441 @@ -970,7 +970,7 @@ def uDefs : List (Ref × RunDef) := [(E2, .ind #[e0R, e1R]), (e0R, .ctor E2 0 0 def isSBmk : Term := app (.const isSB .val) [app (.const mkSBU .val) [v 0]] .imm def isSBmkU : Term := app (.const isSB .val) [app (.const mkSBUU .val) [v 0]] .imm -- Finding 15 (repair J): `NP` with one constructor and two `Nat` fields; `mkK {α β} (a : α) (b : β) : Nat → α := --- fun _ => a`; `g15 (@borrowed k : NP) : Nat → Nat := NP.casesOn k (@mkK Nat Nat)`, on an input whose first +-- fun _ => a`; `g15 (@[borrowed] k : NP) : Nat → Nat := NP.casesOn k (@mkK Nat Nat)`, on an input whose first -- field holds a list cell (ill-typed): a stuck run since repair J; on a well-typed input, a value def NP := mem 8 def npR := ctr 8 0 @@ -1065,7 +1065,7 @@ def findingCases : List Case := [ (kcDefs ++ [(d2h, body [par .unique] (.letE (.value .many) .val (app (.const kc3 .val) [v 0] .val) (app (v 0) [.natLit 1, .natLit 2] .leaf)) .shared .leaf)]) d2h oneList none false, - runCase "a spine longer than the checker's depth left at it: a borrowed list stored in a @shared field" + runCase "a spine longer than the checker's depth left at it: a borrowed list stored in a @[shared] field" s6Defs g6 oneList (some .borrowEscape) false [g6] { depth := 6 }, runCase "the same at the default depth" s6Defs g6 oneList (some .borrowEscape) false, runCase "the same, the list not borrowed, at depth 6" s6Defs g6p oneList none true [g6p] { depth := 6 }, @@ -1135,7 +1135,7 @@ def findingCases : List Case := [ runCase "finding 17: a borrowed wrapper of a number matched, its field bound unique and returned" oDefs u17d oneNat none true, -- L1 W1: borrowEscape before -- L1: accepted runCase "finding 17, control: the wrapper not borrowed" oDefs u17dp oneNat none true, - runCase "finding 18: a borrowed list stored in a @shared field by a callee, projected" + runCase "finding 18: a borrowed list stored in a @[shared] field by a callee, projected" [mkSBDef, (leak18, body [par .borrowed] projSB)] leak18 oneList (some .borrowEscape) false [leak18, mkSB], runCase "finding 18, control: the list not borrowed" [mkSBDef, (leak18p, body [par] projSB)] leak18p oneList none true [leak18p, mkSB], @@ -1167,7 +1167,7 @@ def g4b := mem 341 def p1 (noLeafIdN : Bool) : Prog := prog [ (idN, body [par .many .leaf .data noLeafIdN] (v 0 .leaf) .shared .leaf), (g4, body [par .borrowed .leaf] (app (.const idN .val) [v 0 .leaf] .leaf) .shared .leaf), - -- `g4b (@borrowed n : Nat) : @borrowed Nat := idN n` + -- `g4b (@[borrowed] n : Nat) : @[borrowed] Nat := idN n` (g4b, body [par .borrowed .leaf] (app (.const idN .val) [v 0 .leaf] .leaf) .borrowed .leaf)] def f1Cases : List Case := [ @@ -1326,7 +1326,7 @@ def finding4oracle (t : IO.Ref Tally) : IO Unit := do (match c with | .error e => e.startsWith "decline:" | .ok _ => false) (match c with | .ok x => s!"ok {repr x}" | .error e => s!"error {e}") -/-! ### Finding 5: an extern stores a confined argument in a `@shared` field -/ +/-! ### Finding 5: an extern stores a confined argument in a `@[shared]` field -/ def mkS := mem 312 def leak5 := mem 313 @@ -1485,10 +1485,10 @@ def p8 : Prog := prog [ (deep8, body [par .unique] (onList (v 0) (.natLit 0) (add (app (.const consumeR .val) [app (.const consR .val) [.irr, v 1, v 0]] .leaf) (lenOf (v 0))) .val .leaf) .shared .leaf), - -- `dup2 (@unique x : List Nat) : Nat := consume [x, x]`, the second through a cell of its own + -- `dup2 (@[unique] x : List Nat) : Nat := consume [x, x]`, the second through a cell of its own (dup2, body [par .unique] (app (.const consumeR .val) [app (.const consR .val) [.irr, v 0, app (.const consR .val) [.irr, v 0, app (.const nilR .val) [.irr] .imm]]] .leaf) .shared .leaf), - -- `pairOk (@unique x y : List Nat) : Nat := consume (x :: y)` + -- `pairOk (@[unique] x y : List Nat) : Nat := consume (x :: y)` (pairOk, body [par .unique, par .unique] (app (.const consumeR .val) [app (.const consR .val) [.irr, v 1, v 0]] .leaf) .shared .leaf)] @@ -1533,11 +1533,11 @@ def f9Cases : List Case := [ /-! ### Two more, found while writing repair D (by reading; run): a partial application of a function value holding a value moved into it is once-only, and the checker reused it -`kc17 (@unique a : List Nat) (n : Nat) : Nat := n`; `kc3 (@unique a : List Nat) (b c : Nat) : Nat := b`. -* D1 `d1 (k : (@unique a : List Nat) → Nat → Nat) (@unique x : List Nat) : Nat := let h := k x; h 1 + h 2`: +`kc17 (@[unique] a : List Nat) (n : Nat) : Nat := n`; `kc3 (@[unique] a : List Nat) (b c : Nat) : Nat := b`. +* D1 `d1 (k : (@[unique] a : List Nat) → Nat → Nat) (@[unique] x : List Nat) : Nat := let h := k x; h 1 + h 2`: `k x` is a partial application holding `x` (transferred into it); its first call transfers `x` again, so its second call is `revokedUse`. -* D2 `d2 (@unique x : List Nat) : Nat := let h := kc3 x; let h2 := h 1; h2 2 + h2 3`: `h` is +* D2 `d2 (@[unique] x : List Nat) : Nat := let h := kc3 x; let h2 := h 1; h2 2 + h2 3`: `h` is once-only (`papVal`), but `h2 := h 1` is a partial application holding the same moved value and was not once-only. Repair D (r2) refuses both, because the result's aliases include the moved argument (D1) or the @@ -1613,13 +1613,13 @@ def p10 : Prog := prog [ (h11, body [par .once .val arrowSk] (app (.const callTwice .val) [v 0] .leaf) .shared .leaf), (twiceCall11, body [par .once .val arrowSk] (add (app (v 0) [.natLit 1] .leaf) (app (v 0) [.natLit 2] .leaf)) .shared .leaf), - -- `callOnce (@once f : Nat → Nat) : Nat := f 0` + -- `callOnce (@[once] f : Nat → Nat) : Nat := f 0` (callOnce, body [par .once .val arrowSk] (app (v 0) [.natLit 0] .leaf) .shared .leaf), - -- `ok10 (@unique xs) : Nat := callOnce (fun _ => consume xs)`; `ok11 (@once f) : Nat := callOnce f` + -- `ok10 (@[unique] xs) : Nat := callOnce (fun _ => consume xs)`; `ok11 (@[once] f) : Nat := callOnce f` (ok10, body [par .unique] (app (.const callOnce .val) [lam (par .many .leaf) (app (.const consumeR .val) [v 1] .leaf) .shared .leaf] .leaf) .shared .leaf), (ok11, body [par .once .val arrowSk] (app (.const callOnce .val) [v 0] .leaf) .shared .leaf), - -- `useBox (b : Box (Nat → Nat)) : Nat := b.1 0 + b.1 1`; `bad11b (@once f) : Nat := useBox ⟨f⟩` + -- `useBox (b : Box (Nat → Nat)) : Nat := b.1 0 + b.1 1`; `bad11b (@[once] f) : Nat := useBox ⟨f⟩` (useBox, body [par] (add (app (.proj B 0 (v 0) .val) [.natLit 0] .leaf) (app (.proj B 0 (v 0) .val) [.natLit 1] .leaf)) .shared .leaf), (bad11b, body [par .once .val arrowSk] (app (.const useBox .val) [app (.const boxR .val) [v 0]] .leaf) .shared .leaf)] @@ -1658,7 +1658,7 @@ def p12 : Prog := prog [ (addBc, body [par .borrowed .leaf] (app (.const consR .val) [.irr, v 0 .leaf] .val) .shared .val arrowSk), -- `addP (n : Nat) : Nat → Nat := Nat.add n` (addP, body [par .many .leaf] (app (.const addR .val) [v 0 .leaf] .val) .shared .val arrowSk), - -- `addBb (@borrowed n : Nat) : Nat := let g := Nat.add n; g 1` + -- `addBb (@[borrowed] n : Nat) : Nat := let g := Nat.add n; g 1` (addBb, body [par .borrowed .leaf] (.letE (.value .many) .val (app (.const addR .val) [v 0 .leaf] .val) (app (v 0) [.natLit 1] .leaf)) .shared .leaf)] @@ -1685,7 +1685,7 @@ def use13c := mem 329 def kk0 := mem 334 def p13 : Prog := prog [ - -- `kk (@borrowed a : List Nat) (n : Nat) : Nat := match a with | [] => 0 | _ => 1` (MT's `kk` + -- `kk (@[borrowed] a : List Nat) (n : Nat) : Nat := match a with | [] => 0 | _ => 1` (MT's `kk` -- read `len a`, which the checker refuses since repair A, a borrowed list's length being a -- leaf carrying its region; that hid the finding, so `kk` reads `a` by a match instead) (kk, body [par .borrowed, par .many .leaf] (onList (v 1) (.natLit 0) (.natLit 1) .val .leaf) .shared .leaf), @@ -1839,7 +1839,7 @@ def f16Cases : List Case := [ /-! ### The routes of a once binding and of a once-only value (repair Q and after) -Every way a value read from a `@once` binding `f` can be stored, duplicated or passed on, each +Every way a value read from a `@[once]` binding `f` can be stored, duplicated or passed on, each beside the same program with `f` plain (the control, accepted, runs clean), and the routes of a once-only closure `g := fun _ => consume xs` where its rules differ. `bad11b` (route 1) is the counterexample found after E. -/ @@ -1874,7 +1874,7 @@ def routeBodyPlain (i : Nat) : Term := def routeName : Nat → String | 1 => "an inherited constructor field (useBox ⟨f⟩)" - | 2 => "a @shared constructor field (useSBox ⟨f⟩)" + | 2 => "a @[shared] constructor field (useSBox ⟨f⟩)" | 3 => "a partial application's argument (let p := apply2 f; p 0)" | 4 => "a closure's capture (callTwice (fun n => f n))" | 5 => "a plain let (let h := f; h 0 + h 1)" @@ -1910,11 +1910,11 @@ def pQ : Prog := { p10 with defs := p10.defs ++ #[ -- `apply2 (k : Nat → Nat) (n : Nat) : Nat := k n + k n` (apply2, body [par .many .val arrowSk, par .many .leaf] (add (app (v 1) [v 0 .leaf] .leaf) (app (v 1) [v 0 .leaf] .leaf)) .shared .leaf), - -- `retF (@once f : Nat → Nat) : Nat → Nat := f`; `retP` the same with `f` plain + -- `retF (@[once] f : Nat → Nat) : Nat → Nat := f`; `retP` the same with `f` plain (retF, body [par .once .val arrowSk] (v 0) .shared .val arrowSk), (retP, body [par .many .val arrowSk] (v 0) .shared .val arrowSk), (ext9, .extern #[par .many .val arrowSk] .shared .leaf .data), - -- `retG (@unique xs : List Nat) : Nat → Nat := fun _ => consume xs` + -- `retG (@[unique] xs : List Nat) : Nat → Nat := fun _ => consume xs` (retG, body [par .unique] (gClo 0) .shared .val arrowSk)] ++ ((List.range 10).map (· + 1)).toArray.flatMap (fun i => #[ (routeOnce i, body (routeParams .once i) (routeBody i) .shared .leaf), @@ -1968,7 +1968,7 @@ def routeGCases : List Case := [1, 7, 8, 10].map fun i => verdict := .refuse, run := [(0, .vioOrOof .revokedUse), (100000, .vio .revokedUse)] } /-! Route 7 with the once binding made inside the alternative: -`callTwice (match b with | _ => let (@once h) := k; h)` with `k` plain; the control binds `h` +`callTwice (match b with | _ => let (@[once] h) := k; h)` with `k` plain; the control binds `h` plainly. As landed the join reset the state to before the case, so `h`'s once flag was gone by the time the joined result flowed anywhere. -/ @@ -1997,8 +1997,8 @@ def r7Cases : List Case := [ `termSpine n` cut a spine at the checker's remaining depth, so `S6.mk 1 2 3 4 5 xs` checked at depth 6 (spine cut at 4) was judged as a partial application of `S6.mk` to two arguments followed -by four applications of a function value: `anCtor`'s partial branch does not apply the `@shared` -field's region test, and `anProj` gives a `@shared` field no region. -/ +by four applications of a function value: `anCtor`'s partial branch does not apply the `@[shared]` +field's region test, and `anProj` gives a `@[shared]` field no region. -/ def S6 := mem 354 def s6mk := ctr 354 0 @@ -2015,10 +2015,10 @@ def p6 : Prog := prog [(S6, .ind #[s6mk]), def nCases : List Case := [ -- REPAIR N: accepted as landed (at this depth) { label := "N g6 = (S6.mk 1 2 3 4 5 xs).sh, xs borrowed, at checker depth 6", P := p6, seed := g6, inp := oneList, - toCheck := [g6], verdict := .refuse "borrowEscape: a borrowed value stored in a @shared field", + toCheck := [g6], verdict := .refuse "borrowEscape: a borrowed value stored in a @[shared] field", run := [(0, .vioOrOof .borrowEscape), (100000, .vio .borrowEscape)], lim := { depth := 6 } }, { label := "N control: the same at the default depth", P := p6, seed := g6, inp := oneList, toCheck := [g6], - verdict := .refuse "borrowEscape: a borrowed value stored in a @shared field", + verdict := .refuse "borrowEscape: a borrowed value stored in a @[shared] field", run := [(0, .vioOrOof .borrowEscape), (100000, .vio .borrowEscape)] }, { label := "N control: xs not borrowed, at checker depth 6", P := p6, seed := g6p, inp := oneList, toCheck := [g6p], verdict := .accept, run := [(0, .valOrOof), (100000, .value)], lim := { depth := 6 } }, @@ -2027,13 +2027,13 @@ def nCases : List Case := [ { label := "N g6 at checker depth 3", P := p6, seed := g6, inp := oneList, toCheck := [g6], verdict := .decline, run := [(0, .vioOrOof .borrowEscape), (100000, .vio .borrowEscape)], lim := { depth := 3 } }, { label := "N g6 at checker depth 5", P := p6, seed := g6, inp := oneList, toCheck := [g6], - verdict := .refuse "borrowEscape: a borrowed value stored in a @shared field", + verdict := .refuse "borrowEscape: a borrowed value stored in a @[shared] field", run := [(0, .vioOrOof .borrowEscape), (100000, .vio .borrowEscape)], lim := { depth := 5 } }, { label := "N g6 at checker depth 7", P := p6, seed := g6, inp := oneList, toCheck := [g6], - verdict := .refuse "borrowEscape: a borrowed value stored in a @shared field", + verdict := .refuse "borrowEscape: a borrowed value stored in a @[shared] field", run := [(0, .vioOrOof .borrowEscape), (100000, .vio .borrowEscape)], lim := { depth := 7 } }, { label := "N g6 at checker depth 8", P := p6, seed := g6, inp := oneList, toCheck := [g6], - verdict := .refuse "borrowEscape: a borrowed value stored in a @shared field", + verdict := .refuse "borrowEscape: a borrowed value stored in a @[shared] field", run := [(0, .vioOrOof .borrowEscape), (100000, .vio .borrowEscape)], lim := { depth := 8 } }] /-! ### Finding 17 (repair O): a unique mode on a leaf (MT's encodings (a), (b); (c), (d) MR's) @@ -2060,7 +2060,7 @@ def oCase (label : String) (seed : Ref) (toCheck : List Ref) (refused : Bool) (v def oCases : List Case := [ -- REPAIR O: (a) to (d) accepted before - oCase "F17a let (@unique m) := n, n borrowed" SuiteFindings.u17a [SuiteFindings.u17a] false, -- L1: accepted + oCase "F17a let (@[unique] m) := n, n borrowed" SuiteFindings.u17a [SuiteFindings.u17a] false, -- L1: accepted oCase "F17a control: a plain let" u17ac [u17ac] false, -- L1: accepted oCase "F17a control: n not borrowed" SuiteFindings.u17ap [SuiteFindings.u17ap] false, oCase "F17b idU n, a unique result of class leaf" SuiteFindings.u17b [SuiteFindings.u17b, SuiteFindings.idU] false, -- L1: accepted @@ -2068,7 +2068,7 @@ def oCases : List Case := [ oCase "F17c idUP n, a polymorphic unique result (class val)" SuiteFindings.u17c [SuiteFindings.u17c, SuiteFindings.idUP] false, -- L1: accepted oCase "F17c control: n not borrowed" SuiteFindings.u17cp [SuiteFindings.u17cp, SuiteFindings.idUP] false, - oCase "F17d match w with | ⟨@unique m⟩ => m, w a borrowed wrapper" SuiteFindings.u17d [SuiteFindings.u17d] false, -- L1: accepted + oCase "F17d match w with | ⟨@[unique] m⟩ => m, w a borrowed wrapper" SuiteFindings.u17d [SuiteFindings.u17d] false, -- L1: accepted oCase "F17d control: w not borrowed" SuiteFindings.u17dp [SuiteFindings.u17dp] false] /-! ### Confined values reaching a place the checker treats as unconfined (repair P and after) @@ -2076,7 +2076,7 @@ def oCases : List Case := [ A borrowed list `xs` against the same program with `xs` plain (the control, accepted, runs clean). `mkSB (x : List Nat) : SBox := SBox.mk x` (finding 18), `mkSBU` the same with a unique result, `idSB (b : SBox) : SBox := b`, `isSB (b : SBox) : E := e0`. The other routes are covered elsewhere: -a `@shared` field filled directly (suite "a borrowed value stored in a @shared field and returned", +a `@[shared]` field filled directly (suite "a borrowed value stored in a @[shared] field and returned", refused by `anCtor`), through an extern (F5), a unique binding or result of a leaf and a wrapper (O), a closure capture (F9's control, D's F9), a partial application (F12 and its controls). -/ @@ -2095,11 +2095,11 @@ def pRoute : Nat → Term | _ => app (.const isSB .val) [app (.const mkSBU .val) [v 0]] .imm def pRouteName : Nat → String - | 2 => "a @shared field filled by a callee, projected ((mkSB xs).val, finding 18)" - | 4 => "a @shared field filled by a callee, matched (match mkSB xs with | ⟨y⟩ => y)" - | 5 => "a @shared field of a callee's unique result, projected ((mkSBU xs).val)" - | 12 => "a @shared field passed through a second callee ((idSB (mkSB xs)).val)" - | _ => "a callee's unique result holding a plain argument in a @shared field (isSB (mkSBU xs))" + | 2 => "a @[shared] field filled by a callee, projected ((mkSB xs).val, finding 18)" + | 4 => "a @[shared] field filled by a callee, matched (match mkSB xs with | ⟨y⟩ => y)" + | 5 => "a @[shared] field of a callee's unique result, projected ((mkSBU xs).val)" + | 12 => "a @[shared] field passed through a second callee ((idSB (mkSB xs)).val)" + | _ => "a callee's unique result holding a plain argument in a @[shared] field (isSB (mkSBU xs))" def pRoutes : List Nat := [2, 4, 5, 12, 13] def pB (i : Nat) : Ref := mem (443 + i) @@ -2138,7 +2138,7 @@ def pCases : List Case := pRoutes.flatMap fun i => toCheck := pP i :: helpersP, verdict := .accept, run := [(0, .valOrOof), (100000, .value)] }] -/-! ### Finding 19 (MU): `mkL (n : Nat) : @unique List Nat := [n]`, `c19 (@borrowed n : Nat) : List Nat := +/-! ### Finding 19 (MU): `mkL (n : Nat) : @[unique] List Nat := [n]`, `c19 (@[borrowed] n : Nat) : List Nat := mkL n`. The cell mkL builds holds the borrowed number, confined, and its unique return escapes. Closed by U (the number is retained by a call whose result is unique) and, at c19's return, by O (the unique result carries the argument's regions); accepted on the landed code [run: MU-f19-*]. -/ @@ -2226,7 +2226,7 @@ def v5oracle (t : IO.Ref Tally) : IO Unit := do /-! ### V5 Gap A: what an extern may obtain from a closure argument -`extA (f : Nat → Nat) : List Nat`, an extern. `leakA (@borrowed xs : List Nat) : List Nat := +`extA (f : Nat → Nat) : List Nat`, an extern. `leakA (@[borrowed] xs : List Nat) : List Nat := extA (fun n => n)`: the closure is formed where `xs` is bound but does not capture it, so to the checker it holds nothing and the call's result carries no region. `runR`'s closure cell keeps its whole environment (`formClosure` captures and confines only the `fvs`), and as landed @@ -2370,11 +2370,11 @@ def pGapB : Prog := prog [ (EmptyI, .ind #[]), -- `gb0 (x : Empty) (n : Nat) : Nat := Empty.casesOn x n` (gb0, body [par, par .many .leaf] (.case caseEmp (v 1) #[] #[v 0 .leaf] .leaf) .shared .leaf), - -- `gb0e (@erased e : Nat) (x : Empty) : Nat := Empty.casesOn x e`: an extra argument read erased + -- `gb0e (@[erased] e : Nat) (x : Empty) : Nat := Empty.casesOn x e`: an extra argument read erased (gb0e, body [par .erased .leaf, par] (.case caseEmp (v 0) #[] #[v 1 .leaf] .leaf) .shared .leaf), -- `gbL (xs : List) : Nat`, a case on a list with its `cons` alternative missing (gbL, body [par] (.case caseL (v 0) #[.natLit 0] #[] .leaf) .shared .leaf), - -- `gbL3 (@erased e : Nat) (xs : List) : Nat`, three alternatives for two, the third reading `e` + -- `gbL3 (@[erased] e : Nat) (xs : List) : Nat`, three alternatives for two, the third reading `e` (gbL3, body [par .erased .leaf, par] (.case caseL (v 0) #[.natLit 0, lam (par .many .leaf) (lam (par .many .val) (.natLit 1) .shared .leaf) .shared .leaf, v 1 .leaf] #[] .leaf) .shared .leaf), @@ -2467,7 +2467,7 @@ def erasedM : AllMode := { input := .erased } /-! ### V1 (note 12 §2.1): a raw recursor's rules against its inductive's constructors -`K | mk (a : Nat) (@erased b : Nat) (c : Nat)` (block 270, projections 271, 272), its recursor +`K | mk (a : Nat) (@[erased] b : Nat) (c : Nat)` (block 270, projections 271, 272), its recursor `K.rec.{u} (motive : K → Sort u) (minor : (a b c : Nat) → motive (K.mk a b c)) (t : K)` (273), whose rule's body is `minor a b c` (or the variables `rhs` names), and `useK (k : K) : Nat := K.rec.{1} (fun _ => Nat) (fun a b c => a) k` (274), a raw call. With @@ -2506,7 +2506,7 @@ def kRecords (natA : Address) (prop erases : Bool) (rhs : List Nat := [2, 1, 0]) [(addr 270, kBlock), (addr 271, projI (addr 270) 0), (addr 272, projC (addr 270) 0 0), (addr 273, kRec), (addr 274, useK)] -/-- A mutual block `A | a (x : Nat)`, `B | b0 (@erased x : Nat)` (280; projections 281 to 284) and +/-- A mutual block `A | a (x : Nat)`, `B | b0 (@[erased] x : Nat)` (280; projections 281 to 284) and `B.rec.{u} (motA) (motB) (mA : (x : Nat) → motA (A.a x)) (mB : (x : Nat) → motB (B.b0 x)) (t : B)` (285): two motives, minor premises for both inductives' constructors, one rule (`b0`, body `mB x`: it dispatches minor premise 1). `useB (n : Nat) (t : B) : Nat := @@ -2663,7 +2663,7 @@ def quotRecord (natA : Address) (m₇ : AllMode) : Ixon.Constant := univs := #[] } (fun sh idx o => if sh && idx == 0 && o == 0 then m₇ else {}) -/-- An inductive (310) with one constructor `mk : ∀ (a : Nat), e₀`, `e₀ = ∀ (@erased b : Nat), KS` +/-- An inductive (310) with one constructor `mk : ∀ (a : Nat), e₀`, `e₀ = ∀ (@[erased] b : Nat), KS` a sharing entry, declared with `fields` fields (2 is its type's count). -/ def ksRecord (natA : Address) (fields : Nat) : Ixon.Constant := withSection @@ -2672,7 +2672,7 @@ def ksRecord (natA : Address) (fields : Nat) : Ixon.Constant := (fun sh idx o => if sh && idx == 0 && o == 0 then erasedM else {}) /-- A definition (320) `d : ∀ (a : Nat), e₀ := fun (a : Nat) => e₁`, with the sharing entries -`e₀ = ∀ (@erased b : Nat), Nat` and `e₁ = fun (@erased b : Nat) => a`: its telescopes (two +`e₀ = ∀ (@[erased] b : Nat), Nat` and `e₁ = fun (@[erased] b : Nat) => a`: its telescopes (two binders each) continue in sharing entries. -/ def dRecord (natA : Address) : Ixon.Constant := withSection @@ -2743,7 +2743,7 @@ def useKARecord (natA : Address) (erases : Bool) : Address × Ixon.Constant := sharing := #[], refs := #[natA, addr 271, addr 272, addr 273], univs := #[.succ .zero] } (modeAt (if erases then [(0, 6, erasedM), (1, 6, erasedM)] else []))) -/-- A mutual block (350; projections 351 to 354) `A | a (@erased x : Nat)`, `B | b (y : A)`, with +/-- A mutual block (350; projections 351 to 354) `A | a (@[erased] x : Nat)`, `B | b (y : A)`, with `A.rec` (355) and `B.rec` (356), each over both motives and both minor premises `mA : (x : Nat) → motA (A.a x)`, `mB : (y : A) → (ih : motA y) → motB (B.b y)`. `B.rec`'s rule for `b` is `mB y (A.rec motA motB mA mB y)`: it dispatches `mB`, whose binders are default, so @@ -2930,11 +2930,11 @@ def v4WellFormed (t : IO.Ref Tally) : IO Unit := do A run body with no parameter is a static: `runR` runs it once (`static`), in whatever region its first caller has open, with no region of its own and no return rule, and shares its value; a caller's `anCall` takes its result unconfined. `anDef` read its result mode as for any body, so -a static with a `@borrowed` result could return a value confined to the region it was analysed -in. `idBor (@borrowed x : List) : @borrowed List := x`; `stB : @borrowed List := idBor [1]`; +a static with a `@[borrowed]` result could return a value confined to the region it was analysed +in. `idBor (@[borrowed] x : List) : @[borrowed] List := x`; `stB : @[borrowed] List := idBor [1]`; `useStB (n : Nat) : List := stB`: `idBor`'s return renames its region to the one enclosing the call, which in the run is `useStB`'s, so `useStB`'s shared return finds its result confined. -The test note 12 suggests, `stX : @borrowed List := extP [1]` with `extP (x : List) : List` an +The test note 12 suggests, `stX : @[borrowed] List := extP [1]` with `extP (x : List) : List` an extern returning its argument, and `useStX`: an extern cannot return a confined value at a borrowed result (`ExternVal`), so that run does not violate. Never from records: `readBody` gives a body without λs the result mode `shared`. -/ @@ -3032,7 +3032,7 @@ def eRecords : List (Address × Ixon.Constant) := /-- `L` (block 10; `L` 11, `L.nil` 12, `L.cons` 13), `L.rec.{u}` (14), `Lcases.{u} (motive) (t : L) (mnil) (mcons : (h : E) → (t : L) → motive (L.cons h t)) : motive t := L.rec motive mnil (fun h t _ => mcons h t) t` (15), `headOr` (16) and `mainL` (17); with `borrowL` (18, 19) `headOr`'s `l` is -`@borrowed` (node 1 of its type and of its value). -/ +`@[borrowed]` (node 1 of its type and of its value). -/ def lRecords (borrowL : Bool) : List (Address × Ixon.Constant) := let blk := blockOf #[indP 0 0 (.sort 0) #[ctorP 0 0 0 (.recur 0 #[]), ctorP 1 0 2 (alls [xRef 0, .recur 0 #[]] (.recur 0 #[]))]] #[a7 2] @@ -3326,7 +3326,7 @@ def v8Records (natA zeroA succA : Address) (casesAddr : Address) (a0 a1 a2 : Ixo #[a8 10, succA, zeroA, a7 73, a7 4, a7 72, a7 2] vRecords natA zeroA succA ++ [(casesAddr, vCases), (a8 10, isNil), (a8 11, mainV)] -/-- `kCases` over `kRecords`'s `K | mk (a : Nat) (@erased b : Nat) (c : Nat)` (`addr 270..273`), +/-- `kCases` over `kRecords`'s `K | mk (a : Nat) (@[erased] b : Nat) (c : Nat)` (`addr 270..273`), forwarding `m a b c` unshared (`shared = false`) or with `m a b` behind `sharing[0]` (`shared = true`), plus `badReadB (k : K) : Nat := kCases (fun _ => Nat) k (fun a b c => b)` reading the erased field. -/ def v8KRecords (natA : Address) (casesAddr : Address) (shared : Bool) : List (Address × Ixon.Constant) := @@ -3566,7 +3566,7 @@ def l1SNc := ctr 234 0 def l1ProjVal := mem 235 def pL1 : Prog := prog [ - -- `l1App (@borrowed xs : List) : Nat := let f := fun _ => len xs; f 0` + -- `l1App (@[borrowed] xs : List) : Nat := let f := fun _ => len xs; f 0` -- before L1 cleanup, `applyValue` gave the `.leaf` result `f.regs` and refused (l1App, body [par .borrowed] (.letE (.value .many) .val (lam (par .many .leaf) (lenOf (v 1)) .shared .leaf) @@ -3575,11 +3575,11 @@ def pL1 : Prog := prog [ (l1AppVal, body [par .borrowed] (.letE (.value .many) .val (lam (par .many .leaf) (v 1) .shared .val) (app (v 0) [.natLit 0]))), - -- `l1Proj (@borrowed k : K) : Nat := k.1` (inherited leaf field of a borrowed container) + -- `l1Proj (@[borrowed] k : K) : Nat := k.1` (inherited leaf field of a borrowed container) (l1Proj, body [par .borrowed] (.proj K 1 (v 0) .leaf) .shared .leaf), - -- `SN` with a `@shared` `Nat` field and an inherited `List` field + -- `SN` with a `@[shared]` `Nat` field and an inherited `List` field (l1SN, .ind #[l1SNc]), (l1SNc, .ctor l1SN 0 0 #[fld .leaf .shared, fld .val .inherited]), - -- `l1ProjS (@borrowed sn : SN) : Nat := sn.0` (`@shared` leaf field of a borrowed container) + -- `l1ProjS (@[borrowed] sn : SN) : Nat := sn.0` (`@[shared]` leaf field of a borrowed container) (l1ProjS, body [par .borrowed] (.proj l1SN 0 (v 0) .leaf) .shared .leaf), -- control: projecting the `.val` field of a borrowed `SN` is still refused (l1ProjVal, body [par .borrowed] (.proj l1SN 1 (v 0) .val))] @@ -3600,7 +3600,7 @@ def l1CleanupCases : List Case := [ { label := "L1 cleanup (anProj): projecting a leaf field of a borrowed container", P := pL1, seed := l1Proj, inp := oneKey, toCheck := [l1Proj], verdict := .accept, run := [(0, .value)] }, - { label := "L1 cleanup (anProj): projecting a @shared leaf field of a borrowed container", + { label := "L1 cleanup (anProj): projecting a @[shared] leaf field of a borrowed container", P := pL1, seed := l1ProjS, inp := oneSN, toCheck := [l1ProjS], verdict := .accept, run := [(0, .value)] }, { label := "L1 cleanup control (anProj): projecting a val field of a borrowed container", @@ -3651,7 +3651,7 @@ def runTableTests (t : IO.Ref Tally) : IO Unit := do let fEqDup := thmRecord eqFExpr #[a7 2, eqA, a9 1, a7 4] #[.succ .zero] let fNotThm := defRecord eqFExpr (.sort 0) #[a7 2, eqA, a9 1, a7 4] #[.succ .zero] let fModedEq := thmRecord eqFExpr #[a7 2, eqA, a9 1, a7 4] #[.succ .zero] #[] (modeAt [(0, 0, erasedM)]) - -- L-returning borrowed function `fBor (@borrowed l : L) : L := L.nil`, with bad eq_def returning `l` and ok eq_def returning `L.nil` + -- L-returning borrowed function `fBor (@[borrowed] l : L) : L := L.nil`, with bad eq_def returning `l` and ok eq_def returning `L.nil` let bor : AllMode := { input := .borrowed } let fBor := defRecord (.all (xRef 0) (xRef 0)) (.lam (xRef 0) (xRef 1)) #[a7 11, a7 12] #[] (modeAt [(0, 0, bor), (1, 0, bor)]) @@ -3808,11 +3808,11 @@ def pfAltBorTerm : Term := #[lam (par .borrowed) (lam (par .many .leaf) (v 1) .shared .val) .borrowed .val] #[] .val def pfProg : Prog := prog [ - -- Fix 2 (`evil6`): plain param wrapped in `@shared` field and transferred uniquely + -- Fix 2 (`evil6`): plain param wrapped in `@[shared]` field and transferred uniquely (pfInner6, body [par] (app (.const consumeSR .val) [app (.const sboxR .val) [v 0]] .leaf) .shared .leaf), (pfEvil6, body [par .borrowed] (app (.const pfInner6 .val) [v 0] .leaf) .shared .leaf), (pfMakeSB, body [par] (app (.const sboxR .val) [v 0])), - -- Repair U preserved for `.unique`-returning externs (`#87`): extern embeds plain arg in `@shared` field of fresh `@unique SBox` + -- Repair U preserved for `.unique`-returning externs (`#87`): extern embeds plain arg in `@[shared]` field of fresh `@[unique] SBox` (pfMkWeird, .extern #[par] .unique .val .data), (pfLeakWeird, body [par .borrowed] (.proj S 0 (app (.const pfMkWeird .val) [v 0]) .val)), (pfOkWeird, body [par .unique] (.proj S 0 (app (.const pfMkWeird .val) [v 0]) .val)), @@ -3833,7 +3833,7 @@ def pfProg : Prog := prog [ (pfStepOnceF, body [par .many .val pfSkGOnce, par .once .val arrowSk] (.letE (.value .many) .val (app (v 1) [v 0] .val) (add (app (v 0) [.natLit 0] .leaf) (app (v 0) [.natLit 1] .leaf))) .shared .leaf), - -- Fix 5 (`evil8b`): `Weird | mk (@shared s : List) (inh : List)` + -- Fix 5 (`evil8b`): `Weird | mk (@[shared] s : List) (inh : List)` (pfWeirdI, .ind #[pfWeirdC]), (pfWeirdC, .ctor pfWeirdI 0 0 #[fld .val .shared, fld .val .inherited]), (pfEvil8b, body [par .unique] (lenOf (.proj pfWeirdI 0 (v 0) .val)) .shared .leaf), @@ -3857,7 +3857,7 @@ def pfProg : Prog := prog [ (pfPairC, .ctor pfPairI 0 0 #[fld .val, fld .leaf]), (pfEvilAltBor, body [par .many .leaf] pfAltBorTerm .shared .val), (pfOkAltBor, body [par .many .leaf] pfAltBorTerm .borrowed .val), - -- Fix 9a (`applyValue` re-checks `valid f` after `callResult`): borrowed capture/PAP arg revoked by `@unique` arg + -- Fix 9a (`applyValue` re-checks `valid f` after `callResult`): borrowed capture/PAP arg revoked by `@[unique]` arg (pfMkId2, body [par .borrowed] (lam (par .unique) (lenOf (v 1)) .shared .leaf) .borrowed .val (.arrow .unique .data .shared .data)), (pfEvil9a, body [par .unique] @@ -3877,8 +3877,8 @@ def pfProg : Prog := prog [ (pfEvil9bLend, body [par .unique] (app (.const pfPlainUniq .val) [v 0, v 0] .leaf) .shared .leaf), (pfOk9b, body [par .unique, par .unique] (app (.const pfPlainUniq .val) [v 1, v 0] .leaf) .shared .leaf), (pfNullary, body [] (.natLit 0) .shared .leaf), - -- Fix 10 (`admitsNA`): 2-hop `.arrow → .unknown → .data` hiding under `@unique` (`evil11`), - -- `@once` (`evil10`), and contravariant `@once` domain (`evil12`) + -- Fix 10 (`admitsNA`): 2-hop `.arrow → .unknown → .data` hiding under `@[unique]` (`evil11`), + -- `@[once]` (`evil10`), and contravariant `@[once]` domain (`evil12`) (pfG2_11, body [par .unique, par .many .leaf] (app (.const consumeR .val) [v 1] .leaf) .shared .leaf), (pfEvil11b, body [par .many .val (.arrow .unique .data .shared .data), par .unique] (app (v 1) [v 0]) .shared .val .data), @@ -3935,7 +3935,7 @@ def pfProg : Prog := prog [ (.case pfCasePair (v 0) #[lam (par .unique) (lam (par .many .leaf) (v 1) .shared .val) .unique .val] #[] .val)) .unique .val), - -- Fix 12 (`anProj`/`caseField` preserve `deps` on `@shared` fields) + -- Fix 12 (`anProj`/`caseField` preserve `deps` on `@[shared]` fields) (pfSW14I, .ind #[pfSW14C]), (pfSW14C, .ctor pfSW14I 0 0 #[fld .val .shared, fld .leaf .inherited]), (pfMkWrap14, body [par] (app (.const pfSW14C .val) [v 0, .natLit 0])), @@ -3968,16 +3968,16 @@ def pfProg : Prog := prog [ .shared .leaf)] def pfCases : List Case := [ - { label := "Fix 2 (evil6): plain param stored in @shared field and consumed uniquely", + { label := "Fix 2 (evil6): plain param stored in @[shared] field and consumed uniquely", P := pfProg, seed := pfEvil6, inp := oneList, toCheck := [pfEvil6, pfInner6], verdict := .refuse "borrowEscape", run := [(0, .vioOrOof .borrowEscape), (100000, .vio .borrowEscape)] }, - { label := "Fix 2 control (makeSB): plain param stored in @shared field and returned .shared", + { label := "Fix 2 control (makeSB): plain param stored in @[shared] field and returned .shared", P := pfProg, seed := pfMakeSB, inp := oneList, toCheck := [pfMakeSB], verdict := .accept, run := [(0, .valOrOof), (100000, .value)] }, - { label := "Repair U + extern (mkWeird): borrowed arg passed to .unique extern with @shared field", + { label := "Repair U + extern (mkWeird): borrowed arg passed to .unique extern with @[shared] field", P := pfProg, ext := pfExtWeird, seed := pfLeakWeird, inp := oneList, toCheck := [pfLeakWeird], verdict := .refuse "borrowEscape", run := [(0, .vioOrOof .borrowEscape), (100000, .vio .borrowEscape)] }, - { label := "Repair U + extern control (mkWeird on @unique arg): accepted and clean", + { label := "Repair U + extern control (mkWeird on @[unique] arg): accepted and clean", P := pfProg, ext := pfExtWeird, seed := pfOkWeird, inp := oneList, toCheck := [pfOkWeird], verdict := .accept, run := [(0, .valOrOof), (100000, .value)] }, { label := "Fix 3 (evil10): closure returning unique capture at .unique called twice", @@ -3989,7 +3989,7 @@ def pfCases : List Case := [ { label := "Fix 4 (evil5d): multi-arg PAP via applyValue preserves onceOnly", P := pfProg, seed := pfStepOnce, inp := pfInG3, toCheck := [pfStepOnce, pfG3], verdict := .refuse, run := [(0, .vioOrOof .revokedUse), (100000, .vio .revokedUse)] }, - { label := "Fix 4 (evil5j): multi-arg @once PAP via applyValue preserves onceOnly", + { label := "Fix 4 (evil5j): multi-arg @[once] PAP via applyValue preserves onceOnly", P := pfProg, seed := pfStepOnceF, inp := pfInGOnce, toCheck := [pfStepOnceF, pfGOnce], verdict := .refuse, run := [(0, .vioOrOof .onceReentry), (100000, .vio .onceReentry)] }, { label := "Fix 6a: .prim PAP on borrowed .val argument refused as borrowEscape", @@ -4004,34 +4004,34 @@ def pfCases : List Case := [ { label := "Fix 8 (anAlt borrowed rename): .borrowed alt lambda renames closing region to enclosing region", P := pfProg, seed := pfEvilAltBor, inp := oneNat, toCheck := [pfEvilAltBor], verdict := .refuse "borrowEscape", run := [(0, .vioOrOof .borrowEscape), (100000, .vio .borrowEscape)] }, - { label := "Fix 8 control: .borrowed alt lambda returned @borrowed", + { label := "Fix 8 control: .borrowed alt lambda returned @[borrowed]", P := pfProg, seed := pfOkAltBor, inp := oneNat, toCheck := [pfOkAltBor], verdict := .accept, run := [(0, .valOrOof), (100000, .value)] }, - { label := "Fix 9a (applyValue valid after callResult): borrowed capture revoked by @unique arg", + { label := "Fix 9a (applyValue valid after callResult): borrowed capture revoked by @[unique] arg", P := pfProg, seed := pfEvil9a, inp := oneList, toCheck := [pfEvil9a, pfMkId2], verdict := .refuse "revokedUse", run := [(0, .vioOrOof .revokedUse), (100000, .vio .revokedUse)] }, - { label := "Fix 9a (curried PAP): ((f0 0) u) u revoked by @unique arg", + { label := "Fix 9a (curried PAP): ((f0 0) u) u revoked by @[unique] arg", P := pfProg, seed := pfEvil9aPap, inp := oneList, toCheck := [pfEvil9aPap, pfF0Curried], verdict := .refuse "revokedUse", run := [(0, .vioOrOof .revokedUse), (100000, .vio .revokedUse)] }, - { label := "Fix 9b (callResult post-loop valid): @borrowed precedes @unique on same binding", + { label := "Fix 9b (callResult post-loop valid): @[borrowed] precedes @[unique] on same binding", P := pfProg, seed := pfEvil9b, inp := oneList, toCheck := [pfEvil9b, pfBorUniq], verdict := .refuse "revokedUse", run := [(0, .vioOrOof .revokedUse), (100000, .vio .revokedUse)] }, - { label := "Fix 9b (lendPlain): plain param precedes @unique on same binding (leaf result)", + { label := "Fix 9b (lendPlain): plain param precedes @[unique] on same binding (leaf result)", P := pfProg, seed := pfEvil9bLend, inp := oneList, toCheck := [pfEvil9bLend, pfPlainUniq], verdict := .refuse "revokedUse", run := [(0, .vioOrOof .revokedUse), (100000, .vio .revokedUse)] }, - { label := "Fix 9b control: distinct bindings at plain + @unique params", + { label := "Fix 9b control: distinct bindings at plain + @[unique] params", P := pfProg, seed := pfOk9b, inp := twoLists, toCheck := [pfOk9b, pfPlainUniq], verdict := .accept, run := [(0, .valOrOof), (100000, .value)] }, - { label := "Fix 10 (evil11): 2-hop .arrow -> .unknown -> .data under @unique arrow refused", + { label := "Fix 10 (evil11): 2-hop .arrow -> .unknown -> .data under @[unique] arrow refused", P := pfProg, seed := pfSeed11, inp := oneList, toCheck := [pfSeed11, pfEvil11, pfEvil11b, pfG2_11], verdict := .refuse "mode skeletons differ", run := [(0, .vioOrOof .revokedUse), (100000, .vio .revokedUse)] }, - { label := "Fix 10 (evil10): 2-hop .arrow -> .unknown -> .data through @once param refused", + { label := "Fix 10 (evil10): 2-hop .arrow -> .unknown -> .data through @[once] param refused", P := pfProg, seed := pfSeed10, inp := oneList, toCheck := [pfSeed10, pfEvil10a, pfEvil10b, pfG3_10], verdict := .refuse "mode skeletons differ", run := [(0, .vioOrOof .revokedUse), (100000, .vio .revokedUse)] }, - { label := "Fix 10 (evil12): contravariant 2-hop .arrow -> .unknown -> .data in @once arrow domain refused", + { label := "Fix 10 (evil12): contravariant 2-hop .arrow -> .unknown -> .data in @[once] arrow domain refused", P := pfProg, seed := pfSeed12, inp := oneList, toCheck := [pfSeed12, pfHop1_12, pfHop2_12, pfEvil10b, pfG3_10], verdict := .refuse "mode skeletons differ", run := [(0, .vioOrOof .revokedUse), (100000, .vio .revokedUse)] }, - { label := "Fix 10 control: @once (Nat -> List) called with non-arrow-returning onceOnly closure", + { label := "Fix 10 control: @[once] (Nat -> List) called with non-arrow-returning onceOnly closure", P := pfProg, seed := pfOkOnce10, inp := oneList, toCheck := [pfOkOnce10, pfEvil10b], verdict := .accept, run := [(0, .valOrOof), (100000, .value)] }, { label := "Fix 11 (evil13): local shared dep dropped by anCase deps.filter demotes own to .shared", @@ -4040,22 +4040,22 @@ def pfCases : List Case := [ { label := "Fix 11 control (distinct local bindings in Weird.mk): accepted and clean", P := pfProg, seed := pfOk13, inp := pfInBoolTrue, toCheck := [pfOk13], verdict := .accept, run := [(0, .valOrOof), (100000, .value)] }, - { label := "Fix 11 control (anAlt @unique return clears killed deps): accepted and clean", + { label := "Fix 11 control (anAlt @[unique] return clears killed deps): accepted and clean", P := pfProg, seed := pfOkAltUniq, inp := oneList, toCheck := [pfOkAltUniq], verdict := .accept, run := [(0, .valOrOof), (100000, .value)] }, - { label := "Fix 12 (exploitProj): @shared projection keeps container deps across borrow lend", + { label := "Fix 12 (exploitProj): @[shared] projection keeps container deps across borrow lend", P := pfProg, seed := pfEvil14Proj, inp := oneList, toCheck := [pfEvil14Proj, pfWrap14, pfMkWrap14], verdict := .refuse "revokedUse", run := [(0, .vioOrOof .revokedUse), (100000, .vio .revokedUse)] }, - { label := "Fix 12 (exploitCase): @shared caseField keeps container deps across borrow lend", + { label := "Fix 12 (exploitCase): @[shared] caseField keeps container deps across borrow lend", P := pfProg, seed := pfEvil14Case, inp := oneList, toCheck := [pfEvil14Case, pfWrap14, pfMkWrap14], verdict := .refuse "revokedUse", run := [(0, .vioOrOof .revokedUse), (100000, .vio .revokedUse)] }, - { label := "Fix 12 control (consuming match on @unique @shared-field struct): accepted and clean", + { label := "Fix 12 control (consuming match on @[unique] @[shared]-field struct): accepted and clean", P := pfProg, seed := pfOk14Consume, inp := oneList, toCheck := [pfOk14Consume, pfWrap14, pfMkWrap14], verdict := .accept, run := [(0, .valOrOof), (100000, .value)] }, { label := "Fix 13 (evil15): multi-field anCtor with outer .imm cls still returns .val", P := pfProg, seed := pfEvil15, inp := oneList, toCheck := [pfEvil15], verdict := .refuse, run := [(0, .vioOrOof .borrowEscape), (100000, .vio .borrowEscape)] }, - { label := "Fix 13 control (distinct @unique fields in multi-field ctor): accepted and clean", + { label := "Fix 13 control (distinct @[unique] fields in multi-field ctor): accepted and clean", P := pfProg, seed := pfOk15, inp := twoLists, toCheck := [pfOk15], verdict := .accept, run := [(0, .valOrOof), (100000, .value)] }] @@ -4092,7 +4092,7 @@ def preProofExtraTests (t : IO.Ref Tally) : IO Unit := do (!Skel.data.admits arr && !arr.admits .data && !(Skel.dataApp .data .data).admits arr && !arr.admits (Skel.dataApp .data .data) && Skel.unknown.admits arr && arr.admits .unknown) "" - -- Fix 5 (`evil8b` `OwnTree`): self-aliased `@shared` + `inherited` slot triggers revokedUse in runR + -- Fix 5 (`evil8b` `OwnTree`): self-aliased `@[shared]` + `inherited` slot triggers revokedUse in runR -- and is excluded by `OwnTree`'s non-owned-slot disjointness let (b0, xs) := ({} : HB).list [1] let (bSelf, wSelf) := b0.alloc (.ctor pfWeirdC #[xs, xs]) @@ -4112,7 +4112,7 @@ def preProofExtraTests (t : IO.Ref Tally) : IO Unit := do | none => false | _ => false | none => false - check1 t "Fix 5 (evil8b): self-aliased @shared+inherited hits revokedUse and is rejected by OwnTree; disjoint passes" + check1 t "Fix 5 (evil8b): self-aliased @[shared]+inherited hits revokedUse and is rejected by OwnTree; disjoint passes" (match runSelf, runDisj with | .violation .revokedUse, .value .. => hasNonOwnedAlias bSelf.heap wSelf && !hasNonOwnedAlias bDisj.heap wDisj | _, _ => false) diff --git a/ModeRepairTests/README.md b/ModeRepairTests/README.md index 6aeccfa771..cec21ec3eb 100644 --- a/ModeRepairTests/README.md +++ b/ModeRepairTests/README.md @@ -36,15 +36,15 @@ some repairs in its own terms. The places where this branch does something else, that nothing states. Admitting more inputs is a widening of the statement, for later (with the fresh-extern extension in `REPAIRS.md`, "Statement widenings, not built"). - **Wrapper taint is done by repair P, not by their `r7`** (note 12 §2 item 2). P keeps the - container's regions at every `@shared` field, in a projection (`anProj`) and in a match - (`caseField`), so nothing is assumed about what a `@shared` field holds, whether the "cell" is a + container's regions at every `@[shared]` field, in a projection (`anProj`) and in a match + (`caseField`), so nothing is assumed about what a `@[shared]` field holds, whether the "cell" is a real cell or a trivial wrapper that is the field itself. With repair J (an ill-typed field is a stuck run) and repair L (the oracle declines at its depth limit instead of answering `val`), that covers finding 4 and finding 15 without `r7`'s wrapper condition. -- **A.7(b) is unnecessary because of P** (note 12 §2 item 6: the `@shared` fields of a fresh cell - an extern returns have empty taint). Since P the checker never takes a `@shared` field to be +- **A.7(b) is unnecessary because of P** (note 12 §2 item 6: the `@[shared]` fields of a fresh cell + an extern returns have empty taint). Since P the checker never takes a `@[shared]` field to be unconfined, and a call's result carries every argument's regions, so `ExternOk` needs no clause - about `@shared` slots. Finding 5 (the extern `mkS`) has been refused since P. + about `@[shared]` slots. Finding 5 (the extern `mkS`) has been refused since P. - **L1, the owner's finalized ruling (2026-11-13): a number is never confined** (commits W1 to W6, plus the finalized L1 cleanup in `Check.lean`). It changes `Eval.bindAt`: a borrowed binder no longer adds its region to a number. And it brings back, in a stronger form, the no-leaf refinement @@ -148,7 +148,7 @@ the ones before the rebase onto f2b985847. | + V8 + finalized L1 cleanup + `runTable` widening + hardened `DiffTest` (records, raw recursors, statics, closure-env externs; accepts 216,400 / refuses 583,600; + 40,000 v5 record subjects) | 0 (0 ill-typed hits, 0 record failures) | MR-final | | + Pre-proof soundness & spec fixes 1–10 (slow-path `Term.case`, `paramVal` caller confinement + Repair U preserved for `.unique` externs, `retCheck` unique-capture `deps` kill, `applyValue` PAP `onceOnly` + `Skel.admits`/`admitsNA` + `flowTo` `admitsNA` + `anCase` `r.onceOnly` refusal, `OwnTree` non-owned ctor-slot acyclicity + `ExternOk` acyclicity/`o'.cap < h'.nextCap`/`DataFieldOf`/`ExternFieldVal`/`ExternRetVal`/`PapArgOk` + `papSkel` `n < ps.size`, `.prim` PAP + erased `select`, `anAlt` borrowed region rename, `applyValue`/`callResult` post-transfer `valid`; accepts 215,759 / refuses 584,241, −641 vs `MR-final`; + 40,000 v5 record subjects) | 0 (0 ill-typed hits, 0 record failures) | MR-fixes110 | | + Fix 11 (`anCase` post-alt `valid r` + `isUniq r` own demotion before `deps.filter`; `anAlt` clear `deps`/`src` on `res.isUnique && rc == .val`; accepts 215,759 / refuses 584,241, +0 vs `MR-fixes110`, −641 vs `MR-final`; + 40,000 v5 record subjects) | 0 (0 ill-typed hits, 0 record failures) | MR-fixes111 | -| + Fix 12 (`anProj` + `caseField` preserve container `deps` on `@shared` fields; accepts 215,755 / refuses 584,245, −4 vs `MR-fixes111`, −645 vs `MR-final`; + 40,000 v5 record subjects) | 0 (0 ill-typed hits, 0 record failures) | MR-fixes112 | +| + Fix 12 (`anProj` + `caseField` preserve container `deps` on `@[shared]` fields; accepts 215,755 / refuses 584,245, −4 vs `MR-fixes111`, −645 vs `MR-final`; + 40,000 v5 record subjects) | 0 (0 ill-typed hits, 0 record failures) | MR-fixes112 | | + Fix 13 (`anCtor` `.ctor`-allocation branch always returns `cls := .val`, not outer `c`; accepts 215,755 / refuses 584,245, +0 vs `MR-fixes112`, −645 vs `MR-final`; + 40,000 v5 record subjects) | 0 (0 ill-typed hits, 0 record failures) | MR-fixes113 | At the rebased head (MV-dt-head): accept 188,860, refuse 611,140, decline 0; admitted by K diff --git a/MultiStark/MultiStark/FixedIxvmKey.lean b/MultiStark/MultiStark/FixedIxvmKey.lean index ef049e6042..23180ec12e 100644 --- a/MultiStark/MultiStark/FixedIxvmKey.lean +++ b/MultiStark/MultiStark/FixedIxvmKey.lean @@ -283,7 +283,10 @@ def parseIxvmKey (bytes : ByteArray) : Except String ParsedIxvmKey := do let (pp4, q5) ← readU16LE bytes q4 let (pp5, q6) ← readU16LE bytes q5 let (pp6, q7) ← readU16LE bytes q6 - let (n, q8) ← readU16LE bytes q7 + let (pp7, q7b) ← readU16LE bytes q7 + unless pp7 == 1 do + .error s!"fixed ixvm vk: stage-1 pinning is required, got {pp7}" + let (n, q8) ← readU16LE bytes q7b let (circuits, q9) ← readCircuitsGo bytes q8 n (Array.mkEmpty n) let (preprocessedCommit, q10) ← readOptCommit bytes q9 let (preprocessedIndices, q11) ← readOptIndicesGo bytes q10 0 preprocessedCommit.isSome n @@ -385,7 +388,8 @@ def buildTlimbs (pk : ParsedIxvmKey) : Array (Array Nat) := , u64Bytes pk.params.maxLogArity , u64Bytes pk.params.numQueries , u64Bytes pk.params.commitPowBits - , u64Bytes pk.params.queryPowBits ] + , u64Bytes pk.params.queryPowBits + , u64Bytes 1 ] let shapeHead : List (Array Nat) := [ u64Bytes 3, u64Bytes 2 ] ++ (digest32Limbs pk.vkDigestBytes).toList ++ diff --git a/MultiStark/MultiStark/FunctionGroups.lean b/MultiStark/MultiStark/FunctionGroups.lean index da8cb8ac07..c0a696d5af 100644 --- a/MultiStark/MultiStark/FunctionGroups.lean +++ b/MultiStark/MultiStark/FunctionGroups.lean @@ -19,20 +19,20 @@ def functionGroups : List (String × List String) := [ ("verifier_group_07", ["ProofDeserialize::read_u64", "ProofDeserialize::read_digest_vec_at_n", "ProofDeserialize::read_ext_vec", "StarkVerifier::fingerprint_vals", "StarkVerifier::accs_onto", "StarkVerifier::logup_fingerprint", "StarkVerifier::triple_mul", "Pcs::eg3_inv_nonzero", "Mmcs::frontier_sort", "Mmcs::frontier_level"]), ("verifier_group_08", ["ProofDeserialize::read_u8", "ProofDeserialize::read_u64_vec_vec_n", "${\"name\":\"Lists::concat\",\"types\":[\"field\"]}", "${\"name\":\"Lists::concat\",\"types\":[{\"array\":{\"element\":\"field\",\"length\":3}}]}"]), ("verifier_group_09", ["UInt64::to_field", "SystemDeserialize::read_vk_u16_limb", "SystemDeserialize::read_vk_u32_limb", "SystemDeserialize::read_field", "SystemDeserialize::read_sys_lookups_n", "ProofDeserialize::read_batch_opening_vec_n", "Pcs::bits_to_num", "Pcs::heights_fit", "Pcs::sample_query_indices", "Pcs::inject_maybe", "Pcs::compress_ordered", "Pcs::exp_by_bits", "StarkVerifier::last_acc", "StarkVerifier::batch_claims", "StarkVerifier::claims_onto"]), - ("verifier_group_10", ["SystemDeserialize::read_vk_tag", "UInt32::less_than_fields", "ProofDeserialize::read_u64_vec_n", "${\"name\":\"Lists::lookup\",\"types\":[{\"named\":{\"args\":[],\"name\":\"SystemDeserialize::SysNode\"}}]}", "Pcs::open_batch_2pt"]), + ("verifier_group_10", ["SystemDeserialize::read_vk_tag", "UInt32::less_than_fields", "ProofDeserialize::read_u64_vec_n", "${\"name\":\"Lists::lookup\",\"types\":[{\"named\":{\"args\":[],\"name\":\"SystemDeserialize::SysNode\"}}]}", "Pcs::open_batch_2pt", "Pcs::open_batch_3pt", "Pcs::bucket_update_3pt"]), ("verifier_group_11", ["SystemDeserialize::read_nodes_n", "${\"name\":\"Lists::length\",\"types\":[{\"array\":{\"element\":\"field\",\"length\":8}}]}", "StarkVerifier::limbs_onto", "Mmcs::frontier_leaves", "StarkVerifier::ood_fold"]), ("verifier_group_12", ["SystemDeserialize::read_node_ids_n", "ProofDeserialize::read_u64_vec", "StarkVerifier::rev_onto", "${\"name\":\"Lists::drop\",\"types\":[{\"named\":{\"args\":[],\"name\":\"SystemDeserialize::SysNode\"}}]}"]), - ("verifier_group_13", ["SystemDeserialize::lookup_groups_count", "ProofDeserialize::read_active_n", "ProofDeserialize::read_digest_vec_at", "ProofDeserialize::read_ext_vec_vec", "ProofDeserialize::read_ext_vec_vec_n", "ProofDeserialize::read_opened_round", "ProofDeserialize::read_preprocessed", "${\"name\":\"Lists::length\",\"types\":[{\"named\":{\"args\":[],\"name\":\"ProofDeserialize::ShardHeader\"}}]}", "StarkVerifier::pow2", "StarkVerifier::le_step", "StarkVerifier::headers_onto", "StarkVerifier::log_degrees_onto", "StarkVerifier::assert_log_degrees_ok", "StarkVerifier::count_ones", "StarkVerifier::two_adic_gen", "StarkVerifier::from_ext_basis", "${\"name\":\"Lists::length\",\"types\":[{\"named\":{\"args\":[],\"name\":\"ProofDeserialize::CommitPhaseMultiStep\"}}]}", "Mmcs::frontier_fold", "Pcs::has_height", "Pcs::collect_heights_desc", "Pcs::extract_step_sibs", "StarkVerifier::ext_exp_pow2", "Pcs::round_max_width", "Pcs::openings_at_height", "Pcs::max_openings_across_heights", "Pcs::tensor_num_challenges_loop", "Pcs::sample_ext_n", "Pcs::scale_ext_list", "Pcs::take_ext_list", "Pcs::tensor_weights_loop"]), + ("verifier_group_13", ["SystemDeserialize::lookup_groups_count", "ProofDeserialize::read_active_n", "ProofDeserialize::read_digest_vec_at", "ProofDeserialize::read_ext_vec_vec", "ProofDeserialize::read_ext_vec_vec_n", "ProofDeserialize::read_opened_round", "ProofDeserialize::read_preprocessed", "${\"name\":\"Lists::length\",\"types\":[{\"named\":{\"args\":[],\"name\":\"ProofDeserialize::ShardHeader\"}}]}", "StarkVerifier::pow2", "StarkVerifier::le_step", "StarkVerifier::headers_onto", "StarkVerifier::log_degrees_onto", "StarkVerifier::assert_log_degrees_ok", "StarkVerifier::count_ones", "StarkVerifier::two_adic_gen", "StarkVerifier::from_ext_basis", "${\"name\":\"Lists::length\",\"types\":[{\"named\":{\"args\":[],\"name\":\"ProofDeserialize::CommitPhaseMultiStep\"}}]}", "Mmcs::frontier_fold", "Pcs::has_height", "Pcs::collect_heights_desc", "Pcs::extract_step_sibs", "StarkVerifier::ext_exp_pow2", "StarkVerifier::assert_pinning_point_ok_loop", "StarkVerifier::split_ext_n", "StarkVerifier::split_shard_pins", "StarkVerifier::assert_shard_pins_shape", "StarkVerifier::assert_batch_pins_shape", "Pcs::append_pin_rows", "Pcs::round_max_width", "Pcs::openings_at_height", "Pcs::max_openings_across_heights", "Pcs::tensor_num_challenges_loop", "Pcs::sample_ext_n", "Pcs::scale_ext_list", "Pcs::take_ext_list", "Pcs::tensor_weights_loop"]), ("verifier_group_14", ["SystemDeserialize::read_opt_commit", "StarkVerifier::read_claim_vals_n", "ProofDeserialize::read_merkle_cap_vec_n", "ProofDeserialize::read_commit_phase_step_vec_n", "StarkVerifier::assert_shard_count_ok", "StarkVerifier::count_onto", "StarkVerifier::claims_onto_each", "Pcs::pcs_check_witness", "Mmcs::frontier_split", "Pcs::heights_prep", "Pcs::heights_max", "Pcs::fri_fold2", "StarkVerifier::read_claims_n"]), ("verifier_group_15", ["${\"name\":\"Lists::concat\",\"types\":[{\"array\":{\"element\":\"field\",\"length\":8}}]}", "ProofDeserialize::read_u8_at", "ProofDeserialize::read_ext_vec_n", "Mmcs::mmcs_verify_multi", "${\"name\":\"Lists::drop\",\"types\":[{\"ptr\":{\"target\":{\"array\":{\"element\":{\"array\":{\"element\":\"field\",\"length\":8}},\"length\":4}}}}]}", "Mmcs::frontier_merge"]), - ("verifier_group_16", ["UInt64::eq", "StarkVerifier::assert_same_limbs", "Pcs::ro_fold_2pt"]), + ("verifier_group_16", ["UInt64::eq", "StarkVerifier::assert_same_limbs", "Pcs::ro_fold_2pt", "Pcs::ro_fold_3pt"]), ("verifier_group_17", ["StarkVerifier::fold_roots", "StarkVerifier::eval_at", "${\"name\":\"Lists::length\",\"types\":[{\"named\":{\"args\":[],\"name\":\"SystemDeserialize::SysLookup\"}}]}"]), ("verifier_group_18", ["Pcs::select_rows", "Pcs::ro_fold_1pt", "StarkVerifier::assert_same_claims"]), ("verifier_group_19", ["Pcs::select_rows_le", "Pcs::bucket_update_1pt", "Pcs::open_quotient"]), ("aggr_group_00", ["Aggregation::aggr_read_address", "Aggregation::aggr_pack_address", "Aggregation::aggr_wrap", "Aggregation::aggr_child_check_env_digest", "Aggregation::aggr_verify_child", "Aggregation::aggr_claim_field", "${\"name\":\"Lists::lookup\",\"types\":[{\"array\":{\"element\":\"field\",\"length\":8}}]}", "Aggregation::aggr_claim_digest", "Aggregation::aggr_load_preimage", "Bytes::address_eq", "Bytes::address_eq_tail", "Aggregation::aggr_load_canonical_tree", "Aggregation::aggr_put_address", "Blake3::bytes_to_addr", "Aggregation::aggr_leaf_hash", "Aggregation::aggr_discharge_choice", "Aggregation::aggr_read_digest", "Aggregation::aggr_verify_range", "Aggregation::aggr_child_range", "Aggregation::aggr_binding_class", "Aggregation::aggr_verify_bridge_cert", "Aggregation::aggr_parse_eval", "Aggregation::aggr_read_u24_le", "Aggregation::aggr_is_class_role"]), ("aggr_group_01", ["Aggregation::aggr_load_sys", "Aggregation::aggr_pair", "Aggregation::aggr_address_order", "Aggregation::aggr_assert_union", "Aggregation::aggr_pair_structural", "Aggregation::aggr_range_leaf", "Aggregation::aggr_output_range", "Aggregation::aggr_parse_range", "Aggregation::aggr_range_join", "Aggregation::aggr_range_root", "Aggregation::aggr_discharge_binding", "Aggregation::aggr_cross_binding", "Aggregation::aggr_catalog_join", "Aggregation::aggr_dynamic_link", "Aggregation::aggr_read_u64_list_n", "Aggregation::aggr_discharge_eval", "Aggregation::aggr_parse_eval_discharge_out", "Aggregation::aggr_parse_eval_assumption", "Aggregation::aggr_verify_eq_check_record", "Aggregation::aggr_read_tagn0", "Aggregation::aggr_skip_expr", "Aggregation::aggr_read_tagn4", "Aggregation::aggr_assert_packed_addr_u64s", "Aggregation::aggr_assert_axioms_merge"]), ("aggr_group_02", ["Aggregation::aggr_assert_digest", "Aggregation::aggr_only_claim", "${\"name\":\"Lists::drop\",\"types\":[{\"array\":{\"element\":\"field\",\"length\":8}}]}", "Aggregation::aggr_assert_same_context_base", "Aggregation::aggr_opt_address_eq", "Aggregation::aggr_assert_strict_sorted", "Aggregation::aggr_reduce_hashes", "Aggregation::aggr_node_hash", "Aggregation::aggr_assert_difference", "Aggregation::aggr_next_assumption", "Aggregation::aggr_assert_structural_difference", "Aggregation::aggr_read_headers_n", "Aggregation::aggr_read_bits_n", "Aggregation::aggr_read_cap_n", "Aggregation::aggr_read_message", "Aggregation::aggr_batch_challenges", "Aggregation::aggr_parse_binding", "Aggregation::aggr_assert_same_context", "Aggregation::aggr_context_class", "Aggregation::aggr_put_addresses", "Aggregation::aggr_parse_catalog", "Aggregation::aggr_assert_security_envelope", "Aggregation::aggr_binding_eq_addr", "Aggregation::aggr_class_walk"]), - ("aggr_group_03", ["Aggregation::aggr_parse_check_env", "Aggregation::aggr_get_opt_address", "Aggregation::aggr_parse_tree_body", "Aggregation::aggr_canonical_root", "Aggregation::aggr_pair_hashes", "Aggregation::aggr_leaf_hashes", "Aggregation::aggr_assert_same_list", "Aggregation::aggr_load_optional_tree", "Aggregation::aggr_assert_disjoint", "Aggregation::aggr_assert_disjoint_union", "Aggregation::aggr_seek_subject", "Aggregation::aggr_fold_path", "Aggregation::aggr_read_header", "Aggregation::aggr_read_messages_n", "Aggregation::aggr_catalog_part", "Aggregation::aggr_parse_dynamic_link", "Aggregation::aggr_read_u32_le", "Aggregation::aggr_parse_check", "Aggregation::aggr_parse_eval_assumed", "Aggregation::aggr_extract_removed_leaf", "Aggregation::aggr_find_role_addr", "Aggregation::aggr_skip_tagn0_n", "Aggregation::aggr_skip_exprs_n", "Aggregation::aggr_load_preamble"]) + ("aggr_group_03", ["Aggregation::aggr_parse_check_env", "Aggregation::aggr_get_opt_address", "Aggregation::aggr_parse_tree_body", "Aggregation::aggr_canonical_root", "Aggregation::aggr_pair_hashes", "Aggregation::aggr_leaf_hashes", "Aggregation::aggr_assert_same_list", "Aggregation::aggr_load_optional_tree", "Aggregation::aggr_assert_disjoint", "Aggregation::aggr_assert_disjoint_union", "Aggregation::aggr_seek_subject", "Aggregation::aggr_fold_path", "Aggregation::aggr_read_header", "Aggregation::aggr_read_messages_n", "Aggregation::aggr_read_ext", "Aggregation::aggr_read_ext_vec_n", "Aggregation::aggr_read_ext_vec_vec_n", "Aggregation::aggr_read_pinned_n", "Aggregation::aggr_catalog_part", "Aggregation::aggr_parse_dynamic_link", "Aggregation::aggr_read_u32_le", "Aggregation::aggr_parse_check", "Aggregation::aggr_parse_eval_assumed", "Aggregation::aggr_extract_removed_leaf", "Aggregation::aggr_find_role_addr", "Aggregation::aggr_skip_tagn0_n", "Aggregation::aggr_skip_exprs_n", "Aggregation::aggr_load_preamble"]) ] end MultiStark diff --git a/MultiStark/MultiStark/Modules/Aggregation.lean b/MultiStark/MultiStark/Modules/Aggregation.lean index 5790b78948..16ee732dec 100644 --- a/MultiStark/MultiStark/Modules/Aggregation.lean +++ b/MultiStark/MultiStark/Modules/Aggregation.lean @@ -1094,7 +1094,50 @@ module Aggregation { } } - fn aggr_load_preamble(key: Field, d: Bytes::AddressRef) -> (Lists::List, Lists::List) { + fn aggr_read_ext(s: Bytes::Stream) -> (ProofDeserialize::Ext, Bytes::Stream) { + let (a, s0) = ProofDeserialize::read_u64(s); + let (b, s1) = ProofDeserialize::read_u64(s0); + let (c, s2) = ProofDeserialize::read_u64(s1); + assert_eq!(Goldilocks::gl_lt_p(a), 1); + assert_eq!(Goldilocks::gl_lt_p(b), 1); + assert_eq!(Goldilocks::gl_lt_p(c), 1); + ([Goldilocks::gl_val(a), Goldilocks::gl_val(b), Goldilocks::gl_val(c)], s2) + } + + fn aggr_read_ext_vec_n(s: Bytes::Stream, n: Field) -> (Lists::List, Bytes::Stream) { + match n { + 0 => { ((&(Lists::Node::Nil)), s) } , + _ => { + let (e, s1) = aggr_read_ext(s); + let (rest, s2) = aggr_read_ext_vec_n(s1, n - 1); + ((&(Lists::Node::Cons(e, rest))), s2) } , + } + } + + fn aggr_read_ext_vec_vec_n(s: Bytes::Stream, n: Field) -> (Lists::List>, Bytes::Stream) { + match n { + 0 => { ((&(Lists::Node::Nil)), s) } , + _ => { + let (m, s0) = ProofDeserialize::read_count(s); + let (row, s1) = aggr_read_ext_vec_n(s0, m); + let (rest, s2) = aggr_read_ext_vec_vec_n(s1, n - 1); + ((&(Lists::Node::Cons(row, rest))), s2) } , + } + } + + fn aggr_read_pinned_n(s: Bytes::Stream, n: Field) -> (ProofDeserialize::OpenedRound, Bytes::Stream) { + match n { + 0 => { ((&(Lists::Node::Nil)), s) } , + _ => { + let (m, s0) = ProofDeserialize::read_count(s); + let (shard, s1) = aggr_read_ext_vec_vec_n(s0, m); + let (rest, s2) = aggr_read_pinned_n(s1, n - 1); + ((&(Lists::Node::Cons(shard, rest))), s2) } , + } + } + + fn aggr_load_preamble(key: Field, d: Bytes::AddressRef) + -> (Lists::List, Lists::List, ProofDeserialize::OpenedRound) { let (idx, len) = hint::<(Field, Field)>("stark.io.info", (0, key)); let bytes = StarkIO::read_byte_stream(0, idx, len); assert_eq!(Bytes::address_eq(Blake3::bytes_to_addr(bytes), d), 1, @@ -1102,27 +1145,33 @@ module Aggregation { let (nh, s1) = ProofDeserialize::read_count(bytes); let (headers, s2) = aggr_read_headers_n(s1, nh); let (nm, s3) = ProofDeserialize::read_count(s2); - let (messages, stop) = aggr_read_messages_n(s3, nm); + let (messages, s4) = aggr_read_messages_n(s3, nm); + let (np, s5) = ProofDeserialize::read_count(s4); + let (pinned, stop) = aggr_read_pinned_n(s5, np); let Lists::Node::Nil = (*(stop)); - (headers, messages) + (headers, messages, pinned) } fn aggr_batch_challenges(sys: SystemDeserialize::Sys, headers: Lists::List, - messages: Lists::List) -> (ProofDeserialize::Ext, ProofDeserialize::Ext, Bytes::Stream) { - let SystemDeserialize::Sys::Mk(_params, tlimbs, _circuits, commit, _prep_indices) = sys; + messages: Lists::List, pinned: ProofDeserialize::OpenedRound) + -> (ProofDeserialize::Ext, ProofDeserialize::Ext, ProofDeserialize::Ext, Bytes::Stream) { + let SystemDeserialize::Sys::Mk(_params, tlimbs, circuits, commit, prep_indices) = sys; + assert_eq!(StarkVerifier::assert_batch_pins_shape(circuits, prep_indices, headers, pinned), 1); let prep_cap = StarkVerifier::opt_commit_cap(commit); - Transcript::batch_fiat_shamir(tlimbs, prep_cap, headers, messages) + Transcript::batch_fiat_shamir(tlimbs, prep_cap, headers, messages, pinned) } - fn aggr_verify_range(sys: SystemDeserialize::Sys, headers: Lists::List, i: Field, shard: Field, - n: Field, input: Bytes::Stream, lch: ProofDeserialize::Ext, fch: ProofDeserialize::Ext, acc: ProofDeserialize::Ext) -> (ProofDeserialize::Ext, Field) { + fn aggr_verify_range(sys: SystemDeserialize::Sys, headers: Lists::List, + pinned: ProofDeserialize::OpenedRound, i: Field, shard: Field, + n: Field, input: Bytes::Stream, z0: ProofDeserialize::Ext, lch: ProofDeserialize::Ext, fch: ProofDeserialize::Ext, acc: ProofDeserialize::Ext) -> (ProofDeserialize::Ext, Field) { match n { 0 => { (acc, i) } , _ => { let Lists::Node::Cons(h, hrest) = (*(headers)); + let Lists::Node::Cons(sp, sprest) = (*(pinned)); let (p, j) = ProofDeserialize::read_proof(i); - let r = StarkVerifier::verify_shard(sys, h, shard, p, input, lch, fch); - aggr_verify_range(sys, hrest, j, shard + 1, n - 1, input, lch, fch, + let r = StarkVerifier::verify_shard(sys, h, shard, p, input, z0, lch, fch, sp); + aggr_verify_range(sys, hrest, sprest, j, shard + 1, n - 1, input, z0, lch, fch, Pcs::eg3_add(acc, r)) } , } } @@ -1147,8 +1196,8 @@ module Aggregation { out_claim_digest: [Field; 8]) -> () { let sys = aggr_load_sys(0, ixvm_vk_digest, self_vk_digest); let (d, lo_limb, hi_limb, r) = aggr_output_range(out_claim_digest); - let (headers, messages) = aggr_load_preamble(0, d); - let (lch, fch, input) = aggr_batch_challenges(sys, headers, messages); + let (headers, messages, pinned) = aggr_load_preamble(0, d); + let (z0, lch, fch, input) = aggr_batch_challenges(sys, headers, messages, pinned); assert_eq!(StarkVerifier::bytes8_le(lo_limb, hi_limb), 1, "aggr range: the range ends before it starts"); let lo = UInt64::to_field(lo_limb); @@ -1156,8 +1205,8 @@ module Aggregation { let (pidx, plen) = hint::<(Field, Field)>("stark.io.info", (0, 1)); let (count, j) = ProofDeserialize::read_count_at(pidx); assert_eq!(count, n, "aggr range: proof count differs from the range"); - let (total, stop) = aggr_verify_range(sys, Lists::drop(headers, lo), j, lo, - n, input, lch, fch, [0, 0, 0]); + let (total, stop) = aggr_verify_range(sys, Lists::drop(headers, lo), Lists::drop(pinned, lo), j, lo, + n, input, z0, lch, fch, [0, 0, 0]); assert_eq!(stop, pidx + plen, "aggr range: trailing bytes after the proofs"); assert_eq!(Pcs::eg3_eq(total, r), 1, "aggr range: residual sum differs from the statement"); @@ -1193,7 +1242,7 @@ module Aggregation { let (d, lo, hi, r) = aggr_child_range(0, ixvm_vk_digest, self_vk_digest, verify_idx, aggr_idx, allowed_digest); let sys = aggr_load_sys(0, ixvm_vk_digest, self_vk_digest); - let (headers, messages) = aggr_load_preamble(1, d); + let (headers, messages, pinned) = aggr_load_preamble(1, d); let k = Lists::length(headers); assert_eq!(StarkVerifier::assert_shard_count_ok(k), 1); assert_eq!(StarkVerifier::assert_batch_bounds(sys, headers), 1); @@ -1204,7 +1253,7 @@ module Aggregation { assert_eq!(StarkVerifier::assert_closure_pairs(messages, 0, 0), 1); let SystemDeserialize::Sys::Mk(_params, _tlimbs, circuits, _commit, _prep_indices) = sys; assert_eq!(StarkVerifier::assert_closure_widths_ok(circuits, headers, messages), 1); - let (lch, fch, _input) = aggr_batch_challenges(sys, headers, messages); + let (_z0, lch, fch, _input) = aggr_batch_challenges(sys, headers, messages, pinned); let total = StarkVerifier::messages_acc(r, messages, lch, fch); assert_eq!(StarkVerifier::ext_is_zero(total), 1, "aggr range: the batch does not balance"); let claim = aggr_only_claim(StarkVerifier::batch_claims(headers)); diff --git a/MultiStark/MultiStark/Modules/FixedIxvmKey.lean b/MultiStark/MultiStark/Modules/FixedIxvmKey.lean index a3597d278d..9b6a3c8297 100644 --- a/MultiStark/MultiStark/Modules/FixedIxvmKey.lean +++ b/MultiStark/MultiStark/Modules/FixedIxvmKey.lean @@ -536,16 +536,88 @@ module FixedIxvmKey { } } + fn split_shard_pins_fixed(acirc_ids: Lists::List, + aprep: Lists::List, + shard_pins: Lists::List>) + -> (Lists::List>, Lists::List>) { + match (*(acirc_ids)) { + Lists::Node::Nil => { + let Lists::Node::Nil = (*(aprep)); + let Lists::Node::Nil = (*(shard_pins)); + ((&(Lists::Node::Nil)), (&(Lists::Node::Nil))) } , + Lists::Node::Cons(ci, crest) => { + let &Lists::Node::Cons(pi, prest) = aprep; + let &Lists::Node::Cons(prow, srest) = shard_pins; + let cm = key_circuit(ci); + let mw = cm[8]; + let pw = cm[9]; + let (fixed_rest, main_rest) = split_shard_pins_fixed(crest, prest, srest); + match pi { + SystemDeserialize::OptIdx::NoIdx => { + assert_eq!(Lists::length(prow), mw); + (fixed_rest, (&(Lists::Node::Cons(prow, main_rest)))) } , + SystemDeserialize::OptIdx::SomeIdx(_idx) => { + let (fp, mp) = StarkVerifier::split_ext_n(prow, pw); + assert_eq!(Lists::length(mp), mw); + ((&(Lists::Node::Cons(fp, fixed_rest))), (&(Lists::Node::Cons(mp, main_rest)))) } , + } } , + } + } + + fn assert_shard_pins_shape_fixed(ci: Field, rem: Field, active: Lists::List, + shard_pins: Lists::List>) -> Field { + match rem { + 0 => { + let Lists::Node::Nil = (*(active)); + let Lists::Node::Nil = (*(shard_pins)); + 1 } , + _ => { + let &Lists::Node::Cons(b, arest) = active; + assert_eq!(b * (b - 1), 0); + match b { + 0 => { assert_shard_pins_shape_fixed(ci + 1, rem - 1, arest, shard_pins) } , + _ => { + let &Lists::Node::Cons(prow, srest) = shard_pins; + let cm = key_circuit(ci); + let mw = cm[8]; + let pw = cm[9]; + let fw = match cm[12] { + 0 => { 0 } , + _ => { pw } , + }; + assert_eq!(Lists::length(prow), fw + mw); + assert_shard_pins_shape_fixed(ci + 1, rem - 1, arest, srest) } , + } } , + } + } + + fn assert_batch_pins_shape_fixed(headers: Lists::List, + pinned: ProofDeserialize::OpenedRound) -> Field { + match (*(headers)) { + Lists::Node::Nil => { + let Lists::Node::Nil = (*(pinned)); + 1 } , + Lists::Node::Cons(h, hrest) => { + let &Lists::Node::Cons(sp, prest) = pinned; + let ProofDeserialize::ShardHeader::Mk(active, _cap, _lds, _claims) = h; + assert_eq!(assert_shard_pins_shape_fixed(0, CIRCUITS, active, sp), 1); + assert_batch_pins_shape_fixed(hrest, prest) } , + } + } + fn batch_challenges_fixed(headers: Lists::List, - messages: Lists::List) - -> (ProofDeserialize::Ext, ProofDeserialize::Ext, Bytes::Stream) { + messages: Lists::List, + pinned: ProofDeserialize::OpenedRound) + -> (ProofDeserialize::Ext, ProofDeserialize::Ext, ProofDeserialize::Ext, Bytes::Stream) { + assert_eq!(assert_batch_pins_shape_fixed(headers, pinned), 1); let tlimbs = fixed_tlimbs(0, TLIMBS); let prep_cap = fixed_prep_cap(); - Transcript::batch_fiat_shamir(tlimbs, prep_cap, headers, messages) + Transcript::batch_fiat_shamir(tlimbs, prep_cap, headers, messages, pinned) } fn verify_shard_fixed(header: ProofDeserialize::ShardHeader, shard: Field, proof: ProofDeserialize::Proof, - input: Bytes::Stream, lch: ProofDeserialize::Ext, fch: ProofDeserialize::Ext) -> ProofDeserialize::Ext { + input: Bytes::Stream, z0: ProofDeserialize::Ext, lch: ProofDeserialize::Ext, fch: ProofDeserialize::Ext, + shard_pins: Lists::List>) -> ProofDeserialize::Ext { let log_blowup = PARAMS_0; let cap_height = PARAMS_1; let log_final_poly_len = PARAMS_2; @@ -612,6 +684,8 @@ module FixedIxvmKey { assert_eq!(StarkVerifier::assert_same_u8s(h_lds, log_degrees), 1); assert_eq!(StarkVerifier::assert_log_degrees_ok(log_degrees), 1); assert_eq!(StarkVerifier::count_ones(active), Lists::length(log_degrees)); + assert_eq!(StarkVerifier::assert_pinning_point_ok(z0, log_degrees, log_blowup), 1); + let (fixed_pins, main_pins) = split_shard_pins_fixed(acirc_ids, aprep, shard_pins); let prep_cap = fixed_prep_cap(); let _prep_match = match HAS_COMMIT { 0 => { @@ -627,37 +701,39 @@ module FixedIxvmKey { let _ood = ood_loop_fixed(acirc_ids, aprep, log_degrees, accs, stage1, stage2, prep_opt, q_opened, acc0, lch, fch, alpha, zeta); assert_eq!(Pcs::pcs_fri_verify(post_zeta_input, stage1, stage2, q_opened, prep_opt, opening, - s1c, s2c, qc, prep_cap, aprep, log_degrees, zeta, + s1c, s2c, qc, prep_cap, aprep, log_degrees, zeta, z0, main_pins, fixed_pins, num_circuits, log_blowup, num_queries, commit_pow_bits, query_pow_bits), 1); StarkVerifier::last_acc(accs) } fn verify_shards_fixed(headers: Lists::List, - proofs: Lists::List, shard: Field, - input: Bytes::Stream, lch: ProofDeserialize::Ext, fch: ProofDeserialize::Ext, + proofs: Lists::List, pinned: ProofDeserialize::OpenedRound, shard: Field, + input: Bytes::Stream, z0: ProofDeserialize::Ext, lch: ProofDeserialize::Ext, fch: ProofDeserialize::Ext, acc: ProofDeserialize::Ext) -> ProofDeserialize::Ext { match (*(headers)) { Lists::Node::Nil => { let Lists::Node::Nil = (*(proofs)); + let Lists::Node::Nil = (*(pinned)); acc } , Lists::Node::Cons(h, hrest) => { let Lists::Node::Cons(p, prest) = (*(proofs)); - let r = verify_shard_fixed(h, shard, p, input, lch, fch); - verify_shards_fixed(hrest, prest, shard + 1, input, lch, fch, Pcs::eg3_add(acc, r)) } , + let Lists::Node::Cons(sp, sprest) = (*(pinned)); + let r = verify_shard_fixed(h, shard, p, input, z0, lch, fch, sp); + verify_shards_fixed(hrest, prest, sprest, shard + 1, input, z0, lch, fch, Pcs::eg3_add(acc, r)) } , } } fn verify_batch_fixed(batch: ProofDeserialize::Batch) -> Lists::List> { - let ProofDeserialize::Batch::Mk(headers, messages, proofs) = batch; + let ProofDeserialize::Batch::Mk(headers, messages, proofs, pinned) = batch; assert_eq!(StarkVerifier::assert_shard_count_ok(Lists::length(headers)), 1); assert_eq!(assert_batch_bounds_fixed(headers), 1); assert_eq!(Lists::length(proofs), Lists::length(headers)); assert_eq!(StarkVerifier::assert_closure_pairs(messages, 0, 0), 1); assert_eq!(assert_closure_widths_ok_fixed(headers, messages), 1); - let (lch, fch, input) = batch_challenges_fixed(headers, messages); + let (z0, lch, fch, input) = batch_challenges_fixed(headers, messages, pinned); let acc = StarkVerifier::messages_acc([0, 0, 0], messages, lch, fch); - let total = verify_shards_fixed(headers, proofs, 0, input, lch, fch, acc); + let total = verify_shards_fixed(headers, proofs, pinned, 0, input, z0, lch, fch, acc); assert_eq!(StarkVerifier::ext_is_zero(total), 1); StarkVerifier::batch_claims(headers) } @@ -719,16 +795,18 @@ module Aggregation { } fn aggr_verify_range_fixed(headers: Lists::List, + pinned: ProofDeserialize::OpenedRound, i: Field, shard: Field, n: Field, input: Bytes::Stream, - lch: ProofDeserialize::Ext, fch: ProofDeserialize::Ext, + z0: ProofDeserialize::Ext, lch: ProofDeserialize::Ext, fch: ProofDeserialize::Ext, acc: ProofDeserialize::Ext) -> (ProofDeserialize::Ext, Field) { match n { 0 => { (acc, i) } , _ => { let Lists::Node::Cons(h, hrest) = (*(headers)); + let Lists::Node::Cons(sp, sprest) = (*(pinned)); let (p, j) = ProofDeserialize::read_proof(i); - let r = FixedIxvmKey::verify_shard_fixed(h, shard, p, input, lch, fch); - aggr_verify_range_fixed(hrest, j, shard + 1, n - 1, input, lch, fch, + let r = FixedIxvmKey::verify_shard_fixed(h, shard, p, input, z0, lch, fch, sp); + aggr_verify_range_fixed(hrest, sprest, j, shard + 1, n - 1, input, z0, lch, fch, Pcs::eg3_add(acc, r)) } , } } @@ -737,8 +815,8 @@ module Aggregation { out_claim_digest: [Field; 8]) -> () { FixedIxvmKey::assert_vk_digest(ixvm_vk_digest); let (d, lo_limb, hi_limb, r) = aggr_output_range(out_claim_digest); - let (headers, messages) = aggr_load_preamble(0, d); - let (lch, fch, input) = FixedIxvmKey::batch_challenges_fixed(headers, messages); + let (headers, messages, pinned) = aggr_load_preamble(0, d); + let (z0, lch, fch, input) = FixedIxvmKey::batch_challenges_fixed(headers, messages, pinned); assert_eq!(StarkVerifier::bytes8_le(lo_limb, hi_limb), 1, "aggr range: the range ends before it starts"); let lo = UInt64::to_field(lo_limb); @@ -746,8 +824,8 @@ module Aggregation { let (pidx, plen) = hint::<(Field, Field)>("stark.io.info", (0, 1)); let (count, j) = ProofDeserialize::read_count_at(pidx); assert_eq!(count, n, "aggr range: proof count differs from the range"); - let (total, stop) = aggr_verify_range_fixed(Lists::drop(headers, lo), j, lo, - n, input, lch, fch, [0, 0, 0]); + let (total, stop) = aggr_verify_range_fixed(Lists::drop(headers, lo), Lists::drop(pinned, lo), j, lo, + n, input, z0, lch, fch, [0, 0, 0]); assert_eq!(stop, pidx + plen, "aggr range: trailing bytes after the proofs"); assert_eq!(Pcs::eg3_eq(total, r), 1, "aggr range: residual sum differs from the statement"); @@ -760,7 +838,7 @@ module Aggregation { let (d, lo, hi, r) = aggr_child_range(0, ixvm_vk_digest, self_vk_digest, verify_idx, aggr_idx, allowed_digest); FixedIxvmKey::assert_vk_digest(ixvm_vk_digest); - let (headers, messages) = aggr_load_preamble(1, d); + let (headers, messages, pinned) = aggr_load_preamble(1, d); let k = Lists::length(headers); assert_eq!(StarkVerifier::assert_shard_count_ok(k), 1); assert_eq!(FixedIxvmKey::assert_batch_bounds_fixed(headers), 1); @@ -770,7 +848,7 @@ module Aggregation { "aggr range: root range does not end at the last shard"); assert_eq!(StarkVerifier::assert_closure_pairs(messages, 0, 0), 1); assert_eq!(FixedIxvmKey::assert_closure_widths_ok_fixed(headers, messages), 1); - let (lch, fch, _input) = FixedIxvmKey::batch_challenges_fixed(headers, messages); + let (_z0, lch, fch, _input) = FixedIxvmKey::batch_challenges_fixed(headers, messages, pinned); let total = StarkVerifier::messages_acc(r, messages, lch, fch); assert_eq!(StarkVerifier::ext_is_zero(total), 1, "aggr range: the batch does not balance"); let claim = aggr_only_claim(StarkVerifier::batch_claims(headers)); diff --git a/MultiStark/MultiStark/Modules/Pcs.lean b/MultiStark/MultiStark/Modules/Pcs.lean index 6273c9699e..b85cafecb2 100644 --- a/MultiStark/MultiStark/Modules/Pcs.lean +++ b/MultiStark/MultiStark/Modules/Pcs.lean @@ -47,11 +47,11 @@ module Pcs { enum FrontierNode { Mk(Field, Lists::List, Lists::List>, &[UInt32::U32; 8]) } - enum Bucket { Mk(Field, Lists::List, ProofDeserialize::Ext, ProofDeserialize::Ext) } + enum Bucket { Mk(Field, Lists::List, ProofDeserialize::Ext, ProofDeserialize::Ext, ProofDeserialize::Ext) } enum RollBucket { Mk(Field, ProofDeserialize::Ext) } - enum HeightInfo { Mk(Field, ProofDeserialize::Ext, Goldilocks::Goldilocks, ProofDeserialize::Ext, ProofDeserialize::Ext) } + enum HeightInfo { Mk(Field, ProofDeserialize::Ext, Goldilocks::Goldilocks, ProofDeserialize::Ext, ProofDeserialize::Ext, ProofDeserialize::Ext) } fn compress_ordered(bit: Field, d: &[UInt32::U32; 8], s: ProofDeserialize::DigestP) -> &[UInt32::U32; 8] { match bit { @@ -197,10 +197,10 @@ module Pcs { ProofDeserialize::PreprocessedOpt::SomePreprocessed(_r) => { match pi { SystemDeserialize::OptIdx::NoIdx => { 0 } , - SystemDeserialize::OptIdx::SomeIdx(_j) => { 2 } , + SystemDeserialize::OptIdx::SomeIdx(_j) => { 3 } , } } , }; - 5 + p_add + rest } , + 6 + p_add + rest } , _ => { rest } , } } , } @@ -315,6 +315,46 @@ module Pcs { } } + -- Precomputation-side 3-point OOD dot product (`zeta`, `zeta*g`, `z0`): + -- computes `(Σ w_j * z0_j, Σ w_j * z1_j, Σ w_j * z2_j, len)` once per matrix + -- outside `query_loop`, enforcing equal row lengths. + fn ro_fold_3pt(pz0: Lists::List, pz1: Lists::List, + pz2: Lists::List, col_ws: Lists::List) + -> (ProofDeserialize::Ext, ProofDeserialize::Ext, ProofDeserialize::Ext, Field) { + match (*(pz0)) { + Lists::Node::Nil => { + let Lists::Node::Nil = (*(pz1)); + let Lists::Node::Nil = (*(pz2)); + ([0, 0, 0], [0, 0, 0], [0, 0, 0], 0) } , + Lists::Node::Cons(z0, r0) => { + let &Lists::Node::Cons(z1, r1) = pz1; + let &Lists::Node::Cons(z2, r2) = pz2; + let &Lists::Node::Cons(w, wr) = col_ws; + let (s0, s1, s2, len) = ro_fold_3pt(r0, r1, r2, wr); + (eg3_add(eg3_mul(w, z0), s0), + eg3_add(eg3_mul(w, z1), s1), + eg3_add(eg3_mul(w, z2), s2), + len + 1) } , + } + } + + fn append_pin_rows(round: ProofDeserialize::OpenedRound, + pin_rows: Lists::List>) -> ProofDeserialize::OpenedRound { + match (*(round)) { + Lists::Node::Nil => { + let Lists::Node::Nil = (*(pin_rows)); + (&(Lists::Node::Nil)) } , + Lists::Node::Cons(mat, rrest) => { + let &Lists::Node::Cons(prow, prest) = pin_rows; + let &Lists::Node::Cons(p0, m1) = mat; + let &Lists::Node::Cons(p1, m2) = m1; + let Lists::Node::Nil = (*(m2)); + let mat3 = (&(Lists::Node::Cons(p0, (&(Lists::Node::Cons(p1, + (&(Lists::Node::Cons(prow, (&(Lists::Node::Nil))))))))))); + (&(Lists::Node::Cons(mat3, append_pin_rows(rrest, prest)))) } , + } + } + fn ext_row_onto(row: Lists::List, tail: Bytes::Stream) -> Bytes::Stream { match (*(row)) { Lists::Node::Nil => { tail } , @@ -416,7 +456,7 @@ module Pcs { match (*(hs)) { Lists::Node::Nil => { (&(Lists::Node::Nil)) } , Lists::Node::Cons(h, rest) => { - (&(Lists::Node::Cons(Bucket::Mk(h, open_ws, [0, 0, 0], [0, 0, 0]), build_init_buckets(rest, open_ws)))) } , + (&(Lists::Node::Cons(Bucket::Mk(h, open_ws, [0, 0, 0], [0, 0, 0], [0, 0, 0]), build_init_buckets(rest, open_ws)))) } , } } @@ -424,24 +464,41 @@ module Pcs { match (*(ood_buckets)) { Lists::Node::Nil => { (&(Lists::Node::Nil)) } , Lists::Node::Cons(b, rest) => { - let Bucket::Mk(h, _open_ws, ood0, ood1) = b; + let Bucket::Mk(h, _open_ws, ood0, ood1, ood2) = b; let zn = eg3_mul(zeta, [StarkVerifier::two_adic_gen(h - log_blowup), 0, 0]); let g_h = StarkVerifier::two_adic_gen(h); - (&(Lists::Node::Cons(HeightInfo::Mk(h, zn, g_h, ood0, ood1), build_height_infos(rest, log_blowup, zeta)))) } , + (&(Lists::Node::Cons(HeightInfo::Mk(h, zn, g_h, ood0, ood1, ood2), build_height_infos(rest, log_blowup, zeta)))) } , + } + } + + fn bucket_update_3pt(buckets: Lists::List, lh: Field, + s0: ProofDeserialize::Ext, s1: ProofDeserialize::Ext, s2: ProofDeserialize::Ext) -> Lists::List { + let &Lists::Node::Cons(b, rest) = buckets; + let Bucket::Mk(h, open_ws, ro0, ro1, ro2) = b; + match Fields::is_zero(h - lh) { + 1 => { + let &Lists::Node::Cons(w0, ow1) = open_ws; + let &Lists::Node::Cons(w1, ow2) = ow1; + let &Lists::Node::Cons(w2, ow3) = ow2; + let ro0_2 = eg3_add(ro0, eg3_mul(w0, s0)); + let ro1_2 = eg3_add(ro1, eg3_mul(w1, s1)); + let ro2_2 = eg3_add(ro2, eg3_mul(w2, s2)); + (&(Lists::Node::Cons(Bucket::Mk(h, ow3, ro0_2, ro1_2, ro2_2), rest))) } , + _ => { (&(Lists::Node::Cons(b, bucket_update_3pt(rest, lh, s0, s1, s2)))) } , } } fn bucket_update_2pt(buckets: Lists::List, lh: Field, s0: ProofDeserialize::Ext, s1: ProofDeserialize::Ext) -> Lists::List { let &Lists::Node::Cons(b, rest) = buckets; - let Bucket::Mk(h, open_ws, ro0, ro1) = b; + let Bucket::Mk(h, open_ws, ro0, ro1, ro2) = b; match Fields::is_zero(h - lh) { 1 => { let &Lists::Node::Cons(w0, ow1) = open_ws; let &Lists::Node::Cons(w1, ow2) = ow1; let ro0_2 = eg3_add(ro0, eg3_mul(w0, s0)); let ro1_2 = eg3_add(ro1, eg3_mul(w1, s1)); - (&(Lists::Node::Cons(Bucket::Mk(h, ow2, ro0_2, ro1_2), rest))) } , + (&(Lists::Node::Cons(Bucket::Mk(h, ow2, ro0_2, ro1_2, ro2), rest))) } , _ => { (&(Lists::Node::Cons(b, bucket_update_2pt(rest, lh, s0, s1)))) } , } } @@ -449,42 +506,45 @@ module Pcs { fn bucket_update_1pt(buckets: Lists::List, lh: Field, s0: ProofDeserialize::Ext) -> Lists::List { let &Lists::Node::Cons(b, rest) = buckets; - let Bucket::Mk(h, open_ws, ro0, ro1) = b; + let Bucket::Mk(h, open_ws, ro0, ro1, ro2) = b; match Fields::is_zero(h - lh) { 1 => { let &Lists::Node::Cons(w0, ow1) = open_ws; let ro0_2 = eg3_add(ro0, eg3_mul(w0, s0)); - (&(Lists::Node::Cons(Bucket::Mk(h, ow1, ro0_2, ro1), rest))) } , + (&(Lists::Node::Cons(Bucket::Mk(h, ow1, ro0_2, ro1, ro2), rest))) } , _ => { (&(Lists::Node::Cons(b, bucket_update_1pt(rest, lh, s0)))) } , } } fn finalize_buckets(buckets: Lists::List, infos: Lists::List, cur_bits: Lists::List, prev_h: Field, log_blowup: Field, - zeta: ProofDeserialize::Ext) -> Lists::List { + zeta: ProofDeserialize::Ext, z0: ProofDeserialize::Ext) -> Lists::List { match (*(buckets)) { Lists::Node::Nil => { let Lists::Node::Nil = (*(infos)); (&(Lists::Node::Nil)) } , Lists::Node::Cons(b, brest) => { let &Lists::Node::Cons(info, irest) = infos; - let Bucket::Mk(h, _open_ws, rx0, rx1) = b; - let HeightInfo::Mk(_hi_h, zn, g_h, ood0, ood1) = info; + let Bucket::Mk(h, _open_ws, rx0, rx1, rx2) = b; + let HeightInfo::Mk(_hi_h, zn, g_h, ood0, ood1, ood2) = info; let ro0 = eg3_sub(ood0, rx0); let ro1 = eg3_sub(ood1, rx1); + let ro2 = eg3_sub(ood2, rx2); let bits_h = Lists::drop(cur_bits, prev_h - h); let x = Goldilocks::gl_mul(7, exp_by_bits(g_h, glist_rev(bits_h, (&(Lists::Node::Nil))))); let d0 = eg3_sub(zeta, [x, 0, 0]); let d1 = eg3_sub(zn, [x, 0, 0]); + let d2 = eg3_sub(z0, [x, 0, 0]); let q0 = eg3_inv_nonzero(d0); let q1 = eg3_inv_nonzero(d1); - let ro = eg3_add(eg3_mul(q0, ro0), eg3_mul(q1, ro1)); + let q2 = eg3_inv_nonzero(d2); + let ro = eg3_add(eg3_add(eg3_mul(q0, ro0), eg3_mul(q1, ro1)), eg3_mul(q2, ro2)); let _z = match Fields::is_zero(h - log_blowup) { 1 => { assert_eq!(eg3_eq(ro, [0, 0, 0]), 1); 1 } , _ => { 1 } , }; (&(Lists::Node::Cons(RollBucket::Mk(h, ro), - finalize_buckets(brest, irest, bits_h, h, log_blowup, zeta)))) } , + finalize_buckets(brest, irest, bits_h, h, log_blowup, zeta, z0)))) } , } } @@ -497,7 +557,7 @@ module Pcs { fn open_prep(buckets: Lists::List, hs: Lists::List, opened: ProofDeserialize::OpenedRound, col_ws: Lists::List, - is_2pt: Field) -> (Lists::List, Lists::List) { + mode: Field) -> (Lists::List, Lists::List) { match (*(hs)) { Lists::Node::Nil => { let Lists::Node::Nil = (*(opened)); @@ -505,25 +565,45 @@ module Pcs { Lists::Node::Cons(lh, h_rest) => { let &Lists::Node::Cons(mat, op_rest) = opened; let &Lists::Node::Cons(pz0, mat1) = mat; - let pz1 = match is_2pt { + let (b, w) = match mode { 0 => { let Lists::Node::Nil = (*(mat1)); - pz0 } , - _ => { - let &Lists::Node::Cons(p1, mat2) = mat1; + let (ood0, _ood1, w) = ro_fold_2pt(pz0, pz0, col_ws); + (bucket_update_1pt(buckets, lh, ood0), w) } , + 1 => { + let &Lists::Node::Cons(pz1, mat2) = mat1; let Lists::Node::Nil = (*(mat2)); - p1 } , - }; - let (ood0, ood1, w) = ro_fold_2pt(pz0, pz1, col_ws); - let b = match is_2pt { - 0 => { bucket_update_1pt(buckets, lh, ood0) } , - _ => { bucket_update_2pt(buckets, lh, ood0, ood1) } , + let (ood0, ood1, w) = ro_fold_2pt(pz0, pz1, col_ws); + (bucket_update_2pt(buckets, lh, ood0, ood1), w) } , + _ => { + let &Lists::Node::Cons(pz1, mat2) = mat1; + let &Lists::Node::Cons(pz2, mat3) = mat2; + let Lists::Node::Nil = (*(mat3)); + let (ood0, ood1, ood2, w) = ro_fold_3pt(pz0, pz1, pz2, col_ws); + (bucket_update_3pt(buckets, lh, ood0, ood1, ood2), w) } , }; - let (b2, ws) = open_prep(b, h_rest, op_rest, col_ws, is_2pt); + let (b2, ws) = open_prep(b, h_rest, op_rest, col_ws, mode); (b2, (&(Lists::Node::Cons(w, ws)))) } , } } + fn open_batch_3pt(buckets: Lists::List, hs: Lists::List, + base_rows: Lists::List>, widths: Lists::List, + col_ws: Lists::List) -> Lists::List { + match (*(hs)) { + Lists::Node::Nil => { + let Lists::Node::Nil = (*(base_rows)); + let Lists::Node::Nil = (*(widths)); + buckets } , + Lists::Node::Cons(lh, h_rest) => { + let &Lists::Node::Cons(p_x, br_rest) = base_rows; + let &Lists::Node::Cons(w, w_rest) = widths; + let sx = ro_fold_1pt(p_x, col_ws, w); + let b = bucket_update_3pt(buckets, lh, sx, sx, sx); + open_batch_3pt(b, h_rest, br_rest, w_rest, col_ws) } , + } + } + fn open_batch_2pt(buckets: Lists::List, hs: Lists::List, base_rows: Lists::List>, widths: Lists::List, col_ws: Lists::List) -> Lists::List { @@ -652,13 +732,14 @@ module Pcs { init_buckets: Lists::List, height_infos: Lists::List, col_ws: Lists::List, hall: Lists::List, ph: Lists::List, widths_s1: Lists::List, widths_s2: Lists::List, widths_q: Lists::List, - widths_p: Lists::List, zeta: ProofDeserialize::Ext, log_blowup: Field, log_gmax: Field, + widths_p: Lists::List, zeta: ProofDeserialize::Ext, z0: ProofDeserialize::Ext, + log_blowup: Field, log_gmax: Field, betas: Lists::List, final_eval: ProofDeserialize::Ext) -> Lists::List> { - let buckets = open_batch_2pt(init_buckets, hall, rows_s1, widths_s1, col_ws); + let buckets = open_batch_3pt(init_buckets, hall, rows_s1, widths_s1, col_ws); let buckets = open_batch_2pt(buckets, hall, rows_s2, widths_s2, col_ws); let buckets = open_quotient(buckets, hall, rows_q, widths_q, col_ws); - let buckets = open_batch_2pt(buckets, ph, rows_p, widths_p, col_ws); - let roll_buckets = finalize_buckets(buckets, height_infos, idxbits, log_gmax, log_blowup, zeta); + let buckets = open_batch_3pt(buckets, ph, rows_p, widths_p, col_ws); + let roll_buckets = finalize_buckets(buckets, height_infos, idxbits, log_gmax, log_blowup, zeta, z0); let &Lists::Node::Cons(b0, ro_rest) = roll_buckets; let RollBucket::Mk(h0, folded_start) = b0; @@ -700,7 +781,7 @@ module Pcs { col_ws: Lists::List, hall: Lists::List, ph: Lists::List, widths_s1: Lists::List, widths_s2: Lists::List, widths_q: Lists::List, widths_p: Lists::List, has_prep: Field, - zeta: ProofDeserialize::Ext, log_blowup: Field, log_gmax: Field, + zeta: ProofDeserialize::Ext, z0: ProofDeserialize::Ext, log_blowup: Field, log_gmax: Field, betas: Lists::List, final_eval: ProofDeserialize::Ext) -> Lists::List>> { match (*(indices)) { @@ -723,10 +804,10 @@ module Pcs { let (q_sibs, next_step_sibs) = peel_step_sibs(step_sibs); let qrows_out = verify_one_query(idxbits, rows_s1, rows_s2, rows_q, rows_p, q_sibs, init_buckets, height_infos, col_ws, hall, ph, widths_s1, widths_s2, widths_q, widths_p, - zeta, log_blowup, log_gmax, betas, final_eval); + zeta, z0, log_blowup, log_gmax, betas, final_eval); (&(Lists::Node::Cons(qrows_out, query_loop(irest, s1rest, s2rest, qrest, prest, next_step_sibs, init_buckets, height_infos, col_ws, hall, ph, widths_s1, widths_s2, widths_q, widths_p, - has_prep, zeta, log_blowup, log_gmax, betas, final_eval)))) } , + has_prep, zeta, z0, log_blowup, log_gmax, betas, final_eval)))) } , } } @@ -784,7 +865,9 @@ module Pcs { q_opened: ProofDeserialize::OpenedRound, prep_opt: ProofDeserialize::PreprocessedOpt, opening: ProofDeserialize::FriProof, s1c: ProofDeserialize::MerkleCap, s2c: ProofDeserialize::MerkleCap, qc: ProofDeserialize::MerkleCap, prep_commit: ProofDeserialize::MerkleCap, prep_indices: Lists::List, log_degrees: Lists::List, - zeta: ProofDeserialize::Ext, num_circuits: Field, log_blowup: Field, num_queries: Field, commit_pow_bits: Field, + zeta: ProofDeserialize::Ext, z0: ProofDeserialize::Ext, + main_pins: Lists::List>, fixed_pins: Lists::List>, + num_circuits: Field, log_blowup: Field, num_queries: Field, commit_pow_bits: Field, query_pow_bits: Field) -> Field { let ProofDeserialize::FriProof::Mk(commit_phase_commits, pw, input_openings, commit_phase_openings, final_poly, qpw) = opening; @@ -797,22 +880,31 @@ module Pcs { let &Lists::Node::Cons(final_eval, fp_nil) = final_poly; let Lists::Node::Nil = (*(fp_nil)); - let obs = round_onto(stage1, round_onto(stage2, round_onto(q_opened, - prep_onto(prep_opt, (&(Lists::Node::Nil)))))); + let stage1_pinned = append_pin_rows(stage1, main_pins); + let prep_opt_pinned = match prep_opt { + ProofDeserialize::PreprocessedOpt::NoPreprocessed => { + let Lists::Node::Nil = (*(fixed_pins)); + ProofDeserialize::PreprocessedOpt::NoPreprocessed } , + ProofDeserialize::PreprocessedOpt::SomePreprocessed(pr) => { + ProofDeserialize::PreprocessedOpt::SomePreprocessed(append_pin_rows(pr, fixed_pins)) } , + }; + + let obs = round_onto(stage1_pinned, round_onto(stage2, round_onto(q_opened, + prep_onto(prep_opt_pinned, (&(Lists::Node::Nil)))))); let input = Lists::concat(post_zeta_input, obs); -- FriBatching::Tensor: derive max_width and max_openings_per_height from the -- authenticated opening structure, then sample col_challenges and open_challenges -- consecutively while threading challenger output buffer state across all calls. let distinct_hs = collect_heights_desc(log_degrees, log_blowup, (&(Lists::Node::Nil))); - let max_w = round_max_width(stage1, 0); + let max_w = round_max_width(stage1_pinned, 0); let max_w = round_max_width(stage2, max_w); let max_w = round_max_width(q_opened, max_w); - let max_w = match prep_opt { + let max_w = match prep_opt_pinned { ProofDeserialize::PreprocessedOpt::NoPreprocessed => { max_w } , ProofDeserialize::PreprocessedOpt::SomePreprocessed(pr) => { round_max_width(pr, max_w) } , }; - let max_open = max_openings_across_heights(distinct_hs, log_blowup, log_degrees, prep_opt, prep_indices, 0); + let max_open = max_openings_across_heights(distinct_hs, log_blowup, log_degrees, prep_opt_pinned, prep_indices, 0); let k_col = tensor_num_challenges(max_w); let k_open = tensor_num_challenges(max_open); let (col_chals, input, output) = sample_ext_n(input, (&(Lists::Node::Nil)), k_col); @@ -842,10 +934,10 @@ module Pcs { assert_eq!(Mmcs::mmcs_verify_multi(s2c, s2rows, hall, distinct_hs, indices, s2proof, log_gmax), 1); assert_eq!(Mmcs::mmcs_verify_multi(qc, qrows, hall, distinct_hs, indices, qproof, log_gmax), 1); let init_buckets = build_init_buckets(distinct_hs, open_weights); - let (ood_b1, widths_s1) = open_prep(init_buckets, hall, stage1, col_weights, 1); + let (ood_b1, widths_s1) = open_prep(init_buckets, hall, stage1_pinned, col_weights, 2); let (ood_b2, widths_s2) = open_prep(ood_b1, hall, stage2, col_weights, 1); let (ood_b3, widths_q) = open_prep(ood_b2, hall, q_opened, col_weights, 0); - let (prows, ph, widths_p, ood_buckets) = match prep_opt { + let (prows, ph, widths_p, ood_buckets) = match prep_opt_pinned { ProofDeserialize::PreprocessedOpt::NoPreprocessed => { let Lists::Node::Nil = (*(io3)); ((&(Lists::Node::Nil)), (&(Lists::Node::Nil)), (&(Lists::Node::Nil)), ood_b3) } , @@ -857,14 +949,14 @@ module Pcs { let lp = heights_max(distinct_ph); let pindices = drop_index_bits(indices, log_gmax - lp); assert_eq!(Mmcs::mmcs_verify_multi(prep_commit, pr, ph, distinct_ph, pindices, pproof, lp), 1); - let (ood_b4, wp) = open_prep(ood_b3, ph, prep_round, col_weights, 1); + let (ood_b4, wp) = open_prep(ood_b3, ph, prep_round, col_weights, 2); (pr, ph, wp, ood_b4) } , }; let height_infos = build_height_infos(ood_buckets, log_blowup, zeta); let step_sibs = extract_step_sibs(commit_phase_openings); let fri_rows = query_loop(indices, s1rows, s2rows, qrows, prows, step_sibs, init_buckets, height_infos, col_weights, hall, ph, widths_s1, widths_s2, widths_q, widths_p, - has_prep, zeta, log_blowup, log_gmax, betas, final_eval); + has_prep, zeta, z0, log_blowup, log_gmax, betas, final_eval); verify_commit_multi(commit_phase_openings, commit_phase_commits, fri_rows, indices, log_gmax) } } diff --git a/MultiStark/MultiStark/Modules/ProofDeserialize.lean b/MultiStark/MultiStark/Modules/ProofDeserialize.lean index a83971c1fc..5fa44fb017 100644 --- a/MultiStark/MultiStark/Modules/ProofDeserialize.lean +++ b/MultiStark/MultiStark/Modules/ProofDeserialize.lean @@ -72,7 +72,7 @@ module ProofDeserialize { } enum Batch { - Mk(Lists::List, Lists::List, Lists::List) + Mk(Lists::List, Lists::List, Lists::List, OpenedRound) } fn read_u8(stream: Bytes::Stream) -> (UInt8::U8, Bytes::Stream) { @@ -470,7 +470,8 @@ module ProofDeserialize { let (headers, j0) = read_header_vec(i); let (messages, j1) = read_message_vec(j0); let (proofs, j2) = read_proof_vec(j1); - (Batch::Mk(headers, messages, proofs), j2) + let (pinned, j3) = read_opened_round(j2); + (Batch::Mk(headers, messages, proofs, pinned), j3) } } ⟧ diff --git a/MultiStark/MultiStark/Modules/StarkVerifier.lean b/MultiStark/MultiStark/Modules/StarkVerifier.lean index d6ad96385d..ecb71d4afb 100644 --- a/MultiStark/MultiStark/Modules/StarkVerifier.lean +++ b/MultiStark/MultiStark/Modules/StarkVerifier.lean @@ -948,8 +948,111 @@ module StarkVerifier { } } + fn assert_pinning_point_ok_loop(z0: ProofDeserialize::Ext, unshifted: ProofDeserialize::Ext, + log_degrees: Lists::List, log_blowup: Field) -> Field { + match (*(log_degrees)) { + Lists::Node::Nil => { 1 } , + Lists::Node::Cons(ld, rest) => { + let k = UInt8::to_field(ld); + assert_eq!(Pcs::eg3_eq(ext_exp_pow2(z0, k), [1, 0, 0]), 0); + assert_eq!(Pcs::eg3_eq(ext_exp_pow2(unshifted, k + log_blowup), [1, 0, 0]), 0); + assert_pinning_point_ok_loop(z0, unshifted, rest, log_blowup) } , + } + } + + inline fn assert_pinning_point_ok(z0: ProofDeserialize::Ext, + log_degrees: Lists::List, log_blowup: Field) -> Field { + assert_eq!(ext_is_zero(z0), 0); + let inv7 = Goldilocks::gl_inv_nonzero(7); + let unshifted = Pcs::eg3_mul(z0, [inv7, 0, 0]); + assert_pinning_point_ok_loop(z0, unshifted, log_degrees, log_blowup) + } + + fn split_ext_n(row: Lists::List, n: Field) + -> (Lists::List, Lists::List) { + match n { + 0 => { ((&(Lists::Node::Nil)), row) } , + _ => { + let &Lists::Node::Cons(x, rest) = row; + let (pre, suf) = split_ext_n(rest, n - 1); + ((&(Lists::Node::Cons(x, pre))), suf) } , + } + } + + fn split_shard_pins(acirc: Lists::List, + aprep: Lists::List, + shard_pins: Lists::List>) + -> (Lists::List>, Lists::List>) { + match (*(acirc)) { + Lists::Node::Nil => { + let Lists::Node::Nil = (*(aprep)); + let Lists::Node::Nil = (*(shard_pins)); + ((&(Lists::Node::Nil)), (&(Lists::Node::Nil))) } , + Lists::Node::Cons(circ, crest) => { + let &Lists::Node::Cons(pi, prest) = aprep; + let &Lists::Node::Cons(prow, srest) = shard_pins; + let SystemDeserialize::SysCircuit::Mk(_nodes, _nc, _zeros, _md, _lks, _k, mw, pw, _ph, _s2w) = circ; + let (fixed_rest, main_rest) = split_shard_pins(crest, prest, srest); + match pi { + SystemDeserialize::OptIdx::NoIdx => { + assert_eq!(Lists::length(prow), mw); + (fixed_rest, (&(Lists::Node::Cons(prow, main_rest)))) } , + SystemDeserialize::OptIdx::SomeIdx(_idx) => { + let (fp, mp) = split_ext_n(prow, pw); + assert_eq!(Lists::length(mp), mw); + ((&(Lists::Node::Cons(fp, fixed_rest))), (&(Lists::Node::Cons(mp, main_rest)))) } , + } } , + } + } + + fn assert_shard_pins_shape(circuits: Lists::List, + prep_indices: Lists::List, + active: Lists::List, + shard_pins: Lists::List>) -> Field { + match (*(circuits)) { + Lists::Node::Nil => { + let Lists::Node::Nil = (*(prep_indices)); + let Lists::Node::Nil = (*(active)); + let Lists::Node::Nil = (*(shard_pins)); + 1 } , + Lists::Node::Cons(circ, crest) => { + let &Lists::Node::Cons(pi, prest) = prep_indices; + let &Lists::Node::Cons(b, arest) = active; + assert_eq!(b * (b - 1), 0); + match b { + 0 => { assert_shard_pins_shape(crest, prest, arest, shard_pins) } , + _ => { + let &Lists::Node::Cons(prow, srest) = shard_pins; + let SystemDeserialize::SysCircuit::Mk(_nodes, _nc, _zeros, _md, _lks, _k, mw, pw, _ph, _s2w) = circ; + let fw = match pi { + SystemDeserialize::OptIdx::NoIdx => { 0 } , + SystemDeserialize::OptIdx::SomeIdx(_idx) => { pw } , + }; + assert_eq!(Lists::length(prow), fw + mw); + assert_shard_pins_shape(crest, prest, arest, srest) } , + } } , + } + } + + fn assert_batch_pins_shape(circuits: Lists::List, + prep_indices: Lists::List, + headers: Lists::List, + pinned: ProofDeserialize::OpenedRound) -> Field { + match (*(headers)) { + Lists::Node::Nil => { + let Lists::Node::Nil = (*(pinned)); + 1 } , + Lists::Node::Cons(h, hrest) => { + let &Lists::Node::Cons(sp, prest) = pinned; + let ProofDeserialize::ShardHeader::Mk(active, _cap, _lds, _claims) = h; + assert_eq!(assert_shard_pins_shape(circuits, prep_indices, active, sp), 1); + assert_batch_pins_shape(circuits, prep_indices, hrest, prest) } , + } + } + fn verify_shard(sys: SystemDeserialize::Sys, header: ProofDeserialize::ShardHeader, shard: Field, proof: ProofDeserialize::Proof, - input: Bytes::Stream, lch: ProofDeserialize::Ext, fch: ProofDeserialize::Ext) -> ProofDeserialize::Ext { + input: Bytes::Stream, z0: ProofDeserialize::Ext, lch: ProofDeserialize::Ext, fch: ProofDeserialize::Ext, + shard_pins: Lists::List>) -> ProofDeserialize::Ext { let SystemDeserialize::Sys::Mk(params, _tlimbs, circuits, commit, prep_indices) = sys; let SystemDeserialize::SysParams::Mk(log_blowup, cap_height, log_final_poly_len, max_log_arity, num_queries, commit_pow_bits, @@ -1014,6 +1117,8 @@ module StarkVerifier { assert_eq!(assert_same_u8s(h_lds, log_degrees), 1); assert_eq!(assert_log_degrees_ok(log_degrees), 1); assert_eq!(count_ones(active), Lists::length(log_degrees)); + assert_eq!(assert_pinning_point_ok(z0, log_degrees, log_blowup), 1); + let (fixed_pins, main_pins) = split_shard_pins(acirc, aprep, shard_pins); let prep_cap = opt_commit_cap(commit); let _prep_match = match commit { SystemDeserialize::OptCommit::NoCommit => { @@ -1029,22 +1134,25 @@ module StarkVerifier { let _ood = ood_loop(acirc, aprep, log_degrees, accs, stage1, stage2, prep_opt, q_opened, acc0, lch, fch, alpha, zeta); assert_eq!(Pcs::pcs_fri_verify(post_zeta_input, stage1, stage2, q_opened, prep_opt, opening, - s1c, s2c, qc, prep_cap, aprep, log_degrees, zeta, + s1c, s2c, qc, prep_cap, aprep, log_degrees, zeta, z0, main_pins, fixed_pins, num_circuits, log_blowup, num_queries, commit_pow_bits, query_pow_bits), 1); last_acc(accs) } - fn verify_shards(sys: SystemDeserialize::Sys, headers: Lists::List, proofs: Lists::List, shard: Field, - input: Bytes::Stream, lch: ProofDeserialize::Ext, fch: ProofDeserialize::Ext, acc: ProofDeserialize::Ext) -> ProofDeserialize::Ext { + fn verify_shards(sys: SystemDeserialize::Sys, headers: Lists::List, proofs: Lists::List, + pinned: ProofDeserialize::OpenedRound, shard: Field, + input: Bytes::Stream, z0: ProofDeserialize::Ext, lch: ProofDeserialize::Ext, fch: ProofDeserialize::Ext, acc: ProofDeserialize::Ext) -> ProofDeserialize::Ext { match (*(headers)) { Lists::Node::Nil => { let Lists::Node::Nil = (*(proofs)); + let Lists::Node::Nil = (*(pinned)); acc } , Lists::Node::Cons(h, hrest) => { let Lists::Node::Cons(p, prest) = (*(proofs)); - let r = verify_shard(sys, h, shard, p, input, lch, fch); - verify_shards(sys, hrest, prest, shard + 1, input, lch, fch, Pcs::eg3_add(acc, r)) } , + let Lists::Node::Cons(sp, sprest) = (*(pinned)); + let r = verify_shard(sys, h, shard, p, input, z0, lch, fch, sp); + verify_shards(sys, hrest, prest, sprest, shard + 1, input, z0, lch, fch, Pcs::eg3_add(acc, r)) } , } } @@ -1058,17 +1166,18 @@ module StarkVerifier { } fn verify_batch(sys: SystemDeserialize::Sys, batch: ProofDeserialize::Batch) -> Lists::List> { - let ProofDeserialize::Batch::Mk(headers, messages, proofs) = batch; + let ProofDeserialize::Batch::Mk(headers, messages, proofs, pinned) = batch; assert_eq!(assert_shard_count_ok(Lists::length(headers)), 1); assert_eq!(assert_batch_bounds(sys, headers), 1); assert_eq!(Lists::length(proofs), Lists::length(headers)); assert_eq!(assert_closure_pairs(messages, 0, 0), 1); - let SystemDeserialize::Sys::Mk(_params, tlimbs, circuits, commit, _prep_indices) = sys; + let SystemDeserialize::Sys::Mk(_params, tlimbs, circuits, commit, prep_indices) = sys; assert_eq!(assert_closure_widths_ok(circuits, headers, messages), 1); + assert_eq!(assert_batch_pins_shape(circuits, prep_indices, headers, pinned), 1); let prep_cap = opt_commit_cap(commit); - let (lch, fch, input) = Transcript::batch_fiat_shamir(tlimbs, prep_cap, headers, messages); + let (z0, lch, fch, input) = Transcript::batch_fiat_shamir(tlimbs, prep_cap, headers, messages, pinned); let acc = messages_acc([0, 0, 0], messages, lch, fch); - let total = verify_shards(sys, headers, proofs, 0, input, lch, fch, acc); + let total = verify_shards(sys, headers, proofs, pinned, 0, input, z0, lch, fch, acc); assert_eq!(ext_is_zero(total), 1); batch_claims(headers) } diff --git a/MultiStark/MultiStark/Modules/SystemDeserialize.lean b/MultiStark/MultiStark/Modules/SystemDeserialize.lean index da35c4f74d..54ae85464a 100644 --- a/MultiStark/MultiStark/Modules/SystemDeserialize.lean +++ b/MultiStark/MultiStark/Modules/SystemDeserialize.lean @@ -321,11 +321,13 @@ module SystemDeserialize { let (p4, l4, j4) = read_vk_u16_limb(j3); let (p5, l5, j5) = read_vk_u16_limb(j4); let (p6, l6, j6) = read_vk_u16_limb(j5); + let (p7, l7, j7) = read_vk_u16_limb(j6); + assert_eq!(p7, 1, "vk: stage-1 pinning is required"); (SysParams::Mk(p0, p1, p2, p3, p4, p5, p6), (&(Lists::Node::Cons(l0, (&(Lists::Node::Cons(l1, (&(Lists::Node::Cons(l2, (&(Lists::Node::Cons(l3, (&(Lists::Node::Cons(l4, (&(Lists::Node::Cons(l5, - (&(Lists::Node::Cons(l6, (&(Lists::Node::Nil))))))))))))))))))))))), - j6) + (&(Lists::Node::Cons(l6, (&(Lists::Node::Cons(l7, (&(Lists::Node::Nil)))))))))))))))))))))))))), + j7) } inline fn read_system(i: Bytes::Stream) -> (Sys, Bytes::Stream) { diff --git a/MultiStark/MultiStark/Modules/Transcript.lean b/MultiStark/MultiStark/Modules/Transcript.lean index 49b0496bc5..b0ada086bb 100644 --- a/MultiStark/MultiStark/Modules/Transcript.lean +++ b/MultiStark/MultiStark/Modules/Transcript.lean @@ -66,18 +66,22 @@ module Transcript { } fn batch_fiat_shamir(tlimbs: Lists::List, prep: ProofDeserialize::MerkleCap, headers: Lists::List, - messages: Lists::List) -> (ProofDeserialize::Ext, ProofDeserialize::Ext, Bytes::Stream) { + messages: Lists::List, pinned: ProofDeserialize::OpenedRound) + -> (ProofDeserialize::Ext, ProofDeserialize::Ext, ProofDeserialize::Ext, Bytes::Stream) { let input = StarkVerifier::messages_onto(messages, (&(Lists::Node::Nil))); let input = StarkVerifier::headers_onto(headers, input); let input = StarkVerifier::count_onto(Lists::length(headers), input); let input = StarkVerifier::cap_onto(prep, input); let input = StarkVerifier::limbs_onto(tlimbs, input); let input = StarkVerifier::seed_tag_onto(input); + let (z0_0, z0_1, z0_2, input, _oz0) = ch_sample_ext(input, (&(Lists::Node::Nil))); + let input = Lists::concat(input, Pcs::round_onto(pinned, (&(Lists::Node::Nil)))); let (l0, l1, l2, input, _ol) = ch_sample_ext(input, (&(Lists::Node::Nil))); let input = Lists::concat(input, StarkVerifier::b8_onto(l0, StarkVerifier::b8_onto(l1, StarkVerifier::b8_onto(l2, (&(Lists::Node::Nil)))))); let (f0, f1, f2, input, _of) = ch_sample_ext(input, (&(Lists::Node::Nil))); let input = Lists::concat(input, StarkVerifier::b8_onto(f0, StarkVerifier::b8_onto(f1, StarkVerifier::b8_onto(f2, (&(Lists::Node::Nil)))))); - ([Goldilocks::gl_val(l0), Goldilocks::gl_val(l1), Goldilocks::gl_val(l2)], + ([Goldilocks::gl_val(z0_0), Goldilocks::gl_val(z0_1), Goldilocks::gl_val(z0_2)], + [Goldilocks::gl_val(l0), Goldilocks::gl_val(l1), Goldilocks::gl_val(l2)], [Goldilocks::gl_val(f0), Goldilocks::gl_val(f1), Goldilocks::gl_val(f2)], input) } diff --git a/MultiStark/MultiStark/StarkShrink.lean b/MultiStark/MultiStark/StarkShrink.lean index 80ceaa8aa7..40e3f56ff4 100644 --- a/MultiStark/MultiStark/StarkShrink.lean +++ b/MultiStark/MultiStark/StarkShrink.lean @@ -45,8 +45,10 @@ def starkShrinkFunctionGroups : List (String × List String) := [ "Pcs::select_rows_le", "Pcs::ro_fold_1pt", "Pcs::ro_fold_2pt", + "Pcs::ro_fold_3pt", "Pcs::bucket_update_1pt", "Pcs::bucket_update_2pt", + "Pcs::bucket_update_3pt", "ProofDeserialize::read_u64_vec_n", "SystemDeserialize::read_vk_u8", "SystemDeserialize::read_vk_u16", @@ -113,8 +115,10 @@ def starkShrinkFunctionGroups : List (String × List String) := [ -- Group 3: FRI query loop, tensor batching weights, and PCS opening verification. ("shrink_pcs_fri", [ "Pcs::open_batch_2pt", + "Pcs::open_batch_3pt", "Pcs::open_quotient", "Pcs::open_prep", + "Pcs::append_pin_rows", "Pcs::fri_fold2", "Pcs::eg3_inv_nonzero", "Pcs::exp_by_bits", @@ -174,6 +178,11 @@ def starkShrinkFunctionGroups : List (String × List String) := [ "StarkVerifier::messages_acc", "StarkVerifier::last_acc", "StarkVerifier::ext_exp_pow2", + "StarkVerifier::assert_pinning_point_ok_loop", + "StarkVerifier::split_ext_n", + "StarkVerifier::split_shard_pins", + "StarkVerifier::assert_shard_pins_shape", + "StarkVerifier::assert_batch_pins_shape", "StarkVerifier::two_adic_gen", "StarkVerifier::pow2", "Transcript::ch_sample8", diff --git a/Scripts/FriSecurity.lean b/Scripts/FriSecurity.lean index f933df2fdf..89c85a9a20 100644 --- a/Scripts/FriSecurity.lean +++ b/Scripts/FriSecurity.lean @@ -8,7 +8,9 @@ open Aiur.FriSecurity def usage : String := "usage: fri-security [STATISTICS | -] [--instance LOG_TRACE,COLUMNS,CONSTRAINTS,MAX_DEGREE,LOOKUP_ROWS,LOOKUP_WIDTH] [--log-blowup N] [--queries N] [--query-pow N] [--commit-pow N] [--log-arity N] - [--extension-degree N] [--digest-bytes N] [--protocol-version N] [--batching tensor|powers] + [--extension-degree N] [--digest-bytes N] [--hash-state-bits N] [--protocol-version N] + [--batching tensor|powers] [--stage1-pinning] + [--pq] [--qrom-c1 N] [--qrom-c2 N] [--max-depth-bits N] [--pq-self-test] [--parameters LOG_BLOWUP,QUERIES,COMMIT_POW,QUERY_POW]... [--drop I,J,...] [--set I:LOG_HEIGHT:MAIN,...] [--require-min-bits N] [--regime proven|proven-johnson|johnson|conjectured] [--table] @@ -18,6 +20,7 @@ or `fri_sizing --statistics outer-vk.bin` (the compression stage's FRI key), or Each --parameters set gets its own report; the other options override the key's parameters, which default to Aiur's when only --instance is given. --batching overrides FRI batching (default: tensor for v6 Fp^3, powers for legacy v5). +--pq switches output to Post-Quantum QROM-Q1 (unbounded-depth) and Model-Q2 (CNS+MAXDEPTH) bounds. --require-min-bits N exits non-zero if any evaluated parameter set falls below N bits in the selected --regime (default: proven). --table prints one line per parameter set with each regime's weakest term." @@ -34,12 +37,18 @@ structure Options where drop : List Nat := [] shapes : List (Nat × Nat × Nat) := [] table : Bool := false + pq : Bool := false + pqSelfTest : Bool := false requireMinBits : Option Nat := none regime : RegimeKind := .proven def parse : List String → Options → Except String Options | [], o => .ok o | "--table" :: rest, o => parse rest { o with table := true } + | "--pq" :: rest, o => parse rest { o with pq := true } + | "--pq-self-test" :: rest, o => parse rest { o with pqSelfTest := true } + | "--stage1-pinning" :: rest, o => + parse rest { o with overrides := o.overrides ++ [({ · with stage1Pinning := true })] } | flag :: value :: rest, o => do let one : Except String Nat := value.toNat?.elim (.error s!"{flag}: not a number") .ok match flag with @@ -52,6 +61,14 @@ def parse : List String → Options → Except String Options let v ← one; parse rest { o with overrides := o.overrides ++ [({ · with extensionDegree := v })] } | "--digest-bytes" => let v ← one; parse rest { o with overrides := o.overrides ++ [({ · with digestBytes := v })] } + | "--hash-state-bits" => + let v ← one; parse rest { o with overrides := o.overrides ++ [({ · with hashStateBits := some v })] } + | "--qrom-c1" => + let v ← one; parse rest { o with overrides := o.overrides ++ [({ · with qromC1 := Float.ofNat v })] } + | "--qrom-c2" => + let v ← one; parse rest { o with overrides := o.overrides ++ [({ · with qromC2 := Float.ofNat v })] } + | "--max-depth-bits" => + let v ← one; parse rest { o with overrides := o.overrides ++ [({ · with maxDepthBits := v })] } | "--protocol-version" => let v ← one; parse rest { o with overrides := o.overrides ++ [({ · with protocolVersion := v })] } | "--batching" => @@ -94,8 +111,9 @@ def readKey (path : String) : IO Key := do let text ← if path == "-" then (← IO.getStdin).readToEnd else IO.FS.readFile path IO.ofExcept <| Lean.Json.parse text >>= Key.fromJson? -def tableRow (inst : Instance) (p : Parameters) : String := - let cells := (terms inst p).map fun r => +def tableRow (inst : Instance) (p : Parameters) (pq : Bool := false) : String := + let rs := if pq then pqTerms inst p else terms inst p + let cells := rs.map fun r => let (name, bits) := r.limit s!"{fmt bits} ({name})" s!"| {p.logBlowup} | {p.queries} | {p.commitPow} | {p.queryPow} | {p.conjecturedBits} | " ++ @@ -112,6 +130,10 @@ def main (args : List String) : IO UInt32 := do match parse args {} with | .error e => IO.eprintln s!"{e}\n{usage}"; return 2 | .ok o => + if o.pqSelfTest then + match pqSelfTest with + | .ok msg => IO.println msg; return 0 + | .error err => IO.eprintln s!"pqSelfTest FAIL: {err}"; return 1 let key : Key ← match o.statistics, o.inst with | some path, none => readKey path | none, some _ => pure { parameters := Parameters.default, circuits := #[] } @@ -125,18 +147,19 @@ def main (args : List String) : IO UInt32 := do IO.println s!"instance: trace 2^{inst.logTrace}, {inst.columns} batched columns, \ {inst.constraints} constraints, max degree {inst.maxDegree}, lookup rows \ {inst.lookupRows}, lookup width {inst.lookupWidth}" - let names := (terms inst base).map fun r => + let rs := if o.pq then pqTerms inst base else terms inst base + let names := rs.map fun r => let s := (r.name.splitOn ", m=").headD r.name (s.splitOn " (θ=").headD s IO.println s!"| log_blowup | queries | commit pow | query pow | conjectured | \ {" | ".intercalate names.toList} |" - for p in sets do IO.println (tableRow inst p) + for p in sets do IO.println (tableRow inst p o.pq) else let source := if o.inst.isSome then "given instance" else s!"{key.circuits.size} circuits ({circuits.size} after overrides)" ++ (key.shards.map (s!", {·} shards")).getD "" ++ (key.proofBytes.map (s!", {·} proof bytes")).getD "" - for p in sets do IO.println (report source inst p) + for p in sets do IO.println (if o.pq then pqReport source inst p else report source inst p) if let some minBits := o.requireMinBits then let mut failed := false for p in sets do diff --git a/Scripts/GenPaperFixtures.lean b/Scripts/GenPaperFixtures.lean index a9b584f368..be78864479 100644 --- a/Scripts/GenPaperFixtures.lean +++ b/Scripts/GenPaperFixtures.lean @@ -187,11 +187,11 @@ def run : IO Unit := do ensure (bindingBytes.size == 68) s!"expected Binding claim size 68 B, got {bindingBytes.size}" ensure ((← IO.ofExcept (Ix.Claim.de bindingBytes)) == bindingClaim) "Binding claim round-trip failed" - -- 7. ElabClaim (`0xE8 0x0B`, 68 B) + BoundedStatementElab (`propId` & `AnthropicFLT`) + -- 7. Unified ElabClaim (`0xE8 0x0B | 04 03`, 70 B minimal) + BoundedStatementElab (`propId` & `AnthropicFLT`) let (_, propElabClaim) ← IO.ofExcept (Ixon.BoundedStatementElab.elabPropIdStatement Ixon.BoundedStatementElab.propIdSource (some decProd)) let propElabBytes := Ixon.ElabClaim.ser propElabClaim - ensure (propElabBytes.size == 68) s!"expected ElabClaim size 68 B, got {propElabBytes.size}" + ensure (propElabBytes.size == 70) s!"expected ElabClaim size 70 B, got {propElabBytes.size}" ensure ((← IO.ofExcept (Ixon.ElabClaim.de propElabBytes)) == propElabClaim) "ElabClaim round-trip failed" ensure ((Ix.Claim.de propElabBytes).isOk == false) "Ix.Claim.de must reject ElabClaim" -- Verify alpha-renaming invariance of bounded elaborator @@ -205,13 +205,13 @@ def run : IO Unit := do (Ixon.BoundedStatementElab.mkFltElabClaim Ixon.BoundedStatementElab.fltStatementSource fltTargetPlaceholder) let fltElabBytes := Ixon.ElabClaim.ser fltElabClaim - ensure (fltElabBytes.size == 68) s!"expected FLT ElabClaim size 68 B, got {fltElabBytes.size}" + ensure (fltElabBytes.size == 70) s!"expected FLT ElabClaim size 70 B, got {fltElabBytes.size}" ensure ((← IO.ofExcept (Ixon.ElabClaim.de fltElabBytes)) == fltElabClaim) "FLT ElabClaim round-trip failed" -- 8. DynamicLinkStatement (`0xE8 0x0D`) & LinkedCircuitEntry (`0xE8 0x0F`) round-trip let sampleVk := Address.blake3Pure "ix-paper-eval-abi-vk".toUTF8 let sampleCert := Address.blake3Pure "ix-paper-eval-abi-cert".toUTF8 - let dlStmt := propElabClaim.toDynamicLinkStatement + let dlStmt := propElabClaim.toPairDynamicLinkStatement { vkDigest := sampleVk, entryIdx := 0 } (some { spec := specDig binding := sampleBinding diff --git a/Scripts/VerifyMultiStark.lean b/Scripts/VerifyMultiStark.lean index 10049bc25c..0b471050df 100644 --- a/Scripts/VerifyMultiStark.lean +++ b/Scripts/VerifyMultiStark.lean @@ -1,33 +1,27 @@ -import Ix.Cert.MultiStark.Verifier +import Ix.Cert.MultiStark.PinnedVerifier -/-! # Standalone Mathlib-Free Native Lean Inner Aiur Protocol `v6` Verifier (`Scripts.VerifyMultiStark`) +/-! # Standalone Mathlib-Free Native Lean Protocol `v6` Pinned Verifier (`Scripts.VerifyMultiStark`) -Pure Lean 4 executable verifier for **inner Aiur Protocol `v6` batch proofs** -(`Fp^3 = Fp[X] / (X^3 - X - 1)`, `FriBatching::Tensor`, BLAKE3 `derive_key` domain separation, -`logFinalPolyLen = 0`, `maxLogArity = 1`). On its default production CLI path it calls -`Ix.Cert.MultiStark.verifyBatchBytesTensorCapped` directly; when the explicit test-harness -waivers `--allow-below-floor` or `--allow-inactive-prep` are passed, it routes through -`verifyBatchWithFloor` while still enforcing `shardTensorChallengeCapOk` (`kCol + kOpen ≤ 32`). +Pure Lean 4 executable verifier for **Release 0.5 pinned Protocol `v6` batch proofs** +(`Goldilocks^3`, 32-byte `BLAKE3-256`, `FriBatching::Tensor`, `stage_1_pinning = 1`), wired +directly to `CertiFri.Stark.Profile.verifyBytesPinned` (`CertiFriP3/VerifyBytes.lean`) plus Ix's +`validate_preamble` policy on `CertiFri.P3.Wire.pinnedBatchMessagesOf`. -Imports **zero** Mathlib and calls **zero** Rust FFI (pure Lean BLAKE3 + Goldilocks + -`CertiFri` verifier). In `Ix.Cert.MultiStark.VerifierRefinement`, `verifyBatch` / -`verifyBatchBytes` are proved to refine `CertiFri.Stark.verifyBatchTensor` with **C1 -(`shapeOk`) and C6 (`verifyClaimsFromTensor`, `widthsOk`, `logMaxHeight ≤ 32`) discharged** -(requiring only the explicit Tier-2 arithmetic challenge cap `kCol + kOpen ≤ 32`), and the -capped wrappers `verifyBatchTensorCapped` / `verifyBatchBytesTensorCapped` refine -`CertiFri.Stark.verifyBatchTensor` with **zero** residual hypotheses -(`Ix.Cert.MultiStark.VerifierRefinement.Batch.verifyBatchBytesTensorCapped_refines_verifyBatchTensor`). +Supports both: +- **Inner binary `v6`** (`maxLogArity = 1`, `logFinalPolyLen = 0`: IxVM, recursion, aggregation), and +- **Multi-arity 8-ary EP1** (`maxLogArity = 3`, `logFinalPolyLen = 8`: transparent + `compact400KBBalanced` and `compact400KBCompact`). -Note: multi-arity Endpoint 1 shrunk proofs (`maxLogArity = 3`, `logFinalPolyLen = 8`) and -`v6-zk` hiding-PCS proofs require the multi-arity verifier extension and are outside the scope -of this binary Protocol `v6` batch verifier. +Imports **zero** Mathlib and calls **zero** Rust FFI (pure Lean BLAKE3 + Goldilocks + +`CertiFri` verifier). Note that hiding `v6-zk` proofs are rejected fail-closed (`zk := false`). Usage: - `verify-multistark [--allow-below-floor] [--allow-inactive-prep]` -- `verify-multistark --self-test` (verifies all 5 committed Rust `v6` fixtures + tamper rejection) +- `verify-multistark --self-test` (verifies all 5 committed Rust pinned `v6` fixtures + tamper rejection) -/ -open Ix.Cert.MultiStark +open Ix.Cert.MultiStark.PinnedVerifier +open CertiFri.P3.Wire private def usage : String := "usage: verify-multistark [--allow-below-floor] [--allow-inactive-prep]\n" ++ @@ -39,32 +33,13 @@ private def flipByte (bs : ByteArray) (idx : Nat) : ByteArray := else bs -/-- Production default calls `verifyBatchBytesTensorCapped` directly (enforcing the -128-bit security floor, active-preprocessed parity, and the zero-residual Tier-2 tensor -challenge cap `kCol + kOpen ≤ 32`). Explicit test-harness waivers (`--allow-below-floor`, -`--allow-inactive-prep`) relax only their named checks while retaining `shardTensorChallengeCapOk`. -/ -private def verifyBatchBytesTensorCappedWithFloor (vkBytes claimsBytes proofBytes : ByteArray) - (allowBelowFloor allowInactivePrep : Bool) : Bool := - if !allowBelowFloor && !allowInactivePrep then - verifyBatchBytesTensorCapped vkBytes claimsBytes proofBytes none - else - match StarkSystem.fromBytes vkBytes, decodeClaims claimsBytes, BatchProof.fromBytes proofBytes with - | .ok sys, .ok expectedClaims, .ok batch => - if !batch.proofs.all (shardTensorChallengeCapOk sys) then false - else - let maxLog := 32 - sys.params.logBlowup - match verifyBatchWithFloor sys batch maxLog allowBelowFloor allowInactivePrep with - | some foundClaims => foundClaims == expectedClaims - | none => false - | _, _, _ => false - private def verifyOne (sysPath claimsPath proofPath : System.FilePath) (allowBelowFloor allowInactivePrep : Bool) : IO UInt32 := do let sysBytes ← IO.FS.readBinFile sysPath let claimsBytes ← IO.FS.readBinFile claimsPath let proofBytes ← IO.FS.readBinFile proofPath let t0 ← IO.monoMsNow - let ok := verifyBatchBytesTensorCappedWithFloor sysBytes claimsBytes proofBytes + let ok := verifyBytesPinnedIx sysBytes claimsBytes proofBytes allowBelowFloor allowInactivePrep let dt := (← IO.monoMsNow) - t0 if ok then @@ -90,17 +65,17 @@ private def runSelfTest : IO UInt32 := do let clmBytes ← IO.FS.readBinFile (dir / "claims.bin") let prfBytes ← IO.FS.readBinFile (dir / "proof.bin") let t0 ← IO.monoMsNow - let acc := verifyBatchBytesTensorCappedWithFloor sysBytes clmBytes prfBytes true hasInactivePrep - let rejPrf := !verifyBatchBytesTensorCappedWithFloor sysBytes clmBytes (flipByte prfBytes (prfBytes.size - 1)) - true hasInactivePrep - let rejClm := !verifyBatchBytesTensorCappedWithFloor sysBytes (flipByte clmBytes (clmBytes.size - 1)) prfBytes - true hasInactivePrep - let rejVk := !verifyBatchBytesTensorCappedWithFloor (flipByte sysBytes 6) clmBytes prfBytes - true hasInactivePrep + let acc := verifyBytesPinnedIx sysBytes clmBytes prfBytes false hasInactivePrep + let rejPrf := !verifyBytesPinnedIx sysBytes clmBytes (flipByte prfBytes (prfBytes.size - 1)) + false hasInactivePrep + let rejClm := !verifyBytesPinnedIx sysBytes (flipByte clmBytes (clmBytes.size - 1)) prfBytes + false hasInactivePrep + let rejVk := !verifyBytesPinnedIx (flipByte sysBytes 6) clmBytes prfBytes + false hasInactivePrep let strictOk := !hasInactivePrep || - !verifyBatchBytesTensorCappedWithFloor sysBytes clmBytes prfBytes true false - let capOk := match StarkSystem.fromBytes sysBytes, BatchProof.fromBytes prfBytes with - | .ok sys, .ok batch => batch.proofs.all (shardTensorChallengeCapOk sys) + !verifyBytesPinnedIx sysBytes clmBytes prfBytes false false + let capOk := match decodeKey sysBytes, decodeBatchPinned prfBytes with + | some key, some pb => pb.batch.proofs.all (shardTensorChallengeCapOkPinned key) | _, _ => false let dt := (← IO.monoMsNow) - t0 if acc && rejPrf && rejClm && rejVk && strictOk && capOk then @@ -109,7 +84,26 @@ private def runSelfTest : IO UInt32 := do else failed := failed + 1 IO.eprintln s!"[FAIL] {name}: acc={acc} rejPrf={rejPrf} rejClm={rejClm} rejVk={rejVk} strictOk={strictOk} capOk={capOk}" - IO.println s!"Native Lean Multi-STARK verifier self-test: {passed} passed, {failed} failed" + -- Negative control: below-floor fixture rejected by production default + let lowDir : System.FilePath := "Tests/Fixtures/MultiStark/single_no_prep/below_floor" + let lowSys ← IO.FS.readBinFile (lowDir / "system.bin") + let lowClm ← IO.FS.readBinFile (lowDir / "claims.bin") + let lowPrf ← IO.FS.readBinFile (lowDir / "proof.bin") + let rejBelowFloor := !verifyBytesPinnedIx lowSys lowClm lowPrf false false + let accBelowFloorWaiver := verifyBytesPinnedIx lowSys lowClm lowPrf true false + -- Negative control: non-zero commit PoW witness when commit_pow_bits == 0 rejected + let npDir : System.FilePath := "Tests/Fixtures/MultiStark/single_no_prep" + let npSys ← IO.FS.readBinFile (npDir / "system.bin") + let npClm ← IO.FS.readBinFile (npDir / "claims.bin") + let badCpowPrf ← IO.FS.readBinFile (npDir / "nonzero_cpow" / "proof.bin") + let rejNonzeroCpow := !verifyBytesPinnedIx npSys npClm badCpowPrf false false + if rejBelowFloor && accBelowFloorWaiver && rejNonzeroCpow then + passed := passed + 1 + IO.println "[PASS] negative_controls: below_floor=reject (waiver=accept), nonzero_cpow=reject" + else + failed := failed + 1 + IO.eprintln s!"[FAIL] negative_controls: rejBelowFloor={rejBelowFloor} accWaiver={accBelowFloorWaiver} rejNonzeroCpow={rejNonzeroCpow}" + IO.println s!"Native Lean Multi-STARK pinned verifier self-test: {passed} passed, {failed} failed" return if failed == 0 then 0 else 1 def main (args : List String) : IO UInt32 := do diff --git a/Tests/AggrBindingReuse.lean b/Tests/AggrBindingReuse.lean index f6b0ef5752..6dc720b744 100644 --- a/Tests/AggrBindingReuse.lean +++ b/Tests/AggrBindingReuse.lean @@ -35,6 +35,8 @@ public section namespace Tests.Aggr.BindingReuse +open LSpec + /-- The closures of `names` and of the constants the kernel fabricates during reduction, with every inductive's recursors (`IxVM.ClaimHarness.collectCertifiedClosure`: the binder-data annotator @@ -180,8 +182,9 @@ def runWith (name : String) (aggregate : Bool) : IO UInt32 := do bindingProof aggregate let right ← claimSet exe home dir "right" rightEnv 2 bindingProof aggregate (traceShards := true) - LSpec.lspecIO (.ofList [(name, - (left ++ right).toList.map fun (label, ok) => LSpec.test label ok)]) [] + LSpec.lspecMain (describe name do + for (label, ok) in left ++ right do + itBool label ok) [] finally IO.FS.removeDirAll home IO.FS.removeDirAll dir diff --git a/Tests/AggrSemantics.lean b/Tests/AggrSemantics.lean index f62b7e44e6..07daf14cda 100644 --- a/Tests/AggrSemantics.lean +++ b/Tests/AggrSemantics.lean @@ -20,7 +20,7 @@ open LSpec Aiur namespace Tests.Aggr -open Tests.ProofHelpers (expectOk expectErr recCommitParams innerFri u64le) +open Tests.ProofHelpers (recCommitParams innerFri u64le) private def canonicalTree (leaves : Array Address) : Ix.AssumptionTree := (Ix.AssumptionTree.canonical leaves).get! @@ -771,94 +771,93 @@ def semanticSuite : IO UInt32 := do finally IO.FS.removeDirAll tmpDir - lspecIO (.ofList [("ix-aggr-semantics", [ - test "recursion FRI cache encoding is the pinned 40-byte layout" - defaultFriEncodingStable, - test "FRI and commitment overrides independently change recursion identity" - recursionParametersIndependent, - test "aggregate cache version is 2" (Aggr.aggregateCacheVersion == 2), - test "aggregate cache key is stable for identical inputs" cacheKeyStable, - test "aggregate cache key binds the uniform outer claim" cacheKeyBindsOuter, - test "aggregate cache key binds recursion FRI parameters" cacheKeyBindsFri, - test "aggregate cache key binds the recursion verifying key" cacheKeyBindsVk, - test "aggregate cache key rejects version-1 entries" cacheKeyBindsVersion, - test "Rust and Lean aggregate cache identity share a fixed vector" - cacheKeyMatchesRustVector, - test "wrap-first specs precompute every uniform claim and cache key" - wrapSpecsComplete, - test "direct specs retain raw IxVM leaves and one aggregate root" - directSpecsUseRawLeaves, - test "wrap-first and direct policies derive the same flat root claim" - policiesShareRootClaim, - test "aggregate outer claims bind the exact CheckEnv value" outerClaimBindsValue, - test "aggregate verifier accepts a content-addressed proof wrapper" - wrapperContentAddressAccepted, - test "aggregate verifier rejects a wrapper stored under the wrong address" - wrapperContentAddressRejected, - test "flat host fold constructs canonical union/discharge trees" flatHostCorrect, - test "structural host fold constructs root-of-roots and survivors" - structuralHostCorrect, - test "CheckEnvTrees.ofClaim rejects overlapping subjects and assumptions" - ofClaimRejectsSelfAssumption, - test "host join helpers do not self-discharge assumptions" - hostJoinRejectsSelfDischarge, - test "manifest tree lowers to post-order binary slots" - (manifestPlan == expectedPlan), - test "manifest parser exposes its validated bisection tree" parsedManifestPlan, - test "manifest parser rejects repeated aggregation leaves" - malformedManifestRejected, - test "coverage accepts legacy zero-constant manifest leaves" singleCoverage, - test "empty manifest leaves contract and retained ids remap densely" - emptyPruningCorrect, - test "one retained shard reconstructs one value-based root" singletonValueRoot, - test "two-shard manifest passes exact environment coverage" pairCoverage, - test "aggregate startup prepares every shard from one ownership pass" - batchedShardPreparationCorrect, - test "flat manifest value equals the canonical environment root" - manifestFlatIsCanonical, - test "structural manifest value equals the manifest-relative hybrid root" - manifestStructuralIsHybrid, - test "flat and structural schedules produce distinguishable values" - manifestValuesDiffer, - test "shard prep preserves trees and one-pass closure semantics" - shardPrepPreservesSemantics, - test "verified aggregate proof audit certifies every fixture constant" - aggregateProofAuditsEveryConstant, - test "dated Mathlib Stage 2 proof is pinned and rejected by the current protocol" - productionStage2FixturePinnedAndFenced, - test "aggregate constant audit rejects an omitted environment constant" - missingConstantRejected, - test "aggregate constant audit rejects a foreign subject" - foreignConstantRejected, - test "aggregate constant audit rejects a duplicate subject" - duplicateConstantRejected, - test "aggregate constant audit rejects residual assumptions" - residualAssumptionRejected, - test "threshold scheduling is flat below and structural above monotonically" - mixedScheduleCorrect, - test "flat self-pair RAM reserve is affine in subject leaves" - flatWeightAffine, - test "aggregate scheduler parses MemTotal for its default budget" - memTotalParsing, - test "invalid non-post-order schedules are rejected" invalidScheduleRejected, - test "CodecTag has no custom aliasing for tags 0/1/2" codecTagNoAliasing, - test "DynamicLinkStatement with (spec, binding) BridgeBinding round-trips and is rejected by Claim.de" - dlStmtRoundTripsAndDisjoint, - test "LinkedCircuitEntry (0xE8 0x0F, with evalType) round-trips and is rejected by Claim.de" - dlEntryRoundTripsAndDisjoint, - test "Shape 18 Mode 3a cannot emit validator 3/4 or erase linkedCircuits" - mode3aCannotEmitValidator3Or4, - test "ClaimPolicy rejects linkedCircuits != none (validators 12/13) by default" - defaultPolicyRefusesLinked, - test "ClaimPolicy.refusalDynamicBytes rejects LinkedClaim, EvalAssumedClaim, and DynamicLinkStatement by default" - defaultPolicyRefusesDynamicBytes, - test "ClaimPolicy enforces no wildcard, separate Mode-3a allowlist, full tuple pinning, and rejects forged (myTrue, myFalse, MyProp)" - allowlistPolicyChecks, - test "ClaimPolicy.refusalDynamicLinkStatement enforces bridge.binding/customBinding and codec arities" - dynamicLinkStatementPolicyChecks, - test "VerifyCmd CLI fails closed on wildcards and routes --dynamic-claim through ClaimPolicy" - verifyCmdDynamicDispatchChecks - ])]) [] + lspecMain (describe "ix-aggr-semantics" do + itBool "recursion FRI cache encoding is the pinned 40-byte layout" + defaultFriEncodingStable + itBool "FRI and commitment overrides independently change recursion identity" + recursionParametersIndependent + itBool "aggregate cache version is 2" (Aggr.aggregateCacheVersion == 2) + itBool "aggregate cache key is stable for identical inputs" cacheKeyStable + itBool "aggregate cache key binds the uniform outer claim" cacheKeyBindsOuter + itBool "aggregate cache key binds recursion FRI parameters" cacheKeyBindsFri + itBool "aggregate cache key binds the recursion verifying key" cacheKeyBindsVk + itBool "aggregate cache key rejects version-1 entries" cacheKeyBindsVersion + itBool "Rust and Lean aggregate cache identity share a fixed vector" + cacheKeyMatchesRustVector + itBool "wrap-first specs precompute every uniform claim and cache key" + wrapSpecsComplete + itBool "direct specs retain raw IxVM leaves and one aggregate root" + directSpecsUseRawLeaves + itBool "wrap-first and direct policies derive the same flat root claim" + policiesShareRootClaim + itBool "aggregate outer claims bind the exact CheckEnv value" outerClaimBindsValue + itBool "aggregate verifier accepts a content-addressed proof wrapper" + wrapperContentAddressAccepted + itBool "aggregate verifier rejects a wrapper stored under the wrong address" + wrapperContentAddressRejected + itBool "flat host fold constructs canonical union/discharge trees" flatHostCorrect + itBool "structural host fold constructs root-of-roots and survivors" + structuralHostCorrect + itBool "CheckEnvTrees.ofClaim rejects overlapping subjects and assumptions" + ofClaimRejectsSelfAssumption + itBool "host join helpers do not self-discharge assumptions" + hostJoinRejectsSelfDischarge + itBool "manifest tree lowers to post-order binary slots" + (manifestPlan == expectedPlan) + itBool "manifest parser exposes its validated bisection tree" parsedManifestPlan + itBool "manifest parser rejects repeated aggregation leaves" + malformedManifestRejected + itBool "coverage accepts legacy zero-constant manifest leaves" singleCoverage + itBool "empty manifest leaves contract and retained ids remap densely" + emptyPruningCorrect + itBool "one retained shard reconstructs one value-based root" singletonValueRoot + itBool "two-shard manifest passes exact environment coverage" pairCoverage + itBool "aggregate startup prepares every shard from one ownership pass" + batchedShardPreparationCorrect + itBool "flat manifest value equals the canonical environment root" + manifestFlatIsCanonical + itBool "structural manifest value equals the manifest-relative hybrid root" + manifestStructuralIsHybrid + itBool "flat and structural schedules produce distinguishable values" + manifestValuesDiffer + itBool "shard prep preserves trees and one-pass closure semantics" + shardPrepPreservesSemantics + itBool "verified aggregate proof audit certifies every fixture constant" + aggregateProofAuditsEveryConstant + itBool "dated Mathlib Stage 2 proof is pinned and rejected by the current protocol" + productionStage2FixturePinnedAndFenced + itBool "aggregate constant audit rejects an omitted environment constant" + missingConstantRejected + itBool "aggregate constant audit rejects a foreign subject" + foreignConstantRejected + itBool "aggregate constant audit rejects a duplicate subject" + duplicateConstantRejected + itBool "aggregate constant audit rejects residual assumptions" + residualAssumptionRejected + itBool "threshold scheduling is flat below and structural above monotonically" + mixedScheduleCorrect + itBool "flat self-pair RAM reserve is affine in subject leaves" + flatWeightAffine + itBool "aggregate scheduler parses MemTotal for its default budget" + memTotalParsing + itBool "invalid non-post-order schedules are rejected" invalidScheduleRejected + itBool "CodecTag has no custom aliasing for tags 0/1/2" codecTagNoAliasing + itBool "DynamicLinkStatement with (spec, binding) BridgeBinding round-trips and is rejected by Claim.de" + dlStmtRoundTripsAndDisjoint + itBool "LinkedCircuitEntry (0xE8 0x0F, with evalType) round-trips and is rejected by Claim.de" + dlEntryRoundTripsAndDisjoint + itBool "Shape 18 Mode 3a cannot emit validator 3/4 or erase linkedCircuits" + mode3aCannotEmitValidator3Or4 + itBool "ClaimPolicy rejects linkedCircuits != none (validators 12/13) by default" + defaultPolicyRefusesLinked + itBool "ClaimPolicy.refusalDynamicBytes rejects LinkedClaim, EvalAssumedClaim, and DynamicLinkStatement by default" + defaultPolicyRefusesDynamicBytes + itBool "ClaimPolicy enforces no wildcard, separate Mode-3a allowlist, full tuple pinning, and rejects forged (myTrue, myFalse, MyProp)" + allowlistPolicyChecks + itBool "ClaimPolicy.refusalDynamicLinkStatement enforces bridge.binding/customBinding and codec arities" + dynamicLinkStatementPolicyChecks + itBool "VerifyCmd CLI fails closed on wildcards and routes --dynamic-claim through ClaimPolicy" + verifyCmdDynamicDispatchChecks) [] def convergedSuite : IO UInt32 := semanticSuite diff --git a/Tests/AggrToolchains.lean b/Tests/AggrToolchains.lean index 607e42b483..1149d5a2de 100644 --- a/Tests/AggrToolchains.lean +++ b/Tests/AggrToolchains.lean @@ -41,6 +41,8 @@ public section namespace Tests.Aggr.Toolchains +open LSpec + private def isAddressHex (s : String) : Bool := s.length == 64 && s.all fun c => c.isDigit || ('a' ≤ c && c ≤ 'f') @@ -204,8 +206,9 @@ def run : IO UInt32 := do #["--max-ram", toString maxRam]) checks := checks.push ("the join refuses a catalog with a member root missing", refusedJoin.exitCode != 0) - LSpec.lspecIO (.ofList [("aggregate-toolchains", - checks.toList.map fun (label, ok) => LSpec.test label ok)]) [] + LSpec.lspecMain (describe "aggregate-toolchains" do + for (label, ok) in checks do + itBool label ok) [] finally IO.FS.removeDirAll home IO.FS.removeDirAll dir diff --git a/Tests/Aiur/Cost.lean b/Tests/Aiur/Cost.lean index 0bae3983e7..d6687cf62e 100644 --- a/Tests/Aiur/Cost.lean +++ b/Tests/Aiur/Cost.lean @@ -30,49 +30,52 @@ quotient chunks `q·D = 6`; at `h = 8`: `(B+1)·7·F(8) + D·F(16) + q·D·F(32) = 35·24 + 3·64 + 6·160 = 1992`. -/ def handComputed : Float := 1992.0 -def transformCostTests : TestSeq := - test "F(0) = 0 (empty circuit is deactivated)" (transformCost 0 == 0.0) ++ - test "F(1) = 1 (clamp keeps height-1 transforms nonzero)" - (transformCost 1 == 1.0) ++ - test "F(2) = 2" (transformCost 2 == 2.0) ++ - test "F(4) = 8" (transformCost 4 == 8.0) ++ - test "F(1024) = 10240" (transformCost 1024 == 10240.0) ++ - test "F strictly increases across a power-of-two boundary" - (transformCost 1023 < transformCost 1024 && - transformCost 1024 < transformCost 1025) +def transformCostTests : LSpec.Spec := do + itBool "F(0) = 0 (empty circuit is deactivated)" (transformCost 0 == 0.0) + itBool "F(1) = 1 (clamp keeps height-1 transforms nonzero)" + (transformCost 1 == 1.0) + itBool "F(2) = 2" (transformCost 2 == 2.0) + itBool "F(4) = 8" (transformCost 4 == 8.0) + itBool "F(1024) = 10240" (transformCost 1024 == 10240.0) + itBool "F strictly increases across a power-of-two boundary" + (decide (transformCost 1023 < transformCost 1024) && + decide (transformCost 1024 < transformCost 1025)) -def fftCostTests : TestSeq := - test "cost is zero at h = 0" (fftCost fnShape 0 2 == 0.0) ++ - test "hand-computed value at h = 8, logBlowup = 2" - (fftCost fnShape 8 2 == handComputed) ++ - test "one-row sensitivity at small heights" - (fftCost fnShape 1 2 < fftCost fnShape 2 2 && - fftCost fnShape 2 2 < fftCost fnShape 3 2) ++ - test "one-row sensitivity across a power-of-two boundary" - (fftCost fnShape 1023 2 < fftCost fnShape 1024 2 && - fftCost fnShape 1024 2 < fftCost fnShape 1025 2) ++ - test "wider main trace costs more" - (fftCost fnShape 8 2 < - fftCost { fnShape with mainWidth := fnShape.mainWidth + 1 } 8 2) ++ - test "extra lookup (wider stage 2) costs more" - (fftCost fnShape 8 2 < - fftCost { fnShape with stage2Width := fnShape.stage2Width + 2 } 8 2) ++ - test "higher quotient degree costs more" - (fftCost fnShape 8 2 < - fftCost { fnShape with quotientDegree := 4 } 8 2) ++ - test "larger blowup costs more" - (fftCost fnShape 8 1 < fftCost fnShape 8 2) ++ - test "committedWidth = main + stage2 + q·D" +def fftCostTests : LSpec.Spec := do + itBool "cost is zero at h = 0" (fftCost fnShape 0 2 == 0.0) + itBool "hand-computed value at h = 8, logBlowup = 2" + (fftCost fnShape 8 2 == handComputed) + itBool "one-row sensitivity at small heights" + (decide (fftCost fnShape 1 2 < fftCost fnShape 2 2) && + decide (fftCost fnShape 2 2 < fftCost fnShape 3 2)) + itBool "one-row sensitivity across a power-of-two boundary" + (decide (fftCost fnShape 1023 2 < fftCost fnShape 1024 2) && + decide (fftCost fnShape 1024 2 < fftCost fnShape 1025 2)) + itBool "wider main trace costs more" + (decide (fftCost fnShape 8 2 < + fftCost { fnShape with mainWidth := fnShape.mainWidth + 1 } 8 2)) + itBool "extra lookup (wider stage 2) costs more" + (decide (fftCost fnShape 8 2 < + fftCost { fnShape with stage2Width := fnShape.stage2Width + 2 } 8 2)) + itBool "higher quotient degree costs more" + (decide (fftCost fnShape 8 2 < + fftCost { fnShape with quotientDegree := 4 } 8 2)) + itBool "larger blowup costs more" + (decide (fftCost fnShape 8 1 < fftCost fnShape 8 2)) + itBool "committedWidth = main + stage2 + q·D" (fnShape.committedWidth == 4 + 3 + 2 * G.extensionDegree) -def formatSciTests : TestSeq := - test "formatSci 0 = 0" (formatSci 0.0 == "0") ++ - test "formatSci 1 = 1.00e0" (formatSci 1.0 == "1.00e0") ++ - test "formatSci 1424 = 1.42e3" (formatSci 1424.0 == "1.42e3") ++ - test "formatSci 174253453 = 1.74e8" (formatSci 174253453.0 == "1.74e8") ++ - test "mantissa carry: formatSci 999.9 = 1.00e3" (formatSci 999.9 == "1.00e3") +def formatSciTests : LSpec.Spec := do + itBool "formatSci 0 = 0" (formatSci 0.0 == "0") + itBool "formatSci 1 = 1.00e0" (formatSci 1.0 == "1.00e0") + itBool "formatSci 1424 = 1.42e3" (formatSci 1424.0 == "1.42e3") + itBool "formatSci 174253453 = 1.74e8" (formatSci 174253453.0 == "1.74e8") + itBool "mantissa carry: formatSci 999.9 = 1.00e3" (formatSci 999.9 == "1.00e3") -def tests : TestSeq := transformCostTests ++ fftCostTests ++ formatSciTests +def tests : LSpec.Spec := do + transformCostTests + fftCostTests + formatSciTests end AiurTests.Cost diff --git a/Tests/Cli.lean b/Tests/Cli.lean index 6ba7850b08..504bee025e 100644 --- a/Tests/Cli.lean +++ b/Tests/Cli.lean @@ -100,8 +100,8 @@ private def Tests.Cli.testCompileContracts : IO Unit := do import Tests.Ix.SourceContract.Imported\n\ open scoped Ix.Modes\n\ inductive CliBox | mk (a b : Nat)\n\ - def cliLocal (@borrowed x : CliBox) : @borrowed CliBox := x\n\ - def cliEscape (@borrowed x : CliBox) : CliBox := x\n" + def cliLocal (@[borrowed] x : CliBox) : @[borrowed] CliBox := x\n\ + def cliEscape (@[borrowed] x : CliBox) : CliBox := x\n" let compile := fun name flags => IO.Process.output { cmd := ix.toString args := #["compile", source.toString, "--no-build", "--consts", name, @@ -508,7 +508,7 @@ private def Tests.Cli.testKernelLimits : IO Unit := do open scoped Ix.Modes\n\ def cliLvl.{u, v} : Sort (max (u + 2) (v + 2)) := Sort (max (v + 1) (u + 1))\n\ inductive CliBox | mk (a b : Nat)\n\ - def cliLocal (@borrowed x : CliBox) : @borrowed CliBox := let _ := cliLvl.{0, 0}; x\n" + def cliLocal (@[borrowed] x : CliBox) : @[borrowed] CliBox := let _ := cliLvl.{0, 0}; x\n" let compile := fun (flags : Array String) (vars : Array (String × Option String)) => Tests.Cli.runEnv ix.toString (#["compile", contracts.toString, "--no-build", "--consts", "cliLocal", "--out", (dir / "contracts.ixe").toString] ++ flags) vars diff --git a/Tests/FFI.lean b/Tests/FFI.lean index 36d260e97e..b827d15840 100644 --- a/Tests/FFI.lean +++ b/Tests/FFI.lean @@ -12,14 +12,13 @@ public import Tests.FFI.Refcount namespace Tests.FFI -public def suiteWith (cfg : SlimCheck.Configuration := {}) (valgrind : Bool := false) : - List LSpec.TestSeq := List.foldr (· ++ ·) [] - [ Tests.FFI.Basic.suiteWith cfg - , Tests.FFI.Ixon.suiteWith cfg - , Tests.FFI.Lifecycle.suiteWith cfg - , Tests.FFI.Refcount.suiteWith cfg valgrind - ] +public def suiteWith (cfg : LSpec.Prop.PropertyConfig := {}) (valgrind : Bool := false) : + LSpec.Spec := do + Tests.FFI.Basic.suiteWith cfg + Tests.FFI.Ixon.suiteWith cfg + Tests.FFI.Lifecycle.suiteWith cfg + Tests.FFI.Refcount.suiteWith cfg valgrind -public def suite : List LSpec.TestSeq := suiteWith {} false +public def suite : LSpec.Spec := suiteWith {} false end Tests.FFI diff --git a/Tests/FFI/Basic.lean b/Tests/FFI/Basic.lean index 8794caad12..69dd101a3c 100644 --- a/Tests/FFI/Basic.lean +++ b/Tests/FFI/Basic.lean @@ -8,7 +8,7 @@ public import LSpec public import Tests.Gen.Basic public import Std.Data.HashMap -open LSpec SlimCheck Gen +open LSpec LSpec.Prop Gen namespace Tests.FFI.Basic @@ -42,25 +42,25 @@ def assocListEq (l1 l2 : AssocList Nat (fun _ => Nat)) : Bool := l.toList.map fun ⟨k, v⟩ => (k, v) toSimpleList l1 == toSimpleList l2 -def assocListTests : TestSeq := +def assocListTests : LSpec.Spec := do let emptyList : AssocList Nat (fun _ => Nat) := .nil let single : AssocList Nat (fun _ => Nat) := .cons 1 42 .nil let double : AssocList Nat (fun _ => Nat) := .cons 2 99 (.cons 1 42 .nil) - test "AssocList nil" (assocListEq (roundtripAssocListNatNat emptyList) emptyList) ++ - test "AssocList single" (assocListEq (roundtripAssocListNatNat single) single) ++ - test "AssocList double" (assocListEq (roundtripAssocListNatNat double) double) + itBool "AssocList nil" (assocListEq (roundtripAssocListNatNat emptyList) emptyList) + itBool "AssocList single" (assocListEq (roundtripAssocListNatNat single) single) + itBool "AssocList double" (assocListEq (roundtripAssocListNatNat double) double) -def hashMapTests : TestSeq := - test "HashMap empty" (hashMapEq (roundtripHashMapNatNat {}) {}) ++ - test "HashMap single" (hashMapEq (roundtripHashMapNatNat (({} : Std.HashMap Nat Nat).insert 1 42)) (({} : Std.HashMap Nat Nat).insert 1 42)) +def hashMapTests : LSpec.Spec := do + itBool "HashMap empty" (hashMapEq (roundtripHashMapNatNat {}) {}) + itBool "HashMap single" (hashMapEq (roundtripHashMapNatNat (({} : Std.HashMap Nat Nat).insert 1 42)) (({} : Std.HashMap Nat Nat).insert 1 42)) -def dHashMapRawTests : TestSeq := +def dHashMapRawTests : LSpec.Spec := do let emptyMap : DHashMapRaw Nat (fun _ => Nat) := {} let single : DHashMapRaw Nat (fun _ => Nat) := ({} : DHashMapRaw Nat (fun _ => Nat)).insert 1 42 let double : DHashMapRaw Nat (fun _ => Nat) := (({} : DHashMapRaw Nat (fun _ => Nat)).insert 1 42).insert 2 99 - test "DHashMapRaw empty" (dHashMapRawEq (roundtripDHashMapRawNatNat emptyMap) emptyMap) ++ - test "DHashMapRaw single" (dHashMapRawEq (roundtripDHashMapRawNatNat single) single) ++ - test "DHashMapRaw double" (dHashMapRawEq (roundtripDHashMapRawNatNat double) double) + itBool "DHashMapRaw empty" (dHashMapRawEq (roundtripDHashMapRawNatNat emptyMap) emptyMap) + itBool "DHashMapRaw single" (dHashMapRawEq (roundtripDHashMapRawNatNat single) single) + itBool "DHashMapRaw double" (dHashMapRawEq (roundtripDHashMapRawNatNat double) double) /-! ## Mixed-width scalar records @@ -86,30 +86,31 @@ opaque mixedScalarsFields : @& MixedScalars → String × Array Nat @[extern "rs_roundtrip_mixed_scalars"] opaque roundtripMixedScalars : @& MixedScalars → MixedScalars -def mixedScalarsTests : TestSeq := +def mixedScalarsTests : LSpec.Spec := do let m : MixedScalars := ⟨true, 0x0102030405060708, "mixed", 0xab, 0xcdef, 0x89abcdef, 12345, 678⟩ let z : MixedScalars := ⟨false, 0, "", 0, 0, 0, 0, 0⟩ - test "MixedScalars fields read from Lean" (mixedScalarsFields m == - ("mixed", #[1, 0x0102030405060708, 0xab, 0xcdef, 0x89abcdef, 12345, 678])) ++ - test "MixedScalars zero fields read from Lean" (mixedScalarsFields z == - ("", #[0, 0, 0, 0, 0, 0, 0])) ++ - test "MixedScalars roundtrip" (roundtripMixedScalars m == m) ++ - test "MixedScalars zero roundtrip" (roundtripMixedScalars z == z) + itBool "MixedScalars fields read from Lean" (mixedScalarsFields m == + ("mixed", #[1, 0x0102030405060708, 0xab, 0xcdef, 0x89abcdef, 12345, 678])) + itBool "MixedScalars zero fields read from Lean" (mixedScalarsFields z == + ("", #[0, 0, 0, 0, 0, 0, 0])) + itBool "MixedScalars roundtrip" (roundtripMixedScalars m == m) + itBool "MixedScalars zero roundtrip" (roundtripMixedScalars z == z) /-! ## Test Suite -/ -public def suiteWith (cfg : SlimCheck.Configuration := {}) : List TestSeq := [ - assocListTests, - hashMapTests, - dHashMapRawTests, - mixedScalarsTests, - checkIO "HashMap Nat Nat roundtrip" (∀ m : Std.HashMap Nat Nat, hashMapEq (roundtripHashMapNatNat m) m) .done cfg, - checkIO "DHashMapRaw Nat Nat roundtrip" (∀ m : Std.HashMap Nat Nat, - let raw := m.toList.foldl (init := ({} : DHashMapRaw Nat (fun _ => Nat))) fun acc (k, v) => acc.insert k v - dHashMapRawEq (roundtripDHashMapRawNatNat raw) raw) .done cfg, -] - -public def suite : List TestSeq := suiteWith {} +set_option compiler.extract_closed false in +public def suiteWith (cfg : LSpec.Prop.PropertyConfig := {}) : Spec := do + assocListTests + hashMapTests + dHashMapRawTests + mixedScalarsTests + propWith "HashMap Nat Nat roundtrip" cfg fun (m : Std.HashMap Nat Nat) => + hashMapEq (roundtripHashMapNatNat m) m + propWith "DHashMapRaw Nat Nat roundtrip" cfg fun (m : Std.HashMap Nat Nat) => + let raw := m.toList.foldl (init := ({} : DHashMapRaw Nat (fun _ => Nat))) fun (acc : DHashMapRaw Nat (fun _ => Nat)) (k, v) => acc.insert k v + dHashMapRawEq (roundtripDHashMapRawNatNat raw) raw + +public def suite : Spec := suiteWith {} end Tests.FFI.Basic diff --git a/Tests/FFI/Ixon.lean b/Tests/FFI/Ixon.lean index ee43617179..5ea906b0b9 100644 --- a/Tests/FFI/Ixon.lean +++ b/Tests/FFI/Ixon.lean @@ -12,7 +12,7 @@ public import Ix.Cli.DiffCmd public section -open LSpec SlimCheck Gen Ixon +open LSpec LSpec.Prop Gen Ixon open Ix (DefKind DefinitionSafety QuotKind) namespace Tests.FFI.Ixon @@ -111,66 +111,66 @@ opaque roundtripIxonComm : @& Comm → Comm /-! ## Ixon type FFI unit tests -/ -def ixonDefKindTests : TestSeq := - test "Ixon.DefKind.defn" (roundtripIxonDefKind .defn == .defn) ++ - test "Ixon.DefKind.opaq" (roundtripIxonDefKind .opaq == .opaq) ++ - test "Ixon.DefKind.thm" (roundtripIxonDefKind .thm == .thm) - -def ixonDefinitionSafetyTests : TestSeq := - test "Ixon.DefinitionSafety.unsaf" (roundtripIxonDefinitionSafety .unsaf == .unsaf) ++ - test "Ixon.DefinitionSafety.safe" (roundtripIxonDefinitionSafety .safe == .safe) ++ - test "Ixon.DefinitionSafety.part" (roundtripIxonDefinitionSafety .part == .part) - -def ixonQuotKindTests : TestSeq := - test "Ixon.QuotKind.type" (roundtripIxonQuotKind .type == .type) ++ - test "Ixon.QuotKind.ctor" (roundtripIxonQuotKind .ctor == .ctor) ++ - test "Ixon.QuotKind.lift" (roundtripIxonQuotKind .lift == .lift) ++ - test "Ixon.QuotKind.ind" (roundtripIxonQuotKind .ind == .ind) - -def ixonUnivTests : TestSeq := - test "Ixon.Univ.zero" (roundtripIxonUniv .zero == .zero) ++ - test "Ixon.Univ.var 0" (roundtripIxonUniv (.var 0) == .var 0) ++ - test "Ixon.Univ.var 42" (roundtripIxonUniv (.var 42) == .var 42) ++ - test "Ixon.Univ.succ zero" (roundtripIxonUniv (.succ .zero) == .succ .zero) ++ - test "Ixon.Univ.max" (roundtripIxonUniv (.max .zero (.var 1)) == .max .zero (.var 1)) ++ - test "Ixon.Univ.imax" (roundtripIxonUniv (.imax (.var 0) .zero) == .imax (.var 0) .zero) - -def ixonExprTests : TestSeq := - test "Ixon.Expr.sort" (roundtripIxonExpr (.sort 0) == .sort 0) ++ - test "Ixon.Expr.var" (roundtripIxonExpr (.var 5) == .var 5) ++ - test "Ixon.Expr.ref" (roundtripIxonExpr (.ref 1 #[0, 1]) == .ref 1 #[0, 1]) ++ - test "Ixon.Expr.recur" (roundtripIxonExpr (.recur 2 #[]) == .recur 2 #[]) ++ - test "Ixon.Expr.str" (roundtripIxonExpr (.str 3) == .str 3) ++ - test "Ixon.Expr.nat" (roundtripIxonExpr (.nat 42) == .nat 42) ++ - test "Ixon.Expr.share" (roundtripIxonExpr (.share 0) == .share 0) ++ - test "Ixon.Expr.app" (roundtripIxonExpr (.app (.var 0) (.var 1)) == .app (.var 0) (.var 1)) ++ - test "Ixon.Expr.lam" (roundtripIxonExpr (.lam (.sort 0) (.var 0)) == .lam (.sort 0) (.var 0)) ++ - test "Ixon.Expr.all" (roundtripIxonExpr (.all (.sort 0) (.var 0)) == .all (.sort 0) (.var 0)) ++ - test "Ixon.Expr.letE" (roundtripIxonExpr (.leanLet true (.sort 0) (.var 0) (.var 1)) == .leanLet true (.sort 0) (.var 0) (.var 1)) ++ - test "Ixon.Expr.letE unique" (roundtripIxonExpr (.letE false (.value .unique) (.sort 0) (.var 0) (.var 1)) == - .letE false (.value .unique) (.sort 0) (.var 0) (.var 1)) ++ - test "Ixon.Expr.letE borrow" (roundtripIxonExpr (.letE true .borrow (.sort 0) (.var 0) (.var 1)) == - .letE true .borrow (.sort 0) (.var 0) (.var 1)) ++ - test "Ixon.Expr.prj" (roundtripIxonExpr (.prj 0 1 (.var 0)) == .prj 0 1 (.var 0)) +def ixonDefKindTests : LSpec.Spec := do + itBool "Ixon.DefKind.defn" (roundtripIxonDefKind .defn == .defn) + itBool "Ixon.DefKind.opaq" (roundtripIxonDefKind .opaq == .opaq) + itBool "Ixon.DefKind.thm" (roundtripIxonDefKind .thm == .thm) + +def ixonDefinitionSafetyTests : LSpec.Spec := do + itBool "Ixon.DefinitionSafety.unsaf" (roundtripIxonDefinitionSafety .unsaf == .unsaf) + itBool "Ixon.DefinitionSafety.safe" (roundtripIxonDefinitionSafety .safe == .safe) + itBool "Ixon.DefinitionSafety.part" (roundtripIxonDefinitionSafety .part == .part) + +def ixonQuotKindTests : LSpec.Spec := do + itBool "Ixon.QuotKind.type" (roundtripIxonQuotKind .type == .type) + itBool "Ixon.QuotKind.ctor" (roundtripIxonQuotKind .ctor == .ctor) + itBool "Ixon.QuotKind.lift" (roundtripIxonQuotKind .lift == .lift) + itBool "Ixon.QuotKind.ind" (roundtripIxonQuotKind .ind == .ind) + +def ixonUnivTests : LSpec.Spec := do + itBool "Ixon.Univ.zero" (roundtripIxonUniv .zero == .zero) + itBool "Ixon.Univ.var 0" (roundtripIxonUniv (.var 0) == .var 0) + itBool "Ixon.Univ.var 42" (roundtripIxonUniv (.var 42) == .var 42) + itBool "Ixon.Univ.succ zero" (roundtripIxonUniv (.succ .zero) == .succ .zero) + itBool "Ixon.Univ.max" (roundtripIxonUniv (.max .zero (.var 1)) == .max .zero (.var 1)) + itBool "Ixon.Univ.imax" (roundtripIxonUniv (.imax (.var 0) .zero) == .imax (.var 0) .zero) + +def ixonExprTests : LSpec.Spec := do + itBool "Ixon.Expr.sort" (roundtripIxonExpr (.sort 0) == .sort 0) + itBool "Ixon.Expr.var" (roundtripIxonExpr (.var 5) == .var 5) + itBool "Ixon.Expr.ref" (roundtripIxonExpr (.ref 1 #[0, 1]) == .ref 1 #[0, 1]) + itBool "Ixon.Expr.recur" (roundtripIxonExpr (.recur 2 #[]) == .recur 2 #[]) + itBool "Ixon.Expr.str" (roundtripIxonExpr (.str 3) == .str 3) + itBool "Ixon.Expr.nat" (roundtripIxonExpr (.nat 42) == .nat 42) + itBool "Ixon.Expr.share" (roundtripIxonExpr (.share 0) == .share 0) + itBool "Ixon.Expr.app" (roundtripIxonExpr (.app (.var 0) (.var 1)) == .app (.var 0) (.var 1)) + itBool "Ixon.Expr.lam" (roundtripIxonExpr (.lam (.sort 0) (.var 0)) == .lam (.sort 0) (.var 0)) + itBool "Ixon.Expr.all" (roundtripIxonExpr (.all (.sort 0) (.var 0)) == .all (.sort 0) (.var 0)) + itBool "Ixon.Expr.letE" (roundtripIxonExpr (.leanLet true (.sort 0) (.var 0) (.var 1)) == .leanLet true (.sort 0) (.var 0) (.var 1)) + itBool "Ixon.Expr.letE unique" (roundtripIxonExpr (.letE false (.value .unique) (.sort 0) (.var 0) (.var 1)) == + .letE false (.value .unique) (.sort 0) (.var 0) (.var 1)) + itBool "Ixon.Expr.letE borrow" (roundtripIxonExpr (.letE true .borrow (.sort 0) (.var 0) (.var 1)) == + .letE true .borrow (.sort 0) (.var 0) (.var 1)) + itBool "Ixon.Expr.prj" (roundtripIxonExpr (.prj 0 1 (.var 0)) == .prj 0 1 (.var 0)) /-! ## Metadata Unit Tests -/ -def exprMetaDataTests : TestSeq := +def exprMetaDataTests : LSpec.Spec := do let testAddr := Address.blake3 (ByteArray.mk #[1, 2, 3]) let _kvmap : KVMap := #[(testAddr, DataValue.ofBool true)] - test "ExprMetaData.leaf" (roundtripIxonExprMetaData .leaf == .leaf) ++ - test "ExprMetaData.app" (roundtripIxonExprMetaData (.app 0 1) == .app 0 1) ++ - test "ExprMetaData.ref" (roundtripIxonExprMetaData (.ref testAddr) == .ref testAddr) ++ - test "ExprMetaData.prj" (roundtripIxonExprMetaData (.prj testAddr 5) == .prj testAddr 5) ++ - test "ExprMetaData.letBinder" (roundtripIxonExprMetaData (.letBinder testAddr 0 1 2) == .letBinder testAddr 0 1 2) ++ - test "ExprMetaData.mdata empty" (roundtripIxonExprMetaData (.mdata #[] 0) == .mdata #[] 0) ++ - test "ExprMetaData.mdata with kvmap" (roundtripIxonExprMetaData (.mdata #[_kvmap] 3) == .mdata #[_kvmap] 3) ++ - test "ExprMetaData.binder default" (roundtripIxonExprMetaData (.binder testAddr .default 0 1) == .binder testAddr .default 0 1) ++ - test "ExprMetaData.binder implicit" (roundtripIxonExprMetaData (.binder testAddr .implicit 2 3) == .binder testAddr .implicit 2 3) ++ - test "ExprMetaData.binder strictImplicit" (roundtripIxonExprMetaData (.binder testAddr .strictImplicit 0 0) == .binder testAddr .strictImplicit 0 0) ++ - test "ExprMetaData.binder instImplicit" (roundtripIxonExprMetaData (.binder testAddr .instImplicit 0 0) == .binder testAddr .instImplicit 0 0) - -def exprMetaArenaTests : TestSeq := + itBool "ExprMetaData.leaf" (roundtripIxonExprMetaData .leaf == .leaf) + itBool "ExprMetaData.app" (roundtripIxonExprMetaData (.app 0 1) == .app 0 1) + itBool "ExprMetaData.ref" (roundtripIxonExprMetaData (.ref testAddr) == .ref testAddr) + itBool "ExprMetaData.prj" (roundtripIxonExprMetaData (.prj testAddr 5) == .prj testAddr 5) + itBool "ExprMetaData.letBinder" (roundtripIxonExprMetaData (.letBinder testAddr 0 1 2) == .letBinder testAddr 0 1 2) + itBool "ExprMetaData.mdata empty" (roundtripIxonExprMetaData (.mdata #[] 0) == .mdata #[] 0) + itBool "ExprMetaData.mdata with kvmap" (roundtripIxonExprMetaData (.mdata #[_kvmap] 3) == .mdata #[_kvmap] 3) + itBool "ExprMetaData.binder default" (roundtripIxonExprMetaData (.binder testAddr .default 0 1) == .binder testAddr .default 0 1) + itBool "ExprMetaData.binder implicit" (roundtripIxonExprMetaData (.binder testAddr .implicit 2 3) == .binder testAddr .implicit 2 3) + itBool "ExprMetaData.binder strictImplicit" (roundtripIxonExprMetaData (.binder testAddr .strictImplicit 0 0) == .binder testAddr .strictImplicit 0 0) + itBool "ExprMetaData.binder instImplicit" (roundtripIxonExprMetaData (.binder testAddr .instImplicit 0 0) == .binder testAddr .instImplicit 0 0) + +def exprMetaArenaTests : LSpec.Spec := do let testAddr := Address.blake3 (ByteArray.mk #[1, 2, 3]) let emptyArena : ExprMetaArena := {} let singleLeaf : ExprMetaArena := { nodes := #[.leaf] } @@ -179,12 +179,12 @@ def exprMetaArenaTests : TestSeq := .leaf, .ref testAddr, .app 0 0, .binder testAddr .default 0 1, .letBinder testAddr 0 1 2, .prj testAddr 0, .mdata #[] 0 ] } - checkIO "ExprMetaArena empty" (roundtripIxonExprMetaArena emptyArena == emptyArena) ++ - checkIO "ExprMetaArena single leaf" (roundtripIxonExprMetaArena singleLeaf == singleLeaf) ++ - checkIO "ExprMetaArena small" (roundtripIxonExprMetaArena smallArena == smallArena) ++ - checkIO "ExprMetaArena mixed" (roundtripIxonExprMetaArena mixedArena == mixedArena) + itBool "ExprMetaArena empty" (roundtripIxonExprMetaArena emptyArena == emptyArena) + itBool "ExprMetaArena single leaf" (roundtripIxonExprMetaArena singleLeaf == singleLeaf) + itBool "ExprMetaArena small" (roundtripIxonExprMetaArena smallArena == smallArena) + itBool "ExprMetaArena mixed" (roundtripIxonExprMetaArena mixedArena == mixedArena) -def constantMetaTests : TestSeq := +def constantMetaTests : LSpec.Spec := do let testAddr := Address.blake3 (ByteArray.mk #[1, 2, 3]) let emptyArena : ExprMetaArena := {} let smallArena : ExprMetaArena := { nodes := #[.leaf, .app 0 0, .ref testAddr] } @@ -195,26 +195,26 @@ def constantMetaTests : TestSeq := .mdata #[#[(testAddr, .ofBool true)]] 0 ] } let rt (cm : ConstantMeta) : Bool := roundtripIxonConstantMeta cm == cm - checkIO "ConstantMeta.empty" (rt .empty) ++ - checkIO "ConstantMeta.defn" (rt (.new - (.defn testAddr #[testAddr] #[] #[] smallArena 0 1))) ++ - checkIO "ConstantMeta.axio" (rt (.new (.axio testAddr #[] emptyArena 0))) ++ - checkIO "ConstantMeta.ctor" (rt (.new - (.ctor testAddr #[] testAddr smallArena 2))) ++ - checkIO "ConstantMeta.recr" (rt (.new - (.recr testAddr #[] #[] #[] #[] smallArena 0 #[1, 2]))) ++ - checkIO "ConstantMeta.muts auxLayout none" (rt (.new - (.muts #[#[testAddr]] none))) ++ + itBool "ConstantMeta.empty" (rt .empty) + itBool "ConstantMeta.defn" (rt (.new + (.defn testAddr #[testAddr] #[] #[] smallArena 0 1))) + itBool "ConstantMeta.axio" (rt (.new (.axio testAddr #[] emptyArena 0))) + itBool "ConstantMeta.ctor" (rt (.new + (.ctor testAddr #[] testAddr smallArena 2))) + itBool "ConstantMeta.recr" (rt (.new + (.recr testAddr #[] #[] #[] #[] smallArena 0 #[1, 2]))) + itBool "ConstantMeta.muts auxLayout none" (rt (.new + (.muts #[#[testAddr]] none))) -- `evaporated` fixtures spell the canonical one-flag-per-perm-entry -- form the compiler materializes (the Rust FFI decode expands the -- `#[]` construction default to that shape). - checkIO "ConstantMeta.muts auxLayout some" (rt (.new - (.muts #[#[testAddr]] (some ⟨#[1, 0], #[2, 3], #[0, 0]⟩)))) ++ - checkIO "ConstantMeta.muts auxLayout evaporated" (rt (.new - (.muts #[#[testAddr]] (some ⟨#[1, 0], #[2, 3], #[0, 1]⟩)))) ++ - checkIO "ConstantMeta mdata arena" (rt (.new - (.defn testAddr #[] #[] #[] recordArena 0 1))) ++ - checkIO "ConstantMeta extension tables" (rt + itBool "ConstantMeta.muts auxLayout some" (rt (.new + (.muts #[#[testAddr]] (some ⟨#[1, 0], #[2, 3], #[0, 0]⟩)))) + itBool "ConstantMeta.muts auxLayout evaporated" (rt (.new + (.muts #[#[testAddr]] (some ⟨#[1, 0], #[2, 3], #[0, 1]⟩)))) + itBool "ConstantMeta mdata arena" (rt (.new + (.defn testAddr #[] #[] #[] recordArena 0 1))) + itBool "ConstantMeta extension tables" (rt { info := .defn testAddr #[] #[] #[] recordArena 0 1, metaSharing := #[.app (.share 0) (.var 3), .sort 1], metaRefs := #[testAddr], @@ -245,16 +245,6 @@ opaque rsEqEnvSerialization : @& RawEnv → @& ByteArray → Bool @[extern "rs_roundtrip_raw_env"] opaque roundtripRawEnv : @& RawEnv → RawEnv -instance : Shrinkable RawEnv where - shrink env := - if env.consts.isEmpty && env.named.isEmpty && env.blobs.isEmpty && env.comms.isEmpty then [] - else [{ - consts := if env.consts.isEmpty then #[] else env.consts.pop, - named := if env.named.isEmpty then #[] else env.named.pop, - blobs := if env.blobs.isEmpty then #[] else env.blobs.pop, - comms := if env.comms.isEmpty then #[] else env.comms.pop - }] - /-- Compare RawEnv with content-aware comparison. Checks array sizes and content matching by Address. -/ def rawEnvEq (a b : RawEnv) : Bool := @@ -277,7 +267,7 @@ def rawEnvEq (a b : RawEnv) : Bool := /-! ## RawEnv unit tests -/ -def rawEnvTests : TestSeq := +def rawEnvTests : LSpec.Spec := do let empty : RawEnv := { consts := #[], named := #[], blobs := #[], comms := #[] } -- Create test data for non-empty case let testAddr := Address.blake3 (ByteArray.mk #[1, 2, 3]) @@ -303,8 +293,8 @@ def rawEnvTests : TestSeq := blobs := #[testRawBlob], comms := #[testRawComm] } - test "RawEnv empty" (rawEnvEq (roundtripRawEnv empty) empty) ++ - test "RawEnv with data" (rawEnvEq (roundtripRawEnv withData) withData) + itBool "RawEnv empty" (rawEnvEq (roundtripRawEnv empty) empty) + itBool "RawEnv with data" (rawEnvEq (roundtripRawEnv withData) withData) /-! ## Env diff FFI (`rs_diff_envs`) @@ -312,7 +302,7 @@ The classification logic is covered by Rust unit tests (`crates/ixon/src/diff.rs`); these tests pin the FFI marshaling — a constructor-slot swap would surface as wrong-category contents. -/ -def envDiffTests : TestSeq := +def envDiffTests : LSpec.Spec := do let fooName := Ix.Name.mkStr Ix.Name.mkAnon "foo" let barName := Ix.Name.mkStr Ix.Name.mkAnon "bar" -- `.var` exprs only: classification resolves table indices, so a @@ -349,34 +339,36 @@ def envDiffTests : TestSeq := let runDiff (a b : Env) (compareMeta : Bool := false) : Option Ixon.EnvDiff := (Ixon.rsDiffEnvs (serEnv! a) (serEnv! b) compareMeta).toOption - (TestSeq.individualIO "EnvDiff: CLI exit codes" none (do + it "EnvDiff: CLI exit codes" do let dir ← IO.FS.createTempDir - let pa := dir / "a.ixe" - let pb := dir / "b.ixe" - IO.FS.writeBinFile pa (serEnv! envBase) - IO.FS.writeBinFile pb (serEnv! envValueChanged) - let (sameOut, sameCode) ← IO.FS.withIsolatedStreams - (diffCmd.validate [pa.toString, pa.toString, "--meta"]) - let (_, differCode) ← IO.FS.withIsolatedStreams - (diffCmd.validate [pa.toString, pb.toString, "--anon"]) - IO.FS.removeDirAll dir - let ok := sameCode == 0 && sameOut.contains "identical" && differCode == 1 - return (ok, if ok then 1 else 0, 1, if ok then none else some s!"CLI exits {sameCode}/{differCode}")) .done) ++ - test "EnvDiff: self-diff empty (anon)" - ((runDiff envBase envBase).any (·.isEmpty)) ++ - test "EnvDiff: self-diff empty (meta)" - ((runDiff envBase envBase true).any (·.isEmpty)) ++ - test "EnvDiff: stats populated" + try + let pa := dir / "a.ixe" + let pb := dir / "b.ixe" + IO.FS.writeBinFile pa (serEnv! envBase) + IO.FS.writeBinFile pb (serEnv! envValueChanged) + let (sameOut, sameCode) ← IO.FS.withIsolatedStreams + (diffCmd.validate [pa.toString, pa.toString, "--meta"]) + let (_, differCode) ← IO.FS.withIsolatedStreams + (diffCmd.validate [pa.toString, pb.toString, "--anon"]) + expect (sameCode == 0 && sameOut.contains "identical" && differCode == 1) + s!"CLI exits {sameCode}/{differCode}" + finally + IO.FS.removeDirAll dir + itBool "EnvDiff: self-diff empty (anon)" + ((runDiff envBase envBase).any (·.isEmpty)) + itBool "EnvDiff: self-diff empty (meta)" + ((runDiff envBase envBase true).any (·.isEmpty)) + itBool "EnvDiff: stats populated" ((runDiff envBase envBase).any fun d => - d.statsA.consts == 1 && d.statsA.named == 1 && d.statsB == d.statsA) ++ - test "EnvDiff: added name" + d.statsA.consts == 1 && d.statsA.named == 1 && d.statsB == d.statsA) + itBool "EnvDiff: added name" ((runDiff envBase envExtra).any fun d => d.namedAdded == #[("bar", addrB)] && d.constsOnlyB == #[addrB] - && d.namedRemoved.isEmpty && d.namedChanged.isEmpty) ++ - test "EnvDiff: removed name" + && d.namedRemoved.isEmpty && d.namedChanged.isEmpty) + itBool "EnvDiff: removed name" ((runDiff envExtra envBase).any fun d => - d.namedRemoved == #[("bar", addrB)] && d.constsOnlyA == #[addrB]) ++ - test "EnvDiff: value change classified" + d.namedRemoved == #[("bar", addrB)] && d.constsOnlyA == #[addrB]) + itBool "EnvDiff: value change classified" ((runDiff envBase envValueChanged).any fun d => d.namedChanged.size == 1 && (d.namedChanged[0]!).name == "foo" && @@ -386,10 +378,10 @@ def envDiffTests : TestSeq := (d.namedChanged[0]!).newKind == "defn" && (d.namedChanged[0]!).fields == #["value"] && (d.namedChanged[0]!).metaFields.isEmpty && - (d.namedChanged[0]!).rippled == false) ++ + (d.namedChanged[0]!).rippled == false) -- A dependent whose only change is its ref re-addressing must marshal -- `rippled == true` (pins the num_8 scalar slot against layout swaps). - test "EnvDiff: ripple verdict marshals" + itBool "EnvDiff: ripple verdict marshals" (let mkRefConst (r : Address) : Constant := { info := .defn { kind := .defn, safety := .safe, lvls := 0, typ := .var 3, value := .ref 0 #[] } @@ -409,22 +401,22 @@ def envDiffTests : TestSeq := (runDiff (mkPair constA) (mkPair constB)).any fun d => d.namedChanged.size == 2 && (d.namedChanged.find? (·.name == "foo")).any (·.rippled == false) && - (d.namedChanged.find? (·.name == "bar")).any (·.rippled == true)) ++ + (d.namedChanged.find? (·.name == "bar")).any (·.rippled == true)) -- Hints live only in the env-level hints section, so a hint tweak -- is a pure `hintsChanged` row — no metadata difference in either -- mode (the named entries are identical). - test "EnvDiff: hint change visible in anon mode" + itBool "EnvDiff: hint change visible in anon mode" ((runDiff envBase envHintChanged).any fun d => d.hintsChanged == #[(addrA, "regular(5)", "regular(6)")] - && d.namedMetaOnly.isEmpty && d.namedChanged.isEmpty) ++ - test "EnvDiff: hint change is not a metadata change" + && d.namedMetaOnly.isEmpty && d.namedChanged.isEmpty) + itBool "EnvDiff: hint change is not a metadata change" ((runDiff envBase envHintChanged true).any fun d => d.hintsChanged.size == 1 && d.namedMetaOnly.isEmpty - && d.namedChanged.isEmpty) ++ - test "EnvDiff: main change" + && d.namedChanged.isEmpty) + itBool "EnvDiff: main change" ((runDiff { envBase with main := some addrA } envBase).any fun d => - d.mainChanged == some (some addrA, none)) ++ - test "EnvDiff: assumptions delta" + d.mainChanged == some (some addrA, none)) + itBool "EnvDiff: assumptions delta" (let p := Address.blake3 (ByteArray.mk #[1]) let q := Address.blake3 (ByteArray.mk #[2]) let r := Address.blake3 (ByteArray.mk #[3]) @@ -433,30 +425,25 @@ def envDiffTests : TestSeq := let b := { envBase with assumptions := ({} : Std.HashSet Address).insert q |>.insert r } (runDiff a b).any fun d => - d.assumptionsAdded == #[r] && d.assumptionsRemoved == #[p]) ++ + d.assumptionsAdded == #[r] && d.assumptionsRemoved == #[p]) -- The mmap file-path entry must agree with the bytes-based one, and -- the byte-equality fast path must distinguish same vs different. - (TestSeq.individualIO "EnvDiff: file-based diff matches bytes-based" - none (do - let dir ← IO.FS.createTempDir + it "EnvDiff: file-based diff matches bytes-based" do + let dir ← IO.FS.createTempDir + try let pa := dir / "a.ixe" let pb := dir / "b.ixe" let bytesA := serEnv! envBase let bytesB := serEnv! envValueChanged IO.FS.writeBinFile pa bytesA IO.FS.writeBinFile pb bytesB - let r ← try - let eqSame ← Ixon.rsIxeFilesEqual pa.toString pa.toString - let eqDiff ← Ixon.rsIxeFilesEqual pa.toString pb.toString - let dFiles ← Ixon.rsDiffEnvFiles pa.toString pb.toString false - let ok := eqSame && !eqDiff && - (match Ixon.rsDiffEnvs bytesA bytesB false with - | .ok dBytes => dFiles == dBytes - | .error _ => false) - pure (ok, if ok then none else some "file/bytes reports disagree") - catch e => pure (false, some e.toString) + let eqSame ← Ixon.rsIxeFilesEqual pa.toString pa.toString + let eqDiff ← Ixon.rsIxeFilesEqual pa.toString pb.toString + let dFiles ← Ixon.rsDiffEnvFiles pa.toString pb.toString false + let dBytes ← expectOk (Ixon.rsDiffEnvs bytesA bytesB false) + expect (eqSame && !eqDiff && dFiles == dBytes) "file/bytes reports disagree" + finally IO.FS.removeDirAll dir - pure (r.1, 0, 0, r.2)) .done) /-- Self-diff over the pure-Lean writer's bytes must be empty in both modes (also exercises report marshaling on arbitrary inputs). -/ @@ -496,23 +483,20 @@ private def packFixture (env : Env) (mainName : String) /-- IO test asserting on a successfully packed bundle. -/ private def packTest (descr : String) (act : IO (Except String Env)) - (check : Env → Bool) : TestSeq := - .individualIO descr none (do - match ← act with - | .ok bundle => - let ok := check bundle - pure (ok, 0, 0, if ok then none else some "bundle assertion failed") - | .error e => pure (false, 0, 0, some e)) .done + (check : Env → Bool) : Spec := + it descr do + let bundle ← expectOk (← act) + expect (check bundle) "bundle assertion failed" /-- IO test asserting the pack call fails. -/ private def packErrTest (descr : String) (act : IO (Except String Env)) : - TestSeq := - .individualIO descr none (do + Spec := + it descr do match ← act with - | .ok _ => pure (false, 0, 0, some "expected pack to fail") - | .error _ => pure (true, 0, 0, none)) .done + | .ok _ => fail "expected pack to fail" + | .error _ => pure () -def envPackTests : TestSeq := +def envPackTests : LSpec.Spec := do let fooName := Ix.Name.mkStr Ix.Name.mkAnon "foo" let barName := Ix.Name.mkStr Ix.Name.mkAnon "bar" let quxName := Ix.Name.mkStr Ix.Name.mkAnon "qux" @@ -551,35 +535,30 @@ def envPackTests : TestSeq := && b.getAddr? fooName == some fooAddr && (b.getAddr? quxName).isNone && b.consts.size == 2 - && b.assumptions.isEmpty) ++ - (TestSeq.individualIO "EnvPack: bundle is a removals-only subset under diff" - none (do - match ← packFixture src "bar" #[] with - | .error e => pure (false, 0, 0, some e) - | .ok b => - match Ixon.rsDiffEnvs (serEnv! src) (serEnv! b) with - | .error e => pure (false, 0, 0, some s!"diff failed: {e}") - | .ok d => - let ok := d.mainChanged == some (none, some barAddr) - && d.namedRemoved.size == 1 - && d.namedAdded.isEmpty && d.namedChanged.isEmpty - && d.constsOnlyB.isEmpty && d.blobsOnlyB.isEmpty - let msg := s!"mainOk={d.mainChanged == some (none, some barAddr)} \ - removed={d.namedRemoved.map (·.1)} \ - added={d.namedAdded.map (·.1)} \ - changed={d.namedChanged.map (·.name)} \ - constsOnlyB={d.constsOnlyB.size} blobsOnlyB={d.blobsOnlyB.size}" - pure (ok, 0, 0, if ok then none else some msg)) .done) ++ + && b.assumptions.isEmpty) + it "EnvPack: bundle is a removals-only subset under diff" do + let b ← expectOk (← packFixture src "bar" #[]) + let d ← expectOk (Ixon.rsDiffEnvs (serEnv! src) (serEnv! b)) + let ok := d.mainChanged == some (none, some barAddr) + && d.namedRemoved.size == 1 + && d.namedAdded.isEmpty && d.namedChanged.isEmpty + && d.constsOnlyB.isEmpty && d.blobsOnlyB.isEmpty + let msg := s!"mainOk={d.mainChanged == some (none, some barAddr)} \ + removed={d.namedRemoved.map (·.1)} \ + added={d.namedAdded.map (·.1)} \ + changed={d.namedChanged.map (·.name)} \ + constsOnlyB={d.constsOnlyB.size} blobsOnlyB={d.blobsOnlyB.size}" + expect ok msg packTest "EnvPack: assume cut (by name) records assumption" (packFixture src "bar" #["foo"]) (fun b => b.main == some barAddr && (b.getAddr? fooName).isNone && b.consts.size == 1 && b.assumptions.size == 1 - && b.assumptions.contains fooAddr) ++ + && b.assumptions.contains fooAddr) packTest "EnvPack: assume cut (by hex address) records assumption" (packFixture src "bar" #[toString fooAddr]) (fun b => - b.consts.size == 1 && b.assumptions.contains fooAddr) ++ + b.consts.size == 1 && b.assumptions.contains fooAddr) packTest "EnvPack: anon bundle has no metadata, keeps the value pin" (packFixture src "bar" #[] (anon := true)) (fun b => b.main == some barAddr @@ -587,62 +566,62 @@ def envPackTests : TestSeq := -- The writer always emits the anonymous name as §4 entry 0. && b.names.size <= 1 && b.consts.size == 2 - && (b.getAddr? barName).isNone) ++ + && (b.getAddr? barName).isNone) packErrTest "EnvPack: unknown root name errors" - (packFixture src "nope" #[]) ++ + (packFixture src "nope" #[]) packErrTest "EnvPack: main cannot be assumed" (packFixture src "bar" #["bar"]) /-! ## Test Suite -/ -def suiteWith (cfg : SlimCheck.Configuration := {}) : List TestSeq := [ +set_option compiler.extract_closed false in +def suiteWith (cfg : LSpec.Prop.PropertyConfig := {}) : Spec := do -- Ixon type unit tests - ixonDefKindTests, - ixonDefinitionSafetyTests, - ixonQuotKindTests, - ixonUnivTests, - ixonExprTests, - exprMetaDataTests, - exprMetaArenaTests, - constantMetaTests, - rawEnvTests, + ixonDefKindTests + ixonDefinitionSafetyTests + ixonQuotKindTests + ixonUnivTests + ixonExprTests + exprMetaDataTests + exprMetaArenaTests + constantMetaTests + rawEnvTests -- Ixon property tests - recursive & composite types -- (finite enums `DefKind`, `DefinitionSafety`, `QuotKind` are exhaustively unit-tested above) - checkIO "Ixon.Univ roundtrip" (∀ x : Univ, roundtripIxonUniv x == x) .done cfg, - checkIO "Ixon.Expr roundtrip" (∀ x : Expr, roundtripIxonExpr x == x) .done cfg, - checkIO "Ixon.Definition roundtrip" (∀ x : Definition, roundtripIxonDefinition x == x) .done cfg, - checkIO "Ixon.RecursorRule roundtrip" (∀ x : RecursorRule, roundtripIxonRecursorRule x == x) .done cfg, - checkIO "Ixon.Recursor roundtrip" (∀ x : Recursor, roundtripIxonRecursor x == x) .done cfg, - checkIO "Ixon.Axiom roundtrip" (∀ x : Axiom, roundtripIxonAxiom x == x) .done cfg, - checkIO "Ixon.Quotient roundtrip" (∀ x : Quotient, roundtripIxonQuotient x == x) .done cfg, - checkIO "Ixon.Constructor roundtrip" (∀ x : Constructor, roundtripIxonConstructor x == x) .done cfg, - checkIO "Ixon.Inductive roundtrip" (∀ x : Inductive, roundtripIxonInductive x == x) .done cfg, - checkIO "Ixon.InductiveProj roundtrip" (∀ x : InductiveProj, roundtripIxonInductiveProj x == x) .done cfg, - checkIO "Ixon.ConstructorProj roundtrip" (∀ x : ConstructorProj, roundtripIxonConstructorProj x == x) .done cfg, - checkIO "Ixon.RecursorProj roundtrip" (∀ x : RecursorProj, roundtripIxonRecursorProj x == x) .done cfg, - checkIO "Ixon.DefinitionProj roundtrip" (∀ x : DefinitionProj, roundtripIxonDefinitionProj x == x) .done cfg, - checkIO "Ixon.MutConst roundtrip" (∀ x : MutConst, roundtripIxonMutConst x == x) .done cfg, - checkIO "Ixon.ConstantInfo roundtrip" (∀ x : ConstantInfo, roundtripIxonConstantInfo x == x) .done cfg, - checkIO "Ixon.Constant roundtrip" (∀ x : Constant, roundtripIxonConstant x == x) .done cfg, - checkIO "Ixon.DataValue roundtrip" (∀ x : DataValue, roundtripIxonDataValue x == x) .done cfg, - checkIO "Ixon.Comm roundtrip" (∀ x : Comm, roundtripIxonComm x == x) .done cfg, + propWith "Ixon.Univ roundtrip" cfg fun (x : Univ) => roundtripIxonUniv x == x + propWith "Ixon.Expr roundtrip" cfg fun (x : Expr) => roundtripIxonExpr x == x + propWith "Ixon.Definition roundtrip" cfg fun (x : Definition) => roundtripIxonDefinition x == x + propWith "Ixon.RecursorRule roundtrip" cfg fun (x : RecursorRule) => roundtripIxonRecursorRule x == x + propWith "Ixon.Recursor roundtrip" cfg fun (x : Recursor) => roundtripIxonRecursor x == x + propWith "Ixon.Axiom roundtrip" cfg fun (x : Axiom) => roundtripIxonAxiom x == x + propWith "Ixon.Quotient roundtrip" cfg fun (x : Quotient) => roundtripIxonQuotient x == x + propWith "Ixon.Constructor roundtrip" cfg fun (x : Constructor) => roundtripIxonConstructor x == x + propWith "Ixon.Inductive roundtrip" cfg fun (x : Inductive) => roundtripIxonInductive x == x + propWith "Ixon.InductiveProj roundtrip" cfg fun (x : InductiveProj) => roundtripIxonInductiveProj x == x + propWith "Ixon.ConstructorProj roundtrip" cfg fun (x : ConstructorProj) => roundtripIxonConstructorProj x == x + propWith "Ixon.RecursorProj roundtrip" cfg fun (x : RecursorProj) => roundtripIxonRecursorProj x == x + propWith "Ixon.DefinitionProj roundtrip" cfg fun (x : DefinitionProj) => roundtripIxonDefinitionProj x == x + propWith "Ixon.MutConst roundtrip" cfg fun (x : MutConst) => roundtripIxonMutConst x == x + propWith "Ixon.ConstantInfo roundtrip" cfg fun (x : ConstantInfo) => roundtripIxonConstantInfo x == x + propWith "Ixon.Constant roundtrip" cfg fun (x : Constant) => roundtripIxonConstant x == x + propWith "Ixon.DataValue roundtrip" cfg fun (x : DataValue) => roundtripIxonDataValue x == x + propWith "Ixon.Comm roundtrip" cfg fun (x : Comm) => roundtripIxonComm x == x -- Metadata types (arena-based) - checkIO "Ixon.ExprMetaData roundtrip" (∀ x : ExprMetaData, roundtripIxonExprMetaData x == x) .done cfg, - checkIO "Ixon.ConstantMeta roundtrip" (∀ x : ConstantMeta, roundtripIxonConstantMeta x == x) .done cfg, - checkIO "Ixon.Named roundtrip" (∀ x : Named, roundtripIxonNamed x == x) .done cfg, + propWith "Ixon.ExprMetaData roundtrip" cfg fun (x : ExprMetaData) => roundtripIxonExprMetaData x == x + propWith "Ixon.ConstantMeta roundtrip" cfg fun (x : ConstantMeta) => roundtripIxonConstantMeta x == x + propWith "Ixon.Named roundtrip" cfg fun (x : Named) => roundtripIxonNamed x == x ---- RawEnv roundtrip - checkIO "Ixon.RawEnv roundtrip" (∀ env : RawEnv, rawEnvEq (roundtripRawEnv env) env) .done cfg, + propWith "Ixon.RawEnv roundtrip" cfg fun (env : RawEnv) => rawEnvEq (roundtripRawEnv env) env ---- Env diff - envDiffTests, - checkIO "Ixon.EnvDiff self-diff empty (anon)" - (∀ env : RawEnv, selfDiffEmpty false env) .done cfg, - checkIO "Ixon.EnvDiff self-diff empty (meta)" - (∀ env : RawEnv, selfDiffEmpty true env) .done cfg, + envDiffTests + propWith "Ixon.EnvDiff self-diff empty (anon)" cfg fun (env : RawEnv) => + selfDiffEmpty false env + propWith "Ixon.EnvDiff self-diff empty (meta)" cfg fun (env : RawEnv) => + selfDiffEmpty true env ---- Env pack - envPackTests, -] + envPackTests -def suite : List TestSeq := suiteWith {} +def suite : Spec := suiteWith {} end Tests.FFI.Ixon diff --git a/Tests/FFI/Lifecycle.lean b/Tests/FFI/Lifecycle.lean index d7b124138e..a2b50a27f2 100644 --- a/Tests/FFI/Lifecycle.lean +++ b/Tests/FFI/Lifecycle.lean @@ -12,7 +12,7 @@ public import Ix.Ixon public import Tests.Gen.Ixon public import Tests.FFI.Ixon -open LSpec SlimCheck Gen Ixon +open LSpec LSpec.Prop Gen Ixon open Tests.Gen.Ixon open Tests.FFI.Ixon (rawEnvEq) @@ -21,121 +21,114 @@ namespace Tests.FFI.Lifecycle /-! ## Keccak external object lifecycle tests -/ /-- Basic hash lifecycle: init → update → finalize -/ -def keccakBasicTests : TestSeq := +def keccakBasicTests : LSpec.Spec := do -- Known test vector: SHA3-256 of [0] let input : ByteArray := ⟨#[0]⟩ let expected : ByteArray := ⟨#[ 188, 54, 120, 158, 122, 30, 40, 20, 54, 70, 66, 41, 130, 143, 129, 125, 102, 18, 247, 180, 119, 214, 101, 145, 255, 150, 169, 224, 100, 188, 201, 138 ]⟩ - let result := Keccak.hash input - test "Keccak basic hash [0]" (result == expected) ++ + itBool "Keccak basic hash [0]" (Keccak.hash input == expected) -- Empty input - let emptyResult := Keccak.hash ByteArray.empty - test "Keccak empty input produces 32 bytes" (emptyResult.size == 32) ++ + itBool "Keccak empty input produces 32 bytes" ((Keccak.hash ByteArray.empty).size == 32) -- Determinism: same input twice - let result2 := Keccak.hash input - test "Keccak deterministic" (result == result2) + itBool "Keccak deterministic" (Keccak.hash input == Keccak.hash input) /-- Multi-update lifecycle: init → update × N → finalize Creates N+1 external Hasher objects, exercising the destructor path. -/ -def keccakMultiUpdateTests : TestSeq := +def keccakMultiUpdateTests : LSpec.Spec := do -- Multi-update should produce same result as single update of concatenated input let chunk1 : ByteArray := ⟨#[1, 2, 3]⟩ let chunk2 : ByteArray := ⟨#[4, 5, 6]⟩ let chunk3 : ByteArray := ⟨#[7, 8, 9]⟩ let combined : ByteArray := ⟨#[1, 2, 3, 4, 5, 6, 7, 8, 9]⟩ - let singleHash := Keccak.hash combined - let multiHash := - let h := Keccak.Hasher.init () - let h := h.update chunk1 - let h := h.update chunk2 - let h := h.update chunk3 - h.finalize - test "Keccak multi-update == single" (singleHash == multiHash) ++ + itBool "Keccak multi-update == single" ( + let singleHash := Keccak.hash combined + let multiHash := + let h := Keccak.Hasher.init () + let h := h.update chunk1 + let h := h.update chunk2 + let h := h.update chunk3 + h.finalize + singleHash == multiHash) -- Many updates to stress the external object destructor - let manyHash := Id.run do - let mut h := Keccak.Hasher.init () - for i in [:20] do - h := h.update ⟨#[i.toUInt8]⟩ - return h.finalize - test "Keccak 20 updates produces 32 bytes" (manyHash.size == 32) + itBool "Keccak 20 updates produces 32 bytes" ( + let manyHash := Id.run do + let mut h := Keccak.Hasher.init () + for i in [:20] do + h := h.update ⟨#[i.toUInt8]⟩ + return h.finalize + manyHash.size == 32) /-- Large input to exercise large ByteArray across FFI boundary -/ -def keccakLargeInputTests : TestSeq := +def keccakLargeInputTests : LSpec.Spec := do let large : ByteArray := ⟨Array.range 4096 |>.map Nat.toUInt8⟩ - let result := Keccak.hash large - test "Keccak large input (4096 bytes)" (result.size == 32) ++ + itBool "Keccak large input (4096 bytes)" ((Keccak.hash large).size == 32) -- Verify determinism on large input - let result2 := Keccak.hash large - test "Keccak large input deterministic" (result == result2) + itBool "Keccak large input deterministic" (Keccak.hash large == Keccak.hash large) /-! ## Blake3 external object lifecycle tests -/ /-- Basic hash lifecycle against the official BLAKE3 empty-input test vector. -/ -def blake3BasicTests : TestSeq := +def blake3BasicTests : LSpec.Spec := do -- Official BLAKE3 vector: blake3("") = af1349b9f5f9a1a6…cae41f3262. let expected : ByteArray := ⟨#[ 175, 19, 73, 185, 245, 249, 161, 166, 160, 64, 77, 234, 54, 220, 201, 73, 155, 203, 37, 201, 173, 193, 18, 183, 204, 154, 147, 202, 228, 31, 50, 98 ]⟩ - let emptyResult := (Blake3.Rust.hash ByteArray.empty).val - test "Blake3 empty matches official vector" (emptyResult == expected) ++ - test "Blake3 empty produces 32 bytes" (emptyResult.size == 32) ++ + itBool "Blake3 empty matches official vector" ((Blake3.Rust.hash ByteArray.empty).val == expected) + itBool "Blake3 empty produces 32 bytes" ((Blake3.Rust.hash ByteArray.empty).val.size == 32) -- Determinism: same input twice. let input : ByteArray := ⟨#[1, 2, 3]⟩ - test "Blake3 deterministic" ((Blake3.Rust.hash input).val == (Blake3.Rust.hash input).val) + itBool "Blake3 deterministic" ((Blake3.Rust.hash input).val == (Blake3.Rust.hash input).val) /-- Multi-update lifecycle: init → update × N → finalize. Creates N+1 external `Hasher` objects (exercising the destructor path); must equal the one-shot hash. -/ -def blake3MultiUpdateTests : TestSeq := +def blake3MultiUpdateTests : LSpec.Spec := do let combined : ByteArray := ⟨#[1, 2, 3, 4, 5, 6, 7, 8, 9]⟩ - let singleHash := (Blake3.Rust.hash combined).val - let multiHash := Id.run do - let mut h := Blake3.Rust.Hasher.init () - h := h.update ⟨#[1, 2, 3]⟩ - h := h.update ⟨#[4, 5, 6]⟩ - h := h.update ⟨#[7, 8, 9]⟩ - return (h.finalizeWithLength 32).val - test "Blake3 multi-update == single" (singleHash == multiHash) ++ + itBool "Blake3 multi-update == single" ( + let singleHash := (Blake3.Rust.hash combined).val + let multiHash := Id.run do + let mut h := Blake3.Rust.Hasher.init () + h := h.update ⟨#[1, 2, 3]⟩ + h := h.update ⟨#[4, 5, 6]⟩ + h := h.update ⟨#[7, 8, 9]⟩ + return (h.finalizeWithLength 32).val + singleHash == multiHash) -- Many updates to stress the external object destructor. - let manyHash := Id.run do - let mut h := Blake3.Rust.Hasher.init () - for i in [:20] do - h := h.update ⟨#[i.toUInt8]⟩ - return (h.finalizeWithLength 32).val - let manyExpected := (Blake3.Rust.hash ⟨Array.range 20 |>.map Nat.toUInt8⟩).val - test "Blake3 many-update == single" (manyHash == manyExpected) + itBool "Blake3 many-update == single" ( + let manyHash := Id.run do + let mut h := Blake3.Rust.Hasher.init () + for i in [:20] do + h := h.update ⟨#[i.toUInt8]⟩ + return (h.finalizeWithLength 32).val + let manyExpected := (Blake3.Rust.hash ⟨Array.range 20 |>.map Nat.toUInt8⟩).val + manyHash == manyExpected) /-- Large-input determinism, mirroring the Keccak large-input test. -/ -def blake3LargeInputTests : TestSeq := +def blake3LargeInputTests : LSpec.Spec := do let large : ByteArray := ⟨Array.range 4096 |>.map Nat.toUInt8⟩ - let result := (Blake3.Rust.hash large).val - test "Blake3 large input (4096 bytes)" (result.size == 32) ++ - test "Blake3 large input deterministic" (result == (Blake3.Rust.hash large).val) + itBool "Blake3 large input (4096 bytes)" ((Blake3.Rust.hash large).val.size == 32) + itBool "Blake3 large input deterministic" ((Blake3.Rust.hash large).val == (Blake3.Rust.hash large).val) /-! ## SHA256 hashing tests -/ -def sha256Tests : TestSeq := +def sha256Tests : LSpec.Spec := do -- Empty input: SHA-256("") = e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 - let emptyHash := Sha256.hash ByteArray.empty let expectedEmpty : ByteArray := ⟨#[ 0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4, 0xc8, 0x99, 0x6f, 0xb9, 0x24, 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c, 0xa4, 0x95, 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55 ]⟩ - test "SHA256 empty" (emptyHash == expectedEmpty) ++ + itBool "SHA256 empty" (Sha256.hash ByteArray.empty == expectedEmpty) -- "abc": SHA-256("abc") = ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad - let abcHash := Sha256.hash ⟨#[0x61, 0x62, 0x63]⟩ let expectedAbc : ByteArray := ⟨#[ 0xba, 0x78, 0x16, 0xbf, 0x8f, 0x01, 0xcf, 0xea, 0x41, 0x41, 0x40, 0xde, 0x5d, 0xae, 0x22, 0x23, 0xb0, 0x03, 0x61, 0xa3, 0x96, 0x17, 0x7a, 0x9c, 0xb4, 0x10, 0xff, 0x61, 0xf2, 0x00, 0x15, 0xad ]⟩ - test "SHA256 abc" (abcHash == expectedAbc) ++ + itBool "SHA256 abc" (Sha256.hash ⟨#[0x61, 0x62, 0x63]⟩ == expectedAbc) -- Determinism: hash same input twice - let hash1 := Sha256.hash ⟨#[1, 2, 3]⟩ - let hash2 := Sha256.hash ⟨#[1, 2, 3]⟩ - test "SHA256 deterministic" (hash1 == hash2) ++ - test "SHA256 produces 32 bytes" (hash1.size == 32) + itBool "SHA256 deterministic" (Sha256.hash ⟨#[1, 2, 3]⟩ == Sha256.hash ⟨#[1, 2, 3]⟩) + itBool "SHA256 produces 32 bytes" ((Sha256.hash ⟨#[1, 2, 3]⟩).size == 32) /-! ## Ixon serialization roundtrip tests (ser_env → de_env) -/ @@ -153,34 +146,15 @@ private def serdeEnvEq (a b : RawEnv) : Bool := rc.const.refs.size == rc'.const.refs.size && rc.const.univs.size == rc'.const.univs.size -/-- Wrap a pure computation in an IO action that only executes when the - IO value is run — not when it is constructed. Lean normally evaluates - pure `let` bindings strictly even inside `do` blocks, so `rsSerEnvFFI` - would otherwise fire at `TestSeq` construction time. Placing the - computation inside `fun s => ...` puts it under a lambda, which Lean - does not evaluate until the outer closure is applied — i.e., until the - IO action actually runs. See `EST.pure`/`EST.bind` in - `refs/lean4/src/Init/System/ST.lean`; this is hand-rolled `pure` that - cannot accidentally beta-reduce eagerly. -/ -@[inline] private def deferIO (f : Unit → α) : IO α := fun s => - EST.Out.ok (f ()) s - /-- Build a single serde roundtrip test that defers all FFI calls to - execution time. Constructing the returned `TestSeq` does no FFI work — - the `rsSerEnvFFI` / `rsDeEnvFFI` pair fires only when LSpec actually - runs the test. -/ -private def mkSerdeRoundtripTest (descr : String) (env : RawEnv) : TestSeq := - .individualIO descr none (deferIO fun () => - match rsSerEnvFFI env >>= rsDeEnvFFI with - | .ok decoded => - let ok := serdeEnvEq decoded env - (ok, 0, 0, if ok then none else some "mismatch") - | .error e => - (false, 0, 0, some s!"serialization/deserialization failed: {e}")) .done + execution time via `it`. -/ +private def mkSerdeRoundtripTest (descr : String) (env : RawEnv) : Spec := + it descr do + let decoded ← expectOk (rsSerEnvFFI env >>= rsDeEnvFFI) + expect (serdeEnvEq decoded env) "mismatch" -def serdeTests : TestSeq := - -- Empty RawEnv. Only data construction happens eagerly; FFI is deferred - -- inside `mkSerdeRoundtripTest`. +def serdeTests : LSpec.Spec := do + -- Empty RawEnv. FFI is deferred inside `mkSerdeRoundtripTest`. let empty : RawEnv := { consts := #[], named := #[], blobs := #[], comms := #[] } -- RawEnv with data. Consts AND blobs must be content-addressed — the -- Rust loader verifies `Address::hash(bytes) == addr` per entry for @@ -215,7 +189,7 @@ def serdeTests : TestSeq := comms := #[testRawComm], names := #[testNameEntry, testConstNameEntry] } - mkSerdeRoundtripTest "serde empty RawEnv" empty ++ + mkSerdeRoundtripTest "serde empty RawEnv" empty mkSerdeRoundtripTest "serde RawEnv with data" withData /-- Generate a ConstantInfo without embedded Address fields. @@ -234,19 +208,19 @@ private def genSimpleConstantInfo : Gen ConstantInfo := name table; random RawEnvs almost always violate this. -/ private def genSerdeRawEnv : Gen RawEnv := do -- Build a pool of (address, name) pairs; all addresses used below come from here - let poolSize ← Gen.choose Nat 2 8 + let poolSize ← Gen.chooseNat 2 8 let mut pool : Array (Address × Ix.Name) := #[] for i in [:poolSize] do let addr ← genAddress pool := pool.push (addr, Ix.Name.mkNat Ix.Name.mkAnon i) let pickAddr : Gen Address := do - let idx ← Gen.choose Nat 0 (pool.size - 1) + let idx ← Gen.chooseNat 0 (pool.size - 1) pure pool[idx]!.1 -- Consts: derive addr from content (`Env::get` verifies -- `Address::hash(bytes) == addr` on load). Each canonical address -- gets its own name entry appended to the names table so the serde -- pipeline can resolve it. - let numConsts ← Gen.choose Nat 0 3 + let numConsts ← Gen.chooseNat 0 3 let mut consts : Array RawConst := #[] let mut constNames : Array RawNameEntry := #[] for i in [:numConsts] do @@ -262,23 +236,23 @@ private def genSerdeRawEnv : Gen RawEnv := do -- Named: pool names over stored const addresses with empty metadata — -- §5 keys each entry's constant by §2 rank, so the writers reject -- named entries referencing anything outside `consts`. - let numNamed ← Gen.choose Nat 0 3 + let numNamed ← Gen.chooseNat 0 3 let mut named : Array RawNamed := #[] if consts.size > 0 then for _ in [:numNamed] do - let idx ← Gen.choose Nat 0 (pool.size - 1) + let idx ← Gen.chooseNat 0 (pool.size - 1) let (_, name) := pool[idx]! - let cidx ← Gen.choose Nat 0 (consts.size - 1) + let cidx ← Gen.chooseNat 0 (consts.size - 1) named := named.push { name, addr := (consts[cidx]!).addr, constMeta := .empty } -- Blobs: content-addressed (the loaders verify blake3(bytes) == addr) - let numBlobs ← Gen.choose Nat 0 3 + let numBlobs ← Gen.chooseNat 0 3 let mut blobs : Array RawBlob := #[] for _ in [:numBlobs] do let bytes ← Tests.Gen.Ixon.genByteArray blobs := blobs.push { addr := Address.blake3 bytes, bytes } -- Comms: pool addresses - let numComms ← Gen.choose Nat 0 2 + let numComms ← Gen.chooseNat 0 2 let mut comms : Array RawComm := #[] for _ in [:numComms] do let addr ← pickAddr @@ -296,7 +270,7 @@ private def genSerdeRawEnv : Gen RawEnv := do if acc.any (·.addr == x.addr) then acc else acc.push x pure { consts := consts', named := named', blobs := blobs', comms := comms', names } -/-- Wrapper so we can give well-formed RawEnvs their own SampleableExt instance. -/ +/-- Wrapper so we can give well-formed RawEnvs their own Sampleable instance. -/ private structure serdeRawEnv where env : RawEnv @@ -306,8 +280,8 @@ private instance : Repr serdeRawEnv where private instance : Shrinkable serdeRawEnv where shrink _ := [] -private instance : SampleableExt serdeRawEnv := - SampleableExt.mkSelfContained (serdeRawEnv.mk <$> genSerdeRawEnv) +private instance : Sampleable serdeRawEnv := + ⟨serdeRawEnv.mk <$> genSerdeRawEnv⟩ /-- Check that serialize → deserialize roundtrips for a well-formed RawEnv. -/ def serdeRoundtripOk (env : RawEnv) : Bool := @@ -315,24 +289,25 @@ def serdeRoundtripOk (env : RawEnv) : Bool := | .ok decoded => serdeEnvEq decoded env | .error _ => false +set_option compiler.extract_closed false in /-- Property test: random well-formed RawEnv → serialize → deserialize → compare -/ -def serdePropertyTest (cfg : SlimCheck.Configuration := {}) : TestSeq := - checkIO "serde RawEnv roundtrip" (∀ e : serdeRawEnv, serdeRoundtripOk e.env) .done cfg +def serdePropertyTest (cfg : LSpec.Prop.PropertyConfig := {}) : Spec := + propWith "serde RawEnv roundtrip" cfg fun (e : serdeRawEnv) => serdeRoundtripOk e.env /-! ## Test Suite -/ -public def suiteWith (cfg : SlimCheck.Configuration := {}) : List TestSeq := [ - keccakBasicTests, - keccakMultiUpdateTests, - keccakLargeInputTests, - blake3BasicTests, - blake3MultiUpdateTests, - blake3LargeInputTests, - sha256Tests, - serdeTests, - serdePropertyTest cfg, -] +set_option compiler.extract_closed false in +public def suiteWith (cfg : LSpec.Prop.PropertyConfig := {}) : Spec := do + keccakBasicTests + keccakMultiUpdateTests + keccakLargeInputTests + blake3BasicTests + blake3MultiUpdateTests + blake3LargeInputTests + sha256Tests + serdeTests + serdePropertyTest cfg -public def suite : List TestSeq := suiteWith {} +public def suite : Spec := suiteWith {} end Tests.FFI.Lifecycle diff --git a/Tests/FFI/Refcount.lean b/Tests/FFI/Refcount.lean index 256a3ecd3c..f5fd4ff10b 100644 --- a/Tests/FFI/Refcount.lean +++ b/Tests/FFI/Refcount.lean @@ -22,7 +22,7 @@ public import Tests.Gen.Ix public import Ix.Environment public import Ix.Address -open LSpec SlimCheck Gen +open LSpec LSpec.Prop Gen open Tests.Gen.Ix namespace Tests.FFI.Refcount @@ -88,123 +88,125 @@ private def persistentName : Ix.Name := Ix.Name.mkStr Ix.Name.mkAnon "persistent Verifies that to_owned_ref (lean_inc) produces a valid owned handle. A refcount bug here would manifest as use-after-free or double-free. -/ -def borrowToOwnedTests : TestSeq := - test "borrow→owned Name anonymous" (borrowToOwnedName testAnon == testAnon) ++ - test "borrow→owned Name str" (borrowToOwnedName testStr == testStr) ++ - test "borrow→owned Name num" (borrowToOwnedName testNum == testNum) +def borrowToOwnedTests : LSpec.Spec := do + itBool "borrow→owned Name anonymous" (borrowToOwnedName testAnon == testAnon) + itBool "borrow→owned Name str" (borrowToOwnedName testStr == testStr) + itBool "borrow→owned Name num" (borrowToOwnedName testNum == testNum) /-! ## Multiple borrows from same object Verifies that reading fields multiple times from the same borrowed ctor doesn't corrupt data (no dangling pointer from intermediate borrow). -/ -def multiBorrowTests : TestSeq := +def multiBorrowTests : LSpec.Spec := do let name := Ix.Name.mkStr Ix.Name.mkAnon "hello" - test "multi-borrow Name str" (multiBorrowName name == "hello|hello") + itBool "multi-borrow Name str" (multiBorrowName name == "hello|hello") /-! ## Owned drop tests Passes owned (NOT @&) arrays. Rust drops each element on scope exit. A missing drop leaks; an extra drop crashes. -/ -def ownedDropTests : TestSeq := +def ownedDropTests : LSpec.Spec := do let names := #[testAnon, testStr, testNum] - test "owned array drop 3 names" (ownedArrayDrop names == 3) ++ - test "owned array drop empty" (ownedArrayDrop #[] == 0) + itBool "owned array drop 3 names" (ownedArrayDrop names == 3) + itBool "owned array drop empty" (ownedArrayDrop #[] == 0) /-! ## Clone tests Makes two owned clones of a borrowed Name, decodes both. After decode, both clones are dropped → two lean_dec_ref calls. Would double-free if clone didn't lean_inc. -/ -def cloneTests : TestSeq := - test "clone anonymous" (cloneAndCompare testAnon == 1) ++ - test "clone str name" (cloneAndCompare testStr == 1) ++ - test "clone num name" (cloneAndCompare testNum == 1) +def cloneTests : LSpec.Spec := do + itBool "clone anonymous" (cloneAndCompare testAnon == 1) + itBool "clone str name" (cloneAndCompare testStr == 1) + itBool "clone num name" (cloneAndCompare testNum == 1) /-! ## Roundtrip loop tests Each iteration: decode borrowed → build new owned → drop old → repeat. Stresses N alloc/dealloc cycles. Would crash on any refcount error. -/ -def roundtripLoopTests : TestSeq := - test "roundtrip loop 1x" (roundtripLoop testStr 1 == testStr) ++ - test "roundtrip loop 5x" (roundtripLoop testStr 5 == testStr) ++ - test "roundtrip loop 20x" (roundtripLoop testStr 20 == testStr) ++ - test "roundtrip loop anon 10x" (roundtripLoop testAnon 10 == testAnon) ++ - test "roundtrip loop num 10x" (roundtripLoop testNum 10 == testNum) +def roundtripLoopTests : LSpec.Spec := do + itBool "roundtrip loop 1x" (roundtripLoop testStr 1 == testStr) + itBool "roundtrip loop 5x" (roundtripLoop testStr 5 == testStr) + itBool "roundtrip loop 20x" (roundtripLoop testStr 20 == testStr) + itBool "roundtrip loop anon 10x" (roundtripLoop testAnon 10 == testAnon) + itBool "roundtrip loop num 10x" (roundtripLoop testNum 10 == testNum) /-! ## Persistent object tests Module-level defs have m_rc == 0. Refcount ops are no-ops. Verifies that the typed API handles these correctly. -/ -def persistentTests : TestSeq := - test "persistent name is_persistent" (isPersistent persistentName == 1) ++ - test "persistent roundtrip" (persistentRoundtrip persistentName == persistentName) +def persistentTests : LSpec.Spec := do + itBool "persistent name is_persistent" (isPersistent persistentName == 1) + itBool "persistent roundtrip" (persistentRoundtrip persistentName == persistentName) /-! ## Cache dedup tests Builds N copies of the same Name via LeanBuildCache, which clones cached entries (incrementing refcount). Dropping the array decrements each copy. Would crash if clone refcount was wrong. -/ -def cacheDedupTests : TestSeq := - let duped := cacheDedup testStr 5 - test "cache dedup size 5" (duped.size == 5) ++ - test "cache dedup all equal" (duped.all (· == testStr)) ++ - let duped20 := cacheDedup testNum 20 - test "cache dedup size 20" (duped20.size == 20 && duped20.all (· == testNum)) +def cacheDedupTests : LSpec.Spec := do + itBool "cache dedup size 5" ((cacheDedup testStr 5).size == 5) + itBool "cache dedup all equal" ((cacheDedup testStr 5).all (· == testStr)) + itBool "cache dedup size 20" ( + let duped20 := cacheDedup testNum 20 + duped20.size == 20 && duped20.all (· == testNum)) /-! ## String lifecycle tests -/ -def stringTests : TestSeq := - test "string lifecycle" (stringLifecycle "hello" == "olleh") ++ - test "string lifecycle empty" (stringLifecycle "" == "") ++ - test "string lifecycle unicode" (stringLifecycle "café" == "éfac") +def stringTests : LSpec.Spec := do + itBool "string lifecycle" (stringLifecycle "hello" == "olleh") + itBool "string lifecycle empty" (stringLifecycle "" == "") + itBool "string lifecycle unicode" (stringLifecycle "café" == "éfac") /-! ## Alloc/drop stress tests Builds and immediately drops N Lean objects in a loop. Under `IX_VALGRIND=1`, cap at 100x to skip the redundant 1000x loop. -/ -def allocDropTests (valgrind : Bool := false) : TestSeq := - let base := test "alloc/drop 100x" (allocDropLoop testStr 100 == testStr) - if valgrind then base - else base ++ test "alloc/drop 1000x" (allocDropLoop testNum 1000 == testNum) +set_option compiler.extract_closed false in +def allocDropTests (valgrind : Bool := false) : Spec := do + itBool "alloc/drop 100x" (allocDropLoop testStr 100 == testStr) + unless valgrind do + itBool "alloc/drop 1000x" (allocDropLoop testNum 1000 == testNum) /-! ## Multi-threaded LeanShared tests These exercise lean_mark_mt + atomic refcounting on ix domain types across real OS threads. A refcount bug would cause SIGSEGV or assertion failure. -/ -def mtTests : TestSeq := +def mtTests : LSpec.Spec := do let names := #[testAnon, testStr, testNum] -- Parallel decode: N threads × 3 names each - test "MT parallel decode names 4 threads" (mtParallelDecodeNames names 4 == 12) ++ - test "MT parallel decode names 1 thread" (mtParallelDecodeNames names 1 == 3) ++ - test "MT parallel decode names empty" (mtParallelDecodeNames #[] 4 == 0) ++ + itBool "MT parallel decode names 4 threads" (mtParallelDecodeNames names 4 == 12) + itBool "MT parallel decode names 1 thread" (mtParallelDecodeNames names 1 == 3) + itBool "MT parallel decode names empty" (mtParallelDecodeNames #[] 4 == 0) -- Parallel roundtrip: decode and rebuild from multiple threads - test "MT parallel roundtrip names" (mtParallelRoundtripNames names 4 == names) ++ - test "MT parallel roundtrip empty" (mtParallelRoundtripNames #[] 4 == #[]) + itBool "MT parallel roundtrip names" (mtParallelRoundtripNames names 4 == names) + itBool "MT parallel roundtrip empty" (mtParallelRoundtripNames #[] 4 == #[]) /-! ## Property tests -/ -def propertyTests (cfg : SlimCheck.Configuration := {}) : TestSeq := - checkIO "borrow→owned Name" (∀ n : Ix.Name, borrowToOwnedName n == n) .done cfg ++ - checkIO "clone always equal" (∀ n : Ix.Name, cloneAndCompare n == 1) .done cfg ++ - checkIO "roundtrip loop 3x" (∀ n : Ix.Name, roundtripLoop n 3 == n) .done cfg +set_option compiler.extract_closed false in +def propertyTests (cfg : LSpec.Prop.PropertyConfig := {}) : Spec := do + propWith "borrow→owned Name" cfg fun (n : Ix.Name) => borrowToOwnedName n == n + propWith "clone always equal" cfg fun (n : Ix.Name) => cloneAndCompare n == 1 + propWith "roundtrip loop 3x" cfg fun (n : Ix.Name) => roundtripLoop n 3 == n /-! ## Test Suite -/ -public def suiteWith (cfg : SlimCheck.Configuration := {}) (valgrind : Bool := false) : - List TestSeq := [ - borrowToOwnedTests, - multiBorrowTests, - ownedDropTests, - cloneTests, - roundtripLoopTests, - persistentTests, - cacheDedupTests, - stringTests, - allocDropTests valgrind, - mtTests, - propertyTests cfg, -] - -public def suite : List TestSeq := suiteWith {} false +set_option compiler.extract_closed false in +public def suiteWith (cfg : LSpec.Prop.PropertyConfig := {}) (valgrind : Bool := false) : + Spec := do + borrowToOwnedTests + multiBorrowTests + ownedDropTests + cloneTests + roundtripLoopTests + persistentTests + cacheDedupTests + stringTests + allocDropTests valgrind + mtTests + propertyTests cfg + +public def suite : Spec := suiteWith {} false end Tests.FFI.Refcount diff --git a/Tests/FFIMain.lean b/Tests/FFIMain.lean index 160d3a662b..d6ce59a797 100644 --- a/Tests/FFIMain.lean +++ b/Tests/FFIMain.lean @@ -7,7 +7,7 @@ the merge queue's Valgrind job builds and runs the Rust FFI boundary without the rest of `IxTests`, whose import closure holds the certification's proofs. -/ -def main (_args : List String) : IO UInt32 := do +def main (args : List String) : IO UInt32 := do let valgrind := (← IO.getEnv "IX_VALGRIND") == some "1" - let cfg : SlimCheck.Configuration := if valgrind then { numInst := 8 } else {} - LSpec.lspecIO (.ofList [("ffi", Tests.FFI.suiteWith cfg valgrind)]) [] + let cfg : LSpec.Prop.PropertyConfig := if valgrind then { numTests := 8 } else {} + LSpec.lspecMain (LSpec.describe "ffi" (Tests.FFI.suiteWith cfg valgrind)) args diff --git a/Tests/Fixtures/MultiStark/claims.json b/Tests/Fixtures/MultiStark/claims.json index 780a7559f4..703abe9415 100644 --- a/Tests/Fixtures/MultiStark/claims.json +++ b/Tests/Fixtures/MultiStark/claims.json @@ -18,10 +18,10 @@ "num_messages": 0, "num_queries": 77, "num_shards": 1, - "proof_bytes_len": 33091, - "proof_digest": "5f5a451ebef5246bf7fc964244dac1de9ae588b9412264df1eac837efba94f9e", + "proof_bytes_len": 32715, + "proof_digest": "a8e38f4a36dc925de255e628810f75f937b9c13adf1d010381afbd77bd9cabc6", "proof_of_work_bits": 10, "query_proof_of_work_bits": 10, - "system_bytes_len": 355, - "vk_digest": "0f5391dbf272a26e0f3b4269c94254abe431c6c205923797ac8f0c76aa45cf72" + "system_bytes_len": 357, + "vk_digest": "3985ae0ec5637c570a395bf768550756866eee4b667c19a3480f391aac5015d8" } diff --git a/Tests/Fixtures/MultiStark/memseg_two_shard/claims.json b/Tests/Fixtures/MultiStark/memseg_two_shard/claims.json index 5e726f147f..6fba7d4590 100644 --- a/Tests/Fixtures/MultiStark/memseg_two_shard/claims.json +++ b/Tests/Fixtures/MultiStark/memseg_two_shard/claims.json @@ -12,10 +12,10 @@ "num_messages": 2, "num_queries": 77, "num_shards": 2, - "proof_bytes_len": 37126, - "proof_digest": "291763cce8cc8f58f3fb168b2188baf77c1f479fb964a15c663833bb19ea56c2", + "proof_bytes_len": 37662, + "proof_digest": "031b36275ddbb76be9182a21f4afc67e1208f232c96133f183d62064183549c3", "proof_of_work_bits": 10, "query_proof_of_work_bits": 10, - "system_bytes_len": 146, - "vk_digest": "af6ff0c7f707641ece1301acd188bdb29485daf6cc4c8d237ec1677273dde22c" + "system_bytes_len": 148, + "vk_digest": "56b51ea7adf74d84ed43e00088b444a78eb7db84747ea738abfaf86b9c825365" } diff --git a/Tests/Fixtures/MultiStark/memseg_two_shard/proof.bin b/Tests/Fixtures/MultiStark/memseg_two_shard/proof.bin index 2f6cbbb2e7..1bf83ed366 100644 Binary files a/Tests/Fixtures/MultiStark/memseg_two_shard/proof.bin and b/Tests/Fixtures/MultiStark/memseg_two_shard/proof.bin differ diff --git a/Tests/Fixtures/MultiStark/memseg_two_shard/system.bin b/Tests/Fixtures/MultiStark/memseg_two_shard/system.bin index 77bc40c57f..c18e180464 100644 Binary files a/Tests/Fixtures/MultiStark/memseg_two_shard/system.bin and b/Tests/Fixtures/MultiStark/memseg_two_shard/system.bin differ diff --git a/Tests/Fixtures/MultiStark/prep_first/claims.json b/Tests/Fixtures/MultiStark/prep_first/claims.json index 8ab301fde3..22775ca821 100644 --- a/Tests/Fixtures/MultiStark/prep_first/claims.json +++ b/Tests/Fixtures/MultiStark/prep_first/claims.json @@ -18,10 +18,10 @@ "num_messages": 0, "num_queries": 77, "num_shards": 1, - "proof_bytes_len": 33059, - "proof_digest": "29c2e2b28063f63ecd484f0b98466cb94e0a0574a4e00832c9acf495d4bb814b", + "proof_bytes_len": 33035, + "proof_digest": "b8ea5a8cc4fa5b394a0fbeeee1b0074f867036e106ec190ef7dd4df235d98d50", "proof_of_work_bits": 10, "query_proof_of_work_bits": 10, - "system_bytes_len": 355, - "vk_digest": "fe8ea46376581acd48e9226a70d0c0609d9d7027228d78ab80d93c85e09745d6" + "system_bytes_len": 357, + "vk_digest": "f50ceb7623afa1543d4dde6b8e4f95c90af00c1f64a5e6bcf10fc3ec98409116" } diff --git a/Tests/Fixtures/MultiStark/prep_first/logdeg_0/proof.bin b/Tests/Fixtures/MultiStark/prep_first/logdeg_0/proof.bin index 03d82e36b0..23fd393feb 100644 Binary files a/Tests/Fixtures/MultiStark/prep_first/logdeg_0/proof.bin and b/Tests/Fixtures/MultiStark/prep_first/logdeg_0/proof.bin differ diff --git a/Tests/Fixtures/MultiStark/prep_first/logdeg_1/proof.bin b/Tests/Fixtures/MultiStark/prep_first/logdeg_1/proof.bin index cb5858d024..3983edc014 100644 Binary files a/Tests/Fixtures/MultiStark/prep_first/logdeg_1/proof.bin and b/Tests/Fixtures/MultiStark/prep_first/logdeg_1/proof.bin differ diff --git a/Tests/Fixtures/MultiStark/prep_first/logdeg_3/proof.bin b/Tests/Fixtures/MultiStark/prep_first/logdeg_3/proof.bin index 4366aef93e..a00eae7f1e 100644 Binary files a/Tests/Fixtures/MultiStark/prep_first/logdeg_3/proof.bin and b/Tests/Fixtures/MultiStark/prep_first/logdeg_3/proof.bin differ diff --git a/Tests/Fixtures/MultiStark/prep_first/logdeg_4/proof.bin b/Tests/Fixtures/MultiStark/prep_first/logdeg_4/proof.bin index 0bcd5c9476..2c9881465e 100644 Binary files a/Tests/Fixtures/MultiStark/prep_first/logdeg_4/proof.bin and b/Tests/Fixtures/MultiStark/prep_first/logdeg_4/proof.bin differ diff --git a/Tests/Fixtures/MultiStark/prep_first/proof.bin b/Tests/Fixtures/MultiStark/prep_first/proof.bin index 37054c87f9..4339663796 100644 Binary files a/Tests/Fixtures/MultiStark/prep_first/proof.bin and b/Tests/Fixtures/MultiStark/prep_first/proof.bin differ diff --git a/Tests/Fixtures/MultiStark/prep_first/system.bin b/Tests/Fixtures/MultiStark/prep_first/system.bin index 77675a263a..6e975bfbab 100644 Binary files a/Tests/Fixtures/MultiStark/prep_first/system.bin and b/Tests/Fixtures/MultiStark/prep_first/system.bin differ diff --git a/Tests/Fixtures/MultiStark/proof.bin b/Tests/Fixtures/MultiStark/proof.bin index 1782fd6ef1..f92e9abb63 100644 Binary files a/Tests/Fixtures/MultiStark/proof.bin and b/Tests/Fixtures/MultiStark/proof.bin differ diff --git a/Tests/Fixtures/MultiStark/single_no_prep/below_floor/proof.bin b/Tests/Fixtures/MultiStark/single_no_prep/below_floor/proof.bin index f8ba46f9ec..1f0101e93c 100644 Binary files a/Tests/Fixtures/MultiStark/single_no_prep/below_floor/proof.bin and b/Tests/Fixtures/MultiStark/single_no_prep/below_floor/proof.bin differ diff --git a/Tests/Fixtures/MultiStark/single_no_prep/below_floor/system.bin b/Tests/Fixtures/MultiStark/single_no_prep/below_floor/system.bin index 0c45ee3c11..78e5547257 100644 Binary files a/Tests/Fixtures/MultiStark/single_no_prep/below_floor/system.bin and b/Tests/Fixtures/MultiStark/single_no_prep/below_floor/system.bin differ diff --git a/Tests/Fixtures/MultiStark/single_no_prep/claims.json b/Tests/Fixtures/MultiStark/single_no_prep/claims.json index 18ca7ebb0e..f2f0d8f922 100644 --- a/Tests/Fixtures/MultiStark/single_no_prep/claims.json +++ b/Tests/Fixtures/MultiStark/single_no_prep/claims.json @@ -19,10 +19,10 @@ "num_messages": 0, "num_queries": 77, "num_shards": 1, - "proof_bytes_len": 16735, - "proof_digest": "084ec638bd3c6a3b33adccf3feeb38e7b9fe26a9f6b626c55dee4d66ecd31293", + "proof_bytes_len": 16703, + "proof_digest": "80027fc02897e3cc2e448c7c475ae7a3cda45a8c9a6397d8624f84100891ee33", "proof_of_work_bits": 10, "query_proof_of_work_bits": 10, - "system_bytes_len": 130, - "vk_digest": "0398e901eb36b3eb9acd6d09647d48854b58fe71d7349d7e3fdc42ac37742533" + "system_bytes_len": 132, + "vk_digest": "026ef6da94824bb082218d561d93688e4625a2bab7450bbe3515c39b21295a03" } diff --git a/Tests/Fixtures/MultiStark/single_no_prep/nonzero_cpow/proof.bin b/Tests/Fixtures/MultiStark/single_no_prep/nonzero_cpow/proof.bin index c4257a7159..d0af846d18 100644 Binary files a/Tests/Fixtures/MultiStark/single_no_prep/nonzero_cpow/proof.bin and b/Tests/Fixtures/MultiStark/single_no_prep/nonzero_cpow/proof.bin differ diff --git a/Tests/Fixtures/MultiStark/single_no_prep/proof.bin b/Tests/Fixtures/MultiStark/single_no_prep/proof.bin index 0e14761767..95d2fda00a 100644 Binary files a/Tests/Fixtures/MultiStark/single_no_prep/proof.bin and b/Tests/Fixtures/MultiStark/single_no_prep/proof.bin differ diff --git a/Tests/Fixtures/MultiStark/single_no_prep/system.bin b/Tests/Fixtures/MultiStark/single_no_prep/system.bin index 56230bdb54..c47dc71fd1 100644 Binary files a/Tests/Fixtures/MultiStark/single_no_prep/system.bin and b/Tests/Fixtures/MultiStark/single_no_prep/system.bin differ diff --git a/Tests/Fixtures/MultiStark/system.bin b/Tests/Fixtures/MultiStark/system.bin index 8f2e41744d..7748f9998b 100644 Binary files a/Tests/Fixtures/MultiStark/system.bin and b/Tests/Fixtures/MultiStark/system.bin differ diff --git a/Tests/Fixtures/MultiStark/two_shard/claims.json b/Tests/Fixtures/MultiStark/two_shard/claims.json index 84429062cf..3ce4d6204a 100644 --- a/Tests/Fixtures/MultiStark/two_shard/claims.json +++ b/Tests/Fixtures/MultiStark/two_shard/claims.json @@ -18,10 +18,10 @@ "num_messages": 0, "num_queries": 77, "num_shards": 2, - "proof_bytes_len": 44570, - "proof_digest": "8a2702b929408fbc1d5c39dbdce0730b2c7c26d7cfa54427b4d454ee5f025b0e", + "proof_bytes_len": 44778, + "proof_digest": "9ce942e020335faa9610c869f2d24f35f06de333dd045436c987609a8e279359", "proof_of_work_bits": 10, "query_proof_of_work_bits": 10, - "system_bytes_len": 355, - "vk_digest": "0f5391dbf272a26e0f3b4269c94254abe431c6c205923797ac8f0c76aa45cf72" + "system_bytes_len": 357, + "vk_digest": "3985ae0ec5637c570a395bf768550756866eee4b667c19a3480f391aac5015d8" } diff --git a/Tests/Fixtures/MultiStark/two_shard/proof.bin b/Tests/Fixtures/MultiStark/two_shard/proof.bin index 642f43286b..95163abe83 100644 Binary files a/Tests/Fixtures/MultiStark/two_shard/proof.bin and b/Tests/Fixtures/MultiStark/two_shard/proof.bin differ diff --git a/Tests/Fixtures/MultiStark/two_shard/system.bin b/Tests/Fixtures/MultiStark/two_shard/system.bin index 8f2e41744d..7748f9998b 100644 Binary files a/Tests/Fixtures/MultiStark/two_shard/system.bin and b/Tests/Fixtures/MultiStark/two_shard/system.bin differ diff --git a/Tests/Fixtures/release-05-closure-manifest.txt b/Tests/Fixtures/release-05-closure-manifest.txt new file mode 100644 index 0000000000..39f6ee11d1 --- /dev/null +++ b/Tests/Fixtures/release-05-closure-manifest.txt @@ -0,0 +1,5145 @@ +# definitional closure of Ix.Cert.Release05.release05_inner_default_ok, Ix.Cert.Release05.release05_ep1_balanced_ok, Ix.Cert.Release05.negControl_release05_rejects_unpinned, Ix.Cert.Release05.negControl_release05_rejects_fp2, Ix.Cert.Release05.negControl_release05_rejects_v5_default, Ix.Cert.Release05.negControl_release05_rejects_deceptive_4_55_0, Ix.Cert.Release05.posControl_release05_blake3_256_classical_127, Ix.Cert.Release05.negControl_release05_blake3_256_below_128_classical, Ix.Cert.Release05.negControl_release05_blake3_256_below_128_qrom, Ix.Cert.Release05.negControl_release05_fp3_below_100_qrom, Ix.Cert.Release05.posControl_release05_blake3_256_qrom64_headroom, Ix.Cert.Release05.ixVm2p23_4096sh_balance_lt_p, Ix.Cert.Release05.ixVm2p23_4096sh_hypotheses, Ix.Cert.Release05.ixVm2p23_64sh_hypotheses, Ix.Cert.Release05.aggr2p22_16sh_hypotheses, Ix.Cert.Release05.rec2p22_1sh_hypotheses, Ix.Cert.Release05.ep1V6Hop4_hypotheses, Ix.Cert.Release05.ixVm2p23_64sh_qrom64, Ix.Cert.Release05.ixVm2p23_64sh_qrom64_sub_one, Ix.Cert.Release05.ixVm2p23_4096sh_qrom64, Ix.Cert.Release05.ixVm2p23_4096sh_stdQro64, Ix.Cert.Release05.aggr2p22_16sh_qrom64, Ix.Cert.Release05.rec2p22_1sh_qrom64, Ix.Cert.Release05.ep1V6Hop4_qrom64, Ix.Cert.Release05.ep1V6Hop4_qrom64_sub_one, Ix.Cert.Release05.ep1V6Hop4_stdQro64, Ix.Cert.Release05.ixVm2p23_4096sh_classical_rom_133, Ix.Cert.Release05.ep1V6Hop4_classical_rom_133, CertiFri.P3.GoldilocksExt3.verifyBytesPinned_soundness_v6_553_keyed_133, CertiFri.P3.GoldilocksExt3.verifyBytesPinned_soundness_v6_553_keyed_133_bounded, CertiFri.P3.VerifyBytesPinnedMultiKeyed.verifyBytesPinned_soundness_ep1Balanced_keyed_checked, CertiFri.P3.GoldilocksExt3.qrom64_verifyBatchTensorPinned_v6, CertiFri.P3.GoldilocksExt3.qrom64_verifyBatchTensorPinned_v6_checked, CertiFri.P3.GoldilocksExt3.stdQro64_verifyBatchTensorPinned_v6, CertiFri.P3.GoldilocksExt3.qrom64_verifyBatchTensorMultiArityPinned_ep1, CertiFri.P3.GoldilocksExt3.qrom64_verifyBatchTensorMultiArityPinned_ep1_checked, CertiFri.P3.GoldilocksExt3.stdQro64_verifyBatchTensorMultiArityPinned_ep1 +# lean 4.34.1 5045d0056413266e57c625dcd7c365b10e377c52 +# constants 5142 +A 9621fee63c7d437a10ee5f45ae077be28cb85829549d0c395b090d6aa554a3ad Init.Prelude Quot.sound +A ad27a2569e31d0aae483b4e082259938d57343de61a37bf2e72b98b7eab89167 Init.Prelude Classical.choice +C 00310af89c99462c9a69466cea74924bc4e97d44f200f7aed23329cff6b9e3b7 CertiFriP3.Challenger CertiFri.P3.ChallengerState.mk +C 005220071d0569a2f9d66e45700d8f7366339b7df346bd5a4d72eebf181f12be CertiFriProofs.Exec.Stark.PrunedTensor CertiFri.Exec.Stark.BatchCoveredPruned.mk +C 00839d20c27532b75f295e55c6f8c6d00dc4660e321fcde73008a7e4b98df481 CertiFri.Field CertiFri.ExtensionOps.mk +C 01106888bae509afc9ca7ed3cca22fbd0730ea64e8ce4dbea95c7675509debb8 Mathlib.Algebra.Ring.Defs NonAssocRing.mk +C 043c0d1d354867028eb6a13aed4840b1266d629b8a88de6d0e19d173bfb88a8f Mathlib.Algebra.Order.Monoid.Unbundled.Defs CovariantClass.mk +C 079cb58b9da8ba8141157458dc842dc8d68e107631b50082828163a85ede1f11 CertiFriProofs.Exec.Stark.SpongeGoodLogTensor CertiFri.Exec.Stark.SpongeChain.mk +C 07a3e1db750226f8cbeee63e8c5d03ecc7a9e26b86ee588b74a11da02b199973 CertiFriP3.Pruned CertiFri.P3.Pruned.Node.mk +C 07f1ac5a32b0e8933b2fb3f0eeb781ededa0f1882994586d0d8dbc950430a5f5 CertiFriProofs.Theory.Compiled.Read CertiFri.Compiled.Params.mk +C 07fbd2651edc5ba3e81364ff71afd072b8fa5e007990b5909d4255d8c8ef9422 CertiFri.Challenger CertiFri.Observation.base +C 08db630fe4fcfb0bb0383779906f42e0d59db6133d3bd2383b390f3626ac4ef1 Init.Prelude Option.none +C 08f8de79b5fe71621727b972b945aa7ebf8fcb3351b6893ef31b1674ced19c94 Init.Core Std.Associative.mk +C 09282544c2891de21c49888ca93e1a60fb134f91a2bd7d82113e62cea78d3c2d Init.Core HasEquiv.mk +C 0da8537338068a260d6d3f9a95fdb4a74ee94955a47b30de78af73637e50a585 Init.Data.Int.Basic Int.ofNat +C 0f43bfb625f3de46e33b6b95c992a1165e28f08f2b7fb77d27863b795f256604 CertiFriProofs.Exec.Stark.State CertiFri.Exec.Stark.ShardView.mk +C 0fb15ab8756a265841d3065c6c249098cfd819226b84954e94511c5de69ec4d8 Mathlib.Algebra.Group.Semigroup AddSemigroup.mk +C 11333ddc1e37686f453eaffcaa1a573f62af3c2b853010fd50c94ff5bf6c46ec CertiFriP3.DomainSep CertiFri.P3.DomainSep.KeyedInput.mk +C 113a9428a459c5e9f7052e11ef9b934e11b61aa9fdd520a43f711f4f1a1c6da6 CertiFri.Stark.Graph CertiFri.Stark.Node.var +C 118c844f84b561852f723170285b6f780ef165569719dc095586aff14606b9d9 Mathlib.Algebra.Group.Semigroup IsLeftCancelAdd.mk +C 127224474bdb2e5e7c6b4901f8942fabc95d187bb965356c05084838939f6956 CertiFriProofs.Theory.Oracle.FiatShamir CertiFri.Oracle.FSQuery.chal +C 12cd411f38e699778f0f5a7d928d0c683e6bfc8d8817e807d0bae8c80f923b62 Mathlib.Algebra.Group.Action.Defs MulAction.mk +C 12da70b72a18de8f2c8705b281a6a3b39ce0cb8818195903d99d367330c80404 CertiFriP3.DomainSep CertiFri.P3.Blake3Domain.transcriptBatch +C 139678fc97d69afbf0f86cccec61319b4578e3d1f3b55e715f3dd8d2683ebd7d CertiFriProofs.Exec.Stark.Preamble CertiFri.Exec.Stark.Bounds.mk +C 13c439ae4d44e7caff2648eebfac21e905c84024c527356fdf0d7991257ee981 Mathlib.Algebra.Field.Defs Semifield.mk +C 15a592e3166f31b807e710889d3a688524d384133412f00ca0e87e3317bd5cee CertiFriP3.Wire CertiFri.P3.Wire.Key.mk +C 173eceee89f7a373e7874a0b875626ab9fb1dde8a9eadb5eb259574f0647feac Mathlib.Algebra.GroupWithZero.Action.Defs SMulZeroClass.mk +C 17a0ca768a175ab43ce781dbd2e8b0873060f830f49445a11f8328fe2f41e532 Init.Prelude Decidable.isTrue +C 18923e1d0662f9506a4fd8f677be858dc21fec846fde4e246fa90c8c442e0d7f CertiFri.Stark.Admissible CertiFri.Stark.BatchBounds.mk +C 1a6193562c94c81abb1058e0ff43924bb159eaaa427c698fd0921a0539177ecf Mathlib.Algebra.Ring.Defs Distrib.mk +C 1b0179ff3b0e33d9316e9bb7105710eda672ee79997cf87f6ab006847e9e8cbf Init.Prelude Applicative.mk +C 1b59dc2cf0644acab12aa0ca63e06b8d1d959d77805aadd26331e1b7ca5f1462 Init.Prelude Lean.Name.str +C 1bbf0dbf74f373ae484e36d66c3454774c0df20476adc57f11d3466d185ba278 Init.Prelude BEq.mk +C 1c97662d2011c71de6424b09ad2b0f437a359cd479001aad5b61837138757ee1 CertiFri.Stark.System CertiFri.Stark.BatchProof.mk +C 1dcd5de9f6302474dd2811c994273cb7a0f9bebaf45f21e827258fb95d2327ed Init.Prelude HXor.mk +C 1defb1140035966437399b6a40a704c8ca4bcd7ad4fd5d75684c0099a26ad483 Mathlib.Algebra.GroupWithZero.Defs MulZeroOneClass.mk +C 1e401a224a0fb9133b3d1297fa281609828d5872a5e54a978c71ae77f5d2b680 Init.Prelude Pure.mk +C 1ec925b20f40fdd845edb8f2fa8aefad4f91c750f6fbdc33e476ba83e63bea41 CertiFriProofs.Theory.Stark.Check CertiFri.Stark.Model.ExtData.mk +C 1ee0741c7e8ab100f95c89e83fd42405047d21712eb4ea9ff0c69adde9b7f0f4 Ix.Cert.Release05.SecurityAudit Ix.Cert.Release05.Ep1V6ShapeBounds.mk +C 1f03e67f3c894dc2b24dba5679b979343fd784296bcbed1ceca754e711b3218a Init.Prelude Or.inr +C 203ff60c1d4ab5bed7292b41c7a6249f302a6d96e03f04a17d7b89ce6b7b8148 Init.Prelude Lean.Syntax.missing +C 20f4b63a6b225d965c45703a24570013a0878dccb6ad87b4b24f50cbc9694ae9 Init.Data.Int.Basic IntCast.mk +C 22596208f35c8af794946d6ef0af73d4a960930012611a73433f95ce915c0109 Init.Prelude Zero.mk +C 2284857a045cf19248f13444cfc7b1210731b9d0a5bad218ef4764d7efd7b172 CertiFri.Verifier CertiFri.Fri.TensorChallenges.mk +C 22fccc56b1d1ee88a053b9d44be3440f1df7b368ad4018bbe775ef67afdfd2b8 Init.Prelude String.ofByteArray +C 233c0cc39641dda3de117fe87c93d3ea380315c10eb86a419f8b999fdf821b2c Init.Prelude LE.mk +C 234dd839941b23b9172884ab9e16cf525e360289816fc922488662afd8b4e937 Init.Core ForIn'.mk +C 235eb558f980f39eb68092997a72077c27a59ae084f8b7aa3bc7ae3508daa636 Mathlib.Data.Nat.Cast.Defs AddMonoidWithOne.mk +C 23743935327b6d697704880b8c11548d243b4fb95f58e882fccbdc061c11d27f CertiFri.Proof CertiFri.CommitPhaseStep.mk +C 240317b1296fa4a054305180d0332d6687de6772d40fb0726c882d169321d6c7 CertiFriP3.DomainSep CertiFri.P3.Blake3Domain.zkMerkleCompress +C 250dfb7bb8fc9c259f6541846c9d2462c55fea31a92d2cfa1747a2a078005a02 Init.Core Union.mk +C 25290d2adde1964df378c6f47278cdead69a92eb65b734826ccf088d61284084 Init.Prelude Lean.Name.num +C 254aa809174a5f3ef41a463d8bdc1c64d992090a707c40aa08413a587f86dc74 Init.Prelude HSub.mk +C 263a8ec83193ee4287790c0bee2b0fc1553b7a6858ecd07fad121fb21fd53c29 Init.Prelude Subtype.mk +C 26861fe05a6d693e22f1dc8bef0cd05950cbbdc7780cc1e2ab1e552c2ce56336 Init.Prelude Lean.Syntax.ident +C 26c848dae8238144769b50e12decbed7546f8e5584185b26bdeb11b4291e384e CertiFri.Verifier CertiFri.Fri.OpeningRef.mk +C 2790803bf093f53122d2517f9ef7c0594dc364ff2a0ed343ddac589b564f4bc0 Init.Prelude ShiftLeft.mk +C 282653c8662ad4cd61c266c4e948fa1ba8e38e2029c9406394d0237aa4fd02e4 Mathlib.Data.SetLike.Basic SetLike.mk +C 282776b98da251cc258192bc09f60b40673b51621f66833019a90abb3569647e Mathlib.Logic.Embedding.Basic Function.Embedding.mk +C 2914d654d1543ebe289da4ad24f5bbc24d70415689a8d1bca099c2ebbe5c4bf0 Init.Prelude Array.mk +C 2991c04100fdc8f5ad0188cd58514548c7452495f885d695a67de87f9cd2b7a3 Mathlib.Algebra.Group.Monoid AddCommMonoid.mk +C 29e3be2fa6a50d3a2ba2e12fcccf315acc7ef3fa40d47a8db5b319626f369b16 Mathlib.Basic.Complex.Basic Complex.mk +C 2a13a04d89c1f536233c63aed423ac0dba975e8a9772188a5703b20acb0b2f73 CertiFriP3.Pruned CertiFri.P3.PrunedPaths.mk +C 2a52688544faa6b11104878da9bd00c6bf48694fade64f0ef2bb5853ac84a057 Mathlib.Algebra.Ring.Defs NonUnitalSemiring.mk +C 2ba70aa7430d384fa712b9e886830d1128800061bd88b01b21b4e7b95bf15992 Mathlib.Order.WithBot WithBot.LE.bot_le +C 2c067337dbf01738209937de169d1a2d5e7c614abf598d0b806f39f60f596ac1 CertiFriProofs.Exec.Stark.FixedKey CertiFri.Exec.Stark.HashIface.mk +C 2d15ef8c3917b528b3c89ce08b272faa250c8d87fdd07c3f10213094bdf0ddf2 Mathlib.Order.Notation Bot.mk +C 2dbd7bb801143b59b3b8f28085186b6074436e6281bd31b87cfe4cf55370df04 Init.Prelude Fin.mk +C 2dcbaad55c371babf959add8dcf97b52e0d7c29402bb1751d160bffba7933227 Init.Prelude Lean.Syntax.Preresolved.decl +C 2e13725de743d5cdcf16b39aff81216f0dc5cb92a07f2380402c47555f308878 CertiFriP3.DomainSep CertiFri.P3.Blake3Domain.zkTranscriptBatch +C 2e2b980f47d0a5ea344d14bae8b6d3e27c491b13fd4489edbb6a8dbcde263ea2 CertiFri.Merkle CertiFri.MerkleHasher.mk +C 2f5bc11b4bb7229fb7ec3095823c95981853026fdbbfdbec7bc452e501443cf7 CertiFri.Stark.Verifier CertiFri.Stark.Challenges.mk +C 2fa6a8a35c0e38b8554f0a2d0f85e8b9b12336bf1c8ba224a889c7b58e7d85e5 Init.Data.Int.Basic Int.NonNeg.mk +C 2fbd2ec7099a1f703bb9d53849e7b4b81c7aa062923d6c7b36c5e93e61f98008 CertiFriP3.Blake3 CertiFri.P3.Blake3.Node.mk +C 304d18c6aaf35801ef8720973dee3ff940ba69a4b97c6b68da951264d6f03808 Mathlib.Algebra.Group.Hom.Defs ZeroHom.mk +C 3170406e6e03d14cf64660c2919fc8824087cbabab3c7def3e769aa6013ae611 CertiFri.Params CertiFri.FriParams.mk +C 31a45bef6cfc21a51a9e50a18047aef54356047f7616ef32938ed3407b545e3a CertiFri.Stark.System CertiFri.Stark.BatchMessage.mk +C 31f1fc6f46180648b5fbf2266557ffe4d04e0fab6521dda3f24cd070e7849aca Mathlib.Algebra.Ring.Defs NonUnitalRing.mk +C 3294ce24f7e7e0dd35e8d0544ac4dd008ea6c4c22f1d5ae65a2adf6bc53dec52 Init.Data.Int.Basic Int.negSucc +C 332a3492b6401ac86ae897be8b47349f794fbee19edbf9740e3689529e7d90f7 CertiFri.TensorBatching CertiFri.Fri.TensorSchedule.mk +C 334f42fccb4579243ab700ac952832a3f5b468e04dcc45763a8d8d2274eb3178 CertiFri.Stark.System CertiFri.Stark.ShardHeader.mk +C 33a93b8a39fc3e823d54f02c80d932b5ae06d63529f063a395d99550353b4f7d Mathlib.Algebra.Group.DivInvMonoid DivisionMonoid.mk +C 33be5fa44054da8ae968f6c34adcb6b3a98ad01f77735ced76b5864d1ee3e0cd Mathlib.Algebra.Order.Monoid.Defs IsOrderedAddMonoid.mk +C 34027f0ea69a6e6f72c1b9201f7325c05f2e9044f366b9b8540f000c561da682 Init.Prelude One.mk +C 35978605b2edf4576e8cb9a410250282e23959dec88209fc9a6736e5bd8f9c73 Init.Prelude HOr.mk +C 364bdd8f660d8deabf6f15798292bfb06fbe2293f3853f27c8cb27329e14fe72 Init.Prelude OfNat.mk +C 375d8e49cf420d1e8324bc80b06286cdf4c1465b7e9d63376bf92760a97eb3ee Mathlib.Algebra.Group.DivInvMonoid SubtractionMonoid.mk +C 394904da6393df6e87c1469caa70c9dd8baf47cc4095ccdaab00c613c6e40e71 CertiFriP3.Wire CertiFri.P3.Wire.KeyParams.mk +C 399da5e3c47f1369fd49a59c0fdb7722b06be02a5d5f3c8811457c983ae52748 Mathlib.Algebra.Group.Units.Defs Units.mk +C 39a88356c0e6c461bcec22703d6e0e0499a54f9d20bdff0e52320acf02014036 Init.Core Std.Antisymm.mk +C 39aecd03edf72fd987930e547e893fb4d6d4ca3cbeae997102d0859a955bca93 Mathlib.Analysis.Normed.Group.Defs Norm.mk +C 3aa384786b93329356d6541a3f2cd55cdd0ce67942bb0b08dbeb753055f2e59d CertiFri.Claims CertiFri.CommitmentOpening.mk +C 3b958a8d34ffdf3916b3cac8e2c1045ecfcca42240133445329e2e5c60a1bc49 Mathlib.Algebra.Group.Monoid NPow.mk +C 3c507542ecff7ed7d1d971795e88b8ab00d832d8f409c7baec05e499ce613fbf Mathlib.Logic.OpClass LeftCommutative.mk +C 3ccac0b1e41dde5af57940bf23c8d2a33d84b95cc525436639b1abd62b837809 CertiFriP3.Goldilocks CertiFri.P3.Goldilocks.mk +C 3cf5e4aa8d94ffed3089833a6c476ce2c50b25215c0cb0d1fc67bd61a60f0502 CertiFriProofs.Exec.Stark.StatePinned CertiFri.Exec.Stark.SupportedP.mk +C 3d379d5d11e12ba5692e850bf9eff6a5d49db7918c31c26ad4287262d4d16c96 Mathlib.Algebra.Group.DivInvMonoid DivInvMonoid.mk +C 3d676f5422a8a4578e115d04eb089a1f299442594eb995a1c40254b5cb62ee7d Init.Prelude HMod.mk +C 3dd6cbeaa8ccfbba3ec48822b32028605fb63f8d265efe3bfbc8c628f6441553 Init.Prelude List.nil +C 3ea179fe2274599a47d17654f5b43b8a4d9db91c8ab08505b293bcab3ce071ed Mathlib.Algebra.Order.Ring.Defs IsStrictOrderedRing.mk +C 3f6fc15b5c015eb904135ac884d79b0a6da28a72885f39ebe3ffa7a5af738377 Mathlib.Algebra.Group.DivInvMonoid SubtractionCommMonoid.mk +C 3f881bf86775f743b0051f395f98a992954081baa1a20f62c93aca5f050db44d CertiFriProofs.Qrom.CompressedOracle CertiFri.Qrom.QQueryAlgorithm.mk +C 401ee01c1b1fa6cbed8a36d669ae64eba97e5abf987750bfc12ae70b362c1ca9 Init.Core Sigma.mk +C 4023336a0188793f5a6e38c296151f363d0fe4cbc1e772fcc46fefd5782dd2b9 CertiFriProofs.Exec.Setup CertiFri.Exec.WellFormed.mk +C 414503aad784ac89da04b8a778023975af18fdf9ca5f337b0fea3a34b9d8aee8 CertiFri.Stark.Graph CertiFri.Stark.Node.pub +C 424a8a786a554a842458fdb7d89df4ccaaac14ba0277ef9ba4d75755d8cc5a11 CertiFriProofs.Theory.Oracle.FiatShamir CertiFri.Oracle.Transcript.snoc +C 42e31c942454a5662d457c7c67f3fe16f65fd5606d234999459723fac286343d CertiFri.Stark.Verifier CertiFri.Stark.Selectors.mk +C 430be61a07dd211c49303fbd727803bedbba8d067f92d828f4ecc86bc174fb0c Mathlib.Algebra.Group.Monoid AddZeroClass.mk +C 43c7711c146c0cdc914a056fe0a0efa82ec4976390670458f4f4827ca078934f Mathlib.Data.Nat.Init Nat.AtLeastTwo.mk +C 43d6a39db11d8f83ae17a70666e2e1f554fd8e5d24ffefbb2076891ffd6cb98d Mathlib.Algebra.Group.Monoid CommMonoid.mk +C 440e863d8fd0c39a15f794db0f543fbbfe6984569c0ca9fd79f9eb8f4327bea8 CertiFriProofs.Exec.Stark.Model CertiFri.Exec.Stark.StarkModel.mk +C 451e631d1907b4f0161593b05c40bc26219950b1e0b643e792554f9152aeb626 CertiFri.Stark.Graph CertiFri.Stark.Node.isTransition +C 4555e8f27f9d8baf69944f4ae24b018ca1ed3422cde2aaa2f317c18e761157eb Init.WF WellFounded.intro +C 45d1e22d371bf81a2c42d7d96bb87a5729780d6affd39b03708bd6168bd9b291 Init.Prelude HShiftRight.mk +C 4704f6db31495dc4b9a6686cf21c26fc63fbf3acd747d2a20c9d514fe5039fa0 Mathlib.Algebra.Ring.Hom.Defs RingHom.mk +C 472d803e1e8bf08c73d1651283f901289ceca664619e6b64820639f626e94745 CertiFriP3.DomainSep CertiFri.P3.Blake3Domain.merkleCompress +C 47cc620a2dc283c7c03934e084198b695242b30d5ff0068327a8faccc7e54db9 Init.Prelude Bool.false +C 4824edf7a8b9801e8f986bf585d519c9b46f08d271738ee7facb2716bb0f2108 Mathlib.Algebra.Group.Hom.Defs AddHom.mk +C 49f47c07dd7a816b5b4167b37149077a40d02260f4cbba9dba985075eea09c80 Init.Prelude UInt8.ofBitVec +C 4b73a7484ecad062323b0c42bf2bc5998709c6e3d9f2cdd677100b700f7dfd3f Mathlib.Data.Int.Cast.Defs AddCommGroupWithOne.mk +C 4bc74b0f31718500e7a2eaaf635a1d35ad505f02f2ebffd286f8d8eca45fc775 Mathlib.Data.Rat.Init NNRatCast.mk +C 4c72e8d6ee932c4949d6631154d51d89fbd639ee800386716fc6b9db84816591 CertiFriProofs.Exec.Setup CertiFri.Exec.FieldModel.mk +C 4c82ae40b937067c550324e84f54f1d95bf21a36a7faba5cf55263698d82ad19 Mathlib.Algebra.Field.Defs Field.mk +C 4e3ced6c2850bd25d58ec860df4c98710edc4104251e902ec1abd400cf3606c6 CertiFri.Stark.Graph CertiFri.Stark.RowValues.mk +C 4e81c237dddfd7d4e84bb67756b631de1277c0cfb0f65c3207b5e61db86a9a2b CertiFriProofs.Exec.Stark.Encode CertiFri.Exec.Stark.BoundsLE.mk +C 4ed08a3e1df7791e2f15a8c2c292fb3c4a1a4e53351b042c1f00192256a85a59 CertiFriProofs.Theory.Compiled.Read CertiFri.Compiled.Slot.mk +C 4ed384b7e49dbf8795e0f9e5e55e9f8362e9c59eb5c49ee71ee338c6f5978585 CertiFri.Field CertiFri.TwoAdicOps.mk +C 4f533ef15689ab8e3994961901ad0d043aed5d903ae7cba682c29ce0843fcf87 Init.Prelude Functor.mk +C 5070ef5a2c06821724eed23f8d014bb2ad4c98652226180c1588a4cddac903ea Init.Prelude List.cons +C 507bbc87a3cdebd98e66bb6a37216358fed6661607f6b7031261eb9bfd8923d2 CertiFriProofs.Theory.Compiled.Verifier CertiFri.Compiled.Proof.mk +C 50ed325a3002beb6d9941b5e0040e09815bcbe323a822f7ab3f0a7713f52b6ce Init.Prelude Inv.mk +C 51753c7b94343dbf0b79a459fbe5169642861aad939074def49708036d941aa1 CertiFriP3.DomainSep CertiFri.P3.Blake3Domain.transcriptSingle +C 520be10965c4db8afb7342cf3ca13f0f6219b993023fef5fab4c4a9922e83957 Mathlib.Order.RelIso.Basic RelIso.mk +C 52c690532dc11cd0f8275f0c9269f85748bae17f50c35d9b78f522223c49ba93 Mathlib.Order.Lattice DistribLattice.mk +C 5425f2791194bcde755d177feaf883fef17fe6a9238dd349d920491eaa603ff6 Init.Prelude Div.mk +C 54f33ffa23d0761d7c71cd41bce89831dfa9261a780d58462a4a08f1c73e68ba CertiFri.Stark.Graph CertiFri.Stark.ColRef.mk +C 54f6e9e02dc67a328d07ead8e3ba49ac24cb8c27e55f78aa356cc6de574102e5 Mathlib.Algebra.Group.Semigroup Semigroup.mk +C 553855e52043a75af7caa9628cbe0532319b33f1cfc278629dc6412e756a756a CertiFriProofs.Theory.Oracle.FiatShamir CertiFri.Oracle.FSQuery.other +C 55c473ef204b3c3ff30ac59ee576f4fc7b9636d6f9c238e364c7b3fae8d30a1a CertiFriP3.Blake3 CertiFri.P3.Blake3.State.mk +C 566b77748b137452f64fefb4e0e62cda38a7cbef9b552c6a1848217a2b74880b Mathlib.Order.Lattice Lattice.mk +C 56e6df7388dc12407ec49d9f029a16f7bc296b9f9277cf636e3dafc4edefc108 CertiFri.Mmcs CertiFri.Dimensions.mk +C 57956c182b1e5e74688c9b311e0e8bfa3a0dd9e3b065333ab9dbd3e05ea5408c CertiFri.Verifier CertiFri.Fri.PointRef.mk +C 586d402919bcdec804abf99f2d2cc0fbbbf25c68abf6607f2511c00d3cf214ef Mathlib.Algebra.Group.Semigroup AddCommMagma.mk +C 58a2aefc16c6b879612ff99c9d63c084a7cc355560084cf9b6dd67f236b04b02 Mathlib.Algebra.Group.Irreducible.Defs Irreducible.mk +C 5b9ce281ac5df4b83fd3e5721a761578c55202b017a7b17f19411ad238e2e617 Init.WF Prod.Lex.left +C 5c35028973b489b36ba83114a6eb64a12f1acbb77da8e8417de50aaa68944131 Mathlib.Order.Defs.PartialOrder PartialOrder.mk +C 5dbb9732ad5158392cbb7352fe83471a77825f33f71cbfc4e6b99394fb7e6d7f CertiFriProofs.Theory.Oracle.MerkleFrozen CertiFri.Oracle.SpongeQuery.chal +C 5f87bd57f8d507e8dae859a7e7726dfdf9cea12c813d6d5a97eb20f060509239 CertiFriP3.DomainSep CertiFri.P3.Blake3Domain.zkVerifyingKey +C 6012ce36cd45f30a4f15f319cd0504bd80d67b630b314fdd25471cf2bf6c1670 Init.Prelude HAppend.mk +C 60a329ea92456952fc6148dd44e4c25003a67f2e0159da3a8b9c9f3e243067f1 CertiFri.Stark.System CertiFri.Stark.System.mk +C 6155f9cfc525e7f1224ae4030afbe88071d5d4829720519d16a0b91cb2985dc3 Init.Prelude Or.inl +C 61a4f15ec1947b97e5476e3d0c42b5092d3bcb39edc56b4792239e6920fdd122 Init.Data.Cast NatCast.mk +C 6215f62c72404c0b169527d3aaea9a760c7662c566c567cb570bc05013ed2b0f Init.Data.List.Basic List.Perm.nil +C 62878ff3af335deaf6845b8e1a9c5d58c19ed05d06abdc03cfd61e86188914bc Init.Core Equivalence.mk +C 63b5e7a8514bc65b12a11fa54b1bed3a9f0d4c13afac060c7ef89bfa2962874e Init.Data.Range.Basic Std.Legacy.Range.mk +C 643a2029f2e704db3fd8150dbcad4df4d5472924a81084f8d1f213378068672e CertiFri.Stark.Graph CertiFri.Stark.Node.isFirstRow +C 644bc68f8e7d9594d03a1a1761ebebd3821d7423c566ac918687a54ad6d81872 Init.Prelude Nonempty.intro +C 646508a951dd4983c1142ff9712c669e9cd738ceec33854a7c8c8f96d9450795 Batteries.Classes.RatCast RatCast.mk +C 652b638cd76813f3e63a19fbadd143139a25e2c34c93bead5dad362495061506 Mathlib.Algebra.Group.Hom.Defs OneHom.mk +C 656a08636bd49f0fd64f88682d81fab7275a8353498f1c6f076f5181286aecc3 CertiFriProofs.Theory.Oracle.MerkleOpens CertiFri.Oracle.MerkleRO.Dig.leaf +C 65b0c008d9c5bd68e65213fab327afd99763191dfb92275e4eb594dffa7e9d4f Mathlib.Algebra.Ring.Defs Semiring.mk +C 661e61b8ec3cb0ab0b1dec9ff30ee4144ae9f8c4f6bc5630e9a6565bff0cd2fb CertiFriP3.DomainSep CertiFri.P3.Blake3Domain.plain +C 6698ae9108339a2a7157694cc8fc8e4127ce12cea73f7bcfc4ecc25e06153412 CertiFri.Stark.Graph CertiFri.Stark.Node.isLastRow +C 685e3ff0a81d9fed1d44f64982a0d0a173743c50eb480dcb3a4d70df6bd54498 Init.Core Singleton.mk +C 69aebb313fb9b88c4bc56fe30b9bdbcd73a17cb08220dc7aa8f68f98d75854b6 Init.Data.NeZero NeZero.mk +C 6a7ade7f24f8ff929a978c6dbd20cd5c0c694c17262546aa2baf7e01380cd778 Init.Prelude LT.mk +C 6aca2900d3f7f627d43a8da2be04220fce4d785704b81351e4370a2715b5d7ea Init.Core PSigma.mk +C 6bad293121cef160ec245e8131a4a6f4aaf92c487ce798c971fee3bfb5f47a44 Init.Prelude BitVec.ofFin +C 6c26c6616a76d510eca528bcfd0b0b015df108dddbe9365f56a4e04073475004 Mathlib.Algebra.Group.DivInvMonoid ZPow.mk +C 6c3fd46589bb38d88795e71ed92b98ee26817a6148aa36c5e15690857b592f68 Mathlib.Algebra.Group.Monoid AddZero.mk +C 6c528cc51e16e3ecc2623fa7801bed840c93160bede2256e56ba91ea1ea9791b Init.SizeOf SizeOf.mk +C 6d38aea76c32de8d4caf3f8891961404c4dd07184839ed7b48c92e500276b361 Init.Prelude Option.some +C 6d8e6579d3b2cb6c6b39f36f5e4df8415fe3aad73a75d2cf1288c7cdc8541ec2 Init.Prelude Char.mk +C 6dcbe38dc7873ce813bca366e60ee42c4861fa34d84b2eabcc6f8e03fad55cb7 Init.Core EmptyCollection.mk +C 6e0bf2970beef27f38b23bf6f4b44b09633cc224a66f7da734d2818ec5ed2d1b CertiFri.Stark.Graph CertiFri.Stark.Source.main +C 6e786ee485701790bee6c09becbf3c688e53cd55b143d75e3a4b9ede7666355b Mathlib.Algebra.GroupWithZero.Defs MonoidWithZero.mk +C 6f02bb3cba53e8878f84766ea9e86acc10116e03b279c1b7315531038c197334 CertiFri.Stark.Graph CertiFri.Stark.Node.sub +C 6f11da340d58b7e69e91a4f7a9261f41897207b476648a9872209ab042965158 Init.Prelude NatPow.mk +C 6fd5f062dcd3fc0b81c73316c8fcc640cd60e20b918a773773642a831e696dc4 CertiFriProofs.Exec.Stark.SpongeGoodLogTensor CertiFri.Exec.Stark.SpongeStarkMsg.squeeze +C 70ca7f011e5eb8c173b62673631f6b7a23d22952b9f244a91d93b7111a223e2f Init.Prelude Nat.le.refl +C 70f59af98f1320e68c6f05903b277b33df6914c53fbb5c9a2635d10d6063d757 Mathlib.Algebra.Group.Hom.Defs MonoidHom.mk +C 720821cbf44adb80c132b0b7503cd65502d4948f5a5b44c2ff25e07639350b40 Init.Data.Ord.Basic Ord.mk +C 728292a5a1991b31efacf9edcbadc8e662f2c810d79b726aee2aa6f0e5aad075 CertiFriProofs.Theory.Oracle.Basic CertiFri.Oracle.OracleComp.pure +C 72e21f5220286963df82cfa814695030245808b1f507c908deaf4ce0714c4a24 Init.Core ForInStep.done +C 7345c4b99d226d33f04879cb28f34266f2e81734c7b1409bd0bdfcff822e147a Mathlib.Order.Lattice SemilatticeInf.mk +C 744c4bc49b11061e7ec0012b75b73a0c342909bab38035d41fb3dca279107695 Mathlib.Algebra.Group.DivInvMonoid InvolutiveNeg.mk +C 74a9f58f343e7875c40e5a7350d91d35ba553bf2698b7ff320b612cf85f1607c Init.Prelude SMul.mk +C 7605c431c401dafb1729b81761f8b0636600067c101bf945090e2dad925e9c8a Mathlib.Basic.Nontrivial.Defs Nontrivial.mk +C 7651d695547db5f625788994d8f4147d86becdbb9aeca6e22c410fa48924076c CertiFri.Proof CertiFri.BatchOpening.mk +C 76625d3f6b29e9126bb9bb24edf57a4158bf37cfd6dc51745695ec8e6cccda70 Init.Prelude String.Pos.Raw.mk +C 774fb1aaca46caeea7f6262f54da2f05969a2b5d2d4983b529e9d6ce5e328538 Mathlib.Data.Nat.Cast.Defs AddCommMonoidWithOne.mk +C 77ee12b8ff5c93c418889078e640ae39598c55ce0804a791ee5de7fadb21e87a Init.Prelude XorOp.mk +C 78c837303d7b2398838b51e90e3dee11260842c6d4aa7cfb9fe027366c551755 CertiFriProofs.P3.WireRoundTrip CertiFri.P3.Wire.KeyParams.WireOk.mk +C 79481e6756edbb9bb91c8dd34c43bfb6b3c8f376aa0a8c3b98415e32152e508c CertiFri.MultiArity CertiFri.Fri.QueryResultMulti.mk +C 79ec57dba141e7a943d269a2eb1661a6085e84100c382a11d12910aafe0eff53 CertiFriP3.Blake3 CertiFri.P3.Blake3.Block.mk +C 7a4871fc5f432aa3de77837f4201b66bac942370076d7e480a1f863608306309 CertiFriProofs.Theory.Compiled.Read CertiFri.Compiled.Msg.mk +C 7bc4f05dc05ccbc6ff630132472a9031fe09b7ad24a1e8f4e160bf56cc21f689 Init.Prelude Lean.Syntax.atom +C 7c0a67c5174650ea0af5a9a6a8b18ce6101c4e7a7f614437aea27b885ebade33 Init.Prelude OrOp.mk +C 7c37e9d65312858ea88e286aae7187da4c619eeb34da09e8bf8a049e0f173fd2 CertiFriProofs.P3.ByteLink CertiFri.P3.ByteLink.ComputesByteVerifier.mk +C 7d4dc1c4720db96e259cc2edf162222ecaf3a4a4a2e05564c575d0e98682e256 Init.Data.List.Basic List.Perm.cons +C 7d8f9704cb07017a7d48b8f3ef576b54f5501d2cfa1cf08ee46ca9c68500fd0f CertiFri.Verifier CertiFri.Fri.ClaimRef.mk +C 7d91a740ced3a4ff6eac5ff7f6be68bbb7379bcc7c4d81c8ef5a4cc5209cedb7 Mathlib.Data.Fintype.Defs Fintype.mk +C 7daaa780215a79471387307062ff77e8caf83f8666d7443100c5e6add98465d3 Init.Prelude Lean.SourceInfo.none +C 7e1d49d295c1fe11dd6df2af0669a6049141c75b430bb0bb468646b04b33657f Init.Prelude Append.mk +C 7e2e8498783812e079ff45c97102e23806813c1c8bf88133755c6cf1c4554219 Ix.Aiur.Parameters Aiur.CommitmentParameters.mk +C 7e854245328ba0148833a719b6def8809d07848c8fcd05d11dfb37431055c495 CertiFri.Stark.Graph CertiFri.Stark.Graph.mk +C 7edd9a2baf866a7a4460bfcc1875f2c470c208e4f2eb37e25930bb0e430a106f Mathlib.Data.FunLike.Basic DFunLike.mk +C 7ef674976044f27f707ed621013f7cb2deff0e4d41c1ba4625f1dd20fa8e41b1 Mathlib.Algebra.Order.ZeroLEOne ZeroLEOneClass.mk +C 80778eff010e9e3229b23b95d4adca58a709e2567015da5446723357901df1f6 Init.Prelude Mod.mk +C 81fd14603a48acb0bff89c2bca680cabd2db8dec08df50e91ff3bbfb707ec463 CertiFri.Stark.Graph CertiFri.Stark.Node.add +C 8206d304399be172bea4bee082ad10b98d777eb2b3acb93392b9cdee3ef97f9e Init.Prelude Nat.zero +C 8248f8ed39c9297e2f943e33a59a025268572205723a80718e5e18575a4210f3 Mathlib.Order.WithBot WithBot.LT.bot_lt +C 835846caaafca3cadcf49d79b902ee29977fbc6f3c8a807149f33240871d12c7 CertiFriProofs.P3.EncodingInjective CertiFri.P3.Encoding.HashCall.transcript +C 8379ec5df60b00589a7d29dc077690f7085dff44d987729b03071162e8172793 Mathlib.Algebra.Group.Monoid AddMonoid.mk +C 837c55983593203851d877f452c4f350f5c93c93e75f7aa8e6970e98420bcb2d Mathlib.Algebra.Ring.Equiv RingEquiv.mk +C 843d6c2efbfb09d31c1debd9585414a80f3010e3cb0ddd5849f9511f5dde7eb2 Init.WF WellFoundedRelation.mk +C 8442b740d0a34c8e8cda9d53fba6033ccd7155f0012c43eda604185a143490f7 CertiFriProofs.P3.WireRoundTrip CertiFri.P3.Wire.Key.WireOk.mk +C 84814ae271c7433ec61650851814bbad3cce39932cc55f4732aeb8a41ba0d7c0 Init.WF Prod.Lex.right +C 854429802bc2d6e0f6908af426b130cad111ad59b70dab306a75be244b363f1d Mathlib.RingTheory.RootsOfUnity.PrimitiveRoots IsPrimitiveRoot.mk +C 86ebad76132e01d50cafe5f92fcbcd9e88b3a1f973ba46ca1bed41f824453ed8 Init.Prelude ShiftRight.mk +C 87df5879b219e2f7c69fffa9b2d2105bd79137cd06c5461b4f539d7e781ece73 Init.Prelude Lean.Syntax.Preresolved.namespace +C 889e2ad95ee51dfa6522a62d596ef155a504317030aa4e9ef8c58a5665e3aaf3 CertiFri.Challenger CertiFri.Challenger.mk +C 88c6f72fafb423bd482f1d0f94ab1b3095445f817ba42ef461c3e4c0550a2fc9 Mathlib.Algebra.GroupWithZero.Action.Defs DistribSMul.mk +C 89164adf40e2e5416944e26db9cafacaaf18f39013a9a9e0a7512f6c1a7b51c4 Init.Prelude HAdd.mk +C 8b3f03cc14f5bab6cc822a869262fe1b4633895eef323aedae5e8d88dc53b468 CertiFriProofs.Exec.Stark.SpongeGoodLogTensor CertiFri.Exec.Stark.SpongeStarkMsg.absorb +C 8bb957ef752810a17d4ce71c8d488a374147455795e6e41cecd509a86ddef906 Init.Prelude HSMul.mk +C 8c67e568be5fc9ec44b1cf8da77f4c5a89b1d537cf716a3c9392ea5aa157c229 CertiFri.Verifier CertiFri.Fri.QueryResult.mk +C 8c74a712a791ab5ca7a5cc721af4f64b5efbce9c926367ce22e175bf256baecd Mathlib.Algebra.Order.GroupWithZero.Defs PosMulStrictMono.mk +C 90ec6c76a4ed6b20b5adbc2f119e963a18ec63147414d462d08cebabfa227a20 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.mk +C 9105210de1def9efae17501760750d17691db44ff674988efc3e559c0b4cd353 Init.Prelude True.intro +C 920b698527c92365f501d9b8e222e5b953a84c333d61e4bcc4f99c184ca94d8e CertiFriP3.DomainSep CertiFri.P3.DomainSep.mk +C 9401ca310ca0eb45c27e6a07a614097917b5d627c123e12148d6b6e1526e059c Mathlib.Algebra.GroupWithZero.Hom MonoidWithZeroHom.mk +C 951770cadc89c753fe919d1532b06698e6369a3a961e0dea26dabe584dbc80b6 Init.Core ForIn.mk +C 955b7424adf44b843b2cac749fab62adc1233388de50753546016a1c0056ddb2 Mathlib.Algebra.Order.GroupWithZero.Defs MulPosMono.mk +C 95793d9b44e5527f3a2833792ec2657b6e6e82fa901c5eec0aa2761590faeb0b CertiFriProofs.Theory.Oracle.MerkleFrozen CertiFri.Oracle.SpongeQuery.other +C 962482c84cbfed3b0743142153adac6df001f127a3efd34de6c88bf2ee28a2e6 Init.Core ForInStep.yield +C 96c913b6474800fffe8dc6498a8669e54e2732933b105760d4e22bfc6bc442c6 Init.Prelude Lean.Name.anonymous +C 97503c55f9bb88b029665d827735c91a6e82cacf33d35d5daf0011722462c038 Mathlib.Order.WithBot WithBot.LE.coe_le_coe +C 9763a53c0950e920b06eff80bdf4d1982f28fa35e0eae6cb7fbaa951aefb1880 CertiFriProofs.P3.EncodingInjective CertiFri.P3.Encoding.HashCall.leaf +C 98778a01a0df70faf39d743966083af3e0be997cbe78092678905e96ba79b396 Mathlib.Algebra.Field.Defs DivisionRing.mk +C 995403fcf4d9de3274020acc5ea59e14b989a834a7045b5a5b76866985476831 Mathlib.Algebra.Ring.Defs NonAssocSemiring.mk +C 99a256c5dfb6d938aaef26bb6f2cfba0bb476d482445396002eb93af185b35f1 Ix.Cert.Release05.SecurityAudit Ix.Cert.Release05.InnerV6ShapeBounds.mk +C 99cc61177b111a7ff9d7da4698e441c20760a7d4cba1d2b7f72c5d26a91f7480 Mathlib.Algebra.Ring.Defs NonUnitalNonAssocCommRing.mk +C 9a5c42129b0aad4a465e4688addb4ed1534372d717f50a712aed269951199159 CertiFri.Stark.Graph CertiFri.Stark.Source.preprocessed +C 9aeb70f10fceb3aff2466b21d694816da44e3883700eeeccd057d5d31a526d62 Init.Prelude HEq.refl +C 9b32c028694e7ad02f8c20798939a08896b6fa91495a0c67ff51cbd3a4e79458 Init.Core Std.Refl.mk +C 9c2bc3925136468ed210779f3584585079fecec848021c3022148d56bf129a91 Mathlib.Algebra.Group.DivInvMonoid NegZeroClass.mk +C 9d28df975f072f5a6a14492c32d9b28fc654734419cb171d6020cf2d73753d3d CertiFri.Claims CertiFri.MatrixOpening.mk +C 9e17578c29ad6ab83beb2fe9a26201dbfa74d38669863db3283db90b4ff9f653 Init.Core Inter.mk +C 9e939c981a0ca3a121791c4684f33187bf9675a2a35ceb9847328272dc428e01 Mathlib.Algebra.GroupWithZero.Defs CommGroupWithZero.mk +C 9eacca66c924751f8ad0e129fd516492abc97a6f0ab8b8d7658ab4e3126b68c4 Mathlib.Algebra.Group.Monoid NSMul.mk +C 9fb037d53f8e69668abdd78563b53f969bc28ca9194db86f14eff007bc728f7b CertiFriProofs.Theory.Oracle.MerkleVerify CertiFri.Oracle.HashQuery.rows +C a0ae82e4691c550b1688249e7c0cee32894234478b1e933c609424032fc07ee4 Mathlib.Algebra.Group.DivInvMonoid DivInvOneMonoid.mk +C a16845dfa6a1d39b8ccc8f6bd295afc733c378b185b2f00c27108ae4c4ada05b Mathlib.Algebra.Field.Defs DivisionSemiring.mk +C a16f0b3ab5a424cff8332ebc77017287a04660c4891685715706caeceb793439 CertiFriP3.Wire CertiFri.P3.Wire.KeyCircuit.mk +C a1f5db5371796939137d09934c5b860ae9247492c4005310ef3f99b3ccc40f82 Init.Prelude Lean.Syntax.node +C a256fd69ac2f0a13390c72e95a574b60d6e378334b251d0e51e1a3eface53f84 CertiFriProofs.Exec.Stark.FreeTensor CertiFri.Exec.Stark.UStateTensor.mk +C a34b668ab19a01e7f137243a3b5d5b01214ec3ee961a5cebf6df32bd2660007e Mathlib.Algebra.Group.DivInvMonoid DivisionCommMonoid.mk +C a5036c040f798b755632d67d16d05dd2ec1c2245f6420dce271381be8f23ab5c Init.Prelude Max.mk +C a660b00c75020f06eaca8000db5fb3c0d6c137f3faabff7f3d7e1b9c379bc38a Init.Prelude Eq.refl +C a7496791a3a3fd4c8b71060970b0e5e99b4edca258034b518178f89d454b5b74 Init.Prelude Bool.true +C a7e099dda3ff9d45bc5fc06ea07d69c48b23cf5166893599e8510b0799c0bbf7 Mathlib.Algebra.Ring.Defs NonUnitalCommSemiring.mk +C a7ee880db0da3a20ddc1c0a24234565f6413996c6c3bed20ae9fba6f08ba4766 Mathlib.Algebra.Module.LinearMap.Defs LinearMap.mk +C a81b3fbf9fefbfa38d359a1a1023579ec86eb33d955ad46cb9883087b2ae764f Mathlib.Algebra.Group.Semigroup CommSemigroup.mk +C a82e5686213e90b0290705030105a1e528d3197b26a2286b5f69419c0ca32dbd CertiFri.Challenger CertiFri.Observation.digest +C a84d6d26cd20d808bec30cd95a0b1debabcb81d0204b34d3936a2997eb1f0077 Mathlib.Algebra.Group.Semigroup CommMagma.mk +C a88053cdd9094b1cfa13998e79ff52b9fbd454d27bf29fcde73d36cf8a957c7f Mathlib.Algebra.Group.Monoid AddCancelCommMonoid.mk +C a8973ca2bf91a38ffa4c509278e25c8c2c8e87451948cf824db747904d1304fa Mathlib.Algebra.Group.DivInvMonoid SubNegMonoid.mk +C a967a3032a79092b2172b500172fdf950d95e94e3213ad3f4d25f479d0477a4a Mathlib.Logic.Equiv.Defs Equiv.mk +C a9d13de887053f5941e153022ede68b0f6d5600757998253f251819b241093d3 Mathlib.Algebra.Group.Monoid MulOne.mk +C aae7efc5f3825852101eccdd0f798e43e8ca729c076c8e6943054c0d06d7e930 Init.Prelude Add.mk +C aafe3a9bbd1a10e93375244b920678b46e57758df19f9fe275b5a72f74d3b56c Mathlib.Data.Finsupp.Defs Finsupp.mk +C abb847887f2c268cae343a2beab4aa2784a6a87f57bdb4698f476bda2979fcbf Init.Data.Ord.Basic Ordering.eq +C ac7d2b6a1908dc1ac7e7d5a004a58e13613f9c2b8de6478908638ec4877cec33 Init.Control.Basic Alternative.mk +C ac9ffa8ee4316ddd230ac38d9c2b5320a509847b543e5f21bc1fd64f7a00881c Mathlib.Algebra.Polynomial.Basic Polynomial.ofFinsupp +C ad5d44c08a81c72980af4c6a4ae0db36a157c2b9c807a14ad79de6eef2f3781a Mathlib.Data.SProd SProd.mk +C adbfc7e1c03a42177ab64419e991f5cb798a42a7536c29d90f2481df77ec581b CertiFriP3.GoldilocksExt3 CertiFri.P3.GoldilocksExt3.mk +C ae1caba132fda0a43ecca11080a01f3dff9122b7387d6eebf9d13c33d2306cf6 CertiFri.Proof CertiFri.FriProof.mk +C ae68052b25db1ada6b138def7f8a7301c7163325b353a530361c1172f0006f58 Init.Prelude Lean.SourceInfo.synthetic +C ae88e93a744c8e52e3c7f05a3ce585a5b7ef4e74d97c7436c7511313783049fc Mathlib.Algebra.Ring.Defs Ring.mk +C aefa7e11b01b81d54c7f3ac1f258ec84a856776d343234316677a17b10dee23e CertiFriProofs.Theory.MultiArity.CompiledTensor CertiFri.Compiled.MultiProof.mk +C b101dd179704ea18ea01629c4068008c05cd5da08e81152c224b48edd5b8d45a CertiFri.Stark.Pinned CertiFri.Stark.PinnedBatchProof.mk +C b1101363ff5893a696498f03f3b68d805314d5b13b8777d1308c2f077a91da8d Init.Data.List.Basic List.Pairwise.nil +C b16cb6ac301d96a03db6decfe3ecf8b5d814382e0ec11b6905fcb6d78778e9f0 Mathlib.Algebra.Group.DivInvMonoid InvOneClass.mk +C b2692658d7fd8675c394e972b5fe42ed949ab2cca216be8c7d6ea00173bcdb96 CertiFriP3.DomainSep CertiFri.P3.Blake3Domain.merkleLeaf +C b3a019d31e19ff22df5e8f38c940c919c2d0513f055c4dba6b48b12b350b91d8 Mathlib.Algebra.Group.Defs AddCommGroup.mk +C b3be3532d00b92ed248bbde42ea7c259b762475d533bb8dfe5dff10f95882fe5 CertiFriProofs.Refines CertiFri.Refines.mk +C b456ccef8eab479ddffdbe004b3894b9916fd9d0a28bb10625f0a57b1c5c9e51 Init.Data.Ord.Basic Ordering.gt +C b49831bb39774c9d33c297840d79b15f72604c996fcf3adcbc5cac56f14ca840 Init.Prelude UInt32.ofBitVec +C b50c6cd9fce14e8495cf6f0f25a7ba6ae8b40da23cdaf2ca04a61d2f93648e64 Mathlib.Algebra.Module.Defs Module.mk +C b52e258ebcc060030fa591a611cafe937a5e7603d34b426d10f831370c89c34a Init.Data.List.Basic List.Pairwise.cons +C b546ff36b2b7fb405b9b6c2bc00ffefa5819fbde7ba9dd6d13cb5d0c71d00809 Init.Prelude Prod.mk +C b584659df6977ecae22a273a5a7c69df8a2648e2538fdfefab0027eaa18913dd Mathlib.Data.FunLike.Equiv EquivLike.mk +C b7d27342fcca6621457b8ee861a8d787c7e24b4d7d8a625cbc1c6b9e52cb101b Mathlib.Algebra.Ring.Defs NonUnitalCommRing.mk +C b81704ddbfdc332edb456f0eaf29bee0006800055a9d428c72d0947d98350fda Init.Prelude And.intro +C b974b54b3f9fcdde955e84d0463adfb89688d084fc4d99f625356c98e66315ae CertiFri.Challenger CertiFri.Observation.ext +C b9fbe57d6dcb119209a7035c271c6f1743c3d699e464a916aff2bf2a7e583547 CertiFri.Stark.System CertiFri.Stark.Proof.mk +C b9fc74e48cb28c2a8215c2ca2aef1c5031279219d7b86abb8842472af353c712 Mathlib.Basic.Logic.Basic Fact.mk +C ba01e9ab0081b61fbb295af0dc1e9b0cf300067df143689cf1fa53e2a7b7fdbc Init.Data.List.Basic List.Perm.trans +C baca83f019beb64842eb0cbd59aec86c39953f15a581b936497baa3f3450829a CertiFri.Mmcs CertiFri.Mmcs.mk +C bb62038684cd8db23010c5913d0784483b6ed6dc00f571bf3b65ea5f8eeb3fd9 Mathlib.Algebra.Ring.Defs NonUnitalNonAssocCommSemiring.mk +C bba69c5b40ef2e87506f17e58c83453c607a897006a3f0e3f59b2d121b7f16e7 CertiFri.Claims CertiFri.PointOpening.mk +C bc236582a59d45ad92d753174a95378192b394e38f224fed48e20d1b86931beb CertiFri.Verifier CertiFri.Fri.MatrixShape.mk +C bc25b105290d678976e9f84c5703ab1ab6f7a1f96ed4c3f9375a6a19dd3ff933 Mathlib.Algebra.Ring.Defs NonUnitalNonAssocRing.mk +C bc27ff772b6ed94b317065fa060a16a5d1c717a55a25a1825f836fe847563021 CertiFriProofs.Exec.Stark.Preamble CertiFri.Exec.Stark.RowBudgetOk.mk +C bc83060a7bf1ff886e4b771b460fe1a5da4eea22a393a2c5367466d07a44aaed Init.Prelude HMul.mk +C bccefe62a63532fdf825cff1da5a433e150b0531d54ba4385b5b9c22a217953e Init.Prelude Membership.mk +C bd3a72a84cca620d30d229f14a5b350ec756d753a010dd37e79ea9c2dab75a9b Init.Core Std.Total.mk +C be362b96dbc9f3adbfe94ce9d78310d32a010b38e751716624a385d531b0eb5d Init.Prelude PUnit.unit +C c20a778239ff66131c6ba9404430a4079aa2700e8b7f7361812a29207b486bc6 Init.Prelude PProd.mk +C c221008c6824680e949972cd83a9eaf307f888e5ba4921b697eb59d1b6bcbc18 Init.Prelude Decidable.isFalse +C c2c7134437547c19c39b5eeb8c410266265322f40f7f02c0785d3084a3671e62 Ix.Aiur.Parameters Aiur.FriParameters.mk +C c3677f3781333b96a42b9bf857f37d72c7c309dd865168dcf5746428d0921a35 Init.Prelude ByteArray.mk +C c3de1ca1cfb590b4c928d763f0551875b1496eb0e750f0e570e57d3db3c2d39a CertiFri.Stark.Graph CertiFri.Stark.Node.const +C c45e48e1ffff889e0471b065611d5156d8377deff0d2f5e65aa3848e161ecd15 Init.Core Exists.intro +C c49e12776de3ed24240ff5b71f812f8a132b15641e8a7a49e87a0dfd6c705c88 Init.Prelude SeqLeft.mk +C c4a8dfaf94f065f7bfb1594cafe59f32ee49812dd1e391a5ee294775836eea08 Init.GetElem GetElem?.mk +C c5ed1b7fba751ec9516eddc6a447103e3feb2beb888919a27f4bdd23c61887b4 Init.Prelude Monad.mk +C c6bf5b6fd716d460134e39e2a3020c4781ba36c3b460a79053651074ca831e30 Init.Prelude ByteArray.IsValidUTF8.intro +C c75865a4cfd99b4ac2620ba784c98fe7232960156df38479c5a045ca4c0e768d Init.Prelude Pow.mk +C c773db6505d7d5b9b8024658a3225997b232e6056a469242488cf2b8382f1ff5 Init.Prelude Substring.Raw.mk +C c78be5c58d5dceb2c62336fd27f4e70bddd7c168930a56f6169448e5c9807fed Init.Data.ToString.Basic ToString.mk +C c78d6a919ff0518e931d19812e139e2f7388cb37e732a194d985aec39838bfb4 Mathlib.Order.BoundedOrder.Basic OrderBot.mk +C c790a88595d79b1e510e3c50491656b95ea4a602b656106e379355461885c3e9 CertiFriProofs.P3.EncodingInjective CertiFri.P3.Encoding.HashCall.node +C c9067f38094658f6202c5e199cdbfb31e3aecd6f0d37c257da1b02fce6bbb780 Mathlib.Algebra.Group.Monoid MulOneClass.mk +C cb2d556a9a5daa88119de550a60926f8528eab1eec14bb007a6bcab7cc028d37 Init.Prelude AndOp.mk +C cb8387e57c3a84e137cfb5fe6055884dc2a59ac4a9501eaf6d110392a2415c72 Mathlib.Algebra.Order.Monoid.Defs IsOrderedCancelAddMonoid.mk +C cbe4d1b6cc10faed3939f138a55fec153650408f2c108abe828571835c303d6d Init.Data.List.Basic List.Perm.swap +C cc6ef9e0e875fbf009b4055fcd827f470612d88e72f2cea8582f0cf4f263508b CertiFriProofs.Qrom.CompressedOracle CertiFri.Qrom.IsUnitary.mk +C cc9f270439020b56bdab1aa9f29c91e24893bcab81cc9a6d74557d4226bbbd46 Init.Prelude SeqRight.mk +C cd39b221db1ddcd176448ee953de445ddc15609832e52c72bea0e560c953a689 Init.Core Std.Commutative.mk +C cd7385088fb1aeeed78d7ce0cec24ec50d4b5e7739afe821044b66f18e39ce99 CertiFri.Stark.Graph CertiFri.Stark.Node.neg +C cdbd69185bb71a7ce0dce5d39a59b7e4a71efd633bc05cca2a6491516524024e Mathlib.Order.Defs.PartialOrder Preorder.mk +C cdd22d9305f26352acd5a65bc0759bc648ce9f06afc62e3496a9e40167bd4d39 CertiFri.Stark.Graph CertiFri.Stark.Node.mul +C ce6bfb39db086617bce783cbf30459d321accc0d7fb8df258a05c58ca7b7d2e2 Init.Prelude HShiftLeft.mk +C cf099c8c29ecb3c898f942d5df0a494fdbfadbefd116d9a93fa82c5159876189 Init.Prelude HDiv.mk +C cf25af1763f44037a306b8372af59dbdda608f42daf571ae583890802e03ca52 CertiFri.Stark.System CertiFri.Stark.BatchPreamble.mk +C cf26f14c420e3e0b4d6945a631aca4aa6257ad53bdc3e931e70b62c39c7a2add Mathlib.Algebra.Group.Monoid Monoid.mk +C cf2905a0d56bcc76aa45b7c381728ee2d1d46bcb578a0346fb30f97fcedd57a3 CertiFriProofs.Theory.Oracle.MerkleVerify CertiFri.Oracle.HashQuery.node +C d1236168116a9c1b168de8fe4d89f4f2b31dd5e41bb53177589b6d8385f58cc0 CertiFriProofs.Theory.Oracle.FiatShamir CertiFri.Oracle.Transcript.nil +C d1cd084484b5724c54207635f9387fdaa23c9a259a679f64a21bb31578a1afe1 Mathlib.Algebra.Group.Semigroup AddCommSemigroup.mk +C d1df7cde9d797a0e5d19bbd8367603907ce177a9d5d7081541392fb739524efc Mathlib.Data.Int.Cast.Defs AddGroupWithOne.mk +C d4b2240c75a7d7fb2427c107846b7538f6b28789f29a7db5f1ff52e68b95f9d5 Mathlib.Algebra.GroupWithZero.Defs MulZeroClass.mk +C d4cae6aa65b640b699b90909fceb35a130456900239d8ba7ca42016ad848e526 Mathlib.Order.Lattice SemilatticeSup.mk +C d565c341279b3278ca2494fea3337e2744957a8153eb298aff003a82b18a9792 Init.Prelude HAnd.mk +C d60437e641acdc6279185b591678098802c311a92f6ece03912005777b143fb9 Init.Prelude Sub.mk +C d62a3f847c94d207fe2e49b4508fcaf37510e737e21f2986ce4f2b0d85c0d451 Init.Prelude Nat.le.step +C d6568f23c37a910ca220bbdca8dd30b197543a15459c6f3434eb7ed8a97be458 Mathlib.Algebra.GroupWithZero.Action.Defs SMulWithZero.mk +C d67f779b22e3cc30c12b3a53597834fac908c6c90cbe5b77c55f556996e0c94d Mathlib.Algebra.Ring.Defs CommRing.mk +C d69a9d00547329c4ba5e07772ff6a4d91c7fff6777e6688003acf5aee0b345ae Init.Prelude UInt64.ofBitVec +C d7e78848c8785e55b399c558783a9feda93a98d42d5f3c0b75080f4d79e39811 CertiFriProofs.Merkle.Tree CertiFri.Merkle.Matrix.mk +C d8023dfd4aa5c511c028bbe555642b22c219144b0f448bbb23b2c76a00a363c9 Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.ofCoeff +C d88c5146cb99d7801a7b77e1b91b45719729c73868302f50f87c5c1864f4cf19 CertiFri.Stark.Graph CertiFri.Stark.Source.stage2 +C d90b6830ad345b75ee14497a3f843bfadb2d31f8b103e06354cf1bf989b2faf6 Mathlib.Order.WithBot WithBot.LT.coe_lt_coe +C da64a4dda269e7123ee6b60984f059236e6e39c80f0028c5d37bd6f3cc25657a Init.Core Iff.intro +C da64d66ac9937ccfbe14a6b1a228a49f694e91c1e52d540bb090902c107cd289 CertiFri.Stark.Graph CertiFri.Stark.Lookup.mk +C daca5891be3f7a555823c42ca477a76ebc373fa2b808d402b06c221cd52ac852 CertiFriProofs.Theory.Oracle.MerkleOpens CertiFri.Oracle.MerkleRO.Dig.pair +C dc074a34c7f1333231a97de10ad053723856e77bdc60342c822f52e1c55be597 Mathlib.Algebra.Order.GroupWithZero.Defs MulPosStrictMono.mk +C dc0887d5fc0877ab3c7fe365dfc0e41104d67dd331751dcebf86bea61e21fc03 Mathlib.Algebra.Group.DivInvMonoid ZSMul.mk +C dc678a1dde864cf683cf055294d87d1e543fd715b031dde49b5d2ba6cb5ee93a Init.Data.Rat.Basic Rat.mk' +C dc8280b7fedc5874bb0bcb26a4168f247937f1f77ed32561228889f64f4657f5 CertiFriProofs.P3.WireRoundTrip CertiFri.P3.Wire.KeyCircuit.WireOk.mk +C dda9719e038a0d19224bb194354d1e60d93526999efaed22495585ce1217e154 CertiFriProofs.Qrom.StarkPinnedQrom CertiFri.Qrom.SpongeDbBridge.mk +C de0c017de43611799ca193f7506ac97a4087c5614c88544eabbf1db14af12a76 CertiFriProofs.Theory.Oracle.MerkleOpens CertiFri.Oracle.MerkleRO.Dig.known +C e02fd3c47f65bcc32c30b538f932f29d25e15dc18c71cd8286d971e1cb8879c0 Init.GetElem GetElem.mk +C e0dc3a20134bef9ac41ceeb5f25210545117de8011cee6ce423174546a4ffc93 CertiFriProofs.Exec.Stark.SoundnessPinnedBatch CertiFri.Exec.Stark.BatchCoveredPinned.mk +C e3b24d6cf98b45a76975fab623f60135c9456ef857fb929e89993354f228fa19 Init.Data.List.Basic List.Mem.head +C e3d54b2344b96760ab7bd15122859fda9fae16acda17b3ed13c2c7250be9d898 Mathlib.Order.Defs.LinearOrder LinearOrder.mk +C e44b3f5d32374bdda9e65273ec29cefabf2a566c28a39b7e849492571a24149d Mathlib.Algebra.Group.DivInvMonoid SubNegZeroMonoid.mk +C e4598d3ad9a496b70765ca6bececa01b1b64a1ded0e72498ebb8f1ae3188180c Mathlib.Algebra.Group.Action.Defs SemigroupAction.mk +C e48e8982fd181bd08bcf86db9115de639c106f19160c4a9f5688aebadd7ef13a Init.Prelude Min.mk +C e555d6f5dd7dc59aa3978194ffd0746597e650424861a1a8ef908c2da5497028 Mathlib.Algebra.Group.Defs AddGroup.mk +C e562dac2c72b577439aaff63bf0373a6ef455d8d03b6a8e5be51ea714fa4dc2b Init.Prelude HPow.mk +C e6c4e9988c656b177229648414f6199c234a3c93a1020a0d02d7372fafc57ed0 Init.Prelude Bind.mk +C e80496a0c5f8ae17ea2857902adac62d7d5f0a2e8501e9204aac20e4b2d30299 Init.Data.Array.Basic Array.Mem.mk +C e9be906140edb172fd264d1495eb3a96160fbed57559a2a95fe27599bf8b6d55 Mathlib.Algebra.GroupWithZero.Action.Defs DistribMulAction.mk +C e9ffcae33cac13d87d53516bd4e95925428b0d2c0acbd097be843dfda6e3154d Init.Core Setoid.mk +C ea69b36e2e96c04bc328d0af414324b4b476911efc9e73cf7a8826a70a9a1381 Mathlib.Algebra.Ring.Defs HasDistribNeg.mk +C eb7c56b3dc4d0b72d6725209124ffc70d1770110dd72426945a36ea1f5372cf7 Init.Prelude Neg.mk +C ebd6821525490303cca7765d32ae6c4bc3715fe42fd79e34430466e19d49ac59 Mathlib.Algebra.GroupWithZero.Defs GroupWithZero.mk +C ec76b76c9bfd0667c3844ca2c9ad3231ab38740476080b55340d7eea76de23f8 Mathlib.Algebra.GroupWithZero.Defs CommMonoidWithZero.mk +C edce51f8ef79bbb01209f0c667071da166061a35a8fcfbeaa1e1fcda0165dc58 Init.WF Acc.intro +C eeca465b0f14412f62a396073ffc509e39122b377764de835d1743b92f34c45f Mathlib.Order.RelIso.Basic RelEmbedding.mk +C ef708904d81bb94631d2f3b3db8bbab438c895946cc2e476fcfe6c6f0b85d8f2 CertiFriP3.Digest CertiFri.P3.Digest.mk +C f054a61451f29ee776484f268a0407d4c8e1bf0f9d902f2d77404b5150ff9ca3 Init.Data.Ord.Basic Ordering.lt +C f101d87d7f1bfae387a6e101617b1dc6600eee740f802552890f43dcda823dcc CertiFriProofs.Theory.Oracle.Basic CertiFri.Oracle.OracleComp.queryBind +C f1d0b8a869d1f6ac840671396dd2609e7ee8857ef63148bd184079f8c5d704ac Mathlib.Algebra.Order.Ring.Defs IsOrderedRing.mk +C f22a9fd207bc36b1b3e1caaf69bd1b9724fb7400f6e2489e8b961e9ffd93424b Mathlib.Algebra.Ring.Defs NonUnitalNonAssocSemiring.mk +C f23488a1b965c62e7cbf7fd601fde849271bef0ad82d5cfb35550969c8a87332 Init.Prelude Lean.SourceInfo.original +C f37e6ab465c934369e04b6b3633579f4f12e0f6a78003044e51ac33bafa3738e Mathlib.Data.Finset.Defs Finset.mk +C f4fdb1542bf81e5c92a97211e3f409359d5033eb51209b2ec22159384bbf3e49 Init.Prelude Dvd.mk +C f5cd8287b2a5ee68fb5a5091607cb704bd5445620c5dd657ad3dba67998de124 Mathlib.Algebra.Order.AbsoluteValue.Basic IsAbsoluteValue.mk +C f60aa135ea9fa5e0bb8de48b8550c947800c07993c960fbf169ca4ca40354559 CertiFriP3.DomainSep CertiFri.P3.Blake3Domain.verifyingKey +C f64ae97c446640f72653bebca71ddcd26d182275a3922ff5c160da401ad9c06e Init.Data.List.Basic List.Mem.tail +C f684efdb925053b0d38e3dd861ff21ee9790538f445efd7a339c6a5316e996ac CertiFriProofs.Theory.MultiArity.CompiledTensor CertiFri.Compiled.MultiParams.mk +C f7653f9ef8e8243f4b9e9e3df2a754c4f04c328926fa2d674aa05ebe0e9b4473 CertiFriP3.DomainSep CertiFri.P3.Blake3Domain.zkTranscriptSingle +C f7d0dd20ad629282f065d6bfa428032f5552465a34e0f5efaa25ff34a773a2c6 Init.Core Subsingleton.intro +C f7d7c2809296290070d60ab7554cb1bfd0de43e9f4ac1745525731beeabfe333 Mathlib.Basic.Real.Basic Real.ofCauchy +C f7fb98612c25842f8657e8914d4a07eb1c57b24ad3eb6aa98b7a6a0d8a4a8fad CertiFriP3.DomainSep CertiFri.P3.Blake3Domain.zkMerkleLeaf +C fc1a3ad3b966876a5d18007cc7d9f5d91ae4bf3de6a86a1b5a00d22c9e570cc9 CertiFri.Field CertiFri.FieldOps.mk +C fc75a02cca8189d4a1ac6eb2b4f21bd659d2dfcca0a00c739dcbd65d7b98c287 CertiFriProofs.Theory.Stark.Air CertiFri.Stark.Model.Columns.mk +C fd0286540a8c4010735b61b5e5cc4ed1561f4eb1ecdc1fc3a77ad1c4df13424b CertiFri.Stark.System CertiFri.Stark.Circuit.mk +C fea2db86b70a818f63904c8560ef140c6b55889db4ea87cd581475bc1f1447bf Init.Prelude Inhabited.mk +C feb917b1aabd888b4b627e48f056d30d58593bcd6f09abcb3368025eff085b1a Init.Prelude Nat.succ +C ff07496cfe6799ba479620831d92bfdd2f6be4f73d792531b4d6b1819b999d80 Init.Prelude Mul.mk +C ff0a4071c3044fa0ab19fd1164486c9a8700d74aca83fc0aa2e229e7bee1ff8b Init.Prelude Seq.mk +C ff5454488eff15583ba71bb2d0692af4978dc647e506a1b3b398024a559c1ffa Mathlib.Algebra.Ring.Defs CommSemiring.mk +C ffc487534c4b04587501530c7d17a5a95e8923e8ddc26b867526b8cf5ada08d0 Mathlib.Algebra.Order.GroupWithZero.Defs PosMulMono.mk +C ffd132cb05a8a97f6fa89c73e3abf20155c9cdbff58e1af1d6be2b2a754912b4 CertiFri.Stark.Admissible CertiFri.Stark.Profile.mk +D 000b806f5cf9e4b20bb3f8a05887cdf9ad57021290fb539d7babe52cfc0661a5 CertiFriProofs.Exec.Stark.Meaning CertiFri.Stark.Circuit.LookupsPlain +D 001399248cee8542407ef61383d5bdc441265980bc99a2387b06ef910fc167a9 Mathlib.Algebra.Field.Defs Semifield.toDiv +D 00498cbaa810ad4a2d830d6e6611221657bff9fdef70aa0b8b548c37522953a3 CertiFriP3.Wire CertiFri.P3.Wire.numPublics +D 0055d8fd24e09b6c2d2e3ca4ff8a3b99d1a032fc7e69d8ad58ffaf7b51b8fc1c Mathlib.Algebra.Ring.Hom.Defs RingHom.id +D 00659a5a53c4088821a5b2afa68cf33979b9d7ae6c3859f94d4f7a32a7429cd1 CertiFriProofs.Exec.Stark.GoodLogTensor CertiFri.Exec.Stark.STAns +D 0069101d774595b0a8a81e050dae44bdf40e494ad05ae328d17220622c5ce819 Ix.Aiur.Parameters Aiur.minProvableUdBits +D 007d1cf76dd953075a2141cd2a0c05e52bf77c9b9f0748eec55165752bc84ce9 Mathlib.Algebra.Group.Monoid NSMul.toSMul +D 0090ddd0070bd32a8d03cae0c652aef2a4c36a8361211b2df4dcb41662352eab CertiFriP3.Challenger CertiFri.P3.ChallengerState.sampleBits +D 0093e84b8c308ac99432402242009383a7f8cf8fa5ddd21ed4e206d0d4168d32 Init.Prelude UInt32.size +D 00c106f03bb1be913baba442c54cf864116cfa372815e89ee30fcfbb0d70c02e CertiFriProofs.Theory.Compiled.Read CertiFri.Compiled.Slot.col +D 00c8a239c368ff8e4116812b9b3f2f08d33ac1fd70ade40fc226a7a4f0097e17 Init.Prelude Lean.Name.mkStr4 +D 00eccf1514174657cad09145a51b5aba384c485e486912466e729507fd27ec98 CertiFriProofs.Theory.Oracle.MerkleOpens CertiFri.Oracle.MerkleRO.Dig.ctorIdx +D 00ff07be2ea08d487f7a84dcf772054cfb4afe8508569e6efb0335b7854b7988 Init.Prelude instHSub +D 016185b7e68716cef6dd8f79bde292b7ebc09063c992adaa96857128d58024ab Mathlib.Basic.Real.Basic Real.instInv +D 016bd4bb22e09669fad040f0c01ad75bc656e38dbcd714fc35e4d727fe8390a2 Init.Prelude Decidable.decide +D 0178ea84dc758f1eae85d5988fcdd6e2bbd6e4c3dcff5777b4b09a68f863a1e9 Init.Data.BitVec.Basic BitVec.mul +D 01910cb6f6e9c9cde71fed8191962e198a59f195bce8796ab0c79c214ad95169 CertiFri.Stark.Admissible CertiFri.Stark.Admissible.logDegreesOk +D 01aefd6e54c2aff3e83ea47859b7ab9d4662a96a45aca191560c795254aad9db CertiFriProofs.Exec.Stark.SoundnessPinnedSponge CertiFri.Exec.Stark.shardCompPinnedBinSponge.match_1 +D 01bd7fcbdb0447f480b5b1045be5ee9b5c484450550718b6c074dd7f4538b414 CertiFri.Stark.Verifier CertiFri.Stark.Selectors.isTransition +D 01cc0774e6ead46cda63bcb10906fd346dd47e8a514aff68841bc17a380adb70 Init.Prelude UInt64.casesOn +D 01df567eeb301d376f491e07beb6abd51dba93fb06d16cf4489587b54bb96ee7 Init.Prelude Bool.casesOn +D 01dfa777a400890990268e927b595a66c06772b05bf96b6d93e97b4a61d6f6b7 CertiFriProofs.Exec.Stark.SpongeGoodLogTensor CertiFri.Exec.Stark.spongeToFS.match_1 +D 0208b4a431a031a6f4340ebc4f4406937a260e10876864152f7fe078e7e9641b CertiFriProofs.Exec.Stark.SpongeGoodLogTensor CertiFri.Exec.Stark.spongeRunSteps.match_1 +D 021c4372d480c27e47b2ee7ef23cd98d7404c5c74fae3eea0511d29e6d9385ee Init.Data.Option.Basic Option.instDecidableEq.match_3 +D 022c35f67854564dac824884c054ed45013825844ac247740c1c4807f9ca3e3a Init.Prelude Applicative.toPure +D 022e51b24855080162be4d0d059908e6d460651c0db825b2b83984b78c7e7fff Init.Core Empty.elim +D 02446bd00baafe47818ba32e635668df88c4ef707bbbcc7d0701c43920916b96 Mathlib.Algebra.Polynomial.Basic Polynomial.instNSMul +D 025fa619961daf5de0a500e77569b0581b53583fcb2d08eb747fee4bc107454f CertiFri.Stark.Pinned CertiFri.Stark.verifyBatchPinned.match_1 +D 02822a8024a825fcf3046cb62cb440b9d96a28247df08ca327adc5fe855d1eaa Init.Data.List.Basic List.zipIdx +D 02a0971f71dfb51b1c008f084409a8dc7174b1f3758802e24cf4e8bc9fa4544c Mathlib.Basic.Complex.Basic Complex.ofReal +D 02a88a1ea1a0839d1de31e50c85f3d4a58cf9dd08fa055d0bad77e5354719d43 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.norm +D 02b672f67e30955d6469bb90bf4c72be055a379d2e7761f8c917b37da0b77681 Init.Data.Rat.Basic Rat.pow +D 02c3504a6a1aea900f352c641916e0b5ba79bf2e330bf749b4280fe011ea6e88 Init.Prelude List.map +D 0303de3dde3332660ed34e2acd38fd3e3bc361d53fa7deb7593b223800459a69 CertiFriProofs.Exec.Stark.SoundnessPinnedBatch CertiFri.Exec.Stark.pinnedChalsOf +D 030615666291e54c1232bd67362f88cd0e5b863a790537d1d915eab3960f37f8 Mathlib.Basic.NNReal.Defs NNReal.instSemilatticeInf +D 030f2715963aff29cb2d10d9ef71af5b5d39b1000be5f9e8d7410705addea081 CertiFri.Stark.Logup CertiFri.Stark.lookupMessage +D 03127597ff65bdda6844209b4144a1b1c40305afd6b124dff3ef51c1e5a3c36a Batteries.Data.Nat.Basic Nat.strongRec +D 03146fd1f3cbc022e3672c6f7489672f08e08133ec3ad38a738cfb3249f540fc Init.Data.List.Basic List.all._f +D 031f1fe409f1d993aaa836538df830bd9e6d7280017dda5c90d8f453d9a36db2 CertiFri.Verifier CertiFri.Fri.pointRefs.match_1 +D 032e9df23d7f74cb8e58fe1cd0fec4e0a5d9dc5852166cb51b36c7f5f35dfb8a CertiFriP3.Wire CertiFri.P3.Wire.encodeKey +D 0368bb77fa71b9c4afdcb645784e74a9ffe69f7c4b1cd657561ae2e28013b953 Mathlib.Data.Rat.Init NNRatCast.nnratCast +D 0379c2f1318ab6852f84f28e208e852f2e475bd2b281fcd469dc3db60f1d47a4 CertiFriP3.Wire CertiFri.P3.Wire.uLE +D 03b9f28a411e6fa85e0128f05ae51620b14a6af7374243c00c1af900a1208c72 CertiFriP3.Wire CertiFri.P3.Wire.Decoder.ensure +D 03d94f4574f9ae933dc0999ef78b3bb11c1ee7ae8247c57c570580b183a290e1 CertiFriP3.Blake3 CertiFri.P3.Blake3.pushChunk.match_1 +D 03e92347373150dfd7213870f1c2bac4572538e8ccabe1befbef4c8ca8b1e1cd Init.Data.Rat.Basic Rat.neg +D 0408126edd4eb54fa3155b30986b716fed2164e7ceb7d5b056872d703c4c1d61 CertiFriP3.Wire CertiFri.P3.Wire.Key.params +D 042aa7f74f698019fa8ebf8d47ed9bde60447221826d83b382d2f435d04769a6 Mathlib.Algebra.Ring.Defs Ring.toSub +D 0434b07d04572fea789720ba5164a288dc327dc06198b3b799bc83038502b5aa CertiFri.Verifier CertiFri.Fri.commitPhase +D 0444d82dcf6458f2c1e5976766d9081f451d5e559daefbf6a869360fde151ec4 Init.Prelude dite +D 0446f00c6e099242f4e86842ccee80259a10d9ceee41746dc32aad094a1ee4b2 Mathlib.Logic.Function.Basic Function.Injective.decidableEq +D 045280bd394daa85914c06a4bee5f4d6f132e267bfc5f7d6594613c38d3522e2 CertiFri.Merkle CertiFri.Merkle.verifyOpenings.match_1 +D 047ec70a60c559597fc5c1a3bd0d42ad45dabe10ed2b250ba3b23ce36690d540 CertiFri.Field CertiFri.fieldOfNat +D 04a63ad849a4474ce0e3773a89e8766c369008710ea1259549ca6547a132696e Init.Prelude instMulNat +D 04ab286eefa0a0d205f4db6925d1c5653ec7054dcb4a2a3835df48ff6bb5435b Mathlib.Algebra.Group.Monoid Monoid.toNPow +D 04b0b7af63fd2e58c5bf6c8635c48e1b7e95d26b4abab6d625ff038fe4a8779a Init.Data.List.Basic List.instMembership +D 04b2e8b98fd6984a1a57c66a1c47c73076aacbb412f3cc9f1884413fdadca40f Init.Prelude instAddNat +D 04cfb37ad688ec4d2b93ae3eb507ca29a0848cdb1a9e6218caa909032080ede7 Mathlib.Algebra.Group.Monoid AddZeroClass.toZero +D 04d4274c0c9af1bba07d81787bcf0420f0d9b36224e302dec0190454f6a285cd CertiFriP3.Blake3 CertiFri.P3.Blake3.deriveKeyBlocks +D 04d595eac5bdbd119f8d789b139d72f0943d008e01cddad1f53a93a9d939d63a Mathlib.Data.Set.Basic Set.instDistribLattice +D 04da51729ca511f40c551518e5a5e04bcf06a83391ad2f620d47b5cfa546990b Mathlib.Order.Lattice instDistribLatticeOfLinearOrder +D 04db1df0deb7bcfd202e0da7f64a035d5c33b3db478b22d484bb3d742ad6421f Mathlib.Algebra.Ring.Defs NonUnitalNonAssocSemiring.toMul +D 04e5ddeb0fc86a5fa0e2173527bf47714b6358fdd3c327c4e0f862e2eef0730c Init.Data.Function Function.LeftInverse +D 050095408c03732eba7e7ee9cf5524a779ded9c1d62a3a499b5f67855132c268 CertiFriProofs.Exec.Stark.PinnedLink CertiFri.Exec.Stark.starkShapePinned.match_1 +D 050a0aac3e43c3abb16c4560c3640b133ea1b92289dedd20404411244ddc38ad CertiFriProofs.Exec.Stark.SoundnessPinnedFixed CertiFri.Exec.Stark.fixedRootQueries +D 0519aa149074bd99a31a334d3d4361175dc0a5b93b821890c3a4deaafb923276 Mathlib.Algebra.Ring.Defs CommRing.toCommSemiring +D 0522385c954bd113d43ac389d419bbaa4eebaddfd48547f06265fd80c47d5ade Ix.Aiur.Parameters Aiur.johnsonMillibits +D 053ef217ca740c99f6bc0773c12a356e1d55758c1ba0f56defbb284395ec6d83 Mathlib.Algebra.Field.Defs Semifield.toCommSemiring +D 0547e7119a732d461f6dde4651f31483b95ce3dd9281454d78418fb58b087554 Init.Prelude List.casesOn +D 055c1ad6514be89bf953425600233179184b10dbce179c2905356f916dcd37d3 CertiFriProofs.Exec.Stark.JohnsonBall CertiFri.Exec.Stark.circWord +D 055fae5a049b0291cd2c8e09d6937db6905c979e49130213603dea8bcbe038e2 CertiFriProofs.Exec.Stark.FreeTensor CertiFri.Exec.Stark.uChallengerTensor +D 057713ca7999614d060f3d5e4f7f4e941290fb3cadd924163a1eb1fd701979d8 Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.single +D 05a7bc23374e07532e2d050f8533a7a7d9a3068770db4efcf54ef9b7dbed4554 Mathlib.Algebra.Polynomial.Basic Polynomial.commSemiring +D 05c3d064fdef582057e5e57619fab6592b14676db4d87e3d1f729074e79213ba CertiFriProofs.Exec.Stark.State CertiFri.Exec.Stark.chalsOf.match_1 +D 05d24906e300029f8fc17253102a11c80cdc6d424839e0757b3b2120766838e0 Mathlib.Algebra.Group.DivInvMonoid ZPow.zpow +D 05d99f6d4800b6e8f3f65372d242070ac60ce0fbaffae8c9ac090d9c22b8e49d CertiFriProofs.Exec.Stark.StateTensor CertiFri.Exec.Stark.tFieldAt +D 05e81c2b279ee2aba5b8cf9e5ed13cfa0f629dbe360ffd0b49b48bd3009c72cb Init.Data.Array.Basic _private.Init.Data.Array.Basic.0.Array.mapM.map._unary +D 05e90ae31ea7f6a81bf8f37ed6bd47f6eb215818da3ddc955c731bdfacb49c95 CertiFri.Stark.Graph CertiFri.Stark.RowValues.var.match_1 +D 060a3eca8912dba64a4879bc895322209868985e03891c5aadbfffbefb296645 CertiFriP3.Blake3 CertiFri.P3.Blake3.flagChunkEnd +D 061a650df605351618e24b9f0f2d7cd18f68c7d034b96cdedbed4883a0ec9d3a CertiFri.Pcs CertiFri.Fri.claimValues +D 062eba36a912cac91e0a0ab7fd63fb3ca1dcfc4afa967146f875efcccecc228e CertiFriProofs.Theory.Domain CertiFri.pointOfIndex +D 063566a6eb6db1bcebdfeddd35ba12f5e11fc71f60546ff5406bd207e80fe9c4 Init.Data.Option.Basic Option.elim.match_1 +D 065364c2dd27efa783e52f17d0fd314406977fe00cfc41cc5fa0747b617202d8 Mathlib.Algebra.Field.Defs DivisionSemiring.nnratCast_def._autoParam +D 065617f5a7ce3d27b5f23258cdfe0632916e0740b6a486894f074c7ac1c44f3f Mathlib.Logic.Equiv.Defs Equiv.toFun +D 066c96ec1e0760d49e0a8d510ed1243a99c21005a89d2a76b9d0ae0f0799dc14 CertiFri.Proof CertiFri.FriProof.finalPoly +D 06715d9d2a9c3c8235f9af9c4b266cb22b6093d59d1ed80c6e5bd9f10939003f Init.Data.List.Basic List.insert +D 0673a2fe583b978b544acdd9edad6c74b57abf1d8e82871938259118d2634a11 CertiFriP3.Wire CertiFri.P3.Wire.shardProof +D 0675b2f58409d30a2c68a8138f915b2a1c799d69a58d74c1fc859dc6a6ebd7c9 CertiFriP3.Blake3 CertiFri.P3.Blake3.compress +D 06bc05fb10734f0f9c4f6ad4420d0a28eccd316dfbeb1d1cf327829ccd59a410 Mathlib.Algebra.Polynomial.Basic Polynomial.instOne +D 06d0702bde443d1f24d3e42a18f4b77b9b1eecbfc61ef2ec42c50f2ef910e159 CertiFriProofs.Theory.Stark.Logup CertiFri.Stark.Model.logupValues +D 06d331e9e01c976eb19da158f46b6b0aa4ed6166236fd9e55f5c973fa4ad855b Mathlib.Algebra.Polynomial.Basic Polynomial.toFinsuppIso +D 06eed708358d8a90c86d95980eac10fdab99697f169b1801e6d596636ea71d7a Ix.Cert.Release05.SecurityAudit Ix.Cert.Release05.IxVm2p23_4096ShShape +D 06f95f7e4505421598637f18e46ae8893a4fbab09fe99099afe8cefea5779601 Init.Data.Nat.Coprime Nat.instDecidableCoprime +D 06fafe45554144507508291ac3f9b22a4455bfb4e2c424c858598944bfb6c0b1 CertiFriProofs.Exec.Stark.BalancePinnedBatch CertiFri.Exec.Stark.batchItemsJT +D 077ab30247d90adaa454d8d40190a3253963f0bcbca8a9f3c4918ca0509018d4 Init.Data.BitVec.BasicAux BitVec.instAdd +D 0788a5191c1f465cfdd63c27d389c2c76b0ff9321861bcca09fb8c42388feebe CertiFriProofs.Theory.Stark.Logup CertiFri.Stark.Model.lookupMessage +D 0799de4c2de6f7c25968f871da4af28eb5d8a1f31976ef3050285844764c157f Mathlib.Algebra.Group.Monoid CommMonoid.toCommSemigroup +D 07b3edc725f2182ffceac18d2f245d4f3350bbeedd1afa7a219040fab72cf5c7 Mathlib.Algebra.Ring.Defs NonUnitalSemiring.toNonUnitalNonAssocSemiring +D 07b4a4326755b2a1ec4eab95c774e3f6f13f15abb8f2e191b2dafe1d3b963d73 CertiFriProofs.Exec.Stark.PrunedTensor CertiFri.Exec.Stark.nodeParentM +D 07bd5f67b42b50edb197b75f7735978730cfada5ba491e43ef731900d1128cb1 Init.Data.Rat.Basic Rat.instAdd +D 0800c0a35dc83514f5bc2201428242c9824af4f09ccc596bda14f12e95c4516a CertiFriP3.Blake3 CertiFri.P3.Blake3.quarter +D 08054180fc33ab3301314a34541d8fcd575341c1e949d1eec1f31a38595652f8 CertiFriProofs.Theory.Stark.LookupRoles CertiFri.Stark.Model.senderOk +D 082e009a11e35c106904e3fc266a606fe6da43d2e17d35b67247058cdc81eebc CertiFriP3.Goldilocks CertiFri.P3.Goldilocks.instTwoAdicOps +D 0839764aeae4f3988a7c5377c2e484615122b92f5c1f08b13fb0b0518ebdd126 CertiFriP3.Wire CertiFri.P3.Wire.KeyCircuit.graph +D 086096eb38f6dd799a6707b17725c19ffe51e466a51d9903883a168c73f94588 CertiFriP3.GoldilocksExt3 CertiFri.P3.GoldilocksExt3.toBasis +D 086b0949ece332559f81b8eaf6771dce095d4268074f84e3906033a4c764811e Init.Prelude List.append.match_1 +D 0878a19c34659b8f3f4cdc9c9d1a4f0668a8c76c5d44fbe54ea1b1876b4d000d Mathlib.Data.ZMod.Defs Fin.instCommMonoid +D 08bdac0005f65e6bd83c19b51b7ed7396d395bc3168dbb6cb0ae8aaff10ce98e Init.Prelude panicCore +D 08db8db013dd211eeb0611ce542dabfcea4fea6c58e05bd545c6f929bbf1ddeb Init.Prelude Nat.add.match_1 +D 08e20db78ef88216d80813dd3886f60e808dab8cccf9aeb4b17ca3f52c6dbc96 CertiFri.Stark.Statement CertiFri.Stark.Model.addChan +D 08e93c8727b0aff9cba26add57338f3821f0c23f3eae90b13f691624a00d0cac CertiFriProofs.Exec.Stark.FixedKey CertiFri.Exec.Stark.fixedMatrix +D 08ee599d6ff3ed66dc6652e96e036a6b8bfeb8070875d1472fd9f56d5b17fc66 CertiFriP3.DomainSep CertiFri.P3.v6MerkleLeafContext +D 08fc1b043ef6c8fddaeeda49d163a90310cbd3c2cc80f735a638563b278ccc2c CertiFriP3.Wire CertiFri.P3.Wire.KeyCircuit.nodeBoundsOk +D 090bcc084841143ae495fea136edc22f36daaea7e0518ccc65cad17369962ffa CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.sub +D 09162b818e21fc58b93cb213b6758f967b875d2380576c49e20c2c62b5306e34 Mathlib.Basic.Real.Basic Real.definition.match_1._@.Mathlib.Basic.Real.Basic.4282658333._hygCtx._hyg.2 +D 092fc0dc19d4cbacfea6621072562181328fd46a7484a2b518318a97b0cd64d7 CertiFriP3.Wire CertiFri.P3.Wire.encFlag16 +D 0944e2f6fc4c37256883ddf2df78981dc6d5124ac7f75a976be5b1034897dad1 CertiFri.Field CertiFri.FieldOps.toBEq +D 09866fbdea0327f21e429040cbde87eae2a268eeaa8fb660483e917dabfd8025 CertiFri.TensorBatching CertiFri.Fri.sampleExtMany.match_5 +D 09890fc3a2d634ac5bb0fdf53b4dc079aac4d9e1a0d327754650c0a3d93320aa CertiFriP3.DomainSep CertiFri.P3.v6ZkMerkleLeafKey +D 098f452be6605c45de4efb652770fa607f1f612fa9d9f7b347c91f34dd897348 CertiFri.Verifier CertiFri.Fri.foldChain.match_1 +D 09985d670481330f415cb9f0952def4a9ba8a8fb3720e8c61467e8e45d8afa49 Ix.Aiur.Parameters Aiur.defaultCommitmentParameters +D 099eb2099d8b9dd56a6f7d0c8f3592135e6768a6854307aee29f139a23131186 CertiFriProofs.Qrom.CompressedOracle CertiFri.Qrom.measProb +D 09a6efbd0db668befa7fdd8bd282a81066a29bbb8317b4c1ddb0a123896b9dc2 CertiFri.Stark.Pinned CertiFri.Stark.openingClaimsPinned +D 09cdb682210620297e0476aaef0f8c1920144c0434cf460413200d4f3115e87b CertiFriProofs.Theory.Oracle.SpongeCommitted CertiFri.Oracle.spongeCommittedRow +D 09d705327b2e1384b8e70b6c91106b0e913486c161c0998e013fc4fcd19f6e99 CertiFriProofs.Exec.Stark.SoundnessPinnedSponge CertiFri.Exec.Stark.restorePinnedPathsHashM.match_1 +D 09e2d850f479727db95c88cc231509a07ca8c87f487c8834ac068c6cbe3a5245 CertiFriProofs.P3.ByteLinkPinnedFixed CertiFri.P3.ByteLinkPinnedFixed.keyedAdversary +D 09e6bd839237e2a9510affbf5f8b2562a54c6f34a0fc125bfb0d7b66bcf27274 Mathlib.Algebra.Group.Int.Defs Int.instMonoid +D 09ebefe63d94275903de56614250815b93b66d22e7c01180708f55ca8fa2c398 Init.Data.String.Defs String.toUTF8 +D 0a0581535c1141a577a4c82a48326751f669ddeee773464db5e0e7c0e2229c21 CertiFriP3.Goldilocks CertiFri.P3.Goldilocks.ofCanonical? +D 0a0f228e49d1d555284d3be8e00c86279815f0a7d5bb190fe6a518bab2d84e9d CertiFriP3.Goldilocks CertiFri.P3.Goldilocks.one +D 0a13b3f29273d5e28359072b9e7f62b41d11ac6441fa84958c5652c40f560269 Init.Data.ByteArray.Basic ByteArray.toList.loop._unary +D 0a17cd90d5300c760de0019d4388b92b581e4a2988236fa13fc4c895126815ef CertiFriProofs.P3.ByteQueries CertiFri.P3.ByteQueries.merkleQueries +D 0a36350ecc8ee1e08966b71ec205def41213617cb0376db19a5aea205e97a706 CertiFriProofs.Exec.Stark.SoundnessPinnedBatch CertiFri.Exec.Stark.shardsCompPinnedSponge +D 0a389904d8fb1cc750feb50ef78baa08d937be537584fa71944490ccfb5192b1 CertiFriProofs.Theory.Oracle.FiatShamir CertiFri.Oracle.Transcript.brecOn +D 0a5777f80e89dd8a4ec81df03970d076ef26cf9d8786dceed5e7d160e42cb3b3 CertiFriProofs.Theory.Oracle.MerkleVerify CertiFri.Oracle.MerkleRO.allM.match_1 +D 0a6c05c813030ccef6aa330da596042e7f911b4b51074fc8049f33473011b532 CertiFriProofs.Exec.Stark.SpongeGoodLogTensor CertiFri.Exec.Stark.STAnsSponge +D 0a82479a7edcb1b68e828d2330bbf0c8e7482b99b2dc3f993e097741d7843bd0 CertiFriProofs.Exec.Stark.Preamble CertiFri.Exec.Stark.Bounds.claims +D 0a841d7c34da1c1d49e4299618966c4a0c24cf36413e0c766373d8926c40f9ee CertiFriP3.Wire CertiFri.P3.Wire.KeyCircuit.validate +D 0a88621f418650cf7915ab35465376e8c6911dd11757122c3d2ca5bc11bcbd91 Init.Prelude Nat.lt +D 0a991aef6af41a71799b0a91b7597feef8b02756775a6f4f64cb2afabe137be1 CertiFriP3.Wire CertiFri.P3.Wire.Decoder.bind +D 0abc26d55b06355a9663dd30e5bc7f0c547a45b090697e29392ba7d76a1c03b1 Init.Prelude DecidableEq +D 0ac0759aa49f6fabefd927759d9d660e62208b4572f01be0ea7d49eb6fca2cb5 Init.Data.UInt.Basic instShiftRightUInt32 +D 0ad368d3ce5c9f08374483d8b89d545c9840550443255d4b994955abf73b96a9 Mathlib.Algebra.Order.CauSeq.Basic CauSeq.LimZero +D 0ad986f951b4b463583e43f289ff3158a0f58208a563e64f435159dd8d868618 CertiFri.MultiArity CertiFri.Fri.placeRowMulti +D 0adbdcc1ae63bb210df1f9c7a4185d36d8ef677c6d7ccca030289db0df584a5a CertiFri.Field CertiFri.TwoAdicOps.twoAdicGenerator +D 0adfc92d63edfd524329df32cb1e69249dbb2b4f7fd531b94b1dffc97331cef0 CertiFriProofs.Theory.MultiArity.CompiledTensor CertiFri.Compiled.MultiProof.inputRows +D 0ae970e7c36ea095e317ed8002d2a041313a9dc1fadbad2f03ecf6db97443c04 CertiFri.Proof CertiFri.CommitPhaseStep.siblingValues +D 0b04da0eaf8975a23b37346efe43def2135542f8b6e595d9ce35c5c8fb1e3957 CertiFriP3.Challenger CertiFri.P3.ChallengerState.observeBytes +D 0b0d6dd65c2208c4256781942985b34e880a96d1c63792ad235ed02b82f7cd44 Init.Prelude ByteArray.size +D 0b1e5f59c773cfde109b6440b6f4fc4217eb7b14566a1e3e30ba335cde2c86d7 Mathlib.Basic.Real.Basic Real.instMin +D 0b2fbeda8743bbb2930ca8e3c3960744ce84ae0b6812c6cedd275ce1d839a22f Init.Data.Nat.Basic Nat.instMax +D 0b80a413d85457f84a8ceac38f3bc023f6b91026161f0681b4e0e74f73ac038d Init.Prelude ByteArray.emptyWithCapacity +D 0ba9c55303ddf25ed1d2bb83d9f16a5db27a2b0123de93ad93c97ceffc807e36 Init.Prelude List.foldl +D 0bc915b0dde0cb5bb2947cffd6989b5a8d4f67feeded9d018f2b34a855e86f80 Init.Data.ByteArray.Basic ByteArray.instDecidableEq +D 0bce9691d05f32cf28c4767ecfcdcc2d9bdcd7a24d5ce308035667d23c13085a Ix.Cert.Release05.SecurityAudit Ix.Cert.Release05.Release05InnerProfile +D 0bf007d428683c9fd1f96d527d0e3fd82ebb6801d250a5239d084f67afc1f459 Mathlib.Data.ZMod.Defs ZMod.commRing +D 0bf75a8a1efad5196cc1e8351bd46678b4a70b0ec73d8c5022e39b8c87816899 Init.Data.UInt.Basic instShiftLeftUInt64 +D 0c14443697c17cad8100f0e7977c662c25052f3a89fe5ebfdea93e5a581ad110 CertiFriP3.Pruned CertiFri.P3.Pruned.Node.index +D 0c19fb2316aa565efcdc6a70d762a043f01672ea2c40f4fb16a64d9a686fadc9 CertiFriProofs.Theory.Compiled.Read CertiFri.Compiled.Msg.commitRoot +D 0c1a83930d612da1da55b417db3a7973b88d9979b4780a8c1ea286a627f18e28 Mathlib.Algebra.Group.Semigroup Semigroup.toMul +D 0c1b4feb6b58af4791925cdfe3d0f4a658889096981559e490861a14a55d21d7 CertiFriProofs.Exec.Stark.ShardGoodPinned CertiFri.Exec.Stark.pinnedTailMsg +D 0c23ef0afff4c30087dbc6c1754d253ffdaa239d09a6a6ec4c805f13a4cfccd4 Init.GetElem Array.instGetElem?NatLtSize +D 0c27d3aad736346660770e5a1dd7c968563721b43265d5e92a06fbae31a1ea09 CertiFriP3.Digest CertiFri.P3.instInhabitedDigest.default +D 0c3d65e78f64154c2eed96d153a730ef9bf8618b27d75173cb61e3ea6cce0f6d Init.Data.List.Basic List.zip +D 0c4dc4b6c0af9bee37f3a444be13e249f75786f45d1e18eedd6f1933718f0307 CertiFriProofs.Theory.Stark.UniformTensor CertiFri.Stark.UTensorAns +D 0c8736ff59cffdcf226562f76440134c7922b51d845aa8a5b432ad853e94cc40 Mathlib.Algebra.Group.Monoid NPow.ofPow +D 0c8e4d08e8269fb977501190d3736558fb0829b0f50ef6fc6b40b85c4d5d4e72 Init.Data.List.Basic List.lookup +D 0cd90181c589cbb07c6261b1c2d08c71206c588409bd8a420600840805d5a045 Mathlib.Order.WithBot WithBot.instOrderBot +D 0ce16a2f24781f00762ca9074f992e6f57829f8ff1d4369e9423ae68ce404f97 Ix.Aiur.Parameters Aiur.FriParameters.maxLogArity +D 0cfb4a9aee4e1ab282fb468c9cbf674b8d80c60aff4ea53b17c2f6aee2a7dfff Init.Prelude instInhabitedNat +D 0d025a9273c979ae9195e6cd0c8884372f4766e9a0d92c3ba73f2f19c36cf40b Mathlib.Data.Rat.Init NNRat.cast +D 0d300005fa092abd84be5ac877dd7918a53e2cf0731f48f10483fd13e84c0838 Mathlib.Algebra.Polynomial.Basic Polynomial.casesOn +D 0d349fa8cdde6948895038877d584e6203f74314750ad5eb08722c1721181454 CertiFri.Stark.Verifier CertiFri.Stark.activeIndices +D 0d625b3aaa1210935ef218e5087833e1a03995a1697557daa13120a6763a0db2 Init.Prelude List.set.match_1 +D 0d93515b1482632ddda6c77538bbf06907c8a6b06c2fe74f6ac9c63e85b03ffe Init.Core bne +D 0db04b68a67e56f304d92aa901d6a019ab17ab767edc72d9d9339e105c209e4a Mathlib.Data.Finset.Insert Finset.cons +D 0dba1c35899b1539e3c94585f4517dc68cc1b7e60a465bc875d4665b627f6ed8 Init.Data.List.Sort.Basic List.mergeSort._auto_1 +D 0dba2f025d0dfb6dbf0fe37ad3efae9d50b8b0f8b05bf615330579fc9cd2d6cd Mathlib.Order.Hom.Basic OrderIso.symm +D 0dd06a5dc7e34ee13aef128f69cc95678cc3ed1fce008da7305b2dba0ea7673d Init.Data.Zero One.ofOfNat1 +D 0de4a149be4123e840dec70731774fc0c1e490e778d645c66d257898a8b381fb CertiFriProofs.Theory.MultiArity.CompiledTensor CertiFri.Compiled.MultiParams.opened +D 0e16aadac1a5c0e58d746d49b5e35ebbe66f29a745b5c4d721f1924131e367a0 CertiFri.Verifier CertiFri.Fri.reducedOpeningsTensor +D 0e2c372d4936db190e5df201091d15af5d9db4446e7a62a204dc80ae1764f2ca Init.Data.UInt.BasicAux UInt32.add +D 0e4bca5f0e5241d7bc0283e364352d9d5f6d3d469ede0ab691cfd9f1ec86f233 Mathlib.Data.Finsupp.Defs Finsupp.support +D 0e6eef779823051644803f1508151f2e846bea15e656174ab8eb28232a24b94c Init.Prelude UInt8.size +D 0ea042560e186955674026520617a8357a5bae4991c85164dbc0f3eddfde7b64 Mathlib.Basic.Real.Basic Real.instAddMonoid +D 0ed1910fc1c1977b03d14977233a8a7c0dece114eb647274940105470660405a CertiFriProofs.Exec.Stark.Shard CertiFri.Exec.Stark.starkShape +D 0edb639ad31fa51b7ddfcbd202679e5eeee07f0c8f86ae7ff6430ed5051b57b3 Init.Data.Fin.Basic Fin.castLE +D 0edf37bd6996977bd922923eb0a25e06b11fe7f4637c858902b315c29d8c1d42 CertiFriProofs.Exec.Stark.FixedFamily CertiFri.Stark.System.withFixedCommit +D 0ee975f10ff76f6e0c6a154a49c0f2b514739b6f94d13ad325728ce0761f6c13 CertiFriProofs.Exec.Stark.Preamble CertiFri.Exec.Stark.Bounds.len +D 0efb2c46e8320aa7a97969763ec8ed5dceca3bf6712e33162a366871d9210b72 Init.Prelude Array.getD +D 0f016b7d13fb95b941a1c6d35b8024e2e62db415383730dbd8900888c25f0839 CertiFri.Pcs CertiFri.Fri.widthsUniform +D 0f078e183dea7defede62d31977970a918137deea2553802e2a46c31e2c226db CertiFriProofs.Refines CertiFri.Refines.toModel +D 0f26e55480348be8df00114b234d3518193c34914bad0323c86d08dd639ba12c Init.Prelude Prod.snd +D 0f27869c09746f3456019b4a04afe73b110b0c13bb4d8f8c07a90342d129251e CertiFriProofs.Theory.MultiArity.CompiledTensor CertiFri.Compiled.MultiParams.commitDims +D 0f2f5b3f156ca7c86a531af112a8d5870b5173ce2209a73d2ec402a108826673 Init.Prelude UInt32.isValidChar +D 0f555135abeb5526fda2be024ede05f4436e3b0d9ab5ee2eb11bc96dc14d8b18 CertiFriProofs.Theory.Oracle.Prob CertiFri.Oracle.OracleComp.expect.match_1 +D 0f635ec0d19b09affe38137612e6c2946a872471de5674c565c290428a10a5f0 Init.Data.Int.Basic Int.instNegInt +D 0f63bbdc300ba25e91a4d22acd5999cdcffc26f0e81fa661a8859c0f9b40a23a Init.Data.Option.Basic Option.instDecidableEq.match_1 +D 0f67fb9a1d6fefd31af193373c0c7c20bf45a16f3812a546849d8125d566f916 CertiFri.Field CertiFri.fieldPow +D 0f6f5754071121870550c14f4c0c41fae81f67574d3763a9b7a8046cac397297 Mathlib.Algebra.Group.Units.Defs Units.val +D 0f8ec37f28d394f51c767e960ad0c2cdbdccfbe6bee1ed240c7ee638dc563e11 CertiFri.Stark.System CertiFri.Stark.Proof.stage1Opened +D 0fb2a1a72e3112c6633528eb3ba540c693224bd9e889fbc8f0a104aba9c7e36c CertiFri.Stark.System CertiFri.Stark.System.preprocessedCommit +D 0fb8981f7436a98961dc945710f8e1f3af3e44913c6cc99bc7ac6c43f304f1e4 Init.Data.Nat.Lemmas Nat.decidableBallLT.match_5 +D 0fe183b4efe5fe5fe1601c8b089480732cd1f724f954b65b7c222dc1a40c0cda CertiFri.Verifier CertiFri.Fri.logMaxHeight +D 0fe74307e7af4ae2b58dc5799ce70b8ec2c8b57c43eb651a74d7d548a9418ec5 Init.Prelude Nat.pow +D 0ff6737dc16f65f042a0ab37184a1e47dfea7b160dfa675c7ba1109051ba68d7 CertiFri.Params CertiFri.FriParams.logBlowup +D 1009ddc90460dafe8d2b6b4ac0d58567af0b7dcea1d52491cdf28af1264be939 CertiFriP3.Challenger CertiFri.P3.ChallengerState.sampleExt3? +D 100df87cd5afb1f2e8cdbb40f4c84691bb3d388753194268676c7a257d333bda Init.Data.UInt.BasicAux UInt32.instOfNat +D 10113a9e94adeb863cc5d21e0219b8967613472ea9d468c20d2d2f2410b9aa96 Init.GetElem List.get?Internal._sparseCasesOn_1 +D 1019c992619d631b8f7af1f939be26cae049386f37dce51e1c229a1bfee0155b Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.zero +D 101ae344890cbfcf766c9541445521cdd72e71e1ec29bf91b34610f9fee0f468 Mathlib.Logic.Equiv.Defs Equiv.left_inv._autoParam +D 1022f559906cc428f992a660e6e45744db1bf81d82961ff11e84553a6b998ee3 CertiFriP3.DomainSep CertiFri.P3.challenger3V6Batch +D 103e0fc92984b22354fe59cc585d2a6e47757416e4d52f5f0becc5667029635f Init.Data.Int.Basic Int.decEq +D 10591e089ce47d037ddbdf0da9b3230366d093763358dab33e1203b37e4ff870 CertiFri.Stark.Statement CertiFri.Stark.Model.minusOneCol._sparseCasesOn_1 +D 10794d239f9327289df04f6c1f6c7948062f393354b15ad2d0c1ae37ccd6415e Init.Data.Nat.Bitwise.Basic Nat.shiftLeft._f +D 10891d9baac8151a9b249f12274908a575d21701e703f47aafd0d6de26dd463a Init.Data.UInt.Basic UInt64.decLe +D 10a341580613395a5cf50bb1552bfeb6d142ddc8c0649afd754b1d56c45ca7e2 CertiFriP3.Wire CertiFri.P3.Wire.openedRound +D 10af9d14664c3f9b307acc212bcfab4ff3536bd373a7f9d15b4def84df052dbf Mathlib.Algebra.GroupWithZero.Defs MulZeroOneClass.toZero +D 10c380b2e0514892b0db73c2ce4e5bc3b8e8321f955d1e2ffeacc26b6b5d6e52 Init.Data.Array.Basic Array.foldrM +D 10c558927493d0552cc09d39cbaea78c14983b413c457c7070c6773ced13992a Mathlib.Basic.Complex.Basic Complex.mulAux +D 10c7187e8af4acc431a2bbbd8ca597d5f26d7be1866f9652b4b89ca614bc2af4 Init.Prelude instLTNat +D 10ce79557443cb1ab5948282c8bf7188439d901a3bf65003f595d163964768e1 CertiFri.Stark.Graph CertiFri.Stark.instReprNode.repr.match_1 +D 10d8367df933a2a202a940b414f250837f20688c341761134a6e50d1796867a1 Mathlib.Algebra.GroupWithZero.Defs CommGroupWithZero.toDiv +D 10e83a4937067d47a22149bfa6e5a7acfe6d90df3899d35aed999ec9de4ea10a CertiFriProofs.Merkle.Tree CertiFri.Merkle.dimsOf +D 10fc143260d3329e223aa858be332258b5c546eddeccc91a10c887bf18387d11 CertiFriP3.Wire CertiFri.P3.Wire.encPrepIndex.match_1 +D 111cba52c5708b1b271c21b073f6bbfd52e0687b43eb03a40ae7f27f86d31dd1 CertiFriProofs.Exec.Stark.JohnsonBall CertiFri.Exec.Stark.InBall +D 115ff4b3538991474ef03c51034824d5b3b9ca2b4482273cf411643db25a8e0f CertiFriP3.VerifyBytes CertiFri.Stark.Profile.multiArity +D 11bc49c298490bd167f245a535efcf149ea9e1ba64d36d1083b063d9bf1391f6 CertiFriP3.DomainSep CertiFri.P3.DomainSep.transcriptKey +D 11c32be31244acf7ac16011c81c940d6696027cceba3a63544300fc2d08a965f CertiFriP3.Wire CertiFri.P3.Wire.KeyCircuit.stage2Width +D 11d9f354c51723e2819e25db6c82a51993bde6be59b97a794224631a7cc95276 Init.Core decidable_of_decidable_of_iff +D 11e4ac6372587d3faa49182792ca61cfb42d2ba3f3fa6a372ced0766f5ed94be CertiFriProofs.Exec.Stark.PrunedTensor CertiFri.Exec.Stark.walkM +D 11ed1ec827c33f634e65a6c3589624849e6932cfaa81851941324b861e82f5a0 Init.Data.Nat.Bitwise.Basic Nat.bitwise +D 120ca7e26b8b246b40cb08128ea300c8db3970b786afde536d3f59becf3b0436 Mathlib.Data.Multiset.AddSub Multiset.instAdd +D 1227a97bba692e105b325506e2fb45c6252ffa8e4fca6747db6c7e503e0bb83b Mathlib.Algebra.Order.CauSeq.Completion CauSeq.Completion.instInvCauchy +D 1227d51d07468e723f54ad34261f0be1ba84939fc6ba52335190d1435b64c337 CertiFriP3.DomainSep CertiFri.P3.v6TranscriptSingleKey +D 12466910b4a2ec0363e9fd1e04602fddcc8fce8c83d71e43c78f1536ba5a98f4 Mathlib.Algebra.Order.CauSeq.Completion CauSeq.Completion.instIntCastCauchy +D 1261cafdfbefac5fb25ff77515cc251aeb5e684addbe57e6ec55e971f198d8e2 Init.Prelude Unit +D 126b67a36e9ff469e85e7b4d007dda92510e3a7680a3bf87c4c30d576189e5ae Mathlib.Algebra.Group.Finsupp Finsupp.instIntSMul +D 12ccb3a082e910eff8068c5d8668912f561afde3becd890783a1205d36484e8e CertiFriP3.Blake3 CertiFri.P3.Blake3.Block.m15 +D 12dd0ed105aa8cc834c1fbf858c69bbc422402847272c19ed117640f7b193505 CertiFriProofs.Exec.Stark.FixedKey CertiFri.Exec.Stark.HashIface.rowsQ +D 12e0305ead4562002f5b4b3fff95018be6688990fe54fd5cd828fce8d7175e67 CertiFriProofs.Qrom.StarkPinnedQrom CertiFri.Qrom.SpongeDbBridge.obs +D 12f8d321999643852b05700db59e5eadea04710b860f29d7b67676612009e5cd Mathlib.Algebra.Order.Monoid.Unbundled.Defs AddLeftMono +D 1300b4e8b6aec780395795aaac9549365b0fe88fa34a14fe80c6be6ce74902dc CertiFriP3.Blake3 CertiFri.P3.Blake3.State.v3 +D 130d79880fc359788e9e3eb526b2923b50105aad380e58e6f47af037d0ee5e99 CertiFri.Stark.Statement CertiFri.Stark.Model.unitWeight +D 1310b34352ae6cd14c8fc26f8c1e4360b919cc068b67a415e080acb80cdcc8e1 CertiFriProofs.P3.ByteLinkPinnedFixed CertiFri.P3.ByteLinkPinnedFixed.keygenRoot +D 1317958f8455a7cbb0984353737e9a7480a28e7953c2d444b4cecd03e1649a96 CertiFriP3.Wire CertiFri.P3.Wire.decodeClaims +D 1357adb3c550bb8c2cf75e97f63a06f9a1cd9ed4091e4f3f50bd871a7aada4ad Mathlib.Order.Hom.Basic OrderEmbedding.ofMapLEIff +D 13600f8092ac4aa4edf70a4e8015a53a93fc544d9bd6ae38b0e2317dc8dda2f9 CertiFriP3.Challenger CertiFri.P3.ChallengerState.sampleBaseWith.match_3 +D 136aa6974f763cb8182b9dd378ad853999e2d035d8df860f866ff8dd1a96bbd4 Init.Prelude Nat.modCore.go._f +D 139f115a3102171863ceb2e75231ca39ce905a05bfede76ffab15f5f3b03f833 CertiFri.Stark.Admissible CertiFri.Stark.BatchBounds.len +D 13ad159a67b4d2d0e6d16b17df93a5820d563fab12a7595c5cddfda482bca07c Mathlib.Algebra.Group.Int.Defs Int.instAddCommGroup +D 13c29bc094dc1ff0ecf149f031df783e52e6c34e7073b9a878e8ea5fbed8cb54 CertiFri.Stark.Admissible CertiFri.Stark.Admissible.cosetBound +D 13c81b8ff58338d4b2c7f5830c4837e2ac2d1e6250ce4491a5b993251e105ef8 Mathlib.Algebra.Group.Monoid NPow.toPow +D 1416e1cfdb06565cfd737daf46ff9654c5a28bef4b5e36e4dcc36c28a8b63e2c CertiFriProofs.Theory.Stark.UniformTensor CertiFri.Stark.UTensorAns.field +D 141a532e6bfc42994e931fa0f8d3fc52972337b6b5b0844f79962bd9641cb0fd CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.one +D 14383be1e51b2ca20ccf15cadfced5ae4c472c45b0a6c701e5d88997fc116704 Mathlib.Data.Finset.Image Finset.image +D 14464ce83b8cb8af69af48c59f01e90b7a173c893cc15a1d5cdc4385b6fa85da Mathlib.Algebra.Ring.Hom.Defs RingHom.toMonoidHom +D 14790a0ddf0496afe21448cf69c49a585db69c6f0ecdafb0d505f93d9f08f10e CertiFriProofs.Theory.MultiArity.CompiledTensor CertiFri.Compiled.MultiParams.logArity +D 148260c510ed6ff79dc16bbc0e01cf9ef82fa19ee87f882674ce473eff3d2390 Init.Data.Rat.Basic Rat.instDecidableLt +D 14abfc227810100a358c4bbc1c68b66b54d14c821ab7374ecceeb68f59c60058 Mathlib.Data.Nat.Cast.Defs Nat.unaryCast.match_1 +D 14af814f1772987aae706086f335d1a5bed5a9a9bea1e940330be6e53d93bda6 CertiFri.Params CertiFri.FriParams.finalPolyLen +D 14b38420db5f04a169005ffa133d2ed4dc4ec02ff7515aa76732ddc6cdee429e CertiFri.Challenger CertiFri.Challenger.observe +D 14b6be456f4353911eb561600c816c060792527c8768bbed86bf9696e999ed93 CertiFriProofs.Theory.Stark.Graph CertiFri.Stark.Model.nodeVal +D 14c30936c23cec59729b68f86201c11786f569a491bbc3b1b03002bb4e4228dc Init.Data.Fin.Basic Fin.instMul +D 14d0c97e95fdc12d473169831105d79d3a5f467abf544fd206246be43214fa88 Init.Prelude Dvd.dvd +D 14f28e739f84c0a19ba1b61c4140ec2c0c9b83c09f4e40b1051e6b53b2fce9fc CertiFriP3.Challenger CertiFri.P3.ChallengerState.sampleExt3 +D 15032cd547251694e6cdfbf8e9514b3e2d19c10836d83a11c2f703eb756a1560 CertiFriProofs.Exec.Stark.JohnsonLookups CertiFri.Exec.Stark.projTuple1 +D 151738482fffa9d0459b5fb4f484c002074b170eb90ad5b4a1c80b082a3e0a86 CertiFri.Stark.Admissible CertiFri.Stark.Profile.stage1Pinning +D 151d905dea7760bbe04ece2960829bcfbd4796627369aa91dc4d40c55616d7c5 CertiFri.Stark.Graph CertiFri.Stark.ColRef.source +D 1533752697007769ddea5db58eb5ea14074cb41e09f96d91442a6d46ae7587c5 Init.Core ForIn'.forIn' +D 15351865d272b7a91ee0168358e04eccd9e4cf2f20af64461f557a1e4d7523fc CertiFri.Verifier CertiFri.Fri.claimRefs.match_1 +D 1537893887829a0b022f46b3b11056ccb559c958e01bf40a502695718f962849 Mathlib.Algebra.Group.DivInvMonoid DivisionCommMonoid.toDivisionMonoid +D 153f0989b8c503baa06ac04a219639bfaad5c778f90b8a1531bac55e71e397e1 Batteries.Data.List.Basic List.pwFilter +D 15488f6d8ee835b4b8716502e8b77ce0549f669c1c3dc44e888e0f226afb3853 CertiFri.Verifier CertiFri.Fri.ClaimRef.logHeight +D 154c1ae55e395799764916b296ac577eaac0427d93c088be29dba8cd29cce4bd CertiFri.Verifier CertiFri.Fri.inputChecks.match_1 +D 1558a3caefdcb611f55f0e51c775ccd721474e587c1f1811b8b59e0bc9c36bff Mathlib.Basic.Real.Basic Real.lattice +D 156e1d4f979bf7a7ba0d0be5f63c71d3089dfacd99a74104abc45c6af37c510d Mathlib.Basic.Real.Basic Real.instAddGroup +D 157028e2a76eabbcf1b462b1faf4b73244996c9eda3f44d4b7f67b3b5a9eadcd CertiFri.Bits CertiFri.reverseBitsLen +D 1586dfbb2a922e30a63ab5a53e7494a740ab43e2e4a392706a874e02b4913bff CertiFriProofs.P3.GoldilocksExt3Model CertiFri.P3.Fp3Model.coord +D 1592211342dc3719d432725023841877c7e54a3e55ce523f6a329bdfe7e41a72 CertiFriProofs.Theory.MultiArity.CompiledTensor CertiFri.Compiled.MultiParams.cum +D 159a138436d405440edd4795c9fe5869072fe6e4e6a5e87c169106988787bdc9 Init.Prelude String.utf8EncodeChar +D 15adedebb1a2b3da271b99228acf0a6d3eb51578783e164e13070a6750a252d4 CertiFriProofs.Exec.Stark.JohnsonBall CertiFri.Exec.Stark.circRowVals +D 15b4e522551acb1d7055e6dff3aee8a0b4934375672b3d095e9a7e0dd65ac9ef CertiFri.Stark.Graph CertiFri.Stark.RowValues.publics +D 15f219de8a391053fd5f8832ac1552de869b61f39163776cb8aa116978e669a4 Init.Data.Array.Basic Array.foldlM.loop +D 16039a3357bb843ce986e5554fbbd80677faf4b0ec1f9746fac460e696f8a08e Mathlib.Algebra.Order.CauSeq.Completion CauSeq.Completion.instNatCastCauchy +D 161068ef24f3c7b361f46869b4e79242713665abc1b997aa58b0744839a369c0 Mathlib.Basic.NNReal.Defs NNReal.instSemiring._aux_1 +D 1611ff19ea2c63618d5eda9985eafc0050884039efd339fc46b978d62b11d0f6 Init.Prelude ShiftRight.shiftRight +D 162ae273864f4a1ad09e83b8154a4c6b7022fd1923a624a6a52555986abeb5f7 Init.Data.Array.Basic _private.Init.Data.Array.Basic.0.Array.ofFn.go.match_1 +D 163384e5ebda85517517a9ff498b14fd160e52adad7289ca08315b7ea5e937c8 Init.Data.UInt.Basic UInt64.mul +D 1657b36dbc1efc1e0f9fb3a47a3e450f44eddc96ed367a806c8d21f0f89ffd2f CertiFriP3.Blake3 CertiFri.P3.Blake3.round.match_1 +D 166312de8bdd84a534ea214511c7ab5d30e82cc2eac29400287d664a50838f3f CertiFri.Stark.System CertiFri.Stark.BatchPreamble.headers +D 1699c195616a18d2e06d2adf2cbfe2651859ebc6ab2be8dbc60bc609f1fd4af9 Init.Prelude Bool.decEq.match_1 +D 16a8e75321c4cd6f5ce5ec06e179e07979e0c610ec9bf58ed9750a020d325ba5 Init.Data.UInt.Basic UInt64.lt +D 16af9dd9b7737b77a3066fbd4292f35b98c59d6fd6102b597a70477243c9d0df Init.WF Nat.lt_wfRel +D 16afbc14f2ebd72cba9115993071e34f4f1c21e94e2406a2a19c48e1ff3d3a72 Init.Prelude instSMulOfMul +D 16b0522995b36f127c5fc6bbc1d21a533e55338e3afeba1e310fb82e4b113ea6 Mathlib.Data.Multiset.Fold Multiset.fold +D 16c124af4ab1484ab6ce924d8d9708a6d43378642301feffa0f8faddd74f1e40 CertiFri.Field CertiFri.ExtensionOps.degree +D 16e9906a5d14d1cb0cbd24c0a94911d82e1820d919c141f6d4150baf91201e64 CertiFriP3.Wire CertiFri.P3.Wire.encPrepIndex +D 16f159a2bcd896c41887f7c4b783ed6657c75579f38246dd9a56bb47a7bc81a7 CertiFri.Stark.Admissible CertiFri.Stark.Admissible.rowItemBound +D 1717d3e7c2a4116958ed93337de7b59791d8a20768e051c68145d84cd5994260 Mathlib.Algebra.Group.DivInvMonoid ZSMul.toSMul +D 17222f34475e13e1d59a727cc1c500e1a9f0190b7757fbee3f478ffed5c7db51 Mathlib.Algebra.Group.Finsupp Finsupp.instAdd +D 17257364a2da19ab84a6ade50cc75b3174ff3b8a75d2b512230e252815f3742d Mathlib.Data.ZMod.Basic ZMod.inv.match_1 +D 172c4be61ec2a2f4151ff01a8a6bc1b98a0809c8f20a8a7e48e17805efbd42d7 Ix.Aiur.Parameters Aiur.meetsSecurityFloor +D 175252a638925b152291efb597b762aaf1fd3d7cbf8cf79a4cd4f53d3ba31ebd Init.Prelude Nat.mod.match_1 +D 175aa0d9a5c9662586fe90dfea746fddfd34eb0a81bfb2c0cdfdaf5f18242327 CertiFriProofs.Exec.Stark.Model CertiFri.Exec.Stark.StarkModel.toFieldModel +D 17a7476675324afeffaebfc51b1ecc42b2d4f85e869f9debbcc25b3424f76135 CertiFriProofs.Exec.Stark.Shard CertiFri.Exec.Stark.shardPublics +D 17ad62a328a7e09377a432d54f7cc155399b89975223ed6e86aca64cd21d3f22 Init.Data.Int.Basic Int.decNonneg +D 17b15075189040ee942c346b0a9fa442ddda2c4fac682d9e4beaf040bd47a443 CertiFriProofs.Merkle.Tree CertiFri.Merkle.root +D 17c885aedb2b790e2cc34e05355671786dcf44234d9b8159f88e263e80e8bfa4 Init.Data.UInt.BasicAux UInt64.toNat +D 17da9c485fead71762641535980670989a8f06fb2c0260d3974e8319e478bd8a CertiFri.Verifier CertiFri.Fri.openedRow +D 181f09e31318a032d490806f8321b0383173ef40a94c2713843ef0b3ff02a04e Mathlib.Data.Multiset.Defs Multiset.decidableDforallMultiset +D 184b2e4af008bb2f9eb101adb5c19a6d8ed83b6d3328367d0038e5b34121a2cd CertiFriProofs.P3.DigestCard CertiFri.P3.uint32EquivFin +D 1852d4427e35665d5436136d084a7c90021ceeb52ab71edfd7e9f39bd95373dd CertiFriProofs.Exec.Stark.PrunedTensor CertiFri.Exec.Stark.BAttemptPruned +D 189603cf3fc29743fb78069a02ddb23d9f8dcf6fb75d769127ad195d408e08c3 Init.Core Quotient.liftOn +D 18e66f86ad5c2b157e4867ccc720095a629e42dc160488bafa0f410954a970c8 Mathlib.Basic.Real.Basic Real.instLE +D 18e9d0b14321957b3405b42a4a56d03a1cc66adde6ee94a985a79eef9f5e7d6c Mathlib.Algebra.Order.CauSeq.Basic CauSeq.instNatCast +D 18f5b06b8aeceb5ba243ef96be4824b97519d3f60ecefeaf5894223b8dee4f51 Init.Data.List.Basic List.splitAt.go.match_1 +D 18f8403b2f018addd69c7635e8f34d1bcd6d0608114513ab58483e3b41a795e0 Mathlib.Data.FunLike.Basic DFunLike.coe +D 190e6d8dbc6f65ebebc85fb7970654abd243758cabf9f897557d97171929efb1 CertiFri.Stark.Statement CertiFri.Stark.Model.argsArityOk +D 192614fdaa86f976713e0830e77406c70e519ae295f06a2d906bb758df3672c1 Init.Prelude Array.casesOn +D 196b8b48fac2b291cd14b2fa44aec7b1dba49f6ca8d35f617756f00f171e141f CertiFriProofs.Exec.Stark.Shard CertiFri.Stark.System.HeightOk +D 1999e90d4240e0352434a1d2ac25d5e93ca5da5e21a02fa68748b711abf5b21a CertiFriP3.Challenger CertiFri.P3.ChallengerState.sampleWord +D 199b245a00d2336d19880a0d53c11eac013b129248902dd71aa36f3b456c4f5f CertiFri.Field CertiFri.ExtensionOps.embed +D 19bbef70eac3e0707e5f479b66731379d0244bb09204a2a353d263a9028944a3 CertiFriP3.Wire CertiFri.P3.Wire.lookupWireOk +D 19dedb108340def8d8717fb57289815c7be0d4bab9441bf00199131d6a7414f4 CertiFri.Merkle CertiFri.Merkle.widthsMatch.match_1 +D 19e45b4fc302617ae2b42c34524b94eed9145b13c54ae46dcb304ede6ed4a110 Mathlib.Basic.Real.Basic _private.Mathlib.Basic.Real.Basic.0.Real.one +D 19f2faa6908b947f95d0a64c4ba6611aa24ed1ea761ae66ef2668f132bcf6bd6 Init.Data.List.Basic List.lookup.match_1 +D 19f6419d9087a1ea219c7e3fb43cb45b400de14e3c812924d471610166f23cf7 Mathlib.Order.WithBot WithBot.unbotD +D 1a05d0aa92d8902e6656a936efb94b3ecf3329113bccd06bec04566b88ea8b52 CertiFriP3.Wire CertiFri.P3.Wire.claims +D 1a062fe623aa1db06bd8c76a4ef24a5701d834a52294607e53895faad9b3b06f CertiFriP3.DomainSep CertiFri.P3.v6ZkVkKey +D 1a2ee1897cf55e61b88c7c003c3ba74500c842875bc1bd8579422c3bb0fd8b3d Init.Data.BitVec.Basic BitVec.instHShiftLeftNat +D 1a35793f63e1e0717bc9cbed013bafa3a61cd3f841c25a41d9a272d899b800eb CertiFriP3.Digest CertiFri.P3.instDecidableEqDigest.decEq.match_1 +D 1a6ba43ff8c1298eb758fee5613842c8fbdea7a88539e020d1e0514a7ec4547a CertiFri.Stark.System CertiFri.Stark.Circuit.preprocessedWidth +D 1a7ba9631b4eddda10bef2a6331dd1b8f3a03a269ccdfb97c9290eeab094867f Init.Data.Array.Basic Array.foldrM.fold +D 1a92c43aed0198477435f534c3d242d3440fc8d4712384ec385e360091bbda73 Init.Prelude UInt64.decEq +D 1a9da3775180bbac2ef4971ec31cadff3e3c72a417667ee756140868859e0046 CertiFri.Claims CertiFri.CommitmentOpening.matrices +D 1ab44cc7e92ba35e0b8a6a808f4138026c1f4c088511f7051ebca9e7a2ac4021 CertiFri.Stark.System CertiFri.Stark.Proof.quotientCommit +D 1acba8e2ad1b4b220ad73c3fdeee0d49bb84c3a73a63aa25df0c66978e4ba203 Init.Data.Array.Basic Array.instBEq +D 1b1d2aad0b96982c0bacf95463da211207d36cc17ed10a3be136def8118d1383 CertiFri.Challenger CertiFri.instDecidableEqObservation.decEq.match_1 +D 1b27b240ba0a91f843584610b821c2a22a956265fe537b8c46472d53cfd998a2 Mathlib.Basic.Complex.Basic Complex.commRing +D 1b4df42a6dbd0aee810fb7bc6fd8ae8d2b8f48536958cd853697a55219c29688 CertiFriProofs.Theory.Oracle.MerkleFrozen CertiFri.Oracle.instDecidableEqSpongeQuery.decEq +D 1b632bc328673eecb73933f370947e38a6b7897d1371f7484f6cdb73477aaa1d CertiFriProofs.Theory.MultiArity.CompiledTensor CertiFri.Compiled.MultiParams.foldedTensor +D 1b6d779c9d8b11748ba92bfc3418b5cd9e237120461e4791189e4484dcbf39ba CertiFri.Stark.Pinned CertiFri.Stark.pinnedFixedWidth +D 1b7a2fc524754b9bdb005f181b7a99331132e0fd0b101014e959a8a42d86a602 Mathlib.Algebra.Group.Nat.Defs Nat.instAddMonoid +D 1b81299335ab55618e61dbe332abc86001bacaabc237e3463bdd3f5bd3cd7b48 Mathlib.Algebra.Group.Action.Pi Function.hasSMul +D 1b8a7cb507b3953b5ebbd0f1392cd81503a2bc329e047ab1c8d06cfddedcea17 Mathlib.Order.Defs.LinearOrder LinearOrder.toPartialOrder +D 1bac7dc957f018e0d607b64ebef847624b62c81bee4c16c4718c250369b1c216 CertiFriProofs.Theory.Compiled.Tensor CertiFri.Compiled.Params.verifyWithTensor +D 1bc22a178802f8f95e5ffa324ba022b5466fc4c32cbbc9143b54a9f516a6c7d3 Init.Data.UInt.BasicAux Nat.toUInt32 +D 1bd96fdb189ee51685e70f609c0d905a38768f4e1fada3aff8b5f71b3fee9fb6 Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.addCommGroup +D 1c02547370b5aa33c046be96304efa2f2e895b6ba21d3e4282f7595353be01c9 CertiFriP3.Wire CertiFri.P3.Wire.encLE._f +D 1c1c66ad574d4f676820a90101c43f425f8985fdab6d2002eea67f2541d1a41f Init.Data.List.Basic List.zipWith.match_1 +D 1c4634dc3adff9cc403c6f43e6351e02d2be677447bfde4132fb7d7648cf28e5 CertiFri.Verifier CertiFri.Fri.ClaimRef.col +D 1c63263787c9bb7699a573964da3dc953993a76796b5158def765c61464126fe CertiFriProofs.Exec.Setup CertiFri.Exec.FieldModel.base +D 1c6c724b1914a25ce45ce92c253955046be4d6ee33c16cea0723f8aaefda9a89 CertiFriProofs.Exec.Stark.JohnsonPinning CertiFri.Exec.Stark.SelPinned +D 1c960fa5ab3db2ceef4bfbaa9ee33cf92a7c1c91a82c6b9777fb541f1e9983a9 CertiFriP3.Wire CertiFri.P3.Wire.manyAux._f +D 1c98e9854be1dcdd125b0ec1983c37a2d63a7941aa7ec74655e8ae9b6dd6e88a Init.Prelude Prod.fst +D 1cb734f1b39cd7828beeb919aa38fc044695a6ad29a67d6ed70e5b9a4d8cff0c CertiFriProofs.Exec.Stark.SpongeGoodLogTensor CertiFri.Exec.Stark.deriveSpongeQueries +D 1cc762df4fd3a0f389284f5c566d432f40cd2c3b351dbb63d7409f897e55346b CertiFri.Stark.Verifier CertiFri.Stark.preprocessedRows.match_1 +D 1cd5a89eef5efacce03176bc49d741fb63fd8398b85982063b528d6e6346cdbc CertiFriProofs.Exec.Setup CertiFri.Exec.FieldModel.ext +D 1ce15cfd84fe69de45f2206612c49f7aea2ce5438080d39207b9f527f6f68705 CertiFri.Stark.Verifier CertiFri.Stark.preprocessedRows +D 1cf4cdb79ec2b56e0bab9b51d45208519b31eb86c67c823f6dab0f254c863f58 Init.Core Quotient.hrecOn +D 1cf7c93be9237a06d3e0544e068b815caf97406f9a5e27b7fea9fec48aa1625f Init.Prelude List.utf8Encode +D 1cfd8ec566c0fb694603f7d950e188fb8d4828f7081324d9827ebc8ded8fd76b Mathlib.Algebra.GroupWithZero.Defs CommGroupWithZero.toCommMonoidWithZero +D 1cfe2c2f581c41463b426d3ca7c1d9e990ca533cf9d3785a2ac9d5870219388f CertiFriProofs.Exec.Stark.SpongeGoodLogTensor CertiFri.Exec.Stark.tagSpongeChunks._f +D 1d129c0216de1c7410b84a4f21df1d5ab40b29a97b33f4ced7654956adc42139 Init.Prelude String.utf8ByteSize +D 1d1a517bfb82b5337903fd821d1c905cf5ea3932bd7c5ef514b7f9394c999645 CertiFriP3.Wire CertiFri.P3.Wire.nodeWireOk +D 1d1fc770f3fbbe103c178ace43e97ce96a12e6817954e0fcc2fe9502d9959217 CertiFriProofs.Theory.Oracle.MerkleVerify CertiFri.Oracle.MerkleRO.parentM +D 1d3fc4f648dac7d3fab39e94f7318230e8dedc1ea9b9f26b099f5df3dfb80790 CertiFri.Stark.Verifier CertiFri.Stark.claimsAccumulator +D 1d45bfc9c50baa567721482b8296b60e8ec75ba6949ee466d0341fa8909ec480 CertiFriProofs.Theory.Oracle.MerkleFrozen CertiFri.Oracle.instFintypeSpongeAnswer +D 1d50cde166140cbba4843858aa88d7b543e11ef693582830184eac96c59d1c33 Init.Data.Fin.Fold Fin.foldr +D 1d551cf6dde874a103883a604b4798dcdfef892319eac57ef6260786929da8e7 Mathlib.Order.WithBot WithBot.semilatticeSup +D 1d579ec21bb80cc90d383f106a15700538ac1321439c98524dfeff75d8f520b5 CertiFriProofs.Theory.MultiArity.CompiledTensor CertiFri.Compiled.MultiParams.rounds +D 1d69833e95523d29a1c23d521c93278d445ad55cab8877489ac5727d5df237ce Init.Prelude Mod.mod +D 1d79c485d7e05230e611392b946c9f8aac9b20a2e01378b32a28f1efd0b325de CertiFri.Stark.Statement CertiFri.Stark.Model.bound₂.match_1 +D 1d7c99584efa12367c6a1fa9c5550171e449ec6e5aa747025f81ac40fa29ab07 Init.Data.List.Basic List.any +D 1d95fa1df9d315243df10e6afc5b1e871699c965927075513cf33eb97f84aa98 Mathlib.Data.ZMod.Defs Fin.instDistrib +D 1d9b3eb6cc9fc446653a02a46c9b9571938b6a9060bdb4c7052b7865b21b1c9e Init.Prelude ByteArray.empty +D 1dd01f3e0639491c341079d94603a453dca54229fe475044cacf5fcb65082c19 CertiFri.Verifier CertiFri.Fri.claimedRow +D 1dd28ddb1dc85a89d986d8ad70d10bcd242cd1a612f222213b5a3fd4f9eca69d CertiFriProofs.Theory.MultiArity.CompiledTensor CertiFri.Compiled.MultiParams.FinalCheckTensor +D 1dea0d355a1ea351c71ecc022e0d215cf36d44def5821731fe03a564a065af2e CertiFriProofs.Exec.Stark.FixedKey CertiFri.Exec.Stark.fixedRows +D 1ded007585381d15f85ec573a9a89210cfda83c5eaf7648d6be17caf83027ccd CertiFriP3.Blake3 CertiFri.P3.Blake3.Block.m2 +D 1dedd7e5e19c834c800472b7c49ce60a228f1415bfcd4cb4163ae3c9190a555c CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.GoldilocksExt3.toModel +D 1e033fa4691e188af5411d0bd3a6f42062987adbd144f343c0b9b646a5c29f87 Mathlib.Algebra.Field.Defs DivisionRing.nnratCast_def._autoParam +D 1e28a147d4c4c79dadb3ba60d5edae438b718fc8467cf6dd14a40a7a0890ae2f CertiFriProofs.Theory.MultiArity.CompiledTensor CertiFri.Compiled.MultiParams.reducedTensor +D 1e29fc0f7ac5d910a2f82397d0b63c2850c01547d5150219e5a8951a66a00cbe Mathlib.Logic.Embedding.Basic Function.Embedding.some +D 1e316ed607ce71c73e104f4c500cee6abb8ccc8cb7861ec9ff98cfb1bc98594b Init.Prelude DecidableLE +D 1e44b7c3a0f1bdbe9fd335edff2e1a2afed4bc37d82c21d30c80fe79a76b385b Mathlib.Algebra.Module.LinearMap.Defs LinearMap.toAddHom +D 1e76e5e54de629138451ef4203a2b4d86908aa3da6203ebd5e2a39ac3335fcf3 CertiFriP3.Wire CertiFri.P3.Wire.vkDigestPreimage.match_1 +D 1e852eb11c7ef9c927af90db907fc6ed7649073780236f9d3be7699a01dc693c CertiFriProofs.Qrom.CompressedOracle CertiFri.Qrom.liftAdv +D 1e8c90a1f67e5a7669b75247fdc3ef331fbf1e1fedc92c83acad10a6790c9353 Init.Data.Zero One.toOfNat1 +D 1e8f8de2c1a1e109ee039aadbba5b9afe96fe69fbaa66f21d421d1096f2add7b CertiFriProofs.Exec.Stark.SpongeGoodLogTensor CertiFri.Exec.Stark.spongeToFS +D 1ea3333488ee9acaf22a2a29d015db3eb14f2b7e347c3bf386e98251f2b96da4 Mathlib.Algebra.Group.DivInvMonoid DivInvOneMonoid.toDivInvMonoid +D 1eb3dccfac8e0c3f92b4eae9c7ef796b6a6400af4005d34e5d3a45fc8237bd9a Init.Prelude Option.map +D 1eda235f1e31303e0a670a0d6c1d8f62a1d4a53e9c2c719194d291aeef43dba1 Init.Data.Option.Basic Option.orElse.match_1 +D 1ee7bf385d567f844281e68dfd2eaf03af3fd1fa78ef6c7419c378c0086fe1e5 Init.Prelude Nat.div +D 1efc8b9f287bb85ad6cc1a02a09b1712a1904c26070a07cfb6cf9bdc2a45dabe Init.Data.Array.Basic _private.Init.Data.Array.Basic.0.Array.mapM.map +D 1f01bed019b6f90cace4b2a5901314c4de86000caa68552973e3457c9ff3463f Init.Data.List.Basic List.replicate +D 1f26b81ac5db9d936ea1ba6d36bba605787a439b719f2119957266f8dc8f3fbf CertiFriProofs.Theory.Oracle.FiatShamir CertiFri.Oracle.fsTranscript +D 1f2868fbe5fc98a03252fff63600ed578aebf61a64c9f668fd473e0e0a105f50 Mathlib.Basic.Complex.Basic Complex.instNatCast +D 1f2dda6c384a06a304756ec037984ff6afa98106a52b30a1f9d87eea52565096 Init.Data.Fin.Lemmas Fin.intCast +D 1f3c4a32aa021b87157f47f87713372148689c3e184707e7148d658e415f2795 CertiFriP3.Wire CertiFri.P3.Wire.encFelt +D 1f4a55d0ccad9b9ea78a1f6252328288391357f4499f7a38294f3ff919e87e29 Init.Data.Nat.Gcd Nat.gcd +D 1f79d2139012685dd909ffaaa78552d35c93273d6ecec9ff5b77097e061170f5 CertiFri.Stark.Graph CertiFri.Stark.Graph.lookups +D 1f9bcb8e6c155a2c51736d8ee5068fe88e148942ef5db27ffe6d6f8bd80764dd CertiFri.Stark.Admissible CertiFri.Stark.Admissible.headerRows +D 1fa1c5e2953629cc98d088979fe9629a803c9e52266b9a9fa545d4465bba586c CertiFri.Stark.System CertiFri.Stark.Circuit.mainWidth +D 1faab1b613a0ab6ba56f9bc217f58be96f8be377822405496b31ad4f7e8cf55e Init.GetElem List.get?Internal._f +D 1fc6960df5d123f7c978fd81af96887f7546a1d682af8477ab21481c1b386151 CertiFri.Pcs CertiFri.Fri.claimedWidth +D 1fd6205f578b628aa7e155fcb7e7e1518d8935c8df96e748307971c6b209fec0 CertiFriProofs.Exec.Stark.JohnsonBall CertiFri.Exec.Stark.circWord.match_1 +D 1ffa3de482794153a8da8d78d2a497f620630b3c4c98cc6e7b63eeaef25cfbf4 CertiFriProofs.P3.ByteLinkPinned CertiFri.Stark.Profile.verifyBytesPinnedOf.match_1 +D 200950d0fd59b44f7d281f61ab6594254e6b378561f027a062ba92c399a3fe0e CertiFriProofs.Theory.Compiled.Verifier CertiFri.Compiled.foldRow +D 2016cc8c8d34a2c336943589928e31cb0ac044f3b493c4bcb44a43fdfc417f9f CertiFriP3.Wire CertiFri.P3.Wire.batchOpening +D 201d0f6a6363c6ae8496e2ae7e7101d4ed37a6899807a1dbe4d0992b6770db8c Mathlib.Algebra.Group.Monoid NSMul.ofSMul +D 2026707a59e41cbd2b1c1eb4f4be7dc8e2679e66ad81ec3892d16ad73b0d19bf CertiFriP3.DomainSep CertiFri.P3.DomainSep.v6Single +D 202ed9d3eb2119f0215229e2720ddfdd8f16eb81b466a121b0abbedda4892eb2 Init.Prelude Nat.beq.match_1 +D 206ce5036d43fcf36418da7036e2dc0bf3eb227388ec6bdb52245e8ea41de53d Init.Data.ToString.Basic instToStringNat +D 209838159b5134c2b9afb78c296bb4827add38e89377ab60165d08860ba273b9 CertiFri.Stark.System CertiFri.Stark.Proof.quotientOpened +D 20a4a2f411269610948854be7534e59f027416702c75a7aa3f010a6a968fe10e Init.Data.BitVec.Basic BitVec.and +D 20ac9f27bf592ea88ef525bec5a7ffedb6526ad21958bbb622f7b5b3a1d6588b Init.Data.UInt.Basic UInt64.div +D 20bbc55ba7cc66a58189b58fbcb0abc2424c2f3e9d907955bbe2cdda2e291a38 Init.Data.List.Basic List.range.loop._f +D 20c2106c6a056116bb925d9ad45178c811bab0a69a8f7275ad09fb223d7c23f5 Mathlib.Data.Fintype.Defs Finset.univ +D 20d5cacd35aed84f6e72a32a5227e45ea7fefbaa2e2e3e6c39141cbbebb931de CertiFri.MultiArity CertiFri.Fri.QueryResultMulti.rows +D 20d9544dbea1442064b07b173c94ef86003cd7a836272b881c9c7000c65f1959 CertiFriP3.Blake3 CertiFri.P3.Blake3.Block.m13 +D 21329bdaf2b88bc28f78b2155afe1d9352489a8ba5ec5c2cb211eb47b1c6cb5b Mathlib.Basic.NNReal.Defs Real.toNNReal +D 2133e52495562ba128ebe275cb573667b6da1bf9fafc759e9ba9584b1de7bc1f CertiFriProofs.P3.ByteQueries CertiFri.P3.ByteQueries.byteShardQueries +D 2142198b19eb61916286b420b04fde7ea37275479d9a7fe2aabb17a988cf33dd CertiFriP3.Blake3 CertiFri.P3.Blake3.Block.m14 +D 214b03ff0478a542957808f7633153eb0624250f7ade3ac96d2a75e78d21dcc6 CertiFriProofs.Exec.Stark.SoundnessPinnedSponge CertiFri.Exec.Stark.shardQueriesPinnedSponge +D 216450e4c4b10402e9778c3a8fc42f4ecb9f1b8848d2eda6eeb1079efcd5136e Mathlib.Algebra.Ring.Defs NonAssocSemiring.toNatCast +D 217f4b849915896d9b06da83af513f4343e9ea9216c5fba80deb3b202198ec9f CertiFri.Stark.Statement CertiFri.Stark.Model.lookupArityOk.match_1 +D 21b2c8e27bcf92270902ce30291130ea788211ff7429b05ab79ad85dfe9f83e8 CertiFriProofs.Theory.Stark.Air CertiFri.Stark.Model.pointRow +D 21bb2de11ef1d3111bb5e04d3e9fa8142be58ba75f9b877c48724c1749f4233d Mathlib.Algebra.Group.Int.Defs Int.instCommSemigroup +D 21ca2f48a0f11937da4ca971d5b80d5bcf62df25922408cbf8bc0a245809d3a3 CertiFriP3.DomainSep CertiFri.P3.v6VkKey +D 21f1e25d51ce6a6d5fc3da61acf3eb21aa7077f38029d50c71a1a5ea5100785d Mathlib.Algebra.Polynomial.Basic _private.Mathlib.Algebra.Polynomial.Basic.0.Polynomial.instNeg.match_1 +D 22046b95ea0fd21c3b45c84375caf2b3a63d0b5690e80c19fa7f931fa0689b5b CertiFriP3.Wire CertiFri.P3.Wire.Key.trailerOk +D 222bdb2ce418c488ff6153d6e2b2b92ae348f86a42d6f9ad1d284a5355e61777 Init.Data.ToString.Basic ToString.toString +D 224dd01daa7c083d51c569f6fbf6adbad28a235740ca809ea4c3be54117d420c CertiFriProofs.Merkle.Tree CertiFri.Merkle.Matrix.width +D 22531d13832911486863736dbef3f90eb9bc8d08d44cdecc9daa60c29466c3b4 CertiFriProofs.Exec.Stark.SpongeGoodLogTensor CertiFri.Exec.Stark.SpongeChain.lastAns +D 2254dfeb1a83dd966abc47fd48269f9c8f3c73007f13b687f3df3da8b68f45a3 Mathlib.Algebra.Group.DivInvMonoid SubNegMonoid.toSub +D 227b723c82aa9a8b74056726d2ec167e933c5f916c39d7cc8f4f85fe4c7dbb36 Init.Prelude instLENat +D 227d78bfe63b6d91cc83813efaea03ce18f2a5207089e2b2c90348bb8a23a514 Init.Data.Int.Basic Int.instDvd +D 2281cc9744b2323f3cfb833c8af72ae1229477f9861333078ec69e0c698d6964 Mathlib.Data.Finset.Lattice.Basic Finset.instUnion +D 229ac094d48106fd1bc9e582cc1482bf1e7041387bdec476b13b247e71c142c6 Init.SizeOf Prod._sizeOf_inst +D 22a209ac1f169c11f6f6707352cf7475431d62ddddd52363610be6f8d891d09c CertiFri.Verifier CertiFri.Fri.MatrixShape.numPoints +D 22bea1f59c903fcdaf6024c13c170e0789838f685015212a8859027f5ad69382 CertiFriP3.Wire CertiFri.P3.Wire.encNode.match_1 +D 22c96b91926eefdd57678eb8755caf52b31053959b16827bcf5433b327b4758d CertiFriProofs.Exec.Stark.SpongeGoodLogTensor CertiFri.Exec.Stark.deriveSpongeA._f +D 22d2686c3a8340f7c4f458b5bb3f33ef5fa80819d9141330a03b838d01e0af18 Init.Data.Rat.Basic Rat.instNeg +D 22ebc7caa82e5e67a989028d0d1c1d3d8b94af290951fb21a8f3fd8fad1a52b3 CertiFri.Verifier CertiFri.Fri.finalMessage +D 22f08e5fa750ad8f9197d80007840f970af2b265468e57e98ab61bd22139746a CertiFriProofs.Theory.Oracle.MerkleVerify CertiFri.Oracle.verifyOpeningM +D 22f743635139d0bc830e4ffdfa4066658fd3cd5d3f3650a716a897a872284e01 CertiFriProofs.Exec.Stark.FixedKey CertiFri.Exec.Stark.fixedTraceOk +D 22fb6ce5a035521d374842edaee0e612b45f14f3896630ea7466de6d0e276d8b Mathlib.Algebra.Group.Finsupp Finsupp.instAddCommGroup +D 23003d1fb9be1fc6f0ad914cf51c9d74d3a8f65135f1de0040a7a0a96cd57225 CertiFriP3.Wire CertiFri.P3.Wire.Decoder.runList._sparseCasesOn_2 +D 232e7bf70283160aaf733ac5696df0e13f8f2f40159844ef28484d4a065a5c72 CertiFriP3.DomainSep CertiFri.P3.DomainSep.standard +D 23453a1a92acbb605bed5fcd4f1f4beb24dac1103bf8cfbf3d889f1eedf5d72b Mathlib.Basic.Real.Basic Real.partialOrder +D 234b1ba85a23dea715363aeb3b422210d053b535d21dff6ffcb00d338dd10a25 CertiFriProofs.P3.EncodingInjective CertiFri.P3.Encoding.flatten3 +D 23b2f7f21e543dd90cbaee64390a8d87a192321949fe489c0b54a7c45c7f9c54 Mathlib.Data.Fintype.Card Fintype.card +D 23bf9403f3c9d6ee8cf49bd1cd04c92a7bb9245d400d369495ca71deef3f6358 Mathlib.Order.Hom.Basic OrderIso +D 23db95006bce7a3446556259c47d5128f7575e31cf0af5d20f26a4c3e1b0985a CertiFriProofs.Theory.MultiArity.CompiledTensor CertiFri.Compiled.placeRowMultiM +D 23df8f80c3a2f1d6b5547b93bd7eb00388fbd5bc89945c583426d5fbc013f4c1 Mathlib.Data.Set.Defs Set.ofPred +D 23fe0e22981d0e8e8b1f96a442dee9591862704b1b18430867ec96fb7842ba2c CertiFri.Stark.Admissible CertiFri.Stark.Admissible.sweepDeg +D 241288e5621e0f03dcb1a146abe152069e6f960255f5c7aa10654b5b99927bb8 CertiFriP3.Wire CertiFri.P3.Wire.KeyCircuit.constraintCount +D 24196838e43359bf7f77da9711988c449d8a7477846bb376dd43fd755942e014 CertiFri.Merkle CertiFri.Merkle.maxLogHeight +D 2443eca694c0c70837cb87ca365fb354878f8f497e1c5c2f1514ecf63e4d6af5 Mathlib.Algebra.Ring.Defs NonUnitalCommSemiring.toNonUnitalSemiring +D 24964f58173506d9fad9b248ed9b09751bd732975f04c579c4f03c100bc28e35 CertiFriP3.Wire CertiFri.P3.Wire.bool +D 24a833f58ac19d0931965389831d12903c870d81c06842ddbd49f9ce9d147680 Init.Data.Array.Basic Array.foldrM.fold._f +D 24a8eb40d10f2d7c2675fc5502cc46884b47063e623b5c80e39a9f2c1b221c73 Mathlib.Algebra.Group.DivInvMonoid InvolutiveNeg.toNeg +D 24c47e73108653832cee4919ddacd7ba66471a370be51d4c8cedaae2240ca728 CertiFri.Stark.System CertiFri.Stark.Proof.openingProof +D 24cf7209a3d3db1df6bf8c9b6b374e8ec30bef169723df71d115cdb3311ed1e8 CertiFriP3.Wire CertiFri.P3.Wire.Key.buildSystem._sparseCasesOn_1 +D 24d12ecd6d691a09f6e6d808f850ee5bb04cd6a1230c4bc22c336fa42826485d Init.Prelude List.hasDecEq.match_3 +D 24fdc6c674bd2848be016ddcc4a6f4d3e3819b7d0f36bcfd88bf0c5bce1c1e47 Mathlib.Algebra.Order.CauSeq.Basic CauSeq.instMaxAbs +D 253c448d3a88595b0d8876149c521bb47f3b7e152102dd38ebe04da4afbc4d53 Init.Prelude List.hasDecEq.match_1 +D 254287a39796a683d01b690ef2e960ecb750c2352dc59f3922b445dd6b2b0e3f Init.Data.Int.Basic Int.instLTInt +D 25486b4cf46766d0836a953bf852bf2270e6e995e4b5b5ee6d059f7310b58de6 CertiFri.TensorBatching CertiFri.Fri.tensorNumChallenges +D 254b1b035f29dc7742969ccb4829640780d0706ba44cd0b504af13acc69bc656 CertiFriP3.Wire CertiFri.P3.Wire.KeyCircuit.lookupGroups +D 255fbcd9e3da1245fbada073f8b4e6f8475e9229043c39d9188bd963b5459c87 CertiFriProofs.Theory.Stark.Air CertiFri.Stark.Model.Columns.stage2 +D 2598b384f25adb77eec756ac319fb8ea4d6d6d98be8b3029460b32a2b1515250 Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.nonAssocRing +D 25c06a3bc934a2cc1820c44f5bda7e1ce173c6a6b0a335d6311b23cd4e6d6728 CertiFriP3.Wire CertiFri.P3.Wire.nodeWireOk.match_1 +D 25d468387a5bd28279edd471972e058c30741c01caee0d380f24afeb0ac45d82 CertiFriP3.Digest CertiFri.P3.Digest.w2 +D 25fac011d28361beb31e836d32e835f75954c54b7350e524a629e0bc35794d51 Mathlib.Data.Finsupp.Defs Finsupp.instDecidableEq +D 2609c931da571cb7522359be136f8e1edc218f0b980f49fa5a1947b20690433c Mathlib.Basic.Real.Basic Real.instSemilatticeInf +D 261bfff2b97dfec2806d22c05e3b23c6571ad9a9e15f480e4fa702040fef35bf CertiFriP3.Blake3 CertiFri.P3.Blake3.Block.m7 +D 26212454f35ebadbe9072ae3b13f8386513a2a004a387799e12690a1ef9a0b68 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.goldilocksBase_refines_fp3 +D 2646a40d40a8ce8b4bdcf24904807fd2985b322e99f20938e6af57bfd298e698 Init.Prelude UInt32.casesOn +D 26df59ac6a6dda4472aef293320f0f06a17d1c056f752870bd01a6d5c584c274 Init.Data.Option.Basic Option.instDecidableEq +D 27246a82b808180481849986ee9849a2ec3944d3cb9e1f6ba1c9c46b23c37640 Mathlib.Algebra.Field.Defs DivisionSemiring.nnqsmul_def._autoParam +D 273441f9e424d50a8fa76d6a1ba958e14e7f8c41273d11ad9403760f38a0b395 Mathlib.Algebra.Group.Nat.Defs Nat.instCommMonoid +D 274536a16d58249a52ed81dea24bda69939014b629761107462792905503b07f CertiFri.Merkle CertiFri.Merkle.verifyOpenings._sparseCasesOn_1 +D 274f788cc78f6aabd324186b2e6ad7bfa9d0ad2215a5fe2377fe980d648898e8 CertiFriP3.Goldilocks CertiFri.P3.Goldilocks.add +D 275269c23a716f50f34b8322873aa98c79cf739c36739caa478e7580a3696a48 Mathlib.Algebra.GroupWithZero.Defs MulZeroClass.toZero +D 275f37fc5004babd72aad96425fcaa7dcbda81f47459e2c3be44399572627a36 Mathlib.Logic.Function.Basic Function.invFun +D 277450dc309413a0a940e0c44a80f4d4c1458130ab337e00ca264d600c4e6ef6 CertiFriP3.Wire CertiFri.P3.Wire.encU8 +D 2781b2f17b8e5a0cd70e20b58cec67c113a6d30709e66a47d4386d6f35e04d32 Mathlib.Algebra.Group.Monoid Monoid.toSemigroup +D 279e892683a8047338d5af3391036ce1192d73580b91e0f12fbdb13a8313c041 Mathlib.Algebra.Polynomial.Basic Polynomial.semiring +D 27a1b4584d91e87fc9136a744f771a69ca6a2e158a1f98572f26169b8ee329db CertiFriP3.GoldilocksExt3 CertiFri.P3.GoldilocksExt3.c2 +D 27b23cab2d11fafc8300ae159f2e6a7462805fd9e42c9ac0a1779ecf0030e852 CertiFriProofs.Qrom.CompressedOracle CertiFri.Qrom.QQueryAlgorithm.advU +D 27d624f2dc115b79066957e1982dd17d9701fbea58f1b0c6bbbb0b7669dde911 CertiFriP3.Wire CertiFri.P3.Wire.recomputeDegrees?.match_1 +D 27d8985ac7ea651d0dfe5fdde7388baaf88e1488c2f25b329227b63bb5c6eccf Mathlib.Algebra.BigOperators.Group.Multiset.Defs Multiset.sum +D 27dac4dc3ef2c46db4fbd2c2e1be76849a1ab13a8dd591227566ee7fb8431204 Init.Data.List.Basic List.tail +D 281689c0bd03a4af0fb301c68dbdd6abbb2c05983bdc1f0f82c6d54b52878300 Mathlib.Data.Nat.Cast.Defs AddMonoidWithOne.natCast_zero._autoParam +D 2827fa125c9235df845c21058449d98a3b94705f839bdfa3f1bf80dd7b205b8e Init.Prelude HShiftLeft.hShiftLeft +D 282a03599e0fe8fb13d7ed3b2f8fba6f5f128f157b0967daca3bd0a41ec940af Mathlib.Algebra.Ring.Defs NonAssocRing.toNatCast +D 2835fba601a00f2df8a680ccdd1ba4052b633597c183f07c6343f11b2f010e32 Mathlib.Algebra.Group.Basic DivisionMonoid.toDivInvOneMonoid +D 283a0589c3c8dd695d5ad663ce42de3a746f15d00641c5d02cd3dbfe1ce7fa72 CertiFriP3.Pruned CertiFri.P3.prunedMmcs +D 284c32701ead84ca3f94e7744f03112b7316dca8df97f9943c31b299be16b46b CertiFriP3.DomainSep CertiFri.P3.challenger3Sep +D 28519b6f873ab545ba314bfb2be93ed095f78cadb1976be6da0a75779557b8f5 Init.Prelude Fin.casesOn +D 285d754ca276a2d735c1147b4d1c1a852fc4c32fab407e84276143b8f1eb0d80 Init.Data.Array.Basic Array.instAppend +D 28650eefa14620b10c4f52043813fe4a3cbd2279991c9cf2583af6c6603a3a6b CertiFriP3.Challenger CertiFri.P3.ChallengerState.input +D 286981a1f00f844db44746d06ada23c5f2446f47aaa298bcc66ce8dde5fa0289 CertiFri.Merkle CertiFri.Merkle.groupRows._f +D 28811e51a32a8ed18ab88b62bbfe1e9a654296aa74a135723a2bcc7945120cb5 CertiFriProofs.Exec.Stark.PrunedTensor CertiFri.Exec.Stark.leavesM +D 2891cad7fc98965ef43d839fe58bdf835548b461acb879ba4c6e0986ddfb19b1 CertiFriProofs.Theory.Stark.Graph CertiFri.Stark.Model.nodeDeg +D 28a26ca31a15677f551f431e3ec241df7772cccc6e9a12b1efc252ca738c52bd CertiFri.Merkle CertiFri.Merkle.inject +D 28a3cbc79cf82ae6700e6ea546cfb7d7dd273e7c3d128faa38b37c9bc1c2f752 CertiFriP3.Blake3 CertiFri.P3.Blake3.State.v5 +D 28a784f928d4adbefefb0c490cb00ffcb13d8f50c4b06687ffe742f99754a39b Init.Data.List.Basic List.isPerm._f +D 28c9574b724adc1e034f3890322151785add7462260af6369a955832f1d73ecd Init.Data.Int.Basic Int.pow.match_1 +D 28dbb0d164eadab162a352175f31640093eb8ddaa6ec8570a2239cd90bafd411 Init.Data.Nat.Lemmas Nat.decidableForallFin +D 28dc0fc32e82e809de1633d22501c77343e7e45aa724919eb12a6b30ee122f64 Mathlib.Algebra.Ring.Defs NonAssocRing.toAddCommGroupWithOne +D 28e830ff0e7d96210a4182b79490c2a06f987312a299c56971089fd504570893 CertiFriP3.Goldilocks CertiFri.P3.Goldilocks.val +D 28f61a061342d7bbf90543a0d16f5f89ed4d29bd842d41ed8ba3673d80c4f33c Init.Data.List.Basic List.decidableBAll.match_1 +D 28f628398bcd5698e513fcc55eee1aba3ff38026714a7a93c6ae8986bd6e697a Init.Data.List.Attach List.attachWith +D 293968aad35ef17f42e41af406f462465eb53fe8764e08b09bd8359266b9aaec Init.Data.List.Basic List.range.loop +D 294ab8a3848b22b845b8d9cf06539d59e0b04f49b91831a57f2f8966ddd04fc7 Init.Prelude Fin.Internal.ofNat +D 294ed4db852db2d22b1b29859fdd262753217d67ed94025c5096e13450a20d3d CertiFriP3.Blake3 CertiFri.P3.Blake3.hashBlocksWith +D 29532220c78d3e4cd1fdd1a4d2a4ac1d5f5ae16155190e3210338bfed29c0446 Init.Data.BitVec.Basic BitVec.shiftLeft +D 299396106b8ae3b329d22054d7195fb836785f54594df3f876f9270b1e82b876 CertiFriProofs.Exec.Stark.SoundnessTensorSponge CertiFri.Exec.Stark.starkSpongeDigCap +D 299e97a31a37a8e2e0621ef603389acbf83ef8d20125ae7ea200e118567722b7 CertiFriProofs.Exec.Stark.SpongeGoodLogTensor CertiFri.Exec.Stark.SpongeChain.tr +D 29a3aa806b3cef9db9334e3059654d422f483963b22335018c7a8f5568ac022c CertiFri.Stark.Statement CertiFri.Stark.Model.keyChans +D 29aee4d9eb5b81c00b705dfaa30e84658c54b4d3e315cc86df73a7ed2023a78d CertiFri.Challenger CertiFri.Challenger.sampleBits +D 29c5b179b5e6b54eba65e072e37219a503c06b5975d2b6bbf0ed13aed048e3af Mathlib.Algebra.Group.DivInvMonoid SubNegZeroMonoid.toSubNegMonoid +D 29ecf3b4d475d881c5e06ab20551f32eb588948cee180564dd9436ec953b9d9b CertiFriProofs.Theory.MultiArity.CompiledTensor CertiFri.Compiled.MultiParams.leafWidth +D 29edb6a190bbda9a35007c8d6ef40c0561cdc6b5d34f040e26200eb4db5f507b CertiFri.Params CertiFri.FriParams.numQueries +D 2a1579ff3497271c4bc7682aae677798eef3e9893d6e0eeab691ab2ddf576427 CertiFri.Stark.Logup CertiFri.Stark.coordOne +D 2a2829753221e1f9bc8cbb3dc93a0872f3e548b82a0dbb2a8cddc110767acd3f CertiFriProofs.Theory.Oracle.FiatShamir CertiFri.Oracle.Transcript.casesOn +D 2a2957712ab29a643448495dc03c9014660ffb7a5bc6e363654ce12e70d98e3b Init.Prelude Nat.pred +D 2a30360b75ba54e7a8cb8a49d3661cbe8f1eb02d58806395b076ddb4fe8f32ff CertiFri.Challenger CertiFri.Challenger.observeAll +D 2a37013710eb1f84147010a7a458533d1bbb69d289d91061da8851309c70bbe8 CertiFri.Stark.Verifier CertiFri.Stark.Challenges.zeta +D 2a71052272134998cdc32677d21e0280ebeb522c9ac981956cfa261a70d151c1 CertiFriProofs.Theory.Compiled.Tensor CertiFri.Compiled.Params.commitChecksTensor +D 2a73f1025d8a0962de7b4585cb552194810d18d0913ffa48bed676ffffe511ed CertiFri.Stark.Verifier CertiFri.Stark.secondMessage +D 2aa0ccd02bdb3a1513b209e3cd6a649cbf6bd15d403746152fd8852c7b1d9a5a Init.Data.Int.Basic Int.pow +D 2acc63071a2c0fe1404ca0b55419a0fb116e10bd394a333d38b53ad2bd1fa450 CertiFri.Proof CertiFri.FriProof.commitPhaseOpenings +D 2ad0ef6be26e6fc4d400bc2c0a659931b075bbd6431fbd42544006c056b808f7 Init.Data.BitVec.Basic BitVec.instHShiftRight +D 2af59e18ed5272ce6326dc6fa678f19cfdf8349031badac1154789fc6aa16492 CertiFriProofs.Theory.Oracle.FiatShamir CertiFri.Oracle.FSQuery.casesOn +D 2b4a4302f8575fb677728bbb2fb47664b1cb966a138875dd6d5b83ea133136ff Init.Data.List.Sort.Basic _private.Init.Data.List.Sort.Basic.0.List.merge.match_1 +D 2b5119d2e75b2f4db133ac4a17cb8606f11ad93c5015aefafb8cc66246e857cf CertiFri.Params CertiFri.FriParams.logFinalHeight +D 2b577ea4942299e1ef2d5f71f40076cc3d5beeb2de9466e9f7cda4d028bb0951 CertiFriP3.Blake3 CertiFri.P3.Blake3.State.v9 +D 2b7384b2efad2102a4f69d9aefabc506f8eeeec9ccc00e3cfc2e51980938689c CertiFriProofs.Exec.Stark.PrunedTensor CertiFri.Stark.Proof.withPaths +D 2baeb61cd62eb872455240190244951feced116c8ead1eea38a4ef96ef39efa2 Mathlib.Algebra.Order.Nonneg.Lattice Nonneg.semilatticeSup._aux_1 +D 2bc2230e4c893a1959a2b71da4ef0dd7375e4040bcf35c76cf347df52c2295c8 Init.Prelude Nat.mul.match_1 +D 2bc2589ca8cf7dc2b6dfc91379ef3c086698382eb7782af3a81ddee73fa21d12 Init.Prelude String.ofList +D 2bdcb1aefe6b96feec5d94b61db555555cc100e79766958e00a6ca58e01dbdd3 Mathlib.Order.Hom.Basic instFunLikeOrderEmbedding +D 2c2b7c13d7690f21550fad6185e59931f5a6daaa2923af472ae35d31f746c929 Mathlib.Data.Set.Defs Set.Subset +D 2c2bcf2c07db96bc3361d97ad5426ecbca0ee9ca4bc1d8d778f166b1c9e8e4d2 Mathlib.Algebra.Order.CauSeq.Basic CauSeq.const +D 2c2c05d9cb61bbf7427005c52a13fc5ea55c3cee6b01b2e76c8e444301f2cbdf Init.SizeOf default.sizeOf +D 2c2d84a21ee161c880da3b046c9adfbd9ca0dd3c3b487ddbdbbf17c954a7c743 Init.Prelude Append.append +D 2c2e1627e6fe172ea80f3196c232f825b23b7ecb8b6080496230bcee661061c2 CertiFri.Verifier CertiFri.Fri.OpeningRef.matrix +D 2c3e8dee66daec68d169d2c8a6f5d8625eaf41df89f81415116dc7b078099535 Mathlib.Order.Lattice Pi.instDistribLattice +D 2c78bc0be7913747fedd75049fee77338fb178e8518945c9b1bedf9bee2fe1ad CertiFriP3.DomainSep CertiFri.P3.v6TranscriptBatchContext +D 2c8c114f21487e2fd37f06b000d93a9f91b747323e1a263caccb91277039fc06 Init.Prelude List.get.match_1 +D 2cb8944e1c8c41c6e6ff4880605bf20adce3ab1f243bdebf7ff02345c489fe31 CertiFriProofs.Qrom.StarkPinnedQrom CertiFri.Qrom.SpongeDbBridge.decQuery +D 2cbdde27de8c5986814db4290713ad2b00129839ae5ac6b17734879358a56f18 Init.Data.Fin.Basic Fin.sub +D 2ce327b47af6176d68467b3cc26338cc89195232e059d87233ee9e1d54d2cf3c Mathlib.Algebra.Field.Defs DivisionRing.toRing +D 2d123e6f1b98e490d7c2d3f1c9b57ec7bc8ab20f7d0b13d1f38dc99aac48e9ef Mathlib.Order.Monotone.Defs StrictMono +D 2d2b74c6c922c14fa0d207eb9a26399b83144e91703580ea0f4554c735115862 CertiFri.Stark.Admissible CertiFri.Stark.Admissible.nodeIsPlain._sparseCasesOn_1 +D 2d34ed9744f0e4f9ededc90fbce16d15ec7b4f0f0f619659280669dc0b9be516 CertiFriProofs.Theory.MultiArity.CompiledTensor CertiFri.Compiled.MultiParams.n +D 2d4a9fc1fa0ec533dc74bf389de790d22f96dcb7171130eb1dcc866dffeed277 Init.Data.UInt.BasicAux UInt32.ofNat +D 2d5c7cd2135193a6fc2b74923fdf5b7e841e4e35c7cc9d2a8070efaa8e96f1ab CertiFri.Stark.Logup CertiFri.Stark.groupConstraint +D 2d6f1177871d17b5f4a3e725bef1e1cedd0347302897a10726d497d3c3a31ec8 Init.Data.List.Basic List.eraseRepsBy.loop.match_1 +D 2d7e9d310138ef802784fcd06c25051d4a43d535c999a50add1e4ba093b73c72 Init.Data.Option.Basic Option.isNone +D 2da204f00a64259bb285c591ef330d31d1111d004b52c78b6f3cd71da40e1853 CertiFri.Verifier CertiFri.Fri.commitChecks.match_1 +D 2db0d0ee0f9a392699b19903c1f686a4823935e907a71faaa5032ebea8928f5d CertiFriProofs.Exec.Stark.SoundnessPinnedSpongeMulti CertiFri.Exec.Stark.restorePinnedPathsMultiHashM._sparseCasesOn_5 +D 2e109cfd2fab16fce42cc32416733b9c4b31eaa706f214158c4c7f6a7912a821 CertiFriProofs.Exec.MultiArity.TensorExec CertiFri.Exec.messagesMulti +D 2e1329cb84832a6defacfd303484a8ee390769c7e533962e30206c154e7f07a2 Init.Prelude optParam +D 2e1fbf0f4392437e85bd61808d25e6047d579d05bba8722d4917ca0628261014 Init.Data.ByteArray.Bootstrap ByteArray.append +D 2e2d7bc808337e877df448335b627eccf689e9dd695ee24bc5a63175d410ebe9 Mathlib.Algebra.Ring.Defs NonAssocRing.toOne +D 2e47c53a48d213a556a11501de47d466b72aec6ff32a0d0f16408c5fd2484b95 CertiFriP3.Blake3 CertiFri.P3.Blake3.flagParent +D 2ea49b5ee8ebfb5c6afa88cfb63becfc3804e13943a2437bbc78716f990eb3e6 CertiFri.Field CertiFri.FieldOps.toZero +D 2ec74e4ce44fe1ce8e77acc81e98ede4fef63da9346fa1f414ac7b5c20056916 Mathlib.Basic.Real.Basic Real.definition._@.Mathlib.Basic.Real.Basic.1259013419._hygCtx._hyg.2 +D 2ec92a65aaad12c2d5afd5afe72b5d7e1e580f7fb456fe38d6fe26d127b32051 Mathlib.Algebra.Ring.Defs CommSemiring.toNonUnitalCommSemiring +D 2ed02752c8fcc426b2b24367f3667d92974e94c3a8f5660327f1547b95e82261 CertiFriP3.Blake3 CertiFri.P3.Blake3.State.v12 +D 2ed28922c8805afc94916006dd503589011c9098edb5d30da22d38abc9b4b18e Init.Data.Int.Basic Int.mul +D 2ed3c9b97cfec125fb894601e7d5ee9baf7f64dca3161929fcfb71637835074d Mathlib.Algebra.GroupWithZero.Action.Pi Pi.distribMulAction +D 2ee643f5864f7427f2b51b25a9d9663d68f65fd81319e2634a55363e29e77ca9 CertiFriProofs.P3.WireRoundTrip CertiFri.P3.Wire.LookupWireOk +D 2ef1c2d2ad6e91d5671f1db6ec5cecba77a41c534eb36a1d995e2a5727d2c237 Mathlib.Algebra.GroupWithZero.Defs CommGroupWithZero.toInv +D 2f08514f8573383cd8ab20ad5889857d8da126c5a264a4c730d8cd90d248155c Mathlib.Algebra.Polynomial.Basic Polynomial.instNatCast +D 2f08cbdf14717aa21c364de2054a01e40295752bb2190c1640e89961cfe6e4de Mathlib.Algebra.Ring.Defs NonAssocRing.toNonUnitalNonAssocRing +D 2f129ef56b6dc7f1c3c91732e19f3707781d75434a4cd87eb1b8f4109cbd7b0e CertiFriProofs.Theory.Stark.Graph CertiFri.Stark.Model.sweepDeg +D 2f2120220bb5433e0ed38c90e280b3583e4622369ed275864383b13d5e3aff32 Init.Prelude List.flatten +D 2f2cfeb4ee55eb2d98a3d17f069f71128ca1c686b6b361dc7d2d250f6dcd242b CertiFri.Stark.Admissible CertiFri.Stark.Admissible.pinningOk +D 2f35811fa1dc6acc4c2ddb56ffd073b2eb413689ad1f8fb9ddb0d3872d8c9017 Mathlib.Algebra.Group.DivInvMonoid SubNegMonoid.zsmul_zero'._autoParam +D 2f3f985fd5617b0dc12b8fb8c0ff7a4cd3cb17c72d31206ff1d72bcca5674275 CertiFri.Stark.Graph CertiFri.Stark.RowValues.stage2Next +D 2f6e63d3232f7ce56ef5a621c1162e7364c0150f29d0798aaefdf6fc520e4a51 Init.Data.List.Basic List.erase +D 2f70bfef3d6f18e26e34bc7959ccb1f237ecbca2a3567facb4d5c63ef0ba0700 Init.Core PSigma.snd +D 2f7eea51cc79242c1b3182258519488bd3c9eb398a7d8d175443d327e9a11444 CertiFriP3.Wire CertiFri.P3.Wire.node +D 2f81fe987f800abac5311cf86ee1e5021fab83b08d40137ff2a73e51962cf45f CertiFriP3.Digest CertiFri.P3.LittleEndian.byteOrZero +D 2fc2564a2de28532d091903078eaba77da2928eb5157bf27d60251973a8350b5 CertiFriP3.Goldilocks CertiFri.P3.Goldilocks.zero +D 2fc45bb255bf1db5a9b6697a0d34c666b9b7bd39fc3c6be114c0628e92a7a62e CertiFriP3.Wire CertiFri.P3.Wire.encLE +D 2fcf704d6000ccbd5705c915afa1e271a3be8e9917debbd48ea7710a8fd529ae CertiFriProofs.Theory.Oracle.FiatShamir CertiFri.Oracle.FSAnswer +D 2fd341433be193fddbaed5677eceb54d2c756ae27630e4e4232c4cc909eaaabe CertiFri.Field CertiFri.FieldOps.toInv +D 2fde37104dab5a02045ef69cbc4f5f70b8cb2ab8d96a4ed330d035ffe4a67114 Mathlib.Data.Int.Cast.Defs AddCommGroupWithOne.toIntCast +D 2fdfd4f135cfe5c60ccb10fd6caedb0299db67d124fa8d876647a533f890d88c Init.Data.UInt.Basic UInt64.decLt +D 2fe38192907f92f98000de6cdde40c3b50a3dac9ad8e78fad08d397a38806673 Mathlib.Algebra.Field.Defs DivisionSemiring.toGroupWithZero +D 2fee6287914c6854a57c2e442b0ba05f51071faf5040c6280951c01199f68cc1 Mathlib.Data.Quot Quotient.out +D 304e161992fe8acbe789c5dd776d0ed6dfa0b19f367b3ec40d0dfe0cfa8485b0 Init.Core Singleton.singleton +D 307408a920012ec428be980c070c97c374b12d7b52278b89e71d8a5a287d3952 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.instMul +D 307af923b925f36d713597462d13d5028592a481837d1f1a93960fb1fdd0aaec Init.SizeOf instSizeOfNat +D 307b9c5361bbab6af22665207f6efd81eb477f1b9a12c0a97b2a15546f93a338 CertiFri.Stark.System CertiFri.Stark.Proof.stage1Commit +D 30b84a80ebc0be08a77a393278b6aa7ece71cca2eaf9d86bc9b3a058eb452ea2 Init.Data.List.Attach List.pmap +D 30be089db10acd657f38dc02dd6c3197f77dd1dfa38e750b9d3b86eb6e8fe3f9 CertiFriProofs.Theory.Oracle.MerkleFrozen CertiFri.Oracle.instFintypeSpongeAnswer._aux_4 +D 30be3373774bfcaf05d2d1013a24d2f4adc6c50aae5f1c15f38075dad8b5b487 CertiFriProofs.P3.ByteLinkPinned CertiFri.Stark.Profile.verifyBytesPinnedOf._sparseCasesOn_1 +D 30bf43992e576dbebe0acc9bc32fd1ba7c9373df11fb240ea08c4db34b9fe706 Mathlib.Basic.Real.Basic Real.instNeg +D 30c46afdf9c12e2efbdecbdedd428c4e3403f04d4984bf2604c6afe904d22897 Mathlib.Algebra.GroupWithZero.Defs GroupWithZero.toDiv +D 310f9b3b2a5517f5bbff34523f105c771a4367b3ff085cabf9f6b2bb2c59efae CertiFriProofs.Qrom.CompressedOracle CertiFri.Qrom.decomp1.match_1 +D 31320e66ebdd001cba28c0eb6de87529b65b0b276b5c030dfe8d1177608bb6d1 CertiFri.Challenger CertiFri.Challenger.sampleIndices +D 31341226c6d4207fbbb38508aabaa00b8eac812787d2ea82c4ffa32731e60a73 Mathlib.Basic.Real.Basic Real.instRing +D 314a59c9789fa7d8fd1166ca70ce52811d6d2bb230c932c829cbd2c3a5d3b5e4 CertiFri.Stark.Statement CertiFri.Stark.Model.nodeWeight +D 3151d3f41da3bd59851c1e9671bd39fcf3fff295c59b450023727f6f2d82f99a CertiFriProofs.P3.DigestCard CertiFri.P3.instFintypeUInt32_certiFriProofs +D 3154565fb9b69e0ac6b213b229ec74abf96c60f58270ed3521f223e7b69b8f54 CertiFriP3.Pruned CertiFri.P3.Pruned.ascend.match_8 +D 315569c6879b80bd41bdef6959886bd32e703a59c3005d8a4aa426f6044ed447 Mathlib.Order.Defs.LinearOrder LinearOrder.min_def._autoParam +D 315a408a339a2d645210bb2b6167b7aa3363a68c306900f05488edc2f57304bd CertiFriProofs.Exec.Setup CertiFri.Exec.FieldModel.leafEnc +D 31709a661b50345044c418906ebd6969e0e456f615acc1c094d3d032a0c79b10 Init.Prelude List.flatten._f +D 317d6a6ec31c8eb132b31dc37eb3d15bf4b34d925a3bedabc987175d5098492b CertiFri.Stark.Graph CertiFri.Stark.RowValues.main +D 317fee9813a32207590af9b72ef93287deb8b9bec8d6b6196ea8a387b5316868 CertiFri.Stark.Verifier CertiFri.Stark.matrixOpening +D 3190b37e8267429a08e9a685efe8c251b06c7c46b4b94105a1172c9c9e5c9931 Mathlib.Data.List.Sigma List.dlookup +D 31a69e1cca2b4cf07c25039f15d75a056a1e1e6656bf4cf419b808a76ea98d99 CertiFri.Stark.Verifier CertiFri.Stark.constraintsOk +D 31c009331248cbaa6f43ff3d60801938d520bf265aa59c77aa8cf436284267a0 Mathlib.Basic.Real.Basic Real.definition._@.Mathlib.Basic.Real.Basic.3335671075._hygCtx._hyg.2 +D 320cd292c8027a832b3c24023dfbf8e45ee9f623245ad1a22d44a2e399c9316b Init.Prelude List.get +D 3216dbb62b124e277efea97da3c8ff55326a130b13ad17c9b5cc3fd54a356916 Init.Prelude Unit.unit +D 3234bae00e35efab7a028f7e1ecdabd21f846f7cee4531e67829c5fe3ac70a51 Init.Prelude Char.val +D 32477de0f200f145f25edabf2412a608e573d0e08557c3a4493c1d4ff9ef23d7 CertiFriProofs.Theory.Stark.UniformTensor CertiFri.Stark.UTensorAns.bits +D 324a998bdec80433e9913d3364f00adb6f66e4d7be38b9a5570432cfd437f54d Init.Prelude Option.noConfusionType +D 3259051759614aa1a5c943d075681ebca4fdf30379699f8f349c9a4f0f641d58 CertiFri.Stark.Verifier CertiFri.Stark.messagesAccumulator +D 32638c30ef258f01631739442d411682c76ff0abcb9fae868de3460d0b54dc38 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.neg +D 3275026b1712e18d6c8024cff5f538037db8af24b4bbba2c9f0aa2fe503ba554 Init.Data.ByteArray.Basic ByteArray.get +D 3284e6211d71fbbd8cf8af0aef2d636c477ec3120c7a084e43ccf15a8d8022c5 CertiFriP3.Challenger CertiFri.P3.ChallengerState.sampleBaseWith.match_1 +D 328fbcdafc693248545cd2c56d9bceb8e1a24bd98bed92fd45bb89b5b7b7ca9f Mathlib.Data.Finset.Dedup Multiset.toFinset +D 32b1e002b08ac98c6e63ed328f8591135ba16eb01c875d8b777239a27ef0992c Init.Data.UInt.Basic UInt32.mod +D 32c1e6dfb98b2c616a8eab7c383ac0e6fee111f4f2207aa019d859e8b6715af3 Mathlib.Basic.Real.Basic Real.instMul +D 32dea90d191b49388164444c04cf7d51e1fe45052af1972c9df7ca5e686b4680 Init.Data.Fin.Fold Fin.foldr.loop.match_1 +D 3303c1348438a8938a4424f44abda91112a75e001ceae4565f61fe14e7d83eef CertiFriProofs.Merkle.Tree CertiFri.Merkle.Tree.nodeFrom._f +D 330ff43ca9877d84b91015f8df282a00c42cde5f7c78386d4b59fea43ea9b379 Batteries.Data.List.Basic List.union +D 3317e5a757d57ee18349ae92510e7505ef5fd1ba64aad7970442ae91bb3be4e0 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.equivTriple +D 33212dda296673772b4a33398a700a4510681dab355f97a0e3482e55e98d9415 CertiFriProofs.Theory.Compiled.Read CertiFri.Compiled.Params.ω +D 332ace3578c793b538b4948adbfa2f583322765500063b1a56b9f742e779b0b0 CertiFriP3.Blake3 CertiFri.P3.Blake3.chunkNodeWith +D 33443167cfb5bf14f36ef723f9497b5137040bec6db34937bbc73ac4440ad67c Init.Data.Int.Basic Int.le +D 335e74bdee19080bcda45bad8070deb4028065cec5ff7b2ee32dc4109edfae9d Mathlib.Algebra.Module.Defs Module.toDistribMulAction +D 338e112f43309d2cf97023f576b2c52243210f1c6d4a53dfd65c6ce97d020d28 CertiFriProofs.Exec.SoundnessSponge CertiFri.Sponge.mapHashToSponge.match_1 +D 339bebf819b29fb887133e331831db5dad3a433842ff2f97391cd3ab95ddfa99 CertiFriP3.Wire CertiFri.P3.Wire.KeyParams.logBlowup +D 33b512f0393e2f9b588bad70569d283450df5ae782997165e80dbfe210520f3b CertiFri.Stark.Verifier CertiFri.Stark.fixedMessage +D 33bae5bff9061e698e8cc5ceef2f986990e6173e0586fbdb9723852261f93066 Init.Data.Nat.Div.Basic Nat.instDvd +D 33c32c7077479c7b6fd5b850fbf51320a4f3ffbb5dfa014fa29aec735d372d41 CertiFriP3.Wire CertiFri.P3.Wire.instInhabitedKeyCircuit.default +D 33c4373cd85fdf2488cd0507b64a35d3f23900b192b46d9fa6493e521f414bbd Mathlib.Algebra.Group.DivInvMonoid DivInvMonoid.toInv +D 33e701c659782d104155bc8d5f3cb28c523bd6206daeea55093ea67a4549bd4f Init.Prelude instDecidableNot +D 33ea88d00154d1c534eed1696fa1f182a0cc3857dcded2b3da9685d8c1b54490 Mathlib.Data.Multiset.Bind Multiset.bind +D 33f3bcee5a98b63d6d5b990970e112198bb07903f4f06b45732d0f329adc2910 CertiFri.Stark.Admissible CertiFri.Stark.Admissible.preambleRows +D 340bfcafa6dbdc862028278b2b5595811693b69b0d40467465494f406759eba2 Init.Data.UInt.Basic UInt64.sub +D 3475ff9380f902fd806153c67eb3384dd3d0d70c8ca026fd634efcaca1c3e000 CertiFriProofs.Exec.Stark.SpongeGoodLogTensor CertiFri.Exec.Stark.defaultUTensorAns +D 347786d344c22c602b3cc8849b8d20fe9c10f583d5b9ec7c9ad61c44a4cd1a1a CertiFriP3.Wire CertiFri.P3.Wire.KeyParams.maxLogArity +D 347ea7d6f58a7fab9062de36e7888d1e68a7b95ac3c081879e65278671b5a9e3 Mathlib.Data.Set.Defs Set +D 348384ce3c798cf1e02c0d35cfff360ff5abcfb861f9ee06f305b47d446a100f CertiFri.Merkle CertiFri.Merkle.verifyOpenings +D 34cfecfd40f59e335a6b93562a3567be8d1910d2885c4d8b0648564880944ab2 Init.Prelude HSub.hSub +D 34d77e118ed08efefc93b7863c810a07ce962621d5bcdd0e68e56d6561bdf43c Init.Data.Option.Basic instAlternativeOption +D 34db4f1066826baa87cd9813c1c2592d610662f53bd0a2abfabcdf812376ae86 Mathlib.Algebra.GroupWithZero.Defs MulZeroClass.toMul +D 34fbdf1de8241965c214b33a6ff0f141ac65201ac14f3592b9404ecefb432c75 CertiFriProofs.Exec.Stark.SoundnessPinnedSpongeMulti CertiFri.Exec.Stark.restorePinnedPathsMultiHashM +D 351c272bec3877a7ee4c49662e39395e5ec6f0e8302a2b889e670015c2028d90 Mathlib.Algebra.Field.Defs Semifield.toCommGroupWithZero +D 355f732b39626204516bb855db0654bb156d728c4589f29c386edebc971a554f Mathlib.Basic.Real.Basic _private.Mathlib.Basic.Real.Basic.0.Real.inv' +D 35793290e6282f9a6b03baaa1bbdbdaea75db32d5ffd7bc23aff7c3e17842c20 Init.Data.UInt.Basic instShiftRightUInt64 +D 3595716d50386a3f0372f59a5ea2dcf39efa6b018aefc197ddd03bc0fcb08539 Init.Prelude Pi.instInhabited +D 35969ac2eff620ac0f9c9bea186b55112777a875b6d714fa606eda841facae4b CertiFri.Stark.Statement CertiFri.Stark.Model.boolColOf.match_1 +D 359faf9560bc45e51ad876b8ab6184ebfdff96d690001c24b0211c49e5eec8ab CertiFri.Verifier CertiFri.Fri.TensorChallenges.betas +D 35a1278b62ccc37e7be0b2edcb80580eaf359c171eca472368e67ffd492ea9db Init.Data.Option.Basic Option.isSome.match_1 +D 35a4503bc257bb3c1f30accfec439697c1718a4bcf372e3e7ce02dfe493efcfe Init.Data.List.FinRange List.finRange +D 35a9d7ae4b5db8923e3e26111870e87878117ea6065c3cc02031d8ca6bd0d178 Init.Data.Zero Zero.ofOfNat0 +D 35afebcd84103963bef18f56fbaa0f5cf3bc5cf4a3a1e928af6196d32f1533f7 Init.Prelude cond.match_1 +D 36171c76c570a8b75b866d031431bc9bf8964d3678b83e1c6dedf798391cd1ad Mathlib.Order.Defs.PartialOrder PartialOrder.toPreorder +D 3617480872d3a4de561c5abdb4d78978dc01223dab59b4f7819a7a05f5c76969 CertiFriP3.Wire CertiFri.P3.Wire.Key.preprocessedIndices +D 362e41a6aad75d6fe10ccc4555f9e7dee3db2709834623a1692cd4f81d9db071 CertiFriP3.Wire CertiFri.P3.Wire.Key.buildSystem +D 3631a0ec57d9ca9185b64a23982bf2b9d6d9d455784010790c550415ae9a3578 CertiFriP3.Blake3 CertiFri.P3.Blake3.State.v11 +D 364806b5ac15af6e44826ecf4a7c93fe773e43ed2548b4555ff8fcb4f7fbfda0 Init.Prelude BitVec.casesOn +D 364c30d38da7f8d068d56c8c9d5b0ba360e6f6c80f3466200412941c8f7cbc6a CertiFri.Stark.Admissible CertiFri.Stark.Admissible.rowBudgetOk +D 3658e45223d9e2e084e49306b9324ba4536c30476c0f8d924788ffb132936bc3 Init.Data.Array.Basic Array.map +D 36899d845f6c194eaba9e3f75f506ce982638daa2f06b4293859c71213fa608a Init.Data.List.Basic List.getLastD.match_1 +D 368b2b4e53f5835d0c6640fbdb3bd5c67d96d45e6f23b54e6153688abd432a3f Init.Prelude Array.size +D 368dcec83abc0cd85211ca87d01a2859eac40ad40a85c917fbfb3c21143ab859 CertiFriP3.Wire CertiFri.P3.Wire.KeyCircuit.contextsOk._sparseCasesOn_4 +D 36b1fde4f963c3869935b38c8fae89c3c2e2d56ccbb2e8dc17cc24ab22da2be3 Init.Prelude namedPattern +D 36b3f1ca6f5bbf457c84ac74ab24c601fc6a6c6990aa21a1b6eb175ca1f89249 CertiFri.MultiArity CertiFri.Fri.foldRowMulti._f +D 36c65b86a50fd6fabf550020f3b6e03ede27817893f248dd02dd239252b1efac CertiFriProofs.Theory.Oracle.MerkleVerify CertiFri.Oracle.instDecidableEqHashQuery.decEq +D 36cd40aa50ff064be7a6cadb22c3f22d27f54b63842361982c441c188e05b10d Init.Prelude Option.casesOn +D 36ddf8d9f58a66794506fe3da71b50c79a84caafea8c96cc751b6a1a868c2b46 Mathlib.Data.Multiset.ZeroCons Multiset.instZero +D 36e639c1f61a106727e8db47efa1adc3c32da8a5ccb3030f792b871ac1b96178 Init.Data.Int.Basic Int.neg.match_1 +D 36e87c82990d0408f43f5109b6b927763ae0ded973507e05add24d679b271dda Init.Data.Array.Set Array.setIfInBounds +D 36eabcfed38238a657acec23a6fb8381d46bf439d4be8d07b11e15e5a04e71b8 Mathlib.Data.Multiset.Pi Multiset.Pi.empty.match_1 +D 36f3345474471d19db83057bb6e21573c2a78b9a600504ca7388f7a860eab594 Mathlib.Algebra.Regular.Defs IsAddLeftRegular +D 37155509a3266f696b97cc3720b62922233fceb2dc5614530256d5f80cc885b4 CertiFriProofs.Qrom.CompressedOracle CertiFri.Qrom.decomp1 +D 371bd6188b5744f14504587410871d903809fa12d00b9daae372576e799b299b CertiFri.Stark.Graph CertiFri.Stark.instDecidableEqColRef +D 37351d9e59412c31b6523aed405a217823bfa6106524873b88334c0e931b7b13 Mathlib.Algebra.GroupWithZero.Defs CommGroupWithZero.toZPow +D 373c327a60c0376efbaa9c94d2f3ef2430fbd33321cf1166b53375a45bd8b04c CertiFriP3.Wire CertiFri.P3.Wire.KeyParams.logFinalPolyLen +D 374a274c187ffd78cce7d0cf11782b04ae5a777d359e1c42ea5e795a2a5c33d7 CertiFriProofs.Exec.Stark.SoundnessPinnedSpongeMulti CertiFri.Exec.Stark.shardCompPinnedMultiSponge.match_3 +D 375ce70d91ca1516a6226aa590a9aba1639bed8714f0d23e067dd49e688368b1 Mathlib.Basic.NNReal.Defs NNReal.instSemilatticeInf._aux_1 +D 37931fc64222b2ddc2466450c96121ce217b8ba28349b13751fd3ef445933d51 CertiFriProofs.Exec.TensorExec CertiFri.Exec.openingCoords +D 37a126b515ad28e380498e673f8bb698bffa18f8eac531a2feef87b14fcca415 CertiFri.Pcs CertiFri.Fri.claimPoints +D 37a778f2ab8a3ceceeb567faa3839faf32039f650bcacb881edf2b90e39dd567 CertiFriP3.DomainSep CertiFri.P3.DomainSep.KeyedInput.casesOn +D 37ad39c7c2496ac37ab010c48ae1662b281054164bc905c0d454ddee7af8394e Init.Prelude OrOp.or +D 37f971bc9bd340537276d3d71c12f5239224c2227f13ffda23a1f7162697018a Init.Prelude Lean.SyntaxNodeKind +D 3822fc52da3cbdeb2971d7999b4971019a7351b53ff3c5a5e0b3cccecfdba0b4 Mathlib.Algebra.Group.Finsupp Finsupp.instNatSMul +D 3829861e3d27ff06b7e540ae6e7dfa320eb149552c2f8fd8bda4e8e9a37e90cd Mathlib.Algebra.Field.Defs Semifield.toZPow +D 387b8422c26c58d30d53eb89769484c9329d0f5bee7a2c03a728906708ba47c0 Mathlib.Algebra.Notation.Pi.Defs Pi.instNeg +D 388cb03f08c7c353975cc5dcd9e52c428a6c0200ee39ae1b47319cff9aeaf2c5 CertiFri.Stark.Admissible CertiFri.Stark.BatchBounds.shards +D 38a52e92308a10e5649fe411ab030e00fd7132ed018c451efdcf41c10b52d024 Init.Data.UInt.Basic instAndOpUInt64 +D 38ae290f791426fcc6aa98616620a8572e9cb3bf3c57af3bf25c87837ad08d63 Mathlib.Algebra.Ring.Defs CommRing.toCommMonoid +D 38b755ddd2d638ae67bc71ba1fdfd9c5423a71abfd8421faa78d48e80015a608 CertiFriProofs.Exec.Stark.SpongeGoodLogTensor CertiFri.Exec.Stark.SpongeChain.len +D 38baa3b4bfb5b3861099a3104866d41707d8dd6e66eee93328c5568d63d1c520 CertiFriProofs.Exec.Stark.SoundnessPinnedSponge CertiFri.Exec.Stark.restorePinnedPathsHashM.match_3 +D 38bfb016b0d76b91062b4e5087610fd4325a356470ecbc5db056b0331651ae89 Init.Prelude List.hasDecEq +D 3930ebc0dfd8e3787edd6e0ea4f19a5753a17a9c762fd4b3c3888693ef5aee84 CertiFri.Stark.Pinned CertiFri.Stark.shardPinsOk +D 3935e7e446fe8ebcec40da7b86e751c4e4665e8b399ebb8eb34ff65344b24ed7 Init.Data.UInt.Basic UInt64.le +D 39920e92f8b8043917201665ee98bb44e43f89e3100a491c369ba0169067f1a2 Init.Prelude Membership.mem +D 3998864e8df9dbbb5de9b0dcdd00ad0dfaa4fb4aec821c4f7b009eb9fbc8ee8b CertiFriProofs.Exec.Stark.SpongeGoodLogTensor CertiFri.Exec.Stark.SpongeStarkMsg.casesOn +D 399de803e2481c00800c44dc8b4ee735a2131568c35c1b1e1545f5dae5ae834b Init.Data.List.Perm List.isSetoid +D 39cde92bca78de8727580fad0c43326652cd149a54847a5988bc6c55c7a636f1 Mathlib.Analysis.Real.Sqrt Real.sqrt +D 3a1aa2e2c5b2841d0cb2ca33de796cf07ef0ac1cac338c985e44db0d30e29677 CertiFri.Proof CertiFri.FriProof.commitPhaseCommits +D 3a2b9be9ccd9ac1b833827c10ddd63482f3de6b72981da48969278833926c353 CertiFriProofs.Exec.Stark.JohnsonLookupsBatch CertiFri.Exec.Stark.accsOf +D 3a4c810d012a0271c87271cefa58c56352dd4a2b346a1beabc92c8fd976a380c Init.Data.Array.Basic Array.replicate +D 3a5910787c1a482bdb06080b5ee04df100d8d525b76f76a6b49ae6740c2fdfe6 Init.SizeOf default.sizeOf.match_1 +D 3a5b138d62074da8465c34170cbd92f7fda2b4b18aa584b2a406ac03cf1b9153 CertiFriP3.Pruned CertiFri.P3.Pruned.walk._f +D 3a6d38fd011c7c953cf9e6da182dc4dcb67eb1474441144503fc0d3e503c1c1b CertiFriP3.Goldilocks CertiFri.P3.Goldilocks.instFieldOps +D 3a881f36d3b5bc5772ae369cf6c3b4ad362486a7f10c90c24755fb54fb9f01f0 Init.WF measure +D 3a96abb043bbcb1937e7c4b24331a913f5249f1c31ee41113425477eadaed283 CertiFri.Stark.Statement CertiFri.Stark.Model.squareCol +D 3aa398e406e09c21143c66e58da03ca7ee424f05074c3ddedb08c1508ee3d27a Init.Data.List.Basic List.zipWith +D 3ab5a2c36a564e6ebd593d5de0bd358cec01cc4e9825d968c8b5e4476b295753 Mathlib.Algebra.Field.Defs Field.toDivisionRing +D 3abdb6a273197aa8babad3369aac87e1f9e56638d818facdfb9d29e0b3d20e48 Mathlib.Data.Finsupp.Defs Finsupp.mapRange +D 3acbec174634476906d7fce7b1521f69ebf2c6499ec914c597c11ae29bf22845 Mathlib.Algebra.Order.CauSeq.Completion CauSeq.Completion.instNegCauchy +D 3ae42132a4e5340795e39e20fbc5d7c6e5c3dcce182cf18a52d3e3ee4261c228 Mathlib.Algebra.Ring.Defs NonAssocSemiring.toMulZeroOneClass +D 3af9b6cd82e41d452269b19fccd2b058b5605769334012bc5f0429ba249cc964 Mathlib.Algebra.Polynomial.Eval.Defs Polynomial.eval₂ +D 3b00e9cf54402570b8b881010f63d6fddadf8b85c0ff5a7b15e097384dbe5a21 CertiFriP3.Pruned CertiFri.P3.restorePaths.match_1 +D 3b2d17b685c8e0775fe1f2e478483a4c95e0e1ae002bd12325fd9708ceb8d98c CertiFriProofs.Exec.Stark.SpongeGoodLogTensor CertiFri.Exec.Stark.deriveSpongeA.match_3 +D 3b365a644dae77f4a84b6d970ada7a6328c7ceeb9ed7352230751356011827cd CertiFri.Stark.Verifier CertiFri.Stark.Challenges.alpha +D 3b5c7867887e5eed5b589ba12c1bd35ec29746efc33b17e9d5481edc569370f7 Mathlib.Algebra.GroupWithZero.Hom MonoidWithZeroHom.toZeroHom +D 3b654e027a3a0a1332c2c7945515371572af88f9b23191ef4af4fcda90bcaadd Init.Data.Range.Basic _private.Init.Data.Range.Basic.0.Std.Legacy.Range.forIn'.loop +D 3b79587cb1cfe7daba350b898cbf7f482a78dacf5cfacd33146d11531b637afa CertiFriProofs.P3.ByteQueries CertiFri.P3.ByteQueries.friByteQueries +D 3b86d69d0ca89a231fad083ba0b8596a8528b9c3bd6bd798bdef0a9c3b9c6a60 Init.Prelude Monad.toBind +D 3bac1544160c76ec1ae4556efaa9679f7d0ac01a5ced30637882bb6935a7832d CertiFri.Field CertiFri.fieldOfNatBits +D 3bc0b342e1780bda1aeba65b1968561f7c65effffa898379155f46cc0a3cda9b Init.Data.Int.Basic Int.instDecidableEq +D 3bc75ad04cff37fd3ba01fb453e04b86e1bcb5e801511fdd8f6fe2b1212be9dc CertiFriProofs.Exec.Stark.StatePinned CertiFri.Exec.Stark.ShardView.pshape +D 3bd558f32a3c1ec65d465ece03d6f7f818a8eb905f1667127f7358bf4326aabe CertiFriProofs.Theory.Stark.Graph CertiFri.Stark.Model.sweep +D 3bd8121b1e94294faf10a1ddec379fe3bc9c8943be73ec522a6328bd1eaa32aa Init.Data.UInt.Basic UInt64.decLt._aux_1 +D 3be41ee3f5e289fb3f33feded681beac9553b1525074ea55fa064cfc9a0d785f Mathlib.Data.Int.GCD Nat.xgcd +D 3bef5346c8ecebaa5eccfb430ec053b1e6dcbd17907055a622024838d3f56633 CertiFriP3.Wire CertiFri.P3.Wire.felt.match_1 +D 3c09e3b46b60a289cd51e2daf3e5448a6d4bd4cc2c6f4acc58aabaea0a1f6d79 Init.Prelude List.get._f +D 3c1665f1992d2f66feac81a5d39178c5891f395f76a10afbc51cbff0d68d3368 CertiFriProofs.Exec.Stark.State CertiFri.Exec.Stark.ShardView.hdr +D 3c214fa22d15f491856ebfc3a205cd598682b1dd26a67aa5ad7a34344ff004d9 CertiFriP3.Wire CertiFri.P3.Wire.Decoder.runList.match_1 +D 3c27c83fdce47857cf142d4a1245faa09d413793566d6f6f5bb9e1b41f172f17 CertiFriProofs.Exec.Stark.FreeTensor CertiFri.Exec.Stark.UTensorChal +D 3c31f758e871aa85234779854c431c3f47c54c9c199ccded082ea665cedcef64 CertiFriP3.Blake3 CertiFri.P3.Blake3.State.v8 +D 3c41a9c27c2745eae65e2cb419a273e56b652c6ed0069651aaab1f1af30455f3 Init.Prelude Char.ofNatAux +D 3c7a10bd3e7e3a7f763ac7338ad25bdbef5ec6f5564688eedd8f9ec8e63756f6 Mathlib.Data.ZMod.Basic ZMod.val +D 3c917c5dd9b4f5c52248c914fdd3138f8ac0f090af81562d1216c3727c32f3fc Init.Prelude Nat.beq._f +D 3ca6ccaeb816873821e0e4504af53dae4f1d62797b98aa30fc380f68f9fd2074 Init.Data.List.BasicAux List.getD +D 3cc5a5dde361a5b86dbb0beb9758bc8a8715277555891131945a0a281bc983a1 CertiFriProofs.P3.ByteLink CertiFri.P3.ByteLink.byteExperiment +D 3ccfab99bb46167d913f8c024959263b15919c1ae969f257ffac97fa810eed37 Init.Prelude instDecidableAnd.match_1 +D 3cd226acbcec0635fabb16d2b5ddc5bb3150b3170dc9183a538de5cc03235afd CertiFri.Verifier CertiFri.Fri.reducedOpeningsTensor.match_1 +D 3cd32ad9335621ea797d2e9ee322a5fff6c8b3e96cb460a97739250de396b2fc CertiFri.Stark.Verifier CertiFri.Stark.shapeMessage +D 3d01c66bd859585474b5f2d0437116233053f43e60593106c649e1bf0d0d959f CertiFriProofs.Theory.MultiArity.CompiledTensor CertiFri.Compiled.MultiParams.finalDegree +D 3d2486b9ea6d3188070c52edd2f011d5973dab39969df3201be11455218a616f Mathlib.Algebra.Polynomial.Basic Polynomial.toFinsupp +D 3d35904d026c2f69432bb21daae4283021b811bf7f672989f0a772793920d545 CertiFriProofs.Theory.Oracle.MerkleFrozen CertiFri.Oracle.SpongeQuery.casesOn +D 3d3aa286544bf1be5e2c20d7cce4682dcb171c727fc49746522689dc41ee9067 CertiFriProofs.Qrom.StdEquiv CertiFri.Qrom.runWithOracle._f +D 3d3d34215de63602c5a039069096bdc9c4ede70d7ab51f6c948f2711115342a4 Init.Prelude Option.ctorIdx +D 3d7d2e257b202313a8d0750e643dcc1fbce7c94a84eee831719fe1700cb4b699 CertiFriProofs.Exec.Stark.Shard CertiFri.Exec.Stark.starkShape.match_1 +D 3d7ec3008e0886a19a2fca645dc4e466b771b9783f90d979539d01912cda5bea CertiFriP3.Blake3 CertiFri.P3.Blake3.round +D 3d8c93a0c76bc7c732b022c5809a75bbfc64ae0debf0ae661195a667234b6247 CertiFriP3.Blake3 CertiFri.P3.Blake3.Node.cv +D 3d9467780a77facfaf3678073262d01d0449a85ac7a551e0b1f693d28fccbe43 Mathlib.Order.Lattice Pi.instSemilatticeSup +D 3dba00eb60ffb34ae32c1411e08362acbc0efaf0746fdf2a756af5015181d79c Mathlib.Algebra.Polynomial.Basic Polynomial.X +D 3dcc46e35330a989e105b204ed7d900dedbff6ff7eefd4fc599469dc1f92bf91 CertiFriProofs.Qrom.StarkPinnedQrom CertiFri.Qrom.SpongeDbBridge.decodeEntry +D 3de4ca6eca89e038303381a4d3448628279fa315a442a79e6a64019445f86f97 CertiFriProofs.Exec.Stark.Model CertiFri.Exec.Stark.StarkModel.gen +D 3de6b47833ebb71bdf94ae24bb86f11322071928b9c8f8637f28d3752794a8e9 CertiFri.Verifier CertiFri.Fri.maxWidth +D 3e1e6b8b242741f3ca3c09fb644d14bc55a6a799f0c37e598924944b444c43ed CertiFriProofs.Theory.Compiled.Read CertiFri.Compiled.ofIndexed +D 3e4127feb7ae36b5e1462fb60df1c0e5eb97e3487e3203d41cfb120f891d7265 CertiFri.Stark.Logup CertiFri.Stark.logupConstraintValues +D 3e5841a56ed2b84fbc83ea56e93f34a95ed912420a93fd547f77350df811fbc1 CertiFriP3.Blake3 CertiFri.P3.Blake3.bytesBlock +D 3e6b124abacdde9ee71ec71057d5d0cd40ce0b805e618a1355c5d5fa587fc55e CertiFriProofs.Qrom.StdEquiv CertiFri.Qrom.combinedSteps +D 3e73492479b3ba3ada47ca51d2d2f040452751151e940e88efaa163ea83a65f2 CertiFri.Verifier CertiFri.Fri.MatrixShape.width +D 3e7cc59e37acfc925611e6cba398367f1e8974251103814322456ec9e4e44ea4 CertiFriProofs.Exec.Stark.SoundnessPinnedSponge CertiFri.Exec.Stark.pinnedSpongeMaxSteps +D 3e857e8a521f84418113f9c423b65e2c9a59e7f0f8d12e8d62c6c04f248ef093 Mathlib.Data.Finset.Defs Finset.instPartialOrder +D 3e9dbe87cd4a38a83c2e7a5c09bec6140bf4997979691f69b1c7e270f951415b Init.Data.Rat.Basic Rat.maybeNormalize +D 3ec204efd92a8baa02f38dd06142878f450053d7978a507cba934ae69a2befb4 Init.Prelude Nat.brecOn.go +D 3edf728f2ddee7a083c20dbee6449a968bf9a5f278d92b6fb07f2797fba27c81 Init.Data.Fin.Basic Fin.instAdd +D 3ef091615750be319e97f206a9cc84f5a8e19d064e2a0c606a39fe17c9af6c80 Init.Data.UInt.Basic UInt32.xor +D 3f1f9af8d2aa100f3b1dc8746d438b8d3cc02885f3c6be8803f060ebb46f93ed CertiFri.Challenger CertiFri.Observation.casesOn +D 3f1fed946a32a396c86b9bf4ae97d960f15e7189762e7d31dd3db8e79c35e6b4 CertiFriP3.Challenger CertiFri.P3.ChallengerState.exhausted +D 3f3163bb105c91afe7a23d03f3379395dba325adb89a97b9c73b0deed4077a79 CertiFriProofs.Theory.Oracle.Basic CertiFri.Oracle.OracleComp.below +D 3f3c90a1c0dd7aa693180d9ae2afaacf3d26b8283b2130145d42d0dcb5a29471 Mathlib.Algebra.GroupWithZero.Defs GroupWithZero.toDivInvMonoid +D 3f63c202e939635d8e2d97133221153740742a77b4b1bddfe0b8b4b87f6e1375 CertiFriProofs.Theory.Oracle.Basic CertiFri.Oracle.OracleComp.bind._f +D 3f6710eeca090c94ccac47795f15416200ed0adfd9e297a80b9416d3f8110b07 Mathlib.Algebra.GroupWithZero.Defs MonoidWithZero.toZero +D 3f67ddb30d70c2360bf5d237520725836a3f117d6b2530fb0f99ab8dee9fd903 Mathlib.Basic.Real.Basic Real.definition._@.Mathlib.Basic.Real.Basic.4282658333._hygCtx._hyg.2 +D 3f71affc99bc7f8d41f2146477d7fee04201f3c419266bb621b13b8b5ea515b8 CertiFri.Stark.Admissible CertiFri.Stark.Admissible.circuitLookupsPlainOk +D 3f7bf2f487d866eb4e3af2c30682e6858a36fa0be086edab19e77d434d916837 Mathlib.Data.Fintype.OfMap Fintype.ofBijective +D 3f807ed97afd5e2d46d19e5b328c0d48f8ffe9d202e2e3111343d0ea20c5644e CertiFriProofs.P3.ByteQueries CertiFri.P3.ByteQueries.extSampleQueries +D 3f818ab50baa8524698e652cfdb90e64256147a93864abe728cabea568aa1c04 Mathlib.Algebra.Ring.Defs NonUnitalNonAssocRing.toNonUnitalNonAssocSemiring +D 3f938eddf095977704012bbc238a20854bbc58dc4a8db10e3f9a2b4c8a7ae93a CertiFriProofs.Theory.Compiled.Read CertiFri.Compiled.Params.dims +D 3f9a12a832f4aa590f82dfe03f334a39c4165631c1cdfdf1f46f29180886f1a0 CertiFri.MultiArity CertiFri.Fri.insertDesc.match_1 +D 3fcf3489aff67126ce4f22dec0e35191f227b54f9a90117466e57aa3e399ac1a CertiFriProofs.Theory.MultiArity.CompiledTensor CertiFri.Compiled.MultiParams.commitChecksTensor +D 3fe46fc1b07b8efaed3a2ee872bcc61056053b6af57297bb4c60308f30399f0d CertiFri.Challenger CertiFri.instDecidableEqObservation +D 400161910f585d0a64b69a94f487e19c659dfff1236eaa2661b6e9d7bc2ed26a Mathlib.Basic.NNReal.Defs NNReal.toReal +D 4006549e92efe4e4adfcc7e248833582f619a120be25fcbbc7c48eb84c0a3362 Init.Prelude instHXorOfXorOp +D 4009baf67c935ec5f634ae488c591dc6892307ecd12c4782298fe298e9e1f4cb CertiFriP3.GoldilocksExt3 CertiFri.P3.GoldilocksExt3.c1 +D 400eac9dd863f3deb867c8febe55df90e1e6be9701cc78c216378b333f0b1b21 Mathlib.Analysis.Normed.Group.Defs Norm.norm +D 4031c3d14b1873a60cb71c1eb7609cc8b05a79f597b99b09580a9752bb874948 CertiFriP3.Pruned CertiFri.P3.Pruned.addSibling +D 4049ea3c4167ff49fa787576860a93ae4701c712f2b679c37a61d4b4dc11b14e Mathlib.Basic.Real.Basic Real.instIntCast +D 4052d2eab60194e92fe1088ff58d1655a692a20660309454cd5134a48e963866 Mathlib.Algebra.Group.Pi.Basic Pi.addMonoid +D 405f56d5dfd458839fb56e40ad5f30774b736cb361e023fb42678cc141ac887c CertiFriProofs.P3.DigestCard CertiFri.P3.digestEquivFun +D 406c0b334b214725ef85637f84faec22541b480824ad89b1b8acaa8a7caa1f8d Init.Data.List.Basic List.replicate._f +D 407d86facb2e9a87a3359d23bd89c3ddeef49072930f4f656c8e5579ebc76da6 Mathlib.Data.Rat.Defs Rat.addCommGroup +D 407fb7bc33864a0e4b0b41ad997606236cc4c167bc39aedb4711ff5d33af9727 Init.Prelude HDiv.hDiv +D 4084d420bca743189afbdbbeab2738322468f10344b7c0389bcf6bf1e001b822 CertiFriP3.Wire CertiFri.P3.Wire.Decoder +D 40a454b856c1774d4e88ddc381fa696444187767a562f3764cc5d2b20913f5a2 Mathlib.Logic.Equiv.Defs Equiv.symm +D 40d5495f3748869a43b7277ae7931875c0acad6c5fb56ccd1edd2612a3766a32 CertiFriProofs.Exec.Stark.Preamble CertiFri.Exec.Stark.lenBound +D 40eb2007b6eccd66c2d30856de44bd16a6eafb05c38345d8d4193bff8d1679f8 Mathlib.Order.Hom.Basic OrderEmbedding +D 40fa14964620758f2dc793e48eeccf0ab6adeba0432eadbc899d1be8e2ca4c3b CertiFriProofs.P3.ByteOracle CertiFri.P3.ByteOracle.ByteAns +D 40ffdc24a38dc7b9d177a48cdd107d7d9729eeb1ffe615b524f12673bb959e9b Mathlib.Data.Multiset.Defs Multiset.ofList +D 4105f6816507b3dcd0158a8cb6e492d18fd8cc23255a80f891df2279bac1e770 CertiFriP3.DomainSep CertiFri.P3.v6ZkTranscriptSingleKey +D 412b1db1ba52a20c9fa76a687f677d1641e5735a1624d5caf0e39d8c7477a7b8 CertiFriP3.Digest CertiFri.P3.Digest.w5 +D 413257e66c1bba52f60e4a1ef4867707c654ec222eda22c04dbd116ca0cec0ad Mathlib.Basic.NNReal.Defs NNReal.instSemiring +D 4133ff6c2655b76db608d39965581c01cc7bef0a246c8a5e1b701f5244b6d8bb CertiFri.Stark.Logup CertiFri.Stark.basisElem +D 417a8608af60973dce81286bfd47dede191089414f0fba71bc8d81eda07b3374 CertiFri.MultiArity CertiFri.Fri.reducedOpeningsTensorMulti +D 419812cdfb2939b719b68b042006cacc34255e5d3ba17c1c75ad68c3d2627597 Init.Data.Array.Basic _private.Init.Data.Array.Basic.0.Array.ofFn.go +D 41ab0d8c7c374c95d84e5d52bec1d24f24fb6fead049bf4d7d3309b8d5edc40c CertiFri.Stark.System CertiFri.Stark.instInhabitedCircuit +D 41ac2ebb074d0f0b4c599f1d113438fdc95f38e14a3da335711460e62cacccfe CertiFriProofs.Exec.Stark.SpongeGoodLogTensor CertiFri.Exec.Stark.splitRawByDigest._sparseCasesOn_3 +D 41b58aa20fdba8ca49827da13da5b724bdeef392263f2486a1705f96e8a0739a Init.Data.UInt.Basic UInt32.shiftRight +D 41b70c189bf16ce094d3a06826ea96f8454ba7924aaf7ab2ca515c0b6e7447a3 Mathlib.Basic.Real.Basic Real.definition._@.Mathlib.Basic.Real.Basic.3158186288._hygCtx._hyg.2 +D 41c95bab70c787636133277a910477ccb7ba3e60d59f6c6902010b307db25e83 Init.Data.List.Basic List.zipWith._f +D 41ef57a26d121eeb4daf2230964acaebb25a6c38b40c8dd04a6cec7199665dd0 CertiFri.Stark.Statement CertiFri.Stark.Model.nodeWeight.match_1 +D 420cbf982b8578dfa982fba5582758455c06fca8dca140dd6bacf4e4e125d213 Init.Prelude Nat.le.casesOn +D 4221804f1ede8f650f24876dea1a17e1f7aea5392555b0fbf1345a4dcd80b2d7 CertiFri.Merkle CertiFri.Merkle.verifyOpening +D 4226cc9574e0ef8213d015ea8db0ac59ecadb0684e13a08564000636d86b3d90 CertiFri.MultiArity CertiFri.Fri.scheduleValid +D 426daffbeac6a90fe889a42f809e2f29a3fe2ca98316f80462189c549482ba31 Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.instMul +D 429854cf6e312eef845357739c35a7a1e8a68a0ee1c7d62544da22624023d4c6 CertiFriP3.Goldilocks CertiFri.P3.Goldilocks.ofUInt64 +D 42b6719e3987bc960480782b1e54544e84a6d9a2df72dc372754a59dcfdf89b5 Mathlib.Data.Int.Cast.Defs AddGroupWithOne.intCast_ofNat._autoParam +D 42ba5a30c195ead13d13d40c83d24dda712374803d69d7304ea98bd19bc5f291 CertiFriP3.GoldilocksExt3 CertiFri.P3.GoldilocksExt3.add +D 42d99ee0e8901b2865e67271e818e1cf87f85630390f15c568e44d6829dddb7c Init.Prelude Array.extract.loop +D 42e128d7b3d8b3b216638e5796849b7cd26fd1acc1867ce678eb2f462ef54084 Mathlib.Algebra.Group.DivInvMonoid DivInvMonoid.toDiv +D 42f46c1d643171941fe96fd5309624123c1c3e3641151668eec29e66eef83fd2 Mathlib.Algebra.Order.CauSeq.Basic CauSeq.instNeg +D 43183e5f2bc6b5c5533aa4ae09aa5592f34db6f6b07790cb5ba12a926b9f82f1 Mathlib.Algebra.Field.Defs Field.toInv +D 432d033339ebae61f03afe5da5992470712ca55c326a91296ab73d524527d51c Init.Data.UInt.Basic instLTUInt64 +D 43307c1f5554a4135888096ad10d6d0c30153443616cf332a9db07349f632e84 CertiFriProofs.Exec.Stark.PrunedTensor CertiFri.Exec.Stark.ascendM +D 433695eb6d965609de6d29b00ab7c95528d18a74880af3ef0fa8618d5719589a CertiFri.Stark.Admissible CertiFri.Stark.System.admissible +D 4346aedd977c05dc1450de1c5b36b2c5b7f4bcedd43a3ba29a58689795985553 CertiFriP3.Digest CertiFri.P3.Digest.w4 +D 4348e8062ac0b1f4c3f8e9fad3521c9a545d0ee5ae014d29c09754271458acd5 Init.Data.Rat.Basic Rat.instInv +D 4369ba29ffb9a30e23b0fb0d45fe3b3e2d2a1e481dcd8531a278d054aef62292 Init.Data.Int.Basic Int.natAbs +D 4373e29323d2e89256a02fa29df94d2894652aaa79070cf8e3b08da97c57914e CertiFriP3.Digest CertiFri.P3.Digest.w7 +D 438329db48f570e326a9e1e5c6d85353af5eb2e392183806300cdc5ea12e9bd6 CertiFriP3.Blake3 CertiFri.P3.Blake3.Block.m5 +D 43939742e0a262ef1c15fb575a95189218eb31bd7ad2ce2eebb984edf111a6b7 CertiFri.Stark.Graph CertiFri.Stark.instDecidableEqSource +D 43af180d3d38ff77487f998a592a85a8647a4a2a4544410e8f6de7b4a8b844a8 CertiFriP3.GoldilocksExt3 CertiFri.P3.instDecidableEqGoldilocksExt3.decEq.match_1 +D 43c109a9dfa3d2bfe00ac747321313e36cdca9d3f3d9227c2939b24f9afd8f8d Mathlib.Basic.Real.Basic Real.instDivInvMonoid +D 43c3846d4c33bae522493c2b3cfbf47d75791ddaf29847805b72f5efdb21e615 Init.Data.Array.Basic Array.foldlM +D 43de526a6402564dda095ac2c119ce0aac5c18daaa4a0fb3400fe84e6ec2680d Mathlib.Basic.Real.Basic _private.Mathlib.Basic.Real.Basic.0.Real.zero +D 43e2e65c3665f87ad4d261d8b36c824f52fe7b9427f4ec18ce9c849ba4fe1d76 Init.Data.Array.Basic Array.isEqvAux +D 43e7ed4539ef0d152e05daed63adc77aa22133cf9ac7f10d33af8ec2bddc26f3 CertiFriP3.GoldilocksExt3 CertiFri.P3.GoldilocksExt3.casesOn +D 4408bd955a2ccea3a009996fbc5487e2692698115be8e83618308a571ad1bd3b CertiFri.Verifier CertiFri.Fri.sibling.match_1 +D 4410b37c6f06ffc5a68abc2bbe136d82ba789e5979c022318d1f5bf9e501f54b CertiFri.Stark.System CertiFri.Stark.BatchMessage.args +D 4451146fd4f8dd5c7ec7002f0c3010d7d5fe4363600fa100bb9c6e2ccbce22ca Init.Data.Option.Basic Option.bind +D 445e5ddde4f8bd6e39cbf3e1b0b170cfe0aba90478ce7b00940c92b25f5946cc Init.Prelude BitVec.decEq +D 446e3831684ce586d1ca6c392d23306937e9678cb9b0614ef65f965d045c1758 CertiFriP3.Blake3 CertiFri.P3.Blake3.pushChunkWith +D 4491be404438fc2f4c5297067a4cd6b4f43993362bdb420c4db426ac9c944565 CertiFriP3.Challenger CertiFri.P3.ChallengerState.output +D 44960f70c0749674625cc55b9abd90701d298c179fd818a88f5c0ed1e88e340b CertiFriP3.Blake3 CertiFri.P3.Blake3.chainBlocksWith._f +D 44ab62605c260fa712a6fb9d355bc88b1cd54fa336cf17825637993e20ccf98f Init.Data.Nat.Bitwise.Basic Nat.instAndOp +D 44c2781d5121729f33d8376c306cb08ffbc48129d39d085c5ae367a0aff2d186 Mathlib.Data.Nat.Cast.Defs AddMonoidWithOne.toNatCast +D 44dc7804072880ae8e4b4587b51c16fcc0225dbb337ae963da5707e96c6e1711 Mathlib.Algebra.GroupWithZero.Defs MonoidWithZero.toMulZeroOneClass +D 44e60eb9a7833d122206b3f840e0cc0896d77bc1342ad2b7488d4075ea9c1eb2 CertiFriProofs.Theory.Oracle.FiatShamir CertiFri.Oracle.fsTranscript.match_1 +D 4522564870fd131cecd546ceaa7d6ad58a6ff1d55ae9e3705de4148491a8d672 CertiFri.Stark.Admissible CertiFri.Stark.Admissible.maxNodeDeg +D 456847e8771faa52de28945fea76e70737ab56a0d197c1ec0d97203cf28b40fd Mathlib.Analysis.Complex.Norm Complex.instNorm +D 45c64ee66306b86d1d474bfc869af40c5f8b536a1ba1e3d6ccf4dbf4bbd69454 Mathlib.Algebra.Group.DivInvMonoid DivInvMonoid.zpow_neg'._autoParam +D 45d65d25167b5f1b2d4838267b939a6a407186ee54612cc00d110d958be4fa1b Mathlib.Algebra.Group.Nat.Defs Nat.instAddCommMonoid +D 45e27d604c002b5f7ca71e230f7f972f7a8c70c5155ccda5333953f989748713 CertiFri.Verifier CertiFri.Fri.PointRef.width +D 4620ae77affd2b56cfae2a7b8035dba67a4e3568c5b7c06b298982dcad99aa9b CertiFri.TensorBatching CertiFri.Fri.sampleExtMany +D 4654313a9bebdf8fe025a8c6164a21dba52f91c669a08d8addacf58e40cf9b49 CertiFri.Stark.Pinned CertiFri.Stark.PinnedBatchProof.pinned +D 465ca78b74c4dd1e406946589790512e55c9beae3cf3559829dec10ad978e5ed Mathlib.Data.Finset.Prod Finset.product +D 468b7f10c5a52ddab4c11d2df007ea308609f3e8e23d60803bf7770643f1c9b0 Init.Prelude Neg.neg +D 46ae3f8e9413bdbeab567e10472b84e943578e4a79664fac01c57e1797860e7a Mathlib.Algebra.Ring.Defs NonUnitalNonAssocCommRing.toNonUnitalNonAssocRing +D 46c5a79931926d01cf381a4b0a52eae4915fa0140b3e26602a5c5d99ec876e06 Mathlib.Algebra.Polynomial.Basic Polynomial.instSub +D 46d2004dcb46a1582ce1acc4376acca80f541d49c5ba3dec6fe3bdc733dda908 CertiFriP3.Wire CertiFri.P3.Wire.Decoder.runList +D 46ecf69a5b497b1d56540626a99dbe8628590804effffb09b8fdeddfc2c03db4 Init.Prelude String.toByteArray +D 471ecbcaa2731698943f49ee2ef9471b0090bf6f45e557fe431487436661c49f CertiFriProofs.Exec.Stark.PinnedLink CertiFri.Exec.Stark.starkShapePinned +D 47277fde68fa1ab7df4780711c58aacc0691bdeecf0eade835cbdad9cd478f30 Mathlib.Algebra.Group.Action.Defs SemigroupAction.toSMul +D 47323a1e353a6a56b647ff29e14134573b9588518645b757d169f5b9c97912b8 CertiFriP3.Challenger CertiFri.P3.ChallengerState.sampleByte +D 47557c7ed6ef3f0e5f809e70e3eb78c7bf8870211c60c6038ed51569b882a20c CertiFri.Params CertiFri.FriParams.commitPowBits +D 477c839716ca4db35cc1f120d222cf1dae7b512aef6f167f3b7be3d62e67eac3 CertiFriProofs.Exec.Setup CertiFri.Exec.view +D 477f138a84f20aa38ea8a60f20d9fa29fbc9b84a64bbb95796df6cffd644d145 Mathlib.Algebra.Field.Defs DivisionRing.nnqsmul_def._autoParam +D 47a181f1b024eb511c001726cbc96a69f40bf463571cabdfa8b1c03e3f0de325 CertiFri.Verifier CertiFri.Fri.levelOpenings +D 47cc1729ae4d315ac9b5a686f19172874b74e4a62d7b30c96be54488a2452a9a CertiFriProofs.Exec.Stark.State CertiFri.Exec.Stark.chalsOf +D 47e7b2146171211922956a084abb97fbb7f414e1d95d5858b178000ce28c5352 CertiFriP3.Blake3 CertiFri.P3.Blake3.pushChunksWith +D 47ef5d5adc8132a3b773c925a676db0be6b5a80ba0fed88ff2096f4368ad4f86 Mathlib.Algebra.Polynomial.Basic Polynomial.instZero +D 481cd674c4ad8d30a866c90fd4548ed98a5a4602a78f42ffe09482dc49a35a9b CertiFri.Stark.Logup CertiFri.Stark.coordMul +D 48274c4e9b9dfb43311467e06cf38de3b6c30ee795f861572baa4a15e5393816 CertiFri.Schedule CertiFri.foldSchedule +D 483e910d6f3e7a92ae1255bdee55aca52eb264b4cfc45dbface3ae08e201a7f5 Init.Data.Rat.Basic Rat.den +D 48ad1947ae2cb4efe73c05264df3a27a3f32aaf453cf9aa9b8ba629eddeb4503 Init.Data.Nat.Log2 Nat.log2 +D 48b3acbbd0a761fa9b9d37bf8145741773dcc3b1362c390d9c64f5063487158b Init.Classical Exists.choose +D 48bc4f59311433c35f85b62ce45d4a8c0d4bfba64f67b9691367b5afbc1812e8 Init.Control.Basic instForInOfForIn' +D 48c00cff3023f70059aeac748e2206968fa852d4688679f58779a3cb2c931797 CertiFri.Field CertiFri.TwoAdicOps.cosetShift +D 48ca3898cd64e0bb6252c746173a229b3ec4b1b1cbdb39cb7d6d6695b8037950 Init.Core PSigma.casesOn +D 48d181f47ba570222c1f51b9f88c46b3c61a43691483578b72cea743c824152d Init.Data.Zero npowRec.match_1 +D 48e6d9913812fed2215218793f683bded6ed2c5ca6c75a6bbed171a103c68d10 CertiFriP3.Digest CertiFri.P3.instDecidableEqDigest +D 48e98a490802dfb09886cce3044e35562bdc55d6972b3eb37d489da4a1962553 CertiFriP3.Wire CertiFri.P3.Wire.Key.check.match_1 +D 48fa3d2a66bcf5269c2f44ac4a60ab621e4a7959a10b01326c9fa7262e174e28 Mathlib.Order.Defs.PartialOrder Preorder.toLT +D 490b13621581912ecb79f827c5ea70e69ad6d0fd00b6a393ce713083b67b6420 Init.Data.Subtype.Order Subtype.instLE +D 4923b7b8ee9cc9532e98233fdc2245a6c7cc456347798b1b079c6be8761c10e5 CertiFriP3.Pruned CertiFri.P3.Pruned.walk +D 493e813eb1af3fa20d34adf562cde54cf2b0d010fbc8ef91cb2650e916d7e86a Mathlib.Data.Int.Cast.Defs AddGroupWithOne.toZSMul +D 494404bd6ed740b24fb052cc3a034b085ee677a90ebf550e4d563b5cea036fed Mathlib.Data.Multiset.Defs Multiset.instDecidableRListOfDecidableEq +D 49568cccf37baffdb6004870db94eb7d5a6b13d67868121684947ee9b502572b Mathlib.Algebra.Group.Units.Defs IsUnit +D 498d29338cf9e4d4acf849908cdca8d584d9d60ad8c4b84b1d3c2da7d03a3ec5 CertiFriP3.Goldilocks CertiFri.P3.Goldilocks.neg +D 498e0381a90b67ebdce02d07fe582c6abc2dfcdec6dfe3788b821390c01bb930 Mathlib.Basic.NNReal.Defs NNReal.instSemiring._aux_24 +D 4993754ac86390d60459ec80aff33eee10675012903d30ed0522b7d2675ec4a0 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.c2 +D 49ba08a417697eabd7dfc4d6897370172f39732fcd45d5382ea4c35fcd5fe81c CertiFriP3.Wire CertiFri.P3.Wire.lookup +D 49c7f7cc13eaccd0cebb9116da39d3eb1ecce0338118c8075525127aceba2dfc CertiFriProofs.Exec.Stark.SpongeGoodLogTensor CertiFri.Exec.Stark.splitRawByDigest.match_3 +D 49e74928cad9f175a236f69b289a7cbdf6c27b595492ec7afe06844f97791c70 Mathlib.Data.Finset.Defs Finset.decidableEq +D 4a1c203860122b18b3346ab908483a76ab7f41b244aa6cafe669857ff43ccfdc Mathlib.Algebra.Ring.Defs instMulZeroClassOfSemiring +D 4a37c7f1e2770625c4bf52de1df62c7cf826472a1f822f45702b9ff050dc9131 CertiFri.Merkle CertiFri.Merkle.widthsMatch._sparseCasesOn_1 +D 4a4386c045e4f787596c265681a3b0ffefde4137cd73dd1635ab9315f4e3d248 CertiFriProofs.Exec.Stark.Columns CertiFri.Exec.Stark.StarkModel.colWord +D 4a481642c9ca1267ce794b73317313f6f8eb9f60e2e2b43e4ca0d557861db57d CertiFriProofs.Exec.Stark.ChainTensor CertiFri.Exec.Stark.tLastField.match_1 +D 4a4ac37ccf356039409f6c339350e1818db861c8c0be71ae82f579c8f773c973 CertiFri.Stark.System CertiFri.Stark.BatchMessage.multiplicity +D 4a69873480f4e5d9764edaf42f3b51b2362b884302c8f75d3c5fb11b4f435eb7 Init.Prelude HAppend.hAppend +D 4b09d5f6f8c3d206730d1ff5a18dc72ee8f8a8190861535c0d2cdcb4f73f79c8 CertiFriProofs.Theory.Stark.Air CertiFri.Stark.Model.Columns.pre +D 4b305772bb980d0032f399ec56559bf223649e083e278ef28073186dba799875 Init.Core Quot.recOn +D 4b44031baeee7ebb38e4451bf1bca48081660793a2231eb528456ff48dcfc9f5 Init.Data.UInt.Basic instLEUInt64 +D 4b4a6fccaba41de82e0e1a6843164cdac62aac144c8626b1f02807e1775ff7b2 Mathlib.Order.Defs.Prop Pi.hasLe +D 4b5893b76ef0dbf0276aedc94526d830bb05f2a083769a16fdb474f77336f9b5 Mathlib.Algebra.Group.Monoid AddZeroClass.toAdd +D 4b7cff175a72a0ab1a9b4eae1eb2b1ec883782cdd669a22e7b7f59f267f8b277 Ix.Aiur.Parameters Aiur.minConjecturedSecurityBits +D 4b97b18772fbd522ba29e554a067341a4a7246086a8ebaf6c6ef78a0486c32ae Init.Data.Array.Basic Array.back? +D 4bbaeb4732a783c20dcc9040c1132f1439d2e233f908d9ba9ba779edede5a0cc CertiFri.Field CertiFri.fieldOfNatBits._f +D 4bcf7745153d0a1bd3d6955b35ebcc495bfea2d1248dce8c99dfa8d267f418cf CertiFriProofs.Exec.Stark.SoundnessPinnedBatch CertiFri.Exec.Stark.PAttemptPruned +D 4beadd610f86d28f6923416d7ff4b834ad7ecfe71f612e37f6c9f06223ab9bad CertiFriProofs.Theory.Compiled.Read CertiFri.Compiled.entry +D 4bf659b3c81188efa586ccea3f5c4f30def5f9c2bbd960aa16d6492384db0169 CertiFri.Stark.System CertiFri.Stark.Proof.intermediateAccumulators +D 4c02c4cb50f78fb154147320844c628b23a2f0640282547c3d898294b3eff512 Mathlib.Logic.Embedding.Basic Function.Embedding.toFun +D 4c129ab6426cd0e857e4c42097e4047a81a9b1555e32fa255446fc647ab950c6 CertiFriProofs.Theory.Stark.BalanceReceiver CertiFri.Stark.Model.receiversOf +D 4c2371966f6afd75ef8e00c129496cbf1e9addca69a447bb6b4b61ab27e93ae6 Init.Prelude BitVec.ofNat +D 4c356a9fda7b4f67a9680f8ce01917703a5d59cb4c48d94901e5e1518dd4e639 Mathlib.Algebra.Polynomial.Basic Polynomial.instNeg +D 4c37395805a1cb42b8675198636688ed7e31a758158791a4ecb8d04b600bc892 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.instZero +D 4c418f751121d39d949472c00955f3f4a2c85e0ec3e53dd3c5a936713de07f8a Mathlib.Algebra.Field.Defs Field.qsmul +D 4c5954309a2f942a0a557f335b17b87cdd572c59e5ec12fb49a659d287aa5fca CertiFriProofs.Theory.Oracle.MerkleVerify CertiFri.Oracle.HashQuery.casesOn +D 4c6c604440aa03080f546dd69e959b69a13c3f780bdd27b3c9f5009f8b3bf30b CertiFri.Stark.Admissible CertiFri.Stark.Admissible.fixedActiveOk +D 4ca1e1e95c52b8de38ecbaaf86b20e0f1e3bf68c251e53a024d30b69ce7944e9 Mathlib.Data.SetLike.Basic SetLike.coe +D 4ccb6bef04f716728bebff000139e02f4ac3222e6bdce7788254b7e590c7541e Mathlib.Algebra.Field.ZMod ZMod.instField +D 4d00bc72ec0d7d5b043b97725527d1f9b2f418c06047e829404084da6532a767 CertiFriP3.DomainSep CertiFri.P3.v6MerkleCompressContext +D 4d0ec95831f60f9feba99a551b6ca7a2ac19d240b6499de7c0ca7150a29314af CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.embed +D 4d24379045ddc932c7429b2edd32a6e982590d7babae3e7ac3aafea6998e1b19 CertiFriP3.Blake3 CertiFri.P3.Blake3.Node.rootDigest +D 4d31ddd8a7eb3ede4d661c5c4cbd5f755231cc38b28a2e6f4ed9f8e24a237165 Mathlib.Order.Lattice Pi.instLattice +D 4d7d6c310ecf28b2d2372959a18ad212514f743e63f5f373194d227af54fa932 Mathlib.Algebra.Group.DivInvMonoid SubNegMonoid.zsmul_neg'._autoParam +D 4d8cdbc4d3ada76529ecd4f1c8621d235340cd998402953658e57b555aafdf76 Init.Data.Array.Basic Array.mapIdxM +D 4d9b79cfadbe62c15945a31ef59b3c739ed97e64021708fdf2905f71ef150482 Ix.Cert.Release05.SecurityAudit Ix.Cert.Release05.Release05Ep1BalancedProfile +D 4ddb74067bf170b8c252e4b749727313d9dbaf406c2a1e76e201397101bb7c69 Mathlib.Algebra.Group.Finsupp Finsupp.instNeg +D 4dddc4888bc70f05792534c025fc9b43bb31e205bfbf35fee6d12f8bf8526123 CertiFriProofs.Theory.Oracle.Basic CertiFri.Oracle.OracleComp.run +D 4de89e88df2b1b163de23932e1c1f3752bea2901ef1482eef426ffce48233604 CertiFriP3.Blake3 CertiFri.P3.Blake3.Node.chainingValue +D 4dec2a0046a0dbcb845497d8033a1b4ae57a639639a3dc76c8f08309d1e2d85c Mathlib.Algebra.Group.DivInvMonoid ZSMul.zsmul +D 4df932429c6ecb306b97ddd6519f44d33b398b55c3337f7551c48cdd6e87da6d CertiFriP3.Pruned CertiFri.P3.PrunedPaths.siblingHashes +D 4e17e021272359b07fa1f76c59f9a3981fdd63ee1524b33a8bf320fe10b23b64 CertiFriP3.Wire CertiFri.P3.Wire.prepIndex +D 4e390b056912aa1f98a9470d41cdcfaf9f438be1f68876351092655954323420 CertiFri.TensorBatching CertiFri.Fri.tensorWeightsList +D 4e45649e9b1eecdecd8c8b7195335c8d73e38e1e19d6ec1b8c8a117102d5d972 Mathlib.Data.ZMod.Basic ZMod.instInv +D 4e51dac138b65f5c470ef392ad4b61938315e3fc34f8aaf5c852a715375dc7e2 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.instSub +D 4e57834df6808854056a8e04cfb6671ef37ed4e9b98531642ba7ec163c90385b CertiFriProofs.Exec.Stark.PrunedTensor CertiFri.Exec.Stark.restorePathsM.match_1 +D 4e58060bcfc45be50b9ae58ba4cb3fdc7ace09683fbe1dc95406986dbba70121 CertiFri.Schedule CertiFri.foldSchedule.match_1 +D 4e60a132ca3141df82f9c0c2cd39833d97618b8da80ae793311426fbc55a287d Mathlib.Algebra.Order.Ring.Unbundled.Rat Rat.instLattice +D 4e92f7e662977f706fa2376d9eb02e6c003ffa3c78ceb793d8a73dd32014c9d8 Init.Data.List.Basic List.idxOf? +D 4e95ffdb57bb2cd2bc9152382865cfc199804add2bcb395c62fb3979cc5325b6 CertiFri.Stark.Graph CertiFri.Stark.instInhabitedGraph +D 4ead9094352d33466c1fcac28eabce8ae9e930dc6850255a6c3516ed8aed8ace CertiFriP3.Challenger CertiFri.P3.ChallengerState.observe3 +D 4ee85fd528a8cf79831614df2782441eef943c399abf5711a05ef340e74bc997 CertiFriP3.Wire CertiFri.P3.Wire.uLEAux._f +D 4eee2997b6489e6f0ab25726c6877277dc0da6fcfed6796d83b00f880fd125c9 Mathlib.Basic.Nonempty Classical.arbitrary +D 4f012984722324d9a36fb52ec36b945f073b08fe2fec8b6517069b7845d4628b Init.Data.Nat.Div.Basic Nat.divExact +D 4f0e0c456fa632e7e27714a334fe36216d9fe47a4d72cedda789f888ceb7f92e Mathlib.Algebra.Group.Basic SubtractionMonoid.toSubNegZeroMonoid +D 4f1218f4c3deda5b53bbe8f64b7eaa791e15b34fecd92011a5c746c4ce2623f6 CertiFri.MultiArity CertiFri.Fri.siblingsMulti +D 4f2cbb809e5bc5df1e557b28c7c26d8e557cd66507cd541b68fddfc92eef1bd9 Mathlib.Algebra.Field.Defs Field.toZPow +D 4f4488a68a2dbc2724fd282908bc1b55ebe1e549f2fc6f845312169a73006991 Mathlib.Algebra.Field.Defs DivisionRing.toZPow +D 4f72e0b9a00c9e5fec60c11bd654a6b1e89082a24bb8c4f84d70c71011652c7b CertiFriProofs.Exec.Stark.Shard CertiFri.Exec.Stark.constraintBound +D 4f74e6a2efbfcdb0c6a4c637941f3fdc1e86aa5047d97d81f4dccdf13918ec88 CertiFriP3.Wire CertiFri.P3.Wire.Key.toPinnedSystem +D 4f8025a7c3c579ca5f89367e7e1b79b2c0127cc1ffd567e712a4fafd2283205b CertiFriP3.Wire CertiFri.P3.Wire.KeyParams.queryPowBits +D 4f8d20862cd04e2a7e6a92cd08ed14fb568d007ea9b43172da1a681251f5d398 Mathlib.Basic.Real.Basic Real.instCommSemiring +D 4f8ffd3933566760f90eb60bbe29186a6b184aa4cb8feed6c6404f8f185387bb Ix.Cert.Release05.SecurityAudit Ix.Cert.Release05.Aggr2p22_16ShShape +D 4f9241b854db087afa66a75e745f4b1d8a0f00a219e5f95d6dcc0b38a99c9cfa Init.Data.Int.Basic Int.instSub +D 50003ea8de3f474230223770c9f7e9b4038aeb4513c6399fd02cb2307419d077 CertiFriProofs.Theory.MultiArity.CompiledTensor CertiFri.Compiled.MultiParams.instDecidableFinalCheckTensor +D 5017a57b39c5ada751219fbb25852033086e8e1d7cde2f7d015c4021b8617c37 CertiFriP3.Wire CertiFri.P3.Wire.KeyParams.commitPowBits +D 502b6ad6a18accda50a05e5663ac2132facf7c7738cf53159cf46e5f6912d2bc Mathlib.Algebra.Group.Pi.Basic Pi.addCommMagma +D 5040f4f9ab1efa7c579a2b257fe97fe68af12381b897329be62b288337a1a367 CertiFri.Stark.Verifier CertiFri.Stark.shapeOk.match_1 +D 5073de12e6733a57d8677f46670fce52bf036134d281b92d63bcdf20913a62c6 Mathlib.Algebra.Group.DivInvMonoid SubNegMonoid.toAddMonoid +D 50743d02cd3b1e42ee4adb1021fb941faa24ba21d07ba4acd5c7b17a7d15710b CertiFriProofs.Theory.Stark.Check CertiFri.Stark.Model.ExtData.d +D 5096d7ffe081eb75a505d1df21091db3057d2a370ccd24479159be42e52c07bd CertiFri.Stark.Verifier CertiFri.Stark.residual +D 509da014bd5045b54b173b855fa67b9d833b2c2e4cfd249c557606e38d55108c CertiFriProofs.Exec.Stark.JohnsonPinning CertiFri.Exec.Stark.shardPairs +D 50ef20741364682ef6b76147ebcc0a33c361b9ca1ac7b1250386a19f5b8de180 CertiFriProofs.Theory.PcsRbrTensor CertiFri.PcsRbr.tensorCoordWeight +D 50f1893f72a9b3d44405b7ab82b37a45bc572daafcc8ce8408f085c67154b13f CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.casesOn +D 5146eb3d119249080919685e5532939800082d70f180b839c1eb6f381ac50db7 CertiFri.Params CertiFri.instDecidableEqFriParams +D 51470b97b61c210d5cc9b0dc6337ba7acd22e74462d96426a94b02350fe27865 CertiFriP3.Wire CertiFri.P3.Wire.KeyCircuit.lookupGroupSize +D 514f67e860ecfc7a2f96c267af790bcb87e0f782656ed7654eefa7a35fb1baf7 CertiFri.Verifier CertiFri.Fri.pointRefs.match_3 +D 5167c5c67c3abd3c23d6fbe147a93bb0a4bf6c54ff9d1c48bd68fe81f957dd72 Init.Prelude Array.empty +D 51740a1dc48b44648ba48c0577eda26f9d4ecce8d3875e8cc31f10b29e84013c CertiFri.Stark.Statement CertiFri.Stark.Model.oneAt._sparseCasesOn_1 +D 51bde429c07cc24b65cbe57427b505c58a49b35472bd72d50e86f01d0505606e Mathlib.Data.Multiset.Defs Multiset.card +D 51d963ef380d87932d01f88122a601b4f11f1c2e49fbf7d79bb7b64a31296693 CertiFri.MultiArity CertiFri.Fri.transcriptFromTensorMulti +D 51e3224844dcbaf2ba7cea71e400ec4dff8632b3059e4a8864632acd93d78261 Init.Data.List.Basic List.take.match_1 +D 52172846ff3835537c9345bc9dd1d322b383918a799125dc9248c103471b8461 Init.Data.List.Basic List.sum +D 522c288c2296c9690e22c3e17cf2a60b5d25a20300e0e08eef7f1bda6ada265f CertiFriP3.Wire CertiFri.P3.Wire.encU32 +D 523e7a5b24ac834583e167ab227e9eb711e323b7e469d2739f414b90fd291e6a Mathlib.Algebra.Polynomial.Basic Polynomial.distribMulAction +D 524736499f85445860f24b6649ea056b5b9bef9ec87795b205fb1bdf467198a5 Init.Data.UInt.BasicAux UInt8.instOfNat +D 524771e414e0fa9a3a810a4d5ac4b97bb3e012f96214077bc4a38f66a45aacc8 Mathlib.Data.Fintype.Prod instFintypeProd +D 52619b74b7d9ce34abd0302e8b7965802de29e45486882984ca7b73662e1acea CertiFriP3.DomainSep CertiFri.P3.v6ZkTranscriptBatchKey +D 5267b91bf9f8cf46e1285fa16118954b442764e4be24a5e3ee2090319d1366cb Init.Data.Range.Basic Std.Legacy.Range.forIn' +D 52722fb625d7b8a09cfd88c7c5ccfe46879775f0402ae174a609a49700f586df CertiFriProofs.Theory.Compiled.Read CertiFri.Compiled.Params.commitDims +D 5272f57438d3cb1fb2db4c45f552a94c09d3eee24ce28d6958dc1fa2489c4d41 Mathlib.Algebra.Polynomial.Basic Polynomial.support.match_1 +D 529ec8b086929b8258bdd1359f27f6f0c015ef2f2e63764cc7888ab3cd225293 CertiFri.Verifier CertiFri.Fri.checkQueryTensor +D 52a1d1ebe17a7412ca808f15d34975f55e0b2ba9f33a00c62e34da16a207e35d CertiFriP3.Wire CertiFri.P3.Wire.decodeKey +D 52a75d1d858399d0e0f18fef3a4f8a0a903e736fbe03c81143f389b20027c63c Init.Data.Array.Basic Array.instForIn'InferInstanceMembershipOfMonad +D 52d26202a65b1b53db4ab070be1419ddc26802452367b316205cf7b69c72fce2 CertiFriP3.DomainSep CertiFri.P3.v6ZkMerkleCompressKey +D 532273daa7311ffa26d860e455217c6782f0f601f501abf9c86df543f9b8c04e Mathlib.Data.SetLike.Basic LE.ofSetLike +D 53346cae9790cb9f75d9dd602799770f767cdd2f1ec76a37ea3747bb77940f09 Init.Core PSigma.fst +D 5339db1e703b8402703d732026f70075940e3db34f4bff7c985c11d65d6f6850 CertiFri.Stark.System CertiFri.Stark.Circuit.maxConstraintDegree +D 533f2f1f2c755b66838c34d5a60de99f9eed7bb46fb883b101d081c4f228b37f CertiFriProofs.Qrom.StarkPinnedQrom CertiFri.Qrom.SpongeDbBridge.dbLog +D 534964cdd85a0b3334cc69bcae15dcadf926394f425afcd1f02ddc385b409959 Init.Prelude instDecidableAnd +D 534fa081b048fac7d7608a381c06141c81345f7249e9494ad84a00210fd78081 Mathlib.Order.Basic Prop.partialOrder +D 536acd52fe0d85ecf95a4143aaebd3b004b6c9c400decfa80c8b1176551c9535 Mathlib.Algebra.Ring.Defs CommRing.toNonUnitalCommRing +D 5373f5d5a61b941959ce7e9c5638221246d9850a42dd71e497658f9c7a5b46f6 Init.Data.Nat.Power2.Basic _private.Init.Data.Nat.Power2.Basic.0.Nat.nextPowerOfTwo.go +D 5374f3ca1a413b949392deba6307a2ffd725149f2b989b90c07469d57da3eaa2 Init.Data.ByteArray.Basic ByteArray.instAppend +D 539ad725206cc79ab468174c555ce1236ba24fc953f55642c9032253a547681c Mathlib.Data.Rat.Init Rat.instNNRatCast +D 539d8d2a1c988ec10790c99d90c1701c3413db94202686782a178fddc9e77913 Init.Data.Int.Basic Int.add +D 53c51393e450985ef970fe6e2ef2ac23ce15aecec5b3bd29fa88ca3dd46b5fe7 Init.Data.Zero nsmulRec +D 53c58341c5c3f5d6034acc2ba5ef68b4ff43b6fb51f500ea13b42456af6a43c5 Mathlib.Basic.Complex.Basic Complex.instOne +D 53dffa7e4d4b1d451dabb9441e2e8bb924863721a0758eefbea30d62118f7077 CertiFriP3.Wire CertiFri.P3.Wire.encU16 +D 53e8f54b47fd0748be9fcfe08561ebeddc3dc3665291bf42b7e8eca0edffd846 Init.Data.Array.Basic Array.forIn'.loop.match_1 +D 53f27102c66f2b2364670dea45526f9b11ac43096541f0c3396f6043783459ce Init.Prelude Bind.bind +D 5403746cb4228842ff0ec6eb90f8915b7acbfde630870dd8af0c79102aa4e332 Mathlib.Algebra.Polynomial.Basic Polynomial.coeff +D 5477d6ad27d53e2ad72b6d7c467eed848bc99417dd94f1d60added797fa44f51 CertiFriP3.GoldilocksExt3 CertiFri.P3.GoldilocksExt3.one +D 5479fd02dd1441650e05311893d27a5a928c074801e84b63992138e893836186 CertiFri.MultiArity CertiFri.Fri.foldChainMulti +D 547d5a8fa96638e8533cc001d37745321a52440c8f7da91181b343410c3a130a Mathlib.Order.TypeTags WithBot +D 54868db3367e9a98049ede3c695dfa30a43c4c7a78f7446ea06859cd24fb5711 CertiFri.Stark.Statement CertiFri.Stark.Model.balanceKeyOk +D 549856a34ab7d48373efcc133d070fa38433c7b032cc372c41512e7692ed4c2e CertiFriP3.Wire CertiFri.P3.Wire.KeyCircuit.toCircuit +D 549b563ddab4d171ec1a77b60cec1f306f25f8c1722bcade695c00d7fbc6ab7d CertiFriP3.Wire CertiFri.P3.Wire.KeyParams.toFriParams +D 549cc4e74f44805c7758d21d80eb2f3abb9daf2ec364ddc440cf1ec5bcbc758e Mathlib.Data.Set.Defs Set.instInter +D 54c7befbcd7fd87b0721ff11d1c522301d533b239b1735df85c96ca146d9763f Mathlib.Algebra.Field.Defs Field.toDiv +D 54ca2de7516af9250c5edb2d682e4550b9e95ce87aba3aeebac16ff350f75c6d CertiFri.Stark.Admissible CertiFri.Stark.Admissible.mainWidthOk +D 54d056b1d7189777ec3b7357f0db6d314db9f776a8ad543bcc6df6ef99995b1b Init.Prelude instBEqOfDecidableEq +D 54d0b72337df08789e35a33ea646ed9ffe210f972fac088e4ac71a7a6daeab02 CertiFriProofs.Qrom.CompressedOracle CertiFri.Qrom.runAlg.match_1 +D 54dc4287d6e944fc5f81f8b56e59c2c327a5052277cb2dcd9c7c1497ed6c2da4 CertiFri.Stark.System CertiFri.Stark.BatchPreamble.messages +D 54e8035e618f58ac1db28cb7e62487534339dc764aac976e939fc47c22ae5b15 Mathlib.Algebra.Ring.Equiv RingEquiv.toEquiv +D 55056e453a7234a0ac2052823be670262b2ff0721251676a949e38611ddbf6ff CertiFri.Verifier CertiFri.Fri.openingRefs.go +D 550702654066c7962aaabab12cd15e1d2703221682dda2cadd88875a7087d9b7 Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.nonUnitalSemiring +D 55457dffa924afcca6fbd32fa524779aa7d5264659cebcc92391ecdbc8e2bb16 Init.Data.Rat.Basic Rat.den_nz._autoParam +D 55555a153e6a4353de1dd927432237a74041db7f5145c2299519b403e6aabba3 CertiFriP3.Wire CertiFri.P3.Wire.instDecidableEqBatchMessageGoldilocks +D 555bc09452ec5d5ef4da5f2ce180d7107ef4a23ff7bb11e35ab56aba952d7fc8 Init.Prelude instHAndOfAndOp +D 558dcce84f0d990efe56f3969cfd406757ea3b7f3afe7710041917d520b12f42 Mathlib.Algebra.Group.Semigroup AddCommSemigroup.toAddSemigroup +D 55ae77518380ebb52431324813e7c4397f69e964853858738ddbe787a1f76671 Init.Data.List.Basic List.Mem.casesOn +D 55dc66237ec0642deaa86245a26e866db45aa534d7a56130fb2828830bbf4c4b Mathlib.Algebra.Group.Monoid AddMonoid.toAddZeroClass +D 55de572543b9dac3faef01e777d5bdbde43c4ddb23a0309926d4e388a4adcc5d Init.Data.Rat.Basic Rat.instDiv +D 55eef1d57c3906072fc74c6e31f05258ae8618cad4a72aa7a69e61bf7c5ff4aa Mathlib.Algebra.Group.Hom.Defs AddHom.toFun +D 560ceaaf57febd1b5a69e5e7e633b2cd482da9e375af17c2c5a4f118d099a93e Init.Data.Range.Basic Std.Legacy.Range.step +D 5618b533c232b27b9c6448c4145c5a0b1589dcb1e2e39f8fabac74a98128e9ba Init.Data.List.Control List.mapM.match_1 +D 563c0ca149408a127638c764302bb3e245f7ec957a88931fb951295dcdb5ae88 Mathlib.Algebra.GroupWithZero.Action.Defs DistribMulAction.toDistribSMul +D 565e30febf5d4735ecb28fc51c2135db9aaf5c53a3563167e9cdcbaea120514b CertiFriProofs.Merkle.Tree CertiFri.Merkle.Tree.groupAt +D 5661e58ca4d3cefb22d06fc072f38e4b57e6f296c5f23a5687a10e822de19d9d CertiFriP3.Wire CertiFri.P3.Wire.u32 +D 566c3262e6970d35e43d5a3373251fb78b21ff18ebbc3c06376a7c190c9b6b8c CertiFri.Stark.System CertiFri.Stark.Circuit.graph +D 56ab7708f1d1e93a5d5aeaf2676db5d2a626d974bcd93e2f3f4f10ac7546a45e CertiFriP3.Wire CertiFri.P3.Wire.sourceCode.match_1 +D 56c0d0b57c0d79d9b7787aa5bc21f90f50d6967b56789b59a16e94f40da7274c CertiFriP3.Digest CertiFri.P3.instInhabitedDigest +D 56c2d61f839158b9d9d3d0495654421b620affdf99d4de40172b0a71151fbc7e Mathlib.Algebra.Group.Monoid npowRecAuto +D 56c9af5c5dd701a6ea5175162472b6c6bb7e7f531c3b49098891a4556adbe918 Mathlib.Algebra.GroupWithZero.Defs CommGroupWithZero.toGroupWithZero +D 56dacc9b43c4d2d7db2bde1907856e0ee09f1aa1d5e3f5feced0c5f1697db095 CertiFriProofs.Theory.Oracle.Basic CertiFri.Oracle.OracleComp.Outcome +D 56dd42f20919eeeb96bd96265143ecd059cc49530ab3472fc84711219cdf116d Mathlib.Order.WithBot WithBot.instPartialOrder +D 571bf13578f96d048c624f369897632db6d1372ece367d09f6dfa14a25140c9e Init.Data.UInt.Basic UInt64.shiftRight +D 574cb29687f94253f821497e5d85d7dfc5f0ac86deea97d509f7f19f59a5394b CertiFri.Stark.Graph CertiFri.Stark.ColRef.next +D 574db1c4e53c967670e781ddbf5082c2656b31900d4f8e1bde6a526d314905a6 Init.Data.Int.Basic Int.instNatPow +D 576943976a26dc3aa5589cc75d823e1b6e9fd8168532fc35394374ac369d5c1b Mathlib.Order.Defs.LinearOrder LinearOrder.toDecidableEq +D 57701676add6b82b4699ad9d34a5b7c4df73bc82bcebd35616a1fa8bf0023cd2 Init.Data.Array.Basic Array.forIn'.loop +D 578fd91197b18b2ba45b95d12e1ba1258760a7897d4770a9ffc18817cfbdfd2c Init.Prelude HAdd.hAdd +D 57a276f65fe61d5b3333b4bbe818bb66ec99272dd28294c8d8310d1aa7d4fdc1 CertiFriProofs.P3.ByteQueriesPinned CertiFri.P3.ByteQueries.pinnedBatchQueries +D 57bb5e8f8c14d1f96a147225c1220799b93ceb4636d48c2ecb0a3e18540764cd Init.Data.Int.Basic instOfNat +D 57d3326779dc58a595935a5103c4d466cf24cc08d5d7d01c2dd3ce9be404ca5d CertiFri.MultiArity CertiFri.Fri.commitChecksMulti._sparseCasesOn_1 +D 57d89348999f0f48ff66cd4de3cd5f381b01d0b5344f3f8d5e586e83e5ee4545 CertiFriP3.Wire CertiFri.P3.Wire.twoAdicity +D 57ec1363b466aeed40967a323bbfed8e1f2de6cf483caee3f323f5e4d47f5d53 CertiFriProofs.Exec.Stark.Shard CertiFri.Stark.System.FixedOk +D 581b669b629b630505200ac501db50939570aa93f36acf72e2a7bcacdfacf126 Mathlib.Algebra.Group.DivInvMonoid DivInvMonoid.toMonoid +D 5824f318aa17546e98308d946a7817bbcaa0427622e2865546ff47cb376a531a CertiFri.Verifier CertiFri.Fri.transcriptFromTensor +D 585e84956c94221362e8ab43ee5e0e2187bbfffa666f41b4b9395c170b2c53bd Init.SizeOf List._sizeOf_inst +D 58668d091796861666bcb974f9409aa05864d85b017afc9010bcda831b71b1a6 Init.Data.UInt.Basic instXorOpUInt32 +D 5869ee263e63b5c7478bfc02465af2c9de28ce4ec21e744ebadd4af653cd8469 Init.Prelude HAnd.hAnd +D 587f68c50c41670d0368d9eb95d55c695646c3195f5abdd22fc21546a47ea6cf CertiFri.MultiArity CertiFri.Fri.finalMessageMulti +D 5893348b52c63e3b98ac70c1928c2cead2be6ea61de29eef39c3550855256782 CertiFriProofs.Theory.Oracle.Basic CertiFri.Oracle.OracleComp.query +D 58a7001ee8ecefb2554a93c860e6aece181ad05ba6d4dcdf10c29f6725aa0b56 Mathlib.Algebra.Group.Monoid Monoid.npow_zero._autoParam +D 58efb1e1e7211ccf6ab930353686acaea53e4cf2e79c60c2e5e68b1b4ad93d8d CertiFriP3.Wire CertiFri.P3.Wire.u8 +D 58f5e831b5635daac68b8805825e1012e9e8458104aacc19f8ceae40501091c2 Mathlib.Data.Nat.Basic Nat.instPreorder +D 590a480ed9bd26799a1a627e5e04525bee42a79927529cd15e89401d2c16d686 Init.Data.Int.Basic Int.neg +D 590bb658ebc0a2bc8d36c695a58ee57c1c355ec5e29700c6a22f876d02ad3f02 CertiFri.Stark.Statement CertiFri.Stark.Model.circuitArityOk +D 592e7c844e1a536c90798b7f146c6a049ff4e9d1392c0802e301f3d5210fe523 CertiFriProofs.Exec.Stark.SoundnessPinnedSpongeMulti CertiFri.Exec.Stark.shardCompPinnedMultiSponge +D 5940d43f30b0bf0607cfeaf73dd269c69da357a29c1585b762038528f428324b Mathlib.Algebra.Ring.Defs Distrib.toAdd +D 594cbbc161ebbc6fa2440944d2f28f91f8ed5b9f4257e26ac14260af8bb7c5b0 Ix.Cert.Release05.SecurityAudit Ix.Cert.Release05.Ep1V6Hop4Shape +D 596bb8ad995c17a7d6d918dd5f35366c1e89c320350135747fa695f5eda94e86 CertiFriP3.Challenger CertiFri.P3.ChallengerState.observe3.match_1 +D 5975d8c179e3853eb35e2785d984e6d824c3315c9593dfd50c3701837a8655e2 Init.Data.UInt.BasicAux UInt64.toUInt8 +D 59a7e77d753f5f268daeb614ae78f3ff31753da8571ee18f7ff81b13fdc84b13 CertiFriProofs.Exec.Stark.PrunedTensor CertiFri.Exec.Stark.walkM.match_1 +D 59ac4a638b1247ecbfc4dce728c12da40f10cfd2520c681ae319ee97d50a7904 CertiFriProofs.Exec.Setup CertiFri.Exec.RawMsg +D 59d6b77882ae107f2f182bb42e9996b5bdbe8f88445614cd1b6777ce5175825f Init.Prelude Nat.sub +D 59d78ce5342e6936a3ff63ea1b19a0e8197ae6511784146b83ac5ec1f26efd73 Init.Core Quotient.lift +D 59df7070816d408b76b9a900979aff85fe9439d444efe3b4c9244907a4435b16 Mathlib.Order.Lattice SemilatticeSup.sup +D 5a3007b3fec9dc58640e3668d524823d5aac5d4ae279e253fa9c1aa4ede9f887 Mathlib.Data.Fintype.Pi Pi.instFintype +D 5a44f4e5697e51e616df442f9b1c9d79d94f32327172cc1e16df0fcb98f8b65c Mathlib.Basic.Real.Basic _private.Mathlib.Basic.Real.Basic.0.Real.le +D 5a4e19022f0046d7b75494473a22952b15ce1c3b122e97feae8a6b6087af4012 CertiFriP3.GoldilocksExt3 CertiFri.P3.instDecidableEqGoldilocksExt3 +D 5a4e50ebf1351eb9ad7f05f06bf4801c71a5a3e5f3567173b458f38142687dc4 Mathlib.Algebra.Ring.Defs NonUnitalNonAssocSemiring.toMulZeroClass +D 5a60262e4a11d9230f8e3bdd554b779992c4faaa1a03a0c690b696bf6224f637 Mathlib.Algebra.Group.Finsupp Finsupp.instAddMonoid +D 5aab27487136616bc93f50b3096e27f0d9d93002cbdbee58ff3d1964c10876c5 CertiFriP3.Digest CertiFri.P3.Digest.casesOn +D 5acb971d35fde8070b1a44c682bf1203da22839e4d966098b8b880a24571e3d8 Init.Data.Int.Basic Int.subNatNat +D 5ada7fb9c1377a73ed78d269f2e320a2dd72111d429d5a9c6c1cc3e32fb24444 Mathlib.Data.ZMod.Defs ZMod +D 5adfd66ac7d91342bcc8fa7f679de1c2d9e9fca81c8276c6a034d95e76005f8d CertiFriP3.Wire CertiFri.P3.Wire.KeyCircuit.quotientDegree +D 5ae348ea5a4bb2b0a941dd3c7af46759995d75400ed013f3e028a97da95ca270 CertiFriProofs.Exec.Stark.SpongeGoodLogTensor CertiFri.Exec.Stark.deriveSpongeA.match_1 +D 5b22b98812e53392214e0ac8c035d29aed6ba1ef2ee234eb95c8416adff17119 CertiFriProofs.Theory.Compiled.Verifier CertiFri.Compiled.placeRow +D 5b486f3e7dbcbf05f463222e77a4ecde3cd48750c5e8f9b54bf4d714346df668 CertiFri.Verifier CertiFri.Fri.shapeOk.match_1 +D 5b49efcf2c956fe0933c73145b6a74d823d9a8c9cac17c607c18aaa49f4f8837 CertiFri.Stark.Verifier CertiFri.Stark.batchFirstMessage +D 5b864ff71b84b0213fc5923e0df579b9309bf737d131002e37094193baa4c998 Init.Data.UInt.Basic UInt32.lor +D 5b928423d22b1e7585c5bada16fd113672c69d966e460a408533401669e9ba92 CertiFriProofs.Theory.Oracle.Basic CertiFri.Oracle.OracleComp.run.match_1 +D 5bb4798e2c1773629ff93b570e93dc61a64055877eca71f4ff7c085f2ed97b9d CertiFri.Stark.Verifier CertiFri.Stark.fixedMessage.match_1 +D 5bc50e13eed526090272591fc08ee503e12dd553f5687c1b82b05e841cf3cee0 CertiFriProofs.Theory.Oracle.MerkleFrozen CertiFri.Oracle.instDecidableEqSpongeQuery +D 5be72cdeac457b0ba207b55a8111658632ca3b0b7f852872f91e0772cfd7a422 CertiFriP3.DomainSep CertiFri.P3.Blake3Domain.keyWords +D 5bf6fd393d91611a5c86f31056f73fa390c5e32be4260c3ecdf1ec4f1365e024 CertiFriProofs.Theory.Compiled.Read CertiFri.Compiled.Msg.values +D 5bf997c421992dc13dc1dc2324de70b2763471107a34b593e1406f09bce8b19e Mathlib.Basic.Real.Basic Real.linearOrder +D 5c0f04a160870e956ad5175d2c2fd305eef984cc40564179d0c03406a2270261 CertiFriProofs.P3.DigestCard CertiFri.P3.instFintypeDigest_certiFriProofs +D 5c0f989faabea8b688d0f02973ab50fc26de96f01ee1af6c7a4f89671a99acbc Mathlib.Basic.Real.Basic Real.definition._@.Mathlib.Basic.Real.Basic.2153608522._hygCtx._hyg.2 +D 5c39f6cac5f21fb7b8c7f2bb3d9fceaccb5d7dfaf228318fabba2c41ca9dcac2 Init.Data.List.Basic List.splitAt +D 5c3d9d17776ee5859d8f2aacc89ace658d58a3161379692bf0a0d532589c8324 CertiFriProofs.Theory.MultiArity.CompiledTensor CertiFri.Compiled.MultiParams.foldChainMulti._f +D 5c415c3cc32c28490d63a2c977c342847c198622a04a82dcad4653f914d70772 Init.Prelude instOfNatNat +D 5c6498cae7e9b8f4a328d4574f90c529dd88f86a7cb1557a3554835126564c0c CertiFriP3.Goldilocks CertiFri.P3.Goldilocks.twoAdicGenerator.match_1 +D 5c6548b78c304d221016eb7ff94b0064d464be50475edb915b37fd09dee0dc87 Mathlib.Algebra.Group.DivInvMonoid DivisionMonoid.toDivInvMonoid +D 5c6ca4ec365146a8aa3587e74feae177f95cad7a22c5471c14ecdea95bcfe1d4 CertiFriP3.Blake3 CertiFri.P3.Blake3.pushChunkWith._f +D 5c6db3f9f1a03d19066e01ba33eb98655739619ecd825b128a75b02896edf279 Mathlib.Algebra.Group.Semigroup CommSemigroup.toCommMagma +D 5c6ed80fe1ee3b09b7691e15c5a9672f727afb839fbe4d46116de085a642c191 CertiFri.Verifier CertiFri.Fri.maxOpeningsPerHeight +D 5c930805ae08f1d15ca4d2da407913713f2720652487f76eb9d39c1cc2e3237c CertiFriProofs.P3.ByteOracle CertiFri.P3.ByteOracle.transcriptOf +D 5ca47cef9b2fb6588f9199562a729305988ff72032bfb03a47eb4298d3dc681c CertiFriProofs.Exec.Stark.FreeTensor CertiFri.Exec.Stark.UStateTensor.hist +D 5cc133d467de289c2fc48c6b08a729d77b93c29df88539150e8771bbffe61ad5 CertiFriProofs.Exec.Stark.SpongeGoodLogTensor CertiFri.Exec.Stark.spongeRunSteps +D 5ccdd240deddfea6f11dfb2906b24ab21117b8960ec974c0b6c01498787ee2dd Init.Data.Int.DivMod.Basic Int.ediv.match_1 +D 5ce8092762934c3eef0ac04653b88f780a0563861b7a7fa1f933010a66e35bf1 CertiFriP3.Blake3 CertiFri.P3.Blake3.State.v6 +D 5cf2a9cae45a3038a5f8423b3f6d2266444a6cd270d84d74aebbadf5806c57e3 CertiFriP3.Pruned CertiFri.P3.Pruned.Node.digest +D 5d067a57b4daf922050843376a25c06def3c2a1aba8d9a79cdb3fa08a0a56f5b Mathlib.Algebra.Notation.Pi.Defs Pi.instMul +D 5d0c4e1a6d93243eae52f96cf358222e546b4f9c6740bce2721e3e5d013a35d0 CertiFri.MultiArity CertiFri.Fri.foldRowMulti +D 5d289a873f7e3cce48a8d02249df88a4f66cf4e13a3e73175d59f926fb33c46f CertiFriP3.GoldilocksExt3 CertiFri.P3.GoldilocksExt3.instExtensionOpsGoldilocks +D 5d6e3c00986c45b9067bc5a622836fa805a4aa9410e0119eedccae3e79f7fa95 Mathlib.Data.Finsupp.SMulWithZero Finsupp.smulZeroClass +D 5d720f36b812e66d5cc81fe6d4496f5ffee80165d7eeccb6c413bc0f504879ca CertiFriProofs.Qrom.CompressedOracle CertiFri.Qrom.COState +D 5d80e20e40560256ddbc5d5bd649d25867831b9d23c1e9ed079b8ce54a94088b CertiFriP3.Goldilocks CertiFri.P3.Goldilocks.sub +D 5d84a2d658e628a4c17c295a6748df99fcc3203b0eacff42d07000575a6c4f94 CertiFriP3.Challenger CertiFri.P3.ChallengerState.sampleBase +D 5d9fdeffbf9f1f2560c9181985490334d2dbeb8d1ca91eb47f7933a1e168dce8 Init.Prelude XorOp.xor +D 5db04f84b4fb9e57aa78de1394f4f08d37414fdc43c30c070787d1e02fdb9001 Init.Data.UInt.BasicAux UInt32.toUInt8 +D 5df14cf55c6db95f5c9219df2f722daeb58509915aca0f63e030338f38c8ba8b Init.Prelude List.length +D 5e0125b495b029db7766271c561f07baf401af38a56037491641cf212e375e40 CertiFri.MultiArity CertiFri.Fri.insertDesc._f +D 5e0280ff985030f4ae7d88d78807bba71db87e694f2fc18f639f6c3eeef7ec32 CertiFriProofs.Exec.Stark.JohnsonPinning CertiFri.Exec.Stark.Selection +D 5e1cbd7ec3264440d1557ed6e0206ca3a57d99f81d09592078a8ba0823c2a4e1 Mathlib.Algebra.Polynomial.Degree.Defs Polynomial.degree +D 5e30ca1dbbade73cff1ff99dc0c0ac2912d0968a055e46f89977029be099f351 CertiFriProofs.Exec.Stark.JohnsonPinnedBatch CertiFri.Exec.Stark.batchPinVals +D 5e55fd7ce4139e3f8bd34e4dd163e97c1a2df4eaab9f51b4047b9406842c42cf CertiFriP3.Wire CertiFri.P3.Wire.Key.check +D 5e98d5d671cc8ef4702c20c573cb7775dc4cfc9fca9536dcc68ebde4a779bed3 Mathlib.Basic.NNReal.Defs NNReal.instSemilatticeSup +D 5ea79cbfec71406d28ddc559eb1e6f1834de59074c77242db06b3c945b7548db CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.goldilocksExt3_fieldModel +D 5eb3122edea189e99ef0c291a30478b3cf38c7bbfbf7ca896e7b98dc63420a24 Mathlib.Algebra.Polynomial.Basic Polynomial.module +D 5f0ef6a1950af2094cbe8548afcf6f9d9f9915d73cff8c843eb1b5a3874e3d1f Mathlib.Basic.Complex.Basic Complex.instCommSemiring +D 5f317fa913b44109682518d1971b9f5c440b3a3f53d92e0eb324243a3392e39e CertiFriP3.DomainSep CertiFri.P3.v6TranscriptSingleContext +D 5f58e4261c0469b107fd2004250770f5d5f4dfb1289ff275c3bc919cacd7db67 CertiFri.Verifier CertiFri.Fri.MatrixShape.logDegree +D 5f5e619be29e353feb2c505d35f13ca369ada95655eb19ad4e27d9c32d381788 CertiFri.Stark.Pinned CertiFri.Stark.openingClaimsPinned.match_3 +D 5f9e9cf5f709986e33656359e256a0cc7bdd7d0387cd262d55d346c8837b1d70 Init.Data.Int.Basic Int.decLt +D 5faca620901314fd82684258dbbd6f277d77b2b05981a4db390f4889dd87f092 CertiFriProofs.Theory.MultiArity.CompiledTensor CertiFri.Compiled.MultiParams.leafEnc +D 5fb36be7a879d46a94263fd59cda9ee7c4a9299caba58f10da3b04cdd615fe77 Init.Core Eq.ndrecOn +D 5fb46d255b8aa7664e703afb9009e93deb058b0d52a802ede4ff7567a10ae8fd Mathlib.Logic.Embedding.Basic Equiv.toEmbedding +D 5fc81a1374fc49df7cc0bfb01b0a9797244607f29a250e42a6b6021b92f47827 CertiFriP3.GoldilocksExt3 CertiFri.P3.GoldilocksExt3.sub +D 5ff355bee764e74ef39d9f310643d15ffc7a71f4245709991ec3ab8e60291675 Mathlib.Data.List.Defs List.dedup +D 5ff7d1961d1cb2aae7d627c366dda4552aa8049af5f7e3b4999c937f3484cf1a CertiFriProofs.Theory.MultiArity.Fold CertiFri.foldRowMultiM._f +D 6020ce44398f66fc9591c78e7f42b317cd2ce8ec0e9c637943b621d400ef15b1 CertiFri.Stark.Admissible CertiFri.Stark.BatchBounds.messages +D 602cc0da097cb52ed669694647a6e8d575e6dbed70e35e9963d678657ce8e96b CertiFriProofs.Exec.Stark.FixedKey CertiFri.Exec.Stark.baseOf +D 603db3450a4942d6874b99c1ce1c59e957ff670ba58ee106ce5bb5fbc21a0fed Mathlib.Basic.Real.Basic Real.instPreorder +D 6096cf5f3035a4e486a1a965b4a8ffe3f7b0ff91b9207c25834b1d25b8a3a26d CertiFriP3.Pruned CertiFri.P3.Pruned.Node._sizeOf_1 +D 60e3e72644f0b7682323715d271c1606ca7de6988e8daf9cae2d1601aa222a5b Init.Prelude List.foldl.match_1 +D 60eaf7e630dc98e43aaaefd15e649607f4dcb182610ae51010e6feab5d188f52 Init.Data.Array.Basic Array.mapIdx +D 60efa581986d04e2b61fc1b3a5974550d29f9744cef4a90abba0f7d6121697d0 Init.Prelude Nat.mod +D 60f6b40fe672303f458babdceee1ecf417095f468b8337d3be561b19399350ba CertiFri.MultiArity CertiFri.Fri.checkQueryTensorMulti +D 6102364944bb09ca65ab43e2328ebd6a321b8dd00a1a6dedb645bdf05c216432 CertiFriProofs.Exec.Stark.FreeTensor CertiFri.Exec.Stark.uAnswerTensor +D 6106328c07e04ef9c226f9cce1418825f2406ebdaff39fbecd9468eafc471eb3 CertiFri.Stark.Verifier CertiFri.Stark.lookupPublics +D 6108fd7279247d7f048e36811806597fb203ab4205567e51bcbe2d7e6353d206 Init.GetElem List.get!Internal +D 61097d6d73985a6a8914d1c31febffe7e270f09a54c0be7d6b54749188a00412 Mathlib.Algebra.Ring.Rat Rat.commGroupWithZero +D 610ca791b2d633f11d314bbd7bba6ed531d36e1cfce5ce14fe082f60bf8fd446 CertiFriP3.Blake3 CertiFri.P3.Blake3.parentNodeWith +D 61185b322ed722fbd95bb484db73424d3dfe81a9bae3992259dc6d700bd5e721 Init.Data.Int.Basic Int.toNat +D 6122397d161c97cacc7c24de52783a19516dcacc85bd66c974ab2d326c1284d8 Init.Core Quotient.liftOn₂ +D 612dd3a88f3f0d5ed5d3d27cee39d288e9b6e2fc6466bd16593c8178d9aa4c99 CertiFri.Stark.Statement CertiFri.Stark.Model.lookupWeights +D 61522aed1409de4c3b12efeb72727a230551c5b033f8540425ff634d305206e8 Mathlib.Data.Finset.Option Finset.insertNone +D 61534ab93d1b1d21be6e3737e811fa3c8fda91940b066465ede6786403002f84 Mathlib.Basic.Complex.Basic Complex.instAdd +D 6156edfe4bb0e649b03d92608418d05b39bbd0f9d6610ed49cc5d18dde72de13 Init.Core instHasEquivOfSetoid +D 615f37898d87dfeccf834fb0dde542705237fbdbc8b724271c9aa46b74b27d73 Ix.Aiur.Parameters _private.Ix.Aiur.Parameters.0.Aiur.udMillibitsPerQuery.match_1 +D 61842275bde888040a748c19d519e4a173ea9cb1a23d63a2e65466d9f8774198 Init.WF Prod.lex +D 61964b3aaab69f2aa58cd06dcf0a1a46f42cf794eddfd3d562a21bf506e75e10 Mathlib.Basic.NNReal.Defs NNReal.instPartialOrder._aux_1 +D 619ceee0bea4e4cc6212a990c517225f5c27368ee54342eca5b87514d20f3909 CertiFriP3.Blake3 CertiFri.P3.Blake3.finishNodeWith +D 61a07f12d543c09e01c4c63d01d7a427e214196ff70b911e962d84c8582e51b6 CertiFriProofs.Theory.Compiled.Verifier CertiFri.Compiled.Params.opened +D 61a4fa70329065792987213a6c6d41aaee7bb34d3ebeeff179cc5e6638cf6084 Init.Prelude UInt64.decEq.match_1 +D 61a52283e7f0912b011e6480240d17a3cb701b5c3afc5f280d14bf611dc69b8a Init.Data.Rat.Basic Rat.instLE +D 61aa9af5fe9f22cdcb7ce964eb3f6658e30c57caa0cc894d6de86555a2463ca9 Mathlib.Data.Int.Cast.Defs AddCommGroupWithOne.toOne +D 61b1fcd1636311ceb52e9d6a69202755460e9938abe7387acf55dca7cfa1c87f Mathlib.Algebra.Ring.Defs Semiring.toNonAssocSemiring +D 61eefc09c98021eab684880deb572b70b91934fac7b8c97350fd7a7acd220d9d CertiFri.Verifier CertiFri.Fri.shapeOk +D 61f82c809c5ed14d6fe915d13dca5879585887c012d68d9c632281b2b03f05f8 Init.Prelude Pure.pure +D 62153724278cb4a6698261ed2ed7785dda6589ec0fdae4c67676bc056817232a Init.Data.Fin.Fold Fin.foldr.loop._f +D 621e9d080af3f1ba9b1e9c59b526f372bbf6fda6287b364df4af7e37bbe138a7 CertiFriProofs.Exec.Stark.SoundnessPinnedSponge CertiFri.Exec.Stark.shardCompPinnedBinSponge +D 624f10d04af04f17e8a461264f6e31ca2fe4cf8df27091cde31c709ef4dbdea6 CertiFriProofs.Exec.Stark.BalancePinnedBatch CertiFri.Exec.Stark.balanceWeight +D 625c03e621b7e5c2e57d0f9dcf369208c4df4238bd4b57d9d9d081f94a3343e6 Init.Prelude Nat.modCore.go +D 6263695348f103cc12c5f277b7f5b75660ef348fb64c6b0d446ad85fbb9b5bf2 CertiFriProofs.Exec.Stark.SoundnessPinnedSponge CertiFri.Exec.Stark.restorePinnedPathsHashM._sparseCasesOn_5 +D 627252eee1e80db5b7a646faa9c79221013c37a30ce2652040c72b6ea94fbf33 Mathlib.Basic.Real.Basic Real.instNatCast +D 627ccac6e3f715fa0225451d8759b1adacf6c9ac700df16b3f72ca8f543dae4b Init.Data.List.Attach List.unattach +D 628807a71dc8c813531a34f5773b069b148dc4ec0a7eb28ee4f2b98fdf70b37f Mathlib.Algebra.Group.Defs AddCommGroup.toDivisionAddCommMonoid +D 62994883835ed7d19514b69e8a9febdf84960e732525f4dcbee8f5ad23056b79 Init.Prelude OfNat.ofNat +D 62bacb30834488f9362ead8d13cfa8e89d8e60061847cad4f800dd860331be70 Init.Prelude ByteArray.casesOn +D 62bf2e75c8988fe6fa0a29e77c47ed60bf3478840011fae5da5640ea81bb1455 Mathlib.Basic.NNReal.Defs NNReal.instLinearOrder._aux_4 +D 62dd9420bcf2a61d41bf89e1bd53bcec44cd1f56a49a79a36a32aff77ae99f7f Init.Prelude Zero.zero +D 62f5d8d95828ac8860d53ef068155cb174784968d2fd5e8ed05efbed5496feec Init.Prelude Array.appendCore.loop.match_1 +D 62fc5741734b4bd88a36570d1c9222bb8d79399451a1aa641fa6841ee350be5f Mathlib.Algebra.Group.Monoid AddMonoid.toNSMul +D 633650bd5ca00c82cd57026b0bbba07322244e1677af67515710ad140c547bf4 Mathlib.Logic.Embedding.Basic Function.instFunLikeEmbedding +D 633a77392b99b0ca7b1012cf6ca6d023279b5ffd63dca4638ff5bcfc0a105412 Mathlib.Data.Finset.Erase Finset.erase +D 633b790e5e73d1b37d42a78b4d9fe27550128299a87bd81dd1a63a51e7f816d0 Mathlib.Order.Defs.LinearOrder LinearOrder.max_def._autoParam +D 63535766c0e875d709a577d4771920700e91848383243c5404a48e76341eccd5 Mathlib.Order.TypeTags WithBot.bot +D 63861a696e77205f37cb16fd74195e0641b12d3ffa5dbb91e28a37d98bcf99bc CertiFriP3.Blake3 CertiFri.P3.Blake3.pairBlock +D 63864513a438496814ef6d881681c7e839fb28fd9991baa1df7ff11c43d1228d CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.xElem +D 63c504f4dfa77751fb3245d804fe56c95f0b5020d3dd12105ab11bfdbd3fe8cf CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.instInv +D 63dae87f8f20323f837ec2b9583f44cea8a0c5d1cfe3d0d4e40818e9ec181fea Ix.Cert.Release05.SecurityAudit Ix.Cert.Release05.digestBytesBlake3 +D 63dbfafaff2ae2588c6db3edc2a074fde2001aa4b1b7e3a7e097a70fad87cb6c CertiFri.Stark.Verifier CertiFri.Stark.rowsOk +D 63e6556f85ed6157691f483803b946ceb6f2bb2446901b3889b0adfdf8b9a726 CertiFri.Stark.Graph CertiFri.Stark.Lookup.multiplicity +D 63e95bd91bd731ecdb2b1e22ee63f8aa86141c75da6cb352460e900e16bd1b50 CertiFriP3.DomainSep CertiFri.P3.v6MerkleCompressKey +D 640a85ab2a8f52905a85337865edab5b4a569919b5a37d3ca712978645eb37c0 Mathlib.Basic.Real.Basic Real.instMonoidWithZero +D 6415b09ab7f272c44fcfc2974b531c06ee07a49461cfdf7f56c7bcc5f08c87e6 CertiFriP3.Blake3 CertiFri.P3.Blake3.finish.match_1 +D 64390efe19c4e74ee34dd8a66df82fbc5c84ee9a4b95933717edc421808bf59e Init.Core InvImage +D 6445a0a236006a86f08b587e1ece1516eebfd746b20d38f1db41cc49be11ca8b CertiFriProofs.Theory.Oracle.BadEvent CertiFri.Oracle.FractionLE +D 64522b86e661cebdbd4e98770160c0bd67b8a77640a7fc9c5876595f6b88f3ed CertiFriP3.Wire CertiFri.P3.Wire.Decoder.run +D 6458a1feeaf486feee6ae636d5ca3c4d1b5b6fbd5af6a6da895ee32ab9d00cef Mathlib.Algebra.Order.CauSeq.Completion CauSeq.Completion.Cauchy +D 64593f7a6c708b236df462688f678dd340956dda7009470dd946f0be061adfb0 CertiFriProofs.Exec.Stark.JohnsonLookups CertiFri.Exec.Stark.stage1Items +D 64595fc1c9b017d1c2cbe4b58c6c91fcbe78b7d824aa899c333207a9ff2d3443 Mathlib.Data.ZMod.Defs ZMod.decidableEq._aux_3 +D 645f0a234c7a8953542e86cf66b90d2d4ecce0d7800ae7b2e2d9c40636ed0ec2 CertiFriProofs.Exec.Setup CertiFri.Exec.extsIn._sparseCasesOn_1 +D 649bc48b3571ad36073358663d92dcb4eb82955ac5a9c3ad0b14764fb821166e Init.Core Quot.rec +D 64caaa1dd8179217672b3bee2b000177ca1c6423ec46d1d529cfa9307590f260 Mathlib.Data.FunLike.Equiv EquivLike.coe +D 64cd584749dc0671750e3da7773de8d39e5d123f56729f1207e656f45874086b Init.Data.Nat.Bitwise.Basic Nat.instXorOp +D 64e2f319ebb2c67fd34fb614f49f64b40738f3fd1cf68203bbe13c1e2da274e2 CertiFriProofs.Exec.Stark.FixedKey CertiFri.Exec.Stark.fixedInterp +D 6559e31016e11fabb2d786abbfcb2927dec0552e6d1d10651981f51f16a03146 Mathlib.Order.Lattice Lattice.toLinearOrder +D 65623fe4a58e812fd7f03d1d55a5103a1c87a5a734c7ccb2956ac9e5e2c15134 Init.Prelude Mul.mul +D 6568cc3978f3ccfcac99d6448d9f8453eb00200e89fad7ef9fbc014a39bb610f Mathlib.Basic.NNReal.Defs NNReal.instOne +D 659f47934f3652e9ef4014dd308214cd29ae054c3d4af41cd0ca086feeb7696a CertiFriProofs.P3.ByteOracle CertiFri.P3.ByteOracle.challengerOf +D 65a6cc1bcfe4748bfb9c3dedb1ad84501f2207270c6c81bf9361ab23526ed482 CertiFri.Stark.Admissible CertiFri.Stark.Profile.statementChecks +D 65bad7098321bf1027152b92c1d2622fae842aaa7a1f9906b9e4e99681b10837 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.instDecidableEqFp3Model.decEq +D 65e07f02aebecb95e61f1aa6f69b3bf133775bc9ff8133704d25de1b7c6f401b Mathlib.Basic.Real.Basic _private.Mathlib.Basic.Real.Basic.0.Real.mul +D 66206efe9a8b1720d5b339e04842e7c401f9306b14d3a06367c6fba43f098d01 Init.Data.BitVec.BasicAux BitVec.instSub +D 6641b10973d6a96f1754dc12310c03305c1b9a8d2d9859f1c4c6cd5c44d0204e CertiFriProofs.Theory.Oracle.MerkleVerify CertiFri.Oracle.MerkleRO.climbM.match_1 +D 664c4c30ea5884d45fe53458ffc1ce17dc3e9f79ef341d404e6f51606b919a48 Mathlib.Basic.Real.Basic Real.instZero +D 66655584db0b1b1f40d6d2a826e78e856f9d48dfac0c1afca2716abea9ade6a1 CertiFri.Stark.Admissible CertiFri.Stark.Admissible.zetaBound +D 66731a7a9eef864dc0e1a791ade850ce69431d54af994b4eeed6f4ab10b770ff CertiFri.Challenger CertiFri.Observation.ctorIdx +D 668990cda10d92ab67d4d3a0ecb481671f7a4d61f1f0a187fe9bbd72b1a28ae1 CertiFriProofs.P3.ByteLinkPinned CertiFri.Stark.Profile.verifyBytesPinnedOf.match_4 +D 66a967b6ca13cd5098634d6e2db403b941429d1014a2fe79b5a96d19467c90af Init.Data.Ord.Basic Ord.compare +D 66c23b77416c3d67a0a946e82e4fe17a505c609b7c67bdad3676cfcd31af305b Init.Data.Rat.Basic Rat.inv +D 66fc94333c7b8190b4f1e9123e30b16e837f257e8d8e12079021a432316148a1 CertiFri.MultiArity CertiFri.Fri.QueryResultMulti.ok +D 673f4dca555ff5adaadcfbcf7e51e75fb4002cec50fc7dc773efbf13a4a07e89 Init.Data.Array.Basic Array.forIn' +D 67477e5d8b954f4d9384621339a7c246d0e7c0f005de2103197c5f4e4777f8ce Ix.Aiur.Parameters Aiur.FriParameters.commitProofOfWorkBits +D 67478045453370ccde82440f779560474e9a94c9a4a10bfff0be070806208d05 Mathlib.Data.Fintype.Defs Fintype.elems +D 676a04e1e259f152d37b2480298ec359145b35e0c240b71786cd93acb48f59e6 Init.Prelude instHPow +D 6781b499630a8cb3695996857330a19081b87434ea2105476e28b6e787fd4c97 Init.Data.Nat.Bitwise.Basic Nat.hasNotBit +D 679227bca3e36c6c6779c3b1f951fc61aba928a3df4efee2b715f60989709034 Mathlib.Algebra.Order.Nonneg.Lattice Nonneg.semilatticeInf._aux_1 +D 67953d3398ebce847e9d3dc298ca7d30649361528b615e60aebf14ea7901dec1 Mathlib.Basic.NNReal.Defs NNReal.mk +D 67a0df8462db339cc7d692766b2fa7e8212a7658f6c40109d2147fd53422f654 Mathlib.Basic.Real.Basic Real.instAdd +D 67a60b2c347980672d2077b0d2944217db7d81cba8570d060d4f57b37408525a CertiFri.Verifier CertiFri.Fri.PointRef.logHeight +D 67a93c8414454f48b3fd4d93af1993e6a47e972611ea3efbea8b81ef5d125188 Mathlib.Data.Set.Defs Set.instUnion +D 67b33f40c55812d7d3973f785d7939d293fc0fcaffcc91a6c2ac78a4739e3005 Init.Data.Zero Zero.toOfNat0 +D 67bed80adc91ac8aa318d004ce127319ea7a5a8bbdd050d39e9e13012312e861 Mathlib.Algebra.Group.Pi.Basic Pi.addCommMonoid +D 680d93b0c62c706cf8bc022e14899b5b87ae2fb23c5fe3e55b7aecf0231ff788 Mathlib.Algebra.Group.Monoid AddMonoid.nsmul_succ._autoParam +D 68278a619adfaf72f3e2e71b9af588bf33794957673cc5fef215a8d37747672f CertiFriProofs.Exec.Stark.SpongeGoodLogTensor CertiFri.Exec.Stark.tagSpongeChunks.match_1 +D 6830379998c3c99a5f99f01306b4270a008dfe2b58c7061f669b30fd17b46fb3 Init.Core Union.union +D 683a3a8ad75428f478fd7cbaa0e067f9ec70c1db4fffda33b552229c5ac53108 Init.Prelude Array.emptyWithCapacity +D 6849245a42ea07f87f7a58e65c9bd7e6aa82eb1e6bb6ce10484580dff129d0c5 CertiFriProofs.Exec.Stark.FixedKey CertiFri.Exec.Stark.merkleRootComp +D 6851d5248202325870223a8962a0502cb7e14234a8ce6347f6d55c0b29701043 CertiFri.TensorBatching CertiFri.Fri.sampleExtMany.match_3 +D 686a8d6bbf2216bf12a5a2c0cb3a1b9dc9a75a800bbd0632f8468f34eac0907f CertiFri.Verifier CertiFri.Fri.ClaimRef.batch +D 688ca3b8abb86da0108e69fb0f39ba500d0ad0ad6c6adaafd9aec0180e4aa1ed CertiFriProofs.Theory.Compiled.Read CertiFri.Compiled.Params.shift +D 68cc09c531d0e02853c4625d29b179e6bac396580b2f9e9059535e0015187a47 Mathlib.Data.ZMod.Defs ZMod.decidableEq._aux_1 +D 68d5a02a2743d118599292c846fe46776f75a59753697ba311bd7aa78d56d996 CertiFriProofs.Theory.Compiled.Verifier CertiFri.Compiled.Params.foldChain._f +D 68da8f3b115d7ea2dfac19f4f3c1ccef69b9370361522636761aed9cb8166f1a CertiFriProofs.Exec.Setup CertiFri.Exec.friHasher +D 68e7c85426685ccacb7297869d432a7339d7f2fe77fd2b72baae24403aa91e5d CertiFriP3.Wire CertiFri.P3.Wire.maxPowBits +D 68fd27ff11b3b2144ff8198c067d6324cb9e5ce7475ae831c5539e8c6137b245 CertiFri.Poly CertiFri.horner +D 6906ce949d6c4167aedab7aa7902543426345a814815327da8149ffb1dbee946 CertiFriProofs.Qrom.StarkPinnedQrom CertiFri.Qrom.SpongeDbBridge.extractChal +D 690ead9e48ef3624ad39b56da4dd54bb0c32eb613adc26cb4356bb7a4a9773a6 CertiFriProofs.Exec.Stark.SpongeGoodLogTensor CertiFri.Exec.Stark.splitToSponge +D 693703497c224b53da6fc28ffa4f46c736c00b5367d43f7aec854a50ad030b96 Ix.Aiur.Parameters Aiur.protocolVersionV6 +D 6944e67fcbe4642a8dbaf22a5ae167f43b828ebd5e300809dccb0ebff5f668ab CertiFri.Stark.Graph CertiFri.Stark.Node.ctorIdx +D 694640cab3ba3ef3a6ed23b9e6ff0dc2bbf797c0691a79270e5a1be68ef6eefc Init.Prelude instHSMul +D 694ddc7bd749fbef93f2753747eebe87bfcf372ea379bb064a9509ffb7489ff4 Mathlib.Basic.NNReal.Defs NNReal.instSemiring._aux_11 +D 698d1b8be8dd15318f383af4b20745f46ead273b5f7eb7316171376486ed9b32 Mathlib.Algebra.Order.Ring.Unbundled.Rat Rat.linearOrder +D 698dd163ae1c301cc41e1a837e8ffdb9eb72739787f006082f7c67edcf6e60da Mathlib.Algebra.GroupWithZero.Defs CommMonoidWithZero.toZero +D 69943139c2ed9ed75a8f4d59e033e37b78b0a92c1e793eaab3437d245230878e CertiFri.Bits CertiFri.reverseBitsLen.go +D 69ec99921ce099adba5705837ad71d323660c419caab54888f3cd79d456123ab CertiFri.Stark.Statement CertiFri.Stark.Model.bound₂ +D 6a4a7a534df3e729d861f905bc1d8fe8d520880e170cd283ef9008f6d156254e Mathlib.Algebra.Polynomial.Basic Polynomial.instZSMul +D 6a4b6815e9ed116deaa55303046d72425c09b171ec0138f535ae96afaf5fab62 CertiFriProofs.Theory.Compiled.Verifier CertiFri.Compiled.Params.foldChain +D 6a4cdc88b0b989e253e8acdbbba227d700c22c7b39b9630dae0815996b498a93 Mathlib.Algebra.Field.Defs DivisionRing.toDivisionSemiring +D 6a71e1975a7edc2b824a3f127b37c799b5ea7d43ae5012769e1a1b229fcbe904 CertiFriProofs.Merkle.Tree CertiFri.Merkle.Tree.injectAt +D 6a88efee0fa50d0a37a9a4cb8989524ff8eb9afb97480450ab0ac9d4bdc799c3 Mathlib.Algebra.Field.Rat Rat.instDivisionRing +D 6aa2addc9fb4e24a1a100a1389a0630fae5b72d4dc1bcd149885c6f543e79388 Init.Prelude Eq.ndrec_symm +D 6aa42d88a5a0956822bfd68e6bc7da72bba2400b0be71f5b86c61006d74c3d79 Mathlib.Algebra.Ring.Defs NonUnitalNonAssocSemiring.toAddCommMonoid +D 6abc3d1305ea0c65f3eb3fc58aad7a20bdb00aa8853894dfe69b631497341f55 CertiFriProofs.Exec.Stark.FixedKey CertiFri.Exec.Stark.fixedMatsF +D 6adc737ff65c540a97b18d2dac8c4e6179c0086de3aab8adf2e92d45495812fc CertiFri.Stark.Graph CertiFri.Stark.Graph.zeros +D 6ae9a437be36a60a56006273a23b7b9d33f1376c1d94d97287641dd959764a64 Init.Prelude instPowNat +D 6b0159ea129087464cba2969c0df9e16b593dabec34c8b9863e5eda86a251426 CertiFriProofs.Theory.MultiArity.CompiledTensor CertiFri.Compiled.MultiParams.inputChecks +D 6b04dad9d918c83a6942b750c3fbffb86b8959126d0620a5deeb185dd543aabe Init.Data.String.Bootstrap String.instInhabited +D 6b12de18ed631bc70940c7107d242a5d9d10439063d6c47bfdd967e99f28bf13 Mathlib.Algebra.GroupWithZero.Action.Defs DistribMulAction.toMulAction +D 6b14405a81d9ecea171aaec85c9c65a5c34353cb4f34edfe9e919a02fb499b36 Init.Data.Int.Basic Int.sub +D 6b2916f8bf57e6bb344240122afa7bd71f0c66b4b273322470b1dcca0f9bb44b Init.Data.Range.Basic _private.Init.Data.Range.Basic.0.Std.Legacy.Range.forIn'.loop.match_1 +D 6b31a8c039941bdf8c27366c912236aa023379b1116b3e4a8f156d71a4f414f1 CertiFri.Stark.Graph CertiFri.Stark.Source.casesOn +D 6b36ec3d177b4ca63fd8196c157d284ae1aa119c376d7ecd093adcb1f3cccb5f Mathlib.Data.Multiset.Defs Multiset.decidableEq.match_1 +D 6b47ef5f9825d1a94066df7b624d7fc4317190e0325cd747f54d3283bd1ff3e9 CertiFriP3.Wire CertiFri.P3.Wire.KeyCircuit.maxConstraintDegree +D 6b48194c073351565aac7ea963f8e960c245e358502e2c59c4f6699e96874d8b CertiFriProofs.Theory.Oracle.Basic CertiFri.Oracle.OracleComp.casesOn +D 6b4e8facb6a3f6e981f01d524950dd51ebde6d20d7d5822e96704aa79b410a59 Mathlib.Order.RelIso.Basic RelEmbedding.ofMapRelIff +D 6b55b4ed7d74568ab1f2244b76e2e8326e4ebcde93b563642c6c32bcbf9c2c17 CertiFriProofs.Qrom.StarkPinnedQrom CertiFri.Qrom.SpongeDbBridge.decodeEntry.match_1 +D 6b698b71527c615a28943927139f6e8fcf63dc3206c6141b5d1b2aa3cf30c1bd CertiFri.Merkle CertiFri.MerkleHasher.hashRows +D 6b6e9e07373cde68093fc54f8d5da37d21ce05075841fc41faa1e0750056f870 Mathlib.Basic.Complex.Basic Complex.im +D 6b77f12a141105cceb4e9a3a2038dbf0cc1155690e3aadc97094aae6cb159e08 CertiFriProofs.Exec.Stark.SoundnessPinnedBatch CertiFri.Exec.Stark.BatchViolatesPinnedJ +D 6b79c52fa832efa05929dca1aa4dc5d4a1f30c859a327521195ea02684f5ce2b Mathlib.Algebra.Group.Fin.Basic Fin.instAddMonoidWithOne +D 6b986c5a8dcba03105731e71146056d628d2de3fa2e12a6458c234dccc94d584 Mathlib.Order.Lattice Lattice.toSemilatticeInf +D 6ba4c7f4a1ec88e35881accf141fbaaece0b26591003dffbaaa8d222f697dd92 CertiFriProofs.Theory.Compiled.Verifier CertiFri.Compiled.Proof.inputPaths +D 6badc94d0e8c8123c8ae72902af34645babbd9bf22928b4190b4c2d771be0b8f Mathlib.Basic.Complex.Basic Complex.instSemiring +D 6bafef0dd2bf01a74082a512ee1fa863826c188a8ca3c64cbe3d4436b294f872 CertiFriP3.Wire CertiFri.P3.Wire.digest +D 6be52fe3b41c44052d2d83d5579eaa91082ab1932c6809fa973f405e741f72dc Init.Data.Fin.Basic Fin.instSub +D 6bfce3e0103c3b975d76b0ca4c45321d7dc0b6bee438d2baee455d8d191a7a2c Mathlib.Data.Multiset.Defs Multiset.attach +D 6c0359ee97d3b8687ad12a0e4e50c3633cc6e29df4b5b0fd4c4b74116e4ffaac CertiFriP3.Pruned CertiFri.P3.restorePaths +D 6c03dd78c23bf5c9f230a0610a62086fc51b9f00bbe36ef39a7ce42f6b1179f4 CertiFriProofs.Exec.Stark.Model CertiFri.Exec.Stark.StarkModel.extData +D 6c0a2a2d918d107379681af2ec8066e393694d6635bcc6c7ed923473166a1b15 Mathlib.Data.List.Sigma List.dlookup.match_1 +D 6c138e98f49c6665e80807927b74b25a68fe399613975d359b4a03db9d5fc8b9 CertiFriProofs.Exec.Setup CertiFri.Exec.extsIn.match_1 +D 6c2f5ef3a57b99d071e11a40cd40b1b1fa481cb12aabe9753e07b1250cefdb09 Mathlib.Basic.NNReal.Defs NNReal.instLinearOrder._aux_1 +D 6c52c59060f5fcfcdb879921c003250583d04696aa688f8d5d082dc429e7d290 CertiFri.Schedule CertiFri.foldScheduleFrom.match_1 +D 6c5c91958645b6d71c1b8eb05945b6169d6f0254e11e5fb9534f15beb65a281a Init.Data.List.Control List.mapM +D 6c7cefd1e49028db1a45fcd25ade5048ac8365c7d08c1c296058bcea9fee6515 CertiFriProofs.Exec.Stark.SpongeGoodLogTensor CertiFri.Exec.Stark.splitRawByDigest.match_6 +D 6c954f55492d507cd30d465483fbf1ff93b264a8cd914349eb0c8d66636eb23b Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.coeffEquiv +D 6cea813728f3801e87da976e6b0ddfc558441189cd98f5c644356722f65a1186 Init.Data.List.Basic List.range +D 6cf5c66a6a76dcee2183360d1886f91fb6edfbf1e1dc3879f2388dad582e21f2 Init.Data.Nat.Bitwise.Basic Nat.shiftLeft.match_1 +D 6cfaf990d0c97623abaf4cc9b1f500ca65ce7558a5df7eb7b3670e78b9cae8f8 CertiFriProofs.Exec.Setup CertiFri.Exec.digestsIn.match_1 +D 6d18c5ea1220427a80ddb17753665099f92312aeb772e8817b8b821e392d7b36 Mathlib.Data.Int.Cast.Defs AddGroupWithOne.toIntCast +D 6d2b094e9f3bf283759a14c91fd0f6d0dad92180dfbd977f94f6eac733e8cfff Mathlib.Basic.Real.Basic Real.definition._@.Mathlib.Basic.Real.Basic.339334276._hygCtx._hyg.2 +D 6d5b22f23cf626a886babad17c6010a83337d3b9772c0e01f38d0c8848f8a805 Mathlib.Algebra.Module.Pi Pi.module +D 6d5f4352e0c1c587e878a20017eca47bcd2f00476807d39736c951504258cfc9 CertiFriP3.Goldilocks CertiFri.P3.Goldilocks.mul +D 6d6c917eeab01728a9cc551c4c878bfcc86eff81772fd71f548f30f3972f8288 Ix.Aiur.Parameters Aiur.stage1PinningV6 +D 6d943496089f1f09970237d1dda7edaeb7d3f99625decd25d4bd6c68e2bc4d91 Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.coeff +D 6db882a91d793af1233b39bad89cdf404ad79eb848c82802751a40ae61d8553c Mathlib.Algebra.Ring.Defs MulZeroClass.negZeroClass +D 6de2284dd05a843da22405fbb65261234572c284931e8c3c761859c7cc37329f Init.Prelude List.hasDecEq._f +D 6df19e0c06089ca4d488877aefe8091aad48365efff1e30f72589dfc438a0c3d CertiFri.Proof CertiFri.FriProof.inputOpenings +D 6df25a04134f37934175ea2a992e86dd7c174327ce96551edd3fa201c4520b2c Init.Data.BitVec.Basic BitVec.instHShiftLeft +D 6e301e37504c5aead76e2d4a7aac8604c33992020c9eff36ff15793679654ac4 CertiFriP3.Wire CertiFri.P3.Wire.encKey +D 6e37d448ba15f16f083ba82c6e97c4cff9da1117543da5d8c6307a9a71d7598a Mathlib.Algebra.Polynomial.Basic Polynomial.support +D 6e42394f050323032e0f980c6cfb74f02d7249fc4c0044f0f0fb55e80777e4f9 Mathlib.Data.Finset.Dedup Finset.toList +D 6e6975cd80dbc6c1f74c994ad8f9c90bf3eea8ee0596515dd09747a5ec3ed284 CertiFriP3.Wire CertiFri.P3.Wire.Decoder.runList._sparseCasesOn_1 +D 6e6cf9391c4261e5d98d32f1830ba54cb9ce53bfa4d4b764cc98219abb932423 CertiFriP3.Challenger CertiFri.P3.ChallengerState.sampleExt?.match_1 +D 6e87bf61eca143e3c0e05095f9261e4fb319fbafc99a30832606e82c01c9d9d9 CertiFriProofs.Exec.Stark.PrunedTensor CertiFri.Exec.Stark.restorePathsM._sparseCasesOn_2 +D 6e98bbbf46ed93e6fb08793eaf53237e6591f1f6a3221efa6b62339d650fef10 Init.Data.Fin.Basic Fin.add +D 6ec8f1c371e8803307a23f8ea64a71a02d4788abbdb646c0e85dc65b95661fc6 CertiFriProofs.Theory.Compiled.Read CertiFri.Compiled.Slot.batch +D 6ecd1d3669cc215cc690c67b0505a53a2a1a854e4ce6ed8e15f0731a1a0f5f95 Mathlib.Algebra.Ring.Defs CommSemiring.toCommMonoid +D 6ee29a6e2472dd00a95b83545b4d0821c91c947d7b0bbc53dcd286dbb8092e6c Mathlib.Basic.Complex.Basic Complex.addGroupWithOne +D 6f01c12fc09bb2eada01107cdd506958028ca106a79fa7ccf224442e09862ded CertiFriProofs.Theory.Compiled.Verifier CertiFri.Compiled.hornerEval +D 6f034dad85dd810734d651da5b03a23a94d126d45b73e779685f7ec4e486901e Init.Data.List.Basic List.eraseRepsBy.loop._f +D 6f2cb97b93e92f4fe0847d2429619a0f2541624170cb0e43c04085ca9084e858 CertiFriProofs.Theory.Stark.Balance CertiFri.Stark.Model.fpPoly +D 6f31102d0e71329a34da8d5e2e1da47e98168614fcfbb977d03c53f5ae334b1f Mathlib.Basic.Real.Basic Real.definition.match_1._@.Mathlib.Basic.Real.Basic.2153608522._hygCtx._hyg.2 +D 6f5aa4f78c309dfcf3264456dce4dcc776f17a7518b4d29cd8976bf0b166eaab CertiFriP3.Blake3 CertiFri.P3.Blake3.rounds.match_1 +D 6f6f2c2d8b05484f5a2e0b25d7d1fd5951ed5d751094f5e3cb6f33e87acc87ef Mathlib.Algebra.Group.Hom.Defs ZeroHom.toFun +D 6f953763dce428c4c61a8c935f1d2fe432403b2165897afe839e9aa371c350a6 CertiFriProofs.Exec.Stark.Preamble CertiFri.Exec.Stark.rowItemBound +D 6f970736f1d225bc49d098d8c6b0aaf5347543f0436de45b225241611f0615d5 Ix.Aiur.Parameters Aiur.extensionDegreeV6 +D 6f975c4c510e2de78f37d74a3d0029b7384b03d67649a0f1b7329ef4845e32e6 CertiFriProofs.P3.WireRoundTrip CertiFri.P3.Wire.NodeWireOk.match_1 +D 6fa2fc631ac349a08af9c6ff87a0ca89e68ce59d2e7fd38509ad913c04e76c72 Init.Prelude False.elim +D 6facc4c571502ca7c79dcf5c144c76562d161a80612effa1508eb3d75d156371 CertiFriProofs.Exec.MultiArity.TensorExec CertiFri.Exec.modelProofMulti +D 6fc0ee5cdf22e0342f1e4b6b08129cebc38d933566525e21c097cf531cc0eea3 CertiFri.Stark.Verifier CertiFri.Stark.nextPoint +D 6fcf65311995bb5b7f51e14af171228044ed0580dc27229a3280ab7c016ae1a2 CertiFriP3.Wire CertiFri.P3.Wire.Key.wireOk +D 6ff6d43ab05107da92865f40e032f4d6bbc3dc2ba50141d344ac5311285eb211 Init.WF WellFoundedRelation.rel +D 6ff75861ea5a5a3df2b98dc188ec7321ea3e7703f4b47362fed0e286a9b9d067 CertiFriProofs.Exec.Stark.Shard CertiFri.Exec.Stark.fixedShapes.match_1 +D 6ffd24f73e326c56cc3b34a6a481472d8cf3d3ba3f76264f9417b3cfee68a284 CertiFriP3.Wire CertiFri.P3.Wire.vkDigestOf +D 7013e9fcbc85e59483f0d8c1c6477df6fbd8b7afb9e1e84db0b74e46e9f95dea CertiFriProofs.Theory.Oracle.MerkleVerify CertiFri.Oracle.verifyQueryM +D 702d65dbeacf61bbe4661e92cbbdf46259fd58739e1c96222a7696ba3c65c612 CertiFri.Challenger CertiFri.Challenger.ok +D 7036ad76cf92b45a0c380659459a22e8277a82d9d9f0e647c8c3adfe5366978d Mathlib.Algebra.GroupWithZero.Defs MonoidWithZero.toMonoid +D 704f2adb56c693a479469620e829ce4073a11ada28bfc50e15468664f8303505 CertiFriP3.Blake3 CertiFri.P3.Blake3.Block.m12 +D 707233acce5036bcc76ee10968805c6bf9bd7226091f09bf5642679ce783b047 Init.Prelude Monad.toApplicative +D 7088ac012cdd73deea202866fbdd0a1775d3db7e4ebd6ee0a0ef5eb4833e7be0 Init.Data.List.Basic List.take._f +D 708e91c569c4ac262e60c376272a7a65cd4c664f9f273bd71f54c1266892b68d Mathlib.Data.ZMod.Defs Fin.instCommRing +D 70a359121a3effbca471ac0e4bdea22965c32ef668a4ef54f78726599c43c52a CertiFriProofs.Exec.Stark.Columns CertiFri.Exec.Stark.StarkModel.coset +D 70bff177e8d546d41c7494e87cb3b937b18fdf6f1919c7857c78abc34d1a016c CertiFriP3.Blake3 CertiFri.P3.Blake3.flagRoot +D 70fcbd879a53f13ee3936933464ba1290d6b62aa689fbb12dfe63b2b13031627 Mathlib.Data.FunLike.Basic FunLike +D 7108711ffd7d82e21efb426e6207b32c4d9aa635ae8314b7b8c95a5744699b9a CertiFri.Verifier CertiFri.Fri.batchDims +D 711268cdd40d850722a2ddaed745305a9add68ad1a4ac7338a1128bf3f4f8745 Mathlib.Data.Finset.Defs Finset.val +D 711a3b79fca334a15e5e79aba4b05d719e8f392bb6f69e437254625c9679229a CertiFriP3.Pruned CertiFri.P3.Pruned.Node._sizeOf_inst +D 71304e197da0bd2d2cb6b02ca26415167bd0998f573d2417d8cb7b569dc8e91b Init.Data.Nat.Lemmas Nat.decidableBallLT.match_3 +D 713548871bf297294d6f7e4d741fa7f7bc048fbe5d43d19b1c49327da27ac785 Mathlib.Algebra.Ring.Defs Distrib.toMul +D 714b997c0be6336cd207a0d1420368541b74068fd93fbf4e3f8db95cc2dd4939 Mathlib.Algebra.Group.Pi.Basic Pi.addZeroClass +D 715b6f243c59596eb959ceaac16a4e94432099db95f897369508a6330e30be47 Init.Data.Rat.Basic Rat.instMax +D 71991928bc74ba93c83d92c84954cfc4c1bb971900593637e41d63528b9bbac8 Mathlib.Data.Multiset.ZeroCons Multiset.rec +D 719b0c82d61aee154c6713d00ba79db7a2e403343c10a5f197be771403e10336 Mathlib.Data.Multiset.Pi Multiset.Pi.cons +D 719c0be1715b0fb03826422e084fac635e4cf4d6a352bb27e5437466b44517de CertiFri.Verifier CertiFri.Fri.foldRow +D 71a26161bc297606cc4eebe969d214bf132b5f23c5ccd01874e74e91e170fbfd Init.Data.Option.Basic Option.bind.match_1 +D 71b995a25cee56359669dd6e6e8f73ff3df7d962d9dfda93712afb236487056f Mathlib.Data.Finsupp.Defs Finsupp.instFunLike +D 71bea5e0175b1893ebca2480c1f3108f08c7c0e4ec8c4c28a34bc6a3aeca7ec8 Init.Core Sigma.casesOn +D 7208bdbbf3c199c1cbb780a824c4894bf8eb50a20b2eba0caf37b994a969ab10 Init.Data.Array.Basic Array.foldlM.loop._f +D 721277aed9a03cc968ed82d77a9913ccc567c7b5b9bcb616aa3152e91a638f85 Mathlib.Basic.NNReal.Defs NNReal.instLinearOrder._aux_6 +D 72428dc399c999a116bab83a89256d04cf3e4238537708d51001eaf8421047da Mathlib.Algebra.Order.CauSeq.Basic CauSeq.inv +D 725136640848cc3d02fa9aca0c7ecda25522907265136f97a3281e1b7d3db084 CertiFri.Verifier CertiFri.Fri.foldChain._f +D 7251804ed67e8937bbcdc2796ae5dc16d89a182a8431fbf7fa2e56459f0215ea Mathlib.Algebra.Group.Monoid MulOneClass.toMulOne +D 725aba8d030dabf71036fe03cb0946f18a35bbac0ac38becfff75392fd142246 CertiFriProofs.Exec.Stark.PrunedTensor CertiFri.Exec.Stark.ascendM.match_7 +D 725c73025033a8c045bdff5a7bebfb3ad12334f94c6f476a592289ae706cb185 CertiFriProofs.Exec.Setup CertiFri.Exec.modelProof.match_1 +D 72624c8962b506d51abb42253ea90886436cba2f92dc23b7988e7d8ddde5354b Mathlib.Algebra.Order.CauSeq.Basic CauSeq.ofEq +D 7264a4aee05fb24fd3a5372116b765300c52da65a6ca5767cf2175ff3bc974eb Init.Data.Array.Basic Array.foldlM.loop.match_1 +D 72651ca9411a88828f6236f0f9c85dde4023439d6448a8e8f627383dcf27978a CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.goldilocksExt3_refines +D 72764c7f45d807ea69512b36e4ca952e163a66c05e1548516d5c62aca7adc001 Mathlib.Data.Finset.Empty Finset.instEmptyCollection +D 7295ca206778828d39991a372020bcb18967d4b87b97d3c7b81de4268b8a8813 CertiFri.MultiArity CertiFri.Fri.distinctLogHeights +D 72a98cad40e9ac92248e49aea6e77a89bbf5926cd7043841fc3ce260039f8269 CertiFri.MultiArity CertiFri.Fri.shapeOkMultiArity +D 72b1827325d6f5298b5bf4b8eac8a799fda2dad0be8c1adf4e983913b54d0b9d CertiFriProofs.P3.WireRoundTrip CertiFri.P3.Wire.NodeWireOk +D 72d0cc15bbd3abbd02cee7cb7cf85bf67545738418715d6cb224bf1b712ee807 Init.Data.Function Function.RightInverse +D 730dc25b2936f476d14e32fbcdc60ec554089ff34ab80d9936bb050ea04304d0 Init.Data.BitVec.Basic BitVec.instOrOp +D 731048274c6468dd06f4bdf0e7048824181bdd7af6ec3343df46127ae84f1519 CertiFriP3.Blake3 CertiFri.P3.Blake3.State.v15 +D 7318a30eb3d41b03303eb031629d998128b5c6a98bd35411b0322d4831107c03 Init.Control.Id Id.instMonad +D 732e0dbbf4bf54a1c2f170adea53c2a6007252704ff284d9231761302c430794 CertiFriP3.Blake3 CertiFri.P3.Blake3.pushChunksWith._f +D 733cd07c86f5983629793f281b05a986fe90a9e8671d74ffc3810d26e352601f Mathlib.Order.Defs.LinearOrder LinearOrder.toMin +D 73664e839ddb645dffb9dab8f64491c96ec09a04f1d4ea635ed3082aa1552c13 Init.Data.List.Basic List.isPerm +D 7366bd9346b494409372a04eb5dc9db82e04c94796fa88d74ddb30f998fdea73 Mathlib.Order.Defs.LinearOrder LinearOrder.compare_eq_compareOfLessAndEq._autoParam +D 7394a3a7d32b9664eb23aa31bcfa31da8928b029bfa853f7761d57c9bad50823 Init.Data.Nat.Bitwise.Basic Nat.instShiftLeft +D 73b6d039b1fe5093bfcc9983a33cc35000168f8d7e17f3f8c3ecfb081e384bbb CertiFri.Stark.Graph CertiFri.Stark.evalNode +D 73bb0e7cba7432d4a77562d35cf27fa6e112f583ca4345a0a92b295c76d714b2 CertiFriProofs.Qrom.StarkPinnedQrom CertiFri.Qrom.ForgePinned +D 73be9ab4320b4dc52dad10db2523ec9d24de0b51d9866ce1b318e01f9be37222 CertiFriP3.Wire CertiFri.P3.Wire.shardHeader +D 73c8a0e0a9fafe3f27d5b4732721adac350b4a77f7d382e49d9d6a0fc7dd5a49 CertiFri.Stark.Admissible CertiFri.Stark.Admissible.plainPrefixLen.go +D 73e306535483b12bd3e76f1c11a51c63b87b0b3401ddc67f7343862ed8c08bf6 CertiFriProofs.Exec.Stark.FixedKey CertiFri.Exec.Stark.FixedTrace +D 7401a3eea9c75297445ccea9cdd6dc6685b130f4dc0e350d0e60535133ccbba4 CertiFriProofs.Theory.Oracle.MerkleVerify CertiFri.Oracle.verifyQueryM.match_1 +D 74063a4278005798be4d909c5ca03faf4c23fb35dc985d1d4641ff1553b9ee4b CertiFriProofs.P3.ByteLinkPinned CertiFri.P3.ByteOracle.verifyBatchPinnedOf +D 742272999a08a2006babb5a759e4e66e75e4305773b8a3b498c42b89dca81490 Mathlib.Data.Multiset.Range Multiset.range +D 74259ae009793f3d7aa967850abb0928f771a98c6c2f9bd57da2122a0c0ded4f CertiFriProofs.Exec.TensorExec CertiFri.Exec.tensorCoord +D 742cb1f34505ccea573c6d8725351e1546b00d9a0b1d03e25258b949970864d1 Mathlib.Data.Fintype.Option instFintypeOption +D 7452485d9e273f2e042b21f372cebe23e420ee823bd665fd4da941d1babb02e0 Init.Prelude Nat.add +D 745645e8048bfebff6a69af2ef05898cbc2c308a4824f794183f5c4bd199dd6f CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.instCommRing +D 746733cb1c00babdd64d19fa1ab25252018ea77f472cecbdd2494c4513e96131 CertiFri.Verifier CertiFri.Fri.commitChecks +D 74697335f1ab4524a6dee77f86473f19029e1a2b36615308ea27b9b0f071639e Init.WF WellFounded.Nat.eager +D 7473d3b14c475c3cfb30b157fc658346d0c25c152f0ada1936515f8581498791 Mathlib.Basic.Real.Basic Real.instLT +D 7486b7d6747db3fef193bbf737ddf12bb006c132335cb38759bc2cc2ce8e0521 CertiFri.Field CertiFri.FieldOps.toMul +D 748d18cd70967bad08d75c4d620f5dcbb287c0fd9e5cb37da08918b8c0865b39 CertiFri.Stark.Pinned CertiFri.Stark.pinnedMessage +D 7495d1ccc6a3211d4ef95f1bf04cd54ac1231cdf6e8c1ffee251ef1c60f2f3df CertiFriP3.Blake3 CertiFri.P3.Blake3.flagDeriveKeyMaterial +D 74bc33ee42bf1b98d8d702b22d7bc293095a4a134dbf3a1ff583dc68ed32c665 Mathlib.Algebra.Notation.Pi.Basic Pi.single +D 74de7002eb36f49a8cf75b76f660917f8dad610b56648854a09ab0dacd9ca465 CertiFriProofs.Theory.Compiled.Read CertiFri.Compiled.Msg.point +D 74e48fb1b2167848826a3a555b8b45695dd5a65cf4de72399a90c72bda585478 Mathlib.Algebra.Order.CauSeq.Basic CauSeq +D 74fe7b4fda8a061ab4b69767c84ae50e74262715b642813936f0ed4801516a53 CertiFri.Merkle CertiFri.Merkle.groupDigest +D 751b1dd651a8e81476af28cf4f0760dffb19cd08a126aeba476dda8ad553e316 CertiFri.Verifier CertiFri.Fri.OpeningRef.pointIdx +D 751d03bc8e3968afaef7b5dbb74576f971593bb00faeb94a0d97fb96c021c1cc Mathlib.Algebra.Order.Monoid.Unbundled.Defs Covariant +D 7525403d05354d63730268610a805bed64db3ca50f3b5dd97af2814ee75fa4f2 Mathlib.Algebra.Order.CauSeq.Basic CauSeq.equiv +D 753dd7710e6701fb31d980791e11a8f7456ecb237326fa75fe20ffae126c33a9 CertiFriProofs.Exec.Stark.SpongeGoodLogTensor CertiFri.Exec.Stark.deriveSpongeQueries._f +D 754ee2ce3ebc3e56327e2324fe0e222028191e3346ad51c76f3d941ba312b5a5 Mathlib.Algebra.GroupWithZero.Action.Defs DistribSMul.toSMulZeroClass +D 755a13a86a971352635e762f20e5cae30da0529ab379a6bdfb7a676efd5cf6a1 Init.GetElem GetElem.getElem +D 755a1ca39deaffe61fb4f90eb2d6722ab29d92efc38600f3d653996929a9d77f CertiFriP3.VerifyBytes CertiFri.Stark.Profile.preambleChecks +D 755cdd6e1d3e8e2f4cf3072dfdd4a7da4dae482e88f7e0ce68a9328922aa9a6a CertiFri.Stark.System CertiFri.Stark.Circuit.preprocessedHeight +D 75bc03a154458759c2bf2e09ee435b62e73620e3134ae87f6f7e1b6006870db4 Init.Data.Nat.Bitwise.Basic Nat.instShiftRight +D 75f42bb68e4cfb4b935ce628ec1bdd59205b61c2fc8b6748a9aed03278a464e0 Mathlib.Order.Defs.PartialOrder Preorder.lt_iff_le_not_ge._autoParam +D 7616d1aaf4bc8cd0f62624d7fb15e08387dc43713ce38bc8dc1f3e9fe0b3e917 CertiFriProofs.Exec.MultiArity.TensorExec CertiFri.Exec.modelProofMulti.match_3 +D 761ac79e38bba9912e6402ca33bcc6fd746172c01c63f11cd4af0bbe30c458d8 CertiFriP3.Challenger CertiFri.P3.ChallengerState.sampleBytes.match_1 +D 7637cff7b50c72df3a0151252ba243b356b3dc20ce7569520bcb925f78181ffb Mathlib.Algebra.Order.CauSeq.Completion CauSeq.Completion.instAddCauchy +D 763e0e7d7919acde0a86157df72a1c7ee9113f55083c1b5800ba862209f53399 Init.Data.Rat.Basic Rat.instMin +D 7652a2b6c6a9bd30d1a24768cffa53f7d6538cf85543a0aaf87dbdd61d918e81 CertiFriP3.Challenger CertiFri.P3.ChallengerState.sampleBytes +D 76633381f84fd3e0cb8d9623228e2f66c3d31afd737b1fd1f8bd91f035fc715d Ix.Aiur.Parameters Aiur.CommitmentParameters.capHeight +D 767a1a5a996743ecb47e01333e7602414571196015858d6cca3498d9d52ba15a Init.WF WellFounded.Nat.fix.go +D 7682c7c81d5dfb86cfae86915528e4b56e623ba87029e9a3e3dd01b9057fd577 CertiFriProofs.Theory.Compiled.Tensor CertiFri.Compiled.Params.reducedTensor +D 76848c04dc8de854d0dd7da304603ddb791d72f159e268e84ceb438fc9a449ef CertiFri.Stark.System CertiFri.Stark.instInhabitedCircuit.default +D 7687cc65fc492e69f7d14f9aa6f53e627fd0f2f6ef4f5c62a07e1dcc8e864638 CertiFriProofs.P3.DigestCard CertiFri.P3.digestEquivFun.match_1 +D 76a4d99c1b6da86b7d4c7abd9046e98db574f69fa5d175bc57bc218596d862b4 Mathlib.Data.Nat.Cast.Defs AddMonoidWithOne.toAddMonoid +D 76adcc716a06187b557f0f7a48027f138a4cec5f7a33c8c811d5093bc2de1463 CertiFriP3.Blake3 CertiFri.P3.Blake3.State.v1 +D 76b814510b7f5cd8a4316b57ecc60866b32b626547529cbe293bf68fac2b3cde CertiFri.Stark.Verifier CertiFri.Stark.fingerprint +D 76c8b02df568da265fa4714e09c78472fe205d1931a9b210c785ec43c299b458 CertiFriProofs.P3.EncodingInjective CertiFri.P3.Encoding.HashCall.input.match_1 +D 76c974bbd2a70e84490d896bd6d768653fa6c2cc237d12a39c9d0b74fee26976 Mathlib.Data.Int.Cast.Defs AddGroupWithOne.toSub +D 76ef4da3ac86e65ac089236b88dad4b4df07e56aab9a3ac1efb1b8ca069539dd CertiFri.Stark.Admissible CertiFri.Stark.Admissible.boundsMax +D 771e9a3ac276dd7f897502828c99f0cb4541894d6c5a285b09d375a1b63d0f81 CertiFriP3.Wire CertiFri.P3.Wire.flag16 +D 7753df33df92c684287ad71359346a81bd5c4c0f856ddd81398fc55ce29b2ccb Mathlib.Basic.Complex.Basic Complex.normSq +D 7772be8c3baaa02b36c5d6c8a5f2ab607331d99320bb47f1286a4a546c144f40 CertiFri.Stark.Statement CertiFri.Stark.Model.boolColOf._sparseCasesOn_3 +D 77787fd69cb86f1bae60a958cd21c2d7fef7e9e19b70723e1bd3fa5add648b93 Mathlib.Algebra.Ring.Defs Semiring.toMonoidWithZero +D 777d14e683ed27d3279e3dfb42e2429293886246b9e9e80fc1d27fc1cf5c6b0c Init.Prelude UInt8.ofNatLT +D 777feafbf18d2b3cf65a5cf321f305b8e378dadaf50c3158d9bd7d9159722cec Init.Core ForIn.forIn +D 77845545f822e68c1674ec6fcf039fdf070192b836ec1dbcc24e5c0d825d47c1 Mathlib.Algebra.Group.DivInvMonoid NegZeroClass.toNeg +D 7791b2063329acd0bc2995096ce086bb2f654c59481460cbe86acecf7e48a56f CertiFriP3.Wire CertiFri.P3.Wire.PinnedBatch +D 7792f4af166862ba1b5af28ae08bff137a373cd87fea4cbc83c24746d7234800 Mathlib.Algebra.Ring.Int.Defs Int.instCommSemiring +D 77939b1d72daf9a7986a412af0567d2bc083a441e05987bbdf38b8d450b7e727 Mathlib.Logic.Equiv.Defs Equiv.decidableEq +D 779cbb363ff95a4d42d8ea97f4961fd0a99f78b72c7b931df57cd50fedc74f6f CertiFriP3.Blake3 CertiFri.P3.Blake3.Block.m1 +D 77aa633ee82f9b2f9d8863bb2b1e096f7d18db9eee2b65be563c92fd1f3dbb1b Mathlib.Algebra.Polynomial.Eval.Defs Polynomial.definition._@.Mathlib.Algebra.Polynomial.Eval.Defs.2849575019._hygCtx._hyg.2 +D 77c8defa8944f67517ed9c5b514be66b16342bf021d663846b414fb7b71f3032 Mathlib.Order.RelIso.Basic RelIso.toRelEmbedding +D 77cb900b9c2005126e0aa03af619b0d1bbda42a7823bed273134e6c153582134 CertiFriP3.Wire CertiFri.P3.Wire.messages +D 77e0cf500edea4a6ee50467ccf8a4b5b19cbfaee15461957af41446be5b35fd2 Init.Data.Cast NatCast.natCast +D 77e2b003473a7bfcf461a53054a3f72cfa118e35c0f5c1af59fc58239bb746d4 Mathlib.Order.TypeTags WithBot.recBotCoe +D 77e598b21e43e27fe30fc2c4d938c70a99a303ff13fbdf8d94b8026b486b9466 CertiFri.Stark.Graph CertiFri.Stark.RowValues.var +D 77f091c361f6351943c8a02777d71d5989df09b6009e4dc97c0538a7641c1d27 Init.Data.List.Basic List.Nodup +D 783301ae1ff452ad21d6f1fdd08d39b2049b1441857533b107d555170a8041c5 CertiFri.Stark.Statement CertiFri.Stark.Model.bound₂._sparseCasesOn_1 +D 7857ce529a4d3b723e2aff00e2ca78ee31e72d08d06db575e9370e12480f1b4f CertiFriProofs.Theory.Stark.Graph CertiFri.Stark.Node.Plain._sparseCasesOn_1 +D 786104600ede009e942207d1b48eeb2de1681f30d1376d005436b640c64a18f3 Init.Prelude List.flatMap +D 7871ae294203843fc7e519fff895b22ece05b6cb27c01839efc4f57bfe747063 Mathlib.Data.Nat.Cast.Defs instOfNatAtLeastTwo +D 789acd35f19cfdbcd40376b3b0d1057211d410582ebcc3d3300c91468d4a6c0d CertiFriProofs.Theory.Stark.Graph CertiFri.Stark.Model.nodeVal.match_1 +D 789c316f95b79adef2f2115b8a4471241556484d4ea05f798c6351459ac3d2ea Init.Data.Array.Basic Array.foldl +D 789cc84e69af1c330ed2ac80f3a02852ec4ea2882a41e7a30cffb4fc8ed1502b Init.Data.Cast instNatCastNat +D 78a683ec7a993f22af303d7b425125685f03848fa8a266584d58e98f38274c80 CertiFri.Verifier CertiFri.Fri.placeRow +D 78fe1ddd88fc4ec90540116659973ddc0029a7d9d63bfe3ec5a038b4f4dfc6eb CertiFriP3.Wire CertiFri.P3.Wire.maxNodeDegree +D 7927b7988f0faf6444163e38353e09093844b281b137bcf4b76d6f2fdefe75a8 CertiFriProofs.Exec.Stark.PrunedTensor CertiFri.Exec.Stark.mapM_oc._f +D 7936d35a840e8b35259f8e5cedeb97f02c41991b11ae826bba4d167d44870bb2 Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.instAddCommMonoid +D 793a92132b77c6332d12dabb792b43a58fbdd6f4ed8005726f28be8350ad5d5a Init.Data.UInt.Basic UInt32.shiftLeft +D 793b498c08d01dce519fe5371bc192d00cd232534ff09a686e80275951bf89d2 Init.SizeOf Array._sizeOf_1 +D 794ee2ade2286cd28e6461f7c55fd8feb4be4d528cca1fa3ba90475348243dc0 Init.Prelude ByteArray.size.match_1 +D 79592a71f481418fba9331b603dc1ca9a9644fb62248492f7759b90b84343c03 Mathlib.Data.Nat.Cast.Defs AddMonoidWithOne.toOne +D 796343fefcf8f838a409d11231d7835faeea3e08e09ce6644c3f463c9e6e7eb9 Mathlib.Algebra.Ring.Defs Ring.toNeg +D 79780434d1870e64c8b5a675630110e54e41fce80842364316a6fbfb9bc9c23f CertiFriProofs.Theory.Oracle.MerkleVerify CertiFri.Oracle.verifyQueryM._sparseCasesOn_1 +D 7a349d33f474bf1eef1b92b80793fc7407f3eabac70c6fdb58183adb1eae8e03 Mathlib.Data.Quot Quotient.mk'' +D 7a88905f7f2c57712ee429ee084ae392752568aeeb31c1b3971b3a7633281e37 Init.Data.ByteArray.Basic ByteArray.toList +D 7aa2c458c22b8f7b0949951782b3dc72501afda59bd26879742b2c19920684ba CertiFriP3.Wire CertiFri.P3.Wire.keyParams +D 7af59254d0a7f8bc45dd802849aaf1fd73ba6f29a6c109e373c4d4fd90d9dfbe Init.Prelude List.toByteArray.loop._f +D 7b27f457dccd6504d500868fc101847f89b2da7db6cf4df1550167e0c57c61a6 Init.Data.List.Attach List.pmap.match_1 +D 7b291996bb0964871ed00a1650f3a1fcade1790b698e7f890bb0836d061024c0 CertiFriProofs.Theory.Compiled.Tensor CertiFri.Compiled.Params.FinalCheckTensor +D 7b3a9fc27030601bbac31d76967cb2f54e91032eefc2eec653f16dde8c3c6917 CertiFriP3.Pruned CertiFri.P3.restorePaths._sparseCasesOn_2 +D 7b3df5456634aef0adaf80e4a3ae5de34b91f7aeaab9e62163d3815bbb54f09a CertiFriProofs.Theory.Stark.Check CertiFri.Stark.Model.ExtData.table +D 7b4b2446133dfaeafa827cb83003ca833c53d7b515467a659f7061fb8c60d237 CertiFriProofs.Exec.Stark.SpongeGoodLogTensor CertiFri.Exec.Stark.splitRawByDigest.match_1 +D 7b91da92703958d238f2eef30b0322c5c285cc60008672fffbb474ceff63378f Init.Prelude List.below +D 7bb5da03d20ce5397d1ced8fbeaec0f24b6173df06d378c8583189461ff0af60 CertiFriP3.GoldilocksExt3 CertiFri.P3.GoldilocksExt3.mul +D 7bc7f63ae60a3417ad170294f35cd0ebc75d27760760383da1ad7e8bf0648491 CertiFriProofs.Exec.Stark.ChainTensor CertiFri.Exec.Stark.tLastField +D 7bcac28d3f295f3d58e6be64ae4a3c4c3834f79a8a7efe836d06e2754b255b4d Mathlib.Data.Finset.Fold Finset.fold +D 7be1d536513213e52b6be6d593865174721621e3611f9ec7615ce9b8b7396df4 CertiFri.Stark.Verifier CertiFri.Stark.tensorCapOk +D 7bf5490100963717970f601d360d397d32a0829b0567ac00bd8e59b75a786976 CertiFriProofs.Theory.Compiled.Read CertiFri.Compiled.encRow +D 7bf9fe38e52db471d15ae37e2db34b833cb506edddc318a55efaf83ec5e84ef1 CertiFriProofs.Qrom.StdEquiv CertiFri.Qrom.runWithOracle +D 7c44af822a13cba528b4147d442fa572c19f26bc5c6de4ddb2d1556e028ad45c Init.Prelude List.append._f +D 7c587102fc9e6940c850916fe38aa4cbfa9b033bb7aed350e8eb49703999f70f CertiFriProofs.Theory.Stark.BalanceWeight CertiFri.Stark.Model.sentMsgs +D 7c7c4b86b456c2f6ac833cc0fff0775c5b8a7a57b13fbe16cb6a20ab0974c2e1 CertiFriProofs.Exec.Stark.Model CertiFri.Exec.Stark.StarkModel.shift +D 7cb86cd546e8f28ec8540763382968e2682043952790dea5b22cb3e4b2571bb9 Mathlib.Algebra.Group.Defs AddGroup.toSubNegMonoid +D 7cbb624b54d8c1cbdca171dda721f35b887e3f6e75cfff30b42f354947c85e20 CertiFriProofs.Theory.Compiled.Read CertiFri.Compiled.Params.finalDegree +D 7cd68c587b48c03323c09832b8381b4447b5d64d70a35d5b4d73fec3bb1dd499 CertiFriProofs.Theory.Oracle.MerkleVerify CertiFri.Oracle.MerkleAnswer +D 7cdb66676b4d5d08f0cc4f908964037dd0e0026ff146b9306bb35899027f10a5 Mathlib.Algebra.Group.Action.Defs MulAction.toSemigroupAction +D 7cef4424d6a241c2982ada3822b3a6e36ba960b5549c40dd421f7204ce9ef0bc CertiFriProofs.Exec.Stark.PrunedTensor CertiFri.Exec.Stark.ascendM.match_3 +D 7cf7d7a16b1ca44aff9d289ecc8ae4b0775ee28f7ea0baa09531f164b41a33aa CertiFriProofs.Theory.Compiled.Verifier CertiFri.Compiled.Proof.commitPaths +D 7d020001eacf5e46fcea77d8af6ba80108fb729b8d2adf17971aa916ef77b9ec Init.Core Setoid.r +D 7d2a1aeca4c6ffa150093c59f662891bcd6b12e004d0ffec17080c96cb59310e CertiFriProofs.Theory.Oracle.Prob CertiFri.Oracle.OracleComp.expect +D 7d31a290e5fe11cb66bd483928112c5cad4384f0848b8cb4c739a6b72b4fb2e2 Mathlib.Basic.Real.Basic Real.instOne +D 7d7fa30b6df7ecc5892151898353dd3f0c717a707bcc60aca4ddb8fab80c9e32 Init.Data.Rat.Basic Rat.instMul +D 7d86677ef6d1d1abecb72731c2e3c8f02757226bec1cd8324ba056e0f9a04940 CertiFriProofs.Exec.Stark.Columns CertiFri.Exec.Stark.StarkModel.cosetPoint +D 7db1415431c9064897044662dd589afef059e2fd99f82859722b549fea83fc78 Init.Data.List.Basic List.elem +D 7de12b338b579489595da9bce230b8b3f9a7f26dc6acf7071f3f8a5c771a3d63 CertiFriProofs.Theory.Oracle.SpongeCommitted CertiFri.Oracle.spongeLogHasher.match_1 +D 7e33e5c96be5a4a05dad4f788d8c65bca35d5b7c61c274e3b0607597e57742c7 Init.Data.Nat.Lemmas Nat.decidableBallLT.match_1 +D 7e449cc17c7e07521bb75820716f942e8b0551351b2965e9c92c31d12b8d80d6 Mathlib.Algebra.Order.CauSeq.Completion CauSeq.Completion.mk +D 7e4f24f8060b56cfb3d471bf3e20b38a45f8d9eafb171fc3efac9ee507539f48 Mathlib.Logic.Function.Basic Function.update +D 7e4f995525465b0d2c67b4015ee3e492cbc2a515e269f4a097ebf6eaf22e7acc CertiFri.Params CertiFri.FriParams.logFinalPolyLen +D 7e6bdf5800dab206848e8b5bac8733bdd51107afe6b374bdd2e0084647b674d6 CertiFriProofs.Theory.Stark.Air CertiFri.Stark.Model.Columns.main +D 7e737625bdfb61e672d53f2c386d1c403a376155669581bc247c4d22f6ad86df CertiFriProofs.Theory.Oracle.MerkleFrozen CertiFri.Oracle.SpongeAnswer.match_1 +D 7e7f38b33693cf43651293f5eaadc7860fb9061cce99122a9825b0741e247f89 Init.Prelude instHAppendOfAppend +D 7e868664710d7db13b9854bd99633f88ccd1d2173c917fe2d054d430da29ffa4 Mathlib.Algebra.Group.Monoid AddMonoid.toZero +D 7e977c403a16c907f31c57eca37df15bd3bdb80fe68c4dca81ccb56709be10d9 Mathlib.Algebra.Group.Defs AddGroup.toSubtractionMonoid +D 7ea6374d68f0dad3e9cc1aef076c826e56db09399bb4b79f9436890527b5599d CertiFriP3.Wire CertiFri.P3.Wire.Key.circuits +D 7eaf2173cb6df8875a2e7571c5a6c20508cde80c2b1f5ea573e06d66a185f416 Init.Classical Classical.choose +D 7ebed9183d350c4b382f679e4f72eda34f8015765b5d4bfea241999fe4d9be3e Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.mul' +D 7ebeda9c0d21abc2c6d7f552e7e695246f8045e5033e11bd6de8d152976e2369 CertiFriP3.GoldilocksExt3 CertiFri.P3.GoldilocksExt3.adjugate +D 7ebf7693032f631431f63a456e84ad19541e53210d60bae2214262681ac7fa6b Init.WF WellFounded.fixF +D 7ef49462ea9dc057bee7af7d6f07262983cb7e78e9abc9d3c9086458242d23c9 Mathlib.Algebra.Ring.Rat Rat.commRing +D 7f46ed28f04e77ca238298a6b82252b7bdad8e55fdbdf1e41476565198a12f11 CertiFri.Stark.Logup CertiFri.Stark.fromExtBasis +D 7f4b220f5aa4a57b375dc41696ea36786ee7560b2912cf5ad7a76bbe0aba8be0 CertiFriProofs.Exec.Stark.SoundnessPinnedSpongeMulti CertiFri.Exec.Stark.restorePinnedPathsMultiHashM.match_1 +D 7f61dd0683bd7c0c3996fc856e4b6132b1a6e729e10fac10304fdbc0a35cad81 Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.instDecidableEq +D 7f6479ab704476b1b1c26e80ca250cc8796ade0fd764d7b518fc1e5c1888b28a Mathlib.Order.WithBot WithBot.semilatticeSup.match_1 +D 7f82320d9b5aafb982045b0a7038e7a8fd1b7fa7f8bf4fc7ac9819be93cddd09 CertiFriProofs.Exec.Setup CertiFri.Exec.modelProof.match_3 +D 7f921c762f1667066b1b8a76975d57841b85b72058b84add0c401f64ea67095b Init.Data.UInt.Basic UInt64.add +D 7fb6c6781106082456fd2fc4ce31338fa22de1a340dfc144882c90b20c729e8f Init.Data.List.Sort.Basic List.merge +D 7fcea0b3313b2f19db1c4d73d2745e4de4629dd517c928721c261171563181de CertiFriProofs.Exec.Stark.JohnsonLookups CertiFri.Exec.Stark.msgItems +D 7fe5008e822fff5f327d9b06477b54e64f7817204c02a0189904d23940061670 Init.Data.Repr Nat.repr +D 7fec9c2b5ec02c81bf5fd716097c5ac3661d87b7d5322d358d2a5fd4481503f5 Init.Data.Option.Basic Option.orElse +D 7ff6251ce722802c01d46bc0b15774c3202c2fb41ef67b255676a7e2c4f00294 CertiFriP3.Blake3 CertiFri.P3.Blake3.Block.m9 +D 800c9cadd7dbf227ed511c0a2ad6cc26f6ae2bed5c099fa86553cf376d34c7fe Mathlib.Data.Finsupp.Defs Finsupp.toFun +D 8026975c4cf667dd0fb96cfa45941fb7a8da0629d49b5e8e36748669cf31acac Mathlib.Algebra.Ring.Defs Ring.toAddCommGroup +D 8046751dcc663adf39a103ab5e4e90049c9a6b6a7ac61c663828d2e47023bb14 CertiFriProofs.Exec.Stark.PrunedTensor CertiFri.Exec.Stark.ascendM.match_1 +D 8056bb44164a09da4b4d70879205479060fae67577929f8929e2d23756ab3cb4 Mathlib.Order.Notation Bot.bot +D 807f1fe8c37d53dc8ba19af40a790d0c7059dc6b6e5636207bcfd15ad64ab8e1 Mathlib.Data.Multiset.Defs Multiset.Mem +D 80ba26b19ddcd32028144c021a8d03a48a62567819e491dbbbc8de3029474f37 CertiFriProofs.Theory.Stark.UniformTensor CertiFri.Stark.UTensorAns.fieldAt +D 80be37b66d6fdc5e2204bc0b982f16449818002a29cc057de1fe05927211dbe9 Init.Data.Nat.Lemmas Nat.decidableExistsLT.match_1 +D 80feee7cd63089ee8a77d5bd43d0855b738ecc3bd273221259e5bcd25ab8e521 Mathlib.Algebra.Order.CauSeq.Basic CauSeq.instAdd +D 80ffc6bf65fc70226857de57e9330cfdd82e6ce6c09f67bfba39a8b3b125e658 Init.Data.Function Function.Injective +D 81315557de2f953fabfd0927bf8f8957a9375f98927cc31495164da1ce49322c Init.Data.Int.Basic Int.lt +D 8156d4e172c1c3dfae1918185bb320beecce06e72799a41db5476f5fa65c75f1 CertiFriP3.Pruned CertiFri.P3.Pruned.ascend.match_1 +D 8166fd2cae359e37b0f88b8ecffdc4b353087eec87d8b314f59359d5bc2268b0 Init.Data.Nat.Bitwise.Basic Nat.land +D 8173178e06523fc97f5ee4569c3e3970219bc88a656237420cfdb0d5c88764b1 CertiFri.Verifier CertiFri.Fri.OpeningRef.batch +D 8177245f9ae271a27a121547271c033d81ee73f24a21416dccbc7fbcc3023a29 Init.Data.Rat.Basic Rat.mul +D 817e9bc4a045c161fc3034d7b882af9a31e1c84271d20cae80732c5599277d84 CertiFriProofs.Theory.Oracle.MerkleVerify CertiFri.Oracle.instDecidableEqHashQuery.decEq.match_1 +D 818d7eab8bff98941e6ebb6f58379c09aea111ef97c34f15c1b275c685ea375b CertiFri.Stark.Graph CertiFri.Stark.ColRef.index +D 81a38ec8a23ad6e88ead3a36f33dc8a5631ab94f2639eb51d846eb62899f4a2e Mathlib.Algebra.Notation.Pi.Defs Pi.instAdd +D 81f5ed10681418c5633290dacb702c309f14b7c40843a3e637e223022138d2f3 Mathlib.Algebra.Group.DivInvMonoid SubtractionMonoid.toInvolutiveNeg +D 820539f8da335500ce9be53c652461e057abd2b89e80788e51e35a81481a4022 CertiFri.Verifier CertiFri.Fri.cosetPoint +D 8227e58168fe2f547f3b08b197c1447fd6d6b79d807f2627e36179b1707546f7 CertiFriProofs.Theory.Compiled.Read CertiFri.Compiled.Committed +D 823ce613fe2fd1e722e8426bcca31c32cccf65514a84a14d4c850cd5ccd421be CertiFriP3.Wire CertiFri.P3.Wire.maxLookupGroup +D 824177c0e196f785e5719a88ce14324febbd5cbd11ebdc4606be3d8398e1e813 Mathlib.Data.Finset.Card Finset.card +D 8244e31a7d925ae6d2cc6c8147a0e67a455bf59977a555004e746925505d4bac Mathlib.Algebra.Ring.Defs NonUnitalCommRing.toNonUnitalRing +D 8264888aa3dfb7c974cf35cdee0f812ea09933821a556422edde2d39a60f3567 CertiFriProofs.Exec.Stark.SoundnessPinnedSpongeMulti CertiFri.Exec.Stark.restorePinnedPathsMultiHashM.match_3 +D 826ee4a75b83ba0b625ceea2ef77205d9ff32462fafdf1195427db8d2006f6b3 Mathlib.Algebra.Group.Action.Pi Pi.mulAction +D 82771d236bd24e76af319b24036708dea41a464c5c621d38404688ed362f2602 CertiFri.Proof CertiFri.BatchOpening.openingProof +D 827f37c630ff2394dfca0434b40975ffc1c7f2b782c16bee93538410d75cf084 CertiFri.Verifier CertiFri.Fri.OpeningRef.valueStart +D 82902e9895d476edbddd31f9ff65b8bf2f7876cd8a4436ee8764dc02061bdd25 CertiFriProofs.Theory.Oracle.FiatShamir CertiFri.Oracle.Transcript.msgs +D 82994eb894f8f8bcf4ab8c8b032fb0126fc37c30cc5af527494499b36f90d7da CertiFriProofs.Theory.Compiled.Read CertiFri.Compiled.Slot.matrix +D 829c18ec85e7992e737df82c88849ec12a0306cd473ded8f368fee64d0203740 CertiFri.Stark.Verifier CertiFri.Stark.observeNat +D 82d34b735da9823bf4e69c18a1f65f8851846750da899a6b7641c52dc66a3dd3 CertiFri.Stark.Statement CertiFri.Stark.Model.lookupChan +D 82e6a0ceb0bb3de601ebd5d0bf3ecceed581afcfd51471f0a5519f1b96215e7b CertiFriProofs.Theory.Compiled.Read CertiFri.Compiled.Params.queries +D 82eef66adb890efb9fb54d255a43d07b3481543b7778c980591f965fb4e307cf Init.Data.Array.Basic Array.any +D 8304ca828d45b8a51d2fad04df67689b390db15bac227bba3debe481053daaa8 CertiFriProofs.Exec.Stark.FixedKey CertiFri.Exec.Stark.HashIface.ofNode +D 8315e865107804216ea29d56767da8684a8dd2f1b4440baa576be77ec7d81416 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.adjugate +D 8321fbfcd090bf547231041c3acd8580062181acf78141e5a186b2f792f1ea75 Init.Data.Nat.Bitwise.Basic Nat.xor +D 8323d882196728d18c4b3101661a16bd0b3e7d94d282ea5b74b308a2db1227b5 CertiFriProofs.P3.ByteLinkPinned CertiFri.Stark.Profile.verifyBytesPinnedOf +D 8327642fa669f1638da4477764356babc4ffd98e3af7758c277749c97cef72f6 CertiFri.MultiArity CertiFri.Fri.commitChecksMulti +D 833352a576826425a48dc0ac5bc0550b9cdd8cd12c9f8bc278a0f135153a73bd CertiFriProofs.Exec.Stark.SpongeGoodLogTensor CertiFri.Exec.Stark.SpongeChain.state +D 833738f2f8063a132d21f67a629f3053bb1e58cf69e7df87e470e893861d3223 CertiFri.Verifier CertiFri.Fri.inputChecks._sparseCasesOn_1 +D 8338fb701bf43eadda31474ad6fd6a708c37a321cb41dc07973cf25174f04c73 CertiFriProofs.Theory.MultiArity.CompiledTensor CertiFri.Compiled.MultiParams.slot +D 8378e1a9915b90abc21980c58b8563b71db3d393d1fd8ea8eaa87d2fd5e9734a Init.Prelude List.concat +D 837c09183f1af7b78f04ffdc4b804e0cf311faa4415ab7173f973576f3992af3 Mathlib.Order.WithBot WithBot.instLE +D 83aeafb87f85a72775fbe9d79b1853d50abc2f633698c99904dc73df49b3f5ac CertiFriP3.Wire CertiFri.P3.Wire.encMany +D 83e909759d0c9696286d87e3d8dd58c445b8aa4537e5fb55b8978d4b1d0fb453 CertiFriProofs.Exec.Stark.FreeTensor CertiFri.Exec.Stark.UStateTensor.squeezed +D 83f392531dad50fe0ec63b0146038ad513f4c12a515e6e6ca6a1b03a754e84d3 Init.Prelude Nat.add._f +D 841fe2dbcc74313e4e2825283ca32bfcc5171388ec45339fee0745b6f6666198 Init.Prelude instDecidableLtBitVec +D 843889e1f9bc9540ea8bebe238c64e309c8c53447c6a15d440d8bc313c3898e0 Init.Data.Rat.Basic Rat.instPowInt +D 8457aa686970fc2958de652696dc1a56936f74247bb3e38b11d467821a73e7e1 Mathlib.Order.TypeTags WithBot.some +D 846820c03dba75746658f7371e1e0940f929b0259e612af45134588a6063a144 CertiFriP3.DomainSep CertiFri.P3.Blake3Domain.hash +D 8487c874112abe0374647560120a4508ecdd6a7f973a8988904d82ec2b03f802 Mathlib.Basic.Real.Basic _private.Mathlib.Basic.Real.Basic.0.Real.sup +D 848997d2a1ef0dab7993663eec957d0d7b5ece351fed8c821759145ea9fcac53 Init.Data.List.Basic List.eraseRepsBy.loop +D 84b25fac1a68ef95b94600c4659cc9e609dac3ab16fe47e0d45a09e52633625e Mathlib.Data.Multiset.AddSub Multiset.add +D 84b3633f5c23b7236095ac819489f8e778d60dc27eee48903054d78eabdc63f5 CertiFri.Params CertiFri.FriParams.casesOn +D 84bbf7fac7eebd037675ac936b81aa8b152448c2329c929626107f348fdaf3df CertiFriP3.Digest CertiFri.P3.LittleEndian.pushWord32 +D 84bf291dde67024e6d29546389131f18543bf3c2ef2b04037cb12840b6d62103 Init.Data.Nat.Coprime Nat.Coprime +D 84bf3d717ac817a527b24760932ac3a8572fa360b248cbb5afe86fc308506bb7 CertiFriP3.Blake3 CertiFri.P3.Blake3.Node.blockLen +D 84c5de3c9042e216fc1fb3fd62350ddb8c3f6b713e4f18a152cb0f9b92ecdc2b Init.Prelude instDecidableEqList +D 84e44a5fb21386bb3ad957ccbc1949a7accb780d8e72919c96e25eb220e2c9e3 Init.Prelude instDecidableEqBitVec +D 84e5d6bb98e60fcfcabf36faa3ba5dca1136bfdb1d8b15d554d6dfa843b485bd CertiFri.Pcs CertiFri.Fri.verifyClaimsFromTensor +D 84e904a94abd9cad89c8864a442cda8e4460082cd14db5f00b79125fc2857ccc CertiFriProofs.Exec.Stark.SoundnessPinnedFixed CertiFri.Exec.Stark.BatchStatementHolds +D 852af1b470397b151e2d7fd3e601702094e51004099ea83ab35523209f8de577 Mathlib.Data.Nat.Find _private.Mathlib.Data.Nat.Find.0.Nat.lbp +D 852ebb0929e2b997d5988434026976c12f088950a5378daa04702fd6fb5edbf0 Init.Data.Array.Basic Array.mapFinIdxM.map._f +D 853485d07a70b416f85bc71cf9518d5cecea5b6f36220b12cfded74ac2930bd2 Init.Prelude instInhabitedUInt8 +D 85420cca0ff9d4f0a6f45efe001bff3befb80bb6cbac5c936704129eaa54344f Mathlib.Data.Multiset.ZeroCons Multiset.instSingleton +D 855876ebe74f6dc5c097814dddfc93eac3fc6d85660aeb3edaa6b03618e55a6e CertiFriProofs.Exec.Stark.PrunedTensor CertiFri.Exec.Stark.ascendM._f +D 855ae159b0466684e22a920a983fc04538932e652e89406103db9013ebc5b0b8 Init.Data.Array.Basic Array.instMembership +D 855c8b2972705f0a8e1bfbe4457d15a02a8e783c1ee1b7a32bca26178c005098 Mathlib.Algebra.Order.Nonneg.Basic Nonneg +D 856b5d3b504c28a8d53a0c44bd523c7ba9902b1af43572a7bcdc5c4f6c4ace65 CertiFriP3.Blake3 CertiFri.P3.Blake3.rounds +D 8585be69bfdab9f09142ebcee5f4d74a3a1bd292b875e4bc7699036e0b2ddc56 CertiFriP3.Wire CertiFri.P3.Wire.prunedPaths +D 85a3b3eeda67b5ce8c67deff4274626256c7080b048bfa5c7ad13d87dcdcb724 CertiFriProofs.Exec.MultiArity.TensorExec CertiFri.Exec.tensorCoordMulti +D 85d2e7a7f914ae9b817f2fb663a7a4e645c36f2d825f05ea4b3627fbba69b736 CertiFriProofs.Theory.Compiled.Tensor CertiFri.Compiled.Params.instDecidableFinalCheckTensor +D 85f71d3a72e7c16eb548700317e13e5a0a5db1cb3cde4ae7959f33853ff2b742 CertiFriProofs.Theory.Compiled.Tensor CertiFri.Compiled.Params.commitRowTensor +D 861b88c687075e95fd89039a4b286dba091ad214f483e372c68eeab0d52968e6 Mathlib.Algebra.Group.DivInvMonoid InvOneClass.toInv +D 8627a466cf905a9aa356e1fb722f59f4096a98e57b0f7a3794120eaf6bfb2984 Mathlib.Algebra.Order.Group.Multiset Multiset.instAddCancelCommMonoid +D 865331afb19cf60071f45d1f0768b89f35b0dfd9b18f1c08349a09fd118d80cc Mathlib.Data.Rat.Init NNRat.num +D 86751d3dec6a19e53b308da7dec5f527bcd9c8c88a9b8f2a58a8b492372313cb CertiFriP3.Wire CertiFri.P3.Wire.Batch +D 867ebd085d8de75863292bf9ae5c570f6bd6f6a985547d129ffa59f1b87b3d4b Init.Data.List.Sort.Basic _private.Init.Data.List.Sort.Basic.0.List.mergeSort.match_1 +D 86a14249722bda0c9c24bc3212db84fe6a64918f3c6b0da062807e7f6ac3e594 CertiFriP3.Goldilocks CertiFri.P3.Goldilocks.inv +D 86b88aa0fbe19e2503ec6eb0d978baaf2514784bbc7ffb3a5924ced64c320c37 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.inv +D 86c55b0d1677db453b796b3c134084fb56210781a0951ef92b22ac2dd3d092ae CertiFriP3.Blake3 CertiFri.P3.Blake3.rootNodeWith +D 86d93e72bcd6d975f38db64c2296c614d2e75c9420939511ab8edb77bcd509cf Init.Prelude Nat.div.go.match_1 +D 86e818097d1edf765f15599d976a2cc633166cc500e51e8edbf27fc7e5a1854b CertiFri.Stark.Statement CertiFri.Stark.Model.boolZeroCols +D 86fe4b3792c0cd8e4fabf5cd2620c946aae9920bfc67bcc8ef44a036436dbd29 Init.Prelude List.toArray +D 8714d29901d4ee1b34cf5aade5efe243185602505c355526d9a6f04ca149436d CertiFriProofs.Theory.Oracle.Basic CertiFri.Oracle.OracleComp.Outcome.match_1 +D 8725e5b94d551faee56131991158f943d7eb95daceb81ce07080ad9da77be010 Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.nonUnitalNonAssocSemiring +D 8737d2ee81b1a1b80df889f0a4e6ca01694810bdea440a8000fc881fe35a6eeb Mathlib.Order.Lattice Lattice.inf +D 8738576aee9853f999f75ed15fafaafc7161bef79adbab5ca9fff596c8401205 Init.Prelude BitVec.toNat +D 874ff304d3b7ed11baeb216d186d7c57d291354737b2a136bd31aa3a4bf1d3f8 Mathlib.Data.Multiset.Bind Multiset.product +D 8767830d7e7523ce3b430d0b536840014ea0c9670b2f0c2759078094322f8f87 Mathlib.Algebra.Group.DivInvMonoid DivInvOneMonoid.toInvOneClass +D 87c5ce72b9da822a279ff59b5dd89c828360196f8329aa233af82d72273c5bb9 Init.Data.Array.Basic Array.anyM.loop +D 87d361e49260ef2fd61bb581b7455198e8e5e5cf15cc059814f962baf5f51c67 Init.Prelude Quot.liftOn +D 87e3917732bc3ba24b2b47043e3d5ac0ce68e774100930ec7aacd95ac7a0bf2a CertiFriP3.Wire CertiFri.P3.Wire.decodeMessages +D 88294480c853f301c4ff1dd092324d2bd3e67ead41123db532ba7526c62916c7 CertiFriProofs.Theory.Oracle.MerkleOpens CertiFri.Oracle.MerkleRO.Dig.casesOn +D 883f6e19f6bbf3bf45ad603f7a6d205e541dca70c13919376f599892c17dc7dc Init.Data.UInt.Basic UInt64.mod +D 883fb6bebb4bd76fd745247432b0acbf95dbdc9283cb55861d8a9cb5b3fee676 Init.Data.UInt.Basic instOrOpUInt64 +D 88459d611a6dcb315c9755942e2a4020b03e891ceba4575bf5ce672c62038a69 CertiFriProofs.Theory.MultiArity.CompiledTensor CertiFri.Compiled.MultiParams.commitRowTensor +D 88616cf9ff12476c6f1b42e70d65436c20a85c79a77cf0542cafc399a14c5c09 Mathlib.Order.PropInstances Prop.instDistribLattice +D 888053d4d9eddc84535e1c0c1fb7419c22578616d06c2ba3ae7c50d44adda646 Mathlib.Order.RelIso.Basic RelIso.toEquiv +D 88a9ede85a58472476ab661c70b3419e3682101122e2b51980ecf03183881548 CertiFriProofs.Exec.Stark.FixedKey CertiFri.Exec.Stark.fixedLog +D 88ceb83cef1633619919bb39fb4e85a9d37dd83583452f16e089e119c2afc199 CertiFriProofs.Theory.Compiled.Read CertiFri.Compiled.Params.slot +D 88e24e1012bef7487e51b21f1f1b69c6c749495ba4e9f172f04433222da5c7cc Mathlib.Order.Hom.Set StrictMono.orderIso +D 88ebdd827c4c2562cd130d0bef82c50552dbc6e9bfeab2d144ce6ec5a3c44139 CertiFriProofs.Theory.Oracle.MerkleVerify CertiFri.Oracle.MerkleRO.hashRowsM +D 88ece6f9c9d47b3e40f4ab9147af48407c302c274d7b71088b7030b30387e4d8 Init.Prelude Nat.ble._f +D 8920c2c67d35b03933723306325ac892897e583ef2a7171c69450aebb5e46e66 Init.Data.BitVec.Basic BitVec.or +D 893785b023071ed289dc4804ca0f92496628edabcb69a0c9c4b59ece5f536ecf Init.Data.List.Basic List.decidableBAll._f +D 893ed69ffcbd9afba65e0863debb94d283a46b36ed8ba0483aa2beaf0c50caf5 Mathlib.Data.Set.Defs Set.union +D 894cd62ce67a744212bad0f4da36a1463df77949c9ef29a7ab31d1beef83de6b CertiFriProofs.Exec.Stark.State CertiFri.Exec.Stark.rep +D 89507aee6c90cfeb83c3fe62aac738f80fd02baeb67e6b5255ee870f0e1e1cdf Mathlib.Algebra.Field.Defs DivisionRing.ratCast_def._autoParam +D 8963949f2324e5d52280aad3afa7ee208095c630739f90e3e21a12b6d60d39e7 CertiFriProofs.Exec.Stark.Shard CertiFri.Exec.Stark.cosetBound +D 899a24b6e8e6e026208109caab222ab9656b4ef25b83038d301178dc61a0debc CertiFriProofs.Theory.Stark.Graph CertiFri.Stark.Model.maxNodeDeg +D 89a924b2661b5cb529e8689a494c5be4b5e51416130ba8c2c750ab9dd38c534f Mathlib.Algebra.GroupWithZero.Action.Defs SMulWithZero.toSMulZeroClass +D 89bdc05cadf8ceaba0fd60cb0487481338fc905856e5912eea78c4e22d984953 Mathlib.Algebra.Polynomial.Basic Polynomial.pow +D 89d1bc4c5de83fa493e8ba7c94abf7ee71a876019fcb0e710444b815130aba80 CertiFriP3.VerifyBytes CertiFri.P3.batchClaims +D 8a086487575fc6b5771b615cb47813261d2e432bc4b34feaf08235583af91db6 Mathlib.Data.Int.GCD Nat.xgcdAux +D 8a0f7dd4832076c668fbf408893c6e6df61588f3460cc108d64cbccc8cff42e9 CertiFriProofs.Exec.SoundnessSponge CertiFri.Sponge.mapHashToSponge._f +D 8a1a97696275a1d38e97a9a5144ee77b31eee244f5301781f528b985ec002691 Mathlib.Order.Lattice Lattice.toSemilatticeSup +D 8a2d6da6333a32d0debb1cec1256853cd3c3c68cc972d9374b7e100a565a19f3 CertiFri.Merkle CertiFri.Merkle.widthsMatch._f +D 8a3a460a2f2075f5bff5daaf15a2e542e93c2facca6cde06a5f5f2ef3779946a CertiFriProofs.Theory.Oracle.SpongeCommitted CertiFri.Oracle.spongeHashLookup +D 8a415686b382c9e93a2df60d538dd694abf9b8bb1805110bf19ae70b09f1dc53 Init.Control.Id Id.run +D 8a4d8116cde0baa9f9f3cf675bc1813c8c96f2495736b86e8ef6cc3440031029 Mathlib.Data.ZMod.Defs Fin.instCommSemigroup +D 8a4fd00476ff123cda5ee210106f996d8d5e2ea39f6c0bce1f8797e51ebd8481 Init.Data.List.Basic List.isEmpty +D 8a5c8e5a5b521f9c44cb6a16748ffb22a1202f39d45aef00407fd323448b7073 CertiFri.Claims CertiFri.MatrixOpening.logDegree +D 8a80fde67bdbd3666cca9fc9c9a853f877bf3844744849fb81a0221b33dad342 Mathlib.Algebra.Ring.Defs NonUnitalNonAssocRing.toHasDistribNeg +D 8a8b7daebec7b93423883b96229fb9eddae826374b25779f1b738bb4571a8cec CertiFriProofs.Qrom.CompressedOracle CertiFri.Qrom.emptyDB +D 8a8e80dbde8c378b01b408abd2f1e9244dec395833f25eef60a7968da0f6915b CertiFriProofs.Exec.MultiArity.TensorExec CertiFri.Exec.viewMulti +D 8a9843259155d510c4ab4be9451bd0059d5b71980a4f8601e9a579525a8cf866 CertiFri.Stark.Verifier CertiFri.Stark.zetaOk +D 8aafe06cae36180286373aabe88906d170c6c263578d2924bffb615ee9fef272 CertiFri.Verifier CertiFri.Fri.QueryResult.rows +D 8ac0093390db352305e43a325ef27cd3b7d76570b842215b303b5e5748ffbdd8 Mathlib.Algebra.Group.DivInvMonoid zpowRec +D 8acbd2a47a4b1e4614b805951cd54faa9d4e28e40564d1b98192427ddae5cdd1 CertiFri.Stark.Graph CertiFri.Stark.instInhabitedLookup +D 8ae57065e922f8d135de7ab524a8856e974e991a59e68252445c58c0778abeb4 CertiFriProofs.Theory.Oracle.MerkleFrozen CertiFri.Oracle.SpongeMerkleAnswer +D 8b1df2f02a080c3ff8f192a96d81ac4803210cd181e6477898b458ff7e92fd2b Mathlib.Algebra.Group.Monoid AddMonoid.toAddSemigroup +D 8b228b1b7aab037cb1d1044f99f995bfa95d17c7361a4e4aea6efae049dc0f9c CertiFri.Stark.System CertiFri.Stark.System.fri +D 8b3785f4a6865388e2b0b52524edfe1da545d9b204519420b4d926406359f85c Mathlib.Basic.Real.Basic Real.casesOn +D 8b860f5c1e3aa276293c21cdf3eb15248bf0d51c3f3fef5cde15f011c98b41d4 CertiFri.Stark.Graph CertiFri.Stark.instDecidableEqColRef.decEq.match_1 +D 8ba175c9d04688c41235f5cd3d31b9ed8ed3f98247b15096a9a4a8974c8e794e Init.Data.Int.Basic Int.instLEInt +D 8bc4fde0f7e1783bbb01460214c7aac31c78b9bdb17ced492f74b6c89983baf3 Mathlib.Data.Set.Defs Set.instLE +D 8be9cb7d5a0203a97cc34fcc481838c0e8232a932526bf40cbcfa3c0b78ef454 CertiFriProofs.Exec.Stark.SpongeGoodLogTensor CertiFri.Exec.Stark.spongeRunSteps._f +D 8c0a776c9b96d6beb6c87279aa3e52f9b1f90b89da95f4c353ae77e8c7f2f3f8 CertiFriProofs.Exec.Stark.PrunedTensor CertiFri.Exec.Stark.restorePathsM +D 8c201140d55e7cc5e0c7b560557b4ea38e28edccace87ac998a3b04b3deb88c3 Mathlib.Basic.Real.Basic _private.Mathlib.Basic.Real.Basic.0.Real.add +D 8c64eb456029f55a89d8fd21e7b30766acc01218109243b39041c642ab6ebff8 Mathlib.Algebra.Group.Fin.Basic Fin.addCommGroup +D 8c676998829a61acc28cd50404acb03fba1ab8bb4f3f7be118b8b9fbc754e699 CertiFriProofs.Exec.Stark.SpongeGoodLogTensor CertiFri.Exec.Stark.deriveSpongeSteps._f +D 8c77034bf1409dc8539012dae4e7b02aacfa16ff34ee41683a41e124efc82062 Init.Data.UInt.BasicAux UInt8.toNat +D 8c7d3832d9880e9cae2952025380293f1617fc859567c7900009cd753ff0fc56 Mathlib.Algebra.BigOperators.Group.Finset.Defs Finset.prod +D 8c8c8b131c4549ccce2b20a0bcb73cead9ee77112ee9c6ef26a048dd123d735f Init.Prelude Pow.pow +D 8c8c92af337b81cefe4f222e4be4ab41e09fa09a2d2914e45c8c3fe755affdb5 Ix.Aiur.Parameters Aiur.FriParameters.queryProofOfWorkBits +D 8cb6ceeac4e9eecd0df6cf656e2544a90696dc1b3d9fe4863529b2988bc32e71 Mathlib.Algebra.Group.Finsupp Finsupp.instAddGroup +D 8cd89ab8fea0f8c8b52046434d098763baeb524c41d86c1abfa10ebf85f141a1 Init.Data.List.Basic List.getLast?.match_1 +D 8ce8c387d3f0afc0561d5efeab9445950ebaa5de3e47c72598f585045919eee0 Mathlib.Order.Basic Pi.preorder +D 8ceb5aef0cb0d0be5f5d8f4b4908284ce73d41ae4c2379583d14fa7fef600c09 CertiFri.Stark.Statement CertiFri.Stark.Model.argsArityOk.match_1 +D 8cef5d2aced2dc2adc9e21309a86b3204353fafbfeeaf83ffaf527753d8d77ce Init.Data.UInt.BasicAux UInt64.instOfNat +D 8d1ca9eb8d02ada023e9e36b5e2f5988d0e0833f139f6f8b96cce229baf43e07 CertiFri.Stark.Verifier CertiFri.Stark.Selectors.invVanishing +D 8d27d9972fd7aaf58a140983157547f48904e88ade7d3e680adef2b3d2a45955 Mathlib.Algebra.Ring.Defs NonUnitalRing.toNonUnitalNonAssocRing +D 8d55af46ad8feab57842fc990564a43724dc32ef56db284ef6c3cf12e05b3669 Init.Data.List.Sort.Basic List.mergeSort._unary +D 8d65f48c0a2f3ffac1bb8ee9886cfd3270015405a3557591f2cfa7df5a634067 CertiFri.Mmcs CertiFri.Mmcs.verifyMultiBatch +D 8d68eda68c4bc7cb5bd5c81aead621376dac33758cdb1791b75273f21643808a CertiFriP3.Wire CertiFri.P3.Wire.manyAux.match_1 +D 8d6aab4d162a43edb123a9b2c9f763e4f64f451fcfd20ff1511b3aeedc49ccb1 CertiFri.Stark.Statement CertiFri.Stark.Model.varColAt._sparseCasesOn_1 +D 8dab18b3ce481f77bb6612767e5129c36462f2e296a4364e36381a3166a1f861 Mathlib.Algebra.Field.Defs Field.nnqsmul +D 8dbf1a9ed876e621d12fbf4a628e93ea9b9455815f5c9ea7c845b4c7935574b8 Mathlib.Algebra.Group.Finsupp Finsupp.instSub +D 8dc6e8b1c0ce5d9e16782e450532b4c99808b868869e09f0b06e351babf2ccba Init.Data.Nat.Lemmas Nat.decidableExistsLT +D 8e5c7644f7ee36fce364d06da7036484dcf8c8a492944d6b6ad93515854db0db Init.Data.Nat.Lemmas Nat.decidableBallLT +D 8e6fb55058454d2d58556ecb66cea73e31be8b43441c00d8e7be5db8a4418d6d CertiFriProofs.Exec.Stark.Columns CertiFri.Exec.Stark.StarkModel.baseRows +D 8e6fdd47478f0b47adbd6e783548e40dfc65ca50d308d5efb4ef05cdc92e93fd CertiFriP3.Blake3 CertiFri.P3.Blake3.Block.m10 +D 8e766ffdbffabbc42a4c4e6340db9f67546f482e7dfe699031a9ca8a2e2997c9 Init.Data.Array.Basic Array.append +D 8eac824e402ab6a872b75b07d3eb61c72cd1721166b156b3238d412be7bd0c76 Mathlib.Data.Finset.Defs Finset.instSetLike +D 8ed42fa347a7d8b09969e481149a47bfd6bc864e313ec491469ba14c0c95a5db CertiFriProofs.Exec.Setup CertiFri.Exec.FieldModel.leafWidth +D 8effc03882557b8416a3a5046b4857604710d4349a6cca175733219aca8f2ed9 CertiFriProofs.Theory.Oracle.FiatShamir CertiFri.Oracle.Transcript.brecOn.go +D 8f1d836e48f14b936e40837e6ebf21341a858a682105a5c9c4eb5065e14bbb6f CertiFri.Schedule CertiFri.logArityForRound.match_1 +D 8f1dddda5d2b4663dce505a2375792ff2a2c904e1a948294d43683c6413a42c3 CertiFri.Field CertiFri.FieldOps.toSub +D 8f400978e122962a3aba77ae9a55e1ac3dc64209b84076c0e14bf9da474a2a9a CertiFri.Verifier CertiFri.Fri.sibling +D 8f4de2d70b322c9c5c76d247100ffc95d94c4a39a5ed045eecf99a466763ae32 Init.Data.Int.Basic Int.instMul +D 8f53a0d2de98b564347703123106c7c2846ab09e0ef4f9730d83f40988bdf074 CertiFri.Verifier CertiFri.Fri.QueryResult.ok +D 8f5a79c49e438c66890b88c8e0466b7eb538e8da50d1d577ca366445a1ffbf2d CertiFri.Challenger CertiFri.Challenger.sampleExt +D 8f6b5a29da6b29662cadf9dbd64fed9b02fad11c72dfe00a26b7dfeb3a33d31b Init.Data.Rat.Basic Rat.zpow.match_1 +D 8f8692c2fe28cba0dd41717752ba5738637764f5032b33e444bb4cce2de4428a CertiFriProofs.Theory.Compiled.Read CertiFri.Compiled.Params.numClaims +D 8facc0056f421dcf8c9024a5335140a5d00dfedd4c836a1a0e03f180f8cd53b4 Init.Prelude instDecidableEqList.match_1 +D 8fadc5ffcd059fb7787c35c4f77d72511fbba1fc71e44eea56a267a1e5709981 Mathlib.Algebra.Ring.Defs NonUnitalNonAssocRing.toMul +D 8fc20c646225fbe507da24cce914d3a60c6362a6dfae7a767cf1651c15a268a1 CertiFriP3.Wire CertiFri.P3.Wire.KeyCircuit.preprocessedWidth +D 8fcc74a0a6ba6341b953550c03eafd614a01ebb654a62d84324562c18f3de461 Init.Data.Int.DivMod.Basic Int.divExact +D 8fcf0924049d9bf0644da245a47eeba79d42e76db5f426b4f8405dc2bd405fa9 CertiFri.Params CertiFri.instDecidableEqFriParams.decEq.match_1 +D 8fe988c882427f8b5e2af29ca2a0860173a01933c7d65dd7209f856431f296dd CertiFriProofs.Exec.Stark.LookupsGeneral CertiFri.Exec.Stark.colsItems +D 9006d98e4e9911f62b5ee9e821ef9569534b3f4c6cbabf22645c660be1b8abd4 Init.Data.ByteArray.Basic ByteArray.get!.match_1 +D 9031cd95b72667964aff633cfb16ddb680fa3e69d1b65d0ea86a447ef5312145 Init.Prelude Nat.decLt +D 904cecd25dd521046b2cc0481077c1d173ede7b9269296a80b75943885674857 Mathlib.Data.Quot Quotient.map₂ +D 905ac50afad8501a5b9ab808b3ded255e9236e9ca8a437a4660689ffcf3fef69 Mathlib.Topology.Instances.NNReal.Lemmas NNReal.powOrderIso +D 9063ccd075822e774b397d71333f622765a71742f192a4cf603db2f559bd571d Init.Util mkPanicMessageWithDecl +D 9065bb4d23c46102ee9812ae037d966ecd2ee0bd0857a547f297042a44594ce5 CertiFriP3.Wire CertiFri.P3.Wire.KeyCircuit.preprocessedHeight +D 906b5572c2bfedebd5af4539fe4f580963ca10e8ae5fd343830ff081505be580 CertiFriProofs.Theory.Oracle.MerkleVerify CertiFri.Oracle.MerkleRO.injectM +D 908ea00844715ec6f5bdbe8c07569aae72b60411a63935c4a2e8383643a52716 CertiFriProofs.Theory.MultiArity.CompiledTensor CertiFri.Compiled.MultiParams.dims +D 90a4ae9583ee2ac9374a6eed6724f618a23f92f3704d008bf549434be0e52576 Ix.Aiur.Parameters Aiur.udMillibitsPerQuery +D 90b396aa6c39cb0723f0323324394aa2bb00e9ac4eec5ceb1bc496007e89289b CertiFriP3.Wire CertiFri.P3.Wire.encNode +D 90dec01e8d054f8a0d9bbab9e03ffda7ed6d259a6c86aeaa688e73d9e111b799 CertiFriP3.Pruned CertiFri.P3.Pruned.leaves +D 90eafb997a39129712df9195e604601a1ba4a9136f59359a25ea69c05132ac6e Mathlib.Algebra.GroupWithZero.Units.Basic CommGroupWithZero.toDivisionCommMonoid +D 90f0e608a8206d4b04cf8a819e8e1e4b4bf0b1f436415c2796fbfe4d62217bbb CertiFriP3.Challenger CertiFri.P3.ChallengerState.sampleByte.match_1 +D 90f26bb32f17efe0b9a54ea61a9fbe38ec0767783b6af1d6fb626fe7e53965df Init.Prelude instHOrOfOrOp +D 910387aa8fb645d5cb39b16ff83503b0b9859219d8cb4d2314828295245b80e4 CertiFriProofs.Theory.MultiArity.CompiledTensor CertiFri.Compiled.MultiProof.inputPaths +D 910cab67aae79fca73572289ec3eee1492d1626f7540b3c0d2fa21d972888aa2 Init.Prelude AndOp.and +D 91190c02982f5c4b65cad4a95b2e064f9ed99f992e6fb4267211a5bca8a366c1 Init.Prelude Inv.inv +D 91365a0b5a4cf8b855af88d863604ecba06ff0a5fcd956b6215cb052d78243da Init.Prelude UInt32.toNat +D 9139b3f774a49f220fd3bd2b19d0704f0d050c329c0803b957201d7007d4557f Init.Data.List.Control List.mapM.loop._f +D 913cbeffc233962f468e24eca981a366e9b5d854d6bd718511c3f5140aa8646d CertiFri.Claims CertiFri.CommitmentOpening.commitment +D 915f5edfaec2608ccba08f38a8983602d6635289ad797c83e093c9e7cc1b45be Mathlib.Logic.Function.Basic Function.surjInv +D 916225570a283d4d72f589d3d4d3e625548b7e216a7bf65599ab32bf5951ca03 CertiFriP3.VerifyBytes CertiFri.P3.carriesStatement +D 9171124d34e594e9b2b44c4abc7ea5c84ef4b71ce35f3acc145b07776a9846c6 Init.Data.Cast Nat.cast +D 91748c10166d8cb196f817be9e9142d0d045e8ed05d7d8801e49a69fb0842030 CertiFriP3.Challenger CertiFri.P3.ChallengerState.sampleBaseWith._f +D 91928227a8e850d589613776435914b360317b7b1746205d7ac81042875fd87e Mathlib.Algebra.Order.CauSeq.Basic IsCauSeq +D 91936544e25a15e846c66990a4a85ec60fca6bb7dc770210ab07f23c7b18dc9b CertiFriP3.Wire CertiFri.P3.Wire.encDigest +D 919aae55c3c42cf24bff1c3a29c6b248579a4a3b05b968a01bfa2853b8dca5f7 Mathlib.Algebra.Order.CauSeq.Completion CauSeq.Completion.instZeroCauchy +D 91b9fed5f01d118afad3f56db4025b58c97e285dfa1d735eeb9e7a36128c9519 Init.Data.List.Basic List.elem._f +D 91c54d4d0129dfdaa25432ec09d5d6c743c4fe3a1ac0f9ac60f7aa0cfee18ca2 Init.Data.Rat.Basic Rat.sub +D 91dabc91d82342c3a62eaab198b48f762533fafba83e671155d8e22d03fccf0f CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.instDecidableEqFp3Model.decEq.match_1 +D 91f6b59e41252b3ea88896e5af22279fd7e7d7b65415e56483af979a25edd899 Mathlib.Data.Int.Cast.Defs AddGroupWithOne.toAddMonoidWithOne +D 9251229727addc03aff5108e111a208a7173617dd1eac5b89365ecc80efdb642 Mathlib.Data.Multiset.ZeroCons Multiset.cons +D 9259fc0f627cef3d81c62f4a82519dd57fe260f60bbbe227a11f35a3eb175e62 CertiFriP3.VerifyBytes CertiFri.P3.v6Seed +D 92654b5361408d04b0c7ea4b287f6956e92a6725bc2420da6d1c1a2e31228f9f Init.Data.List.Basic List.filter +D 926fd75a4a16e2dd63313af048dedbfb23e1fd5fbe4aff24bbacc58886c9f2fc CertiFriProofs.Exec.Stark.Preamble CertiFri.Exec.Stark.Bounds.rows +D 927cd3d08377034edcccfdb5f7c6f8d9ce298c9a8d1d6d880468875a6f92abd7 CertiFri.Challenger CertiFri.Challenger.checkWitness +D 92a6475b259d146f935e0da1984ed096d198615618b64e9ee5ff9582997c145d CertiFriP3.Blake3 CertiFri.P3.Blake3.Block.m3 +D 92aca1745f53240eb8985ce2107307efa68136c0fb99f8d812251aa964f50752 Init.Data.List.Basic List.zipIdx._f +D 9304c4498915d962a70165c0079665b6d41d2085c63e3c15d38d34b26e8b49e0 CertiFri.Verifier CertiFri.Fri.commitPhase.match_1 +D 931e1587daf6011e765c551c06eff501ba43364ca90c9b7a1d5928144726d9af Init.Data.UInt.Basic instOrOpUInt32 +D 9320df3c71e43785eb9e92f58ab717933ed85351487497de8b67953c4bf0e4f3 Mathlib.Algebra.Field.Defs Field.toNNRatCast +D 93237c5beab6a2ffdcae3d1e003475b67b771e08e39078cba5c48d71940482a6 CertiFriP3.Wire CertiFri.P3.Wire.vkDigestPreimage +D 9330555094cb8adc3fb04c4ee7157454aabcf8221f7e27c3bae6f3f28a6d3fd7 Batteries.Classes.RatCast instRatCastRat +D 93345cf5b1eadac636a03310f57b4c522757dcb28e9397fa06eb363fec2e92a7 CertiFriP3.GoldilocksExt3 CertiFri.P3.GoldilocksExt3.embed +D 9338105bfb40e440e5b902134ccf51f3f5ac3f96de78f03cf92fe59e81657a26 Init.Data.Rat.Basic Rat.zpow +D 934c20eaee427e8ab168b81f93d35e86822a31efd60c57b93c18cde0f3dba0db Init.Prelude Nat.brecOn +D 93502452690e16b02f9b826dbe2741a639fb831a6c4dafc843b8caa69e0881b7 Init.Data.Nat.Power2.Basic _private.Init.Data.Nat.Power2.Basic.0.Nat.nextPowerOfTwo.go._unary +D 93576179b993bd44087fd52379f0dd8f8e92efe2893e6e02a3acab87df3e3835 Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.nonAssocSemiring +D 935de5138ed52d0afe33fbe001a315bf4c5d671261f403d69aae97c5c6e79bfd Mathlib.Data.Nat.Cast.Defs Nat.unaryCast +D 93772dafd390d83ddf692bae02b1e219c63c0ad7003a19b6dfca14d078f2f16c CertiFri.Stark.Pinned CertiFri.Stark.PinnedBatchProof.batch +D 938525a2d15af57a719314c33b99108d71c91e99cb2e7eda81ba5d31a79150f8 Mathlib.Algebra.Group.Monoid MulOne.toOne +D 938bed03664a71f32443502566b7956a59f5a045801edeae1785e34483312f71 CertiFriP3.Wire CertiFri.P3.Wire.many +D 93a1c87fdfa79fd7eca056a6b876fdf7ae725e77f6efaca21dbf433387f937d8 CertiFriP3.GoldilocksExt3 CertiFri.P3.GoldilocksExt3.zero +D 93a40f201cc22a04b1ff8e0280bac2a817624f7cb54b0fbff82cce89cc8e5bbc Init.Data.Nat.Lemmas Nat.decidableBallLT._f +D 93beb8ce69f3331924ccc9db79942c89a0da8300d5adc4a595742d9699af373d Init.Data.Int.Basic Int.noConfusionType +D 93c47902b05291714f2c951bad93d2043d648d01a7830ff938458c543d27025b CertiFriProofs.Theory.Oracle.MerkleVerify CertiFri.Oracle.MerkleRO.allM +D 93c5f5c18b5e8100100379a57bea247b89c776c8e22bf7b44de60d42ef871cd8 CertiFri.Stark.System CertiFri.Stark.BatchProof.preamble +D 93c7d4d759c18075b57545c8564a035fc803785d81bc6deba2d9eb512dc8eb04 Mathlib.Algebra.Ring.Defs instMulZeroOneClassOfSemiring +D 93dd03aababb5ff6e4bb4b0d1e955b9d2b7979f7ae66af554b8829f09e5a68ee Mathlib.Algebra.Group.Monoid AddCommMonoid.toAddMonoid +D 93f80215f1c5bb1f0430d41bd14304805a18c96ff4923ce740ded05266667390 CertiFri.Verifier CertiFri.Fri.OpeningRef.width +D 9408472e0ddad0fd90bf4fc48386684a4875dd13f978947a17282f5567ef4936 Init.Control.Basic Alternative.toApplicative +D 9416270376436bb2a072f45cc72931747e79b49678c5e1622ea75efdee14b28e Mathlib.Order.WithBot WithBot.instLT +D 941ad7cfdf08bb10a34e2f2f7b2a1e915ae0983c768003e5947b682d7f0c5058 Init.Data.Int.DivMod.Basic Int.ediv +D 9428abf2069a49d42d27f272b9fe065bf99517d3e4388ead7864deacf05653d9 Mathlib.Algebra.Polynomial.Basic Polynomial.commRing +D 942d52dd45b6e968fb31b308f2e5b63b01bcb07a8691aac058a157e67485dbd2 CertiFriP3.Goldilocks CertiFri.P3.Goldilocks.order +D 94367d6e8ace3b2f2d6c3287e4338ce943cee8aceecd95f076287228511495c8 CertiFriProofs.Theory.Oracle.Basic CertiFri.Oracle.OracleComp.bind +D 945d22edee3de92e34f91d08813bf6b1220d13042082b99bb3ae601bf4c22d1e Init.Core Inter.inter +D 945d310409cab6fab1c535fefbc10bd480e39d336aad965255fea2d801bc1d1a Init.Prelude UInt64.toBitVec +D 946abd4be700adde45de9b43231545802b80c8e995139b1d5f79a6a03bb32013 CertiFriProofs.Exec.TensorExec CertiFri.Exec.openingCoords.match_1 +D 94e65fb8463b0713b5f7b7d52501fe7ef75346a6e14c79f17db7349f5d7c167e CertiFriProofs.Exec.Stark.JohnsonBall CertiFri.Exec.Stark.CircCFail +D 94e7d87cf298dc68079da0b72f2152a5c568b59fcbc9be62a7b1cac0dddd9ac0 CertiFriP3.Blake3 CertiFri.P3.Blake3.permute +D 94ecb74a3e40e6d9af88dd49387a090670591c2848774c86e1633464f63e273d CertiFriP3.Wire CertiFri.P3.Wire.Key.buildSystem.match_1 +D 9525d655e89623f65603590d3d9d2b8fee8e16a4a778daa949aaf2bbff885747 CertiFriProofs.Exec.Stark.SpongeGoodLogTensor CertiFri.Exec.Stark.SpongeChain.init +D 9526bd1222fb073261b895f862c61e07a8419fb229570cb46dbffe78c87089ee Init.Prelude HShiftRight.hShiftRight +D 9528a63af2b2dc73df19a755b71b95bc6210966ad0feae10ee6851905564a48b Mathlib.Algebra.Order.CauSeq.Basic CauSeq.instLTAbs +D 95698470b0dbcf12529c27980ed9e59b0bb18a37fa27ce781863c08235847c77 Init.Prelude UInt32.toBitVec +D 959e699ba35cf9d1a70bc35cec21273db2d9e5bc39da3de962f0eef484b5f00f CertiFriP3.Wire CertiFri.P3.Wire.lookupRoots +D 95c2054a39ce12efa3c855cef31c3bb83e05928ee3577a85703cd67c19e81da0 Mathlib.Algebra.Order.CauSeq.Basic CauSeq.Pos +D 95e154dfdb6e6f71ba90048c8c85028c107b45a38fdf796a5d334f4d7d80fa33 CertiFriP3.Blake3 CertiFri.P3.Blake3.State.v13 +D 95f21b3786fa7ad0204981514b8720d5cf785af79ba9551bc2135590aaf86cb1 CertiFriP3.DomainSep CertiFri.P3.DomainSep.nodeInput +D 95f289f2154f033758d6285729cfb4e4e2a323a76369cadb8df5428bcb23ca6a CertiFriProofs.Exec.Stark.PrunedTensor CertiFri.Exec.Stark.ascendM.match_5 +D 9607c6a1b88ea96fc0159bb5b81a2c124bd3ee0e93845a73806644ae423a1040 Ix.Aiur.Parameters Aiur.minQueriesForLogBlowup +D 96098a117a65480abbb9c0ba2c9fd096206e56ce3a32cfae77e5d21be5ebaa5c CertiFriP3.Wire CertiFri.P3.Wire.encKeyCommit +D 960a78c9e79f44dec4f15448f051645834137e3c1de777924cfacdf43949afe4 Init.Data.Int.DivMod.Basic Int.instDiv +D 960ad892be3ecc103efe0cb96236aead769e8b3800b9f78950120d6d7a04c737 CertiFri.Challenger CertiFri.Challenger.sampleIndices._f +D 9618f332790b163063c97ed6256ebf3c02c263d5a53d8b1db5a692c1f0ce3782 CertiFri.Stark.Graph CertiFri.Stark.instInhabitedLookup.default +D 96253405a3303cb5d6dcd7409a18d2446a62d907c5697643df99474ee81ef09a Init.Core Quot.recOnSubsingleton +D 965c7fe8ccef94aa323f3c8396d5a8cd53115d3993738ff86624af5e0eb39346 CertiFriProofs.Theory.Compiled.Read CertiFri.Compiled.Params.leafEnc +D 9661574b5dd91caeba1d57055584f0690c1469efeb95592082874a04d90a497b CertiFri.Stark.Admissible CertiFri.Stark.Admissible.plainPrefixLen +D 966f950ad71fe615693cf5b52f4c8bf94e70d7986a3f839524974e06101c90ab CertiFri.Stark.System CertiFri.Stark.ShardHeader.active +D 9674db3d707bdadaf20b18f7cac0f5e4e7ecdbef86005046b62fb4de3c37ede9 Init.Data.List.Basic List.instAppend +D 9678ce9044963f2a96a0034b61ff555a5024d1d3239c13d527e306f22b923fdb CertiFri.Field CertiFri.FieldOps.toNeg +D 969af8d36e8948c5fe400d2978ebb411994eb84510e820092382324b39841110 Mathlib.Data.Set.Defs Set.inter +D 96a961ee73677f9787791a616978d7555ddf7ce729d6ef146ef9ca4433493bf8 CertiFri.Stark.Pinned CertiFri.Stark.pinnedWidth +D 96dba3fde1f2ab114c74e0e77f797eb09f79a17ab9ebdaaf95b545c438edda51 Mathlib.Algebra.Group.Fin.Basic Fin.addCommSemigroup +D 96ecc9460145ab89c7b45a13d407dfb004ebe364384b5c9ead352c4be9d63340 Init.Data.UInt.BasicAux UInt64.toUInt32 +D 974b7fb89d7dcf7c22fb3c98117ef131b158ff1de5ccd74f27f9263754ff7041 Mathlib.Algebra.Field.Defs DivisionRing.toDiv +D 977a3041a0dec05b27b5055b61fbec5f2dd48b94cc0cf71e498e2ae66512c486 CertiFriProofs.Theory.Oracle.MerkleFrozen CertiFri.Oracle.instDecidableEqSpongeQuery.decEq.match_1 +D 977b2886f82c1d7426b270a1f31e2576ab75013d18859c0c99bfdb830f8f9d4e CertiFri.Stark.System CertiFri.Stark.Proof.logDegrees +D 977d0087fd2c7f4a86756c78b16e8f8397dc4c7c27522c007823680ffda9e64e Mathlib.Basic.Real.Basic _private.Mathlib.Basic.Real.Basic.0.Real.inf +D 97ac881fa6dc210ddf4f281882e7288d2db3aa0e43e5de2afaf2473749c9f190 CertiFriP3.DomainSep CertiFri.P3.v6TranscriptBatchKey +D 97ccc5ae3f560f206e2bff01fca4405e18b8503d2a49f339b44d2b8f125d571f CertiFriProofs.Theory.Stark.BalanceReceiver CertiFri.Stark.Model.netBy +D 9802d4b747fb72aa1ffe1495551dd141e898ece52d7eb626bd6dbdbcfc3002a3 Mathlib.Algebra.Field.Defs Rat.castRec +D 98139d109a332acb92e9b8d63d58f1dd7cfab40c4bf27c5e623fc6f25473f6a7 Init.Data.Zero npowRec +D 98160b677c923afd18fd16df2cfd2bb733028020e1a46a5abd838acb0900764d Init.Data.Repr Nat.toDigitsCore._f +D 9837ba625db139d0b568b3b67317a62ee4fceaa45f647bd3630b95c70a971b06 CertiFri.Verifier CertiFri.Fri.claimRefs.match_3 +D 984163e776034898ee0116db5b97e18a917cc6e63ecaf61b19108f819ef620b6 CertiFri.Stark.Admissible CertiFri.Stark.Admissible.hasFixed +D 985192a2594b8e8a8f8f068f3066288343bd7439804cf412dc857e38f140b478 CertiFriP3.Goldilocks CertiFri.P3.Goldilocks.twoAdicGenerators +D 986b1e605b646cbfa444e80e42d4bdcd0d25b32021f3aff183461f513e570eee Init.WF sizeOfWFRel +D 9893873171297340171b71165ec748f83b1433c60791ef8528c4145b16b6801a CertiFri.Verifier CertiFri.Fri.openingRefs +D 98d4e9eb9ccc172c204dafd7c468bbdc844b96f4931929465bc6e0365253d144 CertiFriProofs.Exec.Stark.JohnsonBall CertiFri.Exec.Stark.tupleAt +D 98da0270d456d19c90579f97a21684c1f69c26450db10218aa62377bc21b72de CertiFri.Stark.Statement CertiFri.Stark.Model.chansOk.match_1 +D 98ecc2c152a7ca424a2507d622e1d7610f6a4466f2e77667436be3a808998757 Init.Data.Array.Basic Array.ofFn +D 990b10d639699d1eefae1336a02df1df2bb18e8f17759491fd297cb34e2cc370 CertiFriP3.Wire CertiFri.P3.Wire.encU64 +D 9934bcf060b8eaab74d48d0af379758ed3973579a7c7dc0ada1acabb5af129db Init.Data.Array.Basic Array.forIn'.loop.match_3 +D 994d8ccfd55d9a55da52588965edb4eec5f6e9f819ff0120dc84f42200d1747c Mathlib.Logic.Equiv.Defs Equiv.right_inv._autoParam +D 99653f57b6aa2df3a6184ad345e7755384a6a5ac3b809f1f8fbb5e00f224d252 Init.Data.Array.Set Array.set! +D 99839b2555c7873be8671c1981c5326ff96775d0a714aaa34e88258ad235efe0 CertiFriP3.Blake3 CertiFri.P3.Blake3.State.v2 +D 99bc8ffaec6bd35c99458d4949cdde1d61b2d8de8afb35c7da7fd4d1572a1d30 Init.Prelude Lean.Name.mkStr1 +D 99c1cac1afc7f24fb91436fd2e43acf4ccfacfc498399950f5ce505ccb1e3fb8 Ix.Aiur.Parameters Aiur.minJohnsonBits +D 9a131b4f5e88dd0830377b9dac746c5163adc288185e7f74870e815f52c13364 CertiFriP3.Goldilocks CertiFri.P3.Goldilocks.invLoop +D 9a1ba53da0efdca615b0131c6e8d90720e9ba6ea6c7e99e3a5404fc564dded1e CertiFri.Stark.Graph CertiFri.Stark.Node.casesOn +D 9a258a138680aee6e6021b1080c32cf1607a7e3a0fa11312e627fa15063dc98a Init.GetElem GetElem?.getElem? +D 9a4a1883535947347ff429094cd257f5dadc83c4b70883a88fcd4d401f116c40 Init.Prelude HOr.hOr +D 9a4c6c9f67e9349a9b11db2d8e7ac0376afe65507b3ebe5748cc16dffcbe7131 CertiFriProofs.Theory.MultiArity.CompiledTensor CertiFri.Compiled.MultiProof.commitPaths +D 9a7f1250108c5976943020ad12136f3ecc779fd8418475faa6e5bf9c2acab391 Init.Data.Rat.Basic Rat.instLT +D 9aa1edefef25179fccf3a264164da4749aa4f9f3a1b6d83f5d484d5e6a8741e7 CertiFri.Params CertiFri.FriParams.maxLogArity +D 9aa871ad7dd62ed11370ffb53bef63be8c47d2e69045464c1b95b3e6a91aed85 CertiFri.Stark.Pinned CertiFri.Stark.shardOkPinned +D 9aa8cc3b9f2efe13b756481cdceb5c04e137a40c3aafecd2d77b9ab0b7072c1c Mathlib.Basic.Real.Basic Real.instMonoid +D 9aa9d0c5a29dfa361aba112c61e2ed7cc6e848a6511189649a57b0072cf3d827 CertiFri.Stark.Logup CertiFri.Stark.lookupGroups +D 9ab44ae293e43a5ed081e41439d27ed31970f2ef288e328268af803165ab7ee8 CertiFriProofs.Theory.Stark.BalanceWeight CertiFri.Stark.Model.receivedMsgs +D 9ab570d96c57b68145682474e44baabd42e946d2cb76522829744b10ea95f120 Init.Prelude HMul.hMul +D 9abab168e07bc77249fa684c741f845c846baf567ec5391092b3d9d6eb6a273a CertiFri.Stark.Verifier CertiFri.Stark.circuitOk +D 9ae82af3d893d30f3277b653e6626a994c81bb1ccd55c19c2073d24aa5f90b96 Init.Prelude Nat.decLe +D 9aefb51764e743edfc13b344d2b9e576cdf644efd9d8071e7ea6519bf3d21e99 CertiFri.Merkle CertiFri.Merkle.hasHeight +D 9af8f2c46b50c2e9a022e25a5e4e5a748941712c487438f75115183d8c5c2552 Init.Data.Array.Basic Array.forIn'.loop._f +D 9b05302b3ed2de3dc2ba95868b55e08f12bf25a583e46d71a9e9e4758bce492c CertiFri.Proof CertiFri.FriProof.queryPowWitness +D 9b2af0b5d483e15788480f4c691b2f1222decfc25972950fc03967b9414b8beb Mathlib.Algebra.Polynomial.Basic Polynomial.instIntCast +D 9b4444e103ccfb77a63dfeabd1b51fce1fcaea2132fd1a4998428206e06b9fe1 Mathlib.Algebra.Ring.Defs NonAssocSemiring.toOne +D 9b48db73ee11c90631c7fd45bf91529b7459da358004c72bfe359a44fc0fd719 CertiFri.Stark.Admissible CertiFri.Stark.Admissible.fixedOk +D 9b4bc1d6c1c51f0823e2dd080c292307c4a0dd5aa28def30f9a962ff76419a41 CertiFri.Stark.Admissible CertiFri.Stark.Profile.bounds +D 9b50053f309abb1d2afe058e357ade9c91e78050c58551942703d5bca8eccab7 Init.Data.Fin.Basic Fin.ofNat +D 9b5c0edb0c8b7a7d2dc4aa0d7a743bc50db24e7581f98b33053611ddee7afcc1 CertiFri.TensorBatching CertiFri.Fri.tensorWeights +D 9b6b5a811b5c94b1366f68a7c62c29030f139e7cd0cda414e4c4cf9b3b43ec46 Init.Data.Int.Basic Int.sign +D 9b851cde994738252729c056430af66586a006008d52bbb2ee9c171ae12fcb48 CertiFriProofs.Theory.Oracle.MerkleVerify CertiFri.Oracle.MerkleRO.allM._f +D 9b90ff51dc35d389da39c24942981ab158037eca6071ee0ff4fae0d8477737fe CertiFriProofs.Exec.Stark.LookupsGeneral CertiFri.Exec.Stark.colsPlainRow +D 9b9f0c2408893ce2888400c62b6d51ac6c02fb40415b6b2317c8f307ec95d7c0 Init.Prelude instMinNat +D 9ba5839b0b68eb18b34a2da3ab69cac8669fe32fc18f4d73cc925ae0bd1fd3f2 Init.Prelude BitVec.ofNatLT +D 9ba644502cb460291499c7fd351555c6d821dcc4215dcdd10d678429b1a882ba CertiFriProofs.Exec.Stark.SoundnessPinnedSponge CertiFri.Exec.Stark.restorePinnedPathsHashM.match_5 +D 9bad524cca45c5af6ae01a03348fc634c790adce0138336d0f6c3bb300d87cff CertiFriProofs.Exec.Stark.PrunedTensor CertiFri.Exec.Stark.walkM._f +D 9bb7dc6b7def0efdc989aff98dd68f9e3ac4e3921706775b00b6293cde4ffa2f Init.Data.Nat.Bitwise.Basic Nat.instOrOp +D 9bc5e857378b4fd5cae378594da0cd7781c519d6adfffeb8b3111f7c8cb1c130 Mathlib.Algebra.Group.Monoid AddMonoid.nsmul_zero._autoParam +D 9bd06c6218b80c89a54cee5ea1c6a935eeaba4790cbcc9496bb54122ad1e6395 Mathlib.Data.Finset.Defs Finset.decidableDforallFinset +D 9bd19ee98324a2166c3fb90e654ae59aed37dd8d70082af35d3c9215a196b283 Mathlib.Basic.Complex.Basic Complex.instIntCast +D 9bffdca7fd136a77f671fb1f14486343cb3dcd3a5be5c02607249553ee2235b2 CertiFriProofs.Theory.Oracle.MerkleVerify CertiFri.Oracle.MerkleRO.climbM +D 9c0b3fb7944f34364bd1c8336f40eaf78d10c047f84b1910722ebae4aefcbe52 Mathlib.Algebra.Field.Defs Field.toCommRing +D 9c0f698faaeccd33899d668e5167e3c631410297080ec92dcfa4c44b441a665d Ix.Cert.Release05.SecurityAudit Ix.Cert.Release05.Rec2p22_1ShShape +D 9c12bce3e53058974e9e2f1796d35491f1033f11cf2d417a96a1caf0dd7a85fc Mathlib.Data.Set.Defs Set.Mem +D 9c13dab1466de8f86b349301dae546de1d980d50ee2b63bff552c936e0d3b645 CertiFriProofs.Exec.Stark.JohnsonBall CertiFri.Exec.Stark.colsOfTuple +D 9c50d2496c3b462b9ee75bfb48bbc73e9dcca2095b4e4bb146c163a13fa83cb9 Mathlib.Data.Multiset.Defs Multiset +D 9c76c33cf66bcffe2d0bb11f7595504d0be512cb2f224334630b1fde8988a3de Init.Prelude outParam +D 9caae813b900cdf3dd6714cfacc35474cfd8b317e25a8005ada00260504005c4 Mathlib.Algebra.Group.Monoid MulOneClass.toMul +D 9cc135d8639048f1627e24d78d57762592ef05bf9c22139f030638f3e08260ae CertiFriProofs.Exec.Stark.FixedKey CertiFri.Exec.Stark.HashIface.nodeQ +D 9d1f0c5a235b7ed7258f1cb5b1a6ae2687fc1ff30c286d1cca09357201391c3b Init.Data.Rat.Basic Rat.instSub +D 9d3f01eea424a468735a41375b9acc70b07f0792e3eeb67cbd398eac721080c1 CertiFriP3.Challenger CertiFri.P3.ChallengerState.sampleBaseWith +D 9d4a11a426144e76054e00988a4514a6fb46aa897a4b927f69bb75059b11a557 Init.WF WellFounded.fix +D 9d4acc0813a1440936f316c6d5b25584a4e321ef78789eed49bc4878c776013e CertiFriP3.Wire CertiFri.P3.Wire.KeyCircuit.lookupPrefixLen +D 9d579c37131d456ca0d6376cd8921978039ba55e78d6092c1a3941d066d6844a CertiFriProofs.Theory.Compiled.Read CertiFri.Compiled.Params.encRow +D 9d7b77ae372ca37eefb6cd81ed19abfc28b4dfffe58a193c4281bfe7b7df6a42 Init.Prelude instDecidableEqFin +D 9d96df2c43fe71b809cbe29d86388137c8675bc0fe884bd603bca1947b4992fb Mathlib.Data.Set.Operations Set.range +D 9da26029338d1be47607cdd036cd11ff3ae72aa4c126985a742e289065a0b28e CertiFri.Stark.Statement CertiFri.Stark.Model.squareCol.match_1 +D 9dbcb83109ad9d25c54e787c4df5305a871897c137821335eb69e7557db1f403 Init.Data.Nat.Bitwise.Basic Nat.shiftLeft +D 9dbe5835c460c461c30d48602284dbdc9cc6bee40a538eaee4bdc2f9524fb702 Init.Data.Rat.Basic Rat.reduced._autoParam +D 9dded3840969e1834a04de2b4d0cddaebeb69501b78d8074c450adf7aff8f812 Init.Data.Rat.Basic Rat.blt +D 9df3992ec3b2e72aebc658262275446d69de8ab2dfb1625d7cf68f5b3f5106c4 CertiFriProofs.Qrom.StdEquiv CertiFri.Qrom.mkCOAlg +D 9e2cff5b364a0e36fe3d770981d2af3fcc47e572987386acd4422131db6ea039 CertiFriProofs.Exec.Stark.SoundnessPinnedFixed CertiFri.Exec.Stark.nodeFromQueries._f +D 9e9f9e3cbb2a4864066d2f988c70b2cf40198e9ffbea1b4efadbec8fa8ab9f37 CertiFriProofs.Theory.Stark.Check CertiFri.Stark.Model.ExtData.publics +D 9eae736539f68a16814bd6b16e5ab97206d5a6fead38551046d5341b79bc6dd8 CertiFriProofs.Exec.Stark.Shard CertiFri.Exec.Stark.zetaBound +D 9ebc5a801be1d42f8ce584a5eebb460dbb23d31c9357bbcf485aa39c86683017 CertiFriProofs.Theory.MultiArity.CompiledTensor CertiFri.Compiled.MultiParams.foldChainMulti +D 9ec6320ea01792595f0dcde80e8ffb1458933f0d7a6b89079d573ca23a663b46 Mathlib.Algebra.BigOperators.Group.Multiset.Defs Multiset.prod +D 9ed594116e249e00b7862c074d890fbb1c2691048514d4e558e3896c597f115e Init.Data.Rat.Basic Rat.instIntCast +D 9f13ccfb19d67995a8c351175f93ffe225dca616b661b2903bf069224958a5f8 CertiFriProofs.Exec.Stark.SoundnessPinnedSponge CertiFri.Exec.Stark.pinnedSpongeDigCap +D 9f1e2f8a6c556779932e6d7df57a60e97a63c04b854c06edc5e636cb88eb5569 CertiFriProofs.Exec.Stark.FixedKey CertiFri.Exec.Stark.fixedMats +D 9f436a017a2d7b751309343cfed94fbb1392586b1e33d01dab49ced62b4b290d Init.Data.List.Basic List.findIdx.go.match_1 +D 9f66159fe72deeff91c15262b09bd262e5b9566bc60aa3716239fc3e220af2f0 Mathlib.Data.Fintype.Pi Fintype.piFinset +D 9f676d4ec9cbbb0573b7ce56ab5885fd1225d490af72fa1703215ef597ccc3cd CertiFri.Stark.Pinned CertiFri.Stark.pinsOk.match_1 +D 9f9b51b4623fea96903fc3b636f448def9da970d8ce4e4066cbf08197d0d6865 Init.Control.Id Id +D 9fa09b20d96e22935b64ed7aa13b71514a364bc46b11af8ac531608142bfa366 Mathlib.Algebra.Order.CauSeq.Basic CauSeq.instZero +D 9faef8c554cdf56a31102c2eb77e46af5cd2bc1a100a41d0cb4be8cfaffe1310 Mathlib.Data.ZMod.Defs ZMod.decidableEq +D 9fb0599471f8fb86b4d39c4038959966a616464d99c531efe998966af242666c Mathlib.Basic.Real.Basic Real.definition._@.Mathlib.Basic.Real.Basic.6358291._hygCtx._hyg.2 +D 9fc98d3ba91d1c278062061e2fbfe4eab99cc9c1e52e95e8c5bf6ec898ad949d CertiFriP3.Blake3 CertiFri.P3.Blake3.chainBlocksWith +D 9fd6f5c7c89aed47d6a035ce3e8a0da43f920f80d3d2121d469bd7caa8b7c314 CertiFriProofs.P3.GoldilocksExt3Model CertiFri.P3.Fp3Model.basis.match_1 +D a01aa62955ae977cb4fec4e2b42ed1968cdb1621a55c7878dbfa0c73e98e7603 CertiFri.Params CertiFri.FriParams.queryPowBits +D a05b0155492001fbb8326ad86ffa6825219ae0f71f0eba23f0bf13d8697caa9d CertiFriProofs.Exec.Stark.Preamble CertiFri.Exec.Stark.Bounds.lookupRows +D a0781fbed49ebe64aeee6bf701fae6fde2c58110edccd0a2e02c4c400232928d CertiFriP3.GoldilocksExt3 CertiFri.P3.GoldilocksExt3.pushBytes +D a08b584bc88d1084ad427439e808d1f7b22b373591797930fcd9d36cd5664d5c Init.Data.Array.DecidableEq Array.instDecidableEq.match_1 +D a0d491429ac4c016d8b734d199957f234ceb8ec4b16cdc318851e175777b9f8d CertiFri.Verifier CertiFri.Fri.queryRows +D a0d7d5175ce3073517227a27a82d7827a3ef0fd232f65bffaa657ef9a671acf2 CertiFriProofs.Theory.Compiled.Verifier CertiFri.Compiled.Params.inputChecks +D a0fcf0b57322f333cfe9262bcb6b6076cafaf40c76081dd97c4b05e4f82c5e43 Init.Data.BitVec.BasicAux BitVec.add +D a0fecd472f40714be702c0f18ad8a3056a9a7df2f6779da844bb053761a51121 CertiFriProofs.Exec.Stark.SoundnessPinnedSpongeMulti CertiFri.Exec.Stark.restorePinnedPathsMultiHashM.match_5 +D a10037edad64f93a5263223843064757f1fe371db5012d620b9dd3d2d04e00de Mathlib.Data.Nat.Find Nat.findX +D a101d860157212d0bafca39d2e448ae361470450315389b06d4ce6cc7468c65f Mathlib.Algebra.Group.Monoid NSMul.nsmul +D a103d340d16367be36f4494a499c89cd6328de47e04a5749fea03455a353a5f0 Init.Data.List.Basic List.reverse +D a117876b0f4ac55bb297d87694ae4bfcdfe1ad1755c6bf994b60497e8f0c67d5 CertiFri.MultiArity CertiFri.Fri.verifyWithTensorMulti +D a128ca12b4967b1bb737c8fe960b6d86dce46abe3eb810c6b985095ca58bac56 CertiFri.Field CertiFri.TwoAdicOps.twoAdicity +D a16894db0151f7fe3473e678fa8d0c563ff687a61ebb269a887b403e01b8563b CertiFri.TensorBatching CertiFri.Fri.TensorSchedule.colWeights +D a19f4779769ceadbd875da0d2e326e9899994366ff16688b11244f5edfaa8eaa Init.Prelude List.brecOn.go +D a1b02affa4023898dbb2662a6a1ffa9b84965c73f360cf007f50d1dc602c3125 Mathlib.Algebra.Group.DivInvMonoid ZSMul.ofSMul +D a202318a8a6323bedc2f30f5f5f0460ae9273d7c376c8d69d5d62f00087d3805 Init.SizeOf List._sizeOf_1 +D a215835f9b28fdc814ec28865106ce011e169289daa36044252fda80e187ca7a Mathlib.Logic.Function.Defs Function.Bijective +D a21af18d28d01b3c7b97a1f98835d708a7f2219153cab365a0e03873f624a0a0 CertiFriProofs.Qrom.CompressedOracle CertiFri.Qrom.IsUnitState +D a226ce7931a2bf407042ea499e5c8632696b63a9d84502127a14fc82a4e3a4a0 Init.Prelude Nat.ble.match_1 +D a22d1d94bbb721d6ca913d801ebe5f4d7947ddb16df24447efcb81eee52c9bfd CertiFriP3.GoldilocksExt3 CertiFri.P3.GoldilocksExt3.c0 +D a237df9a5c84c0a74abf97113cde57fb3f7191446149f8db949c4e565aa3bdf9 CertiFri.Verifier CertiFri.Fri.ClaimShape +D a2618e504944f233fd1c12f240932dbce2839b4a093df12d90e1c504998ee6dd Mathlib.Data.Finset.Range Finset.range +D a270ace75544e778382e63c28c012742f0bcda381a96c1707d8774bc8fcd5b7d Mathlib.Algebra.Polynomial.Basic Polynomial.C +D a2aa81fd4996523ace78822eb3fd0d57e8b5f503ea36340523e87b1679da8f2e Ix.Aiur.Parameters Aiur.johnsonSlackMillibitsPerQuery +D a2c0525109e62c4a1fb20b5defef61627508f7eee8416d87c9677b4f81722593 CertiFri.Stark.Graph CertiFri.Stark.Graph.constraintValues +D a2d0bee697004be2923d53b05639c6b2f1388eab08f243e37426f4cfb5a05f50 CertiFriProofs.Theory.Compiled.Verifier CertiFri.Compiled.Proof.siblings +D a2e5368bd0e33f023022df6df17e82b7ca9b7606693e16b5e58062e85af435c8 CertiFriProofs.Exec.Stark.BalanceReceiverBatch CertiFri.Exec.Stark.checkedRecv +D a2f9fcdc8e662788ab23f8013f3918fe936f65d4e8b07da28488f791c9fde0e0 CertiFriProofs.Exec.Stark.PinnedLink CertiFri.Exec.Stark.fixedShapesPinned +D a3040fa888cf72ecee9f7a569ecb50cb264d2eeae590231adb766aab79de4dee CertiFri.Stark.Statement CertiFri.Stark.Model.keyChans.match_1 +D a30460ea0e5be3419e01006d8df466f5345b15f684d04361413d46a9d05119fb Mathlib.Algebra.Group.Int.Defs Int.instCommMonoid +D a30f28ddaa39166b95c329ae3a174e5e44f83819f5a98a787b9d47071e5dcd61 Init.Data.Rat.Basic Rat.instNatCast +D a3261d781a5dd437b190d696ecec48aafa23ee5d3733dda966d30882986f5452 Init.Data.ByteArray.Basic ByteArray.get.match_1 +D a3302cdc14c85f513d2b76a9dbc89eadd59d1723363e736d2a1341bdbad32751 Init.Data.Int.Basic Int.decLe +D a347fba15555d46571af39c0a5e425bee4b74009644b077023d9765c69828fe7 CertiFriProofs.Qrom.CompressedOracle CertiFri.Qrom.stdOracleFiber +D a34a1fa47ddcd2704710d0ea26be552b22c9306de513fb423d0869b0a21f44d1 Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.smulZeroClass +D a35445d69fbe2e0e0976f927ef1525127007dc75f489ec903ad30357e6a479c0 CertiFri.Pcs CertiFri.Fri.claimedWidth.match_1 +D a373b78875e9dfe9e1a600cac5c04b89fb8b806462a78d11a6987c90c0b09b21 CertiFri.Stark.Statement CertiFri.Stark.Model.lookupArityOk.match_3 +D a3801820e9558130f51a1167db59245dbb4c4770a7cb482402e93a9c702f484e Init.Prelude instHShiftLeftOfShiftLeft +D a380981cabb0fbf39306eab40423a362476c0dcf4ad37777a69c8a2e8adb72f4 Init.Prelude Nat.ble +D a3a0a34fe75391d453c23dd83fef791e99ef1119565be026312d1fa6f41c254e Mathlib.Algebra.Group.Semigroup CommSemigroup.toSemigroup +D a3abd380ba087e4aabc6c2b1978ad6711b5b9c1084d8c02562c824e25da0f665 Mathlib.Algebra.Polynomial.Basic _private.Mathlib.Algebra.Polynomial.Basic.0.Polynomial.instAdd.match_1 +D a3e9fc1e6aaa843da270162051a020f17fd99e69597d482275f9442b75d79b65 Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.instAddMonoid +D a3eb6b1659efdd4bcb85b600420806fc7cb4b45520ff85d194a5a8f4bc2f2e1f CertiFri.Stark.Admissible CertiFri.Stark.Admissible.securityOk +D a3ece8ac67497bcda44b8303f9a7e2d21ea108d84f221bfbf0e53a31c001e783 Init.Prelude List.map._f +D a3f3de4cf12fa96e4f38f5b281e03e4ba60d4e93ff48dc992db2342dd021724d CertiFri.Stark.Graph CertiFri.Stark.instDecidableEqColRef.decEq +D a44dfa6a32cb24f1d3c0896c9b43dd11e91d99964b47fe977477468c221b4917 Init.Prelude GE.ge +D a45f9b17ec2a43540231ba1d82410dbfdc9b255a84e9a8b6eacc2c820e70f7a7 Init.Prelude instHMod +D a47ff60bd53653e01a8709366aa6822b638ad75495f3d97fb7936b37c175faaf Init.Prelude List.ctorIdx +D a4b0589554fda2670ed8ab92929ee60654058b0fd5623927a181d81265ed1b4b Mathlib.Data.Int.Cast.Defs AddCommGroupWithOne.toNatCast +D a4d123374a1a89d7cfd890d43d5f75cf62cac86f165a846b589109cf1d276a24 CertiFri.MultiArity CertiFri.Fri.insertDesc +D a4d443fd665d35e1d883b46595924bb911117a37eb30c50684511b87f0566bcf CertiFriProofs.Theory.Oracle.Basic CertiFri.Oracle.OracleComp.brecOn.go +D a4d85f26181b9ea31c88e1969b33c96fc11f9b5480ae9660a8aa0803e68d0a22 CertiFri.Stark.Graph CertiFri.Stark.RowValues.preprocessedNext +D a4e96dc48cc215f1d909e09c066e6e1e0735cc598ee92337a96e7e223aad3b00 Mathlib.Algebra.Polynomial.Basic Polynomial.instAdd +D a4fa24974ff6818707c53e581607b3215c07bcffb517d2a8984d94fc7f131b9e Mathlib.Data.ZMod.Defs Fin.instNonUnitalCommRing +D a4fc4dff9ca705a8a58153f30c0530b8bedad27c01cb01c82943821d8cf7ea19 Mathlib.Algebra.Order.CauSeq.Completion CauSeq.Completion.ofRat +D a5113085047bbe11d0755783fc0ecc398097d46d4355d9b6a01c806ffa5b3525 Init.Data.Array.Basic Array.mapFinIdxM.map.match_1 +D a53d62b3f4ee8c7326cb4cf93231d2af00d52a52e155c8e95cd226872c0b140a CertiFri.TensorBatching CertiFri.Fri.sampleExtMany.match_1 +D a547bd0be0545408667c90f61f718b3f9e6048092e659518a5f6455db94bec22 CertiFriP3.Digest CertiFri.P3.instDecidableEqDigest.decEq +D a554fcf968ddabbadafe0e9fe8310fe6914ed78629e66a109219e27fd7832afc Init.Data.List.Sort.Basic List.mergeSort +D a5588af3203e8ac0161b72f79eddee5e83ec902565a6660c0711e8d3c02babc0 CertiFriP3.Wire CertiFri.P3.Wire.uLEAux.match_3 +D a56f6ff86aa921676af7167c9e0f5c794d9309900172b438b296020968bb4e13 Init.GetElem List.instGetElemNatLtLength +D a5879380cb3a14f276bc31136757fe7df14a81cb85ad7ed31f0bf7697f1277fc Init.Prelude instNatPowNat +D a5b36684437f9bc558a29a0ede31030af3fa180bfe18349945850cc86d9d791e Mathlib.Data.Finset.Defs Finset.decidableEq.match_1 +D a5b8c99eab60001bd77ed2ac8ece5924af758cfda02dd8afeef061766ea709e2 Mathlib.Algebra.Group.Monoid Monoid.npow_succ._autoParam +D a5c5d499f9d62a9f87b1d204236ca223f53bba78eec393e0732366fa8ebf9291 Mathlib.Algebra.Ring.Defs Semiring.toNatCast +D a5d36401454dd6c5c2753e3d155e628d9e82b7ac9cf44fc7dd87bd5a26fc96fd Mathlib.Basic.Complex.Basic Complex.instZero +D a5fc7e0cbfb39694e90f0a08741bb3ba5b9da59e6d96352e76b0f1e73e2a10c1 Init.Prelude List.foldl._f +D a66f0212cbb1a9bd28aa8a37be10c28540123fecd24b8bad378a139f3cde0d94 CertiFriProofs.Merkle.Tree CertiFri.Merkle.Matrix.logHeight +D a681fa0446e61e8cb34f2e6f929227aecd136e2a6438bdb53a3b9c6790a73424 CertiFri.Merkle CertiFri.Merkle.groupRows +D a685b5a208d1b9414d8e5464053851c54f8c8ac90e1acda5173b8f6ab2832d55 CertiFri.Field CertiFri.fieldPowTwo.match_1 +D a68a0ba785a5700cf2067d566f55ce47a2f803163688547ef706c0ff35fbd8c6 CertiFri.Pcs CertiFri.Fri.verifyClaimsFromTensorMultiArity +D a6a2baa88edb23a7f59d4a1387d97d2fd408c0a4889ddd3cc097ec91dd300fc3 Init.Prelude List.toByteArray.loop +D a6a7b5fff02d649e541913a6534564173cb165b7739764d900960aab9430ea38 CertiFriP3.Wire CertiFri.P3.Wire.Decoder.fail +D a6abb4cb664e451577f07b656aad0807433c733c17d3e9172904f8c30a261297 Init.Data.List.Basic List.reverseAux._f +D a6b6c8a3f4aa57638f760f5d945eb82644c781877f19882ae96d3d197432ebf0 CertiFriProofs.Theory.Compiled.Verifier CertiFri.Compiled.Proof.inputRows +D a731d7ec648bb503d6d4c14a102765a3b92cdd96df1f6b6c63fe32120a2b3869 CertiFri.Verifier CertiFri.Fri.verifyWithTensor +D a7334a6e4d6cb037f8a2f139d9fdb3f3d997b33a0f804b28cbd156cddf49d444 CertiFri.Stark.System CertiFri.Stark.Circuit.constraintCount +D a7362a7e6f1815cb8a775ffd2e1326fd120c12abcb22562f891da486bcf81a80 Init.Core Quotient.recOnSubsingleton₂ +D a73b0435147fe801bdfe41bc61342951e4969b2172b05f328ae5d91f4d6f792e CertiFriP3.Blake3 CertiFri.P3.Blake3.Block.m8 +D a75003eeb51e21d27d5671c080b04f91505b53d4732171b442588cc1b4c58092 CertiFri.Stark.Statement CertiFri.Stark.Model.pairCol.match_1 +D a75ea0e57eaaf06371980b1320310016f780e439c8fbbd2e9a86e6847fa73d33 Init.Prelude One.one +D a78df3a0b5eff43187f0bcfea909e01a30d479f5016b4d60b89affd3208abe6b Mathlib.Algebra.Group.DivInvMonoid DivInvMonoid.zpow_succ'._autoParam +D a7964e3daf8f862789344b09e04df126b8dcacfc7f4f71446eda60bd30c91679 CertiFriProofs.Theory.Compiled.Read CertiFri.Compiled.Msg.finalCoeffs +D a7ae1030c162190107446e22a4b8407f84bfeafd8735825656d869edd0a63bbd Mathlib.Data.Finset.Filter Finset.filter +D a7cf2fb142f21a234c428360d4b0daaf59e7e6cf952788db3039d2d71f7a14ef CertiFriP3.Blake3 CertiFri.P3.Blake3.Node.counter +D a7d8b5b9c28b4614d886046a9a9219a01b814e12c7f2006e6e40f5bff63142c8 CertiFriP3.Blake3 CertiFri.P3.Blake3.flagDeriveKeyContext +D a8281b7d44f572a86d4149ca610bda188d1b00ea3b656c0b7fbff56b28737eb3 CertiFriP3.Wire CertiFri.P3.Wire.KeyCircuit.contextsOk +D a82bc80380914380ea68635187fb9cf1716d2febd8541154ab89f5be1d1b8dc0 CertiFriP3.DomainSep CertiFri.P3.DomainSep.instDecidableEqKeyedInput +D a83c6e4059768f33871bc5bcde55db7021f2beadb50bea7dbdf32ea62b49e2e9 CertiFriProofs.Exec.Stark.FreeTensor CertiFri.Exec.Stark.UStateTensor.nbits +D a8493ae7b2864a4c48588ab61535ee9837f85254063c266b3af3e54c0cf31d6c Init.SizeOf Prod._sizeOf_1 +D a85d50ca1e0b30bea021a128ba09c9e1e711ea7cd8ad4e8eb31e164b7ae00efe Init.Data.BitVec.Basic BitVec.instHShiftRightNat +D a860aec7782a4d79c5c13e32e0684a30d2935fe1f0c3ba612289b08c03189010 Init.Prelude UInt8.decEq +D a8685754bd724f7cfab64890e07b9d32180446a1139e4f284a9c59f65b6fd3c6 CertiFriProofs.Exec.Stark.BalancePinnedBatch CertiFri.Exec.Stark.keyRecv +D a86fb6602d77245042191ddd7ae410ef1d4675f30c6e0c7f1e61afb0a8513877 Mathlib.Logic.Equiv.Defs Equiv.trans +D a8b4547402d8a2acaa26a449ac2b646071c254edd6b77cd82b197a2409e069a5 Mathlib.Order.Lattice Pi.instMaxForall_mathlib +D a8c7e40c76a40c36ddae15dba5ae453b55cbf11e983903b3cd376bfc89cc713d CertiFri.Stark.System CertiFri.Stark.ShardHeader.claims +D a8d0773fb74b6f769a0a5ec591d87ad18f0ef33cf7fc0b5314ddf0fc511ad6ff Init.Prelude instInhabitedUInt32 +D a90d47bcd196c6958540d658a5f0fb01bed910d42a223e85228aeb1eba9103e0 Mathlib.Algebra.Ring.Defs NonUnitalCommSemiring.toCommSemigroup +D a9144d058a59dc93ed47437fe17ff36d0b501ed7d042c77262b0f58b64cbe9f0 Init.Prelude List.hasDecEq.match_5 +D a93109c450b3603ecd4d0ee290d209217834d08a343f86cb962846af7ee42e28 Init.Prelude decEq +D a93b88f5a851806904d8cbe729861209396ecaf6e9dc0cb4bd02e1d53c922dc7 Mathlib.Algebra.Ring.Defs CommRing.toRing +D a93ca9dd1977938da199614f71b19e29739f4cdf204828170b4307e07a2de0d4 Init.Classical Classical.indefiniteDescription +D a95b1e08e69da1a350251c9501b194c2116fdf1828a65a7f9ade3983a700e8dc Mathlib.Algebra.Group.Semigroup AddCommMagma.toAdd +D a95ee2dfb73b7fa6652b78e0b2f3999ece741c349caedba421b32300fd553b96 Init.Prelude GT.gt +D a967c7878fe6613e1e24b02c8346fa239128e87f13f53a8d0b99a245303fc300 Init.Data.Fin.Fold Fin.foldr.loop +D a976865ba1b90c1caf5eed772281f2b24c892f3687fb9f43a76c1ac9794bbb85 CertiFri.Stark.Logup CertiFri.Stark.sumRange +D a98a9dea9617acb009c676db13e9605271d9f67ffc143b71a544c90c5fc0ff22 Init.Prelude List.set._f +D a99b32b4d0938b0dffcc019befc4ec818f42f59a1c84aadb2d3f7fd6dd4342b2 Init.Prelude instDecidableEqUInt32 +D a9b744e1ff124d511ff9af8b335d5f09a831ea689bfeff9f1f67c3e8bbe4dbf2 CertiFri.TensorBatching CertiFri.Fri.tensorOpeningTerm +D a9d3739ee550da44f395b9e7a598c529de84c0886bbd02dcf8f56ad0b71cfee7 CertiFriProofs.Theory.Oracle.MerkleVerify CertiFri.Oracle.MerkleRO.groupDigestM +D a9e531d887c0f89643aa0c606b662e4f3dd8c13e10fb05dccf79db6c373fdd81 CertiFriProofs.Qrom.CompressedOracle CertiFri.Qrom.QQueryAlgorithm.init +D a9efb7b60a0c037bb0f4a057e8d345412ecfc9aab8e5fecc925e92c7ff8327d2 Mathlib.Data.Rat.Init NNRat +D aa06dc771677ef5d87add2adb98388d68a5d788287cde4ce6d3b8fd240e7dd5a CertiFriProofs.Theory.Oracle.SpongeCommitted CertiFri.Oracle.spongeLogHasher._sparseCasesOn_1 +D aa103239a2a5149a2f9cf076420ed03b955eb13332871322f751bf7b427f8918 CertiFriP3.GoldilocksExt3 CertiFri.P3.GoldilocksExt3.inv +D aa2a9d1c3a9f4c1992572d8e8082b20e5fef7c28c48f30b2c738625b02622918 Mathlib.Algebra.Order.CauSeq.Completion CauSeq.Completion.instOneCauchy +D aa51e5d6d86b5010f94f699a64be197da25304d574daaf183cc8792412d42b53 Mathlib.Data.Finsupp.Defs Finsupp.instZero +D aa5dce66805f5a28d7894806de1ee1ecf17a766c3c82341b43e2f571353f637f Init.Data.List.Basic List.contains +D aa5f2dfb1de1793adb49c91a709b5c18c13926ce72e284e821cb18d5c5a6fe17 Init.Data.List.Basic List.any.match_1 +D aa6f630cc7d1770533a74688f45b53af95bde3b765adcdf39c1bc9caa54c2f80 CertiFriP3.Goldilocks CertiFri.P3.Goldilocks.invLoop._unary +D aa776bed3b09425a19f53f7cf5b6f83111054727d91a3de6dec8e3e7e43cf40f Init.Prelude Nat.decEq +D aa83a2dd14d4e0f60b24dd18afd7b7a7d7ce40a5dfc5013f0116c2873ad748aa Init.Prelude Nat.isValidChar +D aa869bd3af00d5213e36e5a5cdab4dce2bd34e03ca2b995d309304b01d3af1fc CertiFri.Merkle CertiFri.Merkle.maxLogHeight.match_1 +D aad3dd1572e042ea3243f883bd3637ca0c2a62d9e6db02bb14ed8800868a97e8 Mathlib.Algebra.Notation.Pi.Defs Pi.instZero +D aad9b65b8a3a132df0e2b369104758544025f572bbffd405e98081f28f9b5cfd Init.Data.Array.Basic Array.mapFinIdxM.map +D aae79183209b4fdf4cabc704b2a3bd9cbce447daae688645b825e07e003c456e Ix.Cert.Release05.SecurityAudit Ix.Cert.Release05.IxVm2p23_64ShShape +D ab0d192ce7360323f31c5c27a256d41c7ca6145bfc14259b0420f72755751641 Mathlib.Data.ZMod.Basic ZMod.inv +D ab3121c83e4e3ccb884af1bd61fa3beeeee422d58c06e0a033f147954b9f6c4d Mathlib.Algebra.Order.Nonneg.Basic Nonneg.pow +D ab730dde0f8be6dccefd9f23a8395017b4baebb4827edc9888abd6ba09806808 Mathlib.Data.Multiset.FinsetOps Multiset.ndunion +D ab8849424b2432bdc310470f79a33b3c9063e8da7da7137fbebe9ece5fd6678f Init.Prelude UInt8.toBitVec +D ab9454a581944c4a2a42f183173ff3cf46e64d9c60564fbe61a33bbb5826df85 CertiFriProofs.Exec.Stark.SpongeGoodLogTensor CertiFri.Exec.Stark.splitRawByDigest +D abaf9f48d9fdb53f99b3c0e9b916f5200ab16383b66476784e63f7d712d09d89 CertiFriProofs.Theory.Stark.Air CertiFri.Stark.Model.circuitItems +D abb2a370d51eda040e86b0c2d3a2bdcc37dff3d25f6cb3a52653f404b1950df8 CertiFri.Stark.Admissible CertiFri.Stark.BatchBounds.claims +D abc2b89ffa40014f69f0025e5ecfe023849a3b0d6ff0c10018a9f04ca9404ae5 CertiFri.Verifier CertiFri.Fri.inputChecks +D abd7871bb9654397afccfdac163e30d5798b11def3ea3e4ee7a266df209794cc CertiFri.Stark.Pinned CertiFri.Stark.openingClaimsPinned.match_1 +D abdc00175b662f6535de208e3faeecb694ce841b213cfe0d9a16840c037ff45c CertiFriP3.DomainSep CertiFri.P3.instReprBlake3Domain.repr.match_1 +D acbb448e59840fb6f2c08784caed4de68465b8733391f6095aea9bb1a89f150f CertiFriP3.Challenger CertiFri.P3.ChallengerState.rejectionFuel +D accc0e75afac0c00ece106dbe3ed71314dbc5f2458d41afb486272f8ed494722 Init.Data.Int.Basic Int.negOfNat +D acd31630cd08a93bca261941bc8cb60b2789636668412ef6112e0dd583224dc0 Init.Prelude UInt32.ofNatLT +D acde6436bc788a4f8c19ae32377c40dfafcdbde07ca067dc1a8355feabc85ffc CertiFriProofs.Exec.Stark.ShardGoodPinned CertiFri.Exec.Stark.nextMsgPinned +D ace99335f1bd92e03dbfd5f930c392ff50e373edb4781c3ee51aced65a504e36 Init.Data.UInt.Basic UInt64.shiftLeft +D ad0a37dc84869c0bcc4aa0e18622e5008b966c0014bd7ee60fd0e8b2c5203e00 CertiFriProofs.Theory.Stark.Balance CertiFri.Stark.Model.lookupSum +D ad24f4654e0e856d172a104ae8d3a9d1539e1593341415a18ee8e8ffe55dc5e2 Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.ring +D ad2d32c3d69f3bce9659b1b10a39fb56b3a1e8e6cdb58fa91df6a92a7d87ea29 CertiFri.Proof CertiFri.CommitPhaseStep.openingProof +D ad3565dcda8ef50416b86002447a1ab3abf59a4c884069846ae8255d74f880e7 CertiFri.Challenger CertiFri.Challenger.sampleIndices.match_1 +D ad3912a1f845e2a169ff009cd74cbf6db0f46fac3689dd16fcf4d65f7430d82a Init.Core Quotient.recOnSubsingleton +D ad3e67bc08a52650a8b4ed48f46d997cc886e21e3fa15eea7fc6d6b319910579 CertiFriProofs.Exec.Stark.SpongeGoodLogTensor CertiFri.Exec.Stark.instDecidableEqSpongeStarkMsg.decEq +D ad449ae8f7d76a6d1c86015dee92427082dfd560e693d6b7e8807374300765c9 CertiFri.Stark.Graph CertiFri.Stark.ColRef.casesOn +D ad65e96c4f32cee672bba8d7494b7bb443e18312b3c2d4777f37be732f1c06fe Init.Data.ByteArray.Basic ByteArray.get._auto_1 +D ad81ff64c518c6d0c9ae89fc65555fbeb25fbf55910deed12bd9edc6ce2d4783 CertiFriProofs.Theory.MultiArity.CompiledTensor CertiFri.Compiled.MultiParams.ω +D ada936b4d6d4c1c901d2e056df9cf5387ae7398ef0c7c5339d3cc4b3b45c06d7 CertiFriProofs.Theory.Oracle.MerkleVerify CertiFri.Oracle.hasherOf +D adf29d6883d219d281aab662b495354ce7a198784bf8df406dd6e6c7bf5eaa99 CertiFriP3.DomainSep CertiFri.P3.blake3Transcript +D adf63313ea9130ce438f13cf772e50c09b219862dec6025a956c535a29828917 CertiFriProofs.Exec.Stark.Shard CertiFri.Exec.Stark.accOut +D ae0ae22272677a6a639c44f9349e0f057c1bf4c6a7d026e458c61e25ab678fc5 CertiFriProofs.Exec.Stark.SoundnessPinnedSponge CertiFri.Exec.Stark.shardCompPinnedBinSponge.match_3 +D ae2ec8e5e262f048b73343037298804b3bb77f8af0d7ebc43fccf23e311b6b73 CertiFriProofs.Theory.Oracle.MerkleVerify CertiFri.Oracle.verifyOpeningsM +D ae5dc9e414f3a1b3b000d9015e404a47d59241f31db16944701bbb58596e3227 Mathlib.Algebra.Field.Defs NNRat.castRec +D ae7d24e75c6689dcdc273d9fb1496aff8e37a1dee6b4d320050e2cbd2d3fbabd Init.Data.Array.Basic _private.Init.Data.Array.Basic.0.Array.ofFn.go._f +D ae801759e39a5b4157b7b7f06b7eb7ab9146b3f3e18f15f69b6e568abca53295 Init.Data.Array.DecidableEq Array.instDecidableEq +D ae875c97e8012ca80fd6a12f36d4d6880d2bea470788ddb7867fcf03effa79c4 CertiFriProofs.Qrom.CompressedOracle CertiFri.Qrom.compressedOracleFiber +D aea67834c29ecd1ef9f93410b9c8183df8a0e05fdcccff3f92f5f6c42b95dc36 Init.Data.Range.Basic _private.Init.Data.Range.Basic.0.Std.Legacy.Range.forIn'.loop._unary +D aea9954e94ce74f19d017ef20806b58c353724c81ae6e8264ea5c85b830355e1 Init.Prelude DecidableRel +D aeb1cbf18eabebb82229a04729781d1415477b84acd17d3c25d91fe46ce1415a CertiFriProofs.Exec.Stark.FixedKey CertiFri.Exec.Stark.nodeFromComp +D aebf344e6979440dda02e336106b939f75aa7e9bdc2b467a6e0866091103ef50 CertiFriP3.Wire CertiFri.P3.Wire.KeyCircuit.contextsOk.match_4 +D aed548a69c055c807cffe098adb65f14cad736063482d24f99bf1929e5d71044 Init.Prelude UInt8.decEq.match_1 +D aedddba335d5341a55dc6b10f6d5e69055de1b930e0dc66594f3fc2cc0025a6a Mathlib.Data.Set.Defs Set.instMembership +D aedfc2a9cf5ad2ac9c6b83fbd138672449477f4bfb54b0242546eaa9eef6d442 Init.Prelude ByteArray.data +D aee6dc7b6cad3c712338d60abff96b62b8bd12440a8e53da93f84e2ebf757858 CertiFri.Stark.Graph CertiFri.Stark.RowValues.mainNext +D aefbb79b767dd7eaacfa3cc5bcc96cf8dafbb337bc739d8ad54ec46d6439e061 CertiFriProofs.Exec.Stark.SoundnessTensorSponge CertiFri.Exec.Stark.starkSpongeDigCap.match_1 +D af511ce11eaef4a431335e6fd24b2384941a74239f21098628b1ef4a74eaa2af CertiFri.Verifier CertiFri.Fri.ClaimRef.valueIdx +D af57ca8c0cf0cc14f148f34396f0429a9740023bef22b0c233a4a9b00ec2abbd Init.WF invImage +D af69f78b6dbaf1c4342e2aebe3b8d4568d5607c424c9de89765a9533854982e0 CertiFriP3.Pruned CertiFri.P3.Pruned.ascend.match_3 +D af70f9564be56a3792b81cd49f2e72591d8c6ce1a59b8481c23f68553340a40c CertiFri.Schedule CertiFri.foldScheduleFrom._f +D af97a860f73537a8b7df1864cc2973370b7edd8562d19bc41d421605f07ea0b2 CertiFriProofs.Exec.Stark.JohnsonLookups CertiFri.Exec.Stark.claimItems +D af97cd862b7173135966aadf1b3221360f0758aabd5f57aaca98de400620246f Init.Prelude UInt8.ofNat +D afcba87361a8dc4b2d5f14925ceadf061d7a20f8ccde390e1b06ea497f6d0d24 Init.Core HasEquiv.Equiv +D afcef664f76e455a8f878dab05cba5c206c6ff838c7c60c2ab9da50c27392f31 CertiFri.Stark.Graph CertiFri.Stark.Source.ctorIdx +D afd52fbb9a6b9192dfccd37af12f6f21644900c1cfb324dd3ad8573d68d27e23 Mathlib.Data.Int.Cast.Defs AddCommGroupWithOne.toAddCommGroup +D afd7ca3b74a3f284198229059bfdba02a00270c32a23e14e24cd3090500a21b2 Init.Core ForInStep.casesOn +D afd8cccd69cba4430700cf97d86a9415c1b4624bd5de4c29113f9e33ff6e5712 CertiFriP3.Pruned CertiFri.P3.Pruned.leaves.match_1 +D afdbc2dec6895bffc335fecb5e52f0af6dd4113ea936039b39a0a2fd47911ab5 CertiFriProofs.Exec.Setup CertiFri.Exec.messages +D b036ef0adb84e12ab43aeb44228e0f66c34a46780937706d8075ce21a39a090d Init.Prelude Max.max +D b03b66d90a1c59ac257e9b53ff7f90d38f44afdad7115c1f4bb43ac490f87bc5 CertiFri.MultiArity CertiFri.Fri.commitChecksMulti.match_1 +D b05a1fddc567dd81a8ba7f9ebdf58b52655dcaa059353359b6dfc3de33d4eea1 Init.Data.Rat.Basic Rat.instDecidableLe +D b0747cd6726f763c7b0d04929d9f105f5a4650029e94d3b547ab8b1d8970ef45 Init.Prelude Nat.instDiv +D b0769b300e68e2c7d08e5f1f0e3bbcc2cd3790a05298c23eeec87c39d14357b3 Mathlib.Basic.Real.Basic Real.instSemilatticeSup +D b087e52931ff312cc0abc5621fe0e24584f8d988301bd4c71d2c257ad37884ef Mathlib.Algebra.Module.Pi Pi.Function.module +D b0a08bed4497ca7d227aa4aa412106fbebd4ad150961ecff057144fd6b34c8ac Init.Data.Int.Basic Int.instAdd +D b0a66d6efbe21eca5cc868a78a68a7864458355ddd4f0328bafe8c8e16abee1c Init.Prelude Bool.noConfusion +D b0aa2dc0a25d294ec453fb76cad93986dcfaf51fccdbbb82cfd69a117f079a98 Init.Prelude List.cons.noConfusion +D b0d8fe013d26c9034bb26c508b2329a2f5af711970d13305d1c26fde06954f3d Init.Prelude instDecidableEqBool +D b0e29d3cdd430d20444a0f5a110844a645c46a897c706faeda3f438082e65c16 Init.Data.Range.Basic Std.Legacy.instMembershipNatRange +D b0f4c3ae69511f2d074a79f732b720ab5c997e95cdda4e3b7f7c252ea39b5933 Mathlib.Data.Multiset.Defs Multiset.Nodup +D b11c3ffeec9be3eeeaaf358aa6dd6fdec162a301c286f7ba1a2d6278e9c9455b Mathlib.Basic.Complex.Basic Complex.instSub +D b11d2afb80082378626a3a7376f1d62768ea1018cfdaad29edfa81de43737d46 Init.Prelude instDecidableLeBitVec +D b143808de74c86901640fd1b883d298c1de64eb40f4ea99ba0245f6e9464ce6f CertiFri.Stark.Admissible CertiFri.Stark.Admissible.heightOk +D b1602867d7a48c58e19433c765b6a0dfdf05d3dda6c420381b67d98e11b31009 CertiFriP3.Wire CertiFri.P3.Wire.Decoder.pure +D b16352318a5c0676974bc0162c2bf421ef977c959601c3b4e9b70298d165c20f Mathlib.Basic.Logic.Basic Classical.decEq +D b1647b4382beaa24ee0a6051010c75e0b9aa30869aa29aa2dae486f0e0c17dc9 CertiFri.Verifier CertiFri.Fri.firstMessage +D b1677b9c3ce20a4a7ac4297f4313bb5390f1be248440deb0584097e509dead5f CertiFri.Stark.Verifier CertiFri.Stark.lookupChallenges +D b1829af0db939edd28a6cb0c5b65bb311f388157fcda2e4bf8ea467d55475498 Mathlib.Data.Quot Quot.out +D b1864d07e7c88dee6763670fc82884b9484b047372fe667c8245cdcbb078f4f6 Mathlib.Logic.Equiv.Basic Equiv.subtypeEquivProp +D b1910470aad97660a9c3160f239b4a0aa120e26c924d55ac1c6038682ca65247 CertiFriProofs.Exec.MultiArity.TensorExec CertiFri.Exec.modelProofMulti.match_1 +D b1a08cb85d80f9f7bd4fe637d63db582fe078cea2344724aa5766e7243ad2b7c CertiFriProofs.Theory.MultiArity.Fold CertiFri.foldRowMultiM.match_1 +D b1a57837ad7277488eadbb450c8b4a99ac26d37a8c90eb01caa9afbc2e15c5bc Init.Prelude Nat.pow._f +D b1c3185e707019c6fdc1360a453d3fc36657ce05a769f7e4c50b1372d4d774c9 Mathlib.Order.Defs.Prop Prop.le +D b1e468091b1bf99be3a1a89455ce0fcd9d00bb545e9e3e6e2e1a2c10f7d7e51e Mathlib.Data.Finset.Insert Finset.instSingleton +D b1e503de0b07da0ceac0520baf088c38372dfd45d9100ddb4bcdbe33d9fdf6a8 Mathlib.Algebra.BigOperators.Group.Finset.Defs Finset.sum +D b22eaa02fcd518dcc2e213c3aecd5a38ef11de98e45bbdfe78bde6db758f5799 CertiFriP3.Digest CertiFri.P3.Digest.w6 +D b23971246c426a0b5ed1297f593f91a725522171a70e0a08c2c25ab06b618b86 Mathlib.Order.BoundedOrder.Basic OrderBot.toBot +D b23b8a643dcad23311bacb629568b1521ae98c2da8022c2e64a4e84a4580bc16 Mathlib.Algebra.Order.Monoid.Unbundled.WithTop WithBot.instNatCast +D b2439a9b64957bcf47dce74b3c59442cda05bcae9f139416e3007655bf603ec5 CertiFriProofs.Theory.Stark.Air CertiFri.Stark.Model.constraintVals +D b24aba9fca551fb2cb7bd2719cae41ed739e9ae4fbc966948d8cf7bdd0584611 CertiFriProofs.Exec.Stark.SoundnessPinnedBatch CertiFri.Exec.Stark.shardCompPinnedSponge +D b256491c9364bc4ffc1d8b05348adea917e532a0106719c2b98e76109fd0401b Mathlib.Order.Defs.LinearOrder LinearOrder.toMax +D b25dbd418fbf784bf2b405a2855fa00f4dac4a69ba0513085cc50a03b85d2a83 Ix.Aiur.Parameters Aiur.defaultFriParameters +D b26c9ee24eb967f38a6835f1d591cc46b699c3657a354e718979e05d52a23b26 Init.Prelude Nat.modCore +D b2746ab1d80123ac1e50f7c8604ed739217e2a11483c89a0cbddae965da4018a CertiFriP3.Wire CertiFri.P3.Wire.pinnedBatch +D b28e4c174b40698ead8138b2c5ba7295bccb500545a3ae7b9f8b15b0b43152c5 Mathlib.Algebra.GroupWithZero.Nat Nat.instMulZeroClass +D b2a1f26721b69b8d4efce322c24fb4fb7654d926b01ae6cb543ec3ef23fac903 Ix.Aiur.Parameters Aiur.conjecturedSecurityBits +D b2c001546ad6f09b1533eea0d73c2345013192f9d431591ffb41c7453b09edb7 Mathlib.Data.SProd SProd.sprod +D b2c3eb99dc9af860ba852eccb911dd0b0652bf910a467b48f84de0dcc322e8c9 Mathlib.Algebra.Ring.Defs NonUnitalNonAssocRing.toAddCommGroup +D b2daa37fe66c6191f0aa40a5f99a46480a260bff431465dab28229db8b0538ac CertiFriProofs.Theory.Stark.LookupRoles CertiFri.Stark.Model.circuitMsgsT +D b2e37afca7c930d0698f8d5a59bd476a1b8c294553da3d59c304960dc55dd4fe Mathlib.Basic.Real.Basic Real.definition._@.Mathlib.Basic.Real.Basic.326038627._hygCtx._hyg.2 +D b2fc1aaba2047f841e276a4ffb8de13230cbc2b282cf37df3463332d648f7973 Init.Prelude Add.add +D b32091f0bfae0b3a97c4b31390ecca55791b9856459df8a84e2c7df213db798d Mathlib.Algebra.Field.Defs Semifield.toInv +D b330209d411f5cf0b9ec1055d692cf998f3554e078d0da6eb7cbebd6684f4420 CertiFriProofs.Theory.Compiled.Verifier CertiFri.Compiled.Params.foldChain.match_1 +D b35a61e3bb57b2a41fc89da45c7661cd43e3919d0ab3da272908f7bb5b6fa353 CertiFriProofs.Qrom.CompressedOracle CertiFri.Qrom.proj +D b364228aa2c65b1ed7bfe9ab112e55d75090cd917aa7700f1ca4979021aea0e6 CertiFriProofs.Exec.Stark.FixedKey CertiFri.Exec.Stark.nodeFromComp.match_1 +D b3650bdac9f0d390e70e3bba03cedd7b5541e8b1fbee71a29bdf04f231c6b342 Init.Prelude Prod.casesOn +D b374135264502f4776a8be60521fd9262f47c4fc388424caf1c76385702db387 CertiFriProofs.Exec.Stark.JohnsonLookups CertiFri.Exec.Stark.w1 +D b37a19851e8aaadd45e4c3bf3ca83ef27ad1146068a70ddc40cbdc94d9c3ee74 CertiFriProofs.Qrom.CompressedOracle CertiFri.Qrom.sqNorm +D b384df3916110f46d00f9e1e8e90c6108a9c52102e45eaa5e84ff51b39f781fc Mathlib.Algebra.Group.Hom.Defs OneHom.toFun +D b3a331524b246dba7d798352a700f6b35523431bfe4f517b2654e0dad420869b CertiFriProofs.Qrom.CompressedOracle CertiFri.Qrom.QQueryAlgorithm.oracleU +D b3c36ebd7393de7aee3a06b7c860647c58934680c913a3bb400721b52ca607e8 Init.Data.ByteArray.Basic ByteArray.decEq +D b3e0e1c37ad5f7b7df3190c55ea7433dddb585a0eb561905cc5d8f790ef83355 CertiFriProofs.P3.MerkleRootBytes CertiFri.P3.ByteOracle.byteIface +D b3f50c628e7dd60778a9c209ed3feefe8642bf14345451c4002b36eacbda601d Init.Prelude Nat.div.go +D b3fb12ecb9a9d05358c5a7bbbf9fec1a1bdd977c0af7c4c55dbcb154f5123ff5 Mathlib.Algebra.Order.CauSeq.Basic CauSeq.instMinAbs +D b414d48a7daab76900b70ace17ec190af5303df5a8d3bf6259265de1ad96ee1a CertiFriP3.Blake3 CertiFri.P3.Blake3.chainBlocks.match_1 +D b4159353753e57b989cd903fcca17c8211e8f98be68fa1f0d3ce007f804aadb1 CertiFri.Stark.Statement CertiFri.Stark.Model.squareCol._sparseCasesOn_1 +D b41e42ac7e2498fc0286068ec6f5d3090b123841c594e0afcb000d2e5677f102 Init.Prelude instSubNat +D b420d7f306cf8dd31c1ee06e8f37c4783893b5d9f5a49b8dde4a6433269e9da5 Init.Prelude instDecidableEqNat +D b42f1319b79854677e1b90f26dad0ee938ba7f3abd8f42b351dba0997d933498 CertiFri.Stark.Statement CertiFri.Stark.Model.tagArityOk +D b42fa3eac5fa15c89598bbe838352c39e95faab9a83276f0e65c5c1dced22681 Init.Data.List.Basic List.take +D b4337c1ae428aa7524f38b838714496279e353d87041305318c81170d287982f CertiFriProofs.Theory.Compiled.Read CertiFri.Compiled.Msg.value +D b43b2ab9f6456d20cdb10d4e5f49b8660ba355936a275698c2f5f2b20866d6ff Mathlib.Algebra.Ring.Defs Ring.toIntCast +D b43fcec6785109d2e0d1ba90987aa32915520aaf0a5666c8da60c92b038a988d CertiFriP3.Wire CertiFri.P3.Wire.KeyCircuit.nodeBoundsOk.match_1 +D b49939eecc8bbf102addcfc7b17ea708bbd6bc3552d57851035c9f4e2ff53e51 CertiFri.MultiArity CertiFri.Fri.scheduleOfShape +D b4a77c5935a7bb057c1d04d6bc763cc456b999063b4707f4831764a55c52641e Init.Data.UInt.Basic instSubUInt64 +D b4c482efbfc2770822d4fecae329f1179356d91dd6981995c3a6dcc78b801b2b CertiFriP3.Pruned CertiFri.P3.Pruned.Node.parent +D b4f9e1b69b5891dbd7b934a0164b0d901337558f71e664766d90d9d0061ae804 Init.Prelude BEq.beq +D b5114e3f435340fb8c3a7028cb08198c425fc5a5f3aecd118f0165592002a6af CertiFriProofs.Qrom.CompressedOracle CertiFri.Qrom.compressedOracle +D b530f376c354b0a70f7bbb1029f01118422593c3bc120fb6c32e87c2042824bd CertiFriP3.Wire CertiFri.P3.Wire.ShardProof +D b54c1fb7a6d80a5a6834c38e85c511eb5491d80a518484c135cb7f01d56696c4 Init.Data.Nat.Bitwise.Basic Nat.testBit +D b54f4317fa2a92b6d0265eca2089fd7d0f3055b2807595525da6e82b696d174d Mathlib.Algebra.Module.Defs Semiring.toModule +D b5698c8c98f76e5a5252cc57b8bb14b811613c5562e13a950adf3fa37368e4ba CertiFriP3.Wire CertiFri.P3.Wire.KeyParams.stage1Pinning +D b56fddcfe8488d344d81469bf4d5dbebc24d9ba87e6792c4c3ca7eac13cccb1a Mathlib.Logic.Equiv.Basic Equiv.subtypeEquiv +D b58906b0cde36223c7afedd5ab8186a3a0077bc137f52deabfae2496b3c7cb46 Init.Prelude Not +D b5897fc96f30c67b0a035402ff90bb16636af8a8bdbe42722735166afe833fc7 Mathlib.Data.Finset.Empty Finset.empty +D b5a52c47462c4302106908aece9c3a982e7166684814b17a39ae42748bb12fb3 CertiFri.Verifier CertiFri.Fri.foldChain +D b5ce6d1d843a10e1e2afd489b3a530f124fa737b85869e417fe5044137ee5645 Init.Data.Array.Basic Array.allM +D b5d247dbc216fe54625a6c3996dfb99670bad2a28e9b878545fcee08c43b87c1 Mathlib.Data.Multiset.Defs Multiset.pmap +D b5d41be9a095ee0c3d9a34d50ed6d5397b8a888ebbede27883427ca18e1ea775 CertiFri.Schedule CertiFri.logArityForRound +D b5d71705457f82e08ae1a05ed7d9c9944ec1edd011e9523091b1ac68a0aa5aee CertiFri.Stark.Statement CertiFri.Stark.Model.boolColOf +D b5deba91267c19e0884729b8a85c6e0a75fb8ed54e063b84416df93e03ab8719 CertiFriP3.Wire CertiFri.P3.Wire.commitPhaseStep +D b61eed0f8f23155e1b832f5672edf447097d0faae2f1eafe164679c714ed1d50 CertiFriProofs.Theory.Oracle.MerkleVerify CertiFri.Oracle.instDecidableEqHashQuery +D b658c5b33e4bb5056a6657a5fe71730f81f3b0993d8d6b7b61e85313113cdfb7 Mathlib.Data.Multiset.ZeroCons Multiset.recOn +D b685621ceaf48e7c62dd5d13ef69bd20daffa0f3eabb3ab5f8856f37e297d92b CertiFriProofs.Exec.Stark.SoundnessPinnedBatch CertiFri.Exec.Stark.batchExperimentPinnedSponge +D b68db3e117e0dcf96c41dc2bc61fe4a9f2f81ab2da10748763dd0bd22b300e41 Init.GetElem decidableGetElem? +D b70acabf9c595ba2b4ba55eedcc00eea22355e264285ebe210fe2cb2efccce34 CertiFriP3.Wire CertiFri.P3.Wire.Key.preprocessedCommit +D b70b3690f500a224c9cc8ab143aebe02794cd51447cfc5a89b3c7d4b76aa53a7 CertiFriP3.VerifyBytes CertiFri.P3.v6BatchInit +D b7228084382a6a55b99c3415f8dddfccaf3c2826e312ea9893395b19d9ef5e46 Init.Prelude instHShiftRightOfShiftRight +D b782fbf3fba9f1e37413128e3125ef6568aa6fca76d8861359a484e54716f870 CertiFri.Stark.Admissible CertiFri.Stark.BatchBounds.rows +D b7aabe41043ffb10d728e8984ce44fbe521e79a7a07580379e16ed1697f4af01 Init.Data.Range.Basic Std.Legacy.Range.start +D b7bd4de2156f97f3bcb90284f2fd1a771cef4c7f59e556371f78e31fa2e67246 Init.Data.Rat.Basic instDecidableEqRat.decEq +D b7d2407444c646e86abb745b3a5210d7ed0f9e7f1c97da92dd1ed5cb792c4e79 CertiFri.Stark.Admissible CertiFri.Stark.Admissible.lookupsPlainOk +D b7fc06d3bcc4737d9e4e96f1a5bf90984b5fc414a18a102e83ee0908ffa0a2b9 Init.Prelude Nat.div.go._f +D b8122c5f32b0ce2fbc07316106387e57206b02bbfcfbb6846396e75447a1416a CertiFriProofs.Exec.Stark.Preamble CertiFri.Exec.Stark.Bounds.messages +D b81393e23172a557665d9fc6513f9da9916244c0aa25b45ae1b563236428727a Init.Data.UInt.BasicAux instAddUInt32 +D b8154e150ff8af0f8f810d500ed82c833e562ad9d498dba3556956089586ae9d CertiFriP3.Blake3 CertiFri.P3.Blake3.deriveContextKey +D b815f92fedb550b144be536ac43ec5a14e37740f0a08556ac1069c2dc39a77db Mathlib.Data.Multiset.MapFold Multiset.foldr +D b8312eb57f9a779e335177371ea655862f784a5ffdb3d04de9dd91fa5541a958 Mathlib.Algebra.Order.CauSeq.Basic CauSeq.instSub +D b8496d519a2e58e0da315c19e605e2adf4da812024188b39183353ea2d40d4a3 CertiFri.Schedule CertiFri.foldScheduleFrom +D b84e540c23a6d5658e02e7a087d134cdca823fac7fbe1c448b4c6e8ac4b820fe CertiFriProofs.Theory.Oracle.Basic CertiFri.Oracle.OracleComp.QueryBound._f +D b87ac56acfb8b1c00fd45482d625de6233bfac7f7d9731e5f3116c740b4b86a3 Mathlib.Algebra.Order.Ring.Unbundled.Rat Rat.instSemilatticeInf +D b87e4693c8c19a50a4b3b19b3be7596c46ce269a075c07f9d811c016b3645ded CertiFriProofs.Theory.Oracle.Prob CertiFri.Oracle.OracleComp.prob +D b892c4b02058608faecb004607fac358088203217349d17a333f07d4f50c63b3 Mathlib.Order.Lattice SemilatticeSup.toMax +D b89383fa7ce66c2877a41abfff10928263eaaa0df6d384fc17374c71884e39b5 Init.Prelude DecidableLT +D b8baf364d3109460f1c6e47434aaa17863633dc0f1ab1b0fd44bf09d0bed7157 CertiFriProofs.Exec.Stark.SpongeGoodLogTensor CertiFri.Exec.Stark.splitRawByDigest._f +D b8bc31fc2ebfb73aa05e46c0cb04a542826f9baeb9b71a664d391f36b7322343 Init.Data.List.Basic List.splitAt.go._f +D b8d5179a3b3e12bdaecc43588e540cef15eaa09345677edd765147f7244e1011 CertiFriP3.Wire CertiFri.P3.Wire.Decoder.bind.match_1 +D b8ebe1aaf1b39306bba500a827810e928695f63cfa9d963c674fa17451dbce3e Mathlib.Data.Int.GCD Nat.gcdA +D b905007b493c312c69e51ff1fbb8295f58a2f5f839589a6aca9ab227a5e76bba Init.Data.List.Basic List.filterMap.match_1 +D b924a8ff7c920ecba0046a1cf4898f2e34b2aac6b39aecbb2c7eacb9f1f69a23 CertiFriProofs.Theory.Stark.Logup CertiFri.Stark.Model.groupConstraint +D b9452a0f4d47e93f92b48a7a9c808eef4b120bd67be0048b5586797cca73bad4 CertiFri.Verifier CertiFri.Fri.PointRef.matrix +D b96d6414b1443d9cca944dde0cd5ce382f8ca0f631f7361be2170c616ac559a6 CertiFri.Stark.Pinned CertiFri.Stark.pinningPointOk +D b97bbd096c68b2e425c002a56b05243f1332cb5594695450f015a25b4c858417 Batteries.Classes.RatCast Rat.cast +D b97cc1641d6b4419da82054eab6f40251478b05a739ef6c85d09fd5762d9b753 Init.Data.Array.Basic Array.isEmpty +D b97e2ac14917fb3d020c82aa68bee4ec7f3854f035e7891a875205988434f4fe Mathlib.Data.Multiset.Basic Multiset.toList +D b98780d59ec18a941bba5027e87222bdff27b98ac8104975fa894a7e9e22eed7 Mathlib.Algebra.Polynomial.Degree.Defs Polynomial.natDegree +D b98f2b60ed56aa27f7b5aaec99190cb39f5ea8b38cf44711ba01f7e35f5a715c Mathlib.Order.RelIso.Basic RelEmbedding.toEmbedding +D b9b0ecdf9d153045093336b309e903f74af99c57d5ccae4333f972a73483fde8 CertiFriP3.Goldilocks CertiFri.P3.Goldilocks.pushBytes +D b9bd47884b9b3a0c8f72b6c9879341d3914c13d5c1620f8e253f93ee31be5dba Init.Prelude Lean.mkAtom +D b9c0672481da7ed1a9401763fd6b57cdbdb1f22a56ac30cb37823a47e41b042a Mathlib.Algebra.Ring.Defs Ring.toAddGroupWithOne +D b9d7113dc73d274b35231025f96e07b8efce47022b475cf319915d438281e3cc CertiFriP3.Pruned CertiFri.P3.restorePaths._sparseCasesOn_1 +D ba0c705771473ceae7b91c4a9190a83fe468651831d41de21ca4bd68c673691b CertiFriProofs.Exec.Stark.StateTensor CertiFri.Exec.Stark.tAnsAt +D ba1a4461e4d56bc5dfaed79e378c6895e3db9ef2fcc6eb384d6d2f4bb096f9d2 Init.Data.List.Basic List.foldr +D ba23a760e1dbab22a61acfa0e87ab47f24b69c56bd1e522994e8cbaf9dc918e5 Mathlib.Algebra.Field.Defs DivisionRing.toNNRatCast +D ba326618f7e363d761b6b0d2774f7aada1a64d966b798f0e2dd1ac73b2c4450c CertiFri.Stark.System CertiFri.Stark.Circuit.stage2Width +D ba51653217d0383b9f2b00f1b077539a43d64cb9764915698de53030e36de194 Mathlib.Data.Multiset.Bind Multiset.join +D ba6e37ebc98c97440372c1c90b7c66ef2c51a781c5973a38994921bedac06023 CertiFriProofs.Exec.Stark.FreeTensor CertiFri.Exec.Stark.UStateTensor.nfields +D ba80d4291f93a2c65e967024101074684f0277cbdc1a6d52aba7bcc5fc7d0c65 Init.Data.Rat.Basic Rat.div +D ba9037ed1397234aada135394a77df3eb6703e9a487abf93751e5a849cbd0c9c Mathlib.Data.Int.Cast.Defs Int.castDef +D ba9fc5537008a03de0eccef17f793b0c58f7b3947d55e68ab53a71eb92171b57 CertiFriP3.DomainSep CertiFri.P3.DomainSep.transcriptInput +D bad064f52b1f10bf79fbc0269ae8e4328bdf11809c5b297ce2f474ba962fe728 Init.Prelude maxOfLe +D bad5209bc8730314f24705c901221f9b72c29da298e77000db77c4cb7c015aad CertiFriProofs.Theory.Compiled.Read CertiFri.Compiled.Msg.inputRoots +D baef7d5a3007e03cfbd2493c37f8f329893e587c9645e493e6631773ca38dec2 Init.Prelude Inhabited.default +D bb072b8ad4da151af291083215673df17f896fe367b72501f3ca9e1b269f02f4 CertiFriProofs.Theory.Stark.Air CertiFri.Stark.Model.deltaScaled +D bb0c6cee5c69ca4221e44af3672213c80dc3f0d6857ee082f2209b63a0090b4f Init.Prelude instHAdd +D bb27ade487d1b0189d9bebc09f81b7f076a2899b26f477d8fb1472818686b026 Mathlib.Order.Hom.Set StrictMono.orderIsoOfSurjective +D bb44a1273e346d9fb202b93f9651e720505b4ac04270dea2d429ebce7acf3dc6 Init.Prelude LT.lt +D bb4a8d00bccd0922ac3910ccdc74b7ec285738d33344812ba1481c8fc71b3e57 CertiFriProofs.Exec.Stark.SoundnessPinnedFixed CertiFri.Exec.Stark.nodeFromQueries +D bb5505e91e99d5e62d1e8f6968b262d83bebca456cef8be07649704d490c1624 CertiFri.Merkle CertiFri.Merkle.climb._f +D bb6a564d1c986b01f576627fd83999387ff7781c210d2048acbcbd9b4c8396a7 CertiFri.Params CertiFri.instDecidableEqFriParams.decEq +D bb6fc4a6ca7ea614c62dd2cea4e9fa1be9452da4d2e371c4f431d08bd097ced3 CertiFri.Merkle CertiFri.Merkle.groupRows._sparseCasesOn_1 +D bb6fe3169d08cc23e93a0803ac2a1e508b326ce4636f16167dc26785014c3791 Mathlib.Algebra.Field.Defs DivisionRing.nnqsmul +D bb7bc8953aaef0ee48745ccd1d658dafefa3de8a4a38acd224a1a81040bd868a Mathlib.Algebra.Group.Hom.Defs MonoidHom.toOneHom +D bb8afe64be783c6686e5aaacecdfe518729cb189d60d285316ebb4ffa7c65b8e CertiFriP3.Wire CertiFri.P3.Wire.keyCircuit +D bbb61993af28ebfdae516f8027cf620137c780ab8840e021e698537d43470a1b Init.Data.Array.DecidableEq Array.instDecidableEqImpl +D bbb68012f877b437416d7107b905fb971e6b151278911cab70139c242cce37ec CertiFriProofs.Theory.Stark.Check CertiFri.Stark.Model.ExtData.basis +D bbc45d4d775da69544a05704235fdd6f63d897f233b3002fe3daed70bbd0e6ee Init.Data.Fin.Basic Fin.instOfNat +D bbd24574da8bcf65b8135f72f01d1a44cd2d690bed347f773779b9119f0b325c CertiFriP3.Wire CertiFri.P3.Wire.u16 +D bbe0f0d86566603332723407516133c86ca8f8efd4eb27c21fc82c200692a07a CertiFriP3.Wire CertiFri.P3.Wire.option +D bbf177acdddc7cd08078454fe890968265276893605448b9b5db538debd51f77 Init.Prelude List.concat.match_1 +D bbfe2c710f5dc0d94ce9404694045061c5c7224e02bac5ea9d316d14d0ea8f60 CertiFriP3.DomainSep CertiFri.P3.DomainSep.v6Batch +D bc28a47ebd7f81912278d220448cef12ec66e1a4276dd578ee58041a76e9c9ac Init.Prelude List.length._f +D bc2f4b83d04ff1fde6fd67acbb9d4b2768512f7dbe1e2ed597e12c8adad6e7d0 CertiFri.Field CertiFri.ExtensionOps.ofBasis +D bc31ab3f1d7da9e650abdef0660797fcbbf25c7759fc9848d7036289c7c4dff0 Mathlib.Logic.Equiv.Defs Equiv.instEquivLike +D bc33687f6c05fab02ecaaba079447141dd372c2713a31bfc4f8f12a20794880a CertiFriProofs.Qrom.CompressedOracle CertiFri.Qrom.runAlg._f +D bc54a092b0e805b15f9dff67de5a728d1b86daf1798804c792eedee0dc32b4d1 CertiFri.Proof CertiFri.CommitPhaseStep.logArity +D bc6965882d47df38ccdbcc8110cb3cc9ecb3f624e74da4ae35d36b1834c1f10c CertiFriP3.Wire CertiFri.P3.Wire.key +D bc7492026a6231bbd3287f224be8693f58140ac817c024060590c56d4d6b1780 Mathlib.Algebra.Field.Defs DivisionRing.toInv +D bc76fa529da9ffcd9cca8f78b9b7f7688de9b5302fc35d03672899876bbce9f1 CertiFriP3.DomainSep CertiFri.P3.DomainSep.leafKey +D bc7c0a393733a384a3e341d24a775c16ebadf6e7ca23bd104f8bf65c9eb791a4 Init.Prelude Nat.pow.match_1 +D bcb2d582b1cf6d6c1205612b4e069df011d5e420cb78265b1848181da51797ac CertiFriProofs.Theory.Oracle.SpongeCommitted CertiFri.Oracle.SpongeShowsRow +D bcbd58fe10a86704e200af5cee2dab40b07f517175600dfc0f6697a1b8e0b1ee Init.Prelude Function.comp +D bcc268e18a5d288efea5dde59020b82438e18801f4fb4bbf2bcf0f3674b33d54 CertiFriP3.DomainSep CertiFri.P3.DomainSep.compressKey +D bcc68a0badabf8123b9a8bd2edd70ab5adbef0c36718e761e0b2369ae2171380 Init.SizeOf instSizeOfDefault +D bccadb6d85708be605c9c836944dca34a5ead9c365b2eb2957c5f8498c9ca4a5 Init.Prelude Char.ofNat +D bcff0c344e9df83e413ea33dc537b6096f088f6c6ed4da2c723dc26902c1cda2 CertiFriProofs.Theory.MultiArity.CompiledTensor CertiFri.Compiled.MultiParams.numClaims +D bd1213f7a9da28acf449669920070ab6f1cbfeb20494837fa679dff8567e041f Init.Data.Array.Basic Array.isEqvAux._f +D bd7c8dc90f473ace9e410ad59ad18d9d67a8fafc380824b01e596f9b26efaf98 CertiFriProofs.P3.ByteLinkPinned CertiFri.Stark.Profile.verifyBytesPinnedOf.match_6 +D bdb270a85e1266082f369cdc58a3d81baaf4c9df950990cbf4aefdb363f072b2 CertiFriProofs.Theory.Oracle.MerkleVerify CertiFri.Oracle.MerkleRO.climbM._f +D bdc142555e700283527b31e1dee583af5d980271c0691d8509f4527750aeb32f Mathlib.Data.Int.GCD Nat.xgcdAux.match_1 +D bdd2adaf2efffaa411fd374722fc63bb712159c28126ab4287ab5b5a843ae900 CertiFriP3.Wire CertiFri.P3.Wire.encKeyCommit.match_1 +D bdd7ad81264f2747ed1a85630ceae6303e54c2703ab9a34563e612081ba84dec CertiFri.MultiArity CertiFri.Fri.verifyFromTensorMultiArity +D bdef36c0d8bc27533665676405cfec6d0b988721613868cb9b2115f7a43071ba CertiFriP3.Blake3 CertiFri.P3.Blake3.Node.block +D be5c99eb7bc6b92675f73e8fa02398e150367f44b93d82d76fb24ca7da0e2491 CertiFriProofs.Exec.Stark.SpongeGoodLogTensor CertiFri.Exec.Stark.tagSpongeChunks +D be8716e4405abcd74ac7dd8b5bf081d3f5250cd1041f3f972d49e51e57537481 CertiFriP3.Blake3 CertiFri.P3.Blake3.Block.m0 +D be892f231b862ec6cddc825b5a875b19531f2a45ecfbf46256fe597586bd94ff CertiFriProofs.P3.ByteLinkPinned CertiFri.P3.ByteLinkPinned.pinnedBatchOf +D be8f874f5c6becea6740648d5039890df944d44805f05fb28fccfe6350662e07 CertiFriProofs.P3.ByteLinkPinnedFixed CertiFri.P3.ByteLinkPinnedFixed.keyWith +D be90932359159f5b88ab5fa5119402c9f28c31cea709cb1c347a227a64868e97 Init.Prelude Bool.and +D be90b6f66c37669015cab6ef501ba094c527a45fd226b09b4f7898fbc11ce254 Mathlib.Algebra.Group.Monoid AddMonoid.toAdd +D be9b2bb5152d9ae249b39a19d722c66f1e2004cb84da36e0b3494b29c0ab0b29 CertiFriProofs.Exec.Stark.FreeTensor CertiFri.Exec.Stark.UStateTensor.cur +D beb310d3a818eead8fe1d7d86ac67dd766410308c68caa939d9577a777fbd6b0 CertiFriProofs.Theory.Stark.Logup CertiFri.Stark.Model.sumRange +D beefcdcae852de72aae9c58f55beffe88d2d7a90bf113124991ed61314df2eed Init.Data.List.Basic List.all +D befa332c79f7a5a623b6b076f8e379314ef14e560a02bb65e43fd96faeaff65c CertiFri.Verifier CertiFri.Fri.claimRefs +D bf332ca5ebdfa4eb184a83dbe630ec71a4c111c2e1d2dcf1c02d46eeea6f4184 Init.Data.Int.Basic Int.casesOn +D bf38b3fb157f362f3bf778add1ad50f08a25df4b126c4eb6d7690cd87a7bd2ee CertiFri.Stark.Admissible CertiFri.Stark.Admissible.nodeIsPlain +D bf47afb53a6ad0d9a13866b808cc79902946574f5d879105f29437c2929b881c CertiFri.Proof CertiFri.BatchOpening.openedValues +D bf5b49b0ca6a5da9d32c8c9ffb475de9f36d4f208638ca752a55ad61bcd0e900 Init.Data.Array.Basic Array.all +D bf657e298ae97b47418a56dc66db01b293c3031bb64a4d3a254777557f4d6ea8 CertiFriP3.Wire CertiFri.P3.Wire.batch +D bf6eb9c527b5ce182a7fced214a89db8a79dfcb9ed6039b7d594a866f975bcf2 Mathlib.Logic.Equiv.Set Set.equivOfEq +D bf7d9393c9cc78a413eabd69f2fa75a614037f2fb4b63f82318597136ecbbf09 Init.Data.Nat.Bitwise.Basic Nat.shiftRight._f +D bf81c1baaf4eae88598f8c7fd49d435f7b33bc0a37dde71b429981b3b8cf8155 CertiFri.Stark.System CertiFri.Stark.Proof.stage2Opened +D bfa435e64c6a2b071dabc386692ab310a6d5eb4b5512e0284ff9f8dc37209abb Init.Prelude Fin.val +D bfc4a80abd8f885a554e57e0fcb04f508350e153de88b3a0b7837bb63bdf4a49 Mathlib.Algebra.GroupWithZero.Action.Pi Pi.distribSMul +D bfcdc844edc7b0d8e881bf67cbdc619c1b5dc693eba9cf10c0484ff2181752a9 Init.Data.List.Basic List.findIdx? +D bfce598a478b1da709cb00d33c616a7095d505348247b0c85f6d4bf3971f4da3 Mathlib.Algebra.Ring.Rat Rat.commSemiring +D bfd558a3dd4cb47d7e86baa1dcb409473eae8b7443a76583abf0033d0933dacd Mathlib.Basic.NNReal.Defs NNReal.instPartialOrder +D bfe2e8a5fca3aa95131021461984ea87eef96b1e00338ff2dca2395fab041fe4 Mathlib.Data.Rat.Defs Rat.commMonoid +D bfee823330ebe617e38f7f0f3d73c234c71cb81ea2094628fadfc7f17db5b658 Mathlib.Algebra.Group.Nat.Defs Nat.instMonoid +D c00233c1a80cbe78004cf7f7bcbeb56317e3340fb8999f339c8872145628361d CertiFriProofs.P3.EncodingInjective CertiFri.P3.Encoding.HashCall.casesOn +D c00423ab987750f5bba12b57b1db46f9e1407e4a78e59d9507d52c366ec17723 CertiFri.Stark.System CertiFri.Stark.ShardHeader.logDegrees +D c02e24df2fa3814321c513a8ff09932657583a7289b8556accfb8d654f24b2ef CertiFri.Stark.Verifier CertiFri.Stark.selectorsAt +D c0664de9bbfdc7c965ad3634361ffddcdf3cc977f736315c8f1f0a79d989b869 CertiFriProofs.Theory.Stark.Balance CertiFri.Stark.Model.Balanced +D c06cff2582fff214a1c1ac8d959248ca111082ccfc1c7544cf528878333de051 CertiFriP3.Pruned CertiFri.P3.Pruned.ascend._unary +D c076dcf03e167f93986db91e86f750fe9d7c4d02268dccf6d44d6699a2091bde Mathlib.Basic.Complex.Basic Complex.addCommGroup +D c07c399ffd97c162a5f18c2055b7554eafc35a523ab9b39707dd6f72a25924e9 CertiFriP3.Wire CertiFri.P3.Wire.vec +D c07cd93d508d924911caf86d44a46332211654ce3a63678003bd431e996989d5 CertiFri.Stark.System CertiFri.Stark.Proof.preprocessedOpened +D c08ee7477936c3821c5ee47af630980643cca8280337c5b3f36f349308a303a6 Mathlib.Algebra.Ring.Defs Ring.toZSMul +D c0a803fbc7289d2d85914ce10d4983b4d66d36a4cd499e31d60ca2cea9591fbd Init.Data.List.Perm List.decidablePerm +D c0ab4ea16bd5c6a30b7fc02bb550bdbc159bbcc98b938fa427af8d6470cd205b Mathlib.Algebra.Field.Defs DivisionSemiring.toSemiring +D c0afc8db0482d60ec1d216e06d9105e71f0b9e1ce37043c3049bebcd2eb14d84 Init.Data.List.Sort.Basic List.merge._unary +D c0d0b2eefe0d9d19400d82b819b0e113054f1eb9a12b067fdb4057247cb94c87 Init.Data.UInt.Basic instMulUInt64 +D c0f134eb43d964de8073590c96de9587ddb318ec53f977582fcef12dd92593e5 CertiFriP3.DomainSep CertiFri.P3.DomainSep.instDecidableEqKeyedInput.decEq.match_1 +D c0fd695ca9b53f510090692941fd8405dfbecfbf83de2cb1fb8eed574ca443f0 Mathlib.Algebra.Ring.Defs instDistribOfSemiring +D c1004c126acc13f61cf712658220eac451813ad4afc320d9ebb496fec57e2802 Mathlib.Algebra.Ring.Defs NonUnitalCommSemiring.toNonUnitalNonAssocCommSemiring +D c1136f8537d7d6af0e997fde276604a647f3db62af7aabfac925bf22fd49c1ea CertiFriProofs.Exec.Stark.SoundnessPinnedBatch CertiFri.Exec.Stark.shardsCompPinnedSponge.match_1 +D c11a859e21082e46352460df775af49e3ea58529c84430aa3871000a00efc25e CertiFri.Merkle CertiFri.Merkle.parent +D c11abab6fe781eb3b1b68ede1745f693a27ea5f3c4a6a12665e80576c7577560 CertiFri.Verifier CertiFri.Fri.openingRefs.go.match_1 +D c128b5a682e3083ef17a14f93ea3b52bcf0d15a5c0743d4f99b47f059cc78165 Mathlib.LinearAlgebra.Lagrange Lagrange.basis +D c14d25329cdb58d28e7402b8849a38a597210c66990cb55062812c1f8365db3f CertiFriP3.Digest CertiFri.P3.LittleEndian.word32 +D c17cc70b64143e960d9b17faf7527a1339d9eff1558fc01de82a089fafef7e24 CertiFriProofs.Theory.Oracle.FiatShamir CertiFri.Oracle.Transcript.msgs.match_1 +D c17d3cd00daa733d04ff487233d5a3c89c80178cbc52f017fc85f9ac08599616 CertiFriProofs.Exec.Stark.Shard CertiFri.Exec.Stark.fixedRank +D c1c0cf4d0858622145d7ed24bd7ba59d80ab4d6460436e0e694c2c6eab247916 CertiFriProofs.Exec.Stark.SoundnessPinnedBatch CertiFri.Exec.Stark.batchPinnedPrunedSpongeAccepts +D c1c990a3554b436c0fa53830fda6185fd8f804252d600bca0ff59f18443c95ff Mathlib.Algebra.Group.Semigroup AddSemigroup.toAdd +D c1e2aa11b5ba9a5d6e9861e76ccafa316cbda50fa5ffa6d8677a371c95e7bcfa Mathlib.Algebra.Group.Monoid Monoid.toMul +D c1fe5d6d61b5a2baf2124697a3afb451042a34b6168dc8936998a817096bcce8 CertiFri.Stark.Admissible CertiFri.Stark.Profile.fri +D c20b017c435cf528bd1f0a484bfda6e0f5fd98fa54d349aef24c56a14f004e45 Mathlib.Algebra.Polynomial.Basic Polynomial.smulZeroClass +D c2522a3ee65a3f8af775ae0753cb6128b2b18b230329381ebeebad0b8b49c44c Init.Prelude Div.div +D c25daed650de33a2592fc77d547563be7e0e5d8a306efbefdaed80efef6bec4e CertiFri.Verifier CertiFri.Fri.levelClaims +D c262f4325ef53a69f5c4c82538fe4a8c02ed53915545433f6290a3916616b875 Init.Prelude Lean.Name.mkStr5 +D c2640fbe58302e9dcd7024d31ac61e764e97414f987de8b9410cfe572d925ebe CertiFriP3.Wire CertiFri.P3.Wire.keyCommit +D c270cfcc769f1d4dc45488291f70956a755251f03a25957550dad7ba21565d44 Init.Data.BitVec.BasicAux BitVec.sub +D c28f2f4c2cdc965b1d2eae03da765a229b3ec682f8d0b2761a0903e4e4a61c43 Init.Data.List.Basic List.foldr._f +D c296b31b4f104d7eb0c4cb9535a96d427dc29c94d0b5185f4dbcb32ffde22bb6 Mathlib.Data.Finsupp.Single Finsupp.single +D c29d9df53d98cf13a92a6cf63d6528c99ef2b1002b7dd66da422793e27a5217c CertiFriProofs.Exec.Stark.SpongeGoodLogTensor CertiFri.Exec.Stark.instDecidableEqSpongeStarkMsg +D c2a77d52c6c2c9eea43522a18d7a51fdd9a9f5a5ea0efc3045bb2259ef67e120 CertiFriProofs.Exec.Stark.PrunedTensor CertiFri.Exec.Stark.leavesM.match_1 +D c2b2780965c7c94ab0333933290dfba1cd5fb864f58d30d78e13d21847dd665d Ix.Aiur.Parameters Aiur.FriParameters.logFinalPolyLen +D c2bf2e627d47730fd0399bd0f4ffb11a7318e55eac238a63ef3efe21f8c20846 CertiFriProofs.Qrom.StarkPinnedQrom CertiFri.Qrom.SpongeDbBridge.decodeEntry._sparseCasesOn_1 +D c2c0427373c37bd5ab6e85e9a2d74897040585695892df0c606244b5bd52e329 Mathlib.Basic.Real.Basic Real.instMax +D c2c526262e773a748e3d46660a7b6e4f37d8cbf6f6f088ba29d8c8cc0574adba CertiFriP3.Wire CertiFri.P3.Wire.u64 +D c301cdec93b898cadf36d87260d8e879ade0575adf1ca9c14269bc3caf39a1f3 CertiFri.Stark.Graph CertiFri.Stark.RowValues.stage2 +D c310d12c5c66f7fa954f9f599079ff3d739a6b07d45117661f3a94ab42c8bf85 Init.Prelude Char.ofNatAux._private_1 +D c3264e9622e6cf7baf38ffcb427dc9786f5a04ac6898ed75513bba8559fd3a6c CertiFriProofs.P3.GoldilocksExt3Model CertiFri.P3.GoldilocksExt3.starkModel +D c3438e0c8a0e3a67384f97a735bbb475f7eaec0412c431889e6821c6503a2659 CertiFri.Proof CertiFri.FriProof.commitPowWitnesses +D c349def645b7c97b8edceeb84bb79eeeaab6a002051c4f19cbcb0213f994ea81 CertiFriProofs.Exec.Stark.PrunedTensor CertiFri.Exec.Stark.mapM_oc.match_1 +D c35d68d5a095796a7235efe97ee73fe5f326769e7383801dd7d7e47b44c0f6af CertiFriP3.GoldilocksExt3 CertiFri.P3.GoldilocksExt3.ofBasis +D c39998fb31b1fa496c92fe5e560137195ff9cca8dec3a65bdf2131d2a6f44d68 CertiFri.Merkle CertiFri.Merkle.climb.match_1 +D c3a765167bc7f49281ef7fa341e8fe59013649115e6ea73990b2025ea159ffb4 CertiFri.Stark.Admissible CertiFri.Stark.Admissible.batchCoveredOk +D c3b87bd453bf8f769b36c61e495c8281d131c5b54f21b78d2b153313c541919c Init.Prelude ByteArray.push +D c3d1db1b0d6ab9c91c609a0c5c2893a61fe97f6aaa539a06079d165069c5d85f CertiFri.Merkle CertiFri.Merkle.widthsMatch +D c3eefbf6fcba2346277f03847685a9ef5a5b5f1ae6bf8ce6d32d1ac9a35be898 Init.Data.Int.Basic IntCast.intCast +D c3f01110d5d0943701434dacb21cbaa4ec4d72339436941734b6785df14b3585 Mathlib.Order.Lattice SemilatticeInf.toMin +D c402c868f765aeb220cd28aca74ed2060f4f203230720545842466c1b80f2489 CertiFri.Verifier CertiFri.Fri.PointRef.batch +D c403d5bd1bd46ae785fa432747165d18c3c59864afd083703cd56f9c483edbad Init.Data.Array.DecidableEq _private.Init.Data.Array.DecidableEq.0.Array.instDecidableEqImpl.match_1 +D c420de76dd5b7ee1bd1480ef5f609a7d4fdad2529a63692318d7341e2c492f97 CertiFriProofs.Theory.Stark.Graph CertiFri.Stark.Model.varVal +D c446deb3597fb0ff2eac8c5cff0d2849a945e8d6c6be1f6f334e28548c731810 Mathlib.Data.Rat.Init NNRat.den +D c452b0a99cfa7db049a9442e205c520f46df4c2c277225e595ec04a91a106160 Init.Prelude Nat.mul._f +D c45ce4db57d1088fb22364773bd2bfb377003029a7c30b4e8f30a96ab5808bbd Init.Data.Nat.Lemmas Nat.decidableExistsLT._f +D c476b5124fca69ea111c903f2913a45afe78a29a836c79be4ca62707798d44ee Mathlib.Algebra.Field.Defs DivisionRing.toDivInvMonoid +D c49df8db3c6a6a8138e75f903782c825234acbc9d527cedb92422c05884f361f CertiFri.Stark.Graph CertiFri.Stark.Lookup.args +D c4ad5d79c859cb3d1a87fbfec36deefa94a7770d75890fe32690a37394b66c60 Init.Data.List.Basic List.any._f +D c51af31b2e71d181b360d6e10a1ce0e309f529e5283f689a3c9b96126156f7bf Init.Core Quot.hrecOn +D c51de93595a006f9e88df3a7528793bd31fa0a860b58a3a5d81654243242122c CertiFriProofs.Qrom.CompressedOracle CertiFri.Qrom.QState +D c522353e447694975cd7881e12ac10c46cd236fb158e1b30e70c8c43f28388a9 CertiFriProofs.Exec.Stark.SpongeGoodLogTensor CertiFri.Exec.Stark.deriveSpongeA +D c526a0c19d93d45d7d94d94c52f0f0e638acf3aac993f5a91b56c35a7fd5c7c9 CertiFriP3.Wire CertiFri.P3.Wire.Key.vkDigest +D c560f833f4fb514e3a4cb79654cc9a68f08a0c836ec2682db6f79861ca4ece86 CertiFriProofs.Theory.Stark.Logup CertiFri.Stark.Model.coordMul +D c56eae2a4a7c3dfa0ee53e5967b25401d71ce9d4c807800337edb05c78d1c3a6 Mathlib.Algebra.Ring.Defs NonAssocSemiring.toAddCommMonoidWithOne +D c57556a30912b6c581403bdfb85485b05e2a7d8d6853de836955d9372fdef715 CertiFriP3.Wire CertiFri.P3.Wire.batchMessage +D c57af715f4e45fdcb21995fc4d2eaca5d7a64ef9c3840c5914937c642dc06e8a CertiFriP3.Wire CertiFri.P3.Wire.KeyParams.ok +D c57ba46293f0317c170e91ed2bad24da33538450ae206add9daf3f2069b12f53 Mathlib.Basic.Real.Basic Real.definition._@.Mathlib.Basic.Real.Basic.2348678026._hygCtx._hyg.2 +D c57bb38588b4207bc9ca2030126a0a68b5fea7ab5f27de5a62b88845c1c65edf CertiFriP3.Wire CertiFri.P3.Wire.KeyCircuit.nodeBoundsOk._sparseCasesOn_1 +D c5d33cccdd939abb2f0b916055881506870802a9eef728f7272cd4b6e517d494 CertiFriP3.Blake3 CertiFri.P3.Blake3.Node.flags +D c5e75d947d26ca84ac5b4b3a3f59d0f6128dd461c0b7c143efb07bd55e883680 CertiFriProofs.Theory.Oracle.SpongeCommitted CertiFri.Oracle.SpongeOpens +D c5f45114588a560c89d94430ed52afceae625c0de9b24875449f5a7dfd761241 Init.Data.List.Basic List.decidableBAll +D c6500e5ec4b263452c4c4bfb4c16582e0922ca099e69a9bf73f4d2f2cc5f6e51 CertiFriP3.Digest CertiFri.P3.Digest.w1 +D c656df956c9097e5cfd178f4d6dd700a065c58d607d29f660a689258df61ad7a Init.Data.List.Basic List.head? +D c673f06b24bba46dd46ab32cecce3b18aec8d81f324c7ed52eb0c9405c276606 Mathlib.Algebra.Group.DivInvMonoid SubNegMonoid.sub_eq_add_neg._autoParam +D c6b09fa95ff79f14f6dc4d9fdb5e1392168df687d30e13d4ceddb24ea350fa7c Init.Data.Int.Basic Int.toNat.match_1 +D c6bfda0f7b0424d7583fab8d04c1784e15b9d610b454b0d6ef82e6be2548ba46 Mathlib.Algebra.Ring.Int.Defs Int.instSemiring +D c6d18519d2e07027dc70a9b78adc92792c003134a7676950c9e09b15d11f259b CertiFriP3.Blake3 CertiFri.P3.Blake3.Block.m6 +D c6e157dc8dc659e54c30656ce966d378a9814a7c2b51f6f85203797e6d1ba511 Mathlib.Order.Basic Function.Injective.preorder +D c7000d5c511a5a91dafa3e1f05fb0a140c23e6bab7915dec8e1a9270886a5335 Mathlib.Data.Multiset.Dedup Multiset.dedup +D c70b7becddd22fdd8afa075eb03cd4bcac08cef49ecaebc3f1237f9fd4249272 Ix.Aiur.Parameters Aiur.maxProofOfWorkBits +D c70ba09d9dc5c7fcd24fa89739ae2b1b1774c5e368b8a1f334e6cef8f80dab44 Init.Classical Classical.propDecidable +D c727124d7418a8b7aeb7f41cea00b68a1cde130dbeb2621b236434e86244e5e0 CertiFri.Stark.Verifier CertiFri.Stark.quotientValue +D c72e43f895c3aa9fba550868d096c36c99d450d56cae3083275751a43c806c9f Mathlib.Algebra.GroupWithZero.Defs CommMonoidWithZero.toCommMonoid +D c737c1b70b2f4a1df653e8c6b3ed1c5c4e0a7f714315be4eaa7b76dd227a1d27 Mathlib.Basic.NNReal.Defs NNReal.instLinearOrder._aux_8 +D c75dbd2e18be65abf07f7fa8c4b9154d973d895eceeca683fd30aed8f4257249 Init.PropLemmas decidable_of_iff +D c7a3d3d503b1addba30cf1971876d47d0f7debf9a311679490a60af48840a3f6 Mathlib.Logic.Equiv.Defs Equiv.refl +D c7a439010450ab3528156ae7817632d490b5126dfc68b90ce05bf8f3771af982 CertiFriP3.Digest CertiFri.P3.Digest.w0 +D c7b9585870d9340b2b5836d494370f2477ddfb9c715284e9c06dd139c12afdc0 CertiFri.Verifier CertiFri.Fri.OpeningRef.logHeight +D c7cbcbe81982e320cbe4c6ebf8ba45d5677ebfc0e5db55f6b23473d3b0e284a7 CertiFriProofs.Exec.SoundnessSponge CertiFri.Sponge.HashOnlyAnswer +D c7e090a6630f8321351efd38a924efcd34f674cf04e02f5bc474b40664d74505 CertiFriProofs.P3.ByteOracle CertiFri.P3.ByteOracle.ext3HasherOf +D c7e8035734e41458fad08939623ff00b9c7cb4cd750741381efb26c91ac05d50 Mathlib.Data.SetLike.Basic SetLike.instMembership +D c80005894837367cac7e21475a37cad139fa406c389aa8753437d0e8a1fa598a Init.Prelude ite +D c83188255c8a444d9a9b95e7ada7da1ac96b38ffe6dbb59738018238faaf998a Mathlib.Order.WithBot WithBot.instPreorder +D c860116ec8076518cb04329a8864b0bcb45b86bac8bef3d9dc08a1f38805bdf2 Init.GetElem List.instGetElem?NatLtLength +D c88a640cda621cd7aa1f8b5d655f75c0f74c3f3b4164cecdaf24adc192c91bb2 Mathlib.Algebra.Ring.Defs NonAssocRing.toIntCast +D c8aa8691567d6ec14b87462c6150fd575d3d1e50d309a4099624ace6d77cdbe8 Mathlib.Algebra.Group.DivInvMonoid DivInvMonoid.zpow_zero'._autoParam +D c8c855f600a778137d7a394027330e0098469748cc45be443eecf4ab4aa41ef0 Init.GetElem List.get?Internal +D c91cc151b37ef6fd45168a3d698e87a3c540bc8bc8379e99531e93d879b60970 Init.Data.Option.Basic Option.isSome +D c91ee76aa53eda067012268dbfa0dc7eb6b8068483e0e25229bb5a41f7335375 CertiFri.Field CertiFri.fieldPowTwo._f +D c95af5a8bbcd2fc1e3ce1741d450e34eb7112ecad208eb15783e4f8eac199fee Mathlib.Algebra.Group.Action.Defs Monoid.toMulAction +D c95b41ba1b91caf718d9adda1e9eac83bacee8171cff93c981f704de5902d031 CertiFri.Stark.Admissible CertiFri.Stark.Admissible.nodeIsPlain.match_1 +D c9836e11f8f1c8c53456266bb67ee46dbdf4108c720ff34e0f16eea00839f43d Init.Prelude instDecidableEqUInt64 +D c99cfddbe8c87aa0af76b4c582d1ec06676f58b68a4c1dec5d2607ea3f7a7a10 CertiFriP3.Blake3 CertiFri.P3.Blake3.Block.m11 +D c9aebfb7c42da700d648fdb989710dbddad9295405a683330cdd29e0a3a48b4b CertiFri.Bits CertiFri.reverseBitsLen.go.match_1 +D c9cefeb5a65db29904e0d39173f9d666e747505381d665a00cb8e774b049bc91 CertiFriP3.Wire CertiFri.P3.Wire.ext3 +D c9d15375c5fd8c42bec9a54158351feec41bf89c4b6989156babed510aaa029c Init.Prelude ByteArray.push.match_1 +D ca56201108e93c1f283c28f327a4f3890a94913eb9f136bdf787b8177933a2f2 Init.Core EmptyCollection.emptyCollection +D ca859573ab63639646f1eadcf221bc72a6cd712cee5d852a8064118214c51965 CertiFriP3.Blake3 CertiFri.P3.Blake3.rounds._f +D ca9283bb2b2a5d9a43f81e9b9398c73493ccb6da68f86606fd6fd2e4748faf1d CertiFri.Verifier CertiFri.Fri.TensorChallenges.indices +D ca92ae5f578eeae72d0c8ba2e2b844ad31220072a622acbe474fe464b727c45e Init.Data.UInt.Basic instModUInt64 +D ca98b03874a6c3e46864fc6f6058c48cc64c4cf01e9bbaf013e2b51573c4d3a2 CertiFriProofs.Theory.Oracle.FiatShamir CertiFri.Oracle.fsTranscript._f +D caae1750253b0f2a87ced946c0757e991ccced68ea23a3b38bda87b4af426043 CertiFri.Claims CertiFri.PointOpening.point +D caae2722fd426ff78af849b4362f8d50fe0f101793e7c6ead4e203bd59dd4931 Mathlib.Algebra.Order.Nonneg.Basic Nonneg.nsmul +D cabb7325eb88fb5e0f42f4192ad48a2bbce95dcd14a55ef7ef2cade5e64d6b83 Mathlib.Order.RelIso.Basic RelIso.symm +D cadce3bc78ddc8e34a0148fee4d6d7ee442e5e3aa4ecde952cd0bae594cabb76 Mathlib.Algebra.Group.Nat.Defs Nat.instAddCancelCommMonoid +D cae1d7d96611ce2f29fbce6ea327b162493c6e5c70c56d898ba0d563e97813e8 Mathlib.Algebra.Group.DivInvMonoid zsmulRec +D caed38534317d7f7e5828255da0e9f1d5d53e7a0ddcf228d5d9960a58d551820 Init.Data.Array.Basic Array.foldr +D caf5cb372df64583c3dfdecc098d538085db859c3a63082c4bc62bf0e3784977 Mathlib.Data.Finset.Pi Finset.pi +D caf8097c1df3890231ad7049788e5ee8ef4c30ef04d2db522fe099360da2465a Init.Prelude UInt32.decEq.match_1 +D cb02f014560f4377a0dac874b4b151cf36ea5138c7ff29183876f4a753896be1 Init.Data.List.Basic List.filter._f +D cb1959c5004b85fb48d900a16187a86be3f9c48a8a1124fbb12163c6d32ff55f CertiFri.Stark.System CertiFri.Stark.System.circuits +D cb31324167c2b740f52fa3f2a561db29796627e8c7cbc54ea270b2e5188b89f2 CertiFriProofs.Exec.Stark.FixedKey CertiFri.Exec.Stark.compressComp +D cb36163615132304cbf701c49141e46f46c73a07a4e60f04c39b7a57ee3926ed Init.Data.Nat.Bitwise.Basic Nat.bitwise._unary +D cb639b80837042c375a34ed27c24fd0b1f487724ee62c8c34738ae02ce1d0d73 Init.Prelude Array.mkEmpty +D cb63c6817bebda9d34aa15cea10666157a06911766a8592e12cf4361152da950 Init.Data.Int.Basic Int.cast +D cb698ce8ffabd5406adeed21d3ee23e3cef49b9e4c5f9ea6c18b6d9826461207 Init.Prelude Bool.or +D cb7e06a4a3bf136010be603623d52f8e0d7ecddcf8ed5aaa88db27dd71a26027 Mathlib.Data.Finsupp.Defs Finsupp.onFinsetSupport +D cb88e4923c38d07d42202bb41a74a9122222b408de40d8249272cd9418527610 CertiFriProofs.Exec.Stark.SpongeGoodLogTensor CertiFri.Exec.Stark.spongeRunMsg +D cba1f5e88579b1f312107edfbad68bdf4c86e0d1b08578777080809cedbcce79 CertiFriProofs.Theory.Stark.Graph CertiFri.Stark.Node.Plain.match_1 +D cbd5511c63ea64f40772ce8f47c5ba9418f6e557beeaac9cab30e6253f50be85 Init.Prelude Sub.sub +D cc1628ed76fcef53112a889435dcbcd5fa8a80618959c27ae7e8a652049f353e CertiFri.Field CertiFri.FieldOps.toAdd +D cc2664399a2e21c06d55f3e1b95e220e04217997c004386189da7f7e029e3bdb CertiFriProofs.Theory.Oracle.Prob CertiFri.Oracle.OracleComp.expect._f +D cc31d702fefb78e087a4fbadce6006a2f1526bfe6c6a0ebdd27624ea43548280 Init.WF Prod.instWellFoundedRelation +D cc669128fcc68ccf17524a61825c12de5ae0a4a3f9892a962ec7201fe6dff270 CertiFriP3.Goldilocks CertiFri.P3.Goldilocks.reduce128 +D cc8407fae610c28fc945e5721a8945399a5c6472d8ca738bf3c49de40a810397 Mathlib.Basic.Real.Basic Real.commRing +D cc9c96de2ff456224d7b56b42fe08aadca5ea003466049e890d4e3665f81d982 CertiFriProofs.Exec.Stark.SoundnessPinnedSponge CertiFri.Exec.Stark.restorePinnedPathsHashM +D cca15c66f561c2e7e2cac7197f695a3d8cfa22d963264faa64e90d015a86f0fc Init.Tactics autoParam +D cca1aa9878dcef093d86bb08e5239024b04ed86867e19578a0c2175e55fc5572 Init.Prelude panic +D cd1e9065c52bc9023dda3659e892fa45d755430fdce07ef31924629cb705a938 Init.Core Quotient.mk +D cd2346fde2099bd2e6fd9221963c0e166a8609ecb5ece8ddf58dc5a316730265 CertiFriProofs.Exec.MultiArity.TensorExec CertiFri.Exec.modelParamsMulti +D cd4524ac805b0f6b901052769d0b1eb40738e70b588b5dcca54b19b062a0c1f0 CertiFriProofs.Exec.Stark.Shard CertiFri.Exec.Stark.accIn +D cd5999f6f45dc85480ae28b25980f5f91ee5be81e3da0a8bf207051c5b2ced10 CertiFriProofs.Theory.Stark.BalanceReceiver CertiFri.Stark.Model.sendersOf +D cd63d2672005f2fa4f9f5446010f6dde3c96df2310f4b2356388ea3bf4298c3c Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.nonUnitalNonAssocRing +D cd71feebdd42771d5ec5413465cf56fd494fccd006027b5ce5ed0444f39e9807 Init.Data.Array.Basic Array.isEqv +D cd846c6e7671e3be73d43b6d109412b4d4db017bc990e4566c6f814b2675cc6c Init.Prelude SMul.smul +D cd8a00f24e59d2d314313c1d31009bf95f3a9ab11ec5ef2236442e5f547c7d97 Init.Data.Int.Basic Int.add.match_1 +D cde9bf388a08ca9d9262b7991f8434c393067de29f2358df45e4db7630a3884a CertiFri.Stark.Verifier CertiFri.Stark.claimsMessage +D cdf3d68585e8f252cab6dff242ca48202d89e634345aa8df12800469c34f8d50 Init.GetElem GetElem?.getElem! +D cdfa8f49871c175208102c34bed8163edebecb5cb0022638c4719027ee56e350 Mathlib.Data.Nat.Cast.Defs AddMonoidWithOne.natCast_succ._autoParam +D ce0745829ea2f61501ffa777cdfb6021d5e3e89d86402cdeb63cda10903a600a Init.Prelude Nat.ctorIdx +D ce1c088662895c5c57638bae10b5aa81b05675973f4b36cd7ee7a568fcc5fcfa CertiFriP3.Wire CertiFri.P3.Wire.KeyCircuit.contextsOk._sparseCasesOn_1 +D ce7e3bb27dfed26e39825989ed2dc2acff58ddbf6375ec494c62ef055322f5da CertiFriP3.Wire CertiFri.P3.Wire.vkDigestPreimage.match_3 +D cea8888a0c07f0384b8992162557f231698892a115fb2a82ce98ebfa00464b1c CertiFri.Stark.Admissible CertiFri.Stark.Admissible.zetaDegree +D ceb3692fe7e8d21c401a08371d7e1b38272ae5062d16b5c3c9d424f0abe5e19e Mathlib.Basic.Complex.Basic Complex.SMul.instSMulRealComplex +D cebd1ff328b7e57018ed5ee3651b6672508d58a5d804a6963fead5ea5a714f69 CertiFriP3.Wire CertiFri.P3.Wire.KeyCircuit.mainWidth +D ceef6e15d2b8f6189235943f46d96cc68a48dab3457e157c19853daacef20107 Init.Prelude ShiftLeft.shiftLeft +D cf0c10226a268b44a8628b3b481a90f3edc5ec1de5e4f507e26753d2edd44d2d Mathlib.Data.ZMod.Defs ZMod.match_1 +D cf0df1845fa26b11208562cb235694a8b94b0cb80fbc1cb4c52cfc6d81240ae3 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.instDecidableEqFp3Model +D cf0ed795097820c7aad7478565bb2b7ac0a82ef92798adf7da68fa31010c8fd3 CertiFriP3.Wire CertiFri.P3.Wire.KeyCircuit.contextsOk.match_1 +D cf10f143be89166cd4e5faca2316a234c906c57e2e508dd07030e5f6ffc28ccd CertiFriProofs.P3.Goldilocks CertiFri.P3.Goldilocks.toZMod +D cf41468d8c152818542cc5121b5929d923cb1423fcd229043637423e4947fb40 Mathlib.Basic.Complex.Basic Complex.instMul +D cf56516674affef7889e3e9da3e9c1dc4d08c2976b4834ea18372b05211c9383 CertiFri.Stark.Graph CertiFri.Stark.Graph.nodes +D cf59dae77b3aefe86f63f875f886d818a189f088c3b6f74fe8ac1babf368b03a CertiFriP3.Challenger CertiFri.P3.ChallengerState.new +D cf6ae8430977fab4a49d93684ba6fa8b5d74d1cf28c515c6e6a275b8ad415e03 CertiFri.Stark.System CertiFri.Stark.ShardHeader.stage1Commit +D cf762b95fc4e7d07db9993b8537a98bd0961e99570b1293c18175b828e762c53 CertiFriP3.Blake3 CertiFri.P3.Blake3.iv +D cfc1ede8e32d72b433c1c6ab8d7dbaad52b0521404043ad0751e414d43b9056f Mathlib.Data.Finsupp.Defs Finsupp.onFinset +D cfdd6176b51123ef6f89307fe826f3ee694ad99dbbdcf2748a444823af6d8909 CertiFriP3.Wire CertiFri.P3.Wire.decodeBatchPinned +D cfef4e5de09d306c43064fbc9a9d92f4451795feea3f3f5ca26d432d133a14d1 Mathlib.Data.Multiset.Bind Multiset.instSProd +D cff83661ca318dbb658fd6ac662ed25dfd9dab7d602a579329ebac06cc78af21 CertiFriP3.Wire CertiFri.P3.Wire.decodeKey.match_1 +D cff83963bb43b51c4681b389be570785961f3fada14774eab8b85f88e1ee96a1 Init.Core Quot.indep +D cfff22be989354aadd4dc8b7b0cd194da2913ca3d917cae1dafd7125ce4497f0 CertiFri.Bits CertiFri.reverseBitsLen.go._f +D d0046dac1b486353fd7f58643609f18c1f82b7d3e4442c6ec4929de11fd616a4 CertiFriProofs.Merkle.Tree CertiFri.Merkle.Tree.nodeFrom +D d0077cccfd97432b2ea607a10ecdd856d3d87c2fab020f7378a8fd6811818643 CertiFriP3.Wire CertiFri.P3.Wire.instInhabitedKeyCircuit +D d02c545cc769825c53e29e7c90d9b57b92ccbd3352b97c760a193d03830f7d51 Init.Prelude List.toByteArray +D d032b7125a19101cb16f7446ddd8f565935c2aeaeb539633ec9278fdc2a54633 Mathlib.Order.Lattice DistribLattice.toLattice +D d03fafd87afdd6ed2cfe62bbcb30b707625eb369d8dd287f05b90519c5f71a8b Init.Prelude List.noConfusion +D d056a0e1972fc1da4d82920f6f11ade5003d5371043e90f6d7dbaa6c12cdd40d CertiFriProofs.Exec.Setup CertiFri.Exec.extsIn +D d05d6db6fc5c35951d9a6b0886f81a6c6f172c0c55c6c8694375d4da3acb04c5 CertiFriP3.Blake3 CertiFri.P3.Blake3.finishNodeWith._f +D d05fc457e39ec4b7bf8fd9d9964f3b3afb26a11fc176e047b54be294d24a7910 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.c0 +D d066c3d907493c96bf2c7b11e9877ae96b85c249c3c08a5e0f89e930646e4dfe Init.Prelude Array.toList +D d08bd50a91cd03f7733dd26ff2db4404d15aae8227d6d28c0cdf7a3cdbed53f7 CertiFriProofs.Theory.MultiArity.CompiledTensor CertiFri.Compiled.MultiParams.shift +D d0b66c9126b74fbf00c10ca683f5bae66dbcd82d0087c3e0e01c5efa6614e741 Mathlib.Algebra.Polynomial.Basic Polynomial.instDecidableEq +D d0c3546ac92eb18e41efc369166f9ce8632a8651c6a35ce5d367ecec7ded6906 CertiFriP3.Wire CertiFri.P3.Wire.KeyParams.numQueries +D d0f22e2f9f933c05c7913c12b83645a3bd9e5ce9dc39f4c32d9ee3d4ca9ed88a Mathlib.Data.Int.Cast.Defs AddCommGroupWithOne.toAddGroupWithOne +D d0f4a43a53ea43a846833c1fdeac0a5c66117e176f2923000846f841758b37db Mathlib.Algebra.Field.Defs DivisionRing.qsmul_def._autoParam +D d104b7f6cab2fc8113dc300c7ad1520f383454505ee53bfb76cf102f67d58bcf CertiFri.Stark.System CertiFri.Stark.Circuit.quotientDegree +D d104f886b179da582dee3954b7baa1a289c9d7068bfc279e9ffb79b3c6ed64e6 Mathlib.Algebra.Group.Semigroup AddCommSemigroup.toAddCommMagma +D d1291c2940ad6139fe950e84b331ba513a9ac980cb87e15f60d09e922c964ca5 Mathlib.Order.Lattice SemilatticeInf.inf +D d12b1d8d2e451b6567715c6426164820a03a6798bfe9c34a34437ae4655c9a7e Mathlib.Algebra.Group.Monoid MulOne.toMul +D d16a0d05a8fbcb82149ccf63abf301674586e57a1a0965857e8b75db9fe60a95 Mathlib.Algebra.Order.Group.Unbundled.Abs abs +D d19848f46abec3c2fee6261ca3fba87c9b1fcc3081ae722565edc2389f0d7ef3 Mathlib.Algebra.Polynomial.Basic Polynomial.ring +D d19e3e09c442f62e98d0c4304700610444a2181dec41803f543578b59f613248 Mathlib.Algebra.Ring.Defs NonUnitalNonAssocSemiring.toDistrib +D d1dfec721ecfaf18428b74085b2bac2b5c510851c3eb515cd5827135aed81347 Mathlib.Algebra.Group.Monoid Monoid.toOne +D d1f0ba7cfadf273dc4911231d3185e3cc4d02a4d80ea6550e973159185324e0b Mathlib.Basic.Complex.Basic Complex.instAddCommMonoid +D d1fbad2a5497f62660a48f7759181b4b111f62f6c8601cf14f50e5016cf95ac3 Init.Control.Do Break.runK.match_1 +D d23d28e48318d06023ebeae4f4b17e0cbfd176d311c1611a193cc316611ef1c2 CertiFriProofs.Theory.Oracle.FiatShamir CertiFri.Oracle.FSAnswer.match_1 +D d2452c33f70d9acf8dfb901802bc62cb4d01fcd81689b2335402145cb2005b75 Mathlib.Basic.NNReal.Defs NNReal.instZero +D d24af19663b7ffc14eb05095142d3e50d33fc8f9fc6e315dc7f3556ad7325bce CertiFriProofs.Theory.Oracle.FiatShamir CertiFri.Oracle.Transcript.below +D d27b365ba5328768c067bd14eeff4b3450a4d742389aaad84b14ae238433b15e Init.Prelude Bool.not +D d27f4368768c853d9d4bc5d0177c2c0de1a75d5684738bac53643f1d7752746b CertiFriP3.Wire CertiFri.P3.Wire.uLEAux +D d2aaf628edea26b829cdb13b4b877883e3b9ea3f8888276f45f916f022c6d5e6 CertiFri.Stark.Statement CertiFri.Stark.Model.boolColOf.match_3 +D d2bade91572cca837c296d4ceb3c3eb20347ee0c0fbfbdcc802ff885e4eee201 CertiFriP3.Wire CertiFri.P3.Wire.sourceOfCode +D d2ebfbf8f3586d7b02780ba3394de93e9cd05efc8ae27e8128057f0a70b67974 Mathlib.Algebra.GroupWithZero.Action.Defs SMulZeroClass.toSMul +D d2f0f3e821224c2308b8d65fcc08303a6ea36bdb54168e7cd7980dd560f6d805 CertiFriP3.Wire CertiFri.P3.Wire.sourceCode +D d2f19374e1d5c5e05acdcac88bbadeed16fc4698f6b4551524d21edadbfd23a9 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.GoldilocksField +D d30146dc1c3b0e0d1eec62d2682819c9cc1865fd28381d4df64680118efa9149 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.instFintype +D d31bebe584914b7cb39646fb9e899c78603c0748165e76628fa2564714dd428b Init.Prelude Option.getD.match_1 +D d342cc687ae2eb9c6414c6f214391455b9e0950db70e2884b7660d3cc6e7dd35 CertiFri.Verifier CertiFri.Fri.pointRefs +D d34ee74c5ab7dbce256252806e5466e1b10e1ac52357aa0f6ecd368bb82f61e1 CertiFriProofs.Theory.Oracle.Basic CertiFri.Oracle.OracleComp.run._f +D d3510cdbfdd8d905a6ff41268d669c8014b097f80f0849d9024d5f5033b4e045 Init.Prelude Array.getInternal +D d383a21e967ba151c15cb0dcef7d22687dd82fe41bff7e3f6d8fa7c0ef5f687f CertiFriP3.Goldilocks CertiFri.P3.Goldilocks.generator +D d38c489053a315610ef5fe6a84d1f6eac0fd6dad79a21d3a0e70dd2d2b33bb61 CertiFri.Stark.Graph CertiFri.Stark.RowValues.isFirstRow +D d38f7431c2fbd22be44ea8470897a52079c5a498aa40d16865428c622fc87a8b CertiFriProofs.Theory.Stark.Graph CertiFri.Stark.Node.Plain +D d39f59da804c0c75e353beaf196135e9a7f80401e8caf2457094cd7dcded0cad CertiFriProofs.Exec.Setup CertiFri.Exec.modelProof +D d3bf507614e794ada90780155204dd914805defd559f264e05e68bada64c378b CertiFri.MultiArity CertiFri.FriParams.compact400KBBalanced +D d3c787a08aa5d37d89be9a0db4cf5f8c1746ed5f63275985ebdaddfa69957e3c CertiFriProofs.Theory.MultiArity.CompiledTensor CertiFri.Compiled.MultiParams.encRow +D d3c7c10451700385ed9ce3f0ac647db9b3ed789cb41c18898a617e70389de471 Mathlib.Algebra.Notation.Pi.Defs Pi.instPow +D d3c87d1a5ad4bf27bea18b8c696384d3bef912b0f0c12347eeef863d943c1987 CertiFriP3.Goldilocks CertiFri.P3.Goldilocks.twoAdicGenerator +D d3d417baf87b909eb94f960fa1c04824aee7b52c16c52f36a7cb7d5903b0b6fc CertiFriP3.Wire CertiFri.P3.Wire.cap1 +D d3db151d8faf5a92d3c5d98fd0572c2cadaa884b450fbecdbf4a8debf3839136 Mathlib.Data.FunLike.Equiv EquivLike.toFunLike +D d3df0634e98983299f9f0e05d89300f8c1528735c3536b01fede9cfac77b7867 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.c1 +D d3e4c1f414e895d90794a82c5f8d8ea5f8d5594305e97a52b0a56b9b4c0ae0bf CertiFri.Challenger CertiFri.instDecidableEqObservation.decEq +D d3f6b54d90ad1023e9495f39d1b9dea7156078838e6fe85b82bf59ca2735b2b3 CertiFriProofs.P3.GoldilocksExt3Model CertiFri.P3.Fp3Model.basis +D d40c852c45bc09c2c07315c13eaabbb19f90974fa7913df3d4579e089f670fa6 Init.Data.Option.Basic Option.elim +D d412ef24b39c7e4e85f7440031a603f15a8ae962995c02ba8d97074e8a4d25d9 Mathlib.Basic.NNReal.Defs NNReal.instPartialOrder._aux_3 +D d44354d9733fc474a280273eba76c7ff004cabe766e890df08a0ebaa119342fa Init.Prelude Array.extract.loop._f +D d44865464f620c089f63e45d5a36bc2da6100e0c588e16fd1250640a01a132a4 CertiFri.TensorBatching CertiFri.Fri.TensorSchedule.sample +D d467848097877dab2f7f8b39ebdb9852730fd7df234de7207e10dce3549f710c CertiFri.TensorBatching CertiFri.Fri.reducedOpeningTensor.match_1 +D d46943e221f549349b81675dc7ba9e1463300bbf46015949e24a7d97f2f73b8a Mathlib.Algebra.Group.Monoid AddZeroClass.toAddZero +D d4701549dccf1eed66072849923c5b96cd3eb077361f97ef50b2bee4128494d5 Mathlib.Algebra.Order.CauSeq.Basic CauSeq.instMul +D d4761fc1aa1aec71a8d377d62d581d2019d812cfac62b07525b68c226eb3be42 Mathlib.Basic.Real.Basic Real.instSub +D d4811bcbb6cf8bed8625ddc6d52fa17af36408405f4e976cf8acbc3e108f1bf7 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.instAdd +D d4aa4d7d7bd590ca806db42f2cb31eac602532288bfe09530f4829be73488e37 Init.Prelude HMod.hMod +D d4e755d615fb7917f1527a152604dc67b4160b120631f5a3c5f33cdf2f078748 CertiFriProofs.Exec.Stark.PinnedLink CertiFri.Exec.Stark.fixedShapesPinned.match_1 +D d500040d5b450436e95048b37336e2291ad13790b14bef99b5517fcdd578dd7d CertiFriP3.Pruned CertiFri.P3.Pruned.walk.match_1 +D d50291c724b827cdffcf993c50e1150b86c1c6ff654058fe2d99348196a09297 CertiFriProofs.Theory.Stark.Check CertiFri.Stark.Model.ExtData.coord +D d50d98d5c17dc023d2dd9fcda500e7c53ec7deaa88b64715844f0cbf3818122d Mathlib.Data.Finsupp.Defs Finsupp.zipWith +D d5174959f4a7f0c7b6c60e66f947f978a2a32ccd2ef2c10069941d4516b77b90 Init.Prelude HPow.hPow +D d531d748dc6769ce978917c3f327be1beee077c337ce887314608b9c60a11c72 CertiFriProofs.Theory.Oracle.Basic CertiFri.Oracle.OracleComp.Outcome.match_3 +D d537cba6190f7a3b5c87a2c8fed60664219a323f8ee95219edf257079392a7ec CertiFriProofs.Theory.Oracle.MerkleVerify CertiFri.Oracle.MerkleRO.compressM +D d55cfcccae79b40831a4481f0c50198370a31c96f494bcb9f46aba45086a7428 CertiFriProofs.Theory.Stark.LookupRoles CertiFri.Stark.Model.lookupRecv +D d5b1236da02d3edc39a77a03551e4a754e6284cf323b5b5b954d19bdd549d513 CertiFriP3.Wire CertiFri.P3.Wire.friProof +D d5bc12031f07bf1661f5486bc90e3edb8defdfd251b2eebe01f4c773a920133b Mathlib.Algebra.BigOperators.Finsupp.Basic Finsupp.sum +D d5db721c9283a618375a5013f60c82d69811e9cf342d02481fafcfa4b0818c76 Init.Data.List.Basic List.decidableBAll.match_3 +D d5de4b3c5b11e59c5684246a681b831c2f8cf63aecaf903e814d88e4ce46f040 CertiFri.Stark.Verifier CertiFri.Stark.Challenges.state +D d5e4d16ffd1e3935ee48e4edfe7ed16af984c0b1ff916c1506cfb2b80d99d691 Init.Data.Fin.Basic Fin.neg +D d5f3ca4c59a1c3fdab5dd3c2d9d2c3f1af4a20f425aeadde77396ff1f5a5e915 Init.Data.Rat.Basic Rat.add +D d5fc0784c1200e42b3da1fdbd860e8fa7a44db48b05d1253eb93921d4d245661 Mathlib.Algebra.GroupWithZero.Defs GroupWithZero.toMonoidWithZero +D d638554a02075e64171c23acb70ba440e4bede9a573926910bc6cca5422421a6 CertiFriProofs.Theory.PcsRbrTensor CertiFri.PcsRbr.TensorChal +D d63ed412012aaca9bef20fead9ee13ce1b1a2c7b5ca14c994b167b14f5e7cc53 Init.Data.BitVec.Basic BitVec.xor +D d644dc97a87137aa029070704814696652bfef4d5067990ab1ee38d490527c8a CertiFri.Stark.Statement CertiFri.Stark.Model.minusOneCol.match_1 +D d64c61ddbf9a9b0fe6064f731432e33ec7dac1e0c9d06012ae8f979ecd89a7c6 CertiFri.MultiArity CertiFri.Fri.foldRowMulti.match_1 +D d65b539d51c6485f31a2eae0445aba5ebf3ad0791b60e747a6f46fa0e814ceff CertiFriP3.Wire CertiFri.P3.Wire.Decoder.instMonad +D d66d09b8f9b5e98900136030e82358c409ff4af61eb61900776f18db417be065 Init.Data.BitVec.Basic BitVec.ushiftRight +D d6755ae49b88928a5b701c24e5b1b8cc6429a955f0a6bdc9964a16de286b25bf Init.Data.Nat.Bitwise.Basic Nat.lor +D d6805f9b5fd8d25592db4984629693919d381010616a584a7b5632751f95eb68 Mathlib.Data.Nat.Prime.Defs Nat.Prime +D d6861794076a014927562fdeed883231a55421ad4e293e0a62fc7b40acd9c747 Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.semiring +D d6b2ee626d1f7fdffb039358fe4d3aca611419257b9d877d9427f27a82154e81 Mathlib.Algebra.Ring.Hom.Defs RingHom.instFunLike +D d6b339d330e4faab21f4669381cf33eeb2572353cb915fe23437600c6b4e4b1e CertiFriProofs.Exec.Stark.SoundnessPinnedFixed CertiFri.Exec.Stark.nodeFromQueries.match_1 +D d6e9efe25aa1c04ad0e661780aba8042b5fb18a6740950062c6b29acc60f8b81 CertiFri.Verifier CertiFri.Fri.openingRefs.go._f +D d6fdaec392c4b04041fd11aea374d2f70f660f6f6d3ae1be1b3055706ee51e29 Init.Prelude Nat.instMod +D d7033e47069f8a21bc6ceebc38a82f981e70fedb018c9b7b53abc81a04c2e5c1 CertiFriProofs.Theory.Compiled.Read CertiFri.Compiled.Msg.points +D d735ae90405255aff58f1700dbcf1d8fe7d712376fb6c57ebd2a4757ca5e6524 Mathlib.Algebra.GroupWithZero.Action.Defs AddGroup.intSMulWithZero +D d7589563348e3ff7530a9ee9dcef99ec17f6a370d45ac5cd755f629dc1f794d4 Init.Data.List.Basic List.findIdx?.go +D d77f1090b05334d4956736fe8098c78f26123d7cc96cd1616673818a7e2bfc2e Mathlib.Algebra.Group.Semigroup CommMagma.toMul +D d77f8b93ef81d4e3925a1345d4cc3b5fa5eeeb391dab74d6e61fe5d783e72b77 Mathlib.Basic.NNReal.Defs NNReal.instLinearOrder +D d79245e8b10b122141a6e088c8d739835fdef04f0c1036b1eb9f442a2b255572 Init.Data.UInt.BasicAux UInt64.ofNat +D d79ca3805cc4ca5bd9a709f91b128da79ff2738e3d6864da6e7e8e4b06c3914b CertiFri.Stark.Admissible CertiFri.Stark.Profile.zk +D d7b0c129647d65715379e38366e493b2fc151a921e31d8d047921bae3ad99938 Init.Data.ByteArray.Basic ByteArray.instGetElemNatUInt8LtSize +D d7bcdb3108d09c61bcb97801a2a7832aab0f8d61baa07c5bd331487630604c38 CertiFriP3.Wire CertiFri.P3.Wire.uLEAux.match_1 +D d7db0647b06ac5d20c658fb21c537d5137387f02b927bfa52b6e59616ed3d3d1 Init.Prelude List.noConfusionType +D d7f68abf41bdc578f74ca5ddb3ee0809a934da9a2a9cd58b68d1fdbfad110081 Mathlib.Algebra.Field.Rat Rat.instField +D d7ffb121f406ba1875519d50538a992e4ae37e8afa0e05c4d19ca572383d2341 Init.Data.Int.Basic Int.sign.match_1 +D d82982ed8cfd7a7b19fb9cf8423935b9f8e8b649f26a8fa7b44ecad04584a536 CertiFriP3.DomainSep CertiFri.P3.Blake3Domain.domainFlags +D d868e86ff4b63636daf533d745ee6238e67eabe3a6793583f1a6b061c8081ce8 CertiFri.Verifier CertiFri.Fri.TensorChallenges.powOk +D d86fc3239a199b1775d2aa228066276b163a4f6ddd580e5fccd0aaf2d8de9a2f Init.Prelude rfl +D d88229fd9751c8fe7fef38274ef8f4f4060fbe838ffe149285a7bd8cfecdedeb CertiFriP3.DomainSep CertiFri.P3.DomainSep.instDecidableEqKeyedInput.decEq +D d88ea73466a12018e34e6462fa9bac64753fbf661841f2db9fda3d7d1228ea37 CertiFri.Stark.Statement CertiFri.Stark.Model.statementOk +D d890c8a674253073d950211de7d2ebda67b6e1e2fb42017d4b320369006705fe Mathlib.Algebra.Group.DivInvMonoid SubNegMonoid.toNeg +D d8d6c4a44b10f8ccb2d1388655526865253bbf3344594bdf2839a21350ec446d Mathlib.Data.Multiset.Defs Multiset.instMembership +D d8e20372567703df5175e1f65a7b49d97a07d9048564bae55ecb494e304483fb CertiFriProofs.Qrom.CompressedOracle CertiFri.Qrom.decompFiber +D d8e95403714e6176e8c401a7ae4d48f93c334e424d441722ee9084f6f943f1ed Init.Prelude DecidablePred +D d8fb6bd423084fed37095d9abf7803e3de24a61a4a51635ab2d505f77212bcba CertiFriProofs.Theory.Oracle.Basic CertiFri.Oracle.OracleComp.QueryBound +D d90e37a939275e40b0288be5b16e78d129630a25cc40829aa984c97acd52d19f Mathlib.Algebra.Group.DivInvMonoid DivInvMonoid.div_eq_mul_inv._autoParam +D d918000516e5c984454383415e90fc970bd73ab362ac30467e1cb6332c759356 Mathlib.Algebra.Field.Defs DivisionSemiring.toZPow +D d927ac858759857273e257a29319a0b0c83e442e2a5da44c21fba384802e2a0b Mathlib.Algebra.GroupWithZero.Defs GroupWithZero.toInv +D d93483215fb6721c4bedd251bcd6511ede19cac14b20817f4fc65af0fcf22402 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.mul +D d936934c6cf0857157c3993256a78b1dad52e8a109d9b2fcde7c9297e70dcadd Mathlib.Data.Finset.Lattice.Fold Finset.sup +D d95e0d01d73086b0b6ae1cca5db4e2c0d2c92e60a4c0ff426a3cf35dbf494e4e Init.Prelude List.set +D d95e442adb4f056d262c7433d30e82c4a2143ce1ae4e0203aa74398df60afe26 Mathlib.Data.Nat.Basic Nat.instLinearOrder +D d97397e031136afc16078dba93f18ef5a292c9624a6b817242cbb2b395282acf CertiFriP3.Pruned CertiFri.P3.Pruned.addSibling.match_1 +D d9922f91b26af063760f3c0d88fec299113cff481a3590b7a5e9b4fa0a6dc424 Init.GetElem List.get?Internal.match_1 +D d9a7720d2637a0890774776d7deb86901a2ed91321082d05ca20618646862ac6 CertiFriProofs.P3.ByteQueries CertiFri.P3.ByteQueries.tailQueries +D d9c0ce0668de8960d38bec3e2992bec90f08c0932152ce5f37fa3c2b282ae2ee CertiFri.MultiArity CertiFri.Fri.foldChainMulti._f +D d9ce5ca031c4fc57640a9b6966b7b155a21a0730ef95d77312797c1899661f6f CertiFri.Mmcs CertiFri.Dimensions.width +D d9fe5e287661c226848746ac33812b8866c1ab5c17cda83a03bb78d66bb1d144 CertiFriP3.GoldilocksExt3 CertiFri.P3.instDecidableEqGoldilocksExt3.decEq +D da105cff4ba8570e8e740e9fbeeb859b717b25b81ba34142dfb0d84a438ec6fa CertiFri.MultiArity CertiFri.Fri.checkQueryTensorMulti.match_1 +D da17c8b7d2806337c9e3411a2e91be0d10e39ce92c7d36da9043f9f8acd59e0d Init.Prelude Option.getD +D da190a24dd7f9a97628ef003944c019d9790fffaf8fa67bd98cb2b164b66dda8 CertiFri.Verifier CertiFri.Fri.transcriptTailTensor +D da489fdfa7cf410f6d718bb86c2b751af6893a2ff44bd6183d80a288938b3f7a Init.WF WellFounded.Nat.fix +D da720b1709ebafb09d094386a58d0348c7d30af8c4e529d0b68db97aa14d09ff Mathlib.Algebra.Ring.Defs NonUnitalCommRing.toNonUnitalCommSemiring +D daa4b5655640b8aafcdc0537b746b3553a415a97b66ddfd37f009082447f61c3 Init.Data.Repr Nat.digitChar +D dab65b9957f0f190d23ce2a92f17158c41d515630d266d96ace25c4a5f8fd68a CertiFriP3.Pruned CertiFri.P3.Pruned.Node.below +D dacda68626c43838488541c942a003f165930ed793f2b0e48dc8bc7805630bce Mathlib.Data.Finset.Max Finset.max +D dad0ffbd568a4868f88c12be328acabc796f7cfae1847e8f9050dbccb63e1418 CertiFriProofs.Theory.Oracle.MerkleFrozen CertiFri.Oracle.instFintypeSpongeAnswer._aux_1 +D dadf97df53beac2fc9764164e46fac42bc63d0c87ad60a1d1fb94b909bcae707 Mathlib.Algebra.GroupWithZero.Defs MulZeroOneClass.toMulZeroClass +D daf156b0f517fef0a51aab34a8a65c32ed91014582bfa8ead4ebdbd1372109f4 Mathlib.Algebra.Group.Defs AddCommGroup.toAddGroup +D daf5d2f3943409bac3d35845e3ffa7ab74c070501731efae03076c0acaa4d8bb Mathlib.Data.Int.Cast.Defs AddGroupWithOne.toNeg +D db138b0373f2b5906ce576039f993651dc322da15fc6b841bef9c5a03cba72c7 CertiFriProofs.Exec.Stark.FixedKey CertiFri.Exec.Stark.HashIface.ofRows +D db35a7e06dcf13f1f260b1ff13e9b8ed16c847fe13bd0955bd1eb5073c433ab0 Init.Data.UInt.Basic UInt64.decLe._aux_1 +D db4c4a83499c461e42fa340db97719b87b298553459beee6637fc32686661a3a CertiFri.Stark.Pinned CertiFri.Stark.verifyBatchPinned +D db5ea16c9bef30ff7b6ab3bc43043f4edc975781cb787c5363aa22c49fdf9c91 CertiFri.MultiArity CertiFri.Fri.cumLogArity +D db71c762e8cf22cf32da3e2e0f4965cbdadbb7d8f1bc75160ec8896b20623f7d CertiFriP3.Blake3 CertiFri.P3.Blake3.State.v0 +D db9745cc66ce8a7c157c32928fa9ab0fe88b0000d39685115c0bd780813e979f Init.Prelude Bool.decEq +D dba8f75b540086f3a8b68bd8b4078955c313e6037265e6449f787aea51a53cb3 Mathlib.Basic.Complex.Basic Complex.re +D dbc4fdfb482502ba2401e9eb26f1842aaf2be7dda92742320de42a70f7246803 CertiFriP3.Wire CertiFri.P3.Wire.manyAux +D dbca1978da628def96df7131f4457c8b754bb0f6d9338cfee8daa696112ea52a Mathlib.Algebra.Polynomial.Basic Polynomial.instMul +D dbcde20bb714b850803ee4ed8b4996a84897595f9c334cd90c4f533fad15ef90 CertiFriP3.Pruned CertiFri.P3.prunedMmcs.match_1 +D dc04f1f4b0d0d623cc434977eaba2c3e6e49582672e11d0bca1caa7c1601b722 CertiFriProofs.Merkle.Tree CertiFri.Merkle.node +D dc10f182b568a8a22f1270b57369b74aede5eeeec241490187bd3cb7091d7113 CertiFriP3.Wire CertiFri.P3.Wire.KeyCircuit.wireOk +D dc18ba0533139e9d51fa3477dc822101791e7bc2708b7de50577053b7285347a Mathlib.Data.Multiset.MapFold Multiset.map +D dc251ba9ff6634572a880693d4e3181c13cdd38a0b7a72837edb5a5643b95c49 CertiFriProofs.Theory.MultiArity.Fold CertiFri.foldRowMultiM +D dc3b79820e0f57f7e363f0659f6c656a0244752ff970b6e212b32d96ee44064d Mathlib.Algebra.Ring.Defs NonAssocSemiring.toNonUnitalNonAssocSemiring +D dc42bb31b0ca2edb2b29ba50660291223ed427948245a578b6641044f4962d53 Init.Data.Repr Nat.toDigits +D dc49fa1ddaf31b49084a0a852f6648920d1271db1d6e1dde7b8c14e2439b213d Mathlib.Basic.Real.Basic Real.definition._@.Mathlib.Basic.Real.Basic.1745762101._hygCtx._hyg.2 +D dc4ae1dc2ce17576f1ac2bee041388f6b91ef1d0cbd3ecff9569eae8a2e4065b Init.Prelude BitVec.toFin +D dc4c06270a46988afa45150bea5af3a021d35c182fe7c5a4f98e7bd592a28a82 CertiFriProofs.Exec.Stark.SoundnessPinnedBatch CertiFri.Exec.Stark.shardsCompPinnedSponge._f +D dc4e133a2044121a8f2b07018b35f94af7d6797d7618de8824e7daa587b048a4 Mathlib.Algebra.Group.Fin.Basic Fin.addCommMonoid +D dc838934f7e071be36dd26af3f8fa2e6c8a1b0fae4a48b359425183cc1a665fe CertiFriProofs.Exec.Stark.PcsSoundTensor CertiFri.Exec.Stark.maxWidthBound +D dc9d3ab74ac1c0398a03447c29f138ec039f9e735703957115410fafe70fdab4 Init.Data.BitVec.Basic BitVec.udiv +D dca000dd26125cb86d4954f6aba1cd819a2753cd30c1314c3a19f17ede71ecc3 Init.Data.List.Basic List.filterMap._f +D dca4ec68707e2b47d52a2a1fbbd8db7bed1e8501a50f15f7d5ef104013cf33c2 CertiFri.Mmcs CertiFri.Dimensions.logHeight +D dcb9899e51680fd116bb45527e8269fbf7df5f1b195308a62b65b16b42da6a83 Init.Prelude NatPow.pow +D dccf623e8344c325faad863a4f02c4c79305953a7ef9fae90050094c99e1bb34 Init.Prelude instHMul +D dd25951b5f449364c4cf9490b223bfd27ab5cccd04cc23911f0e57785a87575e Init.Prelude Decidable.casesOn +D dd33d71a576766ec156ec63e59383945fe81824509e66d31dae7aa1cde8585e8 CertiFriProofs.Exec.Stark.FixedKey CertiFri.Exec.Stark.matrixMap +D dd3edfdffa0efb729d703910b8f2e332c35478af3f600acd63fd3db772a87e92 Init.Data.Repr Nat.toDigitsCore +D dd45d963ea7bf9e2b778c9be61743476593321a556a235e8be04dbad0b17319c Init.Data.List.Attach List.attach +D dd52b89ec011384bb75369f75ef5e74cec2160aeb7e11f8364528cefc375d5ef Mathlib.Algebra.Ring.Rat Rat.semiring +D dd5d0fcdae17bab723817252045f3ff3b1e967cc9930e2380071f85342393284 Mathlib.Data.Finset.Image Finset.map +D dd6688603425399ba22cc416a50fc8debb081fd0031959e6c1b81dd58ad3093f CertiFri.Stark.Statement CertiFri.Stark.Model.sweepWeight +D dd891f4f795fb08b538bf147bc77210afcd8ba90417c1bd6f3b7898f445cd760 Init.Prelude Bool.noConfusionType +D dd93c6d4c1b8e3347dedf4515e1bef4ad0484690510f357a5b6ed8d137c5e11e CertiFriProofs.Theory.Oracle.Basic CertiFri.Oracle.OracleComp.QueryBound.match_1 +D dd95f42c9b0520fa1d24427dbcfc5e7c9232db34aa8e2d46043ded00697cc29d CertiFriProofs.Theory.Oracle.Basic CertiFri.Oracle.OracleComp.Outcome._f +D ddcdec3165eba082b820aa22f3f2fc3dfcf7d1222832668c538f9eba489b4bbd Mathlib.Data.ZMod.Defs Fin.instDistrib._private_1 +D ddd4bd1bfb4963dc1a0c1e6d5fa8c08dc87597fec7ce7563dfe1cd85cbade495 Init.Prelude HXor.hXor +D ddda36826011f52a59f2c9a7bac758dd48a425d20fe39de707a4c34467132671 Mathlib.Basic.Real.Basic Real.instAddCommMonoid +D ddea593dd55d53cc1da68a3efd1f4466c1c4dca4f4471669533bfd49ee7a589f CertiFri.Pcs CertiFri.Fri.claimShape +D ddeca31c155b556fc4a62651d376de8e1d66cad50c3d17460766122f4566d5e4 CertiFriProofs.Exec.Stark.ShardGoodPinned CertiFri.Exec.Stark.nextMsgPinned.match_1 +D ddfb82e990714621f5754fe4b18b70af22e64b816aa223093e963db3b1c05f27 Init.Data.Rat.Basic Rat.instPowNat +D de3d82f947c67f28d073d52f0303e17c4f21f8c5a466447b3db6d079560858f4 CertiFriP3.Goldilocks CertiFri.P3.Goldilocks.instDecidableEq +D de5174d3732b79bb4998917460ca50670b5861234c5f9e634a8a810d9182398a CertiFri.Field CertiFri.fieldPowBits._f +D de5282136acd7a8ef275a7faedc19fb56da45fdbbc3975c13bc9cace9137f67c Init.Prelude Subtype.val +D de53c1888b1806da9f364d2a63b08d623ae8e27afe60a7b44dfa2ff4b4612c0b CertiFriProofs.Qrom.StdEquiv CertiFri.Qrom.runWithOracle.match_1 +D de57ba81c86af12189ca3e51989777ece804567506f3765befb5b8b9b333328d Mathlib.Algebra.GroupWithZero.Defs GroupWithZero.toZPow +D de77a1fda627d382618f08813251a1d50b2af65c7cc6dc8c1745148b35b8c389 CertiFri.Stark.Graph CertiFri.Stark.RowValues.isTransition +D de90f071890353c639c7b232ed088f8cc2c778edb639175d0f7194e3864a16b4 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.zero +D deb273f436c46fc87dafc333bbf74f2a67b7d9c9984e67ec237697acc3613462 Init.Data.UInt.BasicAux UInt8.toUInt64 +D debadd5855c794c577966b485356020719174b7a41481dcd7feb67ea6759c2ca Mathlib.Order.TypeTags WithBot.instRepr.match_1 +D dec200d584a1689ff64154b5de035c08525d3abce96c1f499f50426d1f4ed0ca CertiFriProofs.Theory.MultiArity.CompiledTensor CertiFri.Compiled.MultiParams.foldChainMulti.match_1 +D dedc78fe17103f94a80813e56a762568260c759c88820d982229d67c09b320c6 CertiFriProofs.Exec.Stark.PrunedTensor CertiFri.Exec.Stark.restorePathsM._sparseCasesOn_1 +D dee5b34f97acff9e4d5179b6789f17bb4eff8d35a8a3395e0f9868d88322592c CertiFri.Stark.Admissible CertiFri.Stark.Admissible.preambleCoveredOk +D df03bc487a421840042ff15b2a3de62bbc503c02e678d4a479bc9e0cc493d99f CertiFriP3.Pruned CertiFri.P3.Pruned.ascend._sparseCasesOn_3 +D df7d4f8280d5f284eb84cc93b367e809d80df903f06859eb50646f49aa90d134 CertiFri.MultiArity CertiFri.Fri.transcriptTailTensorMulti +D df7e0fc892b23265fd103f9c7d65ff29f66a787fb8d6ab79eedb7b4cf3eb8f38 CertiFri.Stark.Statement CertiFri.Stark.Model.keyWeight +D dfa2e9da3c019338413b21435ee4c305442254a979997ea35a633655cbff9df8 CertiFri.Merkle CertiFri.Merkle.maxLogHeight._f +D dfb9fb99ff62e714749e9a97d2868dc755d15fb446226e4ae735ec123ac93a15 Mathlib.Algebra.Ring.Defs CommSemiring.toSemiring +D dfbe5f3132caa345d29c549e3c41f778e96e617d0f3c8ed643c26bc6b7127740 CertiFriP3.Blake3 CertiFri.P3.Blake3.State.v7 +D dfd96b08e734657774fe963dd635021af50d4f911ce82794763ce9a7f0a74a65 CertiFriP3.DomainSep CertiFri.P3.Blake3Domain.casesOn +D dff3674ef0d921501793c4a949ed82533a155c16f9e7175f82ad99105babc0f9 Init.Data.UInt.Basic UInt64.land +D dff7e54eaabc136e402965cd73ae7e0be6f65f882a48ecdd02592fa64fef2530 Init.Prelude Nat.decEq.match_1 +D e026c70d7d86e226171cd006225d64990038cd52b9f4126c078b45b0f692bbdf CertiFriP3.Wire CertiFri.P3.Wire.KeyParams.wireOk +D e04298518b84d610538063e5b3c6c93157855ac6e04db9035bfd207a5ac8d47d Init.Data.Rat.Basic Rat.instOfNat +D e0492a530389e505efe424d1910939c53ca062fc048377f60b1e1c35fbcb44d6 Init.Prelude List.toByteArray.match_1 +D e04b9e0abcf622b5ad0db06388b19f1610ec220c285732a75dfd55d55498117b Mathlib.Algebra.Group.Monoid AddZero.toAdd +D e0553386694c233a5b4a5360179a15b7cc1c6380ba052090ca048ade96cbbfef Mathlib.Order.Lattice LinearOrder.toLattice +D e073f18bae302664b44665da44ea1d722a261647e3372b4f61900a2d1283c478 Init.Data.BitVec.Basic BitVec.umod +D e082840ae4e2b1e81b33612187bd29430a2b3719a48c2beb3b98fa5d271057ea Init.Data.Function Function.Surjective +D e09cffe8666328eefe52ddf306763b711b7105d65e48a2a5720f1c7d60be1d46 Mathlib.Data.Fintype.OfMap Fintype.ofEquiv +D e0b343220f76114108a2e5b05357103a5ee291e87e64a6002e9bec07cb69c359 CertiFriProofs.Theory.Oracle.SpongeCommitted CertiFri.Oracle.spongeLogHasher +D e0b39919be60a0c0d9013d68bf9eead7f4afada13f4b8c08585690679b49150c Mathlib.Order.Basic PartialOrder.lift +D e0b82a658a68fae1a22bfb88a46c1b802bc57dda371f2f3f8e697781753f6540 CertiFriProofs.Exec.Stark.Preamble CertiFri.Exec.Stark.Bounds.shards +D e0c98b4daf6d6c896f6cd98ffef79ace6be9ef552cd999f4aa868b9cf955aede Init.Data.BitVec.Basic BitVec.instMul +D e0d3b3e59d2e8f82bd87dedd48d0d202dcf6c1bcaa07c62f80941aec40d8ff78 Init.Data.Fin.Basic Fin.add.match_1 +D e103257a3de6b15ec36790647f6dbd2b9b0cd89100044a9f9ad3da66c5f0ec8c Ix.Aiur.Parameters Aiur.CommitmentParameters.logBlowup +D e1083f90e01da8b2350c614083a81372c95ee2546f4f3c39d5a75f478fa6355a CertiFri.Stark.System CertiFri.Stark.Circuit.lookupGroupSize +D e11b04dc603f16f635d9e08e1872ce5d5944a04b140296c9474c1838da56d4d8 CertiFriProofs.Theory.MultiArity.CompiledTensor CertiFri.Compiled.MultiParams.arities +D e129c942b6eab34b5fadd974a1c2575f08545fbac67feb71fd184650ae9d5921 CertiFriP3.Wire CertiFri.P3.Wire.encLE.match_1 +D e1410d6844bf939439276febc6397a672623593f14e6d5b7fee72dfbec87ff29 Mathlib.Algebra.Group.Pi.Basic Pi.addCommSemigroup +D e1565c64e5fc0a9f13e1e1de7143ab810459490940933ace4adf3b675eaeae41 Mathlib.Logic.Equiv.Set Equiv.Set.univ +D e160c8be2b9134a24b8aec2d49fd3efa043aca2d7e3ee9456c52fb62a9f8e7f8 CertiFriProofs.Theory.Stark.Graph CertiFri.Stark.Model.varVal.match_1 +D e192392d9305337f7bcdf5ada22fbc8cd4cc23b63ba08ffe6f775d73be33eb7a CertiFri.Stark.Admissible CertiFri.Stark.Admissible.nodeDeg +D e1955ebfdcfc9c869d62db50a44824ca76b8789a4253c96b1df23006c3e82606 Mathlib.Data.Fintype.Defs Fintype.decidableForallFintype +D e19761ae36ac2d292947499d3945145bd63d57be6d28d58468f1ae4e28d2f175 Mathlib.Algebra.Field.Defs DivisionSemiring.toInv +D e19a671327400862a298a500cd129a426267e32a74f2d8dbe9711b99a2d129cc CertiFriProofs.Exec.Setup CertiFri.Exec.digestsIn._sparseCasesOn_1 +D e1b0c885c4a737aec7d78cd4402ebc8e9fcf8c1dfcb9221ed749cfa7a9c9ad6e CertiFri.Stark.Statement CertiFri.Stark.Model.chansOk +D e1c10a818254c73279b9ddae7cc8bd45b38729d405503c59030bcdd327ade3e3 Mathlib.Order.Basic Function.Injective.partialOrder +D e1d6322914c7aa1301fa743ecb77fe6f5a0e8ab23de6b0129686bdc0eebda63c Mathlib.Data.Int.Cast.Defs Int.castDef.match_1 +D e1db6e05155a649b419b4e9a37dc16731f6526ef4f7bb8f8ff303bdd9d7fa396 Mathlib.Analysis.Real.Sqrt NNReal.sqrt +D e1ffcaf3a6b85f2a5e1f7738c28dfa645a805b61cfe5d0167a3738c893888010 Mathlib.Order.Interval.Set.Defs Set.Ici +D e231227468249a4a578273e1b019d41d6f38bf889e3b031ce31983275da65e3e Mathlib.Data.SetLike.Basic PartialOrder.ofSetLike +D e2623408c88a755604fed0b4a4e0cabb28af974554f382e6318e5f664250430c Init.Data.UInt.Basic instDivUInt64 +D e28edef038e7c0aa6b2ba06294e3e5bb16efb1be96fa6daf962a1d42dd15a697 Init.Data.Array.Basic Array.mapFinIdxM +D e2a118c3c53bf5f37662d75651bb6a97a599a7523354474edf0c1606d8dd21a6 CertiFriP3.Wire CertiFri.P3.Wire.encKeyParams +D e2b14a471233dc3e25223ae22a33f2a591b89d17c4004d3810d564247929aec0 Init.Data.Array.Basic _private.Init.Data.Array.Basic.0.Array.isEqvAux.match_1 +D e2c9d772ac1d22675c556cc116d3c8c31e73c5627d01723b9ef3f879613a7a63 CertiFriProofs.Theory.MultiArity.CompiledTensor CertiFri.Compiled.MultiProof.siblings +D e2cd7ecdddca021ee6fa041d3a6b8a09e6b92face1c9c76e9b936cf6023a20d4 Init.Prelude List.concat._f +D e2edd08cf0fe640b841ae98edd0d58bff5d04277f27b3ac8f600735b5d36e19e Mathlib.Basic.Real.Basic _private.Mathlib.Basic.Real.Basic.0.Real.neg +D e2efcb99cd0714cbc9df4582661bd11409121f12b3e80dd8b230d6317d07990b Ix.Aiur.Parameters _private.Ix.Aiur.Parameters.0.Aiur.meetsSecurityFloor.match_1 +D e2fc495997649cbcdd82063133db2e0128b67efba6fe748f70dee8bee1d686e3 Mathlib.Order.Lattice SemilatticeSup.toPartialOrder +D e2fefedbd222a72eb96827f8bbf5b7bd9885f94d228ab92ed8359d487cab4820 CertiFri.Field CertiFri.fieldPowBits.match_1 +D e300ee8ef64782cc4faf487c547e9dc27aab12642e91f05542220dedc592d6c9 CertiFri.Verifier CertiFri.Fri.ClaimRef.matrix +D e34787e33a7895ff0e085fed61a04aff6a6d559cc6c0a06d3b66244180a92b02 Mathlib.Algebra.Field.Defs DivisionSemiring.toDiv +D e355fa48d13aab005d0825804e2015d371326dcbdc7e233762572821724bb0cb Mathlib.Algebra.Order.Ring.Unbundled.Rat Rat.instPartialOrder +D e370d6891f6cd2d4702df1c934ec1af51a6a5c713d30fa6d88f0933c46057c11 Init.Prelude minOfLe +D e390fe93771fd6ab13cc607785c2653e678196961c3ff1a63d0a28e6e6fbd438 CertiFri.Stark.Statement CertiFri.Stark.Model.pairCol +D e3918fd6418d988922a82e33a2e851dec5d6fbd020635fd138bf82c0adc6fc11 Mathlib.Algebra.Field.Defs Field.toRatCast +D e3920f619f4a7c78e23ab2b5d9ec4f71fe3b8e335f1c6f372856d67ffc1c9f5d CertiFri.Field CertiFri.fieldPowTwo +D e3d7cadd456bb2f3dba7abfd884850ec18a94b58a8345f56f2e4c126e1dfe533 CertiFriProofs.Exec.Stark.AdmissibleSound CertiFri.Stark.BatchBounds.toBounds +D e3ea1cdda7ededf99c1cb8d8ae0468ebd15fc6a037d61194deb0d707cf6ad4de CertiFriProofs.Exec.Setup CertiFri.Exec.modelParams +D e410ba68c48f383f93513e4620214c3a48bbe7651fb49de62b43abfdda071457 CertiFri.Verifier CertiFri.Fri.verifyFromTensor +D e415a3af8f5cda1d54b2cdef55ebc9f4b5c0711b91f05b9eda75718c10cbbf18 CertiFriProofs.Theory.Compiled.Tensor CertiFri.Compiled.Params.foldedTensor +D e43f13380ac219d4ed4f11a3245d3248b60acf6b52f0d6de45f295377e02a3fa Init.Util panicWithPosWithDecl +D e44291c309734d793a022be745684caee5de6350dee4d5520d1db1274efb2d38 CertiFri.MultiArity CertiFri.Fri.shapeOkMultiArity.match_1 +D e44fdea4e15ba9e1043adc571d3e0cc3ecb4e435995818066637c08dfe549d84 Mathlib.Algebra.Ring.Int.Defs Int.instCommRing +D e4837963bf8addda3ce8d2d0f17c706181fcc6a1c43b84692546f2baf6722dbb Init.Data.UInt.BasicAux Nat.toUInt64 +D e493357cc103d891ddf37d436b92221e75a47fe54038cb8897efc6dd04358d81 Mathlib.Algebra.Group.Monoid AddCommMonoid.toAddCommSemigroup +D e49529a0b72f61fe1c014316f25a2ac7719b223595abdf9fbd960ef3df3df0d9 Init.Data.Range.Basic Std.Legacy.Range.instForIn'NatInferInstanceMembershipOfMonad +D e4ad8b1ddfe15c49ab07133e17bb142adf5ba22cf7eb7297d45d0ca579522015 CertiFri.MultiArity CertiFri.Fri.reducedOpeningsTensorMulti.match_1 +D e4bed16754255ebacba3fc6a9b46537187c885c547a6e2dd9799f8c426aacee3 Mathlib.Algebra.Order.CauSeq.Completion CauSeq.Completion.instMulCauchy +D e4f0f54bdec6112d0ea310a9d724c8886dca1d814ab99e45599a54e645c22421 Init.Data.Rat.Basic instDecidableEqRat.decEq.match_1 +D e4f9ceda8f61d658225d83849e6175b145a1411ea5d4919fc148633173e72f41 Init.Data.List.Basic List.decidableBAll.match_5 +D e50a3bca803eabe996642f8f5718a866383cedf98d14ff6584a4421aadbf4208 Mathlib.Basic.NNReal.Defs NNReal.instSemiring._aux_6 +D e51860354288bed39341aaadd96f0bd4851b9d60ae25df7bc660bb28f3d10eec CertiFri.Merkle CertiFri.Merkle.groupRows.match_1 +D e5216576a8ce5fcc6e67bb6c223c1022f674b819fd46052acbcf79c37e8f98b0 CertiFriP3.Pruned CertiFri.P3.Pruned.ascend.match_6 +D e5485f2494a73fa604c6ac419c16930c1cf91f3c688fb019c795d2d67fd37c41 Init.Data.UInt.Basic instAddUInt64 +D e57cee7ed327ac6fb2904af3b931b546577f8cd1826690b3df5d0e907079384c Init.Prelude instDecidableEqFin.match_1 +D e5a8d2a1ed34b4b9a42baa14ca3ea98935ce86fa7f1be00780a6e8cd8200b482 Batteries.Classes.RatCast RatCast.ratCast +D e5b2d3a0d953e6a98f01d93b7fe844df7c6e096c75a8b2f60c7cb1ab9ab0fb13 Mathlib.Data.Nat.Find Nat.find +D e5c11c633eb01c2b5d597a564863eab1f525416013171ca4b5072519a7b6adb2 CertiFri.Verifier CertiFri.Fri.TensorChallenges.schedule +D e5f35e3c4ee4e4477b9f3c570978a7a2ad4ecbfe02d8e762548e49ad8ac1a11f Mathlib.Algebra.Group.DivInvMonoid SubNegMonoid.zsmul_succ'._autoParam +D e5f5f8f05ab6e7dd18b6a3b40dfdb6ea046525ce2f0bff46332e422d62d6aaec CertiFriProofs.Exec.Stark.SpongeGoodLogTensor CertiFri.Exec.Stark.deriveSpongeSteps.match_1 +D e5f81935e2d944a46457c8b799280560d2025060a4cfaf25b45c9e217510876b CertiFriProofs.Theory.Compiled.Read CertiFri.Compiled.Params.leafWidth +D e6020ba2fa50feacf45ccc56a6223b956fe6a6314ffd9d56371b9b0cf5e7f9c5 CertiFri.Stark.System CertiFri.Stark.BatchProof.proofs +D e607a0ac555110fb72edb3e24c4c99b9ce66d27378c6b031463feac0fd72230f CertiFriProofs.Theory.Oracle.FiatShamir CertiFri.Oracle.Transcript.msgs._f +D e60ad7883ba36425b33fa92e0277f094ad0d3cefb142a5e53204f290b348b76f Mathlib.Algebra.Group.Monoid AddCancelCommMonoid.toAddCommMonoid +D e62b88e2f6e50e9df2d26a32f7c8e19d4ca222083391e4f123ffc23cef394f35 CertiFri.Stark.System CertiFri.Stark.System.maxLogDegree +D e63b1ae94266a6e7bc5f5ce1d430c97376842ddb8973691c49168e592bcc7a16 CertiFriP3.Challenger CertiFri.P3.ChallengerState.sampleExt3.match_1 +D e65dd5d81406a289ad7e54c239859e0d1f6ee43f1778e0d76e5a712b4d4b0919 Mathlib.Algebra.Ring.Defs Semiring.toMonoid +D e664f3009c293362cad6e144f292246439786efd48e5b6940d75a35a38a2fada CertiFri.Stark.System CertiFri.Stark.Proof.active +D e674dbd32e5557b75c2b91c14e4a2cbc87e5982a2874ce1333900df73991d0d5 Mathlib.Algebra.Polynomial.Eval.Defs Polynomial.eval +D e67a32a014a75e5f62dbe19f3e95e3f5dd6858582f1cdceb1364e0e65ef2a18c Init.Prelude HSMul.hSMul +D e68726400cc8cd50009d5adff77fe91fc9014110c8fa37d3a9d4e6abba1dbdda Mathlib.Algebra.Group.Monoid CommMonoid.toMonoid +D e68ab7101c32a1ee5e2db030265853a40cd2d157936eff031452d0026e9ab6d4 Init.Data.Int.Basic Int.decEq.match_1 +D e6bb2a76b1dab874692cd0ae4419d1f5210e384757bf929ea03a9255ee890445 CertiFriProofs.Merkle.Tree CertiFri.Merkle.Matrix.row +D e6bd75f4b9854dac91cc0c0c329e277cc16c9519945959fe050954ec0c997424 CertiFriProofs.Theory.Stark.Logup CertiFri.Stark.Model.coordOne +D e6c410676e888a462a5b141f506814a6787e06c5ba47ba0370bf950e28455b37 Init.Prelude instDecidableOr +D e6d52926ffd989bc53b285851f30156c68b865abe98a0eba1a27b22de3ca579f CertiFriProofs.P3.GoldilocksExt3Model CertiFri.P3.Fp3Model.extData +D e6f00a7eccc9a6c50796ae10c16a6db7e2c7bf85fc77191afa01677ae8b76fd7 Init.Data.Array.Basic Array.instInhabited +D e708e3dcef1eb663e92c79d99893bc733d9d82ef315a0138297de3e20dfeebdf Init.Prelude absurd +D e71c4667bc8f62e9b76bcaeb641e770bd568730cc003b34725198ce666508ecc CertiFri.Stark.Statement CertiFri.Stark.Model.circuitWeight +D e71edf2a696465aa82bf4116e27c5c88f711abcf60f048d85d071fceabf6a03f Init.Data.Option.Basic instMonadOption +D e727091eca0238bc4f34f49fc8aae7cca639fdfc43963c5d40b1fd9fcfb6b628 Mathlib.Data.Multiset.Pi Multiset.Pi.empty +D e73b6850f1f97c7db7666301372337e042beb4ce3fcc9c6e3c4ac989db94a22d Init.Data.Ord.Basic compareOfLessAndEq +D e7563da860ba63805d7b61ccf2548b380a8cd7f1a8d453bfad4466615bb6057f Init.Data.Repr _private.Init.Data.Repr.0.Nat.toDigitsCore.match_1 +D e7577158bdea31d7ad8ba3b81c97d293ead78b946584d24229b595b95420b12e CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.add +D e75fc828a311936150dcdae4ba22c20764d629c32c6633c17e86209eb6d0a55c CertiFri.Stark.Admissible CertiFri.Stark.BatchBounds.lookupRows +D e764088d1cf455933894274d0004cefe4ef0981b3d001378f8757612403338db CertiFriProofs.Exec.Stark.FixedKey CertiFri.Exec.Stark.fixedVal +D e7725cab3fb2344b482fbd72c3a7533823b4b827ee1838f9076cb100b1c221dc Mathlib.Algebra.Ring.Defs NonUnitalNonAssocCommSemiring.toCommMagma +D e77f031f6fa686347bc03fa2d87e35b222a255dbd3182fa16aef001f097298ad Mathlib.Order.Hom.Basic instFunLikeOrderIso +D e7aacef37a26eaca8cf00b1e21c5b940989cb888252d78fed2bac3de79be04c0 CertiFriProofs.Merkle.Tree CertiFri.Merkle.Tree.nodeFrom.match_1 +D e7d2359ed740dfd4255524361f5bf4759ccda770428612e4b34b2968ed342b96 Mathlib.Data.Multiset.Defs Multiset.decidableForallMultiset +D e7e4e4f0ebe36749ce16975ed72182600c13e4effcb10de1746ad978791e7202 CertiFri.Stark.Admissible CertiFri.Stark.Admissible.lenBound +D e7e6dd9658ee2d33344ab1ea11386411d81a4068a34fdbd79c424ce36c12d5f9 Mathlib.Algebra.Polynomial.Basic Polynomial.sum +D e803f6b2cb1ebf91dd54eb9bd639a3265c9e9f41bfe473793c76a42dc6e28286 Ix.Aiur.Parameters Aiur.provableUdMillibits +D e80bb3e3adda954ccdc3baf2c38dddd60236e0d1bddc48592b1e6e7179ffb89e Init.Data.Array.Basic Array.mapM +D e8146193ca8e7393a4290a6084195b6505e6c76890ff98a4f21621f46dd76866 CertiFriProofs.Exec.Stark.JohnsonPinning CertiFri.Exec.Stark.batchItemsJ +D e81b388dac9bd3ac15df8030371be521955cda7fee4fbd32e7112f6e6ca88d86 Mathlib.Data.Multiset.Pi Multiset.pi +D e8218f35f770c314d137f03c942a870c6e556505718ec31eeb45edadb6fbd85e CertiFriProofs.Theory.MultiArity.Fold CertiFri.foldRowM +D e822d754106d014082696c99314503572a151f5d785ddff34b3f5687ca79e28a CertiFriProofs.Theory.Oracle.Basic CertiFri.Oracle.OracleComp.brecOn +D e82f12e3d3bfa8fe2c4fed988fc9fa440ee2d72e3c7d238753d16caa9f38112c Init.Data.List.Basic List.filter.match_1 +D e86ae3913dc175958e5ef48e65b198cdf0208d8d43772b5825faa560201e0d94 CertiFriProofs.Exec.Stark.FixedKey CertiFri.Exec.Stark.nodeFromComp._f +D e8acc5d12be6354b4db77bb8d86b469ce873b9ab5c4d3a305685978291740658 Init.Prelude Array.push +D e8b5606985fa735114534c45ccadc9df68ca58f3d35620a497f33729b9489a02 Init.Data.List.Attach List.pmap._f +D e8e6ec2348905acb9fc956999863a474122bf89e9447f032102dee4341381d42 Init.Data.BitVec.Basic BitVec.instAndOp +D e90d86467ab0a7aff2c358661214c090af88e196f45deda736606ce651649016 CertiFri.Merkle CertiFri.MerkleHasher.compress +D e9538967b58aca75c3eeb4e4308fab94c62566d332e17c1cce4c593c92f0c432 Init.Prelude Functor.map +D e970ea7203e9457c9ea182f126d75014c5de995963e39d6cae26eabc41502e77 Mathlib.Data.Rat.Defs Rat.addGroup +D e97b22e21e24605f7d9b4ffad870e704ac261f821ee6e1ff25fe9da6a706a7b9 Mathlib.Logic.Equiv.Defs Equiv.invFun +D e98565f4421f9fa1d297eaa10e0cf08243f9e86c475dc72945888fc9146777f2 Mathlib.Data.Multiset.Filter Multiset.filter +D e9a71b4dafb57c3b15e64b654c91fef076979f025c930316d07ece257f1f10fd Init.Prelude Array.get!Internal +D e9b532480d3d00fa720494e24350ae1f3023fba3c43d8887cbfe935510c8eeb6 Mathlib.Data.Fintype.Basic Fin.fintype +D e9d59ea12105d45be44f12f193073879eb80777b751ff4ba4a1912ebae77b250 Mathlib.Algebra.Group.DivInvMonoid DivInvMonoid.div' +D e9da9538e16000623abd2b273247c26fc5824eb7eaa58e03c7c9c622c06e3b4b Init.Data.List.Sort.Basic List.merge._auto_1 +D e9e06714f87190c2386ee3eda7a30e7b43f7242937f3b93c8217ba24d020e83d CertiFriP3.GoldilocksExt3 CertiFri.P3.GoldilocksExt3.instFieldOps +D e9eb6f82be17b170f079f118ed8a65dd4875adb899506c65a3a2f57dfa2615b1 Mathlib.Algebra.Order.Ring.Unbundled.Rat Rat.instDistribLattice +D e9f5c1982666c0e52cd2ebd7fdd17454c9efc41a99fade0656b26fd0e002bca1 Ix.Aiur.Parameters Aiur.FriParameters.numQueries +D e9ff74968d688030d48a0a65353addd756f2db20f121f4b874f32b7d902baed7 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.embedHom +D ea526262969b6afd1337b4d715eb00b13d120d3f1b2f4f78a35f10ae38a710cd Mathlib.Basic.Real.Basic Real.semiring +D ea6d0ec6fb543f6559dcf4566632198fb9777fac51955f5e9be95f0d4b7a1f65 CertiFriProofs.Exec.Setup CertiFri.Exec.inputHasher +D ea7f2dbf93720244bc76365ab66d05a5f7ae419a4fc400e312f43c8b37f23bb5 Mathlib.Algebra.Group.Pi.Basic Pi.addSemigroup +D eaa5ba118d9c80c87fc327c996943d86bc7af22f9393ab2fd6455d4c4cd75b55 CertiFri.Stark.Statement CertiFri.Stark.Model.systemArityOk +D eaaf8f78a677bf647af4c92f74aea3033eb2ec517a394189706f43b817d9108f Mathlib.Basic.Real.Basic Real.instDistribLattice +D eabb06bf725fcb1a62d052ca1b8a58e3151db1292e03a4a3375165ce8dc837bc Init.SizeOf SizeOf.sizeOf +D eac0ad16d63bfeafca1c1e3f0de39a3410aa26b5bd663a6a95c423fe53af8d54 Mathlib.Basic.Real.Basic _private.Mathlib.Basic.Real.Basic.0.Real.lt +D ead080539162db554f372fc11101f9ac1fb7dfcfa2912b6e0b426485d2579b85 CertiFriP3.Challenger CertiFri.P3.challenger3With +D eaf252f7ebb9d2df62486f28e46188692bd9943aaa961e6abf0e64cab998fab9 CertiFriP3.Blake3 CertiFri.P3.Blake3.deriveKeyWithKey +D eb0e23dd61010ad7a705443e905b64c4e5eaa752e414188b35c11f23bbb3a758 Init.Data.Nat.Bitwise.Basic Nat.shiftRight +D eb12783cbae502e3b1e47ceb350edc562a7c3b0656cfa01e682476f23d704ef6 Mathlib.Data.Finset.Prod Finset.instSProd +D eb3c7c57c5161d2417421926e7d2f3b3e85ac700f2b840831a95c947fcf7b5cb CertiFriProofs.P3.ByteLinkPinnedFixed CertiFri.P3.ByteLinkPinnedFixed.fixedCheckOf +D eb4303d43369200047960ca6999c2358399e5f57228cf22ec39a39680ec15c88 CertiFriProofs.Exec.Stark.State CertiFri.Exec.Stark.chalsOf._f +D eb657a6b36e1587adb167481c67044f22032c6828824e5d911e291900bf6298c Mathlib.Data.List.Sigma List.dlookup._f +D eb738754cc588f99bf87fb9df16e70294b7fcb2d1487e3d1269e08670ad3fd3c Init.Data.Rat.Basic Rat.casesOn +D eb78777a5a0334f7a6e23b7ee87c4c36917d92ba2b6e65882d51d21610d35bf5 Mathlib.Algebra.GroupWithZero.Basic GroupWithZero.toDivisionMonoid +D eb79c110b81dd73a6df3fcebf3111ce6a5e3bda87f0c00c097699941ab26e008 CertiFriProofs.Exec.SoundnessSponge CertiFri.Sponge.mapHashToSponge +D eb979f1c259af21d117dabae677171606ce95ea9e5b4b8628a39ba163d5eca68 CertiFri.Stark.Verifier CertiFri.Stark.mainChallenges +D eb9fb2902d72fa3b91dce2963eddd7d940d0f511b802f9f13918ce4324378a26 Init.Data.UInt.BasicAux Nat.toUInt8 +D eba0149f0b51fa5cfec5fd79a9f02340d6eaeee8da07664e60d926de051a35d0 Mathlib.Algebra.GroupWithZero.Defs MulZeroOneClass.toMulOneClass +D ebb0e3814ab5eadfbbf744ee276bf4219723a461f4ca99e9c3a2be1379cc9191 CertiFri.TensorBatching CertiFri.Fri.reducedOpeningTensor +D ebb6d4f3ad3109f71824b35ac25849120eecfa16c647b511db841a5cb0d72aa5 Mathlib.Data.ZMod.Defs ZMod.fintype +D ebb89d65800d97132391fcadf777db221f108a5f9c5d8b903395ae9ab2333c34 CertiFri.TensorBatching CertiFri.Fri.sampleExtMany._f +D ebf99dadc99cec5390b4f4dabf810ba98b0e3d08e9f963e997c948899775751b CertiFriProofs.P3.ByteLinkPinned CertiFri.Stark.Profile.pinnedBatchCheckOf +D ec1bc1a20ca0eb5114692550f91670bd75e82fa34ae2b54477e0d2d1012e96c2 Mathlib.Data.Int.Cast.Defs AddGroupWithOne.toAddGroup +D ec3e53c82eb1e710afb64dbe8de59538f523139515b637f47c0afd224e895484 CertiFri.Stark.Verifier CertiFri.Stark.shapeOk +D ec41243fc572b7cbbae0797e2684f6c820a71f12f7c23bd7929c844852077dd5 Mathlib.Order.Basic Pi.partialOrder +D ec435e116069052b76be57552a9acfcba1c3b2c3fe4dc4610a9255d6e255e380 Mathlib.Data.ZMod.Basic ZMod.val.match_1 +D ec6e541e1155beddbdb705f20e8c9456f4d5c8a772ac7255cbb9b624552c0d27 CertiFri.Stark.Verifier CertiFri.Stark.defaultTensorChallengeCap +D ec70771d44de1a872037c301b48a5b65e8d583c3732787eb2bedca811fa3b0a4 Mathlib.Algebra.Group.DivInvMonoid SubtractionMonoid.toSubNegMonoid +D ecaa098b4529a6036573a2a07388840170d3d9f89f183eb7ec11eaa6250604c1 Init.Data.List.Basic List.erase._f +D ecd673fed28815656d316a6f95c46065b0ed27e0f7a2ddef75b990c8b3afead8 CertiFriP3.Blake3 CertiFri.P3.Blake3.Block.m4 +D ed08771e243691ac3fb2fb1fed26998025751995d69b10a5c0f5496d76c404ce Init.Data.List.Basic List.range.loop.match_1 +D ed1ba78b1913075021c41d20e444f78c1f8704a3e5d4837ff1639c347e719455 Mathlib.Algebra.Group.Monoid Monoid.toMulOneClass +D ed4677f80479ab5e6e2cc49f48d94f8585aa736cb1b4c3c3fb16c086a85afc45 Init.Data.UInt.Basic instShiftLeftUInt32 +D ed6d6748ac3db6732fc5bc47aa19d0ffb397e8516428747f6fb860e43ec3778f Init.Prelude Nat.beq +D ed8dfb7d996c5e463122cfd66c7e66b7cea52da231dc9cb2323b49d67b669824 Init.Prelude LE.le +D ed9dbe4ad1c083b89877be709c61bf9d7d03bf866e5dba8a599d93a4ce2acbbf Init.Data.List.Basic List.replicate.match_1 +D eddfa3d1e10ce01f89788191a599602c44df2026beb93d74fa806929c4eeeddd Init.Prelude Nat.sub._f +D ede6353f6b904f3789bbdbfd6d9b4af37fe5c68189abf21bdd0a2472e902bcba CertiFri.Stark.Verifier CertiFri.Stark.activeMessage +D edf303f6cdf97ec746511edb7bc8fa450fe40227eded8e4fe3355ded7396be2e Init.Data.UInt.BasicAux UInt8.toUInt32 +D edf53113755c40f0ddd22b9b7f9758f0547a929063d6082b59d290fbe197691d CertiFriP3.Wire CertiFri.P3.Wire.feltOfNat? +D ee135bdc47c88d677ae577b0ff03a18463265d4e4dce3d18c054bfc093fb309b Mathlib.Order.RelIso.Basic RelEmbedding.instFunLike +D ee3c16f6d2cc7c952967962dd708b02a22dbeba1dedf23e05e97f2e31d7acac7 CertiFriP3.Blake3 CertiFri.P3.Blake3.flagChunkStart +D ee44ad8b2828b9d02dd9e56ae3ef629b34538f26f898ad4f7915f462dc3cf923 CertiFri.Stark.Verifier CertiFri.Stark.Selectors.isLastRow +D ee556dd3866b7f55ba1b34ac3462738eb8539255a669c38f28a818faa94bd6eb Mathlib.Data.Nat.Cast.Defs AddCommMonoidWithOne.toAddMonoidWithOne +D ee58685e60e624f87229bbab429e8ceca0cb266cc7ccf83873c8bbda25887060 CertiFriProofs.Theory.Stark.LookupRoles CertiFri.Stark.Model.senderOk.match_1 +D ee5963e5c05e4c1ae90c02c10ab802b93df457907dc0e2e64382c737125069aa Init.GetElem Array.instGetElemNatLtSize +D eeba86309ad5f3f45a8de440f7943830e33167762ffda5cde81a5cfaf39f88b4 CertiFriProofs.Qrom.CompressedOracle CertiFri.Qrom.fiberBad.match_1 +D eed6069dc073a03801d5a99b07e65da540022b4e119f99e61a52e67fe690d148 Init.Prelude UInt32.decEq +D eef4b9f07ebeeef31ef0a0320facc0d848f86a0d48a5756117224b8be95ea668 CertiFri.Stark.Graph CertiFri.Stark.Graph.sweep +D ef0b51a992849e7e9ad5c3a1e14cd488321e512d75fe612053e7d3da1de6d911 Init.Prelude id +D ef1800ff40037fc8e807cd3d3982cd7d0596a909ae1f801a7be7fbb62c95392c Init.SizeOf Array._sizeOf_inst +D ef4539fd07e59a068a3fdfb0d2c828aa7736f4ba5fac093fc444180a5222ff29 Mathlib.Order.Defs.LinearOrder LinearOrder.toOrd +D ef4a196cfc86fcb789674d7fc7f90487eec6a1f21e989a2d370092084df00b02 CertiFriProofs.Exec.Stark.PrunedTensor CertiFri.Exec.Stark.mapM_oc +D ef57f3f145181e882a75892c4478dec5e2c011ae4a33a5a6f96f28dcad30542c CertiFriProofs.Qrom.StdEquiv CertiFri.Qrom.coInit +D ef62810ed81b9424b67c8e30965a5935ed5cc055f3d495543b6f26cac24fc0db Init.Prelude cond +D ef6c6bb6a5b771f5ba60ea38ef6de7e3eb58898af5e730f701bd76105b93fa2a CertiFriP3.VerifyBytes CertiFri.Stark.Profile.pinnedPreambleChecks +D ef6fcf496150ae22981a48e06c2cd4b08bfa2809d690d44bb41379f587a67b7c CertiFriProofs.Theory.Compiled.Read CertiFri.Compiled.Params.batches +D ef7671e7539b6d18853217c2e6714008d3f8c152a8dabc8ae068a7c0bcf40c2e Mathlib.Order.RelIso.Basic RelIso.trans +D ef7e628f7686211fd6d6756efd064ad670d8f7d8edf0fdd4a67a124b4e888b30 CertiFri.Verifier CertiFri.Fri.numRounds +D ef8317c44fa5bac7a77f7e8688c245aa0350f870cf13ed135bd84aeed6b6d6ad CertiFri.Stark.Statement CertiFri.Stark.Model.oneAt.match_1 +D ef8ac007015f77cc3c711e72c21005bc6cab4f78c54c2ade9d0dddfa88308b11 Init.Data.Nat.Gcd Nat.gcd._unary +D ef96d9420cbb4029c0e17e33c6c2a477bb54b12dadd9ee91da59ebf5bed10847 Init.Data.List.Basic List.lookup._f +D efb4658570b5ac4c18f5a3e7f6b851ef08ca0b94b9d971f3ff1a745e78d8fc80 CertiFriP3.DomainSep CertiFri.P3.v6MerkleLeafKey +D efd744190018b1eeef045ef7d8eece49954b592a8187da5b8601f132d250f3cc CertiFriP3.Digest CertiFri.P3.Digest.toBytes +D efd85ef60ce15f896065080a41849d574bc4ac48dcef9356bbeb4540a812ec5b CertiFriP3.Wire CertiFri.P3.Wire.felt +D efe272075c8f616ebee3c829eeec1ddddd5d5cc68a5693330a86b559c8a2b455 Mathlib.Algebra.Group.DivInvMonoid zpowRec.match_1 +D eff2ae73997ef9c8c4764eb54087f4990d53c2611a78c00794389384eb54fa3c Init.Data.List.Basic List.eraseRepsBy +D f0077c69cee2e115c454db8fbb72c4827c3aeae28a6cd29d345a408fea2088a5 CertiFriP3.Wire CertiFri.P3.Wire.KeyParams.capHeight +D f00d823b18be0565c615fdee22f7f7ed9fe0ab2824192210efd86f550923fc3e Mathlib.Basic.NNReal.Defs NNReal +D f0237e40d7b3dcdc29260d7311230901e8c4097205811fcbad01c12687f1e500 Init.Data.List.Basic List.findIdx?.go._f +D f0333c48626eb3ba2df1550739b77121b9dcaef225c6bdea61f358d4f724e5a7 Init.Data.List.Basic List.filterMap +D f051d3c3b8fb9871f51e0ca5e1204f070c03f5cb966de1d81154e6c71abe62da Init.Data.Range.Basic Std.Legacy.Range.stop +D f0608dd1b011f2b073b1bfea1d453d9ae07f40650d3b1aaa7489bb57f91da8c7 Mathlib.LinearAlgebra.Lagrange Lagrange.interpolate +D f0631312a980a462cbacf485253a7ed33f428305c976a8034b1a4f01c7a2b615 CertiFriProofs.Exec.Stark.Shard CertiFri.Exec.Stark.fixedShapes +D f07705b06086d369825c2c1006406dde4686f15dea985e83d1d5c15777a5ba78 CertiFri.TensorBatching CertiFri.Fri.TensorSchedule.openWeights +D f086d611167ec68ec91cfbbc06abba9758232eae8a09781f1318911a43ef9ac0 CertiFri.Claims CertiFri.MatrixOpening.points +D f0a708c4b37f006eebd298291b78c6719e69a46e4b1570146bafdc9fbc28dd07 CertiFri.MultiArity CertiFri.Fri.verifyFromTensorWithSchedule +D f0b1e80d0f6e649f829e60632a25b6ec5d5ede29094155fa2284767f8c3ef329 Init.Core Quotient +D f0b8fc18e2884e6f7369d0a0e731feba41e084e65b531f62c0de74fbc948bec9 Init.Prelude Min.min +D f1034daf63c3d9241e498c8307a94fa5fb247d738d2954c8ed74fb2551abae0f CertiFriProofs.Exec.Stark.SpongeGoodLogTensor CertiFri.Exec.Stark.spongeRunMsgs +D f1158d105d65d6c49e99a17c8986c3334adc21123813944b967fdefb366b601d CertiFriProofs.Theory.MultiArity.CompiledTensor CertiFri.Compiled.MultiParams.queries +D f117f7f5a6e80703d07521d84aefd6976a52d713a72943dc24d382061ce86285 Init.Prelude Eq.ndrec +D f1267f2e7bfe53978c1cfb093f409089ab1b124bb2527580fd27a910d7860815 Init.Prelude UInt8.casesOn +D f197b2ed42e5c7fa8f32ef6ede557c146e59fdd23183a822d390aa5074988fb1 Init.Prelude instHDiv +D f199a3e01b3b52089d9631a385d6f04bfb2f7f33fc8a9aef00624e41aebc89b7 Init.Data.Zero npowRec._f +D f1c799376db138ab0ef5dfc4542d68a2dbe73bcc2fc583146116e4b523bbfb98 CertiFriP3.Blake3 CertiFri.P3.Blake3.pushChunks.match_1 +D f2032285f9c5ecbe89c9d1bb8899392827d8d1afefcadd65ea3220fa049b5278 CertiFri.MultiArity CertiFri.Fri.foldChainMulti.match_1 +D f206c138168fd9d2a55fdf00ce3d780ee166ac08d1af301cfe229bf43870a213 Init.Data.Ord.Basic instOrdNat +D f2189076cb8c5bc44293fea5f40b84f0f1f4720a4636b7384a5662ad4f448e82 Init.Prelude List.flatten.match_1 +D f2191ffb295551f868764651db88aa8b16ea7e1a7ccd212d3361da05cd3a46d5 Mathlib.Algebra.Group.Monoid MulOneClass.toOne +D f228fba30c7d4150a2654632ed3609ec3c78226eba7012703fb62ea17a5b4689 Init.Data.List.Basic List.reverseAux +D f23c05934d63f51b714818ad6cda2a9bb1343fa38070a31b32c7e371bf437ea3 Init.Data.List.Control List.mapM.loop +D f2475a40bf614b1d2360e1c6b0137095bb0e9eb8ef2f894a49dfb63aa6c4afb9 Mathlib.Order.Lattice Pi.instSemilatticeInf +D f25ddef56b3b8c08f82687b9b8ec7276568415dd67605dd94c1ad5e4b5d1b634 Init.GetElem List.get!Internal._f +D f2835da2d532878068d44f1a1bf0d7e1d0172f20d4fa0b609c1ddca5a5d97ee7 Mathlib.Data.Set.CoeSort Set.Elem +D f29bafd1340de6cebfdbb4da357e2d6da3a721b1110bc92467a1484d0f6214f2 Init.Prelude instDecidableEqUInt8 +D f2cfd44f0e270136fe84360c1ce6fd761131ed768ccd0335eea0768be54de12c CertiFriProofs.Exec.Setup CertiFri.Exec.FieldModel.leafDec +D f2e93aa93586471d494ba8eea41d475bf2342e81a879435d052263d883299de3 Init.Data.Rat.Basic Rat.num +D f314965dd4a1115c135a0cbffc7def2f978d4c161c419847cfdc919c5613cba5 Mathlib.Data.Multiset.Defs Multiset.decidableEq +D f348cd611d0473ba0ac8b1069dfafbe8e68b8a114f585a7664bddb57233e67ab CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.instField +D f34c83adf6f9b486d4fecaca660b10e39e50874b8be19ee7d3ba8fd560f99793 CertiFriP3.Pruned CertiFri.P3.Pruned.ascend +D f38047c31fad56223c5b2b83f0849df0b1700b9952caca022fa90f452fae60fa CertiFri.Stark.Pinned CertiFri.Stark.pinsOk +D f38b7831730034ef2bc5c4c89d6fe7b1b3f8029d3737f1732b922724ca5feef9 Mathlib.Logic.Equiv.Set Equiv.ofInjective +D f38dcfec293a35bf6e7f6744d993f9d0ae6d99b5f98c979041acb15fe9cec08e CertiFriP3.Digest CertiFri.P3.Digest.w3 +D f3b157bdafd943515b830c795ac6c59125f827889bc3eb672211769fb9ad6b84 Mathlib.Data.Set.Defs Set.univ +D f3caed7864c30cd5c0e74dbebf34ab8edaf5f8f9f8784eef1ed019f3967ba3f0 Mathlib.Algebra.Group.DivInvMonoid SubtractionCommMonoid.toSubtractionMonoid +D f4059351ba9c843ba3fa5870ec69aa4aaedd4cc6e4605d29cff3dca780841e26 Init.Data.List.OfFn List.ofFn +D f4342027fc1476ef7aa5ac291b6a4157ef48cbb0bcc3f500af62e463d3e9bad6 Mathlib.Order.RelIso.Basic RelIso.instFunLike +D f44ee49672fbcbad3ad29e10a8a777cb3622ec43a38039155bff8fc3b49be60b Mathlib.Basic.NNReal.Defs NNReal.instSemilatticeSup._aux_1 +D f46b9f23fa5b538c7b82a903e334dfee49568a47d04a61c8c097aec576a328d6 CertiFri.Mmcs CertiFri.Mmcs.MultiProof +D f47cfc0bdc7decd9e250d707a6dbddd4a73df1dc15abb675d8cdbf8efe45c616 CertiFriP3.VerifyBytes CertiFri.Stark.Profile.statementAdmitted +D f48b8017c40a4a05e6c2de9cf7cc32f2fb7f22fe087d300938cf11b9127b503f Mathlib.Algebra.Order.CauSeq.Basic CauSeq.instIntCast +D f490ce2ed534a733cab763297ae5f3d1a8c5363771807eb6f512ed467a9af494 CertiFriProofs.Exec.Stark.SoundnessPinnedSpongeMulti CertiFri.Exec.Stark.shardCompPinnedMultiSponge.match_1 +D f499fa6b07010142679a5d977a01b23bc8a471eaf9ebf735695654a7f5e0ef00 CertiFriP3.Wire CertiFri.P3.Wire.KeyCircuit.lookupDegree +D f4c3a9595984decefe3a67a28b998ce88bbb6093a3482a17f05f6239d71d5413 CertiFriProofs.Theory.Compiled.Read CertiFri.Compiled.Params.n +D f4c870382aa03230cdfa880163530623df079324e6bbb4f03fd99162f0a02cb7 CertiFri.Stark.Admissible CertiFri.Stark.Admissible.constraintBound +D f4d52a5bc7954b017fac23fd9567540190d6ecb324a71273471f49e32bb233d4 Mathlib.Algebra.Group.Monoid AddZero.toZero +D f518f6127bc0c55f2a9b71c1c1da9832765c20337afa91494e3c614e49c1c0a7 Mathlib.Data.ZMod.Defs ZMod.fintype.match_1 +D f526eb6dc593ef0fe732c51e9093cc78aff7643fc48cd882a069386d373f6cec CertiFri.Stark.System CertiFri.Stark.System.preprocessedIndices +D f531f5e6d581253932adeb78d5b5e2032fc0c608c4a753cd2693ecf4835d2bb6 Mathlib.Algebra.Ring.Defs Semiring.toAddCommMonoid +D f53a6f2923a5e87f62fd50fe66d19a4da2a300a2a925032cb42fad755a691dad Init.Data.List.Basic List.splitAt.go +D f5515b7c06fc79c758914bc200bc3ec9e5d4a5d23727693148defb142c22349d CertiFriProofs.Qrom.CompressedOracle CertiFri.Qrom.runAlg +D f559b29ac08c5162d31857856a16890d53c2b37287695c6daf078e8e7fd74f50 Init.Prelude Nat.below +D f59ea4ebabed9d6f442bc66519bf267a99311f82a44420b281f7a68c1cb887dc CertiFri.Field CertiFri.FieldOps.toOne +D f5b304a1f08fd265cdbc170fe8102d544e4e2ba2f8b91849a14c9d468020a140 Mathlib.Order.Lattice Pi.instMinForall_mathlib +D f5b30d10d51017df00d9eb65d90581d2ce4b16230a63cbe2674cc7058887a121 CertiFri.Stark.Admissible CertiFri.Stark.Profile.rejectInactivePreprocessed +D f5b3196d50076d7f4e5426c368942e3b982cc2bf111a5edc853be050fc9ac5de CertiFriP3.Blake3 CertiFri.P3.Blake3.State.v14 +D f5bbf8eec506ef3daa6351be4954cfa9e6b8024710b126c95e077df46d66a33d Init.Data.List.Sort.Basic List.MergeSort.Internal.splitInTwo +D f5c014a9988e6a6aaf5e03bef5dcbe028ba18b7b87d3c8cfcccec4751515cada Mathlib.Data.Int.Cast.Defs AddGroupWithOne.intCast_negSucc._autoParam +D f5c4620a4b9b4c91be28d85e9d001a952ed9549ca53fc3e2d0e99c6991b8a785 CertiFri.Stark.Statement CertiFri.Stark.Model.varColAt +D f5cc8164e90146d14a3d267090dafc85400559f8a2855ed25913b61939a590a4 Init.Prelude Array.extract +D f5e44a83a7f19e217909e9acd148c0bbc06b6818336f2bbbc3ba00d662e1fb69 CertiFriProofs.P3.ByteOracle CertiFri.P3.ByteOracle.baseHasherOf +D f5e61d28d44bf7e4560de01d83ccff84d440a92db40e0879c9fd7be5e157fef1 CertiFri.Stark.Pinned CertiFri.Stark.shardPinsOk.match_1 +D f5eb2acff08a624f7a5228b425cf7be6d30e761ae1b1758c709a81e80dbd35ba CertiFri.Stark.Graph CertiFri.Stark.RowValues.preprocessed +D f5ff356d7fa30396c4c198ac2c3e72096ddab1b30a8ffff8d72bb2484c9e7990 CertiFriProofs.Exec.Stark.JohnsonBall CertiFri.Exec.Stark.qwOf +D f6033dc92fbcce0e4dd247c874d0eb50a4829fb5f54f29c7bbe1077c50444f85 Init.Prelude Eq.recOn +D f6059420f268484e9d9cc852f847082167ef7d9c0c517dd34b9366fc9dbc52ff Mathlib.Algebra.Group.DivInvMonoid NegZeroClass.toZero +D f61a8580ab0b3a74c4eabcf89184b59a52deda216f327f8376eb1edea12411fd Mathlib.Algebra.Polynomial.Basic Polynomial.monomial +D f630a8511496f1cd5e11c7ad1528289550ad18f10328c8d6b24a570cd7d20e74 CertiFriProofs.Exec.Stark.SpongeGoodLogTensor CertiFri.Exec.Stark.deriveSpongeSteps +D f6455bcf81cd4dc3a0e0bbc55a11b9bacb6202c3ebb00e730dfffd0ddffa6980 Mathlib.Data.Quot Quot.map +D f674e7ab472dc9c6830f0b1751d133851adff5ec5d2fff076d50a1ec4c8f1a80 Mathlib.Algebra.Ring.Defs Ring.toSemiring +D f67bbfde0d0e0b63cbdfc49b6d0222db3cd3cb6ad53c0b108d68b790f350c8ba CertiFri.Stark.Statement CertiFri.Stark.Model.chansOk._f +D f6825593a72e6d312017673f46d437f364cbfd504b47cb6e4fb6f056c3b24559 Init.Data.Fin.Basic Fin.mul +D f6ae79863d7dc783c5d0692a664f376d49dbf1c22c3c05c9109b8007b8cdff5f Mathlib.Order.Defs.PartialOrder Preorder.toLE +D f6d04c16db1c8d1abd9e60cdd085714cd5723a7db4a118dc19a771230eb2ca58 CertiFriProofs.P3.EncodingInjective CertiFri.P3.Encoding.HashCall.input +D f6d9d3a9cb8669f80ca4d4a76928614c280920d897c38aec3240bc631c939bc2 Mathlib.Basic.Complex.Basic Complex.instNeg +D f6da751e20b18227ceeeedf0594c5dc2c17a91066b5aeedbd93132d602984772 Mathlib.Algebra.Group.DivInvMonoid ZPow.toPow +D f6e15e0832e8e25875bde2b7bae2810bebfa23ca8040bd1cc23e0ab6e53c1968 Init.Prelude Nat.casesOn +D f704b08a62c21937fa78d89210f612b4161ff14b16a23ab4a0376392f15c92c5 Init.Prelude List.append +D f717666aff5cc88f557ec05a6e1d037af749ab00a3135b7767e1630535f902c2 CertiFri.Verifier CertiFri.Fri.domainPoint +D f75a2f6e349bc6967b77990b615ef886c8566236eb696933d07c8cea4904f2b4 Init.Data.Array.Set Array.set +D f75aa4a1b85038410d51c9b6f039afbf3999fd5c605a99a78ab4b4907c2f6201 Init.Data.Rat.Basic Rat.ofInt +D f77a1e0b575b0412c2a1e115aa23b2b03890943cce7906833bdeb861f3dc6295 Init.Core Quotient.lift₂ +D f7952dc659ec0a14d0ea4ddd6a958c77f37084d7d24bcb1da4b61c0e6c79ce4b CertiFri.TensorBatching CertiFri.Fri.tensorStep +D f79a96331069cfb9a53e1acc49d07fd26d34b0b1c0ace3749d1070128e47acbd CertiFri.Merkle CertiFri.Merkle.climb +D f7a1d0a2e388d9c8c6a5f3546c12432d0dd2dd028762b3308e3927be70ab4773 CertiFri.MultiArity CertiFri.Fri.siblingsMulti.match_1 +D f7a3ff8e670f5a37347f73e4eb35e1fbd2c6ed5a6431c3a7dfacf0276bdfd8e2 CertiFriProofs.Exec.Stark.FreeTensor CertiFri.Exec.Stark.UStateTensor.round +D f7bc2d98e3b01ea86e90e6968db52e0be2f60906c387c1f34800cc36c132c884 Mathlib.Data.ZMod.Defs Fin.instPowNatOfNeZero_mathlib +D f7c2f0abe6384ec04a8c33b8dfe97df56591700fd13bad197b0f24f8235a1f3d CertiFriP3.Wire CertiFri.P3.Wire.encKeyCircuit +D f7d2c524b069c2401c6eab39b7467c8b67945e1c1310702c5fd0b872303802da CertiFri.Field CertiFri.fieldPowBits +D f7de333da45a41801aaf04f9a9ab88294431bfd1d5c4434a8afd8b4a4db8124a CertiFriP3.Wire CertiFri.P3.Wire.encLookup +D f7dfaeb48616102b753e8ca36da34782db70d9238c3e4c79d89551c6b22bfdd8 Init.Data.Zero nsmulRec._f +D f83973a445de0a22db5ca8d5921843936d177a57199d9158ac805e0db86061ba Mathlib.Algebra.Field.Defs Field.toSemifield +D f83b896e65273c1dfe04ac4ea2007d72c15ba2feba9ca14659831e76a481733d Init.Prelude instLEBitVec +D f83d9ac46a9724387fe2d660ab809a74a8ad37b6292329620ca9fb44c52d2ede CertiFriP3.GoldilocksExt3 CertiFri.P3.GoldilocksExt3.neg +D f84d5e8ebe9290c1335dc06c9fa411122751f89977132e1d1113d41f47028b92 Mathlib.Algebra.Module.LinearMap.Defs LinearMap.instFunLike +D f85c472707778e8de588091e03484251b9e052a07a7c7b44ead697f18795b8fe CertiFri.Stark.Statement CertiFri.Stark.Model.varColAt.match_1 +D f86bc0a09590cd18d2708c36659180a5c5c044a3a1b24833181939a4b9a0551a CertiFriProofs.Theory.MultiArity.CompiledTensor CertiFri.Compiled.MultiParams.verifyWithTensor +D f87424b8516d1594be5d2362a71da1aa7c7b071563f3755789511d3806477f34 Mathlib.Basic.NNReal.Defs NNReal.instSemiring._aux_16 +D f875f2bd53b13123c32a011bdbfdde409fc4d5f481e5bec4f75785eb6f4c675e CertiFriProofs.Exec.Stark.PinnedLink CertiFri.Exec.Stark.pinVals +D f883d84b26b5b64e66611423a4d63336df5e02d7ede3567aabf5ecdf4d37ec94 CertiFriProofs.Exec.Stark.JohnsonBall CertiFri.Exec.Stark.w12 +D f88fdcf0b09453e5ac26a099acc19efbf3a3f546a276994f1c434670e9d7d408 CertiFriProofs.Theory.Stark.BalanceWeight CertiFri.Stark.Model.IntBalancedBy +D f8a6ffcf4bb36d8c06de9c581504cb4484a46b1b58b3190120c7bd14f0b3e41c Init.Data.UInt.Basic UInt64.lor +D f8b21bcb0f6e998aa562b2e1a0c1955777f327535c0b798830e1c4b2e40f4c2c CertiFri.Stark.System CertiFri.Stark.Proof.stage2Commit +D f8bf92d888573215049a80936ddddf292c278102c28b656799d1fb1793a9f30a CertiFri.Stark.Logup CertiFri.Stark.basisTable +D f8c4863286c02f7980623d56f67eb81fc4db08738650b438246c89181774b830 CertiFri.Stark.Statement CertiFri.Stark.Model.oneAt +D f8d601ace442d14711e284810281545500d0bf3e9a4941e6fa3c903387689f60 CertiFriProofs.Exec.Stark.JohnsonLookupsBatch CertiFri.Exec.Stark.stage2Of +D f8d64e673fc4d9550356fa846b1c123a54d0bb3ff679cd4aa65839f38266fbc8 Mathlib.Data.Multiset.ZeroCons Multiset.zero +D f8e3d8867e2db823073a069776eba33f30980cce2b061af3e0f6191489301196 Mathlib.Algebra.Ring.Defs HasDistribNeg.toInvolutiveNeg +D f8f4fede10a189f9a0cd2c0f2c5361a34ba6df2975b95371c0f7d33148a43ab4 CertiFri.Stark.Pinned CertiFri.Stark.checkAfterChallengesPinned +D f91efa263990bf89bde61a3fc7247dbe0f472e3cbc1c50f1c6d391478db2aa7c Mathlib.Algebra.Ring.Defs NonUnitalNonAssocCommSemiring.toNonUnitalNonAssocSemiring +D f92b9f7602b69dd8200de411c1320401862b2805af612718364ff7e3c922554d Mathlib.Algebra.Group.DivInvMonoid SubNegZeroMonoid.toNegZeroClass +D f9730b58d3a50a66d0e84f1785d28cc46ee5f0222e6deba9ea7d883fce41d0e3 CertiFriP3.Blake3 CertiFri.P3.Blake3.State.v4 +D f9a931a2bf91d3ff7317078f589df519a87f0e06aa162a09bbebbebb2e794f92 CertiFriProofs.Exec.Stark.Shard CertiFri.Exec.Stark.traceShapes +D f9aa5185c8f69c4b3a999f51757b125812aca9c6e12afb4e596a2305d70e8528 CertiFriP3.Hashers CertiFri.P3.Hashers.rowBytes +D f9bcd7221cdbe74d02f0141dd8a9c5275e948b2e79c242d23d019a2ae8ca08c5 Init.Prelude String.rawEndPos +D f9d660f01effe1d06591d70974551a297530783b416f0fd39ac78b55ea0eb019 CertiFriProofs.Theory.MultiArity.CompiledTensor CertiFri.Compiled.MultiParams.batches +D f9e7c15141bce0352d7e51726b76f31d0c377b723b6184cdfcefbf65373b8ec4 CertiFriProofs.Theory.Stark.Air CertiFri.Stark.Circuit.zetaDegree +D f9f96bde780dda9036ea74dc0932af8e951689e76113561e52888502aa7be9ab Init.Data.Range.Basic _private.Init.Data.Range.Basic.0.Std.Legacy.Range.forIn'._auto_1 +D fa46ddda2c46fcf092b07f67f31f3262c55acdb2f5968ca5950f298ce0d03433 Mathlib.Data.Multiset.AddSub Multiset.erase +D fa6171798eebb4af2541c443c1fd2f858ac75aa4b4f4fad77e9ae2a32f28fb94 Mathlib.Order.Hom.Set OrderIso.Set.univ +D fabbea8ff4abbd9a144fd86d705e78ed79d7b761c4d4c4a6624d1a0552cb8ac0 CertiFri.Verifier CertiFri.Fri.ClaimRef.pointIdx +D fac82345028ea9b1661e01bdb8797777399a3e44fcfba7c455c1c082c30d4922 Mathlib.Data.Quot Quotient.map +D fadd59f1218c701b98c4a945df346253ee11f0e2ee457fa125fcbfe4b19ee714 Init.Data.ByteArray.Basic ByteArray.toList.loop +D fae443df9b0f3188e877734ce2dc5122367d344ca75aeef0f3f4608b02b18f2d CertiFri.Stark.Statement CertiFri.Stark.Model.lookupArityOk +D fb09b1956ff1d540d7387d1bd928a3d64524049260d343503c78a155156b52c2 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.instOne +D fb14a7c3d6a966f3ff33b03ad24a56b74cf44edb4af0bf6a53de00dd7bab95cf Init.Prelude String.toRawSubstring +D fb19d61dc16f398dc94503d06bb7fc10384072d6e132a699cd94e76ed7ae8ecd Mathlib.Algebra.Group.Monoid NPow.npow +D fb2caa8cec88d179f8b16bbff5b8a3b4b0f0652043884ea8651261b179bd0b92 CertiFriProofs.Theory.Oracle.Basic CertiFri.Oracle.Log +D fb34ceb68466871f668bae37d02cb66087fd598706fb50e15e32c07b830baf9b Mathlib.Logic.Equiv.Set Equiv.ofLeftInverse +D fb3b662bd2eeab0fd058ff14eaed9b53b2fa573d5ebfc88da82317bdcb21de37 CertiFriProofs.Exec.Stark.ChainTensor CertiFri.Exec.Stark.tensorChalOfAns +D fb43517809c6abac5a5d2e6507472900be91e1527e8fb3d1859060a11c8d9e05 Init.Prelude BitVec.decEq.match_1 +D fb62d2961a4130adbcfa4000f64c2dfbcfab0b3cf648e3e1f1880e331f154790 CertiFri.Stark.Graph CertiFri.Stark.RowValues.isLastRow +D fba57a4b65731e50642e49ff55b810ef2c5581d45397bc61f30ab8aab210fcf7 Mathlib.Algebra.Ring.Defs NonUnitalCommRing.toNonUnitalNonAssocCommRing +D fbae6b1366fe1f888c9c0fb97fedda3fc4c778526d56208e4d0d95b0d2ad4e38 CertiFriProofs.Exec.Stark.FixedKey CertiFri.Exec.Stark.hashRowsComp +D fbc5334f33d2a978c72f1c5d2bf901a8b6388795421b54b47d6e085f85a81cbf Init.Prelude Nat.mul +D fbcd02e0a1876dae0df9572228ad6e987935b44044e07c0733fa2bafbecfff8e CertiFri.Field CertiFri.ExtensionOps.toBasis +D fc02e9c69a5add57a50b4dfd667285d24f7930665acc75d9da8dec1f9c53693d CertiFri.Claims CertiFri.PointOpening.values +D fc0dcd1b1e3efd0e572f5fc9945aaf12e2c27c1af035b80210407454205a40a7 CertiFri.Stark.Graph CertiFri.Stark.instInhabitedGraph.default +D fc2c46ac213508da92634fb023b80c87d601bdd8e81bddf315dfa23c7e1f0c94 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.instNeg +D fc470a4761613bee6e34571f744060978ff5ecba6029fde8d59a287dbfdfaa44 CertiFriP3.DomainSep CertiFri.P3.DomainSep.leafInput +D fc5d851f8c9831b6d476a02c2765002eacfe2c3b2f033a5477eb6312ff2a70c2 Mathlib.Data.Nat.Cast.Defs Nat.unaryCast._f +D fc6a578efe4d55a179c091fd76de3985290357b18c204102999f210d9268e2aa Init.Data.Array.Basic Array.flatMap +D fc6ae15c10c81a10f38511da9756d31eac2c6c08653f27b91b265e11b3c79a28 CertiFriProofs.Theory.Compiled.Read CertiFri.Compiled.Params.rounds +D fc6c9ec10721f5b48e209e5b7aa0d8401e2e7d23d4e211d1e96084f0f025746d Init.Prelude List.brecOn +D fc6f66f943826241c5aa5cc860c3a57708977a43fc36ded7b33cf08b22f152ce CertiFriProofs.Exec.Stark.JohnsonLookupsBatch CertiFri.Exec.Stark.quotOf +D fcc003653f789a7fb1edb580f678939f3459644a7849a4f529ced90f5b689316 CertiFriP3.Blake3 CertiFri.P3.Blake3.State.v10 +D fcd35ba3169fa58e99d9386dae530a8a9736f766a42cf6c3e45dc5b45c519f8b CertiFri.Stark.Statement CertiFri.Stark.Model.minusOneCol +D fcef4b65f7eb09326e95a02d48797e1e4fd317ca5661cb0b9dcc91edbef6c2e9 Mathlib.LinearAlgebra.Lagrange Lagrange.basisDivisor +D fcf8b15dec2637367def35605f9b07bbdc7c4fac6aa7c35da630f891cc2fdfba CertiFriP3.Wire CertiFri.P3.Wire.sourceOfCode.match_1 +D fd0b9f689474fb29c531227043e8ac48339ca6614a7186de7c940ac2db55e543 CertiFri.Verifier CertiFri.Fri.commitPhase._f +D fd0bc95926bd964fe472bd18e2c8621161bf298fa28c4c6b18efcbaf390bb56a Init.Data.Array.Basic Array.anyM +D fd150526e890df0843615fcdec6d518bf318fae965c2f52354827ed09a9342e6 Init.Core Ne +D fd24dc9a7ea4b1ba7b8d29cda018e8b3b7721866c87a305aeffb314fcfd1177a Init.Data.Rat.Basic instDecidableEqRat +D fd24dedfda77e01665e793949410333bfdd8d32f798eb97e429cb902e8b1a5eb CertiFriP3.Wire CertiFri.P3.Wire.recomputeDegrees? +D fd25d90f46930311b16dfd6b07347e629a78a3b33a1dff7ecb233a1124a41fd2 Init.Data.Nat.Power2.Basic Nat.nextPowerOfTwo +D fd650dc4254c5e3d29827651a5ed912f15e3d09d1fef9bf5e1e382361d6ed7e0 CertiFri.Stark.Admissible CertiFri.Stark.Admissible.nodeDeg.match_1 +D fd759f68a5e697238457672469bc3c81152f693deacd1990afde9f487f2fa4b9 Init.Prelude Function.const +D fd7c01bd424163ba86fdc175dfe0e0b9858f8226a6a1bbd4924ac3e246273769 CertiFriP3.GoldilocksExt3 CertiFri.P3.GoldilocksExt3.inv? +D fd8577addf4b3c946d8894407de0c2595deee21d6f31ea8589125c0f72f8d391 Mathlib.Algebra.Group.DivInvMonoid SubNegMonoid.toZSMul +D fd93163deb6af32b508cf0aef0695537e7d4fc282cfbc4403d974dd942272f80 Init.Data.Int.Basic Int.negOfNat.match_1 +D fdead7540fde89693ed7ada89fa6ec2f4d4fd76dc09c08c358384be06c81667f CertiFri.Stark.Verifier CertiFri.Stark.Selectors.isFirstRow +D fe185c7acd5267bd4307da99f739d945334fd6592d639768ca7e4333b2180e77 Mathlib.Algebra.Notation.Pi.Defs Pi.instSMul +D fe1b578d8e02dcfbaad39314f962f5567c9bc0671bc4800163f516ddfebdfa3e Mathlib.Order.Hom.Basic OrderIso.trans +D fe46f115ecb9daa24cee8636da62fec235973eb45c1dd7b399b8208f04656d4f Init.PropLemmas decidable_of_iff' +D fe4b78b228abd73836d4b8d7f9219690582be59c72aeba9bc9f535ac1fcfb68a Init.Data.Option.Basic instFunctorOption +D fe7496af3021d83aba11adb1ccfa13a5c3122c583a3454519635f0d298cdb37b Init.Prelude instLTBitVec +D fe9f951d65534d02027d5c2097a7f39cf97a852a9c046589f71ac7ddbf2ff14e CertiFriP3.Goldilocks CertiFri.P3.Goldilocks.mulHigh +D feb84bcc4656c96c65186f9f081bbabfb8a377eccbfb14ad1fd8d5ae0bfb6c49 CertiFriP3.Pruned CertiFri.P3.Pruned.Node.rows +D febc8754db1485878ca7e01ce916e06541660850df6a72ecf47aeb9b583d46ea Init.Data.BitVec.Basic BitVec.instXorOp +D fecee90534ea37d4341fda62fdf66122c5fad0a0eb12cffbb488f17572ab761c CertiFriProofs.Exec.Setup CertiFri.Exec.digestsIn +D fed935310748d985d6107f1ecb63604ddc8c1dd2a097c85b575b67fbff4326ac Mathlib.Order.Lattice SemilatticeInf.toPartialOrder +D ff1d3276f1c6761f76515f812c6565dd40297cb78adfb9826c715cf35b7ddd4a CertiFriProofs.Exec.Stark.FreeTensor CertiFri.Exec.Stark.UStateTensor.init +D ff5f0eff248faa219b7a0430907f465f2db4041ec8e7afb434e6444ce8f8458d Init.Data.List.Basic List.reverseAux.match_1 +D ff69771465f526cbf7cfbeb3591eeabaf8c10e5b831726e9ebfdd53072f029f5 CertiFri.TensorBatching CertiFri.Fri.tensorColAcc +D ff7527400cac601a4bf99a39acc73edc12983ac56d3606ba13bfa7a7b77b19ff CertiFriProofs.Theory.Oracle.Prob CertiFri.Oracle.OracleComp.expect.match_3 +D ff7672a22066db69426aef56250dd670876a1c72572236c535dd4af0e3edc684 CertiFriProofs.Exec.Stark.SpongeGoodLogTensor CertiFri.Exec.Stark.instDecidableEqSpongeStarkMsg.decEq.match_1 +D ff891dee432d0e3ba918e30c6d3685993cffe9f257acbdc9a22ae8a4229e6b78 Mathlib.Order.Hom.Set Set.orderIsoOfEq +D ff964ed5a6823bd16d0d51760896e02d858a977a4608f6b251f1b08092211d1b Init.Data.Array.Set Array.set._auto_1 +D ff99116ac42ff72dabc01be01a7f268213b01bc5a7c4d99c9d92b89a87014348 CertiFriProofs.Theory.Oracle.MerkleFrozen CertiFri.Oracle.SpongeAnswer +D ffb09d949836113bf152388e47b3a69acea5ba4d4561a59d96e228f774dd2b83 CertiFriProofs.Theory.ProximityGap.TensorMCA CertiFri.tensorWeight +D ffb0b63b6ffe92552d3c19938acee4205be3c6d3d22d379b17c717cd2c3da13f Mathlib.Algebra.GroupWithZero.Hom MonoidWithZeroHom.funLike +D ffb3ed438524045fa9cd2e27134449772e1e18e8696ba4347b6f9465aadef93e Init.Prelude inferInstance +D ffb5849caf619588c59498e9e4baf8e713ddc7f25d50092a133089f89a7f1ee8 Init.Data.Int.Basic instNatCastInt +D ffc4658d74be5abf46ff2f78c6bc2c9060d374a77ea37503a26df6833602b89f CertiFriProofs.Theory.Oracle.Basic CertiFri.Oracle.OracleComp.bind.match_1 +D ffd0fd9b36053e67a19b5837a477da16dc85314dedfe4d546f98f95063685ced Init.Data.ByteArray.Basic ByteArray.get! +D ffd72410988b9bd4a40eaba8dba8da5bfaaffff4a1f73a0fa19c1d5001e94611 CertiFriP3.Challenger CertiFri.P3.ChallengerState.sampleBytes._f +I 00395ccee739dd41393cce9c648219eb36d3c75252db482879cd0a0b10079eb3 Init.Core Sigma +I 00f087e8c72029c1d4a3c2c7a4094b61df897d347308e915233e269c81adda0a Init.Prelude SeqLeft +I 015c6ac3fe69ab5905bd07f3c382cc2bfcb3dd9f524082eaf004bb997fc57cd7 Mathlib.Order.Lattice Lattice +I 01f77449983551014ce3c57b7807f52396325efef91a6d5b1ee5f5c201439fd2 Init.Prelude Eq +I 027381ff9f624f7b8fb0cd3405afb96c2dde31147592a1fa9c143effc5536490 Init.Prelude True +I 02e45fd380dac1c637ae08a47c6e018858ddaf30befaf64ef5fcdb1fbb356c7d Mathlib.Data.Int.Cast.Defs AddGroupWithOne +I 03898b77baa9649bbea607e68ed96b4a2f4a6bae6c492848ba37e20b2754c364 Init.Prelude String.Pos.Raw +I 0595bcaedada2b42f8dfe2161141cb3f9b226864e8910d5b2d3a98e1ee1d5d57 Init.Prelude SeqRight +I 05a5cfce1c2a5ce76ee39553f5517ca175c9b31f8498b61b3d18e64671aea02b Mathlib.Order.Defs.PartialOrder PartialOrder +I 0675e3c8f7cf119c0ce711895a874db26dc4495d57e963f5324f83662f96371e CertiFri.Challenger CertiFri.Observation +I 07551bb38a9b4dd36979e538cf7e919c5bd8acfb050dc097259754c1ac121cda CertiFriP3.Goldilocks CertiFri.P3.Goldilocks +I 0773038c1fa0701e0a3541b3ca4f63ce105f46ddab0af5364b48ab74d97eb111 Init.Prelude Add +I 078cfb6a48f25992ff3e3518e1b4a0a414875c56a04f47a11a0fbdd6737bf329 CertiFri.Claims CertiFri.MatrixOpening +I 07b3cf662a4ee8cc9e47a6b25df374c408af996df256c4baae765e391ea6727e CertiFri.Stark.Admissible CertiFri.Stark.Profile +I 07d47655de49a23b60df1ce1506b57a921e7534ef80fbaab39f78c8d8f0d251d Init.Prelude OfNat +I 094a2433d97be65b2a4fcc901dc7ab1718e20dc11466b737013f235fc6c10bc2 Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra +I 0b09296096cdd1ecbfd05467f822542a08558a184b757298fc9e3f03082ad5e6 CertiFri.Params CertiFri.FriParams +I 0b48060193ea46a99049290895ddc596d25a198b17f8cd9514c2a876060d68ad CertiFriProofs.Theory.Oracle.MerkleOpens CertiFri.Oracle.MerkleRO.Dig +I 0b6261b7e19106fdd62f4901ea1a91f697e0ff7a086409932da7ea97daf13b4d Init.WF Prod.Lex +I 0b9e418f1b458dcd2918edec73185f5029a5af56631779fcf2e0b4ae21534a33 Mathlib.Algebra.Group.Semigroup AddSemigroup +I 0bab11f147cb6b300749820fe6eb9b8244c4d3543249b592b7e5c5b157cab447 Init.Prelude ShiftLeft +I 0bd12b163d5f1ce44fbe7c0720c138a52cbb7ef961d8569c9453e62f92387b9f Mathlib.Algebra.Group.Action.Defs SemigroupAction +I 0d964060a2363a16961fee0c9bd25c5d5f4bdb3e9da0933cfbe0615ced460949 CertiFri.Field CertiFri.TwoAdicOps +I 0da25bd5ccd8d817dd5870e54a9639d27aeac101a501334176160b1e244f1aa1 CertiFriProofs.Theory.Oracle.FiatShamir CertiFri.Oracle.Transcript +I 0da86e81c6dd00a5618061856fbdf0189ec1258294b5176819319dcb07caba0e CertiFriProofs.P3.WireRoundTrip CertiFri.P3.Wire.Key.WireOk +I 0f5ada1c4fb1b112909be861fae8138f01a0f896075eecf9bf791d131647f449 Init.Prelude PUnit +I 0fcd18df79b1237cd68cbd07fa2cff4f7688e1bffb918dd1cc54cd73edfc8b60 CertiFri.Verifier CertiFri.Fri.ClaimRef +I 10224575008dff5de40c7fff635e000bcb00dc7b4895767e2bc0d4a8ae51ac2a Mathlib.Algebra.Group.Monoid MulOne +I 10a5cdb33ea9a2ff68d07730737a1010f4bb949a84c072ed6b8c8873afac25d3 Init.Prelude Bind +I 114589f17a6251ecd36c1d9a6e8863eaa3e986c5642502c55858c895fe76682c Init.Prelude Empty +I 1178e7255789f591c3711db12a3249d4d2b46ce51fd7f2b655fc01787539e9bb Init.Prelude HEq +I 132f402f9e043bd395002cb07040352cfaca7f7403de3408805723fd979d3171 Init.Core Exists +I 15aa958372d96ba744398fc5e1cc3e2b2be148845b3b63fa59ffb31e94cb500d Init.Prelude AndOp +I 163a4d732d47f1704f355f834d1bbd466831387599e45a10a4e7d45251cccc65 CertiFriP3.GoldilocksExt3 CertiFri.P3.GoldilocksExt3 +I 17683f9aeb1f38be7360410896e5164b595466ff989c9e4d7eeec37ddde2a5cb Mathlib.Algebra.Group.Action.Defs MulAction +I 19639259f5187dee1c4d5ab75dbd799c47a45b80cb9f4f7dc826e836fd1937b5 Mathlib.Algebra.Group.Monoid NPow +I 1a10277ef3dee99c79f72ade09e31b5d91ec704551de31b0cc959050654d5a61 Init.Core Std.Antisymm +I 1a304652a2b03bc0bd124bdd0d1be088d03df71042db8267aeb2c322b0893e5c Mathlib.Data.FunLike.Basic DFunLike +I 1a7a6ad4c792efd8bb5f7be17048d6d757fc0e9c5afe401f674b727b503320ad Init.Prelude BitVec +I 1e7770cf94c07f5d9355b222670d9f8e3fbb9baaabdc37f950a31d59daab1c4c Mathlib.Algebra.Group.Hom.Defs MonoidHom +I 1f3a1761b73309045a72ed81146d8c484e3d5366ec579e7b583c29d27c2e23e7 Mathlib.Algebra.Group.Monoid NSMul +I 2065eebe2bf1f9fd25d68f7538eeca31eda0ac337b14953610e92d282b4041f1 CertiFriP3.Wire CertiFri.P3.Wire.KeyCircuit +I 206682b1df6cc6f84f0619c5db76b25d55589ca168b2e8ddd8334a63d4bce080 Init.Data.Range.Basic Std.Legacy.Range +I 20b054a7f5e19353d099f6c0e61726f7c675514182aa94a384f428e36e11939f Mathlib.Order.BoundedOrder.Basic OrderBot +I 20f731af31b686741c0f00cc273fb7e63ec324e28abdc3a697611d928625ff35 Mathlib.Algebra.Group.Monoid CommMonoid +I 21a7a29564824193ac54320e1ab4dfd20fe3f624f060a2b20dcb37b58848c9e7 CertiFriP3.DomainSep CertiFri.P3.Blake3Domain +I 229a083e48627ec69759d0980147f76b2ebe07650a0ae58afc15fa6d0e7b8562 Mathlib.Algebra.Order.Monoid.Defs IsOrderedAddMonoid +I 2331c81b7a53d23d7a667f7530178476a8d93d933429a487000c990f29b3ecf4 Init.Core Union +I 23fffdd7b21cc650b84f17eb251d349ecf53949019007a50395ed7d3439435bc CertiFriProofs.P3.WireRoundTrip CertiFri.P3.Wire.KeyCircuit.WireOk +I 246ded9e9f2dfba0e1cd84910e7ba591b2c7bfb6d67cb8b23248a36ba899a676 CertiFri.Verifier CertiFri.Fri.QueryResult +I 24b7a9d2a85510e9487d2331fe061d5a78e4e308ba94ce77c119cd89a78c7108 Mathlib.Basic.Real.Basic Real +I 266b7463106616c4b71c6e42880914393a57a0ff1aa13823b6a144cb6263b1a7 Init.Core Subsingleton +I 26ad62e272fe3bca1143567a4126407d2f0bc37e7719bb63dddd325dfe0c693f Init.Prelude HPow +I 274c9491bb3c56a32c3631e7ba786565ea1a1b12b55caa119c4c3b05eb658f39 Mathlib.Algebra.Field.Defs Field +I 277597b3c4118a6522c1ffc1ed8d8f80696ab78ee6d368ee8f40a20534745dd9 Mathlib.Algebra.GroupWithZero.Defs MonoidWithZero +I 27cedbff213d1164f2665f0ed46b2470b61e08554ac2dd4c45ff0708dfabb235 Init.Core EmptyCollection +I 28ca985d484a0377dbbaf4d369a8ff96d3c772c1de69ff369321ecdd09cb15ff Mathlib.Order.Defs.LinearOrder LinearOrder +I 290b71d8def5f9644313a2e360514495312974931d17c56bf2523aaa8c27831f Mathlib.Order.RelIso.Basic RelEmbedding +I 2a4f6f1687e1402ecc6cf4c5b41c8a0b4a07438a8918b5148e6d3a57192fa834 Init.Prelude Pow +I 2a53e1906f3fe95219807865bc06a24bda4851ce2c3438140ae109efa2f53ee3 Mathlib.Algebra.GroupWithZero.Defs MulZeroOneClass +I 2aa1b4447bf928a14e26abcd36d4257d01ddc523f13b9866acdd687eea66ef9c CertiFri.Stark.Graph CertiFri.Stark.Graph +I 2ad33d8cddc590388c8fc135931579dfc90e5a2db3f8d80c784d7d89334f840a Init.Prelude Inhabited +I 2b87c56365b8125630a1d7b10b17e9b9c5faad849868f7128ac334564d3d8ce1 Mathlib.Algebra.GroupWithZero.Action.Defs DistribMulAction +I 2cf614f819f0a23f5ebadd17e9bc00581ba93b61b81798d5ee9ece5dc4b6446c Init.Prelude Max +I 2d575f48e7f1069f8e93533e70522b051a8fa468afe46617836412a6a2075aaa Init.Prelude XorOp +I 2da399760424948b5038c7f9ce1477f890c9b81af5ea2c577f4fa84706ef36b9 Ix.Cert.Release05.SecurityAudit Ix.Cert.Release05.Ep1V6ShapeBounds +I 2dd993efd6bff40efceaffa3f1a14d6da2f648d65320f569b57f40b04151d15c Mathlib.Data.SProd SProd +I 2eb1481504928190f958730d425802e33f17c0e39c48261a64129ef9c55eb617 Mathlib.Algebra.Group.Hom.Defs AddHom +I 2fab268d34a427c9ca005d7f714d6f1b7f4e734f9dcc4825c5ee78c8112ca529 Init.Data.NeZero NeZero +I 305e3cd447369f6937b550b4845f91f59e36d6410eb99d5ddd7ecb6cc169aa34 Init.Prelude Subtype +I 3109e6e033939d27b2f91d395f35ff02ffd937defda1640fb0290adcd9a96838 Mathlib.Algebra.Module.Defs Module +I 329b51b3f7652bb5d03eb282375fd7a4ba16b99b2ecbc2a1eb00ccdc6ce5f517 CertiFri.Verifier CertiFri.Fri.PointRef +I 329e3ca9cf1f189864d9962031e5b3328245f4571140ae1619f85f059417d778 Init.Core Std.Refl +I 32f001bc721fd6533060333b240d8005d8fa8aac832e8a710c37b664c586dfed Mathlib.Algebra.Ring.Equiv RingEquiv +I 33d7e4ee7528b07adaeaec8bf3265cb1f8fc1a11453de7e4d8bd2d4ac15bccbb Init.Prelude NatPow +I 380ab36663264068639d0459cbd08624e5af1dac302853e8c0cb9d7468038aaa Init.Prelude HSub +I 38be5a3f7602c8f332cd837962d974c5dab81797301ca9a96166874897e59110 Mathlib.Algebra.Ring.Defs Distrib +I 3b05ae982c423e222ceb7a8eda751bafc2d957199af6df41a477cbf6fbbbfe57 Init.Prelude HAdd +I 3b20a121868d3e3b9bd09f59e41c18e7a165a94e12cc52f6c142b0d7d61308d5 CertiFriProofs.Qrom.StarkPinnedQrom CertiFri.Qrom.SpongeDbBridge +I 3c9124aea9b905c8d2e88bd6389bd922bd899f90eebb3fb6f472e4918bbc495b Mathlib.Algebra.Group.Defs AddCommGroup +I 3cd93faf9a025c2cde5e8f46877d41ceabbd8a22f1f07e7edfdd6b29fed2f5da Init.Prelude Membership +I 3e163c94e52eedcf4543428cabcf7fcef28481e7f796933168ce4fe743f1e174 CertiFriP3.Wire CertiFri.P3.Wire.Key +I 4055a896b7e3967e5c45bda0885d639d2e3a2dabb1ba7255931554801d0364bb CertiFri.Verifier CertiFri.Fri.MatrixShape +I 4235082ecf117884f2f4c7cb2f8f719e6a9d84c34572dcdc671ad145431f8150 Mathlib.Algebra.Group.Monoid AddZeroClass +I 431412c54faf5e4f68744750ea037c84a03653118eea2ce75b32b400cec03195 CertiFri.Stark.System CertiFri.Stark.System +I 43325f88ccc9d591d509170764239794e571aaf886d206cdaf9746ea276e1a2d CertiFriP3.Blake3 CertiFri.P3.Blake3.Block +I 43a72263cc90f3b0b5a4e63ea41352420a191aad6b145263028f80dfc2388271 Mathlib.Order.Lattice SemilatticeInf +I 43dba663b4635c8df1afb9cee956b5ebb0512611369ba4e7ea8d1f925eee7c26 Mathlib.RingTheory.RootsOfUnity.PrimitiveRoots IsPrimitiveRoot +I 43dc8bf686bd6911b3911495010c88d638e800fcc28b705cc057defcfbbaab59 CertiFri.Stark.System CertiFri.Stark.BatchMessage +I 43e41f57d8c8c426cfbfa744938debce2010b6edac8c0a9f516be75a99d34b0d Init.Prelude Neg +I 4493e366197e4e2cfb487cc542fc7ee62ab1c5d186e8a34f924f284404bef94f Mathlib.Algebra.GroupWithZero.Defs CommGroupWithZero +I 449e4fadd50f623fbb25a076466dcfaeebda61b18a788cc6af6245b4b26a1004 Init.Core Equivalence +I 4630033e6be09b20c95e2dc7211732e71779fc43fa9af2416cd6004f71879308 Init.Prelude OrOp +I 46995d26a046ae6859f2b5e7c9c7436da02e5fadde7beca5c1646e762dc3affa Mathlib.Algebra.Ring.Defs Semiring +I 46bffaa2c57b202fa0b70bfcc0e512d59b688efc2d44ba3e1dd85f5bdbc382e6 Init.Data.Cast NatCast +I 46d621dc2cba614f776906b326c6de269ccadf42b4950fc2abc437b63646dda2 CertiFriProofs.Theory.Stark.Check CertiFri.Stark.Model.ExtData +I 46d880ab00cae23517f124b40e84a372668c9e646b7d2eac7c4181859917688a Init.Prelude HShiftLeft +I 46dd381e309481acbc72ac8258a1a35f93a7c596da70ac772fd0c2b1d497ac3e CertiFri.Stark.Admissible CertiFri.Stark.BatchBounds +I 47d071073b32dea7cd68e7624f40f05c54170c326e30507c15258c2274ac7724 CertiFriP3.DomainSep CertiFri.P3.DomainSep.KeyedInput +I 4887be339f084e7a99ec1d6f1d85e3b199d4dc6b1680c02949a9dce1f4597702 Mathlib.Algebra.Group.Semigroup Semigroup +I 4cbaaa404d8c6806d7d3d393f64248b65db5978e3441a1e91816e561d5852aa7 Mathlib.Basic.Nontrivial.Defs Nontrivial +I 4d4795bde578b686ae85f81ca6c010bc6abf3b1709c9ce1a2590e1fa84a56c13 Mathlib.Logic.Equiv.Defs Equiv +I 4d52ab5e999b0a1b7b28062be5d0d710dba00fbaae37f7aec415f5093ca7e3e4 Mathlib.Algebra.Order.Monoid.Unbundled.Defs CovariantClass +I 4dd3901405c1de7303a81742dd77ba9355e00e157689411ae70863ffa0d6d97b Mathlib.Algebra.Ring.Defs NonAssocSemiring +I 4e44381e49c50e7c2baf7b57b00654ccf8138d25e3a934954974ed967f2d23bf Mathlib.Algebra.Polynomial.Basic Polynomial +I 4e8734662a4bbd6077ce3a1b78bf0d5d5ba52907a44bb22847c572d9f89cbb74 CertiFriProofs.Exec.Stark.Model CertiFri.Exec.Stark.StarkModel +I 4eeb2e59a855d15af627cce37dcb4cab272b694312910a0cd4448b23864dee05 CertiFriProofs.Exec.Stark.Encode CertiFri.Exec.Stark.BoundsLE +I 500fbb6458e0049b9b8d5b30746951ff70f3605640d32116f1cd82f8fb595d9b CertiFri.Stark.Graph CertiFri.Stark.Source +I 51ceec212e76f3370210c36cc7f50eff9a4c4ba5a6799326e7518f785b0701d9 Init.Prelude Decidable +I 51f612057f741244a88e0987128ce4f0bb5e9e692e30b31b8a9c5dc252bb4274 Mathlib.Algebra.Group.DivInvMonoid InvOneClass +I 5234c8fb51edcb8c71e9c8990c1ccefde04c54f68a12eb2351138ac5311f504f Mathlib.Algebra.GroupWithZero.Action.Defs SMulWithZero +I 53eb98e9d5f791dbe17053b1a0c964f0ed4d9981303170ca1baebe5c415f9ab5 Init.Core Inter +I 540f8778ff451de392aadd7ffda0722ea81576b87c719d067634eeff1f012b56 Init.Prelude Monad +I 55c83399968c18f22f3d0c8edb34d699d35c42184aeb2b7200902b281acec1b1 Init.Data.Rat.Basic Rat +I 565ff36d2b538c18ba984b91c2e96dc3757c81b9b463f1441d521858cb1b21c2 CertiFriProofs.Exec.Stark.SoundnessPinnedBatch CertiFri.Exec.Stark.BatchCoveredPinned +I 56830a654c60c265e8fe078e8864581f83f20bd8fc2e00719759f69f50031c09 Mathlib.Algebra.Group.DivInvMonoid DivInvMonoid +I 577a47203ce4f802658d71e4d015367b63bc86ba4ddc853112d54e82eeab5619 CertiFri.Stark.Graph CertiFri.Stark.ColRef +I 58b598680b057296522245c3eeaa44e8e94315a26ae5c7bfcac18d91a840d43f Mathlib.Algebra.Group.Hom.Defs OneHom +I 594ed65913d0c28e8ce34b56a2c64f2d9ef3daa2c7bad7cb4f2a43c23e7eeaa6 CertiFri.Stark.System CertiFri.Stark.ShardHeader +I 59baea79e0ba2e82fffaa5682799b57505ad696b3dda0e13faa67e760eb496ae Mathlib.Algebra.GroupWithZero.Action.Defs SMulZeroClass +I 59e360eff6d7be3ff8d6ca2cf46ae67f811fd2e5a39b3bc07398bfe0eb6e5153 CertiFriP3.DomainSep CertiFri.P3.DomainSep +I 5b0d263eba49f9d393cc52b20f73ef6a9aecf337a6519388408a0b5d6ba6f82e CertiFri.MultiArity CertiFri.Fri.QueryResultMulti +I 5b13ad67c324381c342df20f6b802ea0c24b23ad04f83e23b58b478e9e7f0959 Init.Prelude Min +I 5b7f7dfeda6d0cf5d97e6c4dc490017b5d943ddd5e56aee2907ba42237dd81a3 Init.Prelude Prod +I 5d33387dc97f6b3a035370cec3a9bd228b269c7204af2d9d6a23bc0b9d01be13 Mathlib.Algebra.Group.Monoid MulOneClass +I 5dc057f580a3d14bc692178a7f3a858c5508fe6520f86fa4d9efad4f948aebfd CertiFri.Stark.System CertiFri.Stark.BatchPreamble +I 5e406b5bb6d477805375e3bf412e64216f7883820d9fd1c44455b7d1e8670bb4 Mathlib.Algebra.Group.DivInvMonoid SubNegZeroMonoid +I 5e53a8a35703ae958871f74e504300edddbe745281a9f68b59bc9b376627f66b CertiFriProofs.P3.ByteLink CertiFri.P3.ByteLink.ComputesByteVerifier +I 612307a999795feec8f40992268fbd95acc77bccaf698e0c0eba1add8bbdd735 Mathlib.Algebra.Group.Irreducible.Defs Irreducible +I 61821117e906fcb0ae9aec31e400a8cd5f23a303c193c02045b6d94315b35172 Mathlib.Order.RelIso.Basic RelIso +I 630800dd9e3f7446193eb8cb8a5c9fa2b87a729448aea3a99ef1c36197e87caa Init.Prelude List +I 6393c9cb94d3a07920a71e30b85efee14ea44cfb710085776061f91cc17f22cb CertiFriProofs.Exec.Stark.Preamble CertiFri.Exec.Stark.Bounds +I 648683e9ad1d0112f27809380e63468b12daa14fca04df51541bc421800ef25b Init.Data.ToString.Basic ToString +I 64ec6c9450d9527be5c3b3437e61e35c3a54602df8166265c8b24cecb39456e7 Init.Core PSigma +I 65c06a050a2ac1cef3d8fbaef932e69b7797250c140014f9d66b5a341c8c57d6 Mathlib.Data.Nat.Init Nat.AtLeastTwo +I 65d9530f4e5ec7b4bb29cd4ba9e2ec4f186e15b2fe3096b17d11e1b3e0221646 Init.Data.Int.Basic IntCast +I 6829074172dbc8399377b778861f4e421f0455c08c218fd679da23e10f004f97 Init.Control.Basic Alternative +I 68c227389c18cf6d0b564a682d34480334956194e717a6e4a2090170fbc06ccd Mathlib.Algebra.Group.Hom.Defs ZeroHom +I 6a0ef4f43ab4a08fb48ab59bf6c912edb5b01e929ab4c38d0719b479ec00636a Init.Core Setoid +I 6a9bbbfa444caab0e480595d458782d84a4a667a67854b7b7f995d05cb377b30 Mathlib.Algebra.GroupWithZero.Defs MulZeroClass +I 6ab8f76d1c35c7bb49e346175b1bf7b3a962a56df909175764aaacd231147d52 Mathlib.Algebra.GroupWithZero.Defs CommMonoidWithZero +I 6c4e9dfbfbd1362932ab9958f09a7702e6881f8411b2b56958ed1952d121dcb8 CertiFriProofs.Exec.Stark.SpongeGoodLogTensor CertiFri.Exec.Stark.SpongeChain +I 6d076c30a7c41d2a9151693a44092dd2e146aed766dad81a094497d0cef0adfb Init.Core ForInStep +I 6d3fc253b4ede992f6dcc6ee1badbc1f1951ab362c159296fa3e707f883cbe0a Init.Prelude Lean.Syntax +I 6dc98bf3e8566f3114d2492151fe43e3ee7d0cd53f5af67f18c348ce35683415 Init.Prelude HAnd +I 6ef98fe6ceb2a81df014d1db77422dafc7dd3f3721c01c6443709748b951aded Init.Prelude Char +I 7014d1f5a780207e3ae7edf51aa1577b5ad4f4e6e4ba8d5415b5885f7105a72a Mathlib.Algebra.Order.Monoid.Defs IsOrderedCancelAddMonoid +I 7038459ead716041eb5fce37d7c0f7899edec327a6242d0c569887a0a5f43975 Init.Prelude False +I 70f8a2f797d375de99be3a2f8c57b32d51716aaf2158bd459cc36bcbfbc019d7 Init.Prelude LT +I 71059e39df9ab3500a15267d679661774975ec3b71ac0acbe77c1cfd6d397bdc Mathlib.Algebra.Group.Semigroup CommSemigroup +I 725de2e438dad3c2a784ab277abbfa8274e23795a16c46d04a593bdefea844a9 Init.Prelude BEq +I 72dcddef5a62b307b548bb9400f81bef5f8ba79df410b3cd6774fee62c4f2120 CertiFriP3.Blake3 CertiFri.P3.Blake3.State +I 7329c8db9d1cbcdcc86a2c8b7655b474d1d178fc7ef12af233d69f07344f3a40 Init.GetElem GetElem? +I 737395384a9b4837efc4aeeece44ac2d94a6728d4f3fc8b29eae5bd23b88359b CertiFriP3.Challenger CertiFri.P3.ChallengerState +I 73d67df6977c0da7a0cf431695d86532f35dd631aec4546adc476bbabceaac87 Init.Prelude Applicative +I 73f25dbe07355008af277ef0fe73b2f268af53058f0ea2b4ab8eed99025bf539 Init.Data.List.Basic List.Perm +I 74286f5978330f4b8fc65b054da09d9a2db9d2c1fcf80fa6e77971305b04e2ea Init.Prelude Array +I 74abf51010bfc6aefd676e4a7491cf5f7fd4abb4814b72c9f7e8c17f1c90c726 Ix.Aiur.Parameters Aiur.CommitmentParameters +I 74bdc44b0e5842d3ff55a10a8529667941fbe8aa6a07b760c68b50171031d489 Mathlib.Algebra.Ring.Defs NonUnitalNonAssocCommRing +I 74f391ecf29439e12ad8b674f4145b7a8ac3d249befba74de53d20d97474f1e3 Init.Prelude HDiv +I 7599e4b7afde6c8b1198aac6d99326a5edc49b4f2c61ab8685efd2da086a8daa Mathlib.Algebra.Group.DivInvMonoid ZPow +I 761eb5dae14060c4d166314a7847ea58adad35d7f04821800193c82d0f8b889d Mathlib.Algebra.Ring.Defs CommSemiring +I 77cc3246b0d894035ba1f15468a6ef064178e0fe8bb5941a9bfcf097b5ee92e4 Init.Prelude Or +I 789e3b7c87d6a6ee78820d24c93bf487bc67db09dfb45203437bf9b841591dc2 CertiFriProofs.Refines CertiFri.Refines +I 798e6aa4fbed2f019f77188ed2bc4b42fe23b23fb33b1329aebb4e58066c33df Mathlib.Algebra.Field.Defs DivisionSemiring +I 79f3183076b82b0d35c493545f0b1444c859b82a084ac4eeed1ffd29741c35d6 Mathlib.Data.Nat.Cast.Defs AddCommMonoidWithOne +I 7b4616bfe50896a08e7a3e91ceecb6b3869bbc707c19c3b558cc3eb367fde70c Mathlib.Algebra.Group.Monoid Monoid +I 7b6edb5ce49ac269ebab71598d7a86156bea437d8d28e3ad1a4646ef8dd3e331 Mathlib.Algebra.Ring.Defs NonUnitalRing +I 7c77a842ed0ceba37d84c6b091a6923d58da52700f01072b67fc4ab15525714f Init.Prelude Append +I 7c8bd69e9bad00a8b8bcb8232348750d09087bd23ec031d67ad42f09aa79a71e CertiFriProofs.Merkle.Tree CertiFri.Merkle.Matrix +I 7d1657916e350b37329afa5babab6eb872186fe8222274db4fec89a7347aaca3 Init.Prelude HXor +I 7d82204cb742b330b46b6b0f31db1aecbf08e2cbb461ffa1009a5bc290b16c16 Init.Data.Ord.Basic Ord +I 7ddd3169f71c00163d6696e56fecd06ae10a6ea8be9058ded90a261638c66c80 Mathlib.Data.Nat.Cast.Defs AddMonoidWithOne +I 7ded9894adb93d97f85d232ca4032ca87fea1cff71baa950e58afa9a2cac7acf Batteries.Classes.RatCast RatCast +I 7e87c06079146934a225bda78fdd93c03177cd1f17cbff5b6de85a01682a2b0f CertiFri.Claims CertiFri.PointOpening +I 7f17fd986699fee2ba9957a3416322038ef9d6b51184c3e86b4eef01cd95b82d Init.Core HasEquiv +I 803e888b74e6ac585328ed01d1377845ab4cfc9171fb3c6bce63e9dca4747b60 Init.Core Std.Total +I 817f093cedbb7445da67d8ee226d5c0be8b9a66b3f2f46a1aabf0909faa7d5f3 CertiFri.Stark.Pinned CertiFri.Stark.PinnedBatchProof +I 8259e72b32a55af2d28ae61262076a05c4fb37734580da31f709058e00b642bf Init.Data.Ord.Basic Ordering +I 82eef22162cf44f285ba3bd759ae97606f5e32d14808a96a75d12e44a543084e CertiFriProofs.Qrom.CompressedOracle CertiFri.Qrom.IsUnitary +I 831cc25be17a11880de5364020946f30d2a4f513bb3bc4b5ebcfab8dccee92be Mathlib.Data.Int.Cast.Defs AddCommGroupWithOne +I 8519f93b343fca1460319866d702f734156c42573bc4fc781724c7fc1b021b17 CertiFriP3.Blake3 CertiFri.P3.Blake3.Node +I 852ee76f0fc7ea2ab4c83561bd5abe34cb6b1b72132e8562b8ba1d260e11221a CertiFri.Stark.System CertiFri.Stark.Circuit +I 85c2772a0c2b328c2bb2fc8b9d8477899633f122ea104b3be643576b2c5bfcaa CertiFriProofs.Exec.Stark.FreeTensor CertiFri.Exec.Stark.UStateTensor +I 869325d32f3a6a511bb694ef97d624938f4e752ee566516bf69f264bc1776fd7 Mathlib.Algebra.Ring.Defs NonUnitalNonAssocRing +I 86cbf9f9b7313230da9d7e664b3e42970d6adf1d9799ccda29fced7ed26a95a0 Mathlib.Logic.OpClass LeftCommutative +I 870b480ace81e92dca141af0af7680d7242e373a5b837b78102591b6bc48546a Mathlib.Order.Lattice SemilatticeSup +I 876bb506e3d28dc2fe986ced0e67bb22feb52f881e9ec100a0a784e2df1a4345 Init.Prelude Mul +I 878e3433f11f1b422d24c1f3ea144346c070460dbc783e50293e2da32999c8bc Init.Prelude Dvd +I 87b403521f084954e54f85559d280d7ef4277a6a2e92d23665cc161b5ffc2594 CertiFri.Verifier CertiFri.Fri.OpeningRef +I 88734cc610a9aac2119b73ed757b29dbc8d3638bbdf4e93114bd23e286a3b593 Mathlib.Algebra.Group.Semigroup CommMagma +I 8883a6803d0362b840f24040fc3e8a5f408fef00734b9bbe5cfee741a38c893b Mathlib.Data.SetLike.Basic SetLike +I 88d71e216ff1a3715614ea1d4788a41156be385e4319b582b5ce33da95a103f5 Init.Prelude SMul +I 8938b88a981f4bd0a61f20fdaa54a8e274f2b6fc41a6aa553c340a95f1c10276 CertiFriProofs.Exec.Stark.PrunedTensor CertiFri.Exec.Stark.BatchCoveredPruned +I 89f6379333f9a89dfde04294aec75efd1c35c614ee2076f086e71b38c77e3c67 Init.Prelude ByteArray +I 8a11e5f76ed62eee6ca10383e758ef62f98255c804bfb08152415a4aca089242 Mathlib.Algebra.Group.Monoid AddMonoid +I 8ac36adda4d74b4d7e9ddcf85eb1011eacebc16f4210084dc8f2244e7a094a84 CertiFriProofs.Theory.Oracle.MerkleFrozen CertiFri.Oracle.SpongeQuery +I 8bf21a1fd5bb79e1cdf418bb7f40efe613dadd35ca6ab99e281d3050e41d28d0 Mathlib.Basic.Logic.Basic Fact +I 8bf8c5f3d10a1730c9352020524ad4221a27e68692059de17ecf13a11a6cc644 Mathlib.Data.FunLike.Equiv EquivLike +I 8c1d1b42d275e1d280430774eb1e158cd703bf68ca4f4c56ac1f3cbdf1b610cf Init.Data.List.Basic List.Pairwise +I 8c6547ac6735810574e390240dd7fbaba78b8ab089a44bb04bd6350a356f8425 Mathlib.Algebra.Order.Ring.Defs IsStrictOrderedRing +I 8c8303ca7172c74cd138a460c7a242856fdb090edf617aed2112d952f58f34c5 CertiFriProofs.Theory.Compiled.Read CertiFri.Compiled.Slot +I 8d424f033a191e5626d201e9b10bd67048a4fb502abc074972e490f4fd52e70d CertiFri.Stark.System CertiFri.Stark.Proof +I 8d89df6a08fc48d8817276c5f0dd40e28948093acc1750ed3fd15212a1a60ca6 Mathlib.Algebra.Ring.Defs CommRing +I 8da539f5c3887f06518b547ae551e48dc5f0bfbe8581e4f33d29672da366545b Init.Prelude UInt32 +I 8f1f8ecc110e8bc36b184cf1584b96f2ecf0d3dc0adacd3c5c1c6a82454010bd CertiFri.Challenger CertiFri.Challenger +I 9113710124424b062db525773e04be139e8de012243c6da16257127f894cb571 Mathlib.Algebra.Ring.Defs HasDistribNeg +I 916af0acf86938c3a30d22d45e36d6361ec64875974683562fb48a805b07d4ad Mathlib.Algebra.Group.DivInvMonoid SubtractionMonoid +I 922cc55e6a009b0f708850000e0ea23c1020c84fe837b6ee1e96f959dd415544 Init.Prelude HAppend +I 92eec682b83092db174f1f4aa1a10654988e6a26d899af1baeaa9e32d071d86c Mathlib.Algebra.Order.GroupWithZero.Defs PosMulMono +I 939cc418e260b7e16f95e360875ce51ce522f8cacb065877dcd652963dbda16f CertiFri.Proof CertiFri.FriProof +I 9437387de38093c86fcc9323fc53dcc4b55227dc3c91384831e72a83e0085c8d Mathlib.Order.Notation Bot +I 9459f5f0dd5c76c38c8cded001307493ae000c3f8830f14578e6323b81bc86f6 Init.Prelude Substring.Raw +I 966a4ea2f339b463dcf46834b33a30ec507c8d7a8e3fcd29140d881dcfa6744f Mathlib.Data.Finset.Defs Finset +I 96a7a24df88fe96636856f28986ec3c3f5600cbe882a4c4776d443eac3d5709e Mathlib.Data.Finsupp.Defs Finsupp +I 96f0490c62d9954e25fd94dc3cb2dc3a3a9b3fd0d62f07ea85c29b3b5882510a Init.WF WellFounded +I 9767fd401deaab67f207ad81919627e32bb90e81bb0f08a292fcf2ebb0526145 CertiFriProofs.Theory.MultiArity.CompiledTensor CertiFri.Compiled.MultiProof +I 979f9d9ecbfbdcd1da0151b409a3ec65c625a2bf0bbb6cb74676eb01650a6c6e Mathlib.Data.Rat.Init NNRatCast +I 97b6ab41e9e80150a83c7227b816e911992373e95517737e5d24fdc4473ead35 Mathlib.Algebra.Group.DivInvMonoid DivisionCommMonoid +I 9844afe8e57e9efe74e03b3ed5d1c49f9da265cbe9e70a40a7542fdd28549d51 CertiFriProofs.Exec.Stark.Preamble CertiFri.Exec.Stark.RowBudgetOk +I 98f8b90ecc61f8505e89ee699043ee3a35946d77afadd0bce04ac9fee5bf21d9 Mathlib.Logic.Embedding.Basic Function.Embedding +I 9bbb669fcab30afd84d981c03c1c4300cd5707b1d4fcae73a5090bf129f1256e Mathlib.Order.Defs.PartialOrder Preorder +I 9bc97d8a9098afcb054ac9d2f9b551398c7aabc314ffec91bcd5dc9428118881 Init.Core ForIn +I 9d79bc9650b3eacc3bfc4da60fe0362349fcfcb563131fffdfecfebe250a88ea Init.Prelude Div +I 9d81b92b439ef6d3ad5fdf0268353262a60c80523d2b897c9007d2dcad2e38c0 Init.Prelude Pure +I 9db82fde155073247043631d4cf62da320ae16dd971703e18e9a0f3e7b3d9545 CertiFri.Verifier CertiFri.Fri.TensorChallenges +I 9e23f766b7dc137113a4c1ffead7a98499888c6deed6ad06376b7decf235d7b3 Mathlib.Algebra.Group.DivInvMonoid DivInvOneMonoid +I 9f807ae70c005643ed04c4049d63aa044c44894cde115ef52bf3a988a8e62e28 CertiFriP3.Digest CertiFri.P3.Digest +I a100beda29bd080b84ff20b7da1cd5a7a7cc8d411ade3e68a16ba09c41f6c814 Mathlib.Basic.Complex.Basic Complex +I a1a7ef33bf58449f60d56ff20cbc7fb5aef3aeeab6a7ceece989efe155032c6e Init.Prelude Inv +I a1e3a89865221ab735086e2702f9dbac0ef1929c08d5c51f753e2be8053eefba CertiFriProofs.Theory.Stark.Air CertiFri.Stark.Model.Columns +I a1e71b34c1227ab712a4ea83987367521b159d7f014318062763ffa398f2a32a CertiFri.Stark.Verifier CertiFri.Stark.Selectors +I a25e60e7fdd0789c864195cf87a5c9863e5df0cce1889ff65a567b11739ab9e1 Init.SizeOf SizeOf +I a384bc5103ee5b61ef65bbaa1722c1abefd5a96e9b40820759d22dcb2fd03ec3 Ix.Cert.Release05.SecurityAudit Ix.Cert.Release05.InnerV6ShapeBounds +I a43ae46976468000638f845407a6648722c8ade1861828f022d696f4bbf86981 CertiFri.Mmcs CertiFri.Mmcs +I a49659df864b1460a56a6f9c2bb3c3d6be6abaea1184a102a94c23744002ec69 Mathlib.Algebra.Group.DivInvMonoid SubNegMonoid +I a4a2244eca4087101ec061e8c12b3214525460e3de58638405b2f4b0e04fb76e Init.Data.Int.Basic Int.NonNeg +I a4b2090969aecb8e081050fa79fd421c407b5ff9656838059d5fc4a7d7d4d15b CertiFri.Field CertiFri.FieldOps +I a5d690976bf62771d537526963ab4cb0c91329d57831df7b5d5b3a368cdc6ece Mathlib.Algebra.Ring.Defs Ring +I a60e7546cdbcfdba6689adac90843cfaba26b0c250ab88a84e8a788a8e1b106a Init.Prelude Nat +I a833de2e8881082272a0e00daa64ff224261d5bf74d25a2ce958b144f73d1209 Mathlib.Algebra.Group.Semigroup AddCommMagma +I a862f867f15539d80d70a771c24ac9d1089527589c6e6bb7ea66200f33c39bcb Init.Core Std.Associative +I a942ce664a04e449e0f8ce1609dcedfa1c8eaa4758e7e63af07d8589791abe75 CertiFriProofs.Qrom.CompressedOracle CertiFri.Qrom.QQueryAlgorithm +I a9664a33f91a95fc2b12e3dff8e1f49f354cf79d49aabf8247b624b354c534eb Init.Prelude Mod +I ab3ff179efcbaeec5db38e07bf672b0a693466f27f82f986779bbb431df89a4f Mathlib.Algebra.Ring.Defs NonUnitalNonAssocCommSemiring +I ab6584f518dfa8b5f8d7c25003018019e39ab4ee5efa0b4a84ed173532907bbe Mathlib.Algebra.Ring.Defs NonUnitalCommRing +I ac3874f314aa83c84879c0f74342998ac691573466ca1a61945c5acf2b5e5c39 Init.Data.Array.Basic Array.Mem +I acee430f6c41cb352af1a38493e6548dcf40fbe8c3f9a200863ec169826edda0 CertiFriProofs.Theory.Compiled.Verifier CertiFri.Compiled.Proof +I ae2c836e528e110aa1f7301bf2f86a169626786dcafab3a8c87dd6a7bb68116b Mathlib.Algebra.Order.GroupWithZero.Defs PosMulStrictMono +I aeb27cd54f90ff74538343b123f8b86c1023d1d9d66f01fb8db01811393db0c8 Init.WF Acc +I afb6d2364f6b019352d979806b2c0f068f9c80e2118dcd45fa07072948f2a0ce CertiFriProofs.Exec.Stark.FixedKey CertiFri.Exec.Stark.HashIface +I b037ec26ea15cbc3fe6b7c4cb7b7c37657a427a953f82eb7d09a0b3f15a7c3e6 Init.Prelude PProd +I b0739ff0bb7a48e0f4b57b3b4e418343845f4e0e2830095ae5b4ce5ad2743b5a CertiFriProofs.Exec.Stark.State CertiFri.Exec.Stark.ShardView +I b0a0a7548095afb6a24d3c3bb325f55e027c732089ef6734e8b32e69cc0fbbd6 Init.Core ForIn' +I b33edb756344c211d793528a5e6b82d912d2bfe557853cd8277e52fcf0d106f6 Mathlib.Algebra.Group.DivInvMonoid DivisionMonoid +I b4a63fa0e8233111f15ba16e6625368dd4e3996a115d5ee2eff0190af6f293b8 Init.Prelude String +I b5b023e50eb801c26041d3ef665a9660ef5ac1295e87375655eaad1bbe6b6022 CertiFri.Stark.Verifier CertiFri.Stark.Challenges +I b67a37d4fa0a1851505b4efe16c4afa3361d0ca395b8df1115846701b9a74484 CertiFriP3.Wire CertiFri.P3.Wire.KeyParams +I b6ea63ec1eea3878ec6a6bc4779bebf3128cb663f084a8e8afb94c28355bd5e8 Init.Prelude HMod +I b7d6e0ba023f6c01407075e8f86ff78b89322a28a91044bf9855a8aae3fa67ce Mathlib.Algebra.Order.Ring.Defs IsOrderedRing +I b816addbd6d10b12ca3f914656545a633bb5af102819fc006e95b886225e3eb5 Init.Prelude And +I b81a1a9a1e83f002b4f15ae7540c6a940db67517b491e7e4ec007e14f0f58d87 Mathlib.Algebra.Group.Monoid AddCancelCommMonoid +I b83f1b871a0fc24c2a08d4aa76c1bf4e5ebe36e85fbdd2d0d8641ce8dfc66768 Mathlib.Algebra.Ring.Defs NonAssocRing +I b8b40818dd6ceee8ad1214eb022c4cdb7fe8a43df307711cc4c9282b6891be75 Mathlib.Analysis.Normed.Group.Defs Norm +I b8b935b2c6e2d5616b6b98ca3b79022e1c3664aab6af60065cbcafc1ee787652 Init.Prelude Lean.SourceInfo +I b92d97c508dd03e9fc9b89730505512354725dd0713c4723390489f802b45e5f Init.WF WellFoundedRelation +I b9edc3a9b7f285f4f652865619ac4288ff47f3d4c5131c9cf8b6642a84d93722 Init.Prelude Zero +I ba75c514719227925b63203d06665e63315b1cf1302f852dfd0697f1df378184 Init.Core Iff +I bb0601ae97c5116db7572ad6f1bea8a25fad6919a70f8509fa3ba5effb4acd6a CertiFriProofs.P3.EncodingInjective CertiFri.P3.Encoding.HashCall +I bc41f9e609f81984c9328cc11bac81886c4ae91f950107ea7797217947bd18d3 Mathlib.Algebra.GroupWithZero.Defs GroupWithZero +I bd02afa1e46ff9dac71bf86dbd860bfc60643c76cb3ffab1df408a812bbd900e CertiFri.Proof CertiFri.BatchOpening +I bdeed233e6187a45eb5d24b384831e8521106b6d7ed9ad797e7d5a5390d19abc Init.Prelude HSMul +I bf72de5ae70d6c62afe850a768f0d5cf0030576bf75c223867b8f9efa1f87a5a CertiFriProofs.Exec.Setup CertiFri.Exec.FieldModel +I bf916b29d83a0c09d9255bd28903d76cd528743daabfc2550f52bca3692b89a3 Mathlib.Algebra.Module.LinearMap.Defs LinearMap +I c023a5276833b116d475ce37f30dfbd7926b6da198609714fd5980d94c20567a Mathlib.Algebra.Ring.Defs NonUnitalSemiring +I c288becc4b4938b952a5e6c2c68571e9edc8299683de19b333d0ed3042feff80 Mathlib.Algebra.Group.DivInvMonoid NegZeroClass +I c2dcc352a79c8ff8011f257bca576aec4ae81442de19d16cc9ea1b2cb0f11f68 Init.Prelude Bool +I c358bcb456e9e0598a246a59caa3bab20db7ea8e01c5fd59be803336be5014d4 Init.Prelude HShiftRight +I c3e187a743130214a8068faff98a65e53cbdfc89a179e6b02adf439b92019620 Mathlib.Order.WithBot WithBot.LE +I c5764f549b36a86e8094e9967da6f37a6622f245e771c8c7c37c53f2660faf4e CertiFriProofs.Theory.Oracle.Basic CertiFri.Oracle.OracleComp +I c639fe12c93e16233bf9a41e89730edbb00ca3c0df9ccaf8f3ee31a4580c8275 Init.Prelude Lean.Name +I c6a436d837b966035dd0c685c5f6542f9ca6499b674dae6bc1eda014b742db09 CertiFri.Merkle CertiFri.MerkleHasher +I c79e3b228a405de12e1a927766b5f7cece719a10d875a0734602883733d0c2ae CertiFri.Claims CertiFri.CommitmentOpening +I c7cb7eae43b727f61259ecc81395aca0170dbb6e12044e3625c404fe421dea56 Init.Prelude ShiftRight +I c930567e6b83e034e00e27a4c79b11a6563a194cfcb5fbb0e42d4c3614597f66 Init.Prelude Nonempty +I c979b94cc44562ae2512b027b1af541fd5861abf0d412b39b17b9b6c1a4b291c Init.Prelude Lean.Syntax.Preresolved +I ca9728a2269705d4d42db91997cb2f30a226bd758e1ae8407b310f727cd8d063 Mathlib.Algebra.Group.Monoid AddCommMonoid +I cace2c1c3c054c11e2fce7ef03c4b6d67f71fbc0261261881a139c57a21d4743 Mathlib.Algebra.Group.Monoid AddZero +I cad3bb39dce440db48f43b92e311db4cd7f67f089f2d1e16dafb734a1355cdb2 Init.Prelude Option +I cbe2247f2406a5c5c65ee443bb45dac4cca11b73e4b6a89eab62acd3ea4c7b4f Init.Prelude One +I cbff35e12e059b1b10a591fd90de07c802af6448010bfcab8bff0df2c6145e9b Init.Data.List.Basic List.Mem +I cdb4a8afbc4471b012697139143400dc50f0cb48d846042c9156ce272ff19cdb CertiFri.TensorBatching CertiFri.Fri.TensorSchedule +I cebd508639e8a6466c7e0692fa471a70b5f464cf88a5c783be07afe729c30458 CertiFri.Proof CertiFri.CommitPhaseStep +I ced64ef355c5cc9f3271c22f642e20d33a2f1a600eb1484fb056fc87a6528648 Init.Prelude HMul +I cffb63845dbe3f466da110ff63b375a1797201ab0d0267140b3f535569df89af Init.Prelude Functor +I d082a8567c9f0fa64499b8af8b4ba561bfc03fb8099fce839c00db210784c8d5 Mathlib.Data.Fintype.Defs Fintype +I d2525ecc103fe1a7cf0d2d1eec5fd977ead599973cad3f6c508ce5d03681b2fb Mathlib.Algebra.Order.GroupWithZero.Defs MulPosMono +I d3256833ac73801d54c36292bac0ae2843806a2423516b1620292598298d35d6 CertiFri.Mmcs CertiFri.Dimensions +I d33d1bf42a2a87fec9003bfba6c298e6897be3b2725ff39164924d9df42e7983 Mathlib.Algebra.Group.DivInvMonoid InvolutiveNeg +I d3b3d68ba810db34ae57aa09fe7b3e3055bf235bd5fa147f3fef5dca933c02b9 Mathlib.Algebra.Ring.Defs NonUnitalNonAssocSemiring +I d3c8951c876584785725a3bed8a9757595bbf4a049850e62fa638e97a44ba48e CertiFri.Stark.System CertiFri.Stark.BatchProof +I d58ccf6c0d438ed0ac7726bf956acfaeb9f638a84c181a4d969a6eb151300d1a Mathlib.Algebra.GroupWithZero.Action.Defs DistribSMul +I d6129c6c31d83b04101e34da7b0abd5b8dbe4c7f896e40cdbaad44fdf00647df Mathlib.Algebra.Group.Semigroup AddCommSemigroup +I d7956d6e6377b6daadd683d98e4c397d3154b68f05dfa1c38b771f6c929c4595 Mathlib.Algebra.Group.Semigroup IsLeftCancelAdd +I da961e930a60ef2fda5d2852e9dff41745f424ba887f4b3385666b757feaa965 Init.Prelude ByteArray.IsValidUTF8 +I dabc2d87bfcfccf71bed567970fb9aeba1d358f80f530106695f84f78edd52da Init.Prelude Nat.le +I dadc9ec1f48c1899acf8aa4777b7fef7ab3ab87e2e434c3518595818ae60ffc8 Mathlib.Algebra.Group.Units.Defs Units +I dba78b2f84144efe2408d33a671ee7d09f507aa4fafdcd3f5a1da6e02e722cb6 Init.GetElem GetElem +I dbd2a17f4bd822c7a27139c37a4d7b0a825f68cdb0543bcfb97da1935ba1a1a8 CertiFri.Stark.Graph CertiFri.Stark.Lookup +I dc01fd7ea75020c6d0b1cf3d476705906fa76bf375c5981a32cd187eb36c0612 Mathlib.Algebra.Field.Defs DivisionRing +I dd02e45d77f81687a3dffa69eb8f78675c6069a1792e41a8a5c71fa65f3c1a9b Mathlib.Algebra.Field.Defs Semifield +I dee17a33ef9470af56cd6714792aff838b813e997551a5b4b437ecf2dca2b4c4 Mathlib.Algebra.Order.ZeroLEOne ZeroLEOneClass +I dfc120f7053e96b0d08a790f412e7541e8007b72e34eb8c7980bba39ed470ce6 Mathlib.Order.Lattice DistribLattice +I e327a1cef762c932559090cef6ad125a50cf5ba391e7bbd0d58e4f69aaeacedc Init.Data.Int.Basic Int +I e361c77baa47005fc55ad687d7034fe187a8334d3a4e0cfce03530289497ae03 Mathlib.Algebra.Group.DivInvMonoid SubtractionCommMonoid +I e440497a2975922f47ef90b363caebc9b9b6150660ddaaed924e9923acae1081 CertiFriProofs.Theory.Oracle.FiatShamir CertiFri.Oracle.FSQuery +I e54b55b271e2b00d1ef6876a6e9e01b82bf7d09128d0dc82283a1cca93f1c061 CertiFriP3.Pruned CertiFri.P3.PrunedPaths +I e60a155becfdd0ee9e53f8689400fe1bb69afebd06164e6f00640c8463a7a752 CertiFriProofs.Theory.MultiArity.CompiledTensor CertiFri.Compiled.MultiParams +I e6b92d3f3e387427264ce813a5a3f47efadd86aca924972e47ab2c09ccf38b44 CertiFri.Field CertiFri.ExtensionOps +I e73e7c8b3a71d52b12810da6145ef2f9dc8a1bed94e2492d0d702d023dd4bbee Mathlib.Algebra.Group.Defs AddGroup +I e7ad4704f8834edd52162910f21a4018945b8cdfa83c29297441c2be73962c07 Mathlib.Algebra.Ring.Hom.Defs RingHom +I e7ba0fc62d986c910825392efb90b7bde8d9ca64396ce20cc8222afbe18fea2f CertiFriProofs.Exec.Stark.SpongeGoodLogTensor CertiFri.Exec.Stark.SpongeStarkMsg +I e89ce425ced766514dfab06200267908cd7b7a285119fede098e285ef3080498 Init.Core Singleton +I e93b40bf16f9e66090024d24f09df83af7bf425cac253748c53f3981eb232cdb Init.Prelude UInt8 +I ea4675eb27c8ec3b37cf737d142687c4141f77424ae05bf6f2bfe92d4a6a984a Init.Prelude Seq +I eb07387df5c8d36b648d4a462b329a515a9ee72b0cebc0a47c9e8d7f6334f915 CertiFriProofs.Exec.Setup CertiFri.Exec.WellFormed +I ebf7f9f3451a8e2fb3a2221250655d7a416d9e4366800424963a89a199765870 CertiFriProofs.Theory.Compiled.Read CertiFri.Compiled.Params +I ec1970210b9be229b3c76bbc6ef99e285700c9ff63459ac2d85a98775eb4d7a9 Mathlib.Algebra.GroupWithZero.Hom MonoidWithZeroHom +I eca30688ef07f75e017590c8a4bc192353e587423e934709368fb25ecb38840d CertiFri.Stark.Graph CertiFri.Stark.Node +I ed3392bdc4034968d84aa218416de1b4c544ef99e147496e5a065279dd138545 Init.Prelude LE +I ee7904a728a7c02514c60801dab52e8706244ba68444de37870f9b05619add40 CertiFriP3.Pruned CertiFri.P3.Pruned.Node +I eea380140f7b023b672e20c77f1b30e371798c932a1388de3e994eadd392d058 Mathlib.Order.WithBot WithBot.LT +I efe0e31a96ed18e41db805dbef629e42b22c56437ac99aa1f935e3741fcce5b2 Mathlib.Algebra.Order.AbsoluteValue.Basic IsAbsoluteValue +I efef69c2948e485010ee8691c78cd1743816153e27c4c83fa047d3ba77489e4b Mathlib.Algebra.Order.GroupWithZero.Defs MulPosStrictMono +I f0db54c57ed0243df5098ab9092e32cab3362ed0aa1a26d3282daab60d95a06e Init.Prelude HOr +I f22c1787d139904b29693e54b9122abf701bb3fab7f1f4c9a923492c9f2cf993 CertiFriProofs.Theory.Compiled.Read CertiFri.Compiled.Msg +I f2812eec2ebb3c60b43f93b77b1f945d430746ddb54d2ca74c8cd3bd140cecfe CertiFriProofs.Exec.Stark.StatePinned CertiFri.Exec.Stark.SupportedP +I f2b10b40944df651113c5063319668259a8c79651c94347b6a2ea68f8a506b00 Mathlib.Algebra.Group.DivInvMonoid ZSMul +I f2c20ec4319dd7f25776a201b7bba9a8d2495e08c9908b72065310976866b11f Init.Core Std.Commutative +I f6221175693074454b6a0bc1865f06ff78ad8c385baa9c9e2d76bd4fd0773882 Init.Prelude Fin +I f93abbe8cba182fcd35203d671ce119e915b6a7ec217e9e03ed150ec97a0962e Mathlib.Algebra.Ring.Defs NonUnitalCommSemiring +I fab95bc06b7415741f9092fa8d1d6f1dd7030d7d46763da5660fdb2e8492aa11 CertiFriProofs.Theory.Oracle.MerkleVerify CertiFri.Oracle.HashQuery +I fc8626c1ccdb27a89b4a249b42fc68d42f1cbce2e30e8f0b06b0f28753c0b70f CertiFri.Stark.Graph CertiFri.Stark.RowValues +I fcc9e79907812cc7808345a4b58ac1d0e3faa7da3e6133213f0a9ef1b8c74ab3 Init.Prelude Sub +I fd6d36fdbf3e7a1e9c55eca6cfb9439ec19b23fb64a2ceb31559500f9d957031 Init.Prelude UInt64 +I fdb3a3473497cdaa1ddf602bb106a287a65d6f1deea7e66400282d20f5f54630 CertiFriProofs.P3.WireRoundTrip CertiFri.P3.Wire.KeyParams.WireOk +I fdd3a5d8e0bb3aef9b66214dc4e55d79bfe2b2ad88b927a31a58eb03d25999d2 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model +I ff5e2fbc4b79964450149c88672c5c2fd8a9654c80ad4a731f4e87b769eb7143 Ix.Aiur.Parameters Aiur.FriParameters +O 0472f54b4108c579821fa4d0e24bca123f67454ff195cd2aca57db76d21e01bd Mathlib.Basic.Real.Basic Real.wrapped._@.Mathlib.Basic.Real.Basic.4282658333._hygCtx._hyg.2 +O 04e129ec9877db7c208dc9b72d35730ed0ef38f34fefe6478b42544865a8552d Mathlib.Basic.Real.Basic Real.wrapped._@.Mathlib.Basic.Real.Basic.326038627._hygCtx._hyg.2 +O 2b71f7cf68dbbf0dedddac587b1c46a44e3a1592909b5583fba7dd727eb9fb2e Mathlib.Basic.Real.Basic Real.wrapped._@.Mathlib.Basic.Real.Basic.2348678026._hygCtx._hyg.2 +O 44c1cebc5c828c163ba78432faddcc8f9cd85ef40e488e6041c51f0aaf427bf9 Mathlib.Basic.Real.Basic Real.wrapped._@.Mathlib.Basic.Real.Basic.6358291._hygCtx._hyg.2 +O 5b735273b3e0a02057e71495838529a36b5251306c8768540a825706dc02184b Mathlib.Basic.Real.Basic Real.wrapped._@.Mathlib.Basic.Real.Basic.3158186288._hygCtx._hyg.2 +O 6ee89e6ad0fa6f5066b39433642e4bd9bb1b9e57b4699a326b9d19a993b29472 Mathlib.Basic.Real.Basic Real.wrapped._@.Mathlib.Basic.Real.Basic.1259013419._hygCtx._hyg.2 +O b20f9fa695d5fc650d2af8cb550ae15e49cca7ec803c8e2b11d1466b9bab7db9 Mathlib.Basic.Real.Basic Real.wrapped._@.Mathlib.Basic.Real.Basic.1745762101._hygCtx._hyg.2 +O c2af5ab11873043f3b6bbcbc189c795bf5140f968069384e2aff9136d2ad1a5c Mathlib.Basic.Real.Basic Real.wrapped._@.Mathlib.Basic.Real.Basic.2153608522._hygCtx._hyg.2 +O c44559a06f33388fbd42cd98fb2207b83c127e7a54a685424dfe91e9f7729196 Init.Data.String.Bootstrap String.Internal.append +O c5337c2626c069323d3d823b37a58304aa8425ee45d7c4224bed1557e97544dc Mathlib.Algebra.Polynomial.Eval.Defs Polynomial.wrapped._@.Mathlib.Algebra.Polynomial.Eval.Defs.2849575019._hygCtx._hyg.2 +O d24a0be5fd73c8521839cf405aea6467ec14c05461964a9369b1b2322e5d0bf1 Mathlib.Basic.Real.Basic Real.wrapped._@.Mathlib.Basic.Real.Basic.3335671075._hygCtx._hyg.2 +O f2307b32a882a1c18b432c0c6c4a6a659cca0905c67f0b997b86fdfa6f64c7f7 Mathlib.Basic.Real.Basic Real.wrapped._@.Mathlib.Basic.Real.Basic.339334276._hygCtx._hyg.2 +Q 23e0bf32097bd97b5f8f06bd57934cd1e941518a03a7dedc855b343101c33ddc Init.Prelude Quot.mk +Q 5529d83990e201fc45a051c9bd0dbb1a8750351ac2defa363855eb0ab29b578e Init.Prelude Quot +Q ec45bf13fd8ca8e828b8636750cf007d7abbbfc3078286e8f0e3484999f7345c Init.Prelude Quot.lift +R 02f84b0893cbc8417ee2cbd77a5b34ad0eefc460dd48157474ccd6ad836292a5 Init.Prelude BitVec.rec +R 0327f50f7ff3435fd6dcbae74d60fb395b1b73bc87798b864d169075544b60fb Mathlib.Algebra.Polynomial.Basic Polynomial.rec +R 16e3373ba8a7dcfddb59d87ff97bac557c75c00e5e366e5b00a97297f5127e0a Init.Prelude Array.rec +R 20d5ddf9ff5bcb11af62d08c1dbb4094965b0def2b8c3070aa3fd903fca8bffa Init.WF Acc.rec +R 20ee640c7e8f967d56474d4470744148bbaf3dbf27c31adece9582fe3b71d01b CertiFriProofs.P3.EncodingInjective CertiFri.P3.Encoding.HashCall.rec +R 28ecc38d17bca1480af4f2e4173f3c9a8dd793939c52a89b484f2346c06d3a2e CertiFri.Params CertiFri.FriParams.rec +R 3a84b4276a6009496d5987ae80c6aec2d8f8b73374f9951ac4c11f8f52076914 Init.Core Sigma.rec +R 3fbbf8d8fb34ca354e76ab682ab03d4b21ac6021a184afb665f3fa83de2b63a6 Init.Prelude Decidable.rec +R 3fd93e1f54f0e8d58884f42a8d31895482e0ee287bcd99a04f667c843d170473 Init.Prelude Nat.le.rec +R 467853591a00fa66bd87e44e40512084abaa55ab6058c6b8e7878d5c6e1aab04 Init.Prelude UInt32.rec +R 49cfcec0019831246527ef3c0fd6fddc3b66eb183808d27a08ac1b1388944560 Init.Data.Int.Basic Int.rec +R 4f73826b6fc562c4c30d0c66e6dd40b77bfcc589167355de128fb445ebeab40f CertiFriProofs.Theory.Oracle.MerkleOpens CertiFri.Oracle.MerkleRO.Dig.rec +R 51d30cbfd61ad8c1d8e0c4ead50b71da786545a9f2039898892c3c8d392fd3b7 CertiFri.Stark.Graph CertiFri.Stark.Source.rec +R 562cb0658b5dc120c452cb4539106c79977a116f9ddf2b9f9817ddabef7a15c4 Init.Prelude ByteArray.rec +R 5e6f794ed2213d359f76e7e5e11994a4ee3533dadc8f4f7d6f30d7515e2a71ed Init.Core PSigma.rec +R 623f761573f8baf3d3895a8c6110750993be51ec230976e8707cc9634e5c6361 Init.Data.Rat.Basic Rat.rec +R 6830d093d0f8745b17539f65bc22d778b2076832a150d73c69d55adfd4207ada CertiFriProofs.Theory.Oracle.MerkleFrozen CertiFri.Oracle.SpongeQuery.rec +R 7023dcff92bb7414c7c90170805931f1451d1b74e06722cb0730189d80437ec8 CertiFriProofs.Theory.Oracle.MerkleVerify CertiFri.Oracle.HashQuery.rec +R 7547a26494f5fcf1766d2d372ab1a2d2f5b195d31e3eae8dd825c0f0e8a1945d Init.Core ForInStep.rec +R 7913dc8cfc74516e5e98b3587fb3b9b87098932e9813a4ed431ce1382c3ed383 Init.Prelude Nat.rec +R 7c16ee082a3f421650f20d47be73f2b980d05f17ed01026da56297f08030bf17 CertiFri.Challenger CertiFri.Observation.rec +R 86412b0686aa9a32bd7431b1f47d8535ba5b9e95f3e5d1995b25ceed431e56f4 CertiFriProofs.Theory.Oracle.FiatShamir CertiFri.Oracle.FSQuery.rec +R 8920a80ead8c0214865c282201568159eb516878502cbfec47c7328eb77376d3 Init.Prelude Empty.rec +R 895e45be191394d8cfdda04fff85d7ec93ef8abc82e9555873c46183b338cb5f Init.Prelude Eq.rec +R 89a6e6203103e6a476ae32b437c2ccc26d196ac54fe63acc484ab3fcd9ac4ca5 CertiFriP3.DomainSep CertiFri.P3.Blake3Domain.rec +R 926ae7fdd473537c32545372917fb2482cb53a3f99ce913f4b31338fc0fa9be5 CertiFriP3.Pruned CertiFri.P3.Pruned.Node.rec +R a77f4abf080571487ca3ddea33b7c5a7b4029876ed437a48cb59c29398b87eff CertiFriProofs.Theory.Oracle.FiatShamir CertiFri.Oracle.Transcript.rec +R a9de825744728c675ad532c84c041952875c1cbc509fad4b2be85e67a79f666a Mathlib.Basic.Real.Basic Real.rec +R b7a55f8400412c4eee3214680de66f0d15326f01fc53360c4f37a7c5a2e08c60 Init.Prelude List.rec +R bc74e270617fe44cab1e553a31e4a071c86b394a164f2e83784a74f7654f4204 Init.Prelude Option.rec +R bd004ef9904c4cef4518c14bfd96d763540b4d4de9b4ea8c30389647e82ef717 Init.Prelude UInt8.rec +R bdf7df41379e1923816fee05694f246a7fd6ac07035dc9afc04b2df2f71bac59 CertiFriP3.Digest CertiFri.P3.Digest.rec +R c502a1140d7af89effc4d4fd76b065b15030a5dbf70f8b66bb19c4103cc99a1b CertiFriProofs.Exec.Stark.SpongeGoodLogTensor CertiFri.Exec.Stark.SpongeStarkMsg.rec +R cd57be1083df8999b66e335c28ffad4e1f1d3ebe44bcad24501b498386d82a31 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.rec +R d15705f69af25fb74cc60bf3660859fd715008db2a272bbd05b8c753defd6e39 CertiFri.Stark.Graph CertiFri.Stark.ColRef.rec +R d81bc36bdb68e5d8ae06421cdf5436e87652881d1f0f9d71687f795c5f31de4b CertiFriProofs.Theory.Oracle.Basic CertiFri.Oracle.OracleComp.rec +R d8bf9f014b2454d557edcfd4f4a704069178b8f5a79b7a98d6ee694bfdb316ad Init.Prelude Fin.rec +R e07c56f862eef16b49a062406c1639cf85ad7d56fb782039ab22a7278d0c5fa7 Init.Data.List.Basic List.Mem.rec +R e10e4e0c578fa1b81ceb011d980d1d12a89032a4bd6a778e2bcc882ce7231156 Init.Prelude UInt64.rec +R e3b9a4fb9f7a27bffa219ef1e88a9719c8d65a8d65581cd05dedba8a52bdc51d Init.Prelude Prod.rec +R f4791970012f6e6103d82f5e150fccd5474cd849a7fbefd9b25305d43391fa83 CertiFri.Stark.Graph CertiFri.Stark.Node.rec +R f7840c120ca7f12ec08bd18f8ae26b78c299aec3195bd821c8a77d6ade7c6662 CertiFriP3.GoldilocksExt3 CertiFri.P3.GoldilocksExt3.rec +R f8eab5de0938f024f2d69ebf7371105c8f331436a288daa8dc91ead2ff240d90 Init.Prelude False.rec +R fee41dfd6c5c54926bd19f8891250419f17d5ade32148cf5f2fa1c2d89a2021e Init.Prelude Bool.rec +R ff68643c3bf687fcab9b1d1a315199ce488bb07d7d281526cb7108382023eda6 CertiFriP3.DomainSep CertiFri.P3.DomainSep.KeyedInput.rec +T 000ee344a2055b6702b38f7995c0c4197c83f4daf7279a00a69e44e0d30fd4ef Mathlib.Algebra.Group.Defs AddGroup.toSubtractionMonoid._proof_2 +T 003802b8e31593d146175717a3a31d31dbd6afc1e7458d9c7e20b1334a492b3f Init.Prelude Fin.eq_of_val_eq +T 004e3bf5670a1b0f5fe367db66710d5b2202685ee556b98f62ce4da492bb9592 Mathlib.Order.Basic PartialOrder.lift._proof_2 +T 006bc6e2dfacd811aa6c35d4af663eecd9e771041eef7f5090fe2191e4077e45 Mathlib.Basic.Real.Basic Real.commRing._proof_15 +T 00cabedfe686573d65d5e624b3875034bc49966a7cc99fa91016ecbfacabcdf3 Init.Data.Rat.Basic Rat.add._proof_1 +T 00ed05202f00cbd13a780d502e283cea544b13d94aa8c99be600d88a5b4f3e35 CertiFriProofs.P3.GoldilocksExt3Model CertiFri.P3.GoldilocksExt3.starkModel._proof_6 +T 0100b1337ef9d6bc76fbe37ee1e9451cf4409e971ee6b2ce1a0e45438a6d515d Init.Data.Array.DecidableEq _private.Init.Data.Array.DecidableEq.0.Array.instDecidableEqImpl._proof_1 +T 0110dc132318ec94159e9ce25d7f91e712a2a04863b515f6c7833e4edc0917b0 Mathlib.Data.ZMod.Defs Fin.instCommRing._proof_9 +T 0129fd785ca8beda7fc35753f3750cfb8587dd3851e305be4b24832706176276 Mathlib.Data.Option.Basic Option.some_injective +T 0160d96f421622fb52e4a3c205d9cc9ee566af25c1c0d37aa3c7e6dabdc2e0a0 CertiFriProofs.Exec.Setup CertiFri.Exec.WellFormed.shift_ne +T 016e04f629fbaa2a09e5167727b3939ffbe7f13ab1fda28382e2a34b17fc66a0 Init.Prelude UInt64.decEq._proof_1 +T 01753555819955791ec390f400f0bd74fcf48460bb7cb22ce9a30d8436194cb3 Mathlib.Algebra.Order.CauSeq.Basic CauSeq.ofEq._proof_1 +T 018e121f6cd0c3bff20b89cf484b728a92ab651a9ace19f29ffc40a19d077f09 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.equivTriple._proof_1 +T 019a6057d2acb08ed36b186b29d36f6b6a01ba00a14a86a3b72715be8677f776 Init.WF WellFounded.Nat.fix._proof_1 +T 01dfc4f549f8b90c772f9562460c631dc9fd932a80ff62b912232ab90a262ad6 CertiFri.Challenger CertiFri.instDecidableEqObservation.decEq._proof_10 +T 0204b902bb5fe59e9aed1d1f408d09e9dab2d255ae402d2289b9961e5f5a2b7c Mathlib.Algebra.Order.Nonneg.Basic Nonneg.mul._proof_1 +T 023e3f0bac44596273d59796cbf5c22bf431ee3b4bb094d29a2e7fb2007fd408 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.GoldilocksExt3.toModel_inv +T 0245db9cd035e9e1faaa53188f51e7c2d8ecefd9ed75b8320889e135a287688b Mathlib.Logic.Equiv.Basic Equiv.subtypeEquiv._proof_6 +T 024a2d4f7c838719e8391ee86125eac97757fec60aafcb758ec2bd6538daacf8 Mathlib.Data.Nat.Find _private.Mathlib.Data.Nat.Find.0.Nat.findX._proof_2 +T 02606ea33f446d08b49773788639f13c5e270c67e12d4c2889901816c37544a0 Ix.Cert.Release05.SecurityAudit Ix.Cert.Release05.ep1V6Hop4_classical_rom_133 +T 02e446ff4a970bb9878a1667a94e1fa2d778114cd50954a2762c1962231254af Mathlib.Algebra.Group.DivInvMonoid SubNegMonoid.zsmul_succ' +T 02e82a9db91f913f9cb57063d1393f07da1b06fef014b8d3d567e2abaa9f4370 Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.semiring._proof_6 +T 032bdd68ebe9372d471a8664504d67e9dc581bb247ab5ee4bae56d88d0233b19 Mathlib.Algebra.Group.Monoid Monoid.npow_succ +T 03307cc4658b2d2e9f951fc39f86f6838cace952a53dd81462d865a31f5aa6ef CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.instCommRing._proof_25 +T 03553ab33917c4ff3115603230c8ecba5ec9b1c0f2152fad07e5e2cb06d913eb Mathlib.Algebra.GroupWithZero.Defs CommMonoidWithZero.zero_mul +T 03888aa0bc47781a3ce04a4adbe5fcf928fa2c5d6e1f0d11256e40494dc5abc2 Mathlib.Order.Lattice Lattice.inf_le_left +T 03c99b796e848bc76f5a222359193de955998141ac279b28ae3d869e27f5e46f Mathlib.Order.RelClasses instReflLe +T 03d36a6de23a47d45b54f8cd38a2077af917db1c16400d6bf63fa069340e20ab Mathlib.Algebra.Group.Pi.Basic Pi.addCommSemigroup._proof_1 +T 043296ef4eedbcbfda1bcfe9935c6df53b843de5a7fb2d46fa38db765accc081 Mathlib.Algebra.Group.Pi.Basic Pi.addSemigroup._proof_1 +T 0493610e0af63063923111964ab5d0e30d02fd586aafcd4b576a05cc6d890467 Mathlib.Basic.NNReal.Defs NNReal.instLinearOrder._proof_11 +T 04b3a43aa476e755b733fb83635bf5454d1d7e3f2d4e2c26630167d19509f403 Mathlib.Algebra.Group.Action.Pi Pi.mulAction._proof_1 +T 04b581d94d2755fde791ddc38b912f300addd07100b6669f731a1d49824ec697 Mathlib.Data.Fintype.Option instFintypeOption._proof_1 +T 04bda1e7562fe086b6618a96c32ce60996e169aba9c9d0b4cb9cf6f27d670c5e Mathlib.Logic.OpClass instLeftCommutativeOfCommutativeOfAssociative +T 050b241323ff6ca3cf569994a97b018474ebdd8a48438379c3218ffbd5b199eb Mathlib.Topology.Instances.NNReal.Lemmas NNReal.powOrderIso._proof_3 +T 050fedb19e4d441b3b0e3a405741b33f373ffdc60764512b8949ef4b31a57b71 Init.Data.Nat.Gcd _private.Init.Data.Nat.Gcd.0.Nat.gcd._unary._proof_1 +T 05124a4aa3c563c74a03bd4e28f811cde423ebda7e42c9ab982178431e0c0920 Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.semiring._proof_9 +T 05b7bd5ea90789a0adeadf83f54de2184e6797852356dc9f454e9a20768605c2 Ix.Cert.Release05.SecurityAudit Ix.Cert.Release05.negControl_release05_blake3_256_below_128_qrom +T 05c9622f28e5af018855a11544c96a5d5d2050b0d40da7dd027e03472a4d8cb7 Init.Prelude UInt8.decEq._proof_1 +T 05e3b8f402f9a9ebdaadff7ab0be9427298317c31b70a13883b8ed66248e472f Mathlib.Algebra.Group.Finsupp Finsupp.instAddMonoid._proof_2 +T 0614eeb285560630f8026f636534bfa4b9301678f6d27e425a1a9670f25be009 CertiFriProofs.Exec.Stark.State CertiFri.Exec.Stark.rep._proof_1 +T 063f7b131d0f6ed3e1490ae701513ed29fe27fbd8e71da8d636b3570eb3a506c Init.Data.Fin.Lemmas Fin.mul_zero +T 065f64d79c0c8452780ca3be28516f539b4914dd1e4652c208b47db6e0478f86 Init.Data.Nat.Lemmas Nat.decidableForallFin._proof_1 +T 067d3875767300c1ee52b8e3d13da6afd33da866372414504dc797a52b7e225d Mathlib.Order.Lattice Lattice.toLinearOrder._proof_4 +T 0686669a6e7178db5fbef3d7744e6a54b11605a4a24f37d5eca47f2452a0a6f5 Init.Data.Nat.Basic Nat.zero_lt_one +T 06b562eb63e49301e7bc49084f7842e8aced2dc520386a475af3caf4c28603f2 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.instCommRing._proof_11 +T 06c7eea8a52ac36033ed2e027f0552aa8bee0cbacdefd07c26426edb67502272 Mathlib.Data.Nat.Find _private.Mathlib.Data.Nat.Find.0.Nat.findX._proof_5 +T 06d7c6f183797da1f0341809f350b0b165b80f288f057565905209d9594b59ef Mathlib.Algebra.Polynomial.Basic Polynomial.ring._proof_7 +T 06df81e896b8ae06112fe6a56d8edce8ea034eeff618741a00124acdcafe3840 Mathlib.Data.Fintype.Pi Fintype.piFinset._proof_2 +T 06e95891faae1913edbcd671ad904b8feb5b3f7376585cd7fdd5fb29b672f10c CertiFriProofs.P3.DigestCard CertiFri.P3.uint32EquivFin._proof_1 +T 06f326b8e07ea60e6112f0cc354424cc1ccfbbe97973725ae92521266aec1553 CertiFriProofs.P3.GoldilocksExt3Qrom64 CertiFri.P3.GoldilocksExt3.qrom64_verifyBatchTensorPinned_v6 +T 07035a46b4a4ce2043cbe3754b8539e2079e215d7ebdd7214b96e435a823fdec Mathlib.Algebra.Polynomial.Basic Polynomial.commRing._proof_1 +T 070590a30661922bd12dfccd8a321f6f0536cddbd746e5d7b1cf8dff05b790bf Mathlib.Data.ZMod.Defs Fin.instCommRing._proof_7 +T 07130344d8e3616b32f3abe22bf19b6577efc60ba2d60c5523ebd915d538994d Init.Data.Rat.Lemmas Rat.zero_mul +T 0727eebf6ef551dc0bec484927c244e11b1cc28fcf50b7b696e9b0831f35c59a Mathlib.Algebra.Field.Rat Rat.instField._proof_4 +T 07a406394a9eff486f903660a3714bf403cb8787a4c600507df6cce8322a8034 Mathlib.Algebra.Group.Fin.Basic Fin.addCommSemigroup._proof_1 +T 07a84eff4fa58049cc255c481db076a7190c0300474d74a0ee82c090a60c7e36 Mathlib.Algebra.GroupWithZero.Units.Basic CommGroupWithZero.toDivisionCommMonoid._proof_1 +T 0809436e3274ba906b31183e7bde4acd4220e466dbb35ba3adeb97e09312f771 Mathlib.Order.RelIso.Basic RelIso.trans._proof_1 +T 08388f69f3a5053874323174295832ecfed393151078a594fdf78ff84dd994ad Init.Data.Nat.Power2.Basic _private.Init.Data.Nat.Power2.Basic.0.Nat.nextPowerOfTwo._proof_1 +T 08647d8011971c4dc633710d7a37fc0ec192efeec83bc99da6ee9a6da05d0684 Mathlib.Algebra.Polynomial.Basic Polynomial.semiring._proof_9 +T 0891c35c3d3035fed5ae58c997f9e6e181a9ed76d875edc0a4fdbb5efdf48e99 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.instField._proof_11 +T 08b3e40597c6b2db0c829de5c7fde4feea5e44fe04dbb4101dc318b99b408d2f Mathlib.Order.Lattice Pi.instSemilatticeInf._proof_3 +T 0941956ac5837b357d21934346a46602d040557e7c2ba292e862193e188f5a15 CertiFriP3.DomainSep CertiFri.P3.DomainSep.instDecidableEqKeyedInput.decEq._proof_4 +T 096659d52c57ccd27803e4fcda2a57c26f9ab92b1a1e2616486bb9df3f65e131 Mathlib.Logic.Equiv.Defs Equiv.trans._proof_1 +T 0976ca13cbb563d75b7c001a752d22ed6ef1e96e45d60092bd46957d0a208922 Mathlib.Algebra.Ring.Defs Ring.intCast_ofNat +T 0978160d1391c0fca5cc8962ccd967ea3d0d14c066006f325879a20f9502aabd CertiFriP3.DomainSep CertiFri.P3.DomainSep.instDecidableEqKeyedInput.decEq._proof_1 +T 09fe6343a377a5a8ff9aaf89ad2cfc9c192c8a1b1ca2c0b40dd498e9e93bbdb1 Mathlib.Logic.Equiv.Set Equiv.ofLeftInverse._proof_1 +T 0a08afc0a525eca9a869c8e23df16be7080dd472adeb3decbe0922e78b48ce2b Mathlib.Algebra.Field.Defs DivisionRing.zpow_zero' +T 0a86cc89204878a97ec99ee344b5e50c1c09b21f905df60ebacdab983ebccb06 Mathlib.Algebra.Ring.Defs NonUnitalNonAssocCommSemiring.mul_comm +T 0ab4e86a835e86cfe0820cea177f4c752fa608ad506f4b749f9e4f678b70bf43 Init.Data.List.Sort.Basic _private.Init.Data.List.Sort.Basic.0.List.mergeSort._unary._proof_5 +T 0ad3a13a4241ec024655dc7551642091b231b48d5d1c3c3c79ebda2ed08c6b07 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.instFintype._proof_1 +T 0aefa7ddfa4dc19759f2ed147fec044e8f22e1e6e4c0ea7a44d2cbdae2e86236 Mathlib.Algebra.Group.Finsupp Finsupp.instAddGroup._proof_2 +T 0b01811e95db9abda9b1cac38a094ff91070cf6908bcc22abb260c91530bd260 Mathlib.Data.Set.Basic Set.instDistribLattice._proof_4 +T 0b18933698ad45c2a32c2c6ba1be9a58a70fe4c34675e6b6e1640d5fe6bc3c66 Mathlib.Basic.NNReal.Defs NNReal.instLinearOrder._proof_12 +T 0b438c64356b3016388cbbd02ebf69d2fe292b9fa6b8a5281b85f0406246b48b Mathlib.Data.ZMod.Defs Fin.instCommRing._proof_3 +T 0b5ef984e308a62b62bf485b8cd9ffc43c1cb548aa9225b38b41284ea9e3114e CertiFri.Stark.Graph CertiFri.Stark.instDecidableEqColRef.decEq._proof_1 +T 0b954743ab12ba2e5f68e03581443a2d0f7b181570e6f4c2ccb0a6d40a54c869 Mathlib.Algebra.Group.Defs AddGroup.neg_add_cancel +T 0c23d90b5d652c13440a0f72dc4ec1a779225cb9f6ba390e7eb3f938937e015d Ix.Cert.Release05.SecurityAudit Ix.Cert.Release05.ep1V6Hop4_hypotheses +T 0c78761d5a959796d805dd5fee4beafe0863bdd5acc087106b22527c4703f047 CertiFriProofs.P3.GoldilocksExt3Model CertiFri.P3.GoldilocksExt3.starkModel._proof_3 +T 0cd2b67555ead2a2ba7ca530d7560f30bbaee252d4a0b3e860ef6e09969f0db7 Init.Data.Array.Basic Array.mapFinIdxM._proof_1 +T 0cfaa074029f648d6716f5832282c60f52017992f3cf8e32e7290a44cc6d1302 CertiFriProofs.Exec.Setup CertiFri.Exec.modelParams._proof_6 +T 0d66c4cd930dfda251c56f3f94fe83c937a8492faf4bd26ee9e41663798210fc Mathlib.Algebra.GroupWithZero.Hom MonoidWithZeroHom.funLike._proof_1 +T 0d9cf1fb67df7e3a93acd4ff90c5c823c65693afe5cd32489ff66b24913d9ba0 Mathlib.Data.Finset.Defs Finset.instSetLike._proof_1 +T 0e423606b8e714589370f6673b429cb0338674bb8562ffc75dec1d00f33c0b7f Init.Core trivial +T 0e940b28887ec12a8d94cc44fee4b2e04a7e3557d1eee64957a6896e9c23a029 Mathlib.Algebra.Module.Defs Semiring.toModule._proof_2 +T 0ee56edf9b9da4c6a38c2c42da7a3537c4cf0a0838ba0193d47c587887e6d0b1 Mathlib.Algebra.Group.Pi.Basic Pi.addZeroClass._proof_1 +T 0f0ce6e14ba33faf4651bba048d64529c90e057e8dd4c54bf3d695a7e472f46e Mathlib.Order.Lattice Pi.instSemilatticeSup._proof_2 +T 0f28a591adf6cbe4e0652272ebb2c43c78918fff455f74c25041d2dc4a225c04 Init.Data.Array.Basic _private.Init.Data.Array.Basic.0.Array.isEqv._proof_1 +T 0f585145fee65570d43a0fe8d513b1c5385337a55dd8a83d7e9a016b128a24af Init.Data.Fin.Basic Fin.ofNat._proof_1 +T 0f99f2c623aa1a86174a1ac75f11797f4243c30392c8ba7d11f71269fc704f6a Mathlib.Basic.Real.Basic Real.commRing._proof_2 +T 0fc6d684c879edf585d7931484666a15864eb62ad8286a78a51efdf28b809df7 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.instCommRing._proof_24 +T 102f59a8208b51dae5153b949cef0257688f2027c6f0d84614acd5e9498f24fa Mathlib.Data.ZMod.Defs Fin.instNonUnitalCommRing._proof_1 +T 108b1c233640d4822f9816f7e1907717a4b6b5cc30a6a37db719f1e974d38d8d Mathlib.Order.Defs.PartialOrder PartialOrder.le_antisymm +T 109867a8304304d736c1b9b9d026dfa80832f9faa5ba89bf546a3728ba381e3b Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.semiring._proof_4 +T 10aea74cc835387361ddfb90096deea193c23529b058b847b67b93991b976d0c Mathlib.Basic.Real.Basic Real.commRing._proof_24 +T 10ce3cb43209dfd3f0230565b228a301e1717fef4f1eb4d7d1c4508b4ba0d0b5 Mathlib.Data.ZMod.Defs Fin.instCommRing._proof_1 +T 112d37807af4fc7c78cd3e0bbc29759f4e23e1b3c9b49c9c28be79420a515724 CertiFriProofs.P3.GoldilocksExt3Qrom64 CertiFri.P3.GoldilocksExt3.qrom64_verifyBatchTensorMultiArityPinned_ep1 +T 114377990df0dbe6b40fdfd71779a2907cfb4cd0911406b3a5504bba91c2885d CertiFriP3.GoldilocksExt3 CertiFri.P3.instDecidableEqGoldilocksExt3.decEq._proof_4 +T 115ea9eb95a5bbd06e2363d3caef332451b625115aeb516d49d2bb592a008125 Mathlib.Algebra.Group.Finsupp Finsupp.instSub._proof_1 +T 115f4505b48786053e44d70be65d66382ba0fda2bf5a25c1d5a03de4db6221ec Mathlib.Basic.Complex.Basic Complex.addGroupWithOne._proof_2 +T 118dd94b5a70834e733ab3c669bc9bb0e985e4e912c2bbfed88e18d99b275866 Mathlib.Data.Rat.Defs Rat.addCommGroup._proof_2 +T 119a31e9b5af7f5e7e3f5efb67c1a88246fafbfc1ac2ebf51a28455cbc0dc682 Mathlib.Basic.Real.Basic _private.Mathlib.Basic.Real.Basic.0.Real.wrapped._proof_1._@.Mathlib.Basic.Real.Basic.3158186288._hygCtx._hyg.2 +T 121015bf3b4257fa697daed293bfce7c61c5f181ca3e7239837430c75601421d Init.Data.Array.Basic _private.Init.Data.Array.Basic.0.Array.mapM.map._unary._proof_1 +T 1246968cb31718b0148066f22a81a4c456251d7dc0358e50823d97d8523a3c2e Mathlib.Algebra.Order.CauSeq.Completion CauSeq.Completion.instInvCauchy._proof_1 +T 128cf921d2e99025cd98f8b7221655a5ea1b90bdd396d5ed575f7e8d04d15c2b CertiFriProofs.Exec.TensorExec CertiFri.Exec.tensorCoord._proof_2 +T 128f60bab71bc886cf21688e7a8bfb4df7e5b23e9c9479809803cead9d51f518 Mathlib.Algebra.Ring.Int.Defs Int.instCommRing._proof_2 +T 13067e11faad826e707dbdaa02c25f2d897ebddf0a9846757dc7bb1e94638c28 Mathlib.Basic.Real.Basic Real.instDivInvMonoid._proof_1 +T 131a013c210db9279c528c66af37396d29522c80ebf27242c24b3a32f79c5aa2 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.instCommRing._proof_9 +T 131ea08d110bebc3b3b6800d89212ed8c2062e544219e24403949822499c572b Init.Data.Rat.Lemmas Rat.one_mul +T 133080c2dd0cd89a616a9b48bce87f0dacb7fe3259d3c7f2187212e59f4619e2 Mathlib.Order.Defs.LinearOrder le_max_right +T 134723612d49adfc351dcd80211e1e0a2edaae422f5120c233ae4e7e3d399aef Mathlib.Algebra.Group.Finsupp Finsupp.instAddMonoid._proof_5 +T 1353f45aed515e347de5603f8657140903c81144dd3db6f5d0c62592c9e838ff Mathlib.Data.Multiset.Defs Multiset.pmap._proof_3 +T 139e21112504596cdca78fe38ab60a6ca4198822c6c8cebab85ef5fb298483e8 Mathlib.Order.Hom.Set Set.orderIsoOfEq._proof_1 +T 13a21db2aca32131aab5383c5f3b3467aca75e6daf352adc46f89dbb8fc86efc CertiFri.Params CertiFri.instDecidableEqFriParams.decEq._proof_2 +T 13cec29f5c728a5ca747f38b0e90bbe017c88f00aa37141438235d211a75e108 Mathlib.Data.ZMod.Defs ZMod.commRing._proof_13 +T 14379572dbf30f8bf2d1763fc53e59582ffd6122f7347b1ebc78cfec13efbbda Init.Data.Nat.Basic Nat.instNeZeroSucc +T 14c5f96298e94c73c1cc39798127f60e1031b80412a7e9fc34f4f787604fbb66 CertiFriProofs.Qrom.CompressedOracle CertiFri.Qrom.isUnitary_compressedOracle +T 152ad2699319661d9fd0aeb09a1df48f6249902adeec05fffee41fc17361ba9c CertiFriProofs.Theory.PcsRbrTensor CertiFri.PcsRbr.tensorCoordWeight._proof_2 +T 15e68b5fd1ec34ff4c63ff00228d65eeb109533f8454bb23c4e35676c9812874 Mathlib.Basic.Complex.Basic Complex.commRing._proof_10 +T 16133663e20372242fa88f22c40d1164d853053d9f47749035b5743b901fb353 Mathlib.Algebra.Ring.Defs CommRing.toNonUnitalCommRing._proof_1 +T 16c5dbc8fbdc3156029d3e5d459c4fa4bfb4933c8b8a7f304f9c1ec6174ecd64 Mathlib.Algebra.Ring.Defs CommSemiring.toNonUnitalCommSemiring._proof_3 +T 174822fe262808b3a9c73439d7f91a66fe9989525aa04a86f200200d1cd30c75 CertiFriProofs.P3.DigestCard CertiFri.P3.uint32EquivFin._proof_3 +T 17c31dc06bcd4da9a6cab63775b9d9bf625dc922e10c5c221b14e85470745d1a Mathlib.Order.Monotone.Basic StrictMono.le_iff_le +T 181c01145505bcaa737ab92d1817914b2627209a671c14adcfef8df75f022b4d Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.nonAssocRing._proof_3 +T 182e28b2154bf882945576a14c5201d5da183f1edb2ba8b9374d61bb7c286f14 Mathlib.Data.Set.Basic Set.instDistribLattice._proof_10 +T 18974ed0aa5b3a8290c0b109cd63190d2bce76bdc94dccc02949b83de703e364 Mathlib.Algebra.Field.Rat Rat.instField._proof_1 +T 18b8fd7d672f4da78304321ba84c3c6fd65c8454b6ccd9e5c894ba25874ead44 Init.WF Nat.lt_wfRel._proof_3 +T 18c198fa892b57467c300ad8bb58541a881ded6d3ee57da6d93510012545ed0a Mathlib.Basic.NNReal.Defs NNReal.instSemiring._proof_23 +T 1930d09dbe4bbb768c14934255221642fb6a4eeb3911ced886376ed1f087079c Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.nonAssocRing._proof_5 +T 19c968061cb743a758148f0f5368583fb32c3270bd6c0c46aee8fce0f4086438 Mathlib.Basic.NNReal.Defs NNReal.instLinearOrder._proof_10 +T 19decbe4d1288879c21571e95e7a493f00eb7509ce8be9453f0288408a1d18c5 Mathlib.Algebra.Order.CauSeq.Basic CauSeq.equiv._proof_1 +T 1a5ab4335aad206bb193398cb618690669769c346151350c093b53347b9a4d87 Mathlib.Data.Nat.Find _private.Mathlib.Data.Nat.Find.0.Nat.findX._proof_3 +T 1a6b2aca5539d144d753d65d4712a29f52272d81e2f88969c72535839bd06ab1 Mathlib.Algebra.GroupWithZero.Basic GroupWithZero.toDivisionMonoid._proof_1 +T 1a820632f25d55d64d6b2caa1795692b7d0932accf025749b038128237a602ae CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.instDecidableEqFp3Model.decEq._proof_2 +T 1a8881c722ad8928b5b06762dcd96bbc4c875e83877abf6f44d8ee18cee3d952 Mathlib.Data.Int.Cast.Defs AddCommGroupWithOne.natCast_zero +T 1aab49af3f88b5e063b74733dd7b9b836c2eaaa6c84e8185f0523485b051937b CertiFriProofs.P3.GoldilocksExt3Model CertiFri.P3.GoldilocksExt3.starkModel._proof_7 +T 1ba00c7ded3539d17b7160016d699ac3ad199819b69f258bb0970d424863ad14 Init.Data.Int.Lemmas Int.mul_add +T 1ba0efaaee488ccc318f0215e8d417d4eec3acc608ceacc202dc3922bf568a8f Init.Data.Int.Lemmas Int.zero_mul +T 1bb25dbc889d74b16a8d7265885b324cbd8c7076664ece6f0e8ae7198baeb4d6 Mathlib.Basic.Real.Basic _private.Mathlib.Basic.Real.Basic.0.Real.wrapped._proof_1._@.Mathlib.Basic.Real.Basic.339334276._hygCtx._hyg.2 +T 1bed26ea0cf7658d28fd5eaab7ab1deb08ac699d1a0207670a77c002690ce7d3 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.instCommRing._proof_12 +T 1c2a9911773c0de5d9982c8784aa047dfbc3aeb98b659f2157aa932ae8f3bf3d Mathlib.Algebra.Field.ZMod _private.Mathlib.Algebra.Field.ZMod.0.ZMod.mul_inv_cancel_aux +T 1c332b6c351ffddbf270400a0769115fb86018a5e8ba1398f3284e48dbdf9ff2 CertiFriProofs.Qrom.StdEquiv CertiFri.Qrom.mkCOAlg._proof_2 +T 1ca91ade3413a87b36aa861b4d7308ae06f8f8a18b5d626f65bed2daf78b70e3 Mathlib.Algebra.Group.Pi.Basic Pi.addCommMonoid._proof_1 +T 1ca93dc9d4609b9a2e83c8821ed9104e511b40e1c8447df8e73872296710543f Mathlib.Data.Multiset.Defs Multiset.attach._proof_1 +T 1cad474f855767c0e29a6c3e04ac0b2b4e0d7128176ec2787e9173d2a77bbe59 Init.Data.Array.Basic Array.forIn'._proof_1 +T 1cc444f65238a4ce187c4b49a86abac88f8bb50e1fba203aaa75417bc5fa195f Init.Data.Int.Basic Int.decEq._proof_5 +T 1ccc71d870afc2e057892a7a6e8d4517eace9404a96af11f5ca66030e9c7bccd Mathlib.Algebra.Ring.Defs NonAssocRing.intCast_negSucc +T 1d1695a826f5579e10bcbe23752c578a65604e5b41e28ce889265d2fae204e90 Init.Data.UInt.Lemmas UInt32.toNat_lt +T 1d2ebe07a8f280a4b9f0e2e7ea7c94fdb1c0c0366725904fff60c0dac430d5cf Ix.Cert.Release05.SecurityAudit Ix.Cert.Release05.posControl_release05_blake3_256_qrom64_headroom +T 1d675f0bd131296f90661277a19d034fb7f66ecb0e6ad4cb883b45748b649109 Mathlib.Order.Defs.LinearOrder min_le_right +T 1d81a9414e825ca6a416f099a75cd093f24f159df3945c0d575cd78601b8a3b6 Mathlib.Data.Multiset.AddSub Multiset.add_comm +T 1dd829d2fa59e89487071d9e2587f7a92226f66c2b6072398e95fbb60bf1076e Mathlib.Algebra.Group.DivInvMonoid DivisionMonoid.inv_inv +T 1e11c3b9017b45f6f1ba5d88aa3a935a89703c867e7774006fd495431a25498f Init.Data.Int.Lemmas Int.add_zero +T 1e200d8f5a8ce5f8525de5186904855b4fade19db99bc03f33af3d66a1cbd1b3 Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.nonUnitalNonAssocRing._proof_1 +T 1e2bcae99b0ff4f56fe28db07ed174d0ad8347ee533dcda75fb09a37af3c8dff CertiFriProofs.Exec.Setup CertiFri.Exec.WellFormed.prim +T 1e5c07ff9471b042e31d9692d71d10e6a8327de165aaa239e780281c0f745a4f Mathlib.Algebra.Order.AbsoluteValue.Basic IsAbsoluteValue.abs_isAbsoluteValue +T 1e95787b617f8175b971e4701e3e003384e6f3073d695be2c7192b0745d2a700 Init.Data.Int.Lemmas Int.zero_add +T 1eb53201bcd349beca3feb98474510610325b49c02748c9d91796a2f03c5096e Init.Data.Rat.Lemmas Rat.mul_zero +T 1ebe52d3adf5e0f8f98eec0905e7b5a1a25494d0165db79740a0003504337754 Init.Data.Int.Basic Int.decEq._proof_2 +T 1ef2f6117fe1da35b3b3e558659190c95f902e7210bc2ab1f99ce0ad6dc802cc Mathlib.Basic.Complex.Basic Complex.commRing._proof_13 +T 1f279856729e6e875e010f64c78a88ae4621b521cb55e5db4aa965119b9cbb82 Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.addCommGroup._proof_5 +T 1f95e378ad8d72564ce2a0b011d79e97c43f041e01f75eb8c9b126b060eba9aa Init.Prelude heq_of_eq +T 1fa674322eacb3717f28d664f52a1148ed30d20ab05a68442e6419c7c8e8c91e Mathlib.Order.WithBot WithBot.instOrderBot._proof_2 +T 1fc69881a08cab0e52e4988d7d248e5c8b8e687ec0e764ee0f1325515be8b450 Init.Prelude BitVec.decEq._proof_1 +T 1fdbcef7c1a6bc8d1a717324d34bca2bda45524921f89f11e84ef62a53965dbd CertiFriProofs.P3.GoldilocksExt3Model CertiFri.P3.Fp3Model.extData._proof_2 +T 1fdde9963c637faf61d86df2d54f7c8a12e05cad6a5a7cc4cb3d13effdf82812 Mathlib.Algebra.Ring.Defs CommSemiring.toNonUnitalCommSemiring._proof_1 +T 1fee5addf593a9710bb739862bfcc49bb13eade2efa6ae60da7bbf28cfbd04c5 Init.Data.Nat.Basic Nat.two_pow_pos +T 201d60c46bed97f237724f743cee6561717e70e9127fc0fab1a91685947d5030 Init.Data.Rat.Lemmas Rat.mul_comm +T 202a1011cf30be081315ec913d3dcecbf39480e97509cc6030c159ed733781d6 Mathlib.Data.ZMod.Defs ZMod.commRing._proof_7 +T 209ad1534fb04f0cf7e8f5feee4069acc6496d4785dc157da6a0ae9562ddc885 Mathlib.Data.Multiset.ZeroCons Multiset.cons._proof_1 +T 20b581211faac41067abc158704507be553632b748b36346c1ea7302a959ba5a Ix.Cert.Release05.SecurityAudit Ix.Cert.Release05.release05_ep1_balanced_ok +T 215f746339b6f1279671bf95c5533fda68dc4adb832ba8328d7bd2050a59f3b3 Mathlib.Data.ZMod.Defs ZMod.commRing._proof_9 +T 2174e0f4a51205e862762e1a4829c8df02ab3d6c27edeb07fd9b68d3500dafa4 Mathlib.Algebra.Order.Nonneg.Basic Nonneg.pow._proof_1 +T 218262558011250b17427511bf7dc8c2e61623ed9b623482c340f7c9c86cf425 Mathlib.Algebra.Polynomial.Basic Polynomial.semiring._proof_2 +T 22296fe5b4eb0a7000d0ed56decaf16fe496fb1f676383cf5246d36535bd8bbf CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.instCommRing._proof_8 +T 22b31ffce5332d459d92da88220fd5eeea62ba08802e6add74d5e830753da7f6 Mathlib.Data.Finsupp.SMulWithZero Finsupp.smulZeroClass._proof_1 +T 22bd819cd88d04ad2869feb8f738591085516461b0403f649aa8e5d606a626ff Mathlib.Data.FunLike.Equiv EquivLike.toFunLike._proof_1 +T 233cacae5e81e8666fbec84ad1a5e993e521d39111cce57cbc5beac24d1d729f Mathlib.Algebra.Group.Pi.Basic Pi.addMonoid._proof_1 +T 23e3300b2175c0b7314b63f9c696e50961270f13d86755545fef68f4e62c77ff CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.goldilocksBase_refines_fp3._proof_6 +T 2403c1932c35bde1bee6a8471450cb72e188822f5a0fa2fe74f91ceaac24dd22 Mathlib.Algebra.Group.Finsupp Finsupp.instAddGroup._proof_3 +T 2426af27028578ec29f6bf8ffd75c6a1b9f0864c377c6fca52630d642628e0be Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.semiring._proof_7 +T 244bdb5baf085f1737d524ca530137e8067875c5d8428bc5203975d6149626cf Init.Data.List.FinRange List.mem_finRange +T 2466cbb65703ab9d35760ee3c921e6f804124f522d0b834c9aea0450bb9ba78a Mathlib.Algebra.Ring.Defs Ring.neg_add_cancel +T 24775207e604ac15cecf65413cd4dde302b33e7c7baa99d47863500cefcd3ced Mathlib.Algebra.Group.Action.Defs Monoid.toMulAction._proof_2 +T 254ec5a1fe37b3bc0cc87bba2b3e65ad7194b557c9559182662f4f9b86da8acd CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.GoldilocksExt3.beq_iff_toModel +T 256a5bd73b6622087e9bd95bb04a8c1013cf4040c1409b2d8cebba95fbbff01e Mathlib.Logic.Equiv.Set Set.equivOfEq._proof_1 +T 256aff0e3ea22545d88c43130ccb95292688641878d1dbc12cb4b2571d780e36 Mathlib.Basic.Real.Basic _private.Mathlib.Basic.Real.Basic.0.Real.wrapped._proof_1._@.Mathlib.Basic.Real.Basic.4282658333._hygCtx._hyg.2 +T 260f4a775484bec710eed7f5730c04db70dad8fe2b762a0eab369a3f49ce96e8 CertiFri.Challenger CertiFri.instDecidableEqObservation.decEq._proof_9 +T 26b4fd30de892011e76c07ab13b0396ba109943a0889b572a532511fd28056fa CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.instCommRing._proof_20 +T 26c2b12792b6c6a9832d879eb79d5a97a141ba0c68cc0783158ea2951e11d12b Init.Data.Rat.Lemmas Rat.mul_inv_cancel +T 26e860e05294f609af97d8523e774ca68d12e06343715c61800c89314864cbf7 CertiFriProofs.Exec.Setup CertiFri.Exec.modelParams._proof_1 +T 27044cafec48c0fa2d2aefe7a1409f171dd7ffc735fe9bc4ef6c335ba6104fd4 Mathlib.Algebra.Ring.Defs NonAssocRing.natCast_zero +T 2768463e5868c44a984804436007d5b7de81fa2122d7dfd41a270469a1f34b19 Init.Data.Rat.Basic Rat.normalize.den_nz +T 277c223d5d2c3fda2d65c7b721c41a4068cf8ceb61dcbed1d2557c9dccb66eac Init.Data.Nat.Basic Nat.lt_succ_of_lt +T 27d9600d3ab3fac2ee33db3f8b4e94a3104890de9ac4e69975fb32ca38f95eaa Init.Core Quot.liftIndepPr1 +T 28290b12256f914f62e7637f02e9e51f4cb6a380a773f53001c811d8abd3889c Mathlib.Logic.Equiv.Basic Equiv.subtypeEquiv._proof_4 +T 287e233b32a784d0e71a79b3378b3570dd48d1db5f19fb9d9fe58c5961e9ddfb Mathlib.Algebra.Ring.Defs Semiring.right_distrib +T 2883ab1c70afed8da6379ba2746cbade52552c2e0dba6b9697071c9abfbf3db1 Init.Prelude List.hasDecEq._proof_4 +T 28bdee4880487f11eef143e50e37faf5ae70549a8a79f9c3b384bef6c9802afc Mathlib.Algebra.Ring.Rat Rat.commRing._proof_9 +T 28fd1c898fbeb354084df1a750b01c374b52a251e8c5ff35b6687fbfb239d45e Init.Data.Array.Basic Array.mapFinIdxM._proof_2 +T 29262168090ccda3941661050ad045c202a821f82f9969f5277c5075565882fe Mathlib.Data.ZMod.Defs ZMod.commRing._proof_2 +T 296440ce7f81a67c3d742d35dafd39caf968c52991086f035b03e01b97a7c837 CertiFriP3.Digest CertiFri.P3.instDecidableEqDigest.decEq._proof_9 +T 29719244adc392cb39325923112245c929083aca4058687c2e50609f8c272a71 Init.Data.List.Sort.Basic _private.Init.Data.List.Sort.Basic.0.List.merge._unary._proof_3 +T 29d955460016d20ed2696f054e7d2f12a4875c93451a33c67d1079135164f70e Init.WF invImage._proof_1 +T 29d9c6796e596d4f9945eee50bbf622c70d4a0f89d31236eeab2e81f0a753371 Mathlib.Algebra.Group.Finsupp Finsupp.instAddGroup._proof_5 +T 29e3868540174998397090a479aae5abbc8cf7971399a9716741109befbe90b2 Mathlib.Algebra.Ring.Defs CommRing.toNonUnitalCommRing._proof_4 +T 2a13bc304792e0fec31908b74681f855732da36e32d4134fb9cd107d245c8023 Mathlib.Algebra.Ring.Defs NonUnitalCommRing.toNonUnitalCommSemiring._proof_6 +T 2adca6482cbb2ff561ac66e865f834d7fd1badcfbc0b00e8ab0850947c814bef Mathlib.Algebra.Ring.Defs NonUnitalCommRing.mul_comm +T 2afaa1afa36d6162ebaf68c3694cbe2f10b6e52c4e296826b49aed9c69f25c2e Mathlib.Algebra.Field.Defs Field.toNontrivial +T 2b1bc8a4e5d0bf225e2fd2766582545b999cb4c60ea8e4714f3f385844810e4c Init.Data.Rat.Basic Rat.ofInt._proof_1 +T 2b891f763e7b3a5da43273e046e6ca3ee17d9bdcb122c5df0336ee73db8b0ce8 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.goldilocksBase_refines_fp3._proof_2 +T 2baa6a4e1532eee2b293c242697329c626f33accca821c549d07fc35f84a63e5 Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.semiring._proof_8 +T 2bd0fa492c8c4dedecd5698bdaba83962219e94e3f7312df927cf8e8e1771fe6 Mathlib.Basic.NNReal.Defs NNReal.instSemiring._proof_3 +T 2be9a8e00addd6b4a66834077421fbfa17b7322e36fe00190fe2d05b088df6dc Init.Prelude Nat.le_refl +T 2c51540c10f049efeca59d3821ec49aed5e7d61c59d892d207d3e97022bd2a14 Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.nonAssocRing._proof_1 +T 2c699207e0ca50f918ab52357d4a8a9411697f21a75f7661eb850e2d69dd528d CertiFriProofs.Exec.Stark.SoundnessPinnedSpongeMulti CertiFri.Exec.Stark.shardCompPinnedMultiSponge._proof_1 +T 2c7c43c6c2f29720592d73f665066fab52cc2307d8cf3dd303e9bd5234059796 Mathlib.Data.Finset.Option Finset.insertNone._proof_2 +T 2c95cb613a53317334ffa1f5dd4687676923b4e9533b008436ea6fdd1bd285a8 Mathlib.Basic.Complex.Basic Complex.addCommGroup._proof_10 +T 2cb46e63ff9a572572743c3a90be4ee5bc229567bc9fa692d5e5af6bba5d3506 Mathlib.Data.ZMod.Defs ZMod.commRing._proof_4 +T 2d160dbb03c367ac8eebc54c7eca5e82cd8dcd231a12fa25e67d9ca3e09b3b79 Init.Data.Rat.Lemmas Rat.pow_zero +T 2dbcd584eaf9e842f7af427c54a00ad472ff2f127af41066981714a98f31ab04 Mathlib.Basic.Real.Basic Real.commRing._proof_7 +T 2e5dc1a6bd6db16b09cf912869f401c8308491f38e452bc82e63c3210f9165b8 Init.Data.Int.Lemmas Int.add_assoc +T 2e5ee31da6c75a7cbf788ec9deebcdbcf2fe4a93a1d17565ed8dafda11929ffc Mathlib.Basic.Real.Basic Real.instDistribLattice._proof_5 +T 2e639c24888ad17949682b3c73e4f2c27a3d558e5f603e79586e64e216a75fd9 Mathlib.Algebra.Ring.Defs NonAssocRing.natCast_succ +T 2e7ffc744efd75c35be17a1b0e52f1f04d747647c9b099f3c5cb3ba684b3c55d Mathlib.Data.Quot Quotient.map₂._proof_1 +T 2ea36d36ff6a1523671ee7ac86e1567926f3d079426e1a5beb85aee23671ae61 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.goldilocksBase_refines_fp3._proof_7 +T 2ebbbba8f11bb9925829de754e43227d5ee12bb6be08ba8932ec7ccbf8649983 Mathlib.Algebra.Ring.Defs NonAssocSemiring.mul_one +T 2f16670b1de9a0ebe6b2cd677e567f822336dcb9d178766bbc33eab408933e87 Mathlib.Algebra.Field.ZMod ZMod.instField._proof_2 +T 2f74bc45b83a810f66dc0010d16d3891d8dae6a78b5342c7b49b49fbd657c446 CertiFriProofs.Exec.Setup CertiFri.Exec.FieldModel.leafEnc_size +T 2fa512e9e15f24fa74300315a15b8a020f0fc319631bbb8f89c17cc3e5b927a9 Mathlib.Topology.Instances.NNReal.Lemmas NNReal.powOrderIso._proof_1 +T 2fd7965043d50696a3fcd82e198fd0f3bb80ed3841b79e67b15411b3d5125748 Init.Data.Nat.Lemmas Nat.decidableExistsLT._proof_10 +T 2fdae59c27b2fe0bf67a0653c304fab774b878a88bfc91f660d9828662db6b69 Mathlib.Data.ZMod.Defs Fin.instCommRing._proof_13 +T 30368379db476497060246904d9080afbc279eae6a67654a6891b6b5f512fc08 Mathlib.Data.Finset.Defs Finset.val_inj +T 3098e1ae855d72acfb26293ca0d6f8cd645223d54cf579306effb41aba7c4669 Mathlib.Basic.Real.Basic Real.commRing._proof_4 +T 30aeea4f27187c8bda1b13b4fbe7e234509298f810268a8e433a79ceb0d4351d Ix.Cert.Release05.SecurityAudit Ix.Cert.Release05.ixVm2p23_4096sh_balance_lt_p +T 30b0c16e9977eb6d1051a31c793a359a41cab17506cefa6a176848b036f57722 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.GoldilocksExt3.toModel_sub +T 30c8701b3199f6811875417f24c490e3d9298f768664abc27ec52e58eec02978 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.goldilocksBase_refines_fp3._proof_8 +T 30dfc0032aaca9a8420b3d75ca17dcdff3242dac6ac0072a0bbd1301bfb6f7e0 Mathlib.Basic.NNReal.Defs NNReal.instSemiring._proof_14 +T 30e7afc4ad0e85065c30886b5fc73b003c65aeae0bc0761125da9464ea27adf3 Mathlib.Algebra.Group.Fin.Basic Fin.addCommMonoid._proof_4 +T 3198119a4750f6903868958cff9e8d195c87aec95072e875bb1159f4f9898766 Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.instAddMonoid._proof_2 +T 31d11b4b60cdaded0f5970b459e6ada5eff296cc6dc2c6ea5f48a6e151fdc622 Mathlib.Data.Finsupp.Single Finsupp.single._proof_2 +T 31dcecddc30144cfde7e108415a4943d408e16051b6b49c16b563d31b529eb6c Mathlib.Basic.Real.Basic Real.commRing._proof_23 +T 321b3a016e5e23ba132d44337f9b1c25e5337f4310d9d55bf87f5374cfd7eac8 Mathlib.Algebra.Polynomial.Basic Polynomial.ring._proof_1 +T 32379c5515f6d5c6e5c8e8fdc6f43eab0afa655651e25ed08398d651e768f458 Mathlib.Order.Lattice Pi.instLattice._proof_3 +T 329006bf00de6499f2f89fffb1139e19941c76098c77f3f53c0c9825f85e0c48 Init.Data.Rat.Lemmas Rat.add_assoc +T 32a3227993899e8ada302bb0087637e029efeece1036ce37e1e4a2be016af933 Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.addCommGroup._proof_6 +T 32b861d20a0a5632b975fc578a471278c910133b3c6208b76cb15528829fa1c5 Mathlib.Algebra.Group.Nat.Defs Nat.instAddCancelCommMonoid._proof_1 +T 32f99be0725b21039440dc7c59eb7e6d55d6d7a2633c27c763d1dc0fae36f615 Init.Core Quot.hrecOn._proof_1 +T 331b70952fcd3a79ace9fa2f0ee762b1de48ebaeba6a460534786ba0d443f6a4 Mathlib.Algebra.Polynomial.Basic Polynomial.distribMulAction._proof_2 +T 33262c1e4fc95136d208716b94798ce26562211986c974a739cc6bd7a3a21203 Mathlib.Algebra.Group.Nat.Defs Nat.instCommMonoid._proof_1 +T 33307b490ce2edb1c29ff547f44e59a323156f19711da945700fc6f5e9fa9a13 Mathlib.Logic.Equiv.Defs Equiv.refl._proof_1 +T 3346d281c979945336b42ee63b986d54e6b91eb33c4778ed040a5f19b9bed301 Mathlib.Order.Lattice Lattice.toLinearOrder._proof_3 +T 33a483bdf138db2c494999ec5769e41637d2e45298bd57bfcef713e700ed6bf8 Init.Data.BitVec.Basic BitVec.umod._proof_1 +T 33df1cf12bcab5864f3d86698077af39228854891777220df82e546371ef5f80 Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.nonUnitalNonAssocSemiring._proof_2 +T 33f75bbb434f51a11f2861206ceb169e882bbe902bc82dba2684c5971d31d81c Mathlib.Order.Lattice Subtype.semilatticeSup._proof_1 +T 340746f928341916ca4923a436613208a19dc47867ce82d7b394777872085729 Mathlib.Basic.Complex.Basic Complex.addCommGroup._proof_2 +T 3425d1eef8327eeff166fcdcaac5380f63d2cf022cdd79711f4e88891f20bc8a Init.Data.Rat.Lemmas Rat.add_mul +T 34ab5c16215dae541c82452a99b3836a9a13876704d8eaef936d1052a8b6c590 Mathlib.Basic.NNReal.Defs NNReal.instPartialOrder._proof_8 +T 35a2229f23f72a6cc2a2c292b547d9b0092cce6c175df99f1f3d8cf046800170 Mathlib.Basic.Complex.Basic Complex.normSq._proof_2 +T 35eac350d34b73e594e87439519f6cce25fff8d70fa8471e23594312eabf5cb0 Mathlib.Algebra.Polynomial.Basic Polynomial.distribMulAction._proof_1 +T 35f8fdff8265d22f666e4ae68772f989dca0a7d058730bc0e0263181350510d0 Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.coeffEquiv._proof_2 +T 35f9a8ecd32759a7a6178785b0c030a790a5b8c0a9e5c4c8bb2116eab2fc6537 Init.Data.Rat.Basic Rat.normalize.dvd_num +T 360c2d50331c1f9bfb43d9c5b2429038607d61610426b79d46111f967e656395 Mathlib.Algebra.Group.Fin.Basic Fin.addCommMonoid._proof_1 +T 3629e9e81541fda6f583cacaa56357ff93447839babdba910879a907280357d5 CertiFriP3.DomainSep CertiFri.P3.DomainSep.instDecidableEqKeyedInput.decEq._proof_3 +T 3654ad41b7aed1c5e9b44388b0ff91182c7df6f4fa4b4c0c2013b4a82e7af66e CertiFriProofs.Theory.Oracle.MerkleFrozen CertiFri.Oracle.instDecidableEqSpongeQuery.decEq._proof_7 +T 366f90ad1498aeca4a09d7aad35d5bc918a0acf0fbf57899130468221f61ecb7 Ix.Cert.Release05.SecurityAudit Ix.Cert.Release05.negControl_release05_rejects_fp2 +T 369edf4e804c1749f381d28ec88718c1c730afe2560861ba1db2345464032521 Mathlib.Basic.Real.Basic Real.commRing._proof_5 +T 36a814e72f8bcef5cb4bb693808af9de07ff970062b85caf49ed97e45ae56a35 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.instCommRing._proof_5 +T 36b93b303c7edbb6e320444bbb65c0c9b478ac120bb8479860e715897b6d0d2b Mathlib.Order.Basic Function.Injective.preorder._proof_1 +T 36ce5c6302c1ee5174b5ae0296c39983bb81ee416f662d12255274d0a1f7fd28 Init.Data.Rat.Basic instInhabitedRat._proof_1 +T 3700f22013accc7504bd9592acb7c959ce6968220aaf3b329e347525e0ab47ee Init.Data.Rat.Lemmas Rat.le_refl +T 372956f6228990a3552a7e39317b8d54c0c41b86fef48277b6f71b05cab3c31b Ix.Cert.Release05.SecurityAudit Ix.Cert.Release05.aggr2p22_16sh_hypotheses +T 375b98b6808b248e96928cb38dac24e9c0c799946345296d7d42a933742b83e0 Mathlib.Algebra.GroupWithZero.Defs MulZeroOneClass.zero_mul +T 37d60f4749d4f9a84db0f3cf953b97611014c4d6202380543fe84c258cc7def0 Mathlib.Basic.Real.Basic Real.partialOrder._proof_6 +T 37f0a5df987dd4a0ce23025f3ea49c498f7cf2bba54e2f7d8959f3a3f1cbc813 Init.Data.Function Function.Injective.eq_iff +T 381f1c577e418885b76ee01d9756a9f57d355ec10a460ffdb0b9776015417d73 Mathlib.Data.Nat.Cast.Order.Basic Nat.cast_nonneg' +T 3842d3ca03646cd232036011db653dc8f61be0cc00f98840adad5523deef0f95 Mathlib.Order.WithBot WithBot.instPreorder._proof_2 +T 388bb18f331e6edc68b79859f14de028a6d2fe55be790b3ae86300f1ed6b40b0 Mathlib.Algebra.Group.Int.Defs Int.instAddCommGroup._proof_3 +T 38b6109f5b4a96cdb4676df8f630101e593c22fafbf7e7b0d9f28cfdb8ecca4d Mathlib.Algebra.Field.Rat Rat.instField._proof_3 +T 39472bfedfc7cfc969a0fa8ae308908a2ebe4e071116d55e9b2dc6abfbf18d63 CertiFriProofs.P3.Goldilocks CertiFri.P3.instFactPrimeOrder_certiFriProofs +T 394d8ecc1a7254f306e1abe1abae03ac73c66dff2d3855f3c7f8c23170ef9218 Mathlib.Basic.Real.Basic Real.commRing._proof_8 +T 395310029b9c13f9d1b1bd373a996b91b45c9403248dafbfa34fc5eae7826c24 Mathlib.Basic.NNReal.Defs NNReal.instSemiring._proof_18 +T 3a364062b05ca999b4a8faf3635b945411d4e847a1dd9cf6b6ec2678cf8df387 Mathlib.Algebra.Group.Fin.Basic Fin.addCommMonoid._proof_3 +T 3a640478c564d5a4bf242ed750fafbc17f09e64732fe28d174bb64379a93a1c7 Init.Prelude UInt32.decEq._proof_1 +T 3a6cebc6d05dd1a068f3ff05da6e3df07d57c343fafc8b150afee297bb5a5bed Mathlib.Order.Basic Prop.partialOrder._proof_1 +T 3a74b205eff4092a7ea77f4e7be75c6d8388ac683a5dc43048b28fa3f397ca3f Mathlib.Order.WithBot WithBot.semilatticeSup._proof_5 +T 3ac9c127546d28abf6d2290a76cf589eeed612ead7e0ff336ca026f31901a00c Init.Data.Int.Lemmas Int.add_left_neg +T 3b2b7d4a6188dc321229d7380b635a5b094edf275f89046f8e7339482ac99002 Init.Data.Int.Lemmas Int.mul_comm +T 3b5f0c5e6a6f4268fc3f96ccc310b45636c83fbf92f027eb1c12604f7706e46c Init.Data.Fin.Lemmas Fin.zero_mul +T 3bb9c02d040ef00257ae793ffced4403eaf3a8ae7cc96f21c0326c32859562fa Mathlib.Logic.Equiv.Defs Equiv.right_inv +T 3bc884286905b02e831e1551d7ada5803513543ade177962ee3e87d0a77c1be3 Mathlib.Algebra.Ring.Defs Semiring.left_distrib +T 3c2141b005f605b6c5a28e57ef63b34d7be8122aecdd0e96a4cd992a4bb4b5ee Ix.Cert.Release05.SecurityAudit Ix.Cert.Release05.negControl_release05_rejects_unpinned +T 3d0acdcea4d4465586d00e7677aa0b2a7a28620db298579182c70b386d0de352 Mathlib.Algebra.GroupWithZero.Action.Defs AddGroup.intSMulWithZero._proof_1 +T 3d284a3d695ac1bb153cde0d1b8a96a8ad51b3756fda49410dee413c3dfacbe4 Mathlib.Basic.NNReal.Defs NNReal.instSemilatticeInf._proof_3 +T 3d309a1a6f51156c47d6dd8d282bcca606939b647b602d230a07e9786e7e2646 Mathlib.Data.Finsupp.Defs Finsupp.onFinset._proof_2 +T 3d33043e5798a9eee3fcbd9ba87ce3cda1bca2667d6f76644d81535c9dd30ca9 Init.Prelude instDecidableAnd._proof_2 +T 3d6094198f35373457c4cebc76127661721a409787af15e21f06088ca3502d4e Mathlib.Algebra.Group.Fin.Basic Fin.addCommSemigroup._proof_2 +T 3d7b02e83c301e52dd94a35cf6874b99c6250063db0820fb3dbd3432352fd041 Mathlib.Algebra.Field.Defs Field.zpow_neg' +T 3d9e0d443b549b4ca03117dfb81e192fc818207c283443388d4bca48c066557c CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.GoldilocksExt3.toModel_mul +T 3dcf58502d4a971047645c1128efcb884ba5bbdfefa4606504bcb1aa71e2d7a2 Mathlib.Algebra.Polynomial.Basic Polynomial.semiring._proof_8 +T 3e111e2e190a469a536e5ea82dc5009409db8308ed070d215ca2e946246ce8be Mathlib.Data.Finset.Filter Finset.filter._proof_1 +T 3e2749cf7bffa831fb719c4de31e93a3ba4305d716c6d0595af2efb281cf184d CertiFri.Stark.Graph CertiFri.Stark.instDecidableEqSource._proof_1 +T 3e30df3b6bc0e0f5be51bc7e005ac4f3cdea105c2e17b4b26d31f3b924443da5 Mathlib.Data.Multiset.Filter Multiset.filter._proof_1 +T 3ea6639fb45dfc5e836d42f35a2a4cd71413cc3337b84df7d00ffb0973145cdb Mathlib.Algebra.Group.Fin.Basic Fin.instAddMonoidWithOne._proof_2 +T 3ee023ecba53cf92c360f42281d14b0b7a535804f954f912bd6e35070ff65953 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.goldilocksExt3_fieldModel._proof_5 +T 3f07bbcc4eb3826434bf98bc7934b5b99d05c66010ffd9f87d359a821c5694b5 CertiFri.Stark.Graph CertiFri.Stark.instDecidableEqColRef.decEq._proof_4 +T 3f093c59b03c4fedd9b6a26b7f528ccf28a2daa96cc7b6db36f174f4227feeac Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.instAddMonoid._proof_1 +T 3f16dd1a9a067728ead06fbbb6f5d4bfa0eb66b4e97714e8cce6369d18b577e7 CertiFriP3.Wire CertiFri.P3.Wire.instDecidableEqBatchMessageGoldilocks._proof_2 +T 3f254271f9cfd247a745cc84f019fe8697ac13ad4bbaabd4fc87126bd3d100d4 CertiFri.Stark.Graph CertiFri.Stark.instDecidableEqSource._proof_2 +T 3f58e1aa0d801e10d64e2261c7272e1b749fef829c32c6a1ca7caa8c25b9f5c2 Init.Core Quot.recOnSubsingleton._proof_1 +T 3f93ab7d8ee2a2422ddc9842dd7d19e2a37533bb1e5cfa55f28d21de5feead5b Mathlib.Order.Basic Pi.preorder._proof_2 +T 3ff1e46bd7ce047739ed9bb36f3202cfea377bba83c10388a62d3396de1ff919 Mathlib.Basic.Real.Basic Real.commRing._proof_6 +T 406b25a538e95620dea0f0dba1ecc74bdb8e6d84da225900521e0dcee125755e Mathlib.Algebra.BigOperators.Group.Multiset.Defs Multiset.sum._proof_1 +T 40b7dba32cdac7851d359ea403fa883c17f715dbb4a4eb187f6ea2ea0f6920a6 Mathlib.Basic.Real.Basic Real.commRing._proof_20 +T 40bc9103791ad87fd5071c11657bc8879f2ff0524e5d5561141fd0d046f7cb34 CertiFriP3.Goldilocks CertiFri.P3.Goldilocks.sub_order_lt +T 41525349c23f48f2885c430a9f7e720eacb0cae840e42c88c4ff3ac400e64dde Mathlib.Algebra.Ring.Rat Rat.commRing._proof_3 +T 416ad6df1697ca6efccc19f86cff44faf2e5f3e24cf28c03047881a5d91f4dd7 Mathlib.Basic.Real.Basic Real.partialOrder._proof_4 +T 41a07002fb35fff0818ec6d307e4a6a928f50b9fb06f8dea4e9ed12060402c4f Init.Data.Option.Basic Option.instDecidableEq._proof_1 +T 41d7c81cf1a119a99240ce62174d07b7cf65804af0b62e1f6e88fb02d0ac0541 Mathlib.Logic.Equiv.Basic Equiv.subtypeEquiv._proof_5 +T 4234e3f1a65269f893ab5368aef6627dbaf6a567874301976dc7273d00c81431 Mathlib.Data.ZMod.Defs Fin.instNonUnitalCommRing._proof_4 +T 42507f84447e6ef23d2a2391e80841f096fa20ffaabe9810c196e3b9d7260695 Mathlib.Algebra.Ring.Rat Rat.commRing._proof_4 +T 42ae9144b36e2d1d6f3c2e1e81b9fd38fe52ec80961888219c7caa7b4fbb4535 Mathlib.Basic.NNReal.Defs NNReal.instSemiring._proof_20 +T 42b4cf233d4482dab276ae4b12927ca3907679b601650eaa00e1689ce1b5c494 Mathlib.Algebra.Ring.Defs Semiring.natCast_zero +T 42ec597e0f02dbef13d02577b7231ddee08a02a2cbe75e0ea86f69b1b60a6084 Mathlib.Algebra.GroupWithZero.Defs MulZeroOneClass.mul_zero +T 431aa37fc465c8bb77e0746fe65afee26e5a2c905155ad1e654a8e91dc34b2e5 Init.Data.Rat.Basic Rat.add._proof_4 +T 437160c0070a56d1c693cf4610f6960593aa3f0845bc2079d4ceb538f977e4c8 Mathlib.Basic.Complex.Basic Complex.addGroupWithOne._proof_5 +T 43bf0523525df425dc0734a70170710bc9031b08ebff69f218cdd03d96acc768 Init.Data.Nat.Basic Nat.le_of_lt +T 443254a78d424b947f154443e0779132ae9f2356352678fcc59a8eca10e23964 CertiFri.Challenger CertiFri.instDecidableEqObservation.decEq._proof_8 +T 44567674c7008be2118c41468be66500ac5cdc1c88e10a1a8752a459b47a4e19 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.instCommRing._proof_22 +T 445efa9d63d6257828419b80e1b2e302b301af3ad058fa3e9d00e58eec5adb1e Mathlib.Algebra.Order.Ring.Defs IsOrderedRing.toPosMulMono +T 447db045a31eb57f73b9f2dbd8e3f6c9666e7f6759f1f7d3db4b2b86a906b1fa Mathlib.Algebra.GroupWithZero.Defs MonoidWithZero.zero_mul +T 449a395253006c1c226d5dd7337f2cfeee527dd2aed2abfa0fd0a12108ac7654 Mathlib.Algebra.Order.CauSeq.Basic CauSeq.instAdd._proof_1 +T 44a6df5c8239dd295b63a8f318d07e34dec5e9a250f20ecbcc12a7adced209fd Init.Prelude Nat.eq_of_beq_eq_true +T 44b52da8235054fa46c526998315a59c9405384497b6222e64a83e0df5ae1657 CertiFriProofs.P3.GoldilocksExt3Model CertiFri.P3.GoldilocksExt3.starkModel._proof_4 +T 44caeafb5910439804e7391813a730b0803f19c535fa978d8e712c6592e3093b Mathlib.Basic.NNReal.Defs NNReal.instSemiring._proof_4 +T 45429d902579809ed450349bed561fd519ed970eb157f7b33ab88ff0cea7df95 Mathlib.Basic.Complex.Basic Complex.addGroupWithOne._proof_9 +T 45b1f965922d5aa5ec38299b0cb5fe5235a44a80ca1a023cc0600486708c070e Init.Data.Nat.Power2.Basic _private.Init.Data.Nat.Power2.Basic.0.Nat.nextPowerOfTwo.go._unary._proof_2 +T 45ce818eb7f29c72f81fc8e7c006ba02a7687a4d78aac50b43614cc4a8d32b0c Init.Data.List.Sort.Basic _private.Init.Data.List.Sort.Basic.0.List.merge._unary._proof_2 +T 45e1527b562d13db18ed6859a3001b48f6535568f84d9bf33a70f69aada9a6c0 Mathlib.Algebra.Order.Monoid.Defs IsOrderedAddMonoid.toAddLeftMono +T 4603d6e1c367aa8da380c075095784fc32de409bb9e205ae273cbf51b2bf3fd2 Mathlib.Basic.NNReal.Defs NNReal.instPartialOrder._proof_5 +T 4652d36099a01aa0f75a167c338e89e4aeddacd2f138004d1bd63eb1eaadf51f Mathlib.Algebra.Polynomial.Basic Polynomial.semiring._proof_13 +T 4672bd229c5c3ee69ad52c6e9e4e8a8c392a4becf437ea45d92488e560bbbe47 CertiFriProofs.P3.GoldilocksExt3Model CertiFri.P3.GoldilocksExt3.starkModel._proof_5 +T 467b4917f42cc9c7edbce91b7d08496d72b6371108437822a297485dc559597d Mathlib.Algebra.Group.Fin.Basic Fin.addCommGroup._proof_1 +T 469d53e8eef6f0d243bbc692dbbd6add7a3910333f50ab7748de4c7503c921ff Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.nonAssocSemiring._proof_4 +T 46d2025f0787b4c30b1c02e92923e7d73d0c7413a0ceb56e07fbe1aefbe38f3e Mathlib.Basic.Real.Basic Real.commRing._proof_18 +T 471db5a813d09a467a6b3eec266afc031a83aeac6f6495e7407099a4cc0f10e0 Mathlib.Order.Basic Function.Injective.preorder._proof_3 +T 472a3b1ffc0e8d12b426b2e6e9acab7964cc1e6aca6cc0b29a86d6c5b2909b24 Init.Data.Option.Basic Option.instDecidableEq._proof_2 +T 47644c1a64cf571b5ddd57834c129873f1cff7698f930b328d2e6198386fec03 Init.Data.Fin.Basic Fin.castLE._proof_1 +T 476f7de034ae68428bb79601e5683cf0945a2ea3b52fd5678246287631356446 Mathlib.Basic.Real.Basic Real.commRing._proof_12 +T 4785984e305bb38625e156022cac5c59e529129afc24e3b6493ec19e3f0cd8f4 Mathlib.Algebra.Ring.Defs NonUnitalNonAssocSemiring.mul_zero +T 479d0104f7fa7273e98bce1b9e2cf11428725eb51358f5d9d697776329c95cd2 Mathlib.Basic.Complex.Basic Complex.addGroupWithOne._proof_3 +T 47ff4eb8ca7daa255942e915f6cf0fdc893b21deb87a88b397bad9f0bd38b9da CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.GoldilocksExt3.toModel_add +T 48128cf9c6d89a0e301a591ec6438db8f55eb66b4cc1f009e31f718138064cbd Mathlib.Logic.Equiv.Defs Equiv.trans._proof_2 +T 486537a9a5316c79f506bf5dcd31cc99b3b5ce7a74d75c603cc3759339714f2e CertiFriP3.Digest CertiFri.P3.instDecidableEqDigest.decEq._proof_6 +T 4876d4e28a3b5a218cfd9cd7d113726ff5f1977588f83f2183c8c6f40059e813 CertiFriProofs.P3.DigestCard CertiFri.P3.digestEquivFun._proof_1 +T 487b95a27e0e8a7511e9b08e80d13f6ea690ab971d9e72c5189745baf941820d Mathlib.Algebra.Field.Defs Field.inv_zero +T 48ab6e9185d4212e7e739a793f3537ef8ed22d69ba96e02770b5ea238b6f1ea0 Mathlib.Algebra.Group.DivInvMonoid SubtractionMonoid.neg_eq_of_add +T 48d61a9517e7e7cfb94838ffb72b3adad3af8347633fa30034ad61f2dcd6e23c Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.instAddMonoid._proof_4 +T 48ea1f83f716fff9ecc0b9a4595e52d532456e78175545222a69c713bd0d1dbf Mathlib.Basic.Real.Basic Real.instDivInvMonoid._proof_2 +T 48f13785ee03f146e94586049cf5ac68a476f7e120ac9402f1303e91bc27c124 Init.WF WellFounded.apply +T 49118aa845d6846cab3ba7cd2f75b811436f2e1f67d1cf06db9f262d41f46ff6 Mathlib.Basic.NNReal.Defs NNReal.instSemiring._proof_10 +T 493a5529c68583153672bfd11d6915a804ed365290d15cde6300673279b98ba9 Init.Data.Fin.Lemmas Fin.mul_comm +T 496928f355feeaa37242866f19a2e9cf2bfcbabd623e5ca6b874b96734ff81a1 Mathlib.Data.Multiset.FinsetOps Multiset.ndunion._proof_1 +T 496fa2f21d0a368f4be7ea9e183d29fc2740d50c8865fddff6e89d93c2d370a2 Init.Prelude Nat.sub_le +T 4986757c90bfb6f588f51ae49b80e496cbe86e479487837d67fd440d7714cfe5 Mathlib.Data.Multiset.Defs Multiset.decidableDforallMultiset._proof_2 +T 498b3614220c1d88b56378acad26cf381305c73030a9a5f6b164a3afe6a71757 Init.Data.List.Sort.Basic _private.Init.Data.List.Sort.Basic.0.List.merge._unary._proof_1 +T 4a042b1476d914d08ea4eea964c36cad760c209fb3d84f7c7eafe3b91534bd6d CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.instCommRing._proof_21 +T 4a0e8ee55ebe65ca53151d6b883f0758bfdb0e5deba5b24bef5a47d0bb9d8ccb Init.Data.Range.Basic _private.Init.Data.Range.Basic.0.Std.Legacy.Range.forIn'.loop._unary._proof_1 +T 4a2b63da1557bab1c49beff0b14dd29208aabb17b0af670927eaedc073312237 Mathlib.Algebra.Ring.Defs CommSemiring.toNonUnitalCommSemiring._proof_2 +T 4a800f4fcaf11022224d9e88e0ec317353f9562afd2d963636063905e99d5e9b Mathlib.Algebra.Polynomial.Basic Polynomial.monomial._proof_3 +T 4a8215602add64b20496e3dfc05587dcd323a830a9fe87ec92875ff1d901b31a CertiFri.Challenger CertiFri.instDecidableEqObservation.decEq._proof_2 +T 4aaf605c5f20bdd5cccc818ef960012763f7f5663f7429e02d6616f9779b00cf Init.Data.Fin.Basic Fin.add._proof_3 +T 4ae6039f52832c3b2b47d7955f81556c5e33ab54e23f1a009bc5cfb69cace52a CertiFriProofs.Exec.Stark.SoundnessPinnedSpongeMulti CertiFri.Exec.Stark.shardCompPinnedMultiSponge._proof_2 +T 4b155d3476017d1ebb4a46b7a05e695c67e723b5fedd6193ef82519345821c42 Mathlib.Basic.Complex.Basic Complex.normSq._proof_1 +T 4bdcf0cf7bc6fcf9c0406f2f88e115b375394f2ecedcf0e1355576ec56f7992c CertiFriP3.Digest CertiFri.P3.instDecidableEqDigest.decEq._proof_3 +T 4c508fa7322116b2d0f63daa6e26ba54474a171ca7f461b303a50249f4e26cec CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.goldilocksBase_refines_fp3._proof_4 +T 4c66948d621eba1990da7471f03aa741c41c06ce78b24ad98c9226a8b0b90372 Init.Data.Int.Basic Int.decEq._proof_1 +T 4c878627bb8676b6da4b82a37875d791fde5dc1dcce8739b528ef914a9d90667 Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.semiring._proof_3 +T 4cb79ee14943c8aeacfd378aa5b5ccf8de52db76f125ef4a199685e0758ae2f7 Mathlib.Data.ZMod.Defs Fin.instCommRing._proof_4 +T 4cd737cd044bf7ee43452969e70b74ad1a0d455a0fdc208b96b2f790ca2d26e5 Mathlib.Data.SetLike.Basic SetLike.coe_injective +T 4ceb7c119bae05c48a957530695b53b4897a699e83a096fadaa69e4a9a19e20c CertiFriProofs.Theory.Oracle.MerkleFrozen CertiFri.Oracle.instFintypeSpongeAnswer._proof_3 +T 4d11f1231e69ca3ab66b8e8c01ac544af95c7b15dc2a996fa5faf45555eb2dba Mathlib.Data.Int.Cast.Defs AddGroupWithOne.zsmul_neg' +T 4d23cd3b9f0f31f740b338c64828ca2208187e620ed0f7d7fefc838c3caa451b Init.Data.Nat.Basic Nat.zero_mul +T 4d2acfdbb542b47f812c66022b1e56681264c1deaeb891323f6737a1c05fe93e Mathlib.Order.Lattice instDistribLatticeOfLinearOrder._proof_2 +T 4d4896e42962a0109fc8c52d43840c28e2d6b27436dedaef5c0a87d2a4518ec2 Mathlib.Data.Multiset.Dedup Multiset.dedup._proof_1 +T 4d58aa838ea137b8aaa0f0a815bb95adec24a0d04303af31e29353b1903d841e Mathlib.Data.Set.Basic Set.instDistribLattice._proof_9 +T 4ddcd5c93fae0534eb3bc30b049029f03c48b5d8b0eff99896306655aa8d0f13 Mathlib.Order.Lattice Lattice.le_inf +T 4debeb3bf9f64fdaf19ce5d08c8c995f4abfeb4e1beedf7441d8ac8d15a5107e Init.Data.Array.DecidableEq Array.instDecidableEq._proof_3 +T 4e30e06449f0976f862af8b09d3f4e1998bf300658487f060c0477c022629cfa Mathlib.Basic.Real.Basic _private.Mathlib.Basic.Real.Basic.0.Real.wrapped._proof_1._@.Mathlib.Basic.Real.Basic.1745762101._hygCtx._hyg.2 +T 4e391cd3e1addf93d007dee9808131cc149babb154205dcfb99f7c82702a505e Init.Data.Rat.Basic instDecidableEqRat.decEq._proof_1 +T 4e5295d5299168c0c8ee2c550415b682e505aab9e8e1b521b895b36b2dc2c0dd Init.Data.Int.Lemmas Int.add_mul +T 4e63485531fefa4e141cd1ffa685c87abde491633ba0b3f9c30847a4f6d419ea CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.instCommRing._proof_2 +T 4e7219015a8899432ba42bc2d4b36ae42828ea27fad45ec8ed43e0733c75d863 CertiFri.Challenger CertiFri.instDecidableEqObservation.decEq._proof_5 +T 4ebab2aae3428432f7eaff65083f461033bd4bf55fad6870c45d02f9101b1bf6 CertiFriP3.DomainSep CertiFri.P3.DomainSep.v6Single._proof_9 +T 4ec1fc71c811d0efd4b574d416ea7c26f57417805e040f2bf94531aaae26be8e CertiFriProofs.P3.VerifyBytesPinnedMultiKeyed CertiFri.P3.VerifyBytesPinnedMultiKeyed.verifyBytesPinned_soundness_ep1Balanced_keyed_checked +T 4fa109dc6f014ed3b99d0075324e3897ee751cc34431473819b6eaa69455eadc Mathlib.Algebra.Group.Int.Defs Int.instAddCommGroup._proof_1 +T 4feed35fe445214ddc362fabbabf19f31b29f49aba62abcaada21452d6ced078 Init.Data.UInt.BasicAux UInt8.toUInt32._proof_2 +T 4ff6c26d795741e8cf34c827f43b1765eaa66c63b127a61dab9c0f53ed25336c Mathlib.Basic.NNReal.Defs NNReal.instSemilatticeInf._proof_4 +T 5019230fc5b1f255c02b96a713e28bddf600470f0aaf7e410e707eb7bb7deaac Init.WF WellFounded.Nat.fix.go._proof_1 +T 502927b61e1d926e4d044c6c62ab9eff5f28d07530184eaab24f59a88d32c22d Init.Data.Nat.Basic Nat.mul_zero +T 503c25d631b751ac3bc5f169541c1fa4f637f6e112e6fb07dcf7a06843a7f78e Mathlib.Data.Fintype.Defs Fintype.decidableForallFintype._proof_1 +T 504001688b3cabde4652b92983595ec048e8fa0c0edf8bd1de2711a2d74a549e Mathlib.Algebra.Ring.Defs Ring.zsmul_zero' +T 507f3b203da0f63f7ad594efe332f57ccb5880ebd28d8f240749ea766acea2cc Mathlib.Algebra.Ring.Defs Ring.sub_eq_add_neg +T 508f7e1b29d8ead9339ce2b89bfb14cd437be3887bb01786e05ab338490beb2d Init.Data.Rat.Lemmas Rat.neg_add_cancel +T 5095dc15f02014fc5543c4e9687d0f3cb1294c58adf8f0947f242c6d18e13edc CertiFriP3.DomainSep CertiFri.P3.DomainSep.v6Single._proof_8 +T 50a170c8b7a8b41bee4f1aea561f536eb0392bc4c2af3877d40d96a4187772be Init.Data.Rat.Lemmas Rat.mul_assoc +T 50fbb6f67e5bd5bcdec78a9ea28ac4f393ca6b304971d58a12c39e0cdb4ec730 Mathlib.Algebra.Ring.Defs Semiring.mul_zero +T 5148c8a808d033b0b32cf45fc577964d349a11e46fb90f80a3bf6d99c66e0ecc Init.Data.Rat.Basic Rat.maybeNormalize._proof_2 +T 5181d8908725e2fa3e69291f7cc3049a70b2bd946c5048290bda78d88a91be48 Init.Prelude Nat.lt_succ_self +T 51c10ae5fec121a04875d4aafd7054d4ad0bb0f35ca5a5db8bf6e7a2465eb867 Mathlib.Basic.Real.Basic Real.instDivInvMonoid._proof_4 +T 52159fd54a0735e3b3b1c6fba7dfdc94b10b4eca61059c2d8676d00bb885150b Init.Data.Rat.Basic Rat.normalize.reduced +T 5269b347f9e1020c3e431a531a6342e3d11e9a8c2c4e40318f9ce2936b746812 Mathlib.Data.ZMod.Defs Fin.instCommRing._proof_2 +T 527982873b4e6f0ea9222fec482326a1b79abd8b455b90e63c2b1c65da70160f Mathlib.Algebra.Order.Ring.Unbundled.Rat Rat.linearOrder._proof_2 +T 52934bf9939a09a87c47007d7cb25125d14e26e171398b79fe1021055f080674 Mathlib.Algebra.Group.Pi.Basic Pi.addCommMagma._proof_1 +T 52bbb739478123d34ec1728d300bac07e854759b03a5aee6a0073272b2232ce1 Mathlib.Algebra.Group.DivInvMonoid DivisionMonoid.mul_inv_rev +T 531f14343869ad397b04aa004d94723cd53ac9934a4b8bff9cbcd7e4b6628add Init.Data.Nat.Basic Nat.mul_comm +T 533be22585734fcc0d146933175f86e2e61d6832d40d9f45a05d1160020da6d1 Mathlib.Order.Basic Pi.preorder._proof_3 +T 5354ce6c285a36d527a48369fe71a7d4ba427f4a5a8c2e85b941dc9be223d7af Mathlib.Data.Fintype.Defs Finset.mem_univ +T 5360d2cc73b05543c4942b035ac0f751b631ad6f3bd93ed501e3ecbc584d53db CertiFriP3.DomainSep CertiFri.P3.DomainSep.v6Batch._proof_5 +T 53cc4b89956b837fcaf76a466f3741335e500645028f0939f13acb77977b6919 CertiFriProofs.Exec.Stark.Model CertiFri.Exec.Stark.StarkModel.wellFormed +T 53d075f7ed57932d3ca7bbb8fedd1f23478449ad77b8c822b05ed081b364e7ca Mathlib.Order.Basic Function.Injective.preorder._proof_2 +T 53e2218b97df5c201f9a05bea66f63a2100b7794016b56c9921b3fd2c3be7afb Mathlib.Data.Finsupp.Defs Finsupp.instFunLike._proof_1 +T 53e30a3f56f41699ec1be100d134913100d37f846b632c90d131bca675c03e63 Init.Data.Nat.Basic Nat.pow_zero +T 542ad3d365eaac9926a50a14d5be61bd55a555fa2b8f9636042a815770c39e1b Mathlib.Basic.NNReal.Defs NNReal.instSemiring._proof_27 +T 54889ea2378293e4d50c7284c7617d994748615e47ec41be5ae1c51e126f1170 Init.Prelude instInhabitedUInt32._proof_1 +T 5505a563a63512ff0166a4c5c667962a10ec5d140e106b153b4f89e5cd63dc96 Init.Prelude instInhabitedUInt8._proof_1 +T 5505f12298532be53ce1cf9c20212b8da4cd28f2819d8fd196c17e2b80b83e31 Init.Data.Int.Lemmas Int.sub_eq_add_neg +T 5559b9971ab53a464d11a49227e707d10164f5d108d716afdcabf2d749699ded Mathlib.Algebra.Field.Defs Field.toSemifield._proof_1 +T 5587d763b9b3afc56c49cf58fecf43929fbafb0a5190b2304b4f9f9ad0df3507 Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.ring._proof_6 +T 5590e070be10db14b909ece267607a6ae2baa8811e55152fd4e0e36ca39406b3 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.embedHom._proof_3 +T 55bb0672dfcbcbedbd18d7f9cf28b5419e3eeba9c98812988e7c6f919b381bbe Mathlib.Algebra.Order.Nonneg.Basic Nonneg.add._proof_1 +T 55e42d83ebf29948d98ef99657afe0be4780a1e3fbcbce95b11e1f10385c9ca8 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.instCommRing._proof_19 +T 55f57b380ddfa96a9f7a39bf6239675a1d1f1efe5c0e928c09e1127755f9bc21 Init.Data.Nat.Basic Nat.zero_lt_of_lt +T 5623ee6fac13d2c95320077cfe72a229bcef980d3057c6e96457daa80d006d03 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.instField._proof_6 +T 56404ae632fb59bc157f7a7f6c921aacd8989130edd299b49c373695b9b823d4 Mathlib.Logic.Equiv.Set Equiv.ofLeftInverse._proof_5 +T 565460aef629da63a8461aeea08ac68b89cff624b538d519d0983316baf38944 Mathlib.Algebra.Group.DivInvMonoid SubtractionMonoid.neg_add_rev +T 56a01356b61f51ae0a67ad57383d15f2600e50b907afb312589e5e41f14c60ff Mathlib.Algebra.Field.Rat Rat.instField._proof_2 +T 56c0f755628fc9bffd171f33b5bded0a9c067b6220b1e0b104bb5426d9dc9dc9 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.instField._proof_13 +T 56e9f482b7270cc22b9193ea80a1bafa92b488c125135184499f7f2b20acce5c Mathlib.Basic.NNReal.Defs NNReal.instSemilatticeSup._proof_3 +T 574c82b1acd5117bdda223b4f01bfe1c3300e1933c0cd0d4ea3ce5b4e8be1ba6 Mathlib.Basic.Real.Basic Real.commRing._proof_17 +T 57760eaf0ea0675f1c2de331566939e10216d489ff7d5edbfcb84f3936cb114c Mathlib.Basic.Real.Basic Real.commRing._proof_3 +T 578040d39d78ef088410eeed396f8fcb5a959ebb831b657d2eea9377c7986a02 Mathlib.Data.Set.Basic Set.instDistribLattice._proof_8 +T 583171f1bf147b6b99b9a2f1cf3754f7932a49c8fc95773f7b94347d80d1067b Init.Data.Rat.Basic Rat.mul._proof_3 +T 5858b9d2e6d56ce4902ac6ef942b2693ce676bbcd43ae12242d88a27de629c86 Mathlib.Algebra.Order.CauSeq.Basic CauSeq.instMul._proof_1 +T 58748f9f639af9b13f4682515cd59f237e761b0b94f35e8c800df83d3e2c9a04 Mathlib.Basic.Real.Basic Real.instZeroLEOneClass +T 58d2ff7564e43cc553292cf76fb11d72b1a8ffb84c687c885e7244ab4ce00dc4 Init.Data.Nat.Basic Nat.one_mul +T 590a1a69dbea94642f5a6a3d11dd31d7ea353551faa14571846357f0813e328e Mathlib.Data.Fintype.Pi Pi.instFintype._proof_1 +T 590d26615559f6e936e39221907e04f479f3b0b636957935d23de9ff4c40a8f9 Mathlib.Algebra.Ring.Rat Rat.commRing._proof_1 +T 596fbbcaf392dc0157dc9d96e90aab8e1f69d9079d84b70514e6ea8435944ddf Mathlib.Basic.Real.Basic Real.instDivInvMonoid._proof_3 +T 5991a96af48c5b345de5d4dbd400e00b5d73358b2b2d75253b433d0282102e27 Mathlib.Data.ZMod.Defs Fin.instCommRing._proof_6 +T 59ab336da10f53b08854a82fe98fdc4f95dc285b87dc1b28b43e76653ee1beb6 Mathlib.Data.Int.Cast.Defs AddCommGroupWithOne.intCast_ofNat +T 59ce6c458829a02cf9d1be8073b2d71470dd272f6ba7b1bd06d2ba153a431c69 Mathlib.Data.SetLike.Basic PartialOrder.ofSetLike._proof_1 +T 5a5b7dcdce84f220c896a5ffa348182b0ccc124f66432dcddaa2e8bbc8954f76 Mathlib.Data.Set.Basic Set.instDistribLattice._proof_2 +T 5a8085fcaba6daa1a405c7ae1bf42906fe38f990233310b33a4db1208779ad42 Mathlib.Basic.Complex.Basic Complex.addCommGroup._proof_4 +T 5ab2676651644757f194b83e69bd8a6af1ad88ccbf41612825f4d778364835b5 Mathlib.Basic.Real.Basic Real.commRing._proof_1 +T 5b3195184c749c40fa28bf8c37434b9eb91d72373a0db96d32e131584ea8e604 Mathlib.Basic.Real.Basic Real.instIsOrderedAddMonoid +T 5b4d73248f1b56b4878ea1297cb03748b3611ca689a7fe8b6302a89dce3b2fce Mathlib.Algebra.Field.Defs Semifield.inv_zero +T 5b77efde1e8cd2099f9f1fc64c338ccdd16e44f7ca6fa8b06843cbc8188b3fdd Mathlib.Basic.NNReal.Defs NNReal.instLinearOrder._proof_3 +T 5bcce67151f39a78d3e4d30651f3546a62119aa0dc21890a766256a383b0abca Mathlib.Algebra.Group.Monoid Monoid.one_mul +T 5bf06be5d008db052514c6541730bdd4d6af8c768c5dea169a97ea1f0f813231 Mathlib.Algebra.Polynomial.Basic Polynomial.toFinsupp_add +T 5c2f5d072e1ab193069a2d7b4b0bb014ba51c45ed6c1765033679d554ad4f74f Mathlib.Order.Lattice Pi.instSemilatticeSup._proof_3 +T 5c504bb69cf6006906a6c59ea22da47daf35452afd926ece0070714ac2f52bda Init.Data.Rat.Basic instDecidableEqRat.decEq._proof_5 +T 5c8fbf6229ec7957fc8f219b9f3f577ba64d3d82ada51532f54376396ed2edd3 Mathlib.Algebra.Ring.Defs NonUnitalSemiring.mul_assoc +T 5cd8218364ea37bc98ad1afd251df67db08ea516a87a30b6adcc9af71f44a9a9 Init.Data.BitVec.Basic BitVec.or._proof_1 +T 5de01d9eb1110b2dd47c6daa8eff97bb66cd2db239c103cac3bb5c3895173acc Mathlib.Data.SetLike.Basic PartialOrder.ofSetLike._proof_3 +T 5e0546d84afe7dfa50dd8dabad08b6f5869f7fedb9f8f4223ea4ada836047975 Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.addCommGroup._proof_4 +T 5e0c2b007a4a958b0c922974249bebe07b4e99364cfc3ad7575d5b52f6a194c1 Mathlib.Data.Finset.Image Finset.map._proof_1 +T 5e0dcb55c9049b5faf645ef935425c24be6f94c18c557d9733365bec84ef3136 Init.Prelude Or.elim +T 5e4401bca9f14c889464f6df0e957842f93af7d2fe7a7685a4b3c8ceb5d3acb6 Mathlib.Data.ZMod.Defs ZMod.commRing._proof_19 +T 5e53401cec207f7179463463e94f07657422b9d840bc20d581ba7d330055d2f1 Init.Prelude BitVec.ofNat._proof_1 +T 5e97825855ad12f5cb4e0e1c9c70d0869a4293027a979c8d54a36fcae9319865 Init.Data.Range.Basic _private.Init.Data.Range.Basic.0.Std.Legacy.Range.forIn'._proof_2 +T 5ed008056e7b578e715aad2fb0099a52f3bc1d13eedce3889d1eb0e143863fba CertiFriP3.DomainSep CertiFri.P3.DomainSep.v6Batch._proof_4 +T 5ed602b220e5ac7ccff8b626c48aa1ae2eed462cf54efa6338921dda10ed52d7 Init.Data.List.Perm List.Perm.length_eq +T 5f213dfb9c445ba6c75a9f3ef5757223e0aea7c5d25823959638ef60f93c7f0e Init.Data.UInt.BasicAux UInt8.toUInt64._proof_2 +T 5f24a7eb36379a94924731a7944fe6cd35801413ea45c6d236cf7c41fc1dee50 Mathlib.Algebra.Ring.Int.Defs Int.instCommRing._proof_10 +T 5f293ad42c23bab27b30377469c18212de7948df30ec26b5d258483367197d07 Init.Prelude Nat.le_of_ble_eq_true +T 5f2f42abab5f668b5fa59ae987901545b765800a024b5f45888b522a01dac91d Mathlib.Algebra.Ring.Defs NonUnitalCommSemiring.toNonUnitalNonAssocCommSemiring._proof_1 +T 5f4aaa5df18aa01edaf3b6b3b87b53c8f7222fa97356b1cfad0a53c47fd84e5e Mathlib.Algebra.GroupWithZero.Defs GroupWithZero.div_eq_mul_inv +T 5f868b5629d5032bff486b17fe36d60fad860a1e4f904d03a0d1e6506c60e195 Ix.Cert.Release05.SecurityAudit Ix.Cert.Release05.ixVm2p23_4096sh_qrom64 +T 5fa85d59baebf927cae01006fa1d4beb307c9a82c7bb2a86568fcd18908fbc5e Init.Prelude instDecidableAnd._proof_1 +T 5fffa6221e3502bb3ed1c48b048043f188a2531f5cf101c77d6dcb38a018e32a Mathlib.Basic.Complex.Basic Complex.addCommGroup._proof_11 +T 60908ef6b30cdce45839393c80383f28f3cf4bd5093bb1f67d4f96685945b547 Mathlib.Algebra.Group.Pi.Basic Pi.addMonoid._proof_5 +T 60a8780183aec9816d363a61651033fc420038f4b403afac8d09fc35aeb493f1 Mathlib.Order.Defs.LinearOrder le_max_left +T 60ad14ae26ce5c068fac0488e76084bb342edb9f65af1f0589cf9a153361f1f1 CertiFriProofs.Theory.Oracle.MerkleFrozen CertiFri.Oracle.instDecidableEqSpongeQuery.decEq._proof_1 +T 60d787f596bea7fe44fee59fc299bdadeffeedde3e033e3c4b1ab2df93c22367 Init.Data.Int.Lemmas Int.one_mul +T 61349c7e91c0a640da0170af6b6fcfda5b4fec6691904e42eb3d7f2ad6521daa Mathlib.Algebra.Polynomial.Basic Polynomial.toFinsuppIso._proof_1 +T 615131ca745f15701d3d93d53bf7a958a615c4203a0e1325bd053fa50867f1a6 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.instField._proof_12 +T 6151c5b630b6547fc9d535945c9a5802dda533fdb38d880e4d1af62fe28715a8 Mathlib.Data.ZMod.Defs Fin.instDistrib._proof_3 +T 6197d2405b1bf8fe0447e2b828865d249c8701ac5a6ac4a7dbabacb8709fd4a2 CertiFriProofs.Exec.TensorExec CertiFri.Exec.tensorCoord._proof_4 +T 61d0906b11a411323db7e3764e947f24db8716fc7739b4980dfd7ab27670e3ca CertiFriProofs.Theory.Oracle.MerkleVerify CertiFri.Oracle.instDecidableEqHashQuery.decEq._proof_4 +T 61e24fe4b93ab05a566b6a7ee60ef5adfb5ac917fba071d4a3b5a95cad3025d9 CertiFri.Challenger CertiFri.instDecidableEqObservation.decEq._proof_4 +T 61fe2406b043f1f0ac57b64817770229340b6866343081709d89805d35b42bb6 Mathlib.Algebra.Group.Action.Pi Pi.mulAction._proof_2 +T 622e7e3017cb8d23734c450aab6cde1c581913914f16d7617d955d2ff3f00cff Mathlib.Algebra.Group.Monoid nsmul_zero +T 624732edc446c259487562387b327eb12906cc61e37b5b25708d24855b461f17 Mathlib.Algebra.Ring.Hom.Defs RingHom.id._proof_1 +T 627514242441aa07f119db36e1a58efeb809d184c27bf8468d28a3ee12cb73a9 CertiFriProofs.Theory.Oracle.MerkleVerify CertiFri.Oracle.instDecidableEqHashQuery.decEq._proof_6 +T 62790d4ac385c0065f3997eb16486864f21b21212051524400f81ee0545e1dc4 Mathlib.Algebra.Field.Defs DivisionSemiring.inv_zero +T 628b9a86e73406a620e7252871ecdf7c9fa6592f8e3d9e9e578775bc427aa3a7 Init.Prelude Nat.le_antisymm +T 628e2015da2c518c02b93f652a1b7d7800b0230cc6ef8ccd5d59f2af08ea397c Mathlib.Algebra.Ring.Rat Rat.commGroupWithZero._proof_6 +T 62ad9a5e1befad41a9cb62be4198ebf5906a555ed1ae83a279f5424cefa7c0a7 Init.Core Quot.indepCoherent +T 62afcb81f0232690f02035c34d6d48b58cc8ec1461288d63d06ccb7c0fbb8f5f CertiFri.Params CertiFri.instDecidableEqFriParams.decEq._proof_5 +T 62b6db99640759c784f305c3706017c8f542470466f4f8aa3133730fa84fbbec Init.Data.Fin.Lemmas Fin.mul_one +T 62c438a6e99554c8a747a51a2597f2fd7bdcb81af0c4cef4e8ded9fa2db778a5 Init.Data.Nat.Power2.Basic _private.Init.Data.Nat.Power2.Basic.0.Nat.nextPowerOfTwo.go._unary._proof_1 +T 62e93e3abb40d1e9daedc5fdb8edec854463594552d512c1cf512669ce86ff4e Mathlib.Algebra.Polynomial.Basic Polynomial.semiring._proof_6 +T 62ffee2f7f33afb9f8084dbb96376452aff60cbd478cdf0d2466eb965553540d Mathlib.Data.Finsupp.Defs Finsupp.zipWith._proof_2 +T 63672de0cf18fad365adfb07704a0166563027cb5521bfd37bd60e0954bccbc7 Init.Data.Fin.Lemmas Fin.add_zero +T 63682c7b28b28a5f8d723ce266889033d90614435050e4fb9040f0e3a5892d2b CertiFri.Params CertiFri.instDecidableEqFriParams.decEq._proof_6 +T 638c79c0d180a553c37c8b9bd9ff283a78b5b693ec04437e2ffab93db1b16563 Mathlib.Algebra.Ring.Defs NonAssocSemiring.natCast_zero +T 63c139d85f401468cce67377cefe011123499d6afda591d1a8409ef9eb5fa235 CertiFriProofs.Exec.TensorExec CertiFri.Exec.tensorCoord._proof_3 +T 63e1ff0f6b3cd192993615e86e133c981929fcce314bb3a5e68138f2ea5f15d7 Mathlib.Algebra.Ring.Hom.Defs RingHom.id._proof_4 +T 643efce1d1dca9fd799d5fdf509d6f67d7e528dee9135437958d75587e94b258 Mathlib.Algebra.Ring.Defs CommRing.toNonUnitalCommRing._proof_5 +T 643f57c9b35a9897e33245430371e541464696adcb41e26dd200b3e514bb872c Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.nonUnitalNonAssocRing._proof_2 +T 6451a44b46afcbb1309bfaf1b27b28e7af9b69aa542f908c74aef8ee13325553 Mathlib.Algebra.Ring.Defs NonUnitalCommSemiring.mul_comm +T 645348327871c04e0893a6a49f3320bf6ca33170ab94bbb8a0addbf7804487cc Mathlib.Data.ZMod.Defs Fin.instCommRing._proof_8 +T 64974eacc507770737abf72463b678b482a689d4f81b43724e6d21f71a0a0af8 Ix.Cert.Release05.SecurityAudit Ix.Cert.Release05.ep1V6Hop4_qrom64 +T 6503c01dbe510171f5724233963eec178279b5953d1241ffa81286fb46ed2b88 Mathlib.Data.Multiset.AddSub Multiset.nodup_singleton +T 6511bdb537758952e8299a5be2f55585f3bbd3470c26184be3f4858435f17763 Mathlib.Order.Defs.LinearOrder max_le +T 652de5bad6e6e44e98b9fc5c2413bdb6e1bf9d9f7e3a2ad63343742e66f867f8 CertiFri.Challenger CertiFri.instDecidableEqObservation.decEq._proof_7 +T 65625c8377c3764bb24fced27c892833a431675d828663c190ebbb8222bd1009 CertiFriProofs.Exec.Setup CertiFri.Exec.FieldModel.leafDec_empty +T 661bd2172840903085f4998299df39e4cf510130a47a66dcb26680616d2189e6 Init.Data.Array.Basic Array.anyM.loop._proof_2 +T 6666c5d8ee04fa6d8034c0a61107838a2a2c1fc1402a26b5c6f48099b755a24f Mathlib.Data.Fintype.Prod instFintypeProd._proof_1 +T 66f184d611938862ffd696194ca5589fca90e9abb428360b7fbaa4a422cce360 Mathlib.Data.Int.GCD Nat.xgcdAux._proof_1 +T 6714f15346d1b366c1863ff6a7d6a6e20a036a30c57d01fb4839802e1a1e696a Mathlib.Algebra.Order.CauSeq.Basic CauSeq.instMaxAbs._proof_1 +T 6763072e0a35d5ad843a3da59f31e3bd9ddfe6ef614c3d10d348dd3fe2023a9f Mathlib.Algebra.Group.Pi.Basic Pi.addMonoid._proof_4 +T 67a08b0b01613c2b47a990346448a8e679c3c0282cad61ea953a5e6983b5ab26 Mathlib.Algebra.Field.Defs Field.nnratCast_def +T 67cfa1f81cae50def032f009ba784dac4e4302008b078ae4f5226e15fdec0454 Mathlib.Data.ZMod.Defs ZMod.fintype._proof_1 +T 67f0fd4b0a133ad8de165fcbbc24171f03df45fe6c371dcbb59681d546117341 Init.Prelude Eq.symm +T 6827ac49741560ea95dd55b4d3867d56717540b09eadaf06b3f50bc0ffb3f4c6 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.instField._proof_7 +T 68b0dda71958182fd4ffe28205b6fbd70c42085f1808e849ebe06238b618bcb3 Mathlib.Algebra.Order.CauSeq.Basic CauSeq.instLTAbs._proof_1 +T 693873c5a811196720f8c9fc87955ea62fea6524c433065688bf9541e9b1dd59 Init.Data.Rat.Basic instDecidableEqRat.decEq._proof_4 +T 69421bdb9e07ed6a34aee63a2a501d5ff03ad6dca7332bce65da1703861e157a CertiFriP3.Pruned CertiFri.P3.Pruned.ascend._unary._proof_3 +T 6a1814a76a48e0c139ebda9b48ee071968ae69883227e2bf7aebca579246fa10 Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.ring._proof_7 +T 6a2cd9223b3fcbdab193ec3465a90bd46f1d984590a4ffc4296a2edfe1dd2538 Mathlib.Algebra.Polynomial.Basic Polynomial.semiring._proof_17 +T 6ad13ff0375c57e01f08d03f96ad52b707901e6d108aa1b4e91e6fcf24cfd378 Mathlib.LinearAlgebra.Lagrange Lagrange.interpolate._proof_5 +T 6adeb5f8399450baf715a77b7a10c3c797b3cc02ecfa0f9e349c9086533b39bc Mathlib.Order.Lattice Lattice.toLinearOrder._proof_2 +T 6afa32a0404655b8814b9feba4942a03d1579f5a5b632e6e761b4b55b75089bd CertiFriProofs.Exec.Stark.SoundnessPinnedSpongeMulti CertiFri.Exec.Stark.restorePinnedPathsMultiHashM._proof_3 +T 6afee6ece585c0a70fecd266827bd458afa8b7ef16676e490e9df44ce7396f96 Mathlib.Algebra.Ring.Int.Defs Int.instCommRing._proof_8 +T 6b303ebfece1d80a61ea479de6059dd33fa9e454615cfedf0778d8cb7ad1f7d5 Mathlib.Order.Basic Pi.partialOrder._proof_1 +T 6b49201e1a966f78491ee5d3f05931be35262f6a187f58fc722365b48550f44a Init.Data.Nat.Basic Nat.le_of_succ_le +T 6b51b2749a1b32fbb319a89c50fd0cebb6bbe6787696d101417f476933be9885 CertiFriProofs.Exec.MultiArity.TensorExec CertiFri.Exec.modelParamsMulti._proof_5 +T 6bff543ed8e59ff6f48d50d7253dab4d58fdc698beecde097b9d03e5dbefa931 Mathlib.Algebra.Polynomial.Basic Polynomial.semiring._proof_16 +T 6c1c7e5b58af61db33976770ba30ee44479ac8ca9c85cb489944c702884e0215 CertiFriProofs.Theory.Oracle.MerkleVerify CertiFri.Oracle.instDecidableEqHashQuery.decEq._proof_3 +T 6c7b30c48358def36af1df73bafb19de319c1afd04ada7ae0990909e8c7b1265 Mathlib.Algebra.Field.Defs DivisionRing.toNontrivial +T 6c8ac6f5259d5946e211d12508e27e31fa8e613f442089ed5e5b571bda2978e6 Mathlib.Algebra.Order.CauSeq.Basic CauSeq.instMinAbs._proof_1 +T 6c9b0d688c9f89d21d5ce8441cb9ffe8d1dcda5c045562eeb0d00c7c802b1f86 Mathlib.Algebra.Field.ZMod ZMod.instField._proof_6 +T 6ca5afa27132c0faea61bc3102941b042f8a1a523b21944c8e3336148e26ef29 Mathlib.Basic.Complex.Basic Complex.commRing._proof_5 +T 6ccf7677047a63c1004b0fd3434f7aa089036d9cb13c081345a45f805ffc1862 Mathlib.Algebra.Ring.Defs CommRing.toNonUnitalCommRing._proof_3 +T 6cd591541acf3d6f050a60843f121784b427a9fdf69caf5b74f9a2ed1d408f47 CertiFriP3.DomainSep CertiFri.P3.DomainSep.v6Single._proof_5 +T 6cd6814512d3e19eebdee3e1b8445cc81c9c42f9d209ab97b4fa0908e240a543 Mathlib.Algebra.Polynomial.Basic Polynomial.module._proof_1 +T 6d1859b13ab9a54fe4528a5ef6bbe9478198f73ea845bfe3e052dbe2d2eda0d2 CertiFriProofs.Exec.Stark.SpongeGoodLogTensor CertiFri.Exec.Stark.instDecidableEqSpongeStarkMsg.decEq._proof_5 +T 6d7fb243eee9961447395c804110465bd53dafe938a725c5eaa2f4b666fe31b6 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.goldilocksExt3_fieldModel._proof_2 +T 6dbd46f9255f5ff3ca44b847a3f398f33887e597d5c2c5da97cc2ef7d6422ad9 Mathlib.Algebra.Field.Defs Field.div_eq_mul_inv +T 6dde7f72fceeeb8fed101ff557ca7e117f1ccffa89a054c2d643b4f63a19b130 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.embedHom._proof_2 +T 6e2cb42f0d5cacaf018e10c178cacb57a012843ddcccf5b1b17e6f06ab7570d7 Mathlib.Data.Fintype.OfMap Fintype.ofBijective._proof_1 +T 6e3c5f1f0f0d44575e3c3fb1fdfd2c1d10083ea0b8ee93b302b6bcf8d8fe54c3 Init.Data.Rat.Basic Rat.inv._proof_4 +T 6e93379928a3beb00f5eba265ba4f3db1d369a1e4fbbbd325e8d655f540784bb Mathlib.Logic.Equiv.Basic Equiv.subtypeEquiv._proof_8 +T 6ebfbc6582265febe8d3d5c50361017614c90fb915af61db3beaf931169cb932 CertiFri.Params CertiFri.instDecidableEqFriParams.decEq._proof_7 +T 6f1810cf91233409e81e668798e464afd929002603273d2964fe191dc91d9dca Mathlib.Algebra.Group.DivInvMonoid SubNegZeroMonoid.neg_zero +T 6f49deff7c8ddce1e6d4aebf1e121e89a06ef4a8840691be8c84b6fe419cc14e Mathlib.Data.ZMod.Defs ZMod.commRing._proof_6 +T 6f4bc4a647adef3409bf31b34b7b958769ebb521f2c44ffcb07b0dcc139ec696 Init.Data.Nat.Basic Nat.lt_succ_iff_lt_or_eq +T 6f6911761a676042ee7e00aaa4ebcd2a1a7aa77855db51638e585361837437f1 Mathlib.Data.Set.Basic Set.instDistribLattice._proof_6 +T 6ff038f28eff767eda6d87151f68139b50cfd4f2666ab88aa3ba8e65a527465b CertiFriProofs.Theory.Oracle.MerkleFrozen CertiFri.Oracle.instDecidableEqSpongeQuery.decEq._proof_4 +T 6ffb68877d1fc1a377bfe224323506f6d5a6757277da9bfd982b645ba680b2ab CertiFriProofs.Qrom.StdEquiv CertiFri.Qrom.isUnitary_combinedSteps +T 702861c8753e08340ff74293b5718ff2e398f83fd89473fd3d4d73706774ae47 Mathlib.Basic.Complex.Basic Complex.addGroupWithOne._proof_6 +T 70703bd29b81bfb0ffb0885047803908ae8ea8d3b424ee46bac4b27a1b78ec9a CertiFri.Params CertiFri.instDecidableEqFriParams.decEq._proof_3 +T 70c4673f00174a39a052235ce5d543cefafd953b07a9d21e2370553c76ef29e2 Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.nonUnitalSemiring._proof_1 +T 70e7a7c9d7990f7090cc45236daf9041d8523fd7de4cc3ecdc4400f5077774d7 CertiFriP3.Goldilocks CertiFri.P3.Goldilocks.invLoop._unary._proof_2 +T 7147380bbed4e5e8abc0cecc4b2bc6b19e8906fa610dc50c1de0fb3de81b54f4 Mathlib.Algebra.Polynomial.Basic Polynomial.semiring._proof_4 +T 71f41213f9a1edd12217f7d249c8e85405e96ad99a02b73bfbe7828b585c7422 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.instCommRing._proof_13 +T 71feecb3f3a1b18a8b9d30c4330b071c8cb9e8c4ec13d1bd5cd865d7fd14207c Mathlib.Basic.Real.Basic Real.leTotal_R +T 7202af82968775addd9e18b11ccb442e3414e07acfac264bc895293446e60cb8 Mathlib.Algebra.Module.Pi Pi.module._proof_2 +T 72595c33707cb973d64dc0a5f2eb9be6944aa690e459d6f31d954e7a6dde1901 Mathlib.Algebra.Order.Ring.Unbundled.Rat Rat.linearOrder._proof_3 +T 726da66edeabc0ec9acfbb6941acad87af45068426ea13a0e18851acc41d1268 Init.Data.Rat.Lemmas Rat.zpow_zero +T 728302b4248c67c2527d7f1fb18ce59eef6c0accc5ca15e8eb212cbff4482bb2 Mathlib.Order.Monotone.Basic StrictMono.injective +T 72b2928952f5b16703f2efdd48b0fcf45d3f14280b1b542905ec1ea45ef98d02 Mathlib.Basic.Complex.Basic Complex.normSq._proof_3 +T 72b3f0065d6d4a9300df63d6e671a69e598d220175c3d572d0474dca556f78c0 Mathlib.Basic.Real.Basic Real.instDistribLattice._proof_6 +T 72d2f3769d49dd506831b9fbd77967228bf52e8804b8a1eb0af6dc6a736320b9 Mathlib.Basic.NNReal.Defs NNReal.instSemiring._proof_26 +T 73437cb32cc9cc9c58b3e40da3cee5fa9143e19e365a1448b59f70ab1f746043 Mathlib.Algebra.Ring.Defs NonUnitalNonAssocRing.toHasDistribNeg._proof_3 +T 73ae4cc35c1400fce24b1df1c242d7ba52115fd5f2ea6a87d1693320490f6f8f CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.goldilocksExt3_fieldModel._proof_3 +T 745ffabacd78638ae9c6b54fd05f0a1c0089c499e8d114a7135caaf645918db6 Mathlib.Data.Nat.Basic Nat.instLinearOrder._proof_3 +T 7483af7cd204104dad66239a7e4f8d91d28b47018fedd517233901f05798c26f Init.Data.Int.Lemmas Int.mul_zero +T 74ba45de69ac697f73e69582a5a91c1bc60b2b794a7a07aba56b12dcafbcaf39 Mathlib.Basic.Complex.Basic Complex.commRing._proof_7 +T 74d0660c61cb095bd0e37c48c0076f954ebefd2fd90cb1969f3c00a20e5abd9e CertiFriP3.GoldilocksExt3 CertiFri.P3.instDecidableEqGoldilocksExt3.decEq._proof_3 +T 74e62565647af6e3ced393d32949687cf21c4729cd82699243b37c03cad6cbfd Init.Core Iff.symm +T 75011565c1dd878f81315ecdcb6d74bbf0d4d28ce7c7abdf6e7772343be1d097 CertiFriP3.Digest CertiFri.P3.instDecidableEqDigest.decEq._proof_1 +T 755c6ab0aa5f4396b1144a8687c6dfcb36d4d924e2ad10fcc7a6e258c4cebe0a CertiFriProofs.Theory.PcsRbrTensor CertiFri.PcsRbr.tensorCoordWeight._proof_1 +T 75af2c8cc7bd2fb95efd79cbadd0c20e44f9647c3e779bd83ccbc45d44735310 CertiFriProofs.Theory.Oracle.MerkleVerify CertiFri.Oracle.instDecidableEqHashQuery.decEq._proof_7 +T 75e8f6debeefc07c6b05f8d78cd1f57a33047d09b8b7feeb813479228478c1aa Mathlib.Algebra.Polynomial.Basic Polynomial.module._proof_2 +T 7636f45303e1209364b5979878bcc2963d22509c42d6d63fb392f20a4866159e Mathlib.Logic.Equiv.Basic Equiv.subtypeEquiv._proof_3 +T 76638f2ae6ee97934f7bcf8fd6b0318e2d6a5583b5b45d7e3e54c46cdd6d47fa Init.Prelude Char.ofNat._proof_1 +T 76f183dd840061fdbfcbe22dc91c70ddbb44fb8d35ac3ce8697752df086d8c32 Init.Data.ByteArray.Basic ByteArray.decEq._proof_1 +T 7722c1583a392ab61fbb3c169f98109f08cd854e0c5f4fef4a98d376334219f9 CertiFriProofs.Theory.Oracle.MerkleFrozen CertiFri.Oracle.instDecidableEqSpongeQuery.decEq._proof_5 +T 775f012105fad575e2cd66e2bfc4146f9511ef2096ed89de3af500e8e9671731 Mathlib.Algebra.Field.ZMod ZMod.instField._proof_9 +T 780e43969f9a79c5ef767287e2ca67b2b7f8d43c69a4930ec2b9c49167e1a433 Mathlib.Algebra.Ring.Defs Semiring.natCast_succ +T 783243e17e00c7f1caa33088251a60bba1f4824990b4a4e1854c20543c0ad930 Mathlib.Algebra.Group.Finsupp Finsupp.instAdd._proof_1 +T 7877f9a5318ab3d274b6f0a1314bd99955c9a38c0e1067473986afe2577c2de9 Mathlib.Algebra.Polynomial.Basic Polynomial.C._proof_4 +T 787fccea774de917618f177129957d1a597c427115dcceb1b7cafab3806fd6e5 Mathlib.Order.PropInstances Prop.instDistribLattice._proof_3 +T 78a266950f70ec56952695251fc313b3f5d8633c269bc7936d09020516400e89 Mathlib.Data.Int.Cast.Defs AddGroupWithOne.zsmul_zero' +T 78a63e097ed99f28d4e7d17da878f77757ced1b599c5c0dc6d949cd293d281f8 Init.Classical Classical.indefiniteDescription._proof_1 +T 78eed9fb762a5246671d42e5df06a3035196b64a3cb2e8695bad27d01e158017 CertiFriP3.Digest CertiFri.P3.instDecidableEqDigest.decEq._proof_5 +T 791db544a9a8fe1ff9bcb058a3afe5ad3d8f5d00b032751c9d9767372a5acbb2 CertiFri.Challenger CertiFri.instDecidableEqObservation.decEq._proof_6 +T 792e370058c7154336ea3f363dedc46b8c8de8caf424a84f86f229bdceb5be59 Init.Classical Classical.propDecidable._proof_1 +T 7983fc7b4779bee97529ae033dd09fe22665997ec2ba45a0db1e5022581c562b CertiFriP3.DomainSep CertiFri.P3.DomainSep.v6Single._proof_2 +T 7995c37e3b7339ed54d2352e33be5bc5c008b55c118bcae10a78d2488e011623 Init.Prelude List.hasDecEq._proof_5 +T 799b209f617e8905967a7ed3105f918917e9888dee725326dedc2c0a0bc406b7 Mathlib.Logic.Function.Basic Function.leftInverse_invFun +T 799e6e83668ac6f8eede0d16702605a2315710171afae7850f9de5a5770961dc Mathlib.Data.Finsupp.Defs Finsupp.instDecidableEq._proof_1 +T 79a2274020ac9588c252db16887a7d99262578273c8e3b7dbb32c81bd713ccc3 Init.Data.Int.Lemmas Int.mul_assoc +T 79a8ae03027c600170a49c8eb17f130c2140616dc2033e3772b879d7649ae17d Mathlib.Basic.Complex.Basic Complex.commRing._proof_2 +T 7a295100f53bb5175e50f4fb84e8772d32f3e3cb558591efd4a67dbacf204d67 Mathlib.Logic.Equiv.Basic Equiv.subtypeEquiv._proof_7 +T 7a2e9be2e4ab62a8f1267c3d5bf473f6cc58f7d39e57f047f9feb454ce82ebfb Mathlib.Basic.Complex.Basic Complex.addCommGroup._proof_3 +T 7a5abea4af55cf8c71fa05d35f2448c5824bacd71f5d553d02e5c0dbad0d6364 Init.Data.Rat.Basic Rat.pow._proof_1 +T 7a78769eba40f3b39e5d09911e5745eac279b745a76649e4b25aa06224c477eb Mathlib.Data.ZMod.Defs ZMod.commRing._proof_10 +T 7a7d359a087885f58e0de43f013becab1be6e1fadf3fc6116e9fae038edeee48 Init.Data.Range.Basic _private.Init.Data.Range.Basic.0.Std.Legacy.Range.forIn'.loop._unary._proof_4 +T 7b556afeacb0aa43ed98e1270fc5c4147676d036a65104a5bc63ef0900135ef5 Mathlib.Data.Int.Cast.Defs AddCommGroupWithOne.intCast_negSucc +T 7c52b33da7001c43b5bbbb6ab1d6a0ca264fe27d2f208bc5300ae2e1917c3ec7 Init.Data.Rat.Lemmas Rat.sub_eq_add_neg +T 7c594e56a0be9faecfd868f6255c31f8ca8bebeb8ab568a3848f408205dc194b Mathlib.Logic.Equiv.Set Equiv.Set.univ._proof_2 +T 7cd93fe8da60a095f96c530c462ea64d5c3fd99d3a1d4c94ff1ca6c6304c2e31 Mathlib.Order.RelClasses instAntisymmLe +T 7d24b4bc07dc06ebebdfd02c95d3c3e98eb1ff77590143ea356804098f16dbc3 CertiFriProofs.P3.GoldilocksExt3Model CertiFri.P3.GoldilocksExt3.starkModel._proof_1 +T 7d5b9d8b3a57320df9d73344c55c7c6908ec9d4bd6ab139fc247dd04477ce0b5 CertiFri.Challenger CertiFri.instDecidableEqObservation.decEq._proof_3 +T 7d714d1f381f17c37f346755d8efaf27328183acaa98debcc2bfc1529ddb76ff Init.Prelude UInt64.decEq._proof_2 +T 7dc30dbf03525f2d01e3a6e1285dcf6659c9631b575bf5ae8c9263f94ce62c64 Mathlib.Basic.Real.Basic Real.commRing._proof_14 +T 7de853d7bdd41818438563713fbcdd08854634572595e5bcea2fcc255f0a433f Init.Data.Rat.Basic Rat.inv._proof_3 +T 7e14918d6a05cc77f0ee3d9e483a957b8e6bd5871d0a082f3cbde52b82e5b381 Mathlib.Algebra.Module.Pi Pi.module._proof_1 +T 7e361ce66339d63e418f57cb5817d27e4619d9e37d5e1f94cb5b7833136a5e3b Mathlib.Data.ZMod.Defs Fin.instCommMonoid._proof_2 +T 7e4e2d539e3c34ad6682a1cd8806759d098b6aad5b812d4c36158d19f84f4b2d Mathlib.Algebra.Ring.Defs NonUnitalNonAssocRing.right_distrib +T 7e500ee6173ba75f20a81f9f7582dc83f38e5832d51b27348a1c272cb05b5d86 Init.Prelude eq_of_heq +T 7f5504cd17eda7d91b86452e28eb8705539c41695c86e203737c558d2f9c4ea5 CertiFriProofs.Exec.TensorExec CertiFri.Exec.tensorCoord._proof_1 +T 7f7d7e1b5a09293c8896bf5074b5272ddc8b157906055ab99ff5819e89498a24 CertiFriP3.Pruned CertiFri.P3.Pruned.ascend._unary._proof_2 +T 7fbdc278e0695fdaf2f9f3d2c5f9a590ed92d3925015394e5ce01d3a313d032b Init.Data.List.Perm List.Perm.eqv +T 7fd72ff9ce8cd10a4f58e2a16b742903c4f6a9b4a04b3792f31cc1f0985a10a9 Init.Data.Rat.Lemmas Rat.add_zero +T 8002d8b893a590c7399244fcaead9f4caa5b7cd8f3c007d9726b0c33e3f44f5d Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.ring._proof_2 +T 80e2bc84d1a6484a8be0439cab9cb963e24d0847e43f0a2a7375770afa32028b Mathlib.Algebra.Ring.Rat Rat.commRing._proof_5 +T 810d42830eeeacd7e388f5d8e14b19fa30689488f79bd57a3956b7da1d7a6924 CertiFriP3.DomainSep CertiFri.P3.DomainSep.instDecidableEqKeyedInput.decEq._proof_2 +T 812b8dae53094230dd4ecd65caa64d84300fd68cb1fe46c10659501d61b8f89d Mathlib.Algebra.GroupWithZero.Action.Pi Pi.distribMulAction._proof_1 +T 81634f53469f9ccffca09eb0da4be601f986188e67118ace00d902a02dc1dadf Ix.Cert.Release05.SecurityAudit Ix.Cert.Release05.ixVm2p23_4096sh_classical_rom_133 +T 81a068ffe61156bdb15701b3b352f5f5aaba567a086813981d975341a8f196e9 CertiFriProofs.Exec.MultiArity.TensorExec CertiFri.Exec.modelParamsMulti._proof_3 +T 82144faa3226f66bb81fdb908556a47a4033ac1b13ffb1b80a38e44c9a1e9638 Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.nonUnitalNonAssocSemiring._proof_3 +T 821b82cd67c8bd708c3441a57839bcfe49333a5d246e50d2aaa1306b25a788da CertiFriP3.DomainSep CertiFri.P3.DomainSep.v6Single._proof_7 +T 8222d204cf524150dd3ce42b5072c619e08329459f592923daf782743e39da4f Init.Data.List.Sort.Basic _private.Init.Data.List.Sort.Basic.0.List.mergeSort._unary._proof_2 +T 826b73a42506d038039862020bd65e4644187390f3f25b6ec24f190a4510ec09 CertiFriProofs.Exec.Setup CertiFri.Exec.modelParams._proof_5 +T 8271b61ba079163f9e43cf5c2db222c7963284f4f4c0d6cfd16c870b3a968c34 Mathlib.Basic.Complex.Basic Complex.commRing._proof_4 +T 829749ebb2c6b671931e86f772d5992023f30fe736c4a8f8607960271d4e228e Mathlib.Algebra.Field.ZMod ZMod.instField._proof_1 +T 829e22c5fdc5c88711b7f0d83053a10f8f091d039a9e2570a02a7f17caa1eda5 Mathlib.Algebra.Field.Defs Semifield.toNontrivial +T 82a930e8f9d229e39a0136a7ca5c3a8983ff2b1df90be5d8e331e119c3479627 Mathlib.Basic.Real.Basic Real.definition._proof_1._@.Mathlib.Basic.Real.Basic.1259013419._hygCtx._hyg.2 +T 82d1a65ecb910338ebcc1da793409081bfe2a841c554be9f34193325f382dd6a Mathlib.Algebra.Field.Defs DivisionSemiring.mul_inv_cancel +T 82f3df251fbe6469d5073fecda11eb0a918d3dedf7a9632906e14df8332cf13e Mathlib.Algebra.Polynomial.Basic Polynomial.semiring._proof_3 +T 836f843944780e8fc83efe8ce4fad66ea384be9f5048080eda6798da8dfdfa1c Mathlib.Data.Multiset.AddSub Multiset.add_assoc +T 839ab92cf9a3f28e94dd91c1d71008deb0a49914e6fc439a6e67ed44c7b89cdd Mathlib.Basic.NNReal.Defs NNReal.instPartialOrder._proof_6 +T 83a547975b5176a412f9504bebdf81a1301892c50b6780690f8ea3328d5c6d6c CertiFriProofs.Exec.Stark.JohnsonLookups CertiFri.Exec.Stark.w1_le_w12 +T 8407d12dc5f61dfdb987ca0b98376a3dd4557589309778034a2e05a964685c37 Mathlib.Algebra.Group.Pi.Basic Pi.addZeroClass._proof_2 +T 843cd49249b180e935c417afca70f97e662174741cbd02b462b959b5843b05a9 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.instField._proof_3 +T 8446f13907480a68a47ad0826debbf628a3a030935a87fcaf59b2630fe3ca6c4 Init.Data.Rat.Basic Rat.inv._proof_1 +T 847f7b59a7339468fc570f047d910f3a9d69f1ac789e0cf861d7218a9e669199 Init.Data.Int.Basic Int.decEq._proof_3 +T 84b8514e2c0d58f8a50291422bde35732625854a89c0554902619760b53998e5 Mathlib.Logic.Equiv.Set Equiv.Set.univ._proof_1 +T 84dd605111a307a3e477ceb60bc48575e816cab2558a0b4c59d111b509a60928 Mathlib.Basic.Complex.Basic Complex.addCommGroup._proof_9 +T 8570e58b590bde101abe563af8ea9c29579b586f103d33a7400ee455943e8af5 Mathlib.Data.ZMod.Defs Fin.instCommRing._proof_12 +T 857e4c0b8bfe8456ae9c092797b151f56702ba9ba8e53af8826e010834996884 CertiFriP3.GoldilocksExt3 CertiFri.P3.instDecidableEqGoldilocksExt3.decEq._proof_2 +T 85ade3d9c92f9ff5bc4abc2d89a814a3d18fcc5041b04d611c31e9fa7df76813 Mathlib.Data.Multiset.AddSub Multiset.erase._proof_1 +T 85eebc2ac8acec50a5e4c15cf9052adf6323646a142802fa791b02855ccce98a Mathlib.Basic.Complex.Basic Complex.addCommGroup._proof_7 +T 861bc325fd88b8534dbc1fc9312baba58675b35102678b1466003e94e7b1e0a3 Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.semiring._proof_1 +T 865c0d7268cad8b7078c1e322aec14143c4f2edeca001fcfbed4d06d176c7d89 Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.semiring._proof_10 +T 8673cec41acc7b6cbda621ac33d01226c2d29f82cfa30294a7f76ca438406d98 Mathlib.Algebra.Polynomial.Basic Polynomial.commSemiring._proof_1 +T 869d1867ad27c74885fde5d46350565516602c28c55249405301d08e00975455 Mathlib.Algebra.Field.Defs DivisionSemiring.zpow_succ' +T 86a72f1a8f6061da6012c72c662ace41d29f82167c851535eda8b8feaa1e4f58 Init.Data.Rat.Basic Rat.maybeNormalize._proof_1 +T 86ef189b08611b41ce903a4a4f733b1ceb1af0910ebc6ba861a8a726b4e8c91c Mathlib.Data.Int.Cast.Defs AddGroupWithOne.zsmul_succ' +T 86f8dd75148479f201d23a315cfa42f48838da53b130f1ae7773616a4afdcf6a Init.Prelude UInt8.decEq._proof_2 +T 8781a7cc191ee9208a8914d14f2bb5a73ee7bd8611d573cebea7b308e0db0235 Mathlib.Basic.Real.Basic _private.Mathlib.Basic.Real.Basic.0.Real.wrapped._proof_1._@.Mathlib.Basic.Real.Basic.2348678026._hygCtx._hyg.2 +T 87a4d9e62d1709013fdadd32240b01304f4f5e5f693d6f61bb6e26d93346caea Mathlib.Algebra.Group.Finsupp Finsupp.instAddCommGroup._proof_1 +T 87b6e3d8235462715a2afefd812bbf153b617d9803f97ac4c6ff19e0d0d38768 Init.Data.Rat.Basic Rat.sub._proof_2 +T 8823c8cf4ecc9a0dcd9cf8e2788b196e544d88fc3248a0117d230eda3de44f3c Mathlib.Algebra.Order.CauSeq.Basic IsCauSeq.const +T 882f3fcaee68628566b46a1b06af75efb44f1903a90af31879c2d2aab3b17a6a Mathlib.Algebra.Field.Defs DivisionSemiring.zpow_neg' +T 8856a323def9a7cba19d3808ab0b80357bcc0196f6cdeb012de3206dd2777e04 Mathlib.Data.Nat.Basic Nat.instLinearOrder._proof_2 +T 889ccbc2627e6b3cccf9a93766a0937ffe45b1314055f72b3584b5799b23b8fc Init.Data.Rat.Basic Rat.mul._proof_6 +T 89037cd3d29c6954e5a77d30584345e0e9c93f501ff9911c04cb64466b560ace Mathlib.Basic.Real.Basic Real.instDistribLattice._proof_1 +T 891c5e7cd95daa44e6df793fe1bda1ab196341c1d0a12e1ece9587482ca40c04 CertiFriP3.DomainSep CertiFri.P3.DomainSep.v6Batch._proof_3 +T 894c05ae0a61cd959066004d44ac5cbce81133c1d6e14a18ab066d34550185e1 Mathlib.Algebra.Group.DivInvMonoid SubNegMonoid.zsmul_neg' +T 894c523746f0f0ccce2abbd21b14c880534b4de5f45dbf6d5e9938f96e411cd5 Batteries.Data.Nat.Basic Nat.strongRec._proof_1 +T 895cf7b4a2d194d052823556f3c68b33947f324dff8712f9985925a4d4d4225a Init.Data.Fin.Lemmas Fin.zero_add +T 89658ae8fd1019c3b626bfc2450496329eb1494d778d6426e77519f7f3d5e775 Mathlib.Data.ZMod.Defs Fin.instNonUnitalCommRing._proof_2 +T 89912cd0967fa7b8576e94ff494457886f6d27d8295a5601ba894cefa5a77bc6 Mathlib.Algebra.GroupWithZero.Action.Pi Pi.distribSMul._proof_2 +T 89a2d57772c450fd3d4b8ff07937d2f56d880f88ef6f859a3bd68f47f71a76b8 Mathlib.Basic.Real.Basic Real.commRing._proof_19 +T 89ef98c0795d2eb14ce7f3f47d5a4b5283426dadab39415d960e79e04f817e90 Mathlib.Data.ZMod.Defs ZMod.commRing._proof_14 +T 8a0ac4014dc3a277b856d69f399258131fbd9537e572cac02a2e8c001db7e443 Mathlib.Algebra.GroupWithZero.Action.Defs AddGroup.intSMulWithZero._proof_2 +T 8a344f9ebd25ae81a6598c44231977ff1a7ca20a6f61b3af276d67725696ae56 Init.Data.Rat.Lemmas Rat.zero_add +T 8a370b1961a3e41d83adc7551affde044d87b2f1564444140251940e5d126375 Mathlib.Algebra.Ring.Defs NonAssocSemiring.one_mul +T 8a39bf48d3b38b07147393beb0b6322f46de4fda94b7aa2cd7590faa4d5ecf9b Init.Prelude Nat.lt_of_lt_of_le +T 8a411932604f9722744335902d791f68e0906f597f9bd128a53359ee0d862e90 Mathlib.Basic.NNReal.Defs NNReal.instPartialOrder._proof_7 +T 8a8c89f1f60ac505c2bed3252bdec36f415956b784c936bd779b35acfbf72b76 Init.Data.Range.Basic Std.Legacy.Range.step_pos +T 8aa1d34a5c2e91fc1d0aedc296477569f51f53f21b81d728c6352d62ec851236 Mathlib.Order.Basic Prop.partialOrder._proof_2 +T 8aa84f1e351923edf4d82c1071b053186bbb559444fd23e801f53ef80eb8b8f6 Mathlib.Data.Multiset.AddSub Multiset.add_zero +T 8ae72a55441a5a0c0f2ac4ab2b8be7c61bb1211bb8790d56e1015e964cd76b2f Init.Data.Rat.Basic Rat.den_nz +T 8af92d32f3e9de10c43f9842c1e0994de2d8c8241dcfa794dcc13fa659888532 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.instField._proof_15 +T 8afde88b5d4d6c97bb2361c508ebf636b4a46a31c064805f25ff2beee534cf3e Mathlib.Algebra.Field.Defs DivisionSemiring.zpow_zero' +T 8b05dfce4b69a3152836e987ff09b2b256d464e9bcbbf9f9f24dc27e3902529b Mathlib.Algebra.Group.Fin.Basic Fin.addCommGroup._proof_2 +T 8bc42696f9aec3cb9b5482109ea30811031f3f1e56e13414774329bf5e50f4c9 Mathlib.Logic.Equiv.Defs Equiv.bijective +T 8bcf3285be494d77b09a5a28a65e3629265000f59aee21ff8f1f202f1a870107 Init.Data.Array.Basic Array.getElem_mem +T 8c058ab78eeb24629fe6b20a5e44eec26ee22a3a3b18c1e2f309cc4441e4ba42 Init.Core Iff.mpr +T 8c12e5b4cf4ea832350c89afca3df2f117c77a8772dd922614cf6121ed1ed44c Mathlib.Basic.NNReal.Defs NNReal.instSemilatticeInf._proof_5 +T 8c1fc93612f7baf31bd2903bb93a75d5eaa6d199757c2b643ac0a60a24d7f594 Init.Data.Rat.Lemmas Rat.le_trans +T 8c6503441bffcc8282fe3f507d5d2f92cc3c02e79a63147536b90f143e3ea787 Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.nonAssocRing._proof_6 +T 8d483579038b6fab0a0fdb404d72e24344e866dddf66a1452162a00cf33406d3 Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.semiring._proof_2 +T 8d588c5309f0bdf8fb4dc6d6decb4dbacceb4c81b55c12ce96c9f0e106294ea7 Mathlib.Algebra.Order.CauSeq.Basic CauSeq.mul_equiv_mul +T 8d8e6ef0548a8d0e22923cdaa146a6bac4eac0eb1ea116e963a9a12a023f8499 Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.nonAssocSemiring._proof_3 +T 8df9baf08b0c72bd3c6e7f521c3d5d6786c961f9b4c9dae03e19e813da42cc5f Init.Prelude And.right +T 8e5c01afd4c984afb60451b65764849f5e9b9270f81b78c2807d488a4a28a5a3 Mathlib.Algebra.Group.Fin.Basic Fin.addCommGroup._proof_5 +T 8ec80090c6ef8bd99ba2185f0078eb63673949cb12aafa08874745f44ef363c6 Mathlib.Basic.NNReal.Defs NNReal.instSemilatticeSup._proof_5 +T 8ed4593fe678a653cf19e033225eb85a90ef853f9e63d006ce021e9cfde3164d Mathlib.Algebra.Polynomial.Basic Polynomial.semiring._proof_5 +T 8ee8428085b7b1f1d8b0a151253c9d720d087ce7d19f9640fdde47db98ed77ce Mathlib.Data.Fintype.OfMap Fintype.ofBijective._proof_2 +T 8f2b5828c39d166f81abb9bc1300c4bed0fa7dec31e3d5053903b75bece9cafe CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.instField._proof_10 +T 8f7b12c30ac8a3367f8841d40a789507251c1471abe7a4f8fdacacd1014cba00 CertiFriProofs.Exec.MultiArity.TensorExec CertiFri.Exec.modelParamsMulti._proof_4 +T 8f84bb013d45f41abd0a33ef3336a344683fae81dbc1baec975e6d2b7048b81a CertiFriProofs.Exec.MultiArity.StarkState CertiFri.Exec.Stark.scheduleOfShape_pos +T 8f86c90c0b903a7395bd6bcaceabaaab0133e9c17f08ab879b1af14fd122504d Mathlib.Algebra.Polynomial.Basic Polynomial.ring._proof_4 +T 8fb1e0f4ea2ca3bf628270d9ae8fbd51691cc0ac5401074d70eb8869bf29b16b Mathlib.Basic.Real.Basic Real.commRing._proof_25 +T 8fe4f9116fce7f48e394b7bbe2c1ec5a6d268d5ae26374dd98d769553599bd8e Mathlib.Algebra.GroupWithZero.Defs CommGroupWithZero.toNontrivial +T 9055f3c941d8e24f65f3d4476e6ef4b0d0443937553ec33ba1595ea3db8d1f7a CertiFriProofs.Exec.TensorExec CertiFri.Exec.tensorCoord._proof_5 +T 90584c3c836750402156a13989137bf503ea518cbfa3f673558fe51d976fd9c1 Mathlib.Algebra.Group.Int.Defs Int.instCommMonoid._proof_2 +T 9063a5f58a8acdeb428921e867a5fac2d0f42a484525c0da488de83328b15a1f Mathlib.Basic.Complex.Basic Complex.addCommGroup._proof_6 +T 9064b44e405db4324a18dfc5ed3f4a38ee3035ef6a0f657405ea742fef5c658f Init.Data.Range.Basic _private.Init.Data.Range.Basic.0.Std.Legacy.Range.forIn'.loop._unary._proof_3 +T 90a4ffbe07faf9608b31f8fef9567b788d18e345eb09978aac18ab4fbf6c21f9 Ix.Cert.Release05.SecurityAudit Ix.Cert.Release05.rec2p22_1sh_qrom64 +T 911477e00b2534d54717297d0e8f2d4f5132727cacd6e5754275f09d3efc01f0 Mathlib.Basic.Real.Basic _private.Mathlib.Basic.Real.Basic.0.Real.wrapped._proof_1._@.Mathlib.Basic.Real.Basic.1259013419._hygCtx._hyg.2 +T 9130c539765c95fdb703d1d3495e70dc98afb6523f71cf543c3c2673b3e1dff1 CertiFriP3.Wire CertiFri.P3.Wire.instDecidableEqBatchMessageGoldilocks._proof_1 +T 91a997d45ccc6638e9ed4f1b9b60af392571ecf86b9621c36f1a28a36dcc9df3 Mathlib.Algebra.Ring.Defs CommRing.toNonUnitalCommRing._proof_7 +T 91f633bcf6a5390f4b58a8092a0bbabb0d3af5c5994d8b7fc9eadcaba4112c41 Mathlib.Order.Lattice Pi.instSemilatticeInf._proof_1 +T 924b9cf92395023fd4ed95f37b92b977a64cc854ea52466f11c13166fbf872dd Init.Data.List.Sort.Basic _private.Init.Data.List.Sort.Basic.0.List.mergeSort._unary._proof_1 +T 92f8e42c0074007316831922daf4e3eb74c9c2dcc5ac9bdd6f9b652b037427ca Mathlib.Order.Lattice instDistribLatticeOfLinearOrder._proof_4 +T 9396aa75b4737ceedac5bd8bdf7874532c027b05e4ace6ed82aec6811fa59915 Init.Prelude List.hasDecEq._proof_3 +T 941ae7d2f017590c608728a1ba942be0da05c5ffb5ca3db61fbb5f9cbdcc3a54 Mathlib.Algebra.Group.Finsupp Finsupp.instAddGroup._proof_4 +T 944e08efabce7a762d263ee898c622ef9b4f3d85442bfd87c9f1abcbf54e3601 Mathlib.Order.Basic Pi.preorder._proof_1 +T 946743c6223b05fb5c42788a5c44fee4a701174f750ec63d09ab1909a2cd84d2 Mathlib.Basic.Real.Basic Real.commRing._proof_11 +T 94e4f755e49b72cbaef177ff885b587ea25e82e3c1ee1e8bdc2c545e38e9efe4 Mathlib.Order.WithBot WithBot.instPartialOrder._proof_1 +T 94ea517bca8d4d38e217b95da645e434553e285bf59c3f99ae3f7e0755fb4e6f Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.instAddCommMonoid._proof_1 +T 958b2a6035bf1d165e2eb8e67778c425a97c28f96742a9c7a68cf38b5cbb6794 Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.nonAssocSemiring._proof_2 +T 95c18649df7ec143789c2744c9293bdabba605aea2e7e8eead5c4d4350782bc4 Init.Data.Nat.Basic Nat.lt_iff_le_and_not_ge +T 95d6e784cabaebb772dec0050bf76edf7c47f1dee392aeb24094f2c02713fdf8 Mathlib.Order.Lattice instDistribLatticeOfLinearOrder._proof_3 +T 9655b47208442036c9c1330ac31b949cbe1103148ae4630ee903e96f7712d9d0 CertiFriProofs.P3.DigestCard CertiFri.P3.digestEquivFun._proof_3 +T 968a12562d2d487a8643a5f615fa425d65e5e541b0bb48ff8ebe2511e1e0bd2f Mathlib.Algebra.Group.Monoid AddMonoid.add_assoc +T 96b676656117bea7b1b437a62a4aaaea6b58137e52b5f08437d8387fdfe7f595 Mathlib.Algebra.Order.CauSeq.Basic CauSeq.instNeg._proof_1 +T 983e778f9ac443ad26a9109f225f66c80d95d2dd5d3f3be6171b919ff79ea30b Ix.Cert.Release05.SecurityAudit Ix.Cert.Release05.negControl_release05_rejects_deceptive_4_55_0 +T 9842ae4a039ab9748eb67d2ae5184b82e3696364fa4974e993bfb3defb505c99 CertiFriProofs.P3.GoldilocksExt3JohnsonPinned133 CertiFri.P3.GoldilocksExt3.verifyBytesPinned_soundness_v6_553_keyed_133 +T 987b21ebb22158d86a854aaa08933734e4835c91a80db3d1f0645844d7f08d0d Mathlib.Algebra.Group.Action.Defs Monoid.toMulAction._proof_1 +T 98a2731c566f99dacdfe8203967f46d6c98af4750b7dfcdaea7297924b169871 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.goldilocksBase_refines_fp3._proof_1 +T 98a34102b096c2ce37e8852d9201b8168198d5864d3a502d15e1ef13f77a7aa5 Mathlib.Algebra.BigOperators.Group.Multiset.Defs Multiset.prod._proof_1 +T 98f21f32a833af968395956bd45b2df07af5e2e08fc056e6582f87c117a09fdc Mathlib.Algebra.Polynomial.Basic Polynomial.semiring._proof_14 +T 990faa3b848af020900481dd7d47a5d15674a3401aef50136f5ac6e0c3830060 Init.Prelude Nat.ne_of_beq_eq_false +T 991752c2bd7f437c6877c03bc1b914ea1819d66243ff11ff39aca88bc1e85fc6 Mathlib.Algebra.Order.ZeroLEOne zero_le_one +T 9a03c0a72c6a12a73aae8b3d6389f6ecebdd2fc298fa6580be91ca6d8e5575ab Init.Data.List.Lemmas List.forall_mem_cons +T 9a5a7632c2d4ffe86682aba139217ec66da77c1d7bff6572f51c2e021c704f8f CertiFriProofs.Exec.MultiArity.StarkState CertiFri.Exec.Stark.scheduleOfShape_sum_le +T 9a6e6b04e1ec3c22510e860cce19708cdbe0c6842de50fcd074e59d86c029395 Mathlib.Order.Lattice Pi.instDistribLattice._proof_1 +T 9aa44acb33136b058318c4d0f2573278c3cfc33f8e322739cc6309257644eaeb Mathlib.Data.ZMod.Basic ZMod.inv_zero +T 9ae7c54fb3ab246a07427834f31b5c149f6cc2bdb61be0d8ae7e36cfe3af7330 CertiFriProofs.Exec.Stark.SpongeGoodLogTensor CertiFri.Exec.Stark.instDecidableEqSpongeStarkMsg.decEq._proof_2 +T 9b01f2cb3f29b7859b7e4850365248d65fa7b7b0445b22e22794a1401f8a6af3 Mathlib.Data.Finset.Pi Finset.pi._proof_1 +T 9b046e26d729fbcc361220ef84fc114b83c7bd15cfe40954b88cba157b744455 Mathlib.Algebra.GroupWithZero.Basic GroupWithZero.toDivisionMonoid._proof_3 +T 9b05523b8b9fe087c9187ac001a1fee31ed6d873c715645d5fdfd122b68a90fc Init.Prelude Nat.not_le_of_not_ble_eq_true +T 9b250220ef1d8471a1a4a47d03efb0c0336fad4f24d06853b3b2be8208baadae Init.Data.Nat.Lemmas Nat.decidableExistsLT._proof_5 +T 9b51f2ad0498513b681d628bdc26c1689169f2d92c3fb5c539dc63569a7ee20b Mathlib.Algebra.Field.Defs Field.zpow_zero' +T 9b62674a4af4cf6f18c9918829f1e8f23978ad9283206ee7e92033ab2bd8b907 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.instDecidableEqFp3Model.decEq._proof_3 +T 9b8259839f86156dbcf5075e02e6760d0ede3e14ead7500e81350ceec93e818e Mathlib.Data.Multiset.Range Multiset.nodup_range +T 9b95c8c022b2325e36673ddf65c111b4326fd4cba2924af18a2bc0769aa250f5 Mathlib.Algebra.Ring.Int.Defs Int.instCommRing._proof_7 +T 9bda2f42f35674408a0d92a3bbcaea2c1fa4fbc7ae6b123ad5d6e93e093ae055 Mathlib.Basic.NNReal.Defs NNReal.instSemiring._proof_5 +T 9bf99067248632d66938995cdd5b693e7d8a520e01c062ff698ec07c8176256d CertiFriProofs.P3.GoldilocksExt3Qrom64 CertiFri.P3.GoldilocksExt3.stdQro64_verifyBatchTensorMultiArityPinned_ep1 +T 9bffed5c953a8c823cef4a833f21d6c474c769915af0d730dc1f118e08e3602c Mathlib.Order.Lattice le_inf +T 9c24821caea85387d05c757e2cd0c0e0f37c4fed6bf1b96b463879c6443a228c Mathlib.Data.Multiset.MapFold Multiset.map._proof_1 +T 9c26448b7050f51a8519cc13b48268784fbc275c417cf8d35d618964b02c3fe3 Mathlib.Algebra.GroupWithZero.Action.Defs smul_zero +T 9c6198a9ad9fcf594d446ab059be927f31b1e84a317f62fdadd00db26cc76c27 CertiFriProofs.P3.GoldilocksExt3Qrom64 CertiFri.P3.GoldilocksExt3.qrom64_verifyBatchTensorPinned_v6_checked +T 9c9161e16e2a87016b240011c4b490dbd13b5c4030bb0b27b405b74d084b1da0 Init.Data.List.Sort.Basic _private.Init.Data.List.Sort.Basic.0.List.mergeSort._unary._proof_4 +T 9cb8b91b4452ec9e9c947ad7aaf81fa6e4ac00447828af678430a20a9dfc31c4 Mathlib.Algebra.Group.Fin.Basic Fin.instAddMonoidWithOne._proof_1 +T 9ce0a6ad8c75f17b785aa14236c02d09f2284092684437fb14edd165cfa5a341 Mathlib.Algebra.Group.Monoid Monoid.mul_assoc +T 9d54dec7fe16c0e1a405562a94275cc0502a0e11165dd1d7ed9a3cd4c46806ab Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.instAddMonoid._proof_5 +T 9db3d59266a6eab3363f04ba9d3a89a0ec2a02274bfa55a4de3fbd5bd6b5e187 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.instField._proof_8 +T 9dc6c01661058428421a5018c553258cdbdccf4725fd814ecbe0196c054d8966 Init.Data.BitVec.Basic BitVec.xor._proof_1 +T 9df778ea18b8cd3e8d34df3052ca1b558ff9e3c5e6a630e13b6f2ffe9ef21486 Init.Data.Nat.Basic Nat.mul_one +T 9e04cc9e529766fb7b8a8637639a45c28f02bdc65c6e4cfb8c14c6bea03491df CertiFriP3.DomainSep CertiFri.P3.DomainSep.v6Batch._proof_2 +T 9e54f42a51022dff90fab452a6424fca46d6568561670364152e82894de3e3df Init.Prelude instDecidableEqFin._proof_1 +T 9e712377151ef5c11b4b7d248cce2abcb2609649ab871709cdf73d8f40a6e79a Mathlib.Algebra.Ring.Defs CommRing.toNonUnitalCommRing._proof_8 +T 9ec488e0ed3b3ce2c9ebaa7794867dbaf4a50087a68ec53168af4ef8687ba62a Mathlib.Algebra.Order.Ring.Unbundled.Rat Rat.linearOrder._proof_1 +T 9ecf5647a2359ecdecf4b955ad3a801afc9e4b9aa95555c4115d17db9ea1a599 Mathlib.Basic.Complex.Basic Complex.addGroupWithOne._proof_8 +T 9ef40ca51b0c58440ca178b57d2921ebca6fc2613617062fdbea1cec6c9a29c5 Init.Data.Rat.Lemmas Rat.mul_add +T 9f3819e35461bcc14471b3cb558e1fc89ab729db20c6c9131d91ee8fc33b4eca CertiFriP3.DomainSep CertiFri.P3.DomainSep.v6Single._proof_3 +T 9f471d553dcd0db76e4eee600a9a90b321d4ebebfcd5f77aaa18de4cf30843de Mathlib.Algebra.GroupWithZero.Defs MonoidWithZero.mul_zero +T 9fa491dbefd4b1cc7945637b50bd9efd7a45aca24d8fdb2438d3c6d2d34478cf Ix.Cert.Release05.SecurityAudit Ix.Cert.Release05.posControl_release05_blake3_256_classical_127 +T 9fc8e39829f8a288341634fc4ce0f5fcc4039a6afef576e0108257b795438c41 Mathlib.Data.Set.Basic Set.instDistribLattice._proof_5 +T 9fd34d8010fd55303792e57c141acc7bf3d9911af6e386a7335c2d8cc094bb94 Mathlib.Order.WithBot WithBot.instPreorder._proof_4 +T a0023f3af9fbe202200ff4a8e3816e7f771fc72dd512d845f37855d3e47d52cf Mathlib.Algebra.Polynomial.Basic Polynomial.toFinsuppIso._proof_2 +T a008ce74ed51b082cec5af2210076e0e3c00ba2f51dd18479576ab9c1253a264 CertiFriProofs.P3.GoldilocksExt3JohnsonPinned133 CertiFri.P3.GoldilocksExt3.verifyBytesPinned_soundness_v6_553_keyed_133_bounded +T a01a3f94cddedf81824951f87cd6eb75f08f7903eb1fbf4414a8477857131f95 Mathlib.Order.WithBot WithBot.semilatticeSup._proof_4 +T a03f831b8a63a8c93831983d6f58fe4f0e5bf59c8f58b8758a649dfcbfff76e3 Mathlib.Algebra.Order.Group.Multiset Multiset.instAddCancelCommMonoid._proof_2 +T a06c616921e2333f5c771561e06d0acc2900c1678798050634c730c049ddafac CertiFriProofs.P3.GoldilocksExt3Qrom64 CertiFri.P3.GoldilocksExt3.stdQro64_verifyBatchTensorPinned_v6 +T a0a43019138f8fe689f714d8aa153f7195cbad1186f5f3c7bf2c87f59e02fb09 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.instField._proof_5 +T a0be15e6491591f65106e6180ab70cc7bb000a3982affe9e5158afff4ce8e5ab Mathlib.Data.Int.Cast.Defs AddGroupWithOne.intCast_ofNat +T a0f37cfbad3e71b4d19b66ea78c94296a3d8c704a28f7fe1c92732a957463998 Mathlib.Data.ZMod.Defs Fin.instCommSemigroup._proof_1 +T a115143252147a70aa61e4d847844f9912cd4f24a3905ce0035e86b2af56bb8c Mathlib.Order.Lattice Pi.instSemilatticeSup._proof_1 +T a1a7a803d61decba761c2349fa4edfe754ef79697a666bb8103d55dbf8f71830 CertiFriProofs.Exec.Stark.SpongeGoodLogTensor CertiFri.Exec.Stark.instDecidableEqSpongeStarkMsg.decEq._proof_4 +T a2a7a0347010ded5ed8280b3974bac55ccdc80bcb145a41bc5eda41261a385f9 Mathlib.Algebra.Field.Defs Field.zpow_succ' +T a2c97e82d4775f21ca311c407ddca67d1da6f82bc7463f663d953582a5e05d35 Mathlib.Order.WithBot WithBot.semilatticeSup._proof_3 +T a3046f3be4c617a30e33a1fbcbc53ce45c95dd0ecc9e2d26e4685d98527ac8f1 Mathlib.Algebra.Polynomial.Basic Polynomial.C._proof_2 +T a3109534b2a98a7d7ce5abd721b890cfd877c71e96e795699c1e7e93345ad059 Mathlib.Algebra.Order.Group.Multiset Multiset.instAddCancelCommMonoid._proof_3 +T a3b19f00fa58431483ebfd115fcf29e0fe1e558bdd403d59169c747313d55c18 Mathlib.Algebra.Group.Finsupp Finsupp.instAddMonoid._proof_4 +T a3daff39b492ef28010a4466c99f7803ddfb19b6c8004c4c03baf01a07a46730 Mathlib.Data.Nat.Init Nat.instAtLeastTwoHAddOfNat +T a3f43cb22ac1420eff09e2f6d80eaf6d28f599cb0b7b69c8538ac5476cb685ba Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.nonUnitalNonAssocRing._proof_4 +T a47e21498450f6de45392cd7ea990ba5c4e784d215a682d963ca68a7baae49e1 Mathlib.Algebra.Ring.Defs NonUnitalCommRing.toNonUnitalCommSemiring._proof_2 +T a491b98826baf368f765ec135946377ee84fe5ccf27b42f124a597e7ce6147ed Mathlib.Basic.Real.Basic Real.commRing._proof_21 +T a4931fa258fedc709b4a0740b5060ab4de09144009a6d0a1e8c259f928ad7c03 Mathlib.Basic.Complex.Basic Complex.commRing._proof_12 +T a4d3acc33603d734e42a7f260739c6e4a2e0a8014a2d3deed67b4aacf1201c54 Mathlib.Algebra.GroupWithZero.Defs CommGroupWithZero.zpow_neg' +T a5a423af88d406e63525fa9e7bb44bff9849184386db71b5c7ab1a56e99f256e Mathlib.Algebra.Group.DivInvMonoid DivInvOneMonoid.inv_one +T a5cf2b9ccea4174b2e16794bb4773de4d98bfee0ad1f4c044b274a38f34dfbcc Mathlib.Algebra.Ring.Rat Rat.commGroupWithZero._proof_1 +T a611d08c472b35be534334bfea424bac2a0ce5629bec2518aaf0ea8767e335f2 Mathlib.Algebra.Field.Defs DivisionRing.nnqsmul_def +T a62131c5cf1ddd7cd3c77ae0b0c477ff5db6055d0336283b42edbf606f569b12 Mathlib.Algebra.Group.Basic DivisionMonoid.toDivInvOneMonoid._proof_1 +T a62cccbe72ea94c46176c551ce55ef9de3994a3ebffa3094285e486882f1c023 Init.Data.Fin.Lemmas Fin.one_mul +T a6a848e9053f66d35f92704d3c9f408067835bb89c2dcccf4001c3579d9f2429 Mathlib.Data.ZMod.Defs ZMod.commRing._proof_1 +T a6cc774b0f35e5645e5320a930da159a0d279d6189189dddda9da87ca056d4c7 CertiFriProofs.Theory.Oracle.MerkleVerify CertiFri.Oracle.instDecidableEqHashQuery.decEq._proof_2 +T a70e62a638823cbcc856192f944589aa3ae772886c6398b3c8110eecbdc86368 Init.Data.Rat.Basic Rat.mul._proof_5 +T a719e36b6210f53ca07889afd421e31bfb022d9aa2cc03d95ecb7823bc3c831d Mathlib.Algebra.Group.Int.Defs Int.instCommMonoid._proof_1 +T a72e9af794d90355a1a146df175437acf8532ebe50b013a9679ff725ec1ae0e0 Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.ring._proof_5 +T a73b4c0a3145559ebe7a9cc5993f1bff9356ec2bf170bcb32360a2b82a38a864 Mathlib.Data.ZMod.Defs ZMod.commRing._proof_23 +T a74f3b64d3c9612cd724e34ff4c8a365513a7b29b9e946c15d7ef4a05035b0d5 Mathlib.Algebra.Polynomial.Basic Polynomial.semiring._proof_7 +T a757b88becfd3831dcaaa9be0342537a98afc189559bd1e9be15875aeb45f75d Mathlib.Data.Quot Quot.map._proof_1 +T a763002f00fff0962d83821296c966f19727e47f21e1659a6999642469a33c78 Mathlib.Algebra.GroupWithZero.Defs CommMonoidWithZero.mul_zero +T a7d521f08b515d9a15d4b1cffb2a94be9b8a87c97d7224f3430f073c1f6f8b40 CertiFriProofs.Theory.Oracle.MerkleFrozen CertiFri.Oracle.instDecidableEqSpongeQuery.decEq._proof_8 +T a7f768b3a741034b0da194f3cfa6d8bf912dd5c8fef3d71a8f0dafc211e9a308 Init.Data.Array.DecidableEq Array.instDecidableEq._proof_2 +T a8489cccea6714b6ca076180eba41c7ce27c625260b772e9e56b88d5b850b8dc Init.Data.Nat.Basic Nat.add_assoc +T a9155129c2e7ff637e1cf21ac698050df0aaf3d79fbc677e7d3a0a72b923e456 Mathlib.Algebra.Order.CauSeq.Basic CauSeq.neg_equiv_neg +T a9779d61a61e0d0aad5ba979cba49dd4beee3367baecc056c58d155747ed21dc Mathlib.Algebra.Polynomial.Basic Polynomial.C._proof_3 +T a9809c212134a9966c701ece6a5cf9a1622a9f5c7ced6aa9540ea6d39d2b4c17 Mathlib.Algebra.Field.Defs Semifield.zpow_succ' +T a9cb79444873ce96a2dccebfb1f93c0dec0adf45219d43f1cbff0dcf67712126 Mathlib.Order.Basic Function.Injective.partialOrder._proof_1 +T a9ff37ba9d64c0d014b2fb75bd1042e27ab0b397af8e0a5eefe4005cdf3b9c91 Mathlib.Algebra.Field.ZMod ZMod.instField._proof_3 +T aa2658379edc13238d6150f7a430acc02441bad63f021a4cd35c8b1e64d2929e Mathlib.Basic.Real.Basic Real.instDistribLattice._proof_2 +T aa9260a0cadf75841331d34286727ac8d4a0b0eea66bf573489f0abece8aaf83 Mathlib.Algebra.Field.Defs DivisionSemiring.div_eq_mul_inv +T aad69f2384ac1341132864a911ef2e9316754ea2edc626a624a761da7fa71781 Init.Data.Int.Lemmas Int.mul_one +T ab0001f1ff5a44cd773e9eb6d8d4db7e6dcf67375cc5465b1e7052830eb49ccf Mathlib.Algebra.Field.Defs Semifield.zpow_zero' +T ab074c118d32c49eac4e5031e75596431ffe10cff9e59fd4357400f6367581d5 Init.Prelude And.left +T ab174ad9d8b8b031c6ef34d5725372dbd4781e8959b03aaa385ff90391b1632f Mathlib.Algebra.Ring.Rat Rat.commGroupWithZero._proof_4 +T ab2e0902f4c9246f523deee5c17e769210a43eb59e0132d90713a4fe7477a751 Mathlib.Basic.Complex.Basic Complex.commRing._proof_3 +T ab75a0f00a1b0e59739566a8dc34d199b8324d4658eeb89e86e4da66beeae16c Mathlib.Data.Int.Cast.Defs AddGroupWithOne.intCast_negSucc +T ab8945bd24c8cb98ca7b8204e5b82768cbe97403b6092a32bae12fd26c2d1407 Init.Data.ByteArray.Basic ByteArray.toList.loop._unary._proof_1 +T ab99f409d1c1fb8ab4f59d8b827d527acb3ea940e1d73fa48d66d6c68ed77bd5 Ix.Cert.Release05.SecurityAudit Ix.Cert.Release05.ep1V6Hop4_stdQro64 +T abb490342c631b295677bf1eb304326ce6cd738f99ec3ff34c89cadd602f160e Init.Data.Nat.Basic Nat.add_comm +T ace98f06a598cca7a090d856833a0a34c3674f11b5b62530368d7ab31163a4b3 CertiFriProofs.Qrom.StdEquiv CertiFri.Qrom.mkCOAlg._proof_1 +T acf140078a3bfebd0b0f3a3982daecad9137d33da3bdfe4ef6ce33daeddc7ff0 Mathlib.Algebra.Polynomial.Basic Polynomial.semiring._proof_12 +T acf2dcd905daaca3ebc7d394890ba010fa7348ffb3530e3421d5b7fd84050c2f Init.Data.Array.Basic Array.forIn'._proof_2 +T acfac91166230928b4c6307f70476e6d17822a9b9634d7c769ed3a6b2fbcb017 CertiFriProofs.P3.DigestCard CertiFri.P3.uint32EquivFin._proof_2 +T ad39a9fd5b8882b67d003d3a0036c2112d739f6a6b2446e35c03e02f8abd606f Init.Prelude Char.ofNat._proof_2 +T adf3c0a5b967123ebac5576cb11fe5d642b9eb37a791b8c003e91c03dd0b5eba CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.goldilocksExt3_fieldModel._proof_4 +T ae1ff65df07d11f0a2d569aa9656d71e9571270c4990cd485b6a7cd5c029b133 Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.nonAssocRing._proof_2 +T ae3a4ed3ca48f5b9e852c8691a74451f07751e976208b4eff115be87aae49f64 Ix.Cert.Release05.SecurityAudit Ix.Cert.Release05.ixVm2p23_64sh_qrom64 +T ae5f8821a52650e332b969d541e47454d1af6a4d92fa70bc257aa8ae6ddf83bb Init.Data.List.Nat.Pairwise List.nodup_finRange +T ae709b1b820de022f296d191c8202ac5f89e8a1523f13bed9fcd6f9f3bc6f713 Init.Data.Int.Basic Int.decEq._proof_4 +T ae746429f276126676f9d1874e94b28e2974b49d10388fa431de56eabe3c5523 Mathlib.Basic.Real.Basic Real.definition._proof_1._@.Mathlib.Basic.Real.Basic.2348678026._hygCtx._hyg.2 +T ae98c1c6ec745818ca1cf00738e7e1df1697730412636d1577432666c369b488 Mathlib.Algebra.Field.Defs DivisionRing.zpow_succ' +T aeb061937e1143c14df16262f62fc040e21c30563fd6fa0c9241580045cff516 Mathlib.Algebra.Group.Fin.Basic Fin.addCommGroup._proof_4 +T aeb72e9f4c4b96367751b79cbb011cc9ad1f0bde032bbf84a49f35eddc06f727 Init.Core Quot.exists_rep +T aed279334dafef90ee225f5eeabbfd301dadb62d009f982264c71357724cf0ef Mathlib.Basic.NNReal.Defs NNReal.instSemiring._proof_21 +T aedf1f2f1e79494e3013beff70be7c8e77c0b5d1771303615bc5af0348f37b1d Init.Data.List.Sort.Basic _private.Init.Data.List.Sort.Basic.0.List.mergeSort._unary._proof_3 +T af15554d860ac4616e0f77cba6e85dea74048daa59ef06abd7be111d0930c155 CertiFri.Stark.Graph CertiFri.Stark.instDecidableEqColRef.decEq._proof_3 +T af4e5b7083047fed505f956410d4350a03f872bd24d642020313cf3583c85d84 Mathlib.Algebra.Polynomial.Basic Polynomial.toFinsupp_mul +T af5d4dcd40c143589b103395d9c1009fa8ef8433f823130621ca0187ee5392b5 Mathlib.Basic.Real.Basic Real.commRing._proof_13 +T af88eb1af1ea54532fd4cc89b9f58c2e103e13d293bfddd5a4e0af45e76fe865 CertiFriProofs.Theory.Oracle.MerkleFrozen CertiFri.Oracle.instDecidableEqSpongeQuery.decEq._proof_3 +T afd00ef82e66438e825979cb0b47a2640ae81fdaf48e65aa5af21f8721593e55 Mathlib.Logic.Embedding.Basic Function.instFunLikeEmbedding._proof_1 +T affc7e0fe53040e69c2d2177c0d67cb37342067448399bd7a86894fea3c1caec Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.semiring._proof_5 +T b0338d09d6b34ed30694b0dd0b37df8bca85dff2c22f8c5db2d921c715f1a0ae Mathlib.Logic.Equiv.Defs Equiv.instEquivLike._proof_1 +T b0516420ec25a1d1fc4a54534792fe5619dd374ce9f1ee56a807bdee8560f55c CertiFriP3.DomainSep CertiFri.P3.DomainSep.v6Single._proof_6 +T b059c60aecc63686d6703f611c2f19617bfa92982199f534cfac562100a611aa Init.Data.Option.Basic Option.instDecidableEq._proof_3 +T b0628859bb56bf0c121a1123bb5808d067748e835dbf2a30abcc58f80e6b8198 Mathlib.Algebra.Ring.Hom.Defs RingHom.instFunLike._proof_1 +T b072aa68156d949d380154bd5b8d34e02322426a480af04f0f5b440275109c37 Init.Data.Nat.Lemmas Nat.decidableBallLT._proof_7 +T b116daeb295675307157193974d7920e1ab821423152cd1a6cc59a230cc1b09c Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.ring._proof_4 +T b16aa56f51d7ba5bf2aa3e8ae20111942f44a28c84dac2f2113f10cc4c6d76cc Ix.Cert.Release05.SecurityAudit Ix.Cert.Release05.ixVm2p23_4096sh_hypotheses +T b205b85ec2385e242b93764bc61ed61f1581d2f2f2423bc59066f0a395b19b34 Mathlib.Algebra.Field.Defs Field.ratCast_def +T b246e9f8499ff1bc2824f7c0e31fcb640b8867e394f3507e08b653745660b105 Mathlib.Data.ZMod.Defs Fin.instCommRing._proof_11 +T b25b2f3001632708a2fbe85cdc8a635d03bc1a3d33e3793e5fcf364eee2496c6 Init.Prelude Nat.sub_lt +T b267915ac9fa5a61bb1a790d3983196104c3f210bae7cf1886ec08b43ca26ecd CertiFriP3.Goldilocks CertiFri.P3.Goldilocks.instDecidableEq._proof_1 +T b2c8a4e470fdbf9ff3c133ab14011011d887b0966c34e9ee92481757e889dd6a Init.Data.Int.Lemmas Int.add_comm +T b2dca165154b42ca464a34cd7061a9f4a366917e09f77f42ad8a4f79a4e218fc Mathlib.Algebra.Ring.Hom.Defs RingHom.id._proof_3 +T b349c752c6626fb9a797b11f14184aa8a6b656adcb9f5652d4a8946981ac7f4a Mathlib.Algebra.Field.Defs Field.mul_inv_cancel +T b35d0cac853c87f1cac36e1b3eb5b0b66903fb13ba84910935e42dd198d843f4 Mathlib.Algebra.Ring.Rat Rat.commGroupWithZero._proof_2 +T b35ec3f6fff6b0e0e3e1732f1126310f35bca20a44c435f50a64b067010eef3a Mathlib.Algebra.Group.Fin.Basic Fin.addCommGroup._proof_8 +T b436cc9f2f3abf75a6f193352e0c76f66c0a01374fc6b3bc9ddd7a0ad170f90f Mathlib.Data.Int.Cast.Defs AddGroupWithOne.sub_eq_add_neg +T b45062c22523e4881e0af129d991c8b82ec63fe1d2c2c52ab69b23fe9122ba44 CertiFri.Challenger CertiFri.instDecidableEqObservation.decEq._proof_11 +T b48826b3fb583523cc0228a326539405e282a734fa2e8c82056f4c3d854db678 Mathlib.Algebra.Ring.Defs NonAssocSemiring.natCast_succ +T b4df55f9222232b7bafc3b95d7f2d4706a63c721ca56ad16d6735ba9585bb816 Init.Prelude Nat.mod_lt +T b5253caaaa6f2f8e9124124ec8e68e93aca68b3aefaaddf209f9fe8fbfb901ae Init.Data.Nat.Basic Nat.zero_add +T b54953ce81008d26c7a4466a75c2f326a0ae66dde1531796cbbfca0f1dbe6a36 Init.Data.List.Perm List.decidablePerm._proof_1 +T b582e9289c65946c96e9431243589b3c64dd6d38510419d2906e9aad299bdce2 CertiFriP3.Digest CertiFri.P3.instDecidableEqDigest.decEq._proof_4 +T b5d27cb38e814c0a50748e0bb6945858dbe8b7614f034fd4494817396e999677 Init.Data.Array.DecidableEq Array.eq_of_isEqv +T b5d931d1e24d044953db2466c268bc8acee3845bed5d63be86235dcb00e30a49 Mathlib.Algebra.Field.ZMod ZMod.instField._proof_7 +T b5eb92c0e9017f8cc133c823437dbbbcca155f792592d323f827a7f26b1cd935 CertiFriProofs.P3.GoldilocksExt3Model CertiFri.P3.Fp3Model.extData._proof_1 +T b61b7316937337256ee7a0fb1e4012845711de755e9d85660d629a2f6759ea93 Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.semiring._proof_11 +T b624d9cc9b8b671e622e1ec419fdc6fbbaf6e03ed43e6a91de40f7e4754d9bee Init.Data.Rat.Lemmas Rat.le_antisymm +T b65c7454500069042688bb186f27b248e8ee495b59cf03253c9c4e4d9baf4941 Mathlib.Order.RelIso.Basic RelEmbedding.instFunLike._proof_1 +T b6885b90fb202f612bc1783b26462617ba66e637c099e997c9b0dc0689ad1d10 Mathlib.Order.WithBot WithBot.instPreorder._proof_1 +T b6bbed952b74de34e99d89bf7cfe6fbeb1904cba7bc64e7fcb6afe34a5f474e8 Mathlib.Algebra.Group.Defs AddCommGroup.add_comm +T b6d8b1db43042c83ce708eaf59b9c9624bf5a3da9f28d4736540f13aee10ee86 Mathlib.Basic.Complex.Basic Complex.addCommGroup._proof_5 +T b70d9753ce4e6b779ed2fab3aa9fdbf34aa2845a9bd3c6c48a55ef71d1678aae Mathlib.Order.Lattice Pi.instLattice._proof_2 +T b718d4fadaead22c34a6afff6471977f8e31998169b058c7a2ad1d64793ee528 Mathlib.Data.Multiset.Defs Multiset.Nodup._proof_1 +T b7275babe29fc9231fcb5b8e2b3da4b5388c2405b8832073b389d055334955c1 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.instCommRing._proof_3 +T b75ce5efb615f8490a283d86d5d356b9d3f464502928b8a0000c77deac0c9e80 Mathlib.Basic.Real.Basic Real.instDistribLattice._proof_9 +T b793f3f29161ab640aa54f3f2f432e2f58784c2eeccd6b8fc72066e2e118f71b Mathlib.Algebra.Field.ZMod ZMod.instField._proof_4 +T b7d780008d1ac2e8c93846b4dfe5e5a942292df5d6d033ad45fd7e7e4770e147 Mathlib.Order.RelIso.Basic RelIso.symm._proof_1 +T b7ec5efc138c2bfc3057fb3a84f825c47f6b7f51709c84f75048bad399265a09 Mathlib.Algebra.Ring.Int.Defs Int.instCommRing._proof_11 +T b7f4c1e868924b2f8f5e9bd7e5ce4e92adbc2d9ef62076f8ce1b05cc7542b486 Init.Data.List.Sort.Basic _private.Init.Data.List.Sort.Basic.0.List.MergeSort.Internal.splitInTwo._proof_4 +T b7f84f8b9b0ee80f4b9b84bc71abc437e8d618b2fea5b02107ba79241f882d30 Mathlib.Data.ZMod.Defs Fin.instCommRing._proof_5 +T b8205585417e281ea4ade16ec411e30d88a956078b8c187beb1425686ba30492 Mathlib.Data.Multiset.Pi Multiset.Pi.cons._proof_1 +T b82f40ca859d81ad61c0d5c37a03c1fd2eb1b7360d7d698d9e47e6c2981b3250 CertiFriProofs.Exec.Setup CertiFri.Exec.FieldModel.leafDec_enc +T b856c9a91e79f24698701845d150ca54e7d7aa628bec5158ca8c1d53b8232dbb CertiFriProofs.Theory.Oracle.MerkleVerify CertiFri.Oracle.instDecidableEqHashQuery.decEq._proof_1 +T b858494dfd4aa1bd52e63abcd1be65726db9428f52f5499616bd96fbc8b81a05 Mathlib.Order.Basic PartialOrder.lift._proof_1 +T b8ba50915c5e7fb5ef03b373bc2e8d56ecf2348952c584abfbd6cfd83ebc49bf Init.Data.Rat.Basic Rat.add._proof_3 +T b919e8e50d7717de0848ba224153937c7b9cb82f65a5fc59a062ed98e1e5f51f Mathlib.Algebra.Ring.Rat Rat.commRing._proof_6 +T b91d4212561c24bce5ed67a44e53f8852e0a34a1ce075850b696e3696a8c3271 Mathlib.Data.Multiset.ZeroCons Multiset.rec._proof_2 +T b92fcf1f9d5fb20caed64a27496650998f7cd48200b6b7a6f12f30c7a0c56631 Init.Data.Rat.Basic Rat.neg._proof_1 +T b950cba0951f72c14b9f22a37cf7e370651223ed950f41eb4d569ccdb6ffee75 Mathlib.Algebra.Ring.Defs Ring.zsmul_neg' +T b97a02bb6c24a6cc6410408e73050932ae6f9f1990cd820976f3e20a6b2bc732 Mathlib.Data.ZMod.Defs ZMod.commRing._proof_8 +T b9ddf1a9fa1776eadb7d5ca5bf8fe9164abf5aeffa62da19217d5d6cd65e2a3d Mathlib.Algebra.GroupWithZero.Defs CommGroupWithZero.inv_zero +T b9eb454cdf8c543b77ad6216af82052af3b0fd90ebf4516e2ad7b0ad13a6d909 Init.Data.Fin.Basic Fin.neg._proof_1 +T ba287c492021a75947c45206ef8ddcc8ce982d4a919033fa341b45b419de5e91 Mathlib.Data.ZMod.Defs ZMod.commRing._proof_25 +T ba67a39be6a3315716ce967055238d6099101a2043ccc9efa810fb43a6e6e5cc Mathlib.Algebra.Ring.Hom.Defs RingHom.id._proof_2 +T baabd25014faf070267c1018f06bb4ef0663c7d8d4508cf1b268cbc79ea9410f CertiFriP3.GoldilocksExt3 CertiFri.P3.instDecidableEqGoldilocksExt3.decEq._proof_1 +T baebc16ceb3f84eeeac9babd505eac861396cb53dfc3b95ccc18e2f314f5f06b Mathlib.Data.Multiset.Defs Multiset.Mem._proof_1 +T bb4030cf702be8d517617d1dd839d6f634993a4aceb1803bd66ea9f2ff050437 Mathlib.Basic.Complex.Basic Complex.addGroupWithOne._proof_4 +T bb49227cd55d7b3c6892ea61cc06a6d9ffe1fd01deea45fb0fdea3d5de8b5752 Init.Data.Rat.Basic instDecidableEqRat.decEq._proof_2 +T bb6009208162f394aaea708a8eafa3e992d9072ff3f5f81c9ac57f4b21a8f52e Ix.Cert.Release05.SecurityAudit Ix.Cert.Release05.ep1V6Hop4_qrom64_sub_one +T bb8cb72c6b3436a3e778ab0bb06c2302a2e90c75348e25bab387bdd01f0cbff0 Mathlib.Basic.Complex.Basic Complex.addCommGroup._proof_1 +T bba24b90753fac0d29baa444b1ccdca2336fcde5c2195604827494bdb749d2dc CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.instField._proof_9 +T bbd50a62b013ae832c99e43c883492994d5f11280a8e07f9b2159c93454507f2 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.instCommRing._proof_23 +T bbe6aa23d2b9f94a9c733860fada85702fac4a49b134487f0c158ad31cf8b6cb Init.Data.Rat.Lemmas Rat.mul_one +T bc0264433a73ef8a381ce6b6d176a6986340a20f23e49be8c15995549c43b9d6 Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.nonUnitalNonAssocSemiring._proof_4 +T bc5e69468f6e77c278d3fedf693a64edcc9ff34fa53a2a609661dc37f8b39c50 Mathlib.Logic.Equiv.Basic Equiv.subtypeEquivProp._proof_1 +T bc8403f232b2a5f97ba29b9b40ab6a378847bf67bb100cfe93c5821e7af329ec Mathlib.Basic.Real.Basic Real.commRing._proof_9 +T bc87dfb7acc4d2b7b883eb6d6f6755671104b76ce6b1374770d23968a9728eb8 Mathlib.Algebra.Field.Defs DivisionRing.div_eq_mul_inv +T bca4f4a0bc23069534f7ba2f2c9acacf4493970de707d53db7ffe6752feb3255 Mathlib.Algebra.Ring.Rat Rat.commGroupWithZero._proof_3 +T bcbfc5d1b4a7c070a3e10fc85b79af45227a63a31c53e749e38f6952a6f9f93c Init.Data.Rat.Basic Rat.mul._proof_4 +T bd3ec61b3a6f433d285b4dc542c2da7d67bd639b86d1ca2c91498867382056bd Mathlib.Algebra.Group.Basic SubtractionMonoid.toSubNegZeroMonoid._proof_1 +T bd63b4a2d50ad571b81753303e425a6b4faa5a1c4b1d56d62f1f97d5692416e5 Init.Data.Option.Basic Option.instDecidableEq._proof_5 +T bdbd4a642c59e39956bc2a3250d0534c4fbbd9265d7fe415694fd77fb3c066b1 Mathlib.Algebra.GroupWithZero.Defs CommGroupWithZero.zpow_zero' +T bde909bd1ccf61bdec25c9aebd328c98fad4b22c36ab25c2325374bb4050e963 Mathlib.Algebra.Ring.Defs Ring.intCast_negSucc +T be01d89ee2056cac15d3483630a822d2dc2f53ce7fbc47e0ae504e94c648bbf2 Mathlib.Algebra.Module.LinearMap.Defs LinearMap.instFunLike._proof_1 +T be974d4c35f305503e9faf5bb81971903e565249186152ae8127073a78de2335 Init.Data.Nat.Basic Nat.succ_mul +T bea391b9934faf706bc9a7e22966801015d3626fecf6cd05b489d513b72f83b4 Mathlib.Algebra.Ring.Defs NonUnitalNonAssocSemiring.left_distrib +T bea8c14079a245aa90b54ded69fecbea569b4c99f2f6f8bde7eb87872c5bf62d CertiFri.Stark.Graph CertiFri.Stark.instDecidableEqColRef.decEq._proof_2 +T bede9abcd48e9c50bda1d141bfe0b36cfe48185690c8edc38388b1693058b13d Mathlib.Algebra.Group.Monoid AddCommMonoid.add_comm +T bfa1b9f3d2dda10bc02e2d61e2ea43b03fe741f1fd8858eeb0f0cf8d361e76c1 Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.addCommGroup._proof_2 +T bfddf6e9ef0640a9257ecfe42c6cd6c3e6de2e3c1ed271b58b8d939fdc4c9f32 Init.Prelude noConfusion_of_Nat +T bfe09706adaffbf0d9badcc64d061c9f39bfbc0e9780490dd613a064b4409cec Mathlib.Algebra.Polynomial.Basic Polynomial.ring._proof_3 +T c0280fa337ee4e8775f4b4a7517819d851c2cc67db2ca743370489758afe8647 Mathlib.Algebra.Polynomial.Basic Polynomial.ring._proof_2 +T c035c429e2edbf4176c0540bcf50cc1e7f9bc5fc3e7d52c9f2ec2c01eac35b7a Mathlib.Data.ZMod.Defs ZMod.commRing._proof_18 +T c0839d147e6aa1ab3821563891caa6c30aa79dc8a36bef1e34c13d675cb96ab9 Mathlib.Algebra.Polynomial.Basic Polynomial.semiring._proof_15 +T c10174b34ce6acd3e3bb700c4fab1924b6916530a8bded298bc77c7631afbf9e Mathlib.Algebra.Ring.Rat Rat.commRing._proof_2 +T c10c855631a098d8a88b498bbbb7d85cf437f7a3a877d54f5b0ccbdff3a0272d Mathlib.Algebra.Ring.Defs CommRing.toNonUnitalCommRing._proof_2 +T c20fbb98207375706962ea7614d8ed2e616eb74a0c5c600ad023181ec984f68a CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.instCommRing._proof_18 +T c2d048986c49a1a535698d757a35e844f2df8b2f4dd8fe807ce5447e6cec42ea Mathlib.Data.Nat.Find _private.Mathlib.Data.Nat.Find.0.Nat.findX._proof_4 +T c315d253af8a6cb82ed8655ef289f83222c48b8e7a14ce5556825a506183ebb5 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.instField._proof_4 +T c367dd63dd9506b134434ddd59ba1fc9c35700760d07f2d98b6e93bbb84cb7f1 Mathlib.Algebra.Module.Defs Semiring.toModule._proof_1 +T c38ac69cf68a89f9380b9def4627272e40125c0369cf415f3aba49d9bbb5dad7 Init.Core Iff.mp +T c4b17c2c900eed7caf197e00839cb7aaefdcf9bebdcaecd1b958cb824ca9e290 Mathlib.Data.ZMod.Defs ZMod.commRing._proof_21 +T c4f476afa8517ed251e713a693901bc0cce3f0bc14013ee08fa28225fe95ae15 Mathlib.Data.Finset.Option Finset.insertNone._proof_1 +T c50bb7e9d21ea53cb2b2e0d061c62170c710a9db479793736e24ebe2c35033a2 Mathlib.Basic.Complex.Basic Complex.commRing._proof_11 +T c57ac0d0ba909b56ce52ee3538790210c0bd297f56b1a5a4c0ae0d875c37fc67 Ix.Cert.Release05.SecurityAudit Ix.Cert.Release05.aggr2p22_16sh_qrom64 +T c59ec04642f26a5f4f37949741f9caa37a251a428369d9d60fc267582378f8c2 Mathlib.Algebra.GroupWithZero.Defs CommGroupWithZero.zpow_succ' +T c5f4763f988ba526ac5fcecae71f9d3eaab3260793cce75354104bbe40e08f04 Mathlib.Order.Lattice Lattice.inf_le_right +T c64a6d1fc754cae1d4cb998103534daa76eaef6752446f3a930d242d465c9c57 Init.Prelude _private.Init.Prelude.0.isValidChar_UInt32 +T c66f88106626f7acd7bf4cb87b767c17a6ef82c987e0decc160f4b72bec1d197 CertiFriP3.Goldilocks CertiFri.P3.Goldilocks.invLoop._unary._proof_1 +T c6999ca23cc132fccd1b5fb4eeadaa7061046932169cf61cb2de308dc12b2b1b Mathlib.Algebra.GroupWithZero.Defs GroupWithZero.zpow_neg' +T c6ab6d34407da9bb638c2b7a1d2dccd379fa01deee720925f20027c42f2c856e Mathlib.Algebra.Order.Group.Multiset Multiset.instAddCancelCommMonoid._proof_1 +T c6aef57c463db75fab75fc65be21f3abef70d3fab5e3e5c2f9ff82cf164e950b CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.instCommRing._proof_7 +T c6b065093c39b4be675078ca181a524c75d44a133a471a5d79806289ce08a146 Init.Prelude String.ofList._proof_1 +T c6c67a6ef70b1cd990105d4a014082fb62bb7773e03d86571b6016fc9de78581 CertiFriProofs.Exec.Stark.SoundnessPinnedSpongeMulti CertiFri.Exec.Stark.restorePinnedPathsMultiHashM._proof_2 +T c726b87879e44001b9e558981e8bac593153f2c9bd5553babc77ae1c911884ca Mathlib.Algebra.Ring.Defs NonUnitalNonAssocRing.toHasDistribNeg._proof_4 +T c77f640cc15e47a1f4a65d7e2d6756495cd09a0de860c3aced98eec55c4e9da0 Init.Data.Nat.Basic Nat.mul_assoc +T c7a3ff22f2fd59311df6c2234921b35a03903fb3b648e5286a7fe4d0060e5ffb Mathlib.Data.Finset.Insert Finset.cons._proof_1 +T c82b1205ba42e5986c639945bb52210507752638cb0f4fffc993284682d1dbe2 Mathlib.Algebra.Ring.Defs CommSemiring.toNonUnitalCommSemiring._proof_5 +T c82bde65605acf6e443d8c4c8ec5cb505c208599c5d2724414f62fa3e9733acb Init.Data.List.Attach List.attach._proof_1 +T c833aeea3312e34e3754d79a894c3143ed948699611c0eb8c97dc76d82b71adf Mathlib.Algebra.Group.Monoid Monoid.npow_zero +T c8568021a9b82a75cf6499eb12098ba72a060e87e9b0e5bcac795adbd1008222 Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.addCommGroup._proof_3 +T c85a7c675a98cdd0ab300b88d45490585e4e4ccce657adf5e988928eee3f8ba9 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.instCommRing._proof_1 +T c8beb9d2018fa83dc61d8d1b441b7d58e7961f0dd7fcd52f7053e826c5d8df81 Mathlib.Data.Finsupp.Defs Finsupp.mapRange._proof_1 +T c8d292cafb3f8538306b7ca1d41ab563a79d8bbcd505201794c01ed6128f033d Mathlib.Basic.NNReal.Defs NNReal.instSemiring._proof_9 +T c8e5d9c3d659db3854e9793b00d79761ea758aeb30b3e4dda8a0aa12875faa04 Mathlib.Logic.Equiv.Set Equiv.ofLeftInverse._proof_2 +T c8e80b55da7573229d69afd66fb4a64c4325f82849a2cdfca148398840bc0467 Init.Data.BitVec.Basic BitVec.and._proof_1 +T c8f3e886b0729c176fd3cc6945a059d36ba306459f7bb98b9f98cc3a10e3fee9 Mathlib.Data.Multiset.Defs Multiset.decidableEq._proof_1 +T c900e43eec41bf71fc73492936ce6e4eac7277d0e2dc93b512b721144a9fe02c CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.embedHom._proof_4 +T c9674f7f86ffcf84e55f400867aab2bc17ae7b822eaf76c5f8f46f4309809e3b Mathlib.Algebra.Polynomial.Basic Polynomial.semiring._proof_11 +T c9bbb6da14d3a15b7cafe242c50b43e0dbd1fcb75a59f04693e452d546cdae92 Mathlib.Algebra.Polynomial.Basic Polynomial.semiring._proof_10 +T c9c623acfa46352d300f4038d134c57ad3967ef29ed55f187eb835d48e4e1844 CertiFriProofs.P3.GoldilocksExt3Model CertiFri.P3.Fp3Model.extData._proof_3 +T c9f350116a163a23d578432ef521abf85dc84aeb0478a9eede9f537e62e6592d Mathlib.Algebra.GroupWithZero.Action.Pi Pi.distribMulAction._proof_2 +T ca4b377c1bc75c204a8bc62e19ac28651a5f2089acccfd5ae482ca9b21bfe953 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.instCommRing._proof_10 +T ca5fc0ada325a55c5f4ad8d9d5b770aad1c8817cf04bc25791200836b4fdd11c CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.instField._proof_1 +T ca67bca9ecbf8aa2cb910fc40018953357b2d57684964aa0cb393c127c916b3d Mathlib.Basic.Real.Basic Real.partialOrder._proof_1 +T ca8f6e47b60b076d026951ba020c35ecfeecc335c1db21cf064f35cff56ff2f1 Mathlib.Algebra.Ring.Int.Defs Int.instCommRing._proof_5 +T cac1b8595af041e078de20f9b0c5a5b78b56b26fb85b7f9ca90ced47a10575c3 Mathlib.Data.ZMod.Defs Fin.instCommMonoid._proof_1 +T cad768e42c8c22847b739934f568f6f83a4d00189617f90f2e481382bf487a31 Mathlib.Algebra.Group.Finsupp Finsupp.instAddGroup._proof_1 +T caf3472dccac934d0b532475bafd99fc7dbc6ed36c2a04e8c4604dcdb4312874 Init.Prelude Nat.le_trans +T cb1098b78305bc952c37a7ffe2166e6b942503423b19d333625eaef553108f23 Mathlib.Algebra.Ring.Defs NonUnitalNonAssocSemiring.zero_mul +T cb82fed5010157f15c6e9692f2057e77543982e731f2aa241e9ba26048ba616d Init.Data.Rat.Basic instDecidableEqRat.decEq._proof_3 +T cb89ec0dfbf146df99d34170690723f1e3659f9c8228d1c394c5ea8d8c627b21 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.instField._proof_14 +T cc3ee4cfcb14729538f537cbcf7e95004b8df0404ab876c1017c38ab816a81f1 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.instField._proof_2 +T cc4e0e22b9c4619f7dd3e602838541f06ece48e56b52bb423814035cfc4596a0 Mathlib.Algebra.Ring.Int.Defs Int.instCommRing._proof_1 +T cc585d6370b9ba570a6abf88726679c4d129536c97b5e5562bcc227a9ac00b0a Mathlib.Algebra.Polynomial.Basic Polynomial.ring._proof_6 +T cc9ff49d250c98c1ef1cab28e5cdb2c3b9d87b9d528b39e47a219769b961475d CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.instDecidableEqFp3Model.decEq._proof_4 +T ccc2d167256a74a553b63740eeed97858cf911f675117a106a24072564c005e6 Mathlib.Algebra.Ring.Defs NonUnitalNonAssocSemiring.right_distrib +T cccdc5186c907f04de9605db3b4769790d82bb8c4338668261814787f14d271a Mathlib.Algebra.Ring.Defs NonUnitalNonAssocRing.mul_zero +T ccd4bc840b3c097047e493fae6f4cc1941ea51064fcd19aa7514b2430de6d259 Mathlib.Data.SetLike.Basic PartialOrder.ofSetLike._proof_2 +T cd11eb4550702d154bb1c068e8a19cf3f15d7b8c2d40200fac6b47ae46fd8ba5 Init.Prelude UInt32.decEq._proof_2 +T cd1888f3a838e899991402c5547d2f1a094fd5a8becd61d393fec29172468285 Mathlib.Algebra.Ring.Defs NonUnitalCommRing.toNonUnitalCommSemiring._proof_5 +T cd760ecca988a0809ccc0a22b1b2a510885ccbb566095ff75310de7759237952 Mathlib.Algebra.GroupWithZero.Defs GroupWithZero.zpow_succ' +T cdbc6260e6ad10450c9313d8ff708eb6875dc88425652da99afd2c806be479b0 Mathlib.Basic.NNReal.Defs NNReal.instSemiring._proof_8 +T cdda5dc200c819b834eb9746288500535f91e0c52bb6f41743d572ff67dc5008 Mathlib.Algebra.Field.Defs DivisionRing.mul_inv_cancel +T cde69f6782b4ba2c1e444ce72378b33762804ff681ed6cd7f275339c829e5e36 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.goldilocksExt3_fieldModel._proof_1 +T cdeea0e033510844f11b839e9f8a1ee2a809fd9564220a2d769a359d1bb8158f Init.Data.Fin.Basic Fin.mul._proof_1 +T ce0bb430e80706532c8db7366e68d953c9c28c26aa7cf184bd53e5a88541b6bd Mathlib.Algebra.Ring.Defs NonUnitalNonAssocRing.left_distrib +T ce6fb77af9c0e17860d15a3ca56547f81bc28e97bff5ae08bdac1b13f57cde2f CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.instCommRing._proof_15 +T ce737d2536f13148359eaee87ac392d34e528cfac5066974d1cb9ddc62e0c08a Mathlib.Data.Multiset.Dedup Multiset.nodup_dedup +T cea546ce456cf91418dfa5243dcd582ff7a4ff1d8ebe9906ba5831f67320cd5c CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.instCommRing._proof_17 +T cedb184d45712984e93b3ead591a259e9ef9e966a6a226ee6f5ca70d3b6a1879 CertiFriProofs.Exec.Stark.FixedKey CertiFri.Exec.Stark.baseOf._proof_1 +T cf9f8bd840bd436936385a011d417892ed2f143f4d04e141b2869ec298fef394 Mathlib.Basic.NNReal.Defs NNReal.instSemilatticeSup._proof_4 +T cfa07b362622eaa9ab5fbfaee5297aa39e5bd1df14bbbc2a4f5a1fd052f29d54 CertiFriProofs.Exec.Stark.SpongeGoodLogTensor CertiFri.Exec.Stark.instDecidableEqSpongeStarkMsg.decEq._proof_6 +T cfb21dfcfb13b2ee84c857a4c5572a2fe1e3177f219265cbccbc549757cf1507 Mathlib.Basic.Complex.Basic Complex.commRing._proof_1 +T cff47c021ef4f227e2d555f944e7ddd9aedff80d6bd23bd98e754b6e258bb7db Mathlib.Basic.Complex.Basic Complex.commRing._proof_8 +T d02fae61bb32c62a817a90c9a3045d4f7242828379b3acc55dd805e65d889392 Mathlib.Algebra.GroupWithZero.Action.Defs DistribMulAction.smul_zero +T d053b15f08e63744896337eeb936c9c3e426d74c765f7cbcf07b0898ee6deee7 Mathlib.Algebra.Group.Defs AddGroup.toSubtractionMonoid._proof_1 +T d05ef2dcdd6d5ab833c8fb03a5aa5a312b32b725f9a627e9b488bc225d031a16 Init.Data.Int.Basic Int.decEq._proof_6 +T d07dad9d43a947db8c8f4e60212659607c6f24e431fbd2eb74d8a77e0757426d Init.Data.Fin.Basic Fin.sub._proof_1 +T d11f33564c05315ed4906bf9d40816b1c7206aee241d8a1d6341f65ece420d9f CertiFriP3.DomainSep CertiFri.P3.DomainSep.v6Single._proof_4 +T d1b6d950ef6eac37bb8f6135574d997fd3536b29babfc00660a6a41a5d4d2a92 Mathlib.Basic.NNReal.Defs NNReal.instZero._proof_1 +T d1c794cf85a55b4d5e96def3d2ba3b49ec3781cb73ece6cc9090ec9314b35304 Init.Data.BitVec.Basic BitVec.ushiftRight._proof_3 +T d1d26076d72db913d49f8f4c5ca66435964b1ef3a69f5263f5a033486d9ce6f0 Init.Data.Rat.Lemmas Rat.pow_succ +T d1eae83c8a638ecc857dd0c78144978fa0bb196a140c7fc203b6035d2b32bee1 Mathlib.Data.Rat.Defs Rat.addCommGroup._proof_3 +T d1f7a38d56eef16929d565a8e9e75c69b6e6e8fa32af8a3af22d6db4c2a56cf5 Mathlib.Basic.Real.Basic Real.instDistribLattice._proof_4 +T d1fe45cfc259a72dc778c5f46689601d99110320b931e853200ab2daa196ed94 Mathlib.Algebra.Order.Ring.Unbundled.Rat Rat.lt_iff_le_not_ge +T d275962f2e5bc4a48e480ae1f9ac339103b316ae6c262cabc371699044362644 Init.Data.Rat.Basic Rat.mul._proof_1 +T d280510c1a7099ef11acd03513c54b7bcbf892982c24f6448d7eaf318b78b459 Mathlib.Algebra.Ring.Defs CommRing.mul_comm +T d2a91f8f22841f03ffe6bba87de15aad1838dea9552d9c59f6745b22d94cc3d1 Mathlib.Algebra.Ring.Rat Rat.commRing._proof_8 +T d2e55d8e50eaa5c2234c8a2b3039ba6957ea5ebdadc13add43f636b638892376 Init.Data.Nat.Basic Nat.sub_ne_zero_iff_lt +T d3323e330060daf30e47737a22a2810d0f6b9fe1bd56b443d5d2e84e963079a3 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.instNontrivial +T d35f59cc7b450be93c71033e8e7e8ce064f8e2b4bbf66d8e408a2c93e0cf3b65 Mathlib.Order.Defs.LinearOrder min_le_left +T d39dd85bcf5188019b380d6e55b99cb36c766d2df45d741d872e5b5459ed4f60 Mathlib.Algebra.Ring.Defs NonAssocRing.intCast_ofNat +T d3ec793bc266b18723725c5492adaf13444f844aef03a290a8999fb48cae4fb1 Init.Data.BitVec.Basic BitVec.udiv._proof_1 +T d4201aa27d71122527fd47b3b339909a576f157416845adfcc7709f0d73ac8a2 Mathlib.Data.Multiset.Defs Multiset.decidableForallMultiset._proof_1 +T d43efdd8b67304cc19daa1f4fb8e3d0b4d2625806e7746bea1d218a649b6285a CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.instCommRing._proof_4 +T d47f050879ddb0e3c3b57589b5da034301c13ec014dabad10a8917a66a183290 Mathlib.Algebra.Group.Monoid AddMonoid.add_zero +T d4c9acedf8240ffc5e7d5ef5c4912d29a5347f78fb0ca814f496864be80a7d41 Mathlib.Algebra.Ring.Defs CommRing.toNonUnitalCommRing._proof_11 +T d4f42744ec03f84d03dfd84bfa07e7195f5ad06facca40a334a54a6a3a5d7c56 Mathlib.Algebra.Group.Semigroup CommSemigroup.mul_comm +T d51a2e1fc2f8e8a160ade68f6932971b6f99a3c5aea3aec45c6edd40776268cd Init.Data.Nat.Basic Nat.le_total +T d51ecf3e1c44a336eb5b950730770f5955077e7dc1e62737b8ba5669a88474f7 Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.nonAssocSemiring._proof_1 +T d53241509d1c89de3ca514a75a16c6f1ba546b77d5d1f37a2a621c89bf4e05fc Init.Core decidable_of_decidable_of_iff._proof_1 +T d5d0ba94a0d8a410f9e1bb24fde9473f91d0e273eb07a049f120f4aa8f0248d2 Mathlib.Algebra.Field.Defs Semifield.div_eq_mul_inv +T d646934795c8b1ba90305c2866d526d9a5c57e17e258bdf963e579c0c0d221cf Mathlib.Algebra.Ring.Int.Defs Int.instCommRing._proof_6 +T d6ae9cbd66f387df25e8ce0e2f5982fd56c3f099a457d4d83ba2c3779bb34996 Mathlib.Basic.Complex.Basic Complex.addGroupWithOne._proof_1 +T d6c8f20306de455158b66a4904bdd6e08005b47716815046cfad86b466388eab Init.Data.Option.Basic Option.instDecidableEq._proof_4 +T d6e698c05dd3298d46f74d5cfb2df2fe89ae2f056ac4b14a619af99bb0377540 Mathlib.Algebra.Group.Semigroup AddCommSemigroup.add_comm +T d731a94fa8fb172d379c470afdc28fbd7851cd5f500d87748d11a700847ea8bb Init.Core Quotient.lift₂._proof_2 +T d7964cdedc44b40cc03ab2c186f1a3503e019fecbd63d5c596d1ccbbadbe9bc3 Mathlib.Algebra.Group.Pi.Basic Pi.addMonoid._proof_3 +T d7fef688897a17e57e7ad99667808bf2ba9432d9a5693fa6d49791ed69118c5e Mathlib.Algebra.Ring.Defs CommRing.toNonUnitalCommRing._proof_9 +T d825cbfa6fbb031843cdccb2f11992041dba0cfa76a13cc5b2ea083e855c2ea4 Mathlib.Data.Multiset.Pi Multiset.pi._proof_2 +T d82d56ffa88f8bb8aca084bca3410ba361530ed0d1d75d6d93f31ca34026c8b2 Mathlib.Algebra.Order.CauSeq.Basic CauSeq.inf_equiv_inf +T d83d72e337447014c5a2d5b739de75bd0dfe2700cb046e9e665d3ad545db5c0a CertiFriProofs.P3.GoldilocksExt3Model CertiFri.P3.GoldilocksExt3.starkModel._proof_2 +T d87fc46b971c9842ea14aa3b792ee17c5cdc86db94820ff8e12119f1d425f0cf Mathlib.Basic.NNReal.Defs NNReal.instSemiring._proof_22 +T d8f739d494f2fa22bbfc945321a2c34e230e081450a1b1c43c1d3d7fd2d974ee CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.goldilocksBase_refines_fp3._proof_3 +T d9094c809222ce127f4964b08fd5414400158f85c14ab3b86c8fe0ce7cf88f6d Init.Data.Nat.Bitwise.Basic _private.Init.Data.Nat.Bitwise.Basic.0.Nat.bitwise._unary._proof_1 +T d90bd6de70f7e28e10a4d536a1939dbc7766ac5031564f283887259441f2357b Mathlib.Algebra.Polynomial.Basic Polynomial.semiring._proof_1 +T d91883ea96e901c434386fdb726636499354b37730b717764a2c7990503245c6 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.instDecidableEqFp3Model.decEq._proof_1 +T d96aa5e1e5f55423e6db0531fbe77d9be34200a6b20485d3a7eed8ffa4e7d62b Mathlib.Algebra.GroupWithZero.Basic GroupWithZero.toDivisionMonoid._proof_2 +T d97f73a9c38be6a4062cc11e88fa507fabd142cb93a38ad5acffa42824453270 Init.Prelude instDecidableOr._proof_1 +T d99af87cab51ea76311985567459b43d20c7de68282585f8384ca942863fa37f Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.nonAssocRing._proof_4 +T d9a8fdcf3ff41306d0c862139759e725ace9050c168f2d3e41d497d22c54bee4 Mathlib.Data.ZMod.Defs ZMod.commRing._proof_20 +T d9eb22457b4f5e2168ffe30d88221306d82462c1e14ce28a583c331690e2a4aa Mathlib.Data.Multiset.Defs Multiset.decidableDforallMultiset._proof_1 +T d9fa39c80f2608f47dade133944fa432b217ac370044ab209644b82a011b3d1a CertiFri.Challenger CertiFri.instDecidableEqObservation.decEq._proof_12 +T da3dd9d9dc5013023e8b89f97ebca7b0d160ccc7682c36d30ecbdad38e4fcf4b Mathlib.Algebra.Group.Defs AddGroup.toSubtractionMonoid._proof_3 +T da3ed5109c4c512fd33d754e1ae7e305cffc14136842f2f957da188bc0915841 Mathlib.Algebra.Field.Defs Semifield.mul_inv_cancel +T da5e9e04354570c6fd735111759f3cebf5cae979961a0e33cc6a087717cd3f15 Mathlib.Data.Set.Basic Set.instDistribLattice._proof_7 +T da7bac5d4e2d456a737729da117f3a613b5ae9fdc24413f01d16a5dd4f96cb6f Init.WF Prod.lex._proof_1 +T dab65293bc022f3baccf025ae92deda439e3d8196488619e87567d416bfb514c Mathlib.Algebra.Polynomial.Basic Polynomial.distribMulAction._proof_4 +T db2667acce69cb0a3ed83b831c6b58d871548a43b6a20730b058745a56c96486 Mathlib.Basic.Complex.Basic Complex.addGroupWithOne._proof_7 +T db370e0f149ac4e8b435a4fbf7576ce6e51e4e00ab88d1c940d27a3e6747584b Mathlib.Algebra.Group.Monoid AddMonoid.zero_add +T db6eb12839270bd8c41f288abb3d2e35274c6b4ffebddd06dc0e1d3803fe3af4 Mathlib.Data.ZMod.Defs Fin.instCommRing._proof_15 +T dbedbe6ec0ce1df732c73ebb27fa5acc3d8387d6fb7e0da8dd4be1bdf1ac9895 Mathlib.Algebra.Ring.Defs Ring.zsmul_succ' +T dc2888290f8841aec0d61decf799d5b1d4bdfc6b5416345f66556a199a8454f8 Mathlib.Order.Lattice instAssociativeMax_mathlib +T dc7533b7203b79a0f7e23d9867d94e35b5e29402269587ce184010f23786f82e Mathlib.Data.ZMod.Defs ZMod.commRing._proof_22 +T dc7ae7b774b3c162ca5b52bff99a5305a9302df4efbff4906f25136f7aa5973c Init.Prelude List.hasDecEq._proof_6 +T dc87d5beb4cfab50293a7e1b9837080554efedae6b09c0569884b4758b4b37c9 Mathlib.Algebra.Order.CauSeq.Basic CauSeq.add_equiv_add +T dc9abac26aa7331348aaf8d34c86cfc68ef0afe84481725d5da5035257a40276 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.equivTriple._proof_2 +T dc9bc2cc165f26444e376611fe1f84c4cbb07ce3e550777a31473f21de465d19 Init.Prelude Nat.div_rec_fuel_lemma +T dc9ed5f9d0917a23b2fa77a387be3bf45ff4d7ce3ab1338e6d0ad2ddaad69a33 Init.Data.Rat.Lemmas Rat.add_comm +T dca7a94ea24135181b29cef84193c46e50e2b4a898164285c65beeefb249afd5 Mathlib.Algebra.Ring.Defs NonUnitalNonAssocRing.zero_mul +T dd0e94a7fc2bde6f8a2a2a4d05bc35d1404d0306d3337ab2f625aa3361f5ab09 Mathlib.Data.Rat.Defs Rat.addCommGroup._proof_1 +T dd1250e4870fd9147904911f7f53d6fda1a74406fabaf4eec424eb9ea96c4698 Mathlib.Algebra.Group.DivInvMonoid DivisionMonoid.inv_eq_of_mul +T dd208fec76e0be85266de77dafd3acccb7c13e0d210abad727258b341e9810dc Init.Data.Range.Basic _private.Init.Data.Range.Basic.0.Std.Legacy.Range.forIn'.loop._unary._proof_2 +T ddbbf14b6394d14f3e0209b13fcba30e57dc6897f457160fc544ed367b9ca3b2 Mathlib.Basic.Real.Basic Real.instIsOrderedRing +T defbb5e7f477f91ada1a1d0be808da24528d9520ee23ccdd96127990eef7b0c4 Init.Data.Nat.Lemmas Nat.decidableBallLT._proof_8 +T df13c7eb553cbca4e9b935d394a49f00a8c25eae0f08368eb9faffa7a0cf6e76 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.instCommRing._proof_6 +T df2832874a7c77b1e5b92da1b87ac0eef54372d30f17fd05e8f93b5959ca0159 Mathlib.Logic.Equiv.Defs Equiv.injective +T df82e90ee20f13c79e3b510a475fdd4bed834f5bbe3416482aee1c804ce2e2bc Mathlib.Algebra.Field.ZMod ZMod.instField._proof_5 +T dfa40ed2f7246cf824b8cba0c0973284a76f640d61b80ed1cba66056b53f4233 Init.Data.Int.Basic Int.decNonneg._proof_1 +T dfacc90ce77b30b45b747d267761ceeec75632d983c5e76e9b6af5fb425decbc Init.Prelude List.hasDecEq._proof_2 +T dfae4dd88b11d0f167394eeb6241048cf6db2dfeb9e92b122220963daf7a892f Mathlib.Data.Set.Image Function.Surjective.range_eq +T e0f944a428ca93b1663e9ecb07b54e91cae232462955462bf02ed29db2d5c5fb Mathlib.Data.ZMod.Defs ZMod.commRing._proof_24 +T e113a2b59b12b86951ef3ac1a4e6fb5948680378b70877c544aa5fba30de74bc Mathlib.Algebra.Polynomial.Basic Polynomial.smulZeroClass._proof_1 +T e141ae11e4efb42652552c125c08fae1ff2a7e05fb3d0330276ee6b982870eb7 Mathlib.Data.ZMod.Defs ZMod.commRing._proof_11 +T e1442157fc701c8283a3734fa0e5effd448063659aefc692245bd39d86ce8dd7 Mathlib.Order.RelIso.Basic RelIso.instFunLike._proof_1 +T e14ac06f9b5027419b65b870f59012f069f2f8cf0e8e52c8b39cf587796f8458 Mathlib.Algebra.Order.CauSeq.Basic CauSeq.inv_aux +T e1508e353ce7ea05fcc2742168ef4dda47550656f9d5f95d307ebdf73a124852 Init.Core Nat.add_zero +T e161694411d941658174f3c934129293c2ead396473ae8f297fd3ea3aa325fbf Mathlib.Algebra.Group.Int.Defs Int.instAddCommGroup._proof_2 +T e1853afc76357f584ccb573f33195f5acd98633518e559a73f036cd85bb828fc Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.nonUnitalNonAssocRing._proof_3 +T e1b560df0121a5a35173e4dde43cc74b19f1bb9f31d6279c0490b08521a9ea79 CertiFriProofs.Exec.Stark.SoundnessPinnedSponge CertiFri.Exec.Stark.restorePinnedPathsHashM._proof_1 +T e1b60de2dbf2e5507458a03b0db302b2952cfedba59507007b1bd47b65942bd7 CertiFriProofs.Exec.Stark.SpongeGoodLogTensor CertiFri.Exec.Stark.instDecidableEqSpongeStarkMsg.decEq._proof_1 +T e1bf7a5afd79ee8a7741958669e81ed601d4aa2c81584e780bb92b768f852794 Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.addCommGroup._proof_1 +T e1da570a9954d0dbfe2d4005c73ea3c748bfd7eeeb5efccc4e1e8b4f7a8b5efe Init.Data.Array.DecidableEq Array.instDecidableEq._proof_1 +T e1f40f235e60a37ecf7a37597bcef9b4b7b20c7d886c982ccc83867ffe1bf738 Mathlib.Data.ZMod.Defs Fin.instCommMonoid._proof_3 +T e236456b9f2ac70c5ff99f7c50d6ed1721ec5eb59a4642d54de398878faf82f4 Ix.Cert.Release05.SecurityAudit Ix.Cert.Release05.negControl_release05_rejects_v5_default +T e2abf191b45fbf319d2a6dffd8f73c18a5c4c7d504d983a61ac88af4f8db2617 Init.WF WellFounded.Nat.fix._proof_2 +T e2b7dbc3bcfca45119a21ce67379e96f8adead79ed932d0ce4be440fbe970aa3 Ix.Cert.Release05.SecurityAudit Ix.Cert.Release05.release05_inner_default_ok +T e2b8582f68ff4d68af71233048a12ec5a0ce375f01ca076e8e575ff891496846 Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.smulZeroClass._proof_1 +T e2ce70e9dc697598843437d8242e2f43e0be08d443df22f072502512a89d5935 Mathlib.Data.Int.Cast.Defs AddGroupWithOne.neg_add_cancel +T e2cfa0e83edf04564d0fd212d61531ab0c5f6b2f329344b7f2a91627a83901f6 Mathlib.Data.Nat.Find _private.Mathlib.Data.Nat.Find.0.Nat.wf_lbp +T e2de39bc19caa54baa28f44477285da1e2f17bf0d34530bddc836183cabcb489 Mathlib.Order.PropInstances Prop.instDistribLattice._proof_2 +T e2ef3c04f042cbfd0bbef938894097cd7d68bc6c1d0be3f0614ebafa6beb03d1 Mathlib.Algebra.Ring.Int.Defs Int.instCommRing._proof_9 +T e2f5a2b48eee2dcd24be753c60abfbf2d178757696a5674493c01e0043ed886c CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.goldilocksBase_refines_fp3._proof_5 +T e31c6153abc56e8193a4102c641d5abe4baca3cc1bd33c6d352fbc6234bd7639 Mathlib.Data.Finset.Erase Finset.erase._proof_1 +T e31ce11c6e15fe90437159e7d1bda8b5d50b30fe177903cb174731ec9d02731f Mathlib.Algebra.Order.Nonneg.Basic Nonneg.nsmul._proof_1 +T e32944f75ad3d2106eb84a8ba3de5af81d29832a5dba3e335f1ee209c805c014 Mathlib.Basic.NNReal.Defs NNReal.instSemiring._proof_13 +T e33e20c7e4948967fdf701996a802c1d3c3ffd3d33ad39953bd4a872b36cc4fc Mathlib.Algebra.GroupWithZero.Action.Pi Pi.distribSMul._proof_1 +T e34c811a49c9772704c37683341ba9a63751b9a7188c77045fb7a5e99f681455 Mathlib.Algebra.GroupWithZero.Defs GroupWithZero.zpow_zero' +T e3627171775672c30f2a0816b1a51c97ee4c3cce667815a8270a086805173a0d CertiFriProofs.Exec.Stark.SoundnessPinnedSpongeMulti CertiFri.Exec.Stark.restorePinnedPathsMultiHashM._proof_1 +T e375c0ba6f7a3ba78bc80039c100a5c71fea3497ee48713cbd5bfef3e0130136 CertiFriP3.Digest CertiFri.P3.instDecidableEqDigest.decEq._proof_7 +T e37dec8089838cda3310e3e45fe7547d4a1644c5d8c9cee5447a3ae65d7f2a17 CertiFri.Params CertiFri.instDecidableEqFriParams.decEq._proof_1 +T e37f6c095bceb15a78bdd2753696f212d89cf33a7742ab512228bbdbe16a0f18 Init.Data.Rat.Basic Rat.sub._proof_1 +T e392fa10b3f34a9871b6ae51a1b4eae74c5d4b9543d2486c4976f35e338dbe26 Mathlib.Algebra.Ring.Defs NonUnitalCommRing.toNonUnitalCommSemiring._proof_1 +T e3eb819a4d666a46a2479e8ecef5ea4db0078476b861b01dd98d98f79192e604 Mathlib.Algebra.Ring.Defs Semiring.zero_mul +T e3fe85062ee3886e60f95f509f46515aa96e0757733fe506196cf49f91605164 CertiFriProofs.Exec.Stark.SpongeGoodLogTensor CertiFri.Exec.Stark.instDecidableEqSpongeStarkMsg.decEq._proof_3 +T e4499bbf9dd8586126484f5576362db922d8ed172a94efe949bacab95bb90bbe Mathlib.Logic.Equiv.Defs Equiv.left_inv +T e472b01ccc53763bdc7f0e77b035f21e1b5a3891077f2cb2e001f7a37621a699 Mathlib.Algebra.Group.DivInvMonoid SubtractionMonoid.neg_neg +T e4a590b2ba5bc048ddde5bdf32339a0b5ddd78a00f07839ebca6fa6730eeed90 Mathlib.Basic.NNReal.Defs NNReal.instSemiring._proof_19 +T e4be418f431d68145c14e343808735fd281a6867525d7d0f7d11dd4e10763a69 Mathlib.Basic.Real.Basic _private.Mathlib.Basic.Real.Basic.0.Real.wrapped._proof_1._@.Mathlib.Basic.Real.Basic.2153608522._hygCtx._hyg.2 +T e4d229f534fc57cdb0fc278f209c74b20b9348d88a910a80537f37cc04d66739 CertiFri.Params CertiFri.instDecidableEqFriParams.decEq._proof_4 +T e501de73455f01aacb6bd572cfbdda40c8b8073e61ba037d5094805ae826b290 Init.Prelude BitVec.decEq._proof_2 +T e51207c0f7058931c6107f5f775e56804c58775c12cd3b0f13cc66d1c7a4f5f7 Mathlib.Basic.Real.Basic Real.equivCauchy._proof_1 +T e515aa1ce7b3c4e99a5cc19f368739dd1a8d47d3bcf1ed849b88c8718cbcc103 Init.Core Quotient.lift₂._proof_1 +T e539b57e9fa5ffc12abe221d11a922c9564972122523ef2c684e5bed5bea5689 Mathlib.Algebra.Group.Pi.Basic Pi.addMonoid._proof_2 +T e55c95b9ba53298fb4abea73a164675e12bc0220730d73d9f266b7c53f75d394 Mathlib.Algebra.Group.Finsupp Finsupp.instIntSMul._proof_1 +T e58bba6577cda0b8c32b6d36cea82380b07bb9cc7738f7cd96f8990177cc63f9 Mathlib.Order.Lattice instCommutativeMax_mathlib +T e5bd8e40498ffdfce958ab92547879e4246d3153c627dda886faca1e3b68ce24 Mathlib.Data.Multiset.AddSub Multiset.add._proof_1 +T e65198655d7fe0683d2c5d873eb2c790089a16dd0090b9bdbeff39b1dc8764bf Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.nonUnitalNonAssocSemiring._proof_1 +T e65c8f40e885bab283ef59c5873d3a16dbcac3df88c3dc2bfef1c496bc62b6dc Mathlib.Data.ZMod.Defs ZMod.commRing._proof_12 +T e6633e26f8e0de2dbbd0aa57ef71c2e3c3279dc2c5d4b38d8341fb84dfa679a4 Mathlib.Data.Set.Basic Set.instDistribLattice._proof_11 +T e6974cb719b2fb1537e27a46559fc10663db71bc8261f73c3ced793707aab88c Mathlib.Data.Multiset.Defs Multiset.pmap._proof_2 +T e6c328567f1b1c1f0f188a3a894b66789d559fa9bcfa2d4bd4b1a79ade411a3e Mathlib.Data.ZMod.Defs Fin.instCommRing._proof_14 +T e6e0c9cbea16f8c3b34191388c50dce31bcf50ab2a54647f1cac6777d1f14eac Mathlib.Basic.Real.Basic Real.commRing._proof_16 +T e6fbfba92e89fcd1c14a9224f4a2da805daee1ad1ff58c4a88201c3f484cc586 Init.Data.Rat.Basic Rat.inv._proof_2 +T e7511ca6b20edffd035181ae55269c0c17afba76762e4e246f944172cbc4745a Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.ring._proof_1 +T e854e26f8fc2609e5070d5a4dda4882f81d169cad6480371329806d72a0ad738 Mathlib.Algebra.Ring.Int.Defs Int.instCommRing._proof_12 +T e89ccf89d88b00a1a7ec0d5aa5eb2231b85d570c4b6e2703b87e3053545dfe14 Mathlib.Algebra.Ring.Defs CommSemiring.toNonUnitalCommSemiring._proof_4 +T e8a0c68862367f1dc2e2a88b7b606829e290ffaba006777f39cb7529c1bcef55 Mathlib.Algebra.Group.DivInvMonoid neg_zero +T e8f2b86745c53c97ad88f7ca664f17459fb5f54339a71f3f8ad8ad09a3091cdb CertiFriProofs.P3.GoldilocksExt3Qrom64 CertiFri.P3.GoldilocksExt3.qrom64_verifyBatchTensorMultiArityPinned_ep1_checked +T e8f41dd0e116b995f7ced22ba31dcd91e0446d31ec60aeeee591286659c87b58 Mathlib.Data.Nat.Find _private.Mathlib.Data.Nat.Find.0.Nat.findX._proof_1 +T e913464c2e30eefb68dec5a03a21b375d8c7839da8207e817b63c36b75eff53e Mathlib.Algebra.Group.Monoid Monoid.mul_one +T e94b31adda872ee2c326b4b584d3c05c70ec6a52d1d1235a5e6a6a24ea1ad8c1 CertiFriP3.Goldilocks CertiFri.P3.Goldilocks.ext +T e95f7f9df2a28b56c9c10323ddd6912dc90803a95eb72ed9a4d9bfd9e37a6661 Mathlib.Algebra.Polynomial.Eval.Defs _private.Mathlib.Algebra.Polynomial.Eval.Defs.0.Polynomial.wrapped._proof_1._@.Mathlib.Algebra.Polynomial.Eval.Defs.2849575019._hygCtx._hyg.2 +T e96a6c48d6c5b509aa968bee7ba81239cedf9de4d05f96c1572adce83bdb5054 Mathlib.Algebra.Ring.Rat Rat.commRing._proof_7 +T ea3d1d85a8b4b2d3093088d208622f5b3c84e411cdcacdf1337cd54120560869 Init.Data.Array.Basic Array.mapFinIdxM._proof_3 +T eaa4e40414ff2b373dc8dac335a05438e8fe24dca9b67071c3ecbd0a1bc1fe7b Init.Data.Rat.Basic Rat.pow._proof_2 +T eaae66e638d2fa9e1da87ae2d71177d9800cfa8061f1393bdede595c49af0a25 Mathlib.Algebra.Group.Fin.Basic Fin.addCommGroup._proof_6 +T eab2da4eed8998746c5aaabdd3a28fbd0d8645c1adb6c8fb3fc175f917560353 Mathlib.Data.ZMod.Defs _private.Mathlib.Data.ZMod.Defs.0.Fin.left_distrib_aux +T eacf68a563ba3876aa4f556571b1101441fda867e38aa4e7b2529e4d593acd2d Mathlib.Order.Hom.Set OrderIso.Set.univ._proof_1 +T ead4bf659e5b8260311fe5ce1383f44b7338ca3f073d50f3a61948cf429efbc5 Mathlib.Order.Lattice Subtype.semilatticeInf._proof_1 +T eb1bcfe63bc1a44c83200d1d903ff2de9708c23627bd7934cf3447f77f19ccd0 Init.Prelude List.hasDecEq._proof_1 +T eb47f2749f53e461051ad912c83d63f13fa7fbd2c69262e21b80675daa8637fe Mathlib.Data.Multiset.Defs Multiset.decidableForallMultiset._proof_2 +T eb62c83cf99404090162ce176d597485b2a51793cb33de007961864f90c6da3b CertiFriP3.DomainSep CertiFri.P3.DomainSep.v6Batch._proof_1 +T ebb91e1640677b625fc89ccda29bc5e1677ef56a1cf1b5c8e53524fcb5389aa1 CertiFriProofs.Theory.Oracle.MerkleFrozen CertiFri.Oracle.instDecidableEqSpongeQuery.decEq._proof_6 +T ebfb22fe3a018562736a0bc7151e0f70a706891ab4c49410aa5735a7589d79ec Mathlib.Basic.Complex.Basic Complex.addCommGroup._proof_8 +T ebfffd6d42a1c59d12663cef2dbe1cf215560ffc03480fbbd2cdfa09530056aa Init.Data.Rat.Basic Rat.normalize.dvd_den +T ec0e370bb399b439a0ff0f3d0c2ca11cc147a512b39ef304a90cb454435b7e84 Mathlib.Algebra.Ring.Rat Rat.commGroupWithZero._proof_5 +T ec1ec9e48575113c84859de4eb37893eeb1cd0260631a1965faa893f953cd2ef Mathlib.Data.Multiset.ZeroCons Multiset.nodup_zero +T ec846eb7bbee6f3125b2e6456fe080ad9b8866932d5d1e2bd3159be72d9e5e45 Mathlib.Basic.Complex.Basic Complex.commRing._proof_9 +T ec90cdbc7dc90d68d0ff185a6d5a07d00250fa3421ed7330e05437795338acaf CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.GoldilocksExt3.toModel_one +T ec93b1db21c472d5eb60ed67b6a366bff547698f12d666232e342da6388829a9 Mathlib.Order.Lattice Pi.instLattice._proof_1 +T eccfec5b5103ccf7e2d5378c21617f7ee16995735e1ec16e39376191a662fe1b Ix.Cert.Release05.SecurityAudit Ix.Cert.Release05.ixVm2p23_64sh_hypotheses +T ecdfed18a2c99694f343d45d5f778993889f28cf9e7786ededc6fe147a57f5be Mathlib.Data.ZMod.Defs ZMod.commRing._proof_3 +T ed1202a9ccb1d62b1e523898ee70ab71a2b3c34bb214c22c64c229a9e27aafeb CertiFriProofs.Theory.Oracle.MerkleFrozen CertiFri.Oracle.instDecidableEqSpongeQuery.decEq._proof_2 +T ed14ca8278366ffa6c14025da5d0f0d3d6b7986b9fc53c5aa68bdd8b275bdeb8 Mathlib.Algebra.Ring.Defs CommSemiring.mul_comm +T edc667a2d0ff7632e9254d077b539f528a29d3a3a68c2466514fdb67d0cef9b3 Mathlib.Algebra.Ring.Defs NonUnitalCommRing.toNonUnitalCommSemiring._proof_3 +T edf6f0df27960bf6c57ffe49c5f81a50ada23ca48f68effbe214d3f70e90b245 Init.Data.Rat.Basic Rat.add._proof_2 +T ee6b5160cd4d4c14936004be9221e14be2ee7bcf0c25b60b6fc0279141b5eea4 Mathlib.Data.Set.Basic Set.instDistribLattice._proof_1 +T ee7fc164a5487526d4a4bbbd19b3b0b1a7d3e6fdc7d36d8edc21318fa8844cfd CertiFri.Stark.Admissible CertiFri.Stark.Admissible.plainPrefixLen.go._proof_1 +T ee852b40eae82bb3121d4007a6ecf167965dbe470dafb5513e35c2628b5284b7 Mathlib.Algebra.Field.Defs DivisionRing.zpow_neg' +T ee87b38cb52ec3f96c423bd486c970980bccdbcacec9acad01c69fc3f7ae2c32 Mathlib.Basic.Real.Basic Real.commRing._proof_22 +T eeb212ed97fc7538549d130dfe381edcc96afc0bd4edbcc613676e353c49de06 Mathlib.Algebra.Group.DivInvMonoid SubNegMonoid.sub_eq_add_neg +T eeb4a5ef3960e3167f26e967b9d98c9b1e6d7ab53e82e76597d95565bbaf2345 Init.Data.Rat.Basic Rat.mul._proof_2 +T eebdf67333032153b09fe15f35fef3ec358df4a921738cba25e45320ef6667fc Init.Core Quotient.recOnSubsingleton₂._proof_1 +T eec9b65e6445cbbec60ba236a0d330b90b9f552e0f92fd6c26a7c1fd50e345af Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.ring._proof_3 +T ef193f9c83ef95dbea436cb9135ea4200c015a208d6e35af5b7f1dc473c5fc2e Mathlib.Data.Finsupp.Defs Finsupp.instZero._proof_1 +T ef2c123bfac7cc8c3d8a9cd4311e6468607daede3ea2b6528f14bd0a1db64a6a Init.Prelude Nat.le_of_succ_le_succ +T ef5243686ea685ae2f623edeaff2e34869396aa6efb88ea4e9ac63346aa2c551 Mathlib.Logic.Equiv.Set Equiv.ofLeftInverse._proof_4 +T ef57da97ada95b0da3fd89678243673fcd45a19faad925d6d6af9156f488f4f3 Init.Data.Nat.Basic Nat.le_add_right +T ef70c744979bf6601060ed7efcc209a0532c1eeeda470d9bffc364b8838b82e1 Mathlib.LinearAlgebra.Lagrange Lagrange.interpolate._proof_6 +T ef90ddd11cbe7cf7147ddd82be1b35bf9cc70674eeabf0ac076ccf2c6cbd9923 Mathlib.Algebra.Field.Defs DivisionRing.nnratCast_def +T efa8b6339dfcfb2d2665084913f8fc2baf76b15d79203277d290581b43ed925a Mathlib.Algebra.GroupWithZero.Defs CommGroupWithZero.div_eq_mul_inv +T f020b578c1a7b51cd597564065f3d3a3615ec1d3a17a707c245dd9520445052d CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.goldilocksExt3_fieldModel._proof_6 +T f063e5009175d9cc5df4996266634fd759dfc5aed3f5f069ed50e68abafcea0b Mathlib.Data.Int.Cast.Defs AddCommGroupWithOne.natCast_succ +T f065e70791a5b0a4050ada93af62f63c375a80abec8506d9f4feae495f4aefb2 CertiFriProofs.Exec.Setup CertiFri.Exec.modelParams._proof_4 +T f0827c1b72fcbd1b80f1e19cb30837378cf893ce8959ee434e7fcba17ffe42b3 Mathlib.Algebra.GroupWithZero.Action.Defs DistribMulAction.smul_add +T f0ea4edf12697d7c650626bca7a1bcaea10a136454e438d80bfcff8ab7db543a Mathlib.Algebra.Ring.Defs CommRing.toNonUnitalCommRing._proof_10 +T f0f0122138e41558d17a15828a7d2572230b6ff523cbd496bc881d937079ccb2 CertiFriP3.Digest CertiFri.P3.instDecidableEqDigest.decEq._proof_2 +T f0f3e1bbeb98047341daf2f5af5d065949c220fe28aae03edbc6afa3dff4086d CertiFri.Challenger CertiFri.instDecidableEqObservation.decEq._proof_1 +T f10e1c2683543f541c6360788ee1866b256a8fab8728e18782be89344daba847 CertiFriP3.Pruned CertiFri.P3.Pruned.ascend._unary._proof_1 +T f1357e2d07a790d330891b4cc00c7f65aebec4a7b6da1380c8e6e69b7958bab0 Mathlib.Algebra.Ring.Defs NonUnitalCommRing.toNonUnitalCommSemiring._proof_4 +T f15576c00eb5968c9c3d05e5be8353d39befcb83ec4f4b1de6fdb77197fd6cb9 Mathlib.Algebra.Polynomial.Basic Polynomial.ring._proof_5 +T f1a00fb5b8af97d3a705939e448846c99b36e85ca9597a9083a36134b2a03697 Mathlib.Basic.Real.Basic Real.instDistribLattice._proof_8 +T f1a1c6310702fac81cec8ed631267b4573fbe90272a4b5e661f2df2720992131 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.embedHom._proof_1 +T f2172ed580df30c72792bd0280d6869cfb09ed3c05c8e752df146d96d95ad1df Mathlib.Basic.Real.Basic Real.partialOrder._proof_3 +T f21cbc2051862a963d943cebe5798ad3a35f30071e0262765e2e862fa16b9947 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.instCommRing._proof_16 +T f29914863568bdff5a87853dad1860f4c0aaf4446be2b65824eb359fdf538034 Ix.Cert.Release05.SecurityAudit Ix.Cert.Release05.negControl_release05_blake3_256_below_128_classical +T f29995fdca868b9bc910dfa2a867bc88ae9548280933d95439c3346e2dd5c7cf CertiFriP3.DomainSep CertiFri.P3.DomainSep.v6Single._proof_1 +T f31f0f78117cc923e3f7d30c6a39f150d79e52983e009a32eac887829e2bac18 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.GoldilocksExt3.toModel_neg +T f34c7c977e8e755aa2512dcc1a51db61fe2a6a6a6cb97040faad01b0f77f044d Mathlib.Basic.Real.Basic Real.commRing._proof_10 +T f37265cf10f58f9b64f2188ffa1523bf907c69afa0d88dfac9aa083b71f3dad3 CertiFriProofs.Theory.Oracle.MerkleVerify CertiFri.Oracle.instDecidableEqHashQuery.decEq._proof_5 +T f3898a94fdc35590947bc039ce213990e319ef806e9a515bbe027abb17d77237 Mathlib.Data.Finset.Lattice.Basic Finset.instUnion._proof_1 +T f39ab62935f71a98461cffb9ee4102cceb1a3274959d5de5e309c64cee01b116 Mathlib.Order.LatticeIntervals Set.Ici.semilatticeSup._proof_1 +T f3a1ec646ac33d83d35acf0870f0df188875bef4595b819d9ad8b3acbaa0f64b Mathlib.Algebra.Polynomial.Basic Polynomial.monomial._proof_2 +T f3c8c83b4389d1f92b52e8dcf2be73caf252ef645e2f60bd452761a81561f148 Mathlib.Data.ZMod.Defs Fin.instCommRing._proof_10 +T f42ccfb44d5035c2f17b95aec49cdc4150209db580dbac04f7deeb2b214b8e10 Mathlib.Algebra.Order.CauSeq.Basic CauSeq.sup_equiv_sup +T f446c3e4cb170d0714f137571aa7abb669777ce465dd832f533efb00eed62783 Mathlib.Data.ZMod.Defs ZMod.commRing._proof_15 +T f49ab955534c7fa1317849e9ec1d8be5c967d4c0f9b95993da260706bc1a8eb7 Mathlib.Order.Basic Subtype.instLinearOrder._proof_7 +T f4ab8bce9d724be7be95821d6678cd13109f8f5d02a8ae3abdcc2f0e8bcc0ba3 Ix.Cert.Release05.SecurityAudit Ix.Cert.Release05.rec2p22_1sh_hypotheses +T f5004cdca7fb7ae2886553d605ebbee93c915b30859bcdfb4f9529ca884098cb Init.Data.Rat.Lemmas Rat.inv_zero +T f5568752da12da22610bd170a51c976104b30936cd4ba8a260f838c15aacd70d Mathlib.Algebra.Ring.Defs MulZeroClass.negZeroClass._proof_1 +T f55b76d9906f44344862ac63de42dbb7ce8147a7085ae77bb38ae26b60004126 CertiFriProofs.P3.DigestCard CertiFri.P3.digestEquivFun._proof_2 +T f5967521a476243af21298578443af504320241d8f664e18a0cd99149e7ac279 Mathlib.Algebra.Group.Fin.Basic Fin.addCommMonoid._proof_2 +T f5d9283942bb2787e4f5e9da332d2542ab4803dd4c16bfb70fe36631e979b4f1 Mathlib.Basic.NNReal.Defs NNReal.instSemiring._proof_15 +T f6364fb63084a7a327cd75a712b870515f63801c0f4096a0de27faafafa8d6c5 Mathlib.Algebra.Order.Ring.Rat Rat.instIsStrictOrderedRing +T f636a0ee88afc81ac68c9058541154a08f0b389f3eb6c46475b46d7e54819d03 Mathlib.Basic.Real.Basic _private.Mathlib.Basic.Real.Basic.0.Real.wrapped._proof_1._@.Mathlib.Basic.Real.Basic.326038627._hygCtx._hyg.2 +T f663ac37e49fbb1ac4ad041782ed7bea5ba2b8496447ab1bab0fcf5f09603bfc Mathlib.Data.Nat.Basic Nat.instLinearOrder._proof_1 +T f66e44419247db781173c6804a4604606b5e943b4aad5e329dd84cec16672e29 Mathlib.Algebra.Ring.Defs CommRing.toNonUnitalCommRing._proof_6 +T f69351616c5e30607eeccc91ffbe6a32c3f87dd3a12f235f89751c2406b253c2 Mathlib.Algebra.Ring.Defs NonUnitalNonAssocRing.toHasDistribNeg._proof_5 +T f69d4891d71366e111d6f5f9c3867e4b722e3026e85477cd9ff5fbb247d5dc4d Mathlib.Basic.Complex.Basic Complex.commRing._proof_6 +T f712098b6175a7a6ecefcc5625bbeaa21b0657507b842d6d4dd0e98962e8d958 Mathlib.Algebra.Field.ZMod ZMod.instField._proof_8 +T f75faefeccd1d90d7902a410f6620142ef3ceaea05566c77af60a58305fd617d Ix.Cert.Release05.SecurityAudit Ix.Cert.Release05.ixVm2p23_4096sh_stdQro64 +T f77dca7919c4e7b882ce133e116367d75ab6150238e87ee29136be0b3d38b928 Mathlib.Algebra.Field.Defs DivisionRing.inv_zero +T f7a3624fe879ae44cc84eca5f851a34948a8d0c421617dfe4253924e1daccfcd Mathlib.Algebra.Polynomial.Basic Polynomial.distribMulAction._proof_3 +T f7e109c5a326e872ad387222feaa9f2d2df1bb0306dddbaf375d2b4866542d0e Mathlib.Algebra.Field.Defs Field.nnqsmul_def +T f7fb833a18c54db51d9c1af5701a457652d455dcdf6fa48c60c94720d0cae28f CertiFriP3.Digest CertiFri.P3.instDecidableEqDigest.decEq._proof_8 +T f8125c1860fedacadf645c944ae9cf07d0ccd71d1b983ca83e7dfb30d076e07f Init.Data.List.Sort.Basic _private.Init.Data.List.Sort.Basic.0.List.MergeSort.Internal.splitInTwo._proof_3 +T f87864380484c452b9795196d7a4985c6490e401a20d47de41f83db05e9f35b4 Mathlib.Data.ZMod.Defs ZMod.commRing._proof_5 +T f89ea0c14f5cbb3c7e3200b3e9900d7d5480d0762419c4fdbd41632de65effd3 Init.Data.Rat.Lemmas Rat.le_total +T f8ba22dbf8807be58f0955e0f56ccb2963a26beb90836a5b845f74f3b4dbd33d Mathlib.Algebra.Ring.Int.Defs Int.instCommRing._proof_4 +T f92aa9cad27dc72ffed28b9aebc0b35379bd2c5f432fc353cc39eace9800d4ce CertiFriProofs.Exec.Setup CertiFri.Exec.FieldModel.surj +T f933b570a78447f1319a0b6042a8ba7c271721083561dae1723607b089df66e1 Mathlib.Algebra.Field.Defs Semifield.zpow_neg' +T f947eeb0fd871ff029fc635ad8cfa3485d3f845687c776862a7a7644af647226 Mathlib.Order.RelIso.Basic RelEmbedding.ofMapRelIff._proof_1 +T f999f6615354074d64144d4a8b333e17415bf661ee5df2e401dcbe5f72241d38 Ix.Cert.Release05.SecurityAudit Ix.Cert.Release05.negControl_release05_fp3_below_100_qrom +T f99de6d4bad2af597a6402b593b0058afc282473f43852937c378fbe1985fe7c Mathlib.Analysis.Real.Sqrt NNReal.sqrt._proof_1 +T f9bf5ccea9d97d92c15242a9fc3a745c3dee1f41bb6830ef394f7fc1af571ef6 Init.Prelude Nat.lt_of_le_of_lt +T f9d2b8012f0500f0a6b68e737588b7875d248698da6476912744814681c54b4f Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.instAddMonoid._proof_3 +T fa0318e2f9825c819e37c4dfe94535c7f02d8bd79581e17bf54967104f1b9c13 Init.Data.Array.Basic Array.anyM.loop._proof_1 +T fa247b1971741b3492c474fa72d6bf840332e15f2f293369571c53451f611803 Mathlib.Data.List.Perm.Basic List.Perm.foldr_eq +T fa3fb89abf6207411184178a90e9e6cfcca94930d3e7c96735de33067cf1ce6a Mathlib.Algebra.Group.Finsupp Finsupp.instAddMonoid._proof_1 +T fa8ad11e8a4296c9801fbe559b585c643c2e7c5f3cb94e8eb432dafab42f8df8 Mathlib.Order.PropInstances Prop.instDistribLattice._proof_1 +T fa94238de46e624869f68f5abb46f364d457c8ee42c4a7a74b7b3f95739f75c8 Mathlib.Algebra.Group.Finsupp Finsupp.instAddMonoid._proof_3 +T fab99266435a9a162ef4c2340051cacc23666c947ea20c64ae00e8c8e780a153 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.Fp3Model.instCommRing._proof_14 +T fabf4f678f9d2e6612de94548fbe0f8d5272dfad3a526d7a11f5453cc62c6c52 Mathlib.Data.Set.Basic Set.instDistribLattice._proof_3 +T fad94f4a944d040e3c32b6f2f251d7c4dcd667edf29a389ede1eb790e3c6bc2a Mathlib.Logic.Equiv.Set Equiv.ofLeftInverse._proof_3 +T fb4fd93b0ecd524e2984a8b09a48c0cfaae358c18d8ab39e861183568f4cc18b Mathlib.Data.Multiset.AddSub Multiset.zero_add +T fb7c2e882a8b74e714c47220ba6baca6313e09feacfbf59514d2a0b0357f41c4 Mathlib.Data.ZMod.Defs Fin.instNonUnitalCommRing._proof_3 +T fbb13d10a00ea5073920efbc263dc3488727d793a4fe5e31b26f7582c389dbfa Init.Data.Nat.Basic Nat.sub_one_lt +T fbc79119353e4b300d4e520e04f4c7ccf0ddb70acd88e8bf61aef013f346f626 Mathlib.Algebra.Ring.Int.Defs Int.instCommRing._proof_3 +T fbcef55d1ce7fbc1b44de82e292dbb7929ea74880d0dc30c811cbc41fad3a03b Mathlib.Algebra.Field.Defs Field.qsmul_def +T fbd51c0db4269d1d311761bf3fdfe289302b3537666b1425e9a3aa8b0e538494 CertiFriProofs.P3.GoldilocksExt3 CertiFri.P3.GoldilocksExt3.toModel_zero +T fc21d0c3219dc1bbab1eec965781fe5bbf8e1873d045522cdefe3ba8ea5eb519 Mathlib.Order.Lattice instDistribLatticeOfLinearOrder._proof_1 +T fcebe40bcd28e5b023a354fa55729821a29bc1b30cd0adc29a25940d4cf14c4b Mathlib.Data.Multiset.Defs Multiset.decidableEq._proof_2 +T fd7b6903eb9114daafe610a0e1cdb8af62ca09d2e794eb9ccf4156b182092a68 Mathlib.Order.Lattice Lattice.toLinearOrder._proof_1 +T fda59c177a56ca4336a199f9aede57c25970077dc3e2056f407fe8fe3de9a172 Mathlib.Algebra.Field.Defs DivisionSemiring.toNontrivial +T fe198e687cc7bea9299bca0fd66b606ae0697b7f76fb20e2b09d572a4b7a75ea Mathlib.Algebra.MonoidAlgebra.Defs AddMonoidAlgebra.coeffEquiv._proof_1 +T fe19b6a6ee9b4574e0232150da8f2ae744279349d244a4d808ee05246bb9e1b0 Mathlib.Algebra.GroupWithZero.Defs CommGroupWithZero.mul_inv_cancel +T fe21f172aa6ca385e90a24c560ef8ac43d4b6d9bb8f5e0048900846a0c6fe78f Mathlib.Data.Finset.Prod Finset.product._proof_1 +T fe263cf28044e8ccaf5f427f60bca1586c10f817ef063abc045ea3691df55aa5 Mathlib.Order.Defs.LinearOrder le_min +T fe49e5ff78e453b7f7041bf37c0e5940b81efdf93360f2c3ed579a446d7e774b Init.Data.Range.Basic _private.Init.Data.Range.Basic.0.Std.Legacy.Range.forIn'._proof_1 +T fe5414831b17a0194b3909cf9ab77623ba0ef0f757fdddcb34a5fda8ef38c18a Mathlib.Algebra.Polynomial.Basic Polynomial.C._proof_1 +T fe5bd78d89bb8832bee379dfc2c48630d30c8a743519e39323f4f410c5e2bb68 Mathlib.Data.ZMod.Defs ZMod.commRing._proof_16 +T fef02e522afaa0cce3a89055d0f448938051a2c2f4336dd565351be98004adab Ix.Cert.Release05.SecurityAudit Ix.Cert.Release05.ixVm2p23_64sh_qrom64_sub_one +T ff375a999ce4c2e1882b43a92b4f25e9513e0ed3543c8805a4a9e75ab228bd59 Mathlib.Order.RelIso.Basic RelIso.map_rel_iff' +T ff39878c639896c4d43e19be46d9992cf40fa3e09a5f305c7271bfb63b007fc6 Mathlib.Algebra.Group.DivInvMonoid SubNegMonoid.zsmul_zero' +T ff7ab4574a05116fc37f5fc8ef01aff90d4d6d7733ae2a2329d695c4eef1b117 Mathlib.Algebra.Group.Monoid CommMonoid.mul_comm +T ff7f674c7d66b2aa650d88efec4f9c7ad5d5d5539089386a4a9f5791ba7c524f Mathlib.Algebra.Order.CauSeq.Basic CauSeq.instSub._proof_1 +T ff8106e242723d9ec3ef2e27a143388d496011c5ca450f81785f83c4090ed8bf Mathlib.Data.ZMod.Defs ZMod.commRing._proof_17 +T ff81134eb21abcabd3c0ea586cf03e49d856102eabedeadf34e22a7640bd292e Mathlib.Order.Lattice Pi.instSemilatticeInf._proof_2 +T fffdcadfa8c79b41adda3e5fed71a59f2cb8e6b0cfe8413826a4b2aed1a2f900 Mathlib.Basic.NNReal.Defs Real.toNNReal._proof_1 diff --git a/Tests/FormalPackageMain.lean b/Tests/FormalPackageMain.lean index 933826105d..e43b4f8d5b 100644 --- a/Tests/FormalPackageMain.lean +++ b/Tests/FormalPackageMain.lean @@ -21,8 +21,8 @@ private def runNamed (getEnv : IO Lean.Environment) (name : String) : IO UInt32 | "instance-symbols" => Tests.Ix.InstanceSymbols.run | "ixvm-source" => do Tests.Ix.VMSource.run (← getEnv) | "multistark-verifier" => do - let ts ← Tests.Ix.MultiStarkVerifier.suite - LSpec.lspecIO (.ofList [("multistark-verifier", ts)]) [] + let spec ← Tests.Ix.MultiStarkVerifier.suite + LSpec.lspecMain (LSpec.describe "multistark-verifier" spec) [] | "ixvm-export-safe-walk" => Tests.Ix.IxVM.SafeReferencesWalk.exportWalkArtifact | other => IO.eprintln s!"[formal-package-tests] unknown entry: {other}" diff --git a/Tests/Gen/Basic.lean b/Tests/Gen/Basic.lean index cc078b043d..75ff8885f9 100644 --- a/Tests/Gen/Basic.lean +++ b/Tests/Gen/Basic.lean @@ -9,64 +9,58 @@ public import Std.Data.HashMap public section -open LSpec SlimCheck Gen +open LSpec LSpec.Prop Gen /-! ## Helper combinators -/ def genUInt8 : Gen UInt8 := - UInt8.ofNat <$> choose Nat 0 0xFF + Gen.chooseUInt8 def genUInt32 : Gen UInt32 := - UInt32.ofNat <$> choose Nat 0 0xFFFFFFFF + Gen.chooseUInt32 def genUInt64 : Gen UInt64 := - UInt64.ofNat <$> choose Nat 0 0xFFFFFFFFFFFFFFFF + Gen.chooseUInt64 def genUSize : Gen USize := - .ofNat <$> choose Nat 0 (2^System.Platform.numBits - 1) + .ofNat <$> Gen.chooseNat 0 (2^System.Platform.numBits - 1) -def frequency' (default: Gen α) (xs: List (Nat × Gen α)) : Gen α := do - let n ← choose Nat 0 total - pick n xs - where - total := List.sum (Prod.fst <$> xs) - pick n xs := match xs with - | [] => default - | (k, x) :: xs => if n <= k then x else pick (n - k) xs +def frequency' (default : Gen α) (xs : List (Nat × Gen α)) : Gen α := + Gen.frequency xs.toArray default -def frequency [Inhabited α] (xs: List (Nat × Gen α)) : Gen α := - frequency' xs.head!.snd xs +def frequency [Inhabited α] (xs : List (Nat × Gen α)) : Gen α := + Gen.frequency xs.toArray (pure default) -def oneOf' [Inhabited α] (xs: List (Gen α)) : Gen α := - frequency (xs.map (fun x => (100, x))) +def oneOf' [Inhabited α] (xs : List (Gen α)) : Gen α := + Gen.oneOf! xs.toArray /-! ## Basic type generators -/ /-- Generate Nats across the full range: small, medium, large, and huge -/ def genNat : Gen Nat := do - let choice ← choose Nat 0 100 + let choice ← Gen.chooseNat 0 100 if choice < 50 then -- 50%: small nats (0-1000) - choose Nat 0 1000 + Gen.chooseNat 0 1000 else if choice < 75 then -- 25%: medium nats (up to 2^32) - choose Nat 0 (2^32) + Gen.chooseNat 0 (2^32) else if choice < 90 then -- 15%: large nats (up to 2^64) - choose Nat 0 (2^64) + Gen.chooseNat 0 (2^64) else -- 10%: huge nats (up to 2^256) - choose Nat 0 (2^256) + Gen.chooseNat 0 (2^256) -def genSmallNat : Gen Nat := choose Nat 0 1000 +def genSmallNat : Gen Nat := Gen.chooseNat 0 1000 def genString : Gen String := do - let len ← choose Nat 0 100 - let chars ← Gen.listOf (choose Nat 32 126 >>= fun n => pure (Char.ofNat n)) + let len ← Gen.chooseNat 0 100 + let chars ← Gen.listOf (Gen.chooseNat 32 126 >>= fun n => pure (Char.ofNat n)) pure (String.ofList (chars.take len)) def genListNat : Gen (List Nat) := do - let len ← choose Nat 0 20 + let len ← Gen.chooseNat 0 20 let mut result := [] for _ in [:len] do result := (← genSmallNat) :: result @@ -77,17 +71,17 @@ def genArrayNat : Gen (Array Nat) := do pure list.toArray def genByteArray : Gen ByteArray := do - let len ← choose Nat 0 100 + let len ← Gen.chooseNat 0 100 let mut bytes := ByteArray.emptyWithCapacity len for _ in [:len] do - let b ← choose Nat 0 255 + let b ← Gen.chooseNat 0 255 bytes := bytes.push b.toUInt8 pure bytes -def genBool : Gen Bool := choose Bool .false true +def genBool : Gen Bool := Gen.bool def genHashMapNatNat : Gen (Std.HashMap Nat Nat) := do - let len ← choose Nat 0 20 + let len ← Gen.chooseNat 0 20 let mut map : Std.HashMap Nat Nat := {} for _ in [:len] do let k ← genSmallNat @@ -95,27 +89,13 @@ def genHashMapNatNat : Gen (Std.HashMap Nat Nat) := do map := map.insert k v pure map -/-! ## Shrinkable instances -/ - -instance : Shrinkable Nat where - shrink n := if n == 0 then [] else [n / 2] - -instance : Shrinkable (List Nat) where - shrink xs := match xs with - | [] => [] - | _ :: tail => [tail] - -instance : Shrinkable (Array Nat) where - shrink arr := if arr.isEmpty then [] else [arr.pop] +/-! ## FormatValue / Shrinkable / Sampleable instances -/ instance : Repr ByteArray where reprPrec ba _ := s!"ByteArray#{ba.toList}" -instance : Shrinkable ByteArray where - shrink ba := if ba.isEmpty then [] else [ba.extract 0 (ba.size - 1)] - -instance : Shrinkable String where - shrink s := if s.isEmpty then [] else [s.dropEnd 1 |>.toString] +instance : FormatValue (Std.HashMap Nat Nat) where + formatValue m := reprStr m.toList instance : Shrinkable (Std.HashMap Nat Nat) where shrink m := @@ -124,18 +104,6 @@ instance : Shrinkable (Std.HashMap Nat Nat) where | [] => [] | _ :: tail => [Std.HashMap.ofList tail] -/-! ## SampleableExt instances -/ - -instance : SampleableExt Nat := SampleableExt.mkSelfContained genNat - -instance : SampleableExt (List Nat) := SampleableExt.mkSelfContained genListNat - -instance : SampleableExt (Array Nat) := SampleableExt.mkSelfContained genArrayNat - -instance : SampleableExt ByteArray := SampleableExt.mkSelfContained genByteArray - -instance : SampleableExt String := SampleableExt.mkSelfContained genString - -instance : SampleableExt (Std.HashMap Nat Nat) := SampleableExt.mkSelfContained genHashMapNatNat +instance : Sampleable (Std.HashMap Nat Nat) := ⟨genHashMapNatNat⟩ end diff --git a/Tests/Gen/Claim.lean b/Tests/Gen/Claim.lean index f562a4b47b..c553b141d0 100644 --- a/Tests/Gen/Claim.lean +++ b/Tests/Gen/Claim.lean @@ -9,7 +9,7 @@ public import Ix.Claim public section -open LSpec SlimCheck Gen +open LSpec LSpec.Prop Gen open Ix (RevealConstructorInfo RevealRecursorRule RevealMutConstInfo RevealConstantInfo CompilePolicy CompileClaim Claim DefKind DefinitionSafety QuotKind) open Tests.Gen.Ixon (genAddress genUInt64Small genDefKind genDefinitionSafety genQuotKindNew @@ -168,13 +168,13 @@ instance : Shrinkable Claim where | .binding _ _ => [] | .compile _ => [] -/-! ## SampleableExt instances -/ +/-! ## Sampleable instances -/ -instance : SampleableExt RevealConstructorInfo := SampleableExt.mkSelfContained genRevealConstructorInfo -instance : SampleableExt RevealRecursorRule := SampleableExt.mkSelfContained genRevealRecursorRule -instance : SampleableExt RevealMutConstInfo := SampleableExt.mkSelfContained genRevealMutConstInfo -instance : SampleableExt RevealConstantInfo := SampleableExt.mkSelfContained genRevealConstantInfo -instance : SampleableExt Claim := SampleableExt.mkSelfContained genClaim +instance : Sampleable RevealConstructorInfo := ⟨genRevealConstructorInfo⟩ +instance : Sampleable RevealRecursorRule := ⟨genRevealRecursorRule⟩ +instance : Sampleable RevealMutConstInfo := ⟨genRevealMutConstInfo⟩ +instance : Sampleable RevealConstantInfo := ⟨genRevealConstantInfo⟩ +instance : Sampleable Claim := ⟨genClaim⟩ end Tests.Gen.Claim diff --git a/Tests/Gen/Ix.lean b/Tests/Gen/Ix.lean index c3fb90bae1..72f7fcf0da 100644 --- a/Tests/Gen/Ix.lean +++ b/Tests/Gen/Ix.lean @@ -14,7 +14,7 @@ public import Ix.CondenseM public section -open LSpec SlimCheck Gen +open LSpec LSpec.Prop Gen namespace Tests.Gen.Ix @@ -27,13 +27,13 @@ def genIxName : Nat → Gen Ix.Name (1, pure Ix.Name.mkAnon), (4, do let parent ← genIxName fuel - let len ← choose Nat 1 12 - let chars ← Gen.listOf (choose Nat 97 122 >>= fun n => pure (Char.ofNat n)) + let len ← Gen.chooseNat 1 12 + let chars ← Gen.listOf (Gen.chooseNat 97 122 >>= fun n => pure (Char.ofNat n)) let s := String.ofList (chars.take len) pure (Ix.Name.mkStr parent s)), (3, do let parent ← genIxName fuel - let n ← choose Nat 0 1000 + let n ← Gen.chooseNat 0 1000 pure (Ix.Name.mkNat parent n)) ] (pure Ix.Name.mkAnon) @@ -76,27 +76,27 @@ def genBinderInfo : Gen Lean.BinderInfo := /-- Generate a Literal -/ def genLiteral : Gen Lean.Literal := frequency [ - (5, Lean.Literal.natVal <$> choose Nat 0 1000), - (5, Lean.Literal.strVal <$> Gen.elements #["hello", "world", "foo", "bar", "test", "literal"]), + (5, Lean.Literal.natVal <$> Gen.chooseNat 0 1000), + (5, Lean.Literal.strVal <$> Gen.elements! #["hello", "world", "foo", "bar", "test", "literal"]), ] /-- Generate an Ix.Int for DataValue -/ def genIxInt : Gen Ix.Int := frequency [ - (5, Ix.Int.ofNat <$> choose Nat 0 100), - (5, Ix.Int.negSucc <$> choose Nat 0 50), + (5, Ix.Int.ofNat <$> Gen.chooseNat 0 100), + (5, Ix.Int.negSucc <$> Gen.chooseNat 0 50), ] /-- Generate a random string from a list of options -/ def genIxString : Gen String := - Gen.elements #["foo", "bar", "test", "x", "y", "value", "item", "data", "node", "leaf"] + Gen.elements! #["foo", "bar", "test", "x", "y", "value", "item", "data", "node", "leaf"] /-- Generate Ix.Substring -/ def genIxSubstring : Gen Ix.Substring := do - let s ← Gen.elements #["hello world", "test string", "foo bar baz", "quick brown fox", "lorem ipsum"] + let s ← Gen.elements! #["hello world", "test string", "foo bar baz", "quick brown fox", "lorem ipsum"] let maxLen := s.length - let startPos ← choose Nat 0 (maxLen / 2) - let stopPos ← choose Nat startPos maxLen + let startPos ← Gen.chooseNat 0 (maxLen / 2) + let stopPos ← Gen.chooseNat startPos maxLen pure (Ix.Substring.mk s startPos stopPos) instance : Shrinkable Ix.Name where @@ -109,7 +109,7 @@ instance : Shrinkable Ix.Substring where shrink ss := (if ss.str.length > 0 then [{ ss with str := "", startPos := 0, stopPos := 0 }] else []) ++ (if ss.stopPos > ss.startPos then [{ ss with stopPos := ss.startPos }] else []) -instance : SampleableExt Ix.Substring := SampleableExt.mkSelfContained genIxSubstring +instance : Sampleable Ix.Substring := ⟨genIxSubstring⟩ /-- Generate Ix.SourceInfo with all variants -/ def genIxSourceInfo : Gen Ix.SourceInfo := @@ -117,13 +117,13 @@ def genIxSourceInfo : Gen Ix.SourceInfo := (5, pure Ix.SourceInfo.none), (3, do let leading ← genIxSubstring - let leadingPos ← choose Nat 0 100 + let leadingPos ← Gen.chooseNat 0 100 let trailing ← genIxSubstring - let trailingPos ← choose Nat 0 100 + let trailingPos ← Gen.chooseNat 0 100 pure (Ix.SourceInfo.original leading leadingPos trailing trailingPos)), (2, do - let start ← choose Nat 0 100 - let stop ← choose Nat 100 200 + let start ← Gen.chooseNat 0 100 + let stop ← Gen.chooseNat 100 200 let canonical ← frequency [(1, pure true), (1, pure false)] pure (Ix.SourceInfo.synthetic start stop canonical)), ] @@ -133,7 +133,7 @@ instance : Shrinkable Ix.SourceInfo where | .none => [] | _ => [.none] -instance : SampleableExt Ix.SourceInfo := SampleableExt.mkSelfContained genIxSourceInfo +instance : Sampleable Ix.SourceInfo := ⟨genIxSourceInfo⟩ /-- Generate Ix.SyntaxPreresolved with all variants -/ def genIxSyntaxPreresolved : Gen Ix.SyntaxPreresolved := @@ -141,7 +141,7 @@ def genIxSyntaxPreresolved : Gen Ix.SyntaxPreresolved := (1, Ix.SyntaxPreresolved.namespace <$> genIxName 3), (1, do let name ← genIxName 3 - let numAliases ← Gen.choose Nat 0 3 + let numAliases ← Gen.chooseNat 0 3 let mut aliases : Array String := #[] for _ in [:numAliases] do aliases := aliases.push (← genIxString) @@ -155,7 +155,7 @@ instance : Shrinkable Ix.SyntaxPreresolved where [.namespace n] ++ (if aliases.size > 0 then [.decl n aliases.pop] else []) ++ ((.decl · aliases) <$> Shrinkable.shrink n) -instance : SampleableExt Ix.SyntaxPreresolved := SampleableExt.mkSelfContained genIxSyntaxPreresolved +instance : Sampleable Ix.SyntaxPreresolved := ⟨genIxSyntaxPreresolved⟩ /-- Generate Ix.Syntax with all variants including node -/ def genIxSyntaxAux : Nat → Gen Ix.Syntax @@ -166,7 +166,7 @@ def genIxSyntaxAux : Nat → Gen Ix.Syntax let info ← genIxSourceInfo let rawVal ← genIxSubstring let name ← genIxName 2 - let numPreresolved ← Gen.choose Nat 0 2 + let numPreresolved ← Gen.chooseNat 0 2 let mut preresolved : Array Ix.SyntaxPreresolved := #[] for _ in [:numPreresolved] do preresolved := preresolved.push (← genIxSyntaxPreresolved) @@ -179,7 +179,7 @@ def genIxSyntaxAux : Nat → Gen Ix.Syntax let info ← genIxSourceInfo let rawVal ← genIxSubstring let name ← genIxName 2 - let numPreresolved ← Gen.choose Nat 0 2 + let numPreresolved ← Gen.chooseNat 0 2 let mut preresolved : Array Ix.SyntaxPreresolved := #[] for _ in [:numPreresolved] do preresolved := preresolved.push (← genIxSyntaxPreresolved) @@ -187,7 +187,7 @@ def genIxSyntaxAux : Nat → Gen Ix.Syntax (3, do let info ← genIxSourceInfo let kind ← genIxName 2 - let numChildren ← Gen.choose Nat 0 3 + let numChildren ← Gen.chooseNat 0 3 let mut children : Array Ix.Syntax := #[] for _ in [:numChildren] do children := children.push (← genIxSyntaxAux (fuel / 2)) @@ -202,7 +202,7 @@ def genIxDataValue : Gen Ix.DataValue := (10, Ix.DataValue.ofString <$> genIxString), (10, Ix.DataValue.ofBool <$> frequency [(1, pure true), (1, pure false)]), (10, Ix.DataValue.ofName <$> genIxName 3), - (10, Ix.DataValue.ofNat <$> choose Nat 0 1000), + (10, Ix.DataValue.ofNat <$> Gen.chooseNat 0 1000), (10, Ix.DataValue.ofInt <$> genIxInt), (5, Ix.DataValue.ofSyntax <$> genIxSyntax), ] @@ -210,14 +210,14 @@ def genIxDataValue : Gen Ix.DataValue := /-- Generate Ix.Expr with all variants and deeper nesting -/ def genIxExpr : Nat → Gen Ix.Expr | 0 => Gen.frequency #[ - (3, do let idx ← choose Nat 0 20; pure (Ix.Expr.mkBVar idx)), + (3, do let idx ← Gen.chooseNat 0 20; pure (Ix.Expr.mkBVar idx)), (2, do let u ← genIxLevel 3; pure (Ix.Expr.mkSort u)), (2, do let n ← genIxName 3; pure (Ix.Expr.mkFVar n)), (1, Ix.Expr.mkLit <$> genLiteral) ] (pure (Ix.Expr.mkBVar 0)) | fuel + 1 => Gen.frequency #[ -- Base cases (weighted higher to ensure termination) - (4, do let idx ← choose Nat 0 20; pure (Ix.Expr.mkBVar idx)), + (4, do let idx ← Gen.chooseNat 0 20; pure (Ix.Expr.mkBVar idx)), (2, do let u ← genIxLevel 4; pure (Ix.Expr.mkSort u)), (2, do let n ← genIxName 4; pure (Ix.Expr.mkFVar n)), (1, do let n ← genIxName 4; pure (Ix.Expr.mkMVar n)), @@ -225,7 +225,7 @@ def genIxExpr : Nat → Gen Ix.Expr -- Const with universe levels (4, do let n ← genIxName 4 - let numLevels ← choose Nat 0 4 + let numLevels ← Gen.chooseNat 0 4 let mut levels : Array Ix.Level := #[] for _ in [:numLevels] do levels := levels.push (← genIxLevel 4) @@ -259,7 +259,7 @@ def genIxExpr : Nat → Gen Ix.Expr pure (Ix.Expr.mkLetE n ty val body nonDep)), -- MData with metadata (2, do - let numEntries ← choose Nat 1 4 + let numEntries ← Gen.chooseNat 1 4 let mut entries : Array (Ix.Name × Ix.DataValue) := #[] for _ in [:numEntries] do let key ← genIxName 2 @@ -270,12 +270,12 @@ def genIxExpr : Nat → Gen Ix.Expr -- Proj (2, do let typeName ← genIxName 4 - let idx ← choose Nat 0 10 + let idx ← Gen.chooseNat 0 10 let struct ← genIxExpr (fuel / 2) pure (Ix.Expr.mkProj typeName idx struct)) ] (pure (Ix.Expr.mkBVar 0)) -instance : SampleableExt Ix.Name := SampleableExt.mkSelfContained (genIxName 5) +instance : Sampleable Ix.Name := ⟨(genIxName 5)⟩ instance : Shrinkable Ix.Level where shrink l := match l with @@ -286,7 +286,7 @@ instance : Shrinkable Ix.Level where | .param _ _ => [Ix.Level.mkZero] | .mvar _ _ => [Ix.Level.mkZero] -instance : SampleableExt Ix.Level := SampleableExt.mkSelfContained (genIxLevel 5) +instance : Sampleable Ix.Level := ⟨(genIxLevel 5)⟩ instance : Shrinkable Ix.Expr where shrink e := match e with @@ -303,11 +303,11 @@ instance : Shrinkable Ix.Expr where | .mdata _ e _ => [e] | .proj _ _ e _ => [e] -instance : SampleableExt Ix.Expr := SampleableExt.mkSelfContained (genIxExpr 5) +instance : Sampleable Ix.Expr := ⟨(genIxExpr 5)⟩ /-- Generate an array of level parameter names with varied sizes -/ def genLevelParams : Gen (Array Ix.Name) := do - let numParams ← choose Nat 0 5 + let numParams ← Gen.chooseNat 0 5 let mut params : Array Ix.Name := #[] for i in [:numParams] do -- Use varied names, not just u, v, w @@ -347,7 +347,7 @@ def genDefinitionSafety : Gen Lean.DefinitionSafety := /-- Generate an array of mutually recursive names -/ def genMutualNames (baseName : Ix.Name) : Gen (Array Ix.Name) := do - let numMutual ← choose Nat 1 4 + let numMutual ← Gen.chooseNat 1 4 let mut names : Array Ix.Name := #[baseName] for i in [1:numMutual] do names := names.push (Ix.Name.mkStr baseName s!"_mutual_{i}") @@ -392,7 +392,7 @@ def genIxQuotVal : Gen Ix.QuotVal := /-- Generate constructor names for an inductive -/ def genConstructorNames (inductName : Ix.Name) : Gen (Array Ix.Name) := do - let numCtors ← choose Nat 1 5 + let numCtors ← Gen.chooseNat 1 5 let mut ctors : Array Ix.Name := #[] let ctorNames := #["mk", "nil", "cons", "zero", "succ", "inl", "inr", "intro", "refl"] for i in [:numCtors] do @@ -403,12 +403,12 @@ def genConstructorNames (inductName : Ix.Name) : Gen (Array Ix.Name) := do /-- Generate a random Ix.InductiveVal -/ def genIxInductiveVal : Gen Ix.InductiveVal := do let cnst ← genIxConstantVal - let numParams ← choose Nat 0 5 - let numIndices ← choose Nat 0 3 + let numParams ← Gen.chooseNat 0 5 + let numIndices ← Gen.chooseNat 0 3 let isRec ← frequency [(6, pure false), (4, pure true)] let isUnsafe ← frequency [(9, pure false), (1, pure true)] let isReflexive ← frequency [(7, pure false), (3, pure true)] - let numNested ← choose Nat 0 3 + let numNested ← Gen.chooseNat 0 3 let all ← genMutualNames cnst.name let ctors ← genConstructorNames cnst.name pure { @@ -427,16 +427,16 @@ def genIxInductiveVal : Gen Ix.InductiveVal := do def genIxConstructorVal : Gen Ix.ConstructorVal := do let cnst ← genIxConstantVal let induct ← genIxName 5 - let cidx ← choose Nat 0 10 - let numParams ← choose Nat 0 5 - let numFields ← choose Nat 0 8 + let cidx ← Gen.chooseNat 0 10 + let numParams ← Gen.chooseNat 0 5 + let numFields ← Gen.chooseNat 0 8 let isUnsafe ← frequency [(9, pure false), (1, pure true)] pure { cnst, induct, cidx, numParams, numFields, isUnsafe } /-- Generate a random Ix.RecursorRule -/ def genIxRecursorRule : Gen Ix.RecursorRule := do let ctor ← genIxName 5 - let nfields ← choose Nat 0 8 + let nfields ← Gen.chooseNat 0 8 let rhs ← genIxExpr 5 pure { ctor, nfields, rhs } @@ -444,11 +444,11 @@ def genIxRecursorRule : Gen Ix.RecursorRule := do def genIxRecursorVal : Gen Ix.RecursorVal := do let cnst ← genIxConstantVal let all ← genMutualNames cnst.name - let numParams ← choose Nat 0 5 - let numIndices ← choose Nat 0 3 - let numMotives ← choose Nat 1 4 - let numMinors ← choose Nat 0 6 - let numRules ← choose Nat 1 5 + let numParams ← Gen.chooseNat 0 5 + let numIndices ← Gen.chooseNat 0 3 + let numMotives ← Gen.chooseNat 1 4 + let numMinors ← Gen.chooseNat 0 6 + let numRules ← Gen.chooseNat 1 5 let mut rules : Array Ix.RecursorRule := #[] for _ in [:numRules] do rules := rules.push (← genIxRecursorRule) @@ -482,14 +482,14 @@ instance : Shrinkable Ix.ConstantInfo where | .axiomInfo _ => [] | _ => [.axiomInfo { cnst := simpleCnst, isUnsafe := false }] -instance : SampleableExt Ix.ConstantInfo := SampleableExt.mkSelfContained genIxConstantInfo +instance : Sampleable Ix.ConstantInfo := ⟨genIxConstantInfo⟩ /-! ## Generators for Additional Ix Types -/ def genAddress : Gen Address := Tests.Gen.Ixon.genAddress instance : Shrinkable Address where shrink _ := [] -instance : SampleableExt Address := SampleableExt.mkSelfContained genAddress +instance : Sampleable Address := ⟨genAddress⟩ -- Ix.Int already has genIxInt defined earlier instance : Shrinkable Ix.Int where @@ -497,7 +497,7 @@ instance : Shrinkable Ix.Int where | .ofNat n => if n > 0 then [.ofNat (n / 2)] else [] | .negSucc n => [.ofNat 0] ++ if n > 0 then [.negSucc (n / 2)] else [] -instance : SampleableExt Ix.Int := SampleableExt.mkSelfContained genIxInt +instance : Sampleable Ix.Int := ⟨genIxInt⟩ -- Ix.Syntax already has genIxSyntax defined earlier instance : Shrinkable Ix.Syntax where @@ -505,7 +505,7 @@ instance : Shrinkable Ix.Syntax where | .missing => [] | _ => [.missing] -instance : SampleableExt Ix.Syntax := SampleableExt.mkSelfContained genIxSyntax +instance : Sampleable Ix.Syntax := ⟨genIxSyntax⟩ -- Ix.DataValue already has genIxDataValue defined earlier instance : Shrinkable Ix.DataValue where @@ -513,7 +513,7 @@ instance : Shrinkable Ix.DataValue where | .ofBool _ => [] | _ => [.ofBool true] -instance : SampleableExt Ix.DataValue := SampleableExt.mkSelfContained genIxDataValue +instance : Sampleable Ix.DataValue := ⟨genIxDataValue⟩ end Tests.Gen.Ix diff --git a/Tests/Gen/Ixon.lean b/Tests/Gen/Ixon.lean index cfd977b7fd..3e88556e0b 100644 --- a/Tests/Gen/Ixon.lean +++ b/Tests/Gen/Ixon.lean @@ -11,7 +11,7 @@ public import Ix.Address public section -open LSpec SlimCheck Gen Ixon +open LSpec LSpec.Prop Gen Ixon open Ix (DefKind DefinitionSafety QuotKind) namespace Tests.Gen.Ixon @@ -22,7 +22,7 @@ namespace Tests.Gen.Ixon def genAddress : Gen Address := do let mut bytes : ByteArray := ByteArray.empty for _ in [:32] do - let b ← Gen.choose Nat 0 255 + let b ← Gen.chooseNat 0 255 bytes := bytes.push b.toUInt8 pure ⟨(Blake3.Rust.hash bytes).val⟩ @@ -35,19 +35,19 @@ def genList (n: Gen α) : Gen (List α) := def genUInt64Small : Gen UInt64 := USize.toUInt64 <$> genUSize def genDefKind : Gen DefKind := - elements #[.defn, .opaq, .thm] + Gen.elements! #[.defn, .opaq, .thm] def genDefinitionSafety : Gen DefinitionSafety := - elements #[.unsaf, .safe, .part] + Gen.elements! #[.unsaf, .safe, .part] def genQuotKindNew : Gen QuotKind := - elements #[.type, .ctor, .lift, .ind] + Gen.elements! #[.type, .ctor, .lift, .ind] def genBinderMode : Gen BinderMode := - elements #[.many, .borrowed, .unique, .uniqueBorrowed, .once, .onceBorrowed, .erased] + Gen.elements! #[.many, .borrowed, .unique, .uniqueBorrowed, .once, .onceBorrowed, .erased] def genResultMode : Gen ResultMode := - elements #[.shared, .borrowed, .unique, .uniqueBorrowed] + Gen.elements! #[.shared, .borrowed, .unique, .uniqueBorrowed] /-- A binder node's mode, the default most of the time. -/ def genAllMode : Gen AllMode := @@ -65,10 +65,10 @@ def genLetMode : Gen LetMode := ] def genDefAsserts : Gen DefAsserts := - DefAsserts.mk <$> elements #[AllocAssert.unrestricted, .noRc, .noAlloc] <*> genBool + DefAsserts.mk <$> Gen.elements! #[AllocAssert.unrestricted, .noRc, .noAlloc] <*> genBool def genFieldMode : Gen FieldMode := - elements #[.inherited, .shared] + Gen.elements! #[.inherited, .shared] /-- Field modes for a constructor with `n` fields: listed (one of them `shared`) for a few fields, otherwise inherited. -/ @@ -78,7 +78,7 @@ def genFieldModes (n : Nat) : Gen (FieldModes n) := do let mut modes : Array FieldMode := #[] for _ in [:n] do modes := modes.push (← genFieldMode) - let i ← Gen.choose Nat 0 (n - 1) + let i ← Gen.chooseNat 0 (n - 1) return FieldModes.ofArray (modes.set! i .shared) def genArray (g: Gen α) : Gen (Array α) := @@ -239,7 +239,7 @@ def genAxiom : Gen Axiom := .mk <$> genBool <*> genUInt64Small <*> genExpr def genQuotKind : Gen Lean.QuotKind := - elements #[.type, .ctor, .lift, .ind] + Gen.elements! #[.type, .ctor, .lift, .ind] def genQuotient : Gen Quotient := .mk <$> genQuotKindNew <*> genUInt64Small <*> genExpr @@ -278,7 +278,7 @@ def genInductive : Gen Inductive := def genBinderInfo : Gen Lean.BinderInfo := - elements #[.default, .implicit, .strictImplicit, .instImplicit] + Gen.elements! #[.default, .implicit, .strictImplicit, .instImplicit] def genReducibilityHints : Gen Lean.ReducibilityHints := frequency [ @@ -455,27 +455,27 @@ instance : Shrinkable DataValue where | .ofBool _ => [] | _ => [.ofBool true] -/-! ## SampleableExt instances -/ - -instance : SampleableExt DefKind := SampleableExt.mkSelfContained genDefKind -instance : SampleableExt DefinitionSafety := SampleableExt.mkSelfContained genDefinitionSafety -instance : SampleableExt QuotKind := SampleableExt.mkSelfContained genQuotKindNew -instance : SampleableExt Univ := SampleableExt.mkSelfContained genUniv -instance : SampleableExt Expr := SampleableExt.mkSelfContained genExpr -instance : SampleableExt Definition := SampleableExt.mkSelfContained genDefinition -instance : SampleableExt Axiom := SampleableExt.mkSelfContained genAxiom -instance : SampleableExt Quotient := SampleableExt.mkSelfContained genQuotient -instance : SampleableExt RecursorRule := SampleableExt.mkSelfContained genRecursorRule -instance : SampleableExt Recursor := SampleableExt.mkSelfContained genRecursor -instance : SampleableExt Constructor := SampleableExt.mkSelfContained genConstructor -instance : SampleableExt Inductive := SampleableExt.mkSelfContained genInductive -instance : SampleableExt InductiveProj := SampleableExt.mkSelfContained genInductiveProj -instance : SampleableExt ConstructorProj := SampleableExt.mkSelfContained genConstructorProj -instance : SampleableExt RecursorProj := SampleableExt.mkSelfContained genRecursorProj -instance : SampleableExt DefinitionProj := SampleableExt.mkSelfContained genDefinitionProj -instance : SampleableExt MutConst := SampleableExt.mkSelfContained genMutConst -instance : SampleableExt ConstantInfo := SampleableExt.mkSelfContained genConstantInfo -instance : SampleableExt Constant := SampleableExt.mkSelfContained genConstant +/-! ## Sampleable instances -/ + +instance : Sampleable DefKind := ⟨genDefKind⟩ +instance : Sampleable DefinitionSafety := ⟨genDefinitionSafety⟩ +instance : Sampleable QuotKind := ⟨genQuotKindNew⟩ +instance : Sampleable Univ := ⟨genUniv⟩ +instance : Sampleable Expr := ⟨genExpr⟩ +instance : Sampleable Definition := ⟨genDefinition⟩ +instance : Sampleable Axiom := ⟨genAxiom⟩ +instance : Sampleable Quotient := ⟨genQuotient⟩ +instance : Sampleable RecursorRule := ⟨genRecursorRule⟩ +instance : Sampleable Recursor := ⟨genRecursor⟩ +instance : Sampleable Constructor := ⟨genConstructor⟩ +instance : Sampleable Inductive := ⟨genInductive⟩ +instance : Sampleable InductiveProj := ⟨genInductiveProj⟩ +instance : Sampleable ConstructorProj := ⟨genConstructorProj⟩ +instance : Sampleable RecursorProj := ⟨genRecursorProj⟩ +instance : Sampleable DefinitionProj := ⟨genDefinitionProj⟩ +instance : Sampleable MutConst := ⟨genMutConst⟩ +instance : Sampleable ConstantInfo := ⟨genConstantInfo⟩ +instance : Sampleable Constant := ⟨genConstant⟩ /-! ## Generators for Metadata Types -/ @@ -490,7 +490,7 @@ def genDataValueNew : Gen DataValue := (10, .ofSyntax <$> genAddress), ] -instance : SampleableExt DataValue := SampleableExt.mkSelfContained genDataValueNew +instance : Sampleable DataValue := ⟨genDataValueNew⟩ /-! ## Generators for Constant Metadata Types -/ @@ -515,7 +515,7 @@ def genAuxLayout? : Gen (Option AuxLayout) := let c ← genSmallArray genUInt64Small let mut e : Array UInt64 := #[] for _ in [0:p.size] do - e := e.push (UInt64.ofNat (← Gen.choose Nat 0 1)) + e := e.push (UInt64.ofNat (← Gen.chooseNat 0 1)) pure (some { perm := p, sourceCtorCounts := c, evaporated := e })), ] @@ -526,7 +526,7 @@ def genExprMetaData (arenaSize : Nat := 0) (genAddr : Gen Address := genAddress) : Gen ExprMetaData := let genIdx : Gen UInt64 := if arenaSize == 0 then pure 0 - else UInt64.ofNat <$> Gen.choose Nat 0 (arenaSize - 1) + else UInt64.ofNat <$> Gen.chooseNat 0 (arenaSize - 1) frequency [ (20, pure .leaf), (15, ExprMetaData.app <$> genIdx <*> genIdx), @@ -552,7 +552,7 @@ where /-- Generate a valid ExprMetaArena by building nodes bottom-up so child indices always reference earlier entries. -/ def genExprMetaArena (genAddr : Gen Address := genAddress) : Gen ExprMetaArena := do - let numNodes ← Gen.choose Nat 0 6 + let numNodes ← Gen.chooseNat 0 6 let mut arena : ExprMetaArena := {} for _ in [:numNodes] do let node ← genExprMetaData arena.nodes.size genAddr @@ -564,7 +564,7 @@ def genConstantMetaInfo (genAddr : Gen Address := genAddress) : Gen ConstantMeta let arena ← genExprMetaArena genAddr let genRoot : Gen UInt64 := if arena.nodes.size == 0 then pure 0 - else UInt64.ofNat <$> Gen.choose Nat 0 (arena.nodes.size - 1) + else UInt64.ofNat <$> Gen.chooseNat 0 (arena.nodes.size - 1) frequency [ (10, pure .empty), (15, ConstantMetaInfo.defn <$> genAddr <*> genSmallArray genAddr @@ -627,14 +627,15 @@ instance : Shrinkable ConstantMeta where else [] | _ => [{ m with info := .empty }] -instance : SampleableExt AuxLayout := SampleableExt.mkSelfContained do +instance : Sampleable AuxLayout where + sample := do match ← genAuxLayout? with | some l => pure l | none => pure {} -instance : SampleableExt ExprMetaData := SampleableExt.mkSelfContained (genExprMetaData 5) -instance : SampleableExt ExprMetaArena := SampleableExt.mkSelfContained (genExprMetaArena) -instance : SampleableExt ConstantMetaInfo := SampleableExt.mkSelfContained (genConstantMetaInfo) -instance : SampleableExt ConstantMeta := SampleableExt.mkSelfContained (genConstantMeta) +instance : Sampleable ExprMetaData := ⟨(genExprMetaData 5)⟩ +instance : Sampleable ExprMetaArena := ⟨(genExprMetaArena)⟩ +instance : Sampleable ConstantMetaInfo := ⟨(genConstantMetaInfo)⟩ +instance : Sampleable ConstantMeta := ⟨(genConstantMeta)⟩ /-- Generate a Named entry with proper metadata. Exercises both `none` and `some (addr, meta)` for the `original` field @@ -664,17 +665,17 @@ instance : Shrinkable Named where instance : Shrinkable Comm where shrink _ := [] -instance : SampleableExt Named := SampleableExt.mkSelfContained genNamed -instance : SampleableExt Comm := SampleableExt.mkSelfContained genCommNew +instance : Sampleable Named := ⟨genNamed⟩ +instance : Sampleable Comm := ⟨genCommNew⟩ /-! ## Generators for RawEnv Types -/ /-- Generate a ByteArray for blobs -/ def genByteArray : Gen ByteArray := do - let len ← Gen.choose Nat 0 32 + let len ← Gen.chooseNat 0 32 let mut bytes : Array UInt8 := #[] for _ in [:len] do - let b ← Gen.choose Nat 0 255 + let b ← Gen.chooseNat 0 255 bytes := bytes.push b.toUInt8 pure (ByteArray.mk bytes) @@ -685,11 +686,11 @@ def genIxName : Nat → Gen Ix.Name (3, pure Ix.Name.mkAnon), (5, do let parent ← genIxName fuel - let s ← Gen.elements #["a", "b", "test", "foo", "bar"] + let s ← Gen.elements! #["a", "b", "test", "foo", "bar"] pure (Ix.Name.mkStr parent s)), (2, do let parent ← genIxName fuel - let n ← Gen.choose Nat 0 100 + let n ← Gen.chooseNat 0 100 pure (Ix.Name.mkNat parent n)) ] (pure Ix.Name.mkAnon) @@ -782,10 +783,10 @@ def genRawEnv : Gen RawEnv := do pool := nameComponentAddrs e.name pool for n in namedNames do pool := nameComponentAddrs n pool - let genPoolAddr : Gen Address := SlimCheck.Gen.elements pool + let genPoolAddr : Gen Address := Gen.elements! pool let mut named : Array RawNamed := #[] for name in namedNames do - let i ← Gen.choose Nat 0 (consts.size - 1) + let i ← Gen.chooseNat 0 (consts.size - 1) let addr := (consts[i % consts.size]!).addr let constMeta ← genConstantMeta genPoolAddr -- `original` stays a raw address on the wire (may reference an @@ -815,7 +816,7 @@ def genRawEnv : Gen RawEnv := do frequency [ (1, pure none), (1, do - let i ← Gen.choose Nat 0 (consts.size - 1) + let i ← Gen.chooseNat 0 (consts.size - 1) pure (consts[i % consts.size]?.map (·.addr))), ] else pure none @@ -824,7 +825,7 @@ def genRawEnv : Gen RawEnv := do let anonHints ← if consts.size > 0 then do let hintList ← genList do - let i ← Gen.choose Nat 0 (consts.size - 1) + let i ← Gen.chooseNat 0 (consts.size - 1) let h ← genReducibilityHints pure ((consts[i % consts.size]!).addr, h) pure (hintList.toArray.qsort fun a b => (compare a.1 b.1).isLT) @@ -875,11 +876,11 @@ instance : Shrinkable RawEnv where | some _ => [{ env with main := none }] | none => []) -instance : SampleableExt RawConst := SampleableExt.mkSelfContained genRawConst -instance : SampleableExt RawNamed := SampleableExt.mkSelfContained genRawNamed -instance : SampleableExt RawBlob := SampleableExt.mkSelfContained genRawBlob -instance : SampleableExt RawComm := SampleableExt.mkSelfContained genRawComm -instance : SampleableExt RawEnv := SampleableExt.mkSelfContained genRawEnv +instance : Sampleable RawConst := ⟨genRawConst⟩ +instance : Sampleable RawNamed := ⟨genRawNamed⟩ +instance : Sampleable RawBlob := ⟨genRawBlob⟩ +instance : Sampleable RawComm := ⟨genRawComm⟩ +instance : Sampleable RawEnv := ⟨genRawEnv⟩ end Tests.Gen.Ixon diff --git a/Tests/Gen/IxonSyntax.lean b/Tests/Gen/IxonSyntax.lean index 676b186e0f..9c8be78f71 100644 --- a/Tests/Gen/IxonSyntax.lean +++ b/Tests/Gen/IxonSyntax.lean @@ -20,7 +20,7 @@ public import Ix.IxonSyntax public section -open LSpec SlimCheck Gen Ixon.Syntax +open LSpec LSpec.Prop Gen Ixon.Syntax namespace Tests.Gen.IxonSyntax @@ -39,16 +39,16 @@ def strPool : Array String := "Except", "def", "weird name", "123", "max"] def genStrComponent : Gen NameComponent := - .str <$> elements strPool + .str <$> Gen.elements! strPool def genComponent : Gen NameComponent := frequency [ - (1, .num <$> choose Nat 0 999), + (1, .num <$> Gen.chooseNat 0 999), (4, genStrComponent) ] def genSName : Gen SName := do - let n ← choose Nat 0 2 + let n ← Gen.chooseNat 0 2 let mut parts := #[← genStrComponent] for _ in [0:n] do parts := parts.push (← genComponent) @@ -61,28 +61,28 @@ def hexChars : Array Char := def genHex (len : Nat) : Gen String := do let mut s := "" for _ in [0:len] do - s := s.push (← elements hexChars) + s := s.push (← Gen.elements! hexChars) return s def genHash : Gen HashRef := do - return { hex := ← genHex (4 + (← choose Nat 0 11)) } + return { hex := ← genHex (4 + (← Gen.chooseNat 0 11)) } /-- Universe variables: `Str` only; includes `"max"` (must print escaped in universe positions). -/ def genUvar : Gen NameComponent := - .str <$> elements #["u", "v", "w", "max", "weird name"] + .str <$> Gen.elements! #["u", "v", "w", "max", "weird name"] def genUniv : Nat → Gen UnivExpr | 0 => frequency [ - (1, (.nat · {}) <$> choose Nat 0 3), + (1, (.nat · {}) <$> Gen.chooseNat 0 3), (1, (.var · {}) <$> genUvar) ] | d + 1 => frequency [ - (1, (.nat · {}) <$> choose Nat 0 3), + (1, (.nat · {}) <$> Gen.chooseNat 0 3), (1, (.var · {}) <$> genUvar), - (1, do return .add (← genUniv d) (1 + (← choose Nat 0 2)) {}), + (1, do return .add (← genUniv d) (1 + (← Gen.chooseNat 0 2)) {}), (1, do return .max (← genUniv d) (← genUniv d) {}), (1, do return .imax (← genUniv d) (← genUniv d) {}) ] @@ -94,7 +94,7 @@ def genCref : Gen ConstRef := do else frequency [(1, some <$> genHash), (3, pure none)] let levels ← frequency [ (1, do - let n ← choose Nat 1 2 + let n ← Gen.chooseNat 1 2 let mut ls := #[] for _ in [0:n] do ls := ls.push (← genUniv 1) @@ -121,15 +121,15 @@ def genSort : Gen SortKind := pool. -/ def genLitString : Gen String := frequency [ - (3, elements #["", "hi", "line\nbreak", "q\"uote", "tab\there\\"]), + (3, Gen.elements! #["", "hi", "line\nbreak", "q\"uote", "tab\there\\"]), (1, do - let n ← choose Nat 0 12 + let n ← Gen.chooseNat 0 12 let mut s := "" for _ in [0:n] do let c ← frequency [ - (3, elements #['"', '\\', '\n', '\t', 'a', ' ', '«', '»', '¤']), - (2, Char.ofNat <$> choose Nat 0x20 0x7e), - (1, Char.ofNat <$> choose Nat 0xa0 0x2fff) + (3, Gen.elements! #['"', '\\', '\n', '\t', 'a', ' ', '«', '»', '¤']), + (2, Char.ofNat <$> Gen.chooseNat 0x20 0x7e), + (1, Char.ofNat <$> Gen.chooseNat 0xa0 0x2fff) ] s := s.push c pure s) @@ -137,29 +137,29 @@ def genLitString : Gen String := def genValueContract : Gen Ixon.ValueContract := do return { - owned := if (← choose Nat 0 1) == 0 then .unique else .shared - locality := if (← choose Nat 0 1) == 0 then .unrestricted else .local } + owned := if (← Gen.chooseNat 0 1) == 0 then .unique else .shared + locality := if (← Gen.chooseNat 0 1) == 0 then .unrestricted else .local } def genBinderContract : Gen Ixon.BinderContract := do - let uses ← elements #[Ixon.Uses.erased, .linear, .affine, .many] + let uses ← Gen.elements! #[Ixon.Uses.erased, .linear, .affine, .many] return { uses, value := ← genValueContract } def genLetContract : Gen Ixon.LetContract := do return { - nonDep := (← choose Nat 0 1) == 0 - kind := if (← choose Nat 0 1) == 0 then .value else .borrowShared + nonDep := (← Gen.chooseNat 0 1) == 0 + kind := if (← Gen.chooseNat 0 1) == 0 then .value else .borrowShared binder := ← genBinderContract } mutual partial def genBinder (depth : Nat) : Gen BinderGroup := do - let info ← elements #[Lean.BinderInfo.default, .implicit, + let info ← Gen.elements! #[Lean.BinderInfo.default, .implicit, .strictImplicit, .instImplicit] let names ← - if info == Lean.BinderInfo.instImplicit && (← choose Nat 0 1) == 0 then + if info == Lean.BinderInfo.instImplicit && (← Gen.chooseNat 0 1) == 0 then pure #[] else do - let n ← choose Nat 1 2 + let n ← Gen.chooseNat 1 2 let mut ns := #[] for _ in [0:n] do ns := ns.push (← genBinderName) @@ -169,7 +169,7 @@ partial def genBinder (depth : Nat) : Gen BinderGroup := do partial def genTerm (depth : Nat) : Gen Term := do if depth == 0 then frequency [ - (1, (.natLit · {}) <$> choose Nat 0 1000000), + (1, (.natLit · {}) <$> Gen.chooseNat 0 1000000), (1, (.strLit · {}) <$> genLitString), (1, (.sort · {}) <$> genSort), (3, .ref <$> genCref) @@ -179,19 +179,19 @@ partial def genTerm (depth : Nat) : Gen Term := do frequency [ (1, (.sort · {}) <$> genSort), (2, do - let n ← choose Nat 1 3 + let n ← Gen.chooseNat 1 3 let mut args := #[] for _ in [0:n] do args := args.push (← genTerm d) return .app (← genTerm d) args {}), (2, do - let n ← choose Nat 1 2 + let n ← Gen.chooseNat 1 2 let mut bs := #[] for _ in [0:n] do bs := bs.push (← genBinder d) return .lam bs (← genTerm d) {}), (1, do - let n ← choose Nat 1 2 + let n ← Gen.chooseNat 1 2 let mut bs := #[] for _ in [0:n] do bs := bs.push (← genBinder d) @@ -200,14 +200,14 @@ partial def genTerm (depth : Nat) : Gen Term := do (1, do return .letE (← genLetContract) (← genBinderName) (← genTerm d) (← genTerm d) (← genTerm d) {}), - (1, do return .proj (← genCref) (← choose Nat 0 7) (← genTerm d) {}), + (1, do return .proj (← genCref) (← Gen.chooseNat 0 7) (← genTerm d) {}), (1, .ref <$> genCref) ] end def genUParams : Gen (Array UParam) := do - let n ← choose Nat 0 2 + let n ← Gen.chooseNat 0 2 let mut out := #[] for _ in [0:n] do out := out.push { name := ← genUvar } @@ -218,85 +218,85 @@ def genName? : Gen (Option SName) := /-- The parser rejects `partial` on non-`def` and unsafe+partial. -/ def genModifiers (kw : DefKw) : Gen Modifiers := do - match ← choose Nat 0 3 with + match ← Gen.chooseNat 0 3 with | 0 => return { isUnsafe := true } | 1 => if kw == .defn then return { isPartial := true } else return {} | _ => return {} def genDefDecl (depth : Nat) : Gen DefDecl := do - let kw ← elements #[DefKw.defn, .thm, .opaq] + let kw ← Gen.elements! #[DefKw.defn, .thm, .opaq] return { kw, mods := ← genModifiers kw, name := ← genName? uparams := ← genUParams, ty := ← genTerm depth value := ← genTerm depth } def genIndDecl (depth : Nat) : Gen IndDecl := do - let nCtors ← choose Nat 0 2 + let nCtors ← Gen.chooseNat 0 2 let mut ctors := #[] for _ in [0:nCtors] do ctors := ctors.push - { name := ← genName?, params := ← choose Nat 0 3 - fields := ← choose Nat 0 3, ty := ← genTerm depth } - return { isUnsafe := (← choose Nat 0 1) == 0, name := ← genName? - uparams := ← genUParams, params := ← choose Nat 0 3 - indices := ← choose Nat 0 3, ty := ← genTerm depth, ctors } + { name := ← genName?, params := ← Gen.chooseNat 0 3 + fields := ← Gen.chooseNat 0 3, ty := ← genTerm depth } + return { isUnsafe := (← Gen.chooseNat 0 1) == 0, name := ← genName? + uparams := ← genUParams, params := ← Gen.chooseNat 0 3 + indices := ← Gen.chooseNat 0 3, ty := ← genTerm depth, ctors } def genRecrDecl (depth : Nat) : Gen RecrDecl := do - let nRules ← choose Nat 0 2 + let nRules ← Gen.chooseNat 0 2 let mut rules := #[] for _ in [0:nRules] do rules := rules.push - { fields := ← choose Nat 0 3, rhs := ← genTerm depth } - return { isUnsafe := (← choose Nat 0 1) == 0, name := ← genName? - uparams := ← genUParams, params := ← choose Nat 0 3 - indices := ← choose Nat 0 3, motives := 1 + (← choose Nat 0 1) - minors := ← choose Nat 0 3, k := (← choose Nat 0 1) == 0 + { fields := ← Gen.chooseNat 0 3, rhs := ← genTerm depth } + return { isUnsafe := (← Gen.chooseNat 0 1) == 0, name := ← genName? + uparams := ← genUParams, params := ← Gen.chooseNat 0 3 + indices := ← Gen.chooseNat 0 3, motives := 1 + (← Gen.chooseNat 0 1) + minors := ← Gen.chooseNat 0 3, k := (← Gen.chooseNat 0 1) == 0 ty := ← genTerm depth, rules } def genDecl (depth : Nat) : Gen Decl := do - match ← choose Nat 0 7 with + match ← Gen.chooseNat 0 7 with | 0 | 1 => .defn <$> genDefDecl depth | 2 => - return .axio { isUnsafe := (← choose Nat 0 1) == 0 + return .axio { isUnsafe := (← Gen.chooseNat 0 1) == 0 name := ← genName?, uparams := ← genUParams ty := ← genTerm depth } | 3 => - return .quot { kind := ← elements #[QuotKindKw.type, .ctor, .lift, .ind] + return .quot { kind := ← Gen.elements! #[QuotKindKw.type, .ctor, .lift, .ind] name := ← genName?, uparams := ← genUParams ty := ← genTerm depth } | 4 => .indc <$> genIndDecl depth | 5 => .recr <$> genRecrDecl depth | 6 => do - let n ← choose Nat 1 2 + let n ← Gen.chooseNat 1 2 let mut members := #[] for _ in [0:n] do - let m ← match ← choose Nat 0 2 with + let m ← match ← Gen.chooseNat 0 2 with | 0 => Decl.indc <$> genIndDecl depth | 1 => Decl.recr <$> genRecrDecl depth | _ => Decl.defn <$> genDefDecl depth members := members.push m return .muts members {} | _ => do - let kind ← elements #[PrjKind.dprj, .iprj, .cprj, .rprj] + let kind ← Gen.elements! #[PrjKind.dprj, .iprj, .cprj, .rprj] let cidx ← - if kind == .cprj then some <$> choose Nat 0 7 else pure none + if kind == .cprj then some <$> Gen.chooseNat 0 7 else pure none return .prj { kind, name := ← genName?, block := ← genHash - idx := ← choose Nat 0 7, cidx } + idx := ← Gen.chooseNat 0 7, cidx } def genImport : Gen ImportDecl := do return { prefixName := ← frequency [(1, some <$> genSName), (1, pure none)] hash := { hex := ← genHex 64 } } def genFile : Gen File := do - let nImports ← choose Nat 0 2 + let nImports ← Gen.chooseNat 0 2 let mut imports := #[] for _ in [0:nImports] do imports := imports.push (← genImport) - let nDecls ← choose Nat 0 3 + let nDecls ← Gen.chooseNat 0 3 let mut decls := #[] for _ in [0:nDecls] do decls := decls.push (← genDecl 2) let main ← - if (← choose Nat 0 2) == 0 then + if (← Gen.chooseNat 0 2) == 0 then pure (some { value := ← genTerm 2, ty := ← genTerm 2 : MainExpr }) else pure none return { version := VERSION, imports, decls, main } @@ -383,13 +383,11 @@ instance : Shrinkable File where out := out ++ [{ f with decls := f.decls.set! i s }] return out -/-! ## SampleableExt instances -/ +/-! ## Sampleable instances -/ -instance : SampleableExt Term := - SampleableExt.mkSelfContained (genTerm 4) +instance : Sampleable Term := ⟨(genTerm 4)⟩ -instance : SampleableExt File := - SampleableExt.mkSelfContained genFile +instance : Sampleable File := ⟨genFile⟩ /-- Fuzz input: strings biased toward syntax-relevant characters (delimiters, escapes, digits, unicode) — a sharper boundary walk @@ -404,13 +402,13 @@ def fuzzChars : Array Char := 'a', 'x', 'f', '0', '1', '9', 'α', 'd', 'e', 'u', 'n', '-', '/'] def genFuzz : Gen Fuzz := do - let n ← choose Nat 0 60 + let n ← Gen.chooseNat 0 60 let mut s := "" for _ in [0:n] do let c ← frequency [ - (6, elements fuzzChars), - (1, Char.ofNat <$> choose Nat 0x20 0x7e), - (1, Char.ofNat <$> choose Nat 0xa0 0x2fff) + (6, Gen.elements! fuzzChars), + (1, Char.ofNat <$> Gen.chooseNat 0x20 0x7e), + (1, Char.ofNat <$> Gen.chooseNat 0xa0 0x2fff) ] s := s.push c return ⟨s⟩ @@ -424,7 +422,7 @@ instance : Shrinkable Fuzz where ⟨String.ofList (l.drop (l.length / 2))⟩, ⟨String.ofList l.tail⟩] -instance : SampleableExt Fuzz := SampleableExt.mkSelfContained genFuzz +instance : Sampleable Fuzz := ⟨genFuzz⟩ /-- A batch of (position, pool-index) char mutations for the near-valid fuzz property. -/ @@ -433,15 +431,15 @@ structure Muts where deriving Repr, Inhabited def genMuts : Gen Muts := do - let n ← choose Nat 0 6 + let n ← Gen.chooseNat 0 6 let mut out : List (Nat × Nat) := [] for _ in [0:n] do - out := (← choose Nat 0 100000, ← choose Nat 0 1000) :: out + out := (← Gen.chooseNat 0 100000, ← Gen.chooseNat 0 1000) :: out return ⟨out⟩ instance : Shrinkable Muts where shrink m := if m.muts.isEmpty then [] else [⟨m.muts.tail⟩] -instance : SampleableExt Muts := SampleableExt.mkSelfContained genMuts +instance : Sampleable Muts := ⟨genMuts⟩ end Tests.Gen.IxonSyntax diff --git a/Tests/Ix/AiurStatistics.lean b/Tests/Ix/AiurStatistics.lean index 26ba43c03b..1ec96facf9 100644 --- a/Tests/Ix/AiurStatistics.lean +++ b/Tests/Ix/AiurStatistics.lean @@ -6,6 +6,8 @@ public section namespace Tests.Ix.AiurStatistics open Aiur LSpec Lean +set_option compiler.extract_closed false + private def shape : CircuitShape := { mainWidth := 3, stage2Width := 3, quotientDegree := 2, preprocessedWidth := 100, preprocessedHeight := 0 } @@ -23,37 +25,41 @@ private def raw (c : Json) (degree : Nat := 3) : Json := Json.mkObj [ ("log_blowup", toJson (2 : Nat)), ("extension_degree", toJson degree), ("circuits", .arr #[c])] -def suite : List TestSeq := [ - AiurTests.Cost.tests, - let stats := computeStats { logBlowup := 2, circuits := #[measurement "small" 1 3, measurement "large" 4 0] } - test "cached and uncached totals use the same model" - (stats.roundedFftCost == 780 && stats.totalUncachedFftCost == 1392.0 && stats.totalCacheHits == 3) - ++ test "display ranks circuits by cost" (stats.circuits[0]!.name == "large"), - test "decode real host field names" +def suite : LSpec.Spec := do + AiurTests.Cost.tests + it "cached and uncached totals use the same model" do + let stats := computeStats { logBlowup := 2, circuits := #[measurement "small" 1 3, measurement "large" 4 0] } + expect (stats.roundedFftCost == 780 && stats.totalUncachedFftCost == 1392.0 && stats.totalCacheHits == 3) + it "display ranks circuits by cost" do + let stats := computeStats { logBlowup := 2, circuits := #[measurement "small" 1 3, measurement "large" 4 0] } + expect (stats.circuits[0]!.name == "large") + itBool "decode real host field names" ((ExecutionMeasurements.fromJson (raw (rawCircuit 3 2 0))).toOption.any fun m => m.circuits.size == 1 && m.circuits[0]!.height == 3 && m.circuits[0]!.cacheHits == 2) - ++ test "fixed tables keep their full height" + itBool "fixed tables keep their full height" ((ExecutionMeasurements.fromJson (raw (rawCircuit 4 0 4))).isOk) - ++ test "reject truncated fixed tables" + itBool "reject truncated fixed tables" ((ExecutionMeasurements.fromJson (raw (rawCircuit 3 0 4))).toOption.isNone) - ++ test "reject cache savings on fixed tables" + itBool "reject cache savings on fixed tables" ((ExecutionMeasurements.fromJson (raw (rawCircuit 4 1 4))).toOption.isNone) - ++ test "reject missing counts" + itBool "reject missing counts" ((ExecutionMeasurements.fromJson (raw (Json.mkObj []))).toOption.isNone) - ++ test "reject an incompatible extension degree" - ((ExecutionMeasurements.fromJson (raw (rawCircuit 4 0 0) 2)).toOption.isNone), - let report := Json.mkObj [("execution_statistics", raw (rawCircuit 4 0 0)), - ("verified", toJson true)] - let enriched := enrichExecutionReport report - test "benchmark reports contain Lean-computed FFT costs" - ((enriched >>= (·.getObjValAs? Nat "fft-cost")).toOption == some 696) - ++ test "keep existing report fields" - ((enriched >>= (·.getObjValAs? Bool "verified")).toOption == some true) - ++ test "a missing execution does not fabricate zero cost" + itBool "reject an incompatible extension degree" + ((ExecutionMeasurements.fromJson (raw (rawCircuit 4 0 0) 2)).toOption.isNone) + it "benchmark reports contain Lean-computed FFT costs" do + let report := Json.mkObj [("execution_statistics", raw (rawCircuit 4 0 0)), + ("verified", toJson true)] + let enriched := enrichExecutionReport report + expect ((enriched >>= (·.getObjValAs? Nat "fft-cost")).toOption == some 696) + it "keep existing report fields" do + let report := Json.mkObj [("execution_statistics", raw (rawCircuit 4 0 0)), + ("verified", toJson true)] + let enriched := enrichExecutionReport report + expect ((enriched >>= (·.getObjValAs? Bool "verified")).toOption == some true) + itBool "a missing execution does not fabricate zero cost" (((enrichExecutionReport (Json.mkObj [])) >>= (·.getObjVal? "fft-cost")).toOption.isNone) - ++ test "malformed measurements fail the report" + itBool "malformed measurements fail the report" ((enrichExecutionReport (Json.mkObj [("execution_statistics", .null)])).toOption.isNone) -] end Tests.Ix.AiurStatistics end diff --git a/Tests/Ix/AssumptionTree.lean b/Tests/Ix/AssumptionTree.lean index 1a403f53b9..fb7aac36bf 100644 --- a/Tests/Ix/AssumptionTree.lean +++ b/Tests/Ix/AssumptionTree.lean @@ -11,6 +11,8 @@ open Ix.AssumptionTree open Ix.Merkle (merkleRootCanonical merkleJoin verifyMerkleProof) open Ixon (runGet) +set_option compiler.extract_closed false + private def addr (s : String) : Address := Address.blake3 s.toUTF8 /-! ## Canonical construction -/ @@ -20,65 +22,70 @@ private partial def hasPad : Ix.AssumptionTree → Bool | .leaf _ => false | .node l r => hasPad l || hasPad r -private def canonicalUnits : TestSeq := - let a := addr "a" - let b := addr "b" - let c := addr "c" - test "canonical of empty is none" ((Ix.AssumptionTree.canonical #[]) == none) - ++ test "canonical of single leaf" - ((Ix.AssumptionTree.canonical #[a]) == some (.leaf a)) - ++ test "canonical of three leaves contains padding" - (let t := (Ix.AssumptionTree.canonical #[a, b, c]).get! - hasPad t) +private def canonicalUnits : LSpec.Spec := do + itBool "canonical of empty is none" ((Ix.AssumptionTree.canonical #[]) == none) + itBool "canonical of single leaf" + (let a := addr "a"; (Ix.AssumptionTree.canonical #[a]) == some (.leaf a)) + itBool "canonical of three leaves contains padding" + (let a := addr "a"; let b := addr "b"; let c := addr "c" + let t := (Ix.AssumptionTree.canonical #[a, b, c]).get! + hasPad t) /-! ## Root agreement with `merkleRootCanonical` -/ -private def rootAgreementUnits : TestSeq := +private def rootAgreementUnits : LSpec.Spec := do let mkLeaves (n : Nat) : Array Address := Array.range n |>.map fun i => addr s!"leaf-{i}" let check (n : Nat) : Bool := let leaves := mkLeaves n let t := (Ix.AssumptionTree.canonical leaves).get! some t.root == merkleRootCanonical leaves - test "root matches merkleRootCanonical for n=1" (check 1) - ++ test "root matches merkleRootCanonical for n=2" (check 2) - ++ test "root matches merkleRootCanonical for n=3" (check 3) - ++ test "root matches merkleRootCanonical for n=4" (check 4) - ++ test "root matches merkleRootCanonical for n=5" (check 5) - ++ test "root matches merkleRootCanonical for n=7" (check 7) - ++ test "root matches merkleRootCanonical for n=8" (check 8) + itBool "root matches merkleRootCanonical for n=1" (check 1) + itBool "root matches merkleRootCanonical for n=2" (check 2) + itBool "root matches merkleRootCanonical for n=3" (check 3) + itBool "root matches merkleRootCanonical for n=4" (check 4) + itBool "root matches merkleRootCanonical for n=5" (check 5) + itBool "root matches merkleRootCanonical for n=7" (check 7) + itBool "root matches merkleRootCanonical for n=8" (check 8) /-! ## Join agreement -/ -private def joinUnits : TestSeq := - let a := addr "a" - let b := addr "b" - let l := (Ix.AssumptionTree.canonical #[a]).get! - let r := (Ix.AssumptionTree.canonical #[b]).get! - let joined := Ix.AssumptionTree.join l r - test "join root matches merkleJoin" - (joined.root == merkleJoin l.root r.root) +private def joinUnits : LSpec.Spec := do + it "join root matches merkleJoin" do + let a := addr "a" + let b := addr "b" + let l := (Ix.AssumptionTree.canonical #[a]).get! + let r := (Ix.AssumptionTree.canonical #[b]).get! + let joined := Ix.AssumptionTree.join l r + expect (joined.root == merkleJoin l.root r.root) /-! ## Leaves + contains -/ -private def leavesUnits : TestSeq := - let a := addr "a" - let b := addr "b" - let c := addr "c" - let absent := addr "absent" - let t := (Ix.AssumptionTree.canonical #[a, b, c]).get! - -- Sorted leaves. - let sorted := (#[a, b, c]).qsort fun a b => compare a b == .lt - test "leaves skip padding and yield sorted set" - (t.leaves == sorted) - ++ test "contains true for members" - (t.contains a && t.contains b && t.contains c) - ++ test "contains false for nonmember" - (!t.contains absent) +private def leavesUnits : LSpec.Spec := do + it "leaves skip padding and yield sorted set" do + let a := addr "a" + let b := addr "b" + let c := addr "c" + let t := (Ix.AssumptionTree.canonical #[a, b, c]).get! + let sorted := (#[a, b, c]).qsort fun a b => compare a b == .lt + expect (t.leaves == sorted) + it "contains true for members" do + let a := addr "a" + let b := addr "b" + let c := addr "c" + let t := (Ix.AssumptionTree.canonical #[a, b, c]).get! + expect (t.contains a && t.contains b && t.contains c) + it "contains false for nonmember" do + let a := addr "a" + let b := addr "b" + let c := addr "c" + let absent := addr "absent" + let t := (Ix.AssumptionTree.canonical #[a, b, c]).get! + expect (!t.contains absent) /-! ## Merkle proofs -/ -private def merkleProofUnits : TestSeq := +private def merkleProofUnits : LSpec.Spec := do let mkLeaves (n : Nat) : Array Address := Array.range n |>.map fun i => addr s!"leaf-{i}" let checkAll (n : Nat) : Bool := @@ -89,21 +96,20 @@ private def merkleProofUnits : TestSeq := match t.merkleProof leaf with | none => false | some path => verifyMerkleProof root leaf path - test "single-leaf empty path verifies" + itBool "single-leaf empty path verifies" (let a := addr "x" let t : Ix.AssumptionTree := .leaf a - let ok : Bool := match t.merkleProof a with - | some path => path.isEmpty && verifyMerkleProof t.root a path - | none => false - ok) - ++ test "all leaves prove for n=2" (checkAll 2) - ++ test "all leaves prove for n=3" (checkAll 3) - ++ test "all leaves prove for n=5" (checkAll 5) - ++ test "all leaves prove for n=8" (checkAll 8) - ++ test "nonmember returns none" - (let leaves := mkLeaves 3 - let t := (Ix.AssumptionTree.canonical leaves).get! - t.merkleProof (addr "absent") == none) + match t.merkleProof a with + | some path => path.isEmpty && verifyMerkleProof t.root a path + | none => false) + itBool "all leaves prove for n=2" (checkAll 2) + itBool "all leaves prove for n=3" (checkAll 3) + itBool "all leaves prove for n=5" (checkAll 5) + itBool "all leaves prove for n=8" (checkAll 8) + itBool "nonmember returns none" + (let leaves := mkLeaves 3 + let t := (Ix.AssumptionTree.canonical leaves).get! + t.merkleProof (addr "absent") == none) /-! ## Serialization -/ @@ -113,40 +119,33 @@ private def serdeRoundtrip (t : Ix.AssumptionTree) : Bool := | .ok t' => t == t' | .error _ => false -private def serdeUnits : TestSeq := - let a := addr "a" - let b := addr "b" - let leaf := Ix.AssumptionTree.leaf a - let pad := Ix.AssumptionTree.padding - let nodeLeaves := - Ix.AssumptionTree.node (Ix.AssumptionTree.leaf a) (Ix.AssumptionTree.leaf b) - let canon := (Ix.AssumptionTree.canonical #[a, b, addr "c"]).get! - -- Outer tag byte - let leafBytes := Ix.AssumptionTree.ser leaf - let padBytes := Ix.AssumptionTree.ser pad - let nodeBytes := Ix.AssumptionTree.ser nodeLeaves - test "outer tag byte is 0xE2 (Leaf)" (leafBytes.data[0]! == 0xE2) - ++ test "outer tag byte is 0xE2 (Padding)" (padBytes.data[0]! == 0xE2) - ++ test "outer tag byte is 0xE2 (Node)" (nodeBytes.data[0]! == 0xE2) - ++ test "Leaf body tag is 0x00" (leafBytes.data[1]! == 0x00) - ++ test "Padding body tag is 0x01" (padBytes.data[1]! == 0x01) - ++ test "Node body tag is 0x02" (nodeBytes.data[1]! == 0x02) - ++ test "Leaf total bytes" (leafBytes.size == 1 + 1 + 32) - ++ test "Padding total bytes" (padBytes.size == 2) - ++ test "Node total bytes" (nodeBytes.size == 1 + 1 + (1 + 32) + (1 + 32)) +private def serdeUnits : LSpec.Spec := do + let mkLeaf := fun () => Ix.AssumptionTree.leaf (addr "a") + let mkPad := fun () => Ix.AssumptionTree.padding + let mkNode := fun () => + Ix.AssumptionTree.node (Ix.AssumptionTree.leaf (addr "a")) (Ix.AssumptionTree.leaf (addr "b")) + let mkCanon := fun () => (Ix.AssumptionTree.canonical #[addr "a", addr "b", addr "c"]).get! + itBool "outer tag byte is 0xE2 (Leaf)" ((Ix.AssumptionTree.ser (mkLeaf ())).data[0]! == 0xE2) + itBool "outer tag byte is 0xE2 (Padding)" ((Ix.AssumptionTree.ser (mkPad ())).data[0]! == 0xE2) + itBool "outer tag byte is 0xE2 (Node)" ((Ix.AssumptionTree.ser (mkNode ())).data[0]! == 0xE2) + itBool "Leaf body tag is 0x00" ((Ix.AssumptionTree.ser (mkLeaf ())).data[1]! == 0x00) + itBool "Padding body tag is 0x01" ((Ix.AssumptionTree.ser (mkPad ())).data[1]! == 0x01) + itBool "Node body tag is 0x02" ((Ix.AssumptionTree.ser (mkNode ())).data[1]! == 0x02) + itBool "Leaf total bytes" ((Ix.AssumptionTree.ser (mkLeaf ())).size == 1 + 1 + 32) + itBool "Padding total bytes" ((Ix.AssumptionTree.ser (mkPad ())).size == 2) + itBool "Node total bytes" ((Ix.AssumptionTree.ser (mkNode ())).size == 1 + 1 + (1 + 32) + (1 + 32)) -- Roundtrips - ++ test "roundtrip Leaf" (serdeRoundtrip leaf) - ++ test "roundtrip Padding" (serdeRoundtrip pad) - ++ test "roundtrip Node simple" (serdeRoundtrip nodeLeaves) - ++ test "roundtrip canonical n=3" (serdeRoundtrip canon) + itBool "roundtrip Leaf" (serdeRoundtrip (mkLeaf ())) + itBool "roundtrip Padding" (serdeRoundtrip (mkPad ())) + itBool "roundtrip Node simple" (serdeRoundtrip (mkNode ())) + itBool "roundtrip canonical n=3" (serdeRoundtrip (mkCanon ())) /-! ## Suite -/ -public def Tests.AssumptionTree.suite : List TestSeq := [ - canonicalUnits, - rootAgreementUnits, - joinUnits, - leavesUnits, - merkleProofUnits, - serdeUnits, -] +public def Tests.AssumptionTree.suite : LSpec.Spec := do + canonicalUnits + rootAgreementUnits + joinUnits + leavesUnits + merkleProofUnits + serdeUnits diff --git a/Tests/Ix/BenchMeasures.lean b/Tests/Ix/BenchMeasures.lean index d2c6b65cab..5dc944994a 100644 --- a/Tests/Ix/BenchMeasures.lean +++ b/Tests/Ix/BenchMeasures.lean @@ -15,6 +15,8 @@ public section open LSpec Ix.Cli.BenchCmd +set_option compiler.extract_closed false + namespace Tests.Ix.BenchMeasures def envNames : Array String := (envSpecs.map (·.name)).toArray @@ -22,30 +24,30 @@ def envNames : Array String := (envSpecs.map (·.name)).toArray def constantNames : Array String := Ix.BenchConstants.benchConstants.map (·.name) -def testRows : TestSeq := - test "every shared constant's env is a registry env" +def testRows : LSpec.Spec := do + itBool "every shared constant's env is a registry env" (Ix.BenchConstants.benchConstants.all (envNames.contains ·.env)) - ++ test "every backend has env rows" + itBool "every backend has env rows" (backendSpecs.all (!·.envMetrics.isEmpty)) - ++ test "an env-row measure plots every env" + itBool "an env-row measure plots every env" (backendSpecs.all fun b => b.envMetrics.all fun m => envNames.all (b.benchmarkNames m).contains) - ++ test "a constant-row measure plots every shared constant" + itBool "a constant-row measure plots every shared constant" (backendSpecs.all fun b => b.constantMetrics.all fun m => constantNames.all (b.benchmarkNames m).contains) - ++ test "a measure no row kind carries plots nothing" + itBool "a measure no row kind carries plots nothing" (backendSpecs.all fun b => (b.benchmarkNames "no-such-measure").isEmpty) - ++ test "ixvm and ixvm-ooc have constant rows" + itBool "ixvm and ixvm-ooc have constant rows" (["ixvm", "ixvm-ooc"].all fun n => ((findBackend n).map (·.hasConstants)).getD false) - ++ test "compile and decompile have only env rows" + itBool "compile and decompile have only env rows" (["compile", "decompile"].all fun n => ((findBackend n).map (!·.hasConstants)).getD false) - ++ test "stage measures plot the row kinds that support them" + itBool "stage measures plot the row kinds that support them" (backendSpecs.all fun b => b.stages.all fun (_, ms) => ms.all fun m => b.benchmarkNames m == constantNames ++ (if b.envStages.any (·.2.contains m) then envNames else #[])) - ++ test "stage measures are tracked" + itBool "stage measures are tracked" (backendSpecs.all fun b => (b.stages ++ b.envStages).all fun (_, ms) => ms.all b.trackedMetrics.contains) - ++ test "backend testbeds are distinct" + itBool "backend testbeds are distinct" ((backendSpecs.map (·.testbed)).eraseDups.length == backendSpecs.length) /-- Results rows: each `(name, fields)` is one row of numeric fields, with @@ -58,176 +60,180 @@ def rowsOf (rows : List (String × List (String × Nat)) ) (status : List (Strin (name, Lean.Json.mkObj (base ++ extra)) open Ix.Cli.BenchReport in -def testCells : TestSeq := +def testCells : LSpec.Spec := do let cell := fun (b p : Nat) (metric : String) => metricCells (rowsOf [("Nat.add_comm", [(metric, b)])]) (rowsOf [("Nat.add_comm", [(metric, p)])]) "Nat.add_comm" metric 3.0 - test "a slower run past 3% is a regression" + itBool "a slower run past 3% is a regression" (let (text, bad, good) := cell 100 110 "check-time" text == #["1m 40.0s", "1m 50.0s", "+10.0% (1.10× slower) ⚠️"] && bad && !good) - ++ test "a faster run past 3% is an improvement" + itBool "a faster run past 3% is an improvement" (let (text, bad, good) := cell 100 96 "check-time" text[2]! == "-4.0% 🟢" && !bad && good) - ++ test "a change within 3% is unmarked" + itBool "a change within 3% is unmarked" (let (text, bad, good) := cell 100 102 "check-time" text[2]! == "+2.0%" && !bad && !good) - ++ test "a change of 5% or more names its factor in the metric's terms" + itBool "a change of 5% or more names its factor in the metric's terms" ((cell 100 50 "check-time").1[2]! == "-50.0% (2.00× faster) 🟢" && (metricCells (rowsOf [("Nat.add_comm", [("prove-proof-size", 100)])]) (rowsOf [("Nat.add_comm", [("prove-proof-size", 120)])]) "Nat.add_comm" "prove-proof-size" 3.0).1[2]! == "+20.0% (1.20× larger) ⚠️") - ++ test "trace shards render as counts and more of them is a regression" + itBool "trace shards render as counts and more of them is a regression" ((metricCells (rowsOf [("Nat.add_comm", [("prove-trace-shards", 4)])]) (rowsOf [("Nat.add_comm", [("prove-trace-shards", 6)])]) "Nat.add_comm" "prove-trace-shards" 3.0).1 == #["4", "6", "+50.0% (1.50× more) ⚠️"]) - ++ test "higher throughput is an improvement" + itBool "higher throughput is an improvement" ((cell 100 110 "throughput").2.2) - ++ test "a rejected row renders ❌" + itBool "a rejected row renders ❌" ((metricCells (rowsOf [("Nat.add_comm", [("check-time", 1)])]) (rowsOf [("Nat.add_comm", [])] [("Nat.add_comm", "rejected")]) "Nat.add_comm" "check-time" 3.0).1 == #["1.000 s", "❌", "n/a"]) - ++ test "a crashed row renders a generic failure" + itBool "a crashed row renders a generic failure" ((metricCells (rowsOf [("Nat.add_comm", [("check-time", 1)])]) (rowsOf [("Nat.add_comm", [])] [("Nat.add_comm", "crash")]) "Nat.add_comm" "check-time" 3.0).1 == #["1.000 s", "❌ failed", "n/a"]) - ++ test "an OOM row keeps its measured stages and marks the ones it lost" + itBool "an OOM row keeps its measured stages and marks the ones it lost" (let base := rowsOf [("Nat.add_comm", [("execute-time", 1), ("prove-time", 30)])] let pr := rowsOf [("Nat.add_comm", [("execute-time", 1)])] [("Nat.add_comm", "oom")] (metricCells base pr "Nat.add_comm" "execute-time" 3.0).1[2]! == "+0.0%" && (metricCells base pr "Nat.add_comm" "prove-time" 3.0).1 == #["30.000 s", "❌ OOM", "n/a"]) - ++ test "the env row leads, then its constants in registry order" + itBool "the env row leads, then its constants in registry order" ({ backend := "ixvm", env := "InitStd" base := rowsOf [("Std.HashMap", []), ("InitStd", []), ("Nat.add_comm", [])] : Cell }.rows == #[("InitStd", true), ("Nat.add_comm", false), ("Std.HashMap", false)]) - ++ test "constants without an env row get no env label row" + itBool "constants without an env row get no env label row" ({ backend := "ixvm", env := "InitStd", pr := rowsOf [("Nat.add_comm", [])] : Cell }.rows == #[("Nat.add_comm", false)]) open Ix.Cli.BenchReport in -def testReport : TestSeq := .individualIO "ixvm report: an env table, then a constant table, stages on demand" none (do - let some spec := findBackend "ixvm" | return (false, 0, 0, none) - let base := rowsOf [("InitStd", [("execute-time", 40)]), ("Nat.add_comm", [("execute-time", 1)])] - let pr := rowsOf [("InitStd", [("execute-time", 41)]), ("Nat.add_comm", [("execute-time", 1)])] - let plain ← renderBackend spec #[{ backend := "ixvm", env := "InitStd", base, pr }] 3.0 "main" - let lines := plain.splitOn "\n" - let envAt := lines.findIdx? (·.startsWith "| InitStd |") - let constAt := lines.findIdx? (·.startsWith "| `Nat.add_comm` |") - let envHead := lines.findIdx? (· == "#### `ixvm` · envs") - let constHead := lines.findIdx? (· == "#### `ixvm` · constants") - let proved := rowsOf [("Nat.add_comm", [("execute-time", 1), ("prove-time", 30)])] - let staged ← renderBackend spec - #[{ backend := "ixvm", env := "InitStd", base := proved, pr := proved }] 3.0 "main" - let whole := rowsOf [("Init", [("prove-time", 30), ("e2e-time", 40)])] - let envStages ← renderBackend spec - #[{ backend := "ixvm", env := "Init", base := whole, pr := whole }] 3.0 "main" - let ok := plain.startsWith "### `ixvm`" - && (match envHead, envAt, constHead, constAt with - | some eh, some e, some ch, some c => eh < e && e < ch && ch < c - | _, _, _, _ => false) - && (plain.splitOn "| env | execute-time (main)").length == 2 - && (plain.splitOn "| constant | execute-time (main)").length == 2 - && (plain.splitOn "· prove").length == 1 - && (staged.splitOn "#### `ixvm` · prove").length == 2 - && (staged.splitOn "| constant | prove-time (main) | prove-time (PR) | Δ% |\n").length == 2 - && (plain.splitOn "check-time").length == 1 - && (envStages.splitOn "#### `ixvm` · env prove").length == 2 - && (envStages.splitOn "#### `ixvm` · env e2e").length == 2 - && (envStages.splitOn "| env | prove-time (main)").length == 2 - return (ok, 0, 0, if ok then none else some plain)) .done +def testReport : LSpec.Spec := do + it "ixvm report: an env table, then a constant table, stages on demand" do + let some spec := findBackend "ixvm" | fail "missing ixvm backend" + let base := rowsOf [("InitStd", [("execute-time", 40)]), ("Nat.add_comm", [("execute-time", 1)])] + let pr := rowsOf [("InitStd", [("execute-time", 41)]), ("Nat.add_comm", [("execute-time", 1)])] + let plain ← renderBackend spec #[{ backend := "ixvm", env := "InitStd", base, pr }] 3.0 "main" + let lines := plain.splitOn "\n" + let envAt := lines.findIdx? (·.startsWith "| InitStd |") + let constAt := lines.findIdx? (·.startsWith "| `Nat.add_comm` |") + let envHead := lines.findIdx? (· == "#### `ixvm` · envs") + let constHead := lines.findIdx? (· == "#### `ixvm` · constants") + let proved := rowsOf [("Nat.add_comm", [("execute-time", 1), ("prove-time", 30)])] + let staged ← renderBackend spec + #[{ backend := "ixvm", env := "InitStd", base := proved, pr := proved }] 3.0 "main" + let whole := rowsOf [("Init", [("prove-time", 30), ("e2e-time", 40)])] + let envStages ← renderBackend spec + #[{ backend := "ixvm", env := "Init", base := whole, pr := whole }] 3.0 "main" + let ok := plain.startsWith "### `ixvm`" + && (match envHead, envAt, constHead, constAt with + | some eh, some e, some ch, some c => eh < e && e < ch && ch < c + | _, _, _, _ => false) + && (plain.splitOn "| env | execute-time (main)").length == 2 + && (plain.splitOn "| constant | execute-time (main)").length == 2 + && (plain.splitOn "· prove").length == 1 + && (staged.splitOn "#### `ixvm` · prove").length == 2 + && (staged.splitOn "| constant | prove-time (main) | prove-time (PR) | Δ% |\n").length == 2 + && (plain.splitOn "check-time").length == 1 + && (envStages.splitOn "#### `ixvm` · env prove").length == 2 + && (envStages.splitOn "#### `ixvm` · env e2e").length == 2 + && (envStages.splitOn "| env | prove-time (main)").length == 2 + expect ok plain open Ix.Cli.BenchReport in -def testFftCost : TestSeq := .individualIO "ixvm tables show the FFT cost on both row kinds" none (do - let some spec := findBackend "ixvm" | return (false, 0, 0, none) - let rows := fun (env c : Nat) => rowsOf [ - ("InitStd", [("execute-time", 40), ("peak-rss", 1), ("shards", 12), ("fft-cost", env)]), - ("Nat.add_comm", [("execute-time", 1), ("peak-rss", 1), ("fft-cost", c)])] - let text ← renderBackend spec - #[{ backend := "ixvm", env := "InitStd", base := rows 100000000000 390000000, pr := rows 100000000000 400000000 }] - 3.0 "main" - let ok := (text.splitOn "| env-shards (main) | env-shards (PR) | Δ% | fft-cost (main) |").length == 2 - && (text.splitOn "| `Nat.add_comm` | 1.000 s | 1.000 s | +0.0% | 1 B | 1 B | +0.0% | 390.00M | 400.00M | +2.6% |").length == 2 - return (ok, 0, 0, if ok then none else some text)) .done +def testFftCost : LSpec.Spec := do + it "ixvm tables show the FFT cost on both row kinds" do + let some spec := findBackend "ixvm" | fail "missing ixvm backend" + let rows := fun (env c : Nat) => rowsOf [ + ("InitStd", [("execute-time", 40), ("peak-rss", 1), ("shards", 12), ("fft-cost", env)]), + ("Nat.add_comm", [("execute-time", 1), ("peak-rss", 1), ("fft-cost", c)])] + let text ← renderBackend spec + #[{ backend := "ixvm", env := "InitStd", base := rows 100000000000 390000000, pr := rows 100000000000 400000000 }] + 3.0 "main" + let ok := (text.splitOn "| env-shards (main) | env-shards (PR) | Δ% | fft-cost (main) |").length == 2 + && (text.splitOn "| `Nat.add_comm` | 1.000 s | 1.000 s | +0.0% | 1 B | 1 B | +0.0% | 390.00M | 400.00M | +2.6% |").length == 2 + expect ok text open Ix.Cli.BenchReport in -def testThroughput : TestSeq := .individualIO "every measure gets columns, throughputs improve upward" none (do - let some spec := findBackend "ixvm" | return (false, 0, 0, none) - let rows := fun (t : Nat) => rowsOf [ - ("InitStd", [("execute-time", 40), ("throughput", t), ("peak-rss", 1), ("shards", 12), - ("fft-cost", 100)]), - ("Nat.add_comm", [("execute-time", 1), ("prove-time", 30), ("prove-throughput", t)])] - let text ← renderBackend spec - #[{ backend := "ixvm", env := "InitStd", base := rows 100, pr := rows 110 }] 3.0 "main" - let ok := (text.splitOn "| env | execute-time (main) | execute-time (PR) | Δ% | throughput (const/s) (main) | throughput (const/s) (PR) | Δ% | peak-ram (main) | peak-ram (PR) | Δ% | env-shards (main) | env-shards (PR) | Δ% | fft-cost (main) | fft-cost (PR) | Δ% |").length == 2 - && (text.splitOn "more metrics").length == 1 - && (text.splitOn "| prove-throughput (const/s) (main) |").length == 2 - && (text.splitOn "+10.0% (1.10× faster) 🟢").length == 3 - return (ok, 0, 0, if ok then none else some text)) .done +def testThroughput : LSpec.Spec := do + it "every measure gets columns, throughputs improve upward" do + let some spec := findBackend "ixvm" | fail "missing ixvm backend" + let rows := fun (t : Nat) => rowsOf [ + ("InitStd", [("execute-time", 40), ("throughput", t), ("peak-rss", 1), ("shards", 12), + ("fft-cost", 100)]), + ("Nat.add_comm", [("execute-time", 1), ("prove-time", 30), ("prove-throughput", t)])] + let text ← renderBackend spec + #[{ backend := "ixvm", env := "InitStd", base := rows 100, pr := rows 110 }] 3.0 "main" + let ok := (text.splitOn "| env | execute-time (main) | execute-time (PR) | Δ% | throughput (const/s) (main) | throughput (const/s) (PR) | Δ% | peak-ram (main) | peak-ram (PR) | Δ% | env-shards (main) | env-shards (PR) | Δ% | fft-cost (main) | fft-cost (PR) | Δ% |").length == 2 + && (text.splitOn "more metrics").length == 1 + && (text.splitOn "| prove-throughput (const/s) (main) |").length == 2 + && (text.splitOn "+10.0% (1.10× faster) 🟢").length == 3 + expect ok text open Ix.Cli.BenchReport in -def testRowKinds : TestSeq := .individualIO "a row shows and compares only its kind's measures" none (do - let some ooc := findBackend "ixvm-ooc" | return (false, 0, 0, none) - -- The constant rows share one process's peak RSS, which ixvm-ooc does not - -- compare per constant. - let shared := rowsOf [("Nat.add_comm", [("check-time", 5), ("peak-rss", 100)])] - let grew := rowsOf [("Nat.add_comm", [("check-time", 5), ("peak-rss", 200)])] - let oocText ← renderBackend ooc - #[{ backend := "ixvm-ooc", env := "InitStd", base := shared, pr := grew }] 3.0 "main" - let some ixvm := findBackend "ixvm" | return (false, 0, 0, none) - let consts := rowsOf [("Nat.add_comm", [("execute-time", 1)])] - let ixvmText ← renderBackend ixvm - #[{ backend := "ixvm", env := "InitStd", base := consts, pr := consts }] 3.0 "main" - let ok := (oocText.splitOn "0 with regressions").length == 2 - && (oocText.splitOn "peak-ram").length == 1 - && (ixvmText.splitOn "shards").length == 1 - return (ok, 0, 0, if ok then none else some (oocText ++ "\n" ++ ixvmText))) .done +def testRowKinds : LSpec.Spec := do + it "a row shows and compares only its kind's measures" do + let some ooc := findBackend "ixvm-ooc" | fail "missing ixvm-ooc backend" + -- The constant rows share one process's peak RSS, which ixvm-ooc does not + -- compare per constant. + let shared := rowsOf [("Nat.add_comm", [("check-time", 5), ("peak-rss", 100)])] + let grew := rowsOf [("Nat.add_comm", [("check-time", 5), ("peak-rss", 200)])] + let oocText ← renderBackend ooc + #[{ backend := "ixvm-ooc", env := "InitStd", base := shared, pr := grew }] 3.0 "main" + let some ixvm := findBackend "ixvm" | fail "missing ixvm backend" + let consts := rowsOf [("Nat.add_comm", [("execute-time", 1)])] + let ixvmText ← renderBackend ixvm + #[{ backend := "ixvm", env := "InitStd", base := consts, pr := consts }] 3.0 "main" + let ok := (oocText.splitOn "0 with regressions").length == 2 + && (oocText.splitOn "peak-ram").length == 1 + && (ixvmText.splitOn "shards").length == 1 + expect ok (oocText ++ "\n" ++ ixvmText) open Ix.Cli.BenchReport in -def testCommands : TestSeq := +def testCommands : LSpec.Spec := do let modes := fun command => (parseCommand command).toOption.map fun parsed => parsed.matrix.map fun cell => let field := fun key => (cell.getObjValAs? String key).toOption.getD "" (field "backend", field "env", field "mode") let selected := " BENCH_CONSTANTS=Nat.add_comm BENCH_ENVS=none" let rejects := fun command => (parseCommand command).toOption.isNone - test "bare ixvm defaults to execution" + itBool "bare ixvm defaults to execution" (modes ("!benchmark ixvm" ++ selected) == some #[ ("ixvm", "InitStd", "execute") ]) - ++ test "ixvm execute selects execution" + itBool "ixvm execute selects execution" (modes ("!benchmark ixvm execute" ++ selected) == some #[ ("ixvm", "InitStd", "execute") ]) - ++ test "ixvm prove selects proving" + itBool "ixvm prove selects proving" (modes ("!benchmark ixvm prove" ++ selected) == some #[ ("ixvm", "InitStd", "prove") ]) - ++ test "ixvm compress selects compression" + itBool "ixvm compress selects compression" (modes ("!benchmark ixvm compress" ++ selected) == some #[ ("ixvm", "InitStd", "compress") ]) - ++ test "the ixvm mode does not apply to other backends" + itBool "the ixvm mode does not apply to other backends" (modes ("!benchmark ixvm compress ixvm-ooc" ++ selected) == some #[ ("ixvm", "InitStd", "compress"), ("ixvm-ooc", "InitStd", "execute") ]) - ++ test "env-only ixvm cells stay execution-only" + itBool "env-only ixvm cells stay execution-only" (modes "!benchmark ixvm prove BENCH_CONSTANTS=Nat.add_comm BENCH_ENVS=Mathlib" == some #[ ("ixvm", "InitStd", "prove"), ("ixvm", "Mathlib", "execute") ]) - ++ test "all defaults every cell to execution" + itBool "all defaults every cell to execution" ((modes "!benchmark all").any (·.all fun (_, _, mode) => mode == "execute")) - ++ test "all can include an explicit ixvm mode" + itBool "all can include an explicit ixvm mode" ((modes "!benchmark all ixvm compress").any fun cells => cells.any (fun (backend, _, mode) => backend == "ixvm" && mode == "compress") && cells.all (fun (backend, _, mode) => backend == "ixvm" || mode == "execute")) - ++ test "backend and subcommand names are case-insensitive" + itBool "backend and subcommand names are case-insensitive" (modes ("!benchmark IXVM PROVE" ++ selected) == some #[ ("ixvm", "InitStd", "prove") ]) - ++ test "a mode must follow ixvm" + itBool "a mode must follow ixvm" (["!benchmark prove ixvm", "!benchmark ixvm-ooc prove", "!benchmark all compress"].all rejects) - ++ test "conflicting or repeated modes are rejected" + itBool "conflicting or repeated modes are rejected" (["!benchmark ixvm prove compress", "!benchmark ixvm prove ixvm compress"].all rejects) - ++ test "a misspelled mode is rejected" + itBool "a misspelled mode is rejected" (rejects "!benchmark ixvm proev") - ++ test "proving and compression require constant rows" + itBool "proving and compression require constant rows" (["!benchmark ixvm prove BENCH_CONSTANTS=none", "!benchmark ixvm compress BENCH_CONSTANTS=none"].all rejects) - ++ test "stage environment settings are rejected inline and on later lines" + itBool "stage environment settings are rejected inline and on later lines" (["!benchmark ixvm BENCH_PROVE=1", "!benchmark ixvm BENCH_COMPRESS=kzg", "!benchmark ixvm\nBENCH_PROVE=1", "!benchmark ixvm\nBENCH_COMPRESS=kzg"].all rejects) - ++ test "compress reports the complete pipeline and only forwards unrelated settings" + itBool "compress reports the complete pipeline and only forwards unrelated settings" ((parseCommand "!benchmark ixvm compress RUST_LOG=debug").toOption.any fun parsed => (parsed.summary.splitOn "stages `execute+prove+compress`").length == 2 && parsed.passthrough == #["RUST_LOG=debug"]) - ++ test "fresh applies to every backend and retains the ixvm mode" + itBool "fresh applies to every backend and retains the ixvm mode" ((parseCommand "!benchmark ixvm compress ixvm-ooc fresh").toOption.any fun parsed => parsed.fresh && parsed.passthrough.isEmpty && (parsed.summary.splitOn "baseline `fresh`").length == 2 && @@ -235,27 +241,27 @@ def testCommands : TestSeq := (cell.getObjValAs? String "mode").toOption == some (if (cell.getObjValAs? String "backend").toOption == some "ixvm" then "compress" else "execute"))) - ++ test "fresh is case-insensitive and works with all" + itBool "fresh is case-insensitive and works with all" ((parseCommand "!benchmark all FRESH").toOption.any (·.fresh)) - ++ test "ordinary requests retain cache reuse" + itBool "ordinary requests retain cache reuse" ((parseCommand "!benchmark ixvm execute").toOption.any (!·.fresh)) - ++ test "fresh alone does not select a backend" + itBool "fresh alone does not select a backend" (rejects "!benchmark fresh") - ++ test "with neither key set, every shared constant and the InitStd env row run" + itBool "with neither key set, every shared constant and the InitStd env row run" ((parseCommand "!benchmark ixvm").toOption.any fun parsed => parsed.matrix.any (fun cell => (cell.getObjValAs? String "env-row").toOption == some "1") && parsed.matrix.size == 2) - ++ test "BENCH_CONSTANTS alone selects no env rows" + itBool "BENCH_CONSTANTS alone selects no env rows" ((parseCommand "!benchmark ixvm BENCH_CONSTANTS=Nat.add_comm").toOption.any fun parsed => parsed.matrix.size == 1 && parsed.matrix.all (fun cell => (cell.getObjValAs? String "env-row").toOption == some "0")) - ++ test "BENCH_ENVS alone selects no constant rows" + itBool "BENCH_ENVS alone selects no constant rows" ((parseCommand "!benchmark ixvm\nBENCH_ENVS=Mathlib").toOption.any fun parsed => parsed.matrix.size == 1 && parsed.matrix.all (fun cell => (cell.getObjValAs? String "constants").toOption == some "none")) - ++ test "proving with only env rows selected is rejected" + itBool "proving with only env rows selected is rejected" (rejects "!benchmark ixvm prove BENCH_ENVS=InitStd") - ++ test "proving with neither key set selects only Nat.add_comm" + itBool "proving with neither key set selects only Nat.add_comm" (["!benchmark ixvm prove", "!benchmark ixvm compress"].all fun c => modes c == some #[ ("ixvm", "InitStd", c.splitOn " " |>.getLast!) ] && (parseCommand c).toOption.any fun parsed => @@ -263,51 +269,59 @@ def testCommands : TestSeq := (cell.getObjValAs? String "constants").toOption == some "Nat.add_comm" && (cell.getObjValAs? String "env-row").toOption == some "0")) -def testRunMode : TestSeq := .individualIO "invalid run modes fail before starting measured tools" none (do - let mut ok := true - for args in [["--backend", "ixvm", "--mode", "unknown"], - ["--backend", "ixvm-ooc", "--mode", "prove"], - ["--backend", "ixvm", "--mode", "compress", "--constants", "none"], - ["--backend", "ixvm", "--env-mode", "unknown"], - ["--backend", "compile", "--env-mode", "prove"], - ["--backend", "ixvm", "--env-mode", "prove", "--no-env-row"], - ["--backend", "ixvm", "--gpu-device", "0"], - ["--backend", "ixvm", "--env-mode", "prove", "--env-dev-srs"], - ["--backend", "ixvm", "--env-mode", "compress", "--env-compression", "aiur-bn"], - ["--backend", "ixvm", "--env-mode", "compress", "--env-compression", "aiur-bn", "--aiur-chain", "chain.json"], - ["--backend", "ixvm", "--env-mode", "compress", "--env-compression", "kzg", "--aiur-chain", "chain.json"], - ["--backend", "ixvm", "--env-mode", "compress", "--env-compression", "aiur-bn", "--aiur-chain", "chain.json", "--aiur-gl", "gl.ixa"], - ["--backend", "ixvm", "--env-mode", "compress", "--env-compression", "unknown"]] do - let (_, code) ← IO.FS.withIsolatedStreams (benchRunCmd.validate args) - ok := ok && code == 2 - return (ok, 0, 0, none)) .done +def testRunMode : LSpec.Spec := do + it "invalid run modes fail before starting measured tools" do + let mut ok := true + for args in [["--backend", "ixvm", "--mode", "unknown"], + ["--backend", "ixvm-ooc", "--mode", "prove"], + ["--backend", "ixvm", "--mode", "compress", "--constants", "none"], + ["--backend", "ixvm", "--env-mode", "unknown"], + ["--backend", "compile", "--env-mode", "prove"], + ["--backend", "ixvm", "--env-mode", "prove", "--no-env-row"], + ["--backend", "ixvm", "--gpu-device", "0"], + ["--backend", "ixvm", "--env-mode", "prove", "--env-dev-srs"], + ["--backend", "ixvm", "--env-mode", "compress", "--env-compression", "aiur-bn"], + ["--backend", "ixvm", "--env-mode", "compress", "--env-compression", "aiur-bn", "--aiur-chain", "chain.json"], + ["--backend", "ixvm", "--env-mode", "compress", "--env-compression", "kzg", "--aiur-chain", "chain.json"], + ["--backend", "ixvm", "--env-mode", "compress", "--env-compression", "aiur-bn", "--aiur-chain", "chain.json", "--aiur-gl", "gl.ixa"], + ["--backend", "ixvm", "--env-mode", "compress", "--env-compression", "unknown"]] do + let (_, code) ← IO.FS.withIsolatedStreams (benchRunCmd.validate args) + ok := ok && code == 2 + expect ok -def testEnvProofOptions : TestSeq := +def testEnvProofOptions : LSpec.Spec := do let options := fun (args : List String) => do let (_, parsed) ← (benchRunCmd.parse ("--backend" :: "ixvm" :: args)).toOption (envProofOptions parsed "ixvm" true).toOption - test "whole-env proving is explicitly selected without constant rows" + itBool "whole-env proving is explicitly selected without constant rows" ((options ["--env", "Init", "--constants", "none", "--env-mode", "prove"]).any fun opts => opts.mode == .prove && opts.hostArgs.isEmpty && !opts.development) - ++ test "whole-env compression defaults to production PLONK" + itBool "whole-env compression defaults to production PLONK" ((options ["--env-mode", "compress"]).any fun opts => opts.compressArgs == #["--plonk"]) - ++ test "development PLONK selects both development setups" + itBool "development PLONK selects both development setups" ((options ["--env-mode", "compress", "--env-dev-srs"]).any fun opts => opts.compressArgs == #["--plonk", "--dev-kzg-srs", "--dev-final-srs"]) - ++ test "KZG and GPU configuration reach the measured tools" + itBool "KZG and GPU configuration reach the measured tools" ((options ["--env-mode", "compress", "--env-compression", "kzg", "--env-dev-srs", "--gpu-device", "0", "--max-ram", "200"]).any fun opts => opts.compressArgs == #["--dev-kzg-srs"] && opts.hostArgs == #["--gpu-device", "0", "--max-ram", "200"]) - ++ test "Aiur BN forwards only the independently selected chain manifest" + itBool "Aiur BN forwards only the independently selected chain manifest" ((options ["--env-mode", "compress", "--env-compression", "aiur-bn", "--aiur-chain", "trusted-chain.json", "--aiur-chain-blake3", "expected-pin", "--env-dev-srs"]).any fun opts => opts.aiurArgs == #["--aiur-chain", "trusted-chain.json", "--aiur-chain-blake3", "expected-pin"] && opts.compressArgs == #["--dev-kzg-srs", "--aiur-chain", "trusted-chain.json", "--aiur-chain-blake3", "expected-pin"]) -def suite : List TestSeq := - [testRows, testCells, testReport, testFftCost, testThroughput, testRowKinds, testCommands, - testRunMode, testEnvProofOptions] +def suite : LSpec.Spec := do + testRows + testCells + testReport + testFftCost + testThroughput + testRowKinds + testCommands + testRunMode + testEnvProofOptions end Tests.Ix.BenchMeasures diff --git a/Tests/Ix/Catalog.lean b/Tests/Ix/Catalog.lean index ae59e11f72..9af567cfaf 100644 --- a/Tests/Ix/Catalog.lean +++ b/Tests/Ix/Catalog.lean @@ -40,6 +40,8 @@ public section open LSpec +set_option compiler.extract_closed false + namespace Tests.Ix.Catalog @[extern "rs_env_section_counts"] @@ -118,7 +120,7 @@ private def compilePieceToFile (consts : List (Lean.Name × Lean.ConstantInfo)) /-- The end-to-end fixture gate: compile two overlapping pieces, assemble, and pin format parity + identity dedup. -/ -private def assembleParityTest : IO (Bool × Nat × Nat × Option String) := do +private def assembleParityTest : AssertM Unit := do let dir ← IO.FS.createTempDir try -- Piece A: base + idA. Piece B: base + idA + idB (A ⊂ B content). @@ -139,16 +141,12 @@ private def assembleParityTest : IO (Bool × Nat × Nat × Option String) := do ("deps", Lean.Json.arr #[Lean.toJson (0 : Nat)])] ] let summary ← Ix.Cli.CatalogCmd.rsCatalogAssembleFFI ixcDir.toString members.compress - let json ← match Lean.Json.parse summary with - | .ok j => pure j - | .error e => return (false, 0, 0, some s!"assemble JSON: {e}") + let json ← expectOk ((Lean.Json.parse summary).mapError (s!"assemble JSON: {·}")) unless (← (ixcDir / "A.ixe").pathExists) do - return (false, 0, 0, some "piece not ingested into the .ixc dir") + fail "piece not ingested into the .ixc dir" -- Lean mirror: parse the Rust-written manifest inside the dir. let bytes ← IO.FS.readBinFile (ixcDir / "manifest") - let cat ← match Ix.Catalog.de bytes with - | .ok c => pure c - | .error e => return (false, 0, 0, some s!"Lean mirror de: {e}") + let cat ← expectOk ((Ix.Catalog.de bytes).mapError (s!"Lean mirror de: {·}")) let checks : List (String × Bool) := [ -- Byte-identity: Lean ser ∘ de reproduces the Rust bytes. ("mirror re-serializes byte-identical", @@ -166,16 +164,13 @@ private def assembleParityTest : IO (Bool × Nat × Nat × Option String) := do toString cat.members[0]!.envRoot == rootA), ("deps carried", cat.members[1]!.deps == #[0]), ("fat profile", !(cat.storage matches .chunked _)) ] - match checks.find? (!·.2) with - | some (what, _) => return (false, 0, 0, some s!"failed: {what}") - | none => - return (true, cat.members[0]!.constCount.toNat, - cat.members[1]!.constCount.toNat, none) + if let some (what, _) := checks.find? (!·.2) then + fail s!"failed: {what}" finally IO.FS.removeDirAll dir /-- Strict-anon compile: §5 empty, §3 survives, root unmoved. -/ -private def anonCompileTest : IO (Bool × Nat × Nat × Option String) := do +private def anonCompileTest : AssertM Unit := do let dir ← IO.FS.createTempDir try let consts ← fixtureConsts [defnOver `TCat.idA 1] @@ -187,12 +182,8 @@ private def anonCompileTest : IO (Bool × Nat × Nat × Option String) := do match Lean.Json.parse (← rsEnvSectionCountsFFI path) with | .ok j => return .ok j | .error e => return .error e - let cNamed ← match ← countsOf named with - | .ok j => pure j - | .error e => return (false, 0, 0, some s!"counts(named): {e}") - let cAnon ← match ← countsOf anon with - | .ok j => pure j - | .error e => return (false, 0, 0, some s!"counts(anon): {e}") + let cNamed ← expectOk ((← countsOf named).mapError (s!"counts(named): {·}")) + let cAnon ← expectOk ((← countsOf anon).mapError (s!"counts(anon): {·}")) let checks : List (String × Bool) := [ ("roots equal (anon-invariance)", rootNamed == rootAnon), ("named piece carries §5", (num cNamed "named").getD 0 > 0), @@ -204,10 +195,8 @@ private def anonCompileTest : IO (Bool × Nat × Nat × Option String) := do ("§3 hints survive --anon", (num cAnon "hints").getD 0 > 0 && num cAnon "hints" == num cNamed "hints") ] - match checks.find? (!·.2) with - | some (what, _) => return (false, 0, 0, some s!"failed: {what}") - | none => return (true, (num cAnon "consts").getD 0, - (num cAnon "hints").getD 0, none) + if let some (what, _) := checks.find? (!·.2) then + fail s!"failed: {what}" finally IO.FS.removeDirAll dir @@ -227,10 +216,10 @@ private def fatOf (members : Array Ix.Catalog.Member) : Ix.Catalog.Catalog := members storage := .fat (members.map fun m => ⟨addr s!"f{m.label}", 10⟩) } -private def fatCat : Ix.Catalog.Catalog := +private def mkFatCat (_ : Unit) : Ix.Catalog.Catalog := fatOf #[member "A" (addr "rootA"), member "B" (addr "rootB") #[0] (some (addr "pre"))] -private def chunkedCat : Ix.Catalog.Catalog := +private def mkChunkedCat (_ : Unit) : Ix.Catalog.Catalog := let members := #[member "A" (addr "rootA")] { membersRoot := Ix.Catalog.membersRootOf members contentRoot := addr "content" @@ -260,34 +249,34 @@ private def setByte (i : Nat) (v : UInt8) (b : ByteArray) : ByteArray := /-- The offset of the first member's preimage tag in `fatCat`'s bytes: the fixed header (magic, version, flags, scope, two roots, the member count), then the member up to its last byte. -/ -private def firstPreimageTag : Nat := +private def firstPreimageTag (fatCat : Ix.Catalog.Catalog) : Nat := 8 + 4 + 4 + 2 + 32 + 32 + 4 + (Ixon.runPut (Ix.Catalog.putMember fatCat.members[0]!)).size - 1 /-- Malformed manifests, each with a phrase that both readers' refusals contain (an empty phrase: any refusal). -/ -private def malformed : List (String × ByteArray × String) := - let good := serOk fatCat - [ ("bad magic", setByte 0 0xFF good, "magic"), - ("legacy version", setByte 8 1 good, "version"), - ("unknown flags", setByte 12 0xFF good, "flags"), - ("other object format", setByte 16 3 good, "format"), - ("resource validator", setByte 17 2 good, "validator"), - ("members_root drift", setByte (8 + 4 + 4 + 2) 0xFF good, "members_root"), - ("truncated", good.extract 0 (good.size - 1), ""), - ("trailing byte", good.push 0, "trailing"), - ("preimage tag 2", setByte firstPreimageTag 2 good, "preimage tag"), - ("one env root twice", +private def malformedSpecs : List (String × (Unit → ByteArray) × String) := + [ ("bad magic", fun () => setByte 0 0xFF (serOk (mkFatCat ())), "magic"), + ("legacy version", fun () => setByte 8 1 (serOk (mkFatCat ())), "version"), + ("unknown flags", fun () => setByte 12 0xFF (serOk (mkFatCat ())), "flags"), + ("other object format", fun () => setByte 16 3 (serOk (mkFatCat ())), "format"), + ("resource validator", fun () => setByte 17 2 (serOk (mkFatCat ())), "validator"), + ("members_root drift", fun () => setByte (8 + 4 + 4 + 2) 0xFF (serOk (mkFatCat ())), "members_root"), + ("truncated", fun () => let g := serOk (mkFatCat ()); g.extract 0 (g.size - 1), ""), + ("trailing byte", fun () => (serOk (mkFatCat ())).push 0, "trailing"), + ("preimage tag 2", fun () => + let fc := mkFatCat (); setByte (firstPreimageTag fc) 2 (serOk fc), "preimage tag"), + ("one env root twice", fun () => serOk (fatOf #[member "A" (addr "rootA"), member "B" (addr "rootA")]), "duplicate member env root"), - ("one label twice", + ("one label twice", fun () => serOk (fatOf #[member "A" (addr "rootA"), member "A" (addr "rootB")]), "duplicate member label"), - ("dependency not before its member", + ("dependency not before its member", fun () => serOk (fatOf #[member "A" (addr "rootA") #[0]]), "strictly before"), - ("path-traversal label", + ("path-traversal label", fun () => serOk (fatOf #[member "../evil" (addr "rootA")]), "bare filename"), - ("chunk owner out of range", - serOk { chunkedCat with storage := .chunked #[⟨addr "c0", addr "f0", 5, 1⟩] }, + ("chunk owner out of range", fun () => + serOk { mkChunkedCat () with storage := .chunked #[⟨addr "c0", addr "f0", 5, 1⟩] }, "out of range") ] private def deFails (bytes : ByteArray) (needle : String) : Bool := @@ -296,29 +285,30 @@ private def deFails (bytes : ByteArray) (needle : String) : Bool := | .error e => contains e needle /-- A string the writer's `u16` length cannot carry. -/ -private def oversized : String := String.ofList (List.replicate 65536 'x') - -def unitTests : TestSeq := - test "fat catalog roundtrips" (roundtrips fatCat) - ++ test "chunked catalog roundtrips" (roundtrips chunkedCat) - ++ test "the first member's preimage tag is where the malformed cases set it" - ((serOk fatCat)[firstPreimageTag]! == 0) - ++ malformed.foldl (init := .done) fun acc (what, bytes, needle) => - acc ++ test s!"{what} rejected" (deFails bytes needle) - ++ test "writer refuses a source pin over 64 KiB" - (Ix.Catalog.ser (fatOf #[{ member "A" (addr "rootA") with sourcePin := oversized }]) - matches .error _) - ++ test "writer accepts a source pin of exactly 64 KiB - 1" - (Ix.Catalog.ser (fatOf #[{ member "A" (addr "rootA") with - sourcePin := String.ofList (List.replicate 65535 'x') }]) matches .ok _) - ++ test "writer refuses a fat catalog without one storage row per member" - (Ix.Catalog.ser { fatCat with storage := .fat #[] } matches .error _) - ++ test "bare label accepted" - (Ix.Catalog.validateLabel "Mathlib" matches .ok _) +private def mkOversized (_ : Unit) : String := String.ofList (List.replicate 65536 'x') + +def unitTests : LSpec.Spec := do + itBool "fat catalog roundtrips" (roundtrips (mkFatCat ())) + itBool "chunked catalog roundtrips" (roundtrips (mkChunkedCat ())) + it "the first member's preimage tag is where the malformed cases set it" do + let fc := mkFatCat () + expect ((serOk fc)[firstPreimageTag fc]! == 0) + for (what, mkBytes, needle) in malformedSpecs do + itBool s!"{what} rejected" (deFails (mkBytes ()) needle) + itBool "writer refuses a source pin over 64 KiB" + (Ix.Catalog.ser (fatOf #[{ member "A" (addr "rootA") with sourcePin := mkOversized () }]) + matches .error _) + itBool "writer accepts a source pin of exactly 64 KiB - 1" + (Ix.Catalog.ser (fatOf #[{ member "A" (addr "rootA") with + sourcePin := String.ofList (List.replicate 65535 'x') }]) matches .ok _) + itBool "writer refuses a fat catalog without one storage row per member" + (Ix.Catalog.ser { mkFatCat () with storage := .fat #[] } matches .error _) + itBool "bare label accepted" + (Ix.Catalog.validateLabel "Mathlib" matches .ok _) /-- Reject parity: the Lean mirror and the Rust reader (`rs_catalog_info`) refuse the same malformed manifests, and accept the well-formed one. -/ -private def rejectParityTest : IO (Bool × Nat × Nat × Option String) := do +private def rejectParityTest : AssertM Unit := do let dir ← IO.FS.createTempDir try let write (name : String) (bytes : ByteArray) : IO String := do @@ -326,44 +316,47 @@ private def rejectParityTest : IO (Bool × Nat × Nat × Option String) := do IO.FS.createDirAll ixc IO.FS.writeBinFile (ixc / "manifest") bytes return ixc.toString - let good ← write "good" (serOk fatCat) - try - discard <| Ix.Cli.CatalogCmd.rsCatalogInfoFFI good - catch e => return (false, 0, 0, some s!"Rust refuses the well-formed manifest: {e}") - unless Ix.Catalog.de (serOk fatCat) matches .ok _ do - return (false, 0, 0, some "Lean refuses the well-formed manifest") + let goodBytes := serOk (mkFatCat ()) + let good ← write "good" goodBytes + let goodRust : Option String ← liftM (m := IO) do + try + discard <| Ix.Cli.CatalogCmd.rsCatalogInfoFFI good + pure none + catch e => pure (some (toString e)) + if let some e := goodRust then + fail s!"Rust refuses the well-formed manifest: {e}" + unless Ix.Catalog.de goodBytes matches .ok _ do + fail "Lean refuses the well-formed manifest" let mut i := 0 - for (what, bytes, needle) in malformed do + for (what, mkBytes, needle) in malformedSpecs do i := i + 1 + let bytes := mkBytes () let ixc ← write s!"bad{i}" bytes - let rust ← try + let rust : Option String ← liftM (m := IO) do + try discard <| Ix.Cli.CatalogCmd.rsCatalogInfoFFI ixc pure none catch e => pure (some (toString e)) match rust with - | none => return (false, i, 0, some s!"Rust accepts: {what}") + | none => fail s!"Rust accepts: {what}" | some e => unless contains e needle do - return (false, i, 0, some s!"Rust refuses {what} for another reason: {e}") + fail s!"Rust refuses {what} for another reason: {e}" match Ix.Catalog.de bytes with - | .ok _ => return (false, i, 0, some s!"Lean accepts: {what}") + | .ok _ => fail s!"Lean accepts: {what}" | .error e => unless contains e needle do - return (false, i, 0, some s!"Lean refuses {what} for another reason: {e}") - return (true, i, 0, none) + fail s!"Lean refuses {what} for another reason: {e}" finally IO.FS.removeDirAll dir -def suite : List TestSeq := [ - unitTests, - .individualIO - "assemble parity: Rust .ixc ↔ Lean mirror byte-identical, dedup observed" - none assembleParityTest .done, - .individualIO - "reject parity: Lean and Rust refuse the same malformed manifests" - none rejectParityTest .done, - .individualIO - "strict-anon compile: §5 empty, §3 survives, root unmoved" - none anonCompileTest .done ] +def suite : LSpec.Spec := do + unitTests + it "assemble parity: Rust .ixc ↔ Lean mirror byte-identical, dedup observed" + assembleParityTest + it "reject parity: Lean and Rust refuse the same malformed manifests" + rejectParityTest + it "strict-anon compile: §5 empty, §3 survives, root unmoved" + anonCompileTest end Tests.Ix.Catalog diff --git a/Tests/Ix/CatalogDedup.lean b/Tests/Ix/CatalogDedup.lean index 9097ba08d7..89890b74f8 100644 --- a/Tests/Ix/CatalogDedup.lean +++ b/Tests/Ix/CatalogDedup.lean @@ -51,12 +51,12 @@ private def compilePiece (exe : System.FilePath) (driver out : String) : {r.stderr.take 300} … {(r.stdout.takeEnd 300).toString}" return .ok () -private def dedupTest : IO (Bool × Nat × Nat × Option String) := do +private def dedupTest : AssertM Unit := do unless (← ixExe.pathExists) do - return (false, 0, 0, some s!"{ixExe} missing — run `lake build ix` first") + fail s!"{ixExe} missing — run `lake build ix` first" for fixture in [fixtureA, fixtureB] do unless (← fixture.pathExists) do - return (false, 0, 0, some s!"fixture source missing: {fixture}") + fail s!"fixture source missing: {fixture}" let exe ← IO.FS.realPath ixExe let dir ← IO.FS.createTempDir try @@ -67,10 +67,8 @@ private def dedupTest : IO (Bool × Nat × Nat × Option String) := do let taskB ← IO.asTask (prio := .dedicated) (compilePiece exe fixtureB.toString pieceB) let resA ← IO.wait taskA let resB ← IO.wait taskB - if let .error e ← IO.ofExcept resA then - return (false, 0, 0, some e) - if let .error e ← IO.ofExcept resB then - return (false, 0, 0, some e) + discard <| expectOk (← IO.ofExcept resA) + discard <| expectOk (← IO.ofExcept resB) -- Assemble the self-contained .ixc dir via the CLI, then gate on -- the manifest through the in-process core (info/verify FFI) — no -- report artifacts anywhere in this flow. @@ -80,8 +78,7 @@ private def dedupTest : IO (Bool × Nat × Nat × Option String) := do args := #["catalog", "assemble", ixc, pieceA, pieceB, "--labels", "A,B"] } if r.exitCode != 0 then - return (false, 0, 0, some s!"assemble failed ({r.exitCode}): \ -{r.stderr.take 300}") + fail s!"assemble failed ({r.exitCode}): {r.stderr.take 300}" let infoContent ← Ix.Cli.CatalogCmd.rsCatalogInfoFFI ixc let verifyContent ← Ix.Cli.CatalogCmd.rsCatalogVerifyFFI ixc false let checks : Except String (Nat × Nat) := do @@ -100,15 +97,11 @@ content got different addresses across processes" throw s!"union {union} not larger than both pieces ({a}, {b}) — \ the collision pair's distinct content collapsed" return (union, a + b) - match checks with - | .ok (union, sum) => return (true, union, sum, none) - | .error m => return (false, 0, 0, some m) + discard <| expectOk checks finally IO.FS.removeDirAll dir -def suite : List TestSeq := [ - .individualIO - "catalog-dedup: cross-process pieces share addresses, collisions coexist" - none dedupTest .done ] +def suite : LSpec.Spec := do + it "catalog-dedup: cross-process pieces share addresses, collisions coexist" dedupTest end Tests.Ix.CatalogDedup diff --git a/Tests/Ix/Cert/Statement.lean b/Tests/Ix/Cert/Statement.lean index 07f92bb0f7..020830e0d5 100644 --- a/Tests/Ix/Cert/Statement.lean +++ b/Tests/Ix/Cert/Statement.lean @@ -1599,12 +1599,12 @@ def hintCase (leanEnv : Lean.Environment) : IO (Array String × Array String) := return (#[s!"hints: refused, but naming {n.pretty}, not a definition at Nat.add's address"], #[]) | none => return (#["hints: the check accepts an artifact with Nat.add's hint erased"], #[]) -def report (name : String) (action : IO (Array String × Array String)) (count : Nat) : TestSeq := - .individualIO name none (do +def report (name : String) (action : IO (Array String × Array String)) (_count : Nat := 1) : Spec := + it name do let (errors, lines) ← action for l in lines do IO.println l - let msg := if errors.isEmpty then none else some ("\n".intercalate errors.toList) - return (errors.isEmpty, count, 0, msg)) .done + unless errors.isEmpty do + fail ("\n".intercalate errors.toList) initialize fixtureEnvCache : IO.Ref (Option Lean.Environment) ← IO.mkRef none @@ -1614,56 +1614,56 @@ private def fixtureEnv : IO Lean.Environment := do fixtureEnvCache.set (some env) return env -def suite : List TestSeq := [ +def suite : LSpec.Spec := do report "Ix.Cert.compile against the IO pipeline and the Rust compiler, on the fixtures" (do let leanEnv ← fixtureEnv - parity "fixtures" (← fixtureConsts leanEnv) 4) 1, + parity "fixtures" (← fixtureConsts leanEnv) 4) 1 report "an axiom α-equal to sorryAx is published at its address and keyed by its role" (do - sorryAliasCase (← fixtureEnv)) 1, + sorryAliasCase (← fixtureEnv)) 1 report "the statements' hypotheses and conclusion, per root, on the accepted fixtures" (do - perRoot (← fixtureEnv)) 1, + perRoot (← fixtureEnv)) 1 report "CompileCorrect.checked's premises hold on the closures of Nat.add and List.length" (do - Tests.Ix.Cert.ExecutedChecks.checkedCase (← fixtureEnv)) 1, + Tests.Ix.Cert.ExecutedChecks.checkedCase (← fixtureEnv)) 1 report "the evidence check refuses a misbound table and a replaced fallback record" (do - Tests.Ix.Cert.ExecutedChecks.evidenceRefusals (← fixtureEnv)) 1, + Tests.Ix.Cert.ExecutedChecks.evidenceRefusals (← fixtureEnv)) 1 report "annotated source refused on both sides, on the resolved source-contract syntax fixtures" (do - contractAgreement (← getCompileEnv #[syntaxModule])) 1, + contractAgreement (← getCompileEnv #[syntaxModule])) 1 report "the shipped role table's certificates check on their pinned closure (Route A, B6b)" - roleEvidenceCase 1, + roleEvidenceCase 1 report "a closure with a well-founded Nat operation, at the bundle evidence (Nat.div)" (do - natDivClosure (← fixtureEnv)) 1, + natDivClosure (← fixtureEnv)) 1 report "a closure with a string literal holds its literal support (outOfBounds)" (do - literalClosure (← fixtureEnv) `outOfBounds) 1, + literalClosure (← fixtureEnv) `outOfBounds) 1 report "a Nat literal whose bytes are another constant's record is refused (blob check)" - blobRecordCase 1, + blobRecordCase 1 report "a recursor with all = [J] in I's motive slot is refused (recursor check)" (do - recursorFamilyCase (← fixtureEnv)) 1, + recursorFamilyCase (← fixtureEnv)) 1 report "a record of the wrong kind at a bound role's address is refused (role check)" (do - roleKindCase (← fixtureEnv)) 1, + roleKindCase (← fixtureEnv)) 1 report "a copy of Nat without Nat: accepted alone, refused beside a Nat literal" (do - literalRoleCase (← getCompileEnv #[`Tests.Ix.Kernel.TutorialDefs])) 1, + literalRoleCase (← getCompileEnv #[`Tests.Ix.Kernel.TutorialDefs])) 1 report "a recursor rule naming a hash twin of its constructor is refused (inductive input check)" (do - familyNameCase (← fixtureEnv)) 1, + familyNameCase (← fixtureEnv)) 1 report "constructors declaring each other's index are refused (inductive input check)" (do - constructorIndexCase (← fixtureEnv)) 1, + constructorIndexCase (← fixtureEnv)) 1 report "a constructor with its inductive's level parameters reordered is refused (inductive input check)" (do - levelParamsCase (← fixtureEnv)) 1, + levelParamsCase (← fixtureEnv)) 1 report "a recursor with two level parameters too many is refused (inductive input check)" (do - recursorLevelCountCase (← fixtureEnv)) 1, + recursorLevelCountCase (← fixtureEnv)) 1 report "a recursor whose all is not its family's is refused (inductive input check)" (do - familyBlockCase (← fixtureEnv)) 1, + familyBlockCase (← fixtureEnv)) 1 report "two recursors filed at one motive are refused (inductive input check)" (do - recursorSlotCase (← fixtureEnv)) 1, + recursorSlotCase (← fixtureEnv)) 1 report "recursors with each other's types are refused (inductive input check)" (do - recursorShapeCase (← fixtureEnv)) 1, + recursorShapeCase (← fixtureEnv)) 1 report "an artifact with a published definition's hint erased is refused (hint check)" (do - hintCase (← fixtureEnv)) 1] + hintCase (← fixtureEnv)) 1 /-- `cert-evidence-agreement` (landing): the role table's evidence against quotient Source's on the well-founded operations' closure (`evidenceAgreement`); it compiles and reads the closure, so it stays out of the primary tier. -/ -def evidenceSuite : List TestSeq := [ +def evidenceSuite : LSpec.Spec := do report "the role table's evidence against quotient Source's, on the well-founded operations" (do - evidenceAgreement (← fixtureEnv)) 1] + evidenceAgreement (← fixtureEnv)) 1 end Tests.Ix.Cert.Statement diff --git a/Tests/Ix/CircuitMeta.lean b/Tests/Ix/CircuitMeta.lean index 2bd0234abc..88b370cda0 100644 --- a/Tests/Ix/CircuitMeta.lean +++ b/Tests/Ix/CircuitMeta.lean @@ -14,6 +14,8 @@ namespace Tests.Ix.CircuitMeta open Ixon LSpec +set_option compiler.extract_closed false + private def repAddr (b : UInt8) : Address := ⟨⟨(List.replicate 32 b).toArray⟩⟩ @@ -97,7 +99,7 @@ def expectedGoldenSectionBytes : ByteArray := private def patchByte (ba : ByteArray) (idx : Nat) (val : UInt8) : ByteArray := ⟨ba.data.set! idx val⟩ -private def sampleEnv : Env := Id.run do +private def mkSampleEnv (_ : Unit) : Env := Id.run do let defn : Definition := { kind := .defn, safety := .safe, lvls := 0, typ := .sort 0, value := .sort 0 } @@ -116,111 +118,117 @@ private def allFullReadersReject (bytes : ByteArray) : Bool := (rsDeEnv bytes).toOption.isNone && (deEnvAnon bytes).toOption.isNone -public def units : TestSeq := - let secOk : Bool := match CircuitMeta.serSection goldenMeta with - | .ok b => b == expectedGoldenSectionBytes && b.size == 239 - | .error _ => false - let secRoundTrip : Bool := match runGetExact CircuitMeta.getSection expectedGoldenSectionBytes with - | .ok cm => cm == goldenMeta - | .error _ => false - let canonicalSort : Bool := - let reversed : CircuitMeta := { goldenMeta with byAddress := goldenMeta.byAddress.reverse } - match CircuitMeta.serSection reversed with - | .ok b => b == expectedGoldenSectionBytes - | .error _ => false - let dupRejected : Bool := - let dupAddr : CircuitMeta := { goldenMeta with byAddress := goldenMeta.byAddress.push goldenMeta.byAddress[0]! } - let dupFun : CircuitMeta := { goldenMeta with byFun := goldenMeta.byFun.push goldenMeta.byFun[0]! } - let dupGroup : CircuitMeta := { goldenMeta with groups := goldenMeta.groups.push goldenMeta.groups[0]! } - let dupGuess : CircuitMeta := { goldenMeta with guesses := goldenMeta.guesses.push goldenMeta.guesses[0]! } - (CircuitMeta.serSection dupAddr).toOption.isNone && - (CircuitMeta.serSection dupFun).toOption.isNone && - (CircuitMeta.serSection dupGroup).toOption.isNone && - (CircuitMeta.serSection dupGuess).toOption.isNone - let writerInvariants := - let conflictFuel : CircuitMeta := { - byAddress := #[(repAddr 0x01, { fuelParam := some "n", noFuel := true })] - } - let zeroUnroll : CircuitMeta := { - byAddress := #[(repAddr 0x01, { unroll := some 0 })] - } - let zeroLanes : CircuitMeta := { - byAddress := #[(repAddr 0x01, { lanes := some 0 })] - } - let emptyGroup : CircuitMeta := { - byAddress := #[(repAddr 0x01, { group := some "" })] - } - let zeroLimbs : CircuitMeta := { - byAddress := #[(repAddr 0x01, { repr := some (.limbs 0 64) })] - } - let zeroFlat : CircuitMeta := { - byAddress := #[(repAddr 0x01, { repr := some (.flatArray 0) })] - } - [conflictFuel, zeroUnroll, zeroLanes, emptyGroup, zeroLimbs, zeroFlat].all fun cm => - (CircuitMeta.serSection cm).toOption.isNone - - let env := sampleEnv - let plainBytes := (serEnv env).toOption.getD ByteArray.empty - let withMetaBytes := (serEnvWithCircuitMeta env (some goldenMeta)).toOption.getD ByteArray.empty - let appendedBytes := (appendCircuitMetaSection plainBytes goldenMeta).toOption.getD ByteArray.empty - - let prefixIdentical := - !plainBytes.isEmpty && - withMetaBytes == appendedBytes && - withMetaBytes.size == plainBytes.size + expectedGoldenSectionBytes.size && - withMetaBytes.extract 0 plainBytes.size == plainBytes - - let fullDecodeOk := - match deEnvWithCircuitMeta withMetaBytes, deEnv withMetaBytes, deEnvVerifiedLazy withMetaBytes with - | .ok (e1, some cm1), .ok e2, .ok parts => - cm1 == goldenMeta && - parts.circuitMeta == some goldenMeta && - e1.merkleRoot == env.merkleRoot && - e2.merkleRoot == env.merkleRoot && - parts.env.merkleRoot == env.merkleRoot - | _, _, _ => false - - let legacyDecodeNone := - match deEnvWithCircuitMeta plainBytes, deEnvVerifiedLazy plainBytes with - | .ok (e1, none), .ok parts => - parts.circuitMeta.isNone && e1.merkleRoot == env.merkleRoot - | _, _ => false - - let rustReadersOk := - match rsDeEnv withMetaBytes, deEnvAnon withMetaBytes, rsDeEnvAnon withMetaBytes with - | .ok eFull, .ok eLazy, .ok eAnon => - eFull.merkleRoot == env.merkleRoot && - eLazy.merkleRoot == env.merkleRoot && - eAnon.merkleRoot == env.merkleRoot - | _, _, _ => false - - let badVersion := plainBytes ++ patchByte expectedGoldenSectionBytes 4 2 - let badHeaderFlag := plainBytes ++ patchByte expectedGoldenSectionBytes 5 0x20 - let badRangeCheck := plainBytes ++ patchByte expectedGoldenSectionBytes 5 0x03 - let badAiurBit := plainBytes ++ patchByte expectedGoldenSectionBytes 8 0x80 - let badBudgetBit := plainBytes ++ patchByte expectedGoldenSectionBytes 9 0x20 - let truncatedSec := plainBytes ++ expectedGoldenSectionBytes.extract 0 (expectedGoldenSectionBytes.size - 1) - let trailingAfterSec := withMetaBytes ++ ByteArray.mk #[0x00] - let legacyTrailingZero := plainBytes ++ ByteArray.mk #[0x00] - let legacyTrailingTwo := plainBytes ++ ByteArray.mk #[0x00, 0x00] - - test "circuit_meta: cross-language 239-byte golden vector matches" (secOk = true) ++ - test "circuit_meta: golden section roundtrips" (secRoundTrip = true) ++ - test "circuit_meta: writer canonicalizes unsorted keys" (canonicalSort = true) ++ - test "circuit_meta: writer rejects duplicate keys" (dupRejected = true) ++ - test "circuit_meta: writer enforces field invariants" (writerInvariants = true) ++ - test "circuit_meta: §7 appends cleanly with byte-identical header/Merkle root/§1..§6 prefix" (prefixIdentical = true) ++ - test "circuit_meta: Lean deEnv / deEnvWithCircuitMeta / deEnvVerifiedLazy decode §7" (fullDecodeOk = true) ++ - test "circuit_meta: legacy .ixe without §7 decodes to none" (legacyDecodeNone = true) ++ - test "circuit_meta: Rust rsDeEnv / deEnvAnon / rsDeEnvAnon accept .ixe with §7" (rustReadersOk = true) ++ - test "circuit_meta: Lean+Rust reject bad version in §7" (allFullReadersReject badVersion = true) ++ - test "circuit_meta: Lean+Rust reject reserved header flag in §7" (allFullReadersReject badHeaderFlag = true) ++ - test "circuit_meta: Lean+Rust reject invalid rangeCheck tag in §7" (allFullReadersReject badRangeCheck = true) ++ - test "circuit_meta: Lean+Rust reject reserved aiurConfig bit in §7" (allFullReadersReject badAiurBit = true) ++ - test "circuit_meta: Lean+Rust reject reserved budget bit in §7" (allFullReadersReject badBudgetBit = true) ++ - test "circuit_meta: Lean+Rust reject truncated §7 section" (allFullReadersReject truncatedSec = true) ++ - test "circuit_meta: Lean+Rust reject trailing bytes after §7" (allFullReadersReject trailingAfterSec = true) ++ - test "circuit_meta: legacy trailing garbage still rejected by Lean+Rust" - (allFullReadersReject legacyTrailingZero = true ∧ allFullReadersReject legacyTrailingTwo = true) +public def units : LSpec.Spec := do + itBool "circuit_meta: cross-language 239-byte golden vector matches" + (match CircuitMeta.serSection goldenMeta with + | .ok b => b == expectedGoldenSectionBytes && b.size == 239 + | .error _ => false) + itBool "circuit_meta: golden section roundtrips" + (match runGetExact CircuitMeta.getSection expectedGoldenSectionBytes with + | .ok cm => cm == goldenMeta + | .error _ => false) + itBool "circuit_meta: writer canonicalizes unsorted keys" + (let reversed : CircuitMeta := { goldenMeta with byAddress := goldenMeta.byAddress.reverse } + match CircuitMeta.serSection reversed with + | .ok b => b == expectedGoldenSectionBytes + | .error _ => false) + itBool "circuit_meta: writer rejects duplicate keys" + (let dupAddr : CircuitMeta := { goldenMeta with byAddress := goldenMeta.byAddress.push goldenMeta.byAddress[0]! } + let dupFun : CircuitMeta := { goldenMeta with byFun := goldenMeta.byFun.push goldenMeta.byFun[0]! } + let dupGroup : CircuitMeta := { goldenMeta with groups := goldenMeta.groups.push goldenMeta.groups[0]! } + let dupGuess : CircuitMeta := { goldenMeta with guesses := goldenMeta.guesses.push goldenMeta.guesses[0]! } + (CircuitMeta.serSection dupAddr).toOption.isNone && + (CircuitMeta.serSection dupFun).toOption.isNone && + (CircuitMeta.serSection dupGroup).toOption.isNone && + (CircuitMeta.serSection dupGuess).toOption.isNone) + itBool "circuit_meta: writer enforces field invariants" + (let conflictFuel : CircuitMeta := { + byAddress := #[(repAddr 0x01, { fuelParam := some "n", noFuel := true })] + } + let zeroUnroll : CircuitMeta := { + byAddress := #[(repAddr 0x01, { unroll := some 0 })] + } + let zeroLanes : CircuitMeta := { + byAddress := #[(repAddr 0x01, { lanes := some 0 })] + } + let emptyGroup : CircuitMeta := { + byAddress := #[(repAddr 0x01, { group := some "" })] + } + let zeroLimbs : CircuitMeta := { + byAddress := #[(repAddr 0x01, { repr := some (.limbs 0 64) })] + } + let zeroFlat : CircuitMeta := { + byAddress := #[(repAddr 0x01, { repr := some (.flatArray 0) })] + } + [conflictFuel, zeroUnroll, zeroLanes, emptyGroup, zeroLimbs, zeroFlat].all fun cm => + (CircuitMeta.serSection cm).toOption.isNone) + it "circuit_meta: §7 appends cleanly with byte-identical header/Merkle root/§1..§6 prefix" do + let env := mkSampleEnv () + let plainBytes := (serEnv env).toOption.getD ByteArray.empty + let withMetaBytes := (serEnvWithCircuitMeta env (some goldenMeta)).toOption.getD ByteArray.empty + let appendedBytes := (appendCircuitMetaSection plainBytes goldenMeta).toOption.getD ByteArray.empty + expect (!plainBytes.isEmpty && + withMetaBytes == appendedBytes && + withMetaBytes.size == plainBytes.size + expectedGoldenSectionBytes.size && + withMetaBytes.extract 0 plainBytes.size == plainBytes) + it "circuit_meta: Lean deEnv / deEnvWithCircuitMeta / deEnvVerifiedLazy decode §7" do + let env := mkSampleEnv () + let withMetaBytes := (serEnvWithCircuitMeta env (some goldenMeta)).toOption.getD ByteArray.empty + let fullDecodeOk := + match deEnvWithCircuitMeta withMetaBytes, deEnv withMetaBytes, deEnvVerifiedLazy withMetaBytes with + | .ok (e1, some cm1), .ok e2, .ok parts => + cm1 == goldenMeta && + parts.circuitMeta == some goldenMeta && + e1.merkleRoot == env.merkleRoot && + e2.merkleRoot == env.merkleRoot && + parts.env.merkleRoot == env.merkleRoot + | _, _, _ => false + expect fullDecodeOk + it "circuit_meta: legacy .ixe without §7 decodes to none" do + let env := mkSampleEnv () + let plainBytes := (serEnv env).toOption.getD ByteArray.empty + let legacyDecodeNone := + match deEnvWithCircuitMeta plainBytes, deEnvVerifiedLazy plainBytes with + | .ok (e1, none), .ok parts => + parts.circuitMeta.isNone && e1.merkleRoot == env.merkleRoot + | _, _ => false + expect legacyDecodeNone + it "circuit_meta: Rust rsDeEnv / deEnvAnon / rsDeEnvAnon accept .ixe with §7" do + let env := mkSampleEnv () + let withMetaBytes := (serEnvWithCircuitMeta env (some goldenMeta)).toOption.getD ByteArray.empty + let rustReadersOk := + match rsDeEnv withMetaBytes, deEnvAnon withMetaBytes, rsDeEnvAnon withMetaBytes with + | .ok eFull, .ok eLazy, .ok eAnon => + eFull.merkleRoot == env.merkleRoot && + eLazy.merkleRoot == env.merkleRoot && + eAnon.merkleRoot == env.merkleRoot + | _, _, _ => false + expect rustReadersOk + it "circuit_meta: Lean+Rust reject bad version in §7" do + let plainBytes := (serEnv (mkSampleEnv ())).toOption.getD ByteArray.empty + expect (allFullReadersReject (plainBytes ++ patchByte expectedGoldenSectionBytes 4 2)) + it "circuit_meta: Lean+Rust reject reserved header flag in §7" do + let plainBytes := (serEnv (mkSampleEnv ())).toOption.getD ByteArray.empty + expect (allFullReadersReject (plainBytes ++ patchByte expectedGoldenSectionBytes 5 0x20)) + it "circuit_meta: Lean+Rust reject invalid rangeCheck tag in §7" do + let plainBytes := (serEnv (mkSampleEnv ())).toOption.getD ByteArray.empty + expect (allFullReadersReject (plainBytes ++ patchByte expectedGoldenSectionBytes 5 0x03)) + it "circuit_meta: Lean+Rust reject reserved aiurConfig bit in §7" do + let plainBytes := (serEnv (mkSampleEnv ())).toOption.getD ByteArray.empty + expect (allFullReadersReject (plainBytes ++ patchByte expectedGoldenSectionBytes 8 0x80)) + it "circuit_meta: Lean+Rust reject reserved budget bit in §7" do + let plainBytes := (serEnv (mkSampleEnv ())).toOption.getD ByteArray.empty + expect (allFullReadersReject (plainBytes ++ patchByte expectedGoldenSectionBytes 9 0x20)) + it "circuit_meta: Lean+Rust reject truncated §7 section" do + let plainBytes := (serEnv (mkSampleEnv ())).toOption.getD ByteArray.empty + let truncatedSec := plainBytes ++ expectedGoldenSectionBytes.extract 0 (expectedGoldenSectionBytes.size - 1) + expect (allFullReadersReject truncatedSec) + it "circuit_meta: Lean+Rust reject trailing bytes after §7" do + let withMetaBytes := (serEnvWithCircuitMeta (mkSampleEnv ()) (some goldenMeta)).toOption.getD ByteArray.empty + expect (allFullReadersReject (withMetaBytes ++ ByteArray.mk #[0x00])) + it "circuit_meta: legacy trailing garbage still rejected by Lean+Rust" do + let plainBytes := (serEnv (mkSampleEnv ())).toOption.getD ByteArray.empty + expect (allFullReadersReject (plainBytes ++ ByteArray.mk #[0x00]) && + allFullReadersReject (plainBytes ++ ByteArray.mk #[0x00, 0x00])) end Tests.Ix.CircuitMeta diff --git a/Tests/Ix/Claim.lean b/Tests/Ix/Claim.lean index 9ef725820f..8f4066eeb4 100644 --- a/Tests/Ix/Claim.lean +++ b/Tests/Ix/Claim.lean @@ -7,10 +7,12 @@ public import Ix.Claim public import Ix.SpecDigest public import Tests.Gen.Claim -open LSpec SlimCheck +open LSpec LSpec.Prop open Ixon (runGet) open Ix (RevealConstructorInfo RevealRecursorRule RevealConstantInfo Claim) +set_option compiler.extract_closed false + /-! ## Roundtrip helper -/ def claimSerde (c : Claim) : Bool := @@ -27,73 +29,73 @@ def proofSerde (p : Ixon.Proof) : Bool := /-! ## Unit tests -/ -private def addr1 : Address := Address.blake3 "hello".toUTF8 -private def addr2 : Address := Address.blake3 "world".toUTF8 -private def addr3 : Address := Address.blake3 "test".toUTF8 +private def mkAddr1 (_ : Unit) : Address := Address.blake3 "hello".toUTF8 +private def mkAddr2 (_ : Unit) : Address := Address.blake3 "world".toUTF8 +private def mkAddr3 (_ : Unit) : Address := Address.blake3 "test".toUTF8 /-- This specification set, a stand-in binding hash, the standard axioms only. The same fixture as `test_ctx` in `crates/ixon/src/proof.rs`. -/ -private def ctx : Ix.ClaimContext := +private def mkCtx (_ : Unit) : Ix.ClaimContext := { spec := Ix.SpecDigest.specDigest.toOption.getD default binding := Address.blake3 "binding".toUTF8 axioms := none } -def claimUnits : TestSeq := +def claimUnits : LSpec.Spec := do -- Typechecking claims: both no-asm and with-asm forms. - test "Eval no-asm roundtrip" (claimSerde (.eval ctx addr1 addr2 none)) - ++ test "Eval with-asm roundtrip" - (claimSerde (.eval ctx addr1 addr2 (some addr3))) - ++ test "Check no-asm roundtrip" (claimSerde (.check ctx addr1 none)) - ++ test "Check with-asm roundtrip" - (claimSerde (.check ctx addr1 (some addr2))) - ++ test "CheckEnv no-asm roundtrip" (claimSerde (.checkEnv ctx addr1 none)) - ++ test "CheckEnv with-asm roundtrip" - (claimSerde (.checkEnv ctx addr1 (some addr2))) + itBool "Eval no-asm roundtrip" (claimSerde (.eval (mkCtx ()) (mkAddr1 ()) (mkAddr2 ()) none)) + itBool "Eval with-asm roundtrip" + (claimSerde (.eval (mkCtx ()) (mkAddr1 ()) (mkAddr2 ()) (some (mkAddr3 ())))) + itBool "Check no-asm roundtrip" (claimSerde (.check (mkCtx ()) (mkAddr1 ()) none)) + itBool "Check with-asm roundtrip" + (claimSerde (.check (mkCtx ()) (mkAddr1 ()) (some (mkAddr2 ())))) + itBool "CheckEnv no-asm roundtrip" (claimSerde (.checkEnv (mkCtx ()) (mkAddr1 ()) none)) + itBool "CheckEnv with-asm roundtrip" + (claimSerde (.checkEnv (mkCtx ()) (mkAddr1 ()) (some (mkAddr2 ())))) -- Contains - ++ test "Contains roundtrip" (claimSerde (.contains addr1 addr2)) + itBool "Contains roundtrip" (claimSerde (.contains (mkAddr1 ()) (mkAddr2 ()))) -- Catalog (the first multi-byte claim tag) - ++ test "Catalog roundtrip" (claimSerde (.catalog addr1)) - ++ test "CheckEnv under a literal class roundtrip" - (claimSerde (.checkEnv { ctx with literalClass := true } addr1 none)) + itBool "Catalog roundtrip" (claimSerde (.catalog (mkAddr1 ()))) + itBool "CheckEnv under a literal class roundtrip" + (claimSerde (.checkEnv { mkCtx () with literalClass := true } (mkAddr1 ()) none)) -- Reveal claim variants (carried over from previous suite) - ++ test "Reveal defn safety-only" (claimSerde (.reveal addr1 + itBool "Reveal defn safety-only" (claimSerde (.reveal (mkAddr1 ()) (.defn none (some .safe) none none none none) none)) - ++ test "Reveal defn all fields" (claimSerde (.reveal addr1 - (.defn (some .defn) (some .safe) (some 3) (some addr2) (some addr3) - (some { alloc := .noAlloc, boundedStack := true })) (some addr3))) - ++ test "Reveal axio with type" (claimSerde (.reveal addr1 - (.axio none none (some addr2)) none)) - ++ test "Reveal recr with rules" (claimSerde (.reveal addr1 + itBool "Reveal defn all fields" (claimSerde (.reveal (mkAddr1 ()) + (.defn (some .defn) (some .safe) (some 3) (some (mkAddr2 ())) (some (mkAddr3 ())) + (some { alloc := .noAlloc, boundedStack := true })) (some (mkAddr3 ())))) + itBool "Reveal axio with type" (claimSerde (.reveal (mkAddr1 ()) + (.axio none none (some (mkAddr2 ()))) none)) + itBool "Reveal recr with rules" (claimSerde (.reveal (mkAddr1 ()) (.recr (some true) none (some 2) none none none none none - (some #[⟨0, 3, addr2⟩])) none)) - ++ test "Reveal muts with component" (claimSerde (.reveal addr1 + (some #[⟨0, 3, mkAddr2 ()⟩])) none)) + itBool "Reveal muts with component" (claimSerde (.reveal (mkAddr1 ()) (.muts #[(0, .defn (some .defn) (some .safe) none none none (some { alloc := .noRc, boundedStack := false }))]) none)) - ++ test "Reveal muts constructor field modes" (claimSerde (.reveal addr1 + itBool "Reveal muts constructor field modes" (claimSerde (.reveal (mkAddr1 ()) (.muts #[(0, .indc none none none none none (some #[(0, { fieldModes := some #[.inherited, .shared] }), - (1, { fieldModes := some #[] })]))]) (some addr2))) - ++ test "Reveal cPrj" (claimSerde (.reveal addr1 - (.cPrj (some 0) (some 1) (some addr2)) none)) - ++ test "Reveal rPrj" (claimSerde (.reveal addr1 - (.rPrj (some 2) (some addr2)) none)) - ++ test "Reveal iPrj" (claimSerde (.reveal addr1 - (.iPrj (some 3) (some addr2)) none)) - ++ test "Reveal dPrj" (claimSerde (.reveal addr1 - (.dPrj (some 0) (some addr2)) none)) - ++ test "Reveal defn all none" (claimSerde (.reveal addr1 + (1, { fieldModes := some #[] })]))]) (some (mkAddr2 ())))) + itBool "Reveal cPrj" (claimSerde (.reveal (mkAddr1 ()) + (.cPrj (some 0) (some 1) (some (mkAddr2 ()))) none)) + itBool "Reveal rPrj" (claimSerde (.reveal (mkAddr1 ()) + (.rPrj (some 2) (some (mkAddr2 ()))) none)) + itBool "Reveal iPrj" (claimSerde (.reveal (mkAddr1 ()) + (.iPrj (some 3) (some (mkAddr2 ()))) none)) + itBool "Reveal dPrj" (claimSerde (.reveal (mkAddr1 ()) + (.dPrj (some 0) (some (mkAddr2 ()))) none)) + itBool "Reveal defn all none" (claimSerde (.reveal (mkAddr1 ()) (.defn none none none none none none) none)) - ++ test "Reveal quot" (claimSerde (.reveal addr1 - (.quot (some .type) (some 1) (some addr2)) none)) + itBool "Reveal quot" (claimSerde (.reveal (mkAddr1 ()) + (.quot (some .type) (some 1) (some (mkAddr2 ()))) none)) -- Compile claims - ++ test "Compile immortal roundtrip" (claimSerde (.compile - { env := addr1, roleTable := none, target := addr2, policy := .immortal, abiArity := 2, elfHash := addr3 })) - ++ test "Compile zeroRc roundtrip" (claimSerde (.compile - { env := addr1, roleTable := some addr2, target := addr2, policy := .zeroRc, abiArity := 3, elfHash := addr3 })) - ++ test "Compile plainRc roundtrip" (claimSerde (.compile - { env := addr1, roleTable := some addr3, target := addr2, policy := .plainRc, abiArity := 1, elfHash := addr3 })) - ++ test "Compile proof roundtrip" (proofSerde - { claim := .compile { env := addr1, roleTable := some addr1, target := addr2, policy := .zeroRc, abiArity := 2, elfHash := addr3 } + itBool "Compile immortal roundtrip" (claimSerde (.compile + { env := mkAddr1 (), roleTable := none, target := mkAddr2 (), policy := .immortal, abiArity := 2, elfHash := mkAddr3 () })) + itBool "Compile zeroRc roundtrip" (claimSerde (.compile + { env := mkAddr1 (), roleTable := some (mkAddr2 ()), target := mkAddr2 (), policy := .zeroRc, abiArity := 3, elfHash := mkAddr3 () })) + itBool "Compile plainRc roundtrip" (claimSerde (.compile + { env := mkAddr1 (), roleTable := some (mkAddr3 ()), target := mkAddr2 (), policy := .plainRc, abiArity := 1, elfHash := mkAddr3 () })) + itBool "Compile proof roundtrip" (proofSerde + { claim := .compile { env := mkAddr1 (), roleTable := some (mkAddr1 ()), target := mkAddr2 (), policy := .zeroRc, abiArity := 2, elfHash := mkAddr3 () } proof := ⟨#[0x10, 0x20, 0x30]⟩ }) /-! ## Byte-level encoding tests @@ -106,118 +108,131 @@ def claimUnits : TestSeq := `0x01`+32-byte address for `some`). -/ -def claimEncodingTests : TestSeq := - let evalBytes := Claim.ser (.eval ctx addr1 addr2 none) - let evalWithAsm := Claim.ser (.eval ctx addr1 addr2 (some addr3)) - let checkBytes := Claim.ser (.check ctx addr1 none) - let checkWithAsm := Claim.ser (.check ctx addr1 (some addr2)) - let checkEnvBytes := Claim.ser (.checkEnv ctx addr1 none) - let containsBytes := Claim.ser (.contains addr1 addr2) - let revealSafetyOnly := Claim.ser - (.reveal addr1 (.defn none (some .safe) none none none none) none) - let revealAllFields := Claim.ser (.reveal addr1 - (.defn (some .defn) (some .safe) (some 3) (some addr2) (some addr3) - (some { alloc := .noAlloc, boundedStack := true })) (some addr3)) - let retiredRefused : Bool := match Claim.de (checkBytes.set! 2 1) with - | .error e => (e.splitOn "erased-lean-v1 is retired").length > 1 - | .ok _ => false +def claimEncodingTests : LSpec.Spec := do + let mkEvalBytes (_ : Unit) : ByteArray := Claim.ser (.eval (mkCtx ()) (mkAddr1 ()) (mkAddr2 ()) none) + let mkEvalWithAsm (_ : Unit) : ByteArray := Claim.ser (.eval (mkCtx ()) (mkAddr1 ()) (mkAddr2 ()) (some (mkAddr3 ()))) + let mkCheckBytes (_ : Unit) : ByteArray := Claim.ser (.check (mkCtx ()) (mkAddr1 ()) none) + let mkCheckWithAsm (_ : Unit) : ByteArray := Claim.ser (.check (mkCtx ()) (mkAddr1 ()) (some (mkAddr2 ()))) + let mkCheckEnvBytes (_ : Unit) : ByteArray := Claim.ser (.checkEnv (mkCtx ()) (mkAddr1 ()) none) + let mkContainsBytes (_ : Unit) : ByteArray := Claim.ser (.contains (mkAddr1 ()) (mkAddr2 ())) + let mkRevealSafetyOnly (_ : Unit) : ByteArray := Claim.ser + (.reveal (mkAddr1 ()) (.defn none (some .safe) none none none none) none) + let mkRevealAllFields (_ : Unit) : ByteArray := Claim.ser (.reveal (mkAddr1 ()) + (.defn (some .defn) (some .safe) (some 3) (some (mkAddr2 ())) (some (mkAddr3 ())) + (some { alloc := .noAlloc, boundedStack := true })) (some (mkAddr3 ()))) -- Two scope bytes follow each claim tag, then the 65-byte context. -- Eval = 133 bytes; with asm = 165 - test "Eval tag byte is 0xE3" (evalBytes.data[0]! == 0xE3) - ++ test "Eval scope is object format 4, erased-lean-v2" - (evalBytes.data[1]! == 4 && evalBytes.data[2]! == 3) - ++ test "Eval context follows the scope" - (evalBytes.extract 3 35 == ctx.spec.hash - && evalBytes.extract 35 67 == ctx.binding.hash - && evalBytes.data[67]! == 0) - ++ test "Eval no-asm size is 133" (evalBytes.size == 133) - ++ test "Eval with-asm size is 165" (evalWithAsm.size == 165) + itBool "Eval tag byte is 0xE3" ((mkEvalBytes ()).get! 0 == (0xE3 : UInt8)) + it "Eval scope is object format 4, erased-lean-v2" do + let evalBytes := mkEvalBytes () + expect (evalBytes.get! 1 == (4 : UInt8) && evalBytes.get! 2 == (3 : UInt8)) + it "Eval context follows the scope" do + let ctx := mkCtx () + let evalBytes := Claim.ser (.eval ctx (mkAddr1 ()) (mkAddr2 ()) none) + expect (evalBytes.extract 3 35 == ctx.spec.hash + && evalBytes.extract 35 67 == ctx.binding.hash + && evalBytes.get! 67 == (0 : UInt8)) + itBool "Eval no-asm size is 133" ((mkEvalBytes ()).size == 133) + itBool "Eval with-asm size is 165" ((mkEvalWithAsm ()).size == 165) -- Check: tag + scope + context + 32 + option = 101 bytes; with asm = 133 - ++ test "Check tag byte is 0xE4" (checkBytes.data[0]! == 0xE4) - ++ test "Check no-asm size is 101" (checkBytes.size == 101) - ++ test "Check with-asm size is 133" (checkWithAsm.size == 133) + itBool "Check tag byte is 0xE4" ((mkCheckBytes ()).get! 0 == (0xE4 : UInt8)) + itBool "Check no-asm size is 101" ((mkCheckBytes ()).size == 101) + itBool "Check with-asm size is 133" ((mkCheckWithAsm ()).size == 133) -- CheckEnv: tag + scope + context + 32 + option = 101 bytes - ++ test "CheckEnv tag byte is 0xE5" (checkEnvBytes.data[0]! == 0xE5) - ++ test "CheckEnv no-asm size is 101" (checkEnvBytes.size == 101) - ++ test "Check for the retired erased-lean-v1 validator is refused" retiredRefused - ++ test "Check with an axioms commitment roundtrips" - (claimSerde (.check { ctx with axioms := some addr3 } addr1 none)) + itBool "CheckEnv tag byte is 0xE5" ((mkCheckEnvBytes ()).get! 0 == (0xE5 : UInt8)) + itBool "CheckEnv no-asm size is 101" ((mkCheckEnvBytes ()).size == 101) + it "Check for the retired erased-lean-v1 validator is refused" do + let checkBytes := mkCheckBytes () + let retiredRefused : Bool := match Claim.de (checkBytes.set! 2 1) with + | .error e => (e.splitOn "erased-lean-v1 is retired").length > 1 + | .ok _ => false + expect retiredRefused + itBool "Check with an axioms commitment roundtrips" + (claimSerde (.check { mkCtx () with axioms := some (mkAddr3 ()) } (mkAddr1 ()) none)) -- Reveal claim: 0xE6 - ++ test "Reveal tag byte is 0xE6" (revealSafetyOnly.data[0]! == 0xE6) + itBool "Reveal tag byte is 0xE6" ((mkRevealSafetyOnly ()).get! 0 == (0xE6 : UInt8)) -- Reveal: tag + scope + commitment + variant + mask + safety + binders(none) = 39 - ++ test "Reveal safety-only defn size is 39" (revealSafetyOnly.size == 39) - ++ test "Reveal all-fields defn is larger" - (revealAllFields.size > revealSafetyOnly.size) + itBool "Reveal safety-only defn size is 39" ((mkRevealSafetyOnly ()).size == 39) + itBool "Reveal all-fields defn is larger" + (decide ((mkRevealAllFields ()).size > (mkRevealSafetyOnly ()).size)) -- Contains: tag + scope + two addresses = 67 - ++ test "Contains tag byte is 0xE7" (containsBytes.data[0]! == 0xE7) - ++ test "Contains size is 67" (containsBytes.size == 67) + itBool "Contains tag byte is 0xE7" ((mkContainsBytes ()).get! 0 == (0xE7 : UInt8)) + itBool "Contains size is 67" ((mkContainsBytes ()).size == 67) -- Compile: deterministic 103- and 135-byte wire vectors shared with IxCC.CompileClaim - ++ (let envHash : Address := ⟨ByteArray.mk (Array.replicate 32 0x11)⟩ - let target : Address := ⟨ByteArray.mk (Array.replicate 32 0x22)⟩ - let elfHash : Address := ⟨ByteArray.mk (Array.replicate 32 0x33)⟩ - let cc : Ix.CompileClaim := - { env := envHash, roleTable := none, target := target, policy := .plainRc, abiArity := 3 - elfHash := elfHash } - let compileBytes := Claim.ser (.compile cc) - -- The claim names the role table (validator `07`): `00` after `env` for an - -- environment without a role binding, `01` and the table's address otherwise. - let boundCc : Ix.CompileClaim := - { cc with roleTable := some ⟨ByteArray.mk (Array.replicate 32 0x44)⟩ } - let expectedBoundBytes : ByteArray := - ByteArray.mk (#[0xE8, 0x05, 0x04, 0x07] - ++ Array.replicate 32 0x11 ++ #[0x01] ++ Array.replicate 32 0x44 - ++ Array.replicate 32 0x22 ++ #[0x02, 0x03] ++ Array.replicate 32 0x33) - -- The former format (validator `06`, no role table) is refused. - let formerBytes : ByteArray := - ByteArray.mk (#[0xE8, 0x05, 0x04, 0x06] - ++ Array.replicate 32 0x11 ++ Array.replicate 32 0x22 - ++ #[0x02, 0x03] ++ Array.replicate 32 0x33) - let expectedCompileBytes : ByteArray := - ByteArray.mk (#[0xE8, 0x05, 0x04, 0x07] - ++ Array.replicate 32 0x11 ++ #[0x00] - ++ Array.replicate 32 0x22 - ++ #[0x02, 0x03] - ++ Array.replicate 32 0x33) - -- `abiArity`'s `N0` code at its boundaries; `IxCC/IxCCTests/Pipeline/Compiler.lean` - -- pins the same vectors for `IxCC.CompileClaim` (B4-2). `80 80` is 256. - let arityClaimBytes (arity : List UInt8) : ByteArray := - ByteArray.mk (#[0xE8, 0x05, 0x04, 0x07] ++ Array.replicate 32 0x11 ++ #[0x00] - ++ Array.replicate 32 0x22 ++ #[0x02] ++ arity.toArray ++ Array.replicate 32 0x33) - let arityVectors : List (UInt64 × List UInt8) := [ - (0, [0x00]), (5, [0x05]), (6, [0x06]), (127, [0x7F]), (128, [0x80, 0x00]), - (256, [0x80, 0x80]), (16511, [0xBF, 0xFF]), (16512, [0xC0, 0x00, 0x00]), - (18446744073709551615, [0xC3, 0x7F, 0xBF, 0xFE, 0xFE, 0xFE, 0xFF, 0xFF, 0xFF])] - let arityRejected : List (List UInt8) := - [[0xC4], [0xC3, 0x80, 0xBF, 0xFE, 0xFE, 0xFE, 0xFF, 0xFF, 0xFF]] - test "Compile wire header is E8 05 04 07" - (compileBytes.extract 0 4 == ⟨#[0xE8, 0x05, 0x04, 0x07]⟩) - ++ test "Compile wire size is 103 without a role table" (compileBytes.size == 103) - ++ test "Compile wire matches deterministic 103-byte vector" - (compileBytes == expectedCompileBytes) - ++ test "Compile with a role table matches deterministic 135-byte vector and roundtrips" - (Claim.ser (.compile boundCc) == expectedBoundBytes && - (Claim.de expectedBoundBytes).toOption == some (.compile boundCc)) - ++ test "Compile former format (validator 06, no role table) is refused" - ((Claim.de formerBytes).toOption.isNone && (Claim.de (formerBytes.set! 3 0x07)).toOption.isNone - && (Claim.de (expectedCompileBytes.set! 3 0x06)).toOption.isNone - && (Claim.de (expectedCompileBytes.set! 3 0x09)).toOption.isNone - && (Claim.de (expectedCompileBytes.set! 36 0x02)).toOption.isNone) - ++ test "Compile deterministic vector roundtrips via Claim.de" - ((Claim.de compileBytes).toOption == some (.compile cc)) - ++ test "Compile abiArity N0 vectors shared with IxCC.CompileClaim" - (arityVectors.all fun (arity, bytes) => - Claim.ser (.compile { cc with abiArity := arity }) == arityClaimBytes bytes && - (Claim.de (arityClaimBytes bytes)).toOption == some (.compile { cc with abiArity := arity })) - ++ test "Compile invalid and overflowing abiArity codes are refused" - (arityRejected.all fun bytes => (Claim.de (arityClaimBytes bytes)).toOption.isNone) - ++ test "Compile is not read under the role-binding (E8 03) or literal-class (E8 04) tags" - ((Claim.de (compileBytes.set! 1 0x03)).toOption.isNone - && (Claim.de (compileBytes.set! 1 0x04)).toOption.isNone) - ++ test "Compile proof (F8 00) wraps the compile claim" - (let proof : Ixon.Proof := { claim := .compile cc, proof := ⟨#[7]⟩ } - let bytes := Ixon.Proof.ser proof - bytes.extract 0 2 == ⟨#[0xF8, 0x00]⟩ && - (Ixon.Proof.de bytes).toOption.map (·.claim) == some (.compile cc))) + let mkCc (_ : Unit) : Ix.CompileClaim := + { env := ⟨ByteArray.mk (Array.replicate 32 0x11)⟩ + roleTable := none + target := ⟨ByteArray.mk (Array.replicate 32 0x22)⟩ + policy := .plainRc + abiArity := 3 + elfHash := ⟨ByteArray.mk (Array.replicate 32 0x33)⟩ } + let mkCompileBytes (_ : Unit) : ByteArray := Claim.ser (.compile (mkCc ())) + -- The claim names the role table (validator `07`): `00` after `env` for an + -- environment without a role binding, `01` and the table's address otherwise. + let mkBoundCc (_ : Unit) : Ix.CompileClaim := + { mkCc () with roleTable := some ⟨ByteArray.mk (Array.replicate 32 0x44)⟩ } + let mkExpectedBoundBytes (_ : Unit) : ByteArray := + ByteArray.mk (#[0xE8, 0x05, 0x04, 0x07] + ++ Array.replicate 32 0x11 ++ #[0x01] ++ Array.replicate 32 0x44 + ++ Array.replicate 32 0x22 ++ #[0x02, 0x03] ++ Array.replicate 32 0x33) + -- The former format (validator `06`, no role table) is refused. + let mkFormerBytes (_ : Unit) : ByteArray := + ByteArray.mk (#[0xE8, 0x05, 0x04, 0x06] + ++ Array.replicate 32 0x11 ++ Array.replicate 32 0x22 + ++ #[0x02, 0x03] ++ Array.replicate 32 0x33) + let mkExpectedCompileBytes (_ : Unit) : ByteArray := + ByteArray.mk (#[0xE8, 0x05, 0x04, 0x07] + ++ Array.replicate 32 0x11 ++ #[0x00] + ++ Array.replicate 32 0x22 + ++ #[0x02, 0x03] + ++ Array.replicate 32 0x33) + -- `abiArity`'s `N0` code at its boundaries; `IxCC/IxCCTests/Pipeline/Compiler.lean` + -- pins the same vectors for `IxCC.CompileClaim` (B4-2). `80 80` is 256. + let arityClaimBytes (arity : List UInt8) : ByteArray := + ByteArray.mk (#[0xE8, 0x05, 0x04, 0x07] ++ Array.replicate 32 0x11 ++ #[0x00] + ++ Array.replicate 32 0x22 ++ #[0x02] ++ arity.toArray ++ Array.replicate 32 0x33) + let arityVectors : List (UInt64 × List UInt8) := [ + (0, [0x00]), (5, [0x05]), (6, [0x06]), (127, [0x7F]), (128, [0x80, 0x00]), + (256, [0x80, 0x80]), (16511, [0xBF, 0xFF]), (16512, [0xC0, 0x00, 0x00]), + (18446744073709551615, [0xC3, 0x7F, 0xBF, 0xFE, 0xFE, 0xFE, 0xFF, 0xFF, 0xFF])] + let arityRejected : List (List UInt8) := + [[0xC4], [0xC3, 0x80, 0xBF, 0xFE, 0xFE, 0xFE, 0xFF, 0xFF, 0xFF]] + itBool "Compile wire header is E8 05 04 07" + ((mkCompileBytes ()).extract 0 4 == ⟨#[0xE8, 0x05, 0x04, 0x07]⟩) + itBool "Compile wire size is 103 without a role table" ((mkCompileBytes ()).size == 103) + itBool "Compile wire matches deterministic 103-byte vector" + (mkCompileBytes () == mkExpectedCompileBytes ()) + itBool "Compile with a role table matches deterministic 135-byte vector and roundtrips" + (let boundCc := mkBoundCc () + let expectedBoundBytes := mkExpectedBoundBytes () + Claim.ser (.compile boundCc) == expectedBoundBytes && + (Claim.de expectedBoundBytes).toOption == some (.compile boundCc)) + itBool "Compile former format (validator 06, no role table) is refused" + (let formerBytes := mkFormerBytes () + let expectedCompileBytes := mkExpectedCompileBytes () + (Claim.de formerBytes).toOption.isNone && (Claim.de (formerBytes.set! 3 0x07)).toOption.isNone + && (Claim.de (expectedCompileBytes.set! 3 0x06)).toOption.isNone + && (Claim.de (expectedCompileBytes.set! 3 0x09)).toOption.isNone + && (Claim.de (expectedCompileBytes.set! 36 0x02)).toOption.isNone) + itBool "Compile deterministic vector roundtrips via Claim.de" + ((Claim.de (mkCompileBytes ())).toOption == some (.compile (mkCc ()))) + itBool "Compile abiArity N0 vectors shared with IxCC.CompileClaim" + (let cc := mkCc () + arityVectors.all fun (arity, bytes) => + Claim.ser (.compile { cc with abiArity := arity }) == arityClaimBytes bytes && + (Claim.de (arityClaimBytes bytes)).toOption == some (.compile { cc with abiArity := arity })) + itBool "Compile invalid and overflowing abiArity codes are refused" + (arityRejected.all fun bytes => (Claim.de (arityClaimBytes bytes)).toOption.isNone) + itBool "Compile is not read under the role-binding (E8 03) or literal-class (E8 04) tags" + (let compileBytes := mkCompileBytes () + (Claim.de (compileBytes.set! 1 0x03)).toOption.isNone + && (Claim.de (compileBytes.set! 1 0x04)).toOption.isNone) + itBool "Compile proof (F8 00) wraps the compile claim" + (let cc := mkCc () + let proof : Ixon.Proof := { claim := .compile cc, proof := ⟨#[7]⟩ } + let bytes := Ixon.Proof.ser proof + bytes.extract 0 2 == ⟨#[0xF8, 0x00]⟩ && + (Ixon.Proof.de bytes).toOption.map (·.claim) == some (.compile cc)) /-! ## Catalog claim: wire pin + Rust digest parity @@ -229,64 +244,67 @@ def claimEncodingTests : TestSeq := without one of the pins going red. -/ -private def catMembers : Address := Address.blake3 "members".toUTF8 +private def mkCatMembers (_ : Unit) : Address := Address.blake3 "members".toUTF8 /-- Must equal the Rust pin in `proof.rs::catalog_claim_wire_bytes_pinned`. -/ private def catalogDigestPin : String := "4f5686bd1a8386231370703d58223aca769c82c835964d4914ca41305a8030f3" -def catalogClaimTests : TestSeq := - let bytes := Claim.ser (.catalog catMembers) - let proof : Ixon.Proof := { claim := .catalog catMembers, proof := .empty } - let proofBytes := Ixon.Proof.ser proof - let proofRoundtrips : Bool := match Ixon.Proof.de proofBytes with - | .ok p => p.claim == proof.claim && p.proof == proof.proof - | .error _ => false - test "Catalog tag is 2 bytes 0xE8 0x00 (TagN 4 0xE 8)" - (bytes.data[0]! == 0xE8 && bytes.data[1]! == 0x00) - ++ test "Catalog scope is object format 4, erased-lean-v2" - (bytes.data[2]! == 4 && bytes.data[3]! == 3) - ++ test "Catalog is the scope and the members root, 36 bytes" (bytes.size == 4 + 32) - ++ test "Catalog digest parity with Rust pin" - (toString (Address.blake3 bytes) == catalogDigestPin) - ++ test "Catalog proof wrapper tag is single-byte 0xF5" - (proofBytes.data[0]! == 0xF5) - ++ test "Catalog proof wrapper roundtrips" proofRoundtrips +def catalogClaimTests : LSpec.Spec := do + let mkBytes := fun () => Claim.ser (.catalog (mkCatMembers ())) + it "Catalog tag is 2 bytes 0xE8 0x00 (TagN 4 0xE 8)" do + let bytes := mkBytes () + expect (bytes.get! 0 == (0xE8 : UInt8) && bytes.get! 1 == (0x00 : UInt8)) + it "Catalog scope is object format 4, erased-lean-v2" do + let bytes := mkBytes () + expect (bytes.get! 2 == (4 : UInt8) && bytes.get! 3 == (3 : UInt8)) + itBool "Catalog is the scope and the members root, 36 bytes" ((mkBytes ()).size == 4 + 32) + itBool "Catalog digest parity with Rust pin" + (toString (Address.blake3 (mkBytes ())) == catalogDigestPin) + it "Catalog proof wrapper tag is single-byte 0xF5" do + let proof : Ixon.Proof := { claim := .catalog (mkCatMembers ()), proof := .empty } + let proofBytes := Ixon.Proof.ser proof + expect (proofBytes.get! 0 == (0xF5 : UInt8)) + it "Catalog proof wrapper roundtrips" do + let proof : Ixon.Proof := { claim := .catalog (mkCatMembers ()), proof := .empty } + let proofBytes := Ixon.Proof.ser proof + let proofRoundtrips : Bool := match Ixon.Proof.de proofBytes with + | .ok p => p.claim == proof.claim && p.proof == proof.proof + | .error _ => false + expect proofRoundtrips /-- A reveal mask bit beyond the variant's fields is refused, so one claim has one encoding. The Rust reader refuses the same bytes (`proof.rs::reveal_mask_refuses_unknown_bits`): a Reveal claim over the zero commitment, its variant byte, the one-byte mask, then `0x00` (`binders = none`). -/ -def revealMaskTests : TestSeq := - let header : Array UInt8 := #[0xE6, 0x04, 0x00] ++ Array.replicate 32 0 - let bytes (variant mask : UInt8) : ByteArray := ⟨header ++ #[variant, mask, 0x00]⟩ - test "Reveal defn with no fields reads" (Ix.Claim.de (bytes 0 0) matches .ok _) - ++ test "Reveal defn mask bit 5 reads valid DefAsserts" - (Ix.Claim.de ⟨header ++ #[0, 0x20, 0x06, 0x00]⟩ matches .ok _) - ++ test "Reveal defn mask bit 5 refuses alloc 3" - (Ix.Claim.de ⟨header ++ #[0, 0x20, 0x03, 0x00]⟩ matches .error _) - ++ test "Reveal defn mask bit 5 refuses code 8" - (Ix.Claim.de ⟨header ++ #[0, 0x20, 0x08, 0x00]⟩ matches .error _) - ++ test "Reveal defn mask bit 6 refused" (Ix.Claim.de (bytes 0 0x40) matches .error _) - ++ test "Reveal muts ctor mask bit 6 reads fieldModes" - (Ix.Claim.de ⟨header ++ #[8, 1, 1, 0, 1, 0x20, 1, 0, 0x40, 2, 0, 1, 0x00]⟩ matches .ok _) - ++ test "Reveal muts ctor fieldMode 2 refused" - (Ix.Claim.de ⟨header ++ #[8, 1, 1, 0, 1, 0x20, 1, 0, 0x40, 2, 0, 2, 0x00]⟩ matches .error _) - ++ test "Reveal muts ctor mask bit 7 refused" - (Ix.Claim.de ⟨header ++ #[8, 1, 1, 0, 1, 0x20, 1, 0, 0x80, 0x00, 0x00]⟩ matches .error _) - ++ test "Reveal binders opt tag 2 refused" - (Ix.Claim.de ⟨header ++ #[0, 0, 0x02]⟩ matches .error _) - ++ test "Reveal axio with no fields reads" (Ix.Claim.de (bytes 2 0) matches .ok _) - ++ test "Reveal axio mask bit 3 refused" (Ix.Claim.de (bytes 2 0x08) matches .error _) - ++ test "Reveal dprj mask bit 2 refused" (Ix.Claim.de (bytes 7 0x04) matches .error _) +def revealMaskTests : LSpec.Spec := do + let mkHeader (_ : Unit) : Array UInt8 := #[0xE6, 0x04, 0x00] ++ Array.replicate 32 0 + let bytes (variant mask : UInt8) : ByteArray := ⟨mkHeader () ++ #[variant, mask, 0x00]⟩ + itBool "Reveal defn with no fields reads" (Ix.Claim.de (bytes 0 0) matches .ok _) + itBool "Reveal defn mask bit 5 reads valid DefAsserts" + (Ix.Claim.de ⟨mkHeader () ++ #[0, 0x20, 0x06, 0x00]⟩ matches .ok _) + itBool "Reveal defn mask bit 5 refuses alloc 3" + (Ix.Claim.de ⟨mkHeader () ++ #[0, 0x20, 0x03, 0x00]⟩ matches .error _) + itBool "Reveal defn mask bit 5 refuses code 8" + (Ix.Claim.de ⟨mkHeader () ++ #[0, 0x20, 0x08, 0x00]⟩ matches .error _) + itBool "Reveal defn mask bit 6 refused" (Ix.Claim.de (bytes 0 0x40) matches .error _) + itBool "Reveal muts ctor mask bit 6 reads fieldModes" + (Ix.Claim.de ⟨mkHeader () ++ #[8, 1, 1, 0, 1, 0x20, 1, 0, 0x40, 2, 0, 1, 0x00]⟩ matches .ok _) + itBool "Reveal muts ctor fieldMode 2 refused" + (Ix.Claim.de ⟨mkHeader () ++ #[8, 1, 1, 0, 1, 0x20, 1, 0, 0x40, 2, 0, 2, 0x00]⟩ matches .error _) + itBool "Reveal muts ctor mask bit 7 refused" + (Ix.Claim.de ⟨mkHeader () ++ #[8, 1, 1, 0, 1, 0x20, 1, 0, 0x80, 0x00, 0x00]⟩ matches .error _) + itBool "Reveal binders opt tag 2 refused" + (Ix.Claim.de ⟨mkHeader () ++ #[0, 0, 0x02]⟩ matches .error _) + itBool "Reveal axio with no fields reads" (Ix.Claim.de (bytes 2 0) matches .ok _) + itBool "Reveal axio mask bit 3 refused" (Ix.Claim.de (bytes 2 0x08) matches .error _) + itBool "Reveal dprj mask bit 2 refused" (Ix.Claim.de (bytes 7 0x04) matches .error _) /-! ## Suite -/ -public def Tests.Claim.suite : List TestSeq := [ - claimUnits, - claimEncodingTests, - catalogClaimTests, - revealMaskTests, - checkIO "Claim serde roundtrips" (∀ c : Claim, claimSerde c), -] - +public def Tests.Claim.suite : LSpec.Spec := do + claimUnits + claimEncodingTests + catalogClaimTests + revealMaskTests + prop "Claim serde roundtrips" fun (c : Claim) => claimSerde c diff --git a/Tests/Ix/ClaimPolicy.lean b/Tests/Ix/ClaimPolicy.lean index 641c8d816e..a6eb94059f 100644 --- a/Tests/Ix/ClaimPolicy.lean +++ b/Tests/Ix/ClaimPolicy.lean @@ -32,13 +32,15 @@ namespace Tests.ClaimPolicy open LSpec Ix.Cli.ClaimPolicy Ix.Cli.TableAdmission +set_option compiler.extract_closed false + private def addr (s : String) : Address := Address.blake3 s.toUTF8 /-- This build's specification digest. -/ -private def spec : Address := Ix.SpecDigest.specDigest.toOption.getD default +private def mkSpec (_ : Unit) : Address := Ix.SpecDigest.specDigest.toOption.getD default -private def ctx : Ix.ClaimContext := - { spec, binding := Ix.Kernel.Reader.defaultTableAddress.toOption.getD default, +private def mkCtx (_ : Unit) : Ix.ClaimContext := + { spec := mkSpec (), binding := Ix.Kernel.Reader.defaultTableAddress.toOption.getD default, axioms := none } /-- Whether `pol` admits `claim`. -/ @@ -67,37 +69,37 @@ private def allBut (except : String) : Policy := binding := except != "binding" } /-- A claim of each kind that no theorem states, with its kind and its flag. -/ -private def untyped : List (String × Ix.Claim × Policy) := [ - ("eval", .eval ctx (addr "in") (addr "out") none, { eval := true }), - ("reveal", .reveal (addr "comm") (.axio none none none) none, { reveal := true }), - ("contains", .contains (addr "tree") (addr "const"), { contains := true }), - ("binding", .binding spec (addr "binding"), { binding := true })] +private def mkUntyped (_ : Unit) : List (String × (Unit → Ix.Claim) × Policy) := [ + ("eval", fun () => .eval (mkCtx ()) (addr "in") (addr "out") none, { eval := true }), + ("reveal", fun () => .reveal (addr "comm") (.axio none none none) none, { reveal := true }), + ("contains", fun () => .contains (addr "tree") (addr "const"), { contains := true }), + ("binding", fun () => .binding (mkSpec ()) (addr "binding"), { binding := true })] /-- Refusals by kind and by specification set. -/ -def kindTests : TestSeq := - let catalog : Ix.Claim := .catalog (addr "members") - let otherSpec := addr "another specification set" - untyped.foldl (init := TestSeq.done) (fun acc (kind, claim, flag) => - acc ++ test s!"a {kind} claim is refused by default, naming --allow-{kind}-claim" - (refusesSaying {} claim s!"--allow-{kind}-claim") - ++ test s!" accepted under --allow-{kind}-claim" (admits flag claim) - ++ test s!" and refused under every other flag" (!admits (allBut kind) claim)) - ++ test "a catalog is refused by default, naming --ixc" (refusesSaying {} catalog "--ixc") - ++ test " and under every flag" (!admits everyFlag catalog) - ++ test "a typing claim under another specification set is refused" - (refusesSaying {} (.checkEnv { ctx with spec := otherSpec } (addr "root") none) - "specification set") - ++ test " under every flag" (!admits everyFlag (.check { ctx with spec := otherSpec } (addr "c") none)) - ++ test " and under a table the kernel admits" - (!admits everyFlag (.checkEnv { ctx with spec := otherSpec, binding := addr "table" } - (addr "root") none) (tableAdmitted := true)) - ++ test " and as an evaluation" (!admits everyFlag (.eval { ctx with spec := otherSpec } - (addr "in") (addr "out") none)) - ++ test "a binding claim under another specification set is refused under its flag" - (!admits { binding := true } (.binding otherSpec (addr "binding"))) - ++ test "the kind flags accept no conditional typing claim" - (!admits { reveal := true, contains := true, binding := true } - (.checkEnv { ctx with axioms := some (addr "axioms") } (addr "root") none)) +def kindTests : LSpec.Spec := do + let mkCatalog (_ : Unit) : Ix.Claim := .catalog (addr "members") + let mkOtherSpec := fun () => addr "another specification set" + for (kind, mkClaim, flag) in mkUntyped () do + itBool s!"a {kind} claim is refused by default, naming --allow-{kind}-claim" + (refusesSaying {} (mkClaim ()) s!"--allow-{kind}-claim") + itBool s!" accepted under --allow-{kind}-claim" (admits flag (mkClaim ())) + itBool s!" and refused under every other flag" (!admits (allBut kind) (mkClaim ())) + itBool "a catalog is refused by default, naming --ixc" (refusesSaying {} (mkCatalog ()) "--ixc") + itBool " and under every flag" (!admits everyFlag (mkCatalog ())) + itBool "a typing claim under another specification set is refused" + (refusesSaying {} (.checkEnv { mkCtx () with spec := mkOtherSpec () } (addr "root") none) + "specification set") + itBool " under every flag" (!admits everyFlag (.check { mkCtx () with spec := mkOtherSpec () } (addr "c") none)) + itBool " and under a table the kernel admits" + (!admits everyFlag (.checkEnv { mkCtx () with spec := mkOtherSpec (), binding := addr "table" } + (addr "root") none) (tableAdmitted := true)) + itBool " and as an evaluation" (!admits everyFlag (.eval { mkCtx () with spec := mkOtherSpec () } + (addr "in") (addr "out") none)) + itBool "a binding claim under another specification set is refused under its flag" + (!admits { binding := true } (.binding (mkOtherSpec ()) (addr "binding"))) + itBool "the kind flags accept no conditional typing claim" + (!admits { reveal := true, contains := true, binding := true } + (.checkEnv { mkCtx () with axioms := some (addr "axioms") } (addr "root") none)) /-- Whether `claim`'s statement says every one of `texts`. -/ private def statementSays (claim : Ix.Claim) (texts : List String) @@ -108,122 +110,126 @@ private def statementSays (claim : Ix.Claim) (texts : List String) | .error _ => false /-- The verifier's report of each kind. -/ -def statementTests : TestSeq := - let defaultTable := ctx.binding - test "an unconditional check-env names its kind, subject and conditions" - (statementSays (.checkEnv ctx (addr "root") none) +def statementTests : LSpec.Spec := do + it "an unconditional check-env names its kind, subject and conditions" do + let ctx := mkCtx () + let spec := mkSpec () + let defaultTable := ctx.binding + expect (statementSays (.checkEnv ctx (addr "root") none) ["kind: check-env", s!"subject: the constants of the canonical tree with root {addr "root"}", "conditions:", s!"specification set: {spec}, this build's", s!"role table: {defaultTable}, the default role table", "axioms: the standard three only", "role binding: validated lazily by this proof", "typing assumptions: none"]) - ++ test "a check names its constant" (statementSays (.check ctx (addr "c") none) - ["kind: check", s!"subject: the constant {addr "c"}"]) - ++ test " states typing under Ix's rules, not Lean's kernel" - (statementSays (.check ctx (addr "c") none) - ["type-checks under Ix's kernel rules", "equality reflection", "not Lean's kernel"] - && !statementSays (.check ctx (addr "c") none) ["well-typed"]) - ++ test " and names the theorem, which needs a binding proof this run did not verify" - (statementSays (.check ctx (addr "c") none) - ["theorem: IxVM.Refinement.Endpoint.circuitComposed covers this claim only together with \ - an accepted binding claim", "which this run did not verify", - "has a model in every set theory", "no typing by Lean's kernel", - "role binding: validated lazily by this proof", - "established only by a binding proof for it"]) - ++ test " or states what it gives with a binding proof for its table" - (statementSays (.check ctx (addr "c") none) (bindingDischarged := true) - [s!"with the binding proof for role table {defaultTable} verified in this run", - "a BLAKE3 collision, or the table is valid", - "established by the binding proof verified with it"]) - ++ test " and that no theorem covers a table only the kernel admitted" - (statementSays (.check { ctx with binding := addr "table" } (addr "c") none) - (tableAdmitted := true) - ["the kernel's admission of the table is not such a proof", - "no theorem connects that admission"]) - ++ test "a claim with assumed leaves is covered by no theorem" - (statementSays (.checkEnv ctx (addr "root") (some (addr "leaves"))) (assumptionsDischarged := true) - ["theorem: none", "no theorem states the composition of a shard partition"]) - ++ test "nor an aggregation root" - (statementSays (.checkEnv ctx (addr "root") none) (route := .aggregate) - ["theorem: none states an aggregation root", "distinct validators 14/15"]) - ++ test "Mode 2 EvalDischargedClaim (validators 14/15) is distinct from Ix.Claim.de and refused by default" - (let dc : Ix.DynamicLink.EvalDischargedClaim := { ctx, kind := .check (addr "c"), assumptions := none } - let bytes := Ix.DynamicLink.serEvalDischargedClaim dc - (Ix.Claim.de bytes).isOk == false && - (Ix.DynamicLink.deEvalDischargedClaim bytes).toOption == some dc && - (match refusalDynamicBytes {} bytes with | .ok (some _) => true | _ => false) && - (match refusalDynamicBytes { eval := true } bytes with | .ok none => true | _ => false)) - ++ test " nor a compressed one" - (statementSays (.checkEnv ctx (addr "root") none) (route := .compressed) - ["nor a compressed proof to the aggregation proof"]) - ++ test "an eval names its input and output" - (statementSays (.eval ctx (addr "in") (addr "out") none) - ["kind: eval", s!"the constant {addr "in"}, evaluating to the constant {addr "out"}"]) - ++ test "an eval says what it asserts and that no theorem states it" - (statementSays (.eval ctx (addr "in") (addr "out") none) - ["the output is the input's normal form as IxVM's evaluator computes it", - "theorem: none; no theorem states an eval claim", "--allow-eval-claim"]) - ++ test "no other kind carries the eval theorem line" - (!statementSays (.check ctx (addr "c") none) ["no theorem states an eval claim"]) - ++ test "each open condition names the flag that accepted it" - (statementSays (.checkEnv - { ctx with binding := addr "table", axioms := some (addr "ax"), bindingAssumed := true } - (addr "root") (some (addr "leaves"))) - ["not admitted here (open; accepted under --allow-custom-binding)", - s!"user axioms {addr "ax"} (open; accepted under --allow-axioms)", - "(open; accepted under --allow-assumed-binding)", - s!"the leaves under {addr "leaves"} (open; accepted under --allow-assumptions)"]) - ++ test " and each discharged one what discharges it" - (statementSays (.checkEnv { ctx with binding := addr "table", bindingAssumed := true } - (addr "root") (some (addr "leaves"))) (bindingDischarged := true) - (assumptionsDischarged := true) (tableAdmitted := true) - [s!"role table: {addr "table"}, admitted by the kernel", - "discharged by the verified binding proof", "owned by the partition verified with it"]) - ++ test "a literal class is open" (statementSays (.checkEnv { ctx with literalClass := true } - (addr "root") none) ["any with the literal class", "--allow-custom-binding"]) - ++ test "a claim that states no typing says so" - (statementSays (.contains (addr "tree") (addr "const")) - ["kind: contains", s!"the leaf {addr "const"} of the tree with root {addr "tree"}", - "none; the claim states no typing"] - && statementSays (.reveal (addr "comm") (.axio none none none) none) - ["kind: reveal", s!"the constant committed as {addr "comm"}"]) - ++ test "a binding claim names its table and specification set" - (statementSays (.binding spec (addr "binding")) - ["kind: binding", s!"the role table {addr "binding"}", s!"specification set: {spec}, this build's"]) - ++ test "a catalog names its subjects" - (statementSays (.catalog (addr "members")) - ["kind: catalog", s!"root {addr "members"}", "each member's own"]) + itBool "a check names its constant" (statementSays (.check (mkCtx ()) (addr "c") none) + ["kind: check", s!"subject: the constant {addr "c"}"]) + itBool " states typing under Ix's rules, not Lean's kernel" + (statementSays (.check (mkCtx ()) (addr "c") none) + ["type-checks under Ix's kernel rules", "equality reflection", "not Lean's kernel"] + && !statementSays (.check (mkCtx ()) (addr "c") none) ["well-typed"]) + itBool " and names the theorem, which needs a binding proof this run did not verify" + (statementSays (.check (mkCtx ()) (addr "c") none) + ["theorem: IxVM.Refinement.Endpoint.circuitComposed covers this claim only together with \ + an accepted binding claim", "which this run did not verify", + "has a model in every set theory", "no typing by Lean's kernel", + "role binding: validated lazily by this proof", + "established only by a binding proof for it"]) + it " or states what it gives with a binding proof for its table" do + let ctx := mkCtx () + let defaultTable := ctx.binding + expect (statementSays (.check ctx (addr "c") none) (bindingDischarged := true) + [s!"with the binding proof for role table {defaultTable} verified in this run", + "a BLAKE3 collision, or the table is valid", + "established by the binding proof verified with it"]) + itBool " and that no theorem covers a table only the kernel admitted" + (statementSays (.check { mkCtx () with binding := addr "table" } (addr "c") none) + (tableAdmitted := true) + ["the kernel's admission of the table is not such a proof", + "no theorem connects that admission"]) + itBool "a claim with assumed leaves is covered by no theorem" + (statementSays (.checkEnv (mkCtx ()) (addr "root") (some (addr "leaves"))) (assumptionsDischarged := true) + ["theorem: none", "no theorem states the composition of a shard partition"]) + itBool "nor an aggregation root" + (statementSays (.checkEnv (mkCtx ()) (addr "root") none) (route := .aggregate) + ["theorem: none states an aggregation root", "distinct validators 14/15"]) + itBool "Mode 2 EvalDischargedClaim (validators 14/15) is distinct from Ix.Claim.de and refused by default" + (let dc : Ix.DynamicLink.EvalDischargedClaim := { ctx := mkCtx (), kind := .check (addr "c"), assumptions := none } + let bytes := Ix.DynamicLink.serEvalDischargedClaim dc + (Ix.Claim.de bytes).isOk == false && + (Ix.DynamicLink.deEvalDischargedClaim bytes).toOption == some dc && + (match refusalDynamicBytes {} bytes with | .ok (some _) => true | _ => false) && + (match refusalDynamicBytes { eval := true } bytes with | .ok none => true | _ => false)) + itBool " nor a compressed one" + (statementSays (.checkEnv (mkCtx ()) (addr "root") none) (route := .compressed) + ["nor a compressed proof to the aggregation proof"]) + itBool "an eval names its input and output" + (statementSays (.eval (mkCtx ()) (addr "in") (addr "out") none) + ["kind: eval", s!"the constant {addr "in"}, evaluating to the constant {addr "out"}"]) + itBool "an eval says what it asserts and that no theorem states it" + (statementSays (.eval (mkCtx ()) (addr "in") (addr "out") none) + ["the output is the input's normal form as IxVM's evaluator computes it", + "theorem: none; no theorem states an eval claim", "--allow-eval-claim"]) + itBool "no other kind carries the eval theorem line" + (!statementSays (.check (mkCtx ()) (addr "c") none) ["no theorem states an eval claim"]) + itBool "each open condition names the flag that accepted it" + (statementSays (.checkEnv + { mkCtx () with binding := addr "table", axioms := some (addr "ax"), bindingAssumed := true } + (addr "root") (some (addr "leaves"))) + ["not admitted here (open; accepted under --allow-custom-binding)", + s!"user axioms {addr "ax"} (open; accepted under --allow-axioms)", + "(open; accepted under --allow-assumed-binding)", + s!"the leaves under {addr "leaves"} (open; accepted under --allow-assumptions)"]) + itBool " and each discharged one what discharges it" + (statementSays (.checkEnv { mkCtx () with binding := addr "table", bindingAssumed := true } + (addr "root") (some (addr "leaves"))) (bindingDischarged := true) + (assumptionsDischarged := true) (tableAdmitted := true) + [s!"role table: {addr "table"}, admitted by the kernel", + "discharged by the verified binding proof", "owned by the partition verified with it"]) + itBool "a literal class is open" (statementSays (.checkEnv { mkCtx () with literalClass := true } + (addr "root") none) ["any with the literal class", "--allow-custom-binding"]) + itBool "a claim that states no typing says so" + (statementSays (.contains (addr "tree") (addr "const")) + ["kind: contains", s!"the leaf {addr "const"} of the tree with root {addr "tree"}", + "none; the claim states no typing"] + && statementSays (.reveal (addr "comm") (.axio none none none) none) + ["kind: reveal", s!"the constant committed as {addr "comm"}"]) + itBool "a binding claim names its table and specification set" + (statementSays (.binding (mkSpec ()) (addr "binding")) + ["kind: binding", s!"the role table {addr "binding"}", s!"specification set: {mkSpec ()}, this build's"]) + itBool "a catalog names its subjects" + (statementSays (.catalog (addr "members")) + ["kind: catalog", s!"root {addr "members"}", "each member's own"]) -def unitTests : TestSeq := - let unconditional : Ix.Claim := .checkEnv ctx (addr "root") none - let assumed : Ix.Claim := .check ctx (addr "const") (some (addr "leaves")) - let axioms : Ix.Claim := .checkEnv { ctx with axioms := some (addr "axioms") } (addr "root") none - let bound : Ix.Claim := .checkEnv { ctx with bindingAssumed := true } (addr "root") none - let other : Ix.Claim := .checkEnv { ctx with binding := addr "table" } (addr "root") none - let literal : Ix.Claim := .checkEnv { ctx with literalClass := true } (addr "root") none - test "an unconditional typing claim is admitted" (admits {} unconditional) - ++ test "a claim with assumed leaves is refused" (!admits {} assumed) - ++ test " unless --allow-assumptions" (admits { assumptions := true } assumed) - ++ test " or a whole partition discharges them" (admits {} assumed false true) - ++ test "an evaluation with assumed leaves is refused" - (!admits {} (.eval ctx (addr "in") (addr "out") (some (addr "leaves")))) - ++ test "a claim with user axioms is refused" (!admits {} axioms) - ++ test " even when its assumptions are discharged" (!admits {} axioms true true) - ++ test " unless --allow-axioms" (admits { axioms := true } axioms) - ++ test "a claim that assumes its binding is refused" (!admits {} bound) - ++ test " unless a binding proof discharges it" (admits {} bound true) - ++ test " or --allow-assumed-binding" (admits { assumedBinding := true } bound) - ++ test "a claim under another role table is refused" (!admits {} other) - ++ test " and one under a literal class" (!admits {} literal) - ++ test " unless --allow-custom-binding" (admits { customBinding := true } other) - ++ test " or the kernel admits the table" (admits {} other (tableAdmitted := true)) - ++ test " which a literal class never is" (!admits {} literal (tableAdmitted := true)) - ++ test " and a binding proof never discharges a literal class's assumed binding" - (!admits { customBinding := true } - (.checkEnv { ctx with literalClass := true, bindingAssumed := true } (addr "root") none) - (bindingDischarged := true)) - ++ test " and the admission relaxes no other condition" - (!admits {} (.checkEnv { ctx with binding := addr "table", axioms := some (addr "axioms") } - (addr "root") none) (tableAdmitted := true)) +def unitTests : LSpec.Spec := do + let mkUnconditional (_ : Unit) : Ix.Claim := .checkEnv (mkCtx ()) (addr "root") none + let mkAssumed (_ : Unit) : Ix.Claim := .check (mkCtx ()) (addr "const") (some (addr "leaves")) + let mkAxioms (_ : Unit) : Ix.Claim := .checkEnv { mkCtx () with axioms := some (addr "axioms") } (addr "root") none + let mkBound (_ : Unit) : Ix.Claim := .checkEnv { mkCtx () with bindingAssumed := true } (addr "root") none + let mkOther (_ : Unit) : Ix.Claim := .checkEnv { mkCtx () with binding := addr "table" } (addr "root") none + let mkLiteral (_ : Unit) : Ix.Claim := .checkEnv { mkCtx () with literalClass := true } (addr "root") none + itBool "an unconditional typing claim is admitted" (admits {} (mkUnconditional ())) + itBool "a claim with assumed leaves is refused" (!admits {} (mkAssumed ())) + itBool " unless --allow-assumptions" (admits { assumptions := true } (mkAssumed ())) + itBool " or a whole partition discharges them" (admits {} (mkAssumed ()) false true) + itBool "an evaluation with assumed leaves is refused" + (!admits {} (.eval (mkCtx ()) (addr "in") (addr "out") (some (addr "leaves")))) + itBool "a claim with user axioms is refused" (!admits {} (mkAxioms ())) + itBool " even when its assumptions are discharged" (!admits {} (mkAxioms ()) true true) + itBool " unless --allow-axioms" (admits { axioms := true } (mkAxioms ())) + itBool "a claim that assumes its binding is refused" (!admits {} (mkBound ())) + itBool " unless a binding proof discharges it" (admits {} (mkBound ()) true) + itBool " or --allow-assumed-binding" (admits { assumedBinding := true } (mkBound ())) + itBool "a claim under another role table is refused" (!admits {} (mkOther ())) + itBool " and one under a literal class" (!admits {} (mkLiteral ())) + itBool " unless --allow-custom-binding" (admits { customBinding := true } (mkOther ())) + itBool " or the kernel admits the table" (admits {} (mkOther ()) (tableAdmitted := true)) + itBool " which a literal class never is" (!admits {} (mkLiteral ()) (tableAdmitted := true)) + itBool " and a binding proof never discharges a literal class's assumed binding" + (!admits { customBinding := true } + (.checkEnv { mkCtx () with literalClass := true, bindingAssumed := true } (addr "root") none) + (bindingDischarged := true)) + itBool " and the admission relaxes no other condition" + (!admits {} (.checkEnv { mkCtx () with binding := addr "table", axioms := some (addr "axioms") } + (addr "root") none) (tableAdmitted := true)) /-- A standing's shape, for the tests. -/ private def shape : Standing → String @@ -238,7 +244,7 @@ private def says (s : Standing) (text : String) : Bool := | _ => false /-- `standing`'s cases over a temporary cache root. -/ -def standingTests : IO TestSeq := do +def standingTests : IO Spec := do let spec ← IO.ofExcept Ix.SpecDigest.specDigest let defaultTable ← IO.ofExcept Ix.Kernel.Reader.defaultTableAddress let table := addr "a custom table" @@ -268,27 +274,34 @@ def standingTests : IO TestSeq := do -- an entry written by another checker version is a miss IO.FS.writeFile (dir / toString spec / toString table) "table-admission/0\n" let stale ← cached dir spec table - return test "the default table needs no admission and reads no environment" (shape s0 == "default") - ++ test "a literal class is not admitted" (shape s1 == "unestablished") - ++ test "a claim under another specification set is not admitted" (shape s2 == "unestablished") - ++ test "a table no supplied environment carries is not admitted" (shape s3 == "unestablished") - ++ test " nor one only another table's environment carries" (shape s4 == "unestablished") - ++ test "a build with no admission run admits no table" (shape s5 == "unestablished") - ++ test "a table the kernel refuses is not admitted, nor recorded" - (shape s6 == "unestablished" && !recordedEarly) - ++ test " and the refusal gives the refusing stage" (says s6 "the test checker refuses") - ++ test "a table the kernel admits is admitted and recorded" - (shape s7 == "admitted false" && recorded) - ++ test " and the record answers the next claim without an environment or a run" - (shape s8 == "admitted true") - ++ test " under its specification set only" (!otherSpec) - ++ test " and this checker version only" (!stale) - ++ test "the environments were read only where the table needed them" ((← reads.get) == 5) + let readCount ← reads.get + return do + itBool "the default table needs no admission and reads no environment" (shape s0 == "default") + itBool "a literal class is not admitted" (shape s1 == "unestablished") + itBool "a claim under another specification set is not admitted" (shape s2 == "unestablished") + itBool "a table no supplied environment carries is not admitted" (shape s3 == "unestablished") + itBool " nor one only another table's environment carries" (shape s4 == "unestablished") + itBool "a build with no admission run admits no table" (shape s5 == "unestablished") + itBool "a table the kernel refuses is not admitted, nor recorded" + (shape s6 == "unestablished" && !recordedEarly) + itBool " and the refusal gives the refusing stage" (says s6 "the test checker refuses") + itBool "a table the kernel admits is admitted and recorded" + (shape s7 == "admitted false" && recorded) + itBool " and the record answers the next claim without an environment or a run" + (shape s8 == "admitted true") + itBool " under its specification set only" (!otherSpec) + itBool " and this checker version only" (!stale) + itBool "the environments were read only where the table needed them" (readCount == 5) finally IO.FS.removeDirAll dir -def suite : IO (List TestSeq) := do - return [unitTests, kindTests, statementTests, ← standingTests] +def suite : IO Spec := do + let standing ← standingTests + return do + unitTests + kindTests + statementTests + standing end Tests.ClaimPolicy diff --git a/Tests/Ix/CollectDependencies.lean b/Tests/Ix/CollectDependencies.lean index 88667f8861..e726277f47 100644 --- a/Tests/Ix/CollectDependencies.lean +++ b/Tests/Ix/CollectDependencies.lean @@ -63,15 +63,14 @@ def sameSet (ns ms : List Lean.Name) : Bool := ns.length == ms.length && ns.all ms.contains && ms.all ns.contains open LSpec in -def suite : List TestSeq := [ - test "the closure of First lists each declaration once" (distinct fromFirst), - test "the closure of First, in first-discovery order" (fromFirst == firstExpected), - test "the closure of Second lists the family once" (distinct fromSecond && sameSet fromSecond family), - test "the closure of Third lists the family once" (distinct fromThird && sameSet fromThird family), - test "the closure of a constructor lists the family once" - (distinct fromConstructor && sameSet fromConstructor family), - test "two roots of one family share one walk" (distinct fromTwo && sameSet fromTwo family), - test "the single-root collector agrees" (fromFirstOne == fromFirst) -] +def suite : LSpec.Spec := do + itBool "the closure of First lists each declaration once" (distinct fromFirst) + itBool "the closure of First, in first-discovery order" (fromFirst == firstExpected) + itBool "the closure of Second lists the family once" (distinct fromSecond && sameSet fromSecond family) + itBool "the closure of Third lists the family once" (distinct fromThird && sameSet fromThird family) + itBool "the closure of a constructor lists the family once" + (distinct fromConstructor && sameSet fromConstructor family) + itBool "two roots of one family share one walk" (distinct fromTwo && sameSet fromTwo family) + itBool "the single-root collector agrees" (fromFirstOne == fromFirst) end Tests.Ix.CollectDependencies diff --git a/Tests/Ix/Commit.lean b/Tests/Ix/Commit.lean index 4891c80fc4..ab0b958068 100644 --- a/Tests/Ix/Commit.lean +++ b/Tests/Ix/Commit.lean @@ -10,58 +10,67 @@ open LSpec open Ixon (Comm runGet serCommTagged) open Ix (Claim RevealConstantInfo) +set_option compiler.extract_closed false + /-! ## Test addresses -/ -private def payload1 : Address := Address.blake3 "payload1".toUTF8 -private def payload2 : Address := Address.blake3 "payload2".toUTF8 -private def secret1 : Address := Address.blake3 "secret1".toUTF8 -private def secret2 : Address := Address.blake3 "secret2".toUTF8 +private def mkPayload1 (_ : Unit) : Address := Address.blake3 "payload1".toUTF8 +private def mkPayload2 (_ : Unit) : Address := Address.blake3 "payload2".toUTF8 +private def mkSecret1 (_ : Unit) : Address := Address.blake3 "secret1".toUTF8 +private def mkSecret2 (_ : Unit) : Address := Address.blake3 "secret2".toUTF8 /-! ## Comm.commit determinism tests -/ -def commDeterminismTests : TestSeq := - let comm1 := Comm.mk secret1 payload1 - let comm2 := Comm.mk secret1 payload1 - -- Same comm → same address - test "Comm.commit deterministic" (Comm.commit comm1 == Comm.commit comm2) - -- Different secrets → different addresses - ++ test "Different secrets produce different commit addresses" - (Comm.commit (Comm.mk secret1 payload1) != Comm.commit (Comm.mk secret2 payload1)) - -- Different payloads → different addresses - ++ test "Different payloads produce different commit addresses" - (Comm.commit (Comm.mk secret1 payload1) != Comm.commit (Comm.mk secret1 payload2)) - -- Verify commitment format: tagged serialization starts with 0xE1 and is 65 bytes - ++ test "serCommTagged starts with 0xE1" - ((serCommTagged comm1).data[0]! == 0xE1) - ++ test "serCommTagged is 65 bytes" - ((serCommTagged comm1).size == 65) +def commDeterminismTests : LSpec.Spec := do + it "Comm.commit deterministic" do + let comm1 := Comm.mk (mkSecret1 ()) (mkPayload1 ()) + let comm2 := Comm.mk (mkSecret1 ()) (mkPayload1 ()) + expect (Comm.commit comm1 == Comm.commit comm2) + it "Different secrets produce different commit addresses" do + expect (Comm.commit (Comm.mk (mkSecret1 ()) (mkPayload1 ())) != + Comm.commit (Comm.mk (mkSecret2 ()) (mkPayload1 ()))) + it "Different payloads produce different commit addresses" do + expect (Comm.commit (Comm.mk (mkSecret1 ()) (mkPayload1 ())) != + Comm.commit (Comm.mk (mkSecret1 ()) (mkPayload2 ()))) + it "serCommTagged starts with 0xE1" do + let comm1 := Comm.mk (mkSecret1 ()) (mkPayload1 ()) + expect ((serCommTagged comm1).data[0]! == 0xE1) + it "serCommTagged is 65 bytes" do + let comm1 := Comm.mk (mkSecret1 ()) (mkPayload1 ()) + expect ((serCommTagged comm1).size == 65) /-! ## Claim.commit tests -/ /-- A stand-in claim context. -/ -private def ctx : Ix.ClaimContext := +private def mkCtx (_ : Unit) : Ix.ClaimContext := { spec := Address.blake3 "commit-test-spec".toUTF8 binding := Address.blake3 "commit-test-binding".toUTF8 axioms := none } -def claimCommitTests : TestSeq := - let evalClaim := Claim.eval ctx payload1 payload2 none - let checkClaim := Claim.check ctx payload1 none - let revealSafety := Claim.reveal payload1 (.defn none (some .safe) none none none none) none - let revealKind := Claim.reveal payload1 (.defn (some .defn) none none none none none) none - let revealBoth := Claim.reveal payload1 (.defn (some .defn) (some .safe) none none none none) none - -- Claim.commit is deterministic - test "Claim.commit deterministic" (Claim.commit evalClaim == Claim.commit evalClaim) - -- Different claim types → different addresses - ++ test "eval and check have different commit addresses" - (Claim.commit evalClaim != Claim.commit checkClaim) - -- Different reveal fields → different addresses - ++ test "Reveal safety-only differs from kind-only" - (Claim.commit revealSafety != Claim.commit revealKind) - ++ test "Reveal kind-only differs from kind+safety" - (Claim.commit revealKind != Claim.commit revealBoth) - ++ test "Reveal safety-only differs from kind+safety" - (Claim.commit revealSafety != Claim.commit revealBoth) +def claimCommitTests : LSpec.Spec := do + it "Claim.commit deterministic" do + let evalClaim := Claim.eval (mkCtx ()) (mkPayload1 ()) (mkPayload2 ()) none + expect (Claim.commit evalClaim == Claim.commit evalClaim) + it "eval and check have different commit addresses" do + let ctx := mkCtx () + let evalClaim := Claim.eval ctx (mkPayload1 ()) (mkPayload2 ()) none + let checkClaim := Claim.check ctx (mkPayload1 ()) none + expect (Claim.commit evalClaim != Claim.commit checkClaim) + it "Reveal safety-only differs from kind-only" do + let p1 := mkPayload1 () + let revealSafety := Claim.reveal p1 (.defn none (some .safe) none none none none) none + let revealKind := Claim.reveal p1 (.defn (some .defn) none none none none none) none + expect (Claim.commit revealSafety != Claim.commit revealKind) + it "Reveal kind-only differs from kind+safety" do + let p1 := mkPayload1 () + let revealKind := Claim.reveal p1 (.defn (some .defn) none none none none none) none + let revealBoth := Claim.reveal p1 (.defn (some .defn) (some .safe) none none none none) none + expect (Claim.commit revealKind != Claim.commit revealBoth) + it "Reveal safety-only differs from kind+safety" do + let p1 := mkPayload1 () + let revealSafety := Claim.reveal p1 (.defn none (some .safe) none none none none) none + let revealBoth := Claim.reveal p1 (.defn (some .defn) (some .safe) none none none none) none + expect (Claim.commit revealSafety != Claim.commit revealBoth) /-! ## RevealClaim field combination tests -/ @@ -71,41 +80,42 @@ private def claimRoundtrips (c : Claim) : Bool := | .ok c' => c' == c | .error _ => false -private def allNoneClaim : Claim := - Claim.reveal payload1 (.defn none none none none none none) none +private def mkAllNoneClaim (_ : Unit) : Claim := + Claim.reveal (mkPayload1 ()) (.defn none none none none none none) none -private def allFieldsClaim : Claim := - Claim.reveal payload1 - (.defn (some .defn) (some .safe) (some 3) (some payload2) (some payload1) +private def mkAllFieldsClaim (_ : Unit) : Claim := + Claim.reveal (mkPayload1 ()) + (.defn (some .defn) (some .safe) (some 3) (some (mkPayload2 ())) (some (mkPayload1 ())) (some { alloc := .noAlloc, boundedStack := true })) - (some secret1) + (some (mkSecret1 ())) -private def singleFieldAddrsDistinct : Bool := - let comm := payload1 +private def singleFieldAddrsDistinct (_ : Unit) : Bool := + let comm := mkPayload1 () + let p2 := mkPayload2 () let addrK := Claim.commit (.reveal comm (.defn (some .defn) none none none none none) none) let addrS := Claim.commit (.reveal comm (.defn none (some .safe) none none none none) none) let addrL := Claim.commit (.reveal comm (.defn none none (some 1) none none none) none) - let addrT := Claim.commit (.reveal comm (.defn none none none (some payload2) none none) none) - let addrV := Claim.commit (.reveal comm (.defn none none none none (some payload2) none) none) + let addrT := Claim.commit (.reveal comm (.defn none none none (some p2) none none) none) + let addrV := Claim.commit (.reveal comm (.defn none none none none (some p2) none) none) let addrA := Claim.commit (.reveal comm (.defn none none none none none (some { alloc := .noRc, boundedStack := false })) none) - let addrB := Claim.commit (.reveal comm (.defn none none none none none none) (some payload2)) + let addrB := Claim.commit (.reveal comm (.defn none none none none none none) (some p2)) let addrs := #[addrK, addrS, addrL, addrT, addrV, addrA, addrB] (List.range addrs.size).all fun i => (List.range addrs.size).all fun j => i == j || addrs[i]! != addrs[j]! -def fieldCombinationTests : TestSeq := +def fieldCombinationTests : LSpec.Spec := do -- All-none fields still produce a valid claim - test "All-none defn serialization roundtrips" (claimRoundtrips allNoneClaim) + itBool "All-none defn serialization roundtrips" (claimRoundtrips (mkAllNoneClaim ())) -- All fields present still produce a valid claim - ++ test "All-fields defn serialization roundtrips" (claimRoundtrips allFieldsClaim) + itBool "All-fields defn serialization roundtrips" (claimRoundtrips (mkAllFieldsClaim ())) -- Each single field produces a distinct commit address - ++ test "Single-field reveals have distinct commit addresses" singleFieldAddrsDistinct + itBool "Single-field reveals have distinct commit addresses" (singleFieldAddrsDistinct ()) /-! ## compileDef determinism tests -/ -private def emptyCompileEnv : Ix.CompileM.CompileEnv := +private def mkEmptyCompileEnv (_ : Unit) : Ix.CompileM.CompileEnv := Ix.CompileM.CompileEnv.new { consts := {} } -- def anon : Type := Prop @@ -116,27 +126,30 @@ private def simpleValue : Lean.Expr := Lean.mkSort .zero private def simpleType2 : Lean.Expr := Lean.mkSort (.succ (.succ .zero)) private def simpleValue2 : Lean.Expr := Lean.mkSort (.succ .zero) -private def compileDefSucceeds : Bool := - match Ix.Commit.compileDef emptyCompileEnv [] simpleType simpleValue with +private def compileDefSucceeds (_ : Unit) : Bool := + match Ix.Commit.compileDef (mkEmptyCompileEnv ()) [] simpleType simpleValue with | .ok _ => true | .error _ => false -private def compileDefDeterministic : Bool := - match Ix.Commit.compileDef emptyCompileEnv [] simpleType simpleValue, - Ix.Commit.compileDef emptyCompileEnv [] simpleType simpleValue with +private def compileDefDeterministic (_ : Unit) : Bool := + let env := mkEmptyCompileEnv () + match Ix.Commit.compileDef env [] simpleType simpleValue, + Ix.Commit.compileDef env [] simpleType simpleValue with | .ok (addr1, _), .ok (addr2, _) => addr1 == addr2 | _, _ => false -private def compileDefDifferentValueDifferentAddr : Bool := - match Ix.Commit.compileDef emptyCompileEnv [] simpleType simpleValue, - Ix.Commit.compileDef emptyCompileEnv [] simpleType2 simpleValue2 with +private def compileDefDifferentValueDifferentAddr (_ : Unit) : Bool := + let env := mkEmptyCompileEnv () + match Ix.Commit.compileDef env [] simpleType simpleValue, + Ix.Commit.compileDef env [] simpleType2 simpleValue2 with | .ok (addr1, _), .ok (addr2, _) => addr1 != addr2 | _, _ => false -- Alpha-invariance: constant name must not affect the content address -private def compileDefAlphaConstName : Bool := - match Ix.Commit.compileDef emptyCompileEnv [] simpleType simpleValue (name := .anonymous), - Ix.Commit.compileDef emptyCompileEnv [] simpleType simpleValue (name := .str .anonymous "Foo") with +private def compileDefAlphaConstName (_ : Unit) : Bool := + let env := mkEmptyCompileEnv () + match Ix.Commit.compileDef env [] simpleType simpleValue (name := .anonymous), + Ix.Commit.compileDef env [] simpleType simpleValue (name := .str .anonymous "Foo") with | .ok (addr1, _), .ok (addr2, _) => addr1 == addr2 | _, _ => false @@ -148,47 +161,50 @@ private def binderValue1 : Lean.Expr := Lean.mkLambda `x .default propExpr (Lean private def binderType2 : Lean.Expr := Lean.mkForall `y .default propExpr propExpr private def binderValue2 : Lean.Expr := Lean.mkLambda `y .default propExpr (Lean.mkBVar 0) -private def compileDefAlphaBinderNames : Bool := - match Ix.Commit.compileDef emptyCompileEnv [] binderType1 binderValue1, - Ix.Commit.compileDef emptyCompileEnv [] binderType2 binderValue2 with +private def compileDefAlphaBinderNames (_ : Unit) : Bool := + let env := mkEmptyCompileEnv () + match Ix.Commit.compileDef env [] binderType1 binderValue1, + Ix.Commit.compileDef env [] binderType2 binderValue2 with | .ok (addr1, _), .ok (addr2, _) => addr1 == addr2 | _, _ => false -- Alpha-invariance: level parameter names must not affect the content address -- def _.{u} : Sort (u+1) := Sort u vs def _.{v} : Sort (v+1) := Sort v -private def compileDefAlphaLevelNames : Bool := +private def compileDefAlphaLevelNames (_ : Unit) : Bool := + let env := mkEmptyCompileEnv () let typ1 := Lean.mkSort (.succ (.param `u)) let val1 := Lean.mkSort (.param `u) let typ2 := Lean.mkSort (.succ (.param `v)) let val2 := Lean.mkSort (.param `v) - match Ix.Commit.compileDef emptyCompileEnv [`u] typ1 val1, - Ix.Commit.compileDef emptyCompileEnv [`v] typ2 val2 with + match Ix.Commit.compileDef env [`u] typ1 val1, + Ix.Commit.compileDef env [`v] typ2 val2 with | .ok (addr1, _), .ok (addr2, _) => addr1 == addr2 | _, _ => false -def compileDefTests : TestSeq := - test "compileDef succeeds on simple def" compileDefSucceeds - ++ test "compileDef produces same address for same inputs" compileDefDeterministic - ++ test "compileDef produces different address for different inputs" compileDefDifferentValueDifferentAddr - ++ test "alpha-invariance: constant name does not affect address" compileDefAlphaConstName - ++ test "alpha-invariance: binder names do not affect address" compileDefAlphaBinderNames - ++ test "alpha-invariance: level param names do not affect address" compileDefAlphaLevelNames +def compileDefTests : LSpec.Spec := do + itBool "compileDef succeeds on simple def" (compileDefSucceeds ()) + itBool "compileDef produces same address for same inputs" (compileDefDeterministic ()) + itBool "compileDef produces different address for different inputs" (compileDefDifferentValueDifferentAddr ()) + itBool "alpha-invariance: constant name does not affect address" (compileDefAlphaConstName ()) + itBool "alpha-invariance: binder names do not affect address" (compileDefAlphaBinderNames ()) + itBool "alpha-invariance: level param names do not affect address" (compileDefAlphaLevelNames ()) /-! ## checkClaim and revealClaim tests -/ -private def checkClaimSucceeds : Bool := - match Ix.Commit.checkClaim ctx emptyCompileEnv [] simpleType simpleValue with +private def checkClaimSucceeds (_ : Unit) : Bool := + match Ix.Commit.checkClaim (mkCtx ()) (mkEmptyCompileEnv ()) [] simpleType simpleValue with | .ok (.check _ _ _) => true | _ => false -private def checkClaimMatchesCompileDef : Bool := - match Ix.Commit.compileDef emptyCompileEnv [] simpleType simpleValue, - Ix.Commit.checkClaim ctx emptyCompileEnv [] simpleType simpleValue with +private def checkClaimMatchesCompileDef (_ : Unit) : Bool := + let env := mkEmptyCompileEnv () + match Ix.Commit.compileDef env [] simpleType simpleValue, + Ix.Commit.checkClaim (mkCtx ()) env [] simpleType simpleValue with | .ok (addr, _), .ok (.check _ claimAddr _) => addr == claimAddr | _, _ => false -private def openConstantInfoDefn : Bool := - match Ix.Commit.compileDef emptyCompileEnv [] simpleType simpleValue with +private def openConstantInfoDefn (_ : Unit) : Bool := + match Ix.Commit.compileDef (mkEmptyCompileEnv ()) [] simpleType simpleValue with | .ok (_, env') => -- Look up the compiled constant via the anonymous name let (ixName, _) := (Ix.CanonM.canonName .anonymous).run {} @@ -208,8 +224,8 @@ private def openConstantInfoDefn : Bool := | none => false | .error _ => false -private def openConstantInfoRoundtrips : Bool := - match Ix.Commit.compileDef emptyCompileEnv [] simpleType simpleValue with +private def openConstantInfoRoundtrips (_ : Unit) : Bool := + match Ix.Commit.compileDef (mkEmptyCompileEnv ()) [] simpleType simpleValue with | .ok (_, env') => let (ixName, _) := (Ix.CanonM.canonName .anonymous).run {} match env'.nameToNamed.get? ixName with @@ -221,45 +237,45 @@ private def openConstantInfoRoundtrips : Bool := let info := Ix.Commit.openConstantInfo constant.info let bAddr := Ix.Commit.sectionAddr constant.binders -- The fully-revealed RevealConstantInfo and sectionAddr should serde roundtrip - claimRoundtrips (.reveal payload1 info (some bAddr)) + claimRoundtrips (.reveal (mkPayload1 ()) info (some bAddr)) | .error _ => false | none => false | none => false | .error _ => false -private def revealClaimWrapper : Bool := +private def revealClaimWrapper (_ : Unit) : Bool := + let p1 := mkPayload1 () + let p2 := mkPayload2 () let info : RevealConstantInfo := .defn (some .defn) none none none none none - let claim := Ix.Commit.revealClaim payload1 info - let claimWithBinders := Ix.Commit.revealClaim payload1 info (some payload2) - claim == Claim.reveal payload1 info none && - claimWithBinders == Claim.reveal payload1 info (some payload2) - -def claimConstructorTests : TestSeq := - test "checkClaim succeeds" checkClaimSucceeds - ++ test "checkClaim address matches compileDef" checkClaimMatchesCompileDef - ++ test "openConstantInfo produces defn with all fields" openConstantInfoDefn - ++ test "openConstantInfo result serde roundtrips" openConstantInfoRoundtrips - ++ test "revealClaim wraps correctly" revealClaimWrapper + let claim := Ix.Commit.revealClaim p1 info + let claimWithBinders := Ix.Commit.revealClaim p1 info (some p2) + claim == Claim.reveal p1 info none && + claimWithBinders == Claim.reveal p1 info (some p2) + +def claimConstructorTests : LSpec.Spec := do + itBool "checkClaim succeeds" (checkClaimSucceeds ()) + itBool "checkClaim address matches compileDef" (checkClaimMatchesCompileDef ()) + itBool "openConstantInfo produces defn with all fields" (openConstantInfoDefn ()) + itBool "openConstantInfo result serde roundtrips" (openConstantInfoRoundtrips ()) + itBool "revealClaim wraps correctly" (revealClaimWrapper ()) /-! ## IO tests for commitConst -/ -def commitConstIOTest : TestSeq := - .individualIO "commitConst: different random secrets produce different addresses" none (do +def commitConstIOTest : LSpec.Spec := do + it "commitConst: different random secrets produce different addresses" do let payload := Address.blake3 "test-payload".toUTF8 let (_, commitAddr1) ← Ix.Commit.commitConst payload let (_, commitAddr2) ← Ix.Commit.commitConst payload - return (commitAddr1 != commitAddr2, 0, 0, none)) .done + expect (commitAddr1 != commitAddr2) /-! ## Suite registration -/ -public def Tests.Commit.suite : List TestSeq := [ - commDeterminismTests, - claimCommitTests, - fieldCombinationTests, - compileDefTests, - claimConstructorTests, -] - -public def Tests.Commit.suiteIO : List TestSeq := [ - commitConstIOTest, -] +public def Tests.Commit.suite : LSpec.Spec := do + commDeterminismTests + claimCommitTests + fieldCombinationTests + compileDefTests + claimConstructorTests + +public def Tests.Commit.suiteIO : LSpec.Spec := do + commitConstIOTest diff --git a/Tests/Ix/Compile/AuxiliaryClosureCanon.lean b/Tests/Ix/Compile/AuxiliaryClosureCanon.lean index 9e8b416443..dfad0f5ab7 100644 --- a/Tests/Ix/Compile/AuxiliaryClosureCanon.lean +++ b/Tests/Ix/Compile/AuxiliaryClosureCanon.lean @@ -439,8 +439,8 @@ def runLeg (env : Lean.Environment) (dir : System.FilePath) (ref : Ixon.Env) ({classes.size} distinct closures, {(← IO.monoMsNow) - t0} ms)" return failed -def suite : List TestSeq := [ - .individualIO "aux addresses are closure-invariant" none (do +def suite : LSpec.Spec := do + it "aux addresses are closure-invariant" do let env ← get_env! let fx := `Tests.Ix.Compile.AuxiliaryClosureCanon.Fx let seeds := (env.constants.toList.filterMap fun (n, _) => @@ -455,7 +455,7 @@ def suite : List TestSeq := [ let ref ← match ← compileClosure env dir "ref" (Ix.EnvScope.collectSelectedDepsWith env units seeds.toList) (bind := true) with | .ok e => pure e - | .error e => throw (IO.userError s!"reference compile: {e}") + | .error e => fail s!"reference compile: {e}" IO.println s!"[canon-closure-aux] reference: {seeds.size} seeds, {ref.named.size} names, \ bound ({(← IO.monoMsNow) - t0} ms); files in {dir}" -- Leg 1, the closure producers (`collectDeps`): every address is the @@ -508,12 +508,8 @@ def suite : List TestSeq := [ let twinErrors := twinRecursorCheck env for e in twinErrors do IO.println s!"[canon-closure-aux] FAIL {e}" IO.println s!"[canon-closure-aux] twin: {if twinErrors.isEmpty then "ok" else "FAIL"}" - let n := 3 * seeds.size + auxSeeds.size + 1 let failed := f1 + f2 + f3 + f4 + (if twinErrors.isEmpty then 0 else 1) if failed == 0 then IO.FS.removeDirAll dir - return (failed == 0, n - failed, n, - if failed == 0 then none else some s!"{failed} seed check(s) failed")) - .done -] + expect (failed == 0) s!"{failed} seed check(s) failed" end Tests.Ix.Compile.AuxiliaryClosureCanon diff --git a/Tests/Ix/Compile/Equations.lean b/Tests/Ix/Compile/Equations.lean index 5dd2447ba2..c7a38c2467 100644 --- a/Tests/Ix/Compile/Equations.lean +++ b/Tests/Ix/Compile/Equations.lean @@ -77,7 +77,7 @@ def elaborate (dir : System.FilePath) (file : String) (text : String) : IO Envir IO.FS.writeFile path text getFileEnv path -def suite : IO (List LSpec.TestSeq) := do +def suite : IO LSpec.Spec := do IO.FS.withTempDir fun dir => do let env ← elaborate dir "Equations.lean" source let before := structural.map fun d => env.contains (d ++ `eq_def) @@ -102,32 +102,32 @@ def suite : IO (List LSpec.TestSeq) := do | _, _ => none | .error _ => [] let sorted := listed.map (·.1) - return [ - test "no structural unfolding theorem exists before the export" (before.all (!·)), - test "every local recursive definition is associated with its own eq_def" - (recursive.all pairs.contains), - test "the non-recursive definitions are not associated" - (!pairs.any fun (d, _) => d == `EqnFixture.double || d == `EqnFixture.entry), - test "a library definition the root reaches is associated (List.length)" - (pairs.contains (`List.length, `List.length.eq_def)), - test "no equation generation failed" failed.isEmpty, - test "each definition is associated once" - ((pairs.map (·.1)).eraseDups.length == pairs.length), - test "the closure holds every associated theorem" - (found.all fun a => closedNames.contains a.equation), - test "each realized theorem has the statement Lean's elaborator gives it" sameAsLean, - test "each associated theorem states `f xs = …` for its definition" selfUnfolding, - test "the JSON names its format" - ((json.getObjValAs? String "format").toOption == some "ix/compile-equations/2"), - test "the closure reaches word operations, through log2's omega proof only" - (closed.any fun (n, _) => Ix.Compile.WordEquations.operations.contains n), - test "with the word equations on (ix compile's default) none joins the closure: a proof is a theorem, which the word walk does not enter" + return do + itBool "no structural unfolding theorem exists before the export" (before.all (!·)) + itBool "every local recursive definition is associated with its own eq_def" + (recursive.all pairs.contains) + itBool "the non-recursive definitions are not associated" + (!pairs.any fun (d, _) => d == `EqnFixture.double || d == `EqnFixture.entry) + itBool "a library definition the root reaches is associated (List.length)" + (pairs.contains (`List.length, `List.length.eq_def)) + itBool "no equation generation failed" failed.isEmpty + itBool "each definition is associated once" + ((pairs.map (·.1)).eraseDups.length == pairs.length) + itBool "the closure holds every associated theorem" + (found.all fun a => closedNames.contains a.equation) + itBool "each realized theorem has the statement Lean's elaborator gives it" sameAsLean + itBool "each associated theorem states `f xs = …` for its definition" selfUnfolding + itBool "the JSON names its format" + ((json.getObjValAs? String "format").toOption == some "ix/compile-equations/2") + itBool "the closure reaches word operations, through log2's omega proof only" + (closed.any fun (n, _) => Ix.Compile.WordEquations.operations.contains n) + itBool "with the word equations on (ix compile's default) none joins the closure: a proof is a theorem, which the word walk does not enter" ((json.getObjValAs? (Array Json) "theorems").toOption.map (·.size) == some 0 && - !closed.any fun (n, _) => n.getPrefix == `IxWordEquations), - test "the JSON lists every association, sorted by definition" + !closed.any fun (n, _) => n.getPrefix == `IxWordEquations) + itBool "the JSON lists every association, sorted by definition" (listed.length == found.size && sorted == sorted.mergeSort (· ≤ ·) && - recursive.all fun (d, e) => listed.contains (d.toString, e.toString)), - test "the JSON lists no failure" - (json.getObjValAs? (Array Json) "failures" |>.toOption |>.map (·.isEmpty) |>.getD false)] + recursive.all fun (d, e) => listed.contains (d.toString, e.toString)) + itBool "the JSON lists no failure" + (json.getObjValAs? (Array Json) "failures" |>.toOption |>.map (·.isEmpty) |>.getD false) end Tests.Ix.Compile.Equations diff --git a/Tests/Ix/Compile/GroundRefusal.lean b/Tests/Ix/Compile/GroundRefusal.lean index 71df45a5de..12779bccc4 100644 --- a/Tests/Ix/Compile/GroundRefusal.lean +++ b/Tests/Ix/Compile/GroundRefusal.lean @@ -109,8 +109,8 @@ private def compileEnvBytes (cs : List (Lean.Name × Lean.ConstantInfo)) Ix.RoleBinding.Compile.writeAtomic (System.FilePath.mk path) bytes return { status with bytes := bytes.size.toUInt64 } -def failClosedStatusTest : TestSeq := - .individualIO "compileEnvBytes fail-closed: ungrounded ⇒ no artifact" none (do +def failClosedStatusTest : LSpec.Spec := do + it "compileEnvBytes fail-closed: ungrounded ⇒ no artifact" do let dir ← IO.FS.createTempDir let out := dir / "fail-closed.ixe" let status ← compileEnvBytes statusConsts out.toString false @@ -125,13 +125,11 @@ def failClosedStatusTest : TestSeq := , ("ungrounded names the bad axiom", status.ungrounded[0]?.map (·.1) == some statusBadName.toString) , ("root is 64 hex chars", status.root.length == 64) ] - match checks.find? (!·.2) with - | some (what, _) => return (false, 0, 0, some s!"failed: {what}") - | none => return (true, 0, 0, none) - ) .done + if let some (what, _) := checks.find? (!·.2) then + fail s!"failed: {what}" -def allowPartialStatusTest : TestSeq := - .individualIO "compileEnvBytes allow-partial: grounded subset reloads" none (do +def allowPartialStatusTest : LSpec.Spec := do + it "compileEnvBytes allow-partial: grounded subset reloads" do let dir ← IO.FS.createTempDir let out := dir / "partial.ixe" let status ← compileEnvBytes statusConsts out.toString true @@ -139,7 +137,7 @@ def allowPartialStatusTest : TestSeq := IO.FS.removeDirAll dir let env ← match Ixon.deEnv bytes with | .ok env => pure env - | .error e => return (false, 0, 0, some s!"reload failed: {e}") + | .error e => fail s!"reload failed: {e}" let checks : List (String × Bool) := [ ("bytes matches file size", status.bytes.toNat == bytes.size) , ("one ungrounded entry", status.ungrounded.size == 1) @@ -147,31 +145,27 @@ def allowPartialStatusTest : TestSeq := env.named.size == status.named.toNat && status.named ≥ 1) , ("bad axiom is absent from the reloaded env", env.named.size < statusConsts.length + 1) ] - match checks.find? (!·.2) with - | some (what, _) => return (false, 0, 0, some s!"failed: {what}") - | none => return (true, 0, 0, none) - ) .done + if let some (what, _) := checks.find? (!·.2) then + fail s!"failed: {what}" -def suite : List TestSeq := [ - .individualIO "ground refusal: the closed input compiles with no failure, certified IO and pure compile" none (do +def suite : LSpec.Spec := do + it "ground refusal: the closed input compiles with no failure, certified IO and pure compile" do let env ← get_env! let cs := closure env fun _ => false let cert ← certifiedFailures env cs let pure ← pureFailures env cs let complete ← completeError? env cs let ok := cert.isEmpty && pure.isEmpty && complete.isNone - return (ok, if ok then 1 else 0, 1, - if ok then none else some s!"certified {cert.toList.take 4}; \ - pure {pure.toList.take 4}; compileComplete {complete}")) .done, - .individualIO "ground refusal: an omitted dependency is refused by name, certified IO and pure compile" none (do + expect ok s!"certified {cert.toList.take 4}; \ + pure {pure.toList.take 4}; compileComplete {complete}" + it "ground refusal: an omitted dependency is refused by name, certified IO and pure compile" do let env ← get_env! let cs := closure env (· == ``Nat.add) let cert ← certifiedFailures env cs let pure ← pureFailures env cs let ok := cert == expected && pure == expected - return (ok, if ok then 1 else 0, 1, - if ok then none else some s!"certified {cert}; pure {pure}; expected {expected}")) .done, - .individualIO "ground refusal: the pure compile's report keeps the grounded rest, and compileComplete refuses" none (do + expect ok s!"certified {cert}; pure {pure}; expected {expected}" + it "ground refusal: the pure compile's report keeps the grounded rest, and compileComplete refuses" do let env ← get_env! let cs := closure env (· == ``Nat.add) let (ixe, failures) ← pureReport env cs @@ -185,10 +179,9 @@ def suite : List TestSeq := [ then f else k let ok := failures.blocks.isEmpty && failures.ungrounded.size == 2 && missing.isEmpty && complete == some s!"2 constant(s) failed to compile; {least.1}: {least.2}" - return (ok, if ok then 1 else 0, 1, - if ok then none else some s!"blocks {failures.blocks.toList.take 4}; \ - unpublished {(missing.map (·.1)).take 4}; compileComplete {complete}")) .done, - failClosedStatusTest, - allowPartialStatusTest] + expect ok s!"blocks {failures.blocks.toList.take 4}; \ + unpublished {(missing.map (·.1)).take 4}; compileComplete {complete}" + failClosedStatusTest + allowPartialStatusTest end Tests.Ix.Compile.GroundRefusal diff --git a/Tests/Ix/Compile/KernelReportTests.lean b/Tests/Ix/Compile/KernelReportTests.lean index 4faf5f30d7..c2ddc28a6c 100644 --- a/Tests/Ix/Compile/KernelReportTests.lean +++ b/Tests/Ix/Compile/KernelReportTests.lean @@ -40,65 +40,64 @@ private def failOut : String := "# declaration type mismatch\n#" ++ addressA ++ " (A.h)\n" ++ "# total failures: 3\n" -def suite : List TestSeq := [ - test "certified report covers every alias through its owning address" +def suite : LSpec.Spec := do + itBool "certified report covers every alias through its owning address" ((do let report ← parse accepted checkCoverage report #[("Alias1", addressA), ("Alias2", addressA)]).isOk) - ++ test "a rejected record remains rejected for an unlisted alias" + itBool "a rejected record remains rejected for an unlisted alias" ((do let report ← parse (row addressA "reject" "type mismatch") checkCoverage report #[("AliasNotDisplayed", addressA)] pure (report[addressA]?.map fun (v : Verdict) => (v.outcome, v.reason))).toOption == some (some ("reject", "type mismatch"))) - ++ test "declines retain their reason for the caller's coverage policy" + itBool "declines retain their reason for the caller's coverage policy" ((do let report ← parse (row addressA "decline" "reader: unsafe axiom") pure (report[addressA]?.map Verdict.reason)).toOption == some (some "reader: unsafe axiom")) - ++ test "blocked dependency results are preserved" + itBool "blocked dependency results are preserved" ((do let report ← parse (row addressA "blocked" addressB) pure (report[addressA]?.map Verdict.outcome)).toOption == some (some "blocked")) - ++ test "a tier record the typing tier typed is kept with its safety" + itBool "a tier record the typing tier typed is kept with its safety" ((do let report ← parse (row addressA "typed" "partial" ++ "\n" ++ row addressB "typed" "unsafe") pure ([addressA, addressB].map fun a => report[a]?.map fun (v : Verdict) => (v.outcome, v.reason))).toOption == some [some ("typed", "partial"), some ("typed", "unsafe")]) - ++ test "a typed row whose reason is not a tier safety fails" + itBool "a typed row whose reason is not a tier safety fails" (failsWith (parse (row addressA "typed" "")) "not a tier safety") - ++ test "an incomplete process fails despite complete-looking rows" + itBool "an incomplete process fails despite complete-looking rows" (failsWith (parse accepted 3) "exited with code 3") - ++ test "empty successful output fails" + itBool "empty successful output fails" (failsWith (parse " \n") "wrote no rows") - ++ test "a truncated trailing row invalidates the report" + itBool "a truncated trailing row invalidates the report" (failsWith (parse (accepted ++ "\n{\"address\":")) "certified row 2") - ++ test "missing typed verdict fields fail" + itBool "missing typed verdict fields fail" (failsWith (parse "{}") "certified row 1") - ++ test "unknown verdicts fail" + itBool "unknown verdicts fail" (failsWith (parse (row addressA "success" "")) "unknown outcome") - ++ test "invalid record addresses fail" + itBool "invalid record addresses fail" (failsWith (parse (row "bad-address" "accept" "")) "invalid record address") - ++ test "duplicate records cannot replace earlier failures" + itBool "duplicate records cannot replace earlier failures" (failsWith (parse (row addressA "reject" "bad" ++ "\n" ++ accepted)) "duplicate record") - ++ test "a missing requested record fails even when other rows pass" + itBool "a missing requested record fails even when other rows pass" (failsWith (do let report ← parse accepted checkCoverage report #[("Missing", addressB)]) "omitted 1 requested name") - ++ test "anonymous diagnostic labels resolve to the address" + itBool "anonymous diagnostic labels resolve to the address" (anonymousAddress? ("#" ++ addressA ++ " (Displayed)") == some addressA) - ++ test "a bare address label resolves to itself" + itBool "a bare address label resolves to itself" (anonymousAddress? addressA == some addressA) - ++ test "a source name is no anonymous label" + itBool "a source name is no anonymous label" (anonymousAddress? "A.f" == none) - ++ test "fail-out rows carry their message; header, separator and trailer are skipped" + itBool "fail-out rows carry their message; header, separator and trailer are skipped" (failOutRows failOut == #[("A.f", "AppTypeMismatch: expected Nat"), ("A.g", "AppTypeMismatch: expected Nat"), ("#" ++ addressA ++ " (A.h)", "declaration type mismatch")]) - ++ test "checker summary gives the checked count" + itBool "checker summary gives the checked count" (rsChecked "[check] seeded 7\n[check] 5/7 passed\n" == some 7) - ++ test "no summary, no checked count" + itBool "no summary, no checked count" (rsChecked "[check] seeded 7\n" == none) -] end Tests.Ix.Compile.KernelReportTests diff --git a/Tests/Ix/Compile/LeanReportTests.lean b/Tests/Ix/Compile/LeanReportTests.lean index da8baabe1c..2078a006bd 100644 --- a/Tests/Ix/Compile/LeanReportTests.lean +++ b/Tests/Ix/Compile/LeanReportTests.lean @@ -54,9 +54,8 @@ private def check : IO Nat := do IO.println "check-lean protocol: 2 complete reports with all 5 outcomes; 20 invocation/coverage/protocol refusals" return cases.length + 2 -def suite : List TestSeq := [ - .individualIO "IxCK CLI reports require exact labels and coherent outcome evidence" none (do - let n ← check - return (true, n, 0, none)) .done] +def suite : LSpec.Spec := do + it "IxCK CLI reports require exact labels and coherent outcome evidence" do + let _ ← check end Tests.Ix.Compile.LeanReportTests diff --git a/Tests/Ix/Compile/SelectedClosure.lean b/Tests/Ix/Compile/SelectedClosure.lean index a41b0b07c2..6fbc6e951b 100644 --- a/Tests/Ix/Compile/SelectedClosure.lean +++ b/Tests/Ix/Compile/SelectedClosure.lean @@ -168,14 +168,12 @@ private def checkerSupportMatchesNatOpDeps : Bool := theorem checkerSupport_matches_natOpDeps : checkerSupportMatchesNatOpDeps = true := by decide -private def report (errors : Array String) (checked : Nat) (what : String) : - IO (Bool × Nat × Nat × Option String) := do +private def report (errors : Array String) (what : String) : AssertM Unit := do for e in errors do IO.println s!"[selected-closure] FAIL {e}" - return (errors.isEmpty, if errors.isEmpty then checked else 0, checked, - if errors.isEmpty then none else some s!"{errors.size} {what} failure(s)") + expect errors.isEmpty s!"{errors.size} {what} failure(s)" -def suite : List TestSeq := [ - .individualIO "selected closures carry the whole unit of PassO2.SA._sizeOf_N" none (do +def suite : LSpec.Spec := do + it "selected closures carry the whole unit of PassO2.SA._sizeOf_N" do let env ← getFileEnv fixture let units := Ix.EnvScope.unitIndex env.constants let required := sizeOfInstances ++ sizeOfUnitSupport @@ -198,12 +196,11 @@ def suite : List TestSeq := [ let raw := nameSet (Ix.EnvScope.collectDeps env sizeOfRoots {}) for n in sizeOfInstances do if raw.contains n then errors := errors.push s!"raw negative control carries {n}" - report errors (seedSets.length + 1) "unit closure") - (.individualIO "selected closures: a matcher's unit, mutual siblings, checker support" none (do + report errors "unit closure" + it "selected closures: a matcher's unit, mutual siblings, checker support" do let env ← get_env! let units := Ix.EnvScope.unitIndex env.constants let mut errors : Array String := #[] - let mut checked := 0 -- 2. the matcher's unit, and nothing outside it let bare := nameSet (Ix.EnvScope.collectSelectedDepsWith env units [``matcher]) let carried := nameSet (Ix.EnvScope.collectSelectedDepsWith env units [``carriedProof]) @@ -213,10 +210,8 @@ def suite : List TestSeq := [ errors := errors.push "the bare matcher lost matcher._arg_pusher of its unit" if bare.contains ``carriedProof then errors := errors.push "the bare matcher pulled its caller carriedProof" - checked := checked + 1 -- 3. mutual siblings for (root, sibling) in mutualSeeds do - checked := checked + 1 unless (nameSet (Ix.EnvScope.collectSelectedDepsWith env units [root])).contains sibling do errors := errors.push s!"{root}: missing its sibling {sibling}" -- 4. checker support @@ -232,7 +227,6 @@ def suite : List TestSeq := [ errors := errors.push "raw negative control: landUser's raw closure carries Nat.mul" unless selected.contains ``Nat.mul do errors := errors.push "landUser's selected closure lacks Nat.mul" - checked := checked + 1 -- 5. self-contained for IxCK: an inductive's recursor, and the string-literal -- support when a closed constant has a string literal unless bare.contains ``Nat.rec do @@ -248,7 +242,7 @@ def suite : List TestSeq := [ if selected.contains ``String.ofList then errors := errors.push "landUser's selected closure (no string literal) carries String.ofList" -- a String literal in a theorem's proof only (`value? (allowOpaque := true)`) - let some proofCi := env.find? ``stringInProof | throw (IO.userError "stringInProof missing") + let some proofCi := env.find? ``stringInProof | fail "stringInProof missing" let isStr : Expr → Bool | .lit (.strVal _) => true | _ => false unless (proofCi.type.find? isStr).isNone && Ix.EnvScope.hasStringLiteral proofCi do errors := errors.push "stringInProof: the literal is not in its proof only, or is not seen there" @@ -257,9 +251,7 @@ def suite : List TestSeq := [ errors := errors.push "stringInProof's closure holds another String literal (the case is vacuous)" unless (nameSet (Ix.EnvScope.collectSelectedDepsWith env units [``stringInProof])).contains ``String.ofList do errors := errors.push "stringInProof's selected closure (a literal in a proof) lacks String.ofList" - checked := checked + 1 - report errors checked "selected closure") .done) -] + report errors "selected closure" /-- `compiler-selected-closure-e2e`: the fixture compiled whole and as each selected closure of `seedSets`, by the Lean pipeline; the Rust compile of diff --git a/Tests/Ix/Compile/WordEquations.lean b/Tests/Ix/Compile/WordEquations.lean index 6606dbfdee..3a2f07139e 100644 --- a/Tests/Ix/Compile/WordEquations.lean +++ b/Tests/Ix/Compile/WordEquations.lean @@ -43,7 +43,7 @@ def elaborate (dir : System.FilePath) (file : String) (text : String) : IO Envir def wordTheorems (names : List Name) : List Name := names.filter fun n => n.getPrefix == `IxWordEquations -def suite : IO (List LSpec.TestSeq) := do +def suite : IO LSpec.Spec := do IO.FS.withTempDir fun dir => do let plain ← elaborate dir "Plain.lean" plainSource let all := Ix.Compile.WordEquations.all @@ -80,25 +80,25 @@ def suite : IO (List LSpec.TestSeq) := do let named := Ix.Compile.WordEquations.all.filter (added.contains ·.theoremName) let subjects : List String := listed.map (·.2.1) let sorted : Bool := subjects == subjects.mergeSort (fun a b => decide (a ≤ b)) - return [ - test "68 equations: per width one per primitive operation (17; `ofNat`'s is the bridge)" - (all.length == 68), - test "every equation elaborates as a level-monomorphic theorem" allTheorems, - test "a closure without words gets no equation" - (wordTheorems (plainClosed.map (·.1))).isEmpty, - test "no unfolding-theorem failure on the word source" failed.isEmpty, - test s!"the word source's closure holds the theorems of its operations and bridges, and only \ + return do + itBool "68 equations: per width one per primitive operation (17; `ofNat`'s is the bridge)" + (all.length == 68) + itBool "every equation elaborates as a level-monomorphic theorem" allTheorems + itBool "a closure without words gets no equation" + (wordTheorems (plainClosed.map (·.1))).isEmpty + itBool "no unfolding-theorem failure on the word source" failed.isEmpty + itBool s!"the word source's closure holds the theorems of its operations and bridges, and only \ those: {added}" - (expected.all added.contains && added.length == expected.length), - test s!"the walk reaches four operations outside theorems, not UInt64.toNat (in the closure, \ - inside UInt64.toUInt8's body): {reached.toList}" exact, - test s!"the output's theorems name each equation of the closure with its operation: {listed}" + (expected.all added.contains && added.length == expected.length) + itBool s!"the walk reaches four operations outside theorems, not UInt64.toNat (in the closure, \ + inside UInt64.toUInt8's body): {reached.toList}" exact + itBool s!"the output's theorems name each equation of the closure with its operation: {listed}" (listed.length == added.length && named.all fun e => - listed.contains ("word", e.operation.toString, e.theoremName.toString)), - test "the output's theorems are sorted by subject" sorted, - test "with words off (`ix compile --no-word-equations`) the word source gets no equation" - (wordTheorems (closedOff.map (·.1))).isEmpty, - test "a closure without words gets no theorem proposal" - (Ix.Compile.Equations.theorems (plainClosed.map (·.1))).isEmpty] + listed.contains ("word", e.operation.toString, e.theoremName.toString)) + itBool "the output's theorems are sorted by subject" sorted + itBool "with words off (`ix compile --no-word-equations`) the word source gets no equation" + (wordTheorems (closedOff.map (·.1))).isEmpty + itBool "a closure without words gets no theorem proposal" + (Ix.Compile.Equations.theorems (plainClosed.map (·.1))).isEmpty end Tests.Ix.Compile.WordEquations diff --git a/Tests/Ix/CompileDeterminism.lean b/Tests/Ix/CompileDeterminism.lean index e87fd00ef7..ff918f1cef 100644 --- a/Tests/Ix/CompileDeterminism.lean +++ b/Tests/Ix/CompileDeterminism.lean @@ -39,10 +39,9 @@ private def compileOnce (source : String) (out : System.FilePath) : /-- Two separate `ix compile` processes over `source`, byte identity asserted via their Blake3 digests (`Ix.FileDigest.blake3File`). -/ -private def determinismLeg (source : String) : - IO (Bool × Nat × Nat × Option String) := do +private def determinismLeg (source : String) : AssertM Unit := do unless (← ixExe.pathExists) do - return (false, 0, 0, some s!"{ixExe} missing — run `lake build ix` first") + fail s!"{ixExe} missing — run `lake build ix` first" let dir ← IO.FS.createTempDir try let out1 := dir / "run1.ixe" @@ -51,25 +50,23 @@ private def determinismLeg (source : String) : let task2 ← IO.asTask (prio := .dedicated) (compileOnce source out2) let res1 ← IO.wait task1 let res2 ← IO.wait task2 - if let .error e ← IO.ofExcept res1 then - return (false, 0, 0, some e) - if let .error e ← IO.ofExcept res2 then - return (false, 0, 0, some e) - let h1 ← try Ix.FileDigest.blake3File out1 - catch e => return (false, 0, 0, some s!"blake3 of {out1}: {e}") - let h2 ← try Ix.FileDigest.blake3File out2 - catch e => return (false, 0, 0, some s!"blake3 of {out2}: {e}") - let bytes := (← out1.metadata).byteSize.toNat + if let Except.error e ← IO.ofExcept res1 then + fail e + if let Except.error e ← IO.ofExcept res2 then + fail e + let h1 ← match ← (Ix.FileDigest.blake3File out1).toBaseIO with + | .ok h => pure h + | .error e => fail s!"blake3 of {out1}: {e}" + let h2 ← match ← (Ix.FileDigest.blake3File out2).toBaseIO with + | .ok h => pure h + | .error e => fail s!"blake3 of {out2}: {e}" if h1 != h2 then - return (false, bytes, 0, some s!"{source}: cross-process compile \ -is nondeterministic — {h1} vs {h2}") - return (true, bytes, 0, none) + fail s!"{source}: cross-process compile is nondeterministic — {h1} vs {h2}" finally IO.FS.removeDirAll dir -def suite : List TestSeq := [ - .individualIO - "compile determinism: fixture corpus, two processes, Blake3-identical" - none (determinismLeg "Tests/Ix/Compile/Mutual.lean") .done ] +public def suite : LSpec.Spec := do + it "compile determinism: fixture corpus, two processes, Blake3-identical" do + determinismLeg "Tests/Ix/Compile/Mutual.lean" end Tests.Ix.CompileDeterminism diff --git a/Tests/Ix/Decompile.lean b/Tests/Ix/Decompile.lean index 5e6b184562..28bfd7b5b1 100644 --- a/Tests/Ix/Decompile.lean +++ b/Tests/Ix/Decompile.lean @@ -21,6 +21,8 @@ public import Tests.Ix.Fixtures open LSpec +set_option compiler.extract_closed false + namespace Tests.Decompile /-! ## Extension-table append (pure unit) @@ -43,7 +45,7 @@ private def nX : Ix.Name := Ix.Name.mkStr Ix.Name.mkAnon "x" /-- Type `∀ (x : B), Sort (max u 0)` where ref index 1 and univ index 1 are VIRTUAL — resolvable only through the appended extension tables. -/ -private def extFixture : +private def mkExtFixture (_ : Unit) : Ixon.Constant × ConstantMeta × ExprMetaArena × Ixon.Expr := Id.run do let ty : Ixon.Expr := .leanAll (.ref 1 #[]) (.sort 1) let aAddr := Address.blake3 "ext-fixture-A".toUTF8 @@ -59,7 +61,7 @@ private def extFixture : ]⟩ return (cnst, cm, arena, ty) -private def extEnv : DecompileEnv := Id.run do +private def mkExtEnv (_ : Unit) : DecompileEnv := Id.run do let base : Ixon.Env := {} let names := [nB, nU, nX].foldl (init := base.names) Ixon.RawEnv.addNameComponents @@ -67,10 +69,10 @@ private def extEnv : DecompileEnv := Id.run do /-- With extensions installed, the virtual indices resolve and the original expression comes back. -/ -private def extAppendResolves : Bool := Id.run do - let (cnst, cm, arena, ty) := extFixture +private def extAppendResolves (_ : Unit) : Bool := Id.run do + let (cnst, cm, arena, ty) := mkExtFixture () let ctx := mkBlockCtx cnst #[] #[nU] arena cm - match DecompileM.run extEnv ctx {} (decompileExpr ty 2) with + match DecompileM.run (mkExtEnv ()) ctx {} (decompileExpr ty 2) with | .ok (e, _) => let expected := Ix.Expr.mkForallE nX (Ix.Expr.mkConst nB #[]) @@ -82,10 +84,10 @@ private def extAppendResolves : Bool := Id.run do /-- Without the metadata wrapper, the same indices are out of bounds — proving the append (not table size coincidence) made them resolve. -/ -private def extAppendTeeth : Bool := Id.run do - let (cnst, _, arena, ty) := extFixture +private def extAppendTeeth (_ : Unit) : Bool := Id.run do + let (cnst, _, arena, ty) := mkExtFixture () let ctx := mkBlockCtx cnst #[] #[nU] arena - match DecompileM.run extEnv ctx {} (decompileExpr ty 2) with + match DecompileM.run (mkExtEnv ()) ctx {} (decompileExpr ty 2) with | .ok _ => return false | .error e => return match e with @@ -111,7 +113,7 @@ open Ix.DecompileM Ixon private def nAx : Ix.Name := Ix.Name.mkStr Ix.Name.mkAnon "MS.ax" /-- The names the fixtures read. -/ -private def msEnv : DecompileEnv := +private def mkMsEnv (_ : Unit) : DecompileEnv := { ixonEnv := { names := Ixon.RawEnv.addNameComponents {} nAx } } /-- Primary entry 0. -/ @@ -130,15 +132,15 @@ private def isMetaShareErr {α : Type} (idx entry p q : Nat) : Except DecompileE | _ => false /-- Forward reference (`metaSharing[0]` → `metaSharing[1]`): rejected. -/ -private def msForward : Bool := +private def msForward (_ : Unit) : Bool := isMetaShareErr 2 0 1 2 (validateMetaSharing 1 #[.app (.share 2) (.var 3), .var 4]) /-- Self reference (`share p` in `metaSharing[0]`): rejected, not a loop. -/ -private def msSelf : Bool := +private def msSelf (_ : Unit) : Bool := isMetaShareErr 1 0 1 1 (validateMetaSharing 1 #[.app (.share 1) (.var 3)]) /-- `i ≥ p + q`: out of range. -/ -private def msOutOfRange : Bool := +private def msOutOfRange (_ : Unit) : Bool := let r := validateMetaSharing 1 #[.var 0, .app (.share 5) (.var 3)] isMetaShareErr 5 1 1 2 r && (match r with @@ -148,30 +150,30 @@ private def msOutOfRange : Bool := /-- Whole-constant path (`decompileAxiom` → `withFreshBlock`): the table check rejects a malformed entry that nothing reads, and the error names the constant. -/ -private def msAxiomUnreadEntryRejected : Bool := +private def msAxiomUnreadEntryRejected (_ : Unit) : Bool := let ax : Ixon.Axiom := ⟨false, 0, .sort 0⟩ let cnst : Ixon.Constant := ⟨.axio ax, #[prim0], #[], #[.zero], #[]⟩ -- Entry 2 references itself (`share 3 = p + 2`). let cm : ConstantMeta := { info := .axio nAx.getHash #[] ⟨#[.leaf]⟩ 0, metaSharing := #[sharedM0, sharedM1, .app (.share 3) (.var 0)] } - let r := (DecompileM.run msEnv default {} (decompileAxiom ax cnst cm)).map (·.1) + let r := (DecompileM.run (mkMsEnv ()) default {} (decompileAxiom ax cnst cm)).map (·.1) isMetaShareErr 3 2 1 3 r && match r with | .error (.invalidMetaShareIndex _ _ _ _ c) => c == nAx.pretty | _ => false /-- Tables without shares pass the check. -/ -private def msNoShares : Bool := +private def msNoShares (_ : Unit) : Bool := validateMetaSharing 0 #[plainM0, plainM1] matches .ok () /-- A valid shared table passes the check. -/ -private def msSharedTable : Bool := +private def msSharedTable (_ : Unit) : Bool := validateMetaSharing 1 #[sharedM0, sharedM1] matches .ok () /-- The table check visits each shared node once: the chain `e(k+1) = app e(k) e(k)` of depth 64 (2^64 nodes as a tree) validates, and the first violation inside it is still its leftmost leaf. -/ -private def msSharedChain : Bool := +private def msSharedChain (_ : Unit) : Bool := let chain := (List.range 64).foldl (fun e _ => Ixon.Expr.app e e) (Ixon.Expr.app (.share 0) (.var 0)) (validateMetaSharing 1 #[chain, chain] matches .ok ()) && @@ -179,19 +181,15 @@ private def msSharedChain : Bool := end MetaShare -public def unitSuite : List TestSeq := [ - test "extension append: virtual ref/univ indices resolve" - extAppendResolves - ++ test "extension append: absent metadata leaves indices OOB" - extAppendTeeth, - test "metadata share: forward reference rejected" msForward - ++ test "metadata share: self reference rejected" msSelf - ++ test "metadata share: i ≥ p + q rejected" msOutOfRange - ++ test "metadata share: unread malformed entry rejected" - msAxiomUnreadEntryRejected - ++ test "metadata share: tables without shares unchanged" msNoShares - ++ test "metadata share: a valid shared table passes" msSharedTable - ++ test "metadata share: shared subterms are checked once" msSharedChain -] +public def unitSuite : LSpec.Spec := do + itBool "extension append: virtual ref/univ indices resolve" (extAppendResolves ()) + itBool "extension append: absent metadata leaves indices OOB" (extAppendTeeth ()) + itBool "metadata share: forward reference rejected" (msForward ()) + itBool "metadata share: self reference rejected" (msSelf ()) + itBool "metadata share: i ≥ p + q rejected" (msOutOfRange ()) + itBool "metadata share: unread malformed entry rejected" (msAxiomUnreadEntryRejected ()) + itBool "metadata share: tables without shares unchanged" (msNoShares ()) + itBool "metadata share: a valid shared table passes" (msSharedTable ()) + itBool "metadata share: shared subterms are checked once" (msSharedChain ()) end Tests.Decompile diff --git a/Tests/Ix/EnvBody.lean b/Tests/Ix/EnvBody.lean index 777fc3d61f..5781b07227 100644 --- a/Tests/Ix/EnvBody.lean +++ b/Tests/Ix/EnvBody.lean @@ -23,12 +23,12 @@ namespace Tests.Ix.EnvBody `lake test` runs the `IxTests` executable. -/ def fixturePath : System.FilePath := "Tests/Ix/Fixtures/Export.lean" -public def suite : IO LSpec.TestSeq := do +public def suite : IO LSpec.Spec := do let env ← getFileEnv fixturePath - pure $ - LSpec.test "getFileEnv includes the file body (not just imports)" + return do + itBool "getFileEnv includes the file body (not just imports)" ((env.constants.find? `MyNat).isSome) - ++ LSpec.test "getFileEnv still includes imports" + itBool "getFileEnv still includes imports" ((env.constants.find? `Nat).isSome) end Tests.Ix.EnvBody diff --git a/Tests/Ix/HostAdmission.lean b/Tests/Ix/HostAdmission.lean index 426a481128..27c8b4c3ba 100644 --- a/Tests/Ix/HostAdmission.lean +++ b/Tests/Ix/HostAdmission.lean @@ -119,9 +119,8 @@ private def checks : IO Nat := do ensure (!(verify changed tierArtifact limits).isOk) "tier downgrade/partition tampering passed" return 2 -public def units : LSpec.TestSeq := - .individualIO "host admission: actual receipts, canonical identities and replay/tamper controls" none (do - let count ← checks - return (true, count, 0, none)) .done +public def units : LSpec.Spec := + it "host admission: actual receipts, canonical identities and replay/tamper controls" do + let _ ← checks end Tests.Ix.HostAdmission diff --git a/Tests/Ix/HostAdmissionCli.lean b/Tests/Ix/HostAdmissionCli.lean index bbffd41bd3..8f6d9f7854 100644 --- a/Tests/Ix/HostAdmissionCli.lean +++ b/Tests/Ix/HostAdmissionCli.lean @@ -241,9 +241,8 @@ private def checks : IO Nat := do finally IO.FS.removeDirAll dir -def suite : List LSpec.TestSeq := [ - .individualIO "host statement persistence, addressed replay and actual CLI refusals" none (do - let count ← checks - return (true, count, 0, none)) .done] +def suite : LSpec.Spec := + it "host statement persistence, addressed replay and actual CLI refusals" do + let _ ← checks end Tests.Ix.HostAdmissionCli diff --git a/Tests/Ix/IOIngress.lean b/Tests/Ix/IOIngress.lean index dfd5a91320..72eed6d3ab 100644 --- a/Tests/Ix/IOIngress.lean +++ b/Tests/Ix/IOIngress.lean @@ -88,14 +88,13 @@ def violations : IO (Array String) := do found := found.push s!"no function reads {channel}: the scanner no longer reads the sources" return found -def structural : TestSeq := - .individualIO "every IO byte the IxVM and multi-stark programs read is range-checked" none (do +def structural : LSpec.Spec := do + it "every IO byte the IxVM and multi-stark programs read is range-checked" do let found ← violations - let ok := found.isEmpty - return (ok, if ok then 1 else 0, 1, - if ok then none else some ("; ".intercalate found.toList))) .done + expect found.isEmpty ("; ".intercalate found.toList) -def suite : List TestSeq := [structural] +def suite : LSpec.Spec := do + structural /-! ## Execution -/ diff --git a/Tests/Ix/ImportIxe.lean b/Tests/Ix/ImportIxe.lean index 78cf5def0e..bcbde2890a 100644 --- a/Tests/Ix/ImportIxe.lean +++ b/Tests/Ix/ImportIxe.lean @@ -268,63 +268,57 @@ private def compileFixtureToFile (consts : List (Lean.Name × Lean.ConstantInfo) return (root, failures.toMap.size) /-- C6 parity, source root equality and fresh replay. -/ -private def roundtripTest : IO (Bool × Nat × Nat × Option String) := do +private def roundtripTest : AssertM Unit := do let dir ← IO.FS.createTempDir let path := (dir / "fixture.ixe").toString try let original ← buildFixtureConsts let (root1, ungrounded1) ← compileFixtureToFile original.toList path if ungrounded1 > 0 then - return (false, 0, 0, - some s!"fixture compile ungrounded: {ungrounded1}") + fail s!"fixture compile ungrounded: {ungrounded1}" -- C6 parity: materialize everything and compare per constant. Source -- import restores the complete original declaration set. let materialized ← Ix.ImportIxe.materializeIxe path let extra := materialized.filter fun (n, _) => !original.any (·.1 == n) let missing := original.filter fun (n, _) => !materialized.any (·.1 == n) if materialized.size != original.size || !missing.isEmpty || !extra.isEmpty then - return (false, 0, 0, some s!"materialized names: original \ -{original.size}, materialized {materialized.size}; extra {extra.map (·.1)}, missing {missing.map (·.1)}") + fail s!"materialized names: original \ +{original.size}, materialized {materialized.size}; extra {extra.map (·.1)}, missing {missing.map (·.1)}" let mut origMap : Lean.NameMap Lean.ConstantInfo := {} for (n, ci) in original do origMap := origMap.insert n ci let mut matMap : Lean.NameMap Lean.ConstantInfo := {} for (n, ci) in materialized do let some oci := origMap.find? n - | return (false, 0, 0, some s!"unexpected source constant {n}") + | fail s!"unexpected source constant {n}" if let some e := compareCI n oci ci then - return (false, 0, 0, some e) + fail e matMap := matMap.insert n ci -- Root equality: recompiling the complete materialized source output is -- a fixed point of the canonical root. let path2 := (dir / "rebuilt.ixe").toString let (root2, _) ← compileFixtureToFile materialized.toList path2 if root2 != root1 then - return (false, 0, 0, some s!"root drift: {root1.take 12}… → \ -{root2.take 12}…") + fail s!"root drift: {root1.take 12}… → {root2.take 12}…" -- Fresh kernel replay via the shared planner (import_ixe core). let matMapFrozen := matMap - let plan ← match Ix.Replay.planDeclarations matMap - matMapFrozen.find? with - | .ok plan => pure plan - | .error e => return (false, 0, 0, some s!"planDeclarations: {e}") + let plan ← expectOk ((Ix.Replay.planDeclarations matMap matMapFrozen.find?).mapError (s!"planDeclarations: {·}")) let emptyEnv ← Lean.mkEmptyEnvironment let mut kenv := emptyEnv.toKernelEnv for (key, decl) in plan do match kenv.addDecl {} decl with | .ok kenv' => kenv := kenv' | .error _ => - return (false, 0, 0, some s!"fresh kernel replay rejected {key}") + fail s!"fresh kernel replay rejected {key}" for (n, expected) in original do let some actual := kenv.constants.find? n - | return (false, 0, 0, some s!"fresh replay lost source constant {n}") + | fail s!"fresh replay lost source constant {n}" if let some e := compareCI n expected actual then - return (false, 0, 0, some s!"fresh replay: {e}") - return (true, original.size, 0, none) + fail s!"fresh replay: {e}" finally IO.FS.removeDirAll dir -private def closureTest : IO (Bool × Nat × Nat × Option String) := do +private def closureTest : AssertM Unit := do let dir ← IO.FS.createTempDir let path := (dir / "fixture.ixe").toString try @@ -341,9 +335,8 @@ private def closureTest : IO (Bool × Nat × Nat × Option String) := do ("axiom excluded", !names.contains `TIxImp.axm), ("theorem excluded", !names.contains `TIxImp.thm), ("proj fixture excluded", !names.contains `TIxImp.P) ] - match checks.find? (!·.2) with - | some (what, _) => return (false, 0, 0, some s!"failed: {what}") - | none => return (true, subset.size, 0, none) + if let some (what, _) := checks.find? (!·.2) then + fail s!"failed: {what}" finally IO.FS.removeDirAll dir @@ -380,20 +373,21 @@ private def getConsumerEnv : IO Lean.Environment := do /-- C8: a consumer file `import_ixe`s the fixture artifact through the real command elaborator (in-process frontend + interpreter) and defines a term over the materialized constants. -/ -private def elabTest : IO (Bool × Nat × Nat × Option String) := do - try - let env ← getConsumerEnv - let checks : List (String × Bool) := [ - ("consumer def elaborated", env.contains `Consumer.uses), - ("consumer theorem elaborated", env.contains `Consumer.alsoUses), - ("materialized inductive present", env.contains nN), - ("materialized recursor present", env.contains nRec), - ("materialized defn present", env.contains `TIxImp.dbl) ] - match checks.find? (!·.2) with - | some (what, _) => return (false, 0, 0, some s!"failed: {what}") - | none => return (true, 0, 0, none) - catch e => - return (false, 0, 0, some s!"consumer elaboration failed: {e}") +private def elabTest : AssertM Unit := do + let envRes : Except String Lean.Environment ← liftM (m := IO) do + try + pure (.ok (← getConsumerEnv)) + catch e => + pure (.error s!"consumer elaboration failed: {e}") + let env ← expectOk envRes + let checks : List (String × Bool) := [ + ("consumer def elaborated", env.contains `Consumer.uses), + ("consumer theorem elaborated", env.contains `Consumer.alsoUses), + ("materialized inductive present", env.contains nN), + ("materialized recursor present", env.contains nRec), + ("materialized defn present", env.contains `TIxImp.dbl) ] + if let some (what, _) := checks.find? (!·.2) then + fail s!"failed: {what}" /-- C9: the ZkVoting consumption pattern against an imported artifact — `import_ixe` the fixture, commit a private value of an imported @@ -402,7 +396,7 @@ private def elabTest : IO (Bool × Nat × Nat × Option String) := do (`Ix.Commit.evalClaim`) — all with a closure-scoped compile, so cost tracks the claim, not the environment. (Proving the claim is `ix prove`'s job; the IxVM eval arm is still landing.) -/ -private def zkPatternTest : IO (Bool × Nat × Nat × Option String) := do +private def zkPatternTest : AssertM Unit := do let env ← getConsumerEnv -- Closure-scoped compile env over what the claim touches. let mut seen : Lean.NameSet := {} @@ -414,7 +408,7 @@ private def zkPatternTest : IO (Bool × Nat × Nat × Option String) := do if seen.contains n then continue seen := seen.insert n let some ci := env.find? n - | return (false, 0, 0, some s!"consumer env missing {n}") + | fail s!"consumer env missing {n}" closure := (n, ci) :: closure for r in Ix.Replay.constantInfoReferences ci do unless seen.contains r do @@ -433,12 +427,12 @@ private def zkPatternTest : IO (Bool × Nat × Nat × Option String) := do let (chained, env2) ← IO.ofExcept (Ix.Commit.compileDef env1 [] k2Ty k2Val) let (alone, _) ← IO.ofExcept (Ix.Commit.compileDef compileEnv [] k2Ty k2Val) unless chained == alone do - return (false, 0, 0, some "a chained anonymous definition has another address than alone") + fail "a chained anonymous definition has another address than alone" let some bytes := env2.constants.get? chained - | return (false, 0, 0, some "compileDef stored no record") + | fail "compileDef stored no record" let defn ← IO.ofExcept (Ixon.deConstantAt bytes 0 bytes.size) if defn.binders.isEmpty || defn.binders.any (·.nodes.any (·.isUndecided)) then - return (false, 0, 0, some "a definition compiled over the input has no decided binder data") + fail "a definition compiled over the input has no decided binder data" -- Commit a private value of the imported type. let voteType := Lean.Expr.const nN [] let vote := Lean.Expr.app (.const nSucc []) (.const nZero []) @@ -446,8 +440,7 @@ private def zkPatternTest : IO (Bool × Nat × Nat × Option String) := do Ix.Commit.commitDef compileEnv env [] voteType vote let commitName := Address.toUniqueName commitAddr unless env'.contains commitName do - return (false, 0, 0, - some "commitDef did not register the commitment constant") + fail "commitDef did not register the commitment constant" -- Claim: an imported function applied to the commitment evaluates -- to the public result. let input := Lean.mkApp (.const `TIxImp.dbl []) (.const commitName []) @@ -455,25 +448,18 @@ private def zkPatternTest : IO (Bool × Nat × Nat × Option String) := do (Lean.mkApp (.const nSucc []) (.const nZero [])) let ctx : Ix.ClaimContext := { spec := default, binding := default, axioms := none } - let claim ← match Ix.Commit.evalClaim ctx compileEnv' [] input output - voteType with - | .ok claim => pure claim - | .error e => return (false, 0, 0, some s!"evalClaim failed: {e}") + let claim ← expectOk ((Ix.Commit.evalClaim ctx compileEnv' [] input output voteType).mapError (s!"evalClaim failed: {·}")) match claim with | .eval _ i o _ => if i == o then - return (false, 0, 0, some "degenerate claim: input addr = output addr") - return (true, 0, 0, none) - | _ => return (false, 0, 0, some "expected an eval claim") + fail "degenerate claim: input addr = output addr" + | _ => fail "expected an eval claim" -def suite : List TestSeq := [ - .individualIO "materialize ∘ compile is exact and root-stable" none - roundtripTest .done, - .individualIO "only-scoped materialization returns the closure" none - closureTest .done, - .individualIO "import_ixe elaborates a consumer file (C8)" none - elabTest .done, - .individualIO "commit + eval claim over imported constants (C9)" none - zkPatternTest .done ] +def suite : LSpec.Spec := do + it "materialize ∘ compile is exact and root-stable" roundtripTest + it "only-scoped materialization returns the closure" closureTest + sequential do + it "import_ixe elaborates a consumer file (C8)" elabTest + it "commit + eval claim over imported constants (C9)" zkPatternTest end Tests.Ix.ImportIxe diff --git a/Tests/Ix/InitStd.lean b/Tests/Ix/InitStd.lean index 4774515f96..19fe0c2356 100644 --- a/Tests/Ix/InitStd.lean +++ b/Tests/Ix/InitStd.lean @@ -167,7 +167,9 @@ def tail (out : IO.Process.Output) : String := s!"{(out.stdout.takeEnd 2000).toString}\n{(out.stderr.takeEnd 2000).toString}" def reportChecks (name : String) (checks : Array (String × Bool)) : IO UInt32 := - LSpec.lspecIO (.ofList [(name, checks.toList.map fun (label, ok) => LSpec.test label ok)]) [] + LSpec.lspecMain (LSpec.describe name do + for (label, ok) in checks do + LSpec.itCheck label (fun () => ok)) [] /-- `initstd-reference`. -/ def reference : IO UInt32 := do @@ -268,7 +270,7 @@ def fidelity : IO UInt32 := do reportChecks "fidelity-initstd" #[ ("ix validate-lean on Init+Std exits 0", out.exitCode == 0), ("its report has the five phases, every one passed", - match verdict with | .ok n => n ≥ 5 | .error _ => false)] + match verdict with | .ok n => decide (n ≥ 5) | .error _ => false)] finally IO.FS.removeDirAll dir diff --git a/Tests/Ix/IxVM/Eval.lean b/Tests/Ix/IxVM/Eval.lean index 0773498c64..11cd594077 100644 --- a/Tests/Ix/IxVM/Eval.lean +++ b/Tests/Ix/IxVM/Eval.lean @@ -528,15 +528,15 @@ normalizer. Closed numeric examples additionally pin a hand-computed result. Neutral terms deliberately avoid arithmetic, where Lean and IxVM choose different representations for stuck primitives. -/ def difficultTests (leanEnv : Lean.Environment) (base : Ix.CompileM.CompileEnv) - (env : Ixon.Env) (r : Tests.Ix.IxVM.Runner) : IO TestSeq := do - let mut seq : TestSeq := .done + (env : Ixon.Env) (r : Tests.Ix.IxVM.Runner) : IO Spec := do + let mut checks : Array (String × Bool) := #[] for name in difficultNumeric.map Prod.fst ++ difficultNeutral do let some (.defnInfo info) := leanEnv.find? name | throw <| IO.userError s!"expected definition: {name}" let expected ← runMeta (Lean.Meta.withTransparency .all (Lean.Meta.reduceAll info.value)) leanEnv if let some (_, n) := difficultNumeric.find? (fun p => p.1 == name) then - seq := seq ++ test s!"Lean oracle agrees with pinned result: {name}" - (expected == .lit (.natVal n)) + checks := checks.push (s!"Lean oracle agrees with pinned result: {name}", + expected == .lit (.natVal n)) let input ← lookupAddr env name let (fixture, obj) ← compiledOutput base env info.levelParams info.type expected r.build <| execute s!"Lean differential: {name}" (← witness fixture input obj) @@ -550,8 +550,8 @@ def difficultTests (leanEnv : Lean.Environment) (base : Ix.CompileM.CompileEnv) let input ← lookupAddr env ``Fixtures.wellFoundedTree let (fixture, output) ← natOutput env 15 let opaqueId ← lookupAddr env ``Lean.opaqueId - seq := seq ++ test "generated WF fixture contains the opaqueId dependency" - ((closureFrom env input).contains opaqueId) + checks := checks.push ("generated WF fixture contains the opaqueId dependency", + (closureFrom env input).contains opaqueId) r.build <| execute "opaque accessibility proof blocks kernel evaluation" (← witness fixture input output) (some "result does not match") -- This explicit proof does expose constructors to Acc.rec. Meta keeps its @@ -578,7 +578,9 @@ def difficultTests (leanEnv : Lean.Environment) (base : Ix.CompileM.CompileEnv) let input ← lookupAddr env ``Fixtures.openZero r.build <| execute "symbolic Nat addition exposes zero after argument reduction" (← witness env input (definition natArrow (.leanLam (.ref 0 #[]) (.var 0)) #[nat] 0 #[])) - return seq + return do + for (label, ok) in checks do + itBool label ok private structure GenState where seed : UInt64 := 0x4958564d @@ -621,18 +623,18 @@ private def genNat (fuel : Nat) (locals : List Nat) : def differentialTests (leanEnv : Lean.Environment) (base : Ix.CompileM.CompileEnv) (sharedEnv : Ixon.Env) (r : Tests.Ix.IxVM.Runner) - (count : Nat := 24) : IO TestSeq := do + (count : Nat := 24) : IO Spec := do let ty := Lean.mkConst ``Nat let mut state : GenState := {} - let mut seq : TestSeq := .done + let mut checks : Array (String × Bool) := #[] for i in [:count] do let seed := state.seed let ((value, answer), next) := (genNat 4 []).run state state := next let label := s!"generated arithmetic {i}, seed {seed}" let nf ← runMeta (Lean.Meta.withTransparency .all (Lean.Meta.reduceAll value)) leanEnv - seq := seq ++ test s!"Lean agrees with independent numeric oracle: {label}" - (nf == .lit (.natVal answer)) + checks := checks.push (s!"Lean agrees with independent numeric oracle: {label}", + nf == .lit (.natVal answer)) let (input, cache) ← IO.ofExcept (Ix.Commit.compileDef base [] ty value) let some bytes := cache.constants[input]? | throw <| IO.userError "missing generated input" let c : Ixon.Constant ← IO.ofExcept (Ixon.de bytes) @@ -644,9 +646,11 @@ def differentialTests (leanEnv : Lean.Environment) (base : Ix.CompileM.CompileEn r.build <| execute s!"mutated output: {label}" (← witness fixture input wrong) (some "result does not match") if count ≥ 24 then - seq := seq ++ test "generated corpus covers add/mul/sub/let/beta/div/mod" - (state.coverage.all (· > 0)) - return seq + checks := checks.push ("generated corpus covers add/mul/sub/let/beta/div/mod", + state.coverage.all (· > 0)) + return do + for (label, ok) in checks do + itBool label ok private def packBundle (env : Ixon.Env) (root : Address) : IO Ixon.Env := do let name := Ix.Name.mkStr Ix.Name.mkAnon "_obj" @@ -665,7 +669,7 @@ private def packBundle (env : Ixon.Env) (root : Address) : IO Ixon.Env := do /-- Check the command's printed claim against an independent construction, transport both endpoints through ordinary bundles, then execute the claim. -/ def commandTests (leanEnv : Lean.Environment) (base : Ix.CompileM.CompileEnv) - (sharedEnv : Ixon.Env) (r : Tests.Ix.IxVM.Runner) : IO TestSeq := do + (sharedEnv : Ixon.Env) (r : Tests.Ix.IxVM.Runner) : IO Spec := do let (claim, cache) ← IO.ofExcept (Ix.Commit.evalClaimWithEnv evalCtx base [] (Lean.mkConst ``Fixtures.arithmetic) (.lit (.natVal 42)) (Lean.mkConst ``Nat)) let .eval _ input output _ := claim | throw <| IO.userError "expected Eval claim" @@ -690,33 +694,33 @@ def commandTests (leanEnv : Lean.Environment) (base : Ix.CompileM.CompileEnv) let messages ← state.messages.toList.mapM fun msg => do pure (msg.severity, ← msg.data.toString) let expected := s!"42\n{claim}\ndigest {Address.blake3 (Ix.Claim.ser claim)}" - let seq := test "command prints the expected result, Eval claim, and digest" - (messages == [(.information, expected)]) + let msgOk := messages == [(.information, expected)] let inputBundle ← packBundle env input let outputBundle ← packBundle env output - let seq := seq ++ test "bundles retain the claim's individual constant addresses" - (inputBundle.main == some input && outputBundle.main == some output) - ++ test "output bundle prunes the input and display metadata" - (!outputBundle.consts.contains input && outputBundle.named.isEmpty) + let retainOk := inputBundle.main == some input && outputBundle.main == some output + let pruneOk := !outputBundle.consts.contains input && outputBundle.named.isEmpty let transported := { inputBundle with consts := outputBundle.consts.fold (fun m k v => m.insert k v) inputBundle.consts blobs := outputBundle.blobs.fold (fun m k v => m.insert k v) inputBundle.blobs anonHints := outputBundle.anonHints.fold (fun m k v => m.insert k v) inputBundle.anonHints } let w ← IO.ofExcept (buildClaimWitness transported claim) r.build (execute "command claim after bundle transport" w (exactPin := true)) - return seq + return do + itBool "command prints the expected result, Eval claim, and digest" msgOk + itBool "bundles retain the claim's individual constant addresses" retainOk + itBool "output bundle prunes the input and display metadata" pruneOk /-- IxCK's reader on the same Nat literal blobs as the program: the compiler's `[0]` and `[42]` are read, a trailing zero byte and the empty blob are refused (`Ix.Kernel.Reader.canonicalNatural`), each output record through the certified entry under the default table. -/ -def natBlobParity (env : Ixon.Env) : IO TestSeq := do +def natBlobParity (env : Ixon.Env) : IO Spec := do let some binding := Ix.Kernel.Admission.defaultBinding.toOption - | return test "the default role table loads" false + | return itBool "the default role table loads" false let limits : Ix.Kernel.Admission.Limits := { maxRecords := 1 <<< 22, maxBlobs := 1 <<< 22, maxTotalBytes := 1 <<< 34, maxRecordBytes := 1 <<< 28, maxRecordUnivNodes := 1 <<< 26 } - let mut tests := TestSeq.done + let mut checks : Array (String × Bool) := #[] for (label, blob, canonical) in [("[0]", ByteArray.mk #[0], true), ("[42]", ByteArray.mk #[42], true), ("[42, 0]", ByteArray.mk #[42, 0], false), ("[]", ByteArray.empty, false)] do let (_, c) ← natBlobOutput env blob @@ -727,16 +731,19 @@ def natBlobParity (env : Ixon.Env) : IO TestSeq := do | .ok _, true => true | .error e, false => ((toString e).splitOn "natural literal blob is not canonical").length > 1 | _, _ => false - tests := tests ++ test s!"IxCK's reader {if canonical then "reads" else "refuses"} the Nat literal blob {label}" - (ok && Ix.Kernel.Reader.canonicalNatural blob == canonical) - return tests + checks := checks.push ( + s!"IxCK's reader {if canonical then "reads" else "refuses"} the Nat literal blob {label}", + ok && Ix.Kernel.Reader.canonicalNatural blob == canonical) + return do + for (label, ok) in checks do + itBool label ok /-- Run the evaluation suite: `full = false` (PR `ci:ixvm`) runs all handcrafted, compiled, difficult, command, and parity cases plus 6 generated arithmetic pairs and 4 boundary truncation offsets; `full = true` (`ci:nightly`) runs all 24 generated arithmetic pairs (`0..23`) and verifies every FFT pin in `evalFftCosts`. -/ def runWith (leanEnv : Lean.Environment) (suiteName : String) (full : Bool) : IO UInt32 := do - let oracles ← IO.mkRef TestSeq.done + let oracles ← IO.mkRef (pure () : Spec) let genCount := if full then 24 else 6 -- Compile all Eval fixtures once and attach default role binding & models once. let allNames := @@ -755,7 +762,7 @@ def runWith (leanEnv : Lean.Environment) (suiteName : String) (full : Bool) : IO let generated ← differentialTests leanEnv base sharedEnv r (count := genCount) let command ← commandTests leanEnv base sharedEnv r let parity ← natBlobParity sharedEnv - oracles.set (difficult ++ generated ++ command ++ parity) + oracles.set (do difficult; generated; command; parity) let labels ← r.labels.get for (name, _) in evalFftCosts do if !full && name.startsWith "generated arithmetic " then @@ -763,7 +770,7 @@ def runWith (leanEnv : Lean.Environment) (suiteName : String) (full : Bool) : IO if idx?.any (· ≥ genCount) then continue unless labels.contains s!"eval accepts {name}" do r.fail s!"unused evaluation FFT pin: {name}" - let lean ← lspecIO (.ofList [(s!"{suiteName} oracles", [← oracles.get])]) [] + let lean ← lspecMain (describe s!"{suiteName} oracles" (← oracles.get)) [] return if code == 0 && lean == 0 then 0 else 1 /-- PR fast evaluation suite. -/ diff --git a/Tests/Ix/IxVM/Exploits.lean b/Tests/Ix/IxVM/Exploits.lean index 1c1da4be47..9b0a5c2549 100644 --- a/Tests/Ix/IxVM/Exploits.lean +++ b/Tests/Ix/IxVM/Exploits.lean @@ -2293,7 +2293,7 @@ def nativeEvaluationNames : List Lean.Name := claim seeds as well as their uses), and the check that an environment declaring the compiler-trust axioms lists no user axiom. -/ def axiomPolicyCases (ctx : Ix.ClaimContext) (env : Ixon.Env) : - IO (Array ExploitCase × TestSeq) := do + IO (Array ExploitCase × Spec) := do -- Check IxCK over just the native-evaluation + uses closure sliced out of the shared compiled env. -- Include `True.rec` in the sliced scope because `Lean.trustCompiler : True` references `True` -- (which is not in `RoleData.prelude`) and IxCK requires every non-prelude inductive block's recursor. @@ -2324,14 +2324,15 @@ def axiomPolicyCases (ctx : Ix.ClaimContext) (env : Ixon.Env) : | some ("blocked", r) => (true, false, s!"blocked behind {r}") | some (o, r) => (true, false, s!"reject ({o}: {(r.take 120).toString})") | none => (false, false, "no IxCK verdict") - let declTests := nativeEvaluationNames.foldl (init := .done) fun acc n => + let mut ixcChecks : Array (String × Bool) := #[] + for n in nativeEvaluationNames do let (present, accepted, label) := verdictOf n - acc ++ test s!"IxCK tolerates inert compiler-trust declaration {n} ({label})" - (present && accepted) - let ixcTests := nativeUses.foldl (init := declTests) fun acc n => + ixcChecks := ixcChecks.push (s!"IxCK tolerates inert compiler-trust declaration {n} ({label})", + present && accepted) + for n in nativeUses do let (present, accepted, label) := verdictOf n - acc ++ test s!"IxCK refuses use of inert compiler-trust axiom {n} ({label})" - (present && !accepted) + ixcChecks := ixcChecks.push (s!"IxCK refuses use of inert compiler-trust axiom {n} ({label})", + present && !accepted) let mut out : Array ExploitCase := #[] for n in nativeEvaluationNames do let addr ← IxVM.ClaimHarness.lookupAddr env n @@ -2349,8 +2350,9 @@ def axiomPolicyCases (ctx : Ix.ClaimContext) (env : Ixon.Env) : -- An environment that declares the compiler-trust axioms names no user axiom: -- the default table binds them as inert roles. let envCtx ← IO.ofExcept (Ix.ClaimContext.ofEnv env true) - let treeTest := test "an environment declaring the compiler-trust axioms has no user axioms tree" - (envCtx.axioms.isNone && (Ix.ClaimContext.userAxioms env).isEmpty) + ixcChecks := ixcChecks.push ( + "an environment declaring the compiler-trust axioms has no user axioms tree", + envCtx.axioms.isNone && (Ix.ClaimContext.userAxioms env).isEmpty) let (axEnv, axAddr) := storeAt env propAxiom out := out.push { name := "axiom-arbitrary" intent := "an arbitrary safe axiom (`axiom _ : Prop`) declared in a \ @@ -2376,7 +2378,10 @@ def axiomPolicyCases (ctx : Ix.ClaimContext) (env : Ixon.Env) : declares the compiler-trust axioms, in the context `ClaimContext.ofEnv` \ gives it (no user axioms), which must be accepted" env, claim := .check envCtx boolFalseA none, expectAccept := true } - return (out, ixcTests ++ treeTest) + let ixcSpec : Spec := do + for (label, ok) in ixcChecks do + itBool label ok + return (out, ixcSpec) /-! ## Runner -/ @@ -2638,7 +2643,7 @@ def ExploitCase.toCase (c : ExploitCase) : Except String Tests.Ix.IxVM.Case := d /-- Every case, through the production claim entry point (`verify_claim`): each exploit must be rejected and each control accepted. -/ -def exploitCases (leanEnv : Lean.Environment) : IO (Array ExploitCase × TestSeq) := do +def exploitCases (leanEnv : Lean.Environment) : IO (Array ExploitCase × Spec) := do -- Compile all Lean fixtures into one shared Ixon environment once. let allNames := #[``String, ``True, ``True.intro, ``True.rec, ``False, ``Eq, ``Eq.refl, ``Bool, ``Bool.rec, ``Nat.beq, @@ -2702,14 +2707,14 @@ controls, and one fast-failing `.binding` smoke. -/ def run (leanEnv : Lean.Environment) : IO UInt32 := do let (cases, ixcTests) ← exploitCases leanEnv let fast := cases.filter keepInFastExploits - let ixc ← lspecIO (.ofList [("ixvm-exploits IxCK", [ixcTests])]) [] + let ixc ← lspecMain (describe "ixvm-exploits IxCK" ixcTests) [] let ixvm ← Tests.Ix.IxVM.runCases "ixvm-exploits" (fast.map fun c _ => c.toCase) return if ixc == 0 && ixvm == 0 then 0 else 1 /-- Full nightly suite: every exploit and control, including all `.binding` cases. -/ def runFull (leanEnv : Lean.Environment) : IO UInt32 := do let (cases, ixcTests) ← exploitCases leanEnv - let ixc ← lspecIO (.ofList [("ixvm-exploits IxCK", [ixcTests])]) [] + let ixc ← lspecMain (describe "ixvm-exploits IxCK" ixcTests) [] let ixvm ← Tests.Ix.IxVM.runCases "ixvm-exploits-full" (cases.map fun c _ => c.toCase) return if ixc == 0 && ixvm == 0 then 0 else 1 diff --git a/Tests/Ix/IxVM/TagN.lean b/Tests/Ix/IxVM/TagN.lean index e9bd5be545..1874626587 100644 --- a/Tests/Ix/IxVM/TagN.lean +++ b/Tests/Ix/IxVM/TagN.lean @@ -210,25 +210,24 @@ def fieldOfWidth (f : Nat) : Field := if f == 0 then .lvls else if f == 2 then . /-- The host writes the expected bytes, and `Canonical.deConstant` accepts every valid rewritten constant in `expectedVectors` and `boundaryCases` (rejecting only level counts `≥ Ixon.maxLevelCount`). -/ -def expectedHostTests : TestSeq := - let encodingTests := expectedVectors.foldl (init := .done) fun acc (f, flag, v, bytes) => +def expectedHostTests : LSpec.Spec := do + for (f, flag, v, bytes) in expectedVectors do let field := fieldOfWidth f let effFlag := if field == .type && !(flags .type v).contains flag then 0x1 else flag let enc : ByteArray := if field == .type then tagNBytes 4 effFlag v else ⟨bytes⟩ let rewritten := rewrite field enc let expectOk := field != .lvls || v < Ixon.maxLevelCount - acc ++ test s!"host TagN f={f} flag={flag} writes {v} as {bytes}" + itBool s!"host TagN f={f} flag={flag} writes {v} as {bytes}" (tagNBytes f flag v == ⟨bytes⟩) - ++ test s!"host Canonical.deConstant accepts={expectOk} expected f={f} value={v}" - ((Ixon.Canonical.deConstant rewritten.size Ixon.loadMaxUnivNodes rewritten).isOk == expectOk) - let boundaryDecodeTests := fields.foldl (init := .done) fun acc field => - (boundaries field.width).foldl (init := acc) fun acc v => - (flags field v).foldl (init := acc) fun acc flag => + itBool s!"host Canonical.deConstant accepts={expectOk} expected f={f} value={v}" + ((Ixon.Canonical.deConstant rewritten.size Ixon.loadMaxUnivNodes rewritten).isOk == expectOk) + for field in fields do + for v in boundaries field.width do + for flag in flags field v do let rewritten := rewrite field (encodingOf field flag v) let expectOk := field != .lvls || v < Ixon.maxLevelCount - acc ++ test s!"host Canonical.deConstant accepts={expectOk} boundary f={field.width} flag={flag} value={v}" + itBool s!"host Canonical.deConstant accepts={expectOk} boundary f={field.width} flag={flag} value={v}" ((Ixon.Canonical.deConstant rewritten.size Ixon.loadMaxUnivNodes rewritten).isOk == expectOk) - encodingTests ++ boundaryDecodeTests /-- The expected encodings in their field. A flag the field gives no free value (an expression of another kind) is read under the field's own flag. -/ @@ -389,7 +388,7 @@ def invalidCodeSample (_ : Unit) : Array Builder := Id.run do /-- PR fast suite: host checks, all expected/rejected/boundary/level-count/parity/ universe-variable cases, and a boundary sample of invalid codes. -/ def run : IO UInt32 := do - let host ← lspecIO (.ofList [("ixvm-tagn host", [expectedHostTests])]) [] + let host ← lspecMain (describe "ixvm-tagn host" expectedHostTests) [] let cases := expectedCases () ++ rejectedCases () ++ boundaryCases () ++ invalidCodeSample () ++ levelCountCases () ++ levelCountParityCases () ++ universeVariableCases () -- The universe-variable cases are decided by the circuit's range check, so diff --git a/Tests/Ix/Ixon.lean b/Tests/Ix/Ixon.lean index 9623c52cf4..c69084c29d 100644 --- a/Tests/Ix/Ixon.lean +++ b/Tests/Ix/Ixon.lean @@ -10,9 +10,11 @@ public import Tests.Ix.RolePacking public import Tests.Ix.HostAdmission public import Tests.Ix.CircuitMeta -open LSpec SlimCheck Gen Ixon +open LSpec LSpec.Prop Ixon open Tests.FFI.Ixon (rsEqUnivSerialization rsEqExprSerialization rsEqConstantSerialization rsEqEnvSerialization) +set_option compiler.extract_closed false + /-! ## Roundtrip Tests for New Format Types -/ @@ -58,7 +60,7 @@ def envSerde (raw : RawEnv) : Bool := ## Unit Tests for New Format Types -/ -def univUnits : TestSeq := +def univUnits : LSpec.Spec := do let cases : List Univ := [ .zero, .var 0, @@ -76,10 +78,9 @@ def univUnits : TestSeq := .imax (.var 1) .zero, .max (.succ .zero) (.succ (.succ .zero)), ] - cases.foldl (init := .done) fun acc u => - acc ++ test s!"Univ roundtrip: {repr u}" (univSerde u) ++ - test s!"Univ Lean==Rust bytes: {repr u}" - (rsEqUnivSerialization u (serUniv u)) + for u in cases do + itBool s!"Univ roundtrip: {repr u}" (univSerde u) + itBool s!"Univ Lean==Rust bytes: {repr u}" (rsEqUnivSerialization u (serUniv u)) def univPrefixAccepts (bytes : ByteArray) : Bool := match runGet getUniv bytes with @@ -91,14 +92,15 @@ def univExactRejects (bytes : ByteArray) : Bool := | .error _ => true | .ok _ => false -def univExactUnits : TestSeq := - let bytes := serUniv Univ.zero ++ [0].toByteArray - test "Univ prefix runner may leave trailing bytes" - (univPrefixAccepts bytes) ++ - test "Univ full-buffer decoder rejects trailing bytes" - (univExactRejects bytes) +def univExactUnits : LSpec.Spec := do + it "Univ prefix runner may leave trailing bytes" do + let bytes := serUniv Univ.zero ++ [0].toByteArray + expect (univPrefixAccepts bytes) + it "Univ full-buffer decoder rejects trailing bytes" do + let bytes := serUniv Univ.zero ++ [0].toByteArray + expect (univExactRejects bytes) -def exprUnits : TestSeq := +def exprUnits : LSpec.Spec := do let cases : List Expr := [ .sort 0, .var 0, @@ -122,10 +124,9 @@ def exprUnits : TestSeq := .letE true .borrow (.sort 0) (.var 0) (.var 1), .prj 0 1 (.var 0), ] - cases.foldl (init := .done) fun acc e => - acc ++ test s!"Expr roundtrip: {repr e}" (exprSerde e) ++ - test s!"Expr Lean==Rust bytes: {repr e}" - (rsEqExprSerialization e (serExpr e)) + for e in cases do + itBool s!"Expr roundtrip: {repr e}" (exprSerde e) + itBool s!"Expr Lean==Rust bytes: {repr e}" (rsEqExprSerialization e (serExpr e)) def exprPrefixAccepts (bytes : ByteArray) : Bool := match runGet getExpr bytes with @@ -137,12 +138,13 @@ def exprExactRejects (bytes : ByteArray) : Bool := | .error _ => true | .ok _ => false -def exprExactUnits : TestSeq := - let bytes := serExpr (.sort 0) ++ [0].toByteArray - test "Expr prefix runner may leave trailing bytes" - (exprPrefixAccepts bytes) ++ - test "Expr full-buffer decoder rejects trailing bytes" - (exprExactRejects bytes) +def exprExactUnits : LSpec.Spec := do + it "Expr prefix runner may leave trailing bytes" do + let bytes := serExpr (.sort 0) ++ [0].toByteArray + expect (exprPrefixAccepts bytes) + it "Expr full-buffer decoder rejects trailing bytes" do + let bytes := serExpr (.sort 0) ++ [0].toByteArray + expect (exprExactRejects bytes) def exprPrefixRejects (bytes : Array UInt8) : Bool := match runGet getExpr (ByteArray.mk bytes) with @@ -153,13 +155,13 @@ def exprPrefixRejects (bytes : Array UInt8) : Bool := `runGet getExpr` so rejection comes from the grammar itself rather than trailing bytes. Reserved let codes and additional malformed vectors are covered by `Tests.IxonGolden.rejectedExprCases`. -/ -def strictExprUnits : TestSeq := - test "rejects empty app spine" (exprPrefixRejects #[0x70]) ++ - test "rejects nested app base" - (exprPrefixRejects #[0x71, 0x71, 0x10, 0x11, 0x12]) ++ - test "rejects nested lambda body" - (exprPrefixRejects #[0x81, 0x00, 0x81, 0x00, 0x10]) ++ - test "rejects nested forall codomain" +def strictExprUnits : LSpec.Spec := do + itBool "rejects empty app spine" (exprPrefixRejects #[0x70]) + itBool "rejects nested app base" + (exprPrefixRejects #[0x71, 0x71, 0x10, 0x11, 0x12]) + itBool "rejects nested lambda body" + (exprPrefixRejects #[0x81, 0x00, 0x81, 0x00, 0x10]) + itBool "rejects nested forall codomain" (exprPrefixRejects #[0x91, 0x00, 0x91, 0x00, 0x10]) /-! ## TagN integer code -/ @@ -199,83 +201,82 @@ def tagNShortCanonical (f : Nat) : Bool := Id.run do if runPut (putTagN f t.flag t.value) != two then return false return true -def tagNUnits : TestSeq := - let perF (f : Nat) : TestSeq := +def tagNUnits : LSpec.Spec := do + for f in [0, 2, 4] do let flags : List UInt8 := [0, (2 ^ f - 1).toUInt8] - let cases := flags.flatMap fun flag => (tagNBoundaries f).map (flag, ·) - cases.foldl (init := .done) fun acc (flag, v) => - acc ++ test s!"TagN f={f} flag={flag} value={v}: width and roundtrip" - (tagNRoundtrip f flag v) - perF 0 ++ perF 2 ++ perF 4 ++ - test "TagN rung ends f=0" ([tagNEnd1 0, tagNEnd2 0, tagNEnd3 0, tagNEnd4 0, tagNEnd5 0] - == [128, 16512, 82048, 16859264, 4311826560]) ++ - test "TagN rung ends f=2" ([tagNEnd1 2, tagNEnd2 2, tagNEnd3 2, tagNEnd4 2, tagNEnd5 2] - == [32, 4128, 69664, 16846880, 4311814176]) ++ - test "TagN rung ends f=4" ([tagNEnd1 4, tagNEnd2 4, tagNEnd3 4, tagNEnd4 4, tagNEnd5 4] - == [8, 1032, 66568, 16843784, 4311811080]) ++ - test "TagN f=4 bytes: 7" (tagNEncodes 4 0xA 7 #[0xA7]) ++ - test "TagN f=4 bytes: 8" (tagNEncodes 4 0xA 8 #[0xA8, 0x00]) ++ - test "TagN f=4 bytes: 1031" (tagNEncodes 4 0x1 1031 #[0x1B, 0xFF]) ++ - test "TagN f=4 bytes: 1032" (tagNEncodes 4 0 1032 #[0x0C, 0x00, 0x00]) ++ - test "TagN f=4 bytes: 66567" (tagNEncodes 4 0 66567 #[0x0C, 0xFF, 0xFF]) ++ - test "TagN f=4 bytes: 66568" (tagNEncodes 4 0 66568 #[0x0D, 0, 0, 0]) ++ - test "TagN f=4 bytes: 16843783" (tagNEncodes 4 0 16843783 #[0x0D, 0xFF, 0xFF, 0xFF]) ++ - test "TagN f=4 bytes: 16843784" (tagNEncodes 4 0 16843784 #[0x0E, 0, 0, 0, 0]) ++ - test "TagN f=4 bytes: 4311811079" - (tagNEncodes 4 0 4311811079 #[0x0E, 0xFF, 0xFF, 0xFF, 0xFF]) ++ - test "TagN f=4 bytes: 4311811080" - (tagNEncodes 4 0 4311811080 #[0x0F, 0, 0, 0, 0, 0, 0, 0, 0]) ++ - test "TagN f=0 bytes: 127" (tagNEncodes 0 0 127 #[0x7F]) ++ - test "TagN f=0 bytes: 128" (tagNEncodes 0 0 128 #[0x80, 0x00]) ++ - test "TagN f=0 bytes: 16512" (tagNEncodes 0 0 16512 #[0xC0, 0x00, 0x00]) ++ - test "TagN f=0 bytes: 82047" (tagNEncodes 0 0 82047 #[0xC0, 0xFF, 0xFF]) ++ - test "TagN f=0 bytes: 82048" (tagNEncodes 0 0 82048 #[0xC1, 0, 0, 0]) ++ - test "TagN f=0 bytes: 16859263" (tagNEncodes 0 0 16859263 #[0xC1, 0xFF, 0xFF, 0xFF]) ++ - test "TagN f=0 bytes: 16859264" (tagNEncodes 0 0 16859264 #[0xC2, 0, 0, 0, 0]) ++ - test "TagN f=0 bytes: 4311826560" - (tagNEncodes 0 0 4311826560 #[0xC3, 0, 0, 0, 0, 0, 0, 0, 0]) ++ - test "TagN f=0 bytes: 2^64 - 1" - (tagNEncodes 0 0 (2 ^ 64 - 1) #[0xC3, 0x7F, 0xBF, 0xFE, 0xFE, 0xFE, 0xFF, 0xFF, 0xFF]) ++ - test "TagN f=2 bytes: 32" (tagNEncodes 2 3 32 #[0xE0, 0x00]) ++ - test "TagN f=2 bytes: 4128" (tagNEncodes 2 3 4128 #[0xF0, 0x00, 0x00]) ++ - test "TagN f=2 bytes: 69663" (tagNEncodes 2 3 69663 #[0xF0, 0xFF, 0xFF]) ++ - test "TagN f=2 bytes: 69664" (tagNEncodes 2 3 69664 #[0xF1, 0, 0, 0]) ++ - test "TagN f=2 bytes: 16846879" (tagNEncodes 2 3 16846879 #[0xF1, 0xFF, 0xFF, 0xFF]) ++ - test "TagN f=2 bytes: 16846880" (tagNEncodes 2 3 16846880 #[0xF2, 0, 0, 0, 0]) ++ - test "TagN f=2 bytes: 4311814176" - (tagNEncodes 2 3 4311814176 #[0xF3, 0, 0, 0, 0, 0, 0, 0, 0]) ++ - test "TagN f=2 rejects code 4" (tagNRejects 2 #[0x34]) ++ - test "TagN f=2 rejects code 15" (tagNRejects 2 #[0x3F]) ++ - test "TagN f=0 rejects code 4" (tagNRejects 0 #[0xC4]) ++ - test "TagN f=0 rejects code 63" (tagNRejects 0 #[0xFF]) ++ - test "TagN f=4 rejects overflow" - (tagNRejects 4 #[0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]) ++ - test "TagN f=0 rejects overflow" - (tagNRejects 0 #[0xC3, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]) ++ + for flag in flags do + for v in tagNBoundaries f do + itBool s!"TagN f={f} flag={flag} value={v}: width and roundtrip" + (tagNRoundtrip f flag v) + itBool "TagN rung ends f=0" ([tagNEnd1 0, tagNEnd2 0, tagNEnd3 0, tagNEnd4 0, tagNEnd5 0] + == [128, 16512, 82048, 16859264, 4311826560]) + itBool "TagN rung ends f=2" ([tagNEnd1 2, tagNEnd2 2, tagNEnd3 2, tagNEnd4 2, tagNEnd5 2] + == [32, 4128, 69664, 16846880, 4311814176]) + itBool "TagN rung ends f=4" ([tagNEnd1 4, tagNEnd2 4, tagNEnd3 4, tagNEnd4 4, tagNEnd5 4] + == [8, 1032, 66568, 16843784, 4311811080]) + itBool "TagN f=4 bytes: 7" (tagNEncodes 4 0xA 7 #[0xA7]) + itBool "TagN f=4 bytes: 8" (tagNEncodes 4 0xA 8 #[0xA8, 0x00]) + itBool "TagN f=4 bytes: 1031" (tagNEncodes 4 0x1 1031 #[0x1B, 0xFF]) + itBool "TagN f=4 bytes: 1032" (tagNEncodes 4 0 1032 #[0x0C, 0x00, 0x00]) + itBool "TagN f=4 bytes: 66567" (tagNEncodes 4 0 66567 #[0x0C, 0xFF, 0xFF]) + itBool "TagN f=4 bytes: 66568" (tagNEncodes 4 0 66568 #[0x0D, 0, 0, 0]) + itBool "TagN f=4 bytes: 16843783" (tagNEncodes 4 0 16843783 #[0x0D, 0xFF, 0xFF, 0xFF]) + itBool "TagN f=4 bytes: 16843784" (tagNEncodes 4 0 16843784 #[0x0E, 0, 0, 0, 0]) + itBool "TagN f=4 bytes: 4311811079" + (tagNEncodes 4 0 4311811079 #[0x0E, 0xFF, 0xFF, 0xFF, 0xFF]) + itBool "TagN f=4 bytes: 4311811080" + (tagNEncodes 4 0 4311811080 #[0x0F, 0, 0, 0, 0, 0, 0, 0, 0]) + itBool "TagN f=0 bytes: 127" (tagNEncodes 0 0 127 #[0x7F]) + itBool "TagN f=0 bytes: 128" (tagNEncodes 0 0 128 #[0x80, 0x00]) + itBool "TagN f=0 bytes: 16512" (tagNEncodes 0 0 16512 #[0xC0, 0x00, 0x00]) + itBool "TagN f=0 bytes: 82047" (tagNEncodes 0 0 82047 #[0xC0, 0xFF, 0xFF]) + itBool "TagN f=0 bytes: 82048" (tagNEncodes 0 0 82048 #[0xC1, 0, 0, 0]) + itBool "TagN f=0 bytes: 16859263" (tagNEncodes 0 0 16859263 #[0xC1, 0xFF, 0xFF, 0xFF]) + itBool "TagN f=0 bytes: 16859264" (tagNEncodes 0 0 16859264 #[0xC2, 0, 0, 0, 0]) + itBool "TagN f=0 bytes: 4311826560" + (tagNEncodes 0 0 4311826560 #[0xC3, 0, 0, 0, 0, 0, 0, 0, 0]) + itBool "TagN f=0 bytes: 2^64 - 1" + (tagNEncodes 0 0 (2 ^ 64 - 1) #[0xC3, 0x7F, 0xBF, 0xFE, 0xFE, 0xFE, 0xFF, 0xFF, 0xFF]) + itBool "TagN f=2 bytes: 32" (tagNEncodes 2 3 32 #[0xE0, 0x00]) + itBool "TagN f=2 bytes: 4128" (tagNEncodes 2 3 4128 #[0xF0, 0x00, 0x00]) + itBool "TagN f=2 bytes: 69663" (tagNEncodes 2 3 69663 #[0xF0, 0xFF, 0xFF]) + itBool "TagN f=2 bytes: 69664" (tagNEncodes 2 3 69664 #[0xF1, 0, 0, 0]) + itBool "TagN f=2 bytes: 16846879" (tagNEncodes 2 3 16846879 #[0xF1, 0xFF, 0xFF, 0xFF]) + itBool "TagN f=2 bytes: 16846880" (tagNEncodes 2 3 16846880 #[0xF2, 0, 0, 0, 0]) + itBool "TagN f=2 bytes: 4311814176" + (tagNEncodes 2 3 4311814176 #[0xF3, 0, 0, 0, 0, 0, 0, 0, 0]) + itBool "TagN f=2 rejects code 4" (tagNRejects 2 #[0x34]) + itBool "TagN f=2 rejects code 15" (tagNRejects 2 #[0x3F]) + itBool "TagN f=0 rejects code 4" (tagNRejects 0 #[0xC4]) + itBool "TagN f=0 rejects code 63" (tagNRejects 0 #[0xFF]) + itBool "TagN f=4 rejects overflow" + (tagNRejects 4 #[0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]) + itBool "TagN f=0 rejects overflow" + (tagNRejects 0 #[0xC3, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]) -- The smallest overflowing rung-6 payloads: 2^64 - R5 for each f, one past -- the payload of 2^64 - 1 (R5 = 0x1_0101_4080, 0x1_0101_1020, 0x1_0101_0408). - test "TagN f=0 rejects the smallest overflow" - (tagNRejects 0 #[0xC3, 0x80, 0xBF, 0xFE, 0xFE, 0xFE, 0xFF, 0xFF, 0xFF]) ++ - test "TagN f=2 accepts 2^64 - 1" - (tagNEncodes 2 0 (2 ^ 64 - 1) #[0x33, 0xDF, 0xEF, 0xFE, 0xFE, 0xFE, 0xFF, 0xFF, 0xFF]) ++ - test "TagN f=2 rejects the smallest overflow" - (tagNRejects 2 #[0x33, 0xE0, 0xEF, 0xFE, 0xFE, 0xFE, 0xFF, 0xFF, 0xFF]) ++ - test "TagN f=4 accepts 2^64 - 1" - (tagNEncodes 4 0 (2 ^ 64 - 1) #[0x0F, 0xF7, 0xFB, 0xFE, 0xFE, 0xFE, 0xFF, 0xFF, 0xFF]) ++ - test "TagN f=4 rejects the smallest overflow" - (tagNRejects 4 #[0x0F, 0xF8, 0xFB, 0xFE, 0xFE, 0xFE, 0xFF, 0xFF, 0xFF]) ++ + itBool "TagN f=0 rejects the smallest overflow" + (tagNRejects 0 #[0xC3, 0x80, 0xBF, 0xFE, 0xFE, 0xFE, 0xFF, 0xFF, 0xFF]) + itBool "TagN f=2 accepts 2^64 - 1" + (tagNEncodes 2 0 (2 ^ 64 - 1) #[0x33, 0xDF, 0xEF, 0xFE, 0xFE, 0xFE, 0xFF, 0xFF, 0xFF]) + itBool "TagN f=2 rejects the smallest overflow" + (tagNRejects 2 #[0x33, 0xE0, 0xEF, 0xFE, 0xFE, 0xFE, 0xFF, 0xFF, 0xFF]) + itBool "TagN f=4 accepts 2^64 - 1" + (tagNEncodes 4 0 (2 ^ 64 - 1) #[0x0F, 0xF7, 0xFB, 0xFE, 0xFE, 0xFE, 0xFF, 0xFF, 0xFF]) + itBool "TagN f=4 rejects the smallest overflow" + (tagNRejects 4 #[0x0F, 0xF8, 0xFB, 0xFE, 0xFE, 0xFE, 0xFF, 0xFF, 0xFF]) -- An invalid code followed by as many bytes as a valid rung would read: -- a reader that kept only the low two code bits would accept these. - test "TagN f=0 rejects code 4 with two following bytes" (tagNRejects 0 #[0xC4, 0x00, 0x00]) ++ - test "TagN f=2 rejects code 4 with two following bytes" (tagNRejects 2 #[0x34, 0x00, 0x00]) ++ - test "TagN rejects truncated rung 2" (tagNRejects 4 #[0x08]) ++ - test "TagN rejects truncated rung 4" (tagNRejects 4 #[0x0D, 0x00, 0x00]) ++ - test "TagN rejects truncated rung 5" (tagNRejects 4 #[0x0E, 0x00, 0x00, 0x00]) ++ - test "TagN rejects truncated rung 6" (tagNRejects 4 #[0x0F, 0x00, 0x00, 0x00]) ++ - test "TagN rejects trailing byte" (tagNRejects 4 #[0x07, 0x00]) ++ - test "TagN f=0 short strings canonical" (tagNShortCanonical 0) ++ - test "TagN f=2 short strings canonical" (tagNShortCanonical 2) ++ - test "TagN f=4 short strings canonical" (tagNShortCanonical 4) + itBool "TagN f=0 rejects code 4 with two following bytes" (tagNRejects 0 #[0xC4, 0x00, 0x00]) + itBool "TagN f=2 rejects code 4 with two following bytes" (tagNRejects 2 #[0x34, 0x00, 0x00]) + itBool "TagN rejects truncated rung 2" (tagNRejects 4 #[0x08]) + itBool "TagN rejects truncated rung 4" (tagNRejects 4 #[0x0D, 0x00, 0x00]) + itBool "TagN rejects truncated rung 5" (tagNRejects 4 #[0x0E, 0x00, 0x00, 0x00]) + itBool "TagN rejects truncated rung 6" (tagNRejects 4 #[0x0F, 0x00, 0x00, 0x00]) + itBool "TagN rejects trailing byte" (tagNRejects 4 #[0x07, 0x00]) + itBool "TagN f=0 short strings canonical" (tagNShortCanonical 0) + itBool "TagN f=2 short strings canonical" (tagNShortCanonical 2) + itBool "TagN f=4 short strings canonical" (tagNShortCanonical 4) /-! ## ExprMeta arena wire format @@ -284,16 +285,16 @@ explicit TagN backward deltas); the same vectors are pinned in Rust (`ixon::metadata::tests::arena_vector_*`). Name indices are 0 and 1 (one byte in every integer code). -/ -def arenaVecNames : Address × Address × NameIndex × NameReverseIndex := +def arenaVecNames (_ : Unit) : Address × Address × NameIndex × NameReverseIndex := let a := Address.blake3 (ByteArray.mk #[1]) let b := Address.blake3 (ByteArray.mk #[2]) (a, b, (({} : NameIndex).insert a 0).insert b 1, #[a, b]) def arenaBytes (arena : ExprMetaArena) : ByteArray := - runPut (putExprMetaArenaIndexed arena arenaVecNames.2.2.1) + runPut (putExprMetaArenaIndexed arena (arenaVecNames ()).2.2.1) def arenaFrom (bytes : Array UInt8) : Except String ExprMetaArena := - runGetExact (getExprMetaArenaIndexed arenaVecNames.2.2.2) (ByteArray.mk bytes) + runGetExact (getExprMetaArenaIndexed (arenaVecNames ()).2.2.2) (ByteArray.mk bytes) /-- The arena writes exactly `bytes`, and `bytes` read back to the arena. -/ def arenaVector (arena : ExprMetaArena) (bytes : Array UInt8) : Bool := @@ -307,57 +308,60 @@ def arenaRejects (bytes : Array UInt8) : Bool := | .error _ => true | .ok _ => false -def exprMetaArenaUnits : TestSeq := - let a := arenaVecNames.1 - let b := arenaVecNames.2.1 - -- `fun (x : T) => f x` in post-order: every child implicit. - let tree : ExprMetaArena := { nodes := #[ - .ref b, .ref a, .leaf, .app 1 2, .binder a .default 0 3] } - -- Shared nodes: explicit backward deltas next to implicit slots. - let dag : ExprMetaArena := { nodes := #[ - .leaf, .app 0 0, .letBinder a 0 1 0, .prj b 1, .mdata #[] 3] } - -- A forward reference wraps. - let forward : ExprMetaArena := { nodes := #[.leaf, .leaf, .leaf, .prj a 7] } - test "arena: a post-order tree writes no references" - (arenaVector tree #[0x05, 0x38, 0x01, 0x38, 0x00, 0x00, 0x0B, 0x13, 0x00]) ++ - test "arena: shared nodes are explicit backward deltas" - (arenaVector dag #[0x05, 0x00, 0x0A, 0x00, 0x32, 0x00, 0x01, 0x01, 0x40, - 0x01, 0x01, 0x49, 0x00]) ++ - test "arena: a forward reference wraps" - (arenaVector forward #[0x04, 0x00, 0x00, 0x00, - 0x40, 0x00, 0xC3, 0x7B, 0xBF, 0xFE, 0xFE, 0xFE, 0xFF, 0xFF, 0xFF]) ++ - test "arena: rejects the retired call-site kinds 10 and 11" +def exprMetaArenaUnits : LSpec.Spec := do + it "arena: a post-order tree writes no references" do + let (a, b, _, _) := arenaVecNames () + -- `fun (x : T) => f x` in post-order: every child implicit. + let tree : ExprMetaArena := { nodes := #[ + .ref b, .ref a, .leaf, .app 1 2, .binder a .default 0 3] } + expect (arenaVector tree #[0x05, 0x38, 0x01, 0x38, 0x00, 0x00, 0x0B, 0x13, 0x00]) + it "arena: shared nodes are explicit backward deltas" do + let (a, b, _, _) := arenaVecNames () + -- Shared nodes: explicit backward deltas next to implicit slots. + let dag : ExprMetaArena := { nodes := #[ + .leaf, .app 0 0, .letBinder a 0 1 0, .prj b 1, .mdata #[] 3] } + expect (arenaVector dag #[0x05, 0x00, 0x0A, 0x00, 0x32, 0x00, 0x01, 0x01, 0x40, + 0x01, 0x01, 0x49, 0x00]) + it "arena: a forward reference wraps" do + let (a, _, _, _) := arenaVecNames () + -- A forward reference wraps. + let forward : ExprMetaArena := { nodes := #[.leaf, .leaf, .leaf, .prj a 7] } + expect (arenaVector forward #[0x04, 0x00, 0x00, 0x00, + 0x40, 0x00, 0xC3, 0x7B, 0xBF, 0xFE, 0xFE, 0xFE, 0xFF, 0xFF, 0xFF]) + itBool "arena: rejects the retired call-site kinds 10 and 11" (arenaRejects #[0x01, 0x50, 0x00, 0x00, 0x00, 0x00, 0x00] && - arenaRejects #[0x01, 0x58, 0x00, 0x00, 0x00, 0x00, 0x00]) ++ - test "arena: rejects an explicit slot at the implicit position" - (arenaRejects #[0x02, 0x00, 0x08, 0x00, 0x00]) ++ - test "arena: rejects an implicit slot with no preceding node" - (arenaRejects #[0x01, 0x09, 0x00]) ++ - test "arena: rejects mask bits beyond the kind's slots" + arenaRejects #[0x01, 0x58, 0x00, 0x00, 0x00, 0x00, 0x00]) + itBool "arena: rejects an explicit slot at the implicit position" + (arenaRejects #[0x02, 0x00, 0x08, 0x00, 0x00]) + itBool "arena: rejects an implicit slot with no preceding node" + (arenaRejects #[0x01, 0x09, 0x00]) + itBool "arena: rejects mask bits beyond the kind's slots" (arenaRejects #[0x01, 0x01] && arenaRejects #[0x02, 0x00, 0x0C] && - arenaRejects #[0x01, 0x39, 0x00]) ++ - test "arena: rejects unknown kinds" (arenaRejects #[0x01, 0x60]) ++ - test "arena: rejects every truncation" + arenaRejects #[0x01, 0x39, 0x00]) + itBool "arena: rejects unknown kinds" (arenaRejects #[0x01, 0x60]) + itBool "arena: rejects every truncation" (let bytes : Array UInt8 := #[0x05, 0x38, 0x01, 0x38, 0x00, 0x00, 0x0B, 0x13, 0x00] - (List.range bytes.size).all fun n => arenaRejects (bytes.extract 0 n)) ++ - test "arena: the canonical form of a rejected vector is accepted" + (List.range bytes.size).all fun n => arenaRejects (bytes.extract 0 n)) + itBool "arena: the canonical form of a rejected vector is accepted" (arenaVector { nodes := #[.leaf, .app 0 0] } #[0x02, 0x00, 0x0A, 0x00]) -def constantUnits : TestSeq := - let defn := Definition.mk .defn .safe {} 0 (.sort 0) (.var 0) - let c := Constant.mk - (.defn defn) - #[.var 0, .sort 1] -- sharing - #[⟨(Blake3.Rust.hash "ref".toUTF8).val⟩] -- refs - #[.zero, .succ .zero] -- univs - #[] -- binder data - test "Constant roundtrip" (constantSerde c) - -def commUnits : TestSeq := - let addr1 : Address := ⟨(Blake3.Rust.hash "secret".toUTF8).val⟩ - let addr2 : Address := ⟨(Blake3.Rust.hash "payload".toUTF8).val⟩ - let c := Comm.mk addr1 addr2 - test "Comm roundtrip" (commSerde c) +def constantUnits : LSpec.Spec := do + it "Constant roundtrip" do + let defn := Definition.mk .defn .safe {} 0 (.sort 0) (.var 0) + let c := Constant.mk + (.defn defn) + #[.var 0, .sort 1] -- sharing + #[⟨(Blake3.Rust.hash "ref".toUTF8).val⟩] -- refs + #[.zero, .succ .zero] -- univs + #[] -- binder data + expect (constantSerde c) + +def commUnits : LSpec.Spec := do + it "Comm roundtrip" do + let addr1 : Address := ⟨(Blake3.Rust.hash "secret".toUTF8).val⟩ + let addr2 : Address := ⟨(Blake3.Rust.hash "payload".toUTF8).val⟩ + let c := Comm.mk addr1 addr2 + expect (commSerde c) /-! ## Env Unit Tests -/ @@ -372,80 +376,84 @@ def envSerdeUnit (env : Env) : Bool := | .error _ => false | .error _ => false -def envUnitTests : TestSeq := - -- Test 1: Empty env - let emptyEnv : Env := {} - -- Test 2: Env with only a blob. Blob addresses must be the content - -- hash of the bytes — readers verify per entry. - let blobBytes := ByteArray.mk #[4, 5, 6] - let blobAddr := Address.blake3 blobBytes - let envWithBlob : Env := { blobs := ({} : Std.HashMap _ _).insert blobAddr blobBytes } - -- Test 3: Env with a simple name (no named entry) - let testName := Ix.Name.mkStr Ix.Name.mkAnon "test" - let testNameAddr := testName.getHash - let envWithName : Env := { names := ({} : Std.HashMap _ _).insert testNameAddr testName } - -- Test 4: Env with named entry and empty metadata. §5 keys the - -- entry's constant by §2 rank, so the target must be a stored - -- constant (content-addressed — readers verify per entry). - let namedDef : Definition := { - kind := .defn, safety := .safe, lvls := 0, typ := .sort 0, value := .sort 0 - } - let namedConst : Constant := { - info := .defn namedDef, sharing := #[], refs := #[], univs := #[] - } - let constAddr := Address.blake3 (serConstant namedConst) - let envWithNamed : Env := Id.run do - let mut env : Env := {} - env := env.storeConst constAddr namedConst - env := { env with names := RawEnv.addNameComponents env.names testName } - env := env.registerName testName { addr := constAddr, constMeta := .empty } - return env - -- Test 5: Env with nested name and named entry, plus an `original` - -- edge whose address is deliberately NOT a stored constant — the §5 - -- original address stays raw on the wire (it may reference an - -- assumed constant), so this must roundtrip. - let nestedName := Ix.Name.mkStr (Ix.Name.mkNat testName 42) "bar" - let envWithNestedName : Env := Id.run do - let mut env : Env := {} - env := env.storeConst constAddr namedConst - env := { env with names := RawEnv.addNameComponents env.names nestedName } - env := env.registerName nestedName - { addr := constAddr, constMeta := .empty, - original := some (Address.blake3 (ByteArray.mk #[99]), .empty) } - return env - -- Test 6: Env with blob and comm - let secretAddr := Address.blake3 (ByteArray.mk #[10, 11, 12]) - let payloadAddr := Address.blake3 (ByteArray.mk #[13, 14, 15]) - let commAddr := Address.blake3 (ByteArray.mk #[16, 17, 18]) - let envWithBlobAndComm : Env := { - blobs := ({} : Std.HashMap _ _).insert blobAddr blobBytes, - comms := ({} : Std.HashMap _ _).insert commAddr (Comm.mk secretAddr payloadAddr) - } - -- Test 7: Bundle env — main + assumptions + anonHints exercise the - -- bundle header and §3. - let bundleDef : Definition := { - kind := .defn, safety := .safe, lvls := 0, typ := .sort 0, value := .sort 0 - } - let bundleConst : Constant := { - info := .defn bundleDef, sharing := #[], refs := #[], univs := #[] - } - let bundleConstAddr := Address.blake3 (serConstant bundleConst) - let bundleEnv : Env := Id.run do - let mut env : Env := {} - env := env.storeConst bundleConstAddr bundleConst - return { env with - main := some bundleConstAddr - assumptions := ({} : Std.HashSet Address) - |>.insert (Address.blake3 (ByteArray.mk #[42])) - |>.insert (Address.blake3 (ByteArray.mk #[43])) - anonHints := ({} : Std.HashMap _ _).insert bundleConstAddr (.regular 5) } - test "Empty env roundtrip" (envSerdeUnit emptyEnv) ++ - test "Env with blob roundtrip" (envSerdeUnit envWithBlob) ++ - test "Env with name roundtrip" (envSerdeUnit envWithName) ++ - test "Env with named (empty meta) roundtrip" (envSerdeUnit envWithNamed) ++ - test "Env with nested name roundtrip" (envSerdeUnit envWithNestedName) ++ - test "Env with blob+comm roundtrip" (envSerdeUnit envWithBlobAndComm) ++ - test "Bundle env (main/assumptions/hints) roundtrip" (envSerdeUnit bundleEnv) +def envUnitTests : LSpec.Spec := do + it "Empty env roundtrip" do + let emptyEnv : Env := {} + expect (envSerdeUnit emptyEnv) + it "Env with blob roundtrip" do + let blobBytes := ByteArray.mk #[4, 5, 6] + let blobAddr := Address.blake3 blobBytes + let envWithBlob : Env := { blobs := ({} : Std.HashMap _ _).insert blobAddr blobBytes } + expect (envSerdeUnit envWithBlob) + it "Env with name roundtrip" do + let testName := Ix.Name.mkStr Ix.Name.mkAnon "test" + let testNameAddr := testName.getHash + let envWithName : Env := { names := ({} : Std.HashMap _ _).insert testNameAddr testName } + expect (envSerdeUnit envWithName) + it "Env with named (empty meta) roundtrip" do + let testName := Ix.Name.mkStr Ix.Name.mkAnon "test" + let namedDef : Definition := { + kind := .defn, safety := .safe, lvls := 0, typ := .sort 0, value := .sort 0 + } + let namedConst : Constant := { + info := .defn namedDef, sharing := #[], refs := #[], univs := #[] + } + let constAddr := Address.blake3 (serConstant namedConst) + let envWithNamed : Env := Id.run do + let mut env : Env := {} + env := env.storeConst constAddr namedConst + env := { env with names := RawEnv.addNameComponents env.names testName } + env := env.registerName testName { addr := constAddr, constMeta := .empty } + return env + expect (envSerdeUnit envWithNamed) + it "Env with nested name roundtrip" do + let testName := Ix.Name.mkStr Ix.Name.mkAnon "test" + let namedDef : Definition := { + kind := .defn, safety := .safe, lvls := 0, typ := .sort 0, value := .sort 0 + } + let namedConst : Constant := { + info := .defn namedDef, sharing := #[], refs := #[], univs := #[] + } + let constAddr := Address.blake3 (serConstant namedConst) + let nestedName := Ix.Name.mkStr (Ix.Name.mkNat testName 42) "bar" + let envWithNestedName : Env := Id.run do + let mut env : Env := {} + env := env.storeConst constAddr namedConst + env := { env with names := RawEnv.addNameComponents env.names nestedName } + env := env.registerName nestedName + { addr := constAddr, constMeta := .empty, + original := some (Address.blake3 (ByteArray.mk #[99]), .empty) } + return env + expect (envSerdeUnit envWithNestedName) + it "Env with blob+comm roundtrip" do + let blobBytes := ByteArray.mk #[4, 5, 6] + let blobAddr := Address.blake3 blobBytes + let secretAddr := Address.blake3 (ByteArray.mk #[10, 11, 12]) + let payloadAddr := Address.blake3 (ByteArray.mk #[13, 14, 15]) + let commAddr := Address.blake3 (ByteArray.mk #[16, 17, 18]) + let envWithBlobAndComm : Env := { + blobs := ({} : Std.HashMap _ _).insert blobAddr blobBytes, + comms := ({} : Std.HashMap _ _).insert commAddr (Comm.mk secretAddr payloadAddr) + } + expect (envSerdeUnit envWithBlobAndComm) + it "Bundle env (main/assumptions/hints) roundtrip" do + let bundleDef : Definition := { + kind := .defn, safety := .safe, lvls := 0, typ := .sort 0, value := .sort 0 + } + let bundleConst : Constant := { + info := .defn bundleDef, sharing := #[], refs := #[], univs := #[] + } + let bundleConstAddr := Address.blake3 (serConstant bundleConst) + let bundleEnv : Env := Id.run do + let mut env : Env := {} + env := env.storeConst bundleConstAddr bundleConst + return { env with + main := some bundleConstAddr + assumptions := ({} : Std.HashSet Address) + |>.insert (Address.blake3 (ByteArray.mk #[42])) + |>.insert (Address.blake3 (ByteArray.mk #[43])) + anonHints := ({} : Std.HashMap _ _).insert bundleConstAddr (.regular 5) } + expect (envSerdeUnit bundleEnv) /-! ## Cross-implementation serialization comparison tests -/ @@ -494,117 +502,101 @@ def envSerdeAndRustParity (raw : RawEnv) : Bool := leanRoundtrip && rustParity /-- Unit tests for Lean==Rust serialization comparison -/ -def envSerializationUnitTests : TestSeq := - -- Test 1: Empty env - let emptyRaw : RawEnv := { consts := #[], named := #[], blobs := #[], comms := #[] } - -- Test 2: Env with one blob (content-addressed: readers verify). - let blobBytes := ByteArray.mk #[4, 5, 6] - let blobAddr := Address.blake3 blobBytes - let blobRaw : RawEnv := { - consts := #[], named := #[], - blobs := #[{ addr := blobAddr, bytes := blobBytes }], - comms := #[] - } - -- Test 3: Env with one comm - let commAddr := Address.blake3 (ByteArray.mk #[7, 8, 9]) - let secretAddr := Address.blake3 (ByteArray.mk #[10, 11, 12]) - let payloadAddr := Address.blake3 (ByteArray.mk #[13, 14, 15]) - let commRaw : RawEnv := { - consts := #[], named := #[], - blobs := #[], - comms := #[{ addr := commAddr, comm := Comm.mk secretAddr payloadAddr }] - } - -- Test 4: Env with blob + comm - let blobCommRaw : RawEnv := { - consts := #[], named := #[], - blobs := #[{ addr := blobAddr, bytes := blobBytes }], - comms := #[{ addr := commAddr, comm := Comm.mk secretAddr payloadAddr }] - } - -- Test 5: Bundle env — the directed cross-language vector for the - -- bundle header (main/assumptions) and §3 anon_hints. - let bundleDef : Definition := { - kind := .defn, safety := .safe, lvls := 0, typ := .sort 0, value := .sort 0 - } - let bundleConst : Constant := { - info := .defn bundleDef, sharing := #[], refs := #[], univs := #[] - } - let bundleConstAddr := Address.blake3 (serConstant bundleConst) - let bundleRaw : RawEnv := { - consts := #[{ addr := bundleConstAddr, const := bundleConst }], - named := #[], blobs := #[], comms := #[], - main := some bundleConstAddr, - assumptions := #[ - Address.blake3 (ByteArray.mk #[42]), - Address.blake3 (ByteArray.mk #[43])], - anonHints := #[(bundleConstAddr, .regular 5)] - } - -- Test 6: Named entry + hints — the directed cross-language vector - -- for the index-keyed §5 (name §4-index + const §2 rank) and §3 - -- (delta-coded ranks + fused hints). Unlike `RawEnv.toEnv`, the Rust - -- FFI side does not auto-add name components for named entries, so - -- `names` carries the leaf explicitly (ancestors are emitted by both - -- topological sorts from the parent chain). - let namedName := Ix.Name.mkStr Ix.Name.mkAnon "MyDef" - let namedRaw : RawEnv := { - consts := #[{ addr := bundleConstAddr, const := bundleConst }], - named := #[{ name := namedName, addr := bundleConstAddr, - constMeta := .empty, hints := some (.regular 7) }], - blobs := #[], comms := #[], - names := #[{ addr := namedName.getHash, name := namedName }], - anonHints := #[(bundleConstAddr, .abbrev)] - } - -- Test 7: Metadata-bearing named entries — the directed cross-language - -- byte vector for the FULL metadata wire grammar: an arena over the - -- kinds 0-9 (indexed names, binder info, an app, a ref, mdata), the - -- extension tables (sharing exprs, raw refs, univs, univ patches), and - -- a muts entry with the nested-aux `auxLayout` sidecar. Every indexed - -- name address is a registered name component. (Before call-site metadata was retired, the arena - -- also carried a call-site surgery node, kinds 10/11, now retired.) - let surgName := Ix.Name.mkStr Ix.Name.mkAnon "surg" - let blkName := Ix.Name.mkStr Ix.Name.mkAnon "blk" - let anonAddr := Ix.Name.mkAnon.getHash - let surgArena : ExprMetaArena := { nodes := #[ - .leaf, - .binder anonAddr .implicit 0 0, - .ref surgName.getHash, - .app 2 1, - .mdata #[#[(blkName.getHash, .ofName surgName.getHash)]] 3 - ] } - let surgMeta : ConstantMeta := { - info := .defn surgName.getHash #[anonAddr] #[surgName.getHash] #[] - surgArena 0 4, - metaSharing := #[.app (.share 1) (.var 2), .sort 0], - metaRefs := #[bundleConstAddr], - metaUnivs := #[.succ (.var 0), .max .zero (.var 1)], - univPatches := #[⟨1, #[0, 2]⟩, ⟨4, #[3]⟩] - } - let mutsMeta : ConstantMeta := .new - (.muts #[#[surgName.getHash], #[blkName.getHash]] - (some { perm := #[1, 0], sourceCtorCounts := #[2, 3], - evaporated := #[0, 0] })) - let metaRaw : RawEnv := { - consts := #[{ addr := bundleConstAddr, const := bundleConst }], - named := #[ - { name := surgName, addr := bundleConstAddr, constMeta := surgMeta, - hints := some (.regular 3) }, - { name := blkName, addr := bundleConstAddr, constMeta := mutsMeta }], - blobs := #[], comms := #[], - names := #[ - { addr := surgName.getHash, name := surgName }, - { addr := blkName.getHash, name := blkName }] - } - test "Empty env Lean==Rust" (envSerializationMatches emptyRaw) ++ - test "Blob env Lean==Rust" (envSerializationMatches blobRaw) ++ - test "Comm env Lean==Rust" (envSerializationMatches commRaw) ++ - test "Blob+Comm env Lean==Rust" (envSerializationMatches blobCommRaw) ++ - test "Bundle env Lean==Rust" (envSerializationMatches bundleRaw) ++ - test "Named env Lean==Rust" (envSerializationMatches namedRaw) ++ - test "Empty env bytes Lean==Rust" (envBytesMatchRust emptyRaw) ++ - test "Blob env bytes Lean==Rust" (envBytesMatchRust blobRaw) ++ - test "Bundle env bytes Lean==Rust" (envBytesMatchRust bundleRaw) ++ - test "Named env bytes Lean==Rust" (envBytesMatchRust namedRaw) ++ - test "Metadata env bytes Lean==Rust" (envBytesMatchRust metaRaw) ++ - test "Metadata env pure serde" (envSerde metaRaw) +def envSerializationUnitTests : LSpec.Spec := do + let mkEmptyRaw (_ : Unit) : RawEnv := + { consts := #[], named := #[], blobs := #[], comms := #[] } + let mkBlobRaw (_ : Unit) : RawEnv := + let blobBytes := ByteArray.mk #[4, 5, 6] + let blobAddr := Address.blake3 blobBytes + { consts := #[], named := #[], + blobs := #[{ addr := blobAddr, bytes := blobBytes }], + comms := #[] } + let mkCommRaw (_ : Unit) : RawEnv := + let commAddr := Address.blake3 (ByteArray.mk #[7, 8, 9]) + let secretAddr := Address.blake3 (ByteArray.mk #[10, 11, 12]) + let payloadAddr := Address.blake3 (ByteArray.mk #[13, 14, 15]) + { consts := #[], named := #[], blobs := #[], + comms := #[{ addr := commAddr, comm := Comm.mk secretAddr payloadAddr }] } + let mkBlobCommRaw (_ : Unit) : RawEnv := + let blobBytes := ByteArray.mk #[4, 5, 6] + let blobAddr := Address.blake3 blobBytes + let commAddr := Address.blake3 (ByteArray.mk #[7, 8, 9]) + let secretAddr := Address.blake3 (ByteArray.mk #[10, 11, 12]) + let payloadAddr := Address.blake3 (ByteArray.mk #[13, 14, 15]) + { consts := #[], named := #[], + blobs := #[{ addr := blobAddr, bytes := blobBytes }], + comms := #[{ addr := commAddr, comm := Comm.mk secretAddr payloadAddr }] } + let mkBundleConst (_ : Unit) : Address × Constant := + let bundleDef : Definition := { + kind := .defn, safety := .safe, lvls := 0, typ := .sort 0, value := .sort 0 + } + let bundleConst : Constant := { + info := .defn bundleDef, sharing := #[], refs := #[], univs := #[] + } + (Address.blake3 (serConstant bundleConst), bundleConst) + let mkBundleRaw (_ : Unit) : RawEnv := + let (bundleConstAddr, bundleConst) := mkBundleConst () + { consts := #[{ addr := bundleConstAddr, const := bundleConst }], + named := #[], blobs := #[], comms := #[], + main := some bundleConstAddr, + assumptions := #[ + Address.blake3 (ByteArray.mk #[42]), + Address.blake3 (ByteArray.mk #[43])], + anonHints := #[(bundleConstAddr, .regular 5)] } + let mkNamedRaw (_ : Unit) : RawEnv := + let (bundleConstAddr, bundleConst) := mkBundleConst () + let namedName := Ix.Name.mkStr Ix.Name.mkAnon "MyDef" + { consts := #[{ addr := bundleConstAddr, const := bundleConst }], + named := #[{ name := namedName, addr := bundleConstAddr, + constMeta := .empty, hints := some (.regular 7) }], + blobs := #[], comms := #[], + names := #[{ addr := namedName.getHash, name := namedName }], + anonHints := #[(bundleConstAddr, .abbrev)] } + let mkMetaRaw (_ : Unit) : RawEnv := + let (bundleConstAddr, bundleConst) := mkBundleConst () + let surgName := Ix.Name.mkStr Ix.Name.mkAnon "surg" + let blkName := Ix.Name.mkStr Ix.Name.mkAnon "blk" + let anonAddr := Ix.Name.mkAnon.getHash + let surgArena : ExprMetaArena := { nodes := #[ + .leaf, + .binder anonAddr .implicit 0 0, + .ref surgName.getHash, + .app 2 1, + .mdata #[#[(blkName.getHash, .ofName surgName.getHash)]] 3 + ] } + let surgMeta : ConstantMeta := { + info := .defn surgName.getHash #[anonAddr] #[surgName.getHash] #[] + surgArena 0 4, + metaSharing := #[.app (.share 1) (.var 2), .sort 0], + metaRefs := #[bundleConstAddr], + metaUnivs := #[.succ (.var 0), .max .zero (.var 1)], + univPatches := #[⟨1, #[0, 2]⟩, ⟨4, #[3]⟩] + } + let mutsMeta : ConstantMeta := .new + (.muts #[#[surgName.getHash], #[blkName.getHash]] + (some { perm := #[1, 0], sourceCtorCounts := #[2, 3], + evaporated := #[0, 0] })) + { consts := #[{ addr := bundleConstAddr, const := bundleConst }], + named := #[ + { name := surgName, addr := bundleConstAddr, constMeta := surgMeta, + hints := some (.regular 3) }, + { name := blkName, addr := bundleConstAddr, constMeta := mutsMeta }], + blobs := #[], comms := #[], + names := #[ + { addr := surgName.getHash, name := surgName }, + { addr := blkName.getHash, name := blkName }] } + itBool "Empty env Lean==Rust" (envSerializationMatches (mkEmptyRaw ())) + itBool "Blob env Lean==Rust" (envSerializationMatches (mkBlobRaw ())) + itBool "Comm env Lean==Rust" (envSerializationMatches (mkCommRaw ())) + itBool "Blob+Comm env Lean==Rust" (envSerializationMatches (mkBlobCommRaw ())) + itBool "Bundle env Lean==Rust" (envSerializationMatches (mkBundleRaw ())) + itBool "Named env Lean==Rust" (envSerializationMatches (mkNamedRaw ())) + itBool "Empty env bytes Lean==Rust" (envBytesMatchRust (mkEmptyRaw ())) + itBool "Blob env bytes Lean==Rust" (envBytesMatchRust (mkBlobRaw ())) + itBool "Bundle env bytes Lean==Rust" (envBytesMatchRust (mkBundleRaw ())) + itBool "Named env bytes Lean==Rust" (envBytesMatchRust (mkNamedRaw ())) + itBool "Metadata env bytes Lean==Rust" (envBytesMatchRust (mkMetaRaw ())) + itBool "Metadata env pure serde" (envSerde (mkMetaRaw ())) /-! ## Canonical env merkle root: Lean vs. Rust agreement -/ @@ -614,36 +606,35 @@ def envMerkleRootMatches (raw : RawEnv) : Bool := /-- Both pure-Lean and Rust FFI agree on the merkle root over the env's consts addresses. Distinct tests for various const-set shapes. -/ -def envMerkleRootUnitTests : TestSeq := - -- Empty env: no root. - let emptyRaw : RawEnv := - { consts := #[], named := #[], blobs := #[], comms := #[] } - -- Single-const env. - let constAddr := Address.blake3 (ByteArray.mk #[42]) +def envMerkleRootUnitTests : LSpec.Spec := do let oneConst : Constant := { info := .axio { isUnsafe := false, lvls := 0, typ := .sort 0 }, sharing := #[], refs := #[], univs := #[] } - let singleRaw : RawEnv := + let mkEmpty (_ : Unit) : RawEnv := + { consts := #[], named := #[], blobs := #[], comms := #[] } + let mkSingle (_ : Unit) : RawEnv := + let constAddr := Address.blake3 (ByteArray.mk #[42]) { consts := #[{ addr := constAddr, const := oneConst }], named := #[], blobs := #[], comms := #[] } - -- Two-const env, inserted in different orders to check sort invariance. - let addrA := Address.blake3 "a".toUTF8 - let addrB := Address.blake3 "b".toUTF8 - let raw_ab : RawEnv := + let mkAB (_ : Unit) : RawEnv := + let addrA := Address.blake3 "a".toUTF8 + let addrB := Address.blake3 "b".toUTF8 { consts := #[{ addr := addrA, const := oneConst }, { addr := addrB, const := oneConst }], named := #[], blobs := #[], comms := #[] } - let raw_ba : RawEnv := + let mkBA (_ : Unit) : RawEnv := + let addrA := Address.blake3 "a".toUTF8 + let addrB := Address.blake3 "b".toUTF8 { consts := #[{ addr := addrB, const := oneConst }, { addr := addrA, const := oneConst }], named := #[], blobs := #[], comms := #[] } - test "empty env merkle root is none" (emptyRaw.merkleRoot == none) ++ - test "empty env: Lean==Rust" (envMerkleRootMatches emptyRaw) ++ - test "single const: Lean==Rust" (envMerkleRootMatches singleRaw) ++ - test "two consts (a,b): Lean==Rust" (envMerkleRootMatches raw_ab) ++ - test "two consts (b,a): Lean==Rust" (envMerkleRootMatches raw_ba) ++ - test "(a,b) and (b,a) same root" - (raw_ab.merkleRoot == raw_ba.merkleRoot) + itBool "empty env merkle root is none" ((mkEmpty ()).merkleRoot == none) + itBool "empty env: Lean==Rust" (envMerkleRootMatches (mkEmpty ())) + itBool "single const: Lean==Rust" (envMerkleRootMatches (mkSingle ())) + itBool "two consts (a,b): Lean==Rust" (envMerkleRootMatches (mkAB ())) + itBool "two consts (b,a): Lean==Rust" (envMerkleRootMatches (mkBA ())) + itBool "(a,b) and (b,a) same root" + ((mkAB ()).merkleRoot == (mkBA ()).merkleRoot) /-! ## Checked format 4 and versioned storage envelopes -/ @@ -660,18 +651,19 @@ private def versionRejected {α : Type} (r : Except String α) (got : Nat) : Boo | .error e => (e.splitOn s!"unsupported .ixe envelope version {got}").length > 1 -def envHeaderUnits : TestSeq := - let bytes := match serEnv ({} : Env) with | .ok b => b | .error _ => .empty - test "env header is TagN(4, 0xE, 4) = 0xE4" (bytes.data[0]? == some 0xE4) - ++ test "wireFormatId is ixon-v5" (wireFormatId == "ixon-v5") - ++ test "checked object-format byte remains 4" (Env.OBJECT_FORMAT == 4) - ++ test "Lean reader accepts the version 4 header" ((deEnv bytes).toOption.isSome) - ++ test "Lean reader rejects a version 3 header" - (versionRejected (deEnv (emptyEnvWithHeader 0xE3)) 3) - ++ test "Lean streaming reader rejects a version 3 header" - (versionRejected (deEnvVerifiedLazy (emptyEnvWithHeader 0xE3)) 3) - ++ test "Rust reader rejects a version 3 header" - (versionRejected (deEnvAnon (emptyEnvWithHeader 0xE3)) 3) +def envHeaderUnits : LSpec.Spec := do + let mkEmptyBytes (_ : Unit) : ByteArray := + match serEnv ({} : Env) with | .ok b => b | .error _ => .empty + itBool "env header is TagN(4, 0xE, 4) = 0xE4" ((mkEmptyBytes ()).data[0]? == some 0xE4) + itBool "wireFormatId is ixon-v5" (wireFormatId == "ixon-v5") + itBool "checked object-format byte remains 4" (Env.OBJECT_FORMAT == 4) + itBool "Lean reader accepts the version 4 header" ((deEnv (mkEmptyBytes ())).toOption.isSome) + itBool "Lean reader rejects a version 3 header" + (versionRejected (deEnv (emptyEnvWithHeader 0xE3)) 3) + itBool "Lean streaming reader rejects a version 3 header" + (versionRejected (deEnvVerifiedLazy (emptyEnvWithHeader 0xE3)) 3) + itBool "Rust reader rejects a version 3 header" + (versionRejected (deEnvAnon (emptyEnvWithHeader 0xE3)) 3) /-! ## Envelope versions @@ -726,12 +718,10 @@ private def envelopeChecks (definition : Definition) : Except String Unit := do /-- Keep the fixture as a parameter so the compiler cannot initialize the entire closed FFI computation before the selected test runs. -/ -private def envelopeUnits (definition : Definition) : TestSeq := - .individualIO "envelope: v4 bytes, both writers and readers, malformed controls" none (do - let result ← IO.lazyPure fun _ => envelopeChecks definition - return match result with - | .ok _ => (true, 0, 0, none) - | .error e => (false, 0, 0, some e)) .done +private def envelopeUnits (definition : Definition) : Spec := + it "envelope: v4 bytes, both writers and readers, malformed controls" do + let result ← liftM (m := IO) (IO.lazyPure fun _ => envelopeChecks definition) + discard <| expectOk result /-! ## The binder-data section @@ -766,7 +756,7 @@ def canonicalRead (c : Constant) : Bool := (Canonical.deConstant bytes.size loadMaxUnivNodes bytes).toOption == some c /-- Each form still round-trips; the canonical (local) form rejects it. -/ -def noncanonicalSections : List (String × Array BinderBlock) := +def noncanonicalSections (_ : Unit) : List (String × Array BinderBlock) := let b := binderFixture.binders [("blocks out of order", #[b[1]!, b[0]!, b[2]!, b[3]!]), ("a repeated key", b.push b[3]!), @@ -779,7 +769,7 @@ def noncanonicalSections : List (String × Array BinderBlock) := /-- Each form is canonical (local) and round-trips; only the complete form rejects it. -/ -def incompleteSections : List (String × Array BinderBlock) := +def incompleteSections (_ : Unit) : List (String × Array BinderBlock) := let b := binderFixture.binders [("a variant no share node names", b.push ⟨true, 0, 2, #[.never {}]⟩), ("a missing root block", #[b[0]!, b[2]!, b[3]!]), @@ -799,92 +789,96 @@ def projectionWithSection (node : BinderNode) : Constant := { info := .dPrj ⟨0, Address.blake3 "block".toUTF8⟩, sharing := #[], refs := #[], univs := #[], binders := #[⟨false, 0, 0, #[node]⟩] } -def binderSectionUnits : TestSeq := - let bytes := serConstant binderFixture - let badTag := bytes.set! (bytes.size - binderFixtureSection.size + 5) 5 - let badKind := bytes.set! (bytes.size - binderFixtureSection.size + 1) 2 - test "section bytes" ((runPut (putBinders binderFixture.binders)).data == binderFixtureSection) - ++ test "the empty section is 0x00" ((runPut (putBinders #[])).data == #[0]) - ++ test "a record ends with its section" - ((bytes.extract (bytes.size - binderFixtureSection.size) bytes.size).data - == binderFixtureSection) - ++ test "record with a section round-trips" (constantSerde binderFixture) - ++ test "record without a section round-trips" (constantSerde { binderFixture with binders := #[] }) - ++ test "the fixture's section is canonical" binderFixture.bindersCanonical - ++ test "the fixture's section is complete" binderFixture.bindersComplete - ++ test "the canonical decoder accepts it" (canonicalRead binderFixture) - ++ test "a record without binders and no section is canonical and complete" - (let c := { binderFixture with - info := .defn (Definition.mk .defn .safe {} 0 (.sort 0) (.sort 0)), sharing := #[], binders := #[] } - canonicalRead c && c.bindersComplete) - ++ noncanonicalSections.foldl (init := .done) (fun acc (label, blocks) => - let c := { binderFixture with binders := blocks } - acc ++ test s!"{label}: round-trips" (constantSerde c) - ++ test s!"{label}: not canonical" (!c.bindersCanonical && !canonicalRead c)) - ++ incompleteSections.foldl (init := .done) (fun acc (label, blocks) => - let c := { binderFixture with binders := blocks } - acc ++ test s!"{label}: round-trips" (constantSerde c) - ++ test s!"{label}: canonical but not complete" - (c.bindersCanonical && canonicalRead c && !c.bindersComplete)) - ++ test "a projection with a parameter is not canonical" - (!canonicalRead (projectionWithSection (.ifAllZero #[0] {}))) - ++ test "a projection with any section is not canonical" - (!canonicalRead (projectionWithSection (.never {}))) - ++ test "a level count below 2^32 is canonical; 2^32 round-trips and is not" - (let withLvls (n : Nat) : Constant := - { info := .defn (Definition.mk .defn .safe {} n.toUInt64 (.sort 0) (.sort 0)), - sharing := #[], refs := #[], univs := #[.zero], binders := #[] } - canonicalRead (withLvls (maxLevelCount - 1)) && constantSerde (withLvls maxLevelCount) && - !(withLvls maxLevelCount).bindersCanonical && !canonicalRead (withLvls maxLevelCount)) - ++ test "an unknown node tag is rejected" ((deConstant badTag).toOption.isNone) - ++ test "a block kind other than 0 or 1 is rejected" ((deConstant badKind).toOption.isNone) - ++ test "a truncated section is rejected" - ((deConstantExact (bytes.extract 0 (bytes.size - 1))).toOption.isNone) - ++ test "section serialization Lean==Rust" (constantSerializationMatches binderFixture) +def binderSectionUnits : LSpec.Spec := do + itBool "section bytes" ((runPut (putBinders binderFixture.binders)).data == binderFixtureSection) + itBool "the empty section is 0x00" ((runPut (putBinders #[])).data == #[0]) + it "a record ends with its section" do + let bytes := serConstant binderFixture + expect ((bytes.extract (bytes.size - binderFixtureSection.size) bytes.size).data + == binderFixtureSection) + itBool "record with a section round-trips" (constantSerde binderFixture) + itBool "record without a section round-trips" (constantSerde { binderFixture with binders := #[] }) + itBool "the fixture's section is canonical" binderFixture.bindersCanonical + itBool "the fixture's section is complete" binderFixture.bindersComplete + itBool "the canonical decoder accepts it" (canonicalRead binderFixture) + itBool "a record without binders and no section is canonical and complete" + (let c := { binderFixture with + info := .defn (Definition.mk .defn .safe {} 0 (.sort 0) (.sort 0)), sharing := #[], binders := #[] } + canonicalRead c && c.bindersComplete) + for (label, blocks) in noncanonicalSections () do + let c := { binderFixture with binders := blocks } + itBool s!"{label}: round-trips" (constantSerde c) + itBool s!"{label}: not canonical" (!c.bindersCanonical && !canonicalRead c) + for (label, blocks) in incompleteSections () do + let c := { binderFixture with binders := blocks } + itBool s!"{label}: round-trips" (constantSerde c) + itBool s!"{label}: canonical but not complete" + (c.bindersCanonical && canonicalRead c && !c.bindersComplete) + itBool "a projection with a parameter is not canonical" + (!canonicalRead (projectionWithSection (.ifAllZero #[0] {}))) + itBool "a projection with any section is not canonical" + (!canonicalRead (projectionWithSection (.never {}))) + itBool "a level count below 2^32 is canonical; 2^32 round-trips and is not" + (let withLvls (n : Nat) : Constant := + { info := .defn (Definition.mk .defn .safe {} n.toUInt64 (.sort 0) (.sort 0)), + sharing := #[], refs := #[], univs := #[.zero], binders := #[] } + canonicalRead (withLvls (maxLevelCount - 1)) && constantSerde (withLvls maxLevelCount) && + !(withLvls maxLevelCount).bindersCanonical && !canonicalRead (withLvls maxLevelCount)) + it "an unknown node tag is rejected" do + let bytes := serConstant binderFixture + let badTag := bytes.set! (bytes.size - binderFixtureSection.size + 5) 5 + expect (deConstant badTag).toOption.isNone + it "a block kind other than 0 or 1 is rejected" do + let bytes := serConstant binderFixture + let badKind := bytes.set! (bytes.size - binderFixtureSection.size + 1) 2 + expect (deConstant badKind).toOption.isNone + it "a truncated section is rejected" do + let bytes := serConstant binderFixture + expect (deConstantExact (bytes.extract 0 (bytes.size - 1))).toOption.isNone + itBool "section serialization Lean==Rust" (constantSerializationMatches binderFixture) /-! ## Test Suite (property-based) -/ -public def Tests.Ixon.suite : List TestSeq := [ - envHeaderUnits, - Tests.Ix.RoleGeneration.units .natDiv, - Tests.Ix.RoleGeneration.artifactUnits .natDiv, - Tests.Ix.RoleArtifactConsumer.units, - Tests.Ix.RolePacking.units, - Tests.Ix.HostAdmission.units, - Tests.Ix.CircuitMeta.units, +public def Tests.Ixon.suite : LSpec.Spec := do + envHeaderUnits + Tests.Ix.RoleGeneration.units .natDiv + Tests.Ix.RoleGeneration.artifactUnits .natDiv + Tests.Ix.RoleArtifactConsumer.units + Tests.Ix.RolePacking.units + Tests.Ix.HostAdmission.units + Tests.Ix.CircuitMeta.units Tests.Ix.RoleBinding.units { sharing := #[], refs := #[], univs := #[.zero], info := .defn { - kind := .defn, safety := .safe, lvls := 0, typ := .sort 0, value := .sort 0 } }, + kind := .defn, safety := .safe, lvls := 0, typ := .sort 0, value := .sort 0 } } Tests.Ix.RolePublication.units { sharing := #[], refs := #[], univs := #[.zero], info := .defn { - kind := .defn, safety := .safe, lvls := 0, typ := .sort 0, value := .sort 0 } }, + kind := .defn, safety := .safe, lvls := 0, typ := .sort 0, value := .sort 0 } } envelopeUnits { - kind := .defn, safety := .safe, lvls := 0, typ := .sort 0, value := .sort 0 }, - univExactUnits, - univUnits, - exprExactUnits, - exprUnits, - strictExprUnits, - tagNUnits, - exprMetaArenaUnits, - binderSectionUnits, + kind := .defn, safety := .safe, lvls := 0, typ := .sort 0, value := .sort 0 } + univExactUnits + univUnits + exprExactUnits + exprUnits + strictExprUnits + tagNUnits + exprMetaArenaUnits + binderSectionUnits -- Env unit tests (for debugging serialization) - envUnitTests, + envUnitTests -- Env serialization comparison unit tests - envSerializationUnitTests, + envSerializationUnitTests -- Env merkle root agreement (Lean vs. Rust FFI) - envMerkleRootUnitTests, + envMerkleRootUnitTests -- Pure Lean serde roundtrips - checkIO "Univ serde roundtrips" (∀ u : Univ, univSerde u), - checkIO "Expr serde roundtrips" (∀ e : Expr, exprSerde e), - checkIO "Constant serde roundtrips" (∀ c : Constant, constantSerde c), - checkIO "Comm serde roundtrips" (∀ c : Comm, commSerde c), + prop "Univ serde roundtrips" fun (u : Univ) => univSerde u + prop "Expr serde roundtrips" fun (e : Expr) => exprSerde e + prop "Constant serde roundtrips" fun (c : Constant) => constantSerde c + prop "Comm serde roundtrips" fun (c : Comm) => commSerde c -- Cross-implementation serialization comparison (Lean == Rust) - checkIO "Univ serialization Lean==Rust" (∀ u : Univ, univSerializationMatches u), - checkIO "Expr serialization Lean==Rust" (∀ e : Expr, exprSerializationMatches e), - checkIO "Constant serialization Lean==Rust" (∀ c : Constant, constantSerializationMatches c), + prop "Univ serialization Lean==Rust" fun (u : Univ) => univSerializationMatches u + prop "Expr serialization Lean==Rust" fun (e : Expr) => exprSerializationMatches e + prop "Constant serialization Lean==Rust" fun (c : Constant) => constantSerializationMatches c -- Combined Env serde roundtrip + Lean==Rust decode and strict byte equality -- (generated named entries carry full metadata: arena nodes, extension -- tables, auxLayout — keeping the metadata wire format in sync). - checkIO "Env serde roundtrips and Lean==Rust bytes" (∀ raw : RawEnv, envSerdeAndRustParity raw), -] + prop "Env serde roundtrips and Lean==Rust bytes" fun (raw : RawEnv) => envSerdeAndRustParity raw diff --git a/Tests/Ix/IxonRejectParity.lean b/Tests/Ix/IxonRejectParity.lean index 910cc1954a..e41534a6e9 100644 --- a/Tests/Ix/IxonRejectParity.lean +++ b/Tests/Ix/IxonRejectParity.lean @@ -84,74 +84,88 @@ def parseCases (text : String) : Except String (Array Case) := do def maxRecordBytes : Nat := 1 <<< 28 def maxRecordUnivNodes : Nat := 1 <<< 26 -/-- The readers of a kind, each with whether it accepts `bytes`. -/ -def readers (kind : String) (bytes : ByteArray) : Option (List (String × Bool)) := - let canonical := ("Canonical.deConstant", +/-- The readers of a kind, each as `(name, acceptsFn)`. -/ +def readerFns (kind : String) : Option (List (String × (ByteArray → Bool))) := + let canonical := ("Canonical.deConstant", fun bytes => (Ixon.Canonical.deConstant maxRecordBytes maxRecordUnivNodes bytes).isOk) match kind with | "record" => some [canonical, - ("deConstantLoaded", (Ixon.Env.deConstantLoaded bytes).isOk), - ("deConstantAt", (Ixon.deConstantAt bytes 0 bytes.size).isOk), - ("refsAt", (Ix.Cert.RecordRefs.refsAt bytes 0 bytes.size).isSome)] + ("deConstantLoaded", fun bytes => (Ixon.Env.deConstantLoaded bytes).isOk), + ("deConstantAt", fun bytes => (Ixon.deConstantAt bytes 0 bytes.size).isOk), + ("refsAt", fun bytes => (Ix.Cert.RecordRefs.refsAt bytes 0 bytes.size).isSome)] | "noncanonical" | "canonical-rule" => some [canonical] - | "env" => some [("deEnv", (Ixon.deEnv bytes).isOk), - ("deEnvVerifiedLazy", (Ixon.deEnvVerifiedLazy bytes).isOk)] - | "ixes" => some [("parseIxesManifest", (Ix.Shard.parseIxesManifest bytes).isOk)] - | "tree" => some [("AssumptionTree.de", (Ix.AssumptionTree.de bytes).isOk)] - | "claim" => some [("Claim.de", (Ix.Claim.de bytes).isOk)] + | "env" => some [("deEnv", fun bytes => (Ixon.deEnv bytes).isOk), + ("deEnvVerifiedLazy", fun bytes => (Ixon.deEnvVerifiedLazy bytes).isOk)] + | "ixes" => some [("parseIxesManifest", fun bytes => (Ix.Shard.parseIxesManifest bytes).isOk)] + | "tree" => some [("AssumptionTree.de", fun bytes => (Ix.AssumptionTree.de bytes).isOk)] + | "claim" => some [("Claim.de", fun bytes => (Ix.Claim.de bytes).isOk)] | _ => none +/-- The readers of a kind, each with whether it accepts `bytes`. -/ +def readers (kind : String) (bytes : ByteArray) : Option (List (String × Bool)) := + (readerFns kind).map fun rs => rs.map fun (name, f) => (name, f bytes) + /-- The same small table at its exact aggregate budget and one node below. The offset control also exercises a record embedded between unrelated bytes. -/ -def budgetTests : TestSeq := Id.run do - let c : Ixon.Constant := { - info := .axio { isUnsafe := false, lvls := 0, typ := .sort 0 } - sharing := #[], refs := #[], univs := #[.succ .zero, .zero] } - let bytes := Ixon.serConstant c - let window := ByteArray.mk #[255] ++ bytes ++ ByteArray.mk #[255] - let noUnivs := { c with univs := #[] } - let noUnivBytes := Ixon.serConstant noUnivs - let block : Ix.CompileM.BlockResult := { - block := c, blockBytes := bytes, blockAddr := default } - let projected : Ix.CompileM.BlockResult := - { block with block := noUnivs, projections := #[(Ix.Name.anonymous default, c, .empty)] } - return test "lazy window accepts the exact aggregate universe budget" - ((Ixon.deConstantAt window 1 bytes.size 3).toOption == some c) ++ - test "lazy window refuses a universe table one node over budget" - (!(Ixon.deConstantAt window 1 bytes.size 2).isOk) ++ - test "refs-only reader accepts the exact aggregate universe budget" - (Ix.Cert.RecordRefs.refsAt window 1 bytes.size 3 == some (#[], none)) ++ - test "refs-only reader shares the budget across universe entries" - ((Ix.Cert.RecordRefs.refsAt window 1 bytes.size 2).isNone) ++ - test "empty universe tables accept a zero budget" - ((Ixon.deConstantAt noUnivBytes 0 noUnivBytes.size 0).toOption == some noUnivs) ++ - test "compiler accepts a block at the loader budget" - (Ix.CompileM.blockUnivsFit block 3) ++ - test "compiler refuses a block above the loader budget" - (!Ix.CompileM.blockUnivsFit block 2) ++ - test "compiler checks projection records against the loader budget" - (!Ix.CompileM.blockUnivsFit projected 2) +def budgetTests : LSpec.Spec := do + let mkFixture := fun () => + let c : Ixon.Constant := { + info := .axio { isUnsafe := false, lvls := 0, typ := .sort 0 } + sharing := #[], refs := #[], univs := #[.succ .zero, .zero] } + let bytes := Ixon.serConstant c + let window := ByteArray.mk #[255] ++ bytes ++ ByteArray.mk #[255] + let noUnivs := { c with univs := #[] } + let noUnivBytes := Ixon.serConstant noUnivs + let block : Ix.CompileM.BlockResult := { + block := c, blockBytes := bytes, blockAddr := default } + let projected : Ix.CompileM.BlockResult := + { block with block := noUnivs, projections := #[(Ix.Name.anonymous default, c, .empty)] } + (c, bytes, window, noUnivs, noUnivBytes, block, projected) + it "lazy window accepts the exact aggregate universe budget" do + let (c, bytes, window, _, _, _, _) := mkFixture () + expect ((Ixon.deConstantAt window 1 bytes.size 3).toOption == some c) + it "lazy window refuses a universe table one node over budget" do + let (_, bytes, window, _, _, _, _) := mkFixture () + expect (!(Ixon.deConstantAt window 1 bytes.size 2).isOk) + it "refs-only reader accepts the exact aggregate universe budget" do + let (_, bytes, window, _, _, _, _) := mkFixture () + expect (Ix.Cert.RecordRefs.refsAt window 1 bytes.size 3 == some (#[], none)) + it "refs-only reader shares the budget across universe entries" do + let (_, bytes, window, _, _, _, _) := mkFixture () + expect (Ix.Cert.RecordRefs.refsAt window 1 bytes.size 2).isNone + it "empty universe tables accept a zero budget" do + let (_, _, _, noUnivs, noUnivBytes, _, _) := mkFixture () + expect ((Ixon.deConstantAt noUnivBytes 0 noUnivBytes.size 0).toOption == some noUnivs) + it "compiler accepts a block at the loader budget" do + let (_, _, _, _, _, block, _) := mkFixture () + expect (Ix.CompileM.blockUnivsFit block 3) + it "compiler refuses a block above the loader budget" do + let (_, _, _, _, _, block, _) := mkFixture () + expect (!Ix.CompileM.blockUnivsFit block 2) + it "compiler checks projection records against the loader budget" do + let (_, _, _, _, _, _, projected) := mkFixture () + expect (!Ix.CompileM.blockUnivsFit projected 2) /-- Every case of the fixture, every reader of its kind: a control accepted, any other case refused. -/ -def suite : IO (List TestSeq) := do +def suite : IO Spec := do let cases ← IO.ofExcept (parseCases (← IO.FS.readFile fixturePath)) - let mut tests : TestSeq := budgetTests - for case in cases do - let (kind, accepted) := match case.kind.dropSuffix? "-accept" with - | some kind => (kind.toString, true) - | none => (case.kind, false) - match readers kind case.bytes with - | none => tests := tests ++ test s!"{case.kind} {case.name}: known kind" false - | some results => - for (reader, result) in results do - let verb := if accepted then "accepts" else "refuses" - tests := tests ++ test s!"{reader} {verb} {case.kind} {case.name}" (result == accepted) - -- a record rule beyond the codec: the codec reads the bytes either way - if kind == "canonical-rule" then - tests := tests ++ test s!"the codec reads {case.kind} {case.name}" - (Ixon.runGetExact Ixon.getConstant case.bytes).isOk - return [tests] + return do + budgetTests + for case in cases do + let (kind, accepted) := match case.kind.dropSuffix? "-accept" with + | some kind => (kind.toString, true) + | none => (case.kind, false) + match readerFns kind with + | none => itBool s!"{case.kind} {case.name}: known kind" false + | some fns => + for (reader, check) in fns do + let verb := if accepted then "accepts" else "refuses" + itBool s!"{reader} {verb} {case.kind} {case.name}" (check case.bytes == accepted) + -- a record rule beyond the codec: the codec reads the bytes either way + if kind == "canonical-rule" then + itBool s!"the codec reads {case.kind} {case.name}" + (Ixon.runGetExact Ixon.getConstant case.bytes).isOk end Tests.Ix.IxonRejectParity diff --git a/Tests/Ix/IxonRustParity.lean b/Tests/Ix/IxonRustParity.lean index 746cf3f6ff..b41973a75b 100644 --- a/Tests/Ix/IxonRustParity.lean +++ b/Tests/Ix/IxonRustParity.lean @@ -68,165 +68,173 @@ private def reqNat (j : Json) (k : String) : Except String Nat := private def reqArr (j : Json) (k : String) : Except String (Array Json) := do (← j.getObjVal? k).getArr? -def suite : IO (List TestSeq) := do +def suite : IO Spec := do let raw ← IO.FS.readFile fixturePath let root ← IO.ofExcept (Json.parse raw) - let mut tests : TestSeq := .done - - -- 1. Claims (20 positive vectors) let claims ← IO.ofExcept (reqArr root "claims") - tests := tests ++ test "claims count ≥ 15" (claims.size ≥ 15) - for c in claims do + let proofs ← IO.ofExcept (reqArr root "proofs") + let trees ← IO.ofExcept (reqArr root "assumption_trees") + let comms ← IO.ofExcept (reqArr root "comms") + let univs ← IO.ofExcept (reqArr root "univs") + let exprs ← IO.ofExcept (reqArr root "exprs") + let consts ← IO.ofExcept (reqArr root "constants") + let b3s ← IO.ofExcept (reqArr root "blake3") + let negs ← IO.ofExcept (reqArr root "negative_claims") + + let parseClaimVec (c : Json) : IO (String × ByteArray × String × Nat) := do let name ← IO.ofExcept (reqStr c "name") let hex ← IO.ofExcept (reqStr c "hex") let blake ← IO.ofExcept (reqStr c "blake3") let byteLen ← IO.ofExcept (reqNat c "byte_len") let bytes ← IO.ofExcept (parseHex hex) - let lenOk := bytes.size == byteLen - let hashOk := addrHex (Address.blake3 bytes) == blake && addrHex (Address.blake3Pure bytes) == blake - let rtOk := match Ix.Claim.de bytes with - | .ok val => Ix.Claim.ser val == bytes - | .error _ => false - tests := tests ++ test s!"claim/{name}: len+blake3+roundtrip" (lenOk && hashOk && rtOk) - - -- 2. Proofs (7 positive vectors) - let proofs ← IO.ofExcept (reqArr root "proofs") - tests := tests ++ test "proofs count ≥ 7" (proofs.size ≥ 7) - for p in proofs do - let name ← IO.ofExcept (reqStr p "name") - let hex ← IO.ofExcept (reqStr p "hex") - let blake ← IO.ofExcept (reqStr p "blake3") + return (name, bytes, blake, byteLen) + let parseHexVec (v : Json) (hexKey : String := "hex") : IO (String × ByteArray × String) := do + let name ← IO.ofExcept (reqStr v "name") + let hex ← IO.ofExcept (reqStr v hexKey) + let blake ← IO.ofExcept (reqStr v "blake3") let bytes ← IO.ofExcept (parseHex hex) - let hashOk := addrHex (Address.blake3 bytes) == blake && addrHex (Address.blake3Pure bytes) == blake - let rtOk := match Ixon.Proof.de bytes with - | .ok val => Ixon.Proof.ser val == bytes - | .error _ => false - tests := tests ++ test s!"proof/{name}: blake3+roundtrip" (hashOk && rtOk) - - -- 3. AssumptionTrees (5 vectors + root hash) - let trees ← IO.ofExcept (reqArr root "assumption_trees") - tests := tests ++ test "assumption_trees count ≥ 5" (trees.size ≥ 5) - for t in trees do + return (name, bytes, blake) + let parseTreeVec (t : Json) : IO (String × ByteArray × String × String) := do let name ← IO.ofExcept (reqStr t "name") let hex ← IO.ofExcept (reqStr t "hex") let blake ← IO.ofExcept (reqStr t "blake3") let rootBlake ← IO.ofExcept (reqStr t "root_blake3") let bytes ← IO.ofExcept (parseHex hex) - let hashOk := addrHex (Address.blake3 bytes) == blake - let rtOk := match Ix.AssumptionTree.de bytes with - | .ok val => Ix.AssumptionTree.ser val == bytes && addrHex val.root == rootBlake - | .error _ => false - tests := tests ++ test s!"tree/{name}: blake3+roundtrip+root" (hashOk && rtOk) - - -- 4. Comms (2 vectors: untagged, tagged, commitment digest) - let comms ← IO.ofExcept (reqArr root "comms") - tests := tests ++ test "comms count ≥ 2" (comms.size ≥ 2) - for cm in comms do + return (name, bytes, blake, rootBlake) + let parseCommVec (cm : Json) : IO (String × ByteArray × ByteArray × String) := do let name ← IO.ofExcept (reqStr cm "name") let untaggedHex ← IO.ofExcept (reqStr cm "untagged_hex") let taggedHex ← IO.ofExcept (reqStr cm "tagged_hex") let commitBlake ← IO.ofExcept (reqStr cm "commit_blake3") let untagged ← IO.ofExcept (parseHex untaggedHex) let tagged ← IO.ofExcept (parseHex taggedHex) - let rtOk := match Ixon.deComm untagged with - | .ok val => - Ixon.serComm val == untagged && - Ixon.serCommTagged val == tagged && - addrHex val.commit == commitBlake - | .error _ => false - tests := tests ++ test s!"comm/{name}: untagged+tagged+commit" (rtOk == true) - - -- 5. Univs (7 vectors) - let univs ← IO.ofExcept (reqArr root "univs") - tests := tests ++ test "univs count ≥ 7" (univs.size ≥ 7) - for u in univs do - let name ← IO.ofExcept (reqStr u "name") - let hex ← IO.ofExcept (reqStr u "hex") - let blake ← IO.ofExcept (reqStr u "blake3") - let bytes ← IO.ofExcept (parseHex hex) - let hashOk := addrHex (Address.blake3 bytes) == blake - let rtOk := match Ixon.deUniv bytes with - | .ok val => Ixon.serUniv val == bytes - | .error _ => false - tests := tests ++ test s!"univ/{name}: blake3+roundtrip" (hashOk && rtOk) - - -- 6. Exprs (22 vectors) - let exprs ← IO.ofExcept (reqArr root "exprs") - tests := tests ++ test "exprs count ≥ 20" (exprs.size ≥ 20) - for e in exprs do - let name ← IO.ofExcept (reqStr e "name") - let hex ← IO.ofExcept (reqStr e "hex") - let blake ← IO.ofExcept (reqStr e "blake3") - let bytes ← IO.ofExcept (parseHex hex) - let hashOk := addrHex (Address.blake3 bytes) == blake - let rtOk := match Ixon.deExpr bytes with - | .ok val => Ixon.serExpr val == bytes - | .error _ => false - tests := tests ++ test s!"expr/{name}: blake3+roundtrip" (hashOk && rtOk) - - -- 7. Constants (11 vectors) - let consts ← IO.ofExcept (reqArr root "constants") - tests := tests ++ test "constants count ≥ 11" (consts.size ≥ 11) - for k in consts do - let name ← IO.ofExcept (reqStr k "name") - let hex ← IO.ofExcept (reqStr k "hex") - let blake ← IO.ofExcept (reqStr k "blake3") - let bytes ← IO.ofExcept (parseHex hex) - let hashOk := addrHex (Address.blake3 bytes) == blake - let rtOk := match Ixon.deConstant bytes with - | .ok val => Ixon.serConstant val == bytes - | .error _ => false - tests := tests ++ test s!"constant/{name}: blake3+roundtrip" (hashOk && rtOk) - - -- 8. BLAKE3 (6 vectors across block & chunk boundaries) - let b3s ← IO.ofExcept (reqArr root "blake3") - tests := tests ++ test "blake3 count ≥ 6" (b3s.size ≥ 6) - for b in b3s do - let name ← IO.ofExcept (reqStr b "name") - let inputHex ← IO.ofExcept (reqStr b "input_hex") - let blake ← IO.ofExcept (reqStr b "blake3") - let bytes ← IO.ofExcept (parseHex inputHex) - let ok := addrHex (Address.blake3 bytes) == blake && addrHex (Address.blake3Pure bytes) == blake - tests := tests ++ test s!"blake3/{name}: ffi+pure match Rust" ok - - -- 9. Negative Claim Controls (17 vectors: ALL rejected by Claim.de, DynamicLink cases round-trip in Codec) - let negs ← IO.ofExcept (reqArr root "negative_claims") - tests := tests ++ test "negative_claims count ≥ 17" (negs.size ≥ 17) - for n in negs do + return (name, untagged, tagged, commitBlake) + let parseNegVec (n : Json) : IO (String × ByteArray × String) := do let name ← IO.ofExcept (reqStr n "name") let hex ← IO.ofExcept (reqStr n "hex") let dlKind ← IO.ofExcept (reqStr n "dynamic_link_kind") let bytes ← IO.ofExcept (parseHex hex) - let rejectedByClaim := !(Ix.Claim.de bytes).isOk - tests := tests ++ test s!"neg/{name}: Claim.de rejects" rejectedByClaim - -- For the canonical DynamicLink wire vectors (non-scope-prefix probes), verify Lean Codec round-trip - if dlKind == "dynamic_link" && !name.endsWith "_scope_prefix_0403" then - let dlOk := match Ix.DynamicLink.deDynamicLink bytes with - | .ok s => Ix.DynamicLink.serDynamicLink s == bytes - | .error _ => false - tests := tests ++ test s!"neg/{name}: DynamicLink.deDynamicLink roundtrips" (dlOk == true) - else if dlKind == "eval_assumption" && !name.endsWith "_scope_prefix_0403" then - let eaOk := match Ix.DynamicLink.deEvalAssumption bytes with - | .ok e => Ix.DynamicLink.serEvalAssumption e == bytes - | .error _ => false - tests := tests ++ test s!"neg/{name}: DynamicLink.deEvalAssumption roundtrips" (eaOk == true) - else if dlKind == "eval_assumed_claim" then - let eacOk := match Ix.DynamicLink.deEvalAssumedClaim bytes with - | .ok c => Ix.DynamicLink.serEvalAssumedClaim c == bytes - | .error _ => false - tests := tests ++ test s!"neg/{name}: DynamicLink.deEvalAssumedClaim roundtrips" (eacOk == true) - else if dlKind == "linked_circuit_entry" then - let lceOk := match Ix.DynamicLink.deLinkedCircuitEntry bytes with - | .ok e => Ix.DynamicLink.serLinkedCircuitEntry e == bytes - | .error _ => false - tests := tests ++ test s!"neg/{name}: DynamicLink.deLinkedCircuitEntry roundtrips" (lceOk == true) - else if dlKind == "linked_claim" then - let lcOk := match Ix.DynamicLink.deLinkedClaim bytes with - | .ok c => Ix.DynamicLink.serLinkedClaim c == bytes - | .error _ => false - tests := tests ++ test s!"neg/{name}: DynamicLink.deLinkedClaim roundtrips" (lcOk == true) - - return [tests] + return (name, bytes, dlKind) + + let claimVecs ← claims.mapM parseClaimVec + let proofVecs ← proofs.mapM parseHexVec + let treeVecs ← trees.mapM parseTreeVec + let commVecs ← comms.mapM parseCommVec + let univVecs ← univs.mapM parseHexVec + let exprVecs ← exprs.mapM parseHexVec + let constVecs ← consts.mapM parseHexVec + let b3Vecs ← b3s.mapM (parseHexVec · "input_hex") + let negVecs ← negs.mapM parseNegVec + + return do + -- 1. Claims (20 positive vectors) + itBool "claims count ≥ 15" (decide (claimVecs.size ≥ 15)) + for (name, bytes, blake, byteLen) in claimVecs do + itBool s!"claim/{name}: len+blake3+roundtrip" ( + let lenOk := bytes.size == byteLen + let hashOk := addrHex (Address.blake3 bytes) == blake && addrHex (Address.blake3Pure bytes) == blake + let rtOk := match Ix.Claim.de bytes with + | .ok val => Ix.Claim.ser val == bytes + | .error _ => false + lenOk && hashOk && rtOk) + + -- 2. Proofs (7 positive vectors) + itBool "proofs count ≥ 7" (decide (proofVecs.size ≥ 7)) + for (name, bytes, blake) in proofVecs do + itBool s!"proof/{name}: blake3+roundtrip" ( + let hashOk := addrHex (Address.blake3 bytes) == blake && addrHex (Address.blake3Pure bytes) == blake + let rtOk := match Ixon.Proof.de bytes with + | .ok val => Ixon.Proof.ser val == bytes + | .error _ => false + hashOk && rtOk) + + -- 3. AssumptionTrees (5 vectors + root hash) + itBool "assumption_trees count ≥ 5" (decide (treeVecs.size ≥ 5)) + for (name, bytes, blake, rootBlake) in treeVecs do + itBool s!"tree/{name}: blake3+roundtrip+root" ( + let hashOk := addrHex (Address.blake3 bytes) == blake + let rtOk := match Ix.AssumptionTree.de bytes with + | .ok val => Ix.AssumptionTree.ser val == bytes && addrHex val.root == rootBlake + | .error _ => false + hashOk && rtOk) + + -- 4. Comms (2 vectors: untagged, tagged, commitment digest) + itBool "comms count ≥ 2" (decide (commVecs.size ≥ 2)) + for (name, untagged, tagged, commitBlake) in commVecs do + itBool s!"comm/{name}: untagged+tagged+commit" ( + match Ixon.deComm untagged with + | .ok val => + Ixon.serComm val == untagged && + Ixon.serCommTagged val == tagged && + addrHex val.commit == commitBlake + | .error _ => false) + + -- 5. Univs (7 vectors) + itBool "univs count ≥ 7" (decide (univVecs.size ≥ 7)) + for (name, bytes, blake) in univVecs do + itBool s!"univ/{name}: blake3+roundtrip" ( + let hashOk := addrHex (Address.blake3 bytes) == blake + let rtOk := match Ixon.deUniv bytes with + | .ok val => Ixon.serUniv val == bytes + | .error _ => false + hashOk && rtOk) + + -- 6. Exprs (22 vectors) + itBool "exprs count ≥ 20" (decide (exprVecs.size ≥ 20)) + for (name, bytes, blake) in exprVecs do + itBool s!"expr/{name}: blake3+roundtrip" ( + let hashOk := addrHex (Address.blake3 bytes) == blake + let rtOk := match Ixon.deExpr bytes with + | .ok val => Ixon.serExpr val == bytes + | .error _ => false + hashOk && rtOk) + + -- 7. Constants (11 vectors) + itBool "constants count ≥ 11" (decide (constVecs.size ≥ 11)) + for (name, bytes, blake) in constVecs do + itBool s!"constant/{name}: blake3+roundtrip" ( + let hashOk := addrHex (Address.blake3 bytes) == blake + let rtOk := match Ixon.deConstant bytes with + | .ok val => Ixon.serConstant val == bytes + | .error _ => false + hashOk && rtOk) + + -- 8. BLAKE3 (6 vectors across block & chunk boundaries) + itBool "blake3 count ≥ 6" (decide (b3Vecs.size ≥ 6)) + for (name, bytes, blake) in b3Vecs do + itBool s!"blake3/{name}: ffi+pure match Rust" + (addrHex (Address.blake3 bytes) == blake && addrHex (Address.blake3Pure bytes) == blake) + + -- 9. Negative Claim Controls (17 vectors: ALL rejected by Claim.de, DynamicLink cases round-trip in Codec) + itBool "negative_claims count ≥ 17" (decide (negVecs.size ≥ 17)) + for (name, bytes, dlKind) in negVecs do + itBool s!"neg/{name}: Claim.de rejects" (!(Ix.Claim.de bytes).isOk) + -- For the canonical DynamicLink wire vectors (non-scope-prefix probes), verify Lean Codec round-trip + if dlKind == "dynamic_link" && !name.endsWith "_scope_prefix_0403" then + itBool s!"neg/{name}: DynamicLink.deDynamicLink roundtrips" ( + match Ix.DynamicLink.deDynamicLink bytes with + | .ok s => Ix.DynamicLink.serDynamicLink s == bytes + | .error _ => false) + else if dlKind == "eval_assumption" && !name.endsWith "_scope_prefix_0403" then + itBool s!"neg/{name}: DynamicLink.deEvalAssumption roundtrips" ( + match Ix.DynamicLink.deEvalAssumption bytes with + | .ok e => Ix.DynamicLink.serEvalAssumption e == bytes + | .error _ => false) + else if dlKind == "eval_assumed_claim" then + itBool s!"neg/{name}: DynamicLink.deEvalAssumedClaim roundtrips" ( + match Ix.DynamicLink.deEvalAssumedClaim bytes with + | .ok c => Ix.DynamicLink.serEvalAssumedClaim c == bytes + | .error _ => false) + else if dlKind == "linked_circuit_entry" then + itBool s!"neg/{name}: DynamicLink.deLinkedCircuitEntry roundtrips" ( + match Ix.DynamicLink.deLinkedCircuitEntry bytes with + | .ok e => Ix.DynamicLink.serLinkedCircuitEntry e == bytes + | .error _ => false) + else if dlKind == "linked_claim" then + itBool s!"neg/{name}: DynamicLink.deLinkedClaim roundtrips" ( + match Ix.DynamicLink.deLinkedClaim bytes with + | .ok c => Ix.DynamicLink.serLinkedClaim c == bytes + | .error _ => false) end Tests.Ix.IxonRustParity diff --git a/Tests/Ix/IxonSyntax.lean b/Tests/Ix/IxonSyntax.lean index b6e9c9ead1..9ffa97c06c 100644 --- a/Tests/Ix/IxonSyntax.lean +++ b/Tests/Ix/IxonSyntax.lean @@ -20,7 +20,9 @@ public import LSpec public import Ix.IxonSyntax public import Tests.Gen.IxonSyntax -open LSpec Ixon.Syntax +open LSpec LSpec.Prop Ixon.Syntax + +set_option compiler.extract_closed false namespace Tests.IxonSyntax @@ -43,10 +45,10 @@ def roundtripFile (src : String) : Except String String := do else if f1.decls.size != f2.decls.size then throw "decl count changed" else return p1 -/-- Render an `Except String` check as a test. -/ -def checkExcept (name : String) : Except String α → TestSeq - | .ok _ => test name true - | .error e => test s!"{name}: {e}" false +/-- Render an `Except String` check as a deferred test. -/ +def checkExcept (name : String) (f : Unit → Except String α) : Spec := + it name do + discard <| expectOk (f ()) /-- Does the result satisfy the predicate? (`test` needs applied Bool functions, not literal `match` bodies, for `Testable`.) -/ @@ -123,9 +125,9 @@ def termCorpus : List String := [ "x!? y" ] -def termRoundtrips : TestSeq := - termCorpus.foldl (init := .done) fun acc src => - acc ++ checkExcept s!"roundtrip {repr src}" (roundtripTerm src) +def termRoundtrips : LSpec.Spec := do + for src in termCorpus do + checkExcept s!"roundtrip {repr src}" fun () => roundtripTerm src def isPinnedRef : Term → Bool | .ref r => r.hash.isSome @@ -139,46 +141,42 @@ def isLet (nonDep : Bool) : Term → Bool | .letE contract .. => contract.nonDep == nonDep | _ => false -def adjacencyIsSignificant : TestSeq := - let pinned := parseTerm "f#abcd" - let applied := parseTerm "f #abcd" - test "f#abcd is a pinned ref" (isOk pinned isPinnedRef) - ++ test "f #abcd is an application" (isOk applied isUnaryApp) - ++ test "pinned prints f#abcd" (printsTo pinned "f#abcd") - ++ test "applied prints f #abcd" (printsTo applied "f #abcd") +def adjacencyIsSignificant : LSpec.Spec := do + itBool "f#abcd is a pinned ref" (isOk (parseTerm "f#abcd") isPinnedRef) + itBool "f #abcd is an application" (isOk (parseTerm "f #abcd") isUnaryApp) + itBool "pinned prints f#abcd" (printsTo (parseTerm "f#abcd") "f#abcd") + itBool "applied prints f #abcd" (printsTo (parseTerm "f #abcd") "f #abcd") -def typeArgumentIsGreedy : TestSeq := - test "f Type 1 takes 1 as universe arg" +def typeArgumentIsGreedy : LSpec.Spec := do + itBool "f Type 1 takes 1 as universe arg" (isOk (parseTerm "f Type 1") isUnaryApp) - ++ test "f (Type) 1 canonical" (rtEq "f (Type) 1" "f (Type) 1") - ++ test "f Type 1 canonical" (rtEq "f Type 1" "f (Type 1)") + itBool "f (Type) 1 canonical" (rtEq "f (Type) 1" "f (Type) 1") + itBool "f Type 1 canonical" (rtEq "f Type 1" "f (Type 1)") -def letVsHave : TestSeq := - test "let is dependent" +def letVsHave : LSpec.Spec := do + itBool "let is dependent" (isOk (parseTerm "let x : N := v; x") (isLet false)) - ++ test "have is non-dependent" + itBool "have is non-dependent" (isOk (parseTerm "have x : N := v; x") (isLet true)) /-- The acceptance fixture: hand-formatted input normalizes to the SAME canonical bytes the Rust printer emits (shared golden). -/ -def acceptanceFixture : TestSeq := - let src := "ixon 3\n" - ++ "import #9c41aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa9c41\n" - ++ "\n" - ++ "def : String → Except PatchError String :=\n" - ++ " fun (s : String) => Except.ok PatchError String s\n" - let canonical := - "ixon 3\n\nimport #9c41aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa9c41\n" - ++ "\n" - ++ "def : String → Except PatchError String := " - ++ "fun (s : String) => Except.ok PatchError String s\n" - match roundtripFile src with - | .error e => test s!"acceptance fixture: {e}" false - | .ok printed => - test "acceptance fixture prints the shared canonical golden" - (printed == canonical) - -def kitchenSink : TestSeq := +def acceptanceFixture : LSpec.Spec := do + it "acceptance fixture prints the shared canonical golden" do + let src := "ixon 3\n" + ++ "import #9c41aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa9c41\n" + ++ "\n" + ++ "def : String → Except PatchError String :=\n" + ++ " fun (s : String) => Except.ok PatchError String s\n" + let canonical := + "ixon 3\n\nimport #9c41aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa9c41\n" + ++ "\n" + ++ "def : String → Except PatchError String := " + ++ "fun (s : String) => Except.ok PatchError String s\n" + let printed ← expectOk (roundtripFile src) + shouldBe printed canonical + +def kitchenSink : LSpec.Spec := do let src := "ixon 3 import #aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa @@ -216,8 +214,8 @@ cprj Nat'.succ := #dddd 0 1 ⊢ even (succ zero) : Bool " - checkExcept "kitchen sink roundtrip" (roundtripFile src) - ++ test "kitchen sink has a main expression" + checkExcept "kitchen sink roundtrip" fun () => roundtripFile src + itBool "kitchen sink has a main expression" (isOk (parseFile src) (·.main.isSome)) def rtFileEq (src expect : String) : Bool := @@ -225,7 +223,7 @@ def rtFileEq (src expect : String) : Bool := | .ok p => p == expect | .error _ => false -def mainExpression : TestSeq := +def mainExpression : LSpec.Spec := do let cases : List (String × String) := [ ("⊢ 1 : Nat\n", "⊢ 1 : Nat\n"), ("|- 1 : Nat\n", "⊢ 1 : Nat\n"), @@ -236,96 +234,95 @@ def mainExpression : TestSeq := "⊢ (fun (s : String) => Except.ok PatchError String s) : String → Except PatchError String\n"), ("import #aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\nfun (x : Nat) => x : Nat → Nat\n", "import #aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n\n⊢ (fun (x : Nat) => x) : Nat → Nat\n")] - let formats := cases.foldl (init := .done) fun tests (src, expected) => - tests ++ test s!"v3 main {repr src}" + for (src, expected) in cases do + itBool s!"v3 main {repr src}" (rtFileEq ("ixon 3\n" ++ src) ("ixon 3\n\n" ++ expected)) - formats - ++ test "the annotation is mandatory" + itBool "the annotation is mandatory" (errKind (parseFile "ixon 3\n⊢ 1\n") fun k => match k with | .unexpectedToken .. => true | _ => false) - ++ test "after a declaration the turnstile is required" + itBool "after a declaration the turnstile is required" (errKind (parseFile "ixon 3\ndef x : N := v\n1 : Nat\n") fun k => match k with | .unexpectedToken .. => true | _ => false) - ++ test "at most one main expression" + itBool "at most one main expression" (errKind (parseFile "ixon 3\n⊢ 1 : Nat ⊢ 2 : Nat\n") (· == .mainExprNotLast)) - ++ test "main expression must be last" + itBool "main expression must be last" (errKind (parseFile "ixon 3\n⊢ 1 : Nat def x : A := b\n") (· == .mainExprNotLast)) -def mainAfterTermFinalDecl : TestSeq := +def mainAfterTermFinalDecl : LSpec.Spec := do -- Regression (found by quickcheck on the Rust side): the turnstile -- stops the preceding declaration's application spine. - checkExcept "main after where-less inductive" - (roundtripFile - "ixon 3\ninductive N (params := 0) (indices := 0) : Prop\n\n⊢ Prop : Prop\n") - ++ checkExcept "|- after a ctor block is not eaten by the bar" - (roundtripFile + checkExcept "main after where-less inductive" fun () => + roundtripFile + "ixon 3\ninductive N (params := 0) (indices := 0) : Prop\n\n⊢ Prop : Prop\n" + checkExcept "|- after a ctor block is not eaten by the bar" fun () => + roundtripFile ("ixon 3\ninductive N (params := 0) (indices := 0) : Prop where\n" - ++ " | c (params := 0) (fields := 0) : N\n|- c : N\n")) + ++ " | c (params := 0) (fields := 0) : N\n|- c : N\n") -def versionGate : TestSeq := - ([1, 2, 4] : List Nat).foldl (init := - test "version header required" (errKind (parseFile "⊢ 1 : Nat\n") (fun _ => true))) - fun tests version => tests ++ test s!"ixon {version} rejected" +def versionGate : LSpec.Spec := do + itBool "version header required" (errKind (parseFile "⊢ 1 : Nat\n") (fun _ => true)) + for version in ([1, 2, 4] : List Nat) do + itBool s!"ixon {version} rejected" (errKind (parseFile s!"ixon {version}\n") (· == .unknownVersion version 3)) -def importHashLength : TestSeq := - test "short import hash rejected" +def importHashLength : LSpec.Spec := do + itBool "short import hash rejected" (errKind (parseFile "ixon 3\nimport #abcd\n") fun k => k == .importHashLength 4) -def errorShapes : TestSeq := - test "missing => positioned" +def errorShapes : LSpec.Spec := do + itBool "missing => positioned" (errKind (parseTerm "fun (x : Nat) x") fun k => match k with | .unexpectedToken expected _ => (expected.splitOn "=>").length > 1 | _ => false) - ++ test "uppercase hash rejected" + itBool "uppercase hash rejected" (errKind (parseTerm "#DEAD") fun k => match k with | .invalidHash _ => true | _ => false) - ++ test "placeholder is not a term" + itBool "placeholder is not a term" (errKind (parseTerm "f _") (· == .placeholder)) - ++ test "(x : Nat) without arrow is committed" + itBool "(x : Nat) without arrow is committed" (errKind (parseTerm "(x : Nat)") fun k => match k with | .unexpectedToken expected _ => (expected.splitOn "→").length > 1 | _ => false) - ++ test "empty levels" + itBool "empty levels" (errKind (parseTerm "Nat.{}") (· == .emptyLevels)) - ++ test "line/col are 1-based" + itBool "line/col are 1-based" (errLine (parseFile "ixon 3\ndef x : Nat :=\n") 3) -def depthCap : TestSeq := - let limits : Limits := { maxDepth := 16 } - let deep := "".pushn '(' 64 ++ "x" ++ "".pushn ')' 64 - test "depth cap is a structured error" - (errKind (parseTerm deep limits) fun k => +def depthCap : LSpec.Spec := do + it "depth cap is a structured error" do + let limits : Limits := { maxDepth := 16 } + let deep := "".pushn '(' 64 ++ "x" ++ "".pushn ')' 64 + expect (errKind (parseTerm deep limits) fun k => match k with | .capExceeded .depth _ => true | _ => false) -def byteCap : TestSeq := - let limits : Limits := { maxBytes := 8 } - test "byte cap is a structured error" - (errKind (parseTerm "f x y z w" limits) fun k => +def byteCap : LSpec.Spec := do + it "byte cap is a structured error" do + let limits : Limits := { maxBytes := 8 } + expect (errKind (parseTerm "f x y z w" limits) fun k => match k with | .capExceeded .bytes _ => true | _ => false) -def commentsAndWhitespace : TestSeq := - test "comments are skipped" +def commentsAndWhitespace : LSpec.Spec := do + itBool "comments are skipped" (printsTo (parseTerm "f -- line comment\n /- block /- nested -/ -/ x") "f x") - ++ test "unterminated block comment" + itBool "unterminated block comment" (errKind (parseTerm "f /- open") (· == .unterminatedComment)) -def reservedComponentsEscape : TestSeq := - test "Nat.«def» roundtrips" +def reservedComponentsEscape : LSpec.Spec := do + itBool "Nat.«def» roundtrips" (printsTo (parseTerm "Nat.«def»") "Nat.«def»") - ++ test "«123» stays Str" + itBool "«123» stays Str" (printsTo (parseTerm "Foo.«123»") "Foo.«123»") - ++ test "bare 123 is Num" + itBool "bare 123 is Num" (printsTo (parseTerm "Foo.123") "Foo.123") /-! ## Properties (mirror `props.rs`) -/ @@ -383,28 +380,26 @@ def mutatedTotal (t : Term) (m : Muts) : Bool := end Tests.IxonSyntax -open Tests.IxonSyntax Tests.Gen.IxonSyntax in -public def Tests.IxonSyntax.suite : List LSpec.TestSeq := [ - termRoundtrips, - adjacencyIsSignificant, - typeArgumentIsGreedy, - letVsHave, - acceptanceFixture, - kitchenSink, - mainExpression, - mainAfterTermFinalDecl, - versionGate, - importHashLength, - errorShapes, - depthCap, - byteCap, - commentsAndWhitespace, - reservedComponentsEscape, - checkIO "term print∘parse∘print fixpoint" (∀ t : Term, termFixpoint t), - checkIO "file print∘parse∘print fixpoint" (∀ f : File, fileFixpoint f), - checkIO "node count ≤ printed bytes" (∀ t : Term, nodeCountBounded t), - checkIO "parse total on fuzz strings" (∀ f : Fuzz, parseTotal f), - checkIO "parse total under tiny limits" (∀ f : Fuzz, tinyLimitsTotal f), - checkIO "mutated canonical text total" - (∀ (t : Term) (m : Muts), mutatedTotal t m) -] +open Tests.IxonSyntax Tests.Gen.IxonSyntax LSpec LSpec.Prop in +public def Tests.IxonSyntax.suite : LSpec.Spec := do + termRoundtrips + adjacencyIsSignificant + typeArgumentIsGreedy + letVsHave + acceptanceFixture + kitchenSink + mainExpression + mainAfterTermFinalDecl + versionGate + importHashLength + errorShapes + depthCap + byteCap + commentsAndWhitespace + reservedComponentsEscape + prop "term print∘parse∘print fixpoint" fun (t : Term) => termFixpoint t + prop "file print∘parse∘print fixpoint" fun (f : File) => fileFixpoint f + prop "node count ≤ printed bytes" fun (t : Term) => nodeCountBounded t + prop "parse total on fuzz strings" fun (f : Fuzz) => parseTotal f + prop "parse total under tiny limits" fun (f : Fuzz) => tinyLimitsTotal f + prop "mutated canonical text total" fun (t : Term) (m : Muts) => mutatedTotal t m diff --git a/Tests/Ix/IxonUniverse.lean b/Tests/Ix/IxonUniverse.lean index bfc6772b94..07b9653d28 100644 --- a/Tests/Ix/IxonUniverse.lean +++ b/Tests/Ix/IxonUniverse.lean @@ -12,7 +12,9 @@ slip conditions, bounds and rule vectors retain their original definitions. namespace Tests.Ix.IxonUniverse open LSpec -def canonUnivSweep : +set_option compiler.extract_closed false + +def canonUnivSweep (_ : Unit) : Bool × Bool × Bool × Bool × Bool := Id.run do let mut p0 := true let mut p1 := true @@ -94,72 +96,94 @@ def checkCanon (params : Nat) (strict : Bool) (acc : CanonCheck) return acc /-- A `checkCanon` run as a test: no failures (the first three shown). -/ -def canonCheckTest (name : String) (r : CanonCheck) : TestSeq := - test s!"{name} ({r.count} levels, {r.slips} slip-skipped){ - if r.failures.isEmpty then "" else s!": {r.failures.toList.take 3}"}" - r.failures.isEmpty +def canonCheckTest (name : String) (getRes : IO CanonCheck) : Spec := + it name do + let r ← getRes + expect r.failures.isEmpty + s!"{name} ({r.count} levels, {r.slips} slip-skipped): {r.failures.toList.take 3}" /-- P0 on the smallest value-change witness and its family (strict), with the witness's representative pinned (`canon_univ.rs::tests::p0_witness` pins the same term), and on the biased random family. -/ -def canonUnivValueTests : TestSeq := - let (u, v, w) : Ixon.Univ × Ixon.Univ × Ixon.Univ := (.var 0, .var 1, .var 2) - let l : Ixon.Univ := .imax (.imax (.succ (.imax u w)) u) v - let σ : Nat → Nat := fun i => [0, 1, 2].getD i 0 - let witness := Tests.Gen.Ixon.univWitnessFamily.foldl (checkCanon 4 true) {} - let random := - (Tests.Gen.Ixon.biasedUnivFamily 3 10 4000 41).foldl (checkCanon 3 false) {} - let random4 := - (Tests.Gen.Ixon.biasedUnivFamily 4 12 1000 43).foldl (checkCanon 4 false) {} - test "canonUniv P0: imax (imax (imax u w + 1) u) v keeps its value 1 at (0, 1, 2)" - (Tests.Gen.Ixon.univEval σ l == 1 && Tests.Gen.Ixon.univEval σ (Ixon.canonUniv l) == 1) - ++ test "canonUniv: the witness's representative is pinned (Rust pins the same)" - (Ixon.canonUniv l == .max (.imax (.imax (.succ w) u) v) +def canonUnivValueTests : LSpec.Spec := do + it "canonUniv P0: imax (imax (imax u w + 1) u) v keeps its value 1 at (0, 1, 2)" do + let (u, v, w) : Ixon.Univ × Ixon.Univ × Ixon.Univ := (.var 0, .var 1, .var 2) + let l : Ixon.Univ := .imax (.imax (.succ (.imax u w)) u) v + let σ : Nat → Nat := fun i => [0, 1, 2].getD i 0 + expect (Tests.Gen.Ixon.univEval σ l == 1 && Tests.Gen.Ixon.univEval σ (Ixon.canonUniv l) == 1) + it "canonUniv: the witness's representative is pinned (Rust pins the same)" do + let (u, v, w) : Ixon.Univ × Ixon.Univ × Ixon.Univ := (.var 0, .var 1, .var 2) + let l : Ixon.Univ := .imax (.imax (.succ (.imax u w)) u) v + expect (Ixon.canonUniv l == .max (.imax (.imax (.succ w) u) v) (.imax (.imax (.imax (.succ u) w) u) v)) - ++ test "canonUniv: complete witness and seeded context counts" - (witness.count == 121 && random.count == 20000 && random4.count == 5000) - ++ canonCheckTest "canonUniv P0/P1/P2/P3/P6: the witness family" witness - ++ canonCheckTest "canonUniv P0/P1/P2/P3/P6: biased random, 3 params" random - ++ canonCheckTest "canonUniv P0/P1/P2/P3/P6: biased random, 4 params" random4 - -- The slip is rare; a jump here means the normal forms changed. - ++ test "canonUniv: subsumption slips stay rare (< 1 in 200)" - ((random.slips + random4.slips) * 200 < random.count + random4.count) - -def canonUnivVectors : TestSeq := + withResource { + description := "canonUniv witness and biased random families" + acquire := IO.lazyPure fun () => + let witness := Tests.Gen.Ixon.univWitnessFamily.foldl (checkCanon 4 true) {} + let random := + (Tests.Gen.Ixon.biasedUnivFamily 3 10 4000 41).foldl (checkCanon 3 false) {} + let random4 := + (Tests.Gen.Ixon.biasedUnivFamily 4 12 1000 43).foldl (checkCanon 4 false) {} + (witness, random, random4) + } fun getFamilies => do + it "canonUniv: complete witness and seeded context counts" do + let (witness, random, random4) ← getFamilies + expect (witness.count == 121 && random.count == 20000 && random4.count == 5000) + canonCheckTest "canonUniv P0/P1/P2/P3/P6: the witness family" (Prod.fst <$> getFamilies) + canonCheckTest "canonUniv P0/P1/P2/P3/P6: biased random, 3 params" ((·.2.1) <$> getFamilies) + canonCheckTest "canonUniv P0/P1/P2/P3/P6: biased random, 4 params" ((·.2.2) <$> getFamilies) + -- The slip is rare; a jump here means the normal forms changed. + it "canonUniv: subsumption slips stay rare (< 1 in 200)" do + let (_, random, random4) ← getFamilies + expect (decide ((random.slips + random4.slips) * 200 < random.count + random4.count)) + +def canonUnivVectors : LSpec.Spec := do let v : UInt64 → Ixon.Univ := .var let s : Ixon.Univ → Ixon.Univ := .succ let z : Ixon.Univ := .zero - test "canonUniv: commutative twins converge" + itBool "canonUniv: commutative twins converge" (Ixon.canonUniv (.max (v 1) (v 0)) == .max (v 0) (v 1)) - ++ test "canonUniv: reassociation converges" + itBool "canonUniv: reassociation converges" (Ixon.canonUniv (.max (.max (v 0) (v 1)) (v 2)) == .max (v 0) (.max (v 1) (v 2))) - ++ test "canonUniv: succ distributes over max" + itBool "canonUniv: succ distributes over max" (Ixon.canonUniv (s (.max (v 0) (v 1))) == .max (s (v 0)) (s (v 1))) - ++ test "canonUniv: WF eq_def shape reduces" + itBool "canonUniv: WF eq_def shape reduces" (Ixon.canonUniv (.imax (.imax (s z) (v 0)) (v 0)) == v 0) - ++ test "canonUniv: common spellings are fixpoints" + itBool "canonUniv: common spellings are fixpoints" ([z, s z, v 0, s (v 0), .max (v 0) (v 1), .imax (v 0) (v 1), .imax (s (v 1)) (v 0), .imax (.imax (s (v 0)) (v 1)) (v 2)].all fun u => Ixon.canonUniv u == u) - ++ test "reduceUniv: rule table (M1/M4/M7/I2/I4 spot checks)" + itBool "reduceUniv: rule table (M1/M4/M7/I2/I4 spot checks)" (Ixon.reduceUniv (.max (s z) (s (s z))) == s (s z) && Ixon.reduceUniv (.max (v 0) z) == v 0 && Ixon.reduceUniv (.max (s (v 0)) (s (s (v 0)))) == s (s (v 0)) && Ixon.reduceUniv (.imax (v 0) z) == z && Ixon.reduceUniv (.imax (s z) (v 0)) == v 0) -def canonUnivTests : TestSeq := - let (p0, p1, p2, p3, p6) := canonUnivSweep +def canonUnivTests : LSpec.Spec := do canonUnivVectors - ++ canonUnivValueTests - ++ test "canonUniv P0: value-preserving (exhaustive ≤6)" p0 - ++ test "canonUniv P1: idempotent (exhaustive ≤6)" p1 - ++ test "canonUniv P2: linearize∘normalize fixpoint (exhaustive ≤6)" p2 - ++ test "canonUniv P3: canonical forms are mk* fixpoints (exhaustive ≤6)" - p3 - ++ test "canonUniv P6: mk* rebuild absorbed (exhaustive ≤6)" p6 + canonUnivValueTests + withResource { + description := "canonUniv exhaustive sweep (size ≤ 6)" + acquire := IO.lazyPure fun () => canonUnivSweep () + } fun getSweep => do + it "canonUniv P0: value-preserving (exhaustive ≤6)" do + let (p0, _, _, _, _) ← getSweep + expect p0 + it "canonUniv P1: idempotent (exhaustive ≤6)" do + let (_, p1, _, _, _) ← getSweep + expect p1 + it "canonUniv P2: linearize∘normalize fixpoint (exhaustive ≤6)" do + let (_, _, p2, _, _) ← getSweep + expect p2 + it "canonUniv P3: canonical forms are mk* fixpoints (exhaustive ≤6)" do + let (_, _, _, p3, _) ← getSweep + expect p3 + it "canonUniv P6: mk* rebuild absorbed (exhaustive ≤6)" do + let (_, _, _, _, p6) ← getSweep + expect p6 /-! ## Long `imax` chains (canonUniv's normalizer memo) -/ @@ -182,36 +206,37 @@ def mixedChain (n : Nat) : Ixon.Univ := imaxChain of the normalizer (`2ⁿ` calls on these chains); the normalizer skips a repeated call (`CanonUniv.NState`), so chains of 64 finish. Checked by value (P0), idempotence (P1) and the `mk*` fixpoint (P3). -/ -def canonUnivChainTests : TestSeq := +def canonUnivChainTests : LSpec.Spec := do let ok (u : Ixon.Univ) : Bool := let c := Ixon.canonUniv u (Tests.Gen.Ixon.univDifferAt? 2 u c).isNone && Ixon.canonUniv c == c && Ixon.reduceUniv c == c - test "canonUniv: the Cutsat-shaped chain of 64 imax is `u` (0 at u = 0, else u)" + itBool "canonUniv: the Cutsat-shaped chain of 64 imax is `u` (0 at u = 0, else u)" (Ixon.canonUniv (cutsatChain 64) == .var 0) - ++ test "canonUniv P0, P1 and P3: imax chains of 0–10, 24, 40 and 64 links" + itBool "canonUniv P0, P1 and P3: imax chains of 0–10, 24, 40 and 64 links" (((List.range 11) ++ [24, 40, 64]).all fun n => ok (cutsatChain n) && ok (mixedChain n)) /-- `canonUniv` accumulates successor offsets in `Nat`: in `UInt64` an accumulator at `2^64 - 1` plus one successor wrapped to `0`, and the level lost its value. -/ -def canonUnivOffsetTests : TestSeq := - let init : Ixon.CanonUniv.NState := { acc := (∅ : Ixon.CanonUniv.CNorm).insert [] {} } - test "canonUniv offset past 2^64 is kept, not wrapped" - (((Ixon.CanonUniv.normalizeAux (.succ .zero) [] (2 ^ 64 - 1) init).acc.findD [] {}).constant +def canonUnivOffsetTests : LSpec.Spec := do + it "canonUniv offset past 2^64 is kept, not wrapped" do + let init : Ixon.CanonUniv.NState := { acc := (∅ : Ixon.CanonUniv.CNorm).insert [] {} } + expect (((Ixon.CanonUniv.normalizeAux (.succ .zero) [] (2 ^ 64 - 1) init).acc.findD [] {}).constant == 2 ^ 64) - ++ test "canonUniv offset past 2^64 on a variable is kept" - (((Ixon.CanonUniv.normalizeAux (.succ (.var 0)) [] (2 ^ 64 - 1) init).acc.findD [0] {}).vars + it "canonUniv offset past 2^64 on a variable is kept" do + let init : Ixon.CanonUniv.NState := { acc := (∅ : Ixon.CanonUniv.CNorm).insert [] {} } + expect (((Ixon.CanonUniv.normalizeAux (.succ (.var 0)) [] (2 ^ 64 - 1) init).acc.findD [0] {}).vars == #[(0, 2 ^ 64)]) -public def suite : List TestSeq := [ - test "canonUniv: exhaustive size classes 1–6 and total 3736" +public def suite : LSpec.Spec := do + itBool "canonUniv: exhaustive size classes 1–6 and total 3736" ((List.range 6).map (fun i => (Tests.Gen.Ixon.enumerateUniv (i + 1)).length - (Tests.Gen.Ixon.enumerateUniv i).length) == [4, 4, 36, 100, 708, 2884] && - (Tests.Gen.Ixon.enumerateUniv 6).length == 3736), - canonUnivTests, - canonUnivChainTests, - canonUnivOffsetTests] + (Tests.Gen.Ixon.enumerateUniv 6).length == 3736) + canonUnivTests + canonUnivChainTests + canonUnivOffsetTests end Tests.Ix.IxonUniverse diff --git a/Tests/Ix/Kernel/BuildPrimitives.lean b/Tests/Ix/Kernel/BuildPrimitives.lean index 18364ef922..b2f12bf890 100644 --- a/Tests/Ix/Kernel/BuildPrimitives.lean +++ b/Tests/Ix/Kernel/BuildPrimitives.lean @@ -121,8 +121,8 @@ def parseIxName (s : String) : Ix.Name := Id.run do /-- Dump the current `(name, hex)` table for every entry in `kernelPrimitives`. Pass iff every entry resolves; missing names are printed as `// MISSING:` comments so the output is still valid as-is for partial regeneration. -/ -def testBuildPrimitives : TestSeq := - .individualIO "build primitives dump" none (do +def testBuildPrimitives : Spec := + it "build primitives dump" do let leanEnv ← get_env! let filtered := primitiveClosure leanEnv @@ -157,10 +157,7 @@ def testBuildPrimitives : TestSeq := if !missing.isEmpty then IO.println s!"// Missing: {missing}" - let msg : Option String := - if missing.isEmpty then none else some s!"{missing.size} primitives missing from Ixon env" - return (missing.isEmpty, found, missing.size, msg) - ) .done + expect missing.isEmpty s!"{missing.size} primitives missing from Ixon env" /-- FFI: expose `PrimAddrs::new()` from Rust as `(lean_name, hex_address)` pairs in the same order as @@ -186,8 +183,8 @@ opaque rsPrimAddrsCanonicalFFI : IO (Array (String × String)) PrimAddrs value (`0xff…3`) intentionally diverges from its compiled content hash (which collides with `id`). Skip the check for it. -/ -def testPrimitivesParity : TestSeq := - .individualIO "primitive address parity (PrimAddrs vs live compile)" none (do +def testPrimitivesParity : Spec := + it "primitive address parity (PrimAddrs vs live compile)" do -- Reuse the same Lean → Ixon compile pipeline as testBuildPrimitives. let leanEnv ← get_env! let filtered := primitiveClosure leanEnv @@ -232,15 +229,12 @@ def testPrimitivesParity : TestSeq := IO.eprintln "Regenerate via `lake test -- --ignored rust-kernel-build-primitives` and paste into crates/common/src/prim_addrs.rs." let total_problems := missing.size + mismatches.size - let passed := kernelPrimitives.size - min total_problems kernelPrimitives.size - let msg : Option String := - if total_problems == 0 then none - else some s!"{mismatches.size} mismatch(es), {missing.size} missing" - return (total_problems == 0, passed, total_problems, msg) - ) .done + expect (total_problems == 0) s!"{mismatches.size} mismatch(es), {missing.size} missing" -def paritySuite : List TestSeq := [testPrimitivesParity] +def paritySuite : LSpec.Spec := do + testPrimitivesParity -def suite : List TestSeq := [testBuildPrimitives] +def suite : LSpec.Spec := do + testBuildPrimitives end Tests.Ix.Kernel.BuildPrimitives diff --git a/Tests/Ix/Kernel/BundleEvidence.lean b/Tests/Ix/Kernel/BundleEvidence.lean index 900a5cfdc2..f804d3f244 100644 --- a/Tests/Ix/Kernel/BundleEvidence.lean +++ b/Tests/Ix/Kernel/BundleEvidence.lean @@ -32,7 +32,7 @@ def operations : Array Lean.Name := /-- The bundle's evidence: no reason, the structural operations' entries, and each well-founded operation's theorems, in order, under their names. -/ -def shape : TestSeq := +def shape : LSpec.Spec := do let (ev, why) := Ix.RoleEvidence.bundleEvidenceReport () let structural := Ix.RoleEvidence.defeqRoles.all fun r => ev.any fun (r', es) => r' == r && es.length == (Ix.RoleEvidence.defeqEvidence (K := Unit) r).length && @@ -42,9 +42,9 @@ def shape : TestSeq := (es.zip thms).all fun (e, t) => match e with | .proof (k, _) => k == Ix.RoleEvidence.ofLeanName t | .defeq => false - test s!"the committed bundle reads ({why})" why.isEmpty $ - test "the structural operations: their defeq entries" structural $ - test "the well-founded operations: their certificate theorems, in order, by name" proved + itBool s!"the committed bundle reads ({why})" why.isEmpty + itBool "the structural operations: their defeq entries" structural + itBool "the well-founded operations: their certificate theorems, in order, by name" proved /-- The operations' closure in `Init` (no certificate theorem), checked group by group at the input's own evidence and at the bundle's, and all at once at @@ -75,13 +75,14 @@ def evaluate : IO (Array String × Array String) := do | .error e => errors := errors.push s!"checkSourceWith at the bundle's evidence: {e}" return (errors, lines) -def closureCheck : TestSeq := - .individualIO "the operations' Init closure, without certificates, at the bundle's evidence" none (do +def closureCheck : Spec := + it "the operations' Init closure, without certificates, at the bundle's evidence" do let (errors, lines) ← evaluate for l in lines do IO.println l - let msg := if errors.isEmpty then none else some ("\n".intercalate errors.toList) - return (errors.isEmpty, operations.size, 0, msg)) .done + expect errors.isEmpty ("\n".intercalate errors.toList) -def suite : List TestSeq := [shape, closureCheck] +def suite : LSpec.Spec := do + shape + closureCheck end Tests.Ix.Kernel.BundleEvidence diff --git a/Tests/Ix/Kernel/CheckCompPoly.lean b/Tests/Ix/Kernel/CheckCompPoly.lean index a64561060c..9dd944b80b 100644 --- a/Tests/Ix/Kernel/CheckCompPoly.lean +++ b/Tests/Ix/Kernel/CheckCompPoly.lean @@ -36,15 +36,15 @@ private def filterFocusConsts (names : Array Lean.Name) : IO (Array Lean.Name) : {filtered.size}/{names.size}" pure filtered -def testRustCheckCompPoly : TestSeq := - .individualIO s!"kernel check {focusConsts.size} CompPoly focus const(s)" none (do +def testRustCheckCompPoly : Spec := + it s!"kernel check {focusConsts.size} CompPoly focus const(s)" do unless (← ixePath.pathExists) do - return (false, 0, focusConsts.size, some s!"{ixePath} missing — build it with \ + fail s!"{ixePath} missing — build it with \ `lake exe ix compile Benchmarks/Compile/CompPoly.lean \ - --out comppoly.ixe --verbose`") + --out comppoly.ixe --verbose`" let names ← filterFocusConsts focusConsts if names.isEmpty then - return (false, 0, 0, some "IX_KERNEL_FOCUS_CONST matched no CompPoly canary") + fail "IX_KERNEL_FOCUS_CONST matched no CompPoly canary" let start ← IO.monoMsNow let expected := names.map fun _ => true let results ← rsCheckIxonFFI ixePath.toString names expected false "" @@ -57,12 +57,9 @@ def testRustCheckCompPoly : TestSeq := passed in {elapsed}ms" for (name, msg) in failures do IO.println s!" ✗ {name}: {msg}" - if failures.isEmpty then - return (true, names.size, names.size, none) - return (false, names.size - failures.size, names.size, - some s!"CompPoly focus check failed with {failures.size} failure(s)") - ) .done + expect failures.isEmpty s!"CompPoly focus check failed with {failures.size} failure(s)" -def suite : List TestSeq := [testRustCheckCompPoly] +def suite : LSpec.Spec := do + testRustCheckCompPoly end Tests.Ix.Kernel.CheckCompPoly diff --git a/Tests/Ix/Kernel/CheckLeanCli.lean b/Tests/Ix/Kernel/CheckLeanCli.lean index 2b8701fc92..a5127d82d0 100644 --- a/Tests/Ix/Kernel/CheckLeanCli.lean +++ b/Tests/Ix/Kernel/CheckLeanCli.lean @@ -64,7 +64,7 @@ private def check : IO Nat := do -- Keep the actual pin adapter's fresh-run/timing path executable on a small -- fixture; the historical corpus pin labels and budgets stay unchanged. let pin ← Tests.Tc.Pins.checkPin prepared { label := "CliAlias0", budgetMs := 60000 } - ensure ((← lspecIO (.ofList [("pin-adapter", [pin])]) []) == 0) "pin adapter failed" + ensure ((← lspecMain (describe "pin-adapter" pin) []) == 0) "pin adapter failed" let window := prepared.parts.env.consts[twice.addr]! let tampered := bytes.set! window.off (bytes[window.off]! ^^^ 1) for anon in [false, true] do @@ -244,9 +244,8 @@ private def check : IO Nat := do finally IO.FS.removeDirAll dir -def suite : List TestSeq := [ - .individualIO "authenticated IxCK CLI and repeatable prepared callers" none (do - let n ← check - return (true, n, 0, none)) .done] +def suite : LSpec.Spec := do + it "authenticated IxCK CLI and repeatable prepared callers" do + let _ ← check end Tests.Ix.Kernel.CheckLeanCli diff --git a/Tests/Ix/Kernel/CheckLeanTargets.lean b/Tests/Ix/Kernel/CheckLeanTargets.lean index 82427b9c00..d2d17873ba 100644 --- a/Tests/Ix/Kernel/CheckLeanTargets.lean +++ b/Tests/Ix/Kernel/CheckLeanTargets.lean @@ -146,9 +146,8 @@ private def check : IO Nat := do IO.println s!"selected coverage: {labels.size} named at both modes; 5 aliases; caps, recursors, omitted projections and failures" return labels.size * 2 + 5 -def suite : List TestSeq := [ - .individualIO "selected labels require their actual producer and emitted key" none (do - let n ← check - return (true, n, 0, none)) .done] +def suite : LSpec.Spec := do + it "selected labels require their actual producer and emitted key" do + let _ ← check end Tests.Ix.Kernel.CheckLeanTargets diff --git a/Tests/Ix/Kernel/CheckPrimeGaps.lean b/Tests/Ix/Kernel/CheckPrimeGaps.lean index 36272fdeeb..ba309ba316 100644 --- a/Tests/Ix/Kernel/CheckPrimeGaps.lean +++ b/Tests/Ix/Kernel/CheckPrimeGaps.lean @@ -32,16 +32,17 @@ private def filterFocusConsts (names : Array Lean.Name) : IO (Array Lean.Name) : {filtered.size}/{names.size}" pure filtered -def testLeanCheckPrimeGaps : TestSeq := - .individualIO s!"IxCK check {focusConsts.size} inlined PrimeGaps consts" none (do +def testLeanCheckPrimeGaps : Spec := + it s!"IxCK check {focusConsts.size} inlined PrimeGaps consts" do let names ← filterFocusConsts focusConsts let leanEnv ← get_env! IO.println s!"[check-primegaps/lean] compiling \ selected IxCK closure for {names.size} exact subject(s)" - Tests.Ix.Kernel.FocusedLeanCheck.checkClosure "check-primegaps/lean" + let (ok, _, _, msg) ← Tests.Ix.Kernel.FocusedLeanCheck.checkClosure "check-primegaps/lean" "primegaps-reduction" leanEnv names - ) .done + expect ok (msg.getD "PrimeGaps check failed") -def suite : List TestSeq := [testLeanCheckPrimeGaps] +def suite : LSpec.Spec := do + testLeanCheckPrimeGaps end Tests.Ix.Kernel.CheckPrimeGaps diff --git a/Tests/Ix/Kernel/CheckTauCeti.lean b/Tests/Ix/Kernel/CheckTauCeti.lean index 2a0b3db6aa..8d7b5f79a7 100644 --- a/Tests/Ix/Kernel/CheckTauCeti.lean +++ b/Tests/Ix/Kernel/CheckTauCeti.lean @@ -87,11 +87,11 @@ private def filterFocusConsts (names : Array Lean.Name) : IO (Array Lean.Name) : IO.println s!"[check-tauceti] IX_KERNEL_FOCUS_CONST={filter} matched {filtered.size}/{names.size}" pure filtered -def testRustCheckTauCetiConsts (names : Array Lean.Name := focusConsts) : TestSeq := - .individualIO s!"kernel check {names.size} TauCeti focus consts" none (do +def testRustCheckTauCetiConsts (names : Array Lean.Name := focusConsts) : Spec := + it s!"kernel check {names.size} TauCeti focus consts" do unless (← ixePath.pathExists) do - return (false, 0, names.size, some s!"{ixePath} missing — build it \ - with `ix compile Benchmarks/Compile/TauCeti.lean` (see module docstring)") + fail s!"{ixePath} missing — build it \ + with `ix compile Benchmarks/Compile/TauCeti.lean` (see module docstring)" let names ← filterFocusConsts names let expectPass : Array Bool := names.map expectedPass let start ← IO.monoMsNow @@ -129,14 +129,9 @@ def testRustCheckTauCetiConsts (names : Array Lean.Name := focusConsts) : TestSe for (name, msg) in failures do IO.println s!" ✗ {name}: {msg}" - let total := passed + failures.size - if failures.isEmpty then - return (true, passed, total, none) - else - return (false, passed, total, - some s!"TauCeti focus check failed with {failures.size} failure(s)") - ) .done + expect failures.isEmpty s!"TauCeti focus check failed with {failures.size} failure(s)" -def suite : List TestSeq := [testRustCheckTauCetiConsts] +def suite : LSpec.Spec := do + testRustCheckTauCetiConsts end Tests.Ix.Kernel.CheckTauCeti diff --git a/Tests/Ix/Kernel/CheckTauCetiReduction.lean b/Tests/Ix/Kernel/CheckTauCetiReduction.lean index 137e70fc61..c88a6379e1 100644 --- a/Tests/Ix/Kernel/CheckTauCetiReduction.lean +++ b/Tests/Ix/Kernel/CheckTauCetiReduction.lean @@ -23,17 +23,16 @@ def focusConsts : Array Lean.Name := #[ `Tests.Ix.Kernel.TauCetiReduction.composedSymmApply ] -def testLeanCheckTauCetiReduction : TestSeq := - .individualIO s!"IxCK check {focusConsts.size} inlined TauCeti reductions" none (do +def testLeanCheckTauCetiReduction : Spec := + it s!"IxCK check {focusConsts.size} inlined TauCeti reductions" do let leanEnv ← get_env! IO.println s!"[check-tauceti-reduction/lean] compiling \ selected IxCK closure for {focusConsts.size} subject(s)" - Tests.Ix.Kernel.FocusedLeanCheck.checkClosure + let (ok, _, _, msg) ← Tests.Ix.Kernel.FocusedLeanCheck.checkClosure "check-tauceti-reduction/lean" "tauceti-reduction" leanEnv focusConsts - ) .done + expect ok (msg.getD "TauCeti reduction check failed") -def suite : List TestSeq := [ +def suite : LSpec.Spec := do testLeanCheckTauCetiReduction -] end Tests.Ix.Kernel.CheckTauCetiReduction diff --git a/Tests/Ix/Kernel/FastPaths.lean b/Tests/Ix/Kernel/FastPaths.lean index 44841e3cb6..bc7c598448 100644 --- a/Tests/Ix/Kernel/FastPaths.lean +++ b/Tests/Ix/Kernel/FastPaths.lean @@ -93,16 +93,16 @@ def ixcVerdicts (compiled : Ix.CompileM.CertifiedOut) (names : List Lean.Name) : /-- The check of one probe against one kernel's verdicts. -/ def checkProbe (kernel : String) (closure : List Lean.Name) (verdicts : Verdicts) - (p : Probe) : TestSeq := + (p : Probe) : Spec := do let missing := closure.filter (!verdicts.contains ·) let failures := closure.filter fun n => !(verdicts.getD n .accept).isAccept - let describe (ns : List Lean.Name) : String := + let describeVerdicts (ns : List Lean.Name) : String := ", ".intercalate (ns.map fun n => s!"{n}: {(verdicts.getD n .accept).label}") - let complete := test s!"{kernel}: every member of {p.name}'s closure has a verdict \ + itBool s!"{kernel}: every member of {p.name}'s closure has a verdict \ (missing: {missing.take 5})" missing.isEmpty match p.expect with | .accept => - complete ++ test s!"{kernel} accepts the closure of {p.name} ({describe failures})" + itBool s!"{kernel} accepts the closure of {p.name} ({describeVerdicts failures})" failures.isEmpty | .reject culprit => let culpritRejected := (verdicts.getD culprit .accept).isReject @@ -110,11 +110,10 @@ def checkProbe (kernel : String) (closure : List Lean.Name) (verdicts : Verdicts -- trusted) or blocked behind the culprit, never rejected on its own let probeOk := p.name == culprit || !(verdicts.getD p.name .accept).isReject let others := failures.filter fun n => n != culprit && n != p.name - complete - ++ test s!"{kernel} rejects {culprit}, so the closure of {p.name} \ - ({(verdicts.getD culprit .accept).label})" culpritRejected - ++ test s!"{kernel}: {p.name} fails only through {culprit} ({describe others})" - (probeOk && others.isEmpty) + itBool s!"{kernel} rejects {culprit}, so the closure of {p.name} \ + ({(verdicts.getD culprit .accept).label})" culpritRejected + itBool s!"{kernel}: {p.name} fails only through {culprit} ({describeVerdicts others})" + (probeOk && others.isEmpty) def run : IO UInt32 := do let leanEnv ← get_env! @@ -137,10 +136,10 @@ def run : IO UInt32 := do let ixc ← ixcVerdicts compiled names let t2 ← IO.monoMsNow IO.println s!"[kernel-fast-paths] compile {t1 - t0} ms, IxCK {t2 - t1} ms" - let mut seq : TestSeq := .done - for (kernel, verdicts) in [("IxCK", ixc)] do - for p in probes do - seq := seq ++ checkProbe kernel (closures.getD p.name []) verdicts p - lspecIO (.ofList [("kernel-fast-paths", [seq])]) [] + let spec : Spec := describe "kernel-fast-paths" do + for (kernel, verdicts) in [("IxCK", ixc)] do + for p in probes do + checkProbe kernel (closures.getD p.name []) verdicts p + lspecMain spec [] end Tests.Ix.Kernel.FastPaths diff --git a/Tests/Ix/Kernel/FidelityAccess.lean b/Tests/Ix/Kernel/FidelityAccess.lean index ebaaf6e46b..464bcdf46b 100644 --- a/Tests/Ix/Kernel/FidelityAccess.lean +++ b/Tests/Ix/Kernel/FidelityAccess.lean @@ -100,9 +100,8 @@ private def check : IO Nat := do IO.println s!"projection access: {baseline.blocks} blocks, {baseline.compiled} projections; eager/lazy parity and strict faults" return baseline.compiled -def suite : List TestSeq := [ - .individualIO "lazy projection fidelity preserves exact reports and refuses access faults" none (do - let n ← check - return (true, n, 0, none)) .done] +def suite : LSpec.Spec := do + it "lazy projection fidelity preserves exact reports and refuses access faults" do + let _ ← check end Tests.Ix.Kernel.FidelityAccess diff --git a/Tests/Ix/Kernel/Pins.lean b/Tests/Ix/Kernel/Pins.lean index a63ed225c5..9cb7e3d656 100644 --- a/Tests/Ix/Kernel/Pins.lean +++ b/Tests/Ix/Kernel/Pins.lean @@ -55,22 +55,22 @@ def pins : List Pin := [ /-- Check a fresh supporting closure over shared authenticated preparation. The existing per-subject budget measures its actual producer's checker time; input, preparation, reading and support checking are reported separately. -/ -public def checkPin (prepared : Ix.Cli.CheckLeanCmd.PreparedInput) (pin : Pin) : IO TestSeq := do +public def checkPin (prepared : Ix.Cli.CheckLeanCmd.PreparedInput) (pin : Pin) : IO Spec := do let expected ← match Ix.Cli.CheckLeanTargets.findCandidate prepared.inventory pin.label with | .ok c => pure c - | .error _ => return test s!"{pin.label}: resolves unambiguously in the input" false + | .error _ => return itBool s!"{pin.label}: resolves unambiguously in the input" false let cfg : Ix.Cli.CheckLeanCmd.CheckCfg := { workers := 1, silent := true, progressMs := 0, slowMs := 0 } match ← Ix.Cli.CheckLeanCmd.runPrepared prepared cfg (.only #[pin.label]) with - | .error e => return test s!"{pin.label}: driver failed: {e.message}" false + | .error e => return itBool s!"{pin.label}: driver failed: {e.message}" false | .ok report => if report.targets.size != 1 || report.targets.any (fun r => r.target.label != expected.label || r.target.address != expected.address || r.outcome != "accept") then - return test s!"{pin.label}: exact accepted coverage (got {report.failures})" false + return itBool s!"{pin.label}: exact accepted coverage (got {report.failures})" false let subjectMs := report.subjectMicros / 1000 IO.println s!"tc-pins: {pin.label}: selected checker {subjectMs}ms; preparation {report.prepareMs}ms; \ reading {report.readMicros / 1000}ms; support checker {report.supportMicros / 1000}ms; run {report.elapsedMs}ms" - return test s!"{pin.label}: producer checked in {subjectMs}ms (budget {pin.budgetMs}ms)" - (report.subjectMicros ≤ pin.budgetMs * 1000) + return itBool s!"{pin.label}: producer checked in {subjectMs}ms (budget {pin.budgetMs}ms)" + (decide (report.subjectMicros ≤ pin.budgetMs * 1000)) public def run : IO UInt32 := do IO.println "tc-pins" @@ -89,11 +89,13 @@ public def run : IO UInt32 := do activePins := activePins.push pin let tasks ← activePins.mapM fun pin => IO.asTask (prio := .dedicated) (checkPin prepared pin) - let mut seq : TestSeq := .done + let mut specs : Array Spec := #[] for task in tasks do match ← IO.wait task with - | .ok s => seq := seq ++ s + | .ok s => specs := specs.push s | .error e => throw e - lspecIO (.ofList [("tc-pins", [seq])]) [] + lspecMain (describe "tc-pins" do + for s in specs do + s) [] end Tests.Tc.Pins diff --git a/Tests/Ix/Kernel/PreludeFidelity.lean b/Tests/Ix/Kernel/PreludeFidelity.lean index ccf76fd838..6cc40989db 100644 --- a/Tests/Ix/Kernel/PreludeFidelity.lean +++ b/Tests/Ix/Kernel/PreludeFidelity.lean @@ -91,9 +91,8 @@ private def check : IO Nat := do {borrowed.constants} borrowed-owner source comparisons and explicit setup reader failure" return baseline.constants -def suite : List TestSeq := [ - .individualIO "setup-only prelude preserves source coverage and every input/error refusal" none (do - let n ← check - return (true, n, 0, none)) .done] +def suite : LSpec.Spec := do + it "setup-only prelude preserves source coverage and every input/error refusal" do + let _ ← check end Tests.Ix.Kernel.PreludeFidelity diff --git a/Tests/Ix/Kernel/PrimAddrs.lean b/Tests/Ix/Kernel/PrimAddrs.lean index 96de687ee0..f526902f3c 100644 --- a/Tests/Ix/Kernel/PrimAddrs.lean +++ b/Tests/Ix/Kernel/PrimAddrs.lean @@ -104,15 +104,15 @@ def problems (fns : Array Tests.Ix.IxVM.Sources.Function) : Array String := Id.r out := out.push s!"{f.name} reads the default role binding" return out -def literalGuard : TestSeq := - .individualIO "the IxVM program's only address literals are the specification digest, \ - the debug entry points' default binding and the basis pin's default bindings" none (do +def literalGuard : Spec := + it "the IxVM program's only address literals are the specification digest, \ + the debug entry points' default binding and the basis pin's default bindings" do let found := problems (Tests.Ix.IxVM.Sources.functions (← Tests.Ix.IxVM.programSources)) - let ok := found.isEmpty - return (ok, if ok then 1 else 0, 1, - if ok then none else some ("; ".intercalate found.toList))) .done + expect found.isEmpty ("; ".intercalate found.toList) -def suite : List TestSeq := [literalGuard] ++ Tests.Ix.Kernel.PrimitiveTable.suite +def suite : LSpec.Spec := do + literalGuard + Tests.Ix.Kernel.PrimitiveTable.suite /-- A dotted Lean name as an `Ix.Name` (string components only). -/ private def ixNameOf (s : String) : Ix.Name := diff --git a/Tests/Ix/Kernel/PrimitiveTable.lean b/Tests/Ix/Kernel/PrimitiveTable.lean index ea94d99900..2a93460f69 100644 --- a/Tests/Ix/Kernel/PrimitiveTable.lean +++ b/Tests/Ix/Kernel/PrimitiveTable.lean @@ -11,24 +11,20 @@ open LSpec _root_.Ix @[extern "rs_prim_addrs_canonical"] private opaque rsPrimAddrsCanonicalFFI : IO (Array (String × String)) -def primsParity : TestSeq := - .individualIO "PrimAddrs.canonical parity vs Rust PrimAddrs::new()" none (do +def primsParity : Spec := + it "PrimAddrs.canonical parity vs Rust PrimAddrs::new()" do let rust ← rsPrimAddrsCanonicalFFI let lean := PrimAddrs.leanParityTable - if rust.size != lean.size then - return (false, rust.size, lean.size, - some s!"size mismatch: rust {rust.size} vs lean {lean.size}") + expect (rust.size == lean.size) s!"size mismatch: rust {rust.size} vs lean {lean.size}" let mut bad : Array String := #[] for ((rn, rh), (ln, la)) in rust.zip lean do if rn != ln then bad := bad.push s!"order mismatch: {rn} vs {ln}" else if toString la != rh then bad := bad.push s!"{rn}: rust {rh} != lean {toString la}" - if bad.isEmpty then - return (true, rust.size, rust.size, none) - return (false, bad.size, rust.size, - some (String.intercalate "; " bad.toList))) .done + expect bad.isEmpty (String.intercalate "; " bad.toList) -public def suite : List TestSeq := [primsParity] +public def suite : LSpec.Spec := do + primsParity end Tests.Ix.Kernel.PrimitiveTable diff --git a/Tests/Ix/Kernel/ReaderRoundtrip.lean b/Tests/Ix/Kernel/ReaderRoundtrip.lean index 58be0dd1f6..097a1f923b 100644 --- a/Tests/Ix/Kernel/ReaderRoundtrip.lean +++ b/Tests/Ix/Kernel/ReaderRoundtrip.lean @@ -243,14 +243,14 @@ def evaluate : IO (Report × Array String × Array String) := do let (lines, egressErrors) ← evaluateEgress inp return (report, lines, readerErrors ++ egressErrors) -def suiteIO : TestSeq := - .individualIO "reader fidelity and egress: compiled fixture closure against Lean" none (do +def suiteIO : Spec := + it "reader fidelity and egress: compiled fixture closure against Lean" do let (report, lines, errors) ← evaluate IO.println report.summary for l in lines do IO.println l - let msg := if errors.isEmpty then none else some ("\n".intercalate errors.toList) - return (errors.isEmpty, report.constants, 0, msg)) .done + expect errors.isEmpty ("\n".intercalate errors.toList) -def suite : List TestSeq := [suiteIO] +def suite : LSpec.Spec := do + suiteIO end Tests.Ix.Kernel.ReaderRoundtrip diff --git a/Tests/Ix/Kernel/RecordCheck.lean b/Tests/Ix/Kernel/RecordCheck.lean index ff0c34d6b3..55e49e05b8 100644 --- a/Tests/Ix/Kernel/RecordCheck.lean +++ b/Tests/Ix/Kernel/RecordCheck.lean @@ -304,15 +304,11 @@ evaluated when the module initializes. -/ end StoreRefusals -def suite : List TestSeq := [ - .individualIO "actual anon/meta outcomes, rollback, tiers and worker replay" none (do - let n ← check - return (true, n, 0, none)) .done, +def suite : LSpec.Spec := do + it "actual anon/meta outcomes, rollback, tiers and worker replay" do + let _ ← check -- 769 records: at 256 tasks the parallel decoder's chunks are four records long - .individualIO "record store: orphan, noncanonical and oversized records, phase precedence, cache" - none (do - return match StoreRefusals.checks (← StoreRefusals.atRunTime Nat 769) with - | .ok n => (true, n, 0, none) - | .error message => (false, 0, 0, some message)) .done] + it "record store: orphan, noncanonical and oversized records, phase precedence, cache" do + let _ ← expectOk (StoreRefusals.checks (← StoreRefusals.atRunTime Nat 769)) end Tests.Ix.Kernel.RecordCheck diff --git a/Tests/Ix/Kernel/SourceIngress.lean b/Tests/Ix/Kernel/SourceIngress.lean index 5628bb1b7b..851f93f136 100644 --- a/Tests/Ix/Kernel/SourceIngress.lean +++ b/Tests/Ix/Kernel/SourceIngress.lean @@ -148,7 +148,7 @@ def nm (s : String) : Ix.Name := .mkStr anon s /-- The numbering of a constant with no level parameters. -/ def noParams : Numbering := ⟨#[], false⟩ -def refusals : TestSeq := +def refusals : LSpec.Spec := do let fv := Ix.Expr.mkFVar (nm "x") let mv := Ix.Expr.mkMVar (nm "m") let lv := Ix.Expr.mkSort (Ix.Level.mkMvar (nm "u")) @@ -156,9 +156,9 @@ def refusals : TestSeq := match ingressExprs noParams.pos [Ix.Expr.mkApp (Ix.Expr.mkBVar 0) e] with | .error err => k err | .ok _ => false - test "free variable refused" (refused fv fun | .fvar _ => true | _ => false) ++ - test "metavariable refused" (refused mv fun | .mvar _ => true | _ => false) ++ - test "level metavariable refused" (refused lv fun | .levelMVar _ => true | _ => false) + itBool "free variable refused" (refused fv fun | .fvar _ => true | _ => false) + itBool "metavariable refused" (refused mv fun | .mvar _ => true | _ => false) + itBool "level metavariable refused" (refused lv fun | .levelMVar _ => true | _ => false) def sameResult : Except ExprError (List KExpr) → Except ExprError (List KExpr) → Bool | .ok a, .ok b => a == b @@ -168,13 +168,13 @@ def lamDropped : Except ExprError (List KExpr) → Bool | .ok [.lam (.const n []) (.bvar 0) m] => n == Ix.Kernel.roleKey .nat && m == { pw := .never } | _ => false -def erasure : TestSeq := +def erasure : LSpec.Spec := do let body := Ix.Expr.mkConst (nm "Nat") #[] let withData := Ix.Expr.mkMData #[(nm "k", .ofBool true)] body let lam := Ix.Expr.mkLam (nm "x") body (.mkBVar 0) .implicit - test "mdata erased" - (sameResult (ingressExprs noParams.pos [withData]) (ingressExprs noParams.pos [body])) ++ - test "binder name and info dropped, pw never" (lamDropped (ingressExprs noParams.pos [lam])) + itBool "mdata erased" + (sameResult (ingressExprs noParams.pos [withData]) (ingressExprs noParams.pos [body])) + itBool "binder name and info dropped, pw never" (lamDropped (ingressExprs noParams.pos [lam])) /-- `e` under the contract frame of `c`, as `Ix.Compile.CompileInput.prepare` writes it and `Ix.CanonM` keeps it. -/ @@ -206,7 +206,7 @@ def refusedWith (message : String) : Except ExprError (List KExpr) → Bool the binder it wraps, as the compiler lowers it; an unsupported contract mode, a frame not directly around a binder of its kind, or a malformed frame is refused. -/ -def contractFrames : TestSeq := +def contractFrames : LSpec.Spec := do let nat := Ix.Expr.mkConst (nm "Nat") #[] let lam := Ix.Expr.mkLam (nm "x") nat (.mkBVar 0) .default let pi := Ix.Expr.mkForallE (nm "x") nat nat .default @@ -225,38 +225,38 @@ def contractFrames : TestSeq := let misplaced := "semantic contract is not attached to its original binder" let key := Ix.Name.mkStr (nm "ix") "contract" let dag := Ix.Expr.mkApp (framed allC pi) (plain (framed lamC lam)) - test "a plain binder carries the never datum" - (binderOf (conv lam) == some { pw := .never }) ++ - test "an ordinary lam frame lowers to the plain binder" - (binderOf (conv (framed lamO lam)) == some { pw := .never }) ++ - test "an ordinary all frame lowers to the plain binder" - (binderOf (conv (framed allO pi)) == some { pw := .never }) ++ - test "a plain let carries Lean's nonDep" - (letOf (conv letE) == some { nonDep := false }) ++ - test "an ordinary let frame lowers to the plain let" - (letOf (conv (framed letO letE)) == some { nonDep := false }) ++ - test "plain metadata around an ordinary frame is erased" - (binderOf (conv (plain (framed lamO lam))) == some { pw := .never }) ++ - test "a valid annotated lam, all, let, field, or defAsserts frame lowers to the kernel term" + itBool "a plain binder carries the never datum" + (binderOf (conv lam) == some { pw := .never }) + itBool "an ordinary lam frame lowers to the plain binder" + (binderOf (conv (framed lamO lam)) == some { pw := .never }) + itBool "an ordinary all frame lowers to the plain binder" + (binderOf (conv (framed allO pi)) == some { pw := .never }) + itBool "a plain let carries Lean's nonDep" + (letOf (conv letE) == some { nonDep := false }) + itBool "an ordinary let frame lowers to the plain let" + (letOf (conv (framed letO letE)) == some { nonDep := false }) + itBool "plain metadata around an ordinary frame is erased" + (binderOf (conv (plain (framed lamO lam))) == some { pw := .never }) + itBool "a valid annotated lam, all, let, field, or defAsserts frame lowers to the kernel term" (binderOf (conv (framed lamC lam)) == some { pw := .never } && binderOf (conv (framed allC pi)) == some { pw := .never } && binderOf (conv (framed fieldC pi)) == some { pw := .never } && binderOf (conv (framed assertsC pi)) == some { pw := .never } && letOf (conv (framed letC letE)) == some { nonDep := false } && - binderOf (conv (plain (framed lamC lam))) == some { pw := .never }) ++ - test "a frame with reserved mode bits is refused" + binderOf (conv (plain (framed lamC lam))) == some { pw := .never }) + itBool "a frame with reserved mode bits is refused" (frameRefused (conv (Ix.Expr.mkMData #[(key, .ofNat 4), (Ix.Name.mkStr key "kind", .ofNat 0), - (Ix.Name.mkStr key "code", .ofNat 7)] lam))) ++ - test "a frame not directly around a binder of its kind is refused" + (Ix.Name.mkStr key "code", .ofNat 7)] lam))) + itBool "a frame not directly around a binder of its kind is refused" (refusedWith misplaced (conv (framed lamO (plain lam))) && refusedWith misplaced (conv (framed lamC pi)) && refusedWith misplaced (conv (framed allC nat)) && - refusedWith misplaced (conv (framed fieldC nat))) ++ - test "a malformed frame is refused" + refusedWith misplaced (conv (framed fieldC nat))) + itBool "a malformed frame is refused" (frameRefused (conv (Ix.Expr.mkMData #[(key, .ofNat 4)] lam)) && frameRefused (conv (Ix.Expr.mkMData #[(key, .ofNat 3), (Ix.Name.mkStr key "kind", .ofNat 0), - (Ix.Name.mkStr key "code", .ofNat 1)] lam))) ++ - test "the DAG walk is the tree walk on frames" + (Ix.Name.mkStr key "code", .ofNat 1)] lam))) + itBool "the DAG walk is the tree walk on frames" (sameTree (ingressExprsShared noParams.pos [dag]) (ingressExpr noParams.pos dag)) def sortOf : Except ExprError (List KExpr) → Option Ix.Kernel.Level @@ -265,15 +265,15 @@ def sortOf : Except ExprError (List KExpr) → Option Ix.Kernel.Level /-- Level parameters are positions: a constant's `i`-th is `i`, and a large eliminator's first, its elimination level, follows its block's. -/ -def numbering : TestSeq := +def numbering : LSpec.Spec := do let u := nm "u" let v := nm "v" let ty := Ix.Expr.mkSort (Ix.Level.mkMax (Ix.Level.mkParam u) (Ix.Level.mkParam v)) let large : Numbering := ⟨#[v, u], true⟩ - test "the i-th level parameter is position i" + itBool "the i-th level parameter is position i" (sortOf (ingressExprs (Numbering.mk #[u, v] false).pos [ty]) == - some (.max (.param 0) (.param 1))) ++ - test "a large eliminator's elimination level follows its block's parameters" + some (.max (.param 0) (.param 1))) + itBool "a large eliminator's elimination level follows its block's parameters" (sortOf (ingressExprs large.pos [ty]) == some (.max (.param 0) (.param 1)) && large.params == [1, 0]) @@ -282,7 +282,7 @@ reader reads a compiled universe: `Ixon.canonUniv` over the Lean index order (variable `i` is the constant's `i`-th Lean level parameter), back through `Reader.convUniv` (at a large eliminator through `Reader.recParam`, the elimination level first). -/ -def canonical : TestSeq := +def canonical : LSpec.Spec := do let u := nm "u" let v := nm "v" let plain : Numbering := ⟨#[u, v], false⟩ @@ -297,17 +297,17 @@ def canonical : TestSeq := (.max (.param 0) (.succ (.param 0)), .max (.var 0) (.succ (.var 0))), (.imax (.param 1) (.max (.param 0) (.param 1)), .imax (.var 1) (.max (.var 0) (.var 1))), (.succ (.max (.zero) (.param 1)), .succ (.max .zero (.var 1)))] - test "a member's level is the reader's reading of its compiled universe" - (cases.all fun (l, w) => canonLevel plain l == read (fun i => i) w) ++ - test "at a large eliminator the index order puts the elimination level first" + itBool "a member's level is the reader's reading of its compiled universe" + (cases.all fun (l, w) => canonLevel plain l == read (fun i => i) w) + itBool "at a large eliminator the index order puts the elimination level first" -- Source `max u v` is positions `max 0 1`; compiled, `u` is variable 1 (canonLevel large (.max (.param 0) (.param 1)) == read recP (.max (.var 1) (.var 0)) && - canonLevel large (.imax (.param 1) (.param 0)) == read recP (.imax (.var 0) (.var 1))) ++ - test "canonical forms do not depend on the order of a max" - (canonLevel plain (.max (.param 0) (.param 1)) == canonLevel plain (.max (.param 1) (.param 0))) ++ - test "canonicalizing is idempotent" - (cases.all fun (l, _) => canonLevel plain (canonLevel plain l) == canonLevel plain l) ++ - test "mapLevels' executed walk is the structural map" + canonLevel large (.imax (.param 1) (.param 0)) == read recP (.imax (.var 0) (.var 1))) + itBool "canonical forms do not depend on the order of a max" + (canonLevel plain (.max (.param 0) (.param 1)) == canonLevel plain (.max (.param 1) (.param 0))) + itBool "canonicalizing is idempotent" + (cases.all fun (l, _) => canonLevel plain (canonLevel plain l) == canonLevel plain l) + itBool "mapLevels' executed walk is the structural map" (let e : KExpr := .app (.sort (.max (.param 1) (.param 0))) (.const (ingressKey (nm "f")) [.max (.param 1) (.param 0)]) mapLevelsList (canonLevel plain) [e, e] == @@ -329,9 +329,9 @@ def agrees : Except ExprError (List KExpr) → Except ExprError KExpr → Bool | .ok [a], .ok b => decide (a = b) && treeSize b == 2 ^ 13 - 1 | _, _ => false -def sharing : TestSeq := - test "a 2^64-leaf DAG converts" ((ingressExprs noParams.pos [sharedDag 64]).isOk) ++ - test "the DAG walk is the tree walk at depth 12" +def sharing : LSpec.Spec := do + itBool "a 2^64-leaf DAG converts" ((ingressExprs noParams.pos [sharedDag 64]).isOk) + itBool "the DAG walk is the tree walk at depth 12" (agrees (ingressExprsShared noParams.pos [sharedDag 12]) (ingressExpr noParams.pos (sharedDag 12))) /-! ## The fixtures -/ @@ -401,12 +401,11 @@ def evaluate : IO (Array String × Array String) := do | .error e => errors := errors.push s!"checkSourceTiered on the accepted closure and spin: {e}" return (errors, lines) -def fixtures : TestSeq := - .individualIO "source mode: fixture closure, group by group and all at once" none (do +def fixtures : Spec := + it "source mode: fixture closure, group by group and all at once" do let (errors, lines) ← evaluate for l in lines do IO.println l - let msg := if errors.isEmpty then none else some ("\n".intercalate errors.toList) - return (errors.isEmpty, expected.length, 0, msg)) .done + expect errors.isEmpty ("\n".intercalate errors.toList) /-! ## Quotient Source @@ -586,12 +585,11 @@ def evaluateQuotient : IO (Array String × Array String) := do | .error e, _ => errors := errors.push s!"quotient: prelude check: {what}: {e}" return (errors, lines) -def quotient : TestSeq := - .individualIO "quotient source: alias fibers collapsed, mismatches refused, role aliases, canonical levels" none (do +def quotient : Spec := + it "quotient source: alias fibers collapsed, mismatches refused, role aliases, canonical levels" do let (errors, lines) ← evaluateQuotient for l in lines do IO.println l - let msg := if errors.isEmpty then none else some ("\n".intercalate errors.toList) - return (errors.isEmpty, 6, 0, msg)) .done + expect errors.isEmpty ("\n".intercalate errors.toList) /-! ## The `.indDecl` shape guard @@ -625,24 +623,24 @@ def withU : Ix.Kernel.Key .source → Option (Ix.Kernel.ConstantInfo .source) := def noneEnv : Ix.Kernel.Key .source → Option (Ix.Kernel.ConstantInfo .source) := fun _ => none -def shapeUnits : TestSeq := - test "a block naming only its formers passes" - (Ix.Kernel.indShapeOk noneEnv [sind "T" sty, sctor "T.a" (sconst "T"), sctor "T.b" (.app (sconst "T") (sconst "T"))]) $ - test "a mutual block's constructor may name another former" - (Ix.Kernel.indShapeOk noneEnv [sind "A" sty, sind "B" sty, sctor "A.a" (.app (sconst "A") (sconst "B"))]) $ - test "a constructor naming an earlier constructor is refused" - (!Ix.Kernel.indShapeOk noneEnv [sind "T" sty, sctor "T.a" (sconst "T"), sctor "T.b" (.app (sconst "T") (sconst "T.a"))]) $ - test "a constructor naming a later constructor is refused" - (!Ix.Kernel.indShapeOk noneEnv [sind "T" sty, sctor "T.a" (.app (sconst "T") (sconst "T.b")), sctor "T.b" (sconst "T")]) $ - test "a former naming an unknown constant is refused, and passes once it is declared" - (!Ix.Kernel.indShapeOk noneEnv [sind "T" (sconst "U")] && Ix.Kernel.indShapeOk withU [sind "T" (sconst "U")]) $ - test "a constructor name already declared is refused" - (!Ix.Kernel.indShapeOk withU [sind "T" sty, sctor "U" (sconst "T")]) $ - test "a constructor named as a former is refused" - (!Ix.Kernel.indShapeOk noneEnv [sind "T" sty, sctor "T" (sconst "T")]) $ - test "a constructor name declared twice is refused" - (!Ix.Kernel.indShapeOk noneEnv [sind "T" sty, sctor "T.a" (sconst "T"), sctor "T.a" (sconst "T")]) $ - test "a literal needs its support" +def shapeUnits : LSpec.Spec := do + itBool "a block naming only its formers passes" + (Ix.Kernel.indShapeOk noneEnv [sind "T" sty, sctor "T.a" (sconst "T"), sctor "T.b" (.app (sconst "T") (sconst "T"))]) + itBool "a mutual block's constructor may name another former" + (Ix.Kernel.indShapeOk noneEnv [sind "A" sty, sind "B" sty, sctor "A.a" (.app (sconst "A") (sconst "B"))]) + itBool "a constructor naming an earlier constructor is refused" + (!Ix.Kernel.indShapeOk noneEnv [sind "T" sty, sctor "T.a" (sconst "T"), sctor "T.b" (.app (sconst "T") (sconst "T.a"))]) + itBool "a constructor naming a later constructor is refused" + (!Ix.Kernel.indShapeOk noneEnv [sind "T" sty, sctor "T.a" (.app (sconst "T") (sconst "T.b")), sctor "T.b" (sconst "T")]) + itBool "a former naming an unknown constant is refused, and passes once it is declared" + (!Ix.Kernel.indShapeOk noneEnv [sind "T" (sconst "U")] && Ix.Kernel.indShapeOk withU [sind "T" (sconst "U")]) + itBool "a constructor name already declared is refused" + (!Ix.Kernel.indShapeOk withU [sind "T" sty, sctor "U" (sconst "T")]) + itBool "a constructor named as a former is refused" + (!Ix.Kernel.indShapeOk noneEnv [sind "T" sty, sctor "T" (sconst "T")]) + itBool "a constructor name declared twice is refused" + (!Ix.Kernel.indShapeOk noneEnv [sind "T" sty, sctor "T.a" (sconst "T"), sctor "T.a" (sconst "T")]) + itBool "a literal needs its support" (!Ix.Kernel.indShapeOk noneEnv [sind "T" sty, sctor "T.a" (.app (sconst "T") (.lit (.natVal 0)))]) /-! ## Repeated names in a lowered block @@ -669,12 +667,12 @@ def lowersTo (rb : Ix.Kernel.Reader.BlockRead .source) (ks : List String) : Bool | .ok r => r.decls.size == 1 && r.decls.toList.flatMap (·.names) == ks.map skey | .error _ => false -def repeatedNames : TestSeq := - test "a block with distinct names lowers to its declaration" - (lowersTo (blockWith ["T.a", "T.b"]) ["T", "T.a", "T.b"]) $ - test "a block declaring a constructor name twice is declined" - (declinesRepeat (blockWith ["T.a", "T.b", "T.a"]) "T.a") $ - test "a block naming a constructor as its type is declined" +def repeatedNames : LSpec.Spec := do + itBool "a block with distinct names lowers to its declaration" + (lowersTo (blockWith ["T.a", "T.b"]) ["T", "T.a", "T.b"]) + itBool "a block declaring a constructor name twice is declined" + (declinesRepeat (blockWith ["T.a", "T.b", "T.a"]) "T.a") + itBool "a block naming a constructor as its type is declined" (declinesRepeat (blockWith ["T"]) "T") /-- The lowered declarations with `Args.cons`'s declared type naming `Tm.var`. -/ @@ -712,14 +710,23 @@ def evaluateShape : IO (Array String × Array String) := do errors := errors.push s!"shape: refused, but not by the shape guard: {msg}" return (errors, lines) -def shapeGuard : TestSeq := - .individualIO "the shape guard refuses a modeled block's constructor naming an earlier one" none (do +def shapeGuard : Spec := + it "the shape guard refuses a modeled block's constructor naming an earlier one" do let (errors, lines) ← evaluateShape for l in lines do IO.println l - let msg := if errors.isEmpty then none else some ("\n".intercalate errors.toList) - return (errors.isEmpty, 2, 0, msg)) .done - -def suite : List TestSeq := [refusals, erasure, contractFrames, numbering, canonical, sharing, fixtures, - quotient, shapeUnits, repeatedNames, shapeGuard] + expect errors.isEmpty ("\n".intercalate errors.toList) + +def suite : LSpec.Spec := do + refusals + erasure + contractFrames + numbering + canonical + sharing + fixtures + quotient + shapeUnits + repeatedNames + shapeGuard end Tests.Ix.Kernel.SourceIngress diff --git a/Tests/Ix/Kernel/SourceIngressMain.lean b/Tests/Ix/Kernel/SourceIngressMain.lean index 0355003a80..dce8a00c80 100644 --- a/Tests/Ix/Kernel/SourceIngressMain.lean +++ b/Tests/Ix/Kernel/SourceIngressMain.lean @@ -75,7 +75,7 @@ partial def parse (a : Args) : List String → Except String Args def main (args : List String) : IO UInt32 := do if args == ["--fixture"] then - return ← LSpec.lspecIO (.ofList [("kernel-source-ingress", Tests.Ix.Kernel.SourceIngress.suite)]) [] + return ← LSpec.lspecMain (LSpec.describe "kernel-source-ingress" Tests.Ix.Kernel.SourceIngress.suite) [] let a ← IO.ofExcept (parse {} args) let modules := if a.modules.isEmpty then #[`Init] else a.modules let t0 ← IO.monoMsNow diff --git a/Tests/Ix/Kernel/TierInd.lean b/Tests/Ix/Kernel/TierInd.lean index f56c7bcdf0..0beebf4cb5 100644 --- a/Tests/Ix/Kernel/TierInd.lean +++ b/Tests/Ix/Kernel/TierInd.lean @@ -253,13 +253,13 @@ def evaluate : IO (Array String × Array String) := do (errors, lines) := expectDecline s!"Poly, {label} levels" bad fe₀ why errors lines return (errors, lines) -def tierInd : TestSeq := - .individualIO "the tier's typing-only inductive install and its answer view" none (do +def tierInd : Spec := + it "the tier's typing-only inductive install and its answer view" do let (errors, lines) ← evaluate for l in lines do IO.println l - let msg := if errors.isEmpty then none else some ("\n".intercalate errors.toList) - return (errors.isEmpty, lines.size, 0, msg)) .done + expect errors.isEmpty ("\n".intercalate errors.toList) -def suite : List TestSeq := [tierInd] +def suite : LSpec.Spec := do + tierInd end Tests.Ix.Kernel.TierInd diff --git a/Tests/Ix/Kernel/Tutorial.lean b/Tests/Ix/Kernel/Tutorial.lean index 3cade4f579..0146d60400 100644 --- a/Tests/Ix/Kernel/Tutorial.lean +++ b/Tests/Ix/Kernel/Tutorial.lean @@ -164,8 +164,8 @@ def rsCheckMalformedRecRuleIxonFFI | some (outcome, reason) => return some (.kernelException s!"{outcome}: {reason}") | none => return some (.kernelException s!"missing verdict for {recName}") -def testTutorialConsts : TestSeq := - .individualIO "kernel tutorial checks" none (do +def testTutorialConsts : Spec := + it "kernel tutorial checks" do let leanEnv ← get_env! let testCases := TutorialMeta.getTestCases leanEnv @@ -500,12 +500,9 @@ def testTutorialConsts : TestSeq := IO.println e IO.println s!"[kernel-tutorial] {passed} passed, {failed} failed" - if failed == 0 then - return (true, passed, 0, none) - else - return (false, passed, passed + failed, some s!"{failed} checks failed") - ) .done + expect (failed == 0) s!"{failed} checks failed" -def suite : List TestSeq := [testTutorialConsts] +def suite : LSpec.Spec := do + testTutorialConsts end Tests.Ix.Kernel.Tutorial diff --git a/Tests/Ix/Kernel/UserAxioms.lean b/Tests/Ix/Kernel/UserAxioms.lean index 1a5394668b..9001fedf2e 100644 --- a/Tests/Ix/Kernel/UserAxioms.lean +++ b/Tests/Ix/Kernel/UserAxioms.lean @@ -146,16 +146,12 @@ def gateChecks : Except String Unit := do (env.consts.length == env'.consts.length) | _, _ => throw "the prelude through the entry does not accept under both policies" -private def unit (label : String) (check : Unit → Except String Unit) : LSpec.TestSeq := - .individualIO label none (do - let result ← IO.lazyPure check - return match result with - | .ok _ => (true, 0, 0, none) - | .error message => (false, 0, 0, some message)) .done - -def suite : List LSpec.TestSeq := [ - unit "the fold under each axiom policy: user axioms, axiom role specifications, T1" (fun _ => foldChecks), +private def unit (label : String) (check : Unit → Except String Unit) : LSpec.Spec := + it label do + let _ ← LSpec.expectOk (check ()) + +def suite : LSpec.Spec := do + unit "the fold under each axiom policy: user axioms, axiom role specifications, T1" (fun _ => foldChecks) unit "the role table's admission under each axiom policy" (fun _ => gateChecks) -] end Tests.Ix.Kernel.UserAxioms diff --git a/Tests/Ix/Kernel/ValidateReaderCli.lean b/Tests/Ix/Kernel/ValidateReaderCli.lean index 6567eb5719..f3e1a40015 100644 --- a/Tests/Ix/Kernel/ValidateReaderCli.lean +++ b/Tests/Ix/Kernel/ValidateReaderCli.lean @@ -135,9 +135,8 @@ private def check : IO Nat := do {report.constants} direct source comparisons and visible expected declines" return 12 -def suite : List TestSeq := [ - .individualIO "validate-lean source fidelity keeps coverage, declines, failures and lazy/eager reports" none (do - let n ← check - return (true, n, 0, none)) .done] +def suite : LSpec.Spec := do + it "validate-lean source fidelity keeps coverage, declines, failures and lazy/eager reports" do + let _ ← check end Tests.Ix.Kernel.ValidateReaderCli diff --git a/Tests/Ix/LeanExport.lean b/Tests/Ix/LeanExport.lean index 8e27ec9493..71caa3539e 100644 --- a/Tests/Ix/LeanExport.lean +++ b/Tests/Ix/LeanExport.lean @@ -37,6 +37,9 @@ public section namespace Tests.Ix.LeanExport open _root_.Ix.LeanExport (importString environment) +open LSpec + +set_option compiler.extract_closed false private def require (ok : Bool) (message : String) : IO Unit := unless ok do throw (IO.userError message) @@ -62,43 +65,43 @@ private def withMData (data : String) : String := export_ ["{\"ie\":1,\"mdata\":{\"data\":" ++ data ++ ",\"expr\":0}}"] "{\"axiom\":{\"isUnsafe\":false,\"levelParams\":[],\"name\":1,\"type\":1}}" -def readerTests : LSpec.TestSeq := +def readerTests : LSpec.Spec := do let dropped (text : String) : Option Nat := (importString text).toOption.map (·.droppedSyntaxMData) - LSpec.test "a well-formed export is read" ((importString (export_ [])).toOption.any fun im => - im.constants.size == 1 && im.exportMeta.leanVersion == "4.34.1") ++ - LSpec.test "another format version is refused" (refuses ((export_ []).replace metaLine (metaLine "3.0.0"))) ++ - LSpec.test "an export without its meta record is refused" - (refuses ("\n".intercalate ((export_ []).splitOn "\n" |>.drop 1))) ++ - LSpec.test "a second meta record is refused" (refuses (export_ [metaLine])) ++ - LSpec.test "a name index out of sequence is refused" - (refuses (export_ ["{\"in\":3,\"str\":{\"pre\":0,\"str\":\"U\"}}"])) ++ - LSpec.test "a reference to an expression not yet defined is refused" - (refuses (export_ [] "{\"axiom\":{\"isUnsafe\":false,\"levelParams\":[],\"name\":1,\"type\":7}}")) ++ - LSpec.test "an extra field is refused" - (refuses (export_ [] "{\"axiom\":{\"isUnsafe\":false,\"levelParams\":[],\"name\":1,\"type\":0,\"x\":1}}")) ++ - LSpec.test "a missing field is refused" - (refuses (export_ [] "{\"axiom\":{\"levelParams\":[],\"name\":1,\"type\":0}}")) ++ - LSpec.test "a name declared twice is refused" - (refuses (export_ ["{\"axiom\":{\"isUnsafe\":false,\"levelParams\":[],\"name\":1,\"type\":0}}"])) ++ - LSpec.test "an unknown record is refused" (refuses (export_ ["{\"universe\":0}"])) ++ - LSpec.test "an unknown binder info is refused" - (refuses (export_ ["{\"ie\":1,\"lam\":{\"binderInfo\":\"auto\",\"body\":0,\"name\":1,\"type\":0}}"])) ++ - LSpec.test "a canonical numeral is read" - (accepts (export_ ["{\"ie\":1,\"natVal\":\"120\"}"])) ++ - LSpec.test "a numeral that is not canonical is refused" - (refuses (export_ ["{\"ie\":1,\"natVal\":\"0120\"}"])) ++ - LSpec.test "a metadata value that reads back is kept" - (dropped (withMData "{\"noImplicitLambda\":\"Lean.DataValue.ofBool true\"}") == some 0) ++ - LSpec.test "a name-valued metadata entry is kept" - (dropped (withMData "{\"k\":\"Lean.DataValue.ofName `Nat.add\"}") == some 0) ++ - LSpec.test "a name written in constructor form is kept" + itBool "a well-formed export is read" ((importString (export_ [])).toOption.any fun im => + im.constants.size == 1 && im.exportMeta.leanVersion == "4.34.1") + itBool "another format version is refused" (refuses ((export_ []).replace metaLine (metaLine "3.0.0"))) + itBool "an export without its meta record is refused" + (refuses ("\n".intercalate ((export_ []).splitOn "\n" |>.drop 1))) + itBool "a second meta record is refused" (refuses (export_ [metaLine])) + itBool "a name index out of sequence is refused" + (refuses (export_ ["{\"in\":3,\"str\":{\"pre\":0,\"str\":\"U\"}}"])) + itBool "a reference to an expression not yet defined is refused" + (refuses (export_ [] "{\"axiom\":{\"isUnsafe\":false,\"levelParams\":[],\"name\":1,\"type\":7}}")) + itBool "an extra field is refused" + (refuses (export_ [] "{\"axiom\":{\"isUnsafe\":false,\"levelParams\":[],\"name\":1,\"type\":0,\"x\":1}}")) + itBool "a missing field is refused" + (refuses (export_ [] "{\"axiom\":{\"levelParams\":[],\"name\":1,\"type\":0}}")) + itBool "a name declared twice is refused" + (refuses (export_ ["{\"axiom\":{\"isUnsafe\":false,\"levelParams\":[],\"name\":1,\"type\":0}}"])) + itBool "an unknown record is refused" (refuses (export_ ["{\"universe\":0}"])) + itBool "an unknown binder info is refused" + (refuses (export_ ["{\"ie\":1,\"lam\":{\"binderInfo\":\"auto\",\"body\":0,\"name\":1,\"type\":0}}"])) + itBool "a canonical numeral is read" + (accepts (export_ ["{\"ie\":1,\"natVal\":\"120\"}"])) + itBool "a numeral that is not canonical is refused" + (refuses (export_ ["{\"ie\":1,\"natVal\":\"0120\"}"])) + itBool "a metadata value that reads back is kept" + (dropped (withMData "{\"noImplicitLambda\":\"Lean.DataValue.ofBool true\"}") == some 0) + itBool "a name-valued metadata entry is kept" + (dropped (withMData "{\"k\":\"Lean.DataValue.ofName `Nat.add\"}") == some 0) + itBool "a name written in constructor form is kept" (dropped (withMData ("{\"k\":" ++ (Lean.Json.str (reprStr (Lean.DataValue.ofName - (.num (.str (.num `h 4) "_hyg") 17)))).compress ++ "}")) == some 0) ++ - LSpec.test "a syntax-valued metadata entry is dropped and counted" - (dropped (withMData "{\"_recApp\":\"Lean.DataValue.ofSyntax\\n (Lean.Syntax.missing)\"}") == some 1) ++ - LSpec.test "a metadata value that does not read back is refused" - (refuses (withMData "{\"k\":\"Lean.DataValue.ofBool maybe\"}")) ++ - LSpec.test "a metadata value in another form is refused" + (.num (.str (.num `h 4) "_hyg") 17)))).compress ++ "}")) == some 0) + itBool "a syntax-valued metadata entry is dropped and counted" + (dropped (withMData "{\"_recApp\":\"Lean.DataValue.ofSyntax\\n (Lean.Syntax.missing)\"}") == some 1) + itBool "a metadata value that does not read back is refused" + (refuses (withMData "{\"k\":\"Lean.DataValue.ofBool maybe\"}")) + itBool "a metadata value in another form is refused" (refuses (withMData "{\"k\":\"Lean.DataValue.ofNat 3\"}")) /-! ## Fidelity on ix's own toolchain -/ @@ -164,17 +167,17 @@ def compileBound (env : Lean.Environment) : IO Ixon.Env := do Ix.RoleBinding.Compile.finalize (Ix.RoleBinding.Compile.certifiedBackend 8) env (pure env) input out.env Ix.Typing.typingLimits out.existing? -def fidelity : IO (Bool × Nat × Nat × Option String) := do - let exported ← IO.ofExcept (importString (← readFixture Lean.versionString)) - require (exported.exportMeta.leanVersion == Lean.versionString) +def fidelity : AssertM Unit := do + let exported ← expectOk (importString (← readFixture Lean.versionString)) + expect (exported.exportMeta.leanVersion == Lean.versionString) s!"the fixture comes from Lean {exported.exportMeta.leanVersion}, the test runs on {Lean.versionString}" let native ← getCompileEnv #[`IxCK.Kernel.PinGen.Certs, `Tests.Fixtures.toolchains.Primitives] let mut nativeDecls : Array (Lean.Name × Lean.ConstantInfo) := #[] let mut binderDiffs := 0 for (name, ci) in exported.constants do let some nci := native.find? name - | throw (IO.userError s!"{name} is exported but not in the native environment") - require (sameDeclaration ci nci) s!"{name}: the exported declaration differs from the native one" + | fail s!"{name} is exported but not in the native environment" + expect (sameDeclaration ci nci) s!"{name}: the exported declaration differs from the native one" unless sameBinders ci nci do binderDiffs := binderDiffs + 1 nativeDecls := nativeDecls.push (name, nci) let fromNative ← compileBound (← environment nativeDecls) @@ -184,9 +187,8 @@ def fidelity : IO (Bool × Nat × Nat × Option String) := do IO.println s!"[lean-export] {exported.constants.size} declarations; {binderDiffs} differ from the \ native ones in binder names or info; {exported.droppedSyntaxMData} syntax-valued metadata entries dropped" for line in report do IO.println s!"[lean-export] {line}" - require fromNative.roleBinding.isSome "the native compile has no role binding" - require c.contentExact s!"the export's compile differs in content: {report}" - return (true, 0, 0, none) + expect fromNative.roleBinding.isSome "the native compile has no role binding" + expect c.contentExact s!"the export's compile differs in content: {report}" /-! ## Another toolchain's roles -/ @@ -201,45 +203,43 @@ its `Nat.xor` does too. is finalized. Its binding binds the role at the address the export publishes it at, which is not the default table's. `finalize`'s own check of the published role names against that binding passed. -/ -def foreignRoles (version : String) (role : _root_.Ix.Kernel.Role) : - IO (Bool × Nat × Nat × Option String) := do - let exported ← IO.ofExcept (importString (← readFixture version)) +def foreignRoles (version : String) (role : _root_.Ix.Kernel.Role) : AssertM Unit := do + let exported ← expectOk (importString (← readFixture version)) let env ← environment exported.constants let constants := env.constants.toList match ← Ix.CompileM.compileCertified env constants 8 with | .ok _ => - throw (IO.userError s!"{version}: the compile at the default role table accepted {repr role}") + fail s!"{version}: the compile at the default role table accepted {repr role}" | .error e => - require (e.startsWith "role check failed") s!"{version}: refused for another reason: {e}" + expect (e.startsWith "role check failed") s!"{version}: refused for another reason: {e}" let artifact ← match ← Ix.CompileM.compileAndFinalize env constants 8 (allowPartial := false) (certSource := pure env) (defaultRoles := false) with | .ok (_, .done artifact _) => pure artifact | .ok (out, .refused) => - throw (IO.userError s!"{version}: {out.failures.toMap.size} constants failed to compile") - | .ok (_, .failed e) => throw (IO.userError s!"{version}: finalization failed: {e}") - | .error e => throw (IO.userError s!"{version}: the compile failed: {e}") + fail s!"{version}: {out.failures.toMap.size} constants failed to compile" + | .ok (_, .failed e) => fail s!"{version}: finalization failed: {e}" + | .error e => fail s!"{version}: the compile failed: {e}" let some binding := artifact.roleBinding - | throw (IO.userError s!"{version}: the artifact carries no role binding") + | fail s!"{version}: the artifact carries no role binding" let some table := _root_.Ix.Kernel.RoleTable.ofBytes binding.bytes - | throw (IO.userError s!"{version}: the role binding does not decode") - let published := (← IO.ofExcept (_root_.Ix.RoleBinding.sourceAddresses artifact))[role.leanName]? + | fail s!"{version}: the role binding does not decode" + let published := (← expectOk (_root_.Ix.RoleBinding.sourceAddresses artifact))[role.leanName]? let atDefault := (_root_.Ix.Cert.roleTableBound.find? (·.1 == role)).map (·.2) - require (published.isSome && table.addressOf? role == published) + expect (published.isSome && table.addressOf? role == published) s!"{version}: {repr role} is published at {published}, bound at {table.addressOf? role}" - require (published != atDefault) + expect (published != atDefault) s!"{version}: {repr role} is published at the default table's address {atDefault}" IO.println s!"[lean-export] {version}: {repr role} bound at {published}; the default table \ binds it at {atDefault}" - return (true, 0, 0, none) - -def suite : List LSpec.TestSeq := [ - readerTests, - .individualIO "a 4.34.1 export compiles to exactly the native content, role binding included" none - fidelity .done, - .individualIO "a 4.35.0 export binds its own Int.decLt, which the default role table refuses" - none (foreignRoles "4.35.0" .intDecLt) .done, - .individualIO "a 4.33.1 export binds its own Nat.xor, which the default role table refuses" - none (foreignRoles "4.33.1" .natXor) .done] + +def suite : LSpec.Spec := do + readerTests + it "a 4.34.1 export compiles to exactly the native content, role binding included" + fidelity + it "a 4.35.0 export binds its own Int.decLt, which the default role table refuses" + (foreignRoles "4.35.0" .intDecLt) + it "a 4.33.1 export binds its own Nat.xor, which the default role table refuses" + (foreignRoles "4.33.1" .natXor) end Tests.Ix.LeanExport diff --git a/Tests/Ix/Merkle.lean b/Tests/Ix/Merkle.lean index 969df07834..61301f7269 100644 --- a/Tests/Ix/Merkle.lean +++ b/Tests/Ix/Merkle.lean @@ -10,109 +10,113 @@ public import LSpec open LSpec open Ix.Merkle +set_option compiler.extract_closed false + private def addr (seed : String) : Address := Address.blake3 seed.toUTF8 /-! ## Canonical builder -/ -private def canonicalUnits : TestSeq := - let a := addr "a" - let b := addr "b" - let c := addr "c" - test "canonical_empty → none" (merkleRootCanonical #[] == none) - ++ test "canonical_single = leafHash" - (merkleRootCanonical #[a] == some (leafHash a)) - ++ test "canonical_sort_invariant [a,b] = [b,a]" - (merkleRootCanonical #[a, b] == merkleRootCanonical #[b, a]) - ++ test "canonical_dedup [a,a,b] = [a,b]" - (merkleRootCanonical #[a, a, b] == merkleRootCanonical #[a, b]) - ++ test "canonical_distinguishes [a] ≠ [a,b]" - (!(merkleRootCanonical #[a] == merkleRootCanonical #[a, b])) - ++ test "canonical_three_leaves nonempty" - ((merkleRootCanonical #[a, b, c]).isSome) - ++ test "canonical_no_malleability" - -- [a, a] post-dedup is [a], yielding leafHash a. - -- A two-leaf tree node_hash(leaf_hash(a), leaf_hash(a)) is different. - (merkleRootCanonical #[a, a] - == some (leafHash a) - && !(merkleRootCanonical #[a, a] - == some (nodeHash (leafHash a) (leafHash a)))) +private def canonicalUnits : LSpec.Spec := do + itBool "canonical_empty → none" (merkleRootCanonical #[] == none) + itBool "canonical_single = leafHash" + (let a := addr "a"; merkleRootCanonical #[a] == some (leafHash a)) + itBool "canonical_sort_invariant [a,b] = [b,a]" + (let a := addr "a"; let b := addr "b" + merkleRootCanonical #[a, b] == merkleRootCanonical #[b, a]) + itBool "canonical_dedup [a,a,b] = [a,b]" + (let a := addr "a"; let b := addr "b" + merkleRootCanonical #[a, a, b] == merkleRootCanonical #[a, b]) + itBool "canonical_distinguishes [a] ≠ [a,b]" + (let a := addr "a"; let b := addr "b" + !(merkleRootCanonical #[a] == merkleRootCanonical #[a, b])) + itBool "canonical_three_leaves nonempty" + (let a := addr "a"; let b := addr "b"; let c := addr "c" + (merkleRootCanonical #[a, b, c]).isSome) + itBool "canonical_no_malleability" + -- [a, a] post-dedup is [a], yielding leafHash a. + -- A two-leaf tree node_hash(leaf_hash(a), leaf_hash(a)) is different. + (let a := addr "a" + merkleRootCanonical #[a, a] == some (leafHash a) + && !(merkleRootCanonical #[a, a] == some (nodeHash (leafHash a) (leafHash a)))) /-! ## Domain separation -/ -private def domainSepUnits : TestSeq := - let a := addr "a" - test "leaf_vs_node_disjoint" - (!(leafHash a == nodeHash a zeroAddress)) +private def domainSepUnits : LSpec.Spec := do + itBool "leaf_vs_node_disjoint" + (let a := addr "a"; !(leafHash a == nodeHash a zeroAddress)) /-! ## Free-form (merkleJoin) -/ -private def joinUnits : TestSeq := - let a := addr "a" - let b := addr "b" - let c := addr "c" - test "join_is_node_hash" (merkleJoin a b == nodeHash a b) - ++ test "join_non_commutative" (!(merkleJoin a b == merkleJoin b a)) - ++ test "join_canonical_inequal" - -- Free-form tree of {a,b}{c} ≠ canonical tree of {a,b,c}. - (let left := (merkleRootCanonical #[a, b]).get! - let right := (merkleRootCanonical #[c]).get! - let joined := merkleJoin left right - let canon := (merkleRootCanonical #[a, b, c]).get! - !(joined == canon)) +private def joinUnits : LSpec.Spec := do + itBool "join_is_node_hash" + (let a := addr "a"; let b := addr "b"; merkleJoin a b == nodeHash a b) + itBool "join_non_commutative" + (let a := addr "a"; let b := addr "b"; !(merkleJoin a b == merkleJoin b a)) + itBool "join_canonical_inequal" + -- Free-form tree of {a,b}{c} ≠ canonical tree of {a,b,c}. + (let a := addr "a"; let b := addr "b"; let c := addr "c" + let left := (merkleRootCanonical #[a, b]).get! + let right := (merkleRootCanonical #[c]).get! + let joined := merkleJoin left right + let canon := (merkleRootCanonical #[a, b, c]).get! + !(joined == canon)) /-! ## Membership proofs -/ -private def membershipUnits : TestSeq := - let a := addr "a" - let b := addr "b" - let c := addr "c" - let leaves := #[a, b, c] - let root := (merkleRootCanonical leaves).get! - test "proof_single_leaf empty path" - ((merkleProofCanonical #[a] a).get!.isEmpty - && verifyMerkleProof (leafHash a) a #[]) - ++ test "proof_two_leaves roundtrip" - (let leaves := #[a, b] - let root := (merkleRootCanonical leaves).get! - let path_a := (merkleProofCanonical leaves a).get! - let path_b := (merkleProofCanonical leaves b).get! - verifyMerkleProof root a path_a && verifyMerkleProof root b path_b) - ++ test "proof_three_leaves all members" - (let path_a := (merkleProofCanonical leaves a).get! - let path_b := (merkleProofCanonical leaves b).get! - let path_c := (merkleProofCanonical leaves c).get! - verifyMerkleProof root a path_a - && verifyMerkleProof root b path_b - && verifyMerkleProof root c path_c) - ++ test "proof_rejects_nonmember_direct" - ((merkleProofCanonical #[a, b] (addr "x")) == none) +private def membershipUnits : LSpec.Spec := do + itBool "proof_single_leaf empty path" + (let a := addr "a" + (merkleProofCanonical #[a] a).get!.isEmpty + && verifyMerkleProof (leafHash a) a #[]) + itBool "proof_two_leaves roundtrip" + (let a := addr "a"; let b := addr "b" + let leaves := #[a, b] + let root := (merkleRootCanonical leaves).get! + let path_a := (merkleProofCanonical leaves a).get! + let path_b := (merkleProofCanonical leaves b).get! + verifyMerkleProof root a path_a && verifyMerkleProof root b path_b) + itBool "proof_three_leaves all members" + (let a := addr "a"; let b := addr "b"; let c := addr "c" + let leaves := #[a, b, c] + let root := (merkleRootCanonical leaves).get! + let path_a := (merkleProofCanonical leaves a).get! + let path_b := (merkleProofCanonical leaves b).get! + let path_c := (merkleProofCanonical leaves c).get! + verifyMerkleProof root a path_a + && verifyMerkleProof root b path_b + && verifyMerkleProof root c path_c) + itBool "proof_rejects_nonmember_direct" + (let a := addr "a"; let b := addr "b" + (merkleProofCanonical #[a, b] (addr "x")) == none) /-! ## Join composes membership -/ -private def joinMembershipUnits : TestSeq := - let a := addr "a" - let b := addr "b" - let c := addr "c" - let leftLeaves := #[a, b] - let rightLeaves := #[c] - let leftRoot := (merkleRootCanonical leftLeaves).get! - let rightRoot := (merkleRootCanonical rightLeaves).get! - let joined := merkleJoin leftRoot rightRoot - test "join_composes_left" - (let path := (merkleProofCanonical leftLeaves a).get! +private def joinMembershipUnits : LSpec.Spec := do + itBool "join_composes_left" + (let a := addr "a"; let b := addr "b"; let c := addr "c" + let leftLeaves := #[a, b] + let rightLeaves := #[c] + let leftRoot := (merkleRootCanonical leftLeaves).get! + let rightRoot := (merkleRootCanonical rightLeaves).get! + let joined := merkleJoin leftRoot rightRoot + let path := (merkleProofCanonical leftLeaves a).get! verifyMerkleProof joined a (path.push (rightRoot, false))) - ++ test "join_composes_right" - (let path := (merkleProofCanonical rightLeaves c).get! - verifyMerkleProof joined c (path.push (leftRoot, true))) + itBool "join_composes_right" + (let a := addr "a"; let b := addr "b"; let c := addr "c" + let leftLeaves := #[a, b] + let rightLeaves := #[c] + let leftRoot := (merkleRootCanonical leftLeaves).get! + let rightRoot := (merkleRootCanonical rightLeaves).get! + let joined := merkleJoin leftRoot rightRoot + let path := (merkleProofCanonical rightLeaves c).get! + verifyMerkleProof joined c (path.push (leftRoot, true))) /-! ## Suite -/ -public def Tests.Merkle.suite : List TestSeq := [ - canonicalUnits, - domainSepUnits, - joinUnits, - membershipUnits, - joinMembershipUnits, -] - +public def Tests.Merkle.suite : LSpec.Spec := do + canonicalUnits + domainSepUnits + joinUnits + membershipUnits + joinMembershipUnits diff --git a/Tests/Ix/MetaEnv.lean b/Tests/Ix/MetaEnv.lean index d351c7e958..31395c0e80 100644 --- a/Tests/Ix/MetaEnv.lean +++ b/Tests/Ix/MetaEnv.lean @@ -40,21 +40,20 @@ private def constKind : Lean.ConstantInfo → String | .inductInfo _ => "an inductive" | .ctorInfo _ => "a constructor" | .recInfo _ => "a recursor" | .quotInfo _ => "a quotient primitive" -/-- Load a tmpdir fixture with `getFileEnvCore` and run `check` on the result -(the fixture file is gone by the time the TestSeq is folded, so checks run -eagerly here). -/ +/-- Load a tmpdir fixture with `getFileEnvCore` and run `check` on the result. -/ private def withFixture (name source : String) - (check : FilePath → FileEnv → IO (Bool × Option String)) - : IO (Bool × Nat × Nat × Option String) := do + (check : FilePath → FileEnv → AssertM Unit) : AssertM Unit := do let dir ← IO.FS.createTempDir let path := dir / name IO.FS.writeFile path source try - let fe ← getFileEnvCore path - let (ok, err?) ← check path fe - return (ok, 0, 0, err?) - catch e => - return (false, 0, 0, some s!"getFileEnvCore failed: {e}") + let feRes : Except String FileEnv ← liftM (m := IO) do + try + pure (.ok (← getFileEnvCore path)) + catch e => + pure (.error s!"getFileEnvCore failed: {e}") + let fe ← expectOk feRes + check path fe finally IO.FS.removeDirAll dir @@ -82,56 +81,51 @@ private def checkFullContent (env : Lean.Environment) (marker : Lean.Name) | some ci => some s!"Nat.add_comm is {constKind ci}, expected a theorem with a proof" | none => some "Nat.add_comm missing from env" -def moduleFileTest : TestSeq := - .individualIO "module header: full content + isModule flag" none - (withFixture "ModFixture.lean" moduleSource fun _ fe => do - if !fe.isModule then - return (false, some "isModule = false for a `module` header") +def moduleFileTest : LSpec.Spec := do + it "module header: full content + isModule flag" do + withFixture "ModFixture.lean" moduleSource fun _ fe => do + expect fe.isModule "isModule = false for a `module` header" -- The env must also carry private transitive imports (absent entirely -- at exported level). let privCount := fe.env.constants.toList.countP fun (n, _) => isPrivateName n - if privCount == 0 then - return (false, some "no _private.* constants — exported-level trim suspected") - match checkFullContent fe.env `TestsMetaEnv.modMarker with - | some e => return (false, some e) - | none => return (true, none)) .done - -def classicFileTest : TestSeq := - .individualIO "classic header: full content + isModule flag" none - (withFixture "ClassicFixture.lean" classicSource fun _ fe => do - if fe.isModule then - return (false, some "isModule = true for a classic header") - match checkFullContent fe.env `TestsMetaEnv.classicMarker with - | some e => return (false, some e) - | none => return (true, none)) .done + expect (privCount != 0) "no _private.* constants — exported-level trim suspected" + if let some e := checkFullContent fe.env `TestsMetaEnv.modMarker then + fail e + +def classicFileTest : LSpec.Spec := do + it "classic header: full content + isModule flag" do + withFixture "ClassicFixture.lean" classicSource fun _ fe => do + expectFalse fe.isModule "isModule = true for a classic header" + if let some e := checkFullContent fe.env `TestsMetaEnv.classicMarker then + fail e /-- Scoping: `defaultConstList` on a module-mode file must (a) keep the file's own definitions, (b) keep module-visible imports, (c) pull in referenced `_private.*` proof auxiliaries through the closure — with their full-content `ConstantInfo`s (theorems stay theorems) — and (d) still exclude some of the full env (the unreferenced foreign privates the `module` header conceals). -/ -def scopedListTest : TestSeq := - .individualIO "module header: defaultConstList scopes names, not content" none - (withFixture "ScopeFixture.lean" moduleSource fun path fe => do +def scopedListTest : LSpec.Spec := do + it "module header: defaultConstList scopes names, not content" do + withFixture "ScopeFixture.lean" moduleSource fun path fe => do let closed ← defaultConstList fe path.toString let full := fe.env.constants.toList.length let names : Std.HashSet Lean.Name := .ofList (closed.map (·.1)) - if !names.contains `TestsMetaEnv.modMarker then - return (false, some "local definition missing from scoped list") + expect (names.contains `TestsMetaEnv.modMarker) + "local definition missing from scoped list" let addComm := closed.find? fun (n, _) => n == `Nat.add_comm match addComm with | some (_, .thmInfo _) => pure () | some (_, ci) => - return (false, some s!"scoped Nat.add_comm is {constKind ci}, expected a theorem") - | none => return (false, some "Nat.add_comm missing from scoped list") + fail s!"scoped Nat.add_comm is {constKind ci}, expected a theorem" + | none => fail "Nat.add_comm missing from scoped list" let privCount := closed.countP fun (n, _) => isPrivateName n - if privCount == 0 then - return (false, some "closure pulled in no _private.* proof auxiliaries") - if closed.length ≥ full then - return (false, some s!"scoped list ({closed.length}) does not exclude \ -anything from the full env ({full})") - return (true, none)) .done - -def suite : List TestSeq := [moduleFileTest, classicFileTest, scopedListTest] + expect (privCount != 0) "closure pulled in no _private.* proof auxiliaries" + expect (decide (closed.length < full)) + s!"scoped list ({closed.length}) does not exclude anything from the full env ({full})" + +def suite : LSpec.Spec := do + moduleFileTest + classicFileTest + scopedListTest end Tests.Ix.MetaEnv diff --git a/Tests/Ix/MultiStarkVerifier.lean b/Tests/Ix/MultiStarkVerifier.lean index 70b0d58a56..497b1a15a2 100644 --- a/Tests/Ix/MultiStarkVerifier.lean +++ b/Tests/Ix/MultiStarkVerifier.lean @@ -7,6 +7,8 @@ import Ix.Cert.MultiStark.Wire import Ix.Cert.MultiStark.Transcript import Ix.Cert.MultiStark.Preamble import Ix.Cert.MultiStark.Verifier +import Ix.Cert.MultiStark.StarkKey +import Ix.Cert.MultiStark.PinnedVerifier /-! # Protocol v6 ($\mathbb{F}_{p^3}$) Aiur Recursive Verifier Cross-Language Fixture Tests @@ -103,20 +105,35 @@ private def fixtures : List (String × System.FilePath × Bool) := [ ("prep_first", "Tests/Fixtures/MultiStark/prep_first", false) ] -/-- Every committed fixture key decodes under `StarkSystem.fromBytes` and satisfies the full -production static check (`Ix.Cert.MultiStark.checkSystem`), matching the security floor and -structural invariants enforced in-circuit by `MultiStark.recursionProgram`. -/ -def admissibilitySuite : IO (List TestSeq) := do - let mut tests : TestSeq := .done - for (name, dir, _) in fixtures do +/-- Strip the 2-byte `stage_1_pinning` field (offset 52..54) from a pinned Protocol `v6` key +so legacy unpinned `StarkSystem.fromBytes` unit tests can exercise their structural invariants +against the committed fixtures without duplicating fixture binaries. -/ +private def stripStage1Pinning (sys : ByteArray) : ByteArray := + if sys.size ≥ 54 then + sys.extract 0 52 ++ sys.extract 54 sys.size + else + sys + +/-- Every committed fixture key validates under `StarkKey.validateV6` (enforcing `stage_1_pinning = 1` +and the Release 0.5 security floor) and decodes under `CertiFri.P3.Wire.decodeKey`, matching the +security floor and structural invariants enforced in-circuit by `MultiStark.recursionProgram`. -/ +def admissibilitySuite : IO Spec := do + let loaded ← fixtures.mapM fun (name, dir, _) => do let sys ← IO.FS.readBinFile (dir / "system.bin") - match Ix.Cert.MultiStark.StarkSystem.fromBytes sys with - | .ok s => - tests := tests ++ test s!"{name}: key decodes and satisfies checkSystem" - (Ix.Cert.MultiStark.checkSystem s) - | .error e => - tests := tests ++ test s!"{name}: Lean decoder accepts the fixture key ({e})" false - return [tests] + return (name, sys) + return do + for (name, sys) in loaded do + match Ix.Cert.MultiStark.StarkKey.validateV6 sys with + | .ok _ => + itBool s!"{name}: key passes StarkKey.validateV6 (stage_1_pinning = 1 + floor)" true + | .error e => + itBool s!"{name}: StarkKey.validateV6 accepts the fixture key ({e})" false + match CertiFri.P3.Wire.decodeKey sys with + | some k => + itBool s!"{name}: CertiFri.P3.Wire.decodeKey sets stage1Pinning = true" + k.params.stage1Pinning + | none => + itBool s!"{name}: CertiFri.P3.Wire.decodeKey accepts the fixture key" false section DecoderParity @@ -215,339 +232,342 @@ private def expectOkCheck (bytes : ByteArray) (pred : StarkSystem → Bool) : Bo /-- Parity and negative-control suite for the Lean verifying-key decoder (`StarkSystem.fromBytes`), static system validator (`checkSystem` / `checkSystemWithFloor`), transcript shape binding (`observeShape`), and executable `LookupsPlain` checker (`checkLookupsPlain`). -/ -def decoderParitySuite : IO (List TestSeq) := do - let mut tests : TestSeq := .done - - -- 1. Positive checks on all 5 real Rust fixtures (including `prep_first`) - for (name, dir, hasInactivePrep) in fixtures do +def decoderParitySuite : IO Spec := do + let fixtureData ← fixtures.mapM fun (name, dir, hasInactivePrep) => do let sysBytes ← IO.FS.readBinFile (dir / "system.bin") let clmBytes ← IO.FS.readBinFile (dir / "claims.bin") let prfBytes ← IO.FS.readBinFile (dir / "proof.bin") - match StarkSystem.fromBytes sysBytes with - | .error e => - tests := tests ++ test s!"{name}: StarkSystem.fromBytes accepts fixture ({e})" false - | .ok s => - tests := tests ++ test s!"{name}: toBytes round-trips byte-identically" - (s.toBytes == sysBytes) - tests := tests ++ test s!"{name}: vkDigest matches recomputed computeVkDigest" - (s.vkDigest == computeVkDigest s.circuits) - tests := tests ++ test s!"{name}: passes checkSystemWithFloor(allowBelowFloor=true)" - (checkSystemWithFloor s true) - tests := tests ++ test s!"{name}: all circuits pass checkLookupsPlain" - (s.circuits.all checkLookupsPlain) - let sFloor := { s with params := floorParams } - tests := tests ++ test s!"{name}: passes StarkSystem.fromBytes and checkSystem at production floor" - (expectOkCheck sFloor.toBytes fun s2 => checkSystem s2 && s2 == sFloor) - tests := tests ++ test s!"{name}: verifyBatchBytesWithFloor matches expected acceptance" - (verifyBatchBytesWithFloor sysBytes clmBytes prfBytes none true hasInactivePrep) + return (name, hasInactivePrep, sysBytes, clmBytes, prfBytes) + let baseRawBytes ← IO.FS.readBinFile (System.FilePath.mk "Tests/Fixtures/MultiStark" / "system.bin") + let baseBytes := stripStage1Pinning baseRawBytes + return do + -- 1. Positive checks on all 5 real Rust pinned fixtures (including `prep_first`) + for (name, hasInactivePrep, sysBytes, clmBytes, prfBytes) in fixtureData do + itBool s!"{name}: PinnedVerifier.verifyBytesPinnedIx matches expected acceptance" + (Ix.Cert.MultiStark.PinnedVerifier.verifyBytesPinnedIx sysBytes clmBytes prfBytes true hasInactivePrep) if hasInactivePrep then - tests := tests ++ test s!"{name}: strict active-preprocessed rejects inactive fixed table" - (!verifyBatchBytesWithFloor sysBytes clmBytes prfBytes none true false) - - -- Load grouped_prep_1shard as base production-floor key for single-invariant mutations - let baseBytes ← IO.FS.readBinFile (System.FilePath.mk "Tests/Fixtures/MultiStark" / "system.bin") - let .ok baseToy := StarkSystem.fromBytes baseBytes - | return [tests ++ test "base fixture decode" false] - let base := { baseToy with params := floorParams } - let baseFloorBytes := base.toBytes - tests := tests ++ test "base production-floor key decodes and passes checkSystem" - (expectOkCheck baseFloorBytes checkSystem) - - -- 2. Header downgrades, vk_digest mismatch, and transcript binding - tests := tests ++ test "negative: Protocol v5 header rejected by fromBytes" - (expectErr (StarkSystem.fromBytes (setU16LE baseFloorBytes 0 5)) "Protocol v6") - tests := tests ++ test "negative: Fp^2 extension_degree rejected by fromBytes" - (expectErr (StarkSystem.fromBytes (setU16LE baseFloorBytes 2 2)) "cubic extension") - tests := tests ++ test "negative: FriBatching::Horner tag rejected by fromBytes" - (expectErr (StarkSystem.fromBytes (setU16LE baseFloorBytes 4 0)) "Tensor") - tests := tests ++ test "negative: tampered vk_digest rejected by fromBytes" - (expectErr (StarkSystem.fromBytes (flipByte baseFloorBytes 6)) "vk_digest") - let badDigestSys := { base with vkDigest := default } - tests := tests ++ test "negative: mismatched vkDigest rejected by checkSystem" - (!checkSystem badDigestSys) - tests := tests ++ test "transcript: observeShape absorbs recomputed vkDigest regardless of stale field" - (observeShape (initialChallenger base.params) base == - observeShape (initialChallenger base.params) badDigestSys) - let altCirc := { base.circuits[0]! with nodes := base.circuits[0]!.nodes.push (.const Goldilocks.one) } - let altSys := { base with circuits := base.circuits.set! 0 altCirc } - tests := tests ++ test "transcript: observeShape changes when circuit graph changes even with fixed vkDigest" - (observeShape (initialChallenger base.params) base != - observeShape (initialChallenger base.params) altSys) - - -- 3. Lookup roots outside lookupPrefixLen - let c0 := base.circuits[0]! - let badPrefixC0 := { c0 with lookupPrefixLen := c0.lookupPrefixLen - 1 } - let badPrefixSys := makeSelfConsistent floorParams (base.circuits.set! 0 badPrefixC0) - base.preprocessedCommit base.preprocessedIndices - tests := tests ++ test "negative: lookup root outside lookupPrefixLen rejected by fromBytes" - (expectErr (StarkSystem.fromBytes badPrefixSys.toBytes) "lookup") - tests := tests ++ test "negative: lookup root outside lookupPrefixLen rejected by checkSystem" - (!checkSystem badPrefixSys) - tests := tests ++ test "negative: lookup root outside lookupPrefixLen rejected by checkLookupsPlain" - (!checkLookupsPlain badPrefixC0) - let oobPrefixC0 := { c0 with lookupPrefixLen := c0.nodes.size + 1 } - let oobPrefixSys := makeSelfConsistent floorParams (base.circuits.set! 0 oobPrefixC0) - base.preprocessedCommit base.preprocessedIndices - tests := tests ++ test "negative: lookupPrefixLen > nodes.size rejected by fromBytes" - (expectErr (StarkSystem.fromBytes oobPrefixSys.toBytes) "lookup_prefix_len") - tests := tests ++ test "negative: lookupPrefixLen > nodes.size rejected by checkSystem" - (!checkSystem oobPrefixSys) - -- Separate multiplicity vs argument root outside lookupPrefixLen - let badMultCirc : SysCircuit := { - mainWidth := 1, preprocessedWidth := 0, preprocessedHeight := 0 - maxConstraintDegree := 2, lookupGroupSize := 1, lookupPrefixLen := 1 - nodes := #[.var .main .current 0, .const Goldilocks.one] - zeros := #[], lookups := #[{ multiplicity := 1, args := #[0] }] - } - let badMultSys := makeSelfConsistent floorParams #[badMultCirc] - tests := tests ++ test "negative: lookup multiplicity outside lookupPrefixLen rejected by fromBytes" - (expectErr (StarkSystem.fromBytes badMultSys.toBytes) "multiplicity") - tests := tests ++ test "negative: lookup multiplicity outside lookupPrefixLen rejected by checkLookupsPlain" - (!checkLookupsPlain badMultCirc) - - -- 4. Derived maxConstraintDegree mismatch, blowup budget, and mul-DAG degree overflow - let badDegHiC0 := { c0 with maxConstraintDegree := c0.maxConstraintDegree + 1 } - let badDegHiSys := makeSelfConsistent floorParams (base.circuits.set! 0 badDegHiC0) - base.preprocessedCommit base.preprocessedIndices - tests := tests ++ test "negative: inflated maxConstraintDegree rejected by fromBytes" - (expectErr (StarkSystem.fromBytes badDegHiSys.toBytes) "max_constraint_degree") - tests := tests ++ test "negative: inflated maxConstraintDegree rejected by checkSystem" - (!checkSystem badDegHiSys) - let badDegLoC0 := { c0 with maxConstraintDegree := c0.maxConstraintDegree - 1 } - let badDegLoSys := makeSelfConsistent floorParams (base.circuits.set! 0 badDegLoC0) - base.preprocessedCommit base.preprocessedIndices - tests := tests ++ test "negative: deflated maxConstraintDegree rejected by fromBytes" - (expectErr (StarkSystem.fromBytes badDegLoSys.toBytes) "max_constraint_degree") - tests := tests ++ test "negative: deflated maxConstraintDegree rejected by checkSystem" - (!checkSystem badDegLoSys) - let deg4Circ : SysCircuit := { - mainWidth := 1, preprocessedWidth := 0, preprocessedHeight := 0 - maxConstraintDegree := 4, lookupGroupSize := 1, lookupPrefixLen := 0 - nodes := #[.var .main .current 0, .mul 0 0, .mul 1 1] - zeros := #[2], lookups := #[] - } - let lowBlowupParams := { floorParams with logBlowup := 1, numQueries := 238 } - let blowupExceedSys := makeSelfConsistent lowBlowupParams #[deg4Circ] - let blowupOkSys := makeSelfConsistent floorParams #[deg4Circ] - tests := tests ++ test "negative: degree exceeding blowup budget rejected by fromBytes" - (expectErr (StarkSystem.fromBytes blowupExceedSys.toBytes) "blowup") - tests := tests ++ test "negative: degree exceeding blowup budget rejected by checkSystem" - (!checkSystem blowupExceedSys) - tests := tests ++ test "positive: degree within blowup budget accepted by fromBytes and checkSystem" - (expectOkCheck blowupOkSys.toBytes checkSystem) - let overflowNodes : Array GraphNode := Id.run do - let mut ns : Array GraphNode := #[.var .main .current 0] - for i in [0:32] do - ns := ns.push (.mul i i) - return ns - let overflowCirc : SysCircuit := { - mainWidth := 1, preprocessedWidth := 0, preprocessedHeight := 0 - maxConstraintDegree := 1, lookupGroupSize := 1, lookupPrefixLen := 0 - nodes := overflowNodes, zeros := #[32], lookups := #[] - } - let overflowSys := makeSelfConsistent floorParams #[overflowCirc] - tests := tests ++ test "negative: mul-DAG degree overflow rejected by fromBytes" - (expectErr (StarkSystem.fromBytes overflowSys.toBytes) "overflow") - tests := tests ++ test "negative: mul-DAG degree overflow rejected by checkSystem" - (!checkSystem overflowSys) - - -- 5. lookupGroupSize bounds (0 and 9 > MAX_LOOKUP_GROUP = 8; 8 accepted) - let trivialCirc : SysCircuit := { - mainWidth := 1, preprocessedWidth := 0, preprocessedHeight := 0 - maxConstraintDegree := 1, lookupGroupSize := 1, lookupPrefixLen := 0 - nodes := #[.var .main .current 0], zeros := #[0], lookups := #[] - } - let grp0Sys := makeSelfConsistent floorParams #[{ trivialCirc with lookupGroupSize := 0 }] - let grp9Sys := makeSelfConsistent floorParams #[{ trivialCirc with lookupGroupSize := 9 }] - let grp8Sys := makeSelfConsistent floorParams #[{ trivialCirc with lookupGroupSize := 8 }] - tests := tests ++ test "negative: lookupGroupSize = 0 rejected by fromBytes" - (expectErr (StarkSystem.fromBytes grp0Sys.toBytes) "lookup group size") - tests := tests ++ test "negative: lookupGroupSize = 0 rejected by checkSystem" - (!checkSystem grp0Sys) - tests := tests ++ test "negative: lookupGroupSize = 9 (> MAX_LOOKUP_GROUP) rejected by fromBytes" - (expectErr (StarkSystem.fromBytes grp9Sys.toBytes) "lookup group size") - tests := tests ++ test "negative: lookupGroupSize = 9 (> MAX_LOOKUP_GROUP) rejected by checkSystem" - (!checkSystem grp9Sys) - tests := tests ++ test "positive: lookupGroupSize = 8 (MAX_LOOKUP_GROUP) accepted" - (expectOkCheck grp8Sys.toBytes checkSystem) - - -- 6. Compiler-context parity (lookup prefix forbidden nodes & stage-2 reachable from zeros) - let forbiddenPrefixNodes : List (String × GraphNode) := [ - ("Public(0)", .publicInput 0), - ("IsFirstRow", .isFirstRow), - ("IsLastRow", .isLastRow), - ("IsTransition", .isTransition), - ("Var(Stage2)", .var .stage2 .current 0) - ] - for (label, badNode) in forbiddenPrefixNodes do - let rawBadCirc : SysCircuit := { - mainWidth := 1, preprocessedWidth := 0, preprocessedHeight := 0 - maxConstraintDegree := 2, lookupGroupSize := 1, lookupPrefixLen := 2 - nodes := #[.const Goldilocks.one, badNode] - zeros := #[], lookups := #[{ multiplicity := 0, args := #[1] }] - } - let degs := sweepDegreesTotal rawBadCirc.nodes - let expectedDeg := deriveLookupDegree degs rawBadCirc.lookups rawBadCirc.lookupGroupSize - let badCirc := { rawBadCirc with maxConstraintDegree := expectedDeg } - let badSys := makeSelfConsistent floorParams #[badCirc] - tests := tests ++ test s!"negative: {label} in lookup prefix rejected by fromBytes" - (expectErr (StarkSystem.fromBytes badSys.toBytes) "lookup prefix") - tests := tests ++ test s!"negative: {label} in lookup prefix rejected by checkSystem" - (!checkSystem badSys) - tests := tests ++ test s!"negative: {label} in lookup prefix rejected by checkLookupsPlain" - (!checkLookupsPlain badCirc) - let s2ZeroDirect : SysCircuit := { - mainWidth := 1, preprocessedWidth := 0, preprocessedHeight := 0 - maxConstraintDegree := 1, lookupGroupSize := 1, lookupPrefixLen := 0 - nodes := #[.var .stage2 .current 0], zeros := #[0], lookups := #[] - } - let s2DirectSys := makeSelfConsistent floorParams #[s2ZeroDirect] - tests := tests ++ test "negative: stage-2 directly in zero constraint rejected by fromBytes" - (expectErr (StarkSystem.fromBytes s2DirectSys.toBytes) "stage-2") - tests := tests ++ test "negative: stage-2 directly in zero constraint rejected by checkSystem" - (!checkSystem s2DirectSys) - let s2ZeroIndirect : SysCircuit := { - mainWidth := 1, preprocessedWidth := 0, preprocessedHeight := 0 - maxConstraintDegree := 2, lookupGroupSize := 1, lookupPrefixLen := 0 - nodes := #[.var .stage2 .current 0, .mul 0 0, .neg 1], zeros := #[2], lookups := #[] - } - let s2IndirectSys := makeSelfConsistent floorParams #[s2ZeroIndirect] - tests := tests ++ test "negative: stage-2 reachable from zero constraint rejected by fromBytes" - (expectErr (StarkSystem.fromBytes s2IndirectSys.toBytes) "stage-2") - tests := tests ++ test "negative: stage-2 reachable from zero constraint rejected by checkSystem" - (!checkSystem s2IndirectSys) - let selPubZeroCirc : SysCircuit := { - mainWidth := 1, preprocessedWidth := 0, preprocessedHeight := 0 - maxConstraintDegree := 2, lookupGroupSize := 1, lookupPrefixLen := 0 - nodes := #[.var .main .current 0, .isFirstRow, .mul 0 1, .publicInput 0, .add 2 3] - zeros := #[4], lookups := #[] - } - let selPubSys := makeSelfConsistent floorParams #[selPubZeroCirc] - tests := tests ++ test "positive: selectors and publics in zero constraints accepted" - (expectOkCheck selPubSys.toBytes checkSystem) - - -- 7. Preprocessed width/height consistency & power-of-two height - let badPrepW : SysCircuit := { trivialCirc with preprocessedWidth := 1, preprocessedHeight := 0 } - let badPrepWSys := makeSelfConsistent floorParams #[badPrepW] - tests := tests ++ test "negative: preprocessedWidth > 0 with preprocessedHeight == 0 rejected by fromBytes" - (expectErr (StarkSystem.fromBytes badPrepWSys.toBytes) "preprocessed_width") - tests := tests ++ test "negative: preprocessedWidth > 0 with preprocessedHeight == 0 rejected by checkSystem" - (!checkSystem badPrepWSys) - let dummyRoot : D := base.vkDigest - let badPrepH : SysCircuit := { trivialCirc with preprocessedWidth := 0, preprocessedHeight := 4 } - let badPrepHSys := makeSelfConsistent floorParams #[badPrepH] (some #[dummyRoot]) #[some 0] - tests := tests ++ test "negative: preprocessedWidth == 0 with preprocessedHeight > 0 rejected by fromBytes" - (expectErr (StarkSystem.fromBytes badPrepHSys.toBytes) "preprocessed_width") - tests := tests ++ test "negative: preprocessedWidth == 0 with preprocessedHeight > 0 rejected by checkSystem" - (!checkSystem badPrepHSys) - let nonPotPrepH : SysCircuit := { trivialCirc with preprocessedWidth := 1, preprocessedHeight := 3 } - let nonPotSys := makeSelfConsistent floorParams #[nonPotPrepH] (some #[dummyRoot]) #[some 0] - tests := tests ++ test "negative: non-power-of-two preprocessedHeight rejected by fromBytes" - (expectErr (StarkSystem.fromBytes nonPotSys.toBytes) "power of two") - tests := tests ++ test "negative: non-power-of-two preprocessedHeight rejected by checkSystem" - (!checkSystem nonPotSys) - - -- 8. Canonical ConstBig encodings - for badVal in ([0, 1, 0xFFFF, Goldilocks.order, Goldilocks.order + 1, 0xFFFFFFFFFFFFFFFF] : List Nat) do - let badBytes := rawSingleNodeConstBigKey badVal false - tests := tests ++ test s!"negative: non-canonical ConstBig {badVal} rejected by fromBytes" - (expectErr (StarkSystem.fromBytes badBytes) "non-canonical") - for goodVal in ([0x10000, Goldilocks.order - 1] : List Nat) do - let goodBytes := rawSingleNodeConstBigKey goodVal true - tests := tests ++ test s!"positive: canonical ConstBig {goodVal} accepted and round-trips" - (expectOkCheck goodBytes fun s => checkSystem s && s.toBytes == goodBytes) - - -- 9. Node index bounds, topological order, trailer, nonzero capHeight LDE check, PoW cap, EOF - let oobPubSys := makeSelfConsistent floorParams - #[{ trivialCirc with nodes := #[.publicInput 12], zeros := #[] }] - tests := tests ++ test "negative: OOB Public(12) rejected by fromBytes" - (expectErr (StarkSystem.fromBytes oobPubSys.toBytes) "out of bounds") - tests := tests ++ test "negative: OOB Public(12) rejected by checkSystem" - (!checkSystem oobPubSys) - let oobMainSys := makeSelfConsistent floorParams - #[{ trivialCirc with nodes := #[.var .main .current 1], zeros := #[] }] - tests := tests ++ test "negative: OOB Main var rejected by fromBytes" - (expectErr (StarkSystem.fromBytes oobMainSys.toBytes) "out of bounds") - tests := tests ++ test "negative: OOB Main var rejected by checkSystem" - (!checkSystem oobMainSys) - let oobPrepSys := makeSelfConsistent floorParams - #[{ trivialCirc with nodes := #[.var .preprocessed .current 0], zeros := #[] }] - tests := tests ++ test "negative: OOB Preprocessed var rejected by fromBytes" - (expectErr (StarkSystem.fromBytes oobPrepSys.toBytes) "out of bounds") - tests := tests ++ test "negative: OOB Preprocessed var rejected by checkSystem" - (!checkSystem oobPrepSys) - let oobS2Sys := makeSelfConsistent floorParams - #[{ trivialCirc with nodes := #[.var .stage2 .current 3], zeros := #[] }] - tests := tests ++ test "negative: OOB Stage2 var rejected by fromBytes" - (expectErr (StarkSystem.fromBytes oobS2Sys.toBytes) "out of bounds") - tests := tests ++ test "negative: OOB Stage2 var rejected by checkSystem" - (!checkSystem oobS2Sys) - let oobZeroSys := makeSelfConsistent floorParams - #[{ trivialCirc with zeros := #[5] }] - tests := tests ++ test "negative: OOB zero root rejected by fromBytes" - (expectErr (StarkSystem.fromBytes oobZeroSys.toBytes) "out of bounds") - tests := tests ++ test "negative: OOB zero root rejected by checkSystem" - (!checkSystem oobZeroSys) - let nonTopoSys := makeSelfConsistent floorParams - #[{ trivialCirc with nodes := #[.neg 0], zeros := #[] }] - tests := tests ++ test "negative: non-topological node rejected by fromBytes" - (expectErr (StarkSystem.fromBytes nonTopoSys.toBytes) "topological") - tests := tests ++ test "negative: non-topological node rejected by checkSystem" - (!checkSystem nonTopoSys) - - let missingCommitSys := { base with preprocessedCommit := none } - tests := tests ++ test "negative: missing preprocessed commitment rejected by fromBytes" - (expectErr (StarkSystem.fromBytes missingCommitSys.toBytes) "missing preprocessed commitment") - tests := tests ++ test "negative: missing preprocessed commitment rejected by checkSystem" - (!checkSystem missingCommitSys) - let extraCommitSys := makeSelfConsistent floorParams #[trivialCirc] (some #[dummyRoot]) #[none] - tests := tests ++ test "negative: extraneous preprocessed commitment rejected by fromBytes" - (expectErr (StarkSystem.fromBytes extraCommitSys.toBytes) "no preprocessed circuits") - tests := tests ++ test "negative: extraneous preprocessed commitment rejected by checkSystem" - (!checkSystem extraCommitSys) - let badRankSys := { base with preprocessedIndices := #[none, some 1] } - tests := tests ++ test "negative: non-canonical preprocessed rank rejected by fromBytes" - (expectErr (StarkSystem.fromBytes badRankSys.toBytes) "rank") - tests := tests ++ test "negative: non-canonical preprocessed rank rejected by checkSystem" - (!checkSystem badRankSys) - let missingIdxSys := { base with preprocessedIndices := #[none, none] } - tests := tests ++ test "negative: missing preprocessed index rejected by fromBytes" - (expectErr (StarkSystem.fromBytes missingIdxSys.toBytes) "preprocessed_height") - tests := tests ++ test "negative: missing preprocessed index rejected by checkSystem" - (!checkSystem missingIdxSys) - for capN in ([0, 2, 3] : List Nat) do - let badCapSys := { base with preprocessedCommit := some (Array.replicate capN dummyRoot) } - tests := tests ++ test s!"negative: malformed preprocessed cap len {capN} rejected by fromBytes" - (expectErr (StarkSystem.fromBytes badCapSys.toBytes) "roots") - tests := tests ++ test s!"negative: malformed preprocessed cap len {capN} rejected by checkSystem" - (!checkSystem badCapSys) - - -- Nonzero cap_height LDE root count check (height 2, logBlowup 2 => LDE log 3, capHeight 2 => 4 roots) - let prep2Circ : SysCircuit := { trivialCirc with preprocessedWidth := 1, preprocessedHeight := 2 } - let cap2Params := { floorParams with capHeight := 2 } - let cap2GoodSys := makeSelfConsistent cap2Params #[prep2Circ] (some (Array.replicate 4 dummyRoot)) #[some 0] - let cap2BadSys := makeSelfConsistent cap2Params #[prep2Circ] (some (Array.replicate 2 dummyRoot)) #[some 0] - tests := tests ++ test "nonzero capHeight validates against preprocessed LDE height (4 roots ok, checkSystem rejects)" - (expectOkCheck cap2GoodSys.toBytes fun s => !checkSystem s) - tests := tests ++ test "negative: nonzero capHeight with unblown root count (2 roots) rejected by fromBytes" - (expectErr (StarkSystem.fromBytes cap2BadSys.toBytes) "roots") - - let badCommitPowSys := { base with params := { base.params with commitPowBits := 33 } } - let badQueryPowSys := { base with params := { base.params with queryPowBits := 33 } } - tests := tests ++ test "negative: commitPowBits > 32 rejected by fromBytes" - (expectErr (StarkSystem.fromBytes badCommitPowSys.toBytes) "exceeds") - tests := tests ++ test "negative: commitPowBits > 32 rejected by checkSystemWithFloor(true)" - (!checkSystemWithFloor badCommitPowSys true) - tests := tests ++ test "negative: queryPowBits > 32 rejected by fromBytes" - (expectErr (StarkSystem.fromBytes badQueryPowSys.toBytes) "exceeds") - tests := tests ++ test "negative: queryPowBits > 32 rejected by checkSystemWithFloor(true)" - (!checkSystemWithFloor badQueryPowSys true) - tests := tests ++ test "negative: trailing byte rejected by fromBytes" - (expectErr (StarkSystem.fromBytes (baseFloorBytes.push 0)) "trailing") - tests := tests ++ test "negative: truncated key rejected by fromBytes" - (expectErr (StarkSystem.fromBytes (baseFloorBytes.extract 0 (baseFloorBytes.size - 1))) "eof") - - return [tests] + itBool s!"{name}: PinnedVerifier strict active-preprocessed rejects inactive fixed table" + (!Ix.Cert.MultiStark.PinnedVerifier.verifyBytesPinnedIx sysBytes clmBytes prfBytes true false) + let unpinnedSysBytes := stripStage1Pinning sysBytes + match StarkSystem.fromBytes unpinnedSysBytes with + | .error e => + itBool s!"{name}: StarkSystem.fromBytes accepts unpinned projection ({e})" false + | .ok s => + itBool s!"{name}: toBytes round-trips byte-identically on unpinned projection" + (s.toBytes == unpinnedSysBytes) + itBool s!"{name}: vkDigest matches recomputed computeVkDigest" + (s.vkDigest == computeVkDigest s.circuits) + itBool s!"{name}: passes checkSystemWithFloor(allowBelowFloor=true)" + (checkSystemWithFloor s true) + itBool s!"{name}: all circuits pass checkLookupsPlain" + (s.circuits.all checkLookupsPlain) + let sFloor := { s with params := floorParams } + itBool s!"{name}: passes StarkSystem.fromBytes and checkSystem at production floor" + (expectOkCheck sFloor.toBytes fun s2 => checkSystem s2 && s2 == sFloor) + + -- Load grouped_prep_1shard as base production-floor key for single-invariant mutations + match StarkSystem.fromBytes baseBytes with + | .error _ => + itBool "base fixture decode" false + | .ok baseToy => + let base := { baseToy with params := floorParams } + let baseFloorBytes := base.toBytes + itBool "base production-floor key decodes and passes checkSystem" + (expectOkCheck baseFloorBytes checkSystem) + + -- 2. Header downgrades, vk_digest mismatch, and transcript binding + itBool "negative: Protocol v5 header rejected by fromBytes" + (expectErr (StarkSystem.fromBytes (setU16LE baseFloorBytes 0 5)) "Protocol v6") + itBool "negative: Fp^2 extension_degree rejected by fromBytes" + (expectErr (StarkSystem.fromBytes (setU16LE baseFloorBytes 2 2)) "cubic extension") + itBool "negative: FriBatching::Horner tag rejected by fromBytes" + (expectErr (StarkSystem.fromBytes (setU16LE baseFloorBytes 4 0)) "Tensor") + itBool "negative: tampered vk_digest rejected by fromBytes" + (expectErr (StarkSystem.fromBytes (flipByte baseFloorBytes 6)) "vk_digest") + let badDigestSys := { base with vkDigest := default } + itBool "negative: mismatched vkDigest rejected by checkSystem" + (!checkSystem badDigestSys) + itBool "transcript: observeShape absorbs recomputed vkDigest regardless of stale field" + (observeShape (initialChallenger base.params) base == + observeShape (initialChallenger base.params) badDigestSys) + let altCirc := { base.circuits[0]! with nodes := base.circuits[0]!.nodes.push (.const Goldilocks.one) } + let altSys := { base with circuits := base.circuits.set! 0 altCirc } + itBool "transcript: observeShape changes when circuit graph changes even with fixed vkDigest" + (observeShape (initialChallenger base.params) base != + observeShape (initialChallenger base.params) altSys) + + -- 3. Lookup roots outside lookupPrefixLen + let c0 := base.circuits[0]! + let badPrefixC0 := { c0 with lookupPrefixLen := c0.lookupPrefixLen - 1 } + let badPrefixSys := makeSelfConsistent floorParams (base.circuits.set! 0 badPrefixC0) + base.preprocessedCommit base.preprocessedIndices + itBool "negative: lookup root outside lookupPrefixLen rejected by fromBytes" + (expectErr (StarkSystem.fromBytes badPrefixSys.toBytes) "lookup") + itBool "negative: lookup root outside lookupPrefixLen rejected by checkSystem" + (!checkSystem badPrefixSys) + itBool "negative: lookup root outside lookupPrefixLen rejected by checkLookupsPlain" + (!checkLookupsPlain badPrefixC0) + let oobPrefixC0 := { c0 with lookupPrefixLen := c0.nodes.size + 1 } + let oobPrefixSys := makeSelfConsistent floorParams (base.circuits.set! 0 oobPrefixC0) + base.preprocessedCommit base.preprocessedIndices + itBool "negative: lookupPrefixLen > nodes.size rejected by fromBytes" + (expectErr (StarkSystem.fromBytes oobPrefixSys.toBytes) "lookup_prefix_len") + itBool "negative: lookupPrefixLen > nodes.size rejected by checkSystem" + (!checkSystem oobPrefixSys) + -- Separate multiplicity vs argument root outside lookupPrefixLen + let badMultCirc : SysCircuit := { + mainWidth := 1, preprocessedWidth := 0, preprocessedHeight := 0 + maxConstraintDegree := 2, lookupGroupSize := 1, lookupPrefixLen := 1 + nodes := #[.var .main .current 0, .const Goldilocks.one] + zeros := #[], lookups := #[{ multiplicity := 1, args := #[0] }] + } + let badMultSys := makeSelfConsistent floorParams #[badMultCirc] + itBool "negative: lookup multiplicity outside lookupPrefixLen rejected by fromBytes" + (expectErr (StarkSystem.fromBytes badMultSys.toBytes) "multiplicity") + itBool "negative: lookup multiplicity outside lookupPrefixLen rejected by checkLookupsPlain" + (!checkLookupsPlain badMultCirc) + + -- 4. Derived maxConstraintDegree mismatch, blowup budget, and mul-DAG degree overflow + let badDegHiC0 := { c0 with maxConstraintDegree := c0.maxConstraintDegree + 1 } + let badDegHiSys := makeSelfConsistent floorParams (base.circuits.set! 0 badDegHiC0) + base.preprocessedCommit base.preprocessedIndices + itBool "negative: inflated maxConstraintDegree rejected by fromBytes" + (expectErr (StarkSystem.fromBytes badDegHiSys.toBytes) "max_constraint_degree") + itBool "negative: inflated maxConstraintDegree rejected by checkSystem" + (!checkSystem badDegHiSys) + let badDegLoC0 := { c0 with maxConstraintDegree := c0.maxConstraintDegree - 1 } + let badDegLoSys := makeSelfConsistent floorParams (base.circuits.set! 0 badDegLoC0) + base.preprocessedCommit base.preprocessedIndices + itBool "negative: deflated maxConstraintDegree rejected by fromBytes" + (expectErr (StarkSystem.fromBytes badDegLoSys.toBytes) "max_constraint_degree") + itBool "negative: deflated maxConstraintDegree rejected by checkSystem" + (!checkSystem badDegLoSys) + let deg4Circ : SysCircuit := { + mainWidth := 1, preprocessedWidth := 0, preprocessedHeight := 0 + maxConstraintDegree := 4, lookupGroupSize := 1, lookupPrefixLen := 0 + nodes := #[.var .main .current 0, .mul 0 0, .mul 1 1] + zeros := #[2], lookups := #[] + } + let lowBlowupParams := { floorParams with logBlowup := 1, numQueries := 238 } + let blowupExceedSys := makeSelfConsistent lowBlowupParams #[deg4Circ] + let blowupOkSys := makeSelfConsistent floorParams #[deg4Circ] + itBool "negative: degree exceeding blowup budget rejected by fromBytes" + (expectErr (StarkSystem.fromBytes blowupExceedSys.toBytes) "blowup") + itBool "negative: degree exceeding blowup budget rejected by checkSystem" + (!checkSystem blowupExceedSys) + itBool "positive: degree within blowup budget accepted by fromBytes and checkSystem" + (expectOkCheck blowupOkSys.toBytes checkSystem) + let overflowNodes : Array GraphNode := Id.run do + let mut ns : Array GraphNode := #[.var .main .current 0] + for i in [0:32] do + ns := ns.push (.mul i i) + return ns + let overflowCirc : SysCircuit := { + mainWidth := 1, preprocessedWidth := 0, preprocessedHeight := 0 + maxConstraintDegree := 1, lookupGroupSize := 1, lookupPrefixLen := 0 + nodes := overflowNodes, zeros := #[32], lookups := #[] + } + let overflowSys := makeSelfConsistent floorParams #[overflowCirc] + itBool "negative: mul-DAG degree overflow rejected by fromBytes" + (expectErr (StarkSystem.fromBytes overflowSys.toBytes) "overflow") + itBool "negative: mul-DAG degree overflow rejected by checkSystem" + (!checkSystem overflowSys) + + -- 5. lookupGroupSize bounds (0 and 9 > MAX_LOOKUP_GROUP = 8; 8 accepted) + let trivialCirc : SysCircuit := { + mainWidth := 1, preprocessedWidth := 0, preprocessedHeight := 0 + maxConstraintDegree := 1, lookupGroupSize := 1, lookupPrefixLen := 0 + nodes := #[.var .main .current 0], zeros := #[0], lookups := #[] + } + let grp0Sys := makeSelfConsistent floorParams #[{ trivialCirc with lookupGroupSize := 0 }] + let grp9Sys := makeSelfConsistent floorParams #[{ trivialCirc with lookupGroupSize := 9 }] + let grp8Sys := makeSelfConsistent floorParams #[{ trivialCirc with lookupGroupSize := 8 }] + itBool "negative: lookupGroupSize = 0 rejected by fromBytes" + (expectErr (StarkSystem.fromBytes grp0Sys.toBytes) "lookup group size") + itBool "negative: lookupGroupSize = 0 rejected by checkSystem" + (!checkSystem grp0Sys) + itBool "negative: lookupGroupSize = 9 (> MAX_LOOKUP_GROUP) rejected by fromBytes" + (expectErr (StarkSystem.fromBytes grp9Sys.toBytes) "lookup group size") + itBool "negative: lookupGroupSize = 9 (> MAX_LOOKUP_GROUP) rejected by checkSystem" + (!checkSystem grp9Sys) + itBool "positive: lookupGroupSize = 8 (MAX_LOOKUP_GROUP) accepted" + (expectOkCheck grp8Sys.toBytes checkSystem) + + -- 6. Compiler-context parity (lookup prefix forbidden nodes & stage-2 reachable from zeros) + let forbiddenPrefixNodes : List (String × GraphNode) := [ + ("Public(0)", .publicInput 0), + ("IsFirstRow", .isFirstRow), + ("IsLastRow", .isLastRow), + ("IsTransition", .isTransition), + ("Var(Stage2)", .var .stage2 .current 0) + ] + for (label, badNode) in forbiddenPrefixNodes do + let rawBadCirc : SysCircuit := { + mainWidth := 1, preprocessedWidth := 0, preprocessedHeight := 0 + maxConstraintDegree := 2, lookupGroupSize := 1, lookupPrefixLen := 2 + nodes := #[.const Goldilocks.one, badNode] + zeros := #[], lookups := #[{ multiplicity := 0, args := #[1] }] + } + let degs := sweepDegreesTotal rawBadCirc.nodes + let expectedDeg := deriveLookupDegree degs rawBadCirc.lookups rawBadCirc.lookupGroupSize + let badCirc := { rawBadCirc with maxConstraintDegree := expectedDeg } + let badSys := makeSelfConsistent floorParams #[badCirc] + itBool s!"negative: {label} in lookup prefix rejected by fromBytes" + (expectErr (StarkSystem.fromBytes badSys.toBytes) "lookup prefix") + itBool s!"negative: {label} in lookup prefix rejected by checkSystem" + (!checkSystem badSys) + itBool s!"negative: {label} in lookup prefix rejected by checkLookupsPlain" + (!checkLookupsPlain badCirc) + let s2ZeroDirect : SysCircuit := { + mainWidth := 1, preprocessedWidth := 0, preprocessedHeight := 0 + maxConstraintDegree := 1, lookupGroupSize := 1, lookupPrefixLen := 0 + nodes := #[.var .stage2 .current 0], zeros := #[0], lookups := #[] + } + let s2DirectSys := makeSelfConsistent floorParams #[s2ZeroDirect] + itBool "negative: stage-2 directly in zero constraint rejected by fromBytes" + (expectErr (StarkSystem.fromBytes s2DirectSys.toBytes) "stage-2") + itBool "negative: stage-2 directly in zero constraint rejected by checkSystem" + (!checkSystem s2DirectSys) + let s2ZeroIndirect : SysCircuit := { + mainWidth := 1, preprocessedWidth := 0, preprocessedHeight := 0 + maxConstraintDegree := 2, lookupGroupSize := 1, lookupPrefixLen := 0 + nodes := #[.var .stage2 .current 0, .mul 0 0, .neg 1], zeros := #[2], lookups := #[] + } + let s2IndirectSys := makeSelfConsistent floorParams #[s2ZeroIndirect] + itBool "negative: stage-2 reachable from zero constraint rejected by fromBytes" + (expectErr (StarkSystem.fromBytes s2IndirectSys.toBytes) "stage-2") + itBool "negative: stage-2 reachable from zero constraint rejected by checkSystem" + (!checkSystem s2IndirectSys) + let selPubZeroCirc : SysCircuit := { + mainWidth := 1, preprocessedWidth := 0, preprocessedHeight := 0 + maxConstraintDegree := 2, lookupGroupSize := 1, lookupPrefixLen := 0 + nodes := #[.var .main .current 0, .isFirstRow, .mul 0 1, .publicInput 0, .add 2 3] + zeros := #[4], lookups := #[] + } + let selPubSys := makeSelfConsistent floorParams #[selPubZeroCirc] + itBool "positive: selectors and publics in zero constraints accepted" + (expectOkCheck selPubSys.toBytes checkSystem) + + -- 7. Preprocessed width/height consistency & power-of-two height + let badPrepW : SysCircuit := { trivialCirc with preprocessedWidth := 1, preprocessedHeight := 0 } + let badPrepWSys := makeSelfConsistent floorParams #[badPrepW] + itBool "negative: preprocessedWidth > 0 with preprocessedHeight == 0 rejected by fromBytes" + (expectErr (StarkSystem.fromBytes badPrepWSys.toBytes) "preprocessed_width") + itBool "negative: preprocessedWidth > 0 with preprocessedHeight == 0 rejected by checkSystem" + (!checkSystem badPrepWSys) + let dummyRoot : D := base.vkDigest + let badPrepH : SysCircuit := { trivialCirc with preprocessedWidth := 0, preprocessedHeight := 4 } + let badPrepHSys := makeSelfConsistent floorParams #[badPrepH] (some #[dummyRoot]) #[some 0] + itBool "negative: preprocessedWidth == 0 with preprocessedHeight > 0 rejected by fromBytes" + (expectErr (StarkSystem.fromBytes badPrepHSys.toBytes) "preprocessed_width") + itBool "negative: preprocessedWidth == 0 with preprocessedHeight > 0 rejected by checkSystem" + (!checkSystem badPrepHSys) + let nonPotPrepH : SysCircuit := { trivialCirc with preprocessedWidth := 1, preprocessedHeight := 3 } + let nonPotSys := makeSelfConsistent floorParams #[nonPotPrepH] (some #[dummyRoot]) #[some 0] + itBool "negative: non-power-of-two preprocessedHeight rejected by fromBytes" + (expectErr (StarkSystem.fromBytes nonPotSys.toBytes) "power of two") + itBool "negative: non-power-of-two preprocessedHeight rejected by checkSystem" + (!checkSystem nonPotSys) + + -- 8. Canonical ConstBig encodings + for badVal in ([0, 1, 0xFFFF, Goldilocks.order, Goldilocks.order + 1, 0xFFFFFFFFFFFFFFFF] : List Nat) do + let badBytes := rawSingleNodeConstBigKey badVal false + itBool s!"negative: non-canonical ConstBig {badVal} rejected by fromBytes" + (expectErr (StarkSystem.fromBytes badBytes) "non-canonical") + for goodVal in ([0x10000, Goldilocks.order - 1] : List Nat) do + let goodBytes := rawSingleNodeConstBigKey goodVal true + itBool s!"positive: canonical ConstBig {goodVal} accepted and round-trips" + (expectOkCheck goodBytes fun s => checkSystem s && s.toBytes == goodBytes) + + -- 9. Node index bounds, topological order, trailer, nonzero capHeight LDE check, PoW cap, EOF + let oobPubSys := makeSelfConsistent floorParams + #[{ trivialCirc with nodes := #[.publicInput 12], zeros := #[] }] + itBool "negative: OOB Public(12) rejected by fromBytes" + (expectErr (StarkSystem.fromBytes oobPubSys.toBytes) "out of bounds") + itBool "negative: OOB Public(12) rejected by checkSystem" + (!checkSystem oobPubSys) + let oobMainSys := makeSelfConsistent floorParams + #[{ trivialCirc with nodes := #[.var .main .current 1], zeros := #[] }] + itBool "negative: OOB Main var rejected by fromBytes" + (expectErr (StarkSystem.fromBytes oobMainSys.toBytes) "out of bounds") + itBool "negative: OOB Main var rejected by checkSystem" + (!checkSystem oobMainSys) + let oobPrepSys := makeSelfConsistent floorParams + #[{ trivialCirc with nodes := #[.var .preprocessed .current 0], zeros := #[] }] + itBool "negative: OOB Preprocessed var rejected by fromBytes" + (expectErr (StarkSystem.fromBytes oobPrepSys.toBytes) "out of bounds") + itBool "negative: OOB Preprocessed var rejected by checkSystem" + (!checkSystem oobPrepSys) + let oobS2Sys := makeSelfConsistent floorParams + #[{ trivialCirc with nodes := #[.var .stage2 .current 3], zeros := #[] }] + itBool "negative: OOB Stage2 var rejected by fromBytes" + (expectErr (StarkSystem.fromBytes oobS2Sys.toBytes) "out of bounds") + itBool "negative: OOB Stage2 var rejected by checkSystem" + (!checkSystem oobS2Sys) + let oobZeroSys := makeSelfConsistent floorParams + #[{ trivialCirc with zeros := #[5] }] + itBool "negative: OOB zero root rejected by fromBytes" + (expectErr (StarkSystem.fromBytes oobZeroSys.toBytes) "out of bounds") + itBool "negative: OOB zero root rejected by checkSystem" + (!checkSystem oobZeroSys) + let nonTopoSys := makeSelfConsistent floorParams + #[{ trivialCirc with nodes := #[.neg 0], zeros := #[] }] + itBool "negative: non-topological node rejected by fromBytes" + (expectErr (StarkSystem.fromBytes nonTopoSys.toBytes) "topological") + itBool "negative: non-topological node rejected by checkSystem" + (!checkSystem nonTopoSys) + + let missingCommitSys := { base with preprocessedCommit := none } + itBool "negative: missing preprocessed commitment rejected by fromBytes" + (expectErr (StarkSystem.fromBytes missingCommitSys.toBytes) "missing preprocessed commitment") + itBool "negative: missing preprocessed commitment rejected by checkSystem" + (!checkSystem missingCommitSys) + let extraCommitSys := makeSelfConsistent floorParams #[trivialCirc] (some #[dummyRoot]) #[none] + itBool "negative: extraneous preprocessed commitment rejected by fromBytes" + (expectErr (StarkSystem.fromBytes extraCommitSys.toBytes) "no preprocessed circuits") + itBool "negative: extraneous preprocessed commitment rejected by checkSystem" + (!checkSystem extraCommitSys) + let badRankSys := { base with preprocessedIndices := #[none, some 1] } + itBool "negative: non-canonical preprocessed rank rejected by fromBytes" + (expectErr (StarkSystem.fromBytes badRankSys.toBytes) "rank") + itBool "negative: non-canonical preprocessed rank rejected by checkSystem" + (!checkSystem badRankSys) + let missingIdxSys := { base with preprocessedIndices := #[none, none] } + itBool "negative: missing preprocessed index rejected by fromBytes" + (expectErr (StarkSystem.fromBytes missingIdxSys.toBytes) "preprocessed_height") + itBool "negative: missing preprocessed index rejected by checkSystem" + (!checkSystem missingIdxSys) + for capN in ([0, 2, 3] : List Nat) do + let badCapSys := { base with preprocessedCommit := some (Array.replicate capN dummyRoot) } + itBool s!"negative: malformed preprocessed cap len {capN} rejected by fromBytes" + (expectErr (StarkSystem.fromBytes badCapSys.toBytes) "roots") + itBool s!"negative: malformed preprocessed cap len {capN} rejected by checkSystem" + (!checkSystem badCapSys) + + -- Nonzero cap_height LDE root count check (height 2, logBlowup 2 => LDE log 3, capHeight 2 => 4 roots) + let prep2Circ : SysCircuit := { trivialCirc with preprocessedWidth := 1, preprocessedHeight := 2 } + let cap2Params := { floorParams with capHeight := 2 } + let cap2GoodSys := makeSelfConsistent cap2Params #[prep2Circ] (some (Array.replicate 4 dummyRoot)) #[some 0] + let cap2BadSys := makeSelfConsistent cap2Params #[prep2Circ] (some (Array.replicate 2 dummyRoot)) #[some 0] + itBool "nonzero capHeight validates against preprocessed LDE height (4 roots ok, checkSystem rejects)" + (expectOkCheck cap2GoodSys.toBytes fun s => !checkSystem s) + itBool "negative: nonzero capHeight with unblown root count (2 roots) rejected by fromBytes" + (expectErr (StarkSystem.fromBytes cap2BadSys.toBytes) "roots") + + let badCommitPowSys := { base with params := { base.params with commitPowBits := 33 } } + let badQueryPowSys := { base with params := { base.params with queryPowBits := 33 } } + itBool "negative: commitPowBits > 32 rejected by fromBytes" + (expectErr (StarkSystem.fromBytes badCommitPowSys.toBytes) "exceeds") + itBool "negative: commitPowBits > 32 rejected by checkSystemWithFloor(true)" + (!checkSystemWithFloor badCommitPowSys true) + itBool "negative: queryPowBits > 32 rejected by fromBytes" + (expectErr (StarkSystem.fromBytes badQueryPowSys.toBytes) "exceeds") + itBool "negative: queryPowBits > 32 rejected by checkSystemWithFloor(true)" + (!checkSystemWithFloor badQueryPowSys true) + itBool "negative: trailing byte rejected by fromBytes" + (expectErr (StarkSystem.fromBytes (baseFloorBytes.push 0)) "trailing") + itBool "negative: truncated key rejected by fromBytes" + (expectErr (StarkSystem.fromBytes (baseFloorBytes.extract 0 (baseFloorBytes.size - 1))) "eof") end DecoderParity @@ -560,75 +580,82 @@ height assertion of `StarkVerifier::ood_loop` before any other circuit's out-of-domain check. -/ private def prepFirstHeightMutants : List Nat := [0, 1, 3, 4] -def suite : IO (List TestSeq) := do +def suite : IO Spec := do let system ← loadRecursionSystem - let mut tests : TestSeq := .done - for (name, dir, hasInactivePrep) in fixtures do + let loaded ← fixtures.mapM fun (name, dir, hasInactivePrep) => do let sys ← IO.FS.readBinFile (dir / "system.bin") let prf ← IO.FS.readBinFile (dir / "proof.bin") let clm ← IO.FS.readBinFile (dir / "claims.bin") - if hasInactivePrep then - -- Strict active-preprocessed invariant: `select_active_prep` rejects shards that - -- deactivate a circuit with a fixed preprocessed table. - let ok ← checkProof system sys clm prf - tests := tests ++ test s!"{name}: strict active-preprocessed check rejects inactive fixed table" - (!ok) - else - let ok ← checkProof system sys clm prf - tests := tests ++ test s!"{name}: valid Protocol v6 Fp^3 Rust proof accepted by Aiur verifier" ok - -- Negative control 1: flip a byte near the end of the proof (FRI/MMCS payload) - let badPrf1 := flipByte prf (prf.size - 17) - tests := tests ++ test s!"{name}: tampered proof tail rejected" - (!(← checkProof system sys clm badPrf1)) - -- Negative control 2: flip a byte in the proof header/length prefix - let badPrf2 := flipByte prf (min 12 (prf.size - 1)) - tests := tests ++ test s!"{name}: tampered proof header rejected" - (!(← checkProof system sys clm badPrf2)) - -- Negative control 3: flip a byte in claims.bin - let badClm := flipByte clm (clm.size - 1) - tests := tests ++ test s!"{name}: tampered claims rejected" - (!(← checkProof system sys badClm prf)) - -- Negative control 4: truncated proof rejected without panicking - let truncPrf := prf.extract 0 (prf.size / 2) - tests := tests ++ test s!"{name}: truncated proof rejected" - (!(← checkProof system sys clm truncPrf)) - -- Negative control 5: Protocol v5 header downgrade rejected fail-closed - let v5Sys := setU16LE sys 0 5 - tests := tests ++ test s!"{name}: Protocol v5 downgrade rejected fail-closed" - (!(← checkProof system v5Sys clm prf)) - -- Negative control 6: Fp^2 (extension_degree = 2) header downgrade rejected fail-closed - let fp2Sys := setU16LE sys 2 2 - tests := tests ++ test s!"{name}: Fp^2 (ext_degree=2) downgrade rejected fail-closed" - (!(← checkProof system fp2Sys clm prf)) - -- Negative control 7: FriBatching::Horner (tag 0) downgrade rejected fail-closed - let hornerSys := setU16LE sys 4 0 - tests := tests ++ test s!"{name}: FriBatching::Horner downgrade rejected fail-closed" - (!(← checkProof system hornerSys clm prf)) - -- Negative control 8: a fixed table at a height other than its own is rejected. + return (name, hasInactivePrep, sys, prf, clm) let pfDir : System.FilePath := "Tests/Fixtures/MultiStark/prep_first" let pfSys ← IO.FS.readBinFile (pfDir / "system.bin") let pfClm ← IO.FS.readBinFile (pfDir / "claims.bin") - for ld in prepFirstHeightMutants do + let pfMutants ← prepFirstHeightMutants.mapM fun ld => do let bad ← IO.FS.readBinFile (pfDir / s!"logdeg_{ld}" / "proof.bin") - tests := tests ++ test - s!"prep_first: fixed table of 4 rows at log degree {ld} rejected (height binding)" - (!(← checkProof system pfSys pfClm bad)) - -- Negative control 9: non-zero commit PoW witness when commit_pow_bits == 0 is rejected. + return (ld, bad) let npDir : System.FilePath := "Tests/Fixtures/MultiStark/single_no_prep" let npSys ← IO.FS.readBinFile (npDir / "system.bin") let npClm ← IO.FS.readBinFile (npDir / "claims.bin") let badCpowPrf ← IO.FS.readBinFile (npDir / "nonzero_cpow" / "proof.bin") - tests := tests ++ test - "single_no_prep: nonzero commit PoW witness when commit_pow_bits == 0 rejected" - (!(← checkProof system npSys npClm badCpowPrf)) - -- Negative control 10: natively valid below-floor proof rejected in-circuit. let lowDir : System.FilePath := npDir / "below_floor" let lowSys ← IO.FS.readBinFile (lowDir / "system.bin") let lowClm ← IO.FS.readBinFile (lowDir / "claims.bin") let lowPrf ← IO.FS.readBinFile (lowDir / "proof.bin") - tests := tests ++ test - "single_no_prep/below_floor: natively valid below-floor proof rejected in-circuit" - (!(← checkProof system lowSys lowClm lowPrf)) - return [tests] ++ (← admissibilitySuite) ++ (← decoderParitySuite) + let admissibility ← admissibilitySuite + let decoderParity ← decoderParitySuite + return do + for (name, hasInactivePrep, sys, prf, clm) in loaded do + if hasInactivePrep then + -- Strict active-preprocessed invariant: `select_active_prep` rejects shards that + -- deactivate a circuit with a fixed preprocessed table. + it s!"{name}: strict active-preprocessed check rejects inactive fixed table" do + expectFalse (← checkProof system sys clm prf) + else + it s!"{name}: valid Protocol v6 Fp^3 Rust proof accepted by Aiur verifier" do + expect (← checkProof system sys clm prf) + -- Negative control 1: flip a byte near the end of the proof (FRI/MMCS payload) + it s!"{name}: tampered proof tail rejected" do + let badPrf1 := flipByte prf (prf.size - 17) + expectFalse (← checkProof system sys clm badPrf1) + -- Negative control 2: flip a byte in the proof header/length prefix + it s!"{name}: tampered proof header rejected" do + let badPrf2 := flipByte prf (min 12 (prf.size - 1)) + expectFalse (← checkProof system sys clm badPrf2) + -- Negative control 3: flip a byte in claims.bin + it s!"{name}: tampered claims rejected" do + let badClm := flipByte clm (clm.size - 1) + expectFalse (← checkProof system sys badClm prf) + -- Negative control 4: truncated proof rejected without panicking + it s!"{name}: truncated proof rejected" do + let truncPrf := prf.extract 0 (prf.size / 2) + expectFalse (← checkProof system sys clm truncPrf) + -- Negative control 5: Protocol v5 header downgrade rejected fail-closed + it s!"{name}: Protocol v5 downgrade rejected fail-closed" do + let v5Sys := setU16LE sys 0 5 + expectFalse (← checkProof system v5Sys clm prf) + -- Negative control 6: Fp^2 (extension_degree = 2) header downgrade rejected fail-closed + it s!"{name}: Fp^2 (ext_degree=2) downgrade rejected fail-closed" do + let fp2Sys := setU16LE sys 2 2 + expectFalse (← checkProof system fp2Sys clm prf) + -- Negative control 7: FriBatching::Horner (tag 0) downgrade rejected fail-closed + it s!"{name}: FriBatching::Horner downgrade rejected fail-closed" do + let hornerSys := setU16LE sys 4 0 + expectFalse (← checkProof system hornerSys clm prf) + -- Negative control 7b: Stage-1 pinning downgrade (`stage_1_pinning = 0`) rejected fail-closed + it s!"{name}: stage_1_pinning=0 downgrade rejected fail-closed" do + let unpinnedSys := setU16LE sys 52 0 + expectFalse (← checkProof system unpinnedSys clm prf) + -- Negative control 8: a fixed table at a height other than its own is rejected. + for (ld, bad) in pfMutants do + it s!"prep_first: fixed table of 4 rows at log degree {ld} rejected (height binding)" do + expectFalse (← checkProof system pfSys pfClm bad) + -- Negative control 9: non-zero commit PoW witness when commit_pow_bits == 0 is rejected. + it "single_no_prep: nonzero commit PoW witness when commit_pow_bits == 0 rejected" do + expectFalse (← checkProof system npSys npClm badCpowPrf) + -- Negative control 10: natively valid below-floor proof rejected in-circuit. + it "single_no_prep/below_floor: natively valid below-floor proof rejected in-circuit" do + expectFalse (← checkProof system lowSys lowClm lowPrf) + admissibility + decoderParity end Tests.Ix.MultiStarkVerifier diff --git a/Tests/Ix/ResourceHints.lean b/Tests/Ix/ResourceHints.lean index e3ddf1a0d3..5863a0043f 100644 --- a/Tests/Ix/ResourceHints.lean +++ b/Tests/Ix/ResourceHints.lean @@ -89,16 +89,15 @@ def compiledVerdicts : IO (Array String × Array String) := do lines := lines ++ ls return (errors, lines) -def report (name : String) (action : IO (Array String × Array String)) : TestSeq := - .individualIO name none (do +def report (name : String) (action : IO (Array String × Array String)) : Spec := + it name do let (errors, lines) ← action for l in lines do IO.println l - let msg := if errors.isEmpty then none else some ("\n".intercalate (errors.toList.take 20)) - return (errors.isEmpty, 1, 0, msg)) .done + expect errors.isEmpty ("\n".intercalate (errors.toList.take 20)) -def suite : List TestSeq := [ - report "the typing half's verdict on the compiled fixtures" fixtureVerdict, +def suite : LSpec.Spec := do + report "the typing half's verdict on the compiled fixtures" fixtureVerdict report "actual typing verdicts: an ordinary contract input, an assumption axiom, unsafe inductives" - compiledVerdicts] + compiledVerdicts end Tests.ResourceHints diff --git a/Tests/Ix/ResourceModes.lean b/Tests/Ix/ResourceModes.lean index 797d90ff75..a8d28e1d3f 100644 --- a/Tests/Ix/ResourceModes.lean +++ b/Tests/Ix/ResourceModes.lean @@ -17,7 +17,7 @@ the named violation), and the uncertified checker (`IxCK.Resource.checkBodies`) must accept or refuse as stated. Every case the checker accepts runs without a violation (`consistent`), which is what its soundness would give on these inputs. The cases follow the mode rules: erased binders and fields; unique -transfer, consuming match, deep uniqueness, `@shared` fields, leaves; borrows of +transfer, consuming match, deep uniqueness, `@[shared]` fields, leaves; borrows of parameters, of `let`s and of leaves, leaves read out of a borrowed container; once binders; capture and partial-application transfers; mode skeletons; statics; limits; the fast path. @@ -38,7 +38,9 @@ such types (the mode-repair branch, V7). -/ namespace Tests.ResourceModes -open IxCK.Resource Ixon +open IxCK.Resource Ixon LSpec + +set_option compiler.extract_closed false /-! ## A small library -/ @@ -46,7 +48,7 @@ def addr (k : Nat) : Address := ⟨⟨#[k.toUInt8, 0x5a]⟩⟩ def mem (k : Nat) : Ref := .member (addr k) 0 def ctr (k j : Nat) : Ref := .ctor (addr k) 0 j -/-- A list, `Nat`, a box with an inherited field, a box with a `@shared` field, +/-- A list, `Nat`, a box with an inherited field, a box with a `@[shared]` field, a key with an erased field. -/ def L := mem 1 def nilR := ctr 1 0 @@ -163,7 +165,7 @@ def noArgs : Heap × List Val := (({} : HB).heap, []) def noExtern : ExternOracle := fun _ _ _ => none -def outcomeName : Outcome → String +def outcomeName : IxCK.Resource.Outcome → String | .value .. => "a value" | .violation k => s!"violation {repr k}" | .stuck => "stuck" @@ -179,8 +181,8 @@ value, or the violation), and the checker accepts exactly when `accept`. -/ def runCase (label : String) (defs : List (Ref × RunDef)) (entry : Ref) (input : Heap × List Val) (run : Option Violation) (accept : Bool) (toCheck : List Ref := [entry]) (lim : Limits := {}) (ext : ExternOracle := noExtern) : - LSpec.TestSeq := - .individualIO label none (do + Spec := + it label do let P := prog defs let o := runR P ext 100000 entry input.1 input.2 let runOk := match o, run with @@ -194,46 +196,45 @@ def runCase (label : String) (defs : List (Ref × RunDef)) (entry : Ref) (input | .violation _ => false | _ => true let msg := s!"run: {outcomeName o}; checker: {verdictName verdict}" - return (runOk && checkOk && consistent, 0, 0, if runOk && checkOk && consistent then none else some msg)) .done + expect (runOk && checkOk && consistent) msg /-- Run `entry` on `input` (an ill-typed input): the run is stuck, which is not a violation, and the checker accepts exactly when `accept`. -/ def stuckCase (label : String) (defs : List (Ref × RunDef)) (entry : Ref) (input : Heap × List Val) - (accept : Bool) (toCheck : List Ref := [entry]) : LSpec.TestSeq := - .individualIO label none (do + (accept : Bool) (toCheck : List Ref := [entry]) : LSpec.Spec := + it label do let P := prog defs let o := runR P noExtern 100000 entry input.1 input.2 let runOk := match o with | .stuck => true | _ => false let verdict := checkBodies {} P toCheck let checkOk := verdict.isAccept == accept let msg := s!"run: {outcomeName o}; checker: {verdictName verdict}" - return (runOk && checkOk, 0, 0, if runOk && checkOk then none else some msg)) .done + expect (runOk && checkOk) msg /-! ### Erased binders and fields -/ --- `useErased (@erased n : Nat) : Nat := n + 1` +-- `useErased (@[erased] n : Nat) : Nat := n + 1` def useErased := mem 100 --- `keep (@erased n : Nat) (b : List) : List := b` +-- `keep (@[erased] n : Nat) (b : List) : List := b` def keepE := mem 101 -- `leak (k : Key) : Nat := k.ghost`; `idOf (k : Key) : Nat := k.id` def leak := mem 102 def idOf := mem 103 --- `let (@erased x) := xs; len x` +-- `let (@[erased] x) := xs; len x` def eraseLet := mem 104 -def erasedCases : List LSpec.TestSeq := [ +def erasedCases : LSpec.Spec := do runCase "erased: reading an erased parameter" [(useErased, body [par .erased .leaf] - (add (v 0 .leaf) (.natLit 1)) .shared .leaf)] useErased irrArg (some .erasedRead) false, + (add (v 0 .leaf) (.natLit 1)) .shared .leaf)] useErased irrArg (some .erasedRead) false runCase "erased: an erased parameter never read" [(keepE, body [par .erased .leaf, par] - (v 0))] keepE irrAndList none true, + (v 0))] keepE irrAndList none true runCase "erased: projecting an erased field" [(leak, body [par] (.proj K 0 (v 0) .leaf) .shared .leaf)] - leak oneKey (some .erasedRead) false, + leak oneKey (some .erasedRead) false runCase "erased: projecting a kept field" [(idOf, body [par] (.proj K 1 (v 0) .leaf) .shared .leaf)] - idOf oneKey none true, + idOf oneKey none true runCase "erased: reading an erased let" [(eraseLet, body [par] (.letE (.value .erased) .val (v 0) (lenOf (v 0))) .shared .leaf)] eraseLet oneList (some .erasedRead) false -] /-! ### Unique transfer -/ @@ -248,45 +249,44 @@ def boxS := mem 117 def boxI := mem 118 def twiceN := mem 119 -def uniqueCases : List LSpec.TestSeq := [ - -- `twice (@unique xs) := consume xs + consume xs` +def uniqueCases : LSpec.Spec := do + -- `twice (@[unique] xs) := consume xs + consume xs` runCase "unique: a binding transferred twice" [(twice, body [par .unique] (add (app (.const consumeR .val) [v 0] .leaf) (app (.const consumeR .val) [v 0] .leaf)) .shared .leaf)] - twice oneList (some .revokedUse) false, + twice oneList (some .revokedUse) false runCase "unique: a binding transferred once" [(once1, body [par .unique] - (app (.const consumeR .val) [v 0] .leaf) .shared .leaf)] once1 oneList none true, + (app (.const consumeR .val) [v 0] .leaf) .shared .leaf)] once1 oneList none true -- `share1 (xs : List) := consume xs`; `caller (xs) := share1 xs + len xs` runCase "unique: a shared parameter given away, then read by its caller" [(share1, body [par] (app (.const consumeR .val) [v 0] .leaf) .shared .leaf), (caller, body [par] (add (app (.const share1 .val) [v 0] .leaf) (lenOf (v 0))) .shared .leaf)] - caller oneList (some .revokedUse) false [share1, caller], - -- `headU (@unique xs) := match xs with | [] => 0 | _ :: t => len t` + caller oneList (some .revokedUse) false [share1, caller] + -- `headU (@[unique] xs) := match xs with | [] => 0 | _ :: t => len t` runCase "unique: a consuming match, the fields used" [(headU, body [par .unique] - (onList (v 0) (.natLit 0) (lenOf (v 0)) .val .leaf) .shared .leaf)] headU oneList none true, - -- `headBad (@unique xs) := match xs with | [] => 0 | _ :: _ => len xs` + (onList (v 0) (.natLit 0) (lenOf (v 0)) .val .leaf) .shared .leaf)] headU oneList none true + -- `headBad (@[unique] xs) := match xs with | [] => 0 | _ :: _ => len xs` runCase "unique: a consumed major read in an alternative" [(headBad, body [par .unique] (onList (v 0) (.natLit 0) (lenOf (v 2)) .val .leaf) .shared .leaf)] headBad oneList - (some .revokedUse) false, - -- `deep (@unique xs) := match xs with | [] => 0 | h :: t => consume (h :: t) + len t` + (some .revokedUse) false + -- `deep (@[unique] xs) := match xs with | [] => 0 | h :: t => consume (h :: t) + len t` runCase "unique: deep transfer revokes the fields" [(deep, body [par .unique] (onList (v 0) (.natLit 0) (add (app (.const consumeR .val) [app (.const consR .val) [.irr, v 1, v 0]] .leaf) (lenOf (v 0))) .val .leaf) - .shared .leaf)] deep oneList (some .revokedUse) false, - -- `boxS (@unique x : List) := let s := ⟨x⟩ : S; consumeS s + len x` (a `@shared` field stops deep uniqueness; - -- `x` must be `@unique`, not plain: a plain parameter may be caller-borrowed so `consumeS ⟨x⟩` would escape) - runCase "unique: a @shared field stops deep uniqueness" [(boxS, body [par .unique] + .shared .leaf)] deep oneList (some .revokedUse) false + -- `boxS (@[unique] x : List) := let s := ⟨x⟩ : S; consumeS s + len x` (a `@[shared]` field stops deep uniqueness; + -- `x` must be `@[unique]`, not plain: a plain parameter may be caller-borrowed so `consumeS ⟨x⟩` would escape) + runCase "unique: a @[shared] field stops deep uniqueness" [(boxS, body [par .unique] (.letE (.value .many) .val (app (.const sboxR .val) [v 0]) - (add (app (.const consumeSR .val) [v 0] .leaf) (lenOf (v 1)))) .shared .leaf)] boxS oneList none true, + (add (app (.const consumeSR .val) [v 0] .leaf) (lenOf (v 1)))) .shared .leaf)] boxS oneList none true -- `boxI (x : List) := let s := ⟨x⟩ : B; consumeB s + len x` (an inherited field) runCase "unique: an inherited field is transferred with its box" [(boxI, body [par] (.letE (.value .many) .val (app (.const boxR .val) [v 0]) (add (app (.const consumeBR .val) [v 0] .leaf) (lenOf (v 1)))) .shared .leaf)] boxI oneList - (some .revokedUse) false, - -- `twiceN (@unique n : Nat) := consumeN n + consumeN n` (a leaf is never unique) + (some .revokedUse) false + -- `twiceN (@[unique] n : Nat) := consumeN n + consumeN n` (a leaf is never unique) runCase "unique: a leaf transferred twice" [(twiceN, body [par .unique .leaf] (add (app (.const consumeNR .val) [v 0 .leaf] .leaf) (app (.const consumeNR .val) [v 0 .leaf] .leaf)) .shared .leaf)] twiceN oneNat none true -] /-! ### Borrows -/ @@ -303,58 +303,56 @@ def headN := mem 129 def storeN := mem 132 def shf := mem 133 -def borrowCases : List LSpec.TestSeq := [ +def borrowCases : LSpec.Spec := do runCase "borrow: a borrowed parameter returned" [(esc, body [par .borrowed] (v 0))] esc oneList - (some .borrowEscape) false, + (some .borrowEscape) false -- refused after repair A (the leaf-result refinement dropped, findings 1 to 3); accepted again -- under the leaf ruling L1 (a number is never confined): `len`'s leaf result carries no region. runCase "borrow: a borrowed parameter read" [(peek, body [par .borrowed] (lenOf (v 0)) .shared .leaf)] - peek oneList none true, + peek oneList none true runCase "borrow: a borrowed parameter returned borrowed" [(same, body [par .borrowed] (v 0) .borrowed)] - same oneList none true, - -- `stash (@borrowed b : List) : List := [b]` + same oneList none true + -- `stash (@[borrowed] b : List) : List := [b]` runCase "borrow: a borrowed parameter stored in a cell" [(stash, body [par .borrowed] (app (.const consR .val) [.irr, v 0, app (.const nilR .val) [.irr] .imm]))] stash oneList - (some .borrowEscape) false, + (some .borrowEscape) false runCase "borrow: a borrowed parameter given away" [(give, body [par .borrowed] - (app (.const consumeR .val) [v 0] .leaf) .shared .leaf)] give oneList (some .borrowEscape) false, + (app (.const consumeR .val) [v 0] .leaf) .shared .leaf)] give oneList (some .borrowEscape) false runCase "borrow: a let's loan returned" [(letEsc, body [par] (.letE .borrow .val (v 0) (v 0)))] - letEsc oneList (some .borrowEscape) false, + letEsc oneList (some .borrowEscape) false -- refused after repair A, accepted again under L1: `len x` carries no region of the let's. runCase "borrow: a let's loan read" [(letOk, body [par] (.letE .borrow .val (v 0) (lenOf (v 0))) - .shared .leaf)] letOk oneList none true, + .shared .leaf)] letOk oneList none true -- under L1 a borrowed number is not confined: the run returns it and the checker accepts -- (before L1, borrowEscape and a refusal) runCase "borrow: a borrowed leaf returned" [(escN, body [par .borrowed .leaf] (v 0 .leaf) .shared .leaf)] - escN oneNat none true, + escN oneNat none true runCase "borrow: arithmetic on a borrowed leaf" [(addN, body [par .borrowed .leaf] - (add (v 0 .leaf) (.natLit 1)) .shared .leaf)] addN oneNat none true, - -- `headN (@borrowed xs : List Nat) : Nat := match xs with | [] => 0 | h :: _ => h` + (add (v 0 .leaf) (.natLit 1)) .shared .leaf)] addN oneNat none true + -- `headN (@[borrowed] xs : List Nat) : Nat := match xs with | [] => 0 | h :: _ => h` runCase "borrow: a leaf read out of a borrowed container is not confined" [(headN, body [par .borrowed] - (onList (v 0) (.natLit 0) (v 1 .leaf) .leaf .leaf) .shared .leaf)] headN oneList none true, - -- `storeN (@borrowed n : Nat) : Nat := match [n] with | [] => 0 | h :: _ => h` + (onList (v 0) (.natLit 0) (v 1 .leaf) .leaf .leaf) .shared .leaf)] headN oneList none true + -- `storeN (@[borrowed] n : Nat) : Nat := match [n] with | [] => 0 | h :: _ => h` runCase "borrow: a borrowed leaf stored in a cell and read back is a counted value" [(storeN, body [par .borrowed .leaf] (onList (app (.const consR .val) [.irr, v 0 .leaf, app (.const nilR .val) [.irr] .imm]) - (.natLit 0) (v 1 .leaf) .leaf .leaf) .shared .leaf)] storeN oneNat none true, - -- `shf (@borrowed b : List) : List := (⟨b⟩ : S).1` (a borrowed value in a `@shared` field) - runCase "borrow: a borrowed value stored in a @shared field and returned" [(shf, + (.natLit 0) (v 1 .leaf) .leaf .leaf) .shared .leaf)] storeN oneNat none true + -- `shf (@[borrowed] b : List) : List := (⟨b⟩ : S).1` (a borrowed value in a `@[shared]` field) + runCase "borrow: a borrowed value stored in a @[shared] field and returned" [(shf, body [par .borrowed] (.proj S 0 (app (.const sboxR .val) [v 0]) .val))] shf oneList (some .borrowEscape) false -] /-! ### Once -/ def twiceCall := mem 130 def onceCall := mem 131 -def onceCases : List LSpec.TestSeq := [ +def onceCases : LSpec.Spec := do runCase "once: a once parameter called twice" [(twiceCall, body [par .once .val arrowSk] (add (app (v 0) [.natLit 1] .leaf) (app (v 0) [.natLit 2] .leaf)) .shared .leaf)] twiceCall oneFun - (some .onceReentry) false, + (some .onceReentry) false runCase "once: a once parameter called once" [(onceCall, body [par .once .val arrowSk] (app (v 0) [.natLit 1] .leaf) .shared .leaf)] onceCall oneFun none true -] /-! ### Captures and partial applications -/ @@ -363,25 +361,24 @@ def capOuter := mem 141 def capPlain := mem 142 def papT := mem 143 -def captureCases : List LSpec.TestSeq := [ - -- `capOnce (@unique xs) := let g := fun u => consume xs; g 0 + g 1` +def captureCases : LSpec.Spec := do + -- `capOnce (@[unique] xs) := let g := fun u => consume xs; g 0 + g 1` runCase "capture: a closure consuming its capture called twice" [(capOnce, body [par .unique] (.letE (.value .many) .val (lam (par .many .leaf) (app (.const consumeR .val) [v 1] .leaf) .shared .leaf) (add (app (v 0) [.natLit 0] .leaf) (app (v 0) [.natLit 1] .leaf))) .shared .leaf)] capOnce oneList - (some .revokedUse) false, - -- `capOuter (@unique xs) := let g := fun u => len xs; len xs` + (some .revokedUse) false + -- `capOuter (@[unique] xs) := let g := fun u => len xs; len xs` runCase "capture: a unique binding captured, then read outside" [(capOuter, body [par .unique] (.letE (.value .many) .val (lam (par .many .leaf) (lenOf (v 1)) .shared .leaf) (lenOf (v 1))) - .shared .leaf)] capOuter oneList (some .revokedUse) false, + .shared .leaf)] capOuter oneList (some .revokedUse) false -- `capPlain (xs : List) := let g := fun u => len xs; g 0 + len xs` runCase "capture: a shared binding captured and read" [(capPlain, body [par] (.letE (.value .many) .val (lam (par .many .leaf) (lenOf (v 1)) .shared .leaf) - (add (app (v 0) [.natLit 0] .leaf) (lenOf (v 1)))) .shared .leaf)] capPlain oneList none true, - -- `papT (@unique xs) := let g := consume2 xs; len xs` + (add (app (v 0) [.natLit 0] .leaf) (lenOf (v 1)))) .shared .leaf)] capPlain oneList none true + -- `papT (@[unique] xs) := let g := consume2 xs; len xs` runCase "capture: a partial application transfers its unique argument" [(papT, body [par .unique] (.letE (.value .many) .val (app (.const consume2R .val) [v 0]) (lenOf (v 1))) .shared .leaf)] papT oneList (some .revokedUse) false -] /-! ### Skeletons and statics -/ @@ -390,37 +387,36 @@ def callUseOk := mem 151 def badStatic := mem 152 def okStatic := mem 153 -def skeletonCases : List LSpec.TestSeq := [ - -- `callUse (xs) := use (fun (@unique y) => consume y) xs` +def skeletonCases : LSpec.Spec := do + -- `callUse (xs) := use (fun (@[unique] y) => consume y) xs` runCase "skeleton: a closure with a unique binder at a plain arrow" [(callUse, body [par] (app (.const useR .val) [lam (par .unique) (app (.const consumeR .val) [v 0] .leaf) .shared .leaf, v 0] .leaf) - .shared .leaf)] callUse oneList (some .revokedUse) false, + .shared .leaf)] callUse oneList (some .revokedUse) false runCase "skeleton: a closure with a plain binder at a plain arrow" [(callUseOk, body [par] (app (.const useR .val) [lam (par .many) (lenOf (v 0)) .shared .leaf, v 0] .leaf) .shared .leaf)] - callUseOk oneList none true, + callUseOk oneList none true -- `badStatic := consume tbl + len tbl` runCase "static: a static given away, then read" [(badStatic, body [] (add (app (.const consumeR .val) [.const tblR .val] .leaf) (lenOf (.const tblR .val))) .shared .leaf)] badStatic - noArgs (some .revokedUse) false, + noArgs (some .revokedUse) false runCase "static: a static read twice" [(okStatic, body [] (add (lenOf (.const tblR .val)) (lenOf (.const tblR .val))) .shared .leaf)] okStatic noArgs none true -] /-! ### Limits and the fast path -/ /-- A step limit declines. -/ -def limitCase : LSpec.TestSeq := - .individualIO "limits: the step limit declines" none (do +def limitCase : LSpec.Spec := do + it "limits: the step limit declines" do let verdict := checkBodies { steps := 3 } (prog []) [lenR] let ok := match verdict with | .decline _ => true | _ => false - return (ok, 0, 0, if ok then none else some (verdictName verdict))) .done + expect ok (verdictName verdict) /-- A closure of default records is accepted without reading; an annotated axiom is read and refused outside the extern set, accepted inside it. -/ -def fastPathCase : LSpec.TestSeq := - .individualIO "fast path and externs: default records unread; an annotated axiom only as an extern" none (do +def fastPathCase : LSpec.Spec := do + it "fast path and externs: default records unread; an annotated axiom only as an extern" do let plain : Ixon.Constant := { info := .axio ⟨false, 0, .sort 0⟩, sharing := #[], refs := #[], univs := #[.zero] } let moded : Ixon.Constant := @@ -437,8 +433,7 @@ def fastPathCase : LSpec.TestSeq := let ok := (match v1 with | .accept 0 true => true | _ => false) && (match v2 with | .refuse _ w => (w.splitOn "not in the extern set").length > 1 | _ => false) && (match v3 with | .accept _ false => true | _ => false) - return (ok, 0, 0, if ok then none else - some s!"{verdictName v1}; {verdictName v2}; {verdictName v3}")) .done + expect ok s!"{verdictName v1}; {verdictName v2}; {verdictName v3}" /-! ### Must-reject cases: an erased field at an alternative -/ @@ -451,19 +446,18 @@ def altConst := mem 161 def secondOf := mem 162 def altLam := mem 163 -def alternativeCases : List LSpec.TestSeq := [ +def alternativeCases : LSpec.Spec := do -- `firstOf (a : List) (b : Nat) : List := a`; `altConst (k : Key) := Key.casesOn k firstOf` runCase "must-reject: an erased field passed to an alternative that is not a λ" [ (firstOf, body [par, par .many .leaf] (v 1)), (altConst, body [par] (.case caseK (v 0) #[.const firstOf .val] #[] .val))] - altConst oneKey (some .erasedRead) false, - -- `secondOf (b : Nat) : Nat := b`; `altLam (k : Key) := Key.casesOn k (fun (@erased g) => secondOf)` + altConst oneKey (some .erasedRead) false + -- `secondOf (b : Nat) : Nat := b`; `altLam (k : Key) := Key.casesOn k (fun (@[erased] g) => secondOf)` runCase "erased: a λ alternative binds the erased field, the rest passed on" [ (secondOf, body [par .many .leaf] (v 0 .leaf) .shared .leaf), (altLam, body [par] (.case caseK (v 0) #[lam (par .erased) (.const secondOf .val) .shared .leaf] #[] .leaf) .shared .leaf)] altLam oneKey none true -] /-! ### Findings of the mode study (REPLY-2-TO-IXVM.md §4), with their controls @@ -474,16 +468,16 @@ the kernel package alone. Under the owner's provisional leaf ruling (L1: a number is never confined), the programs of findings 1, 2, 3, 12 and 17 run a value and are accepted (marked `L1`). -/ --- Finding 1: `idN (n : Nat) : Nat := n`; `g4 (@borrowed n : Nat) : Nat := idN n` +-- Finding 1: `idN (n : Nat) : Nat := n`; `g4 (@[borrowed] n : Nat) : Nat := idN n` def idN := mem 300 def g4 := mem 301 def g4b := mem 341 --- Finding 2: `app1 (f : Unit → Nat) : Nat := f ()`; `g3 (@borrowed n : Nat) : Nat := app1 (fun _ => n)` +-- Finding 2: `app1 (f : Unit → Nat) : Nat := f ()`; `g3 (@[borrowed] n : Nat) : Nat := app1 (fun _ => n)` def app1 := mem 302 def g3 := mem 303 def g3p := mem 342 -- Finding 3: `bad (h : List Nat = Nat) (xs : List Nat) : Nat := cast h (id xs)`; --- `g2 (h : Nat = List Nat) (h' : List Nat = Nat) (@borrowed n : Nat) : Nat := bad h' (cast h n)` +-- `g2 (h : Nat = List Nat) (h' : List Nat = Nat) (@[borrowed] n : Nat) : Nat := bad h' (cast h n)` def EqI := mem 6 def reflR := ctr 6 0 def caseEq : CaseInfo := { ind := EqI, arity := 4, major := 2, alts := #[{ alt := 3, args := #[] }] } @@ -498,7 +492,7 @@ def eqDefs : List (Ref × RunDef) := [(EqI, .ind #[reflR]), (reflR, .ctor EqI 0 (idR, body [par .many .irr, par] (v 0)), (bad3, body [par .many .irr, parL] (.case caseEq .irr #[app (.const idR .val) [.irr, v 0]] #[] .leaf) .shared .leaf)] def in3 : Heap × List Val := let (b, n) := ({} : HB).alloc (.num 7); (b.heap, [.imm .irr, .imm .irr, n]) --- Finding 7: `f (a b : Nat) (@erased x : List Nat) (c d e : Nat) : Nat := a`, `g` the same +-- Finding 7: `f (a b : Nat) (@[erased] x : List Nat) (c d e : Nat) : Nat := a`, `g` the same -- parameters, `g a b x c d e := f a b x c d e`; the control has the erased parameter first def fV := mem 335 def gV := mem 336 @@ -527,8 +521,8 @@ def in7 : Heap × List Val := def in7x : Heap × List Val := let (b, ns) := fiveNats; (b.heap, .imm .irr :: ns) def fuels0to12 : List Nat := List.range 13 ++ [100000] --- Finding 8: `dup (@unique x : List Nat) : Nat := consume (x :: x)`; `dup2 … := consume [x, x]`; --- the control `pairOk (@unique x y : List Nat) : Nat := consume (x :: y)` +-- Finding 8: `dup (@[unique] x : List Nat) : Nat := consume (x :: x)`; `dup2 … := consume [x, x]`; +-- the control `pairOk (@[unique] x y : List Nat) : Nat := consume (x :: y)` def dup := mem 315 def dup2 := mem 345 def pairOk := mem 346 @@ -536,14 +530,14 @@ def twoLists : Heap × List Val := let (b, xs) := ({} : HB).list [1, 2] let (b, ys) := b.list [3] (b.heap, [xs, ys]) --- Finding 9: `g5 (@borrowed xs : List Nat) : List Nat := let f := fun _ => xs; f 0`; the control `g5p` +-- Finding 9: `g5 (@[borrowed] xs : List Nat) : List Nat := let f := fun _ => xs; f 0`; the control `g5p` -- with `xs` plain def g5 := mem 317 def g5p := mem 353 -- Found with repair D: a partial application of a function value holding a value moved into it is --- once-only. `kc17 (@unique a : List Nat) (n : Nat) : Nat := n`; `kc3 (@unique a) (b c : Nat) : Nat := b`; --- `d1 (k : (@unique a : List Nat) → Nat → Nat) (@unique x) : Nat := let h := k x; h 1 + h 2`, `d1h … := k x 1`; --- `d2 (@unique x) : Nat := let h := kc3 x; let h2 := h 1; h2 2 + h2 3`, `d2h … := let h := kc3 x; h 1 2` +-- once-only. `kc17 (@[unique] a : List Nat) (n : Nat) : Nat := n`; `kc3 (@[unique] a) (b c : Nat) : Nat := b`; +-- `d1 (k : (@[unique] a : List Nat) → Nat → Nat) (@[unique] x) : Nat := let h := k x; h 1 + h 2`, `d1h … := k x 1`; +-- `d2 (@[unique] x) : Nat := let h := kc3 x; let h2 := h 1; h2 2 + h2 3`, `d2h … := let h := kc3 x; h 1 2` def kc17 := mem 347 def d1 := mem 348 def d1h := mem 349 @@ -557,8 +551,8 @@ def inD1 : Heap × List Val := let (b, xs) := ({} : HB).list [1, 2] let (b, k) := b.alloc (.pap kc17 #[]) (b.heap, [k, xs]) --- Finding 13: `use13 (k : (@borrowed a : List Nat) → Nat → Nat) (@unique y : List Nat) : Nat := --- k y (consume y)`, with `kk (@borrowed a : List Nat) (n : Nat) : Nat := match a with | [] => 0 | _ => 1` +-- Finding 13: `use13 (k : (@[borrowed] a : List Nat) → Nat → Nat) (@[unique] y : List Nat) : Nat := +-- k y (consume y)`, with `kk (@[borrowed] a : List Nat) (n : Nat) : Nat := match a with | [] => 0 | _ => 1` -- given as `k` def sk13 : Skel := .arrow .borrowed .data .shared (.arrow .many .data .shared .data) def kk := mem 327 @@ -572,7 +566,7 @@ def in13 : Heap × List Val := let (b, f) := b.alloc (.pap kk #[]) (b.heap, [f, xs]) -- Found with repair N: a spine longer than the checker's depth left at it. `S6` is a structure of --- five `Nat` fields and a `@shared` `List Nat` field; `g6 (@borrowed xs : List Nat) : List Nat := +-- five `Nat` fields and a `@[shared]` `List Nat` field; `g6 (@[borrowed] xs : List Nat) : List Nat := -- (S6.mk 1 2 3 4 5 xs).sh`, checked at depth 6 (its spine of six arguments is cut at 4 as landed) -- and at the default depth; the control `g6p` has `xs` plain def S6 := mem 354 @@ -585,9 +579,9 @@ def s6Defs : List (Ref × RunDef) := [(S6, .ind #[s6mk]), [.natLit 1, .natLit 2, .natLit 3, .natLit 4, .natLit 5, v 0]) .val)), (g6p, body [par] (.proj S6 5 (app (.const s6mk .val) [.natLit 1, .natLit 2, .natLit 3, .natLit 4, .natLit 5, v 0]) .val))] --- Findings 10 and 11: `callTwice (f : Nat → Nat) : Nat := f 0 + f 1`; `callOnce (@once f : Nat → Nat) : Nat := f 0`; --- `bad10 (@unique xs) := callTwice (fun _ => consume xs)`; `alias10 (@unique xs) := let g := fun _ => consume xs; --- let h := g; h 0 + g 0`; `h11 (@once f) := callTwice f`; the controls `ok10`, `ok11` call `callOnce` instead +-- Findings 10 and 11: `callTwice (f : Nat → Nat) : Nat := f 0 + f 1`; `callOnce (@[once] f : Nat → Nat) : Nat := f 0`; +-- `bad10 (@[unique] xs) := callTwice (fun _ => consume xs)`; `alias10 (@[unique] xs) := let g := fun _ => consume xs; +-- let h := g; h 0 + g 0`; `h11 (@[once] f) := callTwice f`; the controls `ok10`, `ok11` call `callOnce` instead def callTwice := mem 319 def bad10 := mem 320 def alias10 := mem 321 @@ -600,10 +594,10 @@ def onceDefs : List (Ref × RunDef) := [ .shared .leaf), (callOnce, body [par .once .val arrowSk] (app (v 0) [.natLit 0] .leaf) .shared .leaf)] def consumeClo : Term := lam (par .many .leaf) (app (.const consumeR .val) [v 1] .leaf) .shared .leaf --- Finding 12: `addB (@borrowed n : Nat) : Nat → Nat := Nat.add n`; the control `addP` with `n` plain +-- Finding 12: `addB (@[borrowed] n : Nat) : Nat → Nat := Nat.add n`; the control `addP` with `n` plain def addB := mem 325 def addP := mem 362 --- Finding 16: `use16 (k : List Nat → Nat → Nat) (@unique y : List Nat) (b : E) : Nat := +-- Finding 16: `use16 (k : List Nat → Nat → Nat) (@[unique] y : List Nat) (b : E) : Nat := -- (match b with | e0 => k | e1 => k) y (consume y)`, the case of class leaf, with -- `kk16 (a : List Nat) (n : Nat) : Nat := len a` given as `k`; the control `use16p` has `y` plain -- and applies the case to `y` and `1` @@ -624,11 +618,11 @@ def in16 : Heap × List Val := let (b, k) := b.alloc (.pap kk16 #[]) (b.heap, [k, xs, .imm (.con e0R)]) -- Found after repair E (repair Q): `useBox (b : Box (Nat → Nat)) : Nat := b.1 0 + b.1 1`; --- `bad11b (@once f : Nat → Nat) : Nat := useBox ⟨f⟩`; the control `ok11b` has `f` plain +-- `bad11b (@[once] f : Nat → Nat) : Nat := useBox ⟨f⟩`; the control `ok11b` has `f` plain def useBox := mem 360 def bad11b := mem 361 def ok11b := mem 380 --- Repair R: `retAlt (@once f : Nat → Nat) (b : E) : Nat := callTwice (match b with | e0 => f | e1 => f)`; +-- Repair R: `retAlt (@[once] f : Nat → Nat) (b : E) : Nat := callTwice (match b with | e0 => f | e1 => f)`; -- the control `retAltP` has `f` plain def retAlt := mem 377 def retAltP := mem 387 @@ -636,7 +630,7 @@ def funAndE0 : Heap × List Val := let (b, f) := ({} : HB).alloc (.pap incR #[]) (b.heap, [f, .imm (.con e0R)]) def retAltBody : Term := app (.const callTwice .val) [.case caseE (v 0 .imm) #[v 1, v 1] #[] .val] .leaf --- Repair S: `retF (@once f : Nat → Nat) : Nat → Nat := f`; `useRet (@once f) : Nat := let h := retF f; h 0 + h 1`; +-- Repair S: `retF (@[once] f : Nat → Nat) : Nat → Nat := f`; `useRet (@[once] f) : Nat := let h := retF f; h 0 + h 1`; -- the control `useRetP` calls `retP`, the same with `f` plain def retF := mem 367 def retP := mem 368 @@ -644,15 +638,15 @@ def useRet := mem 378 def useRetP := mem 388 def useRetBody (r : Ref) : Term := .letE (.value .many) .val (app (.const r .val) [v 0] .val) (add (app (v 0) [.natLit 0] .leaf) (app (v 0) [.natLit 1] .leaf)) --- Repair T: `twiceOnce (@once f : Nat → Nat) : Nat := callOnce f + callOnce f`; the control +-- Repair T: `twiceOnce (@[once] f : Nat → Nat) : Nat := callOnce f + callOnce f`; the control -- `twiceOnceP` has `f` plain def twiceOnce := mem 379 def twiceOnceP := mem 389 def twiceOnceBody : Term := add (app (.const callOnce .val) [v 0] .leaf) (app (.const callOnce .val) [v 0] .leaf) --- Finding 17 (repair O): a unique mode on a leaf. `u17a (@borrowed n : Nat) : Nat := let (@unique m) := n; m` --- (control `u17ap`, `n` plain); `idU (w : WrapN) : @unique WrapN := w`, `u17b (@borrowed w : WrapN) : WrapN := idU w`; --- `idUP {α} (@unique x : α) : @unique α := x`, `u17c (@borrowed n : Nat) : Nat := idUP n` (control `u17cp`, `n` plain); --- `u17d (@borrowed w : WrapN) : Nat := match w with | ⟨@unique m⟩ => m` (control `u17dp`, `w` plain) +-- Finding 17 (repair O): a unique mode on a leaf. `u17a (@[borrowed] n : Nat) : Nat := let (@[unique] m) := n; m` +-- (control `u17ap`, `n` plain); `idU (w : WrapN) : @[unique] WrapN := w`, `u17b (@[borrowed] w : WrapN) : WrapN := idU w`; +-- `idUP {α} (@[unique] x : α) : @[unique] α := x`, `u17c (@[borrowed] n : Nat) : Nat := idUP n` (control `u17cp`, `n` plain); +-- `u17d (@[borrowed] w : WrapN) : Nat := match w with | ⟨@[unique] m⟩ => m` (control `u17dp`, `w` plain) def WNi := mem 420 def wnR := ctr 420 0 def caseWN : CaseInfo := { ind := WNi, arity := 2, major := 0, alts := #[{ alt := 1, args := #[.field 0] }] } @@ -677,7 +671,7 @@ def oDefs : List (Ref × RunDef) := [ (u17cp, body [par .many .leaf] (app (.const idUP .val) [.irr, v 0 .leaf] .leaf) .shared .leaf), (u17d, body [par .borrowed .leaf] matchWNU .shared .leaf), (u17dp, body [par .many .leaf] matchWNU .shared .leaf)] --- Finding 18 (repair P): `mkSB (x : List Nat) : SBox := SBox.mk x`; `leak18 (@borrowed xs : List Nat) : +-- Finding 18 (repair P): `mkSB (x : List Nat) : SBox := SBox.mk x`; `leak18 (@[borrowed] xs : List Nat) : -- List Nat := (mkSB xs).val`, `leak18m … := match mkSB xs with | ⟨y⟩ => y`; the controls have `xs` plain def mkSB := mem 430 def leak18 := mem 445 @@ -688,9 +682,9 @@ def caseS : CaseInfo := { ind := S, arity := 2, major := 0, alts := #[{ alt := 1 def mkSBDef : Ref × RunDef := (mkSB, body [par] (app (.const sboxR .val) [v 0])) def projSB : Term := .proj S 0 (app (.const mkSB .val) [v 0]) .val def matchSB : Term := .case caseS (app (.const mkSB .val) [v 0]) #[lam par (v 0) .shared .val] #[] .val --- Repair U / Fix 2: `mkSBU (x : List Nat) : @unique SBox := SBox.mk x` is itself refused by Fix 2 +-- Repair U / Fix 2: `mkSBU (x : List Nat) : @[unique] SBox := SBox.mk x` is itself refused by Fix 2 -- (`paramVal` gives plain `.many` params caller region `1`, since any caller may pass a borrowed value); --- the sound control `mkSBUU (@unique x : List Nat) : @unique SBox := SBox.mk x` requires `@unique x`. +-- the sound control `mkSBUU (@[unique] x : List Nat) : @[unique] SBox := SBox.mk x` requires `@[unique] x`. def mkSBU := mem 431 def mkSBUU := mem 240 def isSB := mem 441 @@ -800,7 +794,7 @@ def altBor8Term : Term := [app (.const consR .val) [.irr, v 0 .leaf, app (.const nilR .val) [.irr] .imm], .natLit 0]) #[lam (par .borrowed) (lam (par .many .leaf) (v 1) .shared .val) .borrowed .val] #[] .val def preProofDefs : List (Ref × RunDef) := [ - -- Fix 2 (`evil6`): plain param wrapped in `@shared` field and transferred uniquely + -- Fix 2 (`evil6`): plain param wrapped in `@[shared]` field and transferred uniquely (inner6, body [par] (app (.const consumeSR .val) [app (.const sboxR .val) [v 0]] .leaf) .shared .leaf), (evil6, body [par .borrowed] (app (.const inner6 .val) [v 0] .leaf) .shared .leaf), -- Repair U preserved for `.unique`-returning externs (`#87`) @@ -863,7 +857,7 @@ def preProofDefs : List (Ref × RunDef) := [ (add (lenOf (v 1)) (app (.const consumeR .val) [v 0] .leaf)) .shared .leaf), (evil9bLend, body [par .unique] (app (.const plainUniq9b .val) [v 0, v 0] .leaf) .shared .leaf), (ok9b, body [par .unique, par .unique] (app (.const plainUniq9b .val) [v 1, v 0] .leaf) .shared .leaf), - -- Fix 10 (`admitsNA`): 2-hop `.arrow → .unknown → .data` hiding under `@unique`, `@once`, and contravariant `@once` + -- Fix 10 (`admitsNA`): 2-hop `.arrow → .unknown → .data` hiding under `@[unique]`, `@[once]`, and contravariant `@[once]` (pfG2_11, body [par .unique, par .many .leaf] (app (.const consumeR .val) [v 1] .leaf) .shared .leaf), (pfEvil11b, body [par .many .val (.arrow .unique .data .shared .data), par .unique] (app (v 1) [v 0]) .shared .val .data), @@ -920,7 +914,7 @@ def preProofDefs : List (Ref × RunDef) := [ (.case pfCasePair (v 0) #[lam (par .unique) (lam (par .many .leaf) (v 1) .shared .val) .unique .val] #[] .val)) .unique .val), - -- Fix 12 (`anProj`/`caseField` preserve `deps` on `@shared` fields) + -- Fix 12 (`anProj`/`caseField` preserve `deps` on `@[shared]` fields) (pfSW14I, .ind #[pfSW14C]), (pfSW14C, .ctor pfSW14I 0 0 #[fld .val .shared, fld .leaf .inherited]), (pfMkWrap14, body [par] (app (.const pfSW14C .val) [v 0, .natLit 0])), @@ -952,7 +946,7 @@ def preProofDefs : List (Ref × RunDef) := [ (.letE (.value .unique) .val (app (.const pfBox15C .val) [v 1, v 0] .val) (.natLit 0)) .shared .leaf)] -- Finding 15 (repair J): `NP` with one constructor and two `Nat` fields; `mkK {α β} (a : α) (b : β) : Nat → α := --- fun _ => a`; `g15 (@borrowed k : NP) : Nat → Nat := NP.casesOn k (@mkK Nat Nat)`, on an input whose first +-- fun _ => a`; `g15 (@[borrowed] k : NP) : Nat → Nat := NP.casesOn k (@mkK Nat Nat)`, on an input whose first -- field holds a list cell (ill-typed): a stuck run since repair J; on a well-typed input, a value def NP := mem 8 def npR := ctr 8 0 @@ -984,8 +978,8 @@ are out of fuel up to some fuel and a value from there on (the evaluator spends fuel per step and does not change what it runs with it), and the checker accepts exactly when `accept`. -/ def fuelCase (label : String) (defs : List (Ref × RunDef)) (entry : Ref) (input : Heap × List Val) - (fuels : List Nat) (accept : Bool) (toCheck : List Ref := [entry]) : LSpec.TestSeq := - .individualIO label none (do + (fuels : List Nat) (accept : Bool) (toCheck : List Ref := [entry]) : LSpec.Spec := + it label do let P := prog defs let os := fuels.map fun f => runR P noExtern f entry input.1 input.2 let rest := os.dropWhile fun o => match o with | .outOfFuel => true | _ => false @@ -993,218 +987,217 @@ def fuelCase (label : String) (defs : List (Ref × RunDef)) (entry : Ref) (input let verdict := checkBodies {} P toCheck let checkOk := verdict.isAccept == accept let msg := s!"runs: {", ".intercalate (os.map outcomeName)}; checker: {verdictName verdict}" - return (runOk && checkOk, 0, 0, if runOk && checkOk then none else some msg)) .done + expect (runOk && checkOk) msg -def findingCases : List LSpec.TestSeq := [ +def findingCases : LSpec.Spec := do runCase "finding 1: a borrowed number through a call of `Nat → Nat` (its parameter read as no-leaf)" [idNDef true, (g4, body [par .borrowed .leaf] (app (.const idN .val) [v 0 .leaf] .leaf) .shared .leaf)] - g4 oneNat none true, -- L1 W1: borrowEscape before -- L1: accepted + g4 oneNat none true -- L1 W1: borrowEscape before -- L1: accepted runCase "finding 1, control: the parameter not read as no-leaf" [idNDef false, (g4, body [par .borrowed .leaf] (app (.const idN .val) [v 0 .leaf] .leaf) .shared .leaf)] - g4 oneNat none true, -- L1 W1: borrowEscape before -- L1: accepted + g4 oneNat none true -- L1 W1: borrowEscape before -- L1: accepted runCase "finding 1, control: the result returned borrowed" [idNDef true, (g4b, body [par .borrowed .leaf] (app (.const idN .val) [v 0 .leaf] .leaf) .borrowed .leaf)] - g4b oneNat none true, + g4b oneNat none true runCase "finding 2: a borrowed number captured by a closure passed at a function type" [app1Def true, (g3, body [par .borrowed .leaf] (app (.const app1 .val) [lam (par .many .leaf) (v 1 .leaf) .shared .leaf] .leaf) .shared .leaf)] - g3 oneNat none true [g3, app1], -- L1 W1: borrowEscape before -- L1: accepted + g3 oneNat none true [g3, app1] -- L1 W1: borrowEscape before -- L1: accepted runCase "finding 2, control: the parameter not read as no-leaf" [app1Def false, (g3, body [par .borrowed .leaf] (app (.const app1 .val) [lam (par .many .leaf) (v 1 .leaf) .shared .leaf] .leaf) .shared .leaf)] - g3 oneNat none true [g3, app1], -- L1 W1: borrowEscape before -- L1: accepted + g3 oneNat none true [g3, app1] -- L1 W1: borrowEscape before -- L1: accepted runCase "finding 2, control: the captured number not borrowed" [app1Def true, (g3p, body [par .many .leaf] (app (.const app1 .val) [lam (par .many .leaf) (v 1 .leaf) .shared .leaf] .leaf) .shared .leaf)] - g3p oneNat none true [g3p, app1], + g3p oneNat none true [g3p, app1] runCase "finding 3: a borrowed number cast to a list under an absurd hypothesis" (eqDefs ++ [(g2, body [par .many .irr, par .many .irr, par .borrowed .leaf] (app (.const bad3 .val) [.irr, .case caseEq .irr #[v 0 .leaf] #[] .val] .leaf) .shared .leaf)]) - g2 in3 none true [g2, bad3], -- L1 W1: borrowEscape before -- L1: accepted + g2 in3 none true [g2, bad3] -- L1 W1: borrowEscape before -- L1: accepted fuelCase "finding 7: a call of six arguments, the third erased, at every fuel from 0 to 12" - p7Defs gV in7 fuels0to12 true [gV, fV], - fuelCase "finding 7, control: the erased parameter first" p7xDefs gXV in7x fuels0to12 true [gXV, fXV], + p7Defs gV in7 fuels0to12 true [gV, fV] + fuelCase "finding 7, control: the erased parameter first" p7xDefs gXV in7x fuels0to12 true [gXV, fXV] runCase "finding 8: a unique list stored twice in one cell, the cell given away" [(dup, body [par .unique] (app (.const consumeR .val) [app (.const consR .val) [.irr, v 0, v 0]] .leaf) - .shared .leaf)] dup oneList (some .revokedUse) false, + .shared .leaf)] dup oneList (some .revokedUse) false runCase "finding 8: a unique list stored in a cell and in a cell inside it, the cell given away" [(dup2, body [par .unique] (app (.const consumeR .val) [app (.const consR .val) [.irr, v 0, app (.const consR .val) [.irr, v 0, app (.const nilR .val) [.irr] .imm]]] .leaf) .shared .leaf)] - dup2 oneList (some .revokedUse) false, + dup2 oneList (some .revokedUse) false runCase "finding 8, control: two unique lists in one cell, the cell given away" [(pairOk, body [par .unique, par .unique] (app (.const consumeR .val) [app (.const consR .val) [.irr, v 1, v 0]] .leaf) .shared .leaf)] - pairOk twoLists none true, + pairOk twoLists none true runCase "finding 9: a closure capturing a borrowed list, applied, its result returned" [(g5, body [par .borrowed] (.letE (.value .many) .val (lam (par .many .leaf) (v 1) .shared .val) - (app (v 0) [.natLit 0])))] g5 oneList (some .borrowEscape) false, + (app (v 0) [.natLit 0])))] g5 oneList (some .borrowEscape) false runCase "finding 9, control: the list not borrowed" [(g5p, body [par] (.letE (.value .many) .val (lam (par .many .leaf) (v 1) .shared .val) - (app (v 0) [.natLit 0])))] g5p oneList none true, + (app (v 0) [.natLit 0])))] g5p oneList none true runCase "finding 13: a function value applied to a borrowed list, then to its consumption" - p13Defs use13 in13 (some .revokedUse) false [use13, kk], + p13Defs use13 in13 (some .revokedUse) false [use13, kk] runCase "a partial application of a function value at a unique binder, called twice" (kcDefs ++ [(d1, body [par .many .val skU, par .unique] (.letE (.value .many) .val (app (v 1) [v 0] .val) (add (app (v 0) [.natLit 1] .leaf) (app (v 0) [.natLit 2] .leaf))) .shared .leaf)]) - d1 inD1 (some .revokedUse) false, + d1 inD1 (some .revokedUse) false runCase "a partial application of a once-only partial application, called twice" (kcDefs ++ [(d2, body [par .unique] (.letE (.value .many) .val (app (.const kc3 .val) [v 0] .val) (.letE (.value .many) .val (app (v 0) [.natLit 1] .val) (add (app (v 0) [.natLit 2] .leaf) (app (v 0) [.natLit 3] .leaf)))) .shared .leaf)]) - d2 oneList (some .revokedUse) false, + d2 oneList (some .revokedUse) false -- refused since repair D though the runs are clean: the result's aliases include the moved -- argument (d1h) or the consumed once-only binding (d2h) runCase "a function value at a unique binder applied to all its arguments (refused, runs clean)" (kcDefs ++ [(d1h, body [par .many .val skU, par .unique] (app (v 1) [v 0, .natLit 1] .leaf) .shared .leaf)]) - d1h inD1 none false, + d1h inD1 none false runCase "a once-only partial application applied to all its remaining arguments (refused, runs clean)" (kcDefs ++ [(d2h, body [par .unique] (.letE (.value .many) .val (app (.const kc3 .val) [v 0] .val) (app (v 0) [.natLit 1, .natLit 2] .leaf)) .shared .leaf)]) - d2h oneList none false, - runCase "a spine longer than the checker's depth left at it: a borrowed list stored in a @shared field" - s6Defs g6 oneList (some .borrowEscape) false [g6] { depth := 6 }, - runCase "the same at the default depth" s6Defs g6 oneList (some .borrowEscape) false, - runCase "the same, the list not borrowed, at depth 6" s6Defs g6p oneList none true [g6p] { depth := 6 }, + d2h oneList none false + runCase "a spine longer than the checker's depth left at it: a borrowed list stored in a @[shared] field" + s6Defs g6 oneList (some .borrowEscape) false [g6] { depth := 6 } + runCase "the same at the default depth" s6Defs g6 oneList (some .borrowEscape) false + runCase "the same, the list not borrowed, at depth 6" s6Defs g6p oneList none true [g6p] { depth := 6 } runCase "finding 10: a closure consuming its capture, lent to a body that calls it twice" (onceDefs ++ [(bad10, body [par .unique] (app (.const callTwice .val) [consumeClo] .leaf) .shared .leaf)]) - bad10 oneList (some .revokedUse) false [bad10, callTwice], + bad10 oneList (some .revokedUse) false [bad10, callTwice] runCase "finding 10: a closure consuming its capture, aliased by a let, both called" [(alias10, body [par .unique] (.letE (.value .many) .val consumeClo (.letE (.value .many) .val (v 0) (add (app (v 0) [.natLit 0] .leaf) (app (v 1) [.natLit 0] .leaf)))) - .shared .leaf)] alias10 oneList (some .revokedUse) false, + .shared .leaf)] alias10 oneList (some .revokedUse) false runCase "finding 10, control: the closure passed to a once parameter" (onceDefs ++ [(ok10, body [par .unique] (app (.const callOnce .val) [consumeClo] .leaf) .shared .leaf)]) - ok10 oneList none true [ok10, callOnce], + ok10 oneList none true [ok10, callOnce] runCase "finding 11: a once parameter passed to a body that calls it twice" (onceDefs ++ [(h11, body [par .once .val arrowSk] (app (.const callTwice .val) [v 0] .leaf) .shared .leaf)]) - h11 oneFun (some .onceReentry) false [h11, callTwice], + h11 oneFun (some .onceReentry) false [h11, callTwice] runCase "finding 11, control: a once parameter passed to a once parameter" (onceDefs ++ [(ok11, body [par .once .val arrowSk] (app (.const callOnce .val) [v 0] .leaf) .shared .leaf)]) - ok11 oneFun none true [ok11, callOnce], + ok11 oneFun none true [ok11, callOnce] runCase "finding 12: a primitive's partial application holding a borrowed number, returned" [(addB, body [par .borrowed .leaf] (app (.const addR .val) [v 0 .leaf] .val) .shared .val arrowSk)] - addB oneNat none true, -- L1 W1: borrowEscape before -- L1: accepted + addB oneNat none true -- L1 W1: borrowEscape before -- L1: accepted runCase "finding 12, control: the number not borrowed" [(addP, body [par .many .leaf] (app (.const addR .val) [v 0 .leaf] .val) .shared .val arrowSk)] - addP oneNat none true, + addP oneNat none true runCase "finding 16: a case's two extra arguments, the second consuming the first" (p16Defs ++ [(use16, body [par .many .val sk16, par .unique, par .many .imm] (.case caseE (v 0 .imm) #[v 2, v 2] #[v 1, app (.const consumeR .val) [v 1] .leaf] .leaf) .shared .leaf)]) - use16 in16 (some .revokedUse) false [use16, kk16], + use16 in16 (some .revokedUse) false [use16, kk16] runCase "finding 16, control: the extra arguments a plain list and a number" (p16Defs ++ [(use16p, body [par .many .val sk16, par .many, par .many .imm] (.case caseE (v 0 .imm) #[v 2, v 2] #[v 1, .natLit 1] .leaf) .shared .leaf)]) - use16p in16 none true [use16p, kk16], + use16p in16 none true [use16p, kk16] runCase "a once parameter stored in a cell, the cell lent to a body that calls the field twice" [useBoxDef, (bad11b, body [par .once .val arrowSk] (app (.const useBox .val) [app (.const boxR .val) [v 0]] .leaf) - .shared .leaf)] bad11b oneFun (some .onceReentry) false [bad11b, useBox], + .shared .leaf)] bad11b oneFun (some .onceReentry) false [bad11b, useBox] runCase "the same, the parameter plain" [useBoxDef, (ok11b, body [par .many .val arrowSk] (app (.const useBox .val) [app (.const boxR .val) [v 0]] .leaf) - .shared .leaf)] ok11b oneFun none true [ok11b, useBox], + .shared .leaf)] ok11b oneFun none true [ok11b, useBox] runCase "a once parameter returned by a case alternative, the case's value lent to a body that calls it twice" (onceDefs ++ p16Defs ++ [(retAlt, body [par .once .val arrowSk, par .many .imm] retAltBody .shared .leaf)]) - retAlt funAndE0 (some .onceReentry) false, + retAlt funAndE0 (some .onceReentry) false runCase "the same, the parameter plain" (onceDefs ++ p16Defs ++ [(retAltP, body [par .many .val arrowSk, par .many .imm] retAltBody .shared .leaf)]) - retAltP funAndE0 none true, + retAltP funAndE0 none true runCase "a once parameter returned, the result called twice by the caller" [(retF, body [par .once .val arrowSk] (v 0) .shared .val arrowSk), (useRet, body [par .once .val arrowSk] (useRetBody retF) .shared .leaf)] - useRet oneFun (some .onceReentry) false [useRet, retF], + useRet oneFun (some .onceReentry) false [useRet, retF] runCase "the same, the parameter plain" [(retP, body [par .many .val arrowSk] (v 0) .shared .val arrowSk), (useRetP, body [par .many .val arrowSk] (useRetBody retP) .shared .leaf)] - useRetP oneFun none true [useRetP, retP], + useRetP oneFun none true [useRetP, retP] runCase "a once parameter passed to two once parameters" (onceDefs ++ [(twiceOnce, body [par .once .val arrowSk] twiceOnceBody .shared .leaf)]) - twiceOnce oneFun (some .onceReentry) false [twiceOnce, callOnce], + twiceOnce oneFun (some .onceReentry) false [twiceOnce, callOnce] runCase "the same, the parameter plain" (onceDefs ++ [(twiceOnceP, body [par .many .val arrowSk] twiceOnceBody .shared .leaf)]) - twiceOnceP oneFun none true [twiceOnceP, callOnce], - runCase "finding 17: a borrowed number bound at a unique let, returned" oDefs u17a oneNat none true, -- L1 W1: borrowEscape before -- L1: accepted - runCase "finding 17, control: the number not borrowed" oDefs u17ap oneNat none true, + twiceOnceP oneFun none true [twiceOnceP, callOnce] + runCase "finding 17: a borrowed number bound at a unique let, returned" oDefs u17a oneNat none true -- L1 W1: borrowEscape before -- L1: accepted + runCase "finding 17, control: the number not borrowed" oDefs u17ap oneNat none true runCase "finding 17: a borrowed number through a unique result of class leaf" oDefs u17b oneNat - none true [u17b, idU], -- L1 W1: borrowEscape before -- L1: accepted + none true [u17b, idU] -- L1 W1: borrowEscape before -- L1: accepted runCase "finding 17: a borrowed number through a polymorphic unique result" oDefs u17c oneNat - none true [u17c, idUP], -- L1 W1: borrowEscape before -- L1: accepted - runCase "finding 17, control: the number not borrowed" oDefs u17cp oneNat none true [u17cp, idUP], + none true [u17c, idUP] -- L1 W1: borrowEscape before -- L1: accepted + runCase "finding 17, control: the number not borrowed" oDefs u17cp oneNat none true [u17cp, idUP] runCase "finding 17: a borrowed wrapper of a number matched, its field bound unique and returned" oDefs u17d oneNat - none true, -- L1 W1: borrowEscape before -- L1: accepted - runCase "finding 17, control: the wrapper not borrowed" oDefs u17dp oneNat none true, - runCase "finding 18: a borrowed list stored in a @shared field by a callee, projected" - [mkSBDef, (leak18, body [par .borrowed] projSB)] leak18 oneList (some .borrowEscape) false [leak18, mkSB], + none true -- L1 W1: borrowEscape before -- L1: accepted + runCase "finding 17, control: the wrapper not borrowed" oDefs u17dp oneNat none true + runCase "finding 18: a borrowed list stored in a @[shared] field by a callee, projected" + [mkSBDef, (leak18, body [par .borrowed] projSB)] leak18 oneList (some .borrowEscape) false [leak18, mkSB] runCase "finding 18, control: the list not borrowed" - [mkSBDef, (leak18p, body [par] projSB)] leak18p oneList none true [leak18p, mkSB], + [mkSBDef, (leak18p, body [par] projSB)] leak18p oneList none true [leak18p, mkSB] runCase "finding 18: the same field matched" - [mkSBDef, (leak18m, body [par .borrowed] matchSB)] leak18m oneList (some .borrowEscape) false [leak18m, mkSB], + [mkSBDef, (leak18m, body [par .borrowed] matchSB)] leak18m oneList (some .borrowEscape) false [leak18m, mkSB] runCase "finding 18, control: the list not borrowed" - [mkSBDef, (leak18mp, body [par] matchSB)] leak18mp oneList none true [leak18mp, mkSB], + [mkSBDef, (leak18mp, body [par] matchSB)] leak18mp oneList none true [leak18mp, mkSB] runCase "a borrowed list retained by a call whose result is unique" (uDefs ++ [(leakU, body [par .borrowed] isSBmk .shared .imm)]) leakU oneList (some .borrowEscape) false - [leakU, mkSBU, isSB], + [leakU, mkSBU, isSB] runCase "the same, the list unique (mkSBUU)" - (uDefs ++ [(leakUp, body [par .unique] isSBmkU .shared .imm)]) leakUp oneList none true [leakUp, mkSBUU, isSB], - runCase "pre-proof Fix 2 (evil6): plain param wrapped in @shared field and consumed uniquely" - preProofDefs evil6 oneList (some .borrowEscape) false [evil6, inner6], - runCase "pre-proof Repair U + extern (mkWeird): borrowed arg to .unique extern with @shared field" - preProofDefs leakWeirdU oneList (some .borrowEscape) false [leakWeirdU] {} extWeirdU, - runCase "pre-proof Repair U + extern control: @unique arg to .unique extern with @shared field" - preProofDefs okWeirdU oneList none true [okWeirdU] {} extWeirdU, + (uDefs ++ [(leakUp, body [par .unique] isSBmkU .shared .imm)]) leakUp oneList none true [leakUp, mkSBUU, isSB] + runCase "pre-proof Fix 2 (evil6): plain param wrapped in @[shared] field and consumed uniquely" + preProofDefs evil6 oneList (some .borrowEscape) false [evil6, inner6] + runCase "pre-proof Repair U + extern (mkWeird): borrowed arg to .unique extern with @[shared] field" + preProofDefs leakWeirdU oneList (some .borrowEscape) false [leakWeirdU] {} extWeirdU + runCase "pre-proof Repair U + extern control: @[unique] arg to .unique extern with @[shared] field" + preProofDefs okWeirdU oneList none true [okWeirdU] {} extWeirdU runCase "pre-proof Fix 3 (evil10): closure returning unique capture at .unique called twice" - preProofDefs evil10 oneList (some .revokedUse) false [evil10], + preProofDefs evil10 oneList (some .revokedUse) false [evil10] runCase "pre-proof Fix 3 control: closure returning unique capture at .unique called once" - preProofDefs ok10r oneList none true [ok10r], + preProofDefs ok10r oneList none true [ok10r] runCase "pre-proof Fix 4 (evil5d): multi-arg PAP via applyValue loses onceOnly" - preProofDefs stepOnce5 inG3 (some .revokedUse) false [stepOnce5, g3Fix], - runCase "pre-proof Fix 4 (evil5j): multi-arg @once PAP via applyValue called twice" - preProofDefs stepOnceF5 inGOnce (some .onceReentry) false [stepOnceF5, gOnce5], + preProofDefs stepOnce5 inG3 (some .revokedUse) false [stepOnce5, g3Fix] + runCase "pre-proof Fix 4 (evil5j): multi-arg @[once] PAP via applyValue called twice" + preProofDefs stepOnceF5 inGOnce (some .onceReentry) false [stepOnceF5, gOnce5] runCase "pre-proof Fix 6a: .prim PAP on borrowed .val arg refused" - preProofDefs primPap6 oneList (some .borrowEscape) false [primPap6], + preProofDefs primPap6 oneList (some .borrowEscape) false [primPap6] runCase "pre-proof Fix 7 (anCase killSrc): once-only closure returned from case alt called again via binding" - preProofDefs evilCaseOnce7 inCaseOnce7 (some .revokedUse) false [evilCaseOnce7], + preProofDefs evilCaseOnce7 inCaseOnce7 (some .revokedUse) false [evilCaseOnce7] runCase "pre-proof Fix 7 control: once-only closure returned from case alt called once" - preProofDefs okCaseOnce7 inCaseOnce7 none true [okCaseOnce7], + preProofDefs okCaseOnce7 inCaseOnce7 none true [okCaseOnce7] runCase "pre-proof Fix 8 (anAlt borrowed rename): .borrowed alt lambda renames closing region" - preProofDefs evilAltBor8 oneNat (some .borrowEscape) false [evilAltBor8], - runCase "pre-proof Fix 8 control: .borrowed alt lambda returned @borrowed" - preProofDefs okAltBor8 oneNat none true [okAltBor8], - runCase "pre-proof Fix 9a (applyValue valid after callResult): borrowed capture revoked by @unique arg" - preProofDefs evil9a oneList (some .revokedUse) false [evil9a, mkId2_9a], - runCase "pre-proof Fix 9a (curried PAP): ((f0 0) u) u revoked by @unique arg" - preProofDefs evil9aPap oneList (some .revokedUse) false [evil9aPap, f0Curried9a], - runCase "pre-proof Fix 9b (callResult post-loop valid): @borrowed precedes @unique on same binding" - preProofDefs evil9b oneList (some .revokedUse) false [evil9b, borUniq9b], - runCase "pre-proof Fix 9b (lendPlain): plain precedes @unique on same binding (leaf result)" - preProofDefs evil9bLend oneList (some .revokedUse) false [evil9bLend, plainUniq9b], - runCase "pre-proof Fix 9b control: distinct bindings at plain + @unique params" - preProofDefs ok9b twoLists none true [ok9b, plainUniq9b], - runCase "pre-proof Fix 10 (evil11): 2-hop .arrow -> .unknown -> .data under @unique arrow" - preProofDefs pfSeed11 oneList (some .revokedUse) false [pfSeed11, pfEvil11, pfEvil11b, pfG2_11], - runCase "pre-proof Fix 10 (evil10): 2-hop .arrow -> .unknown -> .data through @once param" - preProofDefs pfSeed10 oneList (some .revokedUse) false [pfSeed10, pfEvil10a, pfEvil10b, pfG3_10], - runCase "pre-proof Fix 10 (evil12): contravariant 2-hop .arrow -> .unknown -> .data in @once domain" - preProofDefs pfSeed12 oneList (some .revokedUse) false [pfSeed12, pfHop1_12, pfHop2_12, pfEvil10b, pfG3_10], - runCase "pre-proof Fix 10 control: @once (Nat -> List) called with non-arrow-returning onceOnly closure" - preProofDefs pfOkOnce10 oneList none true [pfOkOnce10, pfEvil10b], + preProofDefs evilAltBor8 oneNat (some .borrowEscape) false [evilAltBor8] + runCase "pre-proof Fix 8 control: .borrowed alt lambda returned @[borrowed]" + preProofDefs okAltBor8 oneNat none true [okAltBor8] + runCase "pre-proof Fix 9a (applyValue valid after callResult): borrowed capture revoked by @[unique] arg" + preProofDefs evil9a oneList (some .revokedUse) false [evil9a, mkId2_9a] + runCase "pre-proof Fix 9a (curried PAP): ((f0 0) u) u revoked by @[unique] arg" + preProofDefs evil9aPap oneList (some .revokedUse) false [evil9aPap, f0Curried9a] + runCase "pre-proof Fix 9b (callResult post-loop valid): @[borrowed] precedes @[unique] on same binding" + preProofDefs evil9b oneList (some .revokedUse) false [evil9b, borUniq9b] + runCase "pre-proof Fix 9b (lendPlain): plain precedes @[unique] on same binding (leaf result)" + preProofDefs evil9bLend oneList (some .revokedUse) false [evil9bLend, plainUniq9b] + runCase "pre-proof Fix 9b control: distinct bindings at plain + @[unique] params" + preProofDefs ok9b twoLists none true [ok9b, plainUniq9b] + runCase "pre-proof Fix 10 (evil11): 2-hop .arrow -> .unknown -> .data under @[unique] arrow" + preProofDefs pfSeed11 oneList (some .revokedUse) false [pfSeed11, pfEvil11, pfEvil11b, pfG2_11] + runCase "pre-proof Fix 10 (evil10): 2-hop .arrow -> .unknown -> .data through @[once] param" + preProofDefs pfSeed10 oneList (some .revokedUse) false [pfSeed10, pfEvil10a, pfEvil10b, pfG3_10] + runCase "pre-proof Fix 10 (evil12): contravariant 2-hop .arrow -> .unknown -> .data in @[once] domain" + preProofDefs pfSeed12 oneList (some .revokedUse) false [pfSeed12, pfHop1_12, pfHop2_12, pfEvil10b, pfG3_10] + runCase "pre-proof Fix 10 control: @[once] (Nat -> List) called with non-arrow-returning onceOnly closure" + preProofDefs pfOkOnce10 oneList none true [pfOkOnce10, pfEvil10b] runCase "pre-proof Fix 11 (evil13): local shared dep dropped by anCase deps.filter demotes own" - preProofDefs pfEvil13 pfInBoolTrue (some .revokedUse) false [pfEvil13], + preProofDefs pfEvil13 pfInBoolTrue (some .revokedUse) false [pfEvil13] runCase "pre-proof Fix 11 control: distinct local bindings in Weird.mk" - preProofDefs pfOk13 pfInBoolTrue none true [pfOk13], - runCase "pre-proof Fix 11 control: anAlt @unique return clears killed deps" - preProofDefs pfOkAltUniq oneList none true [pfOkAltUniq], - runCase "pre-proof Fix 12 (exploitProj): @shared projection keeps container deps across borrow lend" - preProofDefs pfEvil14Proj oneList (some .revokedUse) false [pfEvil14Proj, pfWrap14, pfMkWrap14], - runCase "pre-proof Fix 12 (exploitCase): @shared caseField keeps container deps across borrow lend" - preProofDefs pfEvil14Case oneList (some .revokedUse) false [pfEvil14Case, pfWrap14, pfMkWrap14], - runCase "pre-proof Fix 12 control: consuming match on @unique @shared-field struct" - preProofDefs pfOk14Consume oneList none true [pfOk14Consume, pfWrap14, pfMkWrap14], + preProofDefs pfOk13 pfInBoolTrue none true [pfOk13] + runCase "pre-proof Fix 11 control: anAlt @[unique] return clears killed deps" + preProofDefs pfOkAltUniq oneList none true [pfOkAltUniq] + runCase "pre-proof Fix 12 (exploitProj): @[shared] projection keeps container deps across borrow lend" + preProofDefs pfEvil14Proj oneList (some .revokedUse) false [pfEvil14Proj, pfWrap14, pfMkWrap14] + runCase "pre-proof Fix 12 (exploitCase): @[shared] caseField keeps container deps across borrow lend" + preProofDefs pfEvil14Case oneList (some .revokedUse) false [pfEvil14Case, pfWrap14, pfMkWrap14] + runCase "pre-proof Fix 12 control: consuming match on @[unique] @[shared]-field struct" + preProofDefs pfOk14Consume oneList none true [pfOk14Consume, pfWrap14, pfMkWrap14] runCase "pre-proof Fix 13 (evil15): multi-field anCtor with outer .imm cls still returns .val" - preProofDefs pfEvil15 oneList (some .borrowEscape) false [pfEvil15], - runCase "pre-proof Fix 13 control: distinct @unique fields in multi-field ctor" - preProofDefs pfOk15 twoLists none true [pfOk15], - stuckCase "finding 15: an input cell's Nat field holding a list, read by a case" p15Defs g15 in15 true [g15, mkK], + preProofDefs pfEvil15 oneList (some .borrowEscape) false [pfEvil15] + runCase "pre-proof Fix 13 control: distinct @[unique] fields in multi-field ctor" + preProofDefs pfOk15 twoLists none true [pfOk15] + stuckCase "finding 15: an input cell's Nat field holding a list, read by a case" p15Defs g15 in15 true [g15, mkK] runCase "finding 15, control: a well-typed input" p15Defs g15 in15ok none true [g15, mkK] -] /-! ### Must-reject cases from records -/ @@ -1523,29 +1516,27 @@ def v8CensusOf (b : Built) : Nat × List String × List String × List String × else if pre != post then changed := changed ++ [nm] return (total, preList, postList, gained, lost, changed) -def recordCasesTest : LSpec.TestSeq := - .individualIO "must-reject cases from records: case definitions, primitives, recursors, quotients, \ - η-short interfaces" none (do - match ← buildFixture with - | .error e => return (false, 0, 0, some s!"the fixture: {e}") - | .ok b => - let mut allOk := true - let mut failed : Array String := #[] - for c in recordCases do - let (ok, line) := match runRecCase b c with - | .ok r => r - | .error e => (false, s!"{c.label}: {e}") - IO.println s!" {if ok then "ok" else "FAIL"} {line}" - unless ok do - allOk := false - failed := failed.push line - let (total, preL, postL, gained, lost, changed) := v8CensusOf b - let censusOk := lost.isEmpty && changed.isEmpty - IO.println s!" {if censusOk then "ok" else "FAIL"} V8 census (ResourceModesFixture): {total} refs, pre={preL.length} {preL}, post={postL.length} {postL}, +gained={gained}, -lost={lost}, ~changed={changed}" - unless censusOk do +def recordCasesTest : LSpec.Spec := do + it "must-reject cases from records: case definitions, primitives, recursors, quotients, \ + η-short interfaces" do + let b ← expectOk ((← buildFixture).mapError (s!"the fixture: {·}")) + let mut allOk := true + let mut failed : Array String := #[] + for c in recordCases do + let (ok, line) := match runRecCase b c with + | .ok r => r + | .error e => (false, s!"{c.label}: {e}") + IO.println s!" {if ok then "ok" else "FAIL"} {line}" + unless ok do allOk := false - failed := failed.push s!"V8 census (ResourceModesFixture): lost={lost} changed={changed}" - return (allOk, 0, 0, if allOk then none else some ("; ".intercalate failed.toList))) .done + failed := failed.push line + let (total, preL, postL, gained, lost, changed) := v8CensusOf b + let censusOk := lost.isEmpty && changed.isEmpty + IO.println s!" {if censusOk then "ok" else "FAIL"} V8 census (ResourceModesFixture): {total} refs, pre={preL.length} {preL}, post={postL.length} {postL}, +gained={gained}, -lost={lost}, ~changed={changed}" + unless censusOk do + allOk := false + failed := failed.push s!"V8 census (ResourceModesFixture): lost={lost} changed={changed}" + expect allOk ("; ".intercalate failed.toList) /-! ### Recursive, mutual, nested and indexed types from records (the mode-repair branch, V7 & V8) @@ -1588,28 +1579,26 @@ def recTypeCases : List RecCase := [ reads := true, accept := true, natValue := some 2 } ] -def recTypeCasesTest : LSpec.TestSeq := - .individualIO "recursive, mutual, nested and indexed types from records: the class oracle answers" none (do - match ← buildFixtureAt "Tests/Ix/ResourceModesRecFixture.lean" recFixtureSeeds with - | .error e => return (false, 0, 0, some s!"the fixture: {e}") - | .ok b => - let mut allOk := true - let mut failed : Array String := #[] - for c in recTypeCases do - let (ok, line) := match runRecCase b c with - | .ok r => r - | .error e => (false, s!"{c.label}: {e}") - IO.println s!" {if ok then "ok" else "FAIL"} {line}" - unless ok do - allOk := false - failed := failed.push line - let (total, preL, postL, gained, lost, changed) := v8CensusOf b - let censusOk := lost.isEmpty && changed.isEmpty && gained.any fun s => (s.splitOn "ModeRecFixture.V.casesOn").length > 1 - IO.println s!" {if censusOk then "ok" else "FAIL"} V8 census (ResourceModesRecFixture): {total} refs, pre={preL.length} {preL}, post={postL.length} {postL}, +gained={gained}, -lost={lost}, ~changed={changed}" - unless censusOk do +def recTypeCasesTest : LSpec.Spec := do + it "recursive, mutual, nested and indexed types from records: the class oracle answers" do + let b ← expectOk ((← buildFixtureAt "Tests/Ix/ResourceModesRecFixture.lean" recFixtureSeeds).mapError (s!"the fixture: {·}")) + let mut allOk := true + let mut failed : Array String := #[] + for c in recTypeCases do + let (ok, line) := match runRecCase b c with + | .ok r => r + | .error e => (false, s!"{c.label}: {e}") + IO.println s!" {if ok then "ok" else "FAIL"} {line}" + unless ok do allOk := false - failed := failed.push s!"V8 census (ResourceModesRecFixture): gained={gained} lost={lost} changed={changed}" - return (allOk, 0, 0, if allOk then none else some ("; ".intercalate failed.toList))) .done + failed := failed.push line + let (total, preL, postL, gained, lost, changed) := v8CensusOf b + let censusOk := lost.isEmpty && changed.isEmpty && gained.any fun s => (s.splitOn "ModeRecFixture.V.casesOn").length > 1 + IO.println s!" {if censusOk then "ok" else "FAIL"} V8 census (ResourceModesRecFixture): {total} refs, pre={preL.length} {preL}, post={postL.length} {postL}, +gained={gained}, -lost={lost}, ~changed={changed}" + unless censusOk do + allOk := false + failed := failed.push s!"V8 census (ResourceModesRecFixture): gained={gained} lost={lost} changed={changed}" + expect allOk ("; ".intercalate failed.toList) /-! ### Annotated Lean source compile, closure completeness, `DefAsserts`, and `0x04` diagnostics -/ @@ -1670,7 +1659,7 @@ def runAnnotatedCompileSuite : IO (Array String) := do let mut errs : Array String := #[] -- 1. Surface-annotated Lean declarations from `SyntaxFixture`: positive, post-binder-data, and strip/apply. -- Under finalized L1 (`Nat` is never confined), `localShared`, `sharedLoan`, and `doBlockBorrowEscape` - -- (all on `Nat`) are accepted; under Repair S (`notOnceSrc`), returning a `@once` parameter (`linear`) + -- (all on `Nat`) are accepted; under Repair S (`notOnceSrc`), returning a `@[once]` parameter (`linear`) -- is refused, and `doBlockBorrowEscapeBox` (on heap cell `SyntaxBox`) is refused with `borrowEscape`. let senv ← getCompileEnv #[`Tests.Ix.SourceContract.SyntaxFixture] let posNames : List Lean.Name := [ @@ -1707,7 +1696,7 @@ def runAnnotatedCompileSuite : IO (Array String) := do | some c => unless Ix.Compile.BinderData.hasModes c && c.bindersComplete && c.modesCanonical do errs := errs.push s!"surface contracts: invalid mode/binder invariants on {n}" - -- Verify compiled `Ixon.Constructor.fieldModes` actually received `@shared` + -- Verify compiled `Ixon.Constructor.fieldModes` actually received `@[shared]` for (indName, ctorIdx, expected) in [ (``Tests.Ix.SourceContract.SyntaxFixture.SharedPair, 0, #[Ixon.FieldMode.shared, .inherited]), (``Tests.Ix.SourceContract.SyntaxFixture.SharedOnly, 0, #[.shared]), @@ -1761,17 +1750,17 @@ def runAnnotatedCompileSuite : IO (Array String) := do errs := errs.push "surface contracts: strip/apply roundtrip changed serialized bytes" | .ok _ => errs := errs.push "surface contracts (.post): finalization did not complete" - -- 1b. `@erased` constructor fields: matching via `casesOn` in a minimal closure (without + -- 1b. `@[erased]` constructor fields: matching via `casesOn` in a minimal closure (without -- Lean's unannotated auto-generated `recOn`/`_sizeOf_1` auxiliaries) compiles cleanly, while -- a full unit closure containing those raw-recursor auxiliaries is strictly refused by V8. let erasedMatchConsts := Ix.EnvScope.collectDeps senv [``Tests.Ix.SourceContract.SyntaxFixture.readSharedBox] { recursors := true, units := false, checkerSupport := true } match ← Ix.CompileM.compileCertified senv erasedMatchConsts 2 (modeCheck := Ix.ModeCheck.checkArtifact) with - | .error e => errs := errs.push s!"surface contracts (@erased match): compileCertified failed: {e}" + | .error e => errs := errs.push s!"surface contracts (@[erased] match): compileCertified failed: {e}" | .ok out => match ownerConst? out.env ``Tests.Ix.SourceContract.SyntaxFixture.SharedBox with - | none => errs := errs.push "surface contracts (@erased match): missing SharedBox record" + | none => errs := errs.push "surface contracts (@[erased] match): missing SharedBox record" | some c => let ok := match c.info with | .muts ms => ms.any fun @@ -1780,17 +1769,17 @@ def runAnnotatedCompileSuite : IO (Array String) := do | _ => false | _ => false unless ok && Ix.Compile.BinderData.hasModes c && c.bindersComplete && c.modesCanonical do - errs := errs.push "surface contracts (@erased match): SharedBox modes/fieldModes invalid" + errs := errs.push "surface contracts (@[erased] match): SharedBox modes/fieldModes invalid" let erasedUnitConsts := Ix.EnvScope.collectSelectedDeps senv [``Tests.Ix.SourceContract.SyntaxFixture.SharedBox] match ← Ix.CompileM.compileCertified senv erasedUnitConsts 2 (modeCheck := Ix.ModeCheck.checkArtifact) with - | .ok _ => errs := errs.push "surface contracts (@erased unit V8): unexpectedly accepted unannotated raw recursor auxiliaries" + | .ok _ => errs := errs.push "surface contracts (@[erased] unit V8): unexpectedly accepted unannotated raw recursor auxiliaries" | .error e => unless hasSubstr e "is erased in its constructor and not in minor premise" do - errs := errs.push s!"surface contracts (@erased unit V8): expected V8 recRules refusal, got: {e}" + errs := errs.push s!"surface contracts (@[erased] unit V8): expected V8 recRules refusal, got: {e}" - -- 2. Must-reject surface-annotated declarations: Repair S (`onceReentry` on returning `@once` binding) - -- and `borrowEscape` on `do`-block `let @borrow` of heap cell `SyntaxBox` + -- 2. Must-reject surface-annotated declarations: Repair S (`onceReentry` on returning `@[once]` binding) + -- and `borrowEscape` on `do`-block `let @[borrow]` of heap cell `SyntaxBox` for (bad, expectedErr) in [ (``Tests.Ix.SourceContract.SyntaxFixture.linear, "onceReentry"), (``Tests.Ix.SourceContract.SyntaxFixture.doBlockBorrowEscapeBox, "borrowEscape")] do @@ -1801,10 +1790,10 @@ def runAnnotatedCompileSuite : IO (Array String) := do unless hasSubstr e expectedErr do errs := errs.push s!"surface must-reject {bad}: expected {expectedErr}, got: {e}" - -- 3. `ModeFixture` source contracts: `let @borrow`, `borrowEscape` on heap cell `BoxE`, + -- 3. `ModeFixture` source contracts: `let @[borrow]`, `borrowEscape` on heap cell `BoxE`, -- 2-variant shared `lam`, tier retry, and must-rejects let fenv ← fixtureFileEnv - -- 3a'. Must-reject `borrowEscape` on return (`idBox`) and on `let @borrow` (`leakBorrowBox`) for heap cell `BoxE` + -- 3a'. Must-reject `borrowEscape` on return (`idBox`) and on `let @[borrow]` (`leakBorrowBox`) for heap cell `BoxE` match fenv.find? `ModeFixture.idBox with | none => errs := errs.push "idBox: missing fixture declaration" | some idCi => @@ -1834,12 +1823,12 @@ def runAnnotatedCompileSuite : IO (Array String) := do binders := cLbbOuter.binders.push { site := letSite, mode := .borrowed, isBorrow := true } } match ← compileWithContracts lbbConsts #[cLbb] with - | .ok _ => errs := errs.push "leakBorrowBox (let @borrow BoxE escaped): accepted" + | .ok _ => errs := errs.push "leakBorrowBox (let @[borrow] BoxE escaped): accepted" | .error e => unless hasSubstr e "borrowEscape" do errs := errs.push s!"leakBorrowBox: expected borrowEscape, got: {e}" | _, _ => errs := errs.push "leakBorrowBox: contract setup failed" - -- 3a. Valid `let @borrow` + borrowed parameter on heap cell `BoxE` + -- 3a. Valid `let @[borrow]` + borrowed parameter on heap cell `BoxE` let borrowConsts := Ix.EnvScope.collectSelectedDeps fenv [`ModeFixture.letBorrowBox] match fenv.find? `ModeFixture.inspectBox, fenv.find? `ModeFixture.letBorrowBox with | some inspectCi, some lbCi => @@ -1985,12 +1974,10 @@ def runAnnotatedCompileSuite : IO (Array String) := do errs := errs.push s!"readErased: expected erasedRead, got: {e}" return errs -def annotatedCompileCasesTest : LSpec.TestSeq := - .individualIO "annotated Lean source compile: positive modes, 2-variant shared λ, strip/apply, tier retry, must-rejects" - none (do - let errs ← runAnnotatedCompileSuite - return (errs.isEmpty, 0, 0, - if errs.isEmpty then none else some ("; ".intercalate errs.toList))) .done +def annotatedCompileCasesTest : LSpec.Spec := do + it "annotated Lean source compile: positive modes, 2-variant shared λ, strip/apply, tier retry, must-rejects" do + let errs ← runAnnotatedCompileSuite + expect errs.isEmpty ("; ".intercalate errs.toList) def runCompletenessAndAssertsSuite : IO (Array String) := do let mut errs : Array String := #[] @@ -2150,12 +2137,10 @@ def runCompletenessAndAssertsSuite : IO (Array String) := do | _ => errs := errs.push "ModeFixture.k was not a standalone .defn" return errs -def completenessAndAssertsTest : LSpec.TestSeq := - .individualIO "closure completeness (`bindersComplete`, `modesCanonical`) and `DefAsserts` placement" - none (do - let errs ← runCompletenessAndAssertsSuite - return (errs.isEmpty, 0, 0, - if errs.isEmpty then none else some ("; ".intercalate errs.toList))) .done +def completenessAndAssertsTest : LSpec.Spec := do + it "closure completeness (`bindersComplete`, `modesCanonical`) and `DefAsserts` placement" do + let errs ← runCompletenessAndAssertsSuite + expect errs.isEmpty ("; ".intercalate errs.toList) def runUndecidedRoleDiagnosticSuite : IO (Array String) := do let mut errs : Array String := #[] @@ -2206,16 +2191,26 @@ def runUndecidedRoleDiagnosticSuite : IO (Array String) := do | _ => errs := errs.push "compileAndFinalize for bound diagnostic fixture failed" return errs -def undecidedRoleDiagnosticTest : LSpec.TestSeq := - .individualIO "diagnostic when unannotated (`0x04`) records meet the role table (`Ix.Typing`, `Ix.ModeCheck`)" - none (do - let errs ← runUndecidedRoleDiagnosticSuite - return (errs.isEmpty, 0, 0, - if errs.isEmpty then none else some ("; ".intercalate errs.toList))) .done - -public def suite : List LSpec.TestSeq := - erasedCases ++ uniqueCases ++ borrowCases ++ onceCases ++ captureCases ++ skeletonCases ++ - alternativeCases ++ findingCases ++ [limitCase, fastPathCase, recordCasesTest, recTypeCasesTest, - annotatedCompileCasesTest, completenessAndAssertsTest, undecidedRoleDiagnosticTest] +def undecidedRoleDiagnosticTest : LSpec.Spec := do + it "diagnostic when unannotated (`0x04`) records meet the role table (`Ix.Typing`, `Ix.ModeCheck`)" do + let errs ← runUndecidedRoleDiagnosticSuite + expect errs.isEmpty ("; ".intercalate errs.toList) + +public def suite : LSpec.Spec := do + erasedCases + uniqueCases + borrowCases + onceCases + captureCases + skeletonCases + alternativeCases + findingCases + limitCase + fastPathCase + recordCasesTest + recTypeCasesTest + annotatedCompileCasesTest + completenessAndAssertsTest + undecidedRoleDiagnosticTest end Tests.ResourceModes diff --git a/Tests/Ix/RoleArtifactConsumer.lean b/Tests/Ix/RoleArtifactConsumer.lean index d607ea4ca1..9a54596c2b 100644 --- a/Tests/Ix/RoleArtifactConsumer.lean +++ b/Tests/Ix/RoleArtifactConsumer.lean @@ -55,13 +55,47 @@ private def withBadCheat (env : Env) (falseAddress : Address) : Env × Address : let (env, address) := insert env bad (publish env "badCheat" address, address) -/-- The user-axiom path: strict by default, `--allow-user-axioms` conditional, -listed and without a host statement, and a binding that leaves `sorryAx` -unbound refused. Library entry points first, then the `ix` and -`kernel-check-ixe` binaries over every driver path, the read cache's included. -/ -private def userAxiomChecks (env tierEnv : Env) (generated : _root_.Ix.RoleBinding.Generated) - (ix kernel dir : System.FilePath) : IO Nat := do - let cfg : CheckCfg := { silent := true, progressMs := 0, slowMs := 0 } +private structure Fixture where + env : Env + tierEnv : Env + badEnv : Env + cheatEnv : Env + tierCheatEnv : Env + badCheatEnv : Env + generated : _root_.Ix.RoleBinding.Generated + proofAddress : Address + proof : Constant + tierOwner : Address + tierAddress : Address + cheatAddress : Address + useAddress : Address + badAddress : Address + bytes : ByteArray + tierBytes : ByteArray + badBytes : ByteArray + cheatBytes : ByteArray + badCheatBytes : ByteArray + tierCheatBytes : ByteArray + noSorry : ByteArray + ix : System.FilePath + kernel : System.FilePath + dir : System.FilePath + path : System.FilePath + tierPath : System.FilePath + badPath : System.FilePath + cheatPath : System.FilePath + tierCheatPath : System.FilePath + noSorryPath : System.FilePath + boundPath : System.FilePath + +private def buildFixture : IO Fixture := do + let (env, generated) ← IO.ofExcept (Tests.Ix.RoleGeneration.completeArtifact .natDiv) + let some (proofAddress, proof) := generated.evidence[0]? + | throw (IO.userError "fixture has no proof") + let (tierEnv, tierOwner, tierAddress) ← IO.ofExcept (withTier env proof) + let .defn definition := proof.info | throw (IO.userError "proof kind changed") + let badProof := { proof with info := .defn { definition with value := .var 0 } } + let (badEnv, _) := insert env badProof let some falseAddress := generated.table.addressOf? .false | throw (IO.userError "fixture has no False") let (cheatEnv, cheatAddress, useAddress) := withCheat env falseAddress let (tierCheatEnv, _, _) := withCheat tierEnv falseAddress @@ -72,145 +106,65 @@ private def userAxiomChecks (env tierEnv : Env) (generated : _root_.Ix.RoleBindi let noSorryBytes := noSorryTable.toBytes let noSorryEnv := { cheatEnv with roleBinding := some ⟨Address.admissionHash noSorryBytes, noSorryBytes⟩ } let bytes ← IO.ofExcept (serEnv env) + let tierBytes ← IO.ofExcept (serEnv tierEnv) + let badBytes ← IO.ofExcept (serEnv badEnv) let cheatBytes ← IO.ofExcept (serEnv cheatEnv) let badCheatBytes ← IO.ofExcept (serEnv badCheatEnv) let tierCheatBytes ← IO.ofExcept (serEnv tierCheatEnv) let noSorry ← IO.ofExcept (serEnv noSorryEnv) - for anon in [false, true] do - let strict ← checked (← prepareInput cheatBytes anon) - let r ← checked (← runPrepared strict cfg .all) - ensure (!r.failures.isEmpty && r.artifactAdmission.isNone && r.conditionalOn.isEmpty && - runExit r true == _root_.Ix.Benchmark.Results.exitRejected) - "strict checking admitted a user axiom" - let p ← checked (← prepareInput cheatBytes anon (allowUserAxioms := true)) - let r ← checked (← runPrepared p cfg .all) - ensure (r.failures.isEmpty && r.hostStatement.isNone && - r.artifactAdmission == some (.conditional cheatEnv.consts.size none #[cheatAddress]) && - runExit r true == exitConditional && runExit r true true == _root_.Ix.Benchmark.Results.exitUsage && - runStatus r true == "conditional") - s!"the conditional whole run is not reported as conditional on cheat: {repr r.artifactAdmission}" - let r ← checked (← runPrepared p cfg (.only #[if anon then toString useAddress else "useCheat"])) - ensure (r.failures.isEmpty && r.userAxioms == #[cheatAddress] && runExit r false == exitConditional && - runStatus r false == "conditional") - "a selected run through a user axiom is not conditional on it" - -- a user axiom the run reads and then rejects admits nothing: the run lists - -- only the user axioms whose records it accepted (`admittedUserAxioms`) - let pBad ← checked (← prepareInput badCheatBytes anon (allowUserAxioms := true)) - let r ← checked (← runPrepared pBad cfg (.only (if anon then #[toString useAddress, toString badAddress] - else #["useCheat", "badCheat"]))) - let bad := r.targets.filter (·.target.address == badAddress) - ensure (bad.size == 1 && bad.all (fun t => t.outcome == "reject" && !t.reason.startsWith "reader:") && - r.failures.size == 1 && r.userAxioms == #[cheatAddress] && runStatus r false == "rejected") - s!"a rejected user axiom was listed as admitted: {r.userAxioms}, {bad.map (·.reason)}" - let natDiv := if anon then toString (generated.table.addressOf? .natDiv).get! else "Nat.div" - let r ← checked (← runPrepared p cfg (.only #[natDiv])) - ensure (r.failures.isEmpty && r.userAxioms.isEmpty && runExit r false == 0) - "a selected run that reads no user axiom became conditional" - -- with no user axiom among the declarations, the one run under the flag is - -- the certified entry's (T1, `ReceiptConditional.toReceipt`): the same - -- verdict and host statement as a strict run - let strict ← checked (← runPrepared (← checked (← prepareInput bytes anon)) cfg .all) - let p ← checked (← prepareInput bytes anon (allowUserAxioms := true)) - let r ← checked (← runPrepared p cfg .all) - ensure (r.artifactAdmission == some (.logical env.consts.size) && r.hostStatement.isSome && - r.hostStatement == strict.hostStatement && r.artifactAdmission == strict.artifactAdmission && - runExit r true true == 0) "the flag replaced the certified entry on an artifact without user axioms" - match ← prepareInput noSorry anon (allowUserAxioms := true) with - | .error (.artifact message) => - ensure (message.contains "leaves sorryAx unbound") s!"wrong refusal: {message}" - | _ => throw (IO.userError "a binding without sorryAx admitted user axioms") - let p ← checked (← prepareInput tierCheatBytes true (allowUserAxioms := true)) - let r ← checked (← runPrepared p cfg .all) - ensure (r.artifactAdmission == some (.conditional tierCheatEnv.consts.size (some 1) #[cheatAddress])) - s!"the tiered conditional entry did not run: {repr r.artifactAdmission}" - -- and the tiered entry with no user axiom: the certified tiered receipt - -- (`TierReceiptConditional.toTierReceipt`) and the strict run's statement - let tierBytes ← IO.ofExcept (serEnv tierEnv) - let strict ← checked (← runPrepared (← checked (← prepareInput tierBytes true)) cfg .all) - let r ← checked (← runPrepared (← checked (← prepareInput tierBytes true (allowUserAxioms := true))) cfg .all) - ensure (r.artifactAdmission == some (.tiered tierEnv.consts.size 1) && - r.artifactAdmission == strict.artifactAdmission && r.hostStatement.isSome && - r.hostStatement == strict.hostStatement) - s!"the flag replaced the certified tiered entry: {repr r.artifactAdmission} vs {repr strict.artifactAdmission}" - -- meta mode checks the published names against the binding even when strict - match ← prepareInput noSorry with - | .error (.artifact message) => - ensure (message.contains "role binding") s!"wrong meta refusal: {message}" - | _ => throw (IO.userError "a published sorryAx left unbound passed meta preparation") + let ix ← IO.FS.realPath ".lake/build/bin/ix" + let kernel ← IO.FS.realPath ".lake/build/bin/kernel-check-ixe" + let dir ← IO.FS.createTempDir + let path := dir / "bound.ixe" + let tierPath := dir / "tier.ixe" + let badPath := dir / "invalid.ixe" let cheatPath := dir / "cheat.ixe" let tierCheatPath := dir / "tier-cheat.ixe" let noSorryPath := dir / "no-sorry.ixe" let boundPath := dir / "bound-axioms.ixe" - let unused := dir / "conditional.ixhc" + IO.FS.writeBinFile path bytes + IO.FS.writeBinFile tierPath tierBytes + IO.FS.writeBinFile badPath badBytes IO.FS.writeBinFile cheatPath cheatBytes IO.FS.writeBinFile tierCheatPath tierCheatBytes IO.FS.writeBinFile noSorryPath noSorry IO.FS.writeBinFile boundPath bytes - let vars := #[("IX_KERNEL_CHECK_PROGRESS_MS", some "0"), ("IX_KERNEL_CHECK_SLOW_MS", some "0")] - let listed := s!"[check-lean] {cheatAddress}" - let mut calls := 0 - for (file, args, code, texts) in [ - (cheatPath, #[], 3, #[]), - (cheatPath, #["--anon"], 3, #[]), - (cheatPath, #["--allow-user-axioms"], exitConditional, - #["whole artifact: CONDITIONAL on 1 user axioms:", s!"{listed} cheat", "no host statement"]), - (cheatPath, #["--anon", "--allow-user-axioms"], exitConditional, - #["whole artifact: CONDITIONAL on 1 user axioms:", listed]), - (cheatPath, #["--allow-user-axioms", "--consts", "useCheat"], exitConditional, - #["selected checking: CONDITIONAL on 1 user axioms:", s!"{listed} cheat"]), - (tierCheatPath, #["--anon", "--allow-user-axioms"], exitConditional, - #["whole artifact: CONDITIONAL on 1 user axioms:", "conditional logical entry and typing tier"]), - (cheatPath, #["--allow-user-axioms", "--host-out", unused.toString], 2, - #["CONDITIONAL on 1 user axioms and issues no host statement"]), - (boundPath, #["--allow-user-axioms"], 0, #["whole artifact: logical entry accepted all"]), - (noSorryPath, #["--anon", "--allow-user-axioms"], 3, #["leaves sorryAx unbound"]), - (noSorryPath, #[], 3, #["role binding"])] do - calls := calls + 1 - let out ← IO.Process.output { cmd := ix.toString, args := #["check-lean", file.toString] ++ args, env := vars } - let text := out.stdout ++ out.stderr - ensure (out.exitCode == code && texts.all (fun t => text.contains t) && - (code == 0 || !out.stdout.contains "accepted all")) - s!"user-axiom CLI control {args} failed: {out.exitCode}\n{out.stdout}\n{out.stderr}" - ensure (!(← unused.pathExists)) "a conditional run wrote a host statement" - -- kernel-check-ixe: strict by default and conditional with the flag, on the - -- streamed, eager, pooled and read-cache paths alike - let rowsOf := fun (rowsPath : System.FilePath) => do - let mut rows : Std.HashMap String String := {} - for line in (← IO.FS.readFile rowsPath).splitOn "\n" do - if line.isEmpty then continue - let row ← IO.ofExcept (Lean.Json.parse line) - rows := rows.insert (← IO.ofExcept (row.getObjValAs? String "address")) - (← IO.ofExcept (row.getObjValAs? String "outcome")) - return rows - let cache := dir / "read-cache" - for (args, cached) in [(#["--load", "stream"], false), (#["--load", "eager", "--jobs", "2"], false), - (#["--jobs", "2"], true), (#[], true), (#["--load", "eager"], true)] do - for allow in [true, false] do - calls := calls + 1 - let rowsPath := dir / "cheat.jsonl" - let result ← IO.Process.output { - cmd := kernel.toString - args := #[cheatPath.toString, rowsPath.toString] ++ args ++ (if allow then #["--allow-user-axioms"] else #[]) - env := #[("CHECK_IXE_ROOTS", none), ("CHECK_IXE_SKIP", none), - ("CHECK_IXE_READ_CACHE", if cached then some cache.toString else none)] } - let rows ← rowsOf rowsPath - let label := s!"kernel-check-ixe {args} allow={allow}" - ensure (result.exitCode == 0 && rows.contains (toString cheatAddress) && rows.contains (toString useAddress)) - s!"{label} failed: {result.exitCode}\n{result.stderr}" - if allow then - ensure (rows.toList.all (·.2 == "accept") && - result.stderr.contains s!"CONDITIONAL on 1 user axioms:\n {cheatAddress}") - s!"{label} did not admit and list the user axiom\n{result.stderr}" - else - ensure (rows[toString cheatAddress]? != some "accept" && rows[toString useAddress]? != some "accept" && - !result.stderr.contains "CONDITIONAL") - s!"{label} admitted a user axiom while strict\n{result.stderr}" - ensure (← cache.pathExists) "the read cache was never written" - let refused ← IO.Process.output { - cmd := kernel.toString, args := #[noSorryPath.toString, (dir / "no-sorry.jsonl").toString, "--allow-user-axioms"] } - ensure (refused.exitCode == 2 && refused.stderr.contains "leaves sorryAx unbound") - s!"kernel-check-ixe admitted user axioms under a binding without sorryAx\n{refused.stderr}" - return calls + 1 + return { + env, tierEnv, badEnv, cheatEnv, tierCheatEnv, badCheatEnv, generated, + proofAddress, proof, tierOwner, tierAddress, cheatAddress, useAddress, badAddress, + bytes, tierBytes, badBytes, cheatBytes, badCheatBytes, tierCheatBytes, noSorry, + ix, kernel, dir, path, tierPath, badPath, cheatPath, tierCheatPath, noSorryPath, boundPath + } + +private def rowsOf (rowsPath : System.FilePath) : IO (Std.HashMap String String) := do + let mut rows : Std.HashMap String String := {} + for line in (← IO.FS.readFile rowsPath).splitOn "\n" do + if line.isEmpty then continue + let row ← IO.ofExcept (Lean.Json.parse line) + rows := rows.insert (← IO.ofExcept (row.getObjValAs? String "address")) + (← IO.ofExcept (row.getObjValAs? String "outcome")) + return rows + +private def checkKernelIxeUserAxioms (fx : Fixture) (args : Array String) + (cache? : Option System.FilePath) (allow : Bool) (outName : String) : IO Unit := do + let rowsPath := fx.dir / outName + let result ← IO.Process.output { + cmd := fx.kernel.toString + args := #[fx.cheatPath.toString, rowsPath.toString] ++ args ++ (if allow then #["--allow-user-axioms"] else #[]) + env := #[("CHECK_IXE_ROOTS", none), ("CHECK_IXE_SKIP", none), + ("CHECK_IXE_READ_CACHE", cache?.map (·.toString))] } + let rows ← rowsOf rowsPath + let label := s!"kernel-check-ixe {args} allow={allow}" + ensure (result.exitCode == 0 && rows.contains (toString fx.cheatAddress) && rows.contains (toString fx.useAddress)) + s!"{label} failed: {result.exitCode}\n{result.stderr}" + if allow then + ensure (rows.toList.all (·.2 == "accept") && + result.stderr.contains s!"CONDITIONAL on 1 user axioms:\n {fx.cheatAddress}") + s!"{label} did not admit and list the user axiom\n{result.stderr}" + else + ensure (rows[toString fx.cheatAddress]? != some "accept" && rows[toString fx.useAddress]? != some "accept" && + !result.stderr.contains "CONDITIONAL") + s!"{label} admitted a user axiom while strict\n{result.stderr}" private def orderedChecks (env tierEnv badEnv : Env) : IO Unit := do let prepared ← IO.ofExcept ((prepareRecords env artifactLimits).mapError toString) @@ -249,149 +203,256 @@ private def orderedChecks (env tierEnv badEnv : Env) : IO Unit := do !(checkTieredAt badEnv artifactLimits badOrder).isOk) "explicit-order admission accepted an invalid logical theorem" -private def checks : IO Nat := do - let (env, generated) ← IO.ofExcept (Tests.Ix.RoleGeneration.completeArtifact .natDiv) - let some (proofAddress, proof) := generated.evidence[0]? - | throw (IO.userError "fixture has no proof") - let (tierEnv, tierOwner, tierAddress) ← IO.ofExcept (withTier env proof) - let receipt ← IO.ofExcept ((checkTiered tierEnv artifactLimits).mapError toString) +private def tierFenceChecks (fx : Fixture) : IO Unit := do + let receipt ← IO.ofExcept ((checkTiered fx.tierEnv artifactLimits).mapError toString) ensure (!receipt.logical.consts.isEmpty && receipt.tier.length == 1) "the actual logical/tier fold did not accept the nonempty fixture" - ensure (receipt.prepared.records.length == tierEnv.consts.size && - receipt.prepared.binding.bytes == generated.table.toBytes) + ensure (receipt.prepared.records.length == fx.tierEnv.consts.size && + receipt.prepared.binding.bytes == fx.generated.table.toBytes) "tier receipt changed the actual binding or original raw batch" - ensure (!(check tierEnv artifactLimits).isOk) "logical-only entry accepted a partial definition" - let input ← IO.ofExcept ((prepareRecords tierEnv artifactLimits).mapError toString) + ensure (!(check fx.tierEnv artifactLimits).isOk) "logical-only entry accepted a partial definition" + let input ← IO.ofExcept ((prepareRecords fx.tierEnv artifactLimits).mapError toString) let (logical, tier) := _root_.Ix.Kernel.Admission.partitionTier input.constants let keys := logical.map (·.1) ++ tier.toList.map (fun (_, a, _) => a) ensure (keys.length == input.constants.length && keys.eraseDups.length == keys.length && input.constants.all (fun (a, _) => keys.contains a)) "partition lost or duplicated an original record" - ensure (tier.size == 2 && tier.any (fun (_, a, _) => a == tierOwner) && - tier.any (fun (_, a, _) => a == tierAddress)) "tier projection was not partitioned with its owner" - ensure (!(receipt.prepared.preludeFor { generated.table with bound := #[] }).isOk) + ensure (tier.size == 2 && tier.any (fun (_, a, _) => a == fx.tierOwner) && + tier.any (fun (_, a, _) => a == fx.tierAddress)) "tier projection was not partitioned with its owner" + ensure (!(receipt.prepared.preludeFor { fx.generated.table with bound := #[] }).isOk) "tier prelude accepted a different canonical table" - let some tierRaw := tierEnv.consts[tierOwner]? | throw (IO.userError "tier owner missing") + let some tierRaw := fx.tierEnv.consts[fx.tierOwner]? | throw (IO.userError "tier owner missing") let badRaw := { tierRaw with buf := ByteArray.mk #[0], off := 0, len := 1 } - ensure (match checkTiered { tierEnv with consts := tierEnv.consts.insert tierOwner badRaw } artifactLimits with + ensure (match checkTiered { fx.tierEnv with consts := fx.tierEnv.consts.insert fx.tierOwner badRaw } artifactLimits with | .error (.preparation (.bytes (.mismatch _ _ _))) => true | _ => false) "tier bytes escaped the authentication of the complete input" - ensure (match checkTiered { tierEnv with consts := tierEnv.consts.erase proofAddress } artifactLimits with + ensure (match checkTiered { fx.tierEnv with consts := fx.tierEnv.consts.erase fx.proofAddress } artifactLimits with | .error (.preparation (.coverage _)) => true | _ => false) "missing proof was supplied by a default evidence store" - let .defn definition := proof.info | throw (IO.userError "proof kind changed") - let fenced : Constant := { proof with - refs := proof.refs.push tierAddress - info := .defn { definition with kind := .defn, value := .ref proof.refs.size.toUInt64 #[] } } - let (fencedEnv, _) := insert tierEnv fenced + let .defn definition := fx.proof.info | throw (IO.userError "proof kind changed") + let fenced : Constant := { fx.proof with + refs := fx.proof.refs.push fx.tierAddress + info := .defn { definition with kind := .defn, value := .ref fx.proof.refs.size.toUInt64 #[] } } + let (fencedEnv, _) := insert fx.tierEnv fenced ensure (match checkTiered fencedEnv artifactLimits with | .error (.admission (.fence _ _)) => true | _ => false) "logical reference to tier escaped the fence" +private def inProcessWholeCheck (fx : Fixture) (anon : Bool) : IO Unit := do let cfg : CheckCfg := { silent := true, progressMs := 0, slowMs := 0 } - let bytes ← IO.ofExcept (serEnv env) - let tierBytes ← IO.ofExcept (serEnv tierEnv) - for anon in [false, true] do - let p ← checked (← prepareInput bytes anon) - let logical ← checked (← runPrepared p cfg .all) - ensure (logical.failures.isEmpty && logical.artifactAdmission == some (.logical env.consts.size)) - "bound whole check did not run the actual logical entry" - ensure (logical.hostStatement.any (·.kind == .logical)) - "bound whole check omitted its receipt-derived host statement" - ensure (logical.rows.isEmpty && logical.execution == .serial) - "default quiet whole check did not take the single-pass checkWhole fast path" - let logicalFull ← checked (← runPrepared p { cfg with perRecord := true } .all) - ensure (logical.artifactAdmission == logicalFull.artifactAdmission && - logical.hostStatement == logicalFull.hostStatement && - logical.passed == logicalFull.passed && logical.typed == logicalFull.typed && - logical.targetsCovered == logicalFull.targetsCovered && - logical.roles == logicalFull.roles && !logicalFull.rows.isEmpty) - "single-pass whole check disagreed with per-record pool check" - let selected := if anon then toString (generated.table.addressOf? .natDiv).get! else "Nat.div" - let selected ← checked (← runPrepared p cfg (.only #[selected])) - ensure (selected.failures.isEmpty && selected.artifactAdmission.isNone && selected.hostStatement.isNone) - "selected proof-backed operation lost actual evidence or claimed whole admission" - let capped ← checked (← runPrepared p cfg .all (some 1)) - ensure (capped.artifactAdmission.isNone && capped.hostStatement.isNone) - "capped checking claimed complete artifact admission" - let tp ← checked (← prepareInput tierBytes anon) - let tr ← checked (← runPrepared tp cfg .all) - ensure (tr.failures.isEmpty && tr.artifactAdmission == some (.tiered tierEnv.consts.size 1)) - "bound whole check did not run the actual tiered entry" - ensure (tr.hostStatement.any (fun s => match s.kind with | .tiered .. => true | _ => false)) - "bound tier check omitted its receipt-derived partition commitments" - let thin := { env with assumptions := ({} : Std.HashSet Address).insert tierAddress } - let thin ← IO.ofExcept (serEnv thin) - let thin ← checked (← prepareInput thin anon) - ensure (match checkWhole thin .all none with - | .error (.artifact message) => message.contains "thin artifact" | _ => false) - "unresolved thin input obtained a whole receipt" + let p ← checked (← prepareInput fx.bytes anon) + let logical ← checked (← runPrepared p cfg .all) + ensure (logical.failures.isEmpty && logical.artifactAdmission == some (.logical fx.env.consts.size)) + "bound whole check did not run the actual logical entry" + ensure (logical.hostStatement.any (·.kind == .logical)) + "bound whole check omitted its receipt-derived host statement" + ensure (logical.rows.isEmpty && logical.execution == .serial) + "default quiet whole check did not take the single-pass checkWhole fast path" + let logicalFull ← checked (← runPrepared p { cfg with perRecord := true } .all) + ensure (logical.artifactAdmission == logicalFull.artifactAdmission && + logical.hostStatement == logicalFull.hostStatement && + logical.passed == logicalFull.passed && logical.typed == logicalFull.typed && + logical.targetsCovered == logicalFull.targetsCovered && + logical.roles == logicalFull.roles && !logicalFull.rows.isEmpty) + "single-pass whole check disagreed with per-record pool check" + let selected := if anon then toString (fx.generated.table.addressOf? .natDiv).get! else "Nat.div" + let selected ← checked (← runPrepared p cfg (.only #[selected])) + ensure (selected.failures.isEmpty && selected.artifactAdmission.isNone && selected.hostStatement.isNone) + "selected proof-backed operation lost actual evidence or claimed whole admission" + let capped ← checked (← runPrepared p cfg .all (some 1)) + ensure (capped.artifactAdmission.isNone && capped.hostStatement.isNone) + "capped checking claimed complete artifact admission" + let tp ← checked (← prepareInput fx.tierBytes anon) + let tr ← checked (← runPrepared tp cfg .all) + ensure (tr.failures.isEmpty && tr.artifactAdmission == some (.tiered fx.tierEnv.consts.size 1)) + "bound whole check did not run the actual tiered entry" + ensure (tr.hostStatement.any (fun s => match s.kind with | .tiered .. => true | _ => false)) + "bound tier check omitted its receipt-derived partition commitments" + let thin := { fx.env with assumptions := ({} : Std.HashSet Address).insert fx.tierAddress } + let thin ← IO.ofExcept (serEnv thin) + let thin ← checked (← prepareInput thin anon) + ensure (match checkWhole thin .all none with + | .error (.artifact message) => message.contains "thin artifact" | _ => false) + "unresolved thin input obtained a whole receipt" - -- An unnamed bad theorem is absent from the meta inventory. Whole checking - -- must still refuse it through the exact full artifact entry. - let badProof := { proof with info := .defn { definition with value := .var 0 } } - let (badEnv, _) := insert env badProof - let badBytes ← IO.ofExcept (serEnv badEnv) - let bad ← checked (← prepareInput badBytes) - ensure (match ← runPrepared bad cfg .all with | .error (.artifact _) => true | _ => false) - "an unnamed invalid record escaped bound whole checking" - orderedChecks env tierEnv badEnv - let ix ← IO.FS.realPath ".lake/build/bin/ix" - let dir ← IO.FS.createTempDir - try - let path := dir / "bound.ixe" - let tierPath := dir / "tier.ixe" - let badPath := dir / "invalid.ixe" - IO.FS.writeBinFile path bytes - IO.FS.writeBinFile tierPath tierBytes - IO.FS.writeBinFile badPath badBytes - let vars := #[("IX_KERNEL_CHECK_PROGRESS_MS", some "0"), ("IX_KERNEL_CHECK_SLOW_MS", some "0")] - for (file, args, code, text) in [ - (path, #[], 0, "whole artifact: logical entry accepted"), - (tierPath, #["--anon"], 0, "tier constants typed only"), - (path, #["--consts", "Nat.div"], 0, "selected checking only"), - (badPath, #[], 3, "artifact")] do - let out ← IO.Process.output { cmd := ix.toString, args := #["check-lean", file.toString] ++ args, env := vars } - ensure (out.exitCode == code && (out.stdout ++ out.stderr).contains text) - s!"bound CLI control failed: {out.exitCode}\n{out.stdout}\n{out.stderr}" - let failures := dir / "aggregate-failures.txt" - let out ← IO.Process.output { - cmd := ix.toString - args := #["check-lean", badPath.toString, "--fail-out", failures.toString] - env := vars } - ensure (out.exitCode == 3 && out.stderr.contains "artifact") "aggregate refusal exit changed" - let lines := (← IO.FS.readFile failures).splitOn "\n" |>.map (·.trimAscii.toString) - ensure (lines.any (·.contains "artifact") && lines.all (fun line => line.isEmpty || line.startsWith "#")) - "aggregate refusal wrote a fabricated declaration selector" - let kernel ← IO.FS.realPath ".lake/build/bin/kernel-check-ixe" - let neutral := #["CHECK_IXE_ROOTS", "CHECK_IXE_SKIP", "CHECK_IXE_READ_CACHE"].map (·, none) - let mut previous : Option (Array (String × String × String)) := none - for mode in ["stream", "eager"] do - let rowsPath := dir / s!"{mode}.jsonl" - let result ← IO.Process.output { - cmd := kernel.toString - args := #[path.toString, rowsPath.toString, "--load", mode, "--jobs", "2"] - env := neutral } - ensure (result.exitCode == 0) s!"bound diagnostic {mode} failed: {result.stdout}\n{result.stderr}" - let mut rows : Array (String × String × String) := #[] - for line in (← IO.FS.readFile rowsPath).splitOn "\n" do - if line.isEmpty then continue - let row ← IO.ofExcept (Lean.Json.parse line) - rows := rows.push (← IO.ofExcept (row.getObjValAs? String "address"), - ← IO.ofExcept (row.getObjValAs? String "outcome"), ← IO.ofExcept (row.getObjValAs? String "reason")) - ensure (!rows.isEmpty && rows.all (·.2.1 == "accept")) "actual bound proof/operation records were refused" - for (address, lazy) in env.consts.toList do - let record ← IO.ofExcept lazy.get - let owner := toString (Ixon.CheckOrder.owner address record) - ensure (rows.any (·.1 == owner)) s!"bound diagnostic omitted owner {owner}" - let sorted := rows.qsort (fun a b => a.1 < b.1) - if let some earlier := previous then ensure (earlier == sorted) "stream/eager bound diagnostic rows differ" - previous := some sorted - return 7 + (← userAxiomChecks env tierEnv generated ix kernel dir) - finally - IO.FS.removeDirAll dir +private def inProcessUserAxiomCheck (fx : Fixture) (anon : Bool) : IO Unit := do + let cfg : CheckCfg := { silent := true, progressMs := 0, slowMs := 0 } + let strict ← checked (← prepareInput fx.cheatBytes anon) + let r ← checked (← runPrepared strict cfg .all) + ensure (!r.failures.isEmpty && r.artifactAdmission.isNone && r.conditionalOn.isEmpty && + runExit r true == _root_.Ix.Benchmark.Results.exitRejected) + "strict checking admitted a user axiom" + let p ← checked (← prepareInput fx.cheatBytes anon (allowUserAxioms := true)) + let r ← checked (← runPrepared p cfg .all) + ensure (r.failures.isEmpty && r.hostStatement.isNone && + r.artifactAdmission == some (.conditional fx.cheatEnv.consts.size none #[fx.cheatAddress]) && + runExit r true == exitConditional && runExit r true true == _root_.Ix.Benchmark.Results.exitUsage && + runStatus r true == "conditional") + s!"the conditional whole run is not reported as conditional on cheat: {repr r.artifactAdmission}" + let r ← checked (← runPrepared p cfg (.only #[if anon then toString fx.useAddress else "useCheat"])) + ensure (r.failures.isEmpty && r.userAxioms == #[fx.cheatAddress] && runExit r false == exitConditional && + runStatus r false == "conditional") + "a selected run through a user axiom is not conditional on it" + let pBad ← checked (← prepareInput fx.badCheatBytes anon (allowUserAxioms := true)) + let r ← checked (← runPrepared pBad cfg (.only (if anon then #[toString fx.useAddress, toString fx.badAddress] + else #["useCheat", "badCheat"]))) + let bad := r.targets.filter (·.target.address == fx.badAddress) + ensure (bad.size == 1 && bad.all (fun t => t.outcome == "reject" && !t.reason.startsWith "reader:") && + r.failures.size == 1 && r.userAxioms == #[fx.cheatAddress] && runStatus r false == "rejected") + s!"a rejected user axiom was listed as admitted: {r.userAxioms}, {bad.map (·.reason)}" + let natDiv := if anon then toString (fx.generated.table.addressOf? .natDiv).get! else "Nat.div" + let r ← checked (← runPrepared p cfg (.only #[natDiv])) + ensure (r.failures.isEmpty && r.userAxioms.isEmpty && runExit r false == 0) + "a selected run that reads no user axiom became conditional" + let strict ← checked (← runPrepared (← checked (← prepareInput fx.bytes anon)) cfg .all) + let p ← checked (← prepareInput fx.bytes anon (allowUserAxioms := true)) + let r ← checked (← runPrepared p cfg .all) + ensure (r.artifactAdmission == some (.logical fx.env.consts.size) && r.hostStatement.isSome && + r.hostStatement == strict.hostStatement && r.artifactAdmission == strict.artifactAdmission && + runExit r true true == 0) "the flag replaced the certified entry on an artifact without user axioms" + match ← prepareInput fx.noSorry anon (allowUserAxioms := true) with + | .error (.artifact message) => + ensure (message.contains "leaves sorryAx unbound") s!"wrong refusal: {message}" + | _ => throw (IO.userError "a binding without sorryAx admitted user axioms") -public def units : LSpec.TestSeq := - .individualIO "bound artifact consumers: whole logical/tier entries, the user-axiom path and actual CLI routing" none (do - let count ← checks - return (true, count, 0, none)) .done +private def inProcessTierUserAxiomChecks (fx : Fixture) : IO Unit := do + let cfg : CheckCfg := { silent := true, progressMs := 0, slowMs := 0 } + let p ← checked (← prepareInput fx.tierCheatBytes true (allowUserAxioms := true)) + let r ← checked (← runPrepared p cfg .all) + ensure (r.artifactAdmission == some (.conditional fx.tierCheatEnv.consts.size (some 1) #[fx.cheatAddress])) + s!"the tiered conditional entry did not run: {repr r.artifactAdmission}" + let strict ← checked (← runPrepared (← checked (← prepareInput fx.tierBytes true)) cfg .all) + let r ← checked (← runPrepared (← checked (← prepareInput fx.tierBytes true (allowUserAxioms := true))) cfg .all) + ensure (r.artifactAdmission == some (.tiered fx.tierEnv.consts.size 1) && + r.artifactAdmission == strict.artifactAdmission && r.hostStatement.isSome && + r.hostStatement == strict.hostStatement) + s!"the flag replaced the certified tiered entry: {repr r.artifactAdmission} vs {repr strict.artifactAdmission}" + match ← prepareInput fx.noSorry with + | .error (.artifact message) => + ensure (message.contains "role binding") s!"wrong meta refusal: {message}" + | _ => throw (IO.userError "a published sorryAx left unbound passed meta preparation") + +open LSpec in +public def units : LSpec.Spec := + LSpec.beforeAll buildFixture (fun fx => IO.FS.removeDirAll fx.dir) "role artifact consumer fixtures" fun getFx => do + let vars := #[("IX_KERNEL_CHECK_PROGRESS_MS", some "0"), ("IX_KERNEL_CHECK_SLOW_MS", some "0")] + it "bound artifact consumers: tier partition and fence checks" do + tierFenceChecks (← getFx) + it "bound artifact consumers: in-process whole checks (meta)" do + inProcessWholeCheck (← getFx) false + it "bound artifact consumers: in-process whole checks (anon)" do + inProcessWholeCheck (← getFx) true + it "bound artifact consumers: unnamed invalid record and ordered checks" do + let fx ← getFx + let cfg : CheckCfg := { silent := true, progressMs := 0, slowMs := 0 } + let bad ← checked (← prepareInput fx.badBytes) + ensure (match ← runPrepared bad cfg .all with | .error (.artifact _) => true | _ => false) + "an unnamed invalid record escaped bound whole checking" + orderedChecks fx.env fx.tierEnv fx.badEnv + it "bound artifact consumers: in-process user-axiom checks (meta)" do + inProcessUserAxiomCheck (← getFx) false + it "bound artifact consumers: in-process user-axiom checks (anon)" do + inProcessUserAxiomCheck (← getFx) true + it "bound artifact consumers: in-process tiered user-axiom checks" do + inProcessTierUserAxiomChecks (← getFx) + for (label, pickFile, args, code, text) in [ + ("whole logical CLI", (fun (fx : Fixture) => fx.path), #[], 0, "whole artifact: logical entry accepted"), + ("tier anon CLI", (fun (fx : Fixture) => fx.tierPath), #["--anon"], 0, "tier constants typed only"), + ("selected consts CLI", (fun (fx : Fixture) => fx.path), #["--consts", "Nat.div"], 0, "selected checking only"), + ("invalid artifact CLI", (fun (fx : Fixture) => fx.badPath), #[], 3, "artifact")] do + it s!"bound artifact consumers: ix check-lean {label}" do + let fx ← getFx + let out ← IO.Process.output { cmd := fx.ix.toString, args := #["check-lean", (pickFile fx).toString] ++ args, env := vars } + ensure (out.exitCode == code && (out.stdout ++ out.stderr).contains text) + s!"bound CLI control failed: {out.exitCode}\n{out.stdout}\n{out.stderr}" + it "bound artifact consumers: ix check-lean aggregate fail-out" do + let fx ← getFx + let failures := fx.dir / "aggregate-failures.txt" + let out ← IO.Process.output { + cmd := fx.ix.toString + args := #["check-lean", fx.badPath.toString, "--fail-out", failures.toString] + env := vars } + ensure (out.exitCode == 3 && out.stderr.contains "artifact") "aggregate refusal exit changed" + let lines := (← IO.FS.readFile failures).splitOn "\n" |>.map (·.trimAscii.toString) + ensure (lines.any (·.contains "artifact") && lines.all (fun line => line.isEmpty || line.startsWith "#")) + "aggregate refusal wrote a fabricated declaration selector" + it "bound artifact consumers: kernel-check-ixe stream vs eager parity" do + let fx ← getFx + let neutral := #["CHECK_IXE_ROOTS", "CHECK_IXE_SKIP", "CHECK_IXE_READ_CACHE"].map (·, none) + let mut previous : Option (Array (String × String × String)) := none + for mode in ["stream", "eager"] do + let rowsPath := fx.dir / s!"{mode}.jsonl" + let result ← IO.Process.output { + cmd := fx.kernel.toString + args := #[fx.path.toString, rowsPath.toString, "--load", mode, "--jobs", "2"] + env := neutral } + ensure (result.exitCode == 0) s!"bound diagnostic {mode} failed: {result.stdout}\n{result.stderr}" + let mut rows : Array (String × String × String) := #[] + for line in (← IO.FS.readFile rowsPath).splitOn "\n" do + if line.isEmpty then continue + let row ← IO.ofExcept (Lean.Json.parse line) + rows := rows.push (← IO.ofExcept (row.getObjValAs? String "address"), + ← IO.ofExcept (row.getObjValAs? String "outcome"), ← IO.ofExcept (row.getObjValAs? String "reason")) + ensure (!rows.isEmpty && rows.all (·.2.1 == "accept")) "actual bound proof/operation records were refused" + for (address, lazy) in fx.env.consts.toList do + let record ← IO.ofExcept lazy.get + let owner := toString (Ixon.CheckOrder.owner address record) + ensure (rows.any (·.1 == owner)) s!"bound diagnostic omitted owner {owner}" + let sorted := rows.qsort (fun a b => a.1 < b.1) + if let some earlier := previous then ensure (earlier == sorted) "stream/eager bound diagnostic rows differ" + previous := some sorted + for (label, pickFile, args, code, mkTexts) in [ + ("strict meta", (fun (fx : Fixture) => fx.cheatPath), #[], 3, fun (_ : Fixture) => #[]), + ("strict anon", (fun (fx : Fixture) => fx.cheatPath), #["--anon"], 3, fun (_ : Fixture) => #[]), + ("conditional meta", (fun (fx : Fixture) => fx.cheatPath), #["--allow-user-axioms"], exitConditional, + fun (fx : Fixture) => #["whole artifact: CONDITIONAL on 1 user axioms:", s!"[check-lean] {fx.cheatAddress} cheat", "no host statement"]), + ("conditional anon", (fun (fx : Fixture) => fx.cheatPath), #["--anon", "--allow-user-axioms"], exitConditional, + fun (fx : Fixture) => #["whole artifact: CONDITIONAL on 1 user axioms:", s!"[check-lean] {fx.cheatAddress}"]), + ("conditional selected", (fun (fx : Fixture) => fx.cheatPath), #["--allow-user-axioms", "--consts", "useCheat"], exitConditional, + fun (fx : Fixture) => #["selected checking: CONDITIONAL on 1 user axioms:", s!"[check-lean] {fx.cheatAddress} cheat"]), + ("conditional tiered", (fun (fx : Fixture) => fx.tierCheatPath), #["--anon", "--allow-user-axioms"], exitConditional, + fun (_ : Fixture) => #["whole artifact: CONDITIONAL on 1 user axioms:", "conditional logical entry and typing tier"]), + ("clean artifact with flag", (fun (fx : Fixture) => fx.boundPath), #["--allow-user-axioms"], 0, + fun (_ : Fixture) => #["whole artifact: logical entry accepted all"]), + ("no-sorry anon", (fun (fx : Fixture) => fx.noSorryPath), #["--anon", "--allow-user-axioms"], 3, + fun (_ : Fixture) => #["leaves sorryAx unbound"]), + ("no-sorry meta", (fun (fx : Fixture) => fx.noSorryPath), #[], 3, + fun (_ : Fixture) => #["role binding"])] do + it s!"bound artifact consumers: user-axiom CLI ({label})" do + let fx ← getFx + let out ← IO.Process.output { cmd := fx.ix.toString, args := #["check-lean", (pickFile fx).toString] ++ args, env := vars } + let text := out.stdout ++ out.stderr + ensure (out.exitCode == code && (mkTexts fx).all (fun t => text.contains t) && + (code == 0 || !out.stdout.contains "accepted all")) + s!"user-axiom CLI control {args} failed: {out.exitCode}\n{out.stdout}\n{out.stderr}" + it "bound artifact consumers: user-axiom CLI rejects --host-out" do + let fx ← getFx + let unused := fx.dir / "conditional.ixhc" + let out ← IO.Process.output { + cmd := fx.ix.toString + args := #["check-lean", fx.cheatPath.toString, "--allow-user-axioms", "--host-out", unused.toString] + env := vars } + let text := out.stdout ++ out.stderr + ensure (out.exitCode == 2 && text.contains "CONDITIONAL on 1 user axioms and issues no host statement" && + !out.stdout.contains "accepted all") + s!"user-axiom CLI --host-out control failed: {out.exitCode}\n{out.stdout}\n{out.stderr}" + ensure (!(← unused.pathExists)) "a conditional run wrote a host statement" + for (tag, args) in [("stream", #["--load", "stream"]), ("eager-j2", #["--load", "eager", "--jobs", "2"])] do + for allow in [true, false] do + it s!"bound artifact consumers: kernel-check-ixe uncached {tag} allow={allow}" do + let fx ← getFx + checkKernelIxeUserAxioms fx args none allow s!"cheat-{tag}-{allow}.jsonl" + it "bound artifact consumers: kernel-check-ixe read-cache paths" do + let fx ← getFx + let cache := fx.dir / "read-cache" + for (tag, args) in [("j2", #["--jobs", "2"]), ("default", #[]), ("eager", #["--load", "eager"])] do + for allow in [true, false] do + checkKernelIxeUserAxioms fx args (some cache) allow s!"cheat-cache-{tag}-{allow}.jsonl" + ensure (← cache.pathExists) "the read cache was never written" + it "bound artifact consumers: kernel-check-ixe refuses no-sorry" do + let fx ← getFx + let refused ← IO.Process.output { + cmd := fx.kernel.toString + args := #[fx.noSorryPath.toString, (fx.dir / "no-sorry.jsonl").toString, "--allow-user-axioms"] } + ensure (refused.exitCode == 2 && refused.stderr.contains "leaves sorryAx unbound") + s!"kernel-check-ixe admitted user axioms under a binding without sorryAx\n{refused.stderr}" end Tests.Ix.RoleArtifactConsumer diff --git a/Tests/Ix/RoleBinding.lean b/Tests/Ix/RoleBinding.lean index 707d43d583..1a18371ae6 100644 --- a/Tests/Ix/RoleBinding.lean +++ b/Tests/Ix/RoleBinding.lean @@ -103,12 +103,9 @@ private def checks (_fixture : Constant) : Except String Unit := do need "every header reader rejects bad framing or hash" (!parsed.isOk) /-- The parameter keeps foreign calls out of module initialization. -/ -public def units (fixture : Constant) : LSpec.TestSeq := - .individualIO "role binding: exact v4/v5 bytes, all loaders, FFI and admission boundary" none (do - let result ← IO.lazyPure fun _ => checks fixture - return match result with - | .ok _ => (true, 0, 0, none) - | .error message => (false, 0, 0, some message)) .done +public def units (fixture : Constant) : LSpec.Spec := + it "role binding: exact v4/v5 bytes, all loaders, FFI and admission boundary" do + LSpec.expectOk (checks fixture) end Tests.Ix.RoleBinding diff --git a/Tests/Ix/RoleCompile.lean b/Tests/Ix/RoleCompile.lean index 518e37ada4..0e299efc96 100644 --- a/Tests/Ix/RoleCompile.lean +++ b/Tests/Ix/RoleCompile.lean @@ -120,10 +120,9 @@ private def check : IO Bool := IO.FS.withTempDir fun dir => do "a changed hint passed the finalized-artifact check" return true -public def suite : List LSpec.TestSeq := [ - .individualIO "production artifact bindings: source certificates, both compilers and certified checking" none (do +public def suite : LSpec.Spec := + it "production artifact bindings: source certificates, both compilers and certified checking" do let ok ← check - return (ok, 0, 0, none)) .done -] + LSpec.expect ok end Tests.Ix.RoleCompile diff --git a/Tests/Ix/RoleEquations.lean b/Tests/Ix/RoleEquations.lean index 1e7fa669ee..5f5a477444 100644 --- a/Tests/Ix/RoleEquations.lean +++ b/Tests/Ix/RoleEquations.lean @@ -108,16 +108,11 @@ def roleChecks : Except String Unit := do let missing ← checked #[.indDecl eqBasis 2, .indDecl natBasis 0] need "an absent operation is refused" (!(checkRole missing .intSub evidence).isOk) -private def unit (label : String) (check : Unit → Except String Unit) : LSpec.TestSeq := - .individualIO label none (do - let result ← IO.lazyPure check - return match result with - | .ok _ => (true, 0, 0, none) - | .error message => (false, 0, 0, some message)) .done - -public def suite : List LSpec.TestSeq := [ - unit "dependent equation terms and proof evidence pass the real checker" (fun _ => equationChecks), +private def unit (label : String) (check : Unit → Except String Unit) : LSpec.Spec := + LSpec.itThunk label fun () => LSpec.expectOk (check ()) + +public def suite : LSpec.Spec := do + unit "dependent equation terms and proof evidence pass the real checker" (fun _ => equationChecks) unit "definition behavior and evidence count satisfy the role specification" (fun _ => roleChecks) -] end Tests.Ix.RoleEquations diff --git a/Tests/Ix/RoleGeneration.lean b/Tests/Ix/RoleGeneration.lean index d229eec72e..00ce020474 100644 --- a/Tests/Ix/RoleGeneration.lean +++ b/Tests/Ix/RoleGeneration.lean @@ -207,12 +207,9 @@ private def checks (operation : Role) : Except String Unit := do need "certificate support cannot change an original reducibility hint" (!(strongerHint.emit limits originalHint).isOk) -public def units (operation : Role) : LSpec.TestSeq := - .individualIO "role generation: actual proof records, source bindings, emission and refusals" none (do - let result ← IO.lazyPure fun _ => checks operation - return match result with - | .ok _ => (true, 0, 0, none) - | .error message => (false, 0, 0, some message)) .done +public def units (operation : Role) : LSpec.Spec := + it "role generation: actual proof records, source bindings, emission and refusals" do + LSpec.expectOk (checks operation) private def artifactChecks (operation : Role) : Except String Unit := do let limits := Ix.Typing.typingLimits @@ -303,11 +300,8 @@ private def artifactChecks (operation : Role) : Except String Unit := do need "authenticated replacement proof fails the actual certified consumer" (!(Ix.RoleBinding.Artifact.check changedArtifact limits).isOk) -public def artifactUnits (operation : Role) : LSpec.TestSeq := - .individualIO "artifact consumer: real fold, exact binding, no fallback and evidence refusals" none (do - let result ← IO.lazyPure fun _ => artifactChecks operation - return match result with - | .ok _ => (true, 0, 0, none) - | .error message => (false, 0, 0, some message)) .done +public def artifactUnits (operation : Role) : LSpec.Spec := + it "artifact consumer: real fold, exact binding, no fallback and evidence refusals" do + LSpec.expectOk (artifactChecks operation) end Tests.Ix.RoleGeneration diff --git a/Tests/Ix/RolePacking.lean b/Tests/Ix/RolePacking.lean index 177382a4f7..d20b1bc408 100644 --- a/Tests/Ix/RolePacking.lean +++ b/Tests/Ix/RolePacking.lean @@ -90,9 +90,8 @@ private def checks : IO Nat := do return 6 return 3 -public def units : LSpec.TestSeq := - .individualIO "bound packing: all production pruners preserve actual reader/consumer support" none (do - let count ← checks - return (true, count, 0, none)) .done +public def units : LSpec.Spec := + it "bound packing: all production pruners preserve actual reader/consumer support" do + let _ ← checks end Tests.Ix.RolePacking diff --git a/Tests/Ix/RolePublication.lean b/Tests/Ix/RolePublication.lean index 6b21c6cf81..c006e3a205 100644 --- a/Tests/Ix/RolePublication.lean +++ b/Tests/Ix/RolePublication.lean @@ -80,11 +80,8 @@ private def checks (record : Constant) : Except String Unit := do need "missing owner fails before publication" (!(publication projected (fun a => if a == projectionAddress then some projection else none) [.nat]).isOk) -public def units (record : Constant) : LSpec.TestSeq := - .individualIO "role publication: structural names, aliases, explicit absence and actual prelude owners" none (do - let result ← IO.lazyPure fun _ => checks record - return match result with - | .ok _ => (true, 0, 0, none) - | .error message => (false, 0, 0, some message)) .done +public def units (record : Constant) : LSpec.Spec := + it "role publication: structural names, aliases, explicit absence and actual prelude owners" do + LSpec.expectOk (checks record) end Tests.Ix.RolePublication diff --git a/Tests/Ix/SharingComponents.lean b/Tests/Ix/SharingComponents.lean index c69122937c..cfcdab2d7a 100644 --- a/Tests/Ix/SharingComponents.lean +++ b/Tests/Ix/SharingComponents.lean @@ -113,12 +113,11 @@ private def componentControls (count : Nat) (wild : Bool) : IO Nat := do return tested /-- The comparison over `count` generated inputs. -/ -def suiteOf (count : Nat) (wild : Bool) : List TestSeq := [ - .individualIO s!"uncertain components match the original hashed grouping ({count} inputs)" none (do - let tested ← componentControls count wild - return (true, tested, 0, none)) .done] +def suiteOf (count : Nat) (wild : Bool) : Spec := + it s!"uncertain components match the original hashed grouping ({count} inputs)" do + let _ ← componentControls count wild /-- The primary run: 15 generated inputs and parent arrays within range. -/ -def suite : List TestSeq := suiteOf 15 false +def suite : Spec := suiteOf 15 false end Tests.SharingComponents diff --git a/Tests/Ix/SharingExact.lean b/Tests/Ix/SharingExact.lean index 6346969e16..8d665d8b6b 100644 --- a/Tests/Ix/SharingExact.lean +++ b/Tests/Ix/SharingExact.lean @@ -65,10 +65,10 @@ def u64LE (x : UInt64) : ByteArray := def cbytes (c : Constant) : Nat := (serConstant c).size -def withOk {α} (name : String) (x : Except SharingError α) (k : α → TestSeq) : TestSeq := +def withOk {α} (name : String) (x : Except SharingError α) (k : α → AssertM Unit) : AssertM Unit := match x with | .ok a => k a - | .error e => test s!"{name}: unexpected error {reprStr e}" false + | .error e => fail s!"{name}: unexpected error {reprStr e}" def isErr {α} (x : Except SharingError α) (p : SharingError → Bool) : Bool := match x with @@ -263,35 +263,35 @@ def boundaryValues : List Nat := [tagNEnd1 f, tagNEnd2 f, tagNEnd3 f, tagNEnd4 f, tagNEnd5 f].flatMap fun e => [e - 1, e, e + 1]) -def widthTests (_ : Unit) : TestSeq := - group "integer widths" <| - test "tag0Size = putTagN 0 length at every rung boundary" - (boundaryValues.all fun n => tag0Size n == (runPut (putTagN 0 0 n.toUInt64)).size) ++ - test "tag4Size = putTagN 4 length at every rung boundary" +def widthTests : Spec := + describe "integer widths" do + itBool "tag0Size = putTagN 0 length at every rung boundary" + (boundaryValues.all fun n => tag0Size n == (runPut (putTagN 0 0 n.toUInt64)).size) + itBool "tag4Size = putTagN 4 length at every rung boundary" (boundaryValues.all fun n => [0x7, 0x8, 0x9, 0xB].all fun (f : UInt8) => - tag4Size n == (runPut (putTagN 4 f n.toUInt64)).size) ++ - test "shareWidth = serialized Share length at every boundary" + tag4Size n == (runPut (putTagN 4 f n.toUInt64)).size) + itBool "shareWidth = serialized Share length at every boundary" (boundaryValues.all fun n => shareWidth n == (serExpr (.share n.toUInt64)).size && - exprSize (.share n.toUInt64) == shareWidth n) ++ - test "Share 7/8 → 1/2 bytes" (shareWidth 7 == 1 && shareWidth 8 == 2) ++ - test "Share 1031/1032 → 2/3 bytes" (shareWidth 1031 == 2 && shareWidth 1032 == 3) ++ - test "Share 66567/66568 → 3/4 bytes" (shareWidth 66567 == 3 && shareWidth 66568 == 4) ++ - test "Share 16843783/16843784 → 4/5 bytes" - (shareWidth 16843783 == 4 && shareWidth 16843784 == 5) ++ - test "Share 4311811079/4311811080 → 5/9 bytes" - (shareWidth 4311811079 == 5 && shareWidth 4311811080 == 9) ++ - test "Share 2^64-1 → 9 bytes" (shareWidth (2^64 - 1) == 9) ++ - test "TagN f=0 127/128 → 1/2 bytes, 16511/16512 → 2/3, 82047/82048 → 3/4, 16859263/16859264 → 4/5" + exprSize (.share n.toUInt64) == shareWidth n) + itBool "Share 7/8 → 1/2 bytes" (shareWidth 7 == 1 && shareWidth 8 == 2) + itBool "Share 1031/1032 → 2/3 bytes" (shareWidth 1031 == 2 && shareWidth 1032 == 3) + itBool "Share 66567/66568 → 3/4 bytes" (shareWidth 66567 == 3 && shareWidth 66568 == 4) + itBool "Share 16843783/16843784 → 4/5 bytes" + (shareWidth 16843783 == 4 && shareWidth 16843784 == 5) + itBool "Share 4311811079/4311811080 → 5/9 bytes" + (shareWidth 4311811079 == 5 && shareWidth 4311811080 == 9) + itBool "Share 2^64-1 → 9 bytes" (shareWidth (2^64 - 1) == 9) + itBool "TagN f=0 127/128 → 1/2 bytes, 16511/16512 → 2/3, 82047/82048 → 3/4, 16859263/16859264 → 4/5" (tag0Size 127 == 1 && tag0Size 128 == 2 && tag0Size 16511 == 2 && tag0Size 16512 == 3 && tag0Size 82047 == 3 && tag0Size 82048 == 4 && tag0Size 16859263 == 4 && - tag0Size 16859264 == 5) ++ - test "tag0BracketStart is the start of the count's TagN rung" + tag0Size 16859264 == 5) + itBool "tag0BracketStart is the start of the count's TagN rung" (boundaryValues.all fun k => tag0Size (tag0BracketStart k) == tag0Size k && - (tag0BracketStart k == 0 || tag0Size (tag0BracketStart k - 1) < tag0Size k)) ++ - test "tag0StepBound bounds the growth of the count's TagN width" + (tag0BracketStart k == 0 || decide (tag0Size (tag0BracketStart k - 1) < tag0Size k))) + itBool "tag0StepBound bounds the growth of the count's TagN width" ((boundaryValues.all fun n => n == 0 || decide (tag0Size n - tag0Size (n - 1) ≤ tag0StepBound n)) && tag0StepBound 82048 == 1 && tag0StepBound (tagNEnd5 0 - 1) == 1 && @@ -321,14 +321,14 @@ def genExprForSize : RGen Ixon.Expr := do | 2 => return .lam e (.share idx.toUInt64) | _ => return e -def exprSizeTests (_ : Unit) : TestSeq := - let gen := runGen 7 ((List.range 2000).mapM fun _ => genExprForSize) - group "exact expression length" <| - test "exprSize = serExpr size on telescope boundaries (1/2/7/8/9/255/256/257)" - (telescopeExprs.all fun e => exprSize e == (serExpr e).size) ++ - test "exprSize = serExpr size on 2000 generated expressions with boundary Shares" - (gen.all fun e => exprSize e == (serExpr e).size) ++ - test "App with 7/8 args uses 1/2 header bytes" +def exprSizeTests : Spec := + describe "exact expression length" do + itBool "exprSize = serExpr size on telescope boundaries (1/2/7/8/9/255/256/257)" + (telescopeExprs.all fun e => exprSize e == (serExpr e).size) + it "exprSize = serExpr size on 2000 generated expressions with boundary Shares" do + let gen := runGen 7 ((List.range 2000).mapM fun _ => genExprForSize) + expect (gen.all fun e => exprSize e == (serExpr e).size) + itBool "App with 7/8 args uses 1/2 header bytes" (let a7 := (List.range 7).foldl (fun f _ => .app f (.var 0)) (.var 1) let a8 := Ixon.Expr.app a7 (.var 0) (serExpr a7).size == 1 + 8 && (serExpr a8).size == 2 + 9) @@ -343,24 +343,24 @@ def decompositionHolds (c : Constant) : Bool := cbytes c == fixedConstantBytes c + exprsSize (constantInfoRoots c.info) + tag0Size c.sharing.size + exprsSize c.sharing -def decompositionTests (_ : Unit) : TestSeq := - let mkRoots (k : Nat) (n : Nat) : Array Ixon.Expr := - (Array.range n).map fun i => .app (.share (k - 1 - i % (max k 1)).toUInt64) (.var i.toUInt64) - let infos (rs : Array Ixon.Expr) : List ConstantInfo := - [ .defn ⟨.defn, .safe, {}, 0, rs[0]!, rs[1]!⟩, .axio ⟨false, 1, rs[0]!⟩, - .quot ⟨.lift, 2, rs[0]!⟩, - .recr ⟨true, false, 1, 2, 3, 4, 5, rs[0]!, #[⟨1, rs[1]!⟩, ⟨300, rs[2]!⟩]⟩, - .cPrj ⟨1, 2, testRefs[0]!⟩, .rPrj ⟨3, testRefs[1]!⟩, .iPrj ⟨200, testRefs[0]!⟩, - .dPrj ⟨0, testRefs[1]!⟩, - .muts #[.defn ⟨.thm, .part, {}, 0, rs[0]!, rs[1]!⟩, - .indc ⟨true, 1, 1, 0, rs[2]!, #[⟨false, 1, 0, 1, 2, .inherited, rs[3]!⟩, ⟨false, 1, 1, 1, 0, .inherited, rs[0]!⟩]⟩, - .recr ⟨false, true, 0, 0, 0, 0, 0, rs[1]!, #[⟨2, rs[2]!⟩]⟩] ] - let cases := [0, 1, 8, 9, 127, 128, 255, 256, 257, 1032, 1033].flatMap fun k => - (infos (mkRoots k 4)).map fun info => tableConstant info k - group "complete-Constant length decomposition" <| - test s!"serConstant size = fixed + roots + tag0(table) + table on {cases.length} constants (all kinds; tables 0/1/8/9/127/128/255/256/257/1032/1033)" - (cases.all decompositionHolds) ++ - test "Share 7/8 and 1031/1032 have widths 1/2 and 2/3" +def decompositionTests : Spec := + describe "complete-Constant length decomposition" do + it "serConstant size = fixed + roots + tag0(table) + table (all kinds; tables 0/1/8/9/127/128/255/256/257/1032/1033)" do + let mkRoots (k : Nat) (n : Nat) : Array Ixon.Expr := + (Array.range n).map fun i => .app (.share (k - 1 - i % (max k 1)).toUInt64) (.var i.toUInt64) + let infos (rs : Array Ixon.Expr) : List ConstantInfo := + [ .defn ⟨.defn, .safe, {}, 0, rs[0]!, rs[1]!⟩, .axio ⟨false, 1, rs[0]!⟩, + .quot ⟨.lift, 2, rs[0]!⟩, + .recr ⟨true, false, 1, 2, 3, 4, 5, rs[0]!, #[⟨1, rs[1]!⟩, ⟨300, rs[2]!⟩]⟩, + .cPrj ⟨1, 2, testRefs[0]!⟩, .rPrj ⟨3, testRefs[1]!⟩, .iPrj ⟨200, testRefs[0]!⟩, + .dPrj ⟨0, testRefs[1]!⟩, + .muts #[.defn ⟨.thm, .part, {}, 0, rs[0]!, rs[1]!⟩, + .indc ⟨true, 1, 1, 0, rs[2]!, #[⟨false, 1, 0, 1, 2, .inherited, rs[3]!⟩, ⟨false, 1, 1, 1, 0, .inherited, rs[0]!⟩]⟩, + .recr ⟨false, true, 0, 0, 0, 0, 0, rs[1]!, #[⟨2, rs[2]!⟩]⟩] ] + let cases := [0, 1, 8, 9, 127, 128, 255, 256, 257, 1032, 1033].flatMap fun k => + (infos (mkRoots k 4)).map fun info => tableConstant info k + expect (cases.all decompositionHolds) s!"decomposition failed on {cases.length} constants" + itBool "Share 7/8 and 1031/1032 have widths 1/2 and 2/3" (exprSize (.share 7) == 1 && exprSize (.share 8) == 2 && exprSize (.share 1031) == 2 && exprSize (.share 1032) == 3) @@ -370,161 +370,182 @@ def fixtureA : Ixon.Expr := arr P P def fixtureB : Ixon.Expr := arr P (.sort 1) def tiedMinimaRoot : Ixon.Expr := arr fixtureA (arr fixtureA (arr fixtureB fixtureB)) -def structuralIdTests (_ : Unit) : TestSeq := - let naiveAgree := runGen 11 do - let mut ok := true - for _ in [0:300] do - let roots ← genRoots 5 10 3 - match expandRoots roots with - | .ok ex => - let naive := naiveCanonical roots - let rootIdx := roots.map fun r => (naive.findIdx? (· == r)).getD 1000000 - ok := ok && ex.dag.toExprs == naive && ex.roots == rootIdx - | .error _ => ok := false - return ok - group "structural IDs" <| - withOk "tied-minima fixture" (expandRoots #[tiedMinimaRoot]) (fun ex => - test "ids: Sort0=0 Sort1=1 A=2 B=3 (B→B)=4 (A→B→B)=5 root=6" - (ex.dag.toExprs == #[P, .sort 1, fixtureA, fixtureB, arr fixtureB fixtureB, - arr fixtureA (arr fixtureB fixtureB), tiedMinimaRoot] && ex.roots == #[6])) ++ - withOk "witness" (expandRoots #[arr (chain 2) (chain 2)]) (fun ex => - test "ids: P=0 T1=1 T2=2 R=3" (ex.dag.toExprs == #[P, chain 1, chain 2, - arr (chain 2) (chain 2)])) ++ - test "canonical IDs equal an independent naive assignment on 300 generated inputs" - naiveAgree ++ - test "let modes are part of structural identity" +def structuralIdTests : Spec := + describe "structural IDs" do + it "tied-minima fixture: ids Sort0=0 Sort1=1 A=2 B=3 (B→B)=4 (A→B→B)=5 root=6" do + withOk "tied-minima fixture" (expandRoots #[tiedMinimaRoot]) fun ex => + expect (ex.dag.toExprs == #[P, .sort 1, fixtureA, fixtureB, arr fixtureB fixtureB, + arr fixtureA (arr fixtureB fixtureB), tiedMinimaRoot] && ex.roots == #[6]) + it "witness: ids P=0 T1=1 T2=2 R=3" do + withOk "witness" (expandRoots #[arr (chain 2) (chain 2)]) fun ex => + expect (ex.dag.toExprs == #[P, chain 1, chain 2, arr (chain 2) (chain 2)]) + it "canonical IDs equal an independent naive assignment on 300 generated inputs" do + let naiveAgree := runGen 11 do + let mut ok := true + for _ in [0:300] do + let roots ← genRoots 5 10 3 + match expandRoots roots with + | .ok ex => + let naive := naiveCanonical roots + let rootIdx := roots.map fun r => (naive.findIdx? (· == r)).getD 1000000 + ok := ok && ex.dag.toExprs == naive && ex.roots == rootIdx + | .error _ => ok := false + return ok + expect naiveAgree + itBool "let modes are part of structural identity" (distinctCount #[.lam P P, .all P P, .letE true (.value .many) P P P, .letE false (.value .many) P P P, .letE false .borrow P P P, - .letE false (.value .erased) P P P] == 7) ++ - test "lexCompare: proper prefix first, then numeric" + .letE false (.value .erased) P P P] == 7) + itBool "lexCompare: proper prefix first, then numeric" (lexCompare [1] [1, 0] == .lt && lexCompare [] [0] == .lt && - lexCompare [2] [10] == .lt && lexCompare [1, 0] [1] == .gt) ++ - test "compareBytes: unsigned, proper prefix first" + lexCompare [2] [10] == .lt && lexCompare [1, 0] [1] == .gt) + itBool "compareBytes: unsigned, proper prefix first" (compareBytes ⟨#[0x7f]⟩ ⟨#[0x80]⟩ == .lt && compareBytes ⟨#[1]⟩ ⟨#[1, 0]⟩ == .lt && compareBytes ⟨#[0xff]⟩ ⟨#[0x00, 0x00]⟩ == .gt) /-- The same AST in three pointer layouts: generated (pool-shared), fresh (deserialized, no sharing), and maximally shared (from the DAG). -/ -def representationTestsWith (count : Nat) (_ : Unit) : TestSeq := - let ok := runGen 13 do - let mut ok := true - for i in [0:count] do - let roots ← genRoots 5 10 3 - let c := wrapRoots roots i - let fresh := match deConstant (serConstant c) with - | .ok c' => c' - | .error _ => c - let dagShared := match expandConstantSharing c with - | .ok c' => c' - | .error _ => c - let alt := alternateOf c - let outs := [c, fresh, dagShared, alt].map fun x => - (normalizeConstantSharing x).toOption.map serConstant - let tiered := [c, fresh, dagShared, alt].map fun x => - (normalizeConstantSharingTiered .tagN x).toOption.map serConstant - ok := ok && outs.all (· == outs.head!) && outs.head!.isSome && - tiered.all (· == tiered.head!) && tiered.head!.isSome - return ok - group "representation independence" <| - test s!"pool-shared, deserialized, DAG-shared and uniform-w1-encoded inputs normalize to identical bytes, by the exact search and by the tiered construction ({count} inputs)" ok - -def representationTests (_ : Unit) : TestSeq := representationTestsWith 120 () -def representationTestsPR (_ : Unit) : TestSeq := representationTestsWith 50 () - -def cacheTests (_ : Unit) : TestSeq := - let empty : ExprCache Nat := {} - let key : ExprCache.Key := ⟨0, .var 3⟩ - let cached := empty.insert key 17 - let collision := cached.insert ⟨0, .var 4⟩ 29 - let context : ShareCtx := { resolved := #[], tableSize := 0, entry := none, root := 0, allowShare := false } - let source : Ixon.Expr := .app (.var 3) (.var 4) - let poisoned : IngestState := - { ptrCache := empty.insert ⟨(exprKey source).address, .sort 8⟩ 999 } - let ordinary := (ingestExpr {} context 0 source).run {} - let repaired := (ingestExpr {} context 0 source).run poisoned - let illegal : Ixon.Expr := .share 0 - let illegalState : IngestState := { ptrCache := empty.insert ⟨(exprKey illegal).address, .var 0⟩ 17 } - let dag : Ixon.Expr := (List.range 36).foldl (fun e _ => .app e e) (.var 3) - group "checked expression cache" <| - test "an exact key retrieves its cached ID" (cached.get? key == some 17) ++ - test "a colliding address with a different expression misses" - (cached.get? ⟨0, .var 4⟩ == none) ++ - test "collision replacement cannot return the evicted expression's ID" - (collision.get? key == none && collision.get? ⟨0, .var 4⟩ == some 29) ++ - test "equal expression structure can use the same candidate bucket" - ((empty.insert ⟨0, .app (.var 3) (.var 4)⟩ 17).get? ⟨0, source⟩ == some 17) ++ - test "let modes are checked before accepting a hit" - ((empty.insert ⟨0, .letE false (.value .many) P P P⟩ 17).get? - ⟨0, .letE false .borrow P P P⟩ == none) ++ - test "poisoning a pointer bucket cannot bypass actual ingestion" - (ordinary.toOption.map (fun (id, state) => (id, state.interner.nodes, state.visits)) == - repaired.toOption.map (fun (id, state) => (id, state.interner.nodes, state.visits)) && repaired.isOk) ++ - test "a colliding candidate cannot hide an illegal Share" - (isErr ((ingestExpr {} context 0 illegal).run illegalState) (· == .shareInExpandedInput 0 0)) ++ - test "fast re-expansion rejects the same colliding candidate" - (match ordinary with +def representationTestsWith (count : Nat) : Spec := + describe "representation independence" do + it s!"pool-shared, deserialized, DAG-shared and uniform-w1-encoded inputs normalize to identical bytes, by the exact search and by the tiered construction ({count} inputs)" do + let ok := runGen 13 do + let mut ok := true + for i in [0:count] do + let roots ← genRoots 5 10 3 + let c := wrapRoots roots i + let fresh := match deConstant (serConstant c) with + | .ok c' => c' + | .error _ => c + let dagShared := match expandConstantSharing c with + | .ok c' => c' + | .error _ => c + let alt := alternateOf c + let outs := [c, fresh, dagShared, alt].map fun x => + (normalizeConstantSharing x).toOption.map serConstant + let tiered := [c, fresh, dagShared, alt].map fun x => + (normalizeConstantSharingTiered .tagN x).toOption.map serConstant + ok := ok && outs.all (· == outs.head!) && outs.head!.isSome && + tiered.all (· == tiered.head!) && tiered.head!.isSome + return ok + expect ok + +def representationTests : Spec := representationTestsWith 120 +def representationTestsPR : Spec := representationTestsWith 50 + +def cacheTests : Spec := + describe "checked expression cache" do + it "an exact key retrieves its cached ID" do + let empty : ExprCache Nat := {} + let key : ExprCache.Key := ⟨0, .var 3⟩ + let cached := empty.insert key 17 + expect (cached.get? key == some 17) + it "a colliding address with a different expression misses" do + let empty : ExprCache Nat := {} + let cached := empty.insert ⟨0, .var 3⟩ 17 + expect (cached.get? ⟨0, .var 4⟩ == none) + it "collision replacement cannot return the evicted expression's ID" do + let empty : ExprCache Nat := {} + let key : ExprCache.Key := ⟨0, .var 3⟩ + let cached := empty.insert key 17 + let collision := cached.insert ⟨0, .var 4⟩ 29 + expect (collision.get? key == none && collision.get? ⟨0, .var 4⟩ == some 29) + it "equal expression structure can use the same candidate bucket" do + let empty : ExprCache Nat := {} + let source : Ixon.Expr := .app (.var 3) (.var 4) + expect ((empty.insert ⟨0, .app (.var 3) (.var 4)⟩ 17).get? ⟨0, source⟩ == some 17) + it "let modes are checked before accepting a hit" do + let empty : ExprCache Nat := {} + expect ((empty.insert ⟨0, .letE false (.value .many) P P P⟩ 17).get? + ⟨0, .letE false .borrow P P P⟩ == none) + it "poisoning a pointer bucket cannot bypass actual ingestion" do + let empty : ExprCache Nat := {} + let context : ShareCtx := { resolved := #[], tableSize := 0, entry := none, root := 0, allowShare := false } + let source : Ixon.Expr := .app (.var 3) (.var 4) + let poisoned : IngestState := + { ptrCache := empty.insert ⟨(exprKey source).address, .sort 8⟩ 999 } + let ordinary := (ingestExpr {} context 0 source).run {} + let repaired := (ingestExpr {} context 0 source).run poisoned + expect (ordinary.toOption.map (fun (id, state) => (id, state.interner.nodes, state.visits)) == + repaired.toOption.map (fun (id, state) => (id, state.interner.nodes, state.visits)) && repaired.isOk) + it "a colliding candidate cannot hide an illegal Share" do + let empty : ExprCache Nat := {} + let context : ShareCtx := { resolved := #[], tableSize := 0, entry := none, root := 0, allowShare := false } + let illegal : Ixon.Expr := .share 0 + let illegalState : IngestState := { ptrCache := empty.insert ⟨(exprKey illegal).address, .var 0⟩ 17 } + expect (isErr ((ingestExpr {} context 0 illegal).run illegalState) (· == .shareInExpandedInput 0 0)) + it "fast re-expansion rejects the same colliding candidate" do + let empty : ExprCache Nat := {} + let context : ShareCtx := { resolved := #[], tableSize := 0, entry := none, root := 0, allowShare := false } + let source : Ixon.Expr := .app (.var 3) (.var 4) + let poisoned : IngestState := + { ptrCache := empty.insert ⟨(exprKey source).address, .sort 8⟩ 999 } + let ordinary := (ingestExpr {} context 0 source).run {} + expect (match ordinary with | .ok (id, state) => let target : Dag := ⟨state.interner.nodes⟩ match reIngestExpr {} target (ReIndex.ofDag target) context 0 source poisoned.ptrCache 0 with | .ok actual _ _ => actual == id | _ => false - | .error _ => false : Bool) ++ - test "a 36-level shared DAG keeps linear ingestion work" - (match (ingestExpr {} context 0 dag).run {} with + | .error _ => false) + it "a 36-level shared DAG keeps linear ingestion work" do + let context : ShareCtx := { resolved := #[], tableSize := 0, entry := none, root := 0, allowShare := false } + let dag : Ixon.Expr := (List.range 36).foldl (fun e _ => .app e e) (.var 3) + expect (match (ingestExpr {} context 0 dag).run {} with | .ok (_, state) => state.interner.nodes.size == 37 && state.visits == 37 - | .error _ => false : Bool) - -def expansionTests (_ : Unit) : TestSeq := - let chainTable (k : Nat) : Array Ixon.Expr := - #[.var 0] ++ (Array.range (k - 1)).map fun i => .app (.share i.toUInt64) (.var 0) - let validTables := runGen 17 do - let mut ok := true - for _ in [0:100] do - -- A random valid backward table: entry i is a node over earlier Shares and leaves. - let k := 1 + (← rand 6) - let mut table : Array Ixon.Expr := #[] - for i in [0:k] do - let pick : RGen Ixon.Expr := do - if i > 0 && (← rand 2) == 0 then pure (.share (← rand i).toUInt64) else genLeaf - table := table.push (← genNode #[← pick, ← pick, ← pick]) - let roots := #[Ixon.Expr.app (.share (k - 1).toUInt64) (.share 0), .share (← rand k).toUInt64] - let info : ConstantInfo := .defn ⟨.defn, .safe, {}, 0, roots[0]!, roots[1]!⟩ - let c : Constant := { info, sharing := table, refs := #[], univs := #[] } - match expandConstantSharing c with - | .ok c' => ok := ok && constantInfoRoots c'.info == roots.map (naiveExpand table) - | .error _ => ok := false - return ok - group "bounded share expansion" <| - test "expansion equals direct substitution on 100 random backward tables" validTables ++ - test "forward reference is rejected" + | .error _ => false) + +def expansionTests : Spec := + describe "bounded share expansion" do + it "expansion equals direct substitution on 100 random backward tables" do + let validTables := runGen 17 do + let mut ok := true + for _ in [0:100] do + -- A random valid backward table: entry i is a node over earlier Shares and leaves. + let k := 1 + (← rand 6) + let mut table : Array Ixon.Expr := #[] + for i in [0:k] do + let pick : RGen Ixon.Expr := do + if i > 0 && (← rand 2) == 0 then pure (.share (← rand i).toUInt64) else genLeaf + table := table.push (← genNode #[← pick, ← pick, ← pick]) + let roots := #[Ixon.Expr.app (.share (k - 1).toUInt64) (.share 0), .share (← rand k).toUInt64] + let info : ConstantInfo := .defn ⟨.defn, .safe, {}, 0, roots[0]!, roots[1]!⟩ + let c : Constant := { info, sharing := table, refs := #[], univs := #[] } + match expandConstantSharing c with + | .ok c' => ok := ok && constantInfoRoots c'.info == roots.map (naiveExpand table) + | .error _ => ok := false + return ok + expect validTables + itBool "forward reference is rejected" (isErr (optimizeSharingTable #[.share 1, P] #[.share 0]) - (· == .nonBackwardShare 0 1)) ++ - test "self reference is rejected" + (· == .nonBackwardShare 0 1)) + itBool "self reference is rejected" (isErr (optimizeSharingTable #[.app (.share 0) P] #[.share 0]) - (· == .nonBackwardShare 0 0)) ++ - test "out-of-range root reference is rejected" - (isErr (optimizeSharingTable #[] #[.share 3]) (· == .shareOutOfRange none 3 0)) ++ - test "re-expanding the DAG's own roots gives their IDs; an encoding of another term (the fast path's fallback) gives it a fresh ID" + (· == .nonBackwardShare 0 0)) + itBool "out-of-range root reference is rejected" + (isErr (optimizeSharingTable #[] #[.share 3]) (· == .shareOutOfRange none 3 0)) + itBool "re-expanding the DAG's own roots gives their IDs; an encoding of another term (the fast path's fallback) gives it a fresh ID" (match expandRoots #[arr (chain 2) (chain 2)] with | .ok ex => (reexpand {} ex.dag #[] #[arr (chain 2) (chain 2)]).toOption.map (·.2.1) == some ex.roots && ((reexpand {} ex.dag #[] #[arr (chain 3) (chain 3)]).toOption.map - fun r => r.2.1.all (· ≥ ex.dag.size)) == some true - | .error _ => false : Bool) ++ - test "out-of-range entry reference is rejected" - (isErr (optimizeSharingTable #[.share 5] #[P]) (· == .shareOutOfRange (some 0) 5 1)) ++ - test "Share in an expanded-root input is rejected" - (isErr (optimizeSharing #[P, .share 0]) (· == .shareInExpandedInput 1 0)) ++ - test "stored depth limit" - (isErr (optimizeSharing #[chain 20] { maxDepth := 10 }) (exhausted .depth)) ++ - test "expanded height limit (shallow entries, deep expansion)" - (isErr (optimizeSharingTable (chainTable 40) #[.share 39] { maxDepth := 20 }) - (exhausted .depth)) ++ - test "distinct-node limit" - (isErr (optimizeSharing #[chain 30] { maxNodes := 10 }) (exhausted .nodes)) ++ - test "walk limit" - (isErr (optimizeSharing #[chain 30] { maxExprVisits := 10 }) (exhausted .exprVisits)) ++ - test "unreachable entries do not affect the result" + fun r => r.2.1.all (fun i => decide (i ≥ ex.dag.size))) == some true + | .error _ => false) + itBool "out-of-range entry reference is rejected" + (isErr (optimizeSharingTable #[.share 5] #[P]) (· == .shareOutOfRange (some 0) 5 1)) + itBool "Share in an expanded-root input is rejected" + (isErr (optimizeSharing #[P, .share 0]) (· == .shareInExpandedInput 1 0)) + itBool "stored depth limit" + (isErr (optimizeSharing #[chain 20] { maxDepth := 10 }) (exhausted .depth)) + itBool "expanded height limit (shallow entries, deep expansion)" + (let chainTable (k : Nat) : Array Ixon.Expr := + #[.var 0] ++ (Array.range (k - 1)).map fun i => .app (.share i.toUInt64) (.var 0) + isErr (optimizeSharingTable (chainTable 40) #[.share 39] { maxDepth := 20 }) + (exhausted .depth)) + itBool "distinct-node limit" + (isErr (optimizeSharing #[chain 30] { maxNodes := 10 }) (exhausted .nodes)) + itBool "walk limit" + (isErr (optimizeSharing #[chain 30] { maxExprVisits := 10 }) (exhausted .exprVisits)) + itBool "unreachable entries do not affect the result" (let c := axiomOf (arr (chain 2) (chain 2)) let garbage : Constant := { c with info := .axio ⟨false, 0, arr (.share 2) (.share 2)⟩, @@ -545,22 +566,22 @@ def sampleInfos : List ConstantInfo := .recr ⟨false, false, 0, 0, 0, 0, 0, e 13, #[⟨0, e 14⟩]⟩], .muts #[] ] -def rootApiTests (_ : Unit) : TestSeq := - let shift (rs : Array Ixon.Expr) := rs.map fun r => Ixon.Expr.app r (.var 99) - group "root extraction and reassembly" <| - test "constantInfoRoots = Ix.CompileM.constantInfoRootExprs on every kind" - (sampleInfos.all fun i => constantInfoRoots i == Ix.CompileM.constantInfoRootExprs i) ++ - test "withRoots consumes exactly the extracted roots in order" - (sampleInfos.all fun i => - let rs := shift (constantInfoRoots i) - match withRoots i rs with - | .ok i' => constantInfoRoots i' == rs && (withRoots i' (constantInfoRoots i)).toOption == some i - | .error _ => false) ++ - test "mapRoots f info = withRoots info ((constantInfoRoots info).map f) on every kind" +def rootApiTests : Spec := + describe "root extraction and reassembly" do + itBool "constantInfoRoots = Ix.CompileM.constantInfoRootExprs on every kind" + (sampleInfos.all fun i => constantInfoRoots i == Ix.CompileM.constantInfoRootExprs i) + itBool "withRoots consumes exactly the extracted roots in order" + (let shift (rs : Array Ixon.Expr) := rs.map fun r => Ixon.Expr.app r (.var 99) + sampleInfos.all fun i => + let rs := shift (constantInfoRoots i) + match withRoots i rs with + | .ok i' => constantInfoRoots i' == rs && (withRoots i' (constantInfoRoots i)).toOption == some i + | .error _ => false) + itBool "mapRoots f info = withRoots info ((constantInfoRoots info).map f) on every kind" (sampleInfos.all fun i => let g := fun r => Ixon.Expr.app r (.var 98) - (withRoots i ((constantInfoRoots i).map g)).toOption == some (mapRoots g i)) ++ - test "withRoots rejects one root too many / too few" + (withRoots i ((constantInfoRoots i).map g)).toOption == some (mapRoots g i)) + itBool "withRoots rejects one root too many / too few" (sampleInfos.all fun i => let rs := constantInfoRoots i isErr (withRoots i (rs.push P)) (· == .rootCountMismatch rs.size (rs.size + 1)) && @@ -648,85 +669,84 @@ def genSpines : RGen (Array Ixon.Expr) := do roots := roots.push (.app e e) return roots -def spineWalkTests (_ : Unit) : TestSeq := - let (checked, err) := runGen 53 do - let mut checked := 0 - let mut err : Option String := none - for i in [0:200] do - if err.isSome then break - let roots ← genSpines - match expandRoots roots with - | .ok ex => - let n := ex.dag.size - let p := Prep.ofDag ex.dag - let mut width : Array (Option Nat) := Array.replicate n none - for t in [0:n] do - if (← rand 3) == 0 then - let idx := [← rand 8, 8 + (← rand 300), 65530 + (← rand 12), 2^32 + (← rand 3)][← rand 4]! - width := width.set! t (some (shareWidth idx)) - checked := checked + 1 - unless (p.costsAll width).1 == walkCosts ex.dag width && - p.base == walkCosts ex.dag (Array.replicate n none) do - err := some s!"case {i}: available-descendant evaluation differs from the full spine walk" - | .error e => err := some s!"case {i}: error {reprStr e}" - return (checked, err) - group "telescope evaluation vs full spine walk" <| - test s!"{checked} long-spine DAGs with random dictionaries (widths 1–5): costs equal the O(l) walk over every cut" (err.isNone && checked == 200) ++ - (match err with | some m => test m false | none => .done) - -def deepTests (_ : Unit) : TestSeq := - let d := 10000 - let nested : Ixon.Expr := - (List.range d).foldl (fun acc i => .app (.var (i % 2).toUInt64) acc) (.sort 0) - let telescope : Ixon.Expr := - (List.range d).foldl (fun acc i => .lam (.var (i % 3).toUInt64) acc) (.sort 0) - group "deep inputs" <| - withOk "deep" (optimizeSharing #[nested, telescope]) fun r => - test s!"{d}-deep argument nesting and a {d}-binder telescope optimize under default limits ({r.variableBytes} bytes = unshared {r.unsharedBytes})" - (r.variableBytes == r.unsharedBytes && +def spineWalkTests : Spec := + describe "telescope evaluation vs full spine walk" do + it "200 long-spine DAGs with random dictionaries (widths 1–5): costs equal the O(l) walk over every cut" do + let (checked, err) := runGen 53 do + let mut checked := 0 + let mut err : Option String := none + for i in [0:200] do + if err.isSome then break + let roots ← genSpines + match expandRoots roots with + | .ok ex => + let n := ex.dag.size + let p := Prep.ofDag ex.dag + let mut width : Array (Option Nat) := Array.replicate n none + for t in [0:n] do + if (← rand 3) == 0 then + let idx := [← rand 8, 8 + (← rand 300), 65530 + (← rand 12), 2^32 + (← rand 3)][← rand 4]! + width := width.set! t (some (shareWidth idx)) + checked := checked + 1 + unless (p.costsAll width).1 == walkCosts ex.dag width && + p.base == walkCosts ex.dag (Array.replicate n none) do + err := some s!"case {i}: available-descendant evaluation differs from the full spine walk" + | .error e => err := some s!"case {i}: error {reprStr e}" + return (checked, err) + if let some m := err then fail m + expect (checked == 200) s!"checked {checked} != 200" + +def deepTests : Spec := + describe "deep inputs" do + it "10000-deep argument nesting and a 10000-binder telescope optimize under default limits" do + let d := 10000 + let nested : Ixon.Expr := + (List.range d).foldl (fun acc i => .app (.var (i % 2).toUInt64) acc) (.sort 0) + let telescope : Ixon.Expr := + (List.range d).foldl (fun acc i => .lam (.var (i % 3).toUInt64) acc) (.sort 0) + withOk "deep" (optimizeSharing #[nested, telescope]) fun r => + expect (r.variableBytes == r.unsharedBytes && r.variableBytes == exprSize nested + exprSize telescope + 1 && r.variableBytes == (serExpr nested).size + (serExpr telescope).size + 1) + s!"variableBytes={r.variableBytes}, unsharedBytes={r.unsharedBytes}" -def dictionaryTestsWith (fixMax fixOffMax genTarget genMaxOrders : Nat) (_ : Unit) : TestSeq := +def dictionaryTestsWith (fixMax fixOffMax genTarget genMaxOrders : Nat) : Spec := let fixtures : List (String × Array Ixon.Expr) := [("T2→T2", #[arr (chain 2) (chain 2)]), ("A→A→B→B", #[tiedMinimaRoot]), ("mixed spines", #[.app (.app (.lam P (arr P P)) (arr P P)) (.app (.var 0) (arr P P))]), ("let/prj", #[.letE false (.value .many) (arr P P) (.prj 0 1 (.app (.var 0) P)) (.app (.var 0) P)])] - let fixtureSeq := fixtures.foldl (init := .done) fun acc (name, roots) => - acc ++ withOk name (expandRoots roots) fun ex => - -- Up to `fixMax` of the ordered dictionaries (strided when there are - -- more), each at indices 0.., and `fixOffMax` of them at every index offset. - let total := (orderedSubsets ex.dag.size (List.range ex.dag.size)).length - let stride := if total > fixMax then 7 else 1 - let (c1, e1) := dictionaryAgreement ex.dag [0] fixMax stride - let (c2, e2) := dictionaryAgreement ex.dag dictOffsets fixOffMax (stride * 3) - let err := e1.or e2 - test s!"{name}: C_M and byte-least materialization = enumeration ({c1 + c2} cases over {total} ordered dictionaries, stride {stride}; {dictOffsets.length} index offsets)" - (err.isNone) ++ - (match err with | some m => test m false | none => .done) - let (genChecked, genErr) := runGen 19 do - let mut checked := 0 - let mut err : Option String := none - let mut cases := 0 - for _ in [0:400] do - if cases ≥ genTarget || err.isSome then break - let roots ← genRoots 3 4 2 - match expandRoots roots with - | .ok ex => - if ex.dag.size ≤ 5 then - cases := cases + 1 - let (c, e) := dictionaryAgreement ex.dag [0, 6, 254] genMaxOrders - checked := checked + c - if let some m := e then err := some s!"{m} roots={reprStr roots}" - | .error _ => pure () - return (checked, err) - group "fixed-dictionary optimizer vs enumeration" <| - fixtureSeq ++ - test s!"generated inputs (N ≤ 5): {genChecked} (dictionary, term) cases agree" genErr.isNone ++ - (match genErr with | some m => test m false | none => .done) - -def dictionaryTests (_ : Unit) : TestSeq := dictionaryTestsWith 2000 300 60 400 () -def dictionaryTestsPR (_ : Unit) : TestSeq := dictionaryTestsWith 120 40 15 80 () + describe "fixed-dictionary optimizer vs enumeration" do + for (name, roots) in fixtures do + it s!"{name}: C_M and byte-least materialization = enumeration" do + withOk name (expandRoots roots) fun ex => do + -- Up to `fixMax` of the ordered dictionaries (strided when there are + -- more), each at indices 0.., and `fixOffMax` of them at every index offset. + let total := (orderedSubsets ex.dag.size (List.range ex.dag.size)).length + let stride := if total > fixMax then 7 else 1 + let (_, e1) := dictionaryAgreement ex.dag [0] fixMax stride + let (_, e2) := dictionaryAgreement ex.dag dictOffsets fixOffMax (stride * 3) + if let some m := e1.or e2 then fail m + it s!"generated inputs (N ≤ 5, up to {genTarget} cases): (dictionary, term) cases agree" do + let (_, genErr) := runGen 19 do + let mut checked := 0 + let mut err : Option String := none + let mut cases := 0 + for _ in [0:400] do + if cases ≥ genTarget || err.isSome then break + let roots ← genRoots 3 4 2 + match expandRoots roots with + | .ok ex => + if ex.dag.size ≤ 5 then + cases := cases + 1 + let (c, e) := dictionaryAgreement ex.dag [0, 6, 254] genMaxOrders + checked := checked + c + if let some m := e then err := some s!"{m} roots={reprStr roots}" + | .error _ => pure () + return (checked, err) + if let some m := genErr then fail m + +def dictionaryTests : Spec := dictionaryTestsWith 2000 300 60 400 +def dictionaryTestsPR : Spec := dictionaryTestsWith 120 40 15 80 /-! ## Full optimizer vs exhaustive oracle (P1/P3) -/ @@ -760,17 +780,19 @@ def oracleAgreement (seed cases maxN : Nat) (product : Bool) : Nat × Nat × Nat err := some s!"case {attempts}: error {reprStr e} roots={reprStr roots}" return (checked, skipped, tables, err) -def oracleTestsWith (partCases prodCases : Nat) (_ : Unit) : TestSeq := - let (n1, s1, t1, e1) := oracleAgreement 23 partCases 6 false - let (n2, s2, t2, e2) := oracleAgreement 29 prodCases 4 true - group "optimizer vs exhaustive oracle (full key)" <| - test s!"per-part oracle: {n1} generated constants (N ≤ 6, all kinds and let modes, {t1} tables) agree on bytes and table IDs ({s1} skipped: oracle budget)" (e1.isNone && n1 == partCases) ++ - (match e1 with | some m => test m false | none => .done) ++ - test s!"full-product oracle: {n2} generated constants (N ≤ 4, {t2} tables) agree ({s2} skipped: oracle budget)" (e2.isNone && n2 == prodCases) ++ - (match e2 with | some m => test m false | none => .done) +def oracleTestsWith (partCases prodCases : Nat) : Spec := + describe "optimizer vs exhaustive oracle (full key)" do + it s!"per-part oracle: {partCases} generated constants (N ≤ 6, all kinds and let modes) agree on bytes and table IDs" do + let (n1, s1, t1, e1) := oracleAgreement 23 partCases 6 false + if let some m := e1 then fail m + expect (n1 == partCases) s!"checked {n1}/{partCases} ({t1} tables, {s1} skipped)" + it s!"full-product oracle: {prodCases} generated constants (N ≤ 4) agree" do + let (n2, s2, t2, e2) := oracleAgreement 29 prodCases 4 true + if let some m := e2 then fail m + expect (n2 == prodCases) s!"checked {n2}/{prodCases} ({t2} tables, {s2} skipped)" -def oracleTests (_ : Unit) : TestSeq := oracleTestsWith 150 40 () -def oracleTestsPR (_ : Unit) : TestSeq := oracleTestsWith 30 10 () +def oracleTests : Spec := oracleTestsWith 150 40 +def oracleTestsPR : Spec := oracleTestsWith 30 10 /-- Unit-width relaxation (§4.1): with no telescope merging and at most 8 positive-weight terms of indegree ≥ 2, the minimum variable length is @@ -794,27 +816,28 @@ def unitWidthLength (roots : Array Ixon.Expr) : Option Nat := Id.run do return some (roots.size + kstar + tag0Size kstar + distinct.foldl (fun acc t => acc + w t) 0) -def unitWidthTestsWith (target minRequired : Nat) (_ : Unit) : TestSeq := - let (checked, err) := runGen 31 do - let mut checked := 0 - let mut err : Option String := none - for i in [0:600] do - if checked ≥ target || err.isSome then break - let roots ← genRoots 6 14 4 (noMerge := true) - let some expected := unitWidthLength roots | continue - match optimizeSharing roots with - | .ok r => - checked := checked + 1 - unless r.variableBytes == expected do - err := some s!"case {i}: exact={r.variableBytes} unit={expected} roots={reprStr roots}" - | .error e => err := some s!"case {i}: error {reprStr e}" - return (checked, err) - group "unit-width relaxation oracle" <| - test s!"exact length = unit-width optimum on {checked} merge-free generated inputs" (err.isNone && checked ≥ minRequired) ++ - (match err with | some m => test m false | none => .done) +def unitWidthTestsWith (target minRequired : Nat) : Spec := + describe "unit-width relaxation oracle" do + it s!"exact length = unit-width optimum on up to {target} merge-free generated inputs (≥ {minRequired})" do + let (checked, err) := runGen 31 do + let mut checked := 0 + let mut err : Option String := none + for i in [0:600] do + if checked ≥ target || err.isSome then break + let roots ← genRoots 6 14 4 (noMerge := true) + let some expected := unitWidthLength roots | continue + match optimizeSharing roots with + | .ok r => + checked := checked + 1 + unless r.variableBytes == expected do + err := some s!"case {i}: exact={r.variableBytes} unit={expected} roots={reprStr roots}" + | .error e => err := some s!"case {i}: error {reprStr e}" + return (checked, err) + if let some m := err then fail m + expect (decide (checked ≥ minRequired)) s!"checked {checked} < {minRequired}" -def unitWidthTests (_ : Unit) : TestSeq := unitWidthTestsWith 150 100 () -def unitWidthTestsPR (_ : Unit) : TestSeq := unitWidthTestsWith 50 50 () +def unitWidthTests : Spec := unitWidthTestsWith 150 100 +def unitWidthTestsPR : Spec := unitWidthTestsWith 50 50 /-- Independent atoms: for a fixed stored set the optimal order gives the cheapest slots to the most-used atoms, so a brute force over subsets gives @@ -834,80 +857,87 @@ def atomsBrute (sizes occs : Array Nat) : Nat := Id.run do if mask == 0 || cost < best then best := cost return best -def atomsTests (_ : Unit) : TestSeq := - let (checked, err) := runGen 37 do - let mut checked := 0 - let mut err : Option String := none - for i in [0:12] do - let n := 9 + (← rand 3) - let mut atoms : Array Ixon.Expr := #[] - let mut occs : Array Nat := #[] - for j in [0:n] do - atoms := atoms.push (.ref (j + 2).toUInt64 (Array.replicate (← rand 4) 0)) - occs := occs.push (2 + (← rand 12)) - let roots := (Array.range n).foldl (fun acc j => acc ++ Array.replicate occs[j]! atoms[j]!) #[] - let sizes := atoms.map exprSize - let expected := atomsBrute sizes occs - match optimizeSharing roots with - | .ok r => - checked := checked + 1 - unless r.variableBytes == expected do - err := some s!"case {i}: exact={r.variableBytes} brute={expected} occs={occs} sizes={sizes}" - | .error e => err := some s!"case {i}: error {reprStr e}" - return (checked, err) - group "multi-width buckets vs brute force" <| - test s!"independent atoms (9–11 atoms, slots cross index 8): {checked} cases equal the brute-force minimum" (err.isNone && checked == 12) ++ - (match err with | some m => test m false | none => .done) +def atomsTests : Spec := + describe "multi-width buckets vs brute force" do + it "independent atoms (9–11 atoms, slots cross index 8): 12 cases equal the brute-force minimum" do + let (checked, err) := runGen 37 do + let mut checked := 0 + let mut err : Option String := none + for i in [0:12] do + let n := 9 + (← rand 3) + let mut atoms : Array Ixon.Expr := #[] + let mut occs : Array Nat := #[] + for j in [0:n] do + atoms := atoms.push (.ref (j + 2).toUInt64 (Array.replicate (← rand 4) 0)) + occs := occs.push (2 + (← rand 12)) + let roots := (Array.range n).foldl (fun acc j => acc ++ Array.replicate occs[j]! atoms[j]!) #[] + let sizes := atoms.map exprSize + let expected := atomsBrute sizes occs + match optimizeSharing roots with + | .ok r => + checked := checked + 1 + unless r.variableBytes == expected do + err := some s!"case {i}: exact={r.variableBytes} brute={expected} occs={occs} sizes={sizes}" + | .error e => err := some s!"case {i}: error {reprStr e}" + return (checked, err) + if let some m := err then fail m + expect (checked == 12) s!"checked {checked} != 12" /-! ## §2 fixtures -/ def witness2 : Constant := axiomOf (arr (chain 2) (chain 2)) -def witnessTests (_ : Unit) : TestSeq := - -- A valid 17-byte encoding of T2 → T2, two bytes above the minimum. - let altBytes := ByteArray.mk #[0xd2, 0x00, 0x00, 0x91, 0xb1, 0xb1, 0x02, 0x91, - 0x00, 0x00, 0x91, 0x00, 0xb0, 0x00, 0x01, 0x00, 0x00] - let alt := (deConstant altBytes).toOption.getD witness2 - group "fixture T2 → T2 (17 → 15)" <| - test "the 17-byte encoding decodes to T2 → T2" - (hexOf (serConstant alt) == "d2000091b1b1029100009100b000010000" && +def witnessTests : Spec := + describe "fixture T2 → T2 (17 → 15)" do + it "the 17-byte encoding decodes to T2 → T2" do + -- A valid 17-byte encoding of T2 → T2, two bytes above the minimum. + let altBytes := ByteArray.mk #[0xd2, 0x00, 0x00, 0x91, 0xb1, 0xb1, 0x02, 0x91, + 0x00, 0x00, 0x91, 0x00, 0xb0, 0x00, 0x01, 0x00, 0x00] + let alt := (deConstant altBytes).toOption.getD witness2 + expect (hexOf (serConstant alt) == "d2000091b1b1029100009100b000010000" && (expandConstantSharing alt).toOption.map (constantInfoRoots ·.info) == - some (constantInfoRoots witness2.info)) ++ - test "unshared is 16 bytes" (cbytes witness2 == 16) ++ - withOk "exact" (optimizeSharingTable #[] (constantInfoRoots witness2.info)) (fun r => - test "exact table term IDs = [T2] = [2]" (r.tableTerms == #[2])) ++ - withOk "exact" (normalizeConstantSharing witness2) (fun n => - test "exact bytes d2000091b0b0019200000000010000 (15)" - (hexOf (serConstant n) == "d2000091b0b0019200000000010000")) ++ - withOk "exact from the 17-byte encoding" (normalizeConstantSharing alt) (fun n => - test "normalizing the 17-byte encoding gives the same 15 bytes" - (hexOf (serConstant n) == "d2000091b0b0019200000000010000")) ++ - withOk "oracle" (oracleConstant witness2) (fun (oc, o) => - test s!"per-part oracle: 15-byte unique minimum over {o.work.tables} ordered tables" - (hexOf (serConstant oc) == "d2000091b0b0019200000000010000" && - o.work.tables == 65 && o.minima.size == 1)) + some (constantInfoRoots witness2.info)) + itBool "unshared is 16 bytes" (cbytes witness2 == 16) + it "exact table term IDs = [T2] = [2]" do + withOk "exact" (optimizeSharingTable #[] (constantInfoRoots witness2.info)) fun r => + expect (r.tableTerms == #[2]) + it "exact bytes d2000091b0b0019200000000010000 (15)" do + withOk "exact" (normalizeConstantSharing witness2) fun n => + expect (hexOf (serConstant n) == "d2000091b0b0019200000000010000") + it "normalizing the 17-byte encoding gives the same 15 bytes" do + let altBytes := ByteArray.mk #[0xd2, 0x00, 0x00, 0x91, 0xb1, 0xb1, 0x02, 0x91, + 0x00, 0x00, 0x91, 0x00, 0xb0, 0x00, 0x01, 0x00, 0x00] + let alt := (deConstant altBytes).toOption.getD witness2 + withOk "exact from the 17-byte encoding" (normalizeConstantSharing alt) fun n => + expect (hexOf (serConstant n) == "d2000091b0b0019200000000010000") + it "per-part oracle: 15-byte unique minimum over 65 ordered tables" do + withOk "oracle" (oracleConstant witness2) fun (oc, o) => + expect (hexOf (serConstant oc) == "d2000091b0b0019200000000010000" && + o.work.tables == 65 && o.minima.size == 1) /-- Full-product brute-force oracle over all 3,061,082 complete candidates for `witness2` (nightly sweep). -/ -def witnessProductOracleTests (_ : Unit) : TestSeq := - group "fixture T2 → T2 (full-product oracle)" <| - withOk "product oracle" (oracleConstant witness2 {} true) (fun (oc, o) => - test s!"full-product oracle: {o.work.candidates} complete candidates, 15-byte unique minimum" - (hexOf (serConstant oc) == "d2000091b0b0019200000000010000" && - o.work.candidates == 3061082 && o.minima.size == 1)) +def witnessProductOracleTests : Spec := + describe "fixture T2 → T2 (full-product oracle)" do + it "full-product oracle: 3061082 complete candidates, 15-byte unique minimum" do + withOk "product oracle" (oracleConstant witness2 {} true) fun (oc, o) => + expect (hexOf (serConstant oc) == "d2000091b0b0019200000000010000" && + o.work.candidates == 3061082 && o.minima.size == 1) def witness16 : Constant := axiomOf (arr (chain 16) (chain 16)) -def t16Tests (_ : Unit) : TestSeq := - let only16 : Constant := { witness16 with - info := .axio ⟨false, 0, arr (.share 0) (.share 0)⟩, sharing := #[chain 16] } - group "fixture T16 → T16" <| - test "unshared is 46 bytes" (cbytes witness16 == 46) ++ - test "storing only T16 is 30 bytes" (cbytes only16 == 30) ++ - withOk "exact" (optimizeSharingTable #[] (constantInfoRoots witness16.info)) (fun r => - withOk "exact" (normalizeConstantSharing witness16) fun n => - test s!"exact certified minimum = {cbytes n} bytes ≤ 30 (candidates {r.stats.candidates}, states reached {r.stats.statesReached}, expanded {r.stats.statesExpanded}, pruned {r.stats.statesPruned}, transitions {r.stats.transitions})" - (cbytes n ≤ 30 && cbytes n == r.variableBytes + 7)) +def t16Tests : Spec := + describe "fixture T16 → T16" do + itBool "unshared is 46 bytes" (cbytes witness16 == 46) + itBool "storing only T16 is 30 bytes" + (let only16 : Constant := { witness16 with + info := .axio ⟨false, 0, arr (.share 0) (.share 0)⟩, sharing := #[chain 16] } + cbytes only16 == 30) + it "exact certified minimum ≤ 30 bytes" do + withOk "exact" (optimizeSharingTable #[] (constantInfoRoots witness16.info)) fun r => + withOk "exact" (normalizeConstantSharing witness16) fun n => + expect (decide (cbytes n ≤ 30) && cbytes n == r.variableBytes + 7) + s!"cbytes={cbytes n}, variableBytes={r.variableBytes}" /-- The nine-Ref fixture, built as in the production probe: atoms sorted by the blake3 hash of their encoding, each twice, then 98 more uses of the last (hot) atom; one @@ -926,198 +956,212 @@ def nineRef : Constant × Ixon.Expr := univs := #[.zero] } (c, hot) -def nineRefTests (_ : Unit) : TestSeq := - let (c, hot) := nineRef - -- Two tables of the nine atoms: hash order (the hot atom last, in the 2-byte - -- slot 8) and most-used first. - let atoms := (constantInfoRoots c.info).foldl - (fun acc a => if acc.contains a then acc else acc.push a) #[] - let tableWith (table : Array Ixon.Expr) : Constant := - let idxOf (a : Ixon.Expr) : Nat := (table.findIdx? (· == a)).getD 0 - let roots := (constantInfoRoots c.info).map fun a => Ixon.Expr.share (idxOf a).toUInt64 - match withRoots c.info roots with - | .ok info => { c with info, sharing := table } - | .error _ => c - let hashOrder := tableWith atoms - let freqTable := #[hot] ++ (atoms.filter (· != hot)) - group "fixture nine independent Refs (677 → 579)" <| - test "hot atom is Ref(2,[0,0,0])" (hot == .ref 2 #[0, 0, 0]) ++ - test "hash order: 677 bytes, hot atom in slot 8" - (cbytes hashOrder == 677 && atoms.size == 9 && atoms[8]? == some hot) ++ - test "same entries, frequency order: 579 bytes" (cbytes (tableWith freqTable) == 579) ++ - withOk "exact" (optimizeSharingTable #[] (constantInfoRoots c.info)) (fun r => - withOk "exact" (normalizeConstantSharing c) fun n => - test s!"exact: {cbytes n} bytes, table IDs {r.tableTerms}, hot atom at a width-1 slot" - (cbytes n == 579 && r.tableTerms == #[0, 1, 2, 3, 4, 5, 6, 7, 8] && - ((n.sharing.findIdx? (· == hot)).map fun i => decide (i < 8)) == some true)) +def nineRefTests : Spec := + describe "fixture nine independent Refs (677 → 579)" do + it "hot atom is Ref(2,[0,0,0])" do + let (_, hot) := nineRef + expect (hot == .ref 2 #[0, 0, 0]) + it "hash order: 677 bytes, hot atom in slot 8" do + let (c, hot) := nineRef + let atoms := (constantInfoRoots c.info).foldl + (fun acc a => if acc.contains a then acc else acc.push a) #[] + let tableWith (table : Array Ixon.Expr) : Constant := + let idxOf (a : Ixon.Expr) : Nat := (table.findIdx? (· == a)).getD 0 + let roots := (constantInfoRoots c.info).map fun a => Ixon.Expr.share (idxOf a).toUInt64 + match withRoots c.info roots with + | .ok info => { c with info, sharing := table } + | .error _ => c + let hashOrder := tableWith atoms + expect (cbytes hashOrder == 677 && atoms.size == 9 && atoms[8]? == some hot) + it "same entries, frequency order: 579 bytes" do + let (c, hot) := nineRef + let atoms := (constantInfoRoots c.info).foldl + (fun acc a => if acc.contains a then acc else acc.push a) #[] + let tableWith (table : Array Ixon.Expr) : Constant := + let idxOf (a : Ixon.Expr) : Nat := (table.findIdx? (· == a)).getD 0 + let roots := (constantInfoRoots c.info).map fun a => Ixon.Expr.share (idxOf a).toUInt64 + match withRoots c.info roots with + | .ok info => { c with info, sharing := table } + | .error _ => c + let freqTable := #[hot] ++ (atoms.filter (· != hot)) + expect (cbytes (tableWith freqTable) == 579) + it "exact: 579 bytes, table IDs [0..8], hot atom at a width-1 slot" do + let (c, hot) := nineRef + withOk "exact" (optimizeSharingTable #[] (constantInfoRoots c.info)) fun r => + withOk "exact" (normalizeConstantSharing c) fun n => + expect (cbytes n == 579 && r.tableTerms == #[0, 1, 2, 3, 4, 5, 6, 7, 8] && + ((n.sharing.findIdx? (· == hot)).map fun i => decide (i < 8)) == some true) /-- Fast PR check for the tied-minima fixture: exact solver picks `[A]`. -/ -def tiedMinimaExactTests (_ : Unit) : TestSeq := - let c := axiomOf tiedMinimaRoot #[.zero, .succ .zero] - let onlyA := "d2000094b0b0910001000101910000" ++ "000200010000" - group "fixture three 21-byte minima (exact)" <| - withOk "exact" (optimizeSharingTable #[] (constantInfoRoots c.info)) (fun r => - withOk "exact" (normalizeConstantSharing c) fun n => - test "exact picks the [A] minimum (table IDs [2])" - (hexOf (serConstant n) == onlyA && r.tableTerms == #[2])) +def tiedMinimaExactTests : Spec := + describe "fixture three 21-byte minima (exact)" do + it "exact picks the [A] minimum (table IDs [2])" do + let c := axiomOf tiedMinimaRoot #[.zero, .succ .zero] + let onlyA := "d2000094b0b0910001000101910000" ++ "000200010000" + withOk "exact" (optimizeSharingTable #[] (constantInfoRoots c.info)) fun r => + withOk "exact" (normalizeConstantSharing c) fun n => + expect (hexOf (serConstant n) == onlyA && r.tableTerms == #[2]) /-- Full 13,700-table exhaustive oracle check for the tied-minima fixture (nightly sweep). -/ -def tiedMinimaTests (_ : Unit) : TestSeq := - let c := axiomOf tiedMinimaRoot #[.zero, .succ .zero] - -- Table [A]: the root is one telescope with binders `Share 0`, `Share 0`, `B`, `P` - -- over `Type`; tables [A,B] and [B,A]: the root is cut at `B`, all `Share`s. - let onlyA := "d2000094b0b0910001000101910000" ++ "000200010000" - let first := "d2000093b0b0b1b10291000091000100020001" ++ "0000" - let second := "d2000093b1b1b0b00291000191000000020001" ++ "0000" - group "fixture three 21-byte minima" <| - withOk "oracle" (oracleConstant c) (fun (oc, o) => - test s!"oracle: minimum 21 over {o.work.tables} ordered tables; [A], [A,B] and [B,A] attain it; the least table [A] wins" - (cbytes oc == 21 && o.work.tables == 13700 && o.minima.size == 3 && +def tiedMinimaTests : Spec := + describe "fixture three 21-byte minima" do + it "oracle: minimum 21 over 13700 ordered tables; [A], [A,B] and [B,A] attain it; the least table [A] wins" do + let c := axiomOf tiedMinimaRoot #[.zero, .succ .zero] + -- Table [A]: the root is one telescope with binders `Share 0`, `Share 0`, `B`, `P` + -- over `Type`; tables [A,B] and [B,A]: the root is cut at `B`, all `Share`s. + let onlyA := "d2000094b0b0910001000101910000" ++ "000200010000" + let first := "d2000093b0b0b1b10291000091000100020001" ++ "0000" + let second := "d2000093b1b1b0b00291000191000000020001" ++ "0000" + withOk "oracle" (oracleConstant c) fun (oc, o) => + expect (cbytes oc == 21 && o.work.tables == 13700 && o.minima.size == 3 && o.minima.any (hexOf · == first) && o.minima.any (hexOf · == second) && - hexOf (serConstant oc) == onlyA && o.table == #[2])) ++ - withOk "exact" (optimizeSharingTable #[] (constantInfoRoots c.info)) (fun r => - withOk "exact" (normalizeConstantSharing c) fun n => - test "exact picks the [A] minimum (table IDs [2])" - (hexOf (serConstant n) == onlyA && r.tableTerms == #[2])) + hexOf (serConstant oc) == onlyA && o.table == #[2]) + it "exact picks the [A] minimum (table IDs [2])" do + let c := axiomOf tiedMinimaRoot #[.zero, .succ .zero] + let onlyA := "d2000094b0b0910001000101910000" ++ "000200010000" + withOk "exact" (optimizeSharingTable #[] (constantInfoRoots c.info)) fun r => + withOk "exact" (normalizeConstantSharing c) fun n => + expect (hexOf (serConstant n) == onlyA && r.tableTerms == #[2]) /-- A parent stored before its separately stored descendant (which the parent's entry therefore inlines): seven hot atoms take slots 0–6, the 50-use parent `P = App(Var 0, D)` takes slot 7 and `D` (3 more uses) slot 8. -/ -def orderingTests (_ : Unit) : TestSeq := - let d : Ixon.Expr := .ref 1 #[0, 0, 0] - let p : Ixon.Expr := .app (.var 0) d - let hots := (Array.range 7).map fun i => Ixon.Expr.ref (i + 2).toUInt64 #[0, 0, 0] - let roots := hots.foldl (fun acc h => acc ++ Array.replicate 100 h) #[] ++ - Array.replicate 50 p ++ Array.replicate 3 d - group "ordering: parent before descendant" <| - withOk "exact" (optimizeSharing roots) fun r => - test s!"variable bytes {r.variableBytes} = 804, table IDs {r.tableTerms} = [2..8, 9 (P), 1 (D)], P's entry inlines D" - (r.variableBytes == 804 && r.tableTerms == #[2, 3, 4, 5, 6, 7, 8, 9, 1] && +def orderingTests : Spec := + describe "ordering: parent before descendant" do + it "variable bytes = 804, table IDs = [2..8, 9 (P), 1 (D)], P's entry inlines D" do + let d : Ixon.Expr := .ref 1 #[0, 0, 0] + let p : Ixon.Expr := .app (.var 0) d + let hots := (Array.range 7).map fun i => Ixon.Expr.ref (i + 2).toUInt64 #[0, 0, 0] + let roots := hots.foldl (fun acc h => acc ++ Array.replicate 100 h) #[] ++ + Array.replicate 50 p ++ Array.replicate 3 d + withOk "exact" (optimizeSharing roots) fun r => + expect (r.variableBytes == 804 && r.tableTerms == #[2, 3, 4, 5, 6, 7, 8, 9, 1] && r.sharing[7]? == some p) /-! ## Properties on generated inputs -/ -def propertyTestsWith (target : Nat) (_ : Unit) : TestSeq := - let (checked, err) := runGen 41 do - let mut checked := 0 - let mut err : Option String := none - for i in [0:target] do - if err.isSome then break - let roots ← genRoots 5 12 4 - let c := wrapRoots roots i - let alt := alternateOf c - match normalizeConstantSharing c, optimizeSharingTable #[] (constantInfoRoots c.info) with - | .ok n, .ok r => - checked := checked + 1 - let idem := (normalizeConstantSharing n).toOption.map serConstant == some (serConstant n) - let fromAlt := (normalizeConstantSharing alt).toOption.map serConstant == some (serConstant n) - let fromExpanded := ((expandConstantSharing n).toOption.bind - fun e => (normalizeConstantSharing e).toOption).map serConstant == some (serConstant n) - let minimum := match checkExactMinimum n with - | .ok .minimum => true - | _ => false - let altCheck := match checkExactMinimum alt with - | .ok .minimum => serConstant alt == serConstant n - | .ok (.notMinimum exp) => exp == serConstant n - | .error _ => false - let f := fixedConstantBytes c - let fixedOk := cbytes n == f + r.variableBytes && cbytes c == f + r.unsharedBytes - let expandsBack := (expandConstantSharing n).toOption.map (fun e => constantInfoRoots e.info) == - some (constantInfoRoots c.info) - unless cbytes n ≤ cbytes c && cbytes n ≤ cbytes alt && idem && fromAlt && - fromExpanded && minimum && altCheck && fixedOk && expandsBack do - err := some s!"case {i}: exact={cbytes n} unshared={cbytes c} uniform-w1={cbytes alt} idem={idem} fromAlt={fromAlt} fromExpanded={fromExpanded} minimum={minimum} altCheck={altCheck} fixed={fixedOk} expands={expandsBack} roots={reprStr roots}" - | .error e, _ | _, .error e => err := some s!"case {i}: error {reprStr e}" - return (checked, err) - group "properties on generated inputs" <| - test s!"{checked} constants: exact ≤ unshared, exact ≤ uniform-w1, idempotent, normalize(uniform-w1) = normalize(expanded) = exact, check=minimum, decomposition, expansion preserved" (err.isNone && checked == target) ++ - (match err with | some m => test m false | none => .done) - -def propertyTests (_ : Unit) : TestSeq := propertyTestsWith 250 () -def propertyTestsPR (_ : Unit) : TestSeq := propertyTestsWith 60 () +def propertyTestsWith (target : Nat) : Spec := + describe "properties on generated inputs" do + it s!"{target} constants: exact ≤ unshared, exact ≤ uniform-w1, idempotent, normalize(uniform-w1) = normalize(expanded) = exact, check=minimum, decomposition, expansion preserved" do + let (checked, err) := runGen 41 do + let mut checked := 0 + let mut err : Option String := none + for i in [0:target] do + if err.isSome then break + let roots ← genRoots 5 12 4 + let c := wrapRoots roots i + let alt := alternateOf c + match normalizeConstantSharing c, optimizeSharingTable #[] (constantInfoRoots c.info) with + | .ok n, .ok r => + checked := checked + 1 + let idem := (normalizeConstantSharing n).toOption.map serConstant == some (serConstant n) + let fromAlt := (normalizeConstantSharing alt).toOption.map serConstant == some (serConstant n) + let fromExpanded := ((expandConstantSharing n).toOption.bind + fun e => (normalizeConstantSharing e).toOption).map serConstant == some (serConstant n) + let minimum := match checkExactMinimum n with + | .ok .minimum => true + | _ => false + let altCheck := match checkExactMinimum alt with + | .ok .minimum => serConstant alt == serConstant n + | .ok (.notMinimum exp) => exp == serConstant n + | .error _ => false + let f := fixedConstantBytes c + let fixedOk := cbytes n == f + r.variableBytes && cbytes c == f + r.unsharedBytes + let expandsBack := (expandConstantSharing n).toOption.map (fun e => constantInfoRoots e.info) == + some (constantInfoRoots c.info) + unless cbytes n ≤ cbytes c && cbytes n ≤ cbytes alt && idem && fromAlt && + fromExpanded && minimum && altCheck && fixedOk && expandsBack do + err := some s!"case {i}: exact={cbytes n} unshared={cbytes c} uniform-w1={cbytes alt} idem={idem} fromAlt={fromAlt} fromExpanded={fromExpanded} minimum={minimum} altCheck={altCheck} fixed={fixedOk} expands={expandsBack} roots={reprStr roots}" + | .error e, _ | _, .error e => err := some s!"case {i}: error {reprStr e}" + return (checked, err) + if let some m := err then fail m + expect (checked == target) s!"checked {checked} != {target}" + +def propertyTests : Spec := propertyTestsWith 250 +def propertyTestsPR : Spec := propertyTestsWith 60 /-- LB pruning never changes a result: compare with the search with pruning disabled, on inputs with 9–11 candidates (beyond the oracle's reach; tables can cross the 8-slot width boundary). -/ -def pruningTestsWith (genTarget wideTarget : Nat) (_ : Unit) : TestSeq := - let (checked, wide, err) := runGen 43 do - let mut checked := 0 - let mut wide := 0 - let mut err : Option String := none - for i in [0:4000] do - if checked ≥ genTarget || err.isSome then break - let roots ← genRoots 8 24 6 - let cands := match sharingProfile (wrapRoots roots 0) with - | .ok p => p.candidates - | .error _ => 0 - if cands < 9 || cands > 11 then continue - match optimizeSharing roots, - optimizeSharing roots { prune := false } with - | .ok a, .ok b => - checked := checked + 1 - if a.sharing.size > 8 then wide := wide + 1 - unless a.sharing == b.sharing && a.roots == b.roots && - a.tableTerms == b.tableTerms && a.variableBytes == b.variableBytes do - err := some s!"case {i}: pruned={a.variableBytes} {a.tableTerms} unpruned={b.variableBytes} {b.tableTerms}" - | .error e, _ | _, .error e => err := some s!"case {i}: error {reprStr e}" - return (checked, wide, err) - -- Many profitable atoms plus nested nodes over them: optimal tables - -- usually exceed 8 entries, so widths 1 and 2 compete. - let genWide : RGen (Array Ixon.Expr) := do - let n := 9 + (← rand 3) - let atoms : Array Ixon.Expr := (Array.range n).map fun j => - .ref (j + 2).toUInt64 (Array.replicate (1 + j % 3) 0) - let mut roots : Array Ixon.Expr := #[] - for j in [0:n] do - for _ in [0:2 + (← rand 4)] do roots := roots.push atoms[j]! - for _ in [0:(← rand 3)] do - let a := atoms[← rand n]! - let b := atoms[← rand n]! - let node : Ixon.Expr := if (← rand 2) == 0 then .app a b else arr a b - for _ in [0:2 + (← rand 2)] do roots := roots.push node - return roots - let (wChecked, wWide, wErr) := runGen 47 do - let mut checked := 0 - let mut wide := 0 - let mut err : Option String := none - for i in [0:400] do - if checked ≥ wideTarget || err.isSome then break - let roots ← genWide - let cands := match sharingProfile (wrapRoots roots 0) with - | .ok p => p.candidates - | .error _ => 0 - if cands > 12 then continue - match optimizeSharing roots, - optimizeSharing roots { prune := false } with - | .ok a, .ok b => - checked := checked + 1 - if a.sharing.size > 8 then wide := wide + 1 - unless a.sharing == b.sharing && a.roots == b.roots && - a.tableTerms == b.tableTerms && a.variableBytes == b.variableBytes do - err := some s!"wide case {i}: pruned={a.variableBytes} {a.tableTerms} unpruned={b.variableBytes} {b.tableTerms}" - | .error e, _ | _, .error e => err := some s!"wide case {i}: error {reprStr e}" - return (checked, wide, err) - group "pruning never changes the result" <| - test s!"{checked} inputs with 9–11 candidates ({wide} with more than 8 table entries): pruned search = unpruned search" - (err.isNone && checked == genTarget) ++ - (match err with | some m => test m false | none => .done) ++ - test s!"{wChecked} atom-heavy inputs with ≤ 12 candidates ({wWide} with more than 8 table entries): pruned = unpruned" - (wErr.isNone && wChecked == wideTarget && wWide > 0) ++ - (match wErr with | some m => test m false | none => .done) - -def pruningTests (_ : Unit) : TestSeq := pruningTestsWith 25 15 () -def pruningTestsPR (_ : Unit) : TestSeq := pruningTestsWith 5 5 () - -def profileTests (_ : Unit) : TestSeq := - group "sharing profile" <| - withOk "T2 → T2" (sharingProfile witness2) (fun p => - test "T2→T2: N=4, 3 repeated, 2 candidates (T1,T2), height 3, unshared 9 variable bytes" - (p.distinctSubterms == 4 && p.repeated == 3 && p.candidates == 2 && p.height == 3 && - p.unsharedBytes == 9 && p.inputBytes == 9)) ++ - withOk "T16 → T16" (sharingProfile witness16) (fun p => - test "T16→T16: N=18, 16 candidates, unshared 39 variable bytes" - (p.distinctSubterms == 18 && p.candidates == 16 && p.unsharedBytes == 39)) +def pruningTestsWith (genTarget wideTarget : Nat) : Spec := + describe "pruning never changes the result" do + it s!"{genTarget} inputs with 9–11 candidates: pruned search = unpruned search" do + let (checked, _, err) := runGen 43 do + let mut checked := 0 + let mut wide := 0 + let mut err : Option String := none + for i in [0:4000] do + if checked ≥ genTarget || err.isSome then break + let roots ← genRoots 8 24 6 + let cands := match sharingProfile (wrapRoots roots 0) with + | .ok p => p.candidates + | .error _ => 0 + if cands < 9 || cands > 11 then continue + match optimizeSharing roots, + optimizeSharing roots { prune := false } with + | .ok a, .ok b => + checked := checked + 1 + if a.sharing.size > 8 then wide := wide + 1 + unless a.sharing == b.sharing && a.roots == b.roots && + a.tableTerms == b.tableTerms && a.variableBytes == b.variableBytes do + err := some s!"case {i}: pruned={a.variableBytes} {a.tableTerms} unpruned={b.variableBytes} {b.tableTerms}" + | .error e, _ | _, .error e => err := some s!"case {i}: error {reprStr e}" + return (checked, wide, err) + if let some m := err then fail m + expect (checked == genTarget) s!"checked {checked} != {genTarget}" + it s!"{wideTarget} atom-heavy inputs with ≤ 12 candidates: pruned = unpruned" do + -- Many profitable atoms plus nested nodes over them: optimal tables + -- usually exceed 8 entries, so widths 1 and 2 compete. + let genWide : RGen (Array Ixon.Expr) := do + let n := 9 + (← rand 3) + let atoms : Array Ixon.Expr := (Array.range n).map fun j => + .ref (j + 2).toUInt64 (Array.replicate (1 + j % 3) 0) + let mut roots : Array Ixon.Expr := #[] + for j in [0:n] do + for _ in [0:2 + (← rand 4)] do roots := roots.push atoms[j]! + for _ in [0:(← rand 3)] do + let a := atoms[← rand n]! + let b := atoms[← rand n]! + let node : Ixon.Expr := if (← rand 2) == 0 then .app a b else arr a b + for _ in [0:2 + (← rand 2)] do roots := roots.push node + return roots + let (wChecked, wWide, wErr) := runGen 47 do + let mut checked := 0 + let mut wide := 0 + let mut err : Option String := none + for i in [0:400] do + if checked ≥ wideTarget || err.isSome then break + let roots ← genWide + let cands := match sharingProfile (wrapRoots roots 0) with + | .ok p => p.candidates + | .error _ => 0 + if cands > 12 then continue + match optimizeSharing roots, + optimizeSharing roots { prune := false } with + | .ok a, .ok b => + checked := checked + 1 + if a.sharing.size > 8 then wide := wide + 1 + unless a.sharing == b.sharing && a.roots == b.roots && + a.tableTerms == b.tableTerms && a.variableBytes == b.variableBytes do + err := some s!"wide case {i}: pruned={a.variableBytes} {a.tableTerms} unpruned={b.variableBytes} {b.tableTerms}" + | .error e, _ | _, .error e => err := some s!"wide case {i}: error {reprStr e}" + return (checked, wide, err) + if let some m := wErr then fail m + expect (wChecked == wideTarget && decide (wWide > 0)) s!"wChecked={wChecked}, wWide={wWide}" + +def pruningTests : Spec := pruningTestsWith 25 15 +def pruningTestsPR : Spec := pruningTestsWith 5 5 + +def profileTests : Spec := + describe "sharing profile" do + it "T2→T2: N=4, 3 repeated, 2 candidates (T1,T2), height 3, unshared 9 variable bytes" do + withOk "T2 → T2" (sharingProfile witness2) fun p => + expect (p.distinctSubterms == 4 && p.repeated == 3 && p.candidates == 2 && p.height == 3 && + p.unsharedBytes == 9 && p.inputBytes == 9) + it "T16→T16: N=18, 16 candidates, unshared 39 variable bytes" do + withOk "T16 → T16" (sharingProfile witness16) fun p => + expect (p.distinctSubterms == 18 && p.candidates == 16 && p.unsharedBytes == 39) /-! ## Safety, limits, empty input -/ @@ -1125,53 +1169,41 @@ def staleProjection : Constant := let info : ConstantInfo := .iPrj ⟨0, testRefs[0]!⟩ { info, sharing := #[arr P P, .share 0], refs := testRefs, univs := #[] } -def safetyTests (_ : Unit) : TestSeq := - let roots := constantInfoRoots witness16.info - group "resource limits and edge cases" <| - test "state limit → resourceExhausted, no result" - (isErr (optimizeSharing roots { maxStates := 5 }) (exhausted .states)) ++ - test "transition limit → resourceExhausted" - (isErr (optimizeSharing roots { maxTransitions := 5 }) (exhausted .transitions)) ++ - test "cost-evaluation limit → resourceExhausted" - (isErr (optimizeSharing roots { maxCostEvals := 50 }) (exhausted .costEvals)) ++ - test "output-byte limit → resourceExhausted" - (isErr (optimizeSharing roots { maxOutputBytes := 10 }) (exhausted .outputBytes)) ++ - test "materialization limit → resourceExhausted" - (isErr (optimizeSharing roots { maxMaterialize := 3 }) (exhausted .materialize)) ++ - test "oracle table limit → resourceExhausted" - (isErr (oracleConstant witness2 { maxOracleTables := 10 }) (exhausted .oracleTables)) ++ - test "oracle variant limit → resourceExhausted" - (isErr (oracleConstant witness2 { maxOracleVariants := 100 }) (exhausted .oracleVariants)) ++ - test "larger limits do not change a successful result" - ((optimizeSharing roots { maxStates := 1 <<< 30, maxCostEvals := 1 <<< 40 }).toOption.map (·.sharing) == - (optimizeSharing roots).toOption.map (·.sharing)) ++ - withOk "empty input" (optimizeSharing #[]) (fun r => - test "no roots: empty table, 1 variable byte (the table count)" - (r.sharing.isEmpty && r.roots.isEmpty && r.variableBytes == 1)) ++ - withOk "projection with a stale table" - (normalizeConstantSharing staleProjection) (fun n => - test "a constant without roots drops its (unreachable) table" n.sharing.isEmpty) ++ - test "repeated identical roots can be shared as whole roots" +def safetyTests : Spec := + describe "resource limits and edge cases" do + itBool "state limit → resourceExhausted, no result" + (isErr (optimizeSharing (constantInfoRoots witness16.info) { maxStates := 5 }) (exhausted .states)) + itBool "transition limit → resourceExhausted" + (isErr (optimizeSharing (constantInfoRoots witness16.info) { maxTransitions := 5 }) (exhausted .transitions)) + itBool "cost-evaluation limit → resourceExhausted" + (isErr (optimizeSharing (constantInfoRoots witness16.info) { maxCostEvals := 50 }) (exhausted .costEvals)) + itBool "output-byte limit → resourceExhausted" + (isErr (optimizeSharing (constantInfoRoots witness16.info) { maxOutputBytes := 10 }) (exhausted .outputBytes)) + itBool "materialization limit → resourceExhausted" + (isErr (optimizeSharing (constantInfoRoots witness16.info) { maxMaterialize := 3 }) (exhausted .materialize)) + itBool "oracle table limit → resourceExhausted" + (isErr (oracleConstant witness2 { maxOracleTables := 10 }) (exhausted .oracleTables)) + itBool "oracle variant limit → resourceExhausted" + (isErr (oracleConstant witness2 { maxOracleVariants := 100 }) (exhausted .oracleVariants)) + itBool "larger limits do not change a successful result" + (let roots := constantInfoRoots witness16.info + (optimizeSharing roots { maxStates := 1 <<< 30, maxCostEvals := 1 <<< 40 }).toOption.map (·.sharing) == + (optimizeSharing roots).toOption.map (·.sharing)) + it "no roots: empty table, 1 variable byte (the table count)" do + withOk "empty input" (optimizeSharing #[]) fun r => + expect (r.sharing.isEmpty && r.roots.isEmpty && r.variableBytes == 1) + it "a constant without roots drops its (unreachable) table" do + withOk "projection with a stale table" (normalizeConstantSharing staleProjection) fun n => + expect n.sharing.isEmpty + itBool "repeated identical roots can be shared as whole roots" ((optimizeSharing #[chain 5, chain 5, chain 5]).toOption.map (·.sharing.size) == some 1) -/-! ## Randomized codec properties (SlimCheck) -/ - -def slimTests (_ : Unit) : TestSeq := - checkIO "exprSize = serExpr size (SlimCheck)" (∀ e : Ixon.Expr, exprSize e == (serExpr e).size) ++ - checkIO "Constant length decomposition (SlimCheck)" (∀ c : Constant, decompositionHolds c) - -/-! ## Suite -/ +/-! ## Randomized codec properties -/ -/-- Build and run a test group only when the suite executes (never at module -initialization), printing its report and wall time. -/ -def deferred (descr : String) (mk : Unit → TestSeq) : TestSeq := - .individualIO descr none (do - let start ← IO.monoMsNow - let (ok, out) ← (mk ()).runIO 4 - let stop ← IO.monoMsNow - IO.print out - IO.println s!" [{descr}: {stop - start} ms]" - return (ok, 0, 0, if ok then none else some s!"a check in '{descr}' failed; see above")) .done +def slimTests : Spec := + describe "randomized codec properties" do + prop "exprSize = serExpr size" fun (e : Ixon.Expr) => exprSize e == (serExpr e).size + prop "Constant length decomposition" fun (c : Constant) => decompositionHolds c /-! ## Limits: defaults and overrides -/ @@ -1229,76 +1261,79 @@ def limitSpecMismatches : List String := | .error _ => none if got == want then none else some spec -def limitTests (_ : Unit) : TestSeq := - let d : Limits := {} - let resources : List Resource := [.exprVisits, .depth, .nodes, .states, .transitions, - .costEvals, .outputBytes, .materialize, .materializeWork, .knapsackCells] - group "limits" <| - test "the defaults are the safety net" - (d.maxExprVisits == 2 ^ 40 && d.maxDepth == 2 ^ 20 && d.maxNodes == 2 ^ 32 && - d.maxStates == 2 ^ 40 && d.maxTransitions == 2 ^ 40 && d.maxCostEvals == 2 ^ 50 && - d.maxOutputBytes == 2 ^ 40 && d.maxMaterialize == 2 ^ 40 && - d.maxMaterializeWork == 2 ^ 56 && d.maxKnapsackCells == 2 ^ 28) ++ - test "overrides set the named limits, left to right" - (match d.withOverrides " states = 2^10 ,cost_evals=12345, output_bytes=max,, states=2^11" with +def limitTests : Spec := + describe "limits" do + itBool "the defaults are the safety net" + (let d : Limits := {} + d.maxExprVisits == 2 ^ 40 && d.maxDepth == 2 ^ 20 && d.maxNodes == 2 ^ 32 && + d.maxStates == 2 ^ 40 && d.maxTransitions == 2 ^ 40 && d.maxCostEvals == 2 ^ 50 && + d.maxOutputBytes == 2 ^ 40 && d.maxMaterialize == 2 ^ 40 && + d.maxMaterializeWork == 2 ^ 56 && d.maxKnapsackCells == 2 ^ 28) + itBool "overrides set the named limits, left to right" + (let d : Limits := {} + match d.withOverrides " states = 2^10 ,cost_evals=12345, output_bytes=max,, states=2^11" with | .ok l => l.maxStates == 2048 && l.maxCostEvals == 12345 && l.maxOutputBytes == limitMax && l.maxDepth == d.maxDepth - | .error _ => false : Bool) ++ - test "the retired Rust port's keys are unknown keys" - (["height=5", "work=2^3", "layer_states=9", "input_nodes=1", "distinct_nodes=1", - "candidates=1"].all fun s => overrideFails (d.withOverrides s)) ++ - test "unbounded sets every production limit to max; a later item still applies" - (match d.withOverrides "unbounded,states=2" with + | .error _ => false) + itBool "the retired Rust port's keys are unknown keys" + (let d : Limits := {} + ["height=5", "work=2^3", "layer_states=9", "input_nodes=1", "distinct_nodes=1", + "candidates=1"].all fun s => overrideFails (d.withOverrides s)) + itBool "unbounded sets every production limit to max; a later item still applies" + (let d : Limits := {} + match d.withOverrides "unbounded,states=2" with | .ok l => l.maxDepth == limitMax && l.maxMaterializeWork == limitMax && l.maxStates == 2 && l.maxOracleTables == d.maxOracleTables - | .error _ => false : Bool) ++ - test "malformed overrides are errors" - (["bogus=1", "states", "states=2^64", "states=-1", "states=1e3", "=3", - "states=18446744073709551616"].all fun s => overrideFails (d.withOverrides s)) ++ - test s!"the {limitSpecParity.length} grammar specs get the listed verdict" - (limitSpecParity.length == 35 && limitSpecMismatches.isEmpty) ++ - test "every production resource key names a limit" - (resources.all fun r => (d.set? r.key 3).isSome) - -public def suite : List TestSeq := [ - deferred "integer widths" widthTests, - deferred "limits" limitTests, - deferred "exact expression length" exprSizeTests, - deferred "Constant length decomposition" decompositionTests, - deferred "structural IDs" structuralIdTests, - deferred "representation independence" representationTestsPR, - deferred "checked expression cache" cacheTests, - deferred "bounded share expansion" expansionTests, - deferred "root extraction and reassembly" rootApiTests, - deferred "fixed-dictionary optimizer vs enumeration" dictionaryTestsPR, - deferred "telescope evaluation vs full spine walk" spineWalkTests, - deferred "deep inputs" deepTests, - deferred "optimizer vs exhaustive oracle" oracleTestsPR, - deferred "unit-width relaxation oracle" unitWidthTestsPR, - deferred "multi-width buckets vs brute force" atomsTests, - deferred "fixture T2 → T2" witnessTests, - deferred "fixture T16 → T16" t16Tests, - deferred "fixture nine Refs" nineRefTests, - deferred "fixture three 21-byte minima (exact)" tiedMinimaExactTests, - deferred "ordering: parent before descendant" orderingTests, - deferred "properties on generated inputs" propertyTestsPR, - deferred "pruning never changes the result" pruningTestsPR, - deferred "sharing profile" profileTests, - deferred "resource limits and edge cases" safetyTests, - slimTests (), -] + | .error _ => false) + itBool "malformed overrides are errors" + (let d : Limits := {} + ["bogus=1", "states", "states=2^64", "states=-1", "states=1e3", "=3", + "states=18446744073709551616"].all fun s => overrideFails (d.withOverrides s)) + itBool s!"the {limitSpecParity.length} grammar specs get the listed verdict" + (limitSpecParity.length == 35 && limitSpecMismatches.isEmpty) + itBool "every production resource key names a limit" + (let d : Limits := {} + let resources : List Resource := [.exprVisits, .depth, .nodes, .states, .transitions, + .costEvals, .outputBytes, .materialize, .materializeWork, .knapsackCells] + resources.all fun r => (d.set? r.key 3).isSome) + +public def suite : Spec := do + widthTests + limitTests + exprSizeTests + decompositionTests + structuralIdTests + representationTestsPR + cacheTests + expansionTests + rootApiTests + dictionaryTestsPR + spineWalkTests + deepTests + oracleTestsPR + unitWidthTestsPR + atomsTests + witnessTests + t16Tests + nineRefTests + tiedMinimaExactTests + orderingTests + propertyTestsPR + pruningTestsPR + profileTests + safetyTests + slimTests /-- Full exhaustive oracle and large-sweep checks for nightly CI (`exact-sharing-full`). -/ -public def nightlySuite : List TestSeq := [ - deferred "representation independence (full)" representationTests, - deferred "fixed-dictionary optimizer vs enumeration (full)" dictionaryTests, - deferred "optimizer vs exhaustive oracle (full)" oracleTests, - deferred "unit-width relaxation oracle (full)" unitWidthTests, - deferred "fixture T2 → T2 (full-product oracle)" witnessProductOracleTests, - deferred "fixture three 21-byte minima (exhaustive oracle)" tiedMinimaTests, - deferred "properties on generated inputs (full)" propertyTests, - deferred "pruning never changes the result (full)" pruningTests, -] +public def nightlySuite : Spec := do + representationTests + dictionaryTests + oracleTests + unitWidthTests + witnessProductOracleTests + tiedMinimaTests + propertyTests + pruningTests end Tests.SharingExact diff --git a/Tests/Ix/SharingTiered.lean b/Tests/Ix/SharingTiered.lean index 1e7c54d81d..19870c9a81 100644 --- a/Tests/Ix/SharingTiered.lean +++ b/Tests/Ix/SharingTiered.lean @@ -57,25 +57,25 @@ def sameAsCandidates (l : ShareLayout) (c : Constant) : Bool := | .ok r => candidatesOk l c r | .error _ => false -def fixtureTests (_ : Unit) : TestSeq := - let (nine, hot) := nineRef - let w2 := witness2 - let w16 := axiomOf (arr (chain 16) (chain 16)) +def fixtureTests : Spec := let l := ShareLayout.tagN - group "fixtures, TagN layout" ( - withOk "T2" (normalizeConstantSharingTiered l w2) (fun n => - test s!"T2 → T2: {cbytes n} bytes = 15, d2000091b0b0019200000000010000" - (cbytes n == 15 && hexOf (serConstant n) == "d2000091b0b0019200000000010000" && - sameAsCandidates l w2)) ++ - withOk "T16" (normalizeConstantSharingTiered l w16) (fun n => - test s!"T16 → T16: {cbytes n} bytes = 30, the candidates run alone agree" - (cbytes n == 30 && sameAsCandidates l w16)) ++ - withOk "nine" (canonicalSharingTieredTable l #[] (constantInfoRoots nine.info)) (fun r => - withOk "nine" (normalizeConstantSharingTiered l nine) fun n => - test s!"nine Refs: {cbytes n} bytes = 579, the candidates run alone agree; w={r.stats.w} (candidates {r.stats.candidateLengths}); first tier {r.stats.firstTier} holds the hot atom; phase-1 layout {r.stats.phase1LayoutBytes}, final {r.stats.phase3LayoutBytes}" - (cbytes n == 579 && selectionOk r && sameAsCandidates l nine && + describe "fixtures, TagN layout" do + it "T2 → T2: 15 bytes, d2000091b0b0019200000000010000" do + let w2 := witness2 + withOk "T2" (normalizeConstantSharingTiered l w2) fun n => + expect (cbytes n == 15 && hexOf (serConstant n) == "d2000091b0b0019200000000010000" && + sameAsCandidates l w2) + it "T16 → T16: 30 bytes, the candidates run alone agree" do + let w16 := axiomOf (arr (chain 16) (chain 16)) + withOk "T16" (normalizeConstantSharingTiered l w16) fun n => + expect (cbytes n == 30 && sameAsCandidates l w16) + it "nine Refs: 579 bytes, the candidates run alone agree, first tier holds the hot atom" do + let (nine, hot) := nineRef + withOk "nine" (canonicalSharingTieredTable l #[] (constantInfoRoots nine.info)) fun r => + withOk "nine" (normalizeConstantSharingTiered l nine) fun n => + expect (cbytes n == 579 && selectionOk r && sameAsCandidates l nine && r.stats.firstTier.contains 2 && - (n.sharing.findIdx? (· == hot)).map (fun i => decide (i < 8)) == some true))) + (n.sharing.findIdx? (· == hot)).map (fun i => decide (i < 8)) == some true) /-- A heavy parent `P` over two lighter children, next to more than eight ready atoms used three times each. The pinned order fills the first tier @@ -95,43 +95,44 @@ def genHeavyParent : RGen (Array Ixon.Expr) := do roots := roots.push c2 return roots -def allocationTests (_ : Unit) : TestSeq := - let (checked, changed, saved, beatOther, err) := runGen 71 do - let mut checked := 0 - let mut changed := 0 - let mut saved := 0 - let mut beatOther := 0 - let mut err : Option String := none - for i in [0:120] do - if err.isSome then break - let roots ← if i % 2 == 0 then genHeavyParent else genRoots 6 16 5 - let c := wrapRoots roots i - let l := ShareLayout.tagN - match canonicalSharingTieredTable l #[] (constantInfoRoots c.info), - normalizeConstantSharingTiered l c with - | .ok r, .ok n => - checked := checked + 1 - if r.stats.finalRefCost < r.stats.phase1RefCost then changed := changed + 1 - if r.stats.savings > 0 then saved := saved + 1 - let fixedOk := cbytes n == fixedConstantBytes c + r.result.variableBytes - let idem := (normalizeConstantSharingTiered l n).toOption.map serConstant == - some (serConstant n) - -- every candidate run alone has its recorded length, and the result - -- is the candidate at its winning width - let candOk := candidatesOk l c r - if r.stats.candidateLengths.any (·.2 > r.stats.phase3LayoutBytes) then - beatOther := beatOther + 1 - unless r.stats.phase3LayoutBytes ≤ r.stats.phase1LayoutBytes && - r.stats.finalRefCost ≤ r.stats.phase1RefCost && fixedOk && idem && - selectionOk r && candOk && - r.result.modelBytes == r.result.variableBytes do - err := some s!"case {i} {reprStr l}: phase1={r.stats.phase1LayoutBytes} final={r.stats.phase3LayoutBytes} refcost {r.stats.phase1RefCost}->{r.stats.finalRefCost} fixed={fixedOk} idem={idem} selection={selectionOk r} {r.stats.candidateLengths} candidates={candOk}" - | .error e, _ | _, .error e => err := some s!"case {i} {reprStr l}: error {reprStr e}" - return (checked, changed, saved, beatOther, err) - group "slot allocation and re-materialization" <| - test s!"{checked} runs (120 inputs, TagN layout): final ≤ phase 1 in layout bytes and in reference cost; serialized = fixed + variable; wire price = serialized; idempotent; the fewest bytes over w = 1, 2, 3 (lower w at a tie), each candidate as when run alone ({changed} runs where allocation lowered the reference cost, {saved} with positive savings, {beatOther} where another width was longer)" - (err.isNone && checked == 120 && changed > 0) ++ - (match err with | some m => test m false | none => .done) +def allocationTests : Spec := + describe "slot allocation and re-materialization" do + it "120 runs (TagN layout): final ≤ phase 1 in layout bytes and reference cost; serialized = fixed + variable; idempotent; fewest bytes over w = 1, 2, 3" do + let (checked, changed, saved, beatOther, err) := runGen 71 do + let mut checked := 0 + let mut changed := 0 + let mut saved := 0 + let mut beatOther := 0 + let mut err : Option String := none + for i in [0:120] do + if err.isSome then break + let roots ← if i % 2 == 0 then genHeavyParent else genRoots 6 16 5 + let c := wrapRoots roots i + let l := ShareLayout.tagN + match canonicalSharingTieredTable l #[] (constantInfoRoots c.info), + normalizeConstantSharingTiered l c with + | .ok r, .ok n => + checked := checked + 1 + if r.stats.finalRefCost < r.stats.phase1RefCost then changed := changed + 1 + if r.stats.savings > 0 then saved := saved + 1 + let fixedOk := cbytes n == fixedConstantBytes c + r.result.variableBytes + let idem := (normalizeConstantSharingTiered l n).toOption.map serConstant == + some (serConstant n) + -- every candidate run alone has its recorded length, and the result + -- is the candidate at its winning width + let candOk := candidatesOk l c r + if r.stats.candidateLengths.any (·.2 > r.stats.phase3LayoutBytes) then + beatOther := beatOther + 1 + unless r.stats.phase3LayoutBytes ≤ r.stats.phase1LayoutBytes && + r.stats.finalRefCost ≤ r.stats.phase1RefCost && fixedOk && idem && + selectionOk r && candOk && + r.result.modelBytes == r.result.variableBytes do + err := some s!"case {i} {reprStr l}: phase1={r.stats.phase1LayoutBytes} final={r.stats.phase3LayoutBytes} refcost {r.stats.phase1RefCost}->{r.stats.finalRefCost} fixed={fixedOk} idem={idem} selection={selectionOk r} {r.stats.candidateLengths} candidates={candOk}" + | .error e, _ | _, .error e => err := some s!"case {i} {reprStr l}: error {reprStr e}" + return (checked, changed, saved, beatOther, err) + if let some m := err then fail m + expect (checked == 120 && decide (changed > 0)) + s!"checked={checked}, changed={changed}, saved={saved}, beatOther={beatOther}" /-- Brute force over all subsets: dependency-closed, at most `cap` terms, @@ -161,34 +162,34 @@ def bruteTier (n : Nat) (weight : Array Nat) (deps : Array (Array Nat)) (cap : N | some (_, vec) => (items.zipIdx.filter (fun (_, i) => vec[i]!)).map (·.1) |>.qsort (· < ·) | none => #[] -def tierBruteTests (_ : Unit) : TestSeq := - let (checked, err) := runGen 73 do - let mut checked := 0 - let mut err : Option String := none - for i in [0:300] do - if err.isSome then break - let n := 1 + (← rand 12) - let mut weight : Array Nat := #[] - let mut deps : Array (Array Nat) := #[] - for t in [0:n] do - weight := weight.push (1 + (← rand 4)) - let mut ds : Array Nat := #[] - for u in [0:t] do - if (← rand 4) == 0 then ds := ds.push u - deps := deps.push ds - let cap := min 8 (1 + (← rand n)) - match firstTier (Array.range n) (weight[·]!) (fun t => deps[t]!.toList) cap {} with - | .ok (s, _) => - checked := checked + 1 - let expected := bruteTier n weight deps cap - unless s == expected do - err := some s!"case {i}: n={n} cap={cap} weights={weight} deps={deps} search={s} brute={expected}" - | .error e => err := some s!"case {i}: error {reprStr e}" - return (checked, err) - group "first-tier allocation vs brute force" <| - test s!"{checked} random dependency DAGs (≤ 12 terms, cap ≤ 8, weights 1–4): branch and bound = enumeration, including ties" - (err.isNone && checked == 300) ++ - (match err with | some m => test m false | none => .done) +def tierBruteTests : Spec := + describe "first-tier allocation vs brute force" do + it "300 random dependency DAGs (≤ 12 terms, cap ≤ 8, weights 1–4): branch and bound = enumeration, including ties" do + let (checked, err) := runGen 73 do + let mut checked := 0 + let mut err : Option String := none + for i in [0:300] do + if err.isSome then break + let n := 1 + (← rand 12) + let mut weight : Array Nat := #[] + let mut deps : Array (Array Nat) := #[] + for t in [0:n] do + weight := weight.push (1 + (← rand 4)) + let mut ds : Array Nat := #[] + for u in [0:t] do + if (← rand 4) == 0 then ds := ds.push u + deps := deps.push ds + let cap := min 8 (1 + (← rand n)) + match firstTier (Array.range n) (weight[·]!) (fun t => deps[t]!.toList) cap {} with + | .ok (s, _) => + checked := checked + 1 + let expected := bruteTier n weight deps cap + unless s == expected do + err := some s!"case {i}: n={n} cap={cap} weights={weight} deps={deps} search={s} brute={expected}" + | .error e => err := some s!"case {i}: error {reprStr e}" + return (checked, err) + if let some m := err then fail m + expect (checked == 300) s!"checked {checked} != 300" /-- Reference Kahn priority order: repeatedly the remaining term whose dependencies in `rest` are all placed, of the largest weight, then the @@ -209,35 +210,35 @@ def kahnRef (weight : Nat → Nat) (deps : Nat → List Nat) (rest : Array Nat) remaining := remaining.erase t return out -def kahnTests (_ : Unit) : TestSeq := - let (checked, err) := runGen 91 do - let mut checked := 0 - let mut err : Option String := none - for i in [0:300] do - if err.isSome then break - let n := 1 + (← rand 30) - let mut weight : Array Nat := #[] - let mut deps : Array (List Nat) := #[] - let mut rest : Array Nat := #[] - for t in [0:n] do - weight := weight.push (1 + (← rand 5)) - let mut ds : List Nat := [] - for u in [0:t] do - if (← rand 5) == 0 then ds := u :: ds - -- occasional repeated references - if (← rand 4) == 0 then if let some d := ds.head? then ds := d :: ds - deps := deps.push ds - if (← rand 4) != 0 then rest := rest.push t - let got := kahnOrder (weight[·]!) (deps[·]!) rest - let want := kahnRef (weight[·]!) (deps[·]!) rest - checked := checked + 1 - unless got == want do - err := some s!"case {i}: weights={weight} deps={deps} rest={rest} kahn={got} reference={want}" - return (checked, err) - group "Kahn priority order" <| - test s!"{checked} random dependency DAGs (≤ 30 terms, weights 1–5, repeated references, dependencies outside the set): kahnOrder = the reference order" - (err.isNone && checked == 300) ++ - (match err with | some m => test m false | none => .done) +def kahnTests : Spec := + describe "Kahn priority order" do + it "300 random dependency DAGs (≤ 30 terms, weights 1–5, repeated references, dependencies outside the set): kahnOrder = the reference order" do + let (checked, err) := runGen 91 do + let mut checked := 0 + let mut err : Option String := none + for i in [0:300] do + if err.isSome then break + let n := 1 + (← rand 30) + let mut weight : Array Nat := #[] + let mut deps : Array (List Nat) := #[] + let mut rest : Array Nat := #[] + for t in [0:n] do + weight := weight.push (1 + (← rand 5)) + let mut ds : List Nat := [] + for u in [0:t] do + if (← rand 5) == 0 then ds := u :: ds + -- occasional repeated references + if (← rand 4) == 0 then if let some d := ds.head? then ds := d :: ds + deps := deps.push ds + if (← rand 4) != 0 then rest := rest.push t + let got := kahnOrder (weight[·]!) (deps[·]!) rest + let want := kahnRef (weight[·]!) (deps[·]!) rest + checked := checked + 1 + unless got == want do + err := some s!"case {i}: weights={weight} deps={deps} rest={rest} kahn={got} reference={want}" + return (checked, err) + if let some m := err then fail m + expect (checked == 300) s!"checked {checked} != 300" /-- An application spine of `1 + apps` nodes over `u = app(var 0, var 1)` (the spine's last term), next to hot references: 100 copies of the spine, 20 @@ -273,24 +274,27 @@ def candidatePaths (roots : Array Ixon.Expr) : let onePass := onePassOrder ex.dag order ex.roots (indexOfPrefix ex.dag.size order order.size) return (w, !onePass, sameMaterialization p order ex.roots ShareLayout.tagN.widthAt) -def fallbackTests (_ : Unit) : TestSeq := - withOk "spine witness" (candidatePaths (spineWitness 1287)) (fun paths => - withOk "spine witness" (canonicalSharingTieredTable .tagN #[] (spineWitness 1287)) fun r => - let perPrefix := (paths.filter (·.2.1)).size - test s!"spine of 1288 nodes: {perPrefix} candidate takes the per-prefix path (expected 1), candidates {r.stats.candidateLengths} (expected #[(1, 7106), (2, 7106), (3, 7123)]), every candidate equal to the specification" - (perPrefix == 1 && paths.all (·.2.2) && - r.stats.candidateLengths == #[(1, 7106), (2, 7106), (3, 7123)])) ++ - withOk "spine control" (candidatePaths (spineWitness 1286)) fun paths => - let perPrefix := (paths.filter (·.2.1)).size - test s!"spine of 1287 nodes: {perPrefix} candidates take the per-prefix path (expected 0), every candidate equal to the specification" - (perPrefix == 0 && paths.all (·.2.2)) - -def layoutTests (_ : Unit) : TestSeq := - test "TagN widths: 1 below 8, 2 below 1032, 3 below 66568, 4 below 16843784, 5 below 4311811080, then 9" - ([7, 8, 1031, 1032, 66567, 66568, 16843783, 16843784, 4311811079, 4311811080].map - ShareLayout.tagN.widthAt == [1, 2, 2, 3, 3, 4, 4, 5, 5, 9] && - tagNRung2End == 1032 && tagNRung3End == 66568 && tagNRung4End == 16843784 && - tagNRung5End == 4311811080) +def fallbackTests : Spec := + describe "phase-3 per-prefix fallback" do + it "spine of 1288 nodes: 1 candidate takes the per-prefix path, every candidate equal to the specification" do + withOk "spine witness" (candidatePaths (spineWitness 1287)) fun paths => + withOk "spine witness" (canonicalSharingTieredTable .tagN #[] (spineWitness 1287)) fun r => + let perPrefix := (paths.filter (·.2.1)).size + expect (perPrefix == 1 && paths.all (·.2.2) && + r.stats.candidateLengths == #[(1, 7106), (2, 7106), (3, 7123)]) + s!"perPrefix={perPrefix}, candidates={r.stats.candidateLengths}" + it "spine of 1287 nodes: 0 candidates take the per-prefix path, every candidate equal to the specification" do + withOk "spine control" (candidatePaths (spineWitness 1286)) fun paths => + let perPrefix := (paths.filter (·.2.1)).size + expect (perPrefix == 0 && paths.all (·.2.2)) s!"perPrefix={perPrefix}" + +def layoutTests : Spec := + describe "tiered layouts" do + itBool "TagN widths: 1 below 8, 2 below 1032, 3 below 66568, 4 below 16843784, 5 below 4311811080, then 9" + ([7, 8, 1031, 1032, 66567, 66568, 16843783, 16843784, 4311811079, 4311811080].map + ShareLayout.tagN.widthAt == [1, 2, 2, 3, 3, 4, 4, 5, 5, 9] && + tagNRung2End == 1032 && tagNRung3End == 66568 && tagNRung4End == 16843784 && + tagNRung5End == 4311811080) /-! ## The production construction at scale -/ @@ -339,31 +343,32 @@ def productionOk (c : Constant) (r : TieredSharingResult) (n : Constant) : Bool r.result.modelBytes == r.result.variableBytes && (normalizeConstantSharingTiered .tagN n).toOption.map serConstant == some (serConstant n) -def scaleTests (_ : Unit) : TestSeq := - let big := wrapRoots (scaleRoots 1040 12) 0 - let spine := wrapRoots (spineRoots 1288) 0 - let d := 10000 - let shared : Ixon.Expr := .ref 5 #[0, 0, 0, 0, 0] - let nested : Ixon.Expr := - (List.range d).foldl (fun acc i => .app (.var (i % 2).toUInt64) acc) shared - let telescope : Ixon.Expr := - (List.range d).foldl (fun acc i => .lam (.var (i % 3).toUInt64) acc) shared - let deep := wrapRoots #[nested, telescope, shared] 0 - group "the production construction at scale" <| - withOk "1040 fillers" (canonicalSharingTieredTable .tagN #[] (constantInfoRoots big.info)) - (fun r => withOk "1040 fillers" (normalizeConstantSharingTiered .tagN big) fun n => - test s!"{r.result.stats.distinctSubterms} terms (parallel widths, ≥ {tieredParMin}), {n.sharing.size} entries (> 1032: 3-byte Shares), the phase-2 guard keeps the phase-1 order (reference cost {r.stats.phase1RefCost}); widths run alone agree, idempotent, serialized = fixed + variable" - (r.result.stats.distinctSubterms ≥ tieredParMin && n.sharing.size > 1032 && +def scaleTests : Spec := + describe "the production construction at scale" do + it s!"1040 fillers (parallel widths, ≥ {tieredParMin}), > 1032 entries (3-byte Shares), phase-2 guard keeps phase-1 order" do + let big := wrapRoots (scaleRoots 1040 12) 0 + withOk "1040 fillers" (canonicalSharingTieredTable .tagN #[] (constantInfoRoots big.info)) fun r => + withOk "1040 fillers" (normalizeConstantSharingTiered .tagN big) fun n => + expect (decide (r.result.stats.distinctSubterms ≥ tieredParMin) && + decide (n.sharing.size > 1032) && r.stats.keptPhase1Order && r.stats.finalRefCost == r.stats.phase1RefCost && - productionOk big r n)) ++ - withOk "spine" (canonicalSharingTieredTable .tagN #[] (constantInfoRoots spine.info)) - (fun r => withOk "spine" (normalizeConstantSharingTiered .tagN spine) fun n => - test s!"a 1288-argument App spine over a stored head: {cbytes n} bytes, {n.sharing.size} entries; widths run alone agree, idempotent, serialized = fixed + variable" - (n.sharing.size ≥ 1 && productionOk spine r n)) ++ - withOk "deep" (canonicalSharingTieredTable .tagN #[] (constantInfoRoots deep.info)) - (fun r => withOk "deep" (normalizeConstantSharingTiered .tagN deep) fun n => - test s!"{d}-deep argument nesting and a {d}-binder telescope over a shared Ref: {cbytes n} bytes, {n.sharing.size} entries; widths run alone agree, idempotent, serialized = fixed + variable" - (n.sharing.size ≥ 1 && productionOk deep r n)) + productionOk big r n) + it "a 1288-argument App spine over a stored head: widths run alone agree, idempotent, serialized = fixed + variable" do + let spine := wrapRoots (spineRoots 1288) 0 + withOk "spine" (canonicalSharingTieredTable .tagN #[] (constantInfoRoots spine.info)) fun r => + withOk "spine" (normalizeConstantSharingTiered .tagN spine) fun n => + expect (decide (n.sharing.size ≥ 1) && productionOk spine r n) + it "10000-deep argument nesting and a 10000-binder telescope over a shared Ref: widths run alone agree, idempotent, serialized = fixed + variable" do + let d := 10000 + let shared : Ixon.Expr := .ref 5 #[0, 0, 0, 0, 0] + let nested : Ixon.Expr := + (List.range d).foldl (fun acc i => .app (.var (i % 2).toUInt64) acc) shared + let telescope : Ixon.Expr := + (List.range d).foldl (fun acc i => .lam (.var (i % 3).toUInt64) acc) shared + let deep := wrapRoots #[nested, telescope, shared] 0 + withOk "deep" (canonicalSharingTieredTable .tagN #[] (constantInfoRoots deep.info)) fun r => + withOk "deep" (normalizeConstantSharingTiered .tagN deep) fun n => + expect (decide (n.sharing.size ≥ 1) && productionOk deep r n) /-! ## The production construction under its limits -/ @@ -382,47 +387,49 @@ def compilerFailsWith (c : Constant) (l : Limits) (key : String) (v : Nat) : Boo (msg.splitOn s!"resource exhausted: {key} (limit {v})").length > 1 | _ => false -def productionLimitTests (_ : Unit) : TestSeq := - let t16c := axiomOf (arr (chain 16) (chain 16)) - let t16 := constantInfoRoots t16c.info +def productionLimitTests : Spec := + let d : Limits := {} + let mkT16 : Unit → Constant := fun () => axiomOf (arr (chain 16) (chain 16)) -- 128 two-use atoms: 128 uncertain components and the table-count bracket -- knapsack (`Tests.SharingUniform.bracketTests`). - let atomRoots : Array Ixon.Expr := (Array.range 128).foldl - (fun acc i => let a : Ixon.Expr := .ref i.toUInt64 #[0]; acc ++ #[a, a]) #[] - let atomsC := wrapRoots atomRoots 0 - let d : Limits := {} - let cases : List (String × Constant × Limits × Resource × Nat) := [ - ("T16", t16c, { d with maxExprVisits := 3 }, .exprVisits, 3), - ("T16", t16c, { d with maxDepth := 2 }, .depth, 2), - ("T16", t16c, { d with maxNodes := 2 }, .nodes, 2), - ("T16", t16c, { d with maxStates := 0 }, .states, 0), - ("128 atoms", atomsC, { d with maxStates := 50 }, .states, 50), - ("128 atoms", atomsC, { d with maxCostEvals := 10 }, .costEvals, 10), - ("T16", t16c, { d with maxOutputBytes := 10 }, .outputBytes, 10), - ("T16", t16c, { d with maxMaterialize := 3 }, .materialize, 3), - ("T16", t16c, { d with maxMaterializeWork := 3 }, .materializeWork, 3), - ("128 atoms", atomsC, { d with maxKnapsackCells := 10 }, .knapsackCells, 10)] - group "the production construction under its limits" <| - cases.foldl (init := .done) (fun acc (name, c, l, r, v) => - acc ++ test s!"{name}: {r.key} = {v} → canonicalSharingTiered fails with resourceExhausted {r.key} {v}; the compiler's builder with resourceLimit naming {r.key}" - (failsWith (constantInfoRoots c.info) l r v && compilerFailsWith c l r.key v)) ++ - test "the transitions limit meters only the width-state oracle: maxTransitions = 0 leaves T16 and the 128 atoms unchanged" - ((canonicalSharingTiered .tagN t16 { d with maxTransitions := 0 }).toOption.map + let mkAtomRoots : Unit → Array Ixon.Expr := fun () => + (Array.range 128).foldl + (fun acc i => let a : Ixon.Expr := .ref i.toUInt64 #[0]; acc ++ #[a, a]) #[] + let mkAtoms : Unit → Constant := fun () => wrapRoots (mkAtomRoots ()) 0 + let cases : List (String × (Unit → Constant) × Limits × Resource × Nat) := [ + ("T16", mkT16, { d with maxExprVisits := 3 }, .exprVisits, 3), + ("T16", mkT16, { d with maxDepth := 2 }, .depth, 2), + ("T16", mkT16, { d with maxNodes := 2 }, .nodes, 2), + ("T16", mkT16, { d with maxStates := 0 }, .states, 0), + ("128 atoms", mkAtoms, { d with maxStates := 50 }, .states, 50), + ("128 atoms", mkAtoms, { d with maxCostEvals := 10 }, .costEvals, 10), + ("T16", mkT16, { d with maxOutputBytes := 10 }, .outputBytes, 10), + ("T16", mkT16, { d with maxMaterialize := 3 }, .materialize, 3), + ("T16", mkT16, { d with maxMaterializeWork := 3 }, .materializeWork, 3), + ("128 atoms", mkAtoms, { d with maxKnapsackCells := 10 }, .knapsackCells, 10)] + describe "the production construction under its limits" do + for (name, mkC, l, r, v) in cases do + it s!"{name}: {r.key} = {v} → canonicalSharingTiered fails with resourceExhausted {r.key} {v}; the compiler's builder with resourceLimit naming {r.key}" do + let c := mkC () + expect (failsWith (constantInfoRoots c.info) l r v && compilerFailsWith c l r.key v) + it "the transitions limit meters only the width-state oracle: maxTransitions = 0 leaves T16 and the 128 atoms unchanged" do + let t16 := constantInfoRoots (mkT16 ()).info + let atomRoots := mkAtomRoots () + expect ((canonicalSharingTiered .tagN t16 { d with maxTransitions := 0 }).toOption.map (·.result.sharing) == (canonicalSharingTiered .tagN t16).toOption.map (·.result.sharing) && (canonicalSharingTiered .tagN atomRoots { d with maxTransitions := 0 }).toOption.map (·.result.variableBytes) == (canonicalSharingTiered .tagN atomRoots).toOption.map (·.result.variableBytes) && (canonicalSharingTiered .tagN t16).toOption.isSome) -public def suite : List TestSeq := [ - deferred "tiered layouts" layoutTests, - deferred "tiered fixtures" fixtureTests, - deferred "tiered allocation" allocationTests, - deferred "first-tier brute force" tierBruteTests, - deferred "Kahn priority order" kahnTests, - deferred "phase-3 per-prefix fallback" fallbackTests, - deferred "tiered at scale" scaleTests, - deferred "tiered limits" productionLimitTests, -] +public def suite : Spec := do + layoutTests + fixtureTests + allocationTests + tierBruteTests + kahnTests + fallbackTests + scaleTests + productionLimitTests end Tests.SharingTiered diff --git a/Tests/Ix/SharingUniform.lean b/Tests/Ix/SharingUniform.lean index 7a022af72d..c712f4ca92 100644 --- a/Tests/Ix/SharingUniform.lean +++ b/Tests/Ix/SharingUniform.lean @@ -118,124 +118,131 @@ def checkUniform (w : Nat) (roots : Array Ixon.Expr) : | .error e, _, _ => .error s!"w={w}: uniform error {reprStr e} roots={reprStr roots}" | _, .error e, _ | _, _, .error e => .error s!"w={w}: reference error {reprStr e} roots={reprStr roots}" -def agreementTestsWith (target : Nat) (_ : Unit) : TestSeq := - let (checked, cs, ce, un, maxComp, withUncertain, err) := runGen 61 do - let mut checked := 0 - let mut cs := 0 - let mut ce := 0 - let mut un := 0 - let mut maxComp := 0 - let mut withUncertain := 0 - let mut err : Option String := none - for i in [0:3000] do - if checked ≥ target || err.isSome then break - let roots ← genUniformRoots - let w := [1, 2, 3, 5][← rand 4]! - -- Keep the reference search small. - let refCands := match sharingProfile (wrapRoots roots 0) with - | .ok p => p.candidates - | .error _ => 100 - if refCands > 11 then continue - match checkUniform w roots with - | .ok (a, b, c, m) => - checked := checked + 1 - cs := cs + a - ce := ce + b - un := un + c - maxComp := max maxComp m - if c > 0 then withUncertain := withUncertain + 1 - | .error m => err := some s!"case {i}: {m}" - return (checked, cs, ce, un, maxComp, withUncertain, err) - group "uniform optimizer vs width-state reference (uniform widths)" <| - test s!"{checked} generated inputs (w ∈ 1,2,3,5; prefixes, 2-byte payloads, parent/child pairs, App chains, general): equal minimum (also = in-degree-≥2 reference); certain-stored ⊆ restricted optimum; certain-excluded in neither optimum; ≤ unshared ({cs} certain-stored, {ce} certain-excluded, {un} uncertain terms; {withUncertain} inputs with uncertain terms; largest component {maxComp})" - (err.isNone && checked == target) ++ - (match err with | some m => test m false | none => .done) - -def agreementTests (_ : Unit) : TestSeq := agreementTestsWith 400 () -def agreementTestsPR (_ : Unit) : TestSeq := agreementTestsWith 60 () - -def witnessTests (_ : Unit) : TestSeq := - let roots := constantInfoRoots witness2.info - let run (w : Nat) := optimizeSharingUniform w roots - group "uniform witness T2 → T2 (ids P=0 T1=1 T2=2 R=3)" <| - withOk "w=1" (run 1) (fun u => - test s!"w=1: T2 has gain 1, certain-stored at threshold 1 (no count bracket within reach), stores only T2, model {u.result.modelBytes} = 8" - (u.certainStored == #[2] && u.stored == #[2] && u.result.modelBytes == 8 && - u.result.variableBytes == 8)) ++ - withOk "w=2" (run 2) (fun u => - test s!"w=2: T2 uncertain, search stores nothing, model {u.result.modelBytes} = 9 (unshared); T1 certain-excluded" - (u.uncertain == #[2] && u.stored.isEmpty && u.result.modelBytes == 9 && - u.certainExcluded.contains 1)) ++ - withOk "w=3" (run 3) (fun u => - test s!"w=3: T1 and T2 certain-excluded, stores nothing, model {u.result.modelBytes} = 9 (unshared)" - (u.certainExcluded.contains 1 && u.certainExcluded.contains 2 && u.stored.isEmpty && - u.result.modelBytes == 9)) ++ - test "w=1,2,3 agree with the reference search" - ([1, 2, 3].all fun w => (checkUniform w roots).toOption.isSome) ++ - test "w=0 is rejected" (isErr (optimizeSharingUniform 0 roots) fun - | .formatBound _ _ => true - | _ => false) - -def t16Tests (_ : Unit) : TestSeq := - let roots := constantInfoRoots (axiomOf (arr (chain 16) (chain 16))).info - group "uniform T16 → T16" <| - withOk "w=1" (optimizeSharingUniform 1 roots) (fun u => - withOk "reference" (optimizeSharingUniformReference 1 roots) fun r => - test s!"w=1: model {u.result.modelBytes} = reference {r.modelBytes}; classes {u.certainStored.size} stored / {u.uncertain.size} uncertain / {u.certainExcluded.size} excluded; {u.statesVisited} states vs reference {r.stats.statesReached}" - (u.result.modelBytes == r.modelBytes && (checkUniform 1 roots).toOption.isSome)) +def agreementTestsWith (target : Nat) : Spec := + describe "uniform optimizer vs width-state reference (uniform widths)" do + it s!"{target} generated inputs (w ∈ 1,2,3,5; prefixes, 2-byte payloads, parent/child pairs, App chains, general)" do + let (checked, cs, ce, un, maxComp, withUncertain, err) := runGen 61 do + let mut checked := 0 + let mut cs := 0 + let mut ce := 0 + let mut un := 0 + let mut maxComp := 0 + let mut withUncertain := 0 + let mut err : Option String := none + for i in [0:3000] do + if checked ≥ target || err.isSome then break + let roots ← genUniformRoots + let w := [1, 2, 3, 5][← rand 4]! + -- Keep the reference search small. + let refCands := match sharingProfile (wrapRoots roots 0) with + | .ok p => p.candidates + | .error _ => 100 + if refCands > 11 then continue + match checkUniform w roots with + | .ok (a, b, c, m) => + checked := checked + 1 + cs := cs + a + ce := ce + b + un := un + c + maxComp := max maxComp m + if c > 0 then withUncertain := withUncertain + 1 + | .error m => err := some s!"case {i}: {m}" + return (checked, cs, ce, un, maxComp, withUncertain, err) + if let some m := err then fail m + expect (checked == target) + s!"checked {checked}/{target} ({cs} certain-stored, {ce} certain-excluded, {un} uncertain, {withUncertain} with uncertain, maxComp={maxComp})" + +def agreementTests : Spec := agreementTestsWith 400 +def agreementTestsPR : Spec := agreementTestsWith 60 + +def witnessTests : Spec := + describe "uniform witness T2 → T2 (ids P=0 T1=1 T2=2 R=3)" do + it "w=1: T2 has gain 1, certain-stored at threshold 1, stores only T2, model = 8" do + let roots := constantInfoRoots witness2.info + withOk "w=1" (optimizeSharingUniform 1 roots) fun u => + expect (u.certainStored == #[2] && u.stored == #[2] && u.result.modelBytes == 8 && + u.result.variableBytes == 8) + it "w=2: T2 uncertain, search stores nothing, model = 9 (unshared); T1 certain-excluded" do + let roots := constantInfoRoots witness2.info + withOk "w=2" (optimizeSharingUniform 2 roots) fun u => + expect (u.uncertain == #[2] && u.stored.isEmpty && u.result.modelBytes == 9 && + u.certainExcluded.contains 1) + it "w=3: T1 and T2 certain-excluded, stores nothing, model = 9 (unshared)" do + let roots := constantInfoRoots witness2.info + withOk "w=3" (optimizeSharingUniform 3 roots) fun u => + expect (u.certainExcluded.contains 1 && u.certainExcluded.contains 2 && u.stored.isEmpty && + u.result.modelBytes == 9) + itBool "w=1,2,3 agree with the reference search" + (let roots := constantInfoRoots witness2.info + [1, 2, 3].all fun w => (checkUniform w roots).toOption.isSome) + itBool "w=0 is rejected" + (let roots := constantInfoRoots witness2.info + isErr (optimizeSharingUniform 0 roots) fun + | .formatBound _ _ => true + | _ => false) + +def t16Tests : Spec := + describe "uniform T16 → T16" do + it "w=1: model = reference" do + let roots := constantInfoRoots (axiomOf (arr (chain 16) (chain 16))).info + withOk "w=1" (optimizeSharingUniform 1 roots) fun u => + withOk "reference" (optimizeSharingUniformReference 1 roots) fun r => + expect (u.result.modelBytes == r.modelBytes && (checkUniform 1 roots).toOption.isSome) + s!"model={u.result.modelBytes}, reference={r.modelBytes}" /-- 128 and 129 independent atoms whose sharing saves exactly one byte each: the table count crosses 128. -/ -def bracketTests (_ : Unit) : TestSeq := +def bracketTests : Spec := let atoms (n : Nat) : Array Ixon.Expr := (Array.range n).map fun i => .ref i.toUInt64 #[0] let rootsOf (n : Nat) := (atoms n).foldl (fun acc a => acc ++ #[a, a]) #[] let sizes (n : Nat) := (atoms n).map exprSize - group "table-count bracket coupling" <| - withOk "128 atoms" (optimizeSharingUniform 1 (rootsOf 128)) (fun u => - test s!"128 atoms: all uncertain; storing 127 ties storing 128 (one count byte); the tie order leaves out the smallest ID; model {u.result.modelBytes} = 642" - (u.uncertain.size == 128 && u.stored.size == 127 && !u.stored.contains 0 && + describe "table-count bracket coupling" do + it "128 atoms: all uncertain; storing 127 ties storing 128 (one count byte); model = 642" do + withOk "128 atoms" (optimizeSharingUniform 1 (rootsOf 128)) fun u => + expect (u.uncertain.size == 128 && u.stored.size == 127 && !u.stored.contains 0 && u.lowerBracket && u.result.modelBytes == 1 + 127 * 5 + 6 && - u.result.modelBytes == 2 + 128 * 5)) ++ - withOk "129 atoms" (optimizeSharingUniform 1 (rootsOf 129)) (fun u => - test s!"129 atoms (the last, Ref(128), is 4 bytes and certain-stored): keeps all 129, model {u.result.modelBytes} = 648" - (u.stored.size == 129 && !u.lowerBracket && u.certainStored == #[128] && - u.result.modelBytes == 2 + 128 * 5 + 6)) ++ - test "atom brute force agrees on 10 atoms with mixed sizes and uses" + u.result.modelBytes == 2 + 128 * 5) + it "129 atoms (the last, Ref(128), is 4 bytes and certain-stored): keeps all 129, model = 648" do + withOk "129 atoms" (optimizeSharingUniform 1 (rootsOf 129)) fun u => + expect (u.stored.size == 129 && !u.lowerBracket && u.certainStored == #[128] && + u.result.modelBytes == 2 + 128 * 5 + 6) + itBool "atom brute force agrees on 10 atoms with mixed sizes and uses" (let as : Array Ixon.Expr := (Array.range 10).map fun i => .ref i.toUInt64 (Array.replicate (i % 3) 0) let occs := (Array.range 10).map fun i => 1 + i % 4 let roots := (Array.range 10).foldl (fun acc i => acc ++ Array.replicate occs[i]! as[i]!) #[] [1, 2, 3].all fun w => (optimizeSharingUniform w roots).toOption.map (·.result.modelBytes) == - some (atomsUniformBrute w (as.map exprSize) occs)) ++ - test "sizes" ((sizes 3).all (· == 3)) - -def propertyTestsWith (target : Nat) (_ : Unit) : TestSeq := - let (checked, err) := runGen 67 do - let mut checked := 0 - let mut err : Option String := none - for i in [0:target] do - if err.isSome then break - let roots ← genRoots 6 16 4 - let c := wrapRoots roots i - let w := [1, 2, 4][← rand 3]! - match normalizeConstantSharingUniform w c with - | .ok n => - checked := checked + 1 - let again := (normalizeConstantSharingUniform w n).toOption.map serConstant - let fresh := match deConstant (serConstant c) with - | .ok c' => (normalizeConstantSharingUniform w c').toOption.map serConstant - | .error _ => none - unless again == some (serConstant n) && fresh == some (serConstant n) do - err := some s!"case {i}: not idempotent or representation dependent" - | .error e => err := some s!"case {i}: error {reprStr e}" - return (checked, err) - group "uniform properties" <| - test s!"{checked} constants: normalize is idempotent and independent of pointer layout" (err.isNone && checked == target) ++ - (match err with | some m => test m false | none => .done) - -def propertyTests (_ : Unit) : TestSeq := propertyTestsWith 200 () -def propertyTestsPR (_ : Unit) : TestSeq := propertyTestsWith 60 () + some (atomsUniformBrute w (as.map exprSize) occs)) + itBool "sizes" ((sizes 3).all (· == 3)) + +def propertyTestsWith (target : Nat) : Spec := + describe "uniform properties" do + it s!"{target} constants: normalize is idempotent and independent of pointer layout" do + let (checked, err) := runGen 67 do + let mut checked := 0 + let mut err : Option String := none + for i in [0:target] do + if err.isSome then break + let roots ← genRoots 6 16 4 + let c := wrapRoots roots i + let w := [1, 2, 4][← rand 3]! + match normalizeConstantSharingUniform w c with + | .ok n => + checked := checked + 1 + let again := (normalizeConstantSharingUniform w n).toOption.map serConstant + let fresh := match deConstant (serConstant c) with + | .ok c' => (normalizeConstantSharingUniform w c').toOption.map serConstant + | .error _ => none + unless again == some (serConstant n) && fresh == some (serConstant n) do + err := some s!"case {i}: not idempotent or representation dependent" + | .error e => err := some s!"case {i}: error {reprStr e}" + return (checked, err) + if let some m := err then fail m + expect (checked == target) s!"checked {checked} != {target}" + +def propertyTests : Spec := propertyTestsWith 200 +def propertyTestsPR : Spec := propertyTestsWith 60 /-- `mk a₁ … aₙ`-style prefix chains: `uₖ = uₖ₋₁ aₖ`, each prefix also used once as the head of a longer spine with other arguments (the shape of @@ -324,53 +331,53 @@ uncertain components. The inputs are drawn in order from one seed; both searches run on batches of them in parallel, and the outcomes are read in draw order, so the inputs checked are the first `target` with a component of ≥ 2 uncertain terms, as when the searches ran on one input at a time. -/ -def searchTestsWith (target : Nat) (_ : Unit) : TestSeq := - let inputs := runGen 71 do - let mut out : Array (Array Ixon.Expr × Nat) := #[] - for _ in [0:4000] do - let roots ← genSearchRoots - out := out.push (roots, [1, 2, 3, 5][← rand 4]!) - return out - let (checked, skipped, maxComp, err) := Id.run do - let mut checked := 0 - let mut skipped := 0 - let mut maxComp := 0 - let mut err : Option String := none - for start in [0:inputs.size:64] do - if checked ≥ target || err.isSome then break - let tasks := (inputs.extract start (start + 64)).zipIdx.map fun ((roots, w), k) => - Task.spawn fun _ => searchOutcome (start + k) w roots - for task in tasks do - if checked ≥ target || err.isSome then break - match task.get with - | .small => pure () - | .agree comp => - checked := checked + 1 - maxComp := max maxComp comp - | .skipped => skipped := skipped + 1 - | .failed comp message => - if let some comp := comp then - checked := checked + 1 - maxComp := max maxComp comp - err := some message - return (checked, skipped, maxComp, err) - group "uniform branch and bound vs subset enumeration" <| - test s!"{checked} generated inputs with a component of ≥ 2 uncertain terms (prefix chains, telescopes, App chains, long spines, prefixes, general; w ∈ 1,2,3,5; largest component {maxComp}; {skipped} skipped where the enumeration exceeded 2^16 states): identical retained per-count optima/ties, stored set, model length and bracket choice" - (err.isNone && checked == target) ++ - (match err with | some m => test m false | none => .done) - -def searchTests (_ : Unit) : TestSeq := searchTestsWith 600 () -def searchTestsPR (_ : Unit) : TestSeq := searchTestsWith 60 () +def searchTestsWith (target : Nat) : Spec := + describe "uniform branch and bound vs subset enumeration" do + it s!"{target} generated inputs with a component of ≥ 2 uncertain terms: identical retained per-count optima/ties, stored set, model length and bracket choice" do + let inputs := runGen 71 do + let mut out : Array (Array Ixon.Expr × Nat) := #[] + for _ in [0:4000] do + let roots ← genSearchRoots + out := out.push (roots, [1, 2, 3, 5][← rand 4]!) + return out + let (checked, skipped, maxComp, err) := Id.run do + let mut checked := 0 + let mut skipped := 0 + let mut maxComp := 0 + let mut err : Option String := none + for start in [0:inputs.size:64] do + if checked ≥ target || err.isSome then break + let tasks := (inputs.extract start (start + 64)).zipIdx.map fun ((roots, w), k) => + Task.spawn fun _ => searchOutcome (start + k) w roots + for task in tasks do + if checked ≥ target || err.isSome then break + match task.get with + | .small => pure () + | .agree comp => + checked := checked + 1 + maxComp := max maxComp comp + | .skipped => skipped := skipped + 1 + | .failed comp message => + if let some comp := comp then + checked := checked + 1 + maxComp := max maxComp comp + err := some message + return (checked, skipped, maxComp, err) + if let some m := err then fail m + expect (checked == target) s!"checked {checked}/{target} (largest component {maxComp}, {skipped} skipped)" + +def searchTests : Spec := searchTestsWith 600 +def searchTestsPR : Spec := searchTestsWith 60 /-- Search agreement across the 128-entry table-count bracket: 120 one-byte atoms used twice (uncertain, gain 1) plus an App prefix chain. -/ -def searchBracketTests (_ : Unit) : TestSeq := - let atoms : Array Ixon.Expr := (Array.range 120).map fun i => .ref i.toUInt64 #[0] - let chain := runGen 5 genPrefixChain - let roots := atoms.foldl (fun acc a => acc ++ #[a, a]) #[] ++ chain - group "uniform branch and bound across a count bracket" <| - test "w=1,2,3: the branch and bound and the subset enumeration store the same set" - ([1, 2, 3].all fun w => +def searchBracketTests : Spec := + describe "uniform branch and bound across a count bracket" do + it "w=1,2,3: the branch and bound and the subset enumeration store the same set" do + let atoms : Array Ixon.Expr := (Array.range 120).map fun i => .ref i.toUInt64 #[0] + let chain := runGen 5 genPrefixChain + let roots := atoms.foldl (fun acc a => acc ++ #[a, a]) #[] ++ chain + expect ([1, 2, 3].all fun w => match optimizeSharingUniform w roots, optimizeSharingUniform w roots { uniformSubsetSearch := true } with | .ok u, .ok r => u.stored == r.stored && u.result.modelBytes == r.result.modelBytes && @@ -412,33 +419,31 @@ def symmDiffMinIn (a b : Array Nat) : Bool := | some m => b.contains m | none => false -def tieOrderTests (_ : Unit) : TestSeq := - group "uniform tie order" <| - test "setPrec agrees with the imperative loop on all arrays of length ≤ 3 over 0..3" - (smallArrays.all fun a => smallArrays.all fun b => setPrec a b == setPrecLoop a b) ++ - test "on sets, setPrec a b iff the least element of the symmetric difference is in b" - (smallSets.all fun a => smallSets.all fun b => setPrec a b == symmDiffMinIn a b) ++ - test "setPrec is a strict total order on the subsets of 0..4" +def tieOrderTests : Spec := + describe "uniform tie order" do + itBool "setPrec agrees with the imperative loop on all arrays of length ≤ 3 over 0..3" + (smallArrays.all fun a => smallArrays.all fun b => setPrec a b == setPrecLoop a b) + itBool "on sets, setPrec a b iff the least element of the symmetric difference is in b" + (smallSets.all fun a => smallSets.all fun b => setPrec a b == symmDiffMinIn a b) + itBool "setPrec is a strict total order on the subsets of 0..4" (smallSets.all fun a => !setPrec a a && smallSets.all fun b => (a == b || setPrec a b != setPrec b a) && smallSets.all fun c => !(setPrec a b && setPrec b c) || setPrec a c) -public def suite : List TestSeq := [ - deferred "uniform tie order" tieOrderTests, - deferred "uniform witness" witnessTests, - deferred "uniform vs reference" agreementTestsPR, - deferred "uniform T16" t16Tests, - deferred "uniform table-count brackets" bracketTests, - deferred "uniform properties" propertyTestsPR, - deferred "uniform search vs enumeration" searchTestsPR, - deferred "uniform search across a bracket" searchBracketTests, -] +public def suite : Spec := do + tieOrderTests + witnessTests + agreementTestsPR + t16Tests + bracketTests + propertyTestsPR + searchTestsPR + searchBracketTests /-- Full randomized sweeps for nightly CI (`exact-sharing-full`). -/ -public def nightlySuite : List TestSeq := [ - deferred "uniform vs reference (full)" agreementTests, - deferred "uniform properties (full)" propertyTests, - deferred "uniform search vs enumeration (full)" searchTests, -] +public def nightlySuite : Spec := do + agreementTests + propertyTests + searchTests end Tests.SharingUniform diff --git a/Tests/Ix/SourceContract.lean b/Tests/Ix/SourceContract.lean index 2de2fbc839..0adb0d8e35 100644 --- a/Tests/Ix/SourceContract.lean +++ b/Tests/Ix/SourceContract.lean @@ -15,9 +15,6 @@ namespace Tests.Ix.SourceContract open Lean LSpec open Ix.Compile -private def test (description : String) (condition : Bool) : TestSeq := - LSpec.test description (condition = true) - private def natType : Expr := .const `Nat [] private def definition (name : Name) (type value : Expr) : ConstantInfo := @@ -49,34 +46,34 @@ private def resolvedModes (actual : Except SourceContractError ResolvedSourceCon | .error _ => #[] | .ok contract => contract.binders.map fun binder => (binder.site, binder.mode, binder.result) -def telescopeTests : TestSeq := - test "identity resolves once/unique type and once body at independent sites" +public def telescopeTests : LSpec.Spec := do + itBool "identity resolves once/unique type and once body at independent sites" (resolvedModes (resolveTelescope (identity) #[{ binder := .position 0, mode := .once, result := some .unique }]) == - #[(⟨.type, []⟩, .once, some .unique), (⟨.body, []⟩, .once, none)]) ++ - test "all seven binder modes are accepted without inferring resource validity" + #[(⟨.type, []⟩, .once, some .unique), (⟨.body, []⟩, .once, none)]) + itBool "all seven binder modes are accepted without inferring resource validity" ([Ixon.BinderMode.many, .borrowed, .unique, .uniqueBorrowed, .once, .onceBorrowed, .erased].all fun mode => - (resolveTelescope (identity) #[{ binder := .position 0, mode, result := some .shared }]).isOk) ++ - test "result mode shorthand affects only the selected curried arrow" + (resolveTelescope (identity) #[{ binder := .position 0, mode, result := some .shared }]).isOk) + itBool "result mode shorthand affects only the selected curried arrow" (resolvedModes (resolveTelescope curried #[{ binder := .name `y, mode := .once, result := some .unique }]) == #[(⟨.type, [.binderBody]⟩, .once, some .unique), - (⟨.body, [.binderBody]⟩, .once, none)]) ++ - test "implicit argument retains its position and does not imply erasure" + (⟨.body, [.binderBody]⟩, .once, none)]) + itBool "implicit argument retains its position and does not imply erasure" (match resolveTelescope curried #[{ binder := .position 0, mode := .many }] with | .ok result => result.binders.all fun binder => binder.binderInfo == .implicit && binder.mode == .many - | .error _ => false) ++ - test "out-of-range elaborated positions are rejected" + | .error _ => false) + itBool "out-of-range elaborated positions are rejected" (expectError (resolveTelescope curried #[{ binder := .position 2, mode := .once }]) - (.argumentOutOfRange `curried 2)) ++ - test "missing binder names are rejected" + (.argumentOutOfRange `curried 2)) + itBool "missing binder names are rejected" (expectError (resolveTelescope curried #[{ binder := .name `missing, mode := .once }]) - (.unknownBinder `curried `missing)) ++ - test "name and position annotations cannot silently overwrite the same site" + (.unknownBinder `curried `missing)) + itBool "name and position annotations cannot silently overwrite the same site" (expectError (resolveTelescope curried #[{ binder := .name `y, mode := .once }, { binder := .position 1, mode := .borrowed }]) (.duplicateSite `curried ⟨.type, [.binderBody]⟩)) -def occurrenceTests : TestSeq := Id.run do +public def occurrenceTests : LSpec.Spec := do let lam := Expr.lam `shadow natType (.bvar 0) .default let nested := definition `nested (.forallE `x natType natType .default) (.lam `x natType (.app lam (.app lam (.bvar 0))) .default) @@ -91,28 +88,28 @@ def occurrenceTests : TestSeq := Id.run do let wrapped := definition `wrapped (.mdata {} (.forallE `x natType natType .default)) (.mdata {} (.lam `x natType (.bvar 0) .default)) - return test "equal nested lambdas can carry different occurrence contracts" - (resolvedModes (distinct.resolve nested) == #[(left, .once, none), (right, .borrowed, none)]) ++ - test "annotation order has a canonical resolved order" - (resolvedModes (({ distinct with binders := distinct.binders.reverse }).resolve nested) == - resolvedModes (distinct.resolve nested)) ++ - test "shadowed declaration binders require an explicit position" - (expectError (resolveTelescope shadowed #[{ binder := .name `x, mode := .once }]) - (.ambiguousBinder `shadowed `x)) ++ - test "position disambiguates shadowed declaration binders" - ((resolveTelescope shadowed #[{ binder := .position 1, mode := .once }]).isOk) ++ - test "metadata wrappers appear in resolved telescope paths" - (resolvedModes (resolveTelescope wrapped #[{ binder := .position 0, mode := .once, result := some .unique }]) == - #[(⟨.type, [.metadata]⟩, .once, some .unique), - (⟨.body, [.metadata]⟩, .once, none)]) ++ - test "invalid structural edges fail before canonicalization" - (expectError (({ source := identity, binders := #[{ site := ⟨.body, [.appArg]⟩, mode := .once }] } : SourceContract).resolve identity) - (.invalidSite `identity ⟨.body, [.appArg]⟩)) ++ - test "an expression occurrence must actually be a binder" - (expectError (({ source := identity, binders := #[{ site := ⟨.body, [.binderBody]⟩, mode := .once }] } : SourceContract).resolve identity) - (.expectedBinder `identity ⟨.body, [.binderBody]⟩)) + itBool "equal nested lambdas can carry different occurrence contracts" + (resolvedModes (distinct.resolve nested) == #[(left, .once, none), (right, .borrowed, none)]) + itBool "annotation order has a canonical resolved order" + (resolvedModes (({ distinct with binders := distinct.binders.reverse }).resolve nested) == + resolvedModes (distinct.resolve nested)) + itBool "shadowed declaration binders require an explicit position" + (expectError (resolveTelescope shadowed #[{ binder := .name `x, mode := .once }]) + (.ambiguousBinder `shadowed `x)) + itBool "position disambiguates shadowed declaration binders" + ((resolveTelescope shadowed #[{ binder := .position 1, mode := .once }]).isOk) + itBool "metadata wrappers appear in resolved telescope paths" + (resolvedModes (resolveTelescope wrapped #[{ binder := .position 0, mode := .once, result := some .unique }]) == + #[(⟨.type, [.metadata]⟩, .once, some .unique), + (⟨.body, [.metadata]⟩, .once, none)]) + itBool "invalid structural edges fail before canonicalization" + (expectError (({ source := identity, binders := #[{ site := ⟨.body, [.appArg]⟩, mode := .once }] } : SourceContract).resolve identity) + (.invalidSite `identity ⟨.body, [.appArg]⟩)) + itBool "an expression occurrence must actually be a binder" + (expectError (({ source := identity, binders := #[{ site := ⟨.body, [.binderBody]⟩, mode := .once }] } : SourceContract).resolve identity) + (.expectedBinder `identity ⟨.body, [.binderBody]⟩)) -def rejectionTests : TestSeq := Id.run do +public def rejectionTests : LSpec.Spec := do let bodySite : BinderSite := ⟨.body, []⟩ let typeSite : BinderSite := ⟨.type, []⟩ let contract : SourceContract := { @@ -125,23 +122,23 @@ def rejectionTests : TestSeq := Id.run do let changedMetadata := definition `identity (.forallE `x natType natType .default) (.mdata {} (.lam `x natType (.bvar 0) .default)) let alias := definition `alias (.forallE `x natType natType .default) (.const `identity []) - return test "type/body mode disagreement is rejected" - (expectError (({ source := identity, binders := #[{ site := typeSite, mode := .once }] } : SourceContract).resolve identity) - (.inconsistentTelescope `identity 0 .once .many)) ++ - test "a lambda has no independent result-mode field" - (expectError (({ source := identity, binders := #[{ site := bodySite, mode := .many, result := some .shared }] } : SourceContract).resolve identity) - (.resultOnNonArrow `identity bodySite)) ++ - test "source binder spelling is part of the occurrence fingerprint" - (expectError (contract.resolve renamed) (.staleSource `identity)) ++ - test "source BinderInfo drift invalidates a previously resolved contract" - (expectError (contract.resolve changedInfo) (.staleSource `identity)) ++ - test "source metadata shape drift invalidates structural paths" - (expectError (contract.resolve changedMetadata) (.staleSource `identity)) ++ - test "unsupported body telescope normalization gets a diagnostic" - (expectError (resolveTelescope alias #[{ binder := .position 0, mode := .once }]) - (.missingBodyBinder `alias 0)) + itBool "type/body mode disagreement is rejected" + (expectError (({ source := identity, binders := #[{ site := typeSite, mode := .once }] } : SourceContract).resolve identity) + (.inconsistentTelescope `identity 0 .once .many)) + itBool "a lambda has no independent result-mode field" + (expectError (({ source := identity, binders := #[{ site := bodySite, mode := .many, result := some .shared }] } : SourceContract).resolve identity) + (.resultOnNonArrow `identity bodySite)) + itBool "source binder spelling is part of the occurrence fingerprint" + (expectError (contract.resolve renamed) (.staleSource `identity)) + itBool "source BinderInfo drift invalidates a previously resolved contract" + (expectError (contract.resolve changedInfo) (.staleSource `identity)) + itBool "source metadata shape drift invalidates structural paths" + (expectError (contract.resolve changedMetadata) (.staleSource `identity)) + itBool "unsupported body telescope normalization gets a diagnostic" + (expectError (resolveTelescope alias #[{ binder := .position 0, mode := .once }]) + (.missingBodyBinder `alias 0)) -def inputTests : TestSeq := Id.run do +public def inputTests : LSpec.Spec := do let source := identity let constants := [(source.name, source)] let first : SourceContract := { @@ -155,42 +152,42 @@ def inputTests : TestSeq := Id.run do { constants := constants ++ [(second.name, second)], contracts := #[first, secondContract] } let hinted : CompileInput := { constants, contracts := #[], measureHints := #[⟨source, .name `x, some 1⟩] } - return test "plain input preserves selected source and has no semantic contracts" - (match (CompileInput.plain constants).resolve with - | .ok result => result.constants == constants && result.contracts.isEmpty - | .error _ => false) ++ - test "equal declaration bodies retain their distinct semantic contracts" - (match sameBody.resolve with - | .ok result => result.contracts.size == 2 && - result.contracts[0]!.modeAt ⟨.body, []⟩ == .once && - result.contracts[1]!.modeAt ⟨.body, []⟩ == .borrowed - | .error _ => false) ++ - test "duplicate selected declarations are rejected" - (expectError ((CompileInput.plain (constants ++ constants)).resolve) - (.duplicateDeclaration `identity)) ++ - test "selected names must match their declaration" - (expectError ((CompileInput.plain [(`wrong, source)]).resolve) - (.declarationNameMismatch `wrong `identity)) ++ - test "a dangling registry entry cannot be silently dropped" - (expectError (({ constants := [], contracts := #[first] } : CompileInput).resolve) - (.missingDeclaration `identity)) ++ - test "duplicate declaration contracts cannot overwrite each other" - (expectError (({ constants, contracts := #[first, first] } : CompileInput).resolve) - (.duplicateContract `identity)) ++ - test "measure hints resolve to positions without changing source or modes" - (match hinted.resolve with - | .ok result => result.constants == constants && result.contracts.isEmpty && - result.measureHints.size == 1 && result.measureHints[0]!.argument == 0 && - result.measureHints[0]!.site == ⟨.type, []⟩ - | .error _ => false) ++ - test "zero-step proposals receive a diagnostic" - (expectError (({ hinted with measureHints := #[⟨source, .position 0, some 0⟩] }).resolve) - (.zeroFixedStep `identity)) ++ - test "multiple measure proposals for one declaration are rejected" - (expectError (({ hinted with measureHints := hinted.measureHints ++ hinted.measureHints }).resolve) - (.duplicateMeasure `identity)) + itBool "plain input preserves selected source and has no semantic contracts" + (match (CompileInput.plain constants).resolve with + | .ok result => result.constants == constants && result.contracts.isEmpty + | .error _ => false) + itBool "equal declaration bodies retain their distinct semantic contracts" + (match sameBody.resolve with + | .ok result => result.contracts.size == 2 && + result.contracts[0]!.modeAt ⟨.body, []⟩ == .once && + result.contracts[1]!.modeAt ⟨.body, []⟩ == .borrowed + | .error _ => false) + itBool "duplicate selected declarations are rejected" + (expectError ((CompileInput.plain (constants ++ constants)).resolve) + (.duplicateDeclaration `identity)) + itBool "selected names must match their declaration" + (expectError ((CompileInput.plain [(`wrong, source)]).resolve) + (.declarationNameMismatch `wrong `identity)) + itBool "a dangling registry entry cannot be silently dropped" + (expectError (({ constants := [], contracts := #[first] } : CompileInput).resolve) + (.missingDeclaration `identity)) + itBool "duplicate declaration contracts cannot overwrite each other" + (expectError (({ constants, contracts := #[first, first] } : CompileInput).resolve) + (.duplicateContract `identity)) + itBool "measure hints resolve to positions without changing source or modes" + (match hinted.resolve with + | .ok result => result.constants == constants && result.contracts.isEmpty && + result.measureHints.size == 1 && result.measureHints[0]!.argument == 0 && + result.measureHints[0]!.site == ⟨.type, []⟩ + | .error _ => false) + itBool "zero-step proposals receive a diagnostic" + (expectError (({ hinted with measureHints := #[⟨source, .position 0, some 0⟩] }).resolve) + (.zeroFixedStep `identity)) + itBool "multiple measure proposals for one declaration are rejected" + (expectError (({ hinted with measureHints := hinted.measureHints ++ hinted.measureHints }).resolve) + (.duplicateMeasure `identity)) -def modeBijectionTests : TestSeq := Id.run do +public def modeBijectionTests : LSpec.Spec := do let source := identity let typeSite : BinderSite := ⟨.type, []⟩ let bodySite : BinderSite := ⟨.body, []⟩ @@ -217,46 +214,46 @@ def modeBijectionTests : TestSeq := Id.run do source := ctor binders := #[{ site := ⟨.type, []⟩, mode := .erased }] fieldModes := #[{ fieldIndex := 0, mode := .shared }] } - return test "unique input is independent of the arrow result" - (match resolveTelescope source #[unique] with - | .ok result => result.modeAt typeSite == .unique && result.modeAt bodySite == .unique && - result.resultAt typeSite == .shared - | .error _ => false) ++ - test "all 28 AllMode combinations preserve input, result, and matching lambda fields" - (binderModes.all fun mode => resultModes.all fun output => - match resolveTelescope source #[{ binder := .position 0, mode, result := some output }] with - | .ok c => c.modeAt typeSite == mode && c.modeAt bodySite == mode && - c.resultAt typeSite == output - | .error _ => false) ++ - test "type and body must agree on unique mode" - (expectError (ownershipMismatch.resolve source) - (.inconsistentTelescope `identity 0 .unique .many)) ++ - test "type and body must agree on borrowed mode" - (expectError (localityMismatch.resolve source) - (.inconsistentTelescope `identity 0 .borrowed .many)) ++ - test "borrow let retains its explicit borrow flag and borrowed mode" - (match borrow.resolve binding with - | .ok c => c.binders[0]!.kind == .letE && c.binders[0]!.isBorrow && - c.binders[0]!.mode == .borrowed && c.binders[0]!.result.isNone - | .error _ => false) ++ - test "a shared borrow cannot manufacture unique ownership" - (expectError (({ borrow with binders := borrow.binders.map fun (b : BinderContract) => { b with mode := .uniqueBorrowed } }).resolve binding) - (.invalidBorrowView `binding bodySite)) ++ - test "a borrow flag cannot annotate a function binder" - (expectError (resolveTelescope source #[{ unique with mode := .borrowed, isBorrow := true }]) - (.borrowOnNonLet `identity typeSite)) ++ - test "constructor fieldModes and erased field resolve cleanly and reject @erased + @shared conflict" - (match ctorShared.resolve ctor with - | .ok r => r.fieldModeAt 0 == .shared && r.fieldModeAt 1 == .inherited && - r.modeAt ⟨.type, [.binderBody]⟩ == .erased - | .error _ => false) ++ - test "constructor rejects field that is both @erased and @shared" - (expectError (ctorConflict.resolve ctor) (.erasedSharedField `MyBox.mk 0)) ++ - test "fieldMode on non-constructor is rejected" - (expectError (({ source, fieldModes := #[{ fieldIndex := 0, mode := .shared }] } : SourceContract).resolve source) - (.fieldModeOnNonCtor `identity)) + itBool "unique input is independent of the arrow result" + (match resolveTelescope source #[unique] with + | .ok result => result.modeAt typeSite == .unique && result.modeAt bodySite == .unique && + result.resultAt typeSite == .shared + | .error _ => false) + itBool "all 28 AllMode combinations preserve input, result, and matching lambda fields" + (binderModes.all fun mode => resultModes.all fun output => + match resolveTelescope source #[{ binder := .position 0, mode, result := some output }] with + | .ok c => c.modeAt typeSite == mode && c.modeAt bodySite == mode && + c.resultAt typeSite == output + | .error _ => false) + itBool "type and body must agree on unique mode" + (expectError (ownershipMismatch.resolve source) + (.inconsistentTelescope `identity 0 .unique .many)) + itBool "type and body must agree on borrowed mode" + (expectError (localityMismatch.resolve source) + (.inconsistentTelescope `identity 0 .borrowed .many)) + itBool "borrow let retains its explicit borrow flag and borrowed mode" + (match borrow.resolve binding with + | .ok c => c.binders[0]!.kind == .letE && c.binders[0]!.isBorrow && + c.binders[0]!.mode == .borrowed && c.binders[0]!.result.isNone + | .error _ => false) + itBool "a shared borrow cannot manufacture unique ownership" + (expectError (({ borrow with binders := borrow.binders.map fun (b : BinderContract) => { b with mode := .uniqueBorrowed } }).resolve binding) + (.invalidBorrowView `binding bodySite)) + itBool "a borrow flag cannot annotate a function binder" + (expectError (resolveTelescope source #[{ unique with mode := .borrowed, isBorrow := true }]) + (.borrowOnNonLet `identity typeSite)) + itBool "constructor fieldModes and erased field resolve cleanly and reject @[erased] + @[shared] conflict" + (match ctorShared.resolve ctor with + | .ok r => r.fieldModeAt 0 == .shared && r.fieldModeAt 1 == .inherited && + r.modeAt ⟨.type, [.binderBody]⟩ == .erased + | .error _ => false) + itBool "constructor rejects field that is both @[erased] and @[shared]" + (expectError (ctorConflict.resolve ctor) (.erasedSharedField `MyBox.mk 0)) + itBool "fieldMode on non-constructor is rejected" + (expectError (({ source, fieldModes := #[{ fieldIndex := 0, mode := .shared }] } : SourceContract).resolve source) + (.fieldModeOnNonCtor `identity)) -def markerTests : TestSeq := Id.run do +public def markerTests : LSpec.Spec := do let annotation : BinderAnnotation := { origin := 0, binder := `x, mode := .uniqueBorrowed } let data := annotation.toMetadata @@ -273,126 +270,127 @@ def markerTests : TestSeq := Id.run do rules := [⟨`constructor, 0, .mdata missingVersion natType⟩] k := false, isUnsafe := false } let shared := (List.range 28).foldl (fun expr _ => Expr.app expr expr) natType - return test "source annotation metadata roundtrips v5 BinderMode, ResultMode, borrow flag, and origin" - (match BinderAnnotation.ofMetadata? data with + itBool "source annotation metadata roundtrips v5 BinderMode, ResultMode, borrow flag, and origin" + (match BinderAnnotation.ofMetadata? data with + | .ok decoded => decoded == some annotation + | .error _ => false) + itBool "adding source markers preserves Lean's singleton native borrow wrapper" + (match annotation.attach borrowed with + | .ok type => Lean.isMarkedBorrowed type && + match binderAnnotation? type with | .ok decoded => decoded == some annotation - | .error _ => false) ++ - test "adding source markers preserves Lean's singleton native borrow wrapper" - (match annotation.attach borrowed with - | .ok type => Lean.isMarkedBorrowed type && - match binderAnnotation? type with - | .ok decoded => decoded == some annotation - | .error _ => false - | .error _ => false) ++ - test "strict source metadata rejects unknown keys, duplicates, old versions, and overflowing codes" - ([data.setNat `ix.source.binder.future 0, duplicate, missingVersion, - data.setNat sourceAnnotationKey 3, data.setNat `ix.source.binder.mode 7, - data.setNat `ix.source.binder.mode 256, data.setNat `ix.source.binder.borrow 2].all fun malformed => - !(BinderAnnotation.ofMetadata? malformed).isOk) ++ - test "malformed reserved metadata is still detected by the preflight" - (exprHasSourceAnnotations (.mdata missingVersion natType)) ++ - test "source markers in raw recursor rules are detected and explicitly unsupported" - (sourceHasAnnotations recursor && - expectError (SourceContract.fromAnnotations recursor) (.annotatedRecursorRule recursor.name)) ++ - test "annotation scan handles heavily shared ordinary source and nearby markers" - (!exprHasSourceAnnotations shared && - exprHasSourceAnnotations (.app shared (.mdata data natType))) ++ - test "source markers require explicit matching records and cannot be overridden" - (expectError input.resolve (.missingContract marked.name) && - match SourceContract.fromAnnotations marked with - | .ok contract => - let changed : SourceContract := { contract with - binders := contract.binders.map fun binder => { binder with mode := .many } } - contract.binders.size == 2 && (contract.resolve marked).isOk && - !(changed.resolve marked).isOk - | .error _ => false) + | .error _ => false + | .error _ => false) + itBool "strict source metadata rejects unknown keys, duplicates, old versions, and overflowing codes" + ([data.setNat `ix.source.binder.future 0, duplicate, missingVersion, + data.setNat sourceAnnotationKey 3, data.setNat `ix.source.binder.mode 7, + data.setNat `ix.source.binder.mode 256, data.setNat `ix.source.binder.borrow 2].all fun malformed => + !(BinderAnnotation.ofMetadata? malformed).isOk) + itBool "malformed reserved metadata is still detected by the preflight" + (exprHasSourceAnnotations (.mdata missingVersion natType)) + itBool "source markers in raw recursor rules are detected and explicitly unsupported" + (sourceHasAnnotations recursor && + expectError (SourceContract.fromAnnotations recursor) (.annotatedRecursorRule recursor.name)) + itBool "annotation scan handles heavily shared ordinary source and nearby markers" + (!exprHasSourceAnnotations shared && + exprHasSourceAnnotations (.app shared (.mdata data natType))) + itBool "source markers require explicit matching records and cannot be overridden" + (expectError input.resolve (.missingContract marked.name) && + match SourceContract.fromAnnotations marked with + | .ok contract => + let changed : SourceContract := { contract with + binders := contract.binders.map fun binder => { binder with mode := .many } } + contract.binders.size == 2 && (contract.resolve marked).isOk && + !(changed.resolve marked).isOk + | .error _ => false) -def arityProducerTests : TestSeq := Id.run do +public def arityProducerTests : LSpec.Spec := do let canonical := fun source => (Id.run ((_root_.Ix.CanonM.canonConst source).run {})).1 let frame := fun (kind : _root_.Ix.SemanticContract.Kind) (e : _root_.Ix.Expr) => match e with | .mdata data _ _ => data.size == 3 && ((_root_.Ix.SemanticContract.read data).toOption).any (·.kind == kind) | _ => false let readable := fun e => (_root_.Ix.LeanIngress.ingressExpr (fun _ => 0) e).isOk - let once := resolveTelescope identity #[{ binder := .position 0, mode := .once, result := some .unique }] - let pair := once.toOption.bind (fun c => c.decorate.toOption) - let pairOK := pair.any fun out => match canonical out with - | .defnInfo v => frame .all v.cnst.type && frame .lam v.value && readable v.cnst.type && readable v.value - | _ => false - let binding := definition `arityLet natType (.letE `view natType (.lit (.natVal 0)) (.bvar 0) false) - let borrow : SourceContract := { - source := binding - binders := #[{ site := ⟨.body, []⟩, mode := .borrowed, isBorrow := true }] } - let letOK := ((borrow.resolve binding).toOption.bind (fun c => c.decorate.toOption)).any fun out => - match canonical out with | .defnInfo v => frame .letE v.value && readable v.value | _ => false - -- DefAsserts decoration & extraction - let assertsContract : SourceContract := { - source := identity - defAsserts := { alloc := .noAlloc, boundedStack := true } } - let assertsOK := ((assertsContract.resolve identity).toOption.bind (fun c => c.decorate.toOption)).any fun out => - match canonical out with - | .defnInfo v => - frame .defAsserts v.cnst.type && readable v.cnst.type && - _root_.Ix.SemanticContract.defAsserts .defn v.cnst.type == { alloc := .noAlloc, boundedStack := true } && - _root_.Ix.SemanticContract.defAsserts .thm v.cnst.type == {} - | _ => false - -- Constructor FieldMode decoration & extraction - let ctor : ConstantInfo := .ctorInfo { - name := `ArityBox.mk, levelParams := [] - type := .forallE `a natType (.forallE `b natType (.const `ArityBox []) .default) .default - induct := `ArityBox, cidx := 0, numParams := 0, numFields := 2, isUnsafe := false } - let ctorContract : SourceContract := { - source := ctor - fieldModes := #[{ fieldIndex := 1, mode := .shared }] } - let ctorOK := ((ctorContract.resolve ctor).toOption.bind (fun c => c.decorate.toOption)).any fun out => - match canonical out with - | .ctorInfo v => - readable v.cnst.type && - (_root_.Ix.SemanticContract.ctorFieldModes v.numParams v.numFields.toUInt64 v.cnst.type).toArray == - #[.inherited, .shared] - | _ => false - let thmId : ConstantInfo := .thmInfo { - name := `arityThmId, levelParams := [] - type := .forallE `p (.sort .zero) (.bvar 0) .default - value := .lam `p (.sort .zero) (.bvar 0) .default - all := [`arityThmId] } - let thmStripped := ((resolveTelescope thmId #[{ binder := .position 0, mode := .erased }]).toOption.bind - (fun c => c.decorate.toOption)).any fun out => - !exprHasSemanticContracts out.type && match out with - | .thmInfo v => !exprHasSemanticContracts v.value - | _ => false - let theoremSource : ConstantInfo := .thmInfo { - name := `arityTheorem, levelParams := [], type := .const `True [], value := .const `True.intro [], all := [`arityTheorem] } - let opaqueSource : ConstantInfo := .opaqueInfo { - name := `arityOpaque, levelParams := [], type := natType, value := .lit (.natVal 0), isUnsafe := false, all := [`arityOpaque] } - let axiomSource : ConstantInfo := .axiomInfo { - name := `arityAxiom, levelParams := [], type := natType, isUnsafe := false } - let kinds := [(theoremSource, 0), (opaqueSource, 1), (axiomSource, 2)].all fun (source, expected) => - ((resolveTelescope source #[]).toOption.bind (fun c => c.decorate.toOption)).any fun out => - out.name == source.name && match canonical out, expected with - | .thmInfo v, 0 => readable v.cnst.type && readable v.value - | .opaqueInfo v, 1 => readable v.cnst.type && readable v.value - | .axiomInfo v, 2 => readable v.cnst.type && (sourceBody? out).isNone - | _, _ => false - let body := (sourceBody? identity).getD natType - let plain := ({} : MData).setNat `native.hint 7 - let marker := ({ origin := 0, binder := `x, mode := .once } : BinderAnnotation).toMetadata - let semantic : _root_.Ix.SemanticContract.Contract := .lam .once - let metadata := (resolveTelescope identity #[]).toOption.any fun c => - let kept := (decorateExpr c .body [] (.mdata plain body)).toOption - let stripped := (decorateExpr c .body [] (.mdata marker body)).toOption - (match kept with | some (.mdata data inner) => data.entries == plain.entries && inner == body | _ => false) && - (match stripped with | some (.lam ..) => stripped == some body | _ => false) && - (match decorateExpr c .body [] (semantic.attach body) with - | .error "source transport: reserved semantic metadata in unprocessed source" => true | _ => false) - return test "actual decorator and CanonM keep distinct type/value semantic frames and ingress accepts valid modes" - (pairOK && thmStripped) ++ - test "actual borrow-let decoration has a three-field semantic frame accepted by the ingress" letOK ++ - test "DefAsserts and constructor FieldMode decoration roundtrip cleanly through CanonM and ingress" - (assertsOK && ctorOK) ++ - test "actual theorem/opaque/axiom outputs preserve kind and optional-value boundaries" kinds ++ - test "decorator preserves plain metadata, removes source markers and refuses original semantic frames" metadata + it "actual decorator and CanonM keep distinct type/value semantic frames and ingress accepts valid modes" do + let once := resolveTelescope identity #[{ binder := .position 0, mode := .once, result := some .unique }] + let pair := once.toOption.bind (fun c => c.decorate.toOption) + let pairOK := pair.any fun out => match canonical out with + | .defnInfo v => frame .all v.cnst.type && frame .lam v.value && readable v.cnst.type && readable v.value + | _ => false + let thmId : ConstantInfo := .thmInfo { + name := `arityThmId, levelParams := [] + type := .forallE `p (.sort .zero) (.bvar 0) .default + value := .lam `p (.sort .zero) (.bvar 0) .default + all := [`arityThmId] } + let thmStripped := ((resolveTelescope thmId #[{ binder := .position 0, mode := .erased }]).toOption.bind + (fun c => c.decorate.toOption)).any fun out => + !exprHasSemanticContracts out.type && match out with + | .thmInfo v => !exprHasSemanticContracts v.value + | _ => false + expect (pairOK && thmStripped) + it "actual borrow-let decoration has a three-field semantic frame accepted by the ingress" do + let binding := definition `arityLet natType (.letE `view natType (.lit (.natVal 0)) (.bvar 0) false) + let borrow : SourceContract := { + source := binding + binders := #[{ site := ⟨.body, []⟩, mode := .borrowed, isBorrow := true }] } + let letOK := ((borrow.resolve binding).toOption.bind (fun c => c.decorate.toOption)).any fun out => + match canonical out with | .defnInfo v => frame .letE v.value && readable v.value | _ => false + expect letOK + it "DefAsserts and constructor FieldMode decoration roundtrip cleanly through CanonM and ingress" do + let assertsContract : SourceContract := { + source := identity + defAsserts := { alloc := .noAlloc, boundedStack := true } } + let assertsOK := ((assertsContract.resolve identity).toOption.bind (fun c => c.decorate.toOption)).any fun out => + match canonical out with + | .defnInfo v => + frame .defAsserts v.cnst.type && readable v.cnst.type && + _root_.Ix.SemanticContract.defAsserts .defn v.cnst.type == { alloc := .noAlloc, boundedStack := true } && + _root_.Ix.SemanticContract.defAsserts .thm v.cnst.type == {} + | _ => false + let ctor : ConstantInfo := .ctorInfo { + name := `ArityBox.mk, levelParams := [] + type := .forallE `a natType (.forallE `b natType (.const `ArityBox []) .default) .default + induct := `ArityBox, cidx := 0, numParams := 0, numFields := 2, isUnsafe := false } + let ctorContract : SourceContract := { + source := ctor + fieldModes := #[{ fieldIndex := 1, mode := .shared }] } + let ctorOK := ((ctorContract.resolve ctor).toOption.bind (fun c => c.decorate.toOption)).any fun out => + match canonical out with + | .ctorInfo v => + readable v.cnst.type && + (_root_.Ix.SemanticContract.ctorFieldModes v.numParams v.numFields.toUInt64 v.cnst.type).toArray == + #[.inherited, .shared] + | _ => false + expect (assertsOK && ctorOK) + it "actual theorem/opaque/axiom outputs preserve kind and optional-value boundaries" do + let theoremSource : ConstantInfo := .thmInfo { + name := `arityTheorem, levelParams := [], type := .const `True [], value := .const `True.intro [], all := [`arityTheorem] } + let opaqueSource : ConstantInfo := .opaqueInfo { + name := `arityOpaque, levelParams := [], type := natType, value := .lit (.natVal 0), isUnsafe := false, all := [`arityOpaque] } + let axiomSource : ConstantInfo := .axiomInfo { + name := `arityAxiom, levelParams := [], type := natType, isUnsafe := false } + let kinds := [(theoremSource, 0), (opaqueSource, 1), (axiomSource, 2)].all fun (source, expected) => + ((resolveTelescope source #[]).toOption.bind (fun c => c.decorate.toOption)).any fun out => + out.name == source.name && match canonical out, expected with + | .thmInfo v, 0 => readable v.cnst.type && readable v.value + | .opaqueInfo v, 1 => readable v.cnst.type && readable v.value + | .axiomInfo v, 2 => readable v.cnst.type && (sourceBody? out).isNone + | _, _ => false + expect kinds + it "decorator preserves plain metadata, removes source markers and refuses original semantic frames" do + let body := (sourceBody? identity).getD natType + let plain := ({} : MData).setNat `native.hint 7 + let marker := ({ origin := 0, binder := `x, mode := .once } : BinderAnnotation).toMetadata + let semantic : _root_.Ix.SemanticContract.Contract := .lam .once + let metadata := (resolveTelescope identity #[]).toOption.any fun c => + let kept := (decorateExpr c .body [] (.mdata plain body)).toOption + let stripped := (decorateExpr c .body [] (.mdata marker body)).toOption + (match kept with | some (.mdata data inner) => data.entries == plain.entries && inner == body | _ => false) && + (match stripped with | some (.lam ..) => stripped == some body | _ => false) && + (match decorateExpr c .body [] (semantic.attach body) with + | .error "source transport: reserved semantic metadata in unprocessed source" => true | _ => false) + expect metadata -def inspectionTests : TestSeq := Id.run do +public def inspectionTests : LSpec.Spec := do let digest := fun (n : UInt8) => Address.mk (ByteArray.mk (Array.replicate 32 n)) let scalar := _root_.Ix.Expr.lit (.natVal 0) (digest 3) let lam := _root_.Ix.Expr.lam _root_.Ix.Name.mkAnon scalar @@ -414,44 +412,51 @@ def inspectionTests : TestSeq := Id.run do ("aliased metadata-key hash", data.set! 2 (unknown, .ofNat 1), "unknown or duplicate semantic contract field")] let inspect := _root_.Ix.SemanticContract.inspect let eq := _root_.Ix.Compile.ExactKey.exprEq - let mut tests := TestSeq.done for (label, md, message) in cases do - let bad := frame md - let refused := [bad, .app bad good (digest 1), .app good bad (digest 1)].all fun e => - match inspect e with | .error actual => actual == message | _ => false - tests := tests ++ test s!"exact inspection rejects {label} despite equal digests in either visitation order" - (bad.getHash == good.getHash && !eq bad good && refused) + itBool s!"exact inspection rejects {label} despite equal digests in either visitation order" + (let bad := frame md + let refused := [bad, .app bad good (digest 1), .app good bad (digest 1)].all fun e => + match inspect e with | .error actual => actual == message | _ => false + bad.getHash == good.getHash && !eq bad good && refused) let twin := _root_.Ix.Expr.mdata contract.ixMetadata (.lam _root_.Ix.Name.mkAnon scalar (.bvar 0 (digest 4)) .default (digest 2)) (digest 0) let plain := _root_.Ix.Expr.mdata #[(_root_.Ix.Name.fromLeanName `native.hint, .ofNat 7)] lam (digest 0) - return tests ++ test "exact inspection accepts plain, equal and shared valid nodes" + itBool "exact inspection accepts plain, equal and shared valid nodes" ((inspect scalar).toOption == some false && (inspect plain).toOption == some false && eq good twin && (inspect (.app good good (digest 1))).toOption == some true && (inspect (.app good twin (digest 1))).toOption == some true) -def presenceMemoTests : TestSeq := Id.run do +public def presenceMemoTests : LSpec.Spec := do let plain := Expr.lit (.natVal 0) let binder := Expr.lam `x natType (.bvar 0) .default let contract : _root_.Ix.SemanticContract.Contract := .lam .once let marked := contract.attach binder let hinted := Expr.mdata (({} : MData).setNat `native.hint 7) binder let bucket := fun (_ : Expr) => (0 : USize) - let mut memo : SemanticPresence.Memo := {} - let mut valid := true - for e in [plain, marked, hinted, plain, marked, marked] do - let (result, after) := Id.run ((SemanticPresence.go bucket e).run memo) - valid := valid && result.1 == SemanticPresence.spec e - memo := after - let seeded : SemanticPresence.Memo := ({} : SemanticPresence.Memo).insert 0 - ⟨plain, SemanticPresence.spec plain, rfl⟩ - return test "presence memo preserves real results through constant-bucket collisions, overwrites and warm hits" valid ++ - test "presence memo confirms retained source and computes both positive and negative answers" - ((SemanticPresence.probe seeded 0 marked).isNone && - SemanticPresence.runWith bucket marked && !SemanticPresence.runWith bucket hinted) + it "presence memo preserves real results through constant-bucket collisions, overwrites and warm hits" do + let mut memo : SemanticPresence.Memo := {} + let mut valid := true + for e in [plain, marked, hinted, plain, marked, marked] do + let (result, after) := Id.run ((SemanticPresence.go bucket e).run memo) + valid := valid && result.1 == SemanticPresence.spec e + memo := after + expect valid + itBool "presence memo confirms retained source and computes both positive and negative answers" + (let seeded : SemanticPresence.Memo := ({} : SemanticPresence.Memo).insert 0 + ⟨plain, SemanticPresence.spec plain, rfl⟩ + (SemanticPresence.probe seeded 0 marked).isNone && + SemanticPresence.runWith bucket marked && !SemanticPresence.runWith bucket hinted) -def suite : List TestSeq := - [telescopeTests, occurrenceTests, rejectionTests, inputTests, modeBijectionTests, markerTests, - arityProducerTests, inspectionTests, presenceMemoTests] +public def suite : LSpec.Spec := do + telescopeTests + occurrenceTests + rejectionTests + inputTests + modeBijectionTests + markerTests + arityProducerTests + inspectionTests + presenceMemoTests end Tests.Ix.SourceContract diff --git a/Tests/Ix/SourceContract/Driver.lean b/Tests/Ix/SourceContract/Driver.lean index 7bca53d07a..6ca8a4751a 100644 --- a/Tests/Ix/SourceContract/Driver.lean +++ b/Tests/Ix/SourceContract/Driver.lean @@ -30,20 +30,21 @@ private def markedSource : ConstantInfo := .axiomInfo { private def constants (source : ConstantInfo) := [(source.name, source)] -private def ioTest (description : String) (check : IO Bool) : TestSeq := - .individualIO description none (do return (← check, 0, 0, none)) .done +private def ioTest (description : String) (check : IO Bool) : Spec := + it description do + expect (← check) /-- An IO test that reports what the compile said when mode checking did not refuse an annotated constant with no run body. -/ private def refusalTest (description : String) (result : IO (Except String Ix.CompileM.CertifiedOut)) : - TestSeq := - .individualIO description none (do + Spec := + it description do match ← result with - | .ok _ => return (false, 0, 0, some "compiled") + | .ok _ => fail "compiled" | .error message => let ok := (message.splitOn "not in the extern set").length > 1 || (message.splitOn "annotated source is refused").length > 1 - return (ok, 0, 0, if ok then none else some message)) .done + expect ok message private def compileConsts (consts : List (Lean.Name × ConstantInfo)) : IO (Except String Ix.CompileM.CertifiedOut) := do @@ -91,8 +92,8 @@ private def placement : IO Bool := do unless ok do throw (IO.userError s!"semantic placement: {label}") return true -def suite : List TestSeq := [ - ioTest "prepared semantic lambda: source presence, binder inspection and malformed-frame refusal" placement, +public def suite : LSpec.Spec := do + ioTest "prepared semantic lambda: source presence, binder inspection and malformed-frame refusal" placement ioTest "ordinary source preflight preserves declarations and validates names" do let env ← Lean.mkEmptyEnvironment let sources := constants plainSource @@ -100,7 +101,7 @@ def suite : List TestSeq := [ if (prepare sources).toOption != some sources then return false if (prepare (sources ++ sources)).toOption.isSome then return false if (prepare [(`wrongName, plainSource)]).toOption.isSome then return false - return true, + return true ioTest "ordinary source preflight cannot bypass reserved semantic metadata" do let env ← Lean.mkEmptyEnvironment let source : ConstantInfo := .axiomInfo { @@ -111,7 +112,7 @@ def suite : List TestSeq := [ if (prepare (constants source)).toOption.isSome then return false let .ok marked := prepare (constants markedSource) | return false if marked == constants markedSource then return false - return true, + return true ioTest "parallel source preflight checks every batch and its final remainder" do let sources := (List.range 2049).map fun i => let name := Lean.Name.num plainSource.name i @@ -128,28 +129,28 @@ def suite : List TestSeq := [ isUnsafe := false } (name, source) if (checkOrdinaryConstants marked (fun _ => false)).toOption != some false then return false - return true, + return true refusalTest "Lean constant-list driver refuses an annotated axiom" - (compileConsts (constants markedSource)), + (compileConsts (constants markedSource)) ioTest "explicit Lean input rejects a missing annotation registry" do match ← compileInput (.plain (constants markedSource)) with | .error message => return (message.splitOn "missingContract").length > 1 - | .ok _ => return false, + | .ok _ => return false refusalTest "explicit Lean input refuses an annotated axiom" (do let .ok contract := SourceContract.ofTelescope plainSource #[ { binder := .position 0, mode := .once }] | return .error "the telescope contract does not resolve" - compileInput { constants := constants plainSource, contracts := #[contract] }), + compileInput { constants := constants plainSource, contracts := #[contract] }) ioTest "measure-only input preserves ordinary production bytes" do let input := CompileInput.plain (constants plainSource) let .ok plain ← compileInput input | return false let hinted := { input with measureHints := #[⟨plainSource, .position 0, some 1⟩] } let .ok measured ← compileInput hinted | return false - return (Ixon.serEnv plain.env).toOption == (Ixon.serEnv measured.env).toOption, + return (Ixon.serEnv plain.env).toOption == (Ixon.serEnv measured.env).toOption ioTest "prepared-source preflight rejects unresolved source binder contracts" do match checkPreparedSource (constants markedSource) with | .error message => return (message.splitOn "unresolved source binder contracts").length > 1 - | .ok _ => return false, + | .ok _ => return false ioTest "explicit Lean input compiles and mode-checks a valid annotated definition with DefAsserts" do let tyA : ConstantInfo := .axiomInfo { name := `SourceContractDriver.TyA, levelParams := [], type := .sort (.succ .zero), isUnsafe := false } @@ -169,7 +170,6 @@ def suite : List TestSeq := [ | .defn d => d.asserts == { alloc := .noAlloc, boundedStack := true } | _ => false return out.annotated && assertsOk && _root_.Ix.Compile.BinderData.hasModes c -] end Tests.Ix.SourceContract.Driver diff --git a/Tests/Ix/SourceContract/Imported.lean b/Tests/Ix/SourceContract/Imported.lean index 4dc5af853b..074926c6aa 100644 --- a/Tests/Ix/SourceContract/Imported.lean +++ b/Tests/Ix/SourceContract/Imported.lean @@ -20,8 +20,8 @@ opaque opaqueIdentity (x : Nat) : Nat := x @[no_alloc, bounded_stack] def importedAsserts (x : Nat) : Nat := x + 1 structure ImportedShared where - @shared label : Nat - @erased proof : True + @[shared] label : Nat + @[erased] proof : True body : Nat open Lean Ix.Compile in diff --git a/Tests/Ix/SourceContract/SyntaxCheck.lean b/Tests/Ix/SourceContract/SyntaxCheck.lean index 229ad23c61..cf3fada6de 100644 --- a/Tests/Ix/SourceContract/SyntaxCheck.lean +++ b/Tests/Ix/SourceContract/SyntaxCheck.lean @@ -35,7 +35,7 @@ section ScopedInactive run_cmd do -- Without `open scoped Ix.Modes`, mode-annotated `def` must NOT parse as SourceSyntax.declaration. - if (Parser.runParserCategory (← getEnv) `command "def inactiveUnique (@unique x : Nat) : Nat := x").isOk then + if (Parser.runParserCategory (← getEnv) `command "def inactiveUnique (@[unique] x : Nat) : Nat := x").isOk then throwError "mode-annotated def parsed without `open scoped Ix.Modes`" end ScopedInactive @@ -67,6 +67,7 @@ run_cmd do ``Tests.Ix.SourceContract.SyntaxFixture.onceBorrowedRev, ``Tests.Ix.SourceContract.SyntaxFixture.multiName, ``Tests.Ix.SourceContract.SyntaxFixture.multiNameResult, + ``Tests.Ix.SourceContract.SyntaxFixture.whitespaceMultiline, ``Tests.Ix.SourceContract.SyntaxFixture.localResult, ``Tests.Ix.SourceContract.SyntaxFixture.uniqueResult, ``Tests.Ix.SourceContract.SyntaxFixture.localUniqueResult, @@ -216,16 +217,23 @@ run_cmd do let axU ← getContract ``Tests.Ix.SourceContract.SyntaxFixture.axiomUnique unless axU.modeAt ⟨.type, []⟩ == .unique && axU.resultAt ⟨.type, []⟩ == .unique do throwError "axiom mode annotation failed" + let wsMulti ← getContract ``Tests.Ix.SourceContract.SyntaxFixture.whitespaceMultiline + unless wsMulti.modeAt ⟨.type, []⟩ == .uniqueBorrowed && + wsMulti.modeAt ⟨.type, [.binderBody]⟩ == .uniqueBorrowed && + wsMulti.modeAt ⟨.type, [.binderBody, .binderBody]⟩ == .erased && + wsMulti.modeAt ⟨.type, [.binderBody, .binderBody, .binderBody]⟩ == .borrowed && + wsMulti.resultAt ⟨.type, [.binderBody, .binderBody, .binderBody]⟩ == .uniqueBorrowed do + throwError "whitespace/multiline @[...] mode annotations failed" let prec ← getContract ``Tests.Ix.SourceContract.SyntaxFixture.arrowPrecedence unless prec.resultAt ⟨.type, []⟩ == .unique && prec.resultAt ⟨.type, [.binderBody]⟩ == .shared do - throwError "A → @unique B → C precedence was wrong" + throwError "A → @[unique] B → C precedence was wrong" let chain ← getContract ``Tests.Ix.SourceContract.SyntaxFixture.arrowChain unless chain.modeAt ⟨.type, []⟩ == .borrowed && chain.resultAt ⟨.type, []⟩ == .unique && chain.modeAt ⟨.type, [.binderBody]⟩ == .many && chain.resultAt ⟨.type, [.binderBody]⟩ == .borrowed do - throwError "(@borrowed x : Nat) → @unique Nat → @borrowed Nat failed" + throwError "(@[borrowed] x : Nat) → @[unique] Nat → @[borrowed] Nat failed" for name in #[``Tests.Ix.SourceContract.SyntaxFixture.dependentArrow, ``Tests.Ix.SourceContract.SyntaxFixture.quantified] do let c ← getContract name @@ -246,17 +254,17 @@ run_cmd do throwError "nested lambda annotation was lost on {name}" let lamNoTy ← getContract ``Tests.Ix.SourceContract.SyntaxFixture.lambdaNoType unless lamNoTy.binders.any (fun b => b.kind == .lam && b.mode == .unique) do - throwError "fun (@unique x) without `: T` failed" + throwError "fun (@[unique] x) without `: T` failed" let lamMulti ← getContract ``Tests.Ix.SourceContract.SyntaxFixture.lambdaMultiNoType unless lamMulti.modeAt ⟨.body, []⟩ == .unique && lamMulti.modeAt ⟨.body, [.binderBody]⟩ == .unique do - throwError "fun (@unique x y) without `: T` failed" + throwError "fun (@[unique] x y) without `: T` failed" let lamLeak ← getContract ``Tests.Ix.SourceContract.SyntaxFixture.lambdaZeroLeak unless lamLeak.binders.size == 2 && lamLeak.modeAt ⟨.type, []⟩ == .unique && lamLeak.modeAt ⟨.body, []⟩ == .unique && !lamLeak.binders.any (·.kind == .letE) do - throwError "fun (@unique x) leaked annotation onto inner plain let" + throwError "fun (@[unique] x) leaked annotation onto inner plain let" -- `let` and `do`-block `let` (all 8 modes, with and without `: T`) let localLet ← getContract ``Tests.Ix.SourceContract.SyntaxFixture.localLet @@ -265,7 +273,7 @@ run_cmd do let localLetNoTy ← getContract ``Tests.Ix.SourceContract.SyntaxFixture.localLetNoType unless localLetNoTy.binders.size == 1 && localLetNoTy.binders[0]!.kind == .letE && localLetNoTy.binders[0]!.mode == .unique do - throwError "untyped let @unique leaked onto inner plain let" + throwError "untyped let @[unique] leaked onto inner plain let" let allLet ← getContract ``Tests.Ix.SourceContract.SyntaxFixture.letAllModes for expected in [Ixon.BinderMode.borrowed, .unique, .uniqueBorrowed, .once, .onceBorrowed, .erased] do unless allLet.binders.any (fun b => b.kind == .letE && !b.isBorrow && b.mode == expected) do @@ -276,15 +284,15 @@ run_cmd do ``Tests.Ix.SourceContract.SyntaxFixture.doBlockBorrowEscape] do let loan ← getContract name unless loan.binders.any (fun b => b.kind == .letE && b.isBorrow && b.mode == .borrowed) do - throwError "let @borrow failed on {name}" + throwError "let @[borrow] failed on {name}" let doAll ← getContract ``Tests.Ix.SourceContract.SyntaxFixture.doBlockAllModes for expected in [Ixon.BinderMode.borrowed, .unique, .uniqueBorrowed, .once, .onceBorrowed, .erased] do unless doAll.binders.any (fun b => b.kind == .letE && !b.isBorrow && b.mode == expected) do throwError "doBlockAllModes missing value let mode {repr expected}" unless doAll.binders.any (fun b => b.kind == .letE && b.isBorrow && b.mode == .borrowed) do - throwError "doBlockAllModes missing @borrow" + throwError "doBlockAllModes missing @[borrow]" - -- Structure & inductive fields (`@shared`, `@erased`) + -- Structure & inductive fields (`@[shared]`, `@[erased]`) let sb ← getContract ``Tests.Ix.SourceContract.SyntaxFixture.SharedBox.mk unless sb.fieldModeAt 0 == .shared && sb.fieldModeAt 1 == .inherited && sb.fieldModeAt 2 == .inherited && sb.modeAt ⟨.type, [.binderBody, .binderBody]⟩ == .erased do @@ -296,22 +304,22 @@ run_cmd do unless sd.fieldModeAt 0 == .shared && sd.fieldModeAt 1 == .shared && sd.fieldModeAt 2 == .shared do throwError "SharedDefault.mk field modes wrong: {repr sd.fieldModes}" let es ← getContract ``Tests.Ix.SourceContract.SyntaxFixture.ExtShared.mk - -- field 0 is toBasePair, field 1 is tag (@shared), field 2 is witness (@erased) + -- field 0 is toBasePair, field 1 is tag (@[shared]), field 2 is witness (@[erased]) unless es.fieldModeAt 0 == .inherited && es.fieldModeAt 1 == .shared && es.modeAt ⟨.type, [.binderBody, .binderBody]⟩ == .erased do throwError "ExtShared.mk field modes wrong: {repr es.fieldModes} / {repr es.binders}" let ml ← getContract ``Tests.Ix.SourceContract.SyntaxFixture.ModeList.cons - -- param 0 is α, field 0 is head (@shared), field 1 is proof (@erased), field 2 is tail + -- param 0 is α, field 0 is head (@[shared]), field 1 is proof (@[erased]), field 2 is tail unless ml.fieldModeAt 0 == .shared && ml.fieldModeAt 1 == .inherited && ml.modeAt ⟨.type, [.binderBody, .binderBody]⟩ == .erased do throwError "ModeList.cons field modes wrong: {repr ml.fieldModes} / {repr ml.binders}" let mt ← getContract ``Tests.Ix.SourceContract.SyntaxFixture.ModeTree.node - -- param 0 is α, field 0 is label (@shared), field 1 is proof (@erased) + -- param 0 is α, field 0 is label (@[shared]), field 1 is proof (@[erased]) unless mt.fieldModeAt 0 == .shared && mt.fieldModeAt 1 == .inherited && mt.modeAt ⟨.type, [.binderBody, .binderBody]⟩ == .erased do throwError "ModeTree.node field modes wrong: {repr mt.fieldModes} / {repr mt.binders}" let ai ← getContract ``Tests.Ix.SourceContract.SyntaxFixture.ArrowInd.mk - -- field 0 is Nat, field 1 is x (@shared), field 2 is h (@erased) + -- field 0 is Nat, field 1 is x (@[shared]), field 2 is h (@[erased]) unless ai.fieldModeAt 0 == .inherited && ai.fieldModeAt 1 == .shared && ai.modeAt ⟨.type, [.binderBody, .binderBody]⟩ == .erased do throwError "ArrowInd.mk field modes wrong: {repr ai.fieldModes} / {repr ai.binders}" @@ -370,105 +378,110 @@ run_cmd do section NegativeTests open scoped Ix.Modes --- Verify space after `@` is rejected +-- Verify retired syntax, mid-group annotations, and space between `@` and `[` are rejected run_cmd do for text in [ "def bad (@ unique x : Nat) : Nat := x", - "def bad (@ borrowed x : Nat) : Nat := x", + "def bad (@ [unique] x : Nat) : Nat := x", + "def bad (@unique x : Nat) : Nat := x", + "def bad (@borrowed x : Nat) : Nat := x", + "def bad (a @[unique] b : Nat) : Nat := a + b", "def bad (! x : Nat) : Nat := x", - "def bad (~1 x : Nat) : Nat := x"] do + "def bad (~1 x : Nat) : Nat := x", + "def bad (0 x : Nat) : Nat := 0", + "def bad (& x : Nat) : Nat := x"] do if (Parser.runParserCategory (← getEnv) `command text).isOk then throwError "invalid binder spelling was accepted: {text}" -/-- error: @erased cannot be combined with other mode annotations -/ +/-- error: @[erased] cannot be combined with other mode annotations -/ #guard_msgs in -def badErasedUnique (@erased @unique x : Nat) : Nat := x +def badErasedUnique (@[erased, unique] x : Nat) : Nat := x -/-- error: @erased cannot be combined with other mode annotations -/ +/-- error: @[erased] cannot be combined with other mode annotations -/ #guard_msgs in -def badUniqueErased (@unique @erased x : Nat) : Nat := x +def badUniqueErased (@[unique] @[erased] x : Nat) : Nat := x -/-- error: @erased cannot be combined with other mode annotations -/ +/-- error: @[erased] cannot be combined with other mode annotations -/ #guard_msgs in -def badErasedBorrowed (@erased @borrowed x : Nat) : Nat := x +def badErasedBorrowed (@[erased, borrowed] x : Nat) : Nat := x -/-- error: @erased cannot be combined with other mode annotations -/ +/-- error: @[erased] cannot be combined with other mode annotations -/ #guard_msgs in -def badErasedOnce (@erased @once x : Nat) : Nat := x +def badErasedOnce (@[erased, once] x : Nat) : Nat := x -/-- error: @once cannot be combined with @unique -/ +/-- error: @[once] cannot be combined with @[unique] -/ #guard_msgs in -def badOnceUnique (@once @unique x : Nat) : Nat := x +def badOnceUnique (@[once, unique] x : Nat) : Nat := x -/-- error: @once cannot be combined with @unique -/ +/-- error: @[once] cannot be combined with @[unique] -/ #guard_msgs in -def badUniqueOnce (@unique @once x : Nat) : Nat := x +def badUniqueOnce (@[unique] @[once] x : Nat) : Nat := x -/-- error: duplicate @unique mode annotation -/ +/-- error: duplicate @[unique] mode annotation -/ #guard_msgs in -def badDupUnique (@unique @unique x : Nat) : Nat := x +def badDupUnique (@[unique, unique] x : Nat) : Nat := x -/-- error: duplicate @borrowed mode annotation -/ +/-- error: duplicate @[borrowed] mode annotation -/ #guard_msgs in -def badDupBorrowed (@borrowed @borrowed x : Nat) : Nat := x +def badDupBorrowed (@[borrowed] @[borrowed] x : Nat) : Nat := x -/-- error: duplicate @once mode annotation -/ +/-- error: duplicate @[once] mode annotation -/ #guard_msgs in -def badDupOnce (@once @once x : Nat) : Nat := x +def badDupOnce (@[once, once] x : Nat) : Nat := x -/-- error: duplicate @erased mode annotation -/ +/-- error: duplicate @[erased] mode annotation -/ #guard_msgs in -def badDupErased (@erased @erased x : Nat) : Nat := x +def badDupErased (@[erased, erased] x : Nat) : Nat := x -/-- error: @erased is not a valid result mode; result modes allow only @unique and @borrowed -/ +/-- error: @[erased] is not a valid result mode; result modes allow only @[unique] and @[borrowed] -/ #guard_msgs in -def badErasedResult (x : Nat) : @erased Nat := x +def badErasedResult (x : Nat) : @[erased] Nat := x -/-- error: @once is not a valid result mode; result modes allow only @unique and @borrowed -/ +/-- error: @[once] is not a valid result mode; result modes allow only @[unique] and @[borrowed] -/ #guard_msgs in -example : Nat → @once Nat := fun x => x +example : Nat → @[once] Nat := fun x => x -/-- error: duplicate @unique mode annotation -/ +/-- error: duplicate @[unique] mode annotation -/ #guard_msgs in -def badDupResult (x : Nat) : @unique @unique Nat := x +def badDupResult (x : Nat) : @[unique, unique] Nat := x -/-- error: @borrow cannot be combined with other mode annotations -/ +/-- error: @[borrow] cannot be combined with other mode annotations -/ #guard_msgs in example (owner : Nat) : Nat := - let @borrow @unique view := owner + let @[borrow, unique] view := owner view -/-- error: @borrow cannot be combined with other mode annotations -/ +/-- error: @[borrow] cannot be combined with other mode annotations -/ #guard_msgs in example (owner : Nat) : Nat := - let @borrow @borrowed view := owner + let @[borrow] @[borrowed] view := owner view -/-- error: duplicate @borrow mode annotation -/ +/-- error: duplicate @[borrow] mode annotation -/ #guard_msgs in example (owner : Nat) : Nat := - let @borrow @borrow view := owner + let @[borrow, borrow] view := owner view -/-- error: @erased cannot be combined with @shared on a field -/ +/-- error: @[erased] cannot be combined with @[shared] on a field -/ #guard_msgs in structure BadStructBoth where - @shared @erased x : Nat + @[shared, erased] x : Nat -/-- error: duplicate @shared mode annotation -/ +/-- error: duplicate @[shared] mode annotation -/ #guard_msgs in structure BadStructDup where - @shared @shared x : Nat + @[shared, shared] x : Nat -/-- error: @unique is not a valid field mode; structure and inductive fields only allow @shared or @erased -/ +/-- error: @[unique] is not a valid field mode; structure and inductive fields only allow @[shared] or @[erased] -/ #guard_msgs in structure BadStructUnique where - @unique x : Nat + @[unique] x : Nat -/-- error: @erased cannot be combined with @shared on a field -/ +/-- error: @[erased] cannot be combined with @[shared] on a field -/ #guard_msgs in inductive BadIndBoth where - | mk (@shared @erased x : Nat) + | mk (@[shared, erased] x : Nat) /-- error: definition assertions (@[no_rc], @[no_alloc], @[bounded_stack]) are not allowed on theorems -/ #guard_msgs in diff --git a/Tests/Ix/SourceContract/SyntaxFixture.lean b/Tests/Ix/SourceContract/SyntaxFixture.lean index 1a5201c4ba..47c23caeee 100644 --- a/Tests/Ix/SourceContract/SyntaxFixture.lean +++ b/Tests/Ix/SourceContract/SyntaxFixture.lean @@ -11,175 +11,198 @@ open scoped Ix.Modes /-! ### Binder modes (all 7, composable, order-insensitive, all 4 bracket kinds) -/ -def linear (@once x : Nat) : Nat := x -def unique (@unique x : Nat) : Nat := x -def uniqueAffine (@unique x : Nat) : Nat := x -def erased (@erased _x : Nat) : Nat := 7 -def inferred (@once x : Nat) := x - -def dependent {@erased α : Type} (@once x : α) : α := x -def inferredImplicit (@once x : α) : α := x -def withInstance {@erased α : Type} [@once inst : Inhabited α] : α := default -def withAnonInstance {@erased α : Type} [@borrowed Inhabited α] : α := default -def strictImplicit ⦃@erased α : Type⦄ (@once x : α) : α := x -def shadowed (@once _x : Nat) (@borrowed _x : Nat) : Nat := _x -def anonBinder (@erased _ : Nat) : Nat := 9 - -def nativeBorrow (@unique @borrowed x : @& Nat) : Nat := x -def nativeBorrowRev (@borrowed @unique x : @& Nat) : Nat := x - -def twoLocal (@unique @borrowed x : Nat) (@once @borrowed y : Nat) : Nat := x + y -def twoLocalRev (@borrowed @unique x : Nat) (@borrowed @once y : Nat) : Nat := x + y - -def renamedLocal (@unique @borrowed value : Nat) : Nat := value -def renamedTwoLocal (@unique @borrowed first : Nat) (@once @borrowed second : Nat) : Nat := first + second - -def localShared (@borrowed x : Nat) : Nat := x -def localUnique (@unique @borrowed x : Nat) : Nat := x -def onceBorrowed (@once @borrowed x : Nat) : Nat := x -def onceBorrowedRev (@borrowed @once x : Nat) : Nat := x - -def multiName (@unique x y : Nat) : Nat := x + y -def multiNameResult (@unique x y : Nat) : @unique Nat := x + y - -@[inline] private def privateIdentity (@unique x : Nat) : Nat := x +def linear (@[once] x : Nat) : Nat := x +def unique (@[unique] x : Nat) : Nat := x +def uniqueAffine (@[unique] x : Nat) : Nat := x +def erased (@[erased] _x : Nat) : Nat := 7 +def inferred (@[once] x : Nat) := x + +def dependent {@[erased] α : Type} (@[once] x : α) : α := x +def inferredImplicit (@[once] x : α) : α := x +def withInstance {@[erased] α : Type} [@[once] inst : Inhabited α] : α := default +def withAnonInstance {@[erased] α : Type} [@[borrowed] Inhabited α] : α := default +def strictImplicit ⦃@[erased] α : Type⦄ (@[once] x : α) : α := x +def shadowed (@[once] _x : Nat) (@[borrowed] _x : Nat) : Nat := _x +def anonBinder (@[erased] _ : Nat) : Nat := 9 + +def nativeBorrow (@[unique, borrowed] x : @& Nat) : Nat := x +def nativeBorrowRev (@[borrowed, unique] x : @& Nat) : Nat := x + +def twoLocal (@[unique, borrowed] x : Nat) (@[once, borrowed] y : Nat) : Nat := x + y +def twoLocalRev (@[borrowed] @[unique] x : Nat) (@[borrowed] @[once] y : Nat) : Nat := x + y + +def renamedLocal (@[unique, borrowed] value : Nat) : Nat := value +def renamedTwoLocal (@[unique, borrowed] first : Nat) (@[once, borrowed] second : Nat) : Nat := first + second + +def localShared (@[borrowed] x : Nat) : Nat := x +def localUnique (@[unique, borrowed] x : Nat) : Nat := x +def onceBorrowed (@[once, borrowed] x : Nat) : Nat := x +def onceBorrowedRev (@[borrowed, once] x : Nat) : Nat := x + +def multiName (@[unique] x y : Nat) : Nat := x + y +def multiNameResult (@[unique] x y : Nat) : @[unique] Nat := x + y + +def whitespaceMultiline + ( + @[ unique , borrowed ] + a b : Nat + ) + { + @[erased] + α : Type + } + [ + @[borrowed] + Inhabited α + ] : + @[ + unique, + borrowed + ] + Nat := + let + @[borrow] + v := a + v + b + +@[inline] private def privateIdentity (@[unique] x : Nat) : Nat := x /-! ### Result modes (4) on `def`, `abbrev`, `opaque`, `axiom`, `→`, `∀` -/ -def localResult (@borrowed x : Nat) : @borrowed Nat := x -def uniqueResult (@unique x : Nat) : @unique Nat := x -def localUniqueResult (@unique @borrowed x : Nat) : @unique @borrowed Nat := x -def localUniqueResultRev (@borrowed @unique x : Nat) : @borrowed @unique Nat := x -def curriedResult (x y : Nat) : @borrowed Nat := x + y +def localResult (@[borrowed] x : Nat) : @[borrowed] Nat := x +def uniqueResult (@[unique] x : Nat) : @[unique] Nat := x +def localUniqueResult (@[unique, borrowed] x : Nat) : @[unique, borrowed] Nat := x +def localUniqueResultRev (@[borrowed] @[unique] x : Nat) : @[borrowed] @[unique] Nat := x +def curriedResult (x y : Nat) : @[borrowed] Nat := x + y -abbrev abbrevUnique (@unique x : Nat) : @unique Nat := x -opaque opaqueBorrowed (@borrowed x : Nat) : @borrowed Nat := x -axiom axiomUnique (@unique _x : Nat) : @unique Nat +abbrev abbrevUnique (@[unique] x : Nat) : @[unique] Nat := x +opaque opaqueBorrowed (@[borrowed] x : Nat) : @[borrowed] Nat := x +axiom axiomUnique (@[unique] _x : Nat) : @[unique] Nat -def dependentArrow : (@borrowed _x : Nat) → @borrowed Nat := fun x => x -def anonymousArrow : Nat → @unique @borrowed Nat := fun x => x -def arrowPrecedence : Nat → @unique Nat → Nat := fun x y => x + y -def arrowChain : (@borrowed _x : Nat) → @unique Nat → @borrowed Nat := fun x y => x + y -def quantified : ∀ (@borrowed _x : Nat), @borrowed Nat := fun x => x +def dependentArrow : (@[borrowed] _x : Nat) → @[borrowed] Nat := fun x => x +def anonymousArrow : Nat → @[unique, borrowed] Nat := fun x => x +def arrowPrecedence : Nat → @[unique] Nat → Nat := fun x y => x + y +def arrowChain : (@[borrowed] _x : Nat) → @[unique] Nat → @[borrowed] Nat := fun x y => x + y +def quantified : ∀ (@[borrowed] _x : Nat), @[borrowed] Nat := fun x => x /-! ### Lambdas (with and without `: T`, multi-name) -/ -def nestedLambda (x : Nat) : Nat := (fun (@once @borrowed y : Nat) => y) x -def lambdaDefinition := fun (@once @borrowed x : Nat) => x -def lambdaNoType : (@unique _ : Nat) → Nat := fun (@unique x) => x + 1 -def lambdaMultiNoType : (@unique _ : Nat) → (@unique _ : Nat) → Nat := fun (@unique x y) => x + y -def lambdaZeroLeak : (@unique _ : Nat) → Nat := fun (@unique x) => +def nestedLambda (x : Nat) : Nat := (fun (@[once, borrowed] y : Nat) => y) x +def lambdaDefinition := fun (@[once, borrowed] x : Nat) => x +def lambdaNoType : (@[unique] _ : Nat) → Nat := fun (@[unique] x) => x + 1 +def lambdaMultiNoType : (@[unique] _ : Nat) → (@[unique] _ : Nat) → Nat := fun (@[unique] x y) => x + y +def lambdaZeroLeak : (@[unique] _ : Nat) → Nat := fun (@[unique] x) => let y := x y /-! ### `let` and `do`-block `let` (all 8 modes, unparenthesized, optional `: T`) -/ def localLet (x : Nat) : Nat := - let @unique @borrowed y : Nat := x + let @[unique, borrowed] y : Nat := x y def localLetNoType (x : Nat) : Nat := - let @unique y := x + let @[unique] y := x let w := y w def letAllModes (owner : Nat) : Nat := - let @borrowed a := owner - let @unique b := a - let @unique @borrowed c := b - let @once f := c - let @once @borrowed g := f - let @erased _h := True.intro + let @[borrowed] a := owner + let @[unique] b := a + let @[unique, borrowed] c := b + let @[once] f := c + let @[once, borrowed] g := f + let @[erased] _h := True.intro g -def sharedLoan (@unique owner : Nat) : Nat := - let @borrow view : Nat := owner +def sharedLoan (@[unique] owner : Nat) : Nat := + let @[borrow] view : Nat := owner view -def sharedLoanNoType (@unique owner : Nat) : Nat := - let @borrow view := owner +def sharedLoanNoType (@[unique] owner : Nat) : Nat := + let @[borrow] view := owner view -def doBlockBorrow (@unique owner : Nat) : Id Nat := do - let @borrow v := owner +def doBlockBorrow (@[unique] owner : Nat) : Id Nat := do + let @[borrow] v := owner let w := v - let @unique u : Nat := w + 1 + let @[unique] u : Nat := w + 1 return u -def doBlockBorrowEscape (@unique owner : Nat) : Id Nat := do - let @borrow v := owner +def doBlockBorrowEscape (@[unique] owner : Nat) : Id Nat := do + let @[borrow] v := owner return v structure SyntaxBox where a : Nat b : Nat -def doBlockBorrowEscapeBox (@unique owner : SyntaxBox) : Id SyntaxBox := do - let @borrow v := owner +def doBlockBorrowEscapeBox (@[unique] owner : SyntaxBox) : Id SyntaxBox := do + let @[borrow] v := owner return v def doBlockAllModes (owner : Nat) : Id Nat := do - let @borrowed a := owner - let @unique b := a - let @borrowed @unique c := b - let @once d := c - let @borrowed @once e := d - let @erased _h : True := trivial - let @borrow v := e + let @[borrowed] a := owner + let @[unique] b := a + let @[borrowed, unique] c := b + let @[once] d := c + let @[borrowed] @[once] e := d + let @[erased] _h : True := trivial + let @[borrow] v := e return v -/-! ### Structure & inductive fields (`@shared`, `@erased`, unmarked) -/ +/-! ### Structure & inductive fields (`@[shared]`, `@[erased]`, unmarked) -/ structure SharedBox (α : Type) where - @shared item : α - @erased inv : True + @[shared] item : α + @[erased] inv : True payload : Nat structure SharedOnly where - @shared label : Nat + @[shared] label : Nat structure SharedDefault where - @shared count : Nat := 0 - (@shared a b : Nat) + @[shared] count : Nat := 0 + (@[shared] a b : Nat) structure BasePair where first : Nat structure ExtShared extends BasePair where - @shared tag : Nat - @erased witness : True + @[shared] tag : Nat + @[erased] witness : True set_option linter.unusedVariables false in inductive ModeList (α : Type) where | nil - | cons (@shared head : α) (@erased proof : True) (tail : ModeList α) + | cons (@[shared] head : α) (@[erased] proof : True) (tail : ModeList α) set_option linter.unusedVariables false in inductive ModeTree (α : Type) where | leaf - | node (@shared label : α) (@erased proof : True) (left right : ModeTree α) + | node (@[shared] label : α) (@[erased] proof : True) (left right : ModeTree α) set_option linter.unusedVariables false in inductive ArrowInd where - | mk : Nat → (@shared x : Nat) → (@erased h : True) → ArrowInd + | mk : Nat → (@[shared] x : Nat) → (@[erased] h : True) → ArrowInd structure SharedPair (α : Type) where - @shared item : α + @[shared] item : α payload : Nat set_option linter.unusedVariables false in inductive SharedList (α : Type) where | nil - | cons (@shared head : α) (tail : SharedList α) + | cons (@[shared] head : α) (tail : SharedList α) set_option linter.unusedVariables false in inductive SharedTree (α : Type) where | leaf - | node (@shared label : α) (left right : SharedTree α) + | node (@[shared] label : α) (left right : SharedTree α) set_option linter.unusedVariables false in inductive SharedArrowInd where - | mk : Nat → (@shared x : Nat) → SharedArrowInd + | mk : Nat → (@[shared] x : Nat) → SharedArrowInd def readSharedBox (b : SharedBox Nat) : Nat := match b with @@ -193,7 +216,7 @@ def readSharedBox (b : SharedBox Nat) : Nat := @[no_rc, bounded_stack] def defNoRcBounded (x : Nat) : Nat := x + 1 @[no_alloc, bounded_stack] def defNoAllocBounded (x : Nat) : Nat := x + 1 @[bounded_stack, no_alloc] def defBoundedNoAlloc (x : Nat) : Nat := x + 1 -@[inline, no_rc] def defInlineNoRc (@unique x : Nat) : @unique Nat := x +@[inline, no_rc] def defInlineNoRc (@[unique] x : Nat) : @[unique] Nat := x @[no_alloc, bounded_stack] def defZeroArity : Nat := 42 @[no_rc] def defRecursive : Nat → Nat | 0 => 0 diff --git a/Tests/Ix/TruthMines.lean b/Tests/Ix/TruthMines.lean index f210d1656a..7be0a6262f 100644 --- a/Tests/Ix/TruthMines.lean +++ b/Tests/Ix/TruthMines.lean @@ -65,12 +65,11 @@ private def memberLabels (ixc : String) : IO (Except String (List String)) := do through the core: member set complete, roots well-formed, verify green over a non-empty union. -/ private def driverBuild (mini : Bool) (ixc : System.FilePath) - (expectMembers : Nat) : IO (Bool × Nat × Nat × Option String) := do + (expectMembers : Nat) : AssertM Unit := do unless (← ixExe.pathExists) do - return (false, 0, 0, some s!"{ixExe} missing — run `lake build ix` first") + fail s!"{ixExe} missing — run `lake build ix` first" unless (← driverExe.pathExists) do - return (false, 0, 0, - some s!"{driverExe} missing — run `lake build truthmines` first") + fail s!"{driverExe} missing — run `lake build truthmines` first" let exe ← IO.FS.realPath driverExe let mut args := #["build", "--out", ixc.toString] if mini then @@ -78,38 +77,30 @@ private def driverBuild (mini : Bool) (ixc : System.FilePath) let child ← IO.Process.spawn { cmd := exe.toString, args } let exit ← child.wait if exit != 0 then - return (false, 0, 0, some s!"truthmines build failed ({exit})") + fail s!"truthmines build failed ({exit})" unless (← (ixc / "manifest").pathExists) do - return (false, 0, 0, some s!"driver exited 0 but {ixc} has no manifest") - let labels ← match ← memberLabels ixc.toString with - | .ok ls => pure ls - | .error e => return (false, 0, 0, some s!"manifest: {e}") + fail s!"driver exited 0 but {ixc} has no manifest" + let labels ← expectOk ((← memberLabels ixc.toString).mapError (s!"manifest: {·}")) unless labels.length == expectMembers do - return (false, labels.length, expectMembers, - some s!"manifest carries {labels.length} members, the spec has \ -{expectMembers}") + fail s!"manifest carries {labels.length} members, the spec has {expectMembers}" -- Independent re-verify through the core (the driver already -- verified; this pins the suite's own read of the artifact). let verifyContent ← Ix.Cli.CatalogCmd.rsCatalogVerifyFFI ixc.toString false let union : Except String Nat := do let json ← Lean.Json.parse verifyContent (← json.getObjVal? "unionConsts").getNat? - match union with - | .ok n => - if n == 0 then - return (false, 0, 0, some "catalog verify reports an empty union") - return (true, labels.length, n, none) - | .error e => return (false, 0, 0, some s!"verify: {e}") + let n ← expectOk (union.mapError (s!"verify: {·}")) + if n == 0 then + fail "catalog verify reports an empty union" /-- Drive `truthmines check [--mini]`: the per-piece `ix check-lean --anon` sweep over the tier's `.ixc` — the fat-profile checking rung lives in the driver (bounded pool, output captured per piece, tails + solo repro surfaced on rejection); the suite is exit-code gated. -/ -private def driverCheck (mini : Bool) : IO (Bool × Nat × Nat × Option String) := do +private def driverCheck (mini : Bool) : AssertM Unit := do unless (← driverExe.pathExists) do - return (false, 0, 0, - some s!"{driverExe} missing — run `lake build truthmines` first") + fail s!"{driverExe} missing — run `lake build truthmines` first" let exe ← IO.FS.realPath driverExe let mut args := #["check"] if mini then @@ -117,24 +108,20 @@ private def driverCheck (mini : Bool) : IO (Bool × Nat × Nat × Option String) let child ← IO.Process.spawn { cmd := exe.toString, args } let exit ← child.wait if exit != 0 then - return (false, 0, 0, some s!"truthmines check failed ({exit})") - return (true, 0, 0, none) - -def buildSuite : List TestSeq := [ - .individualIO - "truthmines: full corpus pieces + self-contained .ixc via the driver" - none (driverBuild false "truthmines.ixc" catalogSpec.libs.size) .done ] - -def checkSuite : List TestSeq := [ - .individualIO "truthmines: per-piece kernel check sweep (fat rung 1)" - none (driverCheck false) .done ] - -def miniSuite : List TestSeq := [ - .individualIO - "truthmines-mini: fixtures + spine + Mathlib + FLT → .ixc directory" - none (driverBuild true "truthmines-mini.ixc" - catalogMiniSpec.libs.size) .done, - .individualIO "truthmines-mini: per-piece kernel check sweep" - none (driverCheck true) .done ] + fail s!"truthmines check failed ({exit})" + +def buildSuite : LSpec.Spec := do + it "truthmines: full corpus pieces + self-contained .ixc via the driver" + (driverBuild false "truthmines.ixc" catalogSpec.libs.size) + +def checkSuite : LSpec.Spec := do + it "truthmines: per-piece kernel check sweep (fat rung 1)" + (driverCheck false) + +def miniSuite : LSpec.Spec := do + it "truthmines-mini: fixtures + spine + Mathlib + FLT → .ixc directory" + (driverBuild true "truthmines-mini.ixc" catalogMiniSpec.libs.size) + it "truthmines-mini: per-piece kernel check sweep" + (driverCheck true) end Tests.Ix.TruthMines diff --git a/Tests/Ix/TruthMinesRecords.lean b/Tests/Ix/TruthMinesRecords.lean index 9e6e137930..2554f9dd97 100644 --- a/Tests/Ix/TruthMinesRecords.lean +++ b/Tests/Ix/TruthMinesRecords.lean @@ -30,32 +30,24 @@ open TruthMinesSpec namespace Tests.Ix.TruthMinesRecords -private def check (ok : Bool) (message : String) : - Bool × Nat × Nat × Option String := - (ok, 0, 0, if ok then none else some message) - -private def validationTest : IO (Bool × Nat × Nat × Option String) := do +private def validationTest : AssertM Unit := do let errors := catalogValidationErrors - return check errors.isEmpty + expect errors.isEmpty s!"catalog validation errors:\n{String.intercalate "\n" errors.toList}" -private def toolchainTest : IO (Bool × Nat × Nat × Option String) := do +private def toolchainTest : AssertM Unit := do let repo := (← IO.FS.readFile "lean-toolchain").trimAscii.toString let workspace := (← IO.FS.readFile workspaceToolchainPath).trimAscii.toString let compileWorkspace := (← IO.FS.readFile compileWorkspaceToolchainPath).trimAscii.toString - if repo != expectedToolchain then - return check false - s!"repo lean-toolchain `{repo}` != derived `{expectedToolchain}`" - if workspace != expectedToolchain then - return check false - s!"workspace lean-toolchain `{workspace}` != derived `{expectedToolchain}`" - if compileWorkspace != expectedToolchain then - return check false - s!"compile workspace lean-toolchain `{compileWorkspace}` != derived `{expectedToolchain}`" - return check true "" - -private def projectionTest : IO (Bool × Nat × Nat × Option String) := do + expect (repo == expectedToolchain) + s!"repo lean-toolchain `{repo}` != derived `{expectedToolchain}`" + expect (workspace == expectedToolchain) + s!"workspace lean-toolchain `{workspace}` != derived `{expectedToolchain}`" + expect (compileWorkspace == expectedToolchain) + s!"compile workspace lean-toolchain `{compileWorkspace}` != derived `{expectedToolchain}`" + +private def projectionTest : AssertM Unit := do let mut expected := [ (workspaceLakefilePath, renderWorkspaceLakefile), (workspaceToolchainPath, renderWorkspaceToolchain), @@ -68,10 +60,9 @@ private def projectionTest : IO (Bool × Nat × Nat × Option String) := do (compileMemberModulePath lib.qualifier, renderCompileMemberModule lib)] for (path, content) in expected do unless (← path.pathExists) do - return check false s!"{path} missing — run `lake exe truthmines gen`" + fail s!"{path} missing — run `lake exe truthmines gen`" unless (← IO.FS.readFile path) == content do - return check false s!"{path} is stale — run `lake exe truthmines gen`" - return check true "" + fail s!"{path} is stale — run `lake exe truthmines gen`" /-- Lake stores non-identifier package names guillemet-quoted in the lockfile (`«lean-grpc»`); the records carry them bare. -/ @@ -119,13 +110,11 @@ private def manifestErrors (content : String) : Except String (Array String) := s!"lockfile places `{fixture}` at `{lockDir}`, expected `{dir}`" return errors -private def manifestTest : IO (Bool × Nat × Nat × Option String) := do +private def manifestTest : AssertM Unit := do let content ← IO.FS.readFile workspaceManifestPath - match manifestErrors content with - | .error error => return check false s!"lockfile walk failed: {error}" - | .ok errors => - return check errors.isEmpty - s!"lockfile/record drift:\n{String.intercalate "\n" errors.toList}" + let errors ← expectOk ((manifestErrors content).mapError (s!"lockfile walk failed: {·}")) + expect errors.isEmpty + s!"lockfile/record drift:\n{String.intercalate "\n" errors.toList}" /-- The independent fidelity workspace shares the canonical package store and adds exactly one authored source pin: the aggregate Palomar.ix library. -/ @@ -162,52 +151,42 @@ private def compileManifestErrors (content : String) : Except String (Array Stri errors := errors.push "compile lockfile is missing canonical TruthMines path" return errors -private def compileManifestTest : IO (Bool × Nat × Nat × Option String) := do +private def compileManifestTest : AssertM Unit := do let content ← IO.FS.readFile compileWorkspaceManifestPath - match compileManifestErrors content with - | .error error => return check false s!"compile lockfile walk failed: {error}" - | .ok errors => - return check errors.isEmpty - s!"compile lockfile drift:\n{String.intercalate "\n" errors.toList}" + let errors ← expectOk ((compileManifestErrors content).mapError (s!"compile lockfile walk failed: {·}")) + expect errors.isEmpty + s!"compile lockfile drift:\n{String.intercalate "\n" errors.toList}" /-- The positional member vector is what `ix catalog` receives: one `Qualifier=Root[,Root…]` entry per member, parseable by the same splitting the CLI does (`=` once, roots comma-joined, no whitespace or empty components anywhere). -/ -private def specArgvTest : IO (Bool × Nat × Nat × Option String) := do +private def specArgvTest : AssertM Unit := do for (label, spec) in [("full", catalogSpec), ("mini", catalogMiniSpec)] do let rendered := commandArguments spec if rendered.size != spec.libs.size then - return check false - s!"{label}: {rendered.size} argv entries for {spec.libs.size} members" + fail s!"{label}: {rendered.size} argv entries for {spec.libs.size} members" for (entry, lib) in rendered.zip spec.libs do let parts := entry.splitOn "=" match parts with | [qualifier, roots] => if qualifier.isEmpty || qualifier != lib.qualifier.toString (escape := false) then - return check false s!"{label}: qualifier drift in `{entry}`" + fail s!"{label}: qualifier drift in `{entry}`" let rootParts := roots.splitOn "," if rootParts.length != lib.roots.size || rootParts.any (·.isEmpty) then - return check false s!"{label}: root list drift in `{entry}`" + fail s!"{label}: root list drift in `{entry}`" if entry.any (fun c => c == ' ' || c == '\n') then - return check false s!"{label}: whitespace in argv entry `{entry}`" + fail s!"{label}: whitespace in argv entry `{entry}`" | _ => - return check false s!"{label}: entry `{entry}` is not `Qualifier=Roots`" - return check true "" - -def suite : List TestSeq := [ - .individualIO "truthmines records: catalog validation clean" - none validationTest .done, - .individualIO "truthmines records: one toolchain by construction" - none toolchainTest .done, - .individualIO "truthmines records: workspace projections byte-identical" - none projectionTest .done, - .individualIO "truthmines records: lockfile pins match the records" - none manifestTest .done, - .individualIO "truthmines records: compile workspace pins are coherent" - none compileManifestTest .done, - .individualIO "truthmines records: positional spec argv is well-formed" - none specArgvTest .done ] + fail s!"{label}: entry `{entry}` is not `Qualifier=Roots`" + +def suite : LSpec.Spec := do + it "truthmines records: catalog validation clean" validationTest + it "truthmines records: one toolchain by construction" toolchainTest + it "truthmines records: workspace projections byte-identical" projectionTest + it "truthmines records: lockfile pins match the records" manifestTest + it "truthmines records: compile workspace pins are coherent" compileManifestTest + it "truthmines records: positional spec argv is well-formed" specArgvTest end Tests.Ix.TruthMinesRecords diff --git a/Tests/Main.lean b/Tests/Main.lean index 32192029bf..dddb0ad6cc 100644 --- a/Tests/Main.lean +++ b/Tests/Main.lean @@ -115,8 +115,7 @@ def registry : List Entry := [ .suite "import-ixe" .primary Tests.Ix.ImportIxe.suite, .suite "lean-export" .primary Tests.Ix.LeanExport.suite, .suite "truthmines-spec" .primary Tests.Ix.TruthMinesRecords.suite, - -- `concurrently`: the long role and admission checks run at once - .suiteIO "ixon" .primary (concurrently (Tests.Ixon.suite ++ Tests.Ix.IxonUniverse.suite)), + .suite "ixon" .primary (do Tests.Ixon.suite; Tests.Ix.IxonUniverse.suite), .suiteIO "ixon-reject-parity" .primary Tests.Ix.IxonRejectParity.suite, .suiteIO "ixon-rust-parity" .primary Tests.Ix.IxonRustParity.suite, .suite "role-equations" .primary Tests.Ix.RoleEquations.suite, @@ -125,9 +124,9 @@ def registry : List Entry := [ .suite "merkle" .primary Tests.Merkle.suite, .suite "assumption-tree" .primary Tests.AssumptionTree.suite, .suite "commit" .primary Tests.Commit.suite, - .suiteIO "exact-sharing" .primary (concurrently (Tests.SharingExact.suite ++ Tests.SharingUniform.suite ++ Tests.SharingTiered.suite)), + .suite "exact-sharing" .primary (do Tests.SharingExact.suite; Tests.SharingUniform.suite; Tests.SharingTiered.suite), .suite "sharing-components" .primary Tests.SharingComponents.suite, - .suite "source-contract" .primary (Tests.Ix.SourceContract.suite ++ Tests.Ix.SourceContract.Driver.suite), + .suite "source-contract" .primary (do Tests.Ix.SourceContract.suite; Tests.Ix.SourceContract.Driver.suite), .suite "aiur-statistics" .primary Tests.Ix.AiurStatistics.suite, .suite "bench-measures" .primary Tests.Ix.BenchMeasures.suite, -- the compile's named refusal of ungrounded input (the IO pipeline and the pure compile) @@ -181,7 +180,7 @@ def registry : List Entry := [ .suite "primitive-address-parity" .primary Tests.Ix.Kernel.BuildPrimitives.paritySuite, .suite "decompile-unit" .primary Tests.Decompile.unitSuite, -- getFileEnv body-inclusion regression guard (IO: loads a fixture file) - .suiteIO "getfileenv-body" .primary (do return [← Tests.Ix.EnvBody.suite]), + .suiteIO "getfileenv-body" .primary Tests.Ix.EnvBody.suite, -- Reductions no kernel may make beyond Lean's (class methods reduced -- without their instance, `numBits ≡ 64`, the `Fin.val` commute): every -- probe's closure through IxCK. @@ -273,8 +272,8 @@ def registry : List Entry := [ .runner "admission-hash-diff-initstd" (.ci .nightly) Tests.Ix.Kernel.AdmissionHashDiff.runInitStd, -- Full brute-force exact-sharing oracle (`witness2` 3M-candidate sweep, -- 13.7k tied-minima tables, and 400/600-input uniform search sweeps). - .suiteIO "exact-sharing-full" (.ci .nightly) - (concurrently (Tests.SharingExact.nightlySuite ++ Tests.SharingUniform.nightlySuite)) + .suite "exact-sharing-full" (.ci .nightly) + (do Tests.SharingExact.nightlySuite; Tests.SharingUniform.nightlySuite) ] /-- The host entries that must stay registered once, in their tier diff --git a/Tests/ProofHelpers.lean b/Tests/ProofHelpers.lean index 50b167125d..b7424e82ea 100644 --- a/Tests/ProofHelpers.lean +++ b/Tests/ProofHelpers.lean @@ -7,16 +7,21 @@ namespace Tests.ProofHelpers open LSpec /-- A passing test iff `e` is `.ok`; on `.error` the message is surfaced. -/ -def expectOk [ToString ε] (descr : String) (e : Except ε α) : TestSeq := - match e with - | .ok _ => test descr true - | .error msg => test s!"{descr} — unexpected error: {msg}" false +def checkOk [ToString ε] (descr : String) (e : Except ε α) : Spec := + it descr do + let _ ← LSpec.expectOk e /-- A passing test iff the verifier rejected the input. -/ -def expectErr (descr : String) (e : Except ε α) : TestSeq := - match e with - | .error _ => test descr true - | .ok _ => test s!"{descr} — expected a rejection but it was accepted" false +def checkErr [Repr α] (descr : String) (e : Except ε α) : Spec := + it descr do + let _ ← LSpec.expectErr e + +/-- A passing test iff `e` is `.error` (no `Repr` needed on `α`). -/ +def checkErrAny (descr : String) (e : Except ε α) : Spec := + it descr do + match e with + | .error _ => pure () + | .ok _ => fail s!"{descr} — expected a rejection but it was accepted" /-- Inner-proof commitment/FRI parameters. -/ def recCommitParams : Aiur.CommitmentParameters := diff --git a/Tests/Registry.lean b/Tests/Registry.lean index c3ac6f0ec1..28619b45ef 100644 --- a/Tests/Registry.lean +++ b/Tests/Registry.lean @@ -109,10 +109,10 @@ def Tier.parse? (s : String) : Option (Tier → Bool) := /-- What an entry runs. -/ inductive Body where - /-- LSpec suites (values; built when their module initializes, as before). -/ - | suite (tests : List LSpec.TestSeq) - /-- LSpec suites built by an IO action when the entry is selected. -/ - | suiteIO (tests : IO (List LSpec.TestSeq)) + /-- LSpec v3 specification (deferred; zero work at module initialization). -/ + | suite (spec : LSpec.Spec) + /-- LSpec v3 specification built by an IO action when the entry is selected. -/ + | suiteIO (spec : IO LSpec.Spec) /-- A runner; its result is the exit code. -/ | runner (run : IO UInt32) /-- A runner that takes the test binary's Lean environment. -/ @@ -123,36 +123,16 @@ structure Entry where tier : Tier body : Body -/-- Smart constructors, so that a registration reads `.suite "name" tier tests`. -/ -def Entry.suite (name : String) (tier : Tier) (tests : List LSpec.TestSeq) : Entry := - ⟨name, tier, .suite tests⟩ -def Entry.suiteIO (name : String) (tier : Tier) (tests : IO (List LSpec.TestSeq)) : Entry := - ⟨name, tier, .suiteIO tests⟩ +/-- Smart constructors, so that a registration reads `.suite "name" tier spec`. -/ +def Entry.suite (name : String) (tier : Tier) (spec : LSpec.Spec) : Entry := + ⟨name, tier, .suite spec⟩ +def Entry.suiteIO (name : String) (tier : Tier) (spec : IO LSpec.Spec) : Entry := + ⟨name, tier, .suiteIO spec⟩ def Entry.runner (name : String) (tier : Tier) (run : IO UInt32) : Entry := ⟨name, tier, .runner run⟩ def Entry.env (name : String) (tier : Tier) (run : Lean.Environment → IO UInt32) : Entry := ⟨name, tier, .env run⟩ -/-- `tests` with every `individualIO` check started now, each on a thread of -its own with its output captured; each check of the result waits for its -thread and then prints that output, so results and output keep their order. -For a suite of independent long checks, the suite takes as long as its -longest check rather than their sum. -/ -def startChecks : LSpec.TestSeq → IO LSpec.TestSeq - | .individualIO descr shown check next => do - let task ← IO.asTask (IO.FS.withIsolatedStreams check) .dedicated - return .individualIO descr shown (do - let (output, result) ← IO.ofExcept (← IO.wait task) - IO.print output - return result) (← startChecks next) - | .individual descr p shown inst next => return .individual descr p shown inst (← startChecks next) - | .group descr tests next => return .group descr (← startChecks tests) (← startChecks next) - | .done => return .done - -/-- `suites`, their checks started at once (`startChecks`). -/ -def concurrently (suites : List LSpec.TestSeq) : IO (List LSpec.TestSeq) := - suites.mapM startChecks - /-- A workflow line without its YAML comment: from the first `#` at the line's start or after a space or a tab. A `#` inside a quoted string after a space is cut too, which can only hide a mention, never invent one. -/ @@ -306,6 +286,7 @@ structure Options where exclude : List String := [] list : Bool := false listGate : Option (Tier → Bool) := none + threads : Nat := 1 def parseArgs : List String → Options → Except String Options | [], o => .ok o @@ -318,10 +299,24 @@ def parseArgs : List String → Options → Except String Options | "--list" :: rest, o => parseArgs rest { o with list := true } | "--ignored" :: rest, o => parseArgs rest { o with ignored := true } | "--include-ignored" :: rest, o => parseArgs rest { o with includeIgnored := true } + | "-j" :: val :: rest, o | "--threads" :: val :: rest, o => + match val.toNat? with + | some n => if n == 0 then .error "--threads must be at least 1" else parseArgs rest { o with threads := n } + | none => .error s!"expected natural number for --threads, got '{val}'" | a :: rest, o => if a.startsWith "--exclude=" then let xs := ((a.drop "--exclude=".length).toString.splitOn ",").filter (!·.isEmpty) parseArgs rest { o with exclude := o.exclude ++ xs } + else if a.startsWith "--threads=" then + let val := (a.drop "--threads=".length).toString + match val.toNat? with + | some n => if n == 0 then .error "--threads must be at least 1" else parseArgs rest { o with threads := n } + | none => .error s!"expected natural number for --threads, got '{val}'" + else if a.startsWith "-j" && a.length > 2 then + let val := (a.drop 2).toString + match val.toNat? with + | some n => if n == 0 then .error "-j must be at least 1" else parseArgs rest { o with threads := n } + | none => .error s!"expected natural number for -j, got '{val}'" else if a.startsWith "-" then .error s!"unknown option '{a}'" else parseArgs rest { o with names := o.names ++ [a] } @@ -345,13 +340,43 @@ def select (entries : List Entry) (o : Options) : Except String (List Entry) := if out.isEmpty then throw "nothing selected" return out -def runEntry (getEnv : IO Lean.Environment) (e : Entry) : IO UInt32 := do +def runEntry (getEnv : IO Lean.Environment) (threads : Nat) (e : Entry) : IO UInt32 := do match e.body with - | .suite tests => LSpec.lspecIO (.ofList [(e.name, tests)]) [] - | .suiteIO tests => LSpec.lspecIO (.ofList [(e.name, ← tests)]) [] + | .suite spec => + let tree ← spec.toTestTree e.name + LSpec.defaultMainTree tree [] { threads } + | .suiteIO mkSpec => + let spec ← mkSpec + let tree ← spec.toTestTree e.name + LSpec.defaultMainTree tree [] { threads } | .runner run => run | .env run => run (← getEnv) +/-- Convert an `Entry` into a `TestTree` so all selected entries can share a + single bounded LSpec v3 `WorkerPool` when `threads > 1`. -/ +private def entryToTestTree (getEnv : IO Lean.Environment) (e : Entry) : IO LSpec.TestTree := do + match e.body with + | .suite spec => spec.toTestTree e.name + | .suiteIO mkSpec => + let spec ← mkSpec + spec.toTestTree e.name + | .runner run => + return .leaf e.name #[] fun _ => do + let code ← run + if code == 0 then return .pass + else return .fail s!"exited with code {code}" + | .env run => + return .leaf e.name #[] fun _ => do + let env ← getEnv + let code ← run env + if code == 0 then return .pass + else return .fail s!"exited with code {code}" + +/-- Total duration across all leaves of a `ReportTree`. -/ +private partial def reportTreeDuration : LSpec.ReportTree → Nat + | .leaf r => r.durationMs + | .group _ cs => cs.foldl (fun acc c => acc + reportTreeDuration c) 0 + /-- Internal dispatch shared by `run`, `runScoped`, and `runManual`. -/ private def runEntries (entries : List Entry) (loadEnv : IO Lean.Environment) (args : List String) : IO UInt32 := do @@ -371,17 +396,46 @@ private def runEntries (entries : List Entry) (loadEnv : IO Lean.Environment) -- Non-primary entries ran after the dispatcher's `get_env!`, which also -- set the Lean search path; keep the search path without the import. if selected.any (!isPrimary ·) then initLeanSearchPath - let envRef ← IO.mkRef (none : Option Lean.Environment) - let getEnv : IO Lean.Environment := do - if let some env ← envRef.get then return env - let env ← loadEnv - envRef.set (some env) - return env + let envMutex ← Std.Mutex.new (none : Option Lean.Environment) + let getEnv : IO Lean.Environment := + envMutex.atomically do + if let some env ← get then return env + let env ← loadEnv + set (some env) + return env + if o.threads > 1 && selected.length > 1 then + -- Run ALL selected entries inside one shared bounded LSpec v3 WorkerPool! + let mut children := Array.mkEmpty selected.length + for e in selected do + children := children.push (← entryToTestTree getEnv e) + let combined : LSpec.TestTree := .group "" children + let (report, summary) ← LSpec.runTree combined { threads := o.threads } + let useColor := (← IO.getEnv "NO_COLOR").isNone + let entryReports := match report with + | .group _ cs => cs + | other => #[other] + let mut failed : Array String := #[] + for h : i in [:selected.length] do + let e := selected[i] + let rep := entryReports.getD i (.group e.name #[]) + let s := rep.summarize + let ms := reportTreeDuration rep + if s.allPassed then + IO.println s!"[ixtests] {e.name}: ok {ms} ms ({s.passed} tests)" + else + let rendered := LSpec.Processors.formatReport rep useColor false + unless rendered.isEmpty do IO.eprintln rendered + IO.println s!"[ixtests] {e.name}: FAILED ({s.failed} failed) {ms} ms" + failed := failed.push e.name + IO.println s!"[ixtests] {selected.length - failed.size} of {selected.length} passed\ + {if failed.isEmpty then "" else s!"; failed: {", ".intercalate failed.toList}"} \ + ({summary.totalDurationMs} ms wall, threads={o.threads})" + return if failed.isEmpty then 0 else 1 let mut first : UInt32 := 0 let mut failed : Array String := #[] for e in selected do let start ← IO.monoMsNow - let code ← try runEntry getEnv e catch ex => do + let code ← try runEntry getEnv o.threads e catch ex => do IO.eprintln s!"[ixtests] {e.name}: uncaught exception: {ex}" pure 1 let ms := (← IO.monoMsNow) - start diff --git a/Tests/SourceContractMain.lean b/Tests/SourceContractMain.lean index 8c786eba11..2b9627f9dc 100644 --- a/Tests/SourceContractMain.lean +++ b/Tests/SourceContractMain.lean @@ -4,5 +4,6 @@ import Tests.Ix.SourceContract.SyntaxCheck import Tests.Ix.SourceContract.Driver def main (args : List String) : IO UInt32 := - LSpec.lspecIO (.ofList [("source-contract", - Tests.Ix.SourceContract.suite ++ Tests.Ix.SourceContract.Driver.suite)]) args + LSpec.lspecMain (LSpec.describe "source-contract" do + Tests.Ix.SourceContract.suite + Tests.Ix.SourceContract.Driver.suite) args diff --git a/crates/aiur/examples/ixcc_prove.rs b/crates/aiur/examples/ixcc_prove.rs index 1fa6e1b3d3..f7791ec403 100644 --- a/crates/aiur/examples/ixcc_prove.rs +++ b/crates/aiur/examples/ixcc_prove.rs @@ -81,7 +81,7 @@ const LIES: [(&str, Lie); 3] = [ const USAGE: &str = "usage: ixcc_prove PACKAGE.ixa [PROOF.bin] [REPORT.json] \ [--batch] [--vk VK.bin] [--args N,N,...] \ [--ixvm-io INPUT.ixi] [--advice ADVICE.ixa] \ - [--tamper-hint CHANNEL] [--no-controls] [--pin PIN.json]"; + [--tamper-hint CHANNEL] [--no-controls] [--exec-only] [--pin PIN.json]"; #[derive(Clone, Debug, PartialEq, Eq)] struct Config { @@ -94,6 +94,7 @@ struct Config { advice_path: Option, tamper_hint: Option, controls: bool, + exec_only: bool, pin_path: Option, batch: bool, } @@ -108,6 +109,7 @@ where let mut advice_path: Option = None; let mut tamper_hint: Option = None; let mut controls = true; + let mut exec_only = false; let mut pin_path: Option = None; let mut vk_path: Option = None; let mut batch = false; @@ -135,6 +137,10 @@ where Some(raw.next().ok_or("--tamper-hint needs a channel name")?); }, "--no-controls" => controls = false, + "--exec-only" => { + exec_only = true; + controls = false; + }, "--pin" => pin_path = Some(raw.next().ok_or("--pin needs a file")?), "--batch" => batch = true, "--vk" => vk_path = Some(raw.next().ok_or("--vk needs a path")?), @@ -155,6 +161,7 @@ where advice_path, tamper_hint, controls, + exec_only, pin_path, batch, }) @@ -183,7 +190,7 @@ fn register_ixvm_streams( "ixvm.io.info", &address_key, None, - |channel, _| [1, 2, 4, 6, 7].contains(&channel), + |channel, _| [1, 2, 4, 5, 6, 7].contains(&channel), false, )?; data.extend(advice.metadata( @@ -315,6 +322,7 @@ fn check_pin( } enum ProvedEnvelope { + ExecOnly, Standalone { proof: Box, }, @@ -358,6 +366,19 @@ fn run(config: &Config) -> Result> { drop(raw_bytes); eprintln!("artifact {path} ({kind}): blake3 {digest}"); let (program, trace) = package.traced()?; + let fn_meta: Vec<(String, String)> = program + .functions + .iter() + .map(|f| { + let chip = trace + .functions + .iter() + .find(|p| p.name == f.name) + .map(|p| p.chip.clone()) + .unwrap_or_else(|| f.name.clone()); + (f.name.clone(), chip) + }) + .collect(); let mut program = program.check_field::()?; program.track_depth(&trace)?; let field = program.field(); @@ -459,6 +480,20 @@ fn run(config: &Config) -> Result> { let record = hints.execute(entry, address.clone())?; let execution_seconds = start.elapsed().as_secs_f64(); let divmod64_calls = divmod64_counter.load(Ordering::Relaxed); + let mut fn_counts = vec![0_usize; fn_meta.len()]; + for key in record.queries.keys() { + if let Some(count) = fn_counts.get_mut(key.function) { + *count += 1; + } + } + let function_rows: Vec = fn_meta + .iter() + .enumerate() + .filter_map(|(i, (name, chip))| { + let rows = fn_counts[i]; + (rows > 0).then(|| json!({ "name": name, "chip": chip, "rows": rows })) + }) + .collect(); let public_args = plan.public_args(&record, entry, &address)?; let start = Instant::now(); @@ -619,32 +654,52 @@ fn run(config: &Config) -> Result> { let stage1_words: usize = witness.traces.iter().map(|t| t.values.len()).sum(); drop(record); - eprintln!( - "Proving {active} active circuits ({rows} rows, {stage1_words} stage-1 words)..." - ); - let start = Instant::now(); - let proof = backend.prove(entry, &public_args, &output, witness)?; - let prove_seconds = start.elapsed().as_secs_f64(); - let bytes = proof.to_bytes()?; - let proof = Proof::from_bytes(&bytes)?; - eprintln!("Verifying serialized proof ({} bytes)...", bytes.len()); - let start = Instant::now(); - backend.verify(entry, &public_args, &output, &proof)?; - let verify_seconds = start.elapsed().as_secs_f64(); - ( - circuits, - rows, - table_rows, - rom_rows, - program_rows, - active, - stage1_words, - witness_seconds, - prove_seconds, - verify_seconds, - bytes, - ProvedEnvelope::Standalone { proof: Box::new(proof) }, - ) + if config.exec_only { + eprintln!( + "Exec-only profile: {active} active circuits ({rows} rows, {program_rows} prog, {rom_rows} rom, {stage1_words} stage-1 words)" + ); + ( + circuits, + rows, + table_rows, + rom_rows, + program_rows, + active, + stage1_words, + witness_seconds, + 0.0, + 0.0, + Vec::new(), + ProvedEnvelope::ExecOnly, + ) + } else { + eprintln!( + "Proving {active} active circuits ({rows} rows, {stage1_words} stage-1 words)..." + ); + let start = Instant::now(); + let proof = backend.prove(entry, &public_args, &output, witness)?; + let prove_seconds = start.elapsed().as_secs_f64(); + let bytes = proof.to_bytes()?; + let proof = Proof::from_bytes(&bytes)?; + eprintln!("Verifying serialized proof ({} bytes)...", bytes.len()); + let start = Instant::now(); + backend.verify(entry, &public_args, &output, &proof)?; + let verify_seconds = start.elapsed().as_secs_f64(); + ( + circuits, + rows, + table_rows, + rom_rows, + program_rows, + active, + stage1_words, + witness_seconds, + prove_seconds, + verify_seconds, + bytes, + ProvedEnvelope::Standalone { proof: Box::new(proof) }, + ) + } }; // What the run has cost up to here; the controls below are not part of it. let total_seconds = total.elapsed().as_secs_f64(); @@ -666,6 +721,7 @@ fn run(config: &Config) -> Result> { for index in 0..checked_outputs { let wrong = flip(&output, index)?; match &envelope { + ProvedEnvelope::ExecOnly => {}, ProvedEnvelope::Standalone { proof } => { match backend.verify(entry, &public_args, &wrong, proof) { Ok(()) => { @@ -762,6 +818,7 @@ fn run(config: &Config) -> Result> { for index in 0..checked_arguments { let wrong = flip(&public_args, index)?; match &envelope { + ProvedEnvelope::ExecOnly => {}, ProvedEnvelope::Standalone { proof } => { match backend.verify(entry, &wrong, &output, proof) { Ok(()) => { @@ -1000,6 +1057,7 @@ fn run(config: &Config) -> Result> { (1u64, "tree_stream"), (2u64, "constant_stream"), (4u64, "blob_stream"), + (5u64, "syntax_stream"), (6u64, "role_stream"), (7u64, "model_stream"), ] { @@ -1135,8 +1193,12 @@ fn run(config: &Config) -> Result> { } } - if let Some(path) = &config.proof_path { - std::fs::write(path, &bytes)?; + if !config.exec_only { + if let Some(path) = &config.proof_path { + if path != "-" { + std::fs::write(path, &bytes)?; + } + } } if let (Some(path), ProvedEnvelope::Batch { vk_bytes, .. }) = (&config.vk_path, &envelope) @@ -1144,7 +1206,7 @@ fn run(config: &Config) -> Result> { std::fs::write(path, vk_bytes)?; } let mut report = json!({ - "mode": if config.batch { "batch" } else { "standalone" }, + "mode": if config.exec_only { "exec_only" } else if config.batch { "batch" } else { "standalone" }, "artifact_blake3": digest.to_string(), "pin": pin, "advice_blake3": advice_digest.map(|d| d.to_string()), @@ -1160,7 +1222,7 @@ fn run(config: &Config) -> Result> { "program_rows": program_rows, "table_rows": table_rows, "rom_rows": rom_rows, "controls": controls, "stage1_words": stage1_words, - "verified": true, "rejected_wrong_claims": rejections.len(), + "verified": !config.exec_only, "rejected_wrong_claims": rejections.len(), "rejections": rejections, "divmod64_calls": divmod64_calls, "rejected_wrong_advice": advice_rejections.len(), @@ -1173,6 +1235,7 @@ fn run(config: &Config) -> Result> { .count(), "stream_rejections": stream_rejections, "circuits": circuits, + "function_rows": function_rows, }); if let ProvedEnvelope::Batch { vk_bytes, @@ -1203,6 +1266,7 @@ fn main() -> Result<(), Box> { let mut summary = run(&config)?; // Circuit details go in the report; stdout is a short summary. summary.as_object_mut().unwrap().remove("circuits"); + summary.as_object_mut().unwrap().remove("function_rows"); println!("{}", serde_json::to_string_pretty(&summary)?); Ok(()) } @@ -1277,6 +1341,7 @@ mod tests { advice_path: None, tamper_hint: None, controls: true, + exec_only: false, pin_path: None, batch: true, }; @@ -1327,6 +1392,7 @@ mod tests { advice_path: None, tamper_hint: None, controls: true, + exec_only: false, pin_path: None, batch: false, }; diff --git a/crates/aiur/src/trace/stark.rs b/crates/aiur/src/trace/stark.rs index 8211f1820a..5c8ac7face 100644 --- a/crates/aiur/src/trace/stark.rs +++ b/crates/aiur/src/trace/stark.rs @@ -14,6 +14,7 @@ use crate::{ field::{FieldBackend, NativeField, PrimeField}, }; use multi_stark::{ + config::ProofConfig, expr::Expr, lookup::Lookup, p3_adapter::fri_batching::FriBatching, @@ -338,6 +339,7 @@ fn build_system( names: &[String], parameters: Parameters, device: Option, + stage_1_pinning: bool, ) -> Result< (System, ProverKey), String, @@ -349,6 +351,7 @@ fn build_system( parameters.fri(), device, LookupGroupPolicy::FftDominance, + stage_1_pinning, ) } @@ -359,6 +362,7 @@ fn build_system_with_fri( fri: FriParameters, device: Option, lookup_group_policy: LookupGroupPolicy, + stage_1_pinning: bool, ) -> Result< (System, ProverKey), String, @@ -387,7 +391,8 @@ fn build_system_with_fri( fri, FriBatching::Tensor, device, - ); + ) + .with_stage_1_pinning(stage_1_pinning); let (mut system, key) = System::new(config, inputs); // Tune lookup group sizes against the configured cost policy within the // blowup budget before exposing the system, compiling lookup plans, or @@ -719,7 +724,8 @@ impl<'p, 'a, B: WitnessField> Backend<'p, 'a, B> { fri, FriBatching::Tensor, device, - ); + ) + .with_stage_1_pinning(self.system.config.stage_1_pinning()); let mut circuits = Vec::with_capacity(self.system.circuits.len()); for (i, circuit) in self.system.circuits.iter().enumerate() { if circuit.preprocessed_height > 0 && circuit.preprocessed.is_none() { @@ -1147,6 +1153,7 @@ impl<'p, 'a, B: WitnessField> Backend<'p, 'a, B> { fri, device, lookup_group_policy, + segmented_memory, )? } else { let config = GoldilocksBlake3V6Config::with_device( @@ -1154,7 +1161,8 @@ impl<'p, 'a, B: WitnessField> Backend<'p, 'a, B> { fri, FriBatching::Tensor, device, - ); + ) + .with_stage_1_pinning(segmented_memory); let (mut system, key) = Self::compile_system_without_commit( config, inputs, diff --git a/crates/aiur/src/trace/stark/batch.rs b/crates/aiur/src/trace/stark/batch.rs index 0087e773fd..20fda84adf 100644 --- a/crates/aiur/src/trace/stark/batch.rs +++ b/crates/aiur/src/trace/stark/batch.rs @@ -986,16 +986,27 @@ impl<'p, 'a, B: WitnessField> Backend<'p, 'a, B> { /// The `(round, shard)` supplies of a streamed proof for an explicit /// per-shard retention mask. Round one always commits shards last to first /// (ending on shard zero so deferred host depth-range counts complete before - /// shard zero's fixed tables); round two re-supplies only unretained shards - /// in ascending shard order. + /// shard zero's fixed tables); under stage-1 pinning, unretained shards are + /// then supplied once in ascending shard order to evaluate their pinned + /// columns at `z₀` (round 1), and finally re-supplied in ascending shard + /// order to prove (round 2, or round 1 without pinning). pub(super) fn supply_order_with_retained( shards: usize, retained: &[bool], + stage_1_pinning: bool, ) -> Vec<(usize, usize)> { let mut order: Vec<_> = (0..shards).rev().map(|shard| (0, shard)).collect(); + if stage_1_pinning { + for (shard, &keep) in retained.iter().enumerate() { + if !keep { + order.push((1, shard)); + } + } + } + let prove_round = if stage_1_pinning { 2 } else { 1 }; for (shard, &keep) in retained.iter().enumerate() { if !keep { - order.push((1, shard)); + order.push((prove_round, shard)); } } order @@ -1005,8 +1016,10 @@ impl<'p, 'a, B: WitnessField> Backend<'p, 'a, B> { /// prover takes them. Round one commits the shards last to first, so it /// ends on shard zero, which round two proves first: that commitment is /// kept across the barrier instead of being regenerated, at no cost in - /// peak memory, and only the other shards are supplied again. Commitment - /// order does not enter the transcript, which sees the headers by shard. + /// peak memory, and only the other shards are supplied again (twice when + /// stage-1 pinning is enabled: once for pinning and once to prove). + /// Commitment order does not enter the transcript, which sees the headers + /// by shard. pub(super) fn supply_order( &self, shards: usize, @@ -1014,11 +1027,15 @@ impl<'p, 'a, B: WitnessField> Backend<'p, 'a, B> { ) -> Vec<(usize, usize)> { let retain = !self.requires_regeneration(shards) && matches!(retention, Retention::Retain); - let mut order: Vec<_> = (0..shards).rev().map(|shard| (0, shard)).collect(); - if !retain { - order.extend((1..shards).map(|shard| (1, shard))); + let mut retained = vec![retain; shards]; + if let Some(first) = retained.first_mut() { + *first = true; } - order + Self::supply_order_with_retained( + shards, + &retained, + self.system.config.stage_1_pinning(), + ) } /// Fallible two-round streaming. The supplier may replay a record and keep @@ -1266,8 +1283,26 @@ impl<'p, 'a, B: WitnessField> Backend<'p, 'a, B> { let round1_seconds = round1_start.elapsed().as_secs_f64(); let headers = headers.into_iter().map(Option::unwrap).collect(); let preamble = multi_stark::batch::BatchPreamble { headers, messages }; - let transcript = self.system.batch_transcript(&preamble); - let pins = multi_stark::pinning::BatchPins::default(); + let (transcript, pins) = if self.system.config.stage_1_pinning() { + let pinning = self.system.pinning_transcript(&preamble); + let pins = self.system.batch_pins( + &self.key, + &preamble, + pinning.point(), + &retained, + |shard| { + let witness = supply(shard)?; + self.check_prepared_shape(&witness)?; + Ok::<_, String>(witness) + }, + )?; + (pinning.absorb(pins.values()), pins) + } else { + ( + self.system.batch_transcript(&preamble), + multi_stark::pinning::BatchPins::default(), + ) + }; let mut proofs: Vec<_> = (0..plan.shards).map(|_| None).collect(); let mut s1_commit_r2_seconds = 0.0; @@ -1344,7 +1379,7 @@ impl<'p, 'a, B: WitnessField> Backend<'p, 'a, B> { } let round2_seconds = round2_start.elapsed().as_secs_f64(); let proofs = proofs.into_iter().map(Option::unwrap).collect(); - let proof = BatchProof { preamble, pinned: Vec::new(), proofs }; + let proof = BatchProof { preamble, pinned: pins.into_values(), proofs }; let verify_seconds = if schedule.verify { let verify_start = std::time::Instant::now(); self.verify_batch(entry, args, output, &proof)?; @@ -1457,7 +1492,11 @@ impl<'p, 'a, B: WitnessField> Backend<'p, 'a, B> { plan.retention, schedule.retained, )?; - let order = Self::supply_order_with_retained(plan.shards, &retained_flags); + let order = Self::supply_order_with_retained( + plan.shards, + &retained_flags, + self.system.config.stage_1_pinning(), + ); let schedule = StreamSchedule { retained: Some(&retained_flags), ..schedule }; let Some(feed) = feed.filter(|_| Self::pipelines(&order, feed)) else { @@ -1863,9 +1902,17 @@ impl<'p, 'a, B: WitnessField> Backend<'p, 'a, B> { } else { retention }; - // Shards are supplied in order, once per round: twice when regenerated. - // The source matrices remain resident until their last supply. - let supplies = if matches!(retention, Retention::Retain) { 1 } else { 2 }; + // Shards are supplied in order, once per round: twice when regenerated + // without pinning, three times when regenerated with stage-1 pinning + // (commit, pin evaluation, prove). The source matrices remain resident + // until their last supply. + let supplies = if matches!(retention, Retention::Retain) { + 1 + } else if self.system.config.stage_1_pinning() { + 3 + } else { + 2 + }; let mut supplied = vec![0u8; shards]; let fixed_cells: Vec<_> = traces.iter().map(|t| t.values.len()).collect(); let mut traces = traces; diff --git a/crates/aiur/src/trace/stark/streaming.rs b/crates/aiur/src/trace/stark/streaming.rs index 665e5dee6d..850a151afe 100644 --- a/crates/aiur/src/trace/stark/streaming.rs +++ b/crates/aiur/src/trace/stark/streaming.rs @@ -2398,8 +2398,11 @@ impl Backend<'_, '_, B> { // one, and its witness prefetches its device image: reserve that image // before the previous witness is handed over. #[cfg(feature = "cuda")] - let order = - Self::supply_order_with_retained(layout.shards.len(), &retained_mask); + let order = Self::supply_order_with_retained( + layout.shards.len(), + &retained_mask, + self.system.config.stage_1_pinning(), + ); #[cfg(feature = "cuda")] let pipelined = Self::pipelines(&order, feed); let proving = Instant::now(); @@ -2426,8 +2429,10 @@ impl Backend<'_, '_, B> { let deferred = prepared .deferred_host_ranges .then_some((&host_ranges, &final_counts)); + let prove_round = + if self.system.config.stage_1_pinning() { 2 } else { 1 }; let cached_host = - (round == 1).then(|| host_cache.take(shard)).flatten(); + (round == prove_round).then(|| host_cache.take(shard)).flatten(); let (witness, time) = self.timed_witness_inner( &prepared, &layout.shards[shard], diff --git a/crates/aiur/src/trace/stark/tests/depth.rs b/crates/aiur/src/trace/stark/tests/depth.rs index 43811cc002..1948717792 100644 --- a/crates/aiur/src/trace/stark/tests/depth.rs +++ b/crates/aiur/src/trace/stark/tests/depth.rs @@ -459,7 +459,7 @@ fn unsegmented_vectorized_rom_row_weight_enforced() { let mut inputs = Vec::new(); let mut names = Vec::new(); rom_n.append_circuits(&mut inputs, &mut names, false).unwrap(); - let (synthetic, _) = build_system(inputs, &names, params, None).unwrap(); + let (synthetic, _) = build_system(inputs, &names, params, None, true).unwrap(); let mut active_at = vec![true; at_bound + 1]; active_at[at_bound] = false; diff --git a/crates/aiur/src/trace/stark/tests/parameters.rs b/crates/aiur/src/trace/stark/tests/parameters.rs index b74ed49a99..07187dabdf 100644 --- a/crates/aiur/src/trace/stark/tests/parameters.rs +++ b/crates/aiur/src/trace/stark/tests/parameters.rs @@ -72,6 +72,10 @@ fn lean_mirror_matches() { field("maxProofOfWorkBits"), stark_key::security::MAX_PROOF_OF_WORK_BITS ); + assert_eq!( + field("stage1PinningV6"), + stark_key::security::STAGE_1_PINNING_V6 + ); // Extract `| k => some v` tables from `def ` in `Parameters.lean`. let table_entry = |fn_name: &str, key: usize| -> usize { diff --git a/crates/aiur/src/trace/stark/tests/streaming.rs b/crates/aiur/src/trace/stark/tests/streaming.rs index efc57aba94..9235221df2 100644 --- a/crates/aiur/src/trace/stark/tests/streaming.rs +++ b/crates/aiur/src/trace/stark/tests/streaming.rs @@ -316,8 +316,11 @@ fn streamed_supplier_rejects_a_changed_second_round() { |_| { calls += 1; let mut traces = backend.generate_stage_1(&record, "root", &[3])?; - // Round one supplies shards one and zero; round two regenerates one. - if calls == 3 { + // Round one supplies shards one and zero; under stage-1 pinning, shard + // one is supplied for pinning (call 3) and then regenerated to prove + // (call 4). Tampering the proving regeneration must fail the header check. + let prove_call = if backend.system.config.stage_1_pinning() { 4 } else { 3 }; + if calls == prove_call { traces[0].values[0] += Val::ONE; } Ok(traces) @@ -660,17 +663,24 @@ fn pipelined_population_matches_serial_proofs() { prove_scheduled(&backend, &record, &layout, retention, true); let shards = layout.shards.len(); // Shard zero's commitment carries over the barrier; the others are - // supplied again when regenerated. - let supplies = if matches!(retention, Retention::Retain) { - shards - } else { - 2 * shards - 1 - }; + // supplied again when regenerated (twice under stage-1 pinning: once + // for pinning evaluation and once to prove). + let pinned = backend.system.config.stage_1_pinning(); + let unretained = + if matches!(retention, Retention::Retain) { 0 } else { shards - 1 }; + let supplies = shards + unretained * if pinned { 2 } else { 1 }; assert_eq!(backend.supply_order(shards, retention).len(), supplies); assert_eq!(report.pipelined, supplies > 1); assert_eq!(pipelined, serial, "cap {rows}, {retention:?}"); assert_eq!(report.shards.len(), supplies); - assert_eq!(report.rounds.len(), if supplies > shards { 2 } else { 1 }); + let expected_rounds = if unretained == 0 { + 1 + } else if pinned { + 3 + } else { + 2 + }; + assert_eq!(report.rounds.len(), expected_rounds); assert!(!report.top_circuits.is_empty()); } } diff --git a/crates/aiur/src/trace/stark/wide.rs b/crates/aiur/src/trace/stark/wide.rs index df4b0442b9..f630e43100 100644 --- a/crates/aiur/src/trace/stark/wide.rs +++ b/crates/aiur/src/trace/stark/wide.rs @@ -490,7 +490,13 @@ impl<'p, 'a, B: WitnessField> WideBackend<'p, 'a, B> { let device = Some(rust.device); #[cfg(not(feature = "cuda"))] let device = None; - let (system, key) = build_system(inputs, &names, rust.parameters, device)?; + let (system, key) = build_system( + inputs, + &names, + rust.parameters, + device, + rust.system.config.stage_1_pinning(), + )?; let lookup_plans = system .circuits .iter() diff --git a/crates/ffi/src/shrinker.rs b/crates/ffi/src/shrinker.rs index 27a8d3d6e9..d471feb06e 100644 --- a/crates/ffi/src/shrinker.rs +++ b/crates/ffi/src/shrinker.rs @@ -902,7 +902,7 @@ mod tests { }; let channel = Val::from_u64(MEMSEG); let (system, pk) = System::new( - GoldilocksBlake3V6Config::new(cp, fp), + GoldilocksBlake3V6Config::new(cp, fp).with_stage_1_pinning(true), [(2usize, 4usize), (1, 2)].into_iter().map(|(width, height)| { CircuitInputs { main_width: width + 3, @@ -1250,13 +1250,14 @@ mod tests { query_proof_of_work_bits: 20, }; let (std_system, _) = System::new( - GoldilocksBlake3V6Config::new(std_cp, std_fp), + GoldilocksBlake3V6Config::new(std_cp, std_fp).with_stage_1_pinning(true), build_inputs(), ); let std_vk_bytes = stark_key::to_bytes(&std_system, std_cp, std_fp); let (compact_system, compact_pk) = System::new( - GoldilocksBlake3V6Config::new(compact_cp, compact_fp), + GoldilocksBlake3V6Config::new(compact_cp, compact_fp) + .with_stage_1_pinning(true), build_inputs(), ); let compact_vk_bytes = diff --git a/crates/proof-compression/src/fri/batch.rs b/crates/proof-compression/src/fri/batch.rs index 046c57e381..57a77173de 100644 --- a/crates/proof-compression/src/fri/batch.rs +++ b/crates/proof-compression/src/fri/batch.rs @@ -15,10 +15,11 @@ use super::PcsInputs; use super::TranscriptCommitments; use super::algebra::EXTENSION_DEGREE; use super::algebra::constrain_algebraic_checks_with_residual; -use super::pcs::constrain_pcs; +use super::pcs::{constrain_pcs, constrain_pinning_point_ok}; use super::pcs_witness::expand_after_lookup; use multi_stark::batch::BatchMessage; use multi_stark::batch::BatchProof; +use multi_stark::config::ProofConfig; use multi_stark::p3_adapter::fri_batching::FriBatching; use multi_stark::p3_field::PrimeCharacteristicRing; use multi_stark::plonkish::Circuit; @@ -179,6 +180,30 @@ fn constrain_batch_queries( .collect(); let commitments: Vec<_> = shapes.iter().map(|_| TranscriptCommitments::allocate(b, bytes)).collect(); + let pinned_per_shard: Vec>> = if system.config.stage_1_pinning() { + shapes + .iter() + .enumerate() + .map(|(shard, shape)| { + shape + .active + .iter() + .enumerate() + .filter_map(|(ci, &is_active)| is_active.then_some(ci)) + .enumerate() + .map(|(pos, ci)| { + (0..system.pinned_width(ci)) + .map(|col| { + E::input(b, &format!("shard[{shard}].pinned[{pos}][{col}]")) + }) + .collect() + }) + .collect() + }) + .collect() + } else { + vec![Vec::new(); shapes.len()] + }; let mut ch = Blake3Challenger::with_domain_and_retry_limit( b, bytes, @@ -220,6 +245,19 @@ fn constrain_batch_queries( ch.observe_field(b, bytes, value); } } + let pin_point = if system.config.stage_1_pinning() { + let z0 = ch.sample_extension(b, bytes); + for shard_pins in &pinned_per_shard { + for row in shard_pins { + for &value in row { + ch.observe_extension(b, bytes, value); + } + } + } + Some(z0) + } else { + None + }; let beta = ch.sample_extension(b, bytes); ch.observe_extension(b, bytes, beta); let gamma = ch.sample_extension(b, bytes); @@ -243,8 +281,12 @@ fn constrain_batch_queries( .into_iter() .zip(algebra) .zip(commitments) + .zip(pinned_per_shard) .enumerate() - .map(|(index, ((shape, algebra), commitments))| { + .map(|(index, (((shape, algebra), commitments), shard_pins))| { + if let Some(z0) = pin_point { + constrain_pinning_point_ok(b, z0, &shape.log_degrees, shape.log_blowup); + } beta.assert_equal(b, algebra.challenges.beta); gamma.assert_equal(b, algebra.challenges.gamma); let mut shard_ch = ch.clone(); @@ -290,9 +332,17 @@ fn constrain_batch_queries( &algebra, &commitments, &pcs, + pin_point.map(|z0| (z0, shard_pins.as_slice())), shard_ch, ); - FixedVerifierInputs { shape, algebra, commitments, pcs, query_bits } + FixedVerifierInputs { + shape, + algebra, + commitments, + pcs, + pinned: shard_pins, + query_bits, + } }) .collect(); if check_algebra { @@ -358,7 +408,21 @@ pub fn expand_batch_witness( return Err("batch header differs from proof or profile".into()); } } - let (challenger, beta, gamma) = system.batch_challenger(&batch.preamble); + let (challenger, pin_point, beta, gamma) = + if system.config.stage_1_pinning() { + if batch.pinned.len() != shapes.len() { + return Err("batch pinned shard count differs from profile".into()); + } + let (ch, z0, beta, gamma) = + system.pinned_batch_challenger(&batch.preamble, &batch.pinned); + (ch, Some(z0), beta, gamma) + } else { + if !batch.pinned.is_empty() { + return Err("unexpected pinned values on unpinned system".into()); + } + let (ch, beta, gamma) = system.batch_challenger(&batch.preamble); + (ch, None, beta, gamma) + }; shapes .iter() .zip(&batch.preamble.headers) @@ -368,7 +432,8 @@ pub fn expand_batch_witness( let mut ch = challenger.clone(); ch.observe(Val::from_usize(index)); let claims: Vec<_> = header.claims.iter().map(Vec::as_slice).collect(); - expand_after_lookup(system, shape, proof, &claims, ch, beta, gamma) + let pin = pin_point.map(|z0| (z0, batch.pinned[index].as_slice())); + expand_after_lookup(system, shape, proof, &claims, ch, beta, gamma, pin) }) .collect() } diff --git a/crates/proof-compression/src/fri/key_codec.rs b/crates/proof-compression/src/fri/key_codec.rs index 0a4f8eef4e..6c3cd88413 100644 --- a/crates/proof-compression/src/fri/key_codec.rs +++ b/crates/proof-compression/src/fri/key_codec.rs @@ -37,6 +37,7 @@ struct KeyData { vk_digest: [u8; 32], commitment: [usize; 2], fri: [usize; 5], + stage_1_pinning: bool, circuits: Vec, preprocessing: Option, indices: Vec>, @@ -55,6 +56,7 @@ impl VerifierKey { "log_blowup": system.config.log_blowup(), "cap": system.config.cap_height(), "num_queries": fri.num_queries, "commit_pow": fri.commit_proof_of_work_bits, "query_pow": fri.query_proof_of_work_bits, "max_log_arity": fri.max_log_arity, + "stage_1_pinning": system.config.stage_1_pinning(), "circuits": system.circuits.iter().map(|c| serde_json::json!({ "main": c.main_width, "pre": c.preprocessed_width, "height": c.preprocessed_height, "lookups": c.num_lookups, "stage2": c.stage_2_width, "group": c.lookup_group_size, @@ -93,6 +95,7 @@ impl VerifierKey { fp.commit_proof_of_work_bits, fp.query_proof_of_work_bits, ], + stage_1_pinning: s.config.stage_1_pinning(), circuits: s .circuits .iter() @@ -197,7 +200,8 @@ impl VerifierKey { return Err(VerifierError::Profile("vk digest mismatch")); } let key = Self::new(System { - config: GoldilocksBlake3V6Config::new(commitment, fri), + config: GoldilocksBlake3V6Config::new(commitment, fri) + .with_stage_1_pinning(data.stage_1_pinning), circuits, preprocessed_commit: data.preprocessing, preprocessed_indices: data.indices, diff --git a/crates/proof-compression/src/fri/pcs.rs b/crates/proof-compression/src/fri/pcs.rs index a4aa69829d..7f501f8a21 100644 --- a/crates/proof-compression/src/fri/pcs.rs +++ b/crates/proof-compression/src/fri/pcs.rs @@ -58,6 +58,8 @@ pub struct FixedPcsShape { pub heights: [Vec; 4], /// Canonical batches: main, stage 2, quotient, preprocessing. pub widths: [Vec; 4], + /// Whether stage-1 pinning (`z₀` + 3-point openings on main & preprocessed) is enabled. + pub stage_1_pinning: bool, } /// Deterministic multi-arity FRI round schedule matching @@ -215,6 +217,7 @@ impl FixedPcsShape { .collect(), prep_widths, ], + stage_1_pinning: system.config.stage_1_pinning(), } } @@ -252,7 +255,13 @@ impl FixedPcsShape { let mut max_width = 0usize; let mut openings_per_height: BTreeMap = BTreeMap::new(); for batch in 0..4 { - let points = if batch == 2 { 1 } else { 2 }; + let points = if batch == 2 { + 1 + } else if self.stage_1_pinning && (batch == 0 || batch == 3) { + 3 + } else { + 2 + }; for (&width, &height) in self.widths[batch].iter().zip(&self.heights[batch]) { @@ -349,6 +358,9 @@ pub struct FixedVerifierInputs { pub algebra: AlgebraicInputs, pub commitments: TranscriptCommitments, pub pcs: PcsInputs, + /// Under stage-1 pinning, the claimed values at `z₀` (one row per active + /// circuit, fixed columns followed by main columns). Empty without pinning. + pub pinned: Vec>, /// Derived query bits, useful for differential diagnostics, not inputs. pub query_bits: Vec>, } @@ -433,6 +445,10 @@ pub(super) fn constrain_fixed_queries( if check_algebra { constrain_algebraic_checks(b, &circuits, &shape.log_degrees, &algebra); } + assert!( + !system.config.stage_1_pinning(), + "ordinary verifier does not support stage-1 pinning; use batch verifier" + ); let pcs = PcsInputs::allocate_queries(b, bytes, &shape, queries); let query_bits = constrain_pcs( b, @@ -442,24 +458,78 @@ pub(super) fn constrain_fixed_queries( &algebra, &commitments, &pcs, + None, challenger, ); - FixedVerifierInputs { shape, algebra, commitments, pcs, query_bits } + FixedVerifierInputs { + shape, + algebra, + commitments, + pcs, + pinned: Vec::new(), + query_bits, + } +} + +/// Constrain `pinning_point_ok(z0, log_degrees, log_blowup)`: `z0 != 0`, and +/// for every active circuit log degree `k`, `z0^(2^k) != 1` and +/// `(z0 * coset_shift^-1)^(2^(k + log_blowup)) != 1`. +pub(super) fn constrain_pinning_point_ok( + b: &mut CircuitBuilder, + z0: E, + log_degrees: &[u8], + log_blowup: usize, +) { + let _ = z0.inverse(b); + let one = E::constant(b, [Val::ONE, Val::ZERO, Val::ZERO]); + let unshifted = z0.scale(b, Val::GENERATOR.inverse()); + let distinct: BTreeSet = + log_degrees.iter().copied().map(usize::from).collect(); + for k in distinct { + let mut p = z0; + for _ in 0..k { + p = p.mul(b, p); + } + let _ = p.sub(b, one).inverse(b); + + let mut u = unshifted; + for _ in 0..(k + log_blowup) { + u = u.mul(b, u); + } + let _ = u.sub(b, one).inverse(b); + } } fn opening_rows<'a>( algebra: &'a AlgebraicInputs, shape: &FixedPcsShape, + pinned: Option<&'a [Vec]>, batch: usize, matrix: usize, ) -> Vec<&'a [E]> { - let matrix = if batch == 3 { shape.preprocessed[matrix] } else { matrix }; - let o = &algebra.openings[matrix]; + let active_pos = if batch == 3 { shape.preprocessed[matrix] } else { matrix }; + let o = &algebra.openings[active_pos]; match batch { - 0 => o.main.iter().map(Vec::as_slice).collect(), + 0 => { + let mut rows: Vec<&'a [E]> = o.main.iter().map(Vec::as_slice).collect(); + if let Some(pins) = pinned { + let pin_row = &pins[active_pos]; + let fixed_w = pin_row.len() - shape.widths[0][active_pos]; + rows.push(&pin_row[fixed_w..]); + } + rows + }, 1 => o.stage2.iter().map(Vec::as_slice).collect(), 2 => vec![&o.quotient], - 3 => o.preprocessed.iter().map(Vec::as_slice).collect(), + 3 => { + let mut rows: Vec<&'a [E]> = + o.preprocessed.iter().map(Vec::as_slice).collect(); + if let Some(pins) = pinned { + let fixed_w = shape.widths[3][matrix]; + rows.push(&pins[active_pos][..fixed_w]); + } + rows + }, _ => unreachable!(), } } @@ -671,6 +741,7 @@ pub(super) fn constrain_pcs( algebra: &AlgebraicInputs, commitments: &TranscriptCommitments, pcs: &PcsInputs, + pin: Option<(E, &[Vec])>, mut challenger: Blake3Challenger, ) -> Vec> { assert_eq!( @@ -678,13 +749,19 @@ pub(super) fn constrain_pcs( FriBatching::Tensor, "Protocol v6 verifier requires FriBatching::Tensor" ); + assert_eq!( + pin.is_some(), + shape.stage_1_pinning, + "pin presence must match shape.stage_1_pinning" + ); assert_eq!(pcs.roots.len(), shape.fri_rounds()); assert_eq!(pcs.commit_pow.len(), shape.fri_rounds()); assert_eq!(pcs.final_poly.len(), shape.final_poly_len()); + let pinned_rows = pin.map(|(_, rows)| rows); // PCS observes OOD evaluations in batch, matrix, point, column order. for batch in 0..4 { for matrix in 0..shape.widths[batch].len() { - for row in opening_rows(algebra, shape, batch, matrix) { + for row in opening_rows(algebra, shape, pinned_rows, batch, matrix) { for &value in row { challenger.observe_extension(b, bytes, value); } @@ -781,7 +858,7 @@ pub(super) fn constrain_pcs( for matrix in 0..shape.widths[batch].len() { let height = shape.heights[batch][matrix]; let mut per_point = Vec::new(); - for row in opening_rows(algebra, shape, batch, matrix) { + for row in opening_rows(algebra, shape, pinned_rows, batch, matrix) { let opening_idx = opening_cursors.entry(height).or_insert(0); let idx = *opening_idx; *opening_idx += 1; @@ -815,7 +892,12 @@ pub(super) fn constrain_pcs( let x = E::from_base(b, point); let next = zeta.scale(b, Val::two_adic_generator(height - shape.log_blowup)); - [zeta, next].map(|z| z.sub(b, x).inverse(b)) + let mut denoms = + vec![zeta.sub(b, x).inverse(b), next.sub(b, x).inverse(b)]; + if let Some((z0, _)) = pin { + denoms.push(z0.sub(b, x).inverse(b)); + } + denoms }); } for (batch, root) in roots.iter().enumerate() { diff --git a/crates/proof-compression/src/fri/pcs_witness.rs b/crates/proof-compression/src/fri/pcs_witness.rs index 003a250f20..d6238d6d90 100644 --- a/crates/proof-compression/src/fri/pcs_witness.rs +++ b/crates/proof-compression/src/fri/pcs_witness.rs @@ -47,6 +47,8 @@ pub struct ExpandedPcsWitness { pub input_paths: Vec<[Path; 4]>, /// Query-major, then FRI round. pub fri_paths: Vec>, + /// Under stage-1 pinning, claimed values at `z₀` (active circuit -> columns). + pub pinned: Vec>, } fn validate( @@ -138,6 +140,38 @@ fn native_rows( matrices.get(matrix).map(Vec::as_slice) } +fn native_rows_pinned<'a>( + proof: &'a Proof, + shape: &FixedPcsShape, + pinned: Option<&'a [Vec]>, + batch: usize, + matrix: usize, +) -> Option> { + let mut rows: Vec<&'a [ExtVal3]> = + native_rows(proof, batch, matrix)?.iter().map(Vec::as_slice).collect(); + if let Some(pins) = pinned { + match batch { + 0 => { + let pin_row = pins.get(matrix)?; + let main_w = *shape.widths[0].get(matrix)?; + let fixed_w = pin_row.len().checked_sub(main_w)?; + rows.push(&pin_row[fixed_w..]); + }, + 3 => { + let active_pos = *shape.preprocessed.get(matrix)?; + let pin_row = pins.get(active_pos)?; + let fixed_w = *shape.widths[3].get(matrix)?; + if pin_row.len() < fixed_w { + return None; + } + rows.push(&pin_row[..fixed_w]); + }, + _ => {}, + } + } + Some(rows) +} + fn hash_fields(values: impl IntoIterator) -> Digest { let bytes: Vec = values .into_iter() @@ -302,13 +336,19 @@ pub fn expand_pcs_witness( challenger.observe(Val::from_u8(height)); } observe_claims::(&mut challenger, claims); + if system.config.stage_1_pinning() { + return Err( + "ordinary witness expansion does not support stage-1 pinning".into(), + ); + } let (beta, gamma) = sample_lookup_challenges::(&mut challenger); - expand_after_lookup(system, shape, proof, claims, challenger, beta, gamma) + expand_after_lookup(system, shape, proof, claims, challenger, beta, gamma, None) } /// Shared untrusted PCS normalization after the caller replays its protocol's /// lookup transcript. Both single-proof and batch transcripts use this path. +#[allow(clippy::too_many_arguments)] pub(super) fn expand_after_lookup( system: &System, shape: &FixedPcsShape, @@ -317,6 +357,7 @@ pub(super) fn expand_after_lookup( mut challenger: DomainChallenger, beta: ExtVal3, gamma: ExtVal3, + pin: Option<(ExtVal3, &[Vec])>, ) -> Result { if system.config.fri_batching() != FriBatching::Tensor { return Err("Protocol v6 verifier requires FriBatching::Tensor".into()); @@ -324,10 +365,30 @@ pub(super) fn expand_after_lookup( if system.vk_digest != compute_vk_digest::(&system.circuits) { return Err("system vk_digest mismatch".into()); } + if pin.is_some() != shape.stage_1_pinning { + return Err("stage-1 pinning presence mismatch".into()); + } + if let Some((_, pin_rows)) = pin { + let active_indices: Vec = shape + .active + .iter() + .enumerate() + .filter_map(|(ci, &a)| a.then_some(ci)) + .collect(); + if pin_rows.len() != active_indices.len() + || active_indices + .iter() + .zip(pin_rows) + .any(|(&ci, row)| row.len() != system.pinned_width(ci)) + { + return Err("pinned values shape mismatch".into()); + } + } system .verify_shape(proof) .map_err(|e| format!("invalid proof shape: {e:?}"))?; validate(shape, proof)?; + let pinned_rows = pin.map(|(_, rows)| rows); challenger.observe(proof.commitments.stage_2_trace.clone()); for &acc in &proof.intermediate_accumulators { challenger.observe_algebra_element(acc); @@ -337,7 +398,9 @@ pub(super) fn expand_after_lookup( let zeta: ExtVal3 = challenger.sample_algebra_element(); for batch in 0..4 { for matrix in 0..shape.widths[batch].len() { - for row in native_rows(proof, batch, matrix).unwrap() { + for row in native_rows_pinned(proof, shape, pinned_rows, batch, matrix) + .ok_or("pinned OOD row shape mismatch")? + { challenger.observe_algebra_slice(row); } } @@ -427,7 +490,11 @@ pub(super) fn expand_after_lookup( ); let next = zeta * Val::two_adic_generator(height - system.config.log_blowup()); - let denominators: Vec<_> = [zeta, next] + let mut points = vec![zeta, next]; + if let Some((z0, _)) = pin { + points.push(z0); + } + let denominators: Vec<_> = points .into_iter() .map(|z| { (z - x).try_inverse().ok_or("opening point equals query point") @@ -436,7 +503,10 @@ pub(super) fn expand_after_lookup( let (opening_idx, reduced) = reduced_by_height.entry(height).or_insert((0usize, ExtVal3::ZERO)); for (point, opened) in - native_rows(proof, batch, matrix).unwrap().iter().enumerate() + native_rows_pinned(proof, shape, pinned_rows, batch, matrix) + .ok_or("pinned OOD row shape mismatch")? + .into_iter() + .enumerate() { let mut col_acc = ExtVal3::ZERO; for ((&w_col, &at_x), &at_z) in @@ -519,6 +589,7 @@ pub(super) fn expand_after_lookup( query_indices, input_paths, fri_paths, + pinned: pinned_rows.map(|rows| rows.to_vec()).unwrap_or_default(), }) } @@ -623,6 +694,17 @@ impl ExpandedPcsWitness { self.proof.intermediate_accumulators[matrix], )?; } + if inputs.pinned.len() != self.pinned.len() { + return Err("pinned circuit count mismatch".into()); + } + for (wires, values) in inputs.pinned.iter().zip(&self.pinned) { + if wires.len() != values.len() { + return Err("pinned column count mismatch".into()); + } + for (&wire, &value) in wires.iter().zip(values) { + extension(&mut set, wire, value)?; + } + } for (wires, root) in [ (&inputs.commitments.stage1, &self.proof.commitments.stage_1_trace), (&inputs.commitments.stage2, &self.proof.commitments.stage_2_trace), diff --git a/crates/proof-compression/src/fri/plan.rs b/crates/proof-compression/src/fri/plan.rs index b1447d851f..04b34aa2e4 100644 --- a/crates/proof-compression/src/fri/plan.rs +++ b/crates/proof-compression/src/fri/plan.rs @@ -72,7 +72,8 @@ impl VerifierKey { }, system.config.fri_parameters(), system.config.fri_batching(), - ), + ) + .with_stage_1_pinning(system.config.stage_1_pinning()), circuits, preprocessed_commit: system.preprocessed_commit.clone(), preprocessed_indices: system.preprocessed_indices.clone(), @@ -452,6 +453,13 @@ impl<'a> VerifierPlan<'a> { "proof profile exceeds proved htensor cap (Tier-2 shape)", )); } + if profile.envelope == Envelope::Ordinary + && system.config.stage_1_pinning() + { + return Err(VerifierError::Profile( + "stage-1 pinning requires a batch envelope", + )); + } if profile.envelope == Envelope::Ordinary && !profile.message_lengths.is_empty() { @@ -542,13 +550,14 @@ impl<'a> VerifierPlan<'a> { // Calculate external wire counts with checked arithmetic before allocating a circuit. let widths = sum(shape.widths.iter().flatten().copied())?; let ood = sum(shape.widths.iter().enumerate().flat_map(|(batch, ws)| { - ws.iter().map(move |&w| { - w.saturating_mul(if batch == 2 { - EXTENSION_DEGREE - } else { - 2 * EXTENSION_DEGREE - }) - }) + let points = if batch == 2 { + 1 + } else if shape.stage_1_pinning && (batch == 0 || batch == 3) { + 3 + } else { + 2 + }; + ws.iter().map(move |&w| w.saturating_mul(points * EXTENSION_DEGREE)) }))?; let rounds = shape.fri_log_arities.len(); let mut fri_path_depths = Vec::with_capacity(rounds); diff --git a/crates/proof-compression/src/pipeline/root/fixed.rs b/crates/proof-compression/src/pipeline/root/fixed.rs index 3eb7586e84..f420a8acdd 100644 --- a/crates/proof-compression/src/pipeline/root/fixed.rs +++ b/crates/proof-compression/src/pipeline/root/fixed.rs @@ -637,7 +637,7 @@ mod tests { }; let channel = Val::from_u64(MEMSEG); let (system, pk) = System::new( - GoldilocksBlake3V6Config::new(cp, fp), + GoldilocksBlake3V6Config::new(cp, fp).with_stage_1_pinning(true), [(8, 8), (1, 2)].into_iter().map(|(width, height)| CircuitInputs { main_width: width + 3, preprocessed: Some(RowMajorMatrix::new_col(vec![Val::ZERO; height])), @@ -667,7 +667,7 @@ mod tests { ))?; // Unrecognized ROM circuit width must fail closed in `memory_lanes`. let (bad_sys, _) = System::new( - GoldilocksBlake3V6Config::new(cp, fp), + GoldilocksBlake3V6Config::new(cp, fp).with_stage_1_pinning(true), [CircuitInputs { main_width: 4, preprocessed: Some(RowMajorMatrix::new_col(vec![Val::ZERO; 8])), @@ -809,7 +809,7 @@ mod tests { // 1. Non-ROM circuits whose main_width matches scalar (w + 3 = 4) and // vectorized (1 + 8*(1 + 2) = 25) ROM widths must be rejected. let (non_rom_sys, _) = System::new( - GoldilocksBlake3V6Config::new(cp, fp), + GoldilocksBlake3V6Config::new(cp, fp).with_stage_1_pinning(true), [ CircuitInputs { main_width: 4, @@ -835,7 +835,7 @@ mod tests { // Swapping their circuit indices in FixedRoot must be rejected, while // matching indices succeed with distinct lane counts (8 vs 1). let (aliased_sys, _) = System::new( - GoldilocksBlake3V6Config::new(cp, fp), + GoldilocksBlake3V6Config::new(cp, fp).with_stage_1_pinning(true), [ CircuitInputs { main_width: 25, @@ -864,7 +864,7 @@ mod tests { // 3. Duplicate circuits in one verifying key must be rejected. let (dup_sys, _) = System::new( - GoldilocksBlake3V6Config::new(cp, fp), + GoldilocksBlake3V6Config::new(cp, fp).with_stage_1_pinning(true), [ CircuitInputs { main_width: 4, @@ -886,7 +886,7 @@ mod tests { // 4. A circuit mixing distinct MEMSEG widths must be rejected. let (mixed_sys, _) = System::new( - GoldilocksBlake3V6Config::new(cp, fp), + GoldilocksBlake3V6Config::new(cp, fp).with_stage_1_pinning(true), [CircuitInputs { main_width: 4, preprocessed: Some(RowMajorMatrix::new_col(vec![Val::ZERO; 4])), diff --git a/crates/proof-compression/tests/aiur_chain.rs b/crates/proof-compression/tests/aiur_chain.rs index 84565365d8..f1cb68e071 100644 --- a/crates/proof-compression/tests/aiur_chain.rs +++ b/crates/proof-compression/tests/aiur_chain.rs @@ -33,7 +33,7 @@ fn root_input() -> Input { let mut message = vec![one.clone(), Expr::constant(Val::ZERO)]; message.extend((0..16).map(Expr::main)); let (system, key) = System::new( - GoldilocksBlake3V6Config::new(cp, fp), + GoldilocksBlake3V6Config::new(cp, fp).with_stage_1_pinning(true), vec![CircuitInputs { main_width: 16, constraints: vec![Expr::main(0) * Expr::main(0) - Expr::main(1)], diff --git a/crates/proof-compression/tests/aiur_compress_gl.rs b/crates/proof-compression/tests/aiur_compress_gl.rs index c355856e81..cd405904c5 100644 --- a/crates/proof-compression/tests/aiur_compress_gl.rs +++ b/crates/proof-compression/tests/aiur_compress_gl.rs @@ -25,7 +25,7 @@ fn input() -> Input { let mut message = vec![one.clone(), Expr::constant(Val::ZERO)]; message.extend((0..16).map(Expr::main)); let (system, key) = System::new( - GoldilocksBlake3V6Config::new(cp, fp), + GoldilocksBlake3V6Config::new(cp, fp).with_stage_1_pinning(true), vec![CircuitInputs { main_width: 16, constraints: vec![Expr::main(0) * Expr::main(0) - Expr::main(1)], diff --git a/crates/proof-compression/tests/compress_wrap_statement.rs b/crates/proof-compression/tests/compress_wrap_statement.rs index 6ecd6147f5..f70ed0a5ef 100644 --- a/crates/proof-compression/tests/compress_wrap_statement.rs +++ b/crates/proof-compression/tests/compress_wrap_statement.rs @@ -27,7 +27,7 @@ fn root_key(scale: u64) -> Vec { message.extend([Expr::main(0), Expr::main(1)]); message.extend(std::iter::repeat_n(Expr::constant(Val::ZERO), 14)); let (system, _) = System::new( - GoldilocksBlake3V6Config::new(cp, fp), + GoldilocksBlake3V6Config::new(cp, fp).with_stage_1_pinning(true), vec![CircuitInputs { main_width: 2, constraints: vec![relation * Expr::constant(Val::from_u64(scale))], diff --git a/crates/proof-compression/tests/integration/pipeline_root.rs b/crates/proof-compression/tests/integration/pipeline_root.rs index 9ad719bdda..f76bb4b532 100644 --- a/crates/proof-compression/tests/integration/pipeline_root.rs +++ b/crates/proof-compression/tests/integration/pipeline_root.rs @@ -62,7 +62,7 @@ fn root_system_with( // A small relation carrying the same 18-word shape as an aggregate call. // Its trusted key accepts any values; the caller selects the expected claim. let (system, pk) = System::new( - GoldilocksBlake3V6Config::new(cp, fp), + GoldilocksBlake3V6Config::new(cp, fp).with_stage_1_pinning(true), [CircuitInputs { main_width: 19, preprocessed: Some(RowMajorMatrix::new_col(vec![Val::ZERO; 2])), diff --git a/crates/stark-key/src/lib.rs b/crates/stark-key/src/lib.rs index 488204c02a..245848aed9 100644 --- a/crates/stark-key/src/lib.rs +++ b/crates/stark-key/src/lib.rs @@ -29,9 +29,10 @@ //! u16 LE fri_batching = 1 (1 = Tensor; rejects Horner!) //! 32 bytes vk_digest (BLAKE3 derive_key("multi-stark/v6/vk"), //! recomputed & checked on decode) -//! 7 x u16 LE commitment + FRI parameters (log_blowup, cap_height, +//! 8 x u16 LE commitment + FRI parameters (log_blowup, cap_height, //! log_final_poly_len, max_log_arity, num_queries, -//! commit_proof_of_work_bits, query_proof_of_work_bits) +//! commit_proof_of_work_bits, query_proof_of_work_bits, +//! stage_1_pinning: 0 or 1; production keys require 1) //! u16 circuit count //! PER-CIRCUIT RECORDS (circuit count times; no outer length prefix) //! u16 main_width, u16 preprocessed_width, u32 preprocessed_height, @@ -91,6 +92,8 @@ pub const PROTOCOL_VERSION: u16 = 6; pub const EXTENSION_DEGREE: u16 = 3; /// Wire FRI batching tag required by production Ix (`FriBatching::Tensor`). pub const FRI_BATCHING_TENSOR: u16 = 1; +/// Wire stage-1 pinning flag required by production Ix (Release 0.5). +pub const STAGE_1_PINNING_REQUIRED: u16 = 1; /// Sentinel for `None` in the preprocessed-index trailer. const NO_PREP_INDEX: u16 = u16::MAX; @@ -606,6 +609,12 @@ pub fn try_to_bytes_named( "vk header", "query_proof_of_work_bits", )?; + push_u16( + &mut buf, + usize::from(system.config.stage_1_pinning()), + "vk header", + "stage_1_pinning", + )?; push_u16(&mut buf, system.circuits.len(), "vk header", "circuit_count")?; for (ci, circuit) in system.circuits.iter().enumerate() { let label = circuit_label(ci, circuit_names); @@ -1085,7 +1094,22 @@ fn decode( commit_proof_of_work_bits: r.u16()? as usize, query_proof_of_work_bits: r.u16()? as usize, }; + let stage_1_pinning = match r.u16()? { + 0 => false, + 1 => true, + v => { + return Err(format!( + "invalid stage_1_pinning flag {v}: expected 0 or 1" + )); + }, + }; if let Some(shape) = floor { + if !stage_1_pinning { + return Err( + "unsupported stage_1_pinning 0: production Protocol v6 keys require stage_1_pinning=1" + .into(), + ); + } security::check_with_shape(&commitment_parameters, &fri_parameters, shape)?; } else { // The waiver lifts the security floor only. Proof-of-work counts above @@ -1217,7 +1241,8 @@ fn decode( } r.done("vk")?; let system = System { - config: AiurConfig::new(commitment_parameters, fri_parameters), + config: AiurConfig::new(commitment_parameters, fri_parameters) + .with_stage_1_pinning(stage_1_pinning), circuits, preprocessed_commit, preprocessed_indices, @@ -1275,7 +1300,7 @@ mod tests { ..Default::default() }, ]; - System::new(AiurConfig::new(cp, fp), inputs).0 + System::new(AiurConfig::new(cp, fp).with_stage_1_pinning(true), inputs).0 } fn encoded() -> Vec { @@ -1463,6 +1488,7 @@ mod tests { fp.num_queries, fp.commit_proof_of_work_bits, fp.query_proof_of_work_bits, + usize::from(STAGE_1_PINNING_REQUIRED), 1usize, // n_circuits ] { put_u16(&mut buf, v); @@ -1746,6 +1772,8 @@ mod tests { (2, u16::MAX, "log_final_poly_len"), (3, 0, "max_log_arity"), (3, 2, "max_log_arity"), + (7, 0, "stage_1_pinning"), + (7, 2, "stage_1_pinning"), ] { let bytes = with_header(field, value); let err = from_bytes(&bytes) diff --git a/crates/stark-key/src/range.rs b/crates/stark-key/src/range.rs index 9d76d66cb2..54d716ba7b 100644 --- a/crates/stark-key/src/range.rs +++ b/crates/stark-key/src/range.rs @@ -20,13 +20,17 @@ type AiurProof = multi_stark::batch::BatchProof; pub const RANGE_STATEMENT_TAG: u8 = 0x52; /// The batch preamble as the in-circuit stream readers expect it: the -/// headers vector, then the messages vector — the prefix of the batch's -/// own wire encoding. +/// headers vector, then the messages vector, and (under stage-1 pinning) the +/// claimed values at `z₀` (`pinned`). Hashing these bytes fixes `z₀`, `β`, +/// `γ`, and every shard's pinned evaluations across range-sum recursion nodes. pub fn preamble_bytes(proof: &AiurProof) -> Result, String> { - encode_to_vec( - &proof.preamble, - bincode::config::standard().with_little_endian().with_fixed_int_encoding(), - ) + let cfg = + bincode::config::standard().with_little_endian().with_fixed_int_encoding(); + if proof.pinned.is_empty() { + encode_to_vec(&proof.preamble, cfg) + } else { + encode_to_vec((&proof.preamble, &proof.pinned), cfg) + } .map_err(|e| format!("batch preamble serialization failed: {e}")) } diff --git a/crates/stark-key/src/security.rs b/crates/stark-key/src/security.rs index 1f48688c0e..579c579bc3 100644 --- a/crates/stark-key/src/security.rs +++ b/crates/stark-key/src/security.rs @@ -62,6 +62,11 @@ pub const EXTENSION_DEGREE_V6: usize = 3; /// Protocol version tag for the `v6` `Fp^3` + BLAKE3 `derive_key` profile. pub const PROTOCOL_VERSION_V6: usize = 6; +/// Stage-1 pinning flag required for production Release 0.5 Protocol `v6` keys +/// (`1` = enabled, pinning stage-1 & active preprocessed columns at `z0` before +/// sampling lookup challenges `beta`, `gamma`). +pub const STAGE_1_PINNING_V6: usize = 1; + /// Target provable security floor (in bits) for the `v6` 128-bit profile /// (both unique-decoding and finite-`m` Johnson list-decoding regimes). pub const MIN_PROVABLE_SECURITY_BITS_128: usize = 128; diff --git a/crates/stark-shrinker/src/aiur_shrinker.rs b/crates/stark-shrinker/src/aiur_shrinker.rs index 541bdd5da9..e356020789 100644 --- a/crates/stark-shrinker/src/aiur_shrinker.rs +++ b/crates/stark-shrinker/src/aiur_shrinker.rs @@ -3172,8 +3172,10 @@ mod tests { )], ..Default::default() }]; - let (system, pk) = - System::new(GoldilocksBlake3V6Config::new(cp, fp), inputs); + let (system, pk) = System::new( + GoldilocksBlake3V6Config::new(cp, fp).with_stage_1_pinning(true), + inputs, + ); let claims = vec![vec![Val::ONE, Val::ZERO, Val::from_u64(3), Val::from_u64(9)]]; let witness = SystemWitness::from_stage_1( diff --git a/crates/stark-shrinker/src/compact_codec.rs b/crates/stark-shrinker/src/compact_codec.rs index 79dfd38c33..50aaa192d8 100644 --- a/crates/stark-shrinker/src/compact_codec.rs +++ b/crates/stark-shrinker/src/compact_codec.rs @@ -9,6 +9,7 @@ //! or the underlying `Proof` verified by `System::verify_multiple_claims`. use multi_stark::{ + batch::{BatchPreamble, BatchProof, ShardHeader}, config::ProofConfig, expr::Source, p3_adapter::zk::{HidingMultiProof, ZK_LEAF_SALT_BYTES}, @@ -621,11 +622,101 @@ pub fn decode_v6( bytes: &[u8], ) -> Result, String> { let mut cur = Cursor::new(bytes); + let proof = decode_v6_from_cursor(system, &mut cur)?; + cur.finish()?; + Ok(proof) +} + +/// Canonical fixed-shape compact encoding of a 1-shard transparent Protocol `v6` +/// pinned `BatchProof` (proof followed by its fixed-shape `ShardPins`). +pub fn encode_v6_pinned( + system: &System, + batch: &BatchProof, +) -> Result, String> { + if batch.proofs.len() != 1 + || batch.preamble.headers.len() != 1 + || !batch.preamble.messages.is_empty() + || batch.pinned.len() != 1 + { + return Err( + "compact codec: pinned v6 batch must have 1 shard and no messages".into(), + ); + } + let proof = &batch.proofs[0]; + let shard_pins = &batch.pinned[0]; + let active_indices: Vec = proof + .active + .iter() + .enumerate() + .filter_map(|(ci, &a)| a.then_some(ci)) + .collect(); + if shard_pins.len() != active_indices.len() { + return Err("compact codec: pinned circuit count mismatch".into()); + } + let mut out = encode_v6(system, proof)?; + for (&ci, row) in active_indices.iter().zip(shard_pins) { + let expected = system.pinned_width(ci); + if row.len() != expected { + return Err(format!( + "compact codec: circuit {ci} pinned width {} != expected {expected}", + row.len() + )); + } + for &val in row { + write_ext3(&mut out, val); + } + } + Ok(out) +} + +/// Fail-closed canonical fixed-shape decoder for a 1-shard transparent Protocol +/// `v6` pinned `BatchProof`. Reconstructs the single-shard preamble from the +/// decoded proof header and the caller-supplied `claims`. +pub fn decode_v6_pinned( + system: &System, + claims: &[Vec], + bytes: &[u8], +) -> Result, String> { + let mut cur = Cursor::new(bytes); + let proof = decode_v6_from_cursor(system, &mut cur)?; + let active_indices: Vec = proof + .active + .iter() + .enumerate() + .filter_map(|(ci, &a)| a.then_some(ci)) + .collect(); + let mut shard_pins = Vec::with_capacity(active_indices.len()); + for &ci in &active_indices { + let expected = system.pinned_width(ci); + let mut row = Vec::with_capacity(expected); + for _ in 0..expected { + row.push(cur.read_ext3()?); + } + shard_pins.push(row); + } + cur.finish()?; + let header = ShardHeader { + active: proof.active.clone(), + stage_1_trace: proof.commitments.stage_1_trace.clone(), + log_degrees: proof.log_degrees.clone(), + claims: claims.to_vec(), + }; + Ok(BatchProof { + preamble: BatchPreamble { headers: vec![header], messages: Vec::new() }, + proofs: vec![proof], + pinned: vec![shard_pins], + }) +} + +fn decode_v6_from_cursor( + system: &System, + cur: &mut Cursor<'_>, +) -> Result, String> { let version = cur.read_u8()?; if version != CODEC_VERSION { return Err(format!("compact codec: unsupported version {version}")); } - let active = decode_active_bits(&mut cur, system.circuits.len())?; + let active = decode_active_bits(cur, system.circuits.len())?; let num_active = active.iter().filter(|&&a| a).count(); let log_degrees = cur.take(num_active)?.to_vec(); let layout = compute_layout( @@ -686,7 +777,7 @@ pub fn decode_v6( let mut input_openings = Vec::with_capacity(layout.batch_widths.len()); for widths in &layout.batch_widths { - let opened_values = read_input_rows(&mut cur, layout.num_queries, widths)?; + let opened_values = read_input_rows(cur, layout.num_queries, widths)?; let opening_proof = cur.read_pruned_hashes()?; input_openings.push(BatchMultiOpening { opened_values, opening_proof }); } @@ -710,7 +801,6 @@ pub fn decode_v6( }); } - cur.finish()?; Ok(Proof { active, commitments, diff --git a/crates/stark-shrinker/src/lib.rs b/crates/stark-shrinker/src/lib.rs index 113e3f502e..05b522d9c9 100644 --- a/crates/stark-shrinker/src/lib.rs +++ b/crates/stark-shrinker/src/lib.rs @@ -773,8 +773,10 @@ mod tests { )], ..Default::default() }]; - let (system, pk) = - System::new(GoldilocksBlake3V6Config::new(cp, fp), inputs); + let (system, pk) = System::new( + GoldilocksBlake3V6Config::new(cp, fp).with_stage_1_pinning(true), + inputs, + ); let claims = vec![vec![Val::ONE, Val::ZERO, Val::from_u64(3), Val::from_u64(9)]]; let witness = SystemWitness::from_stage_1( diff --git a/crates/stark-shrinker/src/plonkish.rs b/crates/stark-shrinker/src/plonkish.rs index 4da3feb9b0..403a5c3a1d 100644 --- a/crates/stark-shrinker/src/plonkish.rs +++ b/crates/stark-shrinker/src/plonkish.rs @@ -30,7 +30,7 @@ use ix_proof_compression::{ pipeline::FixedRoot, }; use multi_stark::{ - batch::BatchProof, + batch::{BatchPreamble, BatchProof}, cache::{CacheMode, CacheableProofConfig, ProverKeyCache}, config::{PcsData, ProofConfig}, expr::{Expr, RowOffset, Source}, @@ -1507,7 +1507,7 @@ fn next_hop_verifier_plan<'a>( }) .collect::>()?; let profile = ProofProfile { - envelope: FriEnvelope::Ordinary, + envelope: FriEnvelope::SingleBatch, active: vec![true; num_circuits], log_degrees, claim_lengths: schema.template.iter().map(Vec::len).collect(), @@ -1546,6 +1546,37 @@ fn build_plan_circuit( .map_err(|e| format!("verifier circuit build failed: {e}")) } +fn prove_one_shard_pinned( + system: &System, + key: &ProverKey, + claims: &[&[Val]], + stage1: multi_stark::prover::Stage1, +) -> Result, String> { + let header = stage1.header(claims); + let preamble = BatchPreamble { headers: vec![header], messages: Vec::new() }; + let pinning = system.pinning_transcript(&preamble); + let retained = [Some(stage1)]; + let pins = system + .batch_pins( + key, + &preamble, + pinning.point(), + &retained, + |_| -> Result, String> { + unreachable!("shard 0 is retained") + }, + ) + .map_err(|e| format!("v6 pinned batch_pins failed: {e}"))?; + let transcript = pinning.absorb(pins.values()); + let [Some(stage1)] = retained else { + unreachable!("shard 0 is retained") + }; + let proof = system + .prove_batch_shard(key, stage1, claims, &transcript, &pins, 0) + .map_err(|e| format!("v6 pinned prove_batch_shard failed: {e:?}"))?; + Ok(BatchProof { preamble, proofs: vec![proof], pinned: pins.into_values() }) +} + #[allow(clippy::too_many_arguments)] fn prove_intermediate_hop( compiled: MultiStarkCircuit, @@ -1571,7 +1602,8 @@ fn prove_intermediate_hop( hop_params.fri(), FriBatching::Tensor, device, - ); + ) + .with_stage_1_pinning(true); let (sys, key) = build_system_without_preprocessed(config, definitions, cache, caller_key); let stage1 = if let Some(layout) = merged @@ -1607,13 +1639,13 @@ fn prove_intermediate_hop( s1 }; let refs: Vec<&[Val]> = claims.iter().map(Vec::as_slice).collect(); - let proof = sys.prove_committed(&key, &refs, stage1); + let batch = prove_one_shard_pinned(&sys, &key, &refs, stage1)?; drop(key); #[cfg(feature = "cuda")] multi_stark::cuda::release_device_memory(); ix_common::release_host_memory(); sys - .verify_multiple_claims(&refs, &proof) + .verify_one_shard(&refs, &batch) .map_err(|e| format!("hop {hop} self-verify failed: {e:?}"))?; let sys_vk_digest = sys.vk_digest; @@ -1621,6 +1653,7 @@ fn prove_intermediate_hop( sys.preprocessed_commit.as_ref().map(|c| c.roots().to_vec()); let hop_vk = VerifierKey::new(sys); let (plan, stmt_schema, profile) = next_hop_verifier_plan(&hop_vk, schema)?; + let proof = &batch.proofs[0]; if proof.active != profile.active || proof.log_degrees != profile.log_degrees { return Err(format!( @@ -1630,7 +1663,7 @@ fn prove_intermediate_hop( let (next_circuit, inputs) = build_plan_circuit(&plan, stmt_schema, options) .map_err(|e| format!("hop {} {e}", hop + 1))?; let expanded = plan - .expand_witness(ProofEnvelope::Ordinary { proof: &proof, claims: &claims }) + .expand_witness(ProofEnvelope::SingleBatch(&batch)) .map_err(|e| format!("hop {} witness expansion failed: {e}", hop + 1))?; let mut witness = next_circuit.witness(); inputs @@ -2078,7 +2111,8 @@ impl OuterSystem { params.fri(), FriBatching::Tensor, device, - ); + ) + .with_stage_1_pinning(true); let (system, key) = build_system_without_preprocessed( config, definitions, @@ -2192,22 +2226,22 @@ impl OuterSystem { drop(assignment); s1 }; - let proof = system.prove_committed(&key, &refs, stage1); + let batch = prove_one_shard_pinned(system, &key, &refs, stage1)?; drop(key); #[cfg(feature = "cuda")] multi_stark::cuda::release_device_memory(); ix_common::release_host_memory(); system - .verify_multiple_claims(&refs, &proof) - .map_err(|e| format!("v6 self-verify failed: {e:?}"))?; - let compact_bytes = compact_codec::encode_v6(system, &proof)?; - let breakdown = analyze_v6(&proof, compact_bytes.len())?; + .verify_one_shard(&refs, &batch) + .map_err(|e| format!("v6 pinned self-verify failed: {e:?}"))?; + let compact_bytes = compact_codec::encode_v6_pinned(system, &batch)?; + let breakdown = analyze_v6(&batch.proofs[0], compact_bytes.len())?; let bytes = if compact_encoding { compact_bytes } else { - proof + batch .to_bytes() - .map_err(|e| format!("v6 proof encode failed: {e}"))? + .map_err(|e| format!("v6 pinned proof encode failed: {e}"))? }; Ok((bytes, breakdown)) }, @@ -2283,24 +2317,31 @@ impl OuterSystem { let refs: Vec<&[Val]> = claims.iter().map(Vec::as_slice).collect(); match self { Self::Transparent { system, .. } => { - let proof = if compact_encoding { - let p = compact_codec::decode_v6(system, proof_bytes)?; - let re = compact_codec::encode_v6(system, &p)?; + let batch = if compact_encoding { + let b = compact_codec::decode_v6_pinned(system, claims, proof_bytes)?; + let re = compact_codec::encode_v6_pinned(system, &b)?; if re != proof_bytes { - return Err("noncanonical compact v6 proof bytes".into()); + return Err("noncanonical compact v6 pinned proof bytes".into()); } - p + b } else { - let p = Proof::::from_bytes(proof_bytes) - .map_err(|e| format!("v6 proof decode failed: {e}"))?; - let re = p + let b = + BatchProof::::from_bytes(proof_bytes) + .map_err(|e| format!("v6 pinned proof decode failed: {e}"))?; + let re = b .to_bytes() - .map_err(|e| format!("v6 proof re-encode failed: {e}"))?; + .map_err(|e| format!("v6 pinned proof re-encode failed: {e}"))?; if re != proof_bytes { - return Err("noncanonical or trailing v6 proof bytes".into()); + return Err( + "noncanonical or trailing v6 pinned proof bytes".into(), + ); } - p + b }; + let proof = batch + .proofs + .first() + .ok_or("v6 pinned proof has no shard proof")?; check_outer_row_and_lookup_bounds( system, &proof.active, @@ -2317,8 +2358,8 @@ impl OuterSystem { max_htensor_volume, )?; system - .verify_multiple_claims(&refs, &proof) - .map_err(|e| format!("v6 STARK verification failed: {e:?}")) + .verify_one_shard(&refs, &batch) + .map_err(|e| format!("v6 pinned STARK verification failed: {e:?}")) }, Self::Zk { system, .. } => { let proof = if compact_encoding { @@ -2767,7 +2808,8 @@ impl PlonkishCircuitVerifier { hop_params.fri(), FriBatching::Tensor, None, - ); + ) + .with_stage_1_pinning(true); let (sys, key) = build_system_without_preprocessed( config, definitions, @@ -3215,7 +3257,8 @@ pub fn derive_circuit_hop_statistics_with_cache_mode( hop_params.fri(), FriBatching::Tensor, None, - ); + ) + .with_stage_1_pinning(true); let (sys, key) = build_system_without_preprocessed( config, definitions, @@ -3597,7 +3640,8 @@ pub fn shrink_single_batch_2hop( hop1_params.fri(), FriBatching::Tensor, device, - ); + ) + .with_stage_1_pinning(true); let (sys1, key1) = build_system_without_preprocessed(config1, defs1, cache.as_ref(), None); let stage1 = if let Some(layout) = merged1.as_ref() @@ -3631,15 +3675,15 @@ pub fn shrink_single_batch_2hop( drop(compiled1); drop(assignment1); let refs1: Vec<&[Val]> = claims1.iter().map(Vec::as_slice).collect(); - let hop1_proof = sys1.prove_committed(&key1, &refs1, stage1); + let hop1_batch = prove_one_shard_pinned(&sys1, &key1, &refs1, stage1)?; drop(key1); #[cfg(feature = "cuda")] multi_stark::cuda::release_device_memory(); ix_common::release_host_memory(); sys1 - .verify_multiple_claims(&refs1, &hop1_proof) + .verify_one_shard(&refs1, &hop1_batch) .map_err(|e| format!("hop1 self-verify failed: {e:?}"))?; - let hop1_bytes = hop1_proof + let hop1_bytes = hop1_batch .to_bytes() .map_err(|e| format!("hop1 serialize failed: {e}"))? .len(); @@ -3657,7 +3701,7 @@ pub fn shrink_single_batch_2hop( }) .collect::>()?; let hop2_profile = ProofProfile { - envelope: FriEnvelope::Ordinary, + envelope: FriEnvelope::SingleBatch, active: vec![true; hop1_vk.system().circuits.len()], log_degrees: hop1_log_degrees, claim_lengths: claims1.iter().map(Vec::len).collect(), @@ -3683,10 +3727,7 @@ pub fn shrink_single_batch_2hop( build_plan_circuit(&plan2, hop2_stmt_schema, hop2_options) .map_err(|e| format!("hop2 {e}"))?; let expanded2 = plan2 - .expand_witness(ProofEnvelope::Ordinary { - proof: &hop1_proof, - claims: &claims1, - }) + .expand_witness(ProofEnvelope::SingleBatch(&hop1_batch)) .map_err(|e| format!("hop2 witness expansion failed: {e}"))?; let mut witness2 = circuit2.witness(); inputs2 @@ -4729,7 +4770,7 @@ mod tests { }; let channel = Val::from_u64(MEMSEG); let (system, pk) = System::new( - GoldilocksBlake3V6Config::new(cp, fp), + GoldilocksBlake3V6Config::new(cp, fp).with_stage_1_pinning(true), [(2usize, 4usize), (1, 2)].into_iter().map(|(width, height)| { CircuitInputs { main_width: width + 3, diff --git a/crates/stark-verifier-native/src/main.rs b/crates/stark-verifier-native/src/main.rs index a47d5e8a15..31f2f15bfa 100644 --- a/crates/stark-verifier-native/src/main.rs +++ b/crates/stark-verifier-native/src/main.rs @@ -159,7 +159,10 @@ fn fixture( )], ..Default::default() }]; - let (system, pk) = System::new(GoldilocksBlake3V6Config::new(cp, fp), inputs); + let (system, pk) = System::new( + GoldilocksBlake3V6Config::new(cp, fp).with_stage_1_pinning(true), + inputs, + ); let rows = 1usize << log_rows; let mut values = Vec::with_capacity(rows * columns); for row in 0..rows { diff --git a/crates/stark-verifier/examples/claim_fixture.rs b/crates/stark-verifier/examples/claim_fixture.rs index 89c7f17f25..87a4615f3d 100644 --- a/crates/stark-verifier/examples/claim_fixture.rs +++ b/crates/stark-verifier/examples/claim_fixture.rs @@ -38,7 +38,10 @@ fn main() -> Result<(), Box> { lookups: vec![Lookup::pull(one, lookup)], ..Default::default() }]; - let (system, pk) = System::new(GoldilocksBlake3V6Config::new(cp, fp), inputs); + let (system, pk) = System::new( + GoldilocksBlake3V6Config::new(cp, fp).with_stage_1_pinning(true), + inputs, + ); let args: Vec<_> = args.into_iter().map(Val::from_u64).collect(); let mut claim = vec![Val::ONE, Val::ZERO]; claim.extend(&args); diff --git a/crates/stark-verifier/src/compress_wrap.rs b/crates/stark-verifier/src/compress_wrap.rs index 74c774fcdf..debae3de0a 100644 --- a/crates/stark-verifier/src/compress_wrap.rs +++ b/crates/stark-verifier/src/compress_wrap.rs @@ -1542,7 +1542,10 @@ mod tests { ..Default::default() }]; let (system, pk) = - System::new(GoldilocksBlake3V6Config::new(cp, fp), inputs); + System::new( + GoldilocksBlake3V6Config::new(cp, fp).with_stage_1_pinning(true), + inputs, + ); let mut words = (0..16).map(Val::from_u64).collect::>(); words[0] = Val::from_u64(3); words[1] = Val::from_u64(9); diff --git a/crates/stark-verifier/src/main.rs b/crates/stark-verifier/src/main.rs index 54e10e85f7..c4f491475c 100644 --- a/crates/stark-verifier/src/main.rs +++ b/crates/stark-verifier/src/main.rs @@ -78,7 +78,10 @@ fn fixture( lookups: vec![Lookup::pull(one, message)], ..Default::default() }]; - let (system, pk) = System::new(GoldilocksBlake3V6Config::new(cp, fp), inputs); + let (system, pk) = System::new( + GoldilocksBlake3V6Config::new(cp, fp).with_stage_1_pinning(true), + inputs, + ); let x = Val::from_u64(3) * multiplier; let y = Val::from_u64(9) * multiplier; let mut claim = vec![Val::ONE, Val::ZERO, x, y]; diff --git a/crates/stark-verifier/tests/multi_stark_fixtures.rs b/crates/stark-verifier/tests/multi_stark_fixtures.rs index 31b1e87fd1..02c8378e0c 100644 --- a/crates/stark-verifier/tests/multi_stark_fixtures.rs +++ b/crates/stark-verifier/tests/multi_stark_fixtures.rs @@ -177,6 +177,14 @@ fn wire_verify_system( assert_eq!(c.read_u16_le()?, expected_fp.num_queries); assert_eq!(c.read_u16_le()?, expected_fp.commit_proof_of_work_bits); assert_eq!(c.read_u16_le()?, expected_fp.query_proof_of_work_bits); + assert_eq!( + c.read_u16_le()?, + usize::from( + ::stage_1_pinning( + &expected_system.config + ) + ) + ); let circuit_count = c.read_u16_le()?; assert_eq!(circuit_count, expected_system.circuits.len()); @@ -449,6 +457,21 @@ fn wire_verify_batch_proof( assert_opened_round_eq(&s2_opened, &exp_p.stage_2_opened_values); } + if !expected.pinned.is_empty() { + let pinned = c.read_vec(|cur| { + cur.read_vec(|cur2| cur2.read_vec(WireCursor::read_ef)) + })?; + assert_eq!(pinned.len(), expected.pinned.len()); + for (got_shard, exp_shard) in pinned.iter().zip(&expected.pinned) { + assert_eq!(got_shard.len(), exp_shard.len()); + for (got_row, exp_row) in got_shard.iter().zip(exp_shard) { + let exp_triples: Vec<[u64; 3]> = + exp_row.iter().copied().map(ef_to_triple).collect(); + assert_eq!(got_row, &exp_triples); + } + } + } + c.ensure_eof()?; Ok(()) } @@ -595,7 +618,10 @@ fn two_circuit_system_ordered( }; let circuits = if prep_first { vec![c1, c0] } else { vec![c0, c1] }; - System::new(GoldilocksBlake3V6Config::new(cp, fp), circuits) + System::new( + GoldilocksBlake3V6Config::new(cp, fp).with_stage_1_pinning(true), + circuits, + ) } fn c0_trace() -> RowMajorMatrix { @@ -873,7 +899,7 @@ fn generate_and_verify_multi_stark_fixtures() { let sel = Expr::main(2); let one = Expr::constant(Val::ONE); let (sys_np, pk_np) = System::new( - GoldilocksBlake3V6Config::new(cp, fp), + GoldilocksBlake3V6Config::new(cp, fp).with_stage_1_pinning(true), vec![CircuitInputs { main_width: 3, constraints: vec![ @@ -950,7 +976,7 @@ fn generate_and_verify_multi_stark_fixtures() { let sel_low = Expr::main(2); let one_low = Expr::constant(Val::ONE); let (sys_low, pk_low) = System::new( - GoldilocksBlake3V6Config::new(cp_low, fp_low), + GoldilocksBlake3V6Config::new(cp_low, fp_low).with_stage_1_pinning(true), vec![CircuitInputs { main_width: 3, constraints: vec![ @@ -1021,7 +1047,7 @@ fn generate_and_verify_multi_stark_fixtures() { let memseg = Expr::constant(Val::from_u64(16)); let width_one = Expr::constant(Val::ONE); let (sys_ms, pk_ms) = System::new( - GoldilocksBlake3V6Config::new(cp, fp), + GoldilocksBlake3V6Config::new(cp, fp).with_stage_1_pinning(true), vec![CircuitInputs { main_width: 3, constraints: vec![ diff --git a/docs/endpoint-security-review.md b/docs/endpoint-security-review.md index 72f36e6287..23717dd86e 100644 --- a/docs/endpoint-security-review.md +++ b/docs/endpoint-security-review.md @@ -21,13 +21,14 @@ research on 2026-11-25 and is cited in [Sources](#sources). ## Summary -- **Security level of each endpoint, taking the minimum over its components:** +- **Security level of each endpoint, taking the minimum over its components (updated for Release `0.5` pinned Protocol `v6`):** - | Endpoint | Classical level | Limited by | - |---|---|---| - | Native STARK (`--stark-128`) | about 127.7 bits | 256-bit digest | - | BLS12-381 KZG | about 113.4 bits | Cheon's attack on the setup | - | BN254 KZG | about 100 bits | field sieve on the pairing target group | + | Endpoint | Classical level | Post-Quantum (QROM) | Limited by | + |---|---|---|---| + | Transparent Native STARK (`--stark-128`, pinned `v6`) | **≥ 127.71 bits** (certified ideal sponge + keyed byte-level) | **≥ 64 bits** (machine-checked Zhandry QROM-Q1) | 256-bit digest (classical); `ε_rbr ≤ (3/4)/2^133` over `Fp^3` (QROM) | + | Hiding Native STARK (`--stark-128-zk`, `v6-zk`) | ~127.7 bits (ROM HVZK + Johnson constraint) | Out of Release 0.5 QROM scope | Rejected by `Profile.verifyBytesPinned` (`zk = true`) | + | BLS12-381 KZG | about 113.4 bits | **0 bits** (Shor) | Cheon's attack on the setup | + | BN254 KZG | about 100 bits | **0 bits** (Shor) | field sieve on the pairing target group | - **Recommendation.** Make the native STARK endpoint the basis of the 128-bit claim and of the end-to-end formal argument. Label the two KZG endpoints as @@ -393,7 +394,17 @@ In Ix, the Lean verifier model is proved to refine CertiFRI's tensor batch verifier under two explicit residual hypotheses, C1 (`shapeOk`) and C6 (the opening check) (`Ix/Cert/MultiStark/VerifierRefinement`). -### Remaining gaps for a machine-checked 128-bit claim +### Release `0.5` Resolution of the Gaps Above + +Release `0.5` (`ap/v6-qrom-0.5`, `CertiFRI` `14f7a315bf`, `Ix/Cert/Release05/{SecurityAudit,ClosureManifest}.lean`, and `Ix/Cert/MultiStark/PinnedVerifier.lean`) resolves gaps 1, 2, 4 (on the pure-Lean verification path), 5 (byte-level keyed RO for `Profile.verifyBytesPinned`), and 6 for **transparent Protocol `v6` + Stage-1 pinning**: + +1. **Multi-shard Johnson-regime integer LogUp balance is proved** via mandatory Stage-1 pinning (`stage_1_pinning = 1`) at tightened `ε_rbr ≤ (3/4)/2^133` for both inner binary `v6` (`(2, 128, 0, 20)`, `L = 7`) and transparent EP1 `compact400KBBalanced` (`(4, 58, 0, 28)`, 8-ary, `L = 13`). +2. **Concrete system-size, degree, tensor-challenge-cap, and `< p` balance ceilings are kernel-discharged** across `ixvm-2p23` (64 & 4,096 shards), `aggr-2p22` (16 shards), `rec-2p22` (1 shard), and `ep1-v6-hop4` (1 shard, 8-ary) in `Ix/Cert/Release05/SecurityAudit.lean` (zero `native_decide`, strictly `[propext, Classical.choice, Quot.sound]`). +3. **Pure-Lean `ix verify` and `verify-multistark` execute `CertiFri.Stark.Profile.verifyBytesPinned` directly** (zero Mathlib, zero Rust FFI) alongside Ix's `validate_preamble` policy (`MEMSEG = 16` closure pairs, `K`-lane `2^39` weighted row bound, `stage_1_pinning = 1`, security floor). +4. **Unconditional 64-bit QROM post-quantum soundness is machine-checked** (Zhandry compressed oracle `ForgePinned ≤ ((Q+Nv)/2^64)^2` + Zhandry Lemma 5 standard-QRO equivalence `stdQro64_*`), matching/beating Ethereum LeanVM's `125b / 62b`. +5. **Remaining honest scope boundaries:** 32-byte `BLAKE3-256` is hash-limited at `127.71b` classical (never `128.0b`) and `84.0b` BHT QROM; hiding `v6-zk` (`--stark-128-zk`) and pairing Endpoints 2 & 3 (`0b` PQ) remain outside Release `0.5` PQ scope; Rust provers/verifiers remain differential/CI tested rather than extracted from Lean. + +### Remaining gaps (historical `jcb/ixcc` baseline before Release `0.5`) In order of importance, from CertiFRI's `TODO.md` and Ix's own docs: diff --git a/docs/resource-checking.md b/docs/resource-checking.md index 021afd3670..0ebd9f9d7e 100644 --- a/docs/resource-checking.md +++ b/docs/resource-checking.md @@ -14,34 +14,36 @@ modes. ## Surface syntax (`open scoped Ix.Modes`) Import `Ix.Compile.SourceContract.Elab` and opt in locally with -`open scoped Ix.Modes`. All mode keywords are parsed with -`atomic ("@" >> checkNoWsBefore ... >> nonReservedSymbol w)`, adding **zero** +`open scoped Ix.Modes`. All mode blocks are parsed with +`atomic ("@[" >> sepBy1 ... "," >> "]")` and `nonReservedSymbol`, adding **zero** entries to Lean's `TokenTable` so `@unique_fn`, `@uniqueId`, `@id`, `@&`, `(unique x : Nat)`, `let @Prod.mk _ _ a b := p`, and `let borrow v := owner + v` remain unaffected. -* **Binder modes (7, composable, order-insensitive)** in `(...)`, `{...}`, - `⦃...⦄`, `[...]` (multi-name groups `(@unique x y : T)` and optional `: T` in - `fun` supported): unmarked (`many`), `@borrowed`, `@unique`, - `@unique @borrowed` / `@borrowed @unique`, `@once`, - `@once @borrowed` / `@borrowed @once`, `@erased`. Illegal pairs (`@erased` - with anything, `@once @unique`, duplicates) are rejected at elaboration. +* **Binder modes (7, composable, order-insensitive)** immediately after `(`, `{`, + `⦃`/`{{`, or `[` (allowing spaces, tabs, and linebreaks; multi-name groups + `(@[unique] x y : T)` and optional `: T` in `fun` supported): unmarked (`many`), + `@[borrowed]`, `@[unique]`, `@[unique, borrowed]` / `@[borrowed, unique]`, + `@[once]`, `@[once, borrowed]` / `@[borrowed, once]`, `@[erased]` (adjacent + blocks like `@[unique] @[borrowed]` are also accepted). Illegal pairs + (`@[erased]` with anything, `@[once, unique]`, duplicates) and mid-group + placement (`(a @[unique] b : T)`) are rejected. * **Result modes (4)** after `:` in `def`/`abbrev`/`opaque`/`axiom`, after - `→`/`->`, or after `∀ ...,`: unmarked (`shared`), `@borrowed`, `@unique`, - `@unique @borrowed` / `@borrowed @unique`. Input modes stay bracketed - (`(@borrowed x : α) → @unique β`) so `A → @unique B → C` has no precedence + `→`/`->`, or after `∀ ...,`: unmarked (`shared`), `@[borrowed]`, `@[unique]`, + `@[unique, borrowed]` / `@[borrowed, unique]`. Input modes stay bracketed + (`(@[borrowed] x : α) → @[unique] β`) so `A → @[unique] B → C` has no precedence ambiguity. * **`let` & `do`-block `let` (8, unparenthesized, optional `: T`)**: - `let @borrowed x := e`, `let @unique x := e`, `let @unique @borrowed x := e`, - `let @once f := e`, `let @once @borrowed f := e`, `let @erased h := p`, and - `let @borrow v := owner` (`LetMode.borrow`). -* **Structure & inductive fields**: `@shared field : T` (`FieldMode.shared` in - `Ixon.Constructor.fieldModes`), `@erased field : T` (constructor binder + `let @[borrowed] x := e`, `let @[unique] x := e`, `let @[unique, borrowed] x := e`, + `let @[once] f := e`, `let @[once, borrowed] f := e`, `let @[erased] h := p`, and + `let @[borrow] v := owner` (`LetMode.borrow`). +* **Structure & inductive fields**: `@[shared] field : T` (`FieldMode.shared` in + `Ixon.Constructor.fieldModes`), `@[erased] field : T` (constructor binder `.erased`), unmarked (`FieldMode.inherited`). Note: when an inductive declares - an `@erased` field, pattern matching through `casesOn` (a case shape) is + an `@[erased]` field, pattern matching through `casesOn` (a case shape) is accepted, while Lean's unannotated auto-generated auxiliaries (`*.rec`, `recOn`, `_sizeOf_1`, `brecOn`, `noConfusion*`) call the raw recursor without - marking the corresponding minor-premise binder `@erased` (and `_sizeOf_1` + marking the corresponding minor-premise binder `@[erased]` (and `_sizeOf_1` genuinely reads non-`Prop` fields), so `Reading.recRules` strictly refuses closures that include them. * **Definition assertions (6)**: scoped Lean 4 attributes `@[no_rc]`, @@ -54,15 +56,15 @@ import Ix.Compile.SourceContract.Elab open scoped Ix.Modes structure Packet (α : Type) where - @shared label : α - @erased valid : True + @[shared] label : α + @[erased] valid : True payload : Nat @[no_alloc, bounded_stack] -def forward (@unique @borrowed x : Nat) : @unique @borrowed Nat := x +def forward (@[unique, borrowed] x : Nat) : @[unique, borrowed] Nat := x -def borrowInDo (@unique owner : Nat) : Id Nat := do - let @borrow v := owner +def borrowInDo (@[unique] owner : Nat) : Id Nat := do + let @[borrow] v := owner return v + 1 ``` @@ -106,7 +108,7 @@ wrappers of it such as `Fin n`; under finalized L1, a `leaf` is never confined to a borrow region, whereas `.val` heap cells are), or `val`. **`runR`** is call by value with fuel. A unique transfer gives every cell of a -value's ownership closure (`inherited` fields, captures; not `@shared` fields, +value's ownership closure (`inherited` fields, captures; not `@[shared]` fields, leaves or immediates) a fresh capability, so every other reference dies. A borrowed binder confines its value to the binder's region. A once binder wraps its value in a once view. Its four violations: diff --git a/docs/source-contracts.md b/docs/source-contracts.md index 5c3f7dbe5e..6713c82078 100644 --- a/docs/source-contracts.md +++ b/docs/source-contracts.md @@ -1,7 +1,7 @@ # Source contracts for the Ix frontend -The Ix source frontend maps scoped `@`-prefixed mode annotations and scoped -definition attributes directly onto the Ixon v5 mode vocabulary +The Ix source frontend maps scoped `@[...]` mode attribute annotations and +scoped definition attributes directly onto the Ixon v5 mode vocabulary (`IxCK/Ixon/Types/Modes.lean`): - `Ixon.BinderMode` (7 modes) @@ -26,13 +26,15 @@ All parsers and attributes are declared `scoped` under `namespace Ix.Modes`. Importing `Ix.Compile.SourceContract.Elab` without `open scoped Ix.Modes` adds no global parsers and activates no attributes. -Every `@`-keyword uses -`atomic ("@" >> checkNoWsBefore "no space after @" >> nonReservedSymbol w)` and -every attribute uses `nonReservedSymbol`, adding **zero** entries to Lean's -`TokenTable`. Identifiers and standard Lean syntax such as `@unique_fn`, -`@uniqueId`, `@id Nat x`, `(@unique x : @& Nat)`, `(unique x : Nat)`, -`let @Prod.mk _ _ a b := p`, and `let borrow v := owner + v` continue to parse -and elaborate identically while `open scoped Ix.Modes` is active. +Every mode block uses `atomic ("@[" >> sepBy1 ... "," >> "]")` with +`nonReservedSymbol` (reusing Lean's built-in `"@["`, `","`, and `"]"` tokens), +adding **zero** entries to Lean's `TokenTable`. Arbitrary whitespace (spaces, +tabs, and linebreaks) is allowed after `(`, `{`, `⦃`, `[`, `:`, `→`, `,`, `let`, +and inside `@[ ... , ... ]`, while mid-group binder annotations like +`(a @[unique] b : Nat)` are rejected. Identifiers and standard Lean syntax such +as `@unique_fn`, `@uniqueId`, `@id Nat x`, `(@[unique] x : @& Nat)`, +`(unique x : Nat)`, `let @Prod.mk _ _ a b := p`, and `let borrow v := owner + v` +continue to parse and elaborate identically while `open scoped Ix.Modes` is active. ## Mode table (1-to-1 bijection with `Ixon.Types.Modes`) @@ -41,41 +43,44 @@ and elaborate identically while `open scoped Ix.Modes` is active. | Surface syntax | `Ixon.BinderMode` | Wire code | | --- | --- | --- | | *(unmarked)* | `.many` | 0 | -| `@borrowed` | `.borrowed` | 1 | -| `@unique` | `.unique` | 2 | -| `@unique @borrowed` / `@borrowed @unique` | `.uniqueBorrowed` | 3 | -| `@once` | `.once` | 4 | -| `@once @borrowed` / `@borrowed @once` | `.onceBorrowed` | 5 | -| `@erased` | `.erased` | 6 | - -Supported in `(...)`, `{...}`, `⦃...⦄`, and `[...]` binders, including -multi-name groups (`(@unique x y : T)`) and optional `: T` in `fun` -(`fun (@unique x) => x + 1`). Illegal combinations (`@erased` with any other -mode, `@once @unique`, duplicates) are rejected with explicit elaborator errors. +| `@[borrowed]` | `.borrowed` | 1 | +| `@[unique]` | `.unique` | 2 | +| `@[unique, borrowed]` / `@[borrowed, unique]` | `.uniqueBorrowed` | 3 | +| `@[once]` | `.once` | 4 | +| `@[once, borrowed]` / `@[borrowed, once]` | `.onceBorrowed` | 5 | +| `@[erased]` | `.erased` | 6 | + +Both comma-separated (`@[unique, borrowed]`) and adjacent (`@[unique] @[borrowed]`) +blocks are accepted. Supported immediately after `(`, `{`, `⦃`/`{{`, and `[` +(allowing spaces, tabs, and linebreaks), including multi-name groups +(`(@[unique] x y : T)`) and optional `: T` in `fun` +(`fun (@[unique] x) => x + 1`). Illegal combinations (`@[erased]` with any other +mode, `@[once, unique]`, duplicates) and mid-group placement (`(a @[unique] b : T)`) +are rejected. ### Result modes (4) | Surface syntax | `Ixon.ResultMode` | Wire code | | --- | --- | --- | | *(unmarked)* | `.shared` | 0 | -| `@borrowed` | `.borrowed` | 1 | -| `@unique` | `.unique` | 2 | -| `@unique @borrowed` / `@borrowed @unique` | `.uniqueBorrowed` | 3 | +| `@[borrowed]` | `.borrowed` | 1 | +| `@[unique]` | `.unique` | 2 | +| `@[unique, borrowed]` / `@[borrowed, unique]` | `.uniqueBorrowed` | 3 | Supported after `:` in `def`, `abbrev`, `opaque`, and `axiom`, after `→`/`->`, -and after `∀ ...,`. Input modes stay bracketed (`(@borrowed x : α) → @unique β`) -so `A → @unique B → C` parses unambiguously as `A → (@unique (B → C))`. +and after `∀ ...,`. Input modes stay bracketed (`(@[borrowed] x : α) → @[unique] β`) +so `A → @[unique] B → C` parses unambiguously as `A → (@[unique] (B → C))`. ### `let` and `do`-block `let` (8, unparenthesized, optional `: T`) - `let x := e` → `.value .many` (0) -- `let @borrowed x := e` → `.value .borrowed` (1) -- `let @unique x := e` → `.value .unique` (2) -- `let @unique @borrowed x := e` → `.value .uniqueBorrowed` (3) -- `let @once f := e` → `.value .once` (4) -- `let @once @borrowed f := e` → `.value .onceBorrowed` (5) -- `let @erased h := p` → `.value .erased` (6) -- `let @borrow v := owner` → `.borrow` (7) +- `let @[borrowed] x := e` → `.value .borrowed` (1) +- `let @[unique] x := e` → `.value .unique` (2) +- `let @[unique, borrowed] x := e` → `.value .uniqueBorrowed` (3) +- `let @[once] f := e` → `.value .once` (4) +- `let @[once, borrowed] f := e` → `.value .onceBorrowed` (5) +- `let @[erased] h := p` → `.value .erased` (6) +- `let @[borrow] v := owner` → `.borrow` (7) All 8 forms work in both expression `let` and `do`-block `let`, with or without `: T`. @@ -84,20 +89,20 @@ All 8 forms work in both expression `let` and `do`-block `let`, with or without ```lean structure Box (α : Type) where - @shared item : α - @erased inv : True + @[shared] item : α + @[erased] inv : True count : Nat inductive Tree (α : Type) where | leaf - | node (@shared label : α) (@erased proof : True) (left right : Tree α) + | node (@[shared] label : α) (@[erased] proof : True) (left right : Tree α) ``` -- `@shared`: lowers to `FieldMode.shared` in `Ixon.Constructor.fieldModes` -- `@erased`: lowers to `.erased` on the constructor's binder in `c.binders` +- `@[shared]`: lowers to `FieldMode.shared` in `Ixon.Constructor.fieldModes` +- `@[erased]`: lowers to `.erased` on the constructor's binder in `c.binders` - *(unmarked)*: `FieldMode.inherited` -Combining `@shared` and `@erased` on the same field is rejected. +Combining `@[shared]` and `@[erased]` on the same field is rejected. ### Definition assertions (6) @@ -121,6 +126,6 @@ through `Registry` → `Transport` → `CompileM` into `Ixon.Definition.asserts` - `source-contract-tests` verifies `TokenTable` cleanliness, scoped activation, positive & negative syntax/elaboration, import persistence, resolution, and compilation with `ModeCheck`. -- `IxTests resource-modes` verifies end-to-end compilation of binders, `let @borrow`, +- `IxTests resource-modes` verifies end-to-end compilation of binders, `let @[borrow]`, constructor `fieldModes`, definition `asserts`, `BinderData.strip`/`apply` roundtrips, and `IxCK.Resource.check`. diff --git a/docs/stark-parameters.md b/docs/stark-parameters.md index ed3551f101..ce4d7b3d6b 100644 --- a/docs/stark-parameters.md +++ b/docs/stark-parameters.md @@ -38,6 +38,7 @@ This document specifies: | `max_log_arity` | `1` (binary FRI folding) | fixed by adapter & recursive verifier | | `log_final_poly_len` | `0` (constant final polynomial) | fixed | | `cap_height` | `0` (strictly singleton Merkle roots) | fixed | +| `stage_1_pinning` | `1` (mandatory Stage-1 OOD pinning before lookup challenges) | fixed (production `v6` requires `1`) | The canonical Rust source is `aiur::trace::stark::Parameters::DEFAULT` (`crates/aiur/src/trace/stark.rs`), shared by `ixvm-proof`, `stark-verifier`, @@ -91,14 +92,20 @@ theorem covers the shipped Rust `multi-stark` `v6` verifier (see - All 11 domains (including retired unkeyed `plain` / `v5`) are proved pairwise distinct in Lean (`CertiFri.P3.Blake3Domain.mode_injective`, `v6Zk_keyWords_ne_nonZk`, `Ix.Cert.Compression.StarkShrinker.Blake3Domain.*`). -4. **`vk_digest` and key header binding:** The dense `stark-key` v6 wire format +4. **`vk_digest`, `stage_1_pinning`, and key header binding:** The dense `stark-key` v6 wire format (`crates/stark-key/src/lib.rs`) writes `protocol_version = 6`, `extension_degree = 3`, `fri_batching = 1`, the 32-byte `vk_digest` - (`BLAKE3 derive_key("multi-stark/v6/vk")` over all compiled circuits), and - all seven commitment/FRI parameters into the header. Decoding recomputes - `vk_digest` and rejects mismatches fail-closed. `multi-stark` seeds the - Fiat–Shamir transcript with the protocol tag, parameters, and `vk_digest`, so - a proof produced under any other parameters or circuits fails verification. + (`BLAKE3 derive_key("multi-stark/v6/vk")` over all compiled circuits), all + seven commitment/FRI parameters, and the eighth `u16` flag `stage_1_pinning = 1` + into the header. Decoding recomputes `vk_digest` and rejects mismatches or + `stage_1_pinning != 1` fail-closed. `multi-stark` seeds the Fiat–Shamir + transcript with the protocol tag, parameters (including the pinning flag), + and `vk_digest`, so a proof produced under any other parameters, pinning + mode, or circuits fails verification. After absorbing the preamble, the batch + transcript samples a pinning point `z₀ ∈ Fp^3`, absorbs the claimed Stage-1 + (fixed + main) evaluations at `z₀`, and then samples `(β, γ)`, opening Stage-1 + and active preprocessed traces at `[ζ, ζ·g, z₀]`. This closes Johnson-regime + multi-shard integer LogUp balance without `L^(#circuits · S)` blowup. The aggregation program pins the IxVM and aggregation key digests, binding every recursive step. 5. **Exact `MerkleCap` root counts:** Production keys fix `cap_height = 0` @@ -378,8 +385,8 @@ and on-chain verification properties: | Security Dimension | Endpoint 1: Native STARK (`v6` / `v6-zk`, `--stark-128` / `--stark-128-zk`) | Endpoint 2: BLS12-381 KZG / EIP-2537 PLONK (`--bls12-381`; no release key yet) | Endpoint 3: BN254 KZG / Pre-Pectra PLONK (`--bn254`, recursive KZG current default; legacy Go/gnark final PLONK & Groth16 retired) | | --- | --- | --- | --- | -| **Headline Classical Security** | **136.7–141.9 b interactive JBR** (`soundcalc` tuned gap; **127.71 b** non-interactive ROM with 32B BLAKE3 `c=3/2` collisions, **127.32 b** at `CertiFRI` `4f563b7`'s packaged `(3/4)/2^128` budget, literal **≥ 128 b** with 64B BLAKE2b-512; ~81 b UD at `(4, 58, 0, 28)`). `CertiFRI` `4f563b7` proves unconditional Tier-2 `BatchedLineListCA` (`kCol+kOpen ≤ 32, H ≤ 32`, covering every production layer), `c = 3/2` incremental-sponge STARK soundness, and DEEP-ALI Johnson STARK constraint soundness for `v6` and both shipped `EP1` profiles (LogUp balance remains UD-only); no machine-checked theorem covers the shipped Rust `multi-stark` or `stark-shrinker` verifier binaries directly | **~113.44 b** *(Cheon $q$-SDH on Filecoin $2^{28}-2$ SRS; curve target-group exTNFS ~117–126 b, Pollard-$\rho$ ~127.25 b)* | **~100–103 b** *(BN254 target-group exTNFS; Botrel 2026: $2^{103.2}$ — rejected by 128-bit profile)* | -| **Headline Post-Quantum Security** | **Not established.** The shipped 32B `BLAKE3-256` digests give **~85.3b** BHT quantum collision resistance, and no theorem considers a quantum adversary (all are classical random-oracle statements). *(A 64B RFC 7693 `BLAKE2b-512` profile — 170.7b BHT / 204.8b CNS / 256b Grover — is a Lean specification and parameter study; no prover or verifier uses it.)* | **0 bits** *(Shor breaks ECDLP / pairings in poly-time)* | **0 bits** *(Shor breaks ECDLP / pairings in poly-time)* | +| **Headline Classical Security** | **≥ 127.71 b non-interactive ideal sponge** (`136.7–141.9 b` interactive JBR; hash-limited by 32B `BLAKE3-256` `c=3/2` collisions — never `128.0b` classical with 32B digests; literal `≤ N/2^128` for `6N ≤ 2^128`). `CertiFRI` (`14f7a315bf`) + `Ix.Cert.Release05.SecurityAudit` prove full **Johnson-regime constraint + multi-shard integer LogUp balance** via **Stage-1 pinning** at tightened `ε_rbr ≤ (3/4)/2^133` for both inner binary `v6` (`(2,128,0,20)`, `L=7`) and transparent EP1 `compact400KBBalanced` (`(4,58,0,28)`, 8-ary, `L=13`), plus keyed byte-level soundness for `Profile.verifyBytesPinned` (executed directly by pure-Lean `ix verify` and `verify-multistark`). All five concrete Ix production shapes (`ixvm-2p23` 64sh/4096sh, `aggr-2p22`, `rec-2p22`, `ep1-v6-hop4`) are discharged in the Lean kernel. | **~113.44 b** *(Cheon $q$-SDH on Filecoin $2^{28}-2$ SRS; curve target-group exTNFS ~117–126 b, Pollard-$\rho$ ~127.25 b)* | **~100–103 b** *(BN254 target-group exTNFS; Botrel 2026: $2^{103.2}$ — rejected by 128-bit profile)* | +| **Headline Post-Quantum Security** | **≥ 64 bits QROM-Q1 (transparent `v6` only; matches/beats Ethereum LeanVM's `125b / 62b`).** Machine-checked unconditionally in `CertiFRI` (`14f7a315bf`) + `Ix.Cert.Release05.SecurityAudit` over Zhandry's compressed oracle (`ForgePinned ≤ ((Q+Nv)/2^64)^2` and `< 1` at `Q+Nv ≤ 2^64`) AND Zhandry Lemma 5 standard-QRO equivalence (`stdQro64_verifyBatchTensorPinned_v6`, `stdQro64_verifyBatchTensorMultiArityPinned_ep1`), with zero custom axioms, for inner binary `v6` and transparent EP1 `--stark-128` (`compact400KBBalanced`). 32B `BLAKE3-256` gives `84.0b` BHT (`83.0b` CMS19) hash headroom (`+19b` above 64b). **Out of Release 0.5 PQ scope:** hiding `v6-zk` (`--stark-128-zk`) is not covered by the Release 0.5 QROM theorems (rejected fail-closed by `Profile.verifyBytesPinned`). *(A 128-bit PQ `v7` architecture with `Goldilocks^5` + `BLAKE2b-512` is parked on `ap/pq-security` for Ix `1.0`.)* | **0 bits** *(Shor breaks ECDLP / pairings in poly-time)* | **0 bits** *(Shor breaks ECDLP / pairings in poly-time)* | | **Algebraic / Field Modulus** | Goldilocks $\mathbb{F}_{p^3}$, $p^3 > 2^{191}$ ($\log_2 p^3 = 192.00$b) | $q$: 381b ($\log_2 q = 380.70$, $q^{12} \approx 2^{4568.4}$); $r$: 255b ($\log_2 r = 254.86$) | $q$: 254b ($\log_2 q = 253.60$, $q^{12} \approx 2^{3043.2}$); $r$: 254b ($\log_2 r = 253.60$) | | **Curve DLP (Pollard-$\rho$ in $G_1$)** | N/A (no elliptic curve) | **~127.25 bits** ($\frac{1}{2}\log_2(\pi r / 4)$) | **~126.62 bits** ($\frac{1}{2}\log_2(\pi r / 4)$) | | **Pairing Target DLP (exTNFS in $\mathbb{F}_{q^{12}}^*$)** | N/A (no pairing) | **~117–126 bits** *(Barbulescu–Duquesne 2019 / Guillevic 2020 / Botrel 2026)* | **~100–103 bits** *(Kim–Barbulescu 2016 / Guillevic 2020 / Botrel 2026: $2^{103.2}$)* | @@ -459,13 +466,24 @@ project module in the full transitive import closure of the kernel, refinement, and Aiur audit roots with Lean's kernel via `Scripts/KernelReplay.lean` (in `certified-kernel`, `ixvm-refinement`, and `formal-unit-tests`), in addition to `leanchecker` on the named audit modules. Definitional closures are SHA-256 -pinned in `Ix/Cert/Security128ClosureManifest.lean` +pinned in `Ix/Cert/Release05/ClosureManifest.lean` +(`Tests/Fixtures/release-05-closure-manifest.txt`), +`Ix/Cert/Security128ClosureManifest.lean` (`Tests/Fixtures/security-128-closure-manifest.txt`), `Ix/Cert/StatementClosureManifest.lean` (`Tests/Fixtures/statement-closure-manifest.txt`), and `Ix/Cert/AiurCompressionClosureManifest.lean` (`Tests/Fixtures/aiur-compression-closure-manifest.txt`). +For Release `0.5` transparent Protocol `v6` + Stage-1 pinning, the pure-Lean CLI +verifier (`ix verify` via `Ix/Cli/PureStarkVerifierKernel.lean` and +`Ix/Cert/MultiStark/PinnedVerifier.lean`) and standalone verifier +(`Scripts/VerifyMultiStark.lean`) execute `CertiFri.Stark.Profile.verifyBytesPinned` +directly with zero Rust FFI and zero Mathlib, closing the verifier-model gap on +the pure-Lean verification path. Rust provers/verifiers (`multi-stark`, +`stark-shrinker`, `ix-proof-compression`) and Solidity verifiers remain +differential/CI tested rather than extracted from Lean. + "Lean-Certified" below means that a statement is proved, not that it is about the compiled binaries that ship. **No machine-checked theorem is about the Rust or Solidity verifier binaries** (`multi-stark`, `stark-shrinker`, diff --git a/lake-manifest.json b/lake-manifest.json index e1b2d0cf75..1f66c12eaf 100644 --- a/lake-manifest.json +++ b/lake-manifest.json @@ -42,30 +42,30 @@ "type": "git", "subDir": null, "scope": "", - "rev": "d8eb3e0d9a8e33fc116e6700df0418a1d8114508", + "rev": "b12338b60c87cc2d2dfeeeaa16d859100ec038c8", "name": "LSpec", "manifestFile": "lake-manifest.json", - "inputRev": "d8eb3e0d9a8e33fc116e6700df0418a1d8114508", + "inputRev": "b12338b60c87cc2d2dfeeeaa16d859100ec038c8", "inherited": false, "configFile": "lakefile.toml"}, {"url": "https://github.com/argumentcomputer/CertiFRI", "type": "git", "subDir": "Proofs", "scope": "", - "rev": "2baa40411f32521987069a8526ac3db50c7a5154", + "rev": "14f7a315bf5bc46fb124b6f0e9bb53b1f23ea63b", "name": "«certifri-proofs»", "manifestFile": "lake-manifest.json", - "inputRev": "2baa40411f32521987069a8526ac3db50c7a5154", + "inputRev": "14f7a315bf5bc46fb124b6f0e9bb53b1f23ea63b", "inherited": false, "configFile": "lakefile.toml"}, {"url": "https://github.com/argumentcomputer/CertiFRI", "type": "git", "subDir": null, "scope": "", - "rev": "2baa40411f32521987069a8526ac3db50c7a5154", + "rev": "14f7a315bf5bc46fb124b6f0e9bb53b1f23ea63b", "name": "certifri", "manifestFile": "lake-manifest.json", - "inputRev": "2baa40411f32521987069a8526ac3db50c7a5154", + "inputRev": "14f7a315bf5bc46fb124b6f0e9bb53b1f23ea63b", "inherited": false, "configFile": "lakefile.toml"}, {"type": "path", @@ -89,16 +89,6 @@ "inherited": false, "dir": "Aiur", "configFile": "lakefile.lean"}, - {"url": "https://github.com/leanprover-community/plausible", - "type": "git", - "subDir": null, - "scope": "", - "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", - "name": "plausible", - "manifestFile": "lake-manifest.json", - "inputRev": "v4.34.0", - "inherited": true, - "configFile": "lakefile.toml"}, {"url": "https://github.com/leanprover-community/mathlib4", "type": "git", "subDir": null, @@ -109,6 +99,16 @@ "inputRev": "v4.34.1", "inherited": true, "configFile": "lakefile.lean"}, + {"url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml"}, {"url": "https://github.com/leanprover-community/LeanSearchClient", "type": "git", "subDir": null, diff --git a/lakefile.lean b/lakefile.lean index 25d129ba9c..edabbd9f44 100644 --- a/lakefile.lean +++ b/lakefile.lean @@ -16,13 +16,13 @@ require ixvm from "IxVM" require multiStark from "MultiStark" require certifri from git - "https://github.com/argumentcomputer/CertiFRI" @ "2baa40411f32521987069a8526ac3db50c7a5154" + "https://github.com/argumentcomputer/CertiFRI" @ "14f7a315bf5bc46fb124b6f0e9bb53b1f23ea63b" require «certifri-proofs» from git - "https://github.com/argumentcomputer/CertiFRI" @ "2baa40411f32521987069a8526ac3db50c7a5154" / "Proofs" + "https://github.com/argumentcomputer/CertiFRI" @ "14f7a315bf5bc46fb124b6f0e9bb53b1f23ea63b" / "Proofs" require LSpec from git - "https://github.com/argumentcomputer/LSpec" @ "d8eb3e0d9a8e33fc116e6700df0418a1d8114508" + "https://github.com/argumentcomputer/LSpec" @ "b12338b60c87cc2d2dfeeeaa16d859100ec038c8" /- The pinned package supplies the pure Lean hash and host C/Rust accelerators. -/ @@ -397,7 +397,8 @@ lean_exe «gen-paper-fixtures» where section Tests -lean_lib Tests +lean_lib Tests where + moreLeanArgs := #["-Dcompiler.extract_closed=false"] /-- The certified entry's host cases (`Tests.Ix.Kernel.EntryCaseDefs`), built as a library of their own so that suites can import them at run time (some host cases @@ -693,6 +694,7 @@ def isFormalOnlyModule (m : Lean.Name) : Bool := s.startsWith "Ix.Cert.Aggr." || s.startsWith "Ix.Cert.Compression." || s.startsWith "Ix.Cert.AiurCompression." || + s.startsWith "Ix.Cert.Release05." || m == `Ix.Cert.Security128ClosureManifest || m == `Ix.Cert.StatementClosureManifest || m == `Ix.Cert.AiurCompressionClosureManifest || diff --git a/tools/formal-aiur.keys b/tools/formal-aiur.keys index add2eea729..395c60d857 100644 --- a/tools/formal-aiur.keys +++ b/tools/formal-aiur.keys @@ -16,12 +16,12 @@ # A change means the compiled circuits changed: review it, then regenerate # with `lake run check-formal-keys --update` in a commit of its own. parameters log_blowup 2 num_queries 128 -ixvm d3e932a73b0f3d1cabdba511bd5e313bbfcaa2f502dd4a17856bf70c1de18790 5e1ba572c65c2484db00277dc88e58bf44a9647eca9999eadf174f4b10442159 0 -verifier 47cc1ef9d14e9f12f4a518447758d285ff7715a0b1ed6949513927f60a623666 3ca3f5f91d724ba148b0343bc9737662ff9e96d5420bbedac11f6063007d233d -aggregation 20c24276e56cd9b75f306d17ed5b50f7d3bafd69a5704a5be2b3f09db2abe393 5e7e50a2332f5c992863cac44263f265455e97b52e4df7647b460e6f8e73d000 0 -shrinker stark-128 balanced 1 compiled-trace-v1 c5d0f82f640e963f75fa552b624c09172f320b6c156d5c9ebe895b366b1cbf96 -shrinker stark-128 fast 1 compiled-trace-v1 4cb4e2aaad5ae39818d51509be08d5ff9a6eab08a11f3969ae4084e73bffe7d8 -shrinker stark-128 compact 1 compiled-trace-v1 0f9747a5d9fc0e91364435ddb3f8a3aeb412313a587f3542002d184fe593dba1 -shrinker stark-128-zk balanced 1 compiled-trace-v1 94119194dbeaec5f9d59016e143bed03607ce2cb839cd8ebaf5fd3d41dadc170 -shrinker stark-128-zk fast 1 compiled-trace-v1 994f916c6d263365bc275893b07224c4b03b2351b3663c20b1dd8861257e969c -shrinker stark-128-zk compact 1 compiled-trace-v1 faa961401f9382d1ad584b512bf6bccd3ae71a060767c480f1fd330e9c10d4a3 +ixvm d3e932a73b0f3d1cabdba511bd5e313bbfcaa2f502dd4a17856bf70c1de18790 1a254ffcce6763d31d1b109afaaf438241af2bb2e7e14f88ec82243e0b928739 0 +verifier f52dffc93b751c3227f10736a3f5f16bc2ef4e99dcd8ef3f755e1d079a2f5ab0 d12856c30680d6635fbfaa300ea48f74c70aa38c4f0b208cdd18101c7e4d02f5 +aggregation 3bbd3a192240c8a9e5c9d1b84bd784db5279df00f4058f77cb034de3e0e81666 e43313f9b105462440338d8a90b76c0bb13f453f50e7f46d12366028f7471492 0 +shrinker stark-128 balanced 1 compiled-trace-v1 f53809f5c76afec50c302490fe125619ab362ef2e0e125e69355dfdc000dcc96 +shrinker stark-128 fast 1 compiled-trace-v1 f2df1a4abf873c9689b099125ebc8b140eb6a2daa65834bec2450fd992558e29 +shrinker stark-128 compact 1 compiled-trace-v1 f52d8dd48e9eee9369c21aabfd833b0e3c7a9b55d99d831e207dc366104ba392 +shrinker stark-128-zk balanced 1 compiled-trace-v1 afa61c853e23bc800286a2d74b31e8ef79c7eb7c28f4a8a2857cfd4d3a902800 +shrinker stark-128-zk fast 1 compiled-trace-v1 82a82b4962f21ad212a62e7896ef6c6bd47ba53804997b08cbfccf2484291b53 +shrinker stark-128-zk compact 1 compiled-trace-v1 0f9ea687b910965c5983001205d0b7563044ae6b7f351480d4848874b4f1bed7