1use crate::{Lexer, PErr, PResult};
2use smallvec::SmallVec;
3use solar_ast::{
4 self as ast, AstPath, Box, BoxSlice, DocComment, DocComments,
5 token::{Delimiter, Token, TokenKind},
6};
7use solar_data_structures::{BumpExt, fmt::or_list};
8use solar_interface::{
9 BytePos, Ident, Result, Session, Span, Symbol,
10 diagnostics::DiagCtxt,
11 error_code,
12 source_map::{FileName, SourceFile},
13};
14use std::{fmt, path::Path};
15
16mod expr;
17mod item;
18mod lit;
19mod stmt;
20mod ty;
21mod yul;
22
23const PARSER_RECURSION_LIMIT: usize = 256;
25
26#[doc = include_str!("../../doc-examples/parser.rs")]
34pub struct Parser<'sess, 'ast, 'cb> {
36 pub sess: &'sess Session,
38 pub arena: &'ast ast::Arena,
40
41 pub token: Token,
43 pub prev_token: Token,
45 expected_tokens: Vec<ExpectedToken>,
47 last_unexpected_token_span: Option<Span>,
49 docs: Vec<DocComment<'ast>>,
51 stmts: Vec<ast::Stmt<'ast>>,
56 yul_stmts: Vec<ast::yul::Stmt<'ast>>,
58
59 tokens: std::vec::IntoIter<Token>,
61
62 in_yul: bool,
64 pure_yul: bool,
66 in_contract: bool,
68 in_modifier: bool,
70 recover_incomplete_input: bool,
72
73 recursion_depth: usize,
75 #[allow(clippy::type_complexity)]
77 import_callback:
78 Option<std::boxed::Box<dyn FnMut(ast::ItemId, Span, &ast::ImportDirective<'ast>) + 'cb>>,
79}
80
81#[derive(Clone, Debug, PartialEq, Eq)]
82enum ExpectedToken {
83 Token(TokenKind),
84 Keyword(Symbol),
85 Lit,
86 StrLit,
87 Ident,
88 Path,
89 ElementaryType,
90}
91
92impl fmt::Display for ExpectedToken {
93 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
94 f.write_str(match self {
95 Self::Token(t) => return write!(f, "`{t}`"),
96 Self::Keyword(kw) => return write!(f, "`{kw}`"),
97 Self::StrLit => "string literal",
98 Self::Lit => "literal",
99 Self::Ident => "identifier",
100 Self::Path => "path",
101 Self::ElementaryType => "elementary type name",
102 })
103 }
104}
105
106impl ExpectedToken {
107 fn to_string_many(tokens: &[Self]) -> String {
108 or_list(tokens).to_string()
109 }
110
111 fn eq_kind(&self, other: TokenKind) -> bool {
112 match *self {
113 Self::Token(kind) => kind == other,
114 _ => false,
115 }
116 }
117}
118
119#[derive(Debug)]
121struct SeqSep {
122 sep: Option<TokenKind>,
124 trailing_sep_allowed: bool,
126 trailing_sep_required: bool,
128}
129
130impl SeqSep {
131 fn trailing_enforced(t: TokenKind) -> Self {
132 Self { sep: Some(t), trailing_sep_required: true, trailing_sep_allowed: true }
133 }
134
135 #[allow(dead_code)]
136 fn trailing_allowed(t: TokenKind) -> Self {
137 Self { sep: Some(t), trailing_sep_required: false, trailing_sep_allowed: true }
138 }
139
140 fn trailing_disallowed(t: TokenKind) -> Self {
141 Self { sep: Some(t), trailing_sep_required: false, trailing_sep_allowed: false }
142 }
143
144 fn none() -> Self {
145 Self { sep: None, trailing_sep_required: false, trailing_sep_allowed: false }
146 }
147}
148
149#[derive(Copy, Clone, Debug, PartialEq, Eq)]
151pub enum Recovered {
152 No,
153 Yes,
154}
155
156impl<'sess, 'ast, 'cb> Parser<'sess, 'ast, 'cb> {
157 pub fn new(sess: &'sess Session, arena: &'ast ast::Arena, tokens: Vec<Token>) -> Self {
159 assert!(sess.is_entered(), "session should be entered before parsing");
160 let mut parser = Self {
161 sess,
162 arena,
163 token: Token::DUMMY,
164 prev_token: Token::DUMMY,
165 expected_tokens: Vec::with_capacity(8),
166 last_unexpected_token_span: None,
167 docs: Vec::with_capacity(4),
168 stmts: Vec::new(),
169 yul_stmts: Vec::new(),
170 tokens: tokens.into_iter(),
171 in_yul: false,
172 pure_yul: false,
173 in_contract: false,
174 in_modifier: false,
175 recover_incomplete_input: sess.opts.unstable.recover_incomplete_input,
176 recursion_depth: 0,
177 import_callback: None,
178 };
179 parser.bump();
180 parser
181 }
182
183 pub fn set_import_callback(
185 &mut self,
186 import_callback: impl FnMut(ast::ItemId, Span, &ast::ImportDirective<'ast>) + 'cb,
187 ) {
188 self.import_callback = Some(std::boxed::Box::new(import_callback));
189 }
190
191 pub fn from_source_code(
193 sess: &'sess Session,
194 arena: &'ast ast::Arena,
195 filename: FileName,
196 src: impl Into<String>,
197 ) -> Result<Self> {
198 Self::from_lazy_source_code(sess, arena, filename, || Ok(src.into()))
199 }
200
201 pub fn from_file(sess: &'sess Session, arena: &'ast ast::Arena, path: &Path) -> Result<Self> {
205 Self::from_lazy_source_code(sess, arena, FileName::Real(path.to_path_buf()), || {
206 sess.source_map().file_loader().load_file(path)
207 })
208 }
209
210 pub fn from_lazy_source_code(
214 sess: &'sess Session,
215 arena: &'ast ast::Arena,
216 filename: FileName,
217 get_src: impl FnOnce() -> std::io::Result<String>,
218 ) -> Result<Self> {
219 let file = sess
220 .source_map()
221 .new_source_file_with(filename, get_src)
222 .map_err(|e| sess.dcx.err(e.to_string()).emit())?;
223 Ok(Self::from_source_file(sess, arena, &file))
224 }
225
226 pub fn from_source_file(
232 sess: &'sess Session,
233 arena: &'ast ast::Arena,
234 file: &SourceFile,
235 ) -> Self {
236 Self::from_lexer(arena, Lexer::from_source_file(sess, file))
237 }
238
239 pub fn from_lexer(arena: &'ast ast::Arena, lexer: Lexer<'sess, '_>) -> Self {
241 Self::new(lexer.sess, arena, lexer.into_tokens())
242 }
243
244 #[inline]
246 pub fn dcx(&self) -> &'sess DiagCtxt {
247 &self.sess.dcx
248 }
249
250 pub fn alloc<T>(&self, value: T) -> Box<'ast, T> {
252 self.arena.alloc(value)
253 }
254
255 pub fn alloc_path(&self, segments: &[Ident]) -> AstPath<'ast> {
261 AstPath::new_in(self.arena.bump(), segments)
263 }
264
265 pub fn alloc_vec<T>(&self, values: Vec<T>) -> BoxSlice<'ast, T> {
267 self.arena.alloc_vec_thin((), values)
268 }
269
270 pub fn alloc_smallvec<A: smallvec::Array>(
272 &self,
273 values: SmallVec<A>,
274 ) -> BoxSlice<'ast, A::Item> {
275 self.arena.alloc_smallvec_thin((), values)
276 }
277
278 fn alloc_drain<A: smallvec::Array>(&self, values: &mut SmallVec<A>) -> BoxSlice<'ast, A::Item> {
283 self.arena.alloc_smallvec_drain_thin((), values)
284 }
285
286 pub fn alloc_from_iter<T>(&self, values: impl Iterator<Item = T>) -> BoxSlice<'ast, T> {
288 self.arena.alloc_from_iter_thin((), values)
289 }
290
291 #[inline]
293 #[track_caller]
294 pub fn unexpected<T>(&mut self) -> PResult<'sess, T> {
295 Err(self.unexpected_error())
296 }
297
298 #[cold]
300 #[track_caller]
301 pub fn unexpected_error(&mut self) -> PErr<'sess> {
302 match self.expected_one_of_not_found(&[], &[]) {
303 Ok(b) => unreachable!("`unexpected()` returned Ok({b:?})"),
304 Err(e) => e,
305 }
306 }
307
308 #[inline]
310 #[track_caller]
311 pub fn expect(&mut self, tok: TokenKind) -> PResult<'sess, Recovered> {
312 if self.check_noexpect(tok) {
313 self.bump();
314 Ok(Recovered::No)
315 } else {
316 self.expected_one_of_not_found(std::slice::from_ref(&tok), &[])
317 }
318 }
319
320 #[track_caller]
324 pub fn expect_one_of(
325 &mut self,
326 edible: &[TokenKind],
327 inedible: &[TokenKind],
328 ) -> PResult<'sess, Recovered> {
329 if edible.contains(&self.token.kind) {
330 self.bump();
331 Ok(Recovered::No)
332 } else if inedible.contains(&self.token.kind) {
333 Ok(Recovered::No)
335 } else {
336 self.expected_one_of_not_found(edible, inedible)
337 }
338 }
339
340 #[cold]
341 #[track_caller]
342 fn expected_one_of_not_found(
343 &mut self,
344 edible: &[TokenKind],
345 inedible: &[TokenKind],
346 ) -> PResult<'sess, Recovered> {
347 if self.token.kind != TokenKind::Eof
348 && self.last_unexpected_token_span == Some(self.token.span)
349 {
350 panic!("called unexpected twice on the same token");
351 }
352
353 let mut expected = edible
354 .iter()
355 .chain(inedible)
356 .cloned()
357 .map(ExpectedToken::Token)
358 .chain(self.expected_tokens.iter().cloned())
359 .filter(|token| {
360 fn is_ident_eq_keyword(found: TokenKind, expected: &ExpectedToken) -> bool {
363 if let TokenKind::Ident(current_sym) = found
364 && let ExpectedToken::Keyword(suggested_sym) = expected
365 {
366 return current_sym == *suggested_sym;
367 }
368 false
369 }
370
371 if !token.eq_kind(self.token.kind) {
372 let eq = is_ident_eq_keyword(self.token.kind, token);
373 if !eq {
380 if let ExpectedToken::Token(kind) = token
381 && *kind == self.token.kind
382 {
383 return false;
384 }
385 return true;
386 }
387 }
388 false
389 })
390 .collect::<Vec<_>>();
391 expected.sort_by_cached_key(ToString::to_string);
392 expected.dedup();
393
394 let expect = ExpectedToken::to_string_many(&expected);
395 let actual = self.token.full_description();
396 let (msg_exp, (mut label_span, label_exp)) = match expected.len() {
397 0 => (
398 format!("unexpected token: {actual}"),
399 (self.prev_token.span, "unexpected token after this".to_string()),
400 ),
401 1 => (
402 format!("expected {expect}, found {actual}"),
403 (self.prev_token.span.shrink_to_hi(), format!("expected {expect}")),
404 ),
405 len => {
406 let fmt = format!("expected one of {expect}, found {actual}");
407 let short_expect = if len > 6 { format!("{len} possible tokens") } else { expect };
408 let s = self.prev_token.span.shrink_to_hi();
409 (fmt, (s, format!("expected one of {short_expect}")))
410 }
411 };
412 if self.token.is_eof() {
413 label_span = self.prev_token.span;
415 };
416
417 self.last_unexpected_token_span = Some(self.token.span);
418 let mut err = self.dcx().err(msg_exp).span(self.token.span);
419
420 if self.prev_token.span.is_dummy()
421 || !self
422 .sess
423 .source_map()
424 .is_multiline(self.token.span.shrink_to_hi().until(label_span.shrink_to_lo()))
425 {
426 err = err.span_label(self.token.span, label_exp);
429 } else {
430 err = err.span_label(label_span, label_exp);
431 err = err.span_label(self.token.span, "unexpected token");
432 }
433
434 Err(err)
435 }
436
437 #[inline]
439 #[track_caller]
440 fn expect_semi(&mut self) -> PResult<'sess, ()> {
441 let recover = self.recover_incomplete_input
442 && matches!(self.token.kind, TokenKind::CloseDelim(Delimiter::Brace) | TokenKind::Eof);
443 if recover && self.last_unexpected_token_span == Some(self.token.span) {
444 return Ok(());
445 }
446 match self.expect(TokenKind::Semi) {
447 Ok(_) => Ok(()),
448 Err(err) if recover => {
449 err.emit();
450 Ok(())
451 }
452 Err(err) => Err(err),
453 }
454 }
455
456 #[track_caller]
461 fn expect_seq_close(&mut self, ket: TokenKind) -> PResult<'sess, ()> {
462 if self.recover_incomplete_input && self.token.is_eof() {
463 if self.last_unexpected_token_span != Some(self.token.span)
464 && let Err(err) = self.expect(ket)
465 {
466 err.emit();
467 }
468 return Ok(());
469 }
470 self.expect(ket).map(drop)
471 }
472
473 #[inline]
478 #[must_use]
479 fn check(&mut self, tok: TokenKind) -> bool {
480 let is_present = self.check_noexpect(tok);
481 if !is_present {
482 self.push_expected(ExpectedToken::Token(tok));
483 }
484 is_present
485 }
486
487 #[inline]
488 #[must_use]
489 fn check_noexpect(&self, tok: TokenKind) -> bool {
490 self.token.kind == tok
491 }
492
493 #[inline]
498 #[must_use]
499 pub fn eat_noexpect(&mut self, tok: TokenKind) -> bool {
500 let is_present = self.check_noexpect(tok);
501 if is_present {
502 self.bump()
503 }
504 is_present
505 }
506
507 #[inline]
509 #[must_use]
510 pub fn eat(&mut self, tok: TokenKind) -> bool {
511 let is_present = self.check(tok);
512 if is_present {
513 self.bump()
514 }
515 is_present
516 }
517
518 #[inline]
521 #[must_use]
522 fn check_keyword(&mut self, kw: Symbol) -> bool {
523 let is_keyword = self.token.is_keyword(kw);
524 if !is_keyword {
525 self.push_expected(ExpectedToken::Keyword(kw));
526 }
527 is_keyword
528 }
529
530 #[inline]
533 #[must_use]
534 pub fn eat_keyword(&mut self, kw: Symbol) -> bool {
535 let is_keyword = self.check_keyword(kw);
536 if is_keyword {
537 self.bump();
538 }
539 is_keyword
540 }
541
542 #[track_caller]
546 fn expect_keyword(&mut self, kw: Symbol) -> PResult<'sess, ()> {
547 if !self.eat_keyword(kw) { self.unexpected() } else { Ok(()) }
548 }
549
550 #[must_use]
551 fn check_ident(&mut self) -> bool {
552 self.check_or_expected(self.token.is_ident(), ExpectedToken::Ident)
553 }
554
555 #[must_use]
556 fn check_nr_ident(&mut self) -> bool {
557 self.check_or_expected(self.token.is_non_reserved_ident(self.in_yul), ExpectedToken::Ident)
558 }
559
560 #[must_use]
561 fn check_path(&mut self) -> bool {
562 self.check_or_expected(self.token.is_ident(), ExpectedToken::Path)
563 }
564
565 #[must_use]
566 fn check_lit(&mut self) -> bool {
567 self.check_or_expected(self.token.is_lit(), ExpectedToken::Lit)
568 }
569
570 #[must_use]
571 fn check_str_lit(&mut self) -> bool {
572 self.check_or_expected(self.token.is_str_lit(), ExpectedToken::StrLit)
573 }
574
575 #[must_use]
576 fn check_elementary_type(&mut self) -> bool {
577 self.check_or_expected(self.token.is_elementary_type(), ExpectedToken::ElementaryType)
578 }
579
580 #[must_use]
581 fn check_or_expected(&mut self, ok: bool, t: ExpectedToken) -> bool {
582 if !ok {
583 self.push_expected(t);
584 }
585 ok
586 }
587
588 fn push_expected(&mut self, expected: ExpectedToken) {
590 self.expected_tokens.push(expected);
591 }
592
593 #[track_caller]
597 #[inline]
598 fn parse_paren_comma_seq<T>(
599 &mut self,
600 allow_empty: bool,
601 f: impl FnMut(&mut Self) -> PResult<'sess, T>,
602 ) -> PResult<'sess, BoxSlice<'ast, T>> {
603 self.parse_delim_comma_seq(Delimiter::Parenthesis, allow_empty, f)
604 }
605
606 #[track_caller]
610 #[inline]
611 fn parse_delim_comma_seq<T>(
612 &mut self,
613 delim: Delimiter,
614 allow_empty: bool,
615 f: impl FnMut(&mut Self) -> PResult<'sess, T>,
616 ) -> PResult<'sess, BoxSlice<'ast, T>> {
617 self.parse_delim_seq(delim, SeqSep::trailing_disallowed(TokenKind::Comma), allow_empty, f)
618 }
619
620 #[track_caller]
623 #[inline]
624 fn parse_nodelim_comma_seq<T>(
625 &mut self,
626 stop: TokenKind,
627 allow_empty: bool,
628 f: impl FnMut(&mut Self) -> PResult<'sess, T>,
629 ) -> PResult<'sess, BoxSlice<'ast, T>> {
630 self.parse_seq_to_before_end(
631 stop,
632 SeqSep::trailing_disallowed(TokenKind::Comma),
633 allow_empty,
634 f,
635 )
636 .map(|(v, _recovered)| v)
637 }
638
639 #[track_caller]
643 #[inline]
644 fn parse_delim_seq<T>(
645 &mut self,
646 delim: Delimiter,
647 sep: SeqSep,
648 allow_empty: bool,
649 f: impl FnMut(&mut Self) -> PResult<'sess, T>,
650 ) -> PResult<'sess, BoxSlice<'ast, T>> {
651 self.parse_unspanned_seq::<_, 8>(
652 TokenKind::OpenDelim(delim),
653 TokenKind::CloseDelim(delim),
654 sep,
655 allow_empty,
656 f,
657 )
658 }
659
660 #[track_caller]
664 #[inline(always)]
665 fn parse_unspanned_seq<T, const N: usize>(
666 &mut self,
667 bra: TokenKind,
668 ket: TokenKind,
669 sep: SeqSep,
670 allow_empty: bool,
671 f: impl FnMut(&mut Self) -> PResult<'sess, T>,
672 ) -> PResult<'sess, BoxSlice<'ast, T>> {
673 self.expect(bra)?;
674 self.parse_seq_to_end::<_, N>(ket, sep, allow_empty, f)
675 }
676
677 #[track_caller]
681 #[inline(always)]
682 fn parse_seq_to_end<T, const N: usize>(
683 &mut self,
684 ket: TokenKind,
685 sep: SeqSep,
686 allow_empty: bool,
687 f: impl FnMut(&mut Self) -> PResult<'sess, T>,
688 ) -> PResult<'sess, BoxSlice<'ast, T>> {
689 let (val, recovered) = self.parse_seq_to_before_tokens::<_, N>(ket, sep, allow_empty, f)?;
690 if recovered == Recovered::No {
691 self.expect_seq_close(ket)?;
692 }
693 Ok(val)
694 }
695
696 #[track_caller]
700 #[inline]
701 fn parse_seq_to_before_end<T>(
702 &mut self,
703 ket: TokenKind,
704 sep: SeqSep,
705 allow_empty: bool,
706 f: impl FnMut(&mut Self) -> PResult<'sess, T>,
707 ) -> PResult<'sess, (BoxSlice<'ast, T>, Recovered)> {
708 self.parse_seq_to_before_tokens::<_, 8>(ket, sep, allow_empty, f)
709 }
710
711 #[track_caller]
715 fn parse_seq_to_before_tokens<T, const N: usize>(
716 &mut self,
717 ket: TokenKind,
718 sep: SeqSep,
719 allow_empty: bool,
720 f: impl FnMut(&mut Self) -> PResult<'sess, T>,
721 ) -> PResult<'sess, (BoxSlice<'ast, T>, Recovered)> {
722 let mut v = SmallVec::<[T; N]>::new();
723 let recovered = self.parse_seq_into(ket, sep, allow_empty, f, |_, value| v.push(value))?;
724 Ok((self.alloc_drain(&mut v), recovered))
725 }
726
727 #[track_caller]
729 fn parse_block_seq<T>(
730 &mut self,
731 buf: impl Fn(&mut Self) -> &mut Vec<T> + Copy,
732 f: impl FnMut(&mut Self) -> PResult<'sess, T>,
733 ) -> PResult<'sess, BoxSlice<'ast, T>> {
734 self.expect(TokenKind::OpenDelim(Delimiter::Brace))?;
735 let start = buf(self).len();
736 let ket = TokenKind::CloseDelim(Delimiter::Brace);
737 let res =
738 self.parse_seq_into(ket, SeqSep::none(), true, f, |this, value| buf(this).push(value));
739 let arena = self.arena;
740 let items = buf(self);
741 let slice = unsafe {
743 let slice = arena.alloc_thin_slice_unchecked((), &items[start..]);
744 items.set_len(start);
745 slice
746 };
747 if res? == Recovered::No {
748 self.expect_seq_close(ket)?;
749 }
750 Ok(slice)
751 }
752
753 #[track_caller]
755 fn parse_seq_into<T>(
756 &mut self,
757 ket: TokenKind,
758 sep: SeqSep,
759 allow_empty: bool,
760 mut f: impl FnMut(&mut Self) -> PResult<'sess, T>,
761 mut push: impl FnMut(&mut Self, T),
762 ) -> PResult<'sess, Recovered> {
763 let mut first = true;
764 let mut recovered = Recovered::No;
765 let mut trailing = false;
766
767 loop {
768 let required_first = first && !allow_empty;
769 if !required_first && self.check(ket) {
770 break;
771 }
772 if !required_first && self.token.kind == TokenKind::Eof {
773 if !first && let Some(sep_kind) = sep.sep {
775 self.push_expected(ExpectedToken::Token(sep_kind));
776 }
777 break;
778 }
779
780 if first {
781 first = false;
783 } else if let Some(sep_kind) = sep.sep {
784 let recovered_ = self.expect(sep_kind)?;
786 if recovered_ == Recovered::Yes {
787 recovered = Recovered::Yes;
788 break;
789 }
790
791 if self.check(ket) {
792 trailing = true;
793 break;
794 }
795 }
796
797 match f(self) {
798 Ok(value) => push(self, value),
799 Err(err) if self.can_recover_sequence(ket) => {
800 err.emit();
801 if ket == TokenKind::CloseDelim(Delimiter::Brace)
802 && sep.sep.is_none()
803 && self.token.kind == TokenKind::Semi
804 {
805 self.bump();
806 continue;
807 }
808 if self.token.kind == ket {
809 self.bump();
810 }
811 recovered = Recovered::Yes;
812 break;
813 }
814 Err(err) => return Err(err),
815 }
816 }
817
818 if let Some(sep_kind) = sep.sep {
819 let open_close_delim = first && allow_empty;
820 if !open_close_delim
821 && sep.trailing_sep_required
822 && !trailing
823 && let Err(e) = self.expect(sep_kind)
824 {
825 e.emit();
826 if self.token.is_eof() {
828 recovered = Recovered::Yes;
829 }
830 }
831 if !sep.trailing_sep_allowed && trailing {
832 let msg = format!("trailing `{sep_kind}` separator is not allowed");
833 self.dcx().emit_err(self.prev_token.span, msg);
834 }
835 }
836
837 Ok(recovered)
838 }
839
840 fn can_recover_sequence(&self, ket: TokenKind) -> bool {
841 self.recover_incomplete_input
842 && (self.token.kind == ket
843 || matches!(
844 self.token.kind,
845 TokenKind::Semi | TokenKind::Eof | TokenKind::CloseDelim(_)
846 ))
847 }
848
849 pub fn bump(&mut self) {
851 let next = self.next_token();
852 if next.is_comment_or_doc() {
853 return self.bump_trivia(next);
854 }
855 self.inlined_bump_with(next);
856 }
857
858 pub fn bump_with(&mut self, next: Token) {
864 self.inlined_bump_with(next);
865 }
866
867 #[inline(always)]
869 fn inlined_bump_with(&mut self, next: Token) {
870 #[cfg(debug_assertions)]
871 if next.is_comment_or_doc() {
872 self.dcx().bug("`bump_with` should not be used with comments").span(next.span).emit();
873 }
874 self.prev_token = std::mem::replace(&mut self.token, next);
875 self.expected_tokens.clear();
876 self.docs.clear();
877 }
878
879 #[cold]
883 fn bump_trivia(&mut self, next: Token) {
884 self.docs.clear();
885
886 debug_assert!(next.is_comment_or_doc());
887 self.prev_token = std::mem::replace(&mut self.token, next);
888 let mut items = SmallVec::new();
889 while let Some((is_doc, kind, symbol)) = self.token.comment() {
890 if is_doc {
891 parse_natspec(self.token.span, symbol, kind, self.in_yul, self.dcx(), &mut items);
892 let natspec = if items.is_empty() {
893 BoxSlice::default()
894 } else {
895 self.alloc_drain(&mut items)
896 };
897 self.docs.push(DocComment { kind, span: self.token.span, symbol, natspec });
898 }
899 self.token = self.next_token();
901 }
902
903 self.expected_tokens.clear();
904 }
905
906 #[inline(always)]
910 fn next_token(&mut self) -> Token {
911 self.tokens.next().unwrap_or(Token::new(TokenKind::Eof, self.token.span))
912 }
913
914 #[inline]
919 pub fn look_ahead(&self, dist: usize) -> Token {
920 match dist {
922 0 => self.token,
923 1 => self.look_ahead_full(1),
924 2 => self.look_ahead_full(2),
925 dist => self.look_ahead_full(dist),
926 }
927 }
928
929 fn look_ahead_full(&self, dist: usize) -> Token {
930 self.tokens
931 .as_slice()
932 .iter()
933 .copied()
934 .filter(|t| !t.is_comment_or_doc())
935 .nth(dist - 1)
936 .unwrap_or(Token::EOF)
937 }
938
939 #[inline]
943 pub fn look_ahead_with<R>(&self, dist: usize, f: impl FnOnce(Token) -> R) -> R {
944 f(self.look_ahead(dist))
945 }
946
947 #[inline]
949 fn in_contract<R>(&mut self, f: impl FnOnce(&mut Self) -> R) -> R {
950 let old = std::mem::replace(&mut self.in_contract, true);
951 let res = f(self);
952 self.in_contract = old;
953 res
954 }
955
956 #[inline]
958 fn in_yul<R>(&mut self, f: impl FnOnce(&mut Self) -> R) -> R {
959 let old = std::mem::replace(&mut self.in_yul, true);
960 let res = f(self);
961 self.in_yul = old;
962 res
963 }
964
965 #[inline]
967 fn in_pure_yul<R>(&mut self, f: impl FnOnce(&mut Self) -> R) -> R {
968 let old = std::mem::replace(&mut self.pure_yul, true);
969 let res = f(self);
970 self.pure_yul = old;
971 res
972 }
973
974 #[inline]
976 pub fn with_recursion_limit<T>(
977 &mut self,
978 context: &str,
979 f: impl FnOnce(&mut Self) -> PResult<'sess, T>,
980 ) -> PResult<'sess, T> {
981 self.recursion_depth += 1;
982 let res = if self.recursion_depth > PARSER_RECURSION_LIMIT {
983 Err(self.recursion_limit_reached(context))
984 } else {
985 f(self)
986 };
987 self.recursion_depth -= 1;
988 res
989 }
990
991 #[cold]
992 fn recursion_limit_reached(&mut self, context: &str) -> PErr<'sess> {
993 let mut err = self.dcx().err("recursion limit reached").span(self.token.span);
994 if !self.prev_token.span.is_dummy() {
995 err = err.span_label(self.prev_token.span, format!("while parsing {context}"));
996 }
997 err
998 }
999}
1000
1001impl<'sess, 'ast, 'cb> Parser<'sess, 'ast, 'cb> {
1003 #[track_caller]
1005 pub fn parse_spanned<T>(
1006 &mut self,
1007 f: impl FnOnce(&mut Self) -> PResult<'sess, T>,
1008 ) -> PResult<'sess, (Span, T)> {
1009 let lo = self.token.span;
1010 let res = f(self);
1011 let span = lo.to(self.prev_token.span);
1012 match res {
1013 Ok(t) => Ok((span, t)),
1014 Err(e) if e.span.is_dummy() => Err(e.span(span)),
1015 Err(e) => Err(e),
1016 }
1017 }
1018
1019 #[inline]
1021 pub fn parse_doc_comments(&mut self) -> DocComments<'ast> {
1022 if !self.docs.is_empty() { self.parse_doc_comments_inner() } else { Default::default() }
1023 }
1024
1025 #[cold]
1026 fn parse_doc_comments_inner(&mut self) -> DocComments<'ast> {
1027 assert!(!std::mem::needs_drop::<DocComments<'_>>());
1030 let docs = unsafe { self.arena.alloc_thin_slice_unchecked((), &self.docs) };
1031 self.docs.clear();
1032 docs.into()
1033 }
1034
1035 #[track_caller]
1037 pub fn parse_path(&mut self) -> PResult<'sess, AstPath<'ast>> {
1038 let first = self.parse_ident()?;
1039 self.parse_path_with(first)
1040 }
1041
1042 #[track_caller]
1044 pub fn parse_path_with(&mut self, first: Ident) -> PResult<'sess, AstPath<'ast>> {
1045 if self.in_yul {
1046 self.parse_path_with_f(first, Self::parse_yul_path_ident)
1047 } else {
1048 self.parse_path_with_f(first, Self::parse_ident)
1049 }
1050 }
1051
1052 fn parse_yul_path_ident(&mut self) -> PResult<'sess, Ident> {
1054 let ident = self.ident_or_err(true)?;
1055 if !ident.is_yul_builtin() && self.is_reserved_yul_ident(ident) {
1056 self.expected_ident_found_err().emit();
1057 }
1058 self.bump();
1059 Ok(ident)
1060 }
1061
1062 #[track_caller]
1064 pub fn parse_path_any(&mut self) -> PResult<'sess, AstPath<'ast>> {
1065 let first = self.parse_ident_any()?;
1066 self.parse_path_with_f(first, Self::parse_ident_any)
1067 }
1068
1069 #[track_caller]
1071 fn parse_path_with_f(
1072 &mut self,
1073 first: Ident,
1074 mut f: impl FnMut(&mut Self) -> PResult<'sess, Ident>,
1075 ) -> PResult<'sess, AstPath<'ast>> {
1076 if !self.check_noexpect(TokenKind::Dot) {
1077 return Ok(self.alloc_path(&[first]));
1078 }
1079
1080 let mut path = SmallVec::<[_; 4]>::new();
1081 path.push(first);
1082 while self.eat(TokenKind::Dot) {
1083 path.push(f(self)?);
1084 }
1085 Ok(self.alloc_path(&path))
1086 }
1087
1088 #[track_caller]
1090 pub fn parse_ident(&mut self) -> PResult<'sess, Ident> {
1091 self.parse_ident_common(true)
1092 }
1093
1094 #[track_caller]
1096 pub fn parse_ident_any(&mut self) -> PResult<'sess, Ident> {
1097 let ident = self.ident_or_err(true)?;
1098 self.bump();
1099 Ok(ident)
1100 }
1101
1102 #[track_caller]
1104 pub fn parse_ident_opt(&mut self) -> PResult<'sess, Option<Ident>> {
1105 if self.check_ident() { self.parse_ident().map(Some) } else { Ok(None) }
1106 }
1107
1108 #[track_caller]
1109 fn parse_ident_common(&mut self, recover: bool) -> PResult<'sess, Ident> {
1110 let ident = self.ident_or_err(recover)?;
1111 if self.in_yul && ident.is_future_yul_reserved_identifier(self.sess.opts.evm_version) {
1112 self.dcx()
1113 .warn(format!(
1114 "`{ident}` will be promoted to Yul reserved identifier in the future and will not be allowed anymore as an identifier"
1115 ))
1116 .span(ident.span)
1117 .code(error_code!(5470))
1118 .emit();
1119 } else if if self.in_yul {
1120 self.is_reserved_yul_ident(ident)
1121 } else {
1122 ident.is_reserved(false) || ast::ElementaryType::is_fixed_mxn(ident.name)
1124 } {
1125 let err = self.expected_ident_found_err();
1126 if recover {
1127 err.emit();
1128 } else {
1129 return Err(err);
1130 }
1131 }
1132 self.bump();
1133 Ok(ident)
1134 }
1135
1136 #[inline]
1137 fn is_reserved_yul_ident(&self, ident: Ident) -> bool {
1138 ident.is_yul_keyword()
1139 || (ident.is_yul_builtin()
1140 && !ident.is_future_yul_reserved_identifier(self.sess.opts.evm_version)
1141 && (self.pure_yul || ident.is_reserved_yul_builtin_in(self.sess.opts.evm_version)))
1142 }
1143
1144 #[track_caller]
1146 fn ident_or_err(&mut self, recover: bool) -> PResult<'sess, Ident> {
1147 match self.token.ident() {
1148 Some(ident) => Ok(ident),
1149 None => self.expected_ident_found(recover),
1150 }
1151 }
1152
1153 #[cold]
1154 #[track_caller]
1155 fn expected_ident_found(&mut self, recover: bool) -> PResult<'sess, Ident> {
1156 self.expected_ident_found_other(self.token, recover)
1157 }
1158
1159 #[cold]
1160 #[track_caller]
1161 fn expected_ident_found_other(&mut self, token: Token, recover: bool) -> PResult<'sess, Ident> {
1162 let msg = format!("expected identifier, found {}", token.full_description());
1163 let span = token.span;
1164 let mut err = self.dcx().err(msg).span(span);
1165
1166 let mut recovered_ident = None;
1167
1168 let suggest_remove_comma = token.kind == TokenKind::Comma && self.look_ahead(1).is_ident();
1169 if suggest_remove_comma {
1170 if recover {
1171 self.bump();
1172 recovered_ident = self.ident_or_err(false).ok();
1173 }
1174 err = err.span_help(span, "remove this comma");
1175 }
1176
1177 if recover && let Some(ident) = recovered_ident {
1178 err.emit();
1179 return Ok(ident);
1180 }
1181 Err(err)
1182 }
1183
1184 #[cold]
1185 #[track_caller]
1186 fn expected_ident_found_err(&mut self) -> PErr<'sess> {
1187 self.expected_ident_found(false).unwrap_err()
1188 }
1189}
1190
1191fn parse_natspec(
1209 comment_span: Span,
1210 comment_symbol: Symbol,
1211 comment_kind: ast::CommentKind,
1212 in_yul: bool,
1213 dcx: &DiagCtxt,
1214 items: &mut SmallVec<[ast::NatSpecItem; 6]>,
1215) {
1216 let content = comment_symbol.as_str();
1217 let bytes = content.as_bytes();
1218
1219 if memchr::memchr(b'@', bytes).is_none() {
1221 if content.trim().is_empty() {
1222 return;
1223 }
1224
1225 items.push(ast::NatSpecItem {
1227 kind: ast::NatSpecKind::Notice,
1228 span: comment_span,
1229 symbol: comment_symbol,
1230 content_start: 0,
1231 content_end: content.len() as u32,
1232 });
1233 return;
1234 }
1235
1236 const PREFIX_BYTES: u32 = 3;
1238 let (mut line_start, mut content_start, mut span, mut kind) = (0, 0usize, None, None);
1239
1240 fn flush_item(
1241 items: &mut SmallVec<[ast::NatSpecItem; 6]>,
1242 kind: &mut Option<ast::NatSpecKind>,
1243 span: &mut Option<Span>,
1244 symbol: Symbol,
1245 content_start: usize,
1246 content_end: usize,
1247 ) {
1248 if let Some(k) = kind.take() {
1249 items.push(ast::NatSpecItem {
1250 span: span.take().unwrap(),
1251 kind: k,
1252 symbol,
1253 content_start: content_start as u32,
1254 content_end: content_end as u32,
1255 });
1256 }
1257 }
1258
1259 #[cold]
1260 #[inline(never)]
1261 fn invalid_tag(dcx: &DiagCtxt, tag: &str, span: Span) {
1262 dcx.warn(format!(
1263 "invalid natspec tag '@{tag}', custom tags must use format '@custom:name'"
1264 ))
1265 .code(error_code!(6546))
1266 .span(span)
1267 .emit();
1268 }
1269
1270 let is_line_start = |line_start: usize, at_pos: usize| {
1272 match comment_kind {
1273 ast::CommentKind::Line => bytes[line_start..at_pos].trim_ascii().is_empty(),
1275
1276 ast::CommentKind::Block => {
1281 let mut rest = bytes[line_start..at_pos].trim_ascii_start();
1282 while let Some(stripped) = rest.strip_prefix(b"*") {
1283 rest = stripped.trim_ascii_start();
1284 }
1285 rest.is_empty()
1286 }
1287 }
1288 };
1289
1290 let mut prev_line_end = 0;
1292 for line_end in memchr::memchr_iter(b'\n', bytes).chain(std::iter::once(bytes.len())) {
1293 if let Some(tag_offset) = memchr::memchr(b'@', &bytes[line_start..line_end])
1294 && is_line_start(line_start, line_start + tag_offset)
1295 {
1296 let tag_start = line_start + tag_offset + 1;
1297
1298 let (tag, rest_start) = crate::natspec::split_once_ws(content, tag_start, line_end);
1301 if tag.is_empty() {
1302 prev_line_end = line_end;
1303 line_start = line_end + 1;
1304 continue;
1305 }
1306
1307 flush_item(items, &mut kind, &mut span, comment_symbol, content_start, prev_line_end);
1308
1309 let tag_lo = comment_span.lo().0 + PREFIX_BYTES + 1 + (line_start + tag_offset) as u32; let tag_hi = tag_lo + tag.len() as u32;
1312 span = Some(Span::new(BytePos(tag_lo), BytePos(tag_hi)));
1313 content_start = rest_start;
1314
1315 kind = Some(match tag {
1316 "title" => ast::NatSpecKind::Title,
1317 "author" => ast::NatSpecKind::Author,
1318 "notice" => ast::NatSpecKind::Notice,
1319 "dev" => ast::NatSpecKind::Dev,
1320 "param" | "inheritdoc" => {
1321 let name_start = rest_start;
1322 let (name, content_start_pos) =
1325 crate::natspec::split_once_ident(content, rest_start, line_end);
1326 content_start = content_start_pos;
1327 let name_lo = comment_span.lo() + PREFIX_BYTES + name_start as u32;
1328 let name_span = Span::new(name_lo, name_lo + name.len() as u32);
1329 let ident = Ident::new(Symbol::intern(name), name_span);
1330 match tag {
1331 "param" => ast::NatSpecKind::Param { name: ident },
1332 "inheritdoc" => ast::NatSpecKind::Inheritdoc { contract: ident },
1333 _ => unreachable!(),
1334 }
1335 }
1336 "return" => ast::NatSpecKind::Return { name: None },
1337 _ => {
1338 if let Some(custom_tag) = tag.strip_prefix("custom:") {
1339 let ident = Ident::new(Symbol::intern(custom_tag), comment_span);
1340 ast::NatSpecKind::Custom { name: ident }
1341 } else if ast::NATSPEC_INTERNAL_TAGS[..].contains(&tag) {
1342 let ident = Ident::new(Symbol::intern(tag), comment_span);
1343 ast::NatSpecKind::Internal { tag: ident }
1344 } else {
1345 if !in_yul {
1347 invalid_tag(dcx, tag, comment_span);
1348 }
1349 line_start = line_end + 1;
1350 prev_line_end = line_end;
1351 continue;
1352 }
1353 }
1354 });
1355 }
1356
1357 prev_line_end = line_end;
1358 line_start = line_end + 1;
1359 }
1360 flush_item(items, &mut kind, &mut span, comment_symbol, content_start, bytes.len());
1361}
1362
1363#[cfg(test)]
1364mod tests {
1365 use super::*;
1366 use solar_interface::{Session, SourceMap};
1367
1368 fn check_natspec_item(
1369 sm: &SourceMap,
1370 symbol: Symbol,
1371 item: &ast::NatSpecItem,
1372 snip: &str,
1373 kind: &str,
1374 name: Option<&str>,
1375 content: Option<&str>,
1376 ) {
1377 assert_eq!(sm.span_to_snippet(item.span).unwrap(), snip);
1378
1379 let actual_name = match &item.kind {
1380 ast::NatSpecKind::Title if kind == "title" => None,
1381 ast::NatSpecKind::Author if kind == "author" => None,
1382 ast::NatSpecKind::Notice if kind == "notice" => None,
1383 ast::NatSpecKind::Dev if kind == "dev" => None,
1384 ast::NatSpecKind::Param { name } if kind == "param" => Some(name.name.as_str()),
1385 ast::NatSpecKind::Return { .. } if kind == "return" => None,
1386 ast::NatSpecKind::Inheritdoc { contract } if kind == "inheritdoc" => {
1387 Some(contract.name.as_str())
1388 }
1389 ast::NatSpecKind::Custom { name } if kind == "custom" => Some(name.name.as_str()),
1390 ast::NatSpecKind::Internal { tag } if kind == "internal" => Some(tag.name.as_str()),
1391 _ => panic!("kind mismatch: expected {kind}, got {:?}", item.kind),
1392 };
1393 assert_eq!(actual_name, name);
1394
1395 if let Some(expected) = content {
1396 let actual = &symbol.as_str()[item.content_start as usize..item.content_end as usize];
1397 assert_eq!(actual.trim(), expected.trim());
1398 }
1399 }
1400
1401 #[test]
1402 fn parse_file_import_callback() {
1403 let src = r#"
1404import "a.sol";
1405contract C {}
1406import * as B from "b.sol";
1407"#;
1408
1409 let sess =
1410 Session::builder().with_buffer_emitter(Default::default()).single_threaded().build();
1411 sess.enter_sequential(|| {
1412 let arena = ast::Arena::new();
1413 let mut imports = Vec::new();
1414 let mut parser =
1415 Parser::from_source_code(&sess, &arena, "test.sol".to_string().into(), src)
1416 .expect("failed to create parser");
1417
1418 parser.set_import_callback(|id, span, import| {
1419 imports.push((id, span, import.path.value.as_str().to_string()));
1420 });
1421 let ast = parser.parse_file().expect("failed to parse file");
1422 drop(parser);
1423
1424 assert_eq!(ast.items.len(), 3);
1425 assert_eq!(imports.len(), 2);
1426 assert_eq!(imports[0].0, ast::ItemId::new(0));
1427 assert_eq!(imports[0].2, "a.sol");
1428 assert_eq!(imports[1].0, ast::ItemId::new(2));
1429 assert_eq!(imports[1].2, "b.sol");
1430 assert_eq!(
1431 sess.source_map().span_to_snippet(imports[0].1).unwrap(),
1432 r#"import "a.sol";"#
1433 );
1434 });
1435 }
1436
1437 #[test]
1438 fn nonempty_sequence_requires_a_first_element() {
1439 for (allow_empty, succeeds) in [(true, true), (false, false)] {
1440 let sess = Session::builder()
1441 .with_buffer_emitter(Default::default())
1442 .single_threaded()
1443 .build();
1444 sess.enter_sequential(|| {
1445 let arena = ast::Arena::new();
1446 let mut parser =
1447 Parser::from_source_code(&sess, &arena, "test.sol".to_string().into(), "{}")
1448 .unwrap();
1449 let result = parser
1450 .parse_delim_comma_seq(Delimiter::Brace, allow_empty, Parser::parse_ident)
1451 .map_err(|err| err.emit());
1452
1453 assert_eq!(result.is_ok(), succeeds);
1454 });
1455 }
1456 }
1457
1458 #[test]
1459 fn parse_natspec_line_cmnts() {
1460 let src = r#"
1461/// @title MyContract
1462/// @author Alice
1463/// @notice This is a notice
1464/// that spans multiple lines
1465/// and continues here
1466/// @dev This is dev documentation
1467/// @param x The input parameter
1468/// @return result The return value
1469/// @inheritdoc BaseContract
1470/// @custom:security High priority
1471/// @solidity memory-safe
1472/// @ notice with space
1473"#;
1474
1475 let sess =
1476 Session::builder().with_buffer_emitter(Default::default()).single_threaded().build();
1477 sess.enter_sequential(|| {
1478 let arena = ast::Arena::new();
1479 let mut parser = Parser::from_source_code(&sess, &arena, "test.sol".to_string().into(), src)
1480 .expect("failed to create parser");
1481
1482 let sm = sess.source_map();
1483 let docs = parser.parse_doc_comments();
1484
1485 let natspec_items: Vec<_> = docs.iter().flat_map(|d| d.natspec.iter().map(move |i| (d.symbol, i))).collect();
1486 assert_eq!(natspec_items.len(), 11);
1489
1490 let check = |i: usize, snip, kind, name, content| {
1491 check_natspec_item(sm, natspec_items[i].0, natspec_items[i].1, snip, kind, name, content)
1492 };
1493
1494 check(0, "title", "title", None, Some("MyContract"));
1495 check(1, "author", "author", None, Some("Alice"));
1496 check(2, "notice", "notice", None, Some("This is a notice"));
1497 let span3 = sm.span_to_snippet(natspec_items[3].1.span).unwrap();
1498 check(3, &span3, "notice", None, Some("that spans multiple lines"));
1499 let span4 = sm.span_to_snippet(natspec_items[4].1.span).unwrap();
1500 check(4, &span4, "notice", None, Some("and continues here"));
1501 check(5, "dev", "dev", None, Some("This is dev documentation"));
1502 check(6, "param", "param", Some("x"), Some("The input parameter"));
1503 check(7, "return", "return", None, Some("result The return value"));
1504 check(8, "inheritdoc", "inheritdoc", Some("BaseContract"), Some(""));
1505 check(9, "custom:security", "custom", Some("security"), Some("High priority"));
1506 check(10, "solidity", "internal", Some("solidity"), Some("memory-safe"));
1507
1508 assert_eq!(sm.span_to_snippet(docs.span()).unwrap(), "/// @title MyContract\n/// @author Alice\n/// @notice This is a notice\n/// that spans multiple lines\n/// and continues here\n/// @dev This is dev documentation\n/// @param x The input parameter\n/// @return result The return value\n/// @inheritdoc BaseContract\n/// @custom:security High priority\n/// @solidity memory-safe\n/// @ notice with space");
1509 });
1510 }
1511
1512 #[test]
1513 fn parse_natspec_block_cmnts() {
1514 let src = r#"
1515/**
1516 * @title MyContract
1517 * @author Alice
1518 * @notice This is a notice
1519 * that spans multiple lines
1520 * and continues here
1521 * @dev This is dev documentation
1522 * @param x The input parameter
1523 * @return result The return value
1524 * @inheritdoc BaseContract
1525 * @custom:security High priority
1526 * @src 0:123:456
1527 */
1528"#;
1529
1530 let sess =
1531 Session::builder().with_buffer_emitter(Default::default()).single_threaded().build();
1532 sess.enter_sequential(|| {
1533 let arena = ast::Arena::new();
1534 let mut parser =
1535 Parser::from_source_code(&sess, &arena, "test.sol".to_string().into(), src)
1536 .expect("failed to create parser");
1537
1538 let sm = sess.source_map();
1539 let docs = parser.parse_doc_comments();
1540 assert_eq!(docs.len(), 1);
1541
1542 let (sym, items) = (docs[0].symbol, &docs[0].natspec);
1543 assert_eq!(items.len(), 9);
1544
1545 let check = |i: usize, span, kind, name, content| {
1546 check_natspec_item(sm, sym, &items[i], span, kind, name, content)
1547 };
1548
1549 check(0, "title", "title", None, Some("MyContract"));
1550 check(1, "author", "author", None, Some("Alice"));
1551 check(2, "notice", "notice", None, Some("This is a notice\n * that spans multiple lines\n * and continues here"));
1552 check(3, "dev", "dev", None, Some("This is dev documentation"));
1553 check(4, "param", "param", Some("x"), Some("The input parameter"));
1554 check(5, "return", "return", None, Some("result The return value"));
1555 check(6, "inheritdoc", "inheritdoc", Some("BaseContract"), Some(""));
1556 check(7, "custom:security", "custom", Some("security"), Some("High priority"));
1557 check(8, "src", "internal", Some("src"), Some("0:123:456"));
1558
1559 assert_eq!(sm.span_to_snippet(docs.span()).unwrap(), "/**\n * @title MyContract\n * @author Alice\n * @notice This is a notice\n * that spans multiple lines\n * and continues here\n * @dev This is dev documentation\n * @param x The input parameter\n * @return result The return value\n * @inheritdoc BaseContract\n * @custom:security High priority\n * @src 0:123:456\n */");
1560 });
1561 }
1562
1563 #[test]
1564 fn parse_natspec_line_cmnts_no_tags() {
1565 let src = r#"
1566/// This is a simple comment
1567/// It has no tags at all
1568/// Just plain documentation
1569contract Test {}
1570"#;
1571
1572 let sess =
1573 Session::builder().with_buffer_emitter(Default::default()).single_threaded().build();
1574 sess.enter_sequential(|| {
1575 let arena = ast::Arena::new();
1576 let mut parser =
1577 Parser::from_source_code(&sess, &arena, "test.sol".to_string().into(), src)
1578 .expect("failed to create parser");
1579
1580 let sm = sess.source_map();
1581 let docs = parser.parse_doc_comments();
1582 assert_eq!(docs.len(), 3);
1583
1584 for (doc, expected) in docs.iter().zip([
1585 "This is a simple comment",
1586 "It has no tags at all",
1587 "Just plain documentation",
1588 ]) {
1589 assert_eq!(doc.natspec.len(), 1);
1590 let item = &doc.natspec[0];
1591 let span = sm.span_to_snippet(item.span).unwrap();
1592 check_natspec_item(sm, doc.symbol, item, &span, "notice", None, Some(expected));
1593 }
1594 });
1595 }
1596
1597 #[test]
1598 fn parse_natspec_block_cmnt_no_tags() {
1599 let src = r#"
1600/**
1601 * This is a block comment
1602 * with multiple lines
1603 * but no tags at all
1604 */
1605contract Test {}
1606"#;
1607
1608 let sess =
1609 Session::builder().with_buffer_emitter(Default::default()).single_threaded().build();
1610 sess.enter_sequential(|| {
1611 let arena = ast::Arena::new();
1612 let mut parser =
1613 Parser::from_source_code(&sess, &arena, "test.sol".to_string().into(), src)
1614 .expect("failed to create parser");
1615
1616 let sm = sess.source_map();
1617 let docs = parser.parse_doc_comments();
1618 assert_eq!(docs.len(), 1);
1619 assert_eq!(docs[0].natspec.len(), 1);
1620
1621 let item = &docs[0].natspec[0];
1622 let snip = sm.span_to_snippet(item.span).unwrap();
1623 check_natspec_item(
1624 sm,
1625 docs[0].symbol,
1626 item,
1627 &snip,
1628 "notice",
1629 None,
1630 Some("* This is a block comment\n * with multiple lines\n * but no tags at all"),
1631 );
1632 });
1633 }
1634}