13 use crate::lexer::UnmatchedBrace;
14 pub use attr_wrapper::AttrWrapper;
15 pub use diagnostics::AttemptLocalParseRecovery;
16 pub(crate) use item::FnParseMode;
17 pub use pat::{CommaRecoveryMode, RecoverColon, RecoverComma};
18 pub use path::PathStyle;
20 use rustc_ast::ptr::P;
21 use rustc_ast::token::{self, Delimiter, Nonterminal, 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, AttrStyle, AttrVec, Const, Extern};
28 use rustc_ast::{Async, Expr, ExprKind, MacArgs, MacArgsEq, MacDelimiter, Mutability, StrLit};
29 use rustc_ast::{HasAttrs, HasTokens, Unsafe, Visibility, VisibilityKind};
30 use rustc_ast_pretty::pprust;
31 use rustc_data_structures::fx::FxHashMap;
32 use rustc_errors::PResult;
34 Applicability, DiagnosticBuilder, ErrorGuaranteed, FatalError, IntoDiagnostic, MultiSpan,
36 use rustc_session::parse::ParseSess;
37 use rustc_span::source_map::{Span, DUMMY_SP};
38 use rustc_span::symbol::{kw, sym, Ident, Symbol};
41 use std::{cmp, mem, slice};
44 DocCommentDoesNotDocumentAnything, IncorrectVisibilityRestriction, MismatchedClosingDelimiter,
49 struct Restrictions: u8 {
50 const STMT_EXPR = 1 << 0;
51 const NO_STRUCT_LITERAL = 1 << 1;
52 const CONST_EXPR = 1 << 2;
53 const ALLOW_LET = 1 << 3;
57 #[derive(Clone, Copy, PartialEq, Debug)]
64 #[derive(Clone, Copy, PartialEq, Debug)]
70 /// Whether or not we should force collection of tokens for an AST node,
71 /// regardless of whether or not it has attributes
72 #[derive(Clone, Copy, PartialEq)]
73 pub enum ForceCollect {
78 #[derive(Debug, Eq, PartialEq)]
79 pub enum TrailingToken {
83 /// If the trailing token is a comma, then capture it
84 /// Otherwise, ignore the trailing token
88 /// Like `maybe_whole_expr`, but for things other than expressions.
90 macro_rules! maybe_whole {
91 ($p:expr, $constructor:ident, |$x:ident| $e:expr) => {
92 if let token::Interpolated(nt) = &$p.token.kind {
93 if let token::$constructor(x) = &**nt {
102 /// If the next tokens are ill-formed `$ty::` recover them as `<$ty>::`.
104 macro_rules! maybe_recover_from_interpolated_ty_qpath {
105 ($self: expr, $allow_qpath_recovery: expr) => {
106 if $allow_qpath_recovery
107 && $self.may_recover()
108 && $self.look_ahead(1, |t| t == &token::ModSep)
109 && let token::Interpolated(nt) = &$self.token.kind
110 && let token::NtTy(ty) = &**nt
114 return $self.maybe_recover_from_bad_qpath_stage_2($self.prev_token.span, ty);
119 #[derive(Clone, Copy)]
126 pub struct Parser<'a> {
127 pub sess: &'a ParseSess,
128 /// The current token.
130 /// The spacing for the current token
131 pub token_spacing: Spacing,
132 /// The previous token.
133 pub prev_token: Token,
134 pub capture_cfg: bool,
135 restrictions: Restrictions,
136 expected_tokens: Vec<TokenType>,
137 // Important: This must only be advanced from `bump` to ensure that
138 // `token_cursor.num_next_calls` is updated properly.
139 token_cursor: TokenCursor,
140 desugar_doc_comments: bool,
141 /// This field is used to keep track of how many left angle brackets we have seen. This is
142 /// required in order to detect extra leading left angle brackets (`<` characters) and error
145 /// See the comments in the `parse_path_segment` function for more details.
146 unmatched_angle_bracket_count: u32,
147 max_angle_bracket_count: u32,
148 /// A list of all unclosed delimiters found by the lexer. If an entry is used for error recovery
149 /// it gets removed from here. Every entry left at the end gets emitted as an independent
151 pub(super) unclosed_delims: Vec<UnmatchedBrace>,
152 last_unexpected_token_span: Option<Span>,
153 /// Span pointing at the `:` for the last type ascription the parser has seen, and whether it
154 /// looked like it could have been a mistyped path or literal `Option:Some(42)`).
155 pub last_type_ascription: Option<(Span, bool /* likely path typo */)>,
156 /// If present, this `Parser` is not parsing Rust code but rather a macro call.
157 subparser_name: Option<&'static str>,
158 capture_state: CaptureState,
159 /// This allows us to recover when the user forget to add braces around
160 /// multiple statements in the closure body.
161 pub current_closure: Option<ClosureSpans>,
162 /// Whether the parser is allowed to do recovery.
163 /// This is disabled when parsing macro arguments, see #103534
164 pub recovery: Recovery,
167 // This type is used a lot, e.g. it's cloned when matching many declarative macro rules with nonterminals. Make sure
168 // it doesn't unintentionally get bigger.
169 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
170 rustc_data_structures::static_assert_size!(Parser<'_>, 336);
172 /// Stores span information about a closure.
174 pub struct ClosureSpans {
175 pub whole_closure: Span,
176 pub closing_pipe: Span,
180 /// Indicates a range of tokens that should be replaced by
181 /// the tokens in the provided vector. This is used in two
182 /// places during token collection:
184 /// 1. During the parsing of an AST node that may have a `#[derive]`
185 /// attribute, we parse a nested AST node that has `#[cfg]` or `#[cfg_attr]`
186 /// In this case, we use a `ReplaceRange` to replace the entire inner AST node
187 /// with `FlatToken::AttrTarget`, allowing us to perform eager cfg-expansion
188 /// on an `AttrTokenStream`.
190 /// 2. When we parse an inner attribute while collecting tokens. We
191 /// remove inner attributes from the token stream entirely, and
192 /// instead track them through the `attrs` field on the AST node.
193 /// This allows us to easily manipulate them (for example, removing
194 /// the first macro inner attribute to invoke a proc-macro).
195 /// When create a `TokenStream`, the inner attributes get inserted
196 /// into the proper place in the token stream.
197 pub type ReplaceRange = (Range<u32>, Vec<(FlatToken, Spacing)>);
199 /// Controls how we capture tokens. Capturing can be expensive,
200 /// so we try to avoid performing capturing in cases where
201 /// we will never need an `AttrTokenStream`.
202 #[derive(Copy, Clone)]
204 /// We aren't performing any capturing - this is the default mode.
206 /// We are capturing tokens
211 struct CaptureState {
212 capturing: Capturing,
213 replace_ranges: Vec<ReplaceRange>,
214 inner_attr_ranges: FxHashMap<AttrId, ReplaceRange>,
217 impl<'a> Drop for Parser<'a> {
219 emit_unclosed_delims(&mut self.unclosed_delims, &self.sess);
225 // The current (innermost) frame. `frame` and `stack` could be combined,
226 // but it's faster to have them separately to access `frame` directly
227 // rather than via something like `stack.last().unwrap()` or
228 // `stack[stack.len() - 1]`.
229 frame: TokenCursorFrame,
230 // Additional frames that enclose `frame`.
231 stack: Vec<TokenCursorFrame>,
232 desugar_doc_comments: bool,
233 // Counts the number of calls to `{,inlined_}next`.
234 num_next_calls: usize,
235 // During parsing, we may sometimes need to 'unglue' a
236 // glued token into two component tokens
237 // (e.g. '>>' into '>' and '>), so that the parser
238 // can consume them one at a time. This process
239 // bypasses the normal capturing mechanism
240 // (e.g. `num_next_calls` will not be incremented),
241 // since the 'unglued' tokens due not exist in
242 // the original `TokenStream`.
244 // If we end up consuming both unglued tokens,
245 // then this is not an issue - we'll end up
246 // capturing the single 'glued' token.
248 // However, in certain circumstances, we may
249 // want to capture just the first 'unglued' token.
250 // For example, capturing the `Vec<u8>`
251 // in `Option<Vec<u8>>` requires us to unglue
252 // the trailing `>>` token. The `break_last_token`
253 // field is used to track this token - it gets
254 // appended to the captured stream when
255 // we evaluate a `LazyAttrTokenStream`.
256 break_last_token: bool,
260 struct TokenCursorFrame {
261 delim_sp: Option<(Delimiter, DelimSpan)>,
262 tree_cursor: tokenstream::Cursor,
265 impl TokenCursorFrame {
266 fn new(delim_sp: Option<(Delimiter, DelimSpan)>, tts: TokenStream) -> Self {
267 TokenCursorFrame { delim_sp, tree_cursor: tts.into_trees() }
272 fn next(&mut self, desugar_doc_comments: bool) -> (Token, Spacing) {
273 self.inlined_next(desugar_doc_comments)
276 /// This always-inlined version should only be used on hot code paths.
278 fn inlined_next(&mut self, desugar_doc_comments: bool) -> (Token, Spacing) {
280 // FIXME: we currently don't return `Delimiter` open/close delims. To fix #67062 we will
281 // need to, whereupon the `delim != Delimiter::Invisible` conditions below can be
283 if let Some(tree) = self.frame.tree_cursor.next_ref() {
285 &TokenTree::Token(ref token, spacing) => match (desugar_doc_comments, token) {
286 (true, &Token { kind: token::DocComment(_, attr_style, data), span }) => {
287 return self.desugar(attr_style, data, span);
289 _ => return (token.clone(), spacing),
291 &TokenTree::Delimited(sp, delim, ref tts) => {
292 // Set `open_delim` to true here because we deal with it immediately.
293 let frame = TokenCursorFrame::new(Some((delim, sp)), tts.clone());
294 self.stack.push(mem::replace(&mut self.frame, frame));
295 if delim != Delimiter::Invisible {
296 return (Token::new(token::OpenDelim(delim), sp.open), Spacing::Alone);
298 // No open delimiter to return; continue on to the next iteration.
301 } else if let Some(frame) = self.stack.pop() {
302 if let Some((delim, span)) = self.frame.delim_sp && delim != Delimiter::Invisible {
304 return (Token::new(token::CloseDelim(delim), span.close), Spacing::Alone);
307 // No close delimiter to return; continue on to the next iteration.
309 return (Token::new(token::Eof, DUMMY_SP), Spacing::Alone);
314 fn desugar(&mut self, attr_style: AttrStyle, data: Symbol, span: Span) -> (Token, Spacing) {
315 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
316 // required to wrap the text. E.g.
317 // - `abc d` is wrapped as `r"abc d"` (num_of_hashes = 0)
318 // - `abc "d"` is wrapped as `r#"abc "d""#` (num_of_hashes = 1)
319 // - `abc "##d##"` is wrapped as `r###"abc "d""###` (num_of_hashes = 3)
320 let mut num_of_hashes = 0;
322 for ch in data.as_str().chars() {
325 '#' if count > 0 => count + 1,
328 num_of_hashes = cmp::max(num_of_hashes, count);
331 // `/// foo` becomes `doc = r"foo".
332 let delim_span = DelimSpan::from_single(span);
333 let body = TokenTree::Delimited(
337 TokenTree::token_alone(token::Ident(sym::doc, false), span),
338 TokenTree::token_alone(token::Eq, span),
339 TokenTree::token_alone(
340 TokenKind::lit(token::StrRaw(num_of_hashes), data, None),
345 .collect::<TokenStream>(),
348 self.stack.push(mem::replace(
350 TokenCursorFrame::new(
352 if attr_style == AttrStyle::Inner {
354 TokenTree::token_alone(token::Pound, span),
355 TokenTree::token_alone(token::Not, span),
359 .collect::<TokenStream>()
361 [TokenTree::token_alone(token::Pound, span), body]
363 .collect::<TokenStream>()
368 self.next(/* desugar_doc_comments */ false)
372 #[derive(Debug, Clone, PartialEq)]
385 fn to_string(&self) -> String {
387 TokenType::Token(ref t) => format!("`{}`", pprust::token_kind_to_string(t)),
388 TokenType::Keyword(kw) => format!("`{}`", kw),
389 TokenType::Operator => "an operator".to_string(),
390 TokenType::Lifetime => "lifetime".to_string(),
391 TokenType::Ident => "identifier".to_string(),
392 TokenType::Path => "path".to_string(),
393 TokenType::Type => "type".to_string(),
394 TokenType::Const => "a const expression".to_string(),
399 #[derive(Copy, Clone, Debug)]
400 enum TokenExpectType {
405 /// A sequence separator.
407 /// The separator token.
408 sep: Option<TokenKind>,
409 /// `true` if a trailing separator is allowed.
410 trailing_sep_allowed: bool,
414 fn trailing_allowed(t: TokenKind) -> SeqSep {
415 SeqSep { sep: Some(t), trailing_sep_allowed: true }
418 fn none() -> SeqSep {
419 SeqSep { sep: None, trailing_sep_allowed: false }
423 pub enum FollowedByType {
428 #[derive(Clone, Copy, PartialEq, Eq)]
429 pub enum TokenDescription {
436 impl TokenDescription {
437 pub fn from_token(token: &Token) -> Option<Self> {
439 _ if token.is_special_ident() => Some(TokenDescription::ReservedIdentifier),
440 _ if token.is_used_keyword() => Some(TokenDescription::Keyword),
441 _ if token.is_unused_keyword() => Some(TokenDescription::ReservedKeyword),
442 token::DocComment(..) => Some(TokenDescription::DocComment),
448 pub(super) fn token_descr(token: &Token) -> String {
449 let name = pprust::token_to_string(token).to_string();
451 let kind = TokenDescription::from_token(token).map(|kind| match kind {
452 TokenDescription::ReservedIdentifier => "reserved identifier",
453 TokenDescription::Keyword => "keyword",
454 TokenDescription::ReservedKeyword => "reserved keyword",
455 TokenDescription::DocComment => "doc comment",
458 if let Some(kind) = kind { format!("{} `{}`", kind, name) } else { format!("`{}`", name) }
461 impl<'a> Parser<'a> {
465 desugar_doc_comments: bool,
466 subparser_name: Option<&'static str>,
468 let mut parser = Parser {
470 token: Token::dummy(),
471 token_spacing: Spacing::Alone,
472 prev_token: Token::dummy(),
474 restrictions: Restrictions::empty(),
475 expected_tokens: Vec::new(),
476 token_cursor: TokenCursor {
477 frame: TokenCursorFrame::new(None, tokens),
480 desugar_doc_comments,
481 break_last_token: false,
483 desugar_doc_comments,
484 unmatched_angle_bracket_count: 0,
485 max_angle_bracket_count: 0,
486 unclosed_delims: Vec::new(),
487 last_unexpected_token_span: None,
488 last_type_ascription: None,
490 capture_state: CaptureState {
491 capturing: Capturing::No,
492 replace_ranges: Vec::new(),
493 inner_attr_ranges: Default::default(),
495 current_closure: None,
496 recovery: Recovery::Allowed,
499 // Make parser point to the first token.
505 pub fn forbid_recovery(mut self) -> Self {
506 self.recovery = Recovery::Forbidden;
510 /// Whether the parser is allowed to recover from broken code.
512 /// If this returns false, recovering broken code into valid code (especially if this recovery does lookahead)
513 /// is not allowed. All recovery done by the parser must be gated behind this check.
515 /// Technically, this only needs to restrict eager recovery by doing lookahead at more tokens.
516 /// But making the distinction is very subtle, and simply forbidding all recovery is a lot simpler to uphold.
517 fn may_recover(&self) -> bool {
518 matches!(self.recovery, Recovery::Allowed)
521 pub fn unexpected<T>(&mut self) -> PResult<'a, T> {
522 match self.expect_one_of(&[], &[]) {
524 // We can get `Ok(true)` from `recover_closing_delimiter`
525 // which is called in `expected_one_of_not_found`.
526 Ok(_) => FatalError.raise(),
530 /// Expects and consumes the token `t`. Signals an error if the next token is not `t`.
531 pub fn expect(&mut self, t: &TokenKind) -> PResult<'a, bool /* recovered */> {
532 if self.expected_tokens.is_empty() {
533 if self.token == *t {
537 self.unexpected_try_recover(t)
540 self.expect_one_of(slice::from_ref(t), &[])
544 /// Expect next token to be edible or inedible token. If edible,
545 /// then consume it; if inedible, then return without consuming
546 /// anything. Signal a fatal error if next token is unexpected.
547 pub fn expect_one_of(
549 edible: &[TokenKind],
550 inedible: &[TokenKind],
551 ) -> PResult<'a, bool /* recovered */> {
552 if edible.contains(&self.token.kind) {
555 } else if inedible.contains(&self.token.kind) {
556 // leave it in the input
558 } else if self.last_unexpected_token_span == Some(self.token.span) {
561 self.expected_one_of_not_found(edible, inedible)
565 // Public for rustfmt usage.
566 pub fn parse_ident(&mut self) -> PResult<'a, Ident> {
567 self.parse_ident_common(true)
570 fn ident_or_err(&mut self) -> PResult<'a, (Ident, /* is_raw */ bool)> {
571 self.token.ident().ok_or_else(|| match self.prev_token.kind {
572 TokenKind::DocComment(..) => DocCommentDoesNotDocumentAnything {
573 span: self.prev_token.span,
576 .into_diagnostic(&self.sess.span_diagnostic),
577 _ => self.expected_ident_found(),
581 fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, Ident> {
582 let (ident, is_raw) = self.ident_or_err()?;
583 if !is_raw && ident.is_reserved() {
584 let mut err = self.expected_ident_found();
595 /// Checks if the next token is `tok`, and returns `true` if so.
597 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
599 fn check(&mut self, tok: &TokenKind) -> bool {
600 let is_present = self.token == *tok;
602 self.expected_tokens.push(TokenType::Token(tok.clone()));
607 fn check_noexpect(&self, tok: &TokenKind) -> bool {
611 /// Consumes a token 'tok' if it exists. Returns whether the given token was present.
613 /// the main purpose of this function is to reduce the cluttering of the suggestions list
614 /// which using the normal eat method could introduce in some cases.
615 pub fn eat_noexpect(&mut self, tok: &TokenKind) -> bool {
616 let is_present = self.check_noexpect(tok);
623 /// Consumes a token 'tok' if it exists. Returns whether the given token was present.
624 pub fn eat(&mut self, tok: &TokenKind) -> bool {
625 let is_present = self.check(tok);
632 /// If the next token is the given keyword, returns `true` without eating it.
633 /// An expectation is also added for diagnostics purposes.
634 fn check_keyword(&mut self, kw: Symbol) -> bool {
635 self.expected_tokens.push(TokenType::Keyword(kw));
636 self.token.is_keyword(kw)
639 /// If the next token is the given keyword, eats it and returns `true`.
640 /// Otherwise, returns `false`. An expectation is also added for diagnostics purposes.
641 // Public for rustfmt usage.
642 pub fn eat_keyword(&mut self, kw: Symbol) -> bool {
643 if self.check_keyword(kw) {
651 fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool {
652 if self.token.is_keyword(kw) {
660 /// If the given word is not a keyword, signals an error.
661 /// If the next token is not the given word, signals an error.
662 /// Otherwise, eats it.
663 fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> {
664 if !self.eat_keyword(kw) { self.unexpected() } else { Ok(()) }
667 /// Is the given keyword `kw` followed by a non-reserved identifier?
668 fn is_kw_followed_by_ident(&self, kw: Symbol) -> bool {
669 self.token.is_keyword(kw) && self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
672 fn check_or_expected(&mut self, ok: bool, typ: TokenType) -> bool {
676 self.expected_tokens.push(typ);
681 fn check_ident(&mut self) -> bool {
682 self.check_or_expected(self.token.is_ident(), TokenType::Ident)
685 fn check_path(&mut self) -> bool {
686 self.check_or_expected(self.token.is_path_start(), TokenType::Path)
689 fn check_type(&mut self) -> bool {
690 self.check_or_expected(self.token.can_begin_type(), TokenType::Type)
693 fn check_const_arg(&mut self) -> bool {
694 self.check_or_expected(self.token.can_begin_const_arg(), TokenType::Const)
697 fn check_inline_const(&self, dist: usize) -> bool {
698 self.is_keyword_ahead(dist, &[kw::Const])
699 && self.look_ahead(dist + 1, |t| match t.kind {
700 token::Interpolated(ref nt) => matches!(**nt, token::NtBlock(..)),
701 token::OpenDelim(Delimiter::Brace) => true,
706 /// Checks to see if the next token is either `+` or `+=`.
707 /// Otherwise returns `false`.
708 fn check_plus(&mut self) -> bool {
709 self.check_or_expected(
710 self.token.is_like_plus(),
711 TokenType::Token(token::BinOp(token::Plus)),
715 /// Eats the expected token if it's present possibly breaking
716 /// compound tokens like multi-character operators in process.
717 /// Returns `true` if the token was eaten.
718 fn break_and_eat(&mut self, expected: TokenKind) -> bool {
719 if self.token.kind == expected {
723 match self.token.kind.break_two_token_op() {
724 Some((first, second)) if first == expected => {
725 let first_span = self.sess.source_map().start_point(self.token.span);
726 let second_span = self.token.span.with_lo(first_span.hi());
727 self.token = Token::new(first, first_span);
728 // Keep track of this token - if we end token capturing now,
729 // we'll want to append this token to the captured stream.
731 // If we consume any additional tokens, then this token
732 // is not needed (we'll capture the entire 'glued' token),
733 // and `bump` will set this field to `None`
734 self.token_cursor.break_last_token = true;
735 // Use the spacing of the glued token as the spacing
736 // of the unglued second token.
737 self.bump_with((Token::new(second, second_span), self.token_spacing));
741 self.expected_tokens.push(TokenType::Token(expected));
747 /// Eats `+` possibly breaking tokens like `+=` in process.
748 fn eat_plus(&mut self) -> bool {
749 self.break_and_eat(token::BinOp(token::Plus))
752 /// Eats `&` possibly breaking tokens like `&&` in process.
753 /// Signals an error if `&` is not eaten.
754 fn expect_and(&mut self) -> PResult<'a, ()> {
755 if self.break_and_eat(token::BinOp(token::And)) { Ok(()) } else { self.unexpected() }
758 /// Eats `|` possibly breaking tokens like `||` in process.
759 /// Signals an error if `|` was not eaten.
760 fn expect_or(&mut self) -> PResult<'a, ()> {
761 if self.break_and_eat(token::BinOp(token::Or)) { Ok(()) } else { self.unexpected() }
764 /// Eats `<` possibly breaking tokens like `<<` in process.
765 fn eat_lt(&mut self) -> bool {
766 let ate = self.break_and_eat(token::Lt);
768 // See doc comment for `unmatched_angle_bracket_count`.
769 self.unmatched_angle_bracket_count += 1;
770 self.max_angle_bracket_count += 1;
771 debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count);
776 /// Eats `<` possibly breaking tokens like `<<` in process.
777 /// Signals an error if `<` was not eaten.
778 fn expect_lt(&mut self) -> PResult<'a, ()> {
779 if self.eat_lt() { Ok(()) } else { self.unexpected() }
782 /// Eats `>` possibly breaking tokens like `>>` in process.
783 /// Signals an error if `>` was not eaten.
784 fn expect_gt(&mut self) -> PResult<'a, ()> {
785 if self.break_and_eat(token::Gt) {
786 // See doc comment for `unmatched_angle_bracket_count`.
787 if self.unmatched_angle_bracket_count > 0 {
788 self.unmatched_angle_bracket_count -= 1;
789 debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count);
797 fn expect_any_with_type(&mut self, kets: &[&TokenKind], expect: TokenExpectType) -> bool {
798 kets.iter().any(|k| match expect {
799 TokenExpectType::Expect => self.check(k),
800 TokenExpectType::NoExpect => self.token == **k,
804 fn parse_seq_to_before_tokens<T>(
808 expect: TokenExpectType,
809 mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
810 ) -> PResult<'a, (Vec<T>, bool /* trailing */, bool /* recovered */)> {
811 let mut first = true;
812 let mut recovered = false;
813 let mut trailing = false;
815 let unclosed_delims = !self.unclosed_delims.is_empty();
817 while !self.expect_any_with_type(kets, expect) {
818 if let token::CloseDelim(..) | token::Eof = self.token.kind {
821 if let Some(ref t) = sep.sep {
825 match self.expect(t) {
827 self.current_closure.take();
830 self.current_closure.take();
834 Err(mut expect_err) => {
835 let sp = self.prev_token.span.shrink_to_hi();
836 let token_str = pprust::token_kind_to_string(t);
838 match self.current_closure.take() {
839 Some(closure_spans) if self.token.kind == TokenKind::Semi => {
840 // Finding a semicolon instead of a comma
841 // after a closure body indicates that the
842 // closure body may be a block but the user
843 // forgot to put braces around its
846 self.recover_missing_braces_around_closure_body(
855 // Attempt to keep parsing if it was a similar separator.
856 if let Some(ref tokens) = t.similar_tokens() {
857 if tokens.contains(&self.token.kind) && !unclosed_delims {
864 // If this was a missing `@` in a binding pattern
865 // bail with a suggestion
866 // https://github.com/rust-lang/rust/issues/72373
867 if self.prev_token.is_ident() && self.token.kind == token::DotDot {
869 "if you meant to bind the contents of \
870 the rest of the array pattern into `{}`, use `@`",
871 pprust::token_to_string(&self.prev_token)
874 .span_suggestion_verbose(
875 self.prev_token.span.shrink_to_hi().until(self.token.span),
878 Applicability::MaybeIncorrect,
884 // Attempt to keep parsing if it was an omitted separator.
887 // Parsed successfully, therefore most probably the code only
888 // misses a separator.
890 .span_suggestion_short(
892 &format!("missing `{}`", token_str),
894 Applicability::MaybeIncorrect,
902 // Parsing failed, therefore it must be something more serious
903 // than just a missing separator.
914 if sep.trailing_sep_allowed && self.expect_any_with_type(kets, expect) {
923 Ok((v, trailing, recovered))
926 fn recover_missing_braces_around_closure_body(
928 closure_spans: ClosureSpans,
929 mut expect_err: DiagnosticBuilder<'_, ErrorGuaranteed>,
930 ) -> PResult<'a, ()> {
931 let initial_semicolon = self.token.span;
933 while self.eat(&TokenKind::Semi) {
934 let _ = self.parse_stmt(ForceCollect::Yes)?;
937 expect_err.set_primary_message(
938 "closure bodies that contain statements must be surrounded by braces",
941 let preceding_pipe_span = closure_spans.closing_pipe;
942 let following_token_span = self.token.span;
944 let mut first_note = MultiSpan::from(vec![initial_semicolon]);
945 first_note.push_span_label(
947 "this `;` turns the preceding closure into a statement",
949 first_note.push_span_label(
951 "this expression is a statement because of the trailing semicolon",
953 expect_err.span_note(first_note, "statement found outside of a block");
955 let mut second_note = MultiSpan::from(vec![closure_spans.whole_closure]);
956 second_note.push_span_label(closure_spans.whole_closure, "this is the parsed closure...");
957 second_note.push_span_label(
958 following_token_span,
959 "...but likely you meant the closure to end here",
961 expect_err.span_note(second_note, "the closure body may be incorrectly delimited");
963 expect_err.set_span(vec![preceding_pipe_span, following_token_span]);
965 let opening_suggestion_str = " {".to_string();
966 let closing_suggestion_str = "}".to_string();
968 expect_err.multipart_suggestion(
971 (preceding_pipe_span.shrink_to_hi(), opening_suggestion_str),
972 (following_token_span.shrink_to_lo(), closing_suggestion_str),
974 Applicability::MaybeIncorrect,
982 /// Parses a sequence, not including the closing delimiter. The function
983 /// `f` must consume tokens until reaching the next separator or
985 fn parse_seq_to_before_end<T>(
989 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
990 ) -> PResult<'a, (Vec<T>, bool, bool)> {
991 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
994 /// Parses a sequence, including the closing delimiter. The function
995 /// `f` must consume tokens until reaching the next separator or
997 fn parse_seq_to_end<T>(
1001 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1002 ) -> PResult<'a, (Vec<T>, bool /* trailing */)> {
1003 let (val, trailing, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
1010 /// Parses a sequence, including the closing delimiter. The function
1011 /// `f` must consume tokens until reaching the next separator or
1012 /// closing bracket.
1013 fn parse_unspanned_seq<T>(
1018 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1019 ) -> PResult<'a, (Vec<T>, bool)> {
1021 self.parse_seq_to_end(ket, sep, f)
1024 fn parse_delim_comma_seq<T>(
1027 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1028 ) -> PResult<'a, (Vec<T>, bool)> {
1029 self.parse_unspanned_seq(
1030 &token::OpenDelim(delim),
1031 &token::CloseDelim(delim),
1032 SeqSep::trailing_allowed(token::Comma),
1037 fn parse_paren_comma_seq<T>(
1039 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1040 ) -> PResult<'a, (Vec<T>, bool)> {
1041 self.parse_delim_comma_seq(Delimiter::Parenthesis, f)
1044 /// Advance the parser by one token using provided token as the next one.
1045 fn bump_with(&mut self, next: (Token, Spacing)) {
1046 self.inlined_bump_with(next)
1049 /// This always-inlined version should only be used on hot code paths.
1051 fn inlined_bump_with(&mut self, (next_token, next_spacing): (Token, Spacing)) {
1052 // Update the current and previous tokens.
1053 self.prev_token = mem::replace(&mut self.token, next_token);
1054 self.token_spacing = next_spacing;
1057 self.expected_tokens.clear();
1060 /// Advance the parser by one token.
1061 pub fn bump(&mut self) {
1062 // Note: destructuring here would give nicer code, but it was found in #96210 to be slower
1063 // than `.0`/`.1` access.
1064 let mut next = self.token_cursor.inlined_next(self.desugar_doc_comments);
1065 self.token_cursor.num_next_calls += 1;
1066 // We've retrieved an token from the underlying
1067 // cursor, so we no longer need to worry about
1068 // an unglued token. See `break_and_eat` for more details
1069 self.token_cursor.break_last_token = false;
1070 if next.0.span.is_dummy() {
1071 // Tweak the location for better diagnostics, but keep syntactic context intact.
1072 let fallback_span = self.token.span;
1073 next.0.span = fallback_span.with_ctxt(next.0.span.ctxt());
1075 debug_assert!(!matches!(
1077 token::OpenDelim(Delimiter::Invisible) | token::CloseDelim(Delimiter::Invisible)
1079 self.inlined_bump_with(next)
1082 /// Look-ahead `dist` tokens of `self.token` and get access to that token there.
1083 /// When `dist == 0` then the current token is looked at.
1084 pub fn look_ahead<R>(&self, dist: usize, looker: impl FnOnce(&Token) -> R) -> R {
1086 return looker(&self.token);
1089 let frame = &self.token_cursor.frame;
1090 if let Some((delim, span)) = frame.delim_sp && delim != Delimiter::Invisible {
1091 let all_normal = (0..dist).all(|i| {
1092 let token = frame.tree_cursor.look_ahead(i);
1093 !matches!(token, Some(TokenTree::Delimited(_, Delimiter::Invisible, _)))
1096 return match frame.tree_cursor.look_ahead(dist - 1) {
1097 Some(tree) => match tree {
1098 TokenTree::Token(token, _) => looker(token),
1099 TokenTree::Delimited(dspan, delim, _) => {
1100 looker(&Token::new(token::OpenDelim(*delim), dspan.open))
1103 None => looker(&Token::new(token::CloseDelim(delim), span.close)),
1108 let mut cursor = self.token_cursor.clone();
1110 let mut token = Token::dummy();
1112 token = cursor.next(/* desugar_doc_comments */ false).0;
1115 token::OpenDelim(Delimiter::Invisible) | token::CloseDelim(Delimiter::Invisible)
1121 return looker(&token);
1124 /// Returns whether any of the given keywords are `dist` tokens ahead of the current one.
1125 fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool {
1126 self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw)))
1129 /// Parses asyncness: `async` or nothing.
1130 fn parse_asyncness(&mut self) -> Async {
1131 if self.eat_keyword(kw::Async) {
1132 let span = self.prev_token.uninterpolated_span();
1133 Async::Yes { span, closure_id: DUMMY_NODE_ID, return_impl_trait_id: DUMMY_NODE_ID }
1139 /// Parses unsafety: `unsafe` or nothing.
1140 fn parse_unsafety(&mut self) -> Unsafe {
1141 if self.eat_keyword(kw::Unsafe) {
1142 Unsafe::Yes(self.prev_token.uninterpolated_span())
1148 /// Parses constness: `const` or nothing.
1149 fn parse_constness(&mut self) -> Const {
1150 // Avoid const blocks to be parsed as const items
1151 if self.look_ahead(1, |t| t != &token::OpenDelim(Delimiter::Brace))
1152 && self.eat_keyword(kw::Const)
1154 Const::Yes(self.prev_token.uninterpolated_span())
1160 /// Parses inline const expressions.
1161 fn parse_const_block(&mut self, span: Span, pat: bool) -> PResult<'a, P<Expr>> {
1163 self.sess.gated_spans.gate(sym::inline_const_pat, span);
1165 self.sess.gated_spans.gate(sym::inline_const, span);
1167 self.eat_keyword(kw::Const);
1168 let (attrs, blk) = self.parse_inner_attrs_and_block()?;
1169 let anon_const = AnonConst {
1171 value: self.mk_expr(blk.span, ExprKind::Block(blk, None)),
1173 let blk_span = anon_const.value.span;
1174 Ok(self.mk_expr_with_attrs(
1176 ExprKind::ConstBlock(anon_const),
1177 AttrVec::from(attrs),
1181 /// Parses mutability (`mut` or nothing).
1182 fn parse_mutability(&mut self) -> Mutability {
1183 if self.eat_keyword(kw::Mut) { Mutability::Mut } else { Mutability::Not }
1186 /// Possibly parses mutability (`const` or `mut`).
1187 fn parse_const_or_mut(&mut self) -> Option<Mutability> {
1188 if self.eat_keyword(kw::Mut) {
1189 Some(Mutability::Mut)
1190 } else if self.eat_keyword(kw::Const) {
1191 Some(Mutability::Not)
1197 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
1198 if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) = self.token.kind
1200 if let Some(suffix) = suffix {
1201 self.expect_no_tuple_index_suffix(self.token.span, suffix);
1204 Ok(Ident::new(symbol, self.prev_token.span))
1206 self.parse_ident_common(true)
1210 fn parse_mac_args(&mut self) -> PResult<'a, P<MacArgs>> {
1211 self.parse_mac_args_common(true).map(P)
1214 fn parse_attr_args(&mut self) -> PResult<'a, MacArgs> {
1215 self.parse_mac_args_common(false)
1218 fn parse_mac_args_common(&mut self, delimited_only: bool) -> PResult<'a, MacArgs> {
1220 if self.check(&token::OpenDelim(Delimiter::Parenthesis))
1221 || self.check(&token::OpenDelim(Delimiter::Bracket))
1222 || self.check(&token::OpenDelim(Delimiter::Brace))
1224 match self.parse_token_tree() {
1225 TokenTree::Delimited(dspan, delim, tokens) =>
1226 // We've confirmed above that there is a delimiter so unwrapping is OK.
1228 MacArgs::Delimited(dspan, MacDelimiter::from_token(delim).unwrap(), tokens)
1230 _ => unreachable!(),
1232 } else if !delimited_only {
1233 if self.eat(&token::Eq) {
1234 let eq_span = self.prev_token.span;
1235 MacArgs::Eq(eq_span, MacArgsEq::Ast(self.parse_expr_force_collect()?))
1240 return self.unexpected();
1245 fn parse_or_use_outer_attributes(
1247 already_parsed_attrs: Option<AttrWrapper>,
1248 ) -> PResult<'a, AttrWrapper> {
1249 if let Some(attrs) = already_parsed_attrs {
1252 self.parse_outer_attributes()
1256 /// Parses a single token tree from the input.
1257 pub(crate) fn parse_token_tree(&mut self) -> TokenTree {
1258 match self.token.kind {
1259 token::OpenDelim(..) => {
1260 // Grab the tokens from this frame.
1261 let frame = &self.token_cursor.frame;
1262 let stream = frame.tree_cursor.stream.clone();
1263 let (delim, span) = frame.delim_sp.unwrap();
1265 // Advance the token cursor through the entire delimited
1266 // sequence. After getting the `OpenDelim` we are *within* the
1267 // delimited sequence, i.e. at depth `d`. After getting the
1268 // matching `CloseDelim` we are *after* the delimited sequence,
1269 // i.e. at depth `d - 1`.
1270 let target_depth = self.token_cursor.stack.len() - 1;
1272 // Advance one token at a time, so `TokenCursor::next()`
1273 // can capture these tokens if necessary.
1275 if self.token_cursor.stack.len() == target_depth {
1276 debug_assert!(matches!(self.token.kind, token::CloseDelim(_)));
1281 // Consume close delimiter
1283 TokenTree::Delimited(span, delim, stream)
1285 token::CloseDelim(_) | token::Eof => unreachable!(),
1288 TokenTree::Token(self.prev_token.clone(), Spacing::Alone)
1293 /// Parses a stream of tokens into a list of `TokenTree`s, up to EOF.
1294 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
1295 let mut tts = Vec::new();
1296 while self.token != token::Eof {
1297 tts.push(self.parse_token_tree());
1302 pub fn parse_tokens(&mut self) -> TokenStream {
1303 let mut result = Vec::new();
1305 match self.token.kind {
1306 token::Eof | token::CloseDelim(..) => break,
1307 _ => result.push(self.parse_token_tree()),
1310 TokenStream::new(result)
1313 /// Evaluates the closure with restrictions in place.
1315 /// Afters the closure is evaluated, restrictions are reset.
1316 fn with_res<T>(&mut self, res: Restrictions, f: impl FnOnce(&mut Self) -> T) -> T {
1317 let old = self.restrictions;
1318 self.restrictions = res;
1320 self.restrictions = old;
1324 /// Parses `pub` and `pub(in path)` plus shortcuts `pub(crate)` for `pub(in crate)`, `pub(self)`
1325 /// for `pub(in self)` and `pub(super)` for `pub(in super)`.
1326 /// If the following element can't be a tuple (i.e., it's a function definition), then
1327 /// it's not a tuple struct field), and the contents within the parentheses aren't valid,
1328 /// so emit a proper diagnostic.
1329 // Public for rustfmt usage.
1330 pub fn parse_visibility(&mut self, fbt: FollowedByType) -> PResult<'a, Visibility> {
1331 maybe_whole!(self, NtVis, |x| x.into_inner());
1333 if !self.eat_keyword(kw::Pub) {
1334 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
1335 // keyword to grab a span from for inherited visibility; an empty span at the
1336 // beginning of the current token would seem to be the "Schelling span".
1337 return Ok(Visibility {
1338 span: self.token.span.shrink_to_lo(),
1339 kind: VisibilityKind::Inherited,
1343 let lo = self.prev_token.span;
1345 if self.check(&token::OpenDelim(Delimiter::Parenthesis)) {
1346 // We don't `self.bump()` the `(` yet because this might be a struct definition where
1347 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
1348 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
1349 // by the following tokens.
1350 if self.is_keyword_ahead(1, &[kw::In]) {
1351 // Parse `pub(in path)`.
1353 self.bump(); // `in`
1354 let path = self.parse_path(PathStyle::Mod)?; // `path`
1355 self.expect(&token::CloseDelim(Delimiter::Parenthesis))?; // `)`
1356 let vis = VisibilityKind::Restricted {
1358 id: ast::DUMMY_NODE_ID,
1361 return Ok(Visibility {
1362 span: lo.to(self.prev_token.span),
1366 } else if self.look_ahead(2, |t| t == &token::CloseDelim(Delimiter::Parenthesis))
1367 && self.is_keyword_ahead(1, &[kw::Crate, kw::Super, kw::SelfLower])
1369 // Parse `pub(crate)`, `pub(self)`, or `pub(super)`.
1371 let path = self.parse_path(PathStyle::Mod)?; // `crate`/`super`/`self`
1372 self.expect(&token::CloseDelim(Delimiter::Parenthesis))?; // `)`
1373 let vis = VisibilityKind::Restricted {
1375 id: ast::DUMMY_NODE_ID,
1378 return Ok(Visibility {
1379 span: lo.to(self.prev_token.span),
1383 } else if let FollowedByType::No = fbt {
1384 // Provide this diagnostic if a type cannot follow;
1385 // in particular, if this is not a tuple struct.
1386 self.recover_incorrect_vis_restriction()?;
1387 // Emit diagnostic, but continue with public visibility.
1391 Ok(Visibility { span: lo, kind: VisibilityKind::Public, tokens: None })
1394 /// Recovery for e.g. `pub(something) fn ...` or `struct X { pub(something) y: Z }`
1395 fn recover_incorrect_vis_restriction(&mut self) -> PResult<'a, ()> {
1397 let path = self.parse_path(PathStyle::Mod)?;
1398 self.expect(&token::CloseDelim(Delimiter::Parenthesis))?; // `)`
1400 let path_str = pprust::path_to_string(&path);
1401 self.sess.emit_err(IncorrectVisibilityRestriction { span: path.span, inner_str: path_str });
1406 /// Parses `extern string_literal?`.
1407 fn parse_extern(&mut self) -> Extern {
1408 if self.eat_keyword(kw::Extern) {
1409 let mut extern_span = self.prev_token.span;
1410 let abi = self.parse_abi();
1411 if let Some(abi) = abi {
1412 extern_span = extern_span.to(abi.span);
1414 Extern::from_abi(abi, extern_span)
1420 /// Parses a string literal as an ABI spec.
1421 fn parse_abi(&mut self) -> Option<StrLit> {
1422 match self.parse_str_lit() {
1423 Ok(str_lit) => Some(str_lit),
1424 Err(Some(lit)) => match lit.kind {
1425 ast::LitKind::Err => None,
1427 self.sess.emit_err(NonStringAbiLiteral { span: lit.span });
1435 pub fn collect_tokens_no_attrs<R: HasAttrs + HasTokens>(
1437 f: impl FnOnce(&mut Self) -> PResult<'a, R>,
1438 ) -> PResult<'a, R> {
1439 // The only reason to call `collect_tokens_no_attrs` is if you want tokens, so use
1440 // `ForceCollect::Yes`
1441 self.collect_tokens_trailing_token(
1442 AttrWrapper::empty(),
1444 |this, _attrs| Ok((f(this)?, TrailingToken::None)),
1449 fn is_import_coupler(&mut self) -> bool {
1450 self.check(&token::ModSep)
1451 && self.look_ahead(1, |t| {
1452 *t == token::OpenDelim(Delimiter::Brace) || *t == token::BinOp(token::Star)
1456 pub fn clear_expected_tokens(&mut self) {
1457 self.expected_tokens.clear();
1461 pub(crate) fn make_unclosed_delims_error(
1462 unmatched: UnmatchedBrace,
1464 ) -> Option<DiagnosticBuilder<'_, ErrorGuaranteed>> {
1465 // `None` here means an `Eof` was found. We already emit those errors elsewhere, we add them to
1466 // `unmatched_braces` only for error recovery in the `Parser`.
1467 let found_delim = unmatched.found_delim?;
1468 let mut spans = vec![unmatched.found_span];
1469 if let Some(sp) = unmatched.unclosed_span {
1472 let err = MismatchedClosingDelimiter {
1474 delimiter: pprust::token_kind_to_string(&token::CloseDelim(found_delim)).to_string(),
1475 unmatched: unmatched.found_span,
1476 opening_candidate: unmatched.candidate_span,
1477 unclosed: unmatched.unclosed_span,
1479 .into_diagnostic(&sess.span_diagnostic);
1483 pub fn emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedBrace>, sess: &ParseSess) {
1484 *sess.reached_eof.borrow_mut() |=
1485 unclosed_delims.iter().any(|unmatched_delim| unmatched_delim.found_delim.is_none());
1486 for unmatched in unclosed_delims.drain(..) {
1487 if let Some(mut e) = make_unclosed_delims_error(unmatched, sess) {
1493 /// A helper struct used when building an `AttrTokenStream` from
1494 /// a `LazyAttrTokenStream`. Both delimiter and non-delimited tokens
1495 /// are stored as `FlatToken::Token`. A vector of `FlatToken`s
1496 /// is then 'parsed' to build up an `AttrTokenStream` with nested
1497 /// `AttrTokenTree::Delimited` tokens.
1498 #[derive(Debug, Clone)]
1499 pub enum FlatToken {
1500 /// A token - this holds both delimiter (e.g. '{' and '}')
1501 /// and non-delimiter tokens
1503 /// Holds the `AttributesData` for an AST node. The
1504 /// `AttributesData` is inserted directly into the
1505 /// constructed `AttrTokenStream` as
1506 /// an `AttrTokenTree::Attributes`.
1507 AttrTarget(AttributesData),
1508 /// A special 'empty' token that is ignored during the conversion
1509 /// to an `AttrTokenStream`. This is used to simplify the
1510 /// handling of replace ranges.