1use super::diagnostics::{Result, TranslationError, type_error, unsupported};
12use super::lexer::{Source, Token, TokenCursor, TokenKind, describe, is_js_space, tokenize_source};
13use super::surface::{
14 BinaryOp, SBinder, SComparison, SCtor, SData, SEffect, SExpr, SField, SFn, SItem, SMain,
15 SModule, SNode, SParam, SPattern, SPatternNode, SProgram, SProp, SPropNode, ShowStyle,
16};
17use super::types::{BOOL, INT, NAT, STRING, Type, UNIT};
18use super::{Language, Span};
19
20mod expressions;
21mod proofs;
22
23const ITEM_KEYWORDS: [&str; 28] = [
24 "namespace",
25 "end",
26 "inductive",
27 "def",
28 "theorem",
29 "lemma",
30 "structure",
31 "class",
32 "instance",
33 "abbrev",
34 "open",
35 "section",
36 "variable",
37 "universe",
38 "import",
39 "mutual",
40 "partial",
41 "private",
42 "protected",
43 "noncomputable",
44 "set_option",
45 "example",
46 "axiom",
47 "opaque",
48 "macro",
49 "syntax",
50 "notation",
51 "attribute",
52];
53
54fn is_item_keyword(value: &str) -> bool {
55 ITEM_KEYWORDS.contains(&value)
56}
57
58fn builtin_type(name: &str) -> Option<Type> {
59 match name {
60 "Nat" => Some(NAT),
61 "Int" => Some(INT),
62 "Bool" => Some(BOOL),
63 "String" => Some(STRING),
64 "Unit" => Some(UNIT),
65 _ => None,
66 }
67}
68
69fn is_unsupported_type(name: &str) -> bool {
71 let fixed = name
72 .strip_prefix('U')
73 .unwrap_or(name)
74 .strip_prefix("Int")
75 .is_some_and(|bits| matches!(bits, "8" | "16" | "32" | "64"));
76 fixed
77 || matches!(
78 name,
79 "USize" | "Float" | "Char" | "List" | "Array" | "Option" | "Prop" | "Type" | "Sort"
80 )
81}
82
83struct Level {
84 ops: &'static [&'static str],
85 prec: u32,
86 op: Option<BinaryOp>,
87 right: bool,
88}
89
90const BINARY: [Level; 6] = [
91 Level {
92 ops: &["||"],
93 prec: 30,
94 op: Some(BinaryOp::Or),
95 right: false,
96 },
97 Level {
98 ops: &["&&"],
99 prec: 35,
100 op: Some(BinaryOp::And),
101 right: false,
102 },
103 Level {
104 ops: &["==", "!=", "=", "≠", "<", "<=", "≤", ">", ">=", "≥"],
105 prec: 50,
106 op: None,
107 right: false,
108 },
109 Level {
110 ops: &["++"],
111 prec: 65,
112 op: Some(BinaryOp::Concat),
113 right: true,
114 },
115 Level {
116 ops: &["+", "-"],
117 prec: 65,
118 op: None,
119 right: false,
120 },
121 Level {
122 ops: &["*", "/", "%"],
123 prec: 70,
124 op: None,
125 right: false,
126 },
127];
128
129fn operator_name(op: &str) -> Option<BinaryOp> {
130 Some(match op {
131 "==" | "=" => BinaryOp::Eq,
132 "!=" | "≠" => BinaryOp::Ne,
133 "<" => BinaryOp::Lt,
134 "<=" | "≤" => BinaryOp::Le,
135 ">" => BinaryOp::Gt,
136 ">=" | "≥" => BinaryOp::Ge,
137 "+" => BinaryOp::Add,
138 "-" => BinaryOp::Sub,
139 "*" => BinaryOp::Mul,
140 "/" => BinaryOp::Div,
141 "%" => BinaryOp::Rem,
142 _ => return None,
143 })
144}
145
146type Relation = fn(SComparison) -> SPropNode;
147
148fn prop_relation(op: &str) -> Option<Relation> {
149 Some(match op {
150 "=" => SPropNode::Eq,
151 "≠" => SPropNode::Ne,
152 "<" => SPropNode::Lt,
153 "≤" | "<=" => SPropNode::Le,
154 ">" => SPropNode::Gt,
155 "≥" | ">=" => SPropNode::Ge,
156 _ => return None,
157 })
158}
159
160pub fn parse_lean(source: &str) -> Result<SProgram> {
165 let source = Source::new(source);
166 let mut tokens = tokenize_source(&source, Language::Lean)?.tokens;
167 annotate_layout(&mut tokens, source.units());
168 LeanParser::new(tokens, &source).file()
169}
170
171pub fn annotate_layout(tokens: &mut [Token], source: &[u16]) {
173 let mut line = 0;
174 let mut line_start = 0;
175 let mut cursor = 0;
176 let mut previous_line = None;
177 for token in tokens {
178 while cursor < token.start {
179 if source.get(cursor) == Some(&u16::from(b'\n')) {
180 line += 1;
181 line_start = cursor + 1;
182 }
183 cursor += 1;
184 }
185 token.line = line;
186 token.col = token.start - line_start;
187 token.first = previous_line != Some(line);
188 previous_line = Some(line);
189 }
190}
191
192#[must_use]
194pub fn span(from: &Token, to: &Token) -> Span {
195 let reach = if to.kind == TokenKind::Eof {
196 from.end
197 } else {
198 to.start
199 };
200 Span::new(from.start, from.end.max(reach))
201}
202
203fn column(token: &Token) -> i64 {
205 i64::try_from(token.col).unwrap_or(i64::MAX)
206}
207
208fn syntax_at(message: String, token: &Token) -> TranslationError {
209 TranslationError::syntax(message, Some(token.span()))
210}
211
212fn js_trimmed(units: &[u16]) -> String {
214 let start = units
215 .iter()
216 .position(|&unit| !is_js_space(unit))
217 .unwrap_or(units.len());
218 let end = units
219 .iter()
220 .rposition(|&unit| !is_js_space(unit))
221 .map_or(start, |index| index + 1);
222 String::from_utf16_lossy(&units[start..end.max(start)])
223}
224
225const fn expr(node: SNode, at: Span) -> SExpr {
226 SExpr::new(node, Some(at))
227}
228
229const fn pattern(node: SPatternNode, at: Option<Span>) -> SPattern {
230 SPattern { node, span: at }
231}
232
233struct PatternHead {
235 path: Vec<String>,
236 dot: bool,
237}
238
239enum Definition {
240 Fn(Box<SFn>),
241 Main(SMain, Span),
242}
243
244struct LeanParser<'a> {
245 cursor: TokenCursor,
246 source: &'a Source,
247 bounds: Vec<i64>,
248}
249
250impl<'a> LeanParser<'a> {
251 fn new(tokens: Vec<Token>, source: &'a Source) -> Self {
252 Self {
253 cursor: TokenCursor::new(tokens, Language::Lean),
254 source,
255 bounds: vec![-1],
256 }
257 }
258
259 fn bound(&self) -> i64 {
260 self.bounds.last().copied().unwrap_or(-1)
261 }
262
263 fn with_bound<T>(
264 &mut self,
265 column: i64,
266 parse: impl FnOnce(&mut Self) -> Result<T>,
267 ) -> Result<T> {
268 self.bounds.push(column);
269 let result = parse(self);
270 self.bounds.pop();
271 result
272 }
273
274 fn blocked(&self, token: &Token) -> bool {
276 if token.kind == TokenKind::Eof {
277 return true;
278 }
279 if token.col == 0
280 && token.first
281 && token.kind == TokenKind::Identifier
282 && is_item_keyword(&token.value)
283 {
284 return true;
285 }
286 token.first && column(token) <= self.bound()
287 }
288
289 fn blocked_next(&self) -> bool {
290 self.blocked(self.cursor.peek())
291 }
292
293 fn outdented(&self, at: i64) -> bool {
295 let token = self.cursor.peek();
296 token.kind == TokenKind::Eof || (token.first && column(token) < at)
297 }
298
299 fn fail(&self, message: &str) -> TranslationError {
300 Self::fail_at(message, self.cursor.peek())
301 }
302
303 fn fail_at(message: &str, token: &Token) -> TranslationError {
304 syntax_at(format!("{message} but found {}", describe(token)), token)
305 }
306
307 fn peek(&self) -> Token {
308 self.cursor.peek().clone()
309 }
310
311 fn span_to_next(&self, from: &Token) -> Span {
312 span(from, self.cursor.peek())
313 }
314
315 fn file(mut self) -> Result<SProgram> {
316 let mut items = Vec::new();
317 let mut main = None;
318 self.items(&mut main, &mut items, &[])?;
319 Ok(SProgram {
320 reference_semantics: None,
321 language: Language::Lean,
322 items,
323 main,
324 imports: Vec::new(),
325 externals: Vec::new(),
326 source_pure_unit_calls: None,
327 source_runtime_shell: None,
328 })
329 }
330
331 fn items(
332 &mut self,
333 main: &mut Option<SMain>,
334 items: &mut Vec<SItem>,
335 path: &[String],
336 ) -> Result<()> {
337 while !self.cursor.at_end() {
338 let token = self.peek();
339 if self.cursor.is("end") {
340 let Some(open) = path.last() else {
341 return Err(self.fail("unmatched end"));
342 };
343 self.cursor.advance();
344 let name = self.qualified_name()?.join(".");
345 if name != *open {
346 return Err(syntax_at(
347 format!("end {name} closes namespace {open}"),
348 &token,
349 ));
350 }
351 return Ok(());
352 }
353 if self.cursor.is("namespace") {
354 self.cursor.advance();
355 let mut segments = self.qualified_name()?;
356 let module_span = self.span_to_next(&token);
357 if segments.len() != 1 {
358 return Err(unsupported(
359 "dotted namespace",
360 "use one namespace per level",
361 Some(span(&token, &token)),
362 ));
363 }
364 let name = segments.remove(0);
365 let mut module = SModule {
366 name: name.clone(),
367 items: Vec::new(),
368 span: Some(module_span),
369 };
370 let mut inner = path.to_vec();
371 inner.push(name);
372 self.items(main, &mut module.items, &inner)?;
373 items.push(SItem::Module(module));
374 continue;
375 }
376 if self.cursor.is("inductive") {
377 items.push(SItem::Data(self.inductive()?));
378 continue;
379 }
380 if self.cursor.is("def") {
381 match self.definition(path)? {
382 Definition::Main(program_main, at) => {
383 if !path.is_empty() {
384 return Err(unsupported(
385 "namespaced main",
386 "main must be declared at the top level",
387 Some(at),
388 ));
389 }
390 if main.is_some() {
391 return Err(type_error("duplicate main", Some(at)));
392 }
393 *main = Some(program_main);
394 }
395 Definition::Fn(item) => items.push(SItem::Fn(*item)),
396 }
397 continue;
398 }
399 if self.cursor.is("theorem") {
400 items.push(SItem::Theorem(self.theorem()?));
401 continue;
402 }
403 if token.kind == TokenKind::Identifier && is_item_keyword(&token.value) {
404 return Err(unsupported(
405 &format!("Lean {} declaration", token.value),
406 "outside the portable core",
407 Some(span(&token, &token)),
408 ));
409 }
410 return Err(self.fail("expected a declaration"));
411 }
412 if let Some(open) = path.last() {
413 return Err(syntax_at(
414 format!("namespace {open} is not closed"),
415 self.cursor.peek(),
416 ));
417 }
418 Ok(())
419 }
420
421 fn qualified_name(&mut self) -> Result<Vec<String>> {
422 let token = self.cursor.identifier(Some("name"))?;
423 Ok(token.value.split('.').map(str::to_owned).collect())
424 }
425
426 fn inductive(&mut self) -> Result<SData> {
427 let start = self.cursor.advance();
428 let name = self.cursor.identifier(Some("inductive"))?.value;
429 if name.contains('.') {
430 return Err(unsupported(
431 "qualified inductive name",
432 "declare inductives inside their namespace",
433 Some(span(&start, &start)),
434 ));
435 }
436 if !self.cursor.is("where") {
437 if self.cursor.is("(") || self.cursor.is("{") {
438 return Err(unsupported(
439 "parameterised inductive",
440 "type parameters are outside the portable core",
441 Some(self.span_to_next(&start)),
442 ));
443 }
444 self.cursor.expect("where", Some("inductive"))?;
445 }
446 self.cursor.advance();
447 let mut ctors = Vec::new();
448 while self.cursor.is("|") {
449 let bar = self.cursor.advance();
450 let ctor_name = self.cursor.identifier(Some("constructor"))?.value;
451 let mut fields = Vec::new();
452 while self.cursor.is("(") {
453 fields.extend(self.binder_group()?.into_iter().map(|(name, ty)| SField {
454 name: Some(name),
455 ty,
456 rocq_type: None,
457 span: None,
458 }));
459 }
460 if self.cursor.eat(":").is_some() {
461 let mut types = self.arrow_type()?;
462 let result = types.pop();
463 let constructs_self = matches!(
464 &result,
465 Some(Type::Named { path, .. }) if path.join(".") == name
466 );
467 if !constructs_self {
468 return Err(unsupported(
469 "indexed constructor",
470 &format!("{ctor_name} must construct {name}"),
471 Some(self.span_to_next(&bar)),
472 ));
473 }
474 fields.extend(types.into_iter().map(|ty| SField {
475 name: None,
476 ty,
477 rocq_type: None,
478 span: None,
479 }));
480 }
481 ctors.push(SCtor {
482 name: ctor_name,
483 fields,
484 });
485 }
486 if self.cursor.is("deriving") {
487 self.cursor.advance();
488 self.cursor.identifier(Some("deriving"))?;
489 while self.cursor.eat(",").is_some() {
490 self.cursor.identifier(Some("deriving"))?;
491 }
492 }
493 Ok(SData {
494 name,
495 ctors,
496 span: Some(self.span_to_next(&start)),
497 generated: false,
498 source_unit_clone_derivation: None,
499 })
500 }
501
502 fn binder_group(&mut self) -> Result<Vec<(String, Type)>> {
503 let open = self.cursor.expect("(", Some("binder"))?;
504 let mut names = Vec::new();
505 while self.cursor.is_kind(TokenKind::Identifier) {
506 names.push(self.cursor.advance().value);
507 }
508 if names.is_empty() {
509 return Err(self.fail("expected binder names"));
510 }
511 self.cursor.expect(":", Some("binder"))?;
512 let ty = self.ty()?;
513 self.cursor.expect(")", Some("binder"))?;
514 if self.cursor.is("{") || self.cursor.is("[") {
515 return Err(unsupported(
516 "implicit binder",
517 "implicit and instance binders are outside the portable core",
518 Some(self.span_to_next(&open)),
519 ));
520 }
521 Ok(names.into_iter().map(|name| (name, ty.clone())).collect())
522 }
523
524 fn binders(&mut self) -> Result<Vec<(String, Type)>> {
525 let mut result = Vec::new();
526 while self.cursor.is("(") || self.cursor.is("{") || self.cursor.is("[") {
527 if !self.cursor.is("(") {
528 let token = self.cursor.peek();
529 return Err(unsupported(
530 "implicit binder",
531 "implicit and instance binders are outside the portable core",
532 Some(span(token, token)),
533 ));
534 }
535 result.extend(self.binder_group()?);
536 }
537 Ok(result)
538 }
539
540 fn arrow_type(&mut self) -> Result<Vec<Type>> {
541 let mut types = vec![self.ty()?];
542 while self.cursor.eat("→").is_some() || self.cursor.eat("->").is_some() {
543 types.push(self.ty()?);
544 }
545 Ok(types)
546 }
547
548 fn ty(&mut self) -> Result<Type> {
549 let token = self.peek();
550 if self.cursor.eat("(").is_some() {
551 let mut types = self.arrow_type()?;
552 self.cursor.expect(")", Some("type"))?;
553 if types.len() != 1 {
554 return Err(unsupported(
555 "function type",
556 "higher-order values are outside the portable core",
557 Some(span(&token, &token)),
558 ));
559 }
560 return Ok(types.remove(0));
561 }
562 let name = self.cursor.identifier(Some("type"))?.value;
563 if let Some(builtin) = builtin_type(&name) {
564 return Ok(builtin);
565 }
566 if is_unsupported_type(&name) {
567 return Err(unsupported(
568 &format!("Lean type {name}"),
569 "outside the portable core",
570 Some(span(&token, &token)),
571 ));
572 }
573 let next = self.cursor.peek();
574 if !self.blocked(next)
575 && next.kind == TokenKind::Identifier
576 && !["where", ":=", "with", "deriving"].contains(&next.value.as_str())
577 {
578 return Err(unsupported(
579 "type application",
580 &format!("{name} {} is outside the portable core", next.value),
581 Some(span(&token, next)),
582 ));
583 }
584 Ok(Type::Named {
585 path: name.split('.').map(str::to_owned).collect(),
586 span: Some(span(&token, &token)),
587 })
588 }
589
590 fn definition(&mut self, path: &[String]) -> Result<Definition> {
591 let start = self.cursor.advance();
592 let name_token = self.cursor.identifier(Some("def"))?;
593 let name = name_token.value.clone();
594 if name.contains('.') {
595 return Err(unsupported(
596 "qualified definition name",
597 "declare definitions inside their namespace",
598 Some(span(&name_token, &name_token)),
599 ));
600 }
601 let params: Vec<SParam> = self
602 .binders()?
603 .into_iter()
604 .map(|(name, ty)| param(name, ty))
605 .collect();
606 self.cursor.expect(":", Some("def"))?;
607 if name == "main" && path.is_empty() && self.cursor.is("IO") {
608 return self.main(&start);
609 }
610 let mut types = self.arrow_type()?;
611 let ret = types.pop();
612 let extra: Vec<SParam> = types
613 .into_iter()
614 .enumerate()
615 .map(|(index, ty)| param(format!("ml_arg{index}"), ty))
616 .collect();
617 if self.cursor.eat(":=").is_some() {
618 if !extra.is_empty() {
619 return Err(unsupported(
620 "function-valued definition body",
621 "use binders or equations for arrow types",
622 Some(self.span_to_next(&start)),
623 ));
624 }
625 let body = self.with_bound(0, Self::expr)?;
626 self.end_decl(&start, "termination_by")?;
627 return Ok(Definition::Fn(Box::new(SFn {
628 semantic_ret: None,
629 name,
630 params,
631 ret,
632 source_signature: None,
633 source_primitive_owners: None,
634 source_empty_option: None,
635 source_type_namespace: None,
636 source_local_state: None,
637 source_const_function: None,
638 source_diagnostic_attributes: None,
639 source_loop: None,
640 body,
641 span: Some(self.span_to_next(&start)),
642 generated: false,
643 source_pure_unit: None,
644 })));
645 }
646 if !self.cursor.is("|") {
647 return Err(self.fail("expected := or equations"));
648 }
649 if extra.is_empty() {
650 return Err(unsupported(
651 "equations without arrow arguments",
652 "use match",
653 Some(self.span_to_next(&start)),
654 ));
655 }
656 let rows = self.alternatives(extra.len())?;
657 let body = expr(
658 SNode::Match {
659 scrutinees: extra.iter().map(|param| SExpr::name(¶m.name)).collect(),
660 rows,
661 },
662 self.span_to_next(&start),
663 );
664 self.end_decl(&start, "termination_by")?;
665 Ok(Definition::Fn(Box::new(SFn {
666 semantic_ret: None,
667 name,
668 params: params.into_iter().chain(extra).collect(),
669 ret,
670 source_signature: None,
671 source_primitive_owners: None,
672 source_empty_option: None,
673 source_type_namespace: None,
674 source_local_state: None,
675 source_const_function: None,
676 source_diagnostic_attributes: None,
677 source_loop: None,
678 body,
679 span: Some(self.span_to_next(&start)),
680 generated: false,
681 source_pure_unit: None,
682 })))
683 }
684
685 fn end_decl(&self, start: &Token, keyword: &str) -> Result<()> {
686 if self.cursor.is(keyword) || self.cursor.is("decreasing_by") {
687 return Err(unsupported(
688 &format!("Lean {}", self.cursor.peek().value),
689 "explicit termination arguments are outside the portable core",
690 Some(self.span_to_next(start)),
691 ));
692 }
693 if !self.blocked_next() {
694 return Err(self.fail("expected the end of the declaration"));
695 }
696 Ok(())
697 }
698
699 fn main(&mut self, start: &Token) -> Result<Definition> {
700 self.cursor.expect("IO", Some("main"))?;
701 self.cursor.expect("Unit", Some("main"))?;
702 self.cursor.expect(":=", Some("main"))?;
703 self.cursor.expect("do", Some("main"))?;
704 let mut effects = Vec::new();
705 let first = self.peek();
706 let effect_column = if first.first { column(&first) } else { -1 };
707 if effect_column <= 0 {
708 return Err(unsupported(
709 "inline do block",
710 "write one effect per line",
711 Some(span(&first, &first)),
712 ));
713 }
714 while !self.cursor.at_end()
715 && column(self.cursor.peek()) == effect_column
716 && self.cursor.peek().first
717 {
718 let before = self.cursor.index;
719 effects.push(self.with_bound(effect_column, Self::effect)?);
720 if self.cursor.index == before {
721 return Err(self.fail("expected an effect"));
722 }
723 }
724 self.end_decl(start, "where")?;
725 let at = self.span_to_next(start);
726 Ok(Definition::Main(
727 SMain {
728 effects,
729 span: Some(at),
730 sequential_async: false,
731 source_runtime_worker: None,
732 },
733 at,
734 ))
735 }
736
737 fn effect(&mut self) -> Result<SEffect> {
738 let token = self.peek();
739 if self.cursor.is("IO.println") {
740 self.cursor.advance();
741 let expr = self.atom()?;
742 return Ok(SEffect::Print {
743 expr,
744 style: ShowStyle::Lean,
745 span: Some(self.span_to_next(&token)),
746 });
747 }
748 if self.cursor.is("let") {
749 self.cursor.advance();
750 let name = self.cursor.identifier(Some("let"))?.value;
751 let ty = if self.cursor.eat(":").is_some() {
752 Some(self.ty()?)
753 } else {
754 None
755 };
756 self.cursor.expect(":=", Some("let"))?;
757 let value = self.expr()?;
758 return Ok(SEffect::Let {
759 name,
760 ty,
761 value,
762 constant: false,
763 span: Some(self.span_to_next(&token)),
764 source_pure_unit_call: None,
765 });
766 }
767 Err(unsupported(
768 "Lean do element",
769 &format!("{} is outside the portable effect model", describe(&token)),
770 Some(span(&token, &token)),
771 ))
772 }
773}
774
775fn plain_application(head: SExpr, args: Vec<SExpr>, range: Span) -> Result<SExpr> {
777 if args.is_empty() {
778 return Ok(head);
779 }
780 if !matches!(head.node, SNode::Name { .. } | SNode::DotCtor { .. }) {
781 return Err(unsupported(
782 "higher-order application",
783 "only named functions can be applied",
784 Some(range),
785 ));
786 }
787 Ok(expr(
788 SNode::App {
789 func: Box::new(head),
790 args,
791 },
792 range,
793 ))
794}
795
796const fn connective(node: SPropNode) -> SProp {
797 SProp { node, span: None }
798}
799
800fn bind_or_ctor(head: PatternHead, token: &Token) -> SPattern {
801 let name = head.path.into_iter().next().unwrap_or_default();
802 pattern(SPatternNode::BindOrCtor { name }, Some(span(token, token)))
803}
804
805const fn param(name: String, ty: Type) -> SParam {
806 SParam {
807 name,
808 optional: false,
809 default_value: None,
810 ty: Some(ty),
811 span: None,
812 guard: None,
813 rocq_type: None,
814 }
815}
816
817const fn binder(name: String, ty: Type) -> SBinder {
818 SBinder {
819 name,
820 ty: Some(ty),
821 rocq_type: None,
822 span: None,
823 }
824}