Skip to main content

logicaffeine_kernel/
inductive_compile.rs

1//! Nested-inductive compiler (K3) — the UNTRUSTED front-end for inductives that recur
2//! nested inside a container, `RTree := rnode : TList RTree → RTree`.
3//!
4//! Such a type is not directly a strict-positivity-checkable inductive: `RTree` appears as
5//! an ARGUMENT of `TList`, not to the right of an arrow. The Lean/Coq resolution is
6//! SPECIALIZATION: replace the container `TList RTree` by a fresh sibling `RTree$TList`
7//! defined MUTUALLY with `RTree`, mirroring `TList`'s constructors with the element type
8//! fixed to `RTree`:
9//!
10//! ```text
11//! RTree       := rnode : RTree$TList → RTree
12//! RTree$TList := RTree$TList_TNil | RTree$TList_TCons : RTree → RTree$TList → RTree$TList
13//! ```
14//!
15//! This block is an ordinary mutual inductive (K3b), so its recursor recurses through the
16//! specialized list — the whole point. To relate the specialized form back to the generic
17//! `TList RTree`, the compiler emits CONVERSION ISOS `RTree$TList ↔ TList RTree`.
18//!
19//! Crucially this module is UNTRUSTED: it only produces terms. The caller registers the
20//! mutual block through the trusted mutual machinery and TYPE-CHECKS every iso through the
21//! trusted kernel — a mis-compiled sibling or iso is rejected, never trusted. Zero new
22//! trusted code, exactly as Lean compiles nested inductives to mutual ones.
23//!
24//! # The specialisable fragment
25//!
26//! A container `C` is specialisable when its declared arity is a telescope of `n ≥ 1` SORT
27//! parameters with no indices (`TList : Type → Type`, `TPair : Type → Type → Type`), and
28//! every constructor of `C` has the shape
29//!
30//! ```text
31//! c : Π(p₁:Sort) … Π(pₙ:Sort). ft₁ → … → ftₖ → C p₁ … pₙ
32//! ```
33//!
34//! where each value field `ftᵢ` is one of
35//!
36//! * a bare parameter `pⱼ` — the slot that carries parameter `j`'s value;
37//! * the SPINE `C p₁ … pₙ` — the container recurring on itself; or
38//! * a CARRIED field — any type CLOSED over `p₁ … pₙ` that does not mention `C` (`Text` in
39//!   `lcons : Π(A). Text → A → Labelled A → Labelled A`, `Nat` in a counted container).
40//!
41//! Compound fields are rewritten by the same recursive specialization used for explicit
42//! nested arguments. Each inner field gets checked conversion definitions, emitted before
43//! the outer wrapper uses them. Negative occurrences, dependent fields and nonuniform
44//! container recursion are refused before a mutual block is registered.
45//!
46//! Registered container applications in fields, such as List A inside an array wrapper,
47//! are specialized after fixing the constructor parameters.
48//!
49//! Carrying a closed field is not an unchecked pass. The emitted block goes through
50//! [`Context::add_mutual_inductives`], which runs `check_positivity_mutual` over the WHOLE block
51//! and `check_constructor_universes` on every member — so a carried field whose universe does not
52//! fit the sibling's sort is refused there, transactionally, by the trusted kernel rather than
53//! by this untrusted front end. That is strictly stronger than refusing the shape, which only
54//! made Lean's labelled containers unreachable.
55//!
56//! **Lean agrees, and it was asked rather than assumed.** Run on this box against Lean 4.14.0:
57//!
58//! ```text
59//! inductive Labelled (α : Type) | lnil | lcons : String → α → Labelled α → Labelled α
60//! inductive LTree | node : Labelled LTree → LTree          -- ACCEPTED
61//! inductive Labelled2 (α : Type) | lnil | lcons : α → Nat → Labelled2 α → Labelled2 α
62//! inductive LTree2 | node : Labelled2 LTree2 → LTree2      -- ACCEPTED
63//! ```
64//!
65//! and `#check @LTree.rec` prints exactly the specialised mutual block this module emits —
66//! `{motive_1 : LTree → Sort u_1} → {motive_2 : Labelled LTree → Sort u_1} → …` with the carried
67//! `(a : String)` riding through `lcons`'s minor premise in its own slot. Both FIELD ORDERS are
68//! accepted, which matters because `FieldKind` here is assigned by matching a field's TYPE
69//! against the parameter telescope and reads no position at all — so `Π(A). Nat → A → C A → C A`
70//! and `Π(A). A → Nat → C A → C A` are the same shape to this compiler and to Lean, and no fence
71//! can separate them.
72//! `G_recursor_extra::a_carried_field_after_the_element_mirrors_into_the_same_slot_it_came_from`
73//! takes that by computation: the sibling carries the field at its own index and the isos still
74//! invert.
75//!
76//! Nesting `C a₁ … aₙ` then specialises each `aⱼ` that mentions the inductive (recursively,
77//! so `TList (TList RTree)` becomes two siblings) and mirrors `C`'s constructors with
78//! parameter `j` fixed to `aⱼ`'s representative. Every parameter position is treated
79//! alike — the element may sit in any of them, or in several.
80//!
81//! What is deliberately OUTSIDE the fragment, refused fail-closed rather than mis-compiled:
82//!
83//! * a field mentioning a container parameter in a DOMAIN position, where the
84//!   occurrence is outright negative, and a field
85//!   mentioning the container itself other than as its own spine.
86//! * an indexed container, a permuted or partially-applied result type, a `Sort`-valued
87//!   value field (which the kernel's ι-reduction would mistake for a parameter), and a
88//!   dependent field (one mentioning an earlier field's binder), which the emitted
89//!   non-dependent sibling could not express.
90//!
91//! Explicit universe instances are retained in generic types, constructor references and
92//! generated conversion bodies. Sibling identities include their complete universe instance;
93//! malformed instances are refused by ordinary kernel inference before specialization.
94//!
95//! # Parameters and universes of the nested family itself
96//!
97//! A family may take uniform parameters (`PTree α := node : α → List (PTree α) → PTree α`) and
98//! universe parameters (`UTree.{u} (α : Type u) : Type u`). The parameters are split onto one
99//! canonical telescope that every emitted sibling shares (`PTree$List α`), every member is
100//! universe polymorphic over exactly the family's levels and lives in the family's own sort, and
101//! the base leaf of specialization is the family at exactly its own parameters and levels. An
102//! occurrence at anything else (`PTree (List α)` inside `PTree α`, `UTree.{0}` inside
103//! `UTree.{u}`) is an invalid declaration, refused as Lean refuses it. Recursors, motives and
104//! minor premises follow Lean's auxiliary-type discovery order (outermost occurrence first),
105//! which is not the post-order siblings are emitted in.
106
107use crate::context::{Context, MutualInductive};
108use crate::error::{KernelError, KernelResult};
109use crate::term::Term;
110
111/// A nested inductive declaration: a name, its sort, and constructors whose argument types
112/// may mention the inductive nested inside a registered container (`TList RTree`).
113pub struct NestedDecl {
114    pub name: String,
115    pub sort: Term,
116    pub constructors: Vec<(String, Term)>,
117}
118
119/// One container specialized for this inductive, with the names of its conversion isos.
120#[derive(Debug, Clone)]
121pub struct IsoNames {
122    /// The generic container that was specialized (e.g. `TList`).
123    pub container: String,
124    /// The fresh mutual sibling (e.g. `RTree$TList`).
125    pub sibling: String,
126    /// `to_generic : sibling → container name` — specialized to generic.
127    pub to_generic: String,
128    /// `from_generic : container name → sibling` — generic to specialized.
129    pub from_generic: String,
130}
131
132/// The compiled artifacts of a nested inductive: the mutual block to register, and the
133/// iso DEFINITIONS `(name, type, body)` to kernel-check and add. Nothing here is trusted
134/// until the caller checks it.
135pub struct Compiled {
136    pub block: Vec<MutualInductive>,
137    pub isos: Vec<(String, Term, Term)>,
138    pub iso_names: Vec<IsoNames>,
139    pub siblings: Vec<String>,
140    /// The canonical uniform parameter telescope shared by the source inductive, every
141    /// specialized sibling and every conversion iso. Empty for an unparameterized family.
142    pub parameters: Vec<(String, Term)>,
143}
144
145/// What a nested-inductive registration produced: the specialized sibling type names and
146/// the conversion isos relating each to its generic container.
147#[derive(Debug, Clone)]
148pub struct NestedInfo {
149    pub siblings: Vec<String>,
150    pub isos: Vec<IsoNames>,
151}
152
153// --- small builders ---
154fn g(n: &str) -> Term {
155    Term::Global(n.to_string())
156}
157fn v(n: &str) -> Term {
158    Term::Var(n.to_string())
159}
160fn app(f: Term, x: Term) -> Term {
161    Term::App(Box::new(f), Box::new(x))
162}
163fn apps(f: Term, xs: Vec<Term>) -> Term {
164    xs.into_iter().fold(f, app)
165}
166fn pi(p: &str, t: Term, b: Term) -> Term {
167    Term::Pi {
168        param: p.to_string(),
169        param_type: Box::new(t),
170        body_type: Box::new(b),
171    }
172}
173fn arrow(a: Term, b: Term) -> Term {
174    pi("_", a, b)
175}
176fn lam(p: &str, t: Term, b: Term) -> Term {
177    Term::Lambda {
178        param: p.to_string(),
179        param_type: Box::new(t),
180        body: Box::new(b),
181    }
182}
183
184/// A nested declaration with its uniform parameter telescope made explicit.
185///
186/// Every constructor's leading parameter binders are renamed onto ONE canonical telescope, so the
187/// inductive at its own parameters — the base leaf of specialization — is one syntactic term,
188/// and every specialized sibling takes the same telescope as its own uniform parameters. With
189/// no parameters this is exactly the unparameterized declaration.
190struct Nesting<'a> {
191    decl: &'a NestedDecl,
192    params: Vec<(String, Term)>,
193    /// The declaration's universe parameters: every member of the emitted block is universe
194    /// polymorphic over exactly these, and is referenced at exactly these.
195    levels: Vec<String>,
196    /// The sort every member of the block lives in, after the parameters.
197    sort: Term,
198    /// Each constructor's field telescope and result, over the canonical parameters.
199    constructors: Vec<(String, Term)>,
200}
201
202impl Nesting<'_> {
203    fn name(&self) -> &str {
204        &self.decl.name
205    }
206    fn vars(&self) -> Vec<Term> {
207        self.params.iter().map(|(p, _)| v(p)).collect()
208    }
209    /// A member of the block (or one of its constructors or isos) at the block's own levels.
210    fn reference(&self, name: &str) -> Term {
211        reference_at(name, &self.levels)
212    }
213    /// The inductive applied to its own parameters, in order.
214    fn uniform(&self) -> Term {
215        apps(self.reference(self.name()), self.vars())
216    }
217    /// A specialized sibling applied to the shared parameters.
218    fn applied(&self, sibling: &str) -> Term {
219        apps(self.reference(sibling), self.vars())
220    }
221    fn close_pi(&self, body: Term) -> Term {
222        self.params
223            .iter()
224            .rev()
225            .fold(body, |b, (p, t)| pi(p, t.clone(), b))
226    }
227    fn close_lam(&self, body: Term) -> Term {
228        self.params
229            .iter()
230            .rev()
231            .fold(body, |b, (p, t)| lam(p, t.clone(), b))
232    }
233}
234
235/// `name` at the universe parameters `levels`: a plain global when there are none.
236fn reference_at(name: &str, levels: &[String]) -> Term {
237    if levels.is_empty() {
238        g(name)
239    } else {
240        Term::Const {
241            name: name.to_string(),
242            levels: levels
243                .iter()
244                .cloned()
245                .map(crate::term::Universe::Var)
246                .collect(),
247        }
248    }
249}
250
251/// Split `num_params` uniform parameters off the declaration's sort and every constructor.
252/// A constructor whose parameter domains differ from the sort's is refused: the parameters of
253/// a nested inductive are uniform, and a mismatch means the declaration is not the one its
254/// sort announces.
255fn nesting<'a>(
256    decl: &'a NestedDecl,
257    num_params: usize,
258    levels: &[String],
259) -> KernelResult<Nesting<'a>> {
260    let refuse = |why: String| {
261        KernelError::CertificationError(format!("nested-compile: '{}' {why}", decl.name))
262    };
263    let canonical: Vec<String> = (0..num_params)
264        .map(|i| format!("nested.parameter.{i}"))
265        .collect();
266    let mut params = Vec::with_capacity(num_params);
267    let mut sort = decl.sort.clone();
268    for name in &canonical {
269        let Term::Pi {
270            param,
271            param_type,
272            body_type,
273        } = sort
274        else {
275            return Err(refuse(format!(
276                "declares {num_params} parameter(s) but its sort binds fewer"
277            )));
278        };
279        params.push((name.clone(), *param_type));
280        sort = crate::substitute(&body_type, &param, &v(name));
281    }
282    // Every specialized sibling is emitted in the source's own sort, and the trusted block door
283    // checks each emitted constructor's universe there. A family that may live in `Prop` has
284    // different elimination rules, which specialization does not reconstruct.
285    match &sort {
286        Term::Sort(level) if crate::term::Universe::Type(0).is_subtype_of(level) => {}
287        _ => {
288            return Err(refuse(format!(
289                "ends in {sort} after its parameters; nested families are reconstructed only in \
290             `Type` universes (never `Prop` or a possibly-`Prop` sort)"
291            )))
292        }
293    }
294    let mut constructors = Vec::with_capacity(decl.constructors.len());
295    for (cname, cty) in &decl.constructors {
296        let mut ty = cty.clone();
297        for (name, domain) in &params {
298            let Term::Pi {
299                param,
300                param_type,
301                body_type,
302            } = ty
303            else {
304                return Err(refuse(format!(
305                    "constructor '{cname}' binds fewer than its {num_params} parameter(s)"
306                )));
307            };
308            if *param_type != *domain {
309                return Err(refuse(format!(
310                    "constructor '{cname}' binds parameter {name} at {param_type}, but the \
311                     sort binds it at {domain} — nested parameters are uniform"
312                )));
313            }
314            ty = crate::substitute(&body_type, &param, &v(name));
315        }
316        constructors.push((cname.clone(), ty));
317    }
318    Ok(Nesting {
319        decl,
320        params,
321        levels: levels.to_vec(),
322        sort,
323        constructors,
324    })
325}
326
327/// Simultaneously instantiate the canonical `params` of an open `image` with `args`.
328/// Each parameter is first renamed to a name free in every argument, so instantiating one
329/// parameter can never capture a variable another argument mentions.
330fn instantiate_parameters(image: &Term, params: &[String], args: &[Term]) -> Term {
331    let taken = |candidate: &str| {
332        args.iter().any(|a| mentions_var(a, candidate)) || mentions_var(image, candidate)
333    };
334    let mut term = image.clone();
335    let mut fresh = Vec::with_capacity(params.len());
336    for (i, p) in params.iter().enumerate() {
337        let mut name = format!("native.instance.{i}");
338        while taken(&name) || params.contains(&name) {
339            name.push('\'');
340        }
341        term = crate::substitute(&term, p, &v(&name));
342        fresh.push(name);
343    }
344    for (name, arg) in fresh.iter().zip(args) {
345        term = crate::substitute(&term, name, arg);
346    }
347    term
348}
349
350/// The role of one VALUE field of a container constructor, relative to the container's
351/// parameter telescope `p₁ … pₙ`.
352enum FieldKind {
353    /// The bare parameter `pⱼ` — carries a value of parameter `j`'s type.
354    Param(usize),
355    /// The SPINE `C p₁ … pₙ` — the container recurring on itself.
356    Spine,
357    /// A CARRIED field: a type CLOSED over the container's parameter telescope, mentioning
358    /// neither the container nor the inductive being declared (`Text` in
359    /// `lcons : Π(A). Text → A → Labelled A → Labelled A`). Because it is closed it is the SAME
360    /// type in the specialised sibling and in the generic container, so the conversion isos are
361    /// the identity on it — and, being closed, it is fully visible to the trusted mutual door,
362    /// which re-checks its strict positivity and its universe like any other constructor field.
363    Carried(Term),
364    /// A compound field with its checked specialized/generic conversion pair.
365    Nested(Spec),
366    /// A POSITIVE function field `Π(point : domain). result` whose domain mentions neither the
367    /// container, its parameters nor the inductive: the container recurring on itself under a
368    /// binder, `sup : (Nat → C A) → C A`. It converts pointwise, `λx. c (f x)`.
369    Pointwise {
370        point: String,
371        domain: Term,
372        result: Box<FieldKind>,
373    },
374}
375
376/// How a value moves between a specialised type and the generic type it stands for.
377#[derive(Clone)]
378enum Conversion {
379    /// A checked conversion iso, applied at the shared parameters.
380    Iso(String),
381    /// A function converts POINTWISE: `λpoint:domain. result (f point)`.
382    Pointwise {
383        point: String,
384        domain: Term,
385        result: Box<Conversion>,
386    },
387}
388
389/// A function type's binders and its final codomain, each binder renamed to its own
390/// `nested.point.{i}` — free in the type, and distinct along the telescope, so a pointwise
391/// conversion `λp₀. λp₁. c (f p₀ p₁)` never captures one point with another. A later domain may
392/// depend on an earlier binder; the renaming carries it along.
393fn pointwise_telescope(ty: &Term) -> (Vec<(String, Term)>, Term) {
394    let mut used = 0usize;
395    let mut fresh = || loop {
396        let name = format!("nested.point.{used}");
397        used += 1;
398        if !mentions_var(ty, &name) {
399            return name;
400        }
401    };
402    let mut renamed = Vec::new();
403    let mut rest = ty.clone();
404    while let Term::Pi {
405        param,
406        param_type,
407        body_type,
408    } = rest
409    {
410        let point = fresh();
411        // Keep the remaining binders scoped so substitution respects shadowing.
412        rest = crate::substitute(&body_type, &param, &v(&point));
413        renamed.push((point, *param_type));
414    }
415    (renamed, rest)
416}
417
418/// Peel a term's leading `Π`s into `(name, type)` pairs plus the residual.
419fn peel_pis(t: &Term) -> (Vec<(String, Term)>, Term) {
420    let mut params = Vec::new();
421    let mut cur = t.clone();
422    while let Term::Pi {
423        param,
424        param_type,
425        body_type,
426    } = cur
427    {
428        params.push((param, *param_type));
429        cur = *body_type;
430    }
431    (params, cur)
432}
433
434fn is_global(t: &Term, name: &str) -> bool {
435    matches!(t, Term::Global(n) if n == name)
436}
437
438/// The head and argument spine of an application (`C a b` → `(C, [a, b])`).
439fn spine(t: &Term) -> (&Term, Vec<&Term>) {
440    let mut args = Vec::new();
441    let mut head = t;
442    while let Term::App(f, a) = head {
443        args.push(a.as_ref());
444        head = f;
445    }
446    args.reverse();
447    (head, args)
448}
449
450/// The declared name of either a monomorphic or explicitly instantiated reference.
451/// The complete head term is retained separately when generating specialized conversions.
452fn referenced_name(t: &Term) -> Option<&str> {
453    match t {
454        Term::Global(n) => Some(n.as_str()),
455        Term::Const { name, .. } => Some(name.as_str()),
456        _ => None,
457    }
458}
459
460/// True if the global `name` occurs anywhere in `ty`. TOTAL over `Term` — a blind spot here
461/// silently passes a nesting through unspecialised, so every variant is listed explicitly
462/// rather than swept up by a wildcard.
463fn occurs_anywhere(ty: &Term, name: &str) -> bool {
464    match ty {
465        Term::Global(n) => n == name,
466        Term::Const { name: n, .. } => n == name,
467        Term::Sort(_) | Term::Var(_) | Term::Lit(_) | Term::Hole => false,
468        Term::App(f, x) => occurs_anywhere(f, name) || occurs_anywhere(x, name),
469        Term::Pi {
470            param_type,
471            body_type,
472            ..
473        } => occurs_anywhere(param_type, name) || occurs_anywhere(body_type, name),
474        Term::Lambda {
475            param_type, body, ..
476        } => occurs_anywhere(param_type, name) || occurs_anywhere(body, name),
477        Term::Fix { body, .. } => occurs_anywhere(body, name),
478        Term::MutualFix { defs, .. } => defs.iter().any(|(_, b)| occurs_anywhere(b, name)),
479        Term::Let {
480            ty, value, body, ..
481        } => {
482            occurs_anywhere(ty, name) || occurs_anywhere(value, name) || occurs_anywhere(body, name)
483        }
484        Term::Match {
485            discriminant,
486            motive,
487            cases,
488        } => {
489            occurs_anywhere(discriminant, name)
490                || occurs_anywhere(motive, name)
491                || cases.iter().any(|c| occurs_anywhere(c, name))
492        }
493        Term::Annotated { term, .. } => occurs_anywhere(term, name),
494    }
495}
496
497/// True if the local `name` occurs anywhere in `ty`, IGNORING shadowing — a conservative
498/// over-approximation, because every caller uses it to refuse fail-closed.
499fn mentions_var(ty: &Term, name: &str) -> bool {
500    match ty {
501        Term::Var(n) => n == name,
502        Term::Global(_) | Term::Const { .. } | Term::Sort(_) | Term::Lit(_) | Term::Hole => false,
503        Term::App(f, x) => mentions_var(f, name) || mentions_var(x, name),
504        Term::Pi {
505            param_type,
506            body_type,
507            ..
508        } => mentions_var(param_type, name) || mentions_var(body_type, name),
509        Term::Lambda {
510            param_type, body, ..
511        } => mentions_var(param_type, name) || mentions_var(body, name),
512        Term::Fix { body, .. } => mentions_var(body, name),
513        Term::MutualFix { defs, .. } => defs.iter().any(|(_, b)| mentions_var(b, name)),
514        Term::Let {
515            ty, value, body, ..
516        } => mentions_var(ty, name) || mentions_var(value, name) || mentions_var(body, name),
517        Term::Match {
518            discriminant,
519            motive,
520            cases,
521        } => {
522            mentions_var(discriminant, name)
523                || mentions_var(motive, name)
524                || cases.iter().any(|c| mentions_var(c, name))
525        }
526        Term::Annotated { term, .. } => mentions_var(term, name),
527    }
528}
529
530/// True if `ty` is a constructor argument that must be SPECIALIZED: its head is a registered
531/// container inductive (≠ the inductive being defined) and `name` occurs somewhere inside it
532/// (`TList name`, `TPair Nat name`, `TList (TList name)`). A bare `name`, a `Nat`, a positive
533/// `Nat → name`, or a container not mentioning `name` (`TList Nat`) is NOT nested — it passes
534/// through unchanged.
535fn is_nested_container_type(ctx: &Context, nest: &Nesting, ty: &Term) -> bool {
536    let (head, _) = spine(ty);
537    referenced_name(head).is_some_and(|c| {
538        c != nest.name() && (ctx.is_inductive(c) || matches!(head, Term::Const { .. }))
539    }) && occurs_anywhere(ty, nest.name())
540}
541
542/// The result of specializing one nested type or one container ARGUMENT: the SPECIALIZED
543/// type standing in for it, a name fragment identifying that type (used to mangle sibling
544/// names), the GENERIC type it stands for, and — when the two differ through a container —
545/// the names of the conversion isos relating them.
546struct Spec {
547    repr: Term,
548    tag: String,
549    generic: Term,
550    to: Option<Conversion>,
551    from: Option<Conversion>,
552}
553
554/// One specialized sibling to emit: a mutual inductive mirroring `container` with each of
555/// its parameters fixed, plus the data its conversion isos need (each parameter's generic
556/// form and its own isos, which the sibling's isos delegate to).
557struct SibNode {
558    container: String,
559    container_head: Term,
560    repr: String,
561    /// Per container parameter: the SPECIALIZED type it is fixed to.
562    arg_repr: Vec<Term>,
563    /// Per container parameter: the GENERIC type that stands for.
564    arg_generic: Vec<Term>,
565    /// Per container parameter: the isos converting that parameter's values, or `None`
566    /// when the argument is inert (or the inductive itself) and the conversion is identity.
567    arg_to: Vec<Option<Conversion>>,
568    arg_from: Vec<Option<Conversion>>,
569    ctors: Vec<(String, Vec<FieldKind>)>,
570    to_name: String,
571    from_name: String,
572    /// The shared uniform parameters, as variables: every sibling, sibling constructor and
573    /// conversion iso is referenced applied to them.
574    vars: Vec<Term>,
575    /// The block's universe parameters, at which every sibling, sibling constructor and
576    /// conversion iso is referenced.
577    levels: Vec<String>,
578}
579
580impl SibNode {
581    /// This sibling at the shared parameters.
582    fn applied(&self) -> Term {
583        self.at_params(&self.repr)
584    }
585
586    /// A global of this compilation (sibling, sibling constructor or iso) at the shared
587    /// universe and value parameters.
588    fn at_params(&self, name: &str) -> Term {
589        apps(reference_at(name, &self.levels), self.vars.clone())
590    }
591
592    /// `container generic₁ … genericₙ` — the generic type this sibling represents.
593    fn generic(&self) -> Term {
594        apps(self.container_head.clone(), self.arg_generic.clone())
595    }
596
597    fn constructor(&self, name: &str) -> Term {
598        match &self.container_head {
599            Term::Const { levels, .. } => Term::Const {
600                name: name.into(),
601                levels: levels.clone(),
602            },
603            _ => g(name),
604        }
605    }
606
607    /// The type of one field in the SPECIALIZED sibling constructor.
608    fn sib_field_ty(&self, f: &FieldKind) -> Term {
609        match f {
610            FieldKind::Param(j) => self.arg_repr[*j].clone(),
611            FieldKind::Spine => self.applied(),
612            FieldKind::Carried(t) => t.clone(),
613            FieldKind::Nested(s) => s.repr.clone(),
614            FieldKind::Pointwise {
615                point,
616                domain,
617                result,
618            } => pi(point, domain.clone(), self.sib_field_ty(result)),
619        }
620    }
621
622    /// The type of the same field in the GENERIC container constructor.
623    fn gen_field_ty(&self, f: &FieldKind) -> Term {
624        match f {
625            FieldKind::Param(j) => self.arg_generic[*j].clone(),
626            FieldKind::Spine => self.generic(),
627            FieldKind::Carried(t) => t.clone(),
628            FieldKind::Nested(s) => s.generic.clone(),
629            FieldKind::Pointwise {
630                point,
631                domain,
632                result,
633            } => pi(point, domain.clone(), self.gen_field_ty(result)),
634        }
635    }
636
637    /// True if some constructor recurs on the spine, so the isos need a fixpoint.
638    fn has_spine(&self) -> bool {
639        fn recurs(f: &FieldKind) -> bool {
640            match f {
641                FieldKind::Spine => true,
642                FieldKind::Pointwise { result, .. } => recurs(result),
643                _ => false,
644            }
645        }
646        self.ctors.iter().any(|(_, fs)| fs.iter().any(recurs))
647    }
648}
649
650/// A name fragment identifying a specialized type, so sibling names stay deterministic and
651/// distinguish the container's arguments. `TList RTree` → `RTree$TList`, `TList (TList D)` →
652/// `D$TList$TList`, `TPair Nat PTree` → `Nat$PTree$TPair`. Injectivity is not relied on for
653/// soundness — [`specialize`] refuses outright if two different nestings mangle alike.
654fn tag_of(t: &Term) -> String {
655    match t {
656        Term::Global(n) => n.clone(),
657        Term::Const { name, .. } => name.clone(),
658        Term::Var(n) => n.clone(),
659        // Arguments first, head last — the same shape a specialised name takes, so an inert
660        // `TPair Nat Bool` and a specialised one read alike.
661        Term::App(..) => {
662            let (head, args) = spine(t);
663            let mut parts: Vec<String> = args.iter().map(|a| tag_of(a)).collect();
664            parts.push(tag_of(head));
665            parts.join("$")
666        }
667        other => sanitize(&format!("{other}")),
668    }
669}
670
671/// Render a term into a name fragment: alphanumerics and `_` survive, every other run of
672/// characters collapses to a single `_`.
673fn sanitize(s: &str) -> String {
674    let mut out = String::new();
675    let mut gap = false;
676    for ch in s.chars() {
677        if ch.is_alphanumeric() || ch == '_' {
678            if gap && !out.is_empty() {
679                out.push('_');
680            }
681            gap = false;
682            out.push(ch);
683        } else {
684            gap = true;
685        }
686    }
687    if out.is_empty() {
688        out.push('_');
689    }
690    out
691}
692
693/// Analyse one container constructor against the container's arity and the actual arguments
694/// of this nesting: return the KIND of each value field, or refuse if the constructor is
695/// outside the specialisable fragment (see the module header).
696fn analyze_container_ctor(
697    ctor: &str,
698    ctor_ty: &Term,
699    container: &str,
700    container_head: &Term,
701    arity: usize,
702    ctx: &Context,
703    nest: &Nesting,
704    arguments: &[Spec],
705    nodes: &mut Vec<SibNode>,
706    seen: &mut Vec<(String, Term)>,
707) -> KernelResult<Vec<FieldKind>> {
708    let decl_name = nest.name();
709    let refuse = |why: String| -> KernelError {
710        KernelError::CertificationError(format!(
711            "nested-compile: container '{container}' constructor '{ctor}' is outside the \
712             specialisable fragment — {why}"
713        ))
714    };
715
716    let (binders, residual) = peel_pis(ctor_ty);
717    if binders.len() < arity {
718        return Err(refuse(format!(
719            "it binds {} arguments but '{container}' has {arity} parameter(s)",
720            binders.len()
721        )));
722    }
723    let params: Vec<String> = binders[..arity].iter().map(|(n, _)| n.clone()).collect();
724    // Field positions are assigned by matching a field against a parameter NAME, so two
725    // parameters sharing one name would send the shadowed slot's value to the shadowing one.
726    for (i, p) in params.iter().enumerate() {
727        if params[..i].contains(p) {
728            return Err(refuse(format!("it binds two parameters named '{p}'")));
729        }
730    }
731    for (name, ty) in &binders[..arity] {
732        if !matches!(ty, Term::Sort(_)) {
733            return Err(refuse(format!(
734                "its parameter '{name}' is bound at type {ty}, not a sort — the parameter \
735                 telescope must be exactly the container's {arity} sort binder(s)"
736            )));
737        }
738    }
739
740    // The result must be the container applied to its own parameters, in order. A permuted
741    // or partially-applied result means the field positions do not correspond to the
742    // nesting's arguments, so mirroring them would silently produce a DIFFERENT type.
743    let expected_result = apps(
744        container_head.clone(),
745        params.iter().map(|p| v(p)).collect(),
746    );
747    if residual != expected_result {
748        return Err(refuse(format!(
749            "it returns {residual}, not {expected_result}"
750        )));
751    }
752
753    let value_binders = &binders[arity..];
754    let mut kinds = Vec::new();
755    for (i, (fname, fty)) in value_binders.iter().enumerate() {
756        // A dependent field — one mentioning an earlier field's binder — cannot be expressed
757        // by the non-dependent sibling constructor this compiler emits.
758        for (earlier, _) in &value_binders[..i] {
759            if earlier != "_" && mentions_var(fty, earlier) {
760                return Err(refuse(format!(
761                    "its field '{fname}' depends on the earlier field '{earlier}'"
762                )));
763            }
764        }
765        // A `Sort`-valued value field would be counted as a parameter by the kernel's
766        // ι-reduction heuristic, so the specialised match would drop it.
767        if matches!(fty, Term::Sort(_)) {
768            return Err(refuse(format!("its field '{fname}' is itself a sort")));
769        }
770
771        if let Some(j) = params
772            .iter()
773            .position(|p| matches!(fty, Term::Var(n) if n == p))
774        {
775            kinds.push(FieldKind::Param(j));
776            continue;
777        }
778        if *fty == expected_result {
779            kinds.push(FieldKind::Spine);
780            continue;
781        }
782        if let Some(kind) = pointwise_spine(fty, &expected_result, container, decl_name, &params) {
783            kinds.push(kind);
784            continue;
785        }
786        if occurs_anywhere(fty, container) {
787            return Err(refuse(format!(
788                "its field '{fname}' of type {fty} mentions '{container}' somewhere other than \
789                 as its own spine {expected_result} — the specialised sibling has ONE fixed \
790                 argument list and cannot express a differently-applied self-occurrence"
791            )));
792        }
793        if occurs_anywhere(fty, decl_name) {
794            return Err(refuse(format!(
795                "its field '{fname}' of type {fty} already mentions '{decl_name}', the inductive \
796                 being declared — the mirror cannot tell that occurrence apart from the one it \
797                 is specialising"
798            )));
799        }
800        if params.iter().any(|p| mentions_var(fty, p)) {
801            let mut generic = fty.clone();
802            // Constructor parameters are replaced by closed actual types; dependent
803            // value fields were rejected above, before this substitution.
804            for (parameter, argument) in params.iter().zip(arguments) {
805                generic = crate::substitute(&generic, parameter, &argument.generic);
806            }
807            // Ask the same trusted positivity rule about the instantiated field
808            // before specializing it. A negative arrow is a semantic failure,
809            // while unsupported container shapes retain their own diagnostics.
810            if let Err(KernelError::PositivityViolation { reason, .. }) =
811                crate::positivity::check_positivity_resolved(
812                    ctx,
813                    decl_name,
814                    ctor,
815                    &arrow(generic.clone(), nest.uniform()),
816                )
817            {
818                return Err(KernelError::PositivityViolation {
819                    inductive: decl_name.into(),
820                    constructor: ctor.into(),
821                    reason: format!(
822                        "container '{container}' field '{fname}' has a negative occurrence: {reason}"
823                    ),
824                });
825            }
826            kinds.push(FieldKind::Nested(specialize(
827                ctx, nest, &generic, nodes, seen,
828            )?));
829        } else {
830            kinds.push(FieldKind::Carried(fty.clone()));
831        }
832    }
833    Ok(kinds)
834}
835
836/// `Π(x₁:D₁) … Π(xₖ:Dₖ). C p₁ … pₙ` — the container recurring on itself under binders whose
837/// domains mention neither the container, its parameters nor the inductive — as a pointwise
838/// field; `None` for any other shape. The binders are renamed apart from the conversion's own
839/// variables, and a later domain may depend on an earlier binder.
840fn pointwise_spine(
841    ty: &Term,
842    spine: &Term,
843    container: &str,
844    inductive: &str,
845    params: &[String],
846) -> Option<FieldKind> {
847    let (binders, core) = pointwise_telescope(ty);
848    let closed = |domain: &Term| {
849        !occurs_anywhere(domain, container)
850            && !occurs_anywhere(domain, inductive)
851            && params.iter().all(|p| !mentions_var(domain, p))
852    };
853    if binders.is_empty() || core != *spine || !binders.iter().all(|(_, domain)| closed(domain)) {
854        return None;
855    }
856    Some(
857        binders
858            .into_iter()
859            .rev()
860            .fold(FieldKind::Spine, |result, (point, domain)| {
861                FieldKind::Pointwise {
862                    point,
863                    domain,
864                    result: Box::new(result),
865                }
866            }),
867    )
868}
869
870/// The first nested container instance inside `ty` — a registered inductive other than
871/// `inductive`, applied to arguments that mention `inductive` — whose arguments also mention the
872/// local `point`. Such an instance has no fixed argument list for a sibling to mirror.
873fn nesting_over_local(ctx: &Context, ty: &Term, inductive: &str, point: &str) -> Option<Term> {
874    let (head, args) = spine(ty);
875    if referenced_name(head).is_some_and(|c| c != inductive && ctx.is_inductive(c))
876        && args.iter().any(|a| occurs_anywhere(a, inductive))
877        && args.iter().any(|a| mentions_var(a, point))
878    {
879        return Some(ty.clone());
880    }
881    match ty {
882        Term::App(f, x) => nesting_over_local(ctx, f, inductive, point)
883            .or_else(|| nesting_over_local(ctx, x, inductive, point)),
884        Term::Pi {
885            param_type,
886            body_type,
887            ..
888        } => nesting_over_local(ctx, param_type, inductive, point)
889            .or_else(|| nesting_over_local(ctx, body_type, inductive, point)),
890        _ => None,
891    }
892}
893
894/// Whether `ty` nests the inductive inside a registered container in a positive position: the
895/// container itself, or the codomain of a function type whose domain does not mention it.
896fn nests_positively(ctx: &Context, nest: &Nesting, ty: &Term) -> bool {
897    match ty {
898        Term::Pi {
899            param_type,
900            body_type,
901            ..
902        } => !occurs_anywhere(param_type, nest.name()) && nests_positively(ctx, nest, body_type),
903        _ => is_nested_container_type(ctx, nest, ty),
904    }
905}
906
907/// The first occurrence of `container` inside `ty` that is NOT `expected` (the container applied
908/// to its own parameter telescope, in order) — the shape that costs a container its uniform
909/// parameters. TOTAL over `Term`: a blind spot here would name no culprit and the diagnostic
910/// would silently go back to being unactionable.
911fn non_uniform_occurrence(ty: &Term, container: &str, expected: &Term) -> Option<Term> {
912    // A spine headed by the container is decided HERE, whole: `C p₁ … pₙ` at exactly its own
913    // parameters is the uniform occurrence and nothing inside it needs inspecting, and anything
914    // else headed by `C` — permuted, partially applied, at a different argument — is the culprit.
915    // Recursing into the head instead would report the container's own bare name out of every
916    // legitimate occurrence, which is the shape that made the first version of this diagnostic
917    // point at the wrong constructor.
918    let (head, _) = spine(ty);
919    if is_global(head, container) {
920        return if ty == expected {
921            None
922        } else {
923            Some(ty.clone())
924        };
925    }
926    match ty {
927        Term::Global(_)
928        | Term::Const { .. }
929        | Term::Sort(_)
930        | Term::Var(_)
931        | Term::Lit(_)
932        | Term::Hole => None,
933        Term::App(f, x) => non_uniform_occurrence(f, container, expected)
934            .or_else(|| non_uniform_occurrence(x, container, expected)),
935        Term::Pi {
936            param_type,
937            body_type,
938            ..
939        } => non_uniform_occurrence(param_type, container, expected)
940            .or_else(|| non_uniform_occurrence(body_type, container, expected)),
941        Term::Lambda {
942            param_type, body, ..
943        } => non_uniform_occurrence(param_type, container, expected)
944            .or_else(|| non_uniform_occurrence(body, container, expected)),
945        Term::Fix { body, .. } => non_uniform_occurrence(body, container, expected),
946        Term::MutualFix { defs, .. } => defs
947            .iter()
948            .find_map(|(_, b)| non_uniform_occurrence(b, container, expected)),
949        Term::Let {
950            ty: t, value, body, ..
951        } => non_uniform_occurrence(t, container, expected)
952            .or_else(|| non_uniform_occurrence(value, container, expected))
953            .or_else(|| non_uniform_occurrence(body, container, expected)),
954        Term::Match {
955            discriminant,
956            motive,
957            cases,
958        } => non_uniform_occurrence(discriminant, container, expected)
959            .or_else(|| non_uniform_occurrence(motive, container, expected))
960            .or_else(|| {
961                cases
962                    .iter()
963                    .find_map(|c| non_uniform_occurrence(c, container, expected))
964            }),
965        Term::Annotated { term, .. } => non_uniform_occurrence(term, container, expected),
966    }
967}
968
969/// The constructor that denies `container` a uniform `arity`-long parameter telescope, with the
970/// reason — for the INDEXED-family refusal's diagnostic. `None` when every constructor is uniform
971/// (the split was declared rather than inferred, and the declaration is the authority).
972fn non_uniform_constructor(
973    ctx: &Context,
974    container: &str,
975    arity: usize,
976) -> Option<(String, String)> {
977    for (cname, cty) in ctx.get_constructors(container) {
978        let (binders, residual) = peel_pis(cty);
979        if binders.len() < arity {
980            return Some((
981                cname.to_string(),
982                format!(
983                    "it binds {} argument(s), fewer than the {arity} the arity declares",
984                    binders.len()
985                ),
986            ));
987        }
988        let ps: Vec<String> = binders[..arity].iter().map(|(n, _)| n.clone()).collect();
989        let expected = apps(g(container), ps.iter().map(|p| v(p)).collect());
990        if residual != expected {
991            return Some((
992                cname.to_string(),
993                format!("it returns {residual}, not {expected}"),
994            ));
995        }
996        for (fname, fty) in &binders[arity..] {
997            if let Some(bad) = non_uniform_occurrence(fty, container, &expected) {
998                return Some((
999                    cname.to_string(),
1000                    format!(
1001                        "its field '{fname}' contains the occurrence {bad}, which is not \
1002                         '{container}' at its own parameters {expected}"
1003                    ),
1004                ));
1005            }
1006        }
1007    }
1008    None
1009}
1010
1011/// Recursively specialize a nested type or one container argument, accumulating the siblings
1012/// to emit (in POST-ORDER, so an inner sibling is registered before the outer sibling whose
1013/// isos reference it). Three cases: an argument not mentioning the inductive is INERT and
1014/// stands for itself; the inductive itself is the BASE leaf; and `C a₁ … aₙ` specialises each
1015/// argument first, then mirrors `C` with every parameter fixed.
1016fn specialize(
1017    ctx: &Context,
1018    nest: &Nesting,
1019    ty: &Term,
1020    nodes: &mut Vec<SibNode>,
1021    seen: &mut Vec<(String, Term)>,
1022) -> KernelResult<Spec> {
1023    if !occurs_anywhere(ty, nest.name()) {
1024        return Ok(Spec {
1025            repr: ty.clone(),
1026            tag: tag_of(ty),
1027            generic: ty.clone(),
1028            to: None,
1029            from: None,
1030        });
1031    }
1032    // The base leaf is the inductive at exactly its own parameters. Any other application of
1033    // it — at a different argument, partially applied — is a non-uniform occurrence no
1034    // specialized sibling can stand for, and is refused below.
1035    if *ty == nest.uniform() {
1036        return Ok(Spec {
1037            repr: nest.uniform(),
1038            tag: nest.name().to_string(),
1039            generic: nest.uniform(),
1040            to: None,
1041            from: None,
1042        });
1043    }
1044
1045    // A POSITIVE function type `Π(x:D). B`: Lean's elimination reaches under the binder, so the
1046    // nesting in `B` is specialised there, the binder rides along unchanged, and the conversion is
1047    // pointwise. A domain that mentions the inductive is a negative occurrence no specialisation
1048    // mends; the callers' positivity checks refuse it first, and this refusal backs them.
1049    if matches!(ty, Term::Pi { .. }) {
1050        let (binders, core) = pointwise_telescope(ty);
1051        if let Some((_, domain)) = binders
1052            .iter()
1053            .find(|(_, domain)| occurs_anywhere(domain, nest.name()))
1054        {
1055            return Err(KernelError::CertificationError(format!(
1056                "nested-compile: '{}' occurs in the domain {domain} of {ty}, which is not a positive \
1057                 position",
1058                nest.name()
1059            )));
1060        }
1061        if let Some(instance) = binders
1062            .iter()
1063            .find_map(|(point, _)| nesting_over_local(ctx, &core, nest.name(), point))
1064        {
1065            return Err(KernelError::InvalidDeclaration(format!(
1066                "nested-compile: the nested occurrence {instance} in {ty} mentions a bound variable of \
1067                 the function type in a container argument"
1068            )));
1069        }
1070        let result = specialize(ctx, nest, &core, nodes, seen)?;
1071        let close = |body: Term| {
1072            binders
1073                .iter()
1074                .rev()
1075                .fold(body, |b, (point, domain)| pi(point, domain.clone(), b))
1076        };
1077        let pointwise = |conversion: Option<Conversion>| {
1078            conversion.map(|c| {
1079                binders
1080                    .iter()
1081                    .rev()
1082                    .fold(c, |result, (point, domain)| Conversion::Pointwise {
1083                        point: point.clone(),
1084                        domain: domain.clone(),
1085                        result: Box::new(result),
1086                    })
1087            })
1088        };
1089        let domains: Vec<String> = binders.iter().map(|(_, domain)| tag_of(domain)).collect();
1090        return Ok(Spec {
1091            repr: close(result.repr),
1092            tag: format!("{}_to_{}", domains.join("_"), result.tag),
1093            generic: close(result.generic),
1094            to: pointwise(result.to),
1095            from: pointwise(result.from),
1096        });
1097    }
1098
1099    let (head, args) = spine(ty);
1100    // The inductive applied at anything but its own parameters breaks parameter uniformity.
1101    // That is not a shape this compiler lacks; it is an invalid declaration, and Lean's kernel
1102    // refuses it too ("inductive datatype parameter mismatch").
1103    if referenced_name(head) == Some(nest.name()) {
1104        return Err(KernelError::InvalidDeclaration(format!(
1105            "nested-compile: '{}' occurs as {ty}, not at its own uniform parameters {}",
1106            nest.name(),
1107            nest.uniform()
1108        )));
1109    }
1110    let container = match head {
1111        Term::Global(c) | Term::Const { name: c, .. }
1112            if c != nest.name() && ctx.is_inductive(c) =>
1113        {
1114            c.clone()
1115        }
1116        _ => {
1117            return Err(KernelError::CertificationError(format!(
1118                "nested-compile: '{}' occurs in argument type {ty} in a position that is not a \
1119                 nesting inside a registered container, nor the inductive at its own \
1120                 parameters {} (only `Container …` nestings are specialized)",
1121                nest.name(),
1122                nest.uniform()
1123            )));
1124        }
1125    };
1126
1127    // Validate the universe instance before deriving specialized names.
1128    crate::infer_type(ctx, head)?;
1129    let arity = ctx.inductive_arity(&container);
1130    if arity == 0 || args.len() != arity {
1131        return Err(KernelError::CertificationError(format!(
1132            "nested-compile: container '{container}' has arity {arity} but is applied to {} \
1133             argument(s) in {ty} — only a fully-applied container is specialisable",
1134            args.len()
1135        )));
1136    }
1137    if ctx.inductive_num_params(&container) != arity {
1138        // Name the CONSTRUCTOR that costs the container its uniform parameter telescope. "1 of
1139        // its 1 arguments are indices" is a true sentence a reader cannot act on: the split is
1140        // INFERRED from the constructors, so the repair is always in one of them, and a
1141        // diagnostic that does not say which leaves the author to re-derive the inference by
1142        // hand. Computed only on this path, so the ordinary compile pays nothing for it.
1143        let culprit = match non_uniform_constructor(ctx, &container, arity) {
1144            Some((c, why)) => format!(" — '{c}' is why: {why}"),
1145            None => String::new(),
1146        };
1147        return Err(KernelError::CertificationError(format!(
1148            "nested-compile: container '{container}' is an INDEXED family ({} of its {arity} \
1149             arguments are indices) — specialising it would fix an index as if it were a \
1150             uniform parameter{culprit}",
1151            ctx.inductive_num_indices(&container)
1152        )));
1153    }
1154
1155    // Specialise every argument first (post-order), inert ones standing for themselves.
1156    let mut arg_specs = Vec::with_capacity(arity);
1157    for a in &args {
1158        arg_specs.push(specialize(ctx, nest, a, nodes, seen)?);
1159    }
1160
1161    let repr = {
1162        let tags: Vec<&str> = arg_specs.iter().map(|s| s.tag.as_str()).collect();
1163        let instance = match head {
1164            Term::Const { levels, .. } => format!("$_{}", sanitize(&format!("{levels:?}"))),
1165            _ => String::new(),
1166        };
1167        format!("{}${}{}", tags.join("$"), container, instance)
1168    };
1169    let generic = apps(
1170        head.clone(),
1171        arg_specs.iter().map(|s| s.generic.clone()).collect(),
1172    );
1173    let to_name = format!("{repr}_to_{container}");
1174    let from_name = format!("{repr}_from_{container}");
1175
1176    // Soundness does not rest on the mangling being injective: a repr already claimed by a
1177    // DIFFERENT nesting is refused outright rather than silently reusing the wrong sibling.
1178    match seen.iter().find(|(r, _)| *r == repr) {
1179        Some((_, claimed)) if *claimed == generic => {
1180            return Ok(Spec {
1181                repr: nest.applied(&repr),
1182                tag: repr,
1183                generic,
1184                to: Some(Conversion::Iso(to_name)),
1185                from: Some(Conversion::Iso(from_name)),
1186            });
1187        }
1188        Some((_, claimed)) => {
1189            return Err(KernelError::CertificationError(format!(
1190                "nested-compile: the specialised name '{repr}' would stand for both {claimed} \
1191                 and {generic}"
1192            )));
1193        }
1194        None => seen.push((repr.clone(), generic.clone())),
1195    }
1196
1197    let actual: Vec<Term> = arg_specs.iter().map(|s| s.repr.clone()).collect();
1198    let mut ctors = Vec::new();
1199    for (orig_ctor, _) in ctx.get_constructors(&container) {
1200        let reference = match head {
1201            Term::Const { levels, .. } => Term::Const {
1202                name: orig_ctor.into(),
1203                levels: levels.clone(),
1204            },
1205            _ => g(orig_ctor),
1206        };
1207        let orig_ty = crate::infer_type(ctx, &reference)?;
1208        let kinds = analyze_container_ctor(
1209            orig_ctor, &orig_ty, &container, head, arity, ctx, nest, &arg_specs, nodes, seen,
1210        )?;
1211        ctors.push((orig_ctor.to_string(), kinds));
1212    }
1213
1214    nodes.push(SibNode {
1215        container: container.clone(),
1216        container_head: head.clone(),
1217        repr: repr.clone(),
1218        arg_repr: actual,
1219        arg_generic: arg_specs.iter().map(|s| s.generic.clone()).collect(),
1220        arg_to: arg_specs.iter().map(|s| s.to.clone()).collect(),
1221        arg_from: arg_specs.iter().map(|s| s.from.clone()).collect(),
1222        ctors,
1223        to_name: to_name.clone(),
1224        from_name: from_name.clone(),
1225        vars: nest.vars(),
1226        levels: nest.levels.clone(),
1227    });
1228
1229    Ok(Spec {
1230        repr: nest.applied(&repr),
1231        tag: repr,
1232        generic,
1233        to: Some(Conversion::Iso(to_name)),
1234        from: Some(Conversion::Iso(from_name)),
1235    })
1236}
1237
1238/// Compile a nested inductive into a mutual block plus conversion isos. Untrusted: every
1239/// artifact is checked by the caller. Handles arbitrary nesting DEPTH (`TList (TList RTree)`)
1240/// and arbitrary container ARITY (`TPair Nat PTree`) by recursive specialization — each
1241/// container level becomes its own mutual sibling.
1242pub fn compile_nested(ctx: &Context, decl: &NestedDecl) -> KernelResult<Compiled> {
1243    compile_nested_with_params(ctx, decl, 0)
1244}
1245
1246/// [`compile_nested`] for an inductive with `num_params` uniform parameters
1247/// (`PTree α := node : α → List (PTree α) → PTree α`).
1248///
1249/// The parameters are split off the sort and every constructor onto one canonical telescope
1250/// (see `Nesting`). The base leaf of specialization is the inductive at exactly those
1251/// parameters; every specialized sibling takes the same telescope as its uniform parameters
1252/// (`PTree$List α`), and every conversion iso abstracts it. An occurrence of the inductive at
1253/// any other arguments is a non-uniform nesting and is refused, as are constructor results
1254/// that do not return the inductive at its own parameters.
1255pub fn compile_nested_with_params(
1256    ctx: &Context,
1257    decl: &NestedDecl,
1258    num_params: usize,
1259) -> KernelResult<Compiled> {
1260    compile_nested_poly(ctx, decl, num_params, &[])
1261}
1262
1263/// [`compile_nested_with_params`] for a universe-polymorphic family (`UTree.{u} (α : Type u)`).
1264///
1265/// Every emitted member is universe polymorphic over exactly the declaration's `levels` and
1266/// lives in the declaration's own sort; the inductive, its siblings and their constructors are
1267/// referenced at exactly those levels. An occurrence of the inductive at any other universe
1268/// instance is non-uniform and refused, as Lean refuses it.
1269pub fn compile_nested_poly(
1270    ctx: &Context,
1271    decl: &NestedDecl,
1272    num_params: usize,
1273    levels: &[String],
1274) -> KernelResult<Compiled> {
1275    let nest = nesting(decl, num_params, levels)?;
1276
1277    // Specialization may shrink a container instance into a smaller sibling.
1278    // Preserve the source declaration's universe obligations before rewriting fields.
1279    let mut source = ctx.clone();
1280    if levels.is_empty() {
1281        source.add_indexed_inductive(&decl.name, decl.sort.clone(), num_params);
1282    } else {
1283        source.add_universe_poly_inductive(
1284            &decl.name,
1285            levels.to_vec(),
1286            decl.sort.clone(),
1287            num_params,
1288        );
1289    }
1290    for (name, ty) in &decl.constructors {
1291        crate::type_checker::check_constructor_universes(&source, &decl.name, name, ty)?;
1292    }
1293
1294    // 1. The inductive's own constructors, with each NESTED argument (`TList name`,
1295    //    `TPair Nat name`, `TList (TList name)`, …) replaced by its outermost specialized
1296    //    sibling — recording every sibling that must be emitted (post-order, inner-first).
1297    let mut nodes: Vec<SibNode> = Vec::new();
1298    let mut seen: Vec<(String, Term)> = Vec::new();
1299    let mut own_ctors = Vec::new();
1300    for (cname, cty) in &nest.constructors {
1301        let (fields_in, residual) = peel_pis(cty);
1302        // Every member is emitted with the shared parameters and no indices, so every
1303        // constructor must land on the inductive at exactly its own parameters; an indexed or
1304        // differently-applied result has no sibling to name.
1305        if residual != nest.uniform() {
1306            return Err(KernelError::CertificationError(format!(
1307                "nested-compile: constructor '{cname}' returns {residual}, not {} — a nested \
1308                 inductive's constructors return it at its own uniform parameters",
1309                nest.uniform()
1310            )));
1311        }
1312        // Specialise in FIELD order, so the siblings are emitted in the order the source
1313        // mentions them, then rebuild the telescope inside out.
1314        // Lean refuses a negative occurrence before it eliminates any nesting; so does this, so
1315        // a nesting in a domain is the positivity violation it is rather than an unspecialised
1316        // field. Other outcomes of the check are left to the specialisation and the block door.
1317        if let Err(violation @ KernelError::PositivityViolation { .. }) =
1318            crate::positivity::check_positivity_resolved(ctx, nest.name(), cname, cty)
1319        {
1320            return Err(violation);
1321        }
1322        let mut fields = Vec::with_capacity(fields_in.len());
1323        for (pname, pty) in fields_in {
1324            let pty = if nests_positively(ctx, &nest, &pty) {
1325                specialize(ctx, &nest, &pty, &mut nodes, &mut seen)?.repr
1326            } else {
1327                pty
1328            };
1329            fields.push((pname, pty));
1330        }
1331        let mut rebuilt = residual;
1332        for (pname, pty) in fields.into_iter().rev() {
1333            rebuilt = pi(&pname, pty, rebuilt);
1334        }
1335        own_ctors.push((cname.clone(), nest.close_pi(rebuilt)));
1336    }
1337
1338    if nodes.is_empty() {
1339        return Err(KernelError::CertificationError(format!(
1340            "nested-compile: '{}' has no nested container occurrence — register it directly",
1341            decl.name
1342        )));
1343    }
1344
1345    // 2. The mutual block: the inductive itself, then one specialized sibling per node.
1346    let mut block = vec![MutualInductive {
1347        name: decl.name.clone(),
1348        sort: nest.close_pi(nest.sort.clone()),
1349        num_params,
1350        constructors: own_ctors,
1351    }];
1352    let mut siblings = Vec::new();
1353    for node in &nodes {
1354        siblings.push(node.repr.clone());
1355        let mut sib_ctors = Vec::new();
1356        for (orig, kinds) in &node.ctors {
1357            let mut sty = node.applied();
1358            for kind in kinds.iter().rev() {
1359                sty = arrow(node.sib_field_ty(kind), sty);
1360            }
1361            sib_ctors.push((format!("{}_{}", node.repr, orig), nest.close_pi(sty)));
1362        }
1363        block.push(MutualInductive {
1364            name: node.repr.clone(),
1365            sort: nest.close_pi(nest.sort.clone()),
1366            num_params,
1367            constructors: sib_ctors,
1368        });
1369    }
1370
1371    // 2b. THE PARADOX FENCE, with references RESOLVED — before the block leaves this function
1372    //     and long before `add_mutual_inductives` runs its own (name-comparing) check.
1373    //
1374    //     The nested door has the same δ-shaped hole every declaration door has: declare
1375    //     `LTree` as an inductive, define `Negate := LTree → False`, then nest through a
1376    //     container while carrying a `Negate` field. `Negate` does not SPELL `LTree`, so a
1377    //     fence that compares names sees no occurrence and the Russell constructor
1378    //     `(LTree → False) → LTree` is admitted. `check_positivity_mutual_resolved` resolves
1379    //     the reference first, so the field is judged as the `LTree → False` it is.
1380    //
1381    //     Checking here rather than trusting the registration door also keeps the refusal at
1382    //     the place that can name the CONSTRUCTOR — the specialised sibling's field ordering is
1383    //     this function's doing, and a violation reported from inside the emitted mutual block
1384    //     would name a constructor the source never wrote.
1385    {
1386        let names: Vec<&str> = block.iter().map(|m| m.name.as_str()).collect();
1387        for member in &block {
1388            for (cname, cty) in &member.constructors {
1389                crate::positivity::check_positivity_mutual_resolved(ctx, &names, cname, cty)?;
1390            }
1391        }
1392    }
1393
1394    // 3. The conversion isos, one pair per node — emitted inner-first so the outer iso's
1395    //    element-field delegation to the inner iso resolves when it is kernel-checked. Each
1396    //    abstracts the shared parameters, and delegates to other isos at those parameters.
1397    let mut isos = Vec::new();
1398    let mut iso_names = Vec::new();
1399    for node in &nodes {
1400        let to_ty = nest.close_pi(arrow(node.applied(), node.generic()));
1401        let from_ty = nest.close_pi(arrow(node.generic(), node.applied()));
1402        isos.push((
1403            node.to_name.clone(),
1404            to_ty,
1405            nest.close_lam(build_to_generic(node)),
1406        ));
1407        isos.push((
1408            node.from_name.clone(),
1409            from_ty,
1410            nest.close_lam(build_from_generic(node)),
1411        ));
1412        iso_names.push(IsoNames {
1413            container: node.container.clone(),
1414            sibling: node.repr.clone(),
1415            to_generic: node.to_name.clone(),
1416            from_generic: node.from_name.clone(),
1417        });
1418    }
1419
1420    Ok(Compiled {
1421        block,
1422        isos,
1423        iso_names,
1424        siblings,
1425        parameters: nest.params.clone(),
1426    })
1427}
1428
1429/// Wrap a conversion body `λ x : dom. match x …` in a fixpoint only when some constructor
1430/// recurs on the spine — a container with no self-recursion converts without one.
1431fn fixpoint(node: &SibNode, dom: Term, motive_body: Term, cases: Vec<Term>) -> Term {
1432    let body = lam(
1433        "x",
1434        dom.clone(),
1435        Term::Match {
1436            discriminant: Box::new(v("x")),
1437            motive: Box::new(lam("_", dom, motive_body)),
1438            cases,
1439        },
1440    );
1441    if node.has_spine() {
1442        Term::Fix {
1443            name: "rec".to_string(),
1444            body: Box::new(body),
1445        }
1446    } else {
1447        body
1448    }
1449}
1450
1451/// `to_generic : sibling → C generic₁ … genericₙ` — rebuild each sibling constructor as the
1452/// corresponding container constructor at the arguments' GENERIC types, recursing on spine
1453/// fields and delegating each parameter field to that parameter's own `to` iso (identity at
1454/// an inert argument or the base leaf).
1455fn build_to_generic(node: &SibNode) -> Term {
1456    let mut cases = Vec::new();
1457    for (orig_ctor, kinds) in &node.ctors {
1458        // λa₀ … a_{k-1}. C_ctor generic₁ … genericₙ (convert a₀) … (convert a_{k-1})
1459        let mut body = apps(node.constructor(orig_ctor), node.arg_generic.clone());
1460        for (i, kind) in kinds.iter().enumerate() {
1461            body = app(
1462                body,
1463                convert(node, kind, v(&format!("a{i}")), &node.arg_to, true),
1464            );
1465        }
1466        for (i, kind) in kinds.iter().enumerate().rev() {
1467            body = lam(&format!("a{i}"), node.sib_field_ty(kind), body);
1468        }
1469        cases.push(body);
1470    }
1471    fixpoint(node, node.applied(), node.generic(), cases)
1472}
1473
1474/// `from_generic : C generic₁ … genericₙ → sibling` — rebuild each container constructor
1475/// (matched at the arguments' generic types) as the corresponding sibling constructor,
1476/// recursing on the spine and delegating each parameter field to that parameter's `from` iso.
1477fn build_from_generic(node: &SibNode) -> Term {
1478    let mut cases = Vec::new();
1479    for (orig_ctor, kinds) in &node.ctors {
1480        let mut body = node.at_params(&format!("{}_{}", node.repr, orig_ctor));
1481        for (i, kind) in kinds.iter().enumerate() {
1482            body = app(
1483                body,
1484                convert(node, kind, v(&format!("a{i}")), &node.arg_from, false),
1485            );
1486        }
1487        for (i, kind) in kinds.iter().enumerate().rev() {
1488            // The binder types are the CONTAINER constructor's value fields at the generic
1489            // arguments.
1490            body = lam(&format!("a{i}"), node.gen_field_ty(kind), body);
1491        }
1492        cases.push(body);
1493    }
1494    fixpoint(node, node.generic(), node.applied(), cases)
1495}
1496
1497/// Convert one field of a container constructor: recurse (`rec a`) on a spine occurrence, and
1498/// delegate a parameter field to that parameter's iso (identity when the argument is inert or is
1499/// the inductive itself).
1500fn convert(
1501    node: &SibNode,
1502    kind: &FieldKind,
1503    a: Term,
1504    isos: &[Option<Conversion>],
1505    to_generic: bool,
1506) -> Term {
1507    match kind {
1508        FieldKind::Spine => app(v("rec"), a),
1509        FieldKind::Param(j) => apply_conversion(node, isos[*j].as_ref(), a),
1510        // A carried field has the SAME type on both sides — there is nothing to convert, and
1511        // anything other than the identity here would be a value the round trip does not return.
1512        FieldKind::Carried(_) => a,
1513        FieldKind::Nested(spec) => apply_conversion(
1514            node,
1515            if to_generic {
1516                spec.to.as_ref()
1517            } else {
1518                spec.from.as_ref()
1519            },
1520            a,
1521        ),
1522        FieldKind::Pointwise {
1523            point,
1524            domain,
1525            result,
1526        } => lam(
1527            point,
1528            domain.clone(),
1529            convert(node, result, app(a, v(point)), isos, to_generic),
1530        ),
1531    }
1532}
1533
1534/// `conversion` applied to `a`; no conversion is the identity.
1535fn apply_conversion(node: &SibNode, conversion: Option<&Conversion>, a: Term) -> Term {
1536    match conversion {
1537        None => a,
1538        Some(Conversion::Iso(iso)) => app(node.at_params(iso), a),
1539        Some(Conversion::Pointwise {
1540            point,
1541            domain,
1542            result,
1543        }) => lam(
1544            point,
1545            domain.clone(),
1546            apply_conversion(node, Some(result), app(a, v(point))),
1547        ),
1548    }
1549}
1550
1551/// A recursor whose motive and constructor terms retain the source container applications.
1552pub struct NativeRecursor {
1553    /// The source datatype or a fully applied original container instance, open exactly over
1554    /// [`NativeRecursor::parameters`].
1555    pub carrier: Term,
1556    /// The canonical uniform parameter telescope the carrier is open over — the telescope the
1557    /// recursor's type and body abstract first. Empty for an unparameterized nested inductive.
1558    pub parameters: Vec<(String, Term)>,
1559    /// Independent motive universe parameters, in motive order.
1560    pub levels: Vec<String>,
1561    /// The recursor telescope over original carrier and constructor terms.
1562    pub ty: Term,
1563    /// The guarded implementation, checked in the original source context.
1564    pub body: Term,
1565}
1566
1567/// Reconstruct checked generic recursors from the existing mutual generator.
1568///
1569/// The source nested datatype must already be checked and registered in ctx.
1570/// Results, motives and minor groups follow source/container discovery order.
1571/// Specialization lives in a private context; each restored implementation is
1572/// checked again against the original generic declarations before being returned.
1573pub fn derive_native_recursors(
1574    ctx: &Context,
1575    decl: &NestedDecl,
1576) -> KernelResult<Vec<NativeRecursor>> {
1577    derive_native_recursors_with_params(ctx, decl, 0)
1578}
1579
1580/// [`derive_native_recursors`] for a nested inductive with `num_params` uniform parameters.
1581/// The restored recursors abstract the parameters first, exactly as Lean's generated nested
1582/// recursors do (`PTree.rec : {α : Type} → {motive_1 …} → {motive_2 …} → …`).
1583pub fn derive_native_recursors_with_params(
1584    ctx: &Context,
1585    decl: &NestedDecl,
1586    num_params: usize,
1587) -> KernelResult<Vec<NativeRecursor>> {
1588    derive_native_recursors_poly(ctx, decl, num_params, &[])
1589}
1590
1591/// [`derive_native_recursors_with_params`] for a universe-polymorphic family. Each restored
1592/// recursor's levels are its motive universes followed by the family's own `levels`, in order.
1593pub fn derive_native_recursors_poly(
1594    ctx: &Context,
1595    decl: &NestedDecl,
1596    num_params: usize,
1597    levels: &[String],
1598) -> KernelResult<Vec<NativeRecursor>> {
1599    derive_nested_block_recursors(
1600        ctx,
1601        &NestedBlock {
1602            members: std::slice::from_ref(decl),
1603            num_params,
1604            levels,
1605        },
1606    )
1607}
1608
1609/// A block of source families, each nesting itself or a sibling inside registered containers:
1610/// one family, or an ordinary mutual block. The members share `num_params` uniform parameters
1611/// and the universe parameters `levels`, and may each carry indices of their own.
1612pub struct NestedBlock<'a> {
1613    pub members: &'a [NestedDecl],
1614    pub num_params: usize,
1615    pub levels: &'a [String],
1616}
1617
1618/// The auxiliary mutual block Lean's kernel reduces a nested block to.
1619pub struct Elimination {
1620    /// The source members with every nested occurrence replaced, then one auxiliary family per
1621    /// distinct nested container instance — in Lean's discovery order.
1622    pub block: Vec<MutualInductive>,
1623    /// Each auxiliary family and auxiliary constructor, by name, and the source term it stands
1624    /// for, open over [`Elimination::parameters`].
1625    pub restoration: Vec<(String, Term)>,
1626    pub parameters: Vec<(String, Term)>,
1627}
1628
1629/// Equality of rigid result universes, not one-way cumulativity or parameter unification.
1630fn nested_sorts_equal(a: &Term, b: &Term) -> bool {
1631    match (a, b) {
1632        (Term::Sort(a), Term::Sort(b)) => a.equiv(b),
1633        _ => false,
1634    }
1635}
1636
1637/// Reduce a nested block to an ordinary mutual block exactly as Lean's kernel does
1638/// (`elim_nested_inductive`).
1639///
1640/// Every constructor field of every member is scanned left to right, top-down. A fully applied
1641/// inductive `C A₁ … Aₚ i₁ … iᵣ` that is not a member, whose PARAMETERS mention a member, is a
1642/// nested occurrence: it becomes an auxiliary family `Aux P i₁ … iᵣ` over the block's
1643/// parameters, one per distinct `C A₁ … Aₚ`, whose constructors are `C`'s constructors at
1644/// `A₁ … Aₚ` rewritten the same way. Auxiliary families join the end of the queue, so the block
1645/// order — and with it the recursors, motives and minor premises — is Lean's (all source
1646/// members first, then each auxiliary as it is discovered: `List (Prod α T)` before the
1647/// `Prod α T` inside it). Indices stay indices: an indexed container becomes an indexed
1648/// auxiliary family. A nested occurrence whose parameters mention a constructor's own field
1649/// binders is an invalid declaration, as Lean says; one whose indices mention the block is
1650/// declined. Nothing here is trusted: the caller registers the block through the trusted mutual
1651/// door, which checks positivity and universes.
1652pub fn eliminate_nested(ctx: &Context, block: &NestedBlock) -> KernelResult<Elimination> {
1653    let refuse =
1654        |why: String| KernelError::CertificationError(format!("nested-elimination: {why}"));
1655    let first = block
1656        .members
1657        .first()
1658        .ok_or_else(|| refuse("an empty block".into()))?;
1659    let nests = block
1660        .members
1661        .iter()
1662        .map(|member| nesting_indexed(member, block.num_params))
1663        .collect::<KernelResult<Vec<_>>>()?;
1664    let params = nests[0].params.clone();
1665    for (member, nest) in block.members.iter().zip(&nests) {
1666        if nest.params != params {
1667            return Err(refuse(format!(
1668                "'{}' does not share the block's parameters",
1669                member.name
1670            )));
1671        }
1672    }
1673    let sort = nests[0].sort.clone();
1674    if nests
1675        .iter()
1676        .any(|nest| !nested_sorts_equal(&nest.sort, &sort))
1677    {
1678        return Err(refuse("the block's members live in different sorts".into()));
1679    }
1680    let mut elimination = Eliminator {
1681        ctx,
1682        params: params.clone(),
1683        levels: block.levels.to_vec(),
1684        members: block.members.iter().map(|m| m.name.clone()).collect(),
1685        base: first.name.clone(),
1686        auxiliaries: Vec::new(),
1687    };
1688    let mut emitted = Vec::new();
1689    for (member, nest) in block.members.iter().zip(&nests) {
1690        let mut constructors = Vec::new();
1691        for (name, ty) in &nest.constructors {
1692            let rewritten = elimination.replace(ty, &mut Vec::new())?;
1693            constructors.push((name.clone(), close_pi(&params, rewritten)));
1694        }
1695        emitted.push(MutualInductive {
1696            name: member.name.clone(),
1697            sort: close_pi(&params, nest.indexed_sort.clone()),
1698            num_params: block.num_params,
1699            constructors,
1700        });
1701    }
1702    let mut restoration = Vec::new();
1703    let mut next = 0;
1704    while next < elimination.auxiliaries.len() {
1705        let (name, container, arguments) = {
1706            let aux = &elimination.auxiliaries[next];
1707            (
1708                aux.name.clone(),
1709                aux.container.clone(),
1710                aux.arguments.clone(),
1711            )
1712        };
1713        let container_name = referenced_name(&container)
1714            .expect("a container reference")
1715            .to_string();
1716        let instance = |constructor: &str| match &container {
1717            Term::Const { levels, .. } => Term::Const {
1718                name: constructor.into(),
1719                levels: levels.clone(),
1720            },
1721            _ => g(constructor),
1722        };
1723        // The auxiliary family's own telescope: the container's indices at these arguments.
1724        let mut arity = crate::infer_type(ctx, &container)?;
1725        for argument in &arguments {
1726            let Term::Pi {
1727                param, body_type, ..
1728            } = arity
1729            else {
1730                return Err(refuse(format!(
1731                    "container '{container_name}' has fewer parameters than applied"
1732                )));
1733            };
1734            arity = crate::substitute(&body_type, &param, argument);
1735        }
1736        let mut result = &arity;
1737        while let Term::Pi { body_type, .. } = result {
1738            result = body_type;
1739        }
1740        if !nested_sorts_equal(result, &sort) {
1741            return Err(refuse(format!(
1742                "the nested instance {} lives in {result}, not the block's {sort}",
1743                apps(container.clone(), arguments.clone())
1744            )));
1745        }
1746        let mut constructors = Vec::new();
1747        for (constructor, _) in ctx.get_constructors(&container_name) {
1748            let mut ty = crate::infer_type(ctx, &instance(constructor))?;
1749            for argument in &arguments {
1750                let Term::Pi {
1751                    param, body_type, ..
1752                } = ty
1753                else {
1754                    return Err(refuse(format!(
1755                        "constructor '{constructor}' binds fewer parameters than its family"
1756                    )));
1757                };
1758                ty = crate::substitute(&body_type, &param, argument);
1759            }
1760            let rewritten = elimination.replace(&ty, &mut Vec::new())?;
1761            let auxiliary_constructor = format!("{name}${constructor}");
1762            restoration.push((
1763                auxiliary_constructor.clone(),
1764                apps(instance(constructor), arguments.clone()),
1765            ));
1766            constructors.push((auxiliary_constructor, close_pi(&params, rewritten)));
1767        }
1768        restoration.push((name.clone(), apps(container.clone(), arguments.clone())));
1769        emitted.push(MutualInductive {
1770            name,
1771            sort: close_pi(&params, arity),
1772            num_params: block.num_params,
1773            constructors,
1774        });
1775        next += 1;
1776    }
1777    if elimination.auxiliaries.is_empty() {
1778        return Err(refuse(format!(
1779            "'{}' has no nested occurrence — register it directly",
1780            first.name
1781        )));
1782    }
1783    Ok(Elimination {
1784        block: emitted,
1785        restoration,
1786        parameters: params,
1787    })
1788}
1789
1790fn close_pi(params: &[(String, Term)], body: Term) -> Term {
1791    params
1792        .iter()
1793        .rev()
1794        .fold(body, |b, (p, t)| pi(p, t.clone(), b))
1795}
1796
1797/// A member with its uniform parameters split onto the canonical telescope; indices may follow.
1798struct IndexedNesting {
1799    params: Vec<(String, Term)>,
1800    /// The member's final sort.
1801    sort: Term,
1802    /// The member's telescope after its parameters: its indices, then its sort.
1803    indexed_sort: Term,
1804    /// Each constructor's field telescope and result, over the canonical parameters.
1805    constructors: Vec<(String, Term)>,
1806}
1807
1808fn nesting_indexed(decl: &NestedDecl, num_params: usize) -> KernelResult<IndexedNesting> {
1809    let refuse = |why: String| {
1810        KernelError::CertificationError(format!("nested-elimination: '{}' {why}", decl.name))
1811    };
1812    let mut params = Vec::with_capacity(num_params);
1813    let mut indexed_sort = decl.sort.clone();
1814    for i in 0..num_params {
1815        let name = format!("nested.parameter.{i}");
1816        let Term::Pi {
1817            param,
1818            param_type,
1819            body_type,
1820        } = indexed_sort
1821        else {
1822            return Err(refuse(format!(
1823                "declares {num_params} parameter(s) but its sort binds fewer"
1824            )));
1825        };
1826        params.push((name.clone(), *param_type));
1827        indexed_sort = crate::substitute(&body_type, &param, &v(&name));
1828    }
1829    let mut sort = &indexed_sort;
1830    while let Term::Pi { body_type, .. } = sort {
1831        sort = body_type;
1832    }
1833    if !matches!(sort, Term::Sort(_)) {
1834        return Err(refuse(format!("ends in {sort}, not a sort")));
1835    }
1836    let sort = sort.clone();
1837    let mut constructors = Vec::with_capacity(decl.constructors.len());
1838    for (cname, cty) in &decl.constructors {
1839        let mut ty = cty.clone();
1840        for (name, domain) in &params {
1841            let Term::Pi {
1842                param,
1843                param_type,
1844                body_type,
1845            } = ty
1846            else {
1847                return Err(refuse(format!(
1848                    "constructor '{cname}' binds fewer than its {num_params} parameter(s)"
1849                )));
1850            };
1851            if *param_type != *domain {
1852                return Err(refuse(format!(
1853                    "constructor '{cname}' binds parameter {name} at {param_type}, but the sort binds it \
1854                     at {domain} — nested parameters are uniform")));
1855            }
1856            ty = crate::substitute(&body_type, &param, &v(name));
1857        }
1858        constructors.push((cname.clone(), ty));
1859    }
1860    Ok(IndexedNesting {
1861        params,
1862        sort,
1863        indexed_sort,
1864        constructors,
1865    })
1866}
1867
1868/// One auxiliary family: the nested container instance `container arguments…` it stands for.
1869struct Auxiliary {
1870    name: String,
1871    container: Term,
1872    arguments: Vec<Term>,
1873}
1874
1875struct Eliminator<'a> {
1876    ctx: &'a Context,
1877    params: Vec<(String, Term)>,
1878    levels: Vec<String>,
1879    /// Source members, then auxiliary families as they are discovered.
1880    members: Vec<String>,
1881    base: String,
1882    auxiliaries: Vec<Auxiliary>,
1883}
1884
1885impl Eliminator<'_> {
1886    fn mentions_block(&self, term: &Term) -> bool {
1887        self.members.iter().any(|m| occurs_anywhere(term, m))
1888    }
1889
1890    /// Rewrite every nested occurrence in `term`, top-down. `locals` are the binders of the
1891    /// constructor telescope in scope; a nested container's parameters may not mention them.
1892    fn replace(&mut self, term: &Term, locals: &mut Vec<String>) -> KernelResult<Term> {
1893        let (head, args) = spine(term);
1894        if let Some(container) = referenced_name(head) {
1895            let container = container.to_string();
1896            if !self.members.contains(&container) && self.ctx.is_inductive(&container) {
1897                let p = self.ctx.inductive_num_params(&container);
1898                if args.len() == self.ctx.inductive_arity(&container)
1899                    && p <= args.len()
1900                    && args[..p].iter().any(|a| self.mentions_block(a))
1901                {
1902                    if let Some(local) = locals
1903                        .iter()
1904                        .find(|l| args[..p].iter().any(|a| mentions_var(a, l)))
1905                    {
1906                        return Err(KernelError::InvalidDeclaration(format!(
1907                            "nested-elimination: the nested occurrence {term} mentions the constructor's \
1908                             own binder '{local}' in a container parameter")));
1909                    }
1910                    if args[p..].iter().any(|i| self.mentions_block(i)) {
1911                        return Err(KernelError::CertificationError(format!(
1912                            "nested-elimination: the nested occurrence {term} mentions the block in an index")));
1913                    }
1914                    let arguments: Vec<Term> = args[..p].iter().map(|a| (*a).clone()).collect();
1915                    let name = self.auxiliary(head, &arguments)?;
1916                    let mut applied = apps(
1917                        reference_at(&name, &self.levels),
1918                        self.params.iter().map(|(p, _)| v(p)).collect(),
1919                    );
1920                    for index in &args[p..] {
1921                        applied = app(applied, (*index).clone());
1922                    }
1923                    return Ok(applied);
1924                }
1925            }
1926        }
1927        Ok(match term {
1928            Term::Pi {
1929                param,
1930                param_type,
1931                body_type,
1932            } => {
1933                let domain = self.replace(param_type, locals)?;
1934                locals.push(param.clone());
1935                let body = self.replace(body_type, locals);
1936                locals.pop();
1937                pi(param, domain, body?)
1938            }
1939            Term::Lambda {
1940                param,
1941                param_type,
1942                body,
1943            } => {
1944                let domain = self.replace(param_type, locals)?;
1945                locals.push(param.clone());
1946                let inner = self.replace(body, locals);
1947                locals.pop();
1948                lam(param, domain, inner?)
1949            }
1950            Term::App(f, a) => app(self.replace(f, locals)?, self.replace(a, locals)?),
1951            Term::Let {
1952                name,
1953                ty,
1954                value,
1955                body,
1956            } => {
1957                let ty = self.replace(ty, locals)?;
1958                let value = self.replace(value, locals)?;
1959                locals.push(name.clone());
1960                let inner = self.replace(body, locals);
1961                locals.pop();
1962                Term::Let {
1963                    name: name.clone(),
1964                    ty: Box::new(ty),
1965                    value: Box::new(value),
1966                    body: Box::new(inner?),
1967                }
1968            }
1969            other => other.clone(),
1970        })
1971    }
1972
1973    /// The auxiliary family standing for `container arguments…`, created on first discovery.
1974    fn auxiliary(&mut self, container: &Term, arguments: &[Term]) -> KernelResult<String> {
1975        if let Some(aux) = self
1976            .auxiliaries
1977            .iter()
1978            .find(|aux| aux.container == *container && aux.arguments == arguments)
1979        {
1980            return Ok(aux.name.clone());
1981        }
1982        let name = format!("{}$nested{}", self.base, self.auxiliaries.len() + 1);
1983        if self.ctx.get_global(&name).is_some() || self.members.contains(&name) {
1984            return Err(KernelError::CertificationError(format!(
1985                "nested-elimination: the auxiliary name '{name}' is already taken"
1986            )));
1987        }
1988        self.members.push(name.clone());
1989        self.auxiliaries.push(Auxiliary {
1990            name: name.clone(),
1991            container: container.clone(),
1992            arguments: arguments.to_vec(),
1993        });
1994        Ok(name)
1995    }
1996}
1997
1998/// Reconstruct Lean's recursors for a nested block: the elimination's mutual recursors, each
1999/// restored to the source families and container instances and checked again in `ctx`.
2000///
2001/// The source members must already be registered in `ctx` exactly as declared. Recursors come in
2002/// block order: the source members, then the auxiliary families in discovery order.
2003pub fn derive_nested_block_recursors(
2004    ctx: &Context,
2005    block: &NestedBlock,
2006) -> KernelResult<Vec<NativeRecursor>> {
2007    for decl in block.members {
2008        if ctx.get_global(&decl.name) != Some(&decl.sort)
2009            || ctx.inductive_num_params(&decl.name) != block.num_params
2010            || ctx
2011                .get_constructors(&decl.name)
2012                .iter()
2013                .map(|(n, t)| ((*n).to_string(), (*t).clone()))
2014                .collect::<Vec<_>>()
2015                != decl.constructors
2016        {
2017            return Err(KernelError::CertificationError(
2018                "native nested recursor requires the exact registered source declaration".into(),
2019            ));
2020        }
2021    }
2022    let elimination = eliminate_nested(ctx, block)?;
2023    let elimination = native_specialization::prepare(
2024        ctx,
2025        elimination,
2026        block.levels,
2027        &mut native_specialization::Ordinary,
2028    )?;
2029    let names: Vec<String> = elimination
2030        .parameters
2031        .iter()
2032        .map(|(p, _)| p.clone())
2033        .collect();
2034    let restoration: std::collections::HashMap<String, Term> =
2035        elimination.restoration.iter().cloned().collect();
2036    let mut specialized = ctx.clone();
2037    if block.levels.is_empty() {
2038        specialized.add_mutual_inductives(&elimination.block)?;
2039    } else {
2040        specialized.add_universe_poly_inductives(block.levels, &elimination.block)?;
2041    }
2042    let instance: Vec<crate::term::Universe> = block
2043        .levels
2044        .iter()
2045        .cloned()
2046        .map(crate::term::Universe::Var)
2047        .collect();
2048    let mut result = Vec::new();
2049    for member in &elimination.block {
2050        let (derived, ty, body) = crate::derive_recursor_universe_poly(&specialized, &member.name)?;
2051        let motives = derived
2052            .len()
2053            .checked_sub(block.levels.len())
2054            .filter(|&m| derived[m..] == *block.levels)
2055            .ok_or_else(|| {
2056                KernelError::CertificationError(
2057                    "native nested recursor universe telescope does not end in the family's levels"
2058                        .into(),
2059                )
2060            })?;
2061        let levels = derived[..motives]
2062            .iter()
2063            .chain(block.levels)
2064            .cloned()
2065            .collect();
2066        let ty = restore_native_term(&ty, &restoration, &names, &instance)?;
2067        let body = restore_native_term(&body, &restoration, &names, &instance)?;
2068        let actual = crate::infer_type(ctx, &body)?;
2069        if !crate::defeq_for_test(ctx, &actual, &ty) {
2070            return Err(KernelError::CertificationError(
2071                "restored native nested recursor type differs from its checked implementation"
2072                    .into(),
2073            ));
2074        }
2075        let carrier = restoration.get(&member.name).cloned().unwrap_or_else(|| {
2076            apps(
2077                reference_at(&member.name, block.levels),
2078                names.iter().map(|p| v(p)).collect(),
2079            )
2080        });
2081        result.push(NativeRecursor {
2082            carrier,
2083            parameters: elimination.parameters.clone(),
2084            levels,
2085            ty,
2086            body,
2087        });
2088    }
2089    Ok(result)
2090}
2091
2092/// Replace every specialized sibling and sibling constructor by its source image.
2093///
2094/// Images are open exactly over the shared `params`. A specialized reference is restored only
2095/// as the head of a spine carrying at least those parameters, which instantiate the image;
2096/// the remaining arguments are applied to it. A partially applied reference has no source
2097/// counterpart and is refused rather than restored to an ill-scoped image.
2098fn restore_native_term(
2099    term: &Term,
2100    restoration: &std::collections::HashMap<String, Term>,
2101    params: &[String],
2102    instance: &[crate::term::Universe],
2103) -> KernelResult<Term> {
2104    let go = |t: &Term| restore_native_term(t, restoration, params, instance);
2105    let (head, args) = spine(term);
2106    let specialized = match head {
2107        Term::Global(name) if instance.is_empty() => Some(name),
2108        Term::Const { name, levels } if restoration.contains_key(name) => {
2109            if levels.as_slice() != instance {
2110                return Err(KernelError::CertificationError(format!(
2111                    "native nested restoration met '{name}' at a universe instance other than \
2112                     the family's own"
2113                )));
2114            }
2115            Some(name)
2116        }
2117        _ => None,
2118    };
2119    if let Some(name) = specialized {
2120        if let Some(image) = restoration.get(name) {
2121            if args.len() < params.len() {
2122                return Err(KernelError::CertificationError(format!(
2123                    "native nested restoration met '{name}' applied to {} of its {} shared \
2124                     parameter(s)",
2125                    args.len(),
2126                    params.len()
2127                )));
2128            }
2129            let mut restored = args.into_iter().map(go).collect::<KernelResult<Vec<_>>>()?;
2130            let rest = restored.split_off(params.len());
2131            return Ok(apps(instantiate_parameters(image, params, &restored), rest));
2132        }
2133    }
2134    Ok(match term {
2135        Term::App(f, a) => app(go(f)?, go(a)?),
2136        Term::Pi {
2137            param,
2138            param_type,
2139            body_type,
2140        } => pi(param, go(param_type)?, go(body_type)?),
2141        Term::Lambda {
2142            param,
2143            param_type,
2144            body,
2145        } => lam(param, go(param_type)?, go(body)?),
2146        Term::Let {
2147            name,
2148            ty,
2149            value,
2150            body,
2151        } => Term::Let {
2152            name: name.clone(),
2153            ty: Box::new(go(ty)?),
2154            value: Box::new(go(value)?),
2155            body: Box::new(go(body)?),
2156        },
2157        Term::Match {
2158            discriminant,
2159            motive,
2160            cases,
2161        } => Term::Match {
2162            discriminant: Box::new(go(discriminant)?),
2163            motive: Box::new(go(motive)?),
2164            cases: cases.iter().map(go).collect::<KernelResult<Vec<_>>>()?,
2165        },
2166        Term::Fix { name, body } => Term::Fix {
2167            name: name.clone(),
2168            body: Box::new(go(body)?),
2169        },
2170        Term::MutualFix { defs, index } => Term::MutualFix {
2171            defs: defs
2172                .iter()
2173                .map(|(name, body)| Ok((name.clone(), go(body)?)))
2174                .collect::<KernelResult<Vec<_>>>()?,
2175            index: *index,
2176        },
2177        Term::Global(_)
2178        | Term::Var(_)
2179        | Term::Const { .. }
2180        | Term::Sort(_)
2181        | Term::Lit(_)
2182        | Term::Hole => term.clone(),
2183        Term::Annotated { annotation, term } => Term::Annotated {
2184            annotation: annotation.clone(),
2185            term: Box::new(go(term)?),
2186        },
2187    })
2188}
2189
2190#[path = "elimination_bounded.rs"]
2191mod bounded_elimination;
2192#[path = "bounded_native_restoration.rs"]
2193pub(crate) mod bounded_native_restoration;
2194
2195#[path = "native_recursors_bounded.rs"]
2196pub(crate) mod native_recursors_bounded;
2197
2198#[path = "native_specialization.rs"]
2199mod native_specialization;