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