13 use crate::lexer::UnmatchedBrace;
14 pub use attr_wrapper::AttrWrapper;
15 pub use diagnostics::AttemptLocalParseRecovery;
16 use diagnostics::Error;
17 pub use pat::RecoverComma;
18 pub use path::PathStyle;
20 use rustc_ast::ptr::P;
21 use rustc_ast::token::{self, DelimToken, Token, TokenKind};
22 use rustc_ast::tokenstream::AttributesData;
23 use rustc_ast::tokenstream::{self, DelimSpan, Spacing};
24 use rustc_ast::tokenstream::{TokenStream, TokenTree};
25 use rustc_ast::AttrId;
26 use rustc_ast::DUMMY_NODE_ID;
27 use rustc_ast::{self as ast, AnonConst, AstLike, AttrStyle, AttrVec, Const, CrateSugar, Extern};
28 use rustc_ast::{Async, Expr, ExprKind, MacArgs, MacDelimiter, Mutability, StrLit, Unsafe};
29 use rustc_ast::{Visibility, VisibilityKind};
30 use rustc_ast_pretty::pprust;
31 use rustc_data_structures::fx::FxHashMap;
32 use rustc_data_structures::sync::Lrc;
33 use rustc_errors::PResult;
34 use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder, FatalError};
35 use rustc_session::parse::ParseSess;
36 use rustc_span::source_map::{Span, DUMMY_SP};
37 use rustc_span::symbol::{kw, sym, Ident, Symbol};
41 use std::{cmp, mem, slice};
44 struct Restrictions: u8 {
45 const STMT_EXPR = 1 << 0;
46 const NO_STRUCT_LITERAL = 1 << 1;
47 const CONST_EXPR = 1 << 2;
51 #[derive(Clone, Copy, PartialEq, Debug)]
58 #[derive(Clone, Copy, PartialEq, Debug)]
64 /// Whether or not we should force collection of tokens for an AST node,
65 /// regardless of whether or not it has attributes
66 pub enum ForceCollect {
71 #[derive(Debug, Eq, PartialEq)]
72 pub enum TrailingToken {
75 /// If the trailing token is a comma, then capture it
76 /// Otherwise, ignore the trailing token
80 /// Like `maybe_whole_expr`, but for things other than expressions.
82 macro_rules! maybe_whole {
83 ($p:expr, $constructor:ident, |$x:ident| $e:expr) => {
84 if let token::Interpolated(nt) = &$p.token.kind {
85 if let token::$constructor(x) = &**nt {
94 /// If the next tokens are ill-formed `$ty::` recover them as `<$ty>::`.
96 macro_rules! maybe_recover_from_interpolated_ty_qpath {
97 ($self: expr, $allow_qpath_recovery: expr) => {
98 if $allow_qpath_recovery && $self.look_ahead(1, |t| t == &token::ModSep) {
99 if let token::Interpolated(nt) = &$self.token.kind {
100 if let token::NtTy(ty) = &**nt {
103 return $self.maybe_recover_from_bad_qpath_stage_2($self.prev_token.span, ty);
111 pub struct Parser<'a> {
112 pub sess: &'a ParseSess,
113 /// The current token.
115 /// The spacing for the current token
116 pub token_spacing: Spacing,
117 /// The previous token.
118 pub prev_token: Token,
119 pub capture_cfg: bool,
120 restrictions: Restrictions,
121 expected_tokens: Vec<TokenType>,
122 // Important: This must only be advanced from `next_tok`
123 // to ensure that `token_cursor.num_next_calls` is updated properly
124 token_cursor: TokenCursor,
125 desugar_doc_comments: bool,
126 /// This field is used to keep track of how many left angle brackets we have seen. This is
127 /// required in order to detect extra leading left angle brackets (`<` characters) and error
130 /// See the comments in the `parse_path_segment` function for more details.
131 unmatched_angle_bracket_count: u32,
132 max_angle_bracket_count: u32,
133 /// A list of all unclosed delimiters found by the lexer. If an entry is used for error recovery
134 /// it gets removed from here. Every entry left at the end gets emitted as an independent
136 pub(super) unclosed_delims: Vec<UnmatchedBrace>,
137 last_unexpected_token_span: Option<Span>,
138 /// Span pointing at the `:` for the last type ascription the parser has seen, and whether it
139 /// looked like it could have been a mistyped path or literal `Option:Some(42)`).
140 pub last_type_ascription: Option<(Span, bool /* likely path typo */)>,
141 /// If present, this `Parser` is not parsing Rust code but rather a macro call.
142 subparser_name: Option<&'static str>,
143 capture_state: CaptureState,
146 /// Indicates a range of tokens that should be replaced by
147 /// the tokens in the provided vector. This is used in two
148 /// places during token collection:
150 /// 1. During the parsing of an AST node that may have a `#[derive]`
151 /// attribute, we parse a nested AST node that has `#[cfg]` or `#[cfg_attr]`
152 /// In this case, we use a `ReplaceRange` to replace the entire inner AST node
153 /// with `FlatToken::AttrTarget`, allowing us to perform eager cfg-expansion
154 /// on a `AttrAnnotatedTokenStream`
156 /// 2. When we parse an inner attribute while collecting tokens. We
157 /// remove inner attributes from the token stream entirely, and
158 /// instead track them through the `attrs` field on the AST node.
159 /// This allows us to easily manipulate them (for example, removing
160 /// the first macro inner attribute to invoke a proc-macro).
161 /// When create a `TokenStream`, the inner attributes get inserted
162 /// into the proper place in the token stream.
163 pub type ReplaceRange = (Range<u32>, Vec<(FlatToken, Spacing)>);
165 /// Controls how we capture tokens. Capturing can be expensive,
166 /// so we try to avoid performing capturing in cases where
167 /// we will never need a `AttrAnnotatedTokenStream`
168 #[derive(Copy, Clone)]
170 /// We aren't performing any capturing - this is the default mode.
172 /// We are capturing tokens
177 struct CaptureState {
178 capturing: Capturing,
179 replace_ranges: Vec<ReplaceRange>,
180 inner_attr_ranges: FxHashMap<AttrId, ReplaceRange>,
183 impl<'a> Drop for Parser<'a> {
185 emit_unclosed_delims(&mut self.unclosed_delims, &self.sess);
191 frame: TokenCursorFrame,
192 stack: Vec<TokenCursorFrame>,
193 desugar_doc_comments: bool,
194 // Counts the number of calls to `next` or `next_desugared`,
195 // depending on whether `desugar_doc_comments` is set.
196 num_next_calls: usize,
197 // During parsing, we may sometimes need to 'unglue' a
198 // glued token into two component tokens
199 // (e.g. '>>' into '>' and '>), so that the parser
200 // can consume them one at a time. This process
201 // bypasses the normal capturing mechanism
202 // (e.g. `num_next_calls` will not be incremented),
203 // since the 'unglued' tokens due not exist in
204 // the original `TokenStream`.
206 // If we end up consuming both unglued tokens,
207 // then this is not an issue - we'll end up
208 // capturing the single 'glued' token.
210 // However, in certain circumstances, we may
211 // want to capture just the first 'unglued' token.
212 // For example, capturing the `Vec<u8>`
213 // in `Option<Vec<u8>>` requires us to unglue
214 // the trailing `>>` token. The `break_last_token`
215 // field is used to track this token - it gets
216 // appended to the captured stream when
217 // we evaluate a `LazyTokenStream`
218 break_last_token: bool,
222 struct TokenCursorFrame {
223 delim: token::DelimToken,
226 tree_cursor: tokenstream::Cursor,
230 impl TokenCursorFrame {
231 fn new(span: DelimSpan, delim: DelimToken, tts: TokenStream) -> Self {
236 tree_cursor: tts.into_trees(),
243 fn next(&mut self) -> (Token, Spacing) {
245 let (tree, spacing) = if !self.frame.open_delim {
246 self.frame.open_delim = true;
247 TokenTree::open_tt(self.frame.span, self.frame.delim).into()
248 } else if let Some(tree) = self.frame.tree_cursor.next_with_spacing() {
250 } else if !self.frame.close_delim {
251 self.frame.close_delim = true;
252 TokenTree::close_tt(self.frame.span, self.frame.delim).into()
253 } else if let Some(frame) = self.stack.pop() {
257 (TokenTree::Token(Token::new(token::Eof, DUMMY_SP)), Spacing::Alone)
261 TokenTree::Token(token) => {
262 return (token, spacing);
264 TokenTree::Delimited(sp, delim, tts) => {
265 let frame = TokenCursorFrame::new(sp, delim, tts);
266 self.stack.push(mem::replace(&mut self.frame, frame));
272 fn next_desugared(&mut self) -> (Token, Spacing) {
273 let (data, attr_style, sp) = match self.next() {
274 (Token { kind: token::DocComment(_, attr_style, data), span }, _) => {
275 (data, attr_style, span)
280 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
281 // required to wrap the text.
282 let mut num_of_hashes = 0;
284 for ch in data.as_str().chars() {
287 '#' if count > 0 => count + 1,
290 num_of_hashes = cmp::max(num_of_hashes, count);
293 let delim_span = DelimSpan::from_single(sp);
294 let body = TokenTree::Delimited(
298 TokenTree::token(token::Ident(sym::doc, false), sp),
299 TokenTree::token(token::Eq, sp),
300 TokenTree::token(TokenKind::lit(token::StrRaw(num_of_hashes), data, None), sp),
304 .collect::<TokenStream>(),
307 self.stack.push(mem::replace(
309 TokenCursorFrame::new(
312 if attr_style == AttrStyle::Inner {
313 [TokenTree::token(token::Pound, sp), TokenTree::token(token::Not, sp), body]
316 .collect::<TokenStream>()
318 [TokenTree::token(token::Pound, sp), body]
321 .collect::<TokenStream>()
330 #[derive(Debug, Clone, PartialEq)]
343 fn to_string(&self) -> String {
345 TokenType::Token(ref t) => format!("`{}`", pprust::token_kind_to_string(t)),
346 TokenType::Keyword(kw) => format!("`{}`", kw),
347 TokenType::Operator => "an operator".to_string(),
348 TokenType::Lifetime => "lifetime".to_string(),
349 TokenType::Ident => "identifier".to_string(),
350 TokenType::Path => "path".to_string(),
351 TokenType::Type => "type".to_string(),
352 TokenType::Const => "a const expression".to_string(),
357 #[derive(Copy, Clone, Debug)]
358 enum TokenExpectType {
363 /// A sequence separator.
365 /// The separator token.
366 sep: Option<TokenKind>,
367 /// `true` if a trailing separator is allowed.
368 trailing_sep_allowed: bool,
372 fn trailing_allowed(t: TokenKind) -> SeqSep {
373 SeqSep { sep: Some(t), trailing_sep_allowed: true }
376 fn none() -> SeqSep {
377 SeqSep { sep: None, trailing_sep_allowed: false }
381 pub enum FollowedByType {
386 fn token_descr_opt(token: &Token) -> Option<&'static str> {
387 Some(match token.kind {
388 _ if token.is_special_ident() => "reserved identifier",
389 _ if token.is_used_keyword() => "keyword",
390 _ if token.is_unused_keyword() => "reserved keyword",
391 token::DocComment(..) => "doc comment",
396 pub(super) fn token_descr(token: &Token) -> String {
397 let token_str = pprust::token_to_string(token);
398 match token_descr_opt(token) {
399 Some(prefix) => format!("{} `{}`", prefix, token_str),
400 _ => format!("`{}`", token_str),
404 impl<'a> Parser<'a> {
408 desugar_doc_comments: bool,
409 subparser_name: Option<&'static str>,
411 let mut start_frame = TokenCursorFrame::new(DelimSpan::dummy(), token::NoDelim, tokens);
412 start_frame.open_delim = true;
413 start_frame.close_delim = true;
415 let mut parser = Parser {
417 token: Token::dummy(),
418 token_spacing: Spacing::Alone,
419 prev_token: Token::dummy(),
421 restrictions: Restrictions::empty(),
422 expected_tokens: Vec::new(),
423 token_cursor: TokenCursor {
427 desugar_doc_comments,
428 break_last_token: false,
430 desugar_doc_comments,
431 unmatched_angle_bracket_count: 0,
432 max_angle_bracket_count: 0,
433 unclosed_delims: Vec::new(),
434 last_unexpected_token_span: None,
435 last_type_ascription: None,
437 capture_state: CaptureState {
438 capturing: Capturing::No,
439 replace_ranges: Vec::new(),
440 inner_attr_ranges: Default::default(),
444 // Make parser point to the first token.
450 fn next_tok(&mut self, fallback_span: Span) -> (Token, Spacing) {
452 let (mut next, spacing) = if self.desugar_doc_comments {
453 self.token_cursor.next_desugared()
455 self.token_cursor.next()
457 self.token_cursor.num_next_calls += 1;
458 // We've retrieved an token from the underlying
459 // cursor, so we no longer need to worry about
460 // an unglued token. See `break_and_eat` for more details
461 self.token_cursor.break_last_token = false;
462 if next.span.is_dummy() {
463 // Tweak the location for better diagnostics, but keep syntactic context intact.
464 next.span = fallback_span.with_ctxt(next.span.ctxt());
468 token::OpenDelim(token::NoDelim) | token::CloseDelim(token::NoDelim)
472 return (next, spacing);
476 pub fn unexpected<T>(&mut self) -> PResult<'a, T> {
477 match self.expect_one_of(&[], &[]) {
479 // We can get `Ok(true)` from `recover_closing_delimiter`
480 // which is called in `expected_one_of_not_found`.
481 Ok(_) => FatalError.raise(),
485 /// Expects and consumes the token `t`. Signals an error if the next token is not `t`.
486 pub fn expect(&mut self, t: &TokenKind) -> PResult<'a, bool /* recovered */> {
487 if self.expected_tokens.is_empty() {
488 if self.token == *t {
492 self.unexpected_try_recover(t)
495 self.expect_one_of(slice::from_ref(t), &[])
499 /// Expect next token to be edible or inedible token. If edible,
500 /// then consume it; if inedible, then return without consuming
501 /// anything. Signal a fatal error if next token is unexpected.
502 pub fn expect_one_of(
504 edible: &[TokenKind],
505 inedible: &[TokenKind],
506 ) -> PResult<'a, bool /* recovered */> {
507 if edible.contains(&self.token.kind) {
510 } else if inedible.contains(&self.token.kind) {
511 // leave it in the input
513 } else if self.last_unexpected_token_span == Some(self.token.span) {
516 self.expected_one_of_not_found(edible, inedible)
520 // Public for rustfmt usage.
521 pub fn parse_ident(&mut self) -> PResult<'a, Ident> {
522 self.parse_ident_common(true)
525 fn ident_or_err(&mut self) -> PResult<'a, (Ident, /* is_raw */ bool)> {
526 self.token.ident().ok_or_else(|| match self.prev_token.kind {
527 TokenKind::DocComment(..) => {
528 self.span_err(self.prev_token.span, Error::UselessDocComment)
530 _ => self.expected_ident_found(),
534 fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, Ident> {
535 let (ident, is_raw) = self.ident_or_err()?;
536 if !is_raw && ident.is_reserved() {
537 let mut err = self.expected_ident_found();
548 /// Checks if the next token is `tok`, and returns `true` if so.
550 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
552 fn check(&mut self, tok: &TokenKind) -> bool {
553 let is_present = self.token == *tok;
555 self.expected_tokens.push(TokenType::Token(tok.clone()));
560 /// Consumes a token 'tok' if it exists. Returns whether the given token was present.
561 pub fn eat(&mut self, tok: &TokenKind) -> bool {
562 let is_present = self.check(tok);
569 /// If the next token is the given keyword, returns `true` without eating it.
570 /// An expectation is also added for diagnostics purposes.
571 fn check_keyword(&mut self, kw: Symbol) -> bool {
572 self.expected_tokens.push(TokenType::Keyword(kw));
573 self.token.is_keyword(kw)
576 /// If the next token is the given keyword, eats it and returns `true`.
577 /// Otherwise, returns `false`. An expectation is also added for diagnostics purposes.
578 // Public for rustfmt usage.
579 pub fn eat_keyword(&mut self, kw: Symbol) -> bool {
580 if self.check_keyword(kw) {
588 fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool {
589 if self.token.is_keyword(kw) {
597 /// If the given word is not a keyword, signals an error.
598 /// If the next token is not the given word, signals an error.
599 /// Otherwise, eats it.
600 fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> {
601 if !self.eat_keyword(kw) { self.unexpected() } else { Ok(()) }
604 /// Is the given keyword `kw` followed by a non-reserved identifier?
605 fn is_kw_followed_by_ident(&self, kw: Symbol) -> bool {
606 self.token.is_keyword(kw) && self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
609 fn check_or_expected(&mut self, ok: bool, typ: TokenType) -> bool {
613 self.expected_tokens.push(typ);
618 fn check_ident(&mut self) -> bool {
619 self.check_or_expected(self.token.is_ident(), TokenType::Ident)
622 fn check_path(&mut self) -> bool {
623 self.check_or_expected(self.token.is_path_start(), TokenType::Path)
626 fn check_type(&mut self) -> bool {
627 self.check_or_expected(self.token.can_begin_type(), TokenType::Type)
630 fn check_const_arg(&mut self) -> bool {
631 self.check_or_expected(self.token.can_begin_const_arg(), TokenType::Const)
634 fn check_inline_const(&self, dist: usize) -> bool {
635 self.is_keyword_ahead(dist, &[kw::Const])
636 && self.look_ahead(dist + 1, |t| match t.kind {
637 token::Interpolated(ref nt) => matches!(**nt, token::NtBlock(..)),
638 token::OpenDelim(DelimToken::Brace) => true,
643 /// Checks to see if the next token is either `+` or `+=`.
644 /// Otherwise returns `false`.
645 fn check_plus(&mut self) -> bool {
646 self.check_or_expected(
647 self.token.is_like_plus(),
648 TokenType::Token(token::BinOp(token::Plus)),
652 /// Eats the expected token if it's present possibly breaking
653 /// compound tokens like multi-character operators in process.
654 /// Returns `true` if the token was eaten.
655 fn break_and_eat(&mut self, expected: TokenKind) -> bool {
656 if self.token.kind == expected {
660 match self.token.kind.break_two_token_op() {
661 Some((first, second)) if first == expected => {
662 let first_span = self.sess.source_map().start_point(self.token.span);
663 let second_span = self.token.span.with_lo(first_span.hi());
664 self.token = Token::new(first, first_span);
665 // Keep track of this token - if we end token capturing now,
666 // we'll want to append this token to the captured stream.
668 // If we consume any additional tokens, then this token
669 // is not needed (we'll capture the entire 'glued' token),
670 // and `next_tok` will set this field to `None`
671 self.token_cursor.break_last_token = true;
672 // Use the spacing of the glued token as the spacing
673 // of the unglued second token.
674 self.bump_with((Token::new(second, second_span), self.token_spacing));
678 self.expected_tokens.push(TokenType::Token(expected));
684 /// Eats `+` possibly breaking tokens like `+=` in process.
685 fn eat_plus(&mut self) -> bool {
686 self.break_and_eat(token::BinOp(token::Plus))
689 /// Eats `&` possibly breaking tokens like `&&` in process.
690 /// Signals an error if `&` is not eaten.
691 fn expect_and(&mut self) -> PResult<'a, ()> {
692 if self.break_and_eat(token::BinOp(token::And)) { Ok(()) } else { self.unexpected() }
695 /// Eats `|` possibly breaking tokens like `||` in process.
696 /// Signals an error if `|` was not eaten.
697 fn expect_or(&mut self) -> PResult<'a, ()> {
698 if self.break_and_eat(token::BinOp(token::Or)) { Ok(()) } else { self.unexpected() }
701 /// Eats `<` possibly breaking tokens like `<<` in process.
702 fn eat_lt(&mut self) -> bool {
703 let ate = self.break_and_eat(token::Lt);
705 // See doc comment for `unmatched_angle_bracket_count`.
706 self.unmatched_angle_bracket_count += 1;
707 self.max_angle_bracket_count += 1;
708 debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count);
713 /// Eats `<` possibly breaking tokens like `<<` in process.
714 /// Signals an error if `<` was not eaten.
715 fn expect_lt(&mut self) -> PResult<'a, ()> {
716 if self.eat_lt() { Ok(()) } else { self.unexpected() }
719 /// Eats `>` possibly breaking tokens like `>>` in process.
720 /// Signals an error if `>` was not eaten.
721 fn expect_gt(&mut self) -> PResult<'a, ()> {
722 if self.break_and_eat(token::Gt) {
723 // See doc comment for `unmatched_angle_bracket_count`.
724 if self.unmatched_angle_bracket_count > 0 {
725 self.unmatched_angle_bracket_count -= 1;
726 debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count);
734 fn expect_any_with_type(&mut self, kets: &[&TokenKind], expect: TokenExpectType) -> bool {
735 kets.iter().any(|k| match expect {
736 TokenExpectType::Expect => self.check(k),
737 TokenExpectType::NoExpect => self.token == **k,
741 fn parse_seq_to_before_tokens<T>(
745 expect: TokenExpectType,
746 mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
747 ) -> PResult<'a, (Vec<T>, bool /* trailing */, bool /* recovered */)> {
748 let mut first = true;
749 let mut recovered = false;
750 let mut trailing = false;
752 let unclosed_delims = !self.unclosed_delims.is_empty();
754 while !self.expect_any_with_type(kets, expect) {
755 if let token::CloseDelim(..) | token::Eof = self.token.kind {
758 if let Some(ref t) = sep.sep {
762 match self.expect(t) {
768 Err(mut expect_err) => {
769 let sp = self.prev_token.span.shrink_to_hi();
770 let token_str = pprust::token_kind_to_string(t);
772 // Attempt to keep parsing if it was a similar separator.
773 if let Some(ref tokens) = t.similar_tokens() {
774 if tokens.contains(&self.token.kind) && !unclosed_delims {
779 // If this was a missing `@` in a binding pattern
780 // bail with a suggestion
781 // https://github.com/rust-lang/rust/issues/72373
782 if self.prev_token.is_ident() && self.token.kind == token::DotDot {
784 "if you meant to bind the contents of \
785 the rest of the array pattern into `{}`, use `@`",
786 pprust::token_to_string(&self.prev_token)
789 .span_suggestion_verbose(
790 self.prev_token.span.shrink_to_hi().until(self.token.span),
793 Applicability::MaybeIncorrect,
799 // Attempt to keep parsing if it was an omitted separator.
802 // Parsed successfully, therefore most probably the code only
803 // misses a separator.
805 .span_suggestion_short(
807 &format!("missing `{}`", token_str),
809 Applicability::MaybeIncorrect,
817 // Parsing failed, therefore it must be something more serious
818 // than just a missing separator.
829 if sep.trailing_sep_allowed && self.expect_any_with_type(kets, expect) {
838 Ok((v, trailing, recovered))
841 /// Parses a sequence, not including the closing delimiter. The function
842 /// `f` must consume tokens until reaching the next separator or
844 fn parse_seq_to_before_end<T>(
848 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
849 ) -> PResult<'a, (Vec<T>, bool, bool)> {
850 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
853 /// Parses a sequence, including the closing delimiter. The function
854 /// `f` must consume tokens until reaching the next separator or
856 fn parse_seq_to_end<T>(
860 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
861 ) -> PResult<'a, (Vec<T>, bool /* trailing */)> {
862 let (val, trailing, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
869 /// Parses a sequence, including the closing delimiter. The function
870 /// `f` must consume tokens until reaching the next separator or
872 fn parse_unspanned_seq<T>(
877 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
878 ) -> PResult<'a, (Vec<T>, bool)> {
880 self.parse_seq_to_end(ket, sep, f)
883 fn parse_delim_comma_seq<T>(
886 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
887 ) -> PResult<'a, (Vec<T>, bool)> {
888 self.parse_unspanned_seq(
889 &token::OpenDelim(delim),
890 &token::CloseDelim(delim),
891 SeqSep::trailing_allowed(token::Comma),
896 fn parse_paren_comma_seq<T>(
898 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
899 ) -> PResult<'a, (Vec<T>, bool)> {
900 self.parse_delim_comma_seq(token::Paren, f)
903 /// Advance the parser by one token using provided token as the next one.
904 fn bump_with(&mut self, (next_token, next_spacing): (Token, Spacing)) {
905 // Bumping after EOF is a bad sign, usually an infinite loop.
906 if self.prev_token.kind == TokenKind::Eof {
907 let msg = "attempted to bump the parser past EOF (may be stuck in a loop)";
908 self.span_bug(self.token.span, msg);
911 // Update the current and previous tokens.
912 self.prev_token = mem::replace(&mut self.token, next_token);
913 self.token_spacing = next_spacing;
916 self.expected_tokens.clear();
919 /// Advance the parser by one token.
920 pub fn bump(&mut self) {
921 let next_token = self.next_tok(self.token.span);
922 self.bump_with(next_token);
925 /// Look-ahead `dist` tokens of `self.token` and get access to that token there.
926 /// When `dist == 0` then the current token is looked at.
927 pub fn look_ahead<R>(&self, dist: usize, looker: impl FnOnce(&Token) -> R) -> R {
929 return looker(&self.token);
932 let frame = &self.token_cursor.frame;
933 if frame.delim != DelimToken::NoDelim {
934 let all_normal = (0..dist).all(|i| {
935 let token = frame.tree_cursor.look_ahead(i);
936 !matches!(token, Some(TokenTree::Delimited(_, DelimToken::NoDelim, _)))
939 return match frame.tree_cursor.look_ahead(dist - 1) {
940 Some(tree) => match tree {
941 TokenTree::Token(token) => looker(token),
942 TokenTree::Delimited(dspan, delim, _) => {
943 looker(&Token::new(token::OpenDelim(*delim), dspan.open))
946 None => looker(&Token::new(token::CloseDelim(frame.delim), frame.span.close)),
951 let mut cursor = self.token_cursor.clone();
953 let mut token = Token::dummy();
955 token = cursor.next().0;
958 token::OpenDelim(token::NoDelim) | token::CloseDelim(token::NoDelim)
964 return looker(&token);
967 /// Returns whether any of the given keywords are `dist` tokens ahead of the current one.
968 fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool {
969 self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw)))
972 /// Parses asyncness: `async` or nothing.
973 fn parse_asyncness(&mut self) -> Async {
974 if self.eat_keyword(kw::Async) {
975 let span = self.prev_token.uninterpolated_span();
976 Async::Yes { span, closure_id: DUMMY_NODE_ID, return_impl_trait_id: DUMMY_NODE_ID }
982 /// Parses unsafety: `unsafe` or nothing.
983 fn parse_unsafety(&mut self) -> Unsafe {
984 if self.eat_keyword(kw::Unsafe) {
985 Unsafe::Yes(self.prev_token.uninterpolated_span())
991 /// Parses constness: `const` or nothing.
992 fn parse_constness(&mut self) -> Const {
993 // Avoid const blocks to be parsed as const items
994 if self.look_ahead(1, |t| t != &token::OpenDelim(DelimToken::Brace))
995 && self.eat_keyword(kw::Const)
997 Const::Yes(self.prev_token.uninterpolated_span())
1003 /// Parses inline const expressions.
1004 fn parse_const_block(&mut self, span: Span) -> PResult<'a, P<Expr>> {
1005 self.sess.gated_spans.gate(sym::inline_const, span);
1006 self.eat_keyword(kw::Const);
1007 let blk = self.parse_block()?;
1008 let anon_const = AnonConst {
1010 value: self.mk_expr(blk.span, ExprKind::Block(blk, None), AttrVec::new()),
1012 let blk_span = anon_const.value.span;
1013 Ok(self.mk_expr(span.to(blk_span), ExprKind::ConstBlock(anon_const), AttrVec::new()))
1016 /// Parses mutability (`mut` or nothing).
1017 fn parse_mutability(&mut self) -> Mutability {
1018 if self.eat_keyword(kw::Mut) { Mutability::Mut } else { Mutability::Not }
1021 /// Possibly parses mutability (`const` or `mut`).
1022 fn parse_const_or_mut(&mut self) -> Option<Mutability> {
1023 if self.eat_keyword(kw::Mut) {
1024 Some(Mutability::Mut)
1025 } else if self.eat_keyword(kw::Const) {
1026 Some(Mutability::Not)
1032 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
1033 if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) = self.token.kind
1035 self.expect_no_suffix(self.token.span, "a tuple index", suffix);
1037 Ok(Ident::new(symbol, self.prev_token.span))
1039 self.parse_ident_common(true)
1043 fn parse_mac_args(&mut self) -> PResult<'a, P<MacArgs>> {
1044 self.parse_mac_args_common(true).map(P)
1047 fn parse_attr_args(&mut self) -> PResult<'a, MacArgs> {
1048 self.parse_mac_args_common(false)
1051 fn parse_mac_args_common(&mut self, delimited_only: bool) -> PResult<'a, MacArgs> {
1053 if self.check(&token::OpenDelim(DelimToken::Paren))
1054 || self.check(&token::OpenDelim(DelimToken::Bracket))
1055 || self.check(&token::OpenDelim(DelimToken::Brace))
1057 match self.parse_token_tree() {
1058 TokenTree::Delimited(dspan, delim, tokens) =>
1059 // We've confirmed above that there is a delimiter so unwrapping is OK.
1061 MacArgs::Delimited(dspan, MacDelimiter::from_token(delim).unwrap(), tokens)
1063 _ => unreachable!(),
1065 } else if !delimited_only {
1066 if self.eat(&token::Eq) {
1067 let eq_span = self.prev_token.span;
1069 // Collect tokens because they are used during lowering to HIR.
1070 let expr = self.parse_expr_force_collect()?;
1071 let span = expr.span;
1073 let token_kind = token::Interpolated(Lrc::new(token::NtExpr(expr)));
1074 MacArgs::Eq(eq_span, Token::new(token_kind, span))
1079 return self.unexpected();
1084 fn parse_or_use_outer_attributes(
1086 already_parsed_attrs: Option<AttrWrapper>,
1087 ) -> PResult<'a, AttrWrapper> {
1088 if let Some(attrs) = already_parsed_attrs {
1091 self.parse_outer_attributes()
1095 /// Parses a single token tree from the input.
1096 pub(crate) fn parse_token_tree(&mut self) -> TokenTree {
1097 match self.token.kind {
1098 token::OpenDelim(..) => {
1099 let depth = self.token_cursor.stack.len();
1101 // We keep advancing the token cursor until we hit
1102 // the matching `CloseDelim` token.
1103 while !(depth == self.token_cursor.stack.len()
1104 && matches!(self.token.kind, token::CloseDelim(_)))
1106 // Advance one token at a time, so `TokenCursor::next()`
1107 // can capture these tokens if necessary.
1110 // We are still inside the frame corresponding
1111 // to the delimited stream we captured, so grab
1112 // the tokens from this frame.
1113 let frame = &self.token_cursor.frame;
1114 let stream = frame.tree_cursor.stream.clone();
1115 let span = frame.span;
1116 let delim = frame.delim;
1117 // Consume close delimiter
1119 TokenTree::Delimited(span, delim, stream)
1121 token::CloseDelim(_) | token::Eof => unreachable!(),
1124 TokenTree::Token(self.prev_token.clone())
1129 /// Parses a stream of tokens into a list of `TokenTree`s, up to EOF.
1130 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
1131 let mut tts = Vec::new();
1132 while self.token != token::Eof {
1133 tts.push(self.parse_token_tree());
1138 pub fn parse_tokens(&mut self) -> TokenStream {
1139 let mut result = Vec::new();
1141 match self.token.kind {
1142 token::Eof | token::CloseDelim(..) => break,
1143 _ => result.push(self.parse_token_tree().into()),
1146 TokenStream::new(result)
1149 /// Evaluates the closure with restrictions in place.
1151 /// Afters the closure is evaluated, restrictions are reset.
1152 fn with_res<T>(&mut self, res: Restrictions, f: impl FnOnce(&mut Self) -> T) -> T {
1153 let old = self.restrictions;
1154 self.restrictions = res;
1156 self.restrictions = old;
1160 fn is_crate_vis(&self) -> bool {
1161 self.token.is_keyword(kw::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
1164 /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`,
1165 /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`.
1166 /// If the following element can't be a tuple (i.e., it's a function definition), then
1167 /// it's not a tuple struct field), and the contents within the parentheses isn't valid,
1168 /// so emit a proper diagnostic.
1169 // Public for rustfmt usage.
1170 pub fn parse_visibility(&mut self, fbt: FollowedByType) -> PResult<'a, Visibility> {
1171 maybe_whole!(self, NtVis, |x| x);
1173 self.expected_tokens.push(TokenType::Keyword(kw::Crate));
1174 if self.is_crate_vis() {
1175 self.bump(); // `crate`
1176 self.sess.gated_spans.gate(sym::crate_visibility_modifier, self.prev_token.span);
1177 return Ok(Visibility {
1178 span: self.prev_token.span,
1179 kind: VisibilityKind::Crate(CrateSugar::JustCrate),
1184 if !self.eat_keyword(kw::Pub) {
1185 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
1186 // keyword to grab a span from for inherited visibility; an empty span at the
1187 // beginning of the current token would seem to be the "Schelling span".
1188 return Ok(Visibility {
1189 span: self.token.span.shrink_to_lo(),
1190 kind: VisibilityKind::Inherited,
1194 let lo = self.prev_token.span;
1196 if self.check(&token::OpenDelim(token::Paren)) {
1197 // We don't `self.bump()` the `(` yet because this might be a struct definition where
1198 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
1199 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
1200 // by the following tokens.
1201 if self.is_keyword_ahead(1, &[kw::Crate]) && self.look_ahead(2, |t| t != &token::ModSep)
1202 // account for `pub(crate::foo)`
1204 // Parse `pub(crate)`.
1206 self.bump(); // `crate`
1207 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1208 let vis = VisibilityKind::Crate(CrateSugar::PubCrate);
1209 return Ok(Visibility {
1210 span: lo.to(self.prev_token.span),
1214 } else if self.is_keyword_ahead(1, &[kw::In]) {
1215 // Parse `pub(in path)`.
1217 self.bump(); // `in`
1218 let path = self.parse_path(PathStyle::Mod)?; // `path`
1219 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1220 let vis = VisibilityKind::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
1221 return Ok(Visibility {
1222 span: lo.to(self.prev_token.span),
1226 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren))
1227 && self.is_keyword_ahead(1, &[kw::Super, kw::SelfLower])
1229 // Parse `pub(self)` or `pub(super)`.
1231 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
1232 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1233 let vis = VisibilityKind::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
1234 return Ok(Visibility {
1235 span: lo.to(self.prev_token.span),
1239 } else if let FollowedByType::No = fbt {
1240 // Provide this diagnostic if a type cannot follow;
1241 // in particular, if this is not a tuple struct.
1242 self.recover_incorrect_vis_restriction()?;
1243 // Emit diagnostic, but continue with public visibility.
1247 Ok(Visibility { span: lo, kind: VisibilityKind::Public, tokens: None })
1250 /// Recovery for e.g. `pub(something) fn ...` or `struct X { pub(something) y: Z }`
1251 fn recover_incorrect_vis_restriction(&mut self) -> PResult<'a, ()> {
1253 let path = self.parse_path(PathStyle::Mod)?;
1254 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1256 let msg = "incorrect visibility restriction";
1257 let suggestion = r##"some possible visibility restrictions are:
1258 `pub(crate)`: visible only on the current crate
1259 `pub(super)`: visible only in the current module's parent
1260 `pub(in path::to::module)`: visible only on the specified path"##;
1262 let path_str = pprust::path_to_string(&path);
1264 struct_span_err!(self.sess.span_diagnostic, path.span, E0704, "{}", msg)
1268 &format!("make this visible only to module `{}` with `in`", path_str),
1269 format!("in {}", path_str),
1270 Applicability::MachineApplicable,
1277 /// Parses `extern string_literal?`.
1278 fn parse_extern(&mut self) -> Extern {
1279 if self.eat_keyword(kw::Extern) { Extern::from_abi(self.parse_abi()) } else { Extern::None }
1282 /// Parses a string literal as an ABI spec.
1283 fn parse_abi(&mut self) -> Option<StrLit> {
1284 match self.parse_str_lit() {
1285 Ok(str_lit) => Some(str_lit),
1286 Err(Some(lit)) => match lit.kind {
1287 ast::LitKind::Err(_) => None,
1289 self.struct_span_err(lit.span, "non-string ABI literal")
1292 "specify the ABI with a string literal",
1293 "\"C\"".to_string(),
1294 Applicability::MaybeIncorrect,
1304 pub fn collect_tokens_no_attrs<R: AstLike>(
1306 f: impl FnOnce(&mut Self) -> PResult<'a, R>,
1307 ) -> PResult<'a, R> {
1308 // The only reason to call `collect_tokens_no_attrs` is if you want tokens, so use
1309 // `ForceCollect::Yes`
1310 self.collect_tokens_trailing_token(
1311 AttrWrapper::empty(),
1313 |this, _attrs| Ok((f(this)?, TrailingToken::None)),
1318 fn is_import_coupler(&mut self) -> bool {
1319 self.check(&token::ModSep)
1320 && self.look_ahead(1, |t| {
1321 *t == token::OpenDelim(token::Brace) || *t == token::BinOp(token::Star)
1325 pub fn clear_expected_tokens(&mut self) {
1326 self.expected_tokens.clear();
1330 crate fn make_unclosed_delims_error(
1331 unmatched: UnmatchedBrace,
1333 ) -> Option<DiagnosticBuilder<'_>> {
1334 // `None` here means an `Eof` was found. We already emit those errors elsewhere, we add them to
1335 // `unmatched_braces` only for error recovery in the `Parser`.
1336 let found_delim = unmatched.found_delim?;
1337 let mut err = sess.span_diagnostic.struct_span_err(
1338 unmatched.found_span,
1340 "mismatched closing delimiter: `{}`",
1341 pprust::token_kind_to_string(&token::CloseDelim(found_delim)),
1344 err.span_label(unmatched.found_span, "mismatched closing delimiter");
1345 if let Some(sp) = unmatched.candidate_span {
1346 err.span_label(sp, "closing delimiter possibly meant for this");
1348 if let Some(sp) = unmatched.unclosed_span {
1349 err.span_label(sp, "unclosed delimiter");
1354 pub fn emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedBrace>, sess: &ParseSess) {
1355 *sess.reached_eof.borrow_mut() |=
1356 unclosed_delims.iter().any(|unmatched_delim| unmatched_delim.found_delim.is_none());
1357 for unmatched in unclosed_delims.drain(..) {
1358 if let Some(mut e) = make_unclosed_delims_error(unmatched, sess) {
1364 /// A helper struct used when building a `AttrAnnotatedTokenStream` from
1365 /// a `LazyTokenStream`. Both delimiter and non-delimited tokens
1366 /// are stored as `FlatToken::Token`. A vector of `FlatToken`s
1367 /// is then 'parsed' to build up a `AttrAnnotatedTokenStream` with nested
1368 /// `AttrAnnotatedTokenTree::Delimited` tokens
1369 #[derive(Debug, Clone)]
1370 pub enum FlatToken {
1371 /// A token - this holds both delimiter (e.g. '{' and '}')
1372 /// and non-delimiter tokens
1374 /// Holds the `AttributesData` for an AST node. The
1375 /// `AttributesData` is inserted directly into the
1376 /// constructed `AttrAnnotatedTokenStream` as
1377 /// a `AttrAnnotatedTokenTree::Attributes`
1378 AttrTarget(AttributesData),
1379 /// A special 'empty' token that is ignored during the conversion
1380 /// to a `AttrAnnotatedTokenStream`. This is used to simplify the
1381 /// handling of replace ranges.