Skip to main content

lisette_syntax/parse/
mod.rs

1use crate::ast::{self, Span};
2use crate::attributes::has_test_attribute;
3use crate::constant;
4use crate::lex;
5use crate::lex::TokenKind::*;
6use crate::lex::{Token, TokenKind};
7use crate::types::{ErrorReported, Type};
8use std::borrow::Cow;
9use std::ops::{Deref, DerefMut};
10use std::string;
11
12pub(crate) const MAX_TUPLE_ARITY: usize = 5;
13pub const TUPLE_FIELDS: &[&str] = &["First", "Second", "Third", "Fourth", "Fifth"];
14pub const IMPORT_AFTER_ITEM_CODE: &str = "parse.import_after_item";
15const MAX_DEPTH: u32 = 64;
16const MAX_ERRORS: usize = 50;
17const MAX_LOOKAHEAD: usize = 256;
18
19#[derive(Clone, Copy, PartialEq, Eq)]
20pub(crate) enum ParamMode {
21    Strict,
22    TestFunction,
23}
24
25struct TypeArgsScan {
26    end: usize,
27    crossed_newline: bool,
28}
29
30mod annotations;
31mod control_flow;
32mod definitions;
33mod directives;
34mod error;
35mod expressions;
36mod identifiers;
37mod patterns;
38mod pratt;
39mod strings;
40
41#[cfg(test)]
42mod recovery_tests;
43
44pub use error::ParseError;
45
46pub struct ParseResult {
47    pub ast: Vec<ast::Expression>,
48    pub errors: Vec<ParseError>,
49    pub file_comment: Option<string::String>,
50    pub truncated: bool,
51    pub status: FileParseStatus,
52}
53
54/// How much of a file survived parsing.
55#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
56pub enum FileParseStatus {
57    #[default]
58    Clean,
59    Recovered,
60    Failed,
61}
62
63impl ParseResult {
64    pub fn has_errors(&self) -> bool {
65        !self.errors.is_empty()
66    }
67}
68
69pub struct Parser<'source> {
70    stream: TokenStream<'source>,
71    errors: Vec<ParseError>,
72    file_id: u32,
73    source: &'source str,
74    depth: u32,
75    expressions: u32,
76}
77
78/// A recursion frame owns the parser depth it opened and restores the previous
79/// depth even when parsing exits early or panics.
80struct RecursionScope<'parser, 'source> {
81    parser: &'parser mut Parser<'source>,
82    previous_depth: u32,
83}
84
85impl<'parser, 'source> Deref for RecursionScope<'parser, 'source> {
86    type Target = Parser<'source>;
87
88    fn deref(&self) -> &Self::Target {
89        self.parser
90    }
91}
92
93impl<'parser, 'source> DerefMut for RecursionScope<'parser, 'source> {
94    fn deref_mut(&mut self) -> &mut Self::Target {
95        self.parser
96    }
97}
98
99impl Drop for RecursionScope<'_, '_> {
100    fn drop(&mut self) {
101        self.parser.depth = self.previous_depth;
102    }
103}
104
105impl<'source> Parser<'source> {
106    pub fn new(tokens: Vec<Token<'source>>, source: &'source str) -> Parser<'source> {
107        Self::with_file_id(tokens, source, 0)
108    }
109
110    pub fn lex_and_parse_file(source: &str, file_id: u32) -> ParseResult {
111        let lex_result = lex::Lexer::new(source, file_id).lex();
112
113        if lex_result.failed() {
114            return ParseResult {
115                ast: vec![],
116                errors: lex_result.errors,
117                file_comment: None,
118                truncated: true,
119                status: FileParseStatus::Failed,
120            };
121        }
122
123        Parser::with_file_id(lex_result.tokens, source, file_id).parse()
124    }
125
126    pub fn lex_and_parse_imports(source: &str, file_id: u32) -> ParseResult {
127        let lex_result = lex::Lexer::new(source, file_id).lex();
128
129        if lex_result.failed() {
130            return ParseResult {
131                ast: vec![],
132                errors: lex_result.errors,
133                file_comment: None,
134                truncated: true,
135                status: FileParseStatus::Failed,
136            };
137        }
138
139        Parser::with_file_id(lex_result.tokens, source, file_id).parse_imports()
140    }
141
142    fn with_file_id(
143        tokens: Vec<Token<'source>>,
144        source: &'source str,
145        file_id: u32,
146    ) -> Parser<'source> {
147        let stream = TokenStream::new(tokens);
148
149        Parser {
150            stream,
151            errors: Default::default(),
152            file_id,
153            source,
154            depth: 0,
155            expressions: 0,
156        }
157    }
158
159    fn next_expression_id(&mut self) -> ast::ExpressionId {
160        self.expressions += 1;
161        ast::ExpressionId::parsed(self.file_id, self.expressions - 1)
162    }
163
164    pub fn parse(mut self) -> ParseResult {
165        let mut top_items = vec![];
166        let mut seen_non_import = false;
167
168        let shebang_end = self.consume_shebang();
169        let file_comment = self.collect_file_comments(shebang_end);
170        self.skip_comments();
171
172        while !self.at_eof() && !self.too_many_errors() {
173            let position = self.position();
174            let item = self.parse_top_item();
175            if !matches!(item, ast::Expression::Unit { .. }) {
176                if let ast::Expression::PackageImport {
177                    span, name_span, ..
178                } = &item
179                {
180                    if seen_non_import {
181                        self.error_import_after_item(*span, *name_span);
182                    }
183                } else {
184                    seen_non_import = true;
185                }
186                top_items.push(item);
187            }
188            self.advance_if(Semicolon);
189            if self.position() == position {
190                self.next();
191            }
192        }
193
194        let truncated = !self.at_eof();
195        let status = if self.errors.is_empty() {
196            FileParseStatus::Clean
197        } else {
198            FileParseStatus::Recovered
199        };
200
201        ParseResult {
202            ast: top_items,
203            errors: self.errors,
204            file_comment,
205            truncated,
206            status,
207        }
208    }
209
210    fn parse_imports(mut self) -> ParseResult {
211        let mut imports = vec![];
212
213        let shebang_end = self.consume_shebang();
214        let file_comment = self.collect_file_comments(shebang_end);
215        self.skip_comments();
216
217        while self.is(Import) && !self.too_many_errors() {
218            imports.push(self.parse_top_item());
219            self.advance_if(Semicolon);
220            self.skip_comments();
221        }
222
223        let status = if self.errors.is_empty() {
224            FileParseStatus::Clean
225        } else {
226            FileParseStatus::Recovered
227        };
228
229        ParseResult {
230            ast: imports,
231            errors: self.errors,
232            file_comment,
233            truncated: false,
234            status,
235        }
236    }
237
238    fn parse_top_item(&mut self) -> ast::Expression {
239        let doc_with_span = self.collect_doc_comments();
240
241        let attributes = self.parse_attributes();
242
243        let pub_token = if self.is(Pub) {
244            Some(self.current_token())
245        } else {
246            None
247        };
248        let is_public = pub_token.is_some();
249        if is_public {
250            self.next();
251        }
252
253        if let Some(token) = pub_token {
254            let span = Span::new(self.file_id, token.byte_offset, token.byte_length);
255            match self.current_token().kind {
256                Impl => self.error_misplaced_pub(
257                    span,
258                    "pub_impl",
259                    "Place `pub` on individual methods inside the `impl` block instead",
260                ),
261                Import => self.error_misplaced_pub(
262                    span,
263                    "pub_import",
264                    "Remove `pub`. An import is always private to the file that declares it",
265                ),
266                _ => {}
267            }
268        }
269
270        let is_documentable = matches!(
271            self.current_token().kind,
272            Enum | Struct | Interface | Function | Const | Var | Type
273        );
274
275        if let Some((_, ref span)) = doc_with_span
276            && !is_documentable
277        {
278            self.error_detached_doc_comment(*span);
279        }
280
281        let doc = doc_with_span.map(|(text, _)| text);
282
283        let misplaced = match self.current_token().kind {
284            Enum | Struct | Function | Type => None,
285            Interface | Var => attributes.iter().find(|attribute| attribute.name != "go"),
286            _ => attributes.first(),
287        };
288        if let Some(attribute) = misplaced {
289            self.error_misplaced_attribute(attribute.span);
290        }
291
292        let expression = match self.current_token().kind {
293            Enum => self.parse_enum_definition(doc, attributes),
294            Struct => self.parse_struct_definition(doc, attributes),
295            Interface => self.parse_interface_definition(doc, attributes),
296            Function => {
297                // Only a top-level `#[test]` declaration may write a bare handle parameter.
298                let mode = if has_test_attribute(&attributes) {
299                    ParamMode::TestFunction
300                } else {
301                    ParamMode::Strict
302                };
303                self.parse_function(doc, attributes, mode)
304            }
305            Impl => self.parse_impl_block(),
306            Const => self.parse_const_definition(doc),
307            Var => self.parse_var_declaration(doc, attributes),
308            Import => self.parse_import(),
309            Type => self.parse_type_alias_with_doc(doc, attributes),
310            Comment => {
311                let start = self.current_token();
312                self.skip_comments();
313                ast::Expression::Unit {
314                    id: self.next_expression_id(),
315                    ty: Type::uninferred(),
316                    span: self.span_from_offset(start.byte_offset),
317                }
318            }
319            Let => {
320                let error = self.unexpected_token("top_item");
321                self.parse_let();
322                error
323            }
324            _ => self.unexpected_token("top_item"),
325        };
326
327        if is_public {
328            return expression.set_public();
329        }
330
331        expression
332    }
333
334    fn parse_block_item(&mut self) -> ast::Expression {
335        match self.current_token().kind {
336            Enum => {
337                self.track_coded_error(
338                    "Nested definition",
339                    "nested_definition",
340                    "must be at the top level",
341                    "Move this enum definition to the top level of the file.",
342                );
343                self.parse_enum_definition(None, vec![])
344            }
345            Struct => {
346                self.track_coded_error(
347                    "Nested definition",
348                    "nested_definition",
349                    "must be at the top level",
350                    "Move this struct definition to the top level of the file.",
351                );
352                self.parse_struct_definition(None, vec![])
353            }
354            Type => {
355                self.track_coded_error(
356                    "Nested definition",
357                    "nested_definition",
358                    "must be at the top level",
359                    "Move this type alias to the top level of the file.",
360                );
361                self.parse_type_alias_with_doc(None, vec![])
362            }
363            Import => {
364                self.track_coded_error(
365                    "Nested definition",
366                    "nested_definition",
367                    "must be at the top level",
368                    "Move this import to the top level of the file.",
369                );
370                self.parse_import()
371            }
372            Impl => {
373                self.track_coded_error(
374                    "Nested definition",
375                    "nested_definition",
376                    "must be at the top level",
377                    "Move this `impl` block to the top level of the file.",
378                );
379                self.parse_impl_block()
380            }
381            Interface => {
382                self.track_coded_error(
383                    "Nested definition",
384                    "nested_definition",
385                    "must be at the top level",
386                    "Move this interface definition to the top level of the file.",
387                );
388                self.parse_interface_definition(None, vec![])
389            }
390            Function => self.parse_function(None, vec![], ParamMode::Strict),
391            Const => self.parse_const_definition(None),
392
393            Hash => {
394                let attributes = self.parse_attributes();
395                if let Some(attribute) = attributes.first() {
396                    self.error_misplaced_attribute(attribute.span);
397                }
398                if self.is(RightCurlyBrace) || self.at_eof() {
399                    self.error_expression(self.span_from_token(self.current_token()))
400                } else {
401                    self.parse_block_item()
402                }
403            }
404
405            Let => self.parse_let(),
406            Return => self.parse_return(true),
407            For => self.parse_for(),
408            While => self.parse_while(),
409            Loop => self.parse_loop(),
410            Break => self.parse_break(),
411            Continue => self.parse_continue(),
412            Defer => self.parse_defer(),
413            Assert => self.parse_assert(),
414            Directive => self.parse_directive(),
415            _ => self.parse_assignment(),
416        }
417    }
418
419    fn current_token(&self) -> Token<'source> {
420        self.stream.peek()
421    }
422
423    fn newline_before_current(&self) -> bool {
424        let previous = self.stream.previous();
425        let prev_end = (previous.byte_offset + previous.byte_length) as usize;
426        let curr_start = self.current_token().byte_offset as usize;
427        if prev_end <= curr_start && curr_start <= self.source.len() {
428            return self.source[prev_end..curr_start].contains('\n');
429        }
430        false
431    }
432
433    fn next(&mut self) {
434        self.stream.consume();
435        self.skip_comments();
436    }
437
438    fn skip_comments(&mut self) {
439        while self.is(Comment) {
440            self.stream.consume();
441        }
442        if self.is(FileComment) {
443            self.error_misplaced_file_comment();
444        }
445    }
446
447    fn consume_shebang(&mut self) -> Option<u32> {
448        if !self.is(Shebang) {
449            return None;
450        }
451
452        let token = self.current_token();
453        self.stream.consume();
454        Some(token.end_offset())
455    }
456
457    fn opens_file_header(&self, offset: u32, shebang_end: Option<u32>) -> bool {
458        match shebang_end {
459            None => offset == 0,
460            Some(end) => self
461                .source
462                .get(end as usize..offset as usize)
463                .is_some_and(|between| {
464                    between.chars().all(char::is_whitespace)
465                        && between.bytes().filter(|&byte| byte == b'\n').count() <= 2
466                }),
467        }
468    }
469
470    fn collect_file_comments(&mut self, shebang_end: Option<u32>) -> Option<string::String> {
471        let mut docs = Vec::new();
472        let mut previous_end: Option<u32> = None;
473
474        while self.is(FileComment) {
475            let token = self.current_token();
476            match previous_end {
477                None if !self.opens_file_header(token.byte_offset, shebang_end) => {
478                    self.error_misplaced_file_comment_at(self.span_from_token(token));
479                }
480                Some(end)
481                    if self.source[end as usize..token.byte_offset as usize]
482                        .bytes()
483                        .filter(|&byte| byte == b'\n')
484                        .count()
485                        > 1 =>
486                {
487                    self.error_split_file_comment(self.span_from_token(token));
488                }
489                _ => {}
490            }
491            if is_go_build_constraint(token.text) {
492                self.error_file_comment_build_constraint(self.span_from_token(token));
493            }
494            docs.push(token.text.to_string());
495            previous_end = Some(token.byte_offset + token.byte_length);
496            self.stream.consume();
497        }
498
499        if docs.is_empty() {
500            None
501        } else {
502            Some(docs.join("\n"))
503        }
504    }
505
506    fn collect_doc_comments(&mut self) -> Option<(string::String, Span)> {
507        let mut docs = Vec::new();
508        let mut first_span: Option<Span> = None;
509
510        while self.is(DocComment) {
511            let token = self.current_token();
512            if first_span.is_none() {
513                first_span = Some(self.span_from_token(token));
514            }
515            docs.push(token.text.to_string());
516            self.stream.consume();
517            self.skip_comments();
518        }
519
520        if docs.is_empty() {
521            None
522        } else {
523            Some((docs.join("\n"), first_span.unwrap()))
524        }
525    }
526
527    fn expect_comma_or(&mut self, closing: TokenKind) {
528        if self.is(Comma) || self.is(closing) || self.at_item_boundary() {
529            self.advance_if(Comma);
530            return;
531        }
532
533        self.track_error(
534            format!("expected `,` or {}", closing),
535            "Add a comma between elements.",
536        );
537
538        self.recover_to_comma_or(closing);
539    }
540
541    fn recover_to_comma_or(&mut self, closing: TokenKind) {
542        while !self.at_eof() && !self.is(Comma) && !self.is(closing) && !self.at_recovery_boundary()
543        {
544            self.next();
545        }
546
547        self.advance_if(Comma);
548    }
549
550    fn at_eof(&self) -> bool {
551        self.is(EOF)
552    }
553
554    fn at_range(&self) -> bool {
555        matches!(self.current_token().kind, DotDot | DotDotEqual)
556    }
557
558    fn advance_if(&mut self, token_kind: TokenKind) -> bool {
559        if self.is(token_kind) {
560            self.next();
561            return true;
562        }
563
564        false
565    }
566
567    fn is(&self, token_kind: TokenKind) -> bool {
568        self.current_token().kind == token_kind
569    }
570
571    fn is_not(&self, token_kind: TokenKind) -> bool {
572        if self.at_eof() {
573            return false;
574        }
575
576        self.current_token().kind != token_kind
577    }
578
579    fn ensure(&mut self, token_kind: TokenKind) {
580        if self.current_token().kind != token_kind {
581            self.track_ensure_error(token_kind);
582        }
583
584        if self.at_eof() {
585            return;
586        }
587
588        self.next();
589    }
590
591    fn ensure_in_place(&mut self, token_kind: TokenKind) -> bool {
592        if self.is(token_kind) {
593            self.next();
594            return true;
595        }
596
597        self.track_ensure_error(token_kind);
598        false
599    }
600
601    fn ensure_progress(&mut self, start_position: usize, closing: TokenKind) {
602        if self.stream.position == start_position && self.is_not(closing) && !self.at_eof() {
603            self.next();
604        }
605    }
606
607    fn is_right_angle_like(&self) -> bool {
608        matches!(self.current_token().kind, RightAngleBracket | ShiftRight)
609    }
610
611    fn advance_if_right_angle(&mut self) -> bool {
612        if self.stream.consume_right_angle().is_some() {
613            self.skip_comments();
614            true
615        } else {
616            false
617        }
618    }
619
620    fn span_from_token(&self, token: Token<'source>) -> Span {
621        Span::new(self.file_id, token.byte_offset, token.byte_length)
622    }
623
624    fn span_from_offset(&self, start_byte_offset: u32) -> Span {
625        let previous = self.stream.previous_code();
626        let end_byte_offset = previous.byte_offset + previous.byte_length;
627        let byte_length = end_byte_offset.saturating_sub(start_byte_offset);
628
629        Span::new(self.file_id, start_byte_offset, byte_length)
630    }
631
632    fn scan_type_args(&self) -> Option<TypeArgsScan> {
633        let mut position = 1; // 0 is <
634        let mut depth = 1;
635        let mut crossed_newline = false;
636
637        loop {
638            if position > MAX_LOOKAHEAD {
639                return None;
640            }
641            crossed_newline |= self.newline_before_peek(position);
642            match self.stream.peek_ahead(position).kind {
643                LeftAngleBracket => depth += 1,
644                RightAngleBracket if depth == 1 => {
645                    return Some(TypeArgsScan {
646                        end: position + 1,
647                        crossed_newline,
648                    });
649                }
650                RightAngleBracket => depth -= 1,
651                ShiftRight if depth <= 2 => {
652                    return Some(TypeArgsScan {
653                        end: position + 1,
654                        crossed_newline,
655                    });
656                }
657                ShiftRight => depth -= 2,
658                LeftParen => {
659                    let mut paren_depth = 1;
660                    position += 1;
661                    while paren_depth > 0 {
662                        if position > MAX_LOOKAHEAD {
663                            return None;
664                        }
665                        crossed_newline |= self.newline_before_peek(position);
666                        match self.stream.peek_ahead(position).kind {
667                            LeftParen => paren_depth += 1,
668                            RightParen => paren_depth -= 1,
669                            EOF => return None,
670                            _ => {}
671                        }
672                        position += 1;
673                    }
674                    continue;
675                }
676                EOF | Plus | Minus | Star | Slash | Percent | EqualDouble | NotEqual
677                | AmpersandDouble | PipeDouble | Semicolon | LeftCurlyBrace | RightCurlyBrace
678                | LeftSquareBracket | RightSquareBracket => return None,
679                _ => {}
680            }
681            position += 1;
682        }
683    }
684
685    fn opens_type_args(&self) -> bool {
686        let Some(scan) = self.scan_type_args() else {
687            return false;
688        };
689
690        let next = self.stream.peek_ahead(scan.end).kind;
691
692        let call = next == LeftParen
693            || (next == Dot
694                && self.stream.peek_ahead(scan.end + 1).kind == Identifier
695                && self.stream.peek_ahead(scan.end + 2).kind == LeftParen);
696
697        call || (!scan.crossed_newline && self.ends_expression_at(scan.end))
698    }
699
700    fn ends_expression_at(&self, position: usize) -> bool {
701        let mut position = position;
702        while matches!(
703            self.stream.peek_ahead(position).kind,
704            Comment | DocComment | FileComment
705        ) {
706            position += 1;
707        }
708
709        self.newline_before_peek(position)
710            || matches!(
711                self.stream.peek_ahead(position).kind,
712                EOF | Semicolon | RightCurlyBrace | RightParen | RightSquareBracket | Comma
713            )
714    }
715
716    fn newline_before_peek(&self, position: usize) -> bool {
717        let previous = self.stream.peek_ahead(position.saturating_sub(1));
718        let from = (previous.byte_offset + previous.byte_length) as usize;
719        let to = self.stream.peek_ahead(position).byte_offset as usize;
720
721        from <= to && to <= self.source.len() && self.source[from..to].contains('\n')
722    }
723
724    fn has_block_after_struct(&self) -> bool {
725        let mut depth = 1;
726        let mut i = 0;
727        while depth > 0 {
728            i += 1;
729            if i > MAX_LOOKAHEAD {
730                return false;
731            }
732            let token = self.stream.peek_ahead(i);
733            match token.kind {
734                LeftCurlyBrace => depth += 1,
735                RightCurlyBrace => depth -= 1,
736                EOF => return false,
737                _ => {}
738            }
739        }
740        let after = self.stream.peek_ahead(i + 1);
741        matches!(
742            after.kind,
743            LeftCurlyBrace
744                | RightParen
745                | EqualDouble
746                | NotEqual
747                | LeftAngleBracket
748                | RightAngleBracket
749                | LessThanOrEqual
750                | GreaterThanOrEqual
751                | AmpersandDouble
752                | PipeDouble
753                | Plus
754                | Minus
755                | Star
756                | Slash
757                | Percent
758        )
759    }
760
761    fn is_struct_instantiation(&self, context: pratt::ExpressionContext) -> bool {
762        let previous = self.stream.previous();
763        if previous.kind != Identifier {
764            return false;
765        }
766
767        let is_uppercase = previous.text.starts_with(|c: char| c.is_uppercase());
768        let first_ahead = self.stream.peek_ahead(1);
769
770        if first_ahead.kind == DotDot {
771            return true;
772        }
773
774        if first_ahead.kind == RightCurlyBrace {
775            if context.is_control_flow_header() {
776                return is_uppercase && self.has_block_after_struct();
777            }
778            return is_uppercase;
779        }
780
781        if first_ahead.kind == Identifier {
782            let second_ahead = self.stream.peek_ahead(2);
783            return match second_ahead.kind {
784                Colon => self.stream.peek_ahead(3).kind != Colon,
785                Comma | RightCurlyBrace => {
786                    if context.is_control_flow_header() {
787                        is_uppercase && self.has_block_after_struct()
788                    } else {
789                        is_uppercase
790                    }
791                }
792                _ => false,
793            };
794        }
795
796        false
797    }
798
799    fn with_recursion<T>(&mut self, parse: impl FnOnce(&mut Self) -> T) -> Option<T> {
800        let mut scope = self.enter_recursion()?;
801        Some(parse(&mut scope))
802    }
803
804    fn enter_recursion(&mut self) -> Option<RecursionScope<'_, 'source>> {
805        let previous_depth = self.depth;
806        if self.depth >= MAX_DEPTH {
807            let span = self.span_from_token(self.current_token());
808            self.track_coded_error_at(
809                span,
810                "Nesting too deep",
811                "nesting_too_deep",
812                "too deeply nested",
813                "Reduce nesting depth",
814            );
815            self.next();
816            return None;
817        }
818        self.depth += 1;
819        Some(RecursionScope {
820            parser: self,
821            previous_depth,
822        })
823    }
824
825    fn deepen(&mut self) -> bool {
826        if self.depth >= MAX_DEPTH {
827            let span = self.span_from_token(self.current_token());
828            self.track_coded_error_at(
829                span,
830                "Nesting too deep",
831                "nesting_too_deep",
832                "too deeply nested",
833                "Reduce nesting depth",
834            );
835            return false;
836        }
837        self.depth += 1;
838        true
839    }
840
841    fn too_many_errors(&self) -> bool {
842        self.errors.len() >= MAX_ERRORS
843    }
844
845    fn position(&self) -> u32 {
846        self.current_token().byte_offset
847    }
848
849    fn at_sync_point(&self) -> bool {
850        matches!(
851            self.current_token().kind,
852            Semicolon
853                | RightCurlyBrace
854                | RightParen
855                | RightSquareBracket
856                | Comma
857                | Let
858                | For
859                | While
860                | Loop
861                | If
862                | Match
863                | Return
864                | Break
865                | Continue
866                | Defer
867                | Assert
868                | Task
869                | Try
870                | Recover
871                | Select
872                | Function
873                | Struct
874                | Enum
875                | Const
876                | Impl
877                | Interface
878                | Type
879                | Import
880        )
881    }
882
883    fn can_start_annotation(&self) -> bool {
884        matches!(
885            self.current_token().kind,
886            Identifier | Function | LeftParen | Integer | Mut
887        )
888    }
889
890    fn can_recover_annotation(&self) -> bool {
891        !self.at_recovery_boundary() && self.can_start_annotation()
892    }
893
894    fn at_recovery_boundary(&self) -> bool {
895        if self.is(Function) {
896            return self.at_function_declaration();
897        }
898        matches!(self.current_token().kind, DocComment | Hash | Pub) || self.at_item_boundary()
899    }
900
901    fn at_parameter_recovery_boundary(&self) -> bool {
902        self.at_recovery_boundary() && self.stream.peek_ahead(1).kind != Colon
903    }
904
905    fn at_function_declaration(&self) -> bool {
906        self.is(Function)
907            && self.stream.peek_ahead(1).kind == Identifier
908            && matches!(
909                self.stream.peek_ahead(2).kind,
910                LeftParen | LeftAngleBracket | Dot
911            )
912    }
913
914    fn at_item_boundary(&self) -> bool {
915        matches!(
916            self.current_token().kind,
917            Let | Function | Struct | Enum | Impl | Interface | Type | Const | Import
918        )
919    }
920
921    fn at_match_arm_terminator(&self) -> bool {
922        self.at_eof() || self.is(Comma) || self.is(RightCurlyBrace) || self.at_item_boundary()
923    }
924
925    fn resync_on_error(&mut self) {
926        while !self.at_sync_point() && !self.at_eof() {
927            self.next();
928        }
929    }
930
931    fn track_error(&mut self, label: impl Into<string::String>, help: impl Into<string::String>) {
932        let current = self.current_token();
933        let span = Span::new(self.file_id, current.byte_offset, current.byte_length);
934        self.track_error_at(span, label, help);
935    }
936
937    fn track_error_at(
938        &mut self,
939        span: Span,
940        label: impl Into<string::String>,
941        help: impl Into<string::String>,
942    ) {
943        self.track_coded_error_at(span, "Syntax error", "syntax_error", label, help);
944    }
945
946    fn track_coded_error(
947        &mut self,
948        title: impl Into<string::String>,
949        code: &str,
950        label: impl Into<string::String>,
951        help: impl Into<string::String>,
952    ) {
953        let current = self.current_token();
954        let span = Span::new(self.file_id, current.byte_offset, current.byte_length);
955        self.track_coded_error_at(span, title, code, label, help);
956    }
957
958    fn track_coded_error_at(
959        &mut self,
960        span: Span,
961        title: impl Into<string::String>,
962        code: &str,
963        label: impl Into<string::String>,
964        help: impl Into<string::String>,
965    ) {
966        if self.too_many_errors() {
967            return;
968        }
969        let error = ParseError::new(title, span, label)
970            .with_parse_code(code)
971            .with_help(help.into());
972
973        self.errors.push(error);
974    }
975
976    fn error_angle_brackets_for_generics(&mut self, span: Span, help: impl Into<string::String>) {
977        if self.too_many_errors() {
978            return;
979        }
980        let error = ParseError::new(
981            "Wrong brackets for type arguments",
982            span,
983            "use `<...>` for type args",
984        )
985        .with_parse_code("angle_brackets_for_generics")
986        .with_help(help.into());
987
988        self.errors.push(error);
989    }
990
991    fn error_var_initializer(&mut self, span: Span) {
992        if self.too_many_errors() {
993            return;
994        }
995        let error = ParseError::new("Unsupported `var` declaration", span, "not allowed")
996            .with_parse_code("var_not_allowed")
997            .with_help(
998                "Use `const` for a primitive, or a function that returns the value, e.g. `fn origin() -> Point { ... }` for a composite",
999            );
1000
1001        self.errors.push(error);
1002    }
1003
1004    fn error_import_alias_after_path(&mut self, span: Span, alias: &str, path: &str) {
1005        if self.too_many_errors() {
1006            return;
1007        }
1008        let error = ParseError::new(
1009            "Misplaced import alias",
1010            span,
1011            "import alias goes before the path",
1012        )
1013        .with_parse_code("import_alias_position")
1014        .with_help(format!(
1015            "Use Go-style alias syntax: `import {alias} \"{path}\"`"
1016        ));
1017
1018        self.errors.push(error);
1019    }
1020
1021    fn error_bare_multi_return(&mut self, span: Span, suggestion: &str) {
1022        if self.too_many_errors() {
1023            return;
1024        }
1025        let error = ParseError::new(
1026            "Multiple return values must be a tuple",
1027            span,
1028            "wrap these values in parentheses",
1029        )
1030        .with_parse_code("bare_multi_value_return")
1031        .with_help(format!(
1032            "To return multiple values, use a tuple: `{suggestion}`"
1033        ));
1034
1035        self.errors.push(error);
1036    }
1037
1038    fn error_match_arm_missing_comma(&mut self, span: Span) {
1039        if self.too_many_errors() {
1040            return;
1041        }
1042        let error = ParseError::new("Missing comma after match arm", span, "expected `,`")
1043            .with_parse_code("match_arm_missing_comma")
1044            .with_help("Match arms must be separated by commas, even when the body is a block.");
1045
1046        self.errors.push(error);
1047    }
1048
1049    fn error_map_literal_not_supported(&mut self, span: Span) {
1050        if self.too_many_errors() {
1051            return;
1052        }
1053        let error = ParseError::new("Invalid `Map` initialization", span, "invalid syntax")
1054            .with_parse_code("invalid_map_initialization")
1055            .with_help("To initialize a `Map`, use `Map.new<K, V>()` then `m[key] = value`");
1056
1057        self.errors.push(error);
1058    }
1059
1060    fn error_missing_initializer(&mut self, span: Span) {
1061        if self.too_many_errors() {
1062            return;
1063        }
1064        let error = ParseError::new(
1065            "Missing initializer",
1066            span,
1067            "annotated binding needs a value",
1068        )
1069        .with_parse_code("missing_initializer")
1070        .with_help("Bindings must be initialized");
1071
1072        self.errors.push(error);
1073    }
1074
1075    fn track_ensure_error(&mut self, expected_token: TokenKind) {
1076        if self.too_many_errors() {
1077            return;
1078        }
1079        let current = self.current_token();
1080
1081        let error_code = match expected_token {
1082            Semicolon => "missing_semicolon",
1083            RightCurlyBrace => "unclosed_block",
1084            _ => "unexpected_token",
1085        };
1086
1087        let span = Span::new(self.file_id, current.byte_offset, current.byte_length);
1088        let error = ParseError::new("Syntax error", span, format!("expected {}", expected_token))
1089            .with_parse_code(error_code);
1090
1091        self.errors.push(error);
1092    }
1093
1094    fn close_brace_span(&mut self, start: Token<'source>, error_anchor: Token<'source>) -> Span {
1095        if self.is(RightCurlyBrace) {
1096            let close = self.current_token();
1097            self.next();
1098            let end = close.byte_offset + close.byte_length;
1099            Span::new(
1100                self.file_id,
1101                start.byte_offset,
1102                end.saturating_sub(start.byte_offset),
1103            )
1104        } else {
1105            self.error_unclosed_block(&error_anchor);
1106            self.span_from_offset(start.byte_offset)
1107        }
1108    }
1109
1110    fn error_unclosed_block(&mut self, open_brace: &Token) {
1111        let span = Span::new(self.file_id, open_brace.byte_offset, open_brace.byte_length);
1112        let error = ParseError::new("Unclosed block", span, "opening brace here")
1113            .with_parse_code("unclosed_block")
1114            .with_help("Add a closing `}`");
1115
1116        self.errors.push(error);
1117    }
1118
1119    fn error_tuple_arity(&mut self, arity: usize, span: Span) {
1120        let help = if arity == 0 {
1121            "Use `()` for unit type".to_string()
1122        } else if arity == 1 {
1123            "Use the type directly without wrapping in a tuple".to_string()
1124        } else {
1125            "For more than 5 elements, use a struct with named fields".to_string()
1126        };
1127
1128        let error = ParseError::new(
1129            "Invalid tuple",
1130            span,
1131            format!("{}-element tuple not allowed", arity),
1132        )
1133        .with_parse_code("tuple_element_count")
1134        .with_help(help);
1135
1136        self.errors.push(error);
1137    }
1138
1139    fn error_duplicate_field_in_pattern(
1140        &mut self,
1141        field_name: &str,
1142        first_span: Span,
1143        second_span: Span,
1144    ) {
1145        let error = ParseError::new(
1146            "Duplicate field",
1147            first_span,
1148            format!("first use of `{}`", field_name),
1149        )
1150        .with_span_label(second_span, "used again")
1151        .with_parse_code("duplicate_field_in_pattern")
1152        .with_help("Remove the duplicate binding");
1153
1154        self.errors.push(error);
1155    }
1156
1157    fn error_duplicate_embed_parent(&mut self, first_span: Span, second_span: Span) {
1158        let error = ParseError::new("Duplicate embed", first_span, "first use")
1159            .with_span_label(second_span, "used again")
1160            .with_parse_code("duplicate_embed_parent")
1161            .with_help("Remove the duplicate parent");
1162
1163        self.errors.push(error);
1164    }
1165
1166    fn error_impl_interface_embed(&mut self, keyword_span: Span) {
1167        let error = ParseError::new(
1168            "Interface embedding uses `embed`",
1169            keyword_span,
1170            "write `embed` here",
1171        )
1172        .with_parse_code("impl_interface_embed")
1173        .with_help("Replace `impl` with `embed`. Interfaces embed other interfaces with `embed`");
1174
1175        self.errors.push(error);
1176    }
1177
1178    fn error_duplicate_struct_field(&mut self, name: &str, first_span: Span, second_span: Span) {
1179        let error = ParseError::new("Duplicate field", first_span, "first defined")
1180            .with_span_label(second_span, "defined again")
1181            .with_parse_code("duplicate_struct_field")
1182            .with_help(format!("Remove the duplicate field `{}`", name));
1183
1184        self.errors.push(error);
1185    }
1186
1187    fn error_duplicate_enum_variant(&mut self, name: &str, first_span: Span, second_span: Span) {
1188        let error = ParseError::new("Duplicate variant", first_span, "first defined")
1189            .with_span_label(second_span, "defined again")
1190            .with_parse_code("duplicate_enum_variant")
1191            .with_help(format!("Remove the duplicate variant `{}`", name));
1192
1193        self.errors.push(error);
1194    }
1195
1196    fn error_duplicate_interface_method(
1197        &mut self,
1198        name: &str,
1199        first_span: Span,
1200        second_span: Span,
1201    ) {
1202        let error = ParseError::new("Duplicate method", first_span, "first defined")
1203            .with_span_label(second_span, "defined again")
1204            .with_parse_code("duplicate_interface_method")
1205            .with_help(format!("Remove the duplicate method `{}`", name));
1206
1207        self.errors.push(error);
1208    }
1209
1210    fn error_float_pattern_not_allowed(&mut self, span: Span, float_text: &str) {
1211        let error = ParseError::new("Invalid pattern", span, "float literal not allowed here")
1212            .with_parse_code("float_pattern")
1213            .with_help(format!(
1214                "Use a guard instead: `x if x == {} =>`",
1215                float_text
1216            ));
1217
1218        self.errors.push(error);
1219    }
1220
1221    fn error_uppercase_binding(&mut self, span: Span) {
1222        let error = ParseError::new("Invalid binding name", span, "uppercase not allowed here")
1223            .with_parse_code("uppercase_binding")
1224            .with_help("Lowercase the binding");
1225
1226        self.errors.push(error);
1227    }
1228
1229    fn error_detached_doc_comment(&mut self, span: Span) {
1230        let error = ParseError::new("Unattached doc comment", span, "is detached")
1231            .with_parse_code("detached_doc_comment")
1232            .with_help(
1233                "Place doc comments `///` on the line above a symbol definition and file comments `//!` at the very top of the file",
1234            );
1235
1236        self.errors.push(error);
1237    }
1238
1239    fn error_split_file_comment(&mut self, span: Span) {
1240        let error = ParseError::new("Split file comment", span, "separated from the block above")
1241            .with_parse_code("split_file_comment")
1242            .with_help(
1243                "Remove the blank line, or write a bare `//!` line to keep a visible gap in the emitted header",
1244            );
1245
1246        self.errors.push(error);
1247    }
1248
1249    fn error_file_comment_build_constraint(&mut self, span: Span) {
1250        let error = ParseError::new(
1251            "Invalid file comment",
1252            span,
1253            "would become a Go build constraint",
1254        )
1255        .with_parse_code("file_comment_build_constraint")
1256        .with_help(
1257            "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",
1258        );
1259
1260        self.errors.push(error);
1261    }
1262
1263    fn error_misplaced_file_comment(&mut self) {
1264        let first = self.current_token();
1265        let mut last = first;
1266
1267        while self.is(FileComment) {
1268            last = self.current_token();
1269            self.stream.consume();
1270            while self.is(Comment) {
1271                self.stream.consume();
1272            }
1273        }
1274
1275        let length = last.byte_offset + last.byte_length - first.byte_offset;
1276        self.error_misplaced_file_comment_at(Span::new(self.file_id, first.byte_offset, length));
1277    }
1278
1279    fn error_misplaced_file_comment_at(&mut self, span: Span) {
1280        let error = ParseError::new("Misplaced file comment", span, "not allowed here")
1281            .with_parse_code("misplaced_file_comment")
1282            .with_help(
1283                "Move this file comment to the very top of the file to document it, or use `///` to document the symbol below",
1284            );
1285
1286        self.errors.push(error);
1287    }
1288
1289    fn error_import_after_item(&mut self, statement: Span, path: Span) {
1290        let span = Span::new(
1291            statement.file_id,
1292            statement.byte_offset,
1293            path.end() - statement.byte_offset,
1294        );
1295        let error = ParseError::new("Misplaced import", span, "not allowed here")
1296            .with_parse_code("import_after_item")
1297            .with_help(
1298                "Move this import to the top of the file, or run `lis format` to hoist it. Imports must come before every other top-level item",
1299            );
1300
1301        self.errors.push(error);
1302    }
1303
1304    fn error_misplaced_pub(&mut self, span: Span, code: &str, help: &str) {
1305        let error = ParseError::new("Misplaced `pub`", span, "not allowed here")
1306            .with_parse_code(code)
1307            .with_help(help);
1308
1309        self.errors.push(error);
1310    }
1311
1312    fn error_misplaced_attribute(&mut self, span: Span) {
1313        let error = ParseError::new(
1314            "Attribute not supported on target",
1315            span,
1316            "nothing here can carry an attribute",
1317        )
1318        .with_parse_code("misplaced_attribute")
1319        .with_help("Remove the attribute, or move it onto an enum, struct, or function");
1320
1321        self.errors.push(error);
1322    }
1323
1324    fn error_interface_method_with_type_parameters(&mut self, span: Span, count: usize) {
1325        let label = if count == 1 {
1326            "type parameter not allowed"
1327        } else {
1328            "type parameters not allowed"
1329        };
1330        let error = ParseError::new("Invalid interface method", span, label)
1331            .with_parse_code("interface_method_with_type_parameters")
1332            .with_help(
1333                "Interface methods cannot have type parameters, because Go interfaces do not support generic methods",
1334            );
1335
1336        self.errors.push(error);
1337    }
1338
1339    fn error_leading_zero(&mut self) {
1340        let span = self.span_from_token(self.current_token());
1341        let error = ParseError::new(
1342            "Invalid number literal",
1343            span,
1344            "leading zero in integer literal",
1345        )
1346        .with_parse_code("number_leading_zero")
1347        .with_help("Prefix with `0o` for octal (e.g. `0o644`) or remove the leading zero");
1348        self.errors.push(error);
1349    }
1350
1351    fn parse_integer_text(&mut self, text: &str) -> ast::Literal {
1352        self.parse_integer_text_with(text, false)
1353    }
1354
1355    fn parse_expression_integer_text(&mut self, text: &str) -> ast::Literal {
1356        let leading_zero =
1357            text.len() > 1 && text.starts_with('0') && text.as_bytes()[1].is_ascii_digit();
1358        if constant::exceeds_u64(text) && !leading_zero {
1359            return ast::Literal::Integer {
1360                value: u64::MAX,
1361                text: Some(text.to_string()),
1362            };
1363        }
1364        self.parse_integer_text(text)
1365    }
1366
1367    fn parse_integer_text_with(&mut self, text: &str, preserve_decimal_text: bool) -> ast::Literal {
1368        let clean = if text.contains('_') {
1369            Cow::Owned(text.replace('_', ""))
1370        } else {
1371            Cow::Borrowed(text)
1372        };
1373
1374        let (n, is_decimal) = if clean.starts_with("0x") || clean.starts_with("0X") {
1375            let value = u64::from_str_radix(&clean[2..], 16).unwrap_or_else(|_| {
1376                self.track_coded_error(
1377                    "Literal out of range",
1378                    "literal_out_of_range",
1379                    format!("hex literal '{text}' is too large"),
1380                    "Maximum value is `0xFFFFFFFFFFFFFFFF`.",
1381                );
1382                0
1383            });
1384            (value, false)
1385        } else if clean.starts_with("0o") || clean.starts_with("0O") {
1386            let value = u64::from_str_radix(&clean[2..], 8).unwrap_or_else(|_| {
1387                self.track_coded_error(
1388                    "Literal out of range",
1389                    "literal_out_of_range",
1390                    format!("octal literal '{text}' is too large"),
1391                    "Maximum value is `0o1777777777777777777777`.",
1392                );
1393                0
1394            });
1395            (value, false)
1396        } else if clean.starts_with("0b") || clean.starts_with("0B") {
1397            let value = u64::from_str_radix(&clean[2..], 2).unwrap_or_else(|_| {
1398                self.track_coded_error(
1399                    "Literal out of range",
1400                    "literal_out_of_range",
1401                    format!("binary literal '{text}' is too large"),
1402                    "Value must fit in 64 bits.",
1403                );
1404                0
1405            });
1406            (value, false)
1407        } else if clean.len() > 1 && clean.starts_with('0') {
1408            self.error_leading_zero();
1409            (clean.parse().unwrap_or(0), false)
1410        } else {
1411            let value = clean.parse().unwrap_or_else(|_| {
1412                self.track_coded_error(
1413                    "Literal out of range",
1414                    "literal_out_of_range",
1415                    format!("integer literal '{text}' is too large"),
1416                    "Maximum value is `18446744073709551615`.",
1417                );
1418                0
1419            });
1420            (value, true)
1421        };
1422
1423        let original_text = if is_decimal && !preserve_decimal_text {
1424            None
1425        } else {
1426            Some(text.to_string())
1427        };
1428
1429        ast::Literal::Integer {
1430            value: n,
1431            text: original_text,
1432        }
1433    }
1434
1435    fn unexpected_token(&mut self, ctx: &str) -> ast::Expression {
1436        let token = self.current_token();
1437        let token_descriptor = match token.kind {
1438            _ if !token.text.is_empty() => format!("`{}`", token.text),
1439            Semicolon => "end of line".to_string(),
1440            kind => kind.to_string(),
1441        };
1442
1443        let span = Span::new(self.file_id, token.byte_offset, token.byte_length);
1444
1445        let (label, error_code, help) = match ctx {
1446            "expr" => (
1447                format!("expected expression, found {}", token_descriptor),
1448                "expected_expression",
1449                None,
1450            ),
1451            "pattern" => (
1452                format!("unexpected {} in pattern", token_descriptor),
1453                "invalid_pattern",
1454                Some("Patterns include literals, variables, and destructuring."),
1455            ),
1456            "literal" => (
1457                format!("expected literal, found {}", token_descriptor),
1458                "expected_literal",
1459                Some("Literals include numbers, strings, characters, and booleans."),
1460            ),
1461            "top_item" if token.text == "trait" => (
1462                format!("unexpected {}", token_descriptor),
1463                "trait_unsupported",
1464                Some(
1465                    "Lisette uses `interface` in place of `trait`. Types automatically satisfy interfaces if they have the required methods.",
1466                ),
1467            ),
1468            "top_item" if token.text == "use" => (
1469                "unexpected syntax for import".to_string(),
1470                "use_unsupported",
1471                Some("Use `import` instead of `use` for imports: `import \"package/path\"`"),
1472            ),
1473            "top_item" if token.kind == Let => (
1474                "`let` is not allowed at the top level".to_string(),
1475                "top_level_let",
1476                Some(
1477                    "Use `const` for a primitive value. For a composite value, use a function that returns it, e.g. `fn origin() -> Point { ... }`",
1478                ),
1479            ),
1480            "top_item" => (
1481                "expected declaration".to_string(),
1482                "expected_declaration",
1483                Some(
1484                    "At the top level of a file, Lisette expects `fn`, `struct`, `enum`, `interface`, `impl`, `const`, `import`, or `type`.",
1485                ),
1486            ),
1487            _ => (
1488                format!("unexpected {}", token_descriptor),
1489                "unexpected_token",
1490                None,
1491            ),
1492        };
1493
1494        let mut error = ParseError::new("Syntax error", span, label).with_parse_code(error_code);
1495        if let Some(help) = help {
1496            error = error.with_help(help);
1497        }
1498
1499        if !self.too_many_errors() {
1500            self.errors.push(error);
1501        }
1502
1503        self.resync_on_error();
1504
1505        self.error_expression(span)
1506    }
1507
1508    fn error_expression(&mut self, span: Span) -> ast::Expression {
1509        ast::Expression::Unit {
1510            id: self.next_expression_id(),
1511            ty: Type::error(ErrorReported::unchecked()),
1512            span,
1513        }
1514    }
1515}
1516
1517fn is_go_build_constraint(text: &str) -> bool {
1518    text.split_whitespace().next() == Some("+build")
1519}
1520
1521struct TokenStream<'source> {
1522    tokens: Vec<Token<'source>>,
1523    position: usize,
1524}
1525
1526impl<'source> TokenStream<'source> {
1527    fn new(tokens: Vec<Token<'source>>) -> Self {
1528        debug_assert!(
1529            !tokens.is_empty(),
1530            "lexer must always produce at least an EOF token",
1531        );
1532        Self {
1533            tokens,
1534            position: 0,
1535        }
1536    }
1537
1538    fn peek(&self) -> Token<'source> {
1539        self.tokens[self.position]
1540    }
1541
1542    fn peek_ahead(&self, n: usize) -> Token<'source> {
1543        let last_index = self.tokens.len() - 1;
1544        let idx = self.position.saturating_add(n).min(last_index);
1545        self.tokens[idx]
1546    }
1547
1548    fn read_keyword_as_qualifier(&mut self, keyword: &str) {
1549        for index in self.position..self.tokens.len().saturating_sub(1) {
1550            let next = self.tokens[index + 1];
1551            let token = &mut self.tokens[index];
1552            if token.text == keyword && next.kind == Dot && next.byte_offset == token.end_offset() {
1553                token.kind = Identifier;
1554            }
1555        }
1556    }
1557
1558    fn previous(&self) -> Token<'source> {
1559        self.tokens[self.position.saturating_sub(1)]
1560    }
1561
1562    fn previous_code(&self) -> Token<'source> {
1563        let mut index = self.position.saturating_sub(1);
1564
1565        while index > 0 && matches!(self.tokens[index].kind, Comment | DocComment | FileComment) {
1566            index -= 1;
1567        }
1568
1569        self.tokens[index]
1570    }
1571
1572    fn consume(&mut self) -> Token<'source> {
1573        let token = self.tokens[self.position];
1574        if self.position + 1 < self.tokens.len() {
1575            self.position += 1;
1576        }
1577        token
1578    }
1579
1580    fn consume_right_angle(&mut self) -> Option<Token<'source>> {
1581        let token = self.peek();
1582        match token.kind {
1583            RightAngleBracket => Some(self.consume()),
1584            ShiftRight => {
1585                let first = Token {
1586                    kind: RightAngleBracket,
1587                    text: ">",
1588                    byte_offset: token.byte_offset,
1589                    byte_length: 1,
1590                };
1591                let second = Token {
1592                    byte_offset: token.byte_offset + 1,
1593                    ..first
1594                };
1595                self.tokens[self.position] = first;
1596                self.tokens.insert(self.position + 1, second);
1597                Some(self.consume())
1598            }
1599            _ => None,
1600        }
1601    }
1602}
1603
1604#[cfg(test)]
1605mod import_order_tests {
1606    use super::IMPORT_AFTER_ITEM_CODE;
1607    use crate::ast::Expression;
1608    use crate::build_ast;
1609
1610    fn codes(source: &str) -> Vec<String> {
1611        build_ast(source, 0)
1612            .errors
1613            .iter()
1614            .map(|error| error.code.clone())
1615            .collect()
1616    }
1617
1618    #[test]
1619    fn imports_before_every_other_item_are_allowed() {
1620        for source in [
1621            "import \"go:fmt\"\nimport _ \"go:os\"\nimport alias \"go:io\"\nfn f() {}",
1622            "//! header\n\nimport \"go:fmt\"\n\nfn f() {}",
1623            "// note\nimport \"go:fmt\"\n\n/// docs\nfn f() {}",
1624            "import \"go:fmt\"\n\n#[test]\nfn f(t: T) {}",
1625            "import \"go:fmt\"",
1626        ] {
1627            assert!(codes(source).is_empty(), "for source: {source:?}");
1628        }
1629    }
1630
1631    #[test]
1632    fn a_public_import_is_rejected() {
1633        for source in [
1634            "pub import \"go:fmt\"",
1635            "pub import _ \"go:fmt\"",
1636            "pub import alias \"go:fmt\"",
1637            "pub // note\nimport \"go:fmt\"",
1638            "import \"go:os\"\npub import \"go:fmt\"\nfn f() {}",
1639        ] {
1640            assert_eq!(
1641                codes(source),
1642                ["parse.pub_import"],
1643                "for source: {source:?}"
1644            );
1645        }
1646    }
1647
1648    #[test]
1649    fn visibility_on_definitions_is_untouched() {
1650        for source in [
1651            "pub fn f() {}",
1652            "pub struct S {}",
1653            "pub enum E { A }",
1654            "pub const N: int = 1",
1655            "pub type T = int",
1656            "pub interface I {}",
1657        ] {
1658            assert!(codes(source).is_empty(), "for source: {source:?}");
1659        }
1660    }
1661
1662    #[test]
1663    fn import_after_a_definition_is_rejected() {
1664        for source in [
1665            "fn f() {}\nimport \"go:fmt\"",
1666            "struct S {}\nimport _ \"go:fmt\"",
1667            "const N: int = 1\nimport alias \"go:fmt\"",
1668            "type T = int\nimport \"go:fmt\"",
1669            "import \"go:os\"\nfn f() {}\nimport \"go:fmt\"",
1670        ] {
1671            assert_eq!(
1672                codes(source),
1673                [IMPORT_AFTER_ITEM_CODE],
1674                "for source: {source:?}"
1675            );
1676        }
1677    }
1678
1679    #[test]
1680    fn every_misplaced_import_is_reported() {
1681        let source = "fn f() {}\nimport \"go:fmt\"\nimport \"go:os\"";
1682        assert_eq!(
1683            codes(source),
1684            [IMPORT_AFTER_ITEM_CODE, IMPORT_AFTER_ITEM_CODE]
1685        );
1686    }
1687
1688    #[test]
1689    fn a_misplaced_import_still_reaches_the_ast() {
1690        let result = super::Parser::lex_and_parse_file("fn f() {}\nimport \"go:fmt\"", 0);
1691        assert!(matches!(
1692            result.ast.last(),
1693            Some(Expression::PackageImport { .. })
1694        ));
1695    }
1696
1697    #[test]
1698    fn a_parse_stopped_by_the_error_cap_is_truncated() {
1699        let mut source = String::from("fn f() {}\n");
1700        for index in 0..60 {
1701            source.push_str(&format!("import \"go:pkg{index}\"\n"));
1702        }
1703        source.push_str("fn last() {}\n");
1704
1705        let result = super::Parser::lex_and_parse_file(&source, 0);
1706        assert!(result.truncated);
1707        assert!(!result.ast.iter().any(|item| matches!(
1708            item,
1709            Expression::Function { name, .. } if name == "last"
1710        )));
1711    }
1712
1713    #[test]
1714    fn a_parse_that_reaches_the_end_is_not_truncated() {
1715        let result = super::Parser::lex_and_parse_file("fn f() {}\nimport \"go:fmt\"", 0);
1716        assert!(!result.truncated);
1717    }
1718
1719    #[test]
1720    fn an_import_inside_a_block_keeps_its_own_error() {
1721        let source = "fn f() {\n  import \"go:fmt\"\n}";
1722        assert_eq!(codes(source), ["parse.nested_definition"]);
1723    }
1724
1725    #[test]
1726    fn comments_between_imports_do_not_count_as_items() {
1727        let source = "import \"go:fmt\"\n// note\n\n// another note\nimport \"go:os\"\nfn f() {}";
1728        assert!(codes(source).is_empty());
1729    }
1730}
1731
1732#[cfg(test)]
1733mod unexpected_token_tests {
1734    use crate::build_ast;
1735
1736    #[test]
1737    fn inserted_semicolon_reads_as_end_of_line() {
1738        let source = "fn foo(a: int, b: int) -> int { a + b }\nfn main() {\n  let x = foo([]int(1), 2)\n  let y = 3\n}\n";
1739        let labels: Vec<String> = build_ast(source, 0)
1740            .errors
1741            .into_iter()
1742            .flat_map(|error| error.labels)
1743            .map(|(_, label)| label)
1744            .collect();
1745        assert!(
1746            labels
1747                .iter()
1748                .any(|label| label == "expected expression, found end of line"),
1749            "{labels:?}"
1750        );
1751        assert!(!labels.iter().any(|label| label.contains("Semicolon")));
1752    }
1753}
1754
1755#[cfg(test)]
1756mod file_comment_tests {
1757    use crate::build_ast;
1758
1759    fn file_comment(source: &str) -> Option<String> {
1760        let result = build_ast(source, 0);
1761        assert!(
1762            result.errors.is_empty(),
1763            "unexpected errors: {:?}",
1764            result.errors
1765        );
1766        result.file_comment
1767    }
1768
1769    #[test]
1770    fn consecutive_lines_join_with_newlines() {
1771        assert_eq!(
1772            file_comment("//! a\n//! b\nfn f() {}").as_deref(),
1773            Some("a\nb")
1774        );
1775    }
1776
1777    #[test]
1778    fn bare_line_contributes_empty_line() {
1779        assert_eq!(
1780            file_comment("//! a\n//!\n//! b\nfn f() {}").as_deref(),
1781            Some("a\n\nb")
1782        );
1783    }
1784
1785    #[test]
1786    fn blank_line_between_runs_is_an_error() {
1787        for source in [
1788            "//! a\n\n//! b\n\nfn f() {}",
1789            "//! a\r\n\r\n//! b\r\n\r\nfn f() {}",
1790            "//! a\n//!\n\n//! b\nfn f() {}",
1791        ] {
1792            let result = build_ast(source, 0);
1793            let codes: Vec<_> = result.errors.iter().map(|e| e.code.as_str()).collect();
1794            assert_eq!(
1795                codes,
1796                ["parse.split_file_comment"],
1797                "for source: {source:?}"
1798            );
1799        }
1800    }
1801
1802    #[test]
1803    fn anything_before_the_block_is_rejected() {
1804        for source in ["\n//! a\nfn f() {}", " //! a\nfn f() {}"] {
1805            let result = build_ast(source, 0);
1806            let codes: Vec<_> = result.errors.iter().map(|e| e.code.as_str()).collect();
1807            assert_eq!(
1808                codes,
1809                ["parse.misplaced_file_comment"],
1810                "for source: {source:?}"
1811            );
1812        }
1813    }
1814
1815    #[test]
1816    fn blank_lines_after_the_block_are_allowed() {
1817        assert_eq!(
1818            file_comment("//! a\n//! b\n\n\nfn f() {}").as_deref(),
1819            Some("a\nb")
1820        );
1821    }
1822
1823    #[test]
1824    fn leading_comment_makes_the_header_misplaced() {
1825        let result = build_ast("// leading\n//! too late\nfn f() {}", 0);
1826        let codes: Vec<_> = result.errors.iter().map(|e| e.code.as_str()).collect();
1827        assert_eq!(codes, ["parse.misplaced_file_comment"]);
1828    }
1829
1830    #[test]
1831    fn interleaved_comment_ends_the_block() {
1832        let result = build_ast("//! a\n// note\n//! b\nfn f() {}", 0);
1833        let codes: Vec<_> = result.errors.iter().map(|e| e.code.as_str()).collect();
1834        assert_eq!(codes, ["parse.misplaced_file_comment"]);
1835    }
1836
1837    #[test]
1838    fn comment_after_the_block_is_allowed() {
1839        assert_eq!(
1840            file_comment("//! a\n\n// section note\nfn f() {}").as_deref(),
1841            Some("a")
1842        );
1843    }
1844
1845    #[test]
1846    fn file_without_header_has_no_file_comment() {
1847        assert_eq!(file_comment("fn f() {}"), None);
1848    }
1849
1850    #[test]
1851    fn header_without_items_is_valid() {
1852        assert_eq!(
1853            file_comment("//! header only").as_deref(),
1854            Some("header only")
1855        );
1856    }
1857
1858    #[test]
1859    fn header_before_doc_commented_item() {
1860        let result = build_ast("//! header\n/// item doc\nfn f() {}", 0);
1861        assert!(result.errors.is_empty(), "{:?}", result.errors);
1862        assert_eq!(result.file_comment.as_deref(), Some("header"));
1863    }
1864
1865    #[test]
1866    fn misplaced_file_comment_reports_one_error_per_run() {
1867        let result = build_ast("fn f() {}\n//! a\n//! b\nfn g() {}", 0);
1868        let codes: Vec<_> = result.errors.iter().map(|e| e.code.as_str()).collect();
1869        assert_eq!(codes, ["parse.misplaced_file_comment"]);
1870    }
1871
1872    #[test]
1873    fn build_constraint_lines_are_rejected() {
1874        for source in [
1875            "//!+build ignore\nfn f() {}",
1876            "//! +build ignore\nfn f() {}",
1877            "//!  \t+build linux\nfn f() {}",
1878            "//! +build\nfn f() {}",
1879            "//! +build ignore\r\nfn f() {}",
1880            "//! +build\r\nfn f() {}",
1881            "//!\u{00A0}+build ignore\nfn f() {}",
1882            "//! +build\u{00A0}ignore\nfn f() {}",
1883            "//! +build\u{3000}ignore\nfn f() {}",
1884        ] {
1885            let result = build_ast(source, 0);
1886            let codes: Vec<_> = result.errors.iter().map(|e| e.code.as_str()).collect();
1887            assert_eq!(
1888                codes,
1889                ["parse.file_comment_build_constraint"],
1890                "for source: {source:?}"
1891            );
1892        }
1893    }
1894
1895    #[test]
1896    fn build_constraint_lookalikes_are_allowed() {
1897        for source in [
1898            "//! +buildx tag\nfn f() {}",
1899            "//! use +build wisely\nfn f() {}",
1900            "//! +builder pattern\nfn f() {}",
1901        ] {
1902            let result = build_ast(source, 0);
1903            assert!(result.errors.is_empty(), "for source: {source:?}");
1904        }
1905    }
1906}