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",
896 first_note.push_span_label(
898 "this expression is a statement because of the trailing semicolon",
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(closure_spans.whole_closure, "this is the parsed closure...");
904 second_note.push_span_label(
905 following_token_span,
906 "...but likely you meant the closure to end here",
908 expect_err.span_note(second_note, "the closure body may be incorrectly delimited");
910 expect_err.set_span(vec![preceding_pipe_span, following_token_span]);
912 let opening_suggestion_str = " {".to_string();
913 let closing_suggestion_str = "}".to_string();
915 expect_err.multipart_suggestion(
918 (preceding_pipe_span.shrink_to_hi(), opening_suggestion_str),
919 (following_token_span.shrink_to_lo(), closing_suggestion_str),
921 Applicability::MaybeIncorrect,
929 /// Parses a sequence, not including the closing delimiter. The function
930 /// `f` must consume tokens until reaching the next separator or
932 fn parse_seq_to_before_end<T>(
936 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
937 ) -> PResult<'a, (Vec<T>, bool, bool)> {
938 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
941 /// Parses a sequence, including the closing delimiter. The function
942 /// `f` must consume tokens until reaching the next separator or
944 fn parse_seq_to_end<T>(
948 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
949 ) -> PResult<'a, (Vec<T>, bool /* trailing */)> {
950 let (val, trailing, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
957 /// Parses a sequence, including the closing delimiter. The function
958 /// `f` must consume tokens until reaching the next separator or
960 fn parse_unspanned_seq<T>(
965 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
966 ) -> PResult<'a, (Vec<T>, bool)> {
968 self.parse_seq_to_end(ket, sep, f)
971 fn parse_delim_comma_seq<T>(
974 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
975 ) -> PResult<'a, (Vec<T>, bool)> {
976 self.parse_unspanned_seq(
977 &token::OpenDelim(delim),
978 &token::CloseDelim(delim),
979 SeqSep::trailing_allowed(token::Comma),
984 fn parse_paren_comma_seq<T>(
986 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
987 ) -> PResult<'a, (Vec<T>, bool)> {
988 self.parse_delim_comma_seq(Delimiter::Parenthesis, f)
991 /// Advance the parser by one token using provided token as the next one.
992 fn bump_with(&mut self, next: (Token, Spacing)) {
993 self.inlined_bump_with(next)
996 /// This always-inlined version should only be used on hot code paths.
998 fn inlined_bump_with(&mut self, (next_token, next_spacing): (Token, Spacing)) {
999 // Update the current and previous tokens.
1000 self.prev_token = mem::replace(&mut self.token, next_token);
1001 self.token_spacing = next_spacing;
1004 self.expected_tokens.clear();
1007 /// Advance the parser by one token.
1008 pub fn bump(&mut self) {
1009 // Note: destructuring here would give nicer code, but it was found in #96210 to be slower
1010 // than `.0`/`.1` access.
1011 let mut next = self.token_cursor.inlined_next(self.desugar_doc_comments);
1012 self.token_cursor.num_next_calls += 1;
1013 // We've retrieved an token from the underlying
1014 // cursor, so we no longer need to worry about
1015 // an unglued token. See `break_and_eat` for more details
1016 self.token_cursor.break_last_token = false;
1017 if next.0.span.is_dummy() {
1018 // Tweak the location for better diagnostics, but keep syntactic context intact.
1019 let fallback_span = self.token.span;
1020 next.0.span = fallback_span.with_ctxt(next.0.span.ctxt());
1022 debug_assert!(!matches!(
1024 token::OpenDelim(Delimiter::Invisible) | token::CloseDelim(Delimiter::Invisible)
1026 self.inlined_bump_with(next)
1029 /// Look-ahead `dist` tokens of `self.token` and get access to that token there.
1030 /// When `dist == 0` then the current token is looked at.
1031 pub fn look_ahead<R>(&self, dist: usize, looker: impl FnOnce(&Token) -> R) -> R {
1033 return looker(&self.token);
1036 let frame = &self.token_cursor.frame;
1037 if let Some((delim, span)) = frame.delim_sp && delim != Delimiter::Invisible {
1038 let all_normal = (0..dist).all(|i| {
1039 let token = frame.tree_cursor.look_ahead(i);
1040 !matches!(token, Some(TokenTree::Delimited(_, Delimiter::Invisible, _)))
1043 return match frame.tree_cursor.look_ahead(dist - 1) {
1044 Some(tree) => match tree {
1045 TokenTree::Token(token) => looker(token),
1046 TokenTree::Delimited(dspan, delim, _) => {
1047 looker(&Token::new(token::OpenDelim(*delim), dspan.open))
1050 None => looker(&Token::new(token::CloseDelim(delim), span.close)),
1055 let mut cursor = self.token_cursor.clone();
1057 let mut token = Token::dummy();
1059 token = cursor.next(/* desugar_doc_comments */ false).0;
1062 token::OpenDelim(Delimiter::Invisible) | token::CloseDelim(Delimiter::Invisible)
1068 return looker(&token);
1071 /// Returns whether any of the given keywords are `dist` tokens ahead of the current one.
1072 fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool {
1073 self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw)))
1076 /// Parses asyncness: `async` or nothing.
1077 fn parse_asyncness(&mut self) -> Async {
1078 if self.eat_keyword(kw::Async) {
1079 let span = self.prev_token.uninterpolated_span();
1080 Async::Yes { span, closure_id: DUMMY_NODE_ID, return_impl_trait_id: DUMMY_NODE_ID }
1086 /// Parses unsafety: `unsafe` or nothing.
1087 fn parse_unsafety(&mut self) -> Unsafe {
1088 if self.eat_keyword(kw::Unsafe) {
1089 Unsafe::Yes(self.prev_token.uninterpolated_span())
1095 /// Parses constness: `const` or nothing.
1096 fn parse_constness(&mut self) -> Const {
1097 // Avoid const blocks to be parsed as const items
1098 if self.look_ahead(1, |t| t != &token::OpenDelim(Delimiter::Brace))
1099 && self.eat_keyword(kw::Const)
1101 Const::Yes(self.prev_token.uninterpolated_span())
1107 /// Parses inline const expressions.
1108 fn parse_const_block(&mut self, span: Span, pat: bool) -> PResult<'a, P<Expr>> {
1110 self.sess.gated_spans.gate(sym::inline_const_pat, span);
1112 self.sess.gated_spans.gate(sym::inline_const, span);
1114 self.eat_keyword(kw::Const);
1115 let (attrs, blk) = self.parse_inner_attrs_and_block()?;
1116 let anon_const = AnonConst {
1118 value: self.mk_expr(blk.span, ExprKind::Block(blk, None), AttrVec::new()),
1120 let blk_span = anon_const.value.span;
1121 Ok(self.mk_expr(span.to(blk_span), ExprKind::ConstBlock(anon_const), AttrVec::from(attrs)))
1124 /// Parses mutability (`mut` or nothing).
1125 fn parse_mutability(&mut self) -> Mutability {
1126 if self.eat_keyword(kw::Mut) { Mutability::Mut } else { Mutability::Not }
1129 /// Possibly parses mutability (`const` or `mut`).
1130 fn parse_const_or_mut(&mut self) -> Option<Mutability> {
1131 if self.eat_keyword(kw::Mut) {
1132 Some(Mutability::Mut)
1133 } else if self.eat_keyword(kw::Const) {
1134 Some(Mutability::Not)
1140 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
1141 if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) = self.token.kind
1143 self.expect_no_suffix(self.token.span, "a tuple index", suffix);
1145 Ok(Ident::new(symbol, self.prev_token.span))
1147 self.parse_ident_common(true)
1151 fn parse_mac_args(&mut self) -> PResult<'a, P<MacArgs>> {
1152 self.parse_mac_args_common(true).map(P)
1155 fn parse_attr_args(&mut self) -> PResult<'a, MacArgs> {
1156 self.parse_mac_args_common(false)
1159 fn parse_mac_args_common(&mut self, delimited_only: bool) -> PResult<'a, MacArgs> {
1161 if self.check(&token::OpenDelim(Delimiter::Parenthesis))
1162 || self.check(&token::OpenDelim(Delimiter::Bracket))
1163 || self.check(&token::OpenDelim(Delimiter::Brace))
1165 match self.parse_token_tree() {
1166 TokenTree::Delimited(dspan, delim, tokens) =>
1167 // We've confirmed above that there is a delimiter so unwrapping is OK.
1169 MacArgs::Delimited(dspan, MacDelimiter::from_token(delim).unwrap(), tokens)
1171 _ => unreachable!(),
1173 } else if !delimited_only {
1174 if self.eat(&token::Eq) {
1175 let eq_span = self.prev_token.span;
1176 MacArgs::Eq(eq_span, MacArgsEq::Ast(self.parse_expr_force_collect()?))
1181 return self.unexpected();
1186 fn parse_or_use_outer_attributes(
1188 already_parsed_attrs: Option<AttrWrapper>,
1189 ) -> PResult<'a, AttrWrapper> {
1190 if let Some(attrs) = already_parsed_attrs {
1193 self.parse_outer_attributes()
1197 /// Parses a single token tree from the input.
1198 pub(crate) fn parse_token_tree(&mut self) -> TokenTree {
1199 match self.token.kind {
1200 token::OpenDelim(..) => {
1201 // Grab the tokens from this frame.
1202 let frame = &self.token_cursor.frame;
1203 let stream = frame.tree_cursor.stream.clone();
1204 let (delim, span) = frame.delim_sp.unwrap();
1206 // Advance the token cursor through the entire delimited
1207 // sequence. After getting the `OpenDelim` we are *within* the
1208 // delimited sequence, i.e. at depth `d`. After getting the
1209 // matching `CloseDelim` we are *after* the delimited sequence,
1210 // i.e. at depth `d - 1`.
1211 let target_depth = self.token_cursor.stack.len() - 1;
1213 // Advance one token at a time, so `TokenCursor::next()`
1214 // can capture these tokens if necessary.
1216 if self.token_cursor.stack.len() == target_depth {
1217 debug_assert!(matches!(self.token.kind, token::CloseDelim(_)));
1222 // Consume close delimiter
1224 TokenTree::Delimited(span, delim, stream)
1226 token::CloseDelim(_) | token::Eof => unreachable!(),
1229 TokenTree::Token(self.prev_token.clone())
1234 /// Parses a stream of tokens into a list of `TokenTree`s, up to EOF.
1235 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
1236 let mut tts = Vec::new();
1237 while self.token != token::Eof {
1238 tts.push(self.parse_token_tree());
1243 pub fn parse_tokens(&mut self) -> TokenStream {
1244 let mut result = Vec::new();
1246 match self.token.kind {
1247 token::Eof | token::CloseDelim(..) => break,
1248 _ => result.push(self.parse_token_tree().into()),
1251 TokenStream::new(result)
1254 /// Evaluates the closure with restrictions in place.
1256 /// Afters the closure is evaluated, restrictions are reset.
1257 fn with_res<T>(&mut self, res: Restrictions, f: impl FnOnce(&mut Self) -> T) -> T {
1258 let old = self.restrictions;
1259 self.restrictions = res;
1261 self.restrictions = old;
1265 /// Parses `pub` and `pub(in path)` plus shortcuts `pub(crate)` for `pub(in crate)`, `pub(self)`
1266 /// for `pub(in self)` and `pub(super)` for `pub(in super)`.
1267 /// If the following element can't be a tuple (i.e., it's a function definition), then
1268 /// it's not a tuple struct field), and the contents within the parentheses aren't valid,
1269 /// so emit a proper diagnostic.
1270 // Public for rustfmt usage.
1271 pub fn parse_visibility(&mut self, fbt: FollowedByType) -> PResult<'a, Visibility> {
1272 maybe_whole!(self, NtVis, |x| x.into_inner());
1274 if !self.eat_keyword(kw::Pub) {
1275 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
1276 // keyword to grab a span from for inherited visibility; an empty span at the
1277 // beginning of the current token would seem to be the "Schelling span".
1278 return Ok(Visibility {
1279 span: self.token.span.shrink_to_lo(),
1280 kind: VisibilityKind::Inherited,
1284 let lo = self.prev_token.span;
1286 if self.check(&token::OpenDelim(Delimiter::Parenthesis)) {
1287 // We don't `self.bump()` the `(` yet because this might be a struct definition where
1288 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
1289 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
1290 // by the following tokens.
1291 if self.is_keyword_ahead(1, &[kw::In]) {
1292 // Parse `pub(in path)`.
1294 self.bump(); // `in`
1295 let path = self.parse_path(PathStyle::Mod)?; // `path`
1296 self.expect(&token::CloseDelim(Delimiter::Parenthesis))?; // `)`
1297 let vis = VisibilityKind::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
1298 return Ok(Visibility {
1299 span: lo.to(self.prev_token.span),
1303 } else if self.look_ahead(2, |t| t == &token::CloseDelim(Delimiter::Parenthesis))
1304 && self.is_keyword_ahead(1, &[kw::Crate, kw::Super, kw::SelfLower])
1306 // Parse `pub(crate)`, `pub(self)`, or `pub(super)`.
1308 let path = self.parse_path(PathStyle::Mod)?; // `crate`/`super`/`self`
1309 self.expect(&token::CloseDelim(Delimiter::Parenthesis))?; // `)`
1310 let vis = VisibilityKind::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
1311 return Ok(Visibility {
1312 span: lo.to(self.prev_token.span),
1316 } else if let FollowedByType::No = fbt {
1317 // Provide this diagnostic if a type cannot follow;
1318 // in particular, if this is not a tuple struct.
1319 self.recover_incorrect_vis_restriction()?;
1320 // Emit diagnostic, but continue with public visibility.
1324 Ok(Visibility { span: lo, kind: VisibilityKind::Public, tokens: None })
1327 /// Recovery for e.g. `pub(something) fn ...` or `struct X { pub(something) y: Z }`
1328 fn recover_incorrect_vis_restriction(&mut self) -> PResult<'a, ()> {
1330 let path = self.parse_path(PathStyle::Mod)?;
1331 self.expect(&token::CloseDelim(Delimiter::Parenthesis))?; // `)`
1333 let msg = "incorrect visibility restriction";
1334 let suggestion = r##"some possible visibility restrictions are:
1335 `pub(crate)`: visible only on the current crate
1336 `pub(super)`: visible only in the current module's parent
1337 `pub(in path::to::module)`: visible only on the specified path"##;
1339 let path_str = pprust::path_to_string(&path);
1341 struct_span_err!(self.sess.span_diagnostic, path.span, E0704, "{}", msg)
1345 &format!("make this visible only to module `{}` with `in`", path_str),
1346 format!("in {}", path_str),
1347 Applicability::MachineApplicable,
1354 /// Parses `extern string_literal?`.
1355 fn parse_extern(&mut self) -> Extern {
1356 if self.eat_keyword(kw::Extern) { Extern::from_abi(self.parse_abi()) } else { Extern::None }
1359 /// Parses a string literal as an ABI spec.
1360 fn parse_abi(&mut self) -> Option<StrLit> {
1361 match self.parse_str_lit() {
1362 Ok(str_lit) => Some(str_lit),
1363 Err(Some(lit)) => match lit.kind {
1364 ast::LitKind::Err(_) => None,
1366 self.struct_span_err(lit.span, "non-string ABI literal")
1369 "specify the ABI with a string literal",
1371 Applicability::MaybeIncorrect,
1381 pub fn collect_tokens_no_attrs<R: HasAttrs + HasTokens>(
1383 f: impl FnOnce(&mut Self) -> PResult<'a, R>,
1384 ) -> PResult<'a, R> {
1385 // The only reason to call `collect_tokens_no_attrs` is if you want tokens, so use
1386 // `ForceCollect::Yes`
1387 self.collect_tokens_trailing_token(
1388 AttrWrapper::empty(),
1390 |this, _attrs| Ok((f(this)?, TrailingToken::None)),
1395 fn is_import_coupler(&mut self) -> bool {
1396 self.check(&token::ModSep)
1397 && self.look_ahead(1, |t| {
1398 *t == token::OpenDelim(Delimiter::Brace) || *t == token::BinOp(token::Star)
1402 pub fn clear_expected_tokens(&mut self) {
1403 self.expected_tokens.clear();
1407 pub(crate) fn make_unclosed_delims_error(
1408 unmatched: UnmatchedBrace,
1410 ) -> Option<DiagnosticBuilder<'_, ErrorGuaranteed>> {
1411 // `None` here means an `Eof` was found. We already emit those errors elsewhere, we add them to
1412 // `unmatched_braces` only for error recovery in the `Parser`.
1413 let found_delim = unmatched.found_delim?;
1414 let span: MultiSpan = if let Some(sp) = unmatched.unclosed_span {
1415 vec![unmatched.found_span, sp].into()
1417 unmatched.found_span.into()
1419 let mut err = sess.span_diagnostic.struct_span_err(
1422 "mismatched closing delimiter: `{}`",
1423 pprust::token_kind_to_string(&token::CloseDelim(found_delim)),
1426 err.span_label(unmatched.found_span, "mismatched closing delimiter");
1427 if let Some(sp) = unmatched.candidate_span {
1428 err.span_label(sp, "closing delimiter possibly meant for this");
1430 if let Some(sp) = unmatched.unclosed_span {
1431 err.span_label(sp, "unclosed delimiter");
1436 pub fn emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedBrace>, sess: &ParseSess) {
1437 *sess.reached_eof.borrow_mut() |=
1438 unclosed_delims.iter().any(|unmatched_delim| unmatched_delim.found_delim.is_none());
1439 for unmatched in unclosed_delims.drain(..) {
1440 if let Some(mut e) = make_unclosed_delims_error(unmatched, sess) {
1446 /// A helper struct used when building an `AttrAnnotatedTokenStream` from
1447 /// a `LazyTokenStream`. Both delimiter and non-delimited tokens
1448 /// are stored as `FlatToken::Token`. A vector of `FlatToken`s
1449 /// is then 'parsed' to build up an `AttrAnnotatedTokenStream` with nested
1450 /// `AttrAnnotatedTokenTree::Delimited` tokens
1451 #[derive(Debug, Clone)]
1452 pub enum FlatToken {
1453 /// A token - this holds both delimiter (e.g. '{' and '}')
1454 /// and non-delimiter tokens
1456 /// Holds the `AttributesData` for an AST node. The
1457 /// `AttributesData` is inserted directly into the
1458 /// constructed `AttrAnnotatedTokenStream` as
1459 /// an `AttrAnnotatedTokenTree::Attributes`
1460 AttrTarget(AttributesData),
1461 /// A special 'empty' token that is ignored during the conversion
1462 /// to an `AttrAnnotatedTokenStream`. This is used to simplify the
1463 /// handling of replace ranges.