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            return None;
737        }
738        self.depth += 1;
739        Some(RecursionScope {
740            parser: self,
741            previous_depth,
742        })
743    }
744
745    fn deepen(&mut self) -> bool {
746        if self.depth >= MAX_DEPTH {
747            let span = self.span_from_token(self.current_token());
748            self.track_error_at(span, "too deeply nested", "Reduce nesting depth");
749            return false;
750        }
751        self.depth += 1;
752        true
753    }
754
755    fn too_many_errors(&self) -> bool {
756        self.errors.len() >= MAX_ERRORS
757    }
758
759    fn position(&self) -> u32 {
760        self.current_token().byte_offset
761    }
762
763    fn at_sync_point(&self) -> bool {
764        matches!(
765            self.current_token().kind,
766            Semicolon
767                | RightCurlyBrace
768                | RightParen
769                | RightSquareBracket
770                | Comma
771                | Let
772                | For
773                | While
774                | Loop
775                | If
776                | Match
777                | Return
778                | Break
779                | Continue
780                | Defer
781                | Assert
782                | Task
783                | Try
784                | Recover
785                | Select
786                | Function
787                | Struct
788                | Enum
789                | Const
790                | Impl
791                | Interface
792                | Type
793                | Import
794        )
795    }
796
797    fn can_start_annotation(&self) -> bool {
798        matches!(
799            self.current_token().kind,
800            Identifier | Function | LeftParen | Integer | Mut
801        )
802    }
803
804    fn can_recover_annotation(&self) -> bool {
805        !self.at_recovery_boundary() && self.can_start_annotation()
806    }
807
808    fn at_recovery_boundary(&self) -> bool {
809        if self.is(Function) {
810            return self.at_function_declaration();
811        }
812        matches!(self.current_token().kind, DocComment | Hash | Pub) || self.at_item_boundary()
813    }
814
815    fn at_parameter_recovery_boundary(&self) -> bool {
816        self.at_recovery_boundary() && self.stream.peek_ahead(1).kind != Colon
817    }
818
819    fn at_function_declaration(&self) -> bool {
820        self.is(Function)
821            && self.stream.peek_ahead(1).kind == Identifier
822            && matches!(
823                self.stream.peek_ahead(2).kind,
824                LeftParen | LeftAngleBracket | Dot
825            )
826    }
827
828    fn at_item_boundary(&self) -> bool {
829        matches!(
830            self.current_token().kind,
831            Let | Function | Struct | Enum | Impl | Interface | Type | Const | Import
832        )
833    }
834
835    fn at_match_arm_terminator(&self) -> bool {
836        self.at_eof() || self.is(Comma) || self.is(RightCurlyBrace) || self.at_item_boundary()
837    }
838
839    fn resync_on_error(&mut self) {
840        while !self.at_sync_point() && !self.at_eof() {
841            self.next();
842        }
843    }
844
845    fn track_error(&mut self, label: impl Into<string::String>, help: impl Into<string::String>) {
846        let current = self.current_token();
847        let span = Span::new(self.file_id, current.byte_offset, current.byte_length);
848        self.track_error_at(span, label, help);
849    }
850
851    fn track_error_at(
852        &mut self,
853        span: Span,
854        label: impl Into<string::String>,
855        help: impl Into<string::String>,
856    ) {
857        if self.too_many_errors() {
858            return;
859        }
860        let error = ParseError::new("Syntax error", span, label.into())
861            .with_parse_code("syntax_error")
862            .with_help(help.into());
863
864        self.errors.push(error);
865    }
866
867    fn error_angle_brackets_for_generics(&mut self, span: Span, help: impl Into<string::String>) {
868        if self.too_many_errors() {
869            return;
870        }
871        let error = ParseError::new("Syntax error", span, "use `<...>` for type args")
872            .with_parse_code("angle_brackets_for_generics")
873            .with_help(help.into());
874
875        self.errors.push(error);
876    }
877
878    fn error_var_initializer(&mut self, span: Span) {
879        if self.too_many_errors() {
880            return;
881        }
882        let error = ParseError::new("Syntax error", span, "not allowed")
883            .with_parse_code("var_not_allowed")
884            .with_help(
885                "Use `const` for a primitive, or a function that returns the value e.g. `fn origin() -> Point { ... }` for a composite",
886            );
887
888        self.errors.push(error);
889    }
890
891    fn error_import_alias_after_path(&mut self, span: Span, alias: &str, path: &str) {
892        if self.too_many_errors() {
893            return;
894        }
895        let error = ParseError::new("Syntax error", span, "import alias goes before the path")
896            .with_parse_code("import_alias_position")
897            .with_help(format!(
898                "Use Go-style alias syntax: `import {alias} \"{path}\"`"
899            ));
900
901        self.errors.push(error);
902    }
903
904    fn error_bare_multi_return(&mut self, span: Span, suggestion: &str) {
905        if self.too_many_errors() {
906            return;
907        }
908        let error = ParseError::new(
909            "Multiple return values must be a tuple",
910            span,
911            "wrap these values in parentheses",
912        )
913        .with_parse_code("bare_multi_value_return")
914        .with_help(format!(
915            "To return multiple values, use a tuple: `{suggestion}`"
916        ));
917
918        self.errors.push(error);
919    }
920
921    fn error_match_arm_missing_comma(&mut self, span: Span) {
922        if self.too_many_errors() {
923            return;
924        }
925        let error = ParseError::new("Syntax error", span, "missing comma after match arm")
926            .with_parse_code("match_arm_missing_comma")
927            .with_help("Match arms must be separated by commas, even when the body is a block.");
928
929        self.errors.push(error);
930    }
931
932    fn error_map_literal_not_supported(&mut self, span: Span) {
933        if self.too_many_errors() {
934            return;
935        }
936        let error = ParseError::new("Invalid `Map` initialization", span, "invalid syntax")
937            .with_parse_code("invalid_map_initialization")
938            .with_help("To initialize a `Map`, use `Map.new<K, V>()` then `m[key] = value`");
939
940        self.errors.push(error);
941    }
942
943    fn error_missing_initializer(&mut self, span: Span) {
944        if self.too_many_errors() {
945            return;
946        }
947        let error = ParseError::new(
948            "Missing initializer",
949            span,
950            "annotated binding needs a value",
951        )
952        .with_parse_code("missing_initializer")
953        .with_help("Bindings must be initialized");
954
955        self.errors.push(error);
956    }
957
958    fn track_ensure_error(&mut self, expected_token: TokenKind) {
959        if self.too_many_errors() {
960            return;
961        }
962        let current = self.current_token();
963
964        let error_code = match expected_token {
965            Semicolon => "missing_semicolon",
966            RightCurlyBrace => "unclosed_block",
967            _ => "unexpected_token",
968        };
969
970        let span = Span::new(self.file_id, current.byte_offset, current.byte_length);
971        let error = ParseError::new("Syntax error", span, format!("expected {}", expected_token))
972            .with_parse_code(error_code);
973
974        self.errors.push(error);
975    }
976
977    fn close_brace_span(&mut self, start: Token<'source>, error_anchor: Token<'source>) -> Span {
978        if self.is(RightCurlyBrace) {
979            let close = self.current_token();
980            self.next();
981            let end = close.byte_offset + close.byte_length;
982            Span::new(
983                self.file_id,
984                start.byte_offset,
985                end.saturating_sub(start.byte_offset),
986            )
987        } else {
988            self.error_unclosed_block(&error_anchor);
989            self.span_from_offset(start.byte_offset)
990        }
991    }
992
993    fn error_unclosed_block(&mut self, open_brace: &Token) {
994        let span = Span::new(self.file_id, open_brace.byte_offset, open_brace.byte_length);
995        let error = ParseError::new("Unclosed block", span, "opening brace here")
996            .with_parse_code("unclosed_block")
997            .with_help("Add a closing `}`");
998
999        self.errors.push(error);
1000    }
1001
1002    fn error_tuple_arity(&mut self, arity: usize, span: Span) {
1003        let help = if arity == 0 {
1004            "Use `()` for unit type".to_string()
1005        } else if arity == 1 {
1006            "Use the type directly without wrapping in a tuple".to_string()
1007        } else {
1008            "For >5 elements, use a struct with named fields".to_string()
1009        };
1010
1011        let error = ParseError::new(
1012            "Invalid tuple",
1013            span,
1014            format!("{}-element tuple not allowed", arity),
1015        )
1016        .with_parse_code("tuple_element_count")
1017        .with_help(help);
1018
1019        self.errors.push(error);
1020    }
1021
1022    fn error_duplicate_field_in_pattern(
1023        &mut self,
1024        field_name: &str,
1025        first_span: Span,
1026        second_span: Span,
1027    ) {
1028        let error = ParseError::new(
1029            "Duplicate field",
1030            first_span,
1031            format!("first use of `{}`", field_name),
1032        )
1033        .with_span_label(second_span, "used again")
1034        .with_parse_code("duplicate_field_in_pattern")
1035        .with_help("Remove the duplicate binding");
1036
1037        self.errors.push(error);
1038    }
1039
1040    fn error_duplicate_embed_parent(&mut self, first_span: Span, second_span: Span) {
1041        let error = ParseError::new("Duplicate embed", first_span, "first use")
1042            .with_span_label(second_span, "used again")
1043            .with_parse_code("duplicate_embed_parent")
1044            .with_help("Remove the duplicate parent");
1045
1046        self.errors.push(error);
1047    }
1048
1049    fn error_impl_interface_embed(&mut self, keyword_span: Span) {
1050        let error = ParseError::new(
1051            "Interface embedding uses `embed`",
1052            keyword_span,
1053            "write `embed` here",
1054        )
1055        .with_parse_code("impl_interface_embed")
1056        .with_help("Interfaces embed other interfaces with `embed`. Replace `impl` with `embed`");
1057
1058        self.errors.push(error);
1059    }
1060
1061    fn error_duplicate_struct_field(&mut self, name: &str, first_span: Span, second_span: Span) {
1062        let error = ParseError::new("Duplicate field", first_span, "first defined")
1063            .with_span_label(second_span, "defined again")
1064            .with_parse_code("duplicate_struct_field")
1065            .with_help(format!("Remove the duplicate field `{}`", name));
1066
1067        self.errors.push(error);
1068    }
1069
1070    fn error_duplicate_enum_variant(&mut self, name: &str, first_span: Span, second_span: Span) {
1071        let error = ParseError::new("Duplicate variant", first_span, "first defined")
1072            .with_span_label(second_span, "defined again")
1073            .with_parse_code("duplicate_enum_variant")
1074            .with_help(format!("Remove the duplicate variant `{}`", name));
1075
1076        self.errors.push(error);
1077    }
1078
1079    fn error_duplicate_interface_method(
1080        &mut self,
1081        name: &str,
1082        first_span: Span,
1083        second_span: Span,
1084    ) {
1085        let error = ParseError::new("Duplicate method", first_span, "first defined")
1086            .with_span_label(second_span, "defined again")
1087            .with_parse_code("duplicate_interface_method")
1088            .with_help(format!("Remove the duplicate method `{}`", name));
1089
1090        self.errors.push(error);
1091    }
1092
1093    fn error_float_pattern_not_allowed(&mut self, span: Span, float_text: &str) {
1094        let error = ParseError::new("Invalid pattern", span, "float literal not allowed here")
1095            .with_parse_code("float_pattern")
1096            .with_help(format!(
1097                "Use a guard instead: `x if x == {} =>`",
1098                float_text
1099            ));
1100
1101        self.errors.push(error);
1102    }
1103
1104    fn error_uppercase_binding(&mut self, span: Span) {
1105        let error = ParseError::new("Invalid binding name", span, "uppercase not allowed here")
1106            .with_parse_code("uppercase_binding")
1107            .with_help("Lowercase the binding");
1108
1109        self.errors.push(error);
1110    }
1111
1112    fn error_detached_doc_comment(&mut self, span: Span) {
1113        let error = ParseError::new("Unattached doc comment", span, "is detached")
1114            .with_parse_code("detached_doc_comment")
1115            .with_help(
1116                "Place doc comments `///` on the line above a symbol definition and file comments `//!` at the very top of the file",
1117            );
1118
1119        self.errors.push(error);
1120    }
1121
1122    fn error_split_file_comment(&mut self, span: Span) {
1123        let error = ParseError::new("Split file comment", span, "separated from the block above")
1124            .with_parse_code("split_file_comment")
1125            .with_help(
1126                "Remove the blank line, or write a bare `//!` line to keep a visible gap in the emitted header",
1127            );
1128
1129        self.errors.push(error);
1130    }
1131
1132    fn error_file_comment_build_constraint(&mut self, span: Span) {
1133        let error = ParseError::new(
1134            "Invalid file comment",
1135            span,
1136            "would become a Go build constraint",
1137        )
1138        .with_parse_code("file_comment_build_constraint")
1139        .with_help(
1140            "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",
1141        );
1142
1143        self.errors.push(error);
1144    }
1145
1146    fn error_misplaced_file_comment(&mut self) {
1147        let first = self.current_token();
1148        let mut last = first;
1149
1150        while self.is(FileComment) {
1151            last = self.current_token();
1152            self.stream.consume();
1153            while self.is(Comment) {
1154                self.stream.consume();
1155            }
1156        }
1157
1158        let length = last.byte_offset + last.byte_length - first.byte_offset;
1159        self.error_misplaced_file_comment_at(Span::new(self.file_id, first.byte_offset, length));
1160    }
1161
1162    fn error_misplaced_file_comment_at(&mut self, span: Span) {
1163        let error = ParseError::new("Misplaced file comment", span, "not allowed here")
1164            .with_parse_code("misplaced_file_comment")
1165            .with_help(
1166                "Move this file comment to the very top of the file to document it, or use `///` to document the symbol below",
1167            );
1168
1169        self.errors.push(error);
1170    }
1171
1172    fn error_import_after_item(&mut self, statement: Span, path: Span) {
1173        let span = Span::new(
1174            statement.file_id,
1175            statement.byte_offset,
1176            path.end() - statement.byte_offset,
1177        );
1178        let error = ParseError::new("Misplaced import", span, "not allowed here")
1179            .with_parse_code("import_after_item")
1180            .with_help(
1181                "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",
1182            );
1183
1184        self.errors.push(error);
1185    }
1186
1187    fn error_misplaced_pub(&mut self, span: Span, code: &str, help: &str) {
1188        let error = ParseError::new("Misplaced `pub`", span, "not allowed here")
1189            .with_parse_code(code)
1190            .with_help(help);
1191
1192        self.errors.push(error);
1193    }
1194
1195    fn error_misplaced_attribute(&mut self, span: Span) {
1196        let error = ParseError::new(
1197            "Attribute not supported on target",
1198            span,
1199            "nothing here can carry an attribute",
1200        )
1201        .with_parse_code("misplaced_attribute")
1202        .with_help("Remove the attribute, or move it onto an enum, struct, or function");
1203
1204        self.errors.push(error);
1205    }
1206
1207    fn error_interface_method_with_type_parameters(&mut self, span: Span, count: usize) {
1208        let label = if count == 1 {
1209            "type parameter not allowed"
1210        } else {
1211            "type parameters not allowed"
1212        };
1213        let error = ParseError::new("Invalid interface method", span, label)
1214            .with_parse_code("interface_method_with_type_parameters")
1215            .with_help(
1216                "Interface methods cannot have type parameters, because Go interfaces do not support generic methods",
1217            );
1218
1219        self.errors.push(error);
1220    }
1221
1222    fn error_leading_zero(&mut self) {
1223        let span = self.span_from_token(self.current_token());
1224        let error = ParseError::new(
1225            "Invalid number literal",
1226            span,
1227            "leading zero in integer literal",
1228        )
1229        .with_parse_code("number_leading_zero")
1230        .with_help("Prefix with `0o` for octal (e.g. `0o644`) or remove the leading zero");
1231        self.errors.push(error);
1232    }
1233
1234    fn parse_integer_text(&mut self, text: &str) -> ast::Literal {
1235        self.parse_integer_text_with(text, false)
1236    }
1237
1238    fn parse_integer_text_with(&mut self, text: &str, preserve_decimal_text: bool) -> ast::Literal {
1239        let clean = if text.contains('_') {
1240            Cow::Owned(text.replace('_', ""))
1241        } else {
1242            Cow::Borrowed(text)
1243        };
1244
1245        let (n, is_decimal) = if clean.starts_with("0x") || clean.starts_with("0X") {
1246            let value = u64::from_str_radix(&clean[2..], 16).unwrap_or_else(|_| {
1247                self.track_error(
1248                    format!("hex literal '{text}' is too large"),
1249                    "Maximum value is `0xFFFFFFFFFFFFFFFF`.",
1250                );
1251                0
1252            });
1253            (value, false)
1254        } else if clean.starts_with("0o") || clean.starts_with("0O") {
1255            let value = u64::from_str_radix(&clean[2..], 8).unwrap_or_else(|_| {
1256                self.track_error(
1257                    format!("octal literal '{text}' is too large"),
1258                    "Maximum value is `0o1777777777777777777777`.",
1259                );
1260                0
1261            });
1262            (value, false)
1263        } else if clean.starts_with("0b") || clean.starts_with("0B") {
1264            let value = u64::from_str_radix(&clean[2..], 2).unwrap_or_else(|_| {
1265                self.track_error(
1266                    format!("binary literal '{text}' is too large"),
1267                    "Value must fit in 64 bits.",
1268                );
1269                0
1270            });
1271            (value, false)
1272        } else if clean.len() > 1 && clean.starts_with('0') {
1273            self.error_leading_zero();
1274            (clean.parse().unwrap_or(0), false)
1275        } else {
1276            let value = clean.parse().unwrap_or_else(|_| {
1277                self.track_error(
1278                    format!("integer literal '{text}' is too large"),
1279                    "Maximum value is `18446744073709551615`.",
1280                );
1281                0
1282            });
1283            (value, true)
1284        };
1285
1286        let original_text = if is_decimal && !preserve_decimal_text {
1287            None
1288        } else {
1289            Some(text.to_string())
1290        };
1291
1292        ast::Literal::Integer {
1293            value: n,
1294            text: original_text,
1295        }
1296    }
1297
1298    fn unexpected_token(&mut self, ctx: &str) -> ast::Expression {
1299        let token = self.current_token();
1300        let token_descriptor = if token.text.is_empty() {
1301            format!("{:?}", token.kind)
1302        } else {
1303            format!("`{}`", token.text)
1304        };
1305
1306        let span = Span::new(self.file_id, token.byte_offset, token.byte_length);
1307
1308        let (label, error_code, help) = match ctx {
1309            "expr" => (
1310                format!("expected expression, found {}", token_descriptor),
1311                "expected_expression",
1312                "Check your syntax.",
1313            ),
1314            "pattern" => (
1315                format!("unexpected {} in pattern", token_descriptor),
1316                "invalid_pattern",
1317                "Patterns include literals, variables, and destructuring.",
1318            ),
1319            "literal" => (
1320                format!("expected literal, found {}", token_descriptor),
1321                "expected_literal",
1322                "Literals include numbers, strings, characters, and booleans.",
1323            ),
1324            "top_item" if token.text == "trait" => (
1325                format!("unexpected {}", token_descriptor),
1326                "trait_unsupported",
1327                "Lisette uses `interface` with Go-style structural typing. Types automatically satisfy interfaces if they have the required methods.",
1328            ),
1329            "top_item" if token.text == "use" => (
1330                "unexpected syntax for import".to_string(),
1331                "use_unsupported",
1332                "Use `import` instead of `use` for imports: `import \"package/path\"`",
1333            ),
1334            "top_item" if token.kind == Let => (
1335                "`let` is not allowed at the top level".to_string(),
1336                "top_level_let",
1337                "Use `const` for a primitive, or a function that returns the value e.g. `fn origin() -> Point { ... }` for a composite",
1338            ),
1339            "top_item" => (
1340                "expected declaration".to_string(),
1341                "expected_declaration",
1342                "At the top level of a file, Lisette expects `fn`, `struct`, `enum`, `interface`, `impl`, `const`, `import`, or `type`.",
1343            ),
1344            _ => (
1345                format!("unexpected {}", token_descriptor),
1346                "unexpected_token",
1347                "Check your syntax.",
1348            ),
1349        };
1350
1351        let error = ParseError::new("Syntax error", span, label)
1352            .with_parse_code(error_code)
1353            .with_help(help);
1354
1355        if !self.too_many_errors() {
1356            self.errors.push(error);
1357        }
1358
1359        self.resync_on_error();
1360
1361        Self::error_expression(span)
1362    }
1363
1364    fn error_expression(span: Span) -> ast::Expression {
1365        ast::Expression::Unit {
1366            ty: Type::Error,
1367            span,
1368        }
1369    }
1370}
1371
1372fn is_go_build_constraint(text: &str) -> bool {
1373    text.split_whitespace().next() == Some("+build")
1374}
1375
1376struct TokenStream<'source> {
1377    tokens: Vec<Token<'source>>,
1378    position: usize,
1379}
1380
1381impl<'source> TokenStream<'source> {
1382    fn new(tokens: Vec<Token<'source>>) -> Self {
1383        debug_assert!(
1384            !tokens.is_empty(),
1385            "lexer must always produce at least an EOF token",
1386        );
1387        Self {
1388            tokens,
1389            position: 0,
1390        }
1391    }
1392
1393    fn peek(&self) -> Token<'source> {
1394        self.tokens[self.position]
1395    }
1396
1397    fn peek_ahead(&self, n: usize) -> Token<'source> {
1398        let last_index = self.tokens.len() - 1;
1399        let idx = self.position.saturating_add(n).min(last_index);
1400        self.tokens[idx]
1401    }
1402
1403    fn previous(&self) -> Token<'source> {
1404        self.tokens[self.position.saturating_sub(1)]
1405    }
1406
1407    fn previous_code(&self) -> Token<'source> {
1408        let mut index = self.position.saturating_sub(1);
1409
1410        while index > 0 && matches!(self.tokens[index].kind, Comment | DocComment | FileComment) {
1411            index -= 1;
1412        }
1413
1414        self.tokens[index]
1415    }
1416
1417    fn consume(&mut self) -> Token<'source> {
1418        let token = self.tokens[self.position];
1419        if self.position + 1 < self.tokens.len() {
1420            self.position += 1;
1421        }
1422        token
1423    }
1424
1425    fn consume_right_angle(&mut self) -> Option<Token<'source>> {
1426        let token = self.peek();
1427        match token.kind {
1428            RightAngleBracket => Some(self.consume()),
1429            ShiftRight => {
1430                let first = Token {
1431                    kind: RightAngleBracket,
1432                    text: ">",
1433                    byte_offset: token.byte_offset,
1434                    byte_length: 1,
1435                };
1436                let second = Token {
1437                    byte_offset: token.byte_offset + 1,
1438                    ..first
1439                };
1440                self.tokens[self.position] = first;
1441                self.tokens.insert(self.position + 1, second);
1442                Some(self.consume())
1443            }
1444            _ => None,
1445        }
1446    }
1447}
1448
1449#[cfg(test)]
1450mod import_order_tests {
1451    use super::IMPORT_AFTER_ITEM_CODE;
1452    use crate::ast::Expression;
1453    use crate::build_ast;
1454
1455    fn codes(source: &str) -> Vec<String> {
1456        build_ast(source, 0)
1457            .errors
1458            .iter()
1459            .map(|error| error.code.clone())
1460            .collect()
1461    }
1462
1463    #[test]
1464    fn imports_before_every_other_item_are_allowed() {
1465        for source in [
1466            "import \"go:fmt\"\nimport _ \"go:os\"\nimport alias \"go:io\"\nfn f() {}",
1467            "//! header\n\nimport \"go:fmt\"\n\nfn f() {}",
1468            "// note\nimport \"go:fmt\"\n\n/// docs\nfn f() {}",
1469            "import \"go:fmt\"\n\n#[test]\nfn f(t: T) {}",
1470            "import \"go:fmt\"",
1471        ] {
1472            assert!(codes(source).is_empty(), "for source: {source:?}");
1473        }
1474    }
1475
1476    #[test]
1477    fn a_public_import_is_rejected() {
1478        for source in [
1479            "pub import \"go:fmt\"",
1480            "pub import _ \"go:fmt\"",
1481            "pub import alias \"go:fmt\"",
1482            "pub // note\nimport \"go:fmt\"",
1483            "import \"go:os\"\npub import \"go:fmt\"\nfn f() {}",
1484        ] {
1485            assert_eq!(
1486                codes(source),
1487                ["parse.pub_import"],
1488                "for source: {source:?}"
1489            );
1490        }
1491    }
1492
1493    #[test]
1494    fn visibility_on_definitions_is_untouched() {
1495        for source in [
1496            "pub fn f() {}",
1497            "pub struct S {}",
1498            "pub enum E { A }",
1499            "pub const N: int = 1",
1500            "pub type T = int",
1501            "pub interface I {}",
1502        ] {
1503            assert!(codes(source).is_empty(), "for source: {source:?}");
1504        }
1505    }
1506
1507    #[test]
1508    fn import_after_a_definition_is_rejected() {
1509        for source in [
1510            "fn f() {}\nimport \"go:fmt\"",
1511            "struct S {}\nimport _ \"go:fmt\"",
1512            "const N: int = 1\nimport alias \"go:fmt\"",
1513            "type T = int\nimport \"go:fmt\"",
1514            "import \"go:os\"\nfn f() {}\nimport \"go:fmt\"",
1515        ] {
1516            assert_eq!(
1517                codes(source),
1518                [IMPORT_AFTER_ITEM_CODE],
1519                "for source: {source:?}"
1520            );
1521        }
1522    }
1523
1524    #[test]
1525    fn every_misplaced_import_is_reported() {
1526        let source = "fn f() {}\nimport \"go:fmt\"\nimport \"go:os\"";
1527        assert_eq!(
1528            codes(source),
1529            [IMPORT_AFTER_ITEM_CODE, IMPORT_AFTER_ITEM_CODE]
1530        );
1531    }
1532
1533    #[test]
1534    fn a_misplaced_import_still_reaches_the_ast() {
1535        let result = super::Parser::lex_and_parse_file("fn f() {}\nimport \"go:fmt\"", 0);
1536        assert!(matches!(
1537            result.ast.last(),
1538            Some(Expression::PackageImport { .. })
1539        ));
1540    }
1541
1542    #[test]
1543    fn a_parse_stopped_by_the_error_cap_is_truncated() {
1544        let mut source = String::from("fn f() {}\n");
1545        for index in 0..60 {
1546            source.push_str(&format!("import \"go:pkg{index}\"\n"));
1547        }
1548        source.push_str("fn last() {}\n");
1549
1550        let result = super::Parser::lex_and_parse_file(&source, 0);
1551        assert!(result.truncated);
1552        assert!(!result.ast.iter().any(|item| matches!(
1553            item,
1554            Expression::Function { name, .. } if name == "last"
1555        )));
1556    }
1557
1558    #[test]
1559    fn a_parse_that_reaches_the_end_is_not_truncated() {
1560        let result = super::Parser::lex_and_parse_file("fn f() {}\nimport \"go:fmt\"", 0);
1561        assert!(!result.truncated);
1562    }
1563
1564    #[test]
1565    fn an_import_inside_a_block_keeps_its_own_error() {
1566        let source = "fn f() {\n  import \"go:fmt\"\n}";
1567        assert_eq!(codes(source), ["parse.syntax_error"]);
1568    }
1569
1570    #[test]
1571    fn comments_between_imports_do_not_count_as_items() {
1572        let source = "import \"go:fmt\"\n// note\n\n// another note\nimport \"go:os\"\nfn f() {}";
1573        assert!(codes(source).is_empty());
1574    }
1575}
1576
1577#[cfg(test)]
1578mod file_comment_tests {
1579    use crate::build_ast;
1580
1581    fn file_comment(source: &str) -> Option<String> {
1582        let result = build_ast(source, 0);
1583        assert!(
1584            result.errors.is_empty(),
1585            "unexpected errors: {:?}",
1586            result.errors
1587        );
1588        result.file_comment
1589    }
1590
1591    #[test]
1592    fn consecutive_lines_join_with_newlines() {
1593        assert_eq!(
1594            file_comment("//! a\n//! b\nfn f() {}").as_deref(),
1595            Some("a\nb")
1596        );
1597    }
1598
1599    #[test]
1600    fn bare_line_contributes_empty_line() {
1601        assert_eq!(
1602            file_comment("//! a\n//!\n//! b\nfn f() {}").as_deref(),
1603            Some("a\n\nb")
1604        );
1605    }
1606
1607    #[test]
1608    fn blank_line_between_runs_is_an_error() {
1609        for source in [
1610            "//! a\n\n//! b\n\nfn f() {}",
1611            "//! a\r\n\r\n//! b\r\n\r\nfn f() {}",
1612            "//! a\n//!\n\n//! b\nfn f() {}",
1613        ] {
1614            let result = build_ast(source, 0);
1615            let codes: Vec<_> = result.errors.iter().map(|e| e.code.as_str()).collect();
1616            assert_eq!(
1617                codes,
1618                ["parse.split_file_comment"],
1619                "for source: {source:?}"
1620            );
1621        }
1622    }
1623
1624    #[test]
1625    fn anything_before_the_block_is_rejected() {
1626        for source in ["\n//! a\nfn f() {}", " //! a\nfn f() {}"] {
1627            let result = build_ast(source, 0);
1628            let codes: Vec<_> = result.errors.iter().map(|e| e.code.as_str()).collect();
1629            assert_eq!(
1630                codes,
1631                ["parse.misplaced_file_comment"],
1632                "for source: {source:?}"
1633            );
1634        }
1635    }
1636
1637    #[test]
1638    fn blank_lines_after_the_block_are_allowed() {
1639        assert_eq!(
1640            file_comment("//! a\n//! b\n\n\nfn f() {}").as_deref(),
1641            Some("a\nb")
1642        );
1643    }
1644
1645    #[test]
1646    fn leading_comment_makes_the_header_misplaced() {
1647        let result = build_ast("// leading\n//! too late\nfn f() {}", 0);
1648        let codes: Vec<_> = result.errors.iter().map(|e| e.code.as_str()).collect();
1649        assert_eq!(codes, ["parse.misplaced_file_comment"]);
1650    }
1651
1652    #[test]
1653    fn interleaved_comment_ends_the_block() {
1654        let result = build_ast("//! a\n// note\n//! b\nfn f() {}", 0);
1655        let codes: Vec<_> = result.errors.iter().map(|e| e.code.as_str()).collect();
1656        assert_eq!(codes, ["parse.misplaced_file_comment"]);
1657    }
1658
1659    #[test]
1660    fn comment_after_the_block_is_allowed() {
1661        assert_eq!(
1662            file_comment("//! a\n\n// section note\nfn f() {}").as_deref(),
1663            Some("a")
1664        );
1665    }
1666
1667    #[test]
1668    fn file_without_header_has_no_file_comment() {
1669        assert_eq!(file_comment("fn f() {}"), None);
1670    }
1671
1672    #[test]
1673    fn header_without_items_is_valid() {
1674        assert_eq!(
1675            file_comment("//! header only").as_deref(),
1676            Some("header only")
1677        );
1678    }
1679
1680    #[test]
1681    fn header_before_doc_commented_item() {
1682        let result = build_ast("//! header\n/// item doc\nfn f() {}", 0);
1683        assert!(result.errors.is_empty(), "{:?}", result.errors);
1684        assert_eq!(result.file_comment.as_deref(), Some("header"));
1685    }
1686
1687    #[test]
1688    fn misplaced_file_comment_reports_one_error_per_run() {
1689        let result = build_ast("fn f() {}\n//! a\n//! b\nfn g() {}", 0);
1690        let codes: Vec<_> = result.errors.iter().map(|e| e.code.as_str()).collect();
1691        assert_eq!(codes, ["parse.misplaced_file_comment"]);
1692    }
1693
1694    #[test]
1695    fn build_constraint_lines_are_rejected() {
1696        for source in [
1697            "//!+build ignore\nfn f() {}",
1698            "//! +build ignore\nfn f() {}",
1699            "//!  \t+build linux\nfn f() {}",
1700            "//! +build\nfn f() {}",
1701            "//! +build ignore\r\nfn f() {}",
1702            "//! +build\r\nfn f() {}",
1703            "//!\u{00A0}+build ignore\nfn f() {}",
1704            "//! +build\u{00A0}ignore\nfn f() {}",
1705            "//! +build\u{3000}ignore\nfn f() {}",
1706        ] {
1707            let result = build_ast(source, 0);
1708            let codes: Vec<_> = result.errors.iter().map(|e| e.code.as_str()).collect();
1709            assert_eq!(
1710                codes,
1711                ["parse.file_comment_build_constraint"],
1712                "for source: {source:?}"
1713            );
1714        }
1715    }
1716
1717    #[test]
1718    fn build_constraint_lookalikes_are_allowed() {
1719        for source in [
1720            "//! +buildx tag\nfn f() {}",
1721            "//! use +build wisely\nfn f() {}",
1722            "//! +builder pattern\nfn f() {}",
1723        ] {
1724            let result = build_ast(source, 0);
1725            assert!(result.errors.is_empty(), "for source: {source:?}");
1726        }
1727    }
1728}