Skip to main content

lisette_syntax/parse/
mod.rs

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                // Only a top-level `#[test]` declaration may write a bare handle parameter.
174                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; // 0 is <
456        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!(self.current_token().kind, Identifier | Function | LeftParen)
626    }
627
628    fn at_item_boundary(&self) -> bool {
629        matches!(
630            self.current_token().kind,
631            Let | Function | Struct | Enum | Impl | Interface | Type | Const | Import
632        )
633    }
634
635    fn at_match_arm_terminator(&self) -> bool {
636        self.at_eof() || self.is(Comma) || self.is(RightCurlyBrace) || self.at_item_boundary()
637    }
638
639    fn resync_on_error(&mut self) {
640        if !self.at_eof() {
641            self.next();
642        }
643
644        while !self.at_sync_point() && !self.at_eof() {
645            self.next();
646        }
647    }
648
649    fn track_error(
650        &mut self,
651        label: impl Into<std::string::String>,
652        help: impl Into<std::string::String>,
653    ) {
654        let current = self.current_token();
655        let span = ast::Span::new(self.file_id, current.byte_offset, current.byte_length);
656        self.track_error_at(span, label, help);
657    }
658
659    fn track_error_at(
660        &mut self,
661        span: ast::Span,
662        label: impl Into<std::string::String>,
663        help: impl Into<std::string::String>,
664    ) {
665        if self.too_many_errors() {
666            return;
667        }
668        let error = ParseError::new("Syntax error", span, label.into())
669            .with_parse_code("syntax_error")
670            .with_help(help.into());
671
672        self.errors.push(error);
673    }
674
675    fn error_angle_brackets_for_generics(
676        &mut self,
677        span: ast::Span,
678        help: impl Into<std::string::String>,
679    ) {
680        if self.too_many_errors() {
681            return;
682        }
683        let error = ParseError::new("Syntax error", span, "use `<...>` for type args")
684            .with_parse_code("angle_brackets_for_generics")
685            .with_help(help.into());
686
687        self.errors.push(error);
688    }
689
690    fn error_var_initializer(&mut self, span: ast::Span) {
691        if self.too_many_errors() {
692            return;
693        }
694        let error = ParseError::new("Syntax error", span, "not allowed")
695            .with_parse_code("var_not_allowed")
696            .with_help(
697                "Use `const` for a primitive, or a function that returns the value e.g. `fn origin() -> Point { ... }` for a composite",
698            );
699
700        self.errors.push(error);
701    }
702
703    fn error_import_alias_after_path(&mut self, span: ast::Span, alias: &str, path: &str) {
704        if self.too_many_errors() {
705            return;
706        }
707        let error = ParseError::new("Syntax error", span, "import alias goes before the path")
708            .with_parse_code("import_alias_position")
709            .with_help(format!(
710                "Use Go-style alias syntax: `import {alias} \"{path}\"`"
711            ));
712
713        self.errors.push(error);
714    }
715
716    fn error_bare_multi_return(&mut self, span: ast::Span, suggestion: &str) {
717        if self.too_many_errors() {
718            return;
719        }
720        let error = ParseError::new(
721            "Multiple return values must be a tuple",
722            span,
723            "wrap these values in parentheses",
724        )
725        .with_parse_code("bare_multi_value_return")
726        .with_help(format!(
727            "To return multiple values, use a tuple: `{suggestion}`"
728        ));
729
730        self.errors.push(error);
731    }
732
733    fn error_match_arm_missing_comma(&mut self, span: ast::Span) {
734        if self.too_many_errors() {
735            return;
736        }
737        let error = ParseError::new("Syntax error", span, "missing comma after match arm")
738            .with_parse_code("match_arm_missing_comma")
739            .with_help("Match arms must be separated by commas, even when the body is a block.");
740
741        self.errors.push(error);
742    }
743
744    pub(super) fn error_map_literal_not_supported(&mut self, span: ast::Span) {
745        if self.too_many_errors() {
746            return;
747        }
748        let error = ParseError::new("Invalid `Map` initialization", span, "invalid syntax")
749            .with_parse_code("invalid_map_initialization")
750            .with_help("To initialize a `Map`, use `Map.new<K, V>()` then `m[key] = value`");
751
752        self.errors.push(error);
753    }
754
755    pub(super) fn error_missing_initializer(&mut self, span: ast::Span) {
756        if self.too_many_errors() {
757            return;
758        }
759        let error = ParseError::new(
760            "Missing initializer",
761            span,
762            "annotated binding needs a value",
763        )
764        .with_parse_code("missing_initializer")
765        .with_help("Bindings must be initialized");
766
767        self.errors.push(error);
768    }
769
770    fn track_ensure_error(&mut self, expected_token: TokenKind) {
771        if self.too_many_errors() {
772            return;
773        }
774        let current = self.current_token();
775
776        let error_code = match expected_token {
777            Semicolon => "missing_semicolon",
778            RightCurlyBrace => "unclosed_block",
779            _ => "unexpected_token",
780        };
781
782        let span = ast::Span::new(self.file_id, current.byte_offset, current.byte_length);
783        let error = ParseError::new("Syntax error", span, format!("expected {}", expected_token))
784            .with_parse_code(error_code);
785
786        self.errors.push(error);
787    }
788
789    fn close_brace_span(&mut self, start: Token<'source>, error_anchor: Token<'source>) -> Span {
790        if self.is(RightCurlyBrace) {
791            let close = self.current_token();
792            self.next();
793            let end = close.byte_offset + close.byte_length;
794            Span::new(
795                self.file_id,
796                start.byte_offset,
797                end.saturating_sub(start.byte_offset),
798            )
799        } else {
800            self.error_unclosed_block(&error_anchor);
801            self.span_from_tokens(start)
802        }
803    }
804
805    fn error_unclosed_block(&mut self, open_brace: &Token) {
806        let span = ast::Span::new(self.file_id, open_brace.byte_offset, open_brace.byte_length);
807        let error = ParseError::new("Unclosed block", span, "opening brace here")
808            .with_parse_code("unclosed_block")
809            .with_help("Add a closing `}`");
810
811        self.errors.push(error);
812    }
813
814    fn error_tuple_arity(&mut self, arity: usize, span: Span) {
815        let help = if arity == 0 {
816            "Use `()` for unit type".to_string()
817        } else if arity == 1 {
818            "Use the type directly without wrapping in a tuple".to_string()
819        } else {
820            "For >5 elements, use a struct with named fields".to_string()
821        };
822
823        let error = ParseError::new(
824            "Invalid tuple",
825            span,
826            format!("{}-element tuple not allowed", arity),
827        )
828        .with_parse_code("tuple_element_count")
829        .with_help(help);
830
831        self.errors.push(error);
832    }
833
834    fn error_duplicate_field_in_pattern(
835        &mut self,
836        field_name: &str,
837        first_span: Span,
838        second_span: Span,
839    ) {
840        let error = ParseError::new(
841            "Duplicate field",
842            first_span,
843            format!("first use of `{}`", field_name),
844        )
845        .with_span_label(second_span, "used again")
846        .with_parse_code("duplicate_field_in_pattern")
847        .with_help("Remove the duplicate binding");
848
849        self.errors.push(error);
850    }
851
852    fn error_duplicate_embed_parent(&mut self, first_span: Span, second_span: Span) {
853        let error = ParseError::new("Duplicate embed", first_span, "first use")
854            .with_span_label(second_span, "used again")
855            .with_parse_code("duplicate_embed_parent")
856            .with_help("Remove the duplicate parent");
857
858        self.errors.push(error);
859    }
860
861    fn error_impl_interface_embed(&mut self, keyword_span: Span) {
862        let error = ParseError::new(
863            "Interface embedding uses `embed`",
864            keyword_span,
865            "write `embed` here",
866        )
867        .with_parse_code("impl_interface_embed")
868        .with_help("Interfaces embed other interfaces with `embed`. Replace `impl` with `embed`");
869
870        self.errors.push(error);
871    }
872
873    fn error_duplicate_struct_field(&mut self, name: &str, first_span: Span, second_span: Span) {
874        let error = ParseError::new("Duplicate field", first_span, "first defined")
875            .with_span_label(second_span, "defined again")
876            .with_parse_code("duplicate_struct_field")
877            .with_help(format!("Remove the duplicate field `{}`", name));
878
879        self.errors.push(error);
880    }
881
882    fn error_duplicate_enum_variant(&mut self, name: &str, first_span: Span, second_span: Span) {
883        let error = ParseError::new("Duplicate variant", first_span, "first defined")
884            .with_span_label(second_span, "defined again")
885            .with_parse_code("duplicate_enum_variant")
886            .with_help(format!("Remove the duplicate variant `{}`", name));
887
888        self.errors.push(error);
889    }
890
891    fn error_duplicate_interface_method(
892        &mut self,
893        name: &str,
894        first_span: Span,
895        second_span: Span,
896    ) {
897        let error = ParseError::new("Duplicate method", first_span, "first defined")
898            .with_span_label(second_span, "defined again")
899            .with_parse_code("duplicate_interface_method")
900            .with_help(format!("Remove the duplicate method `{}`", name));
901
902        self.errors.push(error);
903    }
904
905    fn error_float_pattern_not_allowed(&mut self, span: Span, float_text: &str) {
906        let error = ParseError::new("Invalid pattern", span, "float literal not allowed here")
907            .with_parse_code("float_pattern")
908            .with_help(format!(
909                "Use a guard instead: `x if x == {} =>`",
910                float_text
911            ));
912
913        self.errors.push(error);
914    }
915
916    fn error_uppercase_binding(&mut self, span: Span) {
917        let error = ParseError::new("Invalid binding name", span, "uppercase not allowed here")
918            .with_parse_code("uppercase_binding")
919            .with_help("Lowercase the binding");
920
921        self.errors.push(error);
922    }
923
924    fn error_detached_doc_comment(&mut self, span: Span) {
925        let error = ParseError::new("Unattached doc comment", span, "is detached")
926            .with_parse_code("detached_doc_comment")
927            .with_help("Place the doc comment on the line immediately above a symbol definition");
928
929        self.errors.push(error);
930    }
931
932    fn error_misplaced_attribute(&mut self, span: Span) {
933        let error = ParseError::new(
934            "Attribute not supported on target",
935            span,
936            "not supported on target",
937        )
938        .with_parse_code("misplaced_attribute")
939        .with_help("Remove the attribute, or move it onto an enum, struct, or function");
940
941        self.errors.push(error);
942    }
943
944    fn error_interface_method_with_type_parameters(&mut self, span: Span, count: usize) {
945        let label = if count == 1 {
946            "type parameter not allowed"
947        } else {
948            "type parameters not allowed"
949        };
950        let error = ParseError::new("Invalid interface method", span, label)
951            .with_parse_code("interface_method_with_type_parameters")
952            .with_help(
953                "Interface methods cannot have type parameters, because Go interfaces do not support generic methods",
954            );
955
956        self.errors.push(error);
957    }
958
959    fn error_leading_zero(&mut self) {
960        let span = self.span_from_token(self.current_token());
961        let error = ParseError::new(
962            "Invalid number literal",
963            span,
964            "leading zero in integer literal",
965        )
966        .with_parse_code("number_leading_zero")
967        .with_help("Prefix with `0o` for octal (e.g. `0o644`) or remove the leading zero");
968        self.errors.push(error);
969    }
970
971    pub(crate) fn parse_integer_text(&mut self, text: &str) -> ast::Literal {
972        self.parse_integer_text_with(text, false)
973    }
974
975    pub(crate) fn parse_integer_text_with(
976        &mut self,
977        text: &str,
978        preserve_decimal_text: bool,
979    ) -> ast::Literal {
980        let clean = if text.contains('_') {
981            std::borrow::Cow::Owned(text.replace('_', ""))
982        } else {
983            std::borrow::Cow::Borrowed(text)
984        };
985
986        let (n, is_decimal) = if clean.starts_with("0x") || clean.starts_with("0X") {
987            let value = u64::from_str_radix(&clean[2..], 16).unwrap_or_else(|_| {
988                self.track_error(
989                    format!("hex literal '{text}' is too large"),
990                    "Maximum value is `0xFFFFFFFFFFFFFFFF`.",
991                );
992                0
993            });
994            (value, false)
995        } else if clean.starts_with("0o") || clean.starts_with("0O") {
996            let value = u64::from_str_radix(&clean[2..], 8).unwrap_or_else(|_| {
997                self.track_error(
998                    format!("octal literal '{text}' is too large"),
999                    "Maximum value is `0o1777777777777777777777`.",
1000                );
1001                0
1002            });
1003            (value, false)
1004        } else if clean.starts_with("0b") || clean.starts_with("0B") {
1005            let value = u64::from_str_radix(&clean[2..], 2).unwrap_or_else(|_| {
1006                self.track_error(
1007                    format!("binary literal '{text}' is too large"),
1008                    "Value must fit in 64 bits.",
1009                );
1010                0
1011            });
1012            (value, false)
1013        } else if clean.len() > 1 && clean.starts_with('0') {
1014            self.error_leading_zero();
1015            (clean.parse().unwrap_or(0), false)
1016        } else {
1017            let value = clean.parse().unwrap_or_else(|_| {
1018                self.track_error(
1019                    format!("integer literal '{text}' is too large"),
1020                    "Maximum value is `18446744073709551615`.",
1021                );
1022                0
1023            });
1024            (value, true)
1025        };
1026
1027        let original_text = if is_decimal && !preserve_decimal_text {
1028            None
1029        } else {
1030            Some(text.to_string())
1031        };
1032
1033        ast::Literal::Integer {
1034            value: n,
1035            text: original_text,
1036        }
1037    }
1038
1039    fn unexpected_token(&mut self, ctx: &str) -> ast::Expression {
1040        let token = self.current_token();
1041        let token_descriptor = if token.text.is_empty() {
1042            format!("{:?}", token.kind)
1043        } else {
1044            format!("`{}`", token.text)
1045        };
1046
1047        let span = ast::Span::new(self.file_id, token.byte_offset, token.byte_length);
1048
1049        let (label, error_code, help) = match ctx {
1050            "expr" => (
1051                format!("expected expression, found {}", token_descriptor),
1052                "expected_expression",
1053                "Check your syntax.",
1054            ),
1055            "pattern" => (
1056                format!("unexpected {} in pattern", token_descriptor),
1057                "invalid_pattern",
1058                "Patterns include literals, variables, and destructuring.",
1059            ),
1060            "literal" => (
1061                format!("expected literal, found {}", token_descriptor),
1062                "expected_literal",
1063                "Literals include numbers, strings, characters, and booleans.",
1064            ),
1065            "top_item" if token.text == "trait" => (
1066                format!("unexpected {}", token_descriptor),
1067                "trait_unsupported",
1068                "Lisette uses `interface` with Go-style structural typing. Types automatically satisfy interfaces if they have the required methods.",
1069            ),
1070            "top_item" if token.text == "use" => (
1071                "unexpected syntax for import".to_string(),
1072                "use_unsupported",
1073                "Use `import` instead of `use` for imports: `import \"module/path\"`",
1074            ),
1075            "top_item" if token.kind == Let => (
1076                "`let` is not allowed at the top level".to_string(),
1077                "top_level_let",
1078                "Use `const` for a primitive, or a function that returns the value e.g. `fn origin() -> Point { ... }` for a composite",
1079            ),
1080            "top_item" => (
1081                "expected declaration".to_string(),
1082                "expected_declaration",
1083                "At the top level of a file, Lisette expects `fn`, `struct`, `enum`, `interface`, `impl`, `const`, `import`, or `type`.",
1084            ),
1085            _ => (
1086                format!("unexpected {}", token_descriptor),
1087                "unexpected_token",
1088                "Check your syntax.",
1089            ),
1090        };
1091
1092        let error = ParseError::new("Syntax error", span, label)
1093            .with_parse_code(error_code)
1094            .with_help(help);
1095
1096        if !self.too_many_errors() {
1097            self.errors.push(error);
1098        }
1099
1100        self.resync_on_error();
1101
1102        ast::Expression::Unit {
1103            ty: Type::uninferred(),
1104            span,
1105        }
1106    }
1107}
1108
1109struct TokenStream<'source> {
1110    tokens: Vec<Token<'source>>,
1111    position: usize,
1112    last_index: usize,
1113}
1114
1115impl<'source> TokenStream<'source> {
1116    fn new(tokens: Vec<Token<'source>>) -> Self {
1117        debug_assert!(
1118            !tokens.is_empty(),
1119            "lexer must always produce at least an EOF token",
1120        );
1121        let last_index = tokens.len() - 1;
1122        Self {
1123            tokens,
1124            position: 0,
1125            last_index,
1126        }
1127    }
1128
1129    fn peek(&self) -> Token<'source> {
1130        self.tokens[self.position]
1131    }
1132
1133    fn peek_ahead(&self, n: usize) -> Token<'source> {
1134        let idx = self.position.saturating_add(n);
1135        let idx = if idx > self.last_index {
1136            self.last_index
1137        } else {
1138            idx
1139        };
1140        self.tokens[idx]
1141    }
1142
1143    fn consume(&mut self) -> Token<'source> {
1144        let token = self.tokens[self.position];
1145        if self.position < self.last_index {
1146            self.position += 1;
1147        }
1148        token
1149    }
1150}