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