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