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, AstLike, AttrStyle, AttrVec, Const, CrateSugar, Extern};
29 use rustc_ast::{Async, Expr, ExprKind, MacArgs, MacArgsEq, MacDelimiter, Mutability, StrLit};
30 use rustc_ast::{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 /// Consumes a token 'tok' if it exists. Returns whether the given token was present.
551 pub fn eat(&mut self, tok: &TokenKind) -> bool {
552 let is_present = self.check(tok);
559 /// If the next token is the given keyword, returns `true` without eating it.
560 /// An expectation is also added for diagnostics purposes.
561 fn check_keyword(&mut self, kw: Symbol) -> bool {
562 self.expected_tokens.push(TokenType::Keyword(kw));
563 self.token.is_keyword(kw)
566 /// If the next token is the given keyword, eats it and returns `true`.
567 /// Otherwise, returns `false`. An expectation is also added for diagnostics purposes.
568 // Public for rustfmt usage.
569 pub fn eat_keyword(&mut self, kw: Symbol) -> bool {
570 if self.check_keyword(kw) {
578 fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool {
579 if self.token.is_keyword(kw) {
587 /// If the given word is not a keyword, signals an error.
588 /// If the next token is not the given word, signals an error.
589 /// Otherwise, eats it.
590 fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> {
591 if !self.eat_keyword(kw) { self.unexpected() } else { Ok(()) }
594 /// Is the given keyword `kw` followed by a non-reserved identifier?
595 fn is_kw_followed_by_ident(&self, kw: Symbol) -> bool {
596 self.token.is_keyword(kw) && self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
599 fn check_or_expected(&mut self, ok: bool, typ: TokenType) -> bool {
603 self.expected_tokens.push(typ);
608 fn check_ident(&mut self) -> bool {
609 self.check_or_expected(self.token.is_ident(), TokenType::Ident)
612 fn check_path(&mut self) -> bool {
613 self.check_or_expected(self.token.is_path_start(), TokenType::Path)
616 fn check_type(&mut self) -> bool {
617 self.check_or_expected(self.token.can_begin_type(), TokenType::Type)
620 fn check_const_arg(&mut self) -> bool {
621 self.check_or_expected(self.token.can_begin_const_arg(), TokenType::Const)
624 fn check_inline_const(&self, dist: usize) -> bool {
625 self.is_keyword_ahead(dist, &[kw::Const])
626 && self.look_ahead(dist + 1, |t| match t.kind {
627 token::Interpolated(ref nt) => matches!(**nt, token::NtBlock(..)),
628 token::OpenDelim(Delimiter::Brace) => true,
633 /// Checks to see if the next token is either `+` or `+=`.
634 /// Otherwise returns `false`.
635 fn check_plus(&mut self) -> bool {
636 self.check_or_expected(
637 self.token.is_like_plus(),
638 TokenType::Token(token::BinOp(token::Plus)),
642 /// Eats the expected token if it's present possibly breaking
643 /// compound tokens like multi-character operators in process.
644 /// Returns `true` if the token was eaten.
645 fn break_and_eat(&mut self, expected: TokenKind) -> bool {
646 if self.token.kind == expected {
650 match self.token.kind.break_two_token_op() {
651 Some((first, second)) if first == expected => {
652 let first_span = self.sess.source_map().start_point(self.token.span);
653 let second_span = self.token.span.with_lo(first_span.hi());
654 self.token = Token::new(first, first_span);
655 // Keep track of this token - if we end token capturing now,
656 // we'll want to append this token to the captured stream.
658 // If we consume any additional tokens, then this token
659 // is not needed (we'll capture the entire 'glued' token),
660 // and `bump` will set this field to `None`
661 self.token_cursor.break_last_token = true;
662 // Use the spacing of the glued token as the spacing
663 // of the unglued second token.
664 self.bump_with((Token::new(second, second_span), self.token_spacing));
668 self.expected_tokens.push(TokenType::Token(expected));
674 /// Eats `+` possibly breaking tokens like `+=` in process.
675 fn eat_plus(&mut self) -> bool {
676 self.break_and_eat(token::BinOp(token::Plus))
679 /// Eats `&` possibly breaking tokens like `&&` in process.
680 /// Signals an error if `&` is not eaten.
681 fn expect_and(&mut self) -> PResult<'a, ()> {
682 if self.break_and_eat(token::BinOp(token::And)) { Ok(()) } else { self.unexpected() }
685 /// Eats `|` possibly breaking tokens like `||` in process.
686 /// Signals an error if `|` was not eaten.
687 fn expect_or(&mut self) -> PResult<'a, ()> {
688 if self.break_and_eat(token::BinOp(token::Or)) { Ok(()) } else { self.unexpected() }
691 /// Eats `<` possibly breaking tokens like `<<` in process.
692 fn eat_lt(&mut self) -> bool {
693 let ate = self.break_and_eat(token::Lt);
695 // See doc comment for `unmatched_angle_bracket_count`.
696 self.unmatched_angle_bracket_count += 1;
697 self.max_angle_bracket_count += 1;
698 debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count);
703 /// Eats `<` possibly breaking tokens like `<<` in process.
704 /// Signals an error if `<` was not eaten.
705 fn expect_lt(&mut self) -> PResult<'a, ()> {
706 if self.eat_lt() { Ok(()) } else { self.unexpected() }
709 /// Eats `>` possibly breaking tokens like `>>` in process.
710 /// Signals an error if `>` was not eaten.
711 fn expect_gt(&mut self) -> PResult<'a, ()> {
712 if self.break_and_eat(token::Gt) {
713 // See doc comment for `unmatched_angle_bracket_count`.
714 if self.unmatched_angle_bracket_count > 0 {
715 self.unmatched_angle_bracket_count -= 1;
716 debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count);
724 fn expect_any_with_type(&mut self, kets: &[&TokenKind], expect: TokenExpectType) -> bool {
725 kets.iter().any(|k| match expect {
726 TokenExpectType::Expect => self.check(k),
727 TokenExpectType::NoExpect => self.token == **k,
731 fn parse_seq_to_before_tokens<T>(
735 expect: TokenExpectType,
736 mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
737 ) -> PResult<'a, (Vec<T>, bool /* trailing */, bool /* recovered */)> {
738 let mut first = true;
739 let mut recovered = false;
740 let mut trailing = false;
742 let unclosed_delims = !self.unclosed_delims.is_empty();
744 while !self.expect_any_with_type(kets, expect) {
745 if let token::CloseDelim(..) | token::Eof = self.token.kind {
748 if let Some(ref t) = sep.sep {
752 match self.expect(t) {
754 self.current_closure.take();
757 self.current_closure.take();
761 Err(mut expect_err) => {
762 let sp = self.prev_token.span.shrink_to_hi();
763 let token_str = pprust::token_kind_to_string(t);
765 match self.current_closure.take() {
766 Some(closure_spans) if self.token.kind == TokenKind::Semi => {
767 // Finding a semicolon instead of a comma
768 // after a closure body indicates that the
769 // closure body may be a block but the user
770 // forgot to put braces around its
773 self.recover_missing_braces_around_closure_body(
782 // Attempt to keep parsing if it was a similar separator.
783 if let Some(ref tokens) = t.similar_tokens() {
784 if tokens.contains(&self.token.kind) && !unclosed_delims {
791 // If this was a missing `@` in a binding pattern
792 // bail with a suggestion
793 // https://github.com/rust-lang/rust/issues/72373
794 if self.prev_token.is_ident() && self.token.kind == token::DotDot {
796 "if you meant to bind the contents of \
797 the rest of the array pattern into `{}`, use `@`",
798 pprust::token_to_string(&self.prev_token)
801 .span_suggestion_verbose(
802 self.prev_token.span.shrink_to_hi().until(self.token.span),
805 Applicability::MaybeIncorrect,
811 // Attempt to keep parsing if it was an omitted separator.
814 // Parsed successfully, therefore most probably the code only
815 // misses a separator.
817 .span_suggestion_short(
819 &format!("missing `{}`", token_str),
821 Applicability::MaybeIncorrect,
829 // Parsing failed, therefore it must be something more serious
830 // than just a missing separator.
841 if sep.trailing_sep_allowed && self.expect_any_with_type(kets, expect) {
850 Ok((v, trailing, recovered))
853 fn recover_missing_braces_around_closure_body(
855 closure_spans: ClosureSpans,
856 mut expect_err: DiagnosticBuilder<'_, ErrorGuaranteed>,
857 ) -> PResult<'a, ()> {
858 let initial_semicolon = self.token.span;
860 while self.eat(&TokenKind::Semi) {
861 let _ = self.parse_stmt(ForceCollect::Yes)?;
864 expect_err.set_primary_message(
865 "closure bodies that contain statements must be surrounded by braces",
868 let preceding_pipe_span = closure_spans.closing_pipe;
869 let following_token_span = self.token.span;
871 let mut first_note = MultiSpan::from(vec![initial_semicolon]);
872 first_note.push_span_label(
874 "this `;` turns the preceding closure into a statement".to_string(),
876 first_note.push_span_label(
878 "this expression is a statement because of the trailing semicolon".to_string(),
880 expect_err.span_note(first_note, "statement found outside of a block");
882 let mut second_note = MultiSpan::from(vec![closure_spans.whole_closure]);
883 second_note.push_span_label(
884 closure_spans.whole_closure,
885 "this is the parsed closure...".to_string(),
887 second_note.push_span_label(
888 following_token_span,
889 "...but likely you meant the closure to end here".to_string(),
891 expect_err.span_note(second_note, "the closure body may be incorrectly delimited");
893 expect_err.set_span(vec![preceding_pipe_span, following_token_span]);
895 let opening_suggestion_str = " {".to_string();
896 let closing_suggestion_str = "}".to_string();
898 expect_err.multipart_suggestion(
901 (preceding_pipe_span.shrink_to_hi(), opening_suggestion_str),
902 (following_token_span.shrink_to_lo(), closing_suggestion_str),
904 Applicability::MaybeIncorrect,
912 /// Parses a sequence, not including the closing delimiter. The function
913 /// `f` must consume tokens until reaching the next separator or
915 fn parse_seq_to_before_end<T>(
919 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
920 ) -> PResult<'a, (Vec<T>, bool, bool)> {
921 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
924 /// Parses a sequence, including the closing delimiter. The function
925 /// `f` must consume tokens until reaching the next separator or
927 fn parse_seq_to_end<T>(
931 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
932 ) -> PResult<'a, (Vec<T>, bool /* trailing */)> {
933 let (val, trailing, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
940 /// Parses a sequence, including the closing delimiter. The function
941 /// `f` must consume tokens until reaching the next separator or
943 fn parse_unspanned_seq<T>(
948 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
949 ) -> PResult<'a, (Vec<T>, bool)> {
951 self.parse_seq_to_end(ket, sep, f)
954 fn parse_delim_comma_seq<T>(
957 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
958 ) -> PResult<'a, (Vec<T>, bool)> {
959 self.parse_unspanned_seq(
960 &token::OpenDelim(delim),
961 &token::CloseDelim(delim),
962 SeqSep::trailing_allowed(token::Comma),
967 fn parse_paren_comma_seq<T>(
969 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
970 ) -> PResult<'a, (Vec<T>, bool)> {
971 self.parse_delim_comma_seq(Delimiter::Parenthesis, f)
974 /// Advance the parser by one token using provided token as the next one.
975 fn bump_with(&mut self, next: (Token, Spacing)) {
976 self.inlined_bump_with(next)
979 /// This always-inlined version should only be used on hot code paths.
981 fn inlined_bump_with(&mut self, (next_token, next_spacing): (Token, Spacing)) {
982 // Update the current and previous tokens.
983 self.prev_token = mem::replace(&mut self.token, next_token);
984 self.token_spacing = next_spacing;
987 self.expected_tokens.clear();
990 /// Advance the parser by one token.
991 pub fn bump(&mut self) {
992 // Note: destructuring here would give nicer code, but it was found in #96210 to be slower
993 // than `.0`/`.1` access.
994 let mut next = self.token_cursor.inlined_next(self.desugar_doc_comments);
995 self.token_cursor.num_next_calls += 1;
996 // We've retrieved an token from the underlying
997 // cursor, so we no longer need to worry about
998 // an unglued token. See `break_and_eat` for more details
999 self.token_cursor.break_last_token = false;
1000 if next.0.span.is_dummy() {
1001 // Tweak the location for better diagnostics, but keep syntactic context intact.
1002 let fallback_span = self.token.span;
1003 next.0.span = fallback_span.with_ctxt(next.0.span.ctxt());
1005 debug_assert!(!matches!(
1007 token::OpenDelim(Delimiter::Invisible) | token::CloseDelim(Delimiter::Invisible)
1009 self.inlined_bump_with(next)
1012 /// Look-ahead `dist` tokens of `self.token` and get access to that token there.
1013 /// When `dist == 0` then the current token is looked at.
1014 pub fn look_ahead<R>(&self, dist: usize, looker: impl FnOnce(&Token) -> R) -> R {
1016 return looker(&self.token);
1019 let frame = &self.token_cursor.frame;
1020 if let Some((delim, span)) = frame.delim_sp && delim != Delimiter::Invisible {
1021 let all_normal = (0..dist).all(|i| {
1022 let token = frame.tree_cursor.look_ahead(i);
1023 !matches!(token, Some(TokenTree::Delimited(_, Delimiter::Invisible, _)))
1026 return match frame.tree_cursor.look_ahead(dist - 1) {
1027 Some(tree) => match tree {
1028 TokenTree::Token(token) => looker(token),
1029 TokenTree::Delimited(dspan, delim, _) => {
1030 looker(&Token::new(token::OpenDelim(*delim), dspan.open))
1033 None => looker(&Token::new(token::CloseDelim(delim), span.close)),
1038 let mut cursor = self.token_cursor.clone();
1040 let mut token = Token::dummy();
1042 token = cursor.next(/* desugar_doc_comments */ false).0;
1045 token::OpenDelim(Delimiter::Invisible) | token::CloseDelim(Delimiter::Invisible)
1051 return looker(&token);
1054 /// Returns whether any of the given keywords are `dist` tokens ahead of the current one.
1055 fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool {
1056 self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw)))
1059 /// Parses asyncness: `async` or nothing.
1060 fn parse_asyncness(&mut self) -> Async {
1061 if self.eat_keyword(kw::Async) {
1062 let span = self.prev_token.uninterpolated_span();
1063 Async::Yes { span, closure_id: DUMMY_NODE_ID, return_impl_trait_id: DUMMY_NODE_ID }
1069 /// Parses unsafety: `unsafe` or nothing.
1070 fn parse_unsafety(&mut self) -> Unsafe {
1071 if self.eat_keyword(kw::Unsafe) {
1072 Unsafe::Yes(self.prev_token.uninterpolated_span())
1078 /// Parses constness: `const` or nothing.
1079 fn parse_constness(&mut self) -> Const {
1080 // Avoid const blocks to be parsed as const items
1081 if self.look_ahead(1, |t| t != &token::OpenDelim(Delimiter::Brace))
1082 && self.eat_keyword(kw::Const)
1084 Const::Yes(self.prev_token.uninterpolated_span())
1090 /// Parses inline const expressions.
1091 fn parse_const_block(&mut self, span: Span, pat: bool) -> PResult<'a, P<Expr>> {
1093 self.sess.gated_spans.gate(sym::inline_const_pat, span);
1095 self.sess.gated_spans.gate(sym::inline_const, span);
1097 self.eat_keyword(kw::Const);
1098 let (attrs, blk) = self.parse_inner_attrs_and_block()?;
1099 let anon_const = AnonConst {
1101 value: self.mk_expr(blk.span, ExprKind::Block(blk, None), AttrVec::new()),
1103 let blk_span = anon_const.value.span;
1104 Ok(self.mk_expr(span.to(blk_span), ExprKind::ConstBlock(anon_const), AttrVec::from(attrs)))
1107 /// Parses mutability (`mut` or nothing).
1108 fn parse_mutability(&mut self) -> Mutability {
1109 if self.eat_keyword(kw::Mut) { Mutability::Mut } else { Mutability::Not }
1112 /// Possibly parses mutability (`const` or `mut`).
1113 fn parse_const_or_mut(&mut self) -> Option<Mutability> {
1114 if self.eat_keyword(kw::Mut) {
1115 Some(Mutability::Mut)
1116 } else if self.eat_keyword(kw::Const) {
1117 Some(Mutability::Not)
1123 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
1124 if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) = self.token.kind
1126 self.expect_no_suffix(self.token.span, "a tuple index", suffix);
1128 Ok(Ident::new(symbol, self.prev_token.span))
1130 self.parse_ident_common(true)
1134 fn parse_mac_args(&mut self) -> PResult<'a, P<MacArgs>> {
1135 self.parse_mac_args_common(true).map(P)
1138 fn parse_attr_args(&mut self) -> PResult<'a, MacArgs> {
1139 self.parse_mac_args_common(false)
1142 fn parse_mac_args_common(&mut self, delimited_only: bool) -> PResult<'a, MacArgs> {
1144 if self.check(&token::OpenDelim(Delimiter::Parenthesis))
1145 || self.check(&token::OpenDelim(Delimiter::Bracket))
1146 || self.check(&token::OpenDelim(Delimiter::Brace))
1148 match self.parse_token_tree() {
1149 TokenTree::Delimited(dspan, delim, tokens) =>
1150 // We've confirmed above that there is a delimiter so unwrapping is OK.
1152 MacArgs::Delimited(dspan, MacDelimiter::from_token(delim).unwrap(), tokens)
1154 _ => unreachable!(),
1156 } else if !delimited_only {
1157 if self.eat(&token::Eq) {
1158 let eq_span = self.prev_token.span;
1159 MacArgs::Eq(eq_span, MacArgsEq::Ast(self.parse_expr_force_collect()?))
1164 return self.unexpected();
1169 fn parse_or_use_outer_attributes(
1171 already_parsed_attrs: Option<AttrWrapper>,
1172 ) -> PResult<'a, AttrWrapper> {
1173 if let Some(attrs) = already_parsed_attrs {
1176 self.parse_outer_attributes()
1180 /// Parses a single token tree from the input.
1181 pub(crate) fn parse_token_tree(&mut self) -> TokenTree {
1182 match self.token.kind {
1183 token::OpenDelim(..) => {
1184 // Grab the tokens from this frame.
1185 let frame = &self.token_cursor.frame;
1186 let stream = frame.tree_cursor.stream.clone();
1187 let (delim, span) = frame.delim_sp.unwrap();
1189 // Advance the token cursor through the entire delimited
1190 // sequence. After getting the `OpenDelim` we are *within* the
1191 // delimited sequence, i.e. at depth `d`. After getting the
1192 // matching `CloseDelim` we are *after* the delimited sequence,
1193 // i.e. at depth `d - 1`.
1194 let target_depth = self.token_cursor.stack.len() - 1;
1196 // Advance one token at a time, so `TokenCursor::next()`
1197 // can capture these tokens if necessary.
1199 if self.token_cursor.stack.len() == target_depth {
1200 debug_assert!(matches!(self.token.kind, token::CloseDelim(_)));
1205 // Consume close delimiter
1207 TokenTree::Delimited(span, delim, stream)
1209 token::CloseDelim(_) | token::Eof => unreachable!(),
1212 TokenTree::Token(self.prev_token.clone())
1217 /// Parses a stream of tokens into a list of `TokenTree`s, up to EOF.
1218 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
1219 let mut tts = Vec::new();
1220 while self.token != token::Eof {
1221 tts.push(self.parse_token_tree());
1226 pub fn parse_tokens(&mut self) -> TokenStream {
1227 let mut result = Vec::new();
1229 match self.token.kind {
1230 token::Eof | token::CloseDelim(..) => break,
1231 _ => result.push(self.parse_token_tree().into()),
1234 TokenStream::new(result)
1237 /// Evaluates the closure with restrictions in place.
1239 /// Afters the closure is evaluated, restrictions are reset.
1240 fn with_res<T>(&mut self, res: Restrictions, f: impl FnOnce(&mut Self) -> T) -> T {
1241 let old = self.restrictions;
1242 self.restrictions = res;
1244 self.restrictions = old;
1248 fn is_crate_vis(&self) -> bool {
1249 self.token.is_keyword(kw::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
1252 /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`,
1253 /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`.
1254 /// If the following element can't be a tuple (i.e., it's a function definition), then
1255 /// it's not a tuple struct field), and the contents within the parentheses aren't valid,
1256 /// so emit a proper diagnostic.
1257 // Public for rustfmt usage.
1258 pub fn parse_visibility(&mut self, fbt: FollowedByType) -> PResult<'a, Visibility> {
1259 maybe_whole!(self, NtVis, |x| x.into_inner());
1261 self.expected_tokens.push(TokenType::Keyword(kw::Crate));
1262 if self.is_crate_vis() {
1263 self.bump(); // `crate`
1264 self.sess.gated_spans.gate(sym::crate_visibility_modifier, self.prev_token.span);
1265 return Ok(Visibility {
1266 span: self.prev_token.span,
1267 kind: VisibilityKind::Crate(CrateSugar::JustCrate),
1272 if !self.eat_keyword(kw::Pub) {
1273 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
1274 // keyword to grab a span from for inherited visibility; an empty span at the
1275 // beginning of the current token would seem to be the "Schelling span".
1276 return Ok(Visibility {
1277 span: self.token.span.shrink_to_lo(),
1278 kind: VisibilityKind::Inherited,
1282 let lo = self.prev_token.span;
1284 if self.check(&token::OpenDelim(Delimiter::Parenthesis)) {
1285 // We don't `self.bump()` the `(` yet because this might be a struct definition where
1286 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
1287 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
1288 // by the following tokens.
1289 if self.is_keyword_ahead(1, &[kw::Crate]) && self.look_ahead(2, |t| t != &token::ModSep)
1290 // account for `pub(crate::foo)`
1292 // Parse `pub(crate)`.
1294 self.bump(); // `crate`
1295 self.expect(&token::CloseDelim(Delimiter::Parenthesis))?; // `)`
1296 let vis = VisibilityKind::Crate(CrateSugar::PubCrate);
1297 return Ok(Visibility {
1298 span: lo.to(self.prev_token.span),
1302 } else if self.is_keyword_ahead(1, &[kw::In]) {
1303 // Parse `pub(in path)`.
1305 self.bump(); // `in`
1306 let path = self.parse_path(PathStyle::Mod)?; // `path`
1307 self.expect(&token::CloseDelim(Delimiter::Parenthesis))?; // `)`
1308 let vis = VisibilityKind::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
1309 return Ok(Visibility {
1310 span: lo.to(self.prev_token.span),
1314 } else if self.look_ahead(2, |t| t == &token::CloseDelim(Delimiter::Parenthesis))
1315 && self.is_keyword_ahead(1, &[kw::Super, kw::SelfLower])
1317 // Parse `pub(self)` or `pub(super)`.
1319 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
1320 self.expect(&token::CloseDelim(Delimiter::Parenthesis))?; // `)`
1321 let vis = VisibilityKind::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
1322 return Ok(Visibility {
1323 span: lo.to(self.prev_token.span),
1327 } else if let FollowedByType::No = fbt {
1328 // Provide this diagnostic if a type cannot follow;
1329 // in particular, if this is not a tuple struct.
1330 self.recover_incorrect_vis_restriction()?;
1331 // Emit diagnostic, but continue with public visibility.
1335 Ok(Visibility { span: lo, kind: VisibilityKind::Public, tokens: None })
1338 /// Recovery for e.g. `pub(something) fn ...` or `struct X { pub(something) y: Z }`
1339 fn recover_incorrect_vis_restriction(&mut self) -> PResult<'a, ()> {
1341 let path = self.parse_path(PathStyle::Mod)?;
1342 self.expect(&token::CloseDelim(Delimiter::Parenthesis))?; // `)`
1344 let msg = "incorrect visibility restriction";
1345 let suggestion = r##"some possible visibility restrictions are:
1346 `pub(crate)`: visible only on the current crate
1347 `pub(super)`: visible only in the current module's parent
1348 `pub(in path::to::module)`: visible only on the specified path"##;
1350 let path_str = pprust::path_to_string(&path);
1352 struct_span_err!(self.sess.span_diagnostic, path.span, E0704, "{}", msg)
1356 &format!("make this visible only to module `{}` with `in`", path_str),
1357 format!("in {}", path_str),
1358 Applicability::MachineApplicable,
1365 /// Parses `extern string_literal?`.
1366 fn parse_extern(&mut self) -> Extern {
1367 if self.eat_keyword(kw::Extern) { Extern::from_abi(self.parse_abi()) } else { Extern::None }
1370 /// Parses a string literal as an ABI spec.
1371 fn parse_abi(&mut self) -> Option<StrLit> {
1372 match self.parse_str_lit() {
1373 Ok(str_lit) => Some(str_lit),
1374 Err(Some(lit)) => match lit.kind {
1375 ast::LitKind::Err(_) => None,
1377 self.struct_span_err(lit.span, "non-string ABI literal")
1380 "specify the ABI with a string literal",
1381 "\"C\"".to_string(),
1382 Applicability::MaybeIncorrect,
1392 pub fn collect_tokens_no_attrs<R: AstLike>(
1394 f: impl FnOnce(&mut Self) -> PResult<'a, R>,
1395 ) -> PResult<'a, R> {
1396 // The only reason to call `collect_tokens_no_attrs` is if you want tokens, so use
1397 // `ForceCollect::Yes`
1398 self.collect_tokens_trailing_token(
1399 AttrWrapper::empty(),
1401 |this, _attrs| Ok((f(this)?, TrailingToken::None)),
1406 fn is_import_coupler(&mut self) -> bool {
1407 self.check(&token::ModSep)
1408 && self.look_ahead(1, |t| {
1409 *t == token::OpenDelim(Delimiter::Brace) || *t == token::BinOp(token::Star)
1413 pub fn clear_expected_tokens(&mut self) {
1414 self.expected_tokens.clear();
1418 crate fn make_unclosed_delims_error(
1419 unmatched: UnmatchedBrace,
1421 ) -> Option<DiagnosticBuilder<'_, ErrorGuaranteed>> {
1422 // `None` here means an `Eof` was found. We already emit those errors elsewhere, we add them to
1423 // `unmatched_braces` only for error recovery in the `Parser`.
1424 let found_delim = unmatched.found_delim?;
1425 let span: MultiSpan = if let Some(sp) = unmatched.unclosed_span {
1426 vec![unmatched.found_span, sp].into()
1428 unmatched.found_span.into()
1430 let mut err = sess.span_diagnostic.struct_span_err(
1433 "mismatched closing delimiter: `{}`",
1434 pprust::token_kind_to_string(&token::CloseDelim(found_delim)),
1437 err.span_label(unmatched.found_span, "mismatched closing delimiter");
1438 if let Some(sp) = unmatched.candidate_span {
1439 err.span_label(sp, "closing delimiter possibly meant for this");
1441 if let Some(sp) = unmatched.unclosed_span {
1442 err.span_label(sp, "unclosed delimiter");
1447 pub fn emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedBrace>, sess: &ParseSess) {
1448 *sess.reached_eof.borrow_mut() |=
1449 unclosed_delims.iter().any(|unmatched_delim| unmatched_delim.found_delim.is_none());
1450 for unmatched in unclosed_delims.drain(..) {
1451 if let Some(mut e) = make_unclosed_delims_error(unmatched, sess) {
1457 /// A helper struct used when building an `AttrAnnotatedTokenStream` from
1458 /// a `LazyTokenStream`. Both delimiter and non-delimited tokens
1459 /// are stored as `FlatToken::Token`. A vector of `FlatToken`s
1460 /// is then 'parsed' to build up an `AttrAnnotatedTokenStream` with nested
1461 /// `AttrAnnotatedTokenTree::Delimited` tokens
1462 #[derive(Debug, Clone)]
1463 pub enum FlatToken {
1464 /// A token - this holds both delimiter (e.g. '{' and '}')
1465 /// and non-delimiter tokens
1467 /// Holds the `AttributesData` for an AST node. The
1468 /// `AttributesData` is inserted directly into the
1469 /// constructed `AttrAnnotatedTokenStream` as
1470 /// an `AttrAnnotatedTokenTree::Attributes`
1471 AttrTarget(AttributesData),
1472 /// A special 'empty' token that is ignored during the conversion
1473 /// to an `AttrAnnotatedTokenStream`. This is used to simplify the
1474 /// handling of replace ranges.