logicaffeine_kernel/termination.rs
1//! Termination checking for fixpoints.
2//!
3//! This module implements the syntactic guard condition that ensures all recursive functions
4//! terminate. Without this check, the type system would be unsound — we could "prove" `False`
5//! by writing `fix f. f`.
6//!
7//! # The measure
8//!
9//! The guard decides the LEXICOGRAPHIC product of the structural-subterm order `◁` over an
10//! ORDERED list of COLUMNS:
11//!
12//! * **Column 0** is the Giménez structural argument — the binder the body's `match`
13//! discriminates on, or, when the body does not match on a binder, the first inductive-typed
14//! one. This is what lets an INDEXED family recurse: `le.rec`'s fixpoint is
15//! `fix rec. λm:Nat. λh:le n m. match h …` and the structural argument is the PROOF `h`
16//! (position 1), not the `Nat` index `m`.
17//! * **Columns 1…** are the remaining inductive-typed binders of the λ-telescope, in
18//! positional order.
19//!
20//! A recursive call — to this fixpoint or a sibling in the same mutual block — is admitted iff
21//! there is a column `i` whose argument is a strict subterm of column `i`'s parameter and, for
22//! every earlier column `j < i`, the argument is a strict subterm OR definitionally that
23//! column's parameter. `Succ m1` inside `match m with | Succ m1 => …` is definitionally `m`, so
24//! Ackermann's inner call `ack (Succ m1) n2` holds column 0 EQUAL and decreases column 1 —
25//! which is exactly `termination_by m n => (m, n)`.
26//!
27//! The lexicographic product of finitely many copies of a well-founded relation is
28//! well-founded, and `◁` (strict structural subterm) is well-founded on well-typed values, so
29//! an admitted call chain cannot be infinite. Note that `◁` is one relation over ALL terms —
30//! it does not depend on the column's type — which is what makes a mutual block's members share
31//! a single measure even when their columns are typed differently.
32//!
33//! # What is NOT in the measure
34//!
35//! "Smaller in SOME column" is not a decrease: a subterm of column 1 says nothing about
36//! column 0, and a measure that let one discharge the other would accept `f n2 m1`, which grows.
37//! The scan therefore stops at the first column that is neither smaller nor equal.
38//!
39//! # The subterm analysis
40//!
41//! Deciding `t ◁ p` is more than "is `t` a variable the match bound". Following Coq's
42//! `subterm_specif`, the guard also walks β-redexes, δ-unfolds a transparent definition
43//! applied to arguments, and analyses a `match` on a term already known `≤ p` as the MEET over
44//! its branches (each branch's fields being themselves subterms of `p`). `pred n` δ-unfolds to
45//! `match n with | Zero => Zero | Succ k => k`, whose `Zero` branch yields `Zero` — NOT a
46//! strict subterm of `n` when `n` IS `Zero` — so the meet refuses it, exactly as Coq does.
47//!
48//! # The refutation refinement — `decreasing_by`, discharged in the kernel
49//!
50//! One branch of that meet can be RULED OUT. In case `isFalse` of a `match` whose discriminant
51//! is a δ-transparent, kernel-checked DECISION PROCEDURE applied to the recursion's own data,
52//! the case binds `hn : ¬(x = C)` for a NULLARY constructor `C`. Reaching that branch requires
53//! the discriminant to have ι-reduced to `isFalse _`; since the decision procedure is a closed,
54//! kernel-checked definition, its reduction at a closed `x ↝ C` would have to produce a closed
55//! inhabitant of `¬(C = C)` — a closed proof of `False`. So where the axioms in scope are
56//! consistent, the branch is unreachable at `x ↝ C` and the `C` branch of the meet drops out.
57//! For a two-constructor inductive that pins `x`'s head to the other constructor, and `pred n`
58//! becomes `n`'s `Succ` field — a genuine strict subterm.
59//!
60//! This is the ONE rule here whose soundness is conditional on the consistency of the axioms in
61//! scope rather than unconditional, so it is fenced hard: the discriminant's head must be a
62//! `Context::is_definition` (never a bound variable, never an axiom), every argument of its
63//! spine must be a column parameter, a known subterm, a constructor application or a literal,
64//! the refuted constructor must be NULLARY, the refined variable must be a live column's own
65//! parameter, and it must be the discriminant's ONLY free variable. The argument above needs
66//! the decision closed at `x ↝ C`: with a second open argument, a hypothesis `e : False` say, a
67//! checked procedure can answer `isFalse (λh. e)` at `C` under `e`'s binder, the branch is
68//! reached, and the recursion never ends there. `crates/logicaffeine_tests/tests/G_recursor_extra.rs`
69//! pins each fence with the neighbouring shape it must still refuse, and
70//! `crates/logicaffeine_tests/tests/kernel_paradox_corpus.rs` the closedness fence.
71
72use std::collections::{HashMap, HashSet};
73
74use crate::context::Context;
75use crate::error::{KernelError, KernelResult};
76use crate::term::Term;
77
78/// How deep the subterm analysis may δ-unfold and descend through `match` branches before
79/// giving up. A budget is required, not merely prudent: a recursive definition unfolds
80/// forever, and the guard must terminate even when its subject does not.
81const SUBTERM_FUEL: u32 = 8;
82
83/// One column of the lexicographic structural measure.
84#[derive(Clone)]
85struct Column {
86 /// The λ-binder's name in the CURRENT body.
87 name: String,
88 /// Its argument POSITION in the λ-telescope, so a call's spine can be indexed.
89 pos: usize,
90 /// The inductive this column's type heads — the constructors a `match` on it expects.
91 ind: String,
92 /// The binder's full type (`TList Nat`), so the inductive's PARAMETERS are available when
93 /// the branch's rebuilt constructor application is compared against a call's argument.
94 ty: Term,
95 /// False once an inner binder shadows `name`: the column's parameter is then no longer
96 /// reachable, so nothing can be shown equal to it or smaller than it.
97 live: bool,
98}
99
100/// How an argument compares with one column's parameter.
101#[derive(Clone, Copy, PartialEq, Eq, Debug)]
102enum Rel {
103 /// A strict structural subterm — this column decreases.
104 Smaller,
105 /// Definitionally the column's parameter — this column is held.
106 Equal,
107 /// Neither could be established. The lexicographic scan must stop here.
108 Unknown,
109}
110
111/// Context for termination checking.
112#[derive(Clone)]
113struct GuardContext {
114 /// Each fixpoint name in the (possibly mutual) block → the ordered argument POSITIONS of
115 /// its own columns. A call to ANY member must decrease, and the argument it supplies at
116 /// THAT member's column `c` is compared against the CURRENT body's column `c`.
117 fix_columns: HashMap<String, Vec<usize>>,
118 /// The CURRENT body's columns, in measure order.
119 columns: Vec<Column>,
120 /// How many columns the comparison may use: the MINIMUM column count over the block, so
121 /// every member's measure lands in the same `Terms^K` and the lexicographic order is one
122 /// order rather than one per member.
123 lex_width: usize,
124 /// Variables known to be strict structural SUBTERMS of a column's parameter:
125 /// name → (column index, the inductive its own type heads, or `""` when that type heads
126 /// no inductive).
127 ///
128 /// The subterm relation is TRANSITIVE — a field of a field of `n` is a subterm of `n` — so
129 /// a `match` on a variable already known smaller contributes its own constructor fields at
130 /// the SAME column. That is what makes `| n+2 => …` structurally admissible, and it is why
131 /// the inductive name has to be recorded: the nested match's constructors come from the
132 /// SCRUTINEE's type, which need not be the column's.
133 smaller_than: HashMap<String, (usize, String)>,
134 /// A live column's parameter re-expressed as the constructor application the branch
135 /// destructured it into (`m ≡ Succ m1`), keyed by column index. This is the EQUAL half of
136 /// the lexicographic order — without it, `ack (Succ m1) n2` looks like an increase.
137 rebuilt: HashMap<usize, Term>,
138 /// A column parameter whose constructor HEAD the branch's refutation hypothesis pins.
139 known_head: HashMap<String, String>,
140 /// Fixpoint names shadowed by an inner binder — a call to such a name refers to the
141 /// shadowing binding, not our block, so it is not a recursive call.
142 shadowed_fix: HashSet<String>,
143}
144
145impl GuardContext {
146 /// A stable name for the fixpoint block, for error messages.
147 fn block_name(&self) -> String {
148 let mut names: Vec<&String> = self.fix_columns.keys().collect();
149 names.sort();
150 names
151 .iter()
152 .map(|s| s.as_str())
153 .collect::<Vec<_>>()
154 .join("/")
155 }
156
157 /// The index of the LIVE column whose parameter is named `name`.
158 fn live_column(&self, name: &str) -> Option<usize> {
159 self.columns.iter().position(|c| c.live && c.name == name)
160 }
161
162 /// A one-line description of the current measure, so a refusal says what it measured.
163 fn measure(&self) -> String {
164 let cols: Vec<String> = self.columns[..self.lex_width.min(self.columns.len())]
165 .iter()
166 .map(|c| {
167 if c.live {
168 c.name.clone()
169 } else {
170 format!("{} (shadowed)", c.name)
171 }
172 })
173 .collect();
174 cols.join(", ")
175 }
176}
177
178/// **THE ι-SPECIFICATION — which argument makes a `Fix` unroll.**
179///
180/// The ORDERED argument positions of the lexicographic measure this guard admitted for `body`
181/// (the λ-abstraction under a `Fix`), with column 0 — the Giménez structural argument — first.
182/// Empty when `body` has no inductive-typed binder at all, i.e. when the guard would refuse it.
183///
184/// This exists because a REDUCER has to agree with the guard, and the specification of ι for a
185/// fixpoint is:
186///
187/// > `(fix f. λx₀ … λxₙ. e) a₀ … aₙ` unrolls exactly when the argument at the STRUCTURAL
188/// > position — `structural_columns(ctx, body)[0]` — is in constructor form.
189///
190/// Not "when `a₀` is", which is a different rule and a strictly smaller one: the guard reads the
191/// structural column off the body's own `match`, so `fix f. λm. λn. match n with …` — Lean's
192/// `Nat.add`, which recurses on its SECOND argument — is admitted with column 0 at position 1. A
193/// reducer that insists on position 0 leaves that definition STUCK for every non-constructor
194/// first argument, so `n + 0 = n` is not `rfl` here where it is `rfl` in Lean, and `normalize`
195/// hands back a term that still has a δι-redex in it. Not "when SOME argument is", either: that
196/// unrolls on a non-structural constructor and makes progress the guard never promised.
197///
198/// The two kernels must each implement that rule from this specification — `reduction.rs` over
199/// named terms, `recheck.rs` over de Bruijn levels — and NOT by calling one another or by sharing
200/// a reduction routine. What is shared here is only the guard's own answer to "which column",
201/// which the guard alone is the authority on: a reducer that guesses it is a reducer that
202/// computes a function the guard did not check.
203pub fn structural_columns(ctx: &Context, body: &Term) -> Vec<usize> {
204 match extract_columns(ctx, body) {
205 Ok((columns, _)) => columns.iter().map(|c| c.pos).collect(),
206 Err(_) => Vec::new(),
207 }
208}
209
210/// The single argument POSITION a reducer needs: the Giménez structural column, or `None` when
211/// the guard admits no column at all and therefore no ι rule applies to this fixpoint.
212///
213/// [`structural_columns`] answers with the whole measure because the GUARD needs the whole
214/// measure. A reducer needs one number, and asking it for `[0]` is an index into a vector that
215/// is empty exactly when the answer is "there is none" — so the two honest outcomes are spelled
216/// as `Some`/`None` here rather than left to a caller to remember. `(fix f. λx₀ … λxₙ. e) a₀ … aₙ`
217/// unrolls exactly when `a_p` is constructor-headed, for `p` this position.
218///
219/// ```
220/// use logicaffeine_kernel::prelude::StandardLibrary;
221/// use logicaffeine_kernel::termination::structural_position;
222/// use logicaffeine_kernel::{Term, Universe};
223///
224/// let ctx = StandardLibrary::context();
225/// let g = |n: &str| Term::Global(n.into());
226/// let v = |n: &str| Term::Var(n.into());
227/// let app = |f: Term, x: Term| Term::App(Box::new(f), Box::new(x));
228/// let lam = |p: &str, t: Term, b: Term| Term::Lambda { param: p.into(), param_type: Box::new(t), body: Box::new(b) };
229///
230/// // Lean's `Nat.add` recurses on its SECOND argument: λm. λn. match n with 0 ⇒ m | k+1 ⇒ (add m k)+1.
231/// let add = lam("m", g("Nat"), lam("n", g("Nat"), Term::Match {
232/// discriminant: Box::new(v("n")),
233/// motive: Box::new(lam("_", g("Nat"), g("Nat"))),
234/// cases: vec![v("m"), lam("k", g("Nat"), app(g("Succ"), app(app(v("add"), v("m")), v("k"))))],
235/// }));
236/// assert_eq!(structural_position(ctx, &add), Some(1));
237///
238/// // No inductive-typed binder: no column, so no ι rule.
239/// let id = lam("A", Term::Sort(Universe::Type(0)), lam("a", v("A"), v("a")));
240/// assert_eq!(structural_position(ctx, &id), None);
241/// ```
242///
243/// A fixpoint the guard would REFUSE gets `None`, which is the right answer for a reducer too:
244/// an unguarded fixpoint has no ι rule, and unrolling one is how a normaliser diverges.
245pub fn structural_position(ctx: &Context, body: &Term) -> Option<usize> {
246 extract_columns(ctx, body)
247 .ok()
248 .and_then(|(columns, _)| columns.first().map(|c| c.pos))
249}
250
251/// Shared recursion-column policy for named and de Bruijn syntax. Prefer the
252/// matched parameter when inductive-typed, otherwise the first inductive one.
253pub(crate) fn select_structural_position(
254 candidates: impl IntoIterator<Item = (usize, bool)>,
255 preferred: Option<usize>,
256) -> Option<usize> {
257 let mut first = None;
258 for (position, inductive) in candidates {
259 if inductive {
260 if preferred == Some(position) {
261 return Some(position);
262 }
263 first.get_or_insert(position);
264 }
265 }
266 first
267}
268
269/// Check that a Fix term satisfies the syntactic guard condition.
270///
271/// This is the main entry point for termination checking.
272pub fn check_termination(ctx: &Context, fix_name: &str, body: &Term) -> KernelResult<()> {
273 let (columns, core) = extract_columns(ctx, body)?;
274 let positions: Vec<usize> = columns.iter().map(|c| c.pos).collect();
275 let lex_width = positions.len();
276
277 // A single fixpoint is a mutual block of one.
278 let mut fix_columns = HashMap::new();
279 fix_columns.insert(fix_name.to_string(), positions);
280 let guard_ctx = seed_context(body, fix_columns, columns, lex_width);
281
282 guard_telescope(ctx, &guard_ctx, body)?;
283 check_guarded(ctx, &guard_ctx, core)
284}
285
286/// Check that a MUTUAL block of fixpoints terminates — the mutual Giménez guard.
287///
288/// Every member's columns are computed first; then each body is checked so that a call to ANY
289/// member — itself OR a sibling — decreases the SHARED lexicographic measure with respect to
290/// the CURRENT body's columns. Any infinite call chain would then demand an infinite strictly
291/// descending sequence in `Terms^K`, which cannot exist — so the whole block terminates.
292/// `Even.rec`'s fixpoint calling `Odd.rec` on the sub-proof, and vice versa, is exactly what
293/// this guards.
294///
295/// `K` is the MINIMUM column count over the block: every member's measure must land in one
296/// common `Terms^K`, or the comparison would be between tuples of different shapes.
297pub fn check_termination_mutual(ctx: &Context, defs: &[(String, Term)]) -> KernelResult<()> {
298 if defs.is_empty() {
299 return Err(KernelError::TerminationViolation {
300 fix_name: String::new(),
301 reason: "empty mutual fixpoint block".to_string(),
302 });
303 }
304 // 1. Columns of every member.
305 let mut fix_columns = HashMap::new();
306 let mut per_member: Vec<Vec<Column>> = Vec::with_capacity(defs.len());
307 let mut lex_width = usize::MAX;
308 for (name, body) in defs {
309 let (columns, _) = extract_columns(ctx, body)?;
310 fix_columns.insert(
311 name.clone(),
312 columns.iter().map(|c| c.pos).collect::<Vec<_>>(),
313 );
314 lex_width = lex_width.min(columns.len());
315 per_member.push(columns);
316 }
317 // 2. Check every body against the whole block.
318 for (i, (_, body)) in defs.iter().enumerate() {
319 let (_, core) = extract_columns(ctx, body)?;
320 let guard_ctx = seed_context(body, fix_columns.clone(), per_member[i].clone(), lex_width);
321 guard_telescope(ctx, &guard_ctx, body)?;
322 check_guarded(ctx, &guard_ctx, core)?;
323 }
324 Ok(())
325}
326
327/// The guard context a body starts in: its columns, plus the block members its own λ-telescope
328/// SHADOWS. A binder named after a block member rebinds that name, so occurrences inside the
329/// body denote the binder and are not recursive calls at all.
330fn seed_context(
331 body: &Term,
332 fix_columns: HashMap<String, Vec<usize>>,
333 columns: Vec<Column>,
334 lex_width: usize,
335) -> GuardContext {
336 let mut shadowed_fix = HashSet::new();
337 let mut cur = body;
338 while let Term::Lambda {
339 param, body: inner, ..
340 } = cur
341 {
342 if fix_columns.contains_key(param) {
343 shadowed_fix.insert(param.clone());
344 }
345 cur = inner;
346 }
347 GuardContext {
348 fix_columns,
349 columns,
350 lex_width,
351 smaller_than: HashMap::new(),
352 rebuilt: HashMap::new(),
353 known_head: HashMap::new(),
354 shadowed_fix,
355 }
356}
357
358/// Guard every λ-telescope binder's DOMAIN annotation. The telescope is peeled whole before the
359/// body is walked, so without this a recursive occurrence hidden in a parameter's type would
360/// never be visited.
361///
362/// Binder `i`'s domain is checked with every column bound at or after `i` marked DEAD: those
363/// parameters are not in scope there, so nothing in that domain may be compared against them.
364/// The type checker would reject such a reference anyway, but a guard that can be talked into
365/// admitting a call by reading a not-yet-bound column is a guard that only works because
366/// something else is watching.
367fn guard_telescope(ctx: &Context, guard_ctx: &GuardContext, body: &Term) -> KernelResult<()> {
368 let mut cur = body;
369 let mut i = 0usize;
370 while let Term::Lambda {
371 param_type,
372 body: inner,
373 ..
374 } = cur
375 {
376 let mut scoped = guard_ctx.clone();
377 for c in scoped.columns.iter_mut() {
378 if c.pos >= i {
379 c.live = false;
380 }
381 }
382 check_guarded(ctx, &scoped, param_type)?;
383 cur = inner;
384 i += 1;
385 }
386 Ok(())
387}
388
389/// Identify the COLUMNS of the lexicographic measure and return the body past the whole
390/// λ-telescope.
391///
392/// Column 0 is the binder the body's `match` actually discriminates on (the scrutinee) when
393/// that binder is inductive-typed — this is what lets an INDEXED family recurse on its proof
394/// rather than on a `Nat` index — and otherwise the first inductive-typed binder. The
395/// remaining inductive-typed binders follow in positional order.
396///
397/// A binder that REBINDS an earlier column's name kills that column: within the telescope the
398/// name already denotes the later binder, so nothing can be compared against the earlier one.
399fn extract_columns<'a>(ctx: &Context, body: &'a Term) -> KernelResult<(Vec<Column>, &'a Term)> {
400 // Peel the λ-telescope, recording each binder and its type.
401 let mut chain: Vec<(&'a str, &'a Term)> = Vec::new();
402 let mut cur = body;
403 while let Term::Lambda {
404 param,
405 param_type,
406 body: inner,
407 } = cur
408 {
409 chain.push((param.as_str(), param_type.as_ref()));
410 cur = inner;
411 }
412
413 // The scrutinee: the binder the innermost `match` discriminates on, if any, read through an
414 // application spine, so a convoy `(match v … ) w …` recurses on `v` as a bare `match` does.
415 let mut matched = cur;
416 while let Term::App(function, _) = matched {
417 matched = function;
418 }
419 let scrutinee = match matched {
420 Term::Match { discriminant, .. } => match discriminant.as_ref() {
421 Term::Var(d) => chain.iter().position(|(n, _)| n == d),
422 _ => None,
423 },
424 _ => None,
425 };
426
427 let primary = select_structural_position(
428 chain
429 .iter()
430 .enumerate()
431 .map(|(position, (_, ty))| (position, extract_inductive_name(ctx, ty).is_some())),
432 scrutinee,
433 )
434 .ok_or_else(|| KernelError::TerminationViolation {
435 fix_name: String::new(),
436 reason: "No inductive parameter found for structural recursion".to_string(),
437 })?;
438
439 let mut order: Vec<usize> = vec![primary];
440 for (i, (_, t)) in chain.iter().enumerate() {
441 if i != primary && extract_inductive_name(ctx, t).is_some() {
442 order.push(i);
443 }
444 }
445 let mut columns: Vec<Column> = order
446 .iter()
447 .map(|&i| Column {
448 name: chain[i].0.to_string(),
449 pos: i,
450 ind: extract_inductive_name(ctx, chain[i].1).unwrap(),
451 ty: chain[i].1.clone(),
452 live: true,
453 })
454 .collect();
455 for (i, (n, _)) in chain.iter().enumerate() {
456 for c in columns.iter_mut() {
457 if c.pos < i && c.name == *n {
458 c.live = false;
459 }
460 }
461 }
462 Ok((columns, cur))
463}
464
465/// Extract the inductive type name from a type.
466///
467/// Handles both simple inductives like `Nat` and polymorphic ones like `List A`.
468fn extract_inductive_name(ctx: &Context, ty: &Term) -> Option<String> {
469 match ty {
470 Term::Global(name) | Term::Const { name, .. } if ctx.is_inductive(name) => {
471 Some(name.clone())
472 }
473 Term::App(func, _) => extract_inductive_name(ctx, func),
474 _ => None,
475 }
476}
477
478/// Build the guard context for the scope under a binder that introduces `param`.
479///
480/// The binder shadows any prior meaning of `param`: within its body `param` no longer refers to
481/// a column's parameter, a structurally-smaller variable, a refined variable, or the fixpoint
482/// itself. Failing to honor this lets an inner `match` on a shadowed name be mistaken for the
483/// guarding match (admitting a non-decreasing recursion), or an inner binding of a
484/// smaller-marked name keep its "smaller" status after being rebound to an arbitrary value.
485fn enter_binder(guard_ctx: &GuardContext, param: &str) -> GuardContext {
486 let mut child = guard_ctx.clone();
487 child.smaller_than.remove(param);
488 child.known_head.remove(param);
489 let killed: Vec<usize> = child
490 .columns
491 .iter()
492 .enumerate()
493 .filter(|(_, c)| c.live && c.name == param)
494 .map(|(i, _)| i)
495 .collect();
496 for i in killed {
497 child.columns[i].live = false;
498 child.rebuilt.remove(&i);
499 }
500 if guard_ctx.fix_columns.contains_key(param) {
501 child.shadowed_fix.insert(param.to_string());
502 }
503 child
504}
505
506/// Check that all recursive calls in `term` are guarded (decrease the lexicographic measure).
507fn check_guarded(ctx: &Context, guard_ctx: &GuardContext, term: &Term) -> KernelResult<()> {
508 match term {
509 // Application. Peel the spine into (head, args-in-order). The recursive name is allowed
510 // to occur ONLY here, as the head of a call that decreases the measure; in that
511 // position the head is *consumed* by the application and must NOT be re-descended as a
512 // bare value. Every argument is still checked, so a recursive name smuggled into an
513 // argument (`g f`) is caught by the `Var` leaf below.
514 Term::App(func, arg) => {
515 let mut args: Vec<&Term> = vec![arg.as_ref()];
516 let mut head = func.as_ref();
517 while let Term::App(inner_func, inner_arg) = head {
518 args.push(inner_arg.as_ref());
519 head = inner_func.as_ref();
520 }
521 args.reverse();
522
523 if let Term::Var(name) = head {
524 if !guard_ctx.shadowed_fix.contains(name) {
525 if let Some(cols) = guard_ctx.fix_columns.get(name) {
526 verify_lex_decrease(ctx, guard_ctx, name, cols, &args)?;
527 for a in &args {
528 check_guarded(ctx, guard_ctx, a)?;
529 }
530 return Ok(());
531 }
532 }
533 }
534
535 // Not a recursive call at the head: check the head and every argument normally.
536 check_guarded(ctx, guard_ctx, head)?;
537 for a in &args {
538 check_guarded(ctx, guard_ctx, a)?;
539 }
540 Ok(())
541 }
542
543 // A match on a column's parameter (or on a variable already known smaller) introduces
544 // that constructor's fields as strict subterms of THAT column, and records the
545 // parameter's rebuilt constructor application so a call passing it reads as EQUAL.
546 Term::Match { discriminant, motive, cases } => {
547 // The return motive is an ordinary subterm (in the current scope) and MUST be
548 // guarded too — a recursive occurrence hidden in the return predicate would
549 // otherwise evade the check, diverging from the standard CIC guard.
550 check_guarded(ctx, guard_ctx, motive)?;
551 if let Term::Var(disc_name) = discriminant.as_ref() {
552 if let Some(ci) = guard_ctx.live_column(disc_name) {
553 let col = guard_ctx.columns[ci].clone();
554 return check_match_cases_guarded(
555 ctx,
556 guard_ctx,
557 cases,
558 &col.ind,
559 ci,
560 Some(&col.ty),
561 );
562 }
563 if let Some((ci, ind)) = guard_ctx.smaller_than.get(disc_name).cloned() {
564 if !ind.is_empty() {
565 return check_match_cases_guarded(ctx, guard_ctx, cases, &ind, ci, None);
566 }
567 }
568 }
569
570 // Not a guarding match. Its branches may still carry a REFUTATION that pins a
571 // column parameter's constructor head — Lean's `decreasing_by` hypothesis.
572 check_guarded(ctx, guard_ctx, discriminant)?;
573 let refinements = decidable_refinements(ctx, guard_ctx, discriminant, cases);
574 for (i, case) in cases.iter().enumerate() {
575 match refinements.get(&i) {
576 Some((x, ctor)) => {
577 let mut child = guard_ctx.clone();
578 child.known_head.insert(x.clone(), ctor.clone());
579 check_guarded(ctx, &child, case)?;
580 }
581 None => check_guarded(ctx, guard_ctx, case)?,
582 }
583 }
584 Ok(())
585 }
586
587 // Lambda: guard the DOMAIN annotation (current scope) as well as the body — a
588 // recursive occurrence in a binder's type must not evade the check. The binder may
589 // shadow a column's parameter, a smaller variable, or the fixpoint name.
590 Term::Lambda { param, param_type, body } => {
591 check_guarded(ctx, guard_ctx, param_type)?;
592 let child = enter_binder(guard_ctx, param);
593 check_guarded(ctx, &child, body)
594 }
595
596 // Pi: same domain + binder-shadowing handling as Lambda.
597 Term::Pi { param, param_type, body_type } => {
598 check_guarded(ctx, guard_ctx, param_type)?;
599 let child = enter_binder(guard_ctx, param);
600 check_guarded(ctx, &child, body_type)
601 }
602
603 // Nested fixpoint: its own name shadows ours; its body gets its own
604 // termination check when type-checked.
605 Term::Fix { name, body } => {
606 let child = enter_binder(guard_ctx, name);
607 check_guarded(ctx, &child, body)
608 }
609
610 // Nested MUTUAL fixpoint: all of its names shadow ours; each body gets its own
611 // mutual termination check when type-checked.
612 Term::MutualFix { defs, .. } => {
613 let mut child = enter_binder(guard_ctx, &defs[0].0);
614 for (n, _) in &defs[1..] {
615 child = enter_binder(&child, n);
616 }
617 for (_, b) in defs {
618 check_guarded(ctx, &child, b)?;
619 }
620 Ok(())
621 }
622
623 // Let: the type and value are in the outer scope; the body is under the let-binder,
624 // which may shadow the tracked names.
625 //
626 // A let-bound name whose VALUE is an already-smaller variable INHERITS its smallness,
627 // at the SAME column. Zeta makes `let x := v in b` and `b[x := v]` the same term, so if
628 // `v` is a structural subterm then so is `x` — refusing the alias rejected a definition
629 // purely for how it was spelled, and a lowering pass that introduces a `let` for
630 // sharing turned a passing definition into a build error.
631 Term::Let { name, ty, value, body, .. } => {
632 check_guarded(ctx, guard_ctx, ty)?;
633 check_guarded(ctx, guard_ctx, value)?;
634 let mut child = enter_binder(guard_ctx, name);
635 if let Term::Var(aliased) = value.as_ref() {
636 if let Some(entry) = guard_ctx.smaller_than.get(aliased) {
637 child.smaller_than.insert(name.clone(), entry.clone());
638 }
639 }
640 check_guarded(ctx, &child, body)
641 }
642
643 // A bare occurrence of a block member's name is the higher-order escape: `f` used
644 // as a first-class value (returned, or passed as an argument) rather than applied
645 // to a decreasing argument tuple. Only fully-applied decreasing calls are guarded
646 // (Giménez 1995; the Coq guard), so reject it. Valid recursive calls never reach
647 // here — their head is consumed by the `App` arm above.
648 Term::Var(name)
649 if guard_ctx.fix_columns.contains_key(name)
650 && !guard_ctx.shadowed_fix.contains(name) =>
651 {
652 Err(KernelError::TerminationViolation {
653 fix_name: name.clone(),
654 reason: format!(
655 "recursive name '{}' occurs as a first-class value, not applied to a structurally-smaller argument",
656 name
657 ),
658 })
659 }
660
661 // Other leaves: no recursive calls possible.
662 Term::Sort(_) | Term::Var(_) | Term::Global(_) | Term::Lit(_) | Term::Hole
663 | Term::Const { .. } => Ok(()),
664
665 // An annotation hides nothing from the guard: every call under it is checked.
666 Term::Annotated { term, .. } => check_guarded(ctx, guard_ctx, term),
667 }
668}
669
670/// Verify one recursive call decreases the lexicographic measure.
671///
672/// Scan the columns left to right against the CURRENT body's parameters. A strictly smaller
673/// argument admits the call outright — every later column is then free, which is what
674/// lexicographic means. An EQUAL argument holds that column and the scan continues. Anything
675/// else STOPS the scan: a column that cannot be shown `≤` may have grown, and then no later
676/// column's decrease is a decrease of the tuple. A call that does not even supply the column
677/// stops there for the same reason.
678fn verify_lex_decrease(
679 ctx: &Context,
680 guard_ctx: &GuardContext,
681 callee: &str,
682 callee_columns: &[usize],
683 args: &[&Term],
684) -> KernelResult<()> {
685 let width = guard_ctx
686 .lex_width
687 .min(callee_columns.len())
688 .min(guard_ctx.columns.len());
689 for (c, position) in callee_columns.iter().enumerate().take(width) {
690 let Some(arg) = args.get(*position) else {
691 break;
692 };
693 match classify(ctx, guard_ctx, c, arg) {
694 Rel::Smaller => return Ok(()),
695 Rel::Equal => continue,
696 Rel::Unknown => break,
697 }
698 }
699 Err(KernelError::TerminationViolation {
700 fix_name: guard_ctx.block_name(),
701 reason: format!(
702 "recursive call to '{callee}' does not decrease the structural measure ({}): no \
703 column is passed a strict subterm of its parameter with every earlier column held \
704 equal",
705 guard_ctx.measure()
706 ),
707 })
708}
709
710/// Compare one argument against one column's parameter.
711fn classify(ctx: &Context, guard_ctx: &GuardContext, col: usize, arg: &Term) -> Rel {
712 let Some(column) = guard_ctx.columns.get(col) else {
713 return Rel::Unknown;
714 };
715 // A shadowed column's parameter is not reachable from here, so nothing can be shown
716 // equal to it or smaller than it.
717 if !column.live {
718 return Rel::Unknown;
719 }
720 // EQUAL — the column's own parameter, passed through unchanged.
721 if matches!(arg, Term::Var(v) if *v == column.name) {
722 return Rel::Equal;
723 }
724 // EQUAL — the parameter re-expressed as the constructor this branch destructured it into.
725 if guard_ctx.rebuilt.get(&col).is_some_and(|r| r == arg) {
726 return Rel::Equal;
727 }
728 if subterm_of(
729 ctx,
730 guard_ctx,
731 col,
732 arg,
733 &guard_ctx.smaller_than,
734 SUBTERM_FUEL,
735 ) {
736 return Rel::Smaller;
737 }
738 Rel::Unknown
739}
740
741/// Decide whether `t` is a strict structural SUBTERM of column `col`'s parameter.
742///
743/// Four admissible shapes, following Coq's `subterm_specif`:
744///
745/// * a bare variable bound by matching on that column's parameter (`x` in
746/// `match n with Succ x => … rec x …`), or transitively on such a variable;
747/// * an APPLICATION `h a₁ … aₙ` whose HEAD `h` is such a variable (Giménez's rule). This is
748/// what makes recursion over an accessibility proof terminate: `Acc_intro`'s field
749/// `h : Π(y). R y x → Acc A R y` is bound by the match and marked smaller, and `h y hr` is a
750/// sub-`Acc`-proof it contains. The applied form is SOUND precisely because strict positivity
751/// (`positivity.rs`) guarantees every functional constructor field places the inductive only
752/// in a codomain-result position — so applying such a field can only yield a proper SUBTERM,
753/// never a larger one. A field placing the inductive in a DOMAIN (the `(Bad → …) → Bad`
754/// paradox) is rejected at inductive-registration, so it never reaches this guard;
755/// * a β-redex or a δ-transparent DEFINITION applied to arguments, unfolded one step; and
756/// * a `match` on a term already known `≤` the parameter, whose EVERY reachable branch yields
757/// a subterm — the meet.
758fn subterm_of(
759 ctx: &Context,
760 guard_ctx: &GuardContext,
761 col: usize,
762 t: &Term,
763 smaller: &HashMap<String, (usize, String)>,
764 fuel: u32,
765) -> bool {
766 if fuel == 0 {
767 return false;
768 }
769 let mut head = t;
770 let mut args: Vec<&Term> = Vec::new();
771 while let Term::App(f, a) = head {
772 args.push(a.as_ref());
773 head = f.as_ref();
774 }
775 args.reverse();
776
777 match head {
778 Term::Var(v) => smaller.get(v).is_some_and(|(c, _)| *c == col),
779 Term::Global(n) => unfold_subterm(ctx, guard_ctx, col, n, &args, smaller, fuel),
780 Term::Const { name, .. } => unfold_subterm(ctx, guard_ctx, col, name, &args, smaller, fuel),
781 Term::Lambda { .. } if !args.is_empty() => match beta_apply(head, &args) {
782 Some(reduced) => subterm_of(ctx, guard_ctx, col, &reduced, smaller, fuel - 1),
783 None => false,
784 },
785 Term::Match {
786 discriminant,
787 cases,
788 ..
789 } if args.is_empty() => {
790 match_subterm(ctx, guard_ctx, col, discriminant, cases, smaller, fuel)
791 }
792 _ => false,
793 }
794}
795
796/// δ-unfold a transparent definition applied to `args` and re-analyse the result. An axiom, a
797/// constructor and an inductive have no body, so they are inert — and a constructor
798/// application is precisely NOT a subterm of anything it was built from.
799fn unfold_subterm(
800 ctx: &Context,
801 guard_ctx: &GuardContext,
802 col: usize,
803 name: &str,
804 args: &[&Term],
805 smaller: &HashMap<String, (usize, String)>,
806 fuel: u32,
807) -> bool {
808 if !ctx.is_definition(name) {
809 return false;
810 }
811 let Some(body) = ctx.get_definition_body(name) else {
812 return false;
813 };
814 let body = body.clone();
815 // A definition's body must be CLOSED for its unfolding to mean anything here: a free
816 // variable in it would be captured by whatever name happens to be in scope at the call
817 // site, and the analysis would be reasoning about a term the reducer never produces.
818 if !free_vars(&body).is_empty() {
819 return false;
820 }
821 match beta_apply(&body, args) {
822 Some(reduced) => subterm_of(ctx, guard_ctx, col, &reduced, smaller, fuel - 1),
823 None => false,
824 }
825}
826
827/// The MEET over a `match`'s branches: the whole match is a subterm of column `col`'s parameter
828/// when every REACHABLE branch is. The scrutinee must itself be `≤` that parameter — the
829/// parameter, or a variable already known smaller at the same column — since the branch's bound
830/// fields are only subterms of the parameter when the thing they were destructured from is.
831///
832/// A branch whose constructor a refutation hypothesis has ruled out contributes nothing.
833fn match_subterm(
834 ctx: &Context,
835 guard_ctx: &GuardContext,
836 col: usize,
837 discriminant: &Term,
838 cases: &[Term],
839 smaller: &HashMap<String, (usize, String)>,
840 fuel: u32,
841) -> bool {
842 let Term::Var(d) = discriminant else {
843 return false;
844 };
845 let disc_ind = match guard_ctx.live_column(d) {
846 Some(ci) if ci == col => guard_ctx.columns[ci].ind.clone(),
847 Some(_) => return false,
848 None => match smaller.get(d) {
849 Some((c, ind)) if *c == col && !ind.is_empty() => ind.clone(),
850 _ => return false,
851 },
852 };
853 let constructors = ctx.get_constructors(&disc_ind);
854 if constructors.len() != cases.len() || constructors.is_empty() {
855 return false;
856 }
857 let num_type_params = ctx.inductive_num_params(&disc_ind);
858 let mut reachable = 0usize;
859 for (i, (case, (cname, ctor_type))) in cases.iter().zip(constructors.iter()).enumerate() {
860 let _ = i;
861 if guard_ctx.known_head.get(d).is_some_and(|k| k != cname) {
862 continue;
863 }
864 let param_count = count_pi_params(ctor_type).saturating_sub(num_type_params);
865 let (fields, body) = extract_lambda_params(case, param_count);
866 if fields.len() != param_count {
867 return false;
868 }
869 let field_inductives = field_type_heads(ctx, ctor_type, num_type_params);
870 let mut extended = smaller.clone();
871 for (j, f) in fields.iter().enumerate() {
872 extended.insert(
873 f.clone(),
874 (col, field_inductives.get(j).cloned().unwrap_or_default()),
875 );
876 }
877 if !subterm_of(ctx, guard_ctx, col, body, &extended, fuel - 1) {
878 return false;
879 }
880 reachable += 1;
881 }
882 reachable > 0
883}
884
885/// β-apply `f` to `args`, refusing (as `None`) any substitution that would CAPTURE a free
886/// variable of an argument under one of `f`'s own binders. The analysis is a decision
887/// procedure, so an answer it cannot compute safely must be "no", never a wrong "yes".
888fn beta_apply(f: &Term, args: &[&Term]) -> Option<Term> {
889 let mut cur = f.clone();
890 let mut rest = args;
891 while !rest.is_empty() {
892 match cur {
893 Term::Lambda { param, body, .. } => {
894 let free = free_vars(rest[0]);
895 cur = subst_safe(&body, ¶m, rest[0], &free)?;
896 rest = &rest[1..];
897 }
898 _ => return Some(apply_all(cur, rest)),
899 }
900 }
901 Some(cur)
902}
903
904fn apply_all(f: Term, args: &[&Term]) -> Term {
905 args.iter()
906 .fold(f, |a, x| Term::App(Box::new(a), Box::new((*x).clone())))
907}
908
909/// Substitute `value` for the free occurrences of `x` in `t`, returning `None` if a binder on
910/// the way would CAPTURE one of `value`'s free variables.
911fn subst_safe(t: &Term, x: &str, value: &Term, free: &HashSet<String>) -> Option<Term> {
912 Some(match t {
913 Term::Var(n) if n == x => value.clone(),
914 Term::Var(_)
915 | Term::Global(_)
916 | Term::Sort(_)
917 | Term::Lit(_)
918 | Term::Hole
919 | Term::Const { .. } => t.clone(),
920 Term::App(f, a) => Term::App(
921 Box::new(subst_safe(f, x, value, free)?),
922 Box::new(subst_safe(a, x, value, free)?),
923 ),
924 Term::Lambda {
925 param,
926 param_type,
927 body,
928 } => {
929 let param_type = Box::new(subst_safe(param_type, x, value, free)?);
930 if param == x {
931 Term::Lambda {
932 param: param.clone(),
933 param_type,
934 body: body.clone(),
935 }
936 } else {
937 if free.contains(param) {
938 return None;
939 }
940 Term::Lambda {
941 param: param.clone(),
942 param_type,
943 body: Box::new(subst_safe(body, x, value, free)?),
944 }
945 }
946 }
947 Term::Pi {
948 param,
949 param_type,
950 body_type,
951 } => {
952 let param_type = Box::new(subst_safe(param_type, x, value, free)?);
953 if param == x {
954 Term::Pi {
955 param: param.clone(),
956 param_type,
957 body_type: body_type.clone(),
958 }
959 } else {
960 if free.contains(param) {
961 return None;
962 }
963 Term::Pi {
964 param: param.clone(),
965 param_type,
966 body_type: Box::new(subst_safe(body_type, x, value, free)?),
967 }
968 }
969 }
970 Term::Match {
971 discriminant,
972 motive,
973 cases,
974 } => Term::Match {
975 discriminant: Box::new(subst_safe(discriminant, x, value, free)?),
976 motive: Box::new(subst_safe(motive, x, value, free)?),
977 cases: cases
978 .iter()
979 .map(|c| subst_safe(c, x, value, free))
980 .collect::<Option<Vec<_>>>()?,
981 },
982 Term::Fix { name, body } => {
983 if name == x {
984 t.clone()
985 } else {
986 if free.contains(name) {
987 return None;
988 }
989 Term::Fix {
990 name: name.clone(),
991 body: Box::new(subst_safe(body, x, value, free)?),
992 }
993 }
994 }
995 Term::MutualFix { defs, index } => {
996 if defs.iter().any(|(n, _)| n == x) {
997 t.clone()
998 } else {
999 if defs.iter().any(|(n, _)| free.contains(n)) {
1000 return None;
1001 }
1002 Term::MutualFix {
1003 defs: defs
1004 .iter()
1005 .map(|(n, b)| Some((n.clone(), subst_safe(b, x, value, free)?)))
1006 .collect::<Option<Vec<_>>>()?,
1007 index: *index,
1008 }
1009 }
1010 }
1011 Term::Let {
1012 name,
1013 ty,
1014 value: v,
1015 body,
1016 } => {
1017 let ty = Box::new(subst_safe(ty, x, value, free)?);
1018 let v = Box::new(subst_safe(v, x, value, free)?);
1019 if name == x {
1020 Term::Let {
1021 name: name.clone(),
1022 ty,
1023 value: v,
1024 body: body.clone(),
1025 }
1026 } else {
1027 if free.contains(name) {
1028 return None;
1029 }
1030 Term::Let {
1031 name: name.clone(),
1032 ty,
1033 value: v,
1034 body: Box::new(subst_safe(body, x, value, free)?),
1035 }
1036 }
1037 }
1038 Term::Annotated { annotation, term } => Term::Annotated {
1039 annotation: annotation.clone(),
1040 term: Box::new(subst_safe(term, x, value, free)?),
1041 },
1042 })
1043}
1044
1045/// Every free variable name of `t` — the capture set a substitution must avoid.
1046fn free_vars(t: &Term) -> HashSet<String> {
1047 fn go(t: &Term, bound: &mut Vec<String>, out: &mut HashSet<String>) {
1048 match t {
1049 Term::Var(n) => {
1050 if !bound.iter().any(|b| b == n) {
1051 out.insert(n.clone());
1052 }
1053 }
1054 Term::Global(_) | Term::Sort(_) | Term::Lit(_) | Term::Hole | Term::Const { .. } => {}
1055 Term::App(f, a) => {
1056 go(f, bound, out);
1057 go(a, bound, out);
1058 }
1059 Term::Lambda {
1060 param,
1061 param_type,
1062 body,
1063 } => {
1064 go(param_type, bound, out);
1065 bound.push(param.clone());
1066 go(body, bound, out);
1067 bound.pop();
1068 }
1069 Term::Pi {
1070 param,
1071 param_type,
1072 body_type,
1073 } => {
1074 go(param_type, bound, out);
1075 bound.push(param.clone());
1076 go(body_type, bound, out);
1077 bound.pop();
1078 }
1079 Term::Match {
1080 discriminant,
1081 motive,
1082 cases,
1083 } => {
1084 go(discriminant, bound, out);
1085 go(motive, bound, out);
1086 for c in cases {
1087 go(c, bound, out);
1088 }
1089 }
1090 Term::Fix { name, body } => {
1091 bound.push(name.clone());
1092 go(body, bound, out);
1093 bound.pop();
1094 }
1095 Term::MutualFix { defs, .. } => {
1096 for (n, _) in defs {
1097 bound.push(n.clone());
1098 }
1099 for (_, b) in defs {
1100 go(b, bound, out);
1101 }
1102 for _ in defs {
1103 bound.pop();
1104 }
1105 }
1106 Term::Let {
1107 name,
1108 ty,
1109 value,
1110 body,
1111 ..
1112 } => {
1113 go(ty, bound, out);
1114 go(value, bound, out);
1115 bound.push(name.clone());
1116 go(body, bound, out);
1117 bound.pop();
1118 }
1119 Term::Annotated { term, .. } => go(term, bound, out),
1120 }
1121 }
1122 let mut out = HashSet::new();
1123 go(t, &mut Vec::new(), &mut out);
1124 out
1125}
1126
1127/// The REFUTATION REFINEMENT — see the module header for the soundness argument and the fences.
1128///
1129/// Read off each case of a non-guarding `match` whether its binder's type pins a column
1130/// parameter's constructor head, returning `case index → (parameter, constructor)`.
1131fn decidable_refinements(
1132 ctx: &Context,
1133 guard_ctx: &GuardContext,
1134 discriminant: &Term,
1135 cases: &[Term],
1136) -> HashMap<usize, (String, String)> {
1137 let mut out = HashMap::new();
1138 if !discriminant_is_a_checked_decision(ctx, guard_ctx, discriminant) {
1139 return out;
1140 }
1141 let open = free_vars(discriminant);
1142 for (i, case) in cases.iter().enumerate() {
1143 let Term::Lambda { param_type, .. } = case else {
1144 continue;
1145 };
1146 // `hn : Not (Eq I x C)` REFUTES `C`; `hp : Eq I x C` CONFIRMS it.
1147 let (refuted, prop) = match param_type.as_ref() {
1148 Term::App(f, p) if head_name(f) == Some("Not") => (true, p.as_ref()),
1149 p => (false, p),
1150 };
1151 let Some((x, ctor)) = equation_against_a_constructor(ctx, prop) else {
1152 continue;
1153 };
1154 if guard_ctx.live_column(&x).is_none() {
1155 continue;
1156 }
1157 // The branch is unreachable at `x ↝ C` only because the decision would then be CLOSED and
1158 // reduce to a closed proof of `¬(C = C)`. Any other free variable — a hypothesis of an
1159 // empty type, say — can build that proof under its binder, and the branch is reached.
1160 if open.iter().any(|v| *v != x) {
1161 continue;
1162 }
1163 let Some(ind) = ctx.constructor_inductive(&ctor) else {
1164 continue;
1165 };
1166 if !refuted {
1167 out.insert(i, (x, ctor));
1168 continue;
1169 }
1170 // Refuting one constructor pins the head only when there is exactly one other, and
1171 // only when the refuted one is NULLARY: `x ≠ Succ k` leaves `x` free to be `Succ j`.
1172 let constructors = ctx.get_constructors(ind);
1173 if constructors.len() != 2 {
1174 continue;
1175 }
1176 let nullary = constructors
1177 .iter()
1178 .find(|(n, _)| *n == ctor)
1179 .is_some_and(|(_, t)| count_pi_params(t) == ctx.inductive_num_params(ind));
1180 if !nullary {
1181 continue;
1182 }
1183 if let Some((other, _)) = constructors.iter().find(|(n, _)| *n != ctor) {
1184 out.insert(i, (x, other.to_string()));
1185 }
1186 }
1187 out
1188}
1189
1190/// The refinement's outer fence: the discriminant must be a δ-transparent, kernel-checked
1191/// DEFINITION applied to the recursion's own data. A bound variable of `Decidable` type is
1192/// chosen by the CALLER, and an axiom is chosen by whoever wrote it — neither carries the
1193/// reduction guarantee the refinement rests on.
1194fn discriminant_is_a_checked_decision(
1195 ctx: &Context,
1196 guard_ctx: &GuardContext,
1197 discriminant: &Term,
1198) -> bool {
1199 let mut head = discriminant;
1200 let mut args: Vec<&Term> = Vec::new();
1201 while let Term::App(f, a) = head {
1202 args.push(a.as_ref());
1203 head = f.as_ref();
1204 }
1205 let Some(name) = head_name(head) else {
1206 return false;
1207 };
1208 if !ctx.is_definition(name) {
1209 return false;
1210 }
1211 args.iter().all(|a| is_inert_data(ctx, guard_ctx, a))
1212}
1213
1214/// Data the recursion already owns: a column's parameter, a known subterm, a literal, or a
1215/// constructor applied to such things. Anything else could be a `Decidable` value the caller
1216/// supplied, and the fence exists to keep those out.
1217fn is_inert_data(ctx: &Context, guard_ctx: &GuardContext, t: &Term) -> bool {
1218 let mut head = t;
1219 let mut args: Vec<&Term> = Vec::new();
1220 while let Term::App(f, a) = head {
1221 args.push(a.as_ref());
1222 head = f.as_ref();
1223 }
1224 match head {
1225 Term::Var(v) => {
1226 args.is_empty()
1227 && (guard_ctx.live_column(v).is_some() || guard_ctx.smaller_than.contains_key(v))
1228 }
1229 Term::Lit(_) | Term::Sort(_) => args.is_empty(),
1230 Term::Global(_) | Term::Const { .. } => {
1231 head_name(head).is_some_and(|n| ctx.is_constructor(n) || ctx.is_inductive(n))
1232 && args.iter().all(|a| is_inert_data(ctx, guard_ctx, a))
1233 }
1234 _ => false,
1235 }
1236}
1237
1238/// `Eq I x C…` (in either orientation) where `x` is a variable and `C` a constructor.
1239fn equation_against_a_constructor(ctx: &Context, prop: &Term) -> Option<(String, String)> {
1240 let mut head = prop;
1241 let mut args: Vec<&Term> = Vec::new();
1242 while let Term::App(f, a) = head {
1243 args.push(a.as_ref());
1244 head = f.as_ref();
1245 }
1246 args.reverse();
1247 if head_name(head) != Some("Eq") || args.len() != 3 {
1248 return None;
1249 }
1250 let ctor_head = |t: &Term| -> Option<String> {
1251 let mut h = t;
1252 while let Term::App(f, _) = h {
1253 h = f.as_ref();
1254 }
1255 head_name(h)
1256 .filter(|n| ctx.is_constructor(n))
1257 .map(|n| n.to_string())
1258 };
1259 match (args[1], args[2]) {
1260 (Term::Var(x), c) => ctor_head(c).map(|n| (x.clone(), n)),
1261 (c, Term::Var(x)) => ctor_head(c).map(|n| (x.clone(), n)),
1262 _ => None,
1263 }
1264}
1265
1266/// The name a `Global` or a universe-polymorphic `Const` refers to. They must never be
1267/// conflated in the paradox fence, but here both are simply a reference to a declaration.
1268fn head_name(t: &Term) -> Option<&str> {
1269 match t {
1270 Term::Global(n) | Term::Const { name: n, .. } => Some(n.as_str()),
1271 _ => None,
1272 }
1273}
1274
1275/// Check match cases with the constructor's fields marked as strict subterms of `column`'s
1276/// parameter, and — when the discriminant IS that parameter — the parameter's rebuilt
1277/// constructor application recorded so a call passing it reads as EQUAL rather than as a
1278/// growth.
1279fn check_match_cases_guarded(
1280 ctx: &Context,
1281 guard_ctx: &GuardContext,
1282 cases: &[Term],
1283 disc_inductive: &str,
1284 column: usize,
1285 disc_type: Option<&Term>,
1286) -> KernelResult<()> {
1287 // Get constructors for the SCRUTINEE's inductive type — which is the column's own type for
1288 // a match on its parameter, and the smaller variable's own type for a nested one.
1289 let constructors = ctx.get_constructors(disc_inductive);
1290
1291 // A match whose case count does not match the inductive's is not a match this guard can
1292 // interpret — the positional zip below would pair a case with the WRONG constructor's arity
1293 // and, worse, would simply DROP any case past the constructor list, leaving a recursive call
1294 // inside it unvisited. The type checker rejects such a term, but a guard that relies on that
1295 // is a guard with a hole in it, so fall back to guarding every case in the plain scope.
1296 if constructors.len() != cases.len() {
1297 for case in cases {
1298 check_guarded(ctx, guard_ctx, case)?;
1299 }
1300 return Ok(());
1301 }
1302
1303 // How many of a constructor's Π-binders are the INDUCTIVE'S PARAMETERS, which the
1304 // discriminant fixes and the case therefore does NOT bind.
1305 let num_type_params = ctx.inductive_num_params(disc_inductive);
1306 // The discriminant's own parameter arguments (`Nat` in `TList Nat`), so the rebuilt
1307 // constructor application is the one the branch actually destructured.
1308 let type_args: Vec<Term> = disc_type
1309 .map(|t| {
1310 let mut head = t;
1311 let mut args: Vec<Term> = Vec::new();
1312 while let Term::App(f, a) = head {
1313 args.push(a.as_ref().clone());
1314 head = f.as_ref();
1315 }
1316 args.reverse();
1317 args
1318 })
1319 .unwrap_or_default();
1320
1321 for (case, (ctor_name, ctor_type)) in cases.iter().zip(constructors.iter()) {
1322 // The case binds only the constructor's VALUE FIELDS — its Π-telescope past the
1323 // inductive's parameters — exactly as `compute_case_type` computes it.
1324 //
1325 // SOUNDNESS: counting the whole telescope instead over-peels on any parameterised
1326 // inductive. For `TCons : Π(A:Type 0). A → TList A → TList A` the case binds 2 but the
1327 // full count is 3, so when the motive is a function type the case's third λ — an
1328 // ordinary function parameter, a subterm of nothing — was marked structurally smaller.
1329 // That admits a non-terminating fixpoint, and `Fix` at any type then inhabits it: a
1330 // closed term of type `False` built from nothing but the standard library.
1331 // `recheck.rs::guard_match_cases` miscounted identically, so the second kernel agreed
1332 // and the two-kernel guarantee bought nothing. Pinned by tests/lean_conformance_t04_recursion.rs.
1333 let param_count = count_pi_params(ctor_type).saturating_sub(num_type_params);
1334
1335 // The case is `λx1. … λxn. body`, where `x1…xn` are the constructor's value fields.
1336 let (smaller_vars, case_body) = extract_lambda_params(case, param_count);
1337 // Each field's own type head, so a nested match on one of them knows which
1338 // constructors to expect. Read off the constructor's telescope past the parameters, in
1339 // the same order the case binds them.
1340 let field_inductives = field_type_heads(ctx, ctor_type, num_type_params);
1341
1342 let mut extended_ctx = guard_ctx.clone();
1343
1344 // Mark every constructor field as a strict subterm of THIS column's parameter.
1345 //
1346 // Soundness: we only reach here when the discriminant is the column's parameter or a
1347 // variable already known smaller at the same column, so the matched value is
1348 // `ctor x1 … xn` and each `xi` is a *direct argument* of that constructor — hence a
1349 // genuine structural subterm. Fields of a foreign type are still marked, but `◁` is one
1350 // relation over all terms, so the lexicographic descent is sound regardless of type.
1351 for (i, field) in smaller_vars.iter().enumerate() {
1352 let ind = field_inductives.get(i).cloned().unwrap_or_default();
1353 extended_ctx
1354 .smaller_than
1355 .insert(field.clone(), (column, ind));
1356 // A constructor binder may reuse the name of a column's parameter or of the
1357 // fixpoint; inside this case that name now refers to the (smaller) bound variable,
1358 // so the original meaning is shadowed.
1359 let killed: Vec<usize> = extended_ctx
1360 .columns
1361 .iter()
1362 .enumerate()
1363 .filter(|(_, c)| c.live && c.name == *field)
1364 .map(|(i, _)| i)
1365 .collect();
1366 for k in killed {
1367 extended_ctx.columns[k].live = false;
1368 extended_ctx.rebuilt.remove(&k);
1369 }
1370 extended_ctx.known_head.remove(field);
1371 if guard_ctx.fix_columns.contains_key(field) {
1372 extended_ctx.shadowed_fix.insert(field.clone());
1373 }
1374 }
1375
1376 // The branch destructured the column's parameter into THIS constructor, so within it
1377 // the parameter is definitionally `ctor params… fields…`. That is the EQUAL half of the
1378 // lexicographic order. It is recorded only when the discriminant really is the
1379 // parameter, the case binds every field, and no field shadowed the parameter.
1380 if disc_type.is_some()
1381 && smaller_vars.len() == param_count
1382 && type_args.len() >= num_type_params
1383 && extended_ctx.columns.get(column).is_some_and(|c| c.live)
1384 {
1385 // A constructor is applied to the inductive's PARAMETERS and then its fields; the
1386 // INDICES of the result are computed from those, never passed. So the rebuild reads
1387 // the parameter prefix of the discriminant's type spine and stops there.
1388 let mut rebuilt = Term::Global(ctor_name.to_string());
1389 for a in &type_args[..num_type_params] {
1390 rebuilt = Term::App(Box::new(rebuilt), Box::new(a.clone()));
1391 }
1392 for f in &smaller_vars {
1393 rebuilt = Term::App(Box::new(rebuilt), Box::new(Term::Var(f.clone())));
1394 }
1395 extended_ctx.rebuilt.insert(column, rebuilt);
1396 } else {
1397 extended_ctx.rebuilt.remove(&column);
1398 }
1399
1400 // The peeled field binders carry DOMAIN annotations of their own, and a recursive
1401 // occurrence hiding in one of them would never be visited by the `Lambda` arm.
1402 let mut cur = case;
1403 for _ in 0..smaller_vars.len() {
1404 if let Term::Lambda {
1405 param_type, body, ..
1406 } = cur
1407 {
1408 check_guarded(ctx, guard_ctx, param_type)?;
1409 cur = body;
1410 }
1411 }
1412
1413 check_guarded(ctx, &extended_ctx, case_body)?;
1414 }
1415
1416 Ok(())
1417}
1418
1419/// The inductive each of a constructor's VALUE FIELDS is typed by, in order, skipping the
1420/// inductive's `num_type_params` leading parameter binders. An empty string where the field's
1421/// type does not head an inductive (a function, a sort, a variable) — such a field is still
1422/// marked structurally smaller, but nothing can be matched on it.
1423fn field_type_heads(ctx: &Context, ctor_type: &Term, num_type_params: usize) -> Vec<String> {
1424 let mut heads = Vec::new();
1425 let mut cur = ctor_type;
1426 let mut i = 0usize;
1427 while let Term::Pi {
1428 param_type,
1429 body_type,
1430 ..
1431 } = cur
1432 {
1433 if i >= num_type_params {
1434 let mut head = param_type.as_ref();
1435 while let Term::App(f, _) = head {
1436 head = f;
1437 }
1438 heads.push(match head {
1439 Term::Global(n) | Term::Const { name: n, .. } if ctx.is_inductive(n) => n.clone(),
1440 _ => String::new(),
1441 });
1442 }
1443 cur = body_type;
1444 i += 1;
1445 }
1446 heads
1447}
1448
1449/// Count the number of Pi parameters in a type.
1450fn count_pi_params(ty: &Term) -> usize {
1451 match ty {
1452 Term::Pi { body_type, .. } => 1 + count_pi_params(body_type),
1453 _ => 0,
1454 }
1455}
1456
1457/// Extract lambda parameters and return (param_names, body).
1458fn extract_lambda_params(term: &Term, count: usize) -> (Vec<String>, &Term) {
1459 if count == 0 {
1460 return (Vec::new(), term);
1461 }
1462
1463 match term {
1464 Term::Lambda { param, body, .. } => {
1465 let (mut params, final_body) = extract_lambda_params(body, count - 1);
1466 params.insert(0, param.clone());
1467 (params, final_body)
1468 }
1469 _ => (Vec::new(), term),
1470 }
1471}
1472
1473#[cfg(test)]
1474#[path = "../../logicaffeine_tests/unit/logicaffeine_kernel/termination/tests.rs"]
1475mod tests;