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