Skip to main content

logicaffeine_kernel/interface/
term_parser.rs

1//! Parser for Kernel Term syntax.
2//!
3//! Parses the following grammar:
4//! ```text
5//! term    ::= lambda | forall | fix | match | let | group | instance | arrow
6//! arrow   ::= app ("->" term)?
7//! app     ::= atom+ ".."?
8//! atom    ::= binder | named | "(" term ")" | sort | hole | "@" ident | ident
9//! binder  ::= "(" ident+ ":" term (":=" default)? ")" "->"? term
10//! group   ::= ("{" | "⦃") ident+ ":" term (":=" default)? ("}" | "⦄") "->"? term
11//! instance::= "[" (ident+ ":")? term "]" "->"? term
12//! named   ::= "(" ident ":=" term ")"
13//! default ::= term | "by" ident
14//! sort    ::= "Prop" | "SProp" | "Type" | "Type" digit+ | "Sort" level_atom
15//! hole    ::= "_"
16//! lambda  ::= "fun" binders (":" term)? "=>" term
17//! forall  ::= "forall" binders (":" term)? "," term
18//! binders ::= (ident | bgroup)+
19//! bgroup  ::= "(" ident+ (":" term)? ")" | "{" ident+ (":" term)? "}"
20//!           | "⦃" ident+ (":" term)? "⦄" | "[" (ident+ ":")? term "]"
21//! fix     ::= "fix" ident "=>" term ("with" ident "=>" term)* ("return" ident)?
22//! let     ::= "let" ident (":" term)? ":=" term "in" term
23//!           | "let" ident ":" term ":=" term ";" term
24//! match   ::= "match" app ("return" app)? "with" ("|" pattern "=>" term)* "end"?
25//!           | "match" app "return" app "with" term ("|" term)* "end"
26//! atom    ::= … | atom "." (ident | "«name»" | digit+) | name ".{" (level ("," level)*)? "}"
27//! level   ::= level_atom ("+" digit+)*
28//! level_atom ::= digit+ | ident | "«name»" | "max" level_atom level_atom
29//!              | "imax" level_atom level_atom | "(" level ")"
30//! literal ::= "-"? digit+ ("n" | unit)? | "-"? digit+ ("." digit+)? (("e"|"E") ("+"|"-")? digit+)? "f64"
31//!           | "0x" hex{16} "f64" | "-"? digit{4,} "-" digit{2} "-" digit{2} time?
32//!           | '"' char* '"'
33//! time    ::= "T" digit{2} ":" digit{2} ":" digit{2} ("." digit{1,9})? "Z"
34//! unit    ::= "ns" | "us" | "μs" | "ms" | "s" | "sec" | "min" | "h" | "hr"
35//! ```
36//!
37//! # The kernel's own terms, spelled exactly
38//!
39//! Every production above that the Lean importer's terms need reads STRUCTURALLY, so that
40//! `printer::print_term` can be its exact inverse:
41//!
42//! * a LEVEL is never normalised — `u+1` is `Succ(Var u)`, the numeral `1` is `Type 0`, `0` is
43//!   `Prop`, and `max`/`imax` are the kernel's own two binary operators;
44//! * `name.{ℓ, …}` is `Term::Const` — the explicit level arguments of a universe-polymorphic
45//!   constant; a qualified name before `.{` is ONE constant, never a projection chain;
46//! * a positional `match … return M with c₀ | c₁ end` (no leading bar) is the kernel's own
47//!   `Term::Match`: one case per constructor, in registration order, read with no context at all;
48//! * `fix f => b with g => c return g` is `Term::MutualFix`, every name bound in every body;
49//! * `let x : T := v; b` is the kernel's `Term::Let`, its binder KEPT — where `let … in` substitutes
50//!   and keeps only the ascription;
51//! * every `Literal` has one spelling: `5n` is a `Nat`, `5` an `Int`, `1.5f64` and `0x…f64` a `Float`,
52//!   `5s` a `Duration`, `2026-05-20` a `Date`, `2026-05-20T10:00:00Z` a `Moment`;
53//! * a `«quoted»` name is always a NAME — `«Prop»` is a global, never the sort, and `«fun»` binds.
54//!
55//! # The argument-passing surface, and where it is carried
56//!
57//! Five families of production carry information the kernel's `Term` has no field for. Each rides
58//! on a
59//! RESERVED MARKER global -- the idiom `elaborate::ANON_CTOR_MARKER` / `DOT_MARKER` already
60//! established -- so no `Term` variant is added and no signature in the pipeline grows to hold
61//! them. `Term::Pi` in particular stays at three fields; it has hundreds of construction sites.
62//!
63//! | surface | emitted | consumer |
64//! |---|---|---|
65//! | `f (x := e)` | `f (MARK_named x e)` | the elaborator, resolving into declaration order |
66//! | `@f a b` | `MARK_explicit f a b` | the elaborator, suppressing implicit insertion |
67//! | `(m : T := e) -> B` | `Pi(m : MARK_default T e). B` | the declaration door, as a default |
68//! | `(h : P := by tac) -> B` | `Pi(h : MARK_autoparam P tac). B` | the elaborator, per call site |
69//! | `<a, ..>` / `f ..` | `MARK_anon a MARK_ellipsis` / `f MARK_ellipsis` | the elaborator |
70//! | `{x : T}` / `⦃x : T⦄` / `[C x]` | `Pi(x : MARK_kind T). B` | read off as [`BinderKind`] |
71//! | `fun {A} x => …` / `forall {A}, …` | `Lambda(A : MARK_kind _). …` | read off as [`BinderKind`] |
72//!
73//! The BINDER-KIND markers are the only ones that never leave this module: [`TermParser::parse`]
74//! and every wrapper strips them and hands back the pure kernel `Pi`, after reading the telescope
75//! into a [`BinderKind`] vector. A kind is a POSITION in the telescope, not a prefix count, which
76//! is why it cannot ride on the `implicit_count` number the parser used to return: that number
77//! could not say that the implicit stood third, and it counted a `{...}` written inside a
78//! PARAMETER'S OWN TYPE as a parameter of the declaration.
79//!
80//! A marker must NEVER reach a kernel term. [`TermParser::as_named_arg`],
81//! [`TermParser::as_default_param`], [`TermParser::as_auto_param`], [`TermParser::is_ellipsis`],
82//! [`TermParser::strip_binder_markers`] and [`TermParser::substitute_param_ref`] are the whole
83//! consumer interface, and [`scan_name`] refuses a guillemet name containing the marker brackets
84//! so that no user global can spell one.
85//!
86//! # The declaration door
87//!
88//! A declaration is where every one of these has to be RECORDED, and reading them back off a
89//! marked type is the part each consumer would otherwise reinvent. [`TermParser::read_declaration`]
90//! is the one call: it hands back the marker-free [`DeclarationSurface::kernel_type`] the context
91//! is keyed at, plus one [`BinderSurface`] per parameter carrying its kind, its default and its
92//! auto-param tactic. [`TermParser::name_anonymous_binders`] then recovers the parameter NAMES
93//! from the definition's body -- in LOGOS `A -> B` names nothing, so for a non-dependent signature
94//! the body's lambda telescope is the only place those names exist -- and
95//! [`TermParser::inline_default`] closes a default over the arguments already supplied.
96
97use super::error::ParseError;
98use crate::elaborate::ParamKind;
99use crate::{Literal, Term, Universe};
100use std::collections::{HashMap, HashSet};
101
102use super::surface::Surface;
103
104/// THE name grammar of the vernacular — the ONE both doors read.
105///
106/// A name is either a plain identifier (alphabetic or `_`, then alphanumerics, `_` and the PRIME
107/// `'` — `h`, `h'`, `h''`, and Unicode throughout: `\u{3b1}`, `\u{393}`, `x\u{2081}`) or a
108/// `\u{ab}guillemet name\u{bb}`, whose contents are taken verbatim so a name may hold spaces and
109/// punctuation. It returns the KEY and the bytes consumed.
110///
111/// ★ ONE GRAMMAR, BOTH DOORS. `Definition <name> : …` used to take its name as a raw text slice up
112/// to the first `:` while the term lexer demanded alphanumerics, so `Definition h' : Nat := Zero.`
113/// succeeded and keyed the context at `h'` while `Check h'.` died in the lexer. Those were globals
114/// that could be declared and never referenced — write-only names. The invariant this function
115/// exists to enforce is: every name the declaration door accepts, a term can spell.
116pub(super) fn scan_name(input: &str) -> Option<(String, usize)> {
117    let mut chars = input.char_indices();
118    match chars.next() {
119        Some((_, '\u{ab}')) => {
120            let open = '\u{ab}'.len_utf8();
121            let end = input[open..].find('\u{bb}')?;
122            let name = &input[open..open + end];
123            // A GUILLEMET NAME MAY NOT SPELL A RESERVED MARKER. Every surface-sugar marker is
124            // documented as collision-proof because "the identifier lexer cannot produce
125            // \u{27e8}/\u{27e9}" -- but this verbatim form could, so `Definition \u{ab}\u{27e8}anon\u{27e9}\u{bb} : Nat := Zero.`
126            // declared a global whose every later mention was then read as an anonymous
127            // constructor: a write-only name again, by a different route. Excluding the two
128            // bracket characters outright (exactly as `\u{ab}` is already excluded) makes the
129            // stated invariant true by construction, and true for every marker added later.
130            if name.is_empty()
131                || name.contains('\u{ab}')
132                || name.contains('\u{27e8}')
133                || name.contains('\u{27e9}')
134            {
135                return None;
136            }
137            Some((name.to_string(), open + end + '\u{bb}'.len_utf8()))
138        }
139        Some((_, c)) if c.is_alphabetic() || c == '_' => {
140            let mut end = c.len_utf8();
141            for (i, c) in chars {
142                if c.is_alphanumeric() || c == '_' || c == '\'' {
143                    end = i + c.len_utf8();
144                } else {
145                    break;
146                }
147            }
148            Some((input[..end].to_string(), end))
149        }
150        _ => None,
151    }
152}
153
154/// [`scan_name`], also reporting whether the name was written in GUILLEMETS.
155///
156/// A quoted name is always a NAME: `«Prop»` is a global and `«fun»` a binder, where the same
157/// letters unquoted are a sort and a keyword. That is what makes the guillemets an ESCAPE rather
158/// than a second spelling of the same token — and it is the only way a printer can spell a constant
159/// or a binder whose name happens to be a word this grammar reads as syntax.
160pub(super) fn scan_spelled_name(input: &str) -> Option<(String, usize, bool)> {
161    scan_name(input).map(|(name, len)| (name, len, input.starts_with('\u{ab}')))
162}
163
164/// The words the term grammar reserves — never a name when written bare. `Prop` and `Type` are
165/// deliberately absent: they are SORTS (see [`is_sort_word`]).
166pub(super) fn is_reserved_word(name: &str) -> bool {
167    matches!(
168        name,
169        "fun" | "forall" | "fix" | "match" | "let" | "in" | "with" | "return" | "end" | "by"
170    )
171}
172
173/// Is `word`, written UNQUOTED, read as a SORT rather than a name? `Prop`, `SProp`, `Type`, `Sort`
174/// and every `TypeN` whose suffix is all digits.
175pub(super) fn is_sort_word(word: &str) -> bool {
176    matches!(word, "Prop" | "SProp" | "Type" | "Sort")
177        || word
178            .strip_prefix("Type")
179            .is_some_and(|n| !n.is_empty() && n.chars().all(|c| c.is_ascii_digit()))
180}
181
182/// The deepest text the term door reads: four times the kernel's own term-depth ceiling, which
183/// leaves room for every bracket and binder a printed or written term of admissible depth carries.
184pub(super) const MAX_SYNTACTIC_DEPTH: usize = 4 * crate::type_checker::MAX_TERM_DEPTH;
185
186/// Below this nesting a parse runs on the caller's own stack.
187const INLINE_SYNTACTIC_DEPTH: usize = 48;
188
189thread_local! {
190    /// The stack this thread was given by [`on_stack_for`], or 0 when it was not.
191    static SIZED_FOR: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
192}
193
194/// An upper bound on how deeply reading `input` can recurse.
195///
196/// The reader recurses once per open bracket and once per construct that extends to the right —
197/// a binder keyword (`fun`, `forall`, `let`, `fix`, `match`) or an arrow — and such a construct
198/// stays open until the bracket it stands in closes. So the depth at any point is, over the
199/// enclosing brackets, one for each bracket plus one for each such construct already seen inside
200/// it; this returns the largest. Strings and «quoted names» are skipped, as the reader skips them.
201pub(super) fn syntactic_depth(input: &str) -> usize {
202    let bytes = input.as_bytes();
203    let mut opened: Vec<usize> = vec![0];
204    let (mut depth, mut deepest) = (0usize, 0usize);
205    let mut chars = input.char_indices().peekable();
206    let word_at = |i: usize, w: &str| {
207        input[i..].starts_with(w)
208            && input[..i]
209                .chars()
210                .next_back()
211                .is_none_or(|c| !(c.is_alphanumeric() || c == '_' || c == '\''))
212            && input[i + w.len()..]
213                .chars()
214                .next()
215                .is_none_or(|c| !(c.is_alphanumeric() || c == '_' || c == '\''))
216    };
217    while let Some((i, c)) = chars.next() {
218        match c {
219            '"' => {
220                let mut escaped = false;
221                for (_, c) in chars.by_ref() {
222                    if escaped {
223                        escaped = false;
224                    } else if c == '\\' {
225                        escaped = true;
226                    } else if c == '"' {
227                        break;
228                    }
229                }
230            }
231            '\u{ab}' => {
232                for (_, c) in chars.by_ref() {
233                    if c == '\u{bb}' {
234                        break;
235                    }
236                }
237            }
238            '(' | '{' | '[' | '\u{27e8}' | '\u{2983}' => {
239                opened.push(0);
240                depth += 1;
241            }
242            ')' | '}' | ']' | '\u{27e9}' | '\u{2984}' => {
243                if opened.len() > 1 {
244                    let inner = opened.pop().expect("more than the root");
245                    depth = depth.saturating_sub(1 + inner);
246                }
247            }
248            '-' if bytes.get(i + 1) == Some(&b'>') => {
249                *opened.last_mut().expect("the root") += 1;
250                depth += 1;
251            }
252            c if c.is_alphabetic()
253                && ["fun", "forall", "let", "fix", "match"]
254                    .iter()
255                    .any(|w| word_at(i, w)) =>
256            {
257                *opened.last_mut().expect("the root") += 1;
258                depth += 1;
259            }
260            _ => {}
261        }
262        deepest = deepest.max(depth);
263    }
264    deepest
265}
266
267/// Run `f` on a stack sized for text nested `depth` deep — the caller's own when it is shallow or
268/// already big enough, a scoped thread's otherwise. The kernel's own per-rung budget is used, which
269/// is generous for the reader.
270///
271/// wasm32 has no threads to scope one on; the browser client links a stack already big enough for
272/// the kernel's own worst case (see `term_store::run_on_stack`), so `f` runs inline there and the
273/// sizing is just recorded for any nested call on the same (only) thread.
274pub(super) fn on_stack_for<R: Send>(depth: usize, f: impl FnOnce() -> R + Send) -> R {
275    let bytes = crate::term_store::stack_bytes_for_depth(depth);
276    if depth <= INLINE_SYNTACTIC_DEPTH || SIZED_FOR.with(|s| s.get()) >= bytes {
277        return f();
278    }
279    #[cfg(target_arch = "wasm32")]
280    {
281        SIZED_FOR.with(|s| s.set(bytes));
282        f()
283    }
284    #[cfg(not(target_arch = "wasm32"))]
285    std::thread::scope(|scope| {
286        std::thread::Builder::new()
287            .name("logos-deep-surface".into())
288            .stack_size(bytes)
289            .spawn_scoped(scope, move || {
290                SIZED_FOR.with(|s| s.set(bytes));
291                f()
292            })
293            .expect("reserve a stack for a deep term")
294            .join()
295            .unwrap_or_else(|panic| std::panic::resume_unwind(panic))
296    })
297}
298
299/// The largest `k` a level may add in one `ℓ+k`. A level is a chain of `Succ` nodes, so an
300/// unbounded `k` would let a few bytes of source allocate gigabytes; no level any real development
301/// writes comes near this, and a numeral names every `Type n` without a chain at all.
302pub(super) const MAX_LEVEL_OFFSET: u64 = 1 << 16;
303
304/// Days since the Unix epoch of the proleptic-Gregorian date `y-m-d` — Howard Hinnant's
305/// `days_from_civil`, the exact inverse of the calendar conversion `Literal::Date` displays with.
306pub(super) fn days_from_civil(y: i64, m: u32, d: u32) -> i64 {
307    let y = if m <= 2 { y - 1 } else { y };
308    let era = (if y >= 0 { y } else { y - 399 }) / 400;
309    let yoe = y - era * 400;
310    let mp = (m as i64 + 9) % 12;
311    let doy = (153 * mp + 2) / 5 + d as i64 - 1;
312    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
313    era * 146_097 + doe - 719_468
314}
315
316/// The proleptic-Gregorian date of a day count — Hinnant's `civil_from_days`, over `i64`.
317pub(super) fn civil_from_days(days: i64) -> (i64, u32, u32) {
318    let z = days + 719_468;
319    let era = (if z >= 0 { z } else { z - 146_096 }) / 146_097;
320    let doe = z - era * 146_097;
321    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
322    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
323    let mp = (5 * doy + 2) / 153;
324    let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
325    let m = (if mp < 10 { mp + 3 } else { mp - 9 }) as u32;
326    (yoe + era * 400 + if m <= 2 { 1 } else { 0 }, m, d)
327}
328
329/// How many nanoseconds one of each duration UNIT holds. A numeral's suffix is read WHOLE and looked
330/// up here exactly, so `min` can never be misread as a shorter unit. The imperative language's own
331/// suffix table, so a duration reads the same in both languages.
332pub(super) const DURATION_UNITS: &[(&str, i64)] = &[
333    ("min", 60_000_000_000),
334    ("sec", 1_000_000_000),
335    ("ns", 1),
336    ("us", 1_000),
337    ("\u{3bc}s", 1_000),
338    ("ms", 1_000_000),
339    ("hr", 3_600_000_000_000),
340    ("s", 1_000_000_000),
341    ("h", 3_600_000_000_000),
342];
343
344/// How a parameter is SUPPLIED at a call site -- Lean's four binder kinds.
345///
346/// The kernel has exactly one `Pi`, so a binder kind is not a typing distinction: `{A : Type} -> A`
347/// and `(A : Type) -> A` and `⦃A : Type⦄ -> A` denote the same type and the same terms inhabit
348/// it. What differs is what the ELABORATOR does at an application, and that is why the kind must
349/// travel out of the parser beside the term rather than inside it.
350#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
351pub enum BinderKind {
352    /// `(x : T)` -- the caller writes the argument.
353    Explicit,
354    /// `{x : T}` -- inserted eagerly, solved by unification.
355    Implicit,
356    /// `⦃x : T⦄` (Lean's strict-implicit brackets) -- inserted only when a LATER explicit
357    /// argument is actually supplied, so an unapplied `nilOf` stays the polymorphic function
358    /// rather than becoming an application with an unsolvable metavariable in it.
359    StrictImplicit,
360    /// `[C x]` -- resolved from the instance database, after the explicit arguments have pinned
361    /// the class's type variables.
362    Instance,
363}
364
365impl BinderKind {
366    /// The elaborator's [`ParamKind`] for this binder -- now a BIJECTION, one variant each.
367    ///
368    /// ★ THE LOSSY STEP IS GONE, AND THIS WAS THE ONE LINE. `ParamKind` had three variants and
369    /// this enum four, so a strict implicit could only be collapsed onto `Implicit`. The collapse
370    /// was made HERE, in one named function, rather than spelled at each hand-over site, against
371    /// the day `ParamKind` grew its fourth variant. It has -- Lean's `BinderInfo` has exactly four
372    /// constructors (`Lean/Expr.lean:69`) and `⦃⦄` earns its own because `App.lean:726`'s
373    /// `processStrictImplicitArg` gives it a rule no other kind has: insert only
374    /// `if (← hasArgsToProcess)`, otherwise `finalize`. `ParamKind::StrictImplicit` now exists and
375    /// `elaborate_app_against` implements precisely that rule, so `⦃α⦄` reaches the elaborator as
376    /// itself and this function is a BIJECTION with no information left to lose.
377    /// `lean_conformance_t05_elaboration::a_strict_implicit_is_not_instantiated_until_an_explicit_argument_follows`
378    /// is what pins the behaviour end to end.
379    ///
380    /// The legacy `implicit_count` model still STOPS at a strict implicit
381    /// (`count_implicits`): a count can only describe an
382    /// unconditional prefix, and over-inserting there emits a metavariable nothing can solve.
383    pub fn as_param_kind(self) -> ParamKind {
384        match self {
385            BinderKind::Explicit => ParamKind::Explicit,
386            BinderKind::Implicit => ParamKind::Implicit,
387            BinderKind::StrictImplicit => ParamKind::StrictImplicit,
388            BinderKind::Instance => ParamKind::Instance,
389        }
390    }
391
392    /// The binder kind for an elaborator [`ParamKind`] -- the inverse of
393    /// [`as_param_kind`](Self::as_param_kind).
394    pub fn of_param_kind(kind: ParamKind) -> BinderKind {
395        match kind {
396            ParamKind::Explicit => BinderKind::Explicit,
397            ParamKind::Implicit => BinderKind::Implicit,
398            ParamKind::StrictImplicit => BinderKind::StrictImplicit,
399            ParamKind::Instance => BinderKind::Instance,
400        }
401    }
402
403    /// The reserved marker this kind rides on inside the parser, or `None` for `Explicit` --
404    /// which is the absence of a marker, so that an ordinary `A -> B` costs nothing.
405    fn marker(self) -> Option<&'static str> {
406        match self {
407            BinderKind::Explicit => None,
408            BinderKind::Implicit => Some(TermParser::IMPLICIT_BINDER_MARKER),
409            BinderKind::StrictImplicit => Some(TermParser::STRICT_IMPLICIT_BINDER_MARKER),
410            BinderKind::Instance => Some(TermParser::INSTANCE_BINDER_MARKER),
411        }
412    }
413}
414
415/// Everything the SURFACE says about ONE parameter that the kernel's three-field `Term::Pi`
416/// cannot hold: how it is supplied, and what fills it when the caller does not.
417#[derive(Debug, Clone, PartialEq)]
418pub struct BinderSurface {
419    /// The parameter's name. `"_"` for an anonymous binder -- `A -> B` names nothing, and
420    /// [`TermParser::name_anonymous_binders`] recovers those names from the definition's body.
421    pub name: String,
422    /// How the caller supplies it.
423    pub kind: BinderKind,
424    /// The declared type, with every marker stripped -- the type the kernel sees.
425    pub declared: Term,
426    /// `(m : T := e)` -- the term inlined when the caller omits this argument.
427    pub default: Option<Term>,
428    /// `(h : P := by tac)` -- the tactic that must prove `declared` AFRESH at each call site.
429    /// Distinct from `default` because a default is inlined once per omission and an auto-param
430    /// is a different proof term at every call site, about that call site's own proposition.
431    pub auto: Option<String>,
432}
433
434/// A declared type split into the pure kernel type the context is keyed at and the per-parameter
435/// surface information that has to be recorded beside it.
436///
437/// ★ ONE CALL AT THE DECLARATION DOOR. Before this, the declaration door read a `(Term, usize)`
438/// pair and there was nowhere for a default, an auto-param or a non-leading implicit to go -- so
439/// `Definition f : Int -> (m : Int := 3) -> Int` registered a type with a reserved marker still
440/// inside it, which the kernel then refused as an unbound global. Every piece of surface-only
441/// information now leaves the parser through this one struct.
442#[derive(Debug, Clone, PartialEq)]
443pub struct DeclarationSurface {
444    /// The declared type with every binder marker stripped: what `Context` is keyed at.
445    pub kernel_type: Term,
446    /// One entry per binder of the type's top-level telescope, outermost first.
447    pub binders: Vec<BinderSurface>,
448}
449
450impl DeclarationSurface {
451    /// The elaborator's parameter kinds, one per telescope position.
452    pub fn param_kinds(&self) -> Vec<ParamKind> {
453        self.binders
454            .iter()
455            .map(|b| b.kind.as_param_kind())
456            .collect()
457    }
458
459    /// How many LEADING implicit parameters the declaration has -- the legacy count model, and
460    /// exactly the number [`TermParser::parse_with_implicits`] reports.
461    pub fn leading_implicits(&self) -> usize {
462        self.binders
463            .iter()
464            .take_while(|b| b.kind == BinderKind::Implicit)
465            .count()
466    }
467
468    /// Does any binder carry surface information the plain `(Term, usize)` door would lose?
469    /// A declaration for which this is false can be registered exactly as it always was.
470    pub fn needs_recording(&self) -> bool {
471        self.binders
472            .iter()
473            .any(|b| b.kind != BinderKind::Explicit || b.default.is_some() || b.auto.is_some())
474    }
475}
476
477/// Recursive descent parser for Term syntax.
478pub struct TermParser<'a> {
479    input: &'a str,
480    pos: usize,
481    /// Variables currently in scope (bound by lambda, forall, fix, or match case)
482    bound_vars: HashSet<String>,
483    /// The user-declared notation in scope, if any. `None` is not a special case: a surface with
484    /// nothing declared takes exactly the same path, so the extension point costs nothing when it
485    /// is unused.
486    surface: Option<&'a Surface>,
487}
488
489impl<'a> TermParser<'a> {
490    /// Reserved head marking a NAMED ARGUMENT `(x := e)` at an argument position.
491    ///
492    /// The parser emits `MARKER x e` -- the parameter name carried as a `Global`, exactly as
493    /// [`crate::elaborate::DOT_MARKER`] carries a field name. The elaborator resolves it into the
494    /// declaration's parameter order and discards the marker; it NEVER reaches a kernel term.
495    pub const NAMED_ARG_MARKER: &'static str = "\u{27e8}named\u{27e9}";
496
497    /// Reserved head wrapping a binder's DECLARED TYPE when the binder carries a DEFAULT value:
498    /// `(m : Int := 3)` becomes `Pi(m : MARKER Int 3). ...`.
499    ///
500    /// The binder stays an ordinary `Term::Pi` and the default travels inside its `param_type`,
501    /// so the default reaches the declaration door through every existing pipe with no signature
502    /// change anywhere -- and a consumer that forgets to strip it fails LOUDLY on an unbound
503    /// global rather than silently dropping the default.
504    pub const PARAM_DEFAULT_MARKER: &'static str = "\u{27e8}default\u{27e9}";
505
506    /// Reserved head wrapping a binder's declared type when the binder is TACTIC-FILLED:
507    /// `(h : P := by decide)` becomes `Pi(h : MARKER P decide). ...`, the tactic name carried as
508    /// a `Global`. Distinct from [`Self::PARAM_DEFAULT_MARKER`] because the two are discharged
509    /// differently: a default is a TERM inlined once per omission, an auto-param is a PROOF
510    /// searched afresh at every call site, about that call site's own proposition.
511    pub const AUTO_PARAM_MARKER: &'static str = "\u{27e8}autoparam\u{27e9}";
512
513    /// Reserved head marking an EXPLICIT-ALL application `@f` -- Lean's escape hatch, and the
514    /// one the language had no spelling for at all.
515    ///
516    /// ★ WITHOUT IT AN IMPLICIT ARGUMENT CANNOT BE WRITTEN. Once a declaration's binder kinds are
517    /// recorded, `idf Nat Zero` is not "supply the implicit and the explicit": the elaborator
518    /// inserts a metavariable for the implicit position FIRST and then has two arguments for one
519    /// explicit parameter. `@` is the only way to say "I am writing every parameter myself", which
520    /// is exactly what a user reaches for when inference has failed -- so a language without it
521    /// has no escape hatch on the day it is needed most.
522    ///
523    /// `@f a b` is emitted as `MARKER f a b`: the marker is the SPINE HEAD, so a consumer
524    /// decomposing an application sees it in the position it already inspects, and the head it
525    /// marks is `args[0]`. [`TermParser::is_explicit_all_head`] and
526    /// [`TermParser::as_explicit_all`] are the whole reading interface.
527    pub const EXPLICIT_ALL_MARKER: &'static str = "\u{27e8}explicit\u{27e9}";
528
529    /// Reserved atom marking the ELLIPSIS `..` -- "fill every remaining position with `_`".
530    ///
531    /// Only the elaborator knows the arity of the thing being applied, so the parser records the
532    /// REQUEST and the elaborator expands it into that many solved holes. Emitted as the last
533    /// component of `<a, b, ..>` and as the last argument of `f ..`.
534    pub const ELLIPSIS_MARKER: &'static str = "\u{27e8}..\u{27e9}";
535
536    /// Reserved head wrapping a binder's declared type when the binder is IMPLICIT:
537    /// `{A : Type} -> B` becomes `Pi(A : MARKER Type). B`.
538    ///
539    /// Unlike the other three, a kind marker never leaves this module: every public entry point
540    /// reads the telescope's kinds off it and then strips it, so the emitted term is the same
541    /// pure `Term::Pi` an explicit binder produces. It exists because a binder KIND is a
542    /// position in a telescope, and the only structure that survives the recursive descent in
543    /// telescope order is the telescope itself.
544    pub const IMPLICIT_BINDER_MARKER: &'static str = "\u{27e8}implicit\u{27e9}";
545
546    /// Reserved head wrapping a STRICT-IMPLICIT binder's declared type: `⦃A : Type⦄ -> B`.
547    /// Distinct from [`Self::IMPLICIT_BINDER_MARKER`] because Lean inserts the two at different
548    /// moments, and collapsing them at the parser would make the difference unrecoverable.
549    pub const STRICT_IMPLICIT_BINDER_MARKER: &'static str = "\u{27e8}strict\u{27e9}";
550
551    /// Reserved head wrapping an INSTANCE binder's class type: `[Inhabited A] -> B`.
552    pub const INSTANCE_BINDER_MARKER: &'static str = "\u{27e8}instance\u{27e9}";
553
554    /// Lean's ASCII spelling of the strict-implicit OPEN bracket `⦃` -- `{{`.
555    ///
556    /// `Lean/Parser/Term.lean:346-347` defines both brackets as an alternation, guillemet or
557    /// doubled brace, and `:377` documents them as one binder with two spellings: "A strict
558    /// implicit binder, `⦃y z : A⦄` or its ASCII alternative `{{y z : A}}`". The ASCII one is the
559    /// spelling available to a writer with no unicode input method, so refusing it made Lean's
560    /// fourth binder kind unreachable in practice from an ordinary keyboard.
561    pub const STRICT_IMPLICIT_OPEN_ASCII: &'static str = "{{";
562    /// Lean's ASCII spelling of the strict-implicit CLOSE bracket `⦄` -- `}}`.
563    /// See [`STRICT_IMPLICIT_OPEN_ASCII`](Self::STRICT_IMPLICIT_OPEN_ASCII).
564    pub const STRICT_IMPLICIT_CLOSE_ASCII: &'static str = "}}";
565
566    /// `BinderKind::Explicit`, nameable without naming the enum.
567    pub const EXPLICIT: BinderKind = BinderKind::Explicit;
568    /// `BinderKind::Implicit`, nameable without naming the enum.
569    pub const IMPLICIT: BinderKind = BinderKind::Implicit;
570    /// `BinderKind::StrictImplicit`, nameable without naming the enum.
571    pub const STRICT_IMPLICIT: BinderKind = BinderKind::StrictImplicit;
572    /// `BinderKind::Instance`, nameable without naming the enum.
573    pub const INSTANCE: BinderKind = BinderKind::Instance;
574
575    /// Recognize a NAMED ARGUMENT, returning the parameter name and the supplied value.
576    ///
577    /// The spine is decomposed rather than pattern-matched on a fixed depth, so a named argument
578    /// whose value is itself an application (`(x := f y)`) is recognized too.
579    pub fn as_named_arg(term: &Term) -> Option<(&str, &Term)> {
580        match term {
581            Term::App(f, value) => match &**f {
582                Term::App(marker, name) => match (&**marker, &**name) {
583                    (Term::Global(m), Term::Global(n)) if m == Self::NAMED_ARG_MARKER => {
584                        Some((n.as_str(), value.as_ref()))
585                    }
586                    _ => None,
587                },
588                _ => None,
589            },
590            _ => None,
591        }
592    }
593
594    /// Is this term the ELLIPSIS marker?
595    pub fn is_ellipsis(term: &Term) -> bool {
596        matches!(term, Term::Global(n) if n == Self::ELLIPSIS_MARKER)
597    }
598
599    /// Is this the HEAD of an explicit-all application -- the thing a decomposed spine's innermost
600    /// position holds for `@f a b`? The head `f` is then that spine's first argument.
601    pub fn is_explicit_all_head(term: &Term) -> bool {
602        matches!(term, Term::Global(n) if n == Self::EXPLICIT_ALL_MARKER)
603    }
604
605    /// Recognize an explicit-all application `@f`, returning the head it marks. Only the
606    /// UNAPPLIED shape; an applied `@f a b` is read off the spine with
607    /// [`is_explicit_all_head`](Self::is_explicit_all_head), because that is the form the
608    /// elaborator's application arm already has in hand.
609    pub fn as_explicit_all(term: &Term) -> Option<&Term> {
610        match term {
611            Term::App(marker, head) if Self::is_explicit_all_head(marker) => Some(head.as_ref()),
612            _ => None,
613        }
614    }
615
616    /// Recognize a DEFAULTED binder's `param_type`, returning the declared type and the default
617    /// value the caller may omit. A binder may be BOTH defaulted and non-explicit
618    /// (`{m : Int := 3}`), so the kind marker is peeled first -- reading only the outermost
619    /// marker would have made a defaulted implicit look like an ordinary one and dropped its
620    /// default in silence.
621    pub fn as_default_param(param_type: &Term) -> Option<(&Term, &Term)> {
622        Self::as_marked_binder(Self::peel_kind(param_type), Self::PARAM_DEFAULT_MARKER)
623    }
624
625    /// Recognize an AUTO-PARAM binder's `param_type`, returning the declared type (the obligation)
626    /// and the name of the tactic that must discharge it at each call site.
627    pub fn as_auto_param(param_type: &Term) -> Option<(&Term, &str)> {
628        match Self::as_marked_binder(Self::peel_kind(param_type), Self::AUTO_PARAM_MARKER)? {
629            (declared, Term::Global(tactic)) => Some((declared, tactic.as_str())),
630            _ => None,
631        }
632    }
633
634    /// Recognize a KIND-marked binder type, returning the kind and the type inside it.
635    ///
636    /// The shape is `MARKER declared` -- one argument, where the other two binder markers carry
637    /// two -- so no marker can ever be mistaken for another.
638    fn as_kind_marked(param_type: &Term) -> Option<(BinderKind, &Term)> {
639        let Term::App(f, declared) = param_type else {
640            return None;
641        };
642        let Term::Global(m) = &**f else { return None };
643        for kind in [
644            BinderKind::Implicit,
645            BinderKind::StrictImplicit,
646            BinderKind::Instance,
647        ] {
648            if kind.marker() == Some(m.as_str()) {
649                return Some((kind, declared.as_ref()));
650            }
651        }
652        None
653    }
654
655    /// The type inside a kind marker, or the type itself when there is none.
656    fn peel_kind(param_type: &Term) -> &Term {
657        Self::as_kind_marked(param_type)
658            .map(|(_, d)| d)
659            .unwrap_or(param_type)
660    }
661
662    /// Wrap a binder's declared type in the marker for `kind`. `Explicit` is the ABSENCE of a
663    /// marker, so an ordinary `A -> B` allocates nothing and reads exactly as it always did.
664    fn mark_kind(kind: BinderKind, declared: Term) -> Term {
665        match kind.marker() {
666            None => declared,
667            Some(m) => Term::App(Box::new(Term::Global(m.to_string())), Box::new(declared)),
668        }
669    }
670
671    /// The BINDER KINDS of a type's top-level telescope, outermost first -- one entry per `Pi`,
672    /// `Explicit` where no kind marker stands.
673    ///
674    /// ★ A KIND IS A POSITION, NOT A COUNT. A marker written inside a PARAMETER'S OWN TYPE
675    /// (`{A : Type} -> ({B : Type} -> B) -> A`) lives under that parameter's `param_type` and is
676    /// therefore not on this spine at all -- which is precisely the distinction the running
677    /// `implicit_count` could not make, and why it reported two parameters for a declaration
678    /// that has one.
679    pub fn binder_kinds_of(ty: &Term) -> Vec<BinderKind> {
680        let mut kinds = Vec::new();
681        let mut cur = ty;
682        loop {
683            // ★ A LAMBDA IS A BINDER TELESCOPE TOO. `fun {A} (a : A) => a` declares that its
684            // FIRST argument is supplied by unification, exactly as `{A : Type} -> A -> A` does,
685            // and in LOGOS an un-ascribed `Definition` takes its whole telescope from the body --
686            // so a walk that stopped at `Pi` could not report the kinds of the only spelling that
687            // has them. An unmarked binder reads `Explicit` either way, so every term that had no
688            // kind marker in it answers exactly as it always did.
689            // A binder that carries its kind as an annotation (`Term::Annotated`) answers with it,
690            // exactly as a marked domain does.
691            let annotated = cur.binder_kind();
692            let (param_type, rest) = match cur.peel_annotations() {
693                Term::Pi {
694                    param_type,
695                    body_type,
696                    ..
697                } => (param_type, body_type),
698                Term::Lambda {
699                    param_type, body, ..
700                } => (param_type, body),
701                _ => break,
702            };
703            kinds.push(
704                Self::as_kind_marked(param_type)
705                    .map(|(k, _)| k)
706                    .or_else(|| annotated.map(BinderKind::of_param_kind))
707                    .unwrap_or(BinderKind::Explicit),
708            );
709            cur = rest;
710        }
711        kinds
712    }
713
714    /// The shared shape of both binder markers: `MARKER declared payload`.
715    fn as_marked_binder<'t>(term: &'t Term, marker: &str) -> Option<(&'t Term, &'t Term)> {
716        match term {
717            Term::App(f, payload) => match &**f {
718                Term::App(m, declared) => match &**m {
719                    Term::Global(m) if m == marker => Some((declared.as_ref(), payload.as_ref())),
720                    _ => None,
721                },
722                _ => None,
723            },
724            _ => None,
725        }
726    }
727
728    /// The same term with every BINDER marker removed -- the pure kernel type a declaration is
729    /// registered at, once the defaults have been read off it.
730    ///
731    /// Argument-position sugar (a named argument, an ellipsis) is deliberately NOT stripped: those
732    /// carry a request the elaborator has to ACT on, and silently dropping one would change what
733    /// the user wrote into something that merely typechecks. Only the decoration on a binder's
734    /// type is erased here.
735    pub fn strip_binder_markers(term: &Term) -> Term {
736        if let Some(inner) = Self::peel_binder_marker(term) {
737            return Self::strip_binder_markers(inner);
738        }
739        Self::strip_binder_markers_inner(term)
740    }
741
742    /// The same term with every BINDER-KIND marker removed and nothing else touched -- the pure
743    /// kernel `Pi` telescope, with a defaulted or tactic-filled binder still carrying its payload
744    /// for the declaration door to read.
745    pub fn strip_kind_markers(term: &Term) -> Term {
746        let mut owned = term.clone();
747        Self::strip_kind_markers_in_place(&mut owned);
748        owned
749    }
750
751    /// [`strip_kind_markers`](Self::strip_kind_markers) on a term the caller already owns.
752    ///
753    /// Every parse goes through this, and almost no term has a kind marker in it -- so the walk
754    /// must not COPY the tree it is about to hand back untouched. The `clone` below runs only
755    /// where a marker actually stands; the traversal itself allocates nothing.
756    fn strip_kind_markers_in_place(term: &mut Term) {
757        while let Some(inner) = Self::as_kind_marked(term).map(|(_, d)| d.clone()) {
758            *term = inner;
759        }
760        match term {
761            Term::Pi {
762                param_type,
763                body_type,
764                ..
765            } => {
766                Self::strip_kind_markers_in_place(param_type);
767                Self::strip_kind_markers_in_place(body_type);
768            }
769            Term::Lambda {
770                param_type, body, ..
771            } => {
772                Self::strip_kind_markers_in_place(param_type);
773                Self::strip_kind_markers_in_place(body);
774            }
775            Term::App(f, a) => {
776                Self::strip_kind_markers_in_place(f);
777                Self::strip_kind_markers_in_place(a);
778            }
779            Term::Match {
780                discriminant,
781                motive,
782                cases,
783            } => {
784                Self::strip_kind_markers_in_place(discriminant);
785                Self::strip_kind_markers_in_place(motive);
786                for c in cases {
787                    Self::strip_kind_markers_in_place(c);
788                }
789            }
790            Term::Fix { body, .. } => Self::strip_kind_markers_in_place(body),
791            Term::MutualFix { defs, .. } => {
792                for (_, b) in defs {
793                    Self::strip_kind_markers_in_place(b);
794                }
795            }
796            Term::Let {
797                ty, value, body, ..
798            } => {
799                Self::strip_kind_markers_in_place(ty);
800                Self::strip_kind_markers_in_place(value);
801                Self::strip_kind_markers_in_place(body);
802            }
803            Term::Annotated { term, .. } => Self::strip_kind_markers_in_place(term),
804            _ => {}
805        }
806    }
807
808    /// One layer of every binder marker: the kind wrapper, then the default or auto-param
809    /// wrapper inside it.
810    fn peel_binder_marker(term: &Term) -> Option<&Term> {
811        if let Some((_, declared)) = Self::as_kind_marked(term) {
812            return Some(declared);
813        }
814        if let Some((declared, _)) = Self::as_marked_binder(term, Self::PARAM_DEFAULT_MARKER) {
815            return Some(declared);
816        }
817        if let Some((declared, _)) = Self::as_marked_binder(term, Self::AUTO_PARAM_MARKER) {
818            return Some(declared);
819        }
820        None
821    }
822
823    fn strip_binder_markers_inner(term: &Term) -> Term {
824        match term {
825            Term::Pi {
826                param,
827                param_type,
828                body_type,
829            } => Term::Pi {
830                param: param.clone(),
831                param_type: Box::new(Self::strip_binder_markers(param_type)),
832                body_type: Box::new(Self::strip_binder_markers(body_type)),
833            },
834            Term::Lambda {
835                param,
836                param_type,
837                body,
838            } => Term::Lambda {
839                param: param.clone(),
840                param_type: Box::new(Self::strip_binder_markers(param_type)),
841                body: Box::new(Self::strip_binder_markers(body)),
842            },
843            Term::App(f, a) => Term::App(
844                Box::new(Self::strip_binder_markers(f)),
845                Box::new(Self::strip_binder_markers(a)),
846            ),
847            Term::Match {
848                discriminant,
849                motive,
850                cases,
851            } => Term::Match {
852                discriminant: Box::new(Self::strip_binder_markers(discriminant)),
853                motive: Box::new(Self::strip_binder_markers(motive)),
854                cases: cases
855                    .iter()
856                    .map(|c| Self::strip_binder_markers(c))
857                    .collect(),
858            },
859            Term::Fix { name, body } => Term::Fix {
860                name: name.clone(),
861                body: Box::new(Self::strip_binder_markers(body)),
862            },
863            Term::MutualFix { defs, index } => Term::MutualFix {
864                defs: defs
865                    .iter()
866                    .map(|(n, b)| (n.clone(), Self::strip_binder_markers(b)))
867                    .collect(),
868                index: *index,
869            },
870            Term::Let {
871                name,
872                ty,
873                value,
874                body,
875            } => Term::Let {
876                name: name.clone(),
877                ty: Box::new(Self::strip_binder_markers(ty)),
878                value: Box::new(Self::strip_binder_markers(value)),
879                body: Box::new(Self::strip_binder_markers(body)),
880            },
881            Term::Annotated { annotation, term } => Term::Annotated {
882                annotation: annotation.clone(),
883                term: Box::new(Self::strip_binder_markers(term)),
884            },
885            other => other.clone(),
886        }
887    }
888
889    /// Substitute a declaration's ACTUAL argument for a reference to parameter `name` inside a
890    /// DEFAULT value -- `(m : Int := mul n 2)` applied as `sized 5` inlines `mul 5 2`.
891    ///
892    /// A default is parsed in the scope of the binders before it, so a reference to a NAMED
893    /// earlier binder is already a `Term::Var` and is substituted capture-avoidingly (an inner
894    /// binder of the same name shadows it, and substitution stops). A reference to an ANONYMOUS
895    /// earlier binder -- `Int -> (m : Int := mul n 2) -> Int`, where position 0's `Pi` binder is
896    /// `"_"` and the name `n` exists only in the definition body's lambda telescope -- parsed as
897    /// a `Term::Global`, and a `Global` is not shadowed by any binder, so it is replaced
898    /// unconditionally. Handling both is what keeps an inlined default from escaping as an open
899    /// term with a free `n` in it, which is the way this goes wrong.
900    pub fn substitute_param_ref(term: &Term, name: &str, value: &Term) -> Term {
901        match term {
902            Term::Var(v) if v == name => value.clone(),
903            Term::Global(g) if g == name => value.clone(),
904            Term::Pi {
905                param,
906                param_type,
907                body_type,
908            } => Term::Pi {
909                param: param.clone(),
910                param_type: Box::new(Self::substitute_param_ref(param_type, name, value)),
911                body_type: Box::new(if param == name {
912                    Self::substitute_global_only(body_type, name, value)
913                } else {
914                    Self::substitute_param_ref(body_type, name, value)
915                }),
916            },
917            Term::Lambda {
918                param,
919                param_type,
920                body,
921            } => Term::Lambda {
922                param: param.clone(),
923                param_type: Box::new(Self::substitute_param_ref(param_type, name, value)),
924                body: Box::new(if param == name {
925                    Self::substitute_global_only(body, name, value)
926                } else {
927                    Self::substitute_param_ref(body, name, value)
928                }),
929            },
930            Term::App(f, a) => Term::App(
931                Box::new(Self::substitute_param_ref(f, name, value)),
932                Box::new(Self::substitute_param_ref(a, name, value)),
933            ),
934            Term::Match {
935                discriminant,
936                motive,
937                cases,
938            } => Term::Match {
939                discriminant: Box::new(Self::substitute_param_ref(discriminant, name, value)),
940                motive: Box::new(Self::substitute_param_ref(motive, name, value)),
941                cases: cases
942                    .iter()
943                    .map(|c| Self::substitute_param_ref(c, name, value))
944                    .collect(),
945            },
946            Term::Fix { name: f, body } => Term::Fix {
947                name: f.clone(),
948                body: Box::new(if f == name {
949                    Self::substitute_global_only(body, name, value)
950                } else {
951                    Self::substitute_param_ref(body, name, value)
952                }),
953            },
954            Term::MutualFix { defs, index } => Term::MutualFix {
955                defs: defs
956                    .iter()
957                    .map(|(n, b)| {
958                        let rebound = defs.iter().any(|(other, _)| other == name);
959                        let b = if rebound {
960                            Self::substitute_global_only(b, name, value)
961                        } else {
962                            Self::substitute_param_ref(b, name, value)
963                        };
964                        (n.clone(), b)
965                    })
966                    .collect(),
967                index: *index,
968            },
969            Term::Let {
970                name: l,
971                ty,
972                value: v,
973                body,
974            } => Term::Let {
975                name: l.clone(),
976                ty: Box::new(Self::substitute_param_ref(ty, name, value)),
977                value: Box::new(Self::substitute_param_ref(v, name, value)),
978                body: Box::new(if l == name {
979                    Self::substitute_global_only(body, name, value)
980                } else {
981                    Self::substitute_param_ref(body, name, value)
982                }),
983            },
984            Term::Annotated { annotation, term } => Term::Annotated {
985                annotation: annotation.clone(),
986                term: Box::new(Self::substitute_param_ref(term, name, value)),
987            },
988            other => other.clone(),
989        }
990    }
991
992    /// The `Global`-only half of [`Self::substitute_param_ref`], used under a binder that shadows
993    /// `name`: the local `Var` there is a DIFFERENT variable and must survive untouched, while a
994    /// `Global` of that spelling still denotes the parameter.
995    fn substitute_global_only(term: &Term, name: &str, value: &Term) -> Term {
996        match term {
997            Term::Var(_) => term.clone(),
998            Term::Global(g) if g == name => value.clone(),
999            Term::Pi {
1000                param,
1001                param_type,
1002                body_type,
1003            } => Term::Pi {
1004                param: param.clone(),
1005                param_type: Box::new(Self::substitute_global_only(param_type, name, value)),
1006                body_type: Box::new(Self::substitute_global_only(body_type, name, value)),
1007            },
1008            Term::Lambda {
1009                param,
1010                param_type,
1011                body,
1012            } => Term::Lambda {
1013                param: param.clone(),
1014                param_type: Box::new(Self::substitute_global_only(param_type, name, value)),
1015                body: Box::new(Self::substitute_global_only(body, name, value)),
1016            },
1017            Term::App(f, a) => Term::App(
1018                Box::new(Self::substitute_global_only(f, name, value)),
1019                Box::new(Self::substitute_global_only(a, name, value)),
1020            ),
1021            Term::Match {
1022                discriminant,
1023                motive,
1024                cases,
1025            } => Term::Match {
1026                discriminant: Box::new(Self::substitute_global_only(discriminant, name, value)),
1027                motive: Box::new(Self::substitute_global_only(motive, name, value)),
1028                cases: cases
1029                    .iter()
1030                    .map(|c| Self::substitute_global_only(c, name, value))
1031                    .collect(),
1032            },
1033            Term::Fix { name: f, body } => Term::Fix {
1034                name: f.clone(),
1035                body: Box::new(Self::substitute_global_only(body, name, value)),
1036            },
1037            Term::MutualFix { defs, index } => Term::MutualFix {
1038                defs: defs
1039                    .iter()
1040                    .map(|(n, b)| (n.clone(), Self::substitute_global_only(b, name, value)))
1041                    .collect(),
1042                index: *index,
1043            },
1044            Term::Let {
1045                name: l,
1046                ty,
1047                value: v,
1048                body,
1049            } => Term::Let {
1050                name: l.clone(),
1051                ty: Box::new(Self::substitute_global_only(ty, name, value)),
1052                value: Box::new(Self::substitute_global_only(v, name, value)),
1053                body: Box::new(Self::substitute_global_only(body, name, value)),
1054            },
1055            Term::Annotated { annotation, term } => Term::Annotated {
1056                annotation: annotation.clone(),
1057                term: Box::new(Self::substitute_global_only(term, name, value)),
1058            },
1059            other => other.clone(),
1060        }
1061    }
1062
1063    /// The byte index of the first `sep` at TOP LEVEL of `input` -- outside every bracket, outside
1064    /// a guillemet name, and outside a string literal -- or `None` if there is none.
1065    ///
1066    /// WHY THE VERNACULAR NEEDS THIS. `Definition <name> : <type> := <body>.` is split by searching
1067    /// for `:=`, and the FIRST `:=` in the text is not always the separator. A defaulted binder puts
1068    /// one inside the TYPE (`Definition f : Int -> (m : Int := 3) -> Int := ...` splits at the
1069    /// default and the command is refused for a reason that names neither the default nor the
1070    /// body), and a guillemet name puts one inside the NAME (`Definition \u{ab}a := b\u{bb} : Nat := Zero.`).
1071    /// The same applies to the `:` that opens the type ascription. The lexical structure of a term
1072    /// is this parser's knowledge, so the scan lives here rather than being re-derived -- once per
1073    /// bug -- by every door that has to split a sentence.
1074    ///
1075    /// `sep` must not begin with a bracket, a quote or a guillemet: those characters are what the
1076    /// scan is tracking, so a separator starting with one could never be at top level anyway.
1077    pub fn find_top_level(input: &str, sep: &str) -> Option<usize> {
1078        if sep.is_empty() {
1079            return None;
1080        }
1081        let mut depth = 0usize;
1082        let mut chars = input.char_indices();
1083        while let Some((i, c)) = chars.next() {
1084            match c {
1085                // A string literal is opaque, escapes included -- `"a := b"` holds no separator.
1086                '"' => {
1087                    let mut escaped = false;
1088                    for (_, c) in chars.by_ref() {
1089                        if escaped {
1090                            escaped = false;
1091                        } else if c == '\\' {
1092                            escaped = true;
1093                        } else if c == '"' {
1094                            break;
1095                        }
1096                    }
1097                    continue;
1098                }
1099                // A guillemet name is verbatim and cannot nest (`scan_name` forbids an inner one).
1100                '\u{ab}' => {
1101                    for (_, c) in chars.by_ref() {
1102                        if c == '\u{bb}' {
1103                            break;
1104                        }
1105                    }
1106                    continue;
1107                }
1108                '(' | '{' | '[' | '\u{27e8}' | '\u{2983}' => {
1109                    depth += 1;
1110                    continue;
1111                }
1112                // An unbalanced closer cannot take the depth negative: the sentence is malformed
1113                // and the parser will say so, but this scan must still terminate and stay at 0.
1114                ')' | '}' | ']' | '\u{27e9}' | '\u{2984}' => {
1115                    depth = depth.saturating_sub(1);
1116                    continue;
1117                }
1118                _ => {}
1119            }
1120            if depth == 0 && input[i..].starts_with(sep) {
1121                return Some(i);
1122            }
1123        }
1124        None
1125    }
1126
1127    /// Parse a term from input string.
1128    pub fn parse(input: &'a str) -> Result<Term, ParseError> {
1129        Self::parse_with_implicits(input).map(|(t, _)| t)
1130    }
1131
1132    /// Parse a term through a SURFACE: macros are expanded to a fixpoint first, then the notation
1133    /// in scope is read as part of the grammar.
1134    ///
1135    /// Macro expansion is source-to-source and runs BEFORE the parse, because an alternative may
1136    /// invoke the macro it defines; notation is a parser layer, because a notation has a
1137    /// precedence and text has none. That is the whole staging, and it is the staging Lean uses.
1138    pub fn parse_in(surface: &Surface, input: &str) -> Result<Term, ParseError> {
1139        Self::parse_with_implicits_in(surface, input).map(|(t, _)| t)
1140    }
1141
1142    /// [`parse_in`](Self::parse_in), also reporting the leading implicit-binder count.
1143    pub fn parse_with_implicits_in(
1144        surface: &Surface,
1145        input: &str,
1146    ) -> Result<(Term, usize), ParseError> {
1147        Self::entry(Some(surface), input, Self::finish_implicits)
1148    }
1149
1150    /// [`parse`](Self::parse), also reporting the BINDER KIND of every parameter of the parsed
1151    /// type's top-level telescope -- the vector `Context::set_binder_kinds` is keyed at.
1152    ///
1153    /// This is the honest successor to [`parse_with_implicits`](Self::parse_with_implicits): a
1154    /// count can only describe a PREFIX of implicits, so `Nat -> {A : Type} -> A` -- an implicit
1155    /// in second position, which Lean writes constantly -- has no number that describes it.
1156    pub fn parse_with_binder_kinds(input: &str) -> Result<(Term, Vec<BinderKind>), ParseError> {
1157        Self::entry(None, input, Self::finish_kinds)
1158    }
1159
1160    /// [`parse_with_binder_kinds`](Self::parse_with_binder_kinds), through a [`Surface`].
1161    pub fn parse_with_binder_kinds_in(
1162        surface: &Surface,
1163        input: &str,
1164    ) -> Result<(Term, Vec<BinderKind>), ParseError> {
1165        Self::entry(Some(surface), input, Self::finish_kinds)
1166    }
1167
1168    /// Parse a DECLARED TYPE into the kernel type it is registered at plus the surface
1169    /// information that has to be recorded beside it -- binder kinds, default values and
1170    /// auto-param obligations, in telescope order.
1171    ///
1172    /// The one call the declaration door needs. See [`DeclarationSurface`].
1173    pub fn read_declaration(input: &str) -> Result<DeclarationSurface, ParseError> {
1174        Self::entry(None, input, |t| Self::declaration_surface(&t))
1175    }
1176
1177    /// [`read_declaration`](Self::read_declaration), through a [`Surface`].
1178    pub fn read_declaration_in(
1179        surface: &Surface,
1180        input: &str,
1181    ) -> Result<DeclarationSurface, ParseError> {
1182        Self::entry(Some(surface), input, |t| Self::declaration_surface(&t))
1183    }
1184
1185    /// A DECLARED TYPE as the declaration door must carry it: the parsed type with its
1186    /// binder-kind markers STILL ON, beside the leading-implicit count the legacy model reads.
1187    ///
1188    /// ★ THE CHANNEL BETWEEN THE TWO HALVES WAS A `usize`, AND MATHLIB DOES NOT FIT THROUGH IT.
1189    /// The elaborator has read `Context::binder_kinds` -- one `ParamKind` per POSITION -- ever
1190    /// since `full_param_kinds` and the kinds match in `elab_surface_uncoerced` were written, and
1191    /// this file has parsed all four of Lean's brackets since the binder grammar landed. Between
1192    /// them sat [`parse_with_implicits_in`](Self::parse_with_implicits_in), which STRIPS the kind
1193    /// markers and reports a number. A declaration door reading its type through that one cannot
1194    /// recover a kind afterwards: [`declaration_surface`](Self::declaration_surface) then reads
1195    /// `Explicit` for every binder, correctly, because by then the type no longer says anything
1196    /// else. So `Nat -> {A : Type} -> A -> A` registered THREE EXPLICIT parameters -- the count
1197    /// stops at the first non-leading binder and describes only the prefix -- `⦃A : Type⦄` became
1198    /// an argument the caller now has to write, and `[Inhabited A]` stopped consulting the
1199    /// instance database at all. `theorem foo {α} [Monoid α] (a : α)`, the shape of very nearly
1200    /// every declaration in mathlib, had no working spelling.
1201    ///
1202    /// This door keeps the markers on, so the call the declaration door already makes --
1203    /// `declaration_surface`, which reads `as_kind_marked` and whose `kernel_type` comes back
1204    /// fully stripped -- returns the truth instead of a flattened telescope. The count is
1205    /// reported unchanged beside it, so the leading-implicit model that lives next to it is not
1206    /// disturbed.
1207    ///
1208    /// ★ THE FIRST COMPONENT IS NOT A KERNEL TERM. Its parameter types are marker applications,
1209    /// and every marker is an undeclared global the kernel refuses by name
1210    /// (`no_reserved_marker_is_inhabited_so_a_forgotten_one_fails_loudly`) -- which is the point:
1211    /// a door that forgets to split gets `UnboundVariable`, not a term that typechecks by
1212    /// accident. Take [`DeclarationSurface::kernel_type`] before registering anything.
1213    pub fn read_declared_type_in(
1214        surface: &Surface,
1215        input: &str,
1216    ) -> Result<(Term, usize), ParseError> {
1217        Self::entry(Some(surface), input, Self::count_implicits)
1218    }
1219
1220    /// [`read_declared_type_in`](Self::read_declared_type_in), with no [`Surface`] in scope.
1221    pub fn read_declared_type(input: &str) -> Result<(Term, usize), ParseError> {
1222        Self::entry(None, input, Self::count_implicits)
1223    }
1224
1225    /// Split a declared Pi type or an inferred definition's lambda telescope into its
1226    /// marker-free term and per-binder surface.
1227    ///
1228    /// Safe to call on a type that has been through
1229    /// [`parse_with_implicits`](Self::parse_with_implicits): the binder KINDS are stripped by
1230    /// that door and every binder then reads as `Explicit`, while the defaults and auto-params
1231    /// -- which that door deliberately leaves in place -- are still recovered.
1232    pub fn declaration_surface(ty: &Term) -> DeclarationSurface {
1233        let mut binders = Vec::new();
1234        let mut cur = ty;
1235        let lambda_telescope = matches!(ty, Term::Lambda { .. });
1236        loop {
1237            let (param, param_type, body_type) = match cur {
1238                Term::Pi {
1239                    param,
1240                    param_type,
1241                    body_type,
1242                } if !lambda_telescope => (param, param_type, body_type),
1243                Term::Lambda {
1244                    param,
1245                    param_type,
1246                    body,
1247                } if lambda_telescope => (param, param_type, body),
1248                _ => break,
1249            };
1250            let (kind, inner) = match Self::as_kind_marked(param_type) {
1251                Some((k, d)) => (k, d),
1252                None => (BinderKind::Explicit, param_type.as_ref()),
1253            };
1254            let (declared, default, auto) = if let Some((d, v)) =
1255                Self::as_marked_binder(inner, Self::PARAM_DEFAULT_MARKER)
1256            {
1257                (d, Some(Self::strip_binder_markers(v)), None)
1258            } else if let Some((d, t)) = Self::as_marked_binder(inner, Self::AUTO_PARAM_MARKER) {
1259                let tactic = match t {
1260                    Term::Global(n) => Some(n.clone()),
1261                    _ => None,
1262                };
1263                (d, None, tactic)
1264            } else {
1265                (inner, None, None)
1266            };
1267            binders.push(BinderSurface {
1268                name: param.clone(),
1269                kind,
1270                declared: Self::strip_binder_markers(declared),
1271                default,
1272                auto,
1273            });
1274            cur = body_type;
1275        }
1276        DeclarationSurface {
1277            kernel_type: Self::strip_binder_markers(ty),
1278            binders,
1279        }
1280    }
1281
1282    /// Give every ANONYMOUS binder the name the definition's BODY binds at that position.
1283    ///
1284    /// ★ IN LOGOS THE BODY IS WHERE THE NAMES ARE. `A -> B -> C` is the only spelling of a
1285    /// non-dependent signature and it names nothing -- `parse_arrow` builds every one of those
1286    /// binders as `Pi(_ : A). ...`. So for `Definition sub3 : Int -> Int -> Int -> Int := fun x
1287    /// => fun y => fun z => ...` the parameter names `x`, `y`, `z` exist ONLY in the body's
1288    /// lambda telescope, and a named argument `sub3 (y := 2)` can be resolved from nowhere else.
1289    ///
1290    /// A body name is taken only where the declared binder is anonymous, only while the two
1291    /// telescopes run in step, and never when it would COLLIDE with a name the declared type
1292    /// already gives another parameter -- two parameters answering to one name is worse than one
1293    /// parameter with no name, because a named argument would then silently pick one of them.
1294    pub fn name_anonymous_binders(binders: &mut [BinderSurface], body: &Term) {
1295        let mut names: Vec<String> = binders.iter().map(|b| b.name.clone()).collect();
1296        Self::name_anonymous_positions(&mut names, body);
1297        for (binder, name) in binders.iter_mut().zip(names) {
1298            binder.name = name;
1299        }
1300    }
1301
1302    /// [`name_anonymous_binders`](Self::name_anonymous_binders) over a bare telescope of NAMES --
1303    /// the shape a caller has when it read the names off a `Pi` spine rather than off a
1304    /// [`DeclarationSurface`].
1305    ///
1306    /// ★ ONE ANSWER TO "WHERE ARE THE PARAMETER NAMES", IN THE FILE THAT OWNS THE SURFACE. The
1307    /// rule is not obvious and it is not local: a non-dependent signature names nothing, the body's
1308    /// λ-telescope is the only place the writer's names exist, and the two telescopes only run in
1309    /// step until the first one ends. Re-deriving that at each door is how two doors come to
1310    /// disagree about which parameter `f (x := …)` means.
1311    ///
1312    /// ★ AND A NAME MAY BE TAKEN ONLY ONCE. Two parameters answering to ONE name is worse than one
1313    /// parameter with no name at all: a named argument silently picks the first, the other becomes
1314    /// unreachable by name, and nothing reports it. `(x : Int) -> Int -> Int` defined as
1315    /// `fun y : Int => fun x : Int => …` is exactly that shape -- position 0 is DECLARED `x` while
1316    /// position 1's body binder is also `x` -- and it is ordinary text, not a contrivance. A
1317    /// position whose body name is already taken stays `"_"`, so a named argument resolves to the
1318    /// position that really is `x` or is refused by name.
1319    pub fn name_anonymous_positions(names: &mut [String], body: &Term) {
1320        let mut taken: HashSet<String> = names
1321            .iter()
1322            .filter(|n| n.as_str() != "_")
1323            .cloned()
1324            .collect();
1325        // A RECURSIVE definition's body is wrapped in a `Fix`, and the λ-telescope carrying the
1326        // writer's names is inside it. Transparent here: `fix f => fun x => …` and `fun x => …`
1327        // name their parameters identically, and a caller that had to know this is a caller that
1328        // can forget it.
1329        let mut cur = body;
1330        while let Term::Fix { body, .. } = cur {
1331            cur = body;
1332        }
1333        for slot in names.iter_mut() {
1334            let Term::Lambda { param, body, .. } = cur else {
1335                break;
1336            };
1337            if slot.as_str() == "_" && param != "_" && !taken.contains(param) {
1338                *slot = param.clone();
1339                taken.insert(param.clone());
1340            }
1341            cur = body;
1342        }
1343    }
1344
1345    /// The DEFAULT value for parameter `index`, with every earlier parameter's ACTUAL argument
1346    /// substituted into it -- `sized 5` against `Int -> (m : Int := mul n 2) -> Int` inlines
1347    /// `mul 5 2`, never an open term with a free `n` in it.
1348    ///
1349    /// `args` must hold the arguments already resolved for positions `0..index`; with fewer than
1350    /// that this returns `None` rather than a term it cannot close. `None` also means the
1351    /// parameter simply has no default.
1352    ///
1353    /// ★ CALL [`name_anonymous_binders`](Self::name_anonymous_binders) FIRST. A default parsed in
1354    /// the scope of an ANONYMOUS earlier binder reads that reference as a `Term::Global`, because
1355    /// `A -> B` binds nothing the parser could have put in scope. Substitution is by NAME, so a
1356    /// telescope still full of `"_"` substitutes nothing and hands back exactly the open term this
1357    /// function exists to prevent -- which is why the two are documented as a pair and tested as
1358    /// one.
1359    pub fn inline_default(binders: &[BinderSurface], index: usize, args: &[Term]) -> Option<Term> {
1360        let mut value = binders.get(index)?.default.clone()?;
1361        if args.len() < index {
1362            return None;
1363        }
1364        for (i, earlier) in binders.iter().enumerate().take(index) {
1365            if earlier.name == "_" {
1366                continue;
1367            }
1368            value = Self::substitute_param_ref(&value, &earlier.name, &args[i]);
1369        }
1370        Some(value)
1371    }
1372
1373    /// Every public entry point: the raw parse and its post-processing, on a stack deep enough
1374    /// for the input — see [`syntactic_depth`]. A text nested deeper than the kernel could ever
1375    /// check is refused here, as an error that names it, rather than by the process running out of
1376    /// stack.
1377    fn entry<R: Send>(
1378        surface: Option<&Surface>,
1379        input: &str,
1380        post: impl FnOnce(Term) -> R + Send,
1381    ) -> Result<R, ParseError> {
1382        let depth = syntactic_depth(input);
1383        if depth > MAX_SYNTACTIC_DEPTH {
1384            return Err(ParseError::Unsupported {
1385                what: format!("a term nested {depth} constructs deep"),
1386                why: format!(
1387                    "the kernel checks terms at most {} deep, and a text nested more than {} deep \
1388                     cannot denote one",
1389                    crate::type_checker::MAX_TERM_DEPTH,
1390                    MAX_SYNTACTIC_DEPTH
1391                ),
1392            });
1393        }
1394        on_stack_for(depth, move || Self::parse_raw_in(surface, input).map(post))
1395    }
1396
1397    /// The raw parse: the whole input, markers intact.
1398    fn parse_raw_in<'i>(surface: Option<&'i Surface>, input: &'i str) -> Result<Term, ParseError> {
1399        match surface {
1400            Some(s) => {
1401                let expanded = s.expand_macros(input)?;
1402                let mut parser = TermParser {
1403                    input: &expanded,
1404                    pos: 0,
1405                    bound_vars: HashSet::new(),
1406                    surface: Some(s),
1407                };
1408                parser.parse_whole()
1409            }
1410            None => {
1411                let mut parser = TermParser {
1412                    input,
1413                    pos: 0,
1414                    bound_vars: HashSet::new(),
1415                    surface: None,
1416                };
1417                parser.parse_whole()
1418            }
1419        }
1420    }
1421
1422    /// The legacy door's post-processing: strip the kind markers and report the LEADING run of
1423    /// eager implicits.
1424    ///
1425    /// ★ A STRICT IMPLICIT STOPS THE RUN. The count model inserts its metavariables
1426    /// unconditionally, and Lean's `⦃a⦄` is precisely the binder that must NOT be
1427    /// inserted when no explicit argument follows. Under-inserting leaves the term the
1428    /// polymorphic function it already was; over-inserting emits a metavariable nothing can
1429    /// solve and the kernel then reports an unbound variable far from here. Callers that need
1430    /// the real answer read [`parse_with_binder_kinds`](Self::parse_with_binder_kinds).
1431    fn finish_implicits(raw: Term) -> (Term, usize) {
1432        let (mut t, implicits) = Self::count_implicits(raw);
1433        Self::strip_kind_markers_in_place(&mut t);
1434        (t, implicits)
1435    }
1436
1437    /// The leading-implicit count, leaving the term's kind markers exactly where they are.
1438    ///
1439    /// ★ THE COUNT STOPS AT A STRICT IMPLICIT, AND THAT IS THE RULE, NOT AN OVERSIGHT.
1440    /// `implicit_args` drives an UNCONDITIONAL insertion of that many leading arguments, and
1441    /// Lean's `⦃x : T⦄` is exactly the binder that must not be inserted when nothing follows it
1442    /// (`Lean/Elab/App.lean:726`, `processStrictImplicitArg`: insert only `if (← hasArgsToProcess)`,
1443    /// else `finalize`). A count cannot express a condition, so the honest thing a count can say
1444    /// about `⦃A : Type⦄ -> A -> A` is zero -- under-inserting leaves the polymorphic function,
1445    /// which is still correct, where over-inserting emits a metavariable nothing can solve.
1446    fn count_implicits(raw: Term) -> (Term, usize) {
1447        let implicits = Self::binder_kinds_of(&raw)
1448            .iter()
1449            .take_while(|k| **k == BinderKind::Implicit)
1450            .count();
1451        (raw, implicits)
1452    }
1453
1454    fn finish_kinds(raw: Term) -> (Term, Vec<BinderKind>) {
1455        let kinds = Self::binder_kinds_of(&raw);
1456        let mut t = raw;
1457        Self::strip_kind_markers_in_place(&mut t);
1458        (t, kinds)
1459    }
1460
1461    /// Parse a notation or macro TEMPLATE, with its holes already in scope so each one reads as a
1462    /// variable the expansion substitutes rather than as a global nobody declared.
1463    pub(super) fn parse_template(input: &'a str, holes: &[String]) -> Result<Term, ParseError> {
1464        let mut parser = Self {
1465            input,
1466            pos: 0,
1467            bound_vars: holes.iter().cloned().collect(),
1468            surface: None,
1469        };
1470        parser.parse_whole().map(|mut t| {
1471            Self::strip_kind_markers_in_place(&mut t);
1472            t
1473        })
1474    }
1475
1476    /// Parse a term, also returning how many leading implicit binders `{x:T}` it had —
1477    /// the implicit-argument count the elaborator uses at application sites.
1478    pub fn parse_with_implicits(input: &'a str) -> Result<(Term, usize), ParseError> {
1479        Self::entry(None, input, Self::finish_implicits)
1480    }
1481
1482    /// The whole input, or nothing. Binder-kind markers are still ON the result; every public
1483    /// entry point above strips them.
1484    fn parse_whole(&mut self) -> Result<Term, ParseError> {
1485        let parser = self;
1486        let term = parser.parse_term()?;
1487        parser.skip_whitespace();
1488        // ★ THE WHOLE INPUT, OR NOTHING. This returned here, so anything after the first complete
1489        // term was discarded in silence — `Nat -> Nat garbage here` parsed as `Nat -> Nat`. None of
1490        // the six callers in `command_parser` re-checked the position, so nothing downstream could
1491        // notice either. The `at_end` helper below already existed; it was the application loop's
1492        // stop condition and never a completeness check, which is the entire bug.
1493        // ★ ONE TRAILING `.` IS A TERMINATOR, NOT INPUT. `Zero.` is a complete term followed by a
1494        // full stop — the dot-projection parser deliberately declines to treat a dot before a
1495        // non-identifier as a projection (`surface_sugar::a_bare_trailing_dot_is_not_a_projection`
1496        // states exactly that), and this language ends its sentences with periods. Refusing it
1497        // would have made the completeness check reject ordinary well-formed input, which is how a
1498        // guard like this turns into a bug of its own. Exactly one, and nothing after it: `Zero..`
1499        // and `Zero. garbage` are still refused.
1500        if parser.input[parser.pos..].starts_with('.') {
1501            parser.pos += 1;
1502            parser.skip_whitespace();
1503        }
1504        if !parser.at_end() {
1505            // The BYTE POSITION and the remainder, because "trailing input" without a location is
1506            // the anonymous refusal this codebase keeps having to fix.
1507            return Err(ParseError::TrailingInput {
1508                at: parser.pos,
1509                rest: parser.input[parser.pos..].trim_end().to_string(),
1510            });
1511        }
1512        Ok(term)
1513    }
1514
1515    /// Parse a term (top-level).
1516    fn parse_term(&mut self) -> Result<Term, ParseError> {
1517        self.skip_whitespace();
1518
1519        if self.peek_keyword("fun") {
1520            self.parse_lambda()
1521        } else if self.peek_keyword("forall") {
1522            self.parse_forall()
1523        } else if self.peek_keyword("fix") {
1524            self.parse_fix()
1525        } else if self.peek_keyword("match") {
1526            self.parse_match()
1527        } else if self.peek_keyword("let") {
1528            self.parse_let()
1529        } else if self.at_bracket(Self::STRICT_IMPLICIT_OPEN_ASCII) {
1530            // BEFORE the single brace, exactly as Lean's `bracketedBinder` tries
1531            // `strictImplicitBinder` before `implicitBinder` (`Lean/Parser/Term.lean:381`):
1532            // `{{` must win, or its first brace is eaten as an eager implicit whose binder name
1533            // is then `{`.
1534            self.parse_grouped_binder(
1535                BinderKind::StrictImplicit,
1536                Self::STRICT_IMPLICIT_OPEN_ASCII,
1537                Self::STRICT_IMPLICIT_CLOSE_ASCII,
1538            )
1539        } else if self.peek_char('{') {
1540            self.parse_grouped_binder(BinderKind::Implicit, "{", "}")
1541        } else if self.peek_char('\u{2983}') && !self.at_atom_notation() {
1542            self.parse_grouped_binder(BinderKind::StrictImplicit, "\u{2983}", "\u{2984}")
1543        } else if self.peek_char('[') && !self.at_atom_notation() {
1544            self.parse_instance_binder()
1545        } else {
1546            self.parse_arrow()
1547        }
1548    }
1549
1550    /// Does a BRACKETING notation in scope start here? `[` opens an instance binder in this
1551    /// grammar and a declared `[a, b]` list notation in many surfaces, and a user's own notation
1552    /// must keep winning where it always did -- a new builtin that shadowed a declared one would
1553    /// change the meaning of existing text rather than add to it.
1554    fn at_atom_notation(&self) -> bool {
1555        self.surface
1556            .is_some_and(|s| s.atom_notation_at(&self.input[self.pos..]).is_some())
1557    }
1558
1559    /// Parse a let-expression `let x (":" T)? ":=" e "in" body`.
1560    ///
1561    /// ★ AN ASCRIPTION NOBODY CHECKED. The `: T` was parsed and THROWN AWAY -- the comment here
1562    /// said so -- and the whole form desugared to `body[x := e]`, so `let n : Bool := Zero in n`
1563    /// was a claim the language accepted and no kernel ever saw. Lean checks it
1564    /// (`let x : T := e; b` elaborates `e` AGAINST `T`), and so does this kernel the moment the
1565    /// ascription is allowed to reach it: `Term::Let` is a kernel term whose typing rule is
1566    /// `infer_sort(ty)` then `check_type(value, ty)` then zeta -- in `type_checker.rs` AND,
1567    /// independently, in `recheck.rs`, so `double_check` sees the same claim both times.
1568    ///
1569    /// The UN-ascribed form keeps the substitution desugaring it always had. There is no claim to
1570    /// check there, and emitting a `Let` node for it would put a binder in every term that used to
1571    /// hold none -- a cost paid by every `let` in the suite to buy nothing.
1572    fn parse_let(&mut self) -> Result<Term, ParseError> {
1573        self.consume_keyword("let")?;
1574        self.skip_whitespace();
1575        let name = self.parse_ident()?;
1576        self.skip_whitespace();
1577        let ascribed = if self.at_binder_annotation() {
1578            self.advance();
1579            let ty = self.parse_term()?;
1580            self.skip_whitespace();
1581            Some(ty)
1582        } else {
1583            None
1584        };
1585        self.expect_str(":=")?;
1586        self.skip_whitespace();
1587        let value = self.parse_term()?;
1588        self.skip_whitespace();
1589        // `let x : T := v; b` — the KERNEL's let, binder kept. See [`Self::parse_kernel_let_body`].
1590        if self.try_consume(";") {
1591            let Some(ty) = ascribed else {
1592                return Err(ParseError::Expected {
1593                    expected: format!(
1594                        "`: <type>` on `let {name}` \u{2014} a `;` let keeps its binder in the kernel \
1595                         term, and the kernel's let states the type it binds at"
1596                    ),
1597                    found: ";".to_string(),
1598                });
1599            };
1600            return self.parse_kernel_let_body(name, ty, value);
1601        }
1602        self.consume_keyword("in")?;
1603
1604        let was_bound = self.bound_vars.contains(&name);
1605        self.bound_vars.insert(name.clone());
1606        let body = self.parse_term();
1607        if !was_bound {
1608            self.bound_vars.remove(&name);
1609        }
1610        let body = body?;
1611
1612        // ★ THE BODY IS ζ-SUBSTITUTED EITHER WAY; THE `Let` NODE CARRIES ONLY THE CLAIM.
1613        //
1614        // Two things have to be true at once. The ascription must reach a kernel -- that is the
1615        // whole point -- and the REDUCTION behaviour of this surface must not change, because a
1616        // `let` has always meant its substituted body here. Keeping the bound name inside the node
1617        // would change it: `term_store::zeta_or_share_opt` deliberately SHARES rather than
1618        // duplicates when the name occurs many times, so `let y : Int := 5 in mul y y` would
1619        // survive into normal form as a let-expression and `Eval` would print one where the writer
1620        // asked for a value. Substituting first makes the node's body closed over `name`, so the
1621        // share/expand decision cannot arise and the emitted value is byte-identical to the
1622        // un-ascribed form's.
1623        //
1624        // What the node still does is the only thing it was added for: `infer_type` runs
1625        // `infer_sort(ty)` then `check_type(value, ty)` before it ever looks at the body, and
1626        // `recheck` does the same independently -- so `let n : Bool := Zero in n` is refused twice,
1627        // by two kernels, where it used to be accepted by neither because neither was told.
1628        let body = crate::type_checker::substitute(&body, &name, &value);
1629        match ascribed {
1630            Some(ty) => Ok(Term::Let {
1631                name,
1632                ty: Box::new(ty),
1633                value: Box::new(value),
1634                body: Box::new(body),
1635            }),
1636            None => Ok(body),
1637        }
1638    }
1639
1640    /// The body of `let x : T := v; b`, with `x` in scope, as the kernel's own `Term::Let`.
1641    ///
1642    /// ★ TWO LETS, AND THE DIFFERENCE IS THE BINDER. `let … in b` substitutes `v` into `b` and keeps
1643    /// only the ascription as a claim (see [`Self::parse_let`]) — the right reading for source, and
1644    /// the one every existing `let` has always had. But the kernel HAS a let whose body still
1645    /// mentions its binder: the Lean importer builds one for every `letE` it does not share, the
1646    /// term store keeps one where substitution would duplicate work, and both kernels check and
1647    /// ζ-reduce it. A term like that had no spelling at all — printing it as `let … in` would read
1648    /// back as the substituted body, a different term. `;` is Lean's own separator for exactly this
1649    /// let, and it is the spelling that reads back as the node it was printed from.
1650    fn parse_kernel_let_body(
1651        &mut self,
1652        name: String,
1653        ty: Term,
1654        value: Term,
1655    ) -> Result<Term, ParseError> {
1656        let was_bound = self.bound_vars.contains(&name);
1657        self.bound_vars.insert(name.clone());
1658        let body = self.parse_term();
1659        if !was_bound {
1660            self.bound_vars.remove(&name);
1661        }
1662        Ok(Term::Let {
1663            name,
1664            ty: Box::new(ty),
1665            value: Box::new(value),
1666            body: Box::new(body?),
1667        })
1668    }
1669
1670    /// Parse a BRACKETED binder group `{x y : T}` or `⦃x y : T⦄` (optionally followed
1671    /// by `->`) and the body -- one `Pi` per name, all at the shared type, each carrying `kind`.
1672    ///
1673    /// `{A B : Type}` is n binders sharing one type, the brace-counterpart of `(x y : T)`, and
1674    /// each one is its own ARGUMENT -- so the telescope grows by the number of names, not by the
1675    /// number of groups, or an application would insert too few metavariables. A group may NOT
1676    /// carry a default: see the refusal below, and `Lean/Parser/Term.lean:334` for whose clause
1677    /// `binderDefault` is.
1678    fn parse_grouped_binder(
1679        &mut self,
1680        kind: BinderKind,
1681        open: &str,
1682        close: &str,
1683    ) -> Result<Term, ParseError> {
1684        self.skip_whitespace();
1685        if !self.consume_bracket(open) {
1686            return Err(ParseError::Expected {
1687                expected: format!("'{open}'"),
1688                found: self.found_here(),
1689            });
1690        }
1691        self.skip_whitespace();
1692        let names = self
1693            .try_scan_binder_names()
1694            .ok_or_else(|| ParseError::Expected {
1695                expected: "a binder name".to_string(),
1696                found: self.found_here(),
1697            })?;
1698        self.skip_whitespace();
1699        if !self.at_binder_annotation() {
1700            return Err(ParseError::Expected {
1701                expected: format!("`:` and a type for the binder group `{open}{close}`"),
1702                found: self.found_here(),
1703            });
1704        }
1705        self.advance();
1706        let declared = self.parse_term()?;
1707        self.skip_whitespace();
1708        // ★ ONLY AN EXPLICIT BINDER MAY CARRY A DEFAULT, AND THAT IS NOT A STYLE RULE.
1709        // Lean gives the `binderDefault`/`binderTactic` clause to `explicitBinder` ALONE
1710        // (`Lean/Parser/Term.lean:334`); `implicitBinder` (:344) and `strictImplicitBinder` (:361)
1711        // have no such clause, and the elaborator agrees -- `getOptParamDefault?` and
1712        // `getAutoParamTactic?` are consulted inside `processExplicitArg`
1713        // (`Lean/Elab/App.lean:614`) and nowhere else, so `processImplicitArg` could not honour a
1714        // default even if one could be written.
1715        //
1716        // We accepted it, and that was the dangerous combination: the default was recorded at a
1717        // position `elaborate_app_against` fills with `Fill::Infer`, so the value the writer
1718        // supplied was SILENTLY DISCARDED. A default that is never consulted is a wrong answer
1719        // with no diagnostic, which is strictly worse than a refusal -- so refuse, and say which
1720        // binder would have had to be explicit for the default to mean anything.
1721        if self.peek_str(":=") {
1722            return Err(ParseError::Unsupported {
1723                what: format!(
1724                    "a default value on the `{open}{close}` binder `{}`",
1725                    names.join(" ")
1726                ),
1727                why: "an implicit parameter is filled by unification, never from a default, so                       the value could never be used -- write it as an explicit `(x : T := v)`                       parameter, which is the only binder Lean gives a default to"
1728                    .to_string(),
1729            });
1730        }
1731        self.close_binder_group(close, &names)?;
1732
1733        self.skip_whitespace();
1734        self.try_consume("->"); // optional arrow between the binder and the body
1735
1736        let body_type = self.parse_body_with(&names)?;
1737        Ok(Self::pi_telescope(
1738            names,
1739            Self::mark_kind(kind, declared),
1740            body_type,
1741        ))
1742    }
1743
1744    /// Parse an INSTANCE binder `[C x] -> B` or `[inst : C x] -> B` and the body.
1745    ///
1746    /// ★ `ParamKind::Instance` HAD NO SPELLING. The elaborator has resolved instance parameters
1747    /// from the database since the typeclass package landed, and the only way to install one was
1748    /// a Rust caller reaching in through `Context::set_binder_kinds` -- which nothing outside the
1749    /// test suite ever did. So `[Inhabited A]` was a parameter kind the language could not write
1750    /// down, and every class-constrained declaration had to be spelled as an ordinary explicit
1751    /// argument the caller passes by hand.
1752    ///
1753    /// The anonymous form binds `"_"`, exactly as `A -> B` does: an instance argument is found,
1754    /// not named. The named form is Lean's `[inst : C x]`, and its name is in scope in the body.
1755    fn parse_instance_binder(&mut self) -> Result<Term, ParseError> {
1756        self.expect_char('[')?;
1757        let after_open = self.pos;
1758        // `[ name+ : C x ]` -- the NAMED form. The lookahead rewinds, exactly as `parse_parens`
1759        // does, so `[Inhabited Nat]` (two name-shaped tokens, no colon) still reads as a class
1760        // type rather than as a binder group missing its annotation.
1761        if let Some(names) = self.try_scan_binder_names() {
1762            self.skip_whitespace();
1763            if self.at_binder_annotation() {
1764                self.advance();
1765                let class_type = self.parse_term()?;
1766                self.skip_whitespace();
1767                self.expect_char(']')?;
1768                self.skip_whitespace();
1769                self.try_consume("->");
1770                let body = self.parse_body_with(&names)?;
1771                return Ok(Self::pi_telescope(
1772                    names,
1773                    Self::mark_kind(BinderKind::Instance, class_type),
1774                    body,
1775                ));
1776            }
1777        }
1778        self.pos = after_open;
1779        let class_type = self.parse_term()?;
1780        self.skip_whitespace();
1781        self.expect_char(']')?;
1782        self.skip_whitespace();
1783        self.try_consume("->");
1784        let body = self.parse_term()?;
1785        Ok(Term::Pi {
1786            param: "_".to_string(),
1787            param_type: Box::new(Self::mark_kind(BinderKind::Instance, class_type)),
1788            body_type: Box::new(body),
1789        })
1790    }
1791
1792    /// Parse arrow type: A -> B -> C (right associative).
1793    ///
1794    /// ★ THE RIGHT-HAND SIDE IS A WHOLE TERM. It used to recurse into `parse_arrow`, one level
1795    /// BELOW `parse_term` -- so everything `parse_term` dispatches on (an implicit, strict or
1796    /// instance binder group, a `forall`, a `fun`, a `let`, a `match`, a `fix`) was unreachable
1797    /// after the first arrow, and a telescope could only ever OPEN with one. `Nat -> {A : Type}
1798    /// -> A -> A` and `Nat -> forall x : Nat, P x` are ordinary Lean and had no spelling here for
1799    /// no reason but that the recursion skipped a level. The arrow stays RIGHT-ASSOCIATIVE:
1800    /// `parse_term` falls through to `parse_arrow` for everything that is not one of those
1801    /// keywords, so an ordinary `A -> B -> C` takes exactly the path it always took.
1802    fn parse_arrow(&mut self) -> Result<Term, ParseError> {
1803        let left = self.parse_notation_expr(0)?;
1804
1805        self.skip_whitespace();
1806        if self.try_consume("->") {
1807            let right = self.parse_term()?;
1808            // A -> B is sugar for Π(_:A). B
1809            Ok(Term::Pi {
1810                param: "_".to_string(),
1811                param_type: Box::new(left),
1812                body_type: Box::new(right),
1813            })
1814        } else {
1815            Ok(left)
1816        }
1817    }
1818
1819    /// The user-notation layer: precedence climbing over the infix and postfix notations in
1820    /// scope. With none declared this is one call straight through to [`parse_app`](Self::parse_app).
1821    fn parse_notation_expr(&mut self, min_precedence: u32) -> Result<Term, ParseError> {
1822        let mut lhs = self.parse_app()?;
1823        let Some(surface) = self.surface else {
1824            return Ok(lhs);
1825        };
1826        loop {
1827            self.skip_whitespace();
1828            let Some(m) = surface.operator_notation_at(&self.input[self.pos..], min_precedence)
1829            else {
1830                return Ok(lhs);
1831            };
1832            let pieces = m.pieces();
1833            let right_precedence = m.right_precedence();
1834            let mut args: HashMap<String, Term> = HashMap::new();
1835            let (_, lead_hole) = &pieces[0];
1836            args.insert(
1837                lead_hole
1838                    .clone()
1839                    .expect("an operator notation begins with a hole"),
1840                lhs,
1841            );
1842            for (index, (token, hole)) in pieces.iter().enumerate().skip(1) {
1843                match (token, hole) {
1844                    (Some(tok), _) => {
1845                        self.skip_whitespace();
1846                        if !self.try_consume(tok) {
1847                            return Err(ParseError::Expected {
1848                                expected: format!("`{tok}` of the notation"),
1849                                found: self.remaining().chars().take(8).collect::<String>(),
1850                            });
1851                        }
1852                    }
1853                    (_, Some(name)) => {
1854                        let last = index + 1 == pieces.len();
1855                        let operand = if last {
1856                            self.parse_notation_expr(right_precedence)?
1857                        } else {
1858                            self.parse_notation_expr(0)?
1859                        };
1860                        args.insert(name.clone(), operand);
1861                    }
1862                    _ => unreachable!("a piece is a token or a hole"),
1863                }
1864            }
1865            lhs = m.expand(surface, &args);
1866        }
1867    }
1868
1869    /// A prefix or bracketing notation at atom position, if one starts here.
1870    fn parse_atom_notation(&mut self) -> Result<Option<Term>, ParseError> {
1871        let Some(surface) = self.surface else {
1872            return Ok(None);
1873        };
1874        let Some(m) = surface.atom_notation_at(&self.input[self.pos..]) else {
1875            return Ok(None);
1876        };
1877        let pieces = m.pieces();
1878        let closed = m.is_closed();
1879        let mut args: HashMap<String, Term> = HashMap::new();
1880        for (index, (token, hole)) in pieces.iter().enumerate() {
1881            match (token, hole) {
1882                (Some(tok), _) => {
1883                    self.skip_whitespace();
1884                    if !self.try_consume(tok) {
1885                        return Err(ParseError::Expected {
1886                            expected: format!("`{tok}` of the notation"),
1887                            found: self.remaining().chars().take(8).collect::<String>(),
1888                        });
1889                    }
1890                }
1891                (_, Some(name)) => {
1892                    let last = index + 1 == pieces.len();
1893                    // A prefix operator's operand binds tightly (application level); a bracketed
1894                    // one is delimited by its own closing token, so it may be any term.
1895                    let operand = if last && !closed {
1896                        self.parse_app()?
1897                    } else {
1898                        self.parse_notation_expr(0)?
1899                    };
1900                    args.insert(name.clone(), operand);
1901                }
1902                _ => unreachable!("a piece is a token or a hole"),
1903            }
1904        }
1905        Ok(Some(m.expand(surface, &args)))
1906    }
1907
1908    /// Does a notation token stop an application here? An operator or a closing bracket of a
1909    /// notation in scope ends the argument list; a notation's OPENING token does not, so
1910    /// `f \u{27e6} 5 \u{27e7}` still applies `f` to the bracketed form.
1911    fn at_notation_stop(&self) -> bool {
1912        self.surface
1913            .is_some_and(|s| s.stops_application(&self.input[self.pos..]))
1914    }
1915
1916    /// Parse application: f x y z (left associative), with an optional trailing ELLIPSIS.
1917    fn parse_app(&mut self) -> Result<Term, ParseError> {
1918        let mut func = self.parse_atom()?;
1919
1920        loop {
1921            let before_space = self.pos;
1922            self.skip_whitespace();
1923            // `f ..` -- the ELLIPSIS: "fill every remaining argument with `_`". It must be
1924            // SEPARATED from the function by whitespace, because `Zero..` is a complete term
1925            // followed by a sentence terminator and one dot too many, and
1926            // `term_parser_total_lock::one_trailing_full_stop_is_a_terminator_and_not_input` pins
1927            // that it stays refused -- a grammar addition that quietly repaired malformed input
1928            // would be a bug introduced by a feature. Nothing may follow an ellipsis in a spine,
1929            // so this ends the application.
1930            if self.pos > before_space && self.at_ellipsis() {
1931                self.pos += "..".len();
1932                return Ok(Term::App(
1933                    Box::new(func),
1934                    Box::new(Term::Global(Self::ELLIPSIS_MARKER.to_string())),
1935                ));
1936            }
1937            // Check if we can parse another atom
1938            // Stop at: ), ->, =>, ,, |, with, return, end, ., EOF, or keywords
1939            if self.at_end()
1940                || self.peek_char(')')
1941                || self.peek_char('}')
1942                || self.peek_char('{')
1943                // The three brackets that CLOSE a binder group. Without them an application
1944                // inside one runs past its own closer -- `⦃A : Type⦄ -> A` would read `Type`
1945                // and then try to apply it to `⦄`, and `[Inhabited Nat] -> Nat` likewise.
1946                || self.peek_char(']')
1947                || self.peek_char('⦃')
1948                || self.peek_char('⦄')
1949                || self.peek_char('.')
1950                || self.peek_char(',')
1951                || self.peek_char(';')
1952                || self.peek_char('|')
1953                || self.peek_char('⟩')
1954                || self.peek_str("->")
1955                || self.peek_str("=>")
1956                || self.peek_str(":=")
1957                || self.peek_keyword("with")
1958                || self.peek_keyword("return")
1959                || self.peek_keyword("end")
1960                || self.peek_keyword("in")
1961                || self.at_notation_stop()
1962            {
1963                break;
1964            }
1965
1966            let arg = self.parse_atom()?;
1967            func = Term::App(Box::new(func), Box::new(arg));
1968        }
1969
1970        Ok(func)
1971    }
1972
1973    /// Is an ELLIPSIS `..` at the current position? Exactly two dots: `...` is not one (and stays
1974    /// the trailing input it always was), and a `.field` projection begins with a single dot.
1975    fn at_ellipsis(&self) -> bool {
1976        self.peek_str("..") && !self.peek_str("...")
1977    }
1978
1979    /// Parse an atom: (term), number, string, sort, or identifier
1980    fn parse_atom(&mut self) -> Result<Term, ParseError> {
1981        let base = self.parse_atom_base()?;
1982        self.parse_dot_postfix(base)
1983    }
1984
1985    /// Parse the base of an atom, before any postfix projection.
1986    fn parse_atom_base(&mut self) -> Result<Term, ParseError> {
1987        self.skip_whitespace();
1988
1989        // A prefix or bracketing notation is an atom of the grammar.
1990        if let Some(t) = self.parse_atom_notation()? {
1991            return Ok(t);
1992        }
1993
1994        // Anonymous constructor ⟨e₁, …, eₙ⟩ (E3)
1995        if self.peek_char('⟨') {
1996            return self.parse_anon_ctor();
1997        }
1998
1999        // Check for negative number
2000        if self.peek_char('-') {
2001            if let Some(lit) = self.try_parse_negative_number()? {
2002                return Ok(lit);
2003            }
2004        }
2005
2006        // Check for positive number
2007        if let Some(c) = self.peek() {
2008            if c.is_ascii_digit() {
2009                return self.parse_number_literal();
2010            }
2011        }
2012
2013        // Check for string literal
2014        if self.peek_char('"') {
2015            return self.parse_string_literal();
2016        }
2017
2018        // `@[annotation] atom` -- a TRANSPARENT annotation, `Term::Annotated`: the printer's spelling
2019        // of one, read back to the same term. `@[` never begins an explicit-all name.
2020        if self.peek_str("@[") {
2021            return self.parse_annotated();
2022        }
2023
2024        // `@f` / `@Outer.value` -- EXPLICIT-ALL. It binds TIGHTLY to a name: `@ f` with a space is
2025        // not one, and neither is `@(f)`, exactly as in Lean. The guard is `scan_name` rather than
2026        // a character class, so the one component grammar decides here too and a quoted name works.
2027        if self.peek_char('@') {
2028            let after = self.pos + '@'.len_utf8();
2029            if scan_name(&self.input[after..]).is_some() {
2030                self.pos = after;
2031                let head = self.parse_atom()?;
2032                return Ok(Term::App(
2033                    Box::new(Term::Global(Self::EXPLICIT_ALL_MARKER.to_string())),
2034                    Box::new(head),
2035                ));
2036            }
2037        }
2038
2039        if self.peek_char('(') {
2040            self.parse_parens()
2041        } else {
2042            self.parse_ident_or_sort()
2043        }
2044    }
2045
2046    /// `@[binder <info>] a`, `@[source "<file:line:column>"] a` or `@[mdata "<key>" "<value>"] a`
2047    /// -- an [`Annotation`](crate::Annotation) on the atom `a`, whose binder information is one of
2048    /// Lean's four `BinderInfo` names.
2049    fn parse_annotated(&mut self) -> Result<Term, ParseError> {
2050        use crate::{Annotation, Provenance, SourcePosition};
2051        self.pos += "@[".len();
2052        self.skip_whitespace();
2053        let annotation = if self.try_consume_keyword("binder") {
2054            self.skip_whitespace();
2055            let info = scan_name(&self.input[self.pos..])
2056                .and_then(|(name, len)| Some((ParamKind::from_lean_binder_info(&name)?, len)));
2057            let Some((kind, len)) = info else {
2058                return Err(ParseError::Expected {
2059                    expected: "a binder information: `default`, `implicit`, `strictImplicit` or \
2060                               `instImplicit`"
2061                        .to_string(),
2062                    found: self.found_here(),
2063                });
2064            };
2065            self.pos += len;
2066            Annotation::Binder(kind)
2067        } else if self.try_consume_keyword("source") {
2068            self.skip_whitespace();
2069            let text = self.annotation_text()?;
2070            let position = SourcePosition::parse(&text).ok_or_else(|| ParseError::Expected {
2071                expected: "a source position `file:line:column`".to_string(),
2072                found: format!("{text:?}"),
2073            })?;
2074            Annotation::Source(Provenance::Position(position))
2075        } else if self.try_consume_keyword("mdata") {
2076            self.skip_whitespace();
2077            let key = self.annotation_text()?;
2078            self.skip_whitespace();
2079            let value = self.annotation_text()?;
2080            Annotation::Source(Provenance::LeanMetadata { key, value })
2081        } else {
2082            return Err(ParseError::Expected {
2083                expected: "an annotation: `binder`, `source` or `mdata`".to_string(),
2084                found: self.found_here(),
2085            });
2086        };
2087        self.skip_whitespace();
2088        self.expect_char(']')?;
2089        let term = self.parse_atom()?;
2090        Ok(Term::Annotated {
2091            annotation,
2092            term: Box::new(term),
2093        })
2094    }
2095
2096    /// One string literal of an annotation, as its text.
2097    fn annotation_text(&mut self) -> Result<String, ParseError> {
2098        if !self.peek_char('"') {
2099            return Err(ParseError::Expected {
2100                expected: "a string literal".to_string(),
2101                found: self.found_here(),
2102            });
2103        }
2104        match self.parse_string_literal()? {
2105            Term::Lit(Literal::Text(text)) => Ok(text),
2106            other => Err(ParseError::Expected {
2107                expected: "a string literal".to_string(),
2108                found: other.to_string(),
2109            }),
2110        }
2111    }
2112
2113    /// Apply zero or more TIGHT postfix projections `.field` to `base` (E4). Tight means no
2114    /// intervening whitespace: `p.fst` projects, while `p .` / `p.` at a clause end stays a
2115    /// terminator, and only a `.` immediately followed by an identifier start is a field.
2116    fn parse_dot_postfix(&mut self, mut base: Term) -> Result<Term, ParseError> {
2117        while self.peek_char('.') {
2118            let after = self.pos + '.'.len_utf8();
2119            // `name.{ℓ, …}` — a universe-polymorphic CONSTANT at explicit levels (`Term::Const`).
2120            if self.input[after..].starts_with('{') {
2121                let name = Self::constant_name(&base)?;
2122                self.pos = after + '{'.len_utf8();
2123                let levels = self.parse_level_list()?;
2124                base = Term::Const { name, levels };
2125                continue;
2126            }
2127            let Some((field, len)) = Self::dot_component(&self.input[after..], &base) else {
2128                break;
2129            };
2130            self.pos = after + len;
2131            base = Term::App(
2132                Box::new(Term::App(
2133                    Box::new(Term::Global(crate::elaborate::DOT_MARKER.to_string())),
2134                    Box::new(base),
2135                )),
2136                Box::new(Term::Global(field)),
2137            );
2138        }
2139        Ok(base)
2140    }
2141
2142    /// The NAME COMPONENT after a `.`, and the bytes it occupies -- or `None` when the dot is not
2143    /// a projection at all and the caller should stop.
2144    ///
2145    /// ★ ONE COMPONENT GRAMMAR, BOTH DOORS. This used to admit a component only when the next
2146    /// character satisfied `is_alphabetic() || '_'` -- [`scan_name`]'s FIRST rule rather than its
2147    /// whole rule -- so a guillemet component was unreachable and `Outer.«a b»` was a name no term
2148    /// could spell. The declaration door asks the term door whether a name is spellable
2149    /// (`surface::Name::is_spelled_by`), so it had to refuse a name Lean accepts
2150    /// (`def Foo.«a b»`) to keep that invariant true. Asking `scan_name` -- the very function
2151    /// the declaration door asks -- makes the two agree by construction rather than by review.
2152    ///
2153    /// A NUMERIC component is Lean's anonymous projection `p.1`, and it is refused after a
2154    /// LITERAL for exactly the reason a lexer refuses it there: `3.14` is a decimal numeral, not a
2155    /// projection out of `3`, and turning input this grammar REFUSES into something that silently
2156    /// parses is a bug introduced by a feature. `command_parser::sentence_end` names `3.14` in its
2157    /// own doc comment as a thing that must be able to sit inside a term without ending the
2158    /// sentence, so the collision is reachable rather than theoretical.
2159    fn dot_component(rest: &str, base: &Term) -> Option<(String, usize)> {
2160        if let Some(found) = scan_name(rest) {
2161            return Some(found);
2162        }
2163        if matches!(base, Term::Lit(_)) {
2164            return None;
2165        }
2166        let digits = rest.len() - rest.trim_start_matches(|c: char| c.is_ascii_digit()).len();
2167        if digits == 0 {
2168            return None;
2169        }
2170        Some((rest[..digits].to_string(), digits))
2171    }
2172
2173    /// Parse an anonymous constructor `⟨e₁, …, eₙ⟩` into the reserved marker application
2174    /// `⟨anon⟩ e₁ … eₙ` (E3). The elaborator resolves the marker against the expected type.
2175    fn parse_anon_ctor(&mut self) -> Result<Term, ParseError> {
2176        self.expect_char('⟨')?;
2177        let mut comps = Vec::new();
2178        self.skip_whitespace();
2179        if !self.peek_char('⟩') {
2180            loop {
2181                self.skip_whitespace();
2182                // A trailing `..` fills the REMAINING fields from the expected type. It ends the
2183                // component list, because there is nothing after "the rest".
2184                if self.at_ellipsis() {
2185                    self.pos += "..".len();
2186                    comps.push(Term::Global(Self::ELLIPSIS_MARKER.to_string()));
2187                    break;
2188                }
2189                comps.push(self.parse_term()?);
2190                self.skip_whitespace();
2191                if self.try_consume(",") {
2192                    self.skip_whitespace();
2193                    continue;
2194                }
2195                break;
2196            }
2197        }
2198        self.expect_char('⟩')?;
2199        let mut t = Term::Global(crate::elaborate::ANON_CTOR_MARKER.to_string());
2200        for c in comps {
2201            t = Term::App(Box::new(t), Box::new(c));
2202        }
2203        Ok(t)
2204    }
2205
2206    /// Parse a literal that begins with a digit, at ARBITRARY PRECISION where the kind allows it.
2207    ///
2208    /// The digits go through [`crate::int_lit`], the canonical constructor: a value that fits `i64`
2209    /// is a `Literal::Int` exactly as before, and one that does not is a `Literal::BigInt`. Before
2210    /// the arbitrary-precision reading the parse was `str::parse::<i64>`, so a numeral wider than a
2211    /// machine word was `InvalidNumber` -- a value the kernel holds, compares and REDUCES that no
2212    /// source text could spell.
2213    ///
2214    /// What FOLLOWS the digits, with no space, decides the literal's kind — see
2215    /// [`Self::parse_numeric`]. Plain digits are an `Int`, as they always were.
2216    fn parse_number_literal(&mut self) -> Result<Term, ParseError> {
2217        let start = self.pos;
2218        self.parse_numeric(start, false)
2219    }
2220
2221    /// The literal whose digits start at `self.pos`; `sign_start` is where its `-` stood, if
2222    /// `negative`.
2223    ///
2224    /// ★ ONE LEXER FOR EVERY `Literal`. The kernel carries seven literal kinds and the surface
2225    /// could spell two of them, so a `Nat` literal (every Lean numeral the importer reads), a
2226    /// `Float`, a `Duration`, a `Date` and a `Moment` were kernel terms with no source text at all.
2227    /// Each now has exactly one spelling, chosen so no two kinds collide and no spelling this
2228    /// grammar used to accept changes meaning:
2229    ///
2230    /// | written | literal |
2231    /// |---|---|
2232    /// | `42`, `-42` | `Int` (`BigInt` past `i64`) |
2233    /// | `42n` | `Nat` |
2234    /// | `1.5f64`, `-2.5e-3f64`, `1e300f64` | `Float`, by its shortest exact decimal |
2235    /// | `0x7ff8000000000000f64` | `Float`, by its IEEE-754 bits — every NaN payload, ±∞ |
2236    /// | `5s`, `-250ms`, `3min` | `Duration` (the imperative language's unit table) |
2237    /// | `2026-05-20`, `-0044-03-15` | `Date` |
2238    /// | `2026-05-20T10:00:00.5Z` | `Moment` (UTC, nanosecond precision) |
2239    ///
2240    /// Every form except plain digits was previously either a parse error or — for a letter right
2241    /// after the digits — an application of a numeral to a name, which denotes nothing. A suffix
2242    /// that names no kind is REFUSED, never read as that application: `2x` is a typo, not `2 x`.
2243    fn parse_numeric(&mut self, sign_start: usize, negative: bool) -> Result<Term, ParseError> {
2244        let digits_start = self.pos;
2245        while self.peek().is_some_and(|c| c.is_ascii_digit()) {
2246            self.advance();
2247        }
2248        let digits = self.input[digits_start..self.pos].to_string();
2249        let rest = &self.input[self.pos..];
2250
2251        if !negative && digits == "0" && rest.starts_with('x') {
2252            return self.parse_float_bits();
2253        }
2254        if digits.len() >= 4 && Self::starts_month_day(rest) {
2255            return self.parse_calendar(&digits, negative);
2256        }
2257        // A fraction and an exponent make the numeral a DECIMAL, which must then name its type.
2258        let mut decimal = false;
2259        if rest.starts_with('.') && rest[1..].chars().next().is_some_and(|c| c.is_ascii_digit()) {
2260            self.advance();
2261            while self.peek().is_some_and(|c| c.is_ascii_digit()) {
2262                self.advance();
2263            }
2264            decimal = true;
2265        }
2266        if Self::starts_exponent(&self.input[self.pos..]) {
2267            self.advance();
2268            if self.peek_char('+') || self.peek_char('-') {
2269                self.advance();
2270            }
2271            while self.peek().is_some_and(|c| c.is_ascii_digit()) {
2272                self.advance();
2273            }
2274            decimal = true;
2275        }
2276        let number_end = self.pos;
2277        // The suffix is a whole word — a letter, then letters, digits and `_` — so `f64` and
2278        // `min` are each read in one piece and looked up exactly.
2279        if self.peek().is_some_and(|c| c.is_alphabetic()) {
2280            while self
2281                .peek()
2282                .is_some_and(|c| c.is_alphanumeric() || c == '_' || c == '\'')
2283            {
2284                self.advance();
2285            }
2286        }
2287        let suffix = &self.input[number_end..self.pos];
2288        let written = &self.input[sign_start..number_end];
2289        if suffix == "f64" {
2290            return written
2291                .parse::<f64>()
2292                .map(|x| Term::Lit(Literal::Float(x)))
2293                .map_err(|_| ParseError::InvalidNumber(format!("{written}f64")));
2294        }
2295        if decimal {
2296            // ★ A BARE DECIMAL IS REFUSED. `3.14` is not a projection out of `3`, and it is not a
2297            // float either until it says so: the kernel has more than one literal a decimal could
2298            // mean to a reader, and a spelling that quietly picked one would turn input this
2299            // grammar has always refused into a parse (`X_termparser_extra` locks the refusal).
2300            return Err(ParseError::InvalidNumber(format!(
2301                "{written}{suffix} \u{2014} a decimal literal names its type: write `{written}f64`"
2302            )));
2303        }
2304        let magnitude = crate::BigInt::parse_decimal(&digits)
2305            .ok_or_else(|| ParseError::InvalidNumber(digits.clone()))?;
2306        let value = if negative {
2307            crate::BigInt::zero().sub(&magnitude)
2308        } else {
2309            magnitude
2310        };
2311        match suffix {
2312            "" => Ok(Term::Lit(crate::int_lit(value))),
2313            "n" if negative => Err(ParseError::InvalidNumber(format!(
2314                "-{digits}n \u{2014} a `Nat` literal is a natural number and has no sign"
2315            ))),
2316            "n" => Ok(Term::Lit(Literal::Nat(value))),
2317            unit => match DURATION_UNITS.iter().find(|(u, _)| *u == unit) {
2318                Some((_, nanos)) => {
2319                    let total = value.mul(&crate::BigInt::from_i64(*nanos));
2320                    total
2321                        .to_i64()
2322                        .map(|n| Term::Lit(Literal::Duration(n)))
2323                        .ok_or_else(|| {
2324                            ParseError::InvalidNumber(format!(
2325                                "{}{digits}{unit} \u{2014} a duration is a signed 64-bit count of \
2326                             nanoseconds, and this one does not fit",
2327                                if negative { "-" } else { "" }
2328                            ))
2329                        })
2330                }
2331                None => Err(ParseError::InvalidNumber(format!(
2332                    "{}{digits}{unit} \u{2014} a numeral's suffix names what it counts: `n` for a \
2333                     natural number, or a duration unit (ns, us, ms, s, min, h). Write a space to \
2334                     apply a numeral to a name",
2335                    if negative { "-" } else { "" }
2336                ))),
2337            },
2338        }
2339    }
2340
2341    /// `-DD-DD` — the month and day of a calendar literal, right after its year.
2342    fn starts_month_day(rest: &str) -> bool {
2343        let b = rest.as_bytes();
2344        b.len() >= 6
2345            && b[0] == b'-'
2346            && b[1].is_ascii_digit()
2347            && b[2].is_ascii_digit()
2348            && b[3] == b'-'
2349            && b[4].is_ascii_digit()
2350            && b[5].is_ascii_digit()
2351    }
2352
2353    /// `e5`, `E-7`, `e+10` — a decimal exponent, which makes the numeral before it a float.
2354    fn starts_exponent(rest: &str) -> bool {
2355        let b = rest.as_bytes();
2356        match b {
2357            [b'e' | b'E', d, ..] if d.is_ascii_digit() => true,
2358            [b'e' | b'E', b'+' | b'-', d, ..] if d.is_ascii_digit() => true,
2359            _ => false,
2360        }
2361    }
2362
2363    /// `0x` + sixteen hex digits + `f64`: a `Float` by its IEEE-754 BITS. The one spelling that
2364    /// reaches every value, because `Literal::Float` compares by bits — two NaNs with different
2365    /// payloads are different literals, and no decimal names either.
2366    fn parse_float_bits(&mut self) -> Result<Term, ParseError> {
2367        let at = self.pos;
2368        let rest = &self.input[at..];
2369        let hex = rest
2370            .get(1..17)
2371            .filter(|h| h.chars().all(|c| c.is_ascii_hexdigit()));
2372        let tail_ok = rest.get(17..).is_some_and(|t| {
2373            t.starts_with("f64")
2374                && !t[3..]
2375                    .chars()
2376                    .next()
2377                    .is_some_and(|c| c.is_alphanumeric() || c == '_')
2378        });
2379        match (hex, tail_ok) {
2380            (Some(hex), true) => {
2381                let bits = u64::from_str_radix(hex, 16).expect("sixteen hex digits");
2382                self.pos = at + 20;
2383                Ok(Term::Lit(Literal::Float(f64::from_bits(bits))))
2384            }
2385            _ => Err(ParseError::InvalidNumber(format!(
2386                "0{} \u{2014} a float by its bits is `0x` followed by exactly sixteen hex digits and \
2387                 `f64`",
2388                rest.chars().take(20).collect::<String>()
2389            ))),
2390        }
2391    }
2392
2393    /// `YYYY-MM-DD`, then optionally `THH:MM:SS(.fffffffff)?Z`: a `Date`, or a `Moment` in UTC.
2394    ///
2395    /// Proleptic Gregorian, the calendar `Literal::Date`'s display uses, with the year as a plain
2396    /// signed number of at least four digits — so every `i32` day count and every `i64` nanosecond
2397    /// instant has a spelling, and an impossible date (`2026-02-30`) is refused rather than
2398    /// rolled over into March.
2399    fn parse_calendar(&mut self, year_digits: &str, negative: bool) -> Result<Term, ParseError> {
2400        let bad = |what: String| ParseError::InvalidNumber(what);
2401        let year: i64 = year_digits
2402            .parse::<i64>()
2403            .ok()
2404            .filter(|y| *y <= 100_000_000)
2405            .ok_or_else(|| {
2406                bad(format!(
2407                    "{year_digits} \u{2014} a year this calendar cannot hold"
2408                ))
2409            })?;
2410        let year = if negative { -year } else { year };
2411        let b = &self.input.as_bytes()[self.pos..];
2412        let two = |i: usize| ((b[i] - b'0') * 10 + (b[i + 1] - b'0')) as u32;
2413        let (month, day) = (two(1), two(4));
2414        self.pos += 6;
2415        let leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
2416        let month_days = match month {
2417            1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
2418            4 | 6 | 9 | 11 => 30,
2419            2 if leap => 29,
2420            2 => 28,
2421            _ => 0,
2422        };
2423        if day == 0 || day > month_days {
2424            return Err(bad(format!(
2425                "{year}-{month:02}-{day:02} \u{2014} not a day of the calendar"
2426            )));
2427        }
2428        let days = days_from_civil(year, month, day);
2429        if !self.peek_char('T') {
2430            return i32::try_from(days)
2431                .map(|d| Term::Lit(Literal::Date(d)))
2432                .map_err(|_| bad(format!("{year}-{month:02}-{day:02} \u{2014} outside the 32-bit day range of a date")));
2433        }
2434        self.advance();
2435        let t = self.input.as_bytes()[self.pos..].to_vec();
2436        let shape = t.len() >= 8
2437            && t[0].is_ascii_digit()
2438            && t[1].is_ascii_digit()
2439            && t[2] == b':'
2440            && t[3].is_ascii_digit()
2441            && t[4].is_ascii_digit()
2442            && t[5] == b':'
2443            && t[6].is_ascii_digit()
2444            && t[7].is_ascii_digit();
2445        if !shape {
2446            return Err(bad(
2447                "a time of day `THH:MM:SS` after the date of a moment".to_string()
2448            ));
2449        }
2450        let field = |i: usize| ((t[i] - b'0') as i64) * 10 + (t[i + 1] - b'0') as i64;
2451        let (h, m, sec) = (field(0), field(3), field(6));
2452        if h > 23 || m > 59 || sec > 59 {
2453            return Err(bad(format!(
2454                "{h:02}:{m:02}:{sec:02} \u{2014} not a time of day"
2455            )));
2456        }
2457        self.pos += 8;
2458        let mut fraction: i64 = 0;
2459        if self.peek_char('.') {
2460            self.advance();
2461            let start = self.pos;
2462            while self.peek().is_some_and(|c| c.is_ascii_digit()) {
2463                self.advance();
2464            }
2465            let digits = &self.input[start..self.pos];
2466            if digits.is_empty() || digits.len() > 9 {
2467                return Err(bad(format!(
2468                    ".{digits} \u{2014} a moment's fraction is one to nine digits of a second"
2469                )));
2470            }
2471            fraction =
2472                digits.parse::<i64>().expect("ascii digits") * 10i64.pow(9 - digits.len() as u32);
2473        }
2474        if !self.peek_char('Z') {
2475            return Err(bad("the `Z` that says a moment is in UTC".to_string()));
2476        }
2477        self.advance();
2478        let seconds = days as i128 * 86_400 + (h * 3600 + m * 60 + sec) as i128;
2479        let nanos = seconds * 1_000_000_000 + fraction as i128;
2480        i64::try_from(nanos)
2481            .map(|n| Term::Lit(Literal::Moment(n)))
2482            .map_err(|_| bad("a moment outside the signed 64-bit nanosecond range".to_string()))
2483    }
2484
2485    /// Parse a string literal: "contents"
2486    fn parse_string_literal(&mut self) -> Result<Term, ParseError> {
2487        self.expect_char('"')?;
2488
2489        // Collect characters until closing quote
2490        let mut content = String::new();
2491        loop {
2492            match self.peek() {
2493                Some('"') => {
2494                    self.advance();
2495                    break;
2496                }
2497                Some('\\') => {
2498                    // Handle escape sequences
2499                    self.advance();
2500                    match self.peek() {
2501                        Some('n') => {
2502                            content.push('\n');
2503                            self.advance();
2504                        }
2505                        Some('t') => {
2506                            content.push('\t');
2507                            self.advance();
2508                        }
2509                        Some('\\') => {
2510                            content.push('\\');
2511                            self.advance();
2512                        }
2513                        Some('"') => {
2514                            content.push('"');
2515                            self.advance();
2516                        }
2517                        // `\u{…}` — a Unicode scalar by its hex code point. The escape every other
2518                        // character can be written with, so a printer can put ANY string in source
2519                        // text: a control character, a line separator, a lone NUL.
2520                        Some('u') if self.input[self.pos + 1..].starts_with('{') => {
2521                            let open = self.pos + 2;
2522                            let close = self.input[open..].find('}').map(|i| open + i);
2523                            let scalar = close
2524                                .map(|c| &self.input[open..c])
2525                                .filter(|h| {
2526                                    (1..=6).contains(&h.len())
2527                                        && h.chars().all(|c| c.is_ascii_hexdigit())
2528                                })
2529                                .and_then(|h| u32::from_str_radix(h, 16).ok())
2530                                .and_then(char::from_u32);
2531                            match (scalar, close) {
2532                                (Some(c), Some(close)) => {
2533                                    content.push(c);
2534                                    self.pos = close + 1;
2535                                }
2536                                _ => {
2537                                    return Err(ParseError::Expected {
2538                                        expected: "`\\u{…}` holding one to six hex digits of a Unicode scalar value"
2539                                            .to_string(),
2540                                        found: self.input[self.pos..].chars().take(12).collect(),
2541                                    })
2542                                }
2543                            }
2544                        }
2545                        Some(c) => {
2546                            content.push(c);
2547                            self.advance();
2548                        }
2549                        None => return Err(ParseError::UnexpectedEof),
2550                    }
2551                }
2552                Some(c) => {
2553                    content.push(c);
2554                    self.advance();
2555                }
2556                None => return Err(ParseError::UnexpectedEof),
2557            }
2558        }
2559
2560        Ok(Term::Lit(Literal::Text(content)))
2561    }
2562
2563    /// A negative literal, or `None` when the `-` is not a numeral's sign at all -- so a declared
2564    /// prefix or infix `-` notation still reads as one.
2565    ///
2566    /// A FAILED ATTEMPT MUST NOT CONSUME INPUT. This used to `advance()` past the `-` and the digits
2567    /// and THEN return `None` when the value did not fit an `i64`, leaving the parser's position
2568    /// past a literal nobody had read. `-9223372036854775809 Nat` therefore parsed as `Nat`, with
2569    /// the numeral gone in silence, and `-9223372036854775808` -- `i64::MIN`, whose digits do not
2570    /// fit `i64` as a POSITIVE -- had no spelling at all. Silently reading a prefix of the input is
2571    /// the one failure a proof kernel's parser must not have (`term_parser_total_lock` is entirely
2572    /// about it). Arbitrary precision removes the overflow case; once a digit follows the `-` the
2573    /// literal is COMMITTED, and a malformed one is an error that names it rather than a `None`
2574    /// that lets the caller read something else.
2575    fn try_parse_negative_number(&mut self) -> Result<Option<Term>, ParseError> {
2576        if !self.peek_char('-') {
2577            return Ok(None);
2578        }
2579        let after_dash = self.pos + '-'.len_utf8();
2580        if !self.input[after_dash..]
2581            .chars()
2582            .next()
2583            .is_some_and(|c| c.is_ascii_digit())
2584        {
2585            return Ok(None);
2586        }
2587        let sign_start = self.pos;
2588        self.pos = after_dash;
2589        self.parse_numeric(sign_start, true).map(Some)
2590    }
2591
2592    /// Parse a parenthesized form. THREE productions share the opening `(`, and one token of
2593    /// lookahead separates them:
2594    ///
2595    /// * `( name := e )` -- a NAMED ARGUMENT, emitted as [`Self::NAMED_ARG_MARKER`] `name e`.
2596    /// * `( name+ : T )`, `( name+ : T := e )`, `( name+ : T := by tac )` -- an EXPLICIT dependent
2597    ///   BINDER, the counterpart of the `{x : T} -> body` this parser already read. Every name in
2598    ///   the group is in scope in the body, so `(A : Type) -> A -> A` finally spells what only
2599    ///   `forall A : Type, A -> A` could spell before.
2600    /// * `( term )` -- an ordinary grouping.
2601    ///
2602    /// The lookahead REWINDS rather than guesses: a `(` whose contents are not `name :=` or
2603    /// `name+ :` returns to the position just after the `(` and reads an ordinary term. That is
2604    /// why `(Succ Zero)`, `(x)`, `(fun x : Nat => x)` and `(let y := 0 in y)` take exactly the
2605    /// path they always took -- and why the KEYWORD GUARD in [`Self::try_scan_binder_names`] is
2606    /// load-bearing rather than defensive: `fun` is name-shaped and is followed by a `:`.
2607    fn parse_parens(&mut self) -> Result<Term, ParseError> {
2608        self.expect_char('(')?;
2609        let after_open = self.pos;
2610        if let Some(named) = self.try_parse_named_argument()? {
2611            return Ok(named);
2612        }
2613        self.pos = after_open;
2614        if let Some(binder) = self.try_parse_explicit_binder()? {
2615            return Ok(binder);
2616        }
2617        self.pos = after_open;
2618        let term = self.parse_term()?;
2619        self.skip_whitespace();
2620        self.expect_char(')')?;
2621        Ok(term)
2622    }
2623
2624    /// `( name := e )` -- a named argument. `Ok(None)` when the contents are not one, with the
2625    /// position left dirty for [`Self::parse_parens`] to rewind; an `Err` only once `name :=` has
2626    /// been seen and the form is therefore committed.
2627    fn try_parse_named_argument(&mut self) -> Result<Option<Term>, ParseError> {
2628        self.skip_whitespace();
2629        let Some((name, len, quoted)) = scan_spelled_name(&self.input[self.pos..]) else {
2630            return Ok(None);
2631        };
2632        if !quoted && Self::is_reserved(&name) {
2633            return Ok(None);
2634        }
2635        self.pos += len;
2636        self.skip_whitespace();
2637        if !self.try_consume(":=") {
2638            return Ok(None);
2639        }
2640        let value = self.parse_term()?;
2641        self.skip_whitespace();
2642        self.expect_char(')')?;
2643        Ok(Some(Term::App(
2644            Box::new(Term::App(
2645                Box::new(Term::Global(Self::NAMED_ARG_MARKER.to_string())),
2646                Box::new(Term::Global(name)),
2647            )),
2648            Box::new(value),
2649        )))
2650    }
2651
2652    /// `( name+ : T (":=" default)? )` followed by an optional `->` and the body. `Ok(None)` when
2653    /// the contents are not a binder group, position dirty for the caller to rewind.
2654    fn try_parse_explicit_binder(&mut self) -> Result<Option<Term>, ParseError> {
2655        let Some(names) = self.try_scan_binder_names() else {
2656            return Ok(None);
2657        };
2658        self.skip_whitespace();
2659        if !self.at_binder_annotation() {
2660            return Ok(None);
2661        }
2662        self.advance();
2663        let declared = self.parse_term()?;
2664        self.skip_whitespace();
2665        let param_type = if self.try_consume(":=") {
2666            self.parse_binder_default(declared)?
2667        } else {
2668            declared
2669        };
2670        self.skip_whitespace();
2671        self.close_binder_group(")", &names)?;
2672        self.skip_whitespace();
2673        self.try_consume("->"); // the arrow between a binder and its body is optional
2674        let body = self.parse_body_with(&names)?;
2675        Ok(Some(Self::pi_telescope(names, param_type, body)))
2676    }
2677
2678    /// The `:= ...` half of a binder: a DEFAULT VALUE the caller may omit, or `by tac` -- an
2679    /// obligation a tactic discharges afresh at every call site. Either way the result is the
2680    /// declared type wrapped in the marker that says WHICH, so the binder itself stays an ordinary
2681    /// `Term::Pi` and the information travels with the type through every existing pipe.
2682    fn parse_binder_default(&mut self, declared: Term) -> Result<Term, ParseError> {
2683        let (marker, payload) = if self.try_consume_keyword("by") {
2684            self.skip_whitespace();
2685            (Self::AUTO_PARAM_MARKER, Term::Global(self.parse_ident()?))
2686        } else {
2687            self.skip_whitespace();
2688            (Self::PARAM_DEFAULT_MARKER, self.parse_term()?)
2689        };
2690        Ok(Term::App(
2691            Box::new(Term::App(
2692                Box::new(Term::Global(marker.to_string())),
2693                Box::new(declared),
2694            )),
2695            Box::new(payload),
2696        ))
2697    }
2698
2699    /// Close a binder group, naming the group in the refusal.
2700    ///
2701    /// ★ A REFUSAL THAT NAMES THE BINDER. `Expected { expected: "')'", found: "EOF" }` is what a
2702    /// declaration whose TYPE contains a `:=` reports today, because the declaration door splits
2703    /// the sentence at the first `:=` it finds anywhere -- including the one inside
2704    /// `(m : Int := 3)` -- and hands this parser the truncated text `Int -> (m : Int`. The split
2705    /// is not this parser's to fix ([`Self::find_top_level`] is the scan that does it properly),
2706    /// but the diagnosis is: a message that says WHICH binder group never closed points at the
2707    /// `(m : ...` the reader actually wrote, instead of at a parenthesis they never typed.
2708    fn close_binder_group(&mut self, close: &str, names: &[String]) -> Result<(), ParseError> {
2709        self.skip_whitespace();
2710        if self.consume_bracket(close) {
2711            return Ok(());
2712        }
2713        Err(ParseError::Expected {
2714            expected: format!(
2715                "`{}` closing the binder group for `{}`",
2716                close,
2717                names.join(" ")
2718            ),
2719            found: self.found_here(),
2720        })
2721    }
2722
2723    /// One or more binder NAMES at the current position, or `None` when this is not a binder group.
2724    ///
2725    /// A RESERVED word is never a binder name. Without that rule `(fun x : Nat => x)` reads as the
2726    /// binder group `(fun x : ...)` -- two name-shaped tokens followed by a colon -- and an
2727    /// ordinary lambda in parentheses stops parsing.
2728    fn try_scan_binder_names(&mut self) -> Option<Vec<String>> {
2729        let mut names = Vec::new();
2730        loop {
2731            self.skip_whitespace();
2732            match scan_spelled_name(&self.input[self.pos..]) {
2733                // A QUOTED reserved word is a name — the guillemets are exactly how a binder is
2734                // given one — so only the bare word stops a binder group.
2735                Some((name, _, false)) if Self::is_reserved(&name) => return None,
2736                Some((name, len, _)) => {
2737                    names.push(name);
2738                    self.pos += len;
2739                }
2740                None => break,
2741            }
2742        }
2743        if names.is_empty() {
2744            None
2745        } else {
2746            Some(names)
2747        }
2748    }
2749
2750    /// The words this grammar reserves. `Prop` and `Type` are deliberately absent: they are SORTS,
2751    /// read by [`Self::parse_ident_or_sort`], and a binder group never begins with one.
2752    fn is_reserved(name: &str) -> bool {
2753        is_reserved_word(name)
2754    }
2755
2756    /// A `:` that opens a binder ANNOTATION -- and NOT the `:=` that opens a default value, which
2757    /// is a different production. Call it at a non-whitespace position.
2758    fn at_binder_annotation(&self) -> bool {
2759        self.peek_char(':') && !self.peek_str(":=")
2760    }
2761
2762    /// Parse a term with `names` in scope, restoring the scope afterwards -- on the ERROR path too,
2763    /// so a binder from a failed parse cannot leak into a sibling term. A name already bound is
2764    /// left bound (it is shadowed here, not introduced).
2765    fn parse_body_with(&mut self, names: &[String]) -> Result<Term, ParseError> {
2766        let introduced: Vec<String> = names
2767            .iter()
2768            .filter(|n| self.bound_vars.insert((*n).clone()))
2769            .cloned()
2770            .collect();
2771        let body = self.parse_term();
2772        for n in &introduced {
2773            self.bound_vars.remove(n);
2774        }
2775        body
2776    }
2777
2778    /// `Pi(name0 : T). ... Pi(nameN : T). body` -- one binder per name, all at the same type.
2779    fn pi_telescope(names: Vec<String>, param_type: Term, body: Term) -> Term {
2780        names.into_iter().rev().fold(body, |acc, param| Term::Pi {
2781            param,
2782            param_type: Box::new(param_type.clone()),
2783            body_type: Box::new(acc),
2784        })
2785    }
2786
2787    /// Parse identifier or sort (Prop, SProp, Type, Type0, Sort ℓ).
2788    ///
2789    /// ★ A QUOTED NAME IS NEVER A SORT. `«Prop»` is the global named `Prop`, not the universe of
2790    /// propositions: the guillemets are the escape that lets a declaration or a binder be named by a
2791    /// word this grammar otherwise reads as syntax, and an escape that still meant the keyword would
2792    /// be no escape at all. Only the unquoted words below are sorts.
2793    fn parse_ident_or_sort(&mut self) -> Result<Term, ParseError> {
2794        let (ident, quoted) = self.parse_ident_spelled()?;
2795
2796        if !quoted {
2797            match ident.as_str() {
2798                // ★ `SProp` HAD NO SPELLING. The kernel HAS a definitionally-irrelevant universe --
2799                // `Universe::SProp`, with its own elimination rule in `type_checker.rs` and a corpus
2800                // case (`lean_conformance_t01_universes`) about the `0 = 1` derivation that rule prevents
2801                // -- and `Term::Sort(SProp)` PRINTS as `SProp`, so the kernel emitted a type this
2802                // parser read straight back as an undeclared global.
2803                "SProp" => return Ok(Term::Sort(Universe::SProp)),
2804                "Prop" => return Ok(Term::Sort(Universe::Prop)),
2805                "Type" => {
2806                    // Check for Type followed by a LEVEL
2807                    self.skip_whitespace();
2808                    return match self.parse_universe_level()? {
2809                        Some(n) => Ok(Term::Sort(Universe::Type(n))),
2810                        None => Ok(Term::Sort(Universe::Type(0))),
2811                    };
2812                }
2813                // ★ `Sort ℓ` — THE SORT AT ANY LEVEL, including a level that mentions universe
2814                // VARIABLES. `Type n` reaches only the concrete rungs, so a universe-polymorphic
2815                // declaration (`id.{u} : (A : Sort u) -> A -> A`) had no spelling, and neither did
2816                // any type the Lean importer builds over `Sort u`. The level is one level ATOM, so
2817                // `Sort u -> Sort v` and `f (Sort u) x` read the way they look.
2818                "Sort" => {
2819                    self.skip_whitespace();
2820                    return self.parse_level_atom().map(Term::Sort);
2821                }
2822                _ => {}
2823            }
2824            // `TypeN` (`Type0`, `Type1`) is the sort's other spelling.
2825            //
2826            // ★ AND IT HAD THE SAME CLIFF THE SPACED FORM WAS FIXED FOR. A suffix that is ALL
2827            // DIGITS is a universe level; one that does not fit `Universe::Type`'s `u32` is a level
2828            // this system does not have, and is refused exactly as the spaced form refuses it. A
2829            // suffix that is NOT all digits (`Typeclass`, `Type_x`) was never a level and is still
2830            // an ordinary name.
2831            if let Some(level) = ident.strip_prefix("Type") {
2832                if !level.is_empty() && level.chars().all(|c| c.is_ascii_digit()) {
2833                    return match level.parse() {
2834                        Ok(n) => Ok(Term::Sort(Universe::Type(n))),
2835                        Err(_) => Err(ParseError::InvalidNumber(level.to_string())),
2836                    };
2837                }
2838            }
2839        }
2840        // ★ `_` IS A HOLE, AND NEVER A NAME A TERM REFERS TO. It used to read as
2841        // `Term::Global("_")`, which is the KERNEL'S OWN match-case placeholder protocol:
2842        // `type_checker::check_type` matches a λ whose `param_type` is exactly that global and takes
2843        // the binder's type from the expected `Pi` instead. `Term::Hole` is the honest carrier:
2844        // `infer_type` answers `CannotInferHole` and the elaborator turns it into a fresh
2845        // metavariable, which is exactly Lean's `_`. Checked BEFORE the bound-variable lookup, and
2846        // for the quoted `«_»` too, because the collision it prevents does not care how `_` was
2847        // written.
2848        if ident == "_" {
2849            Ok(Term::Hole)
2850        } else if self.bound_vars.contains(&ident) {
2851            Ok(Term::Var(ident))
2852        } else {
2853            Ok(Term::Global(ident))
2854        }
2855    }
2856
2857    /// A universe LEVEL: an atom followed by any number of `+k` successors.
2858    ///
2859    /// Read STRUCTURALLY and never normalised: `u+2` is `Succ(Succ(Var u))`, `max u u` stays a
2860    /// `Max`, and the numeral `1` is `Type 0` while `0+1` is `Succ(Prop)`. The kernel decides level
2861    /// EQUIVALENCE by its own algebra; the surface's job is to say which expression was written, so
2862    /// that the printer can write back exactly the expression it was handed.
2863    fn parse_level(&mut self) -> Result<Universe, ParseError> {
2864        let mut level = self.parse_level_atom()?;
2865        loop {
2866            self.skip_whitespace();
2867            if !self.peek_char('+') {
2868                return Ok(level);
2869            }
2870            self.advance();
2871            self.skip_whitespace();
2872            let start = self.pos;
2873            while self.peek().is_some_and(|c| c.is_ascii_digit()) {
2874                self.advance();
2875            }
2876            let digits = &self.input[start..self.pos];
2877            let k: u64 = match digits.parse() {
2878                Ok(k) if (1..=MAX_LEVEL_OFFSET).contains(&k) => k,
2879                Ok(0) => {
2880                    return Err(ParseError::InvalidNumber(
2881                        "+0 \u{2014} a level successor adds at least one".to_string(),
2882                    ))
2883                }
2884                Ok(_) | Err(_) if !digits.is_empty() => {
2885                    return Err(ParseError::InvalidNumber(format!(
2886                        "+{digits} \u{2014} a level may add at most {MAX_LEVEL_OFFSET} at once"
2887                    )))
2888                }
2889                _ => {
2890                    return Err(ParseError::Expected {
2891                        expected: "a numeral after `+` in a universe level".to_string(),
2892                        found: self.found_here(),
2893                    })
2894                }
2895            };
2896            for _ in 0..k {
2897                level = Universe::Succ(Box::new(level));
2898            }
2899        }
2900    }
2901
2902    /// One universe level ATOM: a numeral, a universe variable, `max a b`, `imax a b`, or a
2903    /// parenthesised level.
2904    ///
2905    /// A numeral is Lean's level numeral: `0` is `Prop`, `n + 1` is `Type n`. A variable is any
2906    /// name; one spelled like a keyword or a sort (`max`, `Prop`, `_`) must be written `«quoted»`,
2907    /// so `Sort Prop` is refused rather than silently read as a variable named `Prop`.
2908    fn parse_level_atom(&mut self) -> Result<Universe, ParseError> {
2909        self.skip_whitespace();
2910        if self.peek_char('(') {
2911            self.advance();
2912            let level = self.parse_level()?;
2913            self.skip_whitespace();
2914            self.expect_char(')')?;
2915            return Ok(level);
2916        }
2917        if self.peek().is_some_and(|c| c.is_ascii_digit()) {
2918            let start = self.pos;
2919            while self.peek().is_some_and(|c| c.is_ascii_digit()) {
2920                self.advance();
2921            }
2922            let digits = &self.input[start..self.pos];
2923            let n: u64 = digits
2924                .parse()
2925                .map_err(|_| ParseError::InvalidNumber(digits.to_string()))?;
2926            return match n {
2927                0 => Ok(Universe::Prop),
2928                n => u32::try_from(n - 1).map(Universe::Type).map_err(|_| {
2929                    ParseError::InvalidNumber(format!(
2930                        "{digits} \u{2014} the concrete universe levels stop at {}",
2931                        u64::from(u32::MAX) + 1
2932                    ))
2933                }),
2934            };
2935        }
2936        match scan_spelled_name(&self.input[self.pos..]) {
2937            Some((name, len, false)) if name == "max" || name == "imax" => {
2938                self.pos += len;
2939                let a = Box::new(self.parse_level_atom()?);
2940                let b = Box::new(self.parse_level_atom()?);
2941                Ok(if name == "max" {
2942                    Universe::Max(a, b)
2943                } else {
2944                    Universe::IMax(a, b)
2945                })
2946            }
2947            Some((name, _, false))
2948                if name == "_" || Self::is_reserved(&name) || is_sort_word(&name) =>
2949            {
2950                Err(ParseError::Expected {
2951                    expected: format!(
2952                        "a universe level \u{2014} `{name}` is a word of the grammar; a universe \
2953                         variable spelled that way is written \u{ab}{name}\u{bb}"
2954                    ),
2955                    found: name,
2956                })
2957            }
2958            Some((name, len, _)) => {
2959                self.pos += len;
2960                Ok(Universe::Var(name))
2961            }
2962            None => Err(ParseError::Expected {
2963                expected:
2964                    "a universe level: a numeral, a universe variable, `max a b`, `imax a b` \
2965                           or a parenthesised level"
2966                        .to_string(),
2967                found: self.found_here(),
2968            }),
2969        }
2970    }
2971
2972    /// `ℓ, ℓ, …}` — the level ARGUMENTS of a constant, after its `.{`. May be empty.
2973    fn parse_level_list(&mut self) -> Result<Vec<Universe>, ParseError> {
2974        let mut levels = Vec::new();
2975        self.skip_whitespace();
2976        if self.try_consume("}") {
2977            return Ok(levels);
2978        }
2979        loop {
2980            levels.push(self.parse_level()?);
2981            self.skip_whitespace();
2982            if self.try_consume(",") {
2983                continue;
2984            }
2985            if self.try_consume("}") {
2986                return Ok(levels);
2987            }
2988            return Err(ParseError::Expected {
2989                expected: "`,` or `}` in a list of universe levels".to_string(),
2990                found: self.found_here(),
2991            });
2992        }
2993    }
2994
2995    /// The constant a `.{…}` instantiates: a global, or a qualified name read as a projection chain
2996    /// of globals. `.{` can only follow a CONSTANT's name, so a chain before it is one hierarchical
2997    /// name rather than field access — Lean's `Nat.rec.{u}` is one constant.
2998    fn constant_name(base: &Term) -> Result<String, ParseError> {
2999        fn walk(t: &Term, out: &mut Vec<String>) -> Result<(), ParseError> {
3000            match t {
3001                Term::Global(n) => {
3002                    out.push(n.clone());
3003                    Ok(())
3004                }
3005                Term::App(f, field) => match (f.as_ref(), field.as_ref()) {
3006                    (Term::App(head, receiver), Term::Global(field)) if matches!(head.as_ref(), Term::Global(m) if m == crate::elaborate::DOT_MARKER) =>
3007                    {
3008                        walk(receiver, out)?;
3009                        out.push(field.clone());
3010                        Ok(())
3011                    }
3012                    _ => Err(ParseError::Expected {
3013                        expected: "a constant's name before `.{` \u{2014} universe arguments \
3014                                   instantiate a declared constant"
3015                            .to_string(),
3016                        found: format!("{t}"),
3017                    }),
3018                },
3019                Term::Var(n) => Err(ParseError::Expected {
3020                    expected: format!(
3021                        "a constant before `.{{` \u{2014} `{n}` is a local variable, and a local \
3022                         takes no universe arguments"
3023                    ),
3024                    found: n.clone(),
3025                }),
3026                other => Err(ParseError::Expected {
3027                    expected: "a constant's name before `.{` \u{2014} universe arguments \
3028                               instantiate a declared constant"
3029                        .to_string(),
3030                    found: format!("{other}"),
3031                }),
3032            }
3033        }
3034        let mut parts = Vec::new();
3035        walk(base, &mut parts)?;
3036        Ok(parts.join("."))
3037    }
3038
3039    /// Parse a lambda `fun <binders> (":" T)? "=>" body`.
3040    ///
3041    /// A binder is a bare identifier -- whose type is POSTPONED, left as a `Term::Hole` for the
3042    /// elaborator to fill from the expected type, which is what `fun x => Succ x` means and what
3043    /// this parser could not express at all -- or a BRACKETED GROUP, whose bracket says how the
3044    /// argument is supplied: `(x y : T)`, `{A}`, `⦃A⦄`, `[Monoid A]`. A trailing
3045    /// `: T` types every binder that still has none, exactly as Lean's `optType` does, so
3046    /// `fun x y : Nat => x` binds BOTH at `Nat` and the one-binder `fun x : T => body` this parser
3047    /// has always read is the same production at n = 1.
3048    ///
3049    /// A `Hole` left here is not a hole smuggled into a proof: `infer_type` answers
3050    /// `CannotInferHole`, so an un-elaborated `fun x => ...` fails loudly rather than checking
3051    /// against everything.
3052    fn parse_lambda(&mut self) -> Result<Term, ParseError> {
3053        self.consume_keyword("fun")?;
3054        let (binders, body) = self.parse_abstraction("=>")?;
3055        Ok(binders
3056            .into_iter()
3057            .rev()
3058            .fold(body, |acc, (param, param_type, kind)| Term::Lambda {
3059                param,
3060                param_type: Box::new(Self::mark_kind(kind, param_type)),
3061                body: Box::new(acc),
3062            }))
3063    }
3064
3065    /// Parse `forall <binders> (":" T)? "," body` -- the binder grammar of [`Self::parse_lambda`],
3066    /// building `Pi` instead of `Lambda`.
3067    fn parse_forall(&mut self) -> Result<Term, ParseError> {
3068        self.consume_keyword("forall")?;
3069        let (binders, body) = self.parse_abstraction(",")?;
3070        Ok(binders
3071            .into_iter()
3072            .rev()
3073            .fold(body, |acc, (param, param_type, kind)| Term::Pi {
3074                param,
3075                param_type: Box::new(Self::mark_kind(kind, param_type)),
3076                body_type: Box::new(acc),
3077            }))
3078    }
3079
3080    /// The binder telescope shared by `fun` and `forall`: binders, an optional SHARED annotation,
3081    /// the `separator`, then the body -- parsed with every binder in scope, and with each group's
3082    /// names entering scope only AFTER its own type is read, so `(x : Nat) (y : Vec x)` resolves
3083    /// `x` and `(x : Vec x)` still does not. Returns the binders in SOURCE order.
3084    fn parse_abstraction(
3085        &mut self,
3086        separator: &str,
3087    ) -> Result<(Vec<(String, Term, BinderKind)>, Term), ParseError> {
3088        let mut introduced: Vec<String> = Vec::new();
3089        let parsed = self.parse_abstraction_in_scope(separator, &mut introduced);
3090        // ★ THE SCOPE IS RESTORED ON EVERY PATH, THE ERROR PATH INCLUDED. A refused abstraction is
3091        // REWOUND and re-read as an ordinary term -- that is exactly what `parse_parens` does to
3092        // separate `(fun x : Nat => x)` from a binder group -- so a binder the failed attempt left
3093        // in scope makes a later `Global` of that spelling read as a `Var`: a name bound by a
3094        // parse that did not happen. `parse_body_with` already states this rule for the binder
3095        // GROUPS; the telescope's own `?`s were the one place it was not kept, and hoisting the
3096        // restore out of the loop makes the rule structural rather than repeated.
3097        for n in &introduced {
3098            self.bound_vars.remove(n);
3099        }
3100        parsed
3101    }
3102
3103    /// [`parse_abstraction`](Self::parse_abstraction) with the binders LEFT in scope -- every
3104    /// name it puts in `bound_vars` for the first time is recorded in `introduced` for its caller
3105    /// to take back out.
3106    fn parse_abstraction_in_scope(
3107        &mut self,
3108        separator: &str,
3109        introduced: &mut Vec<String>,
3110    ) -> Result<(Vec<(String, Term, BinderKind)>, Term), ParseError> {
3111        let mut binders: Vec<(String, Option<Term>, BinderKind)> = Vec::new();
3112        loop {
3113            self.skip_whitespace();
3114            if self.peek_str(separator) || self.at_binder_annotation() {
3115                break;
3116            }
3117            let (names, declared, kind) = match self.abstraction_bracket() {
3118                Some((kind, open, close)) => {
3119                    self.consume_bracket(open);
3120                    let (names, declared) = self.parse_abstraction_group(kind, close)?;
3121                    (names, declared, kind)
3122                }
3123                None => (vec![self.parse_ident()?], None, BinderKind::Explicit),
3124            };
3125            for name in names {
3126                if self.bound_vars.insert(name.clone()) {
3127                    introduced.push(name.clone());
3128                }
3129                binders.push((name, declared.clone(), kind));
3130            }
3131        }
3132        if binders.is_empty() {
3133            return Err(ParseError::Expected {
3134                expected: "at least one binder".to_string(),
3135                found: self.found_here(),
3136            });
3137        }
3138        let (shared, body) = self.finish_abstraction(separator)?;
3139        let binders = binders
3140            .into_iter()
3141            .map(|(name, ty, kind)| {
3142                (
3143                    name,
3144                    ty.or_else(|| shared.clone()).unwrap_or(Term::Hole),
3145                    kind,
3146                )
3147            })
3148            .collect();
3149        Ok((binders, body))
3150    }
3151
3152    /// The BRACKET a binder group of an abstraction telescope opens with, and the [`BinderKind`]
3153    /// that bracket declares -- or `None` at a bare identifier binder.
3154    ///
3155    /// ★ A TELESCOPE COULD ONLY BIND EXPLICITLY. `fun` and `forall` read `(x y : T)` and a bare
3156    /// name and nothing else, so `theorem foo {α} [Monoid α] (a : α)` -- the shape of very nearly
3157    /// every declaration in mathlib -- had no spelling in an abstraction at all. The Pi-position
3158    /// grammar has read all four brackets since wave 2; this is the same four, at the one place
3159    /// they were missing. A `⦃` or `[` that opens a NOTATION in scope is not a bracket here,
3160    /// exactly as in [`Self::parse_term`]: a user's own notation must keep winning where it
3161    /// always did, or a new builtin changes the meaning of existing text instead of adding to it.
3162    fn abstraction_bracket(&self) -> Option<(BinderKind, &'static str, &'static str)> {
3163        if self.peek_char('(') {
3164            Some((BinderKind::Explicit, "(", ")"))
3165        } else if self.at_bracket(Self::STRICT_IMPLICIT_OPEN_ASCII) {
3166            // `funStrictImplicitBinder <|> funImplicitBinder` -- Lean tries the doubled bracket
3167            // first here too (`Lean/Parser/Term.lean:493`), for the same reason.
3168            Some((
3169                BinderKind::StrictImplicit,
3170                Self::STRICT_IMPLICIT_OPEN_ASCII,
3171                Self::STRICT_IMPLICIT_CLOSE_ASCII,
3172            ))
3173        } else if self.peek_char('{') {
3174            Some((BinderKind::Implicit, "{", "}"))
3175        } else if self.peek_char('\u{2983}') && !self.at_atom_notation() {
3176            Some((BinderKind::StrictImplicit, "\u{2983}", "\u{2984}"))
3177        } else if self.peek_char('[') && !self.at_atom_notation() {
3178            Some((BinderKind::Instance, "[", "]"))
3179        } else {
3180            None
3181        }
3182    }
3183
3184    /// One binder group of an abstraction telescope, its opening bracket already consumed:
3185    /// `(x y : T)`, `(x)`, `{A}`, `⦃A : T⦄`, `[inst : C x]`, or the ANONYMOUS `[C x]`.
3186    ///
3187    /// Returns the names and the declared type -- `None` where the group writes none, leaving the
3188    /// type to the telescope's trailing `: T` annotation and, failing that, to the elaborator as a
3189    /// `Term::Hole`. An INSTANCE group has no such form: `[inst]` names a binder with no class to
3190    /// resolve it from, so the contents of a `[...]` that is not `name+ :` are read as the class
3191    /// TYPE and the binder is `_`, which is what Lean writes and what an instance argument is --
3192    /// found, not named. The lookahead REWINDS, exactly as [`Self::parse_parens`] does, so
3193    /// `[Monoid A]` (two name-shaped tokens, no colon) is never mistaken for a binder group whose
3194    /// annotation is missing.
3195    fn parse_abstraction_group(
3196        &mut self,
3197        kind: BinderKind,
3198        close: &str,
3199    ) -> Result<(Vec<String>, Option<Term>), ParseError> {
3200        let after_open = self.pos;
3201        if let Some(names) = self.try_scan_binder_names() {
3202            self.skip_whitespace();
3203            if self.at_binder_annotation() {
3204                self.advance();
3205                let declared = self.parse_term()?;
3206                self.close_binder_group(close, &names)?;
3207                return Ok((names, Some(declared)));
3208            }
3209            if kind != BinderKind::Instance && self.consume_bracket(close) {
3210                return Ok((names, None));
3211            }
3212        }
3213        if kind == BinderKind::Instance {
3214            self.pos = after_open;
3215            let class_type = self.parse_term()?;
3216            self.close_binder_group(close, &["_".to_string()])?;
3217            return Ok((vec!["_".to_string()], Some(class_type)));
3218        }
3219        Err(ParseError::Expected {
3220            expected: "a binder name".to_string(),
3221            found: self.found_here(),
3222        })
3223    }
3224
3225    /// The optional shared annotation, the separator, and the body of an abstraction. Split out so
3226    /// [`Self::parse_abstraction`] can restore its binder scope on every path, success or failure.
3227    fn finish_abstraction(&mut self, separator: &str) -> Result<(Option<Term>, Term), ParseError> {
3228        let shared = if self.at_binder_annotation() {
3229            self.advance();
3230            Some(self.parse_term()?)
3231        } else {
3232            None
3233        };
3234        self.skip_whitespace();
3235        self.expect_str(separator)?;
3236        let body = self.parse_term()?;
3237        Ok((shared, body))
3238    }
3239
3240    /// The character at the current position, for an error message.
3241    fn found_here(&self) -> String {
3242        self.peek()
3243            .map(|c| c.to_string())
3244            .unwrap_or_else(|| "EOF".to_string())
3245    }
3246
3247    /// Parse fix: `fix f => body`, or a MUTUAL block `fix f => b with g => c … return g`.
3248    ///
3249    /// ★ `Term::MutualFix` HAD NO SPELLING. It is the body of every mutual inductive's derived
3250    /// eliminator — `Even.rec`'s fixpoint calls `Odd.rec`'s — so every mutual block the kernel
3251    /// registers holds terms no source text could write. The block reads like the single form it
3252    /// extends: each member `name => body`, joined by `with` as Coq joins mutual fixpoints, and
3253    /// closed by `return` naming the member the whole term denotes. Every member's name is bound in
3254    /// EVERY body. A one-member block is still a block — `fix f => b return f` is `MutualFix`, and
3255    /// `fix f => b` alone is `Fix` — because the kernel holds the two as different terms.
3256    fn parse_fix(&mut self) -> Result<Term, ParseError> {
3257        self.consume_keyword("fix")?;
3258        self.skip_whitespace();
3259        let name = self.parse_ident()?;
3260        self.skip_whitespace();
3261        self.expect_str("=>")?;
3262
3263        // The recursion name is in scope in the body, and OUT of scope again on every path --
3264        // the error path included. A binder a FAILED parse leaves behind makes a later `Global` of
3265        // that spelling read as a `Var`: a name bound by a parse that did not happen. One rule,
3266        // stated the same way in `parse_body_with`, `parse_abstraction`, `parse_let` and here.
3267        let was_bound = self.bound_vars.contains(&name);
3268        self.bound_vars.insert(name.clone());
3269        let body = self.parse_term();
3270        if !was_bound {
3271            self.bound_vars.remove(&name);
3272        }
3273        let body = body?;
3274        self.skip_whitespace();
3275        if !self.peek_keyword("with") && !self.peek_keyword("return") {
3276            return Ok(Term::Fix {
3277                name,
3278                body: Box::new(body),
3279            });
3280        }
3281        self.parse_mutual_fix(name, body)
3282    }
3283
3284    /// The rest of `fix f₀ => b₀ with f₁ => b₁ … return fᵢ`, the first member already read.
3285    ///
3286    /// A body can mention a member whose name is written only AFTER it, so no single left-to-right
3287    /// pass can have every name in scope. Each body is read with the names seen so far bound, and
3288    /// every remaining `Global` spelled like a member is then turned into that member's variable —
3289    /// sound because a member name SHADOWS any global of that spelling in every body, exactly as a
3290    /// binder does, so a `Global` of that spelling can only be one of the members.
3291    fn parse_mutual_fix(&mut self, first: String, first_body: Term) -> Result<Term, ParseError> {
3292        let mut defs = vec![(first, first_body)];
3293        let mut introduced: Vec<String> = Vec::new();
3294        let parsed = (|| -> Result<String, ParseError> {
3295            for (n, _) in &defs {
3296                if self.bound_vars.insert(n.clone()) {
3297                    introduced.push(n.clone());
3298                }
3299            }
3300            while self.try_consume_keyword("with") {
3301                self.skip_whitespace();
3302                let name = self.parse_ident()?;
3303                self.skip_whitespace();
3304                self.expect_str("=>")?;
3305                if self.bound_vars.insert(name.clone()) {
3306                    introduced.push(name.clone());
3307                }
3308                let body = self.parse_term()?;
3309                self.skip_whitespace();
3310                defs.push((name, body));
3311            }
3312            if !self.try_consume_keyword("return") {
3313                return Err(ParseError::Expected {
3314                    expected:
3315                        "`return <member>` \u{2014} a mutual `fix` names the member it denotes"
3316                            .to_string(),
3317                    found: self.found_here(),
3318                });
3319            }
3320            self.skip_whitespace();
3321            self.parse_ident()
3322        })();
3323        for n in &introduced {
3324            self.bound_vars.remove(n);
3325        }
3326        let selected = parsed?;
3327        let names: Vec<String> = defs.iter().map(|(n, _)| n.clone()).collect();
3328        let index = match names.iter().filter(|n| **n == selected).count() {
3329            1 => names
3330                .iter()
3331                .position(|n| *n == selected)
3332                .expect("counted once"),
3333            0 => {
3334                return Err(ParseError::Expected {
3335                    expected: format!("one of the block's members ({})", names.join(", ")),
3336                    found: selected,
3337                })
3338            }
3339            _ => {
3340                return Err(ParseError::Unsupported {
3341                    what: format!("a mutual `fix` naming `{selected}` twice"),
3342                    why: "`return` could not say which of them the term denotes".to_string(),
3343                })
3344            }
3345        };
3346        let defs = defs
3347            .into_iter()
3348            .map(|(n, b)| (n, Self::bind_members(&b, &names)))
3349            .collect();
3350        Ok(Term::MutualFix { defs, index })
3351    }
3352
3353    /// `term` with every `Global` spelled like one of `names` turned into that name's variable —
3354    /// skipping the three places a `Global` is a LABEL rather than a reference: a named argument's
3355    /// parameter name, a projection's field, and an auto-param's tactic. A raw match clause's
3356    /// PATTERN is skipped too: a name there is a constructor or a pattern variable, never a member.
3357    fn bind_members(term: &Term, names: &[String]) -> Term {
3358        let recur = |t: &Term| Self::bind_members(t, names);
3359        if let Some((pattern, body)) = super::raw_match::as_case(term) {
3360            return super::raw_match::case(pattern.clone(), recur(body));
3361        }
3362        match term {
3363            Term::Global(n) if names.contains(n) => Term::Var(n.clone()),
3364            Term::App(f, x) => {
3365                if let Term::App(head, first) = f.as_ref() {
3366                    if let Term::Global(m) = head.as_ref() {
3367                        if m == Self::NAMED_ARG_MARKER || m == Self::AUTO_PARAM_MARKER {
3368                            let (label, payload) = if m == Self::NAMED_ARG_MARKER {
3369                                (first.as_ref().clone(), recur(x))
3370                            } else {
3371                                (recur(first), x.as_ref().clone())
3372                            };
3373                            return Term::App(
3374                                Box::new(Term::App(head.clone(), Box::new(label))),
3375                                Box::new(payload),
3376                            );
3377                        }
3378                        if m == crate::elaborate::DOT_MARKER {
3379                            return Term::App(
3380                                Box::new(Term::App(head.clone(), Box::new(recur(first)))),
3381                                x.clone(),
3382                            );
3383                        }
3384                    }
3385                }
3386                Term::App(Box::new(recur(f)), Box::new(recur(x)))
3387            }
3388            Term::Pi {
3389                param,
3390                param_type,
3391                body_type,
3392            } => Term::Pi {
3393                param: param.clone(),
3394                param_type: Box::new(recur(param_type)),
3395                body_type: Box::new(recur(body_type)),
3396            },
3397            Term::Lambda {
3398                param,
3399                param_type,
3400                body,
3401            } => Term::Lambda {
3402                param: param.clone(),
3403                param_type: Box::new(recur(param_type)),
3404                body: Box::new(recur(body)),
3405            },
3406            Term::Match {
3407                discriminant,
3408                motive,
3409                cases,
3410            } => Term::Match {
3411                discriminant: Box::new(recur(discriminant)),
3412                motive: Box::new(recur(motive)),
3413                cases: cases.iter().map(recur).collect(),
3414            },
3415            Term::Fix { name, body } => Term::Fix {
3416                name: name.clone(),
3417                body: Box::new(recur(body)),
3418            },
3419            Term::MutualFix { defs, index } => Term::MutualFix {
3420                defs: defs.iter().map(|(n, b)| (n.clone(), recur(b))).collect(),
3421                index: *index,
3422            },
3423            Term::Let {
3424                name,
3425                ty,
3426                value,
3427                body,
3428            } => Term::Let {
3429                name: name.clone(),
3430                ty: Box::new(recur(ty)),
3431                value: Box::new(recur(value)),
3432                body: Box::new(recur(body)),
3433            },
3434            Term::Annotated { annotation, term } => Term::Annotated {
3435                annotation: annotation.clone(),
3436                term: Box::new(recur(term)),
3437            },
3438            other => other.clone(),
3439        }
3440    }
3441
3442    /// Parse match: `match e (return M)? with | C x => t | …` — constructor PATTERNS, compiled
3443    /// against the context later — or the POSITIONAL form `match e return M with c₀ | c₁ … end`.
3444    ///
3445    /// ★ THE KERNEL'S OWN `Term::Match` HAD NO SPELLING. A pattern clause names a constructor, so
3446    /// it can only be compiled once the context says which constructors exist and in what order;
3447    /// and a compiled match is not in general the term it was compiled from (the compiler chooses
3448    /// its own motive, binder types and case nesting). So a kernel match — one case per constructor,
3449    /// in registration order, each a function of the constructor's fields — could be CHECKED but
3450    /// not WRITTEN, and every projection the Lean importer lowers is one. The positional form is
3451    /// that term, read with no context at all: the cases are plain terms after `with` with NO
3452    /// leading bar (which is what tells the two forms apart), separated by `|` and closed by `end`,
3453    /// and the motive is required because the kernel's match always has one.
3454    fn parse_match(&mut self) -> Result<Term, ParseError> {
3455        self.consume_keyword("match")?;
3456        self.skip_whitespace();
3457        let discriminant = self.parse_app()?;
3458        self.skip_whitespace();
3459        // The `return <motive>` clause is OPTIONAL: when omitted, the motive is left as a
3460        // `Hole` for the elaborator to infer (`match e with …`).
3461        let motive = if self.try_consume_keyword("return") {
3462            self.skip_whitespace();
3463            let m = self.parse_app()?;
3464            self.skip_whitespace();
3465            m
3466        } else {
3467            Term::Hole
3468        };
3469        self.consume_keyword("with")?;
3470        self.skip_whitespace();
3471
3472        let mut cases = Vec::new();
3473        if self.at_positional_case() {
3474            loop {
3475                cases.push(self.parse_term()?);
3476                self.skip_whitespace();
3477                if !self.try_consume("|") {
3478                    break;
3479                }
3480            }
3481        } else {
3482            loop {
3483                self.skip_whitespace();
3484                if !self.try_consume("|") {
3485                    break;
3486                }
3487                self.skip_whitespace();
3488
3489                // Parse pattern: C x y z (constructor with binders)
3490                let case_term = self.parse_case_body()?;
3491                cases.push(case_term);
3492            }
3493        }
3494
3495        // Consume optional 'end' keyword
3496        self.skip_whitespace();
3497        let _ = self.try_consume_keyword("end");
3498
3499        Ok(Term::Match {
3500            discriminant: Box::new(discriminant),
3501            motive: Box::new(motive),
3502            cases,
3503        })
3504    }
3505
3506    /// After `with`: does a POSITIONAL case start here? Anything that begins a term does — which
3507    /// is everything except the pattern form's `|`, the closing `end`, a closing bracket, a
3508    /// separator or the end of the input, all of which leave the match with no cases, exactly as
3509    /// they always did.
3510    fn at_positional_case(&self) -> bool {
3511        match self.peek() {
3512            None => false,
3513            Some('|' | ')' | ']' | '}' | ',' | ';' | '\u{27e9}' | '\u{2984}') => false,
3514            Some('.') => false,
3515            Some(_) => {
3516                !["end", "with", "return", "in"]
3517                    .iter()
3518                    .any(|k| self.peek_keyword(k))
3519                    && !self.peek_str(":=")
3520                    && !self.peek_str("=>")
3521            }
3522        }
3523    }
3524
3525    /// Parse one pattern and keep its labels until the context can compile it.
3526    fn parse_case_body(&mut self) -> Result<Term, ParseError> {
3527        let pattern = self.parse_match_pattern()?;
3528        self.skip_whitespace();
3529        self.expect_str("=>")?;
3530        let mut binders = Vec::new();
3531        super::raw_match::candidates(&pattern, &mut binders);
3532        let newly_bound: Vec<_> = binders
3533            .iter()
3534            .filter(|name| !self.bound_vars.contains(*name))
3535            .cloned()
3536            .collect();
3537        self.bound_vars.extend(binders.iter().cloned());
3538        let parsed = self.parse_term();
3539        for name in newly_bound {
3540            self.bound_vars.remove(&name);
3541        }
3542        let mut body = parsed?;
3543        for binder in binders.into_iter().rev() {
3544            body = Term::Lambda {
3545                param: binder,
3546                param_type: Box::new(Term::Hole),
3547                body: Box::new(body),
3548            };
3549        }
3550        Ok(super::raw_match::case(pattern, body))
3551    }
3552
3553    fn parse_match_pattern(&mut self) -> Result<Term, ParseError> {
3554        let mut pattern = self.parse_match_pattern_atom()?;
3555        self.skip_whitespace();
3556        if !self.peek_str("=>") && !self.peek_char(')') {
3557            if let Term::Var(name) = pattern {
3558                pattern = Term::Global(name);
3559            } else if !matches!(pattern, Term::Global(_)) {
3560                return Err(ParseError::Expected {
3561                    expected: "constructor at the head of a pattern application".into(),
3562                    found: format!("{pattern}"),
3563                });
3564            }
3565            while !self.peek_str("=>") && !self.peek_char(')') {
3566                let argument = self.parse_match_pattern_atom()?;
3567                pattern = Term::App(Box::new(pattern), Box::new(argument));
3568                self.skip_whitespace();
3569            }
3570        }
3571        Ok(pattern)
3572    }
3573
3574    fn parse_match_pattern_atom(&mut self) -> Result<Term, ParseError> {
3575        self.skip_whitespace();
3576        if self.try_consume("(") {
3577            let pattern = self.parse_match_pattern()?;
3578            self.skip_whitespace();
3579            self.expect_str(")")?;
3580            return Ok(pattern);
3581        }
3582        if self.peek().is_some_and(|c| c.is_ascii_digit()) {
3583            let start = self.pos;
3584            while self.peek().is_some_and(|c| c.is_ascii_digit()) {
3585                self.advance();
3586            }
3587            let text = &self.input[start..self.pos];
3588            let n = text.parse::<u64>().map_err(|_| ParseError::Expected {
3589                expected: "representable natural-number pattern".into(),
3590                found: text.into(),
3591            })?;
3592            return Ok(Term::Lit(Literal::Nat(crate::BigInt::from_u64(n))));
3593        }
3594        let mut parts = vec![self.parse_ident()?];
3595        while self.peek_char('.') {
3596            let rest = &self.input[self.pos + 1..];
3597            let Some((component, len)) = scan_name(rest) else {
3598                break;
3599            };
3600            self.pos += 1 + len;
3601            parts.push(component);
3602        }
3603        let name = super::surface::Name::from_parts(parts)
3604            .expect("nonempty name")
3605            .key();
3606        if name == "_" {
3607            Ok(Term::Hole)
3608        } else {
3609            Ok(Term::Var(name))
3610        }
3611    }
3612
3613    // =========================================================================
3614    // Low-level parsing utilities
3615    // =========================================================================
3616
3617    /// [`Self::parse_ident`], also reporting whether the name was `«quoted»` — see
3618    /// [`scan_spelled_name`].
3619    fn parse_ident_spelled(&mut self) -> Result<(String, bool), ParseError> {
3620        self.skip_whitespace();
3621        let quoted = self.peek_char('\u{ab}');
3622        self.parse_ident().map(|name| (name, quoted))
3623    }
3624
3625    /// Parse an identifier (alphanumeric + underscore, starting with letter/underscore)
3626    fn parse_ident(&mut self) -> Result<String, ParseError> {
3627        self.skip_whitespace();
3628        match scan_name(&self.input[self.pos..]) {
3629            Some((name, len)) => {
3630                self.pos += len;
3631                Ok(name)
3632            }
3633            None => match self.peek() {
3634                Some(c) => Err(ParseError::Expected {
3635                    expected: "identifier".to_string(),
3636                    found: format!("{}", c),
3637                }),
3638                None => Err(ParseError::UnexpectedEof),
3639            },
3640        }
3641    }
3642
3643    /// The explicit UNIVERSE LEVEL after `Type`, if one is written: `Ok(None)` when no digits
3644    /// stand here, and an ERROR when digits stand here that no level can hold.
3645    ///
3646    /// A LEVEL THAT DOES NOT FIT IS NOT LEVEL ZERO. This used to consume the digits and return
3647    /// `None` on overflow, and the caller reads `None` as "no level was written" -- so
3648    /// `Type 99999999999999999999` became `Type 0`, silently, with the digits gone and the
3649    /// completeness guard satisfied because nothing was left over. The kernel then certified a
3650    /// claim at a universe nobody wrote. Refusing is the only honest answer: `Universe::Type`
3651    /// holds a `u32`, so a wider level is a level this system does not have.
3652    fn parse_universe_level(&mut self) -> Result<Option<u32>, ParseError> {
3653        self.skip_whitespace();
3654        let start = self.pos;
3655
3656        while let Some(c) = self.peek() {
3657            if c.is_ascii_digit() {
3658                self.advance();
3659            } else {
3660                break;
3661            }
3662        }
3663
3664        if self.pos == start {
3665            return Ok(None);
3666        }
3667        let digits = &self.input[start..self.pos];
3668        digits
3669            .parse()
3670            .map(Some)
3671            .map_err(|_| ParseError::InvalidNumber(digits.to_string()))
3672    }
3673
3674    /// Skip whitespace
3675    fn skip_whitespace(&mut self) {
3676        while let Some(c) = self.peek() {
3677            if c.is_whitespace() {
3678                self.advance();
3679            } else {
3680                break;
3681            }
3682        }
3683    }
3684
3685    /// Peek at current character
3686    fn peek(&self) -> Option<char> {
3687        self.input[self.pos..].chars().next()
3688    }
3689
3690    /// Check if we're at a specific character
3691    fn peek_char(&self, c: char) -> bool {
3692        self.peek() == Some(c)
3693    }
3694
3695    /// Check if input starts with a string at current position
3696    fn peek_str(&self, s: &str) -> bool {
3697        self.input[self.pos..].starts_with(s)
3698    }
3699
3700    /// The byte offset just past the binder bracket `bracket`, or `None` if it is not here.
3701    ///
3702    /// ★ A BINDER BRACKET MAY BE TWO OF THEM. Lean's strict-implicit brackets have an ASCII
3703    /// spelling alongside the guillemets -- `strictImplicitLeftBracket := atomic (group (symbol
3704    /// "{" >> "{")) <|> "⦃"` (`Lean/Parser/Term.lean:346`), and its `⦄` counterpart on the next
3705    /// line -- so `{{x y : A}}` is `⦃x y : A⦄`, which is the only spelling available to a writer
3706    /// with no unicode input method. Those are two separate TOKENS in Lean's grammar, and Lean
3707    /// tokenises across whitespace, so `{ {x : A} }` is the same binder; this walk says the same
3708    /// by skipping between the halves and not before the first.
3709    fn bracket_end(&self, bracket: &str) -> Option<usize> {
3710        let mut i = self.pos;
3711        for (n, c) in bracket.chars().enumerate() {
3712            if n > 0 {
3713                let rest = &self.input[i..];
3714                i += rest.len() - rest.trim_start().len();
3715            }
3716            if !self.input[i..].starts_with(c) {
3717                return None;
3718            }
3719            i += c.len_utf8();
3720        }
3721        Some(i)
3722    }
3723
3724    /// Does the binder bracket `bracket` open (or close) here? Non-consuming.
3725    fn at_bracket(&self, bracket: &str) -> bool {
3726        self.bracket_end(bracket).is_some()
3727    }
3728
3729    /// Consume the binder bracket `bracket` if it is here, leaving the position untouched if not.
3730    fn consume_bracket(&mut self, bracket: &str) -> bool {
3731        match self.bracket_end(bracket) {
3732            Some(end) => {
3733                self.pos = end;
3734                true
3735            }
3736            None => false,
3737        }
3738    }
3739
3740    /// Check if input starts with a keyword (followed by non-alphanumeric)
3741    fn peek_keyword(&self, keyword: &str) -> bool {
3742        if !self.peek_str(keyword) {
3743            return false;
3744        }
3745        // Check that keyword is not part of a longer identifier
3746        let after = self.pos + keyword.len();
3747        if after >= self.input.len() {
3748            return true;
3749        }
3750        let next_char = self.input[after..].chars().next();
3751        !next_char
3752            .map(|c| c.is_alphanumeric() || c == '_')
3753            .unwrap_or(false)
3754    }
3755
3756    /// Advance position by one character
3757    fn advance(&mut self) {
3758        if let Some(c) = self.peek() {
3759            self.pos += c.len_utf8();
3760        }
3761    }
3762
3763    /// Check if at end of input
3764    fn at_end(&self) -> bool {
3765        self.pos >= self.input.len()
3766    }
3767
3768    /// Try to consume a string, returning true if successful
3769    fn try_consume(&mut self, s: &str) -> bool {
3770        if self.peek_str(s) {
3771            self.pos += s.len();
3772            true
3773        } else {
3774            false
3775        }
3776    }
3777
3778    /// Try to consume a keyword, returning true if successful
3779    fn try_consume_keyword(&mut self, keyword: &str) -> bool {
3780        self.skip_whitespace();
3781        if self.peek_keyword(keyword) {
3782            self.pos += keyword.len();
3783            true
3784        } else {
3785            false
3786        }
3787    }
3788
3789    /// Expect a specific character
3790    fn expect_char(&mut self, expected: char) -> Result<(), ParseError> {
3791        self.skip_whitespace();
3792        if self.peek_char(expected) {
3793            self.advance();
3794            Ok(())
3795        } else {
3796            Err(ParseError::Expected {
3797                expected: format!("'{}'", expected),
3798                found: self
3799                    .peek()
3800                    .map(|c| c.to_string())
3801                    .unwrap_or("EOF".to_string()),
3802            })
3803        }
3804    }
3805
3806    /// Expect a specific string
3807    fn expect_str(&mut self, expected: &str) -> Result<(), ParseError> {
3808        self.skip_whitespace();
3809        if self.try_consume(expected) {
3810            Ok(())
3811        } else {
3812            let found: String = self.input[self.pos..]
3813                .chars()
3814                .take(expected.len())
3815                .collect();
3816            Err(ParseError::Expected {
3817                expected: format!("'{}'", expected),
3818                found: if found.is_empty() {
3819                    "EOF".to_string()
3820                } else {
3821                    found
3822                },
3823            })
3824        }
3825    }
3826
3827    /// Consume a keyword (must be followed by non-alphanumeric)
3828    fn consume_keyword(&mut self, keyword: &str) -> Result<(), ParseError> {
3829        self.skip_whitespace();
3830        if self.peek_keyword(keyword) {
3831            self.pos += keyword.len();
3832            Ok(())
3833        } else {
3834            Err(ParseError::Expected {
3835                expected: keyword.to_string(),
3836                found: self
3837                    .peek()
3838                    .map(|c| c.to_string())
3839                    .unwrap_or("EOF".to_string()),
3840            })
3841        }
3842    }
3843
3844    /// Get remaining input (for debugging)
3845    #[allow(dead_code)]
3846    fn remaining(&self) -> &str {
3847        &self.input[self.pos..]
3848    }
3849}
3850
3851#[cfg(test)]
3852#[path = "../../../logicaffeine_tests/unit/logicaffeine_kernel/interface/term_parser/tests.rs"]
3853mod tests;