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