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 {
82 /// If the trailing token is a comma, then capture it
83 /// Otherwise, ignore the trailing token
87 /// Like `maybe_whole_expr`, but for things other than expressions.
89 macro_rules! maybe_whole {
90 ($p:expr, $constructor:ident, |$x:ident| $e:expr) => {
91 if let token::Interpolated(nt) = &$p.token.kind {
92 if let token::$constructor(x) = &**nt {
101 /// If the next tokens are ill-formed `$ty::` recover them as `<$ty>::`.
103 macro_rules! maybe_recover_from_interpolated_ty_qpath {
104 ($self: expr, $allow_qpath_recovery: expr) => {
105 if $allow_qpath_recovery
106 && $self.look_ahead(1, |t| t == &token::ModSep)
107 && let token::Interpolated(nt) = &$self.token.kind
108 && let token::NtTy(ty) = &**nt
112 return $self.maybe_recover_from_bad_qpath_stage_2($self.prev_token.span, ty);
118 pub struct Parser<'a> {
119 pub sess: &'a ParseSess,
120 /// The current token.
122 /// The spacing for the current token
123 pub token_spacing: Spacing,
124 /// The previous token.
125 pub prev_token: Token,
126 pub capture_cfg: bool,
127 restrictions: Restrictions,
128 expected_tokens: Vec<TokenType>,
129 // Important: This must only be advanced from `bump` to ensure that
130 // `token_cursor.num_next_calls` is updated properly.
131 token_cursor: TokenCursor,
132 desugar_doc_comments: bool,
133 /// This field is used to keep track of how many left angle brackets we have seen. This is
134 /// required in order to detect extra leading left angle brackets (`<` characters) and error
137 /// See the comments in the `parse_path_segment` function for more details.
138 unmatched_angle_bracket_count: u32,
139 max_angle_bracket_count: u32,
140 /// A list of all unclosed delimiters found by the lexer. If an entry is used for error recovery
141 /// it gets removed from here. Every entry left at the end gets emitted as an independent
143 pub(super) unclosed_delims: Vec<UnmatchedBrace>,
144 last_unexpected_token_span: Option<Span>,
145 /// Span pointing at the `:` for the last type ascription the parser has seen, and whether it
146 /// looked like it could have been a mistyped path or literal `Option:Some(42)`).
147 pub last_type_ascription: Option<(Span, bool /* likely path typo */)>,
148 /// If present, this `Parser` is not parsing Rust code but rather a macro call.
149 subparser_name: Option<&'static str>,
150 capture_state: CaptureState,
151 /// This allows us to recover when the user forget to add braces around
152 /// multiple statements in the closure body.
153 pub current_closure: Option<ClosureSpans>,
156 // This type is used a lot, e.g. it's cloned when matching many declarative macro rules. Make sure
157 // it doesn't unintentionally get bigger.
158 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
159 rustc_data_structures::static_assert_size!(Parser<'_>, 328);
161 /// Stores span information about a closure.
163 pub struct ClosureSpans {
164 pub whole_closure: Span,
165 pub closing_pipe: Span,
169 /// Indicates a range of tokens that should be replaced by
170 /// the tokens in the provided vector. This is used in two
171 /// places during token collection:
173 /// 1. During the parsing of an AST node that may have a `#[derive]`
174 /// attribute, we parse a nested AST node that has `#[cfg]` or `#[cfg_attr]`
175 /// In this case, we use a `ReplaceRange` to replace the entire inner AST node
176 /// with `FlatToken::AttrTarget`, allowing us to perform eager cfg-expansion
177 /// on an `AttrTokenStream`.
179 /// 2. When we parse an inner attribute while collecting tokens. We
180 /// remove inner attributes from the token stream entirely, and
181 /// instead track them through the `attrs` field on the AST node.
182 /// This allows us to easily manipulate them (for example, removing
183 /// the first macro inner attribute to invoke a proc-macro).
184 /// When create a `TokenStream`, the inner attributes get inserted
185 /// into the proper place in the token stream.
186 pub type ReplaceRange = (Range<u32>, Vec<(FlatToken, Spacing)>);
188 /// Controls how we capture tokens. Capturing can be expensive,
189 /// so we try to avoid performing capturing in cases where
190 /// we will never need an `AttrTokenStream`.
191 #[derive(Copy, Clone)]
193 /// We aren't performing any capturing - this is the default mode.
195 /// We are capturing tokens
200 struct CaptureState {
201 capturing: Capturing,
202 replace_ranges: Vec<ReplaceRange>,
203 inner_attr_ranges: FxHashMap<AttrId, ReplaceRange>,
206 impl<'a> Drop for Parser<'a> {
208 emit_unclosed_delims(&mut self.unclosed_delims, &self.sess);
214 // The current (innermost) frame. `frame` and `stack` could be combined,
215 // but it's faster to have them separately to access `frame` directly
216 // rather than via something like `stack.last().unwrap()` or
217 // `stack[stack.len() - 1]`.
218 frame: TokenCursorFrame,
219 // Additional frames that enclose `frame`.
220 stack: Vec<TokenCursorFrame>,
221 desugar_doc_comments: bool,
222 // Counts the number of calls to `{,inlined_}next`.
223 num_next_calls: usize,
224 // During parsing, we may sometimes need to 'unglue' a
225 // glued token into two component tokens
226 // (e.g. '>>' into '>' and '>), so that the parser
227 // can consume them one at a time. This process
228 // bypasses the normal capturing mechanism
229 // (e.g. `num_next_calls` will not be incremented),
230 // since the 'unglued' tokens due not exist in
231 // the original `TokenStream`.
233 // If we end up consuming both unglued tokens,
234 // then this is not an issue - we'll end up
235 // capturing the single 'glued' token.
237 // However, in certain circumstances, we may
238 // want to capture just the first 'unglued' token.
239 // For example, capturing the `Vec<u8>`
240 // in `Option<Vec<u8>>` requires us to unglue
241 // the trailing `>>` token. The `break_last_token`
242 // field is used to track this token - it gets
243 // appended to the captured stream when
244 // we evaluate a `LazyAttrTokenStream`.
245 break_last_token: bool,
249 struct TokenCursorFrame {
250 delim_sp: Option<(Delimiter, DelimSpan)>,
251 tree_cursor: tokenstream::Cursor,
254 impl TokenCursorFrame {
255 fn new(delim_sp: Option<(Delimiter, DelimSpan)>, tts: TokenStream) -> Self {
256 TokenCursorFrame { delim_sp, tree_cursor: tts.into_trees() }
261 fn next(&mut self, desugar_doc_comments: bool) -> (Token, Spacing) {
262 self.inlined_next(desugar_doc_comments)
265 /// This always-inlined version should only be used on hot code paths.
267 fn inlined_next(&mut self, desugar_doc_comments: bool) -> (Token, Spacing) {
269 // FIXME: we currently don't return `Delimiter` open/close delims. To fix #67062 we will
270 // need to, whereupon the `delim != Delimiter::Invisible` conditions below can be
272 if let Some(tree) = self.frame.tree_cursor.next_ref() {
274 &TokenTree::Token(ref token, spacing) => match (desugar_doc_comments, token) {
275 (true, &Token { kind: token::DocComment(_, attr_style, data), span }) => {
276 return self.desugar(attr_style, data, span);
278 _ => return (token.clone(), spacing),
280 &TokenTree::Delimited(sp, delim, ref tts) => {
281 // Set `open_delim` to true here because we deal with it immediately.
282 let frame = TokenCursorFrame::new(Some((delim, sp)), tts.clone());
283 self.stack.push(mem::replace(&mut self.frame, frame));
284 if delim != Delimiter::Invisible {
285 return (Token::new(token::OpenDelim(delim), sp.open), Spacing::Alone);
287 // No open delimiter to return; continue on to the next iteration.
290 } else if let Some(frame) = self.stack.pop() {
291 if let Some((delim, span)) = self.frame.delim_sp && delim != Delimiter::Invisible {
293 return (Token::new(token::CloseDelim(delim), span.close), Spacing::Alone);
296 // No close delimiter to return; continue on to the next iteration.
298 return (Token::new(token::Eof, DUMMY_SP), Spacing::Alone);
303 fn desugar(&mut self, attr_style: AttrStyle, data: Symbol, span: Span) -> (Token, Spacing) {
304 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
305 // required to wrap the text. E.g.
306 // - `abc d` is wrapped as `r"abc d"` (num_of_hashes = 0)
307 // - `abc "d"` is wrapped as `r#"abc "d""#` (num_of_hashes = 1)
308 // - `abc "##d##"` is wrapped as `r###"abc "d""###` (num_of_hashes = 3)
309 let mut num_of_hashes = 0;
311 for ch in data.as_str().chars() {
314 '#' if count > 0 => count + 1,
317 num_of_hashes = cmp::max(num_of_hashes, count);
320 // `/// foo` becomes `doc = r"foo".
321 let delim_span = DelimSpan::from_single(span);
322 let body = TokenTree::Delimited(
326 TokenTree::token_alone(token::Ident(sym::doc, false), span),
327 TokenTree::token_alone(token::Eq, span),
328 TokenTree::token_alone(
329 TokenKind::lit(token::StrRaw(num_of_hashes), data, None),
334 .collect::<TokenStream>(),
337 self.stack.push(mem::replace(
339 TokenCursorFrame::new(
341 if attr_style == AttrStyle::Inner {
343 TokenTree::token_alone(token::Pound, span),
344 TokenTree::token_alone(token::Not, span),
348 .collect::<TokenStream>()
350 [TokenTree::token_alone(token::Pound, span), body]
352 .collect::<TokenStream>()
357 self.next(/* desugar_doc_comments */ false)
361 #[derive(Debug, Clone, PartialEq)]
374 fn to_string(&self) -> String {
376 TokenType::Token(ref t) => format!("`{}`", pprust::token_kind_to_string(t)),
377 TokenType::Keyword(kw) => format!("`{}`", kw),
378 TokenType::Operator => "an operator".to_string(),
379 TokenType::Lifetime => "lifetime".to_string(),
380 TokenType::Ident => "identifier".to_string(),
381 TokenType::Path => "path".to_string(),
382 TokenType::Type => "type".to_string(),
383 TokenType::Const => "a const expression".to_string(),
388 #[derive(Copy, Clone, Debug)]
389 enum TokenExpectType {
394 /// A sequence separator.
396 /// The separator token.
397 sep: Option<TokenKind>,
398 /// `true` if a trailing separator is allowed.
399 trailing_sep_allowed: bool,
403 fn trailing_allowed(t: TokenKind) -> SeqSep {
404 SeqSep { sep: Some(t), trailing_sep_allowed: true }
407 fn none() -> SeqSep {
408 SeqSep { sep: None, trailing_sep_allowed: false }
412 pub enum FollowedByType {
417 #[derive(Clone, Copy, PartialEq, Eq)]
418 pub enum TokenDescription {
425 impl TokenDescription {
426 pub fn from_token(token: &Token) -> Option<Self> {
428 _ if token.is_special_ident() => Some(TokenDescription::ReservedIdentifier),
429 _ if token.is_used_keyword() => Some(TokenDescription::Keyword),
430 _ if token.is_unused_keyword() => Some(TokenDescription::ReservedKeyword),
431 token::DocComment(..) => Some(TokenDescription::DocComment),
437 pub(super) fn token_descr(token: &Token) -> String {
438 let name = pprust::token_to_string(token).to_string();
440 let kind = TokenDescription::from_token(token).map(|kind| match kind {
441 TokenDescription::ReservedIdentifier => "reserved identifier",
442 TokenDescription::Keyword => "keyword",
443 TokenDescription::ReservedKeyword => "reserved keyword",
444 TokenDescription::DocComment => "doc comment",
447 if let Some(kind) = kind { format!("{} `{}`", kind, name) } else { format!("`{}`", name) }
450 impl<'a> Parser<'a> {
454 desugar_doc_comments: bool,
455 subparser_name: Option<&'static str>,
457 let mut parser = Parser {
459 token: Token::dummy(),
460 token_spacing: Spacing::Alone,
461 prev_token: Token::dummy(),
463 restrictions: Restrictions::empty(),
464 expected_tokens: Vec::new(),
465 token_cursor: TokenCursor {
466 frame: TokenCursorFrame::new(None, tokens),
469 desugar_doc_comments,
470 break_last_token: false,
472 desugar_doc_comments,
473 unmatched_angle_bracket_count: 0,
474 max_angle_bracket_count: 0,
475 unclosed_delims: Vec::new(),
476 last_unexpected_token_span: None,
477 last_type_ascription: None,
479 capture_state: CaptureState {
480 capturing: Capturing::No,
481 replace_ranges: Vec::new(),
482 inner_attr_ranges: Default::default(),
484 current_closure: None,
487 // Make parser point to the first token.
493 pub fn unexpected<T>(&mut self) -> PResult<'a, T> {
494 match self.expect_one_of(&[], &[]) {
496 // We can get `Ok(true)` from `recover_closing_delimiter`
497 // which is called in `expected_one_of_not_found`.
498 Ok(_) => FatalError.raise(),
502 /// Expects and consumes the token `t`. Signals an error if the next token is not `t`.
503 pub fn expect(&mut self, t: &TokenKind) -> PResult<'a, bool /* recovered */> {
504 if self.expected_tokens.is_empty() {
505 if self.token == *t {
509 self.unexpected_try_recover(t)
512 self.expect_one_of(slice::from_ref(t), &[])
516 /// Expect next token to be edible or inedible token. If edible,
517 /// then consume it; if inedible, then return without consuming
518 /// anything. Signal a fatal error if next token is unexpected.
519 pub fn expect_one_of(
521 edible: &[TokenKind],
522 inedible: &[TokenKind],
523 ) -> PResult<'a, bool /* recovered */> {
524 if edible.contains(&self.token.kind) {
527 } else if inedible.contains(&self.token.kind) {
528 // leave it in the input
530 } else if self.last_unexpected_token_span == Some(self.token.span) {
533 self.expected_one_of_not_found(edible, inedible)
537 // Public for rustfmt usage.
538 pub fn parse_ident(&mut self) -> PResult<'a, Ident> {
539 self.parse_ident_common(true)
542 fn ident_or_err(&mut self) -> PResult<'a, (Ident, /* is_raw */ bool)> {
543 self.token.ident().ok_or_else(|| match self.prev_token.kind {
544 TokenKind::DocComment(..) => DocCommentDoesNotDocumentAnything {
545 span: self.prev_token.span,
548 .into_diagnostic(&self.sess.span_diagnostic),
549 _ => self.expected_ident_found(),
553 fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, Ident> {
554 let (ident, is_raw) = self.ident_or_err()?;
555 if !is_raw && ident.is_reserved() {
556 let mut err = self.expected_ident_found();
567 /// Checks if the next token is `tok`, and returns `true` if so.
569 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
571 fn check(&mut self, tok: &TokenKind) -> bool {
572 let is_present = self.token == *tok;
574 self.expected_tokens.push(TokenType::Token(tok.clone()));
579 fn check_noexpect(&self, tok: &TokenKind) -> bool {
583 /// Consumes a token 'tok' if it exists. Returns whether the given token was present.
585 /// the main purpose of this function is to reduce the cluttering of the suggestions list
586 /// which using the normal eat method could introduce in some cases.
587 pub fn eat_noexpect(&mut self, tok: &TokenKind) -> bool {
588 let is_present = self.check_noexpect(tok);
595 /// Consumes a token 'tok' if it exists. Returns whether the given token was present.
596 pub fn eat(&mut self, tok: &TokenKind) -> bool {
597 let is_present = self.check(tok);
604 /// If the next token is the given keyword, returns `true` without eating it.
605 /// An expectation is also added for diagnostics purposes.
606 fn check_keyword(&mut self, kw: Symbol) -> bool {
607 self.expected_tokens.push(TokenType::Keyword(kw));
608 self.token.is_keyword(kw)
611 /// If the next token is the given keyword, eats it and returns `true`.
612 /// Otherwise, returns `false`. An expectation is also added for diagnostics purposes.
613 // Public for rustfmt usage.
614 pub fn eat_keyword(&mut self, kw: Symbol) -> bool {
615 if self.check_keyword(kw) {
623 fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool {
624 if self.token.is_keyword(kw) {
632 /// If the given word is not a keyword, signals an error.
633 /// If the next token is not the given word, signals an error.
634 /// Otherwise, eats it.
635 fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> {
636 if !self.eat_keyword(kw) { self.unexpected() } else { Ok(()) }
639 /// Is the given keyword `kw` followed by a non-reserved identifier?
640 fn is_kw_followed_by_ident(&self, kw: Symbol) -> bool {
641 self.token.is_keyword(kw) && self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
644 fn check_or_expected(&mut self, ok: bool, typ: TokenType) -> bool {
648 self.expected_tokens.push(typ);
653 fn check_ident(&mut self) -> bool {
654 self.check_or_expected(self.token.is_ident(), TokenType::Ident)
657 fn check_path(&mut self) -> bool {
658 self.check_or_expected(self.token.is_path_start(), TokenType::Path)
661 fn check_type(&mut self) -> bool {
662 self.check_or_expected(self.token.can_begin_type(), TokenType::Type)
665 fn check_const_arg(&mut self) -> bool {
666 self.check_or_expected(self.token.can_begin_const_arg(), TokenType::Const)
669 fn check_inline_const(&self, dist: usize) -> bool {
670 self.is_keyword_ahead(dist, &[kw::Const])
671 && self.look_ahead(dist + 1, |t| match t.kind {
672 token::Interpolated(ref nt) => matches!(**nt, token::NtBlock(..)),
673 token::OpenDelim(Delimiter::Brace) => true,
678 /// Checks to see if the next token is either `+` or `+=`.
679 /// Otherwise returns `false`.
680 fn check_plus(&mut self) -> bool {
681 self.check_or_expected(
682 self.token.is_like_plus(),
683 TokenType::Token(token::BinOp(token::Plus)),
687 /// Eats the expected token if it's present possibly breaking
688 /// compound tokens like multi-character operators in process.
689 /// Returns `true` if the token was eaten.
690 fn break_and_eat(&mut self, expected: TokenKind) -> bool {
691 if self.token.kind == expected {
695 match self.token.kind.break_two_token_op() {
696 Some((first, second)) if first == expected => {
697 let first_span = self.sess.source_map().start_point(self.token.span);
698 let second_span = self.token.span.with_lo(first_span.hi());
699 self.token = Token::new(first, first_span);
700 // Keep track of this token - if we end token capturing now,
701 // we'll want to append this token to the captured stream.
703 // If we consume any additional tokens, then this token
704 // is not needed (we'll capture the entire 'glued' token),
705 // and `bump` will set this field to `None`
706 self.token_cursor.break_last_token = true;
707 // Use the spacing of the glued token as the spacing
708 // of the unglued second token.
709 self.bump_with((Token::new(second, second_span), self.token_spacing));
713 self.expected_tokens.push(TokenType::Token(expected));
719 /// Eats `+` possibly breaking tokens like `+=` in process.
720 fn eat_plus(&mut self) -> bool {
721 self.break_and_eat(token::BinOp(token::Plus))
724 /// Eats `&` possibly breaking tokens like `&&` in process.
725 /// Signals an error if `&` is not eaten.
726 fn expect_and(&mut self) -> PResult<'a, ()> {
727 if self.break_and_eat(token::BinOp(token::And)) { Ok(()) } else { self.unexpected() }
730 /// Eats `|` possibly breaking tokens like `||` in process.
731 /// Signals an error if `|` was not eaten.
732 fn expect_or(&mut self) -> PResult<'a, ()> {
733 if self.break_and_eat(token::BinOp(token::Or)) { Ok(()) } else { self.unexpected() }
736 /// Eats `<` possibly breaking tokens like `<<` in process.
737 fn eat_lt(&mut self) -> bool {
738 let ate = self.break_and_eat(token::Lt);
740 // See doc comment for `unmatched_angle_bracket_count`.
741 self.unmatched_angle_bracket_count += 1;
742 self.max_angle_bracket_count += 1;
743 debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count);
748 /// Eats `<` possibly breaking tokens like `<<` in process.
749 /// Signals an error if `<` was not eaten.
750 fn expect_lt(&mut self) -> PResult<'a, ()> {
751 if self.eat_lt() { Ok(()) } else { self.unexpected() }
754 /// Eats `>` possibly breaking tokens like `>>` in process.
755 /// Signals an error if `>` was not eaten.
756 fn expect_gt(&mut self) -> PResult<'a, ()> {
757 if self.break_and_eat(token::Gt) {
758 // See doc comment for `unmatched_angle_bracket_count`.
759 if self.unmatched_angle_bracket_count > 0 {
760 self.unmatched_angle_bracket_count -= 1;
761 debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count);
769 fn expect_any_with_type(&mut self, kets: &[&TokenKind], expect: TokenExpectType) -> bool {
770 kets.iter().any(|k| match expect {
771 TokenExpectType::Expect => self.check(k),
772 TokenExpectType::NoExpect => self.token == **k,
776 fn parse_seq_to_before_tokens<T>(
780 expect: TokenExpectType,
781 mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
782 ) -> PResult<'a, (Vec<T>, bool /* trailing */, bool /* recovered */)> {
783 let mut first = true;
784 let mut recovered = false;
785 let mut trailing = false;
787 let unclosed_delims = !self.unclosed_delims.is_empty();
789 while !self.expect_any_with_type(kets, expect) {
790 if let token::CloseDelim(..) | token::Eof = self.token.kind {
793 if let Some(ref t) = sep.sep {
797 match self.expect(t) {
799 self.current_closure.take();
802 self.current_closure.take();
806 Err(mut expect_err) => {
807 let sp = self.prev_token.span.shrink_to_hi();
808 let token_str = pprust::token_kind_to_string(t);
810 match self.current_closure.take() {
811 Some(closure_spans) if self.token.kind == TokenKind::Semi => {
812 // Finding a semicolon instead of a comma
813 // after a closure body indicates that the
814 // closure body may be a block but the user
815 // forgot to put braces around its
818 self.recover_missing_braces_around_closure_body(
827 // Attempt to keep parsing if it was a similar separator.
828 if let Some(ref tokens) = t.similar_tokens() {
829 if tokens.contains(&self.token.kind) && !unclosed_delims {
836 // If this was a missing `@` in a binding pattern
837 // bail with a suggestion
838 // https://github.com/rust-lang/rust/issues/72373
839 if self.prev_token.is_ident() && self.token.kind == token::DotDot {
841 "if you meant to bind the contents of \
842 the rest of the array pattern into `{}`, use `@`",
843 pprust::token_to_string(&self.prev_token)
846 .span_suggestion_verbose(
847 self.prev_token.span.shrink_to_hi().until(self.token.span),
850 Applicability::MaybeIncorrect,
856 // Attempt to keep parsing if it was an omitted separator.
859 // Parsed successfully, therefore most probably the code only
860 // misses a separator.
862 .span_suggestion_short(
864 &format!("missing `{}`", token_str),
866 Applicability::MaybeIncorrect,
874 // Parsing failed, therefore it must be something more serious
875 // than just a missing separator.
886 if sep.trailing_sep_allowed && self.expect_any_with_type(kets, expect) {
895 Ok((v, trailing, recovered))
898 fn recover_missing_braces_around_closure_body(
900 closure_spans: ClosureSpans,
901 mut expect_err: DiagnosticBuilder<'_, ErrorGuaranteed>,
902 ) -> PResult<'a, ()> {
903 let initial_semicolon = self.token.span;
905 while self.eat(&TokenKind::Semi) {
906 let _ = self.parse_stmt(ForceCollect::Yes)?;
909 expect_err.set_primary_message(
910 "closure bodies that contain statements must be surrounded by braces",
913 let preceding_pipe_span = closure_spans.closing_pipe;
914 let following_token_span = self.token.span;
916 let mut first_note = MultiSpan::from(vec![initial_semicolon]);
917 first_note.push_span_label(
919 "this `;` turns the preceding closure into a statement",
921 first_note.push_span_label(
923 "this expression is a statement because of the trailing semicolon",
925 expect_err.span_note(first_note, "statement found outside of a block");
927 let mut second_note = MultiSpan::from(vec![closure_spans.whole_closure]);
928 second_note.push_span_label(closure_spans.whole_closure, "this is the parsed closure...");
929 second_note.push_span_label(
930 following_token_span,
931 "...but likely you meant the closure to end here",
933 expect_err.span_note(second_note, "the closure body may be incorrectly delimited");
935 expect_err.set_span(vec![preceding_pipe_span, following_token_span]);
937 let opening_suggestion_str = " {".to_string();
938 let closing_suggestion_str = "}".to_string();
940 expect_err.multipart_suggestion(
943 (preceding_pipe_span.shrink_to_hi(), opening_suggestion_str),
944 (following_token_span.shrink_to_lo(), closing_suggestion_str),
946 Applicability::MaybeIncorrect,
954 /// Parses a sequence, not including the closing delimiter. The function
955 /// `f` must consume tokens until reaching the next separator or
957 fn parse_seq_to_before_end<T>(
961 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
962 ) -> PResult<'a, (Vec<T>, bool, bool)> {
963 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
966 /// Parses a sequence, including the closing delimiter. The function
967 /// `f` must consume tokens until reaching the next separator or
969 fn parse_seq_to_end<T>(
973 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
974 ) -> PResult<'a, (Vec<T>, bool /* trailing */)> {
975 let (val, trailing, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
982 /// Parses a sequence, including the closing delimiter. The function
983 /// `f` must consume tokens until reaching the next separator or
985 fn parse_unspanned_seq<T>(
990 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
991 ) -> PResult<'a, (Vec<T>, bool)> {
993 self.parse_seq_to_end(ket, sep, f)
996 fn parse_delim_comma_seq<T>(
999 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1000 ) -> PResult<'a, (Vec<T>, bool)> {
1001 self.parse_unspanned_seq(
1002 &token::OpenDelim(delim),
1003 &token::CloseDelim(delim),
1004 SeqSep::trailing_allowed(token::Comma),
1009 fn parse_paren_comma_seq<T>(
1011 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1012 ) -> PResult<'a, (Vec<T>, bool)> {
1013 self.parse_delim_comma_seq(Delimiter::Parenthesis, f)
1016 /// Advance the parser by one token using provided token as the next one.
1017 fn bump_with(&mut self, next: (Token, Spacing)) {
1018 self.inlined_bump_with(next)
1021 /// This always-inlined version should only be used on hot code paths.
1023 fn inlined_bump_with(&mut self, (next_token, next_spacing): (Token, Spacing)) {
1024 // Update the current and previous tokens.
1025 self.prev_token = mem::replace(&mut self.token, next_token);
1026 self.token_spacing = next_spacing;
1029 self.expected_tokens.clear();
1032 /// Advance the parser by one token.
1033 pub fn bump(&mut self) {
1034 // Note: destructuring here would give nicer code, but it was found in #96210 to be slower
1035 // than `.0`/`.1` access.
1036 let mut next = self.token_cursor.inlined_next(self.desugar_doc_comments);
1037 self.token_cursor.num_next_calls += 1;
1038 // We've retrieved an token from the underlying
1039 // cursor, so we no longer need to worry about
1040 // an unglued token. See `break_and_eat` for more details
1041 self.token_cursor.break_last_token = false;
1042 if next.0.span.is_dummy() {
1043 // Tweak the location for better diagnostics, but keep syntactic context intact.
1044 let fallback_span = self.token.span;
1045 next.0.span = fallback_span.with_ctxt(next.0.span.ctxt());
1047 debug_assert!(!matches!(
1049 token::OpenDelim(Delimiter::Invisible) | token::CloseDelim(Delimiter::Invisible)
1051 self.inlined_bump_with(next)
1054 /// Look-ahead `dist` tokens of `self.token` and get access to that token there.
1055 /// When `dist == 0` then the current token is looked at.
1056 pub fn look_ahead<R>(&self, dist: usize, looker: impl FnOnce(&Token) -> R) -> R {
1058 return looker(&self.token);
1061 let frame = &self.token_cursor.frame;
1062 if let Some((delim, span)) = frame.delim_sp && delim != Delimiter::Invisible {
1063 let all_normal = (0..dist).all(|i| {
1064 let token = frame.tree_cursor.look_ahead(i);
1065 !matches!(token, Some(TokenTree::Delimited(_, Delimiter::Invisible, _)))
1068 return match frame.tree_cursor.look_ahead(dist - 1) {
1069 Some(tree) => match tree {
1070 TokenTree::Token(token, _) => looker(token),
1071 TokenTree::Delimited(dspan, delim, _) => {
1072 looker(&Token::new(token::OpenDelim(*delim), dspan.open))
1075 None => looker(&Token::new(token::CloseDelim(delim), span.close)),
1080 let mut cursor = self.token_cursor.clone();
1082 let mut token = Token::dummy();
1084 token = cursor.next(/* desugar_doc_comments */ false).0;
1087 token::OpenDelim(Delimiter::Invisible) | token::CloseDelim(Delimiter::Invisible)
1093 return looker(&token);
1096 /// Returns whether any of the given keywords are `dist` tokens ahead of the current one.
1097 fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool {
1098 self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw)))
1101 /// Parses asyncness: `async` or nothing.
1102 fn parse_asyncness(&mut self) -> Async {
1103 if self.eat_keyword(kw::Async) {
1104 let span = self.prev_token.uninterpolated_span();
1105 Async::Yes { span, closure_id: DUMMY_NODE_ID, return_impl_trait_id: DUMMY_NODE_ID }
1111 /// Parses unsafety: `unsafe` or nothing.
1112 fn parse_unsafety(&mut self) -> Unsafe {
1113 if self.eat_keyword(kw::Unsafe) {
1114 Unsafe::Yes(self.prev_token.uninterpolated_span())
1120 /// Parses constness: `const` or nothing.
1121 fn parse_constness(&mut self) -> Const {
1122 // Avoid const blocks to be parsed as const items
1123 if self.look_ahead(1, |t| t != &token::OpenDelim(Delimiter::Brace))
1124 && self.eat_keyword(kw::Const)
1126 Const::Yes(self.prev_token.uninterpolated_span())
1132 /// Parses inline const expressions.
1133 fn parse_const_block(&mut self, span: Span, pat: bool) -> PResult<'a, P<Expr>> {
1135 self.sess.gated_spans.gate(sym::inline_const_pat, span);
1137 self.sess.gated_spans.gate(sym::inline_const, span);
1139 self.eat_keyword(kw::Const);
1140 let (attrs, blk) = self.parse_inner_attrs_and_block()?;
1141 let anon_const = AnonConst {
1143 value: self.mk_expr(blk.span, ExprKind::Block(blk, None)),
1145 let blk_span = anon_const.value.span;
1146 Ok(self.mk_expr_with_attrs(
1148 ExprKind::ConstBlock(anon_const),
1149 AttrVec::from(attrs),
1153 /// Parses mutability (`mut` or nothing).
1154 fn parse_mutability(&mut self) -> Mutability {
1155 if self.eat_keyword(kw::Mut) { Mutability::Mut } else { Mutability::Not }
1158 /// Possibly parses mutability (`const` or `mut`).
1159 fn parse_const_or_mut(&mut self) -> Option<Mutability> {
1160 if self.eat_keyword(kw::Mut) {
1161 Some(Mutability::Mut)
1162 } else if self.eat_keyword(kw::Const) {
1163 Some(Mutability::Not)
1169 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
1170 if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) = self.token.kind
1172 if let Some(suffix) = suffix {
1173 self.expect_no_tuple_index_suffix(self.token.span, suffix);
1176 Ok(Ident::new(symbol, self.prev_token.span))
1178 self.parse_ident_common(true)
1182 fn parse_mac_args(&mut self) -> PResult<'a, P<MacArgs>> {
1183 self.parse_mac_args_common(true).map(P)
1186 fn parse_attr_args(&mut self) -> PResult<'a, MacArgs> {
1187 self.parse_mac_args_common(false)
1190 fn parse_mac_args_common(&mut self, delimited_only: bool) -> PResult<'a, MacArgs> {
1192 if self.check(&token::OpenDelim(Delimiter::Parenthesis))
1193 || self.check(&token::OpenDelim(Delimiter::Bracket))
1194 || self.check(&token::OpenDelim(Delimiter::Brace))
1196 match self.parse_token_tree() {
1197 TokenTree::Delimited(dspan, delim, tokens) =>
1198 // We've confirmed above that there is a delimiter so unwrapping is OK.
1200 MacArgs::Delimited(dspan, MacDelimiter::from_token(delim).unwrap(), tokens)
1202 _ => unreachable!(),
1204 } else if !delimited_only {
1205 if self.eat(&token::Eq) {
1206 let eq_span = self.prev_token.span;
1207 MacArgs::Eq(eq_span, MacArgsEq::Ast(self.parse_expr_force_collect()?))
1212 return self.unexpected();
1217 fn parse_or_use_outer_attributes(
1219 already_parsed_attrs: Option<AttrWrapper>,
1220 ) -> PResult<'a, AttrWrapper> {
1221 if let Some(attrs) = already_parsed_attrs {
1224 self.parse_outer_attributes()
1228 /// Parses a single token tree from the input.
1229 pub(crate) fn parse_token_tree(&mut self) -> TokenTree {
1230 match self.token.kind {
1231 token::OpenDelim(..) => {
1232 // Grab the tokens from this frame.
1233 let frame = &self.token_cursor.frame;
1234 let stream = frame.tree_cursor.stream.clone();
1235 let (delim, span) = frame.delim_sp.unwrap();
1237 // Advance the token cursor through the entire delimited
1238 // sequence. After getting the `OpenDelim` we are *within* the
1239 // delimited sequence, i.e. at depth `d`. After getting the
1240 // matching `CloseDelim` we are *after* the delimited sequence,
1241 // i.e. at depth `d - 1`.
1242 let target_depth = self.token_cursor.stack.len() - 1;
1244 // Advance one token at a time, so `TokenCursor::next()`
1245 // can capture these tokens if necessary.
1247 if self.token_cursor.stack.len() == target_depth {
1248 debug_assert!(matches!(self.token.kind, token::CloseDelim(_)));
1253 // Consume close delimiter
1255 TokenTree::Delimited(span, delim, stream)
1257 token::CloseDelim(_) | token::Eof => unreachable!(),
1260 TokenTree::Token(self.prev_token.clone(), Spacing::Alone)
1265 /// Parses a stream of tokens into a list of `TokenTree`s, up to EOF.
1266 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
1267 let mut tts = Vec::new();
1268 while self.token != token::Eof {
1269 tts.push(self.parse_token_tree());
1274 pub fn parse_tokens(&mut self) -> TokenStream {
1275 let mut result = Vec::new();
1277 match self.token.kind {
1278 token::Eof | token::CloseDelim(..) => break,
1279 _ => result.push(self.parse_token_tree()),
1282 TokenStream::new(result)
1285 /// Evaluates the closure with restrictions in place.
1287 /// Afters the closure is evaluated, restrictions are reset.
1288 fn with_res<T>(&mut self, res: Restrictions, f: impl FnOnce(&mut Self) -> T) -> T {
1289 let old = self.restrictions;
1290 self.restrictions = res;
1292 self.restrictions = old;
1296 /// Parses `pub` and `pub(in path)` plus shortcuts `pub(crate)` for `pub(in crate)`, `pub(self)`
1297 /// for `pub(in self)` and `pub(super)` for `pub(in super)`.
1298 /// If the following element can't be a tuple (i.e., it's a function definition), then
1299 /// it's not a tuple struct field), and the contents within the parentheses aren't valid,
1300 /// so emit a proper diagnostic.
1301 // Public for rustfmt usage.
1302 pub fn parse_visibility(&mut self, fbt: FollowedByType) -> PResult<'a, Visibility> {
1303 maybe_whole!(self, NtVis, |x| x.into_inner());
1305 if !self.eat_keyword(kw::Pub) {
1306 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
1307 // keyword to grab a span from for inherited visibility; an empty span at the
1308 // beginning of the current token would seem to be the "Schelling span".
1309 return Ok(Visibility {
1310 span: self.token.span.shrink_to_lo(),
1311 kind: VisibilityKind::Inherited,
1315 let lo = self.prev_token.span;
1317 if self.check(&token::OpenDelim(Delimiter::Parenthesis)) {
1318 // We don't `self.bump()` the `(` yet because this might be a struct definition where
1319 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
1320 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
1321 // by the following tokens.
1322 if self.is_keyword_ahead(1, &[kw::In]) {
1323 // Parse `pub(in path)`.
1325 self.bump(); // `in`
1326 let path = self.parse_path(PathStyle::Mod)?; // `path`
1327 self.expect(&token::CloseDelim(Delimiter::Parenthesis))?; // `)`
1328 let vis = VisibilityKind::Restricted {
1330 id: ast::DUMMY_NODE_ID,
1333 return Ok(Visibility {
1334 span: lo.to(self.prev_token.span),
1338 } else if self.look_ahead(2, |t| t == &token::CloseDelim(Delimiter::Parenthesis))
1339 && self.is_keyword_ahead(1, &[kw::Crate, kw::Super, kw::SelfLower])
1341 // Parse `pub(crate)`, `pub(self)`, or `pub(super)`.
1343 let path = self.parse_path(PathStyle::Mod)?; // `crate`/`super`/`self`
1344 self.expect(&token::CloseDelim(Delimiter::Parenthesis))?; // `)`
1345 let vis = VisibilityKind::Restricted {
1347 id: ast::DUMMY_NODE_ID,
1350 return Ok(Visibility {
1351 span: lo.to(self.prev_token.span),
1355 } else if let FollowedByType::No = fbt {
1356 // Provide this diagnostic if a type cannot follow;
1357 // in particular, if this is not a tuple struct.
1358 self.recover_incorrect_vis_restriction()?;
1359 // Emit diagnostic, but continue with public visibility.
1363 Ok(Visibility { span: lo, kind: VisibilityKind::Public, tokens: None })
1366 /// Recovery for e.g. `pub(something) fn ...` or `struct X { pub(something) y: Z }`
1367 fn recover_incorrect_vis_restriction(&mut self) -> PResult<'a, ()> {
1369 let path = self.parse_path(PathStyle::Mod)?;
1370 self.expect(&token::CloseDelim(Delimiter::Parenthesis))?; // `)`
1372 let path_str = pprust::path_to_string(&path);
1373 self.sess.emit_err(IncorrectVisibilityRestriction { span: path.span, inner_str: path_str });
1378 /// Parses `extern string_literal?`.
1379 fn parse_extern(&mut self) -> Extern {
1380 if self.eat_keyword(kw::Extern) {
1381 let mut extern_span = self.prev_token.span;
1382 let abi = self.parse_abi();
1383 if let Some(abi) = abi {
1384 extern_span = extern_span.to(abi.span);
1386 Extern::from_abi(abi, extern_span)
1392 /// Parses a string literal as an ABI spec.
1393 fn parse_abi(&mut self) -> Option<StrLit> {
1394 match self.parse_str_lit() {
1395 Ok(str_lit) => Some(str_lit),
1396 Err(Some(lit)) => match lit.kind {
1397 ast::LitKind::Err => None,
1399 self.sess.emit_err(NonStringAbiLiteral { span: lit.span });
1407 pub fn collect_tokens_no_attrs<R: HasAttrs + HasTokens>(
1409 f: impl FnOnce(&mut Self) -> PResult<'a, R>,
1410 ) -> PResult<'a, R> {
1411 // The only reason to call `collect_tokens_no_attrs` is if you want tokens, so use
1412 // `ForceCollect::Yes`
1413 self.collect_tokens_trailing_token(
1414 AttrWrapper::empty(),
1416 |this, _attrs| Ok((f(this)?, TrailingToken::None)),
1421 fn is_import_coupler(&mut self) -> bool {
1422 self.check(&token::ModSep)
1423 && self.look_ahead(1, |t| {
1424 *t == token::OpenDelim(Delimiter::Brace) || *t == token::BinOp(token::Star)
1428 pub fn clear_expected_tokens(&mut self) {
1429 self.expected_tokens.clear();
1433 pub(crate) fn make_unclosed_delims_error(
1434 unmatched: UnmatchedBrace,
1436 ) -> Option<DiagnosticBuilder<'_, ErrorGuaranteed>> {
1437 // `None` here means an `Eof` was found. We already emit those errors elsewhere, we add them to
1438 // `unmatched_braces` only for error recovery in the `Parser`.
1439 let found_delim = unmatched.found_delim?;
1440 let mut spans = vec![unmatched.found_span];
1441 if let Some(sp) = unmatched.unclosed_span {
1444 let err = MismatchedClosingDelimiter {
1446 delimiter: pprust::token_kind_to_string(&token::CloseDelim(found_delim)).to_string(),
1447 unmatched: unmatched.found_span,
1448 opening_candidate: unmatched.candidate_span,
1449 unclosed: unmatched.unclosed_span,
1451 .into_diagnostic(&sess.span_diagnostic);
1455 pub fn emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedBrace>, sess: &ParseSess) {
1456 *sess.reached_eof.borrow_mut() |=
1457 unclosed_delims.iter().any(|unmatched_delim| unmatched_delim.found_delim.is_none());
1458 for unmatched in unclosed_delims.drain(..) {
1459 if let Some(mut e) = make_unclosed_delims_error(unmatched, sess) {
1465 /// A helper struct used when building an `AttrTokenStream` from
1466 /// a `LazyAttrTokenStream`. Both delimiter and non-delimited tokens
1467 /// are stored as `FlatToken::Token`. A vector of `FlatToken`s
1468 /// is then 'parsed' to build up an `AttrTokenStream` with nested
1469 /// `AttrTokenTree::Delimited` tokens.
1470 #[derive(Debug, Clone)]
1471 pub enum FlatToken {
1472 /// A token - this holds both delimiter (e.g. '{' and '}')
1473 /// and non-delimiter tokens
1475 /// Holds the `AttributesData` for an AST node. The
1476 /// `AttributesData` is inserted directly into the
1477 /// constructed `AttrTokenStream` as
1478 /// an `AttrTokenTree::Attributes`.
1479 AttrTarget(AttributesData),
1480 /// A special 'empty' token that is ignored during the conversion
1481 /// to an `AttrTokenStream`. This is used to simplify the
1482 /// handling of replace ranges.