]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_parse/src/parser/mod.rs
982fde727c8983e6418169e3f4c95d709b8b2f91
[rust.git] / compiler / rustc_parse / src / parser / mod.rs
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::UnmatchedBrace;
14 pub use attr_wrapper::AttrWrapper;
15 pub use diagnostics::AttemptLocalParseRecovery;
16 pub(crate) use item::FnParseMode;
17 pub use pat::{CommaRecoveryMode, RecoverColon, RecoverComma};
18 pub use path::PathStyle;
19
20 use rustc_ast::ptr::P;
21 use rustc_ast::token::{self, Delimiter, Nonterminal, Token, TokenKind};
22 use rustc_ast::tokenstream::AttributesData;
23 use rustc_ast::tokenstream::{self, DelimSpan, Spacing};
24 use rustc_ast::tokenstream::{TokenStream, TokenTree};
25 use rustc_ast::util::case::Case;
26 use rustc_ast::AttrId;
27 use rustc_ast::DUMMY_NODE_ID;
28 use rustc_ast::{self as ast, AnonConst, AttrStyle, Const, DelimArgs, Extern};
29 use rustc_ast::{Async, AttrArgs, AttrArgsEq, Expr, ExprKind, MacDelimiter, Mutability, StrLit};
30 use rustc_ast::{HasAttrs, HasTokens, Unsafe, Visibility, VisibilityKind};
31 use rustc_ast_pretty::pprust;
32 use rustc_data_structures::fx::FxHashMap;
33 use rustc_errors::PResult;
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
41 use std::ops::Range;
42 use std::{cmp, mem, slice};
43
44 use crate::errors::{
45     DocCommentDoesNotDocumentAnything, IncorrectVisibilityRestriction, MismatchedClosingDelimiter,
46     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     /// A list of all unclosed delimiters found by the lexer. If an entry is used for error recovery
150     /// it gets removed from here. Every entry left at the end gets emitted as an independent
151     /// error.
152     pub(super) unclosed_delims: Vec<UnmatchedBrace>,
153     last_unexpected_token_span: Option<Span>,
154     /// Span pointing at the `:` for the last type ascription the parser has seen, and whether it
155     /// looked like it could have been a mistyped path or literal `Option:Some(42)`).
156     pub last_type_ascription: Option<(Span, bool /* likely path typo */)>,
157     /// If present, this `Parser` is not parsing Rust code but rather a macro call.
158     subparser_name: Option<&'static str>,
159     capture_state: CaptureState,
160     /// This allows us to recover when the user forget to add braces around
161     /// multiple statements in the closure body.
162     pub current_closure: Option<ClosureSpans>,
163     /// Whether the parser is allowed to do recovery.
164     /// This is disabled when parsing macro arguments, see #103534
165     pub recovery: Recovery,
166 }
167
168 // This type is used a lot, e.g. it's cloned when matching many declarative macro rules with nonterminals. Make sure
169 // it doesn't unintentionally get bigger.
170 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
171 rustc_data_structures::static_assert_size!(Parser<'_>, 312);
172
173 /// Stores span information about a closure.
174 #[derive(Clone)]
175 pub struct ClosureSpans {
176     pub whole_closure: Span,
177     pub closing_pipe: Span,
178     pub body: Span,
179 }
180
181 /// Indicates a range of tokens that should be replaced by
182 /// the tokens in the provided vector. This is used in two
183 /// places during token collection:
184 ///
185 /// 1. During the parsing of an AST node that may have a `#[derive]`
186 /// attribute, we parse a nested AST node that has `#[cfg]` or `#[cfg_attr]`
187 /// In this case, we use a `ReplaceRange` to replace the entire inner AST node
188 /// with `FlatToken::AttrTarget`, allowing us to perform eager cfg-expansion
189 /// on an `AttrTokenStream`.
190 ///
191 /// 2. When we parse an inner attribute while collecting tokens. We
192 /// remove inner attributes from the token stream entirely, and
193 /// instead track them through the `attrs` field on the AST node.
194 /// This allows us to easily manipulate them (for example, removing
195 /// the first macro inner attribute to invoke a proc-macro).
196 /// When create a `TokenStream`, the inner attributes get inserted
197 /// into the proper place in the token stream.
198 pub type ReplaceRange = (Range<u32>, Vec<(FlatToken, Spacing)>);
199
200 /// Controls how we capture tokens. Capturing can be expensive,
201 /// so we try to avoid performing capturing in cases where
202 /// we will never need an `AttrTokenStream`.
203 #[derive(Copy, Clone)]
204 pub enum Capturing {
205     /// We aren't performing any capturing - this is the default mode.
206     No,
207     /// We are capturing tokens
208     Yes,
209 }
210
211 #[derive(Clone)]
212 struct CaptureState {
213     capturing: Capturing,
214     replace_ranges: Vec<ReplaceRange>,
215     inner_attr_ranges: FxHashMap<AttrId, ReplaceRange>,
216 }
217
218 impl<'a> Drop for Parser<'a> {
219     fn drop(&mut self) {
220         emit_unclosed_delims(&mut self.unclosed_delims, &self.sess);
221     }
222 }
223
224 #[derive(Clone)]
225 struct TokenCursor {
226     // Cursor for the current (innermost) token stream. The delimiters for this
227     // token stream are found in `self.stack.last()`; when that is `None` then
228     // we are in the outermost token stream which never has delimiters.
229     tree_cursor: tokenstream::Cursor,
230
231     // Token streams surrounding the current one. The delimiters for stack[n]'s
232     // tokens are in `stack[n-1]`. `stack[0]` (when present) has no delimiters
233     // because it's the outermost token stream which never has delimiters.
234     stack: Vec<(tokenstream::Cursor, Delimiter, DelimSpan)>,
235
236     desugar_doc_comments: bool,
237
238     // Counts the number of calls to `{,inlined_}next`.
239     num_next_calls: usize,
240
241     // During parsing, we may sometimes need to 'unglue' a
242     // glued token into two component tokens
243     // (e.g. '>>' into '>' and '>), so that the parser
244     // can consume them one at a time. This process
245     // bypasses the normal capturing mechanism
246     // (e.g. `num_next_calls` will not be incremented),
247     // since the 'unglued' tokens due not exist in
248     // the original `TokenStream`.
249     //
250     // If we end up consuming both unglued tokens,
251     // then this is not an issue - we'll end up
252     // capturing the single 'glued' token.
253     //
254     // However, in certain circumstances, we may
255     // want to capture just the first 'unglued' token.
256     // For example, capturing the `Vec<u8>`
257     // in `Option<Vec<u8>>` requires us to unglue
258     // the trailing `>>` token. The `break_last_token`
259     // field is used to track this token - it gets
260     // appended to the captured stream when
261     // we evaluate a `LazyAttrTokenStream`.
262     break_last_token: bool,
263 }
264
265 impl TokenCursor {
266     fn next(&mut self, desugar_doc_comments: bool) -> (Token, Spacing) {
267         self.inlined_next(desugar_doc_comments)
268     }
269
270     /// This always-inlined version should only be used on hot code paths.
271     #[inline(always)]
272     fn inlined_next(&mut self, desugar_doc_comments: bool) -> (Token, Spacing) {
273         loop {
274             // FIXME: we currently don't return `Delimiter` open/close delims. To fix #67062 we will
275             // need to, whereupon the `delim != Delimiter::Invisible` conditions below can be
276             // removed.
277             if let Some(tree) = self.tree_cursor.next_ref() {
278                 match tree {
279                     &TokenTree::Token(ref token, spacing) => match (desugar_doc_comments, token) {
280                         (true, &Token { kind: token::DocComment(_, attr_style, data), span }) => {
281                             let desugared = self.desugar(attr_style, data, span);
282                             self.tree_cursor.replace_prev_and_rewind(desugared);
283                             // Continue to get the first token of the desugared doc comment.
284                         }
285                         _ => {
286                             debug_assert!(!matches!(
287                                 token.kind,
288                                 token::OpenDelim(_) | token::CloseDelim(_)
289                             ));
290                             return (token.clone(), spacing);
291                         }
292                     },
293                     &TokenTree::Delimited(sp, delim, ref tts) => {
294                         let trees = tts.clone().into_trees();
295                         self.stack.push((mem::replace(&mut self.tree_cursor, trees), delim, sp));
296                         if delim != Delimiter::Invisible {
297                             return (Token::new(token::OpenDelim(delim), sp.open), Spacing::Alone);
298                         }
299                         // No open delimiter to return; continue on to the next iteration.
300                     }
301                 };
302             } else if let Some((tree_cursor, delim, span)) = self.stack.pop() {
303                 // We have exhausted this token stream. Move back to its parent token stream.
304                 self.tree_cursor = tree_cursor;
305                 if delim != Delimiter::Invisible {
306                     return (Token::new(token::CloseDelim(delim), span.close), Spacing::Alone);
307                 }
308                 // No close delimiter to return; continue on to the next iteration.
309             } else {
310                 // We have exhausted the outermost token stream.
311                 return (Token::new(token::Eof, DUMMY_SP), Spacing::Alone);
312             }
313         }
314     }
315
316     // Desugar a doc comment into something like `#[doc = r"foo"]`.
317     fn desugar(&mut self, attr_style: AttrStyle, data: Symbol, span: Span) -> Vec<TokenTree> {
318         // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
319         // required to wrap the text. E.g.
320         // - `abc d` is wrapped as `r"abc d"` (num_of_hashes = 0)
321         // - `abc "d"` is wrapped as `r#"abc "d""#` (num_of_hashes = 1)
322         // - `abc "##d##"` is wrapped as `r###"abc ##"d"##"###` (num_of_hashes = 3)
323         let mut num_of_hashes = 0;
324         let mut count = 0;
325         for ch in data.as_str().chars() {
326             count = match ch {
327                 '"' => 1,
328                 '#' if count > 0 => count + 1,
329                 _ => 0,
330             };
331             num_of_hashes = cmp::max(num_of_hashes, count);
332         }
333
334         // `/// foo` becomes `doc = r"foo".
335         let delim_span = DelimSpan::from_single(span);
336         let body = TokenTree::Delimited(
337             delim_span,
338             Delimiter::Bracket,
339             [
340                 TokenTree::token_alone(token::Ident(sym::doc, false), span),
341                 TokenTree::token_alone(token::Eq, span),
342                 TokenTree::token_alone(
343                     TokenKind::lit(token::StrRaw(num_of_hashes), data, None),
344                     span,
345                 ),
346             ]
347             .into_iter()
348             .collect::<TokenStream>(),
349         );
350
351         if attr_style == AttrStyle::Inner {
352             vec![
353                 TokenTree::token_alone(token::Pound, span),
354                 TokenTree::token_alone(token::Not, span),
355                 body,
356             ]
357         } else {
358             vec![TokenTree::token_alone(token::Pound, span), body]
359         }
360     }
361 }
362
363 #[derive(Debug, Clone, PartialEq)]
364 enum TokenType {
365     Token(TokenKind),
366     Keyword(Symbol),
367     Operator,
368     Lifetime,
369     Ident,
370     Path,
371     Type,
372     Const,
373 }
374
375 impl TokenType {
376     fn to_string(&self) -> String {
377         match self {
378             TokenType::Token(t) => format!("`{}`", pprust::token_kind_to_string(t)),
379             TokenType::Keyword(kw) => format!("`{}`", kw),
380             TokenType::Operator => "an operator".to_string(),
381             TokenType::Lifetime => "lifetime".to_string(),
382             TokenType::Ident => "identifier".to_string(),
383             TokenType::Path => "path".to_string(),
384             TokenType::Type => "type".to_string(),
385             TokenType::Const => "a const expression".to_string(),
386         }
387     }
388 }
389
390 #[derive(Copy, Clone, Debug)]
391 enum TokenExpectType {
392     Expect,
393     NoExpect,
394 }
395
396 /// A sequence separator.
397 struct SeqSep {
398     /// The separator token.
399     sep: Option<TokenKind>,
400     /// `true` if a trailing separator is allowed.
401     trailing_sep_allowed: bool,
402 }
403
404 impl SeqSep {
405     fn trailing_allowed(t: TokenKind) -> SeqSep {
406         SeqSep { sep: Some(t), trailing_sep_allowed: true }
407     }
408
409     fn none() -> SeqSep {
410         SeqSep { sep: None, trailing_sep_allowed: false }
411     }
412 }
413
414 pub enum FollowedByType {
415     Yes,
416     No,
417 }
418
419 #[derive(Clone, Copy, PartialEq, Eq)]
420 pub enum TokenDescription {
421     ReservedIdentifier,
422     Keyword,
423     ReservedKeyword,
424     DocComment,
425 }
426
427 impl TokenDescription {
428     pub fn from_token(token: &Token) -> Option<Self> {
429         match token.kind {
430             _ if token.is_special_ident() => Some(TokenDescription::ReservedIdentifier),
431             _ if token.is_used_keyword() => Some(TokenDescription::Keyword),
432             _ if token.is_unused_keyword() => Some(TokenDescription::ReservedKeyword),
433             token::DocComment(..) => Some(TokenDescription::DocComment),
434             _ => None,
435         }
436     }
437 }
438
439 pub(super) fn token_descr(token: &Token) -> String {
440     let name = pprust::token_to_string(token).to_string();
441
442     let kind = TokenDescription::from_token(token).map(|kind| match kind {
443         TokenDescription::ReservedIdentifier => "reserved identifier",
444         TokenDescription::Keyword => "keyword",
445         TokenDescription::ReservedKeyword => "reserved keyword",
446         TokenDescription::DocComment => "doc comment",
447     });
448
449     if let Some(kind) = kind { format!("{} `{}`", kind, name) } else { format!("`{}`", name) }
450 }
451
452 impl<'a> Parser<'a> {
453     pub fn new(
454         sess: &'a ParseSess,
455         tokens: TokenStream,
456         desugar_doc_comments: bool,
457         subparser_name: Option<&'static str>,
458     ) -> Self {
459         let mut parser = Parser {
460             sess,
461             token: Token::dummy(),
462             token_spacing: Spacing::Alone,
463             prev_token: Token::dummy(),
464             capture_cfg: false,
465             restrictions: Restrictions::empty(),
466             expected_tokens: Vec::new(),
467             token_cursor: TokenCursor {
468                 tree_cursor: tokens.into_trees(),
469                 stack: Vec::new(),
470                 num_next_calls: 0,
471                 desugar_doc_comments,
472                 break_last_token: false,
473             },
474             desugar_doc_comments,
475             unmatched_angle_bracket_count: 0,
476             max_angle_bracket_count: 0,
477             unclosed_delims: Vec::new(),
478             last_unexpected_token_span: None,
479             last_type_ascription: None,
480             subparser_name,
481             capture_state: CaptureState {
482                 capturing: Capturing::No,
483                 replace_ranges: Vec::new(),
484                 inner_attr_ranges: Default::default(),
485             },
486             current_closure: None,
487             recovery: Recovery::Allowed,
488         };
489
490         // Make parser point to the first token.
491         parser.bump();
492
493         parser
494     }
495
496     pub fn recovery(mut self, recovery: Recovery) -> Self {
497         self.recovery = recovery;
498         self
499     }
500
501     /// Whether the parser is allowed to recover from broken code.
502     ///
503     /// If this returns false, recovering broken code into valid code (especially if this recovery does lookahead)
504     /// is not allowed. All recovery done by the parser must be gated behind this check.
505     ///
506     /// Technically, this only needs to restrict eager recovery by doing lookahead at more tokens.
507     /// But making the distinction is very subtle, and simply forbidding all recovery is a lot simpler to uphold.
508     fn may_recover(&self) -> bool {
509         matches!(self.recovery, Recovery::Allowed)
510     }
511
512     pub fn unexpected<T>(&mut self) -> PResult<'a, T> {
513         match self.expect_one_of(&[], &[]) {
514             Err(e) => Err(e),
515             // We can get `Ok(true)` from `recover_closing_delimiter`
516             // which is called in `expected_one_of_not_found`.
517             Ok(_) => FatalError.raise(),
518         }
519     }
520
521     /// Expects and consumes the token `t`. Signals an error if the next token is not `t`.
522     pub fn expect(&mut self, t: &TokenKind) -> PResult<'a, bool /* recovered */> {
523         if self.expected_tokens.is_empty() {
524             if self.token == *t {
525                 self.bump();
526                 Ok(false)
527             } else {
528                 self.unexpected_try_recover(t)
529             }
530         } else {
531             self.expect_one_of(slice::from_ref(t), &[])
532         }
533     }
534
535     /// Expect next token to be edible or inedible token. If edible,
536     /// then consume it; if inedible, then return without consuming
537     /// anything. Signal a fatal error if next token is unexpected.
538     pub fn expect_one_of(
539         &mut self,
540         edible: &[TokenKind],
541         inedible: &[TokenKind],
542     ) -> PResult<'a, bool /* recovered */> {
543         if edible.contains(&self.token.kind) {
544             self.bump();
545             Ok(false)
546         } else if inedible.contains(&self.token.kind) {
547             // leave it in the input
548             Ok(false)
549         } else if self.last_unexpected_token_span == Some(self.token.span) {
550             FatalError.raise();
551         } else {
552             self.expected_one_of_not_found(edible, inedible)
553         }
554     }
555
556     // Public for rustfmt usage.
557     pub fn parse_ident(&mut self) -> PResult<'a, Ident> {
558         self.parse_ident_common(true)
559     }
560
561     fn ident_or_err(&mut self) -> PResult<'a, (Ident, /* is_raw */ bool)> {
562         self.token.ident().ok_or_else(|| match self.prev_token.kind {
563             TokenKind::DocComment(..) => DocCommentDoesNotDocumentAnything {
564                 span: self.prev_token.span,
565                 missing_comma: None,
566             }
567             .into_diagnostic(&self.sess.span_diagnostic),
568             _ => self.expected_ident_found(),
569         })
570     }
571
572     fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, Ident> {
573         let (ident, is_raw) = self.ident_or_err()?;
574         if !is_raw && ident.is_reserved() {
575             let mut err = self.expected_ident_found();
576             if recover {
577                 err.emit();
578             } else {
579                 return Err(err);
580             }
581         }
582         self.bump();
583         Ok(ident)
584     }
585
586     /// Checks if the next token is `tok`, and returns `true` if so.
587     ///
588     /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
589     /// encountered.
590     fn check(&mut self, tok: &TokenKind) -> bool {
591         let is_present = self.token == *tok;
592         if !is_present {
593             self.expected_tokens.push(TokenType::Token(tok.clone()));
594         }
595         is_present
596     }
597
598     fn check_noexpect(&self, tok: &TokenKind) -> bool {
599         self.token == *tok
600     }
601
602     /// Consumes a token 'tok' if it exists. Returns whether the given token was present.
603     ///
604     /// the main purpose of this function is to reduce the cluttering of the suggestions list
605     /// which using the normal eat method could introduce in some cases.
606     pub fn eat_noexpect(&mut self, tok: &TokenKind) -> bool {
607         let is_present = self.check_noexpect(tok);
608         if is_present {
609             self.bump()
610         }
611         is_present
612     }
613
614     /// Consumes a token 'tok' if it exists. Returns whether the given token was present.
615     pub fn eat(&mut self, tok: &TokenKind) -> bool {
616         let is_present = self.check(tok);
617         if is_present {
618             self.bump()
619         }
620         is_present
621     }
622
623     /// If the next token is the given keyword, returns `true` without eating it.
624     /// An expectation is also added for diagnostics purposes.
625     fn check_keyword(&mut self, kw: Symbol) -> bool {
626         self.expected_tokens.push(TokenType::Keyword(kw));
627         self.token.is_keyword(kw)
628     }
629
630     fn check_keyword_case(&mut self, kw: Symbol, case: Case) -> bool {
631         if self.check_keyword(kw) {
632             return true;
633         }
634
635         if case == Case::Insensitive
636         && let Some((ident, /* is_raw */ false)) = self.token.ident()
637         && ident.as_str().to_lowercase() == kw.as_str().to_lowercase() {
638             true
639         } else {
640             false
641         }
642     }
643
644     /// If the next token is the given keyword, eats it and returns `true`.
645     /// Otherwise, returns `false`. An expectation is also added for diagnostics purposes.
646     // Public for rustfmt usage.
647     pub fn eat_keyword(&mut self, kw: Symbol) -> bool {
648         if self.check_keyword(kw) {
649             self.bump();
650             true
651         } else {
652             false
653         }
654     }
655
656     /// Eats a keyword, optionally ignoring the case.
657     /// If the case differs (and is ignored) an error is issued.
658     /// This is useful for recovery.
659     fn eat_keyword_case(&mut self, kw: Symbol, case: Case) -> bool {
660         if self.eat_keyword(kw) {
661             return true;
662         }
663
664         if case == Case::Insensitive
665         && let Some((ident, /* is_raw */ false)) = self.token.ident()
666         && ident.as_str().to_lowercase() == kw.as_str().to_lowercase() {
667             self
668                 .struct_span_err(ident.span, format!("keyword `{kw}` is written in a wrong case"))
669                 .span_suggestion(
670                     ident.span,
671                     "write it in the correct case",
672                     kw,
673                     Applicability::MachineApplicable
674                 ).emit();
675
676             self.bump();
677             return true;
678         }
679
680         false
681     }
682
683     fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool {
684         if self.token.is_keyword(kw) {
685             self.bump();
686             true
687         } else {
688             false
689         }
690     }
691
692     /// If the given word is not a keyword, signals an error.
693     /// If the next token is not the given word, signals an error.
694     /// Otherwise, eats it.
695     fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> {
696         if !self.eat_keyword(kw) { self.unexpected() } else { Ok(()) }
697     }
698
699     /// Is the given keyword `kw` followed by a non-reserved identifier?
700     fn is_kw_followed_by_ident(&self, kw: Symbol) -> bool {
701         self.token.is_keyword(kw) && self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
702     }
703
704     fn check_or_expected(&mut self, ok: bool, typ: TokenType) -> bool {
705         if ok {
706             true
707         } else {
708             self.expected_tokens.push(typ);
709             false
710         }
711     }
712
713     fn check_ident(&mut self) -> bool {
714         self.check_or_expected(self.token.is_ident(), TokenType::Ident)
715     }
716
717     fn check_path(&mut self) -> bool {
718         self.check_or_expected(self.token.is_path_start(), TokenType::Path)
719     }
720
721     fn check_type(&mut self) -> bool {
722         self.check_or_expected(self.token.can_begin_type(), TokenType::Type)
723     }
724
725     fn check_const_arg(&mut self) -> bool {
726         self.check_or_expected(self.token.can_begin_const_arg(), TokenType::Const)
727     }
728
729     fn check_const_closure(&self) -> bool {
730         self.is_keyword_ahead(0, &[kw::Const])
731             && self.look_ahead(1, |t| match &t.kind {
732                 token::Ident(kw::Move | kw::Static | kw::Async, _)
733                 | token::OrOr
734                 | token::BinOp(token::Or) => true,
735                 _ => false,
736             })
737     }
738
739     fn check_inline_const(&self, dist: usize) -> bool {
740         self.is_keyword_ahead(dist, &[kw::Const])
741             && self.look_ahead(dist + 1, |t| match &t.kind {
742                 token::Interpolated(nt) => matches!(**nt, token::NtBlock(..)),
743                 token::OpenDelim(Delimiter::Brace) => true,
744                 _ => false,
745             })
746     }
747
748     /// Checks to see if the next token is either `+` or `+=`.
749     /// Otherwise returns `false`.
750     fn check_plus(&mut self) -> bool {
751         self.check_or_expected(
752             self.token.is_like_plus(),
753             TokenType::Token(token::BinOp(token::Plus)),
754         )
755     }
756
757     /// Eats the expected token if it's present possibly breaking
758     /// compound tokens like multi-character operators in process.
759     /// Returns `true` if the token was eaten.
760     fn break_and_eat(&mut self, expected: TokenKind) -> bool {
761         if self.token.kind == expected {
762             self.bump();
763             return true;
764         }
765         match self.token.kind.break_two_token_op() {
766             Some((first, second)) if first == expected => {
767                 let first_span = self.sess.source_map().start_point(self.token.span);
768                 let second_span = self.token.span.with_lo(first_span.hi());
769                 self.token = Token::new(first, first_span);
770                 // Keep track of this token - if we end token capturing now,
771                 // we'll want to append this token to the captured stream.
772                 //
773                 // If we consume any additional tokens, then this token
774                 // is not needed (we'll capture the entire 'glued' token),
775                 // and `bump` will set this field to `None`
776                 self.token_cursor.break_last_token = true;
777                 // Use the spacing of the glued token as the spacing
778                 // of the unglued second token.
779                 self.bump_with((Token::new(second, second_span), self.token_spacing));
780                 true
781             }
782             _ => {
783                 self.expected_tokens.push(TokenType::Token(expected));
784                 false
785             }
786         }
787     }
788
789     /// Eats `+` possibly breaking tokens like `+=` in process.
790     fn eat_plus(&mut self) -> bool {
791         self.break_and_eat(token::BinOp(token::Plus))
792     }
793
794     /// Eats `&` possibly breaking tokens like `&&` in process.
795     /// Signals an error if `&` is not eaten.
796     fn expect_and(&mut self) -> PResult<'a, ()> {
797         if self.break_and_eat(token::BinOp(token::And)) { Ok(()) } else { self.unexpected() }
798     }
799
800     /// Eats `|` possibly breaking tokens like `||` in process.
801     /// Signals an error if `|` was not eaten.
802     fn expect_or(&mut self) -> PResult<'a, ()> {
803         if self.break_and_eat(token::BinOp(token::Or)) { Ok(()) } else { self.unexpected() }
804     }
805
806     /// Eats `<` possibly breaking tokens like `<<` in process.
807     fn eat_lt(&mut self) -> bool {
808         let ate = self.break_and_eat(token::Lt);
809         if ate {
810             // See doc comment for `unmatched_angle_bracket_count`.
811             self.unmatched_angle_bracket_count += 1;
812             self.max_angle_bracket_count += 1;
813             debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count);
814         }
815         ate
816     }
817
818     /// Eats `<` possibly breaking tokens like `<<` in process.
819     /// Signals an error if `<` was not eaten.
820     fn expect_lt(&mut self) -> PResult<'a, ()> {
821         if self.eat_lt() { Ok(()) } else { self.unexpected() }
822     }
823
824     /// Eats `>` possibly breaking tokens like `>>` in process.
825     /// Signals an error if `>` was not eaten.
826     fn expect_gt(&mut self) -> PResult<'a, ()> {
827         if self.break_and_eat(token::Gt) {
828             // See doc comment for `unmatched_angle_bracket_count`.
829             if self.unmatched_angle_bracket_count > 0 {
830                 self.unmatched_angle_bracket_count -= 1;
831                 debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count);
832             }
833             Ok(())
834         } else {
835             self.unexpected()
836         }
837     }
838
839     fn expect_any_with_type(&mut self, kets: &[&TokenKind], expect: TokenExpectType) -> bool {
840         kets.iter().any(|k| match expect {
841             TokenExpectType::Expect => self.check(k),
842             TokenExpectType::NoExpect => self.token == **k,
843         })
844     }
845
846     fn parse_seq_to_before_tokens<T>(
847         &mut self,
848         kets: &[&TokenKind],
849         sep: SeqSep,
850         expect: TokenExpectType,
851         mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
852     ) -> PResult<'a, (Vec<T>, bool /* trailing */, bool /* recovered */)> {
853         let mut first = true;
854         let mut recovered = false;
855         let mut trailing = false;
856         let mut v = vec![];
857         let unclosed_delims = !self.unclosed_delims.is_empty();
858
859         while !self.expect_any_with_type(kets, expect) {
860             if let token::CloseDelim(..) | token::Eof = self.token.kind {
861                 break;
862             }
863             if let Some(t) = &sep.sep {
864                 if first {
865                     first = false;
866                 } else {
867                     match self.expect(t) {
868                         Ok(false) => {
869                             self.current_closure.take();
870                         }
871                         Ok(true) => {
872                             self.current_closure.take();
873                             recovered = true;
874                             break;
875                         }
876                         Err(mut expect_err) => {
877                             let sp = self.prev_token.span.shrink_to_hi();
878                             let token_str = pprust::token_kind_to_string(t);
879
880                             match self.current_closure.take() {
881                                 Some(closure_spans) if self.token.kind == TokenKind::Semi => {
882                                     // Finding a semicolon instead of a comma
883                                     // after a closure body indicates that the
884                                     // closure body may be a block but the user
885                                     // forgot to put braces around its
886                                     // statements.
887
888                                     self.recover_missing_braces_around_closure_body(
889                                         closure_spans,
890                                         expect_err,
891                                     )?;
892
893                                     continue;
894                                 }
895
896                                 _ => {
897                                     // Attempt to keep parsing if it was a similar separator.
898                                     if let Some(tokens) = t.similar_tokens() {
899                                         if tokens.contains(&self.token.kind) && !unclosed_delims {
900                                             self.bump();
901                                         }
902                                     }
903                                 }
904                             }
905
906                             // If this was a missing `@` in a binding pattern
907                             // bail with a suggestion
908                             // https://github.com/rust-lang/rust/issues/72373
909                             if self.prev_token.is_ident() && self.token.kind == token::DotDot {
910                                 let msg = format!(
911                                     "if you meant to bind the contents of \
912                                     the rest of the array pattern into `{}`, use `@`",
913                                     pprust::token_to_string(&self.prev_token)
914                                 );
915                                 expect_err
916                                     .span_suggestion_verbose(
917                                         self.prev_token.span.shrink_to_hi().until(self.token.span),
918                                         &msg,
919                                         " @ ",
920                                         Applicability::MaybeIncorrect,
921                                     )
922                                     .emit();
923                                 break;
924                             }
925
926                             // Attempt to keep parsing if it was an omitted separator.
927                             match f(self) {
928                                 Ok(t) => {
929                                     // Parsed successfully, therefore most probably the code only
930                                     // misses a separator.
931                                     expect_err
932                                         .span_suggestion_short(
933                                             sp,
934                                             &format!("missing `{}`", token_str),
935                                             token_str,
936                                             Applicability::MaybeIncorrect,
937                                         )
938                                         .emit();
939
940                                     v.push(t);
941                                     continue;
942                                 }
943                                 Err(e) => {
944                                     // Parsing failed, therefore it must be something more serious
945                                     // than just a missing separator.
946                                     for xx in &e.children {
947                                         // propagate the help message from sub error 'e' to main error 'expect_err;
948                                         expect_err.children.push(xx.clone());
949                                     }
950                                     expect_err.emit();
951
952                                     e.cancel();
953                                     break;
954                                 }
955                             }
956                         }
957                     }
958                 }
959             }
960             if sep.trailing_sep_allowed && self.expect_any_with_type(kets, expect) {
961                 trailing = true;
962                 break;
963             }
964
965             let t = f(self)?;
966             v.push(t);
967         }
968
969         Ok((v, trailing, recovered))
970     }
971
972     fn recover_missing_braces_around_closure_body(
973         &mut self,
974         closure_spans: ClosureSpans,
975         mut expect_err: DiagnosticBuilder<'_, ErrorGuaranteed>,
976     ) -> PResult<'a, ()> {
977         let initial_semicolon = self.token.span;
978
979         while self.eat(&TokenKind::Semi) {
980             let _ = self.parse_stmt(ForceCollect::Yes)?;
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.
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, (Vec<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.
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, (Vec<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.
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, (Vec<T>, bool)> {
1066         self.expect(bra)?;
1067         self.parse_seq_to_end(ket, sep, f)
1068     }
1069
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, (Vec<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
1083     fn parse_paren_comma_seq<T>(
1084         &mut self,
1085         f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1086     ) -> PResult<'a, (Vec<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.
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)]
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.
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.
1130     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.
1173     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.
1178     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.
1188     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.
1197     fn parse_constness(&mut self, case: Case) -> Const {
1198         // Avoid const blocks to be parsed as const items
1199         if self.look_ahead(1, |t| t != &token::OpenDelim(Delimiter::Brace))
1200             && self.eat_keyword_case(kw::Const, case)
1201         {
1202             Const::Yes(self.prev_token.uninterpolated_span())
1203         } else {
1204             Const::No
1205         }
1206     }
1207
1208     /// Parses inline const expressions.
1209     fn parse_const_block(&mut self, span: Span, pat: bool) -> PResult<'a, P<Expr>> {
1210         if pat {
1211             self.sess.gated_spans.gate(sym::inline_const_pat, span);
1212         } else {
1213             self.sess.gated_spans.gate(sym::inline_const, span);
1214         }
1215         self.eat_keyword(kw::Const);
1216         let (attrs, blk) = self.parse_inner_attrs_and_block()?;
1217         let anon_const = AnonConst {
1218             id: DUMMY_NODE_ID,
1219             value: self.mk_expr(blk.span, ExprKind::Block(blk, None)),
1220         };
1221         let blk_span = anon_const.value.span;
1222         Ok(self.mk_expr_with_attrs(span.to(blk_span), ExprKind::ConstBlock(anon_const), attrs))
1223     }
1224
1225     /// Parses mutability (`mut` or nothing).
1226     fn parse_mutability(&mut self) -> Mutability {
1227         if self.eat_keyword(kw::Mut) { Mutability::Mut } else { Mutability::Not }
1228     }
1229
1230     /// Possibly parses mutability (`const` or `mut`).
1231     fn parse_const_or_mut(&mut self) -> Option<Mutability> {
1232         if self.eat_keyword(kw::Mut) {
1233             Some(Mutability::Mut)
1234         } else if self.eat_keyword(kw::Const) {
1235             Some(Mutability::Not)
1236         } else {
1237             None
1238         }
1239     }
1240
1241     fn parse_field_name(&mut self) -> PResult<'a, Ident> {
1242         if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) = self.token.kind
1243         {
1244             if let Some(suffix) = suffix {
1245                 self.expect_no_tuple_index_suffix(self.token.span, suffix);
1246             }
1247             self.bump();
1248             Ok(Ident::new(symbol, self.prev_token.span))
1249         } else {
1250             self.parse_ident_common(true)
1251         }
1252     }
1253
1254     fn parse_delim_args(&mut self) -> PResult<'a, P<DelimArgs>> {
1255         if let Some(args) = self.parse_delim_args_inner() { Ok(P(args)) } else { self.unexpected() }
1256     }
1257
1258     fn parse_attr_args(&mut self) -> PResult<'a, AttrArgs> {
1259         Ok(if let Some(args) = self.parse_delim_args_inner() {
1260             AttrArgs::Delimited(args)
1261         } else {
1262             if self.eat(&token::Eq) {
1263                 let eq_span = self.prev_token.span;
1264                 AttrArgs::Eq(eq_span, AttrArgsEq::Ast(self.parse_expr_force_collect()?))
1265             } else {
1266                 AttrArgs::Empty
1267             }
1268         })
1269     }
1270
1271     fn parse_delim_args_inner(&mut self) -> Option<DelimArgs> {
1272         if self.check(&token::OpenDelim(Delimiter::Parenthesis))
1273             || self.check(&token::OpenDelim(Delimiter::Bracket))
1274             || self.check(&token::OpenDelim(Delimiter::Brace))
1275         {
1276             match self.parse_token_tree() {
1277                 // We've confirmed above that there is a delimiter so unwrapping is OK.
1278                 TokenTree::Delimited(dspan, delim, tokens) => Some(DelimArgs {
1279                     dspan,
1280                     delim: MacDelimiter::from_token(delim).unwrap(),
1281                     tokens,
1282                 }),
1283                 _ => unreachable!(),
1284             }
1285         } else {
1286             None
1287         }
1288     }
1289
1290     fn parse_or_use_outer_attributes(
1291         &mut self,
1292         already_parsed_attrs: Option<AttrWrapper>,
1293     ) -> PResult<'a, AttrWrapper> {
1294         if let Some(attrs) = already_parsed_attrs {
1295             Ok(attrs)
1296         } else {
1297             self.parse_outer_attributes()
1298         }
1299     }
1300
1301     /// Parses a single token tree from the input.
1302     pub(crate) fn parse_token_tree(&mut self) -> TokenTree {
1303         match self.token.kind {
1304             token::OpenDelim(..) => {
1305                 // Grab the tokens within the delimiters.
1306                 let tree_cursor = &self.token_cursor.tree_cursor;
1307                 let stream = tree_cursor.stream.clone();
1308                 let (_, delim, span) = *self.token_cursor.stack.last().unwrap();
1309
1310                 // Advance the token cursor through the entire delimited
1311                 // sequence. After getting the `OpenDelim` we are *within* the
1312                 // delimited sequence, i.e. at depth `d`. After getting the
1313                 // matching `CloseDelim` we are *after* the delimited sequence,
1314                 // i.e. at depth `d - 1`.
1315                 let target_depth = self.token_cursor.stack.len() - 1;
1316                 loop {
1317                     // Advance one token at a time, so `TokenCursor::next()`
1318                     // can capture these tokens if necessary.
1319                     self.bump();
1320                     if self.token_cursor.stack.len() == target_depth {
1321                         debug_assert!(matches!(self.token.kind, token::CloseDelim(_)));
1322                         break;
1323                     }
1324                 }
1325
1326                 // Consume close delimiter
1327                 self.bump();
1328                 TokenTree::Delimited(span, delim, stream)
1329             }
1330             token::CloseDelim(_) | token::Eof => unreachable!(),
1331             _ => {
1332                 self.bump();
1333                 TokenTree::Token(self.prev_token.clone(), Spacing::Alone)
1334             }
1335         }
1336     }
1337
1338     /// Parses a stream of tokens into a list of `TokenTree`s, up to EOF.
1339     pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
1340         let mut tts = Vec::new();
1341         while self.token != token::Eof {
1342             tts.push(self.parse_token_tree());
1343         }
1344         Ok(tts)
1345     }
1346
1347     pub fn parse_tokens(&mut self) -> TokenStream {
1348         let mut result = Vec::new();
1349         loop {
1350             match self.token.kind {
1351                 token::Eof | token::CloseDelim(..) => break,
1352                 _ => result.push(self.parse_token_tree()),
1353             }
1354         }
1355         TokenStream::new(result)
1356     }
1357
1358     /// Evaluates the closure with restrictions in place.
1359     ///
1360     /// Afters the closure is evaluated, restrictions are reset.
1361     fn with_res<T>(&mut self, res: Restrictions, f: impl FnOnce(&mut Self) -> T) -> T {
1362         let old = self.restrictions;
1363         self.restrictions = res;
1364         let res = f(self);
1365         self.restrictions = old;
1366         res
1367     }
1368
1369     /// Parses `pub` and `pub(in path)` plus shortcuts `pub(crate)` for `pub(in crate)`, `pub(self)`
1370     /// for `pub(in self)` and `pub(super)` for `pub(in super)`.
1371     /// If the following element can't be a tuple (i.e., it's a function definition), then
1372     /// it's not a tuple struct field), and the contents within the parentheses aren't valid,
1373     /// so emit a proper diagnostic.
1374     // Public for rustfmt usage.
1375     pub fn parse_visibility(&mut self, fbt: FollowedByType) -> PResult<'a, Visibility> {
1376         maybe_whole!(self, NtVis, |x| x.into_inner());
1377
1378         if !self.eat_keyword(kw::Pub) {
1379             // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
1380             // keyword to grab a span from for inherited visibility; an empty span at the
1381             // beginning of the current token would seem to be the "Schelling span".
1382             return Ok(Visibility {
1383                 span: self.token.span.shrink_to_lo(),
1384                 kind: VisibilityKind::Inherited,
1385                 tokens: None,
1386             });
1387         }
1388         let lo = self.prev_token.span;
1389
1390         if self.check(&token::OpenDelim(Delimiter::Parenthesis)) {
1391             // We don't `self.bump()` the `(` yet because this might be a struct definition where
1392             // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
1393             // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
1394             // by the following tokens.
1395             if self.is_keyword_ahead(1, &[kw::In]) {
1396                 // Parse `pub(in path)`.
1397                 self.bump(); // `(`
1398                 self.bump(); // `in`
1399                 let path = self.parse_path(PathStyle::Mod)?; // `path`
1400                 self.expect(&token::CloseDelim(Delimiter::Parenthesis))?; // `)`
1401                 let vis = VisibilityKind::Restricted {
1402                     path: P(path),
1403                     id: ast::DUMMY_NODE_ID,
1404                     shorthand: false,
1405                 };
1406                 return Ok(Visibility {
1407                     span: lo.to(self.prev_token.span),
1408                     kind: vis,
1409                     tokens: None,
1410                 });
1411             } else if self.look_ahead(2, |t| t == &token::CloseDelim(Delimiter::Parenthesis))
1412                 && self.is_keyword_ahead(1, &[kw::Crate, kw::Super, kw::SelfLower])
1413             {
1414                 // Parse `pub(crate)`, `pub(self)`, or `pub(super)`.
1415                 self.bump(); // `(`
1416                 let path = self.parse_path(PathStyle::Mod)?; // `crate`/`super`/`self`
1417                 self.expect(&token::CloseDelim(Delimiter::Parenthesis))?; // `)`
1418                 let vis = VisibilityKind::Restricted {
1419                     path: P(path),
1420                     id: ast::DUMMY_NODE_ID,
1421                     shorthand: true,
1422                 };
1423                 return Ok(Visibility {
1424                     span: lo.to(self.prev_token.span),
1425                     kind: vis,
1426                     tokens: None,
1427                 });
1428             } else if let FollowedByType::No = fbt {
1429                 // Provide this diagnostic if a type cannot follow;
1430                 // in particular, if this is not a tuple struct.
1431                 self.recover_incorrect_vis_restriction()?;
1432                 // Emit diagnostic, but continue with public visibility.
1433             }
1434         }
1435
1436         Ok(Visibility { span: lo, kind: VisibilityKind::Public, tokens: None })
1437     }
1438
1439     /// Recovery for e.g. `pub(something) fn ...` or `struct X { pub(something) y: Z }`
1440     fn recover_incorrect_vis_restriction(&mut self) -> PResult<'a, ()> {
1441         self.bump(); // `(`
1442         let path = self.parse_path(PathStyle::Mod)?;
1443         self.expect(&token::CloseDelim(Delimiter::Parenthesis))?; // `)`
1444
1445         let path_str = pprust::path_to_string(&path);
1446         self.sess.emit_err(IncorrectVisibilityRestriction { span: path.span, inner_str: path_str });
1447
1448         Ok(())
1449     }
1450
1451     /// Parses `extern string_literal?`.
1452     fn parse_extern(&mut self, case: Case) -> Extern {
1453         if self.eat_keyword_case(kw::Extern, case) {
1454             let mut extern_span = self.prev_token.span;
1455             let abi = self.parse_abi();
1456             if let Some(abi) = abi {
1457                 extern_span = extern_span.to(abi.span);
1458             }
1459             Extern::from_abi(abi, extern_span)
1460         } else {
1461             Extern::None
1462         }
1463     }
1464
1465     /// Parses a string literal as an ABI spec.
1466     fn parse_abi(&mut self) -> Option<StrLit> {
1467         match self.parse_str_lit() {
1468             Ok(str_lit) => Some(str_lit),
1469             Err(Some(lit)) => match lit.kind {
1470                 ast::LitKind::Err => None,
1471                 _ => {
1472                     self.sess.emit_err(NonStringAbiLiteral { span: lit.span });
1473                     None
1474                 }
1475             },
1476             Err(None) => None,
1477         }
1478     }
1479
1480     pub fn collect_tokens_no_attrs<R: HasAttrs + HasTokens>(
1481         &mut self,
1482         f: impl FnOnce(&mut Self) -> PResult<'a, R>,
1483     ) -> PResult<'a, R> {
1484         // The only reason to call `collect_tokens_no_attrs` is if you want tokens, so use
1485         // `ForceCollect::Yes`
1486         self.collect_tokens_trailing_token(
1487             AttrWrapper::empty(),
1488             ForceCollect::Yes,
1489             |this, _attrs| Ok((f(this)?, TrailingToken::None)),
1490         )
1491     }
1492
1493     /// `::{` or `::*`
1494     fn is_import_coupler(&mut self) -> bool {
1495         self.check(&token::ModSep)
1496             && self.look_ahead(1, |t| {
1497                 *t == token::OpenDelim(Delimiter::Brace) || *t == token::BinOp(token::Star)
1498             })
1499     }
1500
1501     pub fn clear_expected_tokens(&mut self) {
1502         self.expected_tokens.clear();
1503     }
1504
1505     pub fn approx_token_stream_pos(&self) -> usize {
1506         self.token_cursor.num_next_calls
1507     }
1508 }
1509
1510 pub(crate) fn make_unclosed_delims_error(
1511     unmatched: UnmatchedBrace,
1512     sess: &ParseSess,
1513 ) -> Option<DiagnosticBuilder<'_, ErrorGuaranteed>> {
1514     // `None` here means an `Eof` was found. We already emit those errors elsewhere, we add them to
1515     // `unmatched_braces` only for error recovery in the `Parser`.
1516     let found_delim = unmatched.found_delim?;
1517     let mut spans = vec![unmatched.found_span];
1518     if let Some(sp) = unmatched.unclosed_span {
1519         spans.push(sp);
1520     };
1521     let err = MismatchedClosingDelimiter {
1522         spans,
1523         delimiter: pprust::token_kind_to_string(&token::CloseDelim(found_delim)).to_string(),
1524         unmatched: unmatched.found_span,
1525         opening_candidate: unmatched.candidate_span,
1526         unclosed: unmatched.unclosed_span,
1527     }
1528     .into_diagnostic(&sess.span_diagnostic);
1529     Some(err)
1530 }
1531
1532 pub fn emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedBrace>, sess: &ParseSess) {
1533     *sess.reached_eof.borrow_mut() |=
1534         unclosed_delims.iter().any(|unmatched_delim| unmatched_delim.found_delim.is_none());
1535     for unmatched in unclosed_delims.drain(..) {
1536         if let Some(mut e) = make_unclosed_delims_error(unmatched, sess) {
1537             e.emit();
1538         }
1539     }
1540 }
1541
1542 /// A helper struct used when building an `AttrTokenStream` from
1543 /// a `LazyAttrTokenStream`. Both delimiter and non-delimited tokens
1544 /// are stored as `FlatToken::Token`. A vector of `FlatToken`s
1545 /// is then 'parsed' to build up an `AttrTokenStream` with nested
1546 /// `AttrTokenTree::Delimited` tokens.
1547 #[derive(Debug, Clone)]
1548 pub enum FlatToken {
1549     /// A token - this holds both delimiter (e.g. '{' and '}')
1550     /// and non-delimiter tokens
1551     Token(Token),
1552     /// Holds the `AttributesData` for an AST node. The
1553     /// `AttributesData` is inserted directly into the
1554     /// constructed `AttrTokenStream` as
1555     /// an `AttrTokenTree::Attributes`.
1556     AttrTarget(AttributesData),
1557     /// A special 'empty' token that is ignored during the conversion
1558     /// to an `AttrTokenStream`. This is used to simplify the
1559     /// handling of replace ranges.
1560     Empty,
1561 }
1562
1563 #[derive(Debug)]
1564 pub enum NtOrTt {
1565     Nt(Nonterminal),
1566     Tt(TokenTree),
1567 }