Skip to main content

logicaffeine_kernel/
recursor.rs

1//! R2 — auto-derived recursors (dependent eliminators) for inductive types.
2//!
3//! Today a user who declares an inductive must hand-write the `match`/`fix` to recurse
4//! over it. Lean/Coq instead AUTO-GENERATE the recursor `I.rec` (the dependent
5//! eliminator) from the declaration, so "declare `ℕ`, get induction for free." This
6//! module is that derivation: from an inductive's registered constructors it synthesizes
7//!
8//! ```text
9//! I_rec : Π(P : I → Type). minor₀ → … → minorₖ → Π(x : I). P x
10//! I_rec := λP. λf₀ … λfₖ. fix rec. λx. match x return (λx. P x) with
11//!            | Cᵢ a… => fᵢ a… (rec aⱼ)…        -- one rec-call per recursive argument
12//! ```
13//!
14//! where each minor premise is `Π(args). Π(IH : P aⱼ for each recursive arg). P (Cᵢ args)`.
15//! The synthesized term is an ordinary kernel `Term`, so it is re-checked by `infer_type`
16//! for coverage + termination — and (the point of building it now) independently
17//! re-derived by the `recheck` second kernel. A Prop motive may be
18//! passed wherever the `Type` motive is expected, by cumulativity (`Prop ≤ Type 0`), so
19//! the single derived recursor serves BOTH computation and induction.
20//!
21//! Scope: parametric AND indexed inductive families. Beyond the uniform PARAMETERS of a
22//! type like `List A`, an indexed family has INDICES that vary per constructor — `Eq A x :
23//! A → Prop` with `refl : Eq A x x`. Their eliminator's motive abstracts over the indices,
24//! so `derive_recursor("Eq")` synthesizes FULL Paulin-Mohring J:
25//! `Π(A). Π(x:A). Π(P : Π(y:A). Eq A x y → Sort). P x (refl A x) → Π(y). Π(h:Eq A x y). P y h`
26//! — the identity eliminator as a kernel-checked term, not an axiom.
27
28use crate::context::Context;
29use crate::error::{KernelError, KernelResult};
30use crate::infer_type;
31use crate::term::{Term, Universe};
32
33/// Build `I_rec`'s term and type for the inductive `ind`. Returns `(recursor_type,
34/// recursor_term)` where `recursor_type` is exactly `infer_type(recursor_term)` — so the
35/// type is, by construction, the one the kernel certifies the term against.
36pub fn derive_recursor(ctx: &Context, ind: &str) -> KernelResult<(Term, Term)> {
37    derive_recursor_at(ctx, ind, None)
38}
39
40/// Build `I_rec.{u}` — the UNIVERSE-POLYMORPHIC eliminator, `Π(P : I → Sort u). … → Π(x). P x`
41/// with `u` an explicit level PARAMETER. Returns `(level_params, recursor_type, recursor_term)`.
42///
43/// This is the other half of the motive-sort rule (see `motive_target`): monomorphic and
44/// polymorphic are two DECLARATIONS, not two spellings of one. `derive_recursor` gives an
45/// inductive an eliminator at its own concrete sort — the one a `Type 1` inductive needs to
46/// recover the `Type 0` its constructor stores — and this gives Lean's `Nat.rec.{u}`, the one a
47/// `Type 1`-valued family built by recursion over `Nat` needs. A single artefact cannot be both:
48/// a level variable in the motive's target makes `Type 0 ⋠ u` (a variable ranges over `Prop`),
49/// so the concrete instance is lost the moment the polymorphic one is claimed.
50///
51/// Register it either way and both reference forms work:
52/// * [`Context::add_universe_poly`] + `Term::Const { name, levels }` — Lean's explicit
53///   `Nat.rec.{1}`; the level telescope is checked positionally by `term::resolve_const_levels`.
54/// * [`Context::add_definition`] + a bare `Term::Global` — the application rule turns the free
55///   level variable into a metavariable and solves it from the motive actually supplied
56///   (`type_checker.rs::implicit_levels_for_head`).
57///
58/// The soundness gates are NOT parameterised: a non-subsingleton `Prop` still targets `Prop`, a
59/// subsingleton `Prop` still targets `Type 0`, `SProp` still targets `SProp`, and an inductive
60/// whose own sort is already a level variable keeps that variable rather than gaining a second,
61/// independently-instantiable one. A sort provably above Prop (including symbolic successors/maxima) gets an
62/// independent motive level.
63///
64/// The returned telescope COVERS the eliminator's type, in Lean's order (`Eq.rec.{u, u_1}`): the
65/// motive's own level first, then the inductive's levels — its declared universe parameters, in
66/// order and including any unused one, or else the levels its arity auto-binds, in first-occurrence
67/// order — then any level the type still mentions (a mutual sibling's). The explicit door
68/// refuses a level variable no parameter binds, so only a covering telescope keeps the promise
69/// that both reference forms above work.
70pub fn derive_recursor_universe_poly(
71    ctx: &Context,
72    ind: &str,
73) -> KernelResult<(Vec<String>, Term, Term)> {
74    let count = ctx.mutual_block_of(ind).map_or(1, |b| b.len());
75    let levels = fresh_motive_levels(ctx, ind, count);
76    let (ty, term) = derive_recursor_at(ctx, ind, Some(&levels))?;
77    // Only the motive levels the motive-sort rule actually USED are parameters of this
78    // declaration: a `Prop` member's motive keeps `Prop`, so promising a level telescope entry
79    // for it would let a caller instantiate a parameter that appears nowhere — a level arity
80    // mismatch the `Const` door would then have to accept or refuse for reasons the type does not
81    // show.
82    let used = crate::term::free_level_vars(&ty);
83    let mut levels: Vec<String> = levels.into_iter().filter(|l| used.contains(l)).collect();
84    let own = match ctx.poly_declaration(ind) {
85        Some((declared, _)) => declared.to_vec(),
86        None => ctx
87            .get_global(ind)
88            .map(crate::term::free_level_vars)
89            .unwrap_or_default(),
90    };
91    for level in own.into_iter().chain(used) {
92        if !levels.contains(&level) {
93            levels.push(level);
94        }
95    }
96    Ok((levels, ty, term))
97}
98
99/// The shared builder. `motive_levels` is `None` for the monomorphic eliminator and the block's
100/// level-parameter names for the polymorphic one.
101fn derive_recursor_at(
102    ctx: &Context,
103    ind: &str,
104    motive_levels: Option<&[String]>,
105) -> KernelResult<(Term, Term)> {
106    // A member of a mutual block gets the mutual recursor (one shared `MutualFix`).
107    if let Some(block) = ctx.mutual_block_of(ind) {
108        let block = block.to_vec();
109        return derive_mutual_recursor(ctx, ind, &block, motive_levels);
110    }
111
112    let ind_full_ty = ctx
113        .get_global(ind)
114        .ok_or_else(|| KernelError::UnboundVariable(ind.to_string()))?
115        .clone();
116    if !ctx.is_inductive(ind) {
117        return Err(KernelError::UnboundVariable(ind.to_string()));
118    }
119
120    // Split the inductive's arity telescope into uniform PARAMETERS (the first
121    // `num_params`) and INDICES (the rest). `List : Type → Type` is 1 param / 0 index;
122    // `Eq : Π(A). A → A → Prop` is 2 params (`A`, `x`) / 1 index (`y`). Parameters are
123    // bound once at the top as `A0 … A_{p-1}`; indices are re-abstracted inside the
124    // recursion (`Idx0 … Idx_{k-1}`) because each constructor targets its own index.
125    let (arity_tele, ind_sort) = peel_pis(&ind_full_ty);
126    let num_params = ctx.inductive_num_params(ind).min(arity_tele.len());
127
128    let motive_target = motive_target_at(ctx, ind, ind_sort, motive_levels.and_then(|l| l.first()));
129    let param_tele: Vec<(String, Term)> = arity_tele[..num_params].to_vec();
130    let index_tele: Vec<(String, Term)> = arity_tele[num_params..].to_vec();
131    let k = index_tele.len();
132
133    let tp_names: Vec<String> = (0..num_params).map(|i| format!("A{i}")).collect();
134    let idx_names: Vec<String> = (0..k).map(|i| format!("Idx{i}")).collect();
135
136    // Parameter binder types, closed over the earlier parameters' recursor names.
137    let param_types: Vec<Term> = (0..num_params)
138        .map(|i| rename_tele_types(&param_tele[i].1, &param_tele[..i], &tp_names))
139        .collect();
140    // Index binder types, closed over ALL parameters and the earlier indices — with the
141    // given index binder names (the fix and the match motive use different names).
142    let index_types = |names: &[String]| -> Vec<Term> {
143        (0..k)
144            .map(|j| {
145                let with_params = rename_tele_types(&index_tele[j].1, &param_tele, &tp_names);
146                rename_index_refs(&with_params, &index_tele[..j], names)
147            })
148            .collect::<Vec<_>>()
149    };
150
151    // `I A0 … A_{p-1}` (applied to the parameters only).
152    let mut ind_params = declaration_head(ctx, ind);
153    for name in &tp_names {
154        ind_params = app(ind_params, var(name));
155    }
156
157    // The motive `P : Π(Idx0:T0)…Π(Idx_{k-1}). (I A… Idx…) → Type 0`. `Prop` motives pass
158    // by cumulativity, so this one recursor serves computation and induction alike.
159    let idx_types_motive = index_types(&idx_names);
160    let mut ind_at_idx = ind_params.clone();
161    for name in &idx_names {
162        ind_at_idx = app(ind_at_idx, var(name));
163    }
164    let mut motive_ty = arrow(ind_at_idx.clone(), motive_target);
165    for j in (0..k).rev() {
166        motive_ty = pi(&idx_names[j], idx_types_motive[j].clone(), motive_ty);
167    }
168
169    let ctors: Vec<(String, Term)> = ctx
170        .get_constructors(ind)
171        .iter()
172        .map(|(n, t)| (n.to_string(), (*t).clone()))
173        .collect();
174
175    let mut minors: Vec<(String, Term)> = Vec::with_capacity(ctors.len());
176    let mut cases: Vec<Term> = Vec::with_capacity(ctors.len());
177    // A standalone inductive is a mutual block of one: its only motive is `P`, its only
178    // recursive name `rec`, and every recursive occurrence is of member 0 (itself).
179    let mut recursive = false;
180    let block_single = [ind];
181    let motive_single = ["P".to_string()];
182    let rec_single = ["rec".to_string()];
183    for (i, (cname, ctype)) in ctors.iter().enumerate() {
184        let an = constructor_analysis(ctx, ctype, ind, &block_single, num_params, &tp_names)?;
185        recursive |= an.recursive.iter().any(Option::is_some);
186        minors.push((
187            format!("f{i}"),
188            minor_type(ctx, "P", &motive_single, cname, &tp_names, &an),
189        ));
190        cases.push(case_term(
191            cname,
192            &tp_names,
193            &an,
194            &format!("f{i}"),
195            &rec_single,
196        ));
197    }
198
199    // The match's return clause `λj0…λj_{k-1}. λx:(I A… j…). P j… x` — the motive
200    // re-abstracted with FRESH index binders so applying it at the discriminant's own
201    // indices captures nothing.
202    let mj_names: Vec<String> = (0..k).map(|i| format!("mj{i}")).collect();
203    let idx_types_match = index_types(&mj_names);
204    let mut ind_at_mj = ind_params.clone();
205    for name in &mj_names {
206        ind_at_mj = app(ind_at_mj, var(name));
207    }
208    let mut motive_body = var("P");
209    for name in &mj_names {
210        motive_body = app(motive_body, var(name));
211    }
212    motive_body = app(motive_body, var("x"));
213    let mut motive_fn = lam("x", ind_at_mj, motive_body);
214    for j in (0..k).rev() {
215        motive_fn = lam(&mj_names[j], idx_types_match[j].clone(), motive_fn);
216    }
217
218    // fix rec. λIdx0…λIdx_{k-1}. λx:(I A… Idx…). match x return motive_fn with { cases }
219    let match_term = Term::Match {
220        discriminant: Box::new(var("x")),
221        motive: Box::new(motive_fn),
222        cases,
223    };
224    let mut fix_body = lam("x", ind_at_idx.clone(), match_term);
225    for j in (0..k).rev() {
226        fix_body = lam(&idx_names[j], idx_types_motive[j].clone(), fix_body);
227    }
228    let mut term = if recursive {
229        Term::Fix {
230            name: "rec".to_string(),
231            body: Box::new(fix_body),
232        }
233    } else {
234        fix_body
235    };
236
237    // Wrap `λfₙ … λf₀`, then `λP`, then the parameters `λA_{p-1} … λA₀`.
238    for (fname, fty) in minors.iter().rev() {
239        term = lam(fname, fty.clone(), term);
240    }
241    term = lam("P", motive_ty, term);
242    for i in (0..num_params).rev() {
243        term = lam(&tp_names[i], param_types[i].clone(), term);
244    }
245
246    // The recursor's type is, by construction, the type the kernel certifies for it —
247    // coverage and termination included, in both kernels.
248    let ty = infer_type(ctx, &term)?;
249    Ok((ty, term))
250}
251
252/// Derive the recursor for `ind`, a member of the MUTUAL block `block`. Every member
253/// shares one `MutualFix`; this returns `(type, term)` for `ind`'s recursor, whose body
254/// selects `ind`'s component. The eliminator takes ONE motive per member and ALL
255/// members' minor premises; a recursive occurrence of member `k` in any constructor
256/// uses motive `P_k` for its induction hypothesis and calls `rec_k`.
257///
258/// Scope: mutual blocks with shared uniform PARAMETERS (`Tree A`/`Forest A`) and per-member
259/// indices are both supported; every member must agree on the parameter count.
260fn derive_mutual_recursor(
261    ctx: &Context,
262    ind: &str,
263    block: &[String],
264    motive_levels: Option<&[String]>,
265) -> KernelResult<(Term, Term)> {
266    let m = block.len();
267    let bi = block.iter().position(|n| n == ind).ok_or_else(|| {
268        KernelError::CertificationError(format!("'{ind}' is not in its own mutual block"))
269    })?;
270    let block_refs: Vec<&str> = block.iter().map(|s| s.as_str()).collect();
271
272    // Shared PARAMETERS — a mutual block shares its uniform parameters (`Tree A`/`Forest A`).
273    // Taken from the first member; every member must agree on the count.
274    let block0_ty = ctx
275        .get_global(&block[0])
276        .ok_or_else(|| KernelError::UnboundVariable(block[0].clone()))?
277        .clone();
278    let (arity0, _) = peel_pis(&block0_ty);
279    let num_params = ctx.inductive_num_params(&block[0]).min(arity0.len());
280    for name in block {
281        let full = ctx
282            .get_global(name)
283            .ok_or_else(|| KernelError::UnboundVariable(name.clone()))?;
284        if ctx.inductive_num_params(name).min(peel_pis(full).0.len()) != num_params {
285            return Err(KernelError::CertificationError(format!(
286                "auto-recursor: mutual block members disagree on parameter count ('{name}')"
287            )));
288        }
289    }
290    let param_tele: Vec<(String, Term)> = arity0[..num_params].to_vec();
291    let tp_names: Vec<String> = (0..num_params).map(|i| format!("A{i}")).collect();
292    let param_types: Vec<Term> = (0..num_params)
293        .map(|i| rename_tele_types(&param_tele[i].1, &param_tele[..i], &tp_names))
294        .collect();
295
296    let motive_names: Vec<String> = (0..m).map(|k| format!("P{k}")).collect();
297    let rec_names: Vec<String> = (0..m).map(|k| format!("rec{k}")).collect();
298
299    // `I_k` applied to the shared parameters `A0 … A_{p-1}`.
300    let ind_at_params = |name: &str| {
301        tp_names
302            .iter()
303            .fold(declaration_head(ctx, name), |acc, n| app(acc, var(n)))
304    };
305
306    // Per-member skeleton: the index telescope, the motive type, and the applied form.
307    struct MemberInfo {
308        idx_names: Vec<String>,
309        idx_types: Vec<Term>,
310        ind_at_idx: Term,
311        motive_ty: Term,
312    }
313    let mut infos: Vec<MemberInfo> = Vec::with_capacity(m);
314    for (k, name) in block.iter().enumerate() {
315        let full_ty = ctx
316            .get_global(name)
317            .ok_or_else(|| KernelError::UnboundVariable(name.clone()))?
318            .clone();
319        let (arity_tele, ind_sort) = peel_pis(&full_ty);
320        let index_tele: Vec<(String, Term)> = arity_tele[num_params..].to_vec();
321        // The SAME rule as the standalone derivation — a block member must not get a weaker
322        // eliminator for being declared in company. This arm used to pin `Type 0`, which
323        // silently capped a `Type 1` member's motive one level below its own fields.
324        let target = motive_target_at(ctx, name, ind_sort, motive_levels.and_then(|l| l.get(k)));
325        let idx_names: Vec<String> = (0..index_tele.len())
326            .map(|j| format!("Idx{k}_{j}"))
327            .collect();
328        // Index binder types: rename the shared params → `A_i`, and earlier index refs → `Idx…`.
329        let idx_types: Vec<Term> = (0..index_tele.len())
330            .map(|j| {
331                let with_params = rename_tele_types(&index_tele[j].1, &param_tele, &tp_names);
332                rename_index_refs(&with_params, &index_tele[..j], &idx_names)
333            })
334            .collect();
335        // I_k A0 … A_{p-1} Idx0 … Idx_{k-1}
336        let mut ind_at_idx = ind_at_params(name);
337        for n in &idx_names {
338            ind_at_idx = app(ind_at_idx, var(n));
339        }
340        // motive_k : Π(idx…). (I_k params idx…) → target  (params are bound by the outer λ)
341        let mut motive_ty = arrow(ind_at_idx.clone(), target);
342        for j in (0..idx_names.len()).rev() {
343            motive_ty = pi(&idx_names[j], idx_types[j].clone(), motive_ty);
344        }
345        infos.push(MemberInfo {
346            idx_names,
347            idx_types,
348            ind_at_idx,
349            motive_ty,
350        });
351    }
352
353    // All minor premises (across every member, in block order) and, per member, the
354    // `match` cases of its own fixpoint body.
355    let mut minors: Vec<(String, Term)> = Vec::new();
356    let mut member_cases: Vec<Vec<Term>> = Vec::with_capacity(m);
357    for (k, name) in block.iter().enumerate() {
358        let ctors: Vec<(String, Term)> = ctx
359            .get_constructors(name)
360            .iter()
361            .map(|(n, t)| (n.to_string(), (*t).clone()))
362            .collect();
363        let mut cases = Vec::with_capacity(ctors.len());
364        for (cname, ctype) in &ctors {
365            let an = constructor_analysis(ctx, ctype, name, &block_refs, num_params, &tp_names)?;
366            let fi = format!("f{}", minors.len());
367            minors.push((
368                fi.clone(),
369                minor_type(ctx, &motive_names[k], &motive_names, cname, &tp_names, &an),
370            ));
371            cases.push(case_term(cname, &tp_names, &an, &fi, &rec_names));
372        }
373        member_cases.push(cases);
374    }
375
376    // Each member's fixpoint body: `λidx…. λx:(I_k params idx…). match x return motive_fn`.
377    let mut defs: Vec<(String, Term)> = Vec::with_capacity(m);
378    for (k, name) in block.iter().enumerate() {
379        let info = &infos[k];
380        // The match return clause `λmj…. λx. P_k mj… x`, fresh index binders.
381        let mj_names: Vec<String> = (0..info.idx_names.len())
382            .map(|j| format!("mj{k}_{j}"))
383            .collect();
384        let mut motive_body = var(&motive_names[k]);
385        for n in &mj_names {
386            motive_body = app(motive_body, var(n));
387        }
388        motive_body = app(motive_body, var("x"));
389        let mut ind_at_mj = ind_at_params(name);
390        for n in &mj_names {
391            ind_at_mj = app(ind_at_mj, var(n));
392        }
393        let mut motive_fn = lam("x", ind_at_mj, motive_body);
394        for j in (0..mj_names.len()).rev() {
395            // Re-express the index type with the FRESH match binders: `Idx_i → mj_i`.
396            let mut mj_ty = info.idx_types[j].clone();
397            for i in 0..j {
398                mj_ty = subst_name(&mj_ty, &info.idx_names[i], &var(&mj_names[i]));
399            }
400            motive_fn = lam(&mj_names[j], mj_ty, motive_fn);
401        }
402        let match_term = Term::Match {
403            discriminant: Box::new(var("x")),
404            motive: Box::new(motive_fn),
405            cases: member_cases[k].clone(),
406        };
407        let mut fix_body = lam("x", info.ind_at_idx.clone(), match_term);
408        for j in (0..info.idx_names.len()).rev() {
409            fix_body = lam(&info.idx_names[j], info.idx_types[j].clone(), fix_body);
410        }
411        defs.push((rec_names[k].clone(), fix_body));
412    }
413
414    // The whole recursor: `λA0…A_{p-1}. λP0…P_{m-1}. λf0…f_{last}. (mutualfix { rec_k := … }).bi`.
415    let mut term = Term::MutualFix { defs, index: bi };
416    for (fname, fty) in minors.iter().rev() {
417        term = lam(fname, fty.clone(), term);
418    }
419    for k in (0..m).rev() {
420        term = lam(&motive_names[k], infos[k].motive_ty.clone(), term);
421    }
422    for i in (0..num_params).rev() {
423        term = lam(&tp_names[i], param_types[i].clone(), term);
424    }
425
426    let ty = infer_type(ctx, &term)?;
427    Ok((ty, term))
428}
429
430// =====================================================================================
431// R3 — the DERIVED AUXILIARIES
432//
433// Lean synthesises, at declaration time and for EVERY inductive, a fixed family of
434// auxiliaries besides the eliminator: `noConfusionType`/`noConfusion` (constructor
435// disjointness and injectivity — what every `injection`, `cases h` on an equation and
436// `simp [injEq]` proof actually cites), `below`/`brecOn` (course-of-values recursion — what
437// every `| n+2 => …` definition compiles through), and `DecidableEq` instances. None of them
438// may be an AXIOM: axiomatising `noConfusion` turns every `injection` proof in a development
439// into an assumption. Everything below is therefore a TERM, checked by `infer_type` (and so
440// re-derivable by the `recheck` second kernel) exactly as `derive_recursor` is.
441//
442// Like `derive_recursor`, these functions NEVER touch the caller's context: each returns
443// `(type, term)` and the caller registers. Where one auxiliary is stated in terms of another
444// (`noConfusion` cites `noConfusionType`, `brecOn` cites `below`), the derivation checks
445// against a private extension of the context and the returned type mentions the cited name —
446// so the caller must register the whole group, in the order `derive_auxiliaries` returns.
447// =====================================================================================
448
449/// One derived auxiliary: the name Lean gives it, the type the kernel certified for it, and
450/// the term it certified.
451#[derive(Debug, Clone, PartialEq)]
452pub struct DerivedAux {
453    /// The constant's name, in this kernel's flat spelling (`Chain_noConfusion`, `clink_inj`).
454    pub name: String,
455    /// `infer_type(term)` — the type the kernel certified, not a separately written claim.
456    pub ty: Term,
457    /// The definition's body.
458    pub term: Term,
459}
460
461/// Everything the declaration of `ind` should bring with it, in DEPENDENCY ORDER, for a
462/// caller to register verbatim:
463///
464/// ```text
465/// for aux in derive_auxiliaries(&ctx, name) {
466///     ctx.add_definition(aux.name, aux.ty, aux.term);
467/// }
468/// ```
469///
470/// The list is BEST-EFFORT: an auxiliary that this kernel genuinely cannot state for this
471/// inductive (an indexed family with no index unifier, a `Prop` where disjointness is a
472/// category error, a carrier above `Type 0` where `Eq` cannot even be applied) is OMITTED
473/// rather than faked. Registration is therefore never blocked by a shape we do not reach, and
474/// what IS returned was type-checked. Call the individual `derive_*` functions when you want
475/// the REASON one is missing — each returns a `CertificationError` naming it.
476///
477/// It also never DISPLACES: a name already in `ctx` is left alone. Registration overwrites, so
478/// without this the umbrella run over a prelude type would silently replace the hand-written,
479/// separately-tested `decEqNat` with a freshly derived one — same intent, different term, and
480/// nothing would have reported the swap.
481pub fn derive_auxiliaries(ctx: &Context, ind: &str) -> Vec<DerivedAux> {
482    let mut env = ctx.clone();
483    let mut out: Vec<DerivedAux> = Vec::new();
484    let mut generic = generic_family(ctx, ind);
485
486    // The eliminator first: everything else is stated over the same constructor telescope, and
487    // every existing caller already registers it under exactly this name.
488    // The eliminator, derived ONCE and then RESHAPED twice. `recOn` and `casesOn` are the two
489    // argument orders every Lean development actually writes — `cases h` compiles to `casesOn`,
490    // `induction … using` and `match` elaborate through one of them, and
491    // `Lean/Elab/Inductive.lean:729-730` generates both at the declaration, immediately after the
492    // kernel has added `rec`. Sharing the derivation is not only thrift: three independent calls
493    // would be three chances for the motive-sort rule to be asked differently.
494    let elim = derive_recursor(ctx, ind);
495    if let Ok(rec_pair) = &elim {
496        push_aux(
497            ctx,
498            &mut env,
499            &mut out,
500            &mut generic,
501            format!("{ind}_rec"),
502            &|_e: &Context| Ok(rec_pair.clone()),
503        );
504        push_aux(
505            ctx,
506            &mut env,
507            &mut out,
508            &mut generic,
509            format!("{ind}_recOn"),
510            &|e| rec_on_from(e, ind, rec_pair.clone()),
511        );
512        push_aux(
513            ctx,
514            &mut env,
515            &mut out,
516            &mut generic,
517            format!("{ind}_casesOn"),
518            &|e| cases_on_from(e, ind, rec_pair.clone()),
519        );
520    }
521    push_aux(
522        ctx,
523        &mut env,
524        &mut out,
525        &mut generic,
526        format!("{ind}_noConfusionType"),
527        &|e| derive_no_confusion_type(e, ind),
528    );
529    push_aux(
530        ctx,
531        &mut env,
532        &mut out,
533        &mut generic,
534        format!("{ind}_noConfusion"),
535        &|e| derive_no_confusion(e, ind),
536    );
537
538    let ctor_names: Vec<String> = ctx
539        .get_constructors(ind)
540        .iter()
541        .map(|(n, _)| n.to_string())
542        .collect();
543    for c in &ctor_names {
544        push_aux(
545            ctx,
546            &mut env,
547            &mut out,
548            &mut generic,
549            format!("{c}_inj"),
550            &|e| derive_ctor_inj(e, ind, c),
551        );
552    }
553
554    push_aux(
555        ctx,
556        &mut env,
557        &mut out,
558        &mut generic,
559        format!("{ind}_below"),
560        &|e| derive_below(e, ind),
561    );
562    push_aux(
563        ctx,
564        &mut env,
565        &mut out,
566        &mut generic,
567        format!("{ind}_brecOn"),
568        &|e| derive_brec_on(e, ind),
569    );
570    push_aux(
571        ctx,
572        &mut env,
573        &mut out,
574        &mut generic,
575        format!("decEq{ind}"),
576        &|e| derive_dec_eq(e, ind),
577    );
578
579    out
580}
581
582/// `term` with every bare reference to one of `family`'s names written at the generic instance
583/// `name.{levels…}`.
584///
585/// The derivations state a family's auxiliaries at the family's own instance, naming it bare. For
586/// a universe-polymorphic family that instance is the one its telescope's variables denote, so the
587/// auxiliaries are registered over that telescope with the references written out: an auxiliary is
588/// then polymorphic as Lean's (`Big.below.{u}`) and serves every instance of the family, where a
589/// bare reference would leave its level a variable nothing instantiates.
590pub(crate) fn at_generic_levels(
591    term: &Term,
592    family: &std::collections::HashSet<String>,
593    levels: &[String],
594) -> Term {
595    let go = |t: &Term| Box::new(at_generic_levels(t, family, levels));
596    match term {
597        Term::Global(n) if family.contains(n) => Term::Const {
598            name: n.clone(),
599            levels: levels.iter().map(|l| Universe::Var(l.clone())).collect(),
600        },
601        Term::Global(_)
602        | Term::Const { .. }
603        | Term::Var(_)
604        | Term::Sort(_)
605        | Term::Lit(_)
606        | Term::Hole => term.clone(),
607        Term::App(f, a) => Term::App(go(f), go(a)),
608        Term::Pi {
609            param,
610            param_type,
611            body_type,
612        } => Term::Pi {
613            param: param.clone(),
614            param_type: go(param_type),
615            body_type: go(body_type),
616        },
617        Term::Lambda {
618            param,
619            param_type,
620            body,
621        } => Term::Lambda {
622            param: param.clone(),
623            param_type: go(param_type),
624            body: go(body),
625        },
626        Term::Match {
627            discriminant,
628            motive,
629            cases,
630        } => Term::Match {
631            discriminant: go(discriminant),
632            motive: go(motive),
633            cases: cases
634                .iter()
635                .map(|c| at_generic_levels(c, family, levels))
636                .collect(),
637        },
638        Term::Fix { name, body } => Term::Fix {
639            name: name.clone(),
640            body: go(body),
641        },
642        Term::MutualFix { defs, index } => Term::MutualFix {
643            defs: defs
644                .iter()
645                .map(|(n, b)| (n.clone(), at_generic_levels(b, family, levels)))
646                .collect(),
647            index: *index,
648        },
649        Term::Let {
650            name,
651            ty,
652            value,
653            body,
654        } => Term::Let {
655            name: name.clone(),
656            ty: go(ty),
657            value: go(value),
658            body: go(body),
659        },
660        Term::Annotated { annotation, term } => Term::Annotated {
661            annotation: annotation.clone(),
662            term: go(term),
663        },
664    }
665}
666
667/// A universe-polymorphic family's telescope, and the names its auxiliaries write at the generic
668/// instance: the block's members and their constructors, joined by each auxiliary as it is derived.
669/// `None` for a family without levels.
670pub(crate) fn generic_family(
671    ctx: &Context,
672    ind: &str,
673) -> Option<(Vec<String>, std::collections::HashSet<String>)> {
674    let telescope = ctx
675        .poly_declaration(ind)
676        .map(|(ps, _)| ps.to_vec())
677        .filter(|ps| !ps.is_empty())?;
678    let members = ctx
679        .mutual_block_of(ind)
680        .map(<[String]>::to_vec)
681        .unwrap_or_else(|| vec![ind.to_string()]);
682    let constructors: Vec<String> = members
683        .iter()
684        .flat_map(|m| {
685            ctx.get_constructors(m)
686                .into_iter()
687                .map(|(c, _)| c.to_string())
688        })
689        .collect();
690    Some((telescope, members.into_iter().chain(constructors).collect()))
691}
692
693/// Derive one auxiliary unless its name is taken by a constant that is NOT this umbrella's own
694/// prior generation, and make a success visible to the NEXT one (`noConfusion` is stated over
695/// `noConfusionType`) — all in `env`, leaving the caller's context untouched.
696///
697/// The provenance test is what lets declaration-time synthesis work at all. "Never displace a
698/// name already in scope" is the rule that protects the prelude's hand-written `decEqNat` from
699/// being swapped for a same-intent, different term nothing would have reported — but once
700/// auxiliaries are registered AT the declaration they are always already in scope, and a blanket
701/// version of that rule turns the umbrella into a no-op on its second run. An inductive's
702/// auxiliaries have to be re-derived after every constructor, because the ones derived after the
703/// first describe an inductive that is not finished yet, so the umbrella must be able to replace
704/// its OWN previous answer. [`Context::is_derived_aux`] is the record of which constants those
705/// are; everything else is somebody's, and is left alone.
706fn push_aux(
707    ctx: &Context,
708    env: &mut Context,
709    out: &mut Vec<DerivedAux>,
710    generic: &mut Option<(Vec<String>, std::collections::HashSet<String>)>,
711    name: String,
712    derive: &dyn Fn(&Context) -> KernelResult<(Term, Term)>,
713) {
714    if ctx.get_global(&name).is_some() && !ctx.is_derived_aux(&name) {
715        return;
716    }
717    if let Ok((ty, term)) = derive(env) {
718        // An auxiliary is stated as it will be registered, so the next one is typed against that:
719        // a polymorphic family's own names at its generic instance (`at_generic_levels`), and every
720        // other bare reference that is not a head at its own levels (`Context::stored_term`).
721        let (ty, term) = match generic.as_mut() {
722            Some((levels, family)) => {
723                family.insert(name.clone());
724                (
725                    at_generic_levels(&ty, family, levels),
726                    at_generic_levels(&term, family, levels),
727                )
728            }
729            None => (ty, term),
730        };
731        let (ty, term) = (env.stored_term(ty), env.stored_term(term));
732        // This environment exists only to type the next auxiliary. Its equation
733        // products would be discarded, then checked again in the real Context.
734        // The final registration still generates every public equation.
735        env.with_equations_suspended(|env| match generic.as_ref() {
736            Some((levels, _)) => {
737                env.add_universe_poly(&name, levels.clone(), ty.clone(), term.clone())
738            }
739            None => env.add_definition(name.clone(), ty.clone(), term.clone()),
740        });
741        out.push(DerivedAux { name, ty, term });
742    }
743}
744
745/// `I_noConfusionType : Π(A…). Π(P : Type 0). I A… → I A… → Type 0`
746///
747/// The type-level half of constructor disjointness, computed by cases on BOTH arguments:
748///
749/// ```text
750/// noConfusionType P (C x⃗) (C y⃗) ⤳ (x⃗ = y⃗ → P) → P     -- the same constructor: injectivity
751/// noConfusionType P (C x⃗) (D y⃗) ⤳ P                    -- different ones: anything follows
752/// ```
753///
754/// Lean's is `{α} → Sort v → I α → I α → Sort v`; ours pins `P` to `Type 0` because the
755/// prelude's `Eq` quantifies over a `Type 0` carrier, which is the same bound its companion
756/// `noConfusion` runs into. A `Prop` goal still passes by cumulativity, which is the case
757/// `cases h`/`injection` actually needs.
758///
759/// `Match` here is positional with no patterns and no wildcard, so an n-constructor inductive
760/// genuinely spells out all n² arms — that is not a shortcut, it is the shape of the term.
761pub fn derive_no_confusion_type(ctx: &Context, ind: &str) -> KernelResult<(Term, Term)> {
762    let sc = AuxScope::new(ctx, ind)?;
763    sc.require_equatable_carrier()?;
764    require_global(
765        ctx,
766        "Eq",
767        "the equation each same-constructor arm is built from",
768    )?;
769
770    let p_sort = Term::Sort(Universe::Type(0));
771    let ret = lam("_", sc.carrier.clone(), p_sort.clone());
772
773    let mut outer = Vec::with_capacity(sc.ctors.len());
774    for (i, (ci, cti)) in sc.ctors.iter().enumerate() {
775        let xs = ctor_value_fields(cti, ind, sc.num_params, &sc.tp_names, "x")?;
776        let mut inner = Vec::with_capacity(sc.ctors.len());
777        for (j, (_cj, ctj)) in sc.ctors.iter().enumerate() {
778            let ys = ctor_value_fields(ctj, ind, sc.num_params, &sc.tp_names, "y")?;
779            let arm = if i == j {
780                homogeneous_fields(&xs, &ys, ci)?;
781                // `(x₀ = y₀ → … → x_{m-1} = y_{m-1} → P) → P`. With m = 0 this degenerates to
782                // `P → P`, which is the right answer: a nullary constructor equals itself and
783                // the equation carries no information.
784                let mut hyp = var("P");
785                for k in (0..xs.len()).rev() {
786                    hyp = arrow(eq3(xs[k].1.clone(), var(&xs[k].0), var(&ys[k].0)), hyp);
787                }
788                arrow(hyp, var("P"))
789            } else {
790                var("P")
791            };
792            inner.push(lams(&ys, arm));
793        }
794        outer.push(lams(
795            &xs,
796            Term::Match {
797                discriminant: Box::new(var("b")),
798                motive: Box::new(ret.clone()),
799                cases: inner,
800            },
801        ));
802    }
803
804    let body = Term::Match {
805        discriminant: Box::new(var("a")),
806        motive: Box::new(ret),
807        cases: outer,
808    };
809    let term = sc.close_lams(lam(
810        "P",
811        p_sort,
812        lam("a", sc.carrier.clone(), lam("b", sc.carrier.clone(), body)),
813    ));
814    let ty = infer_type(ctx, &term)?;
815    Ok((ty, term))
816}
817
818/// `I_noConfusion : Π(A…). Π(P : Type 0). Π(a b : I A…). Eq (I A…) a b → I_noConfusionType A… P a b`
819///
820/// The proof half. It is ONE transport: `noConfusionType P a a` is inhabited on the DIAGONAL
821/// (for each constructor, `λk. k (refl x₀) … (refl x_{m-1})`), and J carries that along the
822/// equation to `noConfusionType P a b`. Instantiating `P` gives both halves of what Lean's
823/// `injection` and `cases h` use — `P := False` is constructor disjointness, `P := (xₖ = yₖ)`
824/// is field-`k` injectivity (see [`derive_ctor_inj`]).
825///
826/// A definition, kernel-checked: nothing here is assumed.
827pub fn derive_no_confusion(ctx: &Context, ind: &str) -> KernelResult<(Term, Term)> {
828    let sc = AuxScope::new(ctx, ind)?;
829    sc.require_equatable_carrier()?;
830    require_global(ctx, "Eq", "the equation `noConfusion` consumes")?;
831    require_global(ctx, "refl", "the diagonal arm's witness")?;
832    require_global(
833        ctx,
834        "Eq_rec_dep",
835        "the transport (J) that carries the diagonal along it",
836    )?;
837
838    let nct_name = format!("{ind}_noConfusionType");
839    let mut env = ctx.clone();
840    if env.get_global(&nct_name).is_none() {
841        let (t, b) = derive_no_confusion_type(ctx, ind)?;
842        env.add_definition(nct_name.clone(), t, b);
843    }
844
845    let p_sort = Term::Sort(Universe::Type(0));
846    let nct_at = |u: Term, w: Term| {
847        let mut t = gl(&nct_name);
848        for n in &sc.tp_names {
849            t = app(t, var(n));
850        }
851        app(app(app(t, var("P")), u), w)
852    };
853
854    // The DIAGONAL, by cases on `a`: at `C x⃗` the goal reduces to `(x⃗ = x⃗ → P) → P`, and the
855    // hypothesis is discharged by one `refl` per field.
856    let mut diag_cases = Vec::with_capacity(sc.ctors.len());
857    for (cn, cty) in &sc.ctors {
858        let xs = ctor_value_fields(cty, ind, sc.num_params, &sc.tp_names, "x")?;
859        let ys = ctor_value_fields(cty, ind, sc.num_params, &sc.tp_names, "y")?;
860        homogeneous_fields(&xs, &ys, cn)?;
861        let mut hyp = var("P");
862        for k in (0..xs.len()).rev() {
863            hyp = arrow(eq3(xs[k].1.clone(), var(&xs[k].0), var(&xs[k].0)), hyp);
864        }
865        let mut applied = var("k");
866        for (n, t) in &xs {
867            applied = app(applied, app(app(gl("refl"), t.clone()), var(n)));
868        }
869        diag_cases.push(lams(&xs, lam("k", hyp, applied)));
870    }
871    let diagonal = Term::Match {
872        discriminant: Box::new(var("a")),
873        motive: Box::new(lam("z", sc.carrier.clone(), nct_at(var("z"), var("z")))),
874        cases: diag_cases,
875    };
876
877    // `Eq_rec_dep (I A…) a (λy. λ_ : Eq (I A…) a y. noConfusionType A… P a y) diagonal b h`.
878    let j_motive = lam(
879        "y",
880        sc.carrier.clone(),
881        lam(
882            "_",
883            eq3(sc.carrier.clone(), var("a"), var("y")),
884            nct_at(var("a"), var("y")),
885        ),
886    );
887    let transported = apps(
888        gl("Eq_rec_dep"),
889        &[
890            sc.carrier.clone(),
891            var("a"),
892            j_motive,
893            diagonal,
894            var("b"),
895            var("h"),
896        ],
897    );
898    let term = sc.close_lams(lam(
899        "P",
900        p_sort,
901        lam(
902            "a",
903            sc.carrier.clone(),
904            lam(
905                "b",
906                sc.carrier.clone(),
907                lam(
908                    "h",
909                    eq3(sc.carrier.clone(), var("a"), var("b")),
910                    transported,
911                ),
912            ),
913        ),
914    ));
915    let ty = infer_type(&env, &term)?;
916    Ok((ty, term))
917}
918
919/// `C_inj : Π(A…). Π(x⃗). Π(y⃗). Eq (I A…) (C A… x⃗) (C A… y⃗) → (x₀ = y₀ ∧ … ∧ x_{m-1} = y_{m-1})`
920///
921/// Lean's `C.inj` — the constant `injection h` produces. It is [`derive_no_confusion`] at
922/// `P := the conjunction`, applied to the function that just repackages the equations, so it
923/// needs no defaulted projection and therefore no inhabitant of the other constructors'
924/// fields (the reason a hand-written `pred`-style projection cannot do this in general).
925///
926/// NOT derived here: Lean's `C.injEq`, which states the same fact as an EQUALITY of
927/// propositions (`(C x⃗ = C y⃗) = (x⃗ = y⃗)`) and so needs `propext`. The implication above is
928/// the propext-free content.
929pub fn derive_ctor_inj(ctx: &Context, ind: &str, ctor: &str) -> KernelResult<(Term, Term)> {
930    let sc = AuxScope::new(ctx, ind)?;
931    sc.require_equatable_carrier()?;
932    let cty = sc
933        .ctors
934        .iter()
935        .find(|(n, _)| n == ctor)
936        .map(|(_, t)| t.clone())
937        .ok_or_else(|| unsupported(format!("'{ctor}' is not a constructor of '{ind}'")))?;
938    let xs = ctor_value_fields(&cty, ind, sc.num_params, &sc.tp_names, "x")?;
939    let ys = ctor_value_fields(&cty, ind, sc.num_params, &sc.tp_names, "y")?;
940    homogeneous_fields(&xs, &ys, ctor)?;
941    if xs.is_empty() {
942        return Err(unsupported(format!(
943            "'{ctor}' takes no arguments, so it has no injectivity principle to state"
944        )));
945    }
946    if xs.len() > 1 {
947        require_global(
948            ctx,
949            "And",
950            "the conjunction of a multi-field constructor's equations",
951        )?;
952        require_global(ctx, "conj", "the conjunction's introduction rule")?;
953    }
954    let env = with_no_confusion(ctx, ind)?;
955
956    let eqs: Vec<Term> = (0..xs.len())
957        .map(|k| eq3(xs[k].1.clone(), var(&xs[k].0), var(&ys[k].0)))
958        .collect();
959    // `goals[k]` is the conjunction of `eqs[k..]`, right-nested as `And e_k goals[k+1]`.
960    let mut goals: Vec<Term> = Vec::with_capacity(eqs.len());
961    for k in (0..eqs.len()).rev() {
962        let g_k = match goals.last() {
963            None => eqs[k].clone(),
964            Some(rest) => app(app(gl("And"), eqs[k].clone()), rest.clone()),
965        };
966        goals.push(g_k);
967    }
968    goals.reverse();
969
970    // `λe₀ … λe_{m-1}. conj _ _ e₀ (conj _ _ e₁ (… e_{m-1}))`
971    let mut payload = var(&format!("e{}", eqs.len() - 1));
972    for k in (0..eqs.len() - 1).rev() {
973        payload = apps(
974            gl("conj"),
975            &[
976                eqs[k].clone(),
977                goals[k + 1].clone(),
978                var(&format!("e{k}")),
979                payload,
980            ],
981        );
982    }
983    for k in (0..eqs.len()).rev() {
984        payload = lam(&format!("e{k}"), eqs[k].clone(), payload);
985    }
986
987    let cx = sc.ctor_at(ctor, &xs);
988    let cy = sc.ctor_at(ctor, &ys);
989    let mut nc = gl(&format!("{ind}_noConfusion"));
990    for n in &sc.tp_names {
991        nc = app(nc, var(n));
992    }
993    let call = app(
994        apps(nc, &[goals[0].clone(), cx.clone(), cy.clone(), var("h")]),
995        payload,
996    );
997
998    let mut term = lam("h", eq3(sc.carrier.clone(), cx, cy), call);
999    for (n, t) in ys.iter().rev() {
1000        term = lam(n, t.clone(), term);
1001    }
1002    for (n, t) in xs.iter().rev() {
1003        term = lam(n, t.clone(), term);
1004    }
1005    let term = sc.close_lams(term);
1006    let ty = infer_type(&env, &term)?;
1007    Ok((ty, term))
1008}
1009
1010/// `I_below : Π(A…). Π(motive : I A… → Type 0). I A… → Type 0`
1011///
1012/// The course-of-values PACKAGE: `below motive t` is the type of "a `motive` value for every
1013/// subterm reachable below `t`", right-nested one entry per recursive field and closed with
1014/// `Unit`:
1015///
1016/// ```text
1017/// below motive (C x⃗) ⤳ Prod (Prod (motive xⱼ) (below motive xⱼ)) (… Unit)   -- recursive fields only
1018/// ```
1019///
1020/// Each entry is EXACTLY the type of `brecOn`'s internal `aux xⱼ`, which is what makes
1021/// [`derive_brec_on`]'s payload the recursive results themselves rather than a repacking. A
1022/// strictly-positive FUNCTIONAL field `xⱼ : Π(z:B…). I A…` contributes
1023/// `Π(z:B…). Prod (motive (xⱼ z…)) (below motive (xⱼ z…))`, as in `Acc`.
1024///
1025/// Lean's is `Sort (max 1 u)`-valued over `PProd`/`PUnit`; ours uses the prelude's `Prod`/`Unit`
1026/// and is therefore pinned to `Type 0`, the sort those live at.
1027pub fn derive_below(ctx: &Context, ind: &str) -> KernelResult<(Term, Term)> {
1028    let sc = AuxScope::new(ctx, ind)?;
1029    sc.require_no_mutual_block(ctx, "below")?;
1030    require_global(ctx, "Prod", "the pairing the below-package is built from")?;
1031    require_global(ctx, "Unit", "the empty tail of the below-package")?;
1032
1033    let ty0 = Term::Sort(Universe::Type(0));
1034    let motive_ty = arrow(sc.carrier.clone(), ty0.clone());
1035    let below_at = |u: Term| app(var("bel"), u);
1036
1037    let mut cases = Vec::with_capacity(sc.ctors.len());
1038    for (cn, cty) in &sc.ctors {
1039        let xs = ctor_value_fields(cty, ind, sc.num_params, &sc.tp_names, "x")?;
1040        let rfs = recursive_fields(&sc, &xs, cn)?;
1041        let entries: Vec<Term> = rfs.iter().map(|rf| entry_type(rf, &below_at)).collect();
1042        cases.push(lams(&xs, below_package_type(&entries)));
1043    }
1044
1045    let body = Term::Fix {
1046        name: "bel".to_string(),
1047        body: Box::new(lam(
1048            "t",
1049            sc.carrier.clone(),
1050            Term::Match {
1051                discriminant: Box::new(var("t")),
1052                motive: Box::new(lam("_", sc.carrier.clone(), ty0)),
1053                cases,
1054            },
1055        )),
1056    };
1057    let term = sc.close_lams(lam("motive", motive_ty, body));
1058    let ty = infer_type(ctx, &term)?;
1059    Ok((ty, term))
1060}
1061
1062/// `I_brecOn : Π(A…). Π(motive : I A… → Type 0). Π(t : I A…). Π(F : Π(s). I_below A… motive s → motive s). motive t`
1063///
1064/// Course-of-values RECURSION — the eliminator that hands the step function every subterm at
1065/// once, which is how `| n+2 => …` (and `halve`/`fib`/`pairSum`) is a structural definition
1066/// rather than a re-expressed mutual block. Built the way Lean builds it: one structural
1067/// recursion producing the PAIR `(motive s, below motive s)`, then the first projection.
1068pub fn derive_brec_on(ctx: &Context, ind: &str) -> KernelResult<(Term, Term)> {
1069    let sc = AuxScope::new(ctx, ind)?;
1070    sc.require_no_mutual_block(ctx, "brecOn")?;
1071    require_global(ctx, "Prod", "the pairing the recursion carries")?;
1072    require_global(ctx, "Prod_mk", "the pairing's introduction rule")?;
1073    require_global(
1074        ctx,
1075        "Prod_fst",
1076        "the projection that reads the answer back out",
1077    )?;
1078    require_global(ctx, "Unit", "the empty tail of the below-package")?;
1079    require_global(ctx, "Tt", "the empty below-package's inhabitant")?;
1080
1081    let below_name = format!("{ind}_below");
1082    let mut env = ctx.clone();
1083    if env.get_global(&below_name).is_none() {
1084        let (t, b) = derive_below(ctx, ind)?;
1085        env.add_definition(below_name.clone(), t, b);
1086    }
1087
1088    let ty0 = Term::Sort(Universe::Type(0));
1089    let motive_ty = arrow(sc.carrier.clone(), ty0);
1090    let below_at = |u: Term| {
1091        let mut t = gl(&below_name);
1092        for n in &sc.tp_names {
1093            t = app(t, var(n));
1094        }
1095        app(app(t, var("motive")), u)
1096    };
1097    // `F : Π(s : I A…). I_below A… motive s → motive s`
1098    let f_ty = pi(
1099        "s",
1100        sc.carrier.clone(),
1101        arrow(below_at(var("s")), app(var("motive"), var("s"))),
1102    );
1103
1104    let mut cases = Vec::with_capacity(sc.ctors.len());
1105    for (cn, cty) in &sc.ctors {
1106        let xs = ctor_value_fields(cty, ind, sc.num_params, &sc.tp_names, "x")?;
1107        let rfs = recursive_fields(&sc, &xs, cn)?;
1108        let entries: Vec<(Term, Term)> = rfs
1109            .iter()
1110            .map(|rf| (entry_type(rf, &below_at), entry_value(rf, "aux")))
1111            .collect();
1112        let payload = below_package_value(&entries);
1113        let cx = sc.ctor_at(cn, &xs);
1114        // `Prod_mk (motive (C x⃗)) (below … (C x⃗)) (F (C x⃗) payload) payload`
1115        cases.push(lams(
1116            &xs,
1117            apps(
1118                gl("Prod_mk"),
1119                &[
1120                    app(var("motive"), cx.clone()),
1121                    below_at(cx.clone()),
1122                    app(app(var("F"), cx), payload.clone()),
1123                    payload,
1124                ],
1125            ),
1126        ));
1127    }
1128
1129    let aux = Term::Fix {
1130        name: "aux".to_string(),
1131        body: Box::new(lam(
1132            "s",
1133            sc.carrier.clone(),
1134            Term::Match {
1135                discriminant: Box::new(var("s")),
1136                motive: Box::new(lam(
1137                    "z",
1138                    sc.carrier.clone(),
1139                    prod(app(var("motive"), var("z")), below_at(var("z"))),
1140                )),
1141                cases,
1142            },
1143        )),
1144    };
1145    let body = app(
1146        apps(
1147            gl("Prod_fst"),
1148            &[app(var("motive"), var("t")), below_at(var("t"))],
1149        ),
1150        app(aux, var("t")),
1151    );
1152    let term = sc.close_lams(lam(
1153        "motive",
1154        motive_ty,
1155        lam("t", sc.carrier.clone(), lam("F", f_ty, body)),
1156    ));
1157    let ty = infer_type(&env, &term)?;
1158    Ok((ty, term))
1159}
1160
1161/// `decEqI : Π(A…). Π(dA_i : Π(u v : A_i). Decidable (Eq A_i u v))…. Π(a b : I A…). Decidable (Eq (I A…) a b)`
1162///
1163/// Lean's `deriving DecidableEq`, as a term. Structural recursion on `a`, then a case on `b`:
1164/// DIFFERENT constructors are refuted by [`derive_no_confusion`] at `P := False`; the SAME
1165/// constructor decides its fields left to right, assembling the positive proof by iterated
1166/// transport (one `Eq_rec_dep` per field, rewriting one argument of the constructor at a time)
1167/// and the negative one from field-`k` injectivity, again via `noConfusion`.
1168///
1169/// A parametric inductive gets one decidable-equality PREMISE per type parameter, exactly as
1170/// Lean's `instDecidableEqList [DecidableEq α]` does.
1171///
1172/// A field's own decision procedure is resolved as: the inductive itself (the recursion), a
1173/// type parameter (its premise), or a monomorphic `T` with `decEqT` already in scope (the
1174/// prelude's `decEqNat`/`decEqBool`, or an earlier derivation). Anything else is REFUSED with
1175/// the field named — a decision procedure we cannot actually exhibit must not be claimed.
1176pub fn derive_dec_eq(ctx: &Context, ind: &str) -> KernelResult<(Term, Term)> {
1177    let sc = AuxScope::new(ctx, ind)?;
1178    sc.require_equatable_carrier()?;
1179    require_global(ctx, "Eq", "the equation being decided")?;
1180    require_global(
1181        ctx,
1182        "refl",
1183        "the reflexivity the positive branch starts from",
1184    )?;
1185    require_global(
1186        ctx,
1187        "Eq_rec_dep",
1188        "the transport that assembles a constructor congruence",
1189    )?;
1190    require_global(ctx, "Decidable", "the decision procedure's carrier")?;
1191    require_global(ctx, "isTrue", "the decision's positive constructor")?;
1192    require_global(ctx, "isFalse", "the decision's negative constructor")?;
1193    require_global(
1194        ctx,
1195        "False",
1196        "the absurdity a mismatched constructor pair yields",
1197    )?;
1198    let env = with_no_confusion(ctx, ind)?;
1199
1200    // One decidable-equality premise per parameter. A parameter that is not a `Type 0` (an
1201    // index-like value parameter, or a `Prop`) has no such premise to state, so refuse.
1202    let mut premises: Vec<(String, Term)> = Vec::with_capacity(sc.num_params);
1203    for i in 0..sc.num_params {
1204        if sc.param_types[i] != Term::Sort(Universe::Type(0)) {
1205            return Err(unsupported(format!(
1206                "parameter '{}' of '{ind}' is a {}, not a `Type 0`: a decidable-equality premise \
1207                 can only be stated for a type parameter",
1208                sc.tp_names[i], sc.param_types[i]
1209            )));
1210        }
1211        let a_i = var(&sc.tp_names[i]);
1212        premises.push((
1213            format!("dA{i}"),
1214            pi(
1215                "u",
1216                a_i.clone(),
1217                pi("v", a_i.clone(), dec(eq3(a_i, var("u"), var("v")))),
1218            ),
1219        ));
1220    }
1221
1222    let mut nc = gl(&format!("{ind}_noConfusion"));
1223    for n in &sc.tp_names {
1224        nc = app(nc, var(n));
1225    }
1226
1227    let mut outer = Vec::with_capacity(sc.ctors.len());
1228    for (i, (ci, cti)) in sc.ctors.iter().enumerate() {
1229        let xs = ctor_value_fields(cti, ind, sc.num_params, &sc.tp_names, "x")?;
1230        let cx = sc.ctor_at(ci, &xs);
1231        let mut inner = Vec::with_capacity(sc.ctors.len());
1232        for (j, (cj, ctj)) in sc.ctors.iter().enumerate() {
1233            let ys = ctor_value_fields(ctj, ind, sc.num_params, &sc.tp_names, "y")?;
1234            let cy = sc.ctor_at(cj, &ys);
1235            let goal = eq3(sc.carrier.clone(), cx.clone(), cy.clone());
1236            let arm = if i == j {
1237                homogeneous_fields(&xs, &ys, ci)?;
1238                dec_eq_same_ctor(&sc, ci, &xs, &ys, &nc, &premises)?
1239            } else {
1240                // `noConfusionType False (C x⃗) (D y⃗)` IS `False`, so `noConfusion` at `False` is
1241                // the refutation outright — no discriminating family to hand-write per pair.
1242                let refute = lam(
1243                    "h",
1244                    goal.clone(),
1245                    apps(nc.clone(), &[gl("False"), cx.clone(), cy.clone(), var("h")]),
1246                );
1247                app(app(gl("isFalse"), goal), refute)
1248            };
1249            inner.push(lams(&ys, arm));
1250        }
1251        outer.push(lams(
1252            &xs,
1253            Term::Match {
1254                discriminant: Box::new(var("b")),
1255                motive: Box::new(lam(
1256                    "b✧",
1257                    sc.carrier.clone(),
1258                    dec(eq3(sc.carrier.clone(), cx.clone(), var("b✧"))),
1259                )),
1260                cases: inner,
1261            },
1262        ));
1263    }
1264
1265    let a_match = Term::Match {
1266        discriminant: Box::new(var("a")),
1267        motive: Box::new(lam(
1268            "a✧",
1269            sc.carrier.clone(),
1270            dec(eq3(sc.carrier.clone(), var("a✧"), var("b"))),
1271        )),
1272        cases: outer,
1273    };
1274    let mut term = Term::Fix {
1275        name: "rec".to_string(),
1276        body: Box::new(lam(
1277            "a",
1278            sc.carrier.clone(),
1279            lam("b", sc.carrier.clone(), a_match),
1280        )),
1281    };
1282    for (n, t) in premises.iter().rev() {
1283        term = lam(n, t.clone(), term);
1284    }
1285    let term = sc.close_lams(term);
1286    let ty = infer_type(&env, &term)?;
1287    Ok((ty, term))
1288}
1289
1290/// The SAME-constructor arm of a derived decidable equality: decide field `0`, then `1`, …,
1291/// and only once every field agrees assemble `Eq I (C x⃗) (C y⃗)` from the field equations.
1292///
1293/// The positive proof is a CONGRUENCE built by transport: starting from `refl (C x⃗)`, step `k`
1294/// rewrites the `k`-th argument of the right-hand constructor from `xₖ` to `yₖ` along `eₖ`.
1295/// The negative one is field-`k` injectivity via `noConfusion` — which is why no field needs a
1296/// defaulted projection.
1297fn dec_eq_same_ctor(
1298    sc: &AuxScope,
1299    cname: &str,
1300    xs: &[(String, Term)],
1301    ys: &[(String, Term)],
1302    nc: &Term,
1303    premises: &[(String, Term)],
1304) -> KernelResult<Term> {
1305    let cx = sc.ctor_at(cname, xs);
1306    let cy = sc.ctor_at(cname, ys);
1307    let goal = eq3(sc.carrier.clone(), cx.clone(), cy.clone());
1308    let eqs: Vec<Term> = (0..xs.len())
1309        .map(|k| eq3(xs[k].1.clone(), var(&xs[k].0), var(&ys[k].0)))
1310        .collect();
1311
1312    // Every field's decision procedure must EXIST before any of the term is built.
1313    let decs: Vec<Term> = (0..xs.len())
1314        .map(|k| field_decider(sc, &xs[k], cname, premises))
1315        .collect::<KernelResult<Vec<_>>>()?;
1316
1317    // The congruence: `C x⃗ = C y₀…y_{k-1} xₖ…x_{m-1}` after `k` transports.
1318    let mut congruence = app(app(gl("refl"), sc.carrier.clone()), cx.clone());
1319    for k in 0..xs.len() {
1320        let rewritten = |at: Term| {
1321            let mut t = gl(cname);
1322            for n in &sc.tp_names {
1323                t = app(t, var(n));
1324            }
1325            for (q, (xn, _)) in xs.iter().enumerate() {
1326                t = app(
1327                    t,
1328                    match q.cmp(&k) {
1329                        std::cmp::Ordering::Less => var(&ys[q].0),
1330                        std::cmp::Ordering::Equal => at.clone(),
1331                        std::cmp::Ordering::Greater => var(xn),
1332                    },
1333                );
1334            }
1335            t
1336        };
1337        let motive = lam(
1338            "z",
1339            xs[k].1.clone(),
1340            lam(
1341                "_",
1342                eq3(xs[k].1.clone(), var(&xs[k].0), var("z")),
1343                eq3(sc.carrier.clone(), cx.clone(), rewritten(var("z"))),
1344            ),
1345        );
1346        congruence = apps(
1347            gl("Eq_rec_dep"),
1348            &[
1349                xs[k].1.clone(),
1350                var(&xs[k].0),
1351                motive,
1352                congruence,
1353                var(&ys[k].0),
1354                var(&format!("e{k}")),
1355            ],
1356        );
1357    }
1358
1359    // Innermost: every field agreed.
1360    let mut arm = app(app(gl("isTrue"), goal.clone()), congruence);
1361    // …wrapped outwards, one decision per field.
1362    for k in (0..xs.len()).rev() {
1363        // `eₖ` is bound by the `isTrue` case, so the accumulated congruence sees it.
1364        let positive = lam(&format!("e{k}"), eqs[k].clone(), arm);
1365        // `noConfusion (xₖ = yₖ) (C x⃗) (C y⃗) h (λe₀ … e_{m-1}. eₖ)` — field-`k` injectivity.
1366        let mut project = var(&format!("p{k}"));
1367        for q in (0..xs.len()).rev() {
1368            project = lam(&format!("p{q}"), eqs[q].clone(), project);
1369        }
1370        let inj_k = app(
1371            apps(
1372                nc.clone(),
1373                &[eqs[k].clone(), cx.clone(), cy.clone(), var("hEq")],
1374            ),
1375            project,
1376        );
1377        let negative = lam(
1378            &format!("n{k}"),
1379            not_(eqs[k].clone()),
1380            app(
1381                app(gl("isFalse"), goal.clone()),
1382                lam("hEq", goal.clone(), app(var(&format!("n{k}")), inj_k)),
1383            ),
1384        );
1385        arm = Term::Match {
1386            discriminant: Box::new(app(app(decs[k].clone(), var(&xs[k].0)), var(&ys[k].0))),
1387            motive: Box::new(lam("_", dec(eqs[k].clone()), dec(goal.clone()))),
1388            cases: vec![positive, negative],
1389        };
1390    }
1391    Ok(arm)
1392}
1393
1394/// The decision procedure for ONE constructor field: the recursion itself for a field of the
1395/// inductive, the matching premise for a type parameter, an already-registered `decEqT` for a
1396/// monomorphic `T`. Anything else is refused by name — a `Decidable` we cannot exhibit must
1397/// not be claimed, and `decEqNat` silently reused for another carrier would compare one field
1398/// and ignore the constructor tag.
1399fn field_decider(
1400    sc: &AuxScope,
1401    field: &(String, Term),
1402    cname: &str,
1403    premises: &[(String, Term)],
1404) -> KernelResult<Term> {
1405    let (fname, fty) = field;
1406    if *fty == sc.carrier {
1407        return Ok(var("rec"));
1408    }
1409    if let Term::Var(n) = fty {
1410        if let Some(i) = sc.tp_names.iter().position(|a| a == n) {
1411            return Ok(var(&premises[i].0));
1412        }
1413    }
1414    if let Term::Global(t) = fty {
1415        let name = format!("decEq{t}");
1416        if sc.known_dec_eq.contains(&name) {
1417            return Ok(gl(&name));
1418        }
1419        return Err(unsupported(format!(
1420            "field '{fname}' of '{cname}' has type '{t}', and '{name}' is not in scope: derive or \
1421             register a decidable equality for '{t}' first"
1422        )));
1423    }
1424    Err(unsupported(format!(
1425        "field '{fname}' of '{cname}' has type {fty}, which is neither the inductive itself, a \
1426         type parameter, nor a monomorphic carrier with a registered decidable equality"
1427    )))
1428}
1429
1430// =====================================================================================
1431// THE DEPENDENT QUOTIENT ELIMINATOR — DERIVED, NOT ASSUMED
1432// =====================================================================================
1433
1434/// `Quot_rec` — the DEPENDENT quotient eliminator, built from the four quotient primitives
1435/// rather than taken as a fifth one. The prelude registers exactly this body as `Quot_rec`.
1436///
1437/// **Lean does not assume it either.** `init_quot`
1438/// (`Init/Core.lean:1515`–`1527`) introduces exactly `Quot`, `Quot.mk`, `Quot.lift` and
1439/// `Quot.ind`, alongside the `Quot.sound` axiom — four constants and one axiom, not five.
1440/// `Quot.rec` is a `protected abbrev` assembled from them at `Init/Core.lean:1581`–`1611`, and
1441/// `#print axioms Quot.rec` answers `[Quot.sound]`: it costs the trusted base nothing beyond
1442/// the axiom already paid for. The recipe below is Lean's, transcribed constant for constant:
1443///
1444/// ```text
1445/// indep f a             := ⟨Quot_mk a, f a⟩              : PSigma (Quot A r) motive
1446/// indepCoherent f h a b := PSigma.eta (Quot_sound p) (h a b p)
1447/// L                     := Quot_lift A r (PSigma Q motive) indep indepCoherent
1448/// liftIndepPr1 q        : PSigma_fst (L q) = q           -- Quot_ind, then refl
1449/// Quot_rec … q          := liftIndepPr1 q ▸ PSigma_snd (L q)
1450/// ```
1451///
1452/// The two computation steps that make it work are already in the kernel: `Quot_lift … (Quot_mk
1453/// a) ⤳ indep a` is the one ι-rule quotients have, and `PSigma_fst (PSigma_mk x y) ⤳ x` is an
1454/// ordinary structure projection. So `PSigma_fst (L (Quot_mk a))` reduces to `Quot_mk a` and the
1455/// `liftIndepPr1` obligation is discharged by `refl` in every branch `Quot_ind` produces — which
1456/// is exactly why Lean's proof is `induction q using Quot.ind; exact rfl`.
1457///
1458/// `PSigma.eta` is inlined rather than registered: it is used once, and Lean's own
1459/// (`Init/Core.lean:1272`–`1276`) is two `subst`s, which is two `Eq_rec_dep` transports here.
1460///
1461/// The pair is `PSigma`, not `Sigma`, for the reason Lean's is: the carrier is `Sort u`, so the
1462/// pair lives in `Sort (max 1 u)` and `Quot_lift` reaches it through its own target level. Every
1463/// reference is a bare global whose levels the application rule solves at each use, so the only
1464/// level the body names is its carrier binder's, which β removes wherever the eliminator is
1465/// applied. The motive is `Quot A r → Type 0`, the prelude statement's own; Lean's is `Sort v`.
1466pub fn derive_quot_rec(ctx: &Context) -> KernelResult<(Term, Term)> {
1467    let body = quot_rec_body(ctx)?;
1468    let ty = infer_type(ctx, &body)?;
1469    Ok((ty, body))
1470}
1471
1472/// [`derive_quot_rec`]'s term alone, for a caller whose own gateway checks it against a stated
1473/// type — the prelude registers it this way, so the body is checked once.
1474pub(crate) fn quot_rec_body(ctx: &Context) -> KernelResult<Term> {
1475    for need in [
1476        "Quot",
1477        "Quot_mk",
1478        "Quot_lift",
1479        "Quot_ind",
1480        "Quot_sound",
1481        "PSigma",
1482        "PSigma_mk",
1483        "PSigma_fst",
1484        "PSigma_snd",
1485        "Eq",
1486        "refl",
1487        "Eq_rec_dep",
1488    ] {
1489        require_global(ctx, need, "the derived dependent quotient eliminator")?;
1490    }
1491
1492    let ty0 = Term::Sort(Universe::Type(0));
1493    let carrier = Term::Sort(Universe::Var("u".to_string()));
1494    let prop = Term::Sort(Universe::Prop);
1495    let a = || var("A");
1496    let r = || var("r");
1497    let motive = || var("motive");
1498    // `Quot A r`, the quotient being eliminated, and its class former.
1499    let q_ty = || apps(gl("Quot"), &[a(), r()]);
1500    let mk = |x: Term| apps(gl("Quot_mk"), &[a(), r(), x]);
1501    // `PSigma (Quot A r) motive` — the non-dependent carrier `Quot_lift` can actually target.
1502    let sig = || apps(gl("PSigma"), &[q_ty(), motive()]);
1503    let smk = |x: Term, y: Term| apps(gl("PSigma_mk"), &[q_ty(), motive(), x, y]);
1504    let sfst = |s: Term| apps(gl("PSigma_fst"), &[q_ty(), motive(), s]);
1505    let ssnd = |s: Term| apps(gl("PSigma_snd"), &[q_ty(), motive(), s]);
1506    let refl_at = |t: Term, x: Term| apps(gl("refl"), &[t, x]);
1507    // `e ▸ b` at the family `fam` over `carrier`, spelled with the prelude's derived J.
1508    let transport =
1509        |carrier: Term, x: Term, fam: &dyn Fn(Term) -> Term, b: Term, y: Term, e: Term| {
1510            apps(
1511                gl("Eq_rec_dep"),
1512                &[
1513                    carrier.clone(),
1514                    x.clone(),
1515                    lam(
1516                        "tgt✧",
1517                        carrier.clone(),
1518                        lam("_", eq3(carrier, x, var("tgt✧")), fam(var("tgt✧"))),
1519                    ),
1520                    b,
1521                    y,
1522                    e,
1523                ],
1524            )
1525        };
1526    let motive_at = |x: Term| app(motive(), x);
1527
1528    // The respect obligation, stated up to transport exactly as Lean's `h` is: `f a` and `f b`
1529    // inhabit DIFFERENT types, so there is no carrier to equate them at until `f a` has been
1530    // moved along `Quot_sound`.
1531    let sound_p = || {
1532        apps(
1533            gl("Quot_sound"),
1534            &[a(), r(), var("a✧"), var("b✧"), var("p✧")],
1535        )
1536    };
1537    let respect = pi(
1538        "a✧",
1539        a(),
1540        pi(
1541            "b✧",
1542            a(),
1543            pi(
1544                "p✧",
1545                apps(r(), &[var("a✧"), var("b✧")]),
1546                eq3(
1547                    motive_at(mk(var("b✧"))),
1548                    transport(
1549                        q_ty(),
1550                        mk(var("a✧")),
1551                        &motive_at,
1552                        app(var("f"), var("a✧")),
1553                        mk(var("b✧")),
1554                        sound_p(),
1555                    ),
1556                    app(var("f"), var("b✧")),
1557                ),
1558            ),
1559        ),
1560    );
1561
1562    // `PSigma.eta` at this quotient, inlined at the one instantiation that uses it:
1563    // `h₁ : a₁ = a₂` and `h₂ : h₁ ▸ b₁ = b₂` give `⟨a₁,b₁⟩ = ⟨a₂,b₂⟩`, by J on `h₁` and then
1564    // on `h₂` — Lean's `subst; subst; rfl`.
1565    let sigma_eta = |a1: Term, b1: Term, a2: Term, h1: Term, b2: Term, h2: Term| {
1566        // λb2'. λh2'. (h2' : b₁ = b2') ▸ refl ⟨a₁,b₁⟩ — the base case, where the outer
1567        // transport has already ι-reduced away on `refl`.
1568        let base = lam(
1569            "b2✧",
1570            motive_at(a1.clone()),
1571            lam(
1572                "h2✧",
1573                eq3(
1574                    motive_at(a1.clone()),
1575                    transport(
1576                        q_ty(),
1577                        a1.clone(),
1578                        &motive_at,
1579                        b1.clone(),
1580                        a1.clone(),
1581                        refl_at(q_ty(), a1.clone()),
1582                    ),
1583                    var("b2✧"),
1584                ),
1585                transport(
1586                    motive_at(a1.clone()),
1587                    b1.clone(),
1588                    &|z: Term| eq3(sig(), smk(a1.clone(), b1.clone()), smk(a1.clone(), z)),
1589                    refl_at(sig(), smk(a1.clone(), b1.clone())),
1590                    var("b2✧"),
1591                    var("h2✧"),
1592                ),
1593            ),
1594        );
1595        let fam = |y: Term| {
1596            pi(
1597                "b2✧",
1598                motive_at(y.clone()),
1599                arrow(
1600                    eq3(
1601                        motive_at(y.clone()),
1602                        transport(
1603                            q_ty(),
1604                            a1.clone(),
1605                            &motive_at,
1606                            b1.clone(),
1607                            y.clone(),
1608                            var("e✧"),
1609                        ),
1610                        var("b2✧"),
1611                    ),
1612                    eq3(sig(), smk(a1.clone(), b1.clone()), smk(y, var("b2✧"))),
1613                ),
1614            )
1615        };
1616        // The J motive mentions the equation itself (`e✧`), so it is written out rather than
1617        // routed through `transport`, whose family is equation-independent.
1618        let j_motive = lam(
1619            "tgt✧",
1620            q_ty(),
1621            lam("e✧", eq3(q_ty(), a1.clone(), var("tgt✧")), fam(var("tgt✧"))),
1622        );
1623        apps(
1624            apps(gl("Eq_rec_dep"), &[q_ty(), a1, j_motive, base, a2, h1]),
1625            &[b2, h2],
1626        )
1627    };
1628
1629    // `indep : A → PSigma (Quot A r) motive`, and its coherence.
1630    let indep = lam("a✧", a(), smk(mk(var("a✧")), app(var("f"), var("a✧"))));
1631    let indep_coherent = lam(
1632        "a✧",
1633        a(),
1634        lam(
1635            "b✧",
1636            a(),
1637            lam(
1638                "p✧",
1639                apps(r(), &[var("a✧"), var("b✧")]),
1640                sigma_eta(
1641                    mk(var("a✧")),
1642                    app(var("f"), var("a✧")),
1643                    mk(var("b✧")),
1644                    sound_p(),
1645                    app(var("f"), var("b✧")),
1646                    apps(var("h"), &[var("a✧"), var("b✧"), var("p✧")]),
1647                ),
1648            ),
1649        ),
1650    );
1651    let lifted = || {
1652        apps(
1653            gl("Quot_lift"),
1654            &[a(), r(), sig(), indep.clone(), indep_coherent.clone()],
1655        )
1656    };
1657
1658    // `liftIndepPr1 : Π(q). PSigma_fst (L q) = q` — `Quot_ind` reduces the goal to the `Quot_mk`
1659    // branch, where `L (mk a) ⤳ ⟨mk a, f a⟩` and the projection ⤳ `mk a`, so `refl` closes it.
1660    let pr1 = || {
1661        apps(
1662            gl("Quot_ind"),
1663            &[
1664                a(),
1665                r(),
1666                lam(
1667                    "q✧",
1668                    q_ty(),
1669                    eq3(q_ty(), sfst(app(lifted(), var("q✧"))), var("q✧")),
1670                ),
1671                lam("a✧", a(), refl_at(q_ty(), mk(var("a✧")))),
1672            ],
1673        )
1674    };
1675
1676    let body = lam(
1677        "A",
1678        carrier,
1679        lam(
1680            "r",
1681            arrow(a(), arrow(a(), prop)),
1682            lam(
1683                "motive",
1684                arrow(q_ty(), ty0),
1685                lam(
1686                    "f",
1687                    pi("a✧", a(), motive_at(mk(var("a✧")))),
1688                    lam(
1689                        "h",
1690                        respect,
1691                        lam(
1692                            "q",
1693                            q_ty(),
1694                            transport(
1695                                q_ty(),
1696                                sfst(app(lifted(), var("q"))),
1697                                &motive_at,
1698                                ssnd(app(lifted(), var("q"))),
1699                                var("q"),
1700                                app(pr1(), var("q")),
1701                            ),
1702                        ),
1703                    ),
1704                ),
1705            ),
1706        ),
1707    );
1708
1709    Ok(body)
1710}
1711
1712// =====================================================================================
1713// `casesOn` AND `recOn` — THE TWO CONSTANTS LEAN GENERATES THAT WE DID NOT
1714// =====================================================================================
1715
1716/// `Π(tele). body`.
1717fn pis(tele: &[(String, Term)], body: Term) -> Term {
1718    tele.iter()
1719        .rev()
1720        .fold(body, |acc, (n, t)| pi(n, t.clone(), acc))
1721}
1722
1723/// How many MINOR premises and how many INDICES `ind`'s eliminator carries.
1724///
1725/// The minor count is the whole block's constructor count, not this member's: a mutual
1726/// eliminator takes one minor per constructor of every member, because the recursion crosses
1727/// between them. The index count is this member's own.
1728fn eliminator_shape(ctx: &Context, ind: &str) -> (usize, usize) {
1729    let block: Vec<String> = match ctx.mutual_block_of(ind) {
1730        Some(b) => b.to_vec(),
1731        None => vec![ind.to_string()],
1732    };
1733    let minors = block.iter().map(|m| ctx.get_constructors(m).len()).sum();
1734    (minors, ctx.inductive_num_indices(ind))
1735}
1736
1737/// The value arity of each constructor, in the order the eliminator's minor premises take them.
1738fn minor_arities(ctx: &Context, ind: &str) -> Vec<usize> {
1739    let block: Vec<String> = match ctx.mutual_block_of(ind) {
1740        Some(b) => b.to_vec(),
1741        None => vec![ind.to_string()],
1742    };
1743    let mut out = Vec::new();
1744    for member in &block {
1745        let np = ctx.inductive_num_params(member);
1746        for (_, cty) in ctx.get_constructors(member) {
1747            let (binders, _) = peel_pis(cty);
1748            out.push(binders.len().saturating_sub(np));
1749        }
1750    }
1751    out
1752}
1753
1754/// Split `I_rec`'s telescope into `(params_and_motives, minors, indices, major)` — the four
1755/// blocks Lean's `mkRecOn` permutes (`Lean/Meta/Constructions/RecOn.lean:20-26`, whose comment
1756/// spells the layout out: "before: As Cs minor_premises indices major-premise").
1757fn split_eliminator_telescope(
1758    ctx: &Context,
1759    ind: &str,
1760    rec_ty: &Term,
1761) -> KernelResult<(
1762    Vec<(String, Term)>,
1763    Vec<(String, Term)>,
1764    Vec<(String, Term)>,
1765    (String, Term),
1766    Term,
1767)> {
1768    let (xs, residual) = peel_pis(rec_ty);
1769    let (n_minors, n_indices) = eliminator_shape(ctx, ind);
1770    if xs.len() < n_minors + n_indices + 1 {
1771        return Err(unsupported(format!(
1772            "'{ind}'s eliminator binds {} arguments, too few for {n_minors} minor premise(s), \
1773             {n_indices} index/indices and a major premise",
1774            xs.len()
1775        )));
1776    }
1777    let ac = xs.len() - n_minors - n_indices - 1;
1778    // A permutation is only well-typed if the binder NAMES stay distinguishable, and the
1779    // eliminator's own names are the only thing standing between a moved binder and the wrong
1780    // reference. Refuse rather than emit a term whose meaning depends on shadowing.
1781    let mut seen: Vec<&str> = Vec::new();
1782    for (n, _) in &xs {
1783        if n == "_" || seen.contains(&n.as_str()) {
1784            return Err(unsupported(format!(
1785                "'{ind}'s eliminator binds '{n}' anonymously or twice, so its telescope cannot be \
1786                 reordered without capture"
1787            )));
1788        }
1789        seen.push(n);
1790    }
1791    let head = xs[..ac].to_vec();
1792    let minors = xs[ac..ac + n_minors].to_vec();
1793    let indices = xs[ac + n_minors..ac + n_minors + n_indices].to_vec();
1794    let major = xs[ac + n_minors + n_indices].clone();
1795    Ok((head, minors, indices, major, residual.clone()))
1796}
1797
1798/// `I_recOn` — the eliminator with the MAJOR PREMISE moved in front of the minors, which is the
1799/// argument order `induction`/`match` elaboration wants and the one every Lean development
1800/// writes by hand.
1801///
1802/// Lean generates it at every declaration (`Lean/Elab/Inductive.lean:729`) by exactly this
1803/// permutation (`Lean/Meta/Constructions/RecOn.lean:20-31`):
1804///
1805/// ```text
1806/// before: As Cs minor_premises indices major-premise
1807/// after:  As Cs indices major-premise minor_premises
1808/// ```
1809///
1810/// It is a RESHAPING of `derive_recursor`'s answer and nothing else — every soundness gate
1811/// (the motive-sort rule, strict positivity, the termination guard that admitted the `Fix`) is
1812/// the one the eliminator already passed, and no new trusted code is added by moving binders.
1813pub fn derive_rec_on(ctx: &Context, ind: &str) -> KernelResult<(Term, Term)> {
1814    rec_on_from(ctx, ind, derive_recursor(ctx, ind)?)
1815}
1816
1817/// [`derive_rec_on`] over an eliminator that has already been derived — the shape
1818/// [`derive_auxiliaries`] uses so one declaration pays for one derivation.
1819fn rec_on_from(ctx: &Context, ind: &str, elim: (Term, Term)) -> KernelResult<(Term, Term)> {
1820    let (rec_ty, rec_tm) = elim;
1821    let (head, minors, indices, major, residual) = split_eliminator_telescope(ctx, ind, &rec_ty)?;
1822
1823    let mut reordered = head.clone();
1824    reordered.extend(indices.iter().cloned());
1825    reordered.push(major.clone());
1826    reordered.extend(minors.iter().cloned());
1827
1828    // The body applies the ORIGINAL eliminator in the ORIGINAL order.
1829    let mut original: Vec<Term> = Vec::new();
1830    for (n, _) in head.iter().chain(minors.iter()).chain(indices.iter()) {
1831        original.push(var(n));
1832    }
1833    original.push(var(&major.0));
1834    let body = lams(&reordered, apps(rec_tm, &original));
1835    certified_reshaping(ctx, ind, "recOn", body, pis(&reordered, residual))
1836}
1837
1838/// `I_casesOn` — `recOn` with the INDUCTION HYPOTHESES dropped from every minor premise.
1839///
1840/// Lean's is `@Nat.casesOn : {motive : Nat → Sort u} → (t : Nat) → motive Nat.zero →
1841/// ((n : Nat) → motive n.succ) → motive t`: the case analysis `cases h` compiles to, and the
1842/// constant every `match` elaborates through. It is generated at every declaration
1843/// (`Lean/Elab/Inductive.lean:730`).
1844///
1845/// Derived here rather than built: each minor premise keeps its FIELD binders and loses its
1846/// `ih` binders, and the body hands the original eliminator a minor that ignores the hypotheses
1847/// it was given. So `casesOn` is `rec` with the recursion thrown away, which is exactly what it
1848/// means — and it inherits every gate `rec` passed rather than opening a second door.
1849pub fn derive_cases_on(ctx: &Context, ind: &str) -> KernelResult<(Term, Term)> {
1850    cases_on_from(ctx, ind, derive_recursor(ctx, ind)?)
1851}
1852
1853/// [`derive_cases_on`] over an eliminator that has already been derived.
1854fn cases_on_from(ctx: &Context, ind: &str, elim: (Term, Term)) -> KernelResult<(Term, Term)> {
1855    let (rec_ty, rec_tm) = elim;
1856    let (head, minors, indices, major, residual) = split_eliminator_telescope(ctx, ind, &rec_ty)?;
1857    let arities = minor_arities(ctx, ind);
1858    if arities.len() != minors.len() {
1859        return Err(unsupported(format!(
1860            "'{ind}'s eliminator has {} minor premise(s) but the block declares {} constructor(s)",
1861            minors.len(),
1862            arities.len()
1863        )));
1864    }
1865
1866    // Each minor loses its `ih` binders; what is left is the constructor's own fields and the
1867    // motive instance they land at.
1868    let mut stripped: Vec<(String, Term)> = Vec::new();
1869    let mut supplied: Vec<Term> = Vec::new();
1870    for (i, (mname, mty)) in minors.iter().enumerate() {
1871        let (binders, res) = peel_pis(mty);
1872        if binders.len() < arities[i] {
1873            return Err(unsupported(format!(
1874                "'{ind}'s minor premise '{mname}' binds {} arguments, fewer than its \
1875                 constructor's {} field(s)",
1876                binders.len(),
1877                arities[i]
1878            )));
1879        }
1880        let fields = &binders[..arities[i]];
1881        let hyps = &binders[arities[i]..];
1882        stripped.push((mname.clone(), pis(fields, res.clone())));
1883        // `λfields. λihs. mname fields…` — the hypotheses are bound and dropped.
1884        let call = apps(
1885            var(mname),
1886            &fields.iter().map(|(n, _)| var(n)).collect::<Vec<_>>(),
1887        );
1888        supplied.push(lams(fields, lams(hyps, call)));
1889    }
1890
1891    let mut reordered = head.clone();
1892    reordered.extend(indices.iter().cloned());
1893    reordered.push(major.clone());
1894    reordered.extend(stripped.iter().cloned());
1895
1896    let mut original: Vec<Term> = head.iter().map(|(n, _)| var(n)).collect();
1897    original.extend(supplied);
1898    original.extend(indices.iter().map(|(n, _)| var(n)));
1899    original.push(var(&major.0));
1900    let body = lams(&reordered, apps(rec_tm, &original));
1901    certified_reshaping(ctx, ind, "casesOn", body, pis(&reordered, residual))
1902}
1903
1904/// Return a reshaped eliminator ONLY if the kernel certifies it, and only at the type the
1905/// reshaping intended.
1906///
1907/// The type here is CONSTRUCTED — a permutation of the eliminator's telescope — where every
1908/// other `derive_*` in this module reports `infer_type` of the term it built. A constructed type
1909/// that the term does not have is the one failure mode a reshaping can hide: `derive_auxiliaries`
1910/// registers what a `derive_*` returns WITHOUT re-checking it, so an off-by-one in the
1911/// permutation would land a constant whose declared type is not its real one, and the first
1912/// proof to cite it would be the one that discovers it. Asking the kernel makes the reshaping
1913/// fail-closed, and comparing the two makes a SILENTLY different answer impossible.
1914fn certified_reshaping(
1915    ctx: &Context,
1916    ind: &str,
1917    what: &str,
1918    body: Term,
1919    intended: Term,
1920) -> KernelResult<(Term, Term)> {
1921    let certified = infer_type(ctx, &body)?;
1922    if !crate::type_checker::is_subtype(ctx, &certified, &intended)
1923        || !crate::type_checker::is_subtype(ctx, &intended, &certified)
1924    {
1925        return Err(unsupported(format!(
1926            "'{ind}'s {what} was reshaped to {intended} but the kernel certifies it at              {certified} — the telescope permutation is wrong"
1927        )));
1928    }
1929    Ok((certified, body))
1930}
1931
1932/// The shared scope every derived auxiliary of a NON-INDEXED inductive is built in: the
1933/// inductive's uniform parameters renamed `A0 … A_{p-1}`, the applied carrier `I A0 …
1934/// A_{p-1}`, the sort its arity ends in, and its constructors in registration order.
1935struct AuxScope {
1936    ind: String,
1937    num_params: usize,
1938    tp_names: Vec<String>,
1939    param_types: Vec<Term>,
1940    ind_sort: Term,
1941    carrier: Term,
1942    ctors: Vec<(String, Term)>,
1943    /// The `decEq…` names already in scope, so a field's decision procedure can be resolved
1944    /// without carrying the whole context around.
1945    known_dec_eq: Vec<String>,
1946}
1947
1948impl AuxScope {
1949    fn new(ctx: &Context, ind: &str) -> KernelResult<AuxScope> {
1950        if !ctx.is_inductive(ind) {
1951            return Err(KernelError::UnboundVariable(ind.to_string()));
1952        }
1953        let full = ctx
1954            .get_global(ind)
1955            .ok_or_else(|| KernelError::UnboundVariable(ind.to_string()))?
1956            .clone();
1957        let (arity, sort) = peel_pis(&full);
1958        let num_params = ctx.inductive_num_params(ind).min(arity.len());
1959        if arity.len() > num_params {
1960            return Err(unsupported(format!(
1961                "'{ind}' is an INDEXED family with {} index binder(s). Every auxiliary here gives \
1962                 one branch per CONSTRUCTOR PAIR, and the pairs whose declared result indices \
1963                 cannot unify have no inhabitant to offer — discharging them needs an index \
1964                 unifier, which this kernel's positional `Match` (no patterns, no wildcard, \
1965                 coverage by count) does not have",
1966                arity.len() - num_params
1967            )));
1968        }
1969        let tp_names: Vec<String> = (0..num_params).map(|i| format!("A{i}")).collect();
1970        let param_types: Vec<Term> = (0..num_params)
1971            .map(|i| rename_tele_types(&arity[i].1, &arity[..i], &tp_names))
1972            .collect();
1973        let carrier = tp_names
1974            .iter()
1975            .fold(Term::Global(ind.to_string()), |acc, n| app(acc, var(n)));
1976        let ctors = ctx
1977            .get_constructors(ind)
1978            .iter()
1979            .map(|(n, t)| (n.to_string(), (*t).clone()))
1980            .collect();
1981        let known_dec_eq = ctx
1982            .iter_definitions()
1983            .map(|(n, _, _)| n.to_string())
1984            .filter(|n| n.starts_with("decEq"))
1985            .collect();
1986        Ok(AuxScope {
1987            ind: ind.to_string(),
1988            num_params,
1989            tp_names,
1990            param_types,
1991            ind_sort: sort.clone(),
1992            carrier,
1993            ctors,
1994            known_dec_eq,
1995        })
1996    }
1997
1998    /// Refuse an auxiliary that has to state an EQUATION over the inductive unless the carrier
1999    /// is one `Eq` can be applied to.
2000    ///
2001    /// On a `Prop` this is not a missing derivation but a category error: proof irrelevance
2002    /// makes any two inhabitants of a proposition definitionally equal, so constructor
2003    /// disjointness is FALSE there. Above `Type 0` it is the prelude's `Eq` that stops, not us.
2004    fn require_equatable_carrier(&self) -> KernelResult<()> {
2005        match &self.ind_sort {
2006            Term::Sort(Universe::Type(0)) => Ok(()),
2007            Term::Sort(level) if *level == Universe::SProp || level.equiv(&Universe::Prop) => {
2008                Err(unsupported(format!(
2009                "'{}' is a PROPOSITION: proof irrelevance identifies any two of its inhabitants, \
2010                 so constructor disjointness is FALSE there. That is a category error, not a \
2011                 derivation we are missing",
2012                self.ind
2013            )))
2014            }
2015            other => Err(unsupported(format!(
2016                "'{}' lives in {other}, and the prelude's `Eq` quantifies over a `Type 0` carrier \
2017                 only — `Eq {} …` cannot be stated at all. Closing this needs a \
2018                 universe-polymorphic `Eq`, not a change to the derivation",
2019                self.ind, self.ind
2020            ))),
2021        }
2022    }
2023
2024    /// The course-of-values auxiliaries package the subterms of ONE type. A mutual block's
2025    /// below would have to package every member's, keyed by member — refuse rather than emit
2026    /// one that silently drops the siblings.
2027    fn require_no_mutual_block(&self, ctx: &Context, what: &str) -> KernelResult<()> {
2028        match ctx.mutual_block_of(&self.ind) {
2029            None => Ok(()),
2030            Some(block) => Err(unsupported(format!(
2031                "'{}' is a member of the mutual block {block:?}: its `{what}` would have to carry \
2032                 one package per member, keyed by which member each subterm belongs to. The plain \
2033                 mutual recursor already handles the block; this does not",
2034                self.ind
2035            ))),
2036        }
2037    }
2038
2039    /// Wrap `body` in the parameter λ-telescope `λA0 … λA_{p-1}`.
2040    fn close_lams(&self, mut body: Term) -> Term {
2041        for i in (0..self.num_params).rev() {
2042            body = lam(&self.tp_names[i], self.param_types[i].clone(), body);
2043        }
2044        body
2045    }
2046
2047    /// `C A0 … A_{p-1} f0 … f_{m-1}` over the given field binders.
2048    fn ctor_at(&self, cname: &str, fields: &[(String, Term)]) -> Term {
2049        let mut t = Term::Global(cname.to_string());
2050        for n in &self.tp_names {
2051            t = app(t, var(n));
2052        }
2053        for (n, _) in fields {
2054            t = app(t, var(n));
2055        }
2056        t
2057    }
2058}
2059
2060/// Extend `ctx` with `ind`'s no-confusion pair, deriving whichever half is absent, so a term
2061/// that CITES them can be checked. The caller of the outer derivation still has to register
2062/// both — hence [`derive_auxiliaries`]'s order.
2063fn with_no_confusion(ctx: &Context, ind: &str) -> KernelResult<Context> {
2064    let mut env = ctx.clone();
2065    let nct = format!("{ind}_noConfusionType");
2066    if env.get_global(&nct).is_none() {
2067        let (t, b) = derive_no_confusion_type(ctx, ind)?;
2068        env.add_definition(nct, t, b);
2069    }
2070    let nc = format!("{ind}_noConfusion");
2071    if env.get_global(&nc).is_none() {
2072        let (t, b) = derive_no_confusion(&env, ind)?;
2073        env.add_definition(nc, t, b);
2074    }
2075    Ok(env)
2076}
2077
2078/// One constructor's VALUE fields, expressed in the auxiliary's scope: the inductive's
2079/// parameters renamed to `A0 …`, and the k-th field named `{prefix}{k}` — so two copies of the
2080/// same telescope, one per side of an equation, never capture each other.
2081fn ctor_value_fields(
2082    ctor_type: &Term,
2083    owner: &str,
2084    num_params: usize,
2085    tp_names: &[String],
2086    prefix: &str,
2087) -> KernelResult<Vec<(String, Term)>> {
2088    let (params, residual) = peel_pis(ctor_type);
2089    if params.len() < num_params {
2090        return Err(unsupported(format!(
2091            "a constructor of '{owner}' has fewer binders than the inductive has parameters"
2092        )));
2093    }
2094    if head_global(residual) != Some(owner) {
2095        return Err(unsupported(format!(
2096            "constructor result {residual} is not the inductive '{owner}'"
2097        )));
2098    }
2099    let (type_params, value_params) = params.split_at(num_params);
2100    let mut out: Vec<(String, Term)> = Vec::with_capacity(value_params.len());
2101    for (k, (_, ty)) in value_params.iter().enumerate() {
2102        let mut t = ty.clone();
2103        for (i, (tp, _)) in type_params.iter().enumerate() {
2104            if tp != "_" {
2105                t = subst_name(&t, tp, &var(&tp_names[i]));
2106            }
2107        }
2108        for (j, (vj, _)) in value_params.iter().enumerate().take(k) {
2109            if vj != "_" {
2110                t = subst_name(&t, vj, &var(&format!("{prefix}{j}")));
2111            }
2112        }
2113        out.push((format!("{prefix}{k}"), t));
2114    }
2115    Ok(out)
2116}
2117
2118/// Refuse a DEPENDENT field, whose two copies do not even inhabit the same type.
2119///
2120/// The check is exactly "the two renamings agree": the only difference between the `x` and `y`
2121/// telescopes is which earlier field names appear, so the k-th types differ IFF the k-th field
2122/// mentions an earlier one. `xₖ = yₖ` would then be heterogeneous.
2123fn homogeneous_fields(
2124    xs: &[(String, Term)],
2125    ys: &[(String, Term)],
2126    cname: &str,
2127) -> KernelResult<()> {
2128    for (k, ((_, tx), (_, ty))) in xs.iter().zip(ys.iter()).enumerate() {
2129        if tx != ty {
2130            return Err(unsupported(format!(
2131                "field {k} of '{cname}' has type {tx} on one side of the equation and {ty} on the \
2132                 other — a DEPENDENT field, whose two instances do not inhabit the same type. Its \
2133                 equation needs heterogeneous equality (`HEq`), which the prelude does not carry"
2134            )));
2135        }
2136    }
2137    Ok(())
2138}
2139
2140/// A recursive field of one constructor, as `below`/`brecOn` see it: the field's binder name
2141/// and, for a strictly-positive FUNCTIONAL field `Π(z:B…). I A…`, that domain telescope.
2142struct RecField {
2143    field: String,
2144    tele: Vec<(String, Term)>,
2145}
2146
2147/// The recursive fields of one constructor, in order.
2148///
2149/// A recursive occurrence must be the carrier at the inductive's OWN parameters: a NESTED
2150/// occurrence (`I` under another container) is refused, because the package would have to
2151/// recurse through that container's own below. A non-recursive field that merely mentions the
2152/// inductive is refused for the same reason — silently skipping it would produce a `below`
2153/// that is missing a subterm the step function is entitled to.
2154fn recursive_fields(
2155    sc: &AuxScope,
2156    xs: &[(String, Term)],
2157    cname: &str,
2158) -> KernelResult<Vec<RecField>> {
2159    let mut out = Vec::new();
2160    for (fname, fty) in xs {
2161        let (tele, occ) = peel_pis(fty);
2162        if *occ == sc.carrier {
2163            out.push(RecField {
2164                field: fname.clone(),
2165                tele,
2166            });
2167            continue;
2168        }
2169        if mentions_global(fty, &sc.ind) {
2170            return Err(unsupported(format!(
2171                "field '{fname}' of '{cname}' mentions '{}' somewhere other than as a direct \
2172                 recursive occurrence ({fty}): a course-of-values package would have to recurse \
2173                 through the container it is nested under",
2174                sc.ind
2175            )));
2176        }
2177    }
2178    Ok(out)
2179}
2180
2181/// One below-package ENTRY's type: `Π(z:B…). Prod (motive (xⱼ z…)) (<below> (xⱼ z…))`.
2182fn entry_type(rf: &RecField, below_at: &dyn Fn(Term) -> Term) -> Term {
2183    let applied = rf
2184        .tele
2185        .iter()
2186        .fold(var(&rf.field), |acc, (n, _)| app(acc, var(n)));
2187    let mut t = prod(app(var("motive"), applied.clone()), below_at(applied));
2188    for (n, ty) in rf.tele.iter().rev() {
2189        t = pi(n, ty.clone(), t);
2190    }
2191    t
2192}
2193
2194/// One below-package ENTRY's value: `λz…. aux (xⱼ z…)` — literally the recursive result, which
2195/// is why the entry's type is `Prod (motive …) (below …)` and not a repacking of it.
2196fn entry_value(rf: &RecField, aux: &str) -> Term {
2197    let applied = rf
2198        .tele
2199        .iter()
2200        .fold(var(&rf.field), |acc, (n, _)| app(acc, var(n)));
2201    let mut v = app(var(aux), applied);
2202    for (n, ty) in rf.tele.iter().rev() {
2203        v = lam(n, ty.clone(), v);
2204    }
2205    v
2206}
2207
2208/// The right-nested `Prod` of the entry types, closed with `Unit` (so a constructor with no
2209/// recursive fields has the package `Unit` rather than no package).
2210fn below_package_type(entries: &[Term]) -> Term {
2211    entries
2212        .iter()
2213        .rev()
2214        .fold(gl("Unit"), |acc, e| prod(e.clone(), acc))
2215}
2216
2217/// The matching value: `Prod_mk eₜ restₜ e rest`, closed with `Tt`.
2218fn below_package_value(entries: &[(Term, Term)]) -> Term {
2219    let mut ty = gl("Unit");
2220    let mut val = gl("Tt");
2221    for (e_ty, e_val) in entries.iter().rev() {
2222        val = apps(
2223            gl("Prod_mk"),
2224            &[e_ty.clone(), ty.clone(), e_val.clone(), val],
2225        );
2226        ty = prod(e_ty.clone(), ty);
2227    }
2228    val
2229}
2230
2231/// Does `t` mention the global `name` anywhere?
2232fn mentions_global(t: &Term, name: &str) -> bool {
2233    match t {
2234        Term::Global(n) | Term::Const { name: n, .. } => n == name,
2235        Term::Var(_) | Term::Sort(_) | Term::Lit(_) | Term::Hole => false,
2236        Term::Pi {
2237            param_type,
2238            body_type,
2239            ..
2240        } => mentions_global(param_type, name) || mentions_global(body_type, name),
2241        Term::Lambda {
2242            param_type, body, ..
2243        } => mentions_global(param_type, name) || mentions_global(body, name),
2244        Term::App(f, a) => mentions_global(f, name) || mentions_global(a, name),
2245        Term::Match {
2246            discriminant,
2247            motive,
2248            cases,
2249        } => {
2250            mentions_global(discriminant, name)
2251                || mentions_global(motive, name)
2252                || cases.iter().any(|c| mentions_global(c, name))
2253        }
2254        Term::Fix { body, .. } => mentions_global(body, name),
2255        Term::MutualFix { defs, .. } => defs.iter().any(|(_, b)| mentions_global(b, name)),
2256        Term::Let {
2257            ty, value, body, ..
2258        } => {
2259            mentions_global(ty, name) || mentions_global(value, name) || mentions_global(body, name)
2260        }
2261        Term::Annotated { term, .. } => mentions_global(term, name),
2262    }
2263}
2264
2265/// A derivation this kernel declines to fake, with the reason. Never an axiom: a missing
2266/// auxiliary must stay visible as a gap, not reappear as an assumption.
2267fn unsupported(why: String) -> KernelError {
2268    KernelError::CertificationError(format!("auto-derive: {why}"))
2269}
2270
2271/// Refuse early, naming the role, when a derivation's prerequisite is not in scope.
2272fn require_global(ctx: &Context, name: &str, role: &str) -> KernelResult<()> {
2273    if ctx.get_global(name).is_some() {
2274        Ok(())
2275    } else {
2276        Err(unsupported(format!(
2277            "'{name}' is not in scope, and it is {role}"
2278        )))
2279    }
2280}
2281
2282/// The motive-sort rule with an optional level PARAMETER for the one arm that may carry one.
2283///
2284/// An inductive whose sort is provably above Prop may eliminate into the
2285/// independent motive level; a subsingleton Prop uses its existing large-elimination
2286/// permission. Other sorts keep the restrictions of the monomorphic rule.
2287fn motive_target_at(ctx: &Context, ind: &str, ind_sort: &Term, level: Option<&String>) -> Term {
2288    let Some(u) = level else {
2289        return motive_target(ctx, ind, ind_sort);
2290    };
2291    match ind_sort {
2292        // The universe solver proves the carrier cannot become Prop, including
2293        // symbolic successor and maximum levels.
2294        Term::Sort(sort) if Universe::Type(0).is_subtype_of(sort) => {
2295            Term::Sort(Universe::Var(u.clone()))
2296        }
2297        // A SUBSINGLETON `Prop` is already licensed for large elimination — that licence is what
2298        // the monomorphic rule spends on `Type 0`, and Lean spends it on a parameter instead
2299        // (`Eq.rec.{u}`, `False.rec.{u}`, `And.rec.{u}`). Parameterising it grants no elimination
2300        // the `Type 0` arm did not already grant; it grants the LEVELS of it. The subsingleton
2301        // test is the gate, and it is asked here exactly as the monomorphic rule asks it.
2302        Term::Sort(sort)
2303            if !matches!(sort, Universe::SProp)
2304                && crate::type_checker::is_subsingleton_prop(ctx, ind).unwrap_or(false) =>
2305        {
2306            Term::Sort(Universe::Var(u.clone()))
2307        }
2308        // Everything else is a gate, not a ceiling: a multi-constructor `Prop` keeps `Prop`,
2309        // `SProp` keeps `SProp`, and an inductive whose own sort is already a level variable keeps
2310        // THAT one rather than gaining a second, independently-instantiable level.
2311        _ => motive_target(ctx, ind, ind_sort),
2312    }
2313}
2314
2315/// **THE MOTIVE-SORT RULE — stated once, and the same rule for a standalone inductive and for a
2316/// member of a mutual block.**
2317///
2318/// > A derived eliminator's motive targets the inductive's OWN sort.
2319///
2320/// Concretely its own sort, not a level the recursor invents: `Nat : Type 0` gets
2321/// `P : Nat → Type 0`, an inductive declared at `Type 1` gets `Type 1` — the level its own
2322/// constructor fields live at, which is the whole reason it was declared one level up. A motive
2323/// pinned BELOW the inductive's sort accepts the declaration and leaves the type unusable; a
2324/// motive at a free level variable is a DIFFERENT declaration — a universe-polymorphic one — and
2325/// saying so in a monomorphic eliminator's type loses the concrete instance without gaining the
2326/// polymorphic one, because `Type 0 ⋠ u` (a variable ranges over `Prop` too).
2327///
2328/// The polymorphic eliminator is a real and separate artefact:
2329/// [`derive_recursor_universe_poly`] builds `I_rec.{u} : Π(motive : I → Sort u). …` with `u` an
2330/// explicit level PARAMETER, to be registered through [`Context::add_universe_poly`] and
2331/// instantiated at each use. Monomorphic and polymorphic are two declarations, not two spellings
2332/// of one, and this function is the monomorphic one.
2333///
2334/// The four arms below are each a SOUNDNESS gate rather than a limitation:
2335/// - A **multi-constructor `Prop`** keeps its `Prop`-restricted induction principle:
2336///   eliminating it into `Type` would extract computational content from a proof.
2337/// - A **subsingleton `Prop`** gets `Type 0` — `Eq`'s J and `False`'s ex falso are the whole
2338///   reason the subsingleton rule exists, and folding this into the general arm would return
2339///   `Prop` and destroy large elimination.
2340/// - **`SProp`** eliminates ONLY into `SProp`: definitional irrelevance equates every
2341///   inhabitant, so a match out of one into a relevant sort equates its branches. Matches the
2342///   gate in `type_checker.rs`/`recheck.rs`.
2343/// - An inductive whose own sort is a level VARIABLE (`Box.{u} : Sort u → Sort u`) keeps THAT
2344///   variable — it is the inductive's own parameter, instantiated together with the inductive,
2345///   never a free level of the eliminator's own. A free one could be instantiated at `Prop`
2346///   independently, which is large elimination out of a proposition: the gate above, defeated by
2347///   an instantiation.
2348fn motive_target(ctx: &Context, ind: &str, ind_sort: &Term) -> Term {
2349    match ind_sort {
2350        Term::Sort(level)
2351            if level.equiv(&Universe::Prop)
2352                && !crate::type_checker::is_subsingleton_prop(ctx, ind).unwrap_or(false) =>
2353        {
2354            Term::Sort(Universe::Prop)
2355        }
2356        Term::Sort(level) if level.equiv(&Universe::Prop) => Term::Sort(Universe::Type(0)),
2357        Term::Sort(Universe::SProp) => Term::Sort(Universe::SProp),
2358        Term::Sort(u) => Term::Sort(u.clone()),
2359        _ => Term::Sort(Universe::Type(0)),
2360    }
2361}
2362
2363/// `count` fresh universe-PARAMETER names for the motives of `ind`'s (block's) polymorphic
2364/// eliminator — one per motive, so a mutual member is never forced to eliminate at its sibling's
2365/// level just for being declared in company.
2366///
2367/// These are ordinary declaration parameters (`u`, `u1`, …), not metavariables: the artefact
2368/// being built is a universe-polymorphic DECLARATION, whose levels are supplied by the reference
2369/// (`Const { levels }`) or introduced as metavariables by the application rule at a bare
2370/// `Global`. Spelling them as metavariables here would claim they are already solvable, which at
2371/// a declaration is exactly backwards.
2372///
2373/// The names avoid every level variable the block's arities and constructors already mention:
2374/// reusing one would CAPTURE it, so instantiating the motive's level would silently instantiate
2375/// the inductive's and `Box.{u}`'s eliminator would be pinned to one level again.
2376fn fresh_motive_levels(ctx: &Context, ind: &str, count: usize) -> Vec<String> {
2377    let block: Vec<String> = match ctx.mutual_block_of(ind) {
2378        Some(b) => b.to_vec(),
2379        None => vec![ind.to_string()],
2380    };
2381    let mut used: std::collections::HashSet<String> = std::collections::HashSet::new();
2382    for name in &block {
2383        if let Some((parameters, _)) = ctx.poly_declaration(name) {
2384            used.extend(parameters.iter().cloned());
2385        }
2386        if let Some(t) = ctx.get_global(name) {
2387            used.extend(crate::term::free_level_vars(t));
2388        }
2389        for (_, t) in ctx.get_constructors(name) {
2390            used.extend(crate::term::free_level_vars(t));
2391        }
2392    }
2393    let mut out = Vec::with_capacity(count);
2394    let mut next = 0usize;
2395    while out.len() < count {
2396        let cand = if next == 0 {
2397            "u".to_string()
2398        } else {
2399            format!("u{next}")
2400        };
2401        next += 1;
2402        if !used.contains(&cand) {
2403            used.insert(cand.clone());
2404            out.push(cand);
2405        }
2406    }
2407    out
2408}
2409
2410/// A constructor's shape in the recursor's scope: the value-argument types, whether each is
2411/// recursive (and if so, at which INDEX arguments), and the index arguments of the
2412/// constructor's own result. Names are already the recursor's (`A0…`, `a0…`).
2413struct CtorAnalysis {
2414    value_types: Vec<Term>,
2415    /// `Some(occ)` if value argument `j` is a recursive occurrence — either the DIRECT
2416    /// form `I A… e…` (`occ.tele` empty) or the strictly-positive FUNCTIONAL form
2417    /// `Π(z:B…). I A… e…` (`occ.tele` = the `(z, B)` binders), as in `Acc_intro`'s
2418    /// `Π(y). R y x → Acc A R y`. `None` for a non-recursive argument.
2419    recursive: Vec<Option<RecOcc>>,
2420    /// The index arguments of the constructor's result `I A… e…` (empty when non-indexed).
2421    result_indices: Vec<Term>,
2422}
2423
2424/// A recursive occurrence in a constructor argument: WHICH block member it is an
2425/// occurrence of (`0` for a standalone inductive — the whole block is itself), the
2426/// domain telescope of a functional argument (empty for a direct argument), and the
2427/// occurrence's index arguments (in scope of the telescope).
2428struct RecOcc {
2429    member: usize,
2430    tele: Vec<(String, Term)>,
2431    indices: Vec<Term>,
2432}
2433
2434/// Analyse a constructor in the recursor's scope. Its leading `num_params` parameters are
2435/// the inductive's parameters (renamed to `A₀ … A_{p-1}`); the rest are value arguments
2436/// (renamed `a₀ … aₘ`). A value argument is recursive iff its (rewritten) type's head is
2437/// the inductive, and we record that occurrence's INDEX arguments. We also record the
2438/// constructor result's own index arguments — for `refl : Π(A). Π(x). Eq A x x` the value
2439/// arguments are empty and the result index is `[x]`, so the refl case demands `P x (refl
2440/// A x)`.
2441fn constructor_analysis(
2442    ctx: &Context,
2443    ctor_type: &Term,
2444    owner: &str,
2445    block: &[&str],
2446    num_params: usize,
2447    tp_names: &[String],
2448) -> KernelResult<CtorAnalysis> {
2449    let (params, residual) = peel_pis(ctor_type);
2450    if params.len() < num_params {
2451        return Err(KernelError::CertificationError(format!(
2452            "auto-recursor: constructor of '{}' has fewer parameters than the inductive",
2453            owner
2454        )));
2455    }
2456    if head_global(residual) != Some(owner) {
2457        return Err(KernelError::CertificationError(format!(
2458            "auto-recursor: constructor result {} is not the inductive '{}'",
2459            residual, owner
2460        )));
2461    }
2462    let (type_params, value_params) = params.split_at(num_params);
2463
2464    // Rewrite a term from the constructor's scope to the recursor's: parameter names →
2465    // `A_i`, and the first `upto` value names → `a_k`.
2466    let rewrite = |t: &Term, upto: usize| -> Term {
2467        let mut out = t.clone();
2468        for (i, (tp_orig, _)) in type_params.iter().enumerate() {
2469            if tp_orig != "_" {
2470                out = subst_name(&out, tp_orig, &var(&tp_names[i]));
2471            }
2472        }
2473        for (kk, (vk_orig, _)) in value_params.iter().enumerate().take(upto) {
2474            if vk_orig != "_" {
2475                out = subst_name(&out, vk_orig, &var(&format!("a{kk}")));
2476            }
2477        }
2478        out
2479    };
2480
2481    let mut value_types = Vec::with_capacity(value_params.len());
2482    let mut recursive = Vec::with_capacity(value_params.len());
2483    for (j, (_, ty)) in value_params.iter().enumerate() {
2484        let t = rewrite(ty, j);
2485        // Peel any functional telescope: a strictly-positive argument may be
2486        // `Π(z:B…). I A… e…` (Acc's `Π(y). R y x → Acc A R y`) as well as the
2487        // direct `I A… e…`. The occurrence is recursive iff, after peeling, the
2488        // head is the inductive.
2489        // Recursive fields may be hidden behind reducible aliases. Normalize only
2490        // the field used for occurrence analysis: the original constructor result
2491        // indices must retain their syntax for singleton/large-elimination checks.
2492        if !crate::positivity::mentions_inductive_block(ctx, block, &t) {
2493            recursive.push(None);
2494            value_types.push(t);
2495            continue;
2496        }
2497        let reduced = crate::normalize_checked(ctx, &t).map_err(|(_, reason)| {
2498            KernelError::CertificationError(format!(
2499                "auto-recursor: recursive-field normalization unfinished: {reason:?}"
2500            ))
2501        })?;
2502        let (tele, occ) = peel_pis(&reduced);
2503        // Recursive iff the occurrence's head is ANY block member; record which one so
2504        // the minor premise's IH and the recursive call route to that member's motive/fix.
2505        if let Some(member) = head_global(occ).and_then(|h| block.iter().position(|m| *m == h)) {
2506            let indices: Vec<Term> = app_args(occ).into_iter().skip(num_params).collect();
2507            recursive.push(Some(RecOcc {
2508                member,
2509                tele,
2510                indices,
2511            }));
2512        } else {
2513            recursive.push(None);
2514        }
2515        value_types.push(t);
2516    }
2517
2518    // The constructor result's own index arguments, closed over all value arguments.
2519    let result_indices: Vec<Term> = app_args(residual)
2520        .into_iter()
2521        .skip(num_params)
2522        .map(|e| rewrite(&e, value_params.len()))
2523        .collect();
2524
2525    Ok(CtorAnalysis {
2526        value_types,
2527        recursive,
2528        result_indices,
2529    })
2530}
2531
2532/// The minor-premise type for one constructor:
2533/// `Π(a₀:T₀)…Π(aₘ:Tₘ). Π(IHⱼ : P eⱼ… aⱼ per recursive arg). P r… (C A… a₀ … aₘ)`,
2534/// where `r…` are the constructor's result indices and `eⱼ…` the recursive occurrence's.
2535fn minor_type(
2536    ctx: &Context,
2537    owner_motive: &str,
2538    motive_names: &[String],
2539    cname: &str,
2540    tp_names: &[String],
2541    an: &CtorAnalysis,
2542) -> Term {
2543    let mut ctor_applied = declaration_head(ctx, cname);
2544    for name in tp_names {
2545        ctor_applied = app(ctor_applied, var(name));
2546    }
2547    for j in 0..an.value_types.len() {
2548        ctor_applied = app(ctor_applied, var(&format!("a{j}")));
2549    }
2550    // The OWNER's motive applied to the constructor's result indices, then the value.
2551    let mut body = var(owner_motive);
2552    for e in &an.result_indices {
2553        body = app(body, e.clone());
2554    }
2555    body = app(body, ctor_applied);
2556    // One induction hypothesis per recursive argument, using the motive of the block
2557    // MEMBER the occurrence is of (self or sibling). For a DIRECT occurrence it is
2558    // `P_member (its indices) aⱼ`; for a FUNCTIONAL occurrence `aⱼ : Π(z:B…). I e…`
2559    // it is `Π(z:B…). P_member (its indices) (aⱼ z…)`.
2560    for j in (0..an.value_types.len()).rev() {
2561        if let Some(occ) = &an.recursive[j] {
2562            let mut ih = var(&motive_names[occ.member]);
2563            for e in &occ.indices {
2564                ih = app(ih, e.clone());
2565            }
2566            let mut aj = var(&format!("a{j}"));
2567            for (tn, _) in &occ.tele {
2568                aj = app(aj, var(tn));
2569            }
2570            ih = app(ih, aj);
2571            for (tn, tt) in occ.tele.iter().rev() {
2572                ih = pi(tn, tt.clone(), ih);
2573            }
2574            body = pi(&format!("ih{j}"), ih, body);
2575        }
2576    }
2577    for j in (0..an.value_types.len()).rev() {
2578        body = pi(&format!("a{j}"), an.value_types[j].clone(), body);
2579    }
2580    body
2581}
2582
2583/// The `match` case term for one constructor (binds only the VALUE arguments — the
2584/// parameters are fixed by the discriminant):
2585/// `λa₀ … λaₘ. fᵢ a₀ … aₘ (rec eⱼ… aⱼ)…`, where the recursive call carries the recursive
2586/// occurrence's index arguments so it lands at the right motive instance.
2587fn case_term(
2588    cname: &str,
2589    _tp_names: &[String],
2590    an: &CtorAnalysis,
2591    fi: &str,
2592    rec_names: &[String],
2593) -> Term {
2594    let _ = cname;
2595    let mut body = var(fi);
2596    for j in 0..an.value_types.len() {
2597        body = app(body, var(&format!("a{j}")));
2598    }
2599    for j in 0..an.value_types.len() {
2600        if let Some(occ) = &an.recursive[j] {
2601            // DIRECT: `rec (its indices) aⱼ`. FUNCTIONAL: `λ(z:B…). rec (its
2602            // indices) (aⱼ z…)` — recurse on each sub-structure the accessibility
2603            // function yields. The recursive call's structural argument `aⱼ z…`
2604            // is an APPLICATION of the smaller field `aⱼ`, which the guard admits
2605            // (an application headed by a smaller variable is smaller). The call routes
2606            // to the fixpoint of the block MEMBER the occurrence is of.
2607            let mut call = var(&rec_names[occ.member]);
2608            for e in &occ.indices {
2609                call = app(call, e.clone());
2610            }
2611            let mut aj = var(&format!("a{j}"));
2612            for (tn, _) in &occ.tele {
2613                aj = app(aj, var(tn));
2614            }
2615            call = app(call, aj);
2616            for (tn, tt) in occ.tele.iter().rev() {
2617                call = lam(tn, tt.clone(), call);
2618            }
2619            body = app(body, call);
2620        }
2621    }
2622    for j in (0..an.value_types.len()).rev() {
2623        body = lam(&format!("a{j}"), an.value_types[j].clone(), body);
2624    }
2625    body
2626}
2627
2628/// Rewrite an inductive-parameter binder type from the declaration's scope into the
2629/// recursor's: each of the earlier parameter binders `tele[i]` becomes `names[i]`.
2630fn rename_tele_types(ty: &Term, tele: &[(String, Term)], names: &[String]) -> Term {
2631    let mut out = ty.clone();
2632    for (i, (orig, _)) in tele.iter().enumerate() {
2633        if orig != "_" {
2634            out = subst_name(&out, orig, &var(&names[i]));
2635        }
2636    }
2637    out
2638}
2639
2640/// Rewrite an index binder type's references to the EARLIER index binders `tele[i]` to the
2641/// recursor-scope `names[i]` (parameters must already be renamed).
2642fn rename_index_refs(ty: &Term, tele: &[(String, Term)], names: &[String]) -> Term {
2643    rename_tele_types(ty, tele, names)
2644}
2645
2646/// The argument spine of an application `f a b c` → `[a, b, c]` (`[]` for a non-application).
2647fn app_args(t: &Term) -> Vec<Term> {
2648    let mut args = Vec::new();
2649    let mut cur = t;
2650    while let Term::App(f, a) = cur {
2651        args.push((**a).clone());
2652        cur = f;
2653    }
2654    args.reverse();
2655    args
2656}
2657
2658/// Peel a term's leading `Π`s into `(name, type)` pairs plus the residual.
2659fn peel_pis(t: &Term) -> (Vec<(String, Term)>, &Term) {
2660    let mut params = Vec::new();
2661    let mut cur = t;
2662    while let Term::Pi {
2663        param,
2664        param_type,
2665        body_type,
2666    } = cur
2667    {
2668        params.push((param.clone(), (**param_type).clone()));
2669        cur = body_type;
2670    }
2671    (params, cur)
2672}
2673
2674/// Preserve a registered declaration's universe telescope in generated references.
2675fn declaration_head(ctx: &Context, name: &str) -> Term {
2676    match ctx.poly_declaration(name) {
2677        Some((params, _)) if !params.is_empty() => Term::Const {
2678            name: name.to_string(),
2679            levels: params.iter().cloned().map(Universe::Var).collect(),
2680        },
2681        _ => Term::Global(name.to_string()),
2682    }
2683}
2684
2685/// The global or universe-applied constant at the head of an application spine, if any (`List A B` → `List`).
2686fn head_global(t: &Term) -> Option<&str> {
2687    let mut cur = t;
2688    while let Term::App(f, _) = cur {
2689        cur = f;
2690    }
2691    match cur {
2692        Term::Global(n) | Term::Const { name: n, .. } => Some(n),
2693        _ => None,
2694    }
2695}
2696
2697/// Substitute the free variable `old` by `repl` (binder-respecting).
2698fn subst_name(t: &Term, old: &str, repl: &Term) -> Term {
2699    match t {
2700        Term::Var(n) if n == old => repl.clone(),
2701        Term::Var(_)
2702        | Term::Global(_)
2703        | Term::Sort(_)
2704        | Term::Lit(_)
2705        | Term::Hole
2706        | Term::Const { .. } => t.clone(),
2707        Term::Pi {
2708            param,
2709            param_type,
2710            body_type,
2711        } => Term::Pi {
2712            param: param.clone(),
2713            param_type: Box::new(subst_name(param_type, old, repl)),
2714            body_type: if param == old {
2715                body_type.clone()
2716            } else {
2717                Box::new(subst_name(body_type, old, repl))
2718            },
2719        },
2720        Term::Lambda {
2721            param,
2722            param_type,
2723            body,
2724        } => Term::Lambda {
2725            param: param.clone(),
2726            param_type: Box::new(subst_name(param_type, old, repl)),
2727            body: if param == old {
2728                body.clone()
2729            } else {
2730                Box::new(subst_name(body, old, repl))
2731            },
2732        },
2733        Term::App(f, a) => Term::App(
2734            Box::new(subst_name(f, old, repl)),
2735            Box::new(subst_name(a, old, repl)),
2736        ),
2737        Term::Match {
2738            discriminant,
2739            motive,
2740            cases,
2741        } => Term::Match {
2742            discriminant: Box::new(subst_name(discriminant, old, repl)),
2743            motive: Box::new(subst_name(motive, old, repl)),
2744            cases: cases.iter().map(|c| subst_name(c, old, repl)).collect(),
2745        },
2746        Term::Fix { name, body } => Term::Fix {
2747            name: name.clone(),
2748            body: if name == old {
2749                body.clone()
2750            } else {
2751                Box::new(subst_name(body, old, repl))
2752            },
2753        },
2754        Term::MutualFix { defs, index } => {
2755            // Every def name binds in every body; `old` is shadowed iff it matches any.
2756            if defs.iter().any(|(n, _)| n == old) {
2757                t.clone()
2758            } else {
2759                Term::MutualFix {
2760                    defs: defs
2761                        .iter()
2762                        .map(|(n, b)| (n.clone(), subst_name(b, old, repl)))
2763                        .collect(),
2764                    index: *index,
2765                }
2766            }
2767        }
2768        Term::Let {
2769            name,
2770            ty,
2771            value,
2772            body,
2773        } => Term::Let {
2774            name: name.clone(),
2775            ty: Box::new(subst_name(ty, old, repl)),
2776            value: Box::new(subst_name(value, old, repl)),
2777            body: if name == old {
2778                body.clone()
2779            } else {
2780                Box::new(subst_name(body, old, repl))
2781            },
2782        },
2783        Term::Annotated { annotation, term } => Term::Annotated {
2784            annotation: annotation.clone(),
2785            term: Box::new(subst_name(term, old, repl)),
2786        },
2787    }
2788}
2789
2790// --- small term builders ---
2791fn var(n: &str) -> Term {
2792    Term::Var(n.to_string())
2793}
2794fn app(f: Term, x: Term) -> Term {
2795    Term::App(Box::new(f), Box::new(x))
2796}
2797fn lam(p: &str, ty: Term, body: Term) -> Term {
2798    Term::Lambda {
2799        param: p.to_string(),
2800        param_type: Box::new(ty),
2801        body: Box::new(body),
2802    }
2803}
2804fn pi(p: &str, ty: Term, body: Term) -> Term {
2805    Term::Pi {
2806        param: p.to_string(),
2807        param_type: Box::new(ty),
2808        body_type: Box::new(body),
2809    }
2810}
2811fn arrow(a: Term, b: Term) -> Term {
2812    pi("_", a, b)
2813}
2814fn gl(n: &str) -> Term {
2815    Term::Global(n.to_string())
2816}
2817fn apps(f: Term, args: &[Term]) -> Term {
2818    args.iter().fold(f, |acc, a| app(acc, a.clone()))
2819}
2820fn lams(tele: &[(String, Term)], body: Term) -> Term {
2821    tele.iter()
2822        .rev()
2823        .fold(body, |acc, (n, t)| lam(n, t.clone(), acc))
2824}
2825/// `Eq T a b` — the prelude's homogeneous equation at carrier `T`.
2826fn eq3(t: Term, a: Term, b: Term) -> Term {
2827    apps(gl("Eq"), &[t, a, b])
2828}
2829/// `Prod A B`.
2830fn prod(a: Term, b: Term) -> Term {
2831    apps(gl("Prod"), &[a, b])
2832}
2833/// `Decidable p`.
2834fn dec(p: Term) -> Term {
2835    app(gl("Decidable"), p)
2836}
2837/// `Not p`.
2838fn not_(p: Term) -> Term {
2839    app(gl("Not"), p)
2840}
2841
2842#[cfg(test)]
2843#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/recursor/helper_tests.rs"]
2844mod helper_tests;
2845
2846#[path = "recursor_bounded.rs"]
2847pub(crate) mod bounded;