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>,
152 // This type is used a lot, e.g. it's cloned when matching many declarative macro rules. Make sure
153 // it doesn't unintentionally get bigger.
154 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
155 rustc_data_structures::static_assert_size!(Parser<'_>, 328);
157 /// Stores span information about a closure.
159 pub struct ClosureSpans {
160 pub whole_closure: Span,
161 pub closing_pipe: Span,
165 /// Indicates a range of tokens that should be replaced by
166 /// the tokens in the provided vector. This is used in two
167 /// places during token collection:
169 /// 1. During the parsing of an AST node that may have a `#[derive]`
170 /// attribute, we parse a nested AST node that has `#[cfg]` or `#[cfg_attr]`
171 /// In this case, we use a `ReplaceRange` to replace the entire inner AST node
172 /// with `FlatToken::AttrTarget`, allowing us to perform eager cfg-expansion
173 /// on an `AttrAnnotatedTokenStream`
175 /// 2. When we parse an inner attribute while collecting tokens. We
176 /// remove inner attributes from the token stream entirely, and
177 /// instead track them through the `attrs` field on the AST node.
178 /// This allows us to easily manipulate them (for example, removing
179 /// the first macro inner attribute to invoke a proc-macro).
180 /// When create a `TokenStream`, the inner attributes get inserted
181 /// into the proper place in the token stream.
182 pub type ReplaceRange = (Range<u32>, Vec<(FlatToken, Spacing)>);
184 /// Controls how we capture tokens. Capturing can be expensive,
185 /// so we try to avoid performing capturing in cases where
186 /// we will never need an `AttrAnnotatedTokenStream`
187 #[derive(Copy, Clone)]
189 /// We aren't performing any capturing - this is the default mode.
191 /// We are capturing tokens
196 struct CaptureState {
197 capturing: Capturing,
198 replace_ranges: Vec<ReplaceRange>,
199 inner_attr_ranges: FxHashMap<AttrId, ReplaceRange>,
202 impl<'a> Drop for Parser<'a> {
204 emit_unclosed_delims(&mut self.unclosed_delims, &self.sess);
210 // The current (innermost) frame. `frame` and `stack` could be combined,
211 // but it's faster to have them separately to access `frame` directly
212 // rather than via something like `stack.last().unwrap()` or
213 // `stack[stack.len() - 1]`.
214 frame: TokenCursorFrame,
215 // Additional frames that enclose `frame`.
216 stack: Vec<TokenCursorFrame>,
217 desugar_doc_comments: bool,
218 // Counts the number of calls to `{,inlined_}next`.
219 num_next_calls: usize,
220 // During parsing, we may sometimes need to 'unglue' a
221 // glued token into two component tokens
222 // (e.g. '>>' into '>' and '>), so that the parser
223 // can consume them one at a time. This process
224 // bypasses the normal capturing mechanism
225 // (e.g. `num_next_calls` will not be incremented),
226 // since the 'unglued' tokens due not exist in
227 // the original `TokenStream`.
229 // If we end up consuming both unglued tokens,
230 // then this is not an issue - we'll end up
231 // capturing the single 'glued' token.
233 // However, in certain circumstances, we may
234 // want to capture just the first 'unglued' token.
235 // For example, capturing the `Vec<u8>`
236 // in `Option<Vec<u8>>` requires us to unglue
237 // the trailing `>>` token. The `break_last_token`
238 // field is used to track this token - it gets
239 // appended to the captured stream when
240 // we evaluate a `LazyTokenStream`
241 break_last_token: bool,
245 struct TokenCursorFrame {
246 delim_sp: Option<(Delimiter, DelimSpan)>,
247 tree_cursor: tokenstream::Cursor,
250 impl TokenCursorFrame {
251 fn new(delim_sp: Option<(Delimiter, DelimSpan)>, tts: TokenStream) -> Self {
252 TokenCursorFrame { delim_sp, tree_cursor: tts.into_trees() }
257 fn next(&mut self, desugar_doc_comments: bool) -> (Token, Spacing) {
258 self.inlined_next(desugar_doc_comments)
261 /// This always-inlined version should only be used on hot code paths.
263 fn inlined_next(&mut self, desugar_doc_comments: bool) -> (Token, Spacing) {
265 // FIXME: we currently don't return `Delimiter` open/close delims. To fix #67062 we will
266 // need to, whereupon the `delim != Delimiter::Invisible` conditions below can be
268 if let Some((tree, spacing)) = self.frame.tree_cursor.next_with_spacing_ref() {
270 &TokenTree::Token(ref token) => match (desugar_doc_comments, token) {
271 (true, &Token { kind: token::DocComment(_, attr_style, data), span }) => {
272 return self.desugar(attr_style, data, span);
274 _ => return (token.clone(), *spacing),
276 &TokenTree::Delimited(sp, delim, ref tts) => {
277 // Set `open_delim` to true here because we deal with it immediately.
278 let frame = TokenCursorFrame::new(Some((delim, sp)), tts.clone());
279 self.stack.push(mem::replace(&mut self.frame, frame));
280 if delim != Delimiter::Invisible {
281 return (Token::new(token::OpenDelim(delim), sp.open), Spacing::Alone);
283 // No open delimeter to return; continue on to the next iteration.
286 } else if let Some(frame) = self.stack.pop() {
287 if let Some((delim, span)) = self.frame.delim_sp && delim != Delimiter::Invisible {
289 return (Token::new(token::CloseDelim(delim), span.close), Spacing::Alone);
292 // No close delimiter to return; continue on to the next iteration.
294 return (Token::new(token::Eof, DUMMY_SP), Spacing::Alone);
299 fn desugar(&mut self, attr_style: AttrStyle, data: Symbol, span: Span) -> (Token, Spacing) {
300 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
301 // required to wrap the text.
302 let mut num_of_hashes = 0;
304 for ch in data.as_str().chars() {
307 '#' if count > 0 => count + 1,
310 num_of_hashes = cmp::max(num_of_hashes, count);
313 let delim_span = DelimSpan::from_single(span);
314 let body = TokenTree::Delimited(
318 TokenTree::token(token::Ident(sym::doc, false), span),
319 TokenTree::token(token::Eq, span),
320 TokenTree::token(TokenKind::lit(token::StrRaw(num_of_hashes), data, None), span),
324 .collect::<TokenStream>(),
327 self.stack.push(mem::replace(
329 TokenCursorFrame::new(
331 if attr_style == AttrStyle::Inner {
332 [TokenTree::token(token::Pound, span), TokenTree::token(token::Not, span), body]
335 .collect::<TokenStream>()
337 [TokenTree::token(token::Pound, span), body]
340 .collect::<TokenStream>()
345 self.next(/* desugar_doc_comments */ false)
349 #[derive(Debug, Clone, PartialEq)]
362 fn to_string(&self) -> String {
364 TokenType::Token(ref t) => format!("`{}`", pprust::token_kind_to_string(t)),
365 TokenType::Keyword(kw) => format!("`{}`", kw),
366 TokenType::Operator => "an operator".to_string(),
367 TokenType::Lifetime => "lifetime".to_string(),
368 TokenType::Ident => "identifier".to_string(),
369 TokenType::Path => "path".to_string(),
370 TokenType::Type => "type".to_string(),
371 TokenType::Const => "a const expression".to_string(),
376 #[derive(Copy, Clone, Debug)]
377 enum TokenExpectType {
382 /// A sequence separator.
384 /// The separator token.
385 sep: Option<TokenKind>,
386 /// `true` if a trailing separator is allowed.
387 trailing_sep_allowed: bool,
391 fn trailing_allowed(t: TokenKind) -> SeqSep {
392 SeqSep { sep: Some(t), trailing_sep_allowed: true }
395 fn none() -> SeqSep {
396 SeqSep { sep: None, trailing_sep_allowed: false }
400 pub enum FollowedByType {
405 fn token_descr_opt(token: &Token) -> Option<&'static str> {
406 Some(match token.kind {
407 _ if token.is_special_ident() => "reserved identifier",
408 _ if token.is_used_keyword() => "keyword",
409 _ if token.is_unused_keyword() => "reserved keyword",
410 token::DocComment(..) => "doc comment",
415 pub(super) fn token_descr(token: &Token) -> String {
416 let token_str = pprust::token_to_string(token);
417 match token_descr_opt(token) {
418 Some(prefix) => format!("{} `{}`", prefix, token_str),
419 _ => format!("`{}`", token_str),
423 impl<'a> Parser<'a> {
427 desugar_doc_comments: bool,
428 subparser_name: Option<&'static str>,
430 let mut parser = Parser {
432 token: Token::dummy(),
433 token_spacing: Spacing::Alone,
434 prev_token: Token::dummy(),
436 restrictions: Restrictions::empty(),
437 expected_tokens: Vec::new(),
438 token_cursor: TokenCursor {
439 frame: TokenCursorFrame::new(None, tokens),
442 desugar_doc_comments,
443 break_last_token: false,
445 desugar_doc_comments,
446 unmatched_angle_bracket_count: 0,
447 max_angle_bracket_count: 0,
448 unclosed_delims: Vec::new(),
449 last_unexpected_token_span: None,
450 last_type_ascription: None,
452 capture_state: CaptureState {
453 capturing: Capturing::No,
454 replace_ranges: Vec::new(),
455 inner_attr_ranges: Default::default(),
457 current_closure: None,
460 // Make parser point to the first token.
466 pub fn unexpected<T>(&mut self) -> PResult<'a, T> {
467 match self.expect_one_of(&[], &[]) {
469 // We can get `Ok(true)` from `recover_closing_delimiter`
470 // which is called in `expected_one_of_not_found`.
471 Ok(_) => FatalError.raise(),
475 /// Expects and consumes the token `t`. Signals an error if the next token is not `t`.
476 pub fn expect(&mut self, t: &TokenKind) -> PResult<'a, bool /* recovered */> {
477 if self.expected_tokens.is_empty() {
478 if self.token == *t {
482 self.unexpected_try_recover(t)
485 self.expect_one_of(slice::from_ref(t), &[])
489 /// Expect next token to be edible or inedible token. If edible,
490 /// then consume it; if inedible, then return without consuming
491 /// anything. Signal a fatal error if next token is unexpected.
492 pub fn expect_one_of(
494 edible: &[TokenKind],
495 inedible: &[TokenKind],
496 ) -> PResult<'a, bool /* recovered */> {
497 if edible.contains(&self.token.kind) {
500 } else if inedible.contains(&self.token.kind) {
501 // leave it in the input
503 } else if self.last_unexpected_token_span == Some(self.token.span) {
506 self.expected_one_of_not_found(edible, inedible)
510 // Public for rustfmt usage.
511 pub fn parse_ident(&mut self) -> PResult<'a, Ident> {
512 self.parse_ident_common(true)
515 fn ident_or_err(&mut self) -> PResult<'a, (Ident, /* is_raw */ bool)> {
516 self.token.ident().ok_or_else(|| match self.prev_token.kind {
517 TokenKind::DocComment(..) => {
518 self.span_err(self.prev_token.span, Error::UselessDocComment)
520 _ => self.expected_ident_found(),
524 fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, Ident> {
525 let (ident, is_raw) = self.ident_or_err()?;
526 if !is_raw && ident.is_reserved() {
527 let mut err = self.expected_ident_found();
538 /// Checks if the next token is `tok`, and returns `true` if so.
540 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
542 fn check(&mut self, tok: &TokenKind) -> bool {
543 let is_present = self.token == *tok;
545 self.expected_tokens.push(TokenType::Token(tok.clone()));
550 fn check_noexpect(&self, tok: &TokenKind) -> bool {
554 /// Consumes a token 'tok' if it exists. Returns whether the given token was present.
556 /// the main purpose of this function is to reduce the cluttering of the suggestions list
557 /// which using the normal eat method could introduce in some cases.
558 pub fn eat_noexpect(&mut self, tok: &TokenKind) -> bool {
559 let is_present = self.check_noexpect(tok);
566 /// Consumes a token 'tok' if it exists. Returns whether the given token was present.
567 pub fn eat(&mut self, tok: &TokenKind) -> bool {
568 let is_present = self.check(tok);
575 /// If the next token is the given keyword, returns `true` without eating it.
576 /// An expectation is also added for diagnostics purposes.
577 fn check_keyword(&mut self, kw: Symbol) -> bool {
578 self.expected_tokens.push(TokenType::Keyword(kw));
579 self.token.is_keyword(kw)
582 /// If the next token is the given keyword, eats it and returns `true`.
583 /// Otherwise, returns `false`. An expectation is also added for diagnostics purposes.
584 // Public for rustfmt usage.
585 pub fn eat_keyword(&mut self, kw: Symbol) -> bool {
586 if self.check_keyword(kw) {
594 fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool {
595 if self.token.is_keyword(kw) {
603 /// If the given word is not a keyword, signals an error.
604 /// If the next token is not the given word, signals an error.
605 /// Otherwise, eats it.
606 fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> {
607 if !self.eat_keyword(kw) { self.unexpected() } else { Ok(()) }
610 /// Is the given keyword `kw` followed by a non-reserved identifier?
611 fn is_kw_followed_by_ident(&self, kw: Symbol) -> bool {
612 self.token.is_keyword(kw) && self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
615 fn check_or_expected(&mut self, ok: bool, typ: TokenType) -> bool {
619 self.expected_tokens.push(typ);
624 fn check_ident(&mut self) -> bool {
625 self.check_or_expected(self.token.is_ident(), TokenType::Ident)
628 fn check_path(&mut self) -> bool {
629 self.check_or_expected(self.token.is_path_start(), TokenType::Path)
632 fn check_type(&mut self) -> bool {
633 self.check_or_expected(self.token.can_begin_type(), TokenType::Type)
636 fn check_const_arg(&mut self) -> bool {
637 self.check_or_expected(self.token.can_begin_const_arg(), TokenType::Const)
640 fn check_inline_const(&self, dist: usize) -> bool {
641 self.is_keyword_ahead(dist, &[kw::Const])
642 && self.look_ahead(dist + 1, |t| match t.kind {
643 token::Interpolated(ref nt) => matches!(**nt, token::NtBlock(..)),
644 token::OpenDelim(Delimiter::Brace) => true,
649 /// Checks to see if the next token is either `+` or `+=`.
650 /// Otherwise returns `false`.
651 fn check_plus(&mut self) -> bool {
652 self.check_or_expected(
653 self.token.is_like_plus(),
654 TokenType::Token(token::BinOp(token::Plus)),
658 /// Eats the expected token if it's present possibly breaking
659 /// compound tokens like multi-character operators in process.
660 /// Returns `true` if the token was eaten.
661 fn break_and_eat(&mut self, expected: TokenKind) -> bool {
662 if self.token.kind == expected {
666 match self.token.kind.break_two_token_op() {
667 Some((first, second)) if first == expected => {
668 let first_span = self.sess.source_map().start_point(self.token.span);
669 let second_span = self.token.span.with_lo(first_span.hi());
670 self.token = Token::new(first, first_span);
671 // Keep track of this token - if we end token capturing now,
672 // we'll want to append this token to the captured stream.
674 // If we consume any additional tokens, then this token
675 // is not needed (we'll capture the entire 'glued' token),
676 // and `bump` will set this field to `None`
677 self.token_cursor.break_last_token = true;
678 // Use the spacing of the glued token as the spacing
679 // of the unglued second token.
680 self.bump_with((Token::new(second, second_span), self.token_spacing));
684 self.expected_tokens.push(TokenType::Token(expected));
690 /// Eats `+` possibly breaking tokens like `+=` in process.
691 fn eat_plus(&mut self) -> bool {
692 self.break_and_eat(token::BinOp(token::Plus))
695 /// Eats `&` possibly breaking tokens like `&&` in process.
696 /// Signals an error if `&` is not eaten.
697 fn expect_and(&mut self) -> PResult<'a, ()> {
698 if self.break_and_eat(token::BinOp(token::And)) { Ok(()) } else { self.unexpected() }
701 /// Eats `|` possibly breaking tokens like `||` in process.
702 /// Signals an error if `|` was not eaten.
703 fn expect_or(&mut self) -> PResult<'a, ()> {
704 if self.break_and_eat(token::BinOp(token::Or)) { Ok(()) } else { self.unexpected() }
707 /// Eats `<` possibly breaking tokens like `<<` in process.
708 fn eat_lt(&mut self) -> bool {
709 let ate = self.break_and_eat(token::Lt);
711 // See doc comment for `unmatched_angle_bracket_count`.
712 self.unmatched_angle_bracket_count += 1;
713 self.max_angle_bracket_count += 1;
714 debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count);
719 /// Eats `<` possibly breaking tokens like `<<` in process.
720 /// Signals an error if `<` was not eaten.
721 fn expect_lt(&mut self) -> PResult<'a, ()> {
722 if self.eat_lt() { Ok(()) } else { self.unexpected() }
725 /// Eats `>` possibly breaking tokens like `>>` in process.
726 /// Signals an error if `>` was not eaten.
727 fn expect_gt(&mut self) -> PResult<'a, ()> {
728 if self.break_and_eat(token::Gt) {
729 // See doc comment for `unmatched_angle_bracket_count`.
730 if self.unmatched_angle_bracket_count > 0 {
731 self.unmatched_angle_bracket_count -= 1;
732 debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count);
740 fn expect_any_with_type(&mut self, kets: &[&TokenKind], expect: TokenExpectType) -> bool {
741 kets.iter().any(|k| match expect {
742 TokenExpectType::Expect => self.check(k),
743 TokenExpectType::NoExpect => self.token == **k,
747 fn parse_seq_to_before_tokens<T>(
751 expect: TokenExpectType,
752 mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
753 ) -> PResult<'a, (Vec<T>, bool /* trailing */, bool /* recovered */)> {
754 let mut first = true;
755 let mut recovered = false;
756 let mut trailing = false;
758 let unclosed_delims = !self.unclosed_delims.is_empty();
760 while !self.expect_any_with_type(kets, expect) {
761 if let token::CloseDelim(..) | token::Eof = self.token.kind {
764 if let Some(ref t) = sep.sep {
768 match self.expect(t) {
770 self.current_closure.take();
773 self.current_closure.take();
777 Err(mut expect_err) => {
778 let sp = self.prev_token.span.shrink_to_hi();
779 let token_str = pprust::token_kind_to_string(t);
781 match self.current_closure.take() {
782 Some(closure_spans) if self.token.kind == TokenKind::Semi => {
783 // Finding a semicolon instead of a comma
784 // after a closure body indicates that the
785 // closure body may be a block but the user
786 // forgot to put braces around its
789 self.recover_missing_braces_around_closure_body(
798 // Attempt to keep parsing if it was a similar separator.
799 if let Some(ref tokens) = t.similar_tokens() {
800 if tokens.contains(&self.token.kind) && !unclosed_delims {
807 // If this was a missing `@` in a binding pattern
808 // bail with a suggestion
809 // https://github.com/rust-lang/rust/issues/72373
810 if self.prev_token.is_ident() && self.token.kind == token::DotDot {
812 "if you meant to bind the contents of \
813 the rest of the array pattern into `{}`, use `@`",
814 pprust::token_to_string(&self.prev_token)
817 .span_suggestion_verbose(
818 self.prev_token.span.shrink_to_hi().until(self.token.span),
821 Applicability::MaybeIncorrect,
827 // Attempt to keep parsing if it was an omitted separator.
830 // Parsed successfully, therefore most probably the code only
831 // misses a separator.
833 .span_suggestion_short(
835 &format!("missing `{}`", token_str),
837 Applicability::MaybeIncorrect,
845 // Parsing failed, therefore it must be something more serious
846 // than just a missing separator.
857 if sep.trailing_sep_allowed && self.expect_any_with_type(kets, expect) {
866 Ok((v, trailing, recovered))
869 fn recover_missing_braces_around_closure_body(
871 closure_spans: ClosureSpans,
872 mut expect_err: DiagnosticBuilder<'_, ErrorGuaranteed>,
873 ) -> PResult<'a, ()> {
874 let initial_semicolon = self.token.span;
876 while self.eat(&TokenKind::Semi) {
877 let _ = self.parse_stmt(ForceCollect::Yes)?;
880 expect_err.set_primary_message(
881 "closure bodies that contain statements must be surrounded by braces",
884 let preceding_pipe_span = closure_spans.closing_pipe;
885 let following_token_span = self.token.span;
887 let mut first_note = MultiSpan::from(vec![initial_semicolon]);
888 first_note.push_span_label(
890 "this `;` turns the preceding closure into a statement",
892 first_note.push_span_label(
894 "this expression is a statement because of the trailing semicolon",
896 expect_err.span_note(first_note, "statement found outside of a block");
898 let mut second_note = MultiSpan::from(vec![closure_spans.whole_closure]);
899 second_note.push_span_label(closure_spans.whole_closure, "this is the parsed closure...");
900 second_note.push_span_label(
901 following_token_span,
902 "...but likely you meant the closure to end here",
904 expect_err.span_note(second_note, "the closure body may be incorrectly delimited");
906 expect_err.set_span(vec![preceding_pipe_span, following_token_span]);
908 let opening_suggestion_str = " {".to_string();
909 let closing_suggestion_str = "}".to_string();
911 expect_err.multipart_suggestion(
914 (preceding_pipe_span.shrink_to_hi(), opening_suggestion_str),
915 (following_token_span.shrink_to_lo(), closing_suggestion_str),
917 Applicability::MaybeIncorrect,
925 /// Parses a sequence, not including the closing delimiter. The function
926 /// `f` must consume tokens until reaching the next separator or
928 fn parse_seq_to_before_end<T>(
932 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
933 ) -> PResult<'a, (Vec<T>, bool, bool)> {
934 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
937 /// Parses a sequence, including the closing delimiter. The function
938 /// `f` must consume tokens until reaching the next separator or
940 fn parse_seq_to_end<T>(
944 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
945 ) -> PResult<'a, (Vec<T>, bool /* trailing */)> {
946 let (val, trailing, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
953 /// Parses a sequence, including the closing delimiter. The function
954 /// `f` must consume tokens until reaching the next separator or
956 fn parse_unspanned_seq<T>(
961 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
962 ) -> PResult<'a, (Vec<T>, bool)> {
964 self.parse_seq_to_end(ket, sep, f)
967 fn parse_delim_comma_seq<T>(
970 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
971 ) -> PResult<'a, (Vec<T>, bool)> {
972 self.parse_unspanned_seq(
973 &token::OpenDelim(delim),
974 &token::CloseDelim(delim),
975 SeqSep::trailing_allowed(token::Comma),
980 fn parse_paren_comma_seq<T>(
982 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
983 ) -> PResult<'a, (Vec<T>, bool)> {
984 self.parse_delim_comma_seq(Delimiter::Parenthesis, f)
987 /// Advance the parser by one token using provided token as the next one.
988 fn bump_with(&mut self, next: (Token, Spacing)) {
989 self.inlined_bump_with(next)
992 /// This always-inlined version should only be used on hot code paths.
994 fn inlined_bump_with(&mut self, (next_token, next_spacing): (Token, Spacing)) {
995 // Update the current and previous tokens.
996 self.prev_token = mem::replace(&mut self.token, next_token);
997 self.token_spacing = next_spacing;
1000 self.expected_tokens.clear();
1003 /// Advance the parser by one token.
1004 pub fn bump(&mut self) {
1005 // Note: destructuring here would give nicer code, but it was found in #96210 to be slower
1006 // than `.0`/`.1` access.
1007 let mut next = self.token_cursor.inlined_next(self.desugar_doc_comments);
1008 self.token_cursor.num_next_calls += 1;
1009 // We've retrieved an token from the underlying
1010 // cursor, so we no longer need to worry about
1011 // an unglued token. See `break_and_eat` for more details
1012 self.token_cursor.break_last_token = false;
1013 if next.0.span.is_dummy() {
1014 // Tweak the location for better diagnostics, but keep syntactic context intact.
1015 let fallback_span = self.token.span;
1016 next.0.span = fallback_span.with_ctxt(next.0.span.ctxt());
1018 debug_assert!(!matches!(
1020 token::OpenDelim(Delimiter::Invisible) | token::CloseDelim(Delimiter::Invisible)
1022 self.inlined_bump_with(next)
1025 /// Look-ahead `dist` tokens of `self.token` and get access to that token there.
1026 /// When `dist == 0` then the current token is looked at.
1027 pub fn look_ahead<R>(&self, dist: usize, looker: impl FnOnce(&Token) -> R) -> R {
1029 return looker(&self.token);
1032 let frame = &self.token_cursor.frame;
1033 if let Some((delim, span)) = frame.delim_sp && delim != Delimiter::Invisible {
1034 let all_normal = (0..dist).all(|i| {
1035 let token = frame.tree_cursor.look_ahead(i);
1036 !matches!(token, Some(TokenTree::Delimited(_, Delimiter::Invisible, _)))
1039 return match frame.tree_cursor.look_ahead(dist - 1) {
1040 Some(tree) => match tree {
1041 TokenTree::Token(token) => looker(token),
1042 TokenTree::Delimited(dspan, delim, _) => {
1043 looker(&Token::new(token::OpenDelim(*delim), dspan.open))
1046 None => looker(&Token::new(token::CloseDelim(delim), span.close)),
1051 let mut cursor = self.token_cursor.clone();
1053 let mut token = Token::dummy();
1055 token = cursor.next(/* desugar_doc_comments */ false).0;
1058 token::OpenDelim(Delimiter::Invisible) | token::CloseDelim(Delimiter::Invisible)
1064 return looker(&token);
1067 /// Returns whether any of the given keywords are `dist` tokens ahead of the current one.
1068 fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool {
1069 self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw)))
1072 /// Parses asyncness: `async` or nothing.
1073 fn parse_asyncness(&mut self) -> Async {
1074 if self.eat_keyword(kw::Async) {
1075 let span = self.prev_token.uninterpolated_span();
1076 Async::Yes { span, closure_id: DUMMY_NODE_ID, return_impl_trait_id: DUMMY_NODE_ID }
1082 /// Parses unsafety: `unsafe` or nothing.
1083 fn parse_unsafety(&mut self) -> Unsafe {
1084 if self.eat_keyword(kw::Unsafe) {
1085 Unsafe::Yes(self.prev_token.uninterpolated_span())
1091 /// Parses constness: `const` or nothing.
1092 fn parse_constness(&mut self) -> Const {
1093 // Avoid const blocks to be parsed as const items
1094 if self.look_ahead(1, |t| t != &token::OpenDelim(Delimiter::Brace))
1095 && self.eat_keyword(kw::Const)
1097 Const::Yes(self.prev_token.uninterpolated_span())
1103 /// Parses inline const expressions.
1104 fn parse_const_block(&mut self, span: Span, pat: bool) -> PResult<'a, P<Expr>> {
1106 self.sess.gated_spans.gate(sym::inline_const_pat, span);
1108 self.sess.gated_spans.gate(sym::inline_const, span);
1110 self.eat_keyword(kw::Const);
1111 let (attrs, blk) = self.parse_inner_attrs_and_block()?;
1112 let anon_const = AnonConst {
1114 value: self.mk_expr(blk.span, ExprKind::Block(blk, None), AttrVec::new()),
1116 let blk_span = anon_const.value.span;
1117 Ok(self.mk_expr(span.to(blk_span), ExprKind::ConstBlock(anon_const), AttrVec::from(attrs)))
1120 /// Parses mutability (`mut` or nothing).
1121 fn parse_mutability(&mut self) -> Mutability {
1122 if self.eat_keyword(kw::Mut) { Mutability::Mut } else { Mutability::Not }
1125 /// Possibly parses mutability (`const` or `mut`).
1126 fn parse_const_or_mut(&mut self) -> Option<Mutability> {
1127 if self.eat_keyword(kw::Mut) {
1128 Some(Mutability::Mut)
1129 } else if self.eat_keyword(kw::Const) {
1130 Some(Mutability::Not)
1136 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
1137 if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) = self.token.kind
1139 self.expect_no_suffix(self.token.span, "a tuple index", suffix);
1141 Ok(Ident::new(symbol, self.prev_token.span))
1143 self.parse_ident_common(true)
1147 fn parse_mac_args(&mut self) -> PResult<'a, P<MacArgs>> {
1148 self.parse_mac_args_common(true).map(P)
1151 fn parse_attr_args(&mut self) -> PResult<'a, MacArgs> {
1152 self.parse_mac_args_common(false)
1155 fn parse_mac_args_common(&mut self, delimited_only: bool) -> PResult<'a, MacArgs> {
1157 if self.check(&token::OpenDelim(Delimiter::Parenthesis))
1158 || self.check(&token::OpenDelim(Delimiter::Bracket))
1159 || self.check(&token::OpenDelim(Delimiter::Brace))
1161 match self.parse_token_tree() {
1162 TokenTree::Delimited(dspan, delim, tokens) =>
1163 // We've confirmed above that there is a delimiter so unwrapping is OK.
1165 MacArgs::Delimited(dspan, MacDelimiter::from_token(delim).unwrap(), tokens)
1167 _ => unreachable!(),
1169 } else if !delimited_only {
1170 if self.eat(&token::Eq) {
1171 let eq_span = self.prev_token.span;
1172 MacArgs::Eq(eq_span, MacArgsEq::Ast(self.parse_expr_force_collect()?))
1177 return self.unexpected();
1182 fn parse_or_use_outer_attributes(
1184 already_parsed_attrs: Option<AttrWrapper>,
1185 ) -> PResult<'a, AttrWrapper> {
1186 if let Some(attrs) = already_parsed_attrs {
1189 self.parse_outer_attributes()
1193 /// Parses a single token tree from the input.
1194 pub(crate) fn parse_token_tree(&mut self) -> TokenTree {
1195 match self.token.kind {
1196 token::OpenDelim(..) => {
1197 // Grab the tokens from this frame.
1198 let frame = &self.token_cursor.frame;
1199 let stream = frame.tree_cursor.stream.clone();
1200 let (delim, span) = frame.delim_sp.unwrap();
1202 // Advance the token cursor through the entire delimited
1203 // sequence. After getting the `OpenDelim` we are *within* the
1204 // delimited sequence, i.e. at depth `d`. After getting the
1205 // matching `CloseDelim` we are *after* the delimited sequence,
1206 // i.e. at depth `d - 1`.
1207 let target_depth = self.token_cursor.stack.len() - 1;
1209 // Advance one token at a time, so `TokenCursor::next()`
1210 // can capture these tokens if necessary.
1212 if self.token_cursor.stack.len() == target_depth {
1213 debug_assert!(matches!(self.token.kind, token::CloseDelim(_)));
1218 // Consume close delimiter
1220 TokenTree::Delimited(span, delim, stream)
1222 token::CloseDelim(_) | token::Eof => unreachable!(),
1225 TokenTree::Token(self.prev_token.clone())
1230 /// Parses a stream of tokens into a list of `TokenTree`s, up to EOF.
1231 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
1232 let mut tts = Vec::new();
1233 while self.token != token::Eof {
1234 tts.push(self.parse_token_tree());
1239 pub fn parse_tokens(&mut self) -> TokenStream {
1240 let mut result = Vec::new();
1242 match self.token.kind {
1243 token::Eof | token::CloseDelim(..) => break,
1244 _ => result.push(self.parse_token_tree().into()),
1247 TokenStream::new(result)
1250 /// Evaluates the closure with restrictions in place.
1252 /// Afters the closure is evaluated, restrictions are reset.
1253 fn with_res<T>(&mut self, res: Restrictions, f: impl FnOnce(&mut Self) -> T) -> T {
1254 let old = self.restrictions;
1255 self.restrictions = res;
1257 self.restrictions = old;
1261 /// Parses `pub` and `pub(in path)` plus shortcuts `pub(crate)` for `pub(in crate)`, `pub(self)`
1262 /// for `pub(in self)` and `pub(super)` for `pub(in super)`.
1263 /// If the following element can't be a tuple (i.e., it's a function definition), then
1264 /// it's not a tuple struct field), and the contents within the parentheses aren't valid,
1265 /// so emit a proper diagnostic.
1266 // Public for rustfmt usage.
1267 pub fn parse_visibility(&mut self, fbt: FollowedByType) -> PResult<'a, Visibility> {
1268 maybe_whole!(self, NtVis, |x| x.into_inner());
1270 if !self.eat_keyword(kw::Pub) {
1271 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
1272 // keyword to grab a span from for inherited visibility; an empty span at the
1273 // beginning of the current token would seem to be the "Schelling span".
1274 return Ok(Visibility {
1275 span: self.token.span.shrink_to_lo(),
1276 kind: VisibilityKind::Inherited,
1280 let lo = self.prev_token.span;
1282 if self.check(&token::OpenDelim(Delimiter::Parenthesis)) {
1283 // We don't `self.bump()` the `(` yet because this might be a struct definition where
1284 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
1285 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
1286 // by the following tokens.
1287 if self.is_keyword_ahead(1, &[kw::In]) {
1288 // Parse `pub(in path)`.
1290 self.bump(); // `in`
1291 let path = self.parse_path(PathStyle::Mod)?; // `path`
1292 self.expect(&token::CloseDelim(Delimiter::Parenthesis))?; // `)`
1293 let vis = VisibilityKind::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
1294 return Ok(Visibility {
1295 span: lo.to(self.prev_token.span),
1299 } else if self.look_ahead(2, |t| t == &token::CloseDelim(Delimiter::Parenthesis))
1300 && self.is_keyword_ahead(1, &[kw::Crate, kw::Super, kw::SelfLower])
1302 // Parse `pub(crate)`, `pub(self)`, or `pub(super)`.
1304 let path = self.parse_path(PathStyle::Mod)?; // `crate`/`super`/`self`
1305 self.expect(&token::CloseDelim(Delimiter::Parenthesis))?; // `)`
1306 let vis = VisibilityKind::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
1307 return Ok(Visibility {
1308 span: lo.to(self.prev_token.span),
1312 } else if let FollowedByType::No = fbt {
1313 // Provide this diagnostic if a type cannot follow;
1314 // in particular, if this is not a tuple struct.
1315 self.recover_incorrect_vis_restriction()?;
1316 // Emit diagnostic, but continue with public visibility.
1320 Ok(Visibility { span: lo, kind: VisibilityKind::Public, tokens: None })
1323 /// Recovery for e.g. `pub(something) fn ...` or `struct X { pub(something) y: Z }`
1324 fn recover_incorrect_vis_restriction(&mut self) -> PResult<'a, ()> {
1326 let path = self.parse_path(PathStyle::Mod)?;
1327 self.expect(&token::CloseDelim(Delimiter::Parenthesis))?; // `)`
1329 let msg = "incorrect visibility restriction";
1330 let suggestion = r##"some possible visibility restrictions are:
1331 `pub(crate)`: visible only on the current crate
1332 `pub(super)`: visible only in the current module's parent
1333 `pub(in path::to::module)`: visible only on the specified path"##;
1335 let path_str = pprust::path_to_string(&path);
1337 struct_span_err!(self.sess.span_diagnostic, path.span, E0704, "{}", msg)
1341 &format!("make this visible only to module `{}` with `in`", path_str),
1342 format!("in {}", path_str),
1343 Applicability::MachineApplicable,
1350 /// Parses `extern string_literal?`.
1351 fn parse_extern(&mut self) -> Extern {
1352 if self.eat_keyword(kw::Extern) { Extern::from_abi(self.parse_abi()) } else { Extern::None }
1355 /// Parses a string literal as an ABI spec.
1356 fn parse_abi(&mut self) -> Option<StrLit> {
1357 match self.parse_str_lit() {
1358 Ok(str_lit) => Some(str_lit),
1359 Err(Some(lit)) => match lit.kind {
1360 ast::LitKind::Err(_) => None,
1362 self.struct_span_err(lit.span, "non-string ABI literal")
1365 "specify the ABI with a string literal",
1367 Applicability::MaybeIncorrect,
1377 pub fn collect_tokens_no_attrs<R: HasAttrs + HasTokens>(
1379 f: impl FnOnce(&mut Self) -> PResult<'a, R>,
1380 ) -> PResult<'a, R> {
1381 // The only reason to call `collect_tokens_no_attrs` is if you want tokens, so use
1382 // `ForceCollect::Yes`
1383 self.collect_tokens_trailing_token(
1384 AttrWrapper::empty(),
1386 |this, _attrs| Ok((f(this)?, TrailingToken::None)),
1391 fn is_import_coupler(&mut self) -> bool {
1392 self.check(&token::ModSep)
1393 && self.look_ahead(1, |t| {
1394 *t == token::OpenDelim(Delimiter::Brace) || *t == token::BinOp(token::Star)
1398 pub fn clear_expected_tokens(&mut self) {
1399 self.expected_tokens.clear();
1403 pub(crate) fn make_unclosed_delims_error(
1404 unmatched: UnmatchedBrace,
1406 ) -> Option<DiagnosticBuilder<'_, ErrorGuaranteed>> {
1407 // `None` here means an `Eof` was found. We already emit those errors elsewhere, we add them to
1408 // `unmatched_braces` only for error recovery in the `Parser`.
1409 let found_delim = unmatched.found_delim?;
1410 let span: MultiSpan = if let Some(sp) = unmatched.unclosed_span {
1411 vec![unmatched.found_span, sp].into()
1413 unmatched.found_span.into()
1415 let mut err = sess.span_diagnostic.struct_span_err(
1418 "mismatched closing delimiter: `{}`",
1419 pprust::token_kind_to_string(&token::CloseDelim(found_delim)),
1422 err.span_label(unmatched.found_span, "mismatched closing delimiter");
1423 if let Some(sp) = unmatched.candidate_span {
1424 err.span_label(sp, "closing delimiter possibly meant for this");
1426 if let Some(sp) = unmatched.unclosed_span {
1427 err.span_label(sp, "unclosed delimiter");
1432 pub fn emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedBrace>, sess: &ParseSess) {
1433 *sess.reached_eof.borrow_mut() |=
1434 unclosed_delims.iter().any(|unmatched_delim| unmatched_delim.found_delim.is_none());
1435 for unmatched in unclosed_delims.drain(..) {
1436 if let Some(mut e) = make_unclosed_delims_error(unmatched, sess) {
1442 /// A helper struct used when building an `AttrAnnotatedTokenStream` from
1443 /// a `LazyTokenStream`. Both delimiter and non-delimited tokens
1444 /// are stored as `FlatToken::Token`. A vector of `FlatToken`s
1445 /// is then 'parsed' to build up an `AttrAnnotatedTokenStream` with nested
1446 /// `AttrAnnotatedTokenTree::Delimited` tokens
1447 #[derive(Debug, Clone)]
1448 pub enum FlatToken {
1449 /// A token - this holds both delimiter (e.g. '{' and '}')
1450 /// and non-delimiter tokens
1452 /// Holds the `AttributesData` for an AST node. The
1453 /// `AttributesData` is inserted directly into the
1454 /// constructed `AttrAnnotatedTokenStream` as
1455 /// an `AttrAnnotatedTokenTree::Attributes`
1456 AttrTarget(AttributesData),
1457 /// A special 'empty' token that is ignored during the conversion
1458 /// to an `AttrAnnotatedTokenStream`. This is used to simplify the
1459 /// handling of replace ranges.