Skip to main content

logicaffeine_kernel/
eval.rs

1//! A call-by-value evaluator for the kernel's computational fragment — the engine behind
2//! `native_decide`.
3//!
4//! Unlike [`normalize`](crate::reduction::normalize), which β/ι/δ-reduces by SUBSTITUTION
5//! and normalizes under binders to full normal form, this evaluates a CLOSED term to weak
6//! head normal form using an ENVIRONMENT (no substitution), stopping as soon as the head
7//! constructor is known. So deciding `Eq Nat 10000 10000` is a linear environment walk, not
8//! a quadratic substitution blowup — the point of `native_decide`.
9//!
10//! TRUST: `native_decide` trusts this evaluator to agree with the kernel's reduction (as
11//! Lean's `native_decide` trusts its compiler). It is validated by a differential test
12//! against `normalize`, and fail-safes to `None` (declining) on anything it cannot decide,
13//! but it IS part of the trusted base whenever `native_decide` is used.
14
15use crate::context::Context;
16use crate::term::{int_lit, lit_bigint, Literal, Term};
17use std::cell::RefCell;
18use std::collections::HashMap;
19use std::rc::Rc;
20
21/// A persistent environment mapping bound variables to already-evaluated values.
22enum Scope {
23    Empty,
24    Bind(String, Val, Rc<Scope>),
25}
26
27#[derive(Clone)]
28enum Val {
29    /// A constructor applied to ALL its arguments (parameters + value arguments), evaluated.
30    Ctor(String, Vec<Val>),
31    /// A `λ` closure: (parameter name, body) and the captured environment.
32    Clos(Rc<(String, Term)>, Rc<Scope>),
33    /// A `fix`: (recursive-binder name, body) and the captured environment.
34    Fix(Rc<(String, Term)>, Rc<Scope>),
35    /// A primitive literal (`Lit(Int)` and friends) — the ALU-computed values.
36    Lit(Literal),
37    /// A partially-applied arithmetic/comparison primitive (`add`/`le`/…),
38    /// accumulating its two arguments; computes exactly as the kernel's
39    /// primitive reduction does (arbitrary precision and total division by zero).
40    Prim(&'static str, Vec<Val>),
41    /// No progress possible (free variable, opaque/axiom global, `Sort`/`Π`/`Hole`, a
42    /// stuck application, or fuel exhaustion). A Bool decision that reaches `Stuck` is simply
43    /// undecided, so `native_decide` declines — fail-safe.
44    Stuck,
45}
46
47/// Declaration-checked literal views. Values stay compact; only a Match requests
48/// one constructor layer, while primitive arithmetic reads constructor payloads.
49#[derive(Clone, Copy)]
50struct LiteralRules {
51    nat: bool,
52    int: bool,
53}
54
55trait LiteralValue: Sized {
56    fn literal_ref(&self) -> Option<&Literal>;
57    fn constructor_ref(&self) -> Option<(&str, &[Self])>;
58    fn literal_value(literal: Literal) -> Self;
59    fn constructor_value(name: &str, fields: Vec<Self>) -> Self;
60}
61impl LiteralValue for Val {
62    fn literal_ref(&self) -> Option<&Literal> {
63        if let Self::Lit(l) = self {
64            Some(l)
65        } else {
66            None
67        }
68    }
69    fn constructor_ref(&self) -> Option<(&str, &[Self])> {
70        if let Self::Ctor(n, args) = self {
71            Some((n, args))
72        } else {
73            None
74        }
75    }
76    fn literal_value(literal: Literal) -> Self {
77        Self::Lit(literal)
78    }
79    fn constructor_value(name: &str, fields: Vec<Self>) -> Self {
80        Self::Ctor(name.into(), fields)
81    }
82}
83impl LiteralRules {
84    fn new(ctx: &Context) -> Self {
85        Self {
86            nat: crate::int_inductive::canonical_nat_environment(ctx),
87            int: crate::int_inductive::canonical_environment(ctx),
88        }
89    }
90    fn constructor_form<V: LiteralValue>(&self, value: &V) -> bool {
91        value.constructor_ref().is_some()
92            || match value.literal_ref() {
93                Some(Literal::Nat(n)) => self.nat && !n.is_negative(),
94                Some(Literal::Int(_) | Literal::BigInt(_)) => self.int,
95                _ => false,
96            }
97    }
98    fn constructor<V: LiteralValue>(&self, value: V) -> V {
99        let one = logicaffeine_base::BigInt::from_i64(1);
100        let view = match value.literal_ref() {
101            Some(Literal::Nat(n)) if self.nat && !n.is_negative() => {
102                if *n == logicaffeine_base::BigInt::from_i64(0) {
103                    Some(("Zero", None))
104                } else {
105                    Some(("Succ", Some(Literal::Nat(n.sub(&one)))))
106                }
107            }
108            Some(literal) if self.int => lit_bigint(literal).map(|n| {
109                if n.is_negative() {
110                    ("Int_negSucc", Some(Literal::Nat(n.abs().sub(&one))))
111                } else {
112                    ("Int_ofNat", Some(Literal::Nat(n)))
113                }
114            }),
115            _ => None,
116        };
117        if let Some((name, field)) = view {
118            V::constructor_value(name, field.into_iter().map(V::literal_value).collect())
119        } else {
120            value
121        }
122    }
123    fn literal<'a, V: LiteralValue>(&self, value: &'a V) -> Option<std::borrow::Cow<'a, Literal>> {
124        if let Some(l) = value.literal_ref() {
125            return Some(std::borrow::Cow::Borrowed(l));
126        }
127        if !self.int {
128            return None;
129        }
130        let (name, fields) = value.constructor_ref()?;
131        if fields.len() != 1 || !matches!(name, "Int_ofNat" | "Int_negSucc") {
132            return None;
133        }
134        let mut field = &fields[0];
135        let one = logicaffeine_base::BigInt::from_i64(1);
136        let mut n = logicaffeine_base::BigInt::from_i64(0);
137        loop {
138            if let Some(Literal::Nat(tail)) = field.literal_ref() {
139                if tail.is_negative() {
140                    return None;
141                }
142                n = n.add(tail);
143                break;
144            }
145            match field.constructor_ref()? {
146                ("Zero", []) => break,
147                ("Succ", [tail]) => {
148                    n = n.add(&one);
149                    field = tail;
150                }
151                _ => return None,
152            }
153        }
154        if name == "Int_negSucc" {
155            n = n.add(&one).negated();
156        }
157        Some(std::borrow::Cow::Owned(int_lit(n)))
158    }
159}
160
161/// The canonical name of a primitive this engine computes, if `n` is one.
162///
163/// ONE TABLE, AND IT IS THE REDUCER'S. `ofReduceBool` is an axiom: a `native_decide` proof
164/// trusts this engine to agree with `normalize`, so a rule the reducer has and this does not is
165/// a silent gap in what that axiom rests on. The `Text` rules were exactly that gap — they
166/// landed in `reduction::text_binary`/`unary_prim` and not here, so the evaluator was `Stuck` on
167/// precisely the decisions the reducer answered. The divergence was fail-safe and it was still
168/// a divergence; `R_reduction_extra`'s
169/// `the_native_evaluator_decides_the_text_primitives_exactly_as_the_reducer_does` is what keeps
170/// the two tables in step from now on.
171fn prim_name(n: &str) -> Option<&'static str> {
172    match n {
173        "add" => Some("add"),
174        "sub" => Some("sub"),
175        "mul" => Some("mul"),
176        "div" => Some("div"),
177        "mod" => Some("mod"),
178        "le" => Some("le"),
179        "lt" => Some("lt"),
180        "ge" => Some("ge"),
181        "gt" => Some("gt"),
182        "Text_append" => Some("Text_append"),
183        "Text_beq" => Some("Text_beq"),
184        "Text_isPrefixOf" => Some("Text_isPrefixOf"),
185        "Text_length" => Some("Text_length"),
186        _ => None,
187    }
188}
189
190/// How many arguments a primitive takes before it COMPUTES — read from the NAME, never from how
191/// many arguments happen to have arrived.
192///
193/// Before this every primitive was binary by construction, and a unary rule added to the table
194/// would have waited forever for a second argument that a well-typed term never supplies: it
195/// would sit as a partial `Val::Prim` and read out as `Stuck`, which is the failure mode that
196/// looks exactly like "no rule for this" and is therefore invisible.
197fn prim_arity(name: &str) -> usize {
198    match name {
199        "Text_length" => 1,
200        _ => 2,
201    }
202}
203
204/// The outcome of a primitive on its literal arguments.
205enum PrimResult {
206    /// An INTEGER-valued answer — `Literal::Int` on the fast path, `Literal::BigInt` when the
207    /// exact path promoted, `Literal::Nat` for a rule whose declared codomain is `Nat`.
208    Int(Literal),
209    /// A `Text`-valued answer.
210    Text(Literal),
211    Bool(bool),
212    Stuck,
213}
214
215/// The `Nat` order on two `Nat` LITERALS — this engine's own reading of the specification
216/// `reduction.rs::nat_order_value` states as a program:
217///
218/// ```text
219///   natLe := fix f. λm n. match m { Zero => true | Succ m✧ => match n { Zero => false
220///                                                                     | Succ n✧ => f m✧ n✧ } }
221///   natLt := λm n. natLe (Succ m) n
222/// ```
223///
224/// Derived from the program rather than from the reducer's code: `natLe m n` is `true` exactly
225/// when the recursion bottoms out on the FIRST operand, which is exactly `m ≤ n`; `natLt m n`
226/// is that with `m` shifted up by one, which is `m < n`. The negative clamp is the same
227/// boundary the reducer's Peano bridge imposes — a `Literal::Nat` below zero peels to `Zero`,
228/// so it compares AS zero — and an engine that skipped it would answer a pair the other engine
229/// answers differently.
230///
231/// WHY THIS ENGINE NEEDS IT AT ALL. The tree-walker unfolds a `Fix` only on a CONSTRUCTOR
232/// argument, and a `Literal::Nat` is a `Val::Lit`, so before this the evaluator was `Stuck` on
233/// every `Nat` order over literals while `normalize` decided it through the Peano bridge. That
234/// is a silent gap in the agreement `native_decide` is built on: fail-safe, but a gap.
235fn nat_order(name: &str, al: &Literal, bl: &Literal) -> Option<bool> {
236    let (Literal::Nat(a), Literal::Nat(b)) = (al, bl) else {
237        return None;
238    };
239    let zero = logicaffeine_base::BigInt::from_i64(0);
240    let a = if a.is_negative() { &zero } else { a };
241    let b = if b.is_negative() { &zero } else { b };
242    match name {
243        "natLe" => Some(a <= b),
244        "natLt" => Some(a < b),
245        _ => None,
246    }
247}
248
249/// The canonical name of an accelerable `Nat` order, if `n` is one. The CONTEXT decides whether
250/// the acceleration may fire (`reduction::accelerates_nat_order` checks the constant is bound
251/// to the program being accelerated); this only recognises the two names.
252fn nat_order_name(n: &str) -> Option<&'static str> {
253    match n {
254        "natLe" => Some("natLe"),
255        "natLt" => Some("natLt"),
256        _ => None,
257    }
258}
259
260/// Lean 4's `Int.ediv` / `Int.emod` on machine integers — this engine's OWN implementation of
261/// the specification written out in `reduction.rs::ediv_emod_i64`:
262///
263/// ```text
264///   b ≠ 0  ⟹  a = b·q + r   ∧   0 ≤ r < |b|
265///   b = 0  ⟹  q = 0  ∧  r = a
266/// ```
267///
268/// Derived independently of the reducer's: Rust's own `div_euclid`/`rem_euclid` ARE that
269/// specification, so this side never repeats the reducer's correction arithmetic. A second
270/// engine only protects against an independent bug; shared arithmetic is a shared bug.
271fn ediv_emod_i64(a: i64, b: i64) -> Option<(i64, i64)> {
272    if b == 0 {
273        return Some((0, a));
274    }
275    Some((a.checked_div_euclid(b)?, a.checked_rem_euclid(b)?))
276}
277
278/// The same specification in arbitrary precision, and again by a different derivation from the
279/// reducer's: the remainder is lifted into `[0, |b|)` first, and the quotient is then recovered
280/// by an EXACT division of `a - r` (which `b` divides), rather than by nudging a truncated
281/// quotient by one.
282fn ediv_emod_big(
283    a: &logicaffeine_base::BigInt,
284    b: &logicaffeine_base::BigInt,
285) -> (logicaffeine_base::BigInt, logicaffeine_base::BigInt) {
286    use logicaffeine_base::BigInt;
287    let Some((_, truncated)) = a.div_rem(b) else {
288        return (BigInt::from_i64(0), a.clone());
289    };
290    let r = if truncated.is_negative() {
291        truncated.add(&b.abs())
292    } else {
293        truncated
294    };
295    let q = a
296        .sub(&r)
297        .div_rem(b)
298        .map(|(q, _)| q)
299        .unwrap_or_else(|| BigInt::from_i64(0));
300    (q, r)
301}
302
303/// The pure arithmetic/comparison of a binary Int primitive on two literals — the SAME
304/// semantics as the kernel reduction's `try_primitive_reduce` (overflow promotes to exact
305/// arbitrary precision; `div`/`mod` are Lean's TOTAL Euclidean pair; a non-`Int` literal is
306/// `Stuck`, never wrong). Shared by the tree-walker [`prim_compute`] and the compiled
307/// [`cprim_compute`], so both agree with `normalize` — including on big numbers.
308fn prim_arith(name: &str, al: &Literal, bl: &Literal) -> PrimResult {
309    if let Some(r) = text_prim(name, al, bl) {
310        return r;
311    }
312    if let (Literal::Int(x), Literal::Int(y)) = (al, bl) {
313        let fast = match name {
314            "add" => x.checked_add(*y),
315            "sub" => x.checked_sub(*y),
316            "mul" => x.checked_mul(*y),
317            "div" => ediv_emod_i64(*x, *y).map(|(q, _)| q),
318            "mod" => ediv_emod_i64(*x, *y).map(|(_, r)| r),
319            _ => None,
320        };
321        if let Some(r) = fast {
322            return PrimResult::Int(Literal::Int(r));
323        }
324        match name {
325            "le" => return PrimResult::Bool(x <= y),
326            "lt" => return PrimResult::Bool(x < y),
327            "ge" => return PrimResult::Bool(x >= y),
328            "gt" => return PrimResult::Bool(x > y),
329            _ => {}
330        }
331    }
332    let (Some(xb), Some(yb)) = (lit_bigint(al), lit_bigint(bl)) else {
333        return PrimResult::Stuck;
334    };
335    let big = match name {
336        "add" => Some(xb.add(&yb)),
337        "sub" => Some(xb.sub(&yb)),
338        "mul" => Some(xb.mul(&yb)),
339        "div" => Some(ediv_emod_big(&xb, &yb).0),
340        "mod" => Some(ediv_emod_big(&xb, &yb).1),
341        _ => None,
342    };
343    if let Some(r) = big {
344        return PrimResult::Int(int_lit(r));
345    }
346    match name {
347        "le" => PrimResult::Bool(xb <= yb),
348        "lt" => PrimResult::Bool(xb < yb),
349        "ge" => PrimResult::Bool(xb >= yb),
350        "gt" => PrimResult::Bool(xb > yb),
351        _ => PrimResult::Stuck,
352    }
353}
354
355/// The BINARY `Text` rules — this engine's own reading of the specification
356/// `reduction::text_binary` implements, derived from what the operation MEANS rather than
357/// transcribed from the other engine's code:
358///
359/// ```text
360///   Text_append a b     = the characters of `a` followed by the characters of `b`
361///   Text_beq a b        = `a` and `b` are the same sequence of characters
362///   Text_isPrefixOf a b = `b` begins with `a`   (so every text has the empty text as a prefix)
363/// ```
364///
365/// `None` — not `Stuck` — for a name outside this table or an operand that is not a `Text`
366/// literal, so `prim_arith` falls through to the Int table instead of declaring the term dead.
367fn text_prim(name: &str, al: &Literal, bl: &Literal) -> Option<PrimResult> {
368    let (Literal::Text(a), Literal::Text(b)) = (al, bl) else {
369        return None;
370    };
371    Some(match name {
372        "Text_append" => PrimResult::Text(Literal::Text(a.chars().chain(b.chars()).collect())),
373        "Text_beq" => PrimResult::Bool(a.chars().eq(b.chars())),
374        "Text_isPrefixOf" => PrimResult::Bool(
375            b.chars().count() >= a.chars().count() && b.chars().zip(a.chars()).all(|(x, y)| x == y),
376        ),
377        _ => return None,
378    })
379}
380
381/// Every UNARY rule. `Text_length` counts CHARACTERS, as Lean's `String.length` does — a byte
382/// count agrees with it on ASCII and on nothing else, which is the trap that makes the two
383/// engines part company only on the inputs a test is least likely to try.
384fn prim_unary(name: &str, al: &Literal) -> PrimResult {
385    match (name, al) {
386        ("Text_length", Literal::Text(s)) => PrimResult::Int(Literal::Nat(
387            logicaffeine_base::BigInt::from_u64(s.chars().count() as u64),
388        )),
389        _ => PrimResult::Stuck,
390    }
391}
392
393/// Turn a primitive's outcome into a tree-walker value.
394fn prim_val(r: PrimResult) -> Val {
395    match r {
396        PrimResult::Int(l) | PrimResult::Text(l) => Val::Lit(l),
397        PrimResult::Bool(b) => Val::Ctor(if b { "true" } else { "false" }.to_string(), Vec::new()),
398        PrimResult::Stuck => Val::Stuck,
399    }
400}
401
402/// Compute a fully-applied primitive over tree-walker [`Val`]s, at either arity.
403///
404/// A SLICE PATTERN, not a collected `Vec`: this runs once per primitive application inside a
405/// 50-million-step fuel budget, and an allocation per redex would be a real cost for nothing.
406fn prim_compute(rules: LiteralRules, name: &str, args: &[Val]) -> Val {
407    let r = match args {
408        [a] => rules.literal(a).map(|a| prim_unary(name, &a)),
409        [a, b] => rules
410            .literal(a)
411            .zip(rules.literal(b))
412            .map(|(a, b)| prim_arith(name, &a, &b)),
413        _ => None,
414    };
415    prim_val(r.unwrap_or(PrimResult::Stuck))
416}
417
418// Fuel bounds total work; stack distance separately bounds recursive evaluators.
419// Measure actual frames (debug and optimized frames differ substantially), using
420// the same arranged-stack accounting as the kernel and independent re-checker.
421thread_local! {
422    static EVAL_STACK_BASE: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
423}
424struct EvalFrame {
425    previous: usize,
426}
427impl Drop for EvalFrame {
428    fn drop(&mut self) {
429        EVAL_STACK_BASE.with(|base| base.set(self.previous));
430    }
431}
432#[inline(always)]
433fn eval_stack_mark() -> usize {
434    let probe = 0u8;
435    std::ptr::addr_of!(probe) as usize
436}
437fn enter_eval_frame(here: usize) -> Option<EvalFrame> {
438    let previous = EVAL_STACK_BASE.with(|base| base.get());
439    if previous != 0 && previous.abs_diff(here) > crate::term_store::kernel_stack_bytes() / 2 {
440        return None;
441    }
442    if previous == 0 {
443        EVAL_STACK_BASE.with(|base| base.set(here));
444    }
445    Some(EvalFrame { previous })
446}
447
448const FUEL: u64 = 50_000_000;
449
450/// Evaluate a closed Bool term to `true`/`false`, or `None` if it does not reduce to a Bool
451/// constructor within the fuel budget (fail-safe).
452///
453/// FAST PATH: the decision is first COMPILED to a tree of native closures and run
454/// ([`native_compile_decide`]) — this handles the full computational fragment (recursion via
455/// `Fix`, pattern matching via `Match`, δ-unfolding of definitions), so a recursive Bool
456/// decision runs as closure calls with no `Term`-tree walking. Anything the compiler declines
457/// falls back to the tree-walking interpreter [`eval_bool_tree`]. The two are differential-
458/// tested to give IDENTICAL results, so the trusted `reduceBool` reduction and `native_decide`
459/// both get the compiled speedup with no change in meaning.
460pub fn eval_bool(ctx: &Context, term: &Term) -> Option<bool> {
461    if let Some(b) = native_compile_decide(ctx, term) {
462        return Some(b);
463    }
464    eval_bool_tree(ctx, term)
465}
466
467/// The tree-walking interpreter decision — walks the `Term` each step. The fallback for
468/// [`eval_bool`] and the differential oracle the compiled path is validated against.
469pub fn eval_bool_tree(ctx: &Context, term: &Term) -> Option<bool> {
470    let mut fuel = FUEL;
471    let rules = LiteralRules::new(ctx);
472    match eval(ctx, rules, &Rc::new(Scope::Empty), term, &mut fuel) {
473        Val::Ctor(c, _) if c == "true" => Some(true),
474        Val::Ctor(c, _) if c == "false" => Some(false),
475        _ => None,
476    }
477}
478
479/// Build a `native_decide` proof of `prop` from a `Decidable prop` instance `inst`: if the
480/// decision procedure NATIVELY evaluates to `true`, return the proof term
481/// `of_decide_eq_true prop inst (ofReduceBool (decide prop inst) true (refl Bool true))`,
482/// which the (main) kernel checks by running this evaluator via the `reduceBool` hook —
483/// never by re-normalizing the decision procedure. Returns `None` (fail-safe) when the
484/// decision is not `true`, so it can only ever produce proofs of genuinely-true goals.
485pub fn native_decide(ctx: &Context, prop: &Term, inst: &Term) -> Option<Term> {
486    let g = |s: &str| Term::Global(s.to_string());
487    let ap = |f: Term, x: Term| Term::App(Box::new(f), Box::new(x));
488    let decide_app = ap(ap(g("decide"), prop.clone()), inst.clone());
489    if eval_bool(ctx, &decide_app) != Some(true) {
490        return None;
491    }
492    let refl_true = ap(ap(g("refl"), g("Bool")), g("true"));
493    let of_reduce = ap(ap(ap(g("ofReduceBool"), decide_app), g("true")), refl_true);
494    Some(ap(
495        ap(ap(g("of_decide_eq_true"), prop.clone()), inst.clone()),
496        of_reduce,
497    ))
498}
499
500fn lookup(scope: &Rc<Scope>, name: &str) -> Option<Val> {
501    let mut s = scope;
502    loop {
503        match s.as_ref() {
504            Scope::Empty => return None,
505            Scope::Bind(n, v, rest) => {
506                if n == name {
507                    return Some(v.clone());
508                }
509                s = rest;
510            }
511        }
512    }
513}
514
515/// Count the leading `Π`s of a constructor whose domain is a `Sort` — the inductive's
516/// parameters, when it did not declare a split (mirrors `reduction::count_type_params`).
517fn count_type_params(ty: &Term) -> usize {
518    let mut n = 0;
519    let mut cur = ty;
520    while let Term::Pi {
521        param_type,
522        body_type,
523        ..
524    } = cur
525    {
526        if matches!(param_type.as_ref(), Term::Sort(_)) {
527            n += 1;
528            cur = body_type;
529        } else {
530            break;
531        }
532    }
533    n
534}
535
536fn eval(ctx: &Context, rules: LiteralRules, scope: &Rc<Scope>, term: &Term, fuel: &mut u64) -> Val {
537    let Some(_frame) = enter_eval_frame(eval_stack_mark()) else {
538        return Val::Stuck;
539    };
540    if *fuel == 0 {
541        return Val::Stuck;
542    }
543    *fuel -= 1;
544    match term {
545        Term::Var(n) => lookup(scope, n).unwrap_or(Val::Stuck),
546        Term::Global(n) => {
547            if crate::int_inductive::accelerates_integer_alias(ctx, n) {
548                if let Some(p) = prim_name(n) {
549                    return Val::Prim(p, Vec::new());
550                }
551            }
552            if let Some(body) = ctx.get_definition_body(n) {
553                // δ-reduction: definitions are closed, so evaluate in the empty environment.
554                eval(ctx, rules, &Rc::new(Scope::Empty), body, fuel)
555            } else if ctx.is_constructor(n) {
556                Val::Ctor(n.clone(), Vec::new())
557            } else if let Some(p) =
558                prim_name(n).filter(|_| crate::reduction::declaration_agrees_with_the_rule(ctx, n))
559            {
560                Val::Prim(p, Vec::new())
561            } else {
562                Val::Stuck // inductive type, axiom, or other opaque global
563            }
564        }
565        Term::Lambda { param, body, .. } => {
566            Val::Clos(Rc::new((param.clone(), (**body).clone())), scope.clone())
567        }
568        Term::Fix { name, body } => {
569            Val::Fix(Rc::new((name.clone(), (**body).clone())), scope.clone())
570        }
571        Term::App(f, a) => {
572            // An accelerated `Nat` order over two literals is decided HERE rather than by
573            // unfolding the recursion — the tree-walker unfolds a `Fix` only on a constructor
574            // argument, so without this it is `Stuck` on exactly the pairs `normalize` decides.
575            if let Some(decided) = eval_nat_order(ctx, rules, scope, f, a, fuel) {
576                return decided;
577            }
578            let fv = eval(ctx, rules, scope, f, fuel);
579            let av = eval(ctx, rules, scope, a, fuel);
580            apply(ctx, rules, fv, av, fuel)
581        }
582        Term::Match {
583            discriminant,
584            cases,
585            ..
586        } => {
587            match rules.constructor(eval(ctx, rules, scope, discriminant, fuel)) {
588                Val::Ctor(c, args) => {
589                    // ι-reduction: select the case for `c`, applied to its VALUE arguments
590                    // (dropping the inductive's leading parameters).
591                    let ind = match ctx.constructor_inductive(&c) {
592                        Some(i) => i,
593                        None => return Val::Stuck,
594                    };
595                    let ctors = ctx.get_constructors(ind);
596                    let (idx, ctor_ty) = match ctors.iter().position(|(cn, _)| *cn == c) {
597                        Some(i) => (i, ctors[i].1.clone()),
598                        None => return Val::Stuck,
599                    };
600                    if idx >= cases.len() {
601                        return Val::Stuck;
602                    }
603                    let nparams = ctx
604                        .inductive_declared_params(ind)
605                        .unwrap_or_else(|| count_type_params(&ctor_ty));
606                    let value_args: &[Val] = if nparams < args.len() {
607                        &args[nparams..]
608                    } else {
609                        &[]
610                    };
611                    let mut sel = eval(ctx, rules, scope, &cases[idx], fuel);
612                    for va in value_args {
613                        sel = apply(ctx, rules, sel, va.clone(), fuel);
614                    }
615                    sel
616                }
617                _ => Val::Stuck,
618            }
619        }
620        Term::Lit(l) => Val::Lit(l.clone()),
621        // Sorts, Πs, holes, universe-poly consts: not part of a Bool computation.
622        _ => Val::Stuck,
623    }
624}
625
626/// `natLe`/`natLt` applied to two arguments that EVALUATE to `Nat` literals, decided in O(1).
627///
628/// `None` means "not this shape, or not two literals" — and then the caller runs the ordinary
629/// path, which unfolds the constant's own recursion, so a Peano spine decides exactly as it did
630/// before the fast path existed. The two arguments are evaluated twice in that case; it happens
631/// only for these two constants on non-literal arguments, and only on the interpreter path that
632/// the compiled backend already declined.
633fn eval_nat_order(
634    ctx: &Context,
635    rules: LiteralRules,
636    scope: &Rc<Scope>,
637    func: &Term,
638    arg: &Term,
639    fuel: &mut u64,
640) -> Option<Val> {
641    let Term::App(head, x) = func else {
642        return None;
643    };
644    let Term::Global(name) = head.as_ref() else {
645        return None;
646    };
647    let op = nat_order_name(name)?;
648    if !crate::reduction::accelerates_nat_order(ctx, op) {
649        return None;
650    }
651    let (Val::Lit(al), Val::Lit(bl)) = (
652        eval(ctx, rules, scope, x, fuel),
653        eval(ctx, rules, scope, arg, fuel),
654    ) else {
655        return None;
656    };
657    let decided = nat_order(op, &al, &bl)?;
658    Some(Val::Ctor(
659        if decided { "true" } else { "false" }.to_string(),
660        Vec::new(),
661    ))
662}
663
664fn apply(ctx: &Context, rules: LiteralRules, fv: Val, av: Val, fuel: &mut u64) -> Val {
665    if *fuel == 0 {
666        return Val::Stuck;
667    }
668    match fv {
669        Val::Clos(pb, cenv) => {
670            let ext = Rc::new(Scope::Bind(pb.0.clone(), av, cenv));
671            eval(ctx, rules, &ext, &pb.1, fuel)
672        }
673        Val::Ctor(c, mut args) => {
674            args.push(av);
675            Val::Ctor(c, args)
676        }
677        Val::Prim(name, mut args) => {
678            args.push(av);
679            if args.len() < prim_arity(name) {
680                Val::Prim(name, args)
681            } else {
682                prim_compute(rules, name, &args)
683            }
684        }
685        Val::Fix(rb, fenv) => {
686            // Unfold only when the argument is in constructor form — matches the kernel's
687            // guarded `Fix` reduction and guarantees progress on kernel-checked terms.
688            if rules.constructor_form(&av) {
689                let ext = Rc::new(Scope::Bind(
690                    rb.0.clone(),
691                    Val::Fix(rb.clone(), fenv.clone()),
692                    fenv,
693                ));
694                let unfolded = eval(ctx, rules, &ext, &rb.1, fuel);
695                apply(ctx, rules, unfolded, av, fuel)
696            } else {
697                Val::Stuck
698            }
699        }
700        // A literal is not a function.
701        Val::Lit(_) => Val::Stuck,
702        Val::Stuck => Val::Stuck,
703    }
704}
705
706// ---------------------------------------------------------------------------
707// Native closure-compiled decisions (N) — compile a ground Bool decision ONCE
708// into a tree of rustc-compiled native closures and run it, with NO Term-tree
709// walking at run time. The closures ARE machine code (rustc compiled their
710// bodies), so this is genuine "compile the decision to native code and run it",
711// the essence of `native_decide` — sound via the same `ofReduceBool` gate that
712// wraps [`native_decide`]. Reused decisions pay the compile cost once.
713// ---------------------------------------------------------------------------
714
715type IntThunk = Box<dyn Fn() -> i128>;
716type BoolThunk = Box<dyn Fn() -> bool>;
717
718fn as_binop(term: &Term) -> Option<(&str, &Term, &Term)> {
719    if let Term::App(fx, y) = term {
720        if let Term::App(op, x) = fx.as_ref() {
721            if let Term::Global(name) = op.as_ref() {
722                return Some((name.as_str(), x.as_ref(), y.as_ref()));
723            }
724        }
725    }
726    None
727}
728
729/// Compile a ground integer expression (`Int`/`BigInt` literals, `add`/`sub`/`mul`) into a
730/// native closure. `None` if the expression falls outside the compilable fragment.
731fn compile_int(term: &Term) -> Option<IntThunk> {
732    match term {
733        Term::Lit(Literal::Int(n)) => {
734            let n = *n as i128;
735            Some(Box::new(move || n))
736        }
737        Term::Lit(Literal::BigInt(n)) => {
738            let n = n.to_i64().map(|v| v as i128)?;
739            Some(Box::new(move || n))
740        }
741        _ => {
742            let (op, x, y) = as_binop(term)?;
743            let cx = compile_int(x)?;
744            let cy = compile_int(y)?;
745            match op {
746                "add" => Some(Box::new(move || cx() + cy())),
747                "sub" => Some(Box::new(move || cx() - cy())),
748                "mul" => Some(Box::new(move || cx() * cy())),
749                _ => None,
750            }
751        }
752    }
753}
754
755/// Compile a ground Bool decision (`true`/`false`, comparisons of compiled integer
756/// expressions, and `&&`/`||`-shaped `and`/`or`) into a native closure.
757fn compile_bool(term: &Term) -> Option<BoolThunk> {
758    match term {
759        Term::Global(n) if n == "true" => Some(Box::new(|| true)),
760        Term::Global(n) if n == "false" => Some(Box::new(|| false)),
761        _ => {
762            let (op, x, y) = as_binop(term)?;
763            match op {
764                "le" | "lt" | "ge" | "gt" => {
765                    let cx = compile_int(x)?;
766                    let cy = compile_int(y)?;
767                    Some(match op {
768                        "le" => Box::new(move || cx() <= cy()),
769                        "lt" => Box::new(move || cx() < cy()),
770                        "ge" => Box::new(move || cx() >= cy()),
771                        _ => Box::new(move || cx() > cy()),
772                    })
773                }
774                "and" | "or" => {
775                    let cx = compile_bool(x)?;
776                    let cy = compile_bool(y)?;
777                    Some(if op == "and" {
778                        Box::new(move || cx() && cy())
779                    } else {
780                        Box::new(move || cx() || cy())
781                    })
782                }
783                _ => None,
784            }
785        }
786    }
787}
788
789/// Compile a ground Bool decision into native closures and run it — `None` if the term is
790/// outside the compilable fragment (the caller falls back to the [`eval_bool`] interpreter).
791/// Semantics are IDENTICAL to `eval_bool`/`normalize` (differential-tested), so the
792/// `ofReduceBool` certificate `native_decide` builds is equally sound.
793pub fn native_compile_bool(term: &Term) -> Option<bool> {
794    compile_bool(term).map(|c| c())
795}
796
797// ---------------------------------------------------------------------------
798// Native RECURSOR-aware compiled decisions (N) — the general backend. The
799// arithmetic `compile_bool` above handles only ground ×/+/comparisons; this
800// compiles the FULL computational fragment — variables, λ, `fix`, application,
801// `match`, and δ-unfolding of definitions — to a tree of native closures, so a
802// RECURSIVE Bool decision (e.g. `even 1000`, a list predicate) runs as closure
803// calls with NO `Term`-tree walking. Each `Term` shape is dispatched ONCE at
804// compile time; the closures ARE the compiled decision. Semantics are IDENTICAL
805// to the tree-walking `eval` (differential-tested against it and `normalize`),
806// so the `reduceBool` hook that consumes it stays sound.
807// ---------------------------------------------------------------------------
808
809/// A run-time environment for the compiled evaluator (bound variables → values).
810enum CScope {
811    Empty,
812    Bind(Rc<str>, CVal, Rc<CScope>),
813}
814
815/// A compiled run-time value. `Fun`/`Fix` carry COMPILED bodies (closures), so applying them
816/// is a closure call, not a `Term` walk — the essence of the compiled backend.
817#[derive(Clone)]
818enum CVal {
819    /// A constructor applied to all its arguments (parameters + value args).
820    Ctor(Rc<str>, Rc<Vec<CVal>>),
821    /// A compiled `λ`: apply it to an argument to run its compiled body.
822    Fun(Rc<dyn Fn(CVal, &mut u64) -> CVal>),
823    /// A compiled `fix`: its compiled body, recursive-binder name, and captured environment.
824    Fix(Rc<FixClosure>),
825    Lit(Literal),
826    /// A partially-applied Int primitive accumulating its two arguments.
827    Prim(&'static str, Rc<Vec<CVal>>, LiteralRules),
828    Stuck,
829}
830
831impl LiteralValue for CVal {
832    fn literal_ref(&self) -> Option<&Literal> {
833        if let Self::Lit(l) = self {
834            Some(l)
835        } else {
836            None
837        }
838    }
839    fn constructor_ref(&self) -> Option<(&str, &[Self])> {
840        if let Self::Ctor(n, args) = self {
841            Some((n, args))
842        } else {
843            None
844        }
845    }
846    fn literal_value(literal: Literal) -> Self {
847        Self::Lit(literal)
848    }
849    fn constructor_value(name: &str, fields: Vec<Self>) -> Self {
850        Self::Ctor(Rc::from(name), Rc::new(fields))
851    }
852}
853
854/// The captured pieces of a compiled `fix`, unfolded on application (in [`capply`]).
855struct FixClosure {
856    body: Code,
857    name: Rc<str>,
858    env: Rc<CScope>,
859    rules: LiteralRules,
860}
861
862/// A compiled term: a closure from an environment (and a fuel budget) to a value.
863type Code = Rc<dyn Fn(&Rc<CScope>, &mut u64) -> CVal>;
864
865fn clookup(scope: &Rc<CScope>, name: &str) -> CVal {
866    let mut s = scope;
867    loop {
868        match s.as_ref() {
869            CScope::Empty => return CVal::Stuck,
870            CScope::Bind(n, v, rest) => {
871                if n.as_ref() == name {
872                    return v.clone();
873                }
874                s = rest;
875            }
876        }
877    }
878}
879
880/// Compute a fully-applied Int primitive over compiled [`CVal`]s — same [`prim_arith`] as the
881/// tree-walker, so the compiled path agrees with `eval`/`normalize`.
882fn cprim_compute(rules: LiteralRules, name: &str, args: &[CVal]) -> CVal {
883    let r = match args {
884        [a] => rules
885            .literal(a)
886            .map(|a| prim_unary(name, &a))
887            .unwrap_or(PrimResult::Stuck),
888        [a, b] => rules
889            .literal(a)
890            .zip(rules.literal(b))
891            .map(|(a, b)| prim_arith(name, &a, &b))
892            .unwrap_or(PrimResult::Stuck),
893        _ => PrimResult::Stuck,
894    };
895    match r {
896        PrimResult::Int(l) | PrimResult::Text(l) => CVal::Lit(l),
897        PrimResult::Bool(b) => CVal::Ctor(
898            Rc::from(if b { "true" } else { "false" }),
899            Rc::new(Vec::new()),
900        ),
901        PrimResult::Stuck => CVal::Stuck,
902    }
903}
904
905/// Apply a compiled value to an argument — the run-time counterpart of the tree-walker's
906/// [`apply`], with the SAME rules: a `fix` unfolds only on a constructor argument (matching the
907/// kernel's guarded `Fix` reduction), a partial primitive accumulates then computes. Fuel bounds
908/// the reduction so a non-terminating (never kernel-checked) input fails safe to `Stuck`.
909fn capply(f: CVal, arg: CVal, fuel: &mut u64) -> CVal {
910    let Some(_frame) = enter_eval_frame(eval_stack_mark()) else {
911        return CVal::Stuck;
912    };
913    if *fuel == 0 {
914        return CVal::Stuck;
915    }
916    *fuel -= 1;
917    match f {
918        CVal::Fun(func) => func(arg, fuel),
919        CVal::Ctor(c, args) => {
920            let mut v = (*args).clone();
921            v.push(arg);
922            CVal::Ctor(c, Rc::new(v))
923        }
924        CVal::Prim(name, args, rules) => {
925            let mut v = (*args).clone();
926            v.push(arg);
927            if v.len() < prim_arity(name) {
928                CVal::Prim(name, Rc::new(v), rules)
929            } else {
930                cprim_compute(rules, name, &v)
931            }
932        }
933        CVal::Fix(fx) => {
934            if fx.rules.constructor_form(&arg) {
935                let self_val = CVal::Fix(fx.clone());
936                let ext = Rc::new(CScope::Bind(fx.name.clone(), self_val, fx.env.clone()));
937                let unfolded = (fx.body)(&ext, fuel);
938                capply(unfolded, arg, fuel)
939            } else {
940                CVal::Stuck
941            }
942        }
943        CVal::Lit(_) | CVal::Stuck => CVal::Stuck,
944    }
945}
946
947/// Compiles `Term`s to [`Code`]. Holds the constructor→(index, params) table (so a compiled
948/// `Match` selects a case without touching the `Context` at run time) and a per-definition
949/// SLOT map: a definition's body is compiled once into a shared cell that recursive and mutual
950/// references read at run time — tying the knot without infinite compile-time recursion.
951struct Compiler<'c> {
952    ctx: &'c Context,
953    rules: LiteralRules,
954    ctor_map: Rc<HashMap<String, (usize, usize)>>,
955    slots: RefCell<HashMap<String, Rc<RefCell<Option<Code>>>>>,
956}
957
958impl<'c> Compiler<'c> {
959    fn new(ctx: &'c Context) -> Self {
960        // Precompute, for every registered constructor, its index within its inductive and that
961        // inductive's parameter count — the exact `(case index, value-arg offset)` a `Match`
962        // needs, resolved once here instead of per reduction.
963        let mut ctor_map = HashMap::new();
964        let inductives: Vec<String> = ctx.iter_inductives().map(|(n, _)| n.to_string()).collect();
965        for ind in &inductives {
966            let declared = ctx.inductive_declared_params(ind);
967            for (idx, (cname, cty)) in ctx.get_constructors(ind).iter().enumerate() {
968                let nparams = declared.unwrap_or_else(|| count_type_params(cty));
969                ctor_map.entry(cname.to_string()).or_insert((idx, nparams));
970            }
971        }
972        Compiler {
973            ctx,
974            rules: LiteralRules::new(ctx),
975            ctor_map: Rc::new(ctor_map),
976            slots: RefCell::new(HashMap::new()),
977        }
978    }
979
980    fn compile(&self, term: &Term) -> Code {
981        match term {
982            Term::Var(n) => {
983                let n: Rc<str> = Rc::from(n.as_str());
984                Rc::new(move |env, _| clookup(env, &n))
985            }
986            Term::Lit(l) => {
987                let l = l.clone();
988                Rc::new(move |_, _| CVal::Lit(l.clone()))
989            }
990            Term::Global(n) => self.compile_global(n),
991            Term::Lambda { param, body, .. } => {
992                let param: Rc<str> = Rc::from(param.as_str());
993                let cbody = self.compile(body);
994                Rc::new(move |env, _| {
995                    let env = env.clone();
996                    let cbody = cbody.clone();
997                    let param = param.clone();
998                    CVal::Fun(Rc::new(move |arg, fuel| {
999                        let ext = Rc::new(CScope::Bind(param.clone(), arg, env.clone()));
1000                        cbody(&ext, fuel)
1001                    }))
1002                })
1003            }
1004            Term::Fix { name, body } => {
1005                let name: Rc<str> = Rc::from(name.as_str());
1006                let rules = self.rules;
1007                let cbody = self.compile(body);
1008                Rc::new(move |env, _| {
1009                    CVal::Fix(Rc::new(FixClosure {
1010                        body: cbody.clone(),
1011                        name: name.clone(),
1012                        env: env.clone(),
1013                        rules,
1014                    }))
1015                })
1016            }
1017            Term::App(f, a) => {
1018                if let Some(fast) = self.compile_nat_order(f, a) {
1019                    return fast;
1020                }
1021                let cf = self.compile(f);
1022                let ca = self.compile(a);
1023                Rc::new(move |env, fuel| {
1024                    let fv = cf(env, fuel);
1025                    let av = ca(env, fuel);
1026                    capply(fv, av, fuel)
1027                })
1028            }
1029            Term::Match {
1030                discriminant,
1031                cases,
1032                ..
1033            } => {
1034                let cd = self.compile(discriminant);
1035                let ccases: Vec<Code> = cases.iter().map(|c| self.compile(c)).collect();
1036                let ctor_map = self.ctor_map.clone();
1037                let rules = self.rules;
1038                Rc::new(move |env, fuel| match rules.constructor(cd(env, fuel)) {
1039                    CVal::Ctor(c, args) => {
1040                        let (idx, nparams) = match ctor_map.get(c.as_ref()) {
1041                            Some(p) => *p,
1042                            None => return CVal::Stuck,
1043                        };
1044                        if idx >= ccases.len() {
1045                            return CVal::Stuck;
1046                        }
1047                        // ι-reduction: the case is run in the CURRENT environment (it may use
1048                        // outer variables), then applied to the constructor's VALUE arguments.
1049                        let mut sel = ccases[idx](env, fuel);
1050                        let value_args: &[CVal] = if nparams < args.len() {
1051                            &args[nparams..]
1052                        } else {
1053                            &[]
1054                        };
1055                        for va in value_args {
1056                            sel = capply(sel, va.clone(), fuel);
1057                        }
1058                        sel
1059                    }
1060                    _ => CVal::Stuck,
1061                })
1062            }
1063            // `MutualFix` / `Let` / sorts / `Π` / holes / universe-poly consts are not part of
1064            // the compiled Bool fragment (the tree-walker declines them too); a `Stuck` node
1065            // makes `eval_bool` fall back to the interpreter, preserving identical results.
1066            _ => Rc::new(|_, _| CVal::Stuck),
1067        }
1068    }
1069
1070    /// Compile `<natLe|natLt> x y` with the literal fast path in front of the constant's own
1071    /// recursion. The shape is recognised ONCE, at compile time, so no other application pays
1072    /// for the test; and the slow path is the definition's real δ code applied to the SAME
1073    /// already-computed arguments, so a Peano spine costs nothing extra and decides identically.
1074    fn compile_nat_order(&self, func: &Term, arg: &Term) -> Option<Code> {
1075        let Term::App(head, x) = func else {
1076            return None;
1077        };
1078        let Term::Global(name) = head.as_ref() else {
1079            return None;
1080        };
1081        let op = nat_order_name(name)?;
1082        if !crate::reduction::accelerates_nat_order(self.ctx, op) {
1083            return None;
1084        }
1085        let chead = self.compile_global(name);
1086        let cx = self.compile(x);
1087        let cy = self.compile(arg);
1088        Some(Rc::new(move |env, fuel| {
1089            let xv = cx(env, fuel);
1090            let yv = cy(env, fuel);
1091            if let (CVal::Lit(al), CVal::Lit(bl)) = (&xv, &yv) {
1092                if let Some(decided) = nat_order(op, al, bl) {
1093                    let name: Rc<str> = Rc::from(if decided { "true" } else { "false" });
1094                    return CVal::Ctor(name, Rc::new(Vec::new()));
1095                }
1096            }
1097            capply(capply(chead(env, fuel), xv, fuel), yv, fuel)
1098        }))
1099    }
1100
1101    fn compile_global(&self, n: &str) -> Code {
1102        if crate::int_inductive::accelerates_integer_alias(self.ctx, n) {
1103            if let Some(p) = prim_name(n) {
1104                let rules = self.rules;
1105                return Rc::new(move |_, _| CVal::Prim(p, Rc::new(Vec::new()), rules));
1106            }
1107        }
1108        if self.ctx.get_definition_body(n).is_some() {
1109            // δ-reduction: compile the (closed) body once into a shared slot; a recursive or
1110            // mutual reference reads the same slot at run time, so the knot is tied without
1111            // infinite compile-time recursion. The body runs in the EMPTY environment.
1112            let slot = self.def_slot(n);
1113            Rc::new(move |_env, fuel| match slot.borrow().clone() {
1114                Some(code) => code(&Rc::new(CScope::Empty), fuel),
1115                None => CVal::Stuck,
1116            })
1117        } else if self.ctx.is_constructor(n) {
1118            let n: Rc<str> = Rc::from(n);
1119            Rc::new(move |_, _| CVal::Ctor(n.clone(), Rc::new(Vec::new())))
1120        } else if let Some(p) =
1121            prim_name(n).filter(|_| crate::reduction::declaration_agrees_with_the_rule(self.ctx, n))
1122        {
1123            {
1124                let rules = self.rules;
1125                Rc::new(move |_, _| CVal::Prim(p, Rc::new(Vec::new()), rules))
1126            }
1127        } else {
1128            // Inductive type, axiom, or other opaque global.
1129            Rc::new(|_, _| CVal::Stuck)
1130        }
1131    }
1132
1133    /// Get-or-create the shared compiled-body slot for definition `n`, compiling its body once.
1134    /// The slot is registered BEFORE its body is compiled, so a self/mutual reference during
1135    /// compilation resolves to the same (initially empty) cell and reads it at run time.
1136    fn def_slot(&self, n: &str) -> Rc<RefCell<Option<Code>>> {
1137        if let Some(s) = self.slots.borrow().get(n) {
1138            return s.clone();
1139        }
1140        let s = Rc::new(RefCell::new(None));
1141        self.slots.borrow_mut().insert(n.to_string(), s.clone());
1142        let body = self
1143            .ctx
1144            .get_definition_body(n)
1145            .expect("def_slot on a definition")
1146            .clone();
1147        let cbody = self.compile(&body);
1148        *s.borrow_mut() = Some(cbody);
1149        s
1150    }
1151}
1152
1153/// Compile a closed Bool decision to native closures and run it — `None` if it does not reduce
1154/// to a Bool constructor (fail-safe; the caller falls back to the tree-walking interpreter).
1155/// Unlike [`native_compile_bool`], this handles the FULL computational fragment (recursion,
1156/// pattern matching, definitions), so recursor-based decisions compile to native code. Its
1157/// verdict is IDENTICAL to [`eval_bool_tree`]/`normalize` (differential-tested).
1158pub fn native_compile_decide(ctx: &Context, term: &Term) -> Option<bool> {
1159    let compiler = Compiler::new(ctx);
1160    let code = compiler.compile(term);
1161    let mut fuel = FUEL;
1162    match code(&Rc::new(CScope::Empty), &mut fuel) {
1163        CVal::Ctor(c, _) if c.as_ref() == "true" => Some(true),
1164        CVal::Ctor(c, _) if c.as_ref() == "false" => Some(false),
1165        _ => None,
1166    }
1167}
1168
1169#[cfg(test)]
1170#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/eval/prim_arith_tests.rs"]
1171mod prim_arith_tests;
1172
1173#[cfg(test)]
1174#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/eval/eval_tree_tests.rs"]
1175mod eval_tree_tests;