Skip to main content

logicaffeine_kernel/interface/
command_parser.rs

1//! Parser for Vernacular commands.
2//!
3//! Commands:
4//! - Definition name : type := term.
5//! - Definition name := term.  (type inferred)
6//! - Definition name.{u, v} : type := term.  (universe-polymorphic)
7//! - Theorem name : proposition := proof.  (checked, then opaque)
8//! - Opaque name : type := value.  (checked, then opaque — data)
9//! - Axiom name : type.  (an explicit, listed assumption)
10//! - Check term.
11//! - Eval term.
12//! - Inductive Name := C1 : T1 | C2 : T2.
13//! - Inductive Name.{u} (params) : arity := C1 : T1 | … with Name2 (params) : arity := … .
14//!   (a block registered exactly as declared: the written parameters, the declared arity, one
15//!   mutual block)
16//!
17//! # Literate Syntax (dispatched to literate_parser)
18//!
19//! - A Bool is either Yes or No.
20//! - ## To add (n: Nat) and (m: Nat) -> Nat: ...
21//!
22//! # Surface extensions (dispatched to the REPL's `Surface`)
23//!
24//! - Notation "a ⊕ b" := ((myOp a) b).
25//! - Infixl 65 "⋄" := f.   Infixr 65 "▷" := g.   Prefix "∽" := neg.   Postfix "‼" := bang.
26//! - Macro "twice $e" := ...   MacroRules "list![$x, $xs]" := ...
27//! - Section Name.   End Name.   (and `Local` before any of the above)
28//!
29//! # Namespaces (they decide how a name READS, and declare nothing)
30//!
31//! - Namespace Outer.Inner.   End Outer.Inner.   — declarations inside are keyed `Outer.Inner.x`,
32//!   and a short name written inside resolves against the enclosing namespaces, longest first.
33//! - Open Alpha Beta.   Open Alpha in `<command>`.   — the scoped form covers exactly one command.
34//! - Open Alpha (a b).   Open Alpha hiding (a).   Open Alpha renaming a -> b.   — a NARROWED
35//!   opening. Opening a namespace wholesale is what makes short names ambiguous, so these are how
36//!   an ambiguity is AVOIDED rather than reported; each names members, so each is checked against
37//!   the environment. An explicit form matches a PREFIX (`Open Foo (x).` reaches `Foo.x.y`), a
38//!   `hiding` matches a whole name — Lean's asymmetry, and measured against lean 4.14.0.
39//! - Protected Definition Alpha.x : …   — an ordinary constant that stops answering to `x`.
40//! - Private Definition x : …   — accepted and INERT: Lean's `private` is transparent to the
41//!   module that declares it, and a session is one module.
42//! - Section.   End.   — Lean's ANONYMOUS section; a bare `End` closes only an anonymous one.
43//! - Export Alpha (token other).   — `token` answers to `Alpha.token` in the current namespace.
44//! - `_root_.x` is the absolute `x`, whatever is current or open.
45//!
46//! A DECLARATION NAME MUST BE ONE A TERM CAN SPELL, and it is checked by asking the term door
47//! rather than by restating its grammar: see `super::declaration_name`. Two things must hold and
48//! implies the other — the term door reads the spelling back as this same name (so no reserved
49//! word, and no quoted component after a `.`), and the flat key the context is indexed by reads
50//! back as this same name (so «a.b» and `a.b` cannot collide on one key).
51//!
52//! A DECLARATION NAME IS HIERARCHICAL: `Definition Outer.Inner.value : …` is one name of three
53//! components, and Lean's rule that such a declaration elaborates with `Outer.Inner` current is
54//! what makes its body able to say `value` and mean its sibling.
55//!
56//! # Prose
57//!
58//! - /-- doc -/   /-! module doc -/   /- block -/   -- line
59
60use super::command::Command;
61use super::error::ParseError;
62use super::literate_parser;
63use super::surface::{Assoc, Name, OpenClause, OperatorForm, Surface, SurfaceDecl};
64use super::term_parser::TermParser;
65use crate::{Term, Universe};
66
67/// Parse ONE command, and require it to be the WHOLE input.
68///
69/// ★ THE KERNEL MUST NOT ACCEPT A PREFIX. This used to read one command off the front and discard
70/// the rest without a word, so `Repl::execute` on a two-block document returned `Ok` having proved
71/// only the first — and the discarded remainder could be a theorem the kernel would have REFUSED.
72/// `5 < 2` by `lia` is rejected when it stands alone and was accepted by silence when it followed a
73/// true theorem, so concatenation walked straight around the conclusion gate. A document is read
74/// whole, by [`crate::interface::Repl::execute_document`]; a single command is read whole here.
75pub fn parse_command(input: &str) -> Result<Command, ParseError> {
76    parse_command_in(&Surface::new(), input)
77}
78
79/// [`parse_command`], reading the notation and macros a session has declared.
80pub fn parse_command_in(surface: &Surface, input: &str) -> Result<Command, ParseError> {
81    let (cmd, consumed) = parse_command_prefix_in(surface, input)?;
82    let rest = input[consumed..].trim();
83    if !rest.is_empty() {
84        return Err(ParseError::TrailingInput {
85            at: consumed,
86            rest: rest.to_string(),
87        });
88    }
89    Ok(cmd)
90}
91
92/// Parse ONE command off the FRONT of `input`, returning it with the number of bytes consumed.
93///
94/// This is the primitive both doors are built from: `parse_command_in` adds "and nothing
95/// followed", and the document splitter loops it. Every branch reports its own extent — the
96/// literate parsers from their own cursor, the Coq-style ones from the sentence terminator — so no
97/// caller has to guess where a command ended.
98pub fn parse_command_prefix_in(
99    surface: &Surface,
100    input: &str,
101) -> Result<(Command, usize), ParseError> {
102    let lead = input.len() - input.trim_start().len();
103    let rest = &input[lead..];
104
105    // ============================================================
106    // PROSE — accepted, and never a declaration
107    // ============================================================
108
109    if let Some(len) = comment_len(rest)? {
110        return Ok((Command::Comment, lead + len));
111    }
112
113    // ============================================================
114    // LITERATE SYNTAX DISPATCH (check first)
115    // ============================================================
116
117    // 1. Literate Data Definition: "A Nat is either..." or "An Option is either..."
118    if (rest.starts_with("A ") || rest.starts_with("An ")) && rest.contains(" is either") {
119        let (cmd, n) = literate_parser::parse_inductive(rest)?;
120        return Ok((cmd, lead + with_terminator(rest, n)));
121    }
122
123    // 2. Literate Function Definition: "## To add..."
124    if rest.starts_with("## To ") {
125        let (cmd, n) = literate_parser::parse_definition(rest)?;
126        return Ok((cmd, lead + with_terminator(rest, n)));
127    }
128
129    // 3. Literate Constant Definition: "Let X be Y."
130    if rest.starts_with("Let ") && rest.contains(" be ") {
131        let (cmd, n) = literate_parser::parse_let_definition(rest)?;
132        return Ok((cmd, lead + with_terminator(rest, n)));
133    }
134
135    // 4. Literate Theorem Declaration: "## Theorem: Name"
136    if rest.starts_with("## Theorem:") {
137        let (cmd, n) = literate_parser::parse_theorem(rest)?;
138        return Ok((cmd, lead + with_terminator(rest, n)));
139    }
140
141    // 5. A `## Theory` DEVELOPMENT is not a command of this door. Its `Axiom … : for all …` and
142    //    `Theorem … : prove …` sentences are first-order statements proved in citation order by the
143    //    theory driver, so the block is refused BY NAME and sent there, rather than reported as an
144    //    unknown `##`.
145    if let Some(after) = rest.strip_prefix("## Theory") {
146        if after.starts_with(char::is_whitespace) {
147            let header = rest.lines().next().unwrap_or(rest).trim_end();
148            return Err(ParseError::Unsupported {
149                what: format!("the development `{header}`"),
150                why: "a `## Theory` block is checked by the theory driver \
151                      (`logicaffeine_proof::development`, run end to end by \
152                      `ui_bridge::compile_theory_for_ui`), which proves each theorem from the \
153                      development's axioms; the kernel's document door reads declarations and \
154                      commands, not developments"
155                    .to_string(),
156            });
157        }
158    }
159
160    // ============================================================
161    // NAMESPACE SCOPE — it declares nothing, it decides how names READ
162    // ============================================================
163
164    // `Open` is dispatched ahead of the sentence split because `Open Alpha in <command>` brackets a
165    // whole command, whose own extent is the only thing that says where this one ends.
166    if let Some(after_open) = strip_word(rest, "Open") {
167        let (opens, tail) = open_clauses(after_open)?;
168        if let Some(after_in) = strip_word(tail, "in") {
169            let (inner, n) = parse_command_prefix_in(surface, after_in)?;
170            let consumed = (rest.len() - after_in.len()) + n;
171            return Ok((
172                Command::OpenIn {
173                    opens,
174                    inner: Box::new(inner),
175                },
176                lead + consumed,
177            ));
178        }
179        let terminated = tail.strip_prefix('.').ok_or_else(|| {
180            ParseError::Missing(
181                "`.` after `Open <namespace>` \u{2014} or `in <command>` to scope the opening"
182                    .to_string(),
183            )
184        })?;
185        return Ok((Command::Open(opens), lead + (rest.len() - terminated.len())));
186    }
187
188    // ============================================================
189    // EXISTING COQ-STYLE DISPATCH (fallback)
190    // ============================================================
191
192    let end = sentence_end(rest);
193    let sentence = rest[..end].trim_end();
194    let body = sentence.strip_suffix('.').unwrap_or(sentence).trim();
195
196    // `Local` is the explicit spelling of the scoping a section already gives, and is accepted
197    // so a file copied from Coq or Lean reads the same here.
198    let body = body.strip_prefix("Local ").unwrap_or(body).trim_start();
199
200    // VISIBILITY IS EXACTLY ONE QUALIFIER, and reading it ONCE is what makes that true by
201    // construction rather than by a check somebody has to remember. `private protected def` is a
202    // parse error in lean 4.14.0 in BOTH orders ("unexpected token 'protected'; expected … 'def'
203    // …"), and here the second word simply stays in `body` and is reported as the unknown command
204    // word it then is.
205    //
206    // `Private` is accepted and INERT, and that is Lean's answer rather than a shrug: Lean mangles
207    // a private name with the defining module's hash (`mkPrivateName`) and then makes the mangling
208    // transparent to that same module — `resolveQualifiedName` and `resolveExact` both fall back to
209    // the private form (`Lean/ResolveName.lean:107-110` and `:127-131`) — so WITHIN one module a
210    // private declaration answers to every spelling an ordinary one does. Measured on lean 4.14.0:
211    // `private def M.hidden`, then `M.hidden`, `M.user` and (under `open M`) `hidden` all print 3.
212    // A session is one module, so refusing it would block a transcription that is CORRECT here.
213    //
214    // `Protected` is the opposite case, and that is why the two are not one line: it is a
215    // resolution fact in EVERY module, including this one. It WRAPS whatever follows, so every
216    // declaration door gets it at once and none of them has to carry a flag it might forget to
217    // pass on.
218    let (body, protected) = match strip_word(body, "Private") {
219        Some(rest) => (rest, false),
220        None => match strip_word(body, "Protected") {
221            Some(rest) => (rest, true),
222            None => (body, false),
223        },
224    };
225
226    let cmd = if body.starts_with("Definition") {
227        parse_definition(surface, body[10..].trim_start())
228    } else if let Some(rest) = strip_word(body, "Theorem") {
229        parse_opaque(surface, rest, true)
230    } else if let Some(rest) = strip_word(body, "Opaque") {
231        parse_opaque(surface, rest, false)
232    } else if let Some(rest) = strip_word(body, "Axiom") {
233        parse_axiom(surface, rest)
234    } else if let Some(rest) = strip_word(body, "Quotient") {
235        parse_quotient(rest)
236    } else if let Some(rest) = strip_word(body, "Structure") {
237        parse_structure(rest)
238    } else if body.starts_with("Check") {
239        parse_check(surface, body[5..].trim_start())
240    } else if body.starts_with("Eval") {
241        parse_eval(surface, body[4..].trim_start())
242    } else if body.starts_with("Inductive") {
243        parse_inductive(surface, body[9..].trim_start())
244    } else if body.starts_with("Notation") {
245        parse_notation(body[8..].trim_start())
246    } else if body.starts_with("Infixl") {
247        parse_fixity(
248            body[6..].trim_start(),
249            OperatorForm::Infix,
250            Assoc::Left,
251            true,
252        )
253    } else if body.starts_with("Infixr") {
254        parse_fixity(
255            body[6..].trim_start(),
256            OperatorForm::Infix,
257            Assoc::Right,
258            true,
259        )
260    } else if body.starts_with("Prefix") {
261        parse_fixity(
262            body[6..].trim_start(),
263            OperatorForm::Prefix,
264            Assoc::Right,
265            false,
266        )
267    } else if body.starts_with("Postfix") {
268        parse_fixity(
269            body[7..].trim_start(),
270            OperatorForm::Postfix,
271            Assoc::Left,
272            false,
273        )
274    } else if body.starts_with("MacroRules") {
275        parse_macro(body[10..].trim_start())
276    } else if body.starts_with("Macro") {
277        parse_macro(body[5..].trim_start())
278    } else if let Some(printed) = strip_word(body, "Print") {
279        parse_print(printed)
280    } else if let Some(exported) = strip_word(body, "Export") {
281        parse_export(exported)
282    } else if let Some(named) = strip_word(body, "Namespace") {
283        Ok(Command::Surface(SurfaceDecl::OpenNamespace(
284            super::declaration_name(named)?,
285        )))
286    } else if let Some(named) = strip_word(body, "Section") {
287        Ok(Command::Surface(SurfaceDecl::OpenSection(optional_name(
288            named,
289        )?)))
290    } else if let Some(named) = strip_word(body, "End") {
291        Ok(Command::Surface(SurfaceDecl::CloseSection(optional_name(
292            named,
293        )?)))
294    } else {
295        Err(ParseError::UnknownCommand(
296            body.split_whitespace().next().unwrap_or(body).to_string(),
297        ))
298    }?;
299    let cmd = if protected {
300        Command::Protected(Box::new(cmd))
301    } else {
302        cmd
303    };
304    Ok((cmd, lead + end))
305}
306
307/// A scope name that MAY be absent: `Section.` and `End.` are Lean's anonymous forms
308/// (`section` / `end` with no name), and the ordinary way to scope a `local` without inventing a
309/// label for it. A name that IS written is held to the whole declaration-name grammar, so
310/// `End fun.` is refused for the same reason `Definition fun` is.
311fn optional_name(raw: &str) -> Result<Option<String>, ParseError> {
312    let raw = raw.trim();
313    if raw.is_empty() {
314        return Ok(None);
315    }
316    declaration_name(raw).map(Some)
317}
318
319/// Parse `Print Axioms <name>` — our `#print axioms`.
320///
321/// `Axioms` is required rather than assumed: `Print` is a whole family in Coq and in Lean
322/// (`#print`, `#print axioms`, `#print notation`), and a bare `Print foo` that silently meant one
323/// of them would be a command word answering to a question nobody asked. An unknown subject is
324/// reported as such, with the one spelling that exists.
325fn parse_print(input: &str) -> Result<Command, ParseError> {
326    let Some(named) = strip_word(input.trim(), "Axioms") else {
327        return Err(ParseError::Unsupported {
328            what: format!("`Print {}`", input.trim()),
329            why: "the only report is `Print Axioms <name>.` — what a declaration transitively \
330                  rests on, which is Lean's `#print axioms`"
331                .to_string(),
332        });
333    };
334    Ok(Command::PrintAxioms(super::declaration_name(named)?))
335}
336
337/// Parse `Export Alpha (token other)` — a source namespace and the names to alias into the current
338/// one. The list is REQUIRED, exactly as Lean requires it: there is no way to enumerate a namespace's
339/// members, so a bare `Export Alpha` could only be a silent no-op.
340fn parse_export(input: &str) -> Result<Command, ParseError> {
341    let (namespace, len) = Name::scan(input.trim())
342        .ok_or_else(|| ParseError::Missing("the namespace to export from".to_string()))?;
343    let rest = input.trim()[len..].trim_start();
344    let inner = rest
345        .strip_prefix('(')
346        .and_then(|r| r.strip_suffix(')'))
347        .ok_or_else(|| {
348            ParseError::Missing(
349                "a parenthesised list of names, as in `Export Alpha (token other)` \u{2014} a \
350                 namespace's members cannot be enumerated, so the names must be written"
351                    .to_string(),
352            )
353        })?;
354    let mut names = Vec::new();
355    let mut cursor = inner.trim();
356    while !cursor.is_empty() {
357        let (name, n) = Name::scan(cursor).ok_or_else(|| {
358            ParseError::InvalidIdent(format!("{cursor:?} \u{2014} not a name to export"))
359        })?;
360        names.push(name);
361        cursor = cursor[n..]
362            .trim_start()
363            .trim_start_matches(',')
364            .trim_start();
365    }
366    if names.is_empty() {
367        return Err(ParseError::Missing(
368            "at least one name to export".to_string(),
369        ));
370    }
371    Ok(Command::Export { namespace, names })
372}
373
374/// Parse `Notation "<pattern>" := <template>` with an optional leading precedence.
375fn parse_notation(input: &str) -> Result<Command, ParseError> {
376    let (precedence, rest) = leading_precedence(input);
377    let (pattern, rest) = quoted(rest)?;
378    let template = after_assign(rest)?;
379    Ok(Command::Surface(SurfaceDecl::Notation {
380        pattern,
381        template,
382        precedence,
383        // With no declared precedence two notations sit at the same level, and an unparenthesised
384        // chain of unfamiliar operators reads to the RIGHT.
385        assoc: Assoc::Right,
386        operator_form: None,
387    }))
388}
389
390/// Parse `Infixl 65 "<op>" := <fn>` and its siblings, where the command word gives the shape.
391fn parse_fixity(
392    input: &str,
393    form: OperatorForm,
394    assoc: Assoc,
395    precedence_required: bool,
396) -> Result<Command, ParseError> {
397    let (precedence, rest) = leading_precedence(input);
398    if precedence_required && precedence.is_none() {
399        return Err(ParseError::Missing(
400            "a precedence — an infix operator must say how tightly it binds".to_string(),
401        ));
402    }
403    let (pattern, rest) = quoted(rest)?;
404    let template = after_assign(rest)?;
405    Ok(Command::Surface(SurfaceDecl::Notation {
406        pattern,
407        template,
408        precedence,
409        assoc,
410        operator_form: Some(form),
411    }))
412}
413
414/// Parse `Macro "<pattern>" := <template>` / `MacroRules "<pattern>" := <template>`.
415fn parse_macro(input: &str) -> Result<Command, ParseError> {
416    let (pattern, rest) = quoted(input)?;
417    let template = after_assign(rest)?;
418    Ok(Command::Surface(SurfaceDecl::Macro { pattern, template }))
419}
420
421/// A leading decimal precedence, if one is written.
422fn leading_precedence(input: &str) -> (Option<u32>, &str) {
423    let digits: String = input.chars().take_while(char::is_ascii_digit).collect();
424    match digits.parse::<u32>() {
425        Ok(n) => (Some(n), input[digits.len()..].trim_start()),
426        Err(_) => (None, input),
427    }
428}
429
430/// The contents of a leading `"…"`, and what follows it.
431fn quoted(input: &str) -> Result<(String, &str), ParseError> {
432    let input = input.trim_start();
433    let rest = input
434        .strip_prefix('"')
435        .ok_or_else(|| ParseError::Expected {
436            expected: "a quoted pattern".to_string(),
437            found: input.chars().take(12).collect::<String>(),
438        })?;
439    let end = rest
440        .find('"')
441        .ok_or_else(|| ParseError::Missing("the closing quote of the pattern".to_string()))?;
442    Ok((rest[..end].to_string(), &rest[end + 1..]))
443}
444
445/// The text after `:=`.
446fn after_assign(input: &str) -> Result<String, ParseError> {
447    let input = input.trim_start();
448    let body = input
449        .strip_prefix(":=")
450        .ok_or(ParseError::Missing(":=".to_string()))?
451        .trim();
452    if body.is_empty() {
453        return Err(ParseError::Missing("the expansion".to_string()));
454    }
455    Ok(body.to_string())
456}
457
458/// A literate block ends where its own parser stopped, PLUS the sentence terminator if one
459/// follows.
460///
461/// `pub(super)` so the CONTEXT-AWARE door in the parent module measures a block with this same
462/// function rather than a checked copy of it: two doors that disagreed about where a command ended
463/// would split one document two different ways depending on which of them read it. `## To double (n: Int) -> Int: … Yield (add n n).` leaves its final `.` unread — a
464/// full stop is punctuation, not input — and without this the block would look like a command
465/// with a stray period trailing it.
466pub(super) fn with_terminator(rest: &str, n: usize) -> usize {
467    let tail = &rest[n..];
468    let spaces = tail.len() - tail.trim_start_matches([' ', '\t']).len();
469    if tail[spaces..].starts_with('.') {
470        n + spaces + 1
471    } else {
472        n
473    }
474}
475
476/// The end of a vernacular SENTENCE: just past the first `.` that is followed by whitespace or by
477/// end-of-input and is not inside a string literal. Coq's own rule, and the reason `Nat.succ`,
478/// `3.14` and `"a. b"` can all live inside a term without ending the command.
479pub(super) fn sentence_end(input: &str) -> usize {
480    let mut in_string = false;
481    let mut in_name = false;
482    let mut escaped = false;
483    for (i, c) in input.char_indices() {
484        if escaped {
485            escaped = false;
486            continue;
487        }
488        // A «quoted name» is verbatim, and a `.` inside one — `«a. b»` — is part of the NAME. The
489        // term grammar reads it that way; a sentence splitter that ended the command there would
490        // hand the term door half a name.
491        if in_name {
492            in_name = c != '\u{bb}';
493            continue;
494        }
495        match c {
496            '\u{ab}' if !in_string => in_name = true,
497            '\\' if in_string => escaped = true,
498            '"' => in_string = !in_string,
499            '.' if !in_string => {
500                let after = i + c.len_utf8();
501                if input[after..]
502                    .chars()
503                    .next()
504                    .is_none_or(char::is_whitespace)
505                {
506                    return after;
507                }
508            }
509            _ => {}
510        }
511    }
512    input.len()
513}
514
515/// How many bytes of documentation or comment start `input`, or `None` if it starts with neither.
516///
517/// `/-- … -/` (a doc comment), `/-! … -/` (a module doc) and `/- … -/` nest, exactly as they do in
518/// Lean; `-- …` runs to the end of the line. An UNTERMINATED block comment is an error rather than
519/// a silently-swallowed remainder — otherwise one missing `-/` eats the rest of a document.
520fn comment_len(input: &str) -> Result<Option<usize>, ParseError> {
521    if input.starts_with("--") {
522        return Ok(Some(input.find('\n').map_or(input.len(), |i| i + 1)));
523    }
524    if !input.starts_with("/-") {
525        return Ok(None);
526    }
527    let bytes = input.as_bytes();
528    let mut depth = 0usize;
529    let mut i = 0usize;
530    while i + 1 < bytes.len() {
531        if bytes[i] == b'/' && bytes[i + 1] == b'-' {
532            depth += 1;
533            i += 2;
534        } else if bytes[i] == b'-' && bytes[i + 1] == b'/' {
535            depth -= 1;
536            i += 2;
537            if depth == 0 {
538                return Ok(Some(i));
539            }
540        } else {
541            i += 1;
542        }
543    }
544    Err(ParseError::Missing(
545        "closing `-/` for a documentation comment".to_string(),
546    ))
547}
548
549/// A declaration name, as the flat key the context is indexed at.
550///
551/// ★ THE RULE ITSELF LIVES IN THE PARENT MODULE, and so this is four lines. Both declaration doors
552/// — this one's `Definition`/`Inductive` and the literate `## To`/`## Theorem:`/`Let … be`/
553/// `A … is either` — must key a name at the same grammar, and a rule that only one door applied
554/// would not be a rule but a door's habit. It used to be spelled out here, where the literate door
555/// could not reach it; it is now `super::declaration_name` and this is the caller that wants the
556/// key rather than the components.
557fn declaration_name(raw: &str) -> Result<String, ParseError> {
558    super::declaration_name(raw).map(|n| n.key())
559}
560
561/// `input` with `word` stripped from its front, if `word` stands there as a whole word.
562///
563/// The Coq-style dispatch below matches command words by bare prefix, which is fine for words no
564/// identifier begins with. `Open` and `Namespace` are matched here instead because both are
565/// followed by a NAME, and `Opened` must not read as `Open` + `ed`.
566fn strip_word<'a>(input: &'a str, word: &str) -> Option<&'a str> {
567    let rest = input.strip_prefix(word)?;
568    match rest.chars().next() {
569        Some(c) if c.is_alphanumeric() || c == '_' || c == '\'' => None,
570        _ => Some(rest.trim_start()),
571    }
572}
573
574/// One or more `open` clauses, and what follows them.
575///
576/// `Open Alpha Beta.`, `Open Alpha (a b).`, `Open Alpha hiding (a).` and `Open Alpha in …` all
577/// land here. A bare namespace is a WHOLESALE opening; a following `(…)` or `hiding` narrows the
578/// one just read, and then the list continues, so `Open Alpha (x) Beta.` is two clauses. The list
579/// is greedy and stops at the first token that is not a name — which `in` and `hiding` are not
580/// allowed to be, since one scopes the opening and the other narrows it.
581fn open_clauses(input: &str) -> Result<(Vec<OpenClause>, &str), ParseError> {
582    let mut clauses: Vec<OpenClause> = Vec::new();
583    let mut rest = input.trim_start();
584    loop {
585        if strip_word(rest, "in").is_some() || strip_word(rest, "hiding").is_some() {
586            break;
587        }
588        let Some((namespace, len)) = Name::scan(rest) else {
589            break;
590        };
591        rest = rest[len..].trim_start();
592        let mut clause = OpenClause::all(namespace);
593        if rest.starts_with('(') {
594            let (only, after) = parenthesised_names(rest, "open")?;
595            clause.only = Some(only);
596            rest = after;
597        } else if let Some(after_hiding) = strip_word(rest, "hiding") {
598            let (hidden, after) = if after_hiding.starts_with('(') {
599                parenthesised_names(after_hiding, "hide")?
600            } else {
601                bare_names(after_hiding)?
602            };
603            clause.hiding = hidden;
604            rest = after;
605        } else if let Some(after_renaming) = strip_word(rest, "renaming") {
606            let (pairs, after) = renaming_pairs(after_renaming)?;
607            clause.renaming = pairs;
608            rest = after;
609        }
610        clauses.push(clause);
611    }
612    if clauses.is_empty() {
613        return Err(ParseError::Missing("a namespace to open".to_string()));
614    }
615    Ok((clauses, rest))
616}
617
618/// `(a b c)` — a parenthesised name list, and what follows it. Commas are optional separators,
619/// as they are in `Export`'s list.
620fn parenthesised_names<'a>(input: &'a str, what: &str) -> Result<(Vec<Name>, &'a str), ParseError> {
621    let after_open = input
622        .strip_prefix('(')
623        .expect("the caller checked for the opening parenthesis");
624    let close = after_open
625        .find(')')
626        .ok_or_else(|| ParseError::Missing(format!("`)` closing the list of names to {what}")))?;
627    let (names, _) = bare_names(&after_open[..close])?;
628    Ok((names, after_open[close + 1..].trim_start()))
629}
630
631/// `a -> b, c -> d` — the pairs of a `renaming` clause, and what follows them.
632///
633/// The arrow is written `->` or `→`, as Lean writes it either way: `Lean/Elab/Open.lean:89`
634/// matches `$ns renaming $[$froms -> $tos],*`, and every library writes the glyph. The MEMBER is
635/// on the left and the local spelling on the right — the direction that reads as "this becomes
636/// that", and the direction Lean records it in (`OpenDecl.explicit to.getId declName`, line 96).
637fn renaming_pairs(input: &str) -> Result<(Vec<(Name, Name)>, &str), ParseError> {
638    let mut pairs = Vec::new();
639    let mut rest = input.trim_start();
640    loop {
641        let Some((member, len)) = Name::scan(rest) else {
642            break;
643        };
644        let after_member = rest[len..].trim_start();
645        let Some(after_arrow) = after_member
646            .strip_prefix("->")
647            .or_else(|| after_member.strip_prefix('\u{2192}'))
648        else {
649            // No arrow: this name is not part of the renaming list, so the list ends HERE rather
650            // than half-consuming a name the caller still has to read.
651            break;
652        };
653        let after_arrow = after_arrow.trim_start();
654        let (local, n) = Name::scan(after_arrow).ok_or_else(|| {
655            ParseError::Missing(format!(
656                "the local spelling after `{member} ->` — a renaming is `<member> -> <name>`"
657            ))
658        })?;
659        pairs.push((member, local));
660        rest = after_arrow[n..]
661            .trim_start()
662            .trim_start_matches(',')
663            .trim_start();
664    }
665    if pairs.is_empty() {
666        return Err(ParseError::Missing(
667            "at least one `<member> -> <name>` renaming".to_string(),
668        ));
669    }
670    Ok((pairs, rest))
671}
672
673/// A run of space-separated names, and what follows them. Commas are skipped so a list may be
674/// written either way.
675fn bare_names(input: &str) -> Result<(Vec<Name>, &str), ParseError> {
676    let mut names = Vec::new();
677    let mut rest = input.trim_start();
678    while let Some((name, len)) = Name::scan(rest) {
679        names.push(name);
680        rest = rest[len..]
681            .trim_start()
682            .trim_start_matches(',')
683            .trim_start();
684    }
685    if names.is_empty() {
686        return Err(ParseError::Missing("at least one name".to_string()));
687    }
688    Ok((names, rest))
689}
690
691/// The byte offset of `keyword` in `haystack` as a standalone word, if it occurs.
692fn find_keyword(haystack: &str, keyword: &str) -> Option<usize> {
693    let boundary = |c: Option<char>| c.is_none_or(|c| !c.is_alphanumeric() && c != '_');
694    let mut from = 0;
695    while let Some(rel) = haystack[from..].find(keyword) {
696        let at = from + rel;
697        let before = haystack[..at].chars().next_back();
698        let after = haystack[at + keyword.len()..].chars().next();
699        if boundary(before) && boundary(after) {
700            return Some(at);
701        }
702        from = at + keyword.len();
703    }
704    None
705}
706
707/// `input` cut at every TOP-LEVEL occurrence of `sep` — outside every bracket, string and
708/// «quoted name». [`TermParser::find_top_level`] applied until the input is exhausted, which is
709/// the splitting counterpart of the same one scan.
710fn split_top_level<'a>(input: &'a str, sep: &str) -> Vec<&'a str> {
711    let mut parts = Vec::new();
712    let mut rest = input;
713    while let Some(at) = TermParser::find_top_level(rest, sep) {
714        parts.push(&rest[..at]);
715        rest = &rest[at + sep.len()..];
716    }
717    parts.push(rest);
718    parts
719}
720
721/// Parse: name : type := term  OR  name := term
722///
723/// ★ THE SENTENCE IS SPLIT AT A TOP-LEVEL DELIMITER, NEVER BY A RAW SEARCH. The FIRST `:=` in
724/// the text is not always the separator, and neither is the first `:`. A defaulted binder puts a
725/// `:=` inside the TYPE — `Definition f : Int -> (m : Int := 3) -> Int := …` split at the DEFAULT
726/// and handed the term parser the truncated `Int -> (m : Int`, refused for `Expected ')' found
727/// EOF`: a message naming neither the default nor the body. A «guillemet name» puts one inside
728/// the NAME (`Definition «a := b» : Nat := Zero.`), and every `(x : T)` binder in a type puts a
729/// `:` after the ascription's own. Where a bracket, a string and a «quoted name» begin and end is
730/// the TERM grammar's knowledge, so the scan is asked of it rather than re-derived — once per
731/// bug — by each door that has to split a sentence.
732fn parse_definition(surface: &Surface, input: &str) -> Result<Command, ParseError> {
733    // Find the := delimiter
734    let assign_pos =
735        TermParser::find_top_level(input, ":=").ok_or(ParseError::Missing(":=".to_string()))?;
736
737    let before_assign = input[..assign_pos].trim();
738    let body_str = input[assign_pos + 2..].trim();
739
740    // Check if there's a type annotation (: before :=)
741    if let Some(colon_pos) = TermParser::find_top_level(before_assign, ":") {
742        // Has type annotation: name : type
743        let (name, universes) = declaration_head(&before_assign[..colon_pos])?;
744        let type_str = before_assign[colon_pos + 1..].trim();
745
746        let (ty, implicit_count) = TermParser::read_declared_type_in(surface, type_str)?;
747        let body = TermParser::parse_in(surface, body_str)?;
748
749        Ok(with_universes(
750            universes,
751            Command::Definition {
752                name,
753                ty: Some(ty),
754                body,
755                is_hint: false,
756                implicit_count,
757                proof_goal: None,
758            },
759        ))
760    } else {
761        // No type annotation: name := term
762        let (name, universes) = declaration_head(before_assign)?;
763
764        let (body, implicit_count) = TermParser::read_declared_type_in(surface, body_str)?;
765
766        Ok(with_universes(
767            universes,
768            Command::Definition {
769                name,
770                ty: None,
771                body,
772                is_hint: false,
773                implicit_count,
774                proof_goal: None,
775            },
776        ))
777    }
778}
779
780/// Parse `Theorem name : P := proof` (`theorem` true) or `Opaque name : T := value` — both
781/// require their type, because both are checked against it and then kept only as their header.
782fn parse_opaque(surface: &Surface, input: &str, theorem: bool) -> Result<Command, ParseError> {
783    let word = if theorem { "Theorem" } else { "Opaque" };
784    let assign_pos = TermParser::find_top_level(input, ":=").ok_or_else(|| {
785        ParseError::Missing(format!(
786            "`:=` and the {} of the `{word}` \u{2014} it is checked, so it must be written",
787            if theorem { "proof" } else { "value" }
788        ))
789    })?;
790    let before_assign = input[..assign_pos].trim();
791    let colon_pos = TermParser::find_top_level(before_assign, ":").ok_or_else(|| {
792        ParseError::Missing(format!(
793            "the `: <type>` of the `{word}` \u{2014} an opaque declaration is known only by its type"
794        ))
795    })?;
796    let (name, universes) = declaration_head(&before_assign[..colon_pos])?;
797    // The statement keeps its binder-kind markers, exactly as a `Definition`'s declared type does:
798    // `Theorem t {α : Type} (a : α) : …` records how each argument is supplied at a use site.
799    let (ty, _) =
800        TermParser::read_declared_type_in(surface, before_assign[colon_pos + 1..].trim())?;
801    let proof_text = input[assign_pos + 2..].trim();
802    if theorem {
803        if let Some(script) = proof_text
804            .strip_prefix("by")
805            .filter(|rest| rest.starts_with(char::is_whitespace))
806        {
807            let script = parse_tactic_script(surface, script.trim())?;
808            return Ok(with_universes(
809                universes,
810                Command::TheoremBy { name, ty, script },
811            ));
812        }
813    }
814    let value = TermParser::parse_in(surface, proof_text)?;
815    let cmd = if theorem {
816        Command::Theorem {
817            name,
818            ty,
819            proof: value,
820        }
821    } else {
822        Command::Opaque { name, ty, value }
823    };
824    Ok(with_universes(universes, cmd))
825}
826
827/// A tactic script: steps separated by top-level `;` (`intro A x; exact (refl A x)`). The terms a
828/// step carries are read in the surface's notation; a name a goal's hypothesis binds is resolved
829/// against that goal when the step runs.
830fn parse_tactic_script(
831    surface: &Surface,
832    text: &str,
833) -> Result<Vec<crate::tactics::TacticStep>, ParseError> {
834    let mut steps = Vec::new();
835    let mut rest = text;
836    loop {
837        let end = TermParser::find_top_level(rest, ";").unwrap_or(rest.len());
838        let step = rest[..end].trim();
839        if step.is_empty() {
840            return Err(ParseError::Missing(
841                "a tactic: a script step is empty".to_string(),
842            ));
843        }
844        steps.extend(parse_tactic(surface, step)?);
845        if end == rest.len() {
846            return Ok(steps);
847        }
848        rest = &rest[end + 1..];
849    }
850}
851
852/// One tactic of a script. `rw [h₁, ← h₂]` is one step per rule.
853fn parse_tactic(
854    surface: &Surface,
855    step: &str,
856) -> Result<Vec<crate::tactics::TacticStep>, ParseError> {
857    use crate::tactics::TacticStep;
858    let (word, arg) = match step.find(char::is_whitespace) {
859        Some(i) => (&step[..i], step[i..].trim()),
860        None => (step, ""),
861    };
862    let term = |text: &str| {
863        if text.is_empty() {
864            Err(ParseError::Missing(format!("the term `{word}` takes")))
865        } else {
866            TermParser::parse_in(surface, text)
867        }
868    };
869    let bare = |s: TacticStep| {
870        if arg.is_empty() {
871            Ok(vec![s])
872        } else {
873            Err(ParseError::TrailingInput {
874                at: word.len(),
875                rest: arg.to_string(),
876            })
877        }
878    };
879    let names = |text: &str| -> Result<Vec<String>, ParseError> {
880        text.split_whitespace()
881            .map(|n| {
882                if n.chars()
883                    .next()
884                    .is_some_and(|c| c.is_alphabetic() || c == '_')
885                    && n.chars()
886                        .all(|c| c.is_alphanumeric() || c == '_' || c == '\'')
887                {
888                    Ok(n.to_string())
889                } else {
890                    Err(ParseError::InvalidIdent(n.to_string()))
891                }
892            })
893            .collect()
894    };
895    // `x` or `x as [a b | c d]`: the hypothesis eliminated and each case's names.
896    let eliminated = |text: &str| -> Result<(String, Vec<Vec<String>>), ParseError> {
897        let (x, pattern) = match text.find(" as ") {
898            Some(i) => (text[..i].trim(), Some(text[i + 4..].trim())),
899            None => (text.trim(), None),
900        };
901        let x = names(x)?;
902        let [x] = x.as_slice() else {
903            return Err(ParseError::Missing(format!(
904                "the one hypothesis `{word}` eliminates"
905            )));
906        };
907        let cases = match pattern {
908            None => Vec::new(),
909            Some(p) => {
910                let inner = p
911                    .strip_prefix('[')
912                    .and_then(|p| p.strip_suffix(']'))
913                    .ok_or_else(|| ParseError::Expected {
914                        expected: "`[names | names …]`".to_string(),
915                        found: p.to_string(),
916                    })?;
917                inner.split('|').map(names).collect::<Result<_, _>>()?
918            }
919        };
920        Ok((x.clone(), cases))
921    };
922    Ok(match word {
923        "intro" | "intros" => {
924            let xs = names(arg)?;
925            if xs.is_empty() {
926                return Err(ParseError::Missing("the names `intro` introduces".to_string()));
927            }
928            vec![TacticStep::Intro(xs)]
929        }
930        "exact" => vec![TacticStep::Exact(term(arg)?)],
931        "apply" => vec![TacticStep::Apply(term(arg)?)],
932        "exists" => vec![TacticStep::Exists(term(arg)?)],
933        "change" | "show" => vec![TacticStep::Change(term(arg)?)],
934        "assumption" => bare(TacticStep::Assumption)?,
935        "exfalso" => bare(TacticStep::Exfalso)?,
936        "constructor" => bare(TacticStep::Constructor)?,
937        "left" => bare(TacticStep::Left)?,
938        "right" => bare(TacticStep::Right)?,
939        "rfl" | "reflexivity" => bare(TacticStep::Rfl)?,
940        "cc" => bare(TacticStep::Cc)?,
941        "decide" => bare(TacticStep::Decide)?,
942        "simp" if arg.is_empty() => vec![TacticStep::Simp(Vec::new())],
943        "simp" => {
944            let lemmas = arg.strip_prefix('[').and_then(|a| a.strip_suffix(']')).ok_or_else(|| {
945                ParseError::Expected { expected: "`simp` or `simp [l₁, l₂, …]`".to_string(), found: arg.to_string() }
946            })?;
947            let mut out = Vec::new();
948            let mut rest = lemmas;
949            loop {
950                let end = TermParser::find_top_level(rest, ",").unwrap_or(rest.len());
951                out.push(term(rest[..end].trim())?);
952                if end == rest.len() {
953                    break;
954                }
955                rest = &rest[end + 1..];
956            }
957            vec![TacticStep::Simp(out)]
958        }
959        "have" => {
960            let colon = TermParser::find_top_level(arg, ":")
961                .ok_or_else(|| ParseError::Missing("`have h : <statement>`'s `:`".to_string()))?;
962            let name = names(arg[..colon].trim())?;
963            let [name] = name.as_slice() else {
964                return Err(ParseError::Missing("the one name `have` gives its statement".to_string()));
965            };
966            vec![TacticStep::Have(name.clone(), term(arg[colon + 1..].trim())?)]
967        }
968        "rw" | "rewrite" => {
969            let rules = arg.strip_prefix('[').and_then(|a| a.strip_suffix(']')).ok_or_else(|| {
970                ParseError::Expected { expected: "`[h]`, `[← h]` or `[h₁, h₂]`".to_string(), found: arg.to_string() }
971            })?;
972            let mut out = Vec::new();
973            let mut rest = rules;
974            loop {
975                let end = TermParser::find_top_level(rest, ",").unwrap_or(rest.len());
976                let rule = rest[..end].trim();
977                let (reverse, rule) = match rule.strip_prefix("<-").or_else(|| rule.strip_prefix('←')) {
978                    Some(r) => (true, r.trim()),
979                    None => (false, rule),
980                };
981                out.push(TacticStep::Rewrite(term(rule)?, reverse));
982                if end == rest.len() {
983                    break;
984                }
985                rest = &rest[end + 1..];
986            }
987            out
988        }
989        "induction" => {
990            let (x, cases) = eliminated(arg)?;
991            vec![TacticStep::Induction(x, cases)]
992        }
993        "cases" => {
994            let (x, cases) = eliminated(arg)?;
995            vec![TacticStep::Cases(x, cases)]
996        }
997        "refine" => vec![TacticStep::Refine(term(arg)?)],
998        "subst" => {
999            let h = names(arg)?;
1000            let [h] = h.as_slice() else {
1001                return Err(ParseError::Missing("the one equation `subst` substitutes along".to_string()));
1002            };
1003            vec![TacticStep::Subst(h.clone())]
1004        }
1005        "injection" => {
1006            let (h, groups) = eliminated(arg)?;
1007            let names = match groups.as_slice() {
1008                [] => Vec::new(),
1009                [names] => names.clone(),
1010                _ => return Err(ParseError::Missing("one list of names for `injection`'s equations".to_string())),
1011            };
1012            vec![TacticStep::Injection(h, names)]
1013        }
1014        "calc" => {
1015            let body = arg.strip_prefix('[').and_then(|a| a.strip_suffix(']')).ok_or_else(|| ParseError::Expected {
1016                expected: "`[R₁ := p₁, R₂ := p₂, …]`".to_string(),
1017                found: arg.to_string(),
1018            })?;
1019            let mut steps = Vec::new();
1020            let mut rest = body;
1021            loop {
1022                let end = TermParser::find_top_level(rest, ",").unwrap_or(rest.len());
1023                let step = rest[..end].trim();
1024                let at = TermParser::find_top_level(step, ":=")
1025                    .ok_or_else(|| ParseError::Missing(format!("the `:=` and proof of the step `{step}`")))?;
1026                steps.push((term(step[..at].trim())?, term(step[at + 2..].trim())?));
1027                if end == rest.len() {
1028                    break;
1029                }
1030                rest = &rest[end + 1..];
1031            }
1032            vec![TacticStep::Calc(steps)]
1033        }
1034        other => {
1035            return Err(ParseError::Unsupported {
1036                what: format!("the tactic `{other}`"),
1037                why: "the tactics are intro, exact, apply, refine, assumption, exfalso, constructor, left, right, \
1038                      exists, have, rfl, change, rw, subst, injection, calc, cc, decide, simp, induction and cases"
1039                    .to_string(),
1040            })
1041        }
1042    })
1043}
1044
1045/// Parse `Axiom name : T` — a type and nothing else. A `:=` at top level would be a body, and an
1046/// axiom has none, so it is refused rather than dropped.
1047fn parse_axiom(surface: &Surface, input: &str) -> Result<Command, ParseError> {
1048    if TermParser::find_top_level(input, ":=").is_some() {
1049        return Err(ParseError::Unsupported {
1050            what: "a body on an `Axiom`".to_string(),
1051            why:
1052                "an axiom is an ASSUMPTION \u{2014} it has a type and no proof. A declaration with \
1053                  a body is a `Theorem`, an `Opaque` or a `Definition`"
1054                    .to_string(),
1055        });
1056    }
1057    let colon_pos = TermParser::find_top_level(input, ":")
1058        .ok_or_else(|| ParseError::Missing("the `: <type>` an axiom assumes".to_string()))?;
1059    let (name, universes) = declaration_head(&input[..colon_pos])?;
1060    let (ty, _) = TermParser::read_declared_type_in(surface, input[colon_pos + 1..].trim())?;
1061    Ok(with_universes(universes, Command::Axiom { name, ty }))
1062}
1063
1064/// Parse `Quotient <Primitive>.{u, …} (using <equality>)?` — see [`Command::Quotient`].
1065fn parse_quotient(input: &str) -> Result<Command, ParseError> {
1066    use crate::quotient::Kind;
1067    let input = input.trim();
1068    let word_len = input.find(".{").ok_or_else(|| {
1069        ParseError::Missing(
1070            "the universe parameters of a quotient primitive, written `.{u}` right after its name"
1071                .to_string(),
1072        )
1073    })?;
1074    let kind = match &input[..word_len] {
1075        "Type" => Kind::Type,
1076        "Constructor" => Kind::Constructor,
1077        "Lift" => Kind::Lift,
1078        "Induction" => Kind::Induction,
1079        other => {
1080            return Err(ParseError::Expected {
1081                expected: "a quotient primitive: `Type`, `Constructor`, `Lift` or `Induction`"
1082                    .to_string(),
1083                found: other.to_string(),
1084            })
1085        }
1086    };
1087    let after = &input[word_len + 2..];
1088    let close = after.find('}').ok_or_else(|| {
1089        ParseError::Missing("`}` closing the quotient's universe parameters".to_string())
1090    })?;
1091    let params = universe_names(&after[..close])?;
1092    let rest = after[close + 1..].trim();
1093    let equality = match strip_word(rest, "using") {
1094        Some(named) => {
1095            let (name, len) = Name::scan(named.trim()).ok_or_else(|| {
1096                ParseError::Missing("the equality a quotient lift is stated with".to_string())
1097            })?;
1098            if len != named.trim().len() {
1099                return Err(ParseError::TrailingInput {
1100                    at: 0,
1101                    rest: named.trim()[len..].to_string(),
1102                });
1103            }
1104            Some(name.key())
1105        }
1106        None if rest.is_empty() => None,
1107        None => {
1108            return Err(ParseError::TrailingInput {
1109                at: 0,
1110                rest: rest.to_string(),
1111            })
1112        }
1113    };
1114    if (kind == Kind::Lift) != equality.is_some() {
1115        return Err(ParseError::Unsupported {
1116            what: format!(
1117                "`Quotient {}` {} an equality",
1118                &input[..word_len],
1119                if equality.is_some() {
1120                    "naming"
1121                } else {
1122                    "without"
1123                }
1124            ),
1125            why: "only `Lift` states its respect hypothesis with an equality, and it must name it"
1126                .to_string(),
1127        });
1128    }
1129    Ok(Command::Universes {
1130        params,
1131        inner: Box::new(Command::Quotient { kind, equality }),
1132    })
1133}
1134
1135/// Parse `Structure <inductive> := <projection>*` — see [`Command::Structure`]. Both are
1136/// REFERENCES to declarations that already exist, read as a term reads a name.
1137fn parse_structure(input: &str) -> Result<Command, ParseError> {
1138    let assign = TermParser::find_top_level(input, ":=").ok_or_else(|| {
1139        ParseError::Missing(
1140            "`:=` and the projections, one per field, in field order — `Structure Prod := fst snd.`"
1141                .to_string(),
1142        )
1143    })?;
1144    let written = input[..assign].trim();
1145    let inductive = match Name::scan(written) {
1146        Some((name, len)) if len == written.len() => name.key(),
1147        _ => {
1148            return Err(ParseError::InvalidIdent(format!(
1149                "{written:?} \u{2014} `Structure` names the inductive it makes a structure"
1150            )))
1151        }
1152    };
1153    let mut projections = Vec::new();
1154    let mut rest = input[assign + 2..].trim();
1155    while !rest.is_empty() {
1156        let (name, len) = Name::scan(rest).ok_or_else(|| {
1157            ParseError::InvalidIdent(format!("{rest:?} \u{2014} a projection is a name"))
1158        })?;
1159        projections.push(name.key());
1160        rest = rest[len..].trim_start();
1161    }
1162    Ok(Command::Structure {
1163        inductive,
1164        projections,
1165    })
1166}
1167
1168/// A declaration's HEAD: its name, and the universe telescope written after it as `.{u, v}`.
1169///
1170/// The name is read by the one name grammar (`super::declaration_name`), and whatever the name
1171/// grammar does not consume must be exactly one `.{…}` list of distinct-or-not universe names —
1172/// repetition is the kernel's to refuse, so that the vernacular refuses exactly what the kernel
1173/// refuses and says it the kernel's way.
1174fn declaration_head(raw: &str) -> Result<(String, Option<Vec<String>>), ParseError> {
1175    let raw = raw.trim();
1176    let name_len = Name::scan(raw).map_or(raw.len(), |(_, len)| len);
1177    let (name, rest) = raw.split_at(name_len);
1178    let name = declaration_name(name)?;
1179    if rest.is_empty() {
1180        return Ok((name, None));
1181    }
1182    let list = rest
1183        .strip_prefix(".{")
1184        .and_then(|r| r.strip_suffix('}'))
1185        .ok_or_else(|| {
1186            ParseError::InvalidIdent(format!(
1187                "{raw:?} \u{2014} after a declaration's name may come only its universe \
1188                 parameters, written `.{{u, v}}`"
1189            ))
1190        })?;
1191    Ok((name, Some(universe_names(list)?)))
1192}
1193
1194/// `u, v, «w»` — the names of a universe telescope. Empty is allowed and means a telescope of no
1195/// parameters, which registers through the polymorphic door all the same.
1196fn universe_names(list: &str) -> Result<Vec<String>, ParseError> {
1197    let mut names = Vec::new();
1198    let mut rest = list.trim();
1199    if rest.is_empty() {
1200        return Ok(names);
1201    }
1202    loop {
1203        let (name, len) = super::term_parser::scan_name(rest).ok_or_else(|| {
1204            ParseError::InvalidIdent(format!("{rest:?} \u{2014} a universe parameter is a name"))
1205        })?;
1206        if !rest.starts_with('\u{ab}')
1207            && (name == "_"
1208                || name == "max"
1209                || name == "imax"
1210                || super::term_parser::is_sort_word(&name)
1211                || super::term_parser::is_reserved_word(&name))
1212        {
1213            return Err(ParseError::InvalidIdent(format!(
1214                "`{name}` is a word of the level grammar; a universe parameter spelled that way is \
1215                 written \u{ab}{name}\u{bb}"
1216            )));
1217        }
1218        names.push(name);
1219        rest = rest[len..].trim_start();
1220        if rest.is_empty() {
1221            return Ok(names);
1222        }
1223        rest = rest
1224            .strip_prefix(',')
1225            .ok_or_else(|| {
1226                ParseError::Missing(format!("`,` between universe parameters, before {rest:?}"))
1227            })?
1228            .trim_start();
1229    }
1230}
1231
1232/// `cmd` bound by the universe telescope, if one was written.
1233fn with_universes(universes: Option<Vec<String>>, cmd: Command) -> Command {
1234    match universes {
1235        Some(params) => Command::Universes {
1236            params,
1237            inner: Box::new(cmd),
1238        },
1239        None => cmd,
1240    }
1241}
1242
1243/// Parse: term
1244fn parse_check(surface: &Surface, input: &str) -> Result<Command, ParseError> {
1245    let term = TermParser::parse_in(surface, input)?;
1246    Ok(Command::Check(term))
1247}
1248
1249/// Parse: term
1250fn parse_eval(surface: &Surface, input: &str) -> Result<Command, ParseError> {
1251    let term = TermParser::parse_in(surface, input)?;
1252    Ok(Command::Eval(term))
1253}
1254
1255/// Parse: Name (params) := C1 : T1 | C2 : T2
1256///
1257/// Supports polymorphic inductives like:
1258/// `Inductive List (A : Type) := Nil : List A | Cons : A -> List A -> List A.`
1259///
1260/// ★ AND A BLOCK, WHEN THE HEADER SAYS MORE. A header that DECLARES its arity
1261/// (`Inductive Vec (A : Type) : Nat -> Type := …`), names universe parameters
1262/// (`Inductive PBox.{u} …`) or joins members with `with` is an [`Command::InductiveBlock`]: its
1263/// written parameters ARE its parameters, the rest of the arity is indices, and its members are
1264/// one mutual block — registered through the kernel's checked block door, the one the Lean
1265/// importer uses. Without any of those, the header is the legacy form, which lets the kernel
1266/// infer the parameter split, and reads exactly as it always did.
1267fn parse_inductive(surface: &Surface, input: &str) -> Result<Command, ParseError> {
1268    // ★ A `deriving` CLAUSE IS REFUSED, NOT ABSORBED. Lean's `deriving` runs a handler — an
1269    // `Array Name -> CommandElabM Bool` that reads the environment, emits declarations and may
1270    // decline — and the kernel is pure CoC by construction, so there is nowhere for one to live.
1271    // Refusing it is the honest answer. MIS-PARSING it was not: `Inductive Colour := red : Colour
1272    // deriving BEq.` used to be accepted and registered `red : ((Colour deriving) BEq)`, applying
1273    // the inductive to two globals that are not in the context at all.
1274    if find_keyword(input, "deriving").is_some() {
1275        return Err(ParseError::Unsupported {
1276            what: "a `deriving` clause".to_string(),
1277            why: "a deriving handler is a CommandElabM PROGRAM, and the kernel is pure CoC — \
1278                  there is no handler registry for one to live in. Write the declarations it \
1279                  would have generated; they are ordinary and they check"
1280                .to_string(),
1281        });
1282    }
1283
1284    let pieces = split_top_level_word(input, "with");
1285    let mut members = Vec::with_capacity(pieces.len());
1286    let mut telescope: Option<Vec<String>> = None;
1287    let mut declared = pieces.len() > 1;
1288    for piece in &pieces {
1289        let (header, ctors_str) = match TermParser::find_top_level(piece, ":=") {
1290            Some(at) => (piece[..at].trim(), Some(piece[at + 2..].trim())),
1291            None => (piece.trim(), None),
1292        };
1293        let head = parse_inductive_header(surface, header)?;
1294        declared |= head.universes.is_some() || head.arity.is_some();
1295        if let Some(own) = head.universes {
1296            match &telescope {
1297                None if members.is_empty() => telescope = Some(own),
1298                Some(first) if *first == own => {}
1299                _ => {
1300                    return Err(ParseError::Unsupported {
1301                        what: format!("a second universe telescope on `{}`", head.name),
1302                        why: "the members of one inductive block share ONE universe telescope, \
1303                              written on the first member"
1304                            .to_string(),
1305                    })
1306                }
1307            }
1308        }
1309        let constructors = match ctors_str {
1310            Some(text) => parse_constructors(surface, text)?,
1311            None => Vec::new(),
1312        };
1313        members.push((
1314            head.name,
1315            head.params,
1316            head.arity,
1317            ctors_str.is_some(),
1318            constructors,
1319        ));
1320    }
1321
1322    // A restated constructor telescope is block syntax: the legacy form has no field for it.
1323    declared |= members.iter().any(|m| m.4.iter().any(|(_, _, full)| *full));
1324    if !declared {
1325        let (name, params, _, _, constructors) = members.pop().expect("one member");
1326        if constructors.is_empty() {
1327            return Err(ParseError::Missing("constructors".to_string()));
1328        }
1329        return Ok(Command::Inductive {
1330            name,
1331            params,
1332            sort: Term::Sort(Universe::Type(0)),
1333            constructors: constructors.into_iter().map(|(n, t, _)| (n, t)).collect(),
1334        });
1335    }
1336    let members = members
1337        .into_iter()
1338        .map(|(name, params, arity, has_assign, constructors)| {
1339            if !has_assign && arity.is_none() {
1340                return Err(ParseError::Missing(format!(
1341                    "`:=` and the constructors of `{name}` \u{2014} a member with no constructors \
1342                     declares its arity (`{name} : Type`)"
1343                )));
1344            }
1345            let full = constructors.iter().any(|(_, _, f)| *f);
1346            if full && constructors.iter().any(|(_, _, f)| !*f) {
1347                return Err(ParseError::Unsupported {
1348                    what: format!(
1349                        "`{name}` restating the parameters of some constructors and not others"
1350                    ),
1351                    why: "a member's constructors are written one way: every one restates the \
1352                          parameter telescope, or none does"
1353                        .to_string(),
1354                });
1355            }
1356            if full && params.is_empty() {
1357                return Err(ParseError::Unsupported {
1358                    what: format!("a restated telescope on a constructor of `{name}`"),
1359                    why: format!("`{name}` has no parameters to restate"),
1360                });
1361            }
1362            Ok(super::command::InductiveMember {
1363                name,
1364                params,
1365                sort: arity.unwrap_or(Term::Sort(Universe::Type(0))),
1366                constructors: constructors.into_iter().map(|(n, t, _)| (n, t)).collect(),
1367                full_constructors: full,
1368            })
1369        })
1370        .collect::<Result<Vec<_>, _>>()?;
1371    Ok(with_universes(
1372        telescope,
1373        Command::InductiveBlock { members },
1374    ))
1375}
1376
1377/// `C1 : T1 | C2 : T2` — split at a TOP-LEVEL `|`. A `|` inside a bracket, a string or a
1378/// «quoted name» belongs to the constructor's type, not to the alternation.
1379///
1380/// A constructor may RESTATE its parameter telescope before the colon — `C (p : T) … : rest` —
1381/// and then its type is the full `(p : T) -> … -> rest`, the binders in scope in `rest`. The third
1382/// component says which form was written.
1383fn parse_constructors(
1384    surface: &Surface,
1385    input: &str,
1386) -> Result<Vec<(String, Term, bool)>, ParseError> {
1387    let mut constructors = Vec::new();
1388    for ctor_part in split_top_level(input, "|") {
1389        let ctor_part = ctor_part.trim();
1390        if ctor_part.is_empty() {
1391            continue;
1392        }
1393
1394        // Each constructor is: Name : Type, or Name (p : T) … : Type
1395        let colon_pos = TermParser::find_top_level(ctor_part, ":").ok_or(ParseError::Missing(
1396            "constructor type annotation".to_string(),
1397        ))?;
1398        let head = ctor_part[..colon_pos].trim();
1399        let name_len = Name::scan(head).map_or(head.len(), |(_, len)| len);
1400        let ctor_name = declaration_name(&head[..name_len])?;
1401        let restated = head[name_len..].trim();
1402        let ctor_type_str = ctor_part[colon_pos + 1..].trim();
1403
1404        if restated.is_empty() {
1405            constructors.push((
1406                ctor_name,
1407                TermParser::parse_in(surface, ctor_type_str)?,
1408                false,
1409            ));
1410        } else {
1411            if !restated.starts_with('(') {
1412                return Err(ParseError::Expected {
1413                    expected: format!(
1414                        "`:` or the parameter binders `(p : T)` after the constructor `{ctor_name}`"
1415                    ),
1416                    found: restated.chars().take(12).collect(),
1417                });
1418            }
1419            let full = format!("{restated} -> {ctor_type_str}");
1420            constructors.push((ctor_name, TermParser::parse_in(surface, &full)?, true));
1421        }
1422    }
1423    Ok(constructors)
1424}
1425
1426/// `input` cut at every TOP-LEVEL occurrence of the WORD `word` — outside every bracket, string
1427/// and «quoted name», and never inside a longer identifier (`without` holds no `with`).
1428fn split_top_level_word<'a>(input: &'a str, word: &str) -> Vec<&'a str> {
1429    let is_ident = |c: char| c.is_alphanumeric() || c == '_' || c == '\'';
1430    let mut parts = Vec::new();
1431    let mut start = 0;
1432    let mut from = 0;
1433    while let Some(rel) = TermParser::find_top_level(&input[from..], word) {
1434        let at = from + rel;
1435        let before = input[..at].chars().next_back();
1436        let after = input[at + word.len()..].chars().next();
1437        if before.is_none_or(|c| !is_ident(c)) && after.is_none_or(|c| !is_ident(c)) {
1438            parts.push(&input[start..at]);
1439            start = at + word.len();
1440        }
1441        from = at + word.len();
1442    }
1443    parts.push(&input[start..]);
1444    parts
1445}
1446
1447/// An inductive member's header, read: its name, its universe telescope if it wrote one, its
1448/// parameters, and its declared arity if it wrote one.
1449struct InductiveHeader {
1450    name: String,
1451    universes: Option<Vec<String>>,
1452    params: Vec<(String, Term)>,
1453    arity: Option<Term>,
1454}
1455
1456/// Parse the inductive header: name, optional `.{u, …}`, parameters, optional `: arity`.
1457///
1458/// Examples:
1459/// - `List` -> ("List", [])
1460/// - `List (A : Type)` -> ("List", [("A", Type)])
1461/// - `Either (A : Type) (B : Type)` -> ("Either", [("A", Type), ("B", Type)])
1462/// - `Vec.{u} (A : Sort u) : Nat -> Sort (max 1 u)` -> ("Vec", [u], [("A", Sort u)], arity)
1463fn parse_inductive_header(surface: &Surface, header: &str) -> Result<InductiveHeader, ParseError> {
1464    let header = header.trim();
1465
1466    // The NAME is however much of the header the name grammar reads, and the rest is the parameter
1467    // list. Scanning for the first `(` instead put the split INSIDE a «quoted name» that contained
1468    // one, so `«odd(name»` was refused for a reason that named neither the name nor the parameters
1469    // — the same raw-search mistake the sentence split was making, one door along.
1470    let name_len = Name::scan(header).map_or(header.len(), |(_, len)| len);
1471    let name = declaration_name(&header[..name_len])?;
1472    let mut rest = header[name_len..].trim_start();
1473    let mut universes = None;
1474    if let Some(after) = rest.strip_prefix(".{") {
1475        let close = after.find('}').ok_or_else(|| {
1476            ParseError::Missing(format!("`}}` closing the universe parameters of `{name}`"))
1477        })?;
1478        universes = Some(universe_names(&after[..close])?);
1479        rest = after[close + 1..].trim_start();
1480    }
1481    let (params_str, arity) = match TermParser::find_top_level(rest, ":") {
1482        Some(at) => (
1483            rest[..at].trim(),
1484            Some(TermParser::parse_in(surface, rest[at + 1..].trim())?),
1485        ),
1486        None => (rest.trim(), None),
1487    };
1488    let params = if params_str.is_empty() {
1489        Vec::new()
1490    } else {
1491        // Parse all parameter bindings: (A : Type) (B : Type) ...
1492        parse_param_bindings(surface, params_str)?
1493    };
1494    Ok(InductiveHeader {
1495        name,
1496        universes,
1497        params,
1498        arity,
1499    })
1500}
1501
1502/// Parse a sequence of parameter bindings: (A : Type) (B : Type)
1503///
1504/// Each binding is of the form (name : type).
1505fn parse_param_bindings(surface: &Surface, input: &str) -> Result<Vec<(String, Term)>, ParseError> {
1506    let mut params = Vec::new();
1507    let mut remaining = input.trim();
1508
1509    while !remaining.is_empty() {
1510        // Skip whitespace
1511        remaining = remaining.trim();
1512        if remaining.is_empty() {
1513            break;
1514        }
1515
1516        // Expect '('
1517        if !remaining.starts_with('(') {
1518            return Err(ParseError::Missing("opening '(' for parameter".to_string()));
1519        }
1520
1521        // Find matching ')'
1522        let close_pos = find_matching_paren(remaining)?;
1523        let binding = &remaining[1..close_pos]; // Contents inside parens
1524
1525        // Parse name : type — at TOP LEVEL, so `(f : (x : Nat) -> Nat)` splits at its OWN colon.
1526        let colon_pos = TermParser::find_top_level(binding, ":")
1527            .ok_or(ParseError::Missing("':' in parameter binding".to_string()))?;
1528
1529        // The parameter's name is read by the NAME GRAMMAR, not taken verbatim. A binder name is
1530        // what the constructor types refer to, and the term door hands those references back
1531        // UNQUOTED — so a verbatim `«a:b»` bound a parameter under a spelling no term could
1532        // produce and the registration failed with `UnboundVariable("a:b")`, one layer away from
1533        // the binding that caused it.
1534        let written = binding[..colon_pos].trim();
1535        let param_name = match Name::scan(written) {
1536            Some((name, len)) if len == written.len() => name.key(),
1537            _ => {
1538                return Err(ParseError::Missing(format!(
1539                    "a parameter name in {written:?}"
1540                )))
1541            }
1542        };
1543        let param_type_str = binding[colon_pos + 1..].trim();
1544
1545        let param_type = TermParser::parse_in(surface, param_type_str)?;
1546        params.push((param_name, param_type));
1547
1548        // Move past this binding
1549        remaining = remaining[close_pos + 1..].trim();
1550    }
1551
1552    Ok(params)
1553}
1554
1555/// The BYTE offset of the `)` that matches the opening `(` at position 0.
1556///
1557/// ★ A CHAR INDEX IS NOT A BYTE INDEX. This counted characters and the caller sliced with the
1558/// result, so one multi-byte character anywhere inside a parameter list moved every later
1559/// boundary: `Inductive Box («a:b» : Type)` cut the binding short of its own `)` and the next
1560/// iteration reported a missing `(` for a parameter nobody wrote. Every non-ASCII spelling this
1561/// vernacular deliberately supports — a «quoted name», a declared notation, a Unicode identifier —
1562/// is in that class, and a slice that lands mid-character panics outright rather than misreads.
1563fn find_matching_paren(input: &str) -> Result<usize, ParseError> {
1564    let mut depth = 0;
1565    let mut in_string = false;
1566    let mut in_name = false;
1567    let mut escaped = false;
1568    for (i, c) in input.char_indices() {
1569        // A parenthesis inside a string literal or a «quoted name» is TEXT, not structure — the
1570        // same rule `TermParser::find_top_level` applies, so a parameter's type may hold either.
1571        if escaped {
1572            escaped = false;
1573            continue;
1574        }
1575        if in_string {
1576            match c {
1577                '\\' => escaped = true,
1578                '"' => in_string = false,
1579                _ => {}
1580            }
1581            continue;
1582        }
1583        if in_name {
1584            in_name = c != '\u{bb}';
1585            continue;
1586        }
1587        match c {
1588            '"' => in_string = true,
1589            '\u{ab}' => in_name = true,
1590            '(' => depth += 1,
1591            ')' => {
1592                depth -= 1;
1593                if depth == 0 {
1594                    return Ok(i);
1595                }
1596            }
1597            _ => {}
1598        }
1599    }
1600    Err(ParseError::Missing("closing ')' for parameter".to_string()))
1601}
1602
1603#[cfg(test)]
1604#[path = "../../../logicaffeine_tests/unit/logicaffeine_kernel/interface/command_parser/tests.rs"]
1605mod tests;