Skip to main content

logicaffeine_kernel/
simp.rs

1//! Simplifier Tactic
2//!
3//! Normalizes goals by applying rewrite rules from the context and performing
4//! arithmetic evaluation. This is a general-purpose simplification tactic.
5//!
6//! # Algorithm
7//!
8//! The simp tactic works in four steps:
9//! 1. **Extract hypotheses**: Peel implications and extract `x = t` as rewrites
10//! 2. **Simplify LHS**: Apply substitutions and arithmetic bottom-up
11//! 3. **Simplify RHS**: Apply substitutions and arithmetic bottom-up
12//! 4. **Compare**: Goal succeeds if simplified LHS equals simplified RHS
13//!
14//! # Supported Simplifications
15//!
16//! - **Reflexive equalities**: `Eq a a` succeeds immediately
17//! - **Constant folding**: `Eq (add 2 3) 5` simplifies to `Eq 5 5`
18//! - **Hypothesis substitution**: Given `x = 0`, `x + 1` becomes `0 + 1` then `1`
19//!
20//! # Arithmetic Operations
21//!
22//! Supports `add`, `sub`, `mul`, `div`, `mod` on integer literals.
23//! Non-literal arithmetic is left unevaluated.
24//!
25//! # Fuel Limit
26//!
27//! Simplification uses a fuel counter to prevent infinite loops from
28//! cyclic rewrites. The default fuel is 1000 simplification steps.
29
30use std::collections::HashMap;
31
32use crate::term::{Literal, Term};
33
34// =============================================================================
35// SIMPLIFIED SYNTAX REPRESENTATION
36// =============================================================================
37
38/// Simplified representation of Syntax terms for rewriting.
39///
40/// This is a flattened version of the kernel's `Term` type, specialized
41/// for the Syntax deep embedding. Unlike `Term`, `STerm` is designed
42/// for efficient pattern matching and rewriting during simplification.
43///
44/// The correspondence is:
45/// - `Term::App(Global("SLit"), Lit(n))` -> `STerm::Lit(n)`
46/// - `Term::App(Global("SVar"), Lit(i))` -> `STerm::Var(i)`
47/// - `Term::App(Global("SName"), Lit(s))` -> `STerm::Name(s)`
48/// - `Term::App(App(Global("SApp"), f), a)` -> `STerm::App(f, a)`
49#[derive(Debug, Clone, PartialEq, Eq, Hash)]
50pub enum STerm {
51    /// Integer literal from `SLit n`.
52    Lit(i64),
53    /// De Bruijn variable from `SVar i`.
54    Var(i64),
55    /// Named constant or function symbol from `SName s`.
56    Name(String),
57    /// Function application from `SApp f a`.
58    App(Box<STerm>, Box<STerm>),
59}
60
61/// Substitution mapping variable indices to replacement terms.
62///
63/// Extracted from hypothesis equalities like `x = t`, where `x` is a
64/// De Bruijn variable. Applied during simplification to replace variables
65/// with their known values.
66pub type Substitution = HashMap<i64, STerm>;
67
68// =============================================================================
69// TERM CONVERSION
70// =============================================================================
71
72/// Convert a kernel Term (representing Syntax) to our simplified STerm
73fn term_to_sterm(term: &Term) -> Option<STerm> {
74    // SLit n
75    if let Some(n) = extract_slit(term) {
76        return Some(STerm::Lit(n));
77    }
78
79    // SVar i
80    if let Some(i) = extract_svar(term) {
81        return Some(STerm::Var(i));
82    }
83
84    // SName s
85    if let Some(s) = extract_sname(term) {
86        return Some(STerm::Name(s));
87    }
88
89    // SApp f a
90    if let Some((f, a)) = extract_sapp(term) {
91        let sf = term_to_sterm(&f)?;
92        let sa = term_to_sterm(&a)?;
93        return Some(STerm::App(Box::new(sf), Box::new(sa)));
94    }
95
96    None
97}
98
99// =============================================================================
100// SIMPLIFICATION ENGINE
101// =============================================================================
102
103/// Simplify an STerm, reporting honestly when the budget ran out before it finished.
104///
105/// `None` means EXHAUSTED — the simplification did not reach a fixpoint, and what it had
106/// reached is not an answer. This is the same separation `reduction::normalize_checked` draws
107/// against `reduction::normalize`, and it is here for the same reason, one rung more urgent:
108/// [`check_goal`] decides a goal by simplifying BOTH sides and comparing, and
109/// `reduction::try_dsimp_solve_conclude` ACCEPTS PROOFS through that verdict. A simplifier that
110/// hands back how far it got makes "they came out equal" mean two different things — "both
111/// reached the same normal form" and "both were abandoned in the same place" — and the door
112/// cannot tell which it was handed.
113///
114/// The budget is reached by a SUBSTITUTION THAT NEVER SETTLES (`x = f x` as a hypothesis, which
115/// nothing here forbids: `decompose_goal` reads hypotheses off the goal's own implications and
116/// never checks that the variable is absent from the right-hand side) and by a term deeper than
117/// the budget. Both are now refusals rather than answers.
118fn simplify_checked(term: &STerm, subst: &Substitution, fuel: usize) -> Option<STerm> {
119    if fuel == 0 {
120        return None;
121    }
122
123    Some(match term {
124        // Variables: apply substitution if bound
125        STerm::Var(i) => {
126            if let Some(replacement) = subst.get(i) {
127                // Re-simplify the replacement (may enable more rewrites)
128                simplify_checked(replacement, subst, fuel - 1)?
129            } else {
130                term.clone()
131            }
132        }
133
134        // Literals and names are already simplified
135        STerm::Lit(_) => term.clone(),
136        STerm::Name(_) => term.clone(),
137
138        // Applications: simplify children first, then try arithmetic
139        STerm::App(f, a) => {
140            let sf = simplify_checked(f, subst, fuel - 1)?;
141            let sa = simplify_checked(a, subst, fuel - 1)?;
142
143            // Try arithmetic simplification on the simplified application
144            if let Some(result) = try_arithmetic(&sf, &sa) {
145                return simplify_checked(&result, subst, fuel - 1);
146            }
147
148            STerm::App(Box::new(sf), Box::new(sa))
149        }
150    })
151}
152
153/// The BEST-EFFORT face of [`simplify_checked`]: an exhausted budget yields how far the
154/// simplification got. ONE implementation with two faces, exactly as `normalize` is the
155/// best-effort face of `normalize_checked`, so the two can never drift apart and answer
156/// differently about the same term.
157///
158/// `#[cfg(test)]` states the fact rather than hiding it: NOTHING that certifies may use this
159/// face, and today nothing else wants it either — the module's own unit tests pin the
160/// simplifier's arithmetic directly and are its only caller. A production caller that genuinely
161/// wants best-effort simplification lifts the attribute and inherits the argument above; one
162/// that is about to CERTIFY must call [`simplify_checked`] instead.
163#[cfg(test)]
164fn simplify_sterm(term: &STerm, subst: &Substitution, fuel: usize) -> STerm {
165    simplify_checked(term, subst, fuel).unwrap_or_else(|| term.clone())
166}
167
168/// Lean 4's `Int.ediv` / `Int.emod` — this folder's own implementation of the specification
169/// written out in `reduction.rs::ediv_emod_i64`:
170///
171/// ```text
172///   b ≠ 0  ⟹  a = b·q + r   ∧   0 ≤ r < |b|
173///   b = 0  ⟹  q = 0  ∧  r = a
174/// ```
175///
176/// It has to be exactly the reducer's answer, not merely a defensible one: `check_goal` is a
177/// door `try_dsimp_solve_conclude` accepts proofs through, so a folder that still truncated
178/// would CERTIFY `(div (-7) 2) = -3` — false under the kernel's own `div`.
179fn ediv_emod(a: i64, b: i64) -> Option<(i64, i64)> {
180    if b == 0 {
181        return Some((0, a));
182    }
183    Some((a.checked_div_euclid(b)?, a.checked_rem_euclid(b)?))
184}
185
186/// Try to evaluate arithmetic operations on literals.
187/// Handles: add, sub, mul, div, mod
188fn try_arithmetic(func: &STerm, arg: &STerm) -> Option<STerm> {
189    // Pattern: (add x) y, (sub x) y, (mul x) y, etc.
190    // func = App(Name("add"), x)
191    // arg = y
192    if let STerm::App(op_box, x_box) = func {
193        if let STerm::Name(op) = op_box.as_ref() {
194            if let (STerm::Lit(x), STerm::Lit(y)) = (x_box.as_ref(), arg) {
195                let result = match op.as_str() {
196                    "add" => x.checked_add(*y)?,
197                    "sub" => x.checked_sub(*y)?,
198                    "mul" => x.checked_mul(*y)?,
199                    "div" => ediv_emod(*x, *y)?.0,
200                    "mod" => ediv_emod(*x, *y)?.1,
201                    _ => return None,
202                };
203                return Some(STerm::Lit(result));
204            }
205        }
206    }
207    None
208}
209
210// =============================================================================
211// GOAL DECOMPOSITION
212// =============================================================================
213
214/// Extract hypotheses and conclusion from a goal.
215/// Handles nested implications: h1 -> h2 -> ... -> conclusion
216/// Returns (substitution from hypotheses, conclusion)
217fn decompose_goal(goal: &Term) -> (Substitution, Term) {
218    let mut subst = HashMap::new();
219    let mut current = goal.clone();
220
221    // Peel off nested implications
222    while let Some((hyp, rest)) = extract_implication(&current) {
223        // Extract equality from hypothesis
224        if let Some((lhs, rhs)) = extract_equality(&hyp) {
225            // Convert LHS to check if it's a variable
226            if let Some(st_lhs) = term_to_sterm(&lhs) {
227                if let STerm::Var(i) = st_lhs {
228                    // Variable on LHS: add substitution i → rhs
229                    if let Some(st_rhs) = term_to_sterm(&rhs) {
230                        subst.insert(i, st_rhs);
231                    }
232                }
233            }
234        }
235        current = rest;
236    }
237
238    (subst, current)
239}
240
241/// Check if a goal is provable by simplification.
242///
243/// This is the main entry point for the simp tactic. It extracts
244/// hypothesis equalities as rewrites, simplifies both sides of the
245/// conclusion equality, and checks for syntactic equality.
246///
247/// # Supported Goals
248///
249/// - Bare equalities: `Eq a b` where `a` simplifies to `b`
250/// - Implications: `(Eq x 0) -> (Eq (add x 1) 1)` using hypothesis as rewrite
251/// - Nested implications with multiple hypothesis rewrites
252///
253/// # Returns
254///
255/// `true` if the simplified LHS equals the simplified RHS, `false` otherwise.
256pub fn check_goal(goal: &Term) -> bool {
257    let (subst, conclusion) = decompose_goal(goal);
258
259    // Conclusion must be an equality
260    let (lhs, rhs) = match extract_equality(&conclusion) {
261        Some(eq) => eq,
262        None => return false,
263    };
264
265    // Convert to STerm
266    let st_lhs = match term_to_sterm(&lhs) {
267        Some(t) => t,
268        None => return false,
269    };
270
271    let st_rhs = match term_to_sterm(&rhs) {
272        Some(t) => t,
273        None => return false,
274    };
275
276    // Simplify both sides — through the HONEST face. A side that did not finish is not
277    // evidence of anything, and `reduction::try_dsimp_solve_conclude` accepts proofs through
278    // this verdict, so "both were abandoned in the same place" must not read as "both reached
279    // the same normal form".
280    const FUEL: usize = 1000;
281    let (Some(simp_lhs), Some(simp_rhs)) = (
282        simplify_checked(&st_lhs, &subst, FUEL),
283        simplify_checked(&st_rhs, &subst, FUEL),
284    ) else {
285        return false;
286    };
287
288    // Check if they're equal
289    simp_lhs == simp_rhs
290}
291
292// =============================================================================
293// HELPER EXTRACTORS (same pattern as cc.rs)
294// =============================================================================
295
296/// Extract integer from SLit n
297fn extract_slit(term: &Term) -> Option<i64> {
298    if let Term::App(ctor, arg) = term {
299        if let Term::Global(name) = ctor.as_ref() {
300            if name == "SLit" {
301                if let Term::Lit(Literal::Int(n)) = arg.as_ref() {
302                    return Some(*n);
303                }
304            }
305        }
306    }
307    None
308}
309
310/// Extract variable index from SVar i
311fn extract_svar(term: &Term) -> Option<i64> {
312    if let Term::App(ctor, arg) = term {
313        if let Term::Global(name) = ctor.as_ref() {
314            if name == "SVar" {
315                if let Term::Lit(Literal::Int(i)) = arg.as_ref() {
316                    return Some(*i);
317                }
318            }
319        }
320    }
321    None
322}
323
324/// Extract name from SName "x"
325fn extract_sname(term: &Term) -> Option<String> {
326    if let Term::App(ctor, arg) = term {
327        if let Term::Global(name) = ctor.as_ref() {
328            if name == "SName" {
329                if let Term::Lit(Literal::Text(s)) = arg.as_ref() {
330                    return Some(s.clone());
331                }
332            }
333        }
334    }
335    None
336}
337
338/// Extract unary application: SApp f a
339fn extract_sapp(term: &Term) -> Option<(Term, Term)> {
340    if let Term::App(outer, arg) = term {
341        if let Term::App(sapp, func) = outer.as_ref() {
342            if let Term::Global(ctor) = sapp.as_ref() {
343                if ctor == "SApp" {
344                    return Some((func.as_ref().clone(), arg.as_ref().clone()));
345                }
346            }
347        }
348    }
349    None
350}
351
352/// Extract an implication, in EVERY spelling the reflected surface has for it.
353///
354/// THE SPECIFICATION, stated once and implemented here in this module's own idiom (never copied
355/// from `reduction.rs`'s reader, which is written over its own extractors):
356///
357/// > `A → B` is `SApp (SApp (SName "implies") A) B`, `SApp (SApp (SName "Implies") A) B`, or a
358/// > NON-DEPENDENT `SPi A B` — one whose consequent mentions no de Bruijn index. A dependent
359/// > `SPi` is a quantifier and is not an implication.
360///
361/// Reading only the lower-case spelling is why an induction step case — built capitalised — was
362/// invisible to every goal reader, and why the literate `Statement:` surface's infix `implies`,
363/// which desugars to a `Pi` and reflects as an `SPi`, could not be simplified at all.
364fn extract_implication(term: &Term) -> Option<(Term, Term)> {
365    if let Some((op, hyp, concl)) = extract_binary_app(term) {
366        if op == "implies" || op == "Implies" {
367            return Some((hyp, concl));
368        }
369    }
370    let (hyp, concl) = extract_spi(term)?;
371    if mentions_svar(&concl) {
372        return None;
373    }
374    Some((hyp, concl))
375}
376
377/// Extract `SPi A B`.
378fn extract_spi(term: &Term) -> Option<(Term, Term)> {
379    if let Term::App(outer, body) = term {
380        if let Term::App(spi, param) = outer.as_ref() {
381            if let Term::Global(ctor) = spi.as_ref() {
382                if ctor == "SPi" {
383                    return Some((param.as_ref().clone(), body.as_ref().clone()));
384                }
385            }
386        }
387    }
388    None
389}
390
391/// Whether a reflected term mentions any de Bruijn index.
392fn mentions_svar(term: &Term) -> bool {
393    if extract_svar(term).is_some() {
394        return true;
395    }
396    match term {
397        Term::App(f, x) => mentions_svar(f) || mentions_svar(x),
398        _ => false,
399    }
400}
401
402/// Extract equality: SApp (SApp (SName "Eq") lhs) rhs
403/// Also handles: SApp (SApp (SApp (SName "Eq") ty) lhs) rhs
404fn extract_equality(term: &Term) -> Option<(Term, Term)> {
405    // Try binary Eq first (no type annotation)
406    if let Some((op, lhs, rhs)) = extract_binary_app(term) {
407        if op == "Eq" || op == "eq" {
408            return Some((lhs, rhs));
409        }
410    }
411
412    // Try ternary Eq (with type annotation): (Eq T) lhs rhs
413    if let Some((lhs, rhs)) = extract_ternary_eq(term) {
414        return Some((lhs, rhs));
415    }
416
417    None
418}
419
420/// Extract ternary equality: SApp (SApp (SApp (SName "Eq") ty) lhs) rhs
421fn extract_ternary_eq(term: &Term) -> Option<(Term, Term)> {
422    // term = SApp func rhs, where func = SApp (SApp (SName "Eq") ty) lhs
423    let (func, rhs) = extract_sapp(term)?;
424
425    // func = SApp func2 lhs, where func2 = SApp (SName "Eq") ty
426    let (func2, lhs) = extract_sapp(&func)?;
427
428    // func2 = SApp eq_name ty, where eq_name = SName "Eq"
429    let (eq_name, _ty) = extract_sapp(&func2)?;
430
431    // Check that eq_name is SName "Eq"
432    let name = extract_sname(&eq_name)?;
433    if name == "Eq" {
434        return Some((lhs, rhs));
435    }
436
437    None
438}
439
440/// Extract binary application: SApp (SApp (SName "op") a) b
441fn extract_binary_app(term: &Term) -> Option<(String, Term, Term)> {
442    if let Term::App(outer, b) = term {
443        if let Term::App(sapp_outer, inner) = outer.as_ref() {
444            if let Term::Global(ctor) = sapp_outer.as_ref() {
445                if ctor == "SApp" {
446                    if let Term::App(partial, a) = inner.as_ref() {
447                        if let Term::App(sapp_inner, op_term) = partial.as_ref() {
448                            if let Term::Global(ctor2) = sapp_inner.as_ref() {
449                                if ctor2 == "SApp" {
450                                    if let Some(op) = extract_sname(op_term) {
451                                        return Some((op, a.as_ref().clone(), b.as_ref().clone()));
452                                    }
453                                }
454                            }
455                        }
456                    }
457                }
458            }
459        }
460    }
461    None
462}
463
464// =============================================================================
465// UNIT TESTS
466// =============================================================================
467
468#[cfg(test)]
469#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/simp/tests.rs"]
470mod tests;