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