1use crate::ast::{self, Span};
2use crate::attributes::has_test_attribute;
3use crate::lex;
4use crate::lex::TokenKind::*;
5use crate::lex::{Token, TokenKind};
6use crate::types::Type;
7
8pub const MAX_TUPLE_ARITY: usize = 5;
9pub const TUPLE_FIELDS: &[&str] = &["First", "Second", "Third", "Fourth", "Fifth"];
10const MAX_DEPTH: u32 = 64;
11const MAX_ERRORS: usize = 50;
12const MAX_LOOKAHEAD: usize = 256;
13
14#[derive(Clone, Copy, PartialEq, Eq)]
15pub(crate) enum ParamMode {
16 Strict,
17 TestFunction,
18}
19
20mod annotations;
21mod control_flow;
22mod definitions;
23mod directives;
24mod error;
25mod expressions;
26mod identifiers;
27mod patterns;
28mod pratt;
29mod strings;
30
31pub use error::ParseError;
32
33pub struct ParseResult {
34 pub ast: Vec<ast::Expression>,
35 pub errors: Vec<ParseError>,
36 pub has_desugarables: bool,
37}
38
39impl ParseResult {
40 pub fn failed(&self) -> bool {
41 !self.errors.is_empty()
42 }
43}
44
45pub struct Parser<'source> {
46 stream: TokenStream<'source>,
47 previous_token: Token<'source>,
48 pending_right_angle: Option<u32>,
49 pub errors: Vec<ParseError>,
50 file_id: u32,
51 in_control_flow_header: bool,
52 source: &'source str,
53 depth: u32,
54 pub(crate) has_desugarables: bool,
55}
56
57impl<'source> Parser<'source> {
58 pub fn new(tokens: Vec<Token<'source>>, source: &'source str) -> Parser<'source> {
59 Self::with_file_id(tokens, source, 0)
60 }
61
62 pub fn lex_and_parse_file(source: &str, file_id: u32) -> ParseResult {
63 let lex_result = lex::Lexer::new(source, file_id).lex();
64
65 if lex_result.failed() {
66 return ParseResult {
67 ast: vec![],
68 errors: lex_result.errors,
69 has_desugarables: false,
70 };
71 }
72
73 Parser::with_file_id(lex_result.tokens, source, file_id).parse()
74 }
75
76 fn with_file_id(
77 tokens: Vec<Token<'source>>,
78 source: &'source str,
79 file_id: u32,
80 ) -> Parser<'source> {
81 let stream = TokenStream::new(tokens);
82 let first_token = stream.peek();
83
84 let mut parser = Parser {
85 stream,
86 previous_token: first_token,
87 pending_right_angle: None,
88 errors: Default::default(),
89 file_id,
90 in_control_flow_header: false,
91 source,
92 depth: 0,
93 has_desugarables: false,
94 };
95
96 parser.skip_comments();
97
98 parser
99 }
100
101 pub fn parse(mut self) -> ParseResult {
102 let mut top_items = vec![];
103
104 self.skip_comments();
105
106 while !self.at_eof() && !self.too_many_errors() {
107 let position = self.position();
108 let item = self.parse_top_item();
109 if !matches!(item, ast::Expression::Unit { .. }) {
110 top_items.push(item);
111 }
112 self.advance_if(Semicolon);
113 if self.position() == position {
114 self.next();
115 }
116 }
117
118 ParseResult {
119 ast: top_items,
120 errors: self.errors,
121 has_desugarables: self.has_desugarables,
122 }
123 }
124
125 pub fn parse_top_item(&mut self) -> ast::Expression {
126 let doc_with_span = self.collect_doc_comments();
127
128 let attributes = self.parse_attributes();
129
130 let pub_token = if self.is(Pub) {
131 Some(self.current_token())
132 } else {
133 None
134 };
135 let is_public = pub_token.is_some();
136 if is_public {
137 self.next();
138 }
139
140 if is_public && self.is(Impl) {
141 let token = pub_token.unwrap();
142 let span = ast::Span::new(self.file_id, token.byte_offset, token.byte_length);
143 let error = ParseError::new("Misplaced `pub`", span, "not allowed here")
144 .with_parse_code("syntax_error")
145 .with_help("Place `pub` on individual methods inside the `impl` block instead");
146 self.errors.push(error);
147 }
148
149 let is_documentable = matches!(
150 self.current_token().kind,
151 Enum | Struct | Interface | Function | Const | Var | Type
152 );
153
154 if let Some((_, ref span)) = doc_with_span
155 && !is_documentable
156 {
157 self.error_detached_doc_comment(*span);
158 }
159
160 let doc = doc_with_span.map(|(text, _)| text);
161
162 if !matches!(self.current_token().kind, Enum | Struct | Function | Type)
163 && let Some(attribute) = attributes.first()
164 {
165 self.error_misplaced_attribute(attribute.span);
166 }
167
168 let expression = match self.current_token().kind {
169 Enum => self.parse_enum_definition(doc, attributes),
170 Struct => self.parse_struct_definition(doc, attributes),
171 Interface => self.parse_interface_definition(doc),
172 Function => {
173 let mode = if has_test_attribute(&attributes) {
175 ParamMode::TestFunction
176 } else {
177 ParamMode::Strict
178 };
179 self.parse_function(doc, attributes, mode)
180 }
181 Impl => self.parse_impl_block(),
182 Const => self.parse_const_definition(doc),
183 Var => self.parse_var_declaration(doc),
184 Import => self.parse_import(),
185 Type => self.parse_type_alias_with_doc(doc, attributes),
186 Comment => {
187 let start = self.current_token();
188 self.skip_comments();
189 ast::Expression::Unit {
190 ty: Type::uninferred(),
191 span: self.span_from_tokens(start),
192 }
193 }
194 _ => self.unexpected_token("top_item"),
195 };
196
197 if is_public {
198 return expression.set_public();
199 }
200
201 expression
202 }
203
204 pub fn parse_block_item(&mut self) -> ast::Expression {
205 match self.current_token().kind {
206 Enum => {
207 self.track_error(
208 "misplaced",
209 "Move this enum definition to the top level of the file.",
210 );
211 self.parse_enum_definition(None, vec![])
212 }
213 Struct => {
214 self.track_error(
215 "misplaced",
216 "Move this struct definition to the top level of the file.",
217 );
218 self.parse_struct_definition(None, vec![])
219 }
220 Type => {
221 self.track_error(
222 "misplaced",
223 "Move this type alias to the top level of the file.",
224 );
225 self.parse_type_alias_with_doc(None, vec![])
226 }
227 Import => {
228 self.track_error(
229 "misplaced",
230 "Move this import to the top level of the file.",
231 );
232 self.parse_import()
233 }
234 Impl => {
235 self.track_error(
236 "misplaced",
237 "Move this `impl` block to the top level of the file.",
238 );
239 self.parse_impl_block()
240 }
241 Interface => {
242 self.track_error(
243 "misplaced",
244 "Move this interface definition to the top level of the file.",
245 );
246 self.parse_interface_definition(None)
247 }
248 Function => self.parse_function(None, vec![], ParamMode::Strict),
249 Const => self.parse_const_definition(None),
250
251 Hash => {
252 let attributes = self.parse_attributes();
253 if let Some(attribute) = attributes.first() {
254 self.error_misplaced_attribute(attribute.span);
255 }
256 if self.is(RightCurlyBrace) || self.at_eof() {
257 ast::Expression::Unit {
258 ty: Type::uninferred(),
259 span: self.span_from_token(self.current_token()),
260 }
261 } else {
262 self.parse_block_item()
263 }
264 }
265
266 Let => self.parse_let(),
267 Return => self.parse_return(true),
268 For => self.parse_for(),
269 While => self.parse_while(),
270 Loop => self.parse_loop(),
271 Break => self.parse_break(),
272 Continue => self.parse_continue(),
273 Defer => self.parse_defer(),
274 Assert => self.parse_assert(),
275 Directive => self.parse_directive(),
276 _ => self.parse_assignment(),
277 }
278 }
279
280 fn current_token(&self) -> Token<'source> {
281 if let Some(byte_offset) = self.pending_right_angle {
282 return Token {
283 kind: TokenKind::RightAngleBracket,
284 text: ">",
285 byte_offset,
286 byte_length: 1,
287 };
288 }
289 self.stream.peek()
290 }
291
292 fn newline_before_current(&self) -> bool {
293 let prev_end = (self.previous_token.byte_offset + self.previous_token.byte_length) as usize;
294 let curr_start = self.current_token().byte_offset as usize;
295 if prev_end <= curr_start && curr_start <= self.source.len() {
296 return self.source[prev_end..curr_start].contains('\n');
297 }
298 false
299 }
300
301 fn next(&mut self) {
302 self.previous_token = self.current_token();
303 if self.pending_right_angle.take().is_some() {
304 self.skip_comments();
305 return;
306 }
307 self.stream.consume();
308 self.skip_comments();
309 }
310
311 fn skip_comments(&mut self) {
312 while self.is(Comment) {
313 self.previous_token = self.current_token();
314 self.stream.consume();
315 }
316 }
317
318 fn collect_doc_comments(&mut self) -> Option<(std::string::String, ast::Span)> {
319 let mut docs = Vec::new();
320 let mut first_span: Option<ast::Span> = None;
321
322 while self.is(DocComment) {
323 let token = self.current_token();
324 if first_span.is_none() {
325 first_span = Some(self.span_from_token(token));
326 }
327 docs.push(token.text.to_string());
328 self.previous_token = token;
329 self.stream.consume();
330 self.skip_comments();
331 }
332
333 if docs.is_empty() {
334 None
335 } else {
336 Some((docs.join("\n"), first_span.unwrap()))
337 }
338 }
339
340 fn expect_comma_or(&mut self, closing: TokenKind) {
341 if self.is(Comma) || self.is(closing) || self.at_item_boundary() {
342 self.advance_if(Comma);
343 return;
344 }
345
346 self.track_error(
347 format!("expected `,` or {}", closing),
348 "Add a comma between elements.",
349 );
350
351 self.recover_to_comma_or(closing);
352 }
353
354 pub(super) fn recover_to_comma_or(&mut self, closing: TokenKind) {
355 while !self.at_eof() && !self.is(Comma) && !self.is(closing) && !self.at_item_boundary() {
356 self.next();
357 }
358
359 self.advance_if(Comma);
360 }
361
362 pub fn at_eof(&self) -> bool {
363 self.is(EOF)
364 }
365
366 fn at_range(&self) -> bool {
367 matches!(self.current_token().kind, DotDot | DotDotEqual)
368 }
369
370 fn advance_if(&mut self, token_kind: TokenKind) -> bool {
371 if self.is(token_kind) {
372 self.next();
373 return true;
374 }
375
376 false
377 }
378
379 fn is(&self, token_kind: TokenKind) -> bool {
380 self.current_token().kind == token_kind
381 }
382
383 fn is_not(&self, token_kind: TokenKind) -> bool {
384 if self.at_eof() {
385 return false;
386 }
387
388 self.current_token().kind != token_kind
389 }
390
391 fn ensure(&mut self, token_kind: TokenKind) {
392 if self.current_token().kind != token_kind {
393 self.track_ensure_error(token_kind);
394 }
395
396 if self.at_eof() {
397 return;
398 }
399
400 self.next();
401 }
402
403 fn ensure_progress(&mut self, start_position: usize, closing: TokenKind) {
404 if self.stream.position == start_position && self.is_not(closing) && !self.at_eof() {
405 self.next();
406 }
407 }
408
409 fn is_right_angle_like(&self) -> bool {
410 matches!(self.current_token().kind, RightAngleBracket | ShiftRight)
411 }
412
413 fn advance_if_right_angle(&mut self) -> bool {
414 let token = self.current_token();
415 match token.kind {
416 RightAngleBracket => {
417 self.next();
418 true
419 }
420 ShiftRight => {
421 self.previous_token = Token {
422 kind: RightAngleBracket,
423 text: ">",
424 byte_offset: token.byte_offset,
425 byte_length: 1,
426 };
427 self.stream.consume();
428 self.pending_right_angle = Some(token.byte_offset + 1);
429 self.skip_comments();
430 true
431 }
432 _ => false,
433 }
434 }
435
436 fn span_from_token(&self, token: Token<'source>) -> ast::Span {
437 ast::Span::new(self.file_id, token.byte_offset, token.byte_length)
438 }
439
440 fn span_from_tokens(&self, start_token: Token<'source>) -> ast::Span {
441 let end_byte_offset = self.previous_token.byte_offset + self.previous_token.byte_length;
442 let byte_length = end_byte_offset.saturating_sub(start_token.byte_offset);
443
444 ast::Span::new(self.file_id, start_token.byte_offset, byte_length)
445 }
446
447 fn span_from_offset(&self, start_byte_offset: u32) -> ast::Span {
448 let end_byte_offset = self.previous_token.byte_offset + self.previous_token.byte_length;
449 let byte_length = end_byte_offset.saturating_sub(start_byte_offset);
450
451 ast::Span::new(self.file_id, start_byte_offset, byte_length)
452 }
453
454 fn is_type_args_call(&self) -> bool {
455 let mut position = 1; let mut depth = 1;
457
458 loop {
459 if position > MAX_LOOKAHEAD {
460 return false;
461 }
462 match self.stream.peek_ahead(position).kind {
463 LeftAngleBracket => depth += 1,
464 RightAngleBracket if depth == 1 => {
465 let next = self.stream.peek_ahead(position + 1).kind;
466 return next == LeftParen
467 || (next == Dot
468 && self.stream.peek_ahead(position + 2).kind == Identifier
469 && self.stream.peek_ahead(position + 3).kind == LeftParen);
470 }
471 RightAngleBracket => depth -= 1,
472 ShiftRight if depth <= 2 => {
473 let next = self.stream.peek_ahead(position + 1).kind;
474 return next == LeftParen
475 || (next == Dot
476 && self.stream.peek_ahead(position + 2).kind == Identifier
477 && self.stream.peek_ahead(position + 3).kind == LeftParen);
478 }
479 ShiftRight => depth -= 2,
480 LeftParen => {
481 let mut paren_depth = 1;
482 position += 1;
483 while paren_depth > 0 {
484 if position > MAX_LOOKAHEAD {
485 return false;
486 }
487 match self.stream.peek_ahead(position).kind {
488 LeftParen => paren_depth += 1,
489 RightParen => paren_depth -= 1,
490 EOF => return false,
491 _ => {}
492 }
493 position += 1;
494 }
495 continue;
496 }
497 EOF | Plus | Minus | Star | Slash | Percent | EqualDouble | NotEqual
498 | AmpersandDouble | PipeDouble | Semicolon | LeftCurlyBrace | RightCurlyBrace
499 | LeftSquareBracket | RightSquareBracket => return false,
500 _ => {}
501 }
502 position += 1;
503 }
504 }
505
506 fn has_block_after_struct(&self) -> bool {
507 let mut depth = 1;
508 let mut i = 0;
509 while depth > 0 {
510 i += 1;
511 if i > MAX_LOOKAHEAD {
512 return false;
513 }
514 let token = self.stream.peek_ahead(i);
515 match token.kind {
516 LeftCurlyBrace => depth += 1,
517 RightCurlyBrace => depth -= 1,
518 EOF => return false,
519 _ => {}
520 }
521 }
522 let after = self.stream.peek_ahead(i + 1);
523 matches!(
524 after.kind,
525 LeftCurlyBrace
526 | RightParen
527 | EqualDouble
528 | NotEqual
529 | LeftAngleBracket
530 | RightAngleBracket
531 | LessThanOrEqual
532 | GreaterThanOrEqual
533 | AmpersandDouble
534 | PipeDouble
535 | Plus
536 | Minus
537 | Star
538 | Slash
539 | Percent
540 )
541 }
542
543 fn is_struct_instantiation(&self) -> bool {
544 if self.previous_token.kind != Identifier {
545 return false;
546 }
547
548 let is_uppercase = self
549 .previous_token
550 .text
551 .starts_with(|c: char| c.is_uppercase());
552 let first_ahead = self.stream.peek_ahead(1);
553
554 if first_ahead.kind == DotDot {
555 return true;
556 }
557
558 if first_ahead.kind == RightCurlyBrace {
559 if self.in_control_flow_header {
560 return is_uppercase && self.has_block_after_struct();
561 }
562 return is_uppercase;
563 }
564
565 if first_ahead.kind == Identifier {
566 let second_ahead = self.stream.peek_ahead(2);
567 return match second_ahead.kind {
568 Colon => self.stream.peek_ahead(3).kind != Colon,
569 Comma | RightCurlyBrace => {
570 if self.in_control_flow_header {
571 is_uppercase && self.has_block_after_struct()
572 } else {
573 is_uppercase
574 }
575 }
576 _ => false,
577 };
578 }
579
580 false
581 }
582
583 fn enter_recursion(&mut self) -> bool {
584 if self.depth >= MAX_DEPTH {
585 let span = self.span_from_token(self.current_token());
586 self.track_error_at(span, "too deeply nested", "Reduce nesting depth");
587 return false;
588 }
589 self.depth += 1;
590 true
591 }
592
593 fn leave_recursion(&mut self) {
594 self.depth -= 1;
595 }
596
597 fn too_many_errors(&self) -> bool {
598 self.errors.len() >= MAX_ERRORS
599 }
600
601 fn position(&self) -> u32 {
602 self.current_token().byte_offset
603 }
604
605 fn at_sync_point(&self) -> bool {
606 matches!(
607 self.current_token().kind,
608 Semicolon
609 | RightCurlyBrace
610 | RightParen
611 | RightSquareBracket
612 | Comma
613 | Function
614 | Struct
615 | Enum
616 | Const
617 | Impl
618 | Interface
619 | Type
620 | Import
621 )
622 }
623
624 fn can_start_annotation(&self) -> bool {
625 matches!(
626 self.current_token().kind,
627 Identifier | Function | LeftParen | Integer
628 )
629 }
630
631 fn at_item_boundary(&self) -> bool {
632 matches!(
633 self.current_token().kind,
634 Let | Function | Struct | Enum | Impl | Interface | Type | Const | Import
635 )
636 }
637
638 fn at_match_arm_terminator(&self) -> bool {
639 self.at_eof() || self.is(Comma) || self.is(RightCurlyBrace) || self.at_item_boundary()
640 }
641
642 fn resync_on_error(&mut self) {
643 if !self.at_eof() {
644 self.next();
645 }
646
647 while !self.at_sync_point() && !self.at_eof() {
648 self.next();
649 }
650 }
651
652 fn track_error(
653 &mut self,
654 label: impl Into<std::string::String>,
655 help: impl Into<std::string::String>,
656 ) {
657 let current = self.current_token();
658 let span = ast::Span::new(self.file_id, current.byte_offset, current.byte_length);
659 self.track_error_at(span, label, help);
660 }
661
662 fn track_error_at(
663 &mut self,
664 span: ast::Span,
665 label: impl Into<std::string::String>,
666 help: impl Into<std::string::String>,
667 ) {
668 if self.too_many_errors() {
669 return;
670 }
671 let error = ParseError::new("Syntax error", span, label.into())
672 .with_parse_code("syntax_error")
673 .with_help(help.into());
674
675 self.errors.push(error);
676 }
677
678 fn error_angle_brackets_for_generics(
679 &mut self,
680 span: ast::Span,
681 help: impl Into<std::string::String>,
682 ) {
683 if self.too_many_errors() {
684 return;
685 }
686 let error = ParseError::new("Syntax error", span, "use `<...>` for type args")
687 .with_parse_code("angle_brackets_for_generics")
688 .with_help(help.into());
689
690 self.errors.push(error);
691 }
692
693 fn error_var_initializer(&mut self, span: ast::Span) {
694 if self.too_many_errors() {
695 return;
696 }
697 let error = ParseError::new("Syntax error", span, "not allowed")
698 .with_parse_code("var_not_allowed")
699 .with_help(
700 "Use `const` for a primitive, or a function that returns the value e.g. `fn origin() -> Point { ... }` for a composite",
701 );
702
703 self.errors.push(error);
704 }
705
706 fn error_import_alias_after_path(&mut self, span: ast::Span, alias: &str, path: &str) {
707 if self.too_many_errors() {
708 return;
709 }
710 let error = ParseError::new("Syntax error", span, "import alias goes before the path")
711 .with_parse_code("import_alias_position")
712 .with_help(format!(
713 "Use Go-style alias syntax: `import {alias} \"{path}\"`"
714 ));
715
716 self.errors.push(error);
717 }
718
719 fn error_bare_multi_return(&mut self, span: ast::Span, suggestion: &str) {
720 if self.too_many_errors() {
721 return;
722 }
723 let error = ParseError::new(
724 "Multiple return values must be a tuple",
725 span,
726 "wrap these values in parentheses",
727 )
728 .with_parse_code("bare_multi_value_return")
729 .with_help(format!(
730 "To return multiple values, use a tuple: `{suggestion}`"
731 ));
732
733 self.errors.push(error);
734 }
735
736 fn error_match_arm_missing_comma(&mut self, span: ast::Span) {
737 if self.too_many_errors() {
738 return;
739 }
740 let error = ParseError::new("Syntax error", span, "missing comma after match arm")
741 .with_parse_code("match_arm_missing_comma")
742 .with_help("Match arms must be separated by commas, even when the body is a block.");
743
744 self.errors.push(error);
745 }
746
747 pub(super) fn error_map_literal_not_supported(&mut self, span: ast::Span) {
748 if self.too_many_errors() {
749 return;
750 }
751 let error = ParseError::new("Invalid `Map` initialization", span, "invalid syntax")
752 .with_parse_code("invalid_map_initialization")
753 .with_help("To initialize a `Map`, use `Map.new<K, V>()` then `m[key] = value`");
754
755 self.errors.push(error);
756 }
757
758 pub(super) fn error_missing_initializer(&mut self, span: ast::Span) {
759 if self.too_many_errors() {
760 return;
761 }
762 let error = ParseError::new(
763 "Missing initializer",
764 span,
765 "annotated binding needs a value",
766 )
767 .with_parse_code("missing_initializer")
768 .with_help("Bindings must be initialized");
769
770 self.errors.push(error);
771 }
772
773 fn track_ensure_error(&mut self, expected_token: TokenKind) {
774 if self.too_many_errors() {
775 return;
776 }
777 let current = self.current_token();
778
779 let error_code = match expected_token {
780 Semicolon => "missing_semicolon",
781 RightCurlyBrace => "unclosed_block",
782 _ => "unexpected_token",
783 };
784
785 let span = ast::Span::new(self.file_id, current.byte_offset, current.byte_length);
786 let error = ParseError::new("Syntax error", span, format!("expected {}", expected_token))
787 .with_parse_code(error_code);
788
789 self.errors.push(error);
790 }
791
792 fn close_brace_span(&mut self, start: Token<'source>, error_anchor: Token<'source>) -> Span {
793 if self.is(RightCurlyBrace) {
794 let close = self.current_token();
795 self.next();
796 let end = close.byte_offset + close.byte_length;
797 Span::new(
798 self.file_id,
799 start.byte_offset,
800 end.saturating_sub(start.byte_offset),
801 )
802 } else {
803 self.error_unclosed_block(&error_anchor);
804 self.span_from_tokens(start)
805 }
806 }
807
808 fn error_unclosed_block(&mut self, open_brace: &Token) {
809 let span = ast::Span::new(self.file_id, open_brace.byte_offset, open_brace.byte_length);
810 let error = ParseError::new("Unclosed block", span, "opening brace here")
811 .with_parse_code("unclosed_block")
812 .with_help("Add a closing `}`");
813
814 self.errors.push(error);
815 }
816
817 fn error_tuple_arity(&mut self, arity: usize, span: Span) {
818 let help = if arity == 0 {
819 "Use `()` for unit type".to_string()
820 } else if arity == 1 {
821 "Use the type directly without wrapping in a tuple".to_string()
822 } else {
823 "For >5 elements, use a struct with named fields".to_string()
824 };
825
826 let error = ParseError::new(
827 "Invalid tuple",
828 span,
829 format!("{}-element tuple not allowed", arity),
830 )
831 .with_parse_code("tuple_element_count")
832 .with_help(help);
833
834 self.errors.push(error);
835 }
836
837 fn error_duplicate_field_in_pattern(
838 &mut self,
839 field_name: &str,
840 first_span: Span,
841 second_span: Span,
842 ) {
843 let error = ParseError::new(
844 "Duplicate field",
845 first_span,
846 format!("first use of `{}`", field_name),
847 )
848 .with_span_label(second_span, "used again")
849 .with_parse_code("duplicate_field_in_pattern")
850 .with_help("Remove the duplicate binding");
851
852 self.errors.push(error);
853 }
854
855 fn error_duplicate_embed_parent(&mut self, first_span: Span, second_span: Span) {
856 let error = ParseError::new("Duplicate embed", first_span, "first use")
857 .with_span_label(second_span, "used again")
858 .with_parse_code("duplicate_embed_parent")
859 .with_help("Remove the duplicate parent");
860
861 self.errors.push(error);
862 }
863
864 fn error_impl_interface_embed(&mut self, keyword_span: Span) {
865 let error = ParseError::new(
866 "Interface embedding uses `embed`",
867 keyword_span,
868 "write `embed` here",
869 )
870 .with_parse_code("impl_interface_embed")
871 .with_help("Interfaces embed other interfaces with `embed`. Replace `impl` with `embed`");
872
873 self.errors.push(error);
874 }
875
876 fn error_duplicate_struct_field(&mut self, name: &str, first_span: Span, second_span: Span) {
877 let error = ParseError::new("Duplicate field", first_span, "first defined")
878 .with_span_label(second_span, "defined again")
879 .with_parse_code("duplicate_struct_field")
880 .with_help(format!("Remove the duplicate field `{}`", name));
881
882 self.errors.push(error);
883 }
884
885 fn error_duplicate_enum_variant(&mut self, name: &str, first_span: Span, second_span: Span) {
886 let error = ParseError::new("Duplicate variant", first_span, "first defined")
887 .with_span_label(second_span, "defined again")
888 .with_parse_code("duplicate_enum_variant")
889 .with_help(format!("Remove the duplicate variant `{}`", name));
890
891 self.errors.push(error);
892 }
893
894 fn error_duplicate_interface_method(
895 &mut self,
896 name: &str,
897 first_span: Span,
898 second_span: Span,
899 ) {
900 let error = ParseError::new("Duplicate method", first_span, "first defined")
901 .with_span_label(second_span, "defined again")
902 .with_parse_code("duplicate_interface_method")
903 .with_help(format!("Remove the duplicate method `{}`", name));
904
905 self.errors.push(error);
906 }
907
908 fn error_float_pattern_not_allowed(&mut self, span: Span, float_text: &str) {
909 let error = ParseError::new("Invalid pattern", span, "float literal not allowed here")
910 .with_parse_code("float_pattern")
911 .with_help(format!(
912 "Use a guard instead: `x if x == {} =>`",
913 float_text
914 ));
915
916 self.errors.push(error);
917 }
918
919 fn error_uppercase_binding(&mut self, span: Span) {
920 let error = ParseError::new("Invalid binding name", span, "uppercase not allowed here")
921 .with_parse_code("uppercase_binding")
922 .with_help("Lowercase the binding");
923
924 self.errors.push(error);
925 }
926
927 fn error_detached_doc_comment(&mut self, span: Span) {
928 let error = ParseError::new("Unattached doc comment", span, "is detached")
929 .with_parse_code("detached_doc_comment")
930 .with_help("Place the doc comment on the line immediately above a symbol definition");
931
932 self.errors.push(error);
933 }
934
935 fn error_misplaced_attribute(&mut self, span: Span) {
936 let error = ParseError::new(
937 "Attribute not supported on target",
938 span,
939 "not supported on target",
940 )
941 .with_parse_code("misplaced_attribute")
942 .with_help("Remove the attribute, or move it onto an enum, struct, or function");
943
944 self.errors.push(error);
945 }
946
947 fn error_interface_method_with_type_parameters(&mut self, span: Span, count: usize) {
948 let label = if count == 1 {
949 "type parameter not allowed"
950 } else {
951 "type parameters not allowed"
952 };
953 let error = ParseError::new("Invalid interface method", span, label)
954 .with_parse_code("interface_method_with_type_parameters")
955 .with_help(
956 "Interface methods cannot have type parameters, because Go interfaces do not support generic methods",
957 );
958
959 self.errors.push(error);
960 }
961
962 fn error_leading_zero(&mut self) {
963 let span = self.span_from_token(self.current_token());
964 let error = ParseError::new(
965 "Invalid number literal",
966 span,
967 "leading zero in integer literal",
968 )
969 .with_parse_code("number_leading_zero")
970 .with_help("Prefix with `0o` for octal (e.g. `0o644`) or remove the leading zero");
971 self.errors.push(error);
972 }
973
974 pub(crate) fn parse_integer_text(&mut self, text: &str) -> ast::Literal {
975 self.parse_integer_text_with(text, false)
976 }
977
978 pub(crate) fn parse_integer_text_with(
979 &mut self,
980 text: &str,
981 preserve_decimal_text: bool,
982 ) -> ast::Literal {
983 let clean = if text.contains('_') {
984 std::borrow::Cow::Owned(text.replace('_', ""))
985 } else {
986 std::borrow::Cow::Borrowed(text)
987 };
988
989 let (n, is_decimal) = if clean.starts_with("0x") || clean.starts_with("0X") {
990 let value = u64::from_str_radix(&clean[2..], 16).unwrap_or_else(|_| {
991 self.track_error(
992 format!("hex literal '{text}' is too large"),
993 "Maximum value is `0xFFFFFFFFFFFFFFFF`.",
994 );
995 0
996 });
997 (value, false)
998 } else if clean.starts_with("0o") || clean.starts_with("0O") {
999 let value = u64::from_str_radix(&clean[2..], 8).unwrap_or_else(|_| {
1000 self.track_error(
1001 format!("octal literal '{text}' is too large"),
1002 "Maximum value is `0o1777777777777777777777`.",
1003 );
1004 0
1005 });
1006 (value, false)
1007 } else if clean.starts_with("0b") || clean.starts_with("0B") {
1008 let value = u64::from_str_radix(&clean[2..], 2).unwrap_or_else(|_| {
1009 self.track_error(
1010 format!("binary literal '{text}' is too large"),
1011 "Value must fit in 64 bits.",
1012 );
1013 0
1014 });
1015 (value, false)
1016 } else if clean.len() > 1 && clean.starts_with('0') {
1017 self.error_leading_zero();
1018 (clean.parse().unwrap_or(0), false)
1019 } else {
1020 let value = clean.parse().unwrap_or_else(|_| {
1021 self.track_error(
1022 format!("integer literal '{text}' is too large"),
1023 "Maximum value is `18446744073709551615`.",
1024 );
1025 0
1026 });
1027 (value, true)
1028 };
1029
1030 let original_text = if is_decimal && !preserve_decimal_text {
1031 None
1032 } else {
1033 Some(text.to_string())
1034 };
1035
1036 ast::Literal::Integer {
1037 value: n,
1038 text: original_text,
1039 }
1040 }
1041
1042 fn unexpected_token(&mut self, ctx: &str) -> ast::Expression {
1043 let token = self.current_token();
1044 let token_descriptor = if token.text.is_empty() {
1045 format!("{:?}", token.kind)
1046 } else {
1047 format!("`{}`", token.text)
1048 };
1049
1050 let span = ast::Span::new(self.file_id, token.byte_offset, token.byte_length);
1051
1052 let (label, error_code, help) = match ctx {
1053 "expr" => (
1054 format!("expected expression, found {}", token_descriptor),
1055 "expected_expression",
1056 "Check your syntax.",
1057 ),
1058 "pattern" => (
1059 format!("unexpected {} in pattern", token_descriptor),
1060 "invalid_pattern",
1061 "Patterns include literals, variables, and destructuring.",
1062 ),
1063 "literal" => (
1064 format!("expected literal, found {}", token_descriptor),
1065 "expected_literal",
1066 "Literals include numbers, strings, characters, and booleans.",
1067 ),
1068 "top_item" if token.text == "trait" => (
1069 format!("unexpected {}", token_descriptor),
1070 "trait_unsupported",
1071 "Lisette uses `interface` with Go-style structural typing. Types automatically satisfy interfaces if they have the required methods.",
1072 ),
1073 "top_item" if token.text == "use" => (
1074 "unexpected syntax for import".to_string(),
1075 "use_unsupported",
1076 "Use `import` instead of `use` for imports: `import \"module/path\"`",
1077 ),
1078 "top_item" if token.kind == Let => (
1079 "`let` is not allowed at the top level".to_string(),
1080 "top_level_let",
1081 "Use `const` for a primitive, or a function that returns the value e.g. `fn origin() -> Point { ... }` for a composite",
1082 ),
1083 "top_item" => (
1084 "expected declaration".to_string(),
1085 "expected_declaration",
1086 "At the top level of a file, Lisette expects `fn`, `struct`, `enum`, `interface`, `impl`, `const`, `import`, or `type`.",
1087 ),
1088 _ => (
1089 format!("unexpected {}", token_descriptor),
1090 "unexpected_token",
1091 "Check your syntax.",
1092 ),
1093 };
1094
1095 let error = ParseError::new("Syntax error", span, label)
1096 .with_parse_code(error_code)
1097 .with_help(help);
1098
1099 if !self.too_many_errors() {
1100 self.errors.push(error);
1101 }
1102
1103 self.resync_on_error();
1104
1105 ast::Expression::Unit {
1106 ty: Type::uninferred(),
1107 span,
1108 }
1109 }
1110}
1111
1112struct TokenStream<'source> {
1113 tokens: Vec<Token<'source>>,
1114 position: usize,
1115 last_index: usize,
1116}
1117
1118impl<'source> TokenStream<'source> {
1119 fn new(tokens: Vec<Token<'source>>) -> Self {
1120 debug_assert!(
1121 !tokens.is_empty(),
1122 "lexer must always produce at least an EOF token",
1123 );
1124 let last_index = tokens.len() - 1;
1125 Self {
1126 tokens,
1127 position: 0,
1128 last_index,
1129 }
1130 }
1131
1132 fn peek(&self) -> Token<'source> {
1133 self.tokens[self.position]
1134 }
1135
1136 fn peek_ahead(&self, n: usize) -> Token<'source> {
1137 let idx = self.position.saturating_add(n);
1138 let idx = if idx > self.last_index {
1139 self.last_index
1140 } else {
1141 idx
1142 };
1143 self.tokens[idx]
1144 }
1145
1146 fn consume(&mut self) -> Token<'source> {
1147 let token = self.tokens[self.position];
1148 if self.position < self.last_index {
1149 self.position += 1;
1150 }
1151 token
1152 }
1153}