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