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;
7use std::ops::{Deref, DerefMut};
8
9pub(crate) const MAX_TUPLE_ARITY: usize = 5;
10pub const TUPLE_FIELDS: &[&str] = &["First", "Second", "Third", "Fourth", "Fifth"];
11const MAX_DEPTH: u32 = 64;
12const MAX_ERRORS: usize = 50;
13const MAX_LOOKAHEAD: usize = 256;
14
15#[derive(Clone, Copy, PartialEq, Eq)]
16pub(crate) enum ParamMode {
17    Strict,
18    TestFunction,
19}
20
21mod annotations;
22mod control_flow;
23mod definitions;
24mod directives;
25mod error;
26mod expressions;
27mod identifiers;
28mod patterns;
29mod pratt;
30mod strings;
31
32pub use error::ParseError;
33
34pub struct ParseResult {
35    pub ast: Vec<ast::Expression>,
36    pub errors: Vec<ParseError>,
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    errors: Vec<ParseError>,
49    file_id: u32,
50    source: &'source str,
51    depth: u32,
52}
53
54/// A recursion frame owns the parser depth it opened and restores the previous
55/// depth even when parsing exits early or panics.
56struct RecursionScope<'parser, 'source> {
57    parser: &'parser mut Parser<'source>,
58    previous_depth: u32,
59}
60
61impl<'parser, 'source> Deref for RecursionScope<'parser, 'source> {
62    type Target = Parser<'source>;
63
64    fn deref(&self) -> &Self::Target {
65        self.parser
66    }
67}
68
69impl<'parser, 'source> DerefMut for RecursionScope<'parser, 'source> {
70    fn deref_mut(&mut self) -> &mut Self::Target {
71        self.parser
72    }
73}
74
75impl Drop for RecursionScope<'_, '_> {
76    fn drop(&mut self) {
77        self.parser.depth = self.previous_depth;
78    }
79}
80
81impl<'source> Parser<'source> {
82    pub fn new(tokens: Vec<Token<'source>>, source: &'source str) -> Parser<'source> {
83        Self::with_file_id(tokens, source, 0)
84    }
85
86    pub fn lex_and_parse_file(source: &str, file_id: u32) -> ParseResult {
87        let lex_result = lex::Lexer::new(source, file_id).lex();
88
89        if lex_result.failed() {
90            return ParseResult {
91                ast: vec![],
92                errors: lex_result.errors,
93                file_comment: None,
94            };
95        }
96
97        Parser::with_file_id(lex_result.tokens, source, file_id).parse()
98    }
99
100    fn with_file_id(
101        tokens: Vec<Token<'source>>,
102        source: &'source str,
103        file_id: u32,
104    ) -> Parser<'source> {
105        let stream = TokenStream::new(tokens);
106
107        Parser {
108            stream,
109            errors: Default::default(),
110            file_id,
111            source,
112            depth: 0,
113        }
114    }
115
116    pub fn parse(mut self) -> ParseResult {
117        let mut top_items = vec![];
118
119        let file_comment = self.collect_file_comments();
120        self.skip_comments();
121
122        while !self.at_eof() && !self.too_many_errors() {
123            let position = self.position();
124            let item = self.parse_top_item();
125            if !matches!(item, ast::Expression::Unit { .. }) {
126                top_items.push(item);
127            }
128            self.advance_if(Semicolon);
129            if self.position() == position {
130                self.next();
131            }
132        }
133
134        ParseResult {
135            ast: top_items,
136            errors: self.errors,
137            file_comment,
138        }
139    }
140
141    fn parse_top_item(&mut self) -> ast::Expression {
142        let doc_with_span = self.collect_doc_comments();
143
144        let attributes = self.parse_attributes();
145
146        let pub_token = if self.is(Pub) {
147            Some(self.current_token())
148        } else {
149            None
150        };
151        let is_public = pub_token.is_some();
152        if is_public {
153            self.next();
154        }
155
156        if is_public && self.is(Impl) {
157            let token = pub_token.unwrap();
158            let span = ast::Span::new(self.file_id, token.byte_offset, token.byte_length);
159            let error = ParseError::new("Misplaced `pub`", span, "not allowed here")
160                .with_parse_code("syntax_error")
161                .with_help("Place `pub` on individual methods inside the `impl` block instead");
162            self.errors.push(error);
163        }
164
165        let is_documentable = matches!(
166            self.current_token().kind,
167            Enum | Struct | Interface | Function | Const | Var | Type
168        );
169
170        if let Some((_, ref span)) = doc_with_span
171            && !is_documentable
172        {
173            self.error_detached_doc_comment(*span);
174        }
175
176        let doc = doc_with_span.map(|(text, _)| text);
177
178        if !matches!(self.current_token().kind, Enum | Struct | Function | Type)
179            && let Some(attribute) = attributes.first()
180        {
181            self.error_misplaced_attribute(attribute.span);
182        }
183
184        let expression = match self.current_token().kind {
185            Enum => self.parse_enum_definition(doc, attributes),
186            Struct => self.parse_struct_definition(doc, attributes),
187            Interface => self.parse_interface_definition(doc),
188            Function => {
189                // Only a top-level `#[test]` declaration may write a bare handle parameter.
190                let mode = if has_test_attribute(&attributes) {
191                    ParamMode::TestFunction
192                } else {
193                    ParamMode::Strict
194                };
195                self.parse_function(doc, attributes, mode)
196            }
197            Impl => self.parse_impl_block(),
198            Const => self.parse_const_definition(doc),
199            Var => self.parse_var_declaration(doc),
200            Import => self.parse_import(),
201            Type => self.parse_type_alias_with_doc(doc, attributes),
202            Comment => {
203                let start = self.current_token();
204                self.skip_comments();
205                ast::Expression::Unit {
206                    ty: Type::uninferred(),
207                    span: self.span_from_tokens(start),
208                }
209            }
210            _ => self.unexpected_token("top_item"),
211        };
212
213        if is_public {
214            return expression.set_public();
215        }
216
217        expression
218    }
219
220    fn parse_block_item(&mut self) -> ast::Expression {
221        match self.current_token().kind {
222            Enum => {
223                self.track_error(
224                    "misplaced",
225                    "Move this enum definition to the top level of the file.",
226                );
227                self.parse_enum_definition(None, vec![])
228            }
229            Struct => {
230                self.track_error(
231                    "misplaced",
232                    "Move this struct definition to the top level of the file.",
233                );
234                self.parse_struct_definition(None, vec![])
235            }
236            Type => {
237                self.track_error(
238                    "misplaced",
239                    "Move this type alias to the top level of the file.",
240                );
241                self.parse_type_alias_with_doc(None, vec![])
242            }
243            Import => {
244                self.track_error(
245                    "misplaced",
246                    "Move this import to the top level of the file.",
247                );
248                self.parse_import()
249            }
250            Impl => {
251                self.track_error(
252                    "misplaced",
253                    "Move this `impl` block to the top level of the file.",
254                );
255                self.parse_impl_block()
256            }
257            Interface => {
258                self.track_error(
259                    "misplaced",
260                    "Move this interface definition to the top level of the file.",
261                );
262                self.parse_interface_definition(None)
263            }
264            Function => self.parse_function(None, vec![], ParamMode::Strict),
265            Const => self.parse_const_definition(None),
266
267            Hash => {
268                let attributes = self.parse_attributes();
269                if let Some(attribute) = attributes.first() {
270                    self.error_misplaced_attribute(attribute.span);
271                }
272                if self.is(RightCurlyBrace) || self.at_eof() {
273                    ast::Expression::Unit {
274                        ty: Type::uninferred(),
275                        span: self.span_from_token(self.current_token()),
276                    }
277                } else {
278                    self.parse_block_item()
279                }
280            }
281
282            Let => self.parse_let(),
283            Return => self.parse_return(true),
284            For => self.parse_for(),
285            While => self.parse_while(),
286            Loop => self.parse_loop(),
287            Break => self.parse_break(),
288            Continue => self.parse_continue(),
289            Defer => self.parse_defer(),
290            Assert => self.parse_assert(),
291            Directive => self.parse_directive(),
292            _ => self.parse_assignment(),
293        }
294    }
295
296    fn current_token(&self) -> Token<'source> {
297        self.stream.peek()
298    }
299
300    fn newline_before_current(&self) -> bool {
301        let previous = self.stream.previous();
302        let prev_end = (previous.byte_offset + previous.byte_length) as usize;
303        let curr_start = self.current_token().byte_offset as usize;
304        if prev_end <= curr_start && curr_start <= self.source.len() {
305            return self.source[prev_end..curr_start].contains('\n');
306        }
307        false
308    }
309
310    fn next(&mut self) {
311        self.stream.consume();
312        self.skip_comments();
313    }
314
315    fn skip_comments(&mut self) {
316        while self.is(Comment) {
317            self.stream.consume();
318        }
319        if self.is(FileComment) {
320            self.error_misplaced_file_comment();
321        }
322    }
323
324    fn collect_file_comments(&mut self) -> Option<std::string::String> {
325        let mut docs = Vec::new();
326        let mut previous_end: Option<u32> = None;
327
328        while self.is(FileComment) {
329            let token = self.current_token();
330            match previous_end {
331                None if token.byte_offset != 0 => {
332                    self.error_misplaced_file_comment_at(self.span_from_token(token));
333                }
334                Some(end)
335                    if self.source[end as usize..token.byte_offset as usize]
336                        .bytes()
337                        .filter(|&byte| byte == b'\n')
338                        .count()
339                        > 1 =>
340                {
341                    self.error_split_file_comment(self.span_from_token(token));
342                }
343                _ => {}
344            }
345            if is_go_build_constraint(token.text) {
346                self.error_file_comment_build_constraint(self.span_from_token(token));
347            }
348            docs.push(token.text.to_string());
349            previous_end = Some(token.byte_offset + token.byte_length);
350            self.stream.consume();
351        }
352
353        if docs.is_empty() {
354            None
355        } else {
356            Some(docs.join("\n"))
357        }
358    }
359
360    fn collect_doc_comments(&mut self) -> Option<(std::string::String, ast::Span)> {
361        let mut docs = Vec::new();
362        let mut first_span: Option<ast::Span> = None;
363
364        while self.is(DocComment) {
365            let token = self.current_token();
366            if first_span.is_none() {
367                first_span = Some(self.span_from_token(token));
368            }
369            docs.push(token.text.to_string());
370            self.stream.consume();
371            self.skip_comments();
372        }
373
374        if docs.is_empty() {
375            None
376        } else {
377            Some((docs.join("\n"), first_span.unwrap()))
378        }
379    }
380
381    fn expect_comma_or(&mut self, closing: TokenKind) {
382        if self.is(Comma) || self.is(closing) || self.at_item_boundary() {
383            self.advance_if(Comma);
384            return;
385        }
386
387        self.track_error(
388            format!("expected `,` or {}", closing),
389            "Add a comma between elements.",
390        );
391
392        self.recover_to_comma_or(closing);
393    }
394
395    fn recover_to_comma_or(&mut self, closing: TokenKind) {
396        while !self.at_eof() && !self.is(Comma) && !self.is(closing) && !self.at_item_boundary() {
397            self.next();
398        }
399
400        self.advance_if(Comma);
401    }
402
403    fn at_eof(&self) -> bool {
404        self.is(EOF)
405    }
406
407    fn at_range(&self) -> bool {
408        matches!(self.current_token().kind, DotDot | DotDotEqual)
409    }
410
411    fn advance_if(&mut self, token_kind: TokenKind) -> bool {
412        if self.is(token_kind) {
413            self.next();
414            return true;
415        }
416
417        false
418    }
419
420    fn is(&self, token_kind: TokenKind) -> bool {
421        self.current_token().kind == token_kind
422    }
423
424    fn is_not(&self, token_kind: TokenKind) -> bool {
425        if self.at_eof() {
426            return false;
427        }
428
429        self.current_token().kind != token_kind
430    }
431
432    fn ensure(&mut self, token_kind: TokenKind) {
433        if self.current_token().kind != token_kind {
434            self.track_ensure_error(token_kind);
435        }
436
437        if self.at_eof() {
438            return;
439        }
440
441        self.next();
442    }
443
444    fn ensure_progress(&mut self, start_position: usize, closing: TokenKind) {
445        if self.stream.position == start_position && self.is_not(closing) && !self.at_eof() {
446            self.next();
447        }
448    }
449
450    fn is_right_angle_like(&self) -> bool {
451        matches!(self.current_token().kind, RightAngleBracket | ShiftRight)
452    }
453
454    fn advance_if_right_angle(&mut self) -> bool {
455        if self.stream.consume_right_angle().is_some() {
456            self.skip_comments();
457            true
458        } else {
459            false
460        }
461    }
462
463    fn span_from_token(&self, token: Token<'source>) -> ast::Span {
464        ast::Span::new(self.file_id, token.byte_offset, token.byte_length)
465    }
466
467    fn span_from_tokens(&self, start_token: Token<'source>) -> ast::Span {
468        let previous = self.stream.previous();
469        let end_byte_offset = previous.byte_offset + previous.byte_length;
470        let byte_length = end_byte_offset.saturating_sub(start_token.byte_offset);
471
472        ast::Span::new(self.file_id, start_token.byte_offset, byte_length)
473    }
474
475    fn span_from_offset(&self, start_byte_offset: u32) -> ast::Span {
476        let previous = self.stream.previous();
477        let end_byte_offset = previous.byte_offset + previous.byte_length;
478        let byte_length = end_byte_offset.saturating_sub(start_byte_offset);
479
480        ast::Span::new(self.file_id, start_byte_offset, byte_length)
481    }
482
483    fn is_type_args_call(&self) -> bool {
484        let mut position = 1; // 0 is <
485        let mut depth = 1;
486
487        loop {
488            if position > MAX_LOOKAHEAD {
489                return false;
490            }
491            match self.stream.peek_ahead(position).kind {
492                LeftAngleBracket => depth += 1,
493                RightAngleBracket if depth == 1 => {
494                    let next = self.stream.peek_ahead(position + 1).kind;
495                    return next == LeftParen
496                        || (next == Dot
497                            && self.stream.peek_ahead(position + 2).kind == Identifier
498                            && self.stream.peek_ahead(position + 3).kind == LeftParen);
499                }
500                RightAngleBracket => depth -= 1,
501                ShiftRight if depth <= 2 => {
502                    let next = self.stream.peek_ahead(position + 1).kind;
503                    return next == LeftParen
504                        || (next == Dot
505                            && self.stream.peek_ahead(position + 2).kind == Identifier
506                            && self.stream.peek_ahead(position + 3).kind == LeftParen);
507                }
508                ShiftRight => depth -= 2,
509                LeftParen => {
510                    let mut paren_depth = 1;
511                    position += 1;
512                    while paren_depth > 0 {
513                        if position > MAX_LOOKAHEAD {
514                            return false;
515                        }
516                        match self.stream.peek_ahead(position).kind {
517                            LeftParen => paren_depth += 1,
518                            RightParen => paren_depth -= 1,
519                            EOF => return false,
520                            _ => {}
521                        }
522                        position += 1;
523                    }
524                    continue;
525                }
526                EOF | Plus | Minus | Star | Slash | Percent | EqualDouble | NotEqual
527                | AmpersandDouble | PipeDouble | Semicolon | LeftCurlyBrace | RightCurlyBrace
528                | LeftSquareBracket | RightSquareBracket => return false,
529                _ => {}
530            }
531            position += 1;
532        }
533    }
534
535    fn has_block_after_struct(&self) -> bool {
536        let mut depth = 1;
537        let mut i = 0;
538        while depth > 0 {
539            i += 1;
540            if i > MAX_LOOKAHEAD {
541                return false;
542            }
543            let token = self.stream.peek_ahead(i);
544            match token.kind {
545                LeftCurlyBrace => depth += 1,
546                RightCurlyBrace => depth -= 1,
547                EOF => return false,
548                _ => {}
549            }
550        }
551        let after = self.stream.peek_ahead(i + 1);
552        matches!(
553            after.kind,
554            LeftCurlyBrace
555                | RightParen
556                | EqualDouble
557                | NotEqual
558                | LeftAngleBracket
559                | RightAngleBracket
560                | LessThanOrEqual
561                | GreaterThanOrEqual
562                | AmpersandDouble
563                | PipeDouble
564                | Plus
565                | Minus
566                | Star
567                | Slash
568                | Percent
569        )
570    }
571
572    fn is_struct_instantiation(&self, context: pratt::ExpressionContext) -> bool {
573        let previous = self.stream.previous();
574        if previous.kind != Identifier {
575            return false;
576        }
577
578        let is_uppercase = previous.text.starts_with(|c: char| c.is_uppercase());
579        let first_ahead = self.stream.peek_ahead(1);
580
581        if first_ahead.kind == DotDot {
582            return true;
583        }
584
585        if first_ahead.kind == RightCurlyBrace {
586            if context.is_control_flow_header() {
587                return is_uppercase && self.has_block_after_struct();
588            }
589            return is_uppercase;
590        }
591
592        if first_ahead.kind == Identifier {
593            let second_ahead = self.stream.peek_ahead(2);
594            return match second_ahead.kind {
595                Colon => self.stream.peek_ahead(3).kind != Colon,
596                Comma | RightCurlyBrace => {
597                    if context.is_control_flow_header() {
598                        is_uppercase && self.has_block_after_struct()
599                    } else {
600                        is_uppercase
601                    }
602                }
603                _ => false,
604            };
605        }
606
607        false
608    }
609
610    fn with_recursion<T>(&mut self, parse: impl FnOnce(&mut Self) -> T) -> Option<T> {
611        let mut scope = self.enter_recursion()?;
612        Some(parse(&mut scope))
613    }
614
615    fn enter_recursion(&mut self) -> Option<RecursionScope<'_, 'source>> {
616        let previous_depth = self.depth;
617        if self.depth >= MAX_DEPTH {
618            let span = self.span_from_token(self.current_token());
619            self.track_error_at(span, "too deeply nested", "Reduce nesting depth");
620            return None;
621        }
622        self.depth += 1;
623        Some(RecursionScope {
624            parser: self,
625            previous_depth,
626        })
627    }
628
629    fn deepen(&mut self) -> bool {
630        if self.depth >= MAX_DEPTH {
631            let span = self.span_from_token(self.current_token());
632            self.track_error_at(span, "too deeply nested", "Reduce nesting depth");
633            return false;
634        }
635        self.depth += 1;
636        true
637    }
638
639    fn too_many_errors(&self) -> bool {
640        self.errors.len() >= MAX_ERRORS
641    }
642
643    fn position(&self) -> u32 {
644        self.current_token().byte_offset
645    }
646
647    fn at_sync_point(&self) -> bool {
648        matches!(
649            self.current_token().kind,
650            Semicolon
651                | RightCurlyBrace
652                | RightParen
653                | RightSquareBracket
654                | Comma
655                | Function
656                | Struct
657                | Enum
658                | Const
659                | Impl
660                | Interface
661                | Type
662                | Import
663        )
664    }
665
666    fn can_start_annotation(&self) -> bool {
667        matches!(
668            self.current_token().kind,
669            Identifier | Function | LeftParen | Integer
670        )
671    }
672
673    fn at_item_boundary(&self) -> bool {
674        matches!(
675            self.current_token().kind,
676            Let | Function | Struct | Enum | Impl | Interface | Type | Const | Import
677        )
678    }
679
680    fn at_match_arm_terminator(&self) -> bool {
681        self.at_eof() || self.is(Comma) || self.is(RightCurlyBrace) || self.at_item_boundary()
682    }
683
684    fn resync_on_error(&mut self) {
685        if !self.at_eof() {
686            self.next();
687        }
688
689        while !self.at_sync_point() && !self.at_eof() {
690            self.next();
691        }
692    }
693
694    fn track_error(
695        &mut self,
696        label: impl Into<std::string::String>,
697        help: impl Into<std::string::String>,
698    ) {
699        let current = self.current_token();
700        let span = ast::Span::new(self.file_id, current.byte_offset, current.byte_length);
701        self.track_error_at(span, label, help);
702    }
703
704    fn track_error_at(
705        &mut self,
706        span: ast::Span,
707        label: impl Into<std::string::String>,
708        help: impl Into<std::string::String>,
709    ) {
710        if self.too_many_errors() {
711            return;
712        }
713        let error = ParseError::new("Syntax error", span, label.into())
714            .with_parse_code("syntax_error")
715            .with_help(help.into());
716
717        self.errors.push(error);
718    }
719
720    fn error_angle_brackets_for_generics(
721        &mut self,
722        span: ast::Span,
723        help: impl Into<std::string::String>,
724    ) {
725        if self.too_many_errors() {
726            return;
727        }
728        let error = ParseError::new("Syntax error", span, "use `<...>` for type args")
729            .with_parse_code("angle_brackets_for_generics")
730            .with_help(help.into());
731
732        self.errors.push(error);
733    }
734
735    fn error_var_initializer(&mut self, span: ast::Span) {
736        if self.too_many_errors() {
737            return;
738        }
739        let error = ParseError::new("Syntax error", span, "not allowed")
740            .with_parse_code("var_not_allowed")
741            .with_help(
742                "Use `const` for a primitive, or a function that returns the value e.g. `fn origin() -> Point { ... }` for a composite",
743            );
744
745        self.errors.push(error);
746    }
747
748    fn error_import_alias_after_path(&mut self, span: ast::Span, alias: &str, path: &str) {
749        if self.too_many_errors() {
750            return;
751        }
752        let error = ParseError::new("Syntax error", span, "import alias goes before the path")
753            .with_parse_code("import_alias_position")
754            .with_help(format!(
755                "Use Go-style alias syntax: `import {alias} \"{path}\"`"
756            ));
757
758        self.errors.push(error);
759    }
760
761    fn error_bare_multi_return(&mut self, span: ast::Span, suggestion: &str) {
762        if self.too_many_errors() {
763            return;
764        }
765        let error = ParseError::new(
766            "Multiple return values must be a tuple",
767            span,
768            "wrap these values in parentheses",
769        )
770        .with_parse_code("bare_multi_value_return")
771        .with_help(format!(
772            "To return multiple values, use a tuple: `{suggestion}`"
773        ));
774
775        self.errors.push(error);
776    }
777
778    fn error_match_arm_missing_comma(&mut self, span: ast::Span) {
779        if self.too_many_errors() {
780            return;
781        }
782        let error = ParseError::new("Syntax error", span, "missing comma after match arm")
783            .with_parse_code("match_arm_missing_comma")
784            .with_help("Match arms must be separated by commas, even when the body is a block.");
785
786        self.errors.push(error);
787    }
788
789    fn error_map_literal_not_supported(&mut self, span: ast::Span) {
790        if self.too_many_errors() {
791            return;
792        }
793        let error = ParseError::new("Invalid `Map` initialization", span, "invalid syntax")
794            .with_parse_code("invalid_map_initialization")
795            .with_help("To initialize a `Map`, use `Map.new<K, V>()` then `m[key] = value`");
796
797        self.errors.push(error);
798    }
799
800    fn error_missing_initializer(&mut self, span: ast::Span) {
801        if self.too_many_errors() {
802            return;
803        }
804        let error = ParseError::new(
805            "Missing initializer",
806            span,
807            "annotated binding needs a value",
808        )
809        .with_parse_code("missing_initializer")
810        .with_help("Bindings must be initialized");
811
812        self.errors.push(error);
813    }
814
815    fn track_ensure_error(&mut self, expected_token: TokenKind) {
816        if self.too_many_errors() {
817            return;
818        }
819        let current = self.current_token();
820
821        let error_code = match expected_token {
822            Semicolon => "missing_semicolon",
823            RightCurlyBrace => "unclosed_block",
824            _ => "unexpected_token",
825        };
826
827        let span = ast::Span::new(self.file_id, current.byte_offset, current.byte_length);
828        let error = ParseError::new("Syntax error", span, format!("expected {}", expected_token))
829            .with_parse_code(error_code);
830
831        self.errors.push(error);
832    }
833
834    fn close_brace_span(&mut self, start: Token<'source>, error_anchor: Token<'source>) -> Span {
835        if self.is(RightCurlyBrace) {
836            let close = self.current_token();
837            self.next();
838            let end = close.byte_offset + close.byte_length;
839            Span::new(
840                self.file_id,
841                start.byte_offset,
842                end.saturating_sub(start.byte_offset),
843            )
844        } else {
845            self.error_unclosed_block(&error_anchor);
846            self.span_from_tokens(start)
847        }
848    }
849
850    fn error_unclosed_block(&mut self, open_brace: &Token) {
851        let span = ast::Span::new(self.file_id, open_brace.byte_offset, open_brace.byte_length);
852        let error = ParseError::new("Unclosed block", span, "opening brace here")
853            .with_parse_code("unclosed_block")
854            .with_help("Add a closing `}`");
855
856        self.errors.push(error);
857    }
858
859    fn error_tuple_arity(&mut self, arity: usize, span: Span) {
860        let help = if arity == 0 {
861            "Use `()` for unit type".to_string()
862        } else if arity == 1 {
863            "Use the type directly without wrapping in a tuple".to_string()
864        } else {
865            "For >5 elements, use a struct with named fields".to_string()
866        };
867
868        let error = ParseError::new(
869            "Invalid tuple",
870            span,
871            format!("{}-element tuple not allowed", arity),
872        )
873        .with_parse_code("tuple_element_count")
874        .with_help(help);
875
876        self.errors.push(error);
877    }
878
879    fn error_duplicate_field_in_pattern(
880        &mut self,
881        field_name: &str,
882        first_span: Span,
883        second_span: Span,
884    ) {
885        let error = ParseError::new(
886            "Duplicate field",
887            first_span,
888            format!("first use of `{}`", field_name),
889        )
890        .with_span_label(second_span, "used again")
891        .with_parse_code("duplicate_field_in_pattern")
892        .with_help("Remove the duplicate binding");
893
894        self.errors.push(error);
895    }
896
897    fn error_duplicate_embed_parent(&mut self, first_span: Span, second_span: Span) {
898        let error = ParseError::new("Duplicate embed", first_span, "first use")
899            .with_span_label(second_span, "used again")
900            .with_parse_code("duplicate_embed_parent")
901            .with_help("Remove the duplicate parent");
902
903        self.errors.push(error);
904    }
905
906    fn error_impl_interface_embed(&mut self, keyword_span: Span) {
907        let error = ParseError::new(
908            "Interface embedding uses `embed`",
909            keyword_span,
910            "write `embed` here",
911        )
912        .with_parse_code("impl_interface_embed")
913        .with_help("Interfaces embed other interfaces with `embed`. Replace `impl` with `embed`");
914
915        self.errors.push(error);
916    }
917
918    fn error_duplicate_struct_field(&mut self, name: &str, first_span: Span, second_span: Span) {
919        let error = ParseError::new("Duplicate field", first_span, "first defined")
920            .with_span_label(second_span, "defined again")
921            .with_parse_code("duplicate_struct_field")
922            .with_help(format!("Remove the duplicate field `{}`", name));
923
924        self.errors.push(error);
925    }
926
927    fn error_duplicate_enum_variant(&mut self, name: &str, first_span: Span, second_span: Span) {
928        let error = ParseError::new("Duplicate variant", first_span, "first defined")
929            .with_span_label(second_span, "defined again")
930            .with_parse_code("duplicate_enum_variant")
931            .with_help(format!("Remove the duplicate variant `{}`", name));
932
933        self.errors.push(error);
934    }
935
936    fn error_duplicate_interface_method(
937        &mut self,
938        name: &str,
939        first_span: Span,
940        second_span: Span,
941    ) {
942        let error = ParseError::new("Duplicate method", first_span, "first defined")
943            .with_span_label(second_span, "defined again")
944            .with_parse_code("duplicate_interface_method")
945            .with_help(format!("Remove the duplicate method `{}`", name));
946
947        self.errors.push(error);
948    }
949
950    fn error_float_pattern_not_allowed(&mut self, span: Span, float_text: &str) {
951        let error = ParseError::new("Invalid pattern", span, "float literal not allowed here")
952            .with_parse_code("float_pattern")
953            .with_help(format!(
954                "Use a guard instead: `x if x == {} =>`",
955                float_text
956            ));
957
958        self.errors.push(error);
959    }
960
961    fn error_uppercase_binding(&mut self, span: Span) {
962        let error = ParseError::new("Invalid binding name", span, "uppercase not allowed here")
963            .with_parse_code("uppercase_binding")
964            .with_help("Lowercase the binding");
965
966        self.errors.push(error);
967    }
968
969    fn error_detached_doc_comment(&mut self, span: Span) {
970        let error = ParseError::new("Unattached doc comment", span, "is detached")
971            .with_parse_code("detached_doc_comment")
972            .with_help(
973                "Place doc comments `///` on the line above a symbol definition and file comments `//!` at the very top of the file",
974            );
975
976        self.errors.push(error);
977    }
978
979    fn error_split_file_comment(&mut self, span: Span) {
980        let error = ParseError::new("Split file comment", span, "separated from the block above")
981            .with_parse_code("split_file_comment")
982            .with_help(
983                "Remove the blank line, or write a bare `//!` line to keep a visible gap in the emitted header",
984            );
985
986        self.errors.push(error);
987    }
988
989    fn error_file_comment_build_constraint(&mut self, span: Span) {
990        let error = ParseError::new(
991            "Invalid file comment",
992            span,
993            "would become a Go build constraint",
994        )
995        .with_parse_code("file_comment_build_constraint")
996        .with_help(
997            "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",
998        );
999
1000        self.errors.push(error);
1001    }
1002
1003    fn error_misplaced_file_comment(&mut self) {
1004        let first = self.current_token();
1005        let mut last = first;
1006
1007        while self.is(FileComment) {
1008            last = self.current_token();
1009            self.stream.consume();
1010            while self.is(Comment) {
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    fn parse_integer_text(&mut self, text: &str) -> ast::Literal {
1073        self.parse_integer_text_with(text, false)
1074    }
1075
1076    fn parse_integer_text_with(&mut self, text: &str, preserve_decimal_text: bool) -> ast::Literal {
1077        let clean = if text.contains('_') {
1078            std::borrow::Cow::Owned(text.replace('_', ""))
1079        } else {
1080            std::borrow::Cow::Borrowed(text)
1081        };
1082
1083        let (n, is_decimal) = if clean.starts_with("0x") || clean.starts_with("0X") {
1084            let value = u64::from_str_radix(&clean[2..], 16).unwrap_or_else(|_| {
1085                self.track_error(
1086                    format!("hex literal '{text}' is too large"),
1087                    "Maximum value is `0xFFFFFFFFFFFFFFFF`.",
1088                );
1089                0
1090            });
1091            (value, false)
1092        } else if clean.starts_with("0o") || clean.starts_with("0O") {
1093            let value = u64::from_str_radix(&clean[2..], 8).unwrap_or_else(|_| {
1094                self.track_error(
1095                    format!("octal literal '{text}' is too large"),
1096                    "Maximum value is `0o1777777777777777777777`.",
1097                );
1098                0
1099            });
1100            (value, false)
1101        } else if clean.starts_with("0b") || clean.starts_with("0B") {
1102            let value = u64::from_str_radix(&clean[2..], 2).unwrap_or_else(|_| {
1103                self.track_error(
1104                    format!("binary literal '{text}' is too large"),
1105                    "Value must fit in 64 bits.",
1106                );
1107                0
1108            });
1109            (value, false)
1110        } else if clean.len() > 1 && clean.starts_with('0') {
1111            self.error_leading_zero();
1112            (clean.parse().unwrap_or(0), false)
1113        } else {
1114            let value = clean.parse().unwrap_or_else(|_| {
1115                self.track_error(
1116                    format!("integer literal '{text}' is too large"),
1117                    "Maximum value is `18446744073709551615`.",
1118                );
1119                0
1120            });
1121            (value, true)
1122        };
1123
1124        let original_text = if is_decimal && !preserve_decimal_text {
1125            None
1126        } else {
1127            Some(text.to_string())
1128        };
1129
1130        ast::Literal::Integer {
1131            value: n,
1132            text: original_text,
1133        }
1134    }
1135
1136    fn unexpected_token(&mut self, ctx: &str) -> ast::Expression {
1137        let token = self.current_token();
1138        let token_descriptor = if token.text.is_empty() {
1139            format!("{:?}", token.kind)
1140        } else {
1141            format!("`{}`", token.text)
1142        };
1143
1144        let span = ast::Span::new(self.file_id, token.byte_offset, token.byte_length);
1145
1146        let (label, error_code, help) = match ctx {
1147            "expr" => (
1148                format!("expected expression, found {}", token_descriptor),
1149                "expected_expression",
1150                "Check your syntax.",
1151            ),
1152            "pattern" => (
1153                format!("unexpected {} in pattern", token_descriptor),
1154                "invalid_pattern",
1155                "Patterns include literals, variables, and destructuring.",
1156            ),
1157            "literal" => (
1158                format!("expected literal, found {}", token_descriptor),
1159                "expected_literal",
1160                "Literals include numbers, strings, characters, and booleans.",
1161            ),
1162            "top_item" if token.text == "trait" => (
1163                format!("unexpected {}", token_descriptor),
1164                "trait_unsupported",
1165                "Lisette uses `interface` with Go-style structural typing. Types automatically satisfy interfaces if they have the required methods.",
1166            ),
1167            "top_item" if token.text == "use" => (
1168                "unexpected syntax for import".to_string(),
1169                "use_unsupported",
1170                "Use `import` instead of `use` for imports: `import \"module/path\"`",
1171            ),
1172            "top_item" if token.kind == Let => (
1173                "`let` is not allowed at the top level".to_string(),
1174                "top_level_let",
1175                "Use `const` for a primitive, or a function that returns the value e.g. `fn origin() -> Point { ... }` for a composite",
1176            ),
1177            "top_item" => (
1178                "expected declaration".to_string(),
1179                "expected_declaration",
1180                "At the top level of a file, Lisette expects `fn`, `struct`, `enum`, `interface`, `impl`, `const`, `import`, or `type`.",
1181            ),
1182            _ => (
1183                format!("unexpected {}", token_descriptor),
1184                "unexpected_token",
1185                "Check your syntax.",
1186            ),
1187        };
1188
1189        let error = ParseError::new("Syntax error", span, label)
1190            .with_parse_code(error_code)
1191            .with_help(help);
1192
1193        if !self.too_many_errors() {
1194            self.errors.push(error);
1195        }
1196
1197        self.resync_on_error();
1198
1199        ast::Expression::Unit {
1200            ty: Type::uninferred(),
1201            span,
1202        }
1203    }
1204}
1205
1206fn is_go_build_constraint(text: &str) -> bool {
1207    text.split_whitespace().next() == Some("+build")
1208}
1209
1210struct TokenStream<'source> {
1211    tokens: Vec<Token<'source>>,
1212    position: usize,
1213}
1214
1215impl<'source> TokenStream<'source> {
1216    fn new(tokens: Vec<Token<'source>>) -> Self {
1217        debug_assert!(
1218            !tokens.is_empty(),
1219            "lexer must always produce at least an EOF token",
1220        );
1221        Self {
1222            tokens,
1223            position: 0,
1224        }
1225    }
1226
1227    fn peek(&self) -> Token<'source> {
1228        self.tokens[self.position]
1229    }
1230
1231    fn peek_ahead(&self, n: usize) -> Token<'source> {
1232        let last_index = self.tokens.len() - 1;
1233        let idx = self.position.saturating_add(n).min(last_index);
1234        self.tokens[idx]
1235    }
1236
1237    fn previous(&self) -> Token<'source> {
1238        self.tokens[self.position.saturating_sub(1)]
1239    }
1240
1241    fn consume(&mut self) -> Token<'source> {
1242        let token = self.tokens[self.position];
1243        if self.position + 1 < self.tokens.len() {
1244            self.position += 1;
1245        }
1246        token
1247    }
1248
1249    fn consume_right_angle(&mut self) -> Option<Token<'source>> {
1250        let token = self.peek();
1251        match token.kind {
1252            RightAngleBracket => Some(self.consume()),
1253            ShiftRight => {
1254                let first = Token {
1255                    kind: RightAngleBracket,
1256                    text: ">",
1257                    byte_offset: token.byte_offset,
1258                    byte_length: 1,
1259                };
1260                let second = Token {
1261                    byte_offset: token.byte_offset + 1,
1262                    ..first
1263                };
1264                self.tokens[self.position] = first;
1265                self.tokens.insert(self.position + 1, second);
1266                Some(self.consume())
1267            }
1268            _ => None,
1269        }
1270    }
1271}
1272
1273#[cfg(test)]
1274mod file_comment_tests {
1275    use crate::build_ast;
1276
1277    fn file_comment(source: &str) -> Option<std::string::String> {
1278        let result = build_ast(source, 0);
1279        assert!(
1280            result.errors.is_empty(),
1281            "unexpected errors: {:?}",
1282            result.errors
1283        );
1284        result.file_comment
1285    }
1286
1287    #[test]
1288    fn consecutive_lines_join_with_newlines() {
1289        assert_eq!(
1290            file_comment("//! a\n//! b\nfn f() {}").as_deref(),
1291            Some("a\nb")
1292        );
1293    }
1294
1295    #[test]
1296    fn bare_line_contributes_empty_line() {
1297        assert_eq!(
1298            file_comment("//! a\n//!\n//! b\nfn f() {}").as_deref(),
1299            Some("a\n\nb")
1300        );
1301    }
1302
1303    #[test]
1304    fn blank_line_between_runs_is_an_error() {
1305        for source in [
1306            "//! a\n\n//! b\n\nfn f() {}",
1307            "//! a\r\n\r\n//! b\r\n\r\nfn f() {}",
1308            "//! a\n//!\n\n//! b\nfn f() {}",
1309        ] {
1310            let result = build_ast(source, 0);
1311            let codes: Vec<_> = result.errors.iter().map(|e| e.code.as_str()).collect();
1312            assert_eq!(
1313                codes,
1314                ["parse.split_file_comment"],
1315                "for source: {source:?}"
1316            );
1317        }
1318    }
1319
1320    #[test]
1321    fn anything_before_the_block_is_rejected() {
1322        for source in ["\n//! a\nfn f() {}", " //! a\nfn f() {}"] {
1323            let result = build_ast(source, 0);
1324            let codes: Vec<_> = result.errors.iter().map(|e| e.code.as_str()).collect();
1325            assert_eq!(
1326                codes,
1327                ["parse.misplaced_file_comment"],
1328                "for source: {source:?}"
1329            );
1330        }
1331    }
1332
1333    #[test]
1334    fn blank_lines_after_the_block_are_allowed() {
1335        assert_eq!(
1336            file_comment("//! a\n//! b\n\n\nfn f() {}").as_deref(),
1337            Some("a\nb")
1338        );
1339    }
1340
1341    #[test]
1342    fn leading_comment_makes_the_header_misplaced() {
1343        let result = build_ast("// leading\n//! too late\nfn f() {}", 0);
1344        let codes: Vec<_> = result.errors.iter().map(|e| e.code.as_str()).collect();
1345        assert_eq!(codes, ["parse.misplaced_file_comment"]);
1346    }
1347
1348    #[test]
1349    fn interleaved_comment_ends_the_block() {
1350        let result = build_ast("//! a\n// note\n//! b\nfn f() {}", 0);
1351        let codes: Vec<_> = result.errors.iter().map(|e| e.code.as_str()).collect();
1352        assert_eq!(codes, ["parse.misplaced_file_comment"]);
1353    }
1354
1355    #[test]
1356    fn comment_after_the_block_is_allowed() {
1357        assert_eq!(
1358            file_comment("//! a\n\n// section note\nfn f() {}").as_deref(),
1359            Some("a")
1360        );
1361    }
1362
1363    #[test]
1364    fn file_without_header_has_no_file_comment() {
1365        assert_eq!(file_comment("fn f() {}"), None);
1366    }
1367
1368    #[test]
1369    fn header_without_items_is_valid() {
1370        assert_eq!(
1371            file_comment("//! header only").as_deref(),
1372            Some("header only")
1373        );
1374    }
1375
1376    #[test]
1377    fn header_before_doc_commented_item() {
1378        let result = build_ast("//! header\n/// item doc\nfn f() {}", 0);
1379        assert!(result.errors.is_empty(), "{:?}", result.errors);
1380        assert_eq!(result.file_comment.as_deref(), Some("header"));
1381    }
1382
1383    #[test]
1384    fn misplaced_file_comment_reports_one_error_per_run() {
1385        let result = build_ast("fn f() {}\n//! a\n//! b\nfn g() {}", 0);
1386        let codes: Vec<_> = result.errors.iter().map(|e| e.code.as_str()).collect();
1387        assert_eq!(codes, ["parse.misplaced_file_comment"]);
1388    }
1389
1390    #[test]
1391    fn build_constraint_lines_are_rejected() {
1392        for source in [
1393            "//!+build ignore\nfn f() {}",
1394            "//! +build ignore\nfn f() {}",
1395            "//!  \t+build linux\nfn f() {}",
1396            "//! +build\nfn f() {}",
1397            "//! +build ignore\r\nfn f() {}",
1398            "//! +build\r\nfn f() {}",
1399            "//!\u{00A0}+build ignore\nfn f() {}",
1400            "//! +build\u{00A0}ignore\nfn f() {}",
1401            "//! +build\u{3000}ignore\nfn f() {}",
1402        ] {
1403            let result = build_ast(source, 0);
1404            let codes: Vec<_> = result.errors.iter().map(|e| e.code.as_str()).collect();
1405            assert_eq!(
1406                codes,
1407                ["parse.file_comment_build_constraint"],
1408                "for source: {source:?}"
1409            );
1410        }
1411    }
1412
1413    #[test]
1414    fn build_constraint_lookalikes_are_allowed() {
1415        for source in [
1416            "//! +buildx tag\nfn f() {}",
1417            "//! use +build wisely\nfn f() {}",
1418            "//! +builder pattern\nfn f() {}",
1419        ] {
1420            let result = build_ast(source, 0);
1421            assert!(result.errors.is_empty(), "for source: {source:?}");
1422        }
1423    }
1424}