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
40pub use error::ParseError;
41
42pub struct ParseResult {
43    pub ast: Vec<ast::Expression>,
44    pub errors: Vec<ParseError>,
45    pub file_comment: Option<string::String>,
46    pub truncated: bool,
47    pub status: FileParseStatus,
48}
49
50/// How much of a file survived parsing.
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
52pub enum FileParseStatus {
53    #[default]
54    Clean,
55    Recovered,
56    Failed,
57}
58
59impl ParseResult {
60    pub fn has_errors(&self) -> bool {
61        !self.errors.is_empty()
62    }
63}
64
65pub struct Parser<'source> {
66    stream: TokenStream<'source>,
67    errors: Vec<ParseError>,
68    file_id: u32,
69    source: &'source str,
70    depth: u32,
71}
72
73/// A recursion frame owns the parser depth it opened and restores the previous
74/// depth even when parsing exits early or panics.
75struct RecursionScope<'parser, 'source> {
76    parser: &'parser mut Parser<'source>,
77    previous_depth: u32,
78}
79
80impl<'parser, 'source> Deref for RecursionScope<'parser, 'source> {
81    type Target = Parser<'source>;
82
83    fn deref(&self) -> &Self::Target {
84        self.parser
85    }
86}
87
88impl<'parser, 'source> DerefMut for RecursionScope<'parser, 'source> {
89    fn deref_mut(&mut self) -> &mut Self::Target {
90        self.parser
91    }
92}
93
94impl Drop for RecursionScope<'_, '_> {
95    fn drop(&mut self) {
96        self.parser.depth = self.previous_depth;
97    }
98}
99
100impl<'source> Parser<'source> {
101    pub fn new(tokens: Vec<Token<'source>>, source: &'source str) -> Parser<'source> {
102        Self::with_file_id(tokens, source, 0)
103    }
104
105    pub fn lex_and_parse_file(source: &str, file_id: u32) -> ParseResult {
106        let lex_result = lex::Lexer::new(source, file_id).lex();
107
108        if lex_result.failed() {
109            return ParseResult {
110                ast: vec![],
111                errors: lex_result.errors,
112                file_comment: None,
113                truncated: true,
114                status: FileParseStatus::Failed,
115            };
116        }
117
118        Parser::with_file_id(lex_result.tokens, source, file_id).parse()
119    }
120
121    fn with_file_id(
122        tokens: Vec<Token<'source>>,
123        source: &'source str,
124        file_id: u32,
125    ) -> Parser<'source> {
126        let stream = TokenStream::new(tokens);
127
128        Parser {
129            stream,
130            errors: Default::default(),
131            file_id,
132            source,
133            depth: 0,
134        }
135    }
136
137    pub fn parse(mut self) -> ParseResult {
138        let mut top_items = vec![];
139        let mut seen_non_import = false;
140
141        let shebang_end = self.consume_shebang();
142        let file_comment = self.collect_file_comments(shebang_end);
143        self.skip_comments();
144
145        while !self.at_eof() && !self.too_many_errors() {
146            let position = self.position();
147            let item = self.parse_top_item();
148            if !matches!(item, ast::Expression::Unit { .. }) {
149                if let ast::Expression::PackageImport {
150                    span, name_span, ..
151                } = &item
152                {
153                    if seen_non_import {
154                        self.error_import_after_item(*span, *name_span);
155                    }
156                } else {
157                    seen_non_import = true;
158                }
159                top_items.push(item);
160            }
161            self.advance_if(Semicolon);
162            if self.position() == position {
163                self.next();
164            }
165        }
166
167        let truncated = !self.at_eof();
168        let status = if self.errors.is_empty() {
169            FileParseStatus::Clean
170        } else {
171            FileParseStatus::Recovered
172        };
173
174        ParseResult {
175            ast: top_items,
176            errors: self.errors,
177            file_comment,
178            truncated,
179            status,
180        }
181    }
182
183    fn parse_top_item(&mut self) -> ast::Expression {
184        let doc_with_span = self.collect_doc_comments();
185
186        let attributes = self.parse_attributes();
187
188        let pub_token = if self.is(Pub) {
189            Some(self.current_token())
190        } else {
191            None
192        };
193        let is_public = pub_token.is_some();
194        if is_public {
195            self.next();
196        }
197
198        if let Some(token) = pub_token {
199            let span = Span::new(self.file_id, token.byte_offset, token.byte_length);
200            match self.current_token().kind {
201                Impl => self.error_misplaced_pub(
202                    span,
203                    "syntax_error",
204                    "Place `pub` on individual methods inside the `impl` block instead",
205                ),
206                Import => self.error_misplaced_pub(
207                    span,
208                    "pub_import",
209                    "An import is always private to the file that declares it. Remove `pub`",
210                ),
211                _ => {}
212            }
213        }
214
215        let is_documentable = matches!(
216            self.current_token().kind,
217            Enum | Struct | Interface | Function | Const | Var | Type
218        );
219
220        if let Some((_, ref span)) = doc_with_span
221            && !is_documentable
222        {
223            self.error_detached_doc_comment(*span);
224        }
225
226        let doc = doc_with_span.map(|(text, _)| text);
227
228        if !matches!(self.current_token().kind, Enum | Struct | Function | Type)
229            && let Some(attribute) = attributes.first()
230        {
231            self.error_misplaced_attribute(attribute.span);
232        }
233
234        let expression = match self.current_token().kind {
235            Enum => self.parse_enum_definition(doc, attributes),
236            Struct => self.parse_struct_definition(doc, attributes),
237            Interface => self.parse_interface_definition(doc),
238            Function => {
239                // Only a top-level `#[test]` declaration may write a bare handle parameter.
240                let mode = if has_test_attribute(&attributes) {
241                    ParamMode::TestFunction
242                } else {
243                    ParamMode::Strict
244                };
245                self.parse_function(doc, attributes, mode)
246            }
247            Impl => self.parse_impl_block(),
248            Const => self.parse_const_definition(doc),
249            Var => self.parse_var_declaration(doc),
250            Import => self.parse_import(),
251            Type => self.parse_type_alias_with_doc(doc, attributes),
252            Comment => {
253                let start = self.current_token();
254                self.skip_comments();
255                ast::Expression::Unit {
256                    ty: Type::uninferred(),
257                    span: self.span_from_offset(start.byte_offset),
258                }
259            }
260            _ => self.unexpected_token("top_item"),
261        };
262
263        if is_public {
264            return expression.set_public();
265        }
266
267        expression
268    }
269
270    fn parse_block_item(&mut self) -> ast::Expression {
271        match self.current_token().kind {
272            Enum => {
273                self.track_error(
274                    "misplaced",
275                    "Move this enum definition to the top level of the file.",
276                );
277                self.parse_enum_definition(None, vec![])
278            }
279            Struct => {
280                self.track_error(
281                    "misplaced",
282                    "Move this struct definition to the top level of the file.",
283                );
284                self.parse_struct_definition(None, vec![])
285            }
286            Type => {
287                self.track_error(
288                    "misplaced",
289                    "Move this type alias to the top level of the file.",
290                );
291                self.parse_type_alias_with_doc(None, vec![])
292            }
293            Import => {
294                self.track_error(
295                    "misplaced",
296                    "Move this import to the top level of the file.",
297                );
298                self.parse_import()
299            }
300            Impl => {
301                self.track_error(
302                    "misplaced",
303                    "Move this `impl` block to the top level of the file.",
304                );
305                self.parse_impl_block()
306            }
307            Interface => {
308                self.track_error(
309                    "misplaced",
310                    "Move this interface definition to the top level of the file.",
311                );
312                self.parse_interface_definition(None)
313            }
314            Function => self.parse_function(None, vec![], ParamMode::Strict),
315            Const => self.parse_const_definition(None),
316
317            Hash => {
318                let attributes = self.parse_attributes();
319                if let Some(attribute) = attributes.first() {
320                    self.error_misplaced_attribute(attribute.span);
321                }
322                if self.is(RightCurlyBrace) || self.at_eof() {
323                    ast::Expression::Unit {
324                        ty: Type::uninferred(),
325                        span: self.span_from_token(self.current_token()),
326                    }
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                | Function
772                | Struct
773                | Enum
774                | Const
775                | Impl
776                | Interface
777                | Type
778                | Import
779        )
780    }
781
782    fn can_start_annotation(&self) -> bool {
783        matches!(
784            self.current_token().kind,
785            Identifier | Function | LeftParen | Integer | Mut
786        )
787    }
788
789    fn can_recover_annotation(&self) -> bool {
790        !self.at_recovery_boundary() && self.can_start_annotation()
791    }
792
793    fn at_recovery_boundary(&self) -> bool {
794        if self.is(Function) {
795            return self.at_function_declaration();
796        }
797        matches!(self.current_token().kind, DocComment | Hash | Pub) || self.at_item_boundary()
798    }
799
800    fn at_parameter_recovery_boundary(&self) -> bool {
801        self.at_recovery_boundary() && self.stream.peek_ahead(1).kind != Colon
802    }
803
804    fn at_function_declaration(&self) -> bool {
805        self.is(Function)
806            && self.stream.peek_ahead(1).kind == Identifier
807            && matches!(
808                self.stream.peek_ahead(2).kind,
809                LeftParen | LeftAngleBracket | Dot
810            )
811    }
812
813    fn at_item_boundary(&self) -> bool {
814        matches!(
815            self.current_token().kind,
816            Let | Function | Struct | Enum | Impl | Interface | Type | Const | Import
817        )
818    }
819
820    fn at_match_arm_terminator(&self) -> bool {
821        self.at_eof() || self.is(Comma) || self.is(RightCurlyBrace) || self.at_item_boundary()
822    }
823
824    fn resync_on_error(&mut self) {
825        if !self.at_eof() {
826            self.next();
827        }
828
829        while !self.at_sync_point() && !self.at_eof() {
830            self.next();
831        }
832    }
833
834    fn track_error(&mut self, label: impl Into<string::String>, help: impl Into<string::String>) {
835        let current = self.current_token();
836        let span = Span::new(self.file_id, current.byte_offset, current.byte_length);
837        self.track_error_at(span, label, help);
838    }
839
840    fn track_error_at(
841        &mut self,
842        span: Span,
843        label: impl Into<string::String>,
844        help: impl Into<string::String>,
845    ) {
846        if self.too_many_errors() {
847            return;
848        }
849        let error = ParseError::new("Syntax error", span, label.into())
850            .with_parse_code("syntax_error")
851            .with_help(help.into());
852
853        self.errors.push(error);
854    }
855
856    fn error_angle_brackets_for_generics(&mut self, span: Span, help: impl Into<string::String>) {
857        if self.too_many_errors() {
858            return;
859        }
860        let error = ParseError::new("Syntax error", span, "use `<...>` for type args")
861            .with_parse_code("angle_brackets_for_generics")
862            .with_help(help.into());
863
864        self.errors.push(error);
865    }
866
867    fn error_var_initializer(&mut self, span: Span) {
868        if self.too_many_errors() {
869            return;
870        }
871        let error = ParseError::new("Syntax error", span, "not allowed")
872            .with_parse_code("var_not_allowed")
873            .with_help(
874                "Use `const` for a primitive, or a function that returns the value e.g. `fn origin() -> Point { ... }` for a composite",
875            );
876
877        self.errors.push(error);
878    }
879
880    fn error_import_alias_after_path(&mut self, span: Span, alias: &str, path: &str) {
881        if self.too_many_errors() {
882            return;
883        }
884        let error = ParseError::new("Syntax error", span, "import alias goes before the path")
885            .with_parse_code("import_alias_position")
886            .with_help(format!(
887                "Use Go-style alias syntax: `import {alias} \"{path}\"`"
888            ));
889
890        self.errors.push(error);
891    }
892
893    fn error_bare_multi_return(&mut self, span: Span, suggestion: &str) {
894        if self.too_many_errors() {
895            return;
896        }
897        let error = ParseError::new(
898            "Multiple return values must be a tuple",
899            span,
900            "wrap these values in parentheses",
901        )
902        .with_parse_code("bare_multi_value_return")
903        .with_help(format!(
904            "To return multiple values, use a tuple: `{suggestion}`"
905        ));
906
907        self.errors.push(error);
908    }
909
910    fn error_match_arm_missing_comma(&mut self, span: Span) {
911        if self.too_many_errors() {
912            return;
913        }
914        let error = ParseError::new("Syntax error", span, "missing comma after match arm")
915            .with_parse_code("match_arm_missing_comma")
916            .with_help("Match arms must be separated by commas, even when the body is a block.");
917
918        self.errors.push(error);
919    }
920
921    fn error_map_literal_not_supported(&mut self, span: Span) {
922        if self.too_many_errors() {
923            return;
924        }
925        let error = ParseError::new("Invalid `Map` initialization", span, "invalid syntax")
926            .with_parse_code("invalid_map_initialization")
927            .with_help("To initialize a `Map`, use `Map.new<K, V>()` then `m[key] = value`");
928
929        self.errors.push(error);
930    }
931
932    fn error_missing_initializer(&mut self, span: Span) {
933        if self.too_many_errors() {
934            return;
935        }
936        let error = ParseError::new(
937            "Missing initializer",
938            span,
939            "annotated binding needs a value",
940        )
941        .with_parse_code("missing_initializer")
942        .with_help("Bindings must be initialized");
943
944        self.errors.push(error);
945    }
946
947    fn track_ensure_error(&mut self, expected_token: TokenKind) {
948        if self.too_many_errors() {
949            return;
950        }
951        let current = self.current_token();
952
953        let error_code = match expected_token {
954            Semicolon => "missing_semicolon",
955            RightCurlyBrace => "unclosed_block",
956            _ => "unexpected_token",
957        };
958
959        let span = Span::new(self.file_id, current.byte_offset, current.byte_length);
960        let error = ParseError::new("Syntax error", span, format!("expected {}", expected_token))
961            .with_parse_code(error_code);
962
963        self.errors.push(error);
964    }
965
966    fn close_brace_span(&mut self, start: Token<'source>, error_anchor: Token<'source>) -> Span {
967        if self.is(RightCurlyBrace) {
968            let close = self.current_token();
969            self.next();
970            let end = close.byte_offset + close.byte_length;
971            Span::new(
972                self.file_id,
973                start.byte_offset,
974                end.saturating_sub(start.byte_offset),
975            )
976        } else {
977            self.error_unclosed_block(&error_anchor);
978            self.span_from_offset(start.byte_offset)
979        }
980    }
981
982    fn error_unclosed_block(&mut self, open_brace: &Token) {
983        let span = Span::new(self.file_id, open_brace.byte_offset, open_brace.byte_length);
984        let error = ParseError::new("Unclosed block", span, "opening brace here")
985            .with_parse_code("unclosed_block")
986            .with_help("Add a closing `}`");
987
988        self.errors.push(error);
989    }
990
991    fn error_tuple_arity(&mut self, arity: usize, span: Span) {
992        let help = if arity == 0 {
993            "Use `()` for unit type".to_string()
994        } else if arity == 1 {
995            "Use the type directly without wrapping in a tuple".to_string()
996        } else {
997            "For >5 elements, use a struct with named fields".to_string()
998        };
999
1000        let error = ParseError::new(
1001            "Invalid tuple",
1002            span,
1003            format!("{}-element tuple not allowed", arity),
1004        )
1005        .with_parse_code("tuple_element_count")
1006        .with_help(help);
1007
1008        self.errors.push(error);
1009    }
1010
1011    fn error_duplicate_field_in_pattern(
1012        &mut self,
1013        field_name: &str,
1014        first_span: Span,
1015        second_span: Span,
1016    ) {
1017        let error = ParseError::new(
1018            "Duplicate field",
1019            first_span,
1020            format!("first use of `{}`", field_name),
1021        )
1022        .with_span_label(second_span, "used again")
1023        .with_parse_code("duplicate_field_in_pattern")
1024        .with_help("Remove the duplicate binding");
1025
1026        self.errors.push(error);
1027    }
1028
1029    fn error_duplicate_embed_parent(&mut self, first_span: Span, second_span: Span) {
1030        let error = ParseError::new("Duplicate embed", first_span, "first use")
1031            .with_span_label(second_span, "used again")
1032            .with_parse_code("duplicate_embed_parent")
1033            .with_help("Remove the duplicate parent");
1034
1035        self.errors.push(error);
1036    }
1037
1038    fn error_impl_interface_embed(&mut self, keyword_span: Span) {
1039        let error = ParseError::new(
1040            "Interface embedding uses `embed`",
1041            keyword_span,
1042            "write `embed` here",
1043        )
1044        .with_parse_code("impl_interface_embed")
1045        .with_help("Interfaces embed other interfaces with `embed`. Replace `impl` with `embed`");
1046
1047        self.errors.push(error);
1048    }
1049
1050    fn error_duplicate_struct_field(&mut self, name: &str, first_span: Span, second_span: Span) {
1051        let error = ParseError::new("Duplicate field", first_span, "first defined")
1052            .with_span_label(second_span, "defined again")
1053            .with_parse_code("duplicate_struct_field")
1054            .with_help(format!("Remove the duplicate field `{}`", name));
1055
1056        self.errors.push(error);
1057    }
1058
1059    fn error_duplicate_enum_variant(&mut self, name: &str, first_span: Span, second_span: Span) {
1060        let error = ParseError::new("Duplicate variant", first_span, "first defined")
1061            .with_span_label(second_span, "defined again")
1062            .with_parse_code("duplicate_enum_variant")
1063            .with_help(format!("Remove the duplicate variant `{}`", name));
1064
1065        self.errors.push(error);
1066    }
1067
1068    fn error_duplicate_interface_method(
1069        &mut self,
1070        name: &str,
1071        first_span: Span,
1072        second_span: Span,
1073    ) {
1074        let error = ParseError::new("Duplicate method", first_span, "first defined")
1075            .with_span_label(second_span, "defined again")
1076            .with_parse_code("duplicate_interface_method")
1077            .with_help(format!("Remove the duplicate method `{}`", name));
1078
1079        self.errors.push(error);
1080    }
1081
1082    fn error_float_pattern_not_allowed(&mut self, span: Span, float_text: &str) {
1083        let error = ParseError::new("Invalid pattern", span, "float literal not allowed here")
1084            .with_parse_code("float_pattern")
1085            .with_help(format!(
1086                "Use a guard instead: `x if x == {} =>`",
1087                float_text
1088            ));
1089
1090        self.errors.push(error);
1091    }
1092
1093    fn error_uppercase_binding(&mut self, span: Span) {
1094        let error = ParseError::new("Invalid binding name", span, "uppercase not allowed here")
1095            .with_parse_code("uppercase_binding")
1096            .with_help("Lowercase the binding");
1097
1098        self.errors.push(error);
1099    }
1100
1101    fn error_detached_doc_comment(&mut self, span: Span) {
1102        let error = ParseError::new("Unattached doc comment", span, "is detached")
1103            .with_parse_code("detached_doc_comment")
1104            .with_help(
1105                "Place doc comments `///` on the line above a symbol definition and file comments `//!` at the very top of the file",
1106            );
1107
1108        self.errors.push(error);
1109    }
1110
1111    fn error_split_file_comment(&mut self, span: Span) {
1112        let error = ParseError::new("Split file comment", span, "separated from the block above")
1113            .with_parse_code("split_file_comment")
1114            .with_help(
1115                "Remove the blank line, or write a bare `//!` line to keep a visible gap in the emitted header",
1116            );
1117
1118        self.errors.push(error);
1119    }
1120
1121    fn error_file_comment_build_constraint(&mut self, span: Span) {
1122        let error = ParseError::new(
1123            "Invalid file comment",
1124            span,
1125            "would become a Go build constraint",
1126        )
1127        .with_parse_code("file_comment_build_constraint")
1128        .with_help(
1129            "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",
1130        );
1131
1132        self.errors.push(error);
1133    }
1134
1135    fn error_misplaced_file_comment(&mut self) {
1136        let first = self.current_token();
1137        let mut last = first;
1138
1139        while self.is(FileComment) {
1140            last = self.current_token();
1141            self.stream.consume();
1142            while self.is(Comment) {
1143                self.stream.consume();
1144            }
1145        }
1146
1147        let length = last.byte_offset + last.byte_length - first.byte_offset;
1148        self.error_misplaced_file_comment_at(Span::new(self.file_id, first.byte_offset, length));
1149    }
1150
1151    fn error_misplaced_file_comment_at(&mut self, span: Span) {
1152        let error = ParseError::new("Misplaced file comment", span, "not allowed here")
1153            .with_parse_code("misplaced_file_comment")
1154            .with_help(
1155                "Move this file comment to the very top of the file to document it, or use `///` to document the symbol below",
1156            );
1157
1158        self.errors.push(error);
1159    }
1160
1161    fn error_import_after_item(&mut self, statement: Span, path: Span) {
1162        let span = Span::new(
1163            statement.file_id,
1164            statement.byte_offset,
1165            path.end() - statement.byte_offset,
1166        );
1167        let error = ParseError::new("Misplaced import", span, "not allowed here")
1168            .with_parse_code("import_after_item")
1169            .with_help(
1170                "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",
1171            );
1172
1173        self.errors.push(error);
1174    }
1175
1176    fn error_misplaced_pub(&mut self, span: Span, code: &str, help: &str) {
1177        let error = ParseError::new("Misplaced `pub`", span, "not allowed here")
1178            .with_parse_code(code)
1179            .with_help(help);
1180
1181        self.errors.push(error);
1182    }
1183
1184    fn error_misplaced_attribute(&mut self, span: Span) {
1185        let error = ParseError::new(
1186            "Attribute not supported on target",
1187            span,
1188            "nothing here can carry an attribute",
1189        )
1190        .with_parse_code("misplaced_attribute")
1191        .with_help("Remove the attribute, or move it onto an enum, struct, or function");
1192
1193        self.errors.push(error);
1194    }
1195
1196    fn error_interface_method_with_type_parameters(&mut self, span: Span, count: usize) {
1197        let label = if count == 1 {
1198            "type parameter not allowed"
1199        } else {
1200            "type parameters not allowed"
1201        };
1202        let error = ParseError::new("Invalid interface method", span, label)
1203            .with_parse_code("interface_method_with_type_parameters")
1204            .with_help(
1205                "Interface methods cannot have type parameters, because Go interfaces do not support generic methods",
1206            );
1207
1208        self.errors.push(error);
1209    }
1210
1211    fn error_leading_zero(&mut self) {
1212        let span = self.span_from_token(self.current_token());
1213        let error = ParseError::new(
1214            "Invalid number literal",
1215            span,
1216            "leading zero in integer literal",
1217        )
1218        .with_parse_code("number_leading_zero")
1219        .with_help("Prefix with `0o` for octal (e.g. `0o644`) or remove the leading zero");
1220        self.errors.push(error);
1221    }
1222
1223    fn parse_integer_text(&mut self, text: &str) -> ast::Literal {
1224        self.parse_integer_text_with(text, false)
1225    }
1226
1227    fn parse_integer_text_with(&mut self, text: &str, preserve_decimal_text: bool) -> ast::Literal {
1228        let clean = if text.contains('_') {
1229            Cow::Owned(text.replace('_', ""))
1230        } else {
1231            Cow::Borrowed(text)
1232        };
1233
1234        let (n, is_decimal) = if clean.starts_with("0x") || clean.starts_with("0X") {
1235            let value = u64::from_str_radix(&clean[2..], 16).unwrap_or_else(|_| {
1236                self.track_error(
1237                    format!("hex literal '{text}' is too large"),
1238                    "Maximum value is `0xFFFFFFFFFFFFFFFF`.",
1239                );
1240                0
1241            });
1242            (value, false)
1243        } else if clean.starts_with("0o") || clean.starts_with("0O") {
1244            let value = u64::from_str_radix(&clean[2..], 8).unwrap_or_else(|_| {
1245                self.track_error(
1246                    format!("octal literal '{text}' is too large"),
1247                    "Maximum value is `0o1777777777777777777777`.",
1248                );
1249                0
1250            });
1251            (value, false)
1252        } else if clean.starts_with("0b") || clean.starts_with("0B") {
1253            let value = u64::from_str_radix(&clean[2..], 2).unwrap_or_else(|_| {
1254                self.track_error(
1255                    format!("binary literal '{text}' is too large"),
1256                    "Value must fit in 64 bits.",
1257                );
1258                0
1259            });
1260            (value, false)
1261        } else if clean.len() > 1 && clean.starts_with('0') {
1262            self.error_leading_zero();
1263            (clean.parse().unwrap_or(0), false)
1264        } else {
1265            let value = clean.parse().unwrap_or_else(|_| {
1266                self.track_error(
1267                    format!("integer literal '{text}' is too large"),
1268                    "Maximum value is `18446744073709551615`.",
1269                );
1270                0
1271            });
1272            (value, true)
1273        };
1274
1275        let original_text = if is_decimal && !preserve_decimal_text {
1276            None
1277        } else {
1278            Some(text.to_string())
1279        };
1280
1281        ast::Literal::Integer {
1282            value: n,
1283            text: original_text,
1284        }
1285    }
1286
1287    fn unexpected_token(&mut self, ctx: &str) -> ast::Expression {
1288        let token = self.current_token();
1289        let token_descriptor = if token.text.is_empty() {
1290            format!("{:?}", token.kind)
1291        } else {
1292            format!("`{}`", token.text)
1293        };
1294
1295        let span = Span::new(self.file_id, token.byte_offset, token.byte_length);
1296
1297        let (label, error_code, help) = match ctx {
1298            "expr" => (
1299                format!("expected expression, found {}", token_descriptor),
1300                "expected_expression",
1301                "Check your syntax.",
1302            ),
1303            "pattern" => (
1304                format!("unexpected {} in pattern", token_descriptor),
1305                "invalid_pattern",
1306                "Patterns include literals, variables, and destructuring.",
1307            ),
1308            "literal" => (
1309                format!("expected literal, found {}", token_descriptor),
1310                "expected_literal",
1311                "Literals include numbers, strings, characters, and booleans.",
1312            ),
1313            "top_item" if token.text == "trait" => (
1314                format!("unexpected {}", token_descriptor),
1315                "trait_unsupported",
1316                "Lisette uses `interface` with Go-style structural typing. Types automatically satisfy interfaces if they have the required methods.",
1317            ),
1318            "top_item" if token.text == "use" => (
1319                "unexpected syntax for import".to_string(),
1320                "use_unsupported",
1321                "Use `import` instead of `use` for imports: `import \"package/path\"`",
1322            ),
1323            "top_item" if token.kind == Let => (
1324                "`let` is not allowed at the top level".to_string(),
1325                "top_level_let",
1326                "Use `const` for a primitive, or a function that returns the value e.g. `fn origin() -> Point { ... }` for a composite",
1327            ),
1328            "top_item" => (
1329                "expected declaration".to_string(),
1330                "expected_declaration",
1331                "At the top level of a file, Lisette expects `fn`, `struct`, `enum`, `interface`, `impl`, `const`, `import`, or `type`.",
1332            ),
1333            _ => (
1334                format!("unexpected {}", token_descriptor),
1335                "unexpected_token",
1336                "Check your syntax.",
1337            ),
1338        };
1339
1340        let error = ParseError::new("Syntax error", span, label)
1341            .with_parse_code(error_code)
1342            .with_help(help);
1343
1344        if !self.too_many_errors() {
1345            self.errors.push(error);
1346        }
1347
1348        self.resync_on_error();
1349
1350        ast::Expression::Unit {
1351            ty: Type::uninferred(),
1352            span,
1353        }
1354    }
1355}
1356
1357fn is_go_build_constraint(text: &str) -> bool {
1358    text.split_whitespace().next() == Some("+build")
1359}
1360
1361struct TokenStream<'source> {
1362    tokens: Vec<Token<'source>>,
1363    position: usize,
1364}
1365
1366impl<'source> TokenStream<'source> {
1367    fn new(tokens: Vec<Token<'source>>) -> Self {
1368        debug_assert!(
1369            !tokens.is_empty(),
1370            "lexer must always produce at least an EOF token",
1371        );
1372        Self {
1373            tokens,
1374            position: 0,
1375        }
1376    }
1377
1378    fn peek(&self) -> Token<'source> {
1379        self.tokens[self.position]
1380    }
1381
1382    fn peek_ahead(&self, n: usize) -> Token<'source> {
1383        let last_index = self.tokens.len() - 1;
1384        let idx = self.position.saturating_add(n).min(last_index);
1385        self.tokens[idx]
1386    }
1387
1388    fn previous(&self) -> Token<'source> {
1389        self.tokens[self.position.saturating_sub(1)]
1390    }
1391
1392    fn previous_code(&self) -> Token<'source> {
1393        let mut index = self.position.saturating_sub(1);
1394
1395        while index > 0 && matches!(self.tokens[index].kind, Comment | DocComment | FileComment) {
1396            index -= 1;
1397        }
1398
1399        self.tokens[index]
1400    }
1401
1402    fn consume(&mut self) -> Token<'source> {
1403        let token = self.tokens[self.position];
1404        if self.position + 1 < self.tokens.len() {
1405            self.position += 1;
1406        }
1407        token
1408    }
1409
1410    fn consume_right_angle(&mut self) -> Option<Token<'source>> {
1411        let token = self.peek();
1412        match token.kind {
1413            RightAngleBracket => Some(self.consume()),
1414            ShiftRight => {
1415                let first = Token {
1416                    kind: RightAngleBracket,
1417                    text: ">",
1418                    byte_offset: token.byte_offset,
1419                    byte_length: 1,
1420                };
1421                let second = Token {
1422                    byte_offset: token.byte_offset + 1,
1423                    ..first
1424                };
1425                self.tokens[self.position] = first;
1426                self.tokens.insert(self.position + 1, second);
1427                Some(self.consume())
1428            }
1429            _ => None,
1430        }
1431    }
1432}
1433
1434#[cfg(test)]
1435mod import_order_tests {
1436    use super::IMPORT_AFTER_ITEM_CODE;
1437    use crate::ast::Expression;
1438    use crate::build_ast;
1439
1440    fn codes(source: &str) -> Vec<String> {
1441        build_ast(source, 0)
1442            .errors
1443            .iter()
1444            .map(|error| error.code.clone())
1445            .collect()
1446    }
1447
1448    #[test]
1449    fn imports_before_every_other_item_are_allowed() {
1450        for source in [
1451            "import \"go:fmt\"\nimport _ \"go:os\"\nimport alias \"go:io\"\nfn f() {}",
1452            "//! header\n\nimport \"go:fmt\"\n\nfn f() {}",
1453            "// note\nimport \"go:fmt\"\n\n/// docs\nfn f() {}",
1454            "import \"go:fmt\"\n\n#[test]\nfn f(t: T) {}",
1455            "import \"go:fmt\"",
1456        ] {
1457            assert!(codes(source).is_empty(), "for source: {source:?}");
1458        }
1459    }
1460
1461    #[test]
1462    fn a_public_import_is_rejected() {
1463        for source in [
1464            "pub import \"go:fmt\"",
1465            "pub import _ \"go:fmt\"",
1466            "pub import alias \"go:fmt\"",
1467            "pub // note\nimport \"go:fmt\"",
1468            "import \"go:os\"\npub import \"go:fmt\"\nfn f() {}",
1469        ] {
1470            assert_eq!(
1471                codes(source),
1472                ["parse.pub_import"],
1473                "for source: {source:?}"
1474            );
1475        }
1476    }
1477
1478    #[test]
1479    fn visibility_on_definitions_is_untouched() {
1480        for source in [
1481            "pub fn f() {}",
1482            "pub struct S {}",
1483            "pub enum E { A }",
1484            "pub const N: int = 1",
1485            "pub type T = int",
1486            "pub interface I {}",
1487        ] {
1488            assert!(codes(source).is_empty(), "for source: {source:?}");
1489        }
1490    }
1491
1492    #[test]
1493    fn import_after_a_definition_is_rejected() {
1494        for source in [
1495            "fn f() {}\nimport \"go:fmt\"",
1496            "struct S {}\nimport _ \"go:fmt\"",
1497            "const N: int = 1\nimport alias \"go:fmt\"",
1498            "type T = int\nimport \"go:fmt\"",
1499            "import \"go:os\"\nfn f() {}\nimport \"go:fmt\"",
1500        ] {
1501            assert_eq!(
1502                codes(source),
1503                [IMPORT_AFTER_ITEM_CODE],
1504                "for source: {source:?}"
1505            );
1506        }
1507    }
1508
1509    #[test]
1510    fn every_misplaced_import_is_reported() {
1511        let source = "fn f() {}\nimport \"go:fmt\"\nimport \"go:os\"";
1512        assert_eq!(
1513            codes(source),
1514            [IMPORT_AFTER_ITEM_CODE, IMPORT_AFTER_ITEM_CODE]
1515        );
1516    }
1517
1518    #[test]
1519    fn a_misplaced_import_still_reaches_the_ast() {
1520        let result = super::Parser::lex_and_parse_file("fn f() {}\nimport \"go:fmt\"", 0);
1521        assert!(matches!(
1522            result.ast.last(),
1523            Some(Expression::PackageImport { .. })
1524        ));
1525    }
1526
1527    #[test]
1528    fn a_parse_stopped_by_the_error_cap_is_truncated() {
1529        let mut source = String::from("fn f() {}\n");
1530        for index in 0..60 {
1531            source.push_str(&format!("import \"go:pkg{index}\"\n"));
1532        }
1533        source.push_str("fn last() {}\n");
1534
1535        let result = super::Parser::lex_and_parse_file(&source, 0);
1536        assert!(result.truncated);
1537        assert!(!result.ast.iter().any(|item| matches!(
1538            item,
1539            Expression::Function { name, .. } if name == "last"
1540        )));
1541    }
1542
1543    #[test]
1544    fn a_parse_that_reaches_the_end_is_not_truncated() {
1545        let result = super::Parser::lex_and_parse_file("fn f() {}\nimport \"go:fmt\"", 0);
1546        assert!(!result.truncated);
1547    }
1548
1549    #[test]
1550    fn an_import_inside_a_block_keeps_its_own_error() {
1551        let source = "fn f() {\n  import \"go:fmt\"\n}";
1552        assert_eq!(codes(source), ["parse.syntax_error"]);
1553    }
1554
1555    #[test]
1556    fn comments_between_imports_do_not_count_as_items() {
1557        let source = "import \"go:fmt\"\n// note\n\n// another note\nimport \"go:os\"\nfn f() {}";
1558        assert!(codes(source).is_empty());
1559    }
1560}
1561
1562#[cfg(test)]
1563mod file_comment_tests {
1564    use crate::build_ast;
1565
1566    fn file_comment(source: &str) -> Option<String> {
1567        let result = build_ast(source, 0);
1568        assert!(
1569            result.errors.is_empty(),
1570            "unexpected errors: {:?}",
1571            result.errors
1572        );
1573        result.file_comment
1574    }
1575
1576    #[test]
1577    fn consecutive_lines_join_with_newlines() {
1578        assert_eq!(
1579            file_comment("//! a\n//! b\nfn f() {}").as_deref(),
1580            Some("a\nb")
1581        );
1582    }
1583
1584    #[test]
1585    fn bare_line_contributes_empty_line() {
1586        assert_eq!(
1587            file_comment("//! a\n//!\n//! b\nfn f() {}").as_deref(),
1588            Some("a\n\nb")
1589        );
1590    }
1591
1592    #[test]
1593    fn blank_line_between_runs_is_an_error() {
1594        for source in [
1595            "//! a\n\n//! b\n\nfn f() {}",
1596            "//! a\r\n\r\n//! b\r\n\r\nfn f() {}",
1597            "//! a\n//!\n\n//! b\nfn f() {}",
1598        ] {
1599            let result = build_ast(source, 0);
1600            let codes: Vec<_> = result.errors.iter().map(|e| e.code.as_str()).collect();
1601            assert_eq!(
1602                codes,
1603                ["parse.split_file_comment"],
1604                "for source: {source:?}"
1605            );
1606        }
1607    }
1608
1609    #[test]
1610    fn anything_before_the_block_is_rejected() {
1611        for source in ["\n//! a\nfn f() {}", " //! a\nfn f() {}"] {
1612            let result = build_ast(source, 0);
1613            let codes: Vec<_> = result.errors.iter().map(|e| e.code.as_str()).collect();
1614            assert_eq!(
1615                codes,
1616                ["parse.misplaced_file_comment"],
1617                "for source: {source:?}"
1618            );
1619        }
1620    }
1621
1622    #[test]
1623    fn blank_lines_after_the_block_are_allowed() {
1624        assert_eq!(
1625            file_comment("//! a\n//! b\n\n\nfn f() {}").as_deref(),
1626            Some("a\nb")
1627        );
1628    }
1629
1630    #[test]
1631    fn leading_comment_makes_the_header_misplaced() {
1632        let result = build_ast("// leading\n//! too late\nfn f() {}", 0);
1633        let codes: Vec<_> = result.errors.iter().map(|e| e.code.as_str()).collect();
1634        assert_eq!(codes, ["parse.misplaced_file_comment"]);
1635    }
1636
1637    #[test]
1638    fn interleaved_comment_ends_the_block() {
1639        let result = build_ast("//! a\n// note\n//! b\nfn f() {}", 0);
1640        let codes: Vec<_> = result.errors.iter().map(|e| e.code.as_str()).collect();
1641        assert_eq!(codes, ["parse.misplaced_file_comment"]);
1642    }
1643
1644    #[test]
1645    fn comment_after_the_block_is_allowed() {
1646        assert_eq!(
1647            file_comment("//! a\n\n// section note\nfn f() {}").as_deref(),
1648            Some("a")
1649        );
1650    }
1651
1652    #[test]
1653    fn file_without_header_has_no_file_comment() {
1654        assert_eq!(file_comment("fn f() {}"), None);
1655    }
1656
1657    #[test]
1658    fn header_without_items_is_valid() {
1659        assert_eq!(
1660            file_comment("//! header only").as_deref(),
1661            Some("header only")
1662        );
1663    }
1664
1665    #[test]
1666    fn header_before_doc_commented_item() {
1667        let result = build_ast("//! header\n/// item doc\nfn f() {}", 0);
1668        assert!(result.errors.is_empty(), "{:?}", result.errors);
1669        assert_eq!(result.file_comment.as_deref(), Some("header"));
1670    }
1671
1672    #[test]
1673    fn misplaced_file_comment_reports_one_error_per_run() {
1674        let result = build_ast("fn f() {}\n//! a\n//! b\nfn g() {}", 0);
1675        let codes: Vec<_> = result.errors.iter().map(|e| e.code.as_str()).collect();
1676        assert_eq!(codes, ["parse.misplaced_file_comment"]);
1677    }
1678
1679    #[test]
1680    fn build_constraint_lines_are_rejected() {
1681        for source in [
1682            "//!+build ignore\nfn f() {}",
1683            "//! +build ignore\nfn f() {}",
1684            "//!  \t+build linux\nfn f() {}",
1685            "//! +build\nfn f() {}",
1686            "//! +build ignore\r\nfn f() {}",
1687            "//! +build\r\nfn f() {}",
1688            "//!\u{00A0}+build ignore\nfn f() {}",
1689            "//! +build\u{00A0}ignore\nfn f() {}",
1690            "//! +build\u{3000}ignore\nfn f() {}",
1691        ] {
1692            let result = build_ast(source, 0);
1693            let codes: Vec<_> = result.errors.iter().map(|e| e.code.as_str()).collect();
1694            assert_eq!(
1695                codes,
1696                ["parse.file_comment_build_constraint"],
1697                "for source: {source:?}"
1698            );
1699        }
1700    }
1701
1702    #[test]
1703    fn build_constraint_lookalikes_are_allowed() {
1704        for source in [
1705            "//! +buildx tag\nfn f() {}",
1706            "//! use +build wisely\nfn f() {}",
1707            "//! +builder pattern\nfn f() {}",
1708        ] {
1709            let result = build_ast(source, 0);
1710            assert!(result.errors.is_empty(), "for source: {source:?}");
1711        }
1712    }
1713}