13 use crate::lexer::UnmatchedBrace;
14 pub use attr_wrapper::AttrWrapper;
15 pub use diagnostics::AttemptLocalParseRecovery;
16 use diagnostics::Error;
17 pub(crate) use item::FnParseMode;
18 pub use pat::{CommaRecoveryMode, RecoverColon, RecoverComma};
19 pub use path::PathStyle;
21 use rustc_ast::ptr::P;
22 use rustc_ast::token::{self, Delimiter, Nonterminal, Token, TokenKind};
23 use rustc_ast::tokenstream::AttributesData;
24 use rustc_ast::tokenstream::{self, DelimSpan, Spacing};
25 use rustc_ast::tokenstream::{TokenStream, TokenTree};
26 use rustc_ast::AttrId;
27 use rustc_ast::DUMMY_NODE_ID;
28 use rustc_ast::{self as ast, AnonConst, AttrStyle, AttrVec, Const, Extern};
29 use rustc_ast::{Async, Expr, ExprKind, MacArgs, MacArgsEq, MacDelimiter, Mutability, StrLit};
30 use rustc_ast::{HasAttrs, HasTokens, Unsafe, Visibility, VisibilityKind};
31 use rustc_ast_pretty::pprust;
32 use rustc_data_structures::fx::FxHashMap;
33 use rustc_errors::PResult;
35 struct_span_err, Applicability, DiagnosticBuilder, ErrorGuaranteed, FatalError, MultiSpan,
37 use rustc_session::parse::ParseSess;
38 use rustc_span::source_map::{Span, DUMMY_SP};
39 use rustc_span::symbol::{kw, sym, Ident, Symbol};
43 use std::{cmp, mem, slice};
46 struct Restrictions: u8 {
47 const STMT_EXPR = 1 << 0;
48 const NO_STRUCT_LITERAL = 1 << 1;
49 const CONST_EXPR = 1 << 2;
53 #[derive(Clone, Copy, PartialEq, Debug)]
60 #[derive(Clone, Copy, PartialEq, Debug)]
66 /// Whether or not we should force collection of tokens for an AST node,
67 /// regardless of whether or not it has attributes
68 #[derive(Clone, Copy, PartialEq)]
69 pub enum ForceCollect {
74 #[derive(Debug, Eq, PartialEq)]
75 pub enum TrailingToken {
78 /// If the trailing token is a comma, then capture it
79 /// Otherwise, ignore the trailing token
83 /// Like `maybe_whole_expr`, but for things other than expressions.
85 macro_rules! maybe_whole {
86 ($p:expr, $constructor:ident, |$x:ident| $e:expr) => {
87 if let token::Interpolated(nt) = &$p.token.kind {
88 if let token::$constructor(x) = &**nt {
97 /// If the next tokens are ill-formed `$ty::` recover them as `<$ty>::`.
99 macro_rules! maybe_recover_from_interpolated_ty_qpath {
100 ($self: expr, $allow_qpath_recovery: expr) => {
101 if $allow_qpath_recovery
102 && $self.look_ahead(1, |t| t == &token::ModSep)
103 && let token::Interpolated(nt) = &$self.token.kind
104 && let token::NtTy(ty) = &**nt
108 return $self.maybe_recover_from_bad_qpath_stage_2($self.prev_token.span, ty);
114 pub struct Parser<'a> {
115 pub sess: &'a ParseSess,
116 /// The current token.
118 /// The spacing for the current token
119 pub token_spacing: Spacing,
120 /// The previous token.
121 pub prev_token: Token,
122 pub capture_cfg: bool,
123 restrictions: Restrictions,
124 expected_tokens: Vec<TokenType>,
125 // Important: This must only be advanced from `bump` to ensure that
126 // `token_cursor.num_next_calls` is updated properly.
127 token_cursor: TokenCursor,
128 desugar_doc_comments: bool,
129 /// This field is used to keep track of how many left angle brackets we have seen. This is
130 /// required in order to detect extra leading left angle brackets (`<` characters) and error
133 /// See the comments in the `parse_path_segment` function for more details.
134 unmatched_angle_bracket_count: u32,
135 max_angle_bracket_count: u32,
136 /// A list of all unclosed delimiters found by the lexer. If an entry is used for error recovery
137 /// it gets removed from here. Every entry left at the end gets emitted as an independent
139 pub(super) unclosed_delims: Vec<UnmatchedBrace>,
140 last_unexpected_token_span: Option<Span>,
141 /// Span pointing at the `:` for the last type ascription the parser has seen, and whether it
142 /// looked like it could have been a mistyped path or literal `Option:Some(42)`).
143 pub last_type_ascription: Option<(Span, bool /* likely path typo */)>,
144 /// If present, this `Parser` is not parsing Rust code but rather a macro call.
145 subparser_name: Option<&'static str>,
146 capture_state: CaptureState,
147 /// This allows us to recover when the user forget to add braces around
148 /// multiple statements in the closure body.
149 pub current_closure: Option<ClosureSpans>,
150 /// Used to track where `let`s are allowed. For example, `if true && let 1 = 1` is valid
151 /// but `[1, 2, 3][let _ = ()]` is not.
152 let_expr_allowed: bool,
155 // This type is used a lot, e.g. it's cloned when matching many declarative macro rules. Make sure
156 // it doesn't unintentionally get bigger.
157 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
158 rustc_data_structures::static_assert_size!(Parser<'_>, 336);
160 /// Stores span information about a closure.
162 pub struct ClosureSpans {
163 pub whole_closure: Span,
164 pub closing_pipe: Span,
168 /// Indicates a range of tokens that should be replaced by
169 /// the tokens in the provided vector. This is used in two
170 /// places during token collection:
172 /// 1. During the parsing of an AST node that may have a `#[derive]`
173 /// attribute, we parse a nested AST node that has `#[cfg]` or `#[cfg_attr]`
174 /// In this case, we use a `ReplaceRange` to replace the entire inner AST node
175 /// with `FlatToken::AttrTarget`, allowing us to perform eager cfg-expansion
176 /// on an `AttrAnnotatedTokenStream`
178 /// 2. When we parse an inner attribute while collecting tokens. We
179 /// remove inner attributes from the token stream entirely, and
180 /// instead track them through the `attrs` field on the AST node.
181 /// This allows us to easily manipulate them (for example, removing
182 /// the first macro inner attribute to invoke a proc-macro).
183 /// When create a `TokenStream`, the inner attributes get inserted
184 /// into the proper place in the token stream.
185 pub type ReplaceRange = (Range<u32>, Vec<(FlatToken, Spacing)>);
187 /// Controls how we capture tokens. Capturing can be expensive,
188 /// so we try to avoid performing capturing in cases where
189 /// we will never need an `AttrAnnotatedTokenStream`
190 #[derive(Copy, Clone)]
192 /// We aren't performing any capturing - this is the default mode.
194 /// We are capturing tokens
199 struct CaptureState {
200 capturing: Capturing,
201 replace_ranges: Vec<ReplaceRange>,
202 inner_attr_ranges: FxHashMap<AttrId, ReplaceRange>,
205 impl<'a> Drop for Parser<'a> {
207 emit_unclosed_delims(&mut self.unclosed_delims, &self.sess);
213 // The current (innermost) frame. `frame` and `stack` could be combined,
214 // but it's faster to have them separately to access `frame` directly
215 // rather than via something like `stack.last().unwrap()` or
216 // `stack[stack.len() - 1]`.
217 frame: TokenCursorFrame,
218 // Additional frames that enclose `frame`.
219 stack: Vec<TokenCursorFrame>,
220 desugar_doc_comments: bool,
221 // Counts the number of calls to `{,inlined_}next`.
222 num_next_calls: usize,
223 // During parsing, we may sometimes need to 'unglue' a
224 // glued token into two component tokens
225 // (e.g. '>>' into '>' and '>), so that the parser
226 // can consume them one at a time. This process
227 // bypasses the normal capturing mechanism
228 // (e.g. `num_next_calls` will not be incremented),
229 // since the 'unglued' tokens due not exist in
230 // the original `TokenStream`.
232 // If we end up consuming both unglued tokens,
233 // then this is not an issue - we'll end up
234 // capturing the single 'glued' token.
236 // However, in certain circumstances, we may
237 // want to capture just the first 'unglued' token.
238 // For example, capturing the `Vec<u8>`
239 // in `Option<Vec<u8>>` requires us to unglue
240 // the trailing `>>` token. The `break_last_token`
241 // field is used to track this token - it gets
242 // appended to the captured stream when
243 // we evaluate a `LazyTokenStream`
244 break_last_token: bool,
248 struct TokenCursorFrame {
249 delim_sp: Option<(Delimiter, DelimSpan)>,
250 tree_cursor: tokenstream::Cursor,
253 impl TokenCursorFrame {
254 fn new(delim_sp: Option<(Delimiter, DelimSpan)>, tts: TokenStream) -> Self {
255 TokenCursorFrame { delim_sp, tree_cursor: tts.into_trees() }
260 fn next(&mut self, desugar_doc_comments: bool) -> (Token, Spacing) {
261 self.inlined_next(desugar_doc_comments)
264 /// This always-inlined version should only be used on hot code paths.
266 fn inlined_next(&mut self, desugar_doc_comments: bool) -> (Token, Spacing) {
268 // FIXME: we currently don't return `Delimiter` open/close delims. To fix #67062 we will
269 // need to, whereupon the `delim != Delimiter::Invisible` conditions below can be
271 if let Some((tree, spacing)) = self.frame.tree_cursor.next_with_spacing_ref() {
273 &TokenTree::Token(ref token) => match (desugar_doc_comments, token) {
274 (true, &Token { kind: token::DocComment(_, attr_style, data), span }) => {
275 return self.desugar(attr_style, data, span);
277 _ => return (token.clone(), *spacing),
279 &TokenTree::Delimited(sp, delim, ref tts) => {
280 // Set `open_delim` to true here because we deal with it immediately.
281 let frame = TokenCursorFrame::new(Some((delim, sp)), tts.clone());
282 self.stack.push(mem::replace(&mut self.frame, frame));
283 if delim != Delimiter::Invisible {
284 return (Token::new(token::OpenDelim(delim), sp.open), Spacing::Alone);
286 // No open delimeter to return; continue on to the next iteration.
289 } else if let Some(frame) = self.stack.pop() {
290 if let Some((delim, span)) = self.frame.delim_sp && delim != Delimiter::Invisible {
292 return (Token::new(token::CloseDelim(delim), span.close), Spacing::Alone);
295 // No close delimiter to return; continue on to the next iteration.
297 return (Token::new(token::Eof, DUMMY_SP), Spacing::Alone);
302 fn desugar(&mut self, attr_style: AttrStyle, data: Symbol, span: Span) -> (Token, Spacing) {
303 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
304 // required to wrap the text.
305 let mut num_of_hashes = 0;
307 for ch in data.as_str().chars() {
310 '#' if count > 0 => count + 1,
313 num_of_hashes = cmp::max(num_of_hashes, count);
316 let delim_span = DelimSpan::from_single(span);
317 let body = TokenTree::Delimited(
321 TokenTree::token(token::Ident(sym::doc, false), span),
322 TokenTree::token(token::Eq, span),
323 TokenTree::token(TokenKind::lit(token::StrRaw(num_of_hashes), data, None), span),
327 .collect::<TokenStream>(),
330 self.stack.push(mem::replace(
332 TokenCursorFrame::new(
334 if attr_style == AttrStyle::Inner {
335 [TokenTree::token(token::Pound, span), TokenTree::token(token::Not, span), body]
338 .collect::<TokenStream>()
340 [TokenTree::token(token::Pound, span), body]
343 .collect::<TokenStream>()
348 self.next(/* desugar_doc_comments */ false)
352 #[derive(Debug, Clone, PartialEq)]
365 fn to_string(&self) -> String {
367 TokenType::Token(ref t) => format!("`{}`", pprust::token_kind_to_string(t)),
368 TokenType::Keyword(kw) => format!("`{}`", kw),
369 TokenType::Operator => "an operator".to_string(),
370 TokenType::Lifetime => "lifetime".to_string(),
371 TokenType::Ident => "identifier".to_string(),
372 TokenType::Path => "path".to_string(),
373 TokenType::Type => "type".to_string(),
374 TokenType::Const => "a const expression".to_string(),
379 #[derive(Copy, Clone, Debug)]
380 enum TokenExpectType {
385 /// A sequence separator.
387 /// The separator token.
388 sep: Option<TokenKind>,
389 /// `true` if a trailing separator is allowed.
390 trailing_sep_allowed: bool,
394 fn trailing_allowed(t: TokenKind) -> SeqSep {
395 SeqSep { sep: Some(t), trailing_sep_allowed: true }
398 fn none() -> SeqSep {
399 SeqSep { sep: None, trailing_sep_allowed: false }
403 pub enum FollowedByType {
408 fn token_descr_opt(token: &Token) -> Option<&'static str> {
409 Some(match token.kind {
410 _ if token.is_special_ident() => "reserved identifier",
411 _ if token.is_used_keyword() => "keyword",
412 _ if token.is_unused_keyword() => "reserved keyword",
413 token::DocComment(..) => "doc comment",
418 pub(super) fn token_descr(token: &Token) -> String {
419 let token_str = pprust::token_to_string(token);
420 match token_descr_opt(token) {
421 Some(prefix) => format!("{} `{}`", prefix, token_str),
422 _ => format!("`{}`", token_str),
426 impl<'a> Parser<'a> {
430 desugar_doc_comments: bool,
431 subparser_name: Option<&'static str>,
433 let mut parser = Parser {
435 token: Token::dummy(),
436 token_spacing: Spacing::Alone,
437 prev_token: Token::dummy(),
439 restrictions: Restrictions::empty(),
440 expected_tokens: Vec::new(),
441 token_cursor: TokenCursor {
442 frame: TokenCursorFrame::new(None, tokens),
445 desugar_doc_comments,
446 break_last_token: false,
448 desugar_doc_comments,
449 unmatched_angle_bracket_count: 0,
450 max_angle_bracket_count: 0,
451 unclosed_delims: Vec::new(),
452 last_unexpected_token_span: None,
453 last_type_ascription: None,
455 capture_state: CaptureState {
456 capturing: Capturing::No,
457 replace_ranges: Vec::new(),
458 inner_attr_ranges: Default::default(),
460 current_closure: None,
461 let_expr_allowed: false,
464 // Make parser point to the first token.
470 pub fn unexpected<T>(&mut self) -> PResult<'a, T> {
471 match self.expect_one_of(&[], &[]) {
473 // We can get `Ok(true)` from `recover_closing_delimiter`
474 // which is called in `expected_one_of_not_found`.
475 Ok(_) => FatalError.raise(),
479 /// Expects and consumes the token `t`. Signals an error if the next token is not `t`.
480 pub fn expect(&mut self, t: &TokenKind) -> PResult<'a, bool /* recovered */> {
481 if self.expected_tokens.is_empty() {
482 if self.token == *t {
486 self.unexpected_try_recover(t)
489 self.expect_one_of(slice::from_ref(t), &[])
493 /// Expect next token to be edible or inedible token. If edible,
494 /// then consume it; if inedible, then return without consuming
495 /// anything. Signal a fatal error if next token is unexpected.
496 pub fn expect_one_of(
498 edible: &[TokenKind],
499 inedible: &[TokenKind],
500 ) -> PResult<'a, bool /* recovered */> {
501 if edible.contains(&self.token.kind) {
504 } else if inedible.contains(&self.token.kind) {
505 // leave it in the input
507 } else if self.last_unexpected_token_span == Some(self.token.span) {
510 self.expected_one_of_not_found(edible, inedible)
514 // Public for rustfmt usage.
515 pub fn parse_ident(&mut self) -> PResult<'a, Ident> {
516 self.parse_ident_common(true)
519 fn ident_or_err(&mut self) -> PResult<'a, (Ident, /* is_raw */ bool)> {
520 self.token.ident().ok_or_else(|| match self.prev_token.kind {
521 TokenKind::DocComment(..) => {
522 self.span_err(self.prev_token.span, Error::UselessDocComment)
524 _ => self.expected_ident_found(),
528 fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, Ident> {
529 let (ident, is_raw) = self.ident_or_err()?;
530 if !is_raw && ident.is_reserved() {
531 let mut err = self.expected_ident_found();
542 /// Checks if the next token is `tok`, and returns `true` if so.
544 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
546 fn check(&mut self, tok: &TokenKind) -> bool {
547 let is_present = self.token == *tok;
549 self.expected_tokens.push(TokenType::Token(tok.clone()));
554 fn check_noexpect(&self, tok: &TokenKind) -> bool {
558 /// Consumes a token 'tok' if it exists. Returns whether the given token was present.
560 /// the main purpose of this function is to reduce the cluttering of the suggestions list
561 /// which using the normal eat method could introduce in some cases.
562 pub fn eat_noexpect(&mut self, tok: &TokenKind) -> bool {
563 let is_present = self.check_noexpect(tok);
570 /// Consumes a token 'tok' if it exists. Returns whether the given token was present.
571 pub fn eat(&mut self, tok: &TokenKind) -> bool {
572 let is_present = self.check(tok);
579 /// If the next token is the given keyword, returns `true` without eating it.
580 /// An expectation is also added for diagnostics purposes.
581 fn check_keyword(&mut self, kw: Symbol) -> bool {
582 self.expected_tokens.push(TokenType::Keyword(kw));
583 self.token.is_keyword(kw)
586 /// If the next token is the given keyword, eats it and returns `true`.
587 /// Otherwise, returns `false`. An expectation is also added for diagnostics purposes.
588 // Public for rustfmt usage.
589 pub fn eat_keyword(&mut self, kw: Symbol) -> bool {
590 if self.check_keyword(kw) {
598 fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool {
599 if self.token.is_keyword(kw) {
607 /// If the given word is not a keyword, signals an error.
608 /// If the next token is not the given word, signals an error.
609 /// Otherwise, eats it.
610 fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> {
611 if !self.eat_keyword(kw) { self.unexpected() } else { Ok(()) }
614 /// Is the given keyword `kw` followed by a non-reserved identifier?
615 fn is_kw_followed_by_ident(&self, kw: Symbol) -> bool {
616 self.token.is_keyword(kw) && self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
619 fn check_or_expected(&mut self, ok: bool, typ: TokenType) -> bool {
623 self.expected_tokens.push(typ);
628 fn check_ident(&mut self) -> bool {
629 self.check_or_expected(self.token.is_ident(), TokenType::Ident)
632 fn check_path(&mut self) -> bool {
633 self.check_or_expected(self.token.is_path_start(), TokenType::Path)
636 fn check_type(&mut self) -> bool {
637 self.check_or_expected(self.token.can_begin_type(), TokenType::Type)
640 fn check_const_arg(&mut self) -> bool {
641 self.check_or_expected(self.token.can_begin_const_arg(), TokenType::Const)
644 fn check_inline_const(&self, dist: usize) -> bool {
645 self.is_keyword_ahead(dist, &[kw::Const])
646 && self.look_ahead(dist + 1, |t| match t.kind {
647 token::Interpolated(ref nt) => matches!(**nt, token::NtBlock(..)),
648 token::OpenDelim(Delimiter::Brace) => true,
653 /// Checks to see if the next token is either `+` or `+=`.
654 /// Otherwise returns `false`.
655 fn check_plus(&mut self) -> bool {
656 self.check_or_expected(
657 self.token.is_like_plus(),
658 TokenType::Token(token::BinOp(token::Plus)),
662 /// Eats the expected token if it's present possibly breaking
663 /// compound tokens like multi-character operators in process.
664 /// Returns `true` if the token was eaten.
665 fn break_and_eat(&mut self, expected: TokenKind) -> bool {
666 if self.token.kind == expected {
670 match self.token.kind.break_two_token_op() {
671 Some((first, second)) if first == expected => {
672 let first_span = self.sess.source_map().start_point(self.token.span);
673 let second_span = self.token.span.with_lo(first_span.hi());
674 self.token = Token::new(first, first_span);
675 // Keep track of this token - if we end token capturing now,
676 // we'll want to append this token to the captured stream.
678 // If we consume any additional tokens, then this token
679 // is not needed (we'll capture the entire 'glued' token),
680 // and `bump` will set this field to `None`
681 self.token_cursor.break_last_token = true;
682 // Use the spacing of the glued token as the spacing
683 // of the unglued second token.
684 self.bump_with((Token::new(second, second_span), self.token_spacing));
688 self.expected_tokens.push(TokenType::Token(expected));
694 /// Eats `+` possibly breaking tokens like `+=` in process.
695 fn eat_plus(&mut self) -> bool {
696 self.break_and_eat(token::BinOp(token::Plus))
699 /// Eats `&` possibly breaking tokens like `&&` in process.
700 /// Signals an error if `&` is not eaten.
701 fn expect_and(&mut self) -> PResult<'a, ()> {
702 if self.break_and_eat(token::BinOp(token::And)) { Ok(()) } else { self.unexpected() }
705 /// Eats `|` possibly breaking tokens like `||` in process.
706 /// Signals an error if `|` was not eaten.
707 fn expect_or(&mut self) -> PResult<'a, ()> {
708 if self.break_and_eat(token::BinOp(token::Or)) { Ok(()) } else { self.unexpected() }
711 /// Eats `<` possibly breaking tokens like `<<` in process.
712 fn eat_lt(&mut self) -> bool {
713 let ate = self.break_and_eat(token::Lt);
715 // See doc comment for `unmatched_angle_bracket_count`.
716 self.unmatched_angle_bracket_count += 1;
717 self.max_angle_bracket_count += 1;
718 debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count);
723 /// Eats `<` possibly breaking tokens like `<<` in process.
724 /// Signals an error if `<` was not eaten.
725 fn expect_lt(&mut self) -> PResult<'a, ()> {
726 if self.eat_lt() { Ok(()) } else { self.unexpected() }
729 /// Eats `>` possibly breaking tokens like `>>` in process.
730 /// Signals an error if `>` was not eaten.
731 fn expect_gt(&mut self) -> PResult<'a, ()> {
732 if self.break_and_eat(token::Gt) {
733 // See doc comment for `unmatched_angle_bracket_count`.
734 if self.unmatched_angle_bracket_count > 0 {
735 self.unmatched_angle_bracket_count -= 1;
736 debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count);
744 fn expect_any_with_type(&mut self, kets: &[&TokenKind], expect: TokenExpectType) -> bool {
745 kets.iter().any(|k| match expect {
746 TokenExpectType::Expect => self.check(k),
747 TokenExpectType::NoExpect => self.token == **k,
751 fn parse_seq_to_before_tokens<T>(
755 expect: TokenExpectType,
756 mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
757 ) -> PResult<'a, (Vec<T>, bool /* trailing */, bool /* recovered */)> {
758 let mut first = true;
759 let mut recovered = false;
760 let mut trailing = false;
762 let unclosed_delims = !self.unclosed_delims.is_empty();
764 while !self.expect_any_with_type(kets, expect) {
765 if let token::CloseDelim(..) | token::Eof = self.token.kind {
768 if let Some(ref t) = sep.sep {
772 match self.expect(t) {
774 self.current_closure.take();
777 self.current_closure.take();
781 Err(mut expect_err) => {
782 let sp = self.prev_token.span.shrink_to_hi();
783 let token_str = pprust::token_kind_to_string(t);
785 match self.current_closure.take() {
786 Some(closure_spans) if self.token.kind == TokenKind::Semi => {
787 // Finding a semicolon instead of a comma
788 // after a closure body indicates that the
789 // closure body may be a block but the user
790 // forgot to put braces around its
793 self.recover_missing_braces_around_closure_body(
802 // Attempt to keep parsing if it was a similar separator.
803 if let Some(ref tokens) = t.similar_tokens() {
804 if tokens.contains(&self.token.kind) && !unclosed_delims {
811 // If this was a missing `@` in a binding pattern
812 // bail with a suggestion
813 // https://github.com/rust-lang/rust/issues/72373
814 if self.prev_token.is_ident() && self.token.kind == token::DotDot {
816 "if you meant to bind the contents of \
817 the rest of the array pattern into `{}`, use `@`",
818 pprust::token_to_string(&self.prev_token)
821 .span_suggestion_verbose(
822 self.prev_token.span.shrink_to_hi().until(self.token.span),
825 Applicability::MaybeIncorrect,
831 // Attempt to keep parsing if it was an omitted separator.
834 // Parsed successfully, therefore most probably the code only
835 // misses a separator.
837 .span_suggestion_short(
839 &format!("missing `{}`", token_str),
841 Applicability::MaybeIncorrect,
849 // Parsing failed, therefore it must be something more serious
850 // than just a missing separator.
861 if sep.trailing_sep_allowed && self.expect_any_with_type(kets, expect) {
870 Ok((v, trailing, recovered))
873 fn recover_missing_braces_around_closure_body(
875 closure_spans: ClosureSpans,
876 mut expect_err: DiagnosticBuilder<'_, ErrorGuaranteed>,
877 ) -> PResult<'a, ()> {
878 let initial_semicolon = self.token.span;
880 while self.eat(&TokenKind::Semi) {
881 let _ = self.parse_stmt(ForceCollect::Yes)?;
884 expect_err.set_primary_message(
885 "closure bodies that contain statements must be surrounded by braces",
888 let preceding_pipe_span = closure_spans.closing_pipe;
889 let following_token_span = self.token.span;
891 let mut first_note = MultiSpan::from(vec![initial_semicolon]);
892 first_note.push_span_label(
894 "this `;` turns the preceding closure into a statement".to_string(),
896 first_note.push_span_label(
898 "this expression is a statement because of the trailing semicolon".to_string(),
900 expect_err.span_note(first_note, "statement found outside of a block");
902 let mut second_note = MultiSpan::from(vec![closure_spans.whole_closure]);
903 second_note.push_span_label(
904 closure_spans.whole_closure,
905 "this is the parsed closure...".to_string(),
907 second_note.push_span_label(
908 following_token_span,
909 "...but likely you meant the closure to end here".to_string(),
911 expect_err.span_note(second_note, "the closure body may be incorrectly delimited");
913 expect_err.set_span(vec![preceding_pipe_span, following_token_span]);
915 let opening_suggestion_str = " {".to_string();
916 let closing_suggestion_str = "}".to_string();
918 expect_err.multipart_suggestion(
921 (preceding_pipe_span.shrink_to_hi(), opening_suggestion_str),
922 (following_token_span.shrink_to_lo(), closing_suggestion_str),
924 Applicability::MaybeIncorrect,
932 /// Parses a sequence, not including the closing delimiter. The function
933 /// `f` must consume tokens until reaching the next separator or
935 fn parse_seq_to_before_end<T>(
939 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
940 ) -> PResult<'a, (Vec<T>, bool, bool)> {
941 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
944 /// Parses a sequence, including the closing delimiter. The function
945 /// `f` must consume tokens until reaching the next separator or
947 fn parse_seq_to_end<T>(
951 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
952 ) -> PResult<'a, (Vec<T>, bool /* trailing */)> {
953 let (val, trailing, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
960 /// Parses a sequence, including the closing delimiter. The function
961 /// `f` must consume tokens until reaching the next separator or
963 fn parse_unspanned_seq<T>(
968 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
969 ) -> PResult<'a, (Vec<T>, bool)> {
971 self.parse_seq_to_end(ket, sep, f)
974 fn parse_delim_comma_seq<T>(
977 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
978 ) -> PResult<'a, (Vec<T>, bool)> {
979 self.parse_unspanned_seq(
980 &token::OpenDelim(delim),
981 &token::CloseDelim(delim),
982 SeqSep::trailing_allowed(token::Comma),
987 fn parse_paren_comma_seq<T>(
989 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
990 ) -> PResult<'a, (Vec<T>, bool)> {
991 self.parse_delim_comma_seq(Delimiter::Parenthesis, f)
994 /// Advance the parser by one token using provided token as the next one.
995 fn bump_with(&mut self, next: (Token, Spacing)) {
996 self.inlined_bump_with(next)
999 /// This always-inlined version should only be used on hot code paths.
1001 fn inlined_bump_with(&mut self, (next_token, next_spacing): (Token, Spacing)) {
1002 // Update the current and previous tokens.
1003 self.prev_token = mem::replace(&mut self.token, next_token);
1004 self.token_spacing = next_spacing;
1007 self.expected_tokens.clear();
1010 /// Advance the parser by one token.
1011 pub fn bump(&mut self) {
1012 // Note: destructuring here would give nicer code, but it was found in #96210 to be slower
1013 // than `.0`/`.1` access.
1014 let mut next = self.token_cursor.inlined_next(self.desugar_doc_comments);
1015 self.token_cursor.num_next_calls += 1;
1016 // We've retrieved an token from the underlying
1017 // cursor, so we no longer need to worry about
1018 // an unglued token. See `break_and_eat` for more details
1019 self.token_cursor.break_last_token = false;
1020 if next.0.span.is_dummy() {
1021 // Tweak the location for better diagnostics, but keep syntactic context intact.
1022 let fallback_span = self.token.span;
1023 next.0.span = fallback_span.with_ctxt(next.0.span.ctxt());
1025 debug_assert!(!matches!(
1027 token::OpenDelim(Delimiter::Invisible) | token::CloseDelim(Delimiter::Invisible)
1029 self.inlined_bump_with(next)
1032 /// Look-ahead `dist` tokens of `self.token` and get access to that token there.
1033 /// When `dist == 0` then the current token is looked at.
1034 pub fn look_ahead<R>(&self, dist: usize, looker: impl FnOnce(&Token) -> R) -> R {
1036 return looker(&self.token);
1039 let frame = &self.token_cursor.frame;
1040 if let Some((delim, span)) = frame.delim_sp && delim != Delimiter::Invisible {
1041 let all_normal = (0..dist).all(|i| {
1042 let token = frame.tree_cursor.look_ahead(i);
1043 !matches!(token, Some(TokenTree::Delimited(_, Delimiter::Invisible, _)))
1046 return match frame.tree_cursor.look_ahead(dist - 1) {
1047 Some(tree) => match tree {
1048 TokenTree::Token(token) => looker(token),
1049 TokenTree::Delimited(dspan, delim, _) => {
1050 looker(&Token::new(token::OpenDelim(*delim), dspan.open))
1053 None => looker(&Token::new(token::CloseDelim(delim), span.close)),
1058 let mut cursor = self.token_cursor.clone();
1060 let mut token = Token::dummy();
1062 token = cursor.next(/* desugar_doc_comments */ false).0;
1065 token::OpenDelim(Delimiter::Invisible) | token::CloseDelim(Delimiter::Invisible)
1071 return looker(&token);
1074 /// Returns whether any of the given keywords are `dist` tokens ahead of the current one.
1075 fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool {
1076 self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw)))
1079 /// Parses asyncness: `async` or nothing.
1080 fn parse_asyncness(&mut self) -> Async {
1081 if self.eat_keyword(kw::Async) {
1082 let span = self.prev_token.uninterpolated_span();
1083 Async::Yes { span, closure_id: DUMMY_NODE_ID, return_impl_trait_id: DUMMY_NODE_ID }
1089 /// Parses unsafety: `unsafe` or nothing.
1090 fn parse_unsafety(&mut self) -> Unsafe {
1091 if self.eat_keyword(kw::Unsafe) {
1092 Unsafe::Yes(self.prev_token.uninterpolated_span())
1098 /// Parses constness: `const` or nothing.
1099 fn parse_constness(&mut self) -> Const {
1100 // Avoid const blocks to be parsed as const items
1101 if self.look_ahead(1, |t| t != &token::OpenDelim(Delimiter::Brace))
1102 && self.eat_keyword(kw::Const)
1104 Const::Yes(self.prev_token.uninterpolated_span())
1110 /// Parses inline const expressions.
1111 fn parse_const_block(&mut self, span: Span, pat: bool) -> PResult<'a, P<Expr>> {
1113 self.sess.gated_spans.gate(sym::inline_const_pat, span);
1115 self.sess.gated_spans.gate(sym::inline_const, span);
1117 self.eat_keyword(kw::Const);
1118 let (attrs, blk) = self.parse_inner_attrs_and_block()?;
1119 let anon_const = AnonConst {
1121 value: self.mk_expr(blk.span, ExprKind::Block(blk, None), AttrVec::new()),
1123 let blk_span = anon_const.value.span;
1124 Ok(self.mk_expr(span.to(blk_span), ExprKind::ConstBlock(anon_const), AttrVec::from(attrs)))
1127 /// Parses mutability (`mut` or nothing).
1128 fn parse_mutability(&mut self) -> Mutability {
1129 if self.eat_keyword(kw::Mut) { Mutability::Mut } else { Mutability::Not }
1132 /// Possibly parses mutability (`const` or `mut`).
1133 fn parse_const_or_mut(&mut self) -> Option<Mutability> {
1134 if self.eat_keyword(kw::Mut) {
1135 Some(Mutability::Mut)
1136 } else if self.eat_keyword(kw::Const) {
1137 Some(Mutability::Not)
1143 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
1144 if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) = self.token.kind
1146 self.expect_no_suffix(self.token.span, "a tuple index", suffix);
1148 Ok(Ident::new(symbol, self.prev_token.span))
1150 self.parse_ident_common(true)
1154 fn parse_mac_args(&mut self) -> PResult<'a, P<MacArgs>> {
1155 self.parse_mac_args_common(true).map(P)
1158 fn parse_attr_args(&mut self) -> PResult<'a, MacArgs> {
1159 self.parse_mac_args_common(false)
1162 fn parse_mac_args_common(&mut self, delimited_only: bool) -> PResult<'a, MacArgs> {
1164 if self.check(&token::OpenDelim(Delimiter::Parenthesis))
1165 || self.check(&token::OpenDelim(Delimiter::Bracket))
1166 || self.check(&token::OpenDelim(Delimiter::Brace))
1168 match self.parse_token_tree() {
1169 TokenTree::Delimited(dspan, delim, tokens) =>
1170 // We've confirmed above that there is a delimiter so unwrapping is OK.
1172 MacArgs::Delimited(dspan, MacDelimiter::from_token(delim).unwrap(), tokens)
1174 _ => unreachable!(),
1176 } else if !delimited_only {
1177 if self.eat(&token::Eq) {
1178 let eq_span = self.prev_token.span;
1179 MacArgs::Eq(eq_span, MacArgsEq::Ast(self.parse_expr_force_collect()?))
1184 return self.unexpected();
1189 fn parse_or_use_outer_attributes(
1191 already_parsed_attrs: Option<AttrWrapper>,
1192 ) -> PResult<'a, AttrWrapper> {
1193 if let Some(attrs) = already_parsed_attrs {
1196 self.parse_outer_attributes()
1200 /// Parses a single token tree from the input.
1201 pub(crate) fn parse_token_tree(&mut self) -> TokenTree {
1202 match self.token.kind {
1203 token::OpenDelim(..) => {
1204 // Grab the tokens from this frame.
1205 let frame = &self.token_cursor.frame;
1206 let stream = frame.tree_cursor.stream.clone();
1207 let (delim, span) = frame.delim_sp.unwrap();
1209 // Advance the token cursor through the entire delimited
1210 // sequence. After getting the `OpenDelim` we are *within* the
1211 // delimited sequence, i.e. at depth `d`. After getting the
1212 // matching `CloseDelim` we are *after* the delimited sequence,
1213 // i.e. at depth `d - 1`.
1214 let target_depth = self.token_cursor.stack.len() - 1;
1216 // Advance one token at a time, so `TokenCursor::next()`
1217 // can capture these tokens if necessary.
1219 if self.token_cursor.stack.len() == target_depth {
1220 debug_assert!(matches!(self.token.kind, token::CloseDelim(_)));
1225 // Consume close delimiter
1227 TokenTree::Delimited(span, delim, stream)
1229 token::CloseDelim(_) | token::Eof => unreachable!(),
1232 TokenTree::Token(self.prev_token.clone())
1237 /// Parses a stream of tokens into a list of `TokenTree`s, up to EOF.
1238 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
1239 let mut tts = Vec::new();
1240 while self.token != token::Eof {
1241 tts.push(self.parse_token_tree());
1246 pub fn parse_tokens(&mut self) -> TokenStream {
1247 let mut result = Vec::new();
1249 match self.token.kind {
1250 token::Eof | token::CloseDelim(..) => break,
1251 _ => result.push(self.parse_token_tree().into()),
1254 TokenStream::new(result)
1257 /// Evaluates the closure with restrictions in place.
1259 /// Afters the closure is evaluated, restrictions are reset.
1260 fn with_res<T>(&mut self, res: Restrictions, f: impl FnOnce(&mut Self) -> T) -> T {
1261 let old = self.restrictions;
1262 self.restrictions = res;
1264 self.restrictions = old;
1268 /// Parses `pub` and `pub(in path)` plus shortcuts `pub(crate)` for `pub(in crate)`, `pub(self)`
1269 /// for `pub(in self)` and `pub(super)` for `pub(in super)`.
1270 /// If the following element can't be a tuple (i.e., it's a function definition), then
1271 /// it's not a tuple struct field), and the contents within the parentheses aren't valid,
1272 /// so emit a proper diagnostic.
1273 // Public for rustfmt usage.
1274 pub fn parse_visibility(&mut self, fbt: FollowedByType) -> PResult<'a, Visibility> {
1275 maybe_whole!(self, NtVis, |x| x.into_inner());
1277 if !self.eat_keyword(kw::Pub) {
1278 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
1279 // keyword to grab a span from for inherited visibility; an empty span at the
1280 // beginning of the current token would seem to be the "Schelling span".
1281 return Ok(Visibility {
1282 span: self.token.span.shrink_to_lo(),
1283 kind: VisibilityKind::Inherited,
1287 let lo = self.prev_token.span;
1289 if self.check(&token::OpenDelim(Delimiter::Parenthesis)) {
1290 // We don't `self.bump()` the `(` yet because this might be a struct definition where
1291 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
1292 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
1293 // by the following tokens.
1294 if self.is_keyword_ahead(1, &[kw::In]) {
1295 // Parse `pub(in path)`.
1297 self.bump(); // `in`
1298 let path = self.parse_path(PathStyle::Mod)?; // `path`
1299 self.expect(&token::CloseDelim(Delimiter::Parenthesis))?; // `)`
1300 let vis = VisibilityKind::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
1301 return Ok(Visibility {
1302 span: lo.to(self.prev_token.span),
1306 } else if self.look_ahead(2, |t| t == &token::CloseDelim(Delimiter::Parenthesis))
1307 && self.is_keyword_ahead(1, &[kw::Crate, kw::Super, kw::SelfLower])
1309 // Parse `pub(crate)`, `pub(self)`, or `pub(super)`.
1311 let path = self.parse_path(PathStyle::Mod)?; // `crate`/`super`/`self`
1312 self.expect(&token::CloseDelim(Delimiter::Parenthesis))?; // `)`
1313 let vis = VisibilityKind::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
1314 return Ok(Visibility {
1315 span: lo.to(self.prev_token.span),
1319 } else if let FollowedByType::No = fbt {
1320 // Provide this diagnostic if a type cannot follow;
1321 // in particular, if this is not a tuple struct.
1322 self.recover_incorrect_vis_restriction()?;
1323 // Emit diagnostic, but continue with public visibility.
1327 Ok(Visibility { span: lo, kind: VisibilityKind::Public, tokens: None })
1330 /// Recovery for e.g. `pub(something) fn ...` or `struct X { pub(something) y: Z }`
1331 fn recover_incorrect_vis_restriction(&mut self) -> PResult<'a, ()> {
1333 let path = self.parse_path(PathStyle::Mod)?;
1334 self.expect(&token::CloseDelim(Delimiter::Parenthesis))?; // `)`
1336 let msg = "incorrect visibility restriction";
1337 let suggestion = r##"some possible visibility restrictions are:
1338 `pub(crate)`: visible only on the current crate
1339 `pub(super)`: visible only in the current module's parent
1340 `pub(in path::to::module)`: visible only on the specified path"##;
1342 let path_str = pprust::path_to_string(&path);
1344 struct_span_err!(self.sess.span_diagnostic, path.span, E0704, "{}", msg)
1348 &format!("make this visible only to module `{}` with `in`", path_str),
1349 format!("in {}", path_str),
1350 Applicability::MachineApplicable,
1357 /// Parses `extern string_literal?`.
1358 fn parse_extern(&mut self) -> Extern {
1359 if self.eat_keyword(kw::Extern) { Extern::from_abi(self.parse_abi()) } else { Extern::None }
1362 /// Parses a string literal as an ABI spec.
1363 fn parse_abi(&mut self) -> Option<StrLit> {
1364 match self.parse_str_lit() {
1365 Ok(str_lit) => Some(str_lit),
1366 Err(Some(lit)) => match lit.kind {
1367 ast::LitKind::Err(_) => None,
1369 self.struct_span_err(lit.span, "non-string ABI literal")
1372 "specify the ABI with a string literal",
1374 Applicability::MaybeIncorrect,
1384 pub fn collect_tokens_no_attrs<R: HasAttrs + HasTokens>(
1386 f: impl FnOnce(&mut Self) -> PResult<'a, R>,
1387 ) -> PResult<'a, R> {
1388 // The only reason to call `collect_tokens_no_attrs` is if you want tokens, so use
1389 // `ForceCollect::Yes`
1390 self.collect_tokens_trailing_token(
1391 AttrWrapper::empty(),
1393 |this, _attrs| Ok((f(this)?, TrailingToken::None)),
1398 fn is_import_coupler(&mut self) -> bool {
1399 self.check(&token::ModSep)
1400 && self.look_ahead(1, |t| {
1401 *t == token::OpenDelim(Delimiter::Brace) || *t == token::BinOp(token::Star)
1405 pub fn clear_expected_tokens(&mut self) {
1406 self.expected_tokens.clear();
1410 pub(crate) fn make_unclosed_delims_error(
1411 unmatched: UnmatchedBrace,
1413 ) -> Option<DiagnosticBuilder<'_, ErrorGuaranteed>> {
1414 // `None` here means an `Eof` was found. We already emit those errors elsewhere, we add them to
1415 // `unmatched_braces` only for error recovery in the `Parser`.
1416 let found_delim = unmatched.found_delim?;
1417 let span: MultiSpan = if let Some(sp) = unmatched.unclosed_span {
1418 vec![unmatched.found_span, sp].into()
1420 unmatched.found_span.into()
1422 let mut err = sess.span_diagnostic.struct_span_err(
1425 "mismatched closing delimiter: `{}`",
1426 pprust::token_kind_to_string(&token::CloseDelim(found_delim)),
1429 err.span_label(unmatched.found_span, "mismatched closing delimiter");
1430 if let Some(sp) = unmatched.candidate_span {
1431 err.span_label(sp, "closing delimiter possibly meant for this");
1433 if let Some(sp) = unmatched.unclosed_span {
1434 err.span_label(sp, "unclosed delimiter");
1439 pub fn emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedBrace>, sess: &ParseSess) {
1440 *sess.reached_eof.borrow_mut() |=
1441 unclosed_delims.iter().any(|unmatched_delim| unmatched_delim.found_delim.is_none());
1442 for unmatched in unclosed_delims.drain(..) {
1443 if let Some(mut e) = make_unclosed_delims_error(unmatched, sess) {
1449 /// A helper struct used when building an `AttrAnnotatedTokenStream` from
1450 /// a `LazyTokenStream`. Both delimiter and non-delimited tokens
1451 /// are stored as `FlatToken::Token`. A vector of `FlatToken`s
1452 /// is then 'parsed' to build up an `AttrAnnotatedTokenStream` with nested
1453 /// `AttrAnnotatedTokenTree::Delimited` tokens
1454 #[derive(Debug, Clone)]
1455 pub enum FlatToken {
1456 /// A token - this holds both delimiter (e.g. '{' and '}')
1457 /// and non-delimiter tokens
1459 /// Holds the `AttributesData` for an AST node. The
1460 /// `AttributesData` is inserted directly into the
1461 /// constructed `AttrAnnotatedTokenStream` as
1462 /// an `AttrAnnotatedTokenTree::Attributes`
1463 AttrTarget(AttributesData),
1464 /// A special 'empty' token that is ignored during the conversion
1465 /// to an `AttrAnnotatedTokenStream`. This is used to simplify the
1466 /// handling of replace ranges.