Skip to main content

logicaffeine_kernel/
type_checker.rs

1//! Bidirectional type checker for the Calculus of Constructions.
2//!
3//! The type checker implements the typing rules of CoC:
4//!
5//! ```text
6//! ─────────────────────── (Sort)
7//!   Γ ⊢ Type n : Type (n+1)
8//!
9//!   Γ(x) = A
10//! ─────────────── (Var)
11//!   Γ ⊢ x : A
12//!
13//!   Γ ⊢ A : Type i    Γ, x:A ⊢ B : Type j
14//! ─────────────────────────────────────────── (Pi)
15//!          Γ ⊢ Π(x:A). B : Type max(i,j)
16//!
17//!   Γ ⊢ A : Type i    Γ, x:A ⊢ t : B
18//! ─────────────────────────────────────── (Lambda)
19//!      Γ ⊢ λ(x:A). t : Π(x:A). B
20//!
21//!   Γ ⊢ f : Π(x:A). B    Γ ⊢ a : A
22//! ───────────────────────────────────── (App)
23//!         Γ ⊢ f a : B[x := a]
24//! ```
25
26use crate::context::Context;
27use crate::error::{KernelError, KernelResult};
28use crate::reduction::normalize;
29use crate::term::{Literal, Term, Universe};
30
31// =================================================================================================
32// The depth door
33// =================================================================================================
34
35/// The deepest term the kernel will descend.
36///
37/// A `Term` arrives from a translator, a file, or a network peer — it is UNTRUSTED INPUT, and
38/// its nesting depth is chosen by whoever wrote it. `infer_type`, `reduce_step` and the
39/// conversion checker all walk it with native recursion, so a deep enough term exhausts the
40/// thread's stack and the process dies with `SIGABRT`: a denial of service with no error
41/// channel, indistinguishable from a crash in the code that called the kernel. A checker whose
42/// answer to a bad input is "the process is gone" cannot be part of a trusted base.
43///
44/// So the kernel REFUSES at the door what it cannot safely walk, and says so. The limit comes
45/// from MEASUREMENT, not taste, and it is squeezed from both sides:
46///
47/// - It must be ABOVE everything the kernel is asked to do today. The deepest term the suite
48///   builds is a 1500-deep β-spine (`lean_conformance_t00_terms`'s scaling measurement), which
49///   normalises fine because its redex is at the head, so every step is shallow. A door below
50///   that would refuse working code, and a guard that fails silently in the middle of a proof
51///   is worse than the abort it replaced.
52/// - It must be BELOW the depth at which `Term`'s DERIVED `Clone`/`Drop` abort. A single
53///   clone-and-drop survives 2000 and aborts by 4000; a term that is cloned a few times over
54///   (which checking one does) aborts by 2200. Those run before and after any kernel code, so a
55///   term the kernel accepts must at least be one it can copy, repeatedly.
56///
57/// 1600 is the band between the two. The RESIDUE is real and is NOT closed: how deep the kernel
58/// can actually descend depends on the SHAPE of a term, not only its depth — an irreducible
59/// 400-deep spine aborts inside `reduce_step` (no head redex, so it is searched to the bottom)
60/// while a 1500-deep β-spine does not. Closing that needs a larger kernel stack at the call
61/// site, or an iterative `Drop`/`Clone` for `Term` plus an explicit-stack reducer — `term.rs`
62/// and a reducer rewrite, not a constant.
63pub(crate) const MAX_TERM_DEPTH: usize = 1600;
64
65thread_local! {
66    /// Whether a kernel entry point is already on this thread's stack. The door check runs
67    /// once per outermost call, never on the recursive ones, so it costs one linear pass per
68    /// kernel invocation rather than one per node.
69    static INSIDE_KERNEL: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
70}
71
72/// Holds the "inside the kernel" flag for the outermost entry, clearing it on the way out —
73/// including on a panic, so the flag can never be left stale.
74pub(crate) struct DoorGuard(bool);
75
76impl Drop for DoorGuard {
77    fn drop(&mut self) {
78        if self.0 {
79            INSIDE_KERNEL.with(|f| f.set(false));
80        }
81    }
82}
83
84/// `t`'s nesting depth exceeds `limit`.
85///
86/// Measured with an EXPLICIT stack and an early exit, so asking the question about a
87/// pathologically deep term cannot itself overflow — a recursive `depth()` helper would abort
88/// on exactly the inputs this exists to catch.
89pub(crate) fn depth_exceeds(t: &Term, limit: usize) -> bool {
90    let mut work: Vec<(&Term, usize)> = vec![(t, 0)];
91    while let Some((node, d)) = work.pop() {
92        if d > limit {
93            return true;
94        }
95        let deeper = d + 1;
96        match node {
97            Term::Sort(_)
98            | Term::Var(_)
99            | Term::Global(_)
100            | Term::Const { .. }
101            | Term::Lit(_)
102            | Term::Hole => {}
103            Term::App(f, a) => {
104                work.push((f, deeper));
105                work.push((a, deeper));
106            }
107            Term::Pi {
108                param_type,
109                body_type,
110                ..
111            } => {
112                work.push((param_type, deeper));
113                work.push((body_type, deeper));
114            }
115            Term::Lambda {
116                param_type, body, ..
117            } => {
118                work.push((param_type, deeper));
119                work.push((body, deeper));
120            }
121            Term::Let {
122                ty, value, body, ..
123            } => {
124                work.push((ty, deeper));
125                work.push((value, deeper));
126                work.push((body, deeper));
127            }
128            Term::Match {
129                discriminant,
130                motive,
131                cases,
132            } => {
133                work.push((discriminant, deeper));
134                work.push((motive, deeper));
135                for c in cases {
136                    work.push((c, deeper));
137                }
138            }
139            Term::Fix { body, .. } => work.push((body, deeper)),
140            Term::MutualFix { defs, .. } => {
141                for (_, b) in defs {
142                    work.push((b, deeper));
143                }
144            }
145            Term::Annotated { term, .. } => work.push((term, deeper)),
146        }
147    }
148    false
149}
150
151/// Check `term` against the depth door if this is the OUTERMOST kernel call on this thread.
152/// Returns the guard that restores the flag.
153pub(crate) fn enter_kernel(term: &Term, what: &str) -> KernelResult<DoorGuard> {
154    if INSIDE_KERNEL.with(|f| f.get()) {
155        return Ok(DoorGuard(false));
156    }
157    if depth_exceeds(term, MAX_TERM_DEPTH) {
158        crate::reduction::record_resource_stop(crate::reduction::Unreduced::TooDeep);
159        return Err(KernelError::CertificationError(format!(
160            "term nests deeper than the kernel's limit of {MAX_TERM_DEPTH} while running              {what}: this is a REFUSAL, not a verdict — the term is neither accepted nor              rejected, because descending it would exhaust the native stack"
161        )));
162    }
163    INSIDE_KERNEL.with(|f| f.set(true));
164    Ok(DoorGuard(true))
165}
166
167/// The same door for the entry points that cannot report an error. `None` means "refused".
168pub(crate) fn enter_kernel_or_refuse(term: &Term) -> Option<DoorGuard> {
169    enter_kernel(term, "reduction").ok()
170}
171
172/// Whether a kernel entry point is already on this thread's stack.
173///
174/// Read-only: it never opens or closes the door. It exists so an entry point can skip the
175/// stack-SIZING measurement when the answer cannot matter — once a kernel call is under way the
176/// native stack it is going to get has already been chosen, and measuring a subterm to ask for a
177/// bigger one would only pay for a walk whose answer is ignored.
178pub(crate) fn inside_kernel() -> bool {
179    INSIDE_KERNEL.with(|f| f.get())
180}
181
182// App needs only a Pi head; Match needs only a registered inductive spine.
183// A successful positive probe preserves the remaining arguments and annotations.
184// Every inconclusive probe retains the original full-normalization fallback.
185#[derive(Clone, Copy)]
186pub(crate) enum TypeHead {
187    Function,
188    Inductive,
189}
190
191#[cfg(test)]
192thread_local! {
193    static TYPE_HEAD_FULL_NORMALIZATIONS: std::cell::Cell<[usize; 2]> =
194        const { std::cell::Cell::new([0; 2]) };
195}
196
197pub(crate) fn demanded_type_head(ctx: &Context, ty: Term, requested: TypeHead) -> Term {
198    probe_type_head(ctx, ty, requested).unwrap_or_else(|ty| {
199        #[cfg(test)]
200        TYPE_HEAD_FULL_NORMALIZATIONS.with(|count| {
201            let mut values = count.get();
202            values[match requested {
203                TypeHead::Function => 0,
204                TypeHead::Inductive => 1,
205            }] += 1;
206            count.set(values);
207        });
208        normalize(ctx, &ty)
209    })
210}
211
212/// `Ok` with a type whose head is the requested one — the type itself, or its bounded head
213/// reduction — and `Err` with the type handed back when only a full normalization could say.
214fn probe_type_head(ctx: &Context, ty: Term, requested: TypeHead) -> Result<Term, Term> {
215    // Preserve the existing syntactic Pi path, including custom-rule contexts.
216    if matches!(requested, TypeHead::Function) && matches!(ty, Term::Pi { .. }) {
217        return Ok(ty);
218    }
219    let has_requested_head = |candidate: &Term| match requested {
220        TypeHead::Function => matches!(candidate, Term::Pi { .. }),
221        TypeHead::Inductive => extract_inductive_name(ctx, candidate).is_some(),
222    };
223    // Registered rewrites may affect the exposed head. Their general reduction
224    // path is unchanged; the bounded probe also refuses such contexts.
225    if ctx.simp_rules().is_empty() {
226        if has_requested_head(&ty) {
227            return Ok(ty);
228        }
229        if let Some(exposed) = crate::reduction::bounded_conversion_head(ctx, &ty) {
230            if has_requested_head(&exposed) {
231                return Ok(exposed);
232            }
233        }
234    }
235    Err(ty)
236}
237
238/// The type of a projected value with its inductive family exposed at the head, as Lean's
239/// `infer_proj` reads it (`whnf (infer_type e)`): the type itself when its head already names an
240/// inductive family, else the same bounded head reduction the kernel's own `match` typing uses.
241/// `Err` hands the type back when that bounded probe does not reach an inductive head; the caller
242/// keeps its full-normalization fallback, so no type that normalizes to a family is refused here.
243pub(crate) fn exposed_inductive_type(ctx: &Context, ty: Term) -> Result<Term, Term> {
244    probe_type_head(ctx, ty, TypeHead::Inductive)
245}
246
247/// The type of an applied function with its `Π` exposed at the head, as Lean's `infer_app` reads
248/// it (`ensure_pi (whnf (infer f))`) and as this kernel's own application rule does: the type
249/// itself when it is a `Π`, else its bounded head reduction. `Err` hands the type back when that
250/// probe does not reach a `Π`; the caller keeps its full-normalization fallback.
251pub(crate) fn exposed_function_type(ctx: &Context, ty: Term) -> Result<Term, Term> {
252    probe_type_head(ctx, ty, TypeHead::Function)
253}
254
255// Peel only the exact canonical Nat constructor typing rule. Every skipped
256// application has domain Nat and codomain Nat; the residual tail still goes
257// through ordinary checking. This removes recursive typing work, not limits.
258fn infer_canonical_peano(ctx: &Context, term: &Term) -> Option<KernelResult<Term>> {
259    let Term::App(head, _) = term else {
260        return None;
261    };
262    if !matches!(head.as_ref(), Term::Global(name) if name == "Succ")
263        || !ctx.simp_rules().is_empty()
264        || !crate::int_inductive::canonical_nat_environment(ctx)
265    {
266        return None;
267    }
268    let mut tail = term;
269    let mut prefix = 0usize;
270    while let Term::App(head, argument) = tail {
271        if !matches!(head.as_ref(), Term::Global(name) if name == "Succ") {
272            break;
273        }
274        prefix += 1;
275        if prefix > MAX_TERM_DEPTH {
276            return Some(Err(KernelError::CertificationError(
277                "computed Peano term exceeds the kernel term-depth limit".into(),
278            )));
279        }
280        tail = argument;
281    }
282    // Computation may have built this prefix after the outer door ran. Preserve
283    // that same ceiling across the entire result, including a non-Peano tail.
284    if depth_exceeds(tail, MAX_TERM_DEPTH - prefix) {
285        return Some(Err(KernelError::CertificationError(
286            "computed Peano term exceeds the kernel term-depth limit".into(),
287        )));
288    }
289    let natural = Term::Global("Nat".into());
290    Some(check_type(ctx, tail, &natural).map(|()| natural))
291}
292
293#[cfg(test)]
294thread_local! {
295    static PEANO_INFERENCE_ENTRIES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
296}
297
298/// Infer the type of a term in a context.
299///
300/// This is the main entry point for type checking. It implements bidirectional
301/// type inference for the Calculus of Constructions.
302///
303/// # Type Rules
304///
305/// - `Type n : Type (n+1)` - Universes form a hierarchy
306/// - `x : A` if `x : A` in context - Variable lookup
307/// - `Π(x:A). B : Type max(i,j)` if `A : Type i` and `B : Type j`
308/// - `λ(x:A). t : Π(x:A). B` if `t : B` in extended context
309/// - `f a : B[x := a]` if `f : Π(x:A). B` and `a : A`
310///
311/// # Errors
312///
313/// Returns [`KernelError`] variants for:
314/// - Unbound variables
315/// - Type mismatches in applications
316/// - Invalid match constructs
317/// - Termination check failures for fixpoints
318pub fn infer_type(ctx: &Context, term: &Term) -> KernelResult<Term> {
319    if let Some(r) = crate::annotation::erased(term, |term| infer_type(ctx, term)) {
320        return r;
321    }
322    // THE DOOR MUST MEAN WHAT IT SAYS. `MAX_TERM_DEPTH` advertises 1600 rungs, and this walk
323    // dies at about 52 of a dependent telescope on the 2 MiB stack a spawned thread gets —
324    // not with a refusal but with a `SIGABRT`, which is the one answer a kernel may never give.
325    // `deepen_stack` sizes the stack from the term's OWN depth at the OUTERMOST entry: it runs
326    // `f` inline for a shallow term and on a sized thread of the kernel's own for a deep one,
327    // and always returns `None` on the re-entrant call inside the closure, which then falls
328    // through to the body below. So the measurement is paid exactly once per outermost call —
329    // the same budget `enter_kernel`'s own `depth_exceeds` pass already has — and it is skipped
330    // entirely once a kernel call is under way, where a bigger stack can no longer be arranged.
331    if !inside_kernel() {
332        if let Some(r) = crate::term_store::deepen_stack(term, || infer_type(ctx, term)) {
333            return r;
334        }
335    }
336    let _door = enter_kernel(term, "infer_type")?;
337    #[cfg(test)]
338    PEANO_INFERENCE_ENTRIES.with(|count| count.set(count.get() + 1));
339    if let Some(result) = infer_canonical_peano(ctx, term) {
340        return result;
341    }
342    match term {
343        // Sort: Type n : Type (n+1)
344        Term::Sort(u) => Ok(Term::Sort(u.succ())),
345
346        // Var: lookup in local context. A miss is not one event but two — an ordinary
347        // unbound local, and an elaborator metavariable that was never solved — and they
348        // need different repairs, so they get different diagnostics.
349        Term::Var(name) => ctx.get(name).cloned().ok_or_else(|| classify_unbound(name)),
350
351        // Global: lookup in global context (inductives, constructors, definitions, axioms).
352        // The stored type is returned VERBATIM, level variables and all: a bare reference is
353        // universe-polymorphic, and the levels are introduced as metavariables by the
354        // APPLICATION rule (`implicit_levels_for_head`), where there is an argument to solve
355        // them from. Introducing them here instead would rename the level variables of every
356        // reference — including the ones a polymorphic definition's own body is being checked
357        // against, where they are genuinely bound and must not be touched.
358        Term::Global(name) => match ctx.get_global(name) {
359            Some(ty) => Ok(ty.clone()),
360            None => Err(classify_unbound(name)),
361        },
362
363        // Const: a universe-polymorphic global at explicit levels. The telescope, the closure
364        // check and the positional zip are decided ONCE, in `term::resolve_const_levels`, which
365        // the re-checker and the reducer call with their own lookups — so a reference that
366        // typing refuses can never be a normal form to the reducer.
367        Term::Const { name, levels } => {
368            let (declared, ty) = lookup_const(ctx, name).ok_or_else(|| classify_unbound(name))?;
369            let subst = crate::term::resolve_const_levels(name, declared.as_deref(), &ty, levels)
370                .map_err(|e| KernelError::CertificationError(e.to_string()))?;
371            Ok(crate::term::instantiate_universes(&ty, &subst))
372        }
373
374        // Pi: Π(x:A). B : Type max(sort(A), sort(B))
375        Term::Pi {
376            param,
377            param_type,
378            body_type,
379        } => {
380            // A must be a type
381            let a_sort = infer_sort(ctx, param_type)?;
382
383            // B must be a type in the extended context
384            let (param, body_type) = open_context_binder(ctx, param, param_type, body_type);
385            let extended_ctx = ctx.extend(&param, (**param_type).clone());
386            let b_sort = infer_sort(&extended_ctx, &body_type)?;
387
388            // Product formation (CIC). `Prop` is **impredicative**: a Π whose
389            // codomain is a proposition is itself a proposition, no matter the
390            // domain's universe — so `∀x:Entity. P(x)` is a `Prop`, and FOL
391            // formulas built from it (And/Or/Ex over universals) stay in `Prop`
392            // where `And`/`Ex` require their arguments to live. `imax` is exactly
393            // this rule: `imax(a, Prop) = Prop`, `imax(a, non-Prop) = max(a, b)`,
394            // and it stays SYMBOLIC when the codomain level is a variable (whose
395            // Prop-ness is not yet known) — the case the old `_ => max` got wrong.
396            let pi_sort = a_sort.imax(&b_sort);
397            Ok(Term::Sort(pi_sort))
398        }
399
400        // Lambda: λ(x:A). t : Π(x:A). T where t : T
401        Term::Lambda {
402            param,
403            param_type,
404            body,
405        } => {
406            // Check param_type is well-formed (is a type)
407            let _ = infer_sort(ctx, param_type)?;
408
409            // Infer body type in extended context
410            let (param, body) = open_context_binder(ctx, param, param_type, body);
411            let extended_ctx = ctx.extend(&param, (**param_type).clone());
412            let body_type = infer_type(&extended_ctx, &body)?;
413
414            // Keep the same fresh lexical binder in the inferred telescope.
415            Ok(Term::Pi {
416                param: param.into_owned(),
417                param_type: param_type.clone(),
418                body_type: Box::new(body_type),
419            })
420        }
421
422        // Let: `let x : A := v in b`. Check `A` is a type and `v : A`, then type
423        // the body with `x` bound TRANSPARENTLY — by zeta-substituting `v` for
424        // `x` (so `b`'s type sees `x ≡ v`, not an opaque hypothesis). This is
425        // checked by the substitution lemma when possible, with transparent
426        // zeta-expansion retained for bodies that need the value for conversion.
427        Term::Let {
428            name,
429            ty,
430            value,
431            body,
432        } => {
433            let _ = infer_sort(ctx, ty)?;
434            check_type(ctx, value, ty)?;
435            // The substitution lemma lets us check the body with an opaque local
436            // and substitute only its inferred type. A body whose conversions need
437            // the value falls back to the full transparent rule below.
438            if !ctx.local_name_in_use(name) {
439                std::thread_local! { static LET_PROBE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; }
440                struct Probe(bool);
441                impl Drop for Probe {
442                    fn drop(&mut self) {
443                        LET_PROBE.with(|flag| flag.set(self.0));
444                    }
445                }
446                let probe = Probe(LET_PROBE.with(|flag| flag.replace(true)));
447                let nested = probe.0;
448                let result = infer_type(&ctx.extend(name, (**ty).clone()), body);
449                drop(probe);
450                match result {
451                    Ok(body_type) => return Ok(instantiate_codomain(name, ty, &body_type, value)),
452                    // Abort the whole speculative pass at the first dependent
453                    // failure; nested retries would otherwise grow exponentially.
454                    Err(error) if nested => return Err(error),
455                    Err(_) => {}
456                }
457            }
458            let unfolded = substitute(body, name, value);
459            infer_type(ctx, &unfolded)
460        }
461
462        // App: (f a) : B[x := a] where f : Π(x:A). B and a : A
463        Term::App(func, arg) => {
464            let func_type = infer_type(ctx, func)?;
465            // Expose the Pi head without normalizing its domain or codomain.
466            // Hidden/unsupported heads retain the full normalization fallback;
467            // all argument checking and universe solving below still run.
468            let func_type = demanded_type_head(ctx, func_type, TypeHead::Function);
469            // A bare reference to a universe-polymorphic declaration carries no levels, so they
470            // become fresh metavariables HERE — at the one place there is an argument to solve
471            // them from.
472            let func_type = implicit_levels_for_head(func, func_type);
473
474            match func_type {
475                Term::Pi {
476                    param,
477                    param_type,
478                    body_type,
479                } => {
480                    // LEVEL SOLVING. When the head is a bare reference to a
481                    // universe-polymorphic declaration, its domain carries level
482                    // metavariables; solve them by matching the domain against the
483                    // argument's ACTUAL type before checking anything. Choosing an
484                    // instantiation is not accepting one — `check_type` below still runs
485                    // against the substituted domain, so a bad choice refuses the
486                    // application rather than admitting it.
487                    // `None` means there was nothing to solve, and then the ORIGINALS are moved
488                    // through untouched — the ordinary application must not pay a deep clone of
489                    // its domain and codomain for a rule that did not fire.
490                    let (param_type, body_type) =
491                        match solve_domain_levels(ctx, &param_type, &body_type, arg) {
492                            Some(solved) => solved,
493                            None => (*param_type, *body_type),
494                        };
495
496                    // Check argument has expected type
497                    check_type(ctx, arg, &param_type)?;
498
499                    // Substitute argument into body type, SHARING it rather than copying it
500                    // when copying would blow the type up (see `substitute_shared`).
501                    Ok(expose_head(substitute_shared(
502                        &body_type,
503                        &param,
504                        &param_type,
505                        arg,
506                    )))
507                }
508                _ => Err(KernelError::NotAFunction(format!("{}", func))),
509            }
510        }
511
512        // Match: pattern matching on inductive types
513        Term::Match {
514            discriminant,
515            motive,
516            cases,
517        } => {
518            // 1. Expose only a registered inductive head where possible.
519            // Parameters and indices remain available for the exact conversion,
520            // coverage, motive, branch and elimination checks below.
521            let disc_type =
522                demanded_type_head(ctx, infer_type(ctx, discriminant)?, TypeHead::Inductive);
523            let inductive_name = extract_inductive_name(ctx, &disc_type)
524                .ok_or_else(|| KernelError::NotAnInductive(format!("{}", disc_type)))?;
525
526            // An empty `match` is `ex falso` and needs an UNINHABITED discriminant type. A
527            // zero-constructor inductive the kernel's own literal rule inhabits is not one.
528            if empty_match_would_be_a_lie(ctx, &inductive_name) {
529                return Err(KernelError::InvalidMotive(format!(
530                    "'{inductive_name}' is registered with no constructors, but the kernel's \
531                     literal rule produces values of it — so a `match` on one is not `ex falso`: \
532                     it would prove its motive from a value that demonstrably exists. Give \
533                     '{inductive_name}' its constructors"
534                )));
535            }
536
537            // Parameter/index split. `num_params` leading arguments of the inductive are
538            // uniform PARAMETERS fixed by the discriminant; any remaining arguments are
539            // INDICES that vary per constructor, over which the motive abstracts (`Eq`'s
540            // `P : Π(y:A). Eq A x y → Sort`). When there are no indices this is the
541            // ordinary eliminator, which takes the original path below byte-for-byte.
542            let disc_args = extract_type_args(&disc_type);
543            let num_params = ctx
544                .inductive_num_params(&inductive_name)
545                .min(disc_args.len());
546            if disc_args.len() > num_params {
547                return infer_indexed_match(
548                    ctx,
549                    discriminant,
550                    motive,
551                    cases,
552                    &disc_type,
553                    &inductive_name,
554                    num_params,
555                    &disc_args,
556                );
557            }
558
559            // 2. Check motive is well-formed
560            // The motive can be either:
561            // - A function λ_:I. T (proper motive)
562            // - A raw type T (constant motive, wrapped automatically)
563            let motive_type = infer_type(ctx, motive)?;
564            let effective_motive = match &motive_type {
565                Term::Pi {
566                    param,
567                    param_type,
568                    body_type,
569                } => {
570                    // A motive may spell the discriminant type through beta,
571                    // delta, eta, or other kernel conversion rules. Cumulative
572                    // subtyping is insufficient here: the domain is invariant.
573                    if !def_eq(ctx, param_type, &disc_type) {
574                        return Err(KernelError::InvalidMotive(format!(
575                            "motive parameter {} doesn't match discriminant type {}",
576                            param_type, disc_type
577                        )));
578                    }
579                    // This is the CODOMAIN OF THE MOTIVE'S TYPE. It must
580                    // itself reduce to Sort, not merely have a sort as its type:
581                    // Nat has a sort too, but a Nat-valued motive is not a family.
582                    let (param, body_type) = open_context_binder(ctx, param, param_type, body_type);
583                    let motive_context = ctx.extend(&param, (**param_type).clone());
584                    let codomain = crate::reduction::normalize_checked(&motive_context, &body_type)
585                        .map_err(|reason| {
586                            KernelError::CertificationError(format!(
587                                "motive codomain normalization unfinished: {reason:?}"
588                            ))
589                        })?;
590                    if !matches!(codomain, Term::Sort(_)) {
591                        return Err(KernelError::InvalidMotive(format!(
592                            "motive type codomain {} is not a sort",
593                            body_type
594                        )));
595                    }
596                    // Use motive as-is
597                    (**motive).clone()
598                }
599                Term::Sort(_) => {
600                    // Motive is a raw type - wrap in a constant function
601                    // λ_:disc_type. motive
602                    Term::Lambda {
603                        param: "_".to_string(),
604                        param_type: Box::new(disc_type.clone()),
605                        body: motive.clone(),
606                    }
607                }
608                _ => {
609                    return Err(KernelError::InvalidMotive(format!(
610                        "motive {} is not a function or type",
611                        motive
612                    )));
613                }
614            };
615
616            // 3. Check case count matches constructor count
617            let constructors = ctx.get_constructors(&inductive_name);
618            if cases.len() != constructors.len() {
619                return Err(KernelError::WrongNumberOfCases {
620                    expected: constructors.len(),
621                    found: cases.len(),
622                });
623            }
624
625            // 4. Check each case has the correct type
626            for (case, (ctor_name, _)) in cases.iter().zip(constructors.iter()) {
627                let (ctor_head, ctor_type) =
628                    constructor_at_discriminant(ctx, ctor_name, &disc_type)?;
629                let expected_case_type =
630                    compute_case_type(&effective_motive, &ctor_head, &ctor_type, &disc_type);
631                check_type(ctx, case, &expected_case_type)?;
632            }
633
634            // 5. Return type is Motive(discriminant), beta-reduced
635            // Without beta reduction, (λ_:T. R) x returns the un-reduced form
636            // which causes type mismatches in nested matches.
637            let return_type =
638                beta_reduce(&Term::App(Box::new(effective_motive), discriminant.clone()));
639
640            // 6. The elimination restrictions (`check_elimination`).
641            let disc_sort = sort_of_type(ctx, &disc_type)?;
642            check_elimination(ctx, &inductive_name, &disc_sort, || {
643                sort_of_type(ctx, &return_type)
644            })?;
645
646            Ok(return_type)
647        }
648
649        // Literal: infer type based on literal kind
650        Term::Lit(lit) => match lit {
651            Literal::Int(_) | Literal::BigInt(_) => Ok(Term::Global("Int".to_string())),
652            Literal::Nat(n) if *n < logicaffeine_base::BigInt::from_i64(0) => Err(
653                KernelError::CertificationError("a `Nat` literal must be non-negative".to_string()),
654            ),
655            Literal::Nat(_) => Ok(Term::Global("Nat".to_string())),
656            Literal::Float(_) => Ok(Term::Global("Float".to_string())),
657            Literal::Text(_) => Ok(Term::Global("Text".to_string())),
658            Literal::Duration(_) => Ok(Term::Global("Duration".to_string())),
659            Literal::Date(_) => Ok(Term::Global("Date".to_string())),
660            Literal::Moment(_) => Ok(Term::Global("Moment".to_string())),
661        },
662
663        // Hole: implicit argument, cannot infer type standalone
664        // Holes are handled specially in check_type
665        Term::Hole => Err(KernelError::CannotInferHole),
666
667        // Fix: fix f. body
668        // The type of (fix f. body) is the type of body when f is bound to that type.
669        // This is a fixpoint equation: T = type_of(body) where f : T.
670        //
671        // For typical fixpoints, body is a lambda: fix f. λx:A. e
672        // The type is Π(x:A). B where B is the type of e (with f : Π(x:A). B).
673        Term::Fix { name, body } => {
674            let (name, body) = open_context_binder(ctx, name, body, body);
675            // For fix f. body, we need to handle the recursive reference to f.
676            // We structurally infer the type from lambda structure.
677            //
678            // This works because:
679            // 1. The body is typically nested lambdas with explicit parameter types
680            // 2. The return type is determined by the innermost expression's motive
681            // 3. Recursive calls have the same type as the fixpoint itself
682
683            // Extract the structural type from nested lambdas and motive
684            let structural_type = infer_fix_type_structurally(ctx, &body)
685                .map_err(|e| name_the_unreadable_fixpoint(&name, e))?;
686            if occurs_free(&structural_type, &name) {
687                return Err(KernelError::CertificationError(format!(
688                    "the fixpoint `{name}`'s type mentions `{name}` itself"
689                )));
690            }
691
692            // *** THE GUARDIAN: TERMINATION CHECK ***
693            // Verify that recursive calls decrease structurally.
694            // Without this check, we could "prove" False by looping forever.
695            crate::termination::check_termination(ctx, &name, &body)?;
696
697            // Sanity check: verify the body is well-formed with f bound
698            let extended = ctx.extend(&name, structural_type.clone());
699            let _ = infer_type(&extended, &body)?;
700
701            Ok(structural_type)
702        }
703
704        // MutualFix: a block of mutually-recursive definitions; this occurrence denotes
705        // the `index`-th one. Each definition's type is inferred structurally (like the
706        // single Fix), all names are put in scope, and the MUTUAL Giménez guard verifies
707        // termination before the bodies are sanity-checked with every sibling bound.
708        Term::MutualFix { defs, index } => {
709            if defs.is_empty() || *index >= defs.len() {
710                return Err(KernelError::CertificationError(
711                    "mutual fixpoint with an empty block or out-of-range index".to_string(),
712                ));
713            }
714
715            let opened_defs = open_context_mutual(ctx, defs);
716            let defs = opened_defs.as_ref();
717            // Structural type of each definition (independent of the others' bodies).
718            let mut types = Vec::with_capacity(defs.len());
719            for (name, body) in defs {
720                let ty = infer_fix_type_structurally(ctx, body)
721                    .map_err(|e| name_the_unreadable_fixpoint(name, e))?;
722                if let Some((member, _)) = defs.iter().find(|(member, _)| occurs_free(&ty, member))
723                {
724                    return Err(KernelError::CertificationError(format!(
725                        "the mutual fixpoint `{name}`'s type mentions the block's `{member}`"
726                    )));
727                }
728                types.push(ty);
729            }
730
731            // *** THE GUARDIAN: MUTUAL TERMINATION CHECK ***
732            crate::termination::check_termination_mutual(ctx, defs)?;
733
734            // Sanity: every body is well-formed with ALL names bound to their structural
735            // types (a sibling call `rec_Odd n' o` sees `rec_Odd`'s type this way).
736            let mut extended = ctx.clone();
737            for ((name, _), ty) in defs.iter().zip(types.iter()) {
738                extended = extended.extend(name, ty.clone());
739            }
740            for (_, body) in defs {
741                let _ = infer_type(&extended, body)?;
742            }
743
744            Ok(types[*index].clone())
745        }
746
747        Term::Annotated { term, .. } => infer_type(ctx, term),
748    }
749}
750
751/// A structural-inference failure that is really "this fixpoint's own name is not in scope yet",
752/// renamed so it cannot be mistaken for a forward reference.
753///
754/// `infer_fix_type_structurally` runs in the ORIGINAL context — the fixpoint's own name is bound
755/// only afterwards, for the sanity check — so a `Fix` whose result type can be read off no route
756/// but one through the recursive call reports `UnboundVariable(<its own binder>)`. That is the
757/// exact variant `Context::declare` keys its FORWARD-REFERENCE deferral on, so such a definition
758/// used to be DEFERRED, and a deferral that can never resolve (the name is bound by the term
759/// itself, not by any later declaration) leaves the definition registered with a body nothing
760/// type-checked. Naming the situation refuses it loudly instead of admitting it silently.
761///
762/// Only the fixpoint's OWN binder is renamed. A genuine forward reference to another constant
763/// keeps `UnboundVariable` and keeps being deferred, which is the behaviour the prelude's
764/// registration order depends on.
765fn name_the_unreadable_fixpoint(name: &str, e: KernelError) -> KernelError {
766    match &e {
767        KernelError::UnboundVariable(v) if v == name => KernelError::CertificationError(format!(
768            "the fixpoint `{name}`'s result type cannot be read off its body: every route to it \
769             passes through the recursive call, whose type is the very thing being inferred. \
770             Give the recursion a `match` whose motive states the result type — that is the \
771             route this kernel reads a fixpoint's type by."
772        )),
773        _ => e,
774    }
775}
776
777/// Infer the type of a fixpoint body structurally.
778///
779/// For `λx:A. body`, returns `Π(x:A). <type of body>`.
780/// This recursively handles nested lambdas.
781///
782/// The key insight is that for well-formed fixpoints, the body structure
783/// determines the type: parameters have explicit types, and the return type
784/// can be inferred from the innermost expression.
785fn infer_fix_type_structurally(ctx: &Context, term: &Term) -> KernelResult<Term> {
786    match term {
787        Term::Lambda {
788            param,
789            param_type,
790            body,
791        } => {
792            // Check param_type is well-formed
793            let _ = infer_sort(ctx, param_type)?;
794
795            // Extend context and recurse into body
796            let (param, body) = open_context_binder(ctx, param, param_type, body);
797            let extended = ctx.extend(&param, (**param_type).clone());
798            let body_type = infer_fix_type_structurally(&extended, &body)?;
799
800            // Retain the name used during structural inference.
801            Ok(Term::Pi {
802                param: param.into_owned(),
803                param_type: param_type.clone(),
804                body_type: Box::new(body_type),
805            })
806        }
807        // For non-lambda bodies (the base case), we need to determine the return type.
808        // This is typically a Match whose motive determines it: the return type is the
809        // `motive` applied to the discriminant's INDEX arguments (for an indexed family) and
810        // then the discriminant itself, β-normalized. Computing the application — rather
811        // than just reading off the motive's body — is robust to the motive's binder names
812        // (which need not match the fixpoint's) and to indexed families. The discriminant is
813        // the fixpoint's structural binder, in scope, so its type is available without the
814        // not-yet-bound recursive name.
815        Term::Match {
816            discriminant,
817            motive,
818            ..
819        } => {
820            // A constant motive `return T` — one whose own type is a Sort — IS the result
821            // type and is not applied to the discriminant. Only a function motive `λx. P x`
822            // is applied to the discriminant's index arguments and then the discriminant
823            // itself. This mirrors the Term::Match inference rule, which wraps a Sort-typed
824            // motive as the constant `λ_:I. T` rather than applying it; without this guard a
825            // constant motive `Nat`/`List A` becomes the ill-formed `App(Nat, n)`.
826            if let Ok(mt) = infer_type(ctx, motive) {
827                if matches!(normalize(ctx, &mt), Term::Sort(_)) {
828                    return Ok(normalize(ctx, motive));
829                }
830            }
831            let mut applied = (**motive).clone();
832            if let Ok(dt) = infer_type(ctx, discriminant) {
833                let dt = normalize(ctx, &dt);
834                if let Some(ind) = extract_inductive_name(ctx, &dt) {
835                    let args = extract_type_args(&dt);
836                    let p = ctx.inductive_num_params(&ind).min(args.len());
837                    for idx in &args[p..] {
838                        applied = Term::App(Box::new(applied), Box::new(idx.clone()));
839                    }
840                }
841            }
842            applied = Term::App(Box::new(applied), discriminant.clone());
843            Ok(normalize(ctx, &applied))
844        }
845        // A convoy: a `match` applied to further arguments. Its type is the `match`'s, read as
846        // above, applied to those arguments.
847        Term::App(..) if matches!(spine_of(term).0, Term::Match { .. }) => {
848            let (head, args) = spine_of(term);
849            let mut ty = infer_fix_type_structurally(ctx, head)?;
850            for arg in args {
851                match demanded_type_head(ctx, ty, TypeHead::Function) {
852                    Term::Pi {
853                        param, body_type, ..
854                    } => ty = substitute(&body_type, &param, arg),
855                    other => return Err(KernelError::NotAFunction(format!("{other}"))),
856                }
857            }
858            Ok(normalize(ctx, &ty))
859        }
860        // For other expressions, try normal inference
861        _ => infer_type(ctx, term),
862    }
863}
864
865/// Check that a term has the expected type (with subtyping/cumulativity).
866///
867/// Implements bidirectional type checking: when checking a Lambda against a Pi,
868/// we can use the Pi's parameter type instead of the Lambda's (which may be a
869/// placeholder from match case parsing).
870pub(crate) fn check_type(ctx: &Context, term: &Term, expected: &Term) -> KernelResult<()> {
871    // SPEC B — a `Term::Hole` needs no arm here, in either position. A hole TERM falls through
872    // to `infer_type`, which reports `CannotInferHole`; a hole EXPECTED TYPE falls through to
873    // `alpha_eq`/`is_subtype`, which refuse it. The two exemptions that used to sit here —
874    // "a hole stands for a type, so accept it against any `Sort`" and "a hole expects
875    // anything, so accept any well-typed term" — were the only reason `Eq _ (3:Nat) (true:Bool)`
876    // type-checked: a heterogeneous equation this kernel deliberately cannot express.
877
878    // A fixpoint checked against a type: bound at that type, a terminating fixpoint's body must
879    // have it. It types a recursion whose result type no `match` motive states, at every position
880    // that has an expected type (a declared type, a function's domain, a `let`'s type, a case's
881    // type), each of which is a type wherever this is asked. A fixpoint this does not type falls to
882    // inference, which reads the type off the body.
883    if let Term::Fix { name, body } = term {
884        let (name, body) = open_context_binder(ctx, name, body, body);
885        if crate::termination::check_termination(ctx, &name, &body).is_ok() {
886            let scoped = ctx.extend(&name, expected.clone());
887            if matches!(infer_type(&scoped, &body), Ok(got) if is_subtype(&scoped, &got, expected))
888            {
889                return Ok(());
890            }
891        }
892    }
893
894    // Special case: Lambda with placeholder type checked against Pi
895    // This handles match cases where binder types come from the expected type
896    if let Term::Lambda {
897        param,
898        param_type,
899        body,
900    } = term
901    {
902        // Check if param_type is a placeholder ("_")
903        if let Term::Global(name) = param_type.as_ref() {
904            if name == "_" {
905                // Bidirectional mode: get param type from expected
906                if let Term::Pi {
907                    param_type: expected_param_type,
908                    body_type: expected_body_type,
909                    param: expected_param,
910                } = expected
911                {
912                    // Check body in extended context using expected param type
913                    let fresh = fresh_context_name(
914                        ctx,
915                        param,
916                        &[expected_param_type, expected_body_type, body],
917                    );
918                    let body = rename_var(body, param, &fresh);
919                    let extended_ctx = ctx.extend(&fresh, (**expected_param_type).clone());
920                    let body_expected =
921                        substitute(expected_body_type, expected_param, &Term::Var(fresh));
922                    return check_type(&extended_ctx, &body, &body_expected);
923                }
924            }
925        }
926    }
927
928    let inferred = infer_type(ctx, term)?;
929    if is_subtype(ctx, &inferred, expected) {
930        Ok(())
931    } else {
932        Err(KernelError::TypeMismatch {
933            expected: format!("{}", expected),
934            found: format!("{}", inferred),
935        })
936    }
937}
938
939/// Normalize an already inferred non-Sort type for sort recognition.
940fn normalized_inferred_sort(ctx: &Context, term: &Term, inferred: &Term) -> KernelResult<Universe> {
941    let normalized = crate::reduction::normalize_checked(ctx, inferred).map_err(|reason| {
942        KernelError::CertificationError(format!(
943            "sort inference did not finish normalization: {reason:?}"
944        ))
945    })?;
946    match normalized {
947        Term::Sort(universe) => Ok(universe),
948        _ => Err(KernelError::NotAType(format!("{}", term))),
949    }
950}
951
952/// Infer a type expression once, verify its inferred type is a Sort, and retain
953/// that original unnormalized inferred type for independent agreement checks.
954pub(crate) fn infer_type_as_type(ctx: &Context, term: &Term) -> KernelResult<Term> {
955    let inferred = infer_type(ctx, term)?;
956    if !matches!(&inferred, Term::Sort(_)) {
957        normalized_inferred_sort(ctx, term, &inferred)?;
958    }
959    Ok(inferred)
960}
961
962/// Infer the sort (universe) of a type.
963///
964/// A term is a type if its type is a Sort.
965pub(crate) fn infer_sort(ctx: &Context, term: &Term) -> KernelResult<Universe> {
966    let inferred = infer_type(ctx, term)?;
967    match inferred {
968        Term::Sort(universe) => Ok(universe),
969        other => normalized_inferred_sort(ctx, term, &other),
970    }
971}
972
973/// The RESULT sort of an inductive's arity — peel its leading `Π`s to the final `Sort`.
974fn result_sort_universe(t: &Term) -> Option<Universe> {
975    let mut cur = t;
976    while let Term::Pi { body_type, .. } = cur {
977        cur = body_type;
978    }
979    match cur {
980        Term::Sort(u) => Some(u.clone()),
981        _ => None,
982    }
983}
984
985/// Extract the result universe from an already exposed inductive arity.
986pub(crate) fn constructor_target_universe(
987    ind: &str,
988    normalized_arity: &Term,
989) -> KernelResult<Universe> {
990    result_sort_universe(normalized_arity).ok_or_else(|| {
991        KernelError::InvalidDeclaration(format!(
992            "inductive '{ind}' must have a telescope ending in Sort"
993        ))
994    })
995}
996
997/// Whether a family in `target` may store arguments of any sort: the impredicative sorts. Neither
998/// gives a stored argument back as data — an `SProp` eliminates into `SProp` alone, and a `Prop`
999/// into a relevant sort only as a subsingleton whose fields are all proofs — so a large argument
1000/// stored there opens no large elimination.
1001fn stores_any_sort(target: &Universe) -> bool {
1002    *target == Universe::SProp || target.equiv(&Universe::Prop)
1003}
1004
1005/// Shared by the checked, freshened signature walk and the standalone universe gate.
1006pub(crate) fn check_constructor_field_universe(
1007    ctx: &Context,
1008    ind: &str,
1009    ctor: &str,
1010    field: &Term,
1011    target: &Universe,
1012) -> KernelResult<()> {
1013    if stores_any_sort(target) {
1014        return Ok(());
1015    }
1016    let sort = infer_sort(ctx, field)?;
1017    if !sort.is_subtype_of(target) {
1018        return Err(KernelError::InvalidDeclaration(format!(
1019            "universe inconsistency: constructor '{ctor}' stores an argument in sort \
1020             {sort}, which exceeds the sort {target} of its inductive '{ind}'"
1021        )));
1022    }
1023    Ok(())
1024}
1025
1026/// Check the CIC UNIVERSE CONSTRAINT of an inductive constructor: every VALUE argument's
1027/// sort must be `≤` the inductive's result sort — so a `Type 0` inductive cannot store a
1028/// `Type 0`-typed field (which lives in `Type 1`), the universe inconsistency that opens
1029/// Girard/Hurkens paradoxes. A `Prop` or `SProp` inductive is exempt (both sorts are
1030/// impredicative and admit arguments of any sort), as in Rocq. The inductive (and any mutual
1031/// siblings a recursive field references) must already be registered in `ctx`.
1032pub fn check_constructor_universes(
1033    ctx: &Context,
1034    ind: &str,
1035    ctor: &str,
1036    ty: &Term,
1037) -> KernelResult<()> {
1038    let Some(ind_ty) = ctx.get_global(ind) else {
1039        return Ok(());
1040    };
1041    let normal = |term: &Term| {
1042        crate::reduction::normalize_checked(ctx, term).map_err(|error|
1043            KernelError::CertificationError(format!(
1044                "constructor '{ctor}' of '{ind}': universe telescope normalization unfinished: {error:?}"
1045            )))
1046    };
1047    let target = constructor_target_universe(ind, &normal(ind_ty)?)?;
1048    if stores_any_sort(&target) {
1049        return Ok(());
1050    }
1051    let mut cur = normal(ty)?;
1052    let num_params = ctx.inductive_num_params(ind);
1053    let mut ext = ctx.clone();
1054    let mut i = 0usize;
1055    while let Term::Pi {
1056        param,
1057        param_type,
1058        body_type,
1059    } = cur
1060    {
1061        if i >= num_params {
1062            check_constructor_field_universe(&ext, ind, ctor, &param_type, &target)?;
1063        }
1064        let mut fresh = format!("__constructor_universe_local_{i}");
1065        while ext.local_name_in_use(&fresh) {
1066            fresh.push('_');
1067        }
1068        cur = substitute(&body_type, &param, &Term::Var(fresh.clone()));
1069        ext = ext.extend(&fresh, *param_type);
1070        i += 1;
1071    }
1072    Ok(())
1073}
1074
1075/// Beta-reduce a term (single step, at the head).
1076///
1077/// (λx.body) arg → body[x := arg]
1078fn beta_reduce(term: &Term) -> Term {
1079    match term {
1080        Term::App(func, arg) => {
1081            match func.as_ref() {
1082                Term::Lambda { param, body, .. } => {
1083                    // Beta reduction: (λx.body) arg → body[x := arg]
1084                    substitute(body, param, arg)
1085                }
1086                _ => term.clone(),
1087            }
1088        }
1089        _ => term.clone(),
1090    }
1091}
1092
1093/// Instantiate both a constructor reference and its type at the scrutinee's levels.
1094fn constructor_at_discriminant(
1095    ctx: &Context,
1096    name: &str,
1097    disc_type: &Term,
1098) -> KernelResult<(Term, Term)> {
1099    let mut head = disc_type;
1100    while let Term::App(f, _) = head {
1101        head = f;
1102    }
1103    let constructor = match head {
1104        Term::Const { levels, .. } if ctx.poly_declaration(name).is_some() => Term::Const {
1105            name: name.to_string(),
1106            levels: levels.clone(),
1107        },
1108        _ => Term::Global(name.to_string()),
1109    };
1110    let ty = infer_type(ctx, &constructor)?;
1111    Ok((constructor, ty))
1112}
1113
1114/// An indexed motive must abstract over the family's GENERIC index telescope,
1115/// followed by a major premise at those same indices, and return a sort. Validate
1116/// its inferred type rather than beta-reducing applications: a constant motive
1117/// body can otherwise erase ill-typed arguments before anyone checks them.
1118fn validate_indexed_motive(
1119    ctx: &Context,
1120    motive: &Term,
1121    disc_type: &Term,
1122    num_params: usize,
1123    disc_args: &[Term],
1124) -> KernelResult<()> {
1125    fn head(ctx: &Context, ty: Term) -> KernelResult<Term> {
1126        if matches!(ty, Term::Pi { .. } | Term::Sort(_)) {
1127            return Ok(ty);
1128        }
1129        crate::reduction::normalize_checked(ctx, &ty).map_err(|reason| {
1130            KernelError::CertificationError(format!(
1131                "indexed motive telescope normalization unfinished: {reason:?}"
1132            ))
1133        })
1134    }
1135    let error = |message: &str| KernelError::InvalidMotive(message.to_string());
1136    let (family_head, _) = spine_of(disc_type);
1137    let mut family = family_head.clone();
1138    let mut arity = infer_type(ctx, family_head)?;
1139    for parameter in &disc_args[..num_params] {
1140        let Term::Pi {
1141            param, body_type, ..
1142        } = head(ctx, arity)?
1143        else {
1144            return Err(error(
1145                "inductive has fewer parameters than its discriminant",
1146            ));
1147        };
1148        arity = substitute(&body_type, &param, parameter);
1149        family = Term::App(Box::new(family), Box::new(parameter.clone()));
1150    }
1151    let mut motive_type = infer_type(ctx, motive)?;
1152    let mut inner = ctx.clone();
1153    let mut avoid = free_vars(motive);
1154    avoid.extend(free_vars(disc_type));
1155    for index in 0..disc_args.len() - num_params {
1156        let Term::Pi {
1157            param,
1158            param_type,
1159            body_type,
1160        } = head(&inner, arity)?
1161        else {
1162            return Err(error(
1163                "inductive index telescope is shorter than its discriminant",
1164            ));
1165        };
1166        let Term::Pi {
1167            param: actual_param,
1168            param_type: actual_domain,
1169            body_type: actual_body,
1170        } = head(&inner, motive_type)?
1171        else {
1172            return Err(error("indexed motive lacks an index binder"));
1173        };
1174        if !def_eq(&inner, &actual_domain, &param_type) {
1175            return Err(error(
1176                "indexed motive index domain differs from the inductive telescope",
1177            ));
1178        }
1179        let mut name = fresh_name(&format!("__motive_index{index}"), &avoid);
1180        while inner.local_name_in_use(&name) {
1181            name.push('_');
1182        }
1183        avoid.insert(name.clone());
1184        let variable = Term::Var(name.clone());
1185        arity = substitute(&body_type, &param, &variable);
1186        motive_type = substitute(&actual_body, &actual_param, &variable);
1187        family = Term::App(Box::new(family), Box::new(variable));
1188        inner = inner.extend(&name, *param_type);
1189    }
1190    if !matches!(head(&inner, arity)?, Term::Sort(_)) {
1191        return Err(error(
1192            "discriminant does not instantiate the full inductive index telescope",
1193        ));
1194    }
1195    let Term::Pi {
1196        param,
1197        param_type,
1198        body_type,
1199    } = head(&inner, motive_type)?
1200    else {
1201        return Err(error("indexed motive lacks its major-premise binder"));
1202    };
1203    if !def_eq(&inner, &param_type, &family) {
1204        return Err(error(
1205            "indexed motive major domain differs from the generic indexed family",
1206        ));
1207    }
1208    let mut major = fresh_name("__motive_major", &avoid);
1209    while inner.local_name_in_use(&major) {
1210        major.push('_');
1211    }
1212    let codomain = substitute(&body_type, &param, &Term::Var(major.clone()));
1213    inner = inner.extend(&major, family);
1214    if !matches!(head(&inner, codomain)?, Term::Sort(_)) {
1215        return Err(error(
1216            "indexed motive must return a sort after its major-premise binder",
1217        ));
1218    }
1219    Ok(())
1220}
1221
1222/// Type an indexed match after validating its generic index/major telescope.
1223/// Each branch specializes that checked motive to its constructor's indices;
1224/// the result specializes it to the discriminant. Validation must precede beta
1225/// reduction, which can erase malformed motive applications.
1226#[allow(clippy::too_many_arguments)]
1227fn infer_indexed_match(
1228    ctx: &Context,
1229    discriminant: &Term,
1230    motive: &Term,
1231    cases: &[Term],
1232    disc_type: &Term,
1233    inductive_name: &str,
1234    num_params: usize,
1235    disc_args: &[Term],
1236) -> KernelResult<Term> {
1237    // The discriminant's own parameter args (fixed) and index args (what the motive is
1238    // instantiated at for the *result* type).
1239    let disc_params = &disc_args[0..num_params];
1240    let disc_indices = &disc_args[num_params..];
1241
1242    // Validate the generic telescope before applications of the motive are
1243    // beta-reduced below. Checking only their reduced result can erase a
1244    // mismatched index or major-premise argument.
1245    validate_indexed_motive(ctx, motive, disc_type, num_params, disc_args)?;
1246
1247    // SPEC F — coverage is over the constructors the INDICES still allow, not over all of them.
1248    // A branch is owed only for a constructor that could have produced this scrutinee; one
1249    // whose declared result index provably clashes with the discriminant's is discharged here,
1250    // exactly as Lean discharges it by index unification. Supplying every constructor's branch
1251    // anyway stays legal, so nothing written against the old rule stops working.
1252    let constructors = ctx.get_constructors(inductive_name);
1253    let owed: Vec<(&str, &Term)> = if cases.len() == constructors.len() {
1254        constructors.iter().map(|(n, t)| (*n, *t)).collect()
1255    } else {
1256        let allowed = constructors_the_indices_allow(ctx, inductive_name, num_params, disc_args);
1257        if cases.len() != allowed.len() {
1258            return Err(KernelError::WrongNumberOfCases {
1259                expected: allowed.len(),
1260                found: cases.len(),
1261            });
1262        }
1263        allowed
1264            .iter()
1265            .map(|&i| (constructors[i].0, constructors[i].1))
1266            .collect()
1267    };
1268
1269    // Each case against its indexed constructor type.
1270    for (case, (ctor_name, _)) in cases.iter().zip(owed.iter()) {
1271        let (ctor_head, ctor_type) = constructor_at_discriminant(ctx, ctor_name, disc_type)?;
1272        let expected =
1273            compute_indexed_case_type(motive, &ctor_head, &ctor_type, num_params, disc_params);
1274        check_type(ctx, case, &expected)?;
1275    }
1276
1277    // Return type: `motive disc_index₁ … disc_indexₖ discriminant`, normalized.
1278    let mut ret = motive.clone();
1279    for idx in disc_indices {
1280        ret = Term::App(Box::new(ret), Box::new(idx.clone()));
1281    }
1282    ret = Term::App(Box::new(ret), Box::new(discriminant.clone()));
1283    let ret = normalize(ctx, &ret);
1284
1285    // The result must be a type — this is what certifies the motive is a well-formed
1286    // family into a sort (a non-family motive would not infer to a `Sort` here).
1287    match normalize(ctx, &infer_type(ctx, &ret)?) {
1288        Term::Sort(_) => {}
1289        other => {
1290            return Err(KernelError::InvalidMotive(format!(
1291                "indexed match on '{}' has non-type result {} — the motive is not a family into a sort",
1292                inductive_name, other
1293            )));
1294        }
1295    }
1296
1297    let disc_sort = sort_of_type(ctx, disc_type)?;
1298    check_elimination(ctx, inductive_name, &disc_sort, || sort_of_type(ctx, &ret))?;
1299
1300    Ok(ret)
1301}
1302
1303/// The universe a type lives in: the sort its type normalizes to.
1304fn sort_of_type(ctx: &Context, ty: &Term) -> KernelResult<Universe> {
1305    match normalize(ctx, &infer_type(ctx, ty)?) {
1306        Term::Sort(u) => Ok(u),
1307        other => Err(KernelError::InvalidMotive(format!(
1308            "{ty} is not a type: its type is {other}"
1309        ))),
1310    }
1311}
1312
1313/// The elimination restrictions of `match`, for a scrutinee whose family lives in `Sort disc` and
1314/// a result whose sort `ret` reads, read only for a family that may be a proposition; the plain and
1315/// the indexed `match` rules both ask here.
1316///
1317/// * An `SProp` family eliminates only into `SProp`, with no subsingleton exception: definitional
1318///   irrelevance identifies any two inhabitants of an `SProp` type, so a match out of one into a
1319///   relevant sort equates its branches (two constructors, a match into `Nat`, and `Zero` is
1320///   definitionally `Succ Zero`), and into `Prop` it equates `True` with `False`.
1321/// * A family that is a proposition eliminates into a larger sort only when it is a subsingleton:
1322///   no constructors (`ex falso`), or one whose non-parameter arguments are all proofs (`And`,
1323///   `Eq`). Otherwise a proof would pick a value, and proof irrelevance would equate the values it
1324///   picks. The rule must hold at EVERY instance of the family's universe levels: `Sort u` is
1325///   `Prop` at `u := 0`, so for a family whose level may be `Prop` the result's level must be at
1326///   most the family's (`SProp`, `Prop`, or `Sort u` again). Checked with `u` abstract, an
1327///   elimination of a two-constructor `Two.{u} : Sort u` into `Nat` would otherwise pass, and at
1328///   `u := 0` be the `0 = 1` of a large elimination of a proposition. Lean makes such a family's
1329///   recursor eliminate into `Prop` only; this keeps the elimination at the family's own level too.
1330fn check_elimination(
1331    ctx: &Context,
1332    inductive_name: &str,
1333    disc: &Universe,
1334    ret: impl FnOnce() -> KernelResult<Universe>,
1335) -> KernelResult<()> {
1336    if disc.is_never_prop() {
1337        return Ok(());
1338    }
1339    let ret = &ret()?;
1340    if matches!(disc, Universe::SProp) && !matches!(ret, Universe::SProp) {
1341        return Err(KernelError::InvalidMotive(format!(
1342            "elimination of the definitionally-irrelevant proposition '{inductive_name}' \
1343             into a relevant sort is not allowed: every inhabitant of an SProp is \
1344             definitionally equal, so a match on one would equate its branches"
1345        )));
1346    }
1347    let (large, instance) = if disc.equiv(&Universe::Prop) {
1348        (!ret.equiv(&Universe::Prop), "")
1349    } else {
1350        (
1351            !ret.is_subtype_of(disc),
1352            " (a proposition at some instance of its universe levels)",
1353        )
1354    };
1355    if large && !is_subsingleton_prop(ctx, inductive_name)? {
1356        return Err(KernelError::InvalidMotive(format!(
1357            "large elimination of proposition '{inductive_name}'{instance} into a larger sort is not \
1358             allowed: only subsingleton propositions (empty, or one constructor with propositional \
1359             arguments — e.g. False, And, eq) may be eliminated into Type"
1360        )));
1361    }
1362    Ok(())
1363}
1364
1365/// The expected type of one constructor's case in an INDEXED match: the constructor's
1366/// leading `num_params` parameters are instantiated by the discriminant's `disc_params`;
1367/// its remaining value arguments become the case's `Π` binders; and the codomain is the
1368/// `motive` applied to the constructor's RESULT indices (as they appear in its declared
1369/// return type) and then the constructor value itself.
1370fn compute_indexed_case_type(
1371    motive: &Term,
1372    ctor_head: &Term,
1373    ctor_type: &Term,
1374    num_params: usize,
1375    disc_params: &[Term],
1376) -> Term {
1377    // Consume binders while their scope is intact. Substituting independently
1378    // into stripped field types can rewrite variables introduced by an earlier
1379    // parameter substitution, even when each individual substitution is safe.
1380    let mut current = ctor_type.clone();
1381    for arg in disc_params.iter().take(num_params) {
1382        if let Term::Pi {
1383            param, body_type, ..
1384        } = current
1385        {
1386            current = substitute(&body_type, &param, arg);
1387        } else {
1388            break;
1389        }
1390    }
1391    let mut avoid = free_vars(motive);
1392    avoid.extend(free_vars(&current));
1393    for arg in disc_params {
1394        avoid.extend(free_vars(arg));
1395    }
1396    let mut fields = Vec::new();
1397    while let Term::Pi {
1398        param,
1399        param_type,
1400        body_type,
1401    } = current
1402    {
1403        let fresh = fresh_name(&format!("__arg{}", fields.len()), &avoid);
1404        avoid.insert(fresh.clone());
1405        current = substitute(&body_type, &param, &Term::Var(fresh.clone()));
1406        fields.push((fresh, *param_type));
1407    }
1408    let mut ctor_applied = ctor_head.clone();
1409    for arg in disc_params {
1410        ctor_applied = Term::App(Box::new(ctor_applied), Box::new(arg.clone()));
1411    }
1412    for (field, _) in &fields {
1413        ctor_applied = Term::App(Box::new(ctor_applied), Box::new(Term::Var(field.clone())));
1414    }
1415    let mut result = motive.clone();
1416    for index in extract_type_args(&current).into_iter().skip(num_params) {
1417        result = Term::App(Box::new(result), Box::new(index));
1418    }
1419    result = beta_reduce(&Term::App(Box::new(result), Box::new(ctor_applied)));
1420    for (param, domain) in fields.into_iter().rev() {
1421        result = Term::Pi {
1422            param,
1423            param_type: Box::new(beta_reduce(&domain)),
1424            body_type: Box::new(result),
1425        };
1426    }
1427    result
1428}
1429
1430/// Non-indexed cases use the same capture-avoiding telescope instantiation.
1431fn compute_case_type(motive: &Term, ctor_head: &Term, ctor_type: &Term, disc_type: &Term) -> Term {
1432    let parameters = extract_type_args(disc_type);
1433    compute_indexed_case_type(motive, ctor_head, ctor_type, parameters.len(), &parameters)
1434}
1435
1436/// Extract type arguments from a type application.
1437///
1438/// - `List A` → `[A]`
1439/// - `Either A B` → `[A, B]`
1440/// - `Nat` → `[]`
1441fn extract_type_args(ty: &Term) -> Vec<Term> {
1442    let mut args = Vec::new();
1443    let mut current = ty;
1444
1445    while let Term::App(func, arg) = current {
1446        args.push((**arg).clone());
1447        current = func;
1448    }
1449
1450    args.reverse();
1451    args
1452}
1453
1454/// Substitute a term for a variable: `body[var := replacement]`.
1455///
1456/// Performs capture-avoiding substitution. Variables bound by lambda,
1457/// pi, or fix that shadow `var` are not substituted into.
1458///
1459/// # Capture Avoidance
1460///
1461/// Given `substitute(λx. y, "y", x)`, the result is `λx. x` (not `λx. x`
1462/// with the inner x captured). This implementation relies on unique
1463/// variable names from parsing.
1464///
1465/// # Term Forms
1466///
1467/// - `Sort`, `Lit`, `Hole`, `Global` - Unchanged (no variables)
1468/// - `Var(name)` - Replaced if `name == var`, unchanged otherwise
1469/// - `Pi`, `Lambda`, `Fix` - Substitute in components, respecting shadowing
1470/// - `App`, `Match` - Substitute recursively in all subterms
1471pub fn substitute(body: &Term, var: &str, replacement: &Term) -> Term {
1472    // Fast path: if `var` does not occur free in `body`, the substitution is the
1473    // identity. Crucially this lets us skip `free_vars(replacement)` — and the
1474    // `replacement` is, in `App`/`Match` type inference, the WHOLE argument/discriminant
1475    // proof term. A propositional implication's codomain never mentions the bound proof
1476    // variable (non-dependent), so this is the common case and turns quadratic checking
1477    // (walk the giant argument at every application) into linear.
1478    if !occurs_free(body, var) {
1479        return body.clone();
1480    }
1481    // Compute the free variables of the replacement once; a binder in `body`
1482    // that captures any of them must be alpha-renamed before we descend.
1483    let replacement_fvs = free_vars(replacement);
1484    substitute_avoiding(body, var, replacement, &replacement_fvs)
1485}
1486
1487// =================================================================================================
1488// Universe-polymorphic references, level solving, and sharing (main kernel side)
1489// =================================================================================================
1490
1491/// The axioms Lean's kernel carries that LOGOS's trusted base deliberately does NOT.
1492///
1493/// A proof minted against a PATCHED prelude cites one of these and then fails re-check against
1494/// the rebuilt trusted context. Reported as an `UnboundVariable` that reads like a typo, and the
1495/// obvious repair — add the name to `StandardLibrary::register` — is the catastrophic one: the
1496/// trusted base grows while every certificate ever minted still claims the old one. So these
1497/// names get their OWN diagnosis, and every other missing name stays an unbound variable.
1498///
1499/// The list is deliberately CLOSED and small. Widening it to "any unknown global is an axiom"
1500/// is the wrong fix: an unknown name is overwhelmingly a typo or a missing import, and calling
1501/// that a trusted-base event trains the reader to ignore the message that matters.
1502const UNTRUSTED_AXIOMS: &[&str] = &[
1503    "Classical_choice",
1504    "propext",
1505    "Quot_sound",
1506    "sorryAx",
1507    "em",
1508    "choice",
1509];
1510
1511/// Diagnose a name that resolved nowhere. One `KernelError` variant used to cover three
1512/// completely different events; they need three different repairs, so they get three different
1513/// messages.
1514pub(crate) fn unbound_diagnosis(name: &str) -> Option<String> {
1515    if crate::elaborate::is_meta(name) {
1516        return Some(format!(
1517            "E_UNINSTANTIATED_METAVARIABLE: the metavariable '{name}' reached the kernel \
1518             without a solution. Elaboration must instantiate every metavariable before the \
1519             term is checked; a `?`-named variable is not a name the kernel can look up, and \
1520             guessing one is a soundness decision disguised as a convenience",
1521        ));
1522    }
1523    if UNTRUSTED_AXIOMS.contains(&name) {
1524        let admission = matches!(name, "sorryAx");
1525        return Some(format!(
1526            "{}: '{name}' is not in LOGOS's trusted base. {}",
1527            if admission {
1528                "E_INCOMPLETE_PROOF"
1529            } else {
1530                "E_UNTRUSTED_AXIOM"
1531            },
1532            if admission {
1533                "This proof is INCOMPLETE — it rests on an admission (`sorry`), which is an \
1534                 axiom that proves everything. Adding the axiom to the prelude would make the \
1535                 admission invisible to every certificate minted afterwards"
1536            } else {
1537                "Checking this term would enlarge the trusted base. Adding the axiom to \
1538                 `StandardLibrary::register` is the one repair that must not be made: the \
1539                 prelude version would still describe the axiom set the certificate was NOT \
1540                 checked against"
1541            },
1542        ));
1543    }
1544    None
1545}
1546
1547/// The error for a name that resolved nowhere (see [`unbound_diagnosis`]).
1548fn classify_unbound(name: &str) -> KernelError {
1549    match unbound_diagnosis(name) {
1550        Some(msg) => KernelError::CertificationError(msg),
1551        None => KernelError::UnboundVariable(name.to_string()),
1552    }
1553}
1554
1555/// Look up a name as a universe-polymorphic reference: its DECLARED parameter list (present
1556/// only where a declaration STATED one) and its stored type. `None` when the name resolves
1557/// nowhere.
1558///
1559/// The registries stay disjoint on purpose — `get_global` must not see a universe-polymorphic
1560/// definition, because one is δ-transparent and has no constructors — so the lookup is ordered
1561/// rather than merged. [`Context::poly_declaration`] is that order for the two registries that
1562/// carry a LEVEL TELESCOPE: a polymorphic TYPE declaration (a body-less inductive, structure or
1563/// class) outranks a polymorphic DEFINITION, exactly as a header outranks a body in
1564/// `get_global`.
1565///
1566/// ★ READING THE STATED TELESCOPE IS NOT BOOKKEEPING. Where no list is stored the telescope is
1567/// DERIVED from the free level variables of the stored type in first-occurrence order
1568/// (`term::level_telescope`), and the two orders coincide for every declaration whose arity
1569/// happens to mention its parameters in declaration order — which is almost all of them, and is
1570/// why reading only the derived order survived this long. `Swapped.{u,v} : Sort v → Sort u →
1571/// Sort (max u v)` derives `[v, u]`, so `Swapped.{0,3}` came out with its two binders EXCHANGED:
1572/// a well-typed term at a type its declaration does not have, with no diagnostic anywhere, and
1573/// with the second kernel deriving the same wrong order and reporting `Agreed`. Lean cannot
1574/// reach that state: `ConstantInfo.levelParams` is stored on every declaration and
1575/// `Level.instantiateParams` (`Lean/Level.lean:594`) zips THAT list positionally, never one
1576/// recovered from the type.
1577fn lookup_const(ctx: &Context, name: &str) -> Option<(Option<Vec<String>>, Term)> {
1578    if let Some((params, ty)) = ctx.poly_declaration(name) {
1579        return Some((Some(params.to_vec()), ty.clone()));
1580    }
1581    let ty = ctx.get_global(name)?;
1582    // A `Const` is the UNIVERSE-POLYMORPHIC reference form, and `name.{}` is not a second
1583    // spelling of `Global(name)`: a monomorphic declaration has no level telescope, so a
1584    // reference that carries one is a statement about a declaration that does not exist. Lean
1585    // conflates the two (`Expr.const n []` IS the constant); LOGOS keeps them apart on purpose,
1586    // and `lean_conformance_t00_terms::a_monomorphic_reference_resolves_as_a_global_and_a_const_at_no_levels_does_not`
1587    // is the lock. The telescope is what makes a declaration reachable here — which is exactly
1588    // what lets an AXIOM, an INDUCTIVE or a STRUCTURE be universe-polymorphic without entering
1589    // the definition-only `universe_polys` map.
1590    if !crate::term::mentions_level_var(ty) {
1591        return None;
1592    }
1593    Some((None, ty.clone()))
1594}
1595
1596/// Turn the level variables of an APPLICATION HEAD's type into fresh metavariables, so the
1597/// application rule can solve them from the argument.
1598///
1599/// Leaving them as ordinary variables is what pinned a `Sort u` declaration to one
1600/// instantiation: `Type 0 ⋠ u` (a variable may be `Prop`), so `Box Nat` was refused while
1601/// `Box True` was accepted — one declaration, one usable level. Defaulting them to `Type 0` is
1602/// the opposite error, and the worse one, because cumulativity then absorbs the difference
1603/// silently.
1604///
1605/// The rewrite fires ONLY for a head that is a bare `Term::Global`. That restriction is what
1606/// keeps it honest: a level variable anywhere else — in the body of the polymorphic definition
1607/// currently being checked, say — is genuinely BOUND by its own declaration and a use site has
1608/// no business solving it. A `Term::Const` head already carries explicit levels and is left
1609/// alone; a partially-applied head keeps whatever metavariables the earlier application left
1610/// unsolved, so a spine solves its levels left to right.
1611pub(crate) fn implicit_levels_for_head(func: &Term, func_type: Term) -> Term {
1612    let Term::Global(name) = func else {
1613        return func_type;
1614    };
1615    // The guard is allocation-free and short-circuiting: this question is asked at EVERY
1616    // application, and almost every declaration is monomorphic, so learning "no" must cost
1617    // nothing. Collecting the telescope only happens for the declarations that have one.
1618    if !crate::term::mentions_level_var(&func_type) {
1619        return func_type;
1620    }
1621    let params = crate::term::free_level_vars(&func_type);
1622    if params.is_empty() {
1623        return func_type;
1624    }
1625    let subst = crate::term::fresh_level_metas(name, &params);
1626    crate::term::instantiate_universes(&func_type, &subst)
1627}
1628
1629/// Solve the level metavariables of an application's DOMAIN from the argument's actual type,
1630/// and propagate the solution into the codomain.
1631///
1632/// This chooses an instantiation; it does not accept one. The caller still runs `check_type`
1633/// against the substituted domain, so an unsolvable or unhelpful choice makes the application
1634/// FAIL. A domain with no metavariables is returned untouched, so the ordinary path never pays
1635/// for this.
1636fn solve_domain_levels(
1637    ctx: &Context,
1638    param_type: &Term,
1639    body_type: &Term,
1640    arg: &Term,
1641) -> Option<(Term, Term)> {
1642    let subst = domain_level_solution(ctx, param_type, arg)?;
1643    Some((
1644        crate::term::instantiate_universes(param_type, &subst),
1645        crate::term::instantiate_universes(body_type, &subst),
1646    ))
1647}
1648
1649/// The levels `arg` solves for the metavariables of the domain `param_type` — the application
1650/// rule's one decision. [`solve_domain_levels`] applies it; `implicit_instance_levels` records it,
1651/// so conversion reads a bare spine's instance from exactly the rule that typed the spine. `None`
1652/// when the domain has no metavariables or nothing was solved.
1653fn domain_level_solution(
1654    ctx: &Context,
1655    param_type: &Term,
1656    arg: &Term,
1657) -> Option<std::collections::HashMap<String, Universe>> {
1658    if !crate::term::mentions_level_meta(param_type) {
1659        return None;
1660    }
1661    // The argument's type is only a HINT here; if it cannot be inferred (a `Hole`, a term that
1662    // is checkable but not inferrable) the metavariables stay unsolved and `check_type` reports
1663    // the real failure.
1664    let arg_type = infer_type(ctx, arg).ok()?;
1665    let arg_type = match arg_type {
1666        Term::Sort(_) => arg_type,
1667        other => normalize(ctx, &other),
1668    };
1669    let mut subst = std::collections::HashMap::new();
1670    crate::term::unify_levels(param_type, &arg_type, &mut subst);
1671    (!subst.is_empty()).then_some(subst)
1672}
1673
1674/// A term with no proper subterms — copying one is free, so sharing it would only add noise.
1675fn is_atomic(t: &Term) -> bool {
1676    matches!(
1677        t,
1678        Term::Var(_)
1679            | Term::Global(_)
1680            | Term::Sort(_)
1681            | Term::Lit(_)
1682            | Term::Const { .. }
1683            | Term::Hole
1684    )
1685}
1686
1687/// The smallest argument [`substitute_shared`] will consider sharing.
1688///
1689/// Below this, the two walks the sharing decision costs are more expensive than the copies they
1690/// would save, so the argument is simply copied — which keeps the overwhelmingly common
1691/// application byte-identical to eager substitution and costs it nothing to find out.
1692const SHARE_MIN_ARGUMENT_NODES: usize = 16;
1693
1694/// Whether `t` has more than `limit` nodes.
1695///
1696/// Recursive with an early exit and no allocation: the App rule asks this at every node, so a
1697/// `Vec` here would be a malloc per application. The recursion is bounded by the kernel's own
1698/// depth door, and it stops the moment the budget is spent — so a huge argument costs `limit`
1699/// nodes to reject, not its own size.
1700fn size_exceeds(t: &Term, limit: usize) -> bool {
1701    fn walk(t: &Term, left: &mut usize) -> bool {
1702        if *left == 0 {
1703            return true;
1704        }
1705        *left -= 1;
1706        match t {
1707            Term::Var(_) | Term::Global(_) | Term::Sort(_) | Term::Lit(_) | Term::Hole => false,
1708            Term::Const { .. } => false,
1709            Term::App(f, a) => walk(f, left) || walk(a, left),
1710            Term::Pi {
1711                param_type,
1712                body_type,
1713                ..
1714            } => walk(param_type, left) || walk(body_type, left),
1715            Term::Lambda {
1716                param_type, body, ..
1717            } => walk(param_type, left) || walk(body, left),
1718            Term::Fix { body, .. } => walk(body, left),
1719            Term::MutualFix { defs, .. } => defs.iter().any(|(_, b)| walk(b, left)),
1720            Term::Let {
1721                ty, value, body, ..
1722            } => walk(ty, left) || walk(value, left) || walk(body, left),
1723            Term::Match {
1724                discriminant,
1725                motive,
1726                cases,
1727            } => {
1728                walk(discriminant, left)
1729                    || walk(motive, left)
1730                    || cases.iter().any(|c| walk(c, left))
1731            }
1732            Term::Annotated { term, .. } => {
1733                *left += 1;
1734                walk(term, left)
1735            }
1736        }
1737    }
1738    let mut left = limit;
1739    walk(t, &mut left)
1740}
1741
1742/// The node count of a term — the cost model behind [`substitute_shared`]'s decision.
1743fn node_count(t: &Term) -> usize {
1744    match t {
1745        Term::Var(_) | Term::Global(_) | Term::Sort(_) | Term::Lit(_) | Term::Hole => 1,
1746        Term::Const { .. } => 1,
1747        Term::App(f, a) => 1 + node_count(f) + node_count(a),
1748        Term::Pi {
1749            param_type,
1750            body_type,
1751            ..
1752        } => 1 + node_count(param_type) + node_count(body_type),
1753        Term::Lambda {
1754            param_type, body, ..
1755        } => 1 + node_count(param_type) + node_count(body),
1756        Term::Fix { body, .. } => 1 + node_count(body),
1757        Term::MutualFix { defs, .. } => 1 + defs.iter().map(|(_, b)| node_count(b)).sum::<usize>(),
1758        Term::Let {
1759            ty, value, body, ..
1760        } => 1 + node_count(ty) + node_count(value) + node_count(body),
1761        Term::Match {
1762            discriminant,
1763            motive,
1764            cases,
1765        } => {
1766            1 + node_count(discriminant)
1767                + node_count(motive)
1768                + cases.iter().map(node_count).sum::<usize>()
1769        }
1770        Term::Annotated { term, .. } => node_count(term),
1771    }
1772}
1773
1774/// How many FREE occurrences of `var` a term has, plus the term's own node count — one walk,
1775/// because the sharing decision needs both.
1776fn body_stats(term: &Term, var: &str) -> (usize, usize) {
1777    match term {
1778        Term::Var(name) => (usize::from(name == var), 1),
1779        Term::Global(_) | Term::Sort(_) | Term::Lit(_) | Term::Hole | Term::Const { .. } => (0, 1),
1780        Term::App(f, a) => {
1781            let (o1, s1) = body_stats(f, var);
1782            let (o2, s2) = body_stats(a, var);
1783            (o1 + o2, 1 + s1 + s2)
1784        }
1785        Term::Pi {
1786            param,
1787            param_type,
1788            body_type,
1789        } => {
1790            let (o1, s1) = body_stats(param_type, var);
1791            let (o2, s2) = body_stats(body_type, var);
1792            (o1 + if param == var { 0 } else { o2 }, 1 + s1 + s2)
1793        }
1794        Term::Lambda {
1795            param,
1796            param_type,
1797            body,
1798        } => {
1799            let (o1, s1) = body_stats(param_type, var);
1800            let (o2, s2) = body_stats(body, var);
1801            (o1 + if param == var { 0 } else { o2 }, 1 + s1 + s2)
1802        }
1803        Term::Fix { name, body } => {
1804            let (o, s) = body_stats(body, var);
1805            (if name == var { 0 } else { o }, 1 + s)
1806        }
1807        Term::MutualFix { defs, .. } => {
1808            let shadowed = defs.iter().any(|(n, _)| n == var);
1809            let mut occ = 0;
1810            let mut size = 1;
1811            for (_, b) in defs {
1812                let (o, s) = body_stats(b, var);
1813                if !shadowed {
1814                    occ += o;
1815                }
1816                size += s;
1817            }
1818            (occ, size)
1819        }
1820        Term::Let {
1821            name,
1822            ty,
1823            value,
1824            body,
1825        } => {
1826            let (o1, s1) = body_stats(ty, var);
1827            let (o2, s2) = body_stats(value, var);
1828            let (o3, s3) = body_stats(body, var);
1829            (o1 + o2 + if name == var { 0 } else { o3 }, 1 + s1 + s2 + s3)
1830        }
1831        Term::Match {
1832            discriminant,
1833            motive,
1834            cases,
1835        } => {
1836            let (o1, s1) = body_stats(discriminant, var);
1837            let (o2, s2) = body_stats(motive, var);
1838            let mut occ = o1 + o2;
1839            let mut size = 1 + s1 + s2;
1840            for c in cases {
1841                let (o, s) = body_stats(c, var);
1842                occ += o;
1843                size += s;
1844            }
1845            (occ, size)
1846        }
1847        Term::Annotated { term, .. } => body_stats(term, var),
1848    }
1849}
1850
1851/// Substitute `replacement` for `var` in `body`, WRITING IT ONCE when copying it would blow the
1852/// result up.
1853///
1854/// `Term` is a named tree with no sharing, so the ordinary substitution materialises a full
1855/// clone of the argument at every occurrence. In a DEPENDENT telescope — a `variable`-heavy
1856/// section, a bundled algebraic structure, Mathlib's daily shape — the bound variable occurs
1857/// once or twice per binder, so one argument becomes 2n copies and the inferred type is
1858/// superlinear in the telescope depth. Lean pays nothing for this: its `Expr` is a hash-consed
1859/// DAG over de Bruijn indices.
1860///
1861/// LOGOS's equivalent is ζ: `let x : A := a in B` is definitionally `B[x := a]`, and it writes
1862/// `a` ONCE. The decision is a COST MODEL rather than a threshold — share exactly when the
1863/// duplication would more than double the result — so the common case (a small argument, or one
1864/// occurrence) is byte-identical to eager substitution and nothing downstream sees a change.
1865/// Instantiate a Pi codomain while retaining the kernel's sharing strategy.
1866/// This constructs a type expression only; callers must separately establish
1867/// that the function has this Pi type and the argument has its domain.
1868pub fn instantiate_codomain(param: &str, domain: &Term, body: &Term, argument: &Term) -> Term {
1869    expose_head(substitute_shared(body, param, domain, argument))
1870}
1871
1872fn substitute_shared(body: &Term, var: &str, var_type: &Term, replacement: &Term) -> Term {
1873    // THREE CHEAP GATES BEFORE THE ACCOUNTING. The App rule runs this at every node of every
1874    // application, so the accounting below — two full walks — may only be paid where it can pay
1875    // for itself. An atomic argument is free to copy; an argument the body does not mention is
1876    // not copied at all (`substitute`'s own short-circuit); and an argument small enough that
1877    // the accounting costs more than the copies it would save is copied. Skipping these made
1878    // registering the standard library two orders of magnitude slower.
1879    if is_atomic(replacement) {
1880        return substitute(body, var, replacement);
1881    }
1882    if !occurs_free(body, var) {
1883        return body.clone();
1884    }
1885    if !size_exceeds(replacement, SHARE_MIN_ARGUMENT_NODES) {
1886        return substitute(body, var, replacement);
1887    }
1888    let (occurrences, body_size) = body_stats(body, var);
1889    let repl_size = node_count(replacement);
1890    if (occurrences - 1) * repl_size <= body_size + repl_size {
1891        return substitute(body, var, replacement);
1892    }
1893    Term::Let {
1894        name: var.to_string(),
1895        ty: Box::new(var_type.clone()),
1896        value: Box::new(replacement.clone()),
1897        body: Box::new(body.clone()),
1898    }
1899}
1900
1901/// Peel shared bindings off the HEAD of a type so `infer_type` never hands back a `Let`-headed
1902/// one.
1903///
1904/// Every consumer of an inferred type matches on its head — `Pi` to apply another argument,
1905/// `Sort` to read a level, a `Global` spine to find an inductive. A shared binding at the head
1906/// would break all of them, so it is pushed inward instead: the immediate DOMAIN is substituted
1907/// (the caller needs it concrete to check the next argument against), and the binding is
1908/// re-established over the codomain, where it is still written once. Each application therefore
1909/// costs one copy of the argument, not one per remaining binder.
1910///
1911/// A binding whose variable the body does not use is DROPPED rather than carried, so a fully
1912/// applied type reports `Prop`, not `let A := … in Prop`.
1913///
1914/// A β-redex at the head breaks those consumers the same way, and instantiating a codomain
1915/// makes one whenever the argument substituted was a λ heading an application — a motive `P`
1916/// in `P x` is the everyday case. It is contracted here ([`head_beta`]), as Lean's instantiation
1917/// contracts it: `Nat.rec (motive := fun _ => Nat) z s n` infers `Nat`, not `(fun _ => Nat) n`.
1918fn expose_head(t: Term) -> Term {
1919    let Term::Let {
1920        name,
1921        ty,
1922        value,
1923        body,
1924    } = t
1925    else {
1926        // The overwhelmingly common shape: nothing shared and no redex at the head, so the type
1927        // is handed straight back by MOVE.
1928        return head_beta(t);
1929    };
1930    match expose_head(*body) {
1931        Term::Pi {
1932            param,
1933            param_type,
1934            body_type,
1935        } => {
1936            // Pushing the binding under the Π moves `value` under `param`'s binder, so a
1937            // `param` that occurs free in `value` (or shadows `name`) must be renamed first.
1938            let mut value_fvs = free_vars(&value);
1939            // The shared variable itself must be avoided too: the renamed binder lands in the
1940            // same scope as the ζ-binding, so a collision there would capture it.
1941            value_fvs.insert(name.clone());
1942            let (param, body_type) = if param == name || value_fvs.contains(&param) {
1943                let fresh = fresh_name(&param, &value_fvs);
1944                let renamed = substitute(&body_type, &param, &Term::Var(fresh.clone()));
1945                (fresh, renamed)
1946            } else {
1947                (param, *body_type)
1948            };
1949            let new_domain = substitute(&param_type, &name, &value);
1950            let new_codomain = if occurs_free(&body_type, &name) {
1951                Term::Let {
1952                    name,
1953                    ty,
1954                    value,
1955                    body: Box::new(body_type),
1956                }
1957            } else {
1958                body_type
1959            };
1960            Term::Pi {
1961                param,
1962                param_type: Box::new(new_domain),
1963                body_type: Box::new(new_codomain),
1964            }
1965        }
1966        other => head_beta(substitute(&other, &name, &value)),
1967    }
1968}
1969
1970/// The most β-steps [`head_beta`] takes before it hands the type back as it stands. A type
1971/// reaching it was built from checked parts, so its head reduction is short; the bound exists
1972/// so that no input can make the kernel spin, and stopping early is harmless — the result is
1973/// still convertible to the type, merely less exposed.
1974const MAX_HEAD_BETA_STEPS: usize = 4096;
1975
1976/// Contract the β-redexes at the HEAD of `t`: `(λx. B) a ā ⤳ B[x := a] ā`, repeated while the
1977/// head is a λ with an argument waiting. Only the head spine is touched; anything else, and a
1978/// term with no redex at its head, is returned by move.
1979fn head_beta(t: Term) -> Term {
1980    fn head_is_lambda(mut t: &Term) -> bool {
1981        while let Term::App(f, _) = t {
1982            t = f;
1983        }
1984        matches!(t, Term::Lambda { .. })
1985    }
1986    if !matches!(t, Term::App(..)) || !head_is_lambda(&t) {
1987        return t;
1988    }
1989    // The spine's arguments, LAST first, so the next argument to consume is `pop`.
1990    let mut pending: Vec<Term> = Vec::new();
1991    let mut head = t;
1992    while let Term::App(f, a) = head {
1993        pending.push(*a);
1994        head = *f;
1995    }
1996    for _ in 0..MAX_HEAD_BETA_STEPS {
1997        let Term::Lambda {
1998            param,
1999            param_type,
2000            body,
2001        } = head
2002        else {
2003            break;
2004        };
2005        let Some(argument) = pending.pop() else {
2006            head = Term::Lambda {
2007                param,
2008                param_type,
2009                body,
2010            };
2011            break;
2012        };
2013        head = substitute(&body, &param, &argument);
2014        while let Term::App(f, a) = head {
2015            pending.push(*a);
2016            head = *f;
2017        }
2018    }
2019    pending
2020        .into_iter()
2021        .rev()
2022        .fold(head, |f, a| Term::App(Box::new(f), Box::new(a)))
2023}
2024
2025/// Whether `var` occurs free in `term` (binder-aware, short-circuiting).
2026pub(crate) fn occurs_free(term: &Term, var: &str) -> bool {
2027    match term {
2028        Term::Var(name) => name == var,
2029        Term::Sort(_) | Term::Lit(_) | Term::Hole | Term::Global(_) | Term::Const { .. } => false,
2030        Term::App(func, arg) => occurs_free(func, var) || occurs_free(arg, var),
2031        Term::Pi {
2032            param,
2033            param_type,
2034            body_type,
2035        } => occurs_free(param_type, var) || (param != var && occurs_free(body_type, var)),
2036        Term::Lambda {
2037            param,
2038            param_type,
2039            body,
2040        } => occurs_free(param_type, var) || (param != var && occurs_free(body, var)),
2041        Term::Fix { name, body } => name != var && occurs_free(body, var),
2042        Term::MutualFix { defs, .. } => {
2043            // `var` is free only if it is not one of the (all-binding) def names AND
2044            // occurs free in some body.
2045            !defs.iter().any(|(n, _)| n == var) && defs.iter().any(|(_, b)| occurs_free(b, var))
2046        }
2047        Term::Let {
2048            name,
2049            ty,
2050            value,
2051            body,
2052        } => {
2053            occurs_free(ty, var)
2054                || occurs_free(value, var)
2055                || (name != var && occurs_free(body, var))
2056        }
2057        Term::Match {
2058            discriminant,
2059            motive,
2060            cases,
2061        } => {
2062            occurs_free(discriminant, var)
2063                || occurs_free(motive, var)
2064                || cases.iter().any(|c| occurs_free(c, var))
2065        }
2066        Term::Annotated { term, .. } => occurs_free(term, var),
2067    }
2068}
2069
2070/// Collect the free variables of a term (named representation).
2071pub(crate) fn free_vars(term: &Term) -> std::collections::HashSet<String> {
2072    fn go(term: &Term, bound: &mut Vec<String>, acc: &mut std::collections::HashSet<String>) {
2073        match term {
2074            Term::Var(name) => {
2075                if !bound.iter().any(|b| b == name) {
2076                    acc.insert(name.clone());
2077                }
2078            }
2079            Term::Sort(_) | Term::Lit(_) | Term::Hole | Term::Global(_) | Term::Const { .. } => {}
2080            Term::App(func, arg) => {
2081                go(func, bound, acc);
2082                go(arg, bound, acc);
2083            }
2084            Term::Pi {
2085                param,
2086                param_type,
2087                body_type,
2088            } => {
2089                go(param_type, bound, acc);
2090                bound.push(param.clone());
2091                go(body_type, bound, acc);
2092                bound.pop();
2093            }
2094            Term::Lambda {
2095                param,
2096                param_type,
2097                body,
2098            } => {
2099                go(param_type, bound, acc);
2100                bound.push(param.clone());
2101                go(body, bound, acc);
2102                bound.pop();
2103            }
2104            Term::Fix { name, body } => {
2105                bound.push(name.clone());
2106                go(body, bound, acc);
2107                bound.pop();
2108            }
2109            Term::MutualFix { defs, .. } => {
2110                for (n, _) in defs {
2111                    bound.push(n.clone());
2112                }
2113                for (_, b) in defs {
2114                    go(b, bound, acc);
2115                }
2116                for _ in defs {
2117                    bound.pop();
2118                }
2119            }
2120            Term::Let {
2121                name,
2122                ty,
2123                value,
2124                body,
2125            } => {
2126                go(ty, bound, acc);
2127                go(value, bound, acc);
2128                bound.push(name.clone());
2129                go(body, bound, acc);
2130                bound.pop();
2131            }
2132            Term::Match {
2133                discriminant,
2134                motive,
2135                cases,
2136            } => {
2137                go(discriminant, bound, acc);
2138                go(motive, bound, acc);
2139                for c in cases {
2140                    go(c, bound, acc);
2141                }
2142            }
2143            Term::Annotated { term, .. } => go(term, bound, acc),
2144        }
2145    }
2146    let mut acc = std::collections::HashSet::new();
2147    let mut bound = Vec::new();
2148    go(term, &mut bound, &mut acc);
2149    acc
2150}
2151
2152/// Collect every variable name appearing in a term (bound or free).
2153fn all_var_names(term: &Term, acc: &mut std::collections::HashSet<String>) {
2154    match term {
2155        Term::Var(name) => {
2156            acc.insert(name.clone());
2157        }
2158        Term::Sort(_) | Term::Lit(_) | Term::Hole | Term::Global(_) | Term::Const { .. } => {}
2159        Term::App(func, arg) => {
2160            all_var_names(func, acc);
2161            all_var_names(arg, acc);
2162        }
2163        Term::Pi {
2164            param,
2165            param_type,
2166            body_type,
2167        } => {
2168            acc.insert(param.clone());
2169            all_var_names(param_type, acc);
2170            all_var_names(body_type, acc);
2171        }
2172        Term::Lambda {
2173            param,
2174            param_type,
2175            body,
2176        } => {
2177            acc.insert(param.clone());
2178            all_var_names(param_type, acc);
2179            all_var_names(body, acc);
2180        }
2181        Term::Fix { name, body } => {
2182            acc.insert(name.clone());
2183            all_var_names(body, acc);
2184        }
2185        Term::MutualFix { defs, .. } => {
2186            for (n, b) in defs {
2187                acc.insert(n.clone());
2188                all_var_names(b, acc);
2189            }
2190        }
2191        Term::Let {
2192            name,
2193            ty,
2194            value,
2195            body,
2196        } => {
2197            acc.insert(name.clone());
2198            all_var_names(ty, acc);
2199            all_var_names(value, acc);
2200            all_var_names(body, acc);
2201        }
2202        Term::Match {
2203            discriminant,
2204            motive,
2205            cases,
2206        } => {
2207            all_var_names(discriminant, acc);
2208            all_var_names(motive, acc);
2209            for c in cases {
2210                all_var_names(c, acc);
2211            }
2212        }
2213        Term::Annotated { term, .. } => all_var_names(term, acc),
2214    }
2215}
2216
2217/// Pick a binder name derived from `base` that collides with nothing in `avoid`.
2218fn fresh_name(base: &str, avoid: &std::collections::HashSet<String>) -> String {
2219    let mut candidate = format!("{}'", base);
2220    let mut counter: u32 = 0;
2221    while avoid.contains(&candidate) {
2222        counter += 1;
2223        candidate = format!("{}'{}", base, counter);
2224    }
2225    candidate
2226}
2227
2228/// Fresh for scoped syntax and active local keys AND stored local types.
2229fn fresh_context_name(ctx: &Context, base: &str, terms: &[&Term]) -> String {
2230    let mut avoid = std::collections::HashSet::new();
2231    for term in terms {
2232        all_var_names(term, &mut avoid);
2233    }
2234    let mut name = fresh_name(base, &avoid);
2235    while avoid.contains(&name) || ctx.local_name_in_use(&name) {
2236        name.push('_');
2237    }
2238    name
2239}
2240
2241/// A lexical binder may not overwrite a name needed by a stored local type.
2242/// Preserve borrowed syntax when unused; its own annotation is never renamed.
2243fn open_context_binder<'a>(
2244    ctx: &Context,
2245    name: &'a str,
2246    domain: &Term,
2247    body: &'a Term,
2248) -> (std::borrow::Cow<'a, str>, std::borrow::Cow<'a, Term>) {
2249    use std::borrow::Cow;
2250    if !binder_would_capture(ctx, name, domain) {
2251        return (Cow::Borrowed(name), Cow::Borrowed(body));
2252    }
2253    let fresh = fresh_context_name(ctx, name, &[domain, body]);
2254    let opened = rename_var(body, name, &fresh);
2255    (Cow::Owned(fresh), Cow::Owned(opened))
2256}
2257
2258/// Whether entering a binder named `name` over `domain` would capture an outer occurrence.
2259///
2260/// Two occurrences can be captured: one free in a stored local type, which would re-point at the
2261/// new binder, and one free in the binder's own domain, which is read in the OUTER scope — but
2262/// only while an outer local of that name exists, since otherwise the domain is unbound anyway.
2263/// Merely shadowing an outer local that nothing mentions captures nothing: the outer binding is
2264/// unreachable under the binder, exactly as with de Bruijn indices, so the author's binder name
2265/// is kept — the inferred type of `λ(x:A). λ(x:A). x` is `Π(x:A). Π(x:A). A`, as in Lean.
2266fn binder_would_capture(ctx: &Context, name: &str, domain: &Term) -> bool {
2267    ctx.local_types_mention(name) || (ctx.has_local(name) && occurs_free(domain, name))
2268}
2269
2270/// Choose all targets before renaming mutually scoped recursive bodies.
2271fn open_context_mutual<'a>(
2272    ctx: &Context,
2273    defs: &'a [(String, Term)],
2274) -> std::borrow::Cow<'a, [(String, Term)]> {
2275    use std::borrow::Cow;
2276    if !defs.iter().any(|(name, _)| ctx.local_name_in_use(name)) {
2277        return Cow::Borrowed(defs);
2278    }
2279    let mut avoid = std::collections::HashSet::new();
2280    for (name, body) in defs {
2281        avoid.insert(name.clone());
2282        all_var_names(body, &mut avoid);
2283    }
2284    let mut replacements = Vec::new();
2285    for (name, _) in defs {
2286        if ctx.local_name_in_use(name) && !replacements.iter().any(|(old, _)| old == name) {
2287            let mut fresh = fresh_name(name, &avoid);
2288            while avoid.contains(&fresh) || ctx.local_name_in_use(&fresh) {
2289                fresh.push('_');
2290            }
2291            avoid.insert(fresh.clone());
2292            replacements.push((name.clone(), fresh));
2293        }
2294    }
2295    Cow::Owned(
2296        defs.iter()
2297            .map(|(name, body)| {
2298                let mut opened = body.clone();
2299                for (old, fresh) in &replacements {
2300                    opened = rename_var(&opened, old, fresh);
2301                }
2302                let name = replacements
2303                    .iter()
2304                    .find(|(old, _)| old == name)
2305                    .map_or_else(|| name.clone(), |(_, fresh)| fresh.clone());
2306                (name, opened)
2307            })
2308            .collect(),
2309    )
2310}
2311
2312/// Choose a fresh binder name for `param`, avoiding the replacement's free vars,
2313/// every name occurring in `body`, and the variable being substituted.
2314fn freshen(
2315    param: &str,
2316    body: &Term,
2317    replacement_fvs: &std::collections::HashSet<String>,
2318    var: &str,
2319) -> String {
2320    let mut avoid = replacement_fvs.clone();
2321    all_var_names(body, &mut avoid);
2322    avoid.insert(var.to_string());
2323    fresh_name(param, &avoid)
2324}
2325
2326/// Rename free occurrences of `from` to `to` in `term`. `to` must be globally
2327/// fresh in `term`, so this rename cannot itself capture.
2328fn rename_var(term: &Term, from: &str, to: &str) -> Term {
2329    let repl = Term::Var(to.to_string());
2330    let mut fvs = std::collections::HashSet::new();
2331    fvs.insert(to.to_string());
2332    substitute_avoiding(term, from, &repl, &fvs)
2333}
2334
2335/// Capture-avoiding substitution `body[var := replacement]`, where
2336/// `replacement_fvs` is the precomputed free-variable set of `replacement`.
2337///
2338/// When a binder (`Pi`/`Lambda`/`Fix`) would capture a free variable of
2339/// `replacement`, the binder is alpha-renamed to a fresh name before the
2340/// substitution descends into its body.
2341/// Consume the body and final replacement occurrence using the same capture-
2342/// avoiding binder traversal as borrowed substitution. The caller supplies the
2343/// exact lexical occurrence count after checking its own output-size bound.
2344pub(crate) fn substitute_owned_value_counted(
2345    body: Term,
2346    var: &str,
2347    replacement: Term,
2348    occurrences: usize,
2349) -> Term {
2350    if occurrences == 0 {
2351        return body;
2352    }
2353    let free = free_vars(&replacement);
2354    let mut value = SubstitutionValue::Owned {
2355        term: Some(replacement),
2356        remaining: occurrences,
2357    };
2358    let result = substitute_input(SubstitutionInput::Owned(body), var, &mut value, &free);
2359    debug_assert!(matches!(
2360        value,
2361        SubstitutionValue::Owned { remaining: 0, .. }
2362    ));
2363    result
2364}
2365
2366/// With a closed replacement, the final lexical occurrence can take its
2367/// already-owned storage. Earlier occurrences still receive distinct clones.
2368/// The same binder traversal serves borrowed, body-owned and fully-owned input.
2369pub(crate) fn substitute_owned_closed_value_counted(
2370    body: Term,
2371    var: &str,
2372    replacement: Term,
2373    occurrences: usize,
2374) -> Term {
2375    let remaining = occurrences;
2376    let mut value = SubstitutionValue::Owned {
2377        term: Some(replacement),
2378        remaining,
2379    };
2380    let result = substitute_input(
2381        SubstitutionInput::Owned(body),
2382        var,
2383        &mut value,
2384        &std::collections::HashSet::new(),
2385    );
2386    debug_assert!(matches!(
2387        value,
2388        SubstitutionValue::Owned { remaining: 0, .. }
2389    ));
2390    result
2391}
2392
2393enum SubstitutionValue<'a> {
2394    Borrowed(&'a Term),
2395    Owned {
2396        term: Option<Term>,
2397        remaining: usize,
2398    },
2399}
2400impl SubstitutionValue<'_> {
2401    fn materialize(&mut self) -> Term {
2402        match self {
2403            Self::Borrowed(term) => {
2404                #[cfg(test)]
2405                record_substitution_tree(term);
2406                (*term).clone()
2407            }
2408            Self::Owned { term, remaining } => {
2409                assert!(
2410                    *remaining > 0,
2411                    "lexical occurrence count must cover substitution"
2412                );
2413                *remaining -= 1;
2414                if *remaining == 0 {
2415                    term.take().expect("owned replacement available")
2416                } else {
2417                    let term = term.as_ref().expect("owned replacement retained");
2418                    #[cfg(test)]
2419                    record_substitution_tree(term);
2420                    term.clone()
2421                }
2422            }
2423        }
2424    }
2425}
2426fn substitute_avoiding(
2427    body: &Term,
2428    var: &str,
2429    replacement: &Term,
2430    replacement_fvs: &std::collections::HashSet<String>,
2431) -> Term {
2432    substitute_input(
2433        SubstitutionInput::Borrowed(body),
2434        var,
2435        &mut SubstitutionValue::Borrowed(replacement),
2436        replacement_fvs,
2437    )
2438}
2439
2440/// Capture-avoiding substitution that reuses the owned body's containers.
2441/// The borrowed replacement follows the same freshening and occurrence rules
2442/// as public substitution, including when the target variable is absent.
2443pub(crate) fn substitute_owned(body: Term, var: &str, replacement: &Term) -> Term {
2444    if !occurs_free(&body, var) {
2445        return body;
2446    }
2447    let free = free_vars(replacement);
2448    substitute_input(
2449        SubstitutionInput::Owned(body),
2450        var,
2451        &mut SubstitutionValue::Borrowed(replacement),
2452        &free,
2453    )
2454}
2455
2456/// The caller has already established lexical closedness of the replacement.
2457/// This owns the body and retains its existing containers during substitution.
2458pub(crate) fn substitute_owned_closed(body: Term, var: &str, replacement: &Term) -> Term {
2459    substitute_input(
2460        SubstitutionInput::Owned(body),
2461        var,
2462        &mut SubstitutionValue::Borrowed(replacement),
2463        &std::collections::HashSet::new(),
2464    )
2465}
2466
2467enum SubstitutionInput<'a> {
2468    Borrowed(&'a Term),
2469    Owned(Term),
2470}
2471
2472enum SubstitutionChild<'a> {
2473    Borrowed(&'a Term),
2474    Owned(Box<Term>),
2475}
2476
2477enum SubstitutionCases<'a> {
2478    Borrowed(&'a [Term]),
2479    Owned(Vec<Term>),
2480}
2481
2482enum SubstitutionDefinitions<'a> {
2483    Borrowed(&'a [(String, Term)]),
2484    Owned(Vec<(String, Term)>),
2485}
2486
2487// This view separates storage ownership from the single binder algorithm below.
2488enum SubstitutionView<'a> {
2489    Atom(SubstitutionInput<'a>),
2490    Binder {
2491        pi: bool,
2492        name: std::borrow::Cow<'a, str>,
2493        domain: SubstitutionChild<'a>,
2494        body: SubstitutionChild<'a>,
2495    },
2496    App(SubstitutionChild<'a>, SubstitutionChild<'a>),
2497    Match {
2498        discriminant: SubstitutionChild<'a>,
2499        motive: SubstitutionChild<'a>,
2500        cases: SubstitutionCases<'a>,
2501    },
2502    Fix {
2503        name: std::borrow::Cow<'a, str>,
2504        body: SubstitutionChild<'a>,
2505    },
2506    MutualFix {
2507        defs: SubstitutionDefinitions<'a>,
2508        index: usize,
2509    },
2510    Let {
2511        name: std::borrow::Cow<'a, str>,
2512        ty: SubstitutionChild<'a>,
2513        value: SubstitutionChild<'a>,
2514        body: SubstitutionChild<'a>,
2515    },
2516    Annotated {
2517        annotation: std::borrow::Cow<'a, crate::Annotation>,
2518        term: SubstitutionChild<'a>,
2519    },
2520}
2521
2522impl<'a> SubstitutionInput<'a> {
2523    fn view(self) -> SubstitutionView<'a> {
2524        use std::borrow::Cow;
2525        use SubstitutionChild::{Borrowed as B, Owned as O};
2526        match self {
2527            Self::Borrowed(term) => match term {
2528                Term::Pi {
2529                    param,
2530                    param_type,
2531                    body_type,
2532                } => SubstitutionView::Binder {
2533                    pi: true,
2534                    name: Cow::Borrowed(param),
2535                    domain: B(param_type),
2536                    body: B(body_type),
2537                },
2538                Term::Lambda {
2539                    param,
2540                    param_type,
2541                    body,
2542                } => SubstitutionView::Binder {
2543                    pi: false,
2544                    name: Cow::Borrowed(param),
2545                    domain: B(param_type),
2546                    body: B(body),
2547                },
2548                Term::App(f, a) => SubstitutionView::App(B(f), B(a)),
2549                Term::Match {
2550                    discriminant,
2551                    motive,
2552                    cases,
2553                } => SubstitutionView::Match {
2554                    discriminant: B(discriminant),
2555                    motive: B(motive),
2556                    cases: SubstitutionCases::Borrowed(cases),
2557                },
2558                Term::Fix { name, body } => SubstitutionView::Fix {
2559                    name: Cow::Borrowed(name),
2560                    body: B(body),
2561                },
2562                Term::MutualFix { defs, index } => SubstitutionView::MutualFix {
2563                    defs: SubstitutionDefinitions::Borrowed(defs),
2564                    index: *index,
2565                },
2566                Term::Let {
2567                    name,
2568                    ty,
2569                    value,
2570                    body,
2571                } => SubstitutionView::Let {
2572                    name: Cow::Borrowed(name),
2573                    ty: B(ty),
2574                    value: B(value),
2575                    body: B(body),
2576                },
2577                Term::Annotated { annotation, term } => SubstitutionView::Annotated {
2578                    annotation: Cow::Borrowed(annotation),
2579                    term: B(term),
2580                },
2581                _ => SubstitutionView::Atom(Self::Borrowed(term)),
2582            },
2583            Self::Owned(term) => match term {
2584                Term::Pi {
2585                    param,
2586                    param_type,
2587                    body_type,
2588                } => SubstitutionView::Binder {
2589                    pi: true,
2590                    name: Cow::Owned(param),
2591                    domain: O(param_type),
2592                    body: O(body_type),
2593                },
2594                Term::Lambda {
2595                    param,
2596                    param_type,
2597                    body,
2598                } => SubstitutionView::Binder {
2599                    pi: false,
2600                    name: Cow::Owned(param),
2601                    domain: O(param_type),
2602                    body: O(body),
2603                },
2604                Term::App(f, a) => SubstitutionView::App(O(f), O(a)),
2605                Term::Match {
2606                    discriminant,
2607                    motive,
2608                    cases,
2609                } => SubstitutionView::Match {
2610                    discriminant: O(discriminant),
2611                    motive: O(motive),
2612                    cases: SubstitutionCases::Owned(cases),
2613                },
2614                Term::Fix { name, body } => SubstitutionView::Fix {
2615                    name: Cow::Owned(name),
2616                    body: O(body),
2617                },
2618                Term::MutualFix { defs, index } => SubstitutionView::MutualFix {
2619                    defs: SubstitutionDefinitions::Owned(defs),
2620                    index,
2621                },
2622                Term::Let {
2623                    name,
2624                    ty,
2625                    value,
2626                    body,
2627                } => SubstitutionView::Let {
2628                    name: Cow::Owned(name),
2629                    ty: O(ty),
2630                    value: O(value),
2631                    body: O(body),
2632                },
2633                Term::Annotated { annotation, term } => SubstitutionView::Annotated {
2634                    annotation: Cow::Owned(annotation),
2635                    term: O(term),
2636                },
2637                _ => SubstitutionView::Atom(Self::Owned(term)),
2638            },
2639        }
2640    }
2641}
2642
2643impl<'a> SubstitutionChild<'a> {
2644    fn as_term(&self) -> &Term {
2645        match self {
2646            Self::Borrowed(t) => t,
2647            Self::Owned(t) => t,
2648        }
2649    }
2650
2651    fn keep(self) -> Box<Term> {
2652        match self {
2653            Self::Borrowed(t) => {
2654                #[cfg(test)]
2655                record_substitution_tree(t);
2656                Box::new(t.clone())
2657            }
2658            Self::Owned(t) => t,
2659        }
2660    }
2661
2662    fn apply(
2663        self,
2664        var: &str,
2665        value: &mut SubstitutionValue<'_>,
2666        fvs: &std::collections::HashSet<String>,
2667    ) -> Box<Term> {
2668        match self {
2669            Self::Borrowed(t) => Box::new(substitute_input(
2670                SubstitutionInput::Borrowed(t),
2671                var,
2672                value,
2673                fvs,
2674            )),
2675            Self::Owned(mut t) => {
2676                let input = std::mem::replace(t.as_mut(), Term::Hole);
2677                *t = substitute_input(SubstitutionInput::Owned(input), var, value, fvs);
2678                t
2679            }
2680        }
2681    }
2682
2683    fn rename(self, old: &str, new: &str) -> Self {
2684        match self {
2685            Self::Borrowed(t) => Self::Owned(Box::new(rename_var(t, old, new))),
2686            Self::Owned(mut t) => {
2687                *t = rename_var(&t, old, new);
2688                Self::Owned(t)
2689            }
2690        }
2691    }
2692}
2693
2694fn substitute_binder<'a>(
2695    mut name: std::borrow::Cow<'a, str>,
2696    mut body: SubstitutionChild<'a>,
2697    var: &str,
2698    value: &mut SubstitutionValue<'_>,
2699    fvs: &std::collections::HashSet<String>,
2700) -> (String, Box<Term>) {
2701    if name.as_ref() == var {
2702        return (name.into_owned(), body.keep());
2703    }
2704    if fvs.contains(name.as_ref()) {
2705        let fresh = freshen(&name, body.as_term(), fvs, var);
2706        body = body.rename(&name, &fresh);
2707        name = std::borrow::Cow::Owned(fresh);
2708    }
2709    (name.into_owned(), body.apply(var, value, fvs))
2710}
2711
2712#[cfg(test)]
2713thread_local! {
2714    static SUBSTITUTION_COPY_WORK: std::cell::Cell<(usize, usize)> =
2715        const { std::cell::Cell::new((0, 0)) };
2716}
2717
2718#[cfg(test)]
2719pub(crate) fn take_substitution_copy_work() -> (usize, usize) {
2720    SUBSTITUTION_COPY_WORK.with(|work| work.replace((0, 0)))
2721}
2722
2723#[cfg(test)]
2724fn record_substitution_node(term: &Term) {
2725    let bytes = match term {
2726        Term::Var(name)
2727        | Term::Global(name)
2728        | Term::Const { name, .. }
2729        | Term::Fix { name, .. }
2730        | Term::Let { name, .. } => name.len(),
2731        Term::Pi { param, .. } | Term::Lambda { param, .. } => param.len(),
2732        Term::MutualFix { defs, .. } => defs.iter().map(|(name, _)| name.len()).sum(),
2733        _ => 0,
2734    };
2735    SUBSTITUTION_COPY_WORK.with(|work| {
2736        let (nodes, names) = work.get();
2737        work.set((nodes + 1, names + bytes));
2738    });
2739}
2740
2741#[cfg(test)]
2742fn record_substitution_tree(term: &Term) {
2743    record_substitution_node(term);
2744    match term {
2745        Term::Pi {
2746            param_type,
2747            body_type,
2748            ..
2749        } => {
2750            record_substitution_tree(param_type);
2751            record_substitution_tree(body_type);
2752        }
2753        Term::Lambda {
2754            param_type, body, ..
2755        } => {
2756            record_substitution_tree(param_type);
2757            record_substitution_tree(body);
2758        }
2759        Term::App(f, a) => {
2760            record_substitution_tree(f);
2761            record_substitution_tree(a);
2762        }
2763        Term::Match {
2764            discriminant,
2765            motive,
2766            cases,
2767        } => {
2768            record_substitution_tree(discriminant);
2769            record_substitution_tree(motive);
2770            for case in cases {
2771                record_substitution_tree(case);
2772            }
2773        }
2774        Term::Fix { body, .. } => record_substitution_tree(body),
2775        Term::MutualFix { defs, .. } => {
2776            for (_, body) in defs {
2777                record_substitution_tree(body);
2778            }
2779        }
2780        Term::Let {
2781            ty, value, body, ..
2782        } => {
2783            record_substitution_tree(ty);
2784            record_substitution_tree(value);
2785            record_substitution_tree(body);
2786        }
2787        Term::Annotated { term, .. } => record_substitution_tree(term),
2788        Term::Sort(_)
2789        | Term::Var(_)
2790        | Term::Global(_)
2791        | Term::Const { .. }
2792        | Term::Lit(_)
2793        | Term::Hole => {}
2794    }
2795}
2796
2797fn substitute_input(
2798    input: SubstitutionInput<'_>,
2799    var: &str,
2800    value: &mut SubstitutionValue<'_>,
2801    fvs: &std::collections::HashSet<String>,
2802) -> Term {
2803    // Counters observe actual borrowed-node reconstruction and replacement
2804    // clones. Identifier bytes exclude literal and universe payloads.
2805    #[cfg(test)]
2806    if let SubstitutionInput::Borrowed(term) = &input {
2807        if !matches!(term, Term::Var(name) if name == var) {
2808            record_substitution_node(term);
2809        }
2810    }
2811    match input.view() {
2812        SubstitutionView::Atom(input) => {
2813            let term = match &input {
2814                SubstitutionInput::Borrowed(t) => *t,
2815                SubstitutionInput::Owned(t) => t,
2816            };
2817            if matches!(term, Term::Var(name) if name == var) {
2818                value.materialize()
2819            } else {
2820                match input {
2821                    SubstitutionInput::Borrowed(t) => t.clone(),
2822                    SubstitutionInput::Owned(t) => t,
2823                }
2824            }
2825        }
2826        SubstitutionView::Binder {
2827            pi,
2828            name,
2829            domain,
2830            body,
2831        } => {
2832            let param_type = domain.apply(var, value, fvs);
2833            let (param, body) = substitute_binder(name, body, var, value, fvs);
2834            if pi {
2835                Term::Pi {
2836                    param,
2837                    param_type,
2838                    body_type: body,
2839                }
2840            } else {
2841                Term::Lambda {
2842                    param,
2843                    param_type,
2844                    body,
2845                }
2846            }
2847        }
2848        SubstitutionView::App(f, a) => {
2849            Term::App(f.apply(var, value, fvs), a.apply(var, value, fvs))
2850        }
2851        SubstitutionView::Match {
2852            discriminant,
2853            motive,
2854            cases,
2855        } => {
2856            let discriminant = discriminant.apply(var, value, fvs);
2857            let motive = motive.apply(var, value, fvs);
2858            let cases = match cases {
2859                SubstitutionCases::Borrowed(cases) => cases
2860                    .iter()
2861                    .map(|case| {
2862                        substitute_input(SubstitutionInput::Borrowed(case), var, value, fvs)
2863                    })
2864                    .collect(),
2865                SubstitutionCases::Owned(mut cases) => {
2866                    for case in &mut cases {
2867                        let input = std::mem::replace(case, Term::Hole);
2868                        *case = substitute_input(SubstitutionInput::Owned(input), var, value, fvs);
2869                    }
2870                    cases
2871                }
2872            };
2873            Term::Match {
2874                discriminant,
2875                motive,
2876                cases,
2877            }
2878        }
2879        SubstitutionView::Fix { name, body } => {
2880            let (name, body) = substitute_binder(name, body, var, value, fvs);
2881            Term::Fix { name, body }
2882        }
2883        SubstitutionView::MutualFix { defs, index } => {
2884            let mut defs = match defs {
2885                SubstitutionDefinitions::Borrowed(defs) => {
2886                    #[cfg(test)]
2887                    for (_, body) in defs {
2888                        record_substitution_tree(body);
2889                    }
2890                    defs.to_vec()
2891                }
2892                SubstitutionDefinitions::Owned(defs) => defs,
2893            };
2894            if defs.iter().any(|(name, _)| name == var) {
2895                return Term::MutualFix { defs, index };
2896            }
2897            // All mutual names bind in every body. Freshen each conflicting
2898            // name consistently across the block before substituting any body.
2899            for i in 0..defs.len() {
2900                if fvs.contains(&defs[i].0) {
2901                    let mut avoid = fvs.clone();
2902                    for (name, body) in &defs {
2903                        all_var_names(body, &mut avoid);
2904                        avoid.insert(name.clone());
2905                    }
2906                    avoid.insert(var.to_string());
2907                    let fresh = fresh_name(&defs[i].0, &avoid);
2908                    for j in 0..defs.len() {
2909                        defs[j].1 = rename_var(&defs[j].1, &defs[i].0, &fresh);
2910                    }
2911                    defs[i].0 = fresh;
2912                }
2913            }
2914            for (_, body) in &mut defs {
2915                let input = std::mem::replace(body, Term::Hole);
2916                *body = substitute_input(SubstitutionInput::Owned(input), var, value, fvs);
2917            }
2918            Term::MutualFix { defs, index }
2919        }
2920        SubstitutionView::Let {
2921            name,
2922            ty,
2923            value: binding,
2924            body,
2925        } => {
2926            let ty = ty.apply(var, value, fvs);
2927            let binding = binding.apply(var, value, fvs);
2928            let (name, body) = substitute_binder(name, body, var, value, fvs);
2929            Term::Let {
2930                name,
2931                ty,
2932                value: binding,
2933                body,
2934            }
2935        }
2936        SubstitutionView::Annotated { annotation, term } => Term::Annotated {
2937            annotation: annotation.into_owned(),
2938            term: term.apply(var, value, fvs),
2939        },
2940    }
2941}
2942
2943/// Check if type `a` is a subtype of type `b` (cumulativity).
2944///
2945/// Implements the subtyping relation for the Calculus of Constructions
2946/// with cumulative universes.
2947///
2948/// # Subtyping Rules
2949///
2950/// - **Universe cumulativity**: `Type i <= Type j` if `i <= j`
2951/// - **Pi contravariance**: `Π(x:A). B <= Π(x:A'). B'` if `A' <= A` and `B <= B'`
2952/// - **Structural equality**: Other terms are compared after normalization
2953///
2954/// # Normalization
2955///
2956/// Both types are normalized before comparison, ensuring that definitionally
2957/// equal types are recognized as subtypes.
2958///
2959/// # Cumulativity Examples
2960///
2961/// - `Type 0 <= Type 1` (lower universe is subtype of higher)
2962/// - `Nat -> Type 0 <= Nat -> Type 1` (covariant in return type)
2963/// - `Type 1 -> Nat <= Type 0 -> Nat` (contravariant in parameter type)
2964pub fn is_subtype(ctx: &Context, a: &Term, b: &Term) -> bool {
2965    if let Some(r) = crate::annotation::erased_pair(a, b, |a, b| is_subtype(ctx, a, b)) {
2966        return r;
2967    }
2968    // The sized stack, BEFORE the α fast path: `types_equal` descends both terms with real
2969    // frames, so a deep pair aborts the process inside the shortcut rather than inside the
2970    // comparison it was shortcutting. `deepen_stack_all` sizes for the DEEPER of the two, in
2971    // one pass, and short-circuits once a kernel call is already under way.
2972    if !inside_kernel() {
2973        if let Some(r) = crate::term_store::deepen_stack_all(&[a, b], || is_subtype(ctx, a, b)) {
2974            return r;
2975        }
2976    }
2977    // Fast path: already structurally (definitionally) equal — the overwhelming case
2978    // in propositional/FOL proofs, where types are atoms and ∧/∨/¬/→ in normal form.
2979    // Skipping the two `normalize` walks here is the difference between linear and
2980    // pathological checking on a large certified grid proof.
2981    if alpha_eq(a, b) {
2982        return true;
2983    }
2984    // A term too deep to descend is REFUSED, and a refused conversion is "not equal" — never
2985    // "equal", which would certify a comparison the kernel never actually made.
2986    if enter_kernel(a, "is_subtype").is_err() || enter_kernel(b, "is_subtype").is_err() {
2987        return false;
2988    }
2989    if crate::conversion_session::known(ctx, a, b) {
2990        return true;
2991    }
2992    if let Some(equal) = rigid_conversion(ctx, a, b) {
2993        return equal;
2994    }
2995    if conversion_by_congruence(ctx, a, b) {
2996        return true;
2997    }
2998    if conversion_by_unfolded_head(ctx, a, b) {
2999        return true;
3000    }
3001    // Otherwise normalize both terms before comparison — this ensures that e.g.
3002    // `ReachesOne (collatzStep 2)` equals `ReachesOne 1`.
3003    if crate::term_store::beta_zeta_equivalent(ctx, a, b, 1 << 16) {
3004        return true;
3005    }
3006    if crate::term_store::beta_delta_equivalent(ctx, a, b, 1 << 16) {
3007        return true;
3008    }
3009    let a_norm = normalize(ctx, a);
3010    let b_norm = normalize(ctx, b);
3011
3012    is_subtype_normalized(ctx, &a_norm, &b_norm)
3013}
3014
3015/// Check subtyping on already-normalized terms. Cumulativity lives ONLY here: universes
3016/// follow `Prop ≤ Type i ≤ Type j`, and a `Π` is contravariant in its domain and covariant
3017/// in its codomain. Every other position is INVARIANT and delegates to [`def_eq_normalized`]
3018/// (definitional equality: reduction + η + proof irrelevance) — using cumulative subtyping
3019/// in an invariant position (e.g. a function argument) would be unsound.
3020fn is_subtype_normalized(ctx: &Context, a: &Term, b: &Term) -> bool {
3021    // ζ ON DEMAND. `reduction`'s ζ rule now KEEPS a `Let` whose variable occurs more than once
3022    // — the binding IS the sharing node, and writing the value out at every occurrence is the
3023    // quadratic blow-up it exists to avoid — so a `Let` survives into a normal form and
3024    // conversion has to be able to see through one. Without this step two convertible terms,
3025    // one of which kept its binding, compare UNEQUAL, and sharing would change what a type
3026    // MEANS, which is the one thing an optimisation may never do. Expanding is always sound:
3027    // `let x := v in b` and `b[x := v]` are the SAME term by ζ, in every calculus that has it.
3028    // Each expansion removes one binder from the head, so the recursion terminates.
3029    if let Some(expanded) = crate::term_store::zeta_expand_head_term(a) {
3030        return is_subtype_normalized(ctx, &normalize(ctx, &expanded), b);
3031    }
3032    if let Some(expanded) = crate::term_store::zeta_expand_head_term(b) {
3033        return is_subtype_normalized(ctx, a, &normalize(ctx, &expanded));
3034    }
3035    match (a, b) {
3036        // Universe subtyping
3037        (Term::Sort(u1), Term::Sort(u2)) => u1.is_subtype_of(u2),
3038
3039        // Pi subtyping (contravariant in param, covariant in body)
3040        (
3041            Term::Pi {
3042                param: p1,
3043                param_type: t1,
3044                body_type: b1,
3045            },
3046            Term::Pi {
3047                param: p2,
3048                param_type: t2,
3049                body_type: b2,
3050            },
3051        ) => {
3052            // Contravariant: t2 ≤ t1 (the expected param can be more specific)
3053            is_subtype_normalized(ctx, t2, t1) && {
3054                // Covariant: b1 ≤ b2 (alpha-rename to compare bodies, under the binder)
3055                let (name, lhs, rhs) = open_conversion_binders(Some(ctx), p1, b1, p2, b2);
3056                let ext = ctx.extend(&name, (**t1).clone());
3057                is_subtype_normalized(&ext, &lhs, &rhs)
3058            }
3059        }
3060
3061        // Everything else is invariant: definitional equality.
3062        _ => def_eq_normalized(ctx, a, b),
3063    }
3064}
3065
3066#[cfg(test)]
3067thread_local! {
3068    static CONVERSION_FULL_NORMALIZATIONS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3069    static CONVERSION_PROOF_TYPE_PROBES: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };
3070}
3071
3072/// Every full-normalization fallback this process has entered, on any thread. The per-thread
3073/// count cannot see a Lean import: the importer and the kernel's sized stacks run on threads of
3074/// their own. A control that reads this runs its import alone, in a child process.
3075#[cfg(test)]
3076static PROCESS_FULL_NORMALIZATIONS: std::sync::atomic::AtomicUsize =
3077    std::sync::atomic::AtomicUsize::new(0);
3078
3079/// Definitional equality (symmetric): reduction, congruence, η, and proof irrelevance. This
3080/// is the conversion used in INVARIANT positions (function arguments, `Lambda`/`Match`/`Fix`
3081/// subterms). `is_subtype` layers cumulativity on top of it.
3082pub(crate) fn def_eq(ctx: &Context, a: &Term, b: &Term) -> bool {
3083    if let Some(r) = crate::annotation::erased_pair(a, b, |a, b| def_eq(ctx, a, b)) {
3084        return r;
3085    }
3086    within_conversion_rungs(|| {
3087        crate::conversion_session::convert(ctx, a, b, || def_eq_uncached(ctx, a, b))
3088    })
3089}
3090
3091thread_local! {
3092    /// The conversions nested inside one another on this thread, one rung of stack each.
3093    static CONVERSION_NESTING: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3094}
3095
3096/// The conversions enclosing the current one.
3097pub(crate) fn conversion_nesting() -> usize {
3098    CONVERSION_NESTING.with(|n| n.get())
3099}
3100
3101/// One nesting of conversion, returned even when the conversion unwinds.
3102struct ConversionRung(usize);
3103
3104impl Drop for ConversionRung {
3105    fn drop(&mut self) {
3106        CONVERSION_NESTING.with(|n| n.set(self.0));
3107    }
3108}
3109
3110/// Run one conversion nested in its callers. Conversions recurse through their arguments and
3111/// through the reducts their probes expose, so their nesting is bounded by neither input's depth:
3112/// comparing `Nat.below m n` against `Nat.below m k` for two large literals descends once per
3113/// `Succ`. Each nesting takes one rung of this thread's stack (the kernel's own unit,
3114/// `term_store::BYTES_PER_RUNG`). When the rungs run out the conversion continues on a stack twice
3115/// the size, as the normalizer grows its own, carrying the count along; past the kernel's
3116/// term-depth door (`MAX_TERM_DEPTH` nestings) it stops as a recorded resource stop — "not
3117/// shown equal", which `exact` reports as a `ResourceLimit` decline — never a crash.
3118pub(crate) fn within_conversion_rungs(f: impl FnOnce() -> bool + Send) -> bool {
3119    let taken = conversion_nesting();
3120    if taken >= MAX_TERM_DEPTH {
3121        crate::reduction::record_resource_stop(crate::Unreduced::TooDeep);
3122        return false;
3123    }
3124    let rungs = crate::term_store::kernel_stack_rungs();
3125    if taken + 1 >= rungs && rungs < MAX_TERM_DEPTH {
3126        return crate::term_store::grow_stack_for_depth(
3127            (rungs * 2).min(MAX_TERM_DEPTH),
3128            move || {
3129                CONVERSION_NESTING.with(|n| n.set(taken));
3130                within_conversion_rungs(f)
3131            },
3132        );
3133    }
3134    let _rung = ConversionRung(taken);
3135    CONVERSION_NESTING.with(|n| n.set(taken + 1));
3136    f()
3137}
3138
3139fn def_eq_uncached(ctx: &Context, a: &Term, b: &Term) -> bool {
3140    if alpha_eq(a, b) {
3141        return true;
3142    }
3143    if enter_kernel(a, "def_eq").is_err() || enter_kernel(b, "def_eq").is_err() {
3144        return false;
3145    }
3146    // Matching binder heads can compare domains and capture-safely opened
3147    // bodies directly. Do this before allocating stores for every telescope
3148    // suffix; it is the same positive-only congruence rule used below.
3149    let matching_binders = matches!(
3150        (a, b),
3151        (Term::Pi { .. }, Term::Pi { .. }) | (Term::Lambda { .. }, Term::Lambda { .. })
3152    );
3153    if matching_binders && conversion_by_congruence(ctx, a, b) {
3154        return true;
3155    }
3156    if let Some(equal) = rigid_conversion(ctx, a, b) {
3157        return equal;
3158    }
3159    if let Some(equal) = crate::reduction::natural_literal_conversion(ctx, a, b, 1 << 18) {
3160        return equal;
3161    }
3162    if crate::reduction::constructor_equivalent(ctx, a, b, 1 << 26) {
3163        return true;
3164    }
3165    if crate::term_store::beta_zeta_equivalent(ctx, a, b, 1 << 16) {
3166        return true;
3167    }
3168    if crate::term_store::beta_delta_equivalent(ctx, a, b, 1 << 16) {
3169        return true;
3170    }
3171    if !matching_binders && conversion_by_congruence(ctx, a, b) {
3172        return true;
3173    }
3174    // A bounded common reduct can settle open recursor-iota comparisons without
3175    // recursively typing both endpoints merely to rule out proof irrelevance.
3176    // Keep the result: the same probe must not run again after an inconclusive
3177    // attempt, and an ineligible pair must retain the head fallback's old gate.
3178    let bounded_head = bounded_head_conversion(ctx, a, b);
3179    if bounded_head == Some(true) {
3180        return true;
3181    }
3182    // Lean's `is_def_eq_proof_irrel`: two proofs are equal exactly when their propositions are —
3183    // by irrelevance when the propositions convert, and never when they differ, since convertible
3184    // terms have convertible types. Neither proof is ever unfolded.
3185    if let Some(equal) = proof_irrelevance(ctx, a, b) {
3186        return equal;
3187    }
3188    if bounded_head == Some(false) && conversion_by_exposed_heads(ctx, a, b) {
3189        return true;
3190    }
3191    // Closed data whose weak-head values differ at a constructor is refuted as Lean refutes it,
3192    // never by normalizing both sides (LG; `constructor_refutation_controls`).
3193    if crate::reduction::constructors_disagree(ctx, a, b, 1 << 26) {
3194        return false;
3195    }
3196    // LAZY δ (Lean's `lazy_delta_reduction`, LG): weak-head reduce, compare heads, and unfold one
3197    // side at a time by definitional height, theorems last. Undecided pairs fall to the
3198    // normalization below, unchanged.
3199    if let Some(answer) = lazy_delta::lazy_delta_after_the_probes(ctx, a, b) {
3200        #[cfg(debug_assertions)]
3201        lazy_delta::differential(ctx, a, b, answer);
3202        return answer;
3203    }
3204    // LAZY THEOREM DELTA (Lean's `lazy_delta_reduction`: a theorem has the lowest unfolding
3205    // priority). Checked theorems are published unfoldably, as Lean publishes them, but a
3206    // conversion almost never needs to look inside one — proofs are compared by irrelevance —
3207    // and unfolding every theorem inside every proof argument makes normalization explode.
3208    // So normalize first with theorems FOLDED and compare; unfold them only if that fails,
3209    // continuing from the folded normal forms. Sound by construction: the folded forms are
3210    // reducts of the originals (a subset of the same reductions), so an equality found there
3211    // is an equality of the originals, and fully normalizing a reduct reaches the same normal
3212    // form as normalizing the original — no work is repeated and no equality is invented.
3213    #[cfg(test)]
3214    {
3215        CONVERSION_FULL_NORMALIZATIONS.with(|count| count.set(count.get() + 1));
3216        PROCESS_FULL_NORMALIZATIONS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3217    }
3218    let folded = |name: &str| is_transparent_theorem(ctx, name);
3219    let a_folded =
3220        crate::reduction::normalize_at(ctx, a, crate::reduction::Transparency::Excluding(&folded));
3221    let b_folded =
3222        crate::reduction::normalize_at(ctx, b, crate::reduction::Transparency::Excluding(&folded));
3223    if def_eq_normalized(ctx, &a_folded, &b_folded) {
3224        return true;
3225    }
3226    let a_norm = normalize(ctx, &a_folded);
3227    let b_norm = normalize(ctx, &b_folded);
3228    def_eq_normalized(ctx, &a_norm, &b_norm)
3229}
3230
3231/// Whether `name` is a checked theorem published with its proof as a transparent body.
3232pub(crate) fn is_transparent_theorem(ctx: &Context, name: &str) -> bool {
3233    ctx.checked_opaque_dependencies(name).is_some() && ctx.get_definition_body(name).is_some()
3234}
3235
3236// Transparent aliases can conceal a common inductive head. Expose that head
3237// before normalizing its arguments, so invariant fields use ordinary conversion
3238// (including the shared computation path) rather than eager tree evaluation.
3239fn conversion_by_unfolded_head(ctx: &Context, a: &Term, b: &Term) -> bool {
3240    match bounded_head_conversion(ctx, a, b) {
3241        Some(true) => true,
3242        Some(false) => conversion_by_exposed_heads(ctx, a, b),
3243        None => false,
3244    }
3245}
3246
3247// None preserves the existing hole/rewrite admission gate. Some(false) means
3248// only that the single bounded attempt was inconclusive, never inequality.
3249fn bounded_head_conversion(ctx: &Context, a: &Term, b: &Term) -> Option<bool> {
3250    // This positive-only gateway must not certify an erased Hole or run
3251    // outside the head probe's rewrite policy. Literal identity is unchanged.
3252    if !ctx.simp_rules().is_empty() || mentions_hole(a) || mentions_hole(b) {
3253        return None;
3254    }
3255    // A beta application or a closed wrapper can hide the common function.
3256    // Compare after each bounded step before unfolding that common function:
3257    // eager head exposure can otherwise expand all of its shared arguments.
3258    let mut budget = 256;
3259    Some(bounded_conversion(ctx, a, b, &mut budget))
3260}
3261
3262// Call only after an eligible, inconclusive bounded_head_conversion. This
3263// broader fallback may recursively invoke full conversion through rigid heads;
3264// def_eq therefore keeps it after proof irrelevance, unlike the bounded probe.
3265fn conversion_by_exposed_heads(ctx: &Context, a: &Term, b: &Term) -> bool {
3266    let Some(lhs) = crate::reduction::bounded_conversion_head(ctx, a) else {
3267        return false;
3268    };
3269    let Some(rhs) = crate::reduction::bounded_conversion_head(ctx, b) else {
3270        return false;
3271    };
3272    if alpha_eq(a, &lhs) && alpha_eq(b, &rhs) {
3273        return false;
3274    }
3275    alpha_eq(&lhs, &rhs)
3276        || rigid_conversion(ctx, &lhs, &rhs) == Some(true)
3277        || conversion_by_congruence(ctx, &lhs, &rhs)
3278}
3279
3280/// Binder congruence can establish equality without evaluating annotations.
3281/// Failure is inconclusive: eta, proof irrelevance and reduction may still
3282/// equate the terms. Arbitrary function arguments are deliberately left lazy;
3283/// a function may discard an argument whose evaluation is very expensive.
3284fn conversion_by_congruence(ctx: &Context, a: &Term, b: &Term) -> bool {
3285    let binders = match (a, b) {
3286        (
3287            Term::Lambda {
3288                param: p,
3289                param_type: pt,
3290                body: pb,
3291            },
3292            Term::Lambda {
3293                param: q,
3294                param_type: qt,
3295                body: qb,
3296            },
3297        )
3298        | (
3299            Term::Pi {
3300                param: p,
3301                param_type: pt,
3302                body_type: pb,
3303            },
3304            Term::Pi {
3305                param: q,
3306                param_type: qt,
3307                body_type: qb,
3308            },
3309        ) => Some((p, pt, pb, q, qt, qb)),
3310        _ => None,
3311    };
3312    if let Some((p, pt, pb, q, qt, qb)) = binders {
3313        if !def_eq(ctx, pt, qt) {
3314            return false;
3315        }
3316        let name = fresh_context_name(ctx, "__conversion", &[pb, qb, pt, qt]);
3317        let variable = Term::Var(name.clone());
3318        let lhs = substitute(pb, p, &variable);
3319        let rhs = substitute(qb, q, &variable);
3320        return def_eq(&ctx.extend(&name, (**pt).clone()), &lhs, &rhs);
3321    }
3322    // Congruence over a defined function is only an opportunistic proof:
3323    // its arguments may be discarded after unfolding the head. Never invoke
3324    // unrestricted conversion on those arguments before reducing the function.
3325    let (ah, aa) = spine_of(a);
3326    let (bh, ba) = spine_of(b);
3327    if !aa.is_empty() && aa.len() == ba.len() && alpha_eq(ah, bh) {
3328        let mut budget = 256;
3329        return aa
3330            .iter()
3331            .zip(ba)
3332            .all(|(x, y)| bounded_conversion(ctx, x, y, &mut budget));
3333    }
3334    false
3335}
3336
3337/// Predict only a fixed global head after syntactic beta/zeta prefixes. This is
3338/// a scheduling hint, never conversion evidence: substitution cannot alter a
3339/// Global/Const, whereas a variable head is deliberately inconclusive. Every
3340/// inspected node uses the caller's existing conversion fuel.
3341#[cfg(test)]
3342fn delta_exposes_head(candidate: &Term, other: &Term, budget: &mut usize) -> bool {
3343    delta_exposes_head_through(None, candidate, other, budget)
3344}
3345
3346fn delta_exposes_head_through<'a>(
3347    ctx: Option<&'a Context>,
3348    candidate: &'a Term,
3349    other: &Term,
3350    budget: &mut usize,
3351) -> bool {
3352    let mut target = other;
3353    loop {
3354        if *budget == 0 {
3355            return false;
3356        }
3357        *budget -= 1;
3358        match target {
3359            Term::App(f, _) => target = f,
3360            Term::Global(_) | Term::Const { .. } => break,
3361            _ => return false,
3362        }
3363    }
3364    let mut term = candidate;
3365    let mut applied = 0usize;
3366    loop {
3367        if *budget == 0 {
3368            return false;
3369        }
3370        *budget -= 1;
3371        match term {
3372            Term::App(f, _) => {
3373                applied += 1;
3374                term = f;
3375            }
3376            Term::Lambda { body, .. } if applied > 0 => {
3377                applied -= 1;
3378                term = body;
3379            }
3380            Term::Let { body, .. } => term = body,
3381            Term::Global(name) => {
3382                if alpha_eq(term, target) {
3383                    return true;
3384                }
3385                // Follow only the same borrowed monomorphic body lookup used by
3386                // bounded delta. Pending/opaque names have no visible body.
3387                // No substitution is needed to predict a fixed global head;
3388                // the actual conversion still validates every unfolding.
3389                let Some(body) = ctx.and_then(|ctx| ctx.get_definition_body(name)) else {
3390                    return false;
3391                };
3392                term = body;
3393            }
3394            // Polymorphic delta requires universe instantiation; leave it to
3395            // the existing reducer instead of guessing a substituted head.
3396            Term::Const { .. } => return alpha_eq(term, target),
3397            _ => return false,
3398        }
3399    }
3400}
3401
3402/// Compare closed helper bodies before specializing their arguments. This is
3403/// only a positive identity check, with the same admission as bounded delta.
3404/// Kernel conversion uses full transparency; pending/opaque bodies are hidden
3405/// by get_definition_body. Explicit universe constants keep the resolver path.
3406fn bounded_closed_head_identity(ctx: &Context, a: &Term, b: &Term, budget: &mut usize) -> bool {
3407    if !matches!(
3408        (a, b),
3409        (Term::Global(_), Term::Global(_) | Term::Lambda { .. })
3410            | (Term::Lambda { .. }, Term::Global(_))
3411    ) {
3412        return false;
3413    }
3414    fn observe<'a>(ctx: &'a Context, term: &'a Term, budget: &mut usize) -> Option<&'a Term> {
3415        let body = match term {
3416            Term::Global(name) => ctx.get_definition_body(name)?,
3417            Term::Lambda { .. } => term,
3418            _ => return None,
3419        };
3420        if *budget == 0 {
3421            return None;
3422        }
3423        *budget -= 1;
3424        crate::reduction::bounded_closed_conversion_size(body)?;
3425        Some(body)
3426    }
3427    let Some(a) = observe(ctx, a, budget) else {
3428        return false;
3429    };
3430    let Some(b) = observe(ctx, b, budget) else {
3431        return false;
3432    };
3433    // alpha_eq preserves the kernel's binder, universe and literal semantics.
3434    // Its bounded body traversal may freshen binders; it is not allocation-free.
3435    alpha_eq(a, b)
3436}
3437
3438struct BorrowedCongruence {
3439    equal: bool,
3440    fixed_heads: (bool, bool),
3441}
3442
3443/// Borrowed congruence leaves common heads folded. A failed argument comparison
3444/// is inconclusive: the caller may still prove equality by erasing it in beta/delta.
3445#[cfg(test)]
3446thread_local! {
3447    static BORROWED_STRUCTURAL_VISITS: std::cell::Cell<Option<usize>> =
3448        const {std::cell::Cell::new(None)};
3449}
3450
3451fn bounded_structural_congruence(
3452    ctx: &Context,
3453    a: &Term,
3454    b: &Term,
3455    budget: &mut usize,
3456) -> BorrowedCongruence {
3457    #[cfg(test)]
3458    BORROWED_STRUCTURAL_VISITS.with(|count| {
3459        if let Some(n) = count.get() {
3460            count.set(Some(n + 1));
3461        }
3462    });
3463    // Preserve only observations already made by this structural probe. A
3464    // Global/Const-rooted App spine is inert under beta/iota/zeta, even when
3465    // this comparison fails; it may still require delta and argument checking.
3466    let fixed = |head: &Term| matches!(head, Term::Global(_) | Term::Const { .. });
3467    let mut fixed_heads = (fixed(a), fixed(b));
3468    let equal = match (a, b) {
3469        (Term::App(..), Term::App(..)) => {
3470            let (ah, aa) = spine_of(a);
3471            let (bh, ba) = spine_of(b);
3472            fixed_heads = (fixed(ah), fixed(bh));
3473            aa.len() == ba.len()
3474                && (alpha_eq(ah, bh) || bounded_closed_head_identity(ctx, ah, bh, budget))
3475                && aa
3476                    .iter()
3477                    .zip(ba)
3478                    .all(|(x, y)| bounded_conversion(ctx, x, y, budget))
3479        }
3480        (
3481            Term::Lambda {
3482                param: p,
3483                param_type: pt,
3484                body: pb,
3485            },
3486            Term::Lambda {
3487                param: q,
3488                param_type: qt,
3489                body: qb,
3490            },
3491        )
3492        | (
3493            Term::Pi {
3494                param: p,
3495                param_type: pt,
3496                body_type: pb,
3497            },
3498            Term::Pi {
3499                param: q,
3500                param_type: qt,
3501                body_type: qb,
3502            },
3503        ) => {
3504            if bounded_conversion(ctx, pt, qt, budget) {
3505                let (name, lhs, rhs) = open_conversion_binders(Some(ctx), p, pb, q, qb);
3506                bounded_conversion(&ctx.extend(&name, (**pt).clone()), &lhs, &rhs, budget)
3507            } else {
3508                false
3509            }
3510        }
3511        _ => bounded_closed_head_identity(ctx, a, b, budget),
3512    };
3513    BorrowedCongruence { equal, fixed_heads }
3514}
3515
3516/// Positive-only congruence using bounded beta/iota/zeta and closed head delta.
3517/// Exhaustion or an unsupported rule is inconclusive. Prefer exposing a common
3518/// fixed head; otherwise expose the smaller definition before a costly body.
3519pub(crate) fn bounded_conversion(ctx: &Context, a: &Term, b: &Term, budget: &mut usize) -> bool {
3520    if *budget == 0 {
3521        return false;
3522    }
3523    *budget -= 1;
3524    if alpha_eq(a, b) {
3525        return true;
3526    }
3527    let observed = bounded_structural_congruence(ctx, a, b, budget);
3528    if observed.equal {
3529        return true;
3530    }
3531    // The fixedness observation comes from the spine already visited above.
3532    // Retain the same whole-input admission before avoiding the reducer's
3533    // provably unchanged copy/traversal. This is not evidence of equality.
3534    fn expose<'a>(
3535        ctx: &Context,
3536        term: &'a Term,
3537        fixed: bool,
3538        budget: &mut usize,
3539    ) -> Option<std::borrow::Cow<'a, Term>> {
3540        if fixed {
3541            crate::reduction::bounded_conversion_size(term)?;
3542            Some(std::borrow::Cow::Borrowed(term))
3543        } else {
3544            crate::reduction::beta_iota_zeta_head(ctx, term, budget).map(std::borrow::Cow::Owned)
3545        }
3546    }
3547    let Some(a) = expose(ctx, a, observed.fixed_heads.0, budget) else {
3548        return false;
3549    };
3550    let Some(b) = expose(ctx, b, observed.fixed_heads.1, budget) else {
3551        return false;
3552    };
3553    // Two borrowed exposures preserve both terms. Repeating the failed
3554    // structural probe would revisit the same obligations with less fuel.
3555    // Either newly reduced term still needs fresh equality/congruence checks.
3556    if !matches!(
3557        (&a, &b),
3558        (std::borrow::Cow::Borrowed(_), std::borrow::Cow::Borrowed(_))
3559    ) {
3560        if alpha_eq(&a, &b) {
3561            return true;
3562        }
3563        if bounded_structural_congruence(ctx, &a, &b, budget).equal {
3564            return true;
3565        }
3566    }
3567    if *budget == 0 {
3568        return false;
3569    }
3570    match (
3571        crate::reduction::bounded_delta_head(ctx, &a),
3572        crate::reduction::bounded_delta_head(ctx, &b),
3573    ) {
3574        (Some((ac, ua)), Some((bc, ub))) => {
3575            // Inspect only the candidate deferred by the size heuristic, without
3576            // substituting or evaluating either definition speculatively. The
3577            // recursive conversion still checks every resulting obligation.
3578            if ac <= bc {
3579                if delta_exposes_head_through(Some(ctx), &ub, &a, budget) {
3580                    bounded_conversion(ctx, &a, &ub, budget)
3581                } else {
3582                    bounded_conversion(ctx, &ua, &b, budget)
3583                }
3584            } else if delta_exposes_head_through(Some(ctx), &ua, &b, budget) {
3585                bounded_conversion(ctx, &ua, &b, budget)
3586            } else {
3587                bounded_conversion(ctx, &a, &ub, budget)
3588            }
3589        }
3590        (Some((_, unfolded)), None) => bounded_conversion(ctx, &unfolded, &b, budget),
3591        (None, Some((_, unfolded))) => bounded_conversion(ctx, &a, &unfolded, budget),
3592        (None, None) => false,
3593    }
3594}
3595
3596/// Injective inductive heads and data constructors need only compare arguments.
3597/// Trying shallow arguments first can refute a pair without evaluating its other
3598/// field. Proof constructors are handled by proof irrelevance before this rule.
3599fn rigid_conversion(ctx: &Context, a: &Term, b: &Term) -> Option<bool> {
3600    let (ah, aa) = spine_of(a);
3601    let (bh, ba) = spine_of(b);
3602    if aa.is_empty() || aa.len() != ba.len() || !alpha_eq(ah, bh) {
3603        return None;
3604    }
3605    let name = match ah {
3606        Term::Global(n) | Term::Const { name: n, .. } => n,
3607        _ => return None,
3608    };
3609    if !ctx.is_inductive(name) && !ctx.is_constructor(name) {
3610        return None;
3611    }
3612    if ctx.is_constructor(name) && proof_irrelevant(ctx, a, b) {
3613        return Some(true);
3614    }
3615    let mut order: Vec<usize> = (0..aa.len()).collect();
3616    order.sort_by_key(|&i| {
3617        crate::term_store::term_depth(aa[i]) + crate::term_store::term_depth(ba[i])
3618    });
3619    Some(order.into_iter().all(|i| def_eq(ctx, aa[i], ba[i])))
3620}
3621
3622/// Decompose a term into its head and argument spine (`f a b c` → `(f, [a,b,c])`).
3623fn spine_of(t: &Term) -> (&Term, Vec<&Term>) {
3624    let mut args = Vec::new();
3625    let mut head = t;
3626    while let Term::App(f, a) = head {
3627        args.push(a.as_ref());
3628        head = f;
3629    }
3630    args.reverse();
3631    (head, args)
3632}
3633
3634/// Structure η in ONE direction: if `mk_term` is a fully-applied constructor of a
3635/// registered structure `S` (`S_mk p̄ ā`) and `other` is not itself constructor-
3636/// headed, return `Some(eq)` where `eq` decides `mk_term ≡ other` by comparing each
3637/// field `aᵢ` against `S_projᵢ p̄ other`. `None` when the shape does not apply, so the
3638/// caller falls through to ordinary congruence.
3639fn try_structure_eta(ctx: &Context, mk_term: &Term, other: &Term) -> Option<bool> {
3640    let (head, args) = spine_of(mk_term);
3641    let (hname, levels) = match head {
3642        Term::Global(n) => (n, None),
3643        Term::Const { name, levels } => (name, Some(levels)),
3644        _ => return None,
3645    };
3646    let (_sname, info) = ctx.struct_of_constructor(hname)?;
3647    let nfields = info.projections.len();
3648    // Must be fully applied: params + one argument per field.
3649    if args.len() != info.num_params + nfields {
3650        return None;
3651    }
3652    // Do not eta when `other` is ALSO this constructor — that is ordinary
3653    // congruence (and avoids a pointless expansion loop).
3654    let (ohead, _) = spine_of(other);
3655    if matches!(ohead, Term::Global(n) | Term::Const {name:n, ..} if n == hname) {
3656        return None;
3657    }
3658    let params = &args[..info.num_params];
3659    let field_args = &args[info.num_params..];
3660    // Each field argument must equal the projection of `other`.
3661    Some(info.projections.iter().enumerate().all(|(i, proj)| {
3662        let mut proj_applied = match levels {
3663            Some(levels) => Term::Const {
3664                name: proj.clone(),
3665                levels: levels.clone(),
3666            },
3667            None => Term::Global(proj.clone()),
3668        };
3669        for p in params {
3670            proj_applied = Term::App(Box::new(proj_applied), Box::new((*p).clone()));
3671        }
3672        proj_applied = Term::App(Box::new(proj_applied), Box::new(other.clone()));
3673        def_eq(ctx, field_args[i], &proj_applied)
3674    }))
3675}
3676
3677/// `n a₁ … aₖ ≡ n.{ℓ̄} b₁ … bₖ` for a bare reference `n` whose declaration carries a level
3678/// telescope: exactly when the levels the application rule solves for the bare spine are
3679/// equivalent, position by position, to `ℓ̄`, and `aᵢ ≡ bᵢ`. A level the spine does not determine
3680/// leaves the bare reference unsolved, and then nothing is concluded — the conservative direction.
3681/// A DIFFERENT explicit level never converts: `Eq.{u+2} X` is well formed by cumulativity, but it
3682/// is not the constant `refl.{u+1} X x` proves an instance of. With no arguments the bare
3683/// reference stands at its declaration's own levels (`term`'s rule 4), so `n ≡ n.{ℓ̄}` exactly
3684/// when `ℓ̄` is that telescope; an application's head never reaches this case, because
3685/// congruence does not compare a bare head with an explicit one ([`bare_against_explicit`]).
3686fn implicit_instance_conversion(ctx: &Context, a: &Term, b: &Term) -> bool {
3687    if !bare_against_explicit(a, b) {
3688        return false;
3689    }
3690    let (ah, aa) = spine_of(a);
3691    let (bh, ba) = spine_of(b);
3692    if aa.len() != ba.len() {
3693        return false;
3694    }
3695    let (name, levels, bare_args) = match (ah, bh) {
3696        (Term::Global(n), Term::Const { name, levels }) if n == name => (name, levels, &aa),
3697        (Term::Const { name, levels }, Term::Global(n)) if n == name => (name, levels, &ba),
3698        _ => return false,
3699    };
3700    if bare_args.is_empty() {
3701        return lookup_const(ctx, name).is_some_and(|(declared, const_type)| {
3702            let own = crate::term::level_telescope(declared.as_deref(), &const_type);
3703            own.len() == levels.len()
3704                && own
3705                    .iter()
3706                    .zip(levels)
3707                    .all(|(p, l)| l.equiv(&Universe::Var(p.clone())))
3708        });
3709    }
3710    implicit_instance_levels(ctx, name, bare_args).is_some_and(|solved| {
3711        solved.len() == levels.len() && solved.iter().zip(levels).all(|(x, y)| x.equiv(y))
3712    }) && aa.iter().zip(ba.iter()).all(|(x, y)| def_eq(ctx, x, y))
3713}
3714
3715/// Whether the spines of `a` and `b` are headed by the same name, bare in one and explicit in the
3716/// other — allocation-free, since conversion asks it of every pair it reaches. Such a pair converts
3717/// only by [`implicit_instance_conversion`], which reads the bare head's levels from its arguments.
3718fn bare_against_explicit(a: &Term, b: &Term) -> bool {
3719    fn head(t: &Term) -> &Term {
3720        let mut h = t;
3721        while let Term::App(f, _) = h {
3722            h = f;
3723        }
3724        h
3725    }
3726    matches!(
3727        (head(a), head(b)),
3728        (Term::Global(n), Term::Const { name, .. }) | (Term::Const { name, .. }, Term::Global(n))
3729            if n == name
3730    )
3731}
3732
3733/// The levels the application rule solves for the bare spine `name args`, in the positional
3734/// order a `Term::Const` reference to `name` zips them in (`term::resolve_const_levels`). `None`
3735/// when `name` has no telescope or some level stays unsolved.
3736///
3737/// The spine is walked with the application rule's own steps — the head's type exposed by
3738/// `demanded_type_head`, its levels turned into metavariables by `implicit_levels_for_head`, each
3739/// argument's solution decided by `domain_level_solution` — so the instance read here is the one
3740/// the typing of the same spine used, and the two cannot drift apart.
3741fn implicit_instance_levels(ctx: &Context, name: &str, args: &[&Term]) -> Option<Vec<Universe>> {
3742    let (declared, const_type) = lookup_const(ctx, name)?;
3743    let positional = crate::term::level_telescope(declared.as_deref(), &const_type);
3744    let head = Term::Global(name.to_string());
3745    let mut current = infer_type(ctx, &head).ok()?;
3746    let mut solution = std::collections::HashMap::new();
3747    for (i, arg) in args.iter().enumerate() {
3748        let exposed = demanded_type_head(ctx, current, TypeHead::Function);
3749        let exposed = if i == 0 {
3750            implicit_levels_for_head(&head, exposed)
3751        } else {
3752            exposed
3753        };
3754        let Term::Pi {
3755            param,
3756            param_type,
3757            body_type,
3758        } = exposed
3759        else {
3760            return None;
3761        };
3762        let body_type = match domain_level_solution(ctx, &param_type, arg) {
3763            Some(subst) => {
3764                let body_type = crate::term::instantiate_universes(&body_type, &subst);
3765                solution.extend(subst);
3766                body_type
3767            }
3768            None => *body_type,
3769        };
3770        current = substitute(&body_type, &param, arg);
3771    }
3772    let metas = crate::term::fresh_level_metas(name, &positional);
3773    positional
3774        .iter()
3775        .map(|p| {
3776            let solved = metas.get(p)?.substitute(&solution);
3777            (!crate::term::universe_mentions(&solved, &crate::term::is_level_meta))
3778                .then_some(solved)
3779        })
3780        .collect()
3781}
3782
3783/// True if `t` is the head of a `Nat` Peano value — `Zero` or `Succ _` — the shape a
3784/// `Nat` literal bridges against (K6).
3785fn is_nat_peano_headed(t: &Term) -> bool {
3786    match t {
3787        Term::Global(n) => n == "Zero",
3788        Term::App(f, _) => matches!(f.as_ref(), Term::Global(n) if n == "Succ"),
3789        _ => false,
3790    }
3791}
3792
3793/// One Peano-unfolding step of a `Nat` literal: `Nat(0) → Zero`, `Nat(n) → Succ (Nat(n-1))`.
3794fn nat_peano_step(t: &Term) -> Term {
3795    match t {
3796        // `n ≤ 0` collapses to `Zero`, so peeling always TERMINATES even on a malformed
3797        // negative literal (a well-formed Nat is non-negative).
3798        Term::Lit(Literal::Nat(n)) if *n <= logicaffeine_base::BigInt::from_i64(0) => {
3799            Term::Global("Zero".to_string())
3800        }
3801        Term::Lit(Literal::Nat(n)) => Term::App(
3802            Box::new(Term::Global("Succ".to_string())),
3803            Box::new(Term::Lit(Literal::Nat(
3804                n.sub(&logicaffeine_base::BigInt::from_i64(1)),
3805            ))),
3806        ),
3807        other => other.clone(),
3808    }
3809}
3810
3811/// Compare a compact natural with a Peano spine without expanding the literal.
3812/// A mixed spine may end in another literal or an open neutral term.
3813/// The Peano bridge's answer for the literal `number` against the `Zero`/`Succ`-headed `other`,
3814/// where the literal readings it relies on hold (`int_inductive::reads_nat_literal`): all of them
3815/// while `Zero` and `Succ` are `Nat`'s constructors, and `0 ≡ Zero` alone while only `Zero` is.
3816fn nat_bridge(ctx: &Context, number: &logicaffeine_base::BigInt, other: &Term) -> Option<bool> {
3817    let numerals = ctx.canonical_numerals();
3818    if numerals.succ {
3819        return Some(nat_peano_equal(ctx, number, other));
3820    }
3821    (numerals.zero
3822        && *number <= logicaffeine_base::BigInt::from_i64(0)
3823        && matches!(other, Term::Global(zero) if zero == "Zero"))
3824    .then_some(true)
3825}
3826
3827fn nat_peano_equal(ctx: &Context, number: &logicaffeine_base::BigInt, mut term: &Term) -> bool {
3828    let zero = logicaffeine_base::BigInt::from_i64(0);
3829    let one = logicaffeine_base::BigInt::from_i64(1);
3830    let mut remaining = number.clone();
3831    loop {
3832        match term {
3833            Term::Global(name) if name == "Zero" => return remaining == zero,
3834            Term::Lit(Literal::Nat(other)) => return remaining == *other,
3835            Term::App(head, predecessor) if matches!(head.as_ref(), Term::Global(name) if name == "Succ") =>
3836            {
3837                if remaining <= zero {
3838                    return false;
3839                }
3840                remaining = remaining.sub(&one);
3841                term = predecessor;
3842            }
3843            _ => {
3844                return def_eq_normalized(ctx, &Term::Lit(Literal::Nat(remaining)), term);
3845            }
3846        }
3847    }
3848}
3849
3850/// Definitional equality on already-normalized terms.
3851fn def_eq_normalized(ctx: &Context, a: &Term, b: &Term) -> bool {
3852    if alpha_eq(a, b) {
3853        return true;
3854    }
3855
3856    // Literal Int values are the two ordinary constructor forms, not a second carrier.
3857    if let Some(a_ctor) = crate::int_inductive::literal_constructor(ctx, a) {
3858        let b_ctor = crate::int_inductive::literal_constructor(ctx, b);
3859        return def_eq_normalized(ctx, &a_ctor, b_ctor.as_ref().unwrap_or(b));
3860    }
3861    if let Some(b_ctor) = crate::int_inductive::literal_constructor(ctx, b) {
3862        return def_eq_normalized(ctx, a, &b_ctor);
3863    }
3864
3865    // ζ ON DEMAND. `reduction`'s ζ rule now KEEPS a `Let` whose variable occurs more than once
3866    // — the binding IS the sharing node, and writing the value out at every occurrence is the
3867    // quadratic blow-up it exists to avoid — so a `Let` survives into a normal form and
3868    // conversion has to be able to see through one. Without this step two convertible terms,
3869    // one of which kept its binding, compare UNEQUAL, and sharing would change what a type
3870    // MEANS, which is the one thing an optimisation may never do. Expanding is always sound:
3871    // `let x := v in b` and `b[x := v]` are the SAME term by ζ, in every calculus that has it.
3872    // Each expansion removes one binder from the head, so the recursion terminates.
3873    if let Some(expanded) = crate::term_store::zeta_expand_head_term(a) {
3874        return def_eq_normalized(ctx, &normalize(ctx, &expanded), b);
3875    }
3876    if let Some(expanded) = crate::term_store::zeta_expand_head_term(b) {
3877        return def_eq_normalized(ctx, a, &normalize(ctx, &expanded));
3878    }
3879
3880    // η-conversion: `f ≡ λx. f x`. When exactly one side is a λ, compare its body against
3881    // the other side applied to the bound variable, under the binder.
3882    if let Term::Lambda {
3883        param,
3884        param_type,
3885        body,
3886    } = a
3887    {
3888        if !matches!(b, Term::Lambda { .. }) {
3889            let name = fresh_conversion_name(Some(ctx), &[body, b, param_type]);
3890            let variable = Term::Var(name.clone());
3891            let body = substitute(body, param, &variable);
3892            let ext = ctx.extend(&name, (**param_type).clone());
3893            let bx = normalize(&ext, &Term::App(Box::new(b.clone()), Box::new(variable)));
3894            return def_eq_normalized(&ext, &body, &bx);
3895        }
3896    }
3897    if let Term::Lambda {
3898        param,
3899        param_type,
3900        body,
3901    } = b
3902    {
3903        if !matches!(a, Term::Lambda { .. }) {
3904            let name = fresh_conversion_name(Some(ctx), &[body, a, param_type]);
3905            let variable = Term::Var(name.clone());
3906            let body = substitute(body, param, &variable);
3907            let ext = ctx.extend(&name, (**param_type).clone());
3908            let ax = normalize(&ext, &Term::App(Box::new(a.clone()), Box::new(variable)));
3909            return def_eq_normalized(&ext, &ax, &body);
3910        }
3911    }
3912
3913    // Structure η: `⟨p.1, …, p.n⟩ ≡ p`. When one side is a fully-applied
3914    // constructor of a REGISTERED structure and the other is not constructor-
3915    // headed, compare each field argument against the matching projection of the
3916    // other side. Keyed on the structure registry, so it never fires for an
3917    // ordinary inductive.
3918    if let Some(eq) = try_structure_eta(ctx, a, b) {
3919        return eq;
3920    }
3921    if let Some(eq) = try_structure_eta(ctx, b, a) {
3922        return eq;
3923    }
3924
3925    // A bare reference is its own implicit instantiation: `Eq X x y` denotes `Eq.{ℓ} X x y` for
3926    // the ℓ the application rule solves from `X` (`implicit_levels_for_head`). `refl.{ℓ}`'s
3927    // instantiated type mentions the bare form, a statement may spell the explicit one, and
3928    // Lean's `@rfl.{ℓ} α a : @Eq.{ℓ} α a a` needs the two to meet.
3929    if implicit_instance_conversion(ctx, a, b) {
3930        return true;
3931    }
3932
3933    // Peano bridge (K6): a `Nat(n)` literal is definitionally `Succ^n Zero`. Two Nat
3934    // literals are equal iff their counts are; a Nat literal and a `Zero`/`Succ`-headed
3935    // Peano term are compared by peeling one `Succ` at a time (terminating at
3936    // `Nat(0) ≡ Zero`), as far as the readings it needs hold (`nat_bridge`).
3937    match (a, b) {
3938        (Term::Lit(Literal::Nat(x)), Term::Lit(Literal::Nat(y))) => return x == y,
3939        (Term::Lit(Literal::Nat(n)), _) if is_nat_peano_headed(b) => {
3940            if let Some(equal) = nat_bridge(ctx, n, b) {
3941                return equal;
3942            }
3943        }
3944        (_, Term::Lit(Literal::Nat(n))) if is_nat_peano_headed(a) => {
3945            if let Some(equal) = nat_bridge(ctx, n, a) {
3946                return equal;
3947            }
3948        }
3949        _ => {}
3950    }
3951
3952    let congruent = match (a, b) {
3953        (Term::Sort(u1), Term::Sort(u2)) => u1.equiv(u2),
3954        (
3955            Term::Pi {
3956                param: p1,
3957                param_type: t1,
3958                body_type: b1,
3959            },
3960            Term::Pi {
3961                param: p2,
3962                param_type: t2,
3963                body_type: b2,
3964            },
3965        ) => {
3966            def_eq_normalized(ctx, t1, t2) && {
3967                let (name, lhs, rhs) = open_conversion_binders(Some(ctx), p1, b1, p2, b2);
3968                let ext = ctx.extend(&name, (**t1).clone());
3969                def_eq_normalized(&ext, &lhs, &rhs)
3970            }
3971        }
3972        (
3973            Term::Lambda {
3974                param: p1,
3975                param_type: t1,
3976                body: b1,
3977            },
3978            Term::Lambda {
3979                param: p2,
3980                param_type: t2,
3981                body: b2,
3982            },
3983        ) => {
3984            def_eq_normalized(ctx, t1, t2) && {
3985                let (name, lhs, rhs) = open_conversion_binders(Some(ctx), p1, b1, p2, b2);
3986                let ext = ctx.extend(&name, (**t1).clone());
3987                def_eq_normalized(&ext, &lhs, &rhs)
3988            }
3989        }
3990        (Term::App(f1, a1), Term::App(f2, a2)) => {
3991            !bare_against_explicit(a, b)
3992                && def_eq_normalized(ctx, f1, f2)
3993                && def_eq_normalized(ctx, a1, a2)
3994        }
3995        (
3996            Term::Match {
3997                discriminant: d1,
3998                motive: m1,
3999                cases: c1,
4000            },
4001            Term::Match {
4002                discriminant: d2,
4003                motive: m2,
4004                cases: c2,
4005            },
4006        ) => {
4007            // A neutral match reduces only its discriminant. Its motive and
4008            // unselected branches remain unevaluated, so compare those through
4009            // full conversion rather than assuming they are normal forms.
4010            def_eq_normalized(ctx, d1, d2)
4011                && def_eq(ctx, m1, m2)
4012                && c1.len() == c2.len()
4013                && c1.iter().zip(c2.iter()).all(|(x, y)| def_eq(ctx, x, y))
4014        }
4015        (Term::Fix { name: n1, body: b1 }, Term::Fix { name: n2, body: b2 }) => {
4016            let (_, lhs, rhs) = open_conversion_binders(Some(ctx), n1, b1, n2, b2);
4017            // Applied fixpoints stay opaque when their structural argument is
4018            // neutral. Their bodies may therefore still contain redexes even
4019            // after the enclosing application has reached its normal form.
4020            def_eq(ctx, &lhs, &rhs)
4021        }
4022        _ => false,
4023    };
4024    if congruent {
4025        return true;
4026    }
4027
4028    // Unit eta also compares two neutral inhabitants, neither constructor-headed.
4029    // A known constructor of a nonunit family cannot use this rule; avoid
4030    // recursively typing expanded data merely to rediscover its family.
4031    if can_have_unit_type(ctx, a) && can_have_unit_type(ctx, b) {
4032        if let Ok(a_type) = infer_type(ctx, a) {
4033            let a_type = normalize(ctx, &a_type);
4034            let (head, _) = spine_of(&a_type);
4035            let name = match head {
4036                Term::Global(n) | Term::Const { name: n, .. } => Some(n),
4037                _ => None,
4038            };
4039            if name.is_some_and(|n| ctx.unit_constructor(n).is_some()) {
4040                if let Ok(b_type) = infer_type(ctx, b) {
4041                    if def_eq(ctx, &a_type, &b_type) {
4042                        return true;
4043                    }
4044                }
4045            }
4046        }
4047    }
4048
4049    // Proof irrelevance: any two proofs of the same proposition are equal. Fires only when
4050    // structural comparison fails (so it never costs on the common path).
4051    proof_irrelevant(ctx, a, b)
4052}
4053
4054// Read an exact monomorphic constructor family without typing its fields.
4055// Unknown and polymorphic references retain the ordinary conversion probes.
4056fn monomorphic_constructor_parent<'a>(ctx: &'a Context, term: &Term) -> Option<&'a str> {
4057    // Registered conversion rules can change the interpretation of a family.
4058    // Keep the original inference-based probes in every such context.
4059    if !ctx.simp_rules().is_empty() {
4060        return None;
4061    }
4062    let mut remaining = 256usize;
4063    let mut tick = || {
4064        remaining = remaining.checked_sub(1)?;
4065        Some(())
4066    };
4067    let mut head = term;
4068    let mut supplied = 0usize;
4069    while let Term::App(function, _) = head {
4070        tick()?;
4071        supplied += 1;
4072        head = function;
4073    }
4074    let Term::Global(name) = head else {
4075        return None;
4076    };
4077    let parent = ctx.constructor_inductive(name)?;
4078    if !ctx.is_inductive(parent)
4079        || ctx.is_inductive(name)
4080        || ctx.is_constructor(parent)
4081        || ctx.is_definition(name)
4082        || ctx.is_definition(parent)
4083        || ctx.poly_declaration(name).is_some()
4084        || ctx.poly_declaration(parent).is_some()
4085    {
4086        return None;
4087    }
4088    // The legacy raw constructor API records an owner independently of its
4089    // actual type. Require a saturated visible header with that rigid result;
4090    // otherwise a claimed data constructor can in fact be a proof or unit value.
4091    let mut result = ctx.get_global(name)?;
4092    let mut arity = 0usize;
4093    while let Term::Pi { body_type, .. } = result {
4094        tick()?;
4095        arity += 1;
4096        result = body_type;
4097    }
4098    if arity != supplied {
4099        return None;
4100    }
4101    let mut result_arguments = 0usize;
4102    while let Term::App(function, _) = result {
4103        tick()?;
4104        result_arguments += 1;
4105        result = function;
4106    }
4107    if !matches!(result, Term::Global(family) if family == parent) {
4108        return None;
4109    }
4110    let mut family_type = ctx.get_global(parent)?;
4111    let mut family_arity = 0usize;
4112    while let Term::Pi { body_type, .. } = family_type {
4113        tick()?;
4114        family_arity += 1;
4115        family_type = body_type;
4116    }
4117    if family_arity != result_arguments || !matches!(family_type, Term::Sort(_)) {
4118        return None;
4119    }
4120    Some(parent)
4121}
4122
4123fn is_monomorphic_data_constructor(ctx: &Context, term: &Term) -> bool {
4124    let Some(parent) = monomorphic_constructor_parent(ctx, term) else {
4125        return false;
4126    };
4127    matches!(
4128        ctx.get_global(parent).and_then(result_sort_universe),
4129        Some(Universe::Type(_))
4130    )
4131}
4132
4133// Necessary result shape only: this cannot certify an application or equality.
4134// If this syntactic Fix application successfully infers, its structural result
4135// is the visible nullary data family below. No arguments or branches are typed.
4136fn fixed_applied_match_result_family<'a>(ctx: &Context, term: &'a Term) -> Option<&'a str> {
4137    if !ctx.simp_rules().is_empty() {
4138        return None;
4139    }
4140    let mut steps = 256usize;
4141    let mut tick = || {
4142        steps = steps.checked_sub(1)?;
4143        Some(())
4144    };
4145    let mut head = term;
4146    // Lambda wrappers turn this data result into Pi codomains. A fixed Type
4147    // codomain remains in Type, so the wrappers cannot turn it into a proof.
4148    while let Term::Lambda { body, .. } = head {
4149        tick()?;
4150        head = body;
4151    }
4152    let mut supplied = 0usize;
4153    while let Term::App(function, _) = head {
4154        tick()?;
4155        supplied += 1;
4156        head = function;
4157    }
4158    let Term::Fix { body, .. } = head else {
4159        return None;
4160    };
4161    let mut inner = body.as_ref();
4162    let mut binders = Vec::new();
4163    while let Term::Lambda {
4164        param,
4165        param_type,
4166        body,
4167    } = inner
4168    {
4169        tick()?;
4170        binders.push((param.as_str(), param_type.as_ref()));
4171        inner = body;
4172    }
4173    if supplied == 0 || supplied != binders.len() {
4174        return None;
4175    }
4176    let Term::Match {
4177        discriminant,
4178        motive,
4179        ..
4180    } = inner
4181    else {
4182        return None;
4183    };
4184    tick()?;
4185    // Restrict the first version to a directly bound, nullary inductive
4186    // discriminant. Its structural typing has no hidden index applications.
4187    let Term::Var(variable) = discriminant.as_ref() else {
4188        return None;
4189    };
4190    let mut found_domain = None;
4191    for (name, domain) in binders.iter().rev() {
4192        tick()?;
4193        if *name == variable {
4194            found_domain = Some(*domain);
4195            break;
4196        }
4197    }
4198    let domain = found_domain?;
4199    let Term::Global(domain_name) = domain else {
4200        return None;
4201    };
4202    let rigid_sort = |name: &str| {
4203        if !ctx.is_inductive(name)
4204            || ctx.is_definition(name)
4205            || ctx.is_constructor(name)
4206            || ctx.poly_declaration(name).is_some()
4207        {
4208            return None;
4209        }
4210        match ctx.get_global(name) {
4211            Some(Term::Sort(level)) => Some(level),
4212            _ => None,
4213        }
4214    };
4215    rigid_sort(domain_name)?;
4216    let result = match motive.as_ref() {
4217        Term::Lambda {
4218            param_type, body, ..
4219        } if matches!(param_type.as_ref(), Term::Global(name) if name == domain_name) => {
4220            tick()?;
4221            body.as_ref()
4222        }
4223        other => other,
4224    };
4225    let Term::Global(result_name) = result else {
4226        return None;
4227    };
4228    if !matches!(rigid_sort(result_name), Some(Universe::Type(_))) {
4229        return None;
4230    }
4231    Some(result_name.as_str())
4232}
4233
4234fn can_have_unit_type(ctx: &Context, term: &Term) -> bool {
4235    // Successful Lambda inference has a Pi type, never an inductive unit type.
4236    // Registered conversion rules retain the complete inference-based path.
4237    if ctx.simp_rules().is_empty() && matches!(term, Term::Lambda { .. }) {
4238        return false;
4239    }
4240    match monomorphic_constructor_parent(ctx, term)
4241        .or_else(|| fixed_applied_match_result_family(ctx, term))
4242    {
4243        Some(parent) => ctx.unit_constructor(parent).is_some(),
4244        None => true,
4245    }
4246}
4247
4248/// Proof irrelevance: `a ≡ b` when both are proofs of the same proposition — `a : A`, `b : B`,
4249/// `A ≡ B`, and that common type is a `Prop` (or the definitionally-irrelevant `SProp`). Sound
4250/// because `Prop` is a universe of proof-irrelevant propositions.
4251///
4252/// The rule is stated SYMMETRICALLY on purpose. `A ≡ B` makes `A` propositional exactly when
4253/// `B` is, so asking either side is the same question — but only if the kernel asks. Asking
4254/// only the LEFT makes the answer depend on which side of `def_eq` a term was written on
4255/// whenever one side's type infers and the other's does not, and `def_eq`'s own contract is
4256/// that it is symmetric. A conversion check that accepts a proof written one way and refuses
4257/// the identical proof written the other is a bug the call site cannot see.
4258fn proof_irrelevant(ctx: &Context, a: &Term, b: &Term) -> bool {
4259    proof_irrelevance(ctx, a, b) == Some(true)
4260}
4261
4262/// Proof irrelevance as Lean's `is_def_eq_proof_irrel` decides it: `None` when neither term is a
4263/// proof (or a type does not infer), else whether the two propositions convert — two proofs of one
4264/// proposition are equal, and a proof is never equal to a term of a different type.
4265fn proof_irrelevance(ctx: &Context, a: &Term, b: &Term) -> Option<bool> {
4266    if is_monomorphic_data_constructor(ctx, a)
4267        || is_monomorphic_data_constructor(ctx, b)
4268        || fixed_applied_match_result_family(ctx, a).is_some()
4269        || fixed_applied_match_result_family(ctx, b).is_some()
4270    {
4271        return None;
4272    }
4273    #[cfg(test)]
4274    CONVERSION_PROOF_TYPE_PROBES.with(|count| {
4275        if let Some(n) = count.get() {
4276            count.set(Some(n + 1));
4277        }
4278    });
4279    let (Ok(ta), Ok(tb)) = (infer_type(ctx, a), infer_type(ctx, b)) else {
4280        return None;
4281    };
4282    let is_propositional = |t: &Term| {
4283        matches!(
4284            infer_type(ctx, t).map(|s| normalize(ctx, &s)),
4285            Ok(Term::Sort(level)) if level == Universe::SProp || level.equiv(&Universe::Prop)
4286        )
4287    };
4288    if !is_propositional(&ta) && !is_propositional(&tb) {
4289        return None;
4290    }
4291    Some(def_eq(ctx, &ta, &tb))
4292}
4293
4294/// Extract the inductive type name from a type.
4295///
4296/// Handles both:
4297/// - Simple inductives: `Nat` → Some("Nat")
4298/// - Polymorphic inductives: `List A` → Some("List")
4299///
4300/// Returns None if the type is not an inductive type.
4301fn extract_inductive_name(ctx: &Context, ty: &Term) -> Option<String> {
4302    match ty {
4303        // Simple case: Global("Nat")
4304        Term::Global(name) | Term::Const { name, .. } if ctx.is_inductive(name) => {
4305            Some(name.clone())
4306        }
4307
4308        // Polymorphic case: App(App(...App(Global("List"), _)...), _)
4309        // Recursively unwrap App to find the base Global
4310        Term::App(func, _) => extract_inductive_name(ctx, func),
4311
4312        _ => None,
4313    }
4314}
4315
4316/// Whether `t` contains a `Term::Hole` anywhere. Short-circuits on the first one.
4317pub(crate) fn mentions_hole(t: &Term) -> bool {
4318    match t {
4319        Term::Hole => true,
4320        Term::Sort(_) | Term::Var(_) | Term::Global(_) | Term::Const { .. } | Term::Lit(_) => false,
4321        Term::App(f, a) => mentions_hole(f) || mentions_hole(a),
4322        Term::Pi {
4323            param_type,
4324            body_type,
4325            ..
4326        } => mentions_hole(param_type) || mentions_hole(body_type),
4327        Term::Lambda {
4328            param_type, body, ..
4329        } => mentions_hole(param_type) || mentions_hole(body),
4330        Term::Let {
4331            ty, value, body, ..
4332        } => mentions_hole(ty) || mentions_hole(value) || mentions_hole(body),
4333        Term::Match {
4334            discriminant,
4335            motive,
4336            cases,
4337        } => {
4338            mentions_hole(discriminant) || mentions_hole(motive) || cases.iter().any(mentions_hole)
4339        }
4340        Term::Fix { body, .. } => mentions_hole(body),
4341        Term::MutualFix { defs, .. } => defs.iter().any(|(_, b)| mentions_hole(b)),
4342        Term::Annotated { term, .. } => mentions_hole(term),
4343    }
4344}
4345
4346/// α-equivalence **as a kernel verdict** — the syntactic fast path of every conversion check.
4347///
4348/// It is [`types_equal`] with SPEC B applied: a `Term::Hole` is an UNSOLVED ELABORATION
4349/// PROBLEM, not a term of the theory, so no judgement about it may succeed — not against a
4350/// type, not against a sort, not against another `Hole`. `types_equal` is a MATCHER, and a
4351/// matcher may sensibly treat a hole as a wildcard; a matcher's leniency must never become the
4352/// kernel's answer. One hole surviving into a checked statement otherwise makes every
4353/// comparison against that statement succeed, so a theorem is recorded as verified while
4354/// nothing proves it.
4355///
4356/// The hole walk runs only when the structural match already SUCCEEDED, so it never costs more
4357/// than the comparison that has just been paid for.
4358#[cfg(test)]
4359pub(crate) fn bounded_probe_alpha_eq_for_test(a: &Term, b: &Term) -> bool {
4360    alpha_eq(a, b)
4361}
4362
4363fn alpha_eq(a: &Term, b: &Term) -> bool {
4364    types_equal(a, b) && !mentions_hole(a) && !mentions_hole(b)
4365}
4366
4367/// α-equivalence with no hole on either side: the two terms differ at most in the names of their
4368/// bound variables, and so mean the same thing.
4369pub(crate) fn alpha_equivalent(a: &Term, b: &Term) -> bool {
4370    alpha_eq(a, b)
4371}
4372
4373#[inline(never)]
4374fn fresh_conversion_name(ctx: Option<&Context>, terms: &[&Term]) -> String {
4375    let mut avoid = std::collections::HashSet::new();
4376    for term in terms {
4377        avoid.extend(free_vars(term));
4378    }
4379    let mut name = fresh_name("__conversion", &avoid);
4380    while avoid.contains(&name) || ctx.is_some_and(|c| c.local_name_in_use(&name)) {
4381        name.push('_');
4382    }
4383    name
4384}
4385
4386#[inline(never)]
4387fn open_conversion_binders(
4388    ctx: Option<&Context>,
4389    p: &str,
4390    a: &Term,
4391    q: &str,
4392    b: &Term,
4393) -> (String, Term, Term) {
4394    let name = fresh_conversion_name(ctx, &[a, b]);
4395    let variable = Term::Var(name.clone());
4396    (
4397        name,
4398        substitute(a, p, &variable),
4399        substitute(b, q, &variable),
4400    )
4401}
4402
4403#[inline(never)]
4404fn bound_types_equal(p: &str, a: &Term, q: &str, b: &Term) -> bool {
4405    if p == q {
4406        return types_equal(a, b);
4407    }
4408    let (_, a, b) = open_conversion_binders(None, p, a, q, b);
4409    types_equal(&a, &b)
4410}
4411
4412/// Structural α-equivalence AS A MATCHER: the same term up to renaming of bound variables,
4413/// with a `Term::Hole` acting as a WILDCARD that matches any term.
4414///
4415/// The wildcard is why this is not the kernel's conversion check. Every verdict goes through
4416/// [`alpha_eq`], which refuses a hole outright.
4417fn types_equal(a: &Term, b: &Term) -> bool {
4418    // Hole matches anything (it's a type wildcard)
4419    if matches!(a, Term::Hole) || matches!(b, Term::Hole) {
4420        return true;
4421    }
4422
4423    match (a, b) {
4424        (Term::Sort(u1), Term::Sort(u2)) => u1.equiv(u2),
4425
4426        (Term::Lit(l1), Term::Lit(l2)) => l1 == l2,
4427
4428        (Term::Var(n1), Term::Var(n2)) => n1 == n2,
4429
4430        (Term::Global(n1), Term::Global(n2)) => n1 == n2,
4431        (
4432            Term::Const {
4433                name: n1,
4434                levels: l1,
4435            },
4436            Term::Const {
4437                name: n2,
4438                levels: l2,
4439            },
4440        ) => n1 == n2 && l1.len() == l2.len() && l1.iter().zip(l2).all(|(a, b)| a.equiv(b)),
4441
4442        (
4443            Term::Pi {
4444                param: p1,
4445                param_type: t1,
4446                body_type: b1,
4447            },
4448            Term::Pi {
4449                param: p2,
4450                param_type: t2,
4451                body_type: b2,
4452            },
4453        ) => types_equal(t1, t2) && { bound_types_equal(p1, b1, p2, b2) },
4454
4455        (
4456            Term::Lambda {
4457                param: p1,
4458                param_type: t1,
4459                body: b1,
4460            },
4461            Term::Lambda {
4462                param: p2,
4463                param_type: t2,
4464                body: b2,
4465            },
4466        ) => types_equal(t1, t2) && { bound_types_equal(p1, b1, p2, b2) },
4467
4468        (Term::App(f1, a1), Term::App(f2, a2)) => types_equal(f1, f2) && types_equal(a1, a2),
4469
4470        (
4471            Term::Match {
4472                discriminant: d1,
4473                motive: m1,
4474                cases: c1,
4475            },
4476            Term::Match {
4477                discriminant: d2,
4478                motive: m2,
4479                cases: c2,
4480            },
4481        ) => {
4482            types_equal(d1, d2)
4483                && types_equal(m1, m2)
4484                && c1.len() == c2.len()
4485                && c1.iter().zip(c2.iter()).all(|(a, b)| types_equal(a, b))
4486        }
4487
4488        (Term::Fix { name: n1, body: b1 }, Term::Fix { name: n2, body: b2 }) => {
4489            bound_types_equal(n1, b1, n2, b2)
4490        }
4491
4492        // A ζ-binding, up to renaming. Without this arm two structurally identical SHARED types
4493        // fall past `is_subtype`'s fast path and are compared by normalising both — which
4494        // re-materialises exactly the copies the sharing avoided.
4495        //
4496        // The comparison itself lives OUT OF LINE. `types_equal` recurses once per node of a
4497        // term the depth door admits — up to 1600 frames — so every local this arm would add
4498        // (an α-renaming, a substituted body) is paid by all 1600 of them whether or not a `Let`
4499        // is ever seen. Inlining it cost ~180 KB of stack on a 1800-deep spine and turned
4500        // `kernel_core_extra::a_term_past_the_depth_door_is_refused_and_does_not_abort` from a
4501        // refusal into an abort.
4502        (Term::Let { .. }, Term::Let { .. }) => let_types_equal(a, b),
4503
4504        // All recursive names bind every body simultaneously. Reuse the term
4505        // store's scope-aware canonicalizer, which retains member order/index.
4506        (Term::MutualFix { .. }, Term::MutualFix { .. }) => mutual_types_equal(a, b),
4507
4508        _ => false,
4509    }
4510}
4511
4512// Keep arena allocation out of the recursive structural comparator's stack frame.
4513#[inline(never)]
4514fn mutual_types_equal(a: &Term, b: &Term) -> bool {
4515    let mut store = crate::term_store::TermStore::new();
4516    let lhs = store.intern(a);
4517    let rhs = store.intern(b);
4518    store.alpha_same(lhs, rhs)
4519}
4520
4521/// The `Let`/`Let` case of [`types_equal`], kept out of line so its locals do not enlarge the
4522/// frame of the recursion that calls it once per node. See the call site for why that matters.
4523#[inline(never)]
4524fn let_types_equal(a: &Term, b: &Term) -> bool {
4525    let (
4526        Term::Let {
4527            name: n1,
4528            ty: t1,
4529            value: v1,
4530            body: b1,
4531        },
4532        Term::Let {
4533            name: n2,
4534            ty: t2,
4535            value: v2,
4536            body: b2,
4537        },
4538    ) = (a, b)
4539    else {
4540        return false;
4541    };
4542    types_equal(t1, t2) && types_equal(v1, v2) && { bound_types_equal(n1, b1, n2, b2) }
4543}
4544
4545/// The carriers the kernel's own `Term::Lit` rule inhabits DIRECTLY, with no constructor.
4546///
4547/// `ex falso` — an empty `match`, legal because a zero-constructor inductive has no inhabitants
4548/// — is a claim about INHABITATION, not about a constructor count. These carriers are registered
4549/// with no constructors and are inhabited anyway, by the `Term::Lit` arm of `infer_type` a few
4550/// hundred lines up. Without this list, `match (5 : Int) return False with []` type-checks: a
4551/// closed proof of `False` assembled from nothing but the standard library, corroborated by the
4552/// second kernel because it counts constructors the same way.
4553///
4554/// The list belongs HERE, next to the rule that needs it, and must be extended whenever the
4555/// literal rule learns a new carrier — the two are the same question asked twice ("what can the
4556/// kernel hand me a value of?"). The real repair for the six below is to give them their
4557/// constructors (`Int` is `ofNat`/`negSucc` in Lean); until then an empty match on one is
4558/// refused rather than believed.
4559fn is_inhabited_by_a_literal(name: &str) -> bool {
4560    matches!(
4561        name,
4562        "Int" | "Nat" | "Float" | "Text" | "Duration" | "Date" | "Moment"
4563    )
4564}
4565
4566/// Whether a `match` on `inductive_name` is `ex falso` in name only — the inductive has no
4567/// constructors, so the empty case list passes coverage, but the kernel can produce a value of
4568/// it regardless.
4569fn empty_match_would_be_a_lie(ctx: &Context, inductive_name: &str) -> bool {
4570    ctx.get_constructors(inductive_name).is_empty() && is_inhabited_by_a_literal(inductive_name)
4571}
4572
4573/// Decompose `t` into a CONSTRUCTOR head and its arguments, bridging a `Nat` literal to its
4574/// Peano spelling (`0` is `Zero`, `n+1` is `Succ (n-1)`) so that `Vect A 0` and `Vect A Zero`
4575/// are the same index to the unifier below.
4576fn constructor_head(ctx: &Context, t: &Term) -> Option<(String, Vec<Term>)> {
4577    if let Some(constructor) = crate::int_inductive::literal_constructor(ctx, t) {
4578        return constructor_head(ctx, &constructor);
4579    }
4580    if let Term::Lit(Literal::Nat(value)) = t {
4581        if !crate::int_inductive::reads_nat_literal(ctx, value) {
4582            return None;
4583        }
4584        return match nat_peano_step(t) {
4585            Term::Global(z) => Some((z, Vec::new())),
4586            Term::App(s, pred) => match *s {
4587                Term::Global(succ) => Some((succ, vec![*pred])),
4588                _ => None,
4589            },
4590            _ => None,
4591        };
4592    }
4593    let mut args = Vec::new();
4594    let mut head = t;
4595    while let Term::App(f, a) = head {
4596        args.push((**a).clone());
4597        head = f;
4598    }
4599    args.reverse();
4600    match head {
4601        Term::Global(name) | Term::Const { name, .. } if ctx.is_constructor(name) => {
4602            Some((name.clone(), args))
4603        }
4604        _ => None,
4605    }
4606}
4607
4608/// Expose only the discriminant index currently needed for constructor disjointness.
4609/// Its local variables belong to ctx; the constructor's declared index lives in
4610/// another telescope and must not be reduced under this context.
4611pub(crate) fn demanded_index_constructor_head(
4612    ctx: &Context,
4613    t: &Term,
4614) -> Option<(String, Vec<Term>)> {
4615    if let Some(head) = constructor_head(ctx, t) {
4616        return Some(head);
4617    }
4618    if let Some(exposed) = crate::reduction::bounded_conversion_head(ctx, t) {
4619        if let Some(head) = constructor_head(ctx, &exposed) {
4620            return Some(head);
4621        }
4622    }
4623    // A probe boundary is not a semantic refusal. Retain the general checker's
4624    // existing capability, but demand this index alone instead of the whole family.
4625    // An unfinished normalization is never evidence that a case is impossible.
4626    let exposed = crate::reduction::normalize_checked(ctx, t).ok()?;
4627    constructor_head(ctx, &exposed)
4628}
4629
4630/// Whether constructor disjointness is available for `ctor`'s inductive.
4631///
4632/// It is a `Type`-level phenomenon ONLY. In `Prop`, proof irrelevance makes any two inhabitants
4633/// of a proposition definitionally equal, so two distinct constructors of a propositional
4634/// inductive are EQUAL and nothing may be concluded from their difference. Using a clash there
4635/// would let the kernel discharge a branch that is in fact reachable. A family in `Sort u` is a
4636/// proposition at `u := 0`, so the family's arity must end in a sort that is `Type 0` or above at
4637/// every instance of its levels ([`Universe::is_never_prop`]); an arity that ends in anything but
4638/// a written sort grants nothing.
4639fn disjointness_available(ctx: &Context, ctor: &str) -> bool {
4640    let Some(ind) = ctx.constructor_inductive(ctor) else {
4641        return false;
4642    };
4643    let Some(ind_ty) = ctx.get_global(&ind) else {
4644        return false;
4645    };
4646    let mut cur = ind_ty;
4647    while let Term::Pi { body_type, .. } = cur {
4648        cur = body_type;
4649    }
4650    matches!(cur, Term::Sort(level) if level.is_never_prop())
4651}
4652
4653/// Whether the two index terms PROVABLY cannot be made equal.
4654///
4655/// `scrutinee` is rigid — it comes from the discriminant's own type. `declared` is the
4656/// constructor's declared result index, in the constructor's scope, where `flexible` names the
4657/// binders that are still free to be anything.
4658///
4659/// The only reason ever given is CONSTRUCTOR DISJOINTNESS: two distinct constructors of the
4660/// same `Type`-level inductive can never produce equal values. Everything else — a flexible
4661/// variable on either side, a rigid variable, or an index whose head cannot be exposed — is
4662/// treated as possibly-equal, because refusing to rule a branch out is always safe and ruling one out
4663/// wrongly deletes a reachable case.
4664fn indices_clash(ctx: &Context, scrutinee: &Term, declared: &Term, flexible: &[String]) -> bool {
4665    if let Term::Var(v) = declared {
4666        if flexible.iter().any(|f| f == v) {
4667            return false;
4668        }
4669    }
4670    // Without a declared constructor head no clash is possible; do not evaluate
4671    // the scrutinee index merely to rediscover that fact.
4672    let Some((cd, args_d)) = constructor_head(ctx, declared) else {
4673        return false;
4674    };
4675    let Some((cs, args_s)) = demanded_index_constructor_head(ctx, scrutinee) else {
4676        return false;
4677    };
4678    if !disjointness_available(ctx, &cs) || !disjointness_available(ctx, &cd) {
4679        return false;
4680    }
4681    if cs != cd {
4682        return ctx.constructor_inductive(&cs) == ctx.constructor_inductive(&cd);
4683    }
4684    args_s
4685        .iter()
4686        .zip(args_d.iter())
4687        .any(|(a, b)| indices_clash(ctx, a, b, flexible))
4688}
4689
4690/// **SPEC F** — which of `inductive_name`'s constructors the discriminant's INDICES still allow,
4691/// as positions in registration order. `disc_args` are the discriminant's type arguments, its
4692/// `num_params` parameters first.
4693///
4694/// A `Match` on an indexed family owes a branch only for the constructors that could actually
4695/// have produced the scrutinee. `VCons`'s result index is `Succ n`, which can never be `Zero`,
4696/// so a match on `Vect α 0` owes no `VCons` branch — and demanding one forces the caller to
4697/// invent an inhabitant of a type that may have none (`vtail`'s impossible branch owes a
4698/// `Vect A n` with no value in scope). A constructor's parameters are the scrutinee's own, so its
4699/// declared result indices are read with its parameter binders at the scrutinee's parameters:
4700/// `refl`'s index is its parameter `x`, which for `Eq Nat (Succ a) Zero` is `Succ a`, clashing
4701/// with `Zero`.
4702///
4703/// Conservative in the safe direction: a constructor is ruled out only on a definite clash, so
4704/// the worst this can do is ask for a branch that is unreachable — never omit one that is not.
4705pub(crate) fn constructors_the_indices_allow(
4706    ctx: &Context,
4707    inductive_name: &str,
4708    num_params: usize,
4709    disc_args: &[Term],
4710) -> Vec<usize> {
4711    let (params, disc_indices) = disc_args.split_at(num_params.min(disc_args.len()));
4712    ctx.get_constructors(inductive_name)
4713        .iter()
4714        .enumerate()
4715        .filter(|(_, (_, ctor_type))| {
4716            let mut opened: Term = (*ctor_type).clone();
4717            for value in params {
4718                match opened {
4719                    Term::Pi {
4720                        param, body_type, ..
4721                    } => opened = substitute(&body_type, &param, value),
4722                    _ => return true,
4723                }
4724            }
4725            let mut flexible: Vec<String> = Vec::new();
4726            let mut cur = &opened;
4727            while let Term::Pi {
4728                param, body_type, ..
4729            } = cur
4730            {
4731                flexible.push(param.clone());
4732                cur = body_type;
4733            }
4734            let result_args = extract_type_args(cur);
4735            let declared: &[Term] = if result_args.len() > num_params {
4736                &result_args[num_params..]
4737            } else {
4738                &[]
4739            };
4740            !disc_indices
4741                .iter()
4742                .zip(declared.iter())
4743                .any(|(s, d)| indices_clash(ctx, s, d, &flexible))
4744        })
4745        .map(|(i, _)| i)
4746        .collect()
4747}
4748
4749/// Whether a `Prop` inductive may be **large-eliminated** (into `Type`).
4750///
4751/// The CIC criterion, stated once and implemented independently here and in
4752/// [`crate::recheck`]: `I` is large-eliminable iff
4753///
4754/// - it has **zero** constructors (`False` — ex falso reaches every sort), or
4755/// - it has **exactly one**, and every binder of that constructor's telescope beyond `I`'s
4756///   **parameters** is either
4757///   - **propositional** (its type's sort is `Prop`), or
4758///   - **an index**: it occurs, as itself, among the arguments of the constructor's result
4759///     type `I p̄ ī` past the parameters.
4760///
4761/// Two telescopes meet here and they have DIFFERENT lengths. `I`'s arity is params + indices;
4762/// the constructor binds the params and then its own fields — it does not bind the indices, it
4763/// COMPUTES them in its result. Counting the skip off the arity walks past real data fields
4764/// (`Tag : Bool → Prop` with `Tag_mk : Π(n:Nat). Tag (decide …)` would hand back the `n` a
4765/// proof was built from); counting it off the params WITHOUT the index clause amputates `Acc`,
4766/// whose `x : A` field is admissible only because the result is `Acc A R x` — and with `Acc`
4767/// goes every definition by well-founded recursion.
4768///
4769/// The index clause is what makes a data field harmless: if the field IS an index, it is
4770/// already recoverable from the proposition's own type, so eliminating into `Type` reveals
4771/// nothing the type did not already carry.
4772pub(crate) fn is_subsingleton_prop(ctx: &Context, inductive_name: &str) -> KernelResult<bool> {
4773    let ctors = ctx.get_constructors(inductive_name);
4774    match ctors.len() {
4775        0 => Ok(true),
4776        1 => {
4777            let num_params = ctx.inductive_num_params(inductive_name);
4778            let mut local = ctx.clone();
4779            let mut t = ctors[0].1.clone();
4780            let mut i = 0usize;
4781            // Field binders that are NOT propositional; each is admissible only if it
4782            // reappears among the result's indices.
4783            let mut owed: Vec<(String, usize)> = Vec::new();
4784            // Every binder name, to detect shadowing: if a name is bound twice, an occurrence
4785            // in the result refers to the INNER binder, so crediting the outer one would be
4786            // unsound. A repeat is refused rather than resolved.
4787            let mut bound: Vec<(String, String)> = Vec::new();
4788            while let Term::Pi {
4789                param,
4790                param_type,
4791                body_type,
4792            } = t
4793            {
4794                if i >= num_params && !infer_sort(&local, &param_type)?.equiv(&Universe::Prop) {
4795                    owed.push((param.clone(), bound.len()));
4796                }
4797                let original = param.clone();
4798                let (param, body_type) =
4799                    open_context_binder(&local, &param, &param_type, &body_type);
4800                let opened = param.to_string();
4801                t = body_type.into_owned();
4802                local = local.extend(&opened, (*param_type).clone());
4803                bound.push((original, opened));
4804                i += 1;
4805            }
4806            if owed.is_empty() {
4807                return Ok(true);
4808            }
4809            // `t` is now the constructor's result `I p̄ ī`; its arguments past the parameters
4810            // are the indices.
4811            let args = extract_type_args(&t);
4812            let indices: &[Term] = if args.len() > num_params {
4813                &args[num_params..]
4814            } else {
4815                &[]
4816            };
4817            Ok(owed.iter().all(|(original, position)| {
4818                let name = &bound[*position].1;
4819                bound.iter().filter(|(old, _)| old == original).count() == 1
4820                    && indices
4821                        .iter()
4822                        .any(|ix| matches!(ix, Term::Var(v) if v == name))
4823            }))
4824        }
4825        _ => Ok(false),
4826    }
4827}
4828
4829#[cfg(test)]
4830#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/def_eq_and_freshness_mutation_kills.rs"]
4831mod def_eq_and_freshness_mutation_kills;
4832
4833#[cfg(test)]
4834#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/large_elim_tests.rs"]
4835mod large_elim_tests;
4836
4837#[cfg(test)]
4838#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/constructor_universe_controls.rs"]
4839mod constructor_universe_controls;
4840
4841#[cfg(test)]
4842#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/native_mutual_alpha_regressions.rs"]
4843mod native_mutual_alpha_regressions;
4844
4845#[cfg(test)]
4846#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/early_binder_conversion_controls.rs"]
4847mod early_binder_conversion_controls;
4848
4849#[cfg(test)]
4850#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/type_head_work_controls.rs"]
4851mod type_head_work_controls;
4852
4853#[cfg(test)]
4854#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/head_alignment_conversion_controls.rs"]
4855mod head_alignment_conversion_controls;
4856
4857#[cfg(test)]
4858#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/head_alignment_exactness_controls.rs"]
4859mod head_alignment_exactness_controls;
4860
4861#[cfg(test)]
4862#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/head_alignment_float_contract_controls.rs"]
4863mod head_alignment_float_contract_controls;
4864
4865#[cfg(test)]
4866#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/delta_head_alignment_controls.rs"]
4867mod delta_head_alignment_controls;
4868
4869#[cfg(test)]
4870#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/delta_head_hint_boundaries.rs"]
4871mod delta_head_hint_boundaries;
4872
4873#[cfg(test)]
4874#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/delta_head_chain_controls.rs"]
4875mod delta_head_chain_controls;
4876
4877#[cfg(test)]
4878#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/borrowed_common_head_work.rs"]
4879mod borrowed_common_head_work;
4880
4881#[cfg(test)]
4882#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/closed_helper_body_controls.rs"]
4883mod closed_helper_body_controls;
4884
4885#[cfg(test)]
4886#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/closed_helper_body_admission_controls.rs"]
4887mod closed_helper_body_admission_controls;
4888
4889#[cfg(test)]
4890#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/borrowed_fixed_head_controls.rs"]
4891mod borrowed_fixed_head_controls;
4892
4893#[cfg(test)]
4894#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/constructor_probe_guard_controls.rs"]
4895mod constructor_probe_guard_controls;
4896
4897#[cfg(test)]
4898#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/fix_result_eligibility_controls.rs"]
4899mod fix_result_eligibility_controls;
4900
4901#[cfg(test)]
4902#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/fix_lambda_probe_controls.rs"]
4903mod fix_lambda_probe_controls;
4904
4905#[cfg(test)]
4906#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/peano_inference_controls.rs"]
4907mod peano_inference_controls;
4908
4909#[cfg(test)]
4910#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/peano_inference_boundary_controls.rs"]
4911mod peano_inference_boundary_controls;
4912
4913#[cfg(test)]
4914#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/peano_explicit_poly_control.rs"]
4915mod peano_explicit_poly_control;
4916
4917#[cfg(test)]
4918#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/opaque_sort_reuse_controls.rs"]
4919mod opaque_sort_reuse_controls;
4920
4921#[cfg(test)]
4922#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/binder_entry_scope_controls.rs"]
4923mod binder_entry_scope_controls;
4924
4925#[cfg(test)]
4926#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/owned_substitution_controls.rs"]
4927mod owned_substitution_controls;
4928
4929#[cfg(test)]
4930#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/owned_replacement_controls.rs"]
4931mod owned_replacement_controls;
4932
4933#[cfg(test)]
4934#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/bounded_conversion_controls.rs"]
4935mod bounded_conversion_controls;
4936
4937#[cfg(test)]
4938#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/borrowed_retry_controls.rs"]
4939mod borrowed_retry_controls;
4940
4941#[cfg(test)]
4942#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/probe_scheduling_controls.rs"]
4943mod probe_scheduling_controls;
4944
4945#[cfg(test)]
4946#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/constructor_refutation_controls.rs"]
4947mod constructor_refutation_controls;
4948
4949#[path = "lazy_delta.rs"]
4950mod lazy_delta;
4951
4952#[cfg(test)]
4953#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/lazy_delta_controls.rs"]
4954mod lazy_delta_controls;
4955
4956#[cfg(test)]
4957#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/type_checker/recursor_probe_scheduling_controls.rs"]
4958mod recursor_probe_scheduling_controls;