1use 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
67pub fn parse_command(input: &str) -> Result<Command, ParseError> {
76 parse_command_in(&Surface::new(), input)
77}
78
79pub 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
92pub 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 if let Some(len) = comment_len(rest)? {
110 return Ok((Command::Comment, lead + len));
111 }
112
113 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 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 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 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 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 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 let end = sentence_end(rest);
193 let sentence = rest[..end].trim_end();
194 let body = sentence.strip_suffix('.').unwrap_or(sentence).trim();
195
196 let body = body.strip_prefix("Local ").unwrap_or(body).trim_start();
199
200 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
307fn 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
319fn 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
337fn 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
374fn 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 assoc: Assoc::Right,
386 operator_form: None,
387 }))
388}
389
390fn 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
414fn 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
421fn 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
430fn 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
445fn 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
458pub(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
476pub(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 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
515fn 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
549fn declaration_name(raw: &str) -> Result<String, ParseError> {
558 super::declaration_name(raw).map(|n| n.key())
559}
560
561fn 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
574fn 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
618fn 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
631fn 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 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
673fn 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
691fn 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
707fn 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
721fn parse_definition(surface: &Surface, input: &str) -> Result<Command, ParseError> {
733 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 if let Some(colon_pos) = TermParser::find_top_level(before_assign, ":") {
742 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 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
780fn 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 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
827fn 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
852fn 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 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
1045fn 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
1064fn 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
1135fn 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
1168fn 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
1194fn 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
1232fn 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
1243fn parse_check(surface: &Surface, input: &str) -> Result<Command, ParseError> {
1245 let term = TermParser::parse_in(surface, input)?;
1246 Ok(Command::Check(term))
1247}
1248
1249fn parse_eval(surface: &Surface, input: &str) -> Result<Command, ParseError> {
1251 let term = TermParser::parse_in(surface, input)?;
1252 Ok(Command::Eval(term))
1253}
1254
1255fn parse_inductive(surface: &Surface, input: &str) -> Result<Command, ParseError> {
1268 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 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
1377fn 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 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
1426fn 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
1447struct InductiveHeader {
1450 name: String,
1451 universes: Option<Vec<String>>,
1452 params: Vec<(String, Term)>,
1453 arity: Option<Term>,
1454}
1455
1456fn parse_inductive_header(surface: &Surface, header: &str) -> Result<InductiveHeader, ParseError> {
1464 let header = header.trim();
1465
1466 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_param_bindings(surface, params_str)?
1493 };
1494 Ok(InductiveHeader {
1495 name,
1496 universes,
1497 params,
1498 arity,
1499 })
1500}
1501
1502fn 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 remaining = remaining.trim();
1512 if remaining.is_empty() {
1513 break;
1514 }
1515
1516 if !remaining.starts_with('(') {
1518 return Err(ParseError::Missing("opening '(' for parameter".to_string()));
1519 }
1520
1521 let close_pos = find_matching_paren(remaining)?;
1523 let binding = &remaining[1..close_pos]; let colon_pos = TermParser::find_top_level(binding, ":")
1527 .ok_or(ParseError::Missing("':' in parameter binding".to_string()))?;
1528
1529 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 remaining = remaining[close_pos + 1..].trim();
1550 }
1551
1552 Ok(params)
1553}
1554
1555fn 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 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;