Skip to main content

logicaffeine_kernel/interface/
literate_parser.rs

1//! Literate Specification Parser for the Kernel.
2//!
3//! This module parses English-like "Literate" syntax and emits the same
4//! `Command` and `Term` structures as the Coq-style parser.
5//!
6//! # Supported Syntax
7//!
8//! ## Inductive Types
9//! ```text
10//! A Bool is either Yes or No.
11//! A Nat is either:
12//!     Zero.
13//!     a Successor with pred: Nat.
14//! ```
15//!
16//! ## Function Definitions (with implicit recursion)
17//! ```text
18//! ## To add (n: Nat) and (m: Nat) -> Nat:
19//!     Consider n:
20//!         When Zero: Yield m.
21//!         When Successor k: Yield Successor (add k m).
22//! ```
23//!
24//! ## Pattern Matching
25//! ```text
26//! Consider x:
27//!     When Zero: Yield 0.
28//!     When Successor k: Yield k.
29//! ```
30//!
31//! Several columns at once, separated by `and` — Lean's `| 0, _ => …` — with the overlap split
32//! top-to-bottom by the equation compiler:
33//! ```text
34//! Consider a and b:
35//!     When Zero and _: Yield 1.
36//!     When _ and Zero: Yield 2.
37//!     When _ and _: Yield 3.
38//! ```
39//!
40//! ## Lambda Expressions
41//! ```text
42//! given x: Nat yields Successor x
43//! |x: Nat| -> Successor x
44//! ```
45
46use super::command::Command;
47use super::error::ParseError;
48use super::match_compile::{compile_clauses_reporting, pattern_binder_types, Clause, Pattern};
49use super::surface::{respell_names, Name, Namespaces, Resolution};
50use super::with_env;
51use crate::{infer_type, normalize, Context, Literal, Term, Universe};
52use std::collections::HashSet;
53
54/// Build the reflected, inert list of tactic names for a proof script:
55/// `SApp (SApp (SName "step") (SName n0)) ( … (SName "end"))` — decoded by `extract_script_names`.
56fn build_script_name_list(names: &[String]) -> Term {
57    let sname = |s: &str| {
58        Term::App(
59            Box::new(Term::Global("SName".to_string())),
60            Box::new(Term::Lit(Literal::Text(s.to_string()))),
61        )
62    };
63    let sapp = |x: Term, y: Term| {
64        Term::App(
65            Box::new(Term::App(
66                Box::new(Term::Global("SApp".to_string())),
67                Box::new(x),
68            )),
69            Box::new(y),
70        )
71    };
72    let mut result = sname("end");
73    for n in names.iter().rev() {
74        result = sapp(sapp(sname("step"), sname(n)), result);
75    }
76    result
77}
78
79/// The closed one-shot tactic vocabulary of the literate `Proof:` surface: the keyword a
80/// mathematician writes, and the reflected tactic it applies to the reified goal. Adding a
81/// tactic is a row here — `parse_proof_tactic` and `parse_single_tactic` both read this table,
82/// so the two doors can never drift apart again.
83pub const ONE_SHOT_TACTICS: &[(&str, &str)] = &[
84    ("ring", "try_ring"),
85    ("refl", "try_refl"),
86    ("lia", "try_lia"),
87    ("cc", "try_cc"),
88    ("simp", "try_simp"),
89    ("omega", "try_omega"),
90    ("assumption", "try_assumption"),
91    ("split", "try_split"),
92    ("left", "try_left"),
93    ("right", "try_right"),
94    ("decide", "try_decide"),
95    ("auto", "try_auto"),
96];
97
98/// `f x` where `f` is a prelude global.
99fn apply1(global: &str, arg: Term) -> Term {
100    Term::App(Box::new(Term::Global(global.to_string())), Box::new(arg))
101}
102
103/// The eigenvariable marker.
104///
105/// A peeled `forall` binder is reified as a CONSTANT standing for a fixed-but-arbitrary element,
106/// and the ∀-introduction rule is only sound if that constant is FRESH. Without a mark it is not:
107/// `forall add : Nat, (add 1 2) equals 3` would reify its bound variable as `SName "add"` — the
108/// ring's own addition — and `ring` would certify a statement about an opaque `Nat` as though it
109/// were a statement about the operator.
110///
111/// The mark alone does NOT make it fresh, and that was the claim here. `«n#eig»` is a
112/// `«quoted name»`, which `scan_name` accepts everywhere an identifier is read, so a statement
113/// can NAME the eigenvariable the surface is about to introduce — and a `Definition «n#eig»`
114/// can give it a VALUE. Both collapse to one `SName` and the constant stops being arbitrary:
115/// `∀n:Nat, n equals «n#eig»` reifies as `x = x` and `refl` closes it. So the name is checked
116/// fresh against the statement and against the context — see [`to_eigenvariables`].
117const EIGENVARIABLE_MARK: &str = "#eig";
118
119/// Rename each peeled binder to its eigenvariable, capture-avoidingly: an inner binder that
120/// rebinds the name shadows it, and is left alone.
121///
122/// ★ THE EIGENVARIABLE IS CHECKED FRESH, NOT ASSUMED FRESH. The candidate `n#eig` is stepped
123/// (`n#eig1`, `n#eig2`, …) until it is a name the STATEMENT does not spell and the CONTEXT does
124/// not define. Both halves matter and neither implies the other: a statement that writes
125/// `«n#eig»` makes the quantified variable and that constant one atom, and a context that
126/// DEFINES `«n#eig»` gives the "fixed but arbitrary" element a value the reflected evaluator
127/// can unfold — so `∀n:Nat, n equals Zero` would be certified by `simp` against a constant that
128/// happens to be `Zero`. A `ctx` of `None` is the text-only door, which can still check the
129/// statement.
130fn to_eigenvariables(
131    ctx: Option<&Context>,
132    body: &Term,
133    binders: &[(String, Term)],
134    except: Option<&str>,
135) -> Term {
136    let mut taken: HashSet<String> = HashSet::new();
137    super::spelled_names(body, &mut taken);
138    for (name, ty) in binders {
139        taken.insert(name.clone());
140        super::spelled_names(ty, &mut taken);
141    }
142
143    let mut acc = body.clone();
144    for (name, _) in binders
145        .iter()
146        .filter(|(name, _)| Some(name.as_str()) != except)
147    {
148        let mut candidate = format!("{name}{EIGENVARIABLE_MARK}");
149        let mut step = 0usize;
150        while taken.contains(&candidate) || ctx.is_some_and(|c| c.get_global(&candidate).is_some())
151        {
152            step += 1;
153            candidate = format!("{name}{EIGENVARIABLE_MARK}{step}");
154        }
155        taken.insert(candidate.clone());
156        acc = rename_free_var(&acc, name, &candidate);
157    }
158    acc
159}
160
161/// Rename the FREE occurrences of `from` to `to`.
162fn rename_free_var(term: &Term, from: &str, to: &str) -> Term {
163    let go = |t: &Term| rename_free_var(t, from, to);
164    match term {
165        Term::Var(n) if n == from => Term::Var(to.to_string()),
166        Term::App(f, a) => Term::App(Box::new(go(f)), Box::new(go(a))),
167        Term::Lambda {
168            param,
169            param_type,
170            body,
171        } => Term::Lambda {
172            param: param.clone(),
173            param_type: Box::new(go(param_type)),
174            body: if param == from {
175                body.clone()
176            } else {
177                Box::new(go(body))
178            },
179        },
180        Term::Pi {
181            param,
182            param_type,
183            body_type,
184        } => Term::Pi {
185            param: param.clone(),
186            param_type: Box::new(go(param_type)),
187            body_type: if param == from {
188                body_type.clone()
189            } else {
190                Box::new(go(body_type))
191            },
192        },
193        Term::Fix { name, body } => Term::Fix {
194            name: name.clone(),
195            body: if name == from {
196                body.clone()
197            } else {
198                Box::new(go(body))
199            },
200        },
201        Term::MutualFix { defs, index } => Term::MutualFix {
202            defs: defs
203                .iter()
204                .map(|(n, b)| (n.clone(), if n == from { b.clone() } else { go(b) }))
205                .collect(),
206            index: *index,
207        },
208        Term::Match {
209            discriminant,
210            motive,
211            cases,
212        } => Term::Match {
213            discriminant: Box::new(go(discriminant)),
214            motive: Box::new(go(motive)),
215            cases: cases.iter().map(&go).collect(),
216        },
217        Term::Let {
218            name,
219            ty,
220            value,
221            body,
222        } => Term::Let {
223            name: name.clone(),
224            ty: Box::new(go(ty)),
225            value: Box::new(go(value)),
226            body: if name == from {
227                body.clone()
228            } else {
229                Box::new(go(body))
230            },
231        },
232        Term::Annotated { annotation, term } => Term::Annotated {
233            annotation: annotation.clone(),
234            term: Box::new(go(term)),
235        },
236        other => other.clone(),
237    }
238}
239
240/// The free NAME `name` of an unquantified statement as a variable: every `Global(name)` becomes
241/// `Var(name)`. `None` when a binder inside the statement is spelled `name` — turning the free
242/// name into a variable there would let that binder capture it.
243fn free_name_as_variable(term: &Term, name: &str) -> Option<Term> {
244    let go = |t: &Term| free_name_as_variable(t, name);
245    Some(match term {
246        Term::Global(n) if n == name => Term::Var(name.to_string()),
247        Term::App(f, a) => Term::App(Box::new(go(f)?), Box::new(go(a)?)),
248        Term::Lambda { param, .. } | Term::Pi { param, .. } | Term::Let { name: param, .. }
249            if param == name =>
250        {
251            return None
252        }
253        Term::Fix { name: n, .. } if n == name => return None,
254        Term::MutualFix { defs, .. } if defs.iter().any(|(n, _)| n == name) => return None,
255        Term::Lambda {
256            param,
257            param_type,
258            body,
259        } => Term::Lambda {
260            param: param.clone(),
261            param_type: Box::new(go(param_type)?),
262            body: Box::new(go(body)?),
263        },
264        Term::Pi {
265            param,
266            param_type,
267            body_type,
268        } => Term::Pi {
269            param: param.clone(),
270            param_type: Box::new(go(param_type)?),
271            body_type: Box::new(go(body_type)?),
272        },
273        Term::Fix { name: n, body } => Term::Fix {
274            name: n.clone(),
275            body: Box::new(go(body)?),
276        },
277        Term::MutualFix { defs, index } => Term::MutualFix {
278            defs: defs
279                .iter()
280                .map(|(n, b)| Some((n.clone(), go(b)?)))
281                .collect::<Option<_>>()?,
282            index: *index,
283        },
284        Term::Match {
285            discriminant,
286            motive,
287            cases,
288        } => Term::Match {
289            discriminant: Box::new(go(discriminant)?),
290            motive: Box::new(go(motive)?),
291            cases: cases.iter().map(&go).collect::<Option<_>>()?,
292        },
293        Term::Let {
294            name: n,
295            ty,
296            value,
297            body,
298        } => Term::Let {
299            name: n.clone(),
300            ty: Box::new(go(ty)?),
301            value: Box::new(go(value)?),
302            body: Box::new(go(body)?),
303        },
304        Term::Annotated { annotation, term } => Term::Annotated {
305            annotation: annotation.clone(),
306            term: Box::new(go(term)?),
307        },
308        other => other.clone(),
309    })
310}
311
312/// Peel the prenex `forall` binders off a statement.
313///
314/// Each peeled binder becomes an EIGENVARIABLE — a free name that no tactic can instantiate —
315/// which is ∀-introduction, and is the reading this surface already gives every free variable:
316/// `ring` proves `(add x y) equals (add y x)` precisely because `x` and `y` are opaque atoms. The
317/// `implies` desugaring binds `"_"` and is NOT a quantifier, so it stops the peel.
318fn split_universal_prefix(statement: &Term) -> (Vec<(String, Term)>, &Term) {
319    let mut binders = Vec::new();
320    let mut body = statement;
321    while let Term::Pi {
322        param,
323        param_type,
324        body_type,
325    } = body
326    {
327        if param == "_" {
328            break;
329        }
330        binders.push((param.clone(), param_type.as_ref().clone()));
331        body = body_type;
332    }
333    (binders, body)
334}
335
336/// `SApp (SApp (SName "Forall") ind_type) motive` — the quantified proposition an elimination
337/// concludes, in the exact shape `try_delim_conclude` returns it.
338fn forall_syntax(ind_type: &Term, motive: &Term) -> Term {
339    let sapp = |f: Term, x: Term| {
340        Term::App(
341            Box::new(Term::App(
342                Box::new(Term::Global("SApp".to_string())),
343                Box::new(f),
344            )),
345            Box::new(x),
346        )
347    };
348    let sname_forall = Term::App(
349        Box::new(Term::Global("SName".to_string())),
350        Box::new(Term::Lit(Literal::Text("Forall".to_string()))),
351    );
352    sapp(sapp(sname_forall, ind_type.clone()), motive.clone())
353}
354
355/// The goal the `i`-th constructor's bullet must close: `induction_step_goal ind motive i`,
356/// which the kernel reduces against the real constructor list. The index is a `Nat` literal in
357/// constructor form, because that is what `induction_step_goal` decodes.
358fn case_goal_term(ind_type: &Term, motive: &Term, index: usize) -> Term {
359    let mut idx = Term::Global("Zero".to_string());
360    for _ in 0..index {
361        idx = Term::App(Box::new(Term::Global("Succ".to_string())), Box::new(idx));
362    }
363    Term::App(
364        Box::new(Term::App(
365            Box::new(Term::App(
366                Box::new(Term::Global("induction_step_goal".to_string())),
367                Box::new(ind_type.clone()),
368            )),
369            Box::new(motive.clone()),
370        )),
371        Box::new(idx),
372    )
373}
374
375/// Whether a reflected term is `SName "<name>"`.
376fn is_sname(term: &Term, name: &str) -> bool {
377    matches!(term, Term::App(f, x)
378        if matches!(f.as_ref(), Term::Global(n) if n == "SName")
379            && matches!(x.as_ref(), Term::Lit(Literal::Text(s)) if s == name))
380}
381
382/// Match the reflected two-argument application `SApp (SApp (SName head) a) b`.
383fn as_sapp2(term: &Term, head: &str) -> Option<(Term, Term)> {
384    let Term::App(f, b) = term else { return None };
385    let Term::App(sapp_outer, inner) = f.as_ref() else {
386        return None;
387    };
388    if !matches!(sapp_outer.as_ref(), Term::Global(n) if n == "SApp") {
389        return None;
390    }
391    let Term::App(g, a) = inner.as_ref() else {
392        return None;
393    };
394    let Term::App(sapp_inner, sname) = g.as_ref() else {
395        return None;
396    };
397    if !matches!(sapp_inner.as_ref(), Term::Global(n) if n == "SApp") {
398        return None;
399    }
400    if !is_sname(sname, head) {
401        return None;
402    }
403    Some(((**a).clone(), (**b).clone()))
404}
405
406/// The body of `SLam T body`.
407fn as_slam_body(term: &Term) -> Option<Term> {
408    let Term::App(f, body) = term else {
409        return None;
410    };
411    let Term::App(slam, _ty) = f.as_ref() else {
412        return None;
413    };
414    if !matches!(slam.as_ref(), Term::Global(n) if n == "SLam") {
415        return None;
416    }
417    Some((**body).clone())
418}
419
420/// Match the reflected arrow `SPi A B`.
421fn as_spi(term: &Term) -> Option<(Term, Term)> {
422    let Term::App(f, body) = term else {
423        return None;
424    };
425    let Term::App(spi, ty) = f.as_ref() else {
426        return None;
427    };
428    if !matches!(spi.as_ref(), Term::Global(n) if n == "SPi") {
429        return None;
430    }
431    Some(((**ty).clone(), (**body).clone()))
432}
433
434/// Peel ONE arrow-like layer off a reflected goal.
435///
436/// ★ THIS IS `getTargetArity`, NOT `intro`. Lean's `Lean/Meta/Tactic/Induction.lean:97` measures
437/// a minor premise with `getTargetArity`, which counts `forallE` layers — and in Lean a `∀` and
438/// a `→` are the SAME node, so both are counted, dependent or not. The reflected language splits
439/// that node three ways, so all three are peeled here:
440///
441/// * a typed quantifier `SApp (SApp (SName "Forall") T) (SLam T body)`;
442/// * a reflected implication in either spelling — `Implies`, what the case-formula builder
443///   emits, and `implies`, what the surface's own infix emits;
444/// * `SPi A B`, what a `Pi { param: "_" }` reifies as.
445///
446/// The script evaluator's `intro` is STRICTER than this: `reduction::as_implication` declines a
447/// DEPENDENT `SPi`, whose body names its own binder. That difference cannot matter to the count,
448/// and the reason is structural rather than lucky: the layers this count is used for are exactly
449/// the ones `build_case_expected` ADDS — one `Forall` per constructor field, one `Implies` per
450/// induction hypothesis — and it never emits an `SPi`. Every `SPi` layer belongs to the motive
451/// body, and [`LiterateParser::case_binder_count`] subtracts the motive body's own depth away.
452/// Peeling unconditionally is also what makes the count stable: whether a reflected `SPi` looks
453/// dependent depends on whether its de Bruijn indices have been instantiated yet, and the count
454/// must be the same number before and after.
455fn peel_one_binder(goal: &Term) -> Option<Term> {
456    if let Some((_ty, motive)) = as_sapp2(goal, "Forall") {
457        return as_slam_body(&motive);
458    }
459    for spelling in ["Implies", "implies"] {
460        if let Some((_p, q)) = as_sapp2(goal, spelling) {
461            return Some(q);
462        }
463    }
464    as_spi(goal).map(|(_a, b)| b)
465}
466
467/// How many arrow-like layers a reflected goal carries — Lean's `getTargetArity`.
468fn goal_binder_depth(goal: &Term) -> usize {
469    let mut depth = 0;
470    let mut cur = goal.clone();
471    while let Some(next) = peel_one_binder(&cur) {
472        depth += 1;
473        cur = next;
474    }
475    depth
476}
477
478// ============================================================
479// PUBLIC API (called by command_parser.rs dispatcher)
480// ============================================================
481
482/// Parse "A \[Name\] is either..." into Command::Inductive
483///
484/// Supports:
485/// - `A Bool is either Yes or No.`
486/// - `A Nat is either: Zero. a Successor with pred: Nat.`
487/// - `A List of (T: Type) is either: Empty. a Node with head: T and tail: List of T.`
488pub fn parse_inductive(input: &str) -> Result<(Command, usize), ParseError> {
489    let mut parser = LiterateParser::new(input);
490    let cmd = parser.parse_literate_inductive()?;
491    Ok((cmd, parser.pos))
492}
493
494/// Parse "## To \[name\] (params) -> RetType:" into Command::Definition
495///
496/// Handles implicit fixpoints: if the function name appears in the body,
497/// the body is automatically wrapped in Term::Fix.
498///
499/// This door reads TEXT ALONE, so a `Consider` block is limited to what text can carry: one
500/// column, one case per clause, in SOURCE order, with flat identifier binders. Use
501/// [`parse_definition_in`] wherever a context exists — it compiles the equation set instead.
502pub fn parse_definition(input: &str) -> Result<(Command, usize), ParseError> {
503    let mut parser = LiterateParser::new(input);
504    let cmd = parser.parse_literate_definition()?;
505    Ok((cmd, parser.pos))
506}
507
508/// [`parse_definition`], with the kernel context the equation compiler needs.
509///
510/// With a context, a `Consider` block is a real equation set: nested constructor patterns
511/// compile to a tree of positional matches, overlapping equations are split top-to-bottom
512/// (first match wins, as in Lean), a `When _:` catch-all fans out over every constructor with no
513/// clause of its own, several columns can be matched at once (`Consider a and b:` with
514/// `When Zero and _:`), and every clause lands in the slot of the constructor it NAMES rather
515/// than the slot its position in the source happens to hit.
516pub fn parse_definition_in(ctx: &Context, input: &str) -> Result<(Command, usize), ParseError> {
517    parse_definition_scoped(ctx, &Namespaces::new(), input)
518}
519
520/// [`parse_definition_in`], reading every name in the namespace scope `scope` — the door the REPL
521/// reads through, so a literate definition's names mean exactly what they mean to every other door.
522pub fn parse_definition_scoped(
523    ctx: &Context,
524    scope: &Namespaces,
525    input: &str,
526) -> Result<(Command, usize), ParseError> {
527    let mut parser = LiterateParser::new_in(input, ctx, scope);
528    let cmd = parser.parse_literate_definition()?;
529    Ok((parser.respelled(cmd)?, parser.pos))
530}
531
532/// Parse "Let \[name\] be \[term\]." into Command::Definition (constant, not function)
533///
534/// This is for simple constant bindings like:
535/// - `Let T be Apply(Name "Not", Variable 0).`
536/// - `Let G be the diagonalization of T.`
537pub fn parse_let_definition(input: &str) -> Result<(Command, usize), ParseError> {
538    let mut parser = LiterateParser::new(input);
539    let cmd = parser.parse_literate_let()?;
540    Ok((cmd, parser.pos))
541}
542
543/// Parse "## Theorem: \[name\] Statement: \[proposition\]." into Command::Definition
544///
545/// This is for theorem declarations like:
546/// - `## Theorem: Godel_First_Incompleteness\n    Statement: Consistent implies Not(Provable(G)).`
547///
548/// This door reads TEXT ALONE. A `Proof: induction <v>.` therefore cannot be told how many
549/// constructors the variable's type HAS, so a bullet-count mistake surfaces only later, as the
550/// elimination failing to conclude anything. Use [`parse_theorem_in`] wherever a context exists.
551pub fn parse_theorem(input: &str) -> Result<(Command, usize), ParseError> {
552    let mut parser = LiterateParser::new(input);
553    let cmd = parser.parse_literate_theorem()?;
554    Ok((cmd, parser.pos))
555}
556
557/// [`parse_theorem`], with the kernel context.
558///
559/// The one thing it buys is the one thing text cannot carry: the constructor list of whatever
560/// `induction <v>` is eliminating. With it, a bullet-count mistake is reported AS a bullet-count
561/// mistake — naming the inductive, its constructors and the count written — instead of arriving
562/// as "the tactic did not establish the stated goal", which is what a reader sees when the case
563/// chain is silently the wrong length.
564pub fn parse_theorem_in(ctx: &Context, input: &str) -> Result<(Command, usize), ParseError> {
565    parse_theorem_scoped(ctx, &Namespaces::new(), input)
566}
567
568/// The EXTENT of the `## To` block at the front of `input` — where it ends — read from its syntax
569/// alone. See [`measure_theorem`].
570pub fn measure_definition(input: &str) -> Result<usize, ParseError> {
571    let mut parser = LiterateParser::measuring(input);
572    parser.parse_literate_definition()?;
573    Ok(parser.pos)
574}
575
576/// The EXTENT of the `## Theorem:` block at the front of `input`, read from its syntax alone.
577///
578/// Where a block ENDS is a fact about its text; what it MEANS is a fact about the context it is
579/// read in. A document is split into blocks before any of them runs, so its splitter can only ask
580/// the first question: a `## To` block whose equation set is over a function an EARLIER block of the
581/// same document declares cannot be compiled yet, and it does not need to be — it is measured here,
582/// and compiled when it is read to be run, against the context the blocks before it built. The
583/// flat reading's refusals of what only a context can compile (a nested pattern, a catch-all,
584/// a second column) are skipped for the same reason: measuring them needs their syntax only.
585pub fn measure_theorem(input: &str) -> Result<usize, ParseError> {
586    let mut parser = LiterateParser::measuring(input);
587    parser.parse_literate_theorem()?;
588    Ok(parser.pos)
589}
590
591/// [`parse_theorem_in`], reading every name in the namespace scope `scope`. The statement is
592/// reflected into syntax only after its names are resolved, so a theorem about `add` in a session
593/// that shadows `add` is a theorem about the session's `add`.
594pub fn parse_theorem_scoped(
595    ctx: &Context,
596    scope: &Namespaces,
597    input: &str,
598) -> Result<(Command, usize), ParseError> {
599    let mut parser = LiterateParser::new_in(input, ctx, scope);
600    let cmd = parser.parse_literate_theorem()?;
601    Ok((parser.respelled(cmd)?, parser.pos))
602}
603
604/// The head name of a type application: `Hue` → `"Hue"`, `List A` → `"List"`.
605fn type_head_name(ty: &Term) -> Option<&str> {
606    let mut cur = ty;
607    while let Term::App(f, _) = cur {
608        cur = f;
609    }
610    match cur {
611        Term::Global(n) => Some(n),
612        Term::Const { name, .. } => Some(name),
613        _ => None,
614    }
615}
616
617/// The flat positional reading of a clause list: one case per clause, in SOURCE order, each body
618/// re-abstracted over that clause's binders.
619///
620/// This is everything a parser holding only a `&str` can do, and it is kept for the context-free
621/// door alone. It cannot place a clause by the constructor it names (it does not know the
622/// registration order), it cannot nest, it cannot fan a catch-all out, and it cannot split a
623/// second column — so it refuses those shapes by name instead of guessing, and says where the
624/// compiler lives.
625fn flat_positional_match(
626    discriminants: Vec<Term>,
627    motive: Term,
628    clauses: &[Clause],
629) -> Result<Term, ParseError> {
630    let needs_compiler = |what: &str| {
631        ParseError::InvalidConsiderSyntax(format!(
632            "{what} is compiled against the inductive's constructor list, which lives in the \
633             kernel context — this parser has none. Read the definition through \
634             `interface::parse_command_in_ctx` (or `literate_parser::parse_definition_in`), \
635             which does."
636        ))
637    };
638
639    // A SECOND COLUMN is a matrix, and a matrix is split by specialising it constructor by
640    // constructor — which needs the constructor list. One `Match` node cannot hold it.
641    let [discriminant] = <[Term; 1]>::try_from(discriminants)
642        .map_err(|_| needs_compiler("a multi-column `Consider … and …`"))?;
643
644    let mut cases = Vec::with_capacity(clauses.len());
645    for clause in clauses {
646        if clause.patterns.len() != 1 {
647            return Err(needs_compiler("a multi-column equation set"));
648        }
649        let Pattern::Ctor { args, .. } = &clause.patterns[0] else {
650            return Err(needs_compiler("a `When _:` catch-all"));
651        };
652        let mut binders = Vec::with_capacity(args.len());
653        for arg in args {
654            match arg {
655                Pattern::Var(n) => binders.push(n.clone()),
656                Pattern::Wildcard => binders.push("_".to_string()),
657                Pattern::Ctor { .. } => return Err(needs_compiler("a nested constructor pattern")),
658                Pattern::Numeral(_) => return Err(needs_compiler("a numeral pattern")),
659            }
660        }
661        let mut body = clause.body.clone();
662        for binder in binders.into_iter().rev() {
663            body = Term::Lambda {
664                param: binder,
665                param_type: Box::new(Term::Global("_".to_string())),
666                body: Box::new(body),
667            };
668        }
669        cases.push(body);
670    }
671
672    Ok(Term::Match {
673        discriminant: Box::new(discriminant),
674        motive: Box::new(motive),
675        cases,
676    })
677}
678
679// ============================================================
680// PARSER STATE
681// ============================================================
682
683struct LiterateParser<'a> {
684    input: &'a str,
685    pos: usize,
686    bound_vars: HashSet<String>,
687    current_function: Option<String>,
688    /// The return type of the current function (used as motive in Consider)
689    return_type: Option<Term>,
690    /// The kernel context, when the caller has one.
691    ///
692    /// An equation set is compiled against the discriminant's INDUCTIVE — its constructor list,
693    /// their registration order, their arities — and none of that is recoverable from text. With
694    /// a context a `Consider` is compiled by [`super::match_compile`]; without one it falls back
695    /// to the flat positional reading, which is all a `&str` can support.
696    ctx: Option<&'a Context>,
697    /// The namespace scope a name the author wrote is resolved in, beside the context's shadow
698    /// table. Consulted only with a context: without one a name is kept as written, and the REPL
699    /// resolves it when it runs the command.
700    scope: Namespaces,
701    /// Names in scope with their types: the current function's parameters, then a clause's
702    /// pattern binders while that clause's body is being read.
703    locals: Vec<(String, Term)>,
704    /// Read the block for its EXTENT only: an equation set is parsed and not compiled. See
705    /// [`measure_theorem`].
706    measuring: bool,
707}
708
709impl<'a> LiterateParser<'a> {
710    fn new(input: &'a str) -> Self {
711        Self {
712            input,
713            pos: 0,
714            bound_vars: HashSet::new(),
715            current_function: None,
716            return_type: None,
717            ctx: None,
718            scope: Namespaces::new(),
719            locals: Vec::new(),
720            measuring: false,
721        }
722    }
723
724    /// A parser that reads a block for its extent alone (see [`measure_theorem`]).
725    fn measuring(input: &'a str) -> Self {
726        Self {
727            measuring: true,
728            ..Self::new(input)
729        }
730    }
731
732    /// [`Self::new`], with the kernel context the equation compiler needs and the namespace scope
733    /// the names are read in.
734    fn new_in(input: &'a str, ctx: &'a Context, scope: &Namespaces) -> Self {
735        Self {
736            ctx: Some(ctx),
737            scope: scope.clone(),
738            ..Self::new(input)
739        }
740    }
741
742    /// The key a name the AUTHOR wrote denotes, resolved in the scope and through the context's
743    /// shadow table — the one resolution every door shares (`surface::Env::resolve`).
744    ///
745    /// Only a written name, or a surface operator standing for one (`+` is `add`, `equals` is
746    /// `Eq`), comes through here. The reflection and derivation vocabulary this parser builds
747    /// proofs out of (`SName`, `SApp`, `DCase`, `try_simp`, …) is the prelude's own and is never
748    /// looked up: a tactic reads the prelude's `add` whatever a session calls `add`.
749    fn denote(&self, written: String) -> Result<String, ParseError> {
750        let Some(ctx) = self.ctx else {
751            return Ok(written);
752        };
753        let Some(name) = Name::parse(&written) else {
754            return Ok(written);
755        };
756        match with_env(ctx, &[], |env| env.resolve(&self.scope, &name)) {
757            Resolution::Found(key) => Ok(key),
758            Resolution::Unresolved(_) => Ok(written),
759            Resolution::Ambiguous {
760                written,
761                candidates,
762            } => Err(ParseError::AmbiguousName {
763                written,
764                candidates,
765            }),
766        }
767    }
768
769    /// The constant a name the author wrote denotes. See [`Self::denote`].
770    fn global(&self, written: impl Into<String>) -> Result<Term, ParseError> {
771        Ok(Term::Global(self.denote(written.into())?))
772    }
773
774    /// A command this parser read with a context, re-spelled so the REPL's own resolution of it
775    /// reaches exactly the keys it already holds (`surface::respell_names`): the parse resolved
776    /// every name the author wrote, and what it handed the kernel in between — constructors it
777    /// compiled against, constants the elaborator inserted, the proof vocabulary — is in key space.
778    fn respelled(&self, cmd: Command) -> Result<Command, ParseError> {
779        let Some(ctx) = self.ctx else { return Ok(cmd) };
780        let respell = |t: Term| -> Result<Term, ParseError> {
781            with_env(ctx, &[], |env| {
782                respell_names(&self.scope, env, &mut Vec::new(), &t).map(|r| r.into_owned())
783            })
784        };
785        match cmd {
786            Command::Definition {
787                name,
788                ty,
789                body,
790                is_hint,
791                implicit_count,
792                proof_goal,
793            } => Ok(Command::Definition {
794                name,
795                ty: ty.map(respell).transpose()?,
796                body: respell(body)?,
797                is_hint,
798                implicit_count,
799                proof_goal: proof_goal.map(respell).transpose()?,
800            }),
801            other => Ok(other),
802        }
803    }
804
805    /// The context a clause matrix is compiled against: the caller's, extended by every local
806    /// currently in scope. `None` when this parser has no context at all.
807    fn working_context(&self) -> Option<Context> {
808        let base = self.ctx?;
809        Some(
810            self.locals
811                .iter()
812                .fold(base.clone(), |acc, (n, t)| acc.extend(n, t.clone())),
813        )
814    }
815
816    // ============================================================
817    // INDUCTIVE TYPE PARSING
818    // ============================================================
819
820    /// Parse: A [Name] (params)? is either [variants]
821    fn parse_literate_inductive(&mut self) -> Result<Command, ParseError> {
822        self.skip_whitespace();
823
824        // Consume "A" or "An"
825        if self.try_consume_keyword("An") || self.try_consume_keyword("A") {
826            // Good
827        } else {
828            return Err(ParseError::Expected {
829                expected: "'A' or 'An'".to_string(),
830                found: self.peek_word().unwrap_or("EOF".to_string()),
831            });
832        }
833
834        self.skip_whitespace();
835
836        // Parse the type name
837        let name = self.parse_declaration_name()?;
838
839        self.skip_whitespace();
840
841        // Check for type parameters: "of (T: Type)"
842        let params = if self.try_consume_keyword("of") {
843            self.skip_whitespace();
844            self.parse_param_list()?
845        } else {
846            vec![]
847        };
848
849        self.skip_whitespace();
850
851        // Expect "is either"
852        if !self.try_consume_keyword("is") {
853            return Err(ParseError::Expected {
854                expected: "'is'".to_string(),
855                found: self.peek_word().unwrap_or("EOF".to_string()),
856            });
857        }
858        self.skip_whitespace();
859        if !self.try_consume_keyword("either") {
860            return Err(ParseError::Expected {
861                expected: "'either'".to_string(),
862                found: self.peek_word().unwrap_or("EOF".to_string()),
863            });
864        }
865
866        self.skip_whitespace();
867
868        // Parse variants - either inline with "or" or block with indentation
869        let constructors = if self.peek_char(':') {
870            // Block format: "is either:\n    Zero.\n    Successor with pred: Nat."
871            self.advance(); // consume ':'
872            self.parse_indented_variants(&name, &params)?
873        } else {
874            // Inline format: "is either Yes or No."
875            self.parse_inline_variants(&name, &params)?
876        };
877
878        if constructors.is_empty() {
879            return Err(ParseError::Missing("constructors".to_string()));
880        }
881
882        Ok(Command::Inductive {
883            name,
884            params,
885            sort: Term::Sort(Universe::Type(0)),
886            constructors,
887        })
888    }
889
890    /// Parse inline variants: "Yes or No" or "Yes or No."
891    fn parse_inline_variants(
892        &mut self,
893        inductive_name: &str,
894        params: &[(String, Term)],
895    ) -> Result<Vec<(String, Term)>, ParseError> {
896        let mut constructors = Vec::new();
897
898        loop {
899            self.skip_whitespace();
900
901            if self.at_end() || self.peek_char('.') {
902                break;
903            }
904
905            // Parse a single variant
906            let (ctor_name, ctor_type) = self.parse_variant(inductive_name, params)?;
907            constructors.push((ctor_name, ctor_type));
908
909            self.skip_whitespace();
910
911            // Check for "or" separator
912            if !self.try_consume_keyword("or") {
913                break;
914            }
915        }
916
917        // Consume trailing period if present
918        self.skip_whitespace();
919        let _ = self.try_consume(".");
920
921        Ok(constructors)
922    }
923
924    /// Parse indented variants (after "is either:")
925    fn parse_indented_variants(
926        &mut self,
927        inductive_name: &str,
928        params: &[(String, Term)],
929    ) -> Result<Vec<(String, Term)>, ParseError> {
930        let mut constructors = Vec::new();
931
932        loop {
933            self.skip_whitespace_and_newlines();
934
935            if self.at_end() {
936                break;
937            }
938
939            // Check for end of block (non-indented line or empty)
940            if !self.peek_char(' ')
941                && !self.peek_char('\t')
942                && !self.peek_char('a')
943                && !self.peek_char('A')
944            {
945                // Check if this is a variant starting with capital letter
946                if let Some(c) = self.peek() {
947                    if !c.is_uppercase() && c != 'a' && c != 'A' {
948                        break;
949                    }
950                }
951            }
952
953            // Skip leading whitespace for indentation
954            self.skip_whitespace();
955
956            // Check for "a/an" prefix or capital letter
957            if self.at_end() {
958                break;
959            }
960
961            // Parse variant
962            let (ctor_name, ctor_type) = self.parse_variant(inductive_name, params)?;
963            constructors.push((ctor_name, ctor_type));
964
965            // Consume trailing period
966            self.skip_whitespace();
967            let _ = self.try_consume(".");
968        }
969
970        Ok(constructors)
971    }
972
973    /// Parse a single variant: "Zero" or "a Successor with pred: Nat"
974    fn parse_variant(
975        &mut self,
976        inductive_name: &str,
977        params: &[(String, Term)],
978    ) -> Result<(String, Term), ParseError> {
979        self.skip_whitespace();
980
981        // Skip optional "a" or "an" prefix (for readability)
982        let _ = self.try_consume_keyword("an") || self.try_consume_keyword("a");
983        self.skip_whitespace();
984
985        // Parse constructor name
986        let ctor_name = self.parse_declaration_name()?;
987
988        self.skip_whitespace();
989
990        // Build the result type (possibly with parameters applied)
991        let result_type = self.build_applied_type(inductive_name, params);
992
993        // Check for "with" clause (fields)
994        if self.try_consume_keyword("with") {
995            // Parse fields: "field: Type and field2: Type2"
996            let fields = self.parse_field_list()?;
997
998            // Build constructor type: field1_type -> field2_type -> ... -> ResultType
999            let mut ctor_type = result_type;
1000            for (_field_name, field_type) in fields.into_iter().rev() {
1001                ctor_type = Term::Pi {
1002                    param: "_".to_string(),
1003                    param_type: Box::new(field_type),
1004                    body_type: Box::new(ctor_type),
1005                };
1006            }
1007
1008            Ok((ctor_name, ctor_type))
1009        } else {
1010            // Unit constructor (no fields)
1011            Ok((ctor_name, result_type))
1012        }
1013    }
1014
1015    /// Parse field list: "field: Type" or "field: Type and field2: Type2"
1016    fn parse_field_list(&mut self) -> Result<Vec<(String, Term)>, ParseError> {
1017        let mut fields = Vec::new();
1018
1019        loop {
1020            self.skip_whitespace();
1021
1022            // Parse field name
1023            let field_name = self.parse_ident()?;
1024
1025            self.skip_whitespace();
1026
1027            // Expect ":"
1028            if !self.try_consume(":") {
1029                return Err(ParseError::Expected {
1030                    expected: "':'".to_string(),
1031                    found: self.peek_word().unwrap_or("EOF".to_string()),
1032                });
1033            }
1034
1035            self.skip_whitespace();
1036
1037            // Parse field type
1038            let field_type = self.parse_type()?;
1039
1040            fields.push((field_name, field_type));
1041
1042            self.skip_whitespace();
1043
1044            // Check for "and" separator
1045            if !self.try_consume_keyword("and") {
1046                break;
1047            }
1048        }
1049
1050        Ok(fields)
1051    }
1052
1053    /// Build type with parameters applied: List T
1054    fn build_applied_type(&self, name: &str, params: &[(String, Term)]) -> Term {
1055        let mut result = Term::Global(name.to_string());
1056        for (param_name, _) in params {
1057            result = Term::App(Box::new(result), Box::new(Term::Var(param_name.clone())));
1058        }
1059        result
1060    }
1061
1062    // ============================================================
1063    // DEFINITION PARSING
1064    // ============================================================
1065
1066    /// Parse: ## To [name] (params) -> RetType: body
1067    fn parse_literate_definition(&mut self) -> Result<Command, ParseError> {
1068        self.skip_whitespace();
1069
1070        // Consume "## To "
1071        if !self.try_consume("## To ") && !self.try_consume("##To ") {
1072            return Err(ParseError::Expected {
1073                expected: "'## To'".to_string(),
1074                found: self.peek_word().unwrap_or("EOF".to_string()),
1075            });
1076        }
1077
1078        self.skip_whitespace();
1079
1080        // Parse function name
1081        let mut name = self.parse_declaration_name()?;
1082
1083        // Handle predicate syntax: "## To be Provable" means define "Provable", not "be"
1084        // This allows "## To be X (params) -> Prop:" for predicate definitions
1085        if name == "be" {
1086            self.skip_whitespace();
1087            name = self.parse_declaration_name()?;
1088        }
1089
1090        self.current_function = Some(name.clone());
1091
1092        self.skip_whitespace();
1093
1094        // Parse parameter groups: (x: T) and (y: U) or (x: T) (y: U)
1095        // Note: For nullary predicates like "## To be Consistent -> Prop:", params will be empty
1096        let all_params = self.parse_function_params()?;
1097
1098        self.skip_whitespace();
1099
1100        // Parse optional return type: -> RetType
1101        let return_type = if self.try_consume("->") {
1102            self.skip_whitespace();
1103            let ret = self.parse_type()?;
1104            // Store return type for use as motive in Consider blocks
1105            self.return_type = Some(ret.clone());
1106            Some(ret)
1107        } else {
1108            None
1109        };
1110
1111        self.skip_whitespace();
1112
1113        // Expect ":"
1114        if !self.try_consume(":") {
1115            return Err(ParseError::Expected {
1116                expected: "':'".to_string(),
1117                found: self.peek_word().unwrap_or("EOF".to_string()),
1118            });
1119        }
1120
1121        // Add parameters to bound vars, and to the typed local scope the equation compiler
1122        // reads the discriminant's type out of.
1123        for (param_name, param_type) in &all_params {
1124            self.bound_vars.insert(param_name.clone());
1125            self.locals.push((param_name.clone(), param_type.clone()));
1126        }
1127
1128        // Parse body
1129        self.skip_whitespace_and_newlines();
1130        let body = self.parse_body()?;
1131
1132        // Check for self-reference (implicit fixpoint)
1133        let needs_fix = self.contains_self_reference(&name, &body);
1134
1135        // Build the function body with lambdas
1136        let mut func_body = body;
1137        for (param_name, param_type) in all_params.iter().rev() {
1138            func_body = Term::Lambda {
1139                param: param_name.clone(),
1140                param_type: Box::new(param_type.clone()),
1141                body: Box::new(func_body),
1142            };
1143        }
1144
1145        // Wrap in Fix if recursive
1146        if needs_fix {
1147            func_body = Term::Fix {
1148                name: name.clone(),
1149                body: Box::new(func_body),
1150            };
1151        }
1152
1153        // Build the full type annotation if we have a return type
1154        let ty = if let Some(ret) = return_type {
1155            let mut full_type = ret;
1156            for (_, param_type) in all_params.iter().rev() {
1157                full_type = Term::Pi {
1158                    param: "_".to_string(),
1159                    param_type: Box::new(param_type.clone()),
1160                    body_type: Box::new(full_type),
1161                };
1162            }
1163            Some(full_type)
1164        } else {
1165            None
1166        };
1167
1168        self.current_function = None;
1169
1170        Ok(Command::Definition {
1171            name,
1172            ty,
1173            body: func_body,
1174            is_hint: false,
1175            implicit_count: 0,
1176            proof_goal: None,
1177        })
1178    }
1179
1180    // ============================================================
1181    // LET DEFINITION PARSING
1182    // ============================================================
1183
1184    /// Parse: Let [name] be [term].
1185    fn parse_literate_let(&mut self) -> Result<Command, ParseError> {
1186        self.skip_whitespace();
1187
1188        // Consume "Let "
1189        if !self.try_consume_keyword("Let") {
1190            return Err(ParseError::Expected {
1191                expected: "'Let'".to_string(),
1192                found: self.peek_word().unwrap_or("EOF".to_string()),
1193            });
1194        }
1195
1196        self.skip_whitespace();
1197
1198        // Parse the name
1199        let name = self.parse_declaration_name()?;
1200
1201        self.skip_whitespace();
1202
1203        // Expect "be"
1204        if !self.try_consume_keyword("be") {
1205            return Err(ParseError::Expected {
1206                expected: "'be'".to_string(),
1207                found: self.peek_word().unwrap_or("EOF".to_string()),
1208            });
1209        }
1210
1211        self.skip_whitespace();
1212
1213        // Parse the body term
1214        let body = self.parse_term()?;
1215
1216        // Consume trailing period if present
1217        self.skip_whitespace();
1218        let _ = self.try_consume(".");
1219
1220        Ok(Command::Definition {
1221            name,
1222            ty: None,
1223            body,
1224            is_hint: false,
1225            implicit_count: 0,
1226            proof_goal: None,
1227        })
1228    }
1229
1230    /// Parse: ## Theorem: [name]\n    Statement: [proposition].\n    Proof: [tactic].
1231    ///
1232    /// The Proof section is optional. When provided, it applies a tactic like `ring.`
1233    /// to automatically prove the statement.
1234    fn parse_literate_theorem(&mut self) -> Result<Command, ParseError> {
1235        self.skip_whitespace();
1236
1237        // Consume "## Theorem:"
1238        if !self.try_consume("## Theorem:") {
1239            return Err(ParseError::Expected {
1240                expected: "'## Theorem:'".to_string(),
1241                found: self.peek_word().unwrap_or("EOF".to_string()),
1242            });
1243        }
1244
1245        self.skip_whitespace();
1246
1247        // Parse the theorem name
1248        let name = self.parse_declaration_name()?;
1249
1250        self.skip_whitespace_and_newlines();
1251
1252        // Expect "Statement:"
1253        if !self.try_consume_keyword("Statement") {
1254            return Err(ParseError::Expected {
1255                expected: "'Statement'".to_string(),
1256                found: self.peek_word().unwrap_or("EOF".to_string()),
1257            });
1258        }
1259        self.skip_whitespace();
1260        if !self.try_consume(":") {
1261            return Err(ParseError::Expected {
1262                expected: "':'".to_string(),
1263                found: self.peek_word().unwrap_or("EOF".to_string()),
1264            });
1265        }
1266
1267        self.skip_whitespace();
1268
1269        // Parse the statement (proposition)
1270        let statement = self.parse_term()?;
1271
1272        // Consume trailing period if present
1273        self.skip_whitespace();
1274        let _ = self.try_consume(".");
1275
1276        self.skip_whitespace_and_newlines();
1277
1278        // Check for optional "Proof:" section
1279        let (body, ty, proof_goal) = if self.try_consume_keyword("Proof") {
1280            self.skip_whitespace();
1281            if !self.try_consume(":") {
1282                return Err(ParseError::Expected {
1283                    expected: "':'".to_string(),
1284                    found: self.peek_word().unwrap_or("EOF".to_string()),
1285                });
1286            }
1287            self.skip_whitespace();
1288
1289            // Parse the proof tactic. It returns BOTH the derivation and the goal, in `Syntax`
1290            // form, that the derivation must CONCLUDE — the REPL rejects the theorem unless
1291            // `concludes body` reduces to exactly that. The goal is computed from the STATEMENT
1292            // (never from the proof), but which rendering of the statement it is depends on the
1293            // tactic: an ordinary tactic discharges the prenex binders as eigenvariables and is
1294            // handed the open body, while `induction` keeps the binder and is handed the
1295            // `Forall`-quantified form. Both are faithful readings of the same proposition; each
1296            // matches the shape its own derivation concludes.
1297            let (proof, goal_syntax) = self.parse_proof_tactic(&statement)?;
1298
1299            // Consume trailing period if present
1300            self.skip_whitespace();
1301            let _ = self.try_consume(".");
1302
1303            (
1304                proof,
1305                Some(Term::Global("Derivation".to_string())),
1306                Some(goal_syntax),
1307            )
1308        } else {
1309            // No proof - existing behavior (statement as body, Prop as type)
1310            (statement, Some(Term::Sort(Universe::Prop)), None)
1311        };
1312
1313        // Check for optional "Attribute: hint." section
1314        self.skip_whitespace_and_newlines();
1315        let is_hint = if self.try_consume_keyword("Attribute") {
1316            self.skip_whitespace();
1317            if !self.try_consume(":") {
1318                return Err(ParseError::Expected {
1319                    expected: "':'".to_string(),
1320                    found: self.peek_word().unwrap_or("EOF".to_string()),
1321                });
1322            }
1323            self.skip_whitespace();
1324
1325            let hint = self.try_consume_keyword("hint");
1326
1327            // Consume trailing period
1328            self.skip_whitespace();
1329            let _ = self.try_consume(".");
1330
1331            hint
1332        } else {
1333            false
1334        };
1335
1336        Ok(Command::Definition {
1337            name,
1338            ty,
1339            body,
1340            is_hint,
1341            implicit_count: 0,
1342            proof_goal,
1343        })
1344    }
1345
1346    /// Consume one STEP of a proof script or of a bullet case, returning the step's NAME — the
1347    /// vocabulary [`eval_script_names`](crate::reduction) reads — or `None`, position unmoved,
1348    /// when the next token is not a step. Consumes the trailing period.
1349    ///
1350    /// The vocabulary is [`ONE_SHOT_TACTICS`] plus `intro`, read off the table rather than
1351    /// re-listed: a tactic added to the table but forgotten here would be writable as
1352    /// `Proof: <t>.` and silently unreadable as a script step, which stops the parse mid-proof
1353    /// and reports the REMAINDER as trailing input — blaming the author's next line for a hole
1354    /// in ours.
1355    ///
1356    /// `intro` may name the variable it introduces, as it does in Lean. The name is a note to
1357    /// the reader — the script evaluator introduces the antecedent either way — so it is read
1358    /// and dropped rather than being allowed to derail the parse.
1359    fn parse_step_name(&mut self, allow_intro_binder: bool) -> Option<String> {
1360        for kw in std::iter::once("intro").chain(ONE_SHOT_TACTICS.iter().map(|(k, _)| *k)) {
1361            if self.try_consume_keyword(kw) {
1362                self.skip_whitespace();
1363                if allow_intro_binder && kw == "intro" && !self.peek_char('.') && !self.at_end() {
1364                    let _ = self.parse_ident();
1365                    self.skip_whitespace();
1366                }
1367                let _ = self.try_consume(".");
1368                return Some(kw.to_string());
1369            }
1370        }
1371        None
1372    }
1373
1374    /// One step of a top-level proof SCRIPT (after `intro.`), which also swallows the newline
1375    /// before the next step.
1376    fn parse_script_step_name(&mut self) -> Option<String> {
1377        let name = self.parse_step_name(false)?;
1378        self.skip_whitespace_and_newlines();
1379        Some(name)
1380    }
1381
1382    /// Parse a proof tactic and return BOTH the derivation and the goal it must conclude.
1383    ///
1384    /// The closed tactic vocabulary is [`ONE_SHOT_TACTICS`]; `intro` opens a proof SCRIPT and
1385    /// `induction <var>` opens a bullet-per-constructor elimination. Every arm is handed the same
1386    /// reified goal, so a new tactic is one row in the table rather than a new branch.
1387    fn parse_proof_tactic(&mut self, statement: &Term) -> Result<(Term, Term), ParseError> {
1388        // The goal as an ORDINARY tactic sees it: the prenex `forall` binders are discharged as
1389        // eigenvariables (see [`split_universal_prefix`]), which is exactly the reading this
1390        // surface already gives a free variable — `ring` proves `x + y equals y + x` because `x`
1391        // and `y` are opaque atoms no tactic can instantiate.
1392        let (binders, open_body) = split_universal_prefix(statement);
1393        let open_body = to_eigenvariables(self.ctx, open_body, &binders, None);
1394        let goal_syntax = self.term_to_syntax(&open_body, &[]);
1395
1396        for (keyword, builder) in ONE_SHOT_TACTICS {
1397            if self.try_consume_keyword(keyword) {
1398                self.skip_whitespace();
1399                let _ = self.try_consume(".");
1400                return Ok((apply1(builder, goal_syntax.clone()), goal_syntax));
1401            }
1402        }
1403
1404        if self.try_consume_keyword("intro") {
1405            // Sequencing: `intro. … closer.` → `try_script <name-list> <goal>`. Collect the tactic
1406            // names (`intro` first, then the rest of the script); the script is evaluated against
1407            // the threaded residual goal + hypotheses at conclusion time.
1408            self.skip_whitespace();
1409            let _ = self.try_consume(".");
1410            self.skip_whitespace_and_newlines();
1411            let mut names = vec!["intro".to_string()];
1412            while let Some(name) = self.parse_script_step_name() {
1413                names.push(name);
1414            }
1415            let list = build_script_name_list(&names);
1416            let proof = Term::App(
1417                Box::new(Term::App(
1418                    Box::new(Term::Global("try_script".to_string())),
1419                    Box::new(list),
1420                )),
1421                Box::new(goal_syntax.clone()),
1422            );
1423            return Ok((proof, goal_syntax));
1424        }
1425
1426        if self.try_consume_keyword("induction") {
1427            self.skip_whitespace();
1428            let var_name = self.parse_ident()?;
1429            self.skip_whitespace();
1430            let _ = self.try_consume(".");
1431            return self.parse_induction(&var_name, statement);
1432        }
1433
1434        Err(ParseError::Expected {
1435            expected: "proof tactic (ring, refl, lia, cc, simp, omega, auto, intro, induction)"
1436                .to_string(),
1437            found: self.peek_word().unwrap_or("EOF".to_string()),
1438        })
1439    }
1440
1441    /// Check if the next non-whitespace character is a bullet point
1442    fn peek_bullet(&mut self) -> bool {
1443        // Save position
1444        let saved_pos = self.pos;
1445        self.skip_whitespace_and_newlines();
1446        let result = matches!(self.peek(), Some('-') | Some('*') | Some('+'));
1447        self.pos = saved_pos;
1448        result
1449    }
1450
1451    /// Consume a bullet point character
1452    fn consume_bullet(&mut self) {
1453        self.skip_whitespace_and_newlines();
1454        if matches!(self.peek(), Some('-') | Some('*') | Some('+')) {
1455            self.advance();
1456        }
1457    }
1458
1459    /// Parse a bullet case's tactics (`simp. auto.`) closing ONE goal.
1460    ///
1461    /// A sequence reifies as `try_script <name-list> <goal>` — the SAME mechanism a top-level
1462    /// `Proof: intro. <closer>.` uses, evaluated by the same `eval_script_names`. A bullet case
1463    /// is a proof script scoped to one constructor; giving it a second sequencing form would be
1464    /// two evaluators for one idea, and the one it had (`tact_seq`, plus `try_intro` for the
1465    /// `intro` step) was declared nowhere and reduced nowhere — so every bullet with more than
1466    /// one tactic failed with `UnboundVariable` naming a constant the author never wrote.
1467    ///
1468    /// A LONE one-shot tactic stays the direct application it has always been: `try_refl <goal>`
1469    /// carries its own proof object, and wrapping it would change every derivation the suite
1470    /// already pins.
1471    ///
1472    /// `lead_intros` is the count of binders the elimination introduces BEFORE the author's
1473    /// first tactic runs — see [`LiterateParser::case_binder_count`]. It is 0 for a constructor
1474    /// with no fields, which is every constructor of every enumeration, so the one-shot form is
1475    /// unchanged wherever it was reachable before.
1476    fn parse_tactic_sequence(
1477        &mut self,
1478        goal_syntax: &Term,
1479        lead_intros: usize,
1480    ) -> Result<Term, ParseError> {
1481        let mut names: Vec<String> = Vec::new();
1482
1483        loop {
1484            self.skip_whitespace();
1485
1486            // Stop at newline followed by bullet, end of input, or Attribute keyword
1487            if self.peek_bullet() || self.at_end() || self.peek_keyword("Attribute") {
1488                break;
1489            }
1490
1491            match self.parse_step_name(true) {
1492                Some(name) => names.push(name),
1493                None => break,
1494            }
1495        }
1496
1497        if names.is_empty() {
1498            return Err(ParseError::Missing("tactic in bullet case".to_string()));
1499        }
1500
1501        if lead_intros == 0 {
1502            if let [only] = names.as_slice() {
1503                if let Some((_, builder)) = ONE_SHOT_TACTICS.iter().find(|(k, _)| k == only) {
1504                    return Ok(apply1(builder, goal_syntax.clone()));
1505                }
1506            }
1507        } else {
1508            let mut with_intros: Vec<String> = vec!["intro".to_string(); lead_intros];
1509            with_intros.extend(names);
1510            names = with_intros;
1511        }
1512
1513        Ok(Term::App(
1514            Box::new(Term::App(
1515                Box::new(Term::Global("try_script".to_string())),
1516                Box::new(build_script_name_list(&names)),
1517            )),
1518            Box::new(goal_syntax.clone()),
1519        ))
1520    }
1521
1522    /// How many binders the elimination introduces for one bullet, BEFORE the author's tactic
1523    /// sees the goal.
1524    ///
1525    /// ★ THIS IS LEAN'S `introN`, COUNTED LEAN'S WAY. Lean's minor premise for a constructor is
1526    /// the CLOSED formula `∀f₁ … fₙ, (IH …) → motive (C f⃗)`; the branch the author writes never
1527    /// sees it. `Lean/Meta/Tactic/Induction.lean:97-106` computes
1528    /// `nparams := getTargetArity d - initialArity` — the arity of the MINOR PREMISE'S TYPE less
1529    /// the arity the goal already had — and then `mvarId'.introN nparams …` moves exactly that
1530    /// many binders into the local context, so `| succ k ih => rfl` is handed the OPEN goal
1531    /// `motive (Nat.succ k)` with `k` fixed-but-arbitrary and `ih : motive k` in scope.
1532    ///
1533    /// This is the same subtraction, against the same authority. The count is read off the case
1534    /// goal the KERNEL computes (`induction_step_goal ind motive i`, reduced here), less the
1535    /// depth the motive body already had — never off a second walk of the constructor's
1536    /// telescope. Two computations of one fact is how a compiler and its checker drift apart;
1537    /// `build_case_expected` stays the only thing that decides what a case formula IS.
1538    ///
1539    /// Without a context the count is 0, and the text-only door keeps exactly the reading it
1540    /// had: it cannot be told a constructor's field count any more than it can be told the
1541    /// constructor COUNT, so it emits no introductions and its `induction` closes only cases
1542    /// whose constructor carries no fields. That is the same limitation [`parse_theorem`]
1543    /// already documents, not a second one.
1544    fn case_binder_count(&self, case_goal: &Term, motive_body: &Term) -> usize {
1545        let Some(ctx) = self.ctx else { return 0 };
1546        let reduced = normalize(ctx, case_goal);
1547        let base = normalize(ctx, motive_body);
1548        goal_binder_depth(&reduced).saturating_sub(goal_binder_depth(&base))
1549    }
1550
1551    /// Parse `induction <var>.` plus its bullet cases, and return the elimination derivation
1552    /// together with the goal it concludes.
1553    ///
1554    /// Three things decide the shape, and all three used to be wrong:
1555    ///
1556    /// * **The variable is read.** The motive ABSTRACTS it — `SLam T body` with the variable's
1557    ///   occurrences at de Bruijn 0 — which is what `try_delim_conclude` opens with
1558    ///   `extract_slam_body`. A motive with no binder makes every literate induction conclude the
1559    ///   `SName "Error"` sentinel, so it could close no goal of any type.
1560    /// * **The inductive type is COMPUTED, from the binder's own sort** (`forall n : Colour, …`
1561    ///   inducts over `Colour`), falling back to `Nat` only when the statement quantifies nothing
1562    ///   — the case where the variable is a free name and the surface's reading of a free
1563    ///   variable is "universally quantified".
1564    /// * **Each bullet gets ITS OWN case goal**, `induction_step_goal ind motive i`, computed by
1565    ///   the kernel from the i-th constructor. Handing every bullet the whole theorem statement
1566    ///   made the cases compare against a proposition no constructor case ever equals.
1567    fn parse_induction(
1568        &mut self,
1569        var_name: &str,
1570        statement: &Term,
1571    ) -> Result<(Term, Term), ParseError> {
1572        let (binders, open_body) = split_universal_prefix(statement);
1573        // The inductive comes from the binder's OWN sort. A statement that quantifies but not over
1574        // this name is REFUSED rather than defaulted: the default would eliminate over `Nat` with
1575        // a motive that ignores the binder the author wrote, so the proposition CERTIFIED would be
1576        // `∀_:Nat, P(h#eig)` while the statement said `∀h:Hue, P h`. Today the `Succ` case blocks
1577        // every such proof by accident; the moment a ∀-aware bullet step exists it would not, and
1578        // the divergence between what is written and what is proved would be reachable.
1579        //
1580        // A statement with NO prenex binder at all keeps the `Nat` reading: there the surface's
1581        // own rule for a free variable is "universally quantified", and `Nat` is the quantifier it
1582        // is given.
1583        let sort = match binders.iter().find(|(name, _)| name == var_name) {
1584            Some((_, ty)) => ty.clone(),
1585            None if binders.is_empty() => Term::Global("Nat".to_string()),
1586            None => {
1587                return Err(ParseError::Expected {
1588                    expected: format!(
1589                        "a quantified variable to induct on; this statement binds {}",
1590                        binders
1591                            .iter()
1592                            .map(|(n, t)| format!("`{n} : {t}`"))
1593                            .collect::<Vec<_>>()
1594                            .join(", ")
1595                    ),
1596                    found: var_name.to_string(),
1597                })
1598            }
1599        };
1600
1601        let ind_type = self.term_to_syntax(&sort, &[]);
1602        // An unquantified statement reads its free names as universally quantified, so the
1603        // variable inducted on is one of them, spelled as a free NAME: it is abstracted exactly as
1604        // a quantified one is, or the motive would ignore it and every case would restate the
1605        // theorem instead of its instance. A declared constant of that spelling is not a free
1606        // variable, and a binder of that spelling inside the statement would capture it.
1607        let unquantified;
1608        let open_body = if binders.is_empty() {
1609            if self
1610                .ctx
1611                .is_some_and(|ctx| ctx.get_global(var_name).is_some())
1612            {
1613                return Err(ParseError::InvalidConsiderSyntax(format!(
1614                    "`induction {var_name}` needs a VARIABLE to eliminate; `{var_name}` is a \
1615                     declared constant"
1616                )));
1617            }
1618            unquantified = free_name_as_variable(open_body, var_name).ok_or_else(|| {
1619                ParseError::InvalidConsiderSyntax(format!(
1620                    "`induction {var_name}`: the statement binds `{var_name}` itself, so its free \
1621                     `{var_name}` cannot be abstracted without being captured; quantify it with \
1622                     `forall` instead"
1623                ))
1624            })?;
1625            &unquantified
1626        } else {
1627            open_body
1628        };
1629        // The variable being eliminated is ABSTRACTED (de Bruijn 0 in the motive); every OTHER
1630        // prenex binder is discharged as an eigenvariable, exactly as an ordinary tactic's goal is.
1631        let open_body = to_eigenvariables(self.ctx, open_body, &binders, Some(var_name));
1632        let bound = [var_name.to_string()];
1633        let motive_body = self.term_to_syntax(&open_body, &bound);
1634        let motive = Term::App(
1635            Box::new(Term::App(
1636                Box::new(Term::Global("SLam".to_string())),
1637                Box::new(ind_type.clone()),
1638            )),
1639            Box::new(motive_body.clone()),
1640        );
1641
1642        // One bullet per constructor, each closing the goal the kernel derives for that
1643        // constructor from the motive — with the constructor's fields and induction hypotheses
1644        // ALREADY INTRODUCED, which is what Lean's `| succ k ih => …` hands its branch.
1645        let mut cases = Vec::new();
1646        while self.peek_bullet() {
1647            self.consume_bullet();
1648            self.skip_whitespace();
1649            let case_goal = case_goal_term(&ind_type, &motive, cases.len());
1650            let lead_intros = self.case_binder_count(&case_goal, &motive_body);
1651            cases.push(self.parse_tactic_sequence(&case_goal, lead_intros)?);
1652        }
1653
1654        // With a context, the elimination is checked against the REAL constructor list here,
1655        // where the source text is still in hand. `DElim` also checks it, but by then the only
1656        // thing it can say is that nothing was concluded — the count, the inductive and the
1657        // constructor names have all been left behind.
1658        if let Some(ctx) = self.ctx {
1659            let Some(ind_name) = type_head_name(&sort) else {
1660                return Err(ParseError::InvalidConsiderSyntax(format!(
1661                    "`induction {var_name}` needs an INDUCTIVE to eliminate over; `{var_name}` \
1662                     has type `{sort}`, which is not a type application"
1663                )));
1664            };
1665            let ctors = ctx.get_constructors(ind_name);
1666            if ctors.is_empty() {
1667                return Err(ParseError::InvalidConsiderSyntax(format!(
1668                    "`induction {var_name}` needs an INDUCTIVE to eliminate over; `{ind_name}` \
1669                     has no constructors"
1670                )));
1671            }
1672            if cases.len() != ctors.len() {
1673                return Err(ParseError::InvalidConsiderSyntax(format!(
1674                    "`{ind_name}` has {} constructor(s) — {} — so this proof needs {} bullet \
1675                     case(s), one per constructor, in that order; it has {}",
1676                    ctors.len(),
1677                    ctors.iter().map(|(n, _)| *n).collect::<Vec<_>>().join(", "),
1678                    ctors.len(),
1679                    cases.len()
1680                )));
1681            }
1682        }
1683
1684        // `try_induction ind motive cases` — reduces to `DElim`, which verifies every case
1685        // conclusion against its constructor before conceding `Forall ind motive`.
1686        let mut case_chain = Term::Global("DCaseEnd".to_string());
1687        for case_proof in cases.into_iter().rev() {
1688            case_chain = Term::App(
1689                Box::new(Term::App(
1690                    Box::new(Term::Global("DCase".to_string())),
1691                    Box::new(case_proof),
1692                )),
1693                Box::new(case_chain),
1694            );
1695        }
1696        let proof = Term::App(
1697            Box::new(Term::App(
1698                Box::new(Term::App(
1699                    Box::new(Term::Global("try_induction".to_string())),
1700                    Box::new(ind_type.clone()),
1701                )),
1702                Box::new(motive.clone()),
1703            )),
1704            Box::new(case_chain),
1705        );
1706        Ok((proof, forall_syntax(&ind_type, &motive)))
1707    }
1708
1709    /// Parse function parameters: (x: T) and (y: U) or (x: T) (y: U)
1710    fn parse_function_params(&mut self) -> Result<Vec<(String, Term)>, ParseError> {
1711        let mut params = Vec::new();
1712
1713        loop {
1714            self.skip_whitespace();
1715
1716            // Check for opening paren
1717            if !self.peek_char('(') {
1718                break;
1719            }
1720
1721            // Parse one parameter group
1722            self.advance(); // consume '('
1723            self.skip_whitespace();
1724
1725            let param_name = self.parse_ident()?;
1726            self.skip_whitespace();
1727
1728            if !self.try_consume(":") {
1729                return Err(ParseError::Expected {
1730                    expected: "':'".to_string(),
1731                    found: self.peek_word().unwrap_or("EOF".to_string()),
1732                });
1733            }
1734            self.skip_whitespace();
1735
1736            let param_type = self.parse_type()?;
1737            self.skip_whitespace();
1738
1739            if !self.try_consume(")") {
1740                return Err(ParseError::Expected {
1741                    expected: "')'".to_string(),
1742                    found: self.peek_word().unwrap_or("EOF".to_string()),
1743                });
1744            }
1745
1746            params.push((param_name, param_type));
1747
1748            self.skip_whitespace();
1749
1750            // Check for "and" separator
1751            let _ = self.try_consume_keyword("and");
1752        }
1753
1754        Ok(params)
1755    }
1756
1757    /// Parse optional type parameters: (T: Type)
1758    fn parse_param_list(&mut self) -> Result<Vec<(String, Term)>, ParseError> {
1759        let mut params = Vec::new();
1760
1761        if !self.peek_char('(') {
1762            return Ok(params);
1763        }
1764
1765        self.advance(); // consume '('
1766        self.skip_whitespace();
1767
1768        loop {
1769            let param_name = self.parse_ident()?;
1770            self.skip_whitespace();
1771
1772            if !self.try_consume(":") {
1773                return Err(ParseError::Expected {
1774                    expected: "':'".to_string(),
1775                    found: self.peek_word().unwrap_or("EOF".to_string()),
1776                });
1777            }
1778            self.skip_whitespace();
1779
1780            let param_type = self.parse_type()?;
1781            params.push((param_name, param_type));
1782
1783            self.skip_whitespace();
1784
1785            if self.try_consume(")") {
1786                break;
1787            }
1788
1789            if !self.try_consume(",") && !self.try_consume_keyword("and") {
1790                return Err(ParseError::Expected {
1791                    expected: "')' or ','".to_string(),
1792                    found: self.peek_word().unwrap_or("EOF".to_string()),
1793                });
1794            }
1795            self.skip_whitespace();
1796        }
1797
1798        Ok(params)
1799    }
1800
1801    // ============================================================
1802    // BODY / TERM PARSING
1803    // ============================================================
1804
1805    /// Parse function body (indented block after ":")
1806    ///
1807    /// A body may begin on the line after its `:` — `When Succ k:` with a nested `Consider` written
1808    /// beneath it is the ordinary layout for a two-level equation set — so the line break is
1809    /// skipped. What follows must then be a body: a `When` there means the clause before it has
1810    /// none, and that is said here rather than read as an application of a global named `When`.
1811    fn parse_body(&mut self) -> Result<Term, ParseError> {
1812        self.skip_whitespace_and_newlines();
1813        if self.peek_keyword("When") {
1814            return Err(ParseError::Expected {
1815                expected:
1816                    "a clause body (`Yield …` or a nested `Consider …`) before the next `When`"
1817                        .to_string(),
1818                found: "When".to_string(),
1819            });
1820        }
1821
1822        // Check for Consider (pattern matching)
1823        if self.peek_keyword("Consider") {
1824            return self.parse_consider();
1825        }
1826
1827        // Check for Yield (direct return)
1828        if self.peek_keyword("Yield") {
1829            return self.parse_yield();
1830        }
1831
1832        // Check for "given" lambda
1833        if self.peek_keyword("given") {
1834            return self.parse_given_lambda();
1835        }
1836
1837        // Check for pipe lambda |x: T| -> body
1838        if self.peek_char('|') {
1839            return self.parse_pipe_lambda();
1840        }
1841
1842        // Otherwise, parse as a term expression
1843        self.parse_term()
1844    }
1845
1846    /// Parse: `Consider x: When <pattern>: <body>. …`
1847    ///
1848    /// This is the equation-set surface, and with a context it is compiled as one:
1849    /// [`super::match_compile::compile_clauses`] turns the clause matrix into a tree of the
1850    /// kernel's positional `Match` nodes. Three things that reading follows and the flat one
1851    /// cannot:
1852    ///
1853    /// * A clause goes in the slot of the constructor it NAMES. `Bool` is registered `true` then
1854    ///   `false`, so `When false: … When true: …` must not compute the other function — which is
1855    ///   what pushing one case per clause in source order does for every equal-arity inductive.
1856    /// * A pattern NESTS. `When Succ (Succ k):` is a two-level match, not a parse error.
1857    /// * `When _:` is a catch-all, fanned out over every constructor with no clause of its own,
1858    ///   the body replicated and re-abstracted over each one's fields.
1859    /// * A clause set matches SEVERAL COLUMNS at once. `Consider a and b:` with
1860    ///   `When Zero and _:` is Lean's `| 0, _ => …`, and it is the shape an overlap is actually
1861    ///   written in: `pick 0 _ = 1 | _ 0 = 2 | _ _ = 3` splits into `match a with | Zero => 1 |
1862    ///   Succ _ => match b with | Zero => 2 | Succ _ => 3`. One column is the degenerate case of
1863    ///   the same matrix, so this is not a second code path.
1864    ///
1865    /// Overlapping clauses resolve TOP-TO-BOTTOM, and a constructor no clause can reach is a
1866    /// non-exhaustiveness error rather than an invented value: a LOGOS definition is total.
1867    fn parse_consider(&mut self) -> Result<Term, ParseError> {
1868        self.consume_keyword("Consider")?;
1869        self.skip_whitespace();
1870
1871        // THE COLUMNS. `and` separates them, exactly as it separates the parameters they usually
1872        // are (`## To pick (a: Nat) and (b: Nat) -> Nat:`), and nothing in the term grammar reads
1873        // it — application, comparison and the two infix connectives all stop before it — so a
1874        // one-column `Consider` parses byte for byte as it always did.
1875        let mut discriminants = vec![self.parse_term()?];
1876        loop {
1877            self.skip_whitespace();
1878            if !self.try_consume_keyword("and") {
1879                break;
1880            }
1881            self.skip_whitespace();
1882            discriminants.push(self.parse_term()?);
1883        }
1884
1885        self.skip_whitespace();
1886
1887        if !self.try_consume(":") {
1888            return Err(ParseError::Expected {
1889                expected: "':'".to_string(),
1890                found: self.peek_word().unwrap_or("EOF".to_string()),
1891            });
1892        }
1893
1894        // The result type is the motive at every node of the compiled tree. The type checker
1895        // wraps a raw type as the constant motive `λ_:I. T`.
1896        let result_type = self
1897            .return_type
1898            .clone()
1899            .unwrap_or_else(|| Term::Sort(Universe::Type(0)));
1900
1901        // With a context each column's own type is known here, which is what lets a clause's
1902        // binders enter scope with their REAL types before its body is read — a nested
1903        // `Consider` inside a clause body needs exactly that.
1904        let working = self.working_context();
1905        let disc_tys: Option<Vec<Term>> = match &working {
1906            Some(c) => Some(
1907                discriminants
1908                    .iter()
1909                    .map(|d| {
1910                        infer_type(c, d).map_err(|e| {
1911                            ParseError::InvalidConsiderSyntax(format!(
1912                                "`Consider {d}` cannot be compiled: the discriminant has no type \
1913                                 here ({e})"
1914                            ))
1915                        })
1916                    })
1917                    .collect::<Result<Vec<_>, _>>()?,
1918            ),
1919            None => None,
1920        };
1921
1922        let mut clauses: Vec<Clause> = Vec::new();
1923        // THE OFFSIDE RULE. A `Consider`'s first `When` fixes its clause column: its own column
1924        // when it begins a line, and — when it is written beside the `Consider` — the column just
1925        // past the indentation of the line they share, so the siblings are the clauses indented
1926        // beneath that line. A later `When` that begins a line to the LEFT of the fixed column
1927        // belongs to an enclosing `Consider`, and ends this one. Without it a nested equation set
1928        // written beneath (or beside) `When Succ k:` would swallow every clause of the set around
1929        // it, and the outer function would silently lose its remaining cases to the inner match.
1930        // A `When` that does not begin a line is read as it always was: on one line there is no
1931        // layout.
1932        let mut clause_column: Option<usize> = None;
1933
1934        loop {
1935            self.skip_whitespace_and_newlines();
1936
1937            if !self.peek_keyword("When") {
1938                break;
1939            }
1940            let column = self.line_start_column();
1941            if clauses.is_empty() {
1942                clause_column = Some(column.unwrap_or_else(|| self.line_indent() + 1));
1943            } else if let (Some(fixed), Some(here)) = (clause_column, column) {
1944                if here < fixed {
1945                    break;
1946                }
1947            }
1948
1949            self.consume_keyword("When")?;
1950            self.skip_whitespace();
1951
1952            // ONE PATTERN PER COLUMN, separated the way the columns were.
1953            let mut patterns = vec![self.parse_clause_pattern()?];
1954            loop {
1955                self.skip_whitespace();
1956                if !self.try_consume_keyword("and") {
1957                    break;
1958                }
1959                self.skip_whitespace();
1960                patterns.push(self.parse_clause_pattern()?);
1961            }
1962            self.skip_whitespace();
1963
1964            if !self.try_consume(":") {
1965                return Err(ParseError::Expected {
1966                    expected: "':'".to_string(),
1967                    found: self.peek_word().unwrap_or("EOF".to_string()),
1968                });
1969            }
1970
1971            // A column count mismatch is caught HERE, where the source text is still in hand.
1972            // `compile_clauses` checks it too and is the authority — but by then the clause is a
1973            // row of a matrix, and what a reader would get back names neither the `Consider` line
1974            // nor the `When` that disagrees with it. This is the same division of labour the
1975            // bullet-count check in `parse_induction` already draws.
1976            if patterns.len() != discriminants.len() {
1977                return Err(ParseError::InvalidConsiderSyntax(format!(
1978                    "`Consider` names {} column(s) — {} — so every `When` needs {} pattern(s) \
1979                     separated by `and`; this one has {}: `{}`",
1980                    discriminants.len(),
1981                    discriminants
1982                        .iter()
1983                        .map(|d| format!("`{d}`"))
1984                        .collect::<Vec<_>>()
1985                        .join(", "),
1986                    discriminants.len(),
1987                    patterns.len(),
1988                    patterns
1989                        .iter()
1990                        .map(Pattern::render)
1991                        .collect::<Vec<_>>()
1992                        .join(" and ")
1993                )));
1994            }
1995
1996            self.skip_whitespace();
1997
1998            // The binders this clause introduces, with the types the constructor gives them.
1999            // `pattern_binder_types` is the same telescope walk the compiler itself does — one
2000            // computation of one fact, so the scope a body is read in and the scope it is
2001            // compiled in cannot drift.
2002            let typed: Vec<(String, Term)> = match (&working, &disc_tys) {
2003                (Some(c), Some(tys)) => {
2004                    let mut out = Vec::new();
2005                    for (t, pattern) in tys.iter().zip(&patterns) {
2006                        out.extend(
2007                            pattern_binder_types(c, t, pattern)
2008                                .map_err(|e| ParseError::InvalidConsiderSyntax(e.to_string()))?,
2009                        );
2010                    }
2011                    out
2012                }
2013                _ => patterns
2014                    .iter()
2015                    .flat_map(Pattern::binders)
2016                    .map(|n| (n, Term::Global("_".to_string())))
2017                    .collect(),
2018            };
2019
2020            let mark = self.locals.len();
2021            let mut newly_bound: Vec<String> = Vec::new();
2022            for (n, t) in &typed {
2023                if self.bound_vars.insert(n.clone()) {
2024                    newly_bound.push(n.clone());
2025                }
2026                self.locals.push((n.clone(), t.clone()));
2027            }
2028
2029            let body = self.parse_body()?;
2030
2031            // Only the names THIS clause introduced leave scope — an outer binder it shadowed
2032            // stays bound.
2033            for n in &newly_bound {
2034                self.bound_vars.remove(n);
2035            }
2036            self.locals.truncate(mark);
2037
2038            clauses.push(Clause { patterns, body });
2039
2040            self.skip_whitespace();
2041            let _ = self.try_consume(".");
2042        }
2043
2044        if clauses.is_empty() {
2045            return Err(ParseError::Missing("When clauses".to_string()));
2046        }
2047
2048        if self.measuring {
2049            return Ok(Term::Hole);
2050        }
2051        match working {
2052            Some(c) => compile_clauses_reporting(&c, &discriminants, &result_type, &clauses)
2053                .map(|(term, _report)| term)
2054                .map_err(|e| ParseError::InvalidConsiderSyntax(e.to_string())),
2055            None => flat_positional_match(discriminants, result_type, &clauses),
2056        }
2057    }
2058
2059    /// Parse one `When` clause's pattern.
2060    ///
2061    /// ```text
2062    /// pattern := '_' | name atom*  | '(' pattern ')'
2063    /// atom    := '_' | name | '(' pattern ')'
2064    /// ```
2065    ///
2066    /// A bare name is a CONSTRUCTOR if the context says so and a variable otherwise, which is
2067    /// Lean's rule. Without a context the head is read as a constructor name and an argument as a
2068    /// binder — the flat reading, unchanged.
2069    fn parse_clause_pattern(&mut self) -> Result<Pattern, ParseError> {
2070        self.skip_whitespace();
2071        if self.peek_char('(') {
2072            return self.parse_parenthesised_pattern();
2073        }
2074        if let Some(n) = self.parse_pattern_numeral() {
2075            return Ok(Pattern::Numeral(n));
2076        }
2077        let name = self.parse_ident()?;
2078        if name == "_" {
2079            return Ok(Pattern::Wildcard);
2080        }
2081
2082        let mut args = Vec::new();
2083        loop {
2084            self.skip_whitespace();
2085            if self.at_end()
2086                || self.peek_char(':')
2087                || self.peek_char(')')
2088                || self.peek_char('.')
2089                // `and` separates COLUMNS, so it ends this pattern rather than being read as one
2090                // more field of it. It is a keyword of this surface everywhere else it appears
2091                // (parameter groups, field lists), so nothing that was a binder stops being one.
2092                || self.peek_keyword("and")
2093            {
2094                break;
2095            }
2096            args.push(self.parse_pattern_atom()?);
2097        }
2098
2099        // A head with no arguments is a constructor when the name denotes one; a context-free
2100        // parser has to assume it is one, which is what the flat reading always did.
2101        match (self.ctx, self.constructor_named(&name)?) {
2102            (Some(_), Some(key)) => Ok(Pattern::Ctor { name: key, args }),
2103            (Some(_), None) if args.is_empty() => Ok(Pattern::Var(name)),
2104            _ => Ok(Pattern::Ctor { name, args }),
2105        }
2106    }
2107
2108    /// The constructor a pattern name denotes, when it denotes one — resolved like every other
2109    /// name the author wrote, so a clause lands in the slot of the constructor its name MEANS here.
2110    /// A name that denotes no constructor is a binder, and keeps its spelling as one. A name two
2111    /// readings of which are constructors is ambiguous and says so.
2112    fn constructor_named(&self, written: &str) -> Result<Option<String>, ParseError> {
2113        let Some(ctx) = self.ctx else { return Ok(None) };
2114        let Some(name) = Name::parse(written) else {
2115            return Ok(ctx.is_constructor(written).then(|| written.to_string()));
2116        };
2117        match with_env(ctx, &[], |env| env.resolve(&self.scope, &name)) {
2118            Resolution::Found(key) => Ok(ctx.is_constructor(&key).then_some(key)),
2119            Resolution::Unresolved(_) => Ok(None),
2120            Resolution::Ambiguous {
2121                written,
2122                candidates,
2123            } => {
2124                if candidates.iter().any(|c| ctx.is_constructor(c)) {
2125                    Err(ParseError::AmbiguousName {
2126                        written,
2127                        candidates,
2128                    })
2129                } else {
2130                    Ok(None)
2131                }
2132            }
2133        }
2134    }
2135
2136    /// A NUMERAL in pattern position — `When 0:`, `When Succ 1:` — read as a run of digits, or
2137    /// `None` with the position unmoved.
2138    ///
2139    /// Lean writes `| 0 => 10 | 1 => 20 | n+2 => n` and expands the literals into constructor
2140    /// applications inside the matrix compiler (`Lean/Meta/Match/Match.lean:629`
2141    /// `expandNatValuePattern`). The same split is kept here: this door only RECORDS that a
2142    /// numeral was written, and [`super::match_compile::Pattern::Numeral`] is expanded where the
2143    /// column's inductive is finally known. A parser that expanded it would have to guess the
2144    /// constructor names, which is the guess that mis-slots a clause.
2145    fn parse_pattern_numeral(&mut self) -> Option<u64> {
2146        if !self.peek().is_some_and(|c| c.is_ascii_digit()) {
2147            return None;
2148        }
2149        let start = self.pos;
2150        let mut digits = String::new();
2151        while let Some(c) = self.peek() {
2152            if !c.is_ascii_digit() {
2153                break;
2154            }
2155            digits.push(c);
2156            self.advance();
2157        }
2158        match digits.parse::<u64>() {
2159            Ok(n) => Some(n),
2160            // A numeral too large for the unary spelling is not a numeral pattern; leave the
2161            // position untouched so the ordinary reading reports it.
2162            Err(_) => {
2163                self.pos = start;
2164                None
2165            }
2166        }
2167    }
2168
2169    fn parse_pattern_atom(&mut self) -> Result<Pattern, ParseError> {
2170        self.skip_whitespace();
2171        if self.peek_char('(') {
2172            return self.parse_parenthesised_pattern();
2173        }
2174        if let Some(n) = self.parse_pattern_numeral() {
2175            return Ok(Pattern::Numeral(n));
2176        }
2177        let name = self.parse_ident()?;
2178        if name == "_" {
2179            return Ok(Pattern::Wildcard);
2180        }
2181        match self.constructor_named(&name)? {
2182            Some(key) => Ok(Pattern::Ctor {
2183                name: key,
2184                args: Vec::new(),
2185            }),
2186            None => Ok(Pattern::Var(name)),
2187        }
2188    }
2189
2190    fn parse_parenthesised_pattern(&mut self) -> Result<Pattern, ParseError> {
2191        self.advance(); // '('
2192        let inner = self.parse_clause_pattern()?;
2193        self.skip_whitespace();
2194        if !self.try_consume(")") {
2195            return Err(ParseError::Expected {
2196                expected: "')' closing a pattern".to_string(),
2197                found: self.peek_word().unwrap_or("EOF".to_string()),
2198            });
2199        }
2200        Ok(inner)
2201    }
2202
2203    /// Parse: Yield expression
2204    fn parse_yield(&mut self) -> Result<Term, ParseError> {
2205        self.consume_keyword("Yield")?;
2206        self.skip_whitespace();
2207        self.parse_term()
2208    }
2209
2210    /// Parse: given x: Type yields body
2211    fn parse_given_lambda(&mut self) -> Result<Term, ParseError> {
2212        self.consume_keyword("given")?;
2213        self.skip_whitespace();
2214
2215        let param = self.parse_ident()?;
2216        self.skip_whitespace();
2217
2218        if !self.try_consume(":") {
2219            return Err(ParseError::Expected {
2220                expected: "':'".to_string(),
2221                found: self.peek_word().unwrap_or("EOF".to_string()),
2222            });
2223        }
2224        self.skip_whitespace();
2225
2226        let param_type = self.parse_type()?;
2227        self.skip_whitespace();
2228
2229        self.consume_keyword("yields")?;
2230        self.skip_whitespace();
2231
2232        self.bound_vars.insert(param.clone());
2233        let body = self.parse_term()?;
2234        self.bound_vars.remove(&param);
2235
2236        Ok(Term::Lambda {
2237            param,
2238            param_type: Box::new(param_type),
2239            body: Box::new(body),
2240        })
2241    }
2242
2243    /// Parse: |x: Type| -> body
2244    fn parse_pipe_lambda(&mut self) -> Result<Term, ParseError> {
2245        self.advance(); // consume '|'
2246        self.skip_whitespace();
2247
2248        let param = self.parse_ident()?;
2249        self.skip_whitespace();
2250
2251        if !self.try_consume(":") {
2252            return Err(ParseError::Expected {
2253                expected: "':'".to_string(),
2254                found: self.peek_word().unwrap_or("EOF".to_string()),
2255            });
2256        }
2257        self.skip_whitespace();
2258
2259        let param_type = self.parse_type()?;
2260        self.skip_whitespace();
2261
2262        if !self.try_consume("|") {
2263            return Err(ParseError::Expected {
2264                expected: "'|'".to_string(),
2265                found: self.peek_word().unwrap_or("EOF".to_string()),
2266            });
2267        }
2268        self.skip_whitespace();
2269
2270        if !self.try_consume("->") {
2271            return Err(ParseError::Expected {
2272                expected: "'->'".to_string(),
2273                found: self.peek_word().unwrap_or("EOF".to_string()),
2274            });
2275        }
2276        self.skip_whitespace();
2277
2278        self.bound_vars.insert(param.clone());
2279        let body = self.parse_term()?;
2280        self.bound_vars.remove(&param);
2281
2282        Ok(Term::Lambda {
2283            param,
2284            param_type: Box::new(param_type),
2285            body: Box::new(body),
2286        })
2287    }
2288
2289    /// Parse a term expression (handles infix operators like `equals` and `implies`)
2290    fn parse_term(&mut self) -> Result<Term, ParseError> {
2291        self.skip_whitespace();
2292        // The binder form comes first: it is the ONLY way a literate `Statement:` can quantify,
2293        // and without it every ∀-theorem has to be written with its binder erased and hoped over.
2294        if self.peek_keyword("forall") || self.peek_char('\u{2200}') {
2295            return self.parse_forall();
2296        }
2297
2298        let lhs = self.parse_comparison()?;
2299
2300        self.skip_whitespace();
2301
2302        // Check for "equals" infix operator: X equals Y → Eq Hole X Y
2303        if self.peek_keyword("equals") {
2304            self.consume_keyword("equals")?;
2305            self.skip_whitespace();
2306            let rhs = self.parse_comparison()?; // Parse RHS as comparison (not full term to avoid recursion issues)
2307            return Ok(Term::App(
2308                Box::new(Term::App(
2309                    Box::new(Term::App(
2310                        Box::new(self.global("Eq")?),
2311                        Box::new(Term::Hole), // Type placeholder (implicit argument)
2312                    )),
2313                    Box::new(lhs),
2314                )),
2315                Box::new(rhs),
2316            ));
2317        }
2318
2319        // Check for "implies" infix operator at term level too: X implies Y → Pi _ : X, Y
2320        if self.peek_keyword("implies") {
2321            self.consume_keyword("implies")?;
2322            self.skip_whitespace();
2323            let rhs = self.parse_term()?; // Full term for right-associativity
2324            return Ok(Term::Pi {
2325                param: "_".to_string(),
2326                param_type: Box::new(lhs),
2327                body_type: Box::new(rhs),
2328            });
2329        }
2330
2331        Ok(lhs)
2332    }
2333
2334    // ============================================================
2335    // INFIX OPERATOR PARSING (comparison, additive, multiplicative)
2336    // ============================================================
2337
2338    /// Parse `forall x : T, body` (also spelled `\u{2200} x : T, body`) into a named `Pi`.
2339    ///
2340    /// The type is REQUIRED. A binder with no sort would leave `induction` nothing to eliminate
2341    /// over and would let `forall n, …` and a bare free `n` be different spellings of the same
2342    /// thing; demanding the sort is what makes the binder carry information.
2343    fn parse_forall(&mut self) -> Result<Term, ParseError> {
2344        if !(self.try_consume_keyword("forall") || self.try_consume("\u{2200}")) {
2345            return Err(ParseError::Expected {
2346                expected: "'forall'".to_string(),
2347                found: self.peek_word().unwrap_or("EOF".to_string()),
2348            });
2349        }
2350        self.skip_whitespace();
2351        let param = self.parse_ident()?;
2352        self.skip_whitespace();
2353        if !self.try_consume(":") {
2354            return Err(ParseError::Expected {
2355                expected: "':' — a `forall` binder must name its type".to_string(),
2356                found: self.peek_word().unwrap_or("EOF".to_string()),
2357            });
2358        }
2359        self.skip_whitespace();
2360        let param_type = self.parse_type()?;
2361        self.skip_whitespace();
2362        if !self.try_consume(",") {
2363            return Err(ParseError::Expected {
2364                expected: "',' after the `forall` binder".to_string(),
2365                found: self.peek_word().unwrap_or("EOF".to_string()),
2366            });
2367        }
2368        self.skip_whitespace();
2369
2370        let was_bound = self.bound_vars.contains(&param);
2371        self.bound_vars.insert(param.clone());
2372        let body_type = self.parse_term()?;
2373        if !was_bound {
2374            self.bound_vars.remove(&param);
2375        }
2376
2377        Ok(Term::Pi {
2378            param,
2379            param_type: Box::new(param_type),
2380            body_type: Box::new(body_type),
2381        })
2382    }
2383
2384    /// Parse comparison operators: x <= y, x < y, x >= y, x > y
2385    /// Precedence: lower than arithmetic, higher than equals/implies
2386    /// Non-associative: a < b < c is not valid
2387    fn parse_comparison(&mut self) -> Result<Term, ParseError> {
2388        let lhs = self.parse_additive()?;
2389        self.skip_whitespace();
2390
2391        // Check for comparison operators (order matters: >= before >, <= before <)
2392        let op_name = if self.try_consume("<=") || self.try_consume("≤") {
2393            Some("le")
2394        } else if self.try_consume(">=") || self.try_consume("≥") {
2395            Some("ge")
2396        } else if self.try_consume("<") {
2397            Some("lt")
2398        } else if self.try_consume(">") {
2399            Some("gt")
2400        } else {
2401            None
2402        };
2403
2404        if let Some(op) = op_name {
2405            self.skip_whitespace();
2406            let rhs = self.parse_additive()?; // Non-associative: parse additive, not comparison
2407            return Ok(Term::App(
2408                Box::new(Term::App(Box::new(self.global(op)?), Box::new(lhs))),
2409                Box::new(rhs),
2410            ));
2411        }
2412
2413        Ok(lhs)
2414    }
2415
2416    /// Parse additive operators: x + y, x - y
2417    /// Left-associative: a + b - c = (a + b) - c
2418    fn parse_additive(&mut self) -> Result<Term, ParseError> {
2419        let mut result = self.parse_multiplicative()?;
2420
2421        loop {
2422            self.skip_whitespace();
2423
2424            let op_name = if self.try_consume("+") {
2425                Some("add")
2426            } else if self.peek_char('-') && !self.peek_arrow() && !self.peek_negative_number() {
2427                self.advance(); // consume '-'
2428                Some("sub")
2429            } else {
2430                None
2431            };
2432
2433            if let Some(op) = op_name {
2434                self.skip_whitespace();
2435                let rhs = self.parse_multiplicative()?;
2436                result = Term::App(
2437                    Box::new(Term::App(Box::new(self.global(op)?), Box::new(result))),
2438                    Box::new(rhs),
2439                );
2440            } else {
2441                break;
2442            }
2443        }
2444
2445        Ok(result)
2446    }
2447
2448    /// Parse multiplicative operators: x * y
2449    /// Left-associative: a * b * c = (a * b) * c
2450    fn parse_multiplicative(&mut self) -> Result<Term, ParseError> {
2451        let mut result = self.parse_app()?;
2452
2453        loop {
2454            self.skip_whitespace();
2455
2456            if self.try_consume("*") {
2457                self.skip_whitespace();
2458                let rhs = self.parse_app()?;
2459                result = Term::App(
2460                    Box::new(Term::App(Box::new(self.global("mul")?), Box::new(result))),
2461                    Box::new(rhs),
2462                );
2463            } else {
2464                break;
2465            }
2466        }
2467
2468        Ok(result)
2469    }
2470
2471    /// Parse application: f x y or f(x, y)
2472    fn parse_app(&mut self) -> Result<Term, ParseError> {
2473        let mut func = self.parse_atom()?;
2474
2475        loop {
2476            self.skip_whitespace();
2477
2478            // Check for tuple-style call: f(x, y)
2479            if self.peek_char('(') {
2480                self.advance(); // consume '('
2481                self.skip_whitespace();
2482
2483                if !self.peek_char(')') {
2484                    loop {
2485                        let arg = self.parse_term()?;
2486                        func = Term::App(Box::new(func), Box::new(arg));
2487                        self.skip_whitespace();
2488
2489                        if self.try_consume(",") {
2490                            self.skip_whitespace();
2491                        } else {
2492                            break;
2493                        }
2494                    }
2495                }
2496
2497                if !self.try_consume(")") {
2498                    return Err(ParseError::Expected {
2499                        expected: "')'".to_string(),
2500                        found: self.peek_word().unwrap_or("EOF".to_string()),
2501                    });
2502                }
2503                continue;
2504            }
2505
2506            // Check for curried application (next token is an atom)
2507            // Stop before infix operators like `equals`, `implies`, `+`, `-`, `*`, `<`, etc.
2508            if self.at_end()
2509                || self.peek_char(')')
2510                || self.peek_char('.')
2511                || self.peek_char(',')
2512                || self.peek_char(':')
2513                || self.peek_char('|')
2514                || self.peek_keyword("When")
2515                || self.peek_keyword("Yield")
2516                || self.peek_keyword("and")
2517                || self.peek_keyword("or")
2518                || self.peek_keyword("equals")
2519                || self.peek_keyword("implies")
2520                // Stop at infix arithmetic and comparison operators
2521                || self.peek_char('+')
2522                || self.peek_char('*')
2523                || self.peek_comparison_operator()
2524                || (self.peek_char('-') && !self.peek_arrow() && !self.peek_negative_number())
2525            {
2526                break;
2527            }
2528
2529            // Try to parse next atom for curried application
2530            if let Ok(arg) = self.parse_atom() {
2531                func = Term::App(Box::new(func), Box::new(arg));
2532            } else {
2533                break;
2534            }
2535        }
2536
2537        Ok(func)
2538    }
2539
2540    /// Parse an atom: identifier, literal, or parenthesized term
2541    fn parse_atom(&mut self) -> Result<Term, ParseError> {
2542        self.skip_whitespace();
2543
2544        // Check for number literal
2545        if let Some(c) = self.peek() {
2546            if c.is_ascii_digit() {
2547                return self.parse_number();
2548            }
2549            if c == '-' {
2550                // Check for negative number
2551                let saved_pos = self.pos;
2552                self.advance();
2553                if let Some(next) = self.peek() {
2554                    if next.is_ascii_digit() {
2555                        self.pos = saved_pos;
2556                        return self.parse_number();
2557                    }
2558                }
2559                self.pos = saved_pos;
2560            }
2561        }
2562
2563        // Check for string literal
2564        if self.peek_char('"') {
2565            return self.parse_string();
2566        }
2567
2568        // Check for parenthesized term
2569        if self.peek_char('(') {
2570            self.advance();
2571            let term = self.parse_term()?;
2572            self.skip_whitespace();
2573            if !self.try_consume(")") {
2574                return Err(ParseError::Expected {
2575                    expected: "')'".to_string(),
2576                    found: self.peek_word().unwrap_or("EOF".to_string()),
2577                });
2578            }
2579            return Ok(term);
2580        }
2581
2582        // Check for "the" prefix (allows "the Successor of ...", "the diagonalization of ...", "the Name X")
2583        if self.try_consume_keyword("the") {
2584            self.skip_whitespace();
2585            // Check for "diagonalization of" special syntax
2586            if self.try_consume_keyword("diagonalization") {
2587                self.skip_whitespace();
2588                if !self.try_consume_keyword("of") {
2589                    return Err(ParseError::Expected {
2590                        expected: "'of'".to_string(),
2591                        found: self.peek_word().unwrap_or("EOF".to_string()),
2592                    });
2593                }
2594                self.skip_whitespace();
2595                let arg = self.parse_atom()?;
2596                return Ok(Term::App(
2597                    Box::new(Term::Global("syn_diag".to_string())),
2598                    Box::new(arg),
2599                ));
2600            }
2601            // Check for "the Name X" syntax → SName X
2602            if self.peek_keyword("Name") {
2603                self.consume_keyword("Name")?;
2604                self.skip_whitespace();
2605                let arg = self.parse_atom()?;
2606                return Ok(Term::App(
2607                    Box::new(Term::Global("SName".to_string())),
2608                    Box::new(arg),
2609                ));
2610            }
2611            // Otherwise continue to parse the identifier after "the"
2612        }
2613
2614        // Check for "Name" special syntax: Name "X" → SName "X"
2615        if self.peek_keyword("Name") {
2616            self.consume_keyword("Name")?;
2617            self.skip_whitespace();
2618            let arg = self.parse_atom()?;
2619            return Ok(Term::App(
2620                Box::new(Term::Global("SName".to_string())),
2621                Box::new(arg),
2622            ));
2623        }
2624
2625        // Check for "Variable" special syntax: Variable 0 → SVar 0
2626        if self.peek_keyword("Variable") {
2627            self.consume_keyword("Variable")?;
2628            self.skip_whitespace();
2629            let arg = self.parse_atom()?;
2630            return Ok(Term::App(
2631                Box::new(Term::Global("SVar".to_string())),
2632                Box::new(arg),
2633            ));
2634        }
2635
2636        // Check for "Apply" special syntax: Apply(f, x) → SApp f x
2637        if self.peek_keyword("Apply") {
2638            self.consume_keyword("Apply")?;
2639            self.skip_whitespace();
2640            if !self.try_consume("(") {
2641                return Err(ParseError::Expected {
2642                    expected: "'('".to_string(),
2643                    found: self.peek_word().unwrap_or("EOF".to_string()),
2644                });
2645            }
2646            self.skip_whitespace();
2647            let func_arg = self.parse_term()?;
2648            self.skip_whitespace();
2649            if !self.try_consume(",") {
2650                return Err(ParseError::Expected {
2651                    expected: "','".to_string(),
2652                    found: self.peek_word().unwrap_or("EOF".to_string()),
2653                });
2654            }
2655            self.skip_whitespace();
2656            let arg_arg = self.parse_term()?;
2657            self.skip_whitespace();
2658            if !self.try_consume(")") {
2659                return Err(ParseError::Expected {
2660                    expected: "')'".to_string(),
2661                    found: self.peek_word().unwrap_or("EOF".to_string()),
2662                });
2663            }
2664            return Ok(Term::App(
2665                Box::new(Term::App(
2666                    Box::new(Term::Global("SApp".to_string())),
2667                    Box::new(func_arg),
2668                )),
2669                Box::new(arg_arg),
2670            ));
2671        }
2672
2673        // Check for "there exists" special syntax
2674        if self.peek_keyword("there") {
2675            return self.parse_existential();
2676        }
2677
2678        // Parse identifier
2679        let ident = self.parse_ident()?;
2680
2681        // Check for "of" suffix (e.g., "Successor of x")
2682        self.skip_whitespace();
2683        if self.try_consume_keyword("of") {
2684            self.skip_whitespace();
2685            let arg = self.parse_atom()?;
2686            let func = if self.bound_vars.contains(&ident) {
2687                Term::Var(ident)
2688            } else {
2689                self.global(ident)?
2690            };
2691            return Ok(Term::App(Box::new(func), Box::new(arg)));
2692        }
2693
2694        // Return as Var if bound, Global otherwise
2695        if self.bound_vars.contains(&ident) || self.current_function.as_ref() == Some(&ident) {
2696            Ok(Term::Var(ident))
2697        } else {
2698            // Check for special sorts
2699            match ident.as_str() {
2700                "Prop" => Ok(Term::Sort(Universe::Prop)),
2701                "Type" => Ok(Term::Sort(Universe::Type(0))),
2702                _ => self.global(ident),
2703            }
2704        }
2705    }
2706
2707    /// Parse: there exists a [var]: [Type] such that [body]
2708    /// → Ex Type (fun var => body)
2709    fn parse_existential(&mut self) -> Result<Term, ParseError> {
2710        self.consume_keyword("there")?;
2711        self.skip_whitespace();
2712        self.consume_keyword("exists")?;
2713        self.skip_whitespace();
2714
2715        // Optional "a" or "an"
2716        let _ = self.try_consume_keyword("an") || self.try_consume_keyword("a");
2717        self.skip_whitespace();
2718
2719        // Parse variable name
2720        let var_name = self.parse_ident()?;
2721        self.skip_whitespace();
2722
2723        // Expect ":"
2724        if !self.try_consume(":") {
2725            return Err(ParseError::Expected {
2726                expected: "':'".to_string(),
2727                found: self.peek_word().unwrap_or("EOF".to_string()),
2728            });
2729        }
2730        self.skip_whitespace();
2731
2732        // Parse the type
2733        let var_type = self.parse_type()?;
2734        self.skip_whitespace();
2735
2736        // Expect "such that"
2737        if !self.try_consume_keyword("such") {
2738            return Err(ParseError::Expected {
2739                expected: "'such'".to_string(),
2740                found: self.peek_word().unwrap_or("EOF".to_string()),
2741            });
2742        }
2743        self.skip_whitespace();
2744        if !self.try_consume_keyword("that") {
2745            return Err(ParseError::Expected {
2746                expected: "'that'".to_string(),
2747                found: self.peek_word().unwrap_or("EOF".to_string()),
2748            });
2749        }
2750        self.skip_whitespace();
2751
2752        // The variable is in scope for the body, at its type, exactly as a clause's binders are.
2753        let was_bound = !self.bound_vars.insert(var_name.clone());
2754        self.locals.push((var_name.clone(), var_type.clone()));
2755        let body = self.parse_term();
2756        self.locals.pop();
2757        if !was_bound {
2758            self.bound_vars.remove(&var_name);
2759        }
2760        let body = body?;
2761
2762        // `Ex T (λ var : T. body)`: the binder is bound AT the type written for it, so the body is
2763        // read with `var` in scope at `T` — `concludes d` for a `d : Derivation` is then what it
2764        // says, and `Eq`'s carrier is solved from it.
2765        Ok(Term::App(
2766            Box::new(Term::App(
2767                Box::new(self.global("Ex")?),
2768                Box::new(var_type.clone()),
2769            )),
2770            Box::new(Term::Lambda {
2771                param: var_name,
2772                param_type: Box::new(var_type),
2773                body: Box::new(body),
2774            }),
2775        ))
2776    }
2777
2778    /// Parse a type expression (same as term for now)
2779    fn parse_type(&mut self) -> Result<Term, ParseError> {
2780        self.skip_whitespace();
2781
2782        // Handle "List of T" style
2783        let base = self.parse_ident()?;
2784
2785        self.skip_whitespace();
2786
2787        // Check for "of" (polymorphic application)
2788        if self.try_consume_keyword("of") {
2789            self.skip_whitespace();
2790            let arg = self.parse_type()?;
2791            return Ok(Term::App(Box::new(self.global(base)?), Box::new(arg)));
2792        }
2793
2794        // Check for special sorts
2795        match base.as_str() {
2796            "Prop" => Ok(Term::Sort(Universe::Prop)),
2797            "Type" => Ok(Term::Sort(Universe::Type(0))),
2798            _ => self.global(base),
2799        }
2800    }
2801
2802    /// Parse a number literal
2803    fn parse_number(&mut self) -> Result<Term, ParseError> {
2804        let mut num_str = String::new();
2805
2806        // Handle negative sign
2807        if self.peek_char('-') {
2808            num_str.push('-');
2809            self.advance();
2810        }
2811
2812        // Collect digits
2813        while let Some(c) = self.peek() {
2814            if c.is_ascii_digit() {
2815                num_str.push(c);
2816                self.advance();
2817            } else {
2818                break;
2819            }
2820        }
2821
2822        let value: i64 = num_str
2823            .parse()
2824            .map_err(|_| ParseError::InvalidNumber(num_str))?;
2825
2826        Ok(Term::Lit(Literal::Int(value)))
2827    }
2828
2829    /// Parse a string literal
2830    fn parse_string(&mut self) -> Result<Term, ParseError> {
2831        self.advance(); // consume opening '"'
2832
2833        let mut content = String::new();
2834        loop {
2835            match self.peek() {
2836                Some('"') => {
2837                    self.advance();
2838                    break;
2839                }
2840                Some('\\') => {
2841                    self.advance();
2842                    match self.peek() {
2843                        Some('n') => {
2844                            content.push('\n');
2845                            self.advance();
2846                        }
2847                        Some('t') => {
2848                            content.push('\t');
2849                            self.advance();
2850                        }
2851                        Some(c) => {
2852                            content.push(c);
2853                            self.advance();
2854                        }
2855                        None => return Err(ParseError::UnexpectedEof),
2856                    }
2857                }
2858                Some(c) => {
2859                    content.push(c);
2860                    self.advance();
2861                }
2862                None => return Err(ParseError::UnexpectedEof),
2863            }
2864        }
2865
2866        Ok(Term::Lit(Literal::Text(content)))
2867    }
2868
2869    // ============================================================
2870    // TERM TO SYNTAX REIFICATION
2871    // ============================================================
2872
2873    /// Convert a high-level Term to deeply-embedded Syntax representation.
2874    /// This is used by proof tactics like `ring.` that operate on Syntax.
2875    fn term_to_syntax(&self, term: &Term, bound_vars: &[String]) -> Term {
2876        match term {
2877            Term::Var(name) => {
2878                // Convert to SVar with de Bruijn index if bound, else SName
2879                if let Some(idx) = bound_vars.iter().rev().position(|n| n == name) {
2880                    Term::App(
2881                        Box::new(Term::Global("SVar".to_string())),
2882                        Box::new(Term::Lit(Literal::Int(idx as i64))),
2883                    )
2884                } else {
2885                    // Free variable - treat as SName
2886                    Term::App(
2887                        Box::new(Term::Global("SName".to_string())),
2888                        Box::new(Term::Lit(Literal::Text(name.clone()))),
2889                    )
2890                }
2891            }
2892            Term::Global(name) => {
2893                // Global names become SName
2894                Term::App(
2895                    Box::new(Term::Global("SName".to_string())),
2896                    Box::new(Term::Lit(Literal::Text(name.clone()))),
2897                )
2898            }
2899            Term::Const { name, .. } => {
2900                // A universe-polymorphic reference reifies by its name (reflection never
2901                // sees level arguments).
2902                Term::App(
2903                    Box::new(Term::Global("SName".to_string())),
2904                    Box::new(Term::Lit(Literal::Text(name.clone()))),
2905                )
2906            }
2907            Term::Lit(Literal::Int(n)) => {
2908                // Integer literals become SLit
2909                Term::App(
2910                    Box::new(Term::Global("SLit".to_string())),
2911                    Box::new(Term::Lit(Literal::Int(*n))),
2912                )
2913            }
2914            Term::Lit(Literal::Float(_f)) => {
2915                // Float literals - treat as error for ring (ring doesn't handle floats)
2916                Term::App(
2917                    Box::new(Term::Global("SName".to_string())),
2918                    Box::new(Term::Lit(Literal::Text("Error_Float".to_string()))),
2919                )
2920            }
2921            Term::Lit(Literal::BigInt(_)) => {
2922                // BigInt literals do not fit the ring-syntax layer's machine-int SLit.
2923                Term::App(
2924                    Box::new(Term::Global("SName".to_string())),
2925                    Box::new(Term::Lit(Literal::Text("Error_BigInt".to_string()))),
2926                )
2927            }
2928            Term::Lit(Literal::Nat(_)) => {
2929                // Nat literals do not fit the ring-syntax layer's machine-int SLit.
2930                Term::App(
2931                    Box::new(Term::Global("SName".to_string())),
2932                    Box::new(Term::Lit(Literal::Text("Error_Nat".to_string()))),
2933                )
2934            }
2935            Term::Lit(Literal::Duration(_d)) => {
2936                // Duration literals - treat as error for ring (ring doesn't handle durations)
2937                Term::App(
2938                    Box::new(Term::Global("SName".to_string())),
2939                    Box::new(Term::Lit(Literal::Text("Error_Duration".to_string()))),
2940                )
2941            }
2942            Term::Lit(Literal::Date(_d)) => {
2943                // Date literals - treat as error for ring (ring doesn't handle dates)
2944                Term::App(
2945                    Box::new(Term::Global("SName".to_string())),
2946                    Box::new(Term::Lit(Literal::Text("Error_Date".to_string()))),
2947                )
2948            }
2949            Term::Lit(Literal::Moment(_m)) => {
2950                // Moment literals - treat as error for ring (ring doesn't handle moments)
2951                Term::App(
2952                    Box::new(Term::Global("SName".to_string())),
2953                    Box::new(Term::Lit(Literal::Text("Error_Moment".to_string()))),
2954                )
2955            }
2956            Term::Lit(Literal::Text(s)) => {
2957                // Text literals become SLit (wrapped in SName for now)
2958                Term::App(
2959                    Box::new(Term::Global("SName".to_string())),
2960                    Box::new(Term::Lit(Literal::Text(s.clone()))),
2961                )
2962            }
2963            Term::App(f, x) => {
2964                // Applications become SApp
2965                let f_syn = self.term_to_syntax(f, bound_vars);
2966                let x_syn = self.term_to_syntax(x, bound_vars);
2967                Term::App(
2968                    Box::new(Term::App(
2969                        Box::new(Term::Global("SApp".to_string())),
2970                        Box::new(f_syn),
2971                    )),
2972                    Box::new(x_syn),
2973                )
2974            }
2975            Term::Lambda {
2976                param,
2977                param_type,
2978                body,
2979            } => {
2980                // Lambdas become SLam (if we have that constructor)
2981                let ty_syn = self.term_to_syntax(param_type, bound_vars);
2982                let mut new_bound = bound_vars.to_vec();
2983                new_bound.push(param.clone());
2984                let body_syn = self.term_to_syntax(body, &new_bound);
2985                Term::App(
2986                    Box::new(Term::App(
2987                        Box::new(Term::Global("SLam".to_string())),
2988                        Box::new(ty_syn),
2989                    )),
2990                    Box::new(body_syn),
2991                )
2992            }
2993            Term::Pi {
2994                param,
2995                param_type,
2996                body_type,
2997            } => {
2998                let ty_syn = self.term_to_syntax(param_type, bound_vars);
2999                let mut new_bound = bound_vars.to_vec();
3000                new_bound.push(param.clone());
3001                let body_syn = self.term_to_syntax(body_type, &new_bound);
3002                if param == "_" {
3003                    // A non-dependent arrow — the `implies` desugaring — reifies as `SPi`.
3004                    Term::App(
3005                        Box::new(Term::App(
3006                            Box::new(Term::Global("SPi".to_string())),
3007                            Box::new(ty_syn),
3008                        )),
3009                        Box::new(body_syn),
3010                    )
3011                } else {
3012                    // A NAMED binder is a quantifier, and reifies as the `Forall` the elimination
3013                    // rules speak: `SApp (SApp (SName "Forall") T) (SLam T body)`. Reifying it as
3014                    // `SPi` would put the proposition in a shape no conclusion can ever equal.
3015                    let motive = Term::App(
3016                        Box::new(Term::App(
3017                            Box::new(Term::Global("SLam".to_string())),
3018                            Box::new(ty_syn.clone()),
3019                        )),
3020                        Box::new(body_syn),
3021                    );
3022                    forall_syntax(&ty_syn, &motive)
3023                }
3024            }
3025            Term::Sort(Universe::Prop) => {
3026                // Prop sort becomes SSort UProp
3027                Term::App(
3028                    Box::new(Term::Global("SSort".to_string())),
3029                    Box::new(Term::Global("UProp".to_string())),
3030                )
3031            }
3032            Term::Sort(Universe::Type(n)) => {
3033                // Type sort becomes SSort (UType n)
3034                Term::App(
3035                    Box::new(Term::Global("SSort".to_string())),
3036                    Box::new(Term::App(
3037                        Box::new(Term::Global("UType".to_string())),
3038                        Box::new(Term::Lit(Literal::Int(*n as i64))),
3039                    )),
3040                )
3041            }
3042            Term::Sort(_) => {
3043                // Universe-polymorphic levels (Var/Succ/Max) don't arise in ring proofs;
3044                // reify conservatively as an opaque SSort so the conversion stays total.
3045                Term::App(
3046                    Box::new(Term::Global("SSort".to_string())),
3047                    Box::new(Term::Global("UPoly".to_string())),
3048                )
3049            }
3050            Term::Hole => {
3051                // Holes default to Int type for ring proofs
3052                Term::App(
3053                    Box::new(Term::Global("SName".to_string())),
3054                    Box::new(Term::Lit(Literal::Text("Int".to_string()))),
3055                )
3056            }
3057            Term::Match { .. } | Term::Fix { .. } | Term::MutualFix { .. } | Term::Let { .. } => {
3058                // Match, Fix, MutualFix, and Let are complex - return error marker
3059                Term::App(
3060                    Box::new(Term::Global("SName".to_string())),
3061                    Box::new(Term::Lit(Literal::Text("Error".to_string()))),
3062                )
3063            }
3064            // The embedded syntax is kernel meaning; an annotation is not part of it.
3065            Term::Annotated { term, .. } => self.term_to_syntax(term, bound_vars),
3066        }
3067    }
3068
3069    // ============================================================
3070    // SELF-REFERENCE DETECTION
3071    // ============================================================
3072
3073    /// Check if the function name appears in the term (for implicit fixpoint)
3074    fn contains_self_reference(&self, name: &str, term: &Term) -> bool {
3075        match term {
3076            Term::Var(v) => v == name,
3077            Term::Global(_) => false,
3078            Term::Const { .. } => false,
3079            Term::Sort(_) => false,
3080            Term::Lit(_) => false,
3081            Term::Pi {
3082                param_type,
3083                body_type,
3084                ..
3085            } => {
3086                self.contains_self_reference(name, param_type)
3087                    || self.contains_self_reference(name, body_type)
3088            }
3089            Term::Lambda {
3090                param_type, body, ..
3091            } => {
3092                self.contains_self_reference(name, param_type)
3093                    || self.contains_self_reference(name, body)
3094            }
3095            Term::App(f, a) => {
3096                self.contains_self_reference(name, f) || self.contains_self_reference(name, a)
3097            }
3098            Term::Match {
3099                discriminant,
3100                motive,
3101                cases,
3102            } => {
3103                self.contains_self_reference(name, discriminant)
3104                    || self.contains_self_reference(name, motive)
3105                    || cases.iter().any(|c| self.contains_self_reference(name, c))
3106            }
3107            Term::Fix { body, .. } => self.contains_self_reference(name, body),
3108            Term::MutualFix { defs, .. } => defs
3109                .iter()
3110                .any(|(_, b)| self.contains_self_reference(name, b)),
3111            Term::Let {
3112                ty, value, body, ..
3113            } => {
3114                self.contains_self_reference(name, ty)
3115                    || self.contains_self_reference(name, value)
3116                    || self.contains_self_reference(name, body)
3117            }
3118            Term::Hole => false, // Holes never contain self-references
3119            Term::Annotated { term, .. } => self.contains_self_reference(name, term),
3120        }
3121    }
3122
3123    // ============================================================
3124    // LOW-LEVEL UTILITIES
3125    // ============================================================
3126
3127    fn skip_whitespace(&mut self) {
3128        while let Some(c) = self.peek() {
3129            if c == ' ' || c == '\t' {
3130                self.advance();
3131            } else {
3132                break;
3133            }
3134        }
3135    }
3136
3137    /// The column the cursor stands at when only indentation precedes it on its line — when what
3138    /// follows BEGINS a line — and `None` when something else is written before it on that line.
3139    fn line_start_column(&self) -> Option<usize> {
3140        let line_start = self.input[..self.pos].rfind('\n').map_or(0, |at| at + 1);
3141        let indent = &self.input[line_start..self.pos];
3142        indent
3143            .chars()
3144            .all(|c| c == ' ' || c == '\t')
3145            .then_some(indent.len())
3146    }
3147
3148    /// The indentation of the line the cursor stands on: the width of the whitespace that opens it.
3149    fn line_indent(&self) -> usize {
3150        let line_start = self.input[..self.pos].rfind('\n').map_or(0, |at| at + 1);
3151        self.input[line_start..]
3152            .chars()
3153            .take_while(|c| *c == ' ' || *c == '\t')
3154            .count()
3155    }
3156
3157    fn skip_whitespace_and_newlines(&mut self) {
3158        while let Some(c) = self.peek() {
3159            if c.is_whitespace() {
3160                self.advance();
3161            } else {
3162                break;
3163            }
3164        }
3165    }
3166
3167    fn peek(&self) -> Option<char> {
3168        self.input[self.pos..].chars().next()
3169    }
3170
3171    fn peek_char(&self, c: char) -> bool {
3172        self.peek() == Some(c)
3173    }
3174
3175    fn peek_keyword(&self, keyword: &str) -> bool {
3176        if !self.input[self.pos..].starts_with(keyword) {
3177            return false;
3178        }
3179        let after = self.pos + keyword.len();
3180        if after >= self.input.len() {
3181            return true;
3182        }
3183        let next_char = self.input[after..].chars().next();
3184        !next_char
3185            .map(|c| c.is_alphanumeric() || c == '_')
3186            .unwrap_or(false)
3187    }
3188
3189    fn peek_word(&self) -> Option<String> {
3190        let start = self.pos;
3191        let mut end = start;
3192        for c in self.input[start..].chars() {
3193            if c.is_alphanumeric() || c == '_' {
3194                end += c.len_utf8();
3195            } else {
3196                break;
3197            }
3198        }
3199        if end > start {
3200            Some(self.input[start..end].to_string())
3201        } else {
3202            self.peek().map(|c| c.to_string())
3203        }
3204    }
3205
3206    fn advance(&mut self) {
3207        if let Some(c) = self.peek() {
3208            self.pos += c.len_utf8();
3209        }
3210    }
3211
3212    fn at_end(&self) -> bool {
3213        self.pos >= self.input.len()
3214    }
3215
3216    fn try_consume(&mut self, s: &str) -> bool {
3217        if self.input[self.pos..].starts_with(s) {
3218            self.pos += s.len();
3219            true
3220        } else {
3221            false
3222        }
3223    }
3224
3225    fn try_consume_keyword(&mut self, keyword: &str) -> bool {
3226        if self.peek_keyword(keyword) {
3227            self.pos += keyword.len();
3228            true
3229        } else {
3230            false
3231        }
3232    }
3233
3234    fn consume_keyword(&mut self, keyword: &str) -> Result<(), ParseError> {
3235        if self.try_consume_keyword(keyword) {
3236            Ok(())
3237        } else {
3238            Err(ParseError::Expected {
3239                expected: format!("'{}'", keyword),
3240                found: self.peek_word().unwrap_or("EOF".to_string()),
3241            })
3242        }
3243    }
3244
3245    /// Read a name a DECLARATION will be KEYED AT.
3246    ///
3247    /// [`Self::parse_ident`] reads a MENTION: one component, whatever `scan_name` accepts. A
3248    /// declaration is a different obligation — the kernel context is a map of flat keys, so the
3249    /// name has to be one a term can spell back, and its key has to read back as itself. Both
3250    /// are [`super::declaration_name`], the one function every declaration door reads.
3251    ///
3252    /// Without this the literate surface could mint a WRITE-ONLY global by two routes the
3253    /// vernacular door already closes: a word the term door reads as SYNTAX
3254    /// (`## To match (n: Nat) -> Nat:` keys the context at `match`, which no `Check` can name)
3255    /// and a quoted component holding a `.` (`## Theorem: «a.b»` keys at `a.b`, which reads back
3256    /// as the two-component name `a.b`, so the two would share one key).
3257    fn parse_declaration_name(&mut self) -> Result<String, ParseError> {
3258        self.skip_whitespace();
3259        let start = self.pos;
3260        match super::surface::Name::scan(&self.input[start..]) {
3261            Some((_, len)) => {
3262                let name = super::declaration_name(&self.input[start..start + len])?;
3263                self.pos = start + len;
3264                Ok(name.key())
3265            }
3266            None => match self.peek() {
3267                Some(c) => Err(ParseError::Expected {
3268                    expected: "identifier".to_string(),
3269                    found: c.to_string(),
3270                }),
3271                None => Err(ParseError::UnexpectedEof),
3272            },
3273        }
3274    }
3275
3276    /// One name, read through the SHARED grammar (`term_parser::scan_name`) so a theorem, a
3277    /// binder and a `Check` all spell a name the same way.
3278    fn parse_ident(&mut self) -> Result<String, ParseError> {
3279        self.skip_whitespace();
3280        match super::term_parser::scan_name(&self.input[self.pos..]) {
3281            Some((name, len)) => {
3282                self.pos += len;
3283                Ok(name)
3284            }
3285            None => match self.peek() {
3286                Some(c) => Err(ParseError::Expected {
3287                    expected: "identifier".to_string(),
3288                    found: c.to_string(),
3289                }),
3290                None => Err(ParseError::UnexpectedEof),
3291            },
3292        }
3293    }
3294
3295    // ============================================================
3296    // INFIX OPERATOR HELPERS
3297    // ============================================================
3298
3299    /// Check if current position starts a negative number (- followed by digit)
3300    fn peek_negative_number(&self) -> bool {
3301        if !self.peek_char('-') {
3302            return false;
3303        }
3304        self.input
3305            .get(self.pos + 1..)
3306            .and_then(|s| s.chars().next())
3307            .map(|c| c.is_ascii_digit())
3308            .unwrap_or(false)
3309    }
3310
3311    /// Check if current position starts an arrow (->)
3312    fn peek_arrow(&self) -> bool {
3313        self.input[self.pos..].starts_with("->")
3314    }
3315
3316    /// Check if current position has a comparison operator
3317    fn peek_comparison_operator(&self) -> bool {
3318        let rest = &self.input[self.pos..];
3319        rest.starts_with("<=")
3320            || rest.starts_with(">=")
3321            || rest.starts_with("≤")
3322            || rest.starts_with("≥")
3323            || rest.starts_with('<')
3324            || rest.starts_with('>')
3325    }
3326}
3327
3328// ============================================================
3329// UNIT TESTS
3330// ============================================================
3331
3332#[cfg(test)]
3333#[path = "../../../logicaffeine_tests/unit/logicaffeine_kernel/interface/literate_parser/tests.rs"]
3334mod tests;