12 use crate::lexer::UnmatchedBrace;
13 use diagnostics::Error;
14 pub use path::PathStyle;
17 use rustc_ast::ast::DUMMY_NODE_ID;
18 use rustc_ast::ast::{self, AttrStyle, AttrVec, Const, CrateSugar, Extern, Unsafe};
20 Async, MacArgs, MacDelimiter, Mutability, StrLit, Visibility, VisibilityKind,
22 use rustc_ast::ptr::P;
23 use rustc_ast::token::{self, DelimToken, Token, TokenKind};
24 use rustc_ast::tokenstream::{self, DelimSpan, TokenStream, TokenTree, TreeAndJoint};
25 use rustc_ast::util::comments::{doc_comment_style, strip_doc_comment_decoration};
26 use rustc_ast_pretty::pprust;
27 use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder, FatalError, PResult};
28 use rustc_session::parse::ParseSess;
29 use rustc_span::source_map::{respan, Span, DUMMY_SP};
30 use rustc_span::symbol::{kw, sym, Ident, Symbol};
32 use std::{cmp, mem, slice};
35 struct Restrictions: u8 {
36 const STMT_EXPR = 1 << 0;
37 const NO_STRUCT_LITERAL = 1 << 1;
41 #[derive(Clone, Copy, PartialEq, Debug)]
48 #[derive(Clone, Copy, PartialEq, Debug)]
54 /// Like `maybe_whole_expr`, but for things other than expressions.
56 macro_rules! maybe_whole {
57 ($p:expr, $constructor:ident, |$x:ident| $e:expr) => {
58 if let token::Interpolated(nt) = &$p.token.kind {
59 if let token::$constructor(x) = &**nt {
68 /// If the next tokens are ill-formed `$ty::` recover them as `<$ty>::`.
70 macro_rules! maybe_recover_from_interpolated_ty_qpath {
71 ($self: expr, $allow_qpath_recovery: expr) => {
72 if $allow_qpath_recovery && $self.look_ahead(1, |t| t == &token::ModSep) {
73 if let token::Interpolated(nt) = &$self.token.kind {
74 if let token::NtTy(ty) = &**nt {
77 return $self.maybe_recover_from_bad_qpath_stage_2($self.prev_token.span, ty);
85 pub struct Parser<'a> {
86 pub sess: &'a ParseSess,
87 /// The current token.
89 /// The previous token.
90 pub prev_token: Token,
91 restrictions: Restrictions,
92 expected_tokens: Vec<TokenType>,
93 token_cursor: TokenCursor,
94 desugar_doc_comments: bool,
95 /// This field is used to keep track of how many left angle brackets we have seen. This is
96 /// required in order to detect extra leading left angle brackets (`<` characters) and error
99 /// See the comments in the `parse_path_segment` function for more details.
100 unmatched_angle_bracket_count: u32,
101 max_angle_bracket_count: u32,
102 /// A list of all unclosed delimiters found by the lexer. If an entry is used for error recovery
103 /// it gets removed from here. Every entry left at the end gets emitted as an independent
105 pub(super) unclosed_delims: Vec<UnmatchedBrace>,
106 last_unexpected_token_span: Option<Span>,
107 pub last_type_ascription: Option<(Span, bool /* likely path typo */)>,
108 /// If present, this `Parser` is not parsing Rust code but rather a macro call.
109 subparser_name: Option<&'static str>,
112 impl<'a> Drop for Parser<'a> {
114 emit_unclosed_delims(&mut self.unclosed_delims, &self.sess);
120 frame: TokenCursorFrame,
121 stack: Vec<TokenCursorFrame>,
122 cur_token: Option<TreeAndJoint>,
123 collecting: Option<Collecting>,
127 struct TokenCursorFrame {
128 delim: token::DelimToken,
131 tree_cursor: tokenstream::Cursor,
135 /// Used to track additional state needed by `collect_tokens`
136 #[derive(Clone, Debug)]
138 /// Holds the current tokens captured during the most
139 /// recent call to `collect_tokens`
140 buf: Vec<TreeAndJoint>,
141 /// The depth of the `TokenCursor` stack at the time
142 /// collection was started. When we encounter a `TokenTree::Delimited`,
143 /// we want to record the `TokenTree::Delimited` itself,
144 /// but *not* any of the inner tokens while we are inside
145 /// the new frame (this would cause us to record duplicate tokens).
147 /// This `depth` fields tracks stack depth we are recording tokens.
148 /// Only tokens encountered at this depth will be recorded. See
149 /// `TokenCursor::next` for more details.
153 impl TokenCursorFrame {
154 fn new(span: DelimSpan, delim: DelimToken, tts: &TokenStream) -> Self {
158 open_delim: delim == token::NoDelim,
159 tree_cursor: tts.clone().into_trees(),
160 close_delim: delim == token::NoDelim,
166 fn next(&mut self) -> Token {
168 let tree = if !self.frame.open_delim {
169 self.frame.open_delim = true;
170 TokenTree::open_tt(self.frame.span, self.frame.delim).into()
171 } else if let Some(tree) = self.frame.tree_cursor.next_with_joint() {
173 } else if !self.frame.close_delim {
174 self.frame.close_delim = true;
175 TokenTree::close_tt(self.frame.span, self.frame.delim).into()
176 } else if let Some(frame) = self.stack.pop() {
180 return Token::new(token::Eof, DUMMY_SP);
183 // Don't set an open delimiter as our current token - we want
184 // to leave it as the full `TokenTree::Delimited` from the previous
185 // iteration of this loop
186 if !matches!(tree.0, TokenTree::Token(Token { kind: TokenKind::OpenDelim(_), .. })) {
187 self.cur_token = Some(tree.clone());
190 if let Some(collecting) = &mut self.collecting {
191 if collecting.depth == self.stack.len() {
193 "TokenCursor::next(): collected {:?} at depth {:?}",
197 collecting.buf.push(tree.clone())
202 TokenTree::Token(token) => return token,
203 TokenTree::Delimited(sp, delim, tts) => {
204 let frame = TokenCursorFrame::new(sp, delim, &tts);
205 self.stack.push(mem::replace(&mut self.frame, frame));
211 fn next_desugared(&mut self) -> Token {
212 let (name, sp) = match self.next() {
213 Token { kind: token::DocComment(name), span } => (name, span),
217 let stripped = strip_doc_comment_decoration(name);
219 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
220 // required to wrap the text.
221 let mut num_of_hashes = 0;
223 for ch in stripped.chars() {
226 '#' if count > 0 => count + 1,
229 num_of_hashes = cmp::max(num_of_hashes, count);
232 let delim_span = DelimSpan::from_single(sp);
233 let body = TokenTree::Delimited(
237 TokenTree::token(token::Ident(sym::doc, false), sp),
238 TokenTree::token(token::Eq, sp),
240 TokenKind::lit(token::StrRaw(num_of_hashes), Symbol::intern(&stripped), None),
246 .collect::<TokenStream>(),
249 self.stack.push(mem::replace(
251 TokenCursorFrame::new(
254 &if doc_comment_style(name) == AttrStyle::Inner {
255 [TokenTree::token(token::Pound, sp), TokenTree::token(token::Not, sp), body]
258 .collect::<TokenStream>()
260 [TokenTree::token(token::Pound, sp), body]
263 .collect::<TokenStream>()
272 #[derive(Clone, PartialEq)]
285 fn to_string(&self) -> String {
287 TokenType::Token(ref t) => format!("`{}`", pprust::token_kind_to_string(t)),
288 TokenType::Keyword(kw) => format!("`{}`", kw),
289 TokenType::Operator => "an operator".to_string(),
290 TokenType::Lifetime => "lifetime".to_string(),
291 TokenType::Ident => "identifier".to_string(),
292 TokenType::Path => "path".to_string(),
293 TokenType::Type => "type".to_string(),
294 TokenType::Const => "const".to_string(),
299 #[derive(Copy, Clone, Debug)]
300 enum TokenExpectType {
305 /// A sequence separator.
307 /// The separator token.
308 sep: Option<TokenKind>,
309 /// `true` if a trailing separator is allowed.
310 trailing_sep_allowed: bool,
314 fn trailing_allowed(t: TokenKind) -> SeqSep {
315 SeqSep { sep: Some(t), trailing_sep_allowed: true }
318 fn none() -> SeqSep {
319 SeqSep { sep: None, trailing_sep_allowed: false }
323 pub enum FollowedByType {
328 fn token_descr_opt(token: &Token) -> Option<&'static str> {
329 Some(match token.kind {
330 _ if token.is_special_ident() => "reserved identifier",
331 _ if token.is_used_keyword() => "keyword",
332 _ if token.is_unused_keyword() => "reserved keyword",
333 token::DocComment(..) => "doc comment",
338 pub(super) fn token_descr(token: &Token) -> String {
339 let token_str = pprust::token_to_string(token);
340 match token_descr_opt(token) {
341 Some(prefix) => format!("{} `{}`", prefix, token_str),
342 _ => format!("`{}`", token_str),
346 impl<'a> Parser<'a> {
350 desugar_doc_comments: bool,
351 subparser_name: Option<&'static str>,
353 let mut parser = Parser {
355 token: Token::dummy(),
356 prev_token: Token::dummy(),
357 restrictions: Restrictions::empty(),
358 expected_tokens: Vec::new(),
359 token_cursor: TokenCursor {
360 frame: TokenCursorFrame::new(DelimSpan::dummy(), token::NoDelim, &tokens),
365 desugar_doc_comments,
366 unmatched_angle_bracket_count: 0,
367 max_angle_bracket_count: 0,
368 unclosed_delims: Vec::new(),
369 last_unexpected_token_span: None,
370 last_type_ascription: None,
374 // Make parser point to the first token.
380 fn next_tok(&mut self, fallback_span: Span) -> Token {
381 let mut next = if self.desugar_doc_comments {
382 self.token_cursor.next_desugared()
384 self.token_cursor.next()
386 if next.span.is_dummy() {
387 // Tweak the location for better diagnostics, but keep syntactic context intact.
388 next.span = fallback_span.with_ctxt(next.span.ctxt());
393 crate fn unexpected<T>(&mut self) -> PResult<'a, T> {
394 match self.expect_one_of(&[], &[]) {
396 // We can get `Ok(true)` from `recover_closing_delimiter`
397 // which is called in `expected_one_of_not_found`.
398 Ok(_) => FatalError.raise(),
402 /// Expects and consumes the token `t`. Signals an error if the next token is not `t`.
403 pub fn expect(&mut self, t: &TokenKind) -> PResult<'a, bool /* recovered */> {
404 if self.expected_tokens.is_empty() {
405 if self.token == *t {
409 self.unexpected_try_recover(t)
412 self.expect_one_of(slice::from_ref(t), &[])
416 /// Expect next token to be edible or inedible token. If edible,
417 /// then consume it; if inedible, then return without consuming
418 /// anything. Signal a fatal error if next token is unexpected.
419 pub fn expect_one_of(
421 edible: &[TokenKind],
422 inedible: &[TokenKind],
423 ) -> PResult<'a, bool /* recovered */> {
424 if edible.contains(&self.token.kind) {
427 } else if inedible.contains(&self.token.kind) {
428 // leave it in the input
430 } else if self.last_unexpected_token_span == Some(self.token.span) {
433 self.expected_one_of_not_found(edible, inedible)
437 // Public for rustfmt usage.
438 pub fn parse_ident(&mut self) -> PResult<'a, Ident> {
439 self.parse_ident_common(true)
442 fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, Ident> {
443 match self.token.ident() {
444 Some((ident, is_raw)) => {
445 if !is_raw && ident.is_reserved() {
446 let mut err = self.expected_ident_found();
456 _ => Err(match self.prev_token.kind {
457 TokenKind::DocComment(..) => {
458 self.span_fatal_err(self.prev_token.span, Error::UselessDocComment)
460 _ => self.expected_ident_found(),
465 /// Checks if the next token is `tok`, and returns `true` if so.
467 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
469 fn check(&mut self, tok: &TokenKind) -> bool {
470 let is_present = self.token == *tok;
472 self.expected_tokens.push(TokenType::Token(tok.clone()));
477 /// Consumes a token 'tok' if it exists. Returns whether the given token was present.
478 pub fn eat(&mut self, tok: &TokenKind) -> bool {
479 let is_present = self.check(tok);
486 /// If the next token is the given keyword, returns `true` without eating it.
487 /// An expectation is also added for diagnostics purposes.
488 fn check_keyword(&mut self, kw: Symbol) -> bool {
489 self.expected_tokens.push(TokenType::Keyword(kw));
490 self.token.is_keyword(kw)
493 /// If the next token is the given keyword, eats it and returns `true`.
494 /// Otherwise, returns `false`. An expectation is also added for diagnostics purposes.
495 // Public for rustfmt usage.
496 pub fn eat_keyword(&mut self, kw: Symbol) -> bool {
497 if self.check_keyword(kw) {
505 fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool {
506 if self.token.is_keyword(kw) {
514 /// If the given word is not a keyword, signals an error.
515 /// If the next token is not the given word, signals an error.
516 /// Otherwise, eats it.
517 fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> {
518 if !self.eat_keyword(kw) { self.unexpected() } else { Ok(()) }
521 /// Is the given keyword `kw` followed by a non-reserved identifier?
522 fn is_kw_followed_by_ident(&self, kw: Symbol) -> bool {
523 self.token.is_keyword(kw) && self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
526 fn check_or_expected(&mut self, ok: bool, typ: TokenType) -> bool {
530 self.expected_tokens.push(typ);
535 fn check_ident(&mut self) -> bool {
536 self.check_or_expected(self.token.is_ident(), TokenType::Ident)
539 fn check_path(&mut self) -> bool {
540 self.check_or_expected(self.token.is_path_start(), TokenType::Path)
543 fn check_type(&mut self) -> bool {
544 self.check_or_expected(self.token.can_begin_type(), TokenType::Type)
547 fn check_const_arg(&mut self) -> bool {
548 self.check_or_expected(self.token.can_begin_const_arg(), TokenType::Const)
551 /// Checks to see if the next token is either `+` or `+=`.
552 /// Otherwise returns `false`.
553 fn check_plus(&mut self) -> bool {
554 self.check_or_expected(
555 self.token.is_like_plus(),
556 TokenType::Token(token::BinOp(token::Plus)),
560 /// Eats the expected token if it's present possibly breaking
561 /// compound tokens like multi-character operators in process.
562 /// Returns `true` if the token was eaten.
563 fn break_and_eat(&mut self, expected: TokenKind) -> bool {
564 if self.token.kind == expected {
568 match self.token.kind.break_two_token_op() {
569 Some((first, second)) if first == expected => {
570 let first_span = self.sess.source_map().start_point(self.token.span);
571 let second_span = self.token.span.with_lo(first_span.hi());
572 self.token = Token::new(first, first_span);
573 self.bump_with(Token::new(second, second_span));
577 self.expected_tokens.push(TokenType::Token(expected));
583 /// Eats `+` possibly breaking tokens like `+=` in process.
584 fn eat_plus(&mut self) -> bool {
585 self.break_and_eat(token::BinOp(token::Plus))
588 /// Eats `&` possibly breaking tokens like `&&` in process.
589 /// Signals an error if `&` is not eaten.
590 fn expect_and(&mut self) -> PResult<'a, ()> {
591 if self.break_and_eat(token::BinOp(token::And)) { Ok(()) } else { self.unexpected() }
594 /// Eats `|` possibly breaking tokens like `||` in process.
595 /// Signals an error if `|` was not eaten.
596 fn expect_or(&mut self) -> PResult<'a, ()> {
597 if self.break_and_eat(token::BinOp(token::Or)) { Ok(()) } else { self.unexpected() }
600 /// Eats `<` possibly breaking tokens like `<<` in process.
601 fn eat_lt(&mut self) -> bool {
602 let ate = self.break_and_eat(token::Lt);
604 // See doc comment for `unmatched_angle_bracket_count`.
605 self.unmatched_angle_bracket_count += 1;
606 self.max_angle_bracket_count += 1;
607 debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count);
612 /// Eats `<` possibly breaking tokens like `<<` in process.
613 /// Signals an error if `<` was not eaten.
614 fn expect_lt(&mut self) -> PResult<'a, ()> {
615 if self.eat_lt() { Ok(()) } else { self.unexpected() }
618 /// Eats `>` possibly breaking tokens like `>>` in process.
619 /// Signals an error if `>` was not eaten.
620 fn expect_gt(&mut self) -> PResult<'a, ()> {
621 if self.break_and_eat(token::Gt) {
622 // See doc comment for `unmatched_angle_bracket_count`.
623 if self.unmatched_angle_bracket_count > 0 {
624 self.unmatched_angle_bracket_count -= 1;
625 debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count);
633 fn expect_any_with_type(&mut self, kets: &[&TokenKind], expect: TokenExpectType) -> bool {
634 kets.iter().any(|k| match expect {
635 TokenExpectType::Expect => self.check(k),
636 TokenExpectType::NoExpect => self.token == **k,
640 fn parse_seq_to_before_tokens<T>(
644 expect: TokenExpectType,
645 mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
646 ) -> PResult<'a, (Vec<T>, bool /* trailing */, bool /* recovered */)> {
647 let mut first = true;
648 let mut recovered = false;
649 let mut trailing = false;
651 while !self.expect_any_with_type(kets, expect) {
652 if let token::CloseDelim(..) | token::Eof = self.token.kind {
655 if let Some(ref t) = sep.sep {
659 match self.expect(t) {
665 Err(mut expect_err) => {
666 let sp = self.prev_token.span.shrink_to_hi();
667 let token_str = pprust::token_kind_to_string(t);
669 // Attempt to keep parsing if it was a similar separator.
670 if let Some(ref tokens) = t.similar_tokens() {
671 if tokens.contains(&self.token.kind) {
676 // If this was a missing `@` in a binding pattern
677 // bail with a suggestion
678 // https://github.com/rust-lang/rust/issues/72373
679 if self.prev_token.is_ident() && self.token.kind == token::DotDot {
681 "if you meant to bind the contents of \
682 the rest of the array pattern into `{}`, use `@`",
683 pprust::token_to_string(&self.prev_token)
686 .span_suggestion_verbose(
687 self.prev_token.span.shrink_to_hi().until(self.token.span),
690 Applicability::MaybeIncorrect,
696 // Attempt to keep parsing if it was an omitted separator.
699 // Parsed successfully, therefore most probably the code only
700 // misses a separator.
702 .span_suggestion_short(
703 self.sess.source_map().next_point(sp),
704 &format!("missing `{}`", token_str),
706 Applicability::MaybeIncorrect,
714 // Parsing failed, therefore it must be something more serious
715 // than just a missing separator.
726 if sep.trailing_sep_allowed && self.expect_any_with_type(kets, expect) {
735 Ok((v, trailing, recovered))
738 /// Parses a sequence, not including the closing delimiter. The function
739 /// `f` must consume tokens until reaching the next separator or
741 fn parse_seq_to_before_end<T>(
745 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
746 ) -> PResult<'a, (Vec<T>, bool, bool)> {
747 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
750 /// Parses a sequence, including the closing delimiter. The function
751 /// `f` must consume tokens until reaching the next separator or
753 fn parse_seq_to_end<T>(
757 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
758 ) -> PResult<'a, (Vec<T>, bool /* trailing */)> {
759 let (val, trailing, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
766 /// Parses a sequence, including the closing delimiter. The function
767 /// `f` must consume tokens until reaching the next separator or
769 fn parse_unspanned_seq<T>(
774 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
775 ) -> PResult<'a, (Vec<T>, bool)> {
777 self.parse_seq_to_end(ket, sep, f)
780 fn parse_delim_comma_seq<T>(
783 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
784 ) -> PResult<'a, (Vec<T>, bool)> {
785 self.parse_unspanned_seq(
786 &token::OpenDelim(delim),
787 &token::CloseDelim(delim),
788 SeqSep::trailing_allowed(token::Comma),
793 fn parse_paren_comma_seq<T>(
795 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
796 ) -> PResult<'a, (Vec<T>, bool)> {
797 self.parse_delim_comma_seq(token::Paren, f)
800 /// Advance the parser by one token using provided token as the next one.
801 fn bump_with(&mut self, next_token: Token) {
802 // Bumping after EOF is a bad sign, usually an infinite loop.
803 if self.prev_token.kind == TokenKind::Eof {
804 let msg = "attempted to bump the parser past EOF (may be stuck in a loop)";
805 self.span_bug(self.token.span, msg);
808 // Update the current and previous tokens.
809 self.prev_token = mem::replace(&mut self.token, next_token);
812 self.expected_tokens.clear();
815 /// Advance the parser by one token.
816 pub fn bump(&mut self) {
817 let next_token = self.next_tok(self.token.span);
818 self.bump_with(next_token);
821 /// Look-ahead `dist` tokens of `self.token` and get access to that token there.
822 /// When `dist == 0` then the current token is looked at.
823 pub fn look_ahead<R>(&self, dist: usize, looker: impl FnOnce(&Token) -> R) -> R {
825 return looker(&self.token);
828 let frame = &self.token_cursor.frame;
829 looker(&match frame.tree_cursor.look_ahead(dist - 1) {
830 Some(tree) => match tree {
831 TokenTree::Token(token) => token,
832 TokenTree::Delimited(dspan, delim, _) => {
833 Token::new(token::OpenDelim(delim), dspan.open)
836 None => Token::new(token::CloseDelim(frame.delim), frame.span.close),
840 /// Returns whether any of the given keywords are `dist` tokens ahead of the current one.
841 fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool {
842 self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw)))
845 /// Parses asyncness: `async` or nothing.
846 fn parse_asyncness(&mut self) -> Async {
847 if self.eat_keyword(kw::Async) {
848 let span = self.prev_token.uninterpolated_span();
849 Async::Yes { span, closure_id: DUMMY_NODE_ID, return_impl_trait_id: DUMMY_NODE_ID }
855 /// Parses unsafety: `unsafe` or nothing.
856 fn parse_unsafety(&mut self) -> Unsafe {
857 if self.eat_keyword(kw::Unsafe) {
858 Unsafe::Yes(self.prev_token.uninterpolated_span())
864 /// Parses constness: `const` or nothing.
865 fn parse_constness(&mut self) -> Const {
866 if self.eat_keyword(kw::Const) {
867 Const::Yes(self.prev_token.uninterpolated_span())
873 /// Parses mutability (`mut` or nothing).
874 fn parse_mutability(&mut self) -> Mutability {
875 if self.eat_keyword(kw::Mut) { Mutability::Mut } else { Mutability::Not }
878 /// Possibly parses mutability (`const` or `mut`).
879 fn parse_const_or_mut(&mut self) -> Option<Mutability> {
880 if self.eat_keyword(kw::Mut) {
881 Some(Mutability::Mut)
882 } else if self.eat_keyword(kw::Const) {
883 Some(Mutability::Not)
889 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
890 if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) = self.token.kind
892 self.expect_no_suffix(self.token.span, "a tuple index", suffix);
894 Ok(Ident::new(symbol, self.prev_token.span))
896 self.parse_ident_common(false)
900 fn parse_mac_args(&mut self) -> PResult<'a, P<MacArgs>> {
901 self.parse_mac_args_common(true).map(P)
904 fn parse_attr_args(&mut self) -> PResult<'a, MacArgs> {
905 self.parse_mac_args_common(false)
908 fn parse_mac_args_common(&mut self, delimited_only: bool) -> PResult<'a, MacArgs> {
910 if self.check(&token::OpenDelim(DelimToken::Paren))
911 || self.check(&token::OpenDelim(DelimToken::Bracket))
912 || self.check(&token::OpenDelim(DelimToken::Brace))
914 match self.parse_token_tree() {
915 TokenTree::Delimited(dspan, delim, tokens) =>
916 // We've confirmed above that there is a delimiter so unwrapping is OK.
918 MacArgs::Delimited(dspan, MacDelimiter::from_token(delim).unwrap(), tokens)
922 } else if !delimited_only {
923 if self.eat(&token::Eq) {
924 let eq_span = self.prev_token.span;
925 let mut is_interpolated_expr = false;
926 if let token::Interpolated(nt) = &self.token.kind {
927 if let token::NtExpr(..) = **nt {
928 is_interpolated_expr = true;
931 let token_tree = if is_interpolated_expr {
932 // We need to accept arbitrary interpolated expressions to continue
933 // supporting things like `doc = $expr` that work on stable.
934 // Non-literal interpolated expressions are rejected after expansion.
935 self.parse_token_tree()
937 self.parse_unsuffixed_lit()?.token_tree()
940 MacArgs::Eq(eq_span, token_tree.into())
945 return self.unexpected();
950 fn parse_or_use_outer_attributes(
952 already_parsed_attrs: Option<AttrVec>,
953 ) -> PResult<'a, AttrVec> {
954 if let Some(attrs) = already_parsed_attrs {
957 self.parse_outer_attributes().map(|a| a.into())
961 /// Parses a single token tree from the input.
962 pub(crate) fn parse_token_tree(&mut self) -> TokenTree {
963 match self.token.kind {
964 token::OpenDelim(..) => {
965 let frame = mem::replace(
966 &mut self.token_cursor.frame,
967 self.token_cursor.stack.pop().unwrap(),
969 self.token = Token::new(TokenKind::CloseDelim(frame.delim), frame.span.close);
971 TokenTree::Delimited(frame.span, frame.delim, frame.tree_cursor.stream)
973 token::CloseDelim(_) | token::Eof => unreachable!(),
976 TokenTree::Token(self.prev_token.clone())
981 /// Parses a stream of tokens into a list of `TokenTree`s, up to EOF.
982 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
983 let mut tts = Vec::new();
984 while self.token != token::Eof {
985 tts.push(self.parse_token_tree());
990 pub fn parse_tokens(&mut self) -> TokenStream {
991 let mut result = Vec::new();
993 match self.token.kind {
994 token::Eof | token::CloseDelim(..) => break,
995 _ => result.push(self.parse_token_tree().into()),
998 TokenStream::new(result)
1001 /// Evaluates the closure with restrictions in place.
1003 /// Afters the closure is evaluated, restrictions are reset.
1004 fn with_res<T>(&mut self, res: Restrictions, f: impl FnOnce(&mut Self) -> T) -> T {
1005 let old = self.restrictions;
1006 self.restrictions = res;
1008 self.restrictions = old;
1012 fn is_crate_vis(&self) -> bool {
1013 self.token.is_keyword(kw::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
1016 /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`,
1017 /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`.
1018 /// If the following element can't be a tuple (i.e., it's a function definition), then
1019 /// it's not a tuple struct field), and the contents within the parentheses isn't valid,
1020 /// so emit a proper diagnostic.
1021 pub(crate) fn parse_visibility(&mut self, fbt: FollowedByType) -> PResult<'a, Visibility> {
1022 maybe_whole!(self, NtVis, |x| x);
1024 self.expected_tokens.push(TokenType::Keyword(kw::Crate));
1025 if self.is_crate_vis() {
1026 self.bump(); // `crate`
1027 self.sess.gated_spans.gate(sym::crate_visibility_modifier, self.prev_token.span);
1028 return Ok(respan(self.prev_token.span, VisibilityKind::Crate(CrateSugar::JustCrate)));
1031 if !self.eat_keyword(kw::Pub) {
1032 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
1033 // keyword to grab a span from for inherited visibility; an empty span at the
1034 // beginning of the current token would seem to be the "Schelling span".
1035 return Ok(respan(self.token.span.shrink_to_lo(), VisibilityKind::Inherited));
1037 let lo = self.prev_token.span;
1039 if self.check(&token::OpenDelim(token::Paren)) {
1040 // We don't `self.bump()` the `(` yet because this might be a struct definition where
1041 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
1042 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
1043 // by the following tokens.
1044 if self.is_keyword_ahead(1, &[kw::Crate]) && self.look_ahead(2, |t| t != &token::ModSep)
1045 // account for `pub(crate::foo)`
1047 // Parse `pub(crate)`.
1049 self.bump(); // `crate`
1050 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1051 let vis = VisibilityKind::Crate(CrateSugar::PubCrate);
1052 return Ok(respan(lo.to(self.prev_token.span), vis));
1053 } else if self.is_keyword_ahead(1, &[kw::In]) {
1054 // Parse `pub(in path)`.
1056 self.bump(); // `in`
1057 let path = self.parse_path(PathStyle::Mod)?; // `path`
1058 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1059 let vis = VisibilityKind::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
1060 return Ok(respan(lo.to(self.prev_token.span), vis));
1061 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren))
1062 && self.is_keyword_ahead(1, &[kw::Super, kw::SelfLower])
1064 // Parse `pub(self)` or `pub(super)`.
1066 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
1067 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1068 let vis = VisibilityKind::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
1069 return Ok(respan(lo.to(self.prev_token.span), vis));
1070 } else if let FollowedByType::No = fbt {
1071 // Provide this diagnostic if a type cannot follow;
1072 // in particular, if this is not a tuple struct.
1073 self.recover_incorrect_vis_restriction()?;
1074 // Emit diagnostic, but continue with public visibility.
1078 Ok(respan(lo, VisibilityKind::Public))
1081 /// Recovery for e.g. `pub(something) fn ...` or `struct X { pub(something) y: Z }`
1082 fn recover_incorrect_vis_restriction(&mut self) -> PResult<'a, ()> {
1084 let path = self.parse_path(PathStyle::Mod)?;
1085 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1087 let msg = "incorrect visibility restriction";
1088 let suggestion = r##"some possible visibility restrictions are:
1089 `pub(crate)`: visible only on the current crate
1090 `pub(super)`: visible only in the current module's parent
1091 `pub(in path::to::module)`: visible only on the specified path"##;
1093 let path_str = pprust::path_to_string(&path);
1095 struct_span_err!(self.sess.span_diagnostic, path.span, E0704, "{}", msg)
1099 &format!("make this visible only to module `{}` with `in`", path_str),
1100 format!("in {}", path_str),
1101 Applicability::MachineApplicable,
1108 /// Parses `extern string_literal?`.
1109 fn parse_extern(&mut self) -> PResult<'a, Extern> {
1110 Ok(if self.eat_keyword(kw::Extern) {
1111 Extern::from_abi(self.parse_abi())
1117 /// Parses a string literal as an ABI spec.
1118 fn parse_abi(&mut self) -> Option<StrLit> {
1119 match self.parse_str_lit() {
1120 Ok(str_lit) => Some(str_lit),
1121 Err(Some(lit)) => match lit.kind {
1122 ast::LitKind::Err(_) => None,
1124 self.struct_span_err(lit.span, "non-string ABI literal")
1127 "specify the ABI with a string literal",
1128 "\"C\"".to_string(),
1129 Applicability::MaybeIncorrect,
1139 /// Records all tokens consumed by the provided callback,
1140 /// including the current token. These tokens are collected
1141 /// into a `TokenStream`, and returned along with the result
1142 /// of the callback.
1144 /// Note: If your callback consumes an opening delimiter
1145 /// (including the case where you call `collect_tokens`
1146 /// when the current token is an opening delimeter),
1147 /// you must also consume the corresponding closing delimiter.
1149 /// That is, you can consume
1150 /// `something ([{ }])` or `([{}])`, but not `([{}]`
1152 /// This restriction shouldn't be an issue in practice,
1153 /// since this function is used to record the tokens for
1154 /// a parsed AST item, which always has matching delimiters.
1155 pub fn collect_tokens<R>(
1157 f: impl FnOnce(&mut Self) -> PResult<'a, R>,
1158 ) -> PResult<'a, (R, TokenStream)> {
1159 // Record all tokens we parse when parsing this item.
1160 let tokens: Vec<TreeAndJoint> = self.token_cursor.cur_token.clone().into_iter().collect();
1161 debug!("collect_tokens: starting with {:?}", tokens);
1163 // We need special handling for the case where `collect_tokens` is called
1164 // on an opening delimeter (e.g. '('). At this point, we have already pushed
1165 // a new frame - however, we want to record the original `TokenTree::Delimited`,
1166 // for consistency with the case where we start recording one token earlier.
1167 // See `TokenCursor::next` to see how `cur_token` is set up.
1169 if matches!(self.token_cursor.cur_token, Some((TokenTree::Delimited(..), _))) {
1170 if self.token_cursor.stack.is_empty() {
1171 // There is nothing below us in the stack that
1172 // the function could consume, so the only thing it can legally
1173 // capture is the entire contents of the current frame.
1174 return Ok((f(self)?, TokenStream::new(tokens)));
1176 // We have already recorded the full `TokenTree::Delimited` when we created
1177 // our `tokens` vector at the start of this function. We are now inside
1178 // a new frame corresponding to the `TokenTree::Delimited` we already recoreded.
1179 // We don't want to record any of the tokens inside this frame, since they
1180 // will be duplicates of the tokens nested inside the `TokenTree::Delimited`.
1181 // Therefore, we set our recording depth to the *previous* frame. This allows
1182 // us to record a sequence like: `(foo).bar()`: the `(foo)` will be recored
1183 // as our initial `cur_token`, while the `.bar()` will be recored after we
1184 // pop the `(foo)` frame.
1185 self.token_cursor.stack.len() - 1
1187 self.token_cursor.stack.len()
1189 let prev_collecting =
1190 self.token_cursor.collecting.replace(Collecting { buf: tokens, depth: prev_depth });
1194 let mut collected_tokens = if let Some(collecting) = self.token_cursor.collecting.take() {
1197 let msg = "our vector went away?";
1198 debug!("collect_tokens: {}", msg);
1199 self.sess.span_diagnostic.delay_span_bug(self.token.span, &msg);
1200 // This can happen due to a bad interaction of two unrelated recovery mechanisms
1201 // with mismatched delimiters *and* recovery lookahead on the likely typo
1202 // `pub ident(` (#62895, different but similar to the case above).
1203 return Ok((ret?, TokenStream::default()));
1206 debug!("collect_tokens: got raw tokens {:?}", collected_tokens);
1208 // If we're not at EOF our current token wasn't actually consumed by
1209 // `f`, but it'll still be in our list that we pulled out. In that case
1211 let extra_token = if self.token != token::Eof { collected_tokens.pop() } else { None };
1213 if let Some(mut collecting) = prev_collecting {
1214 // If we were previously collecting at the same depth,
1215 // then the previous call to `collect_tokens` needs to see
1216 // the tokens we just recorded.
1218 // If we were previously recording at an lower `depth`,
1219 // then the previous `collect_tokens` call already recorded
1220 // this entire frame in the form of a `TokenTree::Delimited`,
1221 // so there is nothing else for us to do.
1222 if collecting.depth == prev_depth {
1223 collecting.buf.extend(collected_tokens.iter().cloned());
1224 collecting.buf.extend(extra_token);
1225 debug!("collect_tokens: updating previous buf to {:?}", collecting);
1227 self.token_cursor.collecting = Some(collecting)
1230 Ok((ret?, TokenStream::new(collected_tokens)))
1234 fn is_import_coupler(&mut self) -> bool {
1235 self.check(&token::ModSep)
1236 && self.look_ahead(1, |t| {
1237 *t == token::OpenDelim(token::Brace) || *t == token::BinOp(token::Star)
1242 crate fn make_unclosed_delims_error(
1243 unmatched: UnmatchedBrace,
1245 ) -> Option<DiagnosticBuilder<'_>> {
1246 // `None` here means an `Eof` was found. We already emit those errors elsewhere, we add them to
1247 // `unmatched_braces` only for error recovery in the `Parser`.
1248 let found_delim = unmatched.found_delim?;
1249 let mut err = sess.span_diagnostic.struct_span_err(
1250 unmatched.found_span,
1252 "mismatched closing delimiter: `{}`",
1253 pprust::token_kind_to_string(&token::CloseDelim(found_delim)),
1256 err.span_label(unmatched.found_span, "mismatched closing delimiter");
1257 if let Some(sp) = unmatched.candidate_span {
1258 err.span_label(sp, "closing delimiter possibly meant for this");
1260 if let Some(sp) = unmatched.unclosed_span {
1261 err.span_label(sp, "unclosed delimiter");
1266 pub fn emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedBrace>, sess: &ParseSess) {
1267 *sess.reached_eof.borrow_mut() |=
1268 unclosed_delims.iter().any(|unmatched_delim| unmatched_delim.found_delim.is_none());
1269 for unmatched in unclosed_delims.drain(..) {
1270 if let Some(mut e) = make_unclosed_delims_error(unmatched, sess) {