blob: 6666f649943687f9e6ea8194039b6c28cb8ed22b [file] [edit]
/-
# `ConRon.Arena.ExprOps` — the `ExprOps` twins (DESIGN.md §8.6 P2b)
`ConLeche/Kernel/ExprOps.lean`, clause for clause, over handles: 70 (T)
declarations of the census (`Arena/CENSUS.md`, "P2b — the `ExprOps` twins,
with memo"), written in the Rust-shaped style of DESIGN §8.4 — no `for`, no
`mut`, no closures, no `partial`, explicit recursion with fuel where
con-leche recurses structurally on `Expr`, detach before update at every
mutation, one `def` per intended Rust function.
## The four rules this module is written by
1. **`view` where con-leche matched, `intern` where it built, handle equality
where it compared** (§8.3). A leaf arm that con-leche writes as
`| .fvar idx ty => .fvar idx ty` is `pure h` here: the node is already in
the store and `denoteE` is injective, so rebuilding it would be the same
handle.
2. **Fuel.** A handle DAG has no structural order the elaborator can see, so
every walk over the DAG takes an explicit `fuel : Nat` and `fail`s when it
runs out. Exhaustion is a failure and Theorem 1 will claim nothing on
failure (con-leche's `SimAt` shape), so the fuel is invisible above this
module. A recursion that is structural on something else — a `Nat` binder
count (`stripPis`), a `List` of arguments (`mkAppN`), a transient `Level`
tree (`internLevel`) — takes no fuel.
3. **The memo lives in the state** (§8.3 "Caches"). con-leche threads it as
an argument-and-result pair (`instantiate1Go v memo e d`); here it is a
field of `AState`, keyed `(EIdx, cursor)` as nanoda keys it, and dropped
at the top-level entry — which is why the substituted term is not in the
key. Each `…Fast` entry is con-leche's `(…Go v {} e d).1`: clear, walk,
clear.
4. **One `def` per constructor arm.** Each walk is a `mutual` block: the
dispatcher (`…Go`) and one `def` per constructor arm (`…ArmApp`,
`…ArmBind`, …), each arm calling the dispatcher by name. This keeps every
Theorem 1 proof about one arm small. The arms take no function argument
(a closure is what DESIGN §3.4 forbids in code Aeneas must translate).
The Rust keeps con-leche's shape, one function per walk with the arms
inline; Theorem 2 unfolds the twin's arm `def`s (`lockstep_simp`,
`Refine2/ExprOps/Mut.lean`) to meet it. The memo probes sit at the
same places in both.
## The cutoffs (§8.3 lesson 20)
Every traversal that con-leche cuts off on a derived field cuts off here on
the same one, read in `O(1)` off the derived column instead of recomputed:
| walk | cutoff | con-leche's licence |
|---|---|---|
| `instantiate1Go` | `bvarBRaw < satRange && bvarBRaw ≤ d` | `bvarBRaw_exact` + task #97s's `instantiate1_of_bvarBound_le` |
| `abstract1Go` | `fvarB ≤ d` | `abstract1_of_fvarRange_le` |
| `instantiateLiftGo` | `bvarB ≤ d` | `instantiateLift_of_bvarBound_le` |
| `instLPGo` | `hasLP = false` | `Expr.instantiateLevelParams_eq_self` |
| `instantiateList`, `instantiateListGo` | `bvarBRaw < satRange && bvarBRaw ≤ d` | DERIVED, below |
| `liftLooseBVarsGo` | `bvarBRaw < satRange && bvarBRaw ≤ c` | DERIVED, below |
`instantiate1Go`'s is one of three cutoffs con-leche does NOT have (its
`instantiate1Go` walks unconditionally); DESIGN §8.3 asks for it by name and
task #97s proved its licence, so the arena takes it.
**The two derived cutoffs (task #97f, P2f).** `instantiateList` and
`liftLooseBVars` have no cutoff in con-leche either, and task #97b left them
without one because "a cutoff the original does not have needs its licence
proved". P2f's gate is what forced the question: `tests/e2e/proj_share.ndjson`
does not finish without them, with 18 % of its cycles in `instantiateList`.
The licence is elementary and is written out here for P3 to discharge as two
`Expr`-level lemmas:
* `looseBVarsBounded d e → instantiateList e vs d = e`. Induction on `e`.
The only clause that is not the congruence is `.bvar j`, and
`looseBVarsBounded d (.bvar j)` is `j < d`, which takes the `if j < d`
branch — `.bvar j` unchanged. Under a binder the hypothesis weakens
from `d` to `d + 1`, which is what the recursive call passes.
* `looseBVarsBounded c e → liftLooseBVars e c amount = e`. Identically:
`.bvar j` with `j < c` fails `j ≥ c` and is returned unchanged.
`looseBVarsBounded k e` is `e.bvarBound ≤ k`, and the store's derived word is
con-leche's own `Expr.data` (§8.3), so `bvarBRaw < satRange` is exactly the
side condition under which the packed field IS `e.bvarBound` — the same guard
`instantiate1Go` carries, and the reason neither cutoff needs the saturated
branch's memoized recomputation (`bvarB`, which is defined below these walks
anyway). Both cutoffs are therefore DENOTATION-PRESERVING: on a handle they
answer, the walk they replace returns that same handle, because the rebuild
of an unchanged node is the node (`denoteE` is injective, so `intern` of a
node's own view is that node).
The pure `instantiateList` carries the cutoff too, not only the memoized
`instantiateListGo`: its `.bvar` arm recurses into the REPLACEMENT
`vs[j - d]` with a shorter list and no memo, and con-leche's own note says
that on the `bvar`-closed replacements every checker call site passes, that
recursion is the identity. With the cutoff it *is* one `O(1)` test instead
of a full traversal of the replacement, which is where `proj_share`'s 18 %
lived.
## Levels are read back, not twinned (§8.3 lesson 4)
`instLPGo` is the only twin that touches a level ALGORITHM. It reads the
substitution back out of the store once, at the top-level entry, runs
con-leche's own `Level.subst` on the transient trees, and
re-interns the result. `Level.hasParam` and `Expr.hasLevelParam` are not
walks at all here: both are exactly the derived bit the store already carries.
-/
module
public import ConRon.Arena.Monad
public import ConLeche.Kernel.Level
@[expose] public section
namespace ConRon.Arena
open ConLeche
/-! ## The UPWARD cutoff of a substituting walk (task #97-P6-5, lever 2)
**A rebuilt spine whose children did not change is the same node.** `h`
decodes to a view whose children the walk has just rewritten; if every
rewritten child is the child it started from, then the view handed here IS the
view `h` decodes to, and `intern` would answer `h` — the store is hash-consed,
`denoteE` is injective, and §8.3's cross-tier rule ("a scratch entry never
duplicates a persistent one") makes the answer `h` and not some twin of `h` in
the other tier. So the test replaces a cons-table probe with one word
comparison per child.
It is applied ONLY to the walks whose downward cutoff is inexact, which is
where it can fire at all: `abstract1Go` (the cutoff is `fvarB ≤ d`, and the arm
abstracts the index `= d`), `abstractRangeGo` and `instLPGo` (the cutoff is
the `hasLP` bit, and a substitution touching none of the parameters present is
the identity). `instantiate1Go`, `instantiateListGo`, `liftLooseBVarsGo` and
`instantiateLiftGo` are NOT given it: their cutoff is `bvarB ≤ d` against a
field that is EXACT below saturation, so past the cutoff a loose `bvar` at or
above `d` really is present and really does move. -/
/-- con-leche: none — `internE` with task #97-P6-5's upward cutoff. -/
@[inline] def internRebuilt (h : EIdx) (same : Bool) (v : ENodeView) : AM EIdx :=
if same then pure h else internE v
/-- con-leche: none — `internRebuilt` at the `fvar` arm's fields. -/
@[inline] def internRebuiltFVar (h : EIdx) (same : Bool) (idx : Nat) (ty : EIdx) :
AM EIdx := if same then pure h else internFVarE idx ty
/-- con-leche: none — `internRebuilt` at the `sort` arm's fields. -/
@[inline] def internRebuiltSort (h : EIdx) (same : Bool) (u : LIdx) : AM EIdx :=
if same then pure h else internSortE u
/-- con-leche: none — `internRebuilt` at the `const` arm's fields. -/
@[inline] def internRebuiltConst (h : EIdx) (same : Bool) (n : NIdx) (us : LsIdx) :
AM EIdx := if same then pure h else internConstE n us
/-- con-leche: none — `internRebuilt` at the `app` arm's fields. -/
@[inline] def internRebuiltApp (h : EIdx) (same : Bool) (f a : EIdx) : AM EIdx :=
if same then pure h else internAppE f a
/-- con-leche: none — `internRebuilt` at the `lam` arm's fields. -/
@[inline] def internRebuiltLam (h : EIdx) (same : Bool) (ty b : EIdx) : AM EIdx :=
if same then pure h else internLamE ty b
/-- con-leche: none — `internRebuilt` at the `forallE` arm's fields. -/
@[inline] def internRebuiltForallE (h : EIdx) (same : Bool) (ty b : EIdx) :
AM EIdx :=
if same then pure h else internForallEE ty b
/-- con-leche: none — `internRebuilt` at the `letE` arm's fields. -/
@[inline] def internRebuiltLetE (h : EIdx) (same : Bool) (ty val b : EIdx) :
AM EIdx := if same then pure h else internLetEE ty val b
/-- con-leche: none — `internRebuilt` at the `proj` arm's fields. -/
@[inline] def internRebuiltProj (h : EIdx) (same : Bool) (n : NIdx) (i : Nat)
(e : EIdx) : AM EIdx := if same then pure h else internProjE n i e
/-- con-leche: none — `internRebuilt` at a binder arm's fields and the tag the
walk decoded them at: a substituting walk takes a binder apart and puts it
back with `internBindE`. -/
@[inline] def internRebuiltBind (h : EIdx) (same : Bool) (tag : UInt32)
(ty b : EIdx) : AM EIdx :=
if same then pure h else internBindE tag ty b
/-! ## Handle vectors, built by `Array.push`
The maintainer's ruling (DESIGN §8.6, before §8.7): *a `List` accumulator
built by `::` in the Lean twin, mirrored as an insert-at-front on a `Vec`, is
quadratic and silly. The twin uses `Array` with `Array.push` and the Rust
`Vec::push` — idiomatic in both tiers, the same denotation as the reversed
list — and reads the accumulator from the end where the algorithm consumed the
list's head.* So the substituting walks' argument vectors are `Array EIdx` in
PUSH order: con-leche's `vs[j - d]`, the innermost binder's argument first, is
this array's entry `j - d` FROM THE END. -/
/-- con-leche: ConLeche/Cached/CoreC.lean:194-197 pushRange — copy `xs[i], …,
xs[k-1]` onto `out`, in order: the range read in place. -/
def eidxCopyUpto (xs : Array EIdx) (k i : Nat) (out : Array EIdx) : Array EIdx :=
if h : i < k ∧ i < xs.size then
eidxCopyUpto xs k (i + 1) (out.push xs[i])
else out
termination_by k - i
decreasing_by omega
/-- con-leche: none — the `O(1)` cutoff of a bulk instantiation, off the
handle's own derived word: a node whose loose-bvar bound is exact and at most
`d` is its own instantiation (DESIGN §8.3 lesson 20; task #97f's deviation,
denotation-preserving by `looseBVarsBounded d e → instantiateList e vs d = e`). -/
@[inline] def instListCutoff (h : EIdx) (d : Nat) : AM Bool := do
let bRaw := (bvarOfData (← derivedE h)).toNat
pure (bRaw < satRange && bRaw ≤ d)
/-- con-leche: none — `xs.take k` over a push-order `Array EIdx`. -/
def takeEidx (xs : Array EIdx) (k : Nat) : Array EIdx := eidxCopyUpto xs k 0 #[]
/-! ## `instantiate1` — `ExprOps.lean:29-45`, `:80-116`, `:182-184`
One twin for all three: the pure walk is the specification, `instantiate1Go`
is what executes, and the arena has one function — with the memo and the
derived-word cutoff.
**The tag dispatch** (tasks #97-P6-10 and #97-P6-13, and the maintainer's own
ruling before DESIGN §8.7): a clause that is one constructor plus a
fallthrough tests the handle's own tag word BEFORE reading the store, and then
uses the constructor's PROJECTION rather than the whole view. It is the same
clause: a handle in a well-formed store carries the tag of its own view
(`StoreWF`'s `intern`/`push` clause), and the two forms differ only on a
DANGLING handle, where the `else` arm answers `h` and `view` would fail — a
state the checker never builds and `StoreWF` excludes.
**The memo probe before the node read**: two reads of the state commute. -/
/-! ### The arms, split (DESIGN §8.6's ruling of 2026-09-22)
The coordinator's ruling after task #97-P3-0: the Lean twin splits every
multi-arm body into one `def` per constructor arm inside a `mutual` block,
the dispatcher calling the arms by name (no closures — DESIGN §3.4). The
Rust keeps its inline arms; the refinement maps one Rust function onto the
twin's dispatcher-plus-arms, the same denotation, a twin-ledger row of the
"shape" kind. The measured reason is Theorem 1's elaboration: 72 s on this
one inline body (task #97-P3-0's §4) against a few seconds per arm.
**Where the cut goes**: at the memo probe (task #97b). Each arm owns its
probe, its projection, its recursion, its rebuild and its insert; the
dispatcher is the cutoff, the tag chain and nothing else. The measure is the
lexicographic `(fuel, tag)` task #97b predicted — the dispatcher at tag `0`
calls an arm at `fuel - 1`, and an arm at tag `1` calls the dispatcher at its
own fuel. A leaf arm whose whole body is `pure h` has nothing to split and
stays in the dispatcher. -/
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:453-484 instantiate1XP — the
`bvar` arm. It does not recurse, so it sits outside the `mutual` block:
`i = d` answers the substituted handle, `i > d` interns the lowered index,
`i < d` answers the handle itself. -/
def instantiate1ArmBVar (v : EIdx) (h : EIdx) (d : Nat) : AM EIdx := do
match ← viewBVar h with
| none => failDanglingE
| some i =>
if i = d then pure v
else if i > d then internBVarE (i - 1)
else pure h
mutual
/-- con-leche: ConLeche/Kernel/ExprOps.lean:24-40 instantiate1
con-leche: ConLeche/Cached/ExprOpsC.lean:453-484 instantiate1XP
Replace `bvar d` by `v`, lowering loose `bvar`s above `d` by one. The
derived-word cutoff comes first (`bvarB ≤ d`, read off the packed word in
`O(1)`); the five leaf kinds answer without touching the memo; everything
else hands off to its arm, which probes the memo, runs the body one level
down and inserts.
`else .bvar i` is `pure h`: the node is already interned and `denoteE` is
injective, so rebuilding it yields the same handle. -/
def instantiate1Go (v : EIdx) (fuel : Nat) (h : EIdx) (d : Nat) : AM EIdx :=
match fuel with
| 0 => fail (.internal "fuel exhausted: instantiate1")
| fuel + 1 => do
let der ← derivedE h
let b := (bvarOfData der).toNat
if b < satRange && b ≤ d then
pure h
else
let tg := h.tag
if tg == ETag.app then instantiate1ArmApp v fuel h d
else if ETag.isBind tg then instantiate1ArmBind v fuel h d
else if tg == ETag.bvar then instantiate1ArmBVar v h d
else if tg == ETag.letE then instantiate1ArmLet v fuel h d
else if tg == ETag.proj then instantiate1ArmProj v fuel h d
else pure h
termination_by (fuel, 0)
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:453-484 instantiate1XP — the `app`
arm: probe, project, recurse into both children, rebuild, insert. -/
def instantiate1ArmApp (v : EIdx) (fuel : Nat) (h : EIdx) (d : Nat) :
AM EIdx := do
match ← inst1Get (h, d) with
| some r => pure r
| none =>
match ← viewApp h with
| none => failDanglingE
| some (f, a) => do
let f' ← instantiate1Go v fuel f d
let a' ← instantiate1Go v fuel a d
let r ← internAppE f' a'
inst1Set (h, d) r
pure r
termination_by (fuel, 1)
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:453-484 instantiate1XP — the
binder arm, `lam` and `forallE` in one exactly as the tag dispatch tests them
(`ETag.isBind`); the datum travels as a HANDLE (task #97-P6-16). -/
def instantiate1ArmBind (v : EIdx) (fuel : Nat) (h : EIdx) (d : Nat) :
AM EIdx := do
match ← inst1Get (h, d) with
| some r => pure r
| none =>
match ← viewBind h with
| none => failDanglingE
| some (ty, body) => do
let t ← instantiate1Go v fuel ty d
let b' ← instantiate1Go v fuel body (d + 1)
let r ← internBindE h.tag t b'
inst1Set (h, d) r
pure r
termination_by (fuel, 1)
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:453-484 instantiate1XP — the
`letE` arm; the body descends at `d + 1`. -/
def instantiate1ArmLet (v : EIdx) (fuel : Nat) (h : EIdx) (d : Nat) :
AM EIdx := do
match ← inst1Get (h, d) with
| some r => pure r
| none =>
match ← viewLet h with
| none => failDanglingE
| some (ty, val, body) => do
let t ← instantiate1Go v fuel ty d
let w ← instantiate1Go v fuel val d
let b' ← instantiate1Go v fuel body (d + 1)
let r ← internLetEE t w b'
inst1Set (h, d) r
pure r
termination_by (fuel, 1)
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:453-484 instantiate1XP — the
`proj` arm. -/
def instantiate1ArmProj (v : EIdx) (fuel : Nat) (h : EIdx) (d : Nat) :
AM EIdx := do
match ← inst1Get (h, d) with
| some r => pure r
| none =>
match ← viewProj h with
| none => failDanglingE
| some (n, i, sub) => do
let u ← instantiate1Go v fuel sub d
let r ← internProjE n i u
inst1Set (h, d) r
pure r
termination_by (fuel, 1)
end
/-- con-leche: none — `instantiate1Go`'s clause at fuel `0`, as an equation
lemma. A walk whose measure is `termination_by` rather than a constructor
pattern has its clauses as lemmas, and its proofs hand `vcgen` the clause
(`Bridge/ExprOps/Inst1.lean`), not the definition. -/
theorem instantiate1Go_zero (v h : EIdx) (d : Nat) :
instantiate1Go v 0 h d =
fail (.internal "fuel exhausted: instantiate1") := by
rw [instantiate1Go]
/-- con-leche: none — `instantiate1Go`'s clause at `fuel + 1` (template rule
9): the cutoff, then the tag chain, then the arms by name. -/
theorem instantiate1Go_succ (v : EIdx) (fuel : Nat) (h : EIdx) (d : Nat) :
instantiate1Go v (fuel + 1) h d = (do
let der ← derivedE h
let b := (bvarOfData der).toNat
if b < satRange && b ≤ d then
pure h
else
let tg := h.tag
if tg == ETag.app then instantiate1ArmApp v fuel h d
else if ETag.isBind tg then instantiate1ArmBind v fuel h d
else if tg == ETag.bvar then instantiate1ArmBVar v h d
else if tg == ETag.letE then instantiate1ArmLet v fuel h d
else if tg == ETag.proj then instantiate1ArmProj v fuel h d
else pure h) := by
rw [instantiate1Go]
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:486-489 instantiate1C — the
top-level entry: `(instantiate1Go v {} e d).1`, i.e. the memo is fresh before
and dropped after, because it depends on the substituted term. -/
def instantiate1Fast (fuel : Nat) (e v : EIdx) (d : Nat := 0) : AM EIdx := do
inst1Clear
let r ← instantiate1Go v fuel e d
inst1Clear
pure r
/-! ## `instantiateList` — `ExprOps.lean:191-235`, `:267-303`, `:371-373`
**Two** twins, not one: `instantiateListGo`'s `bvar` arm calls the PURE
`instantiateList` (`ExprOps.lean:288`), because that arm recurses into the
replacement with a *shorter* list and the memo is keyed for the outer one. -/
mutual
/-- con-leche: ConLeche/Kernel/ExprOps.lean:532-576 instantiateList
con-leche: ConLeche/Cached/ExprOpsC.lean:639-667 instantiateRevP — the
unmemoized bulk instantiation of the range `vs[n - k:n]`, read from its end
(`instantiateRevP vs n e k d`). con-leche's termination measure is
`(vs.length, sizeOf e)`; the arena's single fuel counter decreases on both
kinds of recursive call, which is the same order flattened. This is the
DISPATCHER; the arms are split per DESIGN §8.6's ruling of 2026-09-22.
DEVIATION (task #97f): the derived-word cutoff `bvarBRaw < satRange &&
bvarBRaw ≤ d`, which con-leche does not have. Denotation-preserving by
`looseBVarsBounded d e → instantiateList e vs d = e` (the module note above
states the induction; P3 discharges it). It is what makes the `.bvar` arm's
recursion into a `bvar`-closed replacement `O(1)` instead of a traversal. -/
def instantiateList (vs : Array EIdx) (n k : Nat) (fuel : Nat) (h : EIdx) (d : Nat) :
AM EIdx :=
match fuel with
| 0 => fail (.internal "fuel exhausted: instantiateList")
| fuel + 1 => do
if ← instListCutoff h d then
pure h
else
let tg := h.tag
if tg == ETag.app then instListArmApp vs n k fuel h d
else if ETag.isBind tg then instListArmBind vs n k fuel h d
else if tg == ETag.letE then instListArmLet vs n k fuel h d
else if tg == ETag.proj then instListArmProj vs n k fuel h d
else if tg == ETag.bvar then instListArmBVar vs n k fuel h d
else pure h
termination_by (fuel, 0)
/-- con-leche: ConLeche/Kernel/ExprOps.lean:532-576 instantiateList — the
`app` arm. -/
def instListArmApp (vs : Array EIdx) (n k : Nat) (fuel : Nat) (h : EIdx) (d : Nat) :
AM EIdx := do
match ← viewApp h with
| none => failDanglingE
| some (f, a) => do
let f' ← instantiateList vs n k fuel f d
let a' ← instantiateList vs n k fuel a d
internAppE f' a'
termination_by (fuel, 1)
/-- con-leche: ConLeche/Kernel/ExprOps.lean:532-576 instantiateList — the
binder arm. -/
def instListArmBind (vs : Array EIdx) (n k : Nat) (fuel : Nat) (h : EIdx) (d : Nat) :
AM EIdx := do
match ← viewBind h with
| none => failDanglingE
| some (ty, body) => do
let t ← instantiateList vs n k fuel ty d
let b ← instantiateList vs n k fuel body (d + 1)
internBindE h.tag t b
termination_by (fuel, 1)
/-- con-leche: ConLeche/Kernel/ExprOps.lean:532-576 instantiateList — the
`letE` arm. -/
def instListArmLet (vs : Array EIdx) (n k : Nat) (fuel : Nat) (h : EIdx) (d : Nat) :
AM EIdx := do
match ← viewLet h with
| none => failDanglingE
| some (ty, val, body) => do
let t ← instantiateList vs n k fuel ty d
let w ← instantiateList vs n k fuel val d
let b ← instantiateList vs n k fuel body (d + 1)
internLetEE t w b
termination_by (fuel, 1)
/-- con-leche: ConLeche/Kernel/ExprOps.lean:532-576 instantiateList — the
`proj` arm. -/
def instListArmProj (vs : Array EIdx) (n k : Nat) (fuel : Nat) (h : EIdx) (d : Nat) :
AM EIdx := do
match ← viewProj h with
| none => failDanglingE
| some (sn, i, sub) => do
let u ← instantiateList vs n k fuel sub d
internProjE sn i u
termination_by (fuel, 1)
/-- con-leche: ConLeche/Kernel/ExprOps.lean:532-576 instantiateList — the
`bvar` arm, which is the one that recurses with a SHORTER range. -/
def instListArmBVar (vs : Array EIdx) (n k : Nat) (fuel : Nat) (h : EIdx) (d : Nat) :
AM EIdx := do
match ← viewBVar h with
| none => failDanglingE
| some j =>
if j < d then pure h
else if j - d < k then
if hlt : j - d < n ∧ n ≤ vs.size then
-- **The range is read from its end** (con-leche's `instantiateRevP vs
-- n e k d`): con-leche's `vs[j - d]`, the innermost binder's argument
-- first, is `vs[n - 1 - (j - d)]`.
let vi := vs[n - 1 - (j - d)]'(by omega)
-- **The cutoff before the re-entry** (task #97-P6-9). The recursion
-- into the replacement is con-leche's own
-- `instantiateList vs[j-d] (vs.take (j-d)) d`, and its own note says it
-- is the identity on `bvar`-closed replacements (every checker call
-- site) — which is exactly what `instListCutoff` decides, in `O(1)` off
-- the handle's derived word. The re-entry is the same range's last
-- `j - d` entries, read in place: the walk at `k := j - d`.
if ← instListCutoff vi d then pure vi
else instantiateList vs n (j - d) fuel vi d
else pure h
else internBVarE (j - k)
termination_by (fuel, 1)
end
/-- con-leche: none — `instantiateList`'s clause at fuel `0` (template rule
9, DESIGN task #97-P3-0 §4). -/
theorem instantiateList_zero (vs : Array EIdx) (n k : Nat) (h : EIdx) (d : Nat) :
instantiateList vs n k 0 h d =
fail (.internal "fuel exhausted: instantiateList") := by
rw [instantiateList]
/-- con-leche: none — `instantiateList`'s clause at `fuel + 1` (template rule
9). -/
theorem instantiateList_succ (vs : Array EIdx) (n k : Nat) (fuel : Nat) (h : EIdx)
(d : Nat) :
instantiateList vs n k (fuel + 1) h d = (do
if ← instListCutoff h d then
pure h
else
let tg := h.tag
if tg == ETag.app then instListArmApp vs n k fuel h d
else if ETag.isBind tg then instListArmBind vs n k fuel h d
else if tg == ETag.letE then instListArmLet vs n k fuel h d
else if tg == ETag.proj then instListArmProj vs n k fuel h d
else if tg == ETag.bvar then instListArmBVar vs n k fuel h d
else pure h) := by
rw [instantiateList]
mutual
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:590-626 instantiateListXP
con-leche: ConLeche/Cached/ExprOpsC.lean:740-776 instantiateRevXP — the
memoized bulk instantiation of the range `vs[n - k:n]`. The `bvar` arm delegates to the pure walk
above, exactly as con-leche's does — so it is called by name and is not one
of this block's arms. This is the DISPATCHER; the arms are split per DESIGN
§8.6's ruling of 2026-09-22.
DEVIATION (task #97f): the same derived-word cutoff as the pure walk, with
the same licence. -/
def instantiateListGo (vs : Array EIdx) (n k : Nat) (fuel : Nat) (h : EIdx) (d : Nat) :
AM EIdx :=
match fuel with
| 0 => fail (.internal "fuel exhausted: instantiateList")
| fuel + 1 => do
if ← instListCutoff h d then
pure h
else
let tg := h.tag
if tg == ETag.app then instListGoArmApp vs n k fuel h d
else if ETag.isBind tg then instListGoArmBind vs n k fuel h d
else if tg == ETag.letE then instListGoArmLet vs n k fuel h d
else if tg == ETag.proj then instListGoArmProj vs n k fuel h d
else if tg == ETag.bvar then instantiateList vs n k fuel h d
else pure h
termination_by (fuel, 0)
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:590-626 instantiateListXP — the
`app` arm. -/
def instListGoArmApp (vs : Array EIdx) (n k : Nat) (fuel : Nat) (h : EIdx) (d : Nat) :
AM EIdx := do
match ← instLGet (h, d) with
| some r => pure r
| none =>
match ← viewApp h with
| none => failDanglingE
| some (f, a) => do
let f' ← instantiateListGo vs n k fuel f d
let a' ← instantiateListGo vs n k fuel a d
let r ← internAppE f' a'
instLSet (h, d) r
pure r
termination_by (fuel, 1)
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:590-626 instantiateListXP — the
binder arm. -/
def instListGoArmBind (vs : Array EIdx) (n k : Nat) (fuel : Nat) (h : EIdx) (d : Nat) :
AM EIdx := do
match ← instLGet (h, d) with
| some r => pure r
| none =>
match ← viewBind h with
| none => failDanglingE
| some (ty, body) => do
let t ← instantiateListGo vs n k fuel ty d
let b ← instantiateListGo vs n k fuel body (d + 1)
let r ← internBindE h.tag t b
instLSet (h, d) r
pure r
termination_by (fuel, 1)
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:590-626 instantiateListXP — the
`letE` arm. -/
def instListGoArmLet (vs : Array EIdx) (n k : Nat) (fuel : Nat) (h : EIdx) (d : Nat) :
AM EIdx := do
match ← instLGet (h, d) with
| some r => pure r
| none =>
match ← viewLet h with
| none => failDanglingE
| some (ty, val, body) => do
let t ← instantiateListGo vs n k fuel ty d
let w ← instantiateListGo vs n k fuel val d
let b ← instantiateListGo vs n k fuel body (d + 1)
let r ← internLetEE t w b
instLSet (h, d) r
pure r
termination_by (fuel, 1)
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:590-626 instantiateListXP — the
`proj` arm. -/
def instListGoArmProj (vs : Array EIdx) (n k : Nat) (fuel : Nat) (h : EIdx) (d : Nat) :
AM EIdx := do
match ← instLGet (h, d) with
| some r => pure r
| none =>
match ← viewProj h with
| none => failDanglingE
| some (sn, i, sub) => do
let u ← instantiateListGo vs n k fuel sub d
let r ← internProjE sn i u
instLSet (h, d) r
pure r
termination_by (fuel, 1)
end
/-- con-leche: none — `instantiateListGo`'s clause at fuel `0` (template rule
9). -/
theorem instantiateListGo_zero (vs : Array EIdx) (n k : Nat) (h : EIdx) (d : Nat) :
instantiateListGo vs n k 0 h d =
fail (.internal "fuel exhausted: instantiateList") := by
rw [instantiateListGo]
/-- con-leche: none — `instantiateListGo`'s clause at `fuel + 1` (template
rule 9). -/
theorem instantiateListGo_succ (vs : Array EIdx) (n k : Nat) (fuel : Nat) (h : EIdx)
(d : Nat) :
instantiateListGo vs n k (fuel + 1) h d = (do
if ← instListCutoff h d then
pure h
else
let tg := h.tag
if tg == ETag.app then instListGoArmApp vs n k fuel h d
else if ETag.isBind tg then instListGoArmBind vs n k fuel h d
else if tg == ETag.letE then instListGoArmLet vs n k fuel h d
else if tg == ETag.proj then instListGoArmProj vs n k fuel h d
else if tg == ETag.bvar then instantiateList vs n k fuel h d
else pure h) := by
rw [instantiateListGo]
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:780-790 instantiateRevRange —
**bulk instantiation from the range `vs[s:n]`**, read from its end: bound
variable `j` below `n - s` becomes `vs[n - 1 - j]`. `n` is clamped to the
array once. The memo is fresh before and dropped after, because it depends
on the substituted range. -/
def instantiateRevRange (fuel : Nat) (e : EIdx) (vs : Array EIdx) (s n : Nat)
(d : Nat := 0) : AM EIdx := do
let n2 := if n < vs.size then n else vs.size
let k := if s < n2 then n2 - s else 0
instLClear
let r ← instantiateListGo vs n2 k fuel e d
instLClear
pure r
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:630-637 instantiateListC
con-leche: ConLeche/Cached/ExprOpsC.lean:792-795 instantiateRev — the whole
array's range: the push-order array is con-leche's `instantiateRev` array,
and the reverse of `instantiateListC`'s list. -/
def instantiateListFast (fuel : Nat) (e : EIdx) (vs : Array EIdx) (d : Nat := 0) :
AM EIdx :=
instantiateRevRange fuel e vs 0 vs.size d
/-! ## `liftLooseBVars` — `ExprOps.lean:380-400`, `:430-466`, `:532-534` -/
mutual
/-- con-leche: ConLeche/Kernel/ExprOps.lean:672-692 liftLooseBVars
con-leche: ConLeche/Cached/ExprOpsC.lean:293-323 liftLooseBVarsXP
Bump every loose bound variable `≥ cutoff` by `amount`. This is the
DISPATCHER (arms split per DESIGN §8.6's ruling of 2026-09-22). A leaf arm
whose whole body is `pure h` has nothing to split and stays here; every arm
with a memo probe is a `def` of its own, and takes the children the
dispatcher's `view` already projected — a second store read per node is what
the split must NOT cost.
DEVIATION (task #97f): the derived-word cutoff `bvarBRaw < satRange &&
bvarBRaw ≤ c`, which con-leche does not have. Denotation-preserving by
`looseBVarsBounded c e → liftLooseBVars e c amount = e` (the module note
above states the induction; P3 discharges it). -/
def liftLooseBVarsGo (amount : Nat) (fuel : Nat) (h : EIdx) (c : Nat) :
AM EIdx :=
match fuel with
| 0 => fail (.internal "fuel exhausted: liftLooseBVars")
| fuel + 1 => do
let bRaw := (bvarOfData (← derivedE h)).toNat
if bRaw < satRange && bRaw ≤ c then
pure h
else
match ← view h with
| .bvar i => if i ≥ c then internE (.bvar (i + amount)) else pure h
| .fvar _ _ => pure h
| .sort _ => pure h
| .const _ _ => pure h
| .lit _ => pure h
| .app a b => liftArmApp amount fuel h c a b
| .lam ty body => liftArmLam amount fuel h c ty body
| .forallE ty body => liftArmForallE amount fuel h c ty body
| .letE ty val body => liftArmLet amount fuel h c ty val body
| .proj n i sub => liftArmProj amount fuel h c n i sub
termination_by (fuel, 0)
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:293-323 liftLooseBVarsXP — the
`app` arm. -/
def liftArmApp (amount fuel : Nat) (h : EIdx) (c : Nat) (a b : EIdx) :
AM EIdx := do
match ← liftGet (h, c) with
| some r => pure r
| none => do
let a' ← liftLooseBVarsGo amount fuel a c
let b' ← liftLooseBVarsGo amount fuel b c
let r ← internE (.app a' b')
liftSet (h, c) r
pure r
termination_by (fuel, 1)
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:293-323 liftLooseBVarsXP — the
`lam` arm; the body descends at `c + 1`. -/
def liftArmLam (amount fuel : Nat) (h : EIdx) (c : Nat) (ty body : EIdx) :
AM EIdx := do
match ← liftGet (h, c) with
| some r => pure r
| none => do
let t ← liftLooseBVarsGo amount fuel ty c
let b ← liftLooseBVarsGo amount fuel body (c + 1)
let r ← internLamE t b
liftSet (h, c) r
pure r
termination_by (fuel, 1)
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:293-323 liftLooseBVarsXP — the
`forallE` arm. -/
def liftArmForallE (amount fuel : Nat) (h : EIdx) (c : Nat) (ty body : EIdx) :
AM EIdx := do
match ← liftGet (h, c) with
| some r => pure r
| none => do
let t ← liftLooseBVarsGo amount fuel ty c
let b ← liftLooseBVarsGo amount fuel body (c + 1)
let r ← internForallEE t b
liftSet (h, c) r
pure r
termination_by (fuel, 1)
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:293-323 liftLooseBVarsXP — the
`letE` arm. -/
def liftArmLet (amount fuel : Nat) (h : EIdx) (c : Nat) (ty val body : EIdx) :
AM EIdx := do
match ← liftGet (h, c) with
| some r => pure r
| none => do
let t ← liftLooseBVarsGo amount fuel ty c
let w ← liftLooseBVarsGo amount fuel val c
let b ← liftLooseBVarsGo amount fuel body (c + 1)
let r ← internE (.letE t w b)
liftSet (h, c) r
pure r
termination_by (fuel, 1)
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:293-323 liftLooseBVarsXP — the
`proj` arm. -/
def liftArmProj (amount fuel : Nat) (h : EIdx) (c : Nat) (n : NIdx) (i : Nat)
(sub : EIdx) : AM EIdx := do
match ← liftGet (h, c) with
| some r => pure r
| none => do
let u ← liftLooseBVarsGo amount fuel sub c
let r ← internE (.proj n i u)
liftSet (h, c) r
pure r
termination_by (fuel, 1)
end
/-- con-leche: none — `liftLooseBVarsGo`'s clause at fuel `0` (template rule
9). -/
theorem liftLooseBVarsGo_zero (amount : Nat) (h : EIdx) (c : Nat) :
liftLooseBVarsGo amount 0 h c =
fail (.internal "fuel exhausted: liftLooseBVars") := by
rw [liftLooseBVarsGo]
/-- con-leche: none — `liftLooseBVarsGo`'s clause at `fuel + 1` (template
rule 9). -/
theorem liftLooseBVarsGo_succ (amount fuel : Nat) (h : EIdx) (c : Nat) :
liftLooseBVarsGo amount (fuel + 1) h c = (do
let bRaw := (bvarOfData (← derivedE h)).toNat
if bRaw < satRange && bRaw ≤ c then
pure h
else
match ← view h with
| .bvar i => if i ≥ c then internE (.bvar (i + amount)) else pure h
| .fvar _ _ => pure h
| .sort _ => pure h
| .const _ _ => pure h
| .lit _ => pure h
| .app a b => liftArmApp amount fuel h c a b
| .lam ty body => liftArmLam amount fuel h c ty body
| .forallE ty body => liftArmForallE amount fuel h c ty body
| .letE ty val body => liftArmLet amount fuel h c ty val body
| .proj n i sub => liftArmProj amount fuel h c n i sub) := by
rw [liftLooseBVarsGo]
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:325-329 liftLooseBVarsC — the
top-level entry. -/
def liftLooseBVarsFast (fuel amount c : Nat) (e : EIdx) : AM EIdx := do
liftClear
let r ← liftLooseBVarsGo amount fuel e c
liftClear
pure r
/-! ## The measures and the scope predicates -/
mutual
/-- con-leche: ConLeche/Kernel/ExprOps.lean:717-724 sizeB — the binder
node count, `fvar` annotations NOT descended into. The dispatcher (arms
split per DESIGN §8.6's ruling of 2026-09-22); the five leaf kinds are one
expression and stay here. -/
def sizeB (fuel : Nat) (h : EIdx) : AM Nat :=
match fuel with
| 0 => fail (.internal "fuel exhausted: sizeB")
| fuel + 1 => do
match ← view h with
| .bvar _ | .fvar _ _ | .sort _ | .const _ _ | .lit _ => pure 1
| .app f a => sizeBArmApp fuel f a
| .lam ty body | .forallE ty body => sizeBArmBind fuel ty body
| .letE ty val body => sizeBArmLet fuel ty val body
| .proj _ _ sub => sizeBArmProj fuel sub
termination_by (fuel, 0)
/-- con-leche: ConLeche/Kernel/ExprOps.lean:717-724 sizeB — the `app`
arm. -/
def sizeBArmApp (fuel : Nat) (f a : EIdx) : AM Nat := do
let x ← sizeB fuel f
let y ← sizeB fuel a
pure (x + y + 1)
termination_by (fuel, 1)
/-- con-leche: ConLeche/Kernel/ExprOps.lean:717-724 sizeB — the binder
arm (`lam` and `forallE` share it, as they do in con-leche). -/
def sizeBArmBind (fuel : Nat) (ty body : EIdx) : AM Nat := do
let x ← sizeB fuel ty
let y ← sizeB fuel body
pure (x + y + 1)
termination_by (fuel, 1)
/-- con-leche: ConLeche/Kernel/ExprOps.lean:717-724 sizeB — the `letE`
arm. -/
def sizeBArmLet (fuel : Nat) (ty val body : EIdx) : AM Nat := do
let x ← sizeB fuel ty
let y ← sizeB fuel val
let z ← sizeB fuel body
pure (x + y + z + 1)
termination_by (fuel, 1)
/-- con-leche: ConLeche/Kernel/ExprOps.lean:717-724 sizeB — the `proj`
arm. -/
def sizeBArmProj (fuel : Nat) (sub : EIdx) : AM Nat := do
let x ← sizeB fuel sub
pure (x + 1)
termination_by (fuel, 1)
end
mutual
/-- con-leche: ConLeche/Kernel/ExprOps.lean:797-809 fvarLeaves — all reachable
`fvar` leaves, hereditarily through their annotations. The dispatcher (arms
split per DESIGN §8.6's ruling of 2026-09-22). -/
def fvarLeaves (fuel : Nat) (h : EIdx) : AM (List (Nat × EIdx)) :=
match fuel with
| 0 => fail (.internal "fuel exhausted: fvarLeaves")
| fuel + 1 => do
match ← view h with
| .fvar idx ty => fvarLeavesArmFVar fuel idx ty
| .app f a => fvarLeavesArmApp fuel f a
| .lam ty b | .forallE ty b => fvarLeavesArmBind fuel ty b
| .letE t v b => fvarLeavesArmLet fuel t v b
| .proj _ _ sub => fvarLeaves fuel sub
| .bvar _ | .sort _ | .const _ _ | .lit _ => pure []
termination_by (fuel, 0)
/-- con-leche: ConLeche/Kernel/ExprOps.lean:797-809 fvarLeaves — the `fvar`
arm: the leaf itself, then its annotation. -/
def fvarLeavesArmFVar (fuel : Nat) (idx : Nat) (ty : EIdx) :
AM (List (Nat × EIdx)) := do
let rest ← fvarLeaves fuel ty
pure ((idx, ty) :: rest)
termination_by (fuel, 1)
/-- con-leche: ConLeche/Kernel/ExprOps.lean:797-809 fvarLeaves — the `app`
arm. -/
def fvarLeavesArmApp (fuel : Nat) (f a : EIdx) : AM (List (Nat × EIdx)) := do
let x ← fvarLeaves fuel f
let y ← fvarLeaves fuel a
pure (x ++ y)
termination_by (fuel, 1)
/-- con-leche: ConLeche/Kernel/ExprOps.lean:797-809 fvarLeaves — the binder
arm. -/
def fvarLeavesArmBind (fuel : Nat) (ty b : EIdx) : AM (List (Nat × EIdx)) := do
let x ← fvarLeaves fuel ty
let y ← fvarLeaves fuel b
pure (x ++ y)
termination_by (fuel, 1)
/-- con-leche: ConLeche/Kernel/ExprOps.lean:797-809 fvarLeaves — the `letE`
arm. -/
def fvarLeavesArmLet (fuel : Nat) (t v b : EIdx) : AM (List (Nat × EIdx)) := do
let x ← fvarLeaves fuel t
let y ← fvarLeaves fuel v
let z ← fvarLeaves fuel b
pure (x ++ y ++ z)
termination_by (fuel, 1)
end
/-! ## The scope queries, MEMOIZED — `Cached/ExprOpsC.lean:997-1268`
The three walks above (`fvarLeaves`, `wscopedB`, and `Core.lean`'s leaf-subset
test) are `Kernel/ExprOps.lean`'s, and over an arena they are the wrong ones.
con-leche runs them on `Expr` TREES, where a walk is linear in the term; (B)
runs them on a hash-consed DAG, where an unmemoized walk is linear in the
term's *unfolding* — which is what hash-consing exists to avoid. con-leche's
EXECUTED tier knows this and carries `wscopedBGoC` ("one memoized DAG walk"),
`fvarLeavesGoC` (a `seen` set) and `leavesSubGo` (task #86's leaf guard, which
never builds the fabrication's leaf list at all); task #97d's twin took the
spec tier's and lost all three. Measured (task #97g): on `core.ndjson`'s
first 27 920 declarations the unmemoized `fabScopeOk` was **43.9 % of the
cycles**, with `fvarLeaves` 2.6 % and `wscopedB` 1.6 % beside it.
Each memo is threaded as an argument-and-result pair rather than put in
`Memos`, which is con-leche's own spelling: the tables are per-CALL and two of the three
depend on data that is not in the key (`leavesSubGo`'s base list), so a
state-carried table would need a clear at every entry anyway.
The `fvarB == 0` short-circuit at the head of each is con-leche's, and it is
the RAW packed field: on the saturated branch the field is `satRange ≠ 0`, so
the test simply does not fire and the walk proceeds — no recomputation.
**Where these citations point since con-leche `78ded4b6` (task #97-catchup).**
Upstream's tasks #313–#319 rewrote every traversal memo in its CACHED tier:
one walk became three declarations — `<name>P`, the memo-free plain descent
that is the specification; `enter<X>P`, the child step, which makes the cutoff
and the compound test and reads `withExclusive`; and `<name>XP`, the walk that
carries its own proof over an ADDRESS key. `wscopedBGoC` is now `wscopedBXP`
and `leavesSubGo` is now `leavesSubXP`, and that is the whole of what this bump
costs these twins: **no arm of any walk below changed**, compared clause for
clause against upstream's new `wscopedBP` / `leavesSubP`. The cutoff that
upstream moved out into `wscopedBC` / `leavesSubC` is still made at the head of
each recursive call here, exactly as `enterWSP` / `enterLSub` make it, so the
computation is the same one.
**And nothing of #319's `withExclusive` gate is owed to this twin.** That
idiom is the CACHED tier's: it asks whether an `Expr` node's reference count
is one and skips the memo when it is, because a node with a single parent
cannot be reached twice. The arena has no reference counts — a term is an
`EIdx` into a per-constructor array, shared by construction — so the question
has no answer here, and the memo policy of DESIGN §8.3 (per-call tables,
handle keys, a cutoff off the derived word) is the arena's own and unchanged.
`crates/con-ron-core`'s `ron::node::is_exclusive` (hole #23, task #98) is the
`Expr`-tier port's answer to the same upstream change; the arena tier has and
needs none. -/
mutual
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:1431-1490 wscopedBXP — the
memoized scope walk. `fvar` annotations are descended (at the annotation's
own index, not `d`), so the cached fvar range does not decide it and the memo
key carries `d`. The dispatcher (arms split per DESIGN §8.6's ruling of
2026-09-22); the memo travels as an argument-and-result pair, so each arm
takes it and returns it. -/
def wscopedBGo (memo : Std.HashMap (EIdx × Nat) Bool) (fuel : Nat) (d : Nat)
(h : EIdx) : AM (Bool × Std.HashMap (EIdx × Nat) Bool) :=
match fuel with
| 0 => fail (.internal "fuel exhausted: wscopedBGo")
| fuel + 1 => do
if (fvarOfData (← derivedE h)).toNat == 0 then pure (true, memo)
else
match memo[(h, d)]? with
| some r => pure (r, memo)
| none => do
let (r, memo') ←
match ← view h with
| .bvar _ | .sort _ | .const _ _ | .lit _ => pure (true, memo)
| .fvar idx ty =>
if idx < d then wscopedBGo memo fuel idx ty
else pure (false, memo)
| .app f a => wscopedBGoArmApp memo fuel d f a
| .lam ty body => wscopedBGoArmBind memo fuel d ty body
| .forallE ty body => wscopedBGoArmBind memo fuel d ty body
| .letE ty val body => wscopedBGoArmLet memo fuel d ty val body
| .proj _ _ sub => wscopedBGo memo fuel d sub
pure (r, memo'.insert (h, d) r)
termination_by (fuel, 0)
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:1431-1490 wscopedBXP — the `app`
arm. -/
def wscopedBGoArmApp (memo : Std.HashMap (EIdx × Nat) Bool) (fuel : Nat)
(d : Nat) (f a : EIdx) : AM (Bool × Std.HashMap (EIdx × Nat) Bool) := do
let (rf, memo) ← wscopedBGo memo fuel d f
if rf then wscopedBGo memo fuel d a else pure (false, memo)
termination_by (fuel, 1)
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:1431-1490 wscopedBXP — the
binder arm (`lam` and `forallE` have the same clause, so they share it). -/
def wscopedBGoArmBind (memo : Std.HashMap (EIdx × Nat) Bool) (fuel : Nat)
(d : Nat) (ty body : EIdx) :
AM (Bool × Std.HashMap (EIdx × Nat) Bool) := do
let (rt, memo) ← wscopedBGo memo fuel d ty
if rt then wscopedBGo memo fuel d body else pure (false, memo)
termination_by (fuel, 1)
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:1431-1490 wscopedBXP — the
`letE` arm. -/
def wscopedBGoArmLet (memo : Std.HashMap (EIdx × Nat) Bool) (fuel : Nat)
(d : Nat) (ty val body : EIdx) :
AM (Bool × Std.HashMap (EIdx × Nat) Bool) := do
let (rt, memo) ← wscopedBGo memo fuel d ty
if rt then do
let (rv, memo) ← wscopedBGo memo fuel d val
if rv then wscopedBGo memo fuel d body else pure (false, memo)
else pure (false, memo)
termination_by (fuel, 1)
end
/-- con-leche: none — `wscopedBGo`'s clause at fuel `0` (template rule 9). -/
theorem wscopedBGo_zero (memo : Std.HashMap (EIdx × Nat) Bool) (d : Nat)
(h : EIdx) :
wscopedBGo memo 0 d h = fail (.internal "fuel exhausted: wscopedBGo") := by
rw [wscopedBGo]
/-- con-leche: none — `wscopedBGo`'s clause at `fuel + 1` (template rule
9). -/
theorem wscopedBGo_succ (memo : Std.HashMap (EIdx × Nat) Bool) (fuel : Nat)
(d : Nat) (h : EIdx) :
wscopedBGo memo (fuel + 1) d h = (do
if (fvarOfData (← derivedE h)).toNat == 0 then pure (true, memo)
else
match memo[(h, d)]? with
| some r => pure (r, memo)
| none => do
let (r, memo') ←
match ← view h with
| .bvar _ | .sort _ | .const _ _ | .lit _ => pure (true, memo)
| .fvar idx ty =>
if idx < d then wscopedBGo memo fuel idx ty
else pure (false, memo)
| .app f a => wscopedBGoArmApp memo fuel d f a
| .lam ty body => wscopedBGoArmBind memo fuel d ty body
| .forallE ty body => wscopedBGoArmBind memo fuel d ty body
| .letE ty val body => wscopedBGoArmLet memo fuel d ty val body
| .proj _ _ sub => wscopedBGo memo fuel d sub
pure (r, memo'.insert (h, d) r)) := by
rw [wscopedBGo]
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:1492-1497 wscopedBC — the executed
`wscopedB`: one memoized DAG walk from the empty memo. -/
def wscopedBFast (fuel d : Nat) (h : EIdx) : AM Bool := do
let p ← wscopedBGo ∅ fuel d h
pure p.1
mutual
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:1955-2009 fvarLeavesGoC — the
reachable `fvar` leaves, accumulated with a `seen` set so a shared subterm is
walked once. The accumulation order is con-leche's (its `acc` is consed on
the way in), and the result is used only as a membership base. The
dispatcher (arms split per DESIGN §8.6's ruling of 2026-09-22); the `seen`
insert happens BEFORE the arm call, which is the gray step `Bridge/ExprOps/
Leaves.lean`'s `SeenInv` is about. -/
def fvarLeavesGo (acc : List (Nat × EIdx)) (seen : Std.HashMap EIdx Unit)
(fuel : Nat) (h : EIdx) :
AM (List (Nat × EIdx) × Std.HashMap EIdx Unit) :=
match fuel with
| 0 => fail (.internal "fuel exhausted: fvarLeavesGo")
| fuel + 1 => do
if (fvarOfData (← derivedE h)).toNat == 0 then pure (acc, seen)
else
match seen[h]? with
| some _ => pure (acc, seen)
| none => do
let seen := seen.insert h ()
match ← view h with
| .bvar _ | .sort _ | .const _ _ | .lit _ => pure (acc, seen)
| .fvar idx ty => fvarLeavesGo ((idx, ty) :: acc) seen fuel ty
| .app f a => fvarLeavesGoArmApp acc seen fuel f a
| .lam ty body => fvarLeavesGoArmBind acc seen fuel ty body
| .forallE ty body => fvarLeavesGoArmBind acc seen fuel ty body
| .letE ty val body => fvarLeavesGoArmLet acc seen fuel ty val body
| .proj _ _ sub => fvarLeavesGo acc seen fuel sub
termination_by (fuel, 0)
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:1955-2009 fvarLeavesGoC — the
`app` arm. -/
def fvarLeavesGoArmApp (acc : List (Nat × EIdx))
(seen : Std.HashMap EIdx Unit) (fuel : Nat) (f a : EIdx) :
AM (List (Nat × EIdx) × Std.HashMap EIdx Unit) := do
let (acc, seen) ← fvarLeavesGo acc seen fuel f
fvarLeavesGo acc seen fuel a
termination_by (fuel, 1)
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:1955-2009 fvarLeavesGoC — the
binder arm. -/
def fvarLeavesGoArmBind (acc : List (Nat × EIdx))
(seen : Std.HashMap EIdx Unit) (fuel : Nat) (ty body : EIdx) :
AM (List (Nat × EIdx) × Std.HashMap EIdx Unit) := do
let (acc, seen) ← fvarLeavesGo acc seen fuel ty
fvarLeavesGo acc seen fuel body
termination_by (fuel, 1)
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:1955-2009 fvarLeavesGoC — the
`letE` arm. -/
def fvarLeavesGoArmLet (acc : List (Nat × EIdx))
(seen : Std.HashMap EIdx Unit) (fuel : Nat) (ty val body : EIdx) :
AM (List (Nat × EIdx) × Std.HashMap EIdx Unit) := do
let (acc, seen) ← fvarLeavesGo acc seen fuel ty
let (acc, seen) ← fvarLeavesGo acc seen fuel val
fvarLeavesGo acc seen fuel body
termination_by (fuel, 1)
end
/-- con-leche: none — `fvarLeavesGo`'s clause at fuel `0` (template rule
9). -/
theorem fvarLeavesGo_zero (acc : List (Nat × EIdx))
(seen : Std.HashMap EIdx Unit) (h : EIdx) :
fvarLeavesGo acc seen 0 h =
fail (.internal "fuel exhausted: fvarLeavesGo") := by
rw [fvarLeavesGo]
/-- con-leche: none — `fvarLeavesGo`'s clause at `fuel + 1` (template rule
9). -/
theorem fvarLeavesGo_succ (acc : List (Nat × EIdx))
(seen : Std.HashMap EIdx Unit) (fuel : Nat) (h : EIdx) :
fvarLeavesGo acc seen (fuel + 1) h = (do
if (fvarOfData (← derivedE h)).toNat == 0 then pure (acc, seen)
else
match seen[h]? with
| some _ => pure (acc, seen)
| none => do
let seen := seen.insert h ()
match ← view h with
| .bvar _ | .sort _ | .const _ _ | .lit _ => pure (acc, seen)
| .fvar idx ty => fvarLeavesGo ((idx, ty) :: acc) seen fuel ty
| .app f a => fvarLeavesGoArmApp acc seen fuel f a
| .lam ty body => fvarLeavesGoArmBind acc seen fuel ty body
| .forallE ty body => fvarLeavesGoArmBind acc seen fuel ty body
| .letE ty val body => fvarLeavesGoArmLet acc seen fuel ty val body
| .proj _ _ sub => fvarLeavesGo acc seen fuel sub) := by
rw [fvarLeavesGo]
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:2012-2013 fvarLeavesC — the
executed `fvarLeaves`. -/
def fvarLeavesFast (fuel : Nat) (h : EIdx) : AM (List (Nat × EIdx)) := do
let p ← fvarLeavesGo [] ∅ fuel h
pure p.1
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:2017-2020 leafMem — is `(idx, ty)`
in the base leaf list? con-leche compares the annotation with `Expr.beq`;
over handles it is handle equality, which is the same test (`denoteE` is
injective, DESIGN §8.3). -/
def leafMem : List (Nat × EIdx) → Nat → EIdx → Bool
| [], _, _ => false
| (i, t) :: rest, idx, ty =>
(i == idx && t == ty) || leafMem rest idx ty
mutual
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:2055-2114 leavesSubXP — the
fabrication-side leaf-subset test: every reachable `fvar` leaf of the walked
term is one of `bl`. Memoized on the node, because `bl` is fixed for the
call. The dispatcher (arms split per DESIGN §8.6's ruling of 2026-09-22);
the memo travels as an argument-and-result pair, so each arm takes it and
returns it. -/
def leavesSubGo (bl : List (Nat × EIdx)) (memo : Std.HashMap EIdx Bool)
(fuel : Nat) (h : EIdx) : AM (Bool × Std.HashMap EIdx Bool) :=
match fuel with
| 0 => fail (.internal "fuel exhausted: leavesSubGo")
| fuel + 1 => do
if (fvarOfData (← derivedE h)).toNat == 0 then pure (true, memo)
else
match memo[h]? with
| some r => pure (r, memo)
| none => do
let (r, memo') ←
match ← view h with
| .bvar _ | .sort _ | .const _ _ | .lit _ => pure (true, memo)
| .fvar idx ty =>
if leafMem bl idx ty then leavesSubGo bl memo fuel ty
else pure (false, memo)
| .app f a => leavesSubArmApp bl memo fuel f a
| .lam ty body => leavesSubArmBind bl memo fuel ty body
| .forallE ty body => leavesSubArmBind bl memo fuel ty body
| .letE ty val body => leavesSubArmLet bl memo fuel ty val body
| .proj _ _ sub => leavesSubGo bl memo fuel sub
pure (r, memo'.insert h r)
termination_by (fuel, 0)
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:2055-2114 leavesSubXP — the
`app` arm. -/
def leavesSubArmApp (bl : List (Nat × EIdx)) (memo : Std.HashMap EIdx Bool)
(fuel : Nat) (f a : EIdx) : AM (Bool × Std.HashMap EIdx Bool) := do
let (rf, memo) ← leavesSubGo bl memo fuel f
if rf then leavesSubGo bl memo fuel a else pure (false, memo)
termination_by (fuel, 1)
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:2055-2114 leavesSubXP — the
binder arm (`lam` and `forallE` have the same clause, so they share it). -/
def leavesSubArmBind (bl : List (Nat × EIdx)) (memo : Std.HashMap EIdx Bool)
(fuel : Nat) (ty body : EIdx) : AM (Bool × Std.HashMap EIdx Bool) := do
let (rt, memo) ← leavesSubGo bl memo fuel ty
if rt then leavesSubGo bl memo fuel body else pure (false, memo)
termination_by (fuel, 1)
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:2055-2114 leavesSubXP — the
`letE` arm. -/
def leavesSubArmLet (bl : List (Nat × EIdx)) (memo : Std.HashMap EIdx Bool)
(fuel : Nat) (ty val body : EIdx) :
AM (Bool × Std.HashMap EIdx Bool) := do
let (rt, memo) ← leavesSubGo bl memo fuel ty
if rt then do
let (rv, memo) ← leavesSubGo bl memo fuel val
if rv then leavesSubGo bl memo fuel body else pure (false, memo)
else pure (false, memo)
termination_by (fuel, 1)
end
/-- con-leche: none — `leavesSubGo`'s clause at fuel `0` (template rule 9). -/
theorem leavesSubGo_zero (bl : List (Nat × EIdx))
(memo : Std.HashMap EIdx Bool) (h : EIdx) :
leavesSubGo bl memo 0 h =
fail (.internal "fuel exhausted: leavesSubGo") := by
rw [leavesSubGo]
/-- con-leche: none — `leavesSubGo`'s clause at `fuel + 1` (template rule
9). -/
theorem leavesSubGo_succ (bl : List (Nat × EIdx))
(memo : Std.HashMap EIdx Bool) (fuel : Nat) (h : EIdx) :
leavesSubGo bl memo (fuel + 1) h = (do
if (fvarOfData (← derivedE h)).toNat == 0 then pure (true, memo)
else
match memo[h]? with
| some r => pure (r, memo)
| none => do
let (r, memo') ←
match ← view h with
| .bvar _ | .sort _ | .const _ _ | .lit _ => pure (true, memo)
| .fvar idx ty =>
if leafMem bl idx ty then leavesSubGo bl memo fuel ty
else pure (false, memo)
| .app f a => leavesSubArmApp bl memo fuel f a
| .lam ty body => leavesSubArmBind bl memo fuel ty body
| .forallE ty body => leavesSubArmBind bl memo fuel ty body
| .letE ty val body => leavesSubArmLet bl memo fuel ty val body
| .proj _ _ sub => leavesSubGo bl memo fuel sub
pure (r, memo'.insert h r)) := by
rw [leavesSubGo]
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:2122-2126 leafGuard — **the
fabrication leaf guard**: every `fvar` leaf of `fab` is a leaf of `base`.
Short-circuits on an `fvar`-free fabrication off the packed range, and
otherwise walks `fab` ONCE against `base`'s leaf list — never building
`fab`'s own list, and never running `Core.lean`'s quadratic
`fvarLeavesSubset`. -/
def leafGuard (fuel : Nat) (fab base : EIdx) : AM Bool := do
if (fvarOfData (← derivedE fab)).toNat == 0 then pure true
else do
let bl ← fvarLeavesFast fuel base
let p ← leavesSubGo bl ∅ fuel fab
pure p.1
/-! ## The one-node readers
Each is a single `view` and a test: no recursion, no fuel. -/
/-- con-leche: ConLeche/Kernel/ExprOps.lean:836-839 isForallE — is the
expression a ∀? A tag read off the handle word. -/
@[inline] def isForallE (h : EIdx) : Bool := h.tag == ETag.forallE
/-- con-leche: ConLeche/Kernel/ExprOps.lean:841-846 binderPair? — two λs
(`lam`) or two ∀s (`!lam`): their domains and bodies (the descent of the
binder-telescope comparison, `defeqBinders`). The tags first, then the two
binder projections. -/
def binderPair? (lam : Bool) (a b : EIdx) : AM (Option (EIdx × EIdx × EIdx × EIdx)) := do
let t := if lam then ETag.lam else ETag.forallE
if a.tag == t && b.tag == t then
match ← viewBind a with
| none => failDanglingE
| some (ty₁, body₁) =>
match ← viewBind b with
| none => failDanglingE
| some (ty₂, body₂) => pure (some (ty₁, body₁, ty₂, body₂))
else pure none
/-! ## Application spines -/
/-- con-leche: ConLeche/Kernel/ExprOps.lean:848-851 getAppFn — the head of an
application spine. -/
def getAppFn : Nat → EIdx → AM EIdx
| 0, _ => fail (.internal "fuel exhausted: getAppFn")
| fuel + 1, h => do
if h.tag == ETag.app then
match ← viewApp h with
| none => failDanglingE
| some (f, _) => getAppFn fuel f
else pure h
/-- con-leche: ConLeche/Kernel/ExprOps.lean:853-856 getAppArgs — the arguments
of an application spine, outermost last. -/
def getAppArgs : Nat → EIdx → AM (List EIdx)
| 0, _ => fail (.internal "fuel exhausted: getAppArgs")
| fuel + 1, h => do
if h.tag == ETag.app then
match ← viewApp h with
| none => failDanglingE
| some (f, a) => do
let as ← getAppArgs fuel f
pure (as ++ [a])
else pure []
/-- con-leche: ConLeche/Kernel/ExprOps.lean:858-861 mkAppN — apply to a list
of arguments. Structural on the list, so no fuel. -/
def mkAppN (f : EIdx) : List EIdx → AM EIdx
| [] => pure f
| a :: as => do
let g ← internE (.app f a)
mkAppN g as
/-- con-leche: ConLeche/Kernel/ExprOps.lean:858-861 mkAppN — apply to the
entries of a push-order array from `i` on, which is what the batched β and the
spine walks hold. §3.4's standing `List`-as-cursor deviation, at an
`Array`. -/
def mkAppNFrom (f : EIdx) (args : Array EIdx) (i : Nat) : AM EIdx := do
if h : i < args.size then do
let g ← internAppE f args[i]
mkAppNFrom g args (i + 1)
else pure f
termination_by args.size - i
decreasing_by omega
/-! ## Telescopes -/
/-- con-leche: ConLeche/Kernel/ExprOps.lean:863-869 lamBody — the body under
`k` leading λs (where there are fewer, under all of them). The recursion is
structural on `k`, so no fuel. -/
def lamBody : Nat → EIdx → AM EIdx
| 0, h => pure h
| k + 1, h => do
if h.tag == ETag.lam then
match ← viewBind h with
| none => failDanglingE
| some (_, b) => lamBody k b
else pure h
/-- con-leche: ConLeche/Kernel/ExprOps.lean:871-877 stripLams — strip `k`
leading λs. The recursion is structural on `k`, so no fuel. -/
def stripLams : Nat → EIdx → AM (Option (List EIdx × EIdx))
| 0, h => pure (some ([], h))
| k + 1, h => do
-- tag first, then the binder projection (task #97-T2-LOCKSTEP, D1)
if h.tag == ETag.lam then
match ← viewBind h with
| none => failDanglingE
| some (ty, b) => do
match ← stripLams k b with
| some p => pure (some (ty :: p.1, p.2))
| none => pure none
else pure none
/-- con-leche: ConLeche/Kernel/ExprOps.lean:879-885 stripPis — strip `k`
leading `∀`s. -/
def stripPis : Nat → EIdx → AM (Option (List EIdx × EIdx))
| 0, h => pure (some ([], h))
| k + 1, h => do
-- tag first, then the binder projection (task #97-T2-LOCKSTEP, D1)
if h.tag == ETag.forallE then
match ← viewBind h with
| none => failDanglingE
| some (ty, b) => do
match ← stripPis k b with
| some p => pure (some (ty :: p.1, p.2))
| none => pure none
else pure none
/-- con-leche: ConLeche/Kernel/ExprOps.lean:887-891 piResult — the body of a
syntactic `∀`-telescope. -/
def piResult : Nat → EIdx → AM EIdx
| 0, _ => fail (.internal "fuel exhausted: piResult")
| fuel + 1, h => do
-- tag first, then the binder projection (task #97-P5-Core round 4's audit)
if h.tag == ETag.forallE then
match ← viewBind h with
| none => failDanglingE
| some (_, b) => piResult fuel b
else pure h
/-- con-leche: ConLeche/Kernel/ExprOps.lean:911-916 fvarTypeD — the type
annotation of a free-variable leaf (the expression itself otherwise). -/
def fvarTypeD (h : EIdx) : AM EIdx := do
-- tag first, then the annotation projection (task #97-T2-LOCKSTEP, D1)
if h.tag == ETag.fvar then
match ← viewFVarTy h with
| none => failDanglingE
| some ty => pure ty
else pure h
/-- con-leche: ConLeche/Kernel/ExprOps.lean:918-926 instSpine — instantiate
a telescope-context expression at an argument spine. -/
def instSpine (fuel : Nat) : List EIdx → Nat → EIdx → AM EIdx
| [], _, e => pure e
| a :: as, t, e => do
let e' ← instantiate1Fast fuel e a t
instSpine fuel as (t - 1) e'
/-! ## The packed range fields and their saturated-branch recomputations
`ExprOps.lean:1293-1303`, `:1312-1323`, `:1368-1425`, `:1427-1439`. The
arena reads both ranges in `O(1)` off the derived column; only on the
saturated branch (a bound at or above `satRange = 32767`) does it walk, and
that walk is memoized exactly as con-leche's is. -/
mutual
/-- con-leche: ConLeche/Kernel/ExprOps.lean:78-88 Expr.bvarBound
con-leche: ConLeche/Kernel/ExprOps.lean:153-177 bvarBoundGo
The memoized exact loose-bvar bound. con-leche's `bvarBound` is the pure
specification and `bvarBoundGo` the memoized walk; the arena has one
function. The memo is probed for every node, leaves included, as con-leche
probes it. The dispatcher (arms split per DESIGN §8.6's ruling of
2026-09-22); the probe and the insert bracket the arm call, so the arms are
the inner `match` alone. -/
def bvarBoundGo (fuel : Nat) (h : EIdx) : AM Nat :=
match fuel with
| 0 => fail (.internal "fuel exhausted: bvarBound")
| fuel + 1 => do
match ← bvarBGet h with
| some r => pure r
| none => do
let r ← (do
match ← view h with
| .bvar i => pure (i + 1)
| .fvar _ _ | .sort _ | .const _ _ | .lit _ => pure 0
| .app f a => bvarBoundArmApp fuel f a
| .lam ty body | .forallE ty body => bvarBoundArmBind fuel ty body
| .letE ty val body => bvarBoundArmLet fuel ty val body
| .proj _ _ sub => bvarBoundGo fuel sub)
bvarBSet h r
pure r
termination_by (fuel, 0)
/-- con-leche: ConLeche/Kernel/ExprOps.lean:153-177 bvarBoundGo — the `app`
arm. -/
def bvarBoundArmApp (fuel : Nat) (f a : EIdx) : AM Nat := do
let x ← bvarBoundGo fuel f
let y ← bvarBoundGo fuel a
pure (max x y)
termination_by (fuel, 1)
/-- con-leche: ConLeche/Kernel/ExprOps.lean:153-177 bvarBoundGo — the
binder arm: the body's bound loses the binder it crossed. -/
def bvarBoundArmBind (fuel : Nat) (ty body : EIdx) : AM Nat := do
let x ← bvarBoundGo fuel ty
let y ← bvarBoundGo fuel body
pure (max x (y - 1))
termination_by (fuel, 1)
/-- con-leche: ConLeche/Kernel/ExprOps.lean:153-177 bvarBoundGo — the
`letE` arm. -/
def bvarBoundArmLet (fuel : Nat) (ty val body : EIdx) : AM Nat := do
let x ← bvarBoundGo fuel ty
let y ← bvarBoundGo fuel val
let z ← bvarBoundGo fuel body
pure (max (max x y) (z - 1))
termination_by (fuel, 1)
end
/-- con-leche: none — `bvarBoundGo`'s clause at fuel `0` (template rule 9). -/
theorem bvarBoundGo_zero (h : EIdx) :
bvarBoundGo 0 h = fail (.internal "fuel exhausted: bvarBound") := by
rw [bvarBoundGo]
/-- con-leche: none — `bvarBoundGo`'s clause at `fuel + 1` (template rule
9). -/
theorem bvarBoundGo_succ (fuel : Nat) (h : EIdx) :
bvarBoundGo (fuel + 1) h = (do
match ← bvarBGet h with
| some r => pure r
| none => do
let r ← (do
match ← view h with
| .bvar i => pure (i + 1)
| .fvar _ _ | .sort _ | .const _ _ | .lit _ => pure 0
| .app f a => bvarBoundArmApp fuel f a
| .lam ty body | .forallE ty body => bvarBoundArmBind fuel ty body
| .letE ty val body => bvarBoundArmLet fuel ty val body
| .proj _ _ sub => bvarBoundGo fuel sub)
bvarBSet h r
pure r) := by
rw [bvarBoundGo]
/-- con-leche: ConLeche/Kernel/ExprOps.lean:179-180 bvarBoundMemo — the
top-level entry of the memoized walk. -/
def bvarBoundMemo (fuel : Nat) (e : EIdx) : AM Nat := do
bvarBClear
let r ← bvarBoundGo fuel e
bvarBClear
pure r
mutual
/-- con-leche: ConLeche/Kernel/ExprOps.lean:97-108 Expr.fvarRange
con-leche: ConLeche/Kernel/ExprOps.lean:182-207 fvarRangeGo
The memoized exact fvar range (`fvar` annotations are not descended into,
matching the abstraction traversals). The dispatcher (arms split per DESIGN
§8.6's ruling of 2026-09-22). -/
def fvarRangeGo (fuel : Nat) (h : EIdx) : AM Nat :=
match fuel with
| 0 => fail (.internal "fuel exhausted: fvarRange")
| fuel + 1 => do
match ← fvarBGet h with
| some r => pure r
| none => do
let r ← (do
match ← view h with
| .fvar idx _ => pure (idx + 1)
| .bvar _ | .sort _ | .const _ _ | .lit _ => pure 0
| .app f a => fvarRangeArmApp fuel f a
| .lam ty body | .forallE ty body => fvarRangeArmBind fuel ty body
| .letE ty val body => fvarRangeArmLet fuel ty val body
| .proj _ _ sub => fvarRangeGo fuel sub)
fvarBSet h r
pure r
termination_by (fuel, 0)
/-- con-leche: ConLeche/Kernel/ExprOps.lean:182-207 fvarRangeGo — the `app`
arm. -/
def fvarRangeArmApp (fuel : Nat) (f a : EIdx) : AM Nat := do
let x ← fvarRangeGo fuel f
let y ← fvarRangeGo fuel a
pure (max x y)
termination_by (fuel, 1)
/-- con-leche: ConLeche/Kernel/ExprOps.lean:182-207 fvarRangeGo — the
binder arm; unlike `bvarBound` the cursor does not move. -/
def fvarRangeArmBind (fuel : Nat) (ty body : EIdx) : AM Nat := do
let x ← fvarRangeGo fuel ty
let y ← fvarRangeGo fuel body
pure (max x y)
termination_by (fuel, 1)
/-- con-leche: ConLeche/Kernel/ExprOps.lean:182-207 fvarRangeGo — the
`letE` arm. -/
def fvarRangeArmLet (fuel : Nat) (ty val body : EIdx) : AM Nat := do
let x ← fvarRangeGo fuel ty
let y ← fvarRangeGo fuel val
let z ← fvarRangeGo fuel body
pure (max (max x y) z)
termination_by (fuel, 1)
end
/-- con-leche: none — `fvarRangeGo`'s clause at fuel `0` (template rule 9). -/
theorem fvarRangeGo_zero (h : EIdx) :
fvarRangeGo 0 h = fail (.internal "fuel exhausted: fvarRange") := by
rw [fvarRangeGo]
/-- con-leche: none — `fvarRangeGo`'s clause at `fuel + 1` (template rule
9). -/
theorem fvarRangeGo_succ (fuel : Nat) (h : EIdx) :
fvarRangeGo (fuel + 1) h = (do
match ← fvarBGet h with
| some r => pure r
| none => do
let r ← (do
match ← view h with
| .fvar idx _ => pure (idx + 1)
| .bvar _ | .sort _ | .const _ _ | .lit _ => pure 0
| .app f a => fvarRangeArmApp fuel f a
| .lam ty body | .forallE ty body => fvarRangeArmBind fuel ty body
| .letE ty val body => fvarRangeArmLet fuel ty val body
| .proj _ _ sub => fvarRangeGo fuel sub)
fvarBSet h r
pure r) := by
rw [fvarRangeGo]
/-- con-leche: ConLeche/Kernel/ExprOps.lean:209-210 fvarRangeMemo — the
top-level entry of the memoized walk. -/
def fvarRangeMemo (fuel : Nat) (e : EIdx) : AM Nat := do
fvarBClear
let r ← fvarRangeGo fuel e
fvarBClear
pure r
/-- con-leche: ConLeche/Kernel/ExprOps.lean:212-217 bvarB — **the
loose-bvar bound the checker reads**: the packed field, or — on the saturated
branch alone — the exact memoized recomputation. `==` on `Nat`, so the `==`
inventory's line 1432 is not a handle comparison. -/
def bvarB (fuel : Nat) (e : EIdx) : AM Nat := do
let der ← derivedE e
let r := (bvarOfData der).toNat
if r == satRange then bvarBoundMemo fuel e else pure r
/-- con-leche: ConLeche/Kernel/ExprOps.lean:219-224 fvarB — **the fvar range
the checker reads**: the packed field, or the exact memoized recomputation on
the saturated branch. -/
def fvarB (fuel : Nat) (e : EIdx) : AM Nat := do
let der ← derivedE e
let r := (fvarOfData der).toNat
if r == satRange then fvarRangeMemo fuel e else pure r
/-- con-leche: ConLeche/Kernel/ExprOps.lean:493-494 hasFvarFast — the
executed `hasFvar`: the fvar-range field read. -/
def hasFvarFast (fuel : Nat) (e : EIdx) : AM Bool := do
let r ← fvarB fuel e
pure (r != 0)
/-- con-leche: ConLeche/Kernel/ExprOps.lean:502-503 looseBVarsBoundedFast —
the executed `looseBVarsBounded`: the loose-bvar field read. -/
def looseBVarsBoundedFast (fuel k : Nat) (e : EIdx) : AM Bool := do
let r ← bvarB fuel e
pure (decide (r ≤ k))
/-! ## `abstract1` — `ExprOps.lean:760-776`, `:1789-1833`, `:1927-1929`
The fvar-range cutoff comes first: a node whose whole subtree mentions no
`fvar` at or above `d` is its own abstraction. -/
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:826-856 abstract1XP — the
`fvar` arm. It does not recurse, so it sits outside the `mutual` block. -/
def abstract1ArmFVar (d : Nat) (h : EIdx) (k : Nat) : AM EIdx := do
match ← viewFVarIdx h with
| none => failDanglingE
| some idx => if idx = d then internBVarE k else pure h
mutual
/-- con-leche: ConLeche/Kernel/ExprOps.lean:736-752 abstract1
con-leche: ConLeche/Cached/ExprOpsC.lean:826-856 abstract1XP
Close a binder body: replace `fvar d …` leaves by `bvar k`, bumping `k` under
binders. `fvar` annotations are not descended into. The dispatcher (arms
split per DESIGN §8.6's ruling of 2026-09-22). -/
def abstract1Go (d : Nat) (fuel : Nat) (h : EIdx) (k : Nat) : AM EIdx :=
match fuel with
| 0 => fail (.internal "fuel exhausted: abstract1")
| fuel + 1 => do
let fb ← fvarB fuel h
if fb ≤ d then
pure h
else
let tg := h.tag
if tg == ETag.app then abstract1ArmApp d fuel h k
else if ETag.isBind tg then abstract1ArmBind d fuel h k
else if tg == ETag.fvar then abstract1ArmFVar d h k
else if tg == ETag.letE then abstract1ArmLet d fuel h k
else if tg == ETag.proj then abstract1ArmProj d fuel h k
else pure h
termination_by (fuel, 0)
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:826-856 abstract1XP — the `app`
arm. -/
def abstract1ArmApp (d : Nat) (fuel : Nat) (h : EIdx) (k : Nat) : AM EIdx := do
match ← abs1Get (h, k) with
| some r => pure r
| none =>
match ← viewApp h with
| none => failDanglingE
| some (f, a) => do
let f' ← abstract1Go d fuel f k
let a' ← abstract1Go d fuel a k
let r ← internRebuiltApp h (f' == f && a' == a) f' a'
abs1Set (h, k) r
pure r
termination_by (fuel, 1)
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:826-856 abstract1XP — the
binder arm; the body descends at `k + 1`. -/
def abstract1ArmBind (d : Nat) (fuel : Nat) (h : EIdx) (k : Nat) :
AM EIdx := do
match ← abs1Get (h, k) with
| some r => pure r
| none =>
match ← viewBind h with
| none => failDanglingE
| some (ty, body) => do
let t ← abstract1Go d fuel ty k
let b ← abstract1Go d fuel body (k + 1)
let r ← internRebuiltBind h (t == ty && b == body) h.tag t b
abs1Set (h, k) r
pure r
termination_by (fuel, 1)
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:826-856 abstract1XP — the
`letE` arm. -/
def abstract1ArmLet (d : Nat) (fuel : Nat) (h : EIdx) (k : Nat) : AM EIdx := do
match ← abs1Get (h, k) with
| some r => pure r
| none =>
match ← viewLet h with
| none => failDanglingE
| some (ty, val, body) => do
let t ← abstract1Go d fuel ty k
let w ← abstract1Go d fuel val k
let b ← abstract1Go d fuel body (k + 1)
let r ← internRebuiltLetE h (t == ty && w == val && b == body) t w b
abs1Set (h, k) r
pure r
termination_by (fuel, 1)
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:826-856 abstract1XP — the
`proj` arm. -/
def abstract1ArmProj (d : Nat) (fuel : Nat) (h : EIdx) (k : Nat) :
AM EIdx := do
match ← abs1Get (h, k) with
| some r => pure r
| none =>
match ← viewProj h with
| none => failDanglingE
| some (n, i, sub) => do
let u ← abstract1Go d fuel sub k
let r ← internRebuiltProj h (u == sub) n i u
abs1Set (h, k) r
pure r
termination_by (fuel, 1)
end
/-- con-leche: none — `abstract1Go`'s clause at fuel `0` (template rule 9). -/
theorem abstract1Go_zero (d : Nat) (h : EIdx) (k : Nat) :
abstract1Go d 0 h k = fail (.internal "fuel exhausted: abstract1") := by
rw [abstract1Go]
/-- con-leche: none — `abstract1Go`'s clause at `fuel + 1` (template rule
9). -/
theorem abstract1Go_succ (d : Nat) (fuel : Nat) (h : EIdx) (k : Nat) :
abstract1Go d (fuel + 1) h k = (do
let fb ← fvarB fuel h
if fb ≤ d then
pure h
else
let tg := h.tag
if tg == ETag.app then abstract1ArmApp d fuel h k
else if ETag.isBind tg then abstract1ArmBind d fuel h k
else if tg == ETag.fvar then abstract1ArmFVar d h k
else if tg == ETag.letE then abstract1ArmLet d fuel h k
else if tg == ETag.proj then abstract1ArmProj d fuel h k
else pure h) := by
rw [abstract1Go]
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:858-861 abstract1C — the
top-level entry. -/
def abstract1Fast (fuel : Nat) (e : EIdx) (d : Nat) (k : Nat := 0) : AM EIdx := do
abs1Clear
let r ← abstract1Go d fuel e k
abs1Clear
pure r
/-! ## `abstractRange`, the EXECUTED form — `Cached/ExprOpsC.lean:684-755`
`abstractRange` above (in "The measures and the scope predicates") is
con-leche's `Kernel/ExprOps.lean:791` SPEC: a bare structural descent. The
cached tier's `abstractRangeC` is the one the checker runs, and it is the same
three devices `abstract1Go` already has — the `fvarB ≤ d` cutoff at the node
(`abstractRangeP`'s first line, `enterAbsRP`), the per-call memo keyed by
`(node, cursor)` (`abstractRangeXP`'s `MemoXP`), and the `k = 0` identity that
skips the traversal outright (`abstractRangeC`'s own first clause).
Task #97-P6-11 is what needed it: the annotation's binder-telescope loop calls
`abstractRange` once per binder domain and once at the leaf, so the bare
descent became the hottest walk of the run.
The memo table is `abstract1`'s (`abs1C`). The two walks never nest — both are
leaf walks over the store, calling nothing but `fvarB`, `view` and `intern` —
and each entry point clears the table before and after itself, so within one
call the key `(h, c)` determines the result at the call's own fixed `d` and
`k`. That is a table IDENTITY, not a clause. -/
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:894-925 abstractRangeXP — the
`fvar` arm, which does not recurse and so sits outside the `mutual` block. -/
def absRangeArmFVar (d k : Nat) (h : EIdx) (c : Nat) : AM EIdx := do
match ← viewFVarIdx h with
| none => failDanglingE
| some idx =>
if d ≤ idx && idx < d + k then internBVarE (c + (d + k - 1 - idx))
else pure h
mutual
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:863-879 abstractRangeP
con-leche: ConLeche/Cached/ExprOpsC.lean:894-925 abstractRangeXP
The memoized `abstractRange` walk: close the `k` free variables
`d … d + k - 1` into `bvar`s at cursor `c`, innermost binder to the lowest
index. The dispatcher (arms split per DESIGN §8.6's ruling of
2026-09-22). -/
def abstractRangeGo (d k : Nat) (fuel : Nat) (h : EIdx) (c : Nat) : AM EIdx :=
match fuel with
| 0 => fail (.internal "fuel exhausted: abstractRange")
| fuel + 1 => do
let fb ← fvarB fuel h
if fb ≤ d then
pure h
else
let tg := h.tag
if tg == ETag.app then absRangeGoArmApp d k fuel h c
else if ETag.isBind tg then absRangeGoArmBind d k fuel h c
else if tg == ETag.fvar then absRangeArmFVar d k h c
else if tg == ETag.letE then absRangeGoArmLet d k fuel h c
else if tg == ETag.proj then absRangeGoArmProj d k fuel h c
else pure h
termination_by (fuel, 0)
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:894-925 abstractRangeXP — the
`app` arm. -/
def absRangeGoArmApp (d k : Nat) (fuel : Nat) (h : EIdx) (c : Nat) :
AM EIdx := do
match ← abs1Get (h, c) with
| some r => pure r
| none =>
match ← viewApp h with
| none => failDanglingE
| some (f, a) => do
let f' ← abstractRangeGo d k fuel f c
let a' ← abstractRangeGo d k fuel a c
let r ← internRebuiltApp h (f' == f && a' == a) f' a'
abs1Set (h, c) r
pure r
termination_by (fuel, 1)
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:894-925 abstractRangeXP — the
binder arm; the body descends at `c + 1`. -/
def absRangeGoArmBind (d k : Nat) (fuel : Nat) (h : EIdx) (c : Nat) :
AM EIdx := do
match ← abs1Get (h, c) with
| some r => pure r
| none =>
match ← viewBind h with
| none => failDanglingE
| some (ty, body) => do
let t ← abstractRangeGo d k fuel ty c
let b ← abstractRangeGo d k fuel body (c + 1)
let r ← internRebuiltBind h (t == ty && b == body) h.tag t b
abs1Set (h, c) r
pure r
termination_by (fuel, 1)
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:894-925 abstractRangeXP — the
`letE` arm. -/
def absRangeGoArmLet (d k : Nat) (fuel : Nat) (h : EIdx) (c : Nat) :
AM EIdx := do
match ← abs1Get (h, c) with
| some r => pure r
| none =>
match ← viewLet h with
| none => failDanglingE
| some (ty, val, body) => do
let t ← abstractRangeGo d k fuel ty c
let w ← abstractRangeGo d k fuel val c
let b ← abstractRangeGo d k fuel body (c + 1)
let r ← internRebuiltLetE h (t == ty && w == val && b == body) t w b
abs1Set (h, c) r
pure r
termination_by (fuel, 1)
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:894-925 abstractRangeXP — the
`proj` arm. -/
def absRangeGoArmProj (d k : Nat) (fuel : Nat) (h : EIdx) (c : Nat) :
AM EIdx := do
match ← abs1Get (h, c) with
| some r => pure r
| none =>
match ← viewProj h with
| none => failDanglingE
| some (n, i, sub) => do
let u ← abstractRangeGo d k fuel sub c
let r ← internRebuiltProj h (u == sub) n i u
abs1Set (h, c) r
pure r
termination_by (fuel, 1)
end
/-- con-leche: none — `abstractRangeGo`'s clause at fuel `0` (template rule
9). -/
theorem abstractRangeGo_zero (d k : Nat) (h : EIdx) (c : Nat) :
abstractRangeGo d k 0 h c =
fail (.internal "fuel exhausted: abstractRange") := by
rw [abstractRangeGo]
/-- con-leche: none — `abstractRangeGo`'s clause at `fuel + 1` (template rule
9). -/
theorem abstractRangeGo_succ (d k : Nat) (fuel : Nat) (h : EIdx) (c : Nat) :
abstractRangeGo d k (fuel + 1) h c = (do
let fb ← fvarB fuel h
if fb ≤ d then
pure h
else
let tg := h.tag
if tg == ETag.app then absRangeGoArmApp d k fuel h c
else if ETag.isBind tg then absRangeGoArmBind d k fuel h c
else if tg == ETag.fvar then absRangeArmFVar d k h c
else if tg == ETag.letE then absRangeGoArmLet d k fuel h c
else if tg == ETag.proj then absRangeGoArmProj d k fuel h c
else pure h) := by
rw [abstractRangeGo]
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:927-934 abstractRangeC — the
top-level entry of the executed `abstractRange`: `k = 0` is the identity and
skips the traversal (con-leche's own clause, and what makes the annotation
telescope's OUTERMOST binder domain cost nothing), then the per-call memo is
cleared around the walk exactly as `abstract1Fast` clears it. -/
def abstractRangeFast (fuel : Nat) (e : EIdx) (d k c : Nat) : AM EIdx := do
if k = 0 then pure e
else do
abs1Clear
let r ← abstractRangeGo d k fuel e c
abs1Clear
pure r
/-! ## `instantiateLift` — `ExprOps.lean:921-952`, `Cached/ExprOpsC.lean:339-420`
The capture-avoiding substitution of several variables at once: the values'
own loose `bvar`s are lifted past the binders crossed on the way. It is the
module's one NESTED walk — its `bvar` arm runs `liftLooseBVars`, which is why
the two have separate memo tables. `vs` is in PUSH order, as
`instantiateList`'s. -/
mutual
/-- con-leche: ConLeche/Kernel/ExprOps.lean:941-961 instantiateLift
con-leche: ConLeche/Cached/ExprOpsC.lean:383-414 instantiateLiftXP
Replace `bvar (d + j)` by value `j` lifted past the `d` binders crossed, and
lower the variables above the values by their count, with con-leche's own
`bvarB ≤ d` cutoff and the cached walk's `(handle, cursor)`-keyed memo. The dispatcher (arms
split per DESIGN §8.6's ruling of 2026-09-22); the `bvar` arm — the NESTED
one, which runs `liftLooseBVars` — has no memo probe and stays here. -/
def instantiateLiftGo (vs : Array EIdx) (fuel : Nat) (h : EIdx) (d : Nat) :
AM EIdx :=
match fuel with
| 0 => fail (.internal "fuel exhausted: instantiateLift")
| fuel + 1 => do
let bb ← bvarB fuel h
if bb ≤ d then
pure h
else
match ← view h with
| .bvar i =>
if i < d then pure h
else if hlt : i - d < vs.size then
-- **`vs` is in PUSH order**, as `instantiateList`'s: con-leche's
-- `vs[i - d]` is this array's entry `i - d` FROM THE END.
liftLooseBVarsFast fuel d 0 (vs[vs.size - 1 - (i - d)]'(by omega))
else internE (.bvar (i - vs.size))
| .fvar _ _ => pure h
| .sort _ => pure h
| .const _ _ => pure h
| .lit _ => pure h
| .app f a => instLiftArmApp vs fuel h d f a
| .lam ty body => instLiftArmLam vs fuel h d ty body
| .forallE ty body => instLiftArmForallE vs fuel h d ty body
| .letE ty val body => instLiftArmLet vs fuel h d ty val body
| .proj n i sub => instLiftArmProj vs fuel h d n i sub
termination_by (fuel, 0)
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:383-414 instantiateLiftXP —
the `app` arm. -/
def instLiftArmApp (vs : Array EIdx) (fuel : Nat) (h : EIdx) (d : Nat) (f a : EIdx) :
AM EIdx := do
match ← inst1LGet (h, d) with
| some r => pure r
| none => do
let f' ← instantiateLiftGo vs fuel f d
let a' ← instantiateLiftGo vs fuel a d
let r ← internE (.app f' a')
inst1LSet (h, d) r
pure r
termination_by (fuel, 1)
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:383-414 instantiateLiftXP —
the `lam` arm. -/
def instLiftArmLam (vs : Array EIdx) (fuel : Nat) (h : EIdx) (d : Nat)
(ty body : EIdx) : AM EIdx := do
match ← inst1LGet (h, d) with
| some r => pure r
| none => do
let t ← instantiateLiftGo vs fuel ty d
let b ← instantiateLiftGo vs fuel body (d + 1)
let r ← internLamE t b
inst1LSet (h, d) r
pure r
termination_by (fuel, 1)
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:383-414 instantiateLiftXP —
the `forallE` arm. -/
def instLiftArmForallE (vs : Array EIdx) (fuel : Nat) (h : EIdx) (d : Nat)
(ty body : EIdx) : AM EIdx := do
match ← inst1LGet (h, d) with
| some r => pure r
| none => do
let t ← instantiateLiftGo vs fuel ty d
let b ← instantiateLiftGo vs fuel body (d + 1)
let r ← internForallEE t b
inst1LSet (h, d) r
pure r
termination_by (fuel, 1)
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:383-414 instantiateLiftXP —
the `letE` arm. -/
def instLiftArmLet (vs : Array EIdx) (fuel : Nat) (h : EIdx) (d : Nat)
(ty val body : EIdx) : AM EIdx := do
match ← inst1LGet (h, d) with
| some r => pure r
| none => do
let t ← instantiateLiftGo vs fuel ty d
let w ← instantiateLiftGo vs fuel val d
let b ← instantiateLiftGo vs fuel body (d + 1)
let r ← internE (.letE t w b)
inst1LSet (h, d) r
pure r
termination_by (fuel, 1)
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:383-414 instantiateLiftXP —
the `proj` arm. -/
def instLiftArmProj (vs : Array EIdx) (fuel : Nat) (h : EIdx) (d : Nat) (n : NIdx)
(i : Nat) (sub : EIdx) : AM EIdx := do
match ← inst1LGet (h, d) with
| some r => pure r
| none => do
let u ← instantiateLiftGo vs fuel sub d
let r ← internE (.proj n i u)
inst1LSet (h, d) r
pure r
termination_by (fuel, 1)
end
/-- con-leche: none — `instantiateLiftGo`'s clause at fuel `0` (template
rule 9). -/
theorem instantiateLiftGo_zero (vs : Array EIdx) (h : EIdx) (d : Nat) :
instantiateLiftGo vs 0 h d =
fail (.internal "fuel exhausted: instantiateLift") := by
rw [instantiateLiftGo]
/-- con-leche: none — `instantiateLiftGo`'s clause at `fuel + 1` (template
rule 9). -/
theorem instantiateLiftGo_succ (vs : Array EIdx) (fuel : Nat) (h : EIdx) (d : Nat) :
instantiateLiftGo vs (fuel + 1) h d = (do
let bb ← bvarB fuel h
if bb ≤ d then
pure h
else
match ← view h with
| .bvar i =>
if i < d then pure h
else if hlt : i - d < vs.size then
liftLooseBVarsFast fuel d 0 (vs[vs.size - 1 - (i - d)]'(by omega))
else internE (.bvar (i - vs.size))
| .fvar _ _ => pure h
| .sort _ => pure h
| .const _ _ => pure h
| .lit _ => pure h
| .app f a => instLiftArmApp vs fuel h d f a
| .lam ty body => instLiftArmLam vs fuel h d ty body
| .forallE ty body => instLiftArmForallE vs fuel h d ty body
| .letE ty val body => instLiftArmLet vs fuel h d ty val body
| .proj n i sub => instLiftArmProj vs fuel h d n i sub) := by
rw [instantiateLiftGo]
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:416-420 instantiateLiftC —
the top-level entry: the memo cleared around the walk. -/
def instantiateLiftFast (fuel : Nat) (e : EIdx) (vs : Array EIdx) (d : Nat := 0) :
AM EIdx := do
inst1LClear
let r ← instantiateLiftGo vs fuel e d
inst1LClear
pure r
/-! ## `instantiateLevelParams` — `ExprOps.lean:2564-2603`, `:2718-2720`
**The one twin that touches a level algorithm** (DESIGN §8.3 lesson 4). The
substitution's names and levels are read back ONCE, at the entry, and the
walk then runs con-leche's own `Level.subst` on transient
trees and re-interns the result. The twin's `ks`/`us` are therefore
`List Name` and `List Level`, not `List NIdx` and `LsIdx` as the census's
mechanical column has them — that column's rule stops where lesson 4
starts. -/
/-- con-leche: ConLeche/Kernel/Level.lean:31-42 subst — `vs.map (Level.subst
ks us)` as explicit recursion. con-leche writes the `.map`; a closure is
what DESIGN §3.4 forbids in code Aeneas must translate, and §3.4's own rule
for a `List` recursion is a helper, so the twin has one. -/
def substLevelList (ks : List ConLeche.Name) (us : List Level) :
List Level → List Level
| [] => []
| u :: rest => Level.subst ks us u :: substLevelList ks us rest
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:1135-1171 instLevelParamsXP — the
LEVEL-handle substitution behind a per-call memo (task #97-P6-13).
`instLPGo`'s `.sort` arm reads a level back, runs `Level.subst` and re-interns
once per OCCURRENCE; keyed on the level handle alone, the whole of that is one
probe. The key omits `ks`/`us` for the reason DESIGN §8.3 gives for
`instantiate`/`abstract`/`instantiateLevelParams`: the table is cleared at
every top-level call (`instLPClear`), so within one call the two vectors are
constants. -/
def substLMemoAt (ks : List ConLeche.Name) (us : List Level) (u : LIdx) : AM LIdx := do
match ← instLPLGet u with
| some r => pure r
| none => do
let l ← readLevelM u
let hl ← internLevel (Level.subst ks us l)
instLPLSet u hl
pure hl
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:1135-1171 instLevelParamsXP — the same
at a universe-argument LIST handle, for the `.const` arm. -/
def substLsMemoAt (ks : List ConLeche.Name) (us : List Level) (vs : LsIdx) :
AM LsIdx := do
match ← instLPLsGet vs with
| some r => pure r
| none => do
let ls ← readLevelsM vs
let vs' ← internLevels (substLevelList ks us ls)
instLPLsSet vs vs'
pure vs'
mutual
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:1135-1171 instLevelParamsXP —
substitute level parameters throughout an expression, with con-leche's own
`hasLP = false` cutoff (the whole subtree is level-parameter free, so the
substitution is the identity on it). `.sort` and `.const` read their levels
back, run `Level.subst` on the transient trees and re-intern; nothing else in
this module touches a level. The dispatcher (arms split per DESIGN §8.6's
ruling of 2026-09-22); the two LEVEL arms have no memo probe of their own and
stay here, beside the two leaves. -/
def instLPGo (ks : List ConLeche.Name) (us : List Level) (fuel : Nat)
(h : EIdx) : AM EIdx :=
match fuel with
| 0 => fail (.internal "fuel exhausted: instantiateLevelParams")
| fuel + 1 => do
let der ← derivedE h
if !(lpOfData der) then
pure h
else
match ← view h with
| .bvar _ => pure h
| .lit _ => pure h
| .sort u => do
let hl ← substLMemoAt ks us u
internRebuiltSort h (hl == u) hl
| .const n vs => do
let vs' ← substLsMemoAt ks us vs
internRebuiltConst h (vs' == vs) n vs'
| .fvar i ty => instLPArmFVar ks us fuel h i ty
| .app f a => instLPArmApp ks us fuel h f a
| .lam ty body => instLPArmLam ks us fuel h ty body
| .forallE ty body => instLPArmForallE ks us fuel h ty body
| .letE ty val body => instLPArmLet ks us fuel h ty val body
| .proj n i sub => instLPArmProj ks us fuel h n i sub
termination_by (fuel, 0)
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:1135-1171 instLevelParamsXP — the
`fvar` arm. -/
def instLPArmFVar (ks : List ConLeche.Name) (us : List Level) (fuel : Nat)
(h : EIdx) (i : Nat) (ty : EIdx) : AM EIdx := do
match ← instLPGet (h, 0) with
| some r => pure r
| none => do
let t ← instLPGo ks us fuel ty
let r ← internRebuiltFVar h (t == ty) i t
instLPSet (h, 0) r
pure r
termination_by (fuel, 1)
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:1135-1171 instLevelParamsXP — the
`app` arm. -/
def instLPArmApp (ks : List ConLeche.Name) (us : List Level) (fuel : Nat)
(h : EIdx) (f a : EIdx) : AM EIdx := do
match ← instLPGet (h, 0) with
| some r => pure r
| none => do
let f' ← instLPGo ks us fuel f
let a' ← instLPGo ks us fuel a
let r ← internRebuiltApp h (f' == f && a' == a) f' a'
instLPSet (h, 0) r
pure r
termination_by (fuel, 1)
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:1135-1171 instLevelParamsXP — the
`lam` arm. -/
def instLPArmLam (ks : List ConLeche.Name) (us : List Level) (fuel : Nat)
(h : EIdx) (ty body : EIdx) : AM EIdx := do
match ← instLPGet (h, 0) with
| some r => pure r
| none => do
let t ← instLPGo ks us fuel ty
let b ← instLPGo ks us fuel body
let r ← internRebuiltLam h (t == ty && b == body) t b
instLPSet (h, 0) r
pure r
termination_by (fuel, 1)
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:1135-1171 instLevelParamsXP — the
`forallE` arm. -/
def instLPArmForallE (ks : List ConLeche.Name) (us : List Level) (fuel : Nat)
(h : EIdx) (ty body : EIdx) : AM EIdx := do
match ← instLPGet (h, 0) with
| some r => pure r
| none => do
let t ← instLPGo ks us fuel ty
let b ← instLPGo ks us fuel body
let r ← internRebuiltForallE h (t == ty && b == body) t b
instLPSet (h, 0) r
pure r
termination_by (fuel, 1)
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:1135-1171 instLevelParamsXP — the
`letE` arm. -/
def instLPArmLet (ks : List ConLeche.Name) (us : List Level) (fuel : Nat)
(h : EIdx) (ty val body : EIdx) : AM EIdx := do
match ← instLPGet (h, 0) with
| some r => pure r
| none => do
let t ← instLPGo ks us fuel ty
let w ← instLPGo ks us fuel val
let b ← instLPGo ks us fuel body
let r ← internRebuiltLetE h (t == ty && w == val && b == body) t w b
instLPSet (h, 0) r
pure r
termination_by (fuel, 1)
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:1135-1171 instLevelParamsXP — the
`proj` arm. -/
def instLPArmProj (ks : List ConLeche.Name) (us : List Level) (fuel : Nat)
(h : EIdx) (n : NIdx) (i : Nat) (sub : EIdx) : AM EIdx := do
match ← instLPGet (h, 0) with
| some r => pure r
| none => do
let u' ← instLPGo ks us fuel sub
let r ← internRebuiltProj h (u' == sub) n i u'
instLPSet (h, 0) r
pure r
termination_by (fuel, 1)
end
/-- con-leche: none — `instLPGo`'s clause at fuel `0` (template rule 9). -/
theorem instLPGo_zero (ks : List ConLeche.Name) (us : List Level) (h : EIdx) :
instLPGo ks us 0 h =
fail (.internal "fuel exhausted: instantiateLevelParams") := by
rw [instLPGo]
/-- con-leche: none — `instLPGo`'s clause at `fuel + 1` (template rule 9). -/
theorem instLPGo_succ (ks : List ConLeche.Name) (us : List Level) (fuel : Nat)
(h : EIdx) :
instLPGo ks us (fuel + 1) h = (do
let der ← derivedE h
if !(lpOfData der) then
pure h
else
match ← view h with
| .bvar _ => pure h
| .lit _ => pure h
| .sort u => do
let hl ← substLMemoAt ks us u
internRebuiltSort h (hl == u) hl
| .const n vs => do
let vs' ← substLsMemoAt ks us vs
internRebuiltConst h (vs' == vs) n vs'
| .fvar i ty => instLPArmFVar ks us fuel h i ty
| .app f a => instLPArmApp ks us fuel h f a
| .lam ty body => instLPArmLam ks us fuel h ty body
| .forallE ty body => instLPArmForallE ks us fuel h ty body
| .letE ty val body => instLPArmLet ks us fuel h ty val body
| .proj n i sub => instLPArmProj ks us fuel h n i sub) := by
rw [instLPGo]
/-- con-leche: ConLeche/Cached/ExprOpsC.lean:1173-1177 instLevelParams — the
top-level entry: read the substitution back out of the store once, walk, drop
the memo. -/
def instLPFast (fuel : Nat) (ks : List NIdx) (us : LsIdx) (e : EIdx) : AM EIdx := do
-- **The cutoff hoisted over the readback** (task #97-P6-10), the shape task
-- #97-P6-9's item 5 has at `instantiateList`'s `.bvar` clause. `instLPGo`'s
-- own first act is `hasLP e = false → e`, and the walk is the only consumer
-- of `ksP`/`usP`; so on a level-parameter-free term both readbacks are
-- computed and dropped. Deciding the cutoff FIRST is the same value by the
-- walk's own equation, in `O(1)` off the derived word.
if !(lpOfData (← derivedE e)) then pure e
else do
let ksP ← readNamesM ks
let usP ← readLevelsM us
instLPClear
let r ← instLPGo ksP usP fuel e
instLPClear
pure r
end ConRon.Arena