1use super::command::Command;
47use super::error::ParseError;
48use super::match_compile::{compile_clauses_reporting, pattern_binder_types, Clause, Pattern};
49use super::surface::{respell_names, Name, Namespaces, Resolution};
50use super::with_env;
51use crate::{infer_type, normalize, Context, Literal, Term, Universe};
52use std::collections::HashSet;
53
54fn build_script_name_list(names: &[String]) -> Term {
57 let sname = |s: &str| {
58 Term::App(
59 Box::new(Term::Global("SName".to_string())),
60 Box::new(Term::Lit(Literal::Text(s.to_string()))),
61 )
62 };
63 let sapp = |x: Term, y: Term| {
64 Term::App(
65 Box::new(Term::App(
66 Box::new(Term::Global("SApp".to_string())),
67 Box::new(x),
68 )),
69 Box::new(y),
70 )
71 };
72 let mut result = sname("end");
73 for n in names.iter().rev() {
74 result = sapp(sapp(sname("step"), sname(n)), result);
75 }
76 result
77}
78
79pub const ONE_SHOT_TACTICS: &[(&str, &str)] = &[
84 ("ring", "try_ring"),
85 ("refl", "try_refl"),
86 ("lia", "try_lia"),
87 ("cc", "try_cc"),
88 ("simp", "try_simp"),
89 ("omega", "try_omega"),
90 ("assumption", "try_assumption"),
91 ("split", "try_split"),
92 ("left", "try_left"),
93 ("right", "try_right"),
94 ("decide", "try_decide"),
95 ("auto", "try_auto"),
96];
97
98fn apply1(global: &str, arg: Term) -> Term {
100 Term::App(Box::new(Term::Global(global.to_string())), Box::new(arg))
101}
102
103const EIGENVARIABLE_MARK: &str = "#eig";
118
119fn to_eigenvariables(
131 ctx: Option<&Context>,
132 body: &Term,
133 binders: &[(String, Term)],
134 except: Option<&str>,
135) -> Term {
136 let mut taken: HashSet<String> = HashSet::new();
137 super::spelled_names(body, &mut taken);
138 for (name, ty) in binders {
139 taken.insert(name.clone());
140 super::spelled_names(ty, &mut taken);
141 }
142
143 let mut acc = body.clone();
144 for (name, _) in binders
145 .iter()
146 .filter(|(name, _)| Some(name.as_str()) != except)
147 {
148 let mut candidate = format!("{name}{EIGENVARIABLE_MARK}");
149 let mut step = 0usize;
150 while taken.contains(&candidate) || ctx.is_some_and(|c| c.get_global(&candidate).is_some())
151 {
152 step += 1;
153 candidate = format!("{name}{EIGENVARIABLE_MARK}{step}");
154 }
155 taken.insert(candidate.clone());
156 acc = rename_free_var(&acc, name, &candidate);
157 }
158 acc
159}
160
161fn rename_free_var(term: &Term, from: &str, to: &str) -> Term {
163 let go = |t: &Term| rename_free_var(t, from, to);
164 match term {
165 Term::Var(n) if n == from => Term::Var(to.to_string()),
166 Term::App(f, a) => Term::App(Box::new(go(f)), Box::new(go(a))),
167 Term::Lambda {
168 param,
169 param_type,
170 body,
171 } => Term::Lambda {
172 param: param.clone(),
173 param_type: Box::new(go(param_type)),
174 body: if param == from {
175 body.clone()
176 } else {
177 Box::new(go(body))
178 },
179 },
180 Term::Pi {
181 param,
182 param_type,
183 body_type,
184 } => Term::Pi {
185 param: param.clone(),
186 param_type: Box::new(go(param_type)),
187 body_type: if param == from {
188 body_type.clone()
189 } else {
190 Box::new(go(body_type))
191 },
192 },
193 Term::Fix { name, body } => Term::Fix {
194 name: name.clone(),
195 body: if name == from {
196 body.clone()
197 } else {
198 Box::new(go(body))
199 },
200 },
201 Term::MutualFix { defs, index } => Term::MutualFix {
202 defs: defs
203 .iter()
204 .map(|(n, b)| (n.clone(), if n == from { b.clone() } else { go(b) }))
205 .collect(),
206 index: *index,
207 },
208 Term::Match {
209 discriminant,
210 motive,
211 cases,
212 } => Term::Match {
213 discriminant: Box::new(go(discriminant)),
214 motive: Box::new(go(motive)),
215 cases: cases.iter().map(&go).collect(),
216 },
217 Term::Let {
218 name,
219 ty,
220 value,
221 body,
222 } => Term::Let {
223 name: name.clone(),
224 ty: Box::new(go(ty)),
225 value: Box::new(go(value)),
226 body: if name == from {
227 body.clone()
228 } else {
229 Box::new(go(body))
230 },
231 },
232 Term::Annotated { annotation, term } => Term::Annotated {
233 annotation: annotation.clone(),
234 term: Box::new(go(term)),
235 },
236 other => other.clone(),
237 }
238}
239
240fn free_name_as_variable(term: &Term, name: &str) -> Option<Term> {
244 let go = |t: &Term| free_name_as_variable(t, name);
245 Some(match term {
246 Term::Global(n) if n == name => Term::Var(name.to_string()),
247 Term::App(f, a) => Term::App(Box::new(go(f)?), Box::new(go(a)?)),
248 Term::Lambda { param, .. } | Term::Pi { param, .. } | Term::Let { name: param, .. }
249 if param == name =>
250 {
251 return None
252 }
253 Term::Fix { name: n, .. } if n == name => return None,
254 Term::MutualFix { defs, .. } if defs.iter().any(|(n, _)| n == name) => return None,
255 Term::Lambda {
256 param,
257 param_type,
258 body,
259 } => Term::Lambda {
260 param: param.clone(),
261 param_type: Box::new(go(param_type)?),
262 body: Box::new(go(body)?),
263 },
264 Term::Pi {
265 param,
266 param_type,
267 body_type,
268 } => Term::Pi {
269 param: param.clone(),
270 param_type: Box::new(go(param_type)?),
271 body_type: Box::new(go(body_type)?),
272 },
273 Term::Fix { name: n, body } => Term::Fix {
274 name: n.clone(),
275 body: Box::new(go(body)?),
276 },
277 Term::MutualFix { defs, index } => Term::MutualFix {
278 defs: defs
279 .iter()
280 .map(|(n, b)| Some((n.clone(), go(b)?)))
281 .collect::<Option<_>>()?,
282 index: *index,
283 },
284 Term::Match {
285 discriminant,
286 motive,
287 cases,
288 } => Term::Match {
289 discriminant: Box::new(go(discriminant)?),
290 motive: Box::new(go(motive)?),
291 cases: cases.iter().map(&go).collect::<Option<_>>()?,
292 },
293 Term::Let {
294 name: n,
295 ty,
296 value,
297 body,
298 } => Term::Let {
299 name: n.clone(),
300 ty: Box::new(go(ty)?),
301 value: Box::new(go(value)?),
302 body: Box::new(go(body)?),
303 },
304 Term::Annotated { annotation, term } => Term::Annotated {
305 annotation: annotation.clone(),
306 term: Box::new(go(term)?),
307 },
308 other => other.clone(),
309 })
310}
311
312fn split_universal_prefix(statement: &Term) -> (Vec<(String, Term)>, &Term) {
319 let mut binders = Vec::new();
320 let mut body = statement;
321 while let Term::Pi {
322 param,
323 param_type,
324 body_type,
325 } = body
326 {
327 if param == "_" {
328 break;
329 }
330 binders.push((param.clone(), param_type.as_ref().clone()));
331 body = body_type;
332 }
333 (binders, body)
334}
335
336fn forall_syntax(ind_type: &Term, motive: &Term) -> Term {
339 let sapp = |f: Term, x: Term| {
340 Term::App(
341 Box::new(Term::App(
342 Box::new(Term::Global("SApp".to_string())),
343 Box::new(f),
344 )),
345 Box::new(x),
346 )
347 };
348 let sname_forall = Term::App(
349 Box::new(Term::Global("SName".to_string())),
350 Box::new(Term::Lit(Literal::Text("Forall".to_string()))),
351 );
352 sapp(sapp(sname_forall, ind_type.clone()), motive.clone())
353}
354
355fn case_goal_term(ind_type: &Term, motive: &Term, index: usize) -> Term {
359 let mut idx = Term::Global("Zero".to_string());
360 for _ in 0..index {
361 idx = Term::App(Box::new(Term::Global("Succ".to_string())), Box::new(idx));
362 }
363 Term::App(
364 Box::new(Term::App(
365 Box::new(Term::App(
366 Box::new(Term::Global("induction_step_goal".to_string())),
367 Box::new(ind_type.clone()),
368 )),
369 Box::new(motive.clone()),
370 )),
371 Box::new(idx),
372 )
373}
374
375fn is_sname(term: &Term, name: &str) -> bool {
377 matches!(term, Term::App(f, x)
378 if matches!(f.as_ref(), Term::Global(n) if n == "SName")
379 && matches!(x.as_ref(), Term::Lit(Literal::Text(s)) if s == name))
380}
381
382fn as_sapp2(term: &Term, head: &str) -> Option<(Term, Term)> {
384 let Term::App(f, b) = term else { return None };
385 let Term::App(sapp_outer, inner) = f.as_ref() else {
386 return None;
387 };
388 if !matches!(sapp_outer.as_ref(), Term::Global(n) if n == "SApp") {
389 return None;
390 }
391 let Term::App(g, a) = inner.as_ref() else {
392 return None;
393 };
394 let Term::App(sapp_inner, sname) = g.as_ref() else {
395 return None;
396 };
397 if !matches!(sapp_inner.as_ref(), Term::Global(n) if n == "SApp") {
398 return None;
399 }
400 if !is_sname(sname, head) {
401 return None;
402 }
403 Some(((**a).clone(), (**b).clone()))
404}
405
406fn as_slam_body(term: &Term) -> Option<Term> {
408 let Term::App(f, body) = term else {
409 return None;
410 };
411 let Term::App(slam, _ty) = f.as_ref() else {
412 return None;
413 };
414 if !matches!(slam.as_ref(), Term::Global(n) if n == "SLam") {
415 return None;
416 }
417 Some((**body).clone())
418}
419
420fn as_spi(term: &Term) -> Option<(Term, Term)> {
422 let Term::App(f, body) = term else {
423 return None;
424 };
425 let Term::App(spi, ty) = f.as_ref() else {
426 return None;
427 };
428 if !matches!(spi.as_ref(), Term::Global(n) if n == "SPi") {
429 return None;
430 }
431 Some(((**ty).clone(), (**body).clone()))
432}
433
434fn peel_one_binder(goal: &Term) -> Option<Term> {
456 if let Some((_ty, motive)) = as_sapp2(goal, "Forall") {
457 return as_slam_body(&motive);
458 }
459 for spelling in ["Implies", "implies"] {
460 if let Some((_p, q)) = as_sapp2(goal, spelling) {
461 return Some(q);
462 }
463 }
464 as_spi(goal).map(|(_a, b)| b)
465}
466
467fn goal_binder_depth(goal: &Term) -> usize {
469 let mut depth = 0;
470 let mut cur = goal.clone();
471 while let Some(next) = peel_one_binder(&cur) {
472 depth += 1;
473 cur = next;
474 }
475 depth
476}
477
478pub fn parse_inductive(input: &str) -> Result<(Command, usize), ParseError> {
489 let mut parser = LiterateParser::new(input);
490 let cmd = parser.parse_literate_inductive()?;
491 Ok((cmd, parser.pos))
492}
493
494pub fn parse_definition(input: &str) -> Result<(Command, usize), ParseError> {
503 let mut parser = LiterateParser::new(input);
504 let cmd = parser.parse_literate_definition()?;
505 Ok((cmd, parser.pos))
506}
507
508pub fn parse_definition_in(ctx: &Context, input: &str) -> Result<(Command, usize), ParseError> {
517 parse_definition_scoped(ctx, &Namespaces::new(), input)
518}
519
520pub fn parse_definition_scoped(
523 ctx: &Context,
524 scope: &Namespaces,
525 input: &str,
526) -> Result<(Command, usize), ParseError> {
527 let mut parser = LiterateParser::new_in(input, ctx, scope);
528 let cmd = parser.parse_literate_definition()?;
529 Ok((parser.respelled(cmd)?, parser.pos))
530}
531
532pub fn parse_let_definition(input: &str) -> Result<(Command, usize), ParseError> {
538 let mut parser = LiterateParser::new(input);
539 let cmd = parser.parse_literate_let()?;
540 Ok((cmd, parser.pos))
541}
542
543pub fn parse_theorem(input: &str) -> Result<(Command, usize), ParseError> {
552 let mut parser = LiterateParser::new(input);
553 let cmd = parser.parse_literate_theorem()?;
554 Ok((cmd, parser.pos))
555}
556
557pub fn parse_theorem_in(ctx: &Context, input: &str) -> Result<(Command, usize), ParseError> {
565 parse_theorem_scoped(ctx, &Namespaces::new(), input)
566}
567
568pub fn measure_definition(input: &str) -> Result<usize, ParseError> {
571 let mut parser = LiterateParser::measuring(input);
572 parser.parse_literate_definition()?;
573 Ok(parser.pos)
574}
575
576pub fn measure_theorem(input: &str) -> Result<usize, ParseError> {
586 let mut parser = LiterateParser::measuring(input);
587 parser.parse_literate_theorem()?;
588 Ok(parser.pos)
589}
590
591pub fn parse_theorem_scoped(
595 ctx: &Context,
596 scope: &Namespaces,
597 input: &str,
598) -> Result<(Command, usize), ParseError> {
599 let mut parser = LiterateParser::new_in(input, ctx, scope);
600 let cmd = parser.parse_literate_theorem()?;
601 Ok((parser.respelled(cmd)?, parser.pos))
602}
603
604fn type_head_name(ty: &Term) -> Option<&str> {
606 let mut cur = ty;
607 while let Term::App(f, _) = cur {
608 cur = f;
609 }
610 match cur {
611 Term::Global(n) => Some(n),
612 Term::Const { name, .. } => Some(name),
613 _ => None,
614 }
615}
616
617fn flat_positional_match(
626 discriminants: Vec<Term>,
627 motive: Term,
628 clauses: &[Clause],
629) -> Result<Term, ParseError> {
630 let needs_compiler = |what: &str| {
631 ParseError::InvalidConsiderSyntax(format!(
632 "{what} is compiled against the inductive's constructor list, which lives in the \
633 kernel context — this parser has none. Read the definition through \
634 `interface::parse_command_in_ctx` (or `literate_parser::parse_definition_in`), \
635 which does."
636 ))
637 };
638
639 let [discriminant] = <[Term; 1]>::try_from(discriminants)
642 .map_err(|_| needs_compiler("a multi-column `Consider … and …`"))?;
643
644 let mut cases = Vec::with_capacity(clauses.len());
645 for clause in clauses {
646 if clause.patterns.len() != 1 {
647 return Err(needs_compiler("a multi-column equation set"));
648 }
649 let Pattern::Ctor { args, .. } = &clause.patterns[0] else {
650 return Err(needs_compiler("a `When _:` catch-all"));
651 };
652 let mut binders = Vec::with_capacity(args.len());
653 for arg in args {
654 match arg {
655 Pattern::Var(n) => binders.push(n.clone()),
656 Pattern::Wildcard => binders.push("_".to_string()),
657 Pattern::Ctor { .. } => return Err(needs_compiler("a nested constructor pattern")),
658 Pattern::Numeral(_) => return Err(needs_compiler("a numeral pattern")),
659 }
660 }
661 let mut body = clause.body.clone();
662 for binder in binders.into_iter().rev() {
663 body = Term::Lambda {
664 param: binder,
665 param_type: Box::new(Term::Global("_".to_string())),
666 body: Box::new(body),
667 };
668 }
669 cases.push(body);
670 }
671
672 Ok(Term::Match {
673 discriminant: Box::new(discriminant),
674 motive: Box::new(motive),
675 cases,
676 })
677}
678
679struct LiterateParser<'a> {
684 input: &'a str,
685 pos: usize,
686 bound_vars: HashSet<String>,
687 current_function: Option<String>,
688 return_type: Option<Term>,
690 ctx: Option<&'a Context>,
697 scope: Namespaces,
701 locals: Vec<(String, Term)>,
704 measuring: bool,
707}
708
709impl<'a> LiterateParser<'a> {
710 fn new(input: &'a str) -> Self {
711 Self {
712 input,
713 pos: 0,
714 bound_vars: HashSet::new(),
715 current_function: None,
716 return_type: None,
717 ctx: None,
718 scope: Namespaces::new(),
719 locals: Vec::new(),
720 measuring: false,
721 }
722 }
723
724 fn measuring(input: &'a str) -> Self {
726 Self {
727 measuring: true,
728 ..Self::new(input)
729 }
730 }
731
732 fn new_in(input: &'a str, ctx: &'a Context, scope: &Namespaces) -> Self {
735 Self {
736 ctx: Some(ctx),
737 scope: scope.clone(),
738 ..Self::new(input)
739 }
740 }
741
742 fn denote(&self, written: String) -> Result<String, ParseError> {
750 let Some(ctx) = self.ctx else {
751 return Ok(written);
752 };
753 let Some(name) = Name::parse(&written) else {
754 return Ok(written);
755 };
756 match with_env(ctx, &[], |env| env.resolve(&self.scope, &name)) {
757 Resolution::Found(key) => Ok(key),
758 Resolution::Unresolved(_) => Ok(written),
759 Resolution::Ambiguous {
760 written,
761 candidates,
762 } => Err(ParseError::AmbiguousName {
763 written,
764 candidates,
765 }),
766 }
767 }
768
769 fn global(&self, written: impl Into<String>) -> Result<Term, ParseError> {
771 Ok(Term::Global(self.denote(written.into())?))
772 }
773
774 fn respelled(&self, cmd: Command) -> Result<Command, ParseError> {
779 let Some(ctx) = self.ctx else { return Ok(cmd) };
780 let respell = |t: Term| -> Result<Term, ParseError> {
781 with_env(ctx, &[], |env| {
782 respell_names(&self.scope, env, &mut Vec::new(), &t).map(|r| r.into_owned())
783 })
784 };
785 match cmd {
786 Command::Definition {
787 name,
788 ty,
789 body,
790 is_hint,
791 implicit_count,
792 proof_goal,
793 } => Ok(Command::Definition {
794 name,
795 ty: ty.map(respell).transpose()?,
796 body: respell(body)?,
797 is_hint,
798 implicit_count,
799 proof_goal: proof_goal.map(respell).transpose()?,
800 }),
801 other => Ok(other),
802 }
803 }
804
805 fn working_context(&self) -> Option<Context> {
808 let base = self.ctx?;
809 Some(
810 self.locals
811 .iter()
812 .fold(base.clone(), |acc, (n, t)| acc.extend(n, t.clone())),
813 )
814 }
815
816 fn parse_literate_inductive(&mut self) -> Result<Command, ParseError> {
822 self.skip_whitespace();
823
824 if self.try_consume_keyword("An") || self.try_consume_keyword("A") {
826 } else {
828 return Err(ParseError::Expected {
829 expected: "'A' or 'An'".to_string(),
830 found: self.peek_word().unwrap_or("EOF".to_string()),
831 });
832 }
833
834 self.skip_whitespace();
835
836 let name = self.parse_declaration_name()?;
838
839 self.skip_whitespace();
840
841 let params = if self.try_consume_keyword("of") {
843 self.skip_whitespace();
844 self.parse_param_list()?
845 } else {
846 vec![]
847 };
848
849 self.skip_whitespace();
850
851 if !self.try_consume_keyword("is") {
853 return Err(ParseError::Expected {
854 expected: "'is'".to_string(),
855 found: self.peek_word().unwrap_or("EOF".to_string()),
856 });
857 }
858 self.skip_whitespace();
859 if !self.try_consume_keyword("either") {
860 return Err(ParseError::Expected {
861 expected: "'either'".to_string(),
862 found: self.peek_word().unwrap_or("EOF".to_string()),
863 });
864 }
865
866 self.skip_whitespace();
867
868 let constructors = if self.peek_char(':') {
870 self.advance(); self.parse_indented_variants(&name, ¶ms)?
873 } else {
874 self.parse_inline_variants(&name, ¶ms)?
876 };
877
878 if constructors.is_empty() {
879 return Err(ParseError::Missing("constructors".to_string()));
880 }
881
882 Ok(Command::Inductive {
883 name,
884 params,
885 sort: Term::Sort(Universe::Type(0)),
886 constructors,
887 })
888 }
889
890 fn parse_inline_variants(
892 &mut self,
893 inductive_name: &str,
894 params: &[(String, Term)],
895 ) -> Result<Vec<(String, Term)>, ParseError> {
896 let mut constructors = Vec::new();
897
898 loop {
899 self.skip_whitespace();
900
901 if self.at_end() || self.peek_char('.') {
902 break;
903 }
904
905 let (ctor_name, ctor_type) = self.parse_variant(inductive_name, params)?;
907 constructors.push((ctor_name, ctor_type));
908
909 self.skip_whitespace();
910
911 if !self.try_consume_keyword("or") {
913 break;
914 }
915 }
916
917 self.skip_whitespace();
919 let _ = self.try_consume(".");
920
921 Ok(constructors)
922 }
923
924 fn parse_indented_variants(
926 &mut self,
927 inductive_name: &str,
928 params: &[(String, Term)],
929 ) -> Result<Vec<(String, Term)>, ParseError> {
930 let mut constructors = Vec::new();
931
932 loop {
933 self.skip_whitespace_and_newlines();
934
935 if self.at_end() {
936 break;
937 }
938
939 if !self.peek_char(' ')
941 && !self.peek_char('\t')
942 && !self.peek_char('a')
943 && !self.peek_char('A')
944 {
945 if let Some(c) = self.peek() {
947 if !c.is_uppercase() && c != 'a' && c != 'A' {
948 break;
949 }
950 }
951 }
952
953 self.skip_whitespace();
955
956 if self.at_end() {
958 break;
959 }
960
961 let (ctor_name, ctor_type) = self.parse_variant(inductive_name, params)?;
963 constructors.push((ctor_name, ctor_type));
964
965 self.skip_whitespace();
967 let _ = self.try_consume(".");
968 }
969
970 Ok(constructors)
971 }
972
973 fn parse_variant(
975 &mut self,
976 inductive_name: &str,
977 params: &[(String, Term)],
978 ) -> Result<(String, Term), ParseError> {
979 self.skip_whitespace();
980
981 let _ = self.try_consume_keyword("an") || self.try_consume_keyword("a");
983 self.skip_whitespace();
984
985 let ctor_name = self.parse_declaration_name()?;
987
988 self.skip_whitespace();
989
990 let result_type = self.build_applied_type(inductive_name, params);
992
993 if self.try_consume_keyword("with") {
995 let fields = self.parse_field_list()?;
997
998 let mut ctor_type = result_type;
1000 for (_field_name, field_type) in fields.into_iter().rev() {
1001 ctor_type = Term::Pi {
1002 param: "_".to_string(),
1003 param_type: Box::new(field_type),
1004 body_type: Box::new(ctor_type),
1005 };
1006 }
1007
1008 Ok((ctor_name, ctor_type))
1009 } else {
1010 Ok((ctor_name, result_type))
1012 }
1013 }
1014
1015 fn parse_field_list(&mut self) -> Result<Vec<(String, Term)>, ParseError> {
1017 let mut fields = Vec::new();
1018
1019 loop {
1020 self.skip_whitespace();
1021
1022 let field_name = self.parse_ident()?;
1024
1025 self.skip_whitespace();
1026
1027 if !self.try_consume(":") {
1029 return Err(ParseError::Expected {
1030 expected: "':'".to_string(),
1031 found: self.peek_word().unwrap_or("EOF".to_string()),
1032 });
1033 }
1034
1035 self.skip_whitespace();
1036
1037 let field_type = self.parse_type()?;
1039
1040 fields.push((field_name, field_type));
1041
1042 self.skip_whitespace();
1043
1044 if !self.try_consume_keyword("and") {
1046 break;
1047 }
1048 }
1049
1050 Ok(fields)
1051 }
1052
1053 fn build_applied_type(&self, name: &str, params: &[(String, Term)]) -> Term {
1055 let mut result = Term::Global(name.to_string());
1056 for (param_name, _) in params {
1057 result = Term::App(Box::new(result), Box::new(Term::Var(param_name.clone())));
1058 }
1059 result
1060 }
1061
1062 fn parse_literate_definition(&mut self) -> Result<Command, ParseError> {
1068 self.skip_whitespace();
1069
1070 if !self.try_consume("## To ") && !self.try_consume("##To ") {
1072 return Err(ParseError::Expected {
1073 expected: "'## To'".to_string(),
1074 found: self.peek_word().unwrap_or("EOF".to_string()),
1075 });
1076 }
1077
1078 self.skip_whitespace();
1079
1080 let mut name = self.parse_declaration_name()?;
1082
1083 if name == "be" {
1086 self.skip_whitespace();
1087 name = self.parse_declaration_name()?;
1088 }
1089
1090 self.current_function = Some(name.clone());
1091
1092 self.skip_whitespace();
1093
1094 let all_params = self.parse_function_params()?;
1097
1098 self.skip_whitespace();
1099
1100 let return_type = if self.try_consume("->") {
1102 self.skip_whitespace();
1103 let ret = self.parse_type()?;
1104 self.return_type = Some(ret.clone());
1106 Some(ret)
1107 } else {
1108 None
1109 };
1110
1111 self.skip_whitespace();
1112
1113 if !self.try_consume(":") {
1115 return Err(ParseError::Expected {
1116 expected: "':'".to_string(),
1117 found: self.peek_word().unwrap_or("EOF".to_string()),
1118 });
1119 }
1120
1121 for (param_name, param_type) in &all_params {
1124 self.bound_vars.insert(param_name.clone());
1125 self.locals.push((param_name.clone(), param_type.clone()));
1126 }
1127
1128 self.skip_whitespace_and_newlines();
1130 let body = self.parse_body()?;
1131
1132 let needs_fix = self.contains_self_reference(&name, &body);
1134
1135 let mut func_body = body;
1137 for (param_name, param_type) in all_params.iter().rev() {
1138 func_body = Term::Lambda {
1139 param: param_name.clone(),
1140 param_type: Box::new(param_type.clone()),
1141 body: Box::new(func_body),
1142 };
1143 }
1144
1145 if needs_fix {
1147 func_body = Term::Fix {
1148 name: name.clone(),
1149 body: Box::new(func_body),
1150 };
1151 }
1152
1153 let ty = if let Some(ret) = return_type {
1155 let mut full_type = ret;
1156 for (_, param_type) in all_params.iter().rev() {
1157 full_type = Term::Pi {
1158 param: "_".to_string(),
1159 param_type: Box::new(param_type.clone()),
1160 body_type: Box::new(full_type),
1161 };
1162 }
1163 Some(full_type)
1164 } else {
1165 None
1166 };
1167
1168 self.current_function = None;
1169
1170 Ok(Command::Definition {
1171 name,
1172 ty,
1173 body: func_body,
1174 is_hint: false,
1175 implicit_count: 0,
1176 proof_goal: None,
1177 })
1178 }
1179
1180 fn parse_literate_let(&mut self) -> Result<Command, ParseError> {
1186 self.skip_whitespace();
1187
1188 if !self.try_consume_keyword("Let") {
1190 return Err(ParseError::Expected {
1191 expected: "'Let'".to_string(),
1192 found: self.peek_word().unwrap_or("EOF".to_string()),
1193 });
1194 }
1195
1196 self.skip_whitespace();
1197
1198 let name = self.parse_declaration_name()?;
1200
1201 self.skip_whitespace();
1202
1203 if !self.try_consume_keyword("be") {
1205 return Err(ParseError::Expected {
1206 expected: "'be'".to_string(),
1207 found: self.peek_word().unwrap_or("EOF".to_string()),
1208 });
1209 }
1210
1211 self.skip_whitespace();
1212
1213 let body = self.parse_term()?;
1215
1216 self.skip_whitespace();
1218 let _ = self.try_consume(".");
1219
1220 Ok(Command::Definition {
1221 name,
1222 ty: None,
1223 body,
1224 is_hint: false,
1225 implicit_count: 0,
1226 proof_goal: None,
1227 })
1228 }
1229
1230 fn parse_literate_theorem(&mut self) -> Result<Command, ParseError> {
1235 self.skip_whitespace();
1236
1237 if !self.try_consume("## Theorem:") {
1239 return Err(ParseError::Expected {
1240 expected: "'## Theorem:'".to_string(),
1241 found: self.peek_word().unwrap_or("EOF".to_string()),
1242 });
1243 }
1244
1245 self.skip_whitespace();
1246
1247 let name = self.parse_declaration_name()?;
1249
1250 self.skip_whitespace_and_newlines();
1251
1252 if !self.try_consume_keyword("Statement") {
1254 return Err(ParseError::Expected {
1255 expected: "'Statement'".to_string(),
1256 found: self.peek_word().unwrap_or("EOF".to_string()),
1257 });
1258 }
1259 self.skip_whitespace();
1260 if !self.try_consume(":") {
1261 return Err(ParseError::Expected {
1262 expected: "':'".to_string(),
1263 found: self.peek_word().unwrap_or("EOF".to_string()),
1264 });
1265 }
1266
1267 self.skip_whitespace();
1268
1269 let statement = self.parse_term()?;
1271
1272 self.skip_whitespace();
1274 let _ = self.try_consume(".");
1275
1276 self.skip_whitespace_and_newlines();
1277
1278 let (body, ty, proof_goal) = if self.try_consume_keyword("Proof") {
1280 self.skip_whitespace();
1281 if !self.try_consume(":") {
1282 return Err(ParseError::Expected {
1283 expected: "':'".to_string(),
1284 found: self.peek_word().unwrap_or("EOF".to_string()),
1285 });
1286 }
1287 self.skip_whitespace();
1288
1289 let (proof, goal_syntax) = self.parse_proof_tactic(&statement)?;
1298
1299 self.skip_whitespace();
1301 let _ = self.try_consume(".");
1302
1303 (
1304 proof,
1305 Some(Term::Global("Derivation".to_string())),
1306 Some(goal_syntax),
1307 )
1308 } else {
1309 (statement, Some(Term::Sort(Universe::Prop)), None)
1311 };
1312
1313 self.skip_whitespace_and_newlines();
1315 let is_hint = if self.try_consume_keyword("Attribute") {
1316 self.skip_whitespace();
1317 if !self.try_consume(":") {
1318 return Err(ParseError::Expected {
1319 expected: "':'".to_string(),
1320 found: self.peek_word().unwrap_or("EOF".to_string()),
1321 });
1322 }
1323 self.skip_whitespace();
1324
1325 let hint = self.try_consume_keyword("hint");
1326
1327 self.skip_whitespace();
1329 let _ = self.try_consume(".");
1330
1331 hint
1332 } else {
1333 false
1334 };
1335
1336 Ok(Command::Definition {
1337 name,
1338 ty,
1339 body,
1340 is_hint,
1341 implicit_count: 0,
1342 proof_goal,
1343 })
1344 }
1345
1346 fn parse_step_name(&mut self, allow_intro_binder: bool) -> Option<String> {
1360 for kw in std::iter::once("intro").chain(ONE_SHOT_TACTICS.iter().map(|(k, _)| *k)) {
1361 if self.try_consume_keyword(kw) {
1362 self.skip_whitespace();
1363 if allow_intro_binder && kw == "intro" && !self.peek_char('.') && !self.at_end() {
1364 let _ = self.parse_ident();
1365 self.skip_whitespace();
1366 }
1367 let _ = self.try_consume(".");
1368 return Some(kw.to_string());
1369 }
1370 }
1371 None
1372 }
1373
1374 fn parse_script_step_name(&mut self) -> Option<String> {
1377 let name = self.parse_step_name(false)?;
1378 self.skip_whitespace_and_newlines();
1379 Some(name)
1380 }
1381
1382 fn parse_proof_tactic(&mut self, statement: &Term) -> Result<(Term, Term), ParseError> {
1388 let (binders, open_body) = split_universal_prefix(statement);
1393 let open_body = to_eigenvariables(self.ctx, open_body, &binders, None);
1394 let goal_syntax = self.term_to_syntax(&open_body, &[]);
1395
1396 for (keyword, builder) in ONE_SHOT_TACTICS {
1397 if self.try_consume_keyword(keyword) {
1398 self.skip_whitespace();
1399 let _ = self.try_consume(".");
1400 return Ok((apply1(builder, goal_syntax.clone()), goal_syntax));
1401 }
1402 }
1403
1404 if self.try_consume_keyword("intro") {
1405 self.skip_whitespace();
1409 let _ = self.try_consume(".");
1410 self.skip_whitespace_and_newlines();
1411 let mut names = vec!["intro".to_string()];
1412 while let Some(name) = self.parse_script_step_name() {
1413 names.push(name);
1414 }
1415 let list = build_script_name_list(&names);
1416 let proof = Term::App(
1417 Box::new(Term::App(
1418 Box::new(Term::Global("try_script".to_string())),
1419 Box::new(list),
1420 )),
1421 Box::new(goal_syntax.clone()),
1422 );
1423 return Ok((proof, goal_syntax));
1424 }
1425
1426 if self.try_consume_keyword("induction") {
1427 self.skip_whitespace();
1428 let var_name = self.parse_ident()?;
1429 self.skip_whitespace();
1430 let _ = self.try_consume(".");
1431 return self.parse_induction(&var_name, statement);
1432 }
1433
1434 Err(ParseError::Expected {
1435 expected: "proof tactic (ring, refl, lia, cc, simp, omega, auto, intro, induction)"
1436 .to_string(),
1437 found: self.peek_word().unwrap_or("EOF".to_string()),
1438 })
1439 }
1440
1441 fn peek_bullet(&mut self) -> bool {
1443 let saved_pos = self.pos;
1445 self.skip_whitespace_and_newlines();
1446 let result = matches!(self.peek(), Some('-') | Some('*') | Some('+'));
1447 self.pos = saved_pos;
1448 result
1449 }
1450
1451 fn consume_bullet(&mut self) {
1453 self.skip_whitespace_and_newlines();
1454 if matches!(self.peek(), Some('-') | Some('*') | Some('+')) {
1455 self.advance();
1456 }
1457 }
1458
1459 fn parse_tactic_sequence(
1477 &mut self,
1478 goal_syntax: &Term,
1479 lead_intros: usize,
1480 ) -> Result<Term, ParseError> {
1481 let mut names: Vec<String> = Vec::new();
1482
1483 loop {
1484 self.skip_whitespace();
1485
1486 if self.peek_bullet() || self.at_end() || self.peek_keyword("Attribute") {
1488 break;
1489 }
1490
1491 match self.parse_step_name(true) {
1492 Some(name) => names.push(name),
1493 None => break,
1494 }
1495 }
1496
1497 if names.is_empty() {
1498 return Err(ParseError::Missing("tactic in bullet case".to_string()));
1499 }
1500
1501 if lead_intros == 0 {
1502 if let [only] = names.as_slice() {
1503 if let Some((_, builder)) = ONE_SHOT_TACTICS.iter().find(|(k, _)| k == only) {
1504 return Ok(apply1(builder, goal_syntax.clone()));
1505 }
1506 }
1507 } else {
1508 let mut with_intros: Vec<String> = vec!["intro".to_string(); lead_intros];
1509 with_intros.extend(names);
1510 names = with_intros;
1511 }
1512
1513 Ok(Term::App(
1514 Box::new(Term::App(
1515 Box::new(Term::Global("try_script".to_string())),
1516 Box::new(build_script_name_list(&names)),
1517 )),
1518 Box::new(goal_syntax.clone()),
1519 ))
1520 }
1521
1522 fn case_binder_count(&self, case_goal: &Term, motive_body: &Term) -> usize {
1545 let Some(ctx) = self.ctx else { return 0 };
1546 let reduced = normalize(ctx, case_goal);
1547 let base = normalize(ctx, motive_body);
1548 goal_binder_depth(&reduced).saturating_sub(goal_binder_depth(&base))
1549 }
1550
1551 fn parse_induction(
1568 &mut self,
1569 var_name: &str,
1570 statement: &Term,
1571 ) -> Result<(Term, Term), ParseError> {
1572 let (binders, open_body) = split_universal_prefix(statement);
1573 let sort = match binders.iter().find(|(name, _)| name == var_name) {
1584 Some((_, ty)) => ty.clone(),
1585 None if binders.is_empty() => Term::Global("Nat".to_string()),
1586 None => {
1587 return Err(ParseError::Expected {
1588 expected: format!(
1589 "a quantified variable to induct on; this statement binds {}",
1590 binders
1591 .iter()
1592 .map(|(n, t)| format!("`{n} : {t}`"))
1593 .collect::<Vec<_>>()
1594 .join(", ")
1595 ),
1596 found: var_name.to_string(),
1597 })
1598 }
1599 };
1600
1601 let ind_type = self.term_to_syntax(&sort, &[]);
1602 let unquantified;
1608 let open_body = if binders.is_empty() {
1609 if self
1610 .ctx
1611 .is_some_and(|ctx| ctx.get_global(var_name).is_some())
1612 {
1613 return Err(ParseError::InvalidConsiderSyntax(format!(
1614 "`induction {var_name}` needs a VARIABLE to eliminate; `{var_name}` is a \
1615 declared constant"
1616 )));
1617 }
1618 unquantified = free_name_as_variable(open_body, var_name).ok_or_else(|| {
1619 ParseError::InvalidConsiderSyntax(format!(
1620 "`induction {var_name}`: the statement binds `{var_name}` itself, so its free \
1621 `{var_name}` cannot be abstracted without being captured; quantify it with \
1622 `forall` instead"
1623 ))
1624 })?;
1625 &unquantified
1626 } else {
1627 open_body
1628 };
1629 let open_body = to_eigenvariables(self.ctx, open_body, &binders, Some(var_name));
1632 let bound = [var_name.to_string()];
1633 let motive_body = self.term_to_syntax(&open_body, &bound);
1634 let motive = Term::App(
1635 Box::new(Term::App(
1636 Box::new(Term::Global("SLam".to_string())),
1637 Box::new(ind_type.clone()),
1638 )),
1639 Box::new(motive_body.clone()),
1640 );
1641
1642 let mut cases = Vec::new();
1646 while self.peek_bullet() {
1647 self.consume_bullet();
1648 self.skip_whitespace();
1649 let case_goal = case_goal_term(&ind_type, &motive, cases.len());
1650 let lead_intros = self.case_binder_count(&case_goal, &motive_body);
1651 cases.push(self.parse_tactic_sequence(&case_goal, lead_intros)?);
1652 }
1653
1654 if let Some(ctx) = self.ctx {
1659 let Some(ind_name) = type_head_name(&sort) else {
1660 return Err(ParseError::InvalidConsiderSyntax(format!(
1661 "`induction {var_name}` needs an INDUCTIVE to eliminate over; `{var_name}` \
1662 has type `{sort}`, which is not a type application"
1663 )));
1664 };
1665 let ctors = ctx.get_constructors(ind_name);
1666 if ctors.is_empty() {
1667 return Err(ParseError::InvalidConsiderSyntax(format!(
1668 "`induction {var_name}` needs an INDUCTIVE to eliminate over; `{ind_name}` \
1669 has no constructors"
1670 )));
1671 }
1672 if cases.len() != ctors.len() {
1673 return Err(ParseError::InvalidConsiderSyntax(format!(
1674 "`{ind_name}` has {} constructor(s) — {} — so this proof needs {} bullet \
1675 case(s), one per constructor, in that order; it has {}",
1676 ctors.len(),
1677 ctors.iter().map(|(n, _)| *n).collect::<Vec<_>>().join(", "),
1678 ctors.len(),
1679 cases.len()
1680 )));
1681 }
1682 }
1683
1684 let mut case_chain = Term::Global("DCaseEnd".to_string());
1687 for case_proof in cases.into_iter().rev() {
1688 case_chain = Term::App(
1689 Box::new(Term::App(
1690 Box::new(Term::Global("DCase".to_string())),
1691 Box::new(case_proof),
1692 )),
1693 Box::new(case_chain),
1694 );
1695 }
1696 let proof = Term::App(
1697 Box::new(Term::App(
1698 Box::new(Term::App(
1699 Box::new(Term::Global("try_induction".to_string())),
1700 Box::new(ind_type.clone()),
1701 )),
1702 Box::new(motive.clone()),
1703 )),
1704 Box::new(case_chain),
1705 );
1706 Ok((proof, forall_syntax(&ind_type, &motive)))
1707 }
1708
1709 fn parse_function_params(&mut self) -> Result<Vec<(String, Term)>, ParseError> {
1711 let mut params = Vec::new();
1712
1713 loop {
1714 self.skip_whitespace();
1715
1716 if !self.peek_char('(') {
1718 break;
1719 }
1720
1721 self.advance(); self.skip_whitespace();
1724
1725 let param_name = self.parse_ident()?;
1726 self.skip_whitespace();
1727
1728 if !self.try_consume(":") {
1729 return Err(ParseError::Expected {
1730 expected: "':'".to_string(),
1731 found: self.peek_word().unwrap_or("EOF".to_string()),
1732 });
1733 }
1734 self.skip_whitespace();
1735
1736 let param_type = self.parse_type()?;
1737 self.skip_whitespace();
1738
1739 if !self.try_consume(")") {
1740 return Err(ParseError::Expected {
1741 expected: "')'".to_string(),
1742 found: self.peek_word().unwrap_or("EOF".to_string()),
1743 });
1744 }
1745
1746 params.push((param_name, param_type));
1747
1748 self.skip_whitespace();
1749
1750 let _ = self.try_consume_keyword("and");
1752 }
1753
1754 Ok(params)
1755 }
1756
1757 fn parse_param_list(&mut self) -> Result<Vec<(String, Term)>, ParseError> {
1759 let mut params = Vec::new();
1760
1761 if !self.peek_char('(') {
1762 return Ok(params);
1763 }
1764
1765 self.advance(); self.skip_whitespace();
1767
1768 loop {
1769 let param_name = self.parse_ident()?;
1770 self.skip_whitespace();
1771
1772 if !self.try_consume(":") {
1773 return Err(ParseError::Expected {
1774 expected: "':'".to_string(),
1775 found: self.peek_word().unwrap_or("EOF".to_string()),
1776 });
1777 }
1778 self.skip_whitespace();
1779
1780 let param_type = self.parse_type()?;
1781 params.push((param_name, param_type));
1782
1783 self.skip_whitespace();
1784
1785 if self.try_consume(")") {
1786 break;
1787 }
1788
1789 if !self.try_consume(",") && !self.try_consume_keyword("and") {
1790 return Err(ParseError::Expected {
1791 expected: "')' or ','".to_string(),
1792 found: self.peek_word().unwrap_or("EOF".to_string()),
1793 });
1794 }
1795 self.skip_whitespace();
1796 }
1797
1798 Ok(params)
1799 }
1800
1801 fn parse_body(&mut self) -> Result<Term, ParseError> {
1812 self.skip_whitespace_and_newlines();
1813 if self.peek_keyword("When") {
1814 return Err(ParseError::Expected {
1815 expected:
1816 "a clause body (`Yield …` or a nested `Consider …`) before the next `When`"
1817 .to_string(),
1818 found: "When".to_string(),
1819 });
1820 }
1821
1822 if self.peek_keyword("Consider") {
1824 return self.parse_consider();
1825 }
1826
1827 if self.peek_keyword("Yield") {
1829 return self.parse_yield();
1830 }
1831
1832 if self.peek_keyword("given") {
1834 return self.parse_given_lambda();
1835 }
1836
1837 if self.peek_char('|') {
1839 return self.parse_pipe_lambda();
1840 }
1841
1842 self.parse_term()
1844 }
1845
1846 fn parse_consider(&mut self) -> Result<Term, ParseError> {
1868 self.consume_keyword("Consider")?;
1869 self.skip_whitespace();
1870
1871 let mut discriminants = vec![self.parse_term()?];
1876 loop {
1877 self.skip_whitespace();
1878 if !self.try_consume_keyword("and") {
1879 break;
1880 }
1881 self.skip_whitespace();
1882 discriminants.push(self.parse_term()?);
1883 }
1884
1885 self.skip_whitespace();
1886
1887 if !self.try_consume(":") {
1888 return Err(ParseError::Expected {
1889 expected: "':'".to_string(),
1890 found: self.peek_word().unwrap_or("EOF".to_string()),
1891 });
1892 }
1893
1894 let result_type = self
1897 .return_type
1898 .clone()
1899 .unwrap_or_else(|| Term::Sort(Universe::Type(0)));
1900
1901 let working = self.working_context();
1905 let disc_tys: Option<Vec<Term>> = match &working {
1906 Some(c) => Some(
1907 discriminants
1908 .iter()
1909 .map(|d| {
1910 infer_type(c, d).map_err(|e| {
1911 ParseError::InvalidConsiderSyntax(format!(
1912 "`Consider {d}` cannot be compiled: the discriminant has no type \
1913 here ({e})"
1914 ))
1915 })
1916 })
1917 .collect::<Result<Vec<_>, _>>()?,
1918 ),
1919 None => None,
1920 };
1921
1922 let mut clauses: Vec<Clause> = Vec::new();
1923 let mut clause_column: Option<usize> = None;
1933
1934 loop {
1935 self.skip_whitespace_and_newlines();
1936
1937 if !self.peek_keyword("When") {
1938 break;
1939 }
1940 let column = self.line_start_column();
1941 if clauses.is_empty() {
1942 clause_column = Some(column.unwrap_or_else(|| self.line_indent() + 1));
1943 } else if let (Some(fixed), Some(here)) = (clause_column, column) {
1944 if here < fixed {
1945 break;
1946 }
1947 }
1948
1949 self.consume_keyword("When")?;
1950 self.skip_whitespace();
1951
1952 let mut patterns = vec![self.parse_clause_pattern()?];
1954 loop {
1955 self.skip_whitespace();
1956 if !self.try_consume_keyword("and") {
1957 break;
1958 }
1959 self.skip_whitespace();
1960 patterns.push(self.parse_clause_pattern()?);
1961 }
1962 self.skip_whitespace();
1963
1964 if !self.try_consume(":") {
1965 return Err(ParseError::Expected {
1966 expected: "':'".to_string(),
1967 found: self.peek_word().unwrap_or("EOF".to_string()),
1968 });
1969 }
1970
1971 if patterns.len() != discriminants.len() {
1977 return Err(ParseError::InvalidConsiderSyntax(format!(
1978 "`Consider` names {} column(s) — {} — so every `When` needs {} pattern(s) \
1979 separated by `and`; this one has {}: `{}`",
1980 discriminants.len(),
1981 discriminants
1982 .iter()
1983 .map(|d| format!("`{d}`"))
1984 .collect::<Vec<_>>()
1985 .join(", "),
1986 discriminants.len(),
1987 patterns.len(),
1988 patterns
1989 .iter()
1990 .map(Pattern::render)
1991 .collect::<Vec<_>>()
1992 .join(" and ")
1993 )));
1994 }
1995
1996 self.skip_whitespace();
1997
1998 let typed: Vec<(String, Term)> = match (&working, &disc_tys) {
2003 (Some(c), Some(tys)) => {
2004 let mut out = Vec::new();
2005 for (t, pattern) in tys.iter().zip(&patterns) {
2006 out.extend(
2007 pattern_binder_types(c, t, pattern)
2008 .map_err(|e| ParseError::InvalidConsiderSyntax(e.to_string()))?,
2009 );
2010 }
2011 out
2012 }
2013 _ => patterns
2014 .iter()
2015 .flat_map(Pattern::binders)
2016 .map(|n| (n, Term::Global("_".to_string())))
2017 .collect(),
2018 };
2019
2020 let mark = self.locals.len();
2021 let mut newly_bound: Vec<String> = Vec::new();
2022 for (n, t) in &typed {
2023 if self.bound_vars.insert(n.clone()) {
2024 newly_bound.push(n.clone());
2025 }
2026 self.locals.push((n.clone(), t.clone()));
2027 }
2028
2029 let body = self.parse_body()?;
2030
2031 for n in &newly_bound {
2034 self.bound_vars.remove(n);
2035 }
2036 self.locals.truncate(mark);
2037
2038 clauses.push(Clause { patterns, body });
2039
2040 self.skip_whitespace();
2041 let _ = self.try_consume(".");
2042 }
2043
2044 if clauses.is_empty() {
2045 return Err(ParseError::Missing("When clauses".to_string()));
2046 }
2047
2048 if self.measuring {
2049 return Ok(Term::Hole);
2050 }
2051 match working {
2052 Some(c) => compile_clauses_reporting(&c, &discriminants, &result_type, &clauses)
2053 .map(|(term, _report)| term)
2054 .map_err(|e| ParseError::InvalidConsiderSyntax(e.to_string())),
2055 None => flat_positional_match(discriminants, result_type, &clauses),
2056 }
2057 }
2058
2059 fn parse_clause_pattern(&mut self) -> Result<Pattern, ParseError> {
2070 self.skip_whitespace();
2071 if self.peek_char('(') {
2072 return self.parse_parenthesised_pattern();
2073 }
2074 if let Some(n) = self.parse_pattern_numeral() {
2075 return Ok(Pattern::Numeral(n));
2076 }
2077 let name = self.parse_ident()?;
2078 if name == "_" {
2079 return Ok(Pattern::Wildcard);
2080 }
2081
2082 let mut args = Vec::new();
2083 loop {
2084 self.skip_whitespace();
2085 if self.at_end()
2086 || self.peek_char(':')
2087 || self.peek_char(')')
2088 || self.peek_char('.')
2089 || self.peek_keyword("and")
2093 {
2094 break;
2095 }
2096 args.push(self.parse_pattern_atom()?);
2097 }
2098
2099 match (self.ctx, self.constructor_named(&name)?) {
2102 (Some(_), Some(key)) => Ok(Pattern::Ctor { name: key, args }),
2103 (Some(_), None) if args.is_empty() => Ok(Pattern::Var(name)),
2104 _ => Ok(Pattern::Ctor { name, args }),
2105 }
2106 }
2107
2108 fn constructor_named(&self, written: &str) -> Result<Option<String>, ParseError> {
2113 let Some(ctx) = self.ctx else { return Ok(None) };
2114 let Some(name) = Name::parse(written) else {
2115 return Ok(ctx.is_constructor(written).then(|| written.to_string()));
2116 };
2117 match with_env(ctx, &[], |env| env.resolve(&self.scope, &name)) {
2118 Resolution::Found(key) => Ok(ctx.is_constructor(&key).then_some(key)),
2119 Resolution::Unresolved(_) => Ok(None),
2120 Resolution::Ambiguous {
2121 written,
2122 candidates,
2123 } => {
2124 if candidates.iter().any(|c| ctx.is_constructor(c)) {
2125 Err(ParseError::AmbiguousName {
2126 written,
2127 candidates,
2128 })
2129 } else {
2130 Ok(None)
2131 }
2132 }
2133 }
2134 }
2135
2136 fn parse_pattern_numeral(&mut self) -> Option<u64> {
2146 if !self.peek().is_some_and(|c| c.is_ascii_digit()) {
2147 return None;
2148 }
2149 let start = self.pos;
2150 let mut digits = String::new();
2151 while let Some(c) = self.peek() {
2152 if !c.is_ascii_digit() {
2153 break;
2154 }
2155 digits.push(c);
2156 self.advance();
2157 }
2158 match digits.parse::<u64>() {
2159 Ok(n) => Some(n),
2160 Err(_) => {
2163 self.pos = start;
2164 None
2165 }
2166 }
2167 }
2168
2169 fn parse_pattern_atom(&mut self) -> Result<Pattern, ParseError> {
2170 self.skip_whitespace();
2171 if self.peek_char('(') {
2172 return self.parse_parenthesised_pattern();
2173 }
2174 if let Some(n) = self.parse_pattern_numeral() {
2175 return Ok(Pattern::Numeral(n));
2176 }
2177 let name = self.parse_ident()?;
2178 if name == "_" {
2179 return Ok(Pattern::Wildcard);
2180 }
2181 match self.constructor_named(&name)? {
2182 Some(key) => Ok(Pattern::Ctor {
2183 name: key,
2184 args: Vec::new(),
2185 }),
2186 None => Ok(Pattern::Var(name)),
2187 }
2188 }
2189
2190 fn parse_parenthesised_pattern(&mut self) -> Result<Pattern, ParseError> {
2191 self.advance(); let inner = self.parse_clause_pattern()?;
2193 self.skip_whitespace();
2194 if !self.try_consume(")") {
2195 return Err(ParseError::Expected {
2196 expected: "')' closing a pattern".to_string(),
2197 found: self.peek_word().unwrap_or("EOF".to_string()),
2198 });
2199 }
2200 Ok(inner)
2201 }
2202
2203 fn parse_yield(&mut self) -> Result<Term, ParseError> {
2205 self.consume_keyword("Yield")?;
2206 self.skip_whitespace();
2207 self.parse_term()
2208 }
2209
2210 fn parse_given_lambda(&mut self) -> Result<Term, ParseError> {
2212 self.consume_keyword("given")?;
2213 self.skip_whitespace();
2214
2215 let param = self.parse_ident()?;
2216 self.skip_whitespace();
2217
2218 if !self.try_consume(":") {
2219 return Err(ParseError::Expected {
2220 expected: "':'".to_string(),
2221 found: self.peek_word().unwrap_or("EOF".to_string()),
2222 });
2223 }
2224 self.skip_whitespace();
2225
2226 let param_type = self.parse_type()?;
2227 self.skip_whitespace();
2228
2229 self.consume_keyword("yields")?;
2230 self.skip_whitespace();
2231
2232 self.bound_vars.insert(param.clone());
2233 let body = self.parse_term()?;
2234 self.bound_vars.remove(¶m);
2235
2236 Ok(Term::Lambda {
2237 param,
2238 param_type: Box::new(param_type),
2239 body: Box::new(body),
2240 })
2241 }
2242
2243 fn parse_pipe_lambda(&mut self) -> Result<Term, ParseError> {
2245 self.advance(); self.skip_whitespace();
2247
2248 let param = self.parse_ident()?;
2249 self.skip_whitespace();
2250
2251 if !self.try_consume(":") {
2252 return Err(ParseError::Expected {
2253 expected: "':'".to_string(),
2254 found: self.peek_word().unwrap_or("EOF".to_string()),
2255 });
2256 }
2257 self.skip_whitespace();
2258
2259 let param_type = self.parse_type()?;
2260 self.skip_whitespace();
2261
2262 if !self.try_consume("|") {
2263 return Err(ParseError::Expected {
2264 expected: "'|'".to_string(),
2265 found: self.peek_word().unwrap_or("EOF".to_string()),
2266 });
2267 }
2268 self.skip_whitespace();
2269
2270 if !self.try_consume("->") {
2271 return Err(ParseError::Expected {
2272 expected: "'->'".to_string(),
2273 found: self.peek_word().unwrap_or("EOF".to_string()),
2274 });
2275 }
2276 self.skip_whitespace();
2277
2278 self.bound_vars.insert(param.clone());
2279 let body = self.parse_term()?;
2280 self.bound_vars.remove(¶m);
2281
2282 Ok(Term::Lambda {
2283 param,
2284 param_type: Box::new(param_type),
2285 body: Box::new(body),
2286 })
2287 }
2288
2289 fn parse_term(&mut self) -> Result<Term, ParseError> {
2291 self.skip_whitespace();
2292 if self.peek_keyword("forall") || self.peek_char('\u{2200}') {
2295 return self.parse_forall();
2296 }
2297
2298 let lhs = self.parse_comparison()?;
2299
2300 self.skip_whitespace();
2301
2302 if self.peek_keyword("equals") {
2304 self.consume_keyword("equals")?;
2305 self.skip_whitespace();
2306 let rhs = self.parse_comparison()?; return Ok(Term::App(
2308 Box::new(Term::App(
2309 Box::new(Term::App(
2310 Box::new(self.global("Eq")?),
2311 Box::new(Term::Hole), )),
2313 Box::new(lhs),
2314 )),
2315 Box::new(rhs),
2316 ));
2317 }
2318
2319 if self.peek_keyword("implies") {
2321 self.consume_keyword("implies")?;
2322 self.skip_whitespace();
2323 let rhs = self.parse_term()?; return Ok(Term::Pi {
2325 param: "_".to_string(),
2326 param_type: Box::new(lhs),
2327 body_type: Box::new(rhs),
2328 });
2329 }
2330
2331 Ok(lhs)
2332 }
2333
2334 fn parse_forall(&mut self) -> Result<Term, ParseError> {
2344 if !(self.try_consume_keyword("forall") || self.try_consume("\u{2200}")) {
2345 return Err(ParseError::Expected {
2346 expected: "'forall'".to_string(),
2347 found: self.peek_word().unwrap_or("EOF".to_string()),
2348 });
2349 }
2350 self.skip_whitespace();
2351 let param = self.parse_ident()?;
2352 self.skip_whitespace();
2353 if !self.try_consume(":") {
2354 return Err(ParseError::Expected {
2355 expected: "':' — a `forall` binder must name its type".to_string(),
2356 found: self.peek_word().unwrap_or("EOF".to_string()),
2357 });
2358 }
2359 self.skip_whitespace();
2360 let param_type = self.parse_type()?;
2361 self.skip_whitespace();
2362 if !self.try_consume(",") {
2363 return Err(ParseError::Expected {
2364 expected: "',' after the `forall` binder".to_string(),
2365 found: self.peek_word().unwrap_or("EOF".to_string()),
2366 });
2367 }
2368 self.skip_whitespace();
2369
2370 let was_bound = self.bound_vars.contains(¶m);
2371 self.bound_vars.insert(param.clone());
2372 let body_type = self.parse_term()?;
2373 if !was_bound {
2374 self.bound_vars.remove(¶m);
2375 }
2376
2377 Ok(Term::Pi {
2378 param,
2379 param_type: Box::new(param_type),
2380 body_type: Box::new(body_type),
2381 })
2382 }
2383
2384 fn parse_comparison(&mut self) -> Result<Term, ParseError> {
2388 let lhs = self.parse_additive()?;
2389 self.skip_whitespace();
2390
2391 let op_name = if self.try_consume("<=") || self.try_consume("≤") {
2393 Some("le")
2394 } else if self.try_consume(">=") || self.try_consume("≥") {
2395 Some("ge")
2396 } else if self.try_consume("<") {
2397 Some("lt")
2398 } else if self.try_consume(">") {
2399 Some("gt")
2400 } else {
2401 None
2402 };
2403
2404 if let Some(op) = op_name {
2405 self.skip_whitespace();
2406 let rhs = self.parse_additive()?; return Ok(Term::App(
2408 Box::new(Term::App(Box::new(self.global(op)?), Box::new(lhs))),
2409 Box::new(rhs),
2410 ));
2411 }
2412
2413 Ok(lhs)
2414 }
2415
2416 fn parse_additive(&mut self) -> Result<Term, ParseError> {
2419 let mut result = self.parse_multiplicative()?;
2420
2421 loop {
2422 self.skip_whitespace();
2423
2424 let op_name = if self.try_consume("+") {
2425 Some("add")
2426 } else if self.peek_char('-') && !self.peek_arrow() && !self.peek_negative_number() {
2427 self.advance(); Some("sub")
2429 } else {
2430 None
2431 };
2432
2433 if let Some(op) = op_name {
2434 self.skip_whitespace();
2435 let rhs = self.parse_multiplicative()?;
2436 result = Term::App(
2437 Box::new(Term::App(Box::new(self.global(op)?), Box::new(result))),
2438 Box::new(rhs),
2439 );
2440 } else {
2441 break;
2442 }
2443 }
2444
2445 Ok(result)
2446 }
2447
2448 fn parse_multiplicative(&mut self) -> Result<Term, ParseError> {
2451 let mut result = self.parse_app()?;
2452
2453 loop {
2454 self.skip_whitespace();
2455
2456 if self.try_consume("*") {
2457 self.skip_whitespace();
2458 let rhs = self.parse_app()?;
2459 result = Term::App(
2460 Box::new(Term::App(Box::new(self.global("mul")?), Box::new(result))),
2461 Box::new(rhs),
2462 );
2463 } else {
2464 break;
2465 }
2466 }
2467
2468 Ok(result)
2469 }
2470
2471 fn parse_app(&mut self) -> Result<Term, ParseError> {
2473 let mut func = self.parse_atom()?;
2474
2475 loop {
2476 self.skip_whitespace();
2477
2478 if self.peek_char('(') {
2480 self.advance(); self.skip_whitespace();
2482
2483 if !self.peek_char(')') {
2484 loop {
2485 let arg = self.parse_term()?;
2486 func = Term::App(Box::new(func), Box::new(arg));
2487 self.skip_whitespace();
2488
2489 if self.try_consume(",") {
2490 self.skip_whitespace();
2491 } else {
2492 break;
2493 }
2494 }
2495 }
2496
2497 if !self.try_consume(")") {
2498 return Err(ParseError::Expected {
2499 expected: "')'".to_string(),
2500 found: self.peek_word().unwrap_or("EOF".to_string()),
2501 });
2502 }
2503 continue;
2504 }
2505
2506 if self.at_end()
2509 || self.peek_char(')')
2510 || self.peek_char('.')
2511 || self.peek_char(',')
2512 || self.peek_char(':')
2513 || self.peek_char('|')
2514 || self.peek_keyword("When")
2515 || self.peek_keyword("Yield")
2516 || self.peek_keyword("and")
2517 || self.peek_keyword("or")
2518 || self.peek_keyword("equals")
2519 || self.peek_keyword("implies")
2520 || self.peek_char('+')
2522 || self.peek_char('*')
2523 || self.peek_comparison_operator()
2524 || (self.peek_char('-') && !self.peek_arrow() && !self.peek_negative_number())
2525 {
2526 break;
2527 }
2528
2529 if let Ok(arg) = self.parse_atom() {
2531 func = Term::App(Box::new(func), Box::new(arg));
2532 } else {
2533 break;
2534 }
2535 }
2536
2537 Ok(func)
2538 }
2539
2540 fn parse_atom(&mut self) -> Result<Term, ParseError> {
2542 self.skip_whitespace();
2543
2544 if let Some(c) = self.peek() {
2546 if c.is_ascii_digit() {
2547 return self.parse_number();
2548 }
2549 if c == '-' {
2550 let saved_pos = self.pos;
2552 self.advance();
2553 if let Some(next) = self.peek() {
2554 if next.is_ascii_digit() {
2555 self.pos = saved_pos;
2556 return self.parse_number();
2557 }
2558 }
2559 self.pos = saved_pos;
2560 }
2561 }
2562
2563 if self.peek_char('"') {
2565 return self.parse_string();
2566 }
2567
2568 if self.peek_char('(') {
2570 self.advance();
2571 let term = self.parse_term()?;
2572 self.skip_whitespace();
2573 if !self.try_consume(")") {
2574 return Err(ParseError::Expected {
2575 expected: "')'".to_string(),
2576 found: self.peek_word().unwrap_or("EOF".to_string()),
2577 });
2578 }
2579 return Ok(term);
2580 }
2581
2582 if self.try_consume_keyword("the") {
2584 self.skip_whitespace();
2585 if self.try_consume_keyword("diagonalization") {
2587 self.skip_whitespace();
2588 if !self.try_consume_keyword("of") {
2589 return Err(ParseError::Expected {
2590 expected: "'of'".to_string(),
2591 found: self.peek_word().unwrap_or("EOF".to_string()),
2592 });
2593 }
2594 self.skip_whitespace();
2595 let arg = self.parse_atom()?;
2596 return Ok(Term::App(
2597 Box::new(Term::Global("syn_diag".to_string())),
2598 Box::new(arg),
2599 ));
2600 }
2601 if self.peek_keyword("Name") {
2603 self.consume_keyword("Name")?;
2604 self.skip_whitespace();
2605 let arg = self.parse_atom()?;
2606 return Ok(Term::App(
2607 Box::new(Term::Global("SName".to_string())),
2608 Box::new(arg),
2609 ));
2610 }
2611 }
2613
2614 if self.peek_keyword("Name") {
2616 self.consume_keyword("Name")?;
2617 self.skip_whitespace();
2618 let arg = self.parse_atom()?;
2619 return Ok(Term::App(
2620 Box::new(Term::Global("SName".to_string())),
2621 Box::new(arg),
2622 ));
2623 }
2624
2625 if self.peek_keyword("Variable") {
2627 self.consume_keyword("Variable")?;
2628 self.skip_whitespace();
2629 let arg = self.parse_atom()?;
2630 return Ok(Term::App(
2631 Box::new(Term::Global("SVar".to_string())),
2632 Box::new(arg),
2633 ));
2634 }
2635
2636 if self.peek_keyword("Apply") {
2638 self.consume_keyword("Apply")?;
2639 self.skip_whitespace();
2640 if !self.try_consume("(") {
2641 return Err(ParseError::Expected {
2642 expected: "'('".to_string(),
2643 found: self.peek_word().unwrap_or("EOF".to_string()),
2644 });
2645 }
2646 self.skip_whitespace();
2647 let func_arg = self.parse_term()?;
2648 self.skip_whitespace();
2649 if !self.try_consume(",") {
2650 return Err(ParseError::Expected {
2651 expected: "','".to_string(),
2652 found: self.peek_word().unwrap_or("EOF".to_string()),
2653 });
2654 }
2655 self.skip_whitespace();
2656 let arg_arg = self.parse_term()?;
2657 self.skip_whitespace();
2658 if !self.try_consume(")") {
2659 return Err(ParseError::Expected {
2660 expected: "')'".to_string(),
2661 found: self.peek_word().unwrap_or("EOF".to_string()),
2662 });
2663 }
2664 return Ok(Term::App(
2665 Box::new(Term::App(
2666 Box::new(Term::Global("SApp".to_string())),
2667 Box::new(func_arg),
2668 )),
2669 Box::new(arg_arg),
2670 ));
2671 }
2672
2673 if self.peek_keyword("there") {
2675 return self.parse_existential();
2676 }
2677
2678 let ident = self.parse_ident()?;
2680
2681 self.skip_whitespace();
2683 if self.try_consume_keyword("of") {
2684 self.skip_whitespace();
2685 let arg = self.parse_atom()?;
2686 let func = if self.bound_vars.contains(&ident) {
2687 Term::Var(ident)
2688 } else {
2689 self.global(ident)?
2690 };
2691 return Ok(Term::App(Box::new(func), Box::new(arg)));
2692 }
2693
2694 if self.bound_vars.contains(&ident) || self.current_function.as_ref() == Some(&ident) {
2696 Ok(Term::Var(ident))
2697 } else {
2698 match ident.as_str() {
2700 "Prop" => Ok(Term::Sort(Universe::Prop)),
2701 "Type" => Ok(Term::Sort(Universe::Type(0))),
2702 _ => self.global(ident),
2703 }
2704 }
2705 }
2706
2707 fn parse_existential(&mut self) -> Result<Term, ParseError> {
2710 self.consume_keyword("there")?;
2711 self.skip_whitespace();
2712 self.consume_keyword("exists")?;
2713 self.skip_whitespace();
2714
2715 let _ = self.try_consume_keyword("an") || self.try_consume_keyword("a");
2717 self.skip_whitespace();
2718
2719 let var_name = self.parse_ident()?;
2721 self.skip_whitespace();
2722
2723 if !self.try_consume(":") {
2725 return Err(ParseError::Expected {
2726 expected: "':'".to_string(),
2727 found: self.peek_word().unwrap_or("EOF".to_string()),
2728 });
2729 }
2730 self.skip_whitespace();
2731
2732 let var_type = self.parse_type()?;
2734 self.skip_whitespace();
2735
2736 if !self.try_consume_keyword("such") {
2738 return Err(ParseError::Expected {
2739 expected: "'such'".to_string(),
2740 found: self.peek_word().unwrap_or("EOF".to_string()),
2741 });
2742 }
2743 self.skip_whitespace();
2744 if !self.try_consume_keyword("that") {
2745 return Err(ParseError::Expected {
2746 expected: "'that'".to_string(),
2747 found: self.peek_word().unwrap_or("EOF".to_string()),
2748 });
2749 }
2750 self.skip_whitespace();
2751
2752 let was_bound = !self.bound_vars.insert(var_name.clone());
2754 self.locals.push((var_name.clone(), var_type.clone()));
2755 let body = self.parse_term();
2756 self.locals.pop();
2757 if !was_bound {
2758 self.bound_vars.remove(&var_name);
2759 }
2760 let body = body?;
2761
2762 Ok(Term::App(
2766 Box::new(Term::App(
2767 Box::new(self.global("Ex")?),
2768 Box::new(var_type.clone()),
2769 )),
2770 Box::new(Term::Lambda {
2771 param: var_name,
2772 param_type: Box::new(var_type),
2773 body: Box::new(body),
2774 }),
2775 ))
2776 }
2777
2778 fn parse_type(&mut self) -> Result<Term, ParseError> {
2780 self.skip_whitespace();
2781
2782 let base = self.parse_ident()?;
2784
2785 self.skip_whitespace();
2786
2787 if self.try_consume_keyword("of") {
2789 self.skip_whitespace();
2790 let arg = self.parse_type()?;
2791 return Ok(Term::App(Box::new(self.global(base)?), Box::new(arg)));
2792 }
2793
2794 match base.as_str() {
2796 "Prop" => Ok(Term::Sort(Universe::Prop)),
2797 "Type" => Ok(Term::Sort(Universe::Type(0))),
2798 _ => self.global(base),
2799 }
2800 }
2801
2802 fn parse_number(&mut self) -> Result<Term, ParseError> {
2804 let mut num_str = String::new();
2805
2806 if self.peek_char('-') {
2808 num_str.push('-');
2809 self.advance();
2810 }
2811
2812 while let Some(c) = self.peek() {
2814 if c.is_ascii_digit() {
2815 num_str.push(c);
2816 self.advance();
2817 } else {
2818 break;
2819 }
2820 }
2821
2822 let value: i64 = num_str
2823 .parse()
2824 .map_err(|_| ParseError::InvalidNumber(num_str))?;
2825
2826 Ok(Term::Lit(Literal::Int(value)))
2827 }
2828
2829 fn parse_string(&mut self) -> Result<Term, ParseError> {
2831 self.advance(); let mut content = String::new();
2834 loop {
2835 match self.peek() {
2836 Some('"') => {
2837 self.advance();
2838 break;
2839 }
2840 Some('\\') => {
2841 self.advance();
2842 match self.peek() {
2843 Some('n') => {
2844 content.push('\n');
2845 self.advance();
2846 }
2847 Some('t') => {
2848 content.push('\t');
2849 self.advance();
2850 }
2851 Some(c) => {
2852 content.push(c);
2853 self.advance();
2854 }
2855 None => return Err(ParseError::UnexpectedEof),
2856 }
2857 }
2858 Some(c) => {
2859 content.push(c);
2860 self.advance();
2861 }
2862 None => return Err(ParseError::UnexpectedEof),
2863 }
2864 }
2865
2866 Ok(Term::Lit(Literal::Text(content)))
2867 }
2868
2869 fn term_to_syntax(&self, term: &Term, bound_vars: &[String]) -> Term {
2876 match term {
2877 Term::Var(name) => {
2878 if let Some(idx) = bound_vars.iter().rev().position(|n| n == name) {
2880 Term::App(
2881 Box::new(Term::Global("SVar".to_string())),
2882 Box::new(Term::Lit(Literal::Int(idx as i64))),
2883 )
2884 } else {
2885 Term::App(
2887 Box::new(Term::Global("SName".to_string())),
2888 Box::new(Term::Lit(Literal::Text(name.clone()))),
2889 )
2890 }
2891 }
2892 Term::Global(name) => {
2893 Term::App(
2895 Box::new(Term::Global("SName".to_string())),
2896 Box::new(Term::Lit(Literal::Text(name.clone()))),
2897 )
2898 }
2899 Term::Const { name, .. } => {
2900 Term::App(
2903 Box::new(Term::Global("SName".to_string())),
2904 Box::new(Term::Lit(Literal::Text(name.clone()))),
2905 )
2906 }
2907 Term::Lit(Literal::Int(n)) => {
2908 Term::App(
2910 Box::new(Term::Global("SLit".to_string())),
2911 Box::new(Term::Lit(Literal::Int(*n))),
2912 )
2913 }
2914 Term::Lit(Literal::Float(_f)) => {
2915 Term::App(
2917 Box::new(Term::Global("SName".to_string())),
2918 Box::new(Term::Lit(Literal::Text("Error_Float".to_string()))),
2919 )
2920 }
2921 Term::Lit(Literal::BigInt(_)) => {
2922 Term::App(
2924 Box::new(Term::Global("SName".to_string())),
2925 Box::new(Term::Lit(Literal::Text("Error_BigInt".to_string()))),
2926 )
2927 }
2928 Term::Lit(Literal::Nat(_)) => {
2929 Term::App(
2931 Box::new(Term::Global("SName".to_string())),
2932 Box::new(Term::Lit(Literal::Text("Error_Nat".to_string()))),
2933 )
2934 }
2935 Term::Lit(Literal::Duration(_d)) => {
2936 Term::App(
2938 Box::new(Term::Global("SName".to_string())),
2939 Box::new(Term::Lit(Literal::Text("Error_Duration".to_string()))),
2940 )
2941 }
2942 Term::Lit(Literal::Date(_d)) => {
2943 Term::App(
2945 Box::new(Term::Global("SName".to_string())),
2946 Box::new(Term::Lit(Literal::Text("Error_Date".to_string()))),
2947 )
2948 }
2949 Term::Lit(Literal::Moment(_m)) => {
2950 Term::App(
2952 Box::new(Term::Global("SName".to_string())),
2953 Box::new(Term::Lit(Literal::Text("Error_Moment".to_string()))),
2954 )
2955 }
2956 Term::Lit(Literal::Text(s)) => {
2957 Term::App(
2959 Box::new(Term::Global("SName".to_string())),
2960 Box::new(Term::Lit(Literal::Text(s.clone()))),
2961 )
2962 }
2963 Term::App(f, x) => {
2964 let f_syn = self.term_to_syntax(f, bound_vars);
2966 let x_syn = self.term_to_syntax(x, bound_vars);
2967 Term::App(
2968 Box::new(Term::App(
2969 Box::new(Term::Global("SApp".to_string())),
2970 Box::new(f_syn),
2971 )),
2972 Box::new(x_syn),
2973 )
2974 }
2975 Term::Lambda {
2976 param,
2977 param_type,
2978 body,
2979 } => {
2980 let ty_syn = self.term_to_syntax(param_type, bound_vars);
2982 let mut new_bound = bound_vars.to_vec();
2983 new_bound.push(param.clone());
2984 let body_syn = self.term_to_syntax(body, &new_bound);
2985 Term::App(
2986 Box::new(Term::App(
2987 Box::new(Term::Global("SLam".to_string())),
2988 Box::new(ty_syn),
2989 )),
2990 Box::new(body_syn),
2991 )
2992 }
2993 Term::Pi {
2994 param,
2995 param_type,
2996 body_type,
2997 } => {
2998 let ty_syn = self.term_to_syntax(param_type, bound_vars);
2999 let mut new_bound = bound_vars.to_vec();
3000 new_bound.push(param.clone());
3001 let body_syn = self.term_to_syntax(body_type, &new_bound);
3002 if param == "_" {
3003 Term::App(
3005 Box::new(Term::App(
3006 Box::new(Term::Global("SPi".to_string())),
3007 Box::new(ty_syn),
3008 )),
3009 Box::new(body_syn),
3010 )
3011 } else {
3012 let motive = Term::App(
3016 Box::new(Term::App(
3017 Box::new(Term::Global("SLam".to_string())),
3018 Box::new(ty_syn.clone()),
3019 )),
3020 Box::new(body_syn),
3021 );
3022 forall_syntax(&ty_syn, &motive)
3023 }
3024 }
3025 Term::Sort(Universe::Prop) => {
3026 Term::App(
3028 Box::new(Term::Global("SSort".to_string())),
3029 Box::new(Term::Global("UProp".to_string())),
3030 )
3031 }
3032 Term::Sort(Universe::Type(n)) => {
3033 Term::App(
3035 Box::new(Term::Global("SSort".to_string())),
3036 Box::new(Term::App(
3037 Box::new(Term::Global("UType".to_string())),
3038 Box::new(Term::Lit(Literal::Int(*n as i64))),
3039 )),
3040 )
3041 }
3042 Term::Sort(_) => {
3043 Term::App(
3046 Box::new(Term::Global("SSort".to_string())),
3047 Box::new(Term::Global("UPoly".to_string())),
3048 )
3049 }
3050 Term::Hole => {
3051 Term::App(
3053 Box::new(Term::Global("SName".to_string())),
3054 Box::new(Term::Lit(Literal::Text("Int".to_string()))),
3055 )
3056 }
3057 Term::Match { .. } | Term::Fix { .. } | Term::MutualFix { .. } | Term::Let { .. } => {
3058 Term::App(
3060 Box::new(Term::Global("SName".to_string())),
3061 Box::new(Term::Lit(Literal::Text("Error".to_string()))),
3062 )
3063 }
3064 Term::Annotated { term, .. } => self.term_to_syntax(term, bound_vars),
3066 }
3067 }
3068
3069 fn contains_self_reference(&self, name: &str, term: &Term) -> bool {
3075 match term {
3076 Term::Var(v) => v == name,
3077 Term::Global(_) => false,
3078 Term::Const { .. } => false,
3079 Term::Sort(_) => false,
3080 Term::Lit(_) => false,
3081 Term::Pi {
3082 param_type,
3083 body_type,
3084 ..
3085 } => {
3086 self.contains_self_reference(name, param_type)
3087 || self.contains_self_reference(name, body_type)
3088 }
3089 Term::Lambda {
3090 param_type, body, ..
3091 } => {
3092 self.contains_self_reference(name, param_type)
3093 || self.contains_self_reference(name, body)
3094 }
3095 Term::App(f, a) => {
3096 self.contains_self_reference(name, f) || self.contains_self_reference(name, a)
3097 }
3098 Term::Match {
3099 discriminant,
3100 motive,
3101 cases,
3102 } => {
3103 self.contains_self_reference(name, discriminant)
3104 || self.contains_self_reference(name, motive)
3105 || cases.iter().any(|c| self.contains_self_reference(name, c))
3106 }
3107 Term::Fix { body, .. } => self.contains_self_reference(name, body),
3108 Term::MutualFix { defs, .. } => defs
3109 .iter()
3110 .any(|(_, b)| self.contains_self_reference(name, b)),
3111 Term::Let {
3112 ty, value, body, ..
3113 } => {
3114 self.contains_self_reference(name, ty)
3115 || self.contains_self_reference(name, value)
3116 || self.contains_self_reference(name, body)
3117 }
3118 Term::Hole => false, Term::Annotated { term, .. } => self.contains_self_reference(name, term),
3120 }
3121 }
3122
3123 fn skip_whitespace(&mut self) {
3128 while let Some(c) = self.peek() {
3129 if c == ' ' || c == '\t' {
3130 self.advance();
3131 } else {
3132 break;
3133 }
3134 }
3135 }
3136
3137 fn line_start_column(&self) -> Option<usize> {
3140 let line_start = self.input[..self.pos].rfind('\n').map_or(0, |at| at + 1);
3141 let indent = &self.input[line_start..self.pos];
3142 indent
3143 .chars()
3144 .all(|c| c == ' ' || c == '\t')
3145 .then_some(indent.len())
3146 }
3147
3148 fn line_indent(&self) -> usize {
3150 let line_start = self.input[..self.pos].rfind('\n').map_or(0, |at| at + 1);
3151 self.input[line_start..]
3152 .chars()
3153 .take_while(|c| *c == ' ' || *c == '\t')
3154 .count()
3155 }
3156
3157 fn skip_whitespace_and_newlines(&mut self) {
3158 while let Some(c) = self.peek() {
3159 if c.is_whitespace() {
3160 self.advance();
3161 } else {
3162 break;
3163 }
3164 }
3165 }
3166
3167 fn peek(&self) -> Option<char> {
3168 self.input[self.pos..].chars().next()
3169 }
3170
3171 fn peek_char(&self, c: char) -> bool {
3172 self.peek() == Some(c)
3173 }
3174
3175 fn peek_keyword(&self, keyword: &str) -> bool {
3176 if !self.input[self.pos..].starts_with(keyword) {
3177 return false;
3178 }
3179 let after = self.pos + keyword.len();
3180 if after >= self.input.len() {
3181 return true;
3182 }
3183 let next_char = self.input[after..].chars().next();
3184 !next_char
3185 .map(|c| c.is_alphanumeric() || c == '_')
3186 .unwrap_or(false)
3187 }
3188
3189 fn peek_word(&self) -> Option<String> {
3190 let start = self.pos;
3191 let mut end = start;
3192 for c in self.input[start..].chars() {
3193 if c.is_alphanumeric() || c == '_' {
3194 end += c.len_utf8();
3195 } else {
3196 break;
3197 }
3198 }
3199 if end > start {
3200 Some(self.input[start..end].to_string())
3201 } else {
3202 self.peek().map(|c| c.to_string())
3203 }
3204 }
3205
3206 fn advance(&mut self) {
3207 if let Some(c) = self.peek() {
3208 self.pos += c.len_utf8();
3209 }
3210 }
3211
3212 fn at_end(&self) -> bool {
3213 self.pos >= self.input.len()
3214 }
3215
3216 fn try_consume(&mut self, s: &str) -> bool {
3217 if self.input[self.pos..].starts_with(s) {
3218 self.pos += s.len();
3219 true
3220 } else {
3221 false
3222 }
3223 }
3224
3225 fn try_consume_keyword(&mut self, keyword: &str) -> bool {
3226 if self.peek_keyword(keyword) {
3227 self.pos += keyword.len();
3228 true
3229 } else {
3230 false
3231 }
3232 }
3233
3234 fn consume_keyword(&mut self, keyword: &str) -> Result<(), ParseError> {
3235 if self.try_consume_keyword(keyword) {
3236 Ok(())
3237 } else {
3238 Err(ParseError::Expected {
3239 expected: format!("'{}'", keyword),
3240 found: self.peek_word().unwrap_or("EOF".to_string()),
3241 })
3242 }
3243 }
3244
3245 fn parse_declaration_name(&mut self) -> Result<String, ParseError> {
3258 self.skip_whitespace();
3259 let start = self.pos;
3260 match super::surface::Name::scan(&self.input[start..]) {
3261 Some((_, len)) => {
3262 let name = super::declaration_name(&self.input[start..start + len])?;
3263 self.pos = start + len;
3264 Ok(name.key())
3265 }
3266 None => match self.peek() {
3267 Some(c) => Err(ParseError::Expected {
3268 expected: "identifier".to_string(),
3269 found: c.to_string(),
3270 }),
3271 None => Err(ParseError::UnexpectedEof),
3272 },
3273 }
3274 }
3275
3276 fn parse_ident(&mut self) -> Result<String, ParseError> {
3279 self.skip_whitespace();
3280 match super::term_parser::scan_name(&self.input[self.pos..]) {
3281 Some((name, len)) => {
3282 self.pos += len;
3283 Ok(name)
3284 }
3285 None => match self.peek() {
3286 Some(c) => Err(ParseError::Expected {
3287 expected: "identifier".to_string(),
3288 found: c.to_string(),
3289 }),
3290 None => Err(ParseError::UnexpectedEof),
3291 },
3292 }
3293 }
3294
3295 fn peek_negative_number(&self) -> bool {
3301 if !self.peek_char('-') {
3302 return false;
3303 }
3304 self.input
3305 .get(self.pos + 1..)
3306 .and_then(|s| s.chars().next())
3307 .map(|c| c.is_ascii_digit())
3308 .unwrap_or(false)
3309 }
3310
3311 fn peek_arrow(&self) -> bool {
3313 self.input[self.pos..].starts_with("->")
3314 }
3315
3316 fn peek_comparison_operator(&self) -> bool {
3318 let rest = &self.input[self.pos..];
3319 rest.starts_with("<=")
3320 || rest.starts_with(">=")
3321 || rest.starts_with("≤")
3322 || rest.starts_with("≥")
3323 || rest.starts_with('<')
3324 || rest.starts_with('>')
3325 }
3326}
3327
3328#[cfg(test)]
3333#[path = "../../../logicaffeine_tests/unit/logicaffeine_kernel/interface/literate_parser/tests.rs"]
3334mod tests;