Skip to main content

logicaffeine_kernel/
reduction.rs

1//! Term reduction for the Calculus of Constructions.
2//!
3//! This module implements the evaluation semantics of the kernel. Terms are
4//! reduced to normal form using a call-by-name strategy.
5//!
6//! # Reduction Rules
7//!
8//! ## Beta Reduction
9//! Function application: `(λx. body) arg → body[x := arg]`
10//!
11//! ## Iota Reduction
12//! Pattern matching: `match (Cᵢ args) { ... caseᵢ ... } → caseᵢ(args)`
13//!
14//! ## Fix Unfolding (Guarded)
15//! Recursive definitions: `(fix f. body) (Cᵢ args) → body[f := fix f. body] (Cᵢ args)`
16//!
17//! Fix unfolding is guarded by requiring the argument to be in constructor form.
18//! This ensures termination by structural recursion.
19//!
20//! ## Delta Reduction
21//! Global definitions are expanded when needed during normalization.
22//!
23//! # Primitive Operations
24//!
25//! The reducer handles built-in operations on literals:
26//! - Arithmetic: `add`, `sub`, `mul`, `div`, `mod`
27//! - Comparison: `lt`, `le`, `gt`, `ge`, `eq`
28//! - Boolean: `ite` (if-then-else)
29//!
30//! # Reflection Builtins
31//!
32//! Special operations for the deep embedding (Syntax type):
33//! - `syn_size`: Compute the size of a syntax tree
34//! - `syn_max_var`: Find the maximum variable index
35//! - `syn_step`, `syn_eval`: Bounded evaluation
36//! - `syn_quote`, `syn_diag`: Reification and diagonalization
37//!
38//! # Divergence
39//!
40//! Normalization detects a CYCLING reduction (Brent's algorithm, O(1) memory) and falls back
41//! on a large step budget for divergence that does not cycle. `normalize_checked` reports
42//! which happened; `normalize` hands back how far it got, because its signature is public API.
43
44use crate::context::Context;
45use crate::omega;
46use crate::term::{int_lit, lit_bigint, Literal, Term};
47use crate::type_checker::substitute;
48
49/// Why a reduction stopped before reaching a normal form.
50///
51/// `normalize` hands back a bare `Term`, so "this is the normal form" and "this is as far as I
52/// got" are THE SAME ANSWER — and the caller cannot tell them apart. That is not a precision
53/// loss, it is a soundness channel: a conversion check that compares two abandoned reductions
54/// and finds them equal has certified nothing.
55///
56/// A δ-cycle (`a := b`, `b := a`) proves no fuel constant can close the gap, because that
57/// reduction has no normal form at all. Only an error channel can.
58///
59/// It is nevertheless CONSERVATIVE rather than unsound, and the reason is worth stating because
60/// it is what a future change can break: `reduce_step_opt` is a FUNCTION of the term, so two
61/// reductions holding the same term after the same number of steps hold it forever after and
62/// therefore have the same normal form. A conversion check built on "normalise both sides, then
63/// compare" can be INCOMPLETE when a budget runs out — never wrong. The same determinism makes
64/// the cycle answer safe: `normalize` hands the INPUT back, and the only term that can be
65/// mistaken for is itself. Collapsing every non-normalising term to one answer instead — a
66/// shared `Hole`, say — would identify two unrelated cycles and let `refl` prove an equation
67/// between two well-typed terms that are not equal.
68#[derive(Debug, Clone, Copy, PartialEq, Eq)]
69pub enum Unreduced {
70    /// The reduction returned to a term it had already produced, so it cycles forever. The
71    /// term has NO normal form.
72    Cyclic,
73    /// The step budget ran out. The term may or may not have a normal form.
74    BudgetSpent,
75    /// The term nests deeper than the kernel will descend, so the reducer never started.
76    TooDeep,
77}
78
79thread_local! {
80    /// The first RESOURCE stop — a spent step budget or a term too deep to descend — of any
81    /// reduction run on this thread since the innermost [`observe_resource_stops`] began.
82    /// Recorded where the kernel gives up, whether or not its caller then carries on with the
83    /// partial term, because the caller that carries on is exactly the one that cannot tell.
84    static RESOURCE_STOP: std::cell::Cell<Option<Unreduced>> = const { std::cell::Cell::new(None) };
85}
86
87/// Record that kernel work stopped for want of a resource rather than reaching its answer.
88/// A cycle is not a resource stop: it is a proof that there is no normal form to reach.
89pub(crate) fn record_resource_stop(reason: Unreduced) {
90    if reason == Unreduced::Cyclic {
91        return;
92    }
93    RESOURCE_STOP.with(|stop| {
94        if stop.get().is_none() {
95            stop.set(Some(reason))
96        }
97    });
98}
99
100/// The resource stop recorded on this thread, for `term_store`'s sized-stack threads to carry
101/// back to the thread that started them.
102pub(crate) fn resource_stop_on_this_thread() -> Option<Unreduced> {
103    RESOURCE_STOP.with(|stop| stop.get())
104}
105
106/// Run `f` and report the first resource stop of any kernel work it did — a reduction that spent
107/// its step budget, or a term too deep to descend — on this thread or on any sized-stack thread
108/// the kernel started for it.
109///
110/// This is what makes "not equal" an answer. A conversion that returns `false` after one of its
111/// reductions stopped short has compared a partial term, and a partial term can differ from a
112/// normal form it never reached: that `false` is an UNDECIDED comparison, never evidence that the
113/// two sides differ. Only the conversion that ran knows whether it depended on such a stop, so
114/// the record is taken from inside it — never reconstructed afterwards by normalizing the whole
115/// sides again, which costs more than the conversion it audits and cannot even see what the
116/// conversion actually compared (`refute-cheap-first` refutes `(false, count 200)` against
117/// `(true, count 201)` at the booleans without ever evaluating `count`).
118///
119/// Observations nest: the record of the enclosing observation is restored afterwards, and learns
120/// of a stop inside this one too.
121pub fn observe_resource_stops<R>(f: impl FnOnce() -> R) -> (R, Option<Unreduced>) {
122    struct Enclosing(Option<Unreduced>);
123    impl Drop for Enclosing {
124        fn drop(&mut self) {
125            RESOURCE_STOP.with(|stop| {
126                let inner = stop.get();
127                stop.set(self.0.or(inner));
128            });
129        }
130    }
131    let enclosing = Enclosing(RESOURCE_STOP.with(|stop| stop.replace(None)));
132    let result = f();
133    let stopped = RESOURCE_STOP.with(|stop| stop.get());
134    drop(enclosing);
135    (result, stopped)
136}
137
138/// Run `f` WITHOUT letting its resource stops reach the enclosing observation — for work whose
139/// answer the verdict does not use (a debug differential that re-decides a pair already decided).
140pub fn discard_resource_stops<R>(f: impl FnOnce() -> R) -> R {
141    struct Enclosing(Option<Unreduced>);
142    impl Drop for Enclosing {
143        fn drop(&mut self) {
144            RESOURCE_STOP.with(|stop| stop.set(self.0));
145        }
146    }
147    let _enclosing = Enclosing(RESOURCE_STOP.with(|stop| stop.replace(None)));
148    f()
149}
150
151/// The maximum number of whole-term reduction steps. Large enough that no TERMINATING
152/// reduction the kernel is asked for hits it (a 20 000-step δ-chain has 50× headroom), because
153/// a budget that stops a terminating reduction is indistinguishable from a normal form. Cyclic
154/// divergence is caught by cycle detection below, long before this.
155const MAX_REDUCTION_STEPS: usize = 1 << 20;
156
157/// How much δ a reduction is allowed — Lean's `TransparencyMode`, narrowed to the axis that
158/// actually changes the answer.
159///
160/// FOLLOWING LEAN, INCLUDING WHERE IT IS SUBTLE. Reducibility in Lean is an ELABORATOR
161/// attribute: Lean's KERNEL unfolds every definition whatever its attribute, which is why
162/// `example : secret = 5 := rfl` on an `@[irreducible] def secret : Nat := 5` is refused by the
163/// elaborator and *accepted* by the kernel. So [`Transparency::All`] is the kernel's own
164/// setting and stays what [`normalize`] uses, and [`Transparency::Excluding`] is the
165/// elaborator's default transparency — the setting under which an `@[irreducible]` constant
166/// keeps its body AND stays folded. Collapsing the two in either direction is a real loss:
167/// always-transparent makes LOGOS prove by `rfl` what Lean's elaborator refuses (the
168/// over-permissive direction), and routing irreducibility through `add_declaration` instead
169/// throws the body away and manufactures a silent axiom.
170///
171/// The opacity set is supplied as a PREDICATE rather than read out of the `Context`, so the
172/// reducer does not have to know how the attribute is stored: a reducibility map in `Context`
173/// wires in as `Transparency::Excluding(&|n| ctx.is_irreducible(n))` and nothing here changes.
174#[derive(Clone, Copy)]
175pub enum Transparency<'a> {
176    /// Unfold every definition. The kernel's setting.
177    All,
178    /// Keep every constant the predicate accepts FOLDED, body intact. The elaborator's default.
179    ///
180    /// `+ Sync` is not decoration: without it `Transparency` is not `Send`, and a normalisation
181    /// entry point that cannot cross a thread boundary cannot be run on a SIZED STACK — which is
182    /// what stops a deep term ABORTING the process instead of failing. The bound costs nothing:
183    /// every predicate here is built from `Context::is_irreducible`, and `Context` is `Sync`.
184    Excluding(&'a (dyn Fn(&str) -> bool + Sync)),
185}
186
187impl Transparency<'_> {
188    /// Whether δ may unfold `name` at this transparency.
189    fn unfolds(&self, name: &str) -> bool {
190        match self {
191            Transparency::All => true,
192            Transparency::Excluding(opaque) => !(*opaque)(name),
193        }
194    }
195}
196
197/// Normalize a term, reporting honestly when the reduction did not finish.
198///
199/// `Err((partial, why))` carries the term the reducer had reached, so a caller that wants
200/// best-effort behaviour can still have it — but it has to ask for it, which is the whole
201/// point.
202///
203/// Divergence is detected with Brent's cycle-finding: one saved term (the "tortoise"), re-saved
204/// at powers of two, compared against each new term. It needs O(1) memory, finds a cycle of any
205/// period within about twice the cycle length, and — unlike a step budget — answers the δ-cycle
206/// case CORRECTLY rather than merely late.
207pub fn normalize_checked(ctx: &Context, term: &Term) -> Result<Term, (Term, Unreduced)> {
208    normalize_checked_at(ctx, term, Transparency::All)
209}
210
211/// [`normalize_checked`] at a chosen transparency — the honest face of [`normalize_at`].
212pub fn normalize_checked_at(
213    ctx: &Context,
214    term: &Term,
215    tr: Transparency<'_>,
216) -> Result<Term, (Term, Unreduced)> {
217    if let Some(r) = crate::annotation::erased(term, |term| normalize_checked_at(ctx, term, tr)) {
218        return r;
219    }
220    // A SIZED STACK, measured ONCE per outermost kernel call, and measured HERE because this is
221    // the one funnel every normalisation entry point reaches — `normalize`, `normalize_at`,
222    // `normalize_checked`, `normalize_elab` and `normalize_checked_elab` all end up in this
223    // function, so wiring it once is wiring it five times without five chances to forget one.
224    //
225    // It matters because `reduce_step_opt` descends with NATIVE recursion: a term deeper than
226    // the thread's stack does not fail, it ABORTS THE PROCESS, and a public entry point may
227    // never do that. `deepen_stack` runs a shallow term inline and a deep one on a scoped
228    // thread sized for it, and returns `None` on the re-entrant call inside its own closure —
229    // so the depth measurement is paid exactly once however deep the recursion goes.
230    let result =
231        match crate::term_store::deepen_stack(term, || normalize_checked_at_sized(ctx, term, tr)) {
232            Some(result) => result,
233            None => normalize_checked_at_sized(ctx, term, tr),
234        };
235    if let Err((_, reason)) = &result {
236        record_resource_stop(*reason);
237    }
238    result
239}
240
241/// [`normalize_checked`] within `steps` whole-term reduction steps rather than the kernel's full
242/// allowance: exactly the same normal form whenever one is reached within them, `BudgetSpent`
243/// sooner otherwise. A PROBE: its stop is not recorded as a resource stop of the enclosing
244/// conversion, because the caller answers it with another method, not with a refusal.
245pub(crate) fn normalize_checked_within(
246    ctx: &Context,
247    term: &Term,
248    steps: usize,
249) -> Result<Term, (Term, Unreduced)> {
250    if let Some(r) =
251        crate::annotation::erased(term, |term| normalize_checked_within(ctx, term, steps))
252    {
253        return r;
254    }
255    let limit = steps.min(MAX_REDUCTION_STEPS);
256    discard_resource_stops(|| {
257        match crate::term_store::deepen_stack(term, || {
258            normalize_sized(ctx, term, Transparency::All, limit)
259        }) {
260            Some(result) => result,
261            None => normalize_sized(ctx, term, Transparency::All, limit),
262        }
263    })
264}
265
266/// [`normalize_checked_at`]'s body, on a stack sized for `term`.
267fn normalize_checked_at_sized(
268    ctx: &Context,
269    term: &Term,
270    tr: Transparency<'_>,
271) -> Result<Term, (Term, Unreduced)> {
272    normalize_sized(ctx, term, tr, MAX_REDUCTION_STEPS)
273}
274
275/// The normalization pipeline within `limit` (at most `MAX_REDUCTION_STEPS`) whole-term steps.
276fn normalize_sized(
277    ctx: &Context,
278    term: &Term,
279    tr: Transparency<'_>,
280    limit: usize,
281) -> Result<Term, (Term, Unreduced)> {
282    // A NESTED normalization may be handed a term deeper than the stack its outermost kernel call
283    // was sized for: a reduct an earlier normalization in the same conversion built (and handed
284    // back partial at the depth door). `deepen_stack` answers `None` for a nested call, so the
285    // term is measured here and the stack grown for it, exactly as `normalize_progress` does for
286    // the terms it builds — a public entry point may refuse a deep term, but never abort.
287    let depth = crate::term_store::term_depth(term);
288    let sized = depth.min(crate::type_checker::MAX_TERM_DEPTH);
289    if sized > crate::term_store::INLINE_DEPTH
290        && crate::term_store::stack_bytes_for_depth(sized) > crate::term_store::kernel_stack_bytes()
291    {
292        return crate::term_store::grow_stack_for_depth(sized, || {
293            normalize_sized(ctx, term, tr, limit)
294        });
295    }
296    // A term past the door is refused here and not by `enter_kernel`, which admits every term once
297    // a kernel call is under way: a nested normalization can be handed the partial reduct an earlier
298    // one stopped at, one level past the door, and descending it would exhaust the stack. The
299    // refusal's partial term is cloned on the stack grown just above.
300    if depth > crate::type_checker::MAX_TERM_DEPTH {
301        return Err((term.clone(), Unreduced::TooDeep));
302    }
303    // `reduce_step_opt` descends into every subterm with native recursion, so a term deeper
304    // than the kernel's door is refused BEFORE the first clone — cloning a `Term` is itself
305    // recursive over its `Box`es, so even copying a deep enough term aborts the process.
306    let Some(_door) = crate::type_checker::enter_kernel_or_refuse(term) else {
307        return Err((term.clone(), Unreduced::TooDeep));
308    };
309    // `None` is the reducer SAYING there is no redex, not a structural comparison guessing it.
310    // That is one fewer Θ(size) walk per step — and, unlike `reduced == current`, it is right
311    // about a term holding a `NaN`, which is never equal to itself.
312    //
313    // The first question is asked on the BORROWED term, because the commonest input to a
314    // conversion check is ALREADY a normal form: that answer now costs one walk and a single
315    // clone (the one the return value needs), where the old shape cloned the whole term TWICE
316    // before taking a single step.
317    // The existing pure beta/zeta door gives the exact same normal form at
318    // every transparency. Its conservative shape/name checks exclude all other
319    // reduction rules. Use it where sharing repays the per-call store setup.
320    if depth >= 64 {
321        if let Some(nf) =
322            crate::term_store::beta_zeta_normal_form_in_context(ctx, term, limit as u64)
323        {
324            return Ok(nf);
325        }
326    }
327    // Spend from the existing budget; unsuccessful speculation does not reset it. A smaller limit
328    // is the same budget with `MAX_REDUCTION_STEPS - limit` already spent.
329    let mut spent = MAX_REDUCTION_STEPS - limit;
330    if shared_head::natural_result_candidate(ctx, term, tr) {
331        let allowance = limit as u64;
332        let (answer, remaining) = shared_head::natural_normal_form(ctx, term, tr, allowance);
333        spent += (allowance - remaining) as usize;
334        if let shared_head::NatReadbackOutcome::Normal(normal) = answer {
335            return Ok(normal);
336        }
337    }
338    normalize_tree_with_spent(ctx, term, tr, spent)
339}
340
341// Resume ordinary reduction with prior speculative work charged to its budget.
342fn normalize_tree_with_spent(
343    ctx: &Context,
344    term: &Term,
345    tr: Transparency<'_>,
346    spent: usize,
347) -> Result<Term, (Term, Unreduced)> {
348    if spent >= MAX_REDUCTION_STEPS {
349        return Err((term.clone(), Unreduced::BudgetSpent));
350    }
351    let Some(current) = reduce_step_opt(ctx, term, tr) else {
352        return Ok(term.clone());
353    };
354    normalize_progress(ctx, tr, current, term.clone(), 0, 1, spent + 1)
355}
356
357/// Resume with exactly the same fuel and cycle detector after stack growth.
358fn normalize_progress(
359    ctx: &Context,
360    tr: Transparency<'_>,
361    mut current: Term,
362    mut tortoise: Term,
363    mut since_save: usize,
364    mut save_at: usize,
365    mut steps: usize,
366) -> Result<Term, (Term, Unreduced)> {
367    let _probes = KProbeMemo::install();
368    loop {
369        let depth = crate::term_store::term_depth(&current);
370        if depth > crate::type_checker::MAX_TERM_DEPTH {
371            return Err((current, Unreduced::TooDeep));
372        }
373        if depth > crate::term_store::INLINE_DEPTH
374            && crate::term_store::stack_bytes_for_depth(depth)
375                > crate::term_store::kernel_stack_bytes()
376        {
377            return crate::term_store::grow_stack_for_depth(depth, || {
378                normalize_progress(ctx, tr, current, tortoise, since_save, save_at, steps)
379            });
380        }
381        if current == tortoise {
382            return Err((current, Unreduced::Cyclic));
383        }
384        since_save += 1;
385        if since_save == save_at {
386            tortoise = current.clone();
387            since_save = 0;
388            save_at *= 2;
389        }
390        if steps == MAX_REDUCTION_STEPS {
391            return Err((current, Unreduced::BudgetSpent));
392        }
393        if !reduce_step_in_place(ctx, &mut current, tr) {
394            return Ok(current);
395        }
396        steps += 1;
397    }
398}
399
400/// Normalize a term to its normal form.
401///
402/// Repeatedly applies reduction rules until no more reductions are possible.
403/// This is a full normalization that reduces under binders.
404///
405/// This is the BEST-EFFORT face of [`normalize_checked`]: when the reduction cannot be
406/// finished it hands back how far it got, which is exactly the answer a caller cannot
407/// distinguish from success. It keeps this shape because `normalize` is re-exported from the
408/// crate root and callers across the workspace depend on the signature; every caller INSIDE the
409/// kernel that can carry an error should ask `normalize_checked` instead.
410pub fn normalize(ctx: &Context, term: &Term) -> Term {
411    normalize_at(ctx, term, Transparency::All)
412}
413
414/// [`normalize`] at a chosen transparency. At [`Transparency::Excluding`] the named constants
415/// keep their bodies and stay FOLDED, which is what `@[irreducible]` means at Lean's default
416/// transparency; `normalize` itself is the kernel's setting and unfolds everything.
417pub fn normalize_at(ctx: &Context, term: &Term, tr: Transparency<'_>) -> Term {
418    match normalize_checked_at(ctx, term, tr) {
419        Ok(normal) => normal,
420        // A CYCLING reduction has no normal form, and every term on the cycle is as good an
421        // answer as any other — so handing back an arbitrary one makes `normalize`
422        // non-idempotent (`normalize(a) = b`, `normalize(b) = a`) and every conversion check
423        // built on "normalize both sides, then compare" inherits the instability. Handing the
424        // term back unchanged is the one answer that is at least a FUNCTION.
425        Err((_partial, Unreduced::Cyclic)) => term.clone(),
426        Err((partial, _why)) => partial,
427    }
428}
429
430/// [`normalize`] at the ELABORATOR's transparency, reading the context's own reducibility
431/// registry — the door that makes `@[irreducible]` reachable without every caller inventing its
432/// own opacity predicate.
433///
434/// [`Transparency::Excluding`] takes a PREDICATE so the reducer need not know how the attribute
435/// is stored; the cost of that freedom is that a caller has to build the closure, and two
436/// callers that build it differently would disagree about whether a constant unfolds — which is
437/// `def_eq` answering differently depending on who asked. This is the one closure, built from
438/// [`Context::is_irreducible`], so there is nothing to get wrong.
439///
440/// FOLLOWING LEAN, INCLUDING WHERE IT IS SUBTLE: this is NOT what the kernel uses. Lean's kernel
441/// unfolds every definition whatever its attribute — `example : secret = 5 := rfl` on an
442/// `@[irreducible] def secret := 5` is refused by the elaborator and accepted by the kernel —
443/// so [`normalize`] stays [`Transparency::All`] and this is the elaborator's face.
444pub fn normalize_elab(ctx: &Context, term: &Term) -> Term {
445    let opaque = |n: &str| ctx.is_irreducible(n);
446    normalize_at(ctx, term, Transparency::Excluding(&opaque))
447}
448
449/// [`normalize_elab`]'s honest face: the elaborator's transparency, and a reduction that did not
450/// finish reported as such rather than handed back as a normal form.
451pub fn normalize_checked_elab(ctx: &Context, term: &Term) -> Result<Term, (Term, Unreduced)> {
452    let opaque = |n: &str| ctx.is_irreducible(n);
453    normalize_checked_at(ctx, term, Transparency::Excluding(&opaque))
454}
455
456/// A rewrite that FIRED, reported as progress only if it actually changed the term.
457///
458/// Some rules are idempotent re-wrappings rather than genuine steps (a reflection builtin that
459/// re-normalises an already-normal argument, say), and a reducer that claimed progress for one
460/// of those would spin until the budget ran out. The comparison costs a walk, but it happens
461/// only on the path where a named rule already matched — never on the search for one.
462fn progressed(term: &Term, result: Term) -> Option<Term> {
463    if result == *term {
464        None
465    } else {
466        Some(result)
467    }
468}
469
470thread_local! {
471    /// The ι follow-up steps nested inside one another on this thread (see `reduce_step_opt`).
472    static IOTA_FOLLOW_UPS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
473}
474
475/// How many ι follow-up steps may nest. The stack a normalization runs on is sized at
476/// `term_store::BYTES_PER_RUNG` (48 KiB) per level of the term it holds; a `reduce_step_opt` frame
477/// is about 8.9 KB in a debug build (measured). Each nested follow-up adds one more frame per level
478/// descended, so the descent and four follow-ups — five frames, ≈ 45 KB — are what one rung holds.
479const IOTA_FOLLOW_UP_LIMIT: usize = 4;
480
481struct IotaFollowUp(usize);
482
483impl IotaFollowUp {
484    fn enter() -> Option<IotaFollowUp> {
485        let nested = IOTA_FOLLOW_UPS.with(|n| n.get());
486        if nested >= IOTA_FOLLOW_UP_LIMIT {
487            return None;
488        }
489        IOTA_FOLLOW_UPS.with(|n| n.set(nested + 1));
490        Some(IotaFollowUp(nested))
491    }
492}
493
494impl Drop for IotaFollowUp {
495    fn drop(&mut self) {
496        IOTA_FOLLOW_UPS.with(|n| n.set(self.0));
497    }
498}
499
500/// Single-step reduction — `None` means THERE WAS NO REDEX, so the term is already normal.
501///
502/// Reduces the outermost redex first (call-by-name), then recurses into subterms for full
503/// normalization.
504///
505/// **Why progress is a RETURN VALUE and not a comparison.** This used to answer with a `Term`
506/// alone, and [`normalize_checked_at`] recovered "did anything happen?" by comparing the answer
507/// to the input. That is wrong twice over. It costs a Θ(size) structural walk PER STEP, on top
508/// of the Θ(size) walk the step itself already paid — and it is only correct if term equality is
509/// REFLEXIVE, which it is not: `Literal::Float` compares with IEEE `==`, so a term holding a
510/// `NaN` is never equal to itself, the fixpoint test can never fire, and `normalize` spent its
511/// whole 2^20-step budget on a term that was ALREADY A NORMAL FORM — then reported
512/// `Unreduced::BudgetSpent` about it. Progress is something the reducer knows for certain;
513/// saying so is both exact and free, and it also stops every no-progress arm from cloning a
514/// term it is handing straight back.
515///
516/// A rule that FIRED and led back to where it started (`a := a`, `fix f. f`) reports progress and
517/// is caught by cycle detection as [`Unreduced::Cyclic`] — which is the honest answer, because
518/// such a term has no normal form. "There is no redex" and "there is a redex that leads nowhere"
519/// are different facts and must not share an answer.
520fn reduce_step_opt(ctx: &Context, term: &Term, tr: Transparency<'_>) -> Option<Term> {
521    #[cfg(test)]
522    TREE_REDUCTION_CALLS.with(|n| n.set(n.get() + 1));
523    // A registered `@[simp]` rule is a REWRITE the environment was told to perform, and it is
524    // tried before β/δ/ι rather than after — see [`try_simp_rewrite`] for why "when everything
525    // else is stuck" is the one placement that can never fire. In a context with no registered
526    // rule (every context the prelude builds) this is one `is_empty` on a slice.
527    if let Some(rewritten) = try_simp_rewrite(ctx, term) {
528        return Some(rewritten);
529    }
530    match term {
531        // Literals are in normal form
532        Term::Lit(_) => None,
533
534        // Delta for a universe-polymorphic reference: unfold its body with the universe
535        // parameters instantiated by the level arguments.
536        //
537        // ONE KERNEL, ONE VERDICT. A `Const` whose level list does not match its declaration's
538        // universe PARAMETERS is not a term of the calculus, and `infer_type` refuses it. This
539        // arm used to fall through to `term.clone()` — the reducer answering "settled normal
540        // form" about a term that denotes nothing, so a conversion check that normalises both
541        // sides and compares would happily compare two meaningless terms and find them equal.
542        // The honest answer is [`Term::Hole`], the kernel's own "nothing determinate here",
543        // which `infer_type` refuses by construction (`CannotInferHole`). It is the one answer
544        // that neither passes for a normal form nor LAUNDERS the term: zipping the level list
545        // and dropping the extra would silently make `id.{0,1}` mean `id.{0}` and hand back
546        // something well typed.
547        //
548        // Malformedness is a property of the TERM, so it is decided before the transparency
549        // door — an `@[irreducible]` constant is still a constant; a mis-levelled one is not.
550        Term::Const { name, levels } => match const_step(ctx, name, levels) {
551            ConstStep::Unresolved => None,
552            ConstStep::Illformed => Some(Term::Hole),
553            ConstStep::Value => None,
554            ConstStep::Delta(subst, body) => {
555                if !tr.unfolds(name) {
556                    return None;
557                }
558                Some(crate::term::instantiate_universes(&body, &subst))
559            }
560        },
561
562        // Beta: (λx. body) arg → body[x := arg]
563        Term::App(func, arg) => {
564            // First try primitive reduction (add, sub, mul, etc.)
565            if let Some(result) = try_primitive_reduce(ctx, func, arg, tr) {
566                return progressed(term, result);
567            }
568
569            // An attested alias is a checked structural definition. First give
570            // its operands one ordinary reduction step so nested compact
571            // arithmetic does not lose the alias head and expand into Peano
572            // recursion. Reuse the outer normalization budget and transparency.
573            if let Term::App(head, first) = func.as_ref() {
574                if let Term::Global(operation) = head.as_ref() {
575                    if crate::int_inductive::integer_alias_dependencies(operation).is_some_and(
576                        |dependencies| dependencies.iter().all(|name| tr.unfolds(name)),
577                    ) && crate::int_inductive::accelerates_integer_alias(ctx, operation)
578                    {
579                        if let Some(reduced_first) = reduce_step_opt(ctx, first, tr) {
580                            return Some(Term::App(
581                                Box::new(Term::App(head.clone(), Box::new(reduced_first))),
582                                arg.clone(),
583                            ));
584                        }
585                        if let Some(reduced_last) = reduce_step_opt(ctx, arg, tr) {
586                            return Some(Term::App(func.clone(), Box::new(reduced_last)));
587                        }
588                    }
589                }
590            }
591
592            // Try reflection builtins (syn_size, syn_max_var)
593            if let Some(result) = try_reflection_reduce(ctx, func, arg) {
594                return progressed(term, result);
595            }
596
597            // Native reduction: `reduceBool t` evaluates `t` with the fast CBV evaluator
598            // (the `native_decide` engine). This is the ONLY place the trusted evaluator
599            // enters kernel reduction — gated behind the `reduceBool` primitive, which only
600            // a `native_decide` proof (via the `ofReduceBool` axiom) ever mentions.
601            //
602            // THE SAME TWO GATES EVERY OTHER COMPUTATION RULE PASSES, and it is the rule that
603            // needs them most, being the one whose answer an AXIOM turns into a proof. It used
604            // to match a bare `Term::Global("reduceBool")` and ask neither:
605            //
606            //   * a DEFINITION of the name outranks the builtin — otherwise the reducer answers
607            //     something the context it type-checked the application against says the
608            //     constant does not mean, with no diagnostic anywhere;
609            //   * the rule may not fire at a type the DECLARATION denies — the answer is always
610            //     a `Bool` constructor, so a context declaring `reduceBool : Nat → Nat` got a
611            //     kernel where `infer_type` said `Nat` and `normalize` produced a `Bool`, which
612            //     is subject reduction failing, and it is the same divergence
613            //     `declaration_agrees_with_the_rule` was written to close for the Int table.
614            //
615            // NOT gated on transparency: this is a computation rule, not δ — Lean runs its
616            // `reduceNat?`/`reduceNative?` from `whnfImp` (`Lean/Meta/WHNF.lean:999-1004`)
617            // before `unfoldDefinition?` and without consulting `TransparencyMode`.
618            if let Term::Global(name) = func.as_ref() {
619                if name == "reduceBool"
620                    && ctx.get_definition_body(name).is_none()
621                    && declaration_agrees_with_the_rule(ctx, name)
622                {
623                    if let Some(b) = crate::eval::eval_bool(ctx, arg) {
624                        return progressed(
625                            term,
626                            Term::Global(if b { "true" } else { "false" }.to_string()),
627                        );
628                    }
629                }
630            }
631
632            // Quotient computation: `Quot_lift A r B f h (Quot_mk A r a) ⤳ f a`, and `Quot_ind`'s.
633            if let Some(result) = try_quot_lift_reduce(ctx, func, arg) {
634                return progressed(term, result);
635            }
636
637            // Observational equality computes on its type (`observational`).
638            if let Some(result) = try_obs_reduce(ctx, func, arg) {
639                return progressed(term, result);
640            }
641
642            // ι for a fixpoint, at the column the termination guard admitted it on. Asked of
643            // the WHOLE spine, because the structural argument need not be the innermost one.
644            if let Some(result) = try_fix_unroll(ctx, term) {
645                return progressed(term, result);
646            }
647
648            // Then try to reduce at the head
649            match func.as_ref() {
650                Term::Lambda { param, body, .. } => {
651                    // Beta reduction. The redex is GONE from the answer — substituting into a
652                    // body cannot reproduce the application that contained it — so this is
653                    // progress without needing to be compared.
654                    Some(substitute(body, param, arg))
655                }
656                // Fix application. UNROLLING IS NOT DECIDED HERE: `try_fix_unroll` above asked
657                // the termination guard which column the recursion descends on and answered for
658                // the whole spine. This arm only makes progress in the ARGUMENT, so a structural
659                // argument that is not yet a constructor can become one.
660                //
661                // The test this arm used to make — "is the argument the innermost `App` happens
662                // to carry a constructor?" — was wrong in both directions at once. It left
663                // `Nat.add`, which recurses on its SECOND argument, stuck for every opaque
664                // first argument; and it UNROLLED on a constructor sitting in a non-structural
665                // column, where the guard promises no decreasing measure and the unrolling need
666                // never stop.
667                Term::Fix { .. } => {
668                    let reduced_arg = reduce_step_opt(ctx, arg, tr)?;
669                    Some(Term::App(func.clone(), Box::new(reduced_arg)))
670                }
671                // Mutual fix application: (mutualfix { fⱼ := bⱼ }.i) arg. When `arg` is a
672                // constructor, unfold the i-th body, substituting EACH sibling name by its
673                // own projection of the block, then apply — the mutual analog of the Fix
674                // unfold above (so `Even.rec`'s call to `Odd.rec` computes).
675                Term::MutualFix { defs, index } => {
676                    if is_constructor_form(ctx, arg) {
677                        let mut unfolded = defs[*index].1.clone();
678                        for (j, (name_j, _)) in defs.iter().enumerate() {
679                            let proj = Term::MutualFix {
680                                defs: defs.clone(),
681                                index: j,
682                            };
683                            unfolded = substitute(&unfolded, name_j, &proj);
684                        }
685                        Some(Term::App(Box::new(unfolded), arg.clone()))
686                    } else {
687                        let reduced_arg = reduce_step_opt(ctx, arg, tr)?;
688                        Some(Term::App(func.clone(), Box::new(reduced_arg)))
689                    }
690                }
691                // Nested application: ((f x) y) - reduce inner first, then the argument.
692                // Other function forms take the same route.
693                _ => {
694                    if let Some(reduced_func) = reduce_step_opt(ctx, func, tr) {
695                        return Some(Term::App(Box::new(reduced_func), arg.clone()));
696                    }
697                    let reduced_arg = reduce_step_opt(ctx, arg, tr)?;
698                    Some(Term::App(func.clone(), Box::new(reduced_arg)))
699                }
700            }
701        }
702
703        // Iota: match (Cᵢ a₁...aₙ) with cases → caseᵢ a₁ ... aₙ
704        Term::Match {
705            discriminant,
706            motive,
707            cases,
708        } => {
709            // `cases.get`, NOT `cases[…]`. The index comes from `extract_constructor`, whose Peano
710            // bridge reports index 1 (`Succ`) for ANY positive `Lit(Nat(n))` regardless of which
711            // inductive the `Match` was written against — so a `Match` with fewer cases than that
712            // index used to panic and ABORT THE PROCESS out of `normalize`, a public entry point
713            // that must be total. An out-of-range index means the `Match` is malformed and the type
714            // checker will reject it; reduction's job is to make no progress, not to crash.
715            if let Some(result) = iota_branch(ctx, discriminant, motive, cases) {
716                // ι fired — the `Match` node is gone whatever happens next — then take one more
717                // step on the selected branch if it has one. That step can be another ι whose
718                // branch is stepped in turn, a recursion bounded by no term's depth, so only a few
719                // follow-ups nest; past them the branch is handed back and the normalization loop
720                // (which sizes its stack by the term it holds) takes the next step.
721                let Some(_follow_up) = IotaFollowUp::enter() else {
722                    return Some(result);
723                };
724                let stepped = reduce_step_opt(ctx, &result, tr);
725                Some(stepped.unwrap_or(result))
726            } else {
727                // K and fieldless structure reduction require exactly one
728                // constructor. Multiple branches cannot use either rule, so
729                // do not recursively type-check their neutral scrutinees.
730                if let Some(constructor) = (cases.len() == 1)
731                    .then(|| k_constructor_form(ctx, discriminant, motive))
732                    .flatten()
733                {
734                    return Some(Term::Match {
735                        discriminant: Box::new(constructor),
736                        motive: motive.clone(),
737                        cases: cases.clone(),
738                    });
739                }
740                // Try reducing the discriminant
741                let reduced_disc = reduce_step_opt(ctx, discriminant, tr)?;
742                Some(Term::Match {
743                    discriminant: Box::new(reduced_disc),
744                    motive: motive.clone(),
745                    cases: cases.clone(),
746                })
747            }
748        }
749
750        // Reduce under lambdas (deep normalization)
751        Term::Lambda {
752            param,
753            param_type,
754            body,
755        } => {
756            let reduced_param_type = reduce_step_opt(ctx, param_type, tr);
757            let reduced_body =
758                reduce_step_opt(&ctx.extend(param, (**param_type).clone()), body, tr);
759            if reduced_param_type.is_none() && reduced_body.is_none() {
760                return None;
761            }
762            Some(Term::Lambda {
763                param: param.clone(),
764                param_type: Box::new(reduced_param_type.unwrap_or_else(|| (**param_type).clone())),
765                body: Box::new(reduced_body.unwrap_or_else(|| (**body).clone())),
766            })
767        }
768
769        // Reduce under Pi types
770        Term::Pi {
771            param,
772            param_type,
773            body_type,
774        } => {
775            let reduced_param_type = reduce_step_opt(ctx, param_type, tr);
776            let reduced_body_type =
777                reduce_step_opt(&ctx.extend(param, (**param_type).clone()), body_type, tr);
778            if reduced_param_type.is_none() && reduced_body_type.is_none() {
779                return None;
780            }
781            Some(Term::Pi {
782                param: param.clone(),
783                param_type: Box::new(reduced_param_type.unwrap_or_else(|| (**param_type).clone())),
784                body_type: Box::new(reduced_body_type.unwrap_or_else(|| (**body_type).clone())),
785            })
786        }
787
788        // Reduce under Fix
789        Term::Fix { name, body } => {
790            let reduced_body = reduce_step_opt(ctx, body, tr)?;
791            Some(Term::Fix {
792                name: name.clone(),
793                body: Box::new(reduced_body),
794            })
795        }
796
797        // Reduce under a MutualFix (each body once; sibling names are free Vars here, so
798        // no unfolding happens — this only normalizes the bodies' own redexes).
799        Term::MutualFix { defs, index } => {
800            let stepped: Vec<Option<Term>> = defs
801                .iter()
802                .map(|(_, b)| reduce_step_opt(ctx, b, tr))
803                .collect();
804            if stepped.iter().all(Option::is_none) {
805                return None;
806            }
807            let new_defs = defs
808                .iter()
809                .zip(stepped)
810                .map(|((n, b), rb)| (n.clone(), rb.unwrap_or_else(|| b.clone())))
811                .collect();
812            Some(Term::MutualFix {
813                defs: new_defs,
814                index: *index,
815            })
816        }
817
818        // ζ, OCCURRENCE-GATED. `let x := v in b ⟶ b[x := v]` writes the value at EVERY
819        // occurrence, so a value bound once and used n times is written n times — and the term
820        // the kernel then checks is BIGGER than the one it was handed, which is the opposite of
821        // what a sharing construct is for. Gated on the occurrence count the value is written
822        // ONCE and the binding survives as the sharing node.
823        //
824        // A binder used at most once is substituted exactly as before, byte for byte, which is
825        // what keeps every `let_zeta` case and the ζ-transparency cases green: all of them are
826        // single-occurrence. The gate is re-read as reduction proceeds, because reduction
827        // ERASES occurrences — a body with three uses before reduction and one after must still
828        // expand, and does, on the next pass over the `Let` the previous pass rebuilt.
829        Term::Let {
830            name,
831            ty,
832            value,
833            body,
834        } => crate::term_store::zeta_or_share_opt(name, ty, value, body, &|t| {
835            reduce_step_opt(ctx, t, tr)
836        }),
837
838        // Base cases: already in normal form
839        Term::Sort(_) | Term::Var(_) | Term::Hole => None,
840
841        // Delta reduction: unfold definitions (but not axioms, constructors, or inductives) —
842        // and not an `@[irreducible]` one below the kernel's own transparency, which is the
843        // whole point of the axis: the body is still THERE (so every equation it satisfies
844        // stays provable and no silent axiom is manufactured), it simply does not unfold here.
845        //
846        // A definition whose body is its own name (`a := a`) UNFOLDS — the rule fired — and the
847        // cycle detector then reports the reduction as `Cyclic`, which is true: the term has no
848        // normal form. Calling that "no redex" would be `normalize` certifying a normal form
849        // that does not exist.
850        Term::Global(name) => {
851            if !tr.unfolds(name) {
852                return None;
853            }
854            // Axiom, constructor, or inductive: no reduction.
855            Some(ctx.get_definition_body(name)?.clone())
856        }
857
858        // An annotation is consumed with the step its term takes, as Lean's `whnfCore` consumes
859        // `mdata`, and never by a step of its own: a step that only dropped an annotation would
860        // hand the cycle detector a term `==` to the one before it.
861        Term::Annotated { term, .. } => reduce_step_opt(ctx, term, tr),
862    }
863}
864
865/// Whether a `match` whose motive is `motive` may select a branch for `discriminant`.
866///
867/// Lean's recursor belongs to ONE inductive and fires only on that inductive's constructors
868/// (`getRecRuleFor`). A LOGOS `match` names its inductive through its motive's last binder
869/// (`λ indices… λ(x : I params indices). T`). When that binder's type is headed by a registered
870/// inductive other than the discriminant's, the match is ill-typed and must not compute: the
871/// `Nat` literal `3` is not the `Int` constructor `negSucc`, although both inductives have two
872/// constructors. A motive that does not name an inductive (a raw sort, an alias) is not refused
873/// here — the type checker is the authority on it, and this guard only removes wrong progress.
874///
875/// An ETA-SHORT motive (`λ y. tail y`, whose major-premise binder lives inside `tail`'s own
876/// type) has fewer lambdas than the discriminant's index telescope plus the major, so its last
877/// lambda binds an INDEX, not the major premise; there is no syntactic major domain to read, and
878/// the guard defers to the type checker exactly as it does for a motive that names no inductive.
879fn motive_admits(ctx: &Context, motive: &Term, discriminant: &Term) -> bool {
880    let Some(actual) = constructor_inductive_of(ctx, discriminant) else {
881        return true;
882    };
883    let mut domain = None;
884    let mut binders = 0usize;
885    let mut current = motive;
886    while let Term::Lambda {
887        param_type, body, ..
888    } = current
889    {
890        domain = Some(param_type.as_ref());
891        binders += 1;
892        current = body;
893    }
894    if binders <= ctx.inductive_num_indices(&actual) {
895        return true;
896    }
897    let Some(domain) = domain else { return true };
898    let mut head = domain;
899    while let Term::App(f, _) = head {
900        head = f;
901    }
902    let named = match head {
903        Term::Global(n) | Term::Const { name: n, .. } if ctx.is_inductive(n) => n,
904        _ => return true,
905    };
906    actual == *named
907}
908
909/// Select an ordinary constructor branch, shared by full and lazy reduction.
910/// Parameter removal and mutual-block case selection remain in the existing
911/// constructor decoder and case-position calculation.
912fn iota_branch(ctx: &Context, discriminant: &Term, motive: &Term, cases: &[Term]) -> Option<Term> {
913    if !motive_admits(ctx, motive, discriminant) {
914        return None;
915    }
916    let (i, args) = extract_constructor(ctx, discriminant)?;
917    let p = case_position(ctx, discriminant, i, cases.len())?;
918    let mut result = cases.get(p)?.clone();
919    for arg in args {
920        result = Term::App(Box::new(result), Box::new(arg));
921    }
922    Some(result)
923}
924
925#[cfg(test)]
926thread_local! {
927    static BOUNDED_SIZE_PENDING_PEAK: std::cell::Cell<usize> =
928        const { std::cell::Cell::new(0) };
929}
930
931// Bound the work stack before extending wide case/definition vectors.
932// The Boolean records a conservative monomorphic-level fragment for readback;
933// ordinary conversion callers retain their previous Term-node admission.
934pub(crate) fn bounded_conversion_metrics(term: &Term) -> Option<(usize, usize, bool)> {
935    let mut pending = vec![(term, 0usize)];
936    let mut nodes = 0usize;
937    let mut depth = 0usize;
938    let mut plain_levels = true;
939    while let Some((t, d)) = pending.pop() {
940        #[cfg(test)]
941        BOUNDED_SIZE_PENDING_PEAK.with(|peak| peak.set(peak.get().max(pending.len() + 1)));
942        nodes += 1;
943        depth = depth.max(d);
944        let children = match t {
945            Term::App(..) | Term::Lambda { .. } | Term::Pi { .. } => 2,
946            Term::Let { .. } => 3,
947            Term::Match { cases, .. } => cases.len().checked_add(2)?,
948            Term::Fix { .. } => 1,
949            Term::MutualFix { defs, .. } => defs.len(),
950            _ => 0,
951        };
952        if nodes.checked_add(pending.len())?.checked_add(children)? > 4096 {
953            return None;
954        }
955        let next = d + 1;
956        match t {
957            Term::App(f, a) => {
958                pending.push((f, next));
959                pending.push((a, next));
960            }
961            Term::Lambda {
962                param_type, body, ..
963            } => {
964                pending.push((param_type, next));
965                pending.push((body, next));
966            }
967            Term::Pi {
968                param_type,
969                body_type,
970                ..
971            } => {
972                pending.push((param_type, next));
973                pending.push((body_type, next));
974            }
975            Term::Let {
976                ty, value, body, ..
977            } => {
978                pending.push((ty, next));
979                pending.push((value, next));
980                pending.push((body, next));
981            }
982            Term::Match {
983                discriminant,
984                motive,
985                cases,
986            } => {
987                pending.push((discriminant, next));
988                pending.push((motive, next));
989                pending.extend(cases.iter().map(|case| (case, next)));
990            }
991            Term::Fix { body, .. } => pending.push((body, next)),
992            Term::MutualFix { defs, .. } => {
993                pending.extend(defs.iter().map(|(_, body)| (body, next)))
994            }
995            Term::Const { .. } => plain_levels = false,
996            Term::Sort(u) => {
997                plain_levels &= matches!(
998                    u,
999                    crate::Universe::Prop | crate::Universe::SProp | crate::Universe::Type(_)
1000                )
1001            }
1002            _ => {}
1003        }
1004    }
1005    Some((nodes, depth, plain_levels))
1006}
1007
1008/// Size check before cloning or substitution keeps the opportunistic path from
1009/// materializing a large tree even when a single beta step duplicates its input.
1010#[cfg(test)]
1011thread_local! {
1012    static BOUNDED_SIZE_CALLS: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };
1013}
1014
1015pub(crate) fn bounded_conversion_size(term: &Term) -> Option<usize> {
1016    #[cfg(test)]
1017    BOUNDED_SIZE_CALLS.with(|count| {
1018        if let Some(n) = count.get() {
1019            count.set(Some(n + 1));
1020        }
1021    });
1022    bounded_conversion_metrics(term).map(|(nodes, _, _)| nodes)
1023}
1024
1025fn bounded_conversion_substitute(body: &Term, name: &str, value: &Term) -> Option<Term> {
1026    let body_size = bounded_conversion_size(body)?;
1027    let occurrences = crate::term_store::occurrence_count_in_term(body, name) as usize;
1028    let value_size = bounded_conversion_size(value)?;
1029    let upper_bound = body_size.checked_add(occurrences.checked_mul(value_size)?)?;
1030    if upper_bound > 4096 {
1031        return None;
1032    }
1033    Some(substitute(body, name, value))
1034}
1035
1036fn bounded_conversion_substitute_owned(body: Term, name: &str, value: Term) -> Option<Term> {
1037    let body_size = bounded_conversion_size(&body)?;
1038    let value_size = bounded_conversion_size(&value)?;
1039    let Some(occurrences) =
1040        crate::term_store::bounded_occurrence_count_in_term(&body, name, 64, 4096)
1041    else {
1042        // The optimization's bounded lexical scan is optional. Preserve the
1043        // existing behavior for deeper terms rather than adding a refusal.
1044        return bounded_conversion_substitute(&body, name, &value);
1045    };
1046    let upper_bound = body_size.checked_add((occurrences as usize).checked_mul(value_size)?)?;
1047    if upper_bound > 4096 {
1048        return None;
1049    }
1050    Some(crate::type_checker::substitute_owned_value_counted(
1051        body,
1052        name,
1053        value,
1054        occurrences as usize,
1055    ))
1056}
1057
1058/// The shared admission boundary for small closed conversion bodies. This
1059/// checks annotations and every branch, including parts head reduction may erase.
1060pub(crate) fn bounded_closed_conversion_size(body: &Term) -> Option<usize> {
1061    let size = bounded_conversion_size(body)?;
1062    if !crate::term_store::is_closed_without_holes(body) {
1063        return None;
1064    }
1065    Some(size)
1066}
1067
1068/// One closed delta step on the head path only. Its size is a scheduling hint,
1069/// not evidence of equality. Small wrappers can be exposed before a shared,
1070/// expensive function body. Match discriminants are the only other head path.
1071pub(crate) fn bounded_delta_head(ctx: &Context, term: &Term) -> Option<(usize, Term)> {
1072    bounded_delta_head_impl(ctx, term, Transparency::All, bounded_conversion_size, false)
1073}
1074
1075/// Same head-delta rule with caller transparency and pre-copy admission. The
1076/// kernel wrapper above retains its original All policy and size admission.
1077pub(crate) fn bounded_delta_head_with(
1078    ctx: &Context,
1079    term: &Term,
1080    tr: Transparency<'_>,
1081    admit: fn(&Term) -> Option<usize>,
1082) -> Option<(usize, Term)> {
1083    bounded_delta_head_impl(ctx, term, tr, admit, true)
1084}
1085
1086fn bounded_delta_head_impl(
1087    ctx: &Context,
1088    term: &Term,
1089    tr: Transparency<'_>,
1090    admit: fn(&Term) -> Option<usize>,
1091    bounded_telescope: bool,
1092) -> Option<(usize, Term)> {
1093    admit(term)?;
1094    match term {
1095        Term::Global(name) | Term::Const { name, .. } => {
1096            if !tr.unfolds(name) {
1097                return None;
1098            }
1099            let body = match term {
1100                Term::Global(_) => {
1101                    let body = ctx.get_definition_body(name)?;
1102                    // This immutable monomorphic body is unchanged by cloning.
1103                    // Retain its admission result and reject open/hole bodies
1104                    // while borrowed, before allocating an unused copy. Explicit
1105                    // universe instantiation below still needs its own recheck.
1106                    let size = admit(body)?;
1107                    if !crate::term_store::is_closed_without_holes(body) {
1108                        return None;
1109                    }
1110                    return Some((size, body.clone()));
1111                }
1112                Term::Const { levels, .. } => {
1113                    // const_step clones its header and body before resolving
1114                    // levels. Reject oversized candidates while still borrowed,
1115                    // using that resolver's exact lookup precedence.
1116                    match ctx.get_universe_poly(name) {
1117                        Some((params, ty, body)) => {
1118                            // const_step also copies explicit parameter names before
1119                            // resolving arity. Bound this borrowed metadata on the
1120                            // elaborator route, including unused parameters. The
1121                            // original kernel All wrapper retains its prior policy.
1122                            if bounded_telescope
1123                                && (params.len() > 16 || params.iter().any(|name| name.len() > 256))
1124                            {
1125                                return None;
1126                            }
1127                            admit(ty)?;
1128                            admit(body)?;
1129                        }
1130                        None => {
1131                            admit(ctx.get_global(name)?)?;
1132                            if let Some(body) = ctx.get_definition_body(name) {
1133                                admit(body)?;
1134                            }
1135                        }
1136                    }
1137                    match const_step(ctx, name, levels) {
1138                        ConstStep::Delta(subst, body) => {
1139                            crate::term::instantiate_universes(&body, &subst)
1140                        }
1141                        _ => return None,
1142                    }
1143                }
1144                _ => unreachable!(),
1145            };
1146            let size = admit(&body)?;
1147            if !crate::term_store::is_closed_without_holes(&body) {
1148                return None;
1149            }
1150            Some((size, body))
1151        }
1152        Term::App(f, a) => {
1153            let (size, f) = bounded_delta_head_impl(ctx, f, tr, admit, bounded_telescope)?;
1154            Some((size, Term::App(Box::new(f), a.clone())))
1155        }
1156        Term::Match {
1157            discriminant,
1158            motive,
1159            cases,
1160        } => {
1161            let (size, disc) =
1162                bounded_delta_head_impl(ctx, discriminant, tr, admit, bounded_telescope)?;
1163            Some((
1164                size,
1165                Term::Match {
1166                    discriminant: Box::new(disc),
1167                    motive: motive.clone(),
1168                    cases: cases.clone(),
1169                },
1170            ))
1171        }
1172        _ => None,
1173    }
1174}
1175
1176/// Expose only a small head spine, leaving arguments, binder annotations and
1177/// unselected branches unevaluated. This is an opportunistic conversion step;
1178/// a resource boundary returns no result, never a claimed normal form.
1179pub(crate) fn bounded_conversion_head(ctx: &Context, term: &Term) -> Option<Term> {
1180    if !ctx.simp_rules().is_empty() {
1181        return None;
1182    }
1183    let mut budget = 256;
1184    let mut current = beta_iota_zeta_head(ctx, term, &mut budget)?;
1185    loop {
1186        if budget == 0 {
1187            return None;
1188        }
1189        budget -= 1;
1190        match bounded_delta_head(ctx, &current) {
1191            Some((_, next)) => current = beta_iota_zeta_head(ctx, &next, &mut budget)?,
1192            None => return Some(current),
1193        }
1194    }
1195}
1196
1197#[cfg(test)]
1198thread_local! {
1199    static BOUNDED_HEAD_CLONE_NODES: std::cell::Cell<Option<usize>> =
1200        const { std::cell::Cell::new(None) };
1201    static BOUNDED_HEAD_VISITS: std::cell::Cell<Option<usize>> =
1202        const { std::cell::Cell::new(None) };
1203}
1204/// Enable/reset an isolated test counter and return the preceding sample.
1205#[cfg(test)]
1206pub(crate) fn take_bounded_head_clone_nodes() -> usize {
1207    BOUNDED_HEAD_CLONE_NODES.with(|count| count.replace(Some(0)).unwrap_or(0))
1208}
1209
1210/// Count actual evaluator-loop entries, independently of copy and fuel totals.
1211#[cfg(test)]
1212pub(crate) fn take_bounded_head_visits() -> usize {
1213    BOUNDED_HEAD_VISITS.with(|count| count.replace(Some(0)).unwrap_or(0))
1214}
1215
1216/// Weak-head beta/iota/zeta and guarded fixpoint reduction without delta,
1217/// primitives, or proof search. The caller shares one budget across an entire congruence proof.
1218/// A depleted budget is inconclusive. Annotations and unused arguments stay lazy.
1219pub(crate) fn beta_iota_zeta_head(ctx: &Context, term: &Term, budget: &mut usize) -> Option<Term> {
1220    let _clone_nodes = bounded_conversion_size(term)?;
1221    #[cfg(test)]
1222    BOUNDED_HEAD_CLONE_NODES.with(|count| {
1223        if let Some(previous) = count.get() {
1224            count.set(Some(previous + _clone_nodes));
1225        }
1226    });
1227    // Continuations own the siblings which the recursive evaluator used to
1228    // leave in its callers. Moving a demanded child avoids copying its prefix;
1229    // every evaluation visit still spends the original shared work allowance.
1230    enum Frame {
1231        Apply(Term),
1232        Match { motive: Term, cases: Vec<Term> },
1233    }
1234    let mut frames = Vec::new();
1235    let mut current = term.clone();
1236    let mut entering = false; // the original input was preflighted above
1237    'evaluate: loop {
1238        #[cfg(test)]
1239        BOUNDED_HEAD_VISITS.with(|count| {
1240            if let Some(previous) = count.get() {
1241                count.set(Some(previous + 1));
1242            }
1243        });
1244        if entering {
1245            bounded_conversion_size(&current)?;
1246        }
1247        if *budget == 0 {
1248            return None;
1249        }
1250        *budget -= 1;
1251        // A descended child was checked above, before spending its fuel.
1252        // Only rewritten terms need the post-fuel check; current is unchanged here.
1253        if !entering {
1254            bounded_conversion_size(&current)?;
1255        }
1256        match current {
1257            Term::Let {
1258                name, value, body, ..
1259            } => {
1260                current = bounded_conversion_substitute_owned(*body, &name, *value)?;
1261                entering = false;
1262                continue;
1263            }
1264            Term::App(function, argument) => {
1265                frames.push(Frame::Apply(*argument));
1266                current = *function;
1267                entering = true;
1268                continue;
1269            }
1270            Term::Match {
1271                discriminant,
1272                motive,
1273                cases,
1274            } => {
1275                frames.push(Frame::Match {
1276                    motive: *motive,
1277                    cases,
1278                });
1279                current = *discriminant;
1280                entering = true;
1281                continue;
1282            }
1283            _ => {}
1284        }
1285        // Returning through a continuation is not a fresh evaluation visit.
1286        // This exactly mirrors the old call return, including partial spines.
1287        while let Some(frame) = frames.pop() {
1288            match frame {
1289                Frame::Apply(argument) => {
1290                    if let Term::Lambda { param, body, .. } = current {
1291                        current = bounded_conversion_substitute_owned(*body, &param, argument)?;
1292                        entering = false;
1293                        continue 'evaluate;
1294                    }
1295                    let applied = Term::App(Box::new(current), Box::new(argument));
1296                    let (head, args) = app_spine(&applied);
1297                    if let Term::Fix { name, body } = head {
1298                        let column = (args.iter().any(|a| is_constructor_form(ctx, a))
1299                            && crate::termination::check_termination(ctx, name, body).is_ok())
1300                        .then(|| crate::termination::structural_columns(ctx, body))
1301                        .and_then(|columns| columns.first().copied());
1302                        if column
1303                            .and_then(|i| args.get(i))
1304                            .is_some_and(|arg| is_constructor_form(ctx, arg))
1305                        {
1306                            let unfolded = bounded_conversion_substitute(body, name, head)?;
1307                            current = args.iter().fold(unfolded, |f, a| {
1308                                Term::App(Box::new(f), Box::new((*a).clone()))
1309                            });
1310                            entering = false;
1311                            continue 'evaluate;
1312                        }
1313                    }
1314                    current = applied;
1315                }
1316                Frame::Match { motive, cases } => {
1317                    let full_inventory = constructor_inductive_of(ctx, &current)
1318                        .is_some_and(|ind| ctx.get_constructors(&ind).len() == cases.len());
1319                    if let Some(branch) = full_inventory
1320                        .then(|| iota_branch(ctx, &current, &motive, &cases))
1321                        .flatten()
1322                    {
1323                        current = branch;
1324                        entering = false;
1325                        continue 'evaluate;
1326                    }
1327                    current = Term::Match {
1328                        discriminant: Box::new(current),
1329                        motive: Box::new(motive),
1330                        cases,
1331                    };
1332                }
1333            }
1334        }
1335        return Some(current);
1336    }
1337}
1338
1339/// Read the result of a declared application spine without validating its
1340/// arguments. Only a negative eligibility filter may consume this hint. Opaque
1341/// type aliases and oversized substitutions return no hint and use full typing.
1342fn declared_spine_type(ctx: &Context, term: &Term) -> Option<Term> {
1343    bounded_conversion_size(term)?;
1344    let mut head = term;
1345    let mut args = Vec::new();
1346    while let Term::App(f, a) = head {
1347        args.push(a.as_ref());
1348        head = f;
1349    }
1350    if !matches!(head, Term::Var(_) | Term::Global(_) | Term::Const { .. }) {
1351        return None;
1352    }
1353    let mut ty = crate::infer_type(ctx, head).ok()?;
1354    bounded_conversion_size(&ty)?;
1355    for arg in args.into_iter().rev() {
1356        let Term::Pi {
1357            param, body_type, ..
1358        } = ty
1359        else {
1360            return None;
1361        };
1362        ty = bounded_conversion_substitute(&body_type, &param, arg)?;
1363    }
1364    Some(ty)
1365}
1366
1367/// Proof irrelevance permits replacing a K-like proof by its nullary constructor
1368/// only when their complete types, including every index, are convertible.
1369/// K-probe answers remembered for the rest of ONE normalization.
1370///
1371/// Full normalization walks the whole term on every step, so a single-case match whose
1372/// discriminant is a stuck proof is probed again on every step while other redexes are
1373/// contracted — Init's `WellFounded.Nat.fix_eq` spent almost all of its time re-deciding the
1374/// same failed probe. The probe proper ([`k_constructor_checked`]) is a pure function of the
1375/// proof and the context it is probed in. Each `normalize_progress` run has one root context and
1376/// the in-place walker extends it only through the λ/Π binders it descends; `Context::extend`
1377/// replaces a name's binding, so that context is the root plus, for every name bound on the
1378/// walker's path, that name's current type. The key records exactly those types (read from the
1379/// probed context itself) and the proof, by structural identity. A nested normalization (the
1380/// probe type-checks and converts) runs with its own memo, and the probe runs with none, so no
1381/// answer crosses a different root context. The cheap motive filter runs before any lookup.
1382struct KProbeMemo {
1383    /// Created on the first probe that passes the motive filter: most normalizations probe
1384    /// nothing, and must not pay for a store they never use.
1385    store: Option<crate::term_store::TermStore>,
1386    path: Vec<String>,
1387    answers: std::collections::HashMap<
1388        (
1389            Vec<(String, crate::term_store::TermId)>,
1390            crate::term_store::TermId,
1391        ),
1392        Option<Term>,
1393    >,
1394}
1395/// Memory bound for one normalization's remembered probes; beyond it the memo is dropped and
1396/// every further probe is computed afresh, exactly as without the memo.
1397const K_PROBE_MEMO_ENTRIES: usize = 256;
1398const K_PROBE_MEMO_NODES: usize = 1 << 16;
1399thread_local! {
1400    static K_PROBE_MEMO: std::cell::RefCell<Option<KProbeMemo>> = const { std::cell::RefCell::new(None) };
1401}
1402struct KProbeScope(Option<KProbeMemo>);
1403impl Drop for KProbeScope {
1404    fn drop(&mut self) {
1405        K_PROBE_MEMO.with(|slot| *slot.borrow_mut() = self.0.take());
1406    }
1407}
1408impl KProbeMemo {
1409    /// A fresh memo for this normalization; the enclosing one is restored on exit or unwind.
1410    fn install() -> KProbeScope {
1411        let fresh = KProbeMemo {
1412            store: None,
1413            path: Vec::new(),
1414            answers: std::collections::HashMap::new(),
1415        };
1416        KProbeScope(K_PROBE_MEMO.with(|slot| slot.borrow_mut().replace(fresh)))
1417    }
1418    /// Record that the walker descends under a binder named `param`.
1419    fn enter(param: &str) -> bool {
1420        K_PROBE_MEMO.with(|slot| match slot.borrow_mut().as_mut() {
1421            Some(memo) => {
1422                memo.path.push(param.to_owned());
1423                true
1424            }
1425            None => false,
1426        })
1427    }
1428    fn leave(pushed: bool) {
1429        if !pushed {
1430            return;
1431        }
1432        K_PROBE_MEMO.with(|slot| {
1433            if let Some(memo) = slot.borrow_mut().as_mut() {
1434                memo.path.pop();
1435            }
1436        });
1437    }
1438    fn probe(ctx: &Context, discriminant: &Term, motive: &Term) -> Option<Term> {
1439        if !k_motive_admits(ctx, motive) {
1440            return None;
1441        }
1442        let key = K_PROBE_MEMO.with(|slot| {
1443            let mut slot = slot.borrow_mut();
1444            let memo = slot.as_mut()?;
1445            let mut names = memo.path.clone();
1446            names.sort();
1447            names.dedup();
1448            let store = memo
1449                .store
1450                .get_or_insert_with(crate::term_store::TermStore::new);
1451            let mut locals = Vec::with_capacity(names.len());
1452            for name in names {
1453                // A path name is bound in the probed context by construction.
1454                let ty = ctx.get(&name)?;
1455                let id = store.intern(ty);
1456                locals.push((name, id));
1457            }
1458            let key = (locals, store.intern(discriminant));
1459            Some(match memo.answers.get(&key) {
1460                Some(answer) => Err(answer.clone()),
1461                None => Ok(key),
1462            })
1463        });
1464        let key = match key {
1465            Some(Err(answer)) => return answer,
1466            Some(Ok(key)) => Some(key),
1467            None => None,
1468        };
1469        // The probe type-checks and converts; it must neither see nor extend this memo.
1470        let suspended = K_PROBE_MEMO.with(|slot| slot.borrow_mut().take());
1471        let answer = k_constructor_checked(ctx, discriminant);
1472        K_PROBE_MEMO.with(|slot| *slot.borrow_mut() = suspended);
1473        if let Some(key) = key {
1474            K_PROBE_MEMO.with(|slot| {
1475                let mut slot = slot.borrow_mut();
1476                let Some(memo) = slot.as_mut() else {
1477                    return;
1478                };
1479                if memo.answers.len() >= K_PROBE_MEMO_ENTRIES
1480                    || memo
1481                        .store
1482                        .as_ref()
1483                        .is_some_and(|store| store.len() >= K_PROBE_MEMO_NODES)
1484                {
1485                    *slot = None;
1486                    return;
1487                }
1488                memo.answers.insert(key, answer.clone());
1489            });
1490        }
1491        answer
1492    }
1493}
1494
1495fn k_constructor_form(ctx: &Context, proof: &Term, motive: &Term) -> Option<Term> {
1496    if !k_motive_admits(ctx, motive) {
1497        return None;
1498    }
1499    k_constructor_checked(ctx, proof)
1500}
1501
1502/// The cheap negative filter: `false` only when the motive's visible major-premise type is an
1503/// inductive family with neither a K nor a unit constructor.
1504fn k_motive_admits(ctx: &Context, motive: &Term) -> bool {
1505    // Indexed motives abstract over indices before the major premise. Only
1506    // use the final domain when the lambda telescope visibly ends in a type;
1507    // an eta-short motive may still hide more binders in its final application.
1508    // This negative filter never establishes a reduction. Candidates still
1509    // undergo full proof inference, sort, constructor and index checks.
1510    let mut current = motive;
1511    let mut major_type = None;
1512    while let Term::Lambda {
1513        param_type, body, ..
1514    } = current
1515    {
1516        major_type = Some(param_type.as_ref());
1517        current = body;
1518    }
1519    let exposed = beta_iota_zeta_head(ctx, current, &mut 64);
1520    let terminal = exposed.as_ref().unwrap_or(current);
1521    let terminal_type = matches!(terminal, Term::Sort(_) | Term::Pi { .. })
1522        || matches!(declared_spine_type(ctx, terminal), Some(Term::Sort(_)));
1523    if let Some(ty) = major_type.filter(|_| terminal_type) {
1524        let mut head = ty;
1525        while let Term::App(f, _) = head {
1526            head = f;
1527        }
1528        if let Term::Global(name) | Term::Const { name, .. } = head {
1529            if ctx.is_inductive(name)
1530                && ctx.k_constructor(name).is_none()
1531                && ctx.unit_constructor(name).is_none()
1532            {
1533                return false;
1534            }
1535        }
1536    }
1537    true
1538}
1539
1540/// The K probe proper: infer the proof's type and check it against the constructor's. Its
1541/// answer depends only on `proof` and `ctx`.
1542fn k_constructor_checked(ctx: &Context, proof: &Term) -> Option<Term> {
1543    #[cfg(test)]
1544    K_PROBES.with(|count| count.set(count.get() + 1));
1545    let proof_type = crate::infer_type(ctx, proof).ok()?;
1546    let proof_type = normalize_checked(ctx, &proof_type).ok()?;
1547    let mut head = &proof_type;
1548    while let Term::App(f, _) = head {
1549        head = f;
1550    }
1551    let (inductive, levels) = match head {
1552        Term::Global(n) => (n.as_str(), None),
1553        Term::Const { name, levels } => (name.as_str(), Some(levels)),
1554        _ => return None,
1555    };
1556    let unit = ctx.unit_constructor(inductive);
1557    let constructor = ctx.k_constructor(inductive).or(unit)?;
1558    let sort = crate::type_checker::infer_sort(ctx, &proof_type).ok()?;
1559    if unit.is_none() && (sort == crate::Universe::SProp || !sort.equiv(&crate::Universe::Prop)) {
1560        return None;
1561    }
1562    let mut value = match levels {
1563        Some(levels) => Term::Const {
1564            name: constructor.into(),
1565            levels: levels.clone(),
1566        },
1567        None => Term::Global(constructor.into()),
1568    };
1569    for arg in spine_args(&proof_type)
1570        .into_iter()
1571        .take(ctx.inductive_num_params(inductive))
1572    {
1573        value = Term::App(Box::new(value), Box::new(arg));
1574    }
1575    let value_type = crate::infer_type(ctx, &value).ok()?;
1576    crate::type_checker::def_eq(ctx, &proof_type, &value_type).then_some(value)
1577}
1578
1579#[cfg(test)]
1580thread_local! {
1581    static K_PROBES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1582}
1583
1584/// What the reducer may do with a `Term::Const { name, levels }` reference.
1585///
1586/// ONE WELL-FORMEDNESS TEST, NOT TWO. Whether `name.{levels}` is a term of the calculus is
1587/// decided by [`crate::term::resolve_const_levels`], which is the same question `infer_type`
1588/// asks and the same one `recheck::const_body` asks — so a reference typing refuses can never
1589/// be a normal form to the reducer. The arm this replaces asked only HALF of it: it compared
1590/// `params.len()` against `levels.len()` itself, and only for a name in the
1591/// universe-polymorphic map. The consequence was live, and it is a typing/reduction divergence
1592/// of exactly the kind this codebase calls conformance defect 3: a declaration whose TYPE is
1593/// not level-CLOSED — a level variable outside its telescope — can never be instantiated, so
1594/// `infer_type` refuses every reference to it, while the reducer's arity test passed (`0 == 0`)
1595/// and it UNFOLDED THE BODY. `normalize` then made an ill-formed reference definitionally equal
1596/// to a well-typed term, which is laundering rather than mere disagreement.
1597///
1598/// [`ConstStep::Unresolved`] is the one case that stays inert, and the line is drawn where it is
1599/// on purpose. A reference that does not RESOLVE — no declaration at all, or a declaration with
1600/// no level telescope, which is reached as a `Term::Global` and never as a `Const` — is an
1601/// UNBOUND reference, and reduction has always left an unbound `Term::Global` alone: whether a
1602/// name is bound is the type checker's business. A reference that DOES resolve and is ill-formed
1603/// against the declaration it resolved to is a different fact, and it is the one that laundered.
1604enum ConstStep {
1605    /// The reference does not resolve — nothing is declared under the name, or what is declared
1606    /// has no level telescope and is reachable only as a `Term::Global`. Inert, exactly as an
1607    /// unbound `Term::Global` is inert.
1608    Unresolved,
1609    /// The reference is not a term of the calculus. `infer_type` refuses it, and so must the
1610    /// reducer's answer: see the `Term::Hole` note on the `Term::Const` arm.
1611    Illformed,
1612    /// Well formed, and the declaration has no body — an axiom, inductive or constructor is a
1613    /// VALUE, so there is no redex.
1614    Value,
1615    /// Well formed, with a body to unfold under this universe substitution.
1616    Delta(
1617        std::collections::HashMap<String, crate::term::Universe>,
1618        Term,
1619    ),
1620}
1621
1622#[cfg(test)]
1623thread_local! {
1624    // Actual type/body clone events at polymorphic delta resolution.
1625    static CONST_STEP_CLONES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1626}
1627
1628/// Resolve a `Const` reference against the environment — the reducer's own lookup, written
1629/// from the rule rather than shared, with the DECISION itself delegated to the one resolver.
1630fn const_step(ctx: &Context, name: &str, levels: &[crate::term::Universe]) -> ConstStep {
1631    // A `Const` is the UNIVERSE-POLYMORPHIC reference form. A declaration carries a telescope
1632    // either by declaring one (`universe_polys`) or by mentioning a level variable in its type;
1633    // a declaration with neither is reachable only as a `Global`.
1634    let (declared, ty, body) = match ctx.get_universe_poly(name) {
1635        Some((params, ty, body)) => {
1636            #[cfg(test)]
1637            CONST_STEP_CLONES.with(|count| count.set(count.get() + 2));
1638            (Some(params.clone()), ty.clone(), Some(body.clone()))
1639        }
1640        None => match ctx.get_global(name) {
1641            None => return ConstStep::Unresolved,
1642            Some(ty) if !crate::term::mentions_level_var(ty) => return ConstStep::Unresolved,
1643            Some(ty) => {
1644                let body = ctx.get_definition_body(name);
1645                #[cfg(test)]
1646                CONST_STEP_CLONES
1647                    .with(|count| count.set(count.get() + 1 + usize::from(body.is_some())));
1648                (None, ty.clone(), body.cloned())
1649            }
1650        },
1651    };
1652    match crate::term::resolve_const_levels(name, declared.as_deref(), &ty, levels) {
1653        Err(_) => ConstStep::Illformed,
1654        Ok(subst) => match body {
1655            Some(body) => ConstStep::Delta(subst, body),
1656            None => ConstStep::Value,
1657        },
1658    }
1659}
1660
1661// -------------------------------------------------------------------------
1662// The `@[simp]` registry, CONSULTED
1663// -------------------------------------------------------------------------
1664
1665/// The head symbol of an application spine — the `@[simp]` registry's DISPATCH KEY.
1666///
1667/// Written here rather than borrowed because the reducer must ask the question the registry
1668/// answered: `SimpRule::compile` keys a rule by its left-hand side's head, and a rewriter that
1669/// computed the head differently would look in the wrong bucket and silently never fire.
1670fn simp_dispatch_head(t: &Term) -> Option<&str> {
1671    let mut cur = t;
1672    while let Term::App(f, _) = cur {
1673        cur = f;
1674    }
1675    match cur {
1676        Term::Global(n) => Some(n.as_str()),
1677        Term::Const { name, .. } => Some(name.as_str()),
1678        _ => None,
1679    }
1680}
1681
1682/// Try to rewrite `term` at the TOP with a registered `@[simp]` rule.
1683///
1684/// **Why this is tried BEFORE δ and not after.** The obvious placement — "at every subterm
1685/// still stuck after β/δ/ι" — cannot work for the shape simp lemmas exist for. A rule's
1686/// left-hand side is headed by a DEFINED constant (`size n ⟶ n`), and δ unfolds that constant
1687/// on the very first step, so by the time a term is stuck the pattern is gone: `size (size n)`
1688/// becomes `plus (plus n 0) 0`, which no `size` rule can ever match again. Lean's `simp`
1689/// rewrites in preference to unfolding for precisely this reason, and so does this.
1690///
1691/// **What it costs when nobody registers anything**, which is every context the prelude
1692/// builds: one `is_empty` on a slice. The dispatch beyond that is one spine walk and one hash
1693/// lookup per node — never a linear scan of [`Context::simp_rules`], which is what the
1694/// head-keyed registry exists to prevent.
1695///
1696/// **Why it cannot loop.** `SimpRule::compile` refuses `lhs = lhs` and a bare-variable
1697/// left-hand side at the door, so no single rule rewrites a term to itself or matches
1698/// everywhere; [`progressed`] refuses a rewrite that did not change the term; and a CYCLE
1699/// between two rules is caught by [`normalize_checked_at`]'s Brent detection as
1700/// [`Unreduced::Cyclic`], which is the honest answer — such a term has no normal form.
1701///
1702/// **What it does NOT do.** Matching is first-order and syntactic, exactly as
1703/// [`crate::SimpRule::rewrite`] performs it — the rule and its matcher live together so a
1704/// rewriter cannot accept what `add_simp_lemma` refused. It never matches up to conversion:
1705/// a rule about `bulk` must not fire on a definitionally-equal `size` application, or one
1706/// registered lemma would rewrite every term in the environment.
1707/// **The SECOND kernel's door.** `recheck.rs::whnf` must apply the same rules or a proof that
1708/// leans on a rewrite is accepted by one kernel and refused by the other. The matching itself
1709/// is `SimpRule::rewrite`, which lives with the rule so the two rewriters cannot disagree about
1710/// what a registered lemma means; only the WALK is each kernel's own.
1711pub(crate) fn try_simp_rewrite(ctx: &Context, term: &Term) -> Option<Term> {
1712    if ctx.simp_rules().is_empty() {
1713        return None;
1714    }
1715    let head = simp_dispatch_head(term)?;
1716    ctx.simp_rules_for(head).find_map(|rule| {
1717        let rewritten = rule.rewrite(term)?;
1718        if captures_a_free_name(term, &rewritten) {
1719            return None;
1720        }
1721        progressed(term, rewritten)
1722    })
1723}
1724
1725/// Whether a rewrite would CAPTURE — turn a variable that was free in `term` into one bound by
1726/// a binder the rule's right-hand side brought with it.
1727///
1728/// **This is a real hazard and it is the price of wiring a rewriter into a NAMED-variable
1729/// kernel.** `SimpRule::rewrite` substitutes the matched terms into the rule's right-hand side
1730/// with a substitution that tracks SHADOWING of the pattern variables — which is the right check
1731/// for the pattern variable's own name and no check at all for the free names of what it was
1732/// bound to. So a lemma whose right-hand side BINDS a name, `∀x. g x = (λn. x)`, rewrites `g n`
1733/// in a scope holding a local `n` to `λn. n` — the identity where the lemma says the constant
1734/// function. That is a wrong ANSWER inside `normalize`, therefore inside `def_eq`, therefore
1735/// inside every `rfl`.
1736///
1737/// The rule that would fire is DECLINED rather than α-renamed, deliberately: renaming is the
1738/// matcher's job and belongs with the matcher (`SimpRule::rewrite`, which owns the substitution
1739/// and is the only place that can rename correctly). Declining is the conservative half — it can
1740/// only make the simplifier weaker, never wrong — and it costs nothing in practice, because a
1741/// right-hand side with no binder in it can never capture and that is almost every simp lemma.
1742fn captures_a_free_name(term: &Term, rewritten: &Term) -> bool {
1743    let mut free: Vec<&str> = Vec::new();
1744    collect_free_names(term, &mut Vec::new(), &mut free);
1745    if free.is_empty() {
1746        return false;
1747    }
1748    binds_any_of(rewritten, &free)
1749}
1750
1751/// The FREE variable names of `t`, first-occurrence order, duplicates removed.
1752fn collect_free_names<'a>(t: &'a Term, bound: &mut Vec<&'a str>, out: &mut Vec<&'a str>) {
1753    match t {
1754        Term::Var(n) => {
1755            if !bound.iter().any(|b| *b == n.as_str()) && !out.iter().any(|o| *o == n.as_str()) {
1756                out.push(n.as_str());
1757            }
1758        }
1759        Term::Sort(_) | Term::Global(_) | Term::Const { .. } | Term::Lit(_) | Term::Hole => {}
1760        Term::App(f, a) => {
1761            collect_free_names(f, bound, out);
1762            collect_free_names(a, bound, out);
1763        }
1764        Term::Pi {
1765            param,
1766            param_type,
1767            body_type,
1768        } => {
1769            collect_free_names(param_type, bound, out);
1770            bound.push(param.as_str());
1771            collect_free_names(body_type, bound, out);
1772            bound.pop();
1773        }
1774        Term::Lambda {
1775            param,
1776            param_type,
1777            body,
1778        } => {
1779            collect_free_names(param_type, bound, out);
1780            bound.push(param.as_str());
1781            collect_free_names(body, bound, out);
1782            bound.pop();
1783        }
1784        Term::Let {
1785            name,
1786            ty,
1787            value,
1788            body,
1789        } => {
1790            collect_free_names(ty, bound, out);
1791            collect_free_names(value, bound, out);
1792            bound.push(name.as_str());
1793            collect_free_names(body, bound, out);
1794            bound.pop();
1795        }
1796        Term::Fix { name, body } => {
1797            bound.push(name.as_str());
1798            collect_free_names(body, bound, out);
1799            bound.pop();
1800        }
1801        Term::MutualFix { defs, .. } => {
1802            for (n, _) in defs {
1803                bound.push(n.as_str());
1804            }
1805            for (_, b) in defs {
1806                collect_free_names(b, bound, out);
1807            }
1808            for _ in defs {
1809                bound.pop();
1810            }
1811        }
1812        Term::Match {
1813            discriminant,
1814            motive,
1815            cases,
1816        } => {
1817            collect_free_names(discriminant, bound, out);
1818            collect_free_names(motive, bound, out);
1819            for c in cases {
1820                collect_free_names(c, bound, out);
1821            }
1822        }
1823        Term::Annotated { term, .. } => collect_free_names(term, bound, out),
1824    }
1825}
1826
1827/// Whether `t` binds any of `names` anywhere inside it.
1828fn binds_any_of(t: &Term, names: &[&str]) -> bool {
1829    let binds = |n: &String| names.iter().any(|x| *x == n.as_str());
1830    match t {
1831        Term::Sort(_)
1832        | Term::Var(_)
1833        | Term::Global(_)
1834        | Term::Const { .. }
1835        | Term::Lit(_)
1836        | Term::Hole => false,
1837        Term::App(f, a) => binds_any_of(f, names) || binds_any_of(a, names),
1838        Term::Pi {
1839            param,
1840            param_type,
1841            body_type,
1842        } => binds(param) || binds_any_of(param_type, names) || binds_any_of(body_type, names),
1843        Term::Lambda {
1844            param,
1845            param_type,
1846            body,
1847        } => binds(param) || binds_any_of(param_type, names) || binds_any_of(body, names),
1848        Term::Let {
1849            name,
1850            ty,
1851            value,
1852            body,
1853        } => {
1854            binds(name)
1855                || binds_any_of(ty, names)
1856                || binds_any_of(value, names)
1857                || binds_any_of(body, names)
1858        }
1859        Term::Fix { name, body } => binds(name) || binds_any_of(body, names),
1860        Term::MutualFix { defs, .. } => {
1861            defs.iter().any(|(n, b)| binds(n) || binds_any_of(b, names))
1862        }
1863        Term::Match {
1864            discriminant,
1865            motive,
1866            cases,
1867        } => {
1868            binds_any_of(discriminant, names)
1869                || binds_any_of(motive, names)
1870                || cases.iter().any(|c| binds_any_of(c, names))
1871        }
1872        Term::Annotated { term, .. } => binds_any_of(term, names),
1873    }
1874}
1875
1876/// Check if a term is a constructor (possibly applied to arguments).
1877fn is_constructor_form(ctx: &Context, term: &Term) -> bool {
1878    // Integer literals retain their existing canonical-signature bridge. All
1879    // other forms use borrowed metadata and never construct discarded fields.
1880    if matches!(term, Term::Lit(Literal::Int(_) | Literal::BigInt(_))) {
1881        return extract_constructor(ctx, term).is_some();
1882    }
1883    constructor_view(ctx, term).is_some()
1884}
1885
1886/// Which entry of a `Match`'s case list belongs to the discriminant's constructor.
1887///
1888/// Usually that is the constructor's own position in its inductive's registration order. But an
1889/// INDEXED family's match may be PRUNED — a constructor whose declared result index cannot equal
1890/// the scrutinee's owes no branch (SPEC F, `type_checker::constructors_the_indices_allow`) — and
1891/// then the case list is SHORTER than the constructor list: the second of two constructors is the
1892/// FIRST of a one-case list. A `Term::Match` does not record which constructors its cases stand
1893/// for, so the mapping is recomputed here, from the scrutinee's own indices.
1894///
1895/// This is where the ι-rule would otherwise go quietly wrong rather than merely get stuck:
1896/// indexing a pruned list by the full position applies the WRONG branch to the right arguments.
1897/// `None` means "cannot be determined" and no reduction happens — sound, and the type checker
1898/// will have refused any match this cannot resolve.
1899fn case_position(
1900    ctx: &Context,
1901    discriminant: &Term,
1902    ctor_index: usize,
1903    num_cases: usize,
1904) -> Option<usize> {
1905    // The overwhelming case: a full case list indexes directly.
1906    let ind = constructor_inductive_of(ctx, discriminant)?;
1907    let ctors = ctx.get_constructors(&ind);
1908    if num_cases == ctors.len() {
1909        return Some(ctor_index);
1910    }
1911    // A pruned list. Recover the scrutinee's indices from the constructor's declared result type
1912    // with its ACTUAL arguments substituted, then ask which constructors those indices allow.
1913    let num_params = ctx.inductive_num_params(&ind);
1914    let (_, ctor_type) = *ctors.get(ctor_index)?;
1915    let actual = spine_args(discriminant);
1916    let mut binders: Vec<String> = Vec::new();
1917    let mut cur = ctor_type;
1918    while let Term::Pi {
1919        param, body_type, ..
1920    } = cur
1921    {
1922        binders.push(param.clone());
1923        cur = body_type;
1924    }
1925    let mut result = cur.clone();
1926    for (binder, value) in binders.iter().zip(actual.iter()) {
1927        result = substitute(&result, binder, value);
1928    }
1929    let result_args = spine_args(&result);
1930    let allowed =
1931        crate::type_checker::constructors_the_indices_allow(ctx, &ind, num_params, &result_args);
1932    if allowed.len() != num_cases {
1933        return None;
1934    }
1935    allowed.iter().position(|&i| i == ctor_index)
1936}
1937
1938/// The inductive a constructor-headed term belongs to, bridging a `Nat` literal to `Nat`.
1939fn constructor_inductive_of(ctx: &Context, t: &Term) -> Option<String> {
1940    if crate::int_inductive::literal_constructor(ctx, t).is_some() {
1941        return Some("Int".to_string());
1942    }
1943    if matches!(t, Term::Lit(Literal::Nat(_))) {
1944        return Some("Nat".to_string());
1945    }
1946    let mut head = t;
1947    while let Term::App(f, _) = head {
1948        head = f;
1949    }
1950    match head {
1951        Term::Global(n) | Term::Const { name: n, .. } => {
1952            ctx.constructor_inductive(n).map(|s| s.to_string())
1953        }
1954        _ => None,
1955    }
1956}
1957
1958/// An application spine's arguments, in source order.
1959fn spine_args(t: &Term) -> Vec<Term> {
1960    let mut args = Vec::new();
1961    let mut cur = t;
1962    while let Term::App(f, a) = cur {
1963        args.push((**a).clone());
1964        cur = f;
1965    }
1966    args.reverse();
1967    args
1968}
1969
1970/// Extract constructor index and VALUE arguments from a term (skipping type arguments).
1971///
1972/// Returns `Some((constructor_index, [value_arg1, value_arg2, ...]))` if term is `Cᵢ(type_args..., value_args...)`
1973/// where `Cᵢ` is the i-th constructor of some inductive type.
1974///
1975/// For polymorphic constructors like `Cons A h t`, this returns only [h, t], not [A, h, t].
1976/// Borrowed constructor metadata. Field materialization belongs to eliminators,
1977/// not to the boolean recognition performed while looking for a fixpoint redex.
1978enum ConstructorView<'a> {
1979    Named {
1980        index: usize,
1981        parameters: usize,
1982        term: &'a Term,
1983    },
1984    Natural {
1985        index: usize,
1986        value: &'a logicaffeine_base::BigInt,
1987    },
1988}
1989fn constructor_view<'a>(ctx: &Context, term: &'a Term) -> Option<ConstructorView<'a>> {
1990    if let Term::Lit(Literal::Nat(value)) = term {
1991        if !crate::int_inductive::reads_nat_literal(ctx, value) {
1992            return None;
1993        }
1994        let constructor = if *value <= logicaffeine_base::BigInt::from_i64(0) {
1995            "Zero"
1996        } else {
1997            "Succ"
1998        };
1999        let index = ctx
2000            .constructor_headers("Nat")
2001            .position(|(name, _)| name == constructor)?;
2002        return Some(ConstructorView::Natural { index, value });
2003    }
2004    let mut head = term;
2005    while let Term::App(f, _) = head {
2006        head = f;
2007    }
2008    let (Term::Global(name) | Term::Const { name, .. }) = head else {
2009        return None;
2010    };
2011    let owner = ctx.constructor_inductive(name)?;
2012    let (index, (_, ty)) = ctx
2013        .constructor_headers(owner)
2014        .enumerate()
2015        .find(|(_, (candidate, _))| *candidate == name)?;
2016    let parameters = ctx
2017        .inductive_declared_params(owner)
2018        .unwrap_or_else(|| count_type_params(ty));
2019    Some(ConstructorView::Named {
2020        index,
2021        parameters,
2022        term,
2023    })
2024}
2025/// `term` as an explicit constructor application: itself when its head is a constructor, and one
2026/// constructor layer of a numeral (`Zero`, `Succ n`, `Int_ofNat n`, `Int_negSucc n`).
2027pub(crate) fn constructor_form(ctx: &Context, term: &Term) -> Option<Term> {
2028    if let Some(layer) = crate::int_inductive::literal_constructor(ctx, term) {
2029        return Some(layer);
2030    }
2031    match constructor_view(ctx, term)? {
2032        ConstructorView::Natural { value, .. }
2033            if *value <= logicaffeine_base::BigInt::from_i64(0) =>
2034        {
2035            Some(Term::Global("Zero".to_string()))
2036        }
2037        ConstructorView::Natural { value, .. } => Some(Term::App(
2038            Box::new(Term::Global("Succ".to_string())),
2039            Box::new(Term::Lit(Literal::Nat(
2040                value.sub(&logicaffeine_base::BigInt::from_i64(1)),
2041            ))),
2042        )),
2043        ConstructorView::Named { .. } => Some(term.clone()),
2044    }
2045}
2046
2047fn extract_constructor(ctx: &Context, term: &Term) -> Option<(usize, Vec<Term>)> {
2048    #[cfg(test)]
2049    CONSTRUCTOR_MATERIALIZATIONS.with(|n| n.set(n.get() + 1));
2050    if let Some(constructor) = crate::int_inductive::literal_constructor(ctx, term) {
2051        return extract_constructor(ctx, &constructor);
2052    }
2053    match constructor_view(ctx, term)? {
2054        ConstructorView::Natural { index, value } => {
2055            let fields = if *value <= logicaffeine_base::BigInt::from_i64(0) {
2056                Vec::new()
2057            } else {
2058                vec![Term::Lit(Literal::Nat(
2059                    value.sub(&logicaffeine_base::BigInt::from_i64(1)),
2060                ))]
2061            };
2062            Some((index, fields))
2063        }
2064        ConstructorView::Named {
2065            index,
2066            parameters,
2067            term,
2068        } => {
2069            let (_, args) = app_spine(term);
2070            Some((index, args.into_iter().skip(parameters).cloned().collect()))
2071        }
2072    }
2073}
2074
2075/// Count leading type parameters in a constructor type.
2076///
2077/// Type parameters are Pis where the param_type is a Sort (Type n or Prop).
2078/// For `Π(A:Type). Π(_:A). Π(_:List A). List A`, this returns 1.
2079fn count_type_params(ty: &Term) -> usize {
2080    let mut count = 0;
2081    let mut current = ty;
2082
2083    while let Term::Pi {
2084        param_type,
2085        body_type,
2086        ..
2087    } = current
2088    {
2089        if is_sort(param_type) {
2090            count += 1;
2091            current = body_type;
2092        } else {
2093            break;
2094        }
2095    }
2096
2097    count
2098}
2099
2100/// Check if a term is a Sort (Type n or Prop).
2101fn is_sort(term: &Term) -> bool {
2102    matches!(term, Term::Sort(_))
2103}
2104
2105/// The head and argument spine of an application, by reference (`f a b c` → `(f, [a,b,c])`).
2106fn app_spine(t: &Term) -> (&Term, Vec<&Term>) {
2107    let mut args = Vec::new();
2108    let mut cur = t;
2109    while let Term::App(f, a) = cur {
2110        args.push(a.as_ref());
2111        cur = f.as_ref();
2112    }
2113    args.reverse();
2114    (cur, args)
2115}
2116
2117/// The certified observational equality's computation rules (`observational::reduce`), offered
2118/// the application `func arg`.
2119fn try_obs_reduce(ctx: &Context, func: &Term, arg: &Term) -> Option<Term> {
2120    ctx.observational.as_ref()?;
2121    let (head, mut args) = app_spine(func);
2122    args.push(arg);
2123    crate::observational::reduce(ctx, head, &args)
2124}
2125
2126/// Quotient elimination applies the function to a constructed representative.
2127/// Legacy lift spines have a respect proof; certified polymorphic induction
2128/// has a Prop-valued motive and one fewer argument. Imported identities come
2129/// from checked certificates, and representative universes must agree.
2130fn try_quot_lift_reduce(ctx: &Context, func: &Term, arg: &Term) -> Option<Term> {
2131    let (fh, fargs) = app_spine(func);
2132    let (arity, universe) = match fh {
2133        Term::Global(n) => {
2134            let arity = match crate::quotient::prelude_kind(ctx, n)? {
2135                crate::quotient::PreludeKind::Lift => 5,
2136                crate::quotient::PreludeKind::Induction => 4,
2137                _ => return None,
2138            };
2139            (arity, None)
2140        }
2141        Term::Const { name, levels } => {
2142            let arity = match crate::quotient::kind(ctx, name, levels)? {
2143                crate::quotient::Kind::Lift => 5,
2144                crate::quotient::Kind::Induction => 4,
2145                _ => return None,
2146            };
2147            (arity, Some(&levels[0]))
2148        }
2149        _ => return None,
2150    };
2151    if fargs.len() != arity {
2152        return None;
2153    }
2154    let (qh, qargs) = app_spine(arg);
2155    let constructor = match (qh, universe) {
2156        (Term::Global(n), None) => {
2157            crate::quotient::prelude_kind(ctx, n) == Some(crate::quotient::PreludeKind::Constructor)
2158        }
2159        (Term::Const { name, levels }, Some(u)) => {
2160            crate::quotient::kind(ctx, name, levels) == Some(crate::quotient::Kind::Constructor)
2161                && levels[0].equiv(u)
2162        }
2163        _ => false,
2164    };
2165    if !constructor || qargs.len() != 3 {
2166        return None;
2167    }
2168    Some(Term::App(
2169        Box::new(fargs[3].clone()),
2170        Box::new(qargs[2].clone()),
2171    ))
2172}
2173
2174/// ι FOR A FIXPOINT, at the column the TERMINATION GUARD admitted it on.
2175///
2176/// The specification is [`crate::termination::structural_columns`]'s, quoted there in full:
2177///
2178/// > `(fix f. λx₀ … λxₙ. e) a₀ … aₙ` unrolls exactly when the argument at the STRUCTURAL
2179/// > position — `structural_columns(ctx, body)[0]` — is in constructor form.
2180///
2181/// The arm this stands beside asks the question of whatever argument the INNERMOST `App`
2182/// happens to carry, which is always `a₀`. That is a strictly smaller rule, and the definition
2183/// it leaves stuck is the commonest one there is: `Nat.add` recurses on its SECOND argument
2184/// (`fix f. λm. λn. match n with …`), so the guard admits it with the structural column at
2185/// position 1 and the reducer never unrolled it for a non-constructor `m`. `n + 0 = n` is
2186/// `rfl` in Lean and was not `rfl` here — and `normalize` handed back a term still holding a
2187/// δι-redex, which is the shape a conversion check cannot see past.
2188///
2189/// WHICH COLUMN is the guard's own answer and is asked of the guard, never guessed: a reducer
2190/// that picked the column itself would compute a function the guard never checked. WHAT TO DO
2191/// with the answer is this kernel's own code, and `recheck.rs` implements the same
2192/// specification independently over de Bruijn levels.
2193///
2194/// Both halves are needed for `double_check` to mean anything here, and neither may be a copy
2195/// of the other: today BOTH kernels are argument-0-only, so they agree by being wrong in the
2196/// same way and the second kernel cannot see it.
2197fn try_fix_unroll(ctx: &Context, term: &Term) -> Option<Term> {
2198    let (head, args) = app_spine(term);
2199    let Term::Fix { name, body } = head else {
2200        return None;
2201    };
2202    // The guard's analysis walks the body, so it is asked only once something could possibly
2203    // unroll. No argument in constructor form means no column can be satisfied, whichever one
2204    // the guard names — and that is the shape every STUCK application has, which is the shape
2205    // reduction spends most of its steps on.
2206    if !args.iter().any(|a| is_constructor_form(ctx, a)) {
2207        return None;
2208    }
2209    // An empty column list means the guard would REFUSE this body: there is no structural
2210    // position, so there is no ι rule and the fixpoint is a value.
2211    let column = *crate::termination::structural_columns(ctx, body).first()?;
2212    if !is_constructor_form(ctx, args.get(column)?) {
2213        return None;
2214    }
2215    let unfolded = substitute(body, name, head);
2216    Some(args.iter().fold(unfolded, |f, a| {
2217        Term::App(Box::new(f), Box::new((*a).clone()))
2218    }))
2219}
2220
2221// -------------------------------------------------------------------------
2222// Primitive computation rules
2223// -------------------------------------------------------------------------
2224
2225/// Lean 4's `Int.ediv` / `Int.emod` — the EUCLIDEAN convention, and TOTAL.
2226///
2227/// THE SPECIFICATION. Every engine that folds `div`/`mod` on literals implements THIS, each
2228/// from the text, never by copying another engine's code — `reduction::try_primitive_reduce`
2229/// (here), `recheck::try_builtin` (the second kernel), `eval::prim_arith` (the `native_decide`
2230/// evaluator) and `simp::try_arithmetic` (the constant folder that certifies `simp` goals):
2231///
2232/// ```text
2233///   b ≠ 0  ⟹  a = b·q + r   ∧   0 ≤ r < |b|      (the unique such pair)
2234///   b = 0  ⟹  q = 0  ∧  r = a                     (`a = 0·0 + a`, so the identity survives)
2235/// ```
2236///
2237/// Rust's `/` and `%` are TRUNCATED — the quotient rounds toward zero and the remainder
2238/// carries the DIVIDEND's sign — so they agree with the spec above on every non-negative
2239/// dividend and disagree on every negative one. That is exactly why a truncating
2240/// implementation survives casual testing and then answers `(-7) / 2 = -3` where Lean answers
2241/// `-4`: a silent wrong answer, the worst outcome there is.
2242///
2243/// This derivation corrects the truncated pair by one; `eval.rs` derives the same pair a
2244/// different way (recovering `q` by exact division once `r` is known), so a slip in one
2245/// derivation cannot hide in the other.
2246fn ediv_emod_i64(a: i64, b: i64) -> Option<(i64, i64)> {
2247    if b == 0 {
2248        return Some((0, a));
2249    }
2250    // `None` only for `i64::MIN / -1`, which overflows the machine quotient; the caller
2251    // promotes to the exact path rather than wrapping.
2252    let q = a.checked_div(b)?;
2253    let r = a.checked_rem(b)?;
2254    if r >= 0 {
2255        return Some((q, r));
2256    }
2257    if b > 0 {
2258        Some((q.checked_sub(1)?, r.checked_add(b)?))
2259    } else {
2260        Some((q.checked_add(1)?, r.checked_sub(b)?))
2261    }
2262}
2263
2264/// The arbitrary-precision half of the same specification. Total in the same way, so the wide
2265/// path and the narrow path answer identically on every value both can represent.
2266fn ediv_emod_big(
2267    a: &logicaffeine_base::BigInt,
2268    b: &logicaffeine_base::BigInt,
2269) -> (logicaffeine_base::BigInt, logicaffeine_base::BigInt) {
2270    use logicaffeine_base::BigInt;
2271    let Some((q, r)) = a.div_rem(b) else {
2272        return (BigInt::from_i64(0), a.clone());
2273    };
2274    if !r.is_negative() {
2275        return (q, r);
2276    }
2277    let one = BigInt::from_i64(1);
2278    if !b.is_negative() {
2279        (q.sub(&one), r.add(b))
2280    } else {
2281        (q.add(&one), r.sub(b))
2282    }
2283}
2284
2285fn bool_term(b: bool) -> Term {
2286    Term::Global(if b { "true" } else { "false" }.to_string())
2287}
2288
2289/// The `Int` computation rules: arithmetic on a machine fast path that PROMOTES on overflow,
2290/// and order decided directly. `None` means "no rule for this name at these literal kinds",
2291/// which is how a `Nat`, `Text` or `Float` operand keeps the term stuck instead of being
2292/// silently read as an integer.
2293fn int_binary(op: &str, xl: &Literal, yl: &Literal) -> Option<Term> {
2294    // FAST PATH: both operands fit `i64`. Only an OVERFLOWING arithmetic op falls through —
2295    // to be redone exactly in BigInt below.
2296    if let (Literal::Int(a), Literal::Int(b)) = (xl, yl) {
2297        let fast = match op {
2298            "add" => a.checked_add(*b),
2299            "sub" => a.checked_sub(*b),
2300            "mul" => a.checked_mul(*b),
2301            "div" => ediv_emod_i64(*a, *b).map(|(q, _)| q),
2302            "mod" => ediv_emod_i64(*a, *b).map(|(_, r)| r),
2303            _ => None,
2304        };
2305        if let Some(r) = fast {
2306            return Some(Term::Lit(Literal::Int(r)));
2307        }
2308        // Bool-valued comparison primitives: ground order decided by computation, so
2309        // `Eq Bool (le m n) true` holds by `refl` exactly when `m ≤ n` — the sound
2310        // substrate for linear-arithmetic certificates.
2311        let fast_bool = match op {
2312            "le" => Some(a <= b),
2313            "lt" => Some(a < b),
2314            "ge" => Some(a >= b),
2315            "gt" => Some(a > b),
2316            _ => None,
2317        };
2318        if let Some(bl) = fast_bool {
2319            return Some(bool_term(bl));
2320        }
2321    }
2322
2323    // EXACT PATH (K6): arbitrary-precision integer arithmetic, reached when an operand is a
2324    // `BigInt` or an `i64` op overflowed. Results are canonicalised by `int_lit` (demote to
2325    // `Int` when they fit), so a value has ONE literal and definitional equality of literals
2326    // stays sound.
2327    let (Some(xb), Some(yb)) = (lit_bigint(xl), lit_bigint(yl)) else {
2328        return None;
2329    };
2330    let big = match op {
2331        "add" => Some(xb.add(&yb)),
2332        "sub" => Some(xb.sub(&yb)),
2333        "mul" => Some(xb.mul(&yb)),
2334        "div" => Some(ediv_emod_big(&xb, &yb).0),
2335        "mod" => Some(ediv_emod_big(&xb, &yb).1),
2336        _ => None,
2337    };
2338    if let Some(r) = big {
2339        return Some(Term::Lit(int_lit(r)));
2340    }
2341    match op {
2342        "le" => Some(bool_term(xb <= yb)),
2343        "lt" => Some(bool_term(xb < yb)),
2344        "ge" => Some(bool_term(xb >= yb)),
2345        "gt" => Some(bool_term(xb > yb)),
2346        _ => None,
2347    }
2348}
2349
2350/// The `Text` computation rules. Lean's `String` operations are recursions over
2351/// `String.data`; `Text` is an opaque carrier, so they are primitive here — but they must
2352/// COMPUTE, or `example : "ab" ++ "cd" = "abcd" := rfl` has no LOGOS form at all and an
2353/// axiomatised `Text_append` makes the equation FALSE rather than unproved.
2354///
2355/// `Text_length` counts CHARACTERS, as Lean's `String.length` does — not bytes.
2356fn text_binary(op: &str, xl: &Literal, yl: &Literal) -> Option<Term> {
2357    let (Literal::Text(a), Literal::Text(b)) = (xl, yl) else {
2358        return None;
2359    };
2360    match op {
2361        "Text_append" => Some(Term::Lit(Literal::Text(format!("{a}{b}")))),
2362        "Text_beq" => Some(bool_term(a == b)),
2363        "Text_isPrefixOf" => Some(bool_term(b.starts_with(a.as_str()))),
2364        _ => None,
2365    }
2366}
2367
2368/// Every binary computation rule, keyed by name and by the literal kinds it accepts. A new
2369/// primitive type is a new ROW here, not another arm grafted onto the `Int` dispatch — which
2370/// is what kept every `Text` operation unstatable.
2371fn binary_prim(op: &str, xl: &Literal, yl: &Literal) -> Option<Term> {
2372    int_binary(op, xl, yl).or_else(|| text_binary(op, xl, yl))
2373}
2374
2375/// Every UNARY computation rule, same shape.
2376fn unary_prim(op: &str, xl: &Literal) -> Option<Term> {
2377    match (op, xl) {
2378        ("Text_length", Literal::Text(s)) => Some(Term::Lit(Literal::Nat(
2379            logicaffeine_base::BigInt::from_u64(s.chars().count() as u64),
2380        ))),
2381        _ => None,
2382    }
2383}
2384
2385// -------------------------------------------------------------------------
2386// The accelerated `Nat` order — Lean's GMP `Nat.ble`/`Nat.blt`, with a check Lean does not do
2387// -------------------------------------------------------------------------
2388
2389/// THE SPECIFICATION the acceleration stands in for, written as a program because that is what
2390/// it is checked against:
2391///
2392/// ```text
2393///   natLe : Nat → Nat → Bool
2394///   natLe := fix f. λm. λn. match m { Zero   => true
2395///                                   | Succ m✧ => match n { Zero   => false
2396///                                                        | Succ n✧ => f m✧ n✧ } }
2397///   natLt : Nat → Nat → Bool
2398///   natLt := λm. λn. natLe (Succ m) n
2399/// ```
2400///
2401/// A `Literal::Nat(k)` enters that recursion through the Peano bridge in
2402/// [`extract_constructor`], which peels ONE `Succ` per unit — so deciding `m ≤ n` costs
2403/// `min(m, n)` whole-term reduction steps. `Char`'s validity bound is `< 0x110000`, which is
2404/// 1 114 112 steps against a 2^20 budget: the verdict is not slow, it is UNREACHABLE, and the
2405/// bound gets refused for want of arithmetic rather than for being false.
2406///
2407/// Lean solves this by overriding `Nat.ble`/`Nat.blt` in the kernel with GMP, keyed on the
2408/// constant's NAME and trusted to match the reference definition. **We do the same thing and
2409/// check it.** The override below fires only when the constant is bound to exactly the program
2410/// above — same skeleton, same case order, same recursive call, same declared type — so the
2411/// fast answer IS the slow answer by construction, and a context that rebinds `natLe` silently
2412/// loses the acceleration instead of silently getting the wrong value. That is a strictly
2413/// smaller act of trust than Lean's, for one small structural comparison per fired redex.
2414///
2415/// The clamp is the boundary a fast path gets wrong: the Peano bridge sends a NEGATIVE
2416/// `Literal::Nat` to `Zero` (a well-formed `Nat` is never negative, but the kernel can be
2417/// HANDED one), so the literal comparison has to clamp the same way or the two spellings of one
2418/// reduction disagree.
2419fn nat_order_value(op: &str, xl: &Literal, yl: &Literal) -> Option<bool> {
2420    let (Literal::Nat(a), Literal::Nat(b)) = (xl, yl) else {
2421        return None;
2422    };
2423    let zero = logicaffeine_base::BigInt::from_i64(0);
2424    let a = if a.is_negative() { &zero } else { a };
2425    let b = if b.is_negative() { &zero } else { b };
2426    match op {
2427        "natLe" => Some(a <= b),
2428        "natLt" => Some(a < b),
2429        _ => None,
2430    }
2431}
2432
2433fn is_var_named(t: &Term, name: &str) -> bool {
2434    matches!(t, Term::Var(n) if n == name)
2435}
2436
2437fn is_global_named(t: &Term, name: &str) -> bool {
2438    matches!(t, Term::Global(n) if n == name)
2439}
2440
2441/// `Nat → Nat → Bool`, whatever the binders are called. Checked as well as the body, because a
2442/// program with the right shape at the wrong type is a different function.
2443fn is_nat_nat_bool(ty: &Term) -> bool {
2444    let Term::Pi {
2445        param_type: first,
2446        body_type: rest,
2447        ..
2448    } = ty
2449    else {
2450        return false;
2451    };
2452    let Term::Pi {
2453        param_type: second,
2454        body_type: result,
2455        ..
2456    } = rest.as_ref()
2457    else {
2458        return false;
2459    };
2460    is_global_named(first, "Nat")
2461        && is_global_named(second, "Nat")
2462        && is_global_named(result, "Bool")
2463}
2464
2465/// Whether `body` is the `natLe` program in the specification above, up to the names of its
2466/// binders. The five binders must be pairwise DISTINCT: with shadowing, a term of this shape
2467/// can compute something else entirely, and a matcher that read the shape without the scoping
2468/// would accept it.
2469fn is_min_recursion_order(body: &Term) -> bool {
2470    let Term::Fix { name: f, body: abs } = body else {
2471        return false;
2472    };
2473    let Term::Lambda {
2474        param: m,
2475        body: abs_n,
2476        ..
2477    } = abs.as_ref()
2478    else {
2479        return false;
2480    };
2481    let Term::Lambda {
2482        param: n,
2483        body: outer,
2484        ..
2485    } = abs_n.as_ref()
2486    else {
2487        return false;
2488    };
2489    let Term::Match {
2490        discriminant: on_m,
2491        cases: m_cases,
2492        ..
2493    } = outer.as_ref()
2494    else {
2495        return false;
2496    };
2497    if m_cases.len() != 2 || !is_var_named(on_m, m) || !is_global_named(&m_cases[0], "true") {
2498        return false;
2499    }
2500    let Term::Lambda {
2501        param: m_pred,
2502        body: inner,
2503        ..
2504    } = &m_cases[1]
2505    else {
2506        return false;
2507    };
2508    let Term::Match {
2509        discriminant: on_n,
2510        cases: n_cases,
2511        ..
2512    } = inner.as_ref()
2513    else {
2514        return false;
2515    };
2516    if n_cases.len() != 2 || !is_var_named(on_n, n) || !is_global_named(&n_cases[0], "false") {
2517        return false;
2518    }
2519    let Term::Lambda {
2520        param: n_pred,
2521        body: call,
2522        ..
2523    } = &n_cases[1]
2524    else {
2525        return false;
2526    };
2527    let Term::App(partial, second) = call.as_ref() else {
2528        return false;
2529    };
2530    let Term::App(head, first) = partial.as_ref() else {
2531        return false;
2532    };
2533    let names = [f, m, n, m_pred, n_pred];
2534    let distinct = names
2535        .iter()
2536        .enumerate()
2537        .all(|(i, a)| names[i + 1..].iter().all(|b| a != b));
2538    distinct && is_var_named(head, f) && is_var_named(first, m_pred) && is_var_named(second, n_pred)
2539}
2540
2541/// Whether `body` is `λm. λn. <le> (Succ m) n` — the `natLt` program, which is only the right
2542/// function if `<le>` is itself the accelerated order.
2543fn is_successor_shifted_order(body: &Term, le: &str) -> bool {
2544    let Term::Lambda {
2545        param: m,
2546        body: abs_n,
2547        ..
2548    } = body
2549    else {
2550        return false;
2551    };
2552    let Term::Lambda {
2553        param: n,
2554        body: call,
2555        ..
2556    } = abs_n.as_ref()
2557    else {
2558        return false;
2559    };
2560    let Term::App(partial, second) = call.as_ref() else {
2561        return false;
2562    };
2563    let Term::App(head, first) = partial.as_ref() else {
2564        return false;
2565    };
2566    let Term::App(succ, shifted) = first.as_ref() else {
2567        return false;
2568    };
2569    m != n
2570        && is_global_named(head, le)
2571        && is_global_named(succ, "Succ")
2572        && is_var_named(shifted, m)
2573        && is_var_named(second, n)
2574}
2575
2576/// Whether `natLe` in this context IS the program the acceleration computes.
2577fn accelerates_nat_le(ctx: &Context) -> bool {
2578    ctx.get_global("natLe").is_some_and(is_nat_nat_bool)
2579        && ctx
2580            .get_definition_body("natLe")
2581            .is_some_and(is_min_recursion_order)
2582}
2583
2584/// The shortcut reads compact Nat literals as Zero/Succ and returns a constructor
2585/// named true/false. Those are semantic dependencies, even when both order bodies
2586/// are unchanged: a checked alias true : Bool := false must evaluate to false,
2587/// and a legacy mutation of Nat's positional inventory must use the actual body.
2588fn has_nat_order_carriers(ctx: &Context) -> bool {
2589    if !crate::int_inductive::canonical_nat_environment(ctx)
2590        || !ctx.is_inductive("Bool")
2591        || ctx.get_global("Bool") != Some(&Term::Sort(crate::term::Universe::Type(0)))
2592        || ctx.inductive_num_params("Bool") != 0
2593        || ctx.poly_declaration("Bool").is_some()
2594        || ctx.get_definition_body("Bool").is_some()
2595        || ctx.get_constructors("Bool").len() != 2
2596    {
2597        return false;
2598    }
2599    ["false", "true"].into_iter().all(|name| {
2600        ctx.constructor_inductive(name) == Some("Bool")
2601            && ctx.get_global(name) == Some(&Term::Global("Bool".into()))
2602            && ctx.poly_declaration(name).is_none()
2603            && ctx.get_definition_body(name).is_none()
2604    })
2605}
2606
2607/// Whether op may be decided on two Nat literals in this context: the shared
2608/// structural gate. The named, de Bruijn and two evaluation engines keep their
2609/// own computations; all must refuse an override whose dependencies changed.
2610pub(crate) fn accelerates_nat_order(ctx: &Context, op: &str) -> bool {
2611    if !has_nat_order_carriers(ctx) {
2612        return false;
2613    }
2614    match op {
2615        "natLe" => accelerates_nat_le(ctx),
2616        "natLt" => {
2617            ctx.get_global("natLt").is_some_and(is_nat_nat_bool)
2618                && ctx
2619                    .get_definition_body("natLt")
2620                    .is_some_and(|b| is_successor_shifted_order(b, "natLe"))
2621                && accelerates_nat_le(ctx)
2622        }
2623        _ => false,
2624    }
2625}
2626
2627/// The non-dependent arrow spine of a type, as bare global names: `A → B → C` is
2628/// `["A", "B", "C"]`. `None` for anything else, which is already a disagreement with every
2629/// primitive's signature and so needs no further analysis. Binder NAMES are ignored, because a
2630/// declaration is free to spell them however it likes; a domain or codomain that is not a bare
2631/// global cannot be one of these signatures at all.
2632fn arrow_spine_of_globals(ty: &Term) -> Option<Vec<&str>> {
2633    let mut spine = Vec::new();
2634    let mut cur = ty;
2635    while let Term::Pi {
2636        param_type,
2637        body_type,
2638        ..
2639    } = cur
2640    {
2641        let Term::Global(name) = param_type.as_ref() else {
2642            return None;
2643        };
2644        spine.push(name.as_str());
2645        cur = body_type;
2646    }
2647    let Term::Global(name) = cur else {
2648        return None;
2649    };
2650    spine.push(name);
2651    Some(spine)
2652}
2653
2654/// The type every computation rule below promises. ONE row per rule, because a rule without one
2655/// is a rule nothing holds to a type — `R_reduction_extra`'s
2656/// `every_primitive_the_reducer_computes_has_a_signature_it_is_held_to` fails if a new primitive
2657/// arrives without its row.
2658fn primitive_signature(op: &str) -> Option<&'static [&'static str]> {
2659    Some(match op {
2660        "add" | "sub" | "mul" | "div" | "mod" => &["Int", "Int", "Int"],
2661        "le" | "lt" | "ge" | "gt" => &["Int", "Int", "Bool"],
2662        "Text_append" => &["Text", "Text", "Text"],
2663        "Text_beq" | "Text_isPrefixOf" => &["Text", "Text", "Bool"],
2664        "Text_length" => &["Text", "Nat"],
2665        // The NATIVE-REDUCTION hook. It computes no literal, so `binary_prim`/`unary_prim` never
2666        // match it and it can never be fired BY this table — its row is here so the hook can ask
2667        // `declaration_agrees_with_the_rule` the same question every other rule asks. Lean's own
2668        // `Lean.reduceBool` is `Bool → Bool`.
2669        "reduceBool" => &["Bool", "Bool"],
2670        _ => return None,
2671    })
2672}
2673
2674/// Whether a computation rule of this kernel fires on the name `op` itself — a registered primitive
2675/// operation, the native-reduction hook or a reflection rule — so that an application of `op` may
2676/// compute although `op` has no body.
2677pub(crate) fn computes_by_name(op: &str) -> bool {
2678    primitive_signature(op).is_some() || reflection_signature(op).is_some()
2679}
2680
2681/// Whether `name.{levels}` is a well-formed reference with no body to unfold (an axiom, an opaque
2682/// constant, an inductive type or a constructor).
2683pub(crate) fn const_is_value(ctx: &Context, name: &str, levels: &[crate::term::Universe]) -> bool {
2684    matches!(const_step(ctx, name, levels), ConstStep::Value)
2685}
2686
2687/// Whether the context's declaration of `op` — if it has one — AGREES with the type the
2688/// computation rule's answer inhabits.
2689///
2690/// SUBJECT REDUCTION. A primitive rule fires on a NAME and a pair of literal kinds, and nothing
2691/// used to make it look at the declared TYPE. So a context declaring
2692/// `Text_append : Text → Text → Nat` got a kernel where `infer_type` answered `Nat` and
2693/// `normalize` produced a `Text` literal — a term and its reduct with different types, which is
2694/// the one thing a conversion check may not have, since every use of a reduct in place of its
2695/// term assumes exactly that they are interchangeable. It is the same typing-versus-reduction
2696/// divergence the codebase calls conformance defect 3, reached through the primitive table
2697/// instead of through `get_global`'s resolution order.
2698///
2699/// A name the context does not declare at all is left alone: the application cannot be typed in
2700/// that context either way, so there is no verdict to disagree with, and refusing here would
2701/// take away the only route a `Text` operation currently has before the prelude declares one.
2702pub(crate) fn declaration_agrees_with_the_rule(ctx: &Context, op: &str) -> bool {
2703    let Some(signature) = primitive_signature(op) else {
2704        return false;
2705    };
2706    match ctx.get_global(op) {
2707        None => true,
2708        Some(declared) => arrow_spine_of_globals(declared).is_some_and(|s| s == signature),
2709    }
2710}
2711
2712#[derive(Clone, Copy)]
2713enum ReflectionType {
2714    Syntax,
2715    Derivation,
2716    Int,
2717    Nat,
2718    Tactic,
2719    TacticList,
2720}
2721
2722/// Ground type schemas for the reflected computation rules, including higher-order tactics.
2723fn reflection_signature(op: &str) -> Option<&'static [ReflectionType]> {
2724    use ReflectionType::{
2725        Derivation as D, Int as I, Nat as N, Syntax as S, Tactic as T, TacticList as L,
2726    };
2727    Some(match op {
2728        "syn_size" | "syn_max_var" => &[S, I],
2729        "syn_quote" | "syn_diag" | "syn_step" => &[S, S],
2730        "syn_beta" | "induction_base_goal" => &[S, S, S],
2731        "syn_eval" => &[I, S, S],
2732        "syn_lift" => &[I, I, S, S],
2733        "syn_subst" => &[S, I, S, S],
2734        "concludes" => &[D, S],
2735        "try_refl" | "try_compute" | "try_ring" | "try_lia" | "try_cc" | "try_simp"
2736        | "try_omega" | "try_auto" | "try_decide" | "try_assumption" | "try_split" | "try_left"
2737        | "try_right" | "try_bitblast" | "try_tabulate" | "try_hw_auto" | "try_inversion"
2738        | "tact_fail" => &[S, D],
2739        "induction_num_cases" => &[S, N],
2740        "try_cong" => &[S, D, D],
2741        "try_rewrite" | "try_rewrite_rev" => &[D, S, D],
2742        "try_script" => &[S, S, D],
2743        "tact_try" | "tact_repeat" | "tact_solve" => &[T, S, D],
2744        "tact_first" => &[L, S, D],
2745        "tact_orelse" | "tact_then" => &[T, T, S, D],
2746        "induction_step_goal" => &[S, S, N, S],
2747        "try_induction" | "try_destruct" => &[S, S, D, D],
2748        "try_apply" => &[S, D, S, D],
2749        _ => return None,
2750    })
2751}
2752
2753fn matches_reflection_type(ty: &Term, shape: ReflectionType) -> bool {
2754    use ReflectionType::*;
2755    match shape {
2756        Tactic => matches_reflection_signature(ty, &[Syntax, Derivation]),
2757        TacticList => matches!(ty, Term::App(head, elem)
2758            if matches!(head.as_ref(), Term::Global(n) if n == "TList")
2759                && matches_reflection_type(elem, Tactic)),
2760        _ => {
2761            let expected = match shape {
2762                Syntax => "Syntax",
2763                Derivation => "Derivation",
2764                Int => "Int",
2765                Nat => "Nat",
2766                _ => unreachable!(),
2767            };
2768            matches!(ty, Term::Global(n) if n == expected)
2769        }
2770    }
2771}
2772
2773fn matches_reflection_signature(mut ty: &Term, signature: &[ReflectionType]) -> bool {
2774    for shape in &signature[..signature.len() - 1] {
2775        let Term::Pi {
2776            param_type,
2777            body_type,
2778            ..
2779        } = ty
2780        else {
2781            return false;
2782        };
2783        if !matches_reflection_type(param_type, *shape) {
2784            return false;
2785        }
2786        ty = body_type;
2787    }
2788    matches_reflection_type(ty, signature[signature.len() - 1])
2789}
2790
2791/// Both kernels gate the same declared primitive interface; their computations remain separate.
2792pub(crate) fn reflection_declaration_agrees(ctx: &Context, op: &str) -> bool {
2793    let Some(signature) = reflection_signature(op) else {
2794        return false;
2795    };
2796    ctx.get_global(op)
2797        .is_none_or(|ty| matches_reflection_signature(ty, signature))
2798}
2799
2800/// Try to reduce a primitive operation.
2801///
2802/// Returns `Some(result)` for a fully applied primitive like `(add 3 4)` or `(Text_length "ab")`.
2803///
2804/// A primitive rule fires on a NAME, so it must never outrank a DEFINITION of that name: if
2805/// the context binds `op` to a body, the kernel has to compute what the body says, or it
2806/// disagrees with the very definition it type-checked the application against — a silent wrong
2807/// answer with no diagnostic anywhere. Bodyless primitives retain their declared
2808/// computation rules; checked definitions require attestation of the exact body
2809/// and its dependencies before literal arithmetic can replace delta reduction.
2810///
2811/// An ACCELERATION is the one thing allowed through that gate, because it is checked against
2812/// the body it is standing in for rather than merely named after it — see [`nat_order_value`].
2813/// It is δ wearing a faster coat, so it asks the transparency door the same question δ asks:
2814/// an `@[irreducible]` constant stays folded here too.
2815fn try_primitive_reduce(
2816    ctx: &Context,
2817    func: &Term,
2818    arg: &Term,
2819    tr: Transparency<'_>,
2820) -> Option<Term> {
2821    let owned_y;
2822    let yl = if let Term::Lit(literal) = arg {
2823        literal
2824    } else {
2825        owned_y = crate::int_inductive::constructor_literal(ctx, arg)?;
2826        &owned_y
2827    };
2828    match func {
2829        // Unary: `op x`
2830        Term::Global(op) => {
2831            let result = unary_prim(op, yl)?;
2832            if ctx.get_definition_body(op).is_some() || !declaration_agrees_with_the_rule(ctx, op) {
2833                return None;
2834            }
2835            Some(result)
2836        }
2837        // Binary: `(op x) y`
2838        Term::App(op_term, x) => {
2839            let Term::Global(op) = op_term.as_ref() else {
2840                return None;
2841            };
2842            let owned_x;
2843            let xl = if let Term::Lit(literal) = x.as_ref() {
2844                literal
2845            } else {
2846                owned_x = crate::int_inductive::constructor_literal(ctx, x)?;
2847                &owned_x
2848            };
2849            if let Some(decided) = nat_order_value(op, xl, yl) {
2850                // natLt's delta body calls natLe. An elaborator transparency
2851                // that keeps that dependency folded must not bypass it either.
2852                if tr.unfolds(op)
2853                    && (op != "natLt" || tr.unfolds("natLe"))
2854                    && accelerates_nat_order(ctx, op)
2855                {
2856                    return Some(bool_term(decided));
2857                }
2858                return None;
2859            }
2860            let result = binary_prim(op, xl, yl)?;
2861            if ctx.get_definition_body(op).is_some() {
2862                let dependencies = crate::int_inductive::integer_alias_dependencies(op)?;
2863                if !dependencies.iter().all(|name| tr.unfolds(name))
2864                    || !crate::int_inductive::accelerates_integer_alias(ctx, op)
2865                {
2866                    return None;
2867                }
2868            } else if !declaration_agrees_with_the_rule(ctx, op) {
2869                return None;
2870            }
2871            Some(result)
2872        }
2873        _ => None,
2874    }
2875}
2876
2877// -------------------------------------------------------------------------
2878// Reflection Builtins
2879// -------------------------------------------------------------------------
2880
2881/// Try to reduce reflection builtins (syn_size, syn_max_var, syn_lift, syn_subst, syn_beta, syn_step).
2882///
2883/// Pattern: (syn_size arg) or (syn_max_var arg) or (syn_step arg) where arg is a Syntax constructor.
2884/// Pattern: ((syn_beta body) arg) for two-argument builtins.
2885/// Pattern: (((syn_lift amount) cutoff) term) for three-argument builtins.
2886/// Pattern: (((syn_subst replacement) index) term) for substitution.
2887///
2888/// An operation `reflection` defines runs natively only where its definition is attested
2889/// (`reflection::attested`), and δ unfolds it everywhere else; the rest are assumptions whose rule
2890/// fires on their declared signature and never past a definition of the name.
2891fn try_reflection_reduce(ctx: &Context, func: &Term, arg: &Term) -> Option<Term> {
2892    let mut head = func;
2893    while let Term::App(f, _) = head {
2894        head = f;
2895    }
2896    let Term::Global(name) = head else {
2897        return None;
2898    };
2899    let gate = if crate::reflection::DEFINED.contains(&name.as_str()) {
2900        crate::reflection::attested(ctx, name)
2901    } else {
2902        !ctx.is_definition(name) && reflection_declaration_agrees(ctx, name)
2903    };
2904    if !gate {
2905        return None;
2906    }
2907    // First, check for single-argument builtins
2908    if let Term::Global(op_name) = func {
2909        match op_name.as_str() {
2910            "syn_size" => {
2911                // Normalize the argument first
2912                let norm_arg = normalize(ctx, arg);
2913                return try_syn_size_reduce(ctx, &norm_arg);
2914            }
2915            "syn_max_var" => {
2916                // Normalize the argument first
2917                let norm_arg = normalize(ctx, arg);
2918                return try_syn_max_var_reduce(ctx, &norm_arg, 0);
2919            }
2920            "syn_step" => {
2921                // Normalize the argument first
2922                let norm_arg = normalize(ctx, arg);
2923                return try_syn_step_reduce(ctx, &norm_arg);
2924            }
2925            "syn_quote" => {
2926                // Normalize the argument first
2927                let norm_arg = normalize(ctx, arg);
2928                return try_syn_quote_reduce(ctx, &norm_arg);
2929            }
2930            "syn_diag" => {
2931                // Normalize the argument first
2932                let norm_arg = normalize(ctx, arg);
2933                return try_syn_diag_reduce(ctx, &norm_arg);
2934            }
2935            "concludes" => {
2936                // Normalize the argument first
2937                let norm_arg = normalize(ctx, arg);
2938                return try_concludes_reduce(ctx, &norm_arg);
2939            }
2940            "try_refl" => {
2941                // Normalize the argument first
2942                let norm_arg = normalize(ctx, arg);
2943                return try_try_refl_reduce(ctx, &norm_arg);
2944            }
2945            "tact_fail" => {
2946                // tact_fail always returns error derivation
2947                return Some(make_error_derivation());
2948            }
2949            "try_compute" => {
2950                // try_compute goal = DCompute goal
2951                // The validation happens in concludes
2952                let norm_arg = normalize(ctx, arg);
2953                return Some(Term::App(
2954                    Box::new(Term::Global("DCompute".to_string())),
2955                    Box::new(norm_arg),
2956                ));
2957            }
2958            "try_ring" => {
2959                // Ring tactic: prove polynomial equalities by normalization
2960                let norm_arg = normalize(ctx, arg);
2961                return try_try_ring_reduce(ctx, &norm_arg);
2962            }
2963            "try_lia" => {
2964                // LIA tactic: prove linear inequalities by Fourier-Motzkin
2965                let norm_arg = normalize(ctx, arg);
2966                return try_try_lia_reduce(ctx, &norm_arg);
2967            }
2968            "try_cc" => {
2969                // CC tactic: prove equalities by congruence closure
2970                let norm_arg = normalize(ctx, arg);
2971                return try_try_cc_reduce(ctx, &norm_arg);
2972            }
2973            "try_simp" => {
2974                // Simp tactic: prove equalities by simplification and arithmetic
2975                let norm_arg = normalize(ctx, arg);
2976                return try_try_simp_reduce(ctx, &norm_arg);
2977            }
2978            "try_omega" => {
2979                // Omega tactic: prove integer inequalities with proper rounding
2980                let norm_arg = normalize(ctx, arg);
2981                return try_try_omega_reduce(ctx, &norm_arg);
2982            }
2983            "try_auto" => {
2984                // Auto tactic: tries all tactics in sequence
2985                let norm_arg = normalize(ctx, arg);
2986                return try_try_auto_reduce(ctx, &norm_arg);
2987            }
2988            "try_decide" => {
2989                // Decide tactic: decide a decidable proposition by reflection + computation
2990                let norm_arg = normalize(ctx, arg);
2991                return try_try_decide_reduce(ctx, &norm_arg);
2992            }
2993            "try_assumption" => {
2994                // Assumption tactic: close the goal with a hypothesis (after intro)
2995                let norm_arg = normalize(ctx, arg);
2996                return try_try_assumption_reduce(ctx, &norm_arg);
2997            }
2998            "try_split" => {
2999                // Split tactic: ∧-introduction (prove both conjuncts)
3000                let norm_arg = normalize(ctx, arg);
3001                return try_try_split_reduce(ctx, &norm_arg);
3002            }
3003            "try_left" => {
3004                // Left tactic: ∨-introduction-left (prove the left disjunct)
3005                let norm_arg = normalize(ctx, arg);
3006                return try_try_left_reduce(ctx, &norm_arg);
3007            }
3008            "try_right" => {
3009                // Right tactic: ∨-introduction-right (prove the right disjunct)
3010                let norm_arg = normalize(ctx, arg);
3011                return try_try_right_reduce(ctx, &norm_arg);
3012            }
3013            "try_bitblast" => {
3014                // Bitblast tactic: prove Bit equalities by normalization
3015                let norm_arg = normalize(ctx, arg);
3016                return try_try_bitblast_reduce(ctx, &norm_arg);
3017            }
3018            "try_tabulate" => {
3019                // Tabulate tactic: prove universal Bit goals by exhaustion
3020                let norm_arg = normalize(ctx, arg);
3021                return try_try_tabulate_reduce(ctx, &norm_arg);
3022            }
3023            "try_hw_auto" => {
3024                // Hardware auto: tries bitblast, then tabulate, then auto
3025                let norm_arg = normalize(ctx, arg);
3026                return try_try_hw_auto_reduce(ctx, &norm_arg);
3027            }
3028            "try_inversion" => {
3029                // Inversion tactic: derives False if no constructor can match
3030                let norm_arg = normalize(ctx, arg);
3031                return try_try_inversion_reduce(ctx, &norm_arg);
3032            }
3033            "induction_num_cases" => {
3034                // Returns number of constructors for an inductive type
3035                let norm_arg = normalize(ctx, arg);
3036                return try_induction_num_cases_reduce(ctx, &norm_arg);
3037            }
3038            _ => {}
3039        }
3040    }
3041
3042    // For multi-argument builtins like syn_lift and syn_subst,
3043    // we need to check if func is a partial application
3044
3045    // syn_lift amount cutoff term
3046    // Structure: (((syn_lift amount) cutoff) term) = App(App(App(syn_lift, amount), cutoff), term)
3047    // When reduced: func = App(App(syn_lift, amount), cutoff), arg = term
3048    if let Term::App(partial2, cutoff) = func {
3049        if let Term::App(partial1, amount) = partial2.as_ref() {
3050            if let Term::Global(op_name) = partial1.as_ref() {
3051                if op_name == "syn_lift" {
3052                    if let (Term::Lit(Literal::Int(amt)), Term::Lit(Literal::Int(cut))) =
3053                        (amount.as_ref(), cutoff.as_ref())
3054                    {
3055                        let norm_term = normalize(ctx, arg);
3056                        return try_syn_lift_reduce(ctx, *amt, *cut, &norm_term);
3057                    }
3058                }
3059            }
3060        }
3061    }
3062
3063    // syn_subst replacement index term
3064    // Structure: (((syn_subst replacement) index) term)
3065    if let Term::App(partial2, index) = func {
3066        if let Term::App(partial1, replacement) = partial2.as_ref() {
3067            if let Term::Global(op_name) = partial1.as_ref() {
3068                if op_name == "syn_subst" {
3069                    if let Term::Lit(Literal::Int(idx)) = index.as_ref() {
3070                        let norm_replacement = normalize(ctx, replacement);
3071                        let norm_term = normalize(ctx, arg);
3072                        return try_syn_subst_reduce(ctx, &norm_replacement, *idx, &norm_term);
3073                    }
3074                }
3075            }
3076        }
3077    }
3078
3079    // syn_beta body arg (2 arguments)
3080    // Structure: ((syn_beta body) arg)
3081    if let Term::App(partial1, body) = func {
3082        if let Term::Global(op_name) = partial1.as_ref() {
3083            if op_name == "syn_beta" {
3084                let norm_body = normalize(ctx, body);
3085                let norm_arg = normalize(ctx, arg);
3086                return try_syn_beta_reduce(ctx, &norm_body, &norm_arg);
3087            }
3088        }
3089    }
3090
3091    // try_cong context eq_proof (2 arguments)
3092    // Structure: ((try_cong context) eq_proof)
3093    // Returns: DCong context eq_proof
3094    if let Term::App(partial1, context) = func {
3095        if let Term::Global(op_name) = partial1.as_ref() {
3096            if op_name == "try_cong" {
3097                let norm_context = normalize(ctx, context);
3098                let norm_proof = normalize(ctx, arg);
3099                return Some(Term::App(
3100                    Box::new(Term::App(
3101                        Box::new(Term::Global("DCong".to_string())),
3102                        Box::new(norm_context),
3103                    )),
3104                    Box::new(norm_proof),
3105                ));
3106            }
3107        }
3108    }
3109
3110    // try_rewrite eq_proof goal (2 arguments)
3111    // Structure: ((try_rewrite eq_proof) goal)
3112    // Given eq_proof : Eq A x y, rewrites goal by replacing x with y
3113    if let Term::App(partial1, eq_proof) = func {
3114        if let Term::Global(op_name) = partial1.as_ref() {
3115            if op_name == "try_rewrite" {
3116                let norm_eq_proof = normalize(ctx, eq_proof);
3117                let norm_goal = normalize(ctx, arg);
3118                return try_try_rewrite_reduce(ctx, &norm_eq_proof, &norm_goal, false);
3119            }
3120            if op_name == "try_rewrite_rev" {
3121                let norm_eq_proof = normalize(ctx, eq_proof);
3122                let norm_goal = normalize(ctx, arg);
3123                return try_try_rewrite_reduce(ctx, &norm_eq_proof, &norm_goal, true);
3124            }
3125        }
3126    }
3127
3128    // syn_eval fuel term (2 arguments)
3129    // Structure: ((syn_eval fuel) term)
3130    if let Term::App(partial1, fuel_term) = func {
3131        if let Term::Global(op_name) = partial1.as_ref() {
3132            if op_name == "syn_eval" {
3133                if let Term::Lit(Literal::Int(fuel)) = fuel_term.as_ref() {
3134                    let norm_term = normalize(ctx, arg);
3135                    return try_syn_eval_reduce(ctx, *fuel, &norm_term);
3136                }
3137            }
3138        }
3139    }
3140
3141    // induction_base_goal ind_type motive (2 arguments)
3142    // Structure: ((induction_base_goal ind_type) motive)
3143    if let Term::App(partial1, ind_type) = func {
3144        if let Term::Global(op_name) = partial1.as_ref() {
3145            if op_name == "induction_base_goal" {
3146                let norm_ind_type = normalize(ctx, ind_type);
3147                let norm_motive = normalize(ctx, arg);
3148                return try_induction_base_goal_reduce(ctx, &norm_ind_type, &norm_motive);
3149            }
3150        }
3151    }
3152
3153    // tact_orelse t1 t2 goal (3 arguments)
3154    // Structure: (((tact_orelse t1) t2) goal)
3155    // Here: func = App(App(tact_orelse, t1), t2), arg = goal
3156    if let Term::App(partial1, t2) = func {
3157        if let Term::App(combinator, t1) = partial1.as_ref() {
3158            if let Term::Global(name) = combinator.as_ref() {
3159                if name == "tact_orelse" {
3160                    return try_tact_orelse_reduce(ctx, t1, t2, arg);
3161                }
3162                // tact_then t1 t2 goal (3 arguments)
3163                if name == "tact_then" {
3164                    return try_tact_then_reduce(ctx, t1, t2, arg);
3165                }
3166            }
3167        }
3168    }
3169
3170    // tact_try t goal (2 arguments)
3171    // Structure: ((tact_try t) goal)
3172    if let Term::App(combinator, t) = func {
3173        if let Term::Global(name) = combinator.as_ref() {
3174            if name == "tact_try" {
3175                return try_tact_try_reduce(ctx, t, arg);
3176            }
3177            // tact_repeat t goal (2 arguments)
3178            if name == "tact_repeat" {
3179                return try_tact_repeat_reduce(ctx, t, arg);
3180            }
3181            // tact_solve t goal (2 arguments)
3182            if name == "tact_solve" {
3183                return try_tact_solve_reduce(ctx, t, arg);
3184            }
3185            // tact_first tactics goal (2 arguments)
3186            if name == "tact_first" {
3187                return try_tact_first_reduce(ctx, t, arg);
3188            }
3189        }
3190    }
3191
3192    // induction_step_goal ind_type motive ctor_idx (3 arguments)
3193    // Structure: (((induction_step_goal ind_type) motive) ctor_idx)
3194    // Returns the goal for the given constructor index
3195    if let Term::App(partial1, motive) = func {
3196        if let Term::App(combinator, ind_type) = partial1.as_ref() {
3197            if let Term::Global(name) = combinator.as_ref() {
3198                if name == "induction_step_goal" {
3199                    let norm_ind_type = normalize(ctx, ind_type);
3200                    let norm_motive = normalize(ctx, motive);
3201                    let norm_idx = normalize(ctx, arg);
3202                    return try_induction_step_goal_reduce(
3203                        ctx,
3204                        &norm_ind_type,
3205                        &norm_motive,
3206                        &norm_idx,
3207                    );
3208                }
3209            }
3210        }
3211    }
3212
3213    // try_induction ind_type motive cases (3 arguments)
3214    // Structure: (((try_induction ind_type) motive) cases)
3215    // Returns DElim ind_type motive cases (delegating to existing infrastructure)
3216    if let Term::App(partial1, motive) = func {
3217        if let Term::App(combinator, ind_type) = partial1.as_ref() {
3218            if let Term::Global(name) = combinator.as_ref() {
3219                if name == "try_induction" {
3220                    let norm_ind_type = normalize(ctx, ind_type);
3221                    let norm_motive = normalize(ctx, motive);
3222                    let norm_cases = normalize(ctx, arg);
3223                    return try_try_induction_reduce(
3224                        ctx,
3225                        &norm_ind_type,
3226                        &norm_motive,
3227                        &norm_cases,
3228                    );
3229                }
3230            }
3231        }
3232    }
3233
3234    // try_destruct ind_type motive cases (3 arguments)
3235    // Structure: (((try_destruct ind_type) motive) cases)
3236    // Case analysis without induction hypotheses
3237    if let Term::App(partial1, motive) = func {
3238        if let Term::App(combinator, ind_type) = partial1.as_ref() {
3239            if let Term::Global(name) = combinator.as_ref() {
3240                if name == "try_destruct" {
3241                    let norm_ind_type = normalize(ctx, ind_type);
3242                    let norm_motive = normalize(ctx, motive);
3243                    let norm_cases = normalize(ctx, arg);
3244                    return try_try_destruct_reduce(&norm_ind_type, &norm_motive, &norm_cases);
3245                }
3246            }
3247        }
3248    }
3249
3250    // try_apply hyp_name hyp_proof goal (3 arguments)
3251    // Structure: (((try_apply hyp_name) hyp_proof) goal)
3252    // Manual backward chaining
3253    if let Term::App(partial1, hyp_proof) = func {
3254        if let Term::App(combinator, hyp_name) = partial1.as_ref() {
3255            if let Term::Global(name) = combinator.as_ref() {
3256                if name == "try_apply" {
3257                    let norm_hyp_name = normalize(ctx, hyp_name);
3258                    let norm_hyp_proof = normalize(ctx, hyp_proof);
3259                    let norm_goal = normalize(ctx, arg);
3260                    return try_try_apply_reduce(ctx, &norm_hyp_name, &norm_hyp_proof, &norm_goal);
3261                }
3262            }
3263        }
3264    }
3265
3266    None
3267}
3268
3269/// Compute size of a Syntax term.
3270///
3271/// SVar n -> 1
3272/// SGlobal n -> 1
3273/// SSort u -> 1
3274/// SApp f x -> 1 + size(f) + size(x)
3275/// SLam A b -> 1 + size(A) + size(b)
3276/// SPi A B -> 1 + size(A) + size(B)
3277fn try_syn_size_reduce(ctx: &Context, term: &Term) -> Option<Term> {
3278    // Match on the constructor form
3279    // Unary constructors: (SVar n), (SGlobal n), (SSort u)
3280    // Binary constructors: ((SApp f) x), ((SLam A) b), ((SPi A) B)
3281
3282    // Check for unary constructor: (Ctor arg)
3283    if let Term::App(ctor_term, _inner_arg) = term {
3284        if let Term::Global(ctor_name) = ctor_term.as_ref() {
3285            match ctor_name.as_str() {
3286                "SVar" | "SGlobal" | "SSort" | "SLit" | "SName" => {
3287                    return Some(Term::Lit(Literal::Int(1)));
3288                }
3289                _ => {}
3290            }
3291        }
3292
3293        // Check for binary constructor: ((Ctor a) b)
3294        if let Term::App(inner, a) = ctor_term.as_ref() {
3295            if let Term::Global(ctor_name) = inner.as_ref() {
3296                match ctor_name.as_str() {
3297                    "SApp" | "SLam" | "SPi" => {
3298                        // Get sizes of both children
3299                        let a_size = try_syn_size_reduce(ctx, a)?;
3300                        let b_size = try_syn_size_reduce(ctx, _inner_arg)?;
3301
3302                        if let (Term::Lit(Literal::Int(a_n)), Term::Lit(Literal::Int(b_n))) =
3303                            (a_size, b_size)
3304                        {
3305                            return Some(Term::Lit(Literal::Int(1 + a_n + b_n)));
3306                        }
3307                    }
3308                    _ => {}
3309                }
3310            }
3311        }
3312    }
3313
3314    None
3315}
3316
3317/// Compute maximum free variable index in a Syntax term.
3318///
3319/// The `depth` parameter tracks how many binders we're under.
3320/// SVar k -> k - depth (returns -1 if bound, k - depth if free)
3321/// SGlobal _ -> -1 (no free variables)
3322/// SSort _ -> -1 (no free variables)
3323/// SApp f x -> max(max_var(f), max_var(x))
3324/// SLam A b -> max(max_var(A), max_var(b, depth+1))
3325/// SPi A B -> max(max_var(A), max_var(B, depth+1))
3326fn try_syn_max_var_reduce(ctx: &Context, term: &Term, depth: i64) -> Option<Term> {
3327    // Check for unary constructor: (Ctor arg)
3328    if let Term::App(ctor_term, inner_arg) = term {
3329        if let Term::Global(ctor_name) = ctor_term.as_ref() {
3330            match ctor_name.as_str() {
3331                "SVar" => {
3332                    // SVar k -> if k >= depth then k - depth else -1
3333                    if let Term::Lit(Literal::Int(k)) = inner_arg.as_ref() {
3334                        if *k >= depth {
3335                            // Free variable with adjusted index
3336                            return Some(Term::Lit(Literal::Int(*k - depth)));
3337                        } else {
3338                            // Bound variable
3339                            return Some(Term::Lit(Literal::Int(-1)));
3340                        }
3341                    }
3342                }
3343                "SGlobal" | "SSort" | "SLit" | "SName" => {
3344                    // No free variables
3345                    return Some(Term::Lit(Literal::Int(-1)));
3346                }
3347                _ => {}
3348            }
3349        }
3350
3351        // Check for binary constructor: ((Ctor a) b)
3352        if let Term::App(inner, a) = ctor_term.as_ref() {
3353            if let Term::Global(ctor_name) = inner.as_ref() {
3354                match ctor_name.as_str() {
3355                    "SApp" => {
3356                        // SApp f x -> max(max_var(f), max_var(x))
3357                        let a_max = try_syn_max_var_reduce(ctx, a, depth)?;
3358                        let b_max = try_syn_max_var_reduce(ctx, inner_arg, depth)?;
3359
3360                        if let (Term::Lit(Literal::Int(a_n)), Term::Lit(Literal::Int(b_n))) =
3361                            (a_max, b_max)
3362                        {
3363                            return Some(Term::Lit(Literal::Int(a_n.max(b_n))));
3364                        }
3365                    }
3366                    "SLam" | "SPi" => {
3367                        // SLam A b -> max(max_var(A, depth), max_var(b, depth+1))
3368                        // The body 'b' is under one additional binder
3369                        let a_max = try_syn_max_var_reduce(ctx, a, depth)?;
3370                        let b_max = try_syn_max_var_reduce(ctx, inner_arg, depth + 1)?;
3371
3372                        if let (Term::Lit(Literal::Int(a_n)), Term::Lit(Literal::Int(b_n))) =
3373                            (a_max, b_max)
3374                        {
3375                            return Some(Term::Lit(Literal::Int(a_n.max(b_n))));
3376                        }
3377                    }
3378                    _ => {}
3379                }
3380            }
3381        }
3382    }
3383
3384    None
3385}
3386
3387// -------------------------------------------------------------------------
3388// Substitution Builtins
3389// -------------------------------------------------------------------------
3390
3391/// Lift De Bruijn indices in a Syntax term.
3392///
3393/// syn_lift amount cutoff term:
3394/// - Variables with index < cutoff are bound -> unchanged
3395/// - Variables with index >= cutoff are free -> add amount
3396fn try_syn_lift_reduce(ctx: &Context, amount: i64, cutoff: i64, term: &Term) -> Option<Term> {
3397    // Check for unary constructor: (Ctor arg)
3398    if let Term::App(ctor_term, inner_arg) = term {
3399        if let Term::Global(ctor_name) = ctor_term.as_ref() {
3400            match ctor_name.as_str() {
3401                "SVar" => {
3402                    if let Term::Lit(Literal::Int(k)) = inner_arg.as_ref() {
3403                        if *k >= cutoff {
3404                            // Free variable, shift
3405                            return Some(Term::App(
3406                                Box::new(Term::Global("SVar".to_string())),
3407                                Box::new(Term::Lit(Literal::Int(k.checked_add(amount)?))),
3408                            ));
3409                        } else {
3410                            // Bound variable, no shift
3411                            return Some(term.clone());
3412                        }
3413                    }
3414                }
3415                "SGlobal" | "SSort" | "SLit" | "SName" => {
3416                    // No free variables
3417                    return Some(term.clone());
3418                }
3419                _ => {}
3420            }
3421        }
3422
3423        // Check for binary constructor: ((Ctor a) b)
3424        if let Term::App(inner, a) = ctor_term.as_ref() {
3425            if let Term::Global(ctor_name) = inner.as_ref() {
3426                match ctor_name.as_str() {
3427                    "SApp" => {
3428                        // No binding, same cutoff for both
3429                        let a_lifted = try_syn_lift_reduce(ctx, amount, cutoff, a)?;
3430                        let b_lifted = try_syn_lift_reduce(ctx, amount, cutoff, inner_arg)?;
3431                        return Some(Term::App(
3432                            Box::new(Term::App(
3433                                Box::new(Term::Global("SApp".to_string())),
3434                                Box::new(a_lifted),
3435                            )),
3436                            Box::new(b_lifted),
3437                        ));
3438                    }
3439                    "SLam" | "SPi" => {
3440                        // Binder: param type at current cutoff, body at cutoff+1
3441                        let param_lifted = try_syn_lift_reduce(ctx, amount, cutoff, a)?;
3442                        let body_lifted = try_syn_lift_reduce(ctx, amount, cutoff + 1, inner_arg)?;
3443                        return Some(Term::App(
3444                            Box::new(Term::App(
3445                                Box::new(Term::Global(ctor_name.clone())),
3446                                Box::new(param_lifted),
3447                            )),
3448                            Box::new(body_lifted),
3449                        ));
3450                    }
3451                    _ => {}
3452                }
3453            }
3454        }
3455    }
3456
3457    None
3458}
3459
3460/// Substitute a term for a variable in a Syntax term.
3461///
3462/// syn_subst replacement index term:
3463/// - If term is SVar k and k == index, return replacement
3464/// - If term is SVar k and k != index, return term unchanged
3465/// - For binders, increment index and lift replacement
3466fn try_syn_subst_reduce(
3467    ctx: &Context,
3468    replacement: &Term,
3469    index: i64,
3470    term: &Term,
3471) -> Option<Term> {
3472    // Plain substitution (no de Bruijn decrement): used by recursor / induction
3473    // handling where the binder is NOT eliminated.
3474    syn_subst_impl(ctx, replacement, index, term, false)
3475}
3476
3477/// Substitute `replacement` for de Bruijn variable `index` in a Syntax term.
3478///
3479/// When `decrement` is true this implements the variable part of a BETA step:
3480/// because the binder is eliminated, surviving free variables `k` with
3481/// `k > index` are lowered to `k - 1`. With `decrement` false it is a plain
3482/// substitution that leaves non-matching variables untouched (the semantics the
3483/// recursor/induction call sites rely on).
3484fn syn_subst_impl(
3485    ctx: &Context,
3486    replacement: &Term,
3487    index: i64,
3488    term: &Term,
3489    decrement: bool,
3490) -> Option<Term> {
3491    // Check for unary constructor: (Ctor arg)
3492    if let Term::App(ctor_term, inner_arg) = term {
3493        if let Term::Global(ctor_name) = ctor_term.as_ref() {
3494            match ctor_name.as_str() {
3495                "SVar" => {
3496                    if let Term::Lit(Literal::Int(k)) = inner_arg.as_ref() {
3497                        if *k == index {
3498                            // Match! Return replacement (already lifted to this depth).
3499                            return Some(replacement.clone());
3500                        } else if decrement && *k > index {
3501                            // Beta: the binder was removed, so a surviving free
3502                            // variable above it drops by one level.
3503                            return Some(Term::App(
3504                                Box::new(Term::Global("SVar".to_string())),
3505                                Box::new(Term::Lit(Literal::Int(*k - 1))),
3506                            ));
3507                        } else {
3508                            // No match, return unchanged
3509                            return Some(term.clone());
3510                        }
3511                    }
3512                }
3513                "SGlobal" | "SSort" | "SLit" | "SName" => {
3514                    // No variables to substitute
3515                    return Some(term.clone());
3516                }
3517                _ => {}
3518            }
3519        }
3520
3521        // Check for binary constructor: ((Ctor a) b)
3522        if let Term::App(inner, a) = ctor_term.as_ref() {
3523            if let Term::Global(ctor_name) = inner.as_ref() {
3524                match ctor_name.as_str() {
3525                    "SApp" => {
3526                        // No binding, same index and replacement
3527                        let a_subst = syn_subst_impl(ctx, replacement, index, a, decrement)?;
3528                        let b_subst =
3529                            syn_subst_impl(ctx, replacement, index, inner_arg, decrement)?;
3530                        return Some(Term::App(
3531                            Box::new(Term::App(
3532                                Box::new(Term::Global("SApp".to_string())),
3533                                Box::new(a_subst),
3534                            )),
3535                            Box::new(b_subst),
3536                        ));
3537                    }
3538                    "SLam" | "SPi" => {
3539                        // Binder: param type at current index, body at index+1
3540                        // Lift replacement when going under binder
3541                        let param_subst = syn_subst_impl(ctx, replacement, index, a, decrement)?;
3542
3543                        // Lift the replacement by 1 when going under the binder
3544                        let lifted_replacement = try_syn_lift_reduce(ctx, 1, 0, replacement)?;
3545                        let body_subst = syn_subst_impl(
3546                            ctx,
3547                            &lifted_replacement,
3548                            index + 1,
3549                            inner_arg,
3550                            decrement,
3551                        )?;
3552
3553                        return Some(Term::App(
3554                            Box::new(Term::App(
3555                                Box::new(Term::Global(ctor_name.clone())),
3556                                Box::new(param_subst),
3557                            )),
3558                            Box::new(body_subst),
3559                        ));
3560                    }
3561                    _ => {}
3562                }
3563            }
3564        }
3565    }
3566
3567    None
3568}
3569
3570// -------------------------------------------------------------------------
3571// Computation Builtins
3572// -------------------------------------------------------------------------
3573
3574/// Beta reduction: substitute arg for variable 0 in body, with the de Bruijn
3575/// decrement that removing the binder requires.
3576///
3577/// `syn_beta body arg` reflects the kernel's real beta step: substitute `arg`
3578/// for index 0 in `body`, AND shift every surviving free variable `k > 0` down
3579/// to `k - 1` (the λ binder is gone, so references that pointed PAST it must
3580/// drop one level). Without the decrement the reflection would be unfaithful —
3581/// `reflected_beta_decrements_surviving_free_vars` pins it: `(λT. SVar 1)(SVar 7)
3582/// → SVar 0`. (`syn_subst` itself is the raw, non-shifting substitution
3583/// primitive — `syn_beta` is `syn_subst` at index 0 composed with that shift.)
3584fn try_syn_beta_reduce(ctx: &Context, body: &Term, arg: &Term) -> Option<Term> {
3585    syn_subst_impl(ctx, arg, 0, body, true)
3586}
3587
3588/// Try to reduce arithmetic on Syntax literals.
3589///
3590/// Handles: SApp (SApp (SName op) (SLit n)) (SLit m) → SLit result
3591/// where op is one of: add, sub, mul, div, mod
3592fn try_syn_arith_reduce(func: &Term, arg: &Term) -> Option<Term> {
3593    // func should be: SApp (SName op) (SLit n)
3594    // Pattern: App(App(Global("SApp"), App(Global("SName"), Lit(Text(op)))), App(Global("SLit"), Lit(Int(n))))
3595    if let Term::App(inner_ctor, n_term) = func {
3596        if let Term::App(sapp_ctor, op_term) = inner_ctor.as_ref() {
3597            // Check for SApp constructor
3598            if let Term::Global(ctor_name) = sapp_ctor.as_ref() {
3599                if ctor_name != "SApp" {
3600                    return None;
3601                }
3602            } else {
3603                return None;
3604            }
3605
3606            // Extract op from SName op
3607            let op = if let Term::App(sname_ctor, op_str) = op_term.as_ref() {
3608                if let Term::Global(name) = sname_ctor.as_ref() {
3609                    if name == "SName" {
3610                        if let Term::Lit(Literal::Text(op)) = op_str.as_ref() {
3611                            op.clone()
3612                        } else {
3613                            return None;
3614                        }
3615                    } else {
3616                        return None;
3617                    }
3618                } else {
3619                    return None;
3620                }
3621            } else {
3622                return None;
3623            };
3624
3625            // Extract n from SLit n
3626            let n = if let Term::App(slit_ctor, n_val) = n_term.as_ref() {
3627                if let Term::Global(name) = slit_ctor.as_ref() {
3628                    if name == "SLit" {
3629                        if let Term::Lit(Literal::Int(n)) = n_val.as_ref() {
3630                            *n
3631                        } else {
3632                            return None;
3633                        }
3634                    } else {
3635                        return None;
3636                    }
3637                } else {
3638                    return None;
3639                }
3640            } else {
3641                return None;
3642            };
3643
3644            // Extract m from SLit m (the arg)
3645            let m = if let Term::App(slit_ctor, m_val) = arg {
3646                if let Term::Global(name) = slit_ctor.as_ref() {
3647                    if name == "SLit" {
3648                        if let Term::Lit(Literal::Int(m)) = m_val.as_ref() {
3649                            *m
3650                        } else {
3651                            return None;
3652                        }
3653                    } else {
3654                        return None;
3655                    }
3656                } else {
3657                    return None;
3658                }
3659            } else {
3660                return None;
3661            };
3662
3663            // Compute result based on operator. The reflected object language models the
3664            // kernel's OWN arithmetic, so `div`/`mod` here are the same TOTAL Euclidean pair
3665            // `try_primitive_reduce` computes: a reflected `div` that truncated while the
3666            // kernel's rounded the other way would let `try_dcompute_conclude` certify
3667            // `Eq Int (div (-7) 2) (-3)` — a FALSE equation, accepted by reflection.
3668            let result = match op.as_str() {
3669                "add" => n.checked_add(m),
3670                "sub" => n.checked_sub(m),
3671                "mul" => n.checked_mul(m),
3672                "div" => ediv_emod_i64(n, m).map(|(q, _)| q),
3673                "mod" => ediv_emod_i64(n, m).map(|(_, r)| r),
3674                _ => None,
3675            };
3676
3677            // Build SLit result
3678            if let Some(r) = result {
3679                return Some(Term::App(
3680                    Box::new(Term::Global("SLit".to_string())),
3681                    Box::new(Term::Lit(Literal::Int(r))),
3682                ));
3683            }
3684        }
3685    }
3686
3687    None
3688}
3689
3690/// Single-step head reduction.
3691///
3692/// Looks for the leftmost-outermost beta redex and reduces it.
3693/// - If SApp (SLam T body) arg: perform beta reduction
3694/// - If SApp f x where f is reducible: reduce f
3695/// - Otherwise: return unchanged (stuck or value)
3696fn try_syn_step_reduce(ctx: &Context, term: &Term) -> Option<Term> {
3697    // Check for SApp (binary constructor)
3698    if let Term::App(ctor_term, arg) = term {
3699        if let Term::App(inner, func) = ctor_term.as_ref() {
3700            if let Term::Global(ctor_name) = inner.as_ref() {
3701                if ctor_name == "SApp" {
3702                    // We have SApp func arg
3703                    // First, check for arithmetic primitives: SApp (SApp (SName op) (SLit n)) (SLit m)
3704                    if let Some(result) = try_syn_arith_reduce(func.as_ref(), arg.as_ref()) {
3705                        return Some(result);
3706                    }
3707
3708                    // Check if func is SLam (beta redex)
3709                    if let Term::App(lam_inner, body) = func.as_ref() {
3710                        if let Term::App(lam_ctor, _param_type) = lam_inner.as_ref() {
3711                            if let Term::Global(lam_name) = lam_ctor.as_ref() {
3712                                if lam_name == "SLam" {
3713                                    // Beta redex! (SApp (SLam T body) arg) → syn_beta body arg
3714                                    return try_syn_beta_reduce(ctx, body.as_ref(), arg.as_ref());
3715                                }
3716                            }
3717                        }
3718                    }
3719
3720                    // Delta reduction via kernel normalization:
3721                    // When the entire SApp tree represents a reducible expression
3722                    // (e.g., SApp(SApp(SName("bit_and"), SName("B1")), SName("B0"))),
3723                    // reify to kernel Term, normalize, and convert back to Syntax.
3724                    // This leverages the kernel's full reduction machinery (delta + iota + beta)
3725                    // without needing Match support in the Syntax representation.
3726                    {
3727                        let full_app = term; // The entire SApp(func, arg) Syntax term
3728                        if let Some(kernel_term) = syntax_to_term(full_app) {
3729                            let normalized = normalize(ctx, &kernel_term);
3730                            if normalized != kernel_term {
3731                                if let Some(result_syntax) = term_to_syntax(&normalized) {
3732                                    return Some(result_syntax);
3733                                }
3734                            }
3735                        }
3736                    }
3737
3738                    // Not a beta redex or reducible application. Try to step the function.
3739                    if let Some(stepped_func) = try_syn_step_reduce(ctx, func.as_ref()) {
3740                        // Check if func actually changed
3741                        if &stepped_func != func.as_ref() {
3742                            // func reduced, reconstruct SApp stepped_func arg
3743                            return Some(Term::App(
3744                                Box::new(Term::App(
3745                                    Box::new(Term::Global("SApp".to_string())),
3746                                    Box::new(stepped_func),
3747                                )),
3748                                Box::new(arg.as_ref().clone()),
3749                            ));
3750                        }
3751                    }
3752
3753                    // func is stuck. Try to step the argument.
3754                    if let Some(stepped_arg) = try_syn_step_reduce(ctx, arg.as_ref()) {
3755                        if &stepped_arg != arg.as_ref() {
3756                            // arg reduced, reconstruct SApp func stepped_arg
3757                            return Some(Term::App(
3758                                Box::new(Term::App(
3759                                    Box::new(Term::Global("SApp".to_string())),
3760                                    Box::new(func.as_ref().clone()),
3761                                )),
3762                                Box::new(stepped_arg),
3763                            ));
3764                        }
3765                    }
3766
3767                    // Both func and arg are stuck, return original term
3768                    return Some(term.clone());
3769                }
3770            }
3771        }
3772    }
3773
3774    // Not an application - it's a value or stuck term
3775    // Return unchanged
3776    Some(term.clone())
3777}
3778
3779// -------------------------------------------------------------------------
3780// Bounded Evaluation
3781// -------------------------------------------------------------------------
3782
3783/// Bounded evaluation: reduce for up to N steps.
3784///
3785/// syn_eval fuel term:
3786/// - If fuel <= 0: return term unchanged
3787/// - Otherwise: step and repeat until normal form or fuel exhausted
3788fn try_syn_eval_reduce(ctx: &Context, fuel: i64, term: &Term) -> Option<Term> {
3789    match syn_eval_checked(ctx, fuel, term) {
3790        // A fuelled evaluator's exhausted result is a legitimate answer for the OBJECT-language
3791        // `syn_eval fuel t`, because the fuel is written in the term and the caller can see it.
3792        // It is NOT a legitimate answer for a proof door, which is why the honest channel exists.
3793        Ok(value) | Err(Some(value)) => Some(value),
3794        Err(None) => None,
3795    }
3796}
3797
3798/// Bounded evaluation of a reflected term, reporting whether it FINISHED.
3799///
3800/// `Ok(v)` — reached a normal form (or a stuck term) with fuel to spare. `Err(Some(v))` — the
3801/// fuel ran out at `v`, which is as far as it got and NOT the value of the expression.
3802/// `Err(None)` — a step could not be taken at all.
3803///
3804/// Iterative on purpose. The recursive shape this replaces recursed ONCE PER STEP, so the fuel
3805/// literal in `syn_eval <fuel> t` — a number the user writes in the term — set the native stack
3806/// depth: a large enough one overflowed the stack and ABORTED THE PROCESS out of `normalize`, a
3807/// total public entry point. Depth is now bounded by the heap, and the budget can be raised
3808/// without buying a crash.
3809fn syn_eval_checked(ctx: &Context, fuel: i64, term: &Term) -> Result<Term, Option<Term>> {
3810    let mut current = term.clone();
3811    let mut left = fuel;
3812    while left > 0 {
3813        let stepped = match try_syn_step_reduce(ctx, &current) {
3814            Some(s) => s,
3815            None => return Err(None),
3816        };
3817        if stepped == current {
3818            return Ok(current);
3819        }
3820        current = stepped;
3821        left -= 1;
3822    }
3823    Err(Some(current))
3824}
3825
3826// -------------------------------------------------------------------------
3827// Reification (Quote)
3828// -------------------------------------------------------------------------
3829
3830/// Quote a Syntax value: produce Syntax that constructs it.
3831///
3832/// syn_quote term:
3833/// - SVar n → SApp (SName "SVar") (SLit n)
3834/// - SGlobal n → SApp (SName "SGlobal") (SLit n)
3835/// - SSort u → SApp (SName "SSort") (quote_univ u)
3836/// - SApp f x → SApp (SApp (SName "SApp") (quote f)) (quote x)
3837/// - SLam T b → SApp (SApp (SName "SLam") (quote T)) (quote b)
3838/// - SPi T B → SApp (SApp (SName "SPi") (quote T)) (quote B)
3839/// - SLit n → SApp (SName "SLit") (SLit n)
3840/// - SName s → SName s (self-quoting)
3841#[allow(dead_code)]
3842fn try_syn_quote_reduce(ctx: &Context, term: &Term) -> Option<Term> {
3843    // Helper to build SApp (SName name) arg
3844    fn sname_app(name: &str, arg: Term) -> Term {
3845        Term::App(
3846            Box::new(Term::App(
3847                Box::new(Term::Global("SApp".to_string())),
3848                Box::new(Term::App(
3849                    Box::new(Term::Global("SName".to_string())),
3850                    Box::new(Term::Lit(Literal::Text(name.to_string()))),
3851                )),
3852            )),
3853            Box::new(arg),
3854        )
3855    }
3856
3857    // Helper to build SLit n
3858    fn slit(n: i64) -> Term {
3859        Term::App(
3860            Box::new(Term::Global("SLit".to_string())),
3861            Box::new(Term::Lit(Literal::Int(n))),
3862        )
3863    }
3864
3865    // Helper to build SName s
3866    fn sname(s: &str) -> Term {
3867        Term::App(
3868            Box::new(Term::Global("SName".to_string())),
3869            Box::new(Term::Lit(Literal::Text(s.to_string()))),
3870        )
3871    }
3872
3873    // Helper to build SApp (SApp (SName name) a) b
3874    fn sname_app2(name: &str, a: Term, b: Term) -> Term {
3875        Term::App(
3876            Box::new(Term::App(
3877                Box::new(Term::Global("SApp".to_string())),
3878                Box::new(sname_app(name, a)),
3879            )),
3880            Box::new(b),
3881        )
3882    }
3883
3884    // Match on Syntax constructors
3885    if let Term::App(ctor_term, inner_arg) = term {
3886        if let Term::Global(ctor_name) = ctor_term.as_ref() {
3887            match ctor_name.as_str() {
3888                "SVar" => {
3889                    if let Term::Lit(Literal::Int(n)) = inner_arg.as_ref() {
3890                        return Some(sname_app("SVar", slit(*n)));
3891                    }
3892                }
3893                "SGlobal" => {
3894                    if let Term::Lit(Literal::Int(n)) = inner_arg.as_ref() {
3895                        return Some(sname_app("SGlobal", slit(*n)));
3896                    }
3897                }
3898                "SSort" => {
3899                    // Quote the universe
3900                    let quoted_univ = quote_univ(inner_arg)?;
3901                    return Some(sname_app("SSort", quoted_univ));
3902                }
3903                "SLit" => {
3904                    if let Term::Lit(Literal::Int(n)) = inner_arg.as_ref() {
3905                        return Some(sname_app("SLit", slit(*n)));
3906                    }
3907                }
3908                "SName" => {
3909                    // SName is self-quoting
3910                    return Some(term.clone());
3911                }
3912                _ => {}
3913            }
3914        }
3915
3916        // Binary constructors: ((Ctor a) b)
3917        if let Term::App(inner, a) = ctor_term.as_ref() {
3918            if let Term::Global(ctor_name) = inner.as_ref() {
3919                match ctor_name.as_str() {
3920                    "SApp" | "SLam" | "SPi" => {
3921                        let quoted_a = try_syn_quote_reduce(ctx, a)?;
3922                        let quoted_b = try_syn_quote_reduce(ctx, inner_arg)?;
3923                        return Some(sname_app2(ctor_name, quoted_a, quoted_b));
3924                    }
3925                    _ => {}
3926                }
3927            }
3928        }
3929    }
3930
3931    None
3932}
3933
3934/// Quote a Univ value.
3935///
3936/// UProp → SName "UProp"
3937/// UType n → SApp (SName "UType") (SLit n)
3938fn quote_univ(term: &Term) -> Option<Term> {
3939    fn sname(s: &str) -> Term {
3940        Term::App(
3941            Box::new(Term::Global("SName".to_string())),
3942            Box::new(Term::Lit(Literal::Text(s.to_string()))),
3943        )
3944    }
3945
3946    fn slit(n: i64) -> Term {
3947        Term::App(
3948            Box::new(Term::Global("SLit".to_string())),
3949            Box::new(Term::Lit(Literal::Int(n))),
3950        )
3951    }
3952
3953    fn sname_app(name: &str, arg: Term) -> Term {
3954        Term::App(
3955            Box::new(Term::App(
3956                Box::new(Term::Global("SApp".to_string())),
3957                Box::new(sname(name)),
3958            )),
3959            Box::new(arg),
3960        )
3961    }
3962
3963    if let Term::Global(name) = term {
3964        if name == "UProp" {
3965            return Some(sname("UProp"));
3966        }
3967    }
3968
3969    if let Term::App(ctor, arg) = term {
3970        if let Term::Global(name) = ctor.as_ref() {
3971            if name == "UType" {
3972                if let Term::Lit(Literal::Int(n)) = arg.as_ref() {
3973                    return Some(sname_app("UType", slit(*n)));
3974                }
3975            }
3976        }
3977    }
3978
3979    None
3980}
3981
3982// -------------------------------------------------------------------------
3983// Diagonalization (Self-Reference)
3984// -------------------------------------------------------------------------
3985
3986/// The diagonal function: syn_diag x = syn_subst (syn_quote x) 0 x
3987///
3988/// This takes a term x with free variable 0, quotes x to get its construction
3989/// code, then substitutes that code for variable 0 in x.
3990fn try_syn_diag_reduce(ctx: &Context, term: &Term) -> Option<Term> {
3991    // Step 1: Quote the term
3992    let quoted = try_syn_quote_reduce(ctx, term)?;
3993
3994    // Step 2: Substitute the quoted form for variable 0 in the original term
3995    try_syn_subst_reduce(ctx, &quoted, 0, term)
3996}
3997
3998// -------------------------------------------------------------------------
3999// Inference Rules
4000// -------------------------------------------------------------------------
4001
4002/// Extract the conclusion from a derivation.
4003///
4004/// concludes d:
4005/// - DAxiom P → P
4006/// - DModusPonens d_impl d_ant → extract B from (Implies A B) if A matches antecedent
4007/// - DUnivIntro d → wrap conclusion in Forall
4008/// - DUnivElim d term → substitute term into forall body
4009/// - DRefl T a → Eq T a a
4010fn try_concludes_reduce(ctx: &Context, deriv: &Term) -> Option<Term> {
4011    // A proof SCRIPT `try_script names goal` concludes its goal iff evaluating the script proves it.
4012    // A failed or malformed script concludes the error sentinel, so the soundness gate rejects it.
4013    if let Some((list, goal)) = extract_try_script(deriv) {
4014        return match extract_script_names(&list) {
4015            // The script proved the goal — but the CONCLUSION this door reports is compared
4016            // against the stated goal by the REPL's soundness gate, so it must be a finished
4017            // normal form. An abandoned reduction reported as the conclusion would let the gate
4018            // match two partial terms and accept a theorem nothing certified.
4019            Some(names) if eval_script_names(ctx, &names, &[], &goal) => {
4020                match normalize_checked(ctx, &goal) {
4021                    Ok(normal) => Some(normal),
4022                    Err(_) => Some(make_sname_error()),
4023                }
4024            }
4025            _ => Some(make_sname_error()),
4026        };
4027    }
4028
4029    // DAxiom P → P
4030    if let Term::App(ctor_term, p) = deriv {
4031        if let Term::Global(ctor_name) = ctor_term.as_ref() {
4032            if ctor_name == "DAxiom" {
4033                return Some(p.as_ref().clone());
4034            }
4035            if ctor_name == "DUnivIntro" {
4036                // Get conclusion of inner derivation
4037                let inner_conc = try_concludes_reduce(ctx, p)?;
4038                // Lift it by 1 and wrap in Forall
4039                let lifted = try_syn_lift_reduce(ctx, 1, 0, &inner_conc)?;
4040                return Some(make_forall_syntax(&lifted));
4041            }
4042            if ctor_name == "DCompute" {
4043                // DCompute goal: verify goal is Eq T A B and eval(A) == eval(B)
4044                return try_dcompute_conclude(ctx, p);
4045            }
4046            if ctor_name == "DRingSolve" {
4047                // DRingSolve goal: verify goal is Eq T A B and polynomials are equal
4048                return try_dring_solve_conclude(ctx, p);
4049            }
4050            if ctor_name == "DLiaSolve" {
4051                // DLiaSolve goal: verify goal is an inequality and LIA proves it
4052                return try_dlia_solve_conclude(ctx, p);
4053            }
4054            if ctor_name == "DccSolve" {
4055                // DccSolve goal: verify goal by congruence closure
4056                return try_dcc_solve_conclude(ctx, p);
4057            }
4058            if ctor_name == "DSimpSolve" {
4059                // DSimpSolve goal: verify goal by simplification
4060                return try_dsimp_solve_conclude(ctx, p);
4061            }
4062            if ctor_name == "DOmegaSolve" {
4063                // DOmegaSolve goal: verify goal by integer arithmetic
4064                return try_domega_solve_conclude(ctx, p);
4065            }
4066            if ctor_name == "DAutoSolve" {
4067                // DAutoSolve goal: verify goal by trying all tactics
4068                return try_dauto_solve_conclude(ctx, p);
4069            }
4070            if ctor_name == "DBitblastSolve" {
4071                // DBitblastSolve goal: verify Eq Bit by normalization
4072                return try_dbitblast_solve_conclude(ctx, p);
4073            }
4074            if ctor_name == "DTabulateSolve" {
4075                // DTabulateSolve goal: verify universal Bit by exhaustion
4076                return try_dtabulate_solve_conclude(ctx, p);
4077            }
4078            if ctor_name == "DHwAutoSolve" {
4079                // DHwAutoSolve goal: verify by hw tactic chain
4080                return try_dhw_auto_solve_conclude(ctx, p);
4081            }
4082            if ctor_name == "DInversion" {
4083                // DInversion hyp_type: verify no constructor can match, return False
4084                return try_dinversion_conclude(ctx, p);
4085            }
4086        }
4087    }
4088
4089    // DRewrite eq_proof old_goal new_goal → new_goal (if verified)
4090    // Pattern: App(App(App(DRewrite, eq_proof), old_goal), new_goal)
4091    if let Term::App(partial1, new_goal) = deriv {
4092        if let Term::App(partial2, old_goal) = partial1.as_ref() {
4093            if let Term::App(ctor_term, eq_proof) = partial2.as_ref() {
4094                if let Term::Global(ctor_name) = ctor_term.as_ref() {
4095                    if ctor_name == "DRewrite" {
4096                        return try_drewrite_conclude(ctx, eq_proof, old_goal, new_goal);
4097                    }
4098                }
4099            }
4100        }
4101    }
4102
4103    // DDestruct ind_type motive cases → Forall ind_type motive (if verified)
4104    // Pattern: App(App(App(DDestruct, ind_type), motive), cases)
4105    if let Term::App(partial1, cases) = deriv {
4106        if let Term::App(partial2, motive) = partial1.as_ref() {
4107            if let Term::App(ctor_term, ind_type) = partial2.as_ref() {
4108                if let Term::Global(ctor_name) = ctor_term.as_ref() {
4109                    if ctor_name == "DDestruct" {
4110                        return try_ddestruct_conclude(ctx, ind_type, motive, cases);
4111                    }
4112                }
4113            }
4114        }
4115    }
4116
4117    // DApply hyp_name hyp_proof old_goal new_goal → new_goal (if verified)
4118    // Pattern: App(App(App(App(DApply, hyp_name), hyp_proof), old_goal), new_goal)
4119    if let Term::App(partial1, new_goal) = deriv {
4120        if let Term::App(partial2, old_goal) = partial1.as_ref() {
4121            if let Term::App(partial3, hyp_proof) = partial2.as_ref() {
4122                if let Term::App(ctor_term, _) = partial3.as_ref() {
4123                    if let Term::Global(ctor_name) = ctor_term.as_ref() {
4124                        if ctor_name == "DApply" {
4125                            return try_dapply_conclude(ctx, hyp_proof, old_goal, new_goal);
4126                        }
4127                    }
4128                }
4129            }
4130        }
4131    }
4132
4133    // DRefl T a → Eq T a a
4134    if let Term::App(partial, a) = deriv {
4135        if let Term::App(ctor_term, t) = partial.as_ref() {
4136            if let Term::Global(ctor_name) = ctor_term.as_ref() {
4137                if ctor_name == "DRefl" {
4138                    return Some(make_eq_syntax(t.as_ref(), a.as_ref()));
4139                }
4140                if ctor_name == "DCong" {
4141                    // DCong context eq_proof → Eq T (f a) (f b)
4142                    // where context = SLam T body, eq_proof proves Eq T a b
4143                    return try_dcong_conclude(ctx, t, a);
4144                }
4145            }
4146        }
4147    }
4148
4149    // DModusPonens d_impl d_ant
4150    if let Term::App(partial, d_ant) = deriv {
4151        if let Term::App(ctor_term, d_impl) = partial.as_ref() {
4152            if let Term::Global(ctor_name) = ctor_term.as_ref() {
4153                if ctor_name == "DModusPonens" {
4154                    // Get conclusions of both derivations
4155                    let impl_conc = try_concludes_reduce(ctx, d_impl)?;
4156                    let ant_conc = try_concludes_reduce(ctx, d_ant)?;
4157
4158                    // Check if impl_conc = SApp (SApp (SName "Implies") A) B
4159                    if let Some((a, b)) = extract_implication(&impl_conc) {
4160                        // Check if ant_conc equals A
4161                        if syntax_equal(&ant_conc, &a) {
4162                            return Some(b);
4163                        }
4164                    }
4165                    // Invalid modus ponens
4166                    return Some(make_sname_error());
4167                }
4168                if ctor_name == "DUnivElim" {
4169                    // d_impl is the derivation, d_ant is the term to substitute
4170                    let conc = try_concludes_reduce(ctx, d_impl)?;
4171                    if let Some(body) = extract_forall_body(&conc) {
4172                        // Substitute d_ant for var 0 in body
4173                        return try_syn_subst_reduce(ctx, d_ant, 0, &body);
4174                    }
4175                    // Invalid universal elimination
4176                    return Some(make_sname_error());
4177                }
4178            }
4179        }
4180    }
4181
4182    // DInduction motive base step → Forall Nat motive (if verified)
4183    // Pattern: App(App(App(DInduction, motive), base), step)
4184    if let Term::App(partial1, step) = deriv {
4185        if let Term::App(partial2, base) = partial1.as_ref() {
4186            if let Term::App(ctor_term, motive) = partial2.as_ref() {
4187                if let Term::Global(ctor_name) = ctor_term.as_ref() {
4188                    if ctor_name == "DInduction" {
4189                        return try_dinduction_reduce(ctx, motive, base, step);
4190                    }
4191                }
4192            }
4193        }
4194    }
4195
4196    // DElim ind_type motive cases → Forall ind_type motive (if verified)
4197    // Pattern: App(App(App(DElim, ind_type), motive), cases)
4198    if let Term::App(partial1, cases) = deriv {
4199        if let Term::App(partial2, motive) = partial1.as_ref() {
4200            if let Term::App(ctor_term, ind_type) = partial2.as_ref() {
4201                if let Term::Global(ctor_name) = ctor_term.as_ref() {
4202                    if ctor_name == "DElim" {
4203                        return try_delim_conclude(ctx, ind_type, motive, cases);
4204                    }
4205                }
4206            }
4207        }
4208    }
4209
4210    None
4211}
4212
4213/// **THE ONE READER OF AN IMPLICATION**, whatever it happens to be spelled as.
4214///
4215/// The reflected surface has THREE spellings of `A → B`, and until this function they never met:
4216///
4217/// * `SApp (SApp (SName "implies") A) B` — lower case, what `intro`, `decide`, `assumption` and
4218///   the simp/cc goal readers build and match;
4219/// * `SApp (SApp (SName "Implies") A) B` — capitalised, what `make_implies_syntax` builds, so
4220///   every induction STEP case was stated in a dialect no script step could read;
4221/// * a NON-DEPENDENT `SPi A B` — what the literate `Statement:` surface produces, because the
4222///   infix `implies` desugars to a `Pi { param: "_" }` and `term_to_syntax` reflects a `Pi`
4223///   faithfully as an `SPi`.
4224///
4225/// One spelling per producer and a different one per consumer is a seam, not a feature, and it
4226/// was observable: `## Theorem: P1 Statement: (implies True True). Proof: auto.` certified while
4227/// `## Theorem: P2 Statement: True implies True. Proof: auto.` — the SAME proposition, written
4228/// the way the documentation teaches — did not, and `intro. assumption.` failed on the infix one
4229/// too.
4230///
4231/// A DEPENDENT `SPi` is a QUANTIFIER and is refused here: its body mentions the bound variable,
4232/// so discharging the antecedent does not hand you the conclusion. The test is conservative on
4233/// purpose — a body mentioning ANY de Bruijn index is declined rather than renumbered, because
4234/// re-indexing it wrongly would hand a tactic the wrong proposition and it would prove THAT.
4235fn as_implication(term: &Term) -> Option<(Term, Term)> {
4236    if let Some(pair) = extract_sapp2(term, "implies") {
4237        return Some(pair);
4238    }
4239    if let Some(pair) = extract_sapp2(term, "Implies") {
4240        return Some(pair);
4241    }
4242    let (antecedent, consequent) = extract_spi(term)?;
4243    if syntax_mentions_svar(&consequent) {
4244        return None;
4245    }
4246    Some((antecedent, consequent))
4247}
4248
4249/// Whether a reflected term mentions any de Bruijn index — `SVar n` for any `n`.
4250fn syntax_mentions_svar(term: &Term) -> bool {
4251    match term {
4252        Term::App(f, x) => {
4253            if let Term::Global(ctor) = f.as_ref() {
4254                if ctor == "SVar" {
4255                    return true;
4256                }
4257            }
4258            syntax_mentions_svar(f) || syntax_mentions_svar(x)
4259        }
4260        _ => false,
4261    }
4262}
4263
4264/// Extract (A, B) from an implication, in any of its three spellings — see [`as_implication`],
4265/// which this is now a name for. Kept because `DModusPonens` and the congruence-closure reader
4266/// both call it by this name.
4267fn extract_implication(term: &Term) -> Option<(Term, Term)> {
4268    as_implication(term)
4269}
4270
4271/// Extract all hypotheses from a chain of nested implications.
4272///
4273/// For `A -> B -> C`, returns `([A, B], C)`.
4274/// For non-implications, returns `([], term)`.
4275fn extract_implications(term: &Term) -> Option<(Vec<Term>, Term)> {
4276    let mut hyps = Vec::new();
4277    let mut current = term.clone();
4278
4279    while let Some((hyp, rest)) = extract_implication(&current) {
4280        hyps.push(hyp);
4281        current = rest;
4282    }
4283
4284    if hyps.is_empty() {
4285        None
4286    } else {
4287        Some((hyps, current))
4288    }
4289}
4290
4291/// Extract body from SApp (SApp (SName "Forall") T) (SLam T body)
4292///
4293/// In kernel representation:
4294/// Extract body from Forall syntax (two forms supported):
4295/// Form 1: SApp (SName "Forall") (SLam T body)
4296/// Form 2: SApp (SApp (SName "Forall") T) (SLam T body)
4297fn extract_forall_body(term: &Term) -> Option<Term> {
4298    // term = App(App(SApp, X), lam)
4299    if let Term::App(outer, lam) = term {
4300        if let Term::App(sapp_outer, x) = outer.as_ref() {
4301            if let Term::Global(ctor) = sapp_outer.as_ref() {
4302                if ctor == "SApp" {
4303                    // Form 1: X = App(SName, "Forall")
4304                    if let Term::App(sname, text) = x.as_ref() {
4305                        if let Term::Global(sname_ctor) = sname.as_ref() {
4306                            if sname_ctor == "SName" {
4307                                if let Term::Lit(Literal::Text(s)) = text.as_ref() {
4308                                    if s == "Forall" {
4309                                        // Extract body from SLam
4310                                        return extract_slam_body(lam);
4311                                    }
4312                                }
4313                            }
4314                        }
4315                    }
4316
4317                    // Form 2: X = App(App(SApp, App(SName, "Forall")), T)
4318                    if let Term::App(inner, _t) = x.as_ref() {
4319                        if let Term::App(sapp_inner, sname_forall) = inner.as_ref() {
4320                            if let Term::Global(ctor2) = sapp_inner.as_ref() {
4321                                if ctor2 == "SApp" {
4322                                    if let Term::App(sname, text) = sname_forall.as_ref() {
4323                                        if let Term::Global(sname_ctor) = sname.as_ref() {
4324                                            if sname_ctor == "SName" {
4325                                                if let Term::Lit(Literal::Text(s)) = text.as_ref() {
4326                                                    if s == "Forall" {
4327                                                        return extract_slam_body(lam);
4328                                                    }
4329                                                }
4330                                            }
4331                                        }
4332                                    }
4333                                }
4334                            }
4335                        }
4336                    }
4337                }
4338            }
4339        }
4340    }
4341    None
4342}
4343
4344/// Extract body from ((SLam T) body)
4345fn extract_slam_body(term: &Term) -> Option<Term> {
4346    if let Term::App(inner, body) = term {
4347        if let Term::App(slam, _t) = inner.as_ref() {
4348            if let Term::Global(name) = slam.as_ref() {
4349                if name == "SLam" {
4350                    return Some(body.as_ref().clone());
4351                }
4352            }
4353        }
4354    }
4355    None
4356}
4357
4358/// Equality of reflected `Syntax` propositions: structural, except that the two spellings of
4359/// `Forall` are one proposition.
4360///
4361/// The encoding spells `Forall` two ways, and [`extract_forall_body`] reads both: Form 1,
4362/// `Forall (SLam T b)`, and Form 2, `Forall T (SLam T b)`, whose domain repeats the one the λ
4363/// carries. Every certifying door asks "is this the proposition that was owed?" through this one
4364/// comparison, and owed formulas are built in Form 2 ([`make_forall_syntax_with_type`]), so a
4365/// proof spelled in Form 1 compares equal. It is not a relaxation: a domain that differs, in
4366/// either spelling, still compares unequal.
4367///
4368/// A reflected `Syntax` value is a tree of constructor applications, so the walk descends through
4369/// `App` and compares every other node structurally. It allocates nothing, and the `a == b` fast
4370/// path keeps the common case at one structural comparison.
4371fn syntax_equal(a: &Term, b: &Term) -> bool {
4372    a == b || syntax_equal_modulo_forall_spelling(a, b)
4373}
4374
4375fn syntax_equal_modulo_forall_spelling(a: &Term, b: &Term) -> bool {
4376    match (reflected_forall(a), reflected_forall(b)) {
4377        (Some((domain_a, lam_a)), Some((domain_b, lam_b))) => {
4378            syntax_equal_modulo_forall_spelling(domain_a, domain_b)
4379                && syntax_equal_modulo_forall_spelling(lam_a, lam_b)
4380        }
4381        (None, None) => match (a, b) {
4382            (Term::App(f_a, x_a), Term::App(f_b, x_b)) => {
4383                syntax_equal_modulo_forall_spelling(f_a, f_b)
4384                    && syntax_equal_modulo_forall_spelling(x_a, x_b)
4385            }
4386            _ => a == b,
4387        },
4388        _ => false,
4389    }
4390}
4391
4392/// The domain and λ of a reflected `Forall` in either spelling: Form 2 states its domain, Form 1
4393/// reads it off its `SLam`. A Form-1 `Forall` applied to anything but an `SLam` has no domain to
4394/// read and is not recognised.
4395fn reflected_forall(term: &Term) -> Option<(&Term, &Term)> {
4396    fn sapp_parts(t: &Term) -> Option<(&Term, &Term)> {
4397        let Term::App(outer, arg) = t else {
4398            return None;
4399        };
4400        let Term::App(ctor, func) = outer.as_ref() else {
4401            return None;
4402        };
4403        match ctor.as_ref() {
4404            Term::Global(name) if name == "SApp" => Some((func.as_ref(), arg.as_ref())),
4405            _ => None,
4406        }
4407    }
4408    fn slam_domain(t: &Term) -> Option<&Term> {
4409        let Term::App(outer, _body) = t else {
4410            return None;
4411        };
4412        let Term::App(ctor, domain) = outer.as_ref() else {
4413            return None;
4414        };
4415        match ctor.as_ref() {
4416            Term::Global(name) if name == "SLam" => Some(domain.as_ref()),
4417            _ => None,
4418        }
4419    }
4420
4421    let (head, lam) = sapp_parts(term)?;
4422    if is_sname_with_value(head, "Forall") {
4423        return Some((slam_domain(lam)?, lam));
4424    }
4425    let (forall, domain) = sapp_parts(head)?;
4426    is_sname_with_value(forall, "Forall").then_some((domain, lam))
4427}
4428
4429/// The goal a `*_conclude` door is about to CERTIFY, normalised through the HONEST face.
4430///
4431/// `None` means the goal's own reduction did not finish, and the door must refuse.
4432///
4433/// Every certifying door began `let norm_goal = normalize(ctx, goal);` — the BEST-EFFORT face,
4434/// which hands back HOW FAR IT GOT, applied to the very term whose truth is about to be
4435/// certified. So a goal whose normalisation was abandoned reached the checker as a PARTIAL
4436/// goal, was decided about, and was then returned as the concluded statement: the door
4437/// certified something other than what it was asked about, with nothing anywhere saying so.
4438/// That is DEFECT 9 at the door layer, and `simp_compute_check` and `try_dcompute_conclude`
4439/// already make exactly this argument about the two SIDES of the equality while taking the
4440/// goal itself from the unchecked face.
4441///
4442/// ONE helper rather than sixteen open-coded `normalize_checked` calls, because a door added
4443/// later copies the line above it: the pit of success is that the only thing there is to copy
4444/// is the honest one.
4445fn goal_to_certify(ctx: &Context, goal: &Term) -> Option<Term> {
4446    normalize_checked(ctx, goal).ok()
4447}
4448
4449/// Build SName "Error"
4450fn make_sname_error() -> Term {
4451    Term::App(
4452        Box::new(Term::Global("SName".to_string())),
4453        Box::new(Term::Lit(Literal::Text("Error".to_string()))),
4454    )
4455}
4456
4457/// Build SName from a string
4458fn make_sname(s: &str) -> Term {
4459    Term::App(
4460        Box::new(Term::Global("SName".to_string())),
4461        Box::new(Term::Lit(Literal::Text(s.to_string()))),
4462    )
4463}
4464
4465/// Build SLit from an integer
4466fn make_slit(n: i64) -> Term {
4467    Term::App(
4468        Box::new(Term::Global("SLit".to_string())),
4469        Box::new(Term::Lit(Literal::Int(n))),
4470    )
4471}
4472
4473/// Build SApp f x
4474fn make_sapp(f: Term, x: Term) -> Term {
4475    Term::App(
4476        Box::new(Term::App(
4477            Box::new(Term::Global("SApp".to_string())),
4478            Box::new(f),
4479        )),
4480        Box::new(x),
4481    )
4482}
4483
4484/// Build SPi A B
4485fn make_spi(a: Term, b: Term) -> Term {
4486    Term::App(
4487        Box::new(Term::App(
4488            Box::new(Term::Global("SPi".to_string())),
4489            Box::new(a),
4490        )),
4491        Box::new(b),
4492    )
4493}
4494
4495/// Build SLam A b
4496fn make_slam(a: Term, b: Term) -> Term {
4497    Term::App(
4498        Box::new(Term::App(
4499            Box::new(Term::Global("SLam".to_string())),
4500            Box::new(a),
4501        )),
4502        Box::new(b),
4503    )
4504}
4505
4506/// Build SSort u
4507fn make_ssort(u: Term) -> Term {
4508    Term::App(Box::new(Term::Global("SSort".to_string())), Box::new(u))
4509}
4510
4511/// Build SVar n
4512fn make_svar(n: i64) -> Term {
4513    Term::App(
4514        Box::new(Term::Global("SVar".to_string())),
4515        Box::new(Term::Lit(Literal::Int(n))),
4516    )
4517}
4518
4519/// Convert a kernel Term to Syntax encoding (S* form).
4520///
4521/// This converts semantic Terms to their syntactic representation:
4522/// - Global(n) → SName n
4523/// - Var(n) → SName n (for named variables)
4524/// - App(f, x) → SApp (convert f) (convert x)
4525/// - Pi { param, param_type, body_type } → SPi (convert param_type) (convert body_type)
4526/// - Lambda { param, param_type, body } → SLam (convert param_type) (convert body)
4527/// - Sort(Type n) → SSort (UType n)
4528/// - Sort(Prop) → SSort UProp
4529/// - Lit(Int n) → SLit n
4530/// - Lit(Text s) → SName s
4531fn term_to_syntax(term: &Term) -> Option<Term> {
4532    match term {
4533        Term::Global(name) => Some(make_sname(name)),
4534
4535        Term::Const { name, .. } => Some(make_sname(name)),
4536
4537        Term::Var(name) => {
4538            // Named variables become SName in syntax representation
4539            Some(make_sname(name))
4540        }
4541
4542        Term::App(f, x) => {
4543            let sf = term_to_syntax(f)?;
4544            let sx = term_to_syntax(x)?;
4545            Some(make_sapp(sf, sx))
4546        }
4547
4548        Term::Pi { param_type, body_type, .. } => {
4549            let sp = term_to_syntax(param_type)?;
4550            let sb = term_to_syntax(body_type)?;
4551            Some(make_spi(sp, sb))
4552        }
4553
4554        Term::Lambda { param_type, body, .. } => {
4555            let sp = term_to_syntax(param_type)?;
4556            let sb = term_to_syntax(body)?;
4557            Some(make_slam(sp, sb))
4558        }
4559
4560        Term::Sort(univ) => Some(make_ssort(univ_to_syntax(univ))),
4561
4562        Term::Lit(Literal::Int(n)) => Some(make_slit(*n)),
4563
4564        Term::Lit(Literal::Text(s)) => Some(make_sname(s)),
4565
4566        // Float, Duration, Date, and Moment literals - skip for now as they're rarely used in proofs
4567        Term::Lit(Literal::Float(_))
4568        | Term::Lit(Literal::Duration(_))
4569        | Term::Lit(Literal::Date(_))
4570        | Term::Lit(Literal::Moment(_))
4571        // Neither a BigInt nor a Nat literal fits the syntax layer's machine-int `SLit`.
4572        | Term::Lit(Literal::BigInt(_))
4573        | Term::Lit(Literal::Nat(_)) => None,
4574
4575        // Match expressions, Fix, Let, and Hole are complex - skip for now
4576        Term::Match { .. } | Term::Fix { .. } | Term::MutualFix { .. } | Term::Let { .. }
4577        | Term::Hole => None,
4578
4579        // The syntax layer encodes kernel meaning; an annotation is not part of it.
4580        Term::Annotated { term, .. } => term_to_syntax(term),
4581    }
4582}
4583
4584/// Build DHint derivation that references a hint by name.
4585///
4586/// Uses DAxiom (SName "hint_name") to indicate the proof uses this hint.
4587fn make_hint_derivation(goal: &Term) -> Term {
4588    // DAutoSolve goal: auto succeeded; which hint was used shows when tracing.
4589    Term::App(
4590        Box::new(Term::Global("DAutoSolve".to_string())),
4591        Box::new(goal.clone()),
4592    )
4593}
4594
4595/// Try to apply a hint to prove a goal.
4596///
4597/// Returns Some(derivation) if the hint's type matches the goal,
4598/// otherwise returns None.
4599fn try_apply_hint(ctx: &Context, hint_type: &Term, goal: &Term) -> Option<Term> {
4600    // Convert hint type to syntax form
4601    let hint_syntax = term_to_syntax(hint_type)?;
4602
4603    // Normalize both for comparison
4604    let norm_hint = normalize(ctx, &hint_syntax);
4605    let norm_goal = normalize(ctx, goal);
4606
4607    // Direct match: hint type equals goal
4608    if syntax_equal(&norm_hint, &norm_goal) {
4609        return Some(make_hint_derivation(goal));
4610    }
4611
4612    // Try backward chaining for implications: if hint is P → Q and goal is Q,
4613    // try to prove P using auto and then apply the hint
4614    if let Term::App(outer, q) = &hint_syntax {
4615        if let Term::App(pi_ctor, _p) = outer.as_ref() {
4616            if let Term::Global(name) = pi_ctor.as_ref() {
4617                if name == "SPi" {
4618                    // hint_type is SPi P Q, goal might be Q
4619                    let norm_q = normalize(ctx, q);
4620                    if syntax_equal(&norm_q, &norm_goal) {
4621                        // Need to prove P first, then apply hint
4622                        // This would require recursive auto call - skip for now
4623                        // to avoid infinite recursion
4624                    }
4625                }
4626            }
4627        }
4628    }
4629
4630    None
4631}
4632
4633/// Build Forall Type0 (SLam Type0 body)
4634fn make_forall_syntax(body: &Term) -> Term {
4635    let type0 = Term::App(
4636        Box::new(Term::Global("SSort".to_string())),
4637        Box::new(Term::App(
4638            Box::new(Term::Global("UType".to_string())),
4639            Box::new(Term::Lit(Literal::Int(0))),
4640        )),
4641    );
4642
4643    // SLam Type0 body
4644    let slam = Term::App(
4645        Box::new(Term::App(
4646            Box::new(Term::Global("SLam".to_string())),
4647            Box::new(type0.clone()),
4648        )),
4649        Box::new(body.clone()),
4650    );
4651
4652    // SApp (SApp (SName "Forall") Type0) slam
4653    Term::App(
4654        Box::new(Term::App(
4655            Box::new(Term::Global("SApp".to_string())),
4656            Box::new(Term::App(
4657                Box::new(Term::App(
4658                    Box::new(Term::Global("SApp".to_string())),
4659                    Box::new(Term::App(
4660                        Box::new(Term::Global("SName".to_string())),
4661                        Box::new(Term::Lit(Literal::Text("Forall".to_string()))),
4662                    )),
4663                )),
4664                Box::new(type0),
4665            )),
4666        )),
4667        Box::new(slam),
4668    )
4669}
4670
4671// -------------------------------------------------------------------------
4672// Core Tactics
4673// -------------------------------------------------------------------------
4674
4675/// Build SApp (SApp (SApp (SName "Eq") type_s) term) term
4676///
4677/// Constructs the Syntax representation of (Eq type_s term term)
4678fn make_eq_syntax(type_s: &Term, term: &Term) -> Term {
4679    let eq_name = Term::App(
4680        Box::new(Term::Global("SName".to_string())),
4681        Box::new(Term::Lit(Literal::Text("Eq".to_string()))),
4682    );
4683
4684    // SApp (SName "Eq") type_s
4685    let app1 = Term::App(
4686        Box::new(Term::App(
4687            Box::new(Term::Global("SApp".to_string())),
4688            Box::new(eq_name),
4689        )),
4690        Box::new(type_s.clone()),
4691    );
4692
4693    // SApp (SApp (SName "Eq") type_s) term
4694    let app2 = Term::App(
4695        Box::new(Term::App(
4696            Box::new(Term::Global("SApp".to_string())),
4697            Box::new(app1),
4698        )),
4699        Box::new(term.clone()),
4700    );
4701
4702    // SApp (SApp (SApp (SName "Eq") type_s) term) term
4703    Term::App(
4704        Box::new(Term::App(
4705            Box::new(Term::Global("SApp".to_string())),
4706            Box::new(app2),
4707        )),
4708        Box::new(term.clone()),
4709    )
4710}
4711
4712/// Extract (T, a, b) from SApp (SApp (SApp (SName "Eq") T) a) b
4713///
4714/// Pattern matches against the Syntax representation of (Eq T a b)
4715fn extract_eq(term: &Term) -> Option<(Term, Term, Term)> {
4716    // term = App(App(SApp, X), b)
4717    if let Term::App(outer, b) = term {
4718        if let Term::App(sapp_outer, x) = outer.as_ref() {
4719            if let Term::Global(ctor) = sapp_outer.as_ref() {
4720                if ctor == "SApp" {
4721                    // x = App(App(SApp, Y), a)
4722                    if let Term::App(inner, a) = x.as_ref() {
4723                        if let Term::App(sapp_inner, y) = inner.as_ref() {
4724                            if let Term::Global(ctor2) = sapp_inner.as_ref() {
4725                                if ctor2 == "SApp" {
4726                                    // y = App(App(SApp, eq_name), t)
4727                                    if let Term::App(inner2, t) = y.as_ref() {
4728                                        if let Term::App(sapp_inner2, sname_eq) = inner2.as_ref() {
4729                                            if let Term::Global(ctor3) = sapp_inner2.as_ref() {
4730                                                if ctor3 == "SApp" {
4731                                                    // sname_eq = App(SName, "Eq")
4732                                                    if let Term::App(sname, text) =
4733                                                        sname_eq.as_ref()
4734                                                    {
4735                                                        if let Term::Global(sname_ctor) =
4736                                                            sname.as_ref()
4737                                                        {
4738                                                            if sname_ctor == "SName" {
4739                                                                if let Term::Lit(Literal::Text(s)) =
4740                                                                    text.as_ref()
4741                                                                {
4742                                                                    if s == "Eq" {
4743                                                                        return Some((
4744                                                                            t.as_ref().clone(),
4745                                                                            a.as_ref().clone(),
4746                                                                            b.as_ref().clone(),
4747                                                                        ));
4748                                                                    }
4749                                                                }
4750                                                            }
4751                                                        }
4752                                                    }
4753                                                }
4754                                            }
4755                                        }
4756                                    }
4757                                }
4758                            }
4759                        }
4760                    }
4761                }
4762            }
4763        }
4764    }
4765    None
4766}
4767
4768/// Build DRefl type_s term
4769fn make_drefl(type_s: &Term, term: &Term) -> Term {
4770    let drefl = Term::Global("DRefl".to_string());
4771    let app1 = Term::App(Box::new(drefl), Box::new(type_s.clone()));
4772    Term::App(Box::new(app1), Box::new(term.clone()))
4773}
4774
4775/// Build DAxiom (SName "Error")
4776fn make_error_derivation() -> Term {
4777    let daxiom = Term::Global("DAxiom".to_string());
4778    let error = make_sname_error();
4779    Term::App(Box::new(daxiom), Box::new(error))
4780}
4781
4782/// Build DAxiom goal (identity derivation)
4783fn make_daxiom(goal: &Term) -> Term {
4784    let daxiom = Term::Global("DAxiom".to_string());
4785    Term::App(Box::new(daxiom), Box::new(goal.clone()))
4786}
4787
4788/// Reflexivity tactic: try to prove a goal by reflexivity.
4789///
4790/// try_refl goal:
4791/// - If goal matches (Eq T a b) and a == b, return DRefl T a
4792/// - Otherwise return DAxiom (SName "Error")
4793fn try_try_refl_reduce(ctx: &Context, goal: &Term) -> Option<Term> {
4794    // Normalize the goal first
4795    let norm_goal = normalize(ctx, goal);
4796
4797    // Pattern match: SApp (SApp (SApp (SName "Eq") T) a) b
4798    if let Some((type_s, left, right)) = extract_eq(&norm_goal) {
4799        // Check if left == right (structural equality)
4800        if syntax_equal(&left, &right) {
4801            // Success! Return DRefl T a
4802            return Some(make_drefl(&type_s, &left));
4803        }
4804    }
4805
4806    // Failure: return error derivation
4807    Some(make_error_derivation())
4808}
4809
4810// =============================================================================
4811// RING TACTIC (POLYNOMIAL EQUALITY)
4812// =============================================================================
4813
4814use crate::cc;
4815use crate::lia;
4816use crate::ring;
4817use crate::simp;
4818
4819/// Ring tactic: try to prove a goal by polynomial normalization.
4820///
4821/// try_ring goal:
4822/// - If goal matches (Eq T a b) where T is Int or Nat
4823/// - And poly(a) == poly(b) after normalization
4824/// - Returns DRingSolve goal
4825/// - Otherwise returns DAxiom (SName "Error")
4826fn try_try_ring_reduce(ctx: &Context, goal: &Term) -> Option<Term> {
4827    // Normalize the goal first
4828    let norm_goal = normalize(ctx, goal);
4829
4830    // Pattern match: SApp (SApp (SApp (SName "Eq") T) a) b
4831    if let Some((type_s, left, right)) = extract_eq(&norm_goal) {
4832        // Check type is Int or Nat (ring types)
4833        if !is_ring_type(&type_s) {
4834            return Some(make_error_derivation());
4835        }
4836
4837        // Reify both sides to polynomials (one interner: both sides must
4838        // agree on which named global is which variable)
4839        let mut vars = crate::reify::VarInterner::new();
4840        let poly_left = match ring::reify(&left, &mut vars) {
4841            Ok(p) => p,
4842            Err(_) => return Some(make_error_derivation()),
4843        };
4844        let poly_right = match ring::reify(&right, &mut vars) {
4845            Ok(p) => p,
4846            Err(_) => return Some(make_error_derivation()),
4847        };
4848
4849        // Check canonical equality
4850        if poly_left.canonical_eq(&poly_right) {
4851            // Success! Return DRingSolve goal
4852            return Some(Term::App(
4853                Box::new(Term::Global("DRingSolve".to_string())),
4854                Box::new(norm_goal),
4855            ));
4856        }
4857    }
4858
4859    // Failure: return error derivation
4860    Some(make_error_derivation())
4861}
4862
4863/// Verify DRingSolve proof.
4864///
4865/// DRingSolve goal → goal (if verified)
4866fn try_dring_solve_conclude(ctx: &Context, goal: &Term) -> Option<Term> {
4867    let Some(norm_goal) = goal_to_certify(ctx, goal) else {
4868        return Some(make_sname_error());
4869    };
4870
4871    // Extract T, lhs, rhs from Eq T lhs rhs
4872    if let Some((type_s, left, right)) = extract_eq(&norm_goal) {
4873        // Verify type is a ring type
4874        if !is_ring_type(&type_s) {
4875            return Some(make_sname_error());
4876        }
4877
4878        // Reify and verify (one interner across both sides)
4879        let mut vars = crate::reify::VarInterner::new();
4880        let poly_left = match ring::reify(&left, &mut vars) {
4881            Ok(p) => p,
4882            Err(_) => return Some(make_sname_error()),
4883        };
4884        let poly_right = match ring::reify(&right, &mut vars) {
4885            Ok(p) => p,
4886            Err(_) => return Some(make_sname_error()),
4887        };
4888
4889        if poly_left.canonical_eq(&poly_right) {
4890            return Some(norm_goal);
4891        }
4892    }
4893
4894    Some(make_sname_error())
4895}
4896
4897/// Check if a Syntax type is a ring type (Int or Nat)
4898fn is_ring_type(type_term: &Term) -> bool {
4899    if let Some(name) = extract_sname_from_syntax(type_term) {
4900        return name == "Int" || name == "Nat";
4901    }
4902    false
4903}
4904
4905/// Extract name from SName term
4906fn extract_sname_from_syntax(term: &Term) -> Option<String> {
4907    if let Term::App(ctor, arg) = term {
4908        if let Term::Global(name) = ctor.as_ref() {
4909            if name == "SName" {
4910                if let Term::Lit(Literal::Text(s)) = arg.as_ref() {
4911                    return Some(s.clone());
4912                }
4913            }
4914        }
4915    }
4916    None
4917}
4918
4919// =============================================================================
4920// LIA TACTIC (LINEAR INTEGER ARITHMETIC)
4921// =============================================================================
4922
4923/// LIA tactic: try to prove a goal by Fourier-Motzkin elimination.
4924///
4925/// try_lia goal:
4926/// - If goal matches (Lt/Le/Gt/Ge a b)
4927/// - And Fourier-Motzkin shows the negation is unsatisfiable
4928/// - Returns DLiaSolve goal
4929/// - Otherwise returns DAxiom (SName "Error")
4930fn try_try_lia_reduce(ctx: &Context, goal: &Term) -> Option<Term> {
4931    // Normalize the goal first
4932    let norm_goal = normalize(ctx, goal);
4933
4934    // Extract comparison: (SApp (SApp (SName "Lt"|"Le"|etc) a) b)
4935    if let Some((rel, lhs_term, rhs_term)) = lia::extract_comparison(&norm_goal) {
4936        // Reify both sides to linear expressions (one interner across both)
4937        let mut vars = crate::reify::VarInterner::new();
4938        let lhs = match lia::reify_linear(&lhs_term, &mut vars) {
4939            Ok(l) => l,
4940            Err(_) => return Some(make_error_derivation()),
4941        };
4942        let rhs = match lia::reify_linear(&rhs_term, &mut vars) {
4943            Ok(r) => r,
4944            Err(_) => return Some(make_error_derivation()),
4945        };
4946
4947        // Convert to negated constraint for validity checking
4948        if let Some(negated) = lia::goal_to_negated_constraint(&rel, &lhs, &rhs) {
4949            // If the negation is unsatisfiable, the goal is valid
4950            if lia::fourier_motzkin_unsat(&[negated]) {
4951                // Success! Return DLiaSolve goal
4952                return Some(Term::App(
4953                    Box::new(Term::Global("DLiaSolve".to_string())),
4954                    Box::new(norm_goal),
4955                ));
4956            }
4957        }
4958    }
4959
4960    // Failure: return error derivation
4961    Some(make_error_derivation())
4962}
4963
4964/// Verify DLiaSolve proof.
4965///
4966/// DLiaSolve goal → goal (if verified)
4967fn try_dlia_solve_conclude(ctx: &Context, goal: &Term) -> Option<Term> {
4968    let Some(norm_goal) = goal_to_certify(ctx, goal) else {
4969        return Some(make_sname_error());
4970    };
4971
4972    // Extract comparison and verify
4973    if let Some((rel, lhs_term, rhs_term)) = lia::extract_comparison(&norm_goal) {
4974        // Reify both sides (one interner across both)
4975        let mut vars = crate::reify::VarInterner::new();
4976        let lhs = match lia::reify_linear(&lhs_term, &mut vars) {
4977            Ok(l) => l,
4978            Err(_) => return Some(make_sname_error()),
4979        };
4980        let rhs = match lia::reify_linear(&rhs_term, &mut vars) {
4981            Ok(r) => r,
4982            Err(_) => return Some(make_sname_error()),
4983        };
4984
4985        // Verify via Fourier-Motzkin
4986        if let Some(negated) = lia::goal_to_negated_constraint(&rel, &lhs, &rhs) {
4987            if lia::fourier_motzkin_unsat(&[negated]) {
4988                return Some(norm_goal);
4989            }
4990        }
4991    }
4992
4993    Some(make_sname_error())
4994}
4995
4996// =============================================================================
4997// CONGRUENCE CLOSURE TACTIC
4998// =============================================================================
4999
5000/// CC tactic: try to prove a goal by congruence closure.
5001///
5002/// try_cc goal:
5003/// - If goal is a direct equality (Eq a b) or an implication with hypotheses
5004/// - And congruence closure shows the conclusion follows
5005/// - Returns DccSolve goal
5006/// - Otherwise returns DAxiom (SName "Error")
5007fn try_try_cc_reduce(ctx: &Context, goal: &Term) -> Option<Term> {
5008    // Normalize the goal first
5009    let norm_goal = normalize(ctx, goal);
5010
5011    // Use cc::check_goal which handles both:
5012    // - Direct equalities: (Eq a b)
5013    // - Implications: (implies (Eq x y) (Eq (f x) (f y)))
5014    if cc::check_goal(&norm_goal) {
5015        // Success! Return DccSolve goal
5016        return Some(Term::App(
5017            Box::new(Term::Global("DccSolve".to_string())),
5018            Box::new(norm_goal),
5019        ));
5020    }
5021
5022    // Failure: return error derivation
5023    Some(make_error_derivation())
5024}
5025
5026/// Verify DccSolve proof.
5027///
5028/// DccSolve goal → goal (if verified)
5029fn try_dcc_solve_conclude(ctx: &Context, goal: &Term) -> Option<Term> {
5030    let Some(norm_goal) = goal_to_certify(ctx, goal) else {
5031        return Some(make_sname_error());
5032    };
5033
5034    // Re-verify using congruence closure
5035    if cc::check_goal(&norm_goal) {
5036        return Some(norm_goal);
5037    }
5038
5039    Some(make_sname_error())
5040}
5041
5042// =============================================================================
5043// SIMP TACTIC (SIMPLIFICATION)
5044// =============================================================================
5045
5046/// try_simp goal:
5047/// - Prove equalities by simplification and arithmetic evaluation
5048/// - Handles hypotheses via implications: (implies (Eq x 0) (Eq (add x 1) 1))
5049/// - Returns DSimpSolve goal on success
5050/// - Otherwise returns DAxiom (SName "Error")
5051fn try_try_simp_reduce(ctx: &Context, goal: &Term) -> Option<Term> {
5052    // Normalize the goal first
5053    let norm_goal = normalize(ctx, goal);
5054
5055    // Use simp::check_goal (congruence closure) which handles:
5056    // - Reflexive equalities: (Eq a a)
5057    // - Constant folding: (Eq (add 2 3) 5)
5058    // - Hypothesis substitution: (implies (Eq x 0) (Eq (add x 1) 1))
5059    // …or decide the equality by REFLECTION + kernel normalization (unfolds `## To` user
5060    // definitions and evaluates arithmetic), so `(double 3) equals 6` is proven by computation.
5061    if simp::check_goal(&norm_goal) || simp_compute_check(ctx, &norm_goal) {
5062        // Success! Return DSimpSolve goal
5063        return Some(Term::App(
5064            Box::new(Term::Global("DSimpSolve".to_string())),
5065            Box::new(norm_goal),
5066        ));
5067    }
5068
5069    // Failure: return error derivation
5070    Some(make_error_derivation())
5071}
5072
5073/// Match a reflected 2-argument application `SApp (SApp (SName name) a) b`, returning `(a, b)`.
5074/// (`extract_eq` is the 3-argument `Eq T a b` counterpart.)
5075fn extract_sapp2(term: &Term, name: &str) -> Option<(Term, Term)> {
5076    if let Term::App(outer, b) = term {
5077        if let Term::App(sapp_outer, x) = outer.as_ref() {
5078            if matches!(sapp_outer.as_ref(), Term::Global(c) if c == "SApp") {
5079                if let Term::App(inner, a) = x.as_ref() {
5080                    if let Term::App(sapp_inner, sname_app) = inner.as_ref() {
5081                        if matches!(sapp_inner.as_ref(), Term::Global(c) if c == "SApp") {
5082                            if let Term::App(sname, text) = sname_app.as_ref() {
5083                                if matches!(sname.as_ref(), Term::Global(c) if c == "SName")
5084                                    && matches!(text.as_ref(), Term::Lit(Literal::Text(s)) if s == name)
5085                                {
5086                                    return Some((a.as_ref().clone(), b.as_ref().clone()));
5087                                }
5088                            }
5089                        }
5090                    }
5091                }
5092            }
5093        }
5094    }
5095    None
5096}
5097
5098/// Match a reflected 1-argument application `SApp (SName name) a`, returning `a` (e.g. `not P`).
5099fn extract_sapp1(term: &Term, name: &str) -> Option<Term> {
5100    if let Term::App(outer, arg) = term {
5101        if let Term::App(sapp, sname_app) = outer.as_ref() {
5102            if matches!(sapp.as_ref(), Term::Global(c) if c == "SApp") {
5103                if let Term::App(sname, text) = sname_app.as_ref() {
5104                    if matches!(sname.as_ref(), Term::Global(c) if c == "SName")
5105                        && matches!(text.as_ref(), Term::Lit(Literal::Text(s)) if s == name)
5106                    {
5107                        return Some(arg.as_ref().clone());
5108                    }
5109                }
5110            }
5111        }
5112    }
5113    None
5114}
5115
5116/// Reflect a `Syntax` term to a real term, normalize it, and read off an integer literal — the
5117/// ground value of a closed arithmetic expression, or `None` if it does not reduce to a literal.
5118fn eval_int(ctx: &Context, syntax: &Term) -> Option<i64> {
5119    let t = syntax_to_term(syntax)?;
5120    // `normalize_checked`, not `normalize`: a literal read out of an ABANDONED reduction is
5121    // not the value of the expression, and this feeds tactic decisions.
5122    if let Ok(Term::Lit(Literal::Int(n))) = normalize_checked(ctx, &t) {
5123        Some(n)
5124    } else {
5125        None
5126    }
5127}
5128
5129/// Structural substitution: replace every subterm equal to `from` with `to`. Used to apply an
5130/// equality hypothesis (`x = 0`) as a rewrite. First-order — recurses through applications, which
5131/// is all the reflected arithmetic goals contain.
5132fn subst_structural(t: &Term, from: &Term, to: &Term) -> Term {
5133    if t == from {
5134        return to.clone();
5135    }
5136    match t {
5137        Term::App(f, x) => Term::App(
5138            Box::new(subst_structural(f, from, to)),
5139            Box::new(subst_structural(x, from, to)),
5140        ),
5141        _ => t.clone(),
5142    }
5143}
5144
5145fn is_atom_var(t: &Term) -> bool {
5146    matches!(t, Term::Global(_) | Term::Var(_))
5147}
5148
5149/// Decide an (optionally hypothesis-guarded) equality goal by REFLECTION + kernel normalization.
5150///
5151/// Peels `implies H1 (implies H2 … conclusion)`, uses each equality hypothesis `a = b` as a rewrite
5152/// (substituting the variable side by the other), reflects the conclusion's sides back to real terms
5153/// and checks they share a normal form — i.e. definitional equality in the kernel. This unfolds user
5154/// `## To` definitions and EVALUATES arithmetic, which the congruence-closure [`simp::check_goal`]
5155/// cannot: `(double 3) equals 6` and `x = 0 → x + 1 = 1` both decide here.
5156///
5157/// When the variable rewrites do not close it, every equality hypothesis is used as a rewrite
5158/// between normal forms instead ([`rewrite_by_hypotheses`]), which is how an induction step
5159/// consumes its hypothesis.
5160///
5161/// Sound: same normal form ⟺ `refl`-inhabited; a false equality (`48 = 6·9` → `48` vs `54`) is
5162/// rejected, and a hypothesis neither pass can use is conservatively DROPPED (so we only ever
5163/// prove the conclusion when it holds under the rewrites we applied). Symbolic-only goals
5164/// (`add a b = add b a`) return `false` and are left to `ring`.
5165fn simp_compute_check(ctx: &Context, norm_goal: &Term) -> bool {
5166    // Peel hypotheses off nested implications.
5167    let mut hyps: Vec<Term> = Vec::new();
5168    let mut current = norm_goal.clone();
5169    while let Some((h, rest)) = as_implication(&current) {
5170        hyps.push(h);
5171        current = rest;
5172    }
5173
5174    // The conclusion must be an equality.
5175    let (_ty, left_s, right_s) = match extract_eq(&current) {
5176        Some(t) => t,
5177        None => return false,
5178    };
5179    let (mut l, mut r) = match (syntax_to_term(&left_s), syntax_to_term(&right_s)) {
5180        (Some(l), Some(r)) => (l, r),
5181        _ => return false,
5182    };
5183
5184    // A pending declaration is unavailable, even if reduction would erase it
5185    // or leave the same unresolved name on both sides.
5186    if ctx.has_pending_dependency(&l)
5187        || ctx.has_pending_dependency(&r)
5188        || syntax_to_term(&_ty).is_some_and(|ty| ctx.has_pending_dependency(&ty))
5189    {
5190        return false;
5191    }
5192
5193    let (conclusion_left, conclusion_right) = (l.clone(), r.clone());
5194
5195    // Apply each equality hypothesis as a rewrite (variable side → other side).
5196    for h in &hyps {
5197        let (hl, hr) = match extract_eq(h) {
5198            Some((_, hl_s, hr_s)) => match (syntax_to_term(&hl_s), syntax_to_term(&hr_s)) {
5199                (Some(hl), Some(hr)) => (hl, hr),
5200                _ => continue,
5201            },
5202            None => continue,
5203        };
5204        let (from, to) = if is_atom_var(&hl) {
5205            (hl, hr)
5206        } else if is_atom_var(&hr) {
5207            (hr, hl)
5208        } else {
5209            continue;
5210        };
5211        if ctx.has_pending_dependency(&from) || ctx.has_pending_dependency(&to) {
5212            return false;
5213        }
5214        l = subst_structural(&l, &from, &to);
5215        r = subst_structural(&r, &from, &to);
5216    }
5217
5218    // THE HONEST COMPARISON. `normalize` hands back how far it got, so "these two reached the
5219    // same normal form" and "these two were abandoned at the same place" are the same answer —
5220    // and this is a door that ACCEPTS PROOFS. Two ABANDONED reductions comparing equal
5221    // certifies nothing, so both sides must have actually FINISHED. `normalize_checked` is the
5222    // only way to know.
5223    if let (Ok(ln), Ok(rn)) = (normalize_checked(ctx, &l), normalize_checked(ctx, &r)) {
5224        if ln == rn {
5225            return true;
5226        }
5227    }
5228    rewrite_by_hypotheses(ctx, &hyps, conclusion_left, conclusion_right)
5229}
5230
5231/// How many rounds of rewrite-then-normalize [`rewrite_by_hypotheses`] runs before it gives up.
5232const MAX_HYPOTHESIS_REWRITE_ROUNDS: usize = 16;
5233
5234/// Decide `l = r` under the equality hypotheses by rewriting with them BETWEEN NORMAL FORMS —
5235/// what an induction step needs and a variable substitution cannot give.
5236///
5237/// The succ case of `0 + n = n` is `(0 + k = k) → 0 + (k+1) = k+1`. Substituting the variable
5238/// side of the hypothesis (`k := 0 + k`) only moves the problem; the step is closed by FOLDING:
5239/// `0 + (k+1)` computes to `Succ (0 + k)`, and the hypothesis turns that `0 + k` back into `k`.
5240/// Both sides of every hypothesis are normalized first, so the rule meets the goal in the one
5241/// shape reduction leaves it in — an unfolded `Nat_add` stuck on the open `k` is the same term
5242/// in the hypothesis and in the goal. A hypothesis with an atom on one side rewrites the other
5243/// side to that atom; any other hypothesis rewrites left to right.
5244///
5245/// Sound: every rewrite replaces a subterm `a` by `b` under the hypothesis `a = b`, and only at
5246/// a position reached through APPLICATIONS from the root — never under a binder, a match or a
5247/// fixpoint — so no variable of `a` or `b` is ever captured and the context around the rewritten
5248/// subterm is a plain first-order application, where `a = b` gives `C[a] = C[b]`. A hypothesis
5249/// whose sides cannot be normalized is dropped, which only proves less, and a pending
5250/// declaration anywhere refuses the whole goal, as the variable rewrites above do. The answer is
5251/// again two FINISHED normal forms compared, so an abandoned reduction certifies nothing, and a
5252/// hypothesis that cannot be oriented toward termination (`f k = g (f k)`) spends at most
5253/// [`MAX_HYPOTHESIS_REWRITE_ROUNDS`] rounds.
5254fn rewrite_by_hypotheses(ctx: &Context, hyps: &[Term], mut l: Term, mut r: Term) -> bool {
5255    let mut rules: Vec<(Term, Term)> = Vec::new();
5256    for h in hyps {
5257        let Some((_, a_s, b_s)) = extract_eq(h) else {
5258            continue;
5259        };
5260        let (Some(a), Some(b)) = (syntax_to_term(&a_s), syntax_to_term(&b_s)) else {
5261            continue;
5262        };
5263        if ctx.has_pending_dependency(&a) || ctx.has_pending_dependency(&b) {
5264            return false;
5265        }
5266        let (Ok(a), Ok(b)) = (normalize_checked(ctx, &a), normalize_checked(ctx, &b)) else {
5267            continue;
5268        };
5269        if a == b {
5270            continue;
5271        }
5272        rules.push(if is_atom_var(&a) && !is_atom_var(&b) {
5273            (b, a)
5274        } else {
5275            (a, b)
5276        });
5277    }
5278    if rules.is_empty() {
5279        return false;
5280    }
5281    for _ in 0..MAX_HYPOTHESIS_REWRITE_ROUNDS {
5282        let (Ok(ln), Ok(rn)) = (normalize_checked(ctx, &l), normalize_checked(ctx, &r)) else {
5283            return false;
5284        };
5285        if ln == rn {
5286            return true;
5287        }
5288        let (next_l, rewrote_l) = rewrite_application_spine(&ln, &rules);
5289        let (next_r, rewrote_r) = rewrite_application_spine(&rn, &rules);
5290        if !rewrote_l && !rewrote_r {
5291            return false;
5292        }
5293        l = next_l;
5294        r = next_r;
5295    }
5296    false
5297}
5298
5299/// Replace every outermost occurrence of a rule's left side by its right side, descending only
5300/// through applications (see [`rewrite_by_hypotheses`] for why that is the sound frontier), and
5301/// report whether anything was replaced.
5302fn rewrite_application_spine(t: &Term, rules: &[(Term, Term)]) -> (Term, bool) {
5303    if let Some((_, to)) = rules.iter().find(|(from, _)| from == t) {
5304        return (to.clone(), true);
5305    }
5306    match t {
5307        Term::App(f, x) => {
5308            let (f, rewrote_f) = rewrite_application_spine(f, rules);
5309            let (x, rewrote_x) = rewrite_application_spine(x, rules);
5310            (Term::App(Box::new(f), Box::new(x)), rewrote_f || rewrote_x)
5311        }
5312        _ => (t.clone(), false),
5313    }
5314}
5315
5316/// Verify DSimpSolve proof.
5317///
5318/// DSimpSolve goal → goal (if verified)
5319fn try_dsimp_solve_conclude(ctx: &Context, goal: &Term) -> Option<Term> {
5320    let Some(norm_goal) = goal_to_certify(ctx, goal) else {
5321        return Some(make_sname_error());
5322    };
5323
5324    // Re-verify using simplification OR reflection+normalization (same check as the reduce path).
5325    if simp::check_goal(&norm_goal) || simp_compute_check(ctx, &norm_goal) {
5326        return Some(norm_goal);
5327    }
5328
5329    Some(make_sname_error())
5330}
5331
5332// =============================================================================
5333// OMEGA TACTIC (TRUE INTEGER ARITHMETIC)
5334// =============================================================================
5335
5336/// try_omega goal:
5337///
5338/// Omega tactic using integer-aware Fourier-Motzkin elimination.
5339/// Unlike lia (which uses rationals), omega handles integers properly:
5340/// - x > 1 means x >= 2 (strict-to-nonstrict conversion)
5341/// - 3x <= 10 means x <= 3 (floor division)
5342///
5343/// - Extracts comparison (Lt, Le, Gt, Ge) from goal
5344/// - Reifies to integer linear expressions
5345/// - Converts to negated constraint (validity = negation is unsat)
5346/// - Applies omega test
5347/// - Returns DOmegaSolve goal on success
5348fn try_try_omega_reduce(ctx: &Context, goal: &Term) -> Option<Term> {
5349    let norm_goal = normalize(ctx, goal);
5350
5351    // Handle implications: extract hypotheses and check conclusion
5352    if let Some((hyps, conclusion)) = extract_implications(&norm_goal) {
5353        // Convert hypotheses to constraints. ONE interner spans hypotheses
5354        // and conclusion: a named global must be the same variable everywhere.
5355        let mut vars = crate::reify::VarInterner::new();
5356        let constraints = omega_hyp_constraints(&hyps, &mut vars);
5357
5358        // Now check if the conclusion is provable given the constraints
5359        if let Some((rel, lhs_term, rhs_term)) = omega::extract_comparison(&conclusion) {
5360            if let (Some(lhs), Some(rhs)) = (
5361                omega::reify_int_linear(&lhs_term, &mut vars),
5362                omega::reify_int_linear(&rhs_term, &mut vars),
5363            ) {
5364                // To prove the conclusion, check if its negation is unsat
5365                if let Some(neg_constraint) = omega::goal_to_negated_constraint(&rel, &lhs, &rhs) {
5366                    let mut all_constraints = constraints;
5367                    all_constraints.push(neg_constraint);
5368
5369                    if omega::omega_unsat(&all_constraints) {
5370                        return Some(Term::App(
5371                            Box::new(Term::Global("DOmegaSolve".to_string())),
5372                            Box::new(norm_goal),
5373                        ));
5374                    }
5375                }
5376            }
5377        }
5378
5379        // Failure
5380        return Some(make_error_derivation());
5381    }
5382
5383    // Direct comparison (no hypotheses)
5384    if let Some((rel, lhs_term, rhs_term)) = omega::extract_comparison(&norm_goal) {
5385        let mut vars = crate::reify::VarInterner::new();
5386        if let (Some(lhs), Some(rhs)) = (
5387            omega::reify_int_linear(&lhs_term, &mut vars),
5388            omega::reify_int_linear(&rhs_term, &mut vars),
5389        ) {
5390            if let Some(constraint) = omega::goal_to_negated_constraint(&rel, &lhs, &rhs) {
5391                if omega::omega_unsat(&[constraint]) {
5392                    return Some(Term::App(
5393                        Box::new(Term::Global("DOmegaSolve".to_string())),
5394                        Box::new(norm_goal),
5395                    ));
5396                }
5397            }
5398        }
5399    }
5400
5401    Some(make_error_derivation())
5402}
5403
5404/// Convert comparison hypotheses to omega constraints (facts).
5405///
5406/// A hypothesis is given, so it enters the system directly with integer
5407/// strict-to-nonstrict tightening: `a < b` becomes `a - b + 1 <= 0`.
5408fn omega_hyp_constraints(
5409    hyps: &[Term],
5410    vars: &mut crate::reify::VarInterner,
5411) -> Vec<omega::IntConstraint> {
5412    let one = omega::IntExpr::constant(1);
5413    let mut constraints = Vec::new();
5414    for hyp in hyps {
5415        if let Some((rel, lhs_term, rhs_term)) = omega::extract_comparison(hyp) {
5416            if let (Some(lhs), Some(rhs)) = (
5417                omega::reify_int_linear(&lhs_term, vars),
5418                omega::reify_int_linear(&rhs_term, vars),
5419            ) {
5420                match rel.as_str() {
5421                    "Lt" | "lt" => {
5422                        // a < b means a - b <= -1, i.e., (a - b + 1) <= 0
5423                        constraints.push(omega::IntConstraint {
5424                            expr: lhs.sub(&rhs).add(&one),
5425                            strict: false,
5426                        });
5427                    }
5428                    "Le" | "le" => {
5429                        // a <= b means a - b <= 0
5430                        constraints.push(omega::IntConstraint {
5431                            expr: lhs.sub(&rhs),
5432                            strict: false,
5433                        });
5434                    }
5435                    "Gt" | "gt" => {
5436                        // a > b means a - b >= 1, i.e., (b - a + 1) <= 0
5437                        constraints.push(omega::IntConstraint {
5438                            expr: rhs.sub(&lhs).add(&one),
5439                            strict: false,
5440                        });
5441                    }
5442                    "Ge" | "ge" => {
5443                        // a >= b means b - a <= 0
5444                        constraints.push(omega::IntConstraint {
5445                            expr: rhs.sub(&lhs),
5446                            strict: false,
5447                        });
5448                    }
5449                    _ => {}
5450                }
5451            }
5452        }
5453    }
5454    constraints
5455}
5456
5457/// Verify DOmegaSolve proof.
5458///
5459/// DOmegaSolve goal → goal (if verified)
5460fn try_domega_solve_conclude(ctx: &Context, goal: &Term) -> Option<Term> {
5461    let Some(norm_goal) = goal_to_certify(ctx, goal) else {
5462        return Some(make_sname_error());
5463    };
5464
5465    // Re-verify using omega test
5466    // Handle implications
5467    if let Some((hyps, conclusion)) = extract_implications(&norm_goal) {
5468        let mut vars = crate::reify::VarInterner::new();
5469        let constraints = omega_hyp_constraints(&hyps, &mut vars);
5470
5471        if let Some((rel, lhs_term, rhs_term)) = omega::extract_comparison(&conclusion) {
5472            if let (Some(lhs), Some(rhs)) = (
5473                omega::reify_int_linear(&lhs_term, &mut vars),
5474                omega::reify_int_linear(&rhs_term, &mut vars),
5475            ) {
5476                if let Some(neg_constraint) = omega::goal_to_negated_constraint(&rel, &lhs, &rhs) {
5477                    let mut all_constraints = constraints;
5478                    all_constraints.push(neg_constraint);
5479
5480                    if omega::omega_unsat(&all_constraints) {
5481                        return Some(norm_goal);
5482                    }
5483                }
5484            }
5485        }
5486
5487        return Some(make_sname_error());
5488    }
5489
5490    // Direct comparison
5491    if let Some((rel, lhs_term, rhs_term)) = omega::extract_comparison(&norm_goal) {
5492        let mut vars = crate::reify::VarInterner::new();
5493        if let (Some(lhs), Some(rhs)) = (
5494            omega::reify_int_linear(&lhs_term, &mut vars),
5495            omega::reify_int_linear(&rhs_term, &mut vars),
5496        ) {
5497            if let Some(constraint) = omega::goal_to_negated_constraint(&rel, &lhs, &rhs) {
5498                if omega::omega_unsat(&[constraint]) {
5499                    return Some(norm_goal);
5500                }
5501            }
5502        }
5503    }
5504
5505    Some(make_sname_error())
5506}
5507
5508// =============================================================================
5509// AUTO TACTIC (THE INFINITY GAUNTLET)
5510// =============================================================================
5511
5512/// Check if a derivation is an error derivation.
5513///
5514/// Error derivations have the pattern: DAxiom (SApp (SName "Error") ...)
5515fn is_error_derivation(term: &Term) -> bool {
5516    // Check for DAxiom constructor
5517    if let Term::App(ctor, arg) = term {
5518        if let Term::Global(name) = ctor.as_ref() {
5519            if name == "DAxiom" {
5520                // Check if arg is SName "Error" or SApp (SName "Error") ...
5521                if let Term::App(sname, inner) = arg.as_ref() {
5522                    if let Term::Global(sn) = sname.as_ref() {
5523                        if sn == "SName" {
5524                            if let Term::Lit(Literal::Text(s)) = inner.as_ref() {
5525                                return s == "Error";
5526                            }
5527                        }
5528                        if sn == "SApp" {
5529                            // Recursively check - could be SApp (SName "Error") ...
5530                            return true; // For now, treat any DAxiom as potential error
5531                        }
5532                    }
5533                }
5534                // DAxiom with SName "Error"
5535                if let Term::Global(sn) = arg.as_ref() {
5536                    // This shouldn't happen but just in case
5537                    return sn == "Error";
5538                }
5539                return true; // Any DAxiom is treated as error for auto purposes
5540            }
5541        }
5542    }
5543    false
5544}
5545
5546/// Auto tactic: tries each decision procedure in sequence.
5547///
5548/// Order: True/False → simp → ring → cc → omega → lia
5549/// Returns the first successful derivation, or error if all fail.
5550// =============================================================================
5551// HARDWARE TACTICS (bitblast, tabulate, hw_auto)
5552// =============================================================================
5553
5554/// Bitblast tactic: prove Eq Bit lhs rhs by normalizing both sides.
5555///
5556/// Operates on Syntax terms: SApp(SApp(SApp(SName("Eq"), SName("Bit")), lhs), rhs)
5557/// Normalizes lhs and rhs to concrete Bit values (B0/B1) and checks equality.
5558fn try_try_bitblast_reduce(ctx: &Context, goal: &Term) -> Option<Term> {
5559    let norm_goal = normalize(ctx, goal);
5560
5561    // Extract Eq T lhs rhs from Syntax
5562    if let Some((type_s, left, right)) = extract_eq_syntax_parts(&norm_goal) {
5563        // Check type is Bit (or BVec — for future extension)
5564        if !is_bit_type(&type_s) {
5565            return Some(make_error_derivation());
5566        }
5567
5568        // Evaluate both sides using syn_eval with delta reduction support.
5569        // syn_step now handles definition unfolding (delta reduction),
5570        // so syn_eval correctly reduces expressions like
5571        // SApp(SApp(SName("bit_and"), SName("B1")), SName("B0")) → SName("B0")
5572        let fuel = 1000;
5573        let left_eval = try_syn_eval_reduce(ctx, fuel, &left)?;
5574        let right_eval = try_syn_eval_reduce(ctx, fuel, &right)?;
5575
5576        if syntax_equal(&left_eval, &right_eval) {
5577            return Some(Term::App(
5578                Box::new(Term::Global("DBitblastSolve".to_string())),
5579                Box::new(norm_goal),
5580            ));
5581        }
5582    }
5583
5584    Some(make_error_derivation())
5585}
5586
5587/// Convert a Syntax deep embedding back to a kernel Term.
5588///
5589/// This is the proper bridge between the reflected Syntax representation
5590/// and the kernel's native Term language. The kernel normalizer handles
5591/// all reduction strategies (delta, iota, beta, fix), so reifying to Term
5592/// and normalizing there gives correct results for hardware gate expressions.
5593///
5594/// Handles: SName, SApp, SLit, SVar, SLam, SPi, SSort, SMatch
5595fn syntax_to_term(syntax: &Term) -> Option<Term> {
5596    if let Term::App(ctor, inner) = syntax {
5597        if let Term::Global(name) = ctor.as_ref() {
5598            match name.as_str() {
5599                "SName" => {
5600                    if let Term::Lit(Literal::Text(s)) = inner.as_ref() {
5601                        return Some(Term::Global(s.clone()));
5602                    }
5603                }
5604                "SLit" => {
5605                    if let Term::Lit(Literal::Int(n)) = inner.as_ref() {
5606                        return Some(Term::Lit(Literal::Int(*n)));
5607                    }
5608                }
5609                "SVar" => {
5610                    if let Term::Lit(Literal::Int(n)) = inner.as_ref() {
5611                        return Some(Term::Var(format!("v{}", n)));
5612                    }
5613                }
5614                "SGlobal" => {
5615                    if let Term::Lit(Literal::Int(n)) = inner.as_ref() {
5616                        return Some(Term::Var(format!("g{}", n)));
5617                    }
5618                }
5619                _ => {}
5620            }
5621        }
5622    }
5623
5624    // Two-argument constructors: SApp, SLam, SPi
5625    if let Term::App(outer, second) = syntax {
5626        if let Term::App(sctor, first) = outer.as_ref() {
5627            if let Term::Global(name) = sctor.as_ref() {
5628                match name.as_str() {
5629                    "SApp" => {
5630                        let f = syntax_to_term(first)?;
5631                        let x = syntax_to_term(second)?;
5632                        return Some(Term::App(Box::new(f), Box::new(x)));
5633                    }
5634                    "SLam" => {
5635                        let param_type = syntax_to_term(first)?;
5636                        let body = syntax_to_term(second)?;
5637                        return Some(Term::Lambda {
5638                            param: "_".to_string(),
5639                            param_type: Box::new(param_type),
5640                            body: Box::new(body),
5641                        });
5642                    }
5643                    "SPi" => {
5644                        let param_type = syntax_to_term(first)?;
5645                        let body_type = syntax_to_term(second)?;
5646                        return Some(Term::Pi {
5647                            param: "_".to_string(),
5648                            param_type: Box::new(param_type),
5649                            body_type: Box::new(body_type),
5650                        });
5651                    }
5652                    _ => {}
5653                }
5654            }
5655        }
5656    }
5657
5658    // Three-argument: SMatch discriminant motive cases
5659    // (SApp (SApp (SApp (SName "SMatch") disc) motive) cases)
5660    if let Term::App(outer, third) = syntax {
5661        if let Term::App(mid, second) = outer.as_ref() {
5662            if let Term::App(inner, first) = mid.as_ref() {
5663                if let Term::Global(name) = inner.as_ref() {
5664                    if name == "SMatch" {
5665                        let disc = syntax_to_term(first)?;
5666                        let motive = syntax_to_term(second)?;
5667                        // cases would need list handling — skip for now
5668                        let _ = third;
5669                        return Some(Term::Match {
5670                            discriminant: Box::new(disc),
5671                            motive: Box::new(motive),
5672                            cases: vec![],
5673                        });
5674                    }
5675                }
5676            }
5677        }
5678    }
5679
5680    None
5681}
5682
5683/// Check if a Syntax type term represents Bit.
5684fn is_bit_type(term: &Term) -> bool {
5685    // SName "Bit"
5686    if let Term::App(ctor, inner) = term {
5687        if let Term::Global(name) = ctor.as_ref() {
5688            if name == "SName" {
5689                if let Term::Lit(Literal::Text(s)) = inner.as_ref() {
5690                    return s == "Bit";
5691                }
5692            }
5693        }
5694    }
5695    false
5696}
5697
5698/// Substitute SVar(idx) with `replacement` in a Syntax term, shifting de Bruijn
5699/// indices under binders (SPi, SLam).
5700fn syntax_subst_var(term: &Term, idx: i64, replacement: &Term) -> Term {
5701    // Check for SVar n
5702    if let Term::App(ctor, inner) = term {
5703        if let Term::Global(name) = ctor.as_ref() {
5704            if name == "SVar" {
5705                if let Term::Lit(Literal::Int(n)) = inner.as_ref() {
5706                    if *n == idx {
5707                        return replacement.clone();
5708                    } else if *n > idx {
5709                        // Free variable above the binder — shift down
5710                        return make_svar(*n - 1);
5711                    } else {
5712                        return term.clone();
5713                    }
5714                }
5715            }
5716        }
5717    }
5718
5719    // Two-argument constructors: SApp, SLam, SPi
5720    if let Term::App(outer, second) = term {
5721        if let Term::App(sctor, first) = outer.as_ref() {
5722            if let Term::Global(name) = sctor.as_ref() {
5723                match name.as_str() {
5724                    "SApp" => {
5725                        let f = syntax_subst_var(first, idx, replacement);
5726                        let x = syntax_subst_var(second, idx, replacement);
5727                        return make_sapp(f, x);
5728                    }
5729                    "SPi" => {
5730                        // Under a binder, shift the index
5731                        let param_t = syntax_subst_var(first, idx, replacement);
5732                        let body = syntax_subst_var(second, idx + 1, replacement);
5733                        return make_spi(param_t, body);
5734                    }
5735                    "SLam" => {
5736                        let param_t = syntax_subst_var(first, idx, replacement);
5737                        let body = syntax_subst_var(second, idx + 1, replacement);
5738                        return make_slam(param_t, body);
5739                    }
5740                    _ => {}
5741                }
5742            }
5743        }
5744    }
5745
5746    // One-argument constructors that don't bind: SName, SLit, SSort — return as-is
5747    term.clone()
5748}
5749
5750/// Tabulate tactic: prove universally quantified Bit goals by exhaustive enumeration.
5751///
5752/// For a goal of the form SPi(SName("Bit"), body):
5753/// 1. Substitute SVar 0 with SName("B0") in body → body_b0
5754/// 2. Substitute SVar 0 with SName("B1") in body → body_b1
5755/// 3. Recursively verify both substituted bodies
5756/// 4. If both succeed, return DTabulateSolve(goal)
5757///
5758/// Handles nested Pi binders (e.g., Pi(a:Bit). Pi(b:Bit). P(a,b)) by recursion.
5759/// Rejects non-Bit quantification.
5760fn try_try_tabulate_reduce(ctx: &Context, goal: &Term) -> Option<Term> {
5761    let norm_goal = normalize(ctx, goal);
5762
5763    // Try to extract SPi(param_type, body)
5764    if let Some((param_type, body)) = extract_spi(&norm_goal) {
5765        // Only handle Bit quantification
5766        if !is_bit_type(&param_type) {
5767            return Some(make_error_derivation());
5768        }
5769
5770        // Substitute SVar 0 with B0 and B1
5771        let body_b0 = syntax_subst_var(&body, 0, &make_sname("B0"));
5772        let body_b1 = syntax_subst_var(&body, 0, &make_sname("B1"));
5773
5774        // Recursively verify both cases
5775        let ok_b0 = tabulate_verify_case(ctx, &body_b0);
5776        let ok_b1 = tabulate_verify_case(ctx, &body_b1);
5777
5778        if ok_b0 && ok_b1 {
5779            return Some(Term::App(
5780                Box::new(Term::Global("DTabulateSolve".to_string())),
5781                Box::new(norm_goal),
5782            ));
5783        }
5784
5785        return Some(make_error_derivation());
5786    }
5787
5788    // Not a Pi — not a quantified goal
5789    Some(make_error_derivation())
5790}
5791
5792/// Verify a single case for tabulation. The case is either:
5793/// - An Eq(Bit, lhs, rhs) — verify by normalizing both sides
5794/// - Another SPi(Bit, ...) — recurse (nested quantification)
5795/// - A formula that reduces to SName("True") — trivially true
5796fn tabulate_verify_case(ctx: &Context, case: &Term) -> bool {
5797    let norm = normalize(ctx, case);
5798
5799    // If it's another Pi over Bit, recurse
5800    if let Some((param_type, _)) = extract_spi(&norm) {
5801        if is_bit_type(&param_type) {
5802            if let Some(result) = try_try_tabulate_reduce(ctx, &norm) {
5803                return !is_error_derivation(&result);
5804            }
5805        }
5806        return false;
5807    }
5808
5809    // Try to verify as an Eq
5810    if let Some((_type_s, left, right)) = extract_eq_syntax_parts(&norm) {
5811        let fuel = 1000;
5812        if let (Some(left_eval), Some(right_eval)) = (
5813            try_syn_eval_reduce(ctx, fuel, &left),
5814            try_syn_eval_reduce(ctx, fuel, &right),
5815        ) {
5816            return syntax_equal(&left_eval, &right_eval);
5817        }
5818        // Try evaluating the whole equality — might reduce to True
5819        if let Some(full_eval) = try_syn_eval_reduce(ctx, fuel, &norm) {
5820            if is_sname_with_value(&full_eval, "True") {
5821                return true;
5822            }
5823        }
5824        return false;
5825    }
5826
5827    // Try evaluating the whole formula — might be SName("True")
5828    let fuel = 1000;
5829    if let Some(eval) = try_syn_eval_reduce(ctx, fuel, &norm) {
5830        if is_sname_with_value(&eval, "True") {
5831            return true;
5832        }
5833    }
5834
5835    false
5836}
5837
5838/// Check if a Syntax term is SName(value)
5839fn is_sname_with_value(term: &Term, value: &str) -> bool {
5840    if let Term::App(ctor, inner) = term {
5841        if let Term::Global(name) = ctor.as_ref() {
5842            if name == "SName" {
5843                if let Term::Lit(Literal::Text(s)) = inner.as_ref() {
5844                    return s == value;
5845                }
5846            }
5847        }
5848    }
5849    false
5850}
5851
5852/// Whether an ATOMIC (non-connective) goal is decided by the arithmetic/equality tactics. Used by
5853/// [`auto_prop_check`] at the leaves of a propositional goal.
5854fn auto_atom_provable(ctx: &Context, goal: &Term) -> bool {
5855    if simp::check_goal(goal) || simp_compute_check(ctx, goal) {
5856        return true;
5857    }
5858    for reduce in [
5859        try_try_ring_reduce,
5860        try_try_omega_reduce,
5861        try_try_lia_reduce,
5862    ] {
5863        if let Some(r) = reduce(ctx, goal) {
5864            if !is_error_derivation(&r) {
5865                return true;
5866            }
5867        }
5868    }
5869    false
5870}
5871
5872/// Decide a proposition by REFLECTION + kernel computation, returning `Some(true)` if it is
5873/// decidably TRUE, `Some(false)` if decidably FALSE, and `None` if undecided (left to other tactics).
5874///
5875/// Handles: `True`/`False`; equalities and equality-hypothesis implications (via
5876/// [`simp_compute_check`], which unfolds `## To` defs + evaluates arithmetic); `not P` (refute `P`);
5877/// `And`/`Or`/`implies` over sub-decisions; and integer comparisons `Lt`/`le`/`Gt`/`ge` over closed
5878/// literals (both directions — so `not (Lt 5 2)` and `not (Eq 2 3)` decide). Sound: every `Some(b)`
5879/// follows from computation or an intro/refutation rule; symbolic goals return `None`.
5880fn decide_prop(ctx: &Context, goal: &Term) -> Option<bool> {
5881    let ng = normalize(ctx, goal);
5882
5883    if is_sname_with_value(&ng, "True") {
5884        return Some(true);
5885    }
5886    if is_sname_with_value(&ng, "False") {
5887        return Some(false);
5888    }
5889    // Equalities + implication-with-equality-hypotheses: a positive decision only.
5890    if simp_compute_check(ctx, &ng) {
5891        return Some(true);
5892    }
5893    if let Some(p) = extract_sapp1(&ng, "not") {
5894        return decide_prop(ctx, &p).map(|b| !b);
5895    }
5896    if let Some((p, q)) = extract_sapp2(&ng, "And") {
5897        return match (decide_prop(ctx, &p), decide_prop(ctx, &q)) {
5898            (Some(false), _) | (_, Some(false)) => Some(false),
5899            (Some(true), Some(true)) => Some(true),
5900            _ => None,
5901        };
5902    }
5903    if let Some((p, q)) = extract_sapp2(&ng, "Or") {
5904        return match (decide_prop(ctx, &p), decide_prop(ctx, &q)) {
5905            (Some(true), _) | (_, Some(true)) => Some(true),
5906            (Some(false), Some(false)) => Some(false),
5907            _ => None,
5908        };
5909    }
5910    if as_implication(&ng).is_some() {
5911        return decide_implication(ctx, &ng);
5912    }
5913    // Integer comparisons over closed literals (both directions).
5914    let comparisons: [(&str, fn(i64, i64) -> bool); 4] = [
5915        ("Lt", |a, b| a < b),
5916        ("le", |a, b| a <= b),
5917        ("Gt", |a, b| a > b),
5918        ("ge", |a, b| a >= b),
5919    ];
5920    for (name, cmp) in comparisons {
5921        if let Some((a_s, b_s)) = extract_sapp2(&ng, name) {
5922            if let (Some(a), Some(b)) = (eval_int(ctx, &a_s), eval_int(ctx, &b_s)) {
5923                return Some(cmp(a, b));
5924            }
5925            // Symbolic comparison (e.g. `x < x + 1`): defer the positive case to lia/omega.
5926            return if auto_atom_provable(ctx, &ng) {
5927                Some(true)
5928            } else {
5929                None
5930            };
5931        }
5932    }
5933    // A disequality survives to here only when both sides are distinct ground literals.
5934    if let Some((_, a_s, b_s)) = extract_eq(&ng) {
5935        if let (Some(a), Some(b)) = (eval_int(ctx, &a_s), eval_int(ctx, &b_s)) {
5936            return Some(a == b);
5937        }
5938        return None;
5939    }
5940    // Atomic fallback: provable by the arithmetic tactics?
5941    if auto_atom_provable(ctx, &ng) {
5942        Some(true)
5943    } else {
5944        None
5945    }
5946}
5947
5948/// Decide an implication goal `H1 -> H2 -> … -> C` by →-INTRODUCTION: assume the hypotheses and
5949/// decide the conclusion. Handles a refutable hypothesis (the implication is vacuously true), the
5950/// conclusion being one of the hypotheses (ASSUMPTION), an equality hypothesis used to REWRITE the
5951/// conclusion — including a non-equality conclusion like `x = 5 -> x < 10`, which the equality-only
5952/// `simp_compute_check` cannot — and a conclusion decidable on its own (weakening). Sound: assuming
5953/// `P` to prove `Q` is exactly →-intro; a false `Q[hyps]` means the implication fails at that
5954/// assignment, so it is not a theorem. Returns `None` when undecided.
5955fn decide_implication(ctx: &Context, goal: &Term) -> Option<bool> {
5956    let mut hyps: Vec<Term> = Vec::new();
5957    let mut concl = normalize(ctx, goal);
5958    while let Some((h, rest)) = as_implication(&concl) {
5959        hyps.push(normalize(ctx, &h));
5960        concl = normalize(ctx, &rest);
5961    }
5962    if hyps.is_empty() {
5963        return None;
5964    }
5965
5966    // Process the hypotheses left-to-right, threading the substitutions the equality hypotheses
5967    // license. If any hypothesis becomes decidably FALSE once earlier equalities are applied, the
5968    // hypothesis set is jointly UNSATISFIABLE, so the implication is vacuously true for ANY
5969    // conclusion (this catches both a single false hypothesis and a contradictory pair like
5970    // `x = 5` ∧ `x = 6`). This is sound: no assignment satisfies all antecedents.
5971    let mut subst: Vec<(Term, Term)> = Vec::new();
5972    for h in &hyps {
5973        let mut hh = h.clone();
5974        for (from, to) in &subst {
5975            hh = subst_structural(&hh, from, to);
5976        }
5977        let hh = normalize(ctx, &hh);
5978        if decide_prop(ctx, &hh) == Some(false) {
5979            return Some(true); // contradictory hypotheses ⇒ vacuously true
5980        }
5981        if let Some((_, hl, hr)) = extract_eq(&hh) {
5982            match (syntax_to_term(&hl), syntax_to_term(&hr)) {
5983                (Some(l), Some(_)) if is_atom_var(&l) => subst.push((hl, hr)),
5984                (Some(_), Some(r)) if is_atom_var(&r) => subst.push((hr, hl)),
5985                _ => {}
5986            }
5987        }
5988    }
5989
5990    // Assumption: the conclusion is (syntactically) one of the hypotheses.
5991    if hyps.iter().any(|h| syntax_equal(h, &concl)) {
5992        return Some(true);
5993    }
5994
5995    // Rewrite the conclusion with the gathered equality substitutions, then decide it.
5996    let mut c = concl;
5997    for (from, to) in &subst {
5998        c = subst_structural(&c, from, to);
5999    }
6000    decide_prop(ctx, &c)
6001}
6002
6003/// Whether a propositional/decidable goal is provable — `decide_prop` says `Some(true)`. This is
6004/// what lets `auto` (and the `decide` tactic) conclude `(And True True)`, `(not (Eq Int 2 3))`,
6005/// `(not (Lt 5 2))`, `(implies True True)` — which the flat tactic list cannot.
6006fn auto_prop_check(ctx: &Context, goal: &Term) -> bool {
6007    decide_prop(ctx, goal) == Some(true)
6008}
6009
6010// =============================================================================
6011// TACTIC SEQUENCING — multi-step proof scripts (`intro. <closer>.`)
6012//
6013// A script is carried as `try_script <name-list> <goal>`, where the name-list is a reflected,
6014// INERT list of tactic names (`SApp (SApp (SName "step") (SName "intro")) … (SName "end")`). Keeping
6015// the steps as names (not `try_<kind> goal` terms) is essential: `try_<kind> goal` would REDUCE to
6016// its derivation against the ORIGINAL goal before the evaluator runs, so a structural closer like
6017// `left`/`split` (which needs the residual after `intro`, not the whole implication) could never be
6018// applied correctly. The evaluator threads the residual goal + hypotheses itself.
6019// =============================================================================
6020
6021/// The reflected `SName "s"` as a string.
6022fn extract_sname_string(t: &Term) -> Option<String> {
6023    if let Term::App(f, inner) = t {
6024        if matches!(f.as_ref(), Term::Global(n) if n == "SName") {
6025            if let Term::Lit(Literal::Text(s)) = inner.as_ref() {
6026                return Some(s.clone());
6027            }
6028        }
6029    }
6030    None
6031}
6032
6033/// Match `try_script list goal` = `App(App(Global "try_script", list), goal)`.
6034fn extract_try_script(term: &Term) -> Option<(Term, Term)> {
6035    if let Term::App(outer, goal) = term {
6036        if let Term::App(g, list) = outer.as_ref() {
6037            if matches!(g.as_ref(), Term::Global(n) if n == "try_script") {
6038                return Some(((**list).clone(), (**goal).clone()));
6039            }
6040        }
6041    }
6042    None
6043}
6044
6045/// Decode the reflected script list into tactic names, or `None` if it is malformed.
6046fn extract_script_names(list: &Term) -> Option<Vec<String>> {
6047    let mut names = Vec::new();
6048    let mut cur = list.clone();
6049    loop {
6050        if is_sname_with_value(&cur, "end") {
6051            return Some(names);
6052        }
6053        let (name_s, rest) = extract_sapp2(&cur, "step")?;
6054        names.push(extract_sname_string(&name_s)?);
6055        cur = rest;
6056    }
6057}
6058
6059/// Build the reflected 2-argument application `SApp (SApp (SName name) a) b`.
6060fn build_sapp2(name: &str, a: Term, b: Term) -> Term {
6061    let sname = Term::App(
6062        Box::new(Term::Global("SName".to_string())),
6063        Box::new(Term::Lit(Literal::Text(name.to_string()))),
6064    );
6065    let sapp = |x: Term, y: Term| {
6066        Term::App(
6067            Box::new(Term::App(
6068                Box::new(Term::Global("SApp".to_string())),
6069                Box::new(x),
6070            )),
6071            Box::new(y),
6072        )
6073    };
6074    sapp(sapp(sname, a), b)
6075}
6076
6077/// Rebuild the implication `h1 -> h2 -> … -> goal` from a hypothesis list and a conclusion.
6078fn wrap_implication(hyps: &[Term], goal: &Term) -> Term {
6079    let mut result = goal.clone();
6080    for h in hyps.iter().rev() {
6081        result = build_sapp2("implies", h.clone(), result);
6082    }
6083    result
6084}
6085
6086/// Run the reduce of the named single-shot tactic on `goal` (already normalized).
6087fn run_named_tactic_reduce(ctx: &Context, kind: &str, goal: &Term) -> Option<Term> {
6088    match kind {
6089        "ring" => try_try_ring_reduce(ctx, goal),
6090        "lia" => try_try_lia_reduce(ctx, goal),
6091        "cc" => try_try_cc_reduce(ctx, goal),
6092        "simp" => try_try_simp_reduce(ctx, goal),
6093        "omega" => try_try_omega_reduce(ctx, goal),
6094        "auto" => try_try_auto_reduce(ctx, goal),
6095        "decide" => try_try_decide_reduce(ctx, goal),
6096        "refl" => try_try_refl_reduce(ctx, goal),
6097        "assumption" => try_try_assumption_reduce(ctx, goal),
6098        "split" => try_try_split_reduce(ctx, goal),
6099        "left" => try_try_left_reduce(ctx, goal),
6100        "right" => try_try_right_reduce(ctx, goal),
6101        _ => None,
6102    }
6103}
6104
6105/// Whether the named tactic proves `goal` under `hyps`. Tries it two sound ways: on the re-wrapped
6106/// `hyps -> goal` (so a hypothesis-aware tactic like `auto`/`assumption`/`cc` uses the hypotheses)
6107/// AND on the bare residual `goal` (so a structural tactic like `left`/`split`/`ring` — which cannot
6108/// consume implications — proves it directly, valid by weakening). Either success discharges it.
6109fn close_under_hyps(ctx: &Context, kind: &str, hyps: &[Term], goal: &Term) -> bool {
6110    let ng = normalize(ctx, goal);
6111    let non_error = |d: Option<Term>| d.is_some_and(|t| !is_error_derivation(&t));
6112    if !hyps.is_empty() {
6113        let wrapped = normalize(ctx, &wrap_implication(hyps, &ng));
6114        if non_error(run_named_tactic_reduce(ctx, kind, &wrapped)) {
6115            return true;
6116        }
6117    }
6118    non_error(run_named_tactic_reduce(ctx, kind, &ng))
6119}
6120
6121/// Evaluate a proof SCRIPT (list of tactic names) against a hypothesis context and current goal.
6122/// Leading `intro`s open universal binders or move implication antecedents into the hypotheses.
6123/// Universal variables retain their de Bruijn indices in the open goal. Lifting the previous
6124/// hypotheses makes room for index zero without capturing a free variable or consulting a global
6125/// name. The final closer must verify the residual proposition under those hypotheses.
6126fn eval_script_names(ctx: &Context, names: &[String], hyps: &[Term], goal: &Term) -> bool {
6127    match names.split_first() {
6128        None => false, // empty script proves nothing
6129        Some((first, rest)) if first == "intro" => {
6130            let Ok(ng) = normalize_checked(ctx, goal) else {
6131                return false;
6132            };
6133            if let Some(body) = extract_forall_body(&ng) {
6134                let Some(lifted_hyps) = hyps
6135                    .iter()
6136                    .map(|hyp| try_syn_lift_reduce(ctx, 1, 0, hyp))
6137                    .collect::<Option<Vec<_>>>()
6138                else {
6139                    return false;
6140                };
6141                return eval_script_names(ctx, rest, &lifted_hyps, &body);
6142            }
6143            match as_implication(&ng) {
6144                Some((p, q)) => {
6145                    let mut h2 = hyps.to_vec();
6146                    h2.push(normalize(ctx, &p));
6147                    eval_script_names(ctx, rest, &h2, &q)
6148                }
6149                None => false, // no universal or implication binder to introduce
6150            }
6151        }
6152        Some((closer, rest)) if rest.is_empty() => close_under_hyps(ctx, closer, hyps, goal),
6153        _ => false, // a non-`intro` step before the final closer
6154    }
6155}
6156
6157/// A `DAutoSolve goal` derivation over the normalized goal — the shared proof object for the
6158/// decision-procedure tactics (`decide`, `split`, `left`, `right`), verified by `try_dauto_solve_conclude`.
6159fn dauto_solve(ctx: &Context, goal: &Term) -> Term {
6160    Term::App(
6161        Box::new(Term::Global("DAutoSolve".to_string())),
6162        Box::new(normalize(ctx, goal)),
6163    )
6164}
6165
6166/// The `decide` tactic: prove a decidable proposition by reflection + computation. Succeeds exactly
6167/// when [`decide_prop`] returns `Some(true)`. The derivation reuses `DAutoSolve` (whose conclusion
6168/// re-runs the same decision through [`auto_prop_check`]), so a false or undecided goal yields an
6169/// error derivation that the soundness gate rejects.
6170fn try_try_decide_reduce(ctx: &Context, goal: &Term) -> Option<Term> {
6171    if decide_prop(ctx, goal) == Some(true) {
6172        Some(dauto_solve(ctx, goal))
6173    } else {
6174        Some(make_error_derivation())
6175    }
6176}
6177
6178/// Whether `goal` follows from the hypotheses by →-introduction and ASSUMPTION alone: introduce each
6179/// antecedent of an implication chain, then require the conclusion to be (syntactically) one of the
6180/// gathered hypotheses. Directed — it does NOT invoke the decision procedure, so `assumption` proves
6181/// exactly the goals that close by a hypothesis (`P -> P`, `P -> Q -> P`).
6182fn prove_by_assumption(ctx: &Context, hyps: &[Term], goal: &Term) -> bool {
6183    let ng = normalize(ctx, goal);
6184    if hyps.iter().any(|h| syntax_equal(h, &ng)) {
6185        return true;
6186    }
6187    if let Some((p, q)) = as_implication(&ng) {
6188        let mut h2 = hyps.to_vec();
6189        h2.push(normalize(ctx, &p));
6190        return prove_by_assumption(ctx, &h2, &q);
6191    }
6192    false
6193}
6194
6195/// The `assumption` tactic: close the goal with a hypothesis (after introducing implication
6196/// antecedents). Reuses the `DAutoSolve` proof object.
6197fn try_try_assumption_reduce(ctx: &Context, goal: &Term) -> Option<Term> {
6198    if prove_by_assumption(ctx, &[], goal) {
6199        Some(dauto_solve(ctx, goal))
6200    } else {
6201        Some(make_error_derivation())
6202    }
6203}
6204
6205/// The `split` tactic: the ∧-introduction rule — prove a conjunction `And P Q` by proving BOTH
6206/// conjuncts. Fails on a non-conjunction (directed, unlike `auto`).
6207fn try_try_split_reduce(ctx: &Context, goal: &Term) -> Option<Term> {
6208    let ng = normalize(ctx, goal);
6209    if let Some((p, q)) = extract_sapp2(&ng, "And") {
6210        if decide_prop(ctx, &p) == Some(true) && decide_prop(ctx, &q) == Some(true) {
6211            return Some(dauto_solve(ctx, &ng));
6212        }
6213    }
6214    Some(make_error_derivation())
6215}
6216
6217/// The `left` tactic: the ∨-introduction-left rule — prove a disjunction `Or P Q` by proving the
6218/// LEFT disjunct `P`. Fails if `P` is not provable, even when the whole `Or` is (that is `right`).
6219fn try_try_left_reduce(ctx: &Context, goal: &Term) -> Option<Term> {
6220    let ng = normalize(ctx, goal);
6221    if let Some((p, _q)) = extract_sapp2(&ng, "Or") {
6222        if decide_prop(ctx, &p) == Some(true) {
6223            return Some(dauto_solve(ctx, &ng));
6224        }
6225    }
6226    Some(make_error_derivation())
6227}
6228
6229/// The `right` tactic: the ∨-introduction-right rule — prove `Or P Q` by proving the RIGHT disjunct `Q`.
6230fn try_try_right_reduce(ctx: &Context, goal: &Term) -> Option<Term> {
6231    let ng = normalize(ctx, goal);
6232    if let Some((_p, q)) = extract_sapp2(&ng, "Or") {
6233        if decide_prop(ctx, &q) == Some(true) {
6234            return Some(dauto_solve(ctx, &ng));
6235        }
6236    }
6237    Some(make_error_derivation())
6238}
6239
6240/// Verify DBitblastSolve proof by re-evaluating via syn_eval.
6241fn try_dbitblast_solve_conclude(ctx: &Context, goal: &Term) -> Option<Term> {
6242    let Some(norm_goal) = goal_to_certify(ctx, goal) else {
6243        return Some(make_sname_error());
6244    };
6245    if let Some((type_s, left, right)) = extract_eq_syntax_parts(&norm_goal) {
6246        if is_bit_type(&type_s) {
6247            let fuel = 1000;
6248            let left_eval = try_syn_eval_reduce(ctx, fuel, &left)?;
6249            let right_eval = try_syn_eval_reduce(ctx, fuel, &right)?;
6250            if syntax_equal(&left_eval, &right_eval) {
6251                return Some(norm_goal);
6252            }
6253        }
6254    }
6255    None
6256}
6257
6258/// Verify DTabulateSolve proof by re-running exhaustive enumeration.
6259fn try_dtabulate_solve_conclude(ctx: &Context, goal: &Term) -> Option<Term> {
6260    let Some(norm_goal) = goal_to_certify(ctx, goal) else {
6261        return Some(make_sname_error());
6262    };
6263    // Re-verify: the goal must be a provable Pi-over-Bit
6264    if let Some((param_type, _)) = extract_spi(&norm_goal) {
6265        if is_bit_type(&param_type) {
6266            if let Some(result) = try_try_tabulate_reduce(ctx, &norm_goal) {
6267                if !is_error_derivation(&result) {
6268                    return Some(norm_goal);
6269                }
6270            }
6271        }
6272    }
6273    None
6274}
6275
6276/// Verify DHwAutoSolve proof by re-running hw tactic chain.
6277fn try_dhw_auto_solve_conclude(ctx: &Context, goal: &Term) -> Option<Term> {
6278    // Try bitblast conclude first
6279    if let Some(result) = try_dbitblast_solve_conclude(ctx, goal) {
6280        return Some(result);
6281    }
6282    // Fall back to auto conclude
6283    try_dauto_solve_conclude(ctx, goal)
6284}
6285
6286/// Hardware auto: tries bitblast, then tabulate, then falls back to auto.
6287fn try_try_hw_auto_reduce(ctx: &Context, goal: &Term) -> Option<Term> {
6288    let norm_goal = normalize(ctx, goal);
6289
6290    // Try bitblast first (fast, for concrete Bit equalities)
6291    if let Some(result) = try_try_bitblast_reduce(ctx, &norm_goal) {
6292        if !is_error_derivation(&result) {
6293            return Some(result);
6294        }
6295    }
6296
6297    // Try tabulate (for universal Bit quantification)
6298    if let Some(result) = try_try_tabulate_reduce(ctx, &norm_goal) {
6299        if !is_error_derivation(&result) {
6300            return Some(result);
6301        }
6302    }
6303
6304    // Fall back to auto
6305    try_try_auto_reduce(ctx, &norm_goal)
6306}
6307
6308fn try_try_auto_reduce(ctx: &Context, goal: &Term) -> Option<Term> {
6309    let norm_goal = normalize(ctx, goal);
6310
6311    // Handle trivial cases: True and False
6312    // SName "True" is trivially provable
6313    if let Term::App(ctor, inner) = &norm_goal {
6314        if let Term::Global(name) = ctor.as_ref() {
6315            if name == "SName" {
6316                if let Term::Lit(Literal::Text(s)) = inner.as_ref() {
6317                    if s == "True" {
6318                        // True is always provable - use DAutoSolve
6319                        return Some(Term::App(
6320                            Box::new(Term::Global("DAutoSolve".to_string())),
6321                            Box::new(norm_goal),
6322                        ));
6323                    }
6324                    if s == "False" {
6325                        // False is never provable
6326                        return Some(make_error_derivation());
6327                    }
6328                }
6329            }
6330        }
6331    }
6332
6333    // Try simp (handles equalities with simplification)
6334    if let Some(result) = try_try_simp_reduce(ctx, &norm_goal) {
6335        if !is_error_derivation(&result) {
6336            return Some(result);
6337        }
6338    }
6339
6340    // Try ring (polynomial equalities)
6341    if let Some(result) = try_try_ring_reduce(ctx, &norm_goal) {
6342        if !is_error_derivation(&result) {
6343            return Some(result);
6344        }
6345    }
6346
6347    // Try cc (congruence closure)
6348    if let Some(result) = try_try_cc_reduce(ctx, &norm_goal) {
6349        if !is_error_derivation(&result) {
6350            return Some(result);
6351        }
6352    }
6353
6354    // Try omega (integer arithmetic - most precise)
6355    if let Some(result) = try_try_omega_reduce(ctx, &norm_goal) {
6356        if !is_error_derivation(&result) {
6357            return Some(result);
6358        }
6359    }
6360
6361    // Try lia (linear arithmetic - fallback)
6362    if let Some(result) = try_try_lia_reduce(ctx, &norm_goal) {
6363        if !is_error_derivation(&result) {
6364            return Some(result);
6365        }
6366    }
6367
6368    // Try registered hints
6369    for hint_name in ctx.get_hints() {
6370        if let Some(hint_type) = ctx.get_global(hint_name) {
6371            if let Some(result) = try_apply_hint(ctx, hint_type, &norm_goal) {
6372                return Some(result);
6373            }
6374        }
6375    }
6376
6377    // Propositional structure (And / Or / implies over decidable atoms) — the flat tactic list
6378    // above only decides atomic goals.
6379    if auto_prop_check(ctx, &norm_goal) {
6380        return Some(Term::App(
6381            Box::new(Term::Global("DAutoSolve".to_string())),
6382            Box::new(norm_goal),
6383        ));
6384    }
6385
6386    // All tactics failed
6387    Some(make_error_derivation())
6388}
6389
6390/// Verify DAutoSolve proof by re-running tactic search.
6391fn try_dauto_solve_conclude(ctx: &Context, goal: &Term) -> Option<Term> {
6392    let Some(norm_goal) = goal_to_certify(ctx, goal) else {
6393        return Some(make_sname_error());
6394    };
6395
6396    // Handle trivial cases: True
6397    if let Term::App(ctor, inner) = &norm_goal {
6398        if let Term::Global(name) = ctor.as_ref() {
6399            if name == "SName" {
6400                if let Term::Lit(Literal::Text(s)) = inner.as_ref() {
6401                    if s == "True" {
6402                        return Some(norm_goal.clone());
6403                    }
6404                }
6405            }
6406        }
6407    }
6408
6409    // Try each tactic - if any succeeds, the proof is valid
6410    if let Some(result) = try_try_simp_reduce(ctx, &norm_goal) {
6411        if !is_error_derivation(&result) {
6412            return Some(norm_goal.clone());
6413        }
6414    }
6415    if let Some(result) = try_try_ring_reduce(ctx, &norm_goal) {
6416        if !is_error_derivation(&result) {
6417            return Some(norm_goal.clone());
6418        }
6419    }
6420    if let Some(result) = try_try_cc_reduce(ctx, &norm_goal) {
6421        if !is_error_derivation(&result) {
6422            return Some(norm_goal.clone());
6423        }
6424    }
6425    if let Some(result) = try_try_omega_reduce(ctx, &norm_goal) {
6426        if !is_error_derivation(&result) {
6427            return Some(norm_goal.clone());
6428        }
6429    }
6430    if let Some(result) = try_try_lia_reduce(ctx, &norm_goal) {
6431        if !is_error_derivation(&result) {
6432            return Some(norm_goal.clone());
6433        }
6434    }
6435
6436    // Try registered hints
6437    for hint_name in ctx.get_hints() {
6438        if let Some(hint_type) = ctx.get_global(hint_name) {
6439            if try_apply_hint(ctx, hint_type, &norm_goal).is_some() {
6440                return Some(norm_goal);
6441            }
6442        }
6443    }
6444
6445    // Propositional structure — must mirror the reduce path exactly, or the soundness gate rejects.
6446    if auto_prop_check(ctx, &norm_goal) {
6447        return Some(norm_goal);
6448    }
6449
6450    Some(make_sname_error())
6451}
6452
6453// =============================================================================
6454// GENERIC INDUCTION HELPERS (induction_num_cases, induction_base_goal, etc.)
6455// =============================================================================
6456
6457/// Returns the number of constructors for an inductive type.
6458///
6459/// induction_num_cases (SName "Nat") → Succ (Succ Zero) = 2
6460/// induction_num_cases (SName "Bool") → Succ (Succ Zero) = 2
6461/// induction_num_cases (SApp (SName "List") A) → Succ (Succ Zero) = 2
6462fn try_induction_num_cases_reduce(ctx: &Context, ind_type: &Term) -> Option<Term> {
6463    // Extract inductive name from Syntax
6464    let ind_name = match extract_inductive_name_from_syntax(ind_type) {
6465        Some(name) => name,
6466        None => {
6467            // Not a valid inductive type syntax
6468            return Some(Term::Global("Zero".to_string()));
6469        }
6470    };
6471
6472    // Look up constructors
6473    let constructors = ctx.get_constructors(&ind_name);
6474    let num_ctors = constructors.len();
6475
6476    // Build Nat representation: Succ (Succ (... Zero))
6477    let mut result = Term::Global("Zero".to_string());
6478    for _ in 0..num_ctors {
6479        result = Term::App(Box::new(Term::Global("Succ".to_string())), Box::new(result));
6480    }
6481
6482    Some(result)
6483}
6484
6485/// Returns the base case goal for induction (first constructor).
6486///
6487/// Given ind_type and motive (SLam T body), returns motive[ctor0/var].
6488fn try_induction_base_goal_reduce(ctx: &Context, ind_type: &Term, motive: &Term) -> Option<Term> {
6489    // Extract inductive name
6490    let ind_name = match extract_inductive_name_from_syntax(ind_type) {
6491        Some(name) => name,
6492        None => return Some(make_sname_error()),
6493    };
6494
6495    // Get constructors
6496    let constructors = ctx.get_constructors(&ind_name);
6497    if constructors.is_empty() {
6498        return Some(make_sname_error());
6499    }
6500
6501    // Extract motive body
6502    let motive_body = match extract_slam_body(motive) {
6503        Some(body) => body,
6504        None => return Some(make_sname_error()),
6505    };
6506
6507    // Build goal for first constructor (base case)
6508    let (ctor_name, _) = constructors[0];
6509    build_case_expected(ctx, ctor_name, &constructors, &motive_body, ind_type, true)
6510}
6511
6512/// Returns the goal for a specific constructor index.
6513///
6514/// Given ind_type, motive, and constructor index (as Nat), returns the case goal.
6515fn try_induction_step_goal_reduce(
6516    ctx: &Context,
6517    ind_type: &Term,
6518    motive: &Term,
6519    ctor_idx: &Term,
6520) -> Option<Term> {
6521    // Extract inductive name
6522    let ind_name = match extract_inductive_name_from_syntax(ind_type) {
6523        Some(name) => name,
6524        None => return Some(make_sname_error()),
6525    };
6526
6527    // Get constructors
6528    let constructors = ctx.get_constructors(&ind_name);
6529    if constructors.is_empty() {
6530        return Some(make_sname_error());
6531    }
6532
6533    // Convert Nat to index
6534    let idx = nat_to_usize(ctor_idx)?;
6535    if idx >= constructors.len() {
6536        return Some(make_sname_error());
6537    }
6538
6539    // Extract motive body
6540    let motive_body = match extract_slam_body(motive) {
6541        Some(body) => body,
6542        None => return Some(make_sname_error()),
6543    };
6544
6545    // Build goal for the specified constructor
6546    let (ctor_name, _) = constructors[idx];
6547    build_case_expected(ctx, ctor_name, &constructors, &motive_body, ind_type, true)
6548}
6549
6550/// Convert a Nat term to usize.
6551///
6552/// Zero → 0
6553/// Succ Zero → 1
6554/// Succ (Succ Zero) → 2
6555fn nat_to_usize(term: &Term) -> Option<usize> {
6556    match term {
6557        Term::Global(name) if name == "Zero" => Some(0),
6558        Term::App(succ, inner) => {
6559            if let Term::Global(name) = succ.as_ref() {
6560                if name == "Succ" {
6561                    return nat_to_usize(inner).map(|n| n + 1);
6562                }
6563            }
6564            None
6565        }
6566        _ => None,
6567    }
6568}
6569
6570/// Generic induction tactic.
6571///
6572/// try_induction ind_type motive cases → DElim ind_type motive cases
6573///
6574/// Delegates to existing DElim infrastructure after basic validation.
6575fn try_try_induction_reduce(
6576    ctx: &Context,
6577    ind_type: &Term,
6578    motive: &Term,
6579    cases: &Term,
6580) -> Option<Term> {
6581    // Extract inductive name to validate
6582    let ind_name = match extract_inductive_name_from_syntax(ind_type) {
6583        Some(name) => name,
6584        None => return Some(make_error_derivation()),
6585    };
6586
6587    // Get constructors to validate count
6588    let constructors = ctx.get_constructors(&ind_name);
6589    if constructors.is_empty() {
6590        return Some(make_error_derivation());
6591    }
6592
6593    // Extract case proofs to validate count
6594    let case_proofs = match extract_case_proofs(cases) {
6595        Some(proofs) => proofs,
6596        None => return Some(make_error_derivation()),
6597    };
6598
6599    // Verify case count matches constructor count
6600    if case_proofs.len() != constructors.len() {
6601        return Some(make_error_derivation());
6602    }
6603
6604    // Build DElim term (delegates verification to existing infrastructure)
6605    Some(Term::App(
6606        Box::new(Term::App(
6607            Box::new(Term::App(
6608                Box::new(Term::Global("DElim".to_string())),
6609                Box::new(ind_type.clone()),
6610            )),
6611            Box::new(motive.clone()),
6612        )),
6613        Box::new(cases.clone()),
6614    ))
6615}
6616
6617// -------------------------------------------------------------------------
6618// Deep Induction
6619// -------------------------------------------------------------------------
6620
6621/// DInduction reduction with verification.
6622///
6623/// DInduction motive base step → Forall Nat motive (if verified)
6624///
6625/// Verification:
6626/// 1. Extract motive body from SLam Nat body
6627/// 2. Check that concludes(base) = motive[Zero/0]
6628/// 3. Check that concludes(step) = ∀k:Nat. P(k) → P(Succ k)
6629/// 4. If all checks pass, return Forall Nat motive
6630/// 5. Otherwise, return Error
6631fn try_dinduction_reduce(ctx: &Context, motive: &Term, base: &Term, step: &Term) -> Option<Term> {
6632    // Normalize all inputs
6633    let norm_motive = normalize(ctx, motive);
6634    let norm_base = normalize(ctx, base);
6635    let norm_step = normalize(ctx, step);
6636
6637    // 1. Extract motive body (should be SLam (SName "Nat") body)
6638    let motive_body = match extract_slam_body(&norm_motive) {
6639        Some(body) => body,
6640        None => return Some(make_sname_error()),
6641    };
6642
6643    // 2. Compute expected base: motive body with Zero substituted for SVar 0
6644    let zero = make_sname("Zero");
6645    let expected_base = match try_syn_subst_reduce(ctx, &zero, 0, &motive_body) {
6646        Some(b) => b,
6647        None => return Some(make_sname_error()),
6648    };
6649
6650    // 3. Get actual base conclusion
6651    let base_conc = match try_concludes_reduce(ctx, &norm_base) {
6652        Some(c) => c,
6653        None => return Some(make_sname_error()),
6654    };
6655
6656    // 4. Verify base matches expected
6657    if !syntax_equal(&base_conc, &expected_base) {
6658        return Some(make_sname_error());
6659    }
6660
6661    // 5. Build expected step formula: ∀k:Nat. P(k) → P(Succ k)
6662    let expected_step = match build_induction_step_formula(ctx, &motive_body) {
6663        Some(s) => s,
6664        None => return Some(make_sname_error()),
6665    };
6666
6667    // 6. Get actual step conclusion
6668    let step_conc = match try_concludes_reduce(ctx, &norm_step) {
6669        Some(c) => c,
6670        None => return Some(make_sname_error()),
6671    };
6672
6673    // 7. Verify step matches expected
6674    if !syntax_equal(&step_conc, &expected_step) {
6675        return Some(make_sname_error());
6676    }
6677
6678    // 8. Return conclusion: Forall Nat motive
6679    Some(make_forall_nat_syntax(&norm_motive))
6680}
6681
6682/// Build step formula: ∀k:Nat. P(k) → P(Succ k)
6683///
6684/// Given motive body P (which uses SVar 0 for k), builds:
6685/// Forall (SName "Nat") (SLam (SName "Nat") (Implies P P[Succ(SVar 0)/SVar 0]))
6686fn build_induction_step_formula(ctx: &Context, motive_body: &Term) -> Option<Term> {
6687    // P(k) = motive_body (uses SVar 0 for k)
6688    let p_k = motive_body.clone();
6689
6690    // P(Succ k) = motive_body with (SApp (SName "Succ") (SVar 0)) substituted
6691    let succ_var = Term::App(
6692        Box::new(Term::App(
6693            Box::new(Term::Global("SApp".to_string())),
6694            Box::new(make_sname("Succ")),
6695        )),
6696        Box::new(Term::App(
6697            Box::new(Term::Global("SVar".to_string())),
6698            Box::new(Term::Lit(Literal::Int(0))),
6699        )),
6700    );
6701    let p_succ_k = try_syn_subst_reduce(ctx, &succ_var, 0, motive_body)?;
6702
6703    // Implies P(k) P(Succ k)
6704    let implies_body = make_implies_syntax(&p_k, &p_succ_k);
6705
6706    // SLam (SName "Nat") implies_body
6707    let slam = Term::App(
6708        Box::new(Term::App(
6709            Box::new(Term::Global("SLam".to_string())),
6710            Box::new(make_sname("Nat")),
6711        )),
6712        Box::new(implies_body),
6713    );
6714
6715    // Forall (SName "Nat") slam
6716    Some(make_forall_syntax_with_type(&make_sname("Nat"), &slam))
6717}
6718
6719/// Build SApp (SApp (SName "Implies") a) b
6720fn make_implies_syntax(a: &Term, b: &Term) -> Term {
6721    // SApp (SName "Implies") a
6722    let app1 = Term::App(
6723        Box::new(Term::App(
6724            Box::new(Term::Global("SApp".to_string())),
6725            Box::new(make_sname("Implies")),
6726        )),
6727        Box::new(a.clone()),
6728    );
6729
6730    // SApp (SApp (SName "Implies") a) b
6731    Term::App(
6732        Box::new(Term::App(
6733            Box::new(Term::Global("SApp".to_string())),
6734            Box::new(app1),
6735        )),
6736        Box::new(b.clone()),
6737    )
6738}
6739
6740/// Build SApp (SApp (SName "Forall") (SName "Nat")) motive
6741fn make_forall_nat_syntax(motive: &Term) -> Term {
6742    make_forall_syntax_with_type(&make_sname("Nat"), motive)
6743}
6744
6745/// Build SApp (SApp (SName "Forall") type_s) body
6746fn make_forall_syntax_with_type(type_s: &Term, body: &Term) -> Term {
6747    // SApp (SName "Forall") type_s
6748    let app1 = Term::App(
6749        Box::new(Term::App(
6750            Box::new(Term::Global("SApp".to_string())),
6751            Box::new(make_sname("Forall")),
6752        )),
6753        Box::new(type_s.clone()),
6754    );
6755
6756    // SApp (SApp (SName "Forall") type_s) body
6757    Term::App(
6758        Box::new(Term::App(
6759            Box::new(Term::Global("SApp".to_string())),
6760            Box::new(app1),
6761        )),
6762        Box::new(body.clone()),
6763    )
6764}
6765
6766// -------------------------------------------------------------------------
6767// Solver (Computational Reflection)
6768// -------------------------------------------------------------------------
6769
6770/// DCompute reduction with verification.
6771///
6772/// DCompute goal → goal (if verified by computation)
6773///
6774/// Verification:
6775/// 1. Check that goal is (Eq T A B) as Syntax
6776/// 2. Evaluate A and B using syn_eval with bounded fuel
6777/// 3. If eval(A) == eval(B), return goal
6778/// 4. Otherwise, return Error
6779fn try_dcompute_conclude(ctx: &Context, goal: &Term) -> Option<Term> {
6780    let Some(norm_goal) = goal_to_certify(ctx, goal) else {
6781        return Some(make_sname_error());
6782    };
6783
6784    // Extract T, A, B from Eq T A B (as Syntax)
6785    // Pattern: SApp (SApp (SApp (SName "Eq") T) A) B
6786    let parts = extract_eq_syntax_parts(&norm_goal);
6787    if parts.is_none() {
6788        // Goal is not an equality - return Error
6789        return Some(make_sname_error());
6790    }
6791    let (_, a, b) = parts.unwrap();
6792
6793    // Evaluate A and B, and INSIST both evaluations finished. This door accepts proofs: two
6794    // reductions abandoned at the same place compare equal and certify nothing, and the caller
6795    // of `try_syn_eval_reduce` cannot tell that from success.
6796    //
6797    // The budget stays at the original 1000, MEASURED rather than guessed: raising it to 1<<16
6798    // cost `tactic_qa_adversarial`'s two batteries 2.0-2.4× (3.7s→9.1s, 4.9s→10.1s) and bought
6799    // nothing, because `syn_eval_checked` stops the instant the reflected term stops CHANGING —
6800    // the only way to spend the budget is a genuinely diverging reflected reduction, and a
6801    // ground arithmetic equality (all `DCompute` is ever asked) finishes in a handful of steps.
6802    // 1000 is already two orders of magnitude of headroom.
6803    const DCOMPUTE_BUDGET: i64 = 1000;
6804    let (Ok(a_eval), Ok(b_eval)) = (
6805        syn_eval_checked(ctx, DCOMPUTE_BUDGET, &a),
6806        syn_eval_checked(ctx, DCOMPUTE_BUDGET, &b),
6807    ) else {
6808        return Some(make_sname_error());
6809    };
6810
6811    // Compare normalized results
6812    if syntax_equal(&a_eval, &b_eval) {
6813        Some(norm_goal)
6814    } else {
6815        Some(make_sname_error())
6816    }
6817}
6818
6819/// Extract T, A, B from Eq T A B (as Syntax)
6820///
6821/// Pattern: SApp (SApp (SApp (SName "Eq") T) A) B
6822fn extract_eq_syntax_parts(term: &Term) -> Option<(Term, Term, Term)> {
6823    // term = SApp X B where X = SApp Y A where Y = SApp (SName "Eq") T
6824    // Structure: App(App(SApp, App(App(SApp, App(App(SApp, App(SName, "Eq")), T)), A)), B)
6825    if let Term::App(partial2, b) = term {
6826        if let Term::App(sapp2, inner2) = partial2.as_ref() {
6827            if let Term::Global(sapp2_name) = sapp2.as_ref() {
6828                if sapp2_name != "SApp" {
6829                    return None;
6830                }
6831            } else {
6832                return None;
6833            }
6834
6835            if let Term::App(partial1, a) = inner2.as_ref() {
6836                if let Term::App(sapp1, inner1) = partial1.as_ref() {
6837                    if let Term::Global(sapp1_name) = sapp1.as_ref() {
6838                        if sapp1_name != "SApp" {
6839                            return None;
6840                        }
6841                    } else {
6842                        return None;
6843                    }
6844
6845                    if let Term::App(eq_t, t) = inner1.as_ref() {
6846                        if let Term::App(sapp0, eq_sname) = eq_t.as_ref() {
6847                            if let Term::Global(sapp0_name) = sapp0.as_ref() {
6848                                if sapp0_name != "SApp" {
6849                                    return None;
6850                                }
6851                            } else {
6852                                return None;
6853                            }
6854
6855                            // Check if eq_sname is SName "Eq"
6856                            if let Term::App(sname_ctor, eq_str) = eq_sname.as_ref() {
6857                                if let Term::Global(ctor) = sname_ctor.as_ref() {
6858                                    if ctor == "SName" {
6859                                        if let Term::Lit(Literal::Text(s)) = eq_str.as_ref() {
6860                                            if s == "Eq" {
6861                                                return Some((
6862                                                    t.as_ref().clone(),
6863                                                    a.as_ref().clone(),
6864                                                    b.as_ref().clone(),
6865                                                ));
6866                                            }
6867                                        }
6868                                    }
6869                                }
6870                            }
6871                        }
6872                    }
6873                }
6874            }
6875        }
6876    }
6877    None
6878}
6879
6880// -------------------------------------------------------------------------
6881// Tactic Combinators
6882// -------------------------------------------------------------------------
6883
6884/// Reduce tact_orelse t1 t2 goal
6885///
6886/// - Apply t1 to goal
6887/// - If concludes returns Error, apply t2 to goal
6888/// - Otherwise return t1's result
6889fn try_tact_orelse_reduce(ctx: &Context, t1: &Term, t2: &Term, goal: &Term) -> Option<Term> {
6890    let norm_goal = normalize(ctx, goal);
6891
6892    // Apply t1 to goal
6893    let d1_app = Term::App(Box::new(t1.clone()), Box::new(norm_goal.clone()));
6894    let d1 = normalize(ctx, &d1_app);
6895
6896    // Check if t1 succeeded by looking at concludes
6897    if let Some(conc1) = try_concludes_reduce(ctx, &d1) {
6898        if is_error_syntax(&conc1) {
6899            // t1 failed, try t2
6900            let d2_app = Term::App(Box::new(t2.clone()), Box::new(norm_goal));
6901            return Some(normalize(ctx, &d2_app));
6902        } else {
6903            // t1 succeeded
6904            return Some(d1);
6905        }
6906    }
6907
6908    // Couldn't evaluate concludes - return error
6909    Some(make_error_derivation())
6910}
6911
6912/// Check if a Syntax term is SName "Error"
6913fn is_error_syntax(term: &Term) -> bool {
6914    // Pattern: SName "Error" = App(Global("SName"), Lit(Text("Error")))
6915    if let Term::App(ctor, arg) = term {
6916        if let Term::Global(name) = ctor.as_ref() {
6917            if name == "SName" {
6918                if let Term::Lit(Literal::Text(s)) = arg.as_ref() {
6919                    return s == "Error";
6920                }
6921            }
6922        }
6923    }
6924    false
6925}
6926
6927/// Reduce tact_try t goal
6928///
6929/// - Apply t to goal
6930/// - If concludes returns Error, return identity (DAxiom goal)
6931/// - Otherwise return t's result
6932fn try_tact_try_reduce(ctx: &Context, t: &Term, goal: &Term) -> Option<Term> {
6933    let norm_goal = normalize(ctx, goal);
6934
6935    // Apply t to goal
6936    let d_app = Term::App(Box::new(t.clone()), Box::new(norm_goal.clone()));
6937    let d = normalize(ctx, &d_app);
6938
6939    // Check if t succeeded by looking at concludes
6940    if let Some(conc) = try_concludes_reduce(ctx, &d) {
6941        if is_error_syntax(&conc) {
6942            // t failed, return identity (DAxiom goal)
6943            return Some(make_daxiom(&norm_goal));
6944        } else {
6945            // t succeeded
6946            return Some(d);
6947        }
6948    }
6949
6950    // Couldn't evaluate concludes - return identity
6951    Some(make_daxiom(&norm_goal))
6952}
6953
6954/// Reduce tact_repeat t goal
6955///
6956/// Apply t repeatedly until it fails or makes no progress.
6957/// Returns the accumulated derivation or identity if first application fails.
6958fn try_tact_repeat_reduce(ctx: &Context, t: &Term, goal: &Term) -> Option<Term> {
6959    const MAX_ITERATIONS: usize = 100;
6960
6961    let norm_goal = normalize(ctx, goal);
6962    let mut current_goal = norm_goal.clone();
6963    let mut last_successful_deriv: Option<Term> = None;
6964
6965    for _ in 0..MAX_ITERATIONS {
6966        // Apply t to current goal
6967        let d_app = Term::App(Box::new(t.clone()), Box::new(current_goal.clone()));
6968        let d = normalize(ctx, &d_app);
6969
6970        // Check result
6971        if let Some(conc) = try_concludes_reduce(ctx, &d) {
6972            if is_error_syntax(&conc) {
6973                // Tactic failed - stop and return what we have
6974                break;
6975            }
6976
6977            // Check for no-progress (fixed point)
6978            if syntax_equal(&conc, &current_goal) {
6979                // No progress made - stop
6980                break;
6981            }
6982
6983            // Progress made - continue
6984            current_goal = conc;
6985            last_successful_deriv = Some(d);
6986        } else {
6987            // Couldn't evaluate concludes - stop
6988            break;
6989        }
6990    }
6991
6992    // Return final derivation or identity
6993    last_successful_deriv.or_else(|| Some(make_daxiom(&norm_goal)))
6994}
6995
6996/// Reduce tact_then t1 t2 goal
6997///
6998/// - Apply t1 to goal
6999/// - If t1 fails, return Error
7000/// - Otherwise apply t2 to the result of t1
7001fn try_tact_then_reduce(ctx: &Context, t1: &Term, t2: &Term, goal: &Term) -> Option<Term> {
7002    let norm_goal = normalize(ctx, goal);
7003
7004    // Apply t1 to goal
7005    let d1_app = Term::App(Box::new(t1.clone()), Box::new(norm_goal.clone()));
7006    let d1 = normalize(ctx, &d1_app);
7007
7008    // Check if t1 succeeded
7009    if let Some(conc1) = try_concludes_reduce(ctx, &d1) {
7010        if is_error_syntax(&conc1) {
7011            // t1 failed
7012            return Some(make_error_derivation());
7013        }
7014
7015        // t1 succeeded - apply t2 to the new goal (conc1)
7016        let d2_app = Term::App(Box::new(t2.clone()), Box::new(conc1));
7017        let d2 = normalize(ctx, &d2_app);
7018
7019        // The result is d2 (which may succeed or fail)
7020        return Some(d2);
7021    }
7022
7023    // Couldn't evaluate concludes - return error
7024    Some(make_error_derivation())
7025}
7026
7027/// Reduce tact_first tactics goal
7028///
7029/// Try each tactic in the list until one succeeds.
7030/// Returns Error if all fail or list is empty.
7031fn try_tact_first_reduce(ctx: &Context, tactics: &Term, goal: &Term) -> Option<Term> {
7032    let norm_goal = normalize(ctx, goal);
7033
7034    // Extract tactics from TList
7035    let tactic_vec = extract_tlist(tactics)?;
7036
7037    for tactic in tactic_vec {
7038        // Apply this tactic to goal
7039        let d_app = Term::App(Box::new(tactic), Box::new(norm_goal.clone()));
7040        let d = normalize(ctx, &d_app);
7041
7042        // Check if it succeeded
7043        if let Some(conc) = try_concludes_reduce(ctx, &d) {
7044            if !is_error_syntax(&conc) {
7045                // Success!
7046                return Some(d);
7047            }
7048            // Failed - try next
7049        }
7050    }
7051
7052    // All failed
7053    Some(make_error_derivation())
7054}
7055
7056/// Extract elements from a TList term
7057///
7058/// TList is polymorphic: TNil A and TCons A h t
7059/// So the structure is:
7060/// - TNil A = App(Global("TNil"), type)
7061/// - TCons A h t = App(App(App(Global("TCons"), type), head), tail)
7062fn extract_tlist(term: &Term) -> Option<Vec<Term>> {
7063    let mut result = Vec::new();
7064    let mut current = term.clone();
7065
7066    loop {
7067        match &current {
7068            // TNil A = App(Global("TNil"), type)
7069            Term::App(tnil, _type) => {
7070                if let Term::Global(name) = tnil.as_ref() {
7071                    if name == "TNil" {
7072                        // Empty list
7073                        break;
7074                    }
7075                }
7076                // Try TCons A h t = App(App(App(Global("TCons"), type), head), tail)
7077                if let Term::App(partial2, tail) = &current {
7078                    if let Term::App(partial1, head) = partial2.as_ref() {
7079                        if let Term::App(tcons, _type) = partial1.as_ref() {
7080                            if let Term::Global(name) = tcons.as_ref() {
7081                                if name == "TCons" {
7082                                    result.push(head.as_ref().clone());
7083                                    current = tail.as_ref().clone();
7084                                    continue;
7085                                }
7086                            }
7087                        }
7088                    }
7089                }
7090                // Not a valid TList structure
7091                return None;
7092            }
7093            // Bare Global("TNil") without type argument - also valid
7094            Term::Global(name) if name == "TNil" => {
7095                break;
7096            }
7097            _ => {
7098                // Not a valid TList
7099                return None;
7100            }
7101        }
7102    }
7103
7104    Some(result)
7105}
7106
7107/// Reduce tact_solve t goal
7108///
7109/// - Apply t to goal
7110/// - If t fails (Error), return Error
7111/// - If t succeeds, return its result
7112fn try_tact_solve_reduce(ctx: &Context, t: &Term, goal: &Term) -> Option<Term> {
7113    let norm_goal = normalize(ctx, goal);
7114
7115    // Apply t to goal
7116    let d_app = Term::App(Box::new(t.clone()), Box::new(norm_goal.clone()));
7117    let d = normalize(ctx, &d_app);
7118
7119    // Check if t succeeded
7120    if let Some(conc) = try_concludes_reduce(ctx, &d) {
7121        if is_error_syntax(&conc) {
7122            // t failed
7123            return Some(make_error_derivation());
7124        }
7125        // t succeeded - return its derivation
7126        return Some(d);
7127    }
7128
7129    // Couldn't evaluate concludes - return error
7130    Some(make_error_derivation())
7131}
7132
7133// -------------------------------------------------------------------------
7134// Congruence Closure
7135// -------------------------------------------------------------------------
7136
7137/// Validate DCong proof by congruence.
7138///
7139/// DCong context eq_proof where:
7140/// - context is SLam param_type body
7141/// - eq_proof proves Eq T a b
7142/// Returns: Eq param_type (body[0:=a]) (body[0:=b])
7143fn try_dcong_conclude(ctx: &Context, context: &Term, eq_proof: &Term) -> Option<Term> {
7144    // Get the conclusion of the equality proof
7145    let eq_conc = try_concludes_reduce(ctx, eq_proof)?;
7146
7147    // Extract T, a, b from Eq T a b
7148    let parts = extract_eq_syntax_parts(&eq_conc);
7149    if parts.is_none() {
7150        // Not an equality proof
7151        return Some(make_sname_error());
7152    }
7153    let (_type_term, lhs, rhs) = parts.unwrap();
7154
7155    // Normalize context and check it's a lambda
7156    let norm_context = normalize(ctx, context);
7157
7158    // Extract (param_type, body) from SLam param_type body
7159    let slam_parts = extract_slam_parts(&norm_context);
7160    if slam_parts.is_none() {
7161        // Not a lambda context
7162        return Some(make_sname_error());
7163    }
7164    let (param_type, body) = slam_parts.unwrap();
7165
7166    // Substitute lhs and rhs into body at index 0
7167    let fa = try_syn_subst_reduce(ctx, &lhs, 0, &body)?;
7168    let fb = try_syn_subst_reduce(ctx, &rhs, 0, &body)?;
7169
7170    // Build result: Eq param_type fa fb
7171    Some(make_eq_syntax_three(&param_type, &fa, &fb))
7172}
7173
7174/// Extract (param_type, body) from SLam param_type body
7175///
7176/// Pattern: App(App(Global("SLam"), param_type), body)
7177fn extract_slam_parts(term: &Term) -> Option<(Term, Term)> {
7178    if let Term::App(inner, body) = term {
7179        if let Term::App(slam_ctor, param_type) = inner.as_ref() {
7180            if let Term::Global(name) = slam_ctor.as_ref() {
7181                if name == "SLam" {
7182                    return Some((param_type.as_ref().clone(), body.as_ref().clone()));
7183                }
7184            }
7185        }
7186    }
7187    None
7188}
7189
7190/// Build SApp (SApp (SApp (SName "Eq") type_s) a) b
7191///
7192/// Constructs the Syntax representation of (Eq type_s a b)
7193fn make_eq_syntax_three(type_s: &Term, a: &Term, b: &Term) -> Term {
7194    let eq_name = Term::App(
7195        Box::new(Term::Global("SName".to_string())),
7196        Box::new(Term::Lit(Literal::Text("Eq".to_string()))),
7197    );
7198
7199    // SApp (SName "Eq") type_s
7200    let app1 = Term::App(
7201        Box::new(Term::App(
7202            Box::new(Term::Global("SApp".to_string())),
7203            Box::new(eq_name),
7204        )),
7205        Box::new(type_s.clone()),
7206    );
7207
7208    // SApp (SApp (SName "Eq") type_s) a
7209    let app2 = Term::App(
7210        Box::new(Term::App(
7211            Box::new(Term::Global("SApp".to_string())),
7212            Box::new(app1),
7213        )),
7214        Box::new(a.clone()),
7215    );
7216
7217    // SApp (SApp (SApp (SName "Eq") type_s) a) b
7218    Term::App(
7219        Box::new(Term::App(
7220            Box::new(Term::Global("SApp".to_string())),
7221            Box::new(app2),
7222        )),
7223        Box::new(b.clone()),
7224    )
7225}
7226
7227// -------------------------------------------------------------------------
7228// Generic Elimination
7229// -------------------------------------------------------------------------
7230
7231/// DElim reduction with verification.
7232///
7233/// DElim ind_type motive cases → Forall ind_type motive (if verified)
7234///
7235/// Verification:
7236/// 1. Extract inductive name from ind_type Syntax
7237/// 2. Look up constructors for that inductive
7238/// 3. Extract case proofs from DCase chain
7239/// 4. Verify case count matches constructor count
7240/// 5. For each constructor, verify case conclusion matches expected
7241/// 6. Return Forall ind_type motive
7242fn try_delim_conclude(ctx: &Context, ind_type: &Term, motive: &Term, cases: &Term) -> Option<Term> {
7243    // Normalize inputs
7244    let norm_ind_type = normalize(ctx, ind_type);
7245    let norm_motive = normalize(ctx, motive);
7246    let norm_cases = normalize(ctx, cases);
7247
7248    // 1. Extract inductive name from Syntax
7249    let ind_name = match extract_inductive_name_from_syntax(&norm_ind_type) {
7250        Some(name) => name,
7251        None => return Some(make_sname_error()),
7252    };
7253
7254    // 2. Look up constructors for this inductive
7255    let constructors = ctx.get_constructors(&ind_name);
7256    if constructors.is_empty() {
7257        // Unknown inductive type
7258        return Some(make_sname_error());
7259    }
7260
7261    // 3. Extract case proofs from DCase chain
7262    let case_proofs = match extract_case_proofs(&norm_cases) {
7263        Some(proofs) => proofs,
7264        None => return Some(make_sname_error()),
7265    };
7266
7267    // 4. Verify case count matches constructor count
7268    if case_proofs.len() != constructors.len() {
7269        return Some(make_sname_error());
7270    }
7271
7272    // 5. Extract motive body (should be SLam param_type body)
7273    let motive_body = match extract_slam_body(&norm_motive) {
7274        Some(body) => body,
7275        None => return Some(make_sname_error()),
7276    };
7277
7278    // 6. For each constructor, verify case conclusion matches expected
7279    for (i, (ctor_name, _ctor_type)) in constructors.iter().enumerate() {
7280        let case_proof = &case_proofs[i];
7281
7282        // Get actual conclusion of this case proof
7283        let case_conc = match try_concludes_reduce(ctx, case_proof) {
7284            Some(c) => c,
7285            None => return Some(make_sname_error()),
7286        };
7287
7288        // Build expected conclusion based on constructor
7289        // For base case (0-ary constructor): motive[ctor/var]
7290        // For step case (recursive constructor): requires IH pattern
7291        let expected = match build_case_expected(
7292            ctx,
7293            ctor_name,
7294            &constructors,
7295            &motive_body,
7296            &norm_ind_type,
7297            true,
7298        ) {
7299            Some(e) => e,
7300            None => return Some(make_sname_error()),
7301        };
7302
7303        // Verify conclusion matches expected
7304        if !syntax_equal(&case_conc, &expected) {
7305            return Some(make_sname_error());
7306        }
7307    }
7308
7309    // 7. Return conclusion: Forall ind_type motive
7310    Some(make_forall_syntax_generic(&norm_ind_type, &norm_motive))
7311}
7312
7313/// Extract inductive name from Syntax term.
7314///
7315/// Handles:
7316/// - SName "Nat" → "Nat"
7317/// - SApp (SName "List") A → "List"
7318fn extract_inductive_name_from_syntax(term: &Term) -> Option<String> {
7319    // Case 1: SName "X"
7320    if let Term::App(sname, text) = term {
7321        if let Term::Global(ctor) = sname.as_ref() {
7322            if ctor == "SName" {
7323                if let Term::Lit(Literal::Text(name)) = text.as_ref() {
7324                    return Some(name.clone());
7325                }
7326            }
7327        }
7328    }
7329
7330    // Case 2: SApp (SName "X") args → extract "X" from the function position
7331    if let Term::App(inner, _arg) = term {
7332        if let Term::App(sapp, func) = inner.as_ref() {
7333            if let Term::Global(ctor) = sapp.as_ref() {
7334                if ctor == "SApp" {
7335                    // Recursively extract from the function
7336                    return extract_inductive_name_from_syntax(func);
7337                }
7338            }
7339        }
7340    }
7341
7342    None
7343}
7344
7345/// Extract case proofs from DCase chain.
7346///
7347/// DCase p1 (DCase p2 DCaseEnd) → [p1, p2]
7348fn extract_case_proofs(term: &Term) -> Option<Vec<Term>> {
7349    let mut proofs = Vec::new();
7350    let mut current = term;
7351
7352    loop {
7353        // DCaseEnd - end of list
7354        if let Term::Global(name) = current {
7355            if name == "DCaseEnd" {
7356                return Some(proofs);
7357            }
7358        }
7359
7360        // DCase head tail - Pattern: App(App(DCase, head), tail)
7361        if let Term::App(inner, tail) = current {
7362            if let Term::App(dcase, head) = inner.as_ref() {
7363                if let Term::Global(name) = dcase.as_ref() {
7364                    if name == "DCase" {
7365                        proofs.push(head.as_ref().clone());
7366                        current = tail.as_ref();
7367                        continue;
7368                    }
7369                }
7370            }
7371        }
7372
7373        // Unrecognized structure
7374        return None;
7375    }
7376}
7377
7378/// THE CASE FORMULA for one constructor — the proposition a bullet must prove.
7379///
7380/// For `C : Π(f₁:T₁) … (fₙ:Tₙ). Ind` the formula is
7381///
7382/// ```text
7383///   ∀f₁ … ∀fₙ.  (IH for each RECURSIVE fᵢ) →  P (C f₁ … fₙ)
7384/// ```
7385///
7386/// and the induction hypotheses are included only when `include_ih` — `induction` has them,
7387/// `destruct`/`cases` does not, and that is the ENTIRE difference between the two eliminators.
7388///
7389/// **ONE BUILDER, NOT THREE.** This used to branch three ways, and two of the branches were
7390/// wrong in the same direction — they checked a WEAKER proposition than the eliminator then
7391/// conceded:
7392///
7393/// * a hard-coded `ind_name == "Nat"` arm, which is `build_recursive_case_formula` written a
7394///   second time and therefore a second place for the formula to drift;
7395/// * a `is_recursive_constructor` gate whose false branch substituted the BARE constructor —
7396///   no field arguments and no quantifier. For `A Tag is either Zed or a Val with n: Nat.`
7397///   the `Val` case was checked as `P Val`, a proposition about a partially applied
7398///   constructor, while `DElim` went on to conclude `∀t:Tag, P t` — which includes every
7399///   `P (Val n)` that was never proved. `∀t:Tag, t = t` with two `refl` bullets certified,
7400///   while the same shape over a RECURSIVE constructor was correctly refused: the two
7401///   answers differed only by which branch of the gate the constructor fell into.
7402///
7403/// `build_recursive_case_formula` degrades correctly when a constructor has no value fields
7404/// (it substitutes the applied constructor, which is the base case), so the gate bought
7405/// nothing it did not also get wrong.
7406fn build_case_expected(
7407    ctx: &Context,
7408    ctor_name: &str,
7409    _constructors: &[(&str, &Term)],
7410    motive_body: &Term,
7411    ind_type: &Term,
7412    include_ih: bool,
7413) -> Option<Term> {
7414    let ind_name = extract_inductive_name_from_syntax(ind_type)?;
7415    match ctx.get_global(ctor_name) {
7416        Some(ctor_ty) => build_recursive_case_formula(
7417            ctx,
7418            ctor_name,
7419            ctor_ty,
7420            motive_body,
7421            ind_type,
7422            &ind_name,
7423            include_ih,
7424        ),
7425        // A constructor the context does not declare has no fields the kernel can see, so the
7426        // only formula available is the one about the constructor itself.
7427        None => {
7428            let ctor_applied = apply_type_args_to_ctor(&make_sname(ctor_name), ind_type);
7429            try_syn_subst_reduce(ctx, &ctor_applied, 0, motive_body)
7430        }
7431    }
7432}
7433
7434/// Apply type arguments from ind_type to a constructor.
7435///
7436/// If ind_type = SApp (SName "List") A, and ctor = SName "Nil",
7437/// result = SApp (SName "Nil") A
7438fn apply_type_args_to_ctor(ctor: &Term, ind_type: &Term) -> Term {
7439    // Extract type arguments from ind_type
7440    let args = extract_type_args(ind_type);
7441
7442    if args.is_empty() {
7443        return ctor.clone();
7444    }
7445
7446    // Apply each arg: SApp (... (SApp ctor arg1) ...) argN
7447    args.iter().fold(ctor.clone(), |acc, arg| {
7448        Term::App(
7449            Box::new(Term::App(
7450                Box::new(Term::Global("SApp".to_string())),
7451                Box::new(acc),
7452            )),
7453            Box::new(arg.clone()),
7454        )
7455    })
7456}
7457
7458/// Extract type arguments from polymorphic Syntax.
7459///
7460/// SApp (SApp (SName "Either") A) B → [A, B]
7461/// SApp (SName "List") A → [A]
7462/// SName "Nat" → []
7463fn extract_type_args(term: &Term) -> Vec<Term> {
7464    let mut args = Vec::new();
7465    let mut current = term;
7466
7467    // Traverse SApp chain from outside in
7468    loop {
7469        if let Term::App(inner, arg) = current {
7470            if let Term::App(sapp, func) = inner.as_ref() {
7471                if let Term::Global(ctor) = sapp.as_ref() {
7472                    if ctor == "SApp" {
7473                        args.push(arg.as_ref().clone());
7474                        current = func.as_ref();
7475                        continue;
7476                    }
7477                }
7478            }
7479        }
7480        break;
7481    }
7482
7483    // Reverse because we collected outside-in but want inside-out
7484    args.reverse();
7485    args
7486}
7487
7488/// Build Forall Syntax for generic inductive type.
7489///
7490/// Forall ind_type motive = SApp (SApp (SName "Forall") ind_type) motive
7491fn make_forall_syntax_generic(ind_type: &Term, motive: &Term) -> Term {
7492    // SApp (SName "Forall") ind_type
7493    let forall_type = Term::App(
7494        Box::new(Term::App(
7495            Box::new(Term::Global("SApp".to_string())),
7496            Box::new(make_sname("Forall")),
7497        )),
7498        Box::new(ind_type.clone()),
7499    );
7500
7501    // SApp forall_type motive
7502    Term::App(
7503        Box::new(Term::App(
7504            Box::new(Term::Global("SApp".to_string())),
7505            Box::new(forall_type),
7506        )),
7507        Box::new(motive.clone()),
7508    )
7509}
7510
7511/// Build the case formula for a recursive constructor.
7512///
7513/// For Cons : Π(A:Type). A -> List A -> List A
7514/// with motive P : List A -> Prop
7515/// Expected case: ∀x:A. ∀xs:List A. P(xs) -> P(Cons A x xs)
7516fn build_recursive_case_formula(
7517    ctx: &Context,
7518    ctor_name: &str,
7519    ctor_ty: &Term,
7520    motive_body: &Term,
7521    ind_type: &Term,
7522    ind_name: &str,
7523    include_ih: bool,
7524) -> Option<Term> {
7525    // Extract type args from ind_type for matching
7526    let type_args = extract_type_args(ind_type);
7527
7528    // Collect constructor arguments (skipping type parameters)
7529    let args = collect_ctor_args(ctor_ty, ind_name, &type_args);
7530
7531    if args.is_empty() {
7532        // No non-type arguments, treat as base case
7533        let ctor_applied = apply_type_args_to_ctor(&make_sname(ctor_name), ind_type);
7534        return try_syn_subst_reduce(ctx, &ctor_applied, 0, motive_body);
7535    }
7536
7537    // Build from inside out:
7538    // 1. Build ctor application: Cons A x xs (with de Bruijn indices for args)
7539    // 2. Build P(ctor args): motive_body[ctor args/var]
7540    // 3. For each recursive arg, wrap with IH: P(xs) ->
7541    // 4. For each arg, wrap with forall: ∀xs:List A.
7542
7543    // Build constructor application with de Bruijn indices
7544    let mut ctor_app = apply_type_args_to_ctor(&make_sname(ctor_name), ind_type);
7545    for (i, _) in args.iter().enumerate() {
7546        // Index from end: last arg is index 0, second-to-last is 1, etc.
7547        let idx = (args.len() - 1 - i) as i64;
7548        let var = Term::App(
7549            Box::new(Term::Global("SVar".to_string())),
7550            Box::new(Term::Lit(Literal::Int(idx))),
7551        );
7552        ctor_app = Term::App(
7553            Box::new(Term::App(
7554                Box::new(Term::Global("SApp".to_string())),
7555                Box::new(ctor_app),
7556            )),
7557            Box::new(var),
7558        );
7559    }
7560
7561    // P(ctor args) - substitute ctor_app into motive
7562    let p_ctor = try_syn_subst_reduce(ctx, &ctor_app, 0, motive_body)?;
7563
7564    // Build implications from inside out (for recursive args)
7565    let mut body = p_ctor;
7566    for (i, (arg_ty, is_recursive)) in args.iter().enumerate().rev() {
7567        if *is_recursive && include_ih {
7568            // Add IH: P(arg) -> body
7569            // arg is at index (args.len() - 1 - i)
7570            let idx = (args.len() - 1 - i) as i64;
7571            let var = Term::App(
7572                Box::new(Term::Global("SVar".to_string())),
7573                Box::new(Term::Lit(Literal::Int(idx))),
7574            );
7575            let p_arg = try_syn_subst_reduce(ctx, &var, 0, motive_body)?;
7576            body = make_implies_syntax(&p_arg, &body);
7577        }
7578        // Skip non-recursive args in the implication chain
7579        let _ = (i, arg_ty); // suppress unused warning
7580    }
7581
7582    // Wrap with foralls from inside out
7583    for (arg_ty, _) in args.iter().rev() {
7584        // SLam arg_ty body
7585        let slam = Term::App(
7586            Box::new(Term::App(
7587                Box::new(Term::Global("SLam".to_string())),
7588                Box::new(arg_ty.clone()),
7589            )),
7590            Box::new(body.clone()),
7591        );
7592        // Forall arg_ty slam
7593        body = make_forall_syntax_with_type(arg_ty, &slam);
7594    }
7595
7596    Some(body)
7597}
7598
7599/// Collect constructor arguments, skipping type parameters.
7600/// Returns (arg_type, is_recursive) pairs.
7601fn collect_ctor_args(ctor_ty: &Term, ind_name: &str, type_args: &[Term]) -> Vec<(Term, bool)> {
7602    let mut args = Vec::new();
7603    let mut current = ctor_ty;
7604    let mut skip_count = type_args.len();
7605
7606    loop {
7607        match current {
7608            Term::Pi {
7609                param_type,
7610                body_type,
7611                ..
7612            } => {
7613                if skip_count > 0 {
7614                    // Skip type parameter
7615                    skip_count -= 1;
7616                } else {
7617                    // Regular argument
7618                    let is_recursive = contains_inductive_term(param_type, ind_name);
7619                    // Convert kernel type to Syntax representation
7620                    let arg_ty_syntax = kernel_type_to_syntax(param_type);
7621                    args.push((arg_ty_syntax, is_recursive));
7622                }
7623                current = body_type;
7624            }
7625            _ => break,
7626        }
7627    }
7628
7629    args
7630}
7631
7632/// Check if a kernel Term contains the inductive type.
7633fn contains_inductive_term(term: &Term, ind_name: &str) -> bool {
7634    match term {
7635        Term::Global(name) => name == ind_name,
7636        Term::App(f, a) => {
7637            contains_inductive_term(f, ind_name) || contains_inductive_term(a, ind_name)
7638        }
7639        Term::Pi {
7640            param_type,
7641            body_type,
7642            ..
7643        } => {
7644            contains_inductive_term(param_type, ind_name)
7645                || contains_inductive_term(body_type, ind_name)
7646        }
7647        Term::Lambda {
7648            param_type, body, ..
7649        } => {
7650            contains_inductive_term(param_type, ind_name) || contains_inductive_term(body, ind_name)
7651        }
7652        _ => false,
7653    }
7654}
7655
7656/// Convert a kernel Term (type) to its Syntax representation.
7657fn kernel_type_to_syntax(term: &Term) -> Term {
7658    match term {
7659        Term::Global(name) => make_sname(name),
7660        Term::Var(name) => make_sname(name), // Named variable
7661        Term::App(f, a) => {
7662            let f_syn = kernel_type_to_syntax(f);
7663            let a_syn = kernel_type_to_syntax(a);
7664            // SApp f_syn a_syn
7665            Term::App(
7666                Box::new(Term::App(
7667                    Box::new(Term::Global("SApp".to_string())),
7668                    Box::new(f_syn),
7669                )),
7670                Box::new(a_syn),
7671            )
7672        }
7673        Term::Pi {
7674            param: _,
7675            param_type,
7676            body_type,
7677        } => {
7678            let pt_syn = kernel_type_to_syntax(param_type);
7679            let bt_syn = kernel_type_to_syntax(body_type);
7680            // SPi pt_syn bt_syn
7681            Term::App(
7682                Box::new(Term::App(
7683                    Box::new(Term::Global("SPi".to_string())),
7684                    Box::new(pt_syn),
7685                )),
7686                Box::new(bt_syn),
7687            )
7688        }
7689        Term::Sort(univ) => {
7690            // SSort univ
7691            Term::App(
7692                Box::new(Term::Global("SSort".to_string())),
7693                Box::new(univ_to_syntax(univ)),
7694            )
7695        }
7696        Term::Lit(lit) => {
7697            // SLit lit
7698            Term::App(
7699                Box::new(Term::Global("SLit".to_string())),
7700                Box::new(Term::Lit(lit.clone())),
7701            )
7702        }
7703        _ => {
7704            // Fallback for complex terms
7705            make_sname("Unknown")
7706        }
7707    }
7708}
7709
7710/// Convert a Universe to Syntax.
7711fn univ_to_syntax(univ: &crate::term::Universe) -> Term {
7712    use crate::term::Universe;
7713    match univ {
7714        Universe::SProp => Term::Global("USProp".to_string()),
7715        Universe::Prop => Term::Global("UProp".to_string()),
7716        Universe::Type(n) => Term::App(
7717            Box::new(Term::Global("UType".to_string())),
7718            Box::new(Term::Lit(Literal::Int(*n as i64))),
7719        ),
7720        // Universe-polymorphic levels: deeply-embedded so reflection stays total.
7721        Universe::Var(v) => Term::App(
7722            Box::new(Term::Global("UVar".to_string())),
7723            Box::new(Term::Global(v.clone())),
7724        ),
7725        Universe::Succ(l) => Term::App(
7726            Box::new(Term::Global("USucc".to_string())),
7727            Box::new(univ_to_syntax(l)),
7728        ),
7729        Universe::Max(a, b) => Term::App(
7730            Box::new(Term::App(
7731                Box::new(Term::Global("UMax".to_string())),
7732                Box::new(univ_to_syntax(a)),
7733            )),
7734            Box::new(univ_to_syntax(b)),
7735        ),
7736        Universe::IMax(a, b) => Term::App(
7737            Box::new(Term::App(
7738                Box::new(Term::Global("UIMax".to_string())),
7739                Box::new(univ_to_syntax(a)),
7740            )),
7741            Box::new(univ_to_syntax(b)),
7742        ),
7743    }
7744}
7745
7746// -------------------------------------------------------------------------
7747// Inversion Tactic
7748// -------------------------------------------------------------------------
7749
7750/// Inversion tactic: analyze hypothesis to derive False if no constructor matches.
7751///
7752/// Given hypothesis H of form `SApp (SName "IndName") args`, check if any constructor
7753/// of IndName can produce those args. If no constructor can match, return DInversion H.
7754fn try_try_inversion_reduce(ctx: &Context, goal: &Term) -> Option<Term> {
7755    // Extract inductive name and arguments from the hypothesis type
7756    let (ind_name, hyp_args) = match extract_applied_inductive_from_syntax(goal) {
7757        Some((name, args)) => (name, args),
7758        None => return Some(make_error_derivation()),
7759    };
7760
7761    // Check if the inductive type actually exists
7762    if !ctx.is_inductive(&ind_name) {
7763        // Unknown inductive type - cannot derive anything
7764        return Some(make_error_derivation());
7765    }
7766
7767    // Get constructors for this inductive
7768    let constructors = ctx.get_constructors(&ind_name);
7769
7770    // Check each constructor to see if it can match
7771    let mut any_possible = false;
7772    for (_ctor_name, ctor_type) in constructors.iter() {
7773        if can_constructor_match_args(ctx, ctor_type, &hyp_args, &ind_name) {
7774            any_possible = true;
7775            break;
7776        }
7777    }
7778
7779    if any_possible {
7780        // Cannot derive False - some constructor could match
7781        return Some(make_error_derivation());
7782    }
7783
7784    // All constructors impossible → build DInversion
7785    Some(Term::App(
7786        Box::new(Term::Global("DInversion".to_string())),
7787        Box::new(goal.clone()),
7788    ))
7789}
7790
7791/// Verify DInversion proof: check that no constructor can match the hypothesis.
7792fn try_dinversion_conclude(ctx: &Context, hyp_type: &Term) -> Option<Term> {
7793    let norm_hyp = normalize(ctx, hyp_type);
7794
7795    let (ind_name, hyp_args) = match extract_applied_inductive_from_syntax(&norm_hyp) {
7796        Some((name, args)) => (name, args),
7797        None => return Some(make_sname_error()),
7798    };
7799
7800    // Check if the inductive type actually exists
7801    if !ctx.is_inductive(&ind_name) {
7802        return Some(make_sname_error());
7803    }
7804
7805    let constructors = ctx.get_constructors(&ind_name);
7806
7807    // Verify ALL constructors are impossible
7808    for (_ctor_name, ctor_type) in constructors.iter() {
7809        if can_constructor_match_args(ctx, ctor_type, &hyp_args, &ind_name) {
7810            return Some(make_sname_error());
7811        }
7812    }
7813
7814    // All impossible → concludes False
7815    Some(make_sname("False"))
7816}
7817
7818/// Extract inductive name and arguments from Syntax.
7819///
7820/// SApp (SApp (SName "Even") x) y → ("Even", [x, y])
7821/// SName "False" → ("False", [])
7822fn extract_applied_inductive_from_syntax(term: &Term) -> Option<(String, Vec<Term>)> {
7823    // Base case: SName "X"
7824    if let Term::App(ctor, text) = term {
7825        if let Term::Global(ctor_name) = ctor.as_ref() {
7826            if ctor_name == "SName" {
7827                if let Term::Lit(Literal::Text(name)) = text.as_ref() {
7828                    return Some((name.clone(), vec![]));
7829                }
7830            }
7831        }
7832    }
7833
7834    // Recursive case: SApp f x
7835    if let Term::App(inner, arg) = term {
7836        if let Term::App(sapp_ctor, func) = inner.as_ref() {
7837            if let Term::Global(ctor_name) = sapp_ctor.as_ref() {
7838                if ctor_name == "SApp" {
7839                    // Recursively extract from the function
7840                    let (name, mut args) = extract_applied_inductive_from_syntax(func)?;
7841                    args.push(arg.as_ref().clone());
7842                    return Some((name, args));
7843                }
7844            }
7845        }
7846    }
7847
7848    None
7849}
7850
7851/// Check if a constructor can possibly match the given arguments.
7852///
7853/// For constructor `even_succ : ∀n. Even n → Even (Succ (Succ n))`:
7854/// - The constructor's result pattern is `Even (Succ (Succ n))`
7855/// - If hyp_args is `[Succ (Succ (Succ Zero))]` (representing 3):
7856///   - Unify `Succ (Succ n)` with `Succ (Succ (Succ Zero))`
7857///   - This succeeds with n = Succ Zero = 1
7858///   - But then we need to check if `Even 1` is constructible (recursive)
7859fn can_constructor_match_args(
7860    ctx: &Context,
7861    ctor_type: &Term,
7862    hyp_args: &[Term],
7863    ind_name: &str,
7864) -> bool {
7865    // Decompose constructor type to get result pattern and bound variable names
7866    let (result, pattern_vars) = decompose_ctor_type_with_vars(ctor_type);
7867
7868    // Extract result's arguments (what the constructor produces)
7869    let result_args = match extract_applied_inductive_from_syntax(&kernel_type_to_syntax(&result)) {
7870        Some((name, args)) if name == *ind_name => args,
7871        _ => return false,
7872    };
7873
7874    // If argument counts don't match, can't unify
7875    if result_args.len() != hyp_args.len() {
7876        return false;
7877    }
7878
7879    // Try syntactic unification of all arguments together (tracking bindings across args)
7880    let mut bindings: std::collections::HashMap<String, Term> = std::collections::HashMap::new();
7881
7882    for (pattern, concrete) in result_args.iter().zip(hyp_args.iter()) {
7883        if !can_unify_syntax_terms_with_bindings(
7884            ctx,
7885            pattern,
7886            concrete,
7887            &pattern_vars,
7888            &mut bindings,
7889        ) {
7890            return false;
7891        }
7892    }
7893
7894    // If we get here, the constructor could match
7895    // (We don't check recursive hypotheses for simplicity - that would require
7896    // full inversion with backtracking)
7897    true
7898}
7899
7900/// Decompose a constructor type to get the result type and bound variable names.
7901///
7902/// `∀n:Nat. Even n → Even (Succ (Succ n))` → (`Even (Succ (Succ n))`, ["n"])
7903/// `∀A:Type. ∀x:A. Eq A x x` → (`Eq A x x`, ["A", "x"])
7904/// `Bool` → (`Bool`, [])
7905fn decompose_ctor_type_with_vars(ty: &Term) -> (Term, Vec<String>) {
7906    let mut vars = Vec::new();
7907    let mut current = ty;
7908    loop {
7909        match current {
7910            Term::Pi {
7911                param, body_type, ..
7912            } => {
7913                vars.push(param.clone());
7914                current = body_type;
7915            }
7916            _ => break,
7917        }
7918    }
7919    (current.clone(), vars)
7920}
7921
7922/// Check if two Syntax terms can unify, tracking variable bindings.
7923///
7924/// Pattern variables (names in `pattern_vars`) can bind to any concrete value,
7925/// but must bind consistently (same variable must bind to same value).
7926/// Other SNames must match exactly.
7927/// SApp recurses on function and argument.
7928fn can_unify_syntax_terms_with_bindings(
7929    ctx: &Context,
7930    pattern: &Term,
7931    concrete: &Term,
7932    pattern_vars: &[String],
7933    bindings: &mut std::collections::HashMap<String, Term>,
7934) -> bool {
7935    // SVar can match anything (explicit unification variable)
7936    if let Term::App(ctor, _idx) = pattern {
7937        if let Term::Global(name) = ctor.as_ref() {
7938            if name == "SVar" {
7939                return true;
7940            }
7941        }
7942    }
7943
7944    // SName: check if it's a pattern variable or a constant
7945    if let Term::App(ctor1, text1) = pattern {
7946        if let Term::Global(n1) = ctor1.as_ref() {
7947            if n1 == "SName" {
7948                if let Term::Lit(Literal::Text(var_name)) = text1.as_ref() {
7949                    // Check if this is a pattern variable
7950                    if pattern_vars.contains(var_name) {
7951                        // Pattern variable: check existing binding or create new one
7952                        if let Some(existing) = bindings.get(var_name) {
7953                            // Already bound: concrete must match existing binding
7954                            return syntax_terms_equal(existing, concrete);
7955                        } else {
7956                            // Not yet bound: bind to concrete value
7957                            bindings.insert(var_name.clone(), concrete.clone());
7958                            return true;
7959                        }
7960                    }
7961                }
7962                // Not a pattern variable: must match exactly
7963                if let Term::App(ctor2, text2) = concrete {
7964                    if let Term::Global(n2) = ctor2.as_ref() {
7965                        if n2 == "SName" {
7966                            return text1 == text2;
7967                        }
7968                    }
7969                }
7970                return false;
7971            }
7972        }
7973    }
7974
7975    // SApp: recurse on both function and argument
7976    if let (Term::App(inner1, arg1), Term::App(inner2, arg2)) = (pattern, concrete) {
7977        if let (Term::App(sapp1, func1), Term::App(sapp2, func2)) =
7978            (inner1.as_ref(), inner2.as_ref())
7979        {
7980            if let (Term::Global(n1), Term::Global(n2)) = (sapp1.as_ref(), sapp2.as_ref()) {
7981                if n1 == "SApp" && n2 == "SApp" {
7982                    return can_unify_syntax_terms_with_bindings(
7983                        ctx,
7984                        func1,
7985                        func2,
7986                        pattern_vars,
7987                        bindings,
7988                    ) && can_unify_syntax_terms_with_bindings(
7989                        ctx,
7990                        arg1.as_ref(),
7991                        arg2.as_ref(),
7992                        pattern_vars,
7993                        bindings,
7994                    );
7995                }
7996            }
7997        }
7998    }
7999
8000    // SLit: compare literal values
8001    if let (Term::App(ctor1, lit1), Term::App(ctor2, lit2)) = (pattern, concrete) {
8002        if let (Term::Global(n1), Term::Global(n2)) = (ctor1.as_ref(), ctor2.as_ref()) {
8003            if n1 == "SLit" && n2 == "SLit" {
8004                return lit1 == lit2;
8005            }
8006        }
8007    }
8008
8009    // Fall back to exact structural equality
8010    pattern == concrete
8011}
8012
8013/// Check if two Syntax terms are structurally equal.
8014fn syntax_terms_equal(a: &Term, b: &Term) -> bool {
8015    match (a, b) {
8016        (Term::App(f1, x1), Term::App(f2, x2)) => {
8017            syntax_terms_equal(f1, f2) && syntax_terms_equal(x1, x2)
8018        }
8019        (Term::Global(n1), Term::Global(n2)) => n1 == n2,
8020        (Term::Lit(l1), Term::Lit(l2)) => l1 == l2,
8021        _ => a == b,
8022    }
8023}
8024
8025// -------------------------------------------------------------------------
8026// Operator Tactics (rewrite, destruct, apply)
8027// -------------------------------------------------------------------------
8028
8029/// Extract Eq A x y components from a Syntax term.
8030///
8031/// SApp (SApp (SApp (SName "Eq") A) x) y → Some((A, x, y))
8032fn extract_eq_components_from_syntax(term: &Term) -> Option<(Term, Term, Term)> {
8033    // term = SApp (SApp (SApp (SName "Eq") A) x) y
8034    // In kernel representation: App(App(SApp, App(App(SApp, App(App(SApp, SName "Eq"), A)), x)), y)
8035
8036    // Peel off outermost SApp to get ((SApp (SApp (SName "Eq") A) x), y)
8037    let (eq_a_x, y) = extract_sapp(term)?;
8038
8039    // Peel off next SApp to get ((SApp (SName "Eq") A), x)
8040    let (eq_a, x) = extract_sapp(&eq_a_x)?;
8041
8042    // Peel off next SApp to get ((SName "Eq"), A)
8043    let (eq, a) = extract_sapp(&eq_a)?;
8044
8045    // Verify it's SName "Eq"
8046    let eq_name = extract_sname(&eq)?;
8047    if eq_name != "Eq" {
8048        return None;
8049    }
8050
8051    Some((a, x, y))
8052}
8053
8054/// Extract (f, x) from SApp f x (in kernel representation).
8055fn extract_sapp(term: &Term) -> Option<(Term, Term)> {
8056    // SApp f x = App(App(Global("SApp"), f), x)
8057    if let Term::App(inner, x) = term {
8058        if let Term::App(sapp_ctor, f) = inner.as_ref() {
8059            if let Term::Global(ctor_name) = sapp_ctor.as_ref() {
8060                if ctor_name == "SApp" {
8061                    return Some((f.as_ref().clone(), x.as_ref().clone()));
8062                }
8063            }
8064        }
8065    }
8066    None
8067}
8068
8069/// Extract name from SName "name".
8070fn extract_sname(term: &Term) -> Option<String> {
8071    if let Term::App(ctor, text) = term {
8072        if let Term::Global(ctor_name) = ctor.as_ref() {
8073            if ctor_name == "SName" {
8074                if let Term::Lit(Literal::Text(name)) = text.as_ref() {
8075                    return Some(name.clone());
8076                }
8077            }
8078        }
8079    }
8080    None
8081}
8082
8083/// Check if a Syntax term contains a specific subterm.
8084fn contains_subterm_syntax(term: &Term, target: &Term) -> bool {
8085    if syntax_equal(term, target) {
8086        return true;
8087    }
8088
8089    // Check SApp f x
8090    if let Some((f, x)) = extract_sapp(term) {
8091        if contains_subterm_syntax(&f, target) || contains_subterm_syntax(&x, target) {
8092            return true;
8093        }
8094    }
8095
8096    // Check SLam T body
8097    if let Some((t, body)) = extract_slam(term) {
8098        if contains_subterm_syntax(&t, target) || contains_subterm_syntax(&body, target) {
8099            return true;
8100        }
8101    }
8102
8103    // Check SPi T body
8104    if let Some((t, body)) = extract_spi(term) {
8105        if contains_subterm_syntax(&t, target) || contains_subterm_syntax(&body, target) {
8106            return true;
8107        }
8108    }
8109
8110    false
8111}
8112
8113/// Extract (T, body) from SLam T body.
8114fn extract_slam(term: &Term) -> Option<(Term, Term)> {
8115    if let Term::App(inner, body) = term {
8116        if let Term::App(slam_ctor, t) = inner.as_ref() {
8117            if let Term::Global(ctor_name) = slam_ctor.as_ref() {
8118                if ctor_name == "SLam" {
8119                    return Some((t.as_ref().clone(), body.as_ref().clone()));
8120                }
8121            }
8122        }
8123    }
8124    None
8125}
8126
8127/// Extract (T, body) from SPi T body.
8128fn extract_spi(term: &Term) -> Option<(Term, Term)> {
8129    if let Term::App(inner, body) = term {
8130        if let Term::App(spi_ctor, t) = inner.as_ref() {
8131            if let Term::Global(ctor_name) = spi_ctor.as_ref() {
8132                if ctor_name == "SPi" {
8133                    return Some((t.as_ref().clone(), body.as_ref().clone()));
8134                }
8135            }
8136        }
8137    }
8138    None
8139}
8140
8141/// Replace first occurrence of target with replacement in a Syntax term.
8142fn replace_first_subterm_syntax(term: &Term, target: &Term, replacement: &Term) -> Option<Term> {
8143    // If term equals target, return replacement
8144    if syntax_equal(term, target) {
8145        return Some(replacement.clone());
8146    }
8147
8148    // Try to replace in SApp f x
8149    if let Some((f, x)) = extract_sapp(term) {
8150        // First try to replace in f
8151        if let Some(new_f) = replace_first_subterm_syntax(&f, target, replacement) {
8152            return Some(make_sapp(new_f, x));
8153        }
8154        // Then try to replace in x
8155        if let Some(new_x) = replace_first_subterm_syntax(&x, target, replacement) {
8156            return Some(make_sapp(f, new_x));
8157        }
8158    }
8159
8160    // Try to replace in SLam T body
8161    if let Some((t, body)) = extract_slam(term) {
8162        if let Some(new_t) = replace_first_subterm_syntax(&t, target, replacement) {
8163            return Some(make_slam(new_t, body));
8164        }
8165        if let Some(new_body) = replace_first_subterm_syntax(&body, target, replacement) {
8166            return Some(make_slam(t, new_body));
8167        }
8168    }
8169
8170    // Try to replace in SPi T body
8171    if let Some((t, body)) = extract_spi(term) {
8172        if let Some(new_t) = replace_first_subterm_syntax(&t, target, replacement) {
8173            return Some(make_spi(new_t, body));
8174        }
8175        if let Some(new_body) = replace_first_subterm_syntax(&body, target, replacement) {
8176            return Some(make_spi(t, new_body));
8177        }
8178    }
8179
8180    // No replacement found
8181    None
8182}
8183
8184/// Rewrite tactic: given eq_proof (concluding Eq A x y) and goal,
8185/// replaces x with y (or y with x if reverse=true) in goal.
8186fn try_try_rewrite_reduce(
8187    ctx: &Context,
8188    eq_proof: &Term,
8189    goal: &Term,
8190    reverse: bool,
8191) -> Option<Term> {
8192    // Get the conclusion of eq_proof
8193    let eq_conclusion = try_concludes_reduce(ctx, eq_proof)?;
8194
8195    // Extract Eq A x y components
8196    let (_, lhs, rhs) = match extract_eq_components_from_syntax(&eq_conclusion) {
8197        Some(components) => components,
8198        None => return Some(make_error_derivation()),
8199    };
8200
8201    // Determine what to replace based on direction
8202    let (target, replacement) = if reverse { (rhs, lhs) } else { (lhs, rhs) };
8203
8204    // Check if target exists in goal
8205    if !contains_subterm_syntax(goal, &target) {
8206        return Some(make_error_derivation());
8207    }
8208
8209    // Replace target with replacement in goal
8210    let new_goal = match replace_first_subterm_syntax(goal, &target, &replacement) {
8211        Some(ng) => ng,
8212        None => return Some(make_error_derivation()),
8213    };
8214
8215    // Build DRewrite eq_proof goal new_goal
8216    Some(Term::App(
8217        Box::new(Term::App(
8218            Box::new(Term::App(
8219                Box::new(Term::Global("DRewrite".to_string())),
8220                Box::new(eq_proof.clone()),
8221            )),
8222            Box::new(goal.clone()),
8223        )),
8224        Box::new(new_goal),
8225    ))
8226}
8227
8228/// Verify DRewrite derivation and return the new goal.
8229fn try_drewrite_conclude(
8230    ctx: &Context,
8231    eq_proof: &Term,
8232    old_goal: &Term,
8233    new_goal: &Term,
8234) -> Option<Term> {
8235    // Get the conclusion of eq_proof
8236    let eq_conclusion = try_concludes_reduce(ctx, eq_proof)?;
8237
8238    // Extract Eq A x y components
8239    let (_ty, lhs, rhs) = match extract_eq_components_from_syntax(&eq_conclusion) {
8240        Some(components) => components,
8241        None => return Some(make_sname_error()),
8242    };
8243
8244    // Verify: new_goal = old_goal[lhs := rhs] OR new_goal = old_goal[rhs := lhs]
8245    // Check forward direction first
8246    if let Some(computed_new) = replace_first_subterm_syntax(old_goal, &lhs, &rhs) {
8247        if syntax_equal(&computed_new, new_goal) {
8248            return Some(new_goal.clone());
8249        }
8250    }
8251
8252    // Check reverse direction
8253    if let Some(computed_new) = replace_first_subterm_syntax(old_goal, &rhs, &lhs) {
8254        if syntax_equal(&computed_new, new_goal) {
8255            return Some(new_goal.clone());
8256        }
8257    }
8258
8259    // Verification failed
8260    Some(make_sname_error())
8261}
8262
8263/// Destruct tactic: case analysis without induction hypotheses.
8264fn try_try_destruct_reduce(
8265    ind_type: &Term,
8266    motive: &Term,
8267    cases: &Term,
8268) -> Option<Term> {
8269    // For now, destruct is essentially the same as induction
8270    // The key difference is in what goals are expected for each case
8271    // (no IH for recursive constructors)
8272    //
8273    // We simply build a DDestruct and let verification check case proofs
8274
8275    Some(Term::App(
8276        Box::new(Term::App(
8277            Box::new(Term::App(
8278                Box::new(Term::Global("DDestruct".to_string())),
8279                Box::new(ind_type.clone()),
8280            )),
8281            Box::new(motive.clone()),
8282        )),
8283        Box::new(cases.clone()),
8284    ))
8285}
8286
8287/// Verify a `DDestruct` derivation — case analysis WITHOUT induction hypotheses.
8288///
8289/// Identical to [`try_delim_conclude`] but for the induction hypotheses, which is the entire
8290/// difference between `cases` and `induction`, so the two share the case-formula builder and
8291/// differ only in the `include_ih` flag they pass it.
8292///
8293/// **This used to check the case COUNT and nothing else** — its own comment said so — and then
8294/// concede `∀x:Ind, P x`. `DDestruct` is a declared `Derivation` constructor and `try_destruct`
8295/// is a declared tactic that builds one, so
8296///
8297/// ```text
8298///   Definition fake : Derivation :=
8299///     try_destruct (SName "Bool") (SLam (SName "Bool") (SName "False"))
8300///       (DCase (DAxiom (SName "True")) (DCase (DAxiom (SName "True")) DCaseEnd)).
8301///   Eval concludes fake.
8302/// ```
8303///
8304/// answered `Forall Bool (λb. False)` — a derivation of `∀b:Bool, False` from two case proofs
8305/// that were never looked at, and one `DAxiom` away from a proof of anything at all. Nothing in
8306/// the literate surface reached it only because `destruct` is absent from that vocabulary, and
8307/// a hole whose only fence is "no caller has been written yet" is a hole.
8308fn try_ddestruct_conclude(
8309    ctx: &Context,
8310    ind_type: &Term,
8311    motive: &Term,
8312    cases: &Term,
8313) -> Option<Term> {
8314    let norm_ind_type = normalize(ctx, ind_type);
8315    let norm_motive = normalize(ctx, motive);
8316    let norm_cases = normalize(ctx, cases);
8317
8318    let ind_name = extract_inductive_name_from_syntax(&norm_ind_type)?;
8319    if !ctx.is_inductive(&ind_name) {
8320        return Some(make_sname_error());
8321    }
8322    let constructors = ctx.get_constructors(&ind_name);
8323    if constructors.is_empty() {
8324        return Some(make_sname_error());
8325    }
8326
8327    let case_proofs = match extract_case_proofs(&norm_cases) {
8328        Some(proofs) => proofs,
8329        None => return Some(make_sname_error()),
8330    };
8331    if case_proofs.len() != constructors.len() {
8332        return Some(make_sname_error());
8333    }
8334
8335    let motive_body = match extract_slam_body(&norm_motive) {
8336        Some(body) => body,
8337        None => return Some(make_sname_error()),
8338    };
8339
8340    // EVERY case is checked against the proposition its constructor owes. `include_ih` is
8341    // false: a `destruct` bullet is handed no induction hypothesis, so demanding one would
8342    // refuse correct case proofs, and offering one would concede a hypothesis nobody proved.
8343    for (i, (ctor_name, _ctor_type)) in constructors.iter().enumerate() {
8344        let case_conc = match try_concludes_reduce(ctx, &case_proofs[i]) {
8345            Some(c) => c,
8346            None => return Some(make_sname_error()),
8347        };
8348        let expected = match build_case_expected(
8349            ctx,
8350            ctor_name,
8351            &constructors,
8352            &motive_body,
8353            &norm_ind_type,
8354            false,
8355        ) {
8356            Some(e) => e,
8357            None => return Some(make_sname_error()),
8358        };
8359        if !syntax_equal(&case_conc, &expected) {
8360            return Some(make_sname_error());
8361        }
8362    }
8363
8364    Some(make_forall_syntax_generic(&norm_ind_type, &norm_motive))
8365}
8366
8367/// Apply tactic: manual backward chaining.
8368fn try_try_apply_reduce(
8369    ctx: &Context,
8370    hyp_name: &Term,
8371    hyp_proof: &Term,
8372    goal: &Term,
8373) -> Option<Term> {
8374    // Get the conclusion of hyp_proof
8375    let hyp_conclusion = try_concludes_reduce(ctx, hyp_proof)?;
8376
8377    // Check if it's an implication: SPi A B where B doesn't use the bound var
8378    if let Some((antecedent, consequent)) = extract_spi(&hyp_conclusion) {
8379        // Check if consequent matches goal
8380        if syntax_equal(&consequent, goal) {
8381            // Build DApply hyp_name hyp_proof goal antecedent
8382            return Some(Term::App(
8383                Box::new(Term::App(
8384                    Box::new(Term::App(
8385                        Box::new(Term::App(
8386                            Box::new(Term::Global("DApply".to_string())),
8387                            Box::new(hyp_name.clone()),
8388                        )),
8389                        Box::new(hyp_proof.clone()),
8390                    )),
8391                    Box::new(goal.clone()),
8392                )),
8393                Box::new(antecedent),
8394            ));
8395        }
8396    }
8397
8398    // Check if it's a forall that could match
8399    if let Some(_forall_body) = extract_forall_body(&hyp_conclusion) {
8400        // Try to match goal with forall body (simple syntactic check)
8401        // For now, if goal appears to be an instance of the forall body, accept it
8402        // Full implementation would do proper unification
8403
8404        // Build DApply with new goal being True (trivially satisfied)
8405        return Some(Term::App(
8406            Box::new(Term::App(
8407                Box::new(Term::App(
8408                    Box::new(Term::App(
8409                        Box::new(Term::Global("DApply".to_string())),
8410                        Box::new(hyp_name.clone()),
8411                    )),
8412                    Box::new(hyp_proof.clone()),
8413                )),
8414                Box::new(goal.clone()),
8415            )),
8416            Box::new(make_sname("True")),
8417        ));
8418    }
8419
8420    // If hypothesis directly matches goal, we're done
8421    if syntax_equal(&hyp_conclusion, goal) {
8422        return Some(Term::App(
8423            Box::new(Term::App(
8424                Box::new(Term::App(
8425                    Box::new(Term::App(
8426                        Box::new(Term::Global("DApply".to_string())),
8427                        Box::new(hyp_name.clone()),
8428                    )),
8429                    Box::new(hyp_proof.clone()),
8430                )),
8431                Box::new(goal.clone()),
8432            )),
8433            Box::new(make_sname("True")),
8434        ));
8435    }
8436
8437    // Cannot apply this hypothesis to this goal
8438    Some(make_error_derivation())
8439}
8440
8441/// Verify DApply derivation.
8442fn try_dapply_conclude(
8443    ctx: &Context,
8444    hyp_proof: &Term,
8445    old_goal: &Term,
8446    new_goal: &Term,
8447) -> Option<Term> {
8448    // Get the conclusion of hyp_proof
8449    let hyp_conclusion = try_concludes_reduce(ctx, hyp_proof)?;
8450
8451    // If hypothesis is an implication A -> B and old_goal is B
8452    // then new_goal should be A
8453    if let Some((antecedent, consequent)) = extract_spi(&hyp_conclusion) {
8454        if syntax_equal(&consequent, old_goal) {
8455            if syntax_equal(&antecedent, new_goal)
8456                || extract_sname(new_goal) == Some("True".to_string())
8457            {
8458                return Some(new_goal.clone());
8459            }
8460        }
8461    }
8462
8463    // If hypothesis is a forall and goal matches instantiation
8464    if let Some(_forall_body) = extract_forall_body(&hyp_conclusion) {
8465        // For forall application, the new goal is typically True or the instantiated body
8466        if extract_sname(new_goal) == Some("True".to_string()) {
8467            return Some(new_goal.clone());
8468        }
8469    }
8470
8471    // If hypothesis directly matches old_goal
8472    if syntax_equal(&hyp_conclusion, old_goal) {
8473        if extract_sname(new_goal) == Some("True".to_string()) {
8474            return Some(new_goal.clone());
8475        }
8476    }
8477
8478    // Verification failed
8479    Some(make_sname_error())
8480}
8481
8482#[cfg(test)]
8483#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/reduction/normalize_tests.rs"]
8484mod normalize_tests;
8485
8486#[cfg(test)]
8487#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/reduction/reflection_signature_tests.rs"]
8488mod reflection_signature_tests;
8489
8490#[cfg(test)]
8491#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/reduction/lazy_head_tests.rs"]
8492mod lazy_head_tests;
8493
8494mod shared_head;
8495pub(crate) use shared_head::{
8496    certified_application, certified_program, program_shape, CertifiedProgram, ProgramShape,
8497};
8498pub(crate) use shared_head::{
8499    constructor_equivalent, constructors_disagree, natural_literal_conversion,
8500};
8501mod whnf_core;
8502pub(crate) use whnf_core::{
8503    beta_normal_form, certified_value, delta_head, unfold_head, whnf, whnf_core, Allowance,
8504    Exhausted,
8505};
8506
8507/// Optional inventory of real machine operations during atomic observation.
8508/// These counters do not replenish or alter evaluator fuel.
8509#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
8510pub struct DagAtomWork {
8511    pub eval: u64,
8512    pub compute: u64,
8513    pub force: u64,
8514    pub returned: u64,
8515    pub force_ready: u64,
8516    pub force_suspended: u64,
8517    pub force_blocked: u64,
8518    pub return_update: u64,
8519    pub return_apply: u64,
8520    pub return_unroll: u64,
8521    pub return_match: u64,
8522    pub return_finish_unary: u64,
8523    pub return_complete: u64,
8524    pub return_unary_demand: u64,
8525    pub thunk_allocations: u64,
8526    pub capture_key_entries: u64,
8527    pub ready_value_rewrites: u64,
8528    pub lambda_values: u64,
8529    pub eval_global: u64,
8530    pub compute_global: u64,
8531    pub global_cache_hits: u64,
8532    pub delta: u64,
8533    pub beta: u64,
8534    pub zeta: u64,
8535    pub iota: u64,
8536    pub guarded_unroll: u64,
8537    pub suspended_constructions: u64,
8538    pub demanded_fresh_suspended: u64,
8539    pub demanded_fresh_running: u64,
8540    pub demanded_cached_suspended: u64,
8541    pub demanded_ready: u64,
8542    pub suspended_lambda_constructions: u64,
8543    pub forced_lambda_suspensions: u64,
8544}
8545
8546#[cfg(test)]
8547#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/reduction/normalization_growth_controls.rs"]
8548mod normalization_growth_controls;
8549
8550#[cfg(test)]
8551#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/reduction/bounded_fix_controls.rs"]
8552mod bounded_fix_controls;
8553
8554#[cfg(test)]
8555#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/reduction/bounded_polymorphic_delta_work.rs"]
8556mod bounded_polymorphic_delta_work;
8557
8558#[cfg(test)]
8559#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/reduction/owned_bounded_spine_controls.rs"]
8560mod owned_bounded_spine_controls;
8561
8562#[cfg(test)]
8563thread_local! { static TREE_REDUCTION_CALLS: std::cell::Cell<usize> = const {std::cell::Cell::new(0)}; }
8564
8565#[cfg(test)]
8566#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/reduction/bounded_size_scratch_controls.rs"]
8567mod bounded_size_scratch_controls;
8568
8569#[cfg(test)]
8570thread_local! {static CONSTRUCTOR_MATERIALIZATIONS:std::cell::Cell<usize>=const {std::cell::Cell::new(0)};}
8571#[cfg(test)]
8572#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/reduction/borrowed_constructor_controls.rs"]
8573mod borrowed_constructor_controls;
8574
8575#[cfg(test)]
8576#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/reduction/owned_conversion_integration_controls.rs"]
8577mod owned_conversion_integration_controls;
8578
8579fn assign_progress_in_place(term: &mut Term, result: Term) -> bool {
8580    if result == *term {
8581        return false;
8582    }
8583    *term = result;
8584    true
8585}
8586
8587/// The full reducer's existing one-step order, consuming only changed nodes.
8588/// The outer normalizer retains its cycle detector, depth checks and step fuel.
8589fn reduce_step_in_place(ctx: &Context, term: &mut Term, tr: Transparency<'_>) -> bool {
8590    #[cfg(test)]
8591    TREE_REDUCTION_CALLS.with(|n| n.set(n.get() + 1));
8592    if let Some(result) = try_simp_rewrite(ctx, term) {
8593        *term = result;
8594        return true;
8595    }
8596    if let Term::App(func, arg) = term {
8597        if let Some(result) = try_primitive_reduce(ctx, func, arg, tr) {
8598            return assign_progress_in_place(term, result);
8599        }
8600        if let Term::App(head, first) = func.as_mut() {
8601            if let Term::Global(operation) = head.as_ref() {
8602                if crate::int_inductive::integer_alias_dependencies(operation)
8603                    .is_some_and(|dependencies| dependencies.iter().all(|name| tr.unfolds(name)))
8604                    && crate::int_inductive::accelerates_integer_alias(ctx, operation)
8605                {
8606                    if reduce_step_in_place(ctx, first, tr) {
8607                        return true;
8608                    }
8609                    if reduce_step_in_place(ctx, arg, tr) {
8610                        return true;
8611                    }
8612                }
8613            }
8614        }
8615        if let Some(result) = try_reflection_reduce(ctx, func, arg) {
8616            return assign_progress_in_place(term, result);
8617        }
8618        if let Term::Global(name) = func.as_ref() {
8619            if name == "reduceBool"
8620                && ctx.get_definition_body(name).is_none()
8621                && declaration_agrees_with_the_rule(ctx, name)
8622            {
8623                if let Some(value) = crate::eval::eval_bool(ctx, arg) {
8624                    return assign_progress_in_place(
8625                        term,
8626                        Term::Global(if value { "true" } else { "false" }.into()),
8627                    );
8628                }
8629            }
8630        }
8631        if let Some(result) = try_quot_lift_reduce(ctx, func, arg) {
8632            return assign_progress_in_place(term, result);
8633        }
8634        if let Some(result) = try_obs_reduce(ctx, func, arg) {
8635            return assign_progress_in_place(term, result);
8636        }
8637    }
8638    if matches!(term, Term::App(..)) {
8639        if let Some(result) = try_fix_unroll(ctx, term) {
8640            return assign_progress_in_place(term, result);
8641        }
8642    }
8643    match term {
8644        Term::Lit(_) | Term::Sort(_) | Term::Var(_) | Term::Hole => false,
8645        Term::Const { name, levels } => {
8646            let result = match const_step(ctx, name, levels) {
8647                ConstStep::Unresolved | ConstStep::Value => return false,
8648                ConstStep::Illformed => Term::Hole,
8649                ConstStep::Delta(subst, body) => {
8650                    if !tr.unfolds(name) {
8651                        return false;
8652                    }
8653                    crate::term::instantiate_universes(&body, &subst)
8654                }
8655            };
8656            *term = result;
8657            true
8658        }
8659        Term::App(func, arg) => match func.as_mut() {
8660            Term::Lambda { .. } => {
8661                let Term::App(func, arg) = std::mem::replace(term, Term::Hole) else {
8662                    unreachable!()
8663                };
8664                let Term::Lambda { param, body, .. } = *func else {
8665                    unreachable!()
8666                };
8667                *term = crate::type_checker::substitute_owned(*body, &param, &arg);
8668                true
8669            }
8670            Term::Fix { .. } => reduce_step_in_place(ctx, arg, tr),
8671            Term::MutualFix { defs, index } => {
8672                if is_constructor_form(ctx, arg) {
8673                    let mut unfolded = defs[*index].1.clone();
8674                    for (j, (name, _)) in defs.iter().enumerate() {
8675                        let projection = Term::MutualFix {
8676                            defs: defs.clone(),
8677                            index: j,
8678                        };
8679                        unfolded = substitute(&unfolded, name, &projection);
8680                    }
8681                    **func = unfolded;
8682                    true
8683                } else {
8684                    reduce_step_in_place(ctx, arg, tr)
8685                }
8686            }
8687            _ => {
8688                if reduce_step_in_place(ctx, func, tr) {
8689                    return true;
8690                }
8691                reduce_step_in_place(ctx, arg, tr)
8692            }
8693        },
8694        Term::Match {
8695            discriminant,
8696            motive,
8697            cases,
8698        } => {
8699            if let Some(mut result) = iota_branch(ctx, discriminant, motive, cases) {
8700                reduce_step_in_place(ctx, &mut result, tr);
8701                *term = result;
8702                return true;
8703            }
8704            if let Some(constructor) = (cases.len() == 1)
8705                .then(|| KProbeMemo::probe(ctx, discriminant, motive))
8706                .flatten()
8707            {
8708                **discriminant = constructor;
8709                return true;
8710            }
8711            reduce_step_in_place(ctx, discriminant, tr)
8712        }
8713        Term::Lambda {
8714            param,
8715            param_type,
8716            body,
8717        } => {
8718            let original_type = (**param_type).clone();
8719            let domain_changed = reduce_step_in_place(ctx, param_type, tr);
8720            let scope = KProbeMemo::enter(param);
8721            let body_changed = reduce_step_in_place(&ctx.extend(param, original_type), body, tr);
8722            KProbeMemo::leave(scope);
8723            domain_changed || body_changed
8724        }
8725        Term::Pi {
8726            param,
8727            param_type,
8728            body_type,
8729        } => {
8730            let original_type = (**param_type).clone();
8731            let domain_changed = reduce_step_in_place(ctx, param_type, tr);
8732            let scope = KProbeMemo::enter(param);
8733            let body_changed =
8734                reduce_step_in_place(&ctx.extend(param, original_type), body_type, tr);
8735            KProbeMemo::leave(scope);
8736            domain_changed || body_changed
8737        }
8738        Term::Fix { body, .. } => reduce_step_in_place(ctx, body, tr),
8739        Term::MutualFix { defs, .. } => {
8740            let mut changed = false;
8741            for (_, body) in defs {
8742                changed |= reduce_step_in_place(ctx, body, tr);
8743            }
8744            changed
8745        }
8746        Term::Let { .. } => {
8747            // The occurrence-gated sharing policy and its order, applied where the parts lie.
8748            crate::term_store::zeta_or_share_in_place(
8749                term,
8750                &|t| reduce_step_in_place(ctx, t, tr),
8751                &|t| reduce_step_opt(ctx, t, tr),
8752            )
8753        }
8754        Term::Global(name) => {
8755            if !tr.unfolds(name) {
8756                return false;
8757            }
8758            let Some(body) = ctx.get_definition_body(name) else {
8759                return false;
8760            };
8761            *term = body.clone();
8762            true
8763        }
8764        // Consumed with its term's step, never by one of its own (see `reduce_step_opt`).
8765        Term::Annotated { term: inner, .. } => {
8766            if !reduce_step_in_place(ctx, inner, tr) {
8767                return false;
8768            }
8769            let reduct = std::mem::replace(inner.as_mut(), Term::Hole);
8770            *term = reduct;
8771            true
8772        }
8773    }
8774}
8775
8776#[cfg(test)]
8777#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/reduction/owned_normalize_controls.rs"]
8778mod owned_normalize_controls;
8779
8780#[cfg(test)]
8781#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/reduction/k_probe_controls.rs"]
8782mod k_probe_controls;
8783#[cfg(test)]
8784#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/reduction/nested_depth_controls.rs"]
8785mod nested_depth_controls;
8786
8787#[cfg(test)]
8788#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/reduction/pending_compute_controls.rs"]
8789mod pending_compute_controls;
8790
8791#[cfg(test)]
8792#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/reduction/borrowed_closed_controls.rs"]
8793mod borrowed_closed_controls;
8794
8795#[cfg(test)]
8796#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/reduction/lazy_telescope_admission.rs"]
8797mod lazy_telescope_admission;
8798
8799#[cfg(test)]
8800#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/reduction/head_size_scan_controls.rs"]
8801mod head_size_scan_controls;
8802
8803#[cfg(test)]
8804#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/reduction/delta_borrowed_admission_controls.rs"]
8805mod delta_borrowed_admission_controls;