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