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