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    pub file_comment: Option<std::string::String>,
38}
39
40impl ParseResult {
41    pub fn failed(&self) -> bool {
42        !self.errors.is_empty()
43    }
44}
45
46pub struct Parser<'source> {
47    stream: TokenStream<'source>,
48    previous_token: Token<'source>,
49    pending_right_angle: Option<u32>,
50    pub errors: Vec<ParseError>,
51    file_id: u32,
52    in_control_flow_header: bool,
53    source: &'source str,
54    depth: u32,
55    pub(crate) has_desugarables: bool,
56}
57
58impl<'source> Parser<'source> {
59    pub fn new(tokens: Vec<Token<'source>>, source: &'source str) -> Parser<'source> {
60        Self::with_file_id(tokens, source, 0)
61    }
62
63    pub fn lex_and_parse_file(source: &str, file_id: u32) -> ParseResult {
64        let lex_result = lex::Lexer::new(source, file_id).lex();
65
66        if lex_result.failed() {
67            return ParseResult {
68                ast: vec![],
69                errors: lex_result.errors,
70                has_desugarables: false,
71                file_comment: None,
72            };
73        }
74
75        Parser::with_file_id(lex_result.tokens, source, file_id).parse()
76    }
77
78    fn with_file_id(
79        tokens: Vec<Token<'source>>,
80        source: &'source str,
81        file_id: u32,
82    ) -> Parser<'source> {
83        let stream = TokenStream::new(tokens);
84        let first_token = stream.peek();
85
86        Parser {
87            stream,
88            previous_token: first_token,
89            pending_right_angle: None,
90            errors: Default::default(),
91            file_id,
92            in_control_flow_header: false,
93            source,
94            depth: 0,
95            has_desugarables: false,
96        }
97    }
98
99    pub fn parse(mut self) -> ParseResult {
100        let mut top_items = vec![];
101
102        let file_comment = self.collect_file_comments();
103        self.skip_comments();
104
105        while !self.at_eof() && !self.too_many_errors() {
106            let position = self.position();
107            let item = self.parse_top_item();
108            if !matches!(item, ast::Expression::Unit { .. }) {
109                top_items.push(item);
110            }
111            self.advance_if(Semicolon);
112            if self.position() == position {
113                self.next();
114            }
115        }
116
117        ParseResult {
118            ast: top_items,
119            errors: self.errors,
120            has_desugarables: self.has_desugarables,
121            file_comment,
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        if self.is(FileComment) {
317            self.error_misplaced_file_comment();
318        }
319    }
320
321    fn collect_file_comments(&mut self) -> Option<std::string::String> {
322        let mut docs = Vec::new();
323        let mut previous_end: Option<u32> = None;
324
325        while self.is(FileComment) {
326            let token = self.current_token();
327            match previous_end {
328                None if token.byte_offset != 0 => {
329                    self.error_misplaced_file_comment_at(self.span_from_token(token));
330                }
331                Some(end)
332                    if self.source[end as usize..token.byte_offset as usize]
333                        .bytes()
334                        .filter(|&byte| byte == b'\n')
335                        .count()
336                        > 1 =>
337                {
338                    self.error_split_file_comment(self.span_from_token(token));
339                }
340                _ => {}
341            }
342            if is_go_build_constraint(token.text) {
343                self.error_file_comment_build_constraint(self.span_from_token(token));
344            }
345            docs.push(token.text.to_string());
346            previous_end = Some(token.byte_offset + token.byte_length);
347            self.previous_token = token;
348            self.stream.consume();
349        }
350
351        if docs.is_empty() {
352            None
353        } else {
354            Some(docs.join("\n"))
355        }
356    }
357
358    fn collect_doc_comments(&mut self) -> Option<(std::string::String, ast::Span)> {
359        let mut docs = Vec::new();
360        let mut first_span: Option<ast::Span> = None;
361
362        while self.is(DocComment) {
363            let token = self.current_token();
364            if first_span.is_none() {
365                first_span = Some(self.span_from_token(token));
366            }
367            docs.push(token.text.to_string());
368            self.previous_token = token;
369            self.stream.consume();
370            self.skip_comments();
371        }
372
373        if docs.is_empty() {
374            None
375        } else {
376            Some((docs.join("\n"), first_span.unwrap()))
377        }
378    }
379
380    fn expect_comma_or(&mut self, closing: TokenKind) {
381        if self.is(Comma) || self.is(closing) || self.at_item_boundary() {
382            self.advance_if(Comma);
383            return;
384        }
385
386        self.track_error(
387            format!("expected `,` or {}", closing),
388            "Add a comma between elements.",
389        );
390
391        self.recover_to_comma_or(closing);
392    }
393
394    pub(super) fn recover_to_comma_or(&mut self, closing: TokenKind) {
395        while !self.at_eof() && !self.is(Comma) && !self.is(closing) && !self.at_item_boundary() {
396            self.next();
397        }
398
399        self.advance_if(Comma);
400    }
401
402    pub fn at_eof(&self) -> bool {
403        self.is(EOF)
404    }
405
406    fn at_range(&self) -> bool {
407        matches!(self.current_token().kind, DotDot | DotDotEqual)
408    }
409
410    fn advance_if(&mut self, token_kind: TokenKind) -> bool {
411        if self.is(token_kind) {
412            self.next();
413            return true;
414        }
415
416        false
417    }
418
419    fn is(&self, token_kind: TokenKind) -> bool {
420        self.current_token().kind == token_kind
421    }
422
423    fn is_not(&self, token_kind: TokenKind) -> bool {
424        if self.at_eof() {
425            return false;
426        }
427
428        self.current_token().kind != token_kind
429    }
430
431    fn ensure(&mut self, token_kind: TokenKind) {
432        if self.current_token().kind != token_kind {
433            self.track_ensure_error(token_kind);
434        }
435
436        if self.at_eof() {
437            return;
438        }
439
440        self.next();
441    }
442
443    fn ensure_progress(&mut self, start_position: usize, closing: TokenKind) {
444        if self.stream.position == start_position && self.is_not(closing) && !self.at_eof() {
445            self.next();
446        }
447    }
448
449    fn is_right_angle_like(&self) -> bool {
450        matches!(self.current_token().kind, RightAngleBracket | ShiftRight)
451    }
452
453    fn advance_if_right_angle(&mut self) -> bool {
454        let token = self.current_token();
455        match token.kind {
456            RightAngleBracket => {
457                self.next();
458                true
459            }
460            ShiftRight => {
461                self.previous_token = Token {
462                    kind: RightAngleBracket,
463                    text: ">",
464                    byte_offset: token.byte_offset,
465                    byte_length: 1,
466                };
467                self.stream.consume();
468                self.pending_right_angle = Some(token.byte_offset + 1);
469                self.skip_comments();
470                true
471            }
472            _ => false,
473        }
474    }
475
476    fn span_from_token(&self, token: Token<'source>) -> ast::Span {
477        ast::Span::new(self.file_id, token.byte_offset, token.byte_length)
478    }
479
480    fn span_from_tokens(&self, start_token: Token<'source>) -> ast::Span {
481        let end_byte_offset = self.previous_token.byte_offset + self.previous_token.byte_length;
482        let byte_length = end_byte_offset.saturating_sub(start_token.byte_offset);
483
484        ast::Span::new(self.file_id, start_token.byte_offset, byte_length)
485    }
486
487    fn span_from_offset(&self, start_byte_offset: u32) -> ast::Span {
488        let end_byte_offset = self.previous_token.byte_offset + self.previous_token.byte_length;
489        let byte_length = end_byte_offset.saturating_sub(start_byte_offset);
490
491        ast::Span::new(self.file_id, start_byte_offset, byte_length)
492    }
493
494    fn is_type_args_call(&self) -> bool {
495        let mut position = 1; // 0 is <
496        let mut depth = 1;
497
498        loop {
499            if position > MAX_LOOKAHEAD {
500                return false;
501            }
502            match self.stream.peek_ahead(position).kind {
503                LeftAngleBracket => depth += 1,
504                RightAngleBracket if depth == 1 => {
505                    let next = self.stream.peek_ahead(position + 1).kind;
506                    return next == LeftParen
507                        || (next == Dot
508                            && self.stream.peek_ahead(position + 2).kind == Identifier
509                            && self.stream.peek_ahead(position + 3).kind == LeftParen);
510                }
511                RightAngleBracket => depth -= 1,
512                ShiftRight if depth <= 2 => {
513                    let next = self.stream.peek_ahead(position + 1).kind;
514                    return next == LeftParen
515                        || (next == Dot
516                            && self.stream.peek_ahead(position + 2).kind == Identifier
517                            && self.stream.peek_ahead(position + 3).kind == LeftParen);
518                }
519                ShiftRight => depth -= 2,
520                LeftParen => {
521                    let mut paren_depth = 1;
522                    position += 1;
523                    while paren_depth > 0 {
524                        if position > MAX_LOOKAHEAD {
525                            return false;
526                        }
527                        match self.stream.peek_ahead(position).kind {
528                            LeftParen => paren_depth += 1,
529                            RightParen => paren_depth -= 1,
530                            EOF => return false,
531                            _ => {}
532                        }
533                        position += 1;
534                    }
535                    continue;
536                }
537                EOF | Plus | Minus | Star | Slash | Percent | EqualDouble | NotEqual
538                | AmpersandDouble | PipeDouble | Semicolon | LeftCurlyBrace | RightCurlyBrace
539                | LeftSquareBracket | RightSquareBracket => return false,
540                _ => {}
541            }
542            position += 1;
543        }
544    }
545
546    fn has_block_after_struct(&self) -> bool {
547        let mut depth = 1;
548        let mut i = 0;
549        while depth > 0 {
550            i += 1;
551            if i > MAX_LOOKAHEAD {
552                return false;
553            }
554            let token = self.stream.peek_ahead(i);
555            match token.kind {
556                LeftCurlyBrace => depth += 1,
557                RightCurlyBrace => depth -= 1,
558                EOF => return false,
559                _ => {}
560            }
561        }
562        let after = self.stream.peek_ahead(i + 1);
563        matches!(
564            after.kind,
565            LeftCurlyBrace
566                | RightParen
567                | EqualDouble
568                | NotEqual
569                | LeftAngleBracket
570                | RightAngleBracket
571                | LessThanOrEqual
572                | GreaterThanOrEqual
573                | AmpersandDouble
574                | PipeDouble
575                | Plus
576                | Minus
577                | Star
578                | Slash
579                | Percent
580        )
581    }
582
583    fn is_struct_instantiation(&self) -> bool {
584        if self.previous_token.kind != Identifier {
585            return false;
586        }
587
588        let is_uppercase = self
589            .previous_token
590            .text
591            .starts_with(|c: char| c.is_uppercase());
592        let first_ahead = self.stream.peek_ahead(1);
593
594        if first_ahead.kind == DotDot {
595            return true;
596        }
597
598        if first_ahead.kind == RightCurlyBrace {
599            if self.in_control_flow_header {
600                return is_uppercase && self.has_block_after_struct();
601            }
602            return is_uppercase;
603        }
604
605        if first_ahead.kind == Identifier {
606            let second_ahead = self.stream.peek_ahead(2);
607            return match second_ahead.kind {
608                Colon => self.stream.peek_ahead(3).kind != Colon,
609                Comma | RightCurlyBrace => {
610                    if self.in_control_flow_header {
611                        is_uppercase && self.has_block_after_struct()
612                    } else {
613                        is_uppercase
614                    }
615                }
616                _ => false,
617            };
618        }
619
620        false
621    }
622
623    fn enter_recursion(&mut self) -> bool {
624        if self.depth >= MAX_DEPTH {
625            let span = self.span_from_token(self.current_token());
626            self.track_error_at(span, "too deeply nested", "Reduce nesting depth");
627            return false;
628        }
629        self.depth += 1;
630        true
631    }
632
633    fn leave_recursion(&mut self) {
634        self.depth -= 1;
635    }
636
637    fn too_many_errors(&self) -> bool {
638        self.errors.len() >= MAX_ERRORS
639    }
640
641    fn position(&self) -> u32 {
642        self.current_token().byte_offset
643    }
644
645    fn at_sync_point(&self) -> bool {
646        matches!(
647            self.current_token().kind,
648            Semicolon
649                | RightCurlyBrace
650                | RightParen
651                | RightSquareBracket
652                | Comma
653                | Function
654                | Struct
655                | Enum
656                | Const
657                | Impl
658                | Interface
659                | Type
660                | Import
661        )
662    }
663
664    fn can_start_annotation(&self) -> bool {
665        matches!(
666            self.current_token().kind,
667            Identifier | Function | LeftParen | Integer
668        )
669    }
670
671    fn at_item_boundary(&self) -> bool {
672        matches!(
673            self.current_token().kind,
674            Let | Function | Struct | Enum | Impl | Interface | Type | Const | Import
675        )
676    }
677
678    fn at_match_arm_terminator(&self) -> bool {
679        self.at_eof() || self.is(Comma) || self.is(RightCurlyBrace) || self.at_item_boundary()
680    }
681
682    fn resync_on_error(&mut self) {
683        if !self.at_eof() {
684            self.next();
685        }
686
687        while !self.at_sync_point() && !self.at_eof() {
688            self.next();
689        }
690    }
691
692    fn track_error(
693        &mut self,
694        label: impl Into<std::string::String>,
695        help: impl Into<std::string::String>,
696    ) {
697        let current = self.current_token();
698        let span = ast::Span::new(self.file_id, current.byte_offset, current.byte_length);
699        self.track_error_at(span, label, help);
700    }
701
702    fn track_error_at(
703        &mut self,
704        span: ast::Span,
705        label: impl Into<std::string::String>,
706        help: impl Into<std::string::String>,
707    ) {
708        if self.too_many_errors() {
709            return;
710        }
711        let error = ParseError::new("Syntax error", span, label.into())
712            .with_parse_code("syntax_error")
713            .with_help(help.into());
714
715        self.errors.push(error);
716    }
717
718    fn error_angle_brackets_for_generics(
719        &mut self,
720        span: ast::Span,
721        help: impl Into<std::string::String>,
722    ) {
723        if self.too_many_errors() {
724            return;
725        }
726        let error = ParseError::new("Syntax error", span, "use `<...>` for type args")
727            .with_parse_code("angle_brackets_for_generics")
728            .with_help(help.into());
729
730        self.errors.push(error);
731    }
732
733    fn error_var_initializer(&mut self, span: ast::Span) {
734        if self.too_many_errors() {
735            return;
736        }
737        let error = ParseError::new("Syntax error", span, "not allowed")
738            .with_parse_code("var_not_allowed")
739            .with_help(
740                "Use `const` for a primitive, or a function that returns the value e.g. `fn origin() -> Point { ... }` for a composite",
741            );
742
743        self.errors.push(error);
744    }
745
746    fn error_import_alias_after_path(&mut self, span: ast::Span, alias: &str, path: &str) {
747        if self.too_many_errors() {
748            return;
749        }
750        let error = ParseError::new("Syntax error", span, "import alias goes before the path")
751            .with_parse_code("import_alias_position")
752            .with_help(format!(
753                "Use Go-style alias syntax: `import {alias} \"{path}\"`"
754            ));
755
756        self.errors.push(error);
757    }
758
759    fn error_bare_multi_return(&mut self, span: ast::Span, suggestion: &str) {
760        if self.too_many_errors() {
761            return;
762        }
763        let error = ParseError::new(
764            "Multiple return values must be a tuple",
765            span,
766            "wrap these values in parentheses",
767        )
768        .with_parse_code("bare_multi_value_return")
769        .with_help(format!(
770            "To return multiple values, use a tuple: `{suggestion}`"
771        ));
772
773        self.errors.push(error);
774    }
775
776    fn error_match_arm_missing_comma(&mut self, span: ast::Span) {
777        if self.too_many_errors() {
778            return;
779        }
780        let error = ParseError::new("Syntax error", span, "missing comma after match arm")
781            .with_parse_code("match_arm_missing_comma")
782            .with_help("Match arms must be separated by commas, even when the body is a block.");
783
784        self.errors.push(error);
785    }
786
787    pub(super) fn error_map_literal_not_supported(&mut self, span: ast::Span) {
788        if self.too_many_errors() {
789            return;
790        }
791        let error = ParseError::new("Invalid `Map` initialization", span, "invalid syntax")
792            .with_parse_code("invalid_map_initialization")
793            .with_help("To initialize a `Map`, use `Map.new<K, V>()` then `m[key] = value`");
794
795        self.errors.push(error);
796    }
797
798    pub(super) fn error_missing_initializer(&mut self, span: ast::Span) {
799        if self.too_many_errors() {
800            return;
801        }
802        let error = ParseError::new(
803            "Missing initializer",
804            span,
805            "annotated binding needs a value",
806        )
807        .with_parse_code("missing_initializer")
808        .with_help("Bindings must be initialized");
809
810        self.errors.push(error);
811    }
812
813    fn track_ensure_error(&mut self, expected_token: TokenKind) {
814        if self.too_many_errors() {
815            return;
816        }
817        let current = self.current_token();
818
819        let error_code = match expected_token {
820            Semicolon => "missing_semicolon",
821            RightCurlyBrace => "unclosed_block",
822            _ => "unexpected_token",
823        };
824
825        let span = ast::Span::new(self.file_id, current.byte_offset, current.byte_length);
826        let error = ParseError::new("Syntax error", span, format!("expected {}", expected_token))
827            .with_parse_code(error_code);
828
829        self.errors.push(error);
830    }
831
832    fn close_brace_span(&mut self, start: Token<'source>, error_anchor: Token<'source>) -> Span {
833        if self.is(RightCurlyBrace) {
834            let close = self.current_token();
835            self.next();
836            let end = close.byte_offset + close.byte_length;
837            Span::new(
838                self.file_id,
839                start.byte_offset,
840                end.saturating_sub(start.byte_offset),
841            )
842        } else {
843            self.error_unclosed_block(&error_anchor);
844            self.span_from_tokens(start)
845        }
846    }
847
848    fn error_unclosed_block(&mut self, open_brace: &Token) {
849        let span = ast::Span::new(self.file_id, open_brace.byte_offset, open_brace.byte_length);
850        let error = ParseError::new("Unclosed block", span, "opening brace here")
851            .with_parse_code("unclosed_block")
852            .with_help("Add a closing `}`");
853
854        self.errors.push(error);
855    }
856
857    fn error_tuple_arity(&mut self, arity: usize, span: Span) {
858        let help = if arity == 0 {
859            "Use `()` for unit type".to_string()
860        } else if arity == 1 {
861            "Use the type directly without wrapping in a tuple".to_string()
862        } else {
863            "For >5 elements, use a struct with named fields".to_string()
864        };
865
866        let error = ParseError::new(
867            "Invalid tuple",
868            span,
869            format!("{}-element tuple not allowed", arity),
870        )
871        .with_parse_code("tuple_element_count")
872        .with_help(help);
873
874        self.errors.push(error);
875    }
876
877    fn error_duplicate_field_in_pattern(
878        &mut self,
879        field_name: &str,
880        first_span: Span,
881        second_span: Span,
882    ) {
883        let error = ParseError::new(
884            "Duplicate field",
885            first_span,
886            format!("first use of `{}`", field_name),
887        )
888        .with_span_label(second_span, "used again")
889        .with_parse_code("duplicate_field_in_pattern")
890        .with_help("Remove the duplicate binding");
891
892        self.errors.push(error);
893    }
894
895    fn error_duplicate_embed_parent(&mut self, first_span: Span, second_span: Span) {
896        let error = ParseError::new("Duplicate embed", first_span, "first use")
897            .with_span_label(second_span, "used again")
898            .with_parse_code("duplicate_embed_parent")
899            .with_help("Remove the duplicate parent");
900
901        self.errors.push(error);
902    }
903
904    fn error_impl_interface_embed(&mut self, keyword_span: Span) {
905        let error = ParseError::new(
906            "Interface embedding uses `embed`",
907            keyword_span,
908            "write `embed` here",
909        )
910        .with_parse_code("impl_interface_embed")
911        .with_help("Interfaces embed other interfaces with `embed`. Replace `impl` with `embed`");
912
913        self.errors.push(error);
914    }
915
916    fn error_duplicate_struct_field(&mut self, name: &str, first_span: Span, second_span: Span) {
917        let error = ParseError::new("Duplicate field", first_span, "first defined")
918            .with_span_label(second_span, "defined again")
919            .with_parse_code("duplicate_struct_field")
920            .with_help(format!("Remove the duplicate field `{}`", name));
921
922        self.errors.push(error);
923    }
924
925    fn error_duplicate_enum_variant(&mut self, name: &str, first_span: Span, second_span: Span) {
926        let error = ParseError::new("Duplicate variant", first_span, "first defined")
927            .with_span_label(second_span, "defined again")
928            .with_parse_code("duplicate_enum_variant")
929            .with_help(format!("Remove the duplicate variant `{}`", name));
930
931        self.errors.push(error);
932    }
933
934    fn error_duplicate_interface_method(
935        &mut self,
936        name: &str,
937        first_span: Span,
938        second_span: Span,
939    ) {
940        let error = ParseError::new("Duplicate method", first_span, "first defined")
941            .with_span_label(second_span, "defined again")
942            .with_parse_code("duplicate_interface_method")
943            .with_help(format!("Remove the duplicate method `{}`", name));
944
945        self.errors.push(error);
946    }
947
948    fn error_float_pattern_not_allowed(&mut self, span: Span, float_text: &str) {
949        let error = ParseError::new("Invalid pattern", span, "float literal not allowed here")
950            .with_parse_code("float_pattern")
951            .with_help(format!(
952                "Use a guard instead: `x if x == {} =>`",
953                float_text
954            ));
955
956        self.errors.push(error);
957    }
958
959    fn error_uppercase_binding(&mut self, span: Span) {
960        let error = ParseError::new("Invalid binding name", span, "uppercase not allowed here")
961            .with_parse_code("uppercase_binding")
962            .with_help("Lowercase the binding");
963
964        self.errors.push(error);
965    }
966
967    fn error_detached_doc_comment(&mut self, span: Span) {
968        let error = ParseError::new("Unattached doc comment", span, "is detached")
969            .with_parse_code("detached_doc_comment")
970            .with_help(
971                "Place doc comments `///` on the line above a symbol definition and file comments `//!` at the very top of the file",
972            );
973
974        self.errors.push(error);
975    }
976
977    fn error_split_file_comment(&mut self, span: Span) {
978        let error = ParseError::new("Split file comment", span, "separated from the block above")
979            .with_parse_code("split_file_comment")
980            .with_help(
981                "Remove the blank line, or write a bare `//!` line to keep a visible gap in the emitted header",
982            );
983
984        self.errors.push(error);
985    }
986
987    fn error_file_comment_build_constraint(&mut self, span: Span) {
988        let error = ParseError::new(
989            "Invalid file comment",
990            span,
991            "would become a Go build constraint",
992        )
993        .with_parse_code("file_comment_build_constraint")
994        .with_help(
995            "Reword the line so it does not start with `+build`. Emitted as a Go comment it would act as a legacy build constraint and exclude the generated file from builds",
996        );
997
998        self.errors.push(error);
999    }
1000
1001    fn error_misplaced_file_comment(&mut self) {
1002        let first = self.current_token();
1003        let mut last = first;
1004
1005        while self.is(FileComment) {
1006            last = self.current_token();
1007            self.previous_token = last;
1008            self.stream.consume();
1009            while self.is(Comment) {
1010                self.previous_token = self.current_token();
1011                self.stream.consume();
1012            }
1013        }
1014
1015        let length = last.byte_offset + last.byte_length - first.byte_offset;
1016        self.error_misplaced_file_comment_at(ast::Span::new(
1017            self.file_id,
1018            first.byte_offset,
1019            length,
1020        ));
1021    }
1022
1023    fn error_misplaced_file_comment_at(&mut self, span: Span) {
1024        let error = ParseError::new("Misplaced file comment", span, "not allowed here")
1025            .with_parse_code("misplaced_file_comment")
1026            .with_help(
1027                "Move this file comment to the very top of the file to document it, or use `///` to document the symbol below",
1028            );
1029
1030        self.errors.push(error);
1031    }
1032
1033    fn error_misplaced_attribute(&mut self, span: Span) {
1034        let error = ParseError::new(
1035            "Attribute not supported on target",
1036            span,
1037            "not supported on target",
1038        )
1039        .with_parse_code("misplaced_attribute")
1040        .with_help("Remove the attribute, or move it onto an enum, struct, or function");
1041
1042        self.errors.push(error);
1043    }
1044
1045    fn error_interface_method_with_type_parameters(&mut self, span: Span, count: usize) {
1046        let label = if count == 1 {
1047            "type parameter not allowed"
1048        } else {
1049            "type parameters not allowed"
1050        };
1051        let error = ParseError::new("Invalid interface method", span, label)
1052            .with_parse_code("interface_method_with_type_parameters")
1053            .with_help(
1054                "Interface methods cannot have type parameters, because Go interfaces do not support generic methods",
1055            );
1056
1057        self.errors.push(error);
1058    }
1059
1060    fn error_leading_zero(&mut self) {
1061        let span = self.span_from_token(self.current_token());
1062        let error = ParseError::new(
1063            "Invalid number literal",
1064            span,
1065            "leading zero in integer literal",
1066        )
1067        .with_parse_code("number_leading_zero")
1068        .with_help("Prefix with `0o` for octal (e.g. `0o644`) or remove the leading zero");
1069        self.errors.push(error);
1070    }
1071
1072    pub(crate) fn parse_integer_text(&mut self, text: &str) -> ast::Literal {
1073        self.parse_integer_text_with(text, false)
1074    }
1075
1076    pub(crate) fn parse_integer_text_with(
1077        &mut self,
1078        text: &str,
1079        preserve_decimal_text: bool,
1080    ) -> ast::Literal {
1081        let clean = if text.contains('_') {
1082            std::borrow::Cow::Owned(text.replace('_', ""))
1083        } else {
1084            std::borrow::Cow::Borrowed(text)
1085        };
1086
1087        let (n, is_decimal) = if clean.starts_with("0x") || clean.starts_with("0X") {
1088            let value = u64::from_str_radix(&clean[2..], 16).unwrap_or_else(|_| {
1089                self.track_error(
1090                    format!("hex literal '{text}' is too large"),
1091                    "Maximum value is `0xFFFFFFFFFFFFFFFF`.",
1092                );
1093                0
1094            });
1095            (value, false)
1096        } else if clean.starts_with("0o") || clean.starts_with("0O") {
1097            let value = u64::from_str_radix(&clean[2..], 8).unwrap_or_else(|_| {
1098                self.track_error(
1099                    format!("octal literal '{text}' is too large"),
1100                    "Maximum value is `0o1777777777777777777777`.",
1101                );
1102                0
1103            });
1104            (value, false)
1105        } else if clean.starts_with("0b") || clean.starts_with("0B") {
1106            let value = u64::from_str_radix(&clean[2..], 2).unwrap_or_else(|_| {
1107                self.track_error(
1108                    format!("binary literal '{text}' is too large"),
1109                    "Value must fit in 64 bits.",
1110                );
1111                0
1112            });
1113            (value, false)
1114        } else if clean.len() > 1 && clean.starts_with('0') {
1115            self.error_leading_zero();
1116            (clean.parse().unwrap_or(0), false)
1117        } else {
1118            let value = clean.parse().unwrap_or_else(|_| {
1119                self.track_error(
1120                    format!("integer literal '{text}' is too large"),
1121                    "Maximum value is `18446744073709551615`.",
1122                );
1123                0
1124            });
1125            (value, true)
1126        };
1127
1128        let original_text = if is_decimal && !preserve_decimal_text {
1129            None
1130        } else {
1131            Some(text.to_string())
1132        };
1133
1134        ast::Literal::Integer {
1135            value: n,
1136            text: original_text,
1137        }
1138    }
1139
1140    fn unexpected_token(&mut self, ctx: &str) -> ast::Expression {
1141        let token = self.current_token();
1142        let token_descriptor = if token.text.is_empty() {
1143            format!("{:?}", token.kind)
1144        } else {
1145            format!("`{}`", token.text)
1146        };
1147
1148        let span = ast::Span::new(self.file_id, token.byte_offset, token.byte_length);
1149
1150        let (label, error_code, help) = match ctx {
1151            "expr" => (
1152                format!("expected expression, found {}", token_descriptor),
1153                "expected_expression",
1154                "Check your syntax.",
1155            ),
1156            "pattern" => (
1157                format!("unexpected {} in pattern", token_descriptor),
1158                "invalid_pattern",
1159                "Patterns include literals, variables, and destructuring.",
1160            ),
1161            "literal" => (
1162                format!("expected literal, found {}", token_descriptor),
1163                "expected_literal",
1164                "Literals include numbers, strings, characters, and booleans.",
1165            ),
1166            "top_item" if token.text == "trait" => (
1167                format!("unexpected {}", token_descriptor),
1168                "trait_unsupported",
1169                "Lisette uses `interface` with Go-style structural typing. Types automatically satisfy interfaces if they have the required methods.",
1170            ),
1171            "top_item" if token.text == "use" => (
1172                "unexpected syntax for import".to_string(),
1173                "use_unsupported",
1174                "Use `import` instead of `use` for imports: `import \"module/path\"`",
1175            ),
1176            "top_item" if token.kind == Let => (
1177                "`let` is not allowed at the top level".to_string(),
1178                "top_level_let",
1179                "Use `const` for a primitive, or a function that returns the value e.g. `fn origin() -> Point { ... }` for a composite",
1180            ),
1181            "top_item" => (
1182                "expected declaration".to_string(),
1183                "expected_declaration",
1184                "At the top level of a file, Lisette expects `fn`, `struct`, `enum`, `interface`, `impl`, `const`, `import`, or `type`.",
1185            ),
1186            _ => (
1187                format!("unexpected {}", token_descriptor),
1188                "unexpected_token",
1189                "Check your syntax.",
1190            ),
1191        };
1192
1193        let error = ParseError::new("Syntax error", span, label)
1194            .with_parse_code(error_code)
1195            .with_help(help);
1196
1197        if !self.too_many_errors() {
1198            self.errors.push(error);
1199        }
1200
1201        self.resync_on_error();
1202
1203        ast::Expression::Unit {
1204            ty: Type::uninferred(),
1205            span,
1206        }
1207    }
1208}
1209
1210fn is_go_build_constraint(text: &str) -> bool {
1211    text.split_whitespace().next() == Some("+build")
1212}
1213
1214struct TokenStream<'source> {
1215    tokens: Vec<Token<'source>>,
1216    position: usize,
1217    last_index: usize,
1218}
1219
1220impl<'source> TokenStream<'source> {
1221    fn new(tokens: Vec<Token<'source>>) -> Self {
1222        debug_assert!(
1223            !tokens.is_empty(),
1224            "lexer must always produce at least an EOF token",
1225        );
1226        let last_index = tokens.len() - 1;
1227        Self {
1228            tokens,
1229            position: 0,
1230            last_index,
1231        }
1232    }
1233
1234    fn peek(&self) -> Token<'source> {
1235        self.tokens[self.position]
1236    }
1237
1238    fn peek_ahead(&self, n: usize) -> Token<'source> {
1239        let idx = self.position.saturating_add(n);
1240        let idx = if idx > self.last_index {
1241            self.last_index
1242        } else {
1243            idx
1244        };
1245        self.tokens[idx]
1246    }
1247
1248    fn consume(&mut self) -> Token<'source> {
1249        let token = self.tokens[self.position];
1250        if self.position < self.last_index {
1251            self.position += 1;
1252        }
1253        token
1254    }
1255}
1256
1257#[cfg(test)]
1258mod file_comment_tests {
1259    use crate::build_ast;
1260
1261    fn file_comment(source: &str) -> Option<std::string::String> {
1262        let result = build_ast(source, 0);
1263        assert!(
1264            result.errors.is_empty(),
1265            "unexpected errors: {:?}",
1266            result.errors
1267        );
1268        result.file_comment
1269    }
1270
1271    #[test]
1272    fn consecutive_lines_join_with_newlines() {
1273        assert_eq!(
1274            file_comment("//! a\n//! b\nfn f() {}").as_deref(),
1275            Some("a\nb")
1276        );
1277    }
1278
1279    #[test]
1280    fn bare_line_contributes_empty_line() {
1281        assert_eq!(
1282            file_comment("//! a\n//!\n//! b\nfn f() {}").as_deref(),
1283            Some("a\n\nb")
1284        );
1285    }
1286
1287    #[test]
1288    fn blank_line_between_runs_is_an_error() {
1289        for source in [
1290            "//! a\n\n//! b\n\nfn f() {}",
1291            "//! a\r\n\r\n//! b\r\n\r\nfn f() {}",
1292            "//! a\n//!\n\n//! b\nfn f() {}",
1293        ] {
1294            let result = build_ast(source, 0);
1295            let codes: Vec<_> = result.errors.iter().map(|e| e.code.as_str()).collect();
1296            assert_eq!(
1297                codes,
1298                ["parse.split_file_comment"],
1299                "for source: {source:?}"
1300            );
1301        }
1302    }
1303
1304    #[test]
1305    fn anything_before_the_block_is_rejected() {
1306        for source in ["\n//! a\nfn f() {}", " //! a\nfn f() {}"] {
1307            let result = build_ast(source, 0);
1308            let codes: Vec<_> = result.errors.iter().map(|e| e.code.as_str()).collect();
1309            assert_eq!(
1310                codes,
1311                ["parse.misplaced_file_comment"],
1312                "for source: {source:?}"
1313            );
1314        }
1315    }
1316
1317    #[test]
1318    fn blank_lines_after_the_block_are_allowed() {
1319        assert_eq!(
1320            file_comment("//! a\n//! b\n\n\nfn f() {}").as_deref(),
1321            Some("a\nb")
1322        );
1323    }
1324
1325    #[test]
1326    fn leading_comment_makes_the_header_misplaced() {
1327        let result = build_ast("// leading\n//! too late\nfn f() {}", 0);
1328        let codes: Vec<_> = result.errors.iter().map(|e| e.code.as_str()).collect();
1329        assert_eq!(codes, ["parse.misplaced_file_comment"]);
1330    }
1331
1332    #[test]
1333    fn interleaved_comment_ends_the_block() {
1334        let result = build_ast("//! a\n// note\n//! b\nfn f() {}", 0);
1335        let codes: Vec<_> = result.errors.iter().map(|e| e.code.as_str()).collect();
1336        assert_eq!(codes, ["parse.misplaced_file_comment"]);
1337    }
1338
1339    #[test]
1340    fn comment_after_the_block_is_allowed() {
1341        assert_eq!(
1342            file_comment("//! a\n\n// section note\nfn f() {}").as_deref(),
1343            Some("a")
1344        );
1345    }
1346
1347    #[test]
1348    fn file_without_header_has_no_file_comment() {
1349        assert_eq!(file_comment("fn f() {}"), None);
1350    }
1351
1352    #[test]
1353    fn header_without_items_is_valid() {
1354        assert_eq!(
1355            file_comment("//! header only").as_deref(),
1356            Some("header only")
1357        );
1358    }
1359
1360    #[test]
1361    fn header_before_doc_commented_item() {
1362        let result = build_ast("//! header\n/// item doc\nfn f() {}", 0);
1363        assert!(result.errors.is_empty(), "{:?}", result.errors);
1364        assert_eq!(result.file_comment.as_deref(), Some("header"));
1365    }
1366
1367    #[test]
1368    fn misplaced_file_comment_reports_one_error_per_run() {
1369        let result = build_ast("fn f() {}\n//! a\n//! b\nfn g() {}", 0);
1370        let codes: Vec<_> = result.errors.iter().map(|e| e.code.as_str()).collect();
1371        assert_eq!(codes, ["parse.misplaced_file_comment"]);
1372    }
1373
1374    #[test]
1375    fn build_constraint_lines_are_rejected() {
1376        for source in [
1377            "//!+build ignore\nfn f() {}",
1378            "//! +build ignore\nfn f() {}",
1379            "//!  \t+build linux\nfn f() {}",
1380            "//! +build\nfn f() {}",
1381            "//! +build ignore\r\nfn f() {}",
1382            "//! +build\r\nfn f() {}",
1383            "//!\u{00A0}+build ignore\nfn f() {}",
1384            "//! +build\u{00A0}ignore\nfn f() {}",
1385            "//! +build\u{3000}ignore\nfn f() {}",
1386        ] {
1387            let result = build_ast(source, 0);
1388            let codes: Vec<_> = result.errors.iter().map(|e| e.code.as_str()).collect();
1389            assert_eq!(
1390                codes,
1391                ["parse.file_comment_build_constraint"],
1392                "for source: {source:?}"
1393            );
1394        }
1395    }
1396
1397    #[test]
1398    fn build_constraint_lookalikes_are_allowed() {
1399        for source in [
1400            "//! +buildx tag\nfn f() {}",
1401            "//! use +build wisely\nfn f() {}",
1402            "//! +builder pattern\nfn f() {}",
1403        ] {
1404            let result = build_ast(source, 0);
1405            assert!(result.errors.is_empty(), "for source: {source:?}");
1406        }
1407    }
1408}