• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 pub mod attr;
2 mod attr_wrapper;
3 mod diagnostics;
4 mod expr;
5 mod generics;
6 mod item;
7 mod nonterminal;
8 mod pat;
9 mod path;
10 mod stmt;
11 mod ty;
12 
13 use crate::lexer::UnmatchedDelim;
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;
19 
20 use rustc_ast::ptr::P;
21 use rustc_ast::token::{self, Delimiter, Nonterminal, Token, TokenKind};
22 use rustc_ast::tokenstream::{AttributesData, DelimSpan, Spacing};
23 use rustc_ast::tokenstream::{TokenStream, TokenTree, TokenTreeCursor};
24 use rustc_ast::util::case::Case;
25 use rustc_ast::AttrId;
26 use rustc_ast::DUMMY_NODE_ID;
27 use rustc_ast::{self as ast, AnonConst, AttrStyle, Const, DelimArgs, Extern};
28 use rustc_ast::{Async, AttrArgs, AttrArgsEq, Expr, ExprKind, 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_data_structures::sync::Ordering;
33 use rustc_errors::PResult;
34 use rustc_errors::{
35     Applicability, DiagnosticBuilder, ErrorGuaranteed, FatalError, IntoDiagnostic, MultiSpan,
36 };
37 use rustc_session::parse::ParseSess;
38 use rustc_span::source_map::{Span, DUMMY_SP};
39 use rustc_span::symbol::{kw, sym, Ident, Symbol};
40 use std::ops::Range;
41 use std::{cmp, mem, slice};
42 use thin_vec::ThinVec;
43 use tracing::debug;
44 
45 use crate::errors::{
46     self, IncorrectVisibilityRestriction, MismatchedClosingDelimiter, NonStringAbiLiteral,
47 };
48 
49 bitflags::bitflags! {
50     struct Restrictions: u8 {
51         const STMT_EXPR         = 1 << 0;
52         const NO_STRUCT_LITERAL = 1 << 1;
53         const CONST_EXPR        = 1 << 2;
54         const ALLOW_LET         = 1 << 3;
55     }
56 }
57 
58 #[derive(Clone, Copy, PartialEq, Debug)]
59 enum SemiColonMode {
60     Break,
61     Ignore,
62     Comma,
63 }
64 
65 #[derive(Clone, Copy, PartialEq, Debug)]
66 enum BlockMode {
67     Break,
68     Ignore,
69 }
70 
71 /// Whether or not we should force collection of tokens for an AST node,
72 /// regardless of whether or not it has attributes
73 #[derive(Clone, Copy, PartialEq)]
74 pub enum ForceCollect {
75     Yes,
76     No,
77 }
78 
79 #[derive(Debug, Eq, PartialEq)]
80 pub enum TrailingToken {
81     None,
82     Semi,
83     Gt,
84     /// If the trailing token is a comma, then capture it
85     /// Otherwise, ignore the trailing token
86     MaybeComma,
87 }
88 
89 /// Like `maybe_whole_expr`, but for things other than expressions.
90 #[macro_export]
91 macro_rules! maybe_whole {
92     ($p:expr, $constructor:ident, |$x:ident| $e:expr) => {
93         if let token::Interpolated(nt) = &$p.token.kind {
94             if let token::$constructor(x) = &**nt {
95                 let $x = x.clone();
96                 $p.bump();
97                 return Ok($e);
98             }
99         }
100     };
101 }
102 
103 /// If the next tokens are ill-formed `$ty::` recover them as `<$ty>::`.
104 #[macro_export]
105 macro_rules! maybe_recover_from_interpolated_ty_qpath {
106     ($self: expr, $allow_qpath_recovery: expr) => {
107         if $allow_qpath_recovery
108                     && $self.may_recover()
109                     && $self.look_ahead(1, |t| t == &token::ModSep)
110                     && let token::Interpolated(nt) = &$self.token.kind
111                     && let token::NtTy(ty) = &**nt
112                 {
113                     let ty = ty.clone();
114                     $self.bump();
115                     return $self.maybe_recover_from_bad_qpath_stage_2($self.prev_token.span, ty);
116                 }
117     };
118 }
119 
120 #[derive(Clone, Copy)]
121 pub enum Recovery {
122     Allowed,
123     Forbidden,
124 }
125 
126 #[derive(Clone)]
127 pub struct Parser<'a> {
128     pub sess: &'a ParseSess,
129     /// The current token.
130     pub token: Token,
131     /// The spacing for the current token
132     pub token_spacing: Spacing,
133     /// The previous token.
134     pub prev_token: Token,
135     pub capture_cfg: bool,
136     restrictions: Restrictions,
137     expected_tokens: Vec<TokenType>,
138     // Important: This must only be advanced from `bump` to ensure that
139     // `token_cursor.num_next_calls` is updated properly.
140     token_cursor: TokenCursor,
141     desugar_doc_comments: bool,
142     /// This field is used to keep track of how many left angle brackets we have seen. This is
143     /// required in order to detect extra leading left angle brackets (`<` characters) and error
144     /// appropriately.
145     ///
146     /// See the comments in the `parse_path_segment` function for more details.
147     unmatched_angle_bracket_count: u32,
148     max_angle_bracket_count: u32,
149 
150     last_unexpected_token_span: Option<Span>,
151     /// If present, this `Parser` is not parsing Rust code but rather a macro call.
152     subparser_name: Option<&'static str>,
153     capture_state: CaptureState,
154     /// This allows us to recover when the user forget to add braces around
155     /// multiple statements in the closure body.
156     pub current_closure: Option<ClosureSpans>,
157     /// Whether the parser is allowed to do recovery.
158     /// This is disabled when parsing macro arguments, see #103534
159     pub recovery: Recovery,
160 }
161 
162 // This type is used a lot, e.g. it's cloned when matching many declarative macro rules with nonterminals. Make sure
163 // it doesn't unintentionally get bigger.
164 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
165 rustc_data_structures::static_assert_size!(Parser<'_>, 272);
166 
167 /// Stores span information about a closure.
168 #[derive(Clone)]
169 pub struct ClosureSpans {
170     pub whole_closure: Span,
171     pub closing_pipe: Span,
172     pub body: Span,
173 }
174 
175 /// Indicates a range of tokens that should be replaced by
176 /// the tokens in the provided vector. This is used in two
177 /// places during token collection:
178 ///
179 /// 1. During the parsing of an AST node that may have a `#[derive]`
180 /// attribute, we parse a nested AST node that has `#[cfg]` or `#[cfg_attr]`
181 /// In this case, we use a `ReplaceRange` to replace the entire inner AST node
182 /// with `FlatToken::AttrTarget`, allowing us to perform eager cfg-expansion
183 /// on an `AttrTokenStream`.
184 ///
185 /// 2. When we parse an inner attribute while collecting tokens. We
186 /// remove inner attributes from the token stream entirely, and
187 /// instead track them through the `attrs` field on the AST node.
188 /// This allows us to easily manipulate them (for example, removing
189 /// the first macro inner attribute to invoke a proc-macro).
190 /// When create a `TokenStream`, the inner attributes get inserted
191 /// into the proper place in the token stream.
192 pub type ReplaceRange = (Range<u32>, Vec<(FlatToken, Spacing)>);
193 
194 /// Controls how we capture tokens. Capturing can be expensive,
195 /// so we try to avoid performing capturing in cases where
196 /// we will never need an `AttrTokenStream`.
197 #[derive(Copy, Clone)]
198 pub enum Capturing {
199     /// We aren't performing any capturing - this is the default mode.
200     No,
201     /// We are capturing tokens
202     Yes,
203 }
204 
205 #[derive(Clone)]
206 struct CaptureState {
207     capturing: Capturing,
208     replace_ranges: Vec<ReplaceRange>,
209     inner_attr_ranges: FxHashMap<AttrId, ReplaceRange>,
210 }
211 
212 /// Iterator over a `TokenStream` that produces `Token`s. It's a bit odd that
213 /// we (a) lex tokens into a nice tree structure (`TokenStream`), and then (b)
214 /// use this type to emit them as a linear sequence. But a linear sequence is
215 /// what the parser expects, for the most part.
216 #[derive(Clone)]
217 struct TokenCursor {
218     // Cursor for the current (innermost) token stream. The delimiters for this
219     // token stream are found in `self.stack.last()`; when that is `None` then
220     // we are in the outermost token stream which never has delimiters.
221     tree_cursor: TokenTreeCursor,
222 
223     // Token streams surrounding the current one. The delimiters for stack[n]'s
224     // tokens are in `stack[n-1]`. `stack[0]` (when present) has no delimiters
225     // because it's the outermost token stream which never has delimiters.
226     stack: Vec<(TokenTreeCursor, Delimiter, DelimSpan)>,
227 
228     desugar_doc_comments: bool,
229 
230     // Counts the number of calls to `{,inlined_}next`.
231     num_next_calls: usize,
232 
233     // During parsing, we may sometimes need to 'unglue' a
234     // glued token into two component tokens
235     // (e.g. '>>' into '>' and '>), so that the parser
236     // can consume them one at a time. This process
237     // bypasses the normal capturing mechanism
238     // (e.g. `num_next_calls` will not be incremented),
239     // since the 'unglued' tokens due not exist in
240     // the original `TokenStream`.
241     //
242     // If we end up consuming both unglued tokens,
243     // then this is not an issue - we'll end up
244     // capturing the single 'glued' token.
245     //
246     // However, in certain circumstances, we may
247     // want to capture just the first 'unglued' token.
248     // For example, capturing the `Vec<u8>`
249     // in `Option<Vec<u8>>` requires us to unglue
250     // the trailing `>>` token. The `break_last_token`
251     // field is used to track this token - it gets
252     // appended to the captured stream when
253     // we evaluate a `LazyAttrTokenStream`.
254     break_last_token: bool,
255 }
256 
257 impl TokenCursor {
next(&mut self, desugar_doc_comments: bool) -> (Token, Spacing)258     fn next(&mut self, desugar_doc_comments: bool) -> (Token, Spacing) {
259         self.inlined_next(desugar_doc_comments)
260     }
261 
262     /// This always-inlined version should only be used on hot code paths.
263     #[inline(always)]
inlined_next(&mut self, desugar_doc_comments: bool) -> (Token, Spacing)264     fn inlined_next(&mut self, desugar_doc_comments: bool) -> (Token, Spacing) {
265         loop {
266             // FIXME: we currently don't return `Delimiter` open/close delims. To fix #67062 we will
267             // need to, whereupon the `delim != Delimiter::Invisible` conditions below can be
268             // removed.
269             if let Some(tree) = self.tree_cursor.next_ref() {
270                 match tree {
271                     &TokenTree::Token(ref token, spacing) => match (desugar_doc_comments, token) {
272                         (true, &Token { kind: token::DocComment(_, attr_style, data), span }) => {
273                             let desugared = self.desugar(attr_style, data, span);
274                             self.tree_cursor.replace_prev_and_rewind(desugared);
275                             // Continue to get the first token of the desugared doc comment.
276                         }
277                         _ => {
278                             debug_assert!(!matches!(
279                                 token.kind,
280                                 token::OpenDelim(_) | token::CloseDelim(_)
281                             ));
282                             return (token.clone(), spacing);
283                         }
284                     },
285                     &TokenTree::Delimited(sp, delim, ref tts) => {
286                         let trees = tts.clone().into_trees();
287                         self.stack.push((mem::replace(&mut self.tree_cursor, trees), delim, sp));
288                         if delim != Delimiter::Invisible {
289                             return (Token::new(token::OpenDelim(delim), sp.open), Spacing::Alone);
290                         }
291                         // No open delimiter to return; continue on to the next iteration.
292                     }
293                 };
294             } else if let Some((tree_cursor, delim, span)) = self.stack.pop() {
295                 // We have exhausted this token stream. Move back to its parent token stream.
296                 self.tree_cursor = tree_cursor;
297                 if delim != Delimiter::Invisible {
298                     return (Token::new(token::CloseDelim(delim), span.close), Spacing::Alone);
299                 }
300                 // No close delimiter to return; continue on to the next iteration.
301             } else {
302                 // We have exhausted the outermost token stream.
303                 return (Token::new(token::Eof, DUMMY_SP), Spacing::Alone);
304             }
305         }
306     }
307 
308     // Desugar a doc comment into something like `#[doc = r"foo"]`.
desugar(&mut self, attr_style: AttrStyle, data: Symbol, span: Span) -> Vec<TokenTree>309     fn desugar(&mut self, attr_style: AttrStyle, data: Symbol, span: Span) -> Vec<TokenTree> {
310         // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
311         // required to wrap the text. E.g.
312         // - `abc d` is wrapped as `r"abc d"` (num_of_hashes = 0)
313         // - `abc "d"` is wrapped as `r#"abc "d""#` (num_of_hashes = 1)
314         // - `abc "##d##"` is wrapped as `r###"abc ##"d"##"###` (num_of_hashes = 3)
315         let mut num_of_hashes = 0;
316         let mut count = 0;
317         for ch in data.as_str().chars() {
318             count = match ch {
319                 '"' => 1,
320                 '#' if count > 0 => count + 1,
321                 _ => 0,
322             };
323             num_of_hashes = cmp::max(num_of_hashes, count);
324         }
325 
326         // `/// foo` becomes `doc = r"foo"`.
327         let delim_span = DelimSpan::from_single(span);
328         let body = TokenTree::Delimited(
329             delim_span,
330             Delimiter::Bracket,
331             [
332                 TokenTree::token_alone(token::Ident(sym::doc, false), span),
333                 TokenTree::token_alone(token::Eq, span),
334                 TokenTree::token_alone(
335                     TokenKind::lit(token::StrRaw(num_of_hashes), data, None),
336                     span,
337                 ),
338             ]
339             .into_iter()
340             .collect::<TokenStream>(),
341         );
342 
343         if attr_style == AttrStyle::Inner {
344             vec![
345                 TokenTree::token_alone(token::Pound, span),
346                 TokenTree::token_alone(token::Not, span),
347                 body,
348             ]
349         } else {
350             vec![TokenTree::token_alone(token::Pound, span), body]
351         }
352     }
353 }
354 
355 #[derive(Debug, Clone, PartialEq)]
356 enum TokenType {
357     Token(TokenKind),
358     Keyword(Symbol),
359     Operator,
360     Lifetime,
361     Ident,
362     Path,
363     Type,
364     Const,
365 }
366 
367 impl TokenType {
to_string(&self) -> String368     fn to_string(&self) -> String {
369         match self {
370             TokenType::Token(t) => format!("`{}`", pprust::token_kind_to_string(t)),
371             TokenType::Keyword(kw) => format!("`{}`", kw),
372             TokenType::Operator => "an operator".to_string(),
373             TokenType::Lifetime => "lifetime".to_string(),
374             TokenType::Ident => "identifier".to_string(),
375             TokenType::Path => "path".to_string(),
376             TokenType::Type => "type".to_string(),
377             TokenType::Const => "a const expression".to_string(),
378         }
379     }
380 }
381 
382 #[derive(Copy, Clone, Debug)]
383 enum TokenExpectType {
384     Expect,
385     NoExpect,
386 }
387 
388 /// A sequence separator.
389 struct SeqSep {
390     /// The separator token.
391     sep: Option<TokenKind>,
392     /// `true` if a trailing separator is allowed.
393     trailing_sep_allowed: bool,
394 }
395 
396 impl SeqSep {
trailing_allowed(t: TokenKind) -> SeqSep397     fn trailing_allowed(t: TokenKind) -> SeqSep {
398         SeqSep { sep: Some(t), trailing_sep_allowed: true }
399     }
400 
none() -> SeqSep401     fn none() -> SeqSep {
402         SeqSep { sep: None, trailing_sep_allowed: false }
403     }
404 }
405 
406 pub enum FollowedByType {
407     Yes,
408     No,
409 }
410 
411 #[derive(Clone, Copy, PartialEq, Eq)]
412 pub enum TokenDescription {
413     ReservedIdentifier,
414     Keyword,
415     ReservedKeyword,
416     DocComment,
417 }
418 
419 impl TokenDescription {
from_token(token: &Token) -> Option<Self>420     pub fn from_token(token: &Token) -> Option<Self> {
421         match token.kind {
422             _ if token.is_special_ident() => Some(TokenDescription::ReservedIdentifier),
423             _ if token.is_used_keyword() => Some(TokenDescription::Keyword),
424             _ if token.is_unused_keyword() => Some(TokenDescription::ReservedKeyword),
425             token::DocComment(..) => Some(TokenDescription::DocComment),
426             _ => None,
427         }
428     }
429 }
430 
token_descr(token: &Token) -> String431 pub(super) fn token_descr(token: &Token) -> String {
432     let name = pprust::token_to_string(token).to_string();
433 
434     let kind = TokenDescription::from_token(token).map(|kind| match kind {
435         TokenDescription::ReservedIdentifier => "reserved identifier",
436         TokenDescription::Keyword => "keyword",
437         TokenDescription::ReservedKeyword => "reserved keyword",
438         TokenDescription::DocComment => "doc comment",
439     });
440 
441     if let Some(kind) = kind { format!("{} `{}`", kind, name) } else { format!("`{}`", name) }
442 }
443 
444 impl<'a> Parser<'a> {
new( sess: &'a ParseSess, tokens: TokenStream, desugar_doc_comments: bool, subparser_name: Option<&'static str>, ) -> Self445     pub fn new(
446         sess: &'a ParseSess,
447         tokens: TokenStream,
448         desugar_doc_comments: bool,
449         subparser_name: Option<&'static str>,
450     ) -> Self {
451         let mut parser = Parser {
452             sess,
453             token: Token::dummy(),
454             token_spacing: Spacing::Alone,
455             prev_token: Token::dummy(),
456             capture_cfg: false,
457             restrictions: Restrictions::empty(),
458             expected_tokens: Vec::new(),
459             token_cursor: TokenCursor {
460                 tree_cursor: tokens.into_trees(),
461                 stack: Vec::new(),
462                 num_next_calls: 0,
463                 desugar_doc_comments,
464                 break_last_token: false,
465             },
466             desugar_doc_comments,
467             unmatched_angle_bracket_count: 0,
468             max_angle_bracket_count: 0,
469             last_unexpected_token_span: None,
470             subparser_name,
471             capture_state: CaptureState {
472                 capturing: Capturing::No,
473                 replace_ranges: Vec::new(),
474                 inner_attr_ranges: Default::default(),
475             },
476             current_closure: None,
477             recovery: Recovery::Allowed,
478         };
479 
480         // Make parser point to the first token.
481         parser.bump();
482 
483         parser
484     }
485 
recovery(mut self, recovery: Recovery) -> Self486     pub fn recovery(mut self, recovery: Recovery) -> Self {
487         self.recovery = recovery;
488         self
489     }
490 
491     /// Whether the parser is allowed to recover from broken code.
492     ///
493     /// If this returns false, recovering broken code into valid code (especially if this recovery does lookahead)
494     /// is not allowed. All recovery done by the parser must be gated behind this check.
495     ///
496     /// Technically, this only needs to restrict eager recovery by doing lookahead at more tokens.
497     /// But making the distinction is very subtle, and simply forbidding all recovery is a lot simpler to uphold.
may_recover(&self) -> bool498     fn may_recover(&self) -> bool {
499         matches!(self.recovery, Recovery::Allowed)
500     }
501 
unexpected<T>(&mut self) -> PResult<'a, T>502     pub fn unexpected<T>(&mut self) -> PResult<'a, T> {
503         match self.expect_one_of(&[], &[]) {
504             Err(e) => Err(e),
505             // We can get `Ok(true)` from `recover_closing_delimiter`
506             // which is called in `expected_one_of_not_found`.
507             Ok(_) => FatalError.raise(),
508         }
509     }
510 
511     /// Expects and consumes the token `t`. Signals an error if the next token is not `t`.
expect(&mut self, t: &TokenKind) -> PResult<'a, bool >512     pub fn expect(&mut self, t: &TokenKind) -> PResult<'a, bool /* recovered */> {
513         if self.expected_tokens.is_empty() {
514             if self.token == *t {
515                 self.bump();
516                 Ok(false)
517             } else {
518                 self.unexpected_try_recover(t)
519             }
520         } else {
521             self.expect_one_of(slice::from_ref(t), &[])
522         }
523     }
524 
525     /// Expect next token to be edible or inedible token. If edible,
526     /// then consume it; if inedible, then return without consuming
527     /// anything. Signal a fatal error if next token is unexpected.
expect_one_of( &mut self, edible: &[TokenKind], inedible: &[TokenKind], ) -> PResult<'a, bool >528     pub fn expect_one_of(
529         &mut self,
530         edible: &[TokenKind],
531         inedible: &[TokenKind],
532     ) -> PResult<'a, bool /* recovered */> {
533         if edible.contains(&self.token.kind) {
534             self.bump();
535             Ok(false)
536         } else if inedible.contains(&self.token.kind) {
537             // leave it in the input
538             Ok(false)
539         } else if self.token.kind != token::Eof
540             && self.last_unexpected_token_span == Some(self.token.span)
541         {
542             FatalError.raise();
543         } else {
544             self.expected_one_of_not_found(edible, inedible)
545         }
546     }
547 
548     // Public for rustfmt usage.
parse_ident(&mut self) -> PResult<'a, Ident>549     pub fn parse_ident(&mut self) -> PResult<'a, Ident> {
550         self.parse_ident_common(true)
551     }
552 
parse_ident_common(&mut self, recover: bool) -> PResult<'a, Ident>553     fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, Ident> {
554         let (ident, is_raw) = self.ident_or_err(recover)?;
555 
556         if !is_raw && ident.is_reserved() {
557             let mut err = self.expected_ident_found_err();
558             if recover {
559                 err.emit();
560             } else {
561                 return Err(err);
562             }
563         }
564         self.bump();
565         Ok(ident)
566     }
567 
ident_or_err(&mut self, recover: bool) -> PResult<'a, (Ident, bool)>568     fn ident_or_err(&mut self, recover: bool) -> PResult<'a, (Ident, /* is_raw */ bool)> {
569         let result = self.token.ident().ok_or_else(|| self.expected_ident_found(recover));
570 
571         let (ident, is_raw) = match result {
572             Ok(ident) => ident,
573             Err(err) => match err {
574                 // we recovered!
575                 Ok(ident) => ident,
576                 Err(err) => return Err(err),
577             },
578         };
579 
580         Ok((ident, is_raw))
581     }
582 
583     /// Checks if the next token is `tok`, and returns `true` if so.
584     ///
585     /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
586     /// encountered.
check(&mut self, tok: &TokenKind) -> bool587     fn check(&mut self, tok: &TokenKind) -> bool {
588         let is_present = self.token == *tok;
589         if !is_present {
590             self.expected_tokens.push(TokenType::Token(tok.clone()));
591         }
592         is_present
593     }
594 
check_noexpect(&self, tok: &TokenKind) -> bool595     fn check_noexpect(&self, tok: &TokenKind) -> bool {
596         self.token == *tok
597     }
598 
599     /// Consumes a token 'tok' if it exists. Returns whether the given token was present.
600     ///
601     /// the main purpose of this function is to reduce the cluttering of the suggestions list
602     /// which using the normal eat method could introduce in some cases.
eat_noexpect(&mut self, tok: &TokenKind) -> bool603     pub fn eat_noexpect(&mut self, tok: &TokenKind) -> bool {
604         let is_present = self.check_noexpect(tok);
605         if is_present {
606             self.bump()
607         }
608         is_present
609     }
610 
611     /// Consumes a token 'tok' if it exists. Returns whether the given token was present.
eat(&mut self, tok: &TokenKind) -> bool612     pub fn eat(&mut self, tok: &TokenKind) -> bool {
613         let is_present = self.check(tok);
614         if is_present {
615             self.bump()
616         }
617         is_present
618     }
619 
620     /// If the next token is the given keyword, returns `true` without eating it.
621     /// An expectation is also added for diagnostics purposes.
check_keyword(&mut self, kw: Symbol) -> bool622     fn check_keyword(&mut self, kw: Symbol) -> bool {
623         self.expected_tokens.push(TokenType::Keyword(kw));
624         self.token.is_keyword(kw)
625     }
626 
check_keyword_case(&mut self, kw: Symbol, case: Case) -> bool627     fn check_keyword_case(&mut self, kw: Symbol, case: Case) -> bool {
628         if self.check_keyword(kw) {
629             return true;
630         }
631 
632         if case == Case::Insensitive
633         && let Some((ident, /* is_raw */ false)) = self.token.ident()
634         && ident.as_str().to_lowercase() == kw.as_str().to_lowercase() {
635             true
636         } else {
637             false
638         }
639     }
640 
641     /// If the next token is the given keyword, eats it and returns `true`.
642     /// Otherwise, returns `false`. An expectation is also added for diagnostics purposes.
643     // Public for rustfmt usage.
eat_keyword(&mut self, kw: Symbol) -> bool644     pub fn eat_keyword(&mut self, kw: Symbol) -> bool {
645         if self.check_keyword(kw) {
646             self.bump();
647             true
648         } else {
649             false
650         }
651     }
652 
653     /// Eats a keyword, optionally ignoring the case.
654     /// If the case differs (and is ignored) an error is issued.
655     /// This is useful for recovery.
eat_keyword_case(&mut self, kw: Symbol, case: Case) -> bool656     fn eat_keyword_case(&mut self, kw: Symbol, case: Case) -> bool {
657         if self.eat_keyword(kw) {
658             return true;
659         }
660 
661         if case == Case::Insensitive
662         && let Some((ident, /* is_raw */ false)) = self.token.ident()
663         && ident.as_str().to_lowercase() == kw.as_str().to_lowercase() {
664             self.sess.emit_err(errors::KwBadCase {
665                 span: ident.span,
666                 kw: kw.as_str()
667             });
668             self.bump();
669             return true;
670         }
671 
672         false
673     }
674 
eat_keyword_noexpect(&mut self, kw: Symbol) -> bool675     fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool {
676         if self.token.is_keyword(kw) {
677             self.bump();
678             true
679         } else {
680             false
681         }
682     }
683 
684     /// If the given word is not a keyword, signals an error.
685     /// If the next token is not the given word, signals an error.
686     /// Otherwise, eats it.
expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()>687     fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> {
688         if !self.eat_keyword(kw) { self.unexpected() } else { Ok(()) }
689     }
690 
691     /// Is the given keyword `kw` followed by a non-reserved identifier?
is_kw_followed_by_ident(&self, kw: Symbol) -> bool692     fn is_kw_followed_by_ident(&self, kw: Symbol) -> bool {
693         self.token.is_keyword(kw) && self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
694     }
695 
check_or_expected(&mut self, ok: bool, typ: TokenType) -> bool696     fn check_or_expected(&mut self, ok: bool, typ: TokenType) -> bool {
697         if ok {
698             true
699         } else {
700             self.expected_tokens.push(typ);
701             false
702         }
703     }
704 
check_ident(&mut self) -> bool705     fn check_ident(&mut self) -> bool {
706         self.check_or_expected(self.token.is_ident(), TokenType::Ident)
707     }
708 
check_path(&mut self) -> bool709     fn check_path(&mut self) -> bool {
710         self.check_or_expected(self.token.is_path_start(), TokenType::Path)
711     }
712 
check_type(&mut self) -> bool713     fn check_type(&mut self) -> bool {
714         self.check_or_expected(self.token.can_begin_type(), TokenType::Type)
715     }
716 
check_const_arg(&mut self) -> bool717     fn check_const_arg(&mut self) -> bool {
718         self.check_or_expected(self.token.can_begin_const_arg(), TokenType::Const)
719     }
720 
check_const_closure(&self) -> bool721     fn check_const_closure(&self) -> bool {
722         self.is_keyword_ahead(0, &[kw::Const])
723             && self.look_ahead(1, |t| match &t.kind {
724                 // async closures do not work with const closures, so we do not parse that here.
725                 token::Ident(kw::Move | kw::Static, _) | token::OrOr | token::BinOp(token::Or) => {
726                     true
727                 }
728                 _ => false,
729             })
730     }
731 
check_inline_const(&self, dist: usize) -> bool732     fn check_inline_const(&self, dist: usize) -> bool {
733         self.is_keyword_ahead(dist, &[kw::Const])
734             && self.look_ahead(dist + 1, |t| match &t.kind {
735                 token::Interpolated(nt) => matches!(**nt, token::NtBlock(..)),
736                 token::OpenDelim(Delimiter::Brace) => true,
737                 _ => false,
738             })
739     }
740 
741     /// Checks to see if the next token is either `+` or `+=`.
742     /// Otherwise returns `false`.
check_plus(&mut self) -> bool743     fn check_plus(&mut self) -> bool {
744         self.check_or_expected(
745             self.token.is_like_plus(),
746             TokenType::Token(token::BinOp(token::Plus)),
747         )
748     }
749 
750     /// Eats the expected token if it's present possibly breaking
751     /// compound tokens like multi-character operators in process.
752     /// Returns `true` if the token was eaten.
break_and_eat(&mut self, expected: TokenKind) -> bool753     fn break_and_eat(&mut self, expected: TokenKind) -> bool {
754         if self.token.kind == expected {
755             self.bump();
756             return true;
757         }
758         match self.token.kind.break_two_token_op() {
759             Some((first, second)) if first == expected => {
760                 let first_span = self.sess.source_map().start_point(self.token.span);
761                 let second_span = self.token.span.with_lo(first_span.hi());
762                 self.token = Token::new(first, first_span);
763                 // Keep track of this token - if we end token capturing now,
764                 // we'll want to append this token to the captured stream.
765                 //
766                 // If we consume any additional tokens, then this token
767                 // is not needed (we'll capture the entire 'glued' token),
768                 // and `bump` will set this field to `None`
769                 self.token_cursor.break_last_token = true;
770                 // Use the spacing of the glued token as the spacing
771                 // of the unglued second token.
772                 self.bump_with((Token::new(second, second_span), self.token_spacing));
773                 true
774             }
775             _ => {
776                 self.expected_tokens.push(TokenType::Token(expected));
777                 false
778             }
779         }
780     }
781 
782     /// Eats `+` possibly breaking tokens like `+=` in process.
eat_plus(&mut self) -> bool783     fn eat_plus(&mut self) -> bool {
784         self.break_and_eat(token::BinOp(token::Plus))
785     }
786 
787     /// Eats `&` possibly breaking tokens like `&&` in process.
788     /// Signals an error if `&` is not eaten.
expect_and(&mut self) -> PResult<'a, ()>789     fn expect_and(&mut self) -> PResult<'a, ()> {
790         if self.break_and_eat(token::BinOp(token::And)) { Ok(()) } else { self.unexpected() }
791     }
792 
793     /// Eats `|` possibly breaking tokens like `||` in process.
794     /// Signals an error if `|` was not eaten.
expect_or(&mut self) -> PResult<'a, ()>795     fn expect_or(&mut self) -> PResult<'a, ()> {
796         if self.break_and_eat(token::BinOp(token::Or)) { Ok(()) } else { self.unexpected() }
797     }
798 
799     /// Eats `<` possibly breaking tokens like `<<` in process.
eat_lt(&mut self) -> bool800     fn eat_lt(&mut self) -> bool {
801         let ate = self.break_and_eat(token::Lt);
802         if ate {
803             // See doc comment for `unmatched_angle_bracket_count`.
804             self.unmatched_angle_bracket_count += 1;
805             self.max_angle_bracket_count += 1;
806             debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count);
807         }
808         ate
809     }
810 
811     /// Eats `<` possibly breaking tokens like `<<` in process.
812     /// Signals an error if `<` was not eaten.
expect_lt(&mut self) -> PResult<'a, ()>813     fn expect_lt(&mut self) -> PResult<'a, ()> {
814         if self.eat_lt() { Ok(()) } else { self.unexpected() }
815     }
816 
817     /// Eats `>` possibly breaking tokens like `>>` in process.
818     /// Signals an error if `>` was not eaten.
expect_gt(&mut self) -> PResult<'a, ()>819     fn expect_gt(&mut self) -> PResult<'a, ()> {
820         if self.break_and_eat(token::Gt) {
821             // See doc comment for `unmatched_angle_bracket_count`.
822             if self.unmatched_angle_bracket_count > 0 {
823                 self.unmatched_angle_bracket_count -= 1;
824                 debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count);
825             }
826             Ok(())
827         } else {
828             self.unexpected()
829         }
830     }
831 
expect_any_with_type(&mut self, kets: &[&TokenKind], expect: TokenExpectType) -> bool832     fn expect_any_with_type(&mut self, kets: &[&TokenKind], expect: TokenExpectType) -> bool {
833         kets.iter().any(|k| match expect {
834             TokenExpectType::Expect => self.check(k),
835             TokenExpectType::NoExpect => self.token == **k,
836         })
837     }
838 
parse_seq_to_before_tokens<T>( &mut self, kets: &[&TokenKind], sep: SeqSep, expect: TokenExpectType, mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, ) -> PResult<'a, (ThinVec<T>, bool , bool )>839     fn parse_seq_to_before_tokens<T>(
840         &mut self,
841         kets: &[&TokenKind],
842         sep: SeqSep,
843         expect: TokenExpectType,
844         mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
845     ) -> PResult<'a, (ThinVec<T>, bool /* trailing */, bool /* recovered */)> {
846         let mut first = true;
847         let mut recovered = false;
848         let mut trailing = false;
849         let mut v = ThinVec::new();
850 
851         while !self.expect_any_with_type(kets, expect) {
852             if let token::CloseDelim(..) | token::Eof = self.token.kind {
853                 break;
854             }
855             if let Some(t) = &sep.sep {
856                 if first {
857                     first = false;
858                 } else {
859                     match self.expect(t) {
860                         Ok(false) => {
861                             self.current_closure.take();
862                         }
863                         Ok(true) => {
864                             self.current_closure.take();
865                             recovered = true;
866                             break;
867                         }
868                         Err(mut expect_err) => {
869                             let sp = self.prev_token.span.shrink_to_hi();
870                             let token_str = pprust::token_kind_to_string(t);
871 
872                             match self.current_closure.take() {
873                                 Some(closure_spans) if self.token.kind == TokenKind::Semi => {
874                                     // Finding a semicolon instead of a comma
875                                     // after a closure body indicates that the
876                                     // closure body may be a block but the user
877                                     // forgot to put braces around its
878                                     // statements.
879 
880                                     self.recover_missing_braces_around_closure_body(
881                                         closure_spans,
882                                         expect_err,
883                                     )?;
884 
885                                     continue;
886                                 }
887 
888                                 _ => {
889                                     // Attempt to keep parsing if it was a similar separator.
890                                     if let Some(tokens) = t.similar_tokens() {
891                                         if tokens.contains(&self.token.kind) {
892                                             self.bump();
893                                         }
894                                     }
895                                 }
896                             }
897 
898                             // If this was a missing `@` in a binding pattern
899                             // bail with a suggestion
900                             // https://github.com/rust-lang/rust/issues/72373
901                             if self.prev_token.is_ident() && self.token.kind == token::DotDot {
902                                 let msg = format!(
903                                     "if you meant to bind the contents of \
904                                     the rest of the array pattern into `{}`, use `@`",
905                                     pprust::token_to_string(&self.prev_token)
906                                 );
907                                 expect_err
908                                     .span_suggestion_verbose(
909                                         self.prev_token.span.shrink_to_hi().until(self.token.span),
910                                         msg,
911                                         " @ ",
912                                         Applicability::MaybeIncorrect,
913                                     )
914                                     .emit();
915                                 break;
916                             }
917 
918                             // Attempt to keep parsing if it was an omitted separator.
919                             match f(self) {
920                                 Ok(t) => {
921                                     // Parsed successfully, therefore most probably the code only
922                                     // misses a separator.
923                                     expect_err
924                                         .span_suggestion_short(
925                                             sp,
926                                             format!("missing `{}`", token_str),
927                                             token_str,
928                                             Applicability::MaybeIncorrect,
929                                         )
930                                         .emit();
931 
932                                     v.push(t);
933                                     continue;
934                                 }
935                                 Err(e) => {
936                                     // Parsing failed, therefore it must be something more serious
937                                     // than just a missing separator.
938                                     for xx in &e.children {
939                                         // propagate the help message from sub error 'e' to main error 'expect_err;
940                                         expect_err.children.push(xx.clone());
941                                     }
942                                     e.cancel();
943                                     if self.token == token::Colon {
944                                         // we will try to recover in `maybe_recover_struct_lit_bad_delims`
945                                         return Err(expect_err);
946                                     } else {
947                                         expect_err.emit();
948                                         break;
949                                     }
950                                 }
951                             }
952                         }
953                     }
954                 }
955             }
956             if sep.trailing_sep_allowed && self.expect_any_with_type(kets, expect) {
957                 trailing = true;
958                 break;
959             }
960 
961             let t = f(self)?;
962             v.push(t);
963         }
964 
965         Ok((v, trailing, recovered))
966     }
967 
recover_missing_braces_around_closure_body( &mut self, closure_spans: ClosureSpans, mut expect_err: DiagnosticBuilder<'_, ErrorGuaranteed>, ) -> PResult<'a, ()>968     fn recover_missing_braces_around_closure_body(
969         &mut self,
970         closure_spans: ClosureSpans,
971         mut expect_err: DiagnosticBuilder<'_, ErrorGuaranteed>,
972     ) -> PResult<'a, ()> {
973         let initial_semicolon = self.token.span;
974 
975         while self.eat(&TokenKind::Semi) {
976             let _ =
977                 self.parse_stmt_without_recovery(false, ForceCollect::Yes).unwrap_or_else(|e| {
978                     e.cancel();
979                     None
980                 });
981         }
982 
983         expect_err.set_primary_message(
984             "closure bodies that contain statements must be surrounded by braces",
985         );
986 
987         let preceding_pipe_span = closure_spans.closing_pipe;
988         let following_token_span = self.token.span;
989 
990         let mut first_note = MultiSpan::from(vec![initial_semicolon]);
991         first_note.push_span_label(
992             initial_semicolon,
993             "this `;` turns the preceding closure into a statement",
994         );
995         first_note.push_span_label(
996             closure_spans.body,
997             "this expression is a statement because of the trailing semicolon",
998         );
999         expect_err.span_note(first_note, "statement found outside of a block");
1000 
1001         let mut second_note = MultiSpan::from(vec![closure_spans.whole_closure]);
1002         second_note.push_span_label(closure_spans.whole_closure, "this is the parsed closure...");
1003         second_note.push_span_label(
1004             following_token_span,
1005             "...but likely you meant the closure to end here",
1006         );
1007         expect_err.span_note(second_note, "the closure body may be incorrectly delimited");
1008 
1009         expect_err.set_span(vec![preceding_pipe_span, following_token_span]);
1010 
1011         let opening_suggestion_str = " {".to_string();
1012         let closing_suggestion_str = "}".to_string();
1013 
1014         expect_err.multipart_suggestion(
1015             "try adding braces",
1016             vec![
1017                 (preceding_pipe_span.shrink_to_hi(), opening_suggestion_str),
1018                 (following_token_span.shrink_to_lo(), closing_suggestion_str),
1019             ],
1020             Applicability::MaybeIncorrect,
1021         );
1022 
1023         expect_err.emit();
1024 
1025         Ok(())
1026     }
1027 
1028     /// Parses a sequence, not including the closing delimiter. The function
1029     /// `f` must consume tokens until reaching the next separator or
1030     /// closing bracket.
parse_seq_to_before_end<T>( &mut self, ket: &TokenKind, sep: SeqSep, f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, ) -> PResult<'a, (ThinVec<T>, bool, bool)>1031     fn parse_seq_to_before_end<T>(
1032         &mut self,
1033         ket: &TokenKind,
1034         sep: SeqSep,
1035         f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1036     ) -> PResult<'a, (ThinVec<T>, bool, bool)> {
1037         self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
1038     }
1039 
1040     /// Parses a sequence, including the closing delimiter. The function
1041     /// `f` must consume tokens until reaching the next separator or
1042     /// closing bracket.
parse_seq_to_end<T>( &mut self, ket: &TokenKind, sep: SeqSep, f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, ) -> PResult<'a, (ThinVec<T>, bool )>1043     fn parse_seq_to_end<T>(
1044         &mut self,
1045         ket: &TokenKind,
1046         sep: SeqSep,
1047         f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1048     ) -> PResult<'a, (ThinVec<T>, bool /* trailing */)> {
1049         let (val, trailing, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
1050         if !recovered {
1051             self.eat(ket);
1052         }
1053         Ok((val, trailing))
1054     }
1055 
1056     /// Parses a sequence, including the closing delimiter. The function
1057     /// `f` must consume tokens until reaching the next separator or
1058     /// closing bracket.
parse_unspanned_seq<T>( &mut self, bra: &TokenKind, ket: &TokenKind, sep: SeqSep, f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, ) -> PResult<'a, (ThinVec<T>, bool)>1059     fn parse_unspanned_seq<T>(
1060         &mut self,
1061         bra: &TokenKind,
1062         ket: &TokenKind,
1063         sep: SeqSep,
1064         f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1065     ) -> PResult<'a, (ThinVec<T>, bool)> {
1066         self.expect(bra)?;
1067         self.parse_seq_to_end(ket, sep, f)
1068     }
1069 
parse_delim_comma_seq<T>( &mut self, delim: Delimiter, f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, ) -> PResult<'a, (ThinVec<T>, bool)>1070     fn parse_delim_comma_seq<T>(
1071         &mut self,
1072         delim: Delimiter,
1073         f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1074     ) -> PResult<'a, (ThinVec<T>, bool)> {
1075         self.parse_unspanned_seq(
1076             &token::OpenDelim(delim),
1077             &token::CloseDelim(delim),
1078             SeqSep::trailing_allowed(token::Comma),
1079             f,
1080         )
1081     }
1082 
parse_paren_comma_seq<T>( &mut self, f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, ) -> PResult<'a, (ThinVec<T>, bool)>1083     fn parse_paren_comma_seq<T>(
1084         &mut self,
1085         f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1086     ) -> PResult<'a, (ThinVec<T>, bool)> {
1087         self.parse_delim_comma_seq(Delimiter::Parenthesis, f)
1088     }
1089 
1090     /// Advance the parser by one token using provided token as the next one.
bump_with(&mut self, next: (Token, Spacing))1091     fn bump_with(&mut self, next: (Token, Spacing)) {
1092         self.inlined_bump_with(next)
1093     }
1094 
1095     /// This always-inlined version should only be used on hot code paths.
1096     #[inline(always)]
inlined_bump_with(&mut self, (next_token, next_spacing): (Token, Spacing))1097     fn inlined_bump_with(&mut self, (next_token, next_spacing): (Token, Spacing)) {
1098         // Update the current and previous tokens.
1099         self.prev_token = mem::replace(&mut self.token, next_token);
1100         self.token_spacing = next_spacing;
1101 
1102         // Diagnostics.
1103         self.expected_tokens.clear();
1104     }
1105 
1106     /// Advance the parser by one token.
bump(&mut self)1107     pub fn bump(&mut self) {
1108         // Note: destructuring here would give nicer code, but it was found in #96210 to be slower
1109         // than `.0`/`.1` access.
1110         let mut next = self.token_cursor.inlined_next(self.desugar_doc_comments);
1111         self.token_cursor.num_next_calls += 1;
1112         // We've retrieved an token from the underlying
1113         // cursor, so we no longer need to worry about
1114         // an unglued token. See `break_and_eat` for more details
1115         self.token_cursor.break_last_token = false;
1116         if next.0.span.is_dummy() {
1117             // Tweak the location for better diagnostics, but keep syntactic context intact.
1118             let fallback_span = self.token.span;
1119             next.0.span = fallback_span.with_ctxt(next.0.span.ctxt());
1120         }
1121         debug_assert!(!matches!(
1122             next.0.kind,
1123             token::OpenDelim(Delimiter::Invisible) | token::CloseDelim(Delimiter::Invisible)
1124         ));
1125         self.inlined_bump_with(next)
1126     }
1127 
1128     /// Look-ahead `dist` tokens of `self.token` and get access to that token there.
1129     /// When `dist == 0` then the current token is looked at.
look_ahead<R>(&self, dist: usize, looker: impl FnOnce(&Token) -> R) -> R1130     pub fn look_ahead<R>(&self, dist: usize, looker: impl FnOnce(&Token) -> R) -> R {
1131         if dist == 0 {
1132             return looker(&self.token);
1133         }
1134 
1135         let tree_cursor = &self.token_cursor.tree_cursor;
1136         if let Some(&(_, delim, span)) = self.token_cursor.stack.last()
1137             && delim != Delimiter::Invisible
1138         {
1139             let all_normal = (0..dist).all(|i| {
1140                 let token = tree_cursor.look_ahead(i);
1141                 !matches!(token, Some(TokenTree::Delimited(_, Delimiter::Invisible, _)))
1142             });
1143             if all_normal {
1144                 return match tree_cursor.look_ahead(dist - 1) {
1145                     Some(tree) => match tree {
1146                         TokenTree::Token(token, _) => looker(token),
1147                         TokenTree::Delimited(dspan, delim, _) => {
1148                             looker(&Token::new(token::OpenDelim(*delim), dspan.open))
1149                         }
1150                     },
1151                     None => looker(&Token::new(token::CloseDelim(delim), span.close)),
1152                 };
1153             }
1154         }
1155 
1156         let mut cursor = self.token_cursor.clone();
1157         let mut i = 0;
1158         let mut token = Token::dummy();
1159         while i < dist {
1160             token = cursor.next(/* desugar_doc_comments */ false).0;
1161             if matches!(
1162                 token.kind,
1163                 token::OpenDelim(Delimiter::Invisible) | token::CloseDelim(Delimiter::Invisible)
1164             ) {
1165                 continue;
1166             }
1167             i += 1;
1168         }
1169         return looker(&token);
1170     }
1171 
1172     /// Returns whether any of the given keywords are `dist` tokens ahead of the current one.
is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool1173     fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool {
1174         self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw)))
1175     }
1176 
1177     /// Parses asyncness: `async` or nothing.
parse_asyncness(&mut self, case: Case) -> Async1178     fn parse_asyncness(&mut self, case: Case) -> Async {
1179         if self.eat_keyword_case(kw::Async, case) {
1180             let span = self.prev_token.uninterpolated_span();
1181             Async::Yes { span, closure_id: DUMMY_NODE_ID, return_impl_trait_id: DUMMY_NODE_ID }
1182         } else {
1183             Async::No
1184         }
1185     }
1186 
1187     /// Parses unsafety: `unsafe` or nothing.
parse_unsafety(&mut self, case: Case) -> Unsafe1188     fn parse_unsafety(&mut self, case: Case) -> Unsafe {
1189         if self.eat_keyword_case(kw::Unsafe, case) {
1190             Unsafe::Yes(self.prev_token.uninterpolated_span())
1191         } else {
1192             Unsafe::No
1193         }
1194     }
1195 
1196     /// Parses constness: `const` or nothing.
parse_constness(&mut self, case: Case) -> Const1197     fn parse_constness(&mut self, case: Case) -> Const {
1198         self.parse_constness_(case, false)
1199     }
1200 
1201     /// Parses constness for closures (case sensitive, feature-gated)
parse_closure_constness(&mut self) -> Const1202     fn parse_closure_constness(&mut self) -> Const {
1203         let constness = self.parse_constness_(Case::Sensitive, true);
1204         if let Const::Yes(span) = constness {
1205             self.sess.gated_spans.gate(sym::const_closures, span);
1206         }
1207         constness
1208     }
1209 
parse_constness_(&mut self, case: Case, is_closure: bool) -> Const1210     fn parse_constness_(&mut self, case: Case, is_closure: bool) -> Const {
1211         // Avoid const blocks and const closures to be parsed as const items
1212         if (self.check_const_closure() == is_closure)
1213             && self.look_ahead(1, |t| t != &token::OpenDelim(Delimiter::Brace))
1214             && self.eat_keyword_case(kw::Const, case)
1215         {
1216             Const::Yes(self.prev_token.uninterpolated_span())
1217         } else {
1218             Const::No
1219         }
1220     }
1221 
1222     /// Parses inline const expressions.
parse_const_block(&mut self, span: Span, pat: bool) -> PResult<'a, P<Expr>>1223     fn parse_const_block(&mut self, span: Span, pat: bool) -> PResult<'a, P<Expr>> {
1224         if pat {
1225             self.sess.gated_spans.gate(sym::inline_const_pat, span);
1226         } else {
1227             self.sess.gated_spans.gate(sym::inline_const, span);
1228         }
1229         self.eat_keyword(kw::Const);
1230         let (attrs, blk) = self.parse_inner_attrs_and_block()?;
1231         let anon_const = AnonConst {
1232             id: DUMMY_NODE_ID,
1233             value: self.mk_expr(blk.span, ExprKind::Block(blk, None)),
1234         };
1235         let blk_span = anon_const.value.span;
1236         Ok(self.mk_expr_with_attrs(span.to(blk_span), ExprKind::ConstBlock(anon_const), attrs))
1237     }
1238 
1239     /// Parses mutability (`mut` or nothing).
parse_mutability(&mut self) -> Mutability1240     fn parse_mutability(&mut self) -> Mutability {
1241         if self.eat_keyword(kw::Mut) { Mutability::Mut } else { Mutability::Not }
1242     }
1243 
1244     /// Possibly parses mutability (`const` or `mut`).
parse_const_or_mut(&mut self) -> Option<Mutability>1245     fn parse_const_or_mut(&mut self) -> Option<Mutability> {
1246         if self.eat_keyword(kw::Mut) {
1247             Some(Mutability::Mut)
1248         } else if self.eat_keyword(kw::Const) {
1249             Some(Mutability::Not)
1250         } else {
1251             None
1252         }
1253     }
1254 
parse_field_name(&mut self) -> PResult<'a, Ident>1255     fn parse_field_name(&mut self) -> PResult<'a, Ident> {
1256         if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) = self.token.kind
1257         {
1258             if let Some(suffix) = suffix {
1259                 self.expect_no_tuple_index_suffix(self.token.span, suffix);
1260             }
1261             self.bump();
1262             Ok(Ident::new(symbol, self.prev_token.span))
1263         } else {
1264             self.parse_ident_common(true)
1265         }
1266     }
1267 
parse_delim_args(&mut self) -> PResult<'a, P<DelimArgs>>1268     fn parse_delim_args(&mut self) -> PResult<'a, P<DelimArgs>> {
1269         if let Some(args) = self.parse_delim_args_inner() { Ok(P(args)) } else { self.unexpected() }
1270     }
1271 
parse_attr_args(&mut self) -> PResult<'a, AttrArgs>1272     fn parse_attr_args(&mut self) -> PResult<'a, AttrArgs> {
1273         Ok(if let Some(args) = self.parse_delim_args_inner() {
1274             AttrArgs::Delimited(args)
1275         } else {
1276             if self.eat(&token::Eq) {
1277                 let eq_span = self.prev_token.span;
1278                 AttrArgs::Eq(eq_span, AttrArgsEq::Ast(self.parse_expr_force_collect()?))
1279             } else {
1280                 AttrArgs::Empty
1281             }
1282         })
1283     }
1284 
parse_delim_args_inner(&mut self) -> Option<DelimArgs>1285     fn parse_delim_args_inner(&mut self) -> Option<DelimArgs> {
1286         let delimited = self.check(&token::OpenDelim(Delimiter::Parenthesis))
1287             || self.check(&token::OpenDelim(Delimiter::Bracket))
1288             || self.check(&token::OpenDelim(Delimiter::Brace));
1289 
1290         delimited.then(|| {
1291             // We've confirmed above that there is a delimiter so unwrapping is OK.
1292             let TokenTree::Delimited(dspan, delim, tokens) = self.parse_token_tree() else { unreachable!() };
1293 
1294             DelimArgs { dspan, delim: MacDelimiter::from_token(delim).unwrap(), tokens }
1295         })
1296     }
1297 
parse_or_use_outer_attributes( &mut self, already_parsed_attrs: Option<AttrWrapper>, ) -> PResult<'a, AttrWrapper>1298     fn parse_or_use_outer_attributes(
1299         &mut self,
1300         already_parsed_attrs: Option<AttrWrapper>,
1301     ) -> PResult<'a, AttrWrapper> {
1302         if let Some(attrs) = already_parsed_attrs {
1303             Ok(attrs)
1304         } else {
1305             self.parse_outer_attributes()
1306         }
1307     }
1308 
1309     /// Parses a single token tree from the input.
parse_token_tree(&mut self) -> TokenTree1310     pub(crate) fn parse_token_tree(&mut self) -> TokenTree {
1311         match self.token.kind {
1312             token::OpenDelim(..) => {
1313                 // Grab the tokens within the delimiters.
1314                 let tree_cursor = &self.token_cursor.tree_cursor;
1315                 let stream = tree_cursor.stream.clone();
1316                 let (_, delim, span) = *self.token_cursor.stack.last().unwrap();
1317 
1318                 // Advance the token cursor through the entire delimited
1319                 // sequence. After getting the `OpenDelim` we are *within* the
1320                 // delimited sequence, i.e. at depth `d`. After getting the
1321                 // matching `CloseDelim` we are *after* the delimited sequence,
1322                 // i.e. at depth `d - 1`.
1323                 let target_depth = self.token_cursor.stack.len() - 1;
1324                 loop {
1325                     // Advance one token at a time, so `TokenCursor::next()`
1326                     // can capture these tokens if necessary.
1327                     self.bump();
1328                     if self.token_cursor.stack.len() == target_depth {
1329                         debug_assert!(matches!(self.token.kind, token::CloseDelim(_)));
1330                         break;
1331                     }
1332                 }
1333 
1334                 // Consume close delimiter
1335                 self.bump();
1336                 TokenTree::Delimited(span, delim, stream)
1337             }
1338             token::CloseDelim(_) | token::Eof => unreachable!(),
1339             _ => {
1340                 self.bump();
1341                 TokenTree::Token(self.prev_token.clone(), Spacing::Alone)
1342             }
1343         }
1344     }
1345 
1346     /// Parses a stream of tokens into a list of `TokenTree`s, up to EOF.
parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>>1347     pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
1348         let mut tts = Vec::new();
1349         while self.token != token::Eof {
1350             tts.push(self.parse_token_tree());
1351         }
1352         Ok(tts)
1353     }
1354 
parse_tokens(&mut self) -> TokenStream1355     pub fn parse_tokens(&mut self) -> TokenStream {
1356         let mut result = Vec::new();
1357         loop {
1358             match self.token.kind {
1359                 token::Eof | token::CloseDelim(..) => break,
1360                 _ => result.push(self.parse_token_tree()),
1361             }
1362         }
1363         TokenStream::new(result)
1364     }
1365 
1366     /// Evaluates the closure with restrictions in place.
1367     ///
1368     /// Afters the closure is evaluated, restrictions are reset.
with_res<T>(&mut self, res: Restrictions, f: impl FnOnce(&mut Self) -> T) -> T1369     fn with_res<T>(&mut self, res: Restrictions, f: impl FnOnce(&mut Self) -> T) -> T {
1370         let old = self.restrictions;
1371         self.restrictions = res;
1372         let res = f(self);
1373         self.restrictions = old;
1374         res
1375     }
1376 
1377     /// Parses `pub` and `pub(in path)` plus shortcuts `pub(crate)` for `pub(in crate)`, `pub(self)`
1378     /// for `pub(in self)` and `pub(super)` for `pub(in super)`.
1379     /// If the following element can't be a tuple (i.e., it's a function definition), then
1380     /// it's not a tuple struct field), and the contents within the parentheses aren't valid,
1381     /// so emit a proper diagnostic.
1382     // Public for rustfmt usage.
parse_visibility(&mut self, fbt: FollowedByType) -> PResult<'a, Visibility>1383     pub fn parse_visibility(&mut self, fbt: FollowedByType) -> PResult<'a, Visibility> {
1384         maybe_whole!(self, NtVis, |x| x.into_inner());
1385 
1386         if !self.eat_keyword(kw::Pub) {
1387             // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
1388             // keyword to grab a span from for inherited visibility; an empty span at the
1389             // beginning of the current token would seem to be the "Schelling span".
1390             return Ok(Visibility {
1391                 span: self.token.span.shrink_to_lo(),
1392                 kind: VisibilityKind::Inherited,
1393                 tokens: None,
1394             });
1395         }
1396         let lo = self.prev_token.span;
1397 
1398         if self.check(&token::OpenDelim(Delimiter::Parenthesis)) {
1399             // We don't `self.bump()` the `(` yet because this might be a struct definition where
1400             // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
1401             // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
1402             // by the following tokens.
1403             if self.is_keyword_ahead(1, &[kw::In]) {
1404                 // Parse `pub(in path)`.
1405                 self.bump(); // `(`
1406                 self.bump(); // `in`
1407                 let path = self.parse_path(PathStyle::Mod)?; // `path`
1408                 self.expect(&token::CloseDelim(Delimiter::Parenthesis))?; // `)`
1409                 let vis = VisibilityKind::Restricted {
1410                     path: P(path),
1411                     id: ast::DUMMY_NODE_ID,
1412                     shorthand: false,
1413                 };
1414                 return Ok(Visibility {
1415                     span: lo.to(self.prev_token.span),
1416                     kind: vis,
1417                     tokens: None,
1418                 });
1419             } else if self.look_ahead(2, |t| t == &token::CloseDelim(Delimiter::Parenthesis))
1420                 && self.is_keyword_ahead(1, &[kw::Crate, kw::Super, kw::SelfLower])
1421             {
1422                 // Parse `pub(crate)`, `pub(self)`, or `pub(super)`.
1423                 self.bump(); // `(`
1424                 let path = self.parse_path(PathStyle::Mod)?; // `crate`/`super`/`self`
1425                 self.expect(&token::CloseDelim(Delimiter::Parenthesis))?; // `)`
1426                 let vis = VisibilityKind::Restricted {
1427                     path: P(path),
1428                     id: ast::DUMMY_NODE_ID,
1429                     shorthand: true,
1430                 };
1431                 return Ok(Visibility {
1432                     span: lo.to(self.prev_token.span),
1433                     kind: vis,
1434                     tokens: None,
1435                 });
1436             } else if let FollowedByType::No = fbt {
1437                 // Provide this diagnostic if a type cannot follow;
1438                 // in particular, if this is not a tuple struct.
1439                 self.recover_incorrect_vis_restriction()?;
1440                 // Emit diagnostic, but continue with public visibility.
1441             }
1442         }
1443 
1444         Ok(Visibility { span: lo, kind: VisibilityKind::Public, tokens: None })
1445     }
1446 
1447     /// Recovery for e.g. `pub(something) fn ...` or `struct X { pub(something) y: Z }`
recover_incorrect_vis_restriction(&mut self) -> PResult<'a, ()>1448     fn recover_incorrect_vis_restriction(&mut self) -> PResult<'a, ()> {
1449         self.bump(); // `(`
1450         let path = self.parse_path(PathStyle::Mod)?;
1451         self.expect(&token::CloseDelim(Delimiter::Parenthesis))?; // `)`
1452 
1453         let path_str = pprust::path_to_string(&path);
1454         self.sess.emit_err(IncorrectVisibilityRestriction { span: path.span, inner_str: path_str });
1455 
1456         Ok(())
1457     }
1458 
1459     /// Parses `extern string_literal?`.
parse_extern(&mut self, case: Case) -> Extern1460     fn parse_extern(&mut self, case: Case) -> Extern {
1461         if self.eat_keyword_case(kw::Extern, case) {
1462             let mut extern_span = self.prev_token.span;
1463             let abi = self.parse_abi();
1464             if let Some(abi) = abi {
1465                 extern_span = extern_span.to(abi.span);
1466             }
1467             Extern::from_abi(abi, extern_span)
1468         } else {
1469             Extern::None
1470         }
1471     }
1472 
1473     /// Parses a string literal as an ABI spec.
parse_abi(&mut self) -> Option<StrLit>1474     fn parse_abi(&mut self) -> Option<StrLit> {
1475         match self.parse_str_lit() {
1476             Ok(str_lit) => Some(str_lit),
1477             Err(Some(lit)) => match lit.kind {
1478                 ast::LitKind::Err => None,
1479                 _ => {
1480                     self.sess.emit_err(NonStringAbiLiteral { span: lit.span });
1481                     None
1482                 }
1483             },
1484             Err(None) => None,
1485         }
1486     }
1487 
collect_tokens_no_attrs<R: HasAttrs + HasTokens>( &mut self, f: impl FnOnce(&mut Self) -> PResult<'a, R>, ) -> PResult<'a, R>1488     pub fn collect_tokens_no_attrs<R: HasAttrs + HasTokens>(
1489         &mut self,
1490         f: impl FnOnce(&mut Self) -> PResult<'a, R>,
1491     ) -> PResult<'a, R> {
1492         // The only reason to call `collect_tokens_no_attrs` is if you want tokens, so use
1493         // `ForceCollect::Yes`
1494         self.collect_tokens_trailing_token(
1495             AttrWrapper::empty(),
1496             ForceCollect::Yes,
1497             |this, _attrs| Ok((f(this)?, TrailingToken::None)),
1498         )
1499     }
1500 
1501     /// `::{` or `::*`
is_import_coupler(&mut self) -> bool1502     fn is_import_coupler(&mut self) -> bool {
1503         self.check(&token::ModSep)
1504             && self.look_ahead(1, |t| {
1505                 *t == token::OpenDelim(Delimiter::Brace) || *t == token::BinOp(token::Star)
1506             })
1507     }
1508 
clear_expected_tokens(&mut self)1509     pub fn clear_expected_tokens(&mut self) {
1510         self.expected_tokens.clear();
1511     }
1512 
approx_token_stream_pos(&self) -> usize1513     pub fn approx_token_stream_pos(&self) -> usize {
1514         self.token_cursor.num_next_calls
1515     }
1516 }
1517 
make_unclosed_delims_error( unmatched: UnmatchedDelim, sess: &ParseSess, ) -> Option<DiagnosticBuilder<'_, ErrorGuaranteed>>1518 pub(crate) fn make_unclosed_delims_error(
1519     unmatched: UnmatchedDelim,
1520     sess: &ParseSess,
1521 ) -> Option<DiagnosticBuilder<'_, ErrorGuaranteed>> {
1522     // `None` here means an `Eof` was found. We already emit those errors elsewhere, we add them to
1523     // `unmatched_delims` only for error recovery in the `Parser`.
1524     let found_delim = unmatched.found_delim?;
1525     let mut spans = vec![unmatched.found_span];
1526     if let Some(sp) = unmatched.unclosed_span {
1527         spans.push(sp);
1528     };
1529     let err = MismatchedClosingDelimiter {
1530         spans,
1531         delimiter: pprust::token_kind_to_string(&token::CloseDelim(found_delim)).to_string(),
1532         unmatched: unmatched.found_span,
1533         opening_candidate: unmatched.candidate_span,
1534         unclosed: unmatched.unclosed_span,
1535     }
1536     .into_diagnostic(&sess.span_diagnostic);
1537     Some(err)
1538 }
1539 
emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedDelim>, sess: &ParseSess)1540 pub fn emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedDelim>, sess: &ParseSess) {
1541     let _ = sess.reached_eof.fetch_or(
1542         unclosed_delims.iter().any(|unmatched_delim| unmatched_delim.found_delim.is_none()),
1543         Ordering::Relaxed,
1544     );
1545     for unmatched in unclosed_delims.drain(..) {
1546         if let Some(mut e) = make_unclosed_delims_error(unmatched, sess) {
1547             e.emit();
1548         }
1549     }
1550 }
1551 
1552 /// A helper struct used when building an `AttrTokenStream` from
1553 /// a `LazyAttrTokenStream`. Both delimiter and non-delimited tokens
1554 /// are stored as `FlatToken::Token`. A vector of `FlatToken`s
1555 /// is then 'parsed' to build up an `AttrTokenStream` with nested
1556 /// `AttrTokenTree::Delimited` tokens.
1557 #[derive(Debug, Clone)]
1558 pub enum FlatToken {
1559     /// A token - this holds both delimiter (e.g. '{' and '}')
1560     /// and non-delimiter tokens
1561     Token(Token),
1562     /// Holds the `AttributesData` for an AST node. The
1563     /// `AttributesData` is inserted directly into the
1564     /// constructed `AttrTokenStream` as
1565     /// an `AttrTokenTree::Attributes`.
1566     AttrTarget(AttributesData),
1567     /// A special 'empty' token that is ignored during the conversion
1568     /// to an `AttrTokenStream`. This is used to simplify the
1569     /// handling of replace ranges.
1570     Empty,
1571 }
1572 
1573 #[derive(Debug)]
1574 pub enum NtOrTt {
1575     Nt(Nonterminal),
1576     Tt(TokenTree),
1577 }
1578