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