Skip to main content

logicaffeine_kernel/
prelude.rs

1//! Standard Library for the Kernel.
2//!
3//! Defines fundamental types and logical connectives:
4//! - Entity: domain of individuals (for FOL)
5//! - Nat: natural numbers
6//! - True, False: propositional constants
7//! - Eq: propositional equality
8//! - And, Or: logical connectives
9
10pub(crate) mod natural_arithmetic;
11
12use crate::context::Context;
13use crate::term::{Literal, Term, Universe};
14
15/// Standard library definitions.
16pub struct StandardLibrary;
17
18#[cfg(feature = "shadow")]
19thread_local! {
20    /// How deep this thread is inside [`StandardLibrary::register`].
21    static REGISTERING: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
22}
23
24/// This thread is registering the standard library while one lives.
25#[cfg(feature = "shadow")]
26struct Registering;
27
28#[cfg(feature = "shadow")]
29impl Registering {
30    fn enter() -> Registering {
31        REGISTERING.with(|depth| depth.set(depth.get() + 1));
32        Registering
33    }
34}
35
36#[cfg(feature = "shadow")]
37impl Drop for Registering {
38    fn drop(&mut self) {
39        REGISTERING.with(|depth| depth.set(depth.get() - 1));
40    }
41}
42
43/// Whether this thread is registering the standard library (shadow mode stands down meanwhile).
44#[cfg(feature = "shadow")]
45pub(crate) fn registering() -> bool {
46    REGISTERING.with(|depth| depth.get() > 0)
47}
48
49/// The standard library's one registration ([`StandardLibrary::context`]).
50static PRELUDE: std::sync::OnceLock<Context> = std::sync::OnceLock::new();
51
52impl StandardLibrary {
53    /// Register all standard library definitions in the context.
54    ///
55    /// A thousand checked declarations and their checked equation lemmas: production code asks
56    /// the process's one registration, [`StandardLibrary::context`], instead.
57    pub fn register(ctx: &mut Context) {
58        #[cfg(feature = "shadow")]
59        let _registering = Registering::enter();
60        ctx.with_equations_suspended(Self::register_core);
61        crate::equations::generate_missing_for_all(ctx);
62    }
63
64    /// The standard library's context, registered once per process.
65    ///
66    /// A registered `Context` is `Arc`-backed and copy-on-write throughout (every mutating
67    /// accessor goes through `Arc::make_mut`), so a caller that only asks questions borrows this
68    /// one, and a caller that extends it clones it: about a microsecond, sharing every table
69    /// until the clone writes to it, against the ~0.3 s (optimized) of registering again. The
70    /// clone is an independent value; the attestation caches it shares are keyed by the registry
71    /// generation they inspected, so a clone that diverges never reads another's answer.
72    /// `the_cached_prelude_is_indistinguishable_from_a_fresh_one` pins it against a fresh
73    /// registration.
74    pub fn context() -> &'static Context {
75        PRELUDE.get_or_init(|| {
76            let mut ctx = Context::new();
77            Self::register(&mut ctx);
78            ctx
79        })
80    }
81
82    /// [`StandardLibrary::context`] if it is registered already: no context descends from the
83    /// standard library before it is.
84    pub(crate) fn registered() -> Option<&'static Context> {
85        PRELUDE.get()
86    }
87
88    fn register_core(ctx: &mut Context) {
89        Self::register_entity(ctx);
90        Self::register_nat(ctx);
91        Self::register_monolist(ctx);
92        Self::register_bool(ctx);
93        Self::register_tlist(ctx);
94        Self::register_true(ctx);
95        Self::register_false(ctx);
96        Self::register_not(ctx);
97        Self::register_eq(ctx);
98        Self::register_heq(ctx);
99        Self::register_and(ctx);
100        Self::register_or(ctx);
101        Self::register_ex(ctx);
102        Self::register_decidable(ctx);
103        Self::register_of_decide(ctx);
104        Self::register_dec_eq_bool(ctx);
105        Self::register_dec_eq_nat(ctx);
106        Self::register_decidable_instances(ctx);
107        Self::register_native_decide(ctx);
108        Self::register_psigma(ctx);
109        Self::register_quot(ctx);
110        Self::register_setoid(ctx);
111        Self::register_acc(ctx);
112        Self::register_primitives(ctx);
113        Self::register_int_ring_axioms(ctx);
114        Self::register_int_order_axioms(ctx);
115        Self::register_reflection(ctx);
116        Self::register_hardware(ctx);
117        Self::register_core_types(ctx);
118        natural_arithmetic::register(ctx);
119        crate::int_inductive::register_inductive_int(ctx)
120            .expect("checked structural integer prelude");
121        crate::int_inductive::register_public_arithmetic_aliases(ctx)
122            .expect("checked public integer arithmetic aliases");
123        crate::int_inductive::register_public_division_aliases(ctx)
124            .expect("checked public integer division aliases");
125        crate::integer_laws::register(ctx).expect("checked constructor-derived integer laws");
126        Self::register_extensionality_and_choice(ctx);
127    }
128
129    /// **Lean's other core constants, and everything that derives from them.**
130    ///
131    /// The four constants a Lean development actually reaches for are `propext`, `funext`,
132    /// `Classical.choice` and `Quot.sound` — but Lean's trusted base is only THREE of them, and
133    /// that distinction is the whole design of this function. LOGOS had `Quot.sound` and `dne` and
134    /// none of the rest, which is a STATEABILITY gap, not a convenience one: without `propext`
135    /// there is no `Set`, no quotient extensionality and no `simp` on `↔`; without `funext` there
136    /// is no `ext` lemma and no equality of `Set`/`Finset`/`Matrix`; without `Classical.choice`
137    /// almost every Mathlib theorem loses its `#print axioms` line. A translator that meets one of
138    /// them can only give up or forge, and forging is what rule 6 of the campaign exists to
139    /// prevent.
140    ///
141    /// **TWO axioms, and not one more.** `funext` is a THEOREM here, proved from `Quot_sound`
142    /// exactly as Lean proves it — an earlier wave assumed it, which bought at permanent cost to
143    /// the trusted base something the reference implementation gets for free. Everything else in
144    /// this function is likewise a DEFINITION with a kernel-checked body, so the trusted base
145    /// grows by exactly the two assumptions Lean also makes and by nothing that Lean proves:
146    ///
147    /// | constant | kind | why |
148    /// |---|---|---|
149    /// | `propext` | axiom | Lean's; unprovable — `Prop` has no extensionality rule |
150    /// | `Classical_choice` | axiom | Lean's; `Nonempty α → α` extracts data from a proof |
151    /// | `funext` | **definition** | Lean PROVES it from `Quot.sound`; so do we (see below) |
152    /// | `eq_true`, `eq_false` | definitions | `propext`'s canonical users — `simp`'s Prop normal form |
153    /// | `nonemptyNat` | definition | `Nonempty_intro Nat Zero` |
154    /// | `Or_rec`, `Ex_rec` | definitions | auto-derived eliminators |
155    /// | `Classical_em` | definition | the standard intuitionistic derivation from `dne` |
156    /// | `Classical_propDecidable` | definition | `dne` + `choice`, NO `em` needed (see below) |
157    /// | `Classical_axiomOfChoice` | definition | pointwise `choice` through `Subtype` |
158    ///
159    /// **Why `Classical_propDecidable` does not go through `em`.** The textbook route is
160    /// `em p : p ∨ ¬p`, then `Or_rec` into `Nonempty (Decidable p)`, then `choice`. The shorter
161    /// route needs no disjunction at all: `Nonempty (Decidable p)` is itself a `Prop`, so `dne`
162    /// applies to it directly, and the double-negation argument builds `isTrue`/`isFalse` from the
163    /// SAME refutation `k`. Fewer moving parts, one fewer eliminator in the proof term, and it
164    /// makes plain that the classical content is `choice` — `em` is not on the critical path.
165    ///
166    /// **The firewall stays shut.** `Classical_propDecidable` is what MAKES data out of a
167    /// proposition, and it does so only by applying `Classical_choice`. Eliminating `p ∨ ¬p` into
168    /// `Decidable p` is still refused, because `Or` has two constructors and `motive_target` keeps
169    /// its motive in `Prop` — keyed on the MOTIVE'S SORT, never on a `Classical.` name prefix. So
170    /// the new capability arrives as a term you apply, not as a loosened eliminator.
171    fn register_extensionality_and_choice(ctx: &mut Context) {
172        let type0 = || Term::Sort(Universe::Type(0));
173        let prop = || Term::Sort(Universe::Prop);
174        let eq3 = |t: Term, x: Term, y: Term| apps_(gl("Eq"), &[t, x, y]);
175
176        // ---- propext : Π(p q : Prop). Iff p q → Eq Prop p q  (AXIOM) ----------------------
177        //
178        // The conclusion is an equation between PROPOSITIONS, and it is already expressible:
179        // `Prop.succ() == Type 0`, so `Sort Prop : Type 0` and `Eq`'s `Type 0` carrier accepts it.
180        // `Iff` is a DEFINITION unfolding to the conjunction, so the hypothesis is the `And` a
181        // translator already has — a fresh `Iff` inductive would be a different proposition that
182        // `propext` itself could not bridge back.
183        ctx.add_declaration(
184            "propext",
185            pi_(
186                "p",
187                prop(),
188                pi_(
189                    "q",
190                    prop(),
191                    arrow_(
192                        apps_(gl("Iff"), &[v_("p"), v_("q")]),
193                        eq3(prop(), v_("p"), v_("q")),
194                    ),
195                ),
196            ),
197        );
198
199        // ---- funext, in its DEPENDENT form — a THEOREM, proved from `Quot_sound` ----------
200        //
201        //   Π(A:Type). Π(B:A→Type). Π(f g : Π(x:A). B x).
202        //     (Π(x:A). Eq (B x) (f x) (g x)) → Eq (Π(x:A). B x) f g
203        //
204        // **Lean does not assume this, and neither do we.** `funext` is one of the four constants
205        // a Lean user reaches for, but it is NOT one of Lean's three axioms: Lean PROVES it from
206        // `Quot.sound`. Assuming it would have bought — at a permanent cost to the trusted base —
207        // something the reference implementation gets for free, and the trusted base is the first
208        // number a Lean reader checks.
209        //
210        // THE ARGUMENT, and it is Lean's. Write `F := Π(x:A). B x`, and let `eqv` be POINTWISE
211        // equality on `F`. That is a relation, not an equality, so quotienting by it is legal and
212        // assumes nothing. At each point `x`, lift the single application `λu. u x` through
213        // `Quot F eqv`: its respect obligation is `eqv u w → Eq (B x) (u x) (w x)`, which the
214        // hypothesis supplies POINTWISE — no extensionality is needed to build it. That gives
215        //
216        //     ext : Quot F eqv → F        with     ext (Quot_mk F eqv u)  ≡  λx. u x  ≡  u
217        //
218        // — the first step by the quotient ι-rule, the second by η, which `def_eq` decides and
219        // `normalize` does not (exactly the asymmetry T00-014 pins). Now `Quot_sound F eqv f g h`
220        // proves `Eq (Quot F eqv) (mk f) (mk g)`, and substituting along it in the motive
221        // `λq. Eq F f (ext q)` — `Eq_rec`, the Prop-motive substitution eliminator, itself derived
222        // from J — carries `Eq F f (ext (mk f))`, which is `refl F f` by the conversion above, to
223        // `Eq F f (ext (mk g))`, which IS `Eq F f g` by the same conversion.
224        //
225        // So extensionality of functions follows from the ONE thing quotients already assume: that
226        // `Quot_sound` identifies related representatives. The η step is load-bearing and is why
227        // this is a proof rather than a restatement — without η, `ext (mk u)` would only ever be
228        // `λx. u x`, and the theorem would not close.
229        //
230        // It remains a theorem you APPLY, never a conversion rule the kernel silently gained:
231        // `def_eq`'s `Lambda`/`Lambda` arm stays α-equivalence, so `λn. addz n` and `λn. n` are
232        // still not convertible. A monomorphic `Nat → Nat` version would be strictly weaker at the
233        // same length; the dependent form is the one `ext`, `Set` and `Matrix` need.
234        let b_at = |x: Term| Term::App(Box::new(v_("B")), Box::new(x));
235        let dep_fn = || pi_("x", v_("A"), b_at(v_("x")));
236        let at = |f: Term, x: Term| Term::App(Box::new(f), Box::new(x));
237        // `eqv := λ(u w : F). Π(pt:A). Eq (B pt) (u pt) (w pt)` — pointwise equality, as a
238        // RELATION. Every binder below is uniquely named: the kernel is name-keyed, and a shared
239        // spelling between this relation's binder and the point it is later instantiated at is
240        // exactly the capture a named kernel has to freshen around.
241        let pointwise_named = |u: &str, w: &str, pt: &str| {
242            pi_(
243                pt,
244                v_("A"),
245                eq3(b_at(v_(pt)), at(v_(u), v_(pt)), at(v_(w), v_(pt))),
246            )
247        };
248        let eqv = || {
249            lam_(
250                "u",
251                dep_fn(),
252                lam_("w", dep_fn(), pointwise_named("u", "w", "pt")),
253            )
254        };
255        let quot_f = || apps_(gl("Quot"), &[dep_fn(), eqv()]);
256        let mk_class = |u: Term| apps_(gl("Quot_mk"), &[dep_fn(), eqv(), u]);
257        // `ext := λ(q : Quot F eqv). λ(ix:A). Quot_lift F eqv (B ix) (λu2. u2 ix) (λa2 b2 hab.
258        //          hab ix) q`
259        let ext = || {
260            lam_(
261                "q",
262                quot_f(),
263                lam_(
264                    "ix",
265                    v_("A"),
266                    apps_(
267                        gl("Quot_lift"),
268                        &[
269                            dep_fn(),
270                            eqv(),
271                            b_at(v_("ix")),
272                            lam_("u2", dep_fn(), at(v_("u2"), v_("ix"))),
273                            lam_(
274                                "a2",
275                                dep_fn(),
276                                lam_(
277                                    "b2",
278                                    dep_fn(),
279                                    lam_(
280                                        "hab",
281                                        pointwise_named("a2", "b2", "pt2"),
282                                        at(v_("hab"), v_("ix")),
283                                    ),
284                                ),
285                            ),
286                            v_("q"),
287                        ],
288                    ),
289                ),
290            )
291        };
292        // `Eq_rec (Quot F eqv) (mk f) (λq2. Eq F f (ext q2)) (refl F f) (mk g)
293        //         (Quot_sound F eqv f g h)`
294        let funext_body = lam_(
295            "A",
296            type0(),
297            lam_(
298                "B",
299                pi_("_x", v_("A"), type0()),
300                lam_(
301                    "f",
302                    dep_fn(),
303                    lam_(
304                        "g",
305                        dep_fn(),
306                        lam_(
307                            "h",
308                            pointwise_named("f", "g", "pt3"),
309                            apps_(
310                                gl("Eq_rec"),
311                                &[
312                                    quot_f(),
313                                    mk_class(v_("f")),
314                                    lam_(
315                                        "q2",
316                                        quot_f(),
317                                        eq3(dep_fn(), v_("f"), at(ext(), v_("q2"))),
318                                    ),
319                                    apps_(gl("refl"), &[dep_fn(), v_("f")]),
320                                    mk_class(v_("g")),
321                                    apps_(
322                                        gl("Quot_sound"),
323                                        &[dep_fn(), eqv(), v_("f"), v_("g"), v_("h")],
324                                    ),
325                                ],
326                            ),
327                        ),
328                    ),
329                ),
330            ),
331        );
332        ctx.add_definition(
333            "funext".to_string(),
334            pi_(
335                "A",
336                type0(),
337                pi_(
338                    "B",
339                    pi_("_x", v_("A"), type0()),
340                    pi_(
341                        "f",
342                        dep_fn(),
343                        pi_(
344                            "g",
345                            dep_fn(),
346                            arrow_(
347                                pointwise_named("f", "g", "pt3"),
348                                eq3(dep_fn(), v_("f"), v_("g")),
349                            ),
350                        ),
351                    ),
352                ),
353            ),
354            funext_body,
355        );
356
357        // ---- Classical_choice : Π(A:Type). Nonempty A → A  (AXIOM) ------------------------
358        //
359        // `Nonempty α` is a PROPOSITION and `α` is data; turning one into the other is exactly
360        // the content of choice, and it is why `Nonempty` is registered at `Prop` with a
361        // data-carrying constructor — that shape is NOT a subsingleton, so the kernel refuses to
362        // large-eliminate it and the only route to a witness is this declared axiom. Deriving it
363        // instead (by placing `Nonempty` in `Type 0`) would be choice that the axiom census could
364        // never see.
365        ctx.add_declaration(
366            "Classical_choice",
367            pi_(
368                "A",
369                type0(),
370                arrow_(
371                    Term::App(Box::new(gl("Nonempty")), Box::new(v_("A"))),
372                    v_("A"),
373                ),
374            ),
375        );
376
377        // ---- from here on: DEFINITIONS ONLY. ---------------------------------------------
378
379        // `eq_true` and `eq_false` — `propext`'s two canonical users, and Lean's own
380        // (`eq_true`, `eq_false`). They are here because an axiom nothing cites is an axiom
381        // nothing can REPORT: `axiom_dependencies` computes the closure of a term, so `propext`
382        // becomes visible to `Print Axioms` only once something in the library rests on it.
383        //
384        // They are also the proposition normal form `simp` works in — `p` becomes `p = True` and
385        // `¬p` becomes `p = False` — which is the shape that makes propositional rewriting a
386        // rewrite at all. Both cost the trusted base NOTHING: each is one application of
387        // `propext` to an `Iff` built from `conj`.
388        //
389        //   eq_true  : Π(p:Prop). p     → Eq Prop p True
390        //            := λp hp. propext p True  (conj (p → True) (True → p) (λ_. I)  (λ_. hp))
391        //   eq_false : Π(p:Prop). Not p → Eq Prop p False
392        //            := λp hn. propext p False (conj (p → False) (False → p) hn (λh. absurd h))
393        //
394        // `Iff p q` is a DEFINITION unfolding to `And (p→q) (q→p)`, so `conj` at those two arrow
395        // types IS the biconditional — no `Iff` constructor exists to reach for, deliberately.
396        let iff_via_conj = |q: Term, fwd: Term, bwd: Term| {
397            apps_(
398                gl("conj"),
399                &[arrow_(v_("p"), q.clone()), arrow_(q, v_("p")), fwd, bwd],
400            )
401        };
402        ctx.add_definition(
403            "eq_true".to_string(),
404            pi_(
405                "p",
406                prop(),
407                arrow_(v_("p"), eq3(prop(), v_("p"), gl("True"))),
408            ),
409            lam_(
410                "p",
411                prop(),
412                lam_(
413                    "hp",
414                    v_("p"),
415                    apps_(
416                        gl("propext"),
417                        &[
418                            v_("p"),
419                            gl("True"),
420                            iff_via_conj(
421                                gl("True"),
422                                lam_("_", v_("p"), gl("I")),
423                                lam_("_", gl("True"), v_("hp")),
424                            ),
425                        ],
426                    ),
427                ),
428            ),
429        );
430        // `False`'s eliminator into `Prop` is a zero-case `Match`: small elimination is
431        // unconditional, so no `False_rec` constant is needed to cross back.
432        let from_false = lam_(
433            "hf",
434            gl("False"),
435            Term::Match {
436                discriminant: Box::new(v_("hf")),
437                motive: Box::new(lam_("_", gl("False"), v_("p"))),
438                cases: vec![],
439            },
440        );
441        ctx.add_definition(
442            "eq_false".to_string(),
443            pi_(
444                "p",
445                prop(),
446                arrow_(
447                    Term::App(Box::new(gl("Not")), Box::new(v_("p"))),
448                    eq3(prop(), v_("p"), gl("False")),
449                ),
450            ),
451            lam_(
452                "p",
453                prop(),
454                lam_(
455                    "hn",
456                    Term::App(Box::new(gl("Not")), Box::new(v_("p"))),
457                    apps_(
458                        gl("propext"),
459                        &[
460                            v_("p"),
461                            gl("False"),
462                            iff_via_conj(gl("False"), v_("hn"), from_false),
463                        ],
464                    ),
465                ),
466            ),
467        );
468
469        // nonemptyNat : Nonempty Nat := Nonempty_intro Nat Zero
470        ctx.add_definition(
471            "nonemptyNat".to_string(),
472            Term::App(Box::new(gl("Nonempty")), Box::new(gl("Nat"))),
473            apps_(gl("Nonempty_intro"), &[gl("Nat"), gl("Zero")]),
474        );
475
476        // The two eliminators the classical layer needs, auto-derived. Both keep their `Prop`
477        // motive: `Or` has two constructors and `Ex` stores a witness that is not among its
478        // indices, so neither is a subsingleton and neither may reach `Type`. That restriction is
479        // the firewall, and `Classical_choice` is the declared, visible way through it.
480        for ind in ["Or", "Ex"] {
481            let (ty, body) = crate::recursor::derive_recursor(ctx, ind)
482                .unwrap_or_else(|e| panic!("`{ind}`'s eliminator must derive: {e:?}"));
483            ctx.add_definition(format!("{ind}_rec"), ty, body);
484        }
485
486        // ═══ THE CLASSICAL LAYER, DERIVED — Lean's `Init/Classical.lean`, ported ═══════════
487        //
488        // Lean's trusted base is THREE axioms and excluded middle is not one of them:
489        // `Classical.em` is **Diaconescu's theorem**, proved from `Classical.choice`, `funext`
490        // and `propext` at `Init/Classical.lean:32-63`, and `Classical.byContradiction` — our
491        // `dne` — is two further steps downstream of it (`Init/Classical.lean:131`, through
492        // `propDecidable` at :75). LOGOS used to ASSUME `dne`: the same classical content,
493        // bought instead of proved, standing as a fourth foundational assumption exactly where
494        // the reference implementation has a proof.
495        //
496        // It is a proof here too, and it runs in Lean's own order:
497        //
498        //     Classical_choice ─▶ indefiniteDescription ─▶ choose / choose_spec
499        //                                  │
500        //     funext + propext ────────────┴─▶ em (Diaconescu) ─▶ propDecidable ─▶ dne
501        //
502        // so `dne` is the LAST link rather than the first, and the FOUNDATIONAL fragment of the
503        // trusted base is now exactly `propext`, `Classical_choice` and `Quot_sound` — Lean's
504        // three, under LOGOS spellings, and not one more.
505        //
506        // The firewall is unchanged and is still structural: `Or` has two constructors, so
507        // `Or_rec`'s motive stays in `Prop` and `p ∨ ¬p` still cannot be eliminated into
508        // `Decidable p`. `propDecidable` crosses `Prop → Type` by APPLYING `Classical_choice`,
509        // which is the one declared, visible way through, and it is now the only one: nothing
510        // below reaches for a second.
511
512        // ---- Classical.indefiniteDescription (Init/Classical.lean:15) ---------------------
513        //
514        //   indefiniteDescription : Π(A:Type). Π(p:A→Prop). Ex A p → Subtype A p
515        //     := λA p h. Classical_choice (Subtype A p)
516        //                  (Ex_rec A p (λ_. Nonempty (Subtype A p))
517        //                              (λw hw. Nonempty_intro (Subtype A p) (Subtype_mk A p w hw))
518        //                              h)
519        //
520        // `Ex_rec` at a `Prop` motive is SMALL elimination and needs no axiom; the `Prop → Type`
521        // step is `Classical_choice`, applied once, in the open.
522        let pred_ty = || arrow_(v_("A"), prop());
523        let sub_ap = || apps_(gl("Subtype"), &[v_("A"), v_("p")]);
524        let ex_ap = || apps_(gl("Ex"), &[v_("A"), v_("p")]);
525        ctx.add_definition(
526            "Classical_indefiniteDescription".to_string(),
527            pi_("A", type0(), pi_("p", pred_ty(), arrow_(ex_ap(), sub_ap()))),
528            lam_(
529                "A",
530                type0(),
531                lam_(
532                    "p",
533                    pred_ty(),
534                    lam_(
535                        "hex",
536                        ex_ap(),
537                        apps_(
538                            gl("Classical_choice"),
539                            &[
540                                sub_ap(),
541                                apps_(
542                                    gl("Ex_rec"),
543                                    &[
544                                        v_("A"),
545                                        v_("p"),
546                                        lam_(
547                                            "_e",
548                                            ex_ap(),
549                                            Term::App(Box::new(gl("Nonempty")), Box::new(sub_ap())),
550                                        ),
551                                        lam_(
552                                            "w",
553                                            v_("A"),
554                                            lam_(
555                                                "hw",
556                                                Term::App(Box::new(v_("p")), Box::new(v_("w"))),
557                                                apps_(
558                                                    gl("Nonempty_intro"),
559                                                    &[
560                                                        sub_ap(),
561                                                        apps_(
562                                                            gl("Subtype_mk"),
563                                                            &[v_("A"), v_("p"), v_("w"), v_("hw")],
564                                                        ),
565                                                    ],
566                                                ),
567                                            ),
568                                        ),
569                                        v_("hex"),
570                                    ],
571                                ),
572                            ],
573                        ),
574                    ),
575                ),
576            ),
577        );
578
579        // ---- Classical.choose / choose_spec (Init/Classical.lean:25, :28) -----------------
580        //
581        // The `val`/`property` projections of the subtype `indefiniteDescription` picked. They
582        // COMPUTE: both are structure projections over a constructor form once the existence
583        // proof is concrete, which is why `choose` is a function and not a name.
584        let indef_at = || {
585            apps_(
586                gl("Classical_indefiniteDescription"),
587                &[v_("A"), v_("p"), v_("hex")],
588            )
589        };
590        ctx.add_definition(
591            "Classical_choose".to_string(),
592            pi_("A", type0(), pi_("p", pred_ty(), arrow_(ex_ap(), v_("A")))),
593            lam_(
594                "A",
595                type0(),
596                lam_(
597                    "p",
598                    pred_ty(),
599                    lam_(
600                        "hex",
601                        ex_ap(),
602                        apps_(gl("Subtype_val"), &[v_("A"), v_("p"), indef_at()]),
603                    ),
604                ),
605            ),
606        );
607        ctx.add_definition(
608            "Classical_choose_spec".to_string(),
609            pi_(
610                "A",
611                type0(),
612                pi_(
613                    "p",
614                    pred_ty(),
615                    pi_(
616                        "hex",
617                        ex_ap(),
618                        Term::App(
619                            Box::new(v_("p")),
620                            Box::new(apps_(
621                                gl("Classical_choose"),
622                                &[v_("A"), v_("p"), v_("hex")],
623                            )),
624                        ),
625                    ),
626                ),
627            ),
628            lam_(
629                "A",
630                type0(),
631                lam_(
632                    "p",
633                    pred_ty(),
634                    lam_(
635                        "hex",
636                        ex_ap(),
637                        apps_(gl("Subtype_property"), &[v_("A"), v_("p"), indef_at()]),
638                    ),
639                ),
640            ),
641        );
642
643        // ---- Classical.em — DIACONESCU'S THEOREM (Init/Classical.lean:32-63) --------------
644        //
645        // Lean's proof, term for term. Two predicates on `Prop`,
646        //
647        //     U x := (x = True)  ∨ P          V x := (x = False) ∨ P
648        //
649        // are each inhabited (`True` witnesses `U`, `False` witnesses `V`), so `choose` picks
650        // `u := choose U` and `v := choose V` and `choose_spec` returns `U u` and `V v`.
651        //
652        //   * If either disjunct lands on the right, `P` holds outright.
653        //   * If both land on the left then `u = True` and `v = False`, so `u ≠ v` — the one
654        //     place `True ≠ False` is needed, and it is PROVED by transporting `I : True` along
655        //     `Eq Prop True False` into `False`, not assumed.
656        //   * And `P → u = v`: under `hp : P`, every `U x` and `V x` is inhabited by `Or.inr hp`
657        //     in both directions, so `propext` makes them the SAME proposition pointwise and
658        //     `funext` makes `U` and `V` the same FUNCTION. Substituting along that equality
659        //     carries `choose U e₁ = choose U e₂` — which is `refl`, because the two existence
660        //     proofs are proofs of one proposition and the kernel is proof-irrelevant — to
661        //     `choose U exU = choose V exV`, i.e. `u = v`.
662        //
663        // Contraposing the two gives `¬P` in the first case and `P` in the second.
664        //
665        // NOTHING here is assumed. `propext` and `Classical_choice` are Lean's own axioms;
666        // `funext` is the theorem proved above from `Quot_sound`.
667        let eq_prop = |x: Term, y: Term| eq3(prop(), x, y);
668        let p_prop = || v_("P");
669        let not_p_of = || Term::App(Box::new(gl("Not")), Box::new(v_("P")));
670        // U := λ(x:Prop). Or (Eq Prop x True) P   /   V := λ(x:Prop). Or (Eq Prop x False) P
671        let side = |anchor: &'static str| {
672            lam_(
673                "x",
674                prop(),
675                apps_(gl("Or"), &[eq_prop(v_("x"), gl(anchor)), p_prop()]),
676            )
677        };
678        let u_pred = || side("True");
679        let v_pred = || side("False");
680        // exU : Ex Prop U := witness Prop U True (left (Eq Prop True True) P (refl Prop True))
681        let ex_side = |anchor: &'static str, pred: Term| {
682            apps_(
683                gl("witness"),
684                &[
685                    prop(),
686                    pred,
687                    gl(anchor),
688                    apps_(
689                        gl("left"),
690                        &[
691                            eq_prop(gl(anchor), gl(anchor)),
692                            p_prop(),
693                            apps_(gl("refl"), &[prop(), gl(anchor)]),
694                        ],
695                    ),
696                ],
697            )
698        };
699        let ex_u = || ex_side("True", u_pred());
700        let ex_v = || ex_side("False", v_pred());
701        let chosen = |pred: Term, ex: Term| apps_(gl("Classical_choose"), &[prop(), pred, ex]);
702        let u_of = || chosen(u_pred(), ex_u());
703        let v_of = || chosen(v_pred(), ex_v());
704        let spec = |pred: Term, ex: Term| apps_(gl("Classical_choose_spec"), &[prop(), pred, ex]);
705        let not_uv = || Term::App(Box::new(gl("Not")), Box::new(eq_prop(u_of(), v_of())));
706        let disj = || apps_(gl("Or"), &[not_uv(), p_prop()]);
707
708        // `True = False → False`, by transport. `Eq_rec_dep`'s motive lands in `Prop` by
709        // cumulativity, and `(λ(y:Prop). λ_. y) True refl ≡ True` is the `I` slot.
710        let true_ne_false = |witness_eq: Term| {
711            apps_(
712                gl("Eq_rec_dep"),
713                &[
714                    prop(),
715                    gl("True"),
716                    lam_(
717                        "y",
718                        prop(),
719                        lam_("_hy", eq_prop(gl("True"), v_("y")), v_("y")),
720                    ),
721                    gl("I"),
722                    gl("False"),
723                    witness_eq,
724                ],
725            )
726        };
727        // u = True, u = v, v = False  ⟹  True = False
728        let true_eq_false = apps_(
729            gl("Eq_trans"),
730            &[
731                prop(),
732                gl("True"),
733                u_of(),
734                gl("False"),
735                apps_(gl("Eq_sym"), &[prop(), u_of(), gl("True"), v_("hut")]),
736                apps_(
737                    gl("Eq_trans"),
738                    &[prop(), u_of(), v_of(), gl("False"), v_("huv"), v_("hvf")],
739                ),
740            ],
741        );
742        // not_uv_or_p : Or (¬(u = v)) P
743        let not_uv_or_p = apps_(
744            gl("Or_rec"),
745            &[
746                eq_prop(u_of(), gl("True")),
747                p_prop(),
748                lam_(
749                    "_du",
750                    apps_(gl("Or"), &[eq_prop(u_of(), gl("True")), p_prop()]),
751                    disj(),
752                ),
753                lam_(
754                    "hut",
755                    eq_prop(u_of(), gl("True")),
756                    apps_(
757                        gl("Or_rec"),
758                        &[
759                            eq_prop(v_of(), gl("False")),
760                            p_prop(),
761                            lam_(
762                                "_dv",
763                                apps_(gl("Or"), &[eq_prop(v_of(), gl("False")), p_prop()]),
764                                disj(),
765                            ),
766                            lam_(
767                                "hvf",
768                                eq_prop(v_of(), gl("False")),
769                                apps_(
770                                    gl("left"),
771                                    &[
772                                        not_uv(),
773                                        p_prop(),
774                                        lam_(
775                                            "huv",
776                                            eq_prop(u_of(), v_of()),
777                                            true_ne_false(true_eq_false),
778                                        ),
779                                    ],
780                                ),
781                            ),
782                            lam_(
783                                "hpv",
784                                p_prop(),
785                                apps_(gl("right"), &[not_uv(), p_prop(), v_("hpv")]),
786                            ),
787                            spec(v_pred(), ex_v()),
788                        ],
789                    ),
790                ),
791                lam_(
792                    "hpu",
793                    p_prop(),
794                    apps_(gl("right"), &[not_uv(), p_prop(), v_("hpu")]),
795                ),
796                spec(u_pred(), ex_u()),
797            ],
798        );
799
800        // p_implies_uv : P → Eq Prop u v
801        let prop_fn = || pi_("x", prop(), prop());
802        let iff_both_right = apps_(
803            gl("conj"),
804            &[
805                arrow_(
806                    Term::App(Box::new(u_pred()), Box::new(v_("x"))),
807                    Term::App(Box::new(v_pred()), Box::new(v_("x"))),
808                ),
809                arrow_(
810                    Term::App(Box::new(v_pred()), Box::new(v_("x"))),
811                    Term::App(Box::new(u_pred()), Box::new(v_("x"))),
812                ),
813                lam_(
814                    "_fu",
815                    Term::App(Box::new(u_pred()), Box::new(v_("x"))),
816                    apps_(
817                        gl("right"),
818                        &[eq_prop(v_("x"), gl("False")), p_prop(), v_("hp")],
819                    ),
820                ),
821                lam_(
822                    "_fv",
823                    Term::App(Box::new(v_pred()), Box::new(v_("x"))),
824                    apps_(
825                        gl("right"),
826                        &[eq_prop(v_("x"), gl("True")), p_prop(), v_("hp")],
827                    ),
828                ),
829            ],
830        );
831        // hpred : Eq (Prop → Prop) U V
832        let hpred = apps_(
833            gl("funext"),
834            &[
835                prop(),
836                lam_("_bx", prop(), prop()),
837                u_pred(),
838                v_pred(),
839                lam_(
840                    "x",
841                    prop(),
842                    apps_(
843                        gl("propext"),
844                        &[
845                            Term::App(Box::new(u_pred()), Box::new(v_("x"))),
846                            Term::App(Box::new(v_pred()), Box::new(v_("x"))),
847                            iff_both_right,
848                        ],
849                    ),
850                ),
851            ],
852        );
853        // The motive: for ANY W equal to U, the choice made from U and the choice made from W
854        // agree — quantified over both existence proofs, because they are what the two `choose`
855        // calls differ in and proof irrelevance is what closes the base case.
856        let ex_of = |w: Term| apps_(gl("Ex"), &[prop(), w]);
857        let agree_motive = lam_(
858            "W",
859            prop_fn(),
860            lam_(
861                "_hw",
862                eq3(prop_fn(), u_pred(), v_("W")),
863                pi_(
864                    "e1",
865                    ex_of(u_pred()),
866                    pi_(
867                        "e2",
868                        ex_of(v_("W")),
869                        eq_prop(chosen(u_pred(), v_("e1")), chosen(v_("W"), v_("e2"))),
870                    ),
871                ),
872            ),
873        );
874        let agree_base = lam_(
875            "e1",
876            ex_of(u_pred()),
877            lam_(
878                "e2",
879                ex_of(u_pred()),
880                apps_(gl("refl"), &[prop(), chosen(u_pred(), v_("e1"))]),
881            ),
882        );
883        let p_implies_uv = apps_(
884            apps_(
885                gl("Eq_rec_dep"),
886                &[
887                    prop_fn(),
888                    u_pred(),
889                    agree_motive,
890                    agree_base,
891                    v_pred(),
892                    hpred,
893                ],
894            ),
895            &[ex_u(), ex_v()],
896        );
897        let em_body = lam_(
898            "P",
899            prop(),
900            apps_(
901                gl("Or_rec"),
902                &[
903                    not_uv(),
904                    p_prop(),
905                    lam_("_dd", disj(), apps_(gl("Or"), &[p_prop(), not_p_of()])),
906                    lam_(
907                        "hne",
908                        not_uv(),
909                        apps_(
910                            gl("right"),
911                            &[
912                                p_prop(),
913                                not_p_of(),
914                                lam_(
915                                    "hp",
916                                    p_prop(),
917                                    Term::App(Box::new(v_("hne")), Box::new(p_implies_uv)),
918                                ),
919                            ],
920                        ),
921                    ),
922                    lam_(
923                        "hpp",
924                        p_prop(),
925                        apps_(gl("left"), &[p_prop(), not_p_of(), v_("hpp")]),
926                    ),
927                    not_uv_or_p,
928                ],
929            ),
930        );
931        ctx.add_definition(
932            "Classical_em".to_string(),
933            pi_("P", prop(), apps_(gl("Or"), &[p_prop(), not_p_of()])),
934            em_body,
935        );
936
937        // ---- Classical.propDecidable (Init/Classical.lean:75) ------------------------------
938        //
939        //   propDecidable a := choice <| match em a with
940        //                                | Or.inl h => ⟨isTrue h⟩
941        //                                | Or.inr h => ⟨isFalse h⟩
942        //
943        // Lean's proof, unchanged: `Or_rec` at the `Prop` motive `Nonempty (Decidable p)` (legal
944        // — `Nonempty` is a proposition), then one `Classical_choice` to cross into `Type`.
945        let dec_p = || Term::App(Box::new(gl("Decidable")), Box::new(v_("p")));
946        let ne_dec = || Term::App(Box::new(gl("Nonempty")), Box::new(dec_p()));
947        let intro = |d: Term| apps_(gl("Nonempty_intro"), &[dec_p(), d]);
948        let not_p_v = || Term::App(Box::new(gl("Not")), Box::new(v_("p")));
949        let or_p_v = || apps_(gl("Or"), &[v_("p"), not_p_v()]);
950        ctx.add_definition(
951            "Classical_propDecidable".to_string(),
952            pi_("p", prop(), dec_p()),
953            lam_(
954                "p",
955                prop(),
956                apps_(
957                    gl("Classical_choice"),
958                    &[
959                        dec_p(),
960                        apps_(
961                            gl("Or_rec"),
962                            &[
963                                v_("p"),
964                                not_p_v(),
965                                lam_("_dp", or_p_v(), ne_dec()),
966                                lam_(
967                                    "hyes",
968                                    v_("p"),
969                                    intro(apps_(gl("isTrue"), &[v_("p"), v_("hyes")])),
970                                ),
971                                lam_(
972                                    "hno",
973                                    not_p_v(),
974                                    intro(apps_(gl("isFalse"), &[v_("p"), v_("hno")])),
975                                ),
976                                Term::App(Box::new(gl("Classical_em")), Box::new(v_("p"))),
977                            ],
978                        ),
979                    ],
980                ),
981            ),
982        );
983
984        // ---- dne — Lean's `Classical.byContradiction` (Init/Classical.lean:131) ------------
985        //
986        //   byContradiction (h : ¬p → False) : p := Decidable.byContradiction (dec := propDecidable _) h
987        //
988        // `dne : Π(P:Prop). ¬¬P → P` is the LOGOS spelling and it is now a THEOREM. It was the
989        // prelude's one home-grown classical axiom, and it is gone from the trusted base: the
990        // blanket `Decidable` instance decides `P`, the `isTrue` branch returns the proof and
991        // the `isFalse` branch feeds the refutation to the double negation and eliminates the
992        // resulting `False` into `P` with a zero-case `Match` (small elimination, no constant).
993        let dne_p = || v_("P");
994        let not_dne = || arrow_(dne_p(), gl("False"));
995        let dne_body = lam_(
996            "P",
997            prop(),
998            lam_(
999                "hnn",
1000                arrow_(not_dne(), gl("False")),
1001                apps_(
1002                    gl("Decidable_rec"),
1003                    &[
1004                        dne_p(),
1005                        lam_(
1006                            "_dd",
1007                            Term::App(Box::new(gl("Decidable")), Box::new(dne_p())),
1008                            dne_p(),
1009                        ),
1010                        lam_("hyes", dne_p(), v_("hyes")),
1011                        lam_(
1012                            "hno",
1013                            Term::App(Box::new(gl("Not")), Box::new(dne_p())),
1014                            Term::Match {
1015                                discriminant: Box::new(Term::App(
1016                                    Box::new(v_("hnn")),
1017                                    Box::new(v_("hno")),
1018                                )),
1019                                motive: Box::new(lam_("_hf", gl("False"), dne_p())),
1020                                cases: vec![],
1021                            },
1022                        ),
1023                        Term::App(Box::new(gl("Classical_propDecidable")), Box::new(dne_p())),
1024                    ],
1025                ),
1026            ),
1027        );
1028        ctx.add_definition(
1029            "dne".to_string(),
1030            pi_("P", prop(), arrow_(arrow_(not_dne(), gl("False")), dne_p())),
1031            dne_body,
1032        );
1033
1034        // Classical_axiomOfChoice — Skolemisation, in Lean's dependent shape:
1035        //
1036        //   Π(A:Type). Π(B:A→Type). Π(r : Π(x:A). B x → Prop).
1037        //     (Π(x:A). Ex (B x) (r x)) → Ex (Π(x:A). B x) (λf. Π(x:A). r x (f x))
1038        //
1039        // It produces a FUNCTION, which is why the `Prop`-only `dne` fragment cannot reach it: the
1040        // witness has to be chosen at every point at once. Proved, not assumed — each `Ex` is
1041        // turned into a `Nonempty (Subtype …)` by `Ex_rec` at a `Prop` motive (legal), `choice`
1042        // picks the subtype element (the one classical step), and its `val`/`property`
1043        // projections COMPUTE the function and its specification.
1044        let b_at = |x: Term| Term::App(Box::new(v_("B")), Box::new(x));
1045        let r_at = |x: Term, y: Term| apps_(v_("r"), &[x, y]);
1046        let sub_x = || {
1047            apps_(
1048                gl("Subtype"),
1049                &[
1050                    b_at(v_("x")),
1051                    Term::App(Box::new(v_("r")), Box::new(v_("x"))),
1052                ],
1053            )
1054        };
1055        let ex_at = |x: Term| {
1056            apps_(
1057                gl("Ex"),
1058                &[b_at(x.clone()), Term::App(Box::new(v_("r")), Box::new(x))],
1059            )
1060        };
1061        // ne x : Nonempty (Subtype (B x) (r x))
1062        let ne_x = apps_(
1063            gl("Ex_rec"),
1064            &[
1065                b_at(v_("x")),
1066                Term::App(Box::new(v_("r")), Box::new(v_("x"))),
1067                lam_(
1068                    "_",
1069                    ex_at(v_("x")),
1070                    Term::App(Box::new(gl("Nonempty")), Box::new(sub_x())),
1071                ),
1072                lam_(
1073                    "y",
1074                    b_at(v_("x")),
1075                    lam_(
1076                        "hy",
1077                        r_at(v_("x"), v_("y")),
1078                        apps_(
1079                            gl("Nonempty_intro"),
1080                            &[
1081                                sub_x(),
1082                                apps_(
1083                                    gl("Subtype_mk"),
1084                                    &[
1085                                        b_at(v_("x")),
1086                                        Term::App(Box::new(v_("r")), Box::new(v_("x"))),
1087                                        v_("y"),
1088                                        v_("hy"),
1089                                    ],
1090                                ),
1091                            ],
1092                        ),
1093                    ),
1094                ),
1095                Term::App(Box::new(v_("h")), Box::new(v_("x"))),
1096            ],
1097        );
1098        // pick x : Subtype (B x) (r x)
1099        let pick = apps_(gl("Classical_choice"), &[sub_x(), ne_x]);
1100        let proj = |field: &str| {
1101            apps_(
1102                gl(field),
1103                &[
1104                    b_at(v_("x")),
1105                    Term::App(Box::new(v_("r")), Box::new(v_("x"))),
1106                    pick.clone(),
1107                ],
1108            )
1109        };
1110        let chosen_fn = lam_("x", v_("A"), proj("Subtype_val"));
1111        let chosen_spec = lam_("x", v_("A"), proj("Subtype_property"));
1112        let fn_ty = || pi_("x", v_("A"), b_at(v_("x")));
1113        let spec_pred = || {
1114            lam_(
1115                "f",
1116                fn_ty(),
1117                pi_(
1118                    "x",
1119                    v_("A"),
1120                    r_at(v_("x"), Term::App(Box::new(v_("f")), Box::new(v_("x")))),
1121                ),
1122            )
1123        };
1124        let rel_ty = || pi_("x", v_("A"), arrow_(b_at(v_("x")), prop()));
1125        let hyp_ty = || pi_("x", v_("A"), ex_at(v_("x")));
1126        ctx.add_definition(
1127            "Classical_axiomOfChoice".to_string(),
1128            pi_(
1129                "A",
1130                type0(),
1131                pi_(
1132                    "B",
1133                    pi_("_x", v_("A"), type0()),
1134                    pi_(
1135                        "r",
1136                        rel_ty(),
1137                        arrow_(hyp_ty(), apps_(gl("Ex"), &[fn_ty(), spec_pred()])),
1138                    ),
1139                ),
1140            ),
1141            lam_(
1142                "A",
1143                type0(),
1144                lam_(
1145                    "B",
1146                    pi_("_x", v_("A"), type0()),
1147                    lam_(
1148                        "r",
1149                        rel_ty(),
1150                        lam_(
1151                            "h",
1152                            hyp_ty(),
1153                            apps_(
1154                                gl("witness"),
1155                                &[fn_ty(), spec_pred(), chosen_fn, chosen_spec],
1156                            ),
1157                        ),
1158                    ),
1159                ),
1160            ),
1161        );
1162    }
1163
1164    /// The commutative-ring axioms for `Int` — the ENTIRE trusted arithmetic base.
1165    ///
1166    /// `Int` is an opaque type (no constructors, `register_primitives`), so these
1167    /// standard ring laws are not derivable in-kernel; they are the axiomatization
1168    /// of `(Int, add, mul, 0, 1)` as a commutative ring — the textbook foundation,
1169    /// not a soundness shortcut. The proof-producing arithmetic procedure builds
1170    /// every arithmetic proof from these (closed/literal goals need none — they
1171    /// hold by `add`/`mul` computation + `refl`). They are the *only* arithmetic
1172    /// things trusted beyond the kernel; `phase98`'s TCB-inventory test locks the
1173    /// exact set so it can never silently grow. Replaceable later (without any
1174    /// downstream churn) by defining `Int` from `Nat` and proving them.
1175    fn register_int_ring_axioms(ctx: &mut Context) {
1176        let int = || Term::Global("Int".to_string());
1177        let lit = |n: i64| Term::Lit(Literal::Int(n));
1178        // (op a b)
1179        let bin = |op: &str, a: Term, b: Term| {
1180            Term::App(
1181                Box::new(Term::App(
1182                    Box::new(Term::Global(op.to_string())),
1183                    Box::new(a),
1184                )),
1185                Box::new(b),
1186            )
1187        };
1188        // Eq Int l r
1189        let eq_int = |l: Term, r: Term| {
1190            Term::App(
1191                Box::new(Term::App(
1192                    Box::new(Term::App(
1193                        Box::new(Term::Global("Eq".to_string())),
1194                        Box::new(Term::Global("Int".to_string())),
1195                    )),
1196                    Box::new(l),
1197                )),
1198                Box::new(r),
1199            )
1200        };
1201        // Π over the given Int-typed parameter names, body = eq.
1202        let forall_ints = |names: &[&str], body: Term| {
1203            names.iter().rev().fold(body, |acc, name| Term::Pi {
1204                param: name.to_string(),
1205                param_type: Box::new(int()),
1206                body_type: Box::new(acc),
1207            })
1208        };
1209        let v = |s: &str| Term::Var(s.to_string());
1210
1211        // add_comm : Π a b. Eq Int (add a b) (add b a)
1212        ctx.add_declaration(
1213            "add_comm",
1214            forall_ints(
1215                &["a", "b"],
1216                eq_int(bin("add", v("a"), v("b")), bin("add", v("b"), v("a"))),
1217            ),
1218        );
1219        // add_assoc : Π a b c. Eq Int (add (add a b) c) (add a (add b c))
1220        ctx.add_declaration(
1221            "add_assoc",
1222            forall_ints(
1223                &["a", "b", "c"],
1224                eq_int(
1225                    bin("add", bin("add", v("a"), v("b")), v("c")),
1226                    bin("add", v("a"), bin("add", v("b"), v("c"))),
1227                ),
1228            ),
1229        );
1230        // add_zero : Π a. Eq Int (add a 0) a
1231        ctx.add_declaration(
1232            "add_zero",
1233            forall_ints(&["a"], eq_int(bin("add", v("a"), lit(0)), v("a"))),
1234        );
1235        // mul_comm : Π a b. Eq Int (mul a b) (mul b a)
1236        ctx.add_declaration(
1237            "mul_comm",
1238            forall_ints(
1239                &["a", "b"],
1240                eq_int(bin("mul", v("a"), v("b")), bin("mul", v("b"), v("a"))),
1241            ),
1242        );
1243        // mul_assoc : Π a b c. Eq Int (mul (mul a b) c) (mul a (mul b c))
1244        ctx.add_declaration(
1245            "mul_assoc",
1246            forall_ints(
1247                &["a", "b", "c"],
1248                eq_int(
1249                    bin("mul", bin("mul", v("a"), v("b")), v("c")),
1250                    bin("mul", v("a"), bin("mul", v("b"), v("c"))),
1251                ),
1252            ),
1253        );
1254        // mul_one : Π a. Eq Int (mul a 1) a
1255        ctx.add_declaration(
1256            "mul_one",
1257            forall_ints(&["a"], eq_int(bin("mul", v("a"), lit(1)), v("a"))),
1258        );
1259        // mul_zero : Π a. Eq Int (mul a 0) 0. Not derivable from the others without
1260        // an additive-inverse axiom; needed so the normalizer can drop a monomial
1261        // whose coefficient cancels to zero (e.g. in a Farkas combination).
1262        ctx.add_declaration(
1263            "mul_zero",
1264            forall_ints(&["a"], eq_int(bin("mul", v("a"), lit(0)), lit(0))),
1265        );
1266        // mul_distrib_add : Π a b c. Eq Int (mul a (add b c)) (add (mul a b) (mul a c))
1267        ctx.add_declaration(
1268            "mul_distrib_add",
1269            forall_ints(
1270                &["a", "b", "c"],
1271                eq_int(
1272                    bin("mul", v("a"), bin("add", v("b"), v("c"))),
1273                    bin(
1274                        "add",
1275                        bin("mul", v("a"), v("b")),
1276                        bin("mul", v("a"), v("c")),
1277                    ),
1278                ),
1279            ),
1280        );
1281        // sub_elim : Π a b. Eq Int (sub a b) (add a (mul (-1) b)). Subtraction defined over the ring.
1282        // `sub` is a primitive with only literal reduction (`sub 5 3 ⇝ 2`), so a symbolic `sub a b`
1283        // stays stuck; this lets the normalizer prove identities written with `sub` by rewriting it to
1284        // the `add`/`mul` vocabulary it decides. Asserted like `mul_zero` (true in ℤ, not derivable from
1285        // the multiplicative/additive laws without it).
1286        ctx.add_declaration(
1287            "sub_elim",
1288            forall_ints(
1289                &["a", "b"],
1290                eq_int(
1291                    bin("sub", v("a"), v("b")),
1292                    bin("add", v("a"), bin("mul", lit(-1), v("b"))),
1293                ),
1294            ),
1295        );
1296    }
1297
1298    /// The standard order axioms for `Int`, completing the ordered-ring trusted
1299    /// base. `Int` is opaque, so just as the ring laws are axioms here (Coq `Int63`
1300    /// / Lean primitives), the order laws are too: reflexivity, transitivity,
1301    /// monotone addition, and scaling by a non-negative factor — the primitives a
1302    /// Farkas linear-arithmetic certificate is reconstructed from. `m ≤ n` is the
1303    /// shallow `Eq Bool (le m n) true` (decidable by computation on literals, see
1304    /// `reduction.rs`); these axioms extend it to the symbolic case. Replaceable
1305    /// later (no downstream churn) by defining `≤` from `Nat` and proving them.
1306    /// Locked by `phase98`'s TCB inventory.
1307    fn register_int_order_axioms(ctx: &mut Context) {
1308        let int = || Term::Global("Int".to_string());
1309        let v = |s: &str| Term::Var(s.to_string());
1310        let g = |s: &str| Term::Global(s.to_string());
1311        let lit = |n: i64| Term::Lit(Literal::Int(n));
1312        let bin = |op: &str, a: Term, b: Term| {
1313            Term::App(
1314                Box::new(Term::App(
1315                    Box::new(Term::Global(op.to_string())),
1316                    Box::new(a),
1317                )),
1318                Box::new(b),
1319            )
1320        };
1321        // le_prop a b = Eq Bool (le a b) true  — the shallow `a ≤ b`.
1322        let le_prop = |a: Term, b: Term| {
1323            Term::App(
1324                Box::new(Term::App(
1325                    Box::new(Term::App(Box::new(g("Eq")), Box::new(g("Bool")))),
1326                    Box::new(bin("le", a, b)),
1327                )),
1328                Box::new(g("true")),
1329            )
1330        };
1331        let arrow = |dom: Term, cod: Term| Term::Pi {
1332            param: "_".to_string(),
1333            param_type: Box::new(dom),
1334            body_type: Box::new(cod),
1335        };
1336        let forall_ints = |names: &[&str], body: Term| {
1337            names.iter().rev().fold(body, |acc, name| Term::Pi {
1338                param: name.to_string(),
1339                param_type: Box::new(int()),
1340                body_type: Box::new(acc),
1341            })
1342        };
1343
1344        // le_refl : Π a. a ≤ a
1345        ctx.add_declaration("le_refl", forall_ints(&["a"], le_prop(v("a"), v("a"))));
1346        // le_trans : Π a b c. a ≤ b → b ≤ c → a ≤ c
1347        ctx.add_declaration(
1348            "le_trans",
1349            forall_ints(
1350                &["a", "b", "c"],
1351                arrow(
1352                    le_prop(v("a"), v("b")),
1353                    arrow(le_prop(v("b"), v("c")), le_prop(v("a"), v("c"))),
1354                ),
1355            ),
1356        );
1357        // le_add_mono : Π a b c d. a ≤ b → c ≤ d → (a + c) ≤ (b + d)
1358        ctx.add_declaration(
1359            "le_add_mono",
1360            forall_ints(
1361                &["a", "b", "c", "d"],
1362                arrow(
1363                    le_prop(v("a"), v("b")),
1364                    arrow(
1365                        le_prop(v("c"), v("d")),
1366                        le_prop(bin("add", v("a"), v("c")), bin("add", v("b"), v("d"))),
1367                    ),
1368                ),
1369            ),
1370        );
1371        // le_mul_nonneg : Π k a b. 0 ≤ k → a ≤ b → (k * a) ≤ (k * b)
1372        ctx.add_declaration(
1373            "le_mul_nonneg",
1374            forall_ints(
1375                &["k", "a", "b"],
1376                arrow(
1377                    le_prop(lit(0), v("k")),
1378                    arrow(
1379                        le_prop(v("a"), v("b")),
1380                        le_prop(bin("mul", v("k"), v("a")), bin("mul", v("k"), v("b"))),
1381                    ),
1382                ),
1383            ),
1384        );
1385        // le_sub : Π a b. a ≤ b → 0 ≤ b + (-1)·a   (the Farkas "move to one side").
1386        // Written with add/mul (not sub) so the ring oracle, whose axioms are over
1387        // add/mul, can prove the combined-term equalities during reconstruction.
1388        ctx.add_declaration(
1389            "le_sub",
1390            forall_ints(
1391                &["a", "b"],
1392                arrow(
1393                    le_prop(v("a"), v("b")),
1394                    le_prop(lit(0), bin("add", v("b"), bin("mul", lit(-1), v("a")))),
1395                ),
1396            ),
1397        );
1398
1399        // lt_prop a b = Eq Bool (lt a b) true  — the shallow `a < b`.
1400        let lt_prop = |a: Term, b: Term| {
1401            Term::App(
1402                Box::new(Term::App(
1403                    Box::new(Term::App(Box::new(g("Eq")), Box::new(g("Bool")))),
1404                    Box::new(bin("lt", a, b)),
1405                )),
1406                Box::new(g("true")),
1407            )
1408        };
1409        // lt_succ_le : Π a b. a < b → (a + 1) ≤ b, and its converse le_succ_lt.  Integer
1410        // DISCRETENESS — the fact rational Fourier-Motzkin lacks: over ℤ a strict `<` is a `≤`
1411        // shifted by one, so nothing lives strictly between `a` and `a+1`. It is what lets
1412        // `omega` refute strict systems the rational solver reports satisfiable
1413        // (`x < y ∧ y < x+1`), and it is discharged by ordinary Farkas afterward.
1414        //
1415        // BOTH DIRECTIONS ARE `λa b h. h`, and that is the whole point. `lt` is no longer an
1416        // opaque primitive: it is DEFINED as `le (a + 1) b` in `register_primitives`, so
1417        // `Eq Bool (lt a b) true` and `Eq Bool (le (a+1) b) true` are the SAME proposition up to
1418        // δβ and the identity inhabits each from the other. Wave 1 assumed the forward direction
1419        // as an axiom and the backward one was simply missing, which is why no `Int` order axiom
1420        // could CONCLUDE a strict `<` and `calc` could not compose a mixed `≤`/`<` chain
1421        // (T08-021). Both are now kernel-checked theorems and the trusted base is two smaller.
1422        let ident_proof = |premise: Term| Term::Lambda {
1423            param: "a".to_string(),
1424            param_type: Box::new(int()),
1425            body: Box::new(Term::Lambda {
1426                param: "b".to_string(),
1427                param_type: Box::new(int()),
1428                body: Box::new(Term::Lambda {
1429                    param: "h".to_string(),
1430                    param_type: Box::new(premise),
1431                    body: Box::new(v("h")),
1432                }),
1433            }),
1434        };
1435        ctx.add_definition(
1436            "lt_succ_le".to_string(),
1437            forall_ints(
1438                &["a", "b"],
1439                arrow(
1440                    lt_prop(v("a"), v("b")),
1441                    le_prop(bin("add", v("a"), lit(1)), v("b")),
1442                ),
1443            ),
1444            ident_proof(lt_prop(v("a"), v("b"))),
1445        );
1446        // le_succ_lt : Π a b. (a + 1) ≤ b → a < b.  The direction that CONCLUDES a `<`, which no
1447        // assumed order law had: `lt_succ_le` and `lt_add1_le` both take one as a premise.
1448        ctx.add_definition(
1449            "le_succ_lt".to_string(),
1450            forall_ints(
1451                &["a", "b"],
1452                arrow(
1453                    le_prop(bin("add", v("a"), lit(1)), v("b")),
1454                    lt_prop(v("a"), v("b")),
1455                ),
1456            ),
1457            ident_proof(le_prop(bin("add", v("a"), lit(1)), v("b"))),
1458        );
1459        // lt_add1_le : Π a b. a < (b + 1) → a ≤ b.  The upper-side companion of
1460        // `lt_succ_le` (`a < b+1 ⟺ a ≤ b` over ℤ): when the strict bound already has
1461        // the shape `b + 1`, this yields the CANCELLED `a ≤ b` directly instead of the
1462        // constant-laden `a + 1 ≤ b + 1`, keeping the reconstructed Farkas terms small.
1463        ctx.add_declaration(
1464            "lt_add1_le",
1465            forall_ints(
1466                &["a", "b"],
1467                arrow(
1468                    lt_prop(v("a"), bin("add", v("b"), lit(1))),
1469                    le_prop(v("a"), v("b")),
1470                ),
1471            ),
1472        );
1473        // le_total : Π a b. (a ≤ b) ∨ (b ≤ a).  Linear order totality — the case-split
1474        // seam for disequality (`a ≠ b` ⟹ split `a < b ∨ b < a`) and for reducing a
1475        // positive `≤` goal to a refutation of its negation.
1476        let or = |p: Term, q: Term| {
1477            Term::App(
1478                Box::new(Term::App(Box::new(g("Or")), Box::new(p))),
1479                Box::new(q),
1480            )
1481        };
1482        ctx.add_declaration(
1483            "le_total",
1484            forall_ints(
1485                &["a", "b"],
1486                or(le_prop(v("a"), v("b")), le_prop(v("b"), v("a"))),
1487            ),
1488        );
1489    }
1490
1491    /// Primitive types and operations.
1492    ///
1493    /// Int : Type 0 (64-bit signed integer)
1494    /// Float : Type 0 (64-bit floating point)
1495    /// Text : Type 0 (UTF-8 string)
1496    /// Duration : Type 0 (nanoseconds, i64 - physical time)
1497    /// Date : Type 0 (days since epoch, i32 - calendar date)
1498    /// Moment : Type 0 (nanoseconds since epoch, i64 - instant in UTC)
1499    ///
1500    /// add, sub, mul, div, mod : Int -> Int -> Int
1501    fn register_primitives(ctx: &mut Context) {
1502        // Opaque types (no constructors, cannot be pattern-matched)
1503        ctx.add_inductive("Int", Term::Sort(Universe::Type(0)));
1504        ctx.add_inductive("Float", Term::Sort(Universe::Type(0)));
1505        ctx.add_inductive("Text", Term::Sort(Universe::Type(0)));
1506
1507        // Temporal types (opaque, no constructors)
1508        ctx.add_inductive("Duration", Term::Sort(Universe::Type(0)));
1509        ctx.add_inductive("Date", Term::Sort(Universe::Type(0)));
1510        ctx.add_inductive("Moment", Term::Sort(Universe::Type(0)));
1511
1512        let int = Term::Global("Int".to_string());
1513
1514        // Binary Int -> Int -> Int type
1515        let bin_int_type = Term::Pi {
1516            param: "_".to_string(),
1517            param_type: Box::new(int.clone()),
1518            body_type: Box::new(Term::Pi {
1519                param: "_".to_string(),
1520                param_type: Box::new(int.clone()),
1521                body_type: Box::new(int.clone()),
1522            }),
1523        };
1524
1525        // Register arithmetic builtins as declarations (axioms with computational behavior)
1526        ctx.add_declaration("add", bin_int_type.clone());
1527        ctx.add_declaration("sub", bin_int_type.clone());
1528        ctx.add_declaration("mul", bin_int_type.clone());
1529        ctx.add_declaration("div", bin_int_type.clone());
1530        ctx.add_declaration("mod", bin_int_type);
1531
1532        // Comparison builtins: Int -> Int -> Bool, decided by computation on
1533        // literals (see `reduction.rs`). `Eq Bool (le m n) true` is the shallow
1534        // encoding of `m ≤ n`, provable by `refl` exactly when it holds.
1535        let bin_int_bool_type = Term::Pi {
1536            param: "_".to_string(),
1537            param_type: Box::new(int.clone()),
1538            body_type: Box::new(Term::Pi {
1539                param: "_".to_string(),
1540                param_type: Box::new(int.clone()),
1541                body_type: Box::new(Term::Global("Bool".to_string())),
1542            }),
1543        };
1544        //
1545        // `le` is the ONE opaque order primitive, and the other three are DEFINITIONS written
1546        // from it — which is exactly what Lean does. `Int.lt a b := a + 1 ≤ b` (integer
1547        // discreteness: nothing lives strictly between `a` and `a+1`), `GE.ge a b := LE.le b a`
1548        // and `GT.gt a b := LT.lt b a`. Assuming those three here would be assuming three facts
1549        // the reference implementation *proves*, and it also made `lt_succ_le` — the bridge every
1550        // `omega` refutation of a strict system runs through — an axiom instead of `λa b h. h`.
1551        //
1552        // A body does NOT cost the literal computation: a primitive rule fires on a NAME and both
1553        // kernels already refuse to let one outrank a definition of that name
1554        // (`reduction.rs::try_primitive_reduce`'s `get_definition_body` gate and
1555        // `recheck.rs::shadowed_by_a_definition`), so `lt 2 3` now δβ-unfolds to `le 3 3` and is
1556        // decided by `le`'s rule in BOTH kernels, from ONE specification instead of two copies.
1557        ctx.add_declaration("le", bin_int_bool_type.clone());
1558
1559        let bin_int = |op: &str, x: Term, y: Term| {
1560            Term::App(
1561                Box::new(Term::App(
1562                    Box::new(Term::Global(op.to_string())),
1563                    Box::new(x),
1564                )),
1565                Box::new(y),
1566            )
1567        };
1568        let order_body = |body: Term| Term::Lambda {
1569            param: "a".to_string(),
1570            param_type: Box::new(int.clone()),
1571            body: Box::new(Term::Lambda {
1572                param: "b".to_string(),
1573                param_type: Box::new(int.clone()),
1574                body: Box::new(body),
1575            }),
1576        };
1577        let a = || Term::Var("a".to_string());
1578        let b = || Term::Var("b".to_string());
1579
1580        // lt a b := le (a + 1) b
1581        ctx.add_definition(
1582            "lt".to_string(),
1583            bin_int_bool_type.clone(),
1584            order_body(bin_int(
1585                "le",
1586                bin_int("add", a(), Term::Lit(Literal::Int(1))),
1587                b(),
1588            )),
1589        );
1590        // ge a b := le b a
1591        ctx.add_definition(
1592            "ge".to_string(),
1593            bin_int_bool_type.clone(),
1594            order_body(bin_int("le", b(), a())),
1595        );
1596        // gt a b := lt b a
1597        ctx.add_definition(
1598            "gt".to_string(),
1599            bin_int_bool_type,
1600            order_body(bin_int("lt", b(), a())),
1601        );
1602
1603        // `Float`'s arithmetic and comparison surface — OPAQUE constants, exactly as in Lean.
1604        //
1605        // Lean's are `@[extern] opaque Float.add : Float → Float → Float`: they exist, they have
1606        // types, they do not reduce in the kernel, and `native_decide` evaluates them. Before
1607        // this, `Float` was a carrier with NOTHING — not one operation, not one axiom, not one
1608        // reduction rule — so `def sum : Float := 1.5 + 2.5` had no target at all, which is
1609        // strictly worse than an axiomatised type (that at least has laws).
1610        //
1611        // They are declarations rather than definitions because `Float` has no constructors, so
1612        // there is no body to write; a definition with an invented body would COMPUTE a wrong
1613        // answer, which is the one outcome worse than not computing. The `Int` ALU builtins
1614        // (`add`/`le`/…) above are the same shape, and `reduction.rs` gives those literal
1615        // short-circuits — the same hook is what `Float` owes next, and until it lands these are
1616        // honestly opaque rather than quietly wrong.
1617        //
1618        // `add`/`sub`/`mul` stay `Int`-ONLY: reusing them at `Float` would make
1619        // `add 1.5 2.5` well-typed and silently reduce it with integer semantics.
1620        let float = Term::Global("Float".to_string());
1621        let bin_float = Term::Pi {
1622            param: "_".to_string(),
1623            param_type: Box::new(float.clone()),
1624            body_type: Box::new(Term::Pi {
1625                param: "_".to_string(),
1626                param_type: Box::new(float.clone()),
1627                body_type: Box::new(float.clone()),
1628            }),
1629        };
1630        let float_cmp = Term::Pi {
1631            param: "_".to_string(),
1632            param_type: Box::new(float.clone()),
1633            body_type: Box::new(Term::Pi {
1634                param: "_".to_string(),
1635                param_type: Box::new(float.clone()),
1636                body_type: Box::new(Term::Global("Bool".to_string())),
1637            }),
1638        };
1639        for name in ["Float_add", "Float_sub", "Float_mul", "Float_div"] {
1640            ctx.add_declaration(name, bin_float.clone());
1641        }
1642        for name in ["Float_lt", "Float_le"] {
1643            ctx.add_declaration(name, float_cmp.clone());
1644        }
1645
1646        // Temporal operations
1647        let duration = Term::Global("Duration".to_string());
1648        let date = Term::Global("Date".to_string());
1649        let moment = Term::Global("Moment".to_string());
1650        let bool_type = Term::Global("Bool".to_string());
1651
1652        // Duration -> Duration -> Duration
1653        let bin_duration_type = Term::Pi {
1654            param: "_".to_string(),
1655            param_type: Box::new(duration.clone()),
1656            body_type: Box::new(Term::Pi {
1657                param: "_".to_string(),
1658                param_type: Box::new(duration.clone()),
1659                body_type: Box::new(duration.clone()),
1660            }),
1661        };
1662
1663        // Duration -> Int -> Duration
1664        let duration_int_duration_type = Term::Pi {
1665            param: "_".to_string(),
1666            param_type: Box::new(duration.clone()),
1667            body_type: Box::new(Term::Pi {
1668                param: "_".to_string(),
1669                param_type: Box::new(int.clone()),
1670                body_type: Box::new(duration.clone()),
1671            }),
1672        };
1673
1674        // Duration arithmetic: add, sub, mul, div
1675        ctx.add_declaration("add_duration", bin_duration_type.clone());
1676        ctx.add_declaration("sub_duration", bin_duration_type.clone());
1677        ctx.add_declaration("mul_duration", duration_int_duration_type.clone());
1678        ctx.add_declaration("div_duration", duration_int_duration_type);
1679
1680        // Date -> Int -> Date (add days offset)
1681        let date_int_date_type = Term::Pi {
1682            param: "_".to_string(),
1683            param_type: Box::new(date.clone()),
1684            body_type: Box::new(Term::Pi {
1685                param: "_".to_string(),
1686                param_type: Box::new(int.clone()),
1687                body_type: Box::new(date.clone()),
1688            }),
1689        };
1690        ctx.add_declaration("date_add_days", date_int_date_type);
1691
1692        // Date -> Date -> Int (difference in days)
1693        let date_date_int_type = Term::Pi {
1694            param: "_".to_string(),
1695            param_type: Box::new(date.clone()),
1696            body_type: Box::new(Term::Pi {
1697                param: "_".to_string(),
1698                param_type: Box::new(date.clone()),
1699                body_type: Box::new(int.clone()),
1700            }),
1701        };
1702        ctx.add_declaration("date_sub_date", date_date_int_type);
1703
1704        // Moment -> Duration -> Moment
1705        let moment_duration_moment_type = Term::Pi {
1706            param: "_".to_string(),
1707            param_type: Box::new(moment.clone()),
1708            body_type: Box::new(Term::Pi {
1709                param: "_".to_string(),
1710                param_type: Box::new(duration.clone()),
1711                body_type: Box::new(moment.clone()),
1712            }),
1713        };
1714        ctx.add_declaration("moment_add_duration", moment_duration_moment_type);
1715
1716        // Moment -> Moment -> Duration
1717        let moment_moment_duration_type = Term::Pi {
1718            param: "_".to_string(),
1719            param_type: Box::new(moment.clone()),
1720            body_type: Box::new(Term::Pi {
1721                param: "_".to_string(),
1722                param_type: Box::new(moment.clone()),
1723                body_type: Box::new(duration.clone()),
1724            }),
1725        };
1726        ctx.add_declaration("moment_sub_moment", moment_moment_duration_type);
1727
1728        // Comparison operations: X -> X -> Bool
1729        let date_date_bool_type = Term::Pi {
1730            param: "_".to_string(),
1731            param_type: Box::new(date.clone()),
1732            body_type: Box::new(Term::Pi {
1733                param: "_".to_string(),
1734                param_type: Box::new(date),
1735                body_type: Box::new(bool_type.clone()),
1736            }),
1737        };
1738        ctx.add_declaration("date_lt", date_date_bool_type);
1739
1740        let moment_moment_bool_type = Term::Pi {
1741            param: "_".to_string(),
1742            param_type: Box::new(moment.clone()),
1743            body_type: Box::new(Term::Pi {
1744                param: "_".to_string(),
1745                param_type: Box::new(moment),
1746                body_type: Box::new(bool_type.clone()),
1747            }),
1748        };
1749        ctx.add_declaration("moment_lt", moment_moment_bool_type);
1750
1751        let duration_duration_bool_type = Term::Pi {
1752            param: "_".to_string(),
1753            param_type: Box::new(duration.clone()),
1754            body_type: Box::new(Term::Pi {
1755                param: "_".to_string(),
1756                param_type: Box::new(duration),
1757                body_type: Box::new(bool_type),
1758            }),
1759        };
1760        ctx.add_declaration("duration_lt", duration_duration_bool_type);
1761    }
1762
1763    /// Entity : Type 0
1764    ///
1765    /// The domain of individuals for first-order logic.
1766    /// Proper names like "Socrates" are declared as Entity.
1767    /// Predicates like "Man" are declared as Entity → Prop.
1768    fn register_entity(ctx: &mut Context) {
1769        ctx.add_inductive("Entity", Term::Sort(Universe::Type(0)));
1770    }
1771
1772    /// Nat : Type 0
1773    /// Zero : Nat
1774    /// Succ : Nat → Nat
1775    fn register_nat(ctx: &mut Context) {
1776        let nat = Term::Global("Nat".to_string());
1777
1778        // Nat : Type 0
1779        ctx.add_inductive("Nat", Term::Sort(Universe::Type(0)));
1780
1781        // Zero : Nat
1782        ctx.add_constructor("Zero", "Nat", nat.clone());
1783
1784        // Succ : Nat → Nat
1785        ctx.add_constructor(
1786            "Succ",
1787            "Nat",
1788            Term::Pi {
1789                param: "_".to_string(),
1790                param_type: Box::new(nat.clone()),
1791                body_type: Box::new(nat),
1792            },
1793        );
1794    }
1795
1796    /// Monomorphic `EList` (a list of `Entity`) — the concrete inductive that
1797    /// structural induction runs over. The kernel's parametric `TList A` carries a
1798    /// type argument, so its constructors are `Π(A:Type)…`; the generic
1799    /// `InductionScheme` eliminator builds a `match` over a *bare* `Global(ind_type)`,
1800    /// which needs a non-parametric type. `EList = μX. ENil | ECons Entity X` is that
1801    /// target: it gives the `induction` tactic an `ENil`/`ECons` recursor that
1802    /// certifies — `fix rec. λl:EList. match l { ENil => …, ECons h t => … }`. The
1803    /// `E`-prefixed names deliberately avoid the user-space `List`/`Nil`/`Cons` a REPL
1804    /// program defines (typically a parametric `List A`), so registering this in the
1805    /// prelude never shadows a user inductive.
1806    ///
1807    /// `EList : Type 0`
1808    /// `ENil  : EList`
1809    /// `ECons : Entity → EList → EList`
1810    fn register_monolist(ctx: &mut Context) {
1811        let list = Term::Global("EList".to_string());
1812        let entity = Term::Global("Entity".to_string());
1813
1814        // EList : Type 0
1815        ctx.add_inductive("EList", Term::Sort(Universe::Type(0)));
1816
1817        // ENil : EList
1818        ctx.add_constructor("ENil", "EList", list.clone());
1819
1820        // ECons : Entity → EList → EList
1821        ctx.add_constructor(
1822            "ECons",
1823            "EList",
1824            Term::Pi {
1825                param: "_".to_string(),
1826                param_type: Box::new(entity),
1827                body_type: Box::new(Term::Pi {
1828                    param: "_".to_string(),
1829                    param_type: Box::new(list.clone()),
1830                    body_type: Box::new(list),
1831                }),
1832            },
1833        );
1834    }
1835
1836    /// Bool : Type 0
1837    /// true : Bool
1838    /// false : Bool
1839    fn register_bool(ctx: &mut Context) {
1840        let bool_type = Term::Global("Bool".to_string());
1841
1842        // Bool : Type 0
1843        ctx.add_inductive("Bool", Term::Sort(Universe::Type(0)));
1844
1845        // true : Bool
1846        ctx.add_constructor("true", "Bool", bool_type.clone());
1847
1848        // false : Bool
1849        ctx.add_constructor("false", "Bool", bool_type);
1850    }
1851
1852    /// TList : Type 0 -> Type 0
1853    /// TNil : Π(A : Type 0). TList A
1854    /// TCons : Π(A : Type 0). A -> TList A -> TList A
1855    fn register_tlist(ctx: &mut Context) {
1856        let type0 = Term::Sort(Universe::Type(0));
1857        let a = Term::Var("A".to_string());
1858
1859        // TList : Type 0 -> Type 0
1860        let tlist_type = Term::Pi {
1861            param: "A".to_string(),
1862            param_type: Box::new(type0.clone()),
1863            body_type: Box::new(type0.clone()),
1864        };
1865        ctx.add_inductive("TList", tlist_type);
1866
1867        // TList A
1868        let tlist_a = Term::App(
1869            Box::new(Term::Global("TList".to_string())),
1870            Box::new(a.clone()),
1871        );
1872
1873        // TNil : Π(A : Type 0). TList A
1874        let tnil_type = Term::Pi {
1875            param: "A".to_string(),
1876            param_type: Box::new(type0.clone()),
1877            body_type: Box::new(tlist_a.clone()),
1878        };
1879        ctx.add_constructor("TNil", "TList", tnil_type);
1880
1881        // TCons : Π(A : Type 0). A -> TList A -> TList A
1882        let tcons_type = Term::Pi {
1883            param: "A".to_string(),
1884            param_type: Box::new(type0),
1885            body_type: Box::new(Term::Pi {
1886                param: "_".to_string(),
1887                param_type: Box::new(a.clone()),
1888                body_type: Box::new(Term::Pi {
1889                    param: "_".to_string(),
1890                    param_type: Box::new(tlist_a.clone()),
1891                    body_type: Box::new(tlist_a),
1892                }),
1893            }),
1894        };
1895        ctx.add_constructor("TCons", "TList", tcons_type);
1896
1897        // Convenience aliases for tactic lists (Syntax -> Derivation)
1898        Self::register_tactic_list_helpers(ctx);
1899    }
1900
1901    /// TTactics : Type 0 = TList (Syntax -> Derivation)
1902    /// TacNil : TTactics
1903    /// TacCons : (Syntax -> Derivation) -> TTactics -> TTactics
1904    ///
1905    /// Convenience wrappers to avoid explicit type arguments for tactic lists.
1906    fn register_tactic_list_helpers(ctx: &mut Context) {
1907        let syntax = Term::Global("Syntax".to_string());
1908        let derivation = Term::Global("Derivation".to_string());
1909
1910        // Tactic type: Syntax -> Derivation
1911        let tactic_type = Term::Pi {
1912            param: "_".to_string(),
1913            param_type: Box::new(syntax.clone()),
1914            body_type: Box::new(derivation.clone()),
1915        };
1916
1917        // TTactics = TList (Syntax -> Derivation)
1918        let ttactics = Term::App(
1919            Box::new(Term::Global("TList".to_string())),
1920            Box::new(tactic_type.clone()),
1921        );
1922
1923        // TTactics : Type 0
1924        ctx.add_definition(
1925            "TTactics".to_string(),
1926            Term::Sort(Universe::Type(0)),
1927            ttactics.clone(),
1928        );
1929
1930        // TacNil : TTactics = TNil (Syntax -> Derivation)
1931        let tac_nil_body = Term::App(
1932            Box::new(Term::Global("TNil".to_string())),
1933            Box::new(tactic_type.clone()),
1934        );
1935        ctx.add_definition("TacNil".to_string(), ttactics.clone(), tac_nil_body);
1936
1937        // TacCons : (Syntax -> Derivation) -> TTactics -> TTactics
1938        let tac_cons_type = Term::Pi {
1939            param: "t".to_string(),
1940            param_type: Box::new(tactic_type.clone()),
1941            body_type: Box::new(Term::Pi {
1942                param: "ts".to_string(),
1943                param_type: Box::new(ttactics.clone()),
1944                body_type: Box::new(ttactics.clone()),
1945            }),
1946        };
1947
1948        // TacCons t ts = TCons (Syntax -> Derivation) t ts
1949        let tac_cons_body = Term::Lambda {
1950            param: "t".to_string(),
1951            param_type: Box::new(tactic_type.clone()),
1952            body: Box::new(Term::Lambda {
1953                param: "ts".to_string(),
1954                param_type: Box::new(ttactics.clone()),
1955                body: Box::new(Term::App(
1956                    Box::new(Term::App(
1957                        Box::new(Term::App(
1958                            Box::new(Term::Global("TCons".to_string())),
1959                            Box::new(tactic_type),
1960                        )),
1961                        Box::new(Term::Var("t".to_string())),
1962                    )),
1963                    Box::new(Term::Var("ts".to_string())),
1964                )),
1965            }),
1966        };
1967        ctx.add_definition("TacCons".to_string(), tac_cons_type, tac_cons_body);
1968    }
1969
1970    /// True : Prop
1971    /// I : True
1972    fn register_true(ctx: &mut Context) {
1973        ctx.add_inductive("True", Term::Sort(Universe::Prop));
1974        ctx.add_constructor("I", "True", Term::Global("True".to_string()));
1975    }
1976
1977    /// False : Prop
1978    /// (no constructors)
1979    fn register_false(ctx: &mut Context) {
1980        ctx.add_inductive("False", Term::Sort(Universe::Prop));
1981    }
1982
1983    /// Not : Prop -> Prop
1984    /// Not P := P -> False
1985    fn register_not(ctx: &mut Context) {
1986        // Type: Π(P : Prop). Prop
1987        let not_type = Term::Pi {
1988            param: "P".to_string(),
1989            param_type: Box::new(Term::Sort(Universe::Prop)),
1990            body_type: Box::new(Term::Sort(Universe::Prop)),
1991        };
1992
1993        // Body: λ(P : Prop). Π(_ : P). False
1994        let not_body = Term::Lambda {
1995            param: "P".to_string(),
1996            param_type: Box::new(Term::Sort(Universe::Prop)),
1997            body: Box::new(Term::Pi {
1998                param: "_".to_string(),
1999                param_type: Box::new(Term::Var("P".to_string())),
2000                body_type: Box::new(Term::Global("False".to_string())),
2001            }),
2002        };
2003
2004        ctx.add_definition("Not".to_string(), not_type, not_body);
2005    }
2006
2007    /// `Decidable (p:Prop) : Type` — the data of a decision procedure for `p`, with
2008    /// `isTrue : p → Decidable p` and `isFalse : ¬p → Decidable p`. Type-valued (so it may
2009    /// be eliminated into `Type` to compute a `Bool`), auto-derives its recursor, and
2010    /// defines `decide : Π(p). Decidable p → Bool` (isTrue ↝ true, isFalse ↝ false).
2011    fn register_decidable(ctx: &mut Context) {
2012        let prop = || Term::Sort(Universe::Prop);
2013        let type0 = || Term::Sort(Universe::Type(0));
2014        let g = |s: &str| Term::Global(s.to_string());
2015        let v = |s: &str| Term::Var(s.to_string());
2016        let ap = |f: Term, x: Term| Term::App(Box::new(f), Box::new(x));
2017        let lm = |p: &str, t: Term, b: Term| Term::Lambda {
2018            param: p.to_string(),
2019            param_type: Box::new(t),
2020            body: Box::new(b),
2021        };
2022        let pi = |p: &str, t: Term, b: Term| Term::Pi {
2023            param: p.to_string(),
2024            param_type: Box::new(t),
2025            body_type: Box::new(b),
2026        };
2027        let dec = |p: Term| ap(g("Decidable"), p);
2028        let not = |p: Term| ap(g("Not"), p);
2029
2030        // Decidable : Π(p:Prop). Type 0   (one uniform parameter, Type-valued)
2031        ctx.add_indexed_inductive("Decidable", pi("p", prop(), type0()), 1);
2032        // isTrue  : Π(p:Prop). p → Decidable p
2033        ctx.add_constructor(
2034            "isTrue",
2035            "Decidable",
2036            pi("p", prop(), pi("_", v("p"), dec(v("p")))),
2037        );
2038        // isFalse : Π(p:Prop). Not p → Decidable p
2039        ctx.add_constructor(
2040            "isFalse",
2041            "Decidable",
2042            pi("p", prop(), pi("_", not(v("p")), dec(v("p")))),
2043        );
2044
2045        // Decidable_rec — auto-derived dependent eliminator, kernel-checked (not an axiom).
2046        let (rec_ty, rec_body) = crate::recursor::derive_recursor(ctx, "Decidable")
2047            .expect("Decidable's eliminator must derive");
2048        ctx.add_definition("Decidable_rec".to_string(), rec_ty, rec_body);
2049
2050        // decide : Π(p:Prop). Decidable p → Bool
2051        //   := λp inst. Decidable_rec p (λ_. Bool) (λh. true) (λh. false) inst
2052        let decide_ty = pi("p", prop(), pi("_", dec(v("p")), g("Bool")));
2053        let decide_body = lm(
2054            "p",
2055            prop(),
2056            lm(
2057                "inst",
2058                dec(v("p")),
2059                ap(
2060                    ap(
2061                        ap(
2062                            ap(
2063                                ap(g("Decidable_rec"), v("p")),
2064                                lm("_", dec(v("p")), g("Bool")),
2065                            ),
2066                            lm("_", v("p"), g("true")),
2067                        ),
2068                        lm("_", not(v("p")), g("false")),
2069                    ),
2070                    v("inst"),
2071                ),
2072            ),
2073        );
2074        ctx.add_definition("decide".to_string(), decide_ty, decide_body);
2075    }
2076
2077    /// `of_decide_eq_true : Π(p:Prop). Π(inst:Decidable p). Eq Bool (decide p inst) true → p`
2078    /// — the bridge that turns a computed `decide` into a proof, PROVEN from `Decidable_rec`
2079    /// and Bool no-confusion (via `Eq_rec_dep`), NOT axiomatized. This is what makes the
2080    /// `decide` tactic sound with zero additions to the trusted base.
2081    fn register_of_decide(ctx: &mut Context) {
2082        let prop = || Term::Sort(Universe::Prop);
2083        let g = |s: &str| Term::Global(s.to_string());
2084        let v = |s: &str| Term::Var(s.to_string());
2085        let ap = |f: Term, x: Term| Term::App(Box::new(f), Box::new(x));
2086        let lm = |p: &str, t: Term, b: Term| Term::Lambda {
2087            param: p.to_string(),
2088            param_type: Box::new(t),
2089            body: Box::new(b),
2090        };
2091        let pi = |p: &str, t: Term, b: Term| Term::Pi {
2092            param: p.to_string(),
2093            param_type: Box::new(t),
2094            body_type: Box::new(b),
2095        };
2096        let dec = |p: Term| ap(g("Decidable"), p);
2097        let not = |p: Term| ap(g("Not"), p);
2098        // Eq Bool x y
2099        let eqb = |x: Term, y: Term| ap(ap(ap(g("Eq"), g("Bool")), x), y);
2100        // decide p inst
2101        let decide = |p: Term, inst: Term| ap(ap(g("decide"), p), inst);
2102        let is_true = |p: Term, h: Term| ap(ap(g("isTrue"), p), h);
2103        let is_false = |p: Term, h: Term| ap(ap(g("isFalse"), p), h);
2104
2105        // of_decide_eq_true : Π(p:Prop). Π(inst:Decidable p). Eq Bool (decide p inst) true → p
2106        let ty = pi(
2107            "p",
2108            prop(),
2109            pi(
2110                "inst",
2111                dec(v("p")),
2112                pi("_", eqb(decide(v("p"), v("inst")), g("true")), v("p")),
2113            ),
2114        );
2115
2116        // Motive for the recursion on `inst`: λinst. Eq Bool (decide p inst) true → p.
2117        let motive = lm(
2118            "inst",
2119            dec(v("p")),
2120            pi("_", eqb(decide(v("p"), v("inst")), g("true")), v("p")),
2121        );
2122        // isTrue branch: `decide p (isTrue p hp) ≡ true`, so just return the witness `hp`.
2123        let f_istrue = lm(
2124            "hp",
2125            v("p"),
2126            lm(
2127                "_",
2128                eqb(decide(v("p"), is_true(v("p"), v("hp"))), g("true")),
2129                v("hp"),
2130            ),
2131        );
2132        // isFalse branch: `decide p (isFalse p hnp) ≡ false`, so the hypothesis is
2133        // `false = true`; Bool no-confusion turns it into `p`. Transport `discr` along the
2134        // equality, where `discr b := match b with true => p | false => True`, taking the
2135        // inhabitant `I : True` at `false` to a proof of `p` at `true`.
2136        let discr = Term::Match {
2137            discriminant: Box::new(v("b")),
2138            motive: Box::new(lm("_", g("Bool"), prop())),
2139            cases: vec![v("p"), g("True")], // Bool constructor order: [true, false]
2140        };
2141        let bool_motive = lm("b", g("Bool"), lm("_", eqb(g("false"), v("b")), discr));
2142        // Eq_rec_dep Bool false bool_motive I true h  :  p
2143        let noconf = ap(
2144            ap(
2145                ap(
2146                    ap(ap(ap(g("Eq_rec_dep"), g("Bool")), g("false")), bool_motive),
2147                    g("I"),
2148                ),
2149                g("true"),
2150            ),
2151            v("h"),
2152        );
2153        let f_isfalse = lm(
2154            "hnp",
2155            not(v("p")),
2156            lm(
2157                "h",
2158                eqb(decide(v("p"), is_false(v("p"), v("hnp"))), g("true")),
2159                noconf,
2160            ),
2161        );
2162
2163        // λp inst h. Decidable_rec p motive f_istrue f_isfalse inst h
2164        let rec_app = ap(
2165            ap(
2166                ap(
2167                    ap(ap(ap(g("Decidable_rec"), v("p")), motive), f_istrue),
2168                    f_isfalse,
2169                ),
2170                v("inst"),
2171            ),
2172            v("h"),
2173        );
2174        let body = lm(
2175            "p",
2176            prop(),
2177            lm(
2178                "inst",
2179                dec(v("p")),
2180                lm("h", eqb(decide(v("p"), v("inst")), g("true")), rec_app),
2181            ),
2182        );
2183        ctx.add_definition("of_decide_eq_true".to_string(), ty, body);
2184    }
2185
2186    /// Decidable equality of `Bool` (`decEqBool : Π(a b:Bool). Decidable (Eq Bool a b)`),
2187    /// with the two Bool no-confusion lemmas it needs — all derived. This is a concrete
2188    /// `Decidable` INSTANCE, so `decide` can actually discharge `Eq Bool _ _` goals.
2189    fn register_dec_eq_bool(ctx: &mut Context) {
2190        let prop = || Term::Sort(Universe::Prop);
2191        let g = |s: &str| Term::Global(s.to_string());
2192        let v = |s: &str| Term::Var(s.to_string());
2193        let ap = |f: Term, x: Term| Term::App(Box::new(f), Box::new(x));
2194        let lm = |p: &str, t: Term, b: Term| Term::Lambda {
2195            param: p.to_string(),
2196            param_type: Box::new(t),
2197            body: Box::new(b),
2198        };
2199        let eqb = |x: Term, y: Term| ap(ap(ap(g("Eq"), g("Bool")), x), y);
2200        let dec = |p: Term| ap(g("Decidable"), p);
2201        let is_true = |p: Term, h: Term| ap(ap(g("isTrue"), p), h);
2202        let is_false = |p: Term, h: Term| ap(ap(g("isFalse"), p), h);
2203        let refl = |x: Term| ap(ap(g("refl"), g("Bool")), x);
2204        // `match b return (λ_:Bool. Prop) with { <true-case>, <false-case> }`.
2205        let bool_match = |t_case: Term, f_case: Term| Term::Match {
2206            discriminant: Box::new(v("b")),
2207            motive: Box::new(lm("_", g("Bool"), prop())),
2208            cases: vec![t_case, f_case],
2209        };
2210
2211        // bool_tf_ne : Not (Eq Bool true false)  — transport True@true along h to False@false.
2212        let tf_discr = bool_match(g("True"), g("False"));
2213        let tf_motive = lm("b", g("Bool"), lm("_", eqb(g("true"), v("b")), tf_discr));
2214        let bool_tf_ne = lm(
2215            "h",
2216            eqb(g("true"), g("false")),
2217            ap(
2218                ap(
2219                    ap(
2220                        ap(ap(ap(g("Eq_rec_dep"), g("Bool")), g("true")), tf_motive),
2221                        g("I"),
2222                    ),
2223                    g("false"),
2224                ),
2225                v("h"),
2226            ),
2227        );
2228        // bool_ft_ne : Not (Eq Bool false true)  — transport True@false along h to False@true.
2229        let ft_discr = bool_match(g("False"), g("True"));
2230        let ft_motive = lm("b", g("Bool"), lm("_", eqb(g("false"), v("b")), ft_discr));
2231        let bool_ft_ne = lm(
2232            "h",
2233            eqb(g("false"), g("true")),
2234            ap(
2235                ap(
2236                    ap(
2237                        ap(ap(ap(g("Eq_rec_dep"), g("Bool")), g("false")), ft_motive),
2238                        g("I"),
2239                    ),
2240                    g("true"),
2241                ),
2242                v("h"),
2243            ),
2244        );
2245
2246        // decEqBool : Π(a b:Bool). Decidable (Eq Bool a b)
2247        let de_ty = Term::Pi {
2248            param: "a".to_string(),
2249            param_type: Box::new(g("Bool")),
2250            body_type: Box::new(Term::Pi {
2251                param: "b".to_string(),
2252                param_type: Box::new(g("Bool")),
2253                body_type: Box::new(dec(eqb(v("a"), v("b")))),
2254            }),
2255        };
2256        // Inner match on `b`, with the outer `a` fixed to a constructor `af`.
2257        let inner = |af: Term, both_same: Term, ne_proof: Term, same_first: bool| {
2258            let motive = lm("b'", g("Bool"), dec(eqb(af.clone(), v("b'"))));
2259            // cases in Bool order [true, false]; `same` is when b matches af.
2260            let (t_case, f_case) = if same_first {
2261                // af == true
2262                (
2263                    is_true(eqb(af.clone(), g("true")), both_same),
2264                    is_false(eqb(af.clone(), g("false")), ne_proof),
2265                )
2266            } else {
2267                // af == false
2268                (
2269                    is_false(eqb(af.clone(), g("true")), ne_proof),
2270                    is_true(eqb(af.clone(), g("false")), both_same),
2271                )
2272            };
2273            Term::Match {
2274                discriminant: Box::new(v("b")),
2275                motive: Box::new(motive),
2276                cases: vec![t_case, f_case],
2277            }
2278        };
2279        let a_true = inner(g("true"), refl(g("true")), bool_tf_ne, true);
2280        let a_false = inner(g("false"), refl(g("false")), bool_ft_ne, false);
2281        let outer_motive = lm("a'", g("Bool"), dec(eqb(v("a'"), v("b"))));
2282        let de_body = lm(
2283            "a",
2284            g("Bool"),
2285            lm(
2286                "b",
2287                g("Bool"),
2288                Term::Match {
2289                    discriminant: Box::new(v("a")),
2290                    motive: Box::new(outer_motive),
2291                    cases: vec![a_true, a_false],
2292                },
2293            ),
2294        );
2295        ctx.add_definition("decEqBool".to_string(), de_ty, de_body);
2296    }
2297
2298    /// Decidable equality of `Nat` (`decEqNat : Π(a b:Nat). Decidable (Eq Nat a b)`) — the
2299    /// flagship: it lets `decide` discharge arithmetic (in)equalities. Built by structural
2300    /// recursion on `a`, using derived Nat no-confusion (`Zero ≠ Succ`), `Succ` congruence
2301    /// (via J), and `Succ` injectivity (via a `pred` congruence). All derived — no axioms.
2302    fn register_dec_eq_nat(ctx: &mut Context) {
2303        let prop = || Term::Sort(Universe::Prop);
2304        let nat = || Term::Global("Nat".to_string());
2305        let g = |s: &str| Term::Global(s.to_string());
2306        let v = |s: &str| Term::Var(s.to_string());
2307        let ap = |f: Term, x: Term| Term::App(Box::new(f), Box::new(x));
2308        let lm = |p: &str, t: Term, b: Term| Term::Lambda {
2309            param: p.to_string(),
2310            param_type: Box::new(t),
2311            body: Box::new(b),
2312        };
2313        let pi = |p: &str, t: Term, b: Term| Term::Pi {
2314            param: p.to_string(),
2315            param_type: Box::new(t),
2316            body_type: Box::new(b),
2317        };
2318        let succ = |n: Term| ap(g("Succ"), n);
2319        let eqn = |x: Term, y: Term| ap(ap(ap(g("Eq"), nat()), x), y);
2320        let not = |p: Term| ap(g("Not"), p);
2321        let dec = |p: Term| ap(g("Decidable"), p);
2322        let is_true = |p: Term, h: Term| ap(ap(g("isTrue"), p), h);
2323        let is_false = |p: Term, h: Term| ap(ap(g("isFalse"), p), h);
2324        let refln = |x: Term| ap(ap(g("refl"), nat()), x);
2325        // `match k return (λ_:Nat. R) with { <Zero-case>, <Succ-case> }` (Nat order Zero,Succ).
2326        let nat_match = |ret: Term, zero_case: Term, succ_case: Term| Term::Match {
2327            discriminant: Box::new(v("k")),
2328            motive: Box::new(lm("_", nat(), ret)),
2329            cases: vec![zero_case, succ_case],
2330        };
2331        // Transport `Eq_rec_dep Nat x (λk.λ_:Eq Nat x k. discr) base y h`.
2332        let transport = |x: Term, discr_motive: Term, base: Term, y: Term, h: Term| {
2333            ap(
2334                ap(
2335                    ap(ap(ap(ap(g("Eq_rec_dep"), nat()), x), discr_motive), base),
2336                    y,
2337                ),
2338                h,
2339            )
2340        };
2341
2342        // nat_zs_ne : Π(n:Nat). Not (Eq Nat Zero (Succ n))  — Zero ≠ Succ n.
2343        let d_zs = nat_match(prop(), g("True"), lm("_", nat(), g("False")));
2344        let zs_motive = lm("k", nat(), lm("_", eqn(g("Zero"), v("k")), d_zs));
2345        let nat_zs_ne = lm(
2346            "n",
2347            nat(),
2348            lm(
2349                "h",
2350                eqn(g("Zero"), succ(v("n"))),
2351                transport(g("Zero"), zs_motive, g("I"), succ(v("n")), v("h")),
2352            ),
2353        );
2354        ctx.add_definition(
2355            "nat_zs_ne".to_string(),
2356            pi("n", nat(), not(eqn(g("Zero"), succ(v("n"))))),
2357            nat_zs_ne,
2358        );
2359
2360        // nat_sz_ne : Π(n:Nat). Not (Eq Nat (Succ n) Zero)  — Succ n ≠ Zero.
2361        let d_sz = nat_match(prop(), g("False"), lm("_", nat(), g("True")));
2362        let sz_motive = lm("k", nat(), lm("_", eqn(succ(v("n")), v("k")), d_sz));
2363        let nat_sz_ne = lm(
2364            "n",
2365            nat(),
2366            lm(
2367                "h",
2368                eqn(succ(v("n")), g("Zero")),
2369                transport(succ(v("n")), sz_motive, g("I"), g("Zero"), v("h")),
2370            ),
2371        );
2372        ctx.add_definition(
2373            "nat_sz_ne".to_string(),
2374            pi("n", nat(), not(eqn(succ(v("n")), g("Zero")))),
2375            nat_sz_ne,
2376        );
2377
2378        // succ_cong : Π(a b:Nat). Eq Nat a b → Eq Nat (Succ a) (Succ b).
2379        let sc_motive = lm(
2380            "b'",
2381            nat(),
2382            lm("_", eqn(v("a"), v("b'")), eqn(succ(v("a")), succ(v("b'")))),
2383        );
2384        let succ_cong_body = lm(
2385            "a",
2386            nat(),
2387            lm(
2388                "b",
2389                nat(),
2390                lm(
2391                    "h",
2392                    eqn(v("a"), v("b")),
2393                    ap(
2394                        ap(
2395                            ap(
2396                                ap(ap(ap(g("Eq_rec_dep"), nat()), v("a")), sc_motive),
2397                                refln(succ(v("a"))),
2398                            ),
2399                            v("b"),
2400                        ),
2401                        v("h"),
2402                    ),
2403                ),
2404            ),
2405        );
2406        let succ_cong_ty = pi(
2407            "a",
2408            nat(),
2409            pi(
2410                "b",
2411                nat(),
2412                pi("_", eqn(v("a"), v("b")), eqn(succ(v("a")), succ(v("b")))),
2413            ),
2414        );
2415        ctx.add_definition("succ_cong".to_string(), succ_cong_ty, succ_cong_body);
2416
2417        // succ_inj : Π(a b:Nat). Eq Nat (Succ a) (Succ b) → Eq Nat a b.
2418        // `pred y := match y with Zero => Zero | Succ p => p`; transport `Eq Nat a (pred y)`
2419        // along `h`, base `refl Nat a` (since `pred (Succ a) ≡ a`), result `Eq Nat a b`.
2420        let pred_y = Term::Match {
2421            discriminant: Box::new(v("y'")),
2422            motive: Box::new(lm("_", nat(), nat())),
2423            cases: vec![g("Zero"), lm("p", nat(), v("p"))],
2424        };
2425        let si_motive = lm(
2426            "y'",
2427            nat(),
2428            lm("_", eqn(succ(v("a")), v("y'")), eqn(v("a"), pred_y)),
2429        );
2430        let succ_inj_body = lm(
2431            "a",
2432            nat(),
2433            lm(
2434                "b",
2435                nat(),
2436                lm(
2437                    "h",
2438                    eqn(succ(v("a")), succ(v("b"))),
2439                    ap(
2440                        ap(
2441                            ap(
2442                                ap(ap(ap(g("Eq_rec_dep"), nat()), succ(v("a"))), si_motive),
2443                                refln(v("a")),
2444                            ),
2445                            succ(v("b")),
2446                        ),
2447                        v("h"),
2448                    ),
2449                ),
2450            ),
2451        );
2452        let succ_inj_ty = pi(
2453            "a",
2454            nat(),
2455            pi(
2456                "b",
2457                nat(),
2458                pi("_", eqn(succ(v("a")), succ(v("b"))), eqn(v("a"), v("b"))),
2459            ),
2460        );
2461        ctx.add_definition("succ_inj".to_string(), succ_inj_ty, succ_inj_body);
2462
2463        // decEqNat : Π(a b:Nat). Decidable (Eq Nat a b)  — structural recursion on `a`.
2464        // Inner match on the recursive result `rec a' b'`.
2465        let rec_call = ap(ap(v("rec"), v("a'")), v("b'"));
2466        let true_case = lm(
2467            "hp",
2468            eqn(v("a'"), v("b'")),
2469            is_true(
2470                eqn(succ(v("a'")), succ(v("b'"))),
2471                ap(ap(ap(g("succ_cong"), v("a'")), v("b'")), v("hp")),
2472            ),
2473        );
2474        let false_case = lm(
2475            "hnp",
2476            not(eqn(v("a'"), v("b'"))),
2477            is_false(
2478                eqn(succ(v("a'")), succ(v("b'"))),
2479                lm(
2480                    "hs",
2481                    eqn(succ(v("a'")), succ(v("b'"))),
2482                    ap(
2483                        v("hnp"),
2484                        ap(ap(ap(g("succ_inj"), v("a'")), v("b'")), v("hs")),
2485                    ),
2486                ),
2487            ),
2488        );
2489        let inner_rec_match = Term::Match {
2490            discriminant: Box::new(rec_call),
2491            motive: Box::new(lm(
2492                "_",
2493                dec(eqn(v("a'"), v("b'"))),
2494                dec(eqn(succ(v("a'")), succ(v("b'")))),
2495            )),
2496            cases: vec![true_case, false_case],
2497        };
2498        // b-match in the `Succ a'` branch: motive λb'. Decidable (Eq Nat (Succ a') b').
2499        let succ_b_match = Term::Match {
2500            discriminant: Box::new(v("b")),
2501            motive: Box::new(lm("b'", nat(), dec(eqn(succ(v("a'")), v("b'"))))),
2502            cases: vec![
2503                is_false(eqn(succ(v("a'")), g("Zero")), ap(g("nat_sz_ne"), v("a'"))),
2504                lm("b'", nat(), inner_rec_match),
2505            ],
2506        };
2507        // b-match in the `Zero` branch: motive λb'. Decidable (Eq Nat Zero b').
2508        let zero_b_match = Term::Match {
2509            discriminant: Box::new(v("b")),
2510            motive: Box::new(lm("b'", nat(), dec(eqn(g("Zero"), v("b'"))))),
2511            cases: vec![
2512                is_true(eqn(g("Zero"), g("Zero")), refln(g("Zero"))),
2513                lm(
2514                    "b'",
2515                    nat(),
2516                    is_false(eqn(g("Zero"), succ(v("b'"))), ap(g("nat_zs_ne"), v("b'"))),
2517                ),
2518            ],
2519        };
2520        // Outer match on `a`: motive λa'. Decidable (Eq Nat a' b).
2521        let a_match = Term::Match {
2522            discriminant: Box::new(v("a")),
2523            motive: Box::new(lm("a'", nat(), dec(eqn(v("a'"), v("b"))))),
2524            cases: vec![zero_b_match, lm("a'", nat(), succ_b_match)],
2525        };
2526        let deceqnat_body = Term::Fix {
2527            name: "rec".to_string(),
2528            body: Box::new(lm("a", nat(), lm("b", nat(), a_match))),
2529        };
2530        let deceqnat_ty = pi("a", nat(), pi("b", nat(), dec(eqn(v("a"), v("b")))));
2531        ctx.add_definition("decEqNat".to_string(), deceqnat_ty, deceqnat_body);
2532    }
2533
2534    /// The `Decidable` INSTANCES — Lean's `instDecidableEqNat` and `instDecidableNot`.
2535    ///
2536    /// `decEqBool` and `decEqNat` are decision PROCEDURES; an instance is what makes one
2537    /// FINDABLE from a goal. Without an entry, `Decidable (Eq Nat b Zero)` is answerable only by
2538    /// the last-resort derived tier and `Decidable (Not p)` is not answerable at all — so an
2539    /// auto-param obligation `(h : b ≠ 0 := by decide)` has nothing to run, which is T05-007's
2540    /// remaining half.
2541    ///
2542    /// Both go in the FALLBACK tier, for the reason [`Self::register_inhabited`] states at
2543    /// length: `Context::instances()` is resolved first-match and is the faithful record of what
2544    /// a USER declared, so a prelude entry there would be entry zero and would permanently
2545    /// outrank every instance anyone writes for the same goal.
2546    ///
2547    /// `instDecidableNot` is a DEFINITION with a kernel-checked body and NOT an assumption — it
2548    /// is `Decidable_rec` with the two constructors swapped, and the `isTrue` case builds
2549    /// `Not (Not p)` from `hp : p` as `λhn. hn hp`. Nothing here enters the trusted base, which
2550    /// matters: an axiomatised `Decidable p` inhabits the class for EVERY proposition, and
2551    /// `of_decide_eq_true` would then turn it into a proof of anything.
2552    fn register_decidable_instances(ctx: &mut Context) {
2553        let prop = || Term::Sort(Universe::Prop);
2554        let g = |s: &str| Term::Global(s.to_string());
2555        let v = |s: &str| Term::Var(s.to_string());
2556        let ap = |f: Term, x: Term| Term::App(Box::new(f), Box::new(x));
2557        let apps = |head: Term, args: &[Term]| {
2558            args.iter()
2559                .fold(head, |acc, a| Term::App(Box::new(acc), Box::new(a.clone())))
2560        };
2561        let lm = |p: &str, t: Term, b: Term| Term::Lambda {
2562            param: p.to_string(),
2563            param_type: Box::new(t),
2564            body: Box::new(b),
2565        };
2566        let pi = |p: &str, t: Term, b: Term| Term::Pi {
2567            param: p.to_string(),
2568            param_type: Box::new(t),
2569            body_type: Box::new(b),
2570        };
2571        let dec = |p: Term| ap(g("Decidable"), p);
2572        let not = |p: Term| ap(g("Not"), p);
2573        let eq_at = |ty: Term, a: Term, b: Term| apps(g("Eq"), &[ty, a, b]);
2574
2575        // `instDecidableEqNat` / `instDecidableEqBool` — the prelude's own `DecidableEq`
2576        // instances, pointing at the procedures it already proved. No new constant: the instance
2577        // IS `decEqNat`, so there is exactly one decision procedure for `Eq Nat` and a goal and a
2578        // direct call can never come to disagree about which one decided.
2579        ctx.add_fallback_instance(
2580            pi(
2581                "a",
2582                g("Nat"),
2583                pi("b", g("Nat"), dec(eq_at(g("Nat"), v("a"), v("b")))),
2584            ),
2585            g("decEqNat"),
2586        );
2587        ctx.add_fallback_instance(
2588            pi(
2589                "a",
2590                g("Bool"),
2591                pi("b", g("Bool"), dec(eq_at(g("Bool"), v("a"), v("b")))),
2592            ),
2593            g("decEqBool"),
2594        );
2595
2596        // instDecidableNot : Π(p:Prop). Decidable p → Decidable (Not p)
2597        //   := λp inst. Decidable_rec p (λ_. Decidable (Not p))
2598        //                 (λhp. isFalse (Not p) (λhn. hn hp))
2599        //                 (λhn. isTrue  (Not p) hn)
2600        //                 inst
2601        let not_ty = pi("p", prop(), pi("_", dec(v("p")), dec(not(v("p")))));
2602        let not_body = lm(
2603            "p",
2604            prop(),
2605            lm(
2606                "inst",
2607                dec(v("p")),
2608                apps(
2609                    g("Decidable_rec"),
2610                    &[
2611                        v("p"),
2612                        lm("_", dec(v("p")), dec(not(v("p")))),
2613                        lm(
2614                            "hp",
2615                            v("p"),
2616                            apps(
2617                                g("isFalse"),
2618                                &[not(v("p")), lm("hn", not(v("p")), ap(v("hn"), v("hp")))],
2619                            ),
2620                        ),
2621                        lm(
2622                            "hn",
2623                            not(v("p")),
2624                            apps(g("isTrue"), &[not(v("p")), v("hn")]),
2625                        ),
2626                        v("inst"),
2627                    ],
2628                ),
2629            ),
2630        );
2631        ctx.add_definition("instDecidableNot".to_string(), not_ty.clone(), not_body);
2632        ctx.add_fallback_instance(not_ty, g("instDecidableNot"));
2633    }
2634
2635    /// The `native_decide` trust boundary (TCB additions, exactly as Lean's `native_decide`
2636    /// adds `ofReduceBool` + its compiler): `reduceBool : Bool → Bool` is the identity, but
2637    /// the KERNEL reduces `reduceBool t` by running the fast [`crate::eval`] evaluator (a
2638    /// reduction hook), and `ofReduceBool` turns `reduceBool a = b` into `a = b`. So a
2639    /// `native_decide` proof discharges `decide p inst = true` by native evaluation instead
2640    /// of the kernel re-normalizing the decision procedure.
2641    fn register_native_decide(ctx: &mut Context) {
2642        let g = |s: &str| Term::Global(s.to_string());
2643        let v = |s: &str| Term::Var(s.to_string());
2644        let ap = |f: Term, x: Term| Term::App(Box::new(f), Box::new(x));
2645        let pi = |p: &str, t: Term, b: Term| Term::Pi {
2646            param: p.to_string(),
2647            param_type: Box::new(t),
2648            body_type: Box::new(b),
2649        };
2650        let eqb = |x: Term, y: Term| ap(ap(ap(g("Eq"), g("Bool")), x), y);
2651        // reduceBool : Bool → Bool
2652        ctx.add_declaration("reduceBool", pi("_", g("Bool"), g("Bool")));
2653        // ofReduceBool : Π(a:Bool). Π(b:Bool). Eq Bool (reduceBool a) b → Eq Bool a b
2654        ctx.add_declaration(
2655            "ofReduceBool",
2656            pi(
2657                "a",
2658                g("Bool"),
2659                pi(
2660                    "b",
2661                    g("Bool"),
2662                    pi(
2663                        "_",
2664                        eqb(ap(g("reduceBool"), v("a")), v("b")),
2665                        eqb(v("a"), v("b")),
2666                    ),
2667                ),
2668            ),
2669        );
2670    }
2671
2672    /// QUOTIENT TYPES — CIC primitives (as in Lean). `Quot A r` is the quotient of `A` by
2673    /// the relation `r`; `Quot_mk` forms classes; `Quot_lift` lifts a relation-respecting
2674    /// function (with the definitional computation rule `Quot_lift … (Quot_mk a) ≡ f a`
2675    /// implemented in `reduction.rs`); `Quot_ind` is the induction principle; and the
2676    /// `Quot_sound` AXIOM identifies related representatives — the propositional content that
2677    /// makes `Quot` a genuine quotient. `Quot A r` is OPAQUE (not an inductive), so it cannot
2678    /// be pattern-matched — only `Quot_lift`/`Quot_ind` eliminate it, which is what keeps the
2679    /// identification consistent. The dependent eliminator `Quot_rec` is a checked DEFINITION
2680    /// over them, as Lean's `Quot.rec` is. Unblocks ℤ/ℚ/ℝ, `Multiset`, setoids.
2681    fn register_quot(ctx: &mut Context) {
2682        crate::quotient::register_prelude(ctx)
2683            .expect("checked legacy quotient primitive registration");
2684    }
2685
2686    /// `Setoid` and `Quotient` — the layer Lean's ENTIRE quotient API is phrased in.
2687    ///
2688    /// Mathlib never writes `Quot`. `Int`, `Rat`, `ZMod`, free groups, completions and every
2689    /// `Quotient.lift` in the library go through `Quotient s` where `s : Setoid α` carries the
2690    /// relation AND its equivalence proof. Silently unfolding `Quotient s` to `Quot s.r` at
2691    /// translation time drops the instance that was resolved there and is no longer resolvable at
2692    /// check time, so the wrapper is not sugar — it is where the relation comes from.
2693    ///
2694    /// Neither costs the trusted base anything: `Setoid` is a STRUCTURE (its projections
2695    /// ι-reduce) and `Quotient`/`Quotient_mk` are δ-transparent DEFINITIONS over the existing
2696    /// `Quot` primitives, so `Quotient_mk` really is `Quot_mk` and the one computation rule
2697    /// quotients have still fires through it.
2698    fn register_setoid(ctx: &mut Context) {
2699        let type0 = || Term::Sort(Universe::Type(0));
2700        let prop = || Term::Sort(Universe::Prop);
2701        let rel_at = |x: Term, y: Term| apps_(v_("r"), &[x, y]);
2702
2703        // structure Setoid (a : Type) where
2704        //   r : a → a → Prop ; refl : Π x. r x x
2705        //   symm : Π x y. r x y → r y x ; trans : Π x y z. r x y → r y z → r x z
2706        ctx.add_structure(
2707            "Setoid",
2708            &[("a", type0())],
2709            &[
2710                ("r", pi_("_x", v_("a"), pi_("_y", v_("a"), prop()))),
2711                ("refl", pi_("x", v_("a"), rel_at(v_("x"), v_("x")))),
2712                (
2713                    "symm",
2714                    pi_(
2715                        "x",
2716                        v_("a"),
2717                        pi_(
2718                            "y",
2719                            v_("a"),
2720                            arrow_(rel_at(v_("x"), v_("y")), rel_at(v_("y"), v_("x"))),
2721                        ),
2722                    ),
2723                ),
2724                (
2725                    "trans",
2726                    pi_(
2727                        "x",
2728                        v_("a"),
2729                        pi_(
2730                            "y",
2731                            v_("a"),
2732                            pi_(
2733                                "z",
2734                                v_("a"),
2735                                arrow_(
2736                                    rel_at(v_("x"), v_("y")),
2737                                    arrow_(rel_at(v_("y"), v_("z")), rel_at(v_("x"), v_("z"))),
2738                                ),
2739                            ),
2740                        ),
2741                    ),
2742                ),
2743            ],
2744        );
2745
2746        // Quotient : Π(a:Type). Setoid a → Type := λa s. Quot a (Setoid_r a s)
2747        let setoid_a = || Term::App(Box::new(gl("Setoid")), Box::new(v_("a")));
2748        let carrier_rel = || apps_(gl("Setoid_r"), &[v_("a"), v_("s")]);
2749        ctx.add_definition(
2750            "Quotient".to_string(),
2751            pi_("a", type0(), arrow_(setoid_a(), type0())),
2752            lam_(
2753                "a",
2754                type0(),
2755                lam_(
2756                    "s",
2757                    setoid_a(),
2758                    apps_(gl("Quot"), &[v_("a"), carrier_rel()]),
2759                ),
2760            ),
2761        );
2762
2763        // Quotient_mk : Π(a:Type). Π(s:Setoid a). a → Quotient a s
2764        //   := λa s x. Quot_mk a (Setoid_r a s) x
2765        ctx.add_definition(
2766            "Quotient_mk".to_string(),
2767            pi_(
2768                "a",
2769                type0(),
2770                pi_(
2771                    "s",
2772                    setoid_a(),
2773                    arrow_(v_("a"), apps_(gl("Quotient"), &[v_("a"), v_("s")])),
2774                ),
2775            ),
2776            lam_(
2777                "a",
2778                type0(),
2779                lam_(
2780                    "s",
2781                    setoid_a(),
2782                    lam_(
2783                        "x",
2784                        v_("a"),
2785                        apps_(gl("Quot_mk"), &[v_("a"), carrier_rel(), v_("x")]),
2786                    ),
2787                ),
2788            ),
2789        );
2790
2791        // ---- The rest of Lean's `Quotient` API (Init/Core.lean:1678-1725) -----------------
2792        //
2793        // `Quotient.sound`, `.lift`, `.ind` and `.rec` are what Mathlib actually calls; `Quot` is
2794        // the layer underneath and is almost never written by hand. Each of Lean's is literally
2795        // its `Quot` counterpart with the relation read off the setoid
2796        // (`sound := Quot.sound`, `lift f := Quot.lift f`, `ind := Quot.ind`, `rec := Quot.rec`),
2797        // and each of ours is the same one-line body. None costs the trusted base anything: they
2798        // are δ-transparent definitions over the `Quot` family, so the quotient
2799        // computation rule still fires through them and `Quotient_lift f h (Quotient_mk s a)`
2800        // really does reduce to `f a`.
2801        let rel = || apps_(gl("Setoid_r"), &[v_("a"), v_("s")]);
2802        let quot_as = || apps_(gl("Quotient"), &[v_("a"), v_("s")]);
2803        let mk_at = |x: Term| apps_(gl("Quotient_mk"), &[v_("a"), v_("s"), x]);
2804        let head2 = |inner: Term| lam_("a", type0(), lam_("s", setoid_a(), inner));
2805        let head2_ty = |inner: Term| pi_("a", type0(), pi_("s", setoid_a(), inner));
2806
2807        // Quotient_sound : Π(a)(s)(x y:a). Setoid_r a s x y → Eq (Quotient a s) (mk x) (mk y)
2808        ctx.add_definition(
2809            "Quotient_sound".to_string(),
2810            head2_ty(pi_(
2811                "x",
2812                v_("a"),
2813                pi_(
2814                    "y",
2815                    v_("a"),
2816                    arrow_(
2817                        apps_(rel(), &[v_("x"), v_("y")]),
2818                        apps_(gl("Eq"), &[quot_as(), mk_at(v_("x")), mk_at(v_("y"))]),
2819                    ),
2820                ),
2821            )),
2822            head2(lam_(
2823                "x",
2824                v_("a"),
2825                lam_(
2826                    "y",
2827                    v_("a"),
2828                    lam_(
2829                        "hxy",
2830                        apps_(rel(), &[v_("x"), v_("y")]),
2831                        apps_(
2832                            gl("Quot_sound"),
2833                            &[v_("a"), rel(), v_("x"), v_("y"), v_("hxy")],
2834                        ),
2835                    ),
2836                ),
2837            )),
2838        );
2839
2840        // Quotient_lift : Π(a)(s)(B:Type)(f:a→B).
2841        //   (Π x y. Setoid_r a s x y → Eq B (f x) (f y)) → Quotient a s → B
2842        let respect = || {
2843            pi_(
2844                "x",
2845                v_("a"),
2846                pi_(
2847                    "y",
2848                    v_("a"),
2849                    arrow_(
2850                        apps_(rel(), &[v_("x"), v_("y")]),
2851                        apps_(
2852                            gl("Eq"),
2853                            &[
2854                                v_("B"),
2855                                Term::App(Box::new(v_("f")), Box::new(v_("x"))),
2856                                Term::App(Box::new(v_("f")), Box::new(v_("y"))),
2857                            ],
2858                        ),
2859                    ),
2860                ),
2861            )
2862        };
2863        ctx.add_definition(
2864            "Quotient_lift".to_string(),
2865            head2_ty(pi_(
2866                "B",
2867                type0(),
2868                pi_(
2869                    "f",
2870                    arrow_(v_("a"), v_("B")),
2871                    arrow_(respect(), arrow_(quot_as(), v_("B"))),
2872                ),
2873            )),
2874            head2(lam_(
2875                "B",
2876                type0(),
2877                lam_(
2878                    "f",
2879                    arrow_(v_("a"), v_("B")),
2880                    lam_(
2881                        "hresp",
2882                        respect(),
2883                        lam_(
2884                            "q",
2885                            quot_as(),
2886                            apps_(
2887                                gl("Quot_lift"),
2888                                &[v_("a"), rel(), v_("B"), v_("f"), v_("hresp"), v_("q")],
2889                            ),
2890                        ),
2891                    ),
2892                ),
2893            )),
2894        );
2895
2896        // Quotient_ind : Π(a)(s)(P : Quotient a s → Prop).
2897        //   (Π x. P (mk x)) → Π q. P q
2898        let ind_motive = || arrow_(quot_as(), prop());
2899        ctx.add_definition(
2900            "Quotient_ind".to_string(),
2901            head2_ty(pi_(
2902                "P",
2903                ind_motive(),
2904                arrow_(
2905                    pi_(
2906                        "x",
2907                        v_("a"),
2908                        Term::App(Box::new(v_("P")), Box::new(mk_at(v_("x")))),
2909                    ),
2910                    pi_(
2911                        "q",
2912                        quot_as(),
2913                        Term::App(Box::new(v_("P")), Box::new(v_("q"))),
2914                    ),
2915                ),
2916            )),
2917            head2(lam_(
2918                "P",
2919                ind_motive(),
2920                lam_(
2921                    "hcase",
2922                    pi_(
2923                        "x",
2924                        v_("a"),
2925                        Term::App(Box::new(v_("P")), Box::new(mk_at(v_("x")))),
2926                    ),
2927                    lam_(
2928                        "q",
2929                        quot_as(),
2930                        apps_(
2931                            gl("Quot_ind"),
2932                            &[v_("a"), rel(), v_("P"), v_("hcase"), v_("q")],
2933                        ),
2934                    ),
2935                ),
2936            )),
2937        );
2938
2939        // Quotient_rec : the DEPENDENT eliminator, `Quot_rec` with the setoid's relation. The
2940        // respect obligation is stated up to transport along `Quot_sound`, exactly as Lean's is
2941        // (`Eq.ndrec (f a) (Quotient.sound p) = f b`).
2942        let dmot = || arrow_(quot_as(), type0());
2943        let mk_raw = |x: Term| apps_(gl("Quot_mk"), &[v_("a"), rel(), x]);
2944        let at_m = |x: Term| Term::App(Box::new(v_("motive")), Box::new(x));
2945        let dep_cases = || pi_("x", v_("a"), at_m(mk_raw(v_("x"))));
2946        let dep_respect = || {
2947            pi_(
2948                "x",
2949                v_("a"),
2950                pi_(
2951                    "y",
2952                    v_("a"),
2953                    pi_(
2954                        "hxy",
2955                        apps_(rel(), &[v_("x"), v_("y")]),
2956                        apps_(
2957                            gl("Eq"),
2958                            &[
2959                                at_m(mk_raw(v_("y"))),
2960                                apps_(
2961                                    gl("Eq_rec_dep"),
2962                                    &[
2963                                        apps_(gl("Quot"), &[v_("a"), rel()]),
2964                                        mk_raw(v_("x")),
2965                                        lam_(
2966                                            "q2",
2967                                            apps_(gl("Quot"), &[v_("a"), rel()]),
2968                                            lam_(
2969                                                "_hq",
2970                                                apps_(
2971                                                    gl("Eq"),
2972                                                    &[
2973                                                        apps_(gl("Quot"), &[v_("a"), rel()]),
2974                                                        mk_raw(v_("x")),
2975                                                        v_("q2"),
2976                                                    ],
2977                                                ),
2978                                                at_m(v_("q2")),
2979                                            ),
2980                                        ),
2981                                        Term::App(Box::new(v_("f")), Box::new(v_("x"))),
2982                                        mk_raw(v_("y")),
2983                                        apps_(
2984                                            gl("Quot_sound"),
2985                                            &[v_("a"), rel(), v_("x"), v_("y"), v_("hxy")],
2986                                        ),
2987                                    ],
2988                                ),
2989                                Term::App(Box::new(v_("f")), Box::new(v_("y"))),
2990                            ],
2991                        ),
2992                    ),
2993                ),
2994            )
2995        };
2996        ctx.add_definition(
2997            "Quotient_rec".to_string(),
2998            head2_ty(pi_(
2999                "motive",
3000                dmot(),
3001                pi_(
3002                    "f",
3003                    dep_cases(),
3004                    arrow_(dep_respect(), pi_("q", quot_as(), at_m(v_("q")))),
3005                ),
3006            )),
3007            head2(lam_(
3008                "motive",
3009                dmot(),
3010                lam_(
3011                    "f",
3012                    dep_cases(),
3013                    lam_(
3014                        "hresp",
3015                        dep_respect(),
3016                        lam_(
3017                            "q",
3018                            quot_as(),
3019                            apps_(
3020                                gl("Quot_rec"),
3021                                &[v_("a"), rel(), v_("motive"), v_("f"), v_("hresp"), v_("q")],
3022                            ),
3023                        ),
3024                    ),
3025                ),
3026            )),
3027        );
3028    }
3029
3030    /// Eq : Π(A : Type 0). A → A → Prop
3031    /// refl : Π(A : Type 0). Π(x : A). Eq A x x
3032    /// Well-founded recursion. `Acc (A)(R) : A → Prop` is the accessibility
3033    /// predicate — `x` is accessible under `R` when every `R`-predecessor of `x` is
3034    /// accessible — with the single constructor
3035    /// `Acc_intro : Π(A)(R)(x). (Π(y:A). R y x → Acc A R y) → Acc A R x`. Its
3036    /// recursive field is FUNCTIONAL (the accessibility of all predecessors), a
3037    /// strictly-positive occurrence under a `Π`; the auto-derived eliminator
3038    /// `Acc_rec` carries the matching functional induction hypothesis, and recursion
3039    /// over an `Acc` proof terminates by the applied-smaller guard. `WellFounded A R`
3040    /// abbreviates `Π(x:A). Acc A R x`. Together these are the substrate for
3041    /// definitions by well-founded recursion (gcd, division, strong induction) that
3042    /// structural recursion cannot express — the parity item Lean's kernel has and
3043    /// ours did not.
3044    fn register_acc(ctx: &mut Context) {
3045        fn pi(p: &str, t: Term, b: Term) -> Term {
3046            Term::Pi {
3047                param: p.to_string(),
3048                param_type: Box::new(t),
3049                body_type: Box::new(b),
3050            }
3051        }
3052        fn arrow(a: Term, b: Term) -> Term {
3053            pi("_", a, b)
3054        }
3055        fn v(n: &str) -> Term {
3056            Term::Var(n.to_string())
3057        }
3058        fn g(n: &str) -> Term {
3059            Term::Global(n.to_string())
3060        }
3061        fn apps(f: Term, xs: &[Term]) -> Term {
3062            xs.iter()
3063                .fold(f, |a, x| Term::App(Box::new(a), Box::new(x.clone())))
3064        }
3065        let type0 = || Term::Sort(Universe::Type(0));
3066        let prop = || Term::Sort(Universe::Prop);
3067        // R : A → A → Prop
3068        let rel = || arrow(v("A"), arrow(v("A"), prop()));
3069        // Acc A R x
3070        let acc = |x: Term| apps(g("Acc"), &[v("A"), v("R"), x]);
3071
3072        // Acc : Π(A:Type). Π(R:A→A→Prop). A → Prop  — two params (A, R), one index (x).
3073        let acc_ty = pi("A", type0(), pi("R", rel(), arrow(v("A"), prop())));
3074        ctx.add_indexed_inductive("Acc", acc_ty, 2);
3075
3076        // Acc_intro : Π(A)(R)(x). (Π(y:A). R y x → Acc A R y) → Acc A R x
3077        let intro_ty = pi(
3078            "A",
3079            type0(),
3080            pi(
3081                "R",
3082                rel(),
3083                pi(
3084                    "x",
3085                    v("A"),
3086                    arrow(
3087                        pi(
3088                            "y",
3089                            v("A"),
3090                            arrow(apps(v("R"), &[v("y"), v("x")]), acc(v("y"))),
3091                        ),
3092                        acc(v("x")),
3093                    ),
3094                ),
3095            ),
3096        );
3097        ctx.add_constructor("Acc_intro", "Acc", intro_ty);
3098
3099        // Acc_rec — the AUTO-DERIVED dependent eliminator carrying the functional
3100        // induction hypothesis (two-kernel verified in tests/well_founded.rs). A
3101        // kernel-checked definition, not an axiom.
3102        // Ordinary definition publication keeps Global callers and lets the
3103        // existing application rules infer the motive's universe.
3104        let (_levels, rec_ty, rec_body) =
3105            crate::recursor::derive_recursor_universe_poly(ctx, "Acc")
3106                .expect("Acc's dependent eliminator must derive");
3107        ctx.add_definition("Acc_rec".to_string(), rec_ty, rec_body);
3108
3109        // WellFounded A R := Π(x:A). Acc A R x  — `R` is well-founded iff every
3110        // element is accessible. A plain definition (abbreviation), no new inductive.
3111        let wf_ty = pi("A", type0(), arrow(rel(), prop()));
3112        let wf_body = Term::Lambda {
3113            param: "A".to_string(),
3114            param_type: Box::new(type0()),
3115            body: Box::new(Term::Lambda {
3116                param: "R".to_string(),
3117                param_type: Box::new(rel()),
3118                body: Box::new(pi("x", v("A"), acc(v("x")))),
3119            }),
3120        };
3121        ctx.add_definition("WellFounded".to_string(), wf_ty, wf_body);
3122
3123        // WellFounded_fix — Lean's `WellFounded.fix`, the combinator EVERY well-founded
3124        // definition goes through. `Acc_rec` alone leaves each caller to rebuild it, and a
3125        // rebuilt-by-hand fixpoint is a different definition from the one the Lean source names.
3126        //
3127        //   WellFounded_fix.{u} : Π(A)(R)(C : A → Sort u). WellFounded A R →
3128        //                     (Π(x:A). (Π(y:A). R y x → C y) → C x) → Π(x:A). C x
3129        //
3130        // A DEFINITION derived from `Acc_rec`, never an axiom: `Acc_rec`'s minor premise already
3131        // hands the step both the accessibility field and the functional induction hypothesis, so
3132        // the step `F` needs only the latter. The accessibility proof is consumed at `wf x`, which
3133        // is what makes the recursion ι-COMPUTE rather than sit stuck.
3134        let motive_ty = pi("_", v("A"), Term::Sort(Universe::Var("wf_u".to_string())));
3135        // ih : Π(y:A). R y x → C y — the recursive calls available at `x`.
3136        let ih_at = |x: &str| {
3137            pi(
3138                "y",
3139                v("A"),
3140                arrow(
3141                    apps(v("R"), &[v("y"), v(x)]),
3142                    Term::App(Box::new(v("C")), Box::new(v("y"))),
3143                ),
3144            )
3145        };
3146        let c_at = |x: &str| Term::App(Box::new(v("C")), Box::new(v(x)));
3147        let step_ty = pi("x", v("A"), arrow(ih_at("x"), c_at("x")));
3148        let fix_ty = pi(
3149            "A",
3150            type0(),
3151            pi(
3152                "R",
3153                rel(),
3154                pi(
3155                    "C",
3156                    motive_ty.clone(),
3157                    arrow(
3158                        apps(g("WellFounded"), &[v("A"), v("R")]),
3159                        arrow(step_ty.clone(), pi("x", v("A"), c_at("x"))),
3160                    ),
3161                ),
3162            ),
3163        );
3164        // λA R C wf F x. Acc_rec A R (λz. λ_. C z) (λz. λh. λih. F z ih) x (wf x)
3165        let rec_motive = lam_(
3166            "z",
3167            v("A"),
3168            lam_(
3169                "_",
3170                apps(g("Acc"), &[v("A"), v("R"), v("z")]),
3171                Term::App(Box::new(v("C")), Box::new(v("z"))),
3172            ),
3173        );
3174        // h : Π(y:A). R y z → Acc A R y — the constructor's own functional field.
3175        let acc_field_ty = pi(
3176            "y",
3177            v("A"),
3178            arrow(
3179                apps(v("R"), &[v("y"), v("z")]),
3180                apps(g("Acc"), &[v("A"), v("R"), v("y")]),
3181            ),
3182        );
3183        let rec_step = lam_(
3184            "z",
3185            v("A"),
3186            lam_(
3187                "h",
3188                acc_field_ty,
3189                lam_("ih", ih_at("z"), apps(v("F"), &[v("z"), v("ih")])),
3190            ),
3191        );
3192        let fix_body = lam_(
3193            "A",
3194            type0(),
3195            lam_(
3196                "R",
3197                rel(),
3198                lam_(
3199                    "C",
3200                    motive_ty,
3201                    lam_(
3202                        "wf",
3203                        apps(g("WellFounded"), &[v("A"), v("R")]),
3204                        lam_(
3205                            "F",
3206                            step_ty,
3207                            lam_(
3208                                "x",
3209                                v("A"),
3210                                apps(
3211                                    g("Acc_rec"),
3212                                    &[
3213                                        v("A"),
3214                                        v("R"),
3215                                        rec_motive,
3216                                        rec_step,
3217                                        v("x"),
3218                                        Term::App(Box::new(v("wf")), Box::new(v("x"))),
3219                                    ],
3220                                ),
3221                            ),
3222                        ),
3223                    ),
3224                ),
3225            ),
3226        );
3227        ctx.add_definition("WellFounded_fix".to_string(), fix_ty, fix_body);
3228    }
3229
3230    /// `Eq.{u} : Π(A : Sort u). A → A → Prop` and `refl.{u} : Π(A : Sort u). Π(x:A). Eq A x x`.
3231    ///
3232    /// Equality over EVERY carrier Lean allows. Lean's is `{α : Sort u}`, and the difference is
3233    /// not cosmetic: a carrier pinned to `Type 0` cannot state `α = β` between two TYPES, which is
3234    /// what `eq_of_heq` casts along, what `∃ α : Type, α = Nat` needs, and what every `Set`- or
3235    /// category-level equation in Mathlib is.
3236    ///
3237    /// `Prop` stays the CODOMAIN, literally: an equation is a proposition whatever its carrier
3238    /// lives in, and computing `max` there instead would promote equations out of `Prop` and
3239    /// silently disable proof irrelevance.
3240    ///
3241    /// No new primitive is needed. `type_checker::implicit_levels_for_head` turns a bare
3242    /// `Term::Global` head's free level variables into metavariables at the application, and
3243    /// `solve_domain_levels` reads the solution off the argument's ACTUAL type — so `Eq Nat 2 2`
3244    /// solves `u := 0` and `Eq Type0 α Nat` solves `u := 1`. Choosing an instantiation is not
3245    /// accepting one: `check_type` still runs against the substituted domain afterwards, and the
3246    /// de Bruijn re-checker solves the same way from the same specification at its own
3247    /// application rule.
3248    fn register_eq(ctx: &mut Context) {
3249        // Eq.{u} : Π(A : Sort u). A → A → Prop
3250        let eq_type = Term::Pi {
3251            param: "A".to_string(),
3252            param_type: Box::new(Term::Sort(Universe::Var("u".to_string()))),
3253            body_type: Box::new(Term::Pi {
3254                param: "x".to_string(),
3255                param_type: Box::new(Term::Var("A".to_string())),
3256                body_type: Box::new(Term::Pi {
3257                    param: "y".to_string(),
3258                    param_type: Box::new(Term::Var("A".to_string())),
3259                    body_type: Box::new(Term::Sort(Universe::Prop)),
3260                }),
3261            }),
3262        };
3263        // `Eq (A) (x) : A → Prop` — the leading `A` and `x` are uniform parameters
3264        // (`refl`'s result `Eq A x x` repeats them), the trailing slot is the index.
3265        ctx.add_indexed_inductive("Eq", eq_type, 2);
3266
3267        // refl.{u} : Π(A : Sort u). Π(x : A). Eq A x x
3268        let refl_type = Term::Pi {
3269            param: "A".to_string(),
3270            param_type: Box::new(Term::Sort(Universe::Var("u".to_string()))),
3271            body_type: Box::new(Term::Pi {
3272                param: "x".to_string(),
3273                param_type: Box::new(Term::Var("A".to_string())),
3274                body_type: Box::new(Term::App(
3275                    Box::new(Term::App(
3276                        Box::new(Term::App(
3277                            Box::new(Term::Global("Eq".to_string())),
3278                            Box::new(Term::Var("A".to_string())),
3279                        )),
3280                        Box::new(Term::Var("x".to_string())),
3281                    )),
3282                    Box::new(Term::Var("x".to_string())),
3283                )),
3284            }),
3285        };
3286        ctx.add_constructor("refl", "Eq", refl_type);
3287
3288        // `Eq_rec_dep` — the AUTO-DERIVED full dependent eliminator (Paulin-Mohring J):
3289        // `Π(A). Π(x:A). Π(P:Π(y:A). Eq A x y → Type). P x (refl A x) → Π(y). Π(h:Eq A x y).
3290        // P y h`. A kernel-CHECKED definition (two-kernel verified), not an axiom — so the
3291        // equality eliminator and its lemmas below leave the trusted base.
3292        Self::register_eq_recursor(ctx);
3293
3294        // Eq_rec : Π(A:Type). Π(x:A). Π(P:A→Prop). P x → Π(y:A). Eq A x y → P y
3295        // The (proof-irrelevant) substitution eliminator — now DERIVED from J.
3296        Self::register_eq_rec(ctx);
3297
3298        // Eq_sym : Π(A:Type). Π(x:A). Π(y:A). Eq A x y → Eq A y x — DERIVED from J.
3299        Self::register_eq_sym(ctx);
3300
3301        // Eq_trans : Π(A:Type). Π(x:A). Π(y:A). Π(z:A). Eq A x y → Eq A y z → Eq A x z — DERIVED.
3302        Self::register_eq_trans(ctx);
3303    }
3304
3305    /// Register the auto-derived dependent equality eliminator `Eq_rec_dep` (full J) as a
3306    /// kernel-checked definition with a polymorphic motive sort. Ordinary registration
3307    /// preserves bare-Global application and its implicit universe instantiation.
3308    /// `Eq` and `refl` must already be registered.
3309    fn register_eq_recursor(ctx: &mut Context) {
3310        let (_levels, ty, body) = crate::recursor::derive_recursor_universe_poly(ctx, "Eq")
3311            .expect("Eq's dependent eliminator (J) must derive");
3312        ctx.add_definition("Eq_rec_dep".to_string(), ty, body);
3313    }
3314
3315    /// Eq_rec : Π(A:Type). Π(x:A). Π(P:A→Prop). P x → Π(y:A). Eq A x y → P y
3316    /// The eliminator for equality - Leibniz's Law / Substitution of Equals
3317    fn register_eq_rec(ctx: &mut Context) {
3318        let a = Term::Var("A".to_string());
3319        let x = Term::Var("x".to_string());
3320        let y = Term::Var("y".to_string());
3321        let p = Term::Var("P".to_string());
3322
3323        // P x = P applied to x
3324        let p_x = Term::App(Box::new(p.clone()), Box::new(x.clone()));
3325
3326        // P y = P applied to y
3327        let p_y = Term::App(Box::new(p.clone()), Box::new(y.clone()));
3328
3329        // Eq A x y
3330        let eq_a_x_y = Term::App(
3331            Box::new(Term::App(
3332                Box::new(Term::App(
3333                    Box::new(Term::Global("Eq".to_string())),
3334                    Box::new(a.clone()),
3335                )),
3336                Box::new(x.clone()),
3337            )),
3338            Box::new(y.clone()),
3339        );
3340
3341        // P : A → Prop
3342        let p_type = Term::Pi {
3343            param: "_".to_string(),
3344            param_type: Box::new(a.clone()),
3345            body_type: Box::new(Term::Sort(Universe::Prop)),
3346        };
3347
3348        // Full type: Π(A:Type). Π(x:A). Π(P:A→Prop). P x → Π(y:A). Eq A x y → P y
3349        let eq_rec_type = Term::Pi {
3350            param: "A".to_string(),
3351            param_type: Box::new(Term::Sort(Universe::Type(0))),
3352            body_type: Box::new(Term::Pi {
3353                param: "x".to_string(),
3354                param_type: Box::new(a.clone()),
3355                body_type: Box::new(Term::Pi {
3356                    param: "P".to_string(),
3357                    param_type: Box::new(p_type),
3358                    body_type: Box::new(Term::Pi {
3359                        param: "_".to_string(),
3360                        param_type: Box::new(p_x),
3361                        body_type: Box::new(Term::Pi {
3362                            param: "y".to_string(),
3363                            param_type: Box::new(a.clone()),
3364                            body_type: Box::new(Term::Pi {
3365                                param: "_".to_string(),
3366                                param_type: Box::new(eq_a_x_y),
3367                                body_type: Box::new(p_y),
3368                            }),
3369                        }),
3370                    }),
3371                }),
3372            }),
3373        };
3374
3375        // Body — the substitution eliminator DERIVED from J by discarding the proof in the
3376        // motive: `λA x P base y h. Eq_rec_dep A x (λy'. λ_:Eq A x y'. P y') base y h`.
3377        let gl = |s: &str| Term::Global(s.to_string());
3378        let vr = |s: &str| Term::Var(s.to_string());
3379        let ap = |f: Term, x: Term| Term::App(Box::new(f), Box::new(x));
3380        let lm = |p: &str, t: Term, b: Term| Term::Lambda {
3381            param: p.to_string(),
3382            param_type: Box::new(t),
3383            body: Box::new(b),
3384        };
3385        let eq3 = |a: Term, x: Term, y: Term| ap(ap(ap(gl("Eq"), a), x), y);
3386        let dep_motive = lm(
3387            "y'",
3388            vr("A"),
3389            lm("_", eq3(vr("A"), vr("x"), vr("y'")), ap(vr("P"), vr("y'"))),
3390        );
3391        let call = ap(
3392            ap(
3393                ap(
3394                    ap(ap(ap(gl("Eq_rec_dep"), vr("A")), vr("x")), dep_motive),
3395                    vr("base"),
3396                ),
3397                vr("y"),
3398            ),
3399            vr("h"),
3400        );
3401        let eq_rec_body = lm(
3402            "A",
3403            Term::Sort(Universe::Type(0)),
3404            lm(
3405                "x",
3406                vr("A"),
3407                lm(
3408                    "P",
3409                    Term::Pi {
3410                        param: "_".to_string(),
3411                        param_type: Box::new(vr("A")),
3412                        body_type: Box::new(Term::Sort(Universe::Prop)),
3413                    },
3414                    lm(
3415                        "base",
3416                        ap(vr("P"), vr("x")),
3417                        lm("y", vr("A"), lm("h", eq3(vr("A"), vr("x"), vr("y")), call)),
3418                    ),
3419                ),
3420            ),
3421        );
3422
3423        ctx.add_definition("Eq_rec".to_string(), eq_rec_type, eq_rec_body);
3424    }
3425
3426    /// Eq_sym : Π(A:Type). Π(x:A). Π(y:A). Eq A x y → Eq A y x
3427    /// Symmetry of equality
3428    fn register_eq_sym(ctx: &mut Context) {
3429        let a = Term::Var("A".to_string());
3430        let x = Term::Var("x".to_string());
3431        let y = Term::Var("y".to_string());
3432
3433        // Eq A x y
3434        let eq_a_x_y = Term::App(
3435            Box::new(Term::App(
3436                Box::new(Term::App(
3437                    Box::new(Term::Global("Eq".to_string())),
3438                    Box::new(a.clone()),
3439                )),
3440                Box::new(x.clone()),
3441            )),
3442            Box::new(y.clone()),
3443        );
3444
3445        // Eq A y x
3446        let eq_a_y_x = Term::App(
3447            Box::new(Term::App(
3448                Box::new(Term::App(
3449                    Box::new(Term::Global("Eq".to_string())),
3450                    Box::new(a.clone()),
3451                )),
3452                Box::new(y.clone()),
3453            )),
3454            Box::new(x.clone()),
3455        );
3456
3457        // Π(A:Type). Π(x:A). Π(y:A). Eq A x y → Eq A y x
3458        let eq_sym_type = Term::Pi {
3459            param: "A".to_string(),
3460            param_type: Box::new(Term::Sort(Universe::Type(0))),
3461            body_type: Box::new(Term::Pi {
3462                param: "x".to_string(),
3463                param_type: Box::new(a.clone()),
3464                body_type: Box::new(Term::Pi {
3465                    param: "y".to_string(),
3466                    param_type: Box::new(a),
3467                    body_type: Box::new(Term::Pi {
3468                        param: "_".to_string(),
3469                        param_type: Box::new(eq_a_x_y),
3470                        body_type: Box::new(eq_a_y_x),
3471                    }),
3472                }),
3473            }),
3474        };
3475
3476        // Body — symmetry DERIVED from J: transport `Eq A x _` along `h` with base `refl`.
3477        // `λA x y h. Eq_rec_dep A x (λy'. λ_:Eq A x y'. Eq A y' x) (refl A x) y h`.
3478        let gl = |s: &str| Term::Global(s.to_string());
3479        let vr = |s: &str| Term::Var(s.to_string());
3480        let ap = |f: Term, x: Term| Term::App(Box::new(f), Box::new(x));
3481        let lm = |p: &str, t: Term, b: Term| Term::Lambda {
3482            param: p.to_string(),
3483            param_type: Box::new(t),
3484            body: Box::new(b),
3485        };
3486        let eq3 = |a: Term, x: Term, y: Term| ap(ap(ap(gl("Eq"), a), x), y);
3487        let motive = lm(
3488            "y'",
3489            vr("A"),
3490            lm(
3491                "_",
3492                eq3(vr("A"), vr("x"), vr("y'")),
3493                eq3(vr("A"), vr("y'"), vr("x")),
3494            ),
3495        );
3496        let refl_a_x = ap(ap(gl("refl"), vr("A")), vr("x"));
3497        let call = ap(
3498            ap(
3499                ap(
3500                    ap(ap(ap(gl("Eq_rec_dep"), vr("A")), vr("x")), motive),
3501                    refl_a_x,
3502                ),
3503                vr("y"),
3504            ),
3505            vr("h"),
3506        );
3507        let eq_sym_body = lm(
3508            "A",
3509            Term::Sort(Universe::Type(0)),
3510            lm(
3511                "x",
3512                vr("A"),
3513                lm("y", vr("A"), lm("h", eq3(vr("A"), vr("x"), vr("y")), call)),
3514            ),
3515        );
3516
3517        ctx.add_definition("Eq_sym".to_string(), eq_sym_type, eq_sym_body);
3518    }
3519
3520    /// Eq_trans : Π(A:Type). Π(x:A). Π(y:A). Π(z:A). Eq A x y → Eq A y z → Eq A x z
3521    /// Transitivity of equality
3522    fn register_eq_trans(ctx: &mut Context) {
3523        let a = Term::Var("A".to_string());
3524        let x = Term::Var("x".to_string());
3525        let y = Term::Var("y".to_string());
3526        let z = Term::Var("z".to_string());
3527
3528        // Eq A x y
3529        let eq_a_x_y = Term::App(
3530            Box::new(Term::App(
3531                Box::new(Term::App(
3532                    Box::new(Term::Global("Eq".to_string())),
3533                    Box::new(a.clone()),
3534                )),
3535                Box::new(x.clone()),
3536            )),
3537            Box::new(y.clone()),
3538        );
3539
3540        // Eq A y z
3541        let eq_a_y_z = Term::App(
3542            Box::new(Term::App(
3543                Box::new(Term::App(
3544                    Box::new(Term::Global("Eq".to_string())),
3545                    Box::new(a.clone()),
3546                )),
3547                Box::new(y.clone()),
3548            )),
3549            Box::new(z.clone()),
3550        );
3551
3552        // Eq A x z
3553        let eq_a_x_z = Term::App(
3554            Box::new(Term::App(
3555                Box::new(Term::App(
3556                    Box::new(Term::Global("Eq".to_string())),
3557                    Box::new(a.clone()),
3558                )),
3559                Box::new(x.clone()),
3560            )),
3561            Box::new(z.clone()),
3562        );
3563
3564        // Π(A:Type). Π(x:A). Π(y:A). Π(z:A). Eq A x y → Eq A y z → Eq A x z
3565        let eq_trans_type = Term::Pi {
3566            param: "A".to_string(),
3567            param_type: Box::new(Term::Sort(Universe::Type(0))),
3568            body_type: Box::new(Term::Pi {
3569                param: "x".to_string(),
3570                param_type: Box::new(a.clone()),
3571                body_type: Box::new(Term::Pi {
3572                    param: "y".to_string(),
3573                    param_type: Box::new(a.clone()),
3574                    body_type: Box::new(Term::Pi {
3575                        param: "z".to_string(),
3576                        param_type: Box::new(a),
3577                        body_type: Box::new(Term::Pi {
3578                            param: "_".to_string(),
3579                            param_type: Box::new(eq_a_x_y),
3580                            body_type: Box::new(Term::Pi {
3581                                param: "_".to_string(),
3582                                param_type: Box::new(eq_a_y_z),
3583                                body_type: Box::new(eq_a_x_z),
3584                            }),
3585                        }),
3586                    }),
3587                }),
3588            }),
3589        };
3590
3591        // Body — transitivity DERIVED from J: transport `Eq A x _` along `hyz` (relating
3592        // `y` and `z`) with base `hxy`.
3593        // `λA x y z hxy hyz. Eq_rec_dep A y (λz'. λ_:Eq A y z'. Eq A x z') hxy z hyz`.
3594        let gl = |s: &str| Term::Global(s.to_string());
3595        let vr = |s: &str| Term::Var(s.to_string());
3596        let ap = |f: Term, x: Term| Term::App(Box::new(f), Box::new(x));
3597        let lm = |p: &str, t: Term, b: Term| Term::Lambda {
3598            param: p.to_string(),
3599            param_type: Box::new(t),
3600            body: Box::new(b),
3601        };
3602        let eq3 = |a: Term, x: Term, y: Term| ap(ap(ap(gl("Eq"), a), x), y);
3603        let motive = lm(
3604            "z'",
3605            vr("A"),
3606            lm(
3607                "_",
3608                eq3(vr("A"), vr("y"), vr("z'")),
3609                eq3(vr("A"), vr("x"), vr("z'")),
3610            ),
3611        );
3612        let call = ap(
3613            ap(
3614                ap(
3615                    ap(ap(ap(gl("Eq_rec_dep"), vr("A")), vr("y")), motive),
3616                    vr("hxy"),
3617                ),
3618                vr("z"),
3619            ),
3620            vr("hyz"),
3621        );
3622        let eq_trans_body = lm(
3623            "A",
3624            Term::Sort(Universe::Type(0)),
3625            lm(
3626                "x",
3627                vr("A"),
3628                lm(
3629                    "y",
3630                    vr("A"),
3631                    lm(
3632                        "z",
3633                        vr("A"),
3634                        lm(
3635                            "hxy",
3636                            eq3(vr("A"), vr("x"), vr("y")),
3637                            lm("hyz", eq3(vr("A"), vr("y"), vr("z")), call),
3638                        ),
3639                    ),
3640                ),
3641            ),
3642        );
3643
3644        ctx.add_definition("Eq_trans".to_string(), eq_trans_type, eq_trans_body);
3645    }
3646
3647    /// And : Prop → Prop → Prop
3648    /// conj : Π(P : Prop). Π(Q : Prop). P → Q → And P Q
3649    /// Heterogeneous equality — `HEq A B a b`, the equation Lean's equation compiler, `Eq.rec`
3650    /// on an indexed family, and `cases`/`injection` on a dependent hypothesis all GENERATE and
3651    /// the source never writes.
3652    ///
3653    /// `Eq` takes ONE carrier, so a heterogeneous equation cannot be spelled as an `Eq` at either
3654    /// side: without this family there is a whole class of goals a translator cannot even STATE,
3655    /// which is worse than one it cannot prove.
3656    ///
3657    /// It costs the trusted base NOTHING. `HEq` is an inductive FAMILY with a checked
3658    /// constructor and a derived eliminator — declaring it ad hoc through the unchecked paths
3659    /// registers a name with no eliminator, i.e. a new axiom wearing an inductive's clothes.
3660    ///
3661    /// The shape is forced by the arity `Π(A B:Type). A → B → Prop`: LOGOS parameters are an
3662    /// arity PREFIX, and the constructor `HEq_refl : Π(A)(a:A). HEq A A a a` binds `A` and `a`
3663    /// but instantiates the second arity slot with `A` rather than binding it. So `A` is the one
3664    /// uniform parameter and `B`, `x`, `y` are indices. (Lean orders the arity
3665    /// `{α} → α → {β} → β → Prop`, which makes `α` and `a` BOTH parameters; ours is the more
3666    /// general elimination — the motive abstracts `x` as well.)
3667    ///
3668    /// Large elimination holds for the same reason `Eq`'s does: `HEq` is a single-constructor
3669    /// `Prop` whose one non-propositional field `a` reappears verbatim among the result's
3670    /// indices, so [`crate::type_checker::is_subsingleton_prop`] admits it and `HEq_rec`'s motive
3671    /// lands in `Type 0`.
3672    ///
3673    /// `heq_of_eq` — the direction that IS derivable at a `Type 0`-pinned `Eq` — is PROVED by J.
3674    /// Its converse `eq_of_heq` is not derivable here and is deliberately NOT assumed: Lean
3675    /// proves it by `cast`ing along an equation `α = β` BETWEEN CARRIERS, which needs `Eq` at a
3676    /// `Type 1` carrier (universe-polymorphic `Eq`). Assuming it instead would be Coq's
3677    /// `JMeq_eq` — an axiom — and would hide the real dependency.
3678    fn register_heq(ctx: &mut Context) {
3679        let type0 = || Term::Sort(Universe::Type(0));
3680        let prop = || Term::Sort(Universe::Prop);
3681        let v = |s: &str| Term::Var(s.to_string());
3682        let heq = |a: Term, b: Term, x: Term, y: Term| apps_(gl("HEq"), &[a, b, x, y]);
3683
3684        // HEq : Π(A B : Type 0). A → B → Prop — one uniform parameter, three indices.
3685        ctx.add_indexed_inductive(
3686            "HEq",
3687            pi_(
3688                "A",
3689                type0(),
3690                pi_("B", type0(), arrow_(v("A"), arrow_(v("B"), prop()))),
3691            ),
3692            1,
3693        );
3694
3695        // HEq_refl : Π(A:Type). Π(a:A). HEq A A a a
3696        Self::checked_ctor(
3697            ctx,
3698            "HEq_refl",
3699            "HEq",
3700            pi_(
3701                "A",
3702                type0(),
3703                pi_("a", v("A"), heq(v("A"), v("A"), v("a"), v("a"))),
3704            ),
3705        );
3706
3707        // HEq_rec — the dependent eliminator, a kernel-checked definition.
3708        //
3709        // Its TYPE comes from `derive_recursor`, so the shape is the canonical one the kernel
3710        // itself computes (and calling it also holds `HEq` to the kernel's own eliminability
3711        // rules — a family that would not derive must not get a hand-written eliminator).
3712        //
3713        // Its BODY is a plain `Match`, not the derived `Fix`. `HEq` is NON-RECURSIVE: `HEq_refl`
3714        // has no recursive occurrence, so the fixpoint is dead weight — and worse than dead.
3715        // `derive_recursor` wraps every eliminator in a `Fix` whose recursion argument is the
3716        // FIRST INDEX, and the kernel unfolds a `Fix` only when that argument is in constructor
3717        // form. `HEq`'s first index is `B : Type 0`, which is never a constructor, so the derived
3718        // body is stuck forever: `HEq_rec … (HEq_refl A a)` type-checks and does not ι-reduce.
3719        // A `Match` on a constructor-form discriminant reduces immediately, so the eliminator
3720        // COMPUTES — which is the difference between an eliminator and an axiom with a body.
3721        let (rec_ty, _derived) = crate::recursor::derive_recursor(ctx, "HEq")
3722            .expect("HEq's dependent eliminator must derive");
3723        let motive_ty = pi_(
3724            "B",
3725            type0(),
3726            pi_(
3727                "x",
3728                v("A"),
3729                pi_(
3730                    "y",
3731                    v("B"),
3732                    arrow_(heq(v("A"), v("B"), v("x"), v("y")), type0()),
3733                ),
3734            ),
3735        );
3736        let base_ty = pi_(
3737            "a",
3738            v("A"),
3739            apps_(
3740                v("P"),
3741                &[
3742                    v("A"),
3743                    v("a"),
3744                    v("a"),
3745                    apps_(gl("HEq_refl"), &[v("A"), v("a")]),
3746                ],
3747            ),
3748        );
3749        let match_motive = lam_(
3750            "i0",
3751            type0(),
3752            lam_(
3753                "i1",
3754                v("A"),
3755                lam_(
3756                    "i2",
3757                    v("i0"),
3758                    lam_(
3759                        "ih",
3760                        heq(v("A"), v("i0"), v("i1"), v("i2")),
3761                        apps_(v("P"), &[v("i0"), v("i1"), v("i2"), v("ih")]),
3762                    ),
3763                ),
3764            ),
3765        );
3766        let rec_body = lam_(
3767            "A",
3768            type0(),
3769            lam_(
3770                "P",
3771                motive_ty,
3772                lam_(
3773                    "f0",
3774                    base_ty,
3775                    lam_(
3776                        "B",
3777                        type0(),
3778                        lam_(
3779                            "x",
3780                            v("A"),
3781                            lam_(
3782                                "y",
3783                                v("B"),
3784                                lam_(
3785                                    "h",
3786                                    heq(v("A"), v("B"), v("x"), v("y")),
3787                                    Term::Match {
3788                                        discriminant: Box::new(v("h")),
3789                                        motive: Box::new(match_motive),
3790                                        cases: vec![v("f0")],
3791                                    },
3792                                ),
3793                            ),
3794                        ),
3795                    ),
3796                ),
3797            ),
3798        );
3799        ctx.add_definition("HEq_rec".to_string(), rec_ty, rec_body);
3800
3801        // heq_of_eq : Π(A:Type). Π(a b:A). Eq A a b → HEq A A a b
3802        //   := λA a b h. Eq_rec_dep A a (λy. λ_. HEq A A a y) (HEq_refl A a) b h
3803        let heq_of_eq_ty = pi_(
3804            "A",
3805            type0(),
3806            pi_(
3807                "a",
3808                v("A"),
3809                pi_(
3810                    "b",
3811                    v("A"),
3812                    arrow_(
3813                        apps_(gl("Eq"), &[v("A"), v("a"), v("b")]),
3814                        heq(v("A"), v("A"), v("a"), v("b")),
3815                    ),
3816                ),
3817            ),
3818        );
3819        let motive = lam_(
3820            "y",
3821            v("A"),
3822            lam_(
3823                "_",
3824                apps_(gl("Eq"), &[v("A"), v("a"), v("y")]),
3825                heq(v("A"), v("A"), v("a"), v("y")),
3826            ),
3827        );
3828        let heq_of_eq_body = lam_(
3829            "A",
3830            type0(),
3831            lam_(
3832                "a",
3833                v("A"),
3834                lam_(
3835                    "b",
3836                    v("A"),
3837                    lam_(
3838                        "h",
3839                        apps_(gl("Eq"), &[v("A"), v("a"), v("b")]),
3840                        apps_(
3841                            gl("Eq_rec_dep"),
3842                            &[
3843                                v("A"),
3844                                v("a"),
3845                                motive,
3846                                apps_(gl("HEq_refl"), &[v("A"), v("a")]),
3847                                v("b"),
3848                                v("h"),
3849                            ],
3850                        ),
3851                    ),
3852                ),
3853            ),
3854        );
3855        ctx.add_definition("heq_of_eq".to_string(), heq_of_eq_ty, heq_of_eq_body);
3856
3857        // ---- cast, and `eq_of_heq` — the bridge BACK, PROVED (Init/Prelude.lean:464) -------
3858        //
3859        // Lean writes
3860        //
3861        //   theorem eq_of_heq {α : Sort u} {a a' : α} (h : HEq a a') : Eq a a' :=
3862        //     have : (α β : Sort u) → (a : α) → (b : β) → HEq a b → (h : Eq α β) → Eq (cast h a) b :=
3863        //       fun _ _ _ _ h₁ => h₁.rec (fun _ => rfl)
3864        //     this α α a a' h rfl
3865        //
3866        // and the `rfl` in the `HEq.refl` case is where the whole argument lives: it asks the
3867        // kernel to accept `cast h a ≡ a` for an ARBITRARY `h : α = α`. Lean's kernel does that by
3868        // K-like ι-reduction; LOGOS's fires the `Eq` ι-rule on a syntactic `refl` only, and an
3869        // earlier wave concluded from that the theorem was unreachable and left the gap open.
3870        //
3871        // It is reachable, by the OTHER door the same fact comes through. LOGOS's conversion is
3872        // PROOF-IRRELEVANT, so `hc : Eq (Type 0) A A` and `refl (Type 0) A` — two proofs of one
3873        // proposition — are already definitionally equal, and therefore
3874        //
3875        //     refl (Eq (Type 0) A A) hc  :  Eq (Eq (Type 0) A A) hc (refl (Type 0) A)
3876        //
3877        // TYPE-CHECKS. That is UIP at the carrier equation, as a theorem rather than as a
3878        // reduction rule, and once it is a propositional equation it can be SUBSTITUTED ALONG:
3879        // rewrite `hc` to `refl` inside `Eq A (cast A A hc a) a`, and the goal becomes
3880        // `Eq A (cast A A (refl (Type 0) A) a) a`, whose cast ι-reduces because the proof standing
3881        // there is now syntactically `refl`. `refl A a` closes it.
3882        //
3883        // So `eq_of_heq` costs the trusted base NOTHING and is not Coq's `JMeq_eq`: no axiom is
3884        // added, the K-like reduction rule is not added either, and the step that was missing is
3885        // supplied by proof irrelevance — which the kernel already has and which is exactly the
3886        // rule Lean's K-like ι-reduction is itself justified by.
3887        //
3888        // `cast` is Lean's own (`Init/Prelude.lean`, `cast : α = β → α → β`), registered here
3889        // because `eq_of_heq`'s statement is unwriteable without it and because every `HEq`
3890        // elimination in translated Lean source mentions it.
3891        let cast_ty = pi_(
3892            "A",
3893            type0(),
3894            pi_(
3895                "B",
3896                type0(),
3897                arrow_(
3898                    apps_(gl("Eq"), &[type0(), v("A"), v("B")]),
3899                    arrow_(v("A"), v("B")),
3900                ),
3901            ),
3902        );
3903        let cast_at = |a: Term, b: Term, h: Term, x: Term| {
3904            apps_(
3905                gl("Eq_rec_dep"),
3906                &[
3907                    type0(),
3908                    a.clone(),
3909                    lam_(
3910                        "y",
3911                        type0(),
3912                        lam_(
3913                            "_hy",
3914                            apps_(gl("Eq"), &[type0(), a.clone(), v("y")]),
3915                            v("y"),
3916                        ),
3917                    ),
3918                    x,
3919                    b,
3920                    h,
3921                ],
3922            )
3923        };
3924        ctx.add_definition(
3925            "cast".to_string(),
3926            cast_ty,
3927            lam_(
3928                "A",
3929                type0(),
3930                lam_(
3931                    "B",
3932                    type0(),
3933                    lam_(
3934                        "hc",
3935                        apps_(gl("Eq"), &[type0(), v("A"), v("B")]),
3936                        lam_("x", v("A"), cast_at(v("A"), v("B"), v("hc"), v("x"))),
3937                    ),
3938                ),
3939            ),
3940        );
3941
3942        // cast_refl : Π(A:Type). Π(hc : Eq (Type 0) A A). Π(a:A). Eq A (cast A A hc a) a
3943        //
3944        // UIP at the carrier, then substitution. The `refl (Eq …) hc` below is the load-bearing
3945        // step and it type-checks ONLY because conversion is proof-irrelevant — it is the theorem
3946        // "every proof of `A = A` is `rfl`", which is Streicher's K, held as a PROPOSITION here
3947        // rather than as a reduction rule.
3948        let carrier_eq = || apps_(gl("Eq"), &[type0(), v("A"), v("A")]);
3949        let refl_a = || apps_(gl("refl"), &[type0(), v("A")]);
3950        let cast_refl_ty = pi_(
3951            "A",
3952            type0(),
3953            pi_(
3954                "hc",
3955                carrier_eq(),
3956                pi_(
3957                    "a",
3958                    v("A"),
3959                    apps_(
3960                        gl("Eq"),
3961                        &[
3962                            v("A"),
3963                            apps_(gl("cast"), &[v("A"), v("A"), v("hc"), v("a")]),
3964                            v("a"),
3965                        ],
3966                    ),
3967                ),
3968            ),
3969        );
3970        let cast_refl_body = lam_(
3971            "A",
3972            type0(),
3973            lam_(
3974                "hc",
3975                carrier_eq(),
3976                lam_(
3977                    "a",
3978                    v("A"),
3979                    apps_(
3980                        gl("Eq_rec_dep"),
3981                        &[
3982                            carrier_eq(),
3983                            refl_a(),
3984                            lam_(
3985                                "e",
3986                                carrier_eq(),
3987                                lam_(
3988                                    "_he",
3989                                    apps_(gl("Eq"), &[carrier_eq(), refl_a(), v("e")]),
3990                                    apps_(
3991                                        gl("Eq"),
3992                                        &[
3993                                            v("A"),
3994                                            apps_(gl("cast"), &[v("A"), v("A"), v("e"), v("a")]),
3995                                            v("a"),
3996                                        ],
3997                                    ),
3998                                ),
3999                            ),
4000                            apps_(gl("refl"), &[v("A"), v("a")]),
4001                            v("hc"),
4002                            apps_(
4003                                gl("Eq_sym"),
4004                                &[
4005                                    carrier_eq(),
4006                                    v("hc"),
4007                                    refl_a(),
4008                                    apps_(gl("refl"), &[carrier_eq(), v("hc")]),
4009                                ],
4010                            ),
4011                        ],
4012                    ),
4013                ),
4014            ),
4015        );
4016        ctx.add_definition("cast_refl".to_string(), cast_refl_ty, cast_refl_body);
4017
4018        // eq_of_heq : Π(A:Type). Π(a b:A). HEq A A a b → Eq A a b
4019        //
4020        //   := λA a b h. HEq_rec A
4021        //        (λB x y _. Π(hc : Eq (Type 0) A B). Eq B (cast A B hc x) y)
4022        //        (λz hc. cast_refl A hc z)
4023        //        A a b h (refl (Type 0) A)
4024        //
4025        // Lean's motive exactly (`Init/Prelude.lean:465`), discharged by `cast_refl` instead of by
4026        // the kernel's K-like ι-rule.
4027        let heq_mot = lam_(
4028            "B",
4029            type0(),
4030            lam_(
4031                "x",
4032                v("A"),
4033                lam_(
4034                    "y",
4035                    v("B"),
4036                    lam_(
4037                        "_hxy",
4038                        heq(v("A"), v("B"), v("x"), v("y")),
4039                        pi_(
4040                            "hc",
4041                            apps_(gl("Eq"), &[type0(), v("A"), v("B")]),
4042                            apps_(
4043                                gl("Eq"),
4044                                &[
4045                                    v("B"),
4046                                    apps_(gl("cast"), &[v("A"), v("B"), v("hc"), v("x")]),
4047                                    v("y"),
4048                                ],
4049                            ),
4050                        ),
4051                    ),
4052                ),
4053            ),
4054        );
4055        let eq_of_heq_ty = pi_(
4056            "A",
4057            type0(),
4058            pi_(
4059                "a",
4060                v("A"),
4061                pi_(
4062                    "b",
4063                    v("A"),
4064                    arrow_(
4065                        heq(v("A"), v("A"), v("a"), v("b")),
4066                        apps_(gl("Eq"), &[v("A"), v("a"), v("b")]),
4067                    ),
4068                ),
4069            ),
4070        );
4071        let eq_of_heq_body = lam_(
4072            "A",
4073            type0(),
4074            lam_(
4075                "a",
4076                v("A"),
4077                lam_(
4078                    "b",
4079                    v("A"),
4080                    lam_(
4081                        "h",
4082                        heq(v("A"), v("A"), v("a"), v("b")),
4083                        Term::App(
4084                            Box::new(apps_(
4085                                gl("HEq_rec"),
4086                                &[
4087                                    v("A"),
4088                                    heq_mot,
4089                                    lam_(
4090                                        "z",
4091                                        v("A"),
4092                                        lam_(
4093                                            "hz",
4094                                            carrier_eq(),
4095                                            apps_(gl("cast_refl"), &[v("A"), v("hz"), v("z")]),
4096                                        ),
4097                                    ),
4098                                    v("A"),
4099                                    v("a"),
4100                                    v("b"),
4101                                    v("h"),
4102                                ],
4103                            )),
4104                            Box::new(refl_a()),
4105                        ),
4106                    ),
4107                ),
4108            ),
4109        );
4110        ctx.add_definition("eq_of_heq".to_string(), eq_of_heq_ty, eq_of_heq_body);
4111    }
4112
4113    fn register_and(ctx: &mut Context) {
4114        // And : Prop → Prop → Prop
4115        let and_type = Term::Pi {
4116            param: "P".to_string(),
4117            param_type: Box::new(Term::Sort(Universe::Prop)),
4118            body_type: Box::new(Term::Pi {
4119                param: "Q".to_string(),
4120                param_type: Box::new(Term::Sort(Universe::Prop)),
4121                body_type: Box::new(Term::Sort(Universe::Prop)),
4122            }),
4123        };
4124        ctx.add_inductive("And", and_type);
4125
4126        // conj : Π(P : Prop). Π(Q : Prop). P → Q → And P Q
4127        let conj_type = Term::Pi {
4128            param: "P".to_string(),
4129            param_type: Box::new(Term::Sort(Universe::Prop)),
4130            body_type: Box::new(Term::Pi {
4131                param: "Q".to_string(),
4132                param_type: Box::new(Term::Sort(Universe::Prop)),
4133                body_type: Box::new(Term::Pi {
4134                    param: "p".to_string(),
4135                    param_type: Box::new(Term::Var("P".to_string())),
4136                    body_type: Box::new(Term::Pi {
4137                        param: "q".to_string(),
4138                        param_type: Box::new(Term::Var("Q".to_string())),
4139                        body_type: Box::new(Term::App(
4140                            Box::new(Term::App(
4141                                Box::new(Term::Global("And".to_string())),
4142                                Box::new(Term::Var("P".to_string())),
4143                            )),
4144                            Box::new(Term::Var("Q".to_string())),
4145                        )),
4146                    }),
4147                }),
4148            }),
4149        };
4150        ctx.add_constructor("conj", "And", conj_type);
4151    }
4152
4153    /// Or : Prop → Prop → Prop
4154    /// left : Π(P : Prop). Π(Q : Prop). P → Or P Q
4155    /// right : Π(P : Prop). Π(Q : Prop). Q → Or P Q
4156    fn register_or(ctx: &mut Context) {
4157        // Or : Prop → Prop → Prop
4158        let or_type = Term::Pi {
4159            param: "P".to_string(),
4160            param_type: Box::new(Term::Sort(Universe::Prop)),
4161            body_type: Box::new(Term::Pi {
4162                param: "Q".to_string(),
4163                param_type: Box::new(Term::Sort(Universe::Prop)),
4164                body_type: Box::new(Term::Sort(Universe::Prop)),
4165            }),
4166        };
4167        ctx.add_inductive("Or", or_type);
4168
4169        // left : Π(P : Prop). Π(Q : Prop). P → Or P Q
4170        let left_type = Term::Pi {
4171            param: "P".to_string(),
4172            param_type: Box::new(Term::Sort(Universe::Prop)),
4173            body_type: Box::new(Term::Pi {
4174                param: "Q".to_string(),
4175                param_type: Box::new(Term::Sort(Universe::Prop)),
4176                body_type: Box::new(Term::Pi {
4177                    param: "p".to_string(),
4178                    param_type: Box::new(Term::Var("P".to_string())),
4179                    body_type: Box::new(Term::App(
4180                        Box::new(Term::App(
4181                            Box::new(Term::Global("Or".to_string())),
4182                            Box::new(Term::Var("P".to_string())),
4183                        )),
4184                        Box::new(Term::Var("Q".to_string())),
4185                    )),
4186                }),
4187            }),
4188        };
4189        ctx.add_constructor("left", "Or", left_type);
4190
4191        // right : Π(P : Prop). Π(Q : Prop). Q → Or P Q
4192        let right_type = Term::Pi {
4193            param: "P".to_string(),
4194            param_type: Box::new(Term::Sort(Universe::Prop)),
4195            body_type: Box::new(Term::Pi {
4196                param: "Q".to_string(),
4197                param_type: Box::new(Term::Sort(Universe::Prop)),
4198                body_type: Box::new(Term::Pi {
4199                    param: "q".to_string(),
4200                    param_type: Box::new(Term::Var("Q".to_string())),
4201                    body_type: Box::new(Term::App(
4202                        Box::new(Term::App(
4203                            Box::new(Term::Global("Or".to_string())),
4204                            Box::new(Term::Var("P".to_string())),
4205                        )),
4206                        Box::new(Term::Var("Q".to_string())),
4207                    )),
4208                }),
4209            }),
4210        };
4211        ctx.add_constructor("right", "Or", right_type);
4212    }
4213
4214    /// `Ex.{u} : Π(A : Sort u). (A → Prop) → Prop`
4215    /// `witness.{u} : Π(A : Sort u). Π(P : A → Prop). Π(x : A). P x → Ex A P`
4216    ///
4217    /// The existential, over EVERY domain Lean allows. `∃ α : Type, α = Nat` is ordinary Lean —
4218    /// `Exists` there is `{α : Sort u}` — and a domain binder pinned to `Sort (Type 0)` refuses
4219    /// it outright: `Sort (Type 0) : Type 1`, and the application rule's `check_type` reports a
4220    /// `Type1`-against-`Type0` mismatch that reads like a universe bug rather than the
4221    /// expressivity gap it is.
4222    ///
4223    /// The `Prop` CODOMAIN is literal and stays that way: `Ex` landing in `Prop` over an
4224    /// arbitrary domain is exactly the impredicativity `imax` already gives, and it is what makes
4225    /// `∃ α : Type, …` a proposition rather than a `Type 1` datum.
4226    ///
4227    /// **No new primitive is needed for this.** `type_checker::implicit_levels_for_head` turns the
4228    /// free level variables of a bare `Term::Global` head's type into fresh metavariables at the
4229    /// application — the one place there is an argument to solve them from — and
4230    /// `solve_domain_levels` reads the solution off the argument's actual type. So `Ex Nat P`
4231    /// solves `u := 0` and `Ex Type0 P` solves `u := 1`, and a WRONG choice still fails, because
4232    /// `check_type` runs against the substituted domain afterwards. The de Bruijn re-checker does
4233    /// the same at its own application rule, from the same specification.
4234    fn register_ex(ctx: &mut Context) {
4235        // Ex.{u} : Π(A : Sort u). (A → Prop) → Prop
4236        let ex_type = Term::Pi {
4237            param: "A".to_string(),
4238            param_type: Box::new(Term::Sort(Universe::Var("u".to_string()))),
4239            body_type: Box::new(Term::Pi {
4240                param: "P".to_string(),
4241                param_type: Box::new(Term::Pi {
4242                    param: "_".to_string(),
4243                    param_type: Box::new(Term::Var("A".to_string())),
4244                    body_type: Box::new(Term::Sort(Universe::Prop)),
4245                }),
4246                body_type: Box::new(Term::Sort(Universe::Prop)),
4247            }),
4248        };
4249        ctx.add_inductive("Ex", ex_type);
4250
4251        // witness : Π(A : Type 0). Π(P : A → Prop). Π(x : A). P x → Ex A P
4252        //
4253        // To construct an existential proof, provide:
4254        // - A: the type being quantified over
4255        // - P: the predicate
4256        // - x: the witness (an element of A)
4257        // - proof: evidence that P(x) holds
4258        let a = Term::Var("A".to_string());
4259        let p = Term::Var("P".to_string());
4260        let x = Term::Var("x".to_string());
4261
4262        // P x = P applied to x
4263        let p_x = Term::App(Box::new(p.clone()), Box::new(x.clone()));
4264
4265        // Ex A P = Ex applied to A, then to P
4266        let ex_a_p = Term::App(
4267            Box::new(Term::App(
4268                Box::new(Term::Global("Ex".to_string())),
4269                Box::new(a.clone()),
4270            )),
4271            Box::new(p.clone()),
4272        );
4273
4274        let witness_type = Term::Pi {
4275            param: "A".to_string(),
4276            param_type: Box::new(Term::Sort(Universe::Var("u".to_string()))),
4277            body_type: Box::new(Term::Pi {
4278                param: "P".to_string(),
4279                param_type: Box::new(Term::Pi {
4280                    param: "_".to_string(),
4281                    param_type: Box::new(a.clone()),
4282                    body_type: Box::new(Term::Sort(Universe::Prop)),
4283                }),
4284                body_type: Box::new(Term::Pi {
4285                    param: "x".to_string(),
4286                    param_type: Box::new(a),
4287                    body_type: Box::new(Term::Pi {
4288                        param: "_".to_string(),
4289                        param_type: Box::new(p_x),
4290                        body_type: Box::new(ex_a_p),
4291                    }),
4292                }),
4293            }),
4294        };
4295        ctx.add_constructor("witness", "Ex", witness_type);
4296    }
4297
4298    // -------------------------------------------------------------------------
4299    // Reflection System (Deep Embedding)
4300    // -------------------------------------------------------------------------
4301
4302    /// The deep embedding: `Univ` and `Syntax`, the operations `reflection` defines over them
4303    /// (checked definitions the native rules accelerate), and the ones that remain assumptions with
4304    /// computation rules (`syn_step`, `syn_eval`, `concludes`, the tactics and their combinators).
4305    fn register_reflection(ctx: &mut Context) {
4306        Self::register_univ(ctx);
4307        Self::register_syntax(ctx);
4308        crate::reflection::register(ctx);
4309        Self::register_syn_step(ctx);
4310        Self::register_syn_eval(ctx);
4311        Self::register_derivation(ctx);
4312        Self::register_concludes(ctx);
4313        Self::register_try_refl(ctx);
4314        Self::register_try_compute(ctx);
4315        Self::register_try_cong(ctx);
4316        Self::register_tact_fail(ctx);
4317        Self::register_tact_orelse(ctx);
4318        Self::register_tact_try(ctx);
4319        Self::register_tact_repeat(ctx);
4320        Self::register_tact_then(ctx);
4321        Self::register_tact_first(ctx);
4322        Self::register_tact_solve(ctx);
4323        Self::register_try_ring(ctx);
4324        Self::register_try_lia(ctx);
4325        Self::register_try_cc(ctx);
4326        Self::register_try_simp(ctx);
4327        Self::register_try_omega(ctx);
4328        Self::register_try_auto(ctx);
4329        Self::register_try_decide(ctx);
4330        Self::register_try_intro_tactics(ctx);
4331        Self::register_tactic_sequencing(ctx);
4332        Self::register_try_induction(ctx);
4333        Self::register_induction_helpers(ctx);
4334        Self::register_try_inversion_tactic(ctx);
4335        Self::register_operator_tactics(ctx);
4336        Self::register_hw_tactics(ctx);
4337    }
4338
4339    /// Univ : Type 0 (representation of universes)
4340    /// UProp : Univ
4341    /// UType : Int -> Univ
4342    fn register_univ(ctx: &mut Context) {
4343        let univ = Term::Global("Univ".to_string());
4344        let int = Term::Global("Int".to_string());
4345
4346        // Univ : Type 0
4347        ctx.add_inductive("Univ", Term::Sort(Universe::Type(0)));
4348
4349        // UProp : Univ
4350        ctx.add_constructor("UProp", "Univ", univ.clone());
4351
4352        // UType : Int -> Univ
4353        ctx.add_constructor(
4354            "UType",
4355            "Univ",
4356            Term::Pi {
4357                param: "_".to_string(),
4358                param_type: Box::new(int),
4359                body_type: Box::new(univ),
4360            },
4361        );
4362    }
4363
4364    /// Syntax : Type 0 (representation of terms with De Bruijn indices)
4365    ///
4366    /// SVar : Int -> Syntax (De Bruijn variable index)
4367    /// SGlobal : Int -> Syntax (global reference by ID)
4368    /// SSort : Univ -> Syntax (universe)
4369    /// SApp : Syntax -> Syntax -> Syntax (application)
4370    /// SLam : Syntax -> Syntax -> Syntax (lambda: param_type, body)
4371    /// SPi : Syntax -> Syntax -> Syntax (pi: param_type, body_type)
4372    fn register_syntax(ctx: &mut Context) {
4373        let syntax = Term::Global("Syntax".to_string());
4374        let int = Term::Global("Int".to_string());
4375        let univ = Term::Global("Univ".to_string());
4376
4377        // Syntax : Type 0
4378        ctx.add_inductive("Syntax", Term::Sort(Universe::Type(0)));
4379
4380        // SVar : Int -> Syntax (De Bruijn index)
4381        ctx.add_constructor(
4382            "SVar",
4383            "Syntax",
4384            Term::Pi {
4385                param: "_".to_string(),
4386                param_type: Box::new(int.clone()),
4387                body_type: Box::new(syntax.clone()),
4388            },
4389        );
4390
4391        // SGlobal : Int -> Syntax (global reference by ID)
4392        ctx.add_constructor(
4393            "SGlobal",
4394            "Syntax",
4395            Term::Pi {
4396                param: "_".to_string(),
4397                param_type: Box::new(int.clone()),
4398                body_type: Box::new(syntax.clone()),
4399            },
4400        );
4401
4402        // SSort : Univ -> Syntax
4403        ctx.add_constructor(
4404            "SSort",
4405            "Syntax",
4406            Term::Pi {
4407                param: "_".to_string(),
4408                param_type: Box::new(univ),
4409                body_type: Box::new(syntax.clone()),
4410            },
4411        );
4412
4413        // SApp : Syntax -> Syntax -> Syntax
4414        ctx.add_constructor(
4415            "SApp",
4416            "Syntax",
4417            Term::Pi {
4418                param: "_".to_string(),
4419                param_type: Box::new(syntax.clone()),
4420                body_type: Box::new(Term::Pi {
4421                    param: "_".to_string(),
4422                    param_type: Box::new(syntax.clone()),
4423                    body_type: Box::new(syntax.clone()),
4424                }),
4425            },
4426        );
4427
4428        // SLam : Syntax -> Syntax -> Syntax (param_type, body)
4429        ctx.add_constructor(
4430            "SLam",
4431            "Syntax",
4432            Term::Pi {
4433                param: "_".to_string(),
4434                param_type: Box::new(syntax.clone()),
4435                body_type: Box::new(Term::Pi {
4436                    param: "_".to_string(),
4437                    param_type: Box::new(syntax.clone()),
4438                    body_type: Box::new(syntax.clone()),
4439                }),
4440            },
4441        );
4442
4443        // SPi : Syntax -> Syntax -> Syntax (param_type, body_type)
4444        ctx.add_constructor(
4445            "SPi",
4446            "Syntax",
4447            Term::Pi {
4448                param: "_".to_string(),
4449                param_type: Box::new(syntax.clone()),
4450                body_type: Box::new(Term::Pi {
4451                    param: "_".to_string(),
4452                    param_type: Box::new(syntax.clone()),
4453                    body_type: Box::new(syntax.clone()),
4454                }),
4455            },
4456        );
4457
4458        // SLit : Int -> Syntax (integer literal in quoted syntax)
4459        ctx.add_constructor(
4460            "SLit",
4461            "Syntax",
4462            Term::Pi {
4463                param: "_".to_string(),
4464                param_type: Box::new(int),
4465                body_type: Box::new(syntax.clone()),
4466            },
4467        );
4468
4469        // SName : Text -> Syntax (named global reference)
4470        let text = Term::Global("Text".to_string());
4471        ctx.add_constructor(
4472            "SName",
4473            "Syntax",
4474            Term::Pi {
4475                param: "_".to_string(),
4476                param_type: Box::new(text),
4477                body_type: Box::new(syntax),
4478            },
4479        );
4480    }
4481
4482    // -------------------------------------------------------------------------
4483    // De Bruijn Operations (Substitution)
4484    // -------------------------------------------------------------------------
4485
4486    // -------------------------------------------------------------------------
4487    // Beta Reduction (Computation)
4488    // -------------------------------------------------------------------------
4489
4490    /// syn_step : Syntax -> Syntax
4491    ///
4492    /// Single-step head reduction. Finds first beta redex and reduces.
4493    /// - If SApp (SLam T body) arg: perform beta reduction
4494    /// - If SApp f x where f is reducible: reduce f
4495    /// - Otherwise: return unchanged (stuck or value)
4496    /// Computational behavior defined in reduction.rs.
4497    fn register_syn_step(ctx: &mut Context) {
4498        let syntax = Term::Global("Syntax".to_string());
4499
4500        // syn_step : Syntax -> Syntax
4501        let syn_step_type = Term::Pi {
4502            param: "_".to_string(),
4503            param_type: Box::new(syntax.clone()),
4504            body_type: Box::new(syntax),
4505        };
4506
4507        ctx.add_declaration("syn_step", syn_step_type);
4508    }
4509
4510    // -------------------------------------------------------------------------
4511    // Bounded Evaluation
4512    // -------------------------------------------------------------------------
4513
4514    /// syn_eval : Int -> Syntax -> Syntax
4515    ///
4516    /// Bounded evaluation: reduce for up to N steps.
4517    /// - syn_eval fuel term
4518    /// - If fuel <= 0: return term unchanged
4519    /// - Otherwise: step and repeat until normal form or fuel exhausted
4520    /// Computational behavior defined in reduction.rs.
4521    fn register_syn_eval(ctx: &mut Context) {
4522        let syntax = Term::Global("Syntax".to_string());
4523        let int = Term::Global("Int".to_string());
4524
4525        // syn_eval : Int -> Syntax -> Syntax
4526        let syn_eval_type = Term::Pi {
4527            param: "_".to_string(),
4528            param_type: Box::new(int),
4529            body_type: Box::new(Term::Pi {
4530                param: "_".to_string(),
4531                param_type: Box::new(syntax.clone()),
4532                body_type: Box::new(syntax),
4533            }),
4534        };
4535
4536        ctx.add_declaration("syn_eval", syn_eval_type);
4537    }
4538
4539    // -------------------------------------------------------------------------
4540    // Reification (Quote)
4541    // -------------------------------------------------------------------------
4542
4543    // -------------------------------------------------------------------------
4544    // Diagonalization (Self-Reference)
4545    // -------------------------------------------------------------------------
4546
4547    // -------------------------------------------------------------------------
4548    // Inference Rules (Proof Trees)
4549    // -------------------------------------------------------------------------
4550
4551    /// Derivation : Type 0 (deep embedding of proof trees)
4552    ///
4553    /// DAxiom : Syntax -> Derivation (introduce an axiom)
4554    /// DModusPonens : Derivation -> Derivation -> Derivation (A->B, A |- B)
4555    /// DUnivIntro : Derivation -> Derivation (P(x) |- forall x. P(x))
4556    /// DUnivElim : Derivation -> Syntax -> Derivation (forall x. P(x), t |- P(t))
4557    fn register_derivation(ctx: &mut Context) {
4558        let syntax = Term::Global("Syntax".to_string());
4559        let derivation = Term::Global("Derivation".to_string());
4560
4561        // Derivation : Type 0
4562        ctx.add_inductive("Derivation", Term::Sort(Universe::Type(0)));
4563
4564        // DAxiom : Syntax -> Derivation
4565        ctx.add_constructor(
4566            "DAxiom",
4567            "Derivation",
4568            Term::Pi {
4569                param: "_".to_string(),
4570                param_type: Box::new(syntax.clone()),
4571                body_type: Box::new(derivation.clone()),
4572            },
4573        );
4574
4575        // DModusPonens : Derivation -> Derivation -> Derivation
4576        ctx.add_constructor(
4577            "DModusPonens",
4578            "Derivation",
4579            Term::Pi {
4580                param: "_".to_string(),
4581                param_type: Box::new(derivation.clone()),
4582                body_type: Box::new(Term::Pi {
4583                    param: "_".to_string(),
4584                    param_type: Box::new(derivation.clone()),
4585                    body_type: Box::new(derivation.clone()),
4586                }),
4587            },
4588        );
4589
4590        // DUnivIntro : Derivation -> Derivation
4591        ctx.add_constructor(
4592            "DUnivIntro",
4593            "Derivation",
4594            Term::Pi {
4595                param: "_".to_string(),
4596                param_type: Box::new(derivation.clone()),
4597                body_type: Box::new(derivation.clone()),
4598            },
4599        );
4600
4601        // DUnivElim : Derivation -> Syntax -> Derivation
4602        ctx.add_constructor(
4603            "DUnivElim",
4604            "Derivation",
4605            Term::Pi {
4606                param: "_".to_string(),
4607                param_type: Box::new(derivation.clone()),
4608                body_type: Box::new(Term::Pi {
4609                    param: "_".to_string(),
4610                    param_type: Box::new(syntax.clone()),
4611                    body_type: Box::new(derivation.clone()),
4612                }),
4613            },
4614        );
4615
4616        // DRefl : Syntax -> Syntax -> Derivation
4617        // DRefl T a proves (Eq T a a)
4618        ctx.add_constructor(
4619            "DRefl",
4620            "Derivation",
4621            Term::Pi {
4622                param: "_".to_string(),
4623                param_type: Box::new(syntax.clone()),
4624                body_type: Box::new(Term::Pi {
4625                    param: "_".to_string(),
4626                    param_type: Box::new(syntax.clone()),
4627                    body_type: Box::new(derivation.clone()),
4628                }),
4629            },
4630        );
4631
4632        // DInduction : Syntax -> Derivation -> Derivation -> Derivation
4633        // DInduction motive base step proves (∀n:Nat. motive n) via induction
4634        // - motive: λn:Nat. P(n) as Syntax
4635        // - base: proof of P(Zero)
4636        // - step: proof of ∀k:Nat. P(k) → P(Succ k)
4637        ctx.add_constructor(
4638            "DInduction",
4639            "Derivation",
4640            Term::Pi {
4641                param: "_".to_string(),
4642                param_type: Box::new(syntax.clone()), // motive
4643                body_type: Box::new(Term::Pi {
4644                    param: "_".to_string(),
4645                    param_type: Box::new(derivation.clone()), // base proof
4646                    body_type: Box::new(Term::Pi {
4647                        param: "_".to_string(),
4648                        param_type: Box::new(derivation.clone()), // step proof
4649                        body_type: Box::new(derivation.clone()),
4650                    }),
4651                }),
4652            },
4653        );
4654
4655        // DCompute : Syntax -> Derivation
4656        // DCompute goal proves goal by computation
4657        // - Validates that goal is (Eq T A B) and eval(A) == eval(B)
4658        ctx.add_constructor(
4659            "DCompute",
4660            "Derivation",
4661            Term::Pi {
4662                param: "_".to_string(),
4663                param_type: Box::new(syntax.clone()),
4664                body_type: Box::new(derivation.clone()),
4665            },
4666        );
4667
4668        // DCong : Syntax -> Derivation -> Derivation
4669        // DCong context eq_proof proves congruence
4670        // - context: SLam T body (function with hole at SVar 0)
4671        // - eq_proof: proof of (Eq T a b)
4672        // - Result: proof of (Eq T (body[0:=a]) (body[0:=b]))
4673        ctx.add_constructor(
4674            "DCong",
4675            "Derivation",
4676            Term::Pi {
4677                param: "_".to_string(),
4678                param_type: Box::new(syntax.clone()), // context
4679                body_type: Box::new(Term::Pi {
4680                    param: "_".to_string(),
4681                    param_type: Box::new(derivation.clone()), // eq_proof
4682                    body_type: Box::new(derivation.clone()),
4683                }),
4684            },
4685        );
4686
4687        // DCase : Derivation -> Derivation -> Derivation
4688        // Cons cell for case proofs in DElim
4689        ctx.add_constructor(
4690            "DCase",
4691            "Derivation",
4692            Term::Pi {
4693                param: "_".to_string(),
4694                param_type: Box::new(derivation.clone()), // head (case proof)
4695                body_type: Box::new(Term::Pi {
4696                    param: "_".to_string(),
4697                    param_type: Box::new(derivation.clone()), // tail (rest of cases)
4698                    body_type: Box::new(derivation.clone()),
4699                }),
4700            },
4701        );
4702
4703        // DCaseEnd : Derivation
4704        // Nil for case proofs in DElim
4705        ctx.add_constructor("DCaseEnd", "Derivation", derivation.clone());
4706
4707        // DElim : Syntax -> Syntax -> Derivation -> Derivation
4708        // Generic elimination for any inductive type
4709        // - ind_type: the inductive type (e.g., SName "Nat" or SApp (SName "List") A)
4710        // - motive: SLam param_type body (the property to prove)
4711        // - cases: DCase chain with one proof per constructor
4712        ctx.add_constructor(
4713            "DElim",
4714            "Derivation",
4715            Term::Pi {
4716                param: "_".to_string(),
4717                param_type: Box::new(syntax.clone()), // ind_type
4718                body_type: Box::new(Term::Pi {
4719                    param: "_".to_string(),
4720                    param_type: Box::new(syntax.clone()), // motive
4721                    body_type: Box::new(Term::Pi {
4722                        param: "_".to_string(),
4723                        param_type: Box::new(derivation.clone()), // cases
4724                        body_type: Box::new(derivation.clone()),
4725                    }),
4726                }),
4727            },
4728        );
4729
4730        // DInversion : Syntax -> Derivation
4731        // Proves False when no constructor can build the given hypothesis.
4732        // - hyp_type: the Syntax representation of the hypothesis (e.g., SApp (SName "Even") three)
4733        // - Returns proof of False if verified that all constructors are impossible
4734        ctx.add_constructor(
4735            "DInversion",
4736            "Derivation",
4737            Term::Pi {
4738                param: "_".to_string(),
4739                param_type: Box::new(syntax.clone()),
4740                body_type: Box::new(derivation.clone()),
4741            },
4742        );
4743
4744        // DRewrite : Derivation -> Syntax -> Syntax -> Derivation
4745        // Stores: eq_proof, original_goal, new_goal
4746        // Given eq_proof : Eq A x y, rewrites goal by replacing x with y
4747        ctx.add_constructor(
4748            "DRewrite",
4749            "Derivation",
4750            Term::Pi {
4751                param: "_".to_string(),
4752                param_type: Box::new(derivation.clone()), // eq_proof
4753                body_type: Box::new(Term::Pi {
4754                    param: "_".to_string(),
4755                    param_type: Box::new(syntax.clone()), // original_goal
4756                    body_type: Box::new(Term::Pi {
4757                        param: "_".to_string(),
4758                        param_type: Box::new(syntax.clone()), // new_goal
4759                        body_type: Box::new(derivation.clone()),
4760                    }),
4761                }),
4762            },
4763        );
4764
4765        // DDestruct : Syntax -> Syntax -> Derivation -> Derivation
4766        // Case analysis without induction hypotheses
4767        // - ind_type: the inductive type
4768        // - motive: the property to prove
4769        // - cases: DCase chain with proofs for each constructor
4770        ctx.add_constructor(
4771            "DDestruct",
4772            "Derivation",
4773            Term::Pi {
4774                param: "_".to_string(),
4775                param_type: Box::new(syntax.clone()), // ind_type
4776                body_type: Box::new(Term::Pi {
4777                    param: "_".to_string(),
4778                    param_type: Box::new(syntax.clone()), // motive
4779                    body_type: Box::new(Term::Pi {
4780                        param: "_".to_string(),
4781                        param_type: Box::new(derivation.clone()), // cases
4782                        body_type: Box::new(derivation.clone()),
4783                    }),
4784                }),
4785            },
4786        );
4787
4788        // DApply : Syntax -> Derivation -> Syntax -> Syntax -> Derivation
4789        // Manual backward chaining
4790        // - hyp_name: name of hypothesis
4791        // - hyp_proof: proof of the hypothesis
4792        // - original_goal: the goal we started with
4793        // - new_goal: the antecedent we need to prove
4794        ctx.add_constructor(
4795            "DApply",
4796            "Derivation",
4797            Term::Pi {
4798                param: "_".to_string(),
4799                param_type: Box::new(syntax.clone()), // hyp_name
4800                body_type: Box::new(Term::Pi {
4801                    param: "_".to_string(),
4802                    param_type: Box::new(derivation.clone()), // hyp_proof
4803                    body_type: Box::new(Term::Pi {
4804                        param: "_".to_string(),
4805                        param_type: Box::new(syntax.clone()), // original_goal
4806                        body_type: Box::new(Term::Pi {
4807                            param: "_".to_string(),
4808                            param_type: Box::new(syntax), // new_goal
4809                            body_type: Box::new(derivation),
4810                        }),
4811                    }),
4812                }),
4813            },
4814        );
4815    }
4816
4817    /// concludes : Derivation -> Syntax
4818    ///
4819    /// Extracts the conclusion from a derivation.
4820    /// Computational behavior defined in reduction.rs.
4821    fn register_concludes(ctx: &mut Context) {
4822        let derivation = Term::Global("Derivation".to_string());
4823        let syntax = Term::Global("Syntax".to_string());
4824
4825        // concludes : Derivation -> Syntax
4826        let concludes_type = Term::Pi {
4827            param: "_".to_string(),
4828            param_type: Box::new(derivation),
4829            body_type: Box::new(syntax),
4830        };
4831
4832        ctx.add_declaration("concludes", concludes_type);
4833    }
4834
4835    // -------------------------------------------------------------------------
4836    // Core Tactics
4837    // -------------------------------------------------------------------------
4838
4839    /// try_refl : Syntax -> Derivation
4840    ///
4841    /// Reflexivity tactic: given a goal, try to prove it by reflexivity.
4842    /// - If goal matches (Eq T a b) and a == b, returns DRefl T a
4843    /// - Otherwise returns DAxiom (SName "Error")
4844    /// Computational behavior defined in reduction.rs.
4845    fn register_try_refl(ctx: &mut Context) {
4846        let syntax = Term::Global("Syntax".to_string());
4847        let derivation = Term::Global("Derivation".to_string());
4848
4849        // try_refl : Syntax -> Derivation
4850        let try_refl_type = Term::Pi {
4851            param: "_".to_string(),
4852            param_type: Box::new(syntax),
4853            body_type: Box::new(derivation),
4854        };
4855
4856        ctx.add_declaration("try_refl", try_refl_type);
4857    }
4858
4859    /// try_compute : Syntax -> Derivation
4860    ///
4861    /// Computation tactic: given a goal (Eq T A B), proves it by evaluating
4862    /// both sides and checking equality.
4863    /// Returns DCompute goal.
4864    /// Computational behavior defined in reduction.rs.
4865    fn register_try_compute(ctx: &mut Context) {
4866        let syntax = Term::Global("Syntax".to_string());
4867        let derivation = Term::Global("Derivation".to_string());
4868
4869        // try_compute : Syntax -> Derivation
4870        let try_compute_type = Term::Pi {
4871            param: "_".to_string(),
4872            param_type: Box::new(syntax),
4873            body_type: Box::new(derivation),
4874        };
4875
4876        ctx.add_declaration("try_compute", try_compute_type);
4877    }
4878
4879    /// try_cong : Syntax -> Derivation -> Derivation
4880    ///
4881    /// Congruence tactic: given a context (SLam T body) and proof of (Eq T a b),
4882    /// produces proof of (Eq T (body[0:=a]) (body[0:=b])).
4883    /// Returns DCong context eq_proof.
4884    /// Computational behavior defined in reduction.rs.
4885    fn register_try_cong(ctx: &mut Context) {
4886        let syntax = Term::Global("Syntax".to_string());
4887        let derivation = Term::Global("Derivation".to_string());
4888
4889        // try_cong : Syntax -> Derivation -> Derivation
4890        let try_cong_type = Term::Pi {
4891            param: "_".to_string(),
4892            param_type: Box::new(syntax), // context
4893            body_type: Box::new(Term::Pi {
4894                param: "_".to_string(),
4895                param_type: Box::new(derivation.clone()), // eq_proof
4896                body_type: Box::new(derivation),
4897            }),
4898        };
4899
4900        ctx.add_declaration("try_cong", try_cong_type);
4901    }
4902
4903    // -------------------------------------------------------------------------
4904    // Tactic Combinators
4905    // -------------------------------------------------------------------------
4906
4907    /// tact_fail : Syntax -> Derivation
4908    ///
4909    /// A tactic that always fails by returning DAxiom (SName "Error").
4910    /// Useful for testing combinators and as a base case.
4911    /// Computational behavior defined in reduction.rs.
4912    fn register_tact_fail(ctx: &mut Context) {
4913        let syntax = Term::Global("Syntax".to_string());
4914        let derivation = Term::Global("Derivation".to_string());
4915
4916        // tact_fail : Syntax -> Derivation
4917        let tact_fail_type = Term::Pi {
4918            param: "_".to_string(),
4919            param_type: Box::new(syntax),
4920            body_type: Box::new(derivation),
4921        };
4922
4923        ctx.add_declaration("tact_fail", tact_fail_type);
4924    }
4925
4926    /// tact_orelse : (Syntax -> Derivation) -> (Syntax -> Derivation) -> Syntax -> Derivation
4927    ///
4928    /// Tactic combinator: try first tactic, if it fails (concludes to Error) try second.
4929    /// Enables composition of tactics with fallback behavior.
4930    /// Computational behavior defined in reduction.rs.
4931    fn register_tact_orelse(ctx: &mut Context) {
4932        let syntax = Term::Global("Syntax".to_string());
4933        let derivation = Term::Global("Derivation".to_string());
4934
4935        // Tactic type: Syntax -> Derivation
4936        let tactic_type = Term::Pi {
4937            param: "_".to_string(),
4938            param_type: Box::new(syntax.clone()),
4939            body_type: Box::new(derivation.clone()),
4940        };
4941
4942        // tact_orelse : (Syntax -> Derivation) -> (Syntax -> Derivation) -> Syntax -> Derivation
4943        let tact_orelse_type = Term::Pi {
4944            param: "_".to_string(),
4945            param_type: Box::new(tactic_type.clone()), // t1
4946            body_type: Box::new(Term::Pi {
4947                param: "_".to_string(),
4948                param_type: Box::new(tactic_type), // t2
4949                body_type: Box::new(Term::Pi {
4950                    param: "_".to_string(),
4951                    param_type: Box::new(syntax), // goal
4952                    body_type: Box::new(derivation),
4953                }),
4954            }),
4955        };
4956
4957        ctx.add_declaration("tact_orelse", tact_orelse_type);
4958    }
4959
4960    /// tact_try : (Syntax -> Derivation) -> Syntax -> Derivation
4961    ///
4962    /// Tactic combinator: try the tactic, but never fail.
4963    /// If the tactic fails (concludes to Error), return identity (DAxiom goal).
4964    /// Computational behavior defined in reduction.rs.
4965    fn register_tact_try(ctx: &mut Context) {
4966        let syntax = Term::Global("Syntax".to_string());
4967        let derivation = Term::Global("Derivation".to_string());
4968
4969        // Tactic type: Syntax -> Derivation
4970        let tactic_type = Term::Pi {
4971            param: "_".to_string(),
4972            param_type: Box::new(syntax.clone()),
4973            body_type: Box::new(derivation.clone()),
4974        };
4975
4976        // tact_try : (Syntax -> Derivation) -> Syntax -> Derivation
4977        let tact_try_type = Term::Pi {
4978            param: "_".to_string(),
4979            param_type: Box::new(tactic_type), // t
4980            body_type: Box::new(Term::Pi {
4981                param: "_".to_string(),
4982                param_type: Box::new(syntax),
4983                body_type: Box::new(derivation),
4984            }),
4985        };
4986
4987        ctx.add_declaration("tact_try", tact_try_type);
4988    }
4989
4990    /// tact_repeat : (Syntax -> Derivation) -> Syntax -> Derivation
4991    ///
4992    /// Tactic combinator: apply tactic repeatedly until it fails or makes no progress.
4993    /// Returns identity if tactic fails immediately.
4994    /// Computational behavior defined in reduction.rs.
4995    fn register_tact_repeat(ctx: &mut Context) {
4996        let syntax = Term::Global("Syntax".to_string());
4997        let derivation = Term::Global("Derivation".to_string());
4998
4999        // Tactic type: Syntax -> Derivation
5000        let tactic_type = Term::Pi {
5001            param: "_".to_string(),
5002            param_type: Box::new(syntax.clone()),
5003            body_type: Box::new(derivation.clone()),
5004        };
5005
5006        // tact_repeat : (Syntax -> Derivation) -> Syntax -> Derivation
5007        let tact_repeat_type = Term::Pi {
5008            param: "_".to_string(),
5009            param_type: Box::new(tactic_type), // t
5010            body_type: Box::new(Term::Pi {
5011                param: "_".to_string(),
5012                param_type: Box::new(syntax),
5013                body_type: Box::new(derivation),
5014            }),
5015        };
5016
5017        ctx.add_declaration("tact_repeat", tact_repeat_type);
5018    }
5019
5020    /// tact_then : (Syntax -> Derivation) -> (Syntax -> Derivation) -> Syntax -> Derivation
5021    ///
5022    /// Tactic combinator: sequence two tactics (the ";" operator).
5023    /// Apply t1 to goal, then apply t2 to the result.
5024    /// Fails if either tactic fails.
5025    /// Computational behavior defined in reduction.rs.
5026    fn register_tact_then(ctx: &mut Context) {
5027        let syntax = Term::Global("Syntax".to_string());
5028        let derivation = Term::Global("Derivation".to_string());
5029
5030        // Tactic type: Syntax -> Derivation
5031        let tactic_type = Term::Pi {
5032            param: "_".to_string(),
5033            param_type: Box::new(syntax.clone()),
5034            body_type: Box::new(derivation.clone()),
5035        };
5036
5037        // tact_then : (Syntax -> Derivation) -> (Syntax -> Derivation) -> Syntax -> Derivation
5038        let tact_then_type = Term::Pi {
5039            param: "_".to_string(),
5040            param_type: Box::new(tactic_type.clone()), // t1
5041            body_type: Box::new(Term::Pi {
5042                param: "_".to_string(),
5043                param_type: Box::new(tactic_type), // t2
5044                body_type: Box::new(Term::Pi {
5045                    param: "_".to_string(),
5046                    param_type: Box::new(syntax),
5047                    body_type: Box::new(derivation),
5048                }),
5049            }),
5050        };
5051
5052        ctx.add_declaration("tact_then", tact_then_type);
5053    }
5054
5055    /// tact_first : TList (Syntax -> Derivation) -> Syntax -> Derivation
5056    ///
5057    /// Tactic combinator: try tactics from a list until one succeeds.
5058    /// Returns Error if all tactics fail or list is empty.
5059    /// Computational behavior defined in reduction.rs.
5060    fn register_tact_first(ctx: &mut Context) {
5061        let syntax = Term::Global("Syntax".to_string());
5062        let derivation = Term::Global("Derivation".to_string());
5063
5064        // Tactic type: Syntax -> Derivation
5065        let tactic_type = Term::Pi {
5066            param: "_".to_string(),
5067            param_type: Box::new(syntax.clone()),
5068            body_type: Box::new(derivation.clone()),
5069        };
5070
5071        // TList (Syntax -> Derivation)
5072        let tactic_list_type = Term::App(
5073            Box::new(Term::Global("TList".to_string())),
5074            Box::new(tactic_type),
5075        );
5076
5077        // tact_first : TList (Syntax -> Derivation) -> Syntax -> Derivation
5078        let tact_first_type = Term::Pi {
5079            param: "_".to_string(),
5080            param_type: Box::new(tactic_list_type), // tactics
5081            body_type: Box::new(Term::Pi {
5082                param: "_".to_string(),
5083                param_type: Box::new(syntax),
5084                body_type: Box::new(derivation),
5085            }),
5086        };
5087
5088        ctx.add_declaration("tact_first", tact_first_type);
5089    }
5090
5091    /// tact_solve : (Syntax -> Derivation) -> Syntax -> Derivation
5092    ///
5093    /// Tactic combinator: tactic MUST completely solve the goal.
5094    /// If tactic returns Error, returns Error.
5095    /// If tactic returns a proof, returns that proof.
5096    /// Computational behavior defined in reduction.rs.
5097    fn register_tact_solve(ctx: &mut Context) {
5098        let syntax = Term::Global("Syntax".to_string());
5099        let derivation = Term::Global("Derivation".to_string());
5100
5101        // Tactic type: Syntax -> Derivation
5102        let tactic_type = Term::Pi {
5103            param: "_".to_string(),
5104            param_type: Box::new(syntax.clone()),
5105            body_type: Box::new(derivation.clone()),
5106        };
5107
5108        // tact_solve : (Syntax -> Derivation) -> Syntax -> Derivation
5109        let tact_solve_type = Term::Pi {
5110            param: "_".to_string(),
5111            param_type: Box::new(tactic_type), // t
5112            body_type: Box::new(Term::Pi {
5113                param: "_".to_string(),
5114                param_type: Box::new(syntax),
5115                body_type: Box::new(derivation),
5116            }),
5117        };
5118
5119        ctx.add_declaration("tact_solve", tact_solve_type);
5120    }
5121
5122    // -------------------------------------------------------------------------
5123    // Ring Tactic (Polynomial Equality)
5124    // -------------------------------------------------------------------------
5125
5126    /// DRingSolve : Syntax -> Derivation
5127    /// try_ring : Syntax -> Derivation
5128    ///
5129    /// Ring tactic: proves polynomial equalities by normalization.
5130    /// Computational behavior defined in reduction.rs.
5131    fn register_try_ring(ctx: &mut Context) {
5132        let syntax = Term::Global("Syntax".to_string());
5133        let derivation = Term::Global("Derivation".to_string());
5134
5135        // DRingSolve : Syntax -> Derivation
5136        // Proof constructor for ring-solved equalities
5137        ctx.add_constructor(
5138            "DRingSolve",
5139            "Derivation",
5140            Term::Pi {
5141                param: "_".to_string(),
5142                param_type: Box::new(syntax.clone()),
5143                body_type: Box::new(derivation.clone()),
5144            },
5145        );
5146
5147        // try_ring : Syntax -> Derivation
5148        // Ring tactic: given a goal, try to prove it by polynomial normalization
5149        let try_ring_type = Term::Pi {
5150            param: "_".to_string(),
5151            param_type: Box::new(syntax),
5152            body_type: Box::new(derivation),
5153        };
5154
5155        ctx.add_declaration("try_ring", try_ring_type);
5156    }
5157
5158    // -------------------------------------------------------------------------
5159    // LIA Tactic (Linear Integer Arithmetic)
5160    // -------------------------------------------------------------------------
5161
5162    /// DLiaSolve : Syntax -> Derivation
5163    /// try_lia : Syntax -> Derivation
5164    ///
5165    /// LIA tactic: proves linear inequalities by Fourier-Motzkin elimination.
5166    /// Computational behavior defined in reduction.rs.
5167    fn register_try_lia(ctx: &mut Context) {
5168        let syntax = Term::Global("Syntax".to_string());
5169        let derivation = Term::Global("Derivation".to_string());
5170
5171        // DLiaSolve : Syntax -> Derivation
5172        // Proof constructor for LIA-solved inequalities
5173        ctx.add_constructor(
5174            "DLiaSolve",
5175            "Derivation",
5176            Term::Pi {
5177                param: "_".to_string(),
5178                param_type: Box::new(syntax.clone()),
5179                body_type: Box::new(derivation.clone()),
5180            },
5181        );
5182
5183        // try_lia : Syntax -> Derivation
5184        // LIA tactic: given a goal, try to prove it by linear arithmetic
5185        let try_lia_type = Term::Pi {
5186            param: "_".to_string(),
5187            param_type: Box::new(syntax),
5188            body_type: Box::new(derivation),
5189        };
5190
5191        ctx.add_declaration("try_lia", try_lia_type);
5192    }
5193
5194    /// DccSolve : Syntax -> Derivation
5195    /// try_cc : Syntax -> Derivation
5196    ///
5197    /// Congruence Closure tactic: proves equalities over uninterpreted functions.
5198    /// Handles hypotheses via implications: (implies (Eq x y) (Eq (f x) (f y)))
5199    /// Computational behavior defined in reduction.rs.
5200    fn register_try_cc(ctx: &mut Context) {
5201        let syntax = Term::Global("Syntax".to_string());
5202        let derivation = Term::Global("Derivation".to_string());
5203
5204        // DccSolve : Syntax -> Derivation
5205        // Proof constructor for congruence closure proofs
5206        ctx.add_constructor(
5207            "DccSolve",
5208            "Derivation",
5209            Term::Pi {
5210                param: "_".to_string(),
5211                param_type: Box::new(syntax.clone()),
5212                body_type: Box::new(derivation.clone()),
5213            },
5214        );
5215
5216        // try_cc : Syntax -> Derivation
5217        // CC tactic: given a goal, try to prove it by congruence closure
5218        let try_cc_type = Term::Pi {
5219            param: "_".to_string(),
5220            param_type: Box::new(syntax),
5221            body_type: Box::new(derivation),
5222        };
5223
5224        ctx.add_declaration("try_cc", try_cc_type);
5225    }
5226
5227    /// DSimpSolve : Syntax -> Derivation
5228    /// try_simp : Syntax -> Derivation
5229    ///
5230    /// Simplifier tactic: proves equalities by term rewriting.
5231    /// Uses bottom-up rewriting with arithmetic evaluation and hypothesis substitution.
5232    /// Handles: reflexivity, constant folding (2+3=5), and hypothesis-based substitution.
5233    /// Computational behavior defined in reduction.rs.
5234    fn register_try_simp(ctx: &mut Context) {
5235        let syntax = Term::Global("Syntax".to_string());
5236        let derivation = Term::Global("Derivation".to_string());
5237
5238        // DSimpSolve : Syntax -> Derivation
5239        // Proof constructor for simplifier proofs
5240        ctx.add_constructor(
5241            "DSimpSolve",
5242            "Derivation",
5243            Term::Pi {
5244                param: "_".to_string(),
5245                param_type: Box::new(syntax.clone()),
5246                body_type: Box::new(derivation.clone()),
5247            },
5248        );
5249
5250        // try_simp : Syntax -> Derivation
5251        // Simp tactic: given a goal, try to prove it by simplification
5252        let try_simp_type = Term::Pi {
5253            param: "_".to_string(),
5254            param_type: Box::new(syntax),
5255            body_type: Box::new(derivation),
5256        };
5257
5258        ctx.add_declaration("try_simp", try_simp_type);
5259    }
5260
5261    /// DOmegaSolve : Syntax -> Derivation
5262    /// try_omega : Syntax -> Derivation
5263    ///
5264    /// Omega tactic: proves linear integer arithmetic with proper floor/ceil rounding.
5265    /// Unlike lia (which uses rationals), omega handles integers correctly:
5266    /// - x > 1 means x >= 2 (strict-to-nonstrict conversion)
5267    /// - 3x <= 10 means x <= 3 (floor division)
5268    /// Computational behavior defined in reduction.rs.
5269    fn register_try_omega(ctx: &mut Context) {
5270        let syntax = Term::Global("Syntax".to_string());
5271        let derivation = Term::Global("Derivation".to_string());
5272
5273        // DOmegaSolve : Syntax -> Derivation
5274        // Proof constructor for omega-solved inequalities
5275        ctx.add_constructor(
5276            "DOmegaSolve",
5277            "Derivation",
5278            Term::Pi {
5279                param: "_".to_string(),
5280                param_type: Box::new(syntax.clone()),
5281                body_type: Box::new(derivation.clone()),
5282            },
5283        );
5284
5285        // try_omega : Syntax -> Derivation
5286        // Omega tactic: given a goal, try to prove it by integer arithmetic
5287        let try_omega_type = Term::Pi {
5288            param: "_".to_string(),
5289            param_type: Box::new(syntax),
5290            body_type: Box::new(derivation),
5291        };
5292
5293        ctx.add_declaration("try_omega", try_omega_type);
5294    }
5295
5296    /// DAutoSolve : Syntax -> Derivation
5297    /// try_auto : Syntax -> Derivation
5298    ///
5299    /// Auto tactic: tries all decision procedures in sequence.
5300    /// Order: simp → ring → cc → omega → lia
5301    /// Returns the first successful derivation, or error if all fail.
5302    /// Computational behavior defined in reduction.rs.
5303    fn register_try_auto(ctx: &mut Context) {
5304        let syntax = Term::Global("Syntax".to_string());
5305        let derivation = Term::Global("Derivation".to_string());
5306
5307        // DAutoSolve : Syntax -> Derivation
5308        // Proof constructor for auto-solved goals
5309        ctx.add_constructor(
5310            "DAutoSolve",
5311            "Derivation",
5312            Term::Pi {
5313                param: "_".to_string(),
5314                param_type: Box::new(syntax.clone()),
5315                body_type: Box::new(derivation.clone()),
5316            },
5317        );
5318
5319        // try_auto : Syntax -> Derivation
5320        // Auto tactic: given a goal, try all tactics in sequence
5321        let try_auto_type = Term::Pi {
5322            param: "_".to_string(),
5323            param_type: Box::new(syntax),
5324            body_type: Box::new(derivation),
5325        };
5326
5327        ctx.add_declaration("try_auto", try_auto_type);
5328    }
5329
5330    /// try_decide : Syntax -> Derivation
5331    ///
5332    /// The `decide` tactic — decides a decidable proposition by reflection + computation. Reuses the
5333    /// `DAutoSolve` proof constructor (registered by [`register_try_auto`]), so only the tactic
5334    /// symbol needs declaring here.
5335    fn register_try_decide(ctx: &mut Context) {
5336        let syntax = Term::Global("Syntax".to_string());
5337        let derivation = Term::Global("Derivation".to_string());
5338        ctx.add_declaration(
5339            "try_decide",
5340            Term::Pi {
5341                param: "_".to_string(),
5342                param_type: Box::new(syntax),
5343                body_type: Box::new(derivation),
5344            },
5345        );
5346    }
5347
5348    /// `try_split`/`try_left`/`try_right` : Syntax -> Derivation — the ∧- and ∨-introduction
5349    /// tactics (`split`, `left`, `right`). All reuse the `DAutoSolve` proof constructor.
5350    fn register_try_intro_tactics(ctx: &mut Context) {
5351        for name in ["try_split", "try_left", "try_right", "try_assumption"] {
5352            let syntax = Term::Global("Syntax".to_string());
5353            let derivation = Term::Global("Derivation".to_string());
5354            ctx.add_declaration(
5355                name,
5356                Term::Pi {
5357                    param: "_".to_string(),
5358                    param_type: Box::new(syntax),
5359                    body_type: Box::new(derivation),
5360                },
5361            );
5362        }
5363    }
5364
5365    /// Tactic sequencing: `try_script : Syntax -> Syntax -> Derivation`. A `## Theorem … Proof:
5366    /// intro. <closer>.` parses to `try_script <name-list> <goal>`, where the name-list is a
5367    /// reflected, inert list of tactic names; its conclusion is decided by evaluating the script
5368    /// against the threaded goal + hypotheses (see `try_concludes_reduce` / `eval_script_names`).
5369    fn register_tactic_sequencing(ctx: &mut Context) {
5370        let syntax = Term::Global("Syntax".to_string());
5371        let derivation = Term::Global("Derivation".to_string());
5372        ctx.add_declaration(
5373            "try_script",
5374            Term::Pi {
5375                param: "_".to_string(),
5376                param_type: Box::new(syntax.clone()),
5377                body_type: Box::new(Term::Pi {
5378                    param: "_".to_string(),
5379                    param_type: Box::new(syntax),
5380                    body_type: Box::new(derivation),
5381                }),
5382            },
5383        );
5384    }
5385
5386    /// try_induction : Syntax -> Syntax -> Derivation -> Derivation
5387    ///
5388    /// Generic induction tactic for any inductive type.
5389    /// Arguments:
5390    /// - ind_type: The inductive type (SName "Nat" or SApp (SName "List") A)
5391    /// - motive: The property to prove (SLam param_type body)
5392    /// - cases: DCase chain with one derivation per constructor
5393    ///
5394    /// Returns a DElim derivation if verification passes.
5395    fn register_try_induction(ctx: &mut Context) {
5396        let syntax = Term::Global("Syntax".to_string());
5397        let derivation = Term::Global("Derivation".to_string());
5398
5399        // try_induction : Syntax -> Syntax -> Derivation -> Derivation
5400        let try_induction_type = Term::Pi {
5401            param: "_".to_string(),
5402            param_type: Box::new(syntax.clone()), // ind_type
5403            body_type: Box::new(Term::Pi {
5404                param: "_".to_string(),
5405                param_type: Box::new(syntax.clone()), // motive
5406                body_type: Box::new(Term::Pi {
5407                    param: "_".to_string(),
5408                    param_type: Box::new(derivation.clone()), // cases
5409                    body_type: Box::new(derivation),
5410                }),
5411            }),
5412        };
5413
5414        ctx.add_declaration("try_induction", try_induction_type);
5415    }
5416
5417    /// Helper functions for building induction goals.
5418    ///
5419    /// These functions help construct the subgoals for induction:
5420    /// - induction_base_goal: Computes the base case goal
5421    /// - induction_step_goal: Computes the step case goal for a constructor
5422    /// - induction_num_cases: Returns number of constructors for an inductive
5423    fn register_induction_helpers(ctx: &mut Context) {
5424        let syntax = Term::Global("Syntax".to_string());
5425        let nat = Term::Global("Nat".to_string());
5426
5427        // induction_base_goal : Syntax -> Syntax -> Syntax
5428        // Given ind_type and motive, returns the base case goal (first constructor)
5429        ctx.add_declaration(
5430            "induction_base_goal",
5431            Term::Pi {
5432                param: "_".to_string(),
5433                param_type: Box::new(syntax.clone()),
5434                body_type: Box::new(Term::Pi {
5435                    param: "_".to_string(),
5436                    param_type: Box::new(syntax.clone()),
5437                    body_type: Box::new(syntax.clone()),
5438                }),
5439            },
5440        );
5441
5442        // induction_step_goal : Syntax -> Syntax -> Nat -> Syntax
5443        // Given ind_type, motive, constructor index, returns the case goal
5444        ctx.add_declaration(
5445            "induction_step_goal",
5446            Term::Pi {
5447                param: "_".to_string(),
5448                param_type: Box::new(syntax.clone()),
5449                body_type: Box::new(Term::Pi {
5450                    param: "_".to_string(),
5451                    param_type: Box::new(syntax.clone()),
5452                    body_type: Box::new(Term::Pi {
5453                        param: "_".to_string(),
5454                        param_type: Box::new(nat),
5455                        body_type: Box::new(syntax.clone()),
5456                    }),
5457                }),
5458            },
5459        );
5460
5461        // induction_num_cases : Syntax -> Nat
5462        // Returns number of constructors for an inductive type
5463        ctx.add_declaration(
5464            "induction_num_cases",
5465            Term::Pi {
5466                param: "_".to_string(),
5467                param_type: Box::new(syntax),
5468                body_type: Box::new(Term::Global("Nat".to_string())),
5469            },
5470        );
5471    }
5472
5473    // -------------------------------------------------------------------------
5474    // Inversion Tactic
5475    // -------------------------------------------------------------------------
5476
5477    /// try_inversion : Syntax -> Derivation
5478    ///
5479    /// Inversion tactic: given a hypothesis type, derives False if no constructor
5480    /// can possibly build that type.
5481    ///
5482    /// Example: try_inversion (SApp (SName "Even") three) proves False because
5483    /// neither even_zero (requires 0) nor even_succ (requires Even 1) can build Even 3.
5484    ///
5485    /// Computational behavior defined in reduction.rs.
5486    fn register_try_inversion_tactic(ctx: &mut Context) {
5487        let syntax = Term::Global("Syntax".to_string());
5488        let derivation = Term::Global("Derivation".to_string());
5489
5490        // try_inversion : Syntax -> Derivation
5491        ctx.add_declaration(
5492            "try_inversion",
5493            Term::Pi {
5494                param: "_".to_string(),
5495                param_type: Box::new(syntax),
5496                body_type: Box::new(derivation),
5497            },
5498        );
5499    }
5500
5501    // -------------------------------------------------------------------------
5502    // Operator Tactics (rewrite, destruct, apply)
5503    // -------------------------------------------------------------------------
5504
5505    /// Operator tactics for manual proof control.
5506    ///
5507    /// try_rewrite : Derivation -> Syntax -> Derivation
5508    /// try_rewrite_rev : Derivation -> Syntax -> Derivation
5509    /// try_destruct : Syntax -> Syntax -> Derivation -> Derivation
5510    /// try_apply : Syntax -> Derivation -> Syntax -> Derivation
5511    fn register_operator_tactics(ctx: &mut Context) {
5512        let syntax = Term::Global("Syntax".to_string());
5513        let derivation = Term::Global("Derivation".to_string());
5514
5515        // try_rewrite : Derivation -> Syntax -> Derivation
5516        // Given eq_proof (concluding Eq A x y) and goal, replaces x with y in goal
5517        ctx.add_declaration(
5518            "try_rewrite",
5519            Term::Pi {
5520                param: "_".to_string(),
5521                param_type: Box::new(derivation.clone()), // eq_proof
5522                body_type: Box::new(Term::Pi {
5523                    param: "_".to_string(),
5524                    param_type: Box::new(syntax.clone()), // goal
5525                    body_type: Box::new(derivation.clone()),
5526                }),
5527            },
5528        );
5529
5530        // try_rewrite_rev : Derivation -> Syntax -> Derivation
5531        // Given eq_proof (concluding Eq A x y) and goal, replaces y with x in goal (reverse direction)
5532        ctx.add_declaration(
5533            "try_rewrite_rev",
5534            Term::Pi {
5535                param: "_".to_string(),
5536                param_type: Box::new(derivation.clone()), // eq_proof
5537                body_type: Box::new(Term::Pi {
5538                    param: "_".to_string(),
5539                    param_type: Box::new(syntax.clone()), // goal
5540                    body_type: Box::new(derivation.clone()),
5541                }),
5542            },
5543        );
5544
5545        // try_destruct : Syntax -> Syntax -> Derivation -> Derivation
5546        // Case analysis without induction hypotheses
5547        ctx.add_declaration(
5548            "try_destruct",
5549            Term::Pi {
5550                param: "_".to_string(),
5551                param_type: Box::new(syntax.clone()), // ind_type
5552                body_type: Box::new(Term::Pi {
5553                    param: "_".to_string(),
5554                    param_type: Box::new(syntax.clone()), // motive
5555                    body_type: Box::new(Term::Pi {
5556                        param: "_".to_string(),
5557                        param_type: Box::new(derivation.clone()), // cases
5558                        body_type: Box::new(derivation.clone()),
5559                    }),
5560                }),
5561            },
5562        );
5563
5564        // try_apply : Syntax -> Derivation -> Syntax -> Derivation
5565        // Manual backward chaining - applies hypothesis to transform goal
5566        ctx.add_declaration(
5567            "try_apply",
5568            Term::Pi {
5569                param: "_".to_string(),
5570                param_type: Box::new(syntax.clone()), // hyp_name
5571                body_type: Box::new(Term::Pi {
5572                    param: "_".to_string(),
5573                    param_type: Box::new(derivation.clone()), // hyp_proof
5574                    body_type: Box::new(Term::Pi {
5575                        param: "_".to_string(),
5576                        param_type: Box::new(syntax), // goal
5577                        body_type: Box::new(derivation),
5578                    }),
5579                }),
5580            },
5581        );
5582    }
5583
5584    // =========================================================================
5585    // HARDWARE TACTICS: try_bitblast, try_tabulate, try_hw_auto
5586    // =========================================================================
5587
5588    fn register_hw_tactics(ctx: &mut Context) {
5589        let syntax = Term::Global("Syntax".to_string());
5590        let derivation = Term::Global("Derivation".to_string());
5591
5592        // DBitblastSolve : Syntax -> Derivation
5593        ctx.add_constructor(
5594            "DBitblastSolve",
5595            "Derivation",
5596            Term::Pi {
5597                param: "_".to_string(),
5598                param_type: Box::new(syntax.clone()),
5599                body_type: Box::new(derivation.clone()),
5600            },
5601        );
5602
5603        // try_bitblast : Syntax -> Derivation
5604        ctx.add_declaration(
5605            "try_bitblast",
5606            Term::Pi {
5607                param: "_".to_string(),
5608                param_type: Box::new(syntax.clone()),
5609                body_type: Box::new(derivation.clone()),
5610            },
5611        );
5612
5613        // DTabulateSolve : Syntax -> Derivation
5614        ctx.add_constructor(
5615            "DTabulateSolve",
5616            "Derivation",
5617            Term::Pi {
5618                param: "_".to_string(),
5619                param_type: Box::new(syntax.clone()),
5620                body_type: Box::new(derivation.clone()),
5621            },
5622        );
5623
5624        // try_tabulate : Syntax -> Derivation
5625        ctx.add_declaration(
5626            "try_tabulate",
5627            Term::Pi {
5628                param: "_".to_string(),
5629                param_type: Box::new(syntax.clone()),
5630                body_type: Box::new(derivation.clone()),
5631            },
5632        );
5633
5634        // DHwAutoSolve : Syntax -> Derivation
5635        ctx.add_constructor(
5636            "DHwAutoSolve",
5637            "Derivation",
5638            Term::Pi {
5639                param: "_".to_string(),
5640                param_type: Box::new(syntax.clone()),
5641                body_type: Box::new(derivation.clone()),
5642            },
5643        );
5644
5645        // try_hw_auto : Syntax -> Derivation
5646        ctx.add_declaration(
5647            "try_hw_auto",
5648            Term::Pi {
5649                param: "_".to_string(),
5650                param_type: Box::new(syntax.clone()),
5651                body_type: Box::new(derivation),
5652            },
5653        );
5654    }
5655
5656    // =========================================================================
5657    // HARDWARE TYPES: Bit, Unit, BVec, gate operations, Circuit, BVec ops
5658    // =========================================================================
5659
5660    /// Register all hardware-related types and operations.
5661    fn register_hardware(ctx: &mut Context) {
5662        Self::register_bit(ctx);
5663        Self::register_hw_unit(ctx);
5664        Self::register_bvec(ctx);
5665        Self::register_gate_ops(ctx);
5666        Self::register_circuit(ctx);
5667        Self::register_bvec_ops(ctx);
5668    }
5669
5670    /// Bit : Type 0 — 1-bit logic value
5671    /// B0 : Bit — logic low
5672    /// B1 : Bit — logic high
5673    fn register_bit(ctx: &mut Context) {
5674        let bit = Term::Global("Bit".to_string());
5675        ctx.add_inductive("Bit", Term::Sort(Universe::Type(0)));
5676        ctx.add_constructor("B0", "Bit", bit.clone());
5677        ctx.add_constructor("B1", "Bit", bit);
5678    }
5679
5680    /// Unit : Type 0 — trivial type for stateless circuits
5681    /// Tt : Unit — sole inhabitant
5682    fn register_hw_unit(ctx: &mut Context) {
5683        let unit = Term::Global("Unit".to_string());
5684        ctx.add_inductive("Unit", Term::Sort(Universe::Type(0)));
5685        ctx.add_constructor("Tt", "Unit", unit);
5686    }
5687
5688    /// BVec : Nat -> Type 0 — length-indexed bitvector
5689    /// BVNil : BVec Zero
5690    /// BVCons : Bit -> Π(n:Nat). BVec n -> BVec (Succ n)
5691    fn register_bvec(ctx: &mut Context) {
5692        let type0 = Term::Sort(Universe::Type(0));
5693        let nat = Term::Global("Nat".to_string());
5694        let n = Term::Var("n".to_string());
5695
5696        // BVec : Nat -> Type 0 — the `Nat` is an INDEX, not a uniform parameter.
5697        //
5698        // `BVNil : BVec Zero` and `BVCons : Bit -> Π(n:Nat). BVec n -> BVec (Succ n)` target
5699        // DIFFERENT lengths, which is the definition of an index. Registering it through the
5700        // unchecked `add_inductive` recorded no `inductive_params` entry, so
5701        // `Context::inductive_num_params` fell back to the arity and answered 1 — the whole arity
5702        // treated as a parameter. The consequence was that a `Match` whose motive abstracts the
5703        // LENGTH — the only kind of match a length-indexed bitvector exists for — was untypeable,
5704        // while a match that ignored the length was accepted with branches whose result lengths
5705        // did not agree with their patterns.
5706        let bvec_type = Term::Pi {
5707            param: "n".to_string(),
5708            param_type: Box::new(nat.clone()),
5709            body_type: Box::new(type0),
5710        };
5711        ctx.add_indexed_inductive("BVec", bvec_type, 0);
5712
5713        // BVNil : BVec Zero
5714        let bvec_zero = Term::App(
5715            Box::new(Term::Global("BVec".to_string())),
5716            Box::new(Term::Global("Zero".to_string())),
5717        );
5718        ctx.add_constructor("BVNil", "BVec", bvec_zero);
5719
5720        // BVCons : Bit -> Π(n:Nat). BVec n -> BVec (Succ n)
5721        let bit = Term::Global("Bit".to_string());
5722        let bvec_n = Term::App(
5723            Box::new(Term::Global("BVec".to_string())),
5724            Box::new(n.clone()),
5725        );
5726        let bvec_succ_n = Term::App(
5727            Box::new(Term::Global("BVec".to_string())),
5728            Box::new(Term::App(
5729                Box::new(Term::Global("Succ".to_string())),
5730                Box::new(n.clone()),
5731            )),
5732        );
5733        let bvcons_type = Term::Pi {
5734            param: "_".to_string(),
5735            param_type: Box::new(bit),
5736            body_type: Box::new(Term::Pi {
5737                param: "n".to_string(),
5738                param_type: Box::new(nat),
5739                body_type: Box::new(Term::Pi {
5740                    param: "_".to_string(),
5741                    param_type: Box::new(bvec_n),
5742                    body_type: Box::new(bvec_succ_n),
5743                }),
5744            }),
5745        };
5746        ctx.add_constructor("BVCons", "BVec", bvcons_type);
5747    }
5748
5749    /// Gate operations as transparent definitions (unfold via iota reduction).
5750    ///
5751    /// bit_and : Bit -> Bit -> Bit — match a: B0 -> B0, B1 -> b
5752    /// bit_or  : Bit -> Bit -> Bit — match a: B0 -> b,  B1 -> B1
5753    /// bit_not : Bit -> Bit        — match a: B0 -> B1, B1 -> B0
5754    /// bit_xor : Bit -> Bit -> Bit — match a: B0 -> bit_not b, B1 -> b
5755    /// bit_mux : Bit -> Bit -> Bit -> Bit — match sel: B0 -> else, B1 -> then
5756    fn register_gate_ops(ctx: &mut Context) {
5757        let bit = Term::Global("Bit".to_string());
5758
5759        // Bit -> Bit -> Bit
5760        let bit2_type = Term::Pi {
5761            param: "_".to_string(),
5762            param_type: Box::new(bit.clone()),
5763            body_type: Box::new(Term::Pi {
5764                param: "_".to_string(),
5765                param_type: Box::new(bit.clone()),
5766                body_type: Box::new(bit.clone()),
5767            }),
5768        };
5769
5770        // Bit -> Bit
5771        let bit1_type = Term::Pi {
5772            param: "_".to_string(),
5773            param_type: Box::new(bit.clone()),
5774            body_type: Box::new(bit.clone()),
5775        };
5776
5777        // Bit -> Bit -> Bit -> Bit
5778        let bit3_type = Term::Pi {
5779            param: "_".to_string(),
5780            param_type: Box::new(bit.clone()),
5781            body_type: Box::new(Term::Pi {
5782                param: "_".to_string(),
5783                param_type: Box::new(bit.clone()),
5784                body_type: Box::new(Term::Pi {
5785                    param: "_".to_string(),
5786                    param_type: Box::new(bit.clone()),
5787                    body_type: Box::new(bit.clone()),
5788                }),
5789            }),
5790        };
5791
5792        // Motive for match on Bit: λ(_:Bit). Bit
5793        let motive = Term::Lambda {
5794            param: "_".to_string(),
5795            param_type: Box::new(bit.clone()),
5796            body: Box::new(bit.clone()),
5797        };
5798
5799        // bit_and := λ(a:Bit). λ(b:Bit). match a return (λ_:Bit. Bit) with [B0, b]
5800        let bit_and_body = Term::Lambda {
5801            param: "a".to_string(),
5802            param_type: Box::new(bit.clone()),
5803            body: Box::new(Term::Lambda {
5804                param: "b".to_string(),
5805                param_type: Box::new(bit.clone()),
5806                body: Box::new(Term::Match {
5807                    discriminant: Box::new(Term::Var("a".to_string())),
5808                    motive: Box::new(motive.clone()),
5809                    cases: vec![
5810                        Term::Global("B0".to_string()), // B0 case: return B0
5811                        Term::Var("b".to_string()),     // B1 case: return b
5812                    ],
5813                }),
5814            }),
5815        };
5816        ctx.add_definition("bit_and".to_string(), bit2_type.clone(), bit_and_body);
5817
5818        // bit_or := λ(a:Bit). λ(b:Bit). match a return (λ_:Bit. Bit) with [b, B1]
5819        let bit_or_body = Term::Lambda {
5820            param: "a".to_string(),
5821            param_type: Box::new(bit.clone()),
5822            body: Box::new(Term::Lambda {
5823                param: "b".to_string(),
5824                param_type: Box::new(bit.clone()),
5825                body: Box::new(Term::Match {
5826                    discriminant: Box::new(Term::Var("a".to_string())),
5827                    motive: Box::new(motive.clone()),
5828                    cases: vec![
5829                        Term::Var("b".to_string()),     // B0 case: return b
5830                        Term::Global("B1".to_string()), // B1 case: return B1
5831                    ],
5832                }),
5833            }),
5834        };
5835        ctx.add_definition("bit_or".to_string(), bit2_type.clone(), bit_or_body);
5836
5837        // bit_not := λ(a:Bit). match a return (λ_:Bit. Bit) with [B1, B0]
5838        let bit_not_body = Term::Lambda {
5839            param: "a".to_string(),
5840            param_type: Box::new(bit.clone()),
5841            body: Box::new(Term::Match {
5842                discriminant: Box::new(Term::Var("a".to_string())),
5843                motive: Box::new(motive.clone()),
5844                cases: vec![
5845                    Term::Global("B1".to_string()), // B0 case: return B1
5846                    Term::Global("B0".to_string()), // B1 case: return B0
5847                ],
5848            }),
5849        };
5850        ctx.add_definition("bit_not".to_string(), bit1_type, bit_not_body);
5851
5852        // bit_xor := λ(a:Bit). λ(b:Bit). match a return (λ_:Bit. Bit) with [b, bit_not b]
5853        // XOR truth table: 0^0=0, 0^1=1, 1^0=1, 1^1=0
5854        // When a=B0: result = b (0^0=0, 0^1=1)
5855        // When a=B1: result = bit_not b (1^0=1, 1^1=0)
5856        let bit_xor_body = Term::Lambda {
5857            param: "a".to_string(),
5858            param_type: Box::new(bit.clone()),
5859            body: Box::new(Term::Lambda {
5860                param: "b".to_string(),
5861                param_type: Box::new(bit.clone()),
5862                body: Box::new(Term::Match {
5863                    discriminant: Box::new(Term::Var("a".to_string())),
5864                    motive: Box::new(motive.clone()),
5865                    cases: vec![
5866                        // B0 case: b
5867                        Term::Var("b".to_string()),
5868                        // B1 case: bit_not b
5869                        Term::App(
5870                            Box::new(Term::Global("bit_not".to_string())),
5871                            Box::new(Term::Var("b".to_string())),
5872                        ),
5873                    ],
5874                }),
5875            }),
5876        };
5877        ctx.add_definition("bit_xor".to_string(), bit2_type, bit_xor_body);
5878
5879        // bit_mux := λ(sel:Bit). λ(then_v:Bit). λ(else_v:Bit).
5880        //            match sel return (λ_:Bit. Bit) with [else_v, then_v]
5881        let bit_mux_body = Term::Lambda {
5882            param: "sel".to_string(),
5883            param_type: Box::new(bit.clone()),
5884            body: Box::new(Term::Lambda {
5885                param: "then_v".to_string(),
5886                param_type: Box::new(bit.clone()),
5887                body: Box::new(Term::Lambda {
5888                    param: "else_v".to_string(),
5889                    param_type: Box::new(bit.clone()),
5890                    body: Box::new(Term::Match {
5891                        discriminant: Box::new(Term::Var("sel".to_string())),
5892                        motive: Box::new(motive),
5893                        cases: vec![
5894                            Term::Var("else_v".to_string()), // B0 case: else
5895                            Term::Var("then_v".to_string()), // B1 case: then
5896                        ],
5897                    }),
5898                }),
5899            }),
5900        };
5901        ctx.add_definition("bit_mux".to_string(), bit3_type, bit_mux_body);
5902    }
5903
5904    /// Circuit : Type 0 -> Type 0 -> Type 0 -> Type 0
5905    /// MkCircuit : Π(S:Type 0). Π(I:Type 0). Π(O:Type 0).
5906    ///             (S -> I -> S) -> (S -> I -> O) -> S -> Circuit S I O
5907    fn register_circuit(ctx: &mut Context) {
5908        let type0 = Term::Sort(Universe::Type(0));
5909        let s = Term::Var("S".to_string());
5910        let i = Term::Var("I".to_string());
5911        let o = Term::Var("O".to_string());
5912
5913        // Circuit : Type 0 -> Type 0 -> Type 0 -> Type 0
5914        let circuit_type = Term::Pi {
5915            param: "S".to_string(),
5916            param_type: Box::new(type0.clone()),
5917            body_type: Box::new(Term::Pi {
5918                param: "I".to_string(),
5919                param_type: Box::new(type0.clone()),
5920                body_type: Box::new(Term::Pi {
5921                    param: "O".to_string(),
5922                    param_type: Box::new(type0.clone()),
5923                    body_type: Box::new(type0.clone()),
5924                }),
5925            }),
5926        };
5927        ctx.add_inductive("Circuit", circuit_type);
5928
5929        // Circuit S I O
5930        let circuit_s_i_o = Term::App(
5931            Box::new(Term::App(
5932                Box::new(Term::App(
5933                    Box::new(Term::Global("Circuit".to_string())),
5934                    Box::new(s.clone()),
5935                )),
5936                Box::new(i.clone()),
5937            )),
5938            Box::new(o.clone()),
5939        );
5940
5941        // S -> I -> S (transition function type)
5942        let trans_type = Term::Pi {
5943            param: "_".to_string(),
5944            param_type: Box::new(s.clone()),
5945            body_type: Box::new(Term::Pi {
5946                param: "_".to_string(),
5947                param_type: Box::new(i.clone()),
5948                body_type: Box::new(s.clone()),
5949            }),
5950        };
5951
5952        // S -> I -> O (output function type)
5953        let out_type = Term::Pi {
5954            param: "_".to_string(),
5955            param_type: Box::new(s.clone()),
5956            body_type: Box::new(Term::Pi {
5957                param: "_".to_string(),
5958                param_type: Box::new(i.clone()),
5959                body_type: Box::new(o.clone()),
5960            }),
5961        };
5962
5963        // MkCircuit : Π(S:Type0). Π(I:Type0). Π(O:Type0).
5964        //             (S->I->S) -> (S->I->O) -> S -> Circuit S I O
5965        let mkcircuit_type = Term::Pi {
5966            param: "S".to_string(),
5967            param_type: Box::new(type0.clone()),
5968            body_type: Box::new(Term::Pi {
5969                param: "I".to_string(),
5970                param_type: Box::new(type0.clone()),
5971                body_type: Box::new(Term::Pi {
5972                    param: "O".to_string(),
5973                    param_type: Box::new(type0),
5974                    body_type: Box::new(Term::Pi {
5975                        param: "_".to_string(),
5976                        param_type: Box::new(trans_type),
5977                        body_type: Box::new(Term::Pi {
5978                            param: "_".to_string(),
5979                            param_type: Box::new(out_type),
5980                            body_type: Box::new(Term::Pi {
5981                                param: "_".to_string(),
5982                                param_type: Box::new(s),
5983                                body_type: Box::new(circuit_s_i_o),
5984                            }),
5985                        }),
5986                    }),
5987                }),
5988            }),
5989        };
5990        ctx.add_constructor("MkCircuit", "Circuit", mkcircuit_type);
5991    }
5992
5993    /// Bitvector operations as recursive Fix definitions.
5994    /// bv_and, bv_or, bv_not, bv_xor : Π(n:Nat). BVec n -> BVec n -> BVec n
5995    fn register_bvec_ops(ctx: &mut Context) {
5996        let nat = Term::Global("Nat".to_string());
5997        let n = Term::Var("n".to_string());
5998        let bvec_n = Term::App(
5999            Box::new(Term::Global("BVec".to_string())),
6000            Box::new(n.clone()),
6001        );
6002
6003        // Π(n:Nat). BVec n -> BVec n -> BVec n
6004        let bv_binop_type = Term::Pi {
6005            param: "n".to_string(),
6006            param_type: Box::new(nat.clone()),
6007            body_type: Box::new(Term::Pi {
6008                param: "_".to_string(),
6009                param_type: Box::new(bvec_n.clone()),
6010                body_type: Box::new(Term::Pi {
6011                    param: "_".to_string(),
6012                    param_type: Box::new(bvec_n.clone()),
6013                    body_type: Box::new(bvec_n.clone()),
6014                }),
6015            }),
6016        };
6017
6018        // Π(n:Nat). BVec n -> BVec n
6019        let bv_unop_type = Term::Pi {
6020            param: "n".to_string(),
6021            param_type: Box::new(nat.clone()),
6022            body_type: Box::new(Term::Pi {
6023                param: "_".to_string(),
6024                param_type: Box::new(bvec_n.clone()),
6025                body_type: Box::new(bvec_n.clone()),
6026            }),
6027        };
6028
6029        let bit = Term::Global("Bit".to_string());
6030
6031        for (name, rec, op) in [
6032            ("bv_and", "bv_and_rec", "bit_and"),
6033            ("bv_or", "bv_or_rec", "bit_or"),
6034            ("bv_xor", "bv_xor_rec", "bit_xor"),
6035        ] {
6036            let body = Self::make_bvec_binop_fix(rec, op, &nat, &bvec_n, &bit);
6037            ctx.add_definition(name.to_string(), bv_binop_type.clone(), body);
6038        }
6039
6040        let bv_not_body = Self::make_bvec_unop_fix("bv_not_rec", "bit_not", &nat, &bvec_n, &bit);
6041        ctx.add_definition("bv_not".to_string(), bv_unop_type, bv_not_body);
6042    }
6043
6044    /// `λ(k:Nat). λ(_:BVec k). <result k>` — the motive shape an INDEXED `BVec` match takes:
6045    /// it abstracts the length as well as the vector, so each branch is checked at its own
6046    /// length. This is the whole difference the index makes, and it is why every branch below
6047    /// returns a vector whose length matches its pattern rather than whatever the scrutinee had.
6048    fn bvec_motive(result: Term) -> Term {
6049        lam_(
6050            "bvLen",
6051            gl("Nat"),
6052            lam_(
6053                "_",
6054                Term::App(Box::new(gl("BVec")), Box::new(v_("bvLen"))),
6055                result,
6056            ),
6057        )
6058    }
6059
6060    /// `match k with Zero => Zero | Succ j => j` — `Nat.pred`, inline.
6061    ///
6062    /// Written in place rather than registered as a prelude constant: it exists only to spell
6063    /// the RESULT LENGTH of a tail projection (`BVec k → BVec (pred k)`), and a new global would
6064    /// be a name in the standard library that nothing else needs.
6065    fn nat_pred_of(k: Term) -> Term {
6066        Term::Match {
6067            discriminant: Box::new(k),
6068            motive: Box::new(lam_("_", gl("Nat"), gl("Nat"))),
6069            cases: vec![gl("Zero"), lam_("j", gl("Nat"), v_("j"))],
6070        }
6071    }
6072
6073    /// `head w` — the leading bit of `w : BVec k`, `B0` at the empty vector.
6074    ///
6075    /// Total by construction, which is what makes it usable inside a length-indexed recursion:
6076    /// the empty case is REACHABLE at the type level even where the caller knows it cannot occur,
6077    /// and a partial projection would need an unreachability proof the matcher cannot synthesise.
6078    fn bvec_head_of(w: Term) -> Term {
6079        Term::Match {
6080            discriminant: Box::new(w),
6081            motive: Box::new(Self::bvec_motive(gl("Bit"))),
6082            cases: vec![
6083                gl("B0"),
6084                lam_(
6085                    "b",
6086                    gl("Bit"),
6087                    lam_(
6088                        "m",
6089                        gl("Nat"),
6090                        lam_(
6091                            "t",
6092                            Term::App(Box::new(gl("BVec")), Box::new(v_("m"))),
6093                            v_("b"),
6094                        ),
6095                    ),
6096                ),
6097            ],
6098        }
6099    }
6100
6101    /// `tail w : BVec (pred k)` for `w : BVec k`. At `k = Succ m` the result type ι-reduces to
6102    /// `BVec m`, which is exactly the length the recursive call needs.
6103    fn bvec_tail_of(w: Term) -> Term {
6104        Term::Match {
6105            discriminant: Box::new(w),
6106            motive: Box::new(Self::bvec_motive(Term::App(
6107                Box::new(gl("BVec")),
6108                Box::new(Self::nat_pred_of(v_("bvLen"))),
6109            ))),
6110            cases: vec![
6111                gl("BVNil"),
6112                lam_(
6113                    "b",
6114                    gl("Bit"),
6115                    lam_(
6116                        "m",
6117                        gl("Nat"),
6118                        lam_(
6119                            "t",
6120                            Term::App(Box::new(gl("BVec")), Box::new(v_("m"))),
6121                            v_("t"),
6122                        ),
6123                    ),
6124                ),
6125            ],
6126        }
6127    }
6128
6129    /// `bv_and`/`bv_or`/`bv_xor` — a pointwise fold over two vectors of the SAME length,
6130    /// written so that every branch's result length is the one its pattern forces.
6131    ///
6132    ///   fix rec. λn. λv1. λv2.
6133    ///     (match v1 return λ(k:Nat). λ(_:BVec k). BVec k → BVec k with
6134    ///      | BVNil            => λ_. BVNil
6135    ///      | BVCons b1 m t1   => λw. BVCons (op b1 (head w)) m (rec m t1 (tail w))) v2
6136    ///
6137    /// The shape is forced by the index, and the forcing is the point. Matching `v1` and then
6138    /// `v2` independently — the pre-index spelling — cannot type-check once the length is an
6139    /// index: after `v1` matches `BVCons b1 m t1` the result must be a `BVec (Succ m)`, and a
6140    /// second match on `v2` would have to produce that from a `BVNil` branch whose pattern says
6141    /// `BVec Zero`. Only Lean-style INDEX REFINEMENT (learning `n ≡ Succ m` inside the branch)
6142    /// would let the two matches be siblings, and `infer_indexed_match` does not refine.
6143    ///
6144    /// So the second vector is consumed by the total projections `head`/`tail` instead, at the
6145    /// length the FIRST vector fixed. Every branch is well-typed at its own index, the recursion
6146    /// still ι-computes on constructor-form vectors, and the denotation is unchanged.
6147    fn make_bvec_binop_fix(
6148        rec_name: &str,
6149        bit_op: &str,
6150        nat: &Term,
6151        bvec_n: &Term,
6152        bit: &Term,
6153    ) -> Term {
6154        let bvec_at = |k: Term| Term::App(Box::new(gl("BVec")), Box::new(k));
6155        // motive: λ(k:Nat). λ(_:BVec k). BVec k → BVec k
6156        let motive = Self::bvec_motive(arrow_(bvec_at(v_("bvLen")), bvec_at(v_("bvLen"))));
6157
6158        // BVCons (bit_op b1 (head w)) m (rec m t1 (tail w))
6159        let combined = apps_(gl(bit_op), &[v_("b1"), Self::bvec_head_of(v_("w"))]);
6160        let recursed = apps_(
6161            v_(rec_name),
6162            &[v_("m"), v_("t1"), Self::bvec_tail_of(v_("w"))],
6163        );
6164        let cons_case = lam_(
6165            "b1",
6166            bit.clone(),
6167            lam_(
6168                "m",
6169                nat.clone(),
6170                lam_(
6171                    "t1",
6172                    bvec_at(v_("m")),
6173                    lam_(
6174                        "w",
6175                        bvec_at(Term::App(Box::new(gl("Succ")), Box::new(v_("m")))),
6176                        apps_(gl("BVCons"), &[combined, v_("m"), recursed]),
6177                    ),
6178                ),
6179            ),
6180        );
6181        let nil_case = lam_("_", bvec_at(gl("Zero")), gl("BVNil"));
6182
6183        let dispatch = Term::Match {
6184            discriminant: Box::new(v_("v1")),
6185            motive: Box::new(motive),
6186            cases: vec![nil_case, cons_case],
6187        };
6188
6189        Term::Fix {
6190            name: rec_name.to_string(),
6191            body: Box::new(lam_(
6192                "n",
6193                nat.clone(),
6194                lam_(
6195                    "v1",
6196                    bvec_n.clone(),
6197                    lam_(
6198                        "v2",
6199                        bvec_n.clone(),
6200                        Term::App(Box::new(dispatch), Box::new(v_("v2"))),
6201                    ),
6202                ),
6203            )),
6204        }
6205    }
6206
6207    /// `bv_not` — the unary fold. A single vector needs no index refinement: each branch returns
6208    /// a vector at exactly its pattern's length.
6209    ///
6210    ///   fix rec. λn. λv.
6211    ///     match v return λ(k:Nat). λ(_:BVec k). BVec k with
6212    ///     | BVNil          => BVNil
6213    ///     | BVCons b m t   => BVCons (op b) m (rec m t)
6214    fn make_bvec_unop_fix(
6215        rec_name: &str,
6216        bit_op: &str,
6217        nat: &Term,
6218        bvec_n: &Term,
6219        bit: &Term,
6220    ) -> Term {
6221        let bvec_at = |k: Term| Term::App(Box::new(gl("BVec")), Box::new(k));
6222        let motive = Self::bvec_motive(bvec_at(v_("bvLen")));
6223        let cons_case = lam_(
6224            "b",
6225            bit.clone(),
6226            lam_(
6227                "m",
6228                nat.clone(),
6229                lam_(
6230                    "t",
6231                    bvec_at(v_("m")),
6232                    apps_(
6233                        gl("BVCons"),
6234                        &[
6235                            Term::App(Box::new(gl(bit_op)), Box::new(v_("b"))),
6236                            v_("m"),
6237                            apps_(v_(rec_name), &[v_("m"), v_("t")]),
6238                        ],
6239                    ),
6240                ),
6241            ),
6242        );
6243        Term::Fix {
6244            name: rec_name.to_string(),
6245            body: Box::new(lam_(
6246                "n",
6247                nat.clone(),
6248                lam_(
6249                    "v",
6250                    bvec_n.clone(),
6251                    Term::Match {
6252                        discriminant: Box::new(v_("v")),
6253                        motive: Box::new(motive),
6254                        cases: vec![gl("BVNil"), cons_case],
6255                    },
6256                ),
6257            )),
6258        }
6259    }
6260
6261    // =========================================================================
6262    // THE STRUCTURAL TYPES LEAN CORE SHIPS
6263    // =========================================================================
6264
6265    /// `Option`, `Prod`, `Sum`, `Sigma`, `Subtype`, `Fin`, `List`, `Array`, the machine widths,
6266    /// `Char`/`String`, `Iff`, `Subsingleton`/`Squash` and `Inhabited`/`Nonempty` — the layer a
6267    /// mathematician needs before a statement can even be WRITTEN.
6268    ///
6269    /// Three decisions run through all of it.
6270    ///
6271    /// **Everything is defined, nothing is assumed.** Not one of these is an
6272    /// `add_declaration`: they are inductives, structures and definitions with bodies, so every
6273    /// projection and every eliminator ι-reduces and the trusted base is exactly the size it was.
6274    /// An axiomatised `Array_get` would type-check and never compute, which turns a capability
6275    /// gap into a `rfl` that silently stops holding far from the declaration.
6276    ///
6277    /// **`Type 0` only, and said out loud.** Lean's `Prod` is
6278    /// `Type u → Type v → Type (max u v)`; `add_inductive` takes ONE fixed sort and there is no
6279    /// level-parameter list on an inductive, so every type here is its `Type 0` instance. That is
6280    /// a genuine restriction, not a monomorphisation trick: the names mean the `Type 0` family
6281    /// and nothing above it.
6282    ///
6283    /// **The bound is computed, never assumed.** `Fin` needs a `Nat` order, and every order
6284    /// primitive in the prelude is `Int → Int → Bool` with sixteen `Int` axioms behind it.
6285    /// Rather than a second axiom set for `Nat`, the bound uses the prelude's own shallow idiom:
6286    /// [`Self::register_nat_order`] defines `natLe`/`natLt` by structural recursion, and
6287    /// `Nat_lt i n` is `Eq Bool (natLt i n) true` — inhabited by `refl` exactly when the bound
6288    /// holds, and UNINHABITED when it does not, decided by ι-reduction.
6289    fn register_core_types(ctx: &mut Context) {
6290        Self::register_iff(ctx);
6291        Self::register_nat_order(ctx);
6292        Self::register_option(ctx);
6293        Self::register_prod(ctx);
6294        Self::register_sum(ctx);
6295        Self::register_sigma(ctx);
6296        Self::register_subtype(ctx);
6297        Self::register_fin(ctx);
6298        Self::register_list(ctx);
6299        Self::register_array(ctx);
6300        Self::register_machine_words(ctx);
6301        Self::register_char_and_string(ctx);
6302        Self::register_truncation(ctx);
6303        Self::register_inhabited(ctx);
6304        Self::register_ofnat(ctx);
6305    }
6306
6307    /// Numeral dictionaries, generalized to Sort u; Lean's Type u instances use the
6308    /// corresponding successor level. The Nat dictionary is a checked definition.
6309    fn register_ofnat(ctx: &mut Context) {
6310        let v = |name: &str| Term::Var(name.to_string());
6311        let level = Universe::Var("u".to_string());
6312        ctx.add_structure_poly_at(
6313            "OfNat",
6314            vec!["u".to_string()],
6315            level.clone(),
6316            &[("A", Term::Sort(level)), ("n", gl("Nat"))],
6317            &[("ofNat", v("A"))],
6318        )
6319        .expect("the OfNat dictionary is well formed");
6320        let at_nat = |name: &str| Term::Const {
6321            name: name.to_string(),
6322            levels: vec![Universe::Type(0)],
6323        };
6324        let ty = pi_("n", gl("Nat"), apps_(at_nat("OfNat"), &[gl("Nat"), v("n")]));
6325        let body = lam_(
6326            "n",
6327            gl("Nat"),
6328            apps_(at_nat("OfNat_mk"), &[gl("Nat"), v("n"), v("n")]),
6329        );
6330        ctx.add_definition("instOfNatNat".to_string(), ty.clone(), body);
6331        ctx.add_fallback_instance(ty, gl("instOfNatNat"));
6332        ctx.set_binder_kinds(
6333            "OfNat_ofNat",
6334            vec![
6335                crate::elaborate::ParamKind::Implicit,
6336                crate::elaborate::ParamKind::Explicit,
6337                crate::elaborate::ParamKind::Instance,
6338            ],
6339        );
6340    }
6341
6342    /// `Iff : Prop → Prop → Prop := λp q. And (p → q) (q → p)`.
6343    ///
6344    /// A DEFINITION, so `↔` is δ-transparent to the conjunction and `.mp`/`.mpr` are the `And`
6345    /// projections. A fresh inductive would be a different proposition that nothing — `propext`
6346    /// included — can bridge back to `And`, and an axiom would have no elimination at all.
6347    fn register_iff(ctx: &mut Context) {
6348        let prop = || Term::Sort(Universe::Prop);
6349        let v = |s: &str| Term::Var(s.to_string());
6350        ctx.add_definition(
6351            "Iff".to_string(),
6352            pi_("p", prop(), pi_("q", prop(), prop())),
6353            lam_(
6354                "p",
6355                prop(),
6356                lam_(
6357                    "q",
6358                    prop(),
6359                    apps_(gl("And"), &[arrow_(v("p"), v("q")), arrow_(v("q"), v("p"))]),
6360                ),
6361            ),
6362        );
6363    }
6364
6365    /// The `Nat` order, as a COMPUTATION rather than an axiom set.
6366    ///
6367    /// ```text
6368    /// natLe : Nat → Nat → Bool := fix f. λm n. match m { 0 => true
6369    ///                                                  | m+1 => match n { 0 => false
6370    ///                                                                   | n+1 => f m n } }
6371    /// natLt m n := natLe (Succ m) n
6372    /// Nat_le m n : Prop := Eq Bool (natLe m n) true
6373    /// Nat_lt m n : Prop := Eq Bool (natLt m n) true
6374    /// ```
6375    ///
6376    /// Two properties earn this shape. The recursion stops as soon as EITHER operand reaches
6377    /// `Zero`, so a decision costs `min(m, n)` steps — a small index into a `2^64` range is
6378    /// cheap, which is what makes `UInt64` usable. And `natLt i Zero` reduces to `false` for an
6379    /// OPEN `i`, because the match is on `Succ i`, which is already a constructor application —
6380    /// so `Fin 0` is uninhabited by computation, with no lemma to prove.
6381    ///
6382    /// The literal bridge does the rest: `Literal::Nat(n)` peels one `Succ` per step, so the
6383    /// order works on compact literals of any size without materialising a Peano spine.
6384    fn register_nat_order(ctx: &mut Context) {
6385        let nat = || gl("Nat");
6386        let bool_ty = || gl("Bool");
6387        let v = |s: &str| Term::Var(s.to_string());
6388        let succ = |x: Term| Term::App(Box::new(gl("Succ")), Box::new(x));
6389
6390        // match n { Zero => false, Succ n' => f m' n' }
6391        let inner = Term::Match {
6392            discriminant: Box::new(v("n")),
6393            motive: Box::new(lam_("_", nat(), bool_ty())),
6394            cases: vec![
6395                gl("false"),
6396                lam_("n✧", nat(), apps_(v("natLe✧"), &[v("m✧"), v("n✧")])),
6397            ],
6398        };
6399        // match m { Zero => true, Succ m' => inner }
6400        let outer = Term::Match {
6401            discriminant: Box::new(v("m")),
6402            motive: Box::new(lam_("_", nat(), bool_ty())),
6403            cases: vec![gl("true"), lam_("m✧", nat(), inner)],
6404        };
6405        let nat_le_body = Term::Fix {
6406            name: "natLe✧".to_string(),
6407            body: Box::new(lam_("m", nat(), lam_("n", nat(), outer))),
6408        };
6409        let binop = || pi_("_", nat(), pi_("_", nat(), bool_ty()));
6410        ctx.add_definition("natLe".to_string(), binop(), nat_le_body);
6411
6412        // natLt m n := natLe (Succ m) n
6413        ctx.add_definition(
6414            "natLt".to_string(),
6415            binop(),
6416            lam_(
6417                "m",
6418                nat(),
6419                lam_("n", nat(), apps_(gl("natLe"), &[succ(v("m")), v("n")])),
6420            ),
6421        );
6422
6423        // The Prop layer a bound proof inhabits: `Eq Bool (natLe m n) true`, the same shallow
6424        // idiom the Int order axioms are stated over.
6425        let prop_of = |op: &str| {
6426            lam_(
6427                "m",
6428                nat(),
6429                lam_(
6430                    "n",
6431                    nat(),
6432                    apps_(
6433                        gl("Eq"),
6434                        &[bool_ty(), apps_(gl(op), &[v("m"), v("n")]), gl("true")],
6435                    ),
6436                ),
6437            )
6438        };
6439        let rel = || pi_("_", nat(), pi_("_", nat(), Term::Sort(Universe::Prop)));
6440        ctx.add_definition("Nat_le".to_string(), rel(), prop_of("natLe"));
6441        ctx.add_definition("Nat_lt".to_string(), rel(), prop_of("natLt"));
6442
6443        // THE DECISION PROCEDURES. `if n < 10 then … else …` is most of what an `if` in
6444        // mathematics branches on, and until now the prelude shipped decidable EQUALITY and
6445        // nothing else — the ordering could be stated and never decided.
6446        //
6447        //   decLeNat : Π(a b:Nat). Decidable (Nat_le a b)
6448        //   decLtNat : Π(a b:Nat). Decidable (Nat_lt a b)
6449        //
6450        // Both are DEFINITIONS, not axioms, and they cost the trusted base nothing: `Nat_le a b`
6451        // IS `Eq Bool (natLe a b) true`, so the decision is `decEqBool` at the computed Boolean.
6452        // `decEqBool` already carries both proofs — `refl` on the true side and the derived
6453        // `true ≠ false` refutation on the false side — so the `isFalse` branch receives a REAL
6454        // `Not (Nat_lt a b)` rather than an assumption, and the whole thing ι-reduces: `natLe`
6455        // computes the Boolean, `decEqBool` matches on it, and the branch is selected.
6456        //
6457        // Deliberately NOT a redefinition of the `Int` builtin `lt`. That builtin is an opaque
6458        // `Int → Int → Bool` and giving it a Nat ordering would make the gap look like a naming
6459        // problem while changing what every existing `Int` comparison means.
6460        let dec_of = |op: &str, rel_name: &str| {
6461            (
6462                pi_(
6463                    "a",
6464                    nat(),
6465                    pi_(
6466                        "b",
6467                        nat(),
6468                        Term::App(
6469                            Box::new(gl("Decidable")),
6470                            Box::new(apps_(gl(rel_name), &[v("a"), v("b")])),
6471                        ),
6472                    ),
6473                ),
6474                lam_(
6475                    "a",
6476                    nat(),
6477                    lam_(
6478                        "b",
6479                        nat(),
6480                        apps_(
6481                            gl("decEqBool"),
6482                            &[apps_(gl(op), &[v("a"), v("b")]), gl("true")],
6483                        ),
6484                    ),
6485                ),
6486            )
6487        };
6488        let (le_ty, le_body) = dec_of("natLe", "Nat_le");
6489        ctx.add_definition("decLeNat".to_string(), le_ty, le_body);
6490        let (lt_ty, lt_body) = dec_of("natLt", "Nat_lt");
6491        ctx.add_definition("decLtNat".to_string(), lt_ty, lt_body);
6492    }
6493
6494    /// `Option A` — `none` registered BEFORE `some`, as in Lean, so a translator that preserves
6495    /// source order lands on the right branch.
6496    ///
6497    /// `Option` is Lean's core container. Registering it does not register a monad: `Bind`,
6498    /// `Pure` and the rest of the do-notation surface stay absent, because an axiomatised `bind`
6499    /// would never reduce.
6500    fn register_option(ctx: &mut Context) {
6501        let type0 = || Term::Sort(Universe::Type(0));
6502        let v = |s: &str| Term::Var(s.to_string());
6503        let opt_a = || Term::App(Box::new(gl("Option")), Box::new(v("A")));
6504
6505        ctx.add_indexed_inductive("Option", pi_("A", type0(), type0()), 1);
6506        Self::checked_ctor(ctx, "none", "Option", pi_("A", type0(), opt_a()));
6507        Self::checked_ctor(
6508            ctx,
6509            "some",
6510            "Option",
6511            pi_("A", type0(), arrow_(v("A"), opt_a())),
6512        );
6513    }
6514
6515    pub(crate) fn division_carrier_reference() -> &'static Context {
6516        static REFERENCE: std::sync::OnceLock<Context> = std::sync::OnceLock::new();
6517        REFERENCE.get_or_init(|| {
6518            let mut ctx = Context::new();
6519            ctx.with_equations_suspended(|ctx| {
6520                Self::register_bool(ctx);
6521                Self::register_prod(ctx);
6522            });
6523            ctx
6524        })
6525    }
6526
6527    /// `Prod A B` with `fst`/`snd`, through `add_structure` — the only path that registers the
6528    /// [`crate::context::StructInfo`] gating definitional eta, so `⟨p.1, p.2⟩ ≡ p`.
6529    fn register_prod(ctx: &mut Context) {
6530        let type0 = Term::Sort(Universe::Type(0));
6531        let v = |s: &str| Term::Var(s.to_string());
6532        ctx.add_structure(
6533            "Prod",
6534            &[("A", type0.clone()), ("B", type0)],
6535            &[("fst", v("A")), ("snd", v("B"))],
6536        );
6537    }
6538
6539    /// `Sum A B` with `Sum_inl`/`Sum_inr`.
6540    ///
6541    /// The injections are NOT spelled `inl`/`inr`: the prelude's disjunction `Or` already owns
6542    /// `left`/`right`, and `Or` is the Prop-valued one whose eliminator's motive is pinned to
6543    /// `Prop`. Keeping the two apart is what stops a `Type`-valued case analysis from being
6544    /// written against a proof.
6545    fn register_sum(ctx: &mut Context) {
6546        let type0 = || Term::Sort(Universe::Type(0));
6547        let v = |s: &str| Term::Var(s.to_string());
6548        let sum_ab = || apps_(gl("Sum"), &[v("A"), v("B")]);
6549
6550        ctx.add_indexed_inductive("Sum", pi_("A", type0(), pi_("B", type0(), type0())), 2);
6551        for (name, field) in [("Sum_inl", "A"), ("Sum_inr", "B")] {
6552            Self::checked_ctor(
6553                ctx,
6554                name,
6555                "Sum",
6556                pi_("A", type0(), pi_("B", type0(), arrow_(v(field), sum_ab()))),
6557            );
6558        }
6559    }
6560
6561    /// `Sigma A B` — the genuinely DEPENDENT pair: `snd`'s TYPE mentions `fst`'s VALUE, so
6562    /// `s.2 : B s.1`. Erasing that dependency gives a constant motive and the wrong projection
6563    /// type, which type-checks and means something else.
6564    fn register_sigma(ctx: &mut Context) {
6565        let type0 = || Term::Sort(Universe::Type(0));
6566        let v = |s: &str| Term::Var(s.to_string());
6567        ctx.add_structure(
6568            "Sigma",
6569            &[("A", type0()), ("B", arrow_(v("A"), type0()))],
6570            &[
6571                ("fst", v("A")),
6572                ("snd", Term::App(Box::new(v("B")), Box::new(v("fst")))),
6573            ],
6574        );
6575    }
6576
6577    /// `PSigma A B` — Lean's `PSigma.{u, v}`, the dependent pair at ANY sorts: `A : Sort u` and
6578    /// `B : A → Sort v`, in `Sort (max 1 u v)`, the least sort that stores both, as
6579    /// `add_structure_poly` computes it. `Sigma` above is the `Type 0` pair a type-level
6580    /// development writes; this is the one `Quot_rec` is built over, because a quotient's carrier
6581    /// is `Sort u` and so is the first component of the pair `Quot_lift` targets.
6582    fn register_psigma(ctx: &mut Context) {
6583        let v = |s: &str| Term::Var(s.to_string());
6584        let sort = |level: &str| Term::Sort(Universe::Var(level.to_string()));
6585        ctx.add_structure_poly(
6586            "PSigma",
6587            vec!["u".to_string(), "v".to_string()],
6588            &[("A", sort("u")), ("B", arrow_(v("A"), sort("v")))],
6589            &[
6590                ("fst", v("A")),
6591                ("snd", Term::App(Box::new(v("B")), Box::new(v("fst")))),
6592            ],
6593        )
6594        .expect("`PSigma` is Lean's dependent pair at any sorts");
6595    }
6596
6597    /// `Subtype A p` = `{x : A // p x}` — the value and a PROOF about that value, checked.
6598    /// `Subtype_property s : p (Subtype_val s)`, not `p` at some other element.
6599    fn register_subtype(ctx: &mut Context) {
6600        let type0 = || Term::Sort(Universe::Type(0));
6601        let prop = || Term::Sort(Universe::Prop);
6602        let v = |s: &str| Term::Var(s.to_string());
6603        ctx.add_structure(
6604            "Subtype",
6605            &[("A", type0()), ("p", arrow_(v("A"), prop()))],
6606            &[
6607                ("val", v("A")),
6608                ("property", Term::App(Box::new(v("p")), Box::new(v("val")))),
6609            ],
6610        );
6611    }
6612
6613    /// `Fin n : Type 0 := Subtype Nat (λi. Nat_lt i n)` — Lean's own encoding, a `Nat` carrying
6614    /// a proof that it is below the bound.
6615    ///
6616    /// `Fin 0` is EMPTY without an appeal to a lemma: `Nat_lt i Zero` unfolds to
6617    /// `Eq Bool (natLe (Succ i) Zero) true`, and `natLe (Succ i) Zero` ι-reduces to `false` for
6618    /// every `i`, open or closed.
6619    fn register_fin(ctx: &mut Context) {
6620        let nat = || gl("Nat");
6621        let v = |s: &str| Term::Var(s.to_string());
6622        ctx.add_definition(
6623            "Fin".to_string(),
6624            pi_("_", nat(), Term::Sort(Universe::Type(0))),
6625            lam_(
6626                "n",
6627                nat(),
6628                apps_(
6629                    gl("Subtype"),
6630                    &[
6631                        nat(),
6632                        lam_("i", nat(), apps_(gl("Nat_lt"), &[v("i"), v("n")])),
6633                    ],
6634                ),
6635            ),
6636        );
6637    }
6638
6639    /// Lean's `List A` — `nil` before `cons`, with the recursor and the three operations `Array`
6640    /// is built from.
6641    ///
6642    /// Deliberately NOT `TList`/`EList`. `EList` is monomorphic in `Entity` (the concrete target
6643    /// the induction tactic's generic eliminator needs) and `TList`'s constructors are spelled
6644    /// `TNil`/`TCons`; both stay exactly as they were. `List` is the name a Lean source writes,
6645    /// and a REPL program that declares its own `List` still overwrites this one.
6646    ///
6647    /// `List_rec`'s motive is `List A → Type 0`, not `List A → Sort u` — the same `Type 0`
6648    /// restriction as everything else in this section. A `Prop`-motive induction over a list goes
6649    /// through `Match`/`Fix` directly.
6650    fn register_list(ctx: &mut Context) {
6651        let type0 = || Term::Sort(Universe::Type(0));
6652        let nat = || gl("Nat");
6653        let v = |s: &str| Term::Var(s.to_string());
6654        let ap = |f: Term, x: Term| Term::App(Box::new(f), Box::new(x));
6655        let list_a = || ap(gl("List"), v("A"));
6656        let succ = |x: Term| ap(gl("Succ"), x);
6657        let nil_a = || ap(gl("nil"), v("A"));
6658        let cons_a = |h: Term, t: Term| apps_(gl("cons"), &[v("A"), h, t]);
6659
6660        ctx.add_indexed_inductive("List", pi_("A", type0(), type0()), 1);
6661        Self::checked_ctor(ctx, "nil", "List", pi_("A", type0(), list_a()));
6662        Self::checked_ctor(
6663            ctx,
6664            "cons",
6665            "List",
6666            pi_("A", type0(), arrow_(v("A"), arrow_(list_a(), list_a()))),
6667        );
6668
6669        // List_rec : Π(A). Π(P : List A → Type 0). P nil →
6670        //            (Π(h:A). Π(t:List A). P t → P (cons h t)) → Π(l : List A). P l
6671        let motive_ty = || arrow_(list_a(), type0());
6672        let p_at = |x: Term| ap(v("P"), x);
6673        let cons_step = || {
6674            pi_(
6675                "h",
6676                v("A"),
6677                pi_(
6678                    "t",
6679                    list_a(),
6680                    arrow_(p_at(v("t")), p_at(cons_a(v("h"), v("t")))),
6681                ),
6682            )
6683        };
6684        let rec_ty = pi_(
6685            "A",
6686            type0(),
6687            pi_(
6688                "P",
6689                motive_ty(),
6690                arrow_(
6691                    p_at(nil_a()),
6692                    arrow_(cons_step(), pi_("l", list_a(), p_at(v("l")))),
6693                ),
6694            ),
6695        );
6696        let rec_match = Term::Match {
6697            discriminant: Box::new(v("l")),
6698            motive: Box::new(lam_("l✧", list_a(), p_at(v("l✧")))),
6699            cases: vec![
6700                v("pnil"),
6701                lam_(
6702                    "h",
6703                    v("A"),
6704                    lam_(
6705                        "t",
6706                        list_a(),
6707                        apps_(v("pcons"), &[v("h"), v("t"), ap(v("List_rec✧"), v("t"))]),
6708                    ),
6709                ),
6710            ],
6711        };
6712        ctx.add_definition(
6713            "List_rec".to_string(),
6714            rec_ty,
6715            lam_(
6716                "A",
6717                type0(),
6718                lam_(
6719                    "P",
6720                    motive_ty(),
6721                    lam_(
6722                        "pnil",
6723                        p_at(nil_a()),
6724                        lam_(
6725                            "pcons",
6726                            cons_step(),
6727                            fix_on_list("List_rec✧", list_a(), rec_match),
6728                        ),
6729                    ),
6730                ),
6731            ),
6732        );
6733
6734        // List_length : Π(A). List A → Nat
6735        let len_match = Term::Match {
6736            discriminant: Box::new(v("l")),
6737            motive: Box::new(lam_("_", list_a(), nat())),
6738            cases: vec![
6739                gl("Zero"),
6740                lam_(
6741                    "_h",
6742                    v("A"),
6743                    lam_("t", list_a(), succ(ap(v("List_length✧"), v("t")))),
6744                ),
6745            ],
6746        };
6747        ctx.add_definition(
6748            "List_length".to_string(),
6749            pi_("A", type0(), arrow_(list_a(), nat())),
6750            lam_(
6751                "A",
6752                type0(),
6753                fix_on_list("List_length✧", list_a(), len_match),
6754            ),
6755        );
6756
6757        // List_append : Π(A). List A → List A → List A
6758        let app_match = Term::Match {
6759            discriminant: Box::new(v("l")),
6760            motive: Box::new(lam_("_", list_a(), list_a())),
6761            cases: vec![
6762                v("r"),
6763                lam_(
6764                    "h",
6765                    v("A"),
6766                    lam_(
6767                        "t",
6768                        list_a(),
6769                        cons_a(v("h"), apps_(v("List_append✧"), &[v("t"), v("r")])),
6770                    ),
6771                ),
6772            ],
6773        };
6774        ctx.add_definition(
6775            "List_append".to_string(),
6776            pi_("A", type0(), arrow_(list_a(), arrow_(list_a(), list_a()))),
6777            lam_(
6778                "A",
6779                type0(),
6780                fix_on_list("List_append✧", list_a(), lam_("r", list_a(), app_match)),
6781            ),
6782        );
6783
6784        Self::register_list_get(ctx);
6785    }
6786
6787    /// `List_get : Π(A). Π(l : List A). Π(i : Nat). Nat_lt i (List_length A l) → A` — Lean's
6788    /// bound-proof indexing, TOTAL with no default and no out-of-range behaviour to choose.
6789    ///
6790    /// The two obligations the recursion has to discharge are both free, which is the whole point
6791    /// of stating the bound as `Eq Bool (natLt i len) true`:
6792    ///
6793    /// - In the `nil` branch the bound is `Nat_lt i Zero`, which ι-reduces to
6794    ///   `Eq Bool false true`. `Eq_false_true_absurd` turns it into `False` and `False_rec_type`
6795    ///   eliminates into `A` — the branch is unreachable, and it is unreachable by COMPUTATION.
6796    /// - In the `cons`/`Succ k` branch the recursive call needs `Nat_lt k len` where the
6797    ///   hypothesis is `Nat_lt (Succ k) (Succ len)`. Those unfold to
6798    ///   `natLe (Succ k) len` and `natLe (Succ (Succ k)) (Succ len)`, and the second ι-reduces to
6799    ///   the first — so the SAME proof is passed down with no transport and no lemma.
6800    fn register_list_get(ctx: &mut Context) {
6801        let type0 = || Term::Sort(Universe::Type(0));
6802        let nat = || gl("Nat");
6803        let v = |s: &str| Term::Var(s.to_string());
6804        let ap = |f: Term, x: Term| Term::App(Box::new(f), Box::new(x));
6805        let list_a = || ap(gl("List"), v("A"));
6806        let len_of = |l: Term| apps_(gl("List_length"), &[v("A"), l]);
6807        let bound = |i: Term, l: Term| apps_(gl("Nat_lt"), &[i, len_of(l)]);
6808        let cons_list = || apps_(gl("cons"), &[v("A"), v("hd"), v("tl")]);
6809
6810        Self::register_absurd_helpers(ctx);
6811
6812        let get_ty = pi_(
6813            "A",
6814            type0(),
6815            pi_(
6816                "l",
6817                list_a(),
6818                pi_("i", nat(), arrow_(bound(v("i"), v("l")), v("A"))),
6819            ),
6820        );
6821
6822        // nil branch: λi. λh. False_rec_type A (Eq_false_true_absurd h)
6823        let nil_case = lam_(
6824            "i",
6825            nat(),
6826            lam_(
6827                "h",
6828                bound(v("i"), ap(gl("nil"), v("A"))),
6829                apps_(
6830                    gl("False_rec_type"),
6831                    &[v("A"), ap(gl("Eq_false_true_absurd"), v("h"))],
6832                ),
6833            ),
6834        );
6835
6836        // cons branch: λ(hd:A). λ(tl:List A). λ(i:Nat). λ(h : Nat_lt i (length (hd::tl))).
6837        //   (match i return (λi✧. Nat_lt i✧ (length (hd::tl)) → A)
6838        //      { Zero => λ_. hd, Succ k => λh✧. rec tl k h✧ }) h
6839        //
6840        // The match ABSTRACTS over the bound proof and is then applied to it, because the
6841        // proof's type mentions `i` and has to be refined per branch.
6842        let index_match = Term::Match {
6843            discriminant: Box::new(v("i")),
6844            motive: Box::new(lam_(
6845                "i✧",
6846                nat(),
6847                arrow_(bound(v("i✧"), cons_list()), v("A")),
6848            )),
6849            cases: vec![
6850                lam_("_h", bound(gl("Zero"), cons_list()), v("hd")),
6851                lam_(
6852                    "k",
6853                    nat(),
6854                    lam_(
6855                        "h✧",
6856                        bound(ap(gl("Succ"), v("k")), cons_list()),
6857                        apps_(v("List_get✧"), &[v("tl"), v("k"), v("h✧")]),
6858                    ),
6859                ),
6860            ],
6861        };
6862        let cons_case = lam_(
6863            "hd",
6864            v("A"),
6865            lam_(
6866                "tl",
6867                list_a(),
6868                lam_(
6869                    "i",
6870                    nat(),
6871                    lam_(
6872                        "h",
6873                        bound(v("i"), cons_list()),
6874                        Term::App(Box::new(index_match), Box::new(v("h"))),
6875                    ),
6876                ),
6877            ),
6878        );
6879
6880        let list_match = Term::Match {
6881            discriminant: Box::new(v("l")),
6882            motive: Box::new(lam_(
6883                "l✧",
6884                list_a(),
6885                pi_("i", nat(), arrow_(bound(v("i"), v("l✧")), v("A"))),
6886            )),
6887            cases: vec![nil_case, cons_case],
6888        };
6889        ctx.add_definition(
6890            "List_get".to_string(),
6891            get_ty,
6892            lam_("A", type0(), fix_on_list("List_get✧", list_a(), list_match)),
6893        );
6894    }
6895
6896    /// The two lemmas a bound-checked eliminator needs, both DERIVED.
6897    ///
6898    /// `False_rec_type : Π(A:Type 0). False → A` is the large elimination a zero-constructor
6899    /// `Prop` is entitled to, and `Eq_false_true_absurd : Eq Bool false true → False` is Bool
6900    /// no-confusion: transport the motive `λb. match b { true => False, false => True }` along
6901    /// the equation and feed it `I`.
6902    fn register_absurd_helpers(ctx: &mut Context) {
6903        let type0 = || Term::Sort(Universe::Type(0));
6904        let v = |s: &str| Term::Var(s.to_string());
6905
6906        // False_rec_type : Π(A:Type 0). False → A
6907        ctx.add_definition(
6908            "False_rec_type".to_string(),
6909            pi_("A", type0(), arrow_(gl("False"), v("A"))),
6910            lam_(
6911                "A",
6912                type0(),
6913                lam_(
6914                    "h",
6915                    gl("False"),
6916                    Term::Match {
6917                        discriminant: Box::new(v("h")),
6918                        motive: Box::new(lam_("_", gl("False"), v("A"))),
6919                        cases: vec![],
6920                    },
6921                ),
6922            ),
6923        );
6924
6925        // notTrue : Bool → Prop := λb. match b { true => False, false => True }
6926        // (Bool's constructors are registered `true` then `false`.)
6927        ctx.add_definition(
6928            "Bool_isFalse".to_string(),
6929            pi_("_", gl("Bool"), Term::Sort(Universe::Prop)),
6930            lam_(
6931                "b",
6932                gl("Bool"),
6933                Term::Match {
6934                    discriminant: Box::new(v("b")),
6935                    motive: Box::new(lam_("_", gl("Bool"), Term::Sort(Universe::Prop))),
6936                    cases: vec![gl("False"), gl("True")],
6937                },
6938            ),
6939        );
6940
6941        // Eq_false_true_absurd : Eq Bool false true → False
6942        //   := λh. Eq_rec Bool false Bool_isFalse I true h
6943        let eq_ft = apps_(gl("Eq"), &[gl("Bool"), gl("false"), gl("true")]);
6944        ctx.add_definition(
6945            "Eq_false_true_absurd".to_string(),
6946            arrow_(eq_ft.clone(), gl("False")),
6947            lam_(
6948                "h",
6949                eq_ft,
6950                apps_(
6951                    gl("Eq_rec"),
6952                    &[
6953                        gl("Bool"),
6954                        gl("false"),
6955                        gl("Bool_isFalse"),
6956                        gl("I"),
6957                        gl("true"),
6958                        v("h"),
6959                    ],
6960                ),
6961            ),
6962        );
6963    }
6964
6965    /// `Array A` — a structure over `List A`, exactly as Lean's is over `List α`, with `size`,
6966    /// `push` and a `get` that TAKES THE BOUND PROOF.
6967    ///
6968    /// The dangerous substitution T10-011 names is `Array ↦ TList`: the `foldl`/`map`/`size`
6969    /// interface lines up, so most sources translate without a type error while `Array.get` goes
6970    /// from indexing-with-a-proof to a recursion that must decide what to do out of range.
6971    /// `Array_get` has no out-of-range behaviour to decide, because there is no way to call it
6972    /// out of range.
6973    fn register_array(ctx: &mut Context) {
6974        let type0 = || Term::Sort(Universe::Type(0));
6975        let nat = || gl("Nat");
6976        let v = |s: &str| Term::Var(s.to_string());
6977        let ap = |f: Term, x: Term| Term::App(Box::new(f), Box::new(x));
6978        let list_a = || ap(gl("List"), v("A"));
6979        let array_a = || ap(gl("Array"), v("A"));
6980        let data_of = |a: Term| apps_(gl("Array_data"), &[v("A"), a]);
6981
6982        ctx.add_structure("Array", &[("A", type0())], &[("data", list_a())]);
6983
6984        // Array_size : Π(A). Array A → Nat := λA a. List_length A a.data
6985        ctx.add_definition(
6986            "Array_size".to_string(),
6987            pi_("A", type0(), arrow_(array_a(), nat())),
6988            lam_(
6989                "A",
6990                type0(),
6991                lam_(
6992                    "a",
6993                    array_a(),
6994                    apps_(gl("List_length"), &[v("A"), data_of(v("a"))]),
6995                ),
6996            ),
6997        );
6998
6999        // Array_push : Π(A). Array A → A → Array A
7000        //   := λA a x. Array_mk A (List_append A a.data (cons A x (nil A)))
7001        ctx.add_definition(
7002            "Array_push".to_string(),
7003            pi_("A", type0(), arrow_(array_a(), arrow_(v("A"), array_a()))),
7004            lam_(
7005                "A",
7006                type0(),
7007                lam_(
7008                    "a",
7009                    array_a(),
7010                    lam_(
7011                        "x",
7012                        v("A"),
7013                        apps_(
7014                            gl("Array_mk"),
7015                            &[
7016                                v("A"),
7017                                apps_(
7018                                    gl("List_append"),
7019                                    &[
7020                                        v("A"),
7021                                        data_of(v("a")),
7022                                        apps_(gl("cons"), &[v("A"), v("x"), ap(gl("nil"), v("A"))]),
7023                                    ],
7024                                ),
7025                            ],
7026                        ),
7027                    ),
7028                ),
7029            ),
7030        );
7031
7032        // Array_get : Π(A). Π(a : Array A). Π(i : Nat). Nat_lt i (Array_size A a) → A
7033        //   := λA a i h. List_get A a.data i h
7034        //
7035        // `Array_size A a` δβ-unfolds to `List_length A a.data`, so the array's bound proof IS
7036        // the list's — no coercion, no restatement.
7037        let bound =
7038            |i: Term, a: Term| apps_(gl("Nat_lt"), &[i, apps_(gl("Array_size"), &[v("A"), a])]);
7039        ctx.add_definition(
7040            "Array_get".to_string(),
7041            pi_(
7042                "A",
7043                type0(),
7044                pi_(
7045                    "a",
7046                    array_a(),
7047                    pi_("i", nat(), arrow_(bound(v("i"), v("a")), v("A"))),
7048                ),
7049            ),
7050            lam_(
7051                "A",
7052                type0(),
7053                lam_(
7054                    "a",
7055                    array_a(),
7056                    lam_(
7057                        "i",
7058                        nat(),
7059                        lam_(
7060                            "h",
7061                            bound(v("i"), v("a")),
7062                            apps_(gl("List_get"), &[v("A"), data_of(v("a")), v("i"), v("h")]),
7063                        ),
7064                    ),
7065                ),
7066            ),
7067        );
7068    }
7069
7070    /// `UInt8`/`UInt16`/`UInt32`/`UInt64`/`USize` as `Fin 2^N` — Lean's own definition.
7071    ///
7072    /// These are the bounded CARRIERS. Their wrapping arithmetic (`(255 : UInt8) + 1 = 0`) is a
7073    /// separate capability and is NOT provided: LOGOS's arithmetic is exact and unbounded by
7074    /// construction, so a modular operation has to be defined rather than inherited, and defining
7075    /// it needs `Nat` `+`/`%` plus `Nat.mod_lt`. What IS provided is the invariant — a value of
7076    /// one of these types carries a proof that it is below the width, so the carriers cannot be
7077    /// confused with `Nat` and cannot hold an out-of-range value.
7078    fn register_machine_words(ctx: &mut Context) {
7079        let ap = |f: Term, x: Term| Term::App(Box::new(f), Box::new(x));
7080        let lit = |s: &str| {
7081            Term::Lit(Literal::Nat(
7082                logicaffeine_base::BigInt::parse_decimal(s).expect("a decimal width"),
7083            ))
7084        };
7085        for (name, size) in [
7086            ("UInt8", "256"),
7087            ("UInt16", "65536"),
7088            ("UInt32", "4294967296"),
7089            ("UInt64", "18446744073709551616"),
7090            ("USize", "18446744073709551616"),
7091        ] {
7092            ctx.add_definition(
7093                name.to_string(),
7094                Term::Sort(Universe::Type(0)),
7095                ap(gl("Fin"), lit(size)),
7096            );
7097        }
7098
7099        // UInt32_toNat : UInt32 → Nat — `Subtype.val` at the width, the projection `Char`'s
7100        // validity predicate reads its argument through.
7101        let v = |s: &str| Term::Var(s.to_string());
7102        let nat = || gl("Nat");
7103        ctx.add_definition(
7104            "UInt32_toNat".to_string(),
7105            pi_("_", gl("UInt32"), nat()),
7106            lam_(
7107                "c",
7108                gl("UInt32"),
7109                apps_(
7110                    gl("Subtype_val"),
7111                    &[
7112                        nat(),
7113                        lam_(
7114                            "i",
7115                            nat(),
7116                            apps_(gl("Nat_lt"), &[v("i"), lit("4294967296")]),
7117                        ),
7118                        v("c"),
7119                    ],
7120                ),
7121            ),
7122        );
7123    }
7124
7125    /// `Char = { val : UInt32 // val.isValidChar }` and `String` as a structure over
7126    /// `List Char` — Lean's definitions, both of them.
7127    ///
7128    /// `Char.isValidChar n` is `n < 0xD800 ∨ (0xDFFF < n ∧ n < 0x110000)`: the surrogate range is
7129    /// excluded, so a `Char` really is a Unicode scalar value and not a `UInt32` wearing a label.
7130    /// The two re-encodings the corpus names are both dead ends — a `Nat` `Char` makes
7131    /// `Nat → Char` and `Nat → Nat` the same type, and a one-character `Text` has nothing to
7132    /// project, `Text` being opaque.
7133    ///
7134    /// `Text` STAYS OPAQUE. It is the carrier `Literal::Text` lands in, and giving it
7135    /// constructors would give the same string two incompatible normal forms — the literal and
7136    /// its cons-list spelling. `String` and `Text` are therefore different types here, and
7137    /// bridging them needs a primitive reduction rule (`"ab" ++ "cd" ⤳ "abcd"`) that lives in
7138    /// the reducer, not in the prelude.
7139    fn register_char_and_string(ctx: &mut Context) {
7140        let prop = || Term::Sort(Universe::Prop);
7141        let v = |s: &str| Term::Var(s.to_string());
7142        let ap = |f: Term, x: Term| Term::App(Box::new(f), Box::new(x));
7143        let lit = |s: &str| {
7144            Term::Lit(Literal::Nat(
7145                logicaffeine_base::BigInt::parse_decimal(s).expect("a decimal code point"),
7146            ))
7147        };
7148        let n_of = || ap(gl("UInt32_toNat"), v("c"));
7149        let lt = |a: Term, b: Term| apps_(gl("Nat_lt"), &[a, b]);
7150
7151        // Char_isValid : UInt32 → Prop
7152        ctx.add_definition(
7153            "Char_isValid".to_string(),
7154            pi_("_", gl("UInt32"), prop()),
7155            lam_(
7156                "c",
7157                gl("UInt32"),
7158                apps_(
7159                    gl("Or"),
7160                    &[
7161                        lt(n_of(), lit("55296")),
7162                        apps_(
7163                            gl("And"),
7164                            &[lt(lit("57343"), n_of()), lt(n_of(), lit("1114112"))],
7165                        ),
7166                    ],
7167                ),
7168            ),
7169        );
7170
7171        // Char : Type 0 := Subtype UInt32 Char_isValid
7172        ctx.add_definition(
7173            "Char".to_string(),
7174            Term::Sort(Universe::Type(0)),
7175            apps_(gl("Subtype"), &[gl("UInt32"), gl("Char_isValid")]),
7176        );
7177
7178        // structure String where data : List Char
7179        ctx.add_structure("String", &[], &[("data", ap(gl("List"), gl("Char")))]);
7180    }
7181
7182    /// `Subsingleton` as a `Prop`-valued CLASS, and `Squash` as truncation that stays in `Type`.
7183    ///
7184    /// `Subsingleton` goes through [`Context::add_structure_at`] at `Prop`, not `add_structure`:
7185    /// the inferred sort floors at `Type 0`, and a `Type 0` `Subsingleton α` inside a
7186    /// proposition's statement promotes that statement out of `Prop` through `imax`. The declared
7187    /// sort is CHECKED by `check_constructor_universes`, so this is a claim the kernel verifies
7188    /// rather than a sort taken on faith.
7189    ///
7190    /// The kernel's own subsingleton notion — read off an inductive's constructor list to decide
7191    /// large elimination — is a property of a DECLARATION and is not addressable from a term.
7192    /// The class is, which is why Mathlib derives instances of it and the kernel rule cannot
7193    /// stand in: `Unit` is a `Type`, so proof irrelevance does not apply and `Subsingleton Unit`
7194    /// must be PROVED.
7195    ///
7196    /// `Squash A := Quot A (λ_ _. True)` — every two elements are related, so the quotient has at
7197    /// most one class, and it is a `Type`. The `Prop`-valued truncation is `Nonempty`, and
7198    /// eliminating THAT into `Type` is choice.
7199    fn register_truncation(ctx: &mut Context) {
7200        let type0 = || Term::Sort(Universe::Type(0));
7201        let v = |s: &str| Term::Var(s.to_string());
7202
7203        let elim_field = pi_(
7204            "x",
7205            v("a"),
7206            pi_("y", v("a"), apps_(gl("Eq"), &[v("a"), v("x"), v("y")])),
7207        );
7208        ctx.add_structure_at(
7209            "Subsingleton",
7210            Universe::Prop,
7211            &[("a", type0())],
7212            &[("elim", elim_field)],
7213        )
7214        .expect("`Subsingleton` is a Prop-valued class: its only field is an equation");
7215
7216        ctx.add_definition(
7217            "Squash".to_string(),
7218            pi_("_", type0(), type0()),
7219            lam_(
7220                "A",
7221                type0(),
7222                apps_(
7223                    gl("Quot"),
7224                    &[v("A"), lam_("_", v("A"), lam_("_", v("A"), gl("True")))],
7225                ),
7226            ),
7227        );
7228    }
7229
7230    /// `Inhabited` (DATA — a chosen element) and `Nonempty` (a PROPOSITION — that one exists).
7231    ///
7232    /// The difference is the whole point, and it is a sort difference. `Inhabited` goes through
7233    /// `add_structure`, which is what registers the `StructInfo` gating eta, and lands in
7234    /// `Type 0` because it stores an `α`. `Nonempty` must land in `Prop`, so it cannot go through
7235    /// `add_structure` at all: it is an indexed inductive at `Prop` with a checked constructor.
7236    ///
7237    /// A `Type 0` `Nonempty` would be eligible for large elimination — and a `Nonempty α` that
7238    /// yields its witness IS `Classical.choice`, derived rather than declared, which the axiom
7239    /// census would never see. The kernel refuses it because `Nonempty`'s single constructor
7240    /// takes DATA, so it is not a subsingleton.
7241    fn register_inhabited(ctx: &mut Context) {
7242        let type0 = || Term::Sort(Universe::Type(0));
7243        let prop = || Term::Sort(Universe::Prop);
7244        let v = |s: &str| Term::Var(s.to_string());
7245        let ap = |f: Term, x: Term| Term::App(Box::new(f), Box::new(x));
7246
7247        ctx.add_structure("Inhabited", &[("a", type0())], &[("default", v("a"))]);
7248
7249        // `instance : Inhabited Nat`, in the FALLBACK tier.
7250        //
7251        // The prelude refused this for a wave, and the refusal was right at the time:
7252        // `Context::instances()` is a push-only Vec resolved FIRST-MATCH, so a prelude entry
7253        // would have been entry zero and would have permanently outranked every user instance
7254        // for the same goal — and it would have moved `instances().len()`, which is a count
7255        // taken against a baseline of nothing.
7256        //
7257        // [`Context::add_fallback_instance`] is the tier that unblocks it, and it is strictly
7258        // better than Lean's answer to the same problem: Lean expresses "library instance, low
7259        // priority" with a NUMBER a user instance can accidentally undercut, while a separate
7260        // tier consulted only after the main scan has failed cannot be undercut at all. The
7261        // entry stays out of `instances()`, which remains the faithful record of what was
7262        // explicitly declared.
7263        ctx.add_fallback_instance(
7264            ap(gl("Inhabited"), gl("Nat")),
7265            apps_(gl("Inhabited_mk"), &[gl("Nat"), gl("Zero")]),
7266        );
7267        ctx.add_fallback_instance(
7268            ap(gl("Inhabited"), gl("Bool")),
7269            apps_(gl("Inhabited_mk"), &[gl("Bool"), gl("true")]),
7270        );
7271
7272        ctx.add_indexed_inductive("Nonempty", pi_("a", type0(), prop()), 1);
7273        Self::checked_ctor(
7274            ctx,
7275            "Nonempty_intro",
7276            "Nonempty",
7277            pi_("a", type0(), arrow_(v("a"), ap(gl("Nonempty"), v("a")))),
7278        );
7279    }
7280
7281    /// Register a prelude constructor through the CHECKED path — positivity and the
7282    /// constructor-universe rule — so a prelude inductive is held to the same standard a user
7283    /// declaration is. A failure here is a bug in this file, not in the caller's input.
7284    fn checked_ctor(ctx: &mut Context, name: &str, inductive: &str, ty: Term) {
7285        ctx.add_constructor_checked(name, inductive, ty)
7286            .unwrap_or_else(|e| {
7287                panic!(
7288                    "prelude constructor `{name} : {inductive}` must pass the checked path: {e:?}"
7289                )
7290            });
7291    }
7292}
7293
7294// =========================================================================
7295// THE AXIOM AUDIT TRAIL — our `#print axioms`, and the taint that cannot be lost.
7296// =========================================================================
7297
7298use std::collections::BTreeSet;
7299
7300/// Names that mark a proof as **ADMITTED** rather than proved.
7301///
7302/// `sorryAx` is Lean's; the rest are the other placeholders a translated or hand-edited
7303/// environment can acquire. LOGOS deliberately registers NONE of them, so seeing one means a
7304/// caller reached past `StandardLibrary::register` — which is the single most dangerous thing that
7305/// can happen to a proof library, because the result type-checks, BOTH kernels agree, and
7306/// `verified == true` really does hold.
7307pub const ADMITTED_AXIOMS: &[&str] =
7308    &["sorryAx", "sorry", "admit", "lcProof", "Lean.trustCompiler"];
7309
7310/// Whether a name marks an admitted (not proved) step.
7311pub fn is_admitted_axiom(name: &str) -> bool {
7312    ADMITTED_AXIOMS.contains(&name)
7313}
7314
7315/// Axioms and constants LOGOS deliberately does NOT have, each with the sentence a diagnostic
7316/// should say instead of "unbound variable".
7317///
7318/// This exists because the information that distinguishes `sorryAx` from a typo is the NAME and
7319/// nothing else: inside `infer_type` an unregistered `Term::Global` carries no provenance, so a
7320/// single verdict for the whole arm cannot both say "your proof rests on an admission" for
7321/// `sorryAx` and "this local is out of scope" for `id`. A name-keyed registry separates them, and
7322/// putting it HERE — beside the trusted base it is the complement of — is what keeps the two in
7323/// step: an axiom that later gets registered must be deleted from this table, and
7324/// `the_foreign_axiom_registry_is_disjoint_from_the_trusted_base` in the lane's own test file
7325/// fails if it is not.
7326pub const FOREIGN_AXIOMS: &[(&str, &str)] = &[
7327    (
7328        "sorryAx",
7329        "an ADMITTED proof: `sorryAx` proves anything, so LOGOS never registers it. A proof term \
7330         that cites it is INCOMPLETE, not misspelled — adding the name to the prelude would make \
7331         every certificate ever minted claim an axiom set it was not checked against",
7332    ),
7333    (
7334        "sorry",
7335        "an ADMITTED proof: LOGOS has no `sorry`, deliberately. The proof is incomplete",
7336    ),
7337    (
7338        "admit",
7339        "an ADMITTED proof: LOGOS has no `admit`, deliberately. The proof is incomplete",
7340    ),
7341    (
7342        "lcProof",
7343        "Lean's compiler-internal proof placeholder. It is not part of any trusted base and has \
7344         no LOGOS counterpart",
7345    ),
7346    (
7347        "Lean.trustCompiler",
7348        "Lean's assumption that its own compiler is correct. LOGOS's analogue is the narrower \
7349         `reduceBool`/`ofReduceBool` pair, which is what `native_decide` rests on",
7350    ),
7351    (
7352        "Classical.choice",
7353        "Lean's dotted spelling. LOGOS registers this axiom as `Classical_choice`",
7354    ),
7355    (
7356        "Classical.em",
7357        "Lean's dotted spelling. LOGOS derives this from `dne` and registers it as `Classical_em` \
7358         — a definition, not an axiom",
7359    ),
7360    (
7361        "Quot.sound",
7362        "Lean's dotted spelling. LOGOS registers this axiom as `Quot_sound`",
7363    ),
7364    (
7365        "Lean.ofReduceBool",
7366        "Lean's dotted spelling. LOGOS registers this axiom as `ofReduceBool`",
7367    ),
7368    (
7369        "Lean.reduceBool",
7370        "Lean's dotted spelling. LOGOS registers this axiom as `reduceBool`",
7371    ),
7372];
7373
7374/// The diagnostic sentence for a constant the trusted base deliberately lacks, or `None` when the
7375/// name is simply not registered (a typo, a missing import, an out-of-scope local).
7376///
7377/// A kernel that answers `UnboundVariable("sorryAx")` invites exactly one repair — add the name to
7378/// the prelude — and that repair is catastrophic. A kernel that answers `UnboundVariable("id")`
7379/// invites the right one. Same arm, same shape, different name: this function is the only thing
7380/// that can tell them apart.
7381pub fn foreign_axiom_note(name: &str) -> Option<&'static str> {
7382    FOREIGN_AXIOMS
7383        .iter()
7384        .find(|(n, _)| *n == name)
7385        .map(|(_, why)| *why)
7386}
7387
7388/// What a proof rests on: the axioms it cites transitively, and the names that resolve to nothing.
7389#[derive(Debug, Clone, Default, PartialEq, Eq)]
7390pub struct AxiomUsage {
7391    /// Axioms cited, TRANSITIVELY through definitions. Sorted, so a report is stable and diffable.
7392    pub axioms: BTreeSet<String>,
7393    /// Names that resolve to NOTHING in the context checked against. Non-empty means the proof was
7394    /// minted against a larger base than the one re-checking it — trusted-base drift, named.
7395    pub unresolved: BTreeSet<String>,
7396}
7397
7398impl AxiomUsage {
7399    /// Fold another report into this one — the union, on both halves.
7400    ///
7401    /// A closure is almost never over one term: a declaration is its TYPE and its BODY, and a
7402    /// certificate is its proof term and the proposition it CLAIMS. Every caller that walks two
7403    /// terms goes through here, so no caller can merge the axioms and forget the unresolved
7404    /// names — the half that reports trusted-base DRIFT, and the half a summary is most tempted
7405    /// to drop.
7406    pub fn absorb(&mut self, other: AxiomUsage) {
7407        self.axioms.extend(other.axioms);
7408        self.unresolved.extend(other.unresolved);
7409    }
7410
7411    /// Every name this proof rests on, declared or not — the ONE view the three query methods
7412    /// below share.
7413    ///
7414    /// `unresolved` is not a lesser half. A name the checking context does not have is
7415    /// trusted-base DRIFT: the proof was minted against a larger base than the one re-checking
7416    /// it, and `sorryAx` re-checked against a clean prelude lands there rather than in `axioms`,
7417    /// because the clean prelude never declared it. A query that read `axioms` alone therefore
7418    /// answered "rests on nothing outside this list" for exactly the proof the audit trail exists
7419    /// to catch.
7420    fn cited(&self) -> impl Iterator<Item = &String> {
7421        self.axioms.iter().chain(self.unresolved.iter())
7422    }
7423
7424    /// Does this proof rest on anything outside `permitted`?
7425    ///
7426    /// A trust POLICY is written from this, so it counts an unresolved name too — see
7427    /// `AxiomUsage::cited`. Permitting a name by spelling silences it whichever half it is in,
7428    /// so one list governs both.
7429    pub fn beyond(&self, permitted: &[&str]) -> BTreeSet<String> {
7430        self.cited()
7431            .filter(|a| !permitted.contains(&a.as_str()))
7432            .cloned()
7433            .collect()
7434    }
7435
7436    /// Every ADMITTED name this proof rests on, transitively — the taint.
7437    ///
7438    /// Better than Lean here, and deliberately: Lean warns on the declaration that CONTAINS the
7439    /// `sorry` and says nothing about its dependants, so a theorem three lemmas downstream of an
7440    /// admission looks finished and `#print axioms` is a command you have to remember to run. This
7441    /// reads the closure, so the taint is a property of the proof rather than of a warning you
7442    /// might have missed, and it cannot be lost by renaming, re-exporting or citing at a distance.
7443    pub fn admitted(&self) -> BTreeSet<String> {
7444        self.cited()
7445            .filter(|a| is_admitted_axiom(a))
7446            .cloned()
7447            .collect()
7448    }
7449
7450    /// Is this proof tainted by an admission? Sugar for `!admitted().is_empty()`.
7451    pub fn is_admitted(&self) -> bool {
7452        !self.admitted().is_empty()
7453    }
7454
7455    /// A proof that cites any name a caller considers admitted is not a proof, and neither is
7456    /// anything that transitively cites it.
7457    pub fn is_tainted_by(&self, admitted: &[&str]) -> bool {
7458        self.cited().any(|a| admitted.contains(&a.as_str()))
7459    }
7460
7461    /// The `#print axioms` report, rendered. One line, stable, diffable — and it names the
7462    /// admission FIRST when there is one, because that is the part a reader must not scroll past.
7463    pub fn render(&self, subject: &str) -> String {
7464        let mut out = String::new();
7465        let tainted = self.admitted();
7466        if !tainted.is_empty() {
7467            out.push_str(&format!(
7468                "'{subject}' is ADMITTED, not proved: it rests on {}\n",
7469                tainted.iter().cloned().collect::<Vec<_>>().join(", ")
7470            ));
7471        }
7472        if self.axioms.is_empty() && self.unresolved.is_empty() {
7473            out.push_str(&format!("'{subject}' depends on no axioms"));
7474            return out;
7475        }
7476        if !self.axioms.is_empty() {
7477            out.push_str(&format!(
7478                "'{subject}' depends on axioms: [{}]",
7479                self.axioms.iter().cloned().collect::<Vec<_>>().join(", ")
7480            ));
7481        }
7482        if !self.unresolved.is_empty() {
7483            if !self.axioms.is_empty() {
7484                out.push('\n');
7485            }
7486            out.push_str(&format!(
7487                "'{subject}' cites names this trusted base does not have: [{}]",
7488                self.unresolved
7489                    .iter()
7490                    .cloned()
7491                    .collect::<Vec<_>>()
7492                    .join(", ")
7493            ));
7494        }
7495        out
7496    }
7497}
7498
7499/// Internally derived evidence for a checked opaque declaration. Its direct
7500/// edges point into Context's shared certification graph, never a copied closure.
7501#[derive(Debug, Clone)]
7502pub(crate) struct CheckedOpaqueDependencies {
7503    pub(crate) usage: AxiomUsage,
7504    pub(crate) dependencies: BTreeSet<String>,
7505}
7506
7507pub(crate) struct CheckedOpaqueTrace {
7508    pub(crate) checked: CheckedOpaqueDependencies,
7509    pub(crate) graph: std::collections::BTreeMap<String, BTreeSet<String>>,
7510}
7511
7512/// Every AXIOM a term actually depends on — Lean's `#print axioms`, as a function.
7513///
7514/// The closure is TRANSITIVE through definitions, following both a definition's BODY and its TYPE
7515/// (a type can cite an axiom the body never mentions). A one-hop scan of a proof term sees only the
7516/// lemma it names, which is precisely how a `sorry` three lemmas upstream stays invisible.
7517///
7518/// A name that resolves to nothing is reported too, in `unresolved`: a proof naming a constant the
7519/// trusted base does not have IS trusted-base drift, and it must be visible as that rather than as
7520/// a name-resolution symptom.
7521///
7522/// Lives in `prelude` rather than in `certificate` on purpose. `certificate` is behind the `serde`
7523/// feature; the audit trail is not optional, and the REPL's `Print Axioms`, the kernel's own
7524/// diagnostics and `logicaffeine_proof`'s verdicts all need it in the default build.
7525pub fn axiom_dependencies(ctx: &Context, term: &Term) -> AxiomUsage {
7526    dependency_trace(ctx, &[term], false, None).checked.usage
7527}
7528
7529/// The axiom closure of `term`, as [`axiom_dependencies`], where `known` answers the axioms of a constant whose
7530/// closure was already taken: the walk takes that answer at the constant instead of walking below it. Reachability is
7531/// transitive, so the answer is what the walk would have found there, and a constant whose closure was taken had
7532/// every name below it resolved. An importer that audits each declaration in order passes the sets it recorded, so
7533/// a declaration's walk covers its own terms and what is not yet audited rather than the whole closure again.
7534pub fn axiom_dependencies_given(
7535    ctx: &Context,
7536    term: &Term,
7537    known: &dyn Fn(&str) -> Option<Vec<String>>,
7538) -> AxiomUsage {
7539    dependency_trace(ctx, &[term], false, Some(known)).checked.usage
7540}
7541
7542pub(crate) fn checked_opaque_dependencies(
7543    ctx: &Context,
7544    ty: &Term,
7545    body: &Term,
7546) -> CheckedOpaqueTrace {
7547    dependency_trace(ctx, &[ty, body], true, None)
7548}
7549
7550/// Usage preserves the existing assumption-leaf policy. Certification edges
7551/// additionally cover assumption TYPES, constructor owners/inventories and
7552/// previously checked opaque references. Context shares those direct edges.
7553/// `known` (usage only, never a footprint) stops the walk at a constant whose axioms it answers.
7554fn dependency_trace(
7555    ctx: &Context,
7556    roots: &[&Term],
7557    footprint: bool,
7558    known: Option<&dyn Fn(&str) -> Option<Vec<String>>>,
7559) -> CheckedOpaqueTrace {
7560    debug_assert!(!(footprint && known.is_some()), "a footprint walks every edge");
7561    let mut result = CheckedOpaqueTrace {
7562        checked: CheckedOpaqueDependencies {
7563            usage: AxiomUsage::default(),
7564            dependencies: BTreeSet::new(),
7565        },
7566        graph: std::collections::BTreeMap::new(),
7567    };
7568    let mut seen = BTreeSet::<(String, bool)>::new();
7569    let mut queue = Vec::<(String, bool)>::new();
7570    fn enqueue(
7571        term: &Term,
7572        used: bool,
7573        queue: &mut Vec<(String, bool)>,
7574        mut edges: Option<&mut BTreeSet<String>>,
7575    ) {
7576        let mut names = Vec::new();
7577        collect_globals(term, &mut names);
7578        for name in names {
7579            if let Some(edges) = edges.as_deref_mut() {
7580                edges.insert(name.clone());
7581            }
7582            queue.push((name, used));
7583        }
7584    }
7585    for root in roots {
7586        enqueue(
7587            root,
7588            true,
7589            &mut queue,
7590            footprint.then_some(&mut result.checked.dependencies),
7591        );
7592    }
7593    while let Some((name, used)) = queue.pop() {
7594        if !seen.insert((name.clone(), used)) {
7595            continue;
7596        }
7597        if let Some(axioms) = known.and_then(|known| known(&name)) {
7598            if used {
7599                result.checked.usage.axioms.extend(axioms);
7600            }
7601            continue;
7602        }
7603        if let Some(checked) = ctx.checked_opaque_dependencies(&name) {
7604            if used {
7605                result.checked.usage.absorb(checked.usage.clone());
7606            }
7607            // This node's existing graph already records its complete proof
7608            // footprint. Keeping the named edge shares it without flattening.
7609            continue;
7610        }
7611        let mut direct = BTreeSet::new();
7612        if let Some((_, ty, body)) = ctx.get_universe_poly(&name) {
7613            enqueue(ty, used, &mut queue, footprint.then_some(&mut direct));
7614            enqueue(body, used, &mut queue, footprint.then_some(&mut direct));
7615        } else if let Some(body) = ctx.get_definition_body(&name) {
7616            enqueue(body, used, &mut queue, footprint.then_some(&mut direct));
7617            if let Some(ty) = ctx.get_definition_type(&name) {
7618                enqueue(ty, used, &mut queue, footprint.then_some(&mut direct));
7619            }
7620        } else if ctx.is_inductive(&name) || ctx.is_constructor(&name) {
7621            if let Some(ty) = ctx.get_global(&name) {
7622                enqueue(ty, used, &mut queue, footprint.then_some(&mut direct));
7623            }
7624            if footprint {
7625                if let Some(owner) = ctx.constructor_inductive(&name) {
7626                    direct.insert(owner.to_string());
7627                    queue.push((owner.to_string(), false));
7628                }
7629            }
7630            for (constructor, ty) in ctx.get_constructors(&name) {
7631                if footprint {
7632                    direct.insert(constructor.to_string());
7633                    queue.push((constructor.to_string(), false));
7634                }
7635                enqueue(ty, used, &mut queue, footprint.then_some(&mut direct));
7636            }
7637        } else if crate::quotient::prelude_kind(ctx, &name).is_some() {
7638            if let Some(ty) = ctx.get_global(&name) {
7639                enqueue(ty, used, &mut queue, footprint.then_some(&mut direct));
7640            }
7641            if footprint {
7642                if let Some(certificate) = &ctx.prelude_quotient {
7643                    for dependency in &certificate.dependencies {
7644                        direct.insert(dependency.clone());
7645                        queue.push((dependency.clone(), false));
7646                    }
7647                }
7648            }
7649        } else if crate::observational::kind(ctx, &name).is_some() {
7650            if let Some((_, ty)) = ctx.poly_declaration(&name) {
7651                enqueue(ty, used, &mut queue, footprint.then_some(&mut direct));
7652            }
7653            if footprint {
7654                if let Some(certificate) = &ctx.observational {
7655                    for dependency in &certificate.dependencies {
7656                        direct.insert(dependency.clone());
7657                        queue.push((dependency.clone(), false));
7658                    }
7659                }
7660            }
7661        } else if let Some((_, ty)) = ctx
7662            .poly_declaration(&name)
7663            .filter(|_| ctx.quotient_primitives.contains_key(&name))
7664        {
7665            enqueue(ty, used, &mut queue, footprint.then_some(&mut direct));
7666            if footprint {
7667                if let Some(certificate) = ctx.quotient_primitives.get(&name) {
7668                    for dependency in &certificate.dependencies {
7669                        direct.insert(dependency.clone());
7670                        queue.push((dependency.clone(), false));
7671                    }
7672                }
7673            }
7674        } else if let Some(ty) = ctx
7675            .get_global(&name)
7676            .or_else(|| ctx.poly_declaration(&name).map(|(_, ty)| ty))
7677        {
7678            if used {
7679                result.checked.usage.axioms.insert(name.clone());
7680            }
7681            // An assumption is a LEAF of the usage report, as in Lean's `CollectAxioms`, whose
7682            // `axiomInfo` arm records the axiom and never visits its type: `#print axioms element`
7683            // for `axiom element : Carrier` is `[element]`. A declaration whose own statement
7684            // mentions `Carrier` is charged for it through that statement. The type still enters
7685            // the certification footprint, so changing it invalidates what was checked against it.
7686            enqueue(ty, false, &mut queue, footprint.then_some(&mut direct));
7687        } else {
7688            // A missing certification dependency must prevent publication too.
7689            result.checked.usage.unresolved.insert(name.clone());
7690        }
7691        if footprint {
7692            result.graph.entry(name).or_default().extend(direct);
7693        }
7694    }
7695    result
7696}
7697
7698/// The axiom closure of a NAMED constant in a context — what `Print Axioms <name>.` reports.
7699///
7700/// A definition reports what its statement and body rest on; an axiom reports itself alone,
7701/// as Lean's `#print axioms` does. `None` when the name is not registered.
7702pub fn axiom_dependencies_of(ctx: &Context, name: &str) -> Option<AxiomUsage> {
7703    if let Some(checked) = ctx.checked_opaque_dependencies(name) {
7704        return Some(checked.usage.clone());
7705    }
7706    if let Some((_, ty, body)) = ctx.get_universe_poly(name) {
7707        let mut usage = axiom_dependencies(ctx, body);
7708        usage.absorb(axiom_dependencies(ctx, ty));
7709        return Some(usage);
7710    }
7711    if let Some(body) = ctx.get_definition_body(name) {
7712        let mut usage = axiom_dependencies(ctx, &body.clone());
7713        if let Some(ty) = ctx.get_definition_type(name) {
7714            usage.absorb(axiom_dependencies(ctx, &ty.clone()));
7715        }
7716        return Some(usage);
7717    }
7718    ctx.get_global(name)
7719        .or_else(|| ctx.poly_declaration(name).map(|(_, ty)| ty))?;
7720    // Inductive types, constructors, certified quotient primitives, the certified observational
7721    // constants and assumptions all read the one closure. An axiom rests on ITSELF — a report that omitted the name would say a
7722    // `sorry`-shaped declaration depends on nothing — and, as in Lean's `#print axioms`, on
7723    // nothing its type mentions: the closure reads an assumption as a leaf.
7724    Some(axiom_dependencies(ctx, &Term::Global(name.to_string())))
7725}
7726
7727/// Collect every `Global`/`Const` name appearing anywhere in a term.
7728fn collect_globals(t: &Term, out: &mut Vec<String>) {
7729    match t {
7730        Term::Global(n) => out.push(n.clone()),
7731        Term::Const { name, .. } => out.push(name.clone()),
7732        Term::Pi {
7733            param_type,
7734            body_type,
7735            ..
7736        } => {
7737            collect_globals(param_type, out);
7738            collect_globals(body_type, out);
7739        }
7740        Term::Lambda {
7741            param_type, body, ..
7742        } => {
7743            collect_globals(param_type, out);
7744            collect_globals(body, out);
7745        }
7746        Term::App(f, a) => {
7747            collect_globals(f, out);
7748            collect_globals(a, out);
7749        }
7750        Term::Match {
7751            discriminant,
7752            motive,
7753            cases,
7754        } => {
7755            collect_globals(discriminant, out);
7756            collect_globals(motive, out);
7757            for c in cases {
7758                collect_globals(c, out);
7759            }
7760        }
7761        Term::Fix { body, .. } => collect_globals(body, out),
7762        Term::MutualFix { defs, .. } => {
7763            for (_, d) in defs {
7764                collect_globals(d, out);
7765            }
7766        }
7767        Term::Let {
7768            ty, value, body, ..
7769        } => {
7770            collect_globals(ty, out);
7771            collect_globals(value, out);
7772            collect_globals(body, out);
7773        }
7774        Term::Annotated { term, .. } => collect_globals(term, out),
7775        Term::Sort(_) | Term::Var(_) | Term::Lit(_) | Term::Hole => {}
7776    }
7777}
7778
7779// -------------------------------------------------------------------------
7780// Term-building shorthands for the structural-type section.
7781// -------------------------------------------------------------------------
7782
7783fn gl(name: &str) -> Term {
7784    Term::Global(name.to_string())
7785}
7786
7787fn v_(name: &str) -> Term {
7788    Term::Var(name.to_string())
7789}
7790
7791fn apps_(head: Term, args: &[Term]) -> Term {
7792    args.iter()
7793        .fold(head, |acc, a| Term::App(Box::new(acc), Box::new(a.clone())))
7794}
7795
7796fn pi_(param: &str, param_type: Term, body_type: Term) -> Term {
7797    Term::Pi {
7798        param: param.to_string(),
7799        param_type: Box::new(param_type),
7800        body_type: Box::new(body_type),
7801    }
7802}
7803
7804fn arrow_(from: Term, to: Term) -> Term {
7805    pi_("_", from, to)
7806}
7807
7808fn lam_(param: &str, param_type: Term, body: Term) -> Term {
7809    Term::Lambda {
7810        param: param.to_string(),
7811        param_type: Box::new(param_type),
7812        body: Box::new(body),
7813    }
7814}
7815
7816/// `fix name. λ(l : list_ty). body` — a recursion whose FIRST argument is the one it recurses on.
7817///
7818/// The kernel's `Fix` rule unfolds `(fix f. b) arg` only when `arg` is constructor-form, and it
7819/// looks at the argument the fixpoint is IMMEDIATELY applied to. A `fix` that binds its type
7820/// parameter first is therefore stuck forever: `List_length Nat [1,2,3]` hands the fixpoint
7821/// `Nat`, which is not a constructor and does not reduce. Parameters are uniform across the
7822/// recursion and belong OUTSIDE it — which is also what Lean does, and what makes the recursive
7823/// call `rec t` rather than `rec A t`.
7824fn fix_on_list(name: &str, list_ty: Term, body: Term) -> Term {
7825    Term::Fix {
7826        name: name.to_string(),
7827        body: Box::new(lam_("l", list_ty, body)),
7828    }
7829}