Skip to main content

logicaffeine_kernel/
context.rs

1//! Typing context for the kernel.
2//!
3//! A context maps variable names to their types.
4//! Used during type checking to track what variables are in scope.
5
6use crate::term::{Term, Universe};
7use std::collections::HashMap;
8use std::sync::Arc;
9
10// A context snapshot shares immutable declaration payloads even when a later
11// registration forks its name map. Map membership retains Global/Const policy.
12type DefinitionPayload = (Vec<String>, Term, Term);
13type DefinitionMap = HashMap<String, Arc<DefinitionPayload>>;
14
15// Removing an absent entry must not fork an immutable context snapshot (or
16// dissociate its weak cache-generation observers).
17fn remove_shared_entry<V: Clone>(map: &mut Arc<HashMap<String, V>>, name: &str) -> Option<V> {
18    if !map.contains_key(name) {
19        return None;
20    }
21    Arc::make_mut(map).remove(name)
22}
23
24/// One change to a context's registries, newest first: the persistent log the core's mirror reads to
25/// learn what a context changed since the one it mirrors (`dag::mirror`). A clone shares the whole
26/// log; the head's pointer is the lineage's identity, and it cannot alias a freed entry while anyone
27/// holds an `Arc` to it.
28pub(crate) struct LogEntry {
29    pub(crate) name: String,
30    /// The name's registration was removed (shadowed, redeclared or revoked) rather than added.
31    pub(crate) removed: bool,
32    pub(crate) prev: Option<Arc<LogEntry>>,
33}
34
35/// One name's registration, as [`Context::registration`] reads it.
36pub(crate) enum Registration<'a> {
37    /// An inductive family: its arity.
38    Inductive(&'a Term),
39    /// A definition: its type and body.
40    Definition(&'a Term, &'a Term),
41    /// A universe-polymorphic definition: its level parameters, type and body.
42    UniversePoly(&'a [String], &'a Term, &'a Term),
43    /// An axiom: its type.
44    Axiom(&'a Term),
45}
46
47impl std::fmt::Debug for LogEntry {
48    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
49        write!(
50            f,
51            "LogEntry({}{})",
52            if self.removed { "-" } else { "+" },
53            self.name
54        )
55    }
56}
57
58impl Drop for LogEntry {
59    // A long log would otherwise drop recursively, one frame per entry.
60    fn drop(&mut self) {
61        let mut next = self.prev.take();
62        while let Some(entry) = next {
63            match Arc::try_unwrap(entry) {
64                Ok(mut owned) => next = owned.prev.take(),
65                Err(_) => break,
66            }
67        }
68    }
69}
70
71#[path = "context_order_cache.rs"]
72mod order_cache;
73
74#[cfg(test)]
75std::thread_local! {
76    static OPAQUE_INVALIDATION_VISITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
77}
78
79/// Identity of every immutable registry inspected by integer arithmetic attestation.
80/// Weak owners prevent allocation-address reuse without keeping whole map payloads
81/// alive or forcing Arc::make_mut to clone them during later declarations.
82#[derive(Debug)]
83struct ArithmeticGeneration {
84    definitions: std::sync::Weak<DefinitionMap>,
85    declarations: std::sync::Weak<HashMap<String, Term>>,
86    pending: std::sync::Weak<HashMap<String, String>>,
87    inductives: std::sync::Weak<HashMap<String, Term>>,
88    constructors: std::sync::Weak<HashMap<String, (String, Term)>>,
89    constructor_order: std::sync::Weak<HashMap<String, Vec<String>>>,
90    inductive_params: std::sync::Weak<HashMap<String, usize>>,
91    inductive_inferred_params: std::sync::Weak<HashMap<String, usize>>,
92    poly_types: std::sync::Weak<HashMap<String, (Vec<String>, Term)>>,
93    universe_polys: std::sync::Weak<DefinitionMap>,
94}
95impl ArithmeticGeneration {
96    fn of(ctx: &Context) -> Self {
97        Self {
98            definitions: Arc::downgrade(&ctx.definitions),
99            declarations: Arc::downgrade(&ctx.declarations),
100            pending: Arc::downgrade(&ctx.pending),
101            inductives: Arc::downgrade(&ctx.inductives),
102            constructors: Arc::downgrade(&ctx.constructors),
103            constructor_order: Arc::downgrade(&ctx.constructor_order),
104            inductive_params: Arc::downgrade(&ctx.inductive_params),
105            inductive_inferred_params: Arc::downgrade(&ctx.inductive_inferred_params),
106            poly_types: Arc::downgrade(&ctx.poly_types),
107            universe_polys: Arc::downgrade(&ctx.universe_polys),
108        }
109    }
110    fn matches(&self, ctx: &Context) -> bool {
111        self.definitions.ptr_eq(&Arc::downgrade(&ctx.definitions))
112            && self.declarations.ptr_eq(&Arc::downgrade(&ctx.declarations))
113            && self.pending.ptr_eq(&Arc::downgrade(&ctx.pending))
114            && self.inductives.ptr_eq(&Arc::downgrade(&ctx.inductives))
115            && self.constructors.ptr_eq(&Arc::downgrade(&ctx.constructors))
116            && self
117                .constructor_order
118                .ptr_eq(&Arc::downgrade(&ctx.constructor_order))
119            && self
120                .inductive_params
121                .ptr_eq(&Arc::downgrade(&ctx.inductive_params))
122            && self
123                .inductive_inferred_params
124                .ptr_eq(&Arc::downgrade(&ctx.inductive_inferred_params))
125            && self.poly_types.ptr_eq(&Arc::downgrade(&ctx.poly_types))
126            && self
127                .universe_polys
128                .ptr_eq(&Arc::downgrade(&ctx.universe_polys))
129    }
130}
131#[derive(Debug)]
132struct ArithmeticAttestation {
133    generation: ArithmeticGeneration,
134    // Independently attest the complete arithmetic operation dependency closures.
135    results: [Option<bool>; 6],
136    // The defined reflection operations (`reflection::DEFINED`), by position.
137    reflection: [Option<bool>; 7],
138    // Whether `Nat` and `Int` are the canonical families literals are read as.
139    numerals: Option<CanonicalNumerals>,
140}
141
142/// How far the context's numeral families are canonical. A literal reads as the constructor it
143/// names while that constructor is its family's: `0` as `Zero` (`zero`: `Zero : Nat` is a
144/// constructor of `Nat`), `n + 1` as `Succ n` (`succ`: so is `Succ : Nat → Nat`). Literal
145/// arithmetic needs the families exact: `nat`, `Nat` is `Zero` and `Succ` and nothing else; `int`,
146/// `Int` is `Int_ofNat` and `Int_negSucc` over that `Nat`, so `-3` reads as `Int_negSucc 2`.
147#[derive(Debug, Clone, Copy, PartialEq, Eq)]
148pub(crate) struct CanonicalNumerals {
149    pub(crate) zero: bool,
150    pub(crate) succ: bool,
151    pub(crate) nat: bool,
152    pub(crate) int: bool,
153}
154
155/// The annotation and its lexical analysis have the same immutable lifetime.
156/// Context extensions share both; replacing a binding creates a fresh analysis.
157#[derive(Debug)]
158struct LocalBinding {
159    ty: Term,
160    free_names: std::sync::OnceLock<std::collections::HashSet<String>>,
161}
162
163/// Typing context: maps variable names to their types.
164///
165/// The context is immutable-by-default: `extend` creates a new context
166/// with the additional binding, preserving the original.
167///
168/// Also stores global definitions:
169/// - Inductive types (e.g., Nat : Type 0)
170/// - Constructors (e.g., Zero : Nat, Succ : Nat -> Nat)
171/// - Declarations (e.g., hypotheses like h1 : P -> Q)
172#[derive(Debug, Clone, Default)]
173pub struct Context {
174    // A certificate must be checked without using the optimization it licenses.
175    pub(crate) checking_order_recurrence: bool,
176    /// Every change to the registries a declaration lands in, newest first ([`LogEntry`]).
177    admissions: Option<Arc<LogEntry>>,
178    arithmetic_attestation: Arc<std::sync::Mutex<Option<ArithmeticAttestation>>>,
179    order_attestation: Arc<std::sync::Mutex<Option<order_cache::OrderAttestation>>>,
180    checked_opaque: Arc<HashMap<String, crate::prelude::CheckedOpaqueDependencies>>,
181    // Shared direct dependency nodes, with reverse edges for conservative
182    // invalidation. A long theorem chain stores one node per declaration.
183    checked_opaque_graph: Arc<HashMap<String, Arc<std::collections::BTreeSet<String>>>>,
184    checked_opaque_dependents: Arc<HashMap<String, std::collections::BTreeSet<String>>>,
185    pub(crate) quotient_primitives: Arc<HashMap<String, crate::quotient::Certificate>>,
186    pub(crate) prelude_quotient: Option<Arc<crate::quotient::PreludeCertificate>>,
187    /// The certified observational equality (`observational`), when one is registered.
188    pub(crate) observational: Option<Arc<crate::observational::Certificate>>,
189    /// Local variable bindings (from λ and Π) — the only part that grows during type
190    /// inference (one entry per enclosing binder). The context is `extend`ed (cloned) at
191    /// every binder, so the binding TYPES are shared behind `Arc`: cloning the map copies
192    /// pointers, not whole proposition types.
193    bindings: HashMap<String, Arc<LocalBinding>>,
194
195    /// The global environment below is FIXED during inference but the context is
196    /// `extend`ed (cloned) at every λ/Π. Sharing it behind `Rc` makes that clone O(1)
197    /// instead of deep-copying every premise type — the difference between linear and
198    /// quadratic checking of a large certified proof.
199    ///
200    /// Inductive type definitions: name -> sort (e.g., "Nat" -> Type 0)
201    inductives: Arc<HashMap<String, Term>>,
202
203    /// Constructor definitions: name -> (inductive_name, type)
204    constructors: Arc<HashMap<String, (String, Term)>>,
205
206    /// How many LEADING arguments of an inductive's arity are uniform PARAMETERS (as
207    /// opposed to INDICES that vary per constructor). `List (A:Type)` has 1 parameter and
208    /// 0 indices; `Eq (A) (x) : A → Prop` has 2 parameters and 1 index; `Vector (A) : Nat
209    /// → Type` has 1 parameter and 1 index. Absence means "all of the arity is
210    /// parameters" (0 indices) — so every non-indexed inductive behaves exactly as before
211    /// this map existed, and indexed elimination is a strict extension.
212    inductive_params: Arc<HashMap<String, usize>>,
213
214    /// The params/indices split INFERRED from the registered constructors, for an inductive that
215    /// never declared one. Maintained by [`Context::add_constructor`] (registration time, so the
216    /// hot readers stay O(1)) and consulted by [`Context::inductive_num_params`] only when
217    /// `inductive_params` has no explicit entry.
218    ///
219    /// Defaulting to the FULL ARITY instead — what this map replaces — declared every indexed
220    /// family's indices to be parameters. `BVec : Nat → Type 0` claimed one uniform parameter
221    /// while `BVNil : BVec Zero` and `BVCons : … → BVec (Succ n)` target different lengths, so the
222    /// only kind of `match` a length-indexed vector exists for was not typeable at all.
223    inductive_inferred_params: Arc<HashMap<String, usize>>,
224
225    /// Order of constructor registration per inductive.
226    /// HashMap doesn't preserve insertion order, so we track it explicitly.
227    constructor_order: Arc<HashMap<String, Vec<String>>>,
228
229    /// Declaration bindings (axioms/hypotheses): name -> type
230    /// Used for certifying proofs where hypotheses are assumed.
231    declarations: Arc<HashMap<String, Term>>,
232
233    /// Definition bodies: name -> (type, body)
234    /// Definitions are transparent - they unfold during normalization.
235    /// Distinguished from declarations (axioms) which have no body.
236    definitions: Arc<DefinitionMap>,
237
238    /// Hint database: theorem names marked as hints for auto tactic.
239    /// When auto fails with decision procedures, it tries to apply these hints.
240    hints: Arc<Vec<String>>,
241
242    /// Universe-polymorphic definitions (R3): name -> (universe params, type, body). A
243    /// `Term::Const { name, levels }` reference instantiates these params with `levels`.
244    universe_polys: Arc<DefinitionMap>,
245
246    /// Typeclass instance database (R4): each `(type, value)` is an instance the
247    /// elaborator may resolve for an instance-implicit argument — e.g.
248    /// `(Inhabited Nat, mk Nat Zero)`. Searched by unifying `type` against the required
249    /// class type.
250    ///
251    /// PUSH-ONLY, and nothing may ever depend on an ABSOLUTE count: a declaration-time
252    /// registration can appear at any moment, so a test that pins `instances().len()` has to
253    /// measure RELATIVE to a baseline it captured itself.
254    instances: Arc<Vec<(Term, Term)>>,
255
256    /// Per-instance PRIORITY, index-aligned with `instances` (Lean's `instance (priority := n)`;
257    /// the default is [`DEFAULT_INSTANCE_PRIORITY`]). Kept as a side-car rather than folded into
258    /// the pair so `instances()` stays a true borrowed slice of `(type, value)` — the shape every
259    /// reader already destructures — while the ordering key gains a second component.
260    ///
261    /// The pair is maintained ONLY by [`Context::add_instance_with_priority`]; every other door
262    /// funnels through it, so the two vectors cannot drift.
263    instance_priorities: Arc<Vec<i64>>,
264
265    /// The SCOPE each instance belongs to, index-aligned with `instances`. `0` is the permanent
266    /// (file) scope; `d > 0` is the depth of the [`Context::push_scope`] that owns it, and
267    /// [`Context::pop_scope`] removes exactly those entries. See the scope section below.
268    instance_scopes: Arc<Vec<usize>>,
269
270    /// THE INSTANCE INDEX — Lean's discrimination tree, rooted at the class head symbol.
271    ///
272    /// `Lean/Meta/Instances.lean:67` keeps instances in a `DiscrTree InstanceEntry` and
273    /// `Lean/Meta/SynthInstance.lean:210` queries it with `getUnify`, so a goal is only ever
274    /// offered the entries whose key path could unify with it. A flat `Vec` scanned end to end
275    /// costs a `MetaCtx` clone, a telescope freshening and a full unification attempt PER ENTRY,
276    /// which at a Mathlib-sized instance set stops being a speed question and becomes a
277    /// usability one.
278    ///
279    /// Maps a class head symbol to the `instances` indices whose conclusion is headed by it. An
280    /// entry whose conclusion head is NOT a closed symbol — an instance concluding at a variable
281    /// it binds, or at a δ-reducible name that could unfold into any class — lives in
282    /// `instance_open` instead and is offered to EVERY goal, which is Lean's `star` bucket
283    /// (`Lean/Meta/DiscrTree.lean:727`, where `getUnify` unions `getStarResult d` into every
284    /// answer). Losing a `star` entry is the one way an index can silently drop an instance.
285    instance_by_head: Arc<HashMap<String, Vec<usize>>>,
286
287    /// The `star` bucket of [`Context::instance_by_head`] — entries no head symbol can rule out.
288    instance_open: Arc<Vec<usize>>,
289
290    /// The SCOPE each coercion belongs to, index-aligned with `coercions`. Same encoding.
291    coercion_scopes: Arc<Vec<usize>>,
292
293    /// The SCOPE each simp rule belongs to, index-aligned with `simp_rules`. Same encoding.
294    simp_scopes: Arc<Vec<usize>>,
295
296    /// The SCOPE each hint belongs to, index-aligned with `hints`. Same encoding.
297    hint_scopes: Arc<Vec<usize>>,
298
299    /// How many scopes are currently OPEN — Lean's `section`/`namespace` nesting depth. `0` is
300    /// the permanent scope, where an unqualified registration always lands.
301    scope_depth: usize,
302
303    /// DECLARED REDUCIBILITY — Lean's `@[reducible]` / `@[irreducible]`. Only the non-default
304    /// entries are stored, so the overwhelmingly common answer costs one failed hash lookup.
305    reducibility: Arc<HashMap<String, Reducibility>>,
306
307    /// The undo log that makes `local attribute [irreducible]` revert: `(owning scope, name,
308    /// the value that was there before)`. A map cannot be filtered by owner the way the
309    /// index-aligned vectors can, so the PREVIOUS value is recorded and replayed in reverse.
310    reducibility_undo: Arc<Vec<(usize, String, Option<Reducibility>)>>,
311
312    /// REGISTERED REWRITE RULES — the `@[simp]` set, compiled once at registration.
313    ///
314    /// The lemma is stored as the shape a simplifier applies, not as a name to look up: a
315    /// consumer that had to re-open a Π-telescope and re-destructure an `Eq` on every rewrite
316    /// attempt would pay for the parse once per candidate per subterm.
317    simp_rules: Arc<Vec<SimpRule>>,
318
319    /// `simp_rules` indexed by the LHS's head symbol — the dispatch key. Rewriting a subterm
320    /// whose head is `f` consults only the rules that could possibly match it, so adding a
321    /// thousand lemmas about other symbols costs a rewrite attempt nothing.
322    simp_by_head: Arc<HashMap<String, Vec<usize>>>,
323
324    /// FALLBACK instances — a second, strictly lower tier consulted only after every entry in
325    /// `instances` has failed. Lean's `default_instance`s and its derived `Decidable` machinery
326    /// live in exactly such a tier: a library entry must never outrank something the user
327    /// declared, and it must not show up in `instances()` as if the user had declared it.
328    ///
329    /// This is where declaration-time synthesis (`decEq{I}`) and prelude-shipped instances go.
330    fallback_instances: Arc<Vec<(Term, Term)>>,
331
332    /// Registered COERCIONS (E1): each `(from, to, coe)` is a function `coe : from → to` the
333    /// elaborator may insert when an argument of type `from` is supplied where `to` is
334    /// expected — Lean's `Coe`/`↑`. Searched by unifying `from`/`to` against the mismatch.
335    coercions: Arc<Vec<(Term, Term, Term)>>,
336
337    /// PER-BINDER implicitness (E2): a global's parameter kinds in order — implicit,
338    /// explicit, and instance may INTERLEAVE (Lean's `BinderInfo`). Absent means the legacy
339    /// "`implicit_args` leading implicits, rest explicit" model.
340    binder_kinds: Arc<HashMap<String, Vec<crate::elaborate::ParamKind>>>,
341
342    /// PER-PARAMETER DEFAULTS: a global's parameter NAME and the value inlined when the caller
343    /// omits that argument, position by position — Lean's `(m : Int := 3)`.
344    ///
345    /// The name travels with the default because a `Term::Pi`'s binder name is not reliable here:
346    /// `Int -> (m : Int := 3) -> Int` has an ANONYMOUS first binder, and a default that mentions
347    /// an earlier parameter has to be closed over the argument that parameter actually received.
348    /// The declaration door knows both (it runs `TermParser::name_anonymous_binders` before it
349    /// records) and a `Pi` telescope alone does not.
350    param_defaults: Arc<HashMap<String, Vec<(String, Option<Term>)>>>,
351
352    /// How many LEADING parameters of a global are implicit (declared with `{…}` in the
353    /// surface). The surface elaborator inserts and infers that many arguments at each
354    /// application of the global, so the user writes `id 0` for `id Int 0`.
355    implicit_args: Arc<HashMap<String, usize>>,
356
357    /// Registered STRUCTURES (Rung 0c): a structure type name → its metadata. Only
358    /// these one-constructor inductives get DEFINITIONAL ETA (`p ≡ ⟨p.1, …, p.n⟩`),
359    /// keyed here so the rule is local and testable, never inferred for arbitrary
360    /// one-constructor inductives.
361    structures: Arc<HashMap<String, StructInfo>>,
362
363    /// Constants this context AUTO-DERIVED at declaration time (`{I}_rec`, `{I}_noConfusion`,
364    /// `decEq{I}`, …), per inductive.
365    ///
366    /// Provenance, and it is load-bearing: `add_constructor_checked` fires once PER CONSTRUCTOR, so
367    /// the auxiliaries derived after the first constructor describe an inductive that is not
368    /// finished yet. Re-deriving must therefore REPLACE the previous generation — but it must never
369    /// replace a constant a human wrote (the prelude's hand-written `decEqNat` is the live case).
370    /// Recording what we generated is what separates those two.
371    derived_aux: Arc<HashMap<String, Vec<String>>>,
372
373    /// Postpone equation products while a prelude is still replacing auxiliaries.
374    equations_suspended: bool,
375
376    /// The REVERSE of `derived_aux`: auxiliary name → the inductive that generated it.
377    ///
378    /// Two jobs, both O(1). It answers [`Context::is_derived_aux`] — "is this constant ours to
379    /// replace, or did a human write it?" — and it lets [`Context::displace`] DISOWN a name the
380    /// moment anything else registers it, so a re-derivation can never reach in and delete a
381    /// constant that is no longer the one we generated. (The prelude's hand-written `decEqNat`,
382    /// registered after an intermediate generation of `Nat`'s auxiliaries, is exactly that case.)
383    derived_aux_owner: Arc<HashMap<String, String>>,
384
385    /// MUTUAL inductive blocks (K3): each member name → the full ordered list of the
386    /// block's members. `Even`/`Odd`, `Tree`/`Forest` — an inductive registered
387    /// alone maps to nothing (its recursor recurses only on itself). The mutual
388    /// recursor derivation reads this to give each member a motive and to route a
389    /// recursive occurrence of a SIBLING to the sibling's fixpoint.
390    mutual_blocks: Arc<HashMap<String, Vec<String>>>,
391
392    /// DEFERRED registration obligations: definition name → the global name its body mentions that
393    /// was not in scope when it was declared. See [`Context::declare`].
394    ///
395    pending: Arc<HashMap<String, String>>,
396
397    /// The INVERSE index of `pending`: blocker name → the definitions waiting on it. Unblocking is
398    /// then a lookup, not a scan of every outstanding obligation — a translator that emits 20 000
399    /// definitions in forward-reference order must not pay quadratically for the privilege.
400    ///
401    /// Stale entries are permitted and filtered on use (`pending` is the authority on who is still
402    /// waiting), which is what keeps removal O(1).
403    pending_waiters: Arc<HashMap<String, Vec<String>>>,
404
405    /// EAGER declaration-time auxiliary synthesis — Lean's behaviour, and OFF by default here for
406    /// one MEASURED reason. `add_constructor` has no "declaration finished" signal, so eager
407    /// synthesis re-derives after every constructor, and a constructor-disjointness table is
408    /// quadratic in the constructor count. Measured on this prelude (the cost is printed by
409    /// `tests/S_spine_extra.rs`): registering the standard library costs 0.18 s with synthesis
410    /// QUEUED against 1.11 s synthesising once per INDUCTIVE (31 inductives, 162 auxiliaries) and
411    /// far more again once per CONSTRUCTOR, against a test suite that rebuilds the prelude
412    /// hundreds of times. The per-inductive figure was 17 s before wave 2; the ratio is what the
413    /// switch is for, and the ratio has not changed.
414    ///
415    /// So it is a switch, not a policy baked into the registration door: a caller that wants Lean's
416    /// declaration-time constants turns it on ([`Context::set_auto_auxiliaries`]) or asks for them
417    /// in one pass at the end of a load ([`Context::seal`]), and a library loader that does not
418    /// want 17 s of quadratic tables for its internal AST types pays nothing for them.
419    auto_aux: bool,
420
421    /// Inductives whose auxiliaries are OWED, in first-touch order (so synthesis is deterministic
422    /// and a later member of a mutual block never overtakes an earlier one).
423    dirty_aux: Arc<Vec<String>>,
424
425    /// Declarations [`Context::declare`] REFUSED, as `(name, reason)`, in the order it refused them.
426    ///
427    /// `add_definition` returns `()`, so a refusal it drops would otherwise be invisible — and an
428    /// invisible refusal is how a definition silently stops existing and a distant `rfl` starts
429    /// failing for no stated reason. Recording it makes the gateway auditable: a caller that cannot
430    /// carry an error can still ASK.
431    refused: Arc<Vec<(String, String)>>,
432
433    /// UNIVERSE-POLYMORPHIC TYPE DECLARATIONS: an inductive (or structure) whose ARITY mentions
434    /// level variables — `Mul.{u} : Sort u → Sort u`, `Box.{u} : Sort u → Sort u`.
435    ///
436    /// Deliberately NOT `universe_polys`, and the difference is not bookkeeping: that map is a
437    /// params/type/BODY triple and `reduce_step`'s `Term::Const` arm δ-unfolds whatever it finds
438    /// there. A type former has no body, so entering one would either need a fake body or would
439    /// teach the reducer to find `None` where it expects a term. Keeping the two registries apart
440    /// is what lets `Const { name: "Mul", levels }` TYPE while staying inert to reduction, which
441    /// is exactly what an inductive reference must do.
442    poly_types: Arc<HashMap<String, (Vec<String>, Term)>>,
443
444    /// Each definition's OWN δ-edges: the distinct global names its body mentions, computed once
445    /// when the definition is registered.
446    ///
447    /// The δ-graph is walked by `Context::delta_reaches` once per declaration, and re-deriving
448    /// an edge list by walking a body every time it is visited makes that walk cost the SIZE of
449    /// every reachable body rather than its out-degree. Caching the edges is what keeps the
450    /// acyclicity gate a gate rather than a tax.
451    definition_deps: Arc<HashMap<String, Arc<[String]>>>,
452
453    /// Each registered definition's DEFINITIONAL HEIGHT, computed by this kernel when its body is
454    /// registered: one more than the greatest height among the constants its body mentions, where
455    /// inductives, constructors, axioms and anything without a registered body count as 0. It is
456    /// Lean's reducibility height, never read from an export: lazy δ in conversion unfolds the
457    /// side whose head is higher first. A height orders unfolding only; it decides no equality.
458    definition_heights: Arc<HashMap<String, u32>>,
459
460    /// Every global name that OCCURS in the body of some definition registered here — a monotone
461    /// over-approximation, never pruned.
462    ///
463    /// It exists so [`Context::declare`]'s δ-acyclicity check can be skipped in the case that is
464    /// almost every case: a name nothing mentions cannot be on a cycle, so a fresh declaration
465    /// costs one hash lookup instead of a walk of the δ-graph. Over-approximating is the safe
466    /// direction — a stale entry buys an unnecessary walk, while a missing one would miss a cycle
467    /// — which is why `displace` does not remove from it.
468    referenced: Arc<std::collections::HashSet<String>>,
469    /// Meanings relied on by native nested positivity, including transitive
470    /// container constructors and unfolded aliases. Immutable once relied on:
471    /// changing them could turn an already admitted datatype negative.
472    native_positivity_dependencies: Arc<std::collections::HashSet<String>>,
473    /// Who MENTIONS whom: for each global name, every registered global whose stored type, sort
474    /// or body mentions it. The reverse index the stable-meaning gate reads — see
475    /// [`Context::admit_meaning`] — so asking "was anything checked against this name?" costs the
476    /// size of the answer, not a walk of the environment.
477    mentioned_by: Arc<HashMap<String, std::collections::BTreeSet<String>>>,
478    /// The forward edges of [`Context::mentioned_by`], per registered name, so `displace` can take
479    /// a name's mentions back out exactly.
480    mentions: Arc<HashMap<String, Vec<String>>>,
481    /// What each registered global's stored terms ELIMINATE — recorded once, at registration, so
482    /// the extension gate reads it instead of walking bodies. See [`Eliminations`].
483    eliminations: Arc<HashMap<String, Eliminations>>,
484    /// THE SHADOW TABLE: each written absolute name that denotes a FRESH IDENTITY rather than the
485    /// declaration this environment holds under that name, paired with the identity, in the order
486    /// the written names were first shadowed. One entry per written name — a second shadow of the
487    /// same name replaces the identity in place. See [`Context::record_shadow`].
488    shadows: Arc<Vec<(String, String)>>,
489    /// Every identity minted for a shadow → the written name it was minted for. Kept for the
490    /// identity's whole life, so a shadow that is itself shadowed still has a name to print by.
491    shadow_origins: Arc<HashMap<String, String>>,
492    /// This crate's own unit tests only: the caches that must notice a change of meaning
493    /// (attestations, certificates, lookup memos) are defence in depth behind the stable-meaning
494    /// gate, and testing them needs the change the gate refuses. No public door reaches this.
495    #[cfg(test)]
496    meaning_changes_permitted: bool,
497}
498
499/// How an incoming declaration relates to what its name already means — the question
500/// [`Context::admit_meaning`] is asked.
501#[derive(Debug, Clone, Copy, PartialEq, Eq)]
502enum Change {
503    /// Exactly the current meaning.
504    Identical,
505    /// A body for what is now a bodyless declaration, at the identical type and levels. Every
506    /// checked dependent stays valid — δ only adds conversions — so it is admitted even when
507    /// something depends on the name. (An AXIOM stated over the old constant may of course be
508    /// false of the body; an axiom is an assumption, and `#print axioms` still names it.)
509    Refinement,
510    /// Anything else.
511    Different,
512}
513
514/// What a registration door may do with a name, as decided by [`Context::admit_meaning`].
515#[derive(Debug, Clone, Copy, PartialEq, Eq)]
516enum Admission {
517    /// Nothing outside the name's declaration unit depends on it: register (and displace) as
518    /// usual.
519    Register,
520    /// Something depends on the name, and the incoming declaration is EXACTLY what it already
521    /// means: nothing changes, so nothing is done.
522    Keep,
523}
524
525/// The outcome of checking a body in [`Context::declare`].
526enum Verdict {
527    /// The body was inferred and has the declared type.
528    Checked,
529    /// The body mentions this name, which is not in scope yet; the check is owed.
530    Pending(String),
531}
532
533/// One member of a MUTUAL inductive block: its name, arity sort, uniform parameter
534/// count, and constructors (name + full type). Constructor types may reference ANY
535/// member of the block — that is the whole point of a mutual declaration.
536#[derive(Clone, Debug)]
537pub struct MutualInductive {
538    /// The inductive's name (e.g. `Even`).
539    pub name: String,
540    /// Its arity sort (e.g. `Nat → Prop`).
541    pub sort: Term,
542    /// How many leading arity arguments are uniform parameters (the rest are indices).
543    pub num_params: usize,
544    /// Constructors: `(name, full type)`, types possibly mentioning sibling members.
545    pub constructors: Vec<(String, Term)>,
546}
547
548/// A coercion as the context stores it: erased, like every term it holds.
549fn stored_coercion(from: Term, to: Term, coe: Term) -> (Term, Term, Term) {
550    use crate::annotation::stored;
551    (stored(from), stored(to), stored(coe))
552}
553
554/// An inductive block with every annotation erased, or `None` when there is nothing to erase —
555/// the block's terms as the context will store and check them.
556fn erased_block(block: &[MutualInductive]) -> Option<Vec<MutualInductive>> {
557    let annotated = !crate::annotation::within_erased_call()
558        && block.iter().any(|member| {
559            member.sort.has_annotations()
560                || member
561                    .constructors
562                    .iter()
563                    .any(|(_, ty)| ty.has_annotations())
564        });
565    annotated.then(|| {
566        block
567            .iter()
568            .map(|member| MutualInductive {
569                name: member.name.clone(),
570                sort: member.sort.strip_annotations(),
571                num_params: member.num_params,
572                constructors: member
573                    .constructors
574                    .iter()
575                    .map(|(name, ty)| (name.clone(), ty.strip_annotations()))
576                    .collect(),
577            })
578            .collect()
579    })
580}
581
582/// Metadata for a registered structure (record): its single constructor, how many
583/// leading type PARAMETERS it takes, the projection function names in field order, and
584/// the declaration shape the elaborator needs — the parameter and field telescopes, the
585/// parents recovered from a flattened field prefix, and which parameters are OUTPUTS.
586#[derive(Clone, Debug)]
587pub struct StructInfo {
588    /// The constructor name (e.g. `Prod_mk`).
589    pub mk: String,
590    /// Number of leading type parameters (e.g. 2 for `Prod A B`).
591    pub num_params: usize,
592    /// Projection definition names, in field order (e.g. `[Prod_fst, Prod_snd]`).
593    pub projections: Vec<String>,
594    /// The parameter telescope, `(name, type)` in order — `[(A, Type 0), (B, Type 0)]`
595    /// for `Prod`. Kept so a later declaration can be compared against this one.
596    pub params: Vec<(String, Term)>,
597    /// The field telescope, `(name, type)` in order. A field type may mention the
598    /// parameters and any EARLIER field by name.
599    pub fields: Vec<(String, Term)>,
600    /// Structures this one EXTENDS, recovered from its flattened field list: a previously
601    /// declared structure over the identical parameter telescope whose whole field list is
602    /// a strict prefix of this one's. See [`Context::add_structure`].
603    pub parents: Vec<String>,
604    /// Parameter positions that are OUTPUTS — determined BY a resolved instance rather than
605    /// matched against (Lean's `outParam`). Inferred at declaration; overridable with
606    /// [`Context::set_out_params`].
607    pub out_params: Vec<usize>,
608}
609
610/// Lean's default instance priority — what `instance foo : C α := …` gets when it says no
611/// `(priority := n)`. Named rather than spelled `1000` at each site so a translator carrying a
612/// Lean source's explicit priorities lands them on the same scale.
613pub const DEFAULT_INSTANCE_PRIORITY: i64 = 1000;
614
615/// The mark a shadow's fresh identity carries after the name it was minted for (`add✝⟨1⟩`), and
616/// the mark an inaccessible name is printed with (`add✝`). See [`Context::mint_shadow_identity`].
617pub(crate) const SHADOW_MARK: char = '\u{271d}';
618
619impl Context {
620    /// One attested answer, reused for exactly the registry generation it inspected: `read` finds
621    /// it in that generation's entry, `attest` decides it outside the lock, and `write` keeps it.
622    fn attested<T: Copy>(
623        &self,
624        read: impl Fn(&ArithmeticAttestation) -> Option<T>,
625        write: impl FnOnce(&mut ArithmeticAttestation, T),
626        attest: impl FnOnce() -> T,
627    ) -> T {
628        if let Ok(cache) = self.arithmetic_attestation.lock() {
629            if let Some(found) = cache
630                .as_ref()
631                .filter(|entry| entry.generation.matches(self))
632                .and_then(&read)
633            {
634                return found;
635            }
636        }
637        // Do not hold the cache mutex while inspecting definitions.
638        let result = attest();
639        if let Ok(mut cache) = self.arithmetic_attestation.lock() {
640            if !cache
641                .as_ref()
642                .is_some_and(|entry| entry.generation.matches(self))
643            {
644                *cache = Some(ArithmeticAttestation {
645                    generation: ArithmeticGeneration::of(self),
646                    results: [None; 6],
647                    reflection: [None; 7],
648                    numerals: None,
649                });
650            }
651            if let Some(entry) = cache.as_mut() {
652                write(entry, result);
653            }
654        }
655        result
656    }
657
658    /// Reuse a structural arithmetic attestation only for the exact global
659    /// registry generation it inspected. Caller transparency/rewrite policy is
660    /// intentionally checked outside this cache.
661    pub(crate) fn cached_integer_arithmetic(
662        &self,
663        operation: &str,
664        attest: impl FnOnce() -> bool,
665    ) -> bool {
666        let slot = match operation {
667            "add" => 0,
668            "mul" => 1,
669            "sub" => 2,
670            "le" => 3,
671            "div" => 4,
672            "mod" => 5,
673            _ => return false,
674        };
675        self.attested(
676            |entry| entry.results[slot],
677            |entry, result| entry.results[slot] = Some(result),
678            attest,
679        )
680    }
681
682    /// [`Context::cached_integer_arithmetic`] for the defined reflection operations: `slot` is the
683    /// operation's position in `reflection::DEFINED`, and the answer lives as long as every registry
684    /// it read.
685    pub(crate) fn cached_reflection_attestation(
686        &self,
687        slot: usize,
688        attest: impl FnOnce() -> bool,
689    ) -> bool {
690        self.attested(
691            |entry| entry.reflection[slot],
692            |entry, result| entry.reflection[slot] = Some(result),
693            attest,
694        )
695    }
696
697    /// Whether `Nat` and `Int` are the canonical families ([`CanonicalNumerals`]), decided once per
698    /// registry generation.
699    pub(crate) fn canonical_numerals(&self) -> CanonicalNumerals {
700        self.attested(
701            |entry| entry.numerals,
702            |entry, numerals| entry.numerals = Some(numerals),
703            || crate::int_inductive::canonical_numerals_of(self),
704        )
705    }
706
707    /// Insert `value` at `name` in one of the registries a declaration lands in, and log it: the
708    /// one door into those registries, so the log cannot miss a registration
709    /// (`context_admission_log_lock`).
710    pub(crate) fn record<V: Clone>(
711        &mut self,
712        table: fn(&mut Context) -> &mut Arc<HashMap<String, V>>,
713        name: String,
714        value: V,
715    ) {
716        Arc::make_mut(table(self)).insert(name.clone(), value);
717        self.log(name, false);
718    }
719
720    fn log(&mut self, name: String, removed: bool) {
721        let prev = self.admissions.take();
722        self.admissions = Some(Arc::new(LogEntry {
723            name,
724            removed,
725            prev,
726        }));
727    }
728
729    /// How `name` is registered, read raw (a pending registration included) and by one precedence:
730    /// an inductive family, a definition, a universe-polymorphic definition, an axiom. A
731    /// constructor is not a registration of its own here; its family's is
732    /// ([`Context::constructor_inductive`]).
733    pub(crate) fn registration(&self, name: &str) -> Option<Registration<'_>> {
734        if let Some(arity) = self.inductives.get(name) {
735            return Some(Registration::Inductive(arity));
736        }
737        if let Some(definition) = self.definitions.get(name) {
738            return Some(Registration::Definition(&definition.1, &definition.2));
739        }
740        if let Some(poly) = self.universe_polys.get(name) {
741            return Some(Registration::UniversePoly(&poly.0, &poly.1, &poly.2));
742        }
743        self.declarations.get(name).map(Registration::Axiom)
744    }
745
746    /// Install the standard library's quotient certificate. A primitive it certifies anew changes
747    /// how the core reads that name (a certified primitive is part of the quotient, not an axiom),
748    /// so each is logged.
749    pub(crate) fn certify_prelude_quotient(
750        &mut self,
751        certificate: crate::quotient::PreludeCertificate,
752    ) {
753        let fresh: Vec<String> = certificate
754            .names()
755            .filter(|n| {
756                !self
757                    .prelude_quotient
758                    .as_ref()
759                    .is_some_and(|held| held.names().any(|m| m == *n))
760            })
761            .map(str::to_string)
762            .collect();
763        self.prelude_quotient = Some(Arc::new(certificate));
764        for name in fresh {
765            self.log(name, false);
766        }
767    }
768
769    /// Install the certificate of an observational equality: its constants compute from now on, so
770    /// each one it certifies anew is logged.
771    pub(crate) fn certify_observational(&mut self, certificate: crate::observational::Certificate) {
772        let fresh: Vec<String> = certificate
773            .names()
774            .filter(|n| {
775                !self
776                    .observational
777                    .as_ref()
778                    .is_some_and(|held| held.names().any(|m| m == *n))
779            })
780            .map(str::to_string)
781            .collect();
782        self.observational = Some(Arc::new(certificate));
783        for name in fresh {
784            self.log(name, false);
785        }
786    }
787
788    /// The newest entry of this context's admission log.
789    pub(crate) fn admissions(&self) -> Option<&Arc<LogEntry>> {
790        self.admissions.as_ref()
791    }
792
793    /// Create an empty context.
794    pub fn new() -> Self {
795        Context {
796            checking_order_recurrence: false,
797            admissions: None,
798            arithmetic_attestation: Arc::new(std::sync::Mutex::new(None)),
799            order_attestation: Arc::new(std::sync::Mutex::new(None)),
800            checked_opaque: Arc::new(HashMap::new()),
801            checked_opaque_graph: Arc::new(HashMap::new()),
802            checked_opaque_dependents: Arc::new(HashMap::new()),
803            quotient_primitives: Arc::new(HashMap::new()),
804            prelude_quotient: None,
805            observational: None,
806            bindings: HashMap::new(),
807            inductives: Arc::new(HashMap::new()),
808            constructors: Arc::new(HashMap::new()),
809            inductive_params: Arc::new(HashMap::new()),
810            inductive_inferred_params: Arc::new(HashMap::new()),
811            constructor_order: Arc::new(HashMap::new()),
812            declarations: Arc::new(HashMap::new()),
813            definitions: Arc::new(HashMap::new()),
814            hints: Arc::new(Vec::new()),
815            universe_polys: Arc::new(HashMap::new()),
816            instances: Arc::new(Vec::new()),
817            instance_priorities: Arc::new(Vec::new()),
818            instance_scopes: Arc::new(Vec::new()),
819            instance_by_head: Arc::new(HashMap::new()),
820            instance_open: Arc::new(Vec::new()),
821            coercion_scopes: Arc::new(Vec::new()),
822            simp_scopes: Arc::new(Vec::new()),
823            hint_scopes: Arc::new(Vec::new()),
824            scope_depth: 0,
825            reducibility: Arc::new(HashMap::new()),
826            reducibility_undo: Arc::new(Vec::new()),
827            simp_rules: Arc::new(Vec::new()),
828            simp_by_head: Arc::new(HashMap::new()),
829            fallback_instances: Arc::new(Vec::new()),
830            coercions: Arc::new(Vec::new()),
831            binder_kinds: Arc::new(HashMap::new()),
832            param_defaults: Arc::new(HashMap::new()),
833            implicit_args: Arc::new(HashMap::new()),
834            structures: Arc::new(HashMap::new()),
835            derived_aux: Arc::new(HashMap::new()),
836            equations_suspended: false,
837            derived_aux_owner: Arc::new(HashMap::new()),
838            mutual_blocks: Arc::new(HashMap::new()),
839            pending: Arc::new(HashMap::new()),
840            pending_waiters: Arc::new(HashMap::new()),
841            auto_aux: false,
842            dirty_aux: Arc::new(Vec::new()),
843            refused: Arc::new(Vec::new()),
844            poly_types: Arc::new(HashMap::new()),
845            definition_deps: Arc::new(HashMap::new()),
846            definition_heights: Arc::new(HashMap::new()),
847            referenced: Arc::new(std::collections::HashSet::new()),
848            native_positivity_dependencies: Arc::new(std::collections::HashSet::new()),
849            mentioned_by: Arc::new(HashMap::new()),
850            mentions: Arc::new(HashMap::new()),
851            eliminations: Arc::new(HashMap::new()),
852            shadows: Arc::new(Vec::new()),
853            shadow_origins: Arc::new(HashMap::new()),
854            #[cfg(test)]
855            meaning_changes_permitted: false,
856        }
857    }
858
859    // ==========================================================================================
860    // THE STABLE-MEANING INVARIANT — a registered global never changes meaning under a dependent
861    // ==========================================================================================
862    //
863    // Lean's environment is append-only: a name is declared once, so nothing checked against it
864    // can ever find it meaning something else. LOGOS lets a name be REDECLARED — the REPL is a
865    // notebook, and a fixture may re-register a shape — and that is sound exactly while nothing
866    // was checked against the old meaning. Without the gate three routes led to a closed proof of
867    // `False` both kernels agreed on: redeclaring a definition a theorem was proved about;
868    // adding a constructor to an inductive a theorem had eliminated exhaustively; and
869    // registering a constructor under a name that was still a definition, so typing read one map
870    // and δ another. Locked by `tests/stable_meaning.rs`.
871
872    /// Whether `name` is registered as a global of any kind.
873    fn is_registered_global(&self, name: &str) -> bool {
874        self.inductives.contains_key(name)
875            || self.constructors.contains_key(name)
876            || self.declarations.contains_key(name)
877            || self.definitions.contains_key(name)
878            || self.universe_polys.contains_key(name)
879            || self.poly_types.contains_key(name)
880    }
881
882    /// Borrow every occupied/reserved global identity for private scratch namespace selection.
883    /// Duplicates are deliberate: no allocation or registration change is needed for this read.
884    pub(crate) fn private_specialization_names(&self) -> impl Iterator<Item = &str> {
885        self.inductives
886            .keys()
887            .chain(self.constructors.keys())
888            .chain(self.declarations.keys())
889            .chain(self.definitions.keys())
890            .chain(self.universe_polys.keys())
891            .chain(self.poly_types.keys())
892            .chain(self.pending.keys())
893            .chain(self.referenced.iter())
894            .chain(self.native_positivity_dependencies.iter())
895            .map(String::as_str)
896    }
897
898    /// Hash-map scans visit vacant buckets too; expose their conservative aggregate capacity.
899    pub(crate) fn private_specialization_name_capacity(&self) -> usize {
900        [
901            self.inductives.capacity(),
902            self.constructors.capacity(),
903            self.declarations.capacity(),
904            self.definitions.capacity(),
905            self.universe_polys.capacity(),
906            self.poly_types.capacity(),
907            self.pending.capacity(),
908            self.referenced.capacity(),
909            self.native_positivity_dependencies.capacity(),
910        ]
911        .into_iter()
912        .fold(0usize, usize::saturating_add)
913    }
914
915    /// The DECLARATION UNIT `name` belongs to: what one declaration introduces, and what is
916    /// regenerated with it — an inductive with its mutual siblings and every member's
917    /// constructors, structure projections and derived auxiliaries; or a definition with the
918    /// auxiliaries derived from it. Members of one unit are never each other's dependents.
919    /// The declaration `name` belongs to: itself, or — for a constructor, a derived auxiliary or a
920    /// structure projection — the declaration that generated it, climbed to the top.
921    fn unit_root(&self, name: &str) -> String {
922        let mut root = name.to_string();
923        let mut climbed = std::collections::HashSet::new();
924        while climbed.insert(root.clone()) {
925            let owner = self
926                .constructors
927                .get(&root)
928                .map(|(owner, _)| owner.clone())
929                .or_else(|| self.derived_aux_owner.get(&root).cloned())
930                .or_else(|| {
931                    self.structures
932                        .iter()
933                        .find(|(_, info)| info.projections.iter().any(|p| p == &root))
934                        .map(|(owner, _)| owner.clone())
935                });
936            match owner {
937                Some(owner) => root = owner,
938                None => break,
939            }
940        }
941        root
942    }
943
944    fn declaration_unit(&self, name: &str) -> std::collections::HashSet<String> {
945        let root = self.unit_root(name);
946        let mut todo: Vec<String> = match self.mutual_blocks.get(&root) {
947            Some(block) => block
948                .iter()
949                .cloned()
950                .chain(std::iter::once(root.clone()))
951                .collect(),
952            None => vec![root],
953        };
954        let mut unit = std::collections::HashSet::new();
955        while let Some(member) = todo.pop() {
956            if !unit.insert(member.clone()) {
957                continue;
958            }
959            if let Some(constructors) = self.constructor_order.get(&member) {
960                todo.extend(constructors.iter().cloned());
961            }
962            if let Some(auxiliaries) = self.derived_aux.get(&member) {
963                todo.extend(auxiliaries.iter().cloned());
964            }
965            if let Some(info) = self.structures.get(&member) {
966                todo.extend(info.projections.iter().cloned());
967            }
968        }
969        unit
970    }
971
972    /// Every registered global OUTSIDE `name`'s declaration unit whose type, sort or body mentions
973    /// a member of it — the declarations that were checked against its current meaning. Sorted,
974    /// so a refusal names its witnesses deterministically.
975    fn external_dependents(&self, name: &str) -> Vec<String> {
976        self.dependents_of_unit(&self.declaration_unit(name))
977    }
978
979    fn dependents_of_unit(&self, unit: &std::collections::HashSet<String>) -> Vec<String> {
980        let mut found = std::collections::BTreeSet::new();
981        for member in unit {
982            if let Some(users) = self.mentioned_by.get(member) {
983                for user in users {
984                    if !unit.contains(user) && self.is_registered_global(user) {
985                        found.insert(user.clone());
986                    }
987                }
988            }
989        }
990        found.into_iter().collect()
991    }
992
993    /// Every registered global that depends on `unit` TRANSITIVELY — through any chain of
994    /// mentions, so a `match` written against a type alias of a member is still found.
995    fn transitive_dependents_of_unit(
996        &self,
997        unit: &std::collections::HashSet<String>,
998    ) -> std::collections::BTreeSet<String> {
999        let mut closure = std::collections::BTreeSet::new();
1000        let mut todo: Vec<&str> = unit.iter().map(String::as_str).collect();
1001        while let Some(name) = todo.pop() {
1002            let Some(users) = self.mentioned_by.get(name) else {
1003                continue;
1004            };
1005            for user in users {
1006                if !unit.contains(user)
1007                    && self.is_registered_global(user)
1008                    && closure.insert(user.clone())
1009                {
1010                    todo.push(user);
1011                }
1012            }
1013        }
1014        closure
1015    }
1016
1017    /// Whether `inductive`'s one constructor stores NOTHING past the parameters — the shape whose
1018    /// constructor set is observable without being named: unit η makes any two values of a
1019    /// fieldless data singleton convertible, and K reduces an eliminator on any proof of a
1020    /// fieldless propositional one. A derivation may have used either anywhere.
1021    fn is_fieldless_singleton(&self, inductive: &str) -> bool {
1022        let constructors = self.get_constructors(inductive);
1023        constructors.len() == 1
1024            && count_leading_pis(constructors[0].1) <= self.inductive_num_params(inductive)
1025    }
1026
1027    /// Whether `dependent` was checked against a member's CONSTRUCTOR SET — so that a new
1028    /// constructor would leave it certified for a statement that is no longer true. It is observed
1029    /// by NAMING a member other than the inductive itself (a constructor, the recursor,
1030    /// `noConfusion`, `below`, a projection…), or by a `match` whose motive eliminates a member or
1031    /// anything defined in terms of one — a `match` whose motive does not show what it eliminates
1032    /// is counted as one.
1033    ///
1034    /// A type that merely MENTIONS the inductive observes nothing: `TTactics := TList (Syntax →
1035    /// Derivation)` stays true however many constructors `Syntax` gains, which is what lets the
1036    /// prelude give `Int` its constructors after the declarations stated over the opaque carrier.
1037    fn observes_constructor_set(
1038        &self,
1039        dependent: &str,
1040        inductive: &str,
1041        unit: &std::collections::HashSet<String>,
1042        observable: &std::collections::BTreeSet<String>,
1043    ) -> bool {
1044        let names_more = self.mentions.get(dependent).is_some_and(|targets| {
1045            targets
1046                .iter()
1047                .any(|target| target != inductive && unit.contains(target))
1048        });
1049        names_more
1050            || self.eliminations.get(dependent).is_some_and(|eliminated| {
1051                eliminated.opaque
1052                    || eliminated
1053                        .heads
1054                        .iter()
1055                        .any(|head| unit.contains(head) || observable.contains(head))
1056            })
1057    }
1058
1059    /// THE GATE every door asks before it (re)declares `name`, told how the incoming
1060    /// declaration relates to what `name` already means.
1061    ///
1062    /// * a name that is not registered, or that nothing outside its declaration unit depends on,
1063    ///   is registered as usual — the notebook convenience, where it is sound;
1064    /// * a body for a bodyless declaration at its identical type is registered too (a
1065    ///   [`Change::Refinement`]);
1066    /// * otherwise a name something depends on keeps its meaning: an identical redeclaration is a
1067    ///   no-op, and any other is REFUSED, naming the dependents checked against the old one.
1068    fn admit_meaning(&self, name: &str, change: Change) -> crate::error::KernelResult<Admission> {
1069        #[cfg(test)]
1070        if self.meaning_changes_permitted {
1071            return Ok(Admission::Register);
1072        }
1073        if !self.is_registered_global(name) || change == Change::Refinement {
1074            return Ok(Admission::Register);
1075        }
1076        let dependents = self.external_dependents(name);
1077        if dependents.is_empty() {
1078            return Ok(Admission::Register);
1079        }
1080        if change == Change::Identical {
1081            return Ok(Admission::Keep);
1082        }
1083        Err(self.meaning_is_relied_on(name, crate::error::MeaningChange::Redeclared, dependents))
1084    }
1085
1086    /// `Identical` when `same` holds, else `Different` — the two-way question most doors ask.
1087    fn change_if(same: bool) -> Change {
1088        if same {
1089            Change::Identical
1090        } else {
1091            Change::Different
1092        }
1093    }
1094
1095    /// The gate for ADDING a constructor to `inductive`: every dependent of an inductive was
1096    /// checked against its constructor set — an exhaustive `match`, a recursor, structure η —
1097    /// so a new constructor is admitted only while nothing outside the declaration depends on it.
1098    fn admit_extension(&self, inductive: &str) -> crate::error::KernelResult<()> {
1099        // A STRUCTURE's η rule (`s ≡ mk (s.1) … (s.n)`) is sound only because it has exactly one
1100        // constructor; a second one would be η-equal to a value it cannot be.
1101        if self.structures.contains_key(inductive) {
1102            return Err(crate::error::KernelError::InvalidDeclaration(format!(
1103                "`{inductive}` is a structure: it has exactly one constructor, and its η rule \
1104                 depends on that, so it cannot be extended"
1105            )));
1106        }
1107        #[cfg(test)]
1108        if self.meaning_changes_permitted {
1109            return Ok(());
1110        }
1111        let unit = self.declaration_unit(inductive);
1112        let closure = self.transitive_dependents_of_unit(&unit);
1113        let observers: Vec<String> = if self.is_fieldless_singleton(inductive) {
1114            closure.into_iter().collect()
1115        } else {
1116            closure
1117                .iter()
1118                .filter(|dependent| {
1119                    self.observes_constructor_set(dependent, inductive, &unit, &closure)
1120                })
1121                .cloned()
1122                .collect()
1123        };
1124        if observers.is_empty() {
1125            return Ok(());
1126        }
1127        Err(self.meaning_is_relied_on(inductive, crate::error::MeaningChange::Extended, observers))
1128    }
1129
1130    /// The gates a constructor passes before it is registered. The identical constructor already
1131    /// registered is kept as it is. Otherwise its inductive must exist, its NAME must not carry a
1132    /// meaning something relies on, and a constructor the inductive does not already list is
1133    /// admitted only while nothing outside the declaration depends on the inductive.
1134    fn admit_constructor(
1135        &self,
1136        name: &str,
1137        inductive: &str,
1138        ty: &Term,
1139    ) -> crate::error::KernelResult<Admission> {
1140        let current = self.constructors.get(name);
1141        if current.is_some_and(|(owner, existing)| owner == inductive && same_meaning(existing, ty))
1142        {
1143            return Ok(Admission::Keep);
1144        }
1145        if !self.is_inductive(inductive) {
1146            return Err(crate::error::KernelError::CertificationError(format!(
1147                "constructor '{name}' names '{inductive}', which is not a registered inductive"
1148            )));
1149        }
1150        self.admit_meaning(name, Change::Different)?;
1151        if !current.is_some_and(|(owner, _)| owner == inductive) {
1152            self.admit_extension(inductive)?;
1153        }
1154        Ok(Admission::Register)
1155    }
1156
1157    /// The refusal, naming each dependent by the declaration it belongs to: `useA_eq_def` is
1158    /// `useA`'s, and the author wrote `useA`.
1159    fn meaning_is_relied_on(
1160        &self,
1161        name: &str,
1162        change: crate::error::MeaningChange,
1163        dependents: Vec<String>,
1164    ) -> crate::error::KernelError {
1165        let dependents: std::collections::BTreeSet<String> = dependents
1166            .iter()
1167            .map(|dependent| self.unit_root(dependent))
1168            .collect();
1169        crate::error::KernelError::StableMeaningViolation {
1170            name: name.to_string(),
1171            change,
1172            dependents: dependents.into_iter().collect(),
1173        }
1174    }
1175
1176    /// Unit tests of the caches behind the stable-meaning gate: from here on this context accepts
1177    /// the changes of meaning the gate refuses, so a test can check that a cache notices one.
1178    #[cfg(test)]
1179    pub(crate) fn permit_meaning_changes_for_cache_tests(&mut self) {
1180        self.meaning_changes_permitted = true;
1181    }
1182
1183    /// Unit tests: apply `change` to a copy of this context under the stable-meaning gate. When
1184    /// the gate refuses it — answered as `StableMeaningViolation`, or recorded by a door that
1185    /// cannot answer — the copy as the refusal left it; `None` when the change was admitted. The
1186    /// context itself is untouched.
1187    #[cfg(test)]
1188    pub(crate) fn refused_meaning_change_for_test(
1189        &self,
1190        change: impl FnOnce(&mut Context) -> crate::error::KernelResult<()>,
1191    ) -> Option<Context> {
1192        let mut copy = self.clone();
1193        let recorded = copy.refused.len();
1194        let answered = change(&mut copy);
1195        let refused = matches!(
1196            answered,
1197            Err(crate::error::KernelError::StableMeaningViolation { .. })
1198        ) || copy.refused[recorded..]
1199            .iter()
1200            .any(|(_, why)| why.starts_with("Stable meaning violation"));
1201        refused.then_some(copy)
1202    }
1203
1204    // ==========================================================================================
1205    // SHADOWS — a written name that denotes a fresh identity
1206    // ==========================================================================================
1207    //
1208    // The gate above never lets a declaration change what a registered key means, and a document
1209    // that writes `Definition add …` has not asked it to: it has introduced ITS `add`. That
1210    // declaration is registered under a FRESH IDENTITY, a key no surface can spell, and the table
1211    // below records that the written name now denotes it. Every key keeps its one meaning; what
1212    // moves is which key a written name reaches, which is name resolution — the surface asks this
1213    // table, and nothing in the kernel reads it.
1214
1215    /// The shadow table, as `(written name, identity)` pairs, in the order the written names were
1216    /// first shadowed.
1217    pub fn shadows(&self) -> &[(String, String)] {
1218        &self.shadows
1219    }
1220
1221    /// The identity the written absolute name `written` denotes, when a shadow redirects it: the
1222    /// table's own entry, or — for a constant DERIVED from a shadowing declaration (a recursor, an
1223    /// equation lemma, a structure's constructor or projection) — that constant, whose key spells
1224    /// the identity where the written name spells the name: `B2_rec` reaches `B2✝⟨1⟩_rec` exactly
1225    /// when `B2` reaches `B2✝⟨1⟩`.
1226    pub fn shadow_of(&self, written: &str) -> Option<String> {
1227        if self.shadows.is_empty() {
1228            return None;
1229        }
1230        if let Some((_, identity)) = self.shadows.iter().find(|(w, _)| w == written) {
1231            return Some(identity.clone());
1232        }
1233        // A derived constant is spelled with its declaration's name inside it (`B2_rec`,
1234        // `decEqB2`), so it is found by putting the identity in the name's place — at each place
1235        // the name occurs — and asking whether that key is derived from the identity.
1236        self.shadows.iter().find_map(|(w, identity)| {
1237            written.match_indices(w.as_str()).find_map(|(at, _)| {
1238                let key = format!("{}{identity}{}", &written[..at], &written[at + w.len()..]);
1239                (self.is_registered_global(&key) && self.owners(&key).any(|o| o == *identity))
1240                    .then_some(key)
1241            })
1242        })
1243    }
1244
1245    /// The declarations `name` was generated by, nearest first: a constructor's inductive, a
1246    /// derived constant's source, a projection's structure — climbed to the top of its unit.
1247    fn owners<'c>(&'c self, name: &str) -> impl Iterator<Item = String> + 'c {
1248        let mut climbed = std::collections::HashSet::from([name.to_string()]);
1249        let mut at = name.to_string();
1250        std::iter::from_fn(move || {
1251            let owner = self
1252                .constructors
1253                .get(&at)
1254                .map(|(owner, _)| owner.clone())
1255                .or_else(|| self.derived_aux_owner.get(&at).cloned())
1256                .or_else(|| {
1257                    self.structures
1258                        .iter()
1259                        .find(|(_, info)| info.projections.iter().any(|p| *p == at))
1260                        .map(|(owner, _)| owner.clone())
1261                })?;
1262            climbed.insert(owner.clone()).then(|| {
1263                at = owner.clone();
1264                owner
1265            })
1266        })
1267    }
1268
1269    /// The written name a minted identity was minted for; `None` for every key no shadow minted.
1270    pub fn shadow_origin(&self, identity: &str) -> Option<&str> {
1271        self.shadow_origins.get(identity).map(String::as_str)
1272    }
1273
1274    /// The minted identity `key` IS, or is DERIVED from (a recursor, an equation lemma, a
1275    /// structure's constructor or projection, spelled with the identity inside its own key).
1276    /// `None` for every key no shadow minted or derived from.
1277    pub fn shadow_root(&self, key: &str) -> Option<String> {
1278        // Every identity carries the mark, so a key without it was neither minted nor derived.
1279        if self.shadow_origins.is_empty() || !key.contains(SHADOW_MARK) {
1280            return None;
1281        }
1282        std::iter::once(key.to_string())
1283            .chain(self.owners(key))
1284            .find(|candidate| {
1285                self.shadow_origins.contains_key(candidate) && key.contains(candidate.as_str())
1286            })
1287    }
1288
1289    /// Whether the minted identity `identity` is the one its written name denotes NOW — `false`
1290    /// once a later declaration of that name has been shadowed in over it.
1291    pub fn is_live_shadow(&self, identity: &str) -> bool {
1292        self.shadow_origins.get(identity).is_some_and(|origin| {
1293            self.shadows
1294                .iter()
1295                .any(|(w, id)| w == origin && id == identity)
1296        })
1297    }
1298
1299    /// The written absolute name that reaches `key` through a shadow, live or not: the name an
1300    /// identity was minted for, or — for a constant derived from an identity — its key with that
1301    /// name in the identity's place. `None` for a key no shadow minted or derived from.
1302    pub fn spelled_by(&self, key: &str) -> Option<String> {
1303        let root = self.shadow_root(key)?;
1304        Some(key.replacen(root.as_str(), &self.shadow_origins[&root], 1))
1305    }
1306
1307    /// How `key` is WRITTEN here, for output that must read as source. A live identity is written
1308    /// as the name it was minted for; an identity whose name has since been shadowed again is
1309    /// written as that name marked inaccessible (`add✝`), the way Lean prints an inaccessible name;
1310    /// a constant derived from an identity is written with the identity's spelling in its place;
1311    /// and a declaration a shadow hides is written with the `_root_` escape, which still reaches
1312    /// it. Every other key is written as itself.
1313    pub fn written_name(&self, key: &str) -> String {
1314        if self.shadows.is_empty() {
1315            return key.to_string();
1316        }
1317        if let Some(root) = self.shadow_root(key) {
1318            let origin = &self.shadow_origins[&root];
1319            let written = if self.is_live_shadow(&root) {
1320                origin.clone()
1321            } else {
1322                format!("{origin}{SHADOW_MARK}")
1323            };
1324            return key.replacen(root.as_str(), &written, 1);
1325        }
1326        if self.shadow_of(key).is_some() {
1327            return format!("_root_.{key}");
1328        }
1329        key.to_string()
1330    }
1331
1332    /// A fresh identity for a declaration of the written name `written`: `written✝⟨n⟩` for the
1333    /// least `n ≥ 1` at which nothing is registered and nothing was minted. Deterministic, so a
1334    /// document read twice mints the same identities; and a key already taken — even one no shadow
1335    /// minted — is stepped past, never reused. No identifier contains `✝` and no `«quoted name»`
1336    /// may contain `⟨`/`⟩`, so no surface can spell what this returns.
1337    pub(crate) fn mint_shadow_identity(&self, written: &str) -> String {
1338        (1u64..)
1339            .map(|n| format!("{written}{SHADOW_MARK}\u{27e8}{n}\u{27e9}"))
1340            .find(|key| !self.is_registered_global(key) && !self.shadow_origins.contains_key(key))
1341            .expect("an unbounded counter reaches a free key")
1342    }
1343
1344    /// Record that the written name `written` now denotes `identity`. A name already shadowed
1345    /// keeps its place in the table and denotes the new identity; the one it denoted before stays
1346    /// registered, keeps every dependent it has, and keeps its origin to be written by.
1347    pub(crate) fn record_shadow(&mut self, written: &str, identity: &str) {
1348        let table = Arc::make_mut(&mut self.shadows);
1349        match table.iter_mut().find(|(w, _)| w == written) {
1350            Some(entry) => entry.1 = identity.to_string(),
1351            None => table.push((written.to_string(), identity.to_string())),
1352        }
1353        Arc::make_mut(&mut self.shadow_origins).insert(identity.to_string(), written.to_string());
1354    }
1355
1356    /// Record that the registered global `name` mentions every global in `term`, and what
1357    /// `term` eliminates.
1358    fn record_mentions(&mut self, name: &str, term: &Term) {
1359        let mut found: Vec<&str> = Vec::new();
1360        collect_global_mentions(term, &mut found);
1361        let found: Vec<String> = found.into_iter().map(str::to_string).collect();
1362        self.record_mention_edges(name, found);
1363        self.record_eliminations(name, term);
1364    }
1365
1366    fn record_eliminations(&mut self, name: &str, term: &Term) {
1367        let mut found = Eliminations::default();
1368        collect_eliminations(term, &mut found);
1369        if found.heads.is_empty() && !found.opaque {
1370            return;
1371        }
1372        let entry = Arc::make_mut(&mut self.eliminations)
1373            .entry(name.to_string())
1374            .or_default();
1375        entry.opaque |= found.opaque;
1376        for head in found.heads {
1377            if !entry.heads.contains(&head) {
1378                entry.heads.push(head);
1379            }
1380        }
1381    }
1382
1383    fn record_mention_edges(&mut self, name: &str, targets: impl IntoIterator<Item = String>) {
1384        let forward = Arc::make_mut(&mut self.mentions)
1385            .entry(name.to_string())
1386            .or_default();
1387        let mut added: Vec<String> = Vec::new();
1388        for target in targets {
1389            if target != name && !forward.contains(&target) {
1390                forward.push(target.clone());
1391                added.push(target);
1392            }
1393        }
1394        if added.is_empty() {
1395            return;
1396        }
1397        let reverse = Arc::make_mut(&mut self.mentioned_by);
1398        for target in added {
1399            reverse.entry(target).or_default().insert(name.to_string());
1400        }
1401    }
1402
1403    /// Take `name`'s mentions out of the index — it is being displaced, so it no longer depends
1404    /// on anything. What depends on IT stays recorded: those declarations still mention it.
1405    fn forget_mentions(&mut self, name: &str) {
1406        if self.eliminations.contains_key(name) {
1407            remove_shared_entry(&mut self.eliminations, name);
1408        }
1409        let Some(targets) = remove_shared_entry(&mut self.mentions, name) else {
1410            return;
1411        };
1412        for target in targets {
1413            if !self
1414                .mentioned_by
1415                .get(&target)
1416                .is_some_and(|users| users.contains(name) || users.is_empty())
1417            {
1418                continue;
1419            }
1420            let reverse = Arc::make_mut(&mut self.mentioned_by);
1421            if let Some(users) = reverse.get_mut(&target) {
1422                users.remove(name);
1423                if users.is_empty() {
1424                    reverse.remove(&target);
1425                }
1426            }
1427        }
1428    }
1429
1430    pub(crate) fn check_native_dependency_mutation(
1431        &self,
1432        name: &str,
1433    ) -> crate::error::KernelResult<()> {
1434        if self.native_positivity_dependencies.contains(name) {
1435            return Err(crate::error::KernelError::CertificationError(format!(
1436                "declaration '{name}' is sealed by a native nested positivity check"
1437            )));
1438        }
1439        Ok(())
1440    }
1441
1442    fn refuse_native_dependency_mutation(&mut self, name: &str) -> bool {
1443        if let Err(error) = self.check_native_dependency_mutation(name) {
1444            self.record_refusal(name, error);
1445            true
1446        } else {
1447            false
1448        }
1449    }
1450
1451    /// A door that cannot return an error records its refusal in the ledger
1452    /// ([`Context::refused_declarations`]) instead of swallowing it.
1453    fn record_refusal(&mut self, name: &str, error: crate::error::KernelError) {
1454        Arc::make_mut(&mut self.refused).push((name.to_string(), error.to_string()));
1455    }
1456
1457    fn check_native_dependencies(
1458        &self,
1459        dependencies: &std::collections::HashSet<String>,
1460    ) -> crate::error::KernelResult<()> {
1461        for name in dependencies {
1462            if self.pending.contains_key(name) {
1463                return Err(crate::error::KernelError::CertificationError(format!(
1464                    "native positivity cannot depend on pending definition '{name}'"
1465                )));
1466            }
1467        }
1468        Ok(())
1469    }
1470
1471    fn seal_native_dependencies(&mut self, dependencies: std::collections::HashSet<String>) {
1472        if dependencies.is_empty() {
1473            return;
1474        }
1475        // Displacing a parent removes its constructors; regenerating its
1476        // auxiliaries removes their definitions. Preserve these owners too.
1477        let mut complete = dependencies;
1478        let mut todo: Vec<_> = complete.iter().cloned().collect();
1479        while let Some(name) = todo.pop() {
1480            let owner = self
1481                .constructors
1482                .get(&name)
1483                .map(|(owner, _)| owner)
1484                .or_else(|| self.derived_aux_owner.get(&name));
1485            if let Some(owner) = owner {
1486                if complete.insert(owner.clone()) {
1487                    todo.push(owner.clone());
1488                }
1489            }
1490        }
1491        Arc::make_mut(&mut self.native_positivity_dependencies).extend(complete);
1492    }
1493
1494    /// Record structure metadata supplied by a caller. Registering [`StructInfo`] grants structure
1495    /// η, so this door grants it only when [`Context::register_structure_checked`]'s decision does:
1496    /// the named projections must be `name`'s projections, and `info`'s constructor and parameter
1497    /// count must be the ones that decision found. The caller's descriptive metadata (field and
1498    /// parameter names, parents, output parameters) is kept. A refusal registers nothing and is
1499    /// recorded in [`Context::refused_declarations`], as every unchecked door records one.
1500    pub fn register_struct_info(&mut self, name: &str, info: StructInfo) {
1501        let refusal = match self.structure_eta_evidence(name, &info.projections) {
1502            Ok(evidence) if evidence.mk == info.mk && evidence.num_params == info.num_params => None,
1503            Ok(evidence) => Some(format!(
1504                "structure metadata for `{name}` names constructor `{}` with {} parameters, but its constructor is `{}` with {}",
1505                info.mk, info.num_params, evidence.mk, evidence.num_params
1506            )),
1507            Err(refusal) => Some(refusal.to_string()),
1508        };
1509        match refusal {
1510            Some(why) => Arc::make_mut(&mut self.refused).push((name.to_string(), why)),
1511            None => self.insert_struct_info(name, info),
1512        }
1513    }
1514
1515    /// Insert structure metadata whose η a caller has already decided: the kernel's own structure
1516    /// builder (which generates the constructor and its projections) and the checked door.
1517    pub(crate) fn insert_struct_info(&mut self, name: &str, mut info: StructInfo) {
1518        if self.refuse_native_dependency_mutation(name) {
1519            return;
1520        }
1521        for (_, ty) in info.params.iter_mut().chain(info.fields.iter_mut()) {
1522            *ty = crate::annotation::stored(std::mem::replace(ty, Term::Hole));
1523        }
1524        self.invalidate_checked_opaque(name);
1525        Arc::make_mut(&mut self.structures).insert(name.to_string(), info);
1526    }
1527
1528    /// The structure metadata for an inductive type name, if it is a registered
1529    /// structure (record). `None` for ordinary inductives — eta never fires for them.
1530    pub fn struct_info(&self, name: &str) -> Option<&StructInfo> {
1531        self.structures.get(name)
1532    }
1533
1534    /// The parameter positions of the class `name` that are OUTPUTS — Lean's `outParam`.
1535    /// An output takes no part in instance MATCHING: the instance determines it, and a
1536    /// mismatch against what the surrounding context expected is an ordinary type error at
1537    /// the use site rather than a different instance. Empty for anything that is not a
1538    /// registered structure.
1539    pub fn out_params(&self, name: &str) -> &[usize] {
1540        self.structures
1541            .get(name)
1542            .map(|i| i.out_params.as_slice())
1543            .unwrap_or(&[])
1544    }
1545
1546    /// Declare the class `name`'s output parameter positions explicitly, replacing the ones
1547    /// [`Context::add_structure`] inferred. The inference is a default for classes declared
1548    /// without annotation; this is the channel a translator uses to carry Lean's `outParam`
1549    /// across exactly.
1550    pub fn set_out_params(&mut self, name: &str, positions: Vec<usize>) {
1551        if let Some(info) = Arc::make_mut(&mut self.structures).get_mut(name) {
1552            info.out_params = positions;
1553        }
1554    }
1555
1556    /// If `name` is a derived parent-forget edge (`{Child}_to{Parent}`, generated by
1557    /// [`Context::add_structure`] from a flattened field prefix), the parent class it forgets
1558    /// to. Instance resolution uses this to tell a HIERARCHY route apart from an ordinary
1559    /// overlapping instance: two routes to one parent that disagree are an incoherent diamond,
1560    /// where two direct instances are merely overlap.
1561    pub fn parent_edge_target(&self, name: &str) -> Option<&str> {
1562        let (child, parent) = name.split_once("_to")?;
1563        let info = self.structures.get(child)?;
1564        info.parents
1565            .iter()
1566            .find(|p| *p == parent)
1567            .map(|p| p.as_str())
1568    }
1569
1570    /// If `ctor` is the constructor of a registered structure, return `(structure
1571    /// name, its info)`. Used to detect an η-expandable constructor head.
1572    pub fn struct_of_constructor(&self, ctor: &str) -> Option<(&str, &StructInfo)> {
1573        let ind = self.constructor_inductive(ctor)?;
1574        let info = self.structures.get(ind)?;
1575        Some((ind, info))
1576    }
1577
1578    /// Record that the global `name` has `count` leading implicit parameters, so the
1579    /// surface elaborator inserts that many inferred arguments at each application.
1580    pub fn set_implicit_args(&mut self, name: &str, count: usize) {
1581        Arc::make_mut(&mut self.implicit_args).insert(name.to_string(), count);
1582    }
1583
1584    /// How many leading parameters of `name` are implicit (0 if none/unknown).
1585    pub fn implicit_args(&self, name: &str) -> usize {
1586        self.implicit_args.get(name).copied().unwrap_or(0)
1587    }
1588
1589    /// Register a typeclass instance: a `value` of type `ty` (e.g. `mk Nat Zero` of type
1590    /// `Inhabited Nat`). The elaborator resolves an instance-implicit argument by
1591    /// searching these for a `ty` that unifies with the required class type.
1592    ///
1593    /// Registered at [`DEFAULT_INSTANCE_PRIORITY`] — Lean's `instance` with no
1594    /// `(priority := …)`. Use [`Context::add_instance_with_priority`] to say otherwise.
1595    pub fn add_instance(&mut self, ty: Term, value: Term) {
1596        self.add_instance_with_priority(ty, value, DEFAULT_INSTANCE_PRIORITY);
1597    }
1598
1599    /// Register a typeclass instance at an explicit PRIORITY — Lean's
1600    /// `instance (priority := n) …`. Higher wins; ties go to the LATER declaration.
1601    pub fn add_instance_with_priority(&mut self, ty: Term, value: Term, priority: i64) {
1602        self.register_instance(ty, value, priority, 0);
1603    }
1604
1605    /// Register a `local instance` — Lean's `local instance`, and the thing the flat push-only
1606    /// `Vec` could not express: it wins for as long as the enclosing scope is open and LEAVES the
1607    /// database at [`Context::pop_scope`].
1608    ///
1609    /// Registered OUTSIDE any open scope this is an ordinary permanent instance, because that is
1610    /// what `local` means at file level in Lean: there is no `end` to revert it.
1611    pub fn add_local_instance(&mut self, ty: Term, value: Term) {
1612        self.add_local_instance_with_priority(ty, value, DEFAULT_INSTANCE_PRIORITY);
1613    }
1614
1615    /// [`Context::add_local_instance`] at an explicit priority.
1616    pub fn add_local_instance_with_priority(&mut self, ty: Term, value: Term, priority: i64) {
1617        let owner = self.scope_depth;
1618        self.register_instance(ty, value, priority, owner);
1619    }
1620
1621    /// The one door every instance registration funnels through, so the three index-aligned
1622    /// vectors cannot drift.
1623    fn register_instance(&mut self, ty: Term, value: Term, priority: i64, owner: usize) {
1624        let (ty, value) = (
1625            crate::annotation::stored(ty),
1626            crate::annotation::stored(value),
1627        );
1628        let index = self.instances.len();
1629        let head = self.discrimination_head(&ty);
1630        Arc::make_mut(&mut self.instances).push((ty, value));
1631        Arc::make_mut(&mut self.instance_priorities).push(priority);
1632        Arc::make_mut(&mut self.instance_scopes).push(owner);
1633        match head {
1634            Some(h) => Arc::make_mut(&mut self.instance_by_head)
1635                .entry(h)
1636                .or_default()
1637                .push(index),
1638            None => Arc::make_mut(&mut self.instance_open).push(index),
1639        }
1640        debug_assert_eq!(self.instances.len(), self.instance_priorities.len());
1641        debug_assert_eq!(self.instances.len(), self.instance_scopes.len());
1642    }
1643
1644    /// The DISCRIMINATION KEY of a class type — the head symbol its conclusion is built from, or
1645    /// `None` when no head symbol can rule anything out.
1646    ///
1647    /// The Π telescope is stripped first, exactly as `mkInstanceKey` strips it with
1648    /// `forallMetaTelescopeReducing` (`Lean/Meta/Instances.lean:97-101`), so
1649    /// `Π{A}. Shown A → Shown (TList A)` keys on `Shown` and not on the arrow.
1650    ///
1651    /// `None` — the `star` bucket — is returned for three shapes, and each is a case where a key
1652    /// would be a LIE rather than an index:
1653    ///
1654    /// * a conclusion headed by a bound variable (`Π(G : Type). G`), which may become any class;
1655    /// * a conclusion headed by a δ-REDUCIBLE name, which unfolds to something else before
1656    ///   anything compares heads — Lean reduces with `reduceDT` before keying
1657    ///   (`Lean/Meta/DiscrTree.lean:352`) and we take the conservative branch instead; and
1658    /// * anything that is not an application of a name at all.
1659    fn discrimination_head(&self, ty: &Term) -> Option<String> {
1660        let mut bound: Vec<&str> = Vec::new();
1661        let mut cur = ty;
1662        while let Term::Pi {
1663            param, body_type, ..
1664        } = cur
1665        {
1666            bound.push(param);
1667            cur = body_type;
1668        }
1669        let mut head = cur;
1670        while let Term::App(f, _) = head {
1671            head = f;
1672        }
1673        let name = match head {
1674            Term::Global(n) => n,
1675            Term::Const { name, .. } => name,
1676            _ => return None,
1677        };
1678        // A binder may SHADOW a global of the same name, and a name the instance itself binds is
1679        // not a class head at all.
1680        if bound.contains(&name.as_str()) {
1681            return None;
1682        }
1683        // A δ-reducible name is not a key: it unfolds before any head comparison happens.
1684        if self.get_definition_body(name).is_some() {
1685            return None;
1686        }
1687        Some(name.clone())
1688    }
1689
1690    /// Rebuild [`Context::instance_by_head`] from `instances`. Called only where the index
1691    /// positions SHIFT — a scope closing compacts the vector — because every other door appends.
1692    fn reindex_instances(&mut self) {
1693        let mut by_head: HashMap<String, Vec<usize>> = HashMap::new();
1694        let mut open: Vec<usize> = Vec::new();
1695        let types: Vec<Term> = self.instances.iter().map(|(t, _)| t.clone()).collect();
1696        for (i, ty) in types.iter().enumerate() {
1697            match self.discrimination_head(ty) {
1698                Some(h) => by_head.entry(h).or_default().push(i),
1699                None => open.push(i),
1700            }
1701        }
1702        self.instance_by_head = Arc::new(by_head);
1703        self.instance_open = Arc::new(open);
1704    }
1705
1706    // ==========================================================================================
1707    // SCOPES — `section` / `namespace` … `end`, and what `local` means
1708    // ==========================================================================================
1709
1710    /// Open a SCOPE — Lean's `section`/`namespace`. Everything registered `local` inside it is
1711    /// reverted by the matching [`Context::pop_scope`]; everything else is permanent.
1712    ///
1713    /// THE INVARIANT, stated once so no future scoped thing can get it wrong: **a scope reverts
1714    /// the four ATTRIBUTE DATABASES — instances, coercions, simp rules, hints — and NEVER a
1715    /// declaration.** A `def` written inside a `section` survives its `end`, which is why
1716    /// snapshotting and restoring the whole context is not a scoping mechanism: it would delete
1717    /// the section's real content along with its attributes.
1718    ///
1719    /// Returns the new depth, so a caller can assert its own nesting.
1720    pub fn push_scope(&mut self) -> usize {
1721        self.scope_depth += 1;
1722        self.scope_depth
1723    }
1724
1725    /// Close the innermost scope — Lean's `end`. Every `local` registration made at this depth
1726    /// leaves the database it was in; declarations made inside are untouched.
1727    ///
1728    /// A `pop_scope` with no scope open is a no-op rather than a panic: an unbalanced `end` is a
1729    /// surface-syntax error, and the kernel's job is to stay consistent, not to be the diagnostic.
1730    pub fn pop_scope(&mut self) {
1731        let closing = self.scope_depth;
1732        if closing == 0 {
1733            return;
1734        }
1735        self.scope_depth -= 1;
1736
1737        // Retain in lock-step so the index-aligned side-cars cannot drift. Each database keeps
1738        // exactly the entries whose owning scope is not the one closing.
1739        let instances_before = self.instances.len();
1740        retain_scoped2(
1741            &mut self.instances,
1742            &mut self.instance_priorities,
1743            &mut self.instance_scopes,
1744            closing,
1745        );
1746        if self.instances.len() != instances_before {
1747            // Positions shifted, so every stored index is stale. Rebuilt rather than patched:
1748            // an index that is a FUNCTION of the vector cannot come to disagree with it.
1749            self.reindex_instances();
1750        }
1751        retain_scoped1(&mut self.coercions, &mut self.coercion_scopes, closing);
1752        retain_scoped1(&mut self.hints, &mut self.hint_scopes, closing);
1753        if self.simp_scopes.iter().any(|d| *d == closing) {
1754            retain_scoped1(&mut self.simp_rules, &mut self.simp_scopes, closing);
1755            self.reindex_simp();
1756        }
1757        self.revert_reducibility(closing);
1758    }
1759
1760    /// How many scopes are open (`0` = the permanent scope).
1761    pub fn scope_depth(&self) -> usize {
1762        self.scope_depth
1763    }
1764
1765    /// Register a FALLBACK instance — one consulted only after every ordinary instance has
1766    /// failed to resolve the goal. This is the tier for library-shipped and DERIVED instances
1767    /// (`decEq{I}`, `Inhabited Nat`): they must be findable, but a user instance for the same
1768    /// goal must always outrank them, and they must not appear in [`Context::instances`], which
1769    /// is the faithful record of what was explicitly declared.
1770    ///
1771    /// Better than Lean in one respect: Lean expresses this with a numeric priority that a user
1772    /// instance can accidentally undercut. A separate tier cannot be undercut at all.
1773    pub fn add_fallback_instance(&mut self, ty: Term, value: Term) {
1774        let (ty, value) = (
1775            crate::annotation::stored(ty),
1776            crate::annotation::stored(value),
1777        );
1778        // Idempotent: declaration-time synthesis re-runs once per constructor, and a fallback
1779        // tier that grew by one entry per re-derivation would turn an n-constructor enum into n
1780        // identical candidates.
1781        if self
1782            .fallback_instances
1783            .iter()
1784            .any(|(t, v)| t == &ty && v == &value)
1785        {
1786            return;
1787        }
1788        Arc::make_mut(&mut self.fallback_instances).push((ty, value));
1789    }
1790
1791    /// All registered FALLBACK instances, as `(type, value)` pairs — the lower tier, searched
1792    /// only once [`Context::instances`] has been exhausted.
1793    pub fn fallback_instances(&self) -> &[(Term, Term)] {
1794        &self.fallback_instances
1795    }
1796
1797    /// Keep fallback candidates that can share the goal's rigid class head, in the
1798    /// existing later-first order. Open/reducible heads stay visible on either side.
1799    /// Recompute in the current context: no cached key can outlive a definition change.
1800    /// This only avoids impossible unification trials, not the fallback head scan.
1801    pub(crate) fn fallback_instance_search_order_for(&self, goal: &Term) -> Vec<usize> {
1802        let head = self.discrimination_head(goal);
1803        (0..self.fallback_instances.len())
1804            .rev()
1805            .filter(|&i| {
1806                match (
1807                    &head,
1808                    self.discrimination_head(&self.fallback_instances[i].0),
1809                ) {
1810                    (Some(expected), Some(actual)) => expected == &actual,
1811                    _ => true,
1812                }
1813            })
1814            .collect()
1815    }
1816
1817    /// The priority of the instance registered at index `i` (Lean's default, 1000, for an
1818    /// instance registered before priorities existed or through [`Context::add_instance`]).
1819    pub fn instance_priority(&self, i: usize) -> i64 {
1820        self.instance_priorities
1821            .get(i)
1822            .copied()
1823            .unwrap_or(DEFAULT_INSTANCE_PRIORITY)
1824    }
1825
1826    /// The order instance resolution must scan [`Context::instances`] in — LEAN'S RULE, stated
1827    /// once, here, so no scan site can invent its own:
1828    ///
1829    /// > higher PRIORITY first; among equal priorities, the LATER declaration first.
1830    ///
1831    /// Earliest-first — what a linear `0..n` scan gives — inverts every tie-break a Lean source
1832    /// relies on, silently: both readings type-check and compute different answers.
1833    ///
1834    /// Returned as indices into `instances()` so a caller can report WHICH entry won and why.
1835    pub fn instance_search_order(&self) -> Vec<usize> {
1836        self.ranked((0..self.instances.len()).collect())
1837    }
1838
1839    /// [`Context::instance_search_order`] restricted to the candidates that could answer `goal` —
1840    /// Lean's `getUnify` against the discrimination tree (`Lean/Meta/SynthInstance.lean:210`),
1841    /// in the same order the unrestricted scan would have visited them.
1842    ///
1843    /// THE INVARIANT, and it is the only one that matters: this is a SUBSET of
1844    /// `instance_search_order()` containing every entry that could possibly unify, in the same
1845    /// relative order. So it changes what a search PAYS, never what it ANSWERS — and
1846    /// `S_spine_extra::the_index_keeps_every_open_candidate_visible_and_the_order_unchanged`
1847    /// holds it to both halves.
1848    ///
1849    /// Returns `(candidates, pruned)`, where `pruned` is how many entries the index excluded
1850    /// without a unification attempt. Lean's tree throws that number away; reporting it is what
1851    /// makes "why did this instance not fire?" answerable.
1852    pub fn instance_search_order_for(&self, goal: &Term) -> (Vec<usize>, usize) {
1853        let Some(head) = self.discrimination_head(goal) else {
1854            // A goal no head symbol describes must see EVERYTHING — the `star` query in
1855            // `getUnify`, which folds over the whole root map.
1856            return (self.instance_search_order(), 0);
1857        };
1858        let mut chosen: Vec<usize> = self
1859            .instance_by_head
1860            .get(&head)
1861            .cloned()
1862            .unwrap_or_default();
1863        chosen.extend_from_slice(&self.instance_open);
1864        let pruned = self.instances.len() - chosen.len();
1865        (self.ranked(chosen), pruned)
1866    }
1867
1868    /// Lean's ordering key applied to a candidate set: higher PRIORITY first, then the LATER
1869    /// declaration. One helper, so a restricted scan and an unrestricted one cannot be ranked by
1870    /// two different rules.
1871    fn ranked(&self, mut order: Vec<usize>) -> Vec<usize> {
1872        // Stable sort on the descending key. Reversing the index first and sorting by descending
1873        // priority alone would rely on stability twice over; keying both components is explicit.
1874        order.sort_by_key(|&i| {
1875            (
1876                std::cmp::Reverse(self.instance_priority(i)),
1877                std::cmp::Reverse(i),
1878            )
1879        });
1880        order
1881    }
1882
1883    /// Register a coercion `coe : from → to` — the elaborator may insert it when an
1884    /// argument of type `from` appears where `to` is expected.
1885    pub fn add_coercion(&mut self, from: Term, to: Term, coe: Term) {
1886        let (from, to, coe) = stored_coercion(from, to, coe);
1887        Arc::make_mut(&mut self.coercions).push((from, to, coe));
1888        Arc::make_mut(&mut self.coercion_scopes).push(0);
1889        debug_assert_eq!(self.coercions.len(), self.coercion_scopes.len());
1890    }
1891
1892    /// A `local` coercion — reverted at [`Context::pop_scope`]. See [`Context::push_scope`].
1893    pub fn add_local_coercion(&mut self, from: Term, to: Term, coe: Term) {
1894        let owner = self.scope_depth;
1895        let (from, to, coe) = stored_coercion(from, to, coe);
1896        Arc::make_mut(&mut self.coercions).push((from, to, coe));
1897        Arc::make_mut(&mut self.coercion_scopes).push(owner);
1898        debug_assert_eq!(self.coercions.len(), self.coercion_scopes.len());
1899    }
1900
1901    /// All registered coercions, as `(from, to, coe)` triples.
1902    pub fn coercions(&self) -> &[(Term, Term, Term)] {
1903        &self.coercions
1904    }
1905
1906    /// Record a global's per-parameter kinds (implicit/explicit/instance, in order), so the
1907    /// elaborator can insert implicit and instance arguments at their real positions.
1908    pub fn set_binder_kinds(&mut self, name: &str, kinds: Vec<crate::elaborate::ParamKind>) {
1909        Arc::make_mut(&mut self.binder_kinds).insert(name.to_string(), kinds);
1910    }
1911
1912    /// A global's per-parameter kinds, if recorded.
1913    pub fn binder_kinds(&self, name: &str) -> Option<&[crate::elaborate::ParamKind]> {
1914        self.binder_kinds.get(name).map(|v| v.as_slice())
1915    }
1916
1917    /// Record a global's per-parameter NAME and DEFAULT VALUE, in telescope order — the surface
1918    /// information a `Term::Pi` has nowhere to put.
1919    ///
1920    /// One entry per position, `None` where the parameter has no default. The declaration door
1921    /// must name its anonymous binders (`TermParser::name_anonymous_binders`) BEFORE it records,
1922    /// or a default that mentions an earlier parameter has no name to be closed over and the
1923    /// elaborator would inline an open term.
1924    pub fn set_param_defaults(&mut self, name: &str, defaults: Vec<(String, Option<Term>)>) {
1925        let defaults = defaults
1926            .into_iter()
1927            .map(|(param, default)| (param, default.map(crate::annotation::stored)))
1928            .collect();
1929        Arc::make_mut(&mut self.param_defaults).insert(name.to_string(), defaults);
1930    }
1931
1932    /// A global's per-parameter names and defaults, if recorded.
1933    pub fn param_defaults(&self, name: &str) -> Option<&[(String, Option<Term>)]> {
1934        self.param_defaults.get(name).map(|v| v.as_slice())
1935    }
1936
1937    /// All registered typeclass instances, as `(type, value)` pairs, in DECLARATION order.
1938    ///
1939    /// This is the record of what was explicitly declared, not the order resolution scans —
1940    /// see [`Context::instance_search_order`] for that, and [`Context::fallback_instances`]
1941    /// for the lower tier.
1942    pub fn instances(&self) -> &[(Term, Term)] {
1943        &self.instances
1944    }
1945
1946    /// Register a universe-polymorphic definition `name.{params} : ty := body`. A
1947    /// `Term::Const { name, levels }` reference later instantiates `params` with `levels`
1948    /// (the `.{ℓ…}` syntax), so one definition is reused at every level.
1949    pub fn add_universe_poly(&mut self, name: &str, params: Vec<String>, ty: Term, body: Term) {
1950        if let Err(error) = self.declare_universe_poly(name, params, ty, body) {
1951            Arc::make_mut(&mut self.refused).push((name.to_string(), error.to_string()));
1952        }
1953    }
1954
1955    /// Check and register a definition with an explicit universe parameter telescope.
1956    pub fn declare_universe_poly(
1957        &mut self,
1958        name: &str,
1959        params: Vec<String>,
1960        ty: Term,
1961        body: Term,
1962    ) -> crate::error::KernelResult<()> {
1963        #[cfg(feature = "shadow")]
1964        let shadow_entry = crate::dag::mirror::shadow_enter(self);
1965        #[cfg(feature = "shadow")]
1966        let candidate = vec![crate::dag::logos_env::candidate_definition(
1967            self,
1968            name,
1969            Some(&params),
1970            &ty,
1971            &body,
1972        )];
1973        let result = self.declare_definition(name, Some(params), ty, body);
1974        #[cfg(feature = "shadow")]
1975        crate::dag::mirror::shadow(self, &shadow_entry, result.as_ref().err(), || candidate);
1976        result
1977    }
1978
1979    fn check_level_telescope<'a>(
1980        kind: &str,
1981        name: &str,
1982        params: &[String],
1983        terms: impl IntoIterator<Item = &'a Term>,
1984    ) -> crate::error::KernelResult<()> {
1985        let mut bound = std::collections::HashSet::new();
1986        for param in params {
1987            if !bound.insert(param.as_str()) {
1988                return Err(crate::error::KernelError::CertificationError(format!(
1989                    "{kind} '{name}' repeats universe parameter '{param}'"
1990                )));
1991            }
1992        }
1993        for term in terms {
1994            for level in crate::term::free_level_vars(term) {
1995                if !bound.contains(level.as_str()) {
1996                    return Err(crate::error::KernelError::CertificationError(format!(
1997                        "{kind} '{name}' has unbound universe parameter '{level}'"
1998                    )));
1999                }
2000            }
2001        }
2002        Ok(())
2003    }
2004
2005    /// Look up a universe-polymorphic definition: `(universe params, type, body)`.
2006    pub fn get_universe_poly(&self, name: &str) -> Option<&(Vec<String>, Term, Term)> {
2007        if self.pending.contains_key(name) {
2008            return None;
2009        }
2010        self.universe_polys.get(name).map(AsRef::as_ref)
2011    }
2012
2013    /// Declare a UNIVERSE-POLYMORPHIC INDUCTIVE: `name.{params…} : arity`, where `arity` may
2014    /// mention the level variables in `params`.
2015    ///
2016    /// The ordinary inductive registry is populated too, at the same arity, so `is_inductive`,
2017    /// `get_constructors`, the params/indices split and every `Term::Global` reference behave
2018    /// exactly as they do for a monomorphic declaration. What this adds is the LEVEL TELESCOPE, so
2019    /// a reference that writes its levels — `Const { name, levels }` — can be resolved and
2020    /// instantiated instead of being reported as an unbound name.
2021    ///
2022    /// ★ ONE LINE MAKES IT VISIBLE TO TYPING, and it is the same line in both kernels:
2023    /// `type_checker::lookup_const` and `recheck`'s `Db::Const` arm each read
2024    /// [`Context::get_universe_poly`] and must read [`Context::poly_declaration`] instead — one
2025    /// lookup that answers for a polymorphic DEFINITION and a polymorphic TYPE alike, so the two
2026    /// kernels cannot come to disagree about which constants carry a level telescope. Reduction
2027    /// must keep reading `get_universe_poly`: a type former has no body and must stay inert.
2028    pub fn add_universe_poly_inductive(
2029        &mut self,
2030        name: &str,
2031        params: Vec<String>,
2032        arity: Term,
2033        num_params: usize,
2034    ) {
2035        if self.refuse_native_dependency_mutation(name) {
2036            return;
2037        }
2038        let arity = self.stored_term(arity);
2039        let unchanged = self
2040            .poly_types
2041            .get(name)
2042            .is_some_and(|(declared, declared_arity)| {
2043                declared == &params && same_meaning(declared_arity, &arity)
2044            })
2045            && self
2046                .inductives
2047                .get(name)
2048                .is_some_and(|current| same_meaning(current, &arity))
2049            && self.inductive_num_params(name) == num_params;
2050        match self.admit_meaning(name, Self::change_if(unchanged)) {
2051            Err(refusal) => return self.record_refusal(name, refusal),
2052            Ok(Admission::Keep) => return,
2053            Ok(Admission::Register) => {}
2054        }
2055        self.add_indexed_inductive(name, arity.clone(), num_params);
2056        self.record_mentions(name, &arity);
2057        self.record(|c| &mut c.poly_types, name.to_string(), (params, arity));
2058    }
2059
2060    /// A name's LEVEL TELESCOPE and the type it stands at — for a polymorphic type declaration or
2061    /// a polymorphic definition alike, in that order.
2062    ///
2063    /// The ordering is the same one [`Context::get_global`] uses (a header outranks a body), and
2064    /// it matters for exactly one case: a name re-declared from a definition into an inductive
2065    /// must resolve as the inductive, or typing would read a level telescope the reducer no
2066    /// longer has a body for.
2067    pub fn poly_declaration(&self, name: &str) -> Option<(&[String], &Term)> {
2068        if self.pending.contains_key(name) {
2069            return None;
2070        }
2071        if let Some((params, arity)) = self.poly_types.get(name) {
2072            return Some((params.as_slice(), arity));
2073        }
2074        // Constructors share their parent's explicit telescope, including unused
2075        // parameters and declaration order. Inferring one from free variables
2076        // would silently drop or reorder those arguments.
2077        if let Some((parent, ty)) = self.constructors.get(name) {
2078            if let Some((params, _)) = self.poly_types.get(parent) {
2079                return Some((params.as_slice(), ty));
2080            }
2081        }
2082        let (params, ty, _body) = self.universe_polys.get(name)?.as_ref();
2083        Some((params.as_slice(), ty))
2084    }
2085
2086    /// The level parameters a bare reference to `name` stands at where no argument solves them
2087    /// (`term`'s rule 4): its declared telescope, or the level variables of its stored type. `None`
2088    /// for a monomorphic or unknown name.
2089    pub(crate) fn own_levels(&self, name: &str) -> Option<Vec<String>> {
2090        if let Some((params, _)) = self.poly_declaration(name) {
2091            return (!params.is_empty()).then(|| params.to_vec());
2092        }
2093        let ty = self.get_global(name)?;
2094        crate::term::mentions_level_var(ty).then(|| crate::term::free_level_vars(ty))
2095    }
2096
2097    /// A declaration's term as the context stores it: erased ([`crate::annotation::stored`]), each
2098    /// bare reference that is not an application's head written at its own levels
2099    /// ([`crate::term::bare_references_at_own_levels`]).
2100    pub(crate) fn stored_term(&self, term: Term) -> Term {
2101        let mut term = crate::annotation::stored(term);
2102        crate::term::bare_references_at_own_levels(&mut term, &|name| self.own_levels(name));
2103        term
2104    }
2105
2106    /// Is `name` a universe-polymorphic TYPE declaration — one with a level telescope and no body?
2107    pub fn is_universe_poly_inductive(&self, name: &str) -> bool {
2108        self.is_inductive(name) && self.poly_types.contains_key(name)
2109    }
2110
2111    /// Add a local binding to this context (mutates in place).
2112    pub fn add(&mut self, name: &str, ty: Term) {
2113        self.bindings.insert(
2114            name.to_string(),
2115            Arc::new(LocalBinding {
2116                ty: crate::annotation::stored(ty),
2117                free_names: std::sync::OnceLock::new(),
2118            }),
2119        );
2120    }
2121
2122    /// Closed global programs are certified in a fresh local telescope. This
2123    /// policy follows Context clones onto any stack-growth worker thread.
2124    pub(crate) fn order_recurrence_context(&self) -> Self {
2125        let mut context = self.clone();
2126        context.bindings.clear();
2127        context.checking_order_recurrence = true;
2128        context
2129    }
2130
2131    /// Look up a local variable's type in the context.
2132    pub fn get(&self, name: &str) -> Option<&Term> {
2133        self.bindings.get(name).map(|binding| &binding.ty)
2134    }
2135
2136    /// Sparse table capacity is copied by Context::clone even when few locals remain.
2137    pub(crate) fn local_binding_capacity(&self) -> usize {
2138        self.bindings.capacity()
2139    }
2140
2141    /// Borrow the local-name payloads copied by Context::clone, for bounded builders.
2142    pub(crate) fn local_binding_names(&self) -> impl Iterator<Item = &str> {
2143        self.bindings.keys().map(String::as_str)
2144    }
2145
2146    /// Whether an independent entry must consider active local assumptions.
2147    pub(crate) fn has_local_bindings(&self) -> bool {
2148        !self.bindings.is_empty()
2149    }
2150
2151    /// Names reserved by active local keys or free in their stored types.
2152    pub(crate) fn local_name_in_use(&self, name: &str) -> bool {
2153        self.bindings.contains_key(name) || self.local_types_mention(name)
2154    }
2155
2156    /// Whether `name` is an active local key.
2157    pub(crate) fn has_local(&self, name: &str) -> bool {
2158        self.bindings.contains_key(name)
2159    }
2160
2161    /// Whether `name` occurs free in some active local's STORED TYPE — the occurrence a new
2162    /// binder named `name` would silently re-point at itself.
2163    /// Each immutable annotation is analyzed at most once across context clones.
2164    pub(crate) fn local_types_mention(&self, name: &str) -> bool {
2165        self.bindings.values().any(|binding| match &binding.ty {
2166            Term::Var(local) => local == name,
2167            Term::Sort(_) | Term::Global(_) | Term::Const { .. } | Term::Lit(_) | Term::Hole => {
2168                false
2169            }
2170            other => binding
2171                .free_names
2172                .get_or_init(|| crate::term_store::free_names_in_term(other))
2173                .contains(name),
2174        })
2175    }
2176
2177    /// Create a new context extended with an additional local binding.
2178    ///
2179    /// Does not mutate the original context.
2180    pub fn extend(&self, name: &str, ty: Term) -> Context {
2181        let mut new_ctx = self.clone();
2182        new_ctx.add(name, ty);
2183        new_ctx
2184    }
2185
2186    /// Register an inductive type.
2187    ///
2188    /// The `sort` is the type of the inductive (e.g., Type 0 for Nat).
2189    ///
2190    /// All of the arity is treated as uniform parameters (0 indices) unless
2191    /// [`set_inductive_params`](Self::set_inductive_params) records a smaller parameter
2192    /// count — see [`add_indexed_inductive`](Self::add_indexed_inductive).
2193    pub fn add_inductive(&mut self, name: &str, sort: Term) {
2194        if let Err(refusal) = self.declare_inductive(name, sort) {
2195            self.record_refusal(name, refusal);
2196        }
2197    }
2198
2199    /// [`Context::add_inductive`] answering instead of recording: the header is registered, kept
2200    /// (the identical header something depends on is not a change), or refused with the reason.
2201    pub fn declare_inductive(&mut self, name: &str, sort: Term) -> crate::error::KernelResult<()> {
2202        self.check_native_dependency_mutation(name)?;
2203        let sort = self.stored_term(sort);
2204        // A header something depends on keeps its meaning — and, being kept, its constructors.
2205        let unchanged = self
2206            .inductives
2207            .get(name)
2208            .is_some_and(|current| same_meaning(current, &sort));
2209        if self.admit_meaning(name, Self::change_if(unchanged))? == Admission::Keep {
2210            return Ok(());
2211        }
2212        // DISPLACE any previous generation of this name before installing the new one.
2213        //
2214        // `add_constructor` PUSHES onto `constructor_order`, so re-declaring a name that already
2215        // has constructors used to ACCUMULATE them: the second generation's constructors were
2216        // appended to the first's, `get_constructors` then returned more than the inductive has,
2217        // and `derive_recursor`/`Match` coverage saw the wrong count. That is one root cause behind
2218        // a whole class of failures whenever a test declares a name the prelude also owns.
2219        //
2220        // It is also half of conformance defect 3: a name could be an inductive AND a definition at
2221        // once, with `get_global` typing it from the inductive map while `get_definition_body`
2222        // reduced it from the definitions map. Displacing makes one name mean one thing.
2223        self.displace(name);
2224        self.record_mentions(name, &sort);
2225        self.record(|c| &mut c.inductives, name.to_string(), sort);
2226        // A name has entered scope, so whatever was deferred waiting for it can be checked now.
2227        // Every door that BINDS a name has to do this, not just `declare`: the prelude declares
2228        // `TTactics := TList (Syntax → Derivation)` long before `Syntax` is an inductive, and an
2229        // obligation only `declare` could discharge would stand for ever.
2230        self.retry_pending(name);
2231        Ok(())
2232    }
2233
2234    /// Borrow internally checked opaque audit evidence for the current declaration.
2235    pub(crate) fn checked_opaque_dependencies(
2236        &self,
2237        name: &str,
2238    ) -> Option<&crate::prelude::CheckedOpaqueDependencies> {
2239        self.checked_opaque.get(name)
2240    }
2241
2242    fn record_checked_opaque_edges(
2243        &mut self,
2244        name: String,
2245        edges: std::collections::BTreeSet<String>,
2246    ) {
2247        // Mutation invalidates this node before its meaning changes. Existing
2248        // nodes therefore belong to the same current declaration generation.
2249        if self.checked_opaque_graph.contains_key(&name) {
2250            return;
2251        }
2252        let reverse = Arc::make_mut(&mut self.checked_opaque_dependents);
2253        for dependency in &edges {
2254            reverse
2255                .entry(dependency.clone())
2256                .or_default()
2257                .insert(name.clone());
2258        }
2259        Arc::make_mut(&mut self.checked_opaque_graph).insert(name, Arc::new(edges));
2260    }
2261
2262    fn invalidate_checked_opaque(&mut self, name: &str) {
2263        if self.checked_opaque_graph.is_empty() {
2264            return;
2265        }
2266        let mut pending = vec![name.to_string()];
2267        let mut seen = std::collections::HashSet::new();
2268        while let Some(changed) = pending.pop() {
2269            #[cfg(test)]
2270            OPAQUE_INVALIDATION_VISITS.with(|count| count.set(count.get() + 1));
2271            if !seen.insert(changed.clone()) {
2272                continue;
2273            }
2274            // Capture dependents before removing this node's outgoing edges;
2275            // cyclic inductive type/constructor graphs are ordinary here.
2276            if let Some(dependents) =
2277                remove_shared_entry(&mut self.checked_opaque_dependents, &changed)
2278            {
2279                pending.extend(dependents);
2280            }
2281            remove_shared_entry(&mut self.checked_opaque, &changed);
2282            if let Some(edges) = remove_shared_entry(&mut self.checked_opaque_graph, &changed) {
2283                for dependency in edges.iter() {
2284                    if !self
2285                        .checked_opaque_dependents
2286                        .get(dependency)
2287                        .is_some_and(|dependents| {
2288                            dependents.contains(&changed) || dependents.is_empty()
2289                        })
2290                    {
2291                        continue;
2292                    }
2293                    let reverse = Arc::make_mut(&mut self.checked_opaque_dependents);
2294                    if let Some(dependents) = reverse.get_mut(dependency) {
2295                        dependents.remove(&changed);
2296                        if dependents.is_empty() {
2297                            reverse.remove(dependency);
2298                        }
2299                    }
2300                }
2301            }
2302        }
2303    }
2304
2305    fn invalidate_certificates(&mut self, name: &str) {
2306        self.invalidate_checked_opaque(name);
2307        if self
2308            .prelude_quotient
2309            .as_ref()
2310            .is_some_and(|c| c.dependencies.contains(name))
2311        {
2312            let certificate = self.prelude_quotient.take().expect("present certificate");
2313            // Revoking the family changes every primitive identity, including
2314            // cached opaque footprints that used only an unaffected member.
2315            for primitive in certificate.names() {
2316                self.invalidate_checked_opaque(primitive);
2317                self.log(primitive.to_string(), true);
2318            }
2319        }
2320        if self
2321            .observational
2322            .as_ref()
2323            .is_some_and(|c| c.dependencies.contains(name))
2324        {
2325            let certificate = self.observational.take().expect("present certificate");
2326            for constant in certificate.names() {
2327                self.invalidate_checked_opaque(constant);
2328                self.log(constant.to_string(), true);
2329            }
2330        }
2331        let revoked: Vec<String> = self
2332            .quotient_primitives
2333            .iter()
2334            .filter(|(_, certificate)| {
2335                certificate
2336                    .dependencies
2337                    .iter()
2338                    .any(|dependency| dependency == name)
2339            })
2340            .map(|(primitive, _)| primitive.clone())
2341            .collect();
2342        for primitive in revoked {
2343            remove_shared_entry(&mut self.quotient_primitives, &primitive);
2344            self.log(primitive, true);
2345        }
2346    }
2347
2348    /// Remove every trace of `name` from the global environment — its inductive header and any
2349    /// constructors registered against it, its parameter split, its structure metadata, its mutual
2350    /// block membership, and any definition or declaration of the same name.
2351    ///
2352    /// One name, one declaration. Re-declaring replaces; it never accumulates and never leaves a
2353    /// second reading of the same name behind in another map.
2354    fn displace(&mut self, name: &str) {
2355        if self.is_registered_global(name) {
2356            self.log(name.to_string(), true);
2357        }
2358        // A checked auxiliary describes its owner's current body/signature.
2359        // Source mutation has already passed the native dependency seal above.
2360        // User replacement disowns its name below, so only our descendants go.
2361        if let Some(children) = remove_shared_entry(&mut self.derived_aux, name) {
2362            for child in children {
2363                self.displace(&child);
2364            }
2365        }
2366        self.invalidate_certificates(name);
2367        // Constructors registered against this inductive, and their order entry.
2368        if let Some(ctors) = remove_shared_entry(&mut self.constructor_order, name) {
2369            for c in ctors {
2370                remove_shared_entry(&mut self.constructors, &c);
2371            }
2372        }
2373        // If the NAME ITSELF was a constructor of something, drop it from that inductive's order.
2374        if let Some((owner, _)) = remove_shared_entry(&mut self.constructors, name) {
2375            if self
2376                .constructor_order
2377                .get(&owner)
2378                .is_some_and(|order| order.iter().any(|c| c == name))
2379            {
2380                if let Some(order) = Arc::make_mut(&mut self.constructor_order).get_mut(&owner) {
2381                    order.retain(|c| c != name);
2382                }
2383            }
2384        }
2385        remove_shared_entry(&mut self.inductives, name);
2386        remove_shared_entry(&mut self.poly_types, name);
2387        remove_shared_entry(&mut self.binder_kinds, name);
2388        remove_shared_entry(&mut self.implicit_args, name);
2389        remove_shared_entry(&mut self.param_defaults, name);
2390        remove_shared_entry(&mut self.universe_polys, name);
2391        remove_shared_entry(&mut self.pending, name);
2392        remove_shared_entry(&mut self.inductive_params, name);
2393        remove_shared_entry(&mut self.inductive_inferred_params, name);
2394        remove_shared_entry(&mut self.definitions, name);
2395        // The edge list belongs to the BODY, so it goes when the body does. (`referenced` does
2396        // not: it is a monotone over-approximation, and shrinking it could hide a cycle.)
2397        remove_shared_entry(&mut self.definition_deps, name);
2398        remove_shared_entry(&mut self.definition_heights, name);
2399        remove_shared_entry(&mut self.declarations, name);
2400        remove_shared_entry(&mut self.structures, name);
2401        remove_shared_entry(&mut self.mutual_blocks, name);
2402        self.forget_mentions(name);
2403        // DISOWN: whatever is about to be registered under `name`, it is not the auxiliary we
2404        // generated. Keeping the claim would let the next re-derivation delete someone else's
2405        // constant — and "someone else" includes the prelude's hand-written `decEqNat`.
2406        if let Some(owner) = remove_shared_entry(&mut self.derived_aux_owner, name) {
2407            if self
2408                .derived_aux
2409                .get(&owner)
2410                .is_some_and(|list| list.iter().any(|n| n == name))
2411            {
2412                if let Some(list) = Arc::make_mut(&mut self.derived_aux).get_mut(&owner) {
2413                    list.retain(|n| n != name);
2414                }
2415            }
2416        }
2417    }
2418
2419    pub(crate) fn equations_suspended(&self) -> bool {
2420        self.equations_suspended
2421    }
2422
2423    /// Intermediate prelude recursors are checked for use during construction,
2424    /// but their equations can be checked once, after their final replacement.
2425    /// Restore the previous mode even if a caller catches a construction panic.
2426    pub(crate) fn with_equations_suspended<R>(
2427        &mut self,
2428        build: impl FnOnce(&mut Context) -> R,
2429    ) -> R {
2430        struct Restore<'a> {
2431            context: &'a mut Context,
2432            previous: bool,
2433        }
2434        impl Drop for Restore<'_> {
2435            fn drop(&mut self) {
2436                self.context.equations_suspended = self.previous;
2437            }
2438        }
2439        let previous = self.equations_suspended;
2440        self.equations_suspended = true;
2441        let restore = Restore {
2442            context: self,
2443            previous,
2444        };
2445        build(&mut *restore.context)
2446    }
2447
2448    /// Include hidden pending and universe-polymorphic declarations when reserving
2449    /// generated names: absence from lookup never authorizes overwriting a user.
2450    pub(crate) fn constant_name_reserved(&self, name: &str) -> bool {
2451        self.get_global(name).is_some()
2452            || self.pending.contains_key(name)
2453            || self.universe_polys.contains_key(name)
2454    }
2455
2456    pub(crate) fn record_derived_aux(&mut self, owner: &str, name: &str) {
2457        Arc::make_mut(&mut self.derived_aux_owner).insert(name.into(), owner.into());
2458        let children = Arc::make_mut(&mut self.derived_aux)
2459            .entry(owner.into())
2460            .or_default();
2461        if !children.iter().any(|child| child == name) {
2462            children.push(name.into());
2463        }
2464    }
2465
2466    /// Is `name` a constant THIS context auto-derived (`{I}_rec`, `{I}_noConfusion`, `decEq{I}`, …)
2467    /// rather than one a human wrote?
2468    ///
2469    /// The distinction is what lets declaration-time synthesis be idempotent: re-deriving must
2470    /// REPLACE its own prior generation — an inductive is incomplete until its last constructor,
2471    /// so the auxiliaries derived after the first one describe a different type — while never
2472    /// touching a hand-written constant of the same name.
2473    pub fn is_derived_aux(&self, name: &str) -> bool {
2474        self.derived_aux_owner.contains_key(name)
2475    }
2476
2477    /// The auxiliaries this context derived for a source declaration, in generation order.
2478    /// Inductives own recursors and related products; definitions own equation lemmas.
2479    pub fn derived_aux_names(&self, ind: &str) -> Option<&[String]> {
2480        self.derived_aux.get(ind).map(|v| v.as_slice())
2481    }
2482
2483    /// Register a STRUCTURE (record) `{name} (params) := {name}_mk (fields)` — a
2484    /// one-constructor inductive with auto-derived projections and definitional eta.
2485    ///
2486    /// `params` are the leading type parameters `(A : Type 0)`, `(B : Type 0)`, …;
2487    /// `fields` are `(fst : A)`, `(snd : B)`, … where a field type may reference the
2488    /// params and any EARLIER field (by name). Registers:
2489    /// - the inductive `{name} : Π(params). Type 0`,
2490    /// - the constructor `{name}_mk : Π(params). Π(fields). {name} params`,
2491    /// - a projection `{name}_{fieldᵢ} : Π(params). Π(s:{name} params). Tᵢ` for each
2492    ///   field (its body a `match` on `s`), and
2493    /// - the [`StructInfo`] that gates the eta rule.
2494    ///
2495    /// The structure lives in `Type 0` (fields over `Type 0` carriers) — the common
2496    /// case for the algebraic hierarchy.
2497    /// The LEAST sort that can store `fields` — the sort `add_structure` infers when the caller
2498    /// does not name one, mirroring Lean's `structure Foo where …` with the result sort omitted.
2499    ///
2500    /// CIC's rule: an inductive's sort must dominate the sort of every field it STORES. Parameters
2501    /// do not constrain it — `List : Type u → Type u` takes a `Type (u+1)` argument and lands in
2502    /// `Type u`. `Prop`-valued fields do not raise it, by impredicativity.
2503    fn structure_min_sort(&self, params: &[(&str, Term)], fields: &[(&str, Term)]) -> Universe {
2504        let mut local = self.clone();
2505        for (p, t) in params {
2506            local = local.extend(p, t.clone());
2507        }
2508        // `acc` is the least DATA sort that dominates every non-propositional field. It is
2509        // consulted only when there IS such a field: a record that stores nothing but proofs is
2510        // a proposition, and seeding the accumulator at `Type 0` is what used to make that
2511        // unreachable — `Conj P Q` (the shape of `And`, `Iff`, and every bundled `Prop`-valued
2512        // class) landed in `Type 0`, where proof irrelevance stops applying and the
2513        // large-elimination gate stops firing.
2514        let mut acc = Universe::Type(0);
2515        let mut stores_data = false;
2516        for (fname, ftype) in fields {
2517            match crate::type_checker::infer_sort(&local, ftype) {
2518                // Impredicativity: a `Prop`/`SProp` field never RAISES the sort. It also never
2519                // forces it up out of `Prop` — that is the half that was missing.
2520                Ok(Universe::Prop) | Ok(Universe::SProp) => {}
2521                Ok(u) => {
2522                    stores_data = true;
2523                    acc = acc.max(&u);
2524                }
2525                // A field whose sort cannot be inferred is treated as DATA, never as a proof:
2526                // guessing `Prop` for something we could not read would silently grant proof
2527                // irrelevance and restrict elimination on a record that may store anything.
2528                Err(_) => stores_data = true,
2529            }
2530            // Later fields may mention earlier ones (`snd : B fst`), so each binding has to be in
2531            // scope before the next is inferred.
2532            local = local.extend(fname, ftype.clone());
2533        }
2534        // A FIELDLESS record is `Type 0`, matching Lean's `structure Foo where` — it is a unit
2535        // type, not a proposition, and `PUnit`/`Unit` must stay eliminable into `Type`.
2536        //
2537        // An all-propositional record is `Prop`, NOT `SProp`, even when every field is `SProp`:
2538        // `SProp` carries DEFINITIONAL proof irrelevance, which a record with fields would then
2539        // have to satisfy pointwise. `Prop` is Lean's answer and the conservative one.
2540        if fields.is_empty() || stores_data {
2541            acc
2542        } else {
2543            Universe::Prop
2544        }
2545    }
2546
2547    /// Register a structure AT a DECLARED sort — Lean's `structure Foo (params) : <sort> where …`.
2548    ///
2549    /// The declared sort is CHECKED, not taken on faith: the generated constructor is run through
2550    /// `crate::type_checker::check_constructor_universes`, the same gate `add_mutual_inductives`
2551    /// uses, so a record may not claim a sort too small to hold what it stores. `Prop` is exempt,
2552    /// because `Prop` is impredicative and may store any sort at the cost of restricted elimination
2553    /// — exactly Lean's and Coq's rule, and what makes `Exists` (which stores an `α : Sort u`)
2554    /// legal in `Prop`.
2555    ///
2556    /// TRANSACTIONAL: the structure is built on a scratch context and committed only if the check
2557    /// passes, so a rejected declaration leaves nothing behind.
2558    ///
2559    /// Better than Lean in one respect: the error names the FIELD that forced the larger sort,
2560    /// where Lean reports only the two universes.
2561    pub fn add_structure_at(
2562        &mut self,
2563        name: &str,
2564        sort: Universe,
2565        params: &[(&str, Term)],
2566        fields: &[(&str, Term)],
2567    ) -> crate::error::KernelResult<()> {
2568        let levels = Self::written_structure_levels(Some(&sort), params, fields);
2569        self.add_structure_poly_at(name, levels, sort, params, fields)
2570    }
2571
2572    /// The level telescope a structure's AUTHOR wrote: the free level variables of its
2573    /// parameter types, its declared sort and its field types, in first-occurrence order — the
2574    /// same derivation [`Context::add_declaration`] and [`Context::add_inductive`] apply to what
2575    /// was written, and Lean's auto-bound universe rule. A structure written over `Sort u` is
2576    /// therefore polymorphic in `u`, and one written at a concrete level has no telescope.
2577    fn written_structure_levels(
2578        sort: Option<&Universe>,
2579        params: &[(&str, Term)],
2580        fields: &[(&str, Term)],
2581    ) -> Vec<String> {
2582        let sort = sort.map(|u| Term::Sort(u.clone()));
2583        let mut levels: Vec<String> = Vec::new();
2584        for term in params
2585            .iter()
2586            .map(|(_, ty)| ty)
2587            .chain(sort.iter())
2588            .chain(fields.iter().map(|(_, ty)| ty))
2589        {
2590            for level in crate::term::free_level_vars(term) {
2591                if !levels.contains(&level) {
2592                    levels.push(level);
2593                }
2594            }
2595        }
2596        levels
2597    }
2598
2599    /// [`Context::add_structure_at`] for a UNIVERSE-POLYMORPHIC structure — Lean's
2600    /// `structure Foo.{u…} (params) : <sort> where …`, where `sort`, the parameter telescope and
2601    /// the field types may all mention the level parameters in `levels`.
2602    ///
2603    /// The level telescope is the whole content: the arity is registered through
2604    /// [`Context::add_universe_poly_inductive`], so `Foo.{ℓ…}` resolves and ONE declaration serves
2605    /// every level. Everything else — the checked sort, the transactional scratch context, the
2606    /// constructor, the projections, the parent edges — is the monomorphic path verbatim, which is
2607    /// what makes an empty `levels` list exactly the old declaration rather than a near-copy.
2608    pub fn add_structure_poly_at(
2609        &mut self,
2610        name: &str,
2611        levels: Vec<String>,
2612        sort: Universe,
2613        params: &[(&str, Term)],
2614        fields: &[(&str, Term)],
2615    ) -> crate::error::KernelResult<()> {
2616        if !crate::annotation::within_erased_call()
2617            && params
2618                .iter()
2619                .chain(fields)
2620                .any(|(_, ty)| ty.has_annotations())
2621        {
2622            let params: Vec<(&str, Term)> = params
2623                .iter()
2624                .map(|(name, ty)| (*name, ty.strip_annotations()))
2625                .collect();
2626            let fields: Vec<(&str, Term)> = fields
2627                .iter()
2628                .map(|(name, ty)| (*name, ty.strip_annotations()))
2629                .collect();
2630            return self.add_structure_poly_at(name, levels, sort, &params, &fields);
2631        }
2632        self.check_native_dependency_mutation(name)?;
2633        self.check_native_dependency_mutation(&format!("{name}_mk"))?;
2634        for (field, _) in fields {
2635            self.check_native_dependency_mutation(&format!("{name}_{field}"))?;
2636        }
2637        let result_sort = Term::Sort(sort.clone());
2638        Self::check_level_telescope(
2639            "structure",
2640            name,
2641            &levels,
2642            std::iter::once(&result_sort)
2643                .chain(params.iter().map(|(_, ty)| ty))
2644                .chain(fields.iter().map(|(_, ty)| ty)),
2645        )?;
2646        let mut scratch = self.clone();
2647        scratch.build_structure(name, &levels, sort.clone(), params, fields);
2648
2649        // A structure something already depends on keeps its meaning: rebuilt identically it is
2650        // left exactly as it is, and rebuilt any other way it is refused.
2651        let generated: Vec<String> = std::iter::once(name.to_string())
2652            .chain(std::iter::once(format!("{name}_mk")))
2653            .chain(fields.iter().map(|(field, _)| format!("{name}_{field}")))
2654            .collect();
2655        let identical = generated.iter().all(|n| {
2656            self.get_global(n).is_some()
2657                && same_meaning_opt(self.get_global(n), scratch.get_global(n))
2658                && same_meaning_opt(self.get_definition_body(n), scratch.get_definition_body(n))
2659                && match (self.poly_declaration(n), scratch.poly_declaration(n)) {
2660                    (Some((ours, our_ty)), Some((theirs, their_ty))) => {
2661                        ours == theirs && same_meaning(our_ty, their_ty)
2662                    }
2663                    (None, None) => true,
2664                    _ => false,
2665                }
2666        });
2667        let mut relied_on = false;
2668        for generated_name in &generated {
2669            relied_on |=
2670                self.admit_meaning(generated_name, Self::change_if(identical))? == Admission::Keep;
2671        }
2672        if relied_on {
2673            return Ok(());
2674        }
2675
2676        let mk = format!("{name}_mk");
2677        let ctor_ty = match scratch.get_global(&mk) {
2678            Some(t) => t.clone(),
2679            None => {
2680                return Err(crate::error::KernelError::CertificationError(format!(
2681                    "structure '{name}' generated no constructor"
2682                )))
2683            }
2684        };
2685        crate::type_checker::infer_sort(&scratch, &ctor_ty)?;
2686        let dependencies =
2687            crate::positivity::native_positivity_dependencies(&scratch, &[name], &mk, &ctor_ty)?;
2688        scratch.check_native_dependencies(&dependencies)?;
2689        if let Err(e) =
2690            crate::type_checker::check_constructor_universes(&scratch, name, &mk, &ctor_ty)
2691        {
2692            let culprit = {
2693                let min = self.structure_min_sort(params, fields);
2694                let mut local = self.clone();
2695                for (p, t) in params {
2696                    local = local.extend(p, t.clone());
2697                }
2698                let mut which = None;
2699                for (fname, ftype) in fields {
2700                    if let Ok(u) = crate::type_checker::infer_sort(&local, ftype) {
2701                        if !matches!(u, Universe::Prop | Universe::SProp) && !u.is_subtype_of(&sort)
2702                        {
2703                            which = Some(format!("field `{fname}` lives in {u}"));
2704                            break;
2705                        }
2706                    }
2707                    local = local.extend(fname, ftype.clone());
2708                }
2709                which.unwrap_or_else(|| format!("its fields need at least {min}"))
2710            };
2711            return Err(crate::error::KernelError::CertificationError(format!(
2712                "structure '{name}' cannot live in {sort}: {culprit} ({e:?})"
2713            )));
2714        }
2715
2716        scratch.seal_native_dependencies(dependencies);
2717        *self = scratch;
2718        Ok(())
2719    }
2720
2721    /// Register a structure, INFERRING the least sort that can hold its fields.
2722    ///
2723    /// Equivalent to `add_structure_at(name, self.structure_min_sort(params, fields), …)`.
2724    /// Invalid declarations are recorded in `refused_declarations` and leave the context intact. Use
2725    /// [`Context::add_structure_at`] to declare a sort explicitly (a `Prop` record, or one placed
2726    /// higher than it needs to be).
2727    pub fn add_structure(&mut self, name: &str, params: &[(&str, Term)], fields: &[(&str, Term)]) {
2728        let levels = Self::written_structure_levels(None, params, fields);
2729        let sort = self.structure_min_sort(params, fields);
2730        if let Err(error) = self.add_structure_poly_at(name, levels, sort, params, fields) {
2731            Arc::make_mut(&mut self.refused).push((name.to_string(), error.to_string()));
2732        }
2733    }
2734
2735    /// Register a UNIVERSE-POLYMORPHIC structure, INFERRING the least sort that can hold its
2736    /// fields — Lean's `class Mul.{u} (α : Sort u) where mul : α → α → α`, and the shape the whole
2737    /// algebraic hierarchy is built from.
2738    ///
2739    /// This is the wall that decided the Mathlib question. `add_structure` computes its result
2740    /// sort from a telescope of CONCRETE parameter types, so a class declared with `α : Type 0`
2741    /// refuses a `Type 0` carrier — `Type 0 : Type 1` — and one declaration could serve exactly
2742    /// one level. Monomorphising at `Type 0` is the tempting wrong move and it is unsound rather
2743    /// than merely lossy: keys are flat `String`s, so two instantiations collapse into one
2744    /// declaration, and because LOGOS is CUMULATIVE the resulting terms very often still
2745    /// type-check.
2746    ///
2747    /// The result sort is COMPUTED over the level telescope, not assumed, exactly as Lean's
2748    /// `mkResultUniverse` (`Lean/Elab/Inductive.lean:484`) computes it: the `max` of the stored
2749    /// fields' sorts, raised to at least `Type 0` when anything is stored, and `Prop` when the
2750    /// record stores nothing but proofs. That inferred sort dominates every field by construction,
2751    /// and registration still validates the declaration's types, positivity, and universes.
2752    ///
2753    /// Invalid types, negative recursion, and inconsistent universes are refused transactionally.
2754    /// This returns the error directly; `add_structure` records it in the refusal ledger.
2755    pub fn add_structure_poly(
2756        &mut self,
2757        name: &str,
2758        levels: Vec<String>,
2759        params: &[(&str, Term)],
2760        fields: &[(&str, Term)],
2761    ) -> crate::error::KernelResult<()> {
2762        let sort = self.structure_min_sort(params, fields);
2763        self.add_structure_poly_at(name, levels, sort, params, fields)
2764    }
2765
2766    fn build_structure(
2767        &mut self,
2768        name: &str,
2769        levels: &[String],
2770        sort: Universe,
2771        params: &[(&str, Term)],
2772        fields: &[(&str, Term)],
2773    ) {
2774        let g = |s: &str| Term::Global(s.to_string());
2775        let var = |s: &str| Term::Var(s.to_string());
2776        // Wrap `body` in a Π / λ telescope.
2777        let pis = |tele: &[(&str, Term)], body: Term| {
2778            tele.iter().rev().fold(body, |acc, (p, t)| Term::Pi {
2779                param: p.to_string(),
2780                param_type: Box::new(t.clone()),
2781                body_type: Box::new(acc),
2782            })
2783        };
2784        let lams = |tele: &[(&str, Term)], body: Term| {
2785            tele.iter().rev().fold(body, |acc, (p, t)| Term::Lambda {
2786                param: p.to_string(),
2787                param_type: Box::new(t.clone()),
2788                body: Box::new(acc),
2789            })
2790        };
2791        // `{name} A B …` — the structure applied to its parameter variables.
2792        let structure_head = if levels.is_empty() {
2793            g(name)
2794        } else {
2795            Term::Const {
2796                name: name.to_string(),
2797                levels: levels
2798                    .iter()
2799                    .map(|level| Universe::Var(level.clone()))
2800                    .collect(),
2801            }
2802        };
2803        let s_applied = params.iter().fold(structure_head, |acc, (p, _)| {
2804            Term::App(Box::new(acc), Box::new(var(p)))
2805        });
2806
2807        // 1. The inductive, at the sort the caller settled on — and, when the declaration named
2808        // level parameters, WITH its level telescope, so `{name}.{ℓ…}` resolves and the one
2809        // declaration serves every level. An empty telescope is the monomorphic door verbatim:
2810        // `add_universe_poly_inductive` would otherwise record an empty parameter list, which is
2811        // a DIFFERENT claim from "this declaration has no level telescope".
2812        let ind_type = pis(params, Term::Sort(sort));
2813        if levels.is_empty() {
2814            self.add_indexed_inductive(name, ind_type, params.len());
2815        } else {
2816            self.add_universe_poly_inductive(name, levels.to_vec(), ind_type, params.len());
2817        }
2818
2819        // 2. The constructor.
2820        let mk = format!("{name}_mk");
2821        let ctor_type = pis(params, pis(fields, s_applied.clone()));
2822        self.add_constructor(&mk, name, ctor_type);
2823
2824        // 3. The projections.
2825        let mut proj_names = Vec::new();
2826        for (i, (fname, ftype)) in fields.iter().enumerate() {
2827            let proj = format!("{name}_{fname}");
2828            proj_names.push(proj.clone());
2829
2830            // Rewrite earlier field references `f_j` (j < i) to `proj_j params disc`,
2831            // for a chosen discriminant term.
2832            let field_of = |disc: &Term, ty: &Term| -> Term {
2833                let mut out = ty.clone();
2834                for (fj, _) in fields.iter().take(i) {
2835                    let proj_j_applied = params
2836                        .iter()
2837                        .fold(g(&format!("{name}_{fj}")), |acc, (p, _)| {
2838                            Term::App(Box::new(acc), Box::new(var(p)))
2839                        });
2840                    let proj_j_applied =
2841                        Term::App(Box::new(proj_j_applied), Box::new(disc.clone()));
2842                    out = crate::type_checker::substitute(&out, fj, &proj_j_applied);
2843                }
2844                out
2845            };
2846
2847            // Projection type: Π(params). Π(s : {name} params). Tᵢ[fⱼ := projⱼ params s].
2848            let ret_ty = field_of(&var("s"), ftype);
2849            let proj_type = pis(
2850                params,
2851                Term::Pi {
2852                    param: "s".to_string(),
2853                    param_type: Box::new(s_applied.clone()),
2854                    body_type: Box::new(ret_ty),
2855                },
2856            );
2857
2858            // Body: λparams. λ(s). match s return (λ(s✧). Tᵢ[fⱼ := projⱼ params s✧])
2859            //                       with | mk => λ(fields). fieldᵢ
2860            let motive = Term::Lambda {
2861                param: "s✧".to_string(),
2862                param_type: Box::new(s_applied.clone()),
2863                body: Box::new(field_of(&var("s✧"), ftype)),
2864            };
2865            let case = lams(fields, var(fname));
2866            let match_term = Term::Match {
2867                discriminant: Box::new(var("s")),
2868                motive: Box::new(motive),
2869                cases: vec![case],
2870            };
2871            let body = lams(
2872                params,
2873                Term::Lambda {
2874                    param: "s".to_string(),
2875                    param_type: Box::new(s_applied.clone()),
2876                    body: Box::new(match_term),
2877                },
2878            );
2879            self.add_definition(proj, proj_type, body);
2880        }
2881
2882        let params_owned: Vec<(String, Term)> = params
2883            .iter()
2884            .map(|(p, t)| (p.to_string(), t.clone()))
2885            .collect();
2886        let fields_owned: Vec<(String, Term)> = fields
2887            .iter()
2888            .map(|(f, t)| (f.to_string(), t.clone()))
2889            .collect();
2890        let parents = self
2891            .immediate_parent(name, &params_owned, &fields_owned)
2892            .into_iter()
2893            .collect();
2894        self.insert_struct_info(
2895            name,
2896            StructInfo {
2897                mk,
2898                num_params: params.len(),
2899                projections: proj_names,
2900                params: params_owned,
2901                fields: fields_owned,
2902                parents,
2903                out_params: infer_out_params(params, fields),
2904            },
2905        );
2906        self.emit_parent_edges(name, params);
2907    }
2908
2909    /// The structure `child` EXTENDS, recovered from its flattened field list.
2910    ///
2911    /// Lean's `structure Child extends Parent` stores the parent's fields FIRST, in parent
2912    /// order, then the child's own — so a flattened declaration carries its inheritance in its
2913    /// shape, and that is the only place it can be read from: `add_structure` takes a flat
2914    /// field slice with no parent list. A previously declared structure is the parent when
2915    ///
2916    /// * its parameter telescope is IDENTICAL (names and types), so one forget map can be
2917    ///   written over the shared parameters, and
2918    /// * its whole field list is a STRICT prefix of the child's (names and types).
2919    ///
2920    /// Each condition rules out a near-miss that is not inheritance: a reordered field list, a
2921    /// same-named field at another type, a different parameter family, and a twin with exactly
2922    /// the same fields (which extends nothing). A FIELDLESS parent is excluded because every
2923    /// structure trivially extends the empty record, so it is evidence of nothing.
2924    ///
2925    /// Only the IMMEDIATE parent — the longest matching prefix — is returned, mirroring Lean:
2926    /// a grandparent is reached by composing edges, not by a second direct one. Ties on length
2927    /// cannot occur (two different field lists of one length cannot both prefix-match), and the
2928    /// name order makes the choice deterministic regardless of the map's iteration order.
2929    fn immediate_parent(
2930        &self,
2931        child: &str,
2932        params: &[(String, Term)],
2933        fields: &[(String, Term)],
2934    ) -> Option<String> {
2935        let mut best: Option<(usize, &String)> = None;
2936        for (pname, info) in self.structures.iter() {
2937            if pname == child || info.fields.is_empty() || info.fields.len() >= fields.len() {
2938                continue;
2939            }
2940            if info.params != params || info.fields[..] != fields[..info.fields.len()] {
2941                continue;
2942            }
2943            let len = info.fields.len();
2944            if best.is_none_or(|(blen, bname)| (len, pname) > (blen, bname)) {
2945                best = Some((len, pname));
2946            }
2947        }
2948        best.map(|(_, n)| n.clone())
2949    }
2950
2951    /// Emit the forget map for each parent recovered by [`Context::immediate_parent`]:
2952    /// `{Child}_to{Parent} : Π(params). Child params → Parent params`, whose body rebuilds the
2953    /// parent from the child's leading projections, plus the instance entry that lets a
2954    /// `Parent τ` obligation be discharged from a `Child τ` in scope.
2955    ///
2956    /// It is a DEFINITION, never an axiom, so `(c.toParent).f ≡ c.f` holds by computation —
2957    /// an axiomatised edge would break every `rfl` that reads a parent field through a child.
2958    fn emit_parent_edges(&mut self, child: &str, params: &[(&str, Term)]) {
2959        let Some(info) = self.structures.get(child) else {
2960            return;
2961        };
2962        let parents = info.parents.clone();
2963        for parent in parents {
2964            let edge = format!("{child}_to{parent}");
2965            let Some(pinfo) = self.structures.get(&parent) else {
2966                continue;
2967            };
2968            let (pmk, pfields) = (pinfo.mk.clone(), pinfo.fields.len());
2969            let var = |s: &str| Term::Var(s.to_string());
2970            let applied = |head: &str| {
2971                params
2972                    .iter()
2973                    .fold(Term::Global(head.to_string()), |acc, (p, _)| {
2974                        Term::App(Box::new(acc), Box::new(var(p)))
2975                    })
2976            };
2977            let pis = |body: Term| {
2978                params.iter().rev().fold(body, |acc, (p, t)| Term::Pi {
2979                    param: p.to_string(),
2980                    param_type: Box::new(t.clone()),
2981                    body_type: Box::new(acc),
2982                })
2983            };
2984            let lams = |body: Term| {
2985                params.iter().rev().fold(body, |acc, (p, t)| Term::Lambda {
2986                    param: p.to_string(),
2987                    param_type: Box::new(t.clone()),
2988                    body: Box::new(acc),
2989                })
2990            };
2991            // The codomain never mentions the receiver, so the edge's own binder is anonymous.
2992            let ty = pis(Term::Pi {
2993                param: "_".to_string(),
2994                param_type: Box::new(applied(child)),
2995                body_type: Box::new(applied(&parent)),
2996            });
2997            // `Parent_mk params (Child_f₁ params s) … (Child_fₙ params s)` — the child's
2998            // leading projections ARE the parent's fields, in order, by the prefix condition.
2999            let mut rebuilt = applied(&pmk);
3000            for i in 0..pfields {
3001                let proj = self.structures[child].projections[i].clone();
3002                let mut value = applied(&proj);
3003                value = Term::App(Box::new(value), Box::new(var("s")));
3004                rebuilt = Term::App(Box::new(rebuilt), Box::new(value));
3005            }
3006            let body = lams(Term::Lambda {
3007                param: "s".to_string(),
3008                param_type: Box::new(applied(child)),
3009                body: Box::new(rebuilt),
3010            });
3011            self.add_definition(edge.clone(), ty.clone(), body);
3012            self.add_instance(ty, Term::Global(edge));
3013        }
3014    }
3015
3016    /// Register an INDEXED inductive: `sort` is its full arity `Π(params). Π(indices).
3017    /// Sort`, of which the first `num_params` leading arguments are uniform parameters and
3018    /// the rest are indices that vary per constructor (e.g. `Eq` with `num_params == 2`).
3019    pub fn add_indexed_inductive(&mut self, name: &str, sort: Term, num_params: usize) {
3020        if self.refuse_native_dependency_mutation(name) {
3021            return;
3022        }
3023        let sort = self.stored_term(sort);
3024        let unchanged = self
3025            .inductives
3026            .get(name)
3027            .is_some_and(|current| same_meaning(current, &sort))
3028            && self.inductive_num_params(name) == num_params;
3029        match self.admit_meaning(name, Self::change_if(unchanged)) {
3030            Err(refusal) => return self.record_refusal(name, refusal),
3031            Ok(Admission::Keep) => return,
3032            Ok(Admission::Register) => {}
3033        }
3034        self.add_inductive(name, sort);
3035        self.set_inductive_params(name, num_params);
3036    }
3037
3038    /// Record how many leading arguments of `name`'s arity are uniform parameters.
3039    pub fn set_inductive_params(&mut self, name: &str, num_params: usize) {
3040        if self.refuse_native_dependency_mutation(name) {
3041            return;
3042        }
3043        // The split decides what a `match` binds and what ι skips, so a split something was
3044        // checked against is part of the inductive's meaning.
3045        match self.admit_meaning(
3046            name,
3047            Self::change_if(self.inductive_num_params(name) == num_params),
3048        ) {
3049            Err(refusal) => return self.record_refusal(name, refusal),
3050            Ok(Admission::Keep) => return,
3051            Ok(Admission::Register) => {}
3052        }
3053        self.invalidate_certificates(name);
3054        self.record(|c| &mut c.inductive_params, name.to_string(), num_params);
3055    }
3056
3057    /// The full arity of an inductive — the number of leading `Π`s in its sort (`Nat` →
3058    /// 0, `TList : Type → Type` → 1, `Eq : Type → A → A → Prop` → 3). `0` for an unknown
3059    /// name.
3060    pub fn inductive_arity(&self, name: &str) -> usize {
3061        self.inductives
3062            .get(name)
3063            .map(count_leading_pis)
3064            .unwrap_or(0)
3065    }
3066
3067    /// The EXPLICITLY declared parameter count for `name`, or `None` if the inductive was
3068    /// registered without one. Reduction uses this to skip exactly the parameters of an
3069    /// indexed constructor (`refl A x` → 2), falling back to a syntactic heuristic for the
3070    /// legacy inductives that never declared a split — so their ι-reduction is untouched.
3071    pub fn inductive_declared_params(&self, name: &str) -> Option<usize> {
3072        self.inductive_params.get(name).copied()
3073    }
3074
3075    /// How many leading arguments of `name`'s arity are uniform PARAMETERS.
3076    ///
3077    /// Three sources, in strict order:
3078    ///
3079    /// 1. the count the declaration stated ([`Context::add_indexed_inductive`]) — always wins, so
3080    ///    a translator carrying Lean's own split across is never second-guessed;
3081    /// 2. otherwise the count INFERRED from the registered constructors (see
3082    ///    `Context::infer_num_params`);
3083    /// 3. otherwise the full arity, for a header with no constructors yet — a declaration in
3084    ///    progress behaves exactly as it always did.
3085    ///
3086    /// O(1): the inference is computed once per `add_constructor`, never per read. This is read on
3087    /// ι-reduction's argument-skipping path, so a scan here would be a scan inside reduction.
3088    pub fn inductive_num_params(&self, name: &str) -> usize {
3089        if let Some(n) = self.inductive_params.get(name) {
3090            return *n;
3091        }
3092        if let Some(n) = self.inductive_inferred_params.get(name) {
3093            return *n;
3094        }
3095        self.inductive_arity(name)
3096    }
3097
3098    /// INFER the params/indices split of `name` from its registered constructors — CIC's own
3099    /// rule, which is the rule Lean applies to `inductive … where`:
3100    ///
3101    /// > arity position `i` is a uniform PARAMETER iff every constructor passes, at position `i`,
3102    /// > exactly that constructor's own `i`-th binder — unchanged — both in its RESULT type and at
3103    /// > every RECURSIVE occurrence of the inductive inside its argument types.
3104    ///
3105    /// The parameters are the longest such PREFIX; everything after it is an index.
3106    ///
3107    /// The recursive-occurrence half is load-bearing, not belt-and-braces. `Acc`'s introduction
3108    /// rule `Acc_intro : Π(A)(R)(x:A). (Π(y:A). R y x → Acc A R y) → Acc A R x` passes its own `x`
3109    /// at position 2 in its RESULT, so the result alone reports 3 parameters — but the recursive
3110    /// occurrence passes `y`, not `x`. Reading the result only would make well-founded recursion's
3111    /// eliminator abstract nothing, and every `Acc`-based definition would die.
3112    ///
3113    /// A constructor whose result is not headed by the inductive at all contributes 0: nothing
3114    /// about it is uniform, and guessing higher is how an unsound split gets in.
3115    fn infer_num_params(&self, name: &str) -> usize {
3116        let arity = self.inductive_arity(name);
3117        if arity == 0 {
3118            return 0;
3119        }
3120        let ctors = self.get_constructors(name);
3121        // A header with no constructors yet: keep the pre-inference answer so a declaration
3122        // mid-flight is never re-interpreted underneath its own caller.
3123        if ctors.is_empty() {
3124            return arity;
3125        }
3126        let mut best = arity;
3127        for (_, cty) in &ctors {
3128            best = best.min(ctor_param_prefix(name, cty, arity));
3129            if best == 0 {
3130                break;
3131            }
3132        }
3133        best
3134    }
3135
3136    /// How many trailing arguments of `name`'s arity are INDICES (arity − parameters).
3137    pub fn inductive_num_indices(&self, name: &str) -> usize {
3138        self.inductive_arity(name)
3139            .saturating_sub(self.inductive_num_params(name))
3140    }
3141
3142    /// Register a constructor for an inductive type.
3143    ///
3144    /// The `ty` is the full type of the constructor
3145    /// (e.g., `Nat` for Zero, `Nat -> Nat` for Succ).
3146    ///
3147    /// Constructors are tracked in registration order for match expressions.
3148    pub fn add_constructor(&mut self, name: &str, inductive: &str, ty: Term) {
3149        if self.refuse_native_dependency_mutation(name)
3150            || self.refuse_native_dependency_mutation(inductive)
3151        {
3152            return;
3153        }
3154        let ty = self.stored_term(ty);
3155        match self.admit_constructor(name, inductive, &ty) {
3156            Err(refusal) => return self.record_refusal(name, refusal),
3157            Ok(Admission::Keep) => return,
3158            Ok(Admission::Register) => {}
3159        }
3160        if let Some((old_owner, _)) = self.constructors.get(name) {
3161            let old_owner = old_owner.clone();
3162            self.invalidate_checked_opaque(&old_owner);
3163        }
3164        // ONE NAME, ONE DECLARATION. Whatever `name` meant before — a definition, an axiom, a
3165        // constructor of another inductive — goes, or `get_global` would type the name as this
3166        // constructor while δ still unfolded the old body.
3167        if self.is_registered_global(name) {
3168            self.displace(name);
3169        }
3170        self.invalidate_certificates(name);
3171        self.invalidate_certificates(inductive);
3172        self.record_mentions(name, &ty);
3173        self.record(
3174            |c| &mut c.constructors,
3175            name.to_string(),
3176            (inductive.to_string(), ty),
3177        );
3178
3179        // Track constructor order for this inductive
3180        Arc::make_mut(&mut self.constructor_order)
3181            .entry(inductive.to_string())
3182            .or_default()
3183            .push(name.to_string());
3184
3185        // Re-infer the params/indices split now that one more constructor constrains it. Done
3186        // HERE, at registration, so `inductive_num_params` stays an O(1) map read for the
3187        // ι-reduction and match-typing paths that call it per step.
3188        //
3189        // An EXPLICIT declaration is never overwritten: `add_indexed_inductive` records the
3190        // caller's own split and that is the authority.
3191        if !self.inductive_params.contains_key(inductive) {
3192            let inferred = self.infer_num_params(inductive);
3193            self.record(
3194                |c| &mut c.inductive_inferred_params,
3195                inductive.to_string(),
3196                inferred,
3197            );
3198        }
3199
3200        // DECLARATION-TIME SYNTHESIS. Lean generates `{I}.rec`, `{I}.noConfusionType`,
3201        // `{I}.noConfusion`, `{C}.inj`, `{I}.below`, `{I}.brecOn` and `{I}.decEq` for EVERY
3202        // inductive, at the declaration. Every `injection`, every `cases h` on an equation, every
3203        // `simp [injEq]` in a Lean development names one of them. Requiring the caller to ask
3204        // meant they did not exist, and axiomatising them would have turned each of those proofs
3205        // into an assumption.
3206        //
3207        // Wired on the PLAIN door as well as the checked one, deliberately: `add_constructor` is
3208        // the door `add_mutual_inductives`, `build_structure` and most translators use, so hanging
3209        // it off `add_constructor_checked` alone would have synthesised for a minority of
3210        // declarations. This is where the whole CLASS is covered.
3211        //
3212        // It fires once per CONSTRUCTOR because there is no "declaration finished" call: the
3213        // auxiliaries derived after the first constructor describe an inductive that is not
3214        // finished yet, so each run REPLACES its own prior generation (`derived_aux` provenance)
3215        // and the last one is the one that stands.
3216        if self.auto_aux {
3217            self.regenerate_auxiliaries(inductive);
3218        } else if !self.dirty_aux.iter().any(|n| n == inductive) {
3219            Arc::make_mut(&mut self.dirty_aux).push(inductive.to_string());
3220        }
3221        self.retry_pending(name);
3222    }
3223
3224    /// Turn EAGER declaration-time auxiliary synthesis on or off — Lean's behaviour, made explicit.
3225    ///
3226    /// Turning it on also [`seal`](Context::seal)s whatever is already owed, so enabling it partway
3227    /// through a load does not silently lose the declarations that came first.
3228    ///
3229    /// See the `auto_aux` field's own note for what it costs and why the default is off.
3230    pub fn set_auto_auxiliaries(&mut self, on: bool) {
3231        self.auto_aux = on;
3232        if on {
3233            self.seal();
3234        }
3235    }
3236
3237    /// Whether eager declaration-time auxiliary synthesis is on.
3238    pub fn auto_auxiliaries(&self) -> bool {
3239        self.auto_aux
3240    }
3241
3242    /// Synthesise the auxiliaries of every inductive declared since the last seal, in declaration
3243    /// order — ONE pass per inductive rather than one per constructor.
3244    ///
3245    /// This is the door a library loader uses: register everything, then seal. Idempotent, and a
3246    /// no-op when nothing is owed.
3247    pub fn seal(&mut self) {
3248        let owed = std::mem::take(Arc::make_mut(&mut self.dirty_aux));
3249        for ind in owed {
3250            self.regenerate_auxiliaries(&ind);
3251        }
3252    }
3253
3254    /// The inductives whose auxiliaries are still OWED — declared, not yet synthesised.
3255    ///
3256    /// An honest channel rather than silence: a caller can see exactly which declarations would
3257    /// gain constants from a [`seal`](Context::seal). Lean does not tell you, because there
3258    /// synthesis is unconditional and its cost is invisible.
3259    pub fn unsealed_inductives(&self) -> &[String] {
3260        &self.dirty_aux
3261    }
3262
3263    /// Add a declaration (typed assumption/hypothesis).
3264    ///
3265    /// Used for proof certification where hypotheses are assumed.
3266    /// Example: h1 : P -> Q
3267    ///
3268    /// The type must be a type; a declaration whose type is not one is refused and recorded in
3269    /// [`Context::refused_declarations`]. A type that names a constant declared later is owed, as a
3270    /// definition's is: the assumption waits as a pending obligation, invisible to lookup, and is
3271    /// checked when that name arrives.
3272    pub fn add_declaration(&mut self, name: &str, ty: Term) {
3273        if self.refuse_native_dependency_mutation(name) {
3274            return;
3275        }
3276        let ty = self.stored_term(ty);
3277        #[cfg(feature = "shadow")]
3278        let shadow_entry = crate::dag::mirror::shadow_enter(self);
3279        let blocker = match crate::type_checker::infer_sort(self, &ty) {
3280            Ok(_) => None,
3281            Err(error) => match self.first_unresolvable_global(&ty) {
3282                Some(missing) => Some(missing),
3283                None => {
3284                    #[cfg(feature = "shadow")]
3285                    crate::dag::mirror::shadow(self, &shadow_entry, Some(&error), || {
3286                        vec![crate::dag::logos_env::candidate_axiom(
3287                            self, name, None, &ty,
3288                        )]
3289                    });
3290                    return self.record_refusal(name, error);
3291                }
3292            },
3293        };
3294        let unchanged = self
3295            .declarations
3296            .get(name)
3297            .is_some_and(|current| same_meaning(current, &ty))
3298            && !self.definitions.contains_key(name);
3299        match self.admit_meaning(name, Self::change_if(unchanged)) {
3300            Err(refusal) => return self.record_refusal(name, refusal),
3301            Ok(Admission::Keep) => return,
3302            Ok(Admission::Register) => {}
3303        }
3304        self.displace(name);
3305        self.record_mentions(name, &ty);
3306        self.record(|c| &mut c.declarations, name.to_string(), ty);
3307        match blocker {
3308            Some(missing) => self.defer(name, missing),
3309            None => self.retry_pending(name),
3310        }
3311        #[cfg(feature = "shadow")]
3312        crate::dag::mirror::shadow(self, &shadow_entry, None, Vec::new);
3313    }
3314
3315    /// Register an opaque assumption with an explicit universe telescope.
3316    /// Its type is checked before either the declaration or its metadata is installed.
3317    pub fn add_universe_poly_declaration(
3318        &mut self,
3319        name: &str,
3320        params: Vec<String>,
3321        ty: Term,
3322    ) -> crate::error::KernelResult<()> {
3323        #[cfg(feature = "shadow")]
3324        let shadow_entry = crate::dag::mirror::shadow_enter(self);
3325        #[cfg(feature = "shadow")]
3326        let candidate = vec![crate::dag::logos_env::candidate_axiom(
3327            self,
3328            name,
3329            Some(&params),
3330            &ty,
3331        )];
3332        let result = self.add_universe_poly_declaration_checked(name, params, ty);
3333        #[cfg(feature = "shadow")]
3334        crate::dag::mirror::shadow(self, &shadow_entry, result.as_ref().err(), || candidate);
3335        result
3336    }
3337
3338    fn add_universe_poly_declaration_checked(
3339        &mut self,
3340        name: &str,
3341        params: Vec<String>,
3342        ty: Term,
3343    ) -> crate::error::KernelResult<()> {
3344        self.check_native_dependency_mutation(name)?;
3345        let ty = self.stored_term(ty);
3346        if self.get_global(name).is_some() || self.pending.contains_key(name) {
3347            return Err(crate::error::KernelError::CertificationError(format!(
3348                "checked assumption cannot replace existing declaration {name}"
3349            )));
3350        }
3351        Self::check_level_telescope("assumption", name, &params, [&ty])?;
3352        crate::type_checker::infer_sort(self, &ty)?;
3353        self.displace(name);
3354        self.record_mentions(name, &ty);
3355        self.record(|c| &mut c.declarations, name.to_string(), ty.clone());
3356        self.record(|c| &mut c.poly_types, name.to_string(), (params, ty));
3357        self.retry_pending(name);
3358        Ok(())
3359    }
3360
3361    /// Check an opaque declaration without exposing its body to conversion.
3362    ///
3363    /// Proof dependency evidence is derived internally from the original closed
3364    /// type/body after both checkers agree. Raw headers remain assumptions.
3365    /// This gateway is atomic on failure and never creates pending obligations.
3366    pub fn declare_opaque_checked(
3367        &mut self,
3368        name: &str,
3369        params: Vec<String>,
3370        ty: Term,
3371        body: Term,
3372    ) -> crate::error::KernelResult<()> {
3373        #[cfg(feature = "shadow")]
3374        let shadow_entry = crate::dag::mirror::shadow_enter(self);
3375        #[cfg(feature = "shadow")]
3376        let candidate = vec![crate::dag::logos_env::candidate_definition(
3377            self,
3378            name,
3379            Some(&params),
3380            &ty,
3381            &body,
3382        )];
3383        let result = self.declare_certified_body(name, params, ty, body, false);
3384        #[cfg(feature = "shadow")]
3385        crate::dag::mirror::shadow(self, &shadow_entry, result.as_ref().err(), || candidate);
3386        result
3387    }
3388
3389    /// Check a proposition and its proof in both kernels, then retain its body
3390    /// for kernel delta reduction. Lean theorems use this rule; opaque values do not.
3391    pub fn declare_theorem_checked(
3392        &mut self,
3393        name: &str,
3394        params: Vec<String>,
3395        ty: Term,
3396        body: Term,
3397    ) -> crate::error::KernelResult<()> {
3398        #[cfg(feature = "shadow")]
3399        let shadow_entry = crate::dag::mirror::shadow_enter(self);
3400        #[cfg(feature = "shadow")]
3401        let candidate = vec![crate::dag::logos_env::candidate_definition(
3402            self,
3403            name,
3404            Some(&params),
3405            &ty,
3406            &body,
3407        )];
3408        let result = self.declare_certified_body(name, params, ty, body, true);
3409        #[cfg(feature = "shadow")]
3410        crate::dag::mirror::shadow(self, &shadow_entry, result.as_ref().err(), || candidate);
3411        result
3412    }
3413
3414    /// Whether `name` already holds exactly this checked declaration: published through the
3415    /// checked door at the same universe parameters and type, with — for a transparent theorem —
3416    /// the same body, and — for an opaque one, whose body is sealed — the same dependency evidence.
3417    ///
3418    /// The checked door refuses every existing name, identical or not: it is append-only, as
3419    /// Lean's environment is. A document read a second time meets its own declarations there, and
3420    /// asks this first, so its second reading registers nothing and refuses nothing.
3421    pub fn holds_checked_declaration(
3422        &self,
3423        name: &str,
3424        params: &[String],
3425        ty: &Term,
3426        body: &Term,
3427        transparent_theorem: bool,
3428    ) -> bool {
3429        let Some(evidence) = self.checked_opaque.get(name) else {
3430            return false;
3431        };
3432        if transparent_theorem {
3433            return self.universe_polys.get(name).is_some_and(|payload| {
3434                payload.0 == params
3435                    && same_meaning(&payload.1, ty)
3436                    && same_meaning(&payload.2, body)
3437            });
3438        }
3439        self.poly_types
3440            .get(name)
3441            .is_some_and(|(declared, declared_ty)| {
3442                declared == params && same_meaning(declared_ty, ty)
3443            })
3444            && crate::prelude::checked_opaque_dependencies(self, ty, body)
3445                .checked
3446                .dependencies
3447                == evidence.dependencies
3448    }
3449
3450    /// Whether `name` already holds exactly this ASSUMPTION — a bodyless declaration at the same
3451    /// universe parameters and type, published through the assumption door. The door refuses every
3452    /// existing name; this is the question a document read again asks first (see
3453    /// [`Context::holds_checked_declaration`]).
3454    pub fn holds_assumption(&self, name: &str, params: &[String], ty: &Term) -> bool {
3455        !self.checked_opaque.contains_key(name)
3456            && !self.definitions.contains_key(name)
3457            && self
3458                .declarations
3459                .get(name)
3460                .is_some_and(|declared| same_meaning(declared, ty))
3461            && self
3462                .poly_types
3463                .get(name)
3464                .is_some_and(|(declared, declared_ty)| {
3465                    declared == params && same_meaning(declared_ty, ty)
3466                })
3467    }
3468
3469    fn declare_certified_body(
3470        &mut self,
3471        name: &str,
3472        params: Vec<String>,
3473        ty: Term,
3474        body: Term,
3475        transparent_theorem: bool,
3476    ) -> crate::error::KernelResult<()> {
3477        use crate::error::KernelError;
3478        let (ty, body) = (self.stored_term(ty), self.stored_term(body));
3479        let kind = if transparent_theorem {
3480            "theorem"
3481        } else {
3482            "opaque declaration"
3483        };
3484        let refuse = |reason: &str| {
3485            KernelError::CertificationError(format!("checked {kind} '{name}': {reason}"))
3486        };
3487        self.check_native_dependency_mutation(name)?;
3488        if self.get_global(name).is_some()
3489            || self.poly_declaration(name).is_some()
3490            || self.pending.contains_key(name)
3491        {
3492            return Err(refuse("cannot replace an existing declaration"));
3493        }
3494        if !self.simp_rules().is_empty() {
3495            return Err(refuse(
3496                "active simp rules are outside opaque proof certification",
3497            ));
3498        }
3499        Self::check_level_telescope(kind, name, &params, [&ty, &body])?;
3500        if transparent_theorem && self.delta_cycle_through(name, &body).is_some() {
3501            return Err(refuse("transparent proof body would create a delta cycle"));
3502        }
3503        let main_type = crate::type_checker::infer_type_as_type(self, &ty)?;
3504        if transparent_theorem {
3505            let sort = crate::normalize_checked(self, &main_type)
3506                .map_err(|_| refuse("theorem sort normalization did not complete"))?;
3507            if !matches!(sort, Term::Sort(ref u) if u.equiv(&Universe::Prop)) {
3508                return Err(refuse("theorem type must be a proposition"));
3509            }
3510        }
3511        let independent_type =
3512            crate::recheck(self, &ty).map_err(|error| KernelError::IndependentRecheck {
3513                subject: format!("checked opaque declaration '{name}' independent type"),
3514                error,
3515            })?;
3516        let main_body = crate::infer_type(self, &body)?;
3517        let independent_body =
3518            crate::recheck(self, &body).map_err(|error| KernelError::IndependentRecheck {
3519                subject: format!("checked opaque declaration '{name}' independent body"),
3520                error,
3521            })?;
3522        let exact =
3523            |a: &Term, b: &Term| crate::is_subtype(self, a, b) && crate::is_subtype(self, b, a);
3524        if !exact(&main_type, &independent_type)
3525            || !exact(&main_body, &ty)
3526            || !exact(&independent_body, &ty)
3527        {
3528            return Err(refuse(
3529                "main and independent types must agree with the declared type",
3530            ));
3531        }
3532        // Both checked entry points enforce their input depth limits before
3533        // allocating this additional closedness/provenance representation.
3534        let mut store = crate::term_store::TermStore::new();
3535        for term in [&ty, &body] {
3536            let id = store.intern(term);
3537            if !store.free_names_are_empty(id)
3538                || store
3539                    .shapes(id)
3540                    .contains(crate::term_store::NodeShape::Hole)
3541            {
3542                return Err(refuse("type and body must be closed and contain no holes"));
3543            }
3544        }
3545        let trace = crate::prelude::checked_opaque_dependencies(self, &ty, &body);
3546        if !trace.checked.usage.unresolved.is_empty() {
3547            return Err(refuse("unresolved certification dependency"));
3548        }
3549        // Every fallible validation precedes publication. Both reference forms
3550        // use the same checked type/body and exact explicit universe telescope.
3551        self.displace(name);
3552        if transparent_theorem {
3553            let payload = Arc::new((params, ty, body));
3554            self.record_definition_payload(name.to_string(), Arc::clone(&payload));
3555            self.record(|c| &mut c.universe_polys, name.to_string(), payload);
3556        } else {
3557            // Opaque declarations retain only headers and dependency evidence.
3558            self.record_mentions(name, &ty);
3559            self.record(|c| &mut c.declarations, name.to_string(), ty.clone());
3560            self.record(|c| &mut c.poly_types, name.to_string(), (params, ty));
3561        }
3562        for (dependency, edges) in trace.graph {
3563            self.record_checked_opaque_edges(dependency, edges);
3564        }
3565        self.record_checked_opaque_edges(name.to_string(), trace.checked.dependencies.clone());
3566        Arc::make_mut(&mut self.checked_opaque).insert(name.to_string(), trace.checked);
3567        self.retry_pending(name);
3568        Ok(())
3569    }
3570
3571    /// Register a definition: name : type := body
3572    ///
3573    /// Definitions are transparent and unfold during normalization (delta reduction).
3574    /// This distinguishes them from declarations (axioms) which have no body.
3575    ///
3576    /// The BODY IS CHECKED against the declared type — see [`Context::declare`], which this is the
3577    /// `()`-returning face of. A body that definitely does not have the declared type is REFUSED
3578    /// and nothing is registered, so `evil : False := Zero` can no longer put a closed term of type
3579    /// `False` in reach of the standard library. Use `declare` where the refusal can be reported.
3580    pub fn add_definition(&mut self, name: String, ty: Term, body: Term) {
3581        if let Err(e) = self.declare(&name, ty, body) {
3582            // A refusal this face cannot return is RECORDED rather than swallowed — see
3583            // [`Context::refused_declarations`].
3584            Arc::make_mut(&mut self.refused).push((name, format!("{e}")));
3585        }
3586    }
3587
3588    /// Every declaration the checked gateway REFUSED, as `(name, reason)`, in refusal order.
3589    ///
3590    /// Empty is the healthy state and the thing to lock: it says every definition in this context
3591    /// was checked or is tracked as owed, and none was silently dropped.
3592    pub fn refused_declarations(&self) -> &[(String, String)] {
3593        &self.refused
3594    }
3595
3596    /// THE CHECKED REGISTRATION GATEWAY — one door, and everything that registers a definition
3597    /// goes through it.
3598    ///
3599    /// `add_definition` used to be an `insert`. That is a hole the size of the whole kernel: the
3600    /// type a name is registered AT is the type `infer_type` hands back for it, so an unchecked
3601    /// insert lets any caller mint a constant of any type, `False` included, and every proof built
3602    /// on top of it certifies. The Repl surface had the check; the raw `Context` API, which is the
3603    /// API several hundred call sites use, did not.
3604    ///
3605    /// What it refuses, and what it deliberately does not:
3606    ///
3607    /// * a body whose inferred type is not a subtype of the declared one — REFUSED, nothing
3608    ///   registered. (That subsumes a nonsense declared type: nothing is a subtype of it.)
3609    /// * a body mentioning a GLOBAL that is not yet in scope — ACCEPTED, with a PENDING OBLIGATION
3610    ///   recorded against the missing name. Forward references are legitimate and common (a
3611    ///   δ-chain registered in ascending order; a family of mutually-referring definitions). The
3612    ///   obligation is retried the moment the missing name is declared, so the check is DEFERRED
3613    ///   rather than skipped — and [`Context::pending_obligations`] reports what is still owed,
3614    ///   which is strictly more than a kernel that simply accepted.
3615    /// * a body whose failure NOTHING can repair — REFUSED. A deferral is owed against a name a
3616    ///   later declaration could supply and against nothing else (see
3617    ///   `Context::deferrable_blocker`); an obligation keyed on anything else is an IOU with no
3618    ///   payer, and a definition sitting in the library behind one has a body that will never be
3619    ///   checked. That state is not reported here, it is made unreachable.
3620    /// * a body that would close a δ-CYCLE — REFUSED, before anything is inserted. See
3621    ///   `Context::delta_cycle_through`.
3622    ///
3623    /// Better than Lean here: Lean's `addDecl` refuses a forward reference outright, so a
3624    /// translator has to topologically sort before it can emit. This accepts the emission order
3625    /// and still reports every claim it has not been able to discharge.
3626    pub fn declare(&mut self, name: &str, ty: Term, body: Term) -> crate::error::KernelResult<()> {
3627        #[cfg(feature = "shadow")]
3628        let shadow_entry = crate::dag::mirror::shadow_enter(self);
3629        #[cfg(feature = "shadow")]
3630        let candidate = vec![crate::dag::logos_env::candidate_definition(
3631            self, name, None, &ty, &body,
3632        )];
3633        let result = self.declare_definition(name, None, ty, body);
3634        #[cfg(feature = "shadow")]
3635        crate::dag::mirror::shadow(self, &shadow_entry, result.as_ref().err(), || candidate);
3636        result
3637    }
3638
3639    /// Run additional source-language checks and ordinary kernel body checking
3640    /// against one immutable context. The callback cannot authorize a body:
3641    /// the kernel still checks it, and all normal registration guards remain.
3642    /// Only kernel-earned positive conversion results are shared within this call.
3643    pub fn declare_with_validation<E: From<crate::error::KernelError>>(
3644        &mut self,
3645        name: &str,
3646        ty: Term,
3647        body: Term,
3648        validate: impl FnOnce(&Context, &Term, &Term) -> Result<(), E>,
3649    ) -> Result<(), E> {
3650        let checked = crate::conversion_session::scope(self, || {
3651            validate(self, &ty, &body)?;
3652            Ok::<_, E>(self.check_body(&ty, &body))
3653        })?;
3654        #[cfg(feature = "shadow")]
3655        let shadow_entry = crate::dag::mirror::shadow_enter(self);
3656        #[cfg(feature = "shadow")]
3657        let candidate = vec![crate::dag::logos_env::candidate_definition(
3658            self, name, None, &ty, &body,
3659        )];
3660        let result =
3661            self.declare_definition_with_checked_body(name, None, ty, body, true, Some(checked));
3662        #[cfg(feature = "shadow")]
3663        crate::dag::mirror::shadow(self, &shadow_entry, result.as_ref().err(), || candidate);
3664        result.map_err(E::from)
3665    }
3666
3667    /// Optional generated proofs use the same checked gateway, but an unknown
3668    /// dependency must refuse the candidate rather than leave a pending proof.
3669    pub(crate) fn declare_checked_auxiliary(
3670        &mut self,
3671        name: &str,
3672        ty: Term,
3673        body: Term,
3674    ) -> crate::error::KernelResult<()> {
3675        self.declare_definition_with_policy(name, None, ty, body, false)
3676    }
3677
3678    fn declare_definition(
3679        &mut self,
3680        name: &str,
3681        levels: Option<Vec<String>>,
3682        ty: Term,
3683        body: Term,
3684    ) -> crate::error::KernelResult<()> {
3685        self.declare_definition_with_policy(name, levels, ty, body, true)
3686    }
3687
3688    fn declare_definition_with_policy(
3689        &mut self,
3690        name: &str,
3691        levels: Option<Vec<String>>,
3692        ty: Term,
3693        body: Term,
3694        allow_pending: bool,
3695    ) -> crate::error::KernelResult<()> {
3696        self.declare_definition_with_checked_body(name, levels, ty, body, allow_pending, None)
3697    }
3698
3699    fn declare_definition_with_checked_body(
3700        &mut self,
3701        name: &str,
3702        levels: Option<Vec<String>>,
3703        ty: Term,
3704        body: Term,
3705        allow_pending: bool,
3706        checked: Option<crate::error::KernelResult<()>>,
3707    ) -> crate::error::KernelResult<()> {
3708        self.check_native_dependency_mutation(name)?;
3709        let (ty, body) = (self.stored_term(ty), self.stored_term(body));
3710        // A definition that states no telescope binds every level its stored terms mention
3711        // (`term`'s rules 1 and 4): its type's, then those only its body's references carry.
3712        let levels = match levels {
3713            Some(params) => {
3714                Self::check_level_telescope("definition", name, &params, [&ty, &body])?;
3715                Some(params)
3716            }
3717            None => crate::term::definition_telescope(&ty, &body),
3718        };
3719        let bodyless_at_this_type = self
3720            .declarations
3721            .get(name)
3722            .is_some_and(|current| same_meaning(current, &ty))
3723            && !self.definitions.contains_key(name)
3724            && !self.universe_polys.contains_key(name)
3725            && match &levels {
3726                None => !self.poly_types.contains_key(name),
3727                Some(params) => self
3728                    .poly_types
3729                    .get(name)
3730                    .is_some_and(|(declared, declared_ty)| {
3731                        declared == params && same_meaning(declared_ty, &ty)
3732                    }),
3733            };
3734        let identical = match &levels {
3735            None => {
3736                !self.universe_polys.contains_key(name)
3737                    && self.definitions.get(name).is_some_and(|current| {
3738                        current.0.is_empty()
3739                            && same_meaning(&current.1, &ty)
3740                            && same_meaning(&current.2, &body)
3741                    })
3742            }
3743            Some(params) => self.universe_polys.get(name).is_some_and(|current| {
3744                &current.0 == params
3745                    && same_meaning(&current.1, &ty)
3746                    && same_meaning(&current.2, &body)
3747            }),
3748        };
3749        let change = if identical {
3750            Change::Identical
3751        } else if bodyless_at_this_type {
3752            Change::Refinement
3753        } else {
3754            Change::Different
3755        };
3756        if self.admit_meaning(name, change)? == Admission::Keep {
3757            return Ok(());
3758        }
3759        // δ-ACYCLICITY, before anything is inserted. Lean's own rule — a constant's value may only
3760        // reference constants declared before it — and it is what makes δ-normalisation TOTAL. See
3761        // `Context::delta_reaches` for why the check is affordable.
3762        if let Some(through) = self.delta_cycle_through(name, &body) {
3763            return Err(crate::error::KernelError::CertificationError(format!(
3764                "`{name}` cannot be defined in terms of `{through}`: `{through}` already unfolds \
3765                 back to `{name}`, so the pair has NO normal form and δ-reduction would never \
3766                 finish. A constant's value may only mention constants that do not depend on it \
3767                 (use a `fix`/`mutualfix` for a genuinely recursive definition, where the \
3768                 termination guard can see it)"
3769            )));
3770        }
3771
3772        let verdict = match checked.unwrap_or_else(|| self.check_body(&ty, &body)) {
3773            Ok(()) => Verdict::Checked,
3774            Err(e) if !allow_pending => return Err(e),
3775            // DEFERRED, never skipped — but only when the FAILURE CAN STILL BE REPAIRED. The
3776            // condition is a property of the body and this context, not the spelling of one
3777            // error variant: a body mentioning a global that resolves nowhere may become
3778            // checkable the moment that global is declared, and nothing else may. Keying on
3779            // `KernelError::UnboundVariable` instead made two mistakes at once — a name in
3780            // `type_checker::UNTRUSTED_AXIOMS` is reported as a `CertificationError`, so a body
3781            // forward-referencing `sorryAx` was REFUSED rather than deferred; and a fixpoint's
3782            // own binder is reported as unbound, so a body blocked on a name NO declaration can
3783            // ever supply was deferred for ever, sitting in the trusted library with an IOU that
3784            // could not be paid.
3785            Err(e) => match self.deferrable_blocker(&ty, &body) {
3786                Some(missing) => Verdict::Pending(missing),
3787                None => return Err(e),
3788            },
3789        };
3790
3791        // Displace first: without this a definition could sit alongside an inductive or constructor
3792        // of the same name, and `get_global` (inductives -> constructors -> definitions) would TYPE
3793        // the name from one map while `get_definition_body` REDUCED it from another. That is
3794        // conformance defect 3, a divergence between typing and reduction — the two
3795        // things a kernel most needs to agree.
3796        self.displace(name);
3797        match levels {
3798            Some(params) => self.record_universe_poly(name.to_string(), params, ty, body),
3799            None => self.record_definition(name.to_string(), ty, body),
3800        }
3801
3802        match verdict {
3803            Verdict::Checked => {
3804                Arc::make_mut(&mut self.pending).remove(name);
3805            }
3806            Verdict::Pending(missing) => self.defer(name, missing),
3807        }
3808        // Equation synthesis is optional, checked front-end output. It does
3809        // nothing for pending bodies or contexts lacking the standard equality.
3810        crate::equations::generate(self, name);
3811        // Whatever was waiting on THIS name can now be retried.
3812        self.retry_pending(name);
3813        Ok(())
3814    }
3815
3816    /// CHECK `body` against the DECLARED type `ty` — the bidirectional half of the gateway.
3817    ///
3818    /// For every body but a fixpoint this is exactly `infer_type` followed by the subtype test,
3819    /// unchanged. A `Term::Fix` is the one shape where CHECKING is strictly stronger than
3820    /// INFERRING, and the difference is not cosmetic:
3821    ///
3822    /// `infer_type`'s `Fix` arm has to GUESS the fixpoint's type from the body's shape
3823    /// (`type_checker::infer_fix_type_structurally`), because nothing has told it one. That guess
3824    /// reads a λ-telescope and then a `Match`'s motive; a body whose base case is an APPLICATION
3825    /// of a match (`fix rec. λn. λv1. λv2. (match v1 … ) v2`) falls through to plain inference in
3826    /// a context where the fixpoint's own binder is NOT bound, and reports it as unbound. A
3827    /// declaration does not have to guess — it was handed the type — so it binds the fixpoint's
3828    /// own name at the declared type and checks the body there, which is the rule a bidirectional
3829    /// elaborator states for `def f : T := fix f. e` and the rule Lean's recursion compiler
3830    /// implements.
3831    ///
3832    /// The GUARDIAN is not skipped: `termination::check_termination` runs on exactly the body
3833    /// `infer_type` would have run it on. Without it `fix f. f` would check at any type at all and
3834    /// `False` would be one line away.
3835    ///
3836    /// Two conditions keep this from ever accepting more than inference does:
3837    ///
3838    /// * the declared type must itself BE a type in this context, or the binding put in scope
3839    ///   would be nonsense and `is_subtype` would then compare the body against that same
3840    ///   nonsense;
3841    /// * a failure FALLS BACK to the inference path and reports ITS error, so nothing that is
3842    ///   accepted today stops being accepted and no diagnostic changes.
3843    /// A definition's body against its declared type: the declared type is a type, and the body
3844    /// checks against it (`type_checker::check_type`: a fixpoint at the declared type itself, with
3845    /// the guard; anything else by inference and cumulative subtyping).
3846    fn check_body(&self, ty: &Term, body: &Term) -> crate::error::KernelResult<()> {
3847        crate::type_checker::infer_sort(self, ty)?;
3848        crate::type_checker::check_type(self, body, ty)
3849    }
3850
3851    /// Install a definition and the δ-bookkeeping that goes with it — the ONE place a definition
3852    /// enters `definitions`, so its edge list and the reverse "is this name mentioned anywhere"
3853    /// index can never fall out of step with it.
3854    fn record_definition(&mut self, name: String, ty: Term, body: Term) {
3855        self.record_definition_payload(name, Arc::new((Vec::new(), ty, body)));
3856    }
3857
3858    /// Install a universe-polymorphic definition: the ONE place one enters `universe_polys`, with
3859    /// the δ-bookkeeping [`Context::record_definition`] gives a monomorphic one.
3860    fn record_universe_poly(&mut self, name: String, params: Vec<String>, ty: Term, body: Term) {
3861        self.record_definition_dependencies(&name, &body);
3862        self.record_definition_mentions(&name, &ty, &body);
3863        self.record(
3864            |c| &mut c.universe_polys,
3865            name,
3866            Arc::new((params, ty, body)),
3867        );
3868    }
3869
3870    fn record_definition_payload(&mut self, name: String, payload: Arc<DefinitionPayload>) {
3871        self.invalidate_checked_opaque(&name);
3872        self.record_definition_dependencies(&name, &payload.2);
3873        self.record_definition_mentions(&name, &payload.1, &payload.2);
3874        self.record(|c| &mut c.definitions, name, payload);
3875    }
3876
3877    /// A definition mentions what its TYPE mentions and what its body does — the body's edges
3878    /// were just recorded for the δ-graph, so they are read back rather than walked twice.
3879    fn record_definition_mentions(&mut self, name: &str, ty: &Term, body: &Term) {
3880        let edges = self
3881            .definition_deps
3882            .get(name)
3883            .map(|edges| edges.to_vec())
3884            .unwrap_or_default();
3885        self.record_mention_edges(name, edges);
3886        self.record_eliminations(name, body);
3887        self.record_mentions(name, ty);
3888    }
3889
3890    fn record_definition_dependencies(&mut self, name: &str, body: &Term) {
3891        let mut borrowed: Vec<&str> = Vec::new();
3892        collect_global_mentions(body, &mut borrowed);
3893        borrowed.sort_unstable();
3894        borrowed.dedup();
3895        let edges: Vec<String> = borrowed.into_iter().map(str::to_string).collect();
3896        if !edges.is_empty() {
3897            let seen = Arc::make_mut(&mut self.referenced);
3898            for e in &edges {
3899                if !seen.contains(e.as_str()) {
3900                    seen.insert(e.clone());
3901                }
3902            }
3903        }
3904        let height = 1 + edges
3905            .iter()
3906            .map(|edge| self.definition_height(edge))
3907            .max()
3908            .unwrap_or(0);
3909        Arc::make_mut(&mut self.definition_heights).insert(name.to_string(), height);
3910        Arc::make_mut(&mut self.definition_deps)
3911            .insert(name.to_string(), edges.into_boxed_slice().into());
3912    }
3913
3914    /// The definitional height of `name` (see `definition_heights`); 0 for anything without a
3915    /// registered body.
3916    pub(crate) fn definition_height(&self, name: &str) -> u32 {
3917        self.definition_heights.get(name).copied().unwrap_or(0)
3918    }
3919
3920    /// The first name in a definition's declared type or `body` that RESOLVES NOWHERE and that a
3921    /// later declaration could still supply — the exact condition under which a deferral is owed,
3922    /// and the only one.
3923    ///
3924    /// "Could still supply" is the whole content of the predicate, and it is why only a
3925    /// CONSTANT-form name qualifies. Every door that binds a constant — `declare`,
3926    /// `add_declaration`, `add_inductive`, `add_constructor`, `add_universe_poly` — retries the
3927    /// obligations keyed on the name it bound. Nothing retries a `Term::Var`, and nothing ever
3928    /// could: `infer_type`'s `Var` arm reads `Context::bindings`, which belongs to the enclosing
3929    /// TERM's binders and not to the environment. So an obligation keyed on a variable name is an
3930    /// IOU with no payer — which is exactly the state three prelude definitions were in, and
3931    /// exactly the state `Definition boom : False := fix f. f` exploited: `infer_type` reports the
3932    /// fixpoint's own binder as `UnboundVariable("f")`, the gateway read the VARIANT, deferred,
3933    /// and registered a constant of type `False` without the termination guard ever running.
3934    fn deferrable_blocker(&self, ty: &Term, body: &Term) -> Option<String> {
3935        self.first_unresolvable_global(ty)
3936            .or_else(|| self.first_unresolvable_global(body))
3937    }
3938
3939    fn first_unresolvable_global(&self, body: &Term) -> Option<String> {
3940        let mut names: Vec<&str> = Vec::new();
3941        collect_global_mentions(body, &mut names);
3942        names
3943            .into_iter()
3944            .find(|n| !self.resolves(n))
3945            .map(str::to_string)
3946    }
3947
3948    /// Does `name` resolve as a CONSTANT here — asked exactly the way `infer_type` asks it, so
3949    /// this can never call reachable a name typing would call unbound.
3950    fn resolves(&self, name: &str) -> bool {
3951        self.get_global(name).is_some() || self.get_universe_poly(name).is_some()
3952    }
3953
3954    /// The global in `body` through which defining `name` would close a δ-CYCLE, if there is one.
3955    ///
3956    /// Lean's rule, and the reason δ-normalisation is total there: a constant's value may only
3957    /// mention constants that do not depend on it. Without it `loop_a := loop_b` beside
3958    /// `loop_b := loop_a` is a well-typed pair with NO normal form, and `normalize` has nothing to
3959    /// hand back but an abandoned reduction that looks exactly like a finished one —
3960    /// conformance defect 9. Refusing the SECOND of the two is the whole fix, and it needs no change to
3961    /// reduction at all.
3962    ///
3963    /// AFFORDABLE, which is what makes it a gateway check rather than an audit:
3964    ///
3965    /// * a name that nothing already mentions cannot be on a cycle, so the common case (a fresh
3966    ///   declaration) costs one hash lookup — that is what `referenced` is for;
3967    /// * the search expands only DEFINITIONS and stops the moment it sees `name`, so a chain
3968    ///   declared in forward-reference order (`chain0 := chain1` while `chain1` has no body yet)
3969    ///   costs one step per insert, not one per link;
3970    /// * `name`'s own current body is never expanded, because the walk stops there — which is
3971    ///   right, since a redeclaration REPLACES it.
3972    fn delta_cycle_through(&self, name: &str, body: &Term) -> Option<String> {
3973        let mut roots: Vec<&str> = Vec::new();
3974        collect_global_mentions(body, &mut roots);
3975        // A body that names ITSELF is the one-element cycle, and it is a cycle whether or not
3976        // anything else has ever mentioned the name — so this question is asked before the
3977        // `referenced` short-circuit, not after it.
3978        if roots.contains(&name) {
3979            return Some(name.to_string());
3980        }
3981        if !self.referenced.contains(name) {
3982            return None;
3983        }
3984        roots.sort_unstable();
3985        roots.dedup();
3986        roots
3987            .into_iter()
3988            .find(|g| self.delta_reaches(g, name))
3989            .map(str::to_string)
3990    }
3991
3992    /// Whether a term depends on a definition whose admission is unfinished.
3993    ///
3994    /// Inspect references before reduction: beta/zeta reduction may erase one,
3995    /// and a previously admitted definition can acquire a pending dependency
3996    /// through redeclaration. The graph is read afresh on every query.
3997    pub(crate) fn has_pending_dependency(&self, term: &Term) -> bool {
3998        if self.pending.is_empty() {
3999            return false;
4000        }
4001        let mut roots = Vec::new();
4002        collect_global_mentions(term, &mut roots);
4003        let mut stack: Vec<String> = roots.into_iter().map(str::to_owned).collect();
4004        let mut seen = std::collections::HashSet::new();
4005        while let Some(name) = stack.pop() {
4006            if self.pending.contains_key(&name) {
4007                return true;
4008            }
4009            if !seen.insert(name.clone()) {
4010                continue;
4011            }
4012            if let Some(edges) = self.edges_of(&name) {
4013                stack.extend(edges.iter().filter(|n| !seen.contains(*n)).cloned());
4014            }
4015            let ty = self
4016                .get_global(&name)
4017                .or_else(|| self.get_universe_poly(&name).map(|(_, ty, _)| ty));
4018            if let Some(ty) = ty {
4019                let mut references = Vec::new();
4020                collect_global_mentions(ty, &mut references);
4021                stack.extend(
4022                    references
4023                        .into_iter()
4024                        .filter(|n| !seen.contains(*n))
4025                        .map(str::to_owned),
4026                );
4027            }
4028        }
4029        false
4030    }
4031
4032    /// The δ-edges of `name`: the cached list where one exists, and the body's own mentions
4033    /// otherwise. `None` for a name that is not a definition at all — a leaf of the δ-graph.
4034    fn edges_of(&self, name: &str) -> Option<Arc<[String]>> {
4035        if let Some(cached) = self.definition_deps.get(name) {
4036            return Some(cached.clone());
4037        }
4038        let body = &self
4039            .definitions
4040            .get(name)
4041            .or_else(|| self.universe_polys.get(name))?
4042            .2;
4043        let mut out: Vec<&str> = Vec::new();
4044        collect_global_mentions(body, &mut out);
4045        out.sort_unstable();
4046        out.dedup();
4047        let owned: Vec<String> = out.into_iter().map(str::to_string).collect();
4048        Some(owned.into_boxed_slice().into())
4049    }
4050
4051    /// Does unfolding definitions from `start` ever reach `target`? `start == target` counts: a
4052    /// definition whose own body names it is a one-element cycle.
4053    fn delta_reaches(&self, start: &str, target: &str) -> bool {
4054        if start == target {
4055            return true;
4056        }
4057        let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
4058        let mut stack: Vec<String> = vec![start.to_string()];
4059        while let Some(cur) = stack.pop() {
4060            let Some(edges) = self.edges_of(&cur) else {
4061                continue;
4062            };
4063            if !seen.insert(cur) {
4064                continue;
4065            }
4066            for n in edges.iter() {
4067                if n == target {
4068                    return true;
4069                }
4070                if !seen.contains(n.as_str())
4071                    && (self.definitions.contains_key(n.as_str())
4072                        || self.universe_polys.contains_key(n.as_str()))
4073                {
4074                    stack.push(n.clone());
4075                }
4076            }
4077        }
4078        false
4079    }
4080
4081    /// Record that `who`'s body cannot be checked until `blocker` is in scope.
4082    fn defer(&mut self, who: &str, blocker: String) {
4083        Arc::make_mut(&mut self.pending_waiters)
4084            .entry(blocker.clone())
4085            .or_default()
4086            .push(who.to_string());
4087        Arc::make_mut(&mut self.pending).insert(who.to_string(), blocker);
4088    }
4089
4090    /// Retry every deferred obligation that was blocked on `name`, now that `name` is in scope.
4091    ///
4092    /// Amortised O(1) per declaration: obligations are keyed by the name they wait for, so this
4093    /// touches only the ones that were actually unblocked. A retry that fails again is re-keyed on
4094    /// whatever it is missing NOW (a chain of forward references resolves one link at a time); a
4095    /// retry that finds a genuine type error leaves the obligation standing, where
4096    /// [`Context::pending_obligations`] reports it, rather than retroactively deleting a constant
4097    /// other declarations may already be built on.
4098    fn retry_pending(&mut self, name: &str) {
4099        let mut ready = std::collections::VecDeque::from([name.to_string()]);
4100        while let Some(available) = ready.pop_front() {
4101            let Some(waiting) = Arc::make_mut(&mut self.pending_waiters).remove(&available) else {
4102                continue;
4103            };
4104            for who in waiting {
4105                if self.pending.get(&who).map(String::as_str) != Some(available.as_str()) {
4106                    continue;
4107                }
4108                let definition = self
4109                    .definitions
4110                    .get(&who)
4111                    .or_else(|| self.universe_polys.get(&who))
4112                    .cloned();
4113                let Some(payload) = definition else {
4114                    // A deferred assumption: its type, checked now.
4115                    if let Some(ty) = self.declarations.get(&who).cloned() {
4116                        match crate::type_checker::infer_sort(self, &ty) {
4117                            Ok(_) => {
4118                                Arc::make_mut(&mut self.pending).remove(&who);
4119                                ready.push_back(who);
4120                            }
4121                            Err(_) => {
4122                                if let Some(next) = self.first_unresolvable_global(&ty) {
4123                                    self.defer(&who, next);
4124                                }
4125                            }
4126                        }
4127                        continue;
4128                    }
4129                    Arc::make_mut(&mut self.pending).remove(&who);
4130                    continue;
4131                };
4132                let (_, ty, body) = payload.as_ref();
4133                match self.check_body(ty, body) {
4134                    Ok(()) => {
4135                        Arc::make_mut(&mut self.pending).remove(&who);
4136                        crate::equations::generate(self, &who);
4137                        ready.push_back(who);
4138                    }
4139                    Err(_) => {
4140                        if let Some(next) = self.deferrable_blocker(ty, body) {
4141                            self.defer(&who, next);
4142                        }
4143                    }
4144                }
4145            }
4146        }
4147    }
4148
4149    /// Definitions whose body has NOT yet been checked against its declared type, and assumptions
4150    /// whose type has not, each paired with the name it is still waiting for — our `#print axioms`
4151    /// for deferred obligations.
4152    ///
4153    /// Pending definitions remain recorded but are unavailable to constant lookup and
4154    /// reduction until their bodies have been checked. Resolving a dependency retries its
4155    /// waiting definitions and exposes only those whose checks succeed.
4156    pub fn pending_obligations(&self) -> Vec<(&str, &str)> {
4157        self.pending
4158            .iter()
4159            .map(|(k, v)| (k.as_str(), v.as_str()))
4160            .collect()
4161    }
4162
4163    /// Look up a global definition (inductive, constructor, definition, or declaration).
4164    ///
4165    /// Returns the type of the global.
4166    pub fn get_global(&self, name: &str) -> Option<&Term> {
4167        if self.pending.contains_key(name) {
4168            return None;
4169        }
4170        // Check inductives first
4171        if let Some(sort) = self.inductives.get(name) {
4172            return Some(sort);
4173        }
4174        // Check constructors
4175        if let Some((_, ty)) = self.constructors.get(name) {
4176            return Some(ty);
4177        }
4178        // Check definitions (return type, not body)
4179        if let Some(payload) = self.definitions.get(name) {
4180            return Some(&payload.1);
4181        }
4182        // Check declarations (axioms)
4183        self.declarations.get(name)
4184    }
4185
4186    /// Check if a name is a definition (has a body that can be unfolded).
4187    pub fn is_definition(&self, name: &str) -> bool {
4188        self.definitions.contains_key(name)
4189    }
4190
4191    /// Get the body of a definition, if it exists.
4192    ///
4193    /// Returns None for axioms, constructors, and inductives (only definitions have bodies).
4194    pub fn get_definition_body(&self, name: &str) -> Option<&Term> {
4195        if self.pending.contains_key(name) {
4196            return None;
4197        }
4198        self.definitions.get(name).map(|payload| &payload.2)
4199    }
4200
4201    /// Get the type of a definition, if it exists.
4202    pub fn get_definition_type(&self, name: &str) -> Option<&Term> {
4203        if self.pending.contains_key(name) {
4204            return None;
4205        }
4206        self.definitions.get(name).map(|payload| &payload.1)
4207    }
4208
4209    /// Check if a name is a constructor.
4210    pub fn is_constructor(&self, name: &str) -> bool {
4211        self.constructors.contains_key(name)
4212    }
4213
4214    /// Get the inductive type a constructor belongs to.
4215    pub fn constructor_inductive(&self, name: &str) -> Option<&str> {
4216        self.constructors.get(name).map(|(ind, _)| ind.as_str())
4217    }
4218
4219    /// Check if a name is an inductive type.
4220    pub fn is_inductive(&self, name: &str) -> bool {
4221        self.inductives.contains_key(name)
4222    }
4223
4224    /// Ordered-name inventory length before filtering stale registry entries.
4225    /// A borrowed allocation-admission upper bound, never a validity certificate.
4226    pub(crate) fn constructor_inventory_upper_bound(&self, inductive: &str) -> usize {
4227        self.constructor_order
4228            .get(inductive)
4229            .map_or(0, |names| names.len())
4230    }
4231
4232    /// Get all constructors for an inductive type, in registration order.
4233    ///
4234    /// Returns a vector of (constructor_name, constructor_type) pairs.
4235    pub fn get_constructors(&self, inductive: &str) -> Vec<(&str, &Term)> {
4236        self.constructor_headers(inductive).collect()
4237    }
4238
4239    /// Borrow constructor headers in the same registration order as get_constructors.
4240    pub(crate) fn constructor_headers<'a>(
4241        &'a self,
4242        inductive: &str,
4243    ) -> impl Iterator<Item = (&'a str, &'a Term)> {
4244        self.constructor_order
4245            .get(inductive)
4246            .into_iter()
4247            .flatten()
4248            .filter_map(|name| {
4249                self.constructors
4250                    .get(name)
4251                    .map(|(_, ty)| (name.as_str(), ty))
4252            })
4253    }
4254
4255    /// Borrow the sole ordered constructor header, without an inventory allocation.
4256    /// This lookup is metadata only and does not certify the declaration.
4257    pub(crate) fn unique_constructor_header(&self, inductive: &str) -> Option<(&str, &Term)> {
4258        let names = self.constructor_order.get(inductive)?;
4259        if names.len() != 1 {
4260            return None;
4261        }
4262        let name = &names[0];
4263        let (_, ty) = self.constructors.get(name)?;
4264        Some((name.as_str(), ty))
4265    }
4266
4267    /// Iterate over all declarations (hypotheses).
4268    ///
4269    /// Used by the certifier to find hypothesis by type.
4270    pub fn iter_declarations(&self) -> impl Iterator<Item = (&str, &Term)> {
4271        self.declarations.iter().map(|(k, v)| (k.as_str(), v))
4272    }
4273
4274    /// Iterate over all definitions.
4275    ///
4276    /// Used by the UI to display definitions.
4277    pub fn iter_definitions(&self) -> impl Iterator<Item = (&str, &Term, &Term)> {
4278        self.definitions
4279            .iter()
4280            .map(|(k, payload)| (k.as_str(), &payload.1, &payload.2))
4281    }
4282
4283    /// Iterate over all inductive types.
4284    ///
4285    /// Used by the UI to display inductive types.
4286    pub fn iter_inductives(&self) -> impl Iterator<Item = (&str, &Term)> {
4287        self.inductives.iter().map(|(k, v)| (k.as_str(), v))
4288    }
4289
4290    /// Iterate over the universe-polymorphic definitions: name, level parameters, type, body.
4291    pub fn iter_universe_polys(&self) -> impl Iterator<Item = (&str, &[String], &Term, &Term)> {
4292        self.universe_polys
4293            .iter()
4294            .map(|(k, payload)| (k.as_str(), payload.0.as_slice(), &payload.1, &payload.2))
4295    }
4296
4297    /// Add a constructor with strict positivity checking.
4298    ///
4299    /// Returns an error if the inductive type appears negatively in the
4300    /// constructor type. This prevents paradoxes like:
4301    /// ```text
4302    /// Inductive Bad := Cons : (Bad -> False) -> Bad
4303    /// ```
4304    /// Derive and register everything Lean synthesises at declaration time — `{I}_rec`,
4305    /// `{I}_noConfusionType`, `{I}_noConfusion`, `{C}_inj`, `{I}_below`, `{I}_brecOn`, `decEq{I}` —
4306    /// and register `decEq{I}` as a `Decidable` instance so `decide` can actually reach it.
4307    ///
4308    /// Lean generates these for EVERY inductive; we generated exactly one, and even that had to be
4309    /// requested by the caller. Every `injection`, every `cases h` on an equation, every
4310    /// `simp [injEq]` in a Lean development names one of these. They are all DERIVED and
4311    /// kernel-checked — axiomatising them would turn each of those proofs into an assumption.
4312    ///
4313    /// Best-effort by construction: `derive_auxiliaries` omits what it cannot state (indexed
4314    /// families, `Prop` carriers where disjointness is *false* by proof irrelevance, carriers above
4315    /// `Type 0` while `Eq` is `Type 0`-only) rather than faking it. Silence here is a scope
4316    /// boundary, not a failure.
4317    pub(crate) fn regenerate_auxiliaries(&mut self, ind: &str) {
4318        if self.native_positivity_dependencies.contains(ind) {
4319            return;
4320        }
4321        // Nothing to derive for a name that is not (yet) an inductive.
4322        if !self.is_inductive(ind) {
4323            return;
4324        }
4325        // Drop only OUR previous generation for this inductive — never a hand-written constant,
4326        // and never one that has since been displaced by something else (`displace` disowns).
4327        if let Some(previous) = Arc::make_mut(&mut self.derived_aux).remove(ind) {
4328            for name in previous {
4329                self.displace(&name);
4330            }
4331        }
4332        // A universe-polymorphic family's auxiliaries come stated over its telescope, its own names
4333        // written at the generic instance, as Lean's are (`recursor::generic_family`), and are
4334        // registered polymorphic in it. Any other auxiliary binds the levels its stored terms
4335        // mention, as a definition through the gateway does.
4336        let produced = crate::recursor::derive_auxiliaries(self, ind);
4337        let telescope = crate::recursor::generic_family(self, ind).map(|(ps, _)| ps);
4338        let mut names: Vec<String> = Vec::with_capacity(produced.len());
4339        for crate::recursor::DerivedAux { name, ty, term } in produced {
4340            // KERNEL-CHECKED before it is trusted, through the door every definition takes. `derive_*`
4341            // is UNTRUSTED front-end code: it builds a term and claims a type, and declaration-time
4342            // registration is the moment that claim would otherwise become an assumption of the
4343            // standard library. Checking costs one pass per auxiliary and buys the guarantee that
4344            // an auxiliary is a THEOREM, never an axiom — the same bargain `add_nested_inductive`
4345            // already strikes for its conversion isos.
4346            //
4347            // A derivation that does not check is DROPPED, silently but harmlessly: the constant
4348            // simply does not exist, exactly as before declaration-time synthesis existed. It is
4349            // never registered unchecked.
4350            if self.check_body(&ty, &term).is_err() {
4351                continue;
4352            }
4353            // A DERIVED decidable equality is also an INSTANCE, or nothing can resolve it — and it
4354            // goes in the FALLBACK tier, never the declared one: `Context::instances()` is the
4355            // faithful record of what the program declared, and a library-synthesised entry must
4356            // not outrank a user instance for the same goal (nor move a count measured against it).
4357            if name == format!("decEq{ind}") {
4358                let value = match &telescope {
4359                    Some(ps) => Term::Const {
4360                        name: name.clone(),
4361                        levels: ps.iter().map(|l| Universe::Var(l.clone())).collect(),
4362                    },
4363                    None => Term::Global(name.clone()),
4364                };
4365                self.add_fallback_instance(ty.clone(), value);
4366            }
4367            Arc::make_mut(&mut self.derived_aux_owner).insert(name.clone(), ind.to_string());
4368            names.push(name.clone());
4369            match telescope
4370                .clone()
4371                .or_else(|| crate::term::definition_telescope(&ty, &term))
4372            {
4373                Some(ps) => self.record_universe_poly(name.clone(), ps, ty, term),
4374                None => self.record_definition(name.clone(), ty, term),
4375            }
4376            crate::equations::generate(self, &name);
4377        }
4378        if !names.is_empty() {
4379            Arc::make_mut(&mut self.derived_aux).insert(ind.to_string(), names);
4380        }
4381    }
4382
4383    /// Validate the constructor telescope before any registration. Positivity alone
4384    /// cannot establish that the result is the declared inductive, or even a type.
4385    fn check_constructor_signature(
4386        &self,
4387        name: &str,
4388        inductive: &str,
4389        ty: &Term,
4390        block: &[&str],
4391    ) -> crate::error::KernelResult<()> {
4392        use crate::error::KernelError;
4393        use crate::type_checker::{def_eq, infer_sort, substitute};
4394        let bad = |why: &str| {
4395            KernelError::InvalidDeclaration(format!("constructor '{name}' of '{inductive}': {why}"))
4396        };
4397        infer_sort(self, ty)?;
4398        let normalize = |ctx: &Context, term: &Term| {
4399            crate::reduction::normalize_checked(ctx, term)
4400                .map_err(|e| KernelError::CertificationError(format!(
4401                    "constructor '{name}' of '{inductive}': signature normalization did not finish: {e:?}"
4402                )))
4403        };
4404        // A failed bounded conversion attempt is not by itself a semantic
4405        // counterexample. Require completed normal forms before rejecting a
4406        // mismatch; exhaustion remains an inconclusive certification error.
4407        let equal =
4408            |ctx: &Context, left: &Term, right: &Term| -> crate::error::KernelResult<bool> {
4409                if def_eq(ctx, left, right) {
4410                    return Ok(true);
4411                }
4412                let left = normalize(ctx, left)?;
4413                let right = normalize(ctx, right)?;
4414                Ok(def_eq(ctx, &left, &right))
4415            };
4416        let mut expected = normalize(
4417            self,
4418            self.get_global(inductive)
4419                .ok_or_else(|| bad("parent is not declared"))?,
4420        )?;
4421        let target_universe =
4422            crate::type_checker::constructor_target_universe(inductive, &expected)?;
4423        let mut cur = ty.clone();
4424        let mut ext = self.clone();
4425        let nparams = self.inductive_num_params(inductive);
4426        let mut parameters = Vec::new();
4427        let mut i = 0;
4428        loop {
4429            if !matches!(cur, Term::Pi { .. }) {
4430                cur = normalize(&ext, &cur)?;
4431            }
4432            let Term::Pi {
4433                param,
4434                param_type,
4435                body_type,
4436            } = cur
4437            else {
4438                break;
4439            };
4440            let mut fresh = format!("__constructor_local_{i}");
4441            while ext.get(&fresh).is_some() {
4442                fresh.push('_');
4443            }
4444            let variable = Term::Var(fresh.clone());
4445            if i < nparams {
4446                let Term::Pi {
4447                    param: p,
4448                    param_type: pty,
4449                    body_type: pbody,
4450                } = expected
4451                else {
4452                    return Err(bad("more parameters than the parent telescope"));
4453                };
4454                if !equal(&ext, &param_type, &pty)? {
4455                    return Err(bad("parameter domain differs from the parent telescope"));
4456                }
4457                expected = substitute(&pbody, &p, &variable);
4458                parameters.push(variable.clone());
4459            }
4460            if i >= nparams {
4461                // Signature validation already exposes each telescope tail and
4462                // freshens its binders. Check precisely that same stored field.
4463                crate::type_checker::check_constructor_field_universe(
4464                    &ext,
4465                    inductive,
4466                    name,
4467                    &param_type,
4468                    &target_universe,
4469                )?;
4470            }
4471            if i >= nparams && nparams != 0 {
4472                // Uniformity is a property of the field up to conversion. In
4473                // particular (lambda f. f p) I contains a partial I syntactically
4474                // but its checked normal form is the complete occurrence I p.
4475                let field = normalize(&ext, &param_type)?;
4476                Self::check_recursive_parameter_occurrences(
4477                    &ext,
4478                    name,
4479                    block,
4480                    &parameters,
4481                    field,
4482                    &equal,
4483                )?;
4484            }
4485            ext = ext.extend(&fresh, *param_type);
4486            cur = substitute(&body_type, &param, &variable);
4487            i += 1;
4488        }
4489        if parameters.len() != nparams {
4490            return Err(bad("constructor omits uniform parameters"));
4491        }
4492        let result = normalize(&ext, &cur)?;
4493        let mut head = &result;
4494        let mut args = Vec::new();
4495        while let Term::App(f, a) = head {
4496            args.push(a.as_ref());
4497            head = f;
4498        }
4499        args.reverse();
4500        if !matches!(head, Term::Global(n) | Term::Const { name: n, .. } if n == inductive) {
4501            return Err(bad("result is not the declared inductive"));
4502        }
4503        if args.len() != self.inductive_arity(inductive) {
4504            return Err(bad("result does not fully apply the parent telescope"));
4505        }
4506        for (arg, parameter) in args.iter().zip(&parameters) {
4507            if !equal(&ext, arg, parameter)? {
4508                return Err(bad("result changes a uniform parameter"));
4509            }
4510        }
4511        Ok(())
4512    }
4513
4514    /// Check complete recursive spines inside an already type-checked, normalized
4515    /// constructor field. Ownership makes this walk iterative without cloning
4516    /// every subtree; contexts retain each nested binder's lexical identity.
4517    fn check_recursive_parameter_occurrences(
4518        ctx: &Context,
4519        constructor: &str,
4520        block: &[&str],
4521        parameters: &[Term],
4522        field: Term,
4523        equal: &impl Fn(&Context, &Term, &Term) -> crate::error::KernelResult<bool>,
4524    ) -> crate::error::KernelResult<()> {
4525        use crate::error::KernelError;
4526        use crate::type_checker::{infer_type, substitute};
4527        let invalid = |why: &str| {
4528            KernelError::InvalidDeclaration(format!(
4529                "constructor '{constructor}': recursive occurrence {why}"
4530            ))
4531        };
4532        let fresh = |ctx: &Context| {
4533            let mut name = "__recursive_parameter_local".to_string();
4534            while ctx.get(&name).is_some() {
4535                name.push('_');
4536            }
4537            name
4538        };
4539        let mut pending = vec![(field, ctx.clone())];
4540        while let Some((term, scope)) = pending.pop() {
4541            let mut head = term;
4542            let mut arguments = Vec::new();
4543            while let Term::App(function, argument) = head {
4544                arguments.push(*argument);
4545                head = *function;
4546            }
4547            arguments.reverse();
4548            if matches!(&head, Term::Global(n) | Term::Const{name:n,..} if block.contains(&n.as_str()))
4549            {
4550                if arguments.len() < parameters.len() {
4551                    return Err(invalid("omits a uniform parameter"));
4552                }
4553                for (argument, expected) in arguments.iter().zip(parameters) {
4554                    if !equal(&scope, argument, expected)? {
4555                        return Err(invalid("changes a uniform parameter"));
4556                    }
4557                }
4558                // Do not revisit the function-side partial spines. Arguments can
4559                // themselves contain a different complete recursive occurrence.
4560                pending.extend(arguments.into_iter().map(|a| (a, scope.clone())));
4561                continue;
4562            }
4563            pending.extend(arguments.into_iter().map(|a| (a, scope.clone())));
4564            match head {
4565                Term::Pi {
4566                    param,
4567                    param_type,
4568                    body_type,
4569                }
4570                | Term::Lambda {
4571                    param,
4572                    param_type,
4573                    body: body_type,
4574                } => {
4575                    let name = fresh(&scope);
4576                    let variable = Term::Var(name.clone());
4577                    let body = substitute(&body_type, &param, &variable);
4578                    let inside = scope.extend(&name, (*param_type).clone());
4579                    pending.push((*param_type, scope));
4580                    pending.push((body, inside));
4581                }
4582                Term::Let {
4583                    name,
4584                    ty,
4585                    value,
4586                    body,
4587                } => {
4588                    // A checked normal form ordinarily has no lets. Preserve
4589                    // lexical substitution if normalization retained one.
4590                    let body = substitute(&body, &name, &value);
4591                    pending.push((*ty, scope.clone()));
4592                    pending.push((*value, scope.clone()));
4593                    pending.push((body, scope));
4594                }
4595                Term::Match {
4596                    discriminant,
4597                    motive,
4598                    cases,
4599                } => {
4600                    pending.push((*discriminant, scope.clone()));
4601                    pending.push((*motive, scope.clone()));
4602                    pending.extend(cases.into_iter().map(|case| (case, scope.clone())));
4603                }
4604                Term::Fix { name, body } => {
4605                    let ty = infer_type(
4606                        &scope,
4607                        &Term::Fix {
4608                            name: name.clone(),
4609                            body: body.clone(),
4610                        },
4611                    )?;
4612                    let new = fresh(&scope);
4613                    let body = substitute(&body, &name, &Term::Var(new.clone()));
4614                    pending.push((body, scope.extend(&new, ty)));
4615                }
4616                Term::MutualFix { defs, index: _ } => {
4617                    let mut inside = scope.clone();
4618                    let mut substitutions = Vec::new();
4619                    for (index, (name, _)) in defs.iter().enumerate() {
4620                        let ty = infer_type(
4621                            &scope,
4622                            &Term::MutualFix {
4623                                defs: defs.clone(),
4624                                index,
4625                            },
4626                        )?;
4627                        let mut new = fresh(&inside);
4628                        while defs.iter().any(|(bound, _)| bound == &new) {
4629                            new.push('_');
4630                            while inside.get(&new).is_some() {
4631                                new.push('_');
4632                            }
4633                        }
4634                        inside = inside.extend(&new, ty);
4635                        substitutions.push((name.clone(), Term::Var(new)));
4636                    }
4637                    for (_, mut body) in defs {
4638                        for (name, value) in &substitutions {
4639                            body = substitute(&body, name, value);
4640                        }
4641                        pending.push((body, inside.clone()));
4642                    }
4643                }
4644                Term::Var(_)
4645                | Term::Global(_)
4646                | Term::Const { .. }
4647                | Term::Sort(_)
4648                | Term::Lit(_)
4649                | Term::Hole => {}
4650                Term::Annotated { term, .. } => pending.push((*term, scope)),
4651                Term::App(..) => unreachable!("application spine peeled above"),
4652            }
4653        }
4654        Ok(())
4655    }
4656
4657    pub fn add_constructor_checked(
4658        &mut self,
4659        name: &str,
4660        inductive: &str,
4661        ty: Term,
4662    ) -> crate::error::KernelResult<()> {
4663        self.check_native_dependency_mutation(name)?;
4664        self.check_native_dependency_mutation(inductive)?;
4665        let ty = self.stored_term(ty);
4666        // The inductive must EXIST, and this has to be the first question asked. Every gate below
4667        // treats an unknown head as inert — `check_constructor_universes` returns `Ok(())` when
4668        // `get_global` misses, and `check_positivity` sees no occurrence to be negative — so the
4669        // CHECKED path used to admit a constructor for a type that does not exist. A
4670        // universe-polymorphic definition of the same name is the live route: `Const{BoxP, [u]}`
4671        // resolves, `Global("BoxP")` does not, and a `BoxP_mk` whose own type will not even infer
4672        // landed anyway.
4673        if !self.is_inductive(inductive) {
4674            return Err(crate::error::KernelError::CertificationError(format!(
4675                "constructor '{name}' names '{inductive}', which is not a registered inductive — \
4676                 declare the inductive first (a definition or a universe-polymorphic abbreviation \
4677                 of that name is not an inductive and has no constructors)"
4678            )));
4679        }
4680        // The stable-meaning gates, asked before any work so a refusal is RETURNED: the bulk
4681        // door below can only record one.
4682        if self.admit_constructor(name, inductive, &ty)? == Admission::Keep {
4683            return Ok(());
4684        }
4685        // Evaluate original typing before bounded head conversion, retaining
4686        // the established proven-negative diagnostic when both gates fail.
4687        // A positive shape never waives an ill-typed erased beta argument.
4688        let source_typing = crate::type_checker::infer_sort(self, &ty);
4689        let block: Vec<&str> = self
4690            .mutual_block_of(inductive)
4691            .map(|members| members.iter().map(String::as_str).collect())
4692            .unwrap_or_else(|| vec![inductive]);
4693        let dependencies =
4694            crate::positivity::native_positivity_dependencies(self, &block, name, &ty)?;
4695        source_typing?;
4696        self.check_native_dependencies(&dependencies)?;
4697        // Infer the final parameter/index split with the candidate included, without
4698        // making the candidate available to its own type checker. The first constructor
4699        // can establish that an arity argument is an index rather than a parameter.
4700        let mut validation = self.clone();
4701        if self.inductive_declared_params(inductive).is_none() {
4702            let mut prospective = self.clone();
4703            prospective.auto_aux = false;
4704            prospective.add_constructor(name, inductive, ty.clone());
4705            let params = prospective.inductive_num_params(inductive);
4706            validation.set_inductive_params(inductive, params);
4707            if params != self.inductive_num_params(inductive) {
4708                // Previously uniform parameters become stored fields when the split
4709                // shrinks. Recheck their universe bounds before committing the change.
4710                for (old_name, old_ty) in self.get_constructors(inductive) {
4711                    validation.check_constructor_signature(old_name, inductive, old_ty, &block)?;
4712                }
4713            }
4714        }
4715        validation.check_constructor_signature(name, inductive, &ty, &block)?;
4716
4717        // If it passes, add the constructor normally
4718        self.add_constructor(name, inductive, ty);
4719        // DECLARATION-TIME SYNTHESIS on the CHECKED door — Lean's behaviour, and T03-018.
4720        // `{I}_noConfusion`, `{I}_noConfusionType`, `{C}_inj`, `{I}_below`, `{I}_brecOn`,
4721        // `decEq{I}` exist the moment the declaration does, all derived and kernel-checked, none
4722        // of them an assumption.
4723        //
4724        // The design tension that held this back is CLOSED: `recursor::push_aux` is
4725        // provenance-keyed (`Context::is_derived_aux`), so a re-derivation replaces ITS OWN prior
4726        // generation and still refuses to touch a hand-written constant — which is why the
4727        // prelude's `decEqNat` survives byte-identical while a two-constructor user inductive gets
4728        // a regenerated eliminator.
4729        //
4730        // It fires once per CONSTRUCTOR because there is no "declaration finished" call; the
4731        // auxiliaries derived after the first constructor describe an inductive that is not
4732        // finished yet, and the last generation is the one that stands. Only the CHECKED door is
4733        // eager: `add_constructor` is the bulk door a library loader and a translator use, and it
4734        // keeps the `auto_aux` switch and the `seal` batch so registering a standard library does
4735        // not pay per constructor for tables nothing will ask for.
4736        self.regenerate_auxiliaries(inductive);
4737        self.seal_native_dependencies(dependencies);
4738        Ok(())
4739    }
4740
4741    /// Register a MUTUAL block of inductives whose constructors may reference one
4742    /// another (`Even`/`Odd`, `Tree`/`Forest`). Strict positivity is checked over the
4743    /// WHOLE block up front — a sibling occurrence is a recursive occurrence, a
4744    /// sibling in a negative position is a cross-block paradox and rejected — and the
4745    /// registration is TRANSACTIONAL: if any constructor violates positivity, nothing
4746    /// is added. On success every member's header (with its parameter split), every
4747    /// constructor, and the block-membership registry are populated, ready for the
4748    /// auto-derived mutual recursors.
4749    pub fn add_mutual_inductives(
4750        &mut self,
4751        block: &[MutualInductive],
4752    ) -> crate::error::KernelResult<()> {
4753        #[cfg(feature = "shadow")]
4754        let shadow_entry = crate::dag::mirror::shadow_enter(self);
4755        #[cfg(feature = "shadow")]
4756        let candidate = crate::dag::logos_env::candidate_block(self, None, block);
4757        let result = self.add_inductive_block(block, None);
4758        #[cfg(feature = "shadow")]
4759        crate::dag::mirror::shadow(self, &shadow_entry, result.as_ref().err(), || candidate);
4760        result
4761    }
4762
4763    fn add_inductive_block(
4764        &mut self,
4765        block: &[MutualInductive],
4766        levels: Option<&[String]>,
4767    ) -> crate::error::KernelResult<()> {
4768        if let Some(erased) = erased_block(block) {
4769            return self.add_inductive_block(&erased, levels);
4770        }
4771        for member in block {
4772            self.check_native_dependency_mutation(&member.name)?;
4773            for (name, _) in &member.constructors {
4774                self.check_native_dependency_mutation(name)?;
4775            }
4776        }
4777        let names: Vec<&str> = block.iter().map(|m| m.name.as_str()).collect();
4778        // A header must end in Sort. Merely having a type would also admit
4779        // `I : False`, which would register I itself as a proof of False.
4780        let mut header_env = self.clone();
4781        for member in block {
4782            header_env.displace(&member.name);
4783        }
4784        let mut checked_arities = Vec::with_capacity(block.len());
4785        for member in block {
4786            crate::type_checker::infer_sort(&header_env, &member.sort)?;
4787            let arity = exposed_arity(&header_env, &member.sort, &mut |ctx, t| {
4788                crate::reduction::normalize_checked(ctx, t)
4789            })
4790            .map_err(|e| {
4791                crate::error::KernelError::CertificationError(format!(
4792                    "inductive '{}' header did not normalize: {e:?}",
4793                    member.name
4794                ))
4795            })?;
4796            let mut result = &arity;
4797            while let Term::Pi { body_type, .. } = result {
4798                result = body_type;
4799            }
4800            if !matches!(result, Term::Sort(_)) {
4801                return Err(crate::error::KernelError::CertificationError(format!(
4802                    "inductive '{}' must have a parameter telescope ending in Sort",
4803                    member.name
4804                )));
4805            }
4806            checked_arities.push(arity);
4807        }
4808        // Reconcile precisely the checked, exposed telescopes that metadata and
4809        // auxiliary generation will use. No constructors are published yet.
4810        let counts: Vec<_> = block
4811            .iter()
4812            .zip(&checked_arities)
4813            .map(|(member, arity)| {
4814                (
4815                    member.name.as_str(),
4816                    member.num_params,
4817                    count_leading_pis(arity),
4818                )
4819            })
4820            .collect();
4821        reconcile_parameter_counts(&counts)?;
4822        // A block something already depends on keeps its meaning: registered again identically it
4823        // is left exactly as it is, and registered any other way it is refused.
4824        let identical = block.iter().zip(&checked_arities).all(|(member, arity)| {
4825            let current = self.get_constructors(&member.name);
4826            self.inductives
4827                .get(&member.name)
4828                .is_some_and(|current| same_meaning(current, arity))
4829                && self.inductive_num_params(&member.name) == member.num_params
4830                && levels.map_or(true, |levels| {
4831                    self.poly_types
4832                        .get(&member.name)
4833                        .is_some_and(|(declared, _)| declared.as_slice() == levels)
4834                })
4835                && current.len() == member.constructors.len()
4836                && current.iter().zip(&member.constructors).all(
4837                    |(&(name, ty), (wanted, wanted_ty))| {
4838                        name == wanted.as_str() && same_meaning(ty, wanted_ty)
4839                    },
4840                )
4841        });
4842        let mut relied_on = false;
4843        for member in block {
4844            relied_on |=
4845                self.admit_meaning(&member.name, Self::change_if(identical))? == Admission::Keep;
4846            for (constructor, _) in &member.constructors {
4847                relied_on |=
4848                    self.admit_meaning(constructor, Self::change_if(identical))? == Admission::Keep;
4849            }
4850        }
4851        if relied_on {
4852            return Ok(());
4853        }
4854        let mut temp = self.clone();
4855        for (member, arity) in block.iter().zip(&checked_arities) {
4856            match levels {
4857                Some(levels) => temp.add_universe_poly_inductive(
4858                    &member.name,
4859                    levels.to_vec(),
4860                    arity.clone(),
4861                    member.num_params,
4862                ),
4863                None => temp.add_indexed_inductive(&member.name, arity.clone(), member.num_params),
4864            }
4865        }
4866        let mut dependencies = std::collections::HashSet::new();
4867        // 1. Positivity of every constructor against the whole block, BEFORE mutating.
4868        for member in block {
4869            for (cname, cty) in &member.constructors {
4870                let source_typing = crate::type_checker::infer_sort(&temp, cty);
4871                dependencies.extend(crate::positivity::native_positivity_dependencies(
4872                    &temp, &names, cname, cty,
4873                )?);
4874                source_typing?;
4875            }
4876        }
4877        self.check_native_dependencies(&dependencies)?;
4878        // 1b. UNIVERSE CONSISTENCY of every constructor — checked in a TEMP env carrying the
4879        // block's headers (so a recursive/sibling field resolves), before mutating `self`,
4880        // keeping the whole registration transactional.
4881        {
4882            for member in block {
4883                for (cname, cty) in &member.constructors {
4884                    if let Some(levels) = levels {
4885                        let normalized = crate::normalize_checked(&temp, cty).map_err(|e| {
4886                            crate::error::KernelError::CertificationError(format!(
4887                                "constructor '{cname}' normalization unfinished: {e:?}"
4888                            ))
4889                        })?;
4890                        Self::check_block_level_instances(&normalized, &names, levels)?;
4891                    }
4892                    temp.check_constructor_signature(cname, &member.name, cty, &names)?;
4893                }
4894            }
4895        }
4896        // 2. Publish the same exposed headers used by every preceding gate.
4897        for (member, arity) in block.iter().zip(checked_arities) {
4898            match levels {
4899                Some(levels) => self.add_universe_poly_inductive(
4900                    &member.name,
4901                    levels.to_vec(),
4902                    arity,
4903                    member.num_params,
4904                ),
4905                None => self.add_indexed_inductive(&member.name, arity, member.num_params),
4906            }
4907        }
4908        // 3. Record block membership — BEFORE the constructors, because registering a
4909        // constructor now synthesises the member's auxiliaries, and a member that does not yet
4910        // know it is in a block would get a STANDALONE recursor: one that reads a sibling
4911        // occurrence as an ordinary non-recursive field. Membership first means every derivation
4912        // sees the real block.
4913        if block.len() > 1 {
4914            let members: Vec<String> = block.iter().map(|m| m.name.clone()).collect();
4915            let reg = Arc::make_mut(&mut self.mutual_blocks);
4916            for member in block {
4917                reg.insert(member.name.clone(), members.clone());
4918            }
4919        }
4920        // 4. All constructors.
4921        for member in block {
4922            for (cname, cty) in &member.constructors {
4923                self.add_constructor(cname, &member.name, cty.clone());
4924            }
4925        }
4926        // 5. One final regeneration per member, now that EVERY member's constructors are in. A
4927        // mutual recursor is stated over the whole block, so the generations produced while the
4928        // block was half-registered describe a smaller block than the one that now exists.
4929        if block.len() > 1 {
4930            for member in block {
4931                let name = member.name.clone();
4932                self.regenerate_auxiliaries(&name);
4933            }
4934        }
4935        self.seal_native_dependencies(dependencies);
4936        Ok(())
4937    }
4938
4939    /// Register a checked inductive block with one shared universe telescope.
4940    pub fn add_universe_poly_inductives(
4941        &mut self,
4942        levels: &[String],
4943        block: &[MutualInductive],
4944    ) -> crate::error::KernelResult<()> {
4945        #[cfg(feature = "shadow")]
4946        let shadow_entry = crate::dag::mirror::shadow_enter(self);
4947        #[cfg(feature = "shadow")]
4948        let candidate = crate::dag::logos_env::candidate_block(self, Some(levels), block);
4949        let result = self.add_universe_poly_inductives_checked(levels, block);
4950        #[cfg(feature = "shadow")]
4951        crate::dag::mirror::shadow(self, &shadow_entry, result.as_ref().err(), || candidate);
4952        result
4953    }
4954
4955    fn add_universe_poly_inductives_checked(
4956        &mut self,
4957        levels: &[String],
4958        block: &[MutualInductive],
4959    ) -> crate::error::KernelResult<()> {
4960        if let Some(erased) = erased_block(block) {
4961            return self.add_universe_poly_inductives_checked(levels, &erased);
4962        }
4963        let mut names = std::collections::HashSet::new();
4964        for member in block {
4965            Self::check_level_telescope("inductive", &member.name, levels, [&member.sort])?;
4966            for (name, ty) in std::iter::once((&member.name, &member.sort))
4967                .chain(member.constructors.iter().map(|(n, t)| (n, t)))
4968            {
4969                if !names.insert(name) {
4970                    return Err(crate::error::KernelError::CertificationError(format!(
4971                        "duplicate declaration '{name}' in polymorphic inductive block"
4972                    )));
4973                }
4974                Self::check_level_telescope("inductive block member", name, levels, [ty])?;
4975            }
4976        }
4977        self.add_inductive_block(block, Some(levels))
4978    }
4979
4980    fn check_block_level_instances(
4981        term: &Term,
4982        block: &[&str],
4983        parameters: &[String],
4984    ) -> crate::error::KernelResult<()> {
4985        let mut pending = vec![term];
4986        while let Some(term) = pending.pop() {
4987            match term {
4988                Term::Global(name) if block.contains(&name.as_str()) && !parameters.is_empty() => {
4989                    return Err(crate::error::KernelError::InvalidDeclaration(format!(
4990                        "recursive reference '{name}' omits the block's universe arguments"
4991                    )))
4992                }
4993                Term::Const { name, levels } if block.contains(&name.as_str()) => {
4994                    if levels.len() != parameters.len()
4995                        || levels.iter().zip(parameters).any(|(level, parameter)| {
4996                            !level.equiv(&Universe::Var(parameter.clone()))
4997                        })
4998                    {
4999                        return Err(crate::error::KernelError::InvalidDeclaration(format!(
5000                            "recursive reference '{name}' changes the block's universe arguments"
5001                        )));
5002                    }
5003                }
5004                Term::Pi {
5005                    param_type,
5006                    body_type,
5007                    ..
5008                } => {
5009                    pending.push(param_type);
5010                    pending.push(body_type);
5011                }
5012                Term::Lambda {
5013                    param_type, body, ..
5014                } => {
5015                    pending.push(param_type);
5016                    pending.push(body);
5017                }
5018                Term::App(f, a) => {
5019                    pending.push(f);
5020                    pending.push(a);
5021                }
5022                Term::Match {
5023                    discriminant,
5024                    motive,
5025                    cases,
5026                } => {
5027                    pending.push(discriminant);
5028                    pending.push(motive);
5029                    pending.extend(cases);
5030                }
5031                Term::Fix { body, .. } => pending.push(body),
5032                Term::MutualFix { defs, .. } => pending.extend(defs.iter().map(|(_, b)| b)),
5033                Term::Let {
5034                    ty, value, body, ..
5035                } => {
5036                    pending.push(ty);
5037                    pending.push(value);
5038                    pending.push(body);
5039                }
5040                _ => {}
5041            }
5042        }
5043        Ok(())
5044    }
5045
5046    /// A non-indexed, fieldless singleton at any universe. Recursive and indexed
5047    /// single-constructor families do not have the unit eta rule.
5048    pub fn unit_constructor(&self, inductive: &str) -> Option<&str> {
5049        if !self.is_inductive(inductive)
5050            || self
5051                .mutual_block_of(inductive)
5052                .is_some_and(|b| b.len() != 1)
5053        {
5054            return None;
5055        }
5056        let parameters = self.inductive_num_params(inductive);
5057        let mut arity = self.get_global(inductive)?;
5058        let mut count = 0;
5059        while let Term::Pi { body_type, .. } = arity {
5060            count += 1;
5061            arity = body_type;
5062        }
5063        if count != parameters || !matches!(arity, Term::Sort(_)) {
5064            return None;
5065        }
5066        let constructors = self.get_constructors(inductive);
5067        if constructors.len() != 1 {
5068            return None;
5069        }
5070        let mut ty = constructors[0].1;
5071        let mut count = 0;
5072        while let Term::Pi { body_type, .. } = ty {
5073            count += 1;
5074            ty = body_type;
5075        }
5076        (count == parameters).then_some(constructors[0].0)
5077    }
5078
5079    /// The unique constructor of a K-like proposition: no stored fields beyond
5080    /// the uniform parameters. Its indices still need conversion at each use.
5081    pub fn k_constructor(&self, inductive: &str) -> Option<&str> {
5082        if !self.is_inductive(inductive) {
5083            return None;
5084        }
5085        if self
5086            .mutual_block_of(inductive)
5087            .is_some_and(|block| block.len() != 1)
5088        {
5089            return None;
5090        }
5091        let mut result = self.get_global(inductive)?;
5092        while let Term::Pi { body_type, .. } = result {
5093            result = body_type;
5094        }
5095        if !matches!(result, Term::Sort(level) if *level != Universe::SProp && level.equiv(&Universe::Prop))
5096        {
5097            return None;
5098        }
5099        let ctors = self.get_constructors(inductive);
5100        if ctors.len() != 1 {
5101            return None;
5102        }
5103        let mut ty = ctors[0].1;
5104        let mut count = 0;
5105        while let Term::Pi { body_type, .. } = ty {
5106            count += 1;
5107            ty = body_type;
5108        }
5109        (count == self.inductive_num_params(inductive)).then_some(ctors[0].0)
5110    }
5111
5112    /// The mutual block `name` belongs to (the full ordered member list), or `None`
5113    /// if `name` is a standalone inductive. Used by the recursor derivation to give
5114    /// every block member a motive and route sibling recursion.
5115    pub fn mutual_block_of(&self, name: &str) -> Option<&[String]> {
5116        self.mutual_blocks.get(name).map(|v| v.as_slice())
5117    }
5118
5119    /// Register a NESTED inductive (`RTree := rnode : TList RTree → RTree`) by compiling
5120    /// it — via the UNTRUSTED [`inductive_compile`](crate::inductive_compile) front-end —
5121    /// to a mutual block plus conversion isos, then registering the block and CHECKING
5122    /// every iso through the trusted kernel. A mis-compiled sibling is caught by mutual
5123    /// positivity; a mis-typed iso is caught here (its inferred type must match its
5124    /// declared conversion type). Soundness rests entirely on those trusted checks — the
5125    /// compiler adds no trusted code, exactly as Lean lowers nested inductives to mutual.
5126    pub fn add_nested_inductive(
5127        &mut self,
5128        decl: &crate::inductive_compile::NestedDecl,
5129    ) -> crate::error::KernelResult<crate::inductive_compile::NestedInfo> {
5130        if !crate::annotation::within_erased_call()
5131            && std::iter::once(&decl.sort)
5132                .chain(decl.constructors.iter().map(|(_, t)| t))
5133                .any(Term::has_annotations)
5134        {
5135            return self.add_nested_inductive(&crate::inductive_compile::NestedDecl {
5136                name: decl.name.clone(),
5137                sort: decl.sort.strip_annotations(),
5138                constructors: decl
5139                    .constructors
5140                    .iter()
5141                    .map(|(name, ty)| (name.clone(), ty.strip_annotations()))
5142                    .collect(),
5143            });
5144        }
5145        let compiled = crate::inductive_compile::compile_nested(self, decl)?;
5146
5147        // TRANSACTIONAL: build the whole declaration on a SCRATCH context and commit only once
5148        // every part of it has checked — the same shape `add_mutual_inductives` already uses.
5149        //
5150        // Registering the block first and checking the isos afterwards meant an iso failure
5151        // returned an error with the block and its siblings ALREADY in the context: a caller that
5152        // handles the error and carries on is then reasoning in an environment holding half a
5153        // declaration — the inductives present, the conversions missing. `compile_nested` refuses
5154        // eight shapes fail-closed and each promises nothing is registered; this is the one path
5155        // that could break that promise.
5156        let mut scratch = self.clone();
5157
5158        // The mutual block is checked by the trusted mutual machinery (block positivity).
5159        scratch.add_mutual_inductives(&compiled.block)?;
5160        // Each iso is KERNEL-CHECKED before it is trusted: infer its type and require it
5161        // be the declared conversion type. A wrong iso is rejected here.
5162        for (name, ty, body) in &compiled.isos {
5163            let inferred = crate::infer_type(&scratch, body)?;
5164            if !crate::is_subtype(&scratch, &inferred, ty)
5165                || !crate::is_subtype(&scratch, ty, &inferred)
5166            {
5167                return Err(crate::error::KernelError::CertificationError(format!(
5168                    "nested-compile: iso '{name}' inferred type {inferred} ≠ declared {ty}"
5169                )));
5170            }
5171            scratch.add_definition(name.clone(), ty.clone(), body.clone());
5172        }
5173
5174        *self = scratch;
5175        Ok(crate::inductive_compile::NestedInfo {
5176            siblings: compiled.siblings,
5177            isos: compiled.iso_names,
5178        })
5179    }
5180
5181    /// Register a theorem as a hint for the auto tactic.
5182    ///
5183    /// Hints are theorems that auto will try to apply when decision
5184    /// procedures fail. This allows auto to "learn" from proven theorems.
5185    pub fn add_hint(&mut self, name: &str) {
5186        self.register_hint(name, 0);
5187    }
5188
5189    /// A `local` hint — reverted at [`Context::pop_scope`]. See [`Context::push_scope`].
5190    pub fn add_local_hint(&mut self, name: &str) {
5191        let owner = self.scope_depth;
5192        self.register_hint(name, owner);
5193    }
5194
5195    fn register_hint(&mut self, name: &str, owner: usize) {
5196        if !self.hints.contains(&name.to_string()) {
5197            Arc::make_mut(&mut self.hints).push(name.to_string());
5198            Arc::make_mut(&mut self.hint_scopes).push(owner);
5199            debug_assert_eq!(self.hints.len(), self.hint_scopes.len());
5200        }
5201        // A hint whose statement is an EQUATION is also a rewrite rule. `hints` is the one
5202        // extensible lemma database the surface can reach, so the `@[simp]` effect has to be
5203        // reachable through it as well as through the explicit [`Context::add_simp_lemma`] door;
5204        // a hint that is not an equation contributes nothing here and stays an `auto` hint alone.
5205        let _ = self.register_simp(name, owner);
5206    }
5207
5208    /// Get all registered hints.
5209    ///
5210    /// Returns the names of theorems registered as hints.
5211    pub fn get_hints(&self) -> &[String] {
5212        &self.hints
5213    }
5214
5215    /// Check if a theorem is registered as a hint.
5216    pub fn is_hint(&self, name: &str) -> bool {
5217        self.hints.contains(&name.to_string())
5218    }
5219
5220    // ==========================================================================================
5221    // THE REDUCIBILITY AXIS — `@[reducible]` / `@[irreducible]`, and the door δ asks
5222    // ==========================================================================================
5223
5224    /// Declare `name`'s REDUCIBILITY — Lean's `@[reducible]` / `@[irreducible]`.
5225    ///
5226    /// The axis is a property of the DECLARATION, not of the reducer, which is why it lives here:
5227    /// `Transparency::Excluding` takes a predicate, and without a registry every caller had to
5228    /// invent its own — so two of them would eventually disagree about whether a constant unfolds,
5229    /// and `def_eq` would answer differently depending on which one asked.
5230    ///
5231    /// The kernel itself still unfolds everything (`normalize` is `Transparency::All`), exactly as
5232    /// Lean's kernel ignores `@[irreducible]`: the attribute constrains the ELABORATOR, and making
5233    /// it constrain the kernel would let an attribute change what is TRUE.
5234    pub fn set_reducibility(&mut self, name: &str, r: Reducibility) {
5235        let owner = self.scope_depth;
5236        let previous = self.reducibility.get(name).copied();
5237        if owner > 0 {
5238            Arc::make_mut(&mut self.reducibility_undo).push((owner, name.to_string(), previous));
5239        }
5240        if r == Reducibility::Semireducible {
5241            Arc::make_mut(&mut self.reducibility).remove(name);
5242        } else {
5243            Arc::make_mut(&mut self.reducibility).insert(name.to_string(), r);
5244        }
5245    }
5246
5247    /// `name`'s declared reducibility (the default when nothing was declared).
5248    pub fn reducibility(&self, name: &str) -> Reducibility {
5249        self.reducibility.get(name).copied().unwrap_or_default()
5250    }
5251
5252    /// Whether `name` is `@[irreducible]` — THE PREDICATE `Transparency::Excluding` wants.
5253    ///
5254    /// One lookup in one map, so a reducer may ask it once per δ-candidate without the question
5255    /// costing more than the unfolding would have.
5256    pub fn is_irreducible(&self, name: &str) -> bool {
5257        matches!(self.reducibility.get(name), Some(Reducibility::Irreducible))
5258    }
5259
5260    /// Conservative eligibility for using full-transparency conversion as an
5261    /// elaborator observation. A large attribute registry merely skips the
5262    /// optimization; no declaration or normalizer policy changes.
5263    pub(crate) fn elaborator_all_transparent(&self) -> bool {
5264        self.reducibility.len() <= 4096
5265            && self
5266                .reducibility
5267                .values()
5268                .all(|r| *r != Reducibility::Irreducible)
5269    }
5270
5271    /// Undo the reducibility edits made inside the scope now closing.
5272    fn revert_reducibility(&mut self, closing: usize) {
5273        if !self.reducibility_undo.iter().any(|(d, _, _)| *d == closing) {
5274            return;
5275        }
5276        let undo = Arc::make_mut(&mut self.reducibility_undo);
5277        let mut restore: Vec<(String, Option<Reducibility>)> = Vec::new();
5278        while let Some((d, _, _)) = undo.last() {
5279            if *d != closing {
5280                break;
5281            }
5282            let (_, name, previous) = undo.pop().expect("just peeked");
5283            restore.push((name, previous));
5284        }
5285        let map = Arc::make_mut(&mut self.reducibility);
5286        for (name, previous) in restore {
5287            match previous {
5288                Some(r) => {
5289                    map.insert(name, r);
5290                }
5291                None => {
5292                    map.remove(&name);
5293                }
5294            }
5295        }
5296    }
5297
5298    // ==========================================================================================
5299    // THE SIMP-LEMMA REGISTRY — `@[simp]`, and the ONE door a simplifier consults
5300    // ==========================================================================================
5301
5302    /// Register `name` as a `@[simp]` lemma — Lean's `@[simp] theorem`.
5303    ///
5304    /// The lemma's DECLARED STATEMENT is compiled, once, into the shape a rewriter applies:
5305    /// `Π(x̄). lhs = rhs` becomes the rule `lhs ⟶ rhs` under the binders `x̄`, keyed by `lhs`'s
5306    /// head symbol. Compiling at registration rather than at every rewrite attempt is the whole
5307    /// reason this is a registry and not a list of names — a name-list forces every consumer to
5308    /// re-open the telescope and re-destructure the `Eq` for every candidate at every subterm.
5309    ///
5310    /// REFUSED, with a reason rather than a silent no-op, because each of these is a rule that
5311    /// would make the simplifier wrong or non-terminating rather than merely weak:
5312    ///
5313    /// * a statement that is not an equation — there is nothing to rewrite WITH;
5314    /// * `x = rhs` with a bare bound variable on the left — it matches every term at every
5315    ///   position, so one such rule rewrites the whole universe;
5316    /// * `lhs = rhs` where `rhs` mentions a variable `lhs` does not bind — matching cannot
5317    ///   determine it, so the replacement would contain a free variable;
5318    /// * `lhs = lhs` — an identity rule that fires for ever without changing anything.
5319    ///
5320    /// Better than Lean here in one small way: Lean accepts a looping simp lemma and you find
5321    /// out when `simp` diverges. The last two shapes are refused at the door with the lemma named.
5322    pub fn add_simp_lemma(&mut self, name: &str) -> crate::error::KernelResult<()> {
5323        self.register_simp(name, 0)
5324    }
5325
5326    /// A `local`/`scoped` `@[simp]` lemma — reverted at [`Context::pop_scope`].
5327    pub fn add_local_simp_lemma(&mut self, name: &str) -> crate::error::KernelResult<()> {
5328        let owner = self.scope_depth;
5329        self.register_simp(name, owner)
5330    }
5331
5332    /// Compile `name`'s declared statement into a rewrite rule owned by scope `owner`.
5333    fn register_simp(&mut self, name: &str, owner: usize) -> crate::error::KernelResult<()> {
5334        if self.simp_rules.iter().any(|r| r.name == name) {
5335            return Ok(());
5336        }
5337        let stmt = self
5338            .get_global(name)
5339            .cloned()
5340            .ok_or_else(|| crate::error::KernelError::UnboundVariable(name.to_string()))?;
5341        let rule = SimpRule::compile(name, &stmt)?;
5342        let head = rule.head.clone();
5343        let index = self.simp_rules.len();
5344        Arc::make_mut(&mut self.simp_rules).push(rule);
5345        Arc::make_mut(&mut self.simp_scopes).push(owner);
5346        Arc::make_mut(&mut self.simp_by_head)
5347            .entry(head)
5348            .or_default()
5349            .push(index);
5350        debug_assert_eq!(self.simp_rules.len(), self.simp_scopes.len());
5351        Ok(())
5352    }
5353
5354    /// Every registered rewrite rule, in registration order.
5355    pub fn simp_rules(&self) -> &[SimpRule] {
5356        &self.simp_rules
5357    }
5358
5359    /// The rules whose left-hand side has head symbol `head` — THE DISPATCH DOOR.
5360    ///
5361    /// A rewriter walking a term asks this once per subterm and gets only the rules that can
5362    /// possibly match it. Never scan [`Context::simp_rules`] linearly from a hot path.
5363    pub fn simp_rules_for(&self, head: &str) -> impl Iterator<Item = &SimpRule> {
5364        self.simp_by_head
5365            .get(head)
5366            .map(|v| v.as_slice())
5367            .unwrap_or(&[])
5368            .iter()
5369            .map(move |i| &self.simp_rules[*i])
5370    }
5371
5372    /// Whether `name` is registered as a `@[simp]` lemma.
5373    pub fn is_simp_lemma(&self, name: &str) -> bool {
5374        self.simp_rules.iter().any(|r| r.name == name)
5375    }
5376
5377    /// Rebuild the head index after a scope close removed rules (indices shift).
5378    fn reindex_simp(&mut self) {
5379        let mut by_head: HashMap<String, Vec<usize>> = HashMap::new();
5380        for (i, r) in self.simp_rules.iter().enumerate() {
5381            by_head.entry(r.head.clone()).or_default().push(i);
5382        }
5383        self.simp_by_head = Arc::new(by_head);
5384    }
5385}
5386
5387/// Lean's REDUCIBILITY axis, declared per constant and read by the elaborator's δ step.
5388///
5389/// Three settings and not two, because `@[reducible]` is not merely "the default": instance
5390/// resolution unfolds a reducible definition and stops at a semireducible one, so collapsing the
5391/// two changes which instances are found.
5392#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
5393pub enum Reducibility {
5394    /// `@[reducible]` — an abbreviation, unfolded even where the elaborator is being careful.
5395    Reducible,
5396    /// The default: unfolded at ordinary transparency.
5397    #[default]
5398    Semireducible,
5399    /// `@[irreducible]` — the elaborator never unfolds it, and `secret = 5` is not `rfl`. The
5400    /// body is KEPT: this is opacity, not an axiom, and the difference is that a later
5401    /// `unfold`/`decide` can still reach the definition.
5402    Irreducible,
5403}
5404
5405/// A `@[simp]` lemma COMPILED to the form a rewriter applies: `∀x̄. lhs ⟶ rhs`.
5406///
5407/// The binders are the lemma's universally quantified variables in order; `lhs` and `rhs`
5408/// mention them as [`Term::Var`]. `head` is `lhs`'s head symbol and is the registry's dispatch
5409/// key — see [`Context::simp_rules_for`].
5410#[derive(Clone, Debug, PartialEq)]
5411pub struct SimpRule {
5412    /// The lemma's name, so a rewrite can say which lemma fired.
5413    pub name: String,
5414    /// Universally quantified variables, outermost first, with their types.
5415    pub binders: Vec<(String, Term)>,
5416    /// The pattern to match.
5417    pub lhs: Term,
5418    /// What to replace a match with.
5419    pub rhs: Term,
5420    /// `lhs`'s head symbol — the dispatch key.
5421    pub head: String,
5422}
5423
5424impl SimpRule {
5425    /// Compile a declared statement `Π(x̄). Eq A lhs rhs` into a rule, or say why it is not one.
5426    pub fn compile(name: &str, stmt: &Term) -> crate::error::KernelResult<SimpRule> {
5427        let mut binders: Vec<(String, Term)> = Vec::new();
5428        let mut cur = stmt;
5429        while let Term::Pi {
5430            param,
5431            param_type,
5432            body_type,
5433        } = cur
5434        {
5435            // A Π whose body does not mention the binder is an IMPLICATION, not a quantifier:
5436            // its premise would have to be discharged before the rule could fire, which is a
5437            // conditional rewrite and not this registry's shape.
5438            binders.push((param.clone(), (**param_type).clone()));
5439            cur = body_type;
5440        }
5441        let refuse = |why: String| {
5442            Err(crate::error::KernelError::CertificationError(format!(
5443                "`{name}` cannot be a simp lemma: {why}"
5444            )))
5445        };
5446        let (lhs, rhs) = match eq_sides(cur) {
5447            Some(pair) => pair,
5448            None => return refuse(format!("its statement is not an equation, it is `{cur}`")),
5449        };
5450        let head =
5451            match spine_head(&lhs) {
5452                Some(h) => h,
5453                None => return refuse(
5454                    "its left-hand side is a bare variable, so the rule would match every term \
5455                     at every position"
5456                        .to_string(),
5457                ),
5458            };
5459        if lhs == rhs {
5460            return refuse("it rewrites a term to itself, which never terminates".to_string());
5461        }
5462        let bound: Vec<&str> = binders.iter().map(|(n, _)| n.as_str()).collect();
5463        let (mut lhs_vars, mut rhs_vars) = (Vec::new(), Vec::new());
5464        free_vars_among(&lhs, &bound, &mut lhs_vars);
5465        free_vars_among(&rhs, &bound, &mut rhs_vars);
5466        if let Some(missing) = rhs_vars.iter().find(|v| !lhs_vars.contains(v)) {
5467            return refuse(format!(
5468                "its right-hand side mentions `{missing}`, which its left-hand side does not \
5469                 bind — matching could never determine it"
5470            ));
5471        }
5472        Ok(SimpRule {
5473            name: name.to_string(),
5474            binders,
5475            lhs,
5476            rhs,
5477            head,
5478        })
5479    }
5480
5481    /// Try to rewrite `term` with this rule AT THE TOP LEVEL — first-order matching of `lhs`
5482    /// against `term`, then `rhs` under the resulting substitution. `None` means the rule does
5483    /// not apply; the caller descends into subterms itself.
5484    ///
5485    /// This lives with the rule rather than with the rewriter for one reason: matching has to
5486    /// agree with what [`SimpRule::compile`] refused. A rewriter that wrote its own matcher could
5487    /// bind a pattern variable twice to two different terms, or substitute a variable the rule
5488    /// never bound — and both are silent wrong answers rather than failures.
5489    pub fn rewrite(&self, term: &Term) -> Option<Term> {
5490        let pattern_vars: Vec<&str> = self.binders.iter().map(|(n, _)| n.as_str()).collect();
5491        let mut subst: HashMap<String, Term> = HashMap::new();
5492        if !match_pattern(&self.lhs, term, &pattern_vars, &mut Vec::new(), &mut subst) {
5493            return None;
5494        }
5495        Some(substitute_vars(&self.rhs, &subst, &mut Vec::new()))
5496    }
5497
5498    /// The instance of the rule's variables, in binder order, that makes `lhs` read as `term` at
5499    /// the top level; `None` when the rule does not match there or leaves a variable undetermined.
5500    pub fn matching(&self, term: &Term) -> Option<Vec<Term>> {
5501        let pattern_vars: Vec<&str> = self.binders.iter().map(|(n, _)| n.as_str()).collect();
5502        let mut subst: HashMap<String, Term> = HashMap::new();
5503        if !match_pattern(&self.lhs, term, &pattern_vars, &mut Vec::new(), &mut subst) {
5504            return None;
5505        }
5506        self.binders
5507            .iter()
5508            .map(|(n, _)| subst.get(n).cloned())
5509            .collect()
5510    }
5511}
5512
5513/// First-order matching of `pattern` against `term`.
5514///
5515/// A [`Term::Var`] named in `vars` is a PATTERN VARIABLE and binds to whatever stands opposite
5516/// it — unless it is shadowed by a binder inside the pattern, in which case it is an ordinary
5517/// bound variable and must match literally. A variable that appears twice must bind to the SAME
5518/// term both times (`f x x = x` may not fire on `f a b`).
5519fn match_pattern(
5520    pattern: &Term,
5521    term: &Term,
5522    vars: &[&str],
5523    shadowed: &mut Vec<String>,
5524    subst: &mut HashMap<String, Term>,
5525) -> bool {
5526    if let Term::Var(n) = pattern {
5527        if vars.contains(&n.as_str()) && !shadowed.contains(n) {
5528            return match subst.get(n) {
5529                Some(bound) => bound == term,
5530                None => {
5531                    subst.insert(n.clone(), term.clone());
5532                    true
5533                }
5534            };
5535        }
5536    }
5537    match (pattern, term) {
5538        (Term::Var(a), Term::Var(b)) => a == b,
5539        (Term::Global(a), Term::Global(b)) => a == b,
5540        (Term::Sort(a), Term::Sort(b)) => a == b,
5541        (Term::Lit(a), Term::Lit(b)) => a == b,
5542        (Term::Hole, Term::Hole) => true,
5543        (
5544            Term::Const {
5545                name: a,
5546                levels: la,
5547            },
5548            Term::Const {
5549                name: b,
5550                levels: lb,
5551            },
5552        ) => a == b && la == lb,
5553        (Term::App(pf, pa), Term::App(tf, ta)) => {
5554            match_pattern(pf, tf, vars, shadowed, subst)
5555                && match_pattern(pa, ta, vars, shadowed, subst)
5556        }
5557        (
5558            Term::Pi {
5559                param: pp,
5560                param_type: pt,
5561                body_type: pb,
5562            },
5563            Term::Pi {
5564                param: tp,
5565                param_type: tt,
5566                body_type: tb,
5567            },
5568        ) => {
5569            pp == tp
5570                && match_pattern(pt, tt, vars, shadowed, subst)
5571                && match_under(pp, pb, tb, vars, shadowed, subst)
5572        }
5573        (
5574            Term::Lambda {
5575                param: pp,
5576                param_type: pt,
5577                body: pb,
5578            },
5579            Term::Lambda {
5580                param: tp,
5581                param_type: tt,
5582                body: tb,
5583            },
5584        ) => {
5585            pp == tp
5586                && match_pattern(pt, tt, vars, shadowed, subst)
5587                && match_under(pp, pb, tb, vars, shadowed, subst)
5588        }
5589        (Term::Fix { name: pn, body: pb }, Term::Fix { name: tn, body: tb }) => {
5590            pn == tn && match_under(pn, pb, tb, vars, shadowed, subst)
5591        }
5592        (
5593            Term::Match {
5594                discriminant: pd,
5595                motive: pm,
5596                cases: pc,
5597            },
5598            Term::Match {
5599                discriminant: td,
5600                motive: tm,
5601                cases: tc,
5602            },
5603        ) => {
5604            pc.len() == tc.len()
5605                && match_pattern(pd, td, vars, shadowed, subst)
5606                && match_pattern(pm, tm, vars, shadowed, subst)
5607                && pc
5608                    .iter()
5609                    .zip(tc.iter())
5610                    .all(|(a, b)| match_pattern(a, b, vars, shadowed, subst))
5611        }
5612        _ => false,
5613    }
5614}
5615
5616/// Match two bodies under a binder that SHADOWS `name` for the length of the descent.
5617fn match_under(
5618    name: &str,
5619    pattern: &Term,
5620    term: &Term,
5621    vars: &[&str],
5622    shadowed: &mut Vec<String>,
5623    subst: &mut HashMap<String, Term>,
5624) -> bool {
5625    shadowed.push(name.to_string());
5626    let ok = match_pattern(pattern, term, vars, shadowed, subst);
5627    shadowed.pop();
5628    ok
5629}
5630
5631/// Replace every free occurrence of a substituted variable in `t`. A binder of the same name
5632/// shadows the substitution for its body — without that, rewriting `f x` to `λx. x` inside a
5633/// term that already binds `x` would capture it.
5634fn substitute_vars(t: &Term, subst: &HashMap<String, Term>, shadowed: &mut Vec<String>) -> Term {
5635    match t {
5636        Term::Var(n) => match subst.get(n) {
5637            Some(v) if !shadowed.contains(n) => v.clone(),
5638            _ => t.clone(),
5639        },
5640        Term::Global(_) | Term::Sort(_) | Term::Lit(_) | Term::Hole | Term::Const { .. } => {
5641            t.clone()
5642        }
5643        Term::App(f, a) => Term::App(
5644            Box::new(substitute_vars(f, subst, shadowed)),
5645            Box::new(substitute_vars(a, subst, shadowed)),
5646        ),
5647        Term::Pi {
5648            param,
5649            param_type,
5650            body_type,
5651        } => {
5652            let param_type = Box::new(substitute_vars(param_type, subst, shadowed));
5653            shadowed.push(param.clone());
5654            let body_type = Box::new(substitute_vars(body_type, subst, shadowed));
5655            shadowed.pop();
5656            Term::Pi {
5657                param: param.clone(),
5658                param_type,
5659                body_type,
5660            }
5661        }
5662        Term::Lambda {
5663            param,
5664            param_type,
5665            body,
5666        } => {
5667            let param_type = Box::new(substitute_vars(param_type, subst, shadowed));
5668            shadowed.push(param.clone());
5669            let body = Box::new(substitute_vars(body, subst, shadowed));
5670            shadowed.pop();
5671            Term::Lambda {
5672                param: param.clone(),
5673                param_type,
5674                body,
5675            }
5676        }
5677        Term::Fix { name, body } => {
5678            shadowed.push(name.clone());
5679            let body = Box::new(substitute_vars(body, subst, shadowed));
5680            shadowed.pop();
5681            Term::Fix {
5682                name: name.clone(),
5683                body,
5684            }
5685        }
5686        Term::MutualFix { defs, index } => Term::MutualFix {
5687            defs: defs
5688                .iter()
5689                .map(|(n, b)| {
5690                    shadowed.push(n.clone());
5691                    let b = substitute_vars(b, subst, shadowed);
5692                    shadowed.pop();
5693                    (n.clone(), b)
5694                })
5695                .collect(),
5696            index: *index,
5697        },
5698        Term::Let {
5699            name,
5700            ty,
5701            value,
5702            body,
5703        } => {
5704            let ty = Box::new(substitute_vars(ty, subst, shadowed));
5705            let value = Box::new(substitute_vars(value, subst, shadowed));
5706            shadowed.push(name.clone());
5707            let body = Box::new(substitute_vars(body, subst, shadowed));
5708            shadowed.pop();
5709            Term::Let {
5710                name: name.clone(),
5711                ty,
5712                value,
5713                body,
5714            }
5715        }
5716        Term::Match {
5717            discriminant,
5718            motive,
5719            cases,
5720        } => Term::Match {
5721            discriminant: Box::new(substitute_vars(discriminant, subst, shadowed)),
5722            motive: Box::new(substitute_vars(motive, subst, shadowed)),
5723            cases: cases
5724                .iter()
5725                .map(|c| substitute_vars(c, subst, shadowed))
5726                .collect(),
5727        },
5728        Term::Annotated { annotation, term } => Term::Annotated {
5729            annotation: annotation.clone(),
5730            term: Box::new(substitute_vars(term, subst, shadowed)),
5731        },
5732    }
5733}
5734
5735/// The two sides of an `Eq A lhs rhs` application, if `t` is one.
5736fn eq_sides(t: &Term) -> Option<(Term, Term)> {
5737    let Term::App(f1, rhs) = t else { return None };
5738    let Term::App(f2, lhs) = f1.as_ref() else {
5739        return None;
5740    };
5741    let Term::App(f3, _carrier) = f2.as_ref() else {
5742        return None;
5743    };
5744    match f3.as_ref() {
5745        Term::Global(n) if n == "Eq" => Some(((**lhs).clone(), (**rhs).clone())),
5746        _ => None,
5747    }
5748}
5749
5750/// The head symbol of an application spine, if it is a global or a constant.
5751fn spine_head(t: &Term) -> Option<String> {
5752    let mut cur = t;
5753    while let Term::App(f, _) = cur {
5754        cur = f;
5755    }
5756    match cur {
5757        Term::Global(n) => Some(n.clone()),
5758        Term::Const { name, .. } => Some(name.clone()),
5759        _ => None,
5760    }
5761}
5762
5763/// Every GLOBAL-form name `t` mentions, in traversal order, duplicates included — BORROWED from
5764/// the term, so a body with a thousand occurrences costs a thousand pointer copies and not a
5765/// thousand heap allocations. Owning is the caller's decision, made once, after deduplication.
5766///
5767/// `Global` and `Const` both denote an environment constant and both make `t` depend on it, so
5768/// both count — the δ-graph is drawn over names, not over reference spellings. Binders are
5769/// irrelevant here on purpose: a binder can shadow a `Var`, never a `Global`.
5770/// Whether two stored terms carry the same meaning for the stable-meaning gate: identical up to
5771/// the names of bound variables. A redeclaration that only renames a binder changes nothing.
5772fn same_meaning(a: &Term, b: &Term) -> bool {
5773    a == b || crate::type_checker::alpha_equivalent(a, b)
5774}
5775
5776fn same_meaning_opt(a: Option<&Term>, b: Option<&Term>) -> bool {
5777    match (a, b) {
5778        (Some(a), Some(b)) => same_meaning(a, b),
5779        (None, None) => true,
5780        _ => false,
5781    }
5782}
5783
5784fn collect_global_mentions<'t>(t: &'t Term, acc: &mut Vec<&'t str>) {
5785    // ITERATIVE, with its own worklist. This runs on EVERY definition body that enters the
5786    // context, and a recursive walk would make the DEPTH of a term a limit on what may be
5787    // declared — a 20 000-rung δ-chain's last body is shallow, but a machine-generated proof term
5788    // is not, and aborting the process is not a refusal a caller can handle.
5789    let mut stack: Vec<&'t Term> = vec![t];
5790    while let Some(cur) = stack.pop() {
5791        match cur {
5792            Term::Global(n) => acc.push(n.as_str()),
5793            Term::Const { name, .. } => acc.push(name.as_str()),
5794            Term::Sort(_) | Term::Var(_) | Term::Lit(_) | Term::Hole => {}
5795            Term::App(f, a) => {
5796                stack.push(f);
5797                stack.push(a);
5798            }
5799            Term::Pi {
5800                param_type,
5801                body_type,
5802                ..
5803            } => {
5804                stack.push(param_type);
5805                stack.push(body_type);
5806            }
5807            Term::Lambda {
5808                param_type, body, ..
5809            } => {
5810                stack.push(param_type);
5811                stack.push(body);
5812            }
5813            Term::Let {
5814                ty, value, body, ..
5815            } => {
5816                stack.push(ty);
5817                stack.push(value);
5818                stack.push(body);
5819            }
5820            Term::Match {
5821                discriminant,
5822                motive,
5823                cases,
5824            } => {
5825                stack.push(discriminant);
5826                stack.push(motive);
5827                stack.extend(cases.iter());
5828            }
5829            Term::Fix { body, .. } => stack.push(body),
5830            Term::MutualFix { defs, .. } => stack.extend(defs.iter().map(|(_, b)| b)),
5831            Term::Annotated { term, .. } => stack.push(term),
5832        }
5833    }
5834}
5835
5836/// What a registered global's stored terms ELIMINATE: the head of the type each of its `match`es
5837/// discriminates — its motive's LAST λ-binder, the major premise after any indices — and whether
5838/// some `match` hides that behind a motive that is not a λ.
5839#[derive(Debug, Clone, Default)]
5840struct Eliminations {
5841    heads: Vec<String>,
5842    opaque: bool,
5843}
5844
5845/// Add what `t` eliminates to `acc`. Iterative, for the same reason as
5846/// [`collect_global_mentions`].
5847fn collect_eliminations(t: &Term, acc: &mut Eliminations) {
5848    let mut stack: Vec<&Term> = vec![t];
5849    while let Some(cur) = stack.pop() {
5850        match cur {
5851            Term::Sort(_)
5852            | Term::Var(_)
5853            | Term::Global(_)
5854            | Term::Const { .. }
5855            | Term::Lit(_)
5856            | Term::Hole => {}
5857            Term::App(f, a) => {
5858                stack.push(f);
5859                stack.push(a);
5860            }
5861            Term::Pi {
5862                param_type,
5863                body_type,
5864                ..
5865            } => {
5866                stack.push(param_type);
5867                stack.push(body_type);
5868            }
5869            Term::Lambda {
5870                param_type, body, ..
5871            } => {
5872                stack.push(param_type);
5873                stack.push(body);
5874            }
5875            Term::Let {
5876                ty, value, body, ..
5877            } => {
5878                stack.push(ty);
5879                stack.push(value);
5880                stack.push(body);
5881            }
5882            Term::Match {
5883                discriminant,
5884                motive,
5885                cases,
5886            } => {
5887                let mut major: Option<&Term> = None;
5888                let mut inner: &Term = motive;
5889                while let Term::Lambda {
5890                    param_type, body, ..
5891                } = inner
5892                {
5893                    major = Some(param_type);
5894                    inner = body;
5895                }
5896                match major {
5897                    None => acc.opaque = true,
5898                    Some(mut head) => {
5899                        while let Term::App(f, _) = head {
5900                            head = f;
5901                        }
5902                        match head {
5903                            Term::Global(name) | Term::Const { name, .. } => {
5904                                if !acc.heads.contains(name) {
5905                                    acc.heads.push(name.clone());
5906                                }
5907                            }
5908                            // A bound type variable is not an inductive a declaration can extend.
5909                            Term::Var(_) => {}
5910                            _ => acc.opaque = true,
5911                        }
5912                    }
5913                }
5914                stack.push(discriminant);
5915                stack.push(motive);
5916                stack.extend(cases.iter());
5917            }
5918            Term::Fix { body, .. } => stack.push(body),
5919            Term::MutualFix { defs, .. } => stack.extend(defs.iter().map(|(_, b)| b)),
5920            Term::Annotated { term, .. } => stack.push(term),
5921        }
5922    }
5923}
5924
5925/// Collect the occurrences of `allowed` names appearing as free [`Term::Var`]s in `t`.
5926fn free_vars_among(t: &Term, allowed: &[&str], acc: &mut Vec<String>) {
5927    match t {
5928        Term::Var(n) => {
5929            if allowed.contains(&n.as_str()) && !acc.contains(n) {
5930                acc.push(n.clone());
5931            }
5932        }
5933        Term::Pi {
5934            param_type,
5935            body_type,
5936            ..
5937        } => {
5938            free_vars_among(param_type, allowed, acc);
5939            free_vars_among(body_type, allowed, acc);
5940        }
5941        Term::Lambda {
5942            param_type, body, ..
5943        } => {
5944            free_vars_among(param_type, allowed, acc);
5945            free_vars_among(body, allowed, acc);
5946        }
5947        Term::App(f, a) => {
5948            free_vars_among(f, allowed, acc);
5949            free_vars_among(a, allowed, acc);
5950        }
5951        Term::Match {
5952            discriminant,
5953            motive,
5954            cases,
5955        } => {
5956            free_vars_among(discriminant, allowed, acc);
5957            free_vars_among(motive, allowed, acc);
5958            for c in cases {
5959                free_vars_among(c, allowed, acc);
5960            }
5961        }
5962        Term::Fix { body, .. } => free_vars_among(body, allowed, acc),
5963        Term::MutualFix { defs, .. } => {
5964            for (_, b) in defs {
5965                free_vars_among(b, allowed, acc);
5966            }
5967        }
5968        Term::Let {
5969            ty, value, body, ..
5970        } => {
5971            free_vars_among(ty, allowed, acc);
5972            free_vars_among(value, allowed, acc);
5973            free_vars_among(body, allowed, acc);
5974        }
5975        _ => {}
5976    }
5977}
5978
5979/// Drop from `items` (and its index-aligned `owners`) every entry owned by the scope `closing`.
5980fn retain_scoped1<T: Clone>(items: &mut Arc<Vec<T>>, owners: &mut Arc<Vec<usize>>, closing: usize) {
5981    if !owners.iter().any(|d| *d == closing) {
5982        return;
5983    }
5984    let keep: Vec<bool> = owners.iter().map(|d| *d != closing).collect();
5985    let items = Arc::make_mut(items);
5986    let owners = Arc::make_mut(owners);
5987    let mut i = 0;
5988    items.retain(|_| {
5989        let k = keep.get(i).copied().unwrap_or(true);
5990        i += 1;
5991        k
5992    });
5993    owners.retain(|d| *d != closing);
5994    debug_assert_eq!(items.len(), owners.len());
5995}
5996
5997/// The two-side-car version: `items` with BOTH `aux` and `owners` index-aligned to it.
5998fn retain_scoped2<T: Clone, A: Clone>(
5999    items: &mut Arc<Vec<T>>,
6000    aux: &mut Arc<Vec<A>>,
6001    owners: &mut Arc<Vec<usize>>,
6002    closing: usize,
6003) {
6004    if !owners.iter().any(|d| *d == closing) {
6005        return;
6006    }
6007    let keep: Vec<bool> = owners.iter().map(|d| *d != closing).collect();
6008    let mut i = 0;
6009    Arc::make_mut(items).retain(|_| {
6010        let k = keep.get(i).copied().unwrap_or(true);
6011        i += 1;
6012        k
6013    });
6014    let mut j = 0;
6015    Arc::make_mut(aux).retain(|_| {
6016        let k = keep.get(j).copied().unwrap_or(true);
6017        j += 1;
6018        k
6019    });
6020    Arc::make_mut(owners).retain(|d| *d != closing);
6021    debug_assert_eq!(items.len(), owners.len());
6022    debug_assert_eq!(aux.len(), owners.len());
6023}
6024
6025/// The ONE parameter-count rule for a MUTUAL block, stated where registration can enforce it.
6026///
6027/// A mutual block shares a single uniform parameter telescope: `Tree A`/`Forest A` are one
6028/// declaration over one `A`. Two things are refused, and the second used to be laundered rather
6029/// than diagnosed:
6030///
6031/// * a member whose recorded `num_params` EXCEEDS its own arity — nonsense that
6032///   `derive_mutual_recursor`'s `.min(arity)` silently clamped, so two members could agree on a
6033///   number while disagreeing about what their parameters mean; and
6034/// * members that disagree on the count.
6035///
6036/// Returns the block's shared parameter count. An EMPTY block has none and is vacuously fine.
6037///
6038/// Better than Lean's diagnostic in one respect: the message lists every member and its own
6039/// count, so the odd one out is visible without re-reading the declaration.
6040pub fn reconcile_block_params(block: &[MutualInductive]) -> crate::error::KernelResult<usize> {
6041    let counts: Vec<_> = block
6042        .iter()
6043        .map(|member| {
6044            (
6045                member.name.as_str(),
6046                member.num_params,
6047                count_leading_pis(&member.sort),
6048            )
6049        })
6050        .collect();
6051    reconcile_parameter_counts(&counts)
6052}
6053
6054/// Shared policy for raw public metadata checks and exposed checked headers.
6055fn reconcile_parameter_counts(
6056    counts: &[(&str, usize, usize)],
6057) -> crate::error::KernelResult<usize> {
6058    for &(name, params, arity) in counts {
6059        if params > arity {
6060            return Err(crate::error::KernelError::CertificationError(format!(
6061                "mutual block: member '{name}' declares {params} parameter(s) but its arity is only {arity} — \
6062                 a parameter count above the arity has no telescope to name"
6063            )));
6064        }
6065    }
6066    let Some(&(_, first, _)) = counts.first() else {
6067        return Ok(0);
6068    };
6069    if counts.iter().any(|&(_, n, _)| n != first) {
6070        let listing = counts
6071            .iter()
6072            .map(|(n, p, a)| format!("{n}: {p} of {a}"))
6073            .collect::<Vec<_>>()
6074            .join(", ");
6075        return Err(crate::error::KernelError::CertificationError(format!(
6076            "mutual block members disagree on parameter count ({listing}) — a mutual block \
6077             shares ONE uniform parameter telescope, so a block that disagrees has no induction \
6078             principle and must be refused at registration"
6079        )));
6080    }
6081    Ok(first)
6082}
6083
6084/// Infer which of a class's parameters are OUTPUTS — Lean's `outParam`, recovered from the
6085/// shape of its methods rather than from an annotation.
6086///
6087/// The reading is functional-dependency: a parameter a method CONSUMES is something a call
6088/// site supplies, so resolution can match on it; a parameter that only ever appears in a
6089/// method's RESULT is something the instance PRODUCES, so matching on it would let the
6090/// surrounding context's expectation silently choose a different instance. `HAdd α β γ`'s
6091/// `hAdd : α → β → γ` is the canonical case: `α`/`β` are consumed, `γ` is produced.
6092///
6093/// Consumption is read off the Π-telescopes of the field types: every free name in any
6094/// DOMAIN is consumed, as is every name a later parameter's own type depends on. Nothing in
6095/// a codomain is.
6096///
6097/// The floor: if EVERY parameter would be an output, none is. A class with no inputs has
6098/// nothing for resolution to key on, so the first registered entry would answer every goal —
6099/// which is why `Inhabited α` (`default : α`, a carrier that appears only as a result) must
6100/// keep matching on its carrier. That rule is what separates a genuine output position from a
6101/// class whose methods simply return their carrier.
6102fn infer_out_params(params: &[(&str, Term)], fields: &[(&str, Term)]) -> Vec<usize> {
6103    let mut consumed: std::collections::HashSet<String> = std::collections::HashSet::new();
6104    for (_, ty) in params {
6105        collect_free_names(ty, &mut Vec::new(), &mut consumed);
6106    }
6107    for (_, ty) in fields {
6108        collect_domain_names(ty, &mut Vec::new(), &mut consumed);
6109    }
6110    let outputs: Vec<usize> = params
6111        .iter()
6112        .enumerate()
6113        .filter(|(_, (p, _))| !consumed.contains(*p))
6114        .map(|(i, _)| i)
6115        .collect();
6116    if outputs.len() == params.len() {
6117        Vec::new()
6118    } else {
6119        outputs
6120    }
6121}
6122
6123/// Collect every free variable name appearing in a `Π`-DOMAIN of `ty` (at any depth of its
6124/// telescope). The final codomain contributes nothing — that is the whole distinction between
6125/// a consumed parameter and a produced one.
6126fn collect_domain_names(
6127    ty: &Term,
6128    bound: &mut Vec<String>,
6129    acc: &mut std::collections::HashSet<String>,
6130) {
6131    if let Term::Pi {
6132        param,
6133        param_type,
6134        body_type,
6135    } = ty
6136    {
6137        collect_free_names(param_type, bound, acc);
6138        bound.push(param.clone());
6139        collect_domain_names(body_type, bound, acc);
6140        bound.pop();
6141    }
6142}
6143
6144/// Collect every free `Term::Var` name in `t`, skipping the ones `bound` shadows.
6145fn collect_free_names(
6146    t: &Term,
6147    bound: &mut Vec<String>,
6148    acc: &mut std::collections::HashSet<String>,
6149) {
6150    match t {
6151        Term::Var(n) => {
6152            if !bound.contains(n) {
6153                acc.insert(n.clone());
6154            }
6155        }
6156        Term::App(f, a) => {
6157            collect_free_names(f, bound, acc);
6158            collect_free_names(a, bound, acc);
6159        }
6160        Term::Pi {
6161            param,
6162            param_type,
6163            body_type,
6164        } => {
6165            collect_free_names(param_type, bound, acc);
6166            bound.push(param.clone());
6167            collect_free_names(body_type, bound, acc);
6168            bound.pop();
6169        }
6170        Term::Lambda {
6171            param,
6172            param_type,
6173            body,
6174        } => {
6175            collect_free_names(param_type, bound, acc);
6176            bound.push(param.clone());
6177            collect_free_names(body, bound, acc);
6178            bound.pop();
6179        }
6180        Term::Match {
6181            discriminant,
6182            motive,
6183            cases,
6184        } => {
6185            collect_free_names(discriminant, bound, acc);
6186            collect_free_names(motive, bound, acc);
6187            for c in cases {
6188                collect_free_names(c, bound, acc);
6189            }
6190        }
6191        Term::Fix { name, body } => {
6192            bound.push(name.clone());
6193            collect_free_names(body, bound, acc);
6194            bound.pop();
6195        }
6196        Term::MutualFix { defs, .. } => {
6197            for (n, b) in defs {
6198                bound.push(n.clone());
6199                collect_free_names(b, bound, acc);
6200                bound.pop();
6201            }
6202        }
6203        Term::Let {
6204            name,
6205            ty,
6206            value,
6207            body,
6208        } => {
6209            collect_free_names(ty, bound, acc);
6210            collect_free_names(value, bound, acc);
6211            bound.push(name.clone());
6212            collect_free_names(body, bound, acc);
6213            bound.pop();
6214        }
6215        Term::Global(_) | Term::Sort(_) | Term::Lit(_) | Term::Hole | Term::Const { .. } => {}
6216        Term::Annotated { term, .. } => collect_free_names(term, bound, acc),
6217    }
6218}
6219
6220/// The length of the longest PREFIX of `arity` positions that constructor type `cty` treats as
6221/// uniform parameters of `ind` — see [`Context::infer_num_params`] for the rule.
6222fn ctor_param_prefix(ind: &str, cty: &Term, arity: usize) -> usize {
6223    // Peel the constructor's own Π telescope, remembering its binder names in order.
6224    let mut binders: Vec<&str> = Vec::new();
6225    let mut cur = cty;
6226    while let Term::Pi {
6227        param, body_type, ..
6228    } = cur
6229    {
6230        binders.push(param.as_str());
6231        cur = body_type;
6232    }
6233    let Some(result_args) = applied_to(cur, ind) else {
6234        return 0;
6235    };
6236    // A binder position the telescope does not even reach cannot be uniform. `refl : Π(A)(x:A).
6237    // Eq A x x` has two binders against `Eq`'s arity of three, so its third position is an index
6238    // — which is exactly right, and is why the cap is on the TELESCOPE, not only on the arity.
6239    let cap = arity.min(binders.len()).min(result_args.len());
6240    let mut p = 0;
6241    while p < cap && matches!(&result_args[p], Term::Var(v) if v == binders[p]) {
6242        p += 1;
6243    }
6244    if p == 0 {
6245        return 0;
6246    }
6247    // Every RECURSIVE occurrence inside an argument type must pass the same binders. Walk the
6248    // whole telescope's domains, not just the recursive-looking ones: an occurrence can be nested
6249    // arbitrarily deep (`Π(y:A). R y x → Acc A R y`).
6250    let mut cur = cty;
6251    while let Term::Pi {
6252        param_type,
6253        body_type,
6254        ..
6255    } = cur
6256    {
6257        p = p.min(uniform_prefix_of_occurrences(param_type, ind, &binders, p));
6258        if p == 0 {
6259            return 0;
6260        }
6261        cur = body_type;
6262    }
6263    p
6264}
6265
6266/// If `t` is the application spine `Global(head) a₀ … aₙ₋₁`, its arguments in order.
6267fn applied_to<'a>(t: &'a Term, head: &str) -> Option<Vec<&'a Term>> {
6268    let mut args: Vec<&Term> = Vec::new();
6269    let mut cur = t;
6270    while let Term::App(f, a) = cur {
6271        args.push(a);
6272        cur = f;
6273    }
6274    match cur {
6275        Term::Global(n) if n == head => {
6276            args.reverse();
6277            Some(args)
6278        }
6279        _ => None,
6280    }
6281}
6282
6283/// Shrink `limit` to the longest prefix over which EVERY occurrence of `ind` inside `t` passes
6284/// `binders[i]` at position `i`.
6285fn uniform_prefix_of_occurrences(t: &Term, ind: &str, binders: &[&str], limit: usize) -> usize {
6286    let mut acc = limit;
6287    if let Some(args) = applied_to(t, ind) {
6288        let mut p = 0;
6289        while p < acc && p < args.len() && matches!(&args[p], Term::Var(v) if v == binders[p]) {
6290            p += 1;
6291        }
6292        // `p` is already capped by `args.len()`, so a PARTIALLY applied occurrence — which
6293        // supplies nothing at the positions it omits — collapses the prefix to what it does
6294        // supply. That is the conservative direction, and the right one.
6295        acc = p;
6296        // Descend into the ARGUMENTS only. Walking the spine's function half as well would
6297        // re-read `I a₀ … aₖ₋₁` as its own shorter occurrence and shrink the prefix to zero for
6298        // every recursive field.
6299        for a in args {
6300            acc = uniform_prefix_of_occurrences(a, ind, binders, acc);
6301        }
6302        return acc;
6303    }
6304    // Recurse into every subterm — an occurrence can hide under any constructor of `Term`.
6305    let visit = |sub: &Term, acc: &mut usize| {
6306        *acc = uniform_prefix_of_occurrences(sub, ind, binders, *acc);
6307    };
6308    match t {
6309        Term::App(f, a) => {
6310            visit(f, &mut acc);
6311            visit(a, &mut acc);
6312        }
6313        Term::Pi {
6314            param_type,
6315            body_type,
6316            ..
6317        } => {
6318            visit(param_type, &mut acc);
6319            visit(body_type, &mut acc);
6320        }
6321        Term::Lambda {
6322            param_type, body, ..
6323        } => {
6324            visit(param_type, &mut acc);
6325            visit(body, &mut acc);
6326        }
6327        Term::Match {
6328            discriminant,
6329            motive,
6330            cases,
6331        } => {
6332            visit(discriminant, &mut acc);
6333            visit(motive, &mut acc);
6334            for c in cases {
6335                visit(c, &mut acc);
6336            }
6337        }
6338        Term::Fix { body, .. } => visit(body, &mut acc),
6339        Term::MutualFix { defs, .. } => {
6340            for (_, b) in defs {
6341                visit(b, &mut acc);
6342            }
6343        }
6344        Term::Let {
6345            ty, value, body, ..
6346        } => {
6347            visit(ty, &mut acc);
6348            visit(value, &mut acc);
6349            visit(body, &mut acc);
6350        }
6351        Term::Annotated { term, .. } => visit(term, &mut acc),
6352        Term::Var(_)
6353        | Term::Global(_)
6354        | Term::Sort(_)
6355        | Term::Lit(_)
6356        | Term::Hole
6357        | Term::Const { .. } => {}
6358    }
6359    acc
6360}
6361
6362/// An inductive's arity as it is declared, with its telescope exposed: every binder domain is kept
6363/// exactly as written (`outParam`, `semiOutParam`, `optParam`, an abbreviation), because the arity
6364/// is the family's statement; only a tail that is neither a product nor a sort is handed to
6365/// `normalize`, which is Lean's `whnf` at each binder of an arity whose telescope hides behind a
6366/// definition. The caller decides what an unfinished normalization means.
6367pub(crate) fn exposed_arity<E>(
6368    ctx: &Context,
6369    arity: &Term,
6370    normalize: &mut dyn FnMut(&Context, &Term) -> Result<Term, E>,
6371) -> Result<Term, E> {
6372    match arity {
6373        Term::Pi {
6374            param,
6375            param_type,
6376            body_type,
6377        } => {
6378            let inner = ctx.extend(param, (**param_type).clone());
6379            Ok(Term::Pi {
6380                param: param.clone(),
6381                param_type: param_type.clone(),
6382                body_type: Box::new(exposed_arity(&inner, body_type, normalize)?),
6383            })
6384        }
6385        Term::Sort(_) => Ok(arity.clone()),
6386        hidden => match normalize(ctx, hidden)? {
6387            exposed @ (Term::Pi { .. } | Term::Sort(_)) => exposed_arity(ctx, &exposed, normalize),
6388            stuck => Ok(stuck),
6389        },
6390    }
6391}
6392
6393/// Count the leading `Π`s of a term — an inductive's arity, or a constructor's parameter
6394/// count.
6395fn count_leading_pis(t: &Term) -> usize {
6396    let mut n = 0;
6397    let mut cur = t;
6398    while let Term::Pi { body_type, .. } = cur {
6399        n += 1;
6400        cur = body_type;
6401    }
6402    n
6403}
6404
6405#[cfg(test)]
6406#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/context/accessor_tests.rs"]
6407mod accessor_tests;
6408
6409#[cfg(test)]
6410#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/context/accessor_tests_more.rs"]
6411mod accessor_tests_more;
6412
6413#[cfg(test)]
6414#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/context/arithmetic_attestation_cache_controls.rs"]
6415mod arithmetic_attestation_cache_controls;
6416
6417#[cfg(test)]
6418#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/context/checked_opaque_storage_controls.rs"]
6419mod checked_opaque_storage_controls;
6420
6421#[cfg(test)]
6422#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/context/local_name_controls.rs"]
6423mod local_name_controls;
6424
6425#[cfg(test)]
6426#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/context/displacement_sharing_controls.rs"]
6427mod displacement_sharing_controls;
6428
6429#[cfg(test)]
6430#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/context/admission_log_controls.rs"]
6431mod admission_log_controls;