]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_parse/src/parser/mod.rs
Rollup merge of #98684 - matthiaskrgr:ice-test-72793, r=oli-obk
[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",
895         );
896         first_note.push_span_label(
897             closure_spans.body,
898             "this expression is a statement because of the trailing semicolon",
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(closure_spans.whole_closure, "this is the parsed closure...");
904         second_note.push_span_label(
905             following_token_span,
906             "...but likely you meant the closure to end here",
907         );
908         expect_err.span_note(second_note, "the closure body may be incorrectly delimited");
909
910         expect_err.set_span(vec![preceding_pipe_span, following_token_span]);
911
912         let opening_suggestion_str = " {".to_string();
913         let closing_suggestion_str = "}".to_string();
914
915         expect_err.multipart_suggestion(
916             "try adding braces",
917             vec![
918                 (preceding_pipe_span.shrink_to_hi(), opening_suggestion_str),
919                 (following_token_span.shrink_to_lo(), closing_suggestion_str),
920             ],
921             Applicability::MaybeIncorrect,
922         );
923
924         expect_err.emit();
925
926         Ok(())
927     }
928
929     /// Parses a sequence, not including the closing delimiter. The function
930     /// `f` must consume tokens until reaching the next separator or
931     /// closing bracket.
932     fn parse_seq_to_before_end<T>(
933         &mut self,
934         ket: &TokenKind,
935         sep: SeqSep,
936         f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
937     ) -> PResult<'a, (Vec<T>, bool, bool)> {
938         self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
939     }
940
941     /// Parses a sequence, including the closing delimiter. The function
942     /// `f` must consume tokens until reaching the next separator or
943     /// closing bracket.
944     fn parse_seq_to_end<T>(
945         &mut self,
946         ket: &TokenKind,
947         sep: SeqSep,
948         f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
949     ) -> PResult<'a, (Vec<T>, bool /* trailing */)> {
950         let (val, trailing, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
951         if !recovered {
952             self.eat(ket);
953         }
954         Ok((val, trailing))
955     }
956
957     /// Parses a sequence, including the closing delimiter. The function
958     /// `f` must consume tokens until reaching the next separator or
959     /// closing bracket.
960     fn parse_unspanned_seq<T>(
961         &mut self,
962         bra: &TokenKind,
963         ket: &TokenKind,
964         sep: SeqSep,
965         f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
966     ) -> PResult<'a, (Vec<T>, bool)> {
967         self.expect(bra)?;
968         self.parse_seq_to_end(ket, sep, f)
969     }
970
971     fn parse_delim_comma_seq<T>(
972         &mut self,
973         delim: Delimiter,
974         f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
975     ) -> PResult<'a, (Vec<T>, bool)> {
976         self.parse_unspanned_seq(
977             &token::OpenDelim(delim),
978             &token::CloseDelim(delim),
979             SeqSep::trailing_allowed(token::Comma),
980             f,
981         )
982     }
983
984     fn parse_paren_comma_seq<T>(
985         &mut self,
986         f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
987     ) -> PResult<'a, (Vec<T>, bool)> {
988         self.parse_delim_comma_seq(Delimiter::Parenthesis, f)
989     }
990
991     /// Advance the parser by one token using provided token as the next one.
992     fn bump_with(&mut self, next: (Token, Spacing)) {
993         self.inlined_bump_with(next)
994     }
995
996     /// This always-inlined version should only be used on hot code paths.
997     #[inline(always)]
998     fn inlined_bump_with(&mut self, (next_token, next_spacing): (Token, Spacing)) {
999         // Update the current and previous tokens.
1000         self.prev_token = mem::replace(&mut self.token, next_token);
1001         self.token_spacing = next_spacing;
1002
1003         // Diagnostics.
1004         self.expected_tokens.clear();
1005     }
1006
1007     /// Advance the parser by one token.
1008     pub fn bump(&mut self) {
1009         // Note: destructuring here would give nicer code, but it was found in #96210 to be slower
1010         // than `.0`/`.1` access.
1011         let mut next = self.token_cursor.inlined_next(self.desugar_doc_comments);
1012         self.token_cursor.num_next_calls += 1;
1013         // We've retrieved an token from the underlying
1014         // cursor, so we no longer need to worry about
1015         // an unglued token. See `break_and_eat` for more details
1016         self.token_cursor.break_last_token = false;
1017         if next.0.span.is_dummy() {
1018             // Tweak the location for better diagnostics, but keep syntactic context intact.
1019             let fallback_span = self.token.span;
1020             next.0.span = fallback_span.with_ctxt(next.0.span.ctxt());
1021         }
1022         debug_assert!(!matches!(
1023             next.0.kind,
1024             token::OpenDelim(Delimiter::Invisible) | token::CloseDelim(Delimiter::Invisible)
1025         ));
1026         self.inlined_bump_with(next)
1027     }
1028
1029     /// Look-ahead `dist` tokens of `self.token` and get access to that token there.
1030     /// When `dist == 0` then the current token is looked at.
1031     pub fn look_ahead<R>(&self, dist: usize, looker: impl FnOnce(&Token) -> R) -> R {
1032         if dist == 0 {
1033             return looker(&self.token);
1034         }
1035
1036         let frame = &self.token_cursor.frame;
1037         if let Some((delim, span)) = frame.delim_sp && delim != Delimiter::Invisible {
1038             let all_normal = (0..dist).all(|i| {
1039                 let token = frame.tree_cursor.look_ahead(i);
1040                 !matches!(token, Some(TokenTree::Delimited(_, Delimiter::Invisible, _)))
1041             });
1042             if all_normal {
1043                 return match frame.tree_cursor.look_ahead(dist - 1) {
1044                     Some(tree) => match tree {
1045                         TokenTree::Token(token) => looker(token),
1046                         TokenTree::Delimited(dspan, delim, _) => {
1047                             looker(&Token::new(token::OpenDelim(*delim), dspan.open))
1048                         }
1049                     },
1050                     None => looker(&Token::new(token::CloseDelim(delim), span.close)),
1051                 };
1052             }
1053         }
1054
1055         let mut cursor = self.token_cursor.clone();
1056         let mut i = 0;
1057         let mut token = Token::dummy();
1058         while i < dist {
1059             token = cursor.next(/* desugar_doc_comments */ false).0;
1060             if matches!(
1061                 token.kind,
1062                 token::OpenDelim(Delimiter::Invisible) | token::CloseDelim(Delimiter::Invisible)
1063             ) {
1064                 continue;
1065             }
1066             i += 1;
1067         }
1068         return looker(&token);
1069     }
1070
1071     /// Returns whether any of the given keywords are `dist` tokens ahead of the current one.
1072     fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool {
1073         self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw)))
1074     }
1075
1076     /// Parses asyncness: `async` or nothing.
1077     fn parse_asyncness(&mut self) -> Async {
1078         if self.eat_keyword(kw::Async) {
1079             let span = self.prev_token.uninterpolated_span();
1080             Async::Yes { span, closure_id: DUMMY_NODE_ID, return_impl_trait_id: DUMMY_NODE_ID }
1081         } else {
1082             Async::No
1083         }
1084     }
1085
1086     /// Parses unsafety: `unsafe` or nothing.
1087     fn parse_unsafety(&mut self) -> Unsafe {
1088         if self.eat_keyword(kw::Unsafe) {
1089             Unsafe::Yes(self.prev_token.uninterpolated_span())
1090         } else {
1091             Unsafe::No
1092         }
1093     }
1094
1095     /// Parses constness: `const` or nothing.
1096     fn parse_constness(&mut self) -> Const {
1097         // Avoid const blocks to be parsed as const items
1098         if self.look_ahead(1, |t| t != &token::OpenDelim(Delimiter::Brace))
1099             && self.eat_keyword(kw::Const)
1100         {
1101             Const::Yes(self.prev_token.uninterpolated_span())
1102         } else {
1103             Const::No
1104         }
1105     }
1106
1107     /// Parses inline const expressions.
1108     fn parse_const_block(&mut self, span: Span, pat: bool) -> PResult<'a, P<Expr>> {
1109         if pat {
1110             self.sess.gated_spans.gate(sym::inline_const_pat, span);
1111         } else {
1112             self.sess.gated_spans.gate(sym::inline_const, span);
1113         }
1114         self.eat_keyword(kw::Const);
1115         let (attrs, blk) = self.parse_inner_attrs_and_block()?;
1116         let anon_const = AnonConst {
1117             id: DUMMY_NODE_ID,
1118             value: self.mk_expr(blk.span, ExprKind::Block(blk, None), AttrVec::new()),
1119         };
1120         let blk_span = anon_const.value.span;
1121         Ok(self.mk_expr(span.to(blk_span), ExprKind::ConstBlock(anon_const), AttrVec::from(attrs)))
1122     }
1123
1124     /// Parses mutability (`mut` or nothing).
1125     fn parse_mutability(&mut self) -> Mutability {
1126         if self.eat_keyword(kw::Mut) { Mutability::Mut } else { Mutability::Not }
1127     }
1128
1129     /// Possibly parses mutability (`const` or `mut`).
1130     fn parse_const_or_mut(&mut self) -> Option<Mutability> {
1131         if self.eat_keyword(kw::Mut) {
1132             Some(Mutability::Mut)
1133         } else if self.eat_keyword(kw::Const) {
1134             Some(Mutability::Not)
1135         } else {
1136             None
1137         }
1138     }
1139
1140     fn parse_field_name(&mut self) -> PResult<'a, Ident> {
1141         if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) = self.token.kind
1142         {
1143             self.expect_no_suffix(self.token.span, "a tuple index", suffix);
1144             self.bump();
1145             Ok(Ident::new(symbol, self.prev_token.span))
1146         } else {
1147             self.parse_ident_common(true)
1148         }
1149     }
1150
1151     fn parse_mac_args(&mut self) -> PResult<'a, P<MacArgs>> {
1152         self.parse_mac_args_common(true).map(P)
1153     }
1154
1155     fn parse_attr_args(&mut self) -> PResult<'a, MacArgs> {
1156         self.parse_mac_args_common(false)
1157     }
1158
1159     fn parse_mac_args_common(&mut self, delimited_only: bool) -> PResult<'a, MacArgs> {
1160         Ok(
1161             if self.check(&token::OpenDelim(Delimiter::Parenthesis))
1162                 || self.check(&token::OpenDelim(Delimiter::Bracket))
1163                 || self.check(&token::OpenDelim(Delimiter::Brace))
1164             {
1165                 match self.parse_token_tree() {
1166                     TokenTree::Delimited(dspan, delim, tokens) =>
1167                     // We've confirmed above that there is a delimiter so unwrapping is OK.
1168                     {
1169                         MacArgs::Delimited(dspan, MacDelimiter::from_token(delim).unwrap(), tokens)
1170                     }
1171                     _ => unreachable!(),
1172                 }
1173             } else if !delimited_only {
1174                 if self.eat(&token::Eq) {
1175                     let eq_span = self.prev_token.span;
1176                     MacArgs::Eq(eq_span, MacArgsEq::Ast(self.parse_expr_force_collect()?))
1177                 } else {
1178                     MacArgs::Empty
1179                 }
1180             } else {
1181                 return self.unexpected();
1182             },
1183         )
1184     }
1185
1186     fn parse_or_use_outer_attributes(
1187         &mut self,
1188         already_parsed_attrs: Option<AttrWrapper>,
1189     ) -> PResult<'a, AttrWrapper> {
1190         if let Some(attrs) = already_parsed_attrs {
1191             Ok(attrs)
1192         } else {
1193             self.parse_outer_attributes()
1194         }
1195     }
1196
1197     /// Parses a single token tree from the input.
1198     pub(crate) fn parse_token_tree(&mut self) -> TokenTree {
1199         match self.token.kind {
1200             token::OpenDelim(..) => {
1201                 // Grab the tokens from this frame.
1202                 let frame = &self.token_cursor.frame;
1203                 let stream = frame.tree_cursor.stream.clone();
1204                 let (delim, span) = frame.delim_sp.unwrap();
1205
1206                 // Advance the token cursor through the entire delimited
1207                 // sequence. After getting the `OpenDelim` we are *within* the
1208                 // delimited sequence, i.e. at depth `d`. After getting the
1209                 // matching `CloseDelim` we are *after* the delimited sequence,
1210                 // i.e. at depth `d - 1`.
1211                 let target_depth = self.token_cursor.stack.len() - 1;
1212                 loop {
1213                     // Advance one token at a time, so `TokenCursor::next()`
1214                     // can capture these tokens if necessary.
1215                     self.bump();
1216                     if self.token_cursor.stack.len() == target_depth {
1217                         debug_assert!(matches!(self.token.kind, token::CloseDelim(_)));
1218                         break;
1219                     }
1220                 }
1221
1222                 // Consume close delimiter
1223                 self.bump();
1224                 TokenTree::Delimited(span, delim, stream)
1225             }
1226             token::CloseDelim(_) | token::Eof => unreachable!(),
1227             _ => {
1228                 self.bump();
1229                 TokenTree::Token(self.prev_token.clone())
1230             }
1231         }
1232     }
1233
1234     /// Parses a stream of tokens into a list of `TokenTree`s, up to EOF.
1235     pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
1236         let mut tts = Vec::new();
1237         while self.token != token::Eof {
1238             tts.push(self.parse_token_tree());
1239         }
1240         Ok(tts)
1241     }
1242
1243     pub fn parse_tokens(&mut self) -> TokenStream {
1244         let mut result = Vec::new();
1245         loop {
1246             match self.token.kind {
1247                 token::Eof | token::CloseDelim(..) => break,
1248                 _ => result.push(self.parse_token_tree().into()),
1249             }
1250         }
1251         TokenStream::new(result)
1252     }
1253
1254     /// Evaluates the closure with restrictions in place.
1255     ///
1256     /// Afters the closure is evaluated, restrictions are reset.
1257     fn with_res<T>(&mut self, res: Restrictions, f: impl FnOnce(&mut Self) -> T) -> T {
1258         let old = self.restrictions;
1259         self.restrictions = res;
1260         let res = f(self);
1261         self.restrictions = old;
1262         res
1263     }
1264
1265     /// Parses `pub` and `pub(in path)` plus shortcuts `pub(crate)` for `pub(in crate)`, `pub(self)`
1266     /// for `pub(in self)` and `pub(super)` for `pub(in super)`.
1267     /// If the following element can't be a tuple (i.e., it's a function definition), then
1268     /// it's not a tuple struct field), and the contents within the parentheses aren't valid,
1269     /// so emit a proper diagnostic.
1270     // Public for rustfmt usage.
1271     pub fn parse_visibility(&mut self, fbt: FollowedByType) -> PResult<'a, Visibility> {
1272         maybe_whole!(self, NtVis, |x| x.into_inner());
1273
1274         if !self.eat_keyword(kw::Pub) {
1275             // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
1276             // keyword to grab a span from for inherited visibility; an empty span at the
1277             // beginning of the current token would seem to be the "Schelling span".
1278             return Ok(Visibility {
1279                 span: self.token.span.shrink_to_lo(),
1280                 kind: VisibilityKind::Inherited,
1281                 tokens: None,
1282             });
1283         }
1284         let lo = self.prev_token.span;
1285
1286         if self.check(&token::OpenDelim(Delimiter::Parenthesis)) {
1287             // We don't `self.bump()` the `(` yet because this might be a struct definition where
1288             // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
1289             // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
1290             // by the following tokens.
1291             if self.is_keyword_ahead(1, &[kw::In]) {
1292                 // Parse `pub(in path)`.
1293                 self.bump(); // `(`
1294                 self.bump(); // `in`
1295                 let path = self.parse_path(PathStyle::Mod)?; // `path`
1296                 self.expect(&token::CloseDelim(Delimiter::Parenthesis))?; // `)`
1297                 let vis = VisibilityKind::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
1298                 return Ok(Visibility {
1299                     span: lo.to(self.prev_token.span),
1300                     kind: vis,
1301                     tokens: None,
1302                 });
1303             } else if self.look_ahead(2, |t| t == &token::CloseDelim(Delimiter::Parenthesis))
1304                 && self.is_keyword_ahead(1, &[kw::Crate, kw::Super, kw::SelfLower])
1305             {
1306                 // Parse `pub(crate)`, `pub(self)`, or `pub(super)`.
1307                 self.bump(); // `(`
1308                 let path = self.parse_path(PathStyle::Mod)?; // `crate`/`super`/`self`
1309                 self.expect(&token::CloseDelim(Delimiter::Parenthesis))?; // `)`
1310                 let vis = VisibilityKind::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
1311                 return Ok(Visibility {
1312                     span: lo.to(self.prev_token.span),
1313                     kind: vis,
1314                     tokens: None,
1315                 });
1316             } else if let FollowedByType::No = fbt {
1317                 // Provide this diagnostic if a type cannot follow;
1318                 // in particular, if this is not a tuple struct.
1319                 self.recover_incorrect_vis_restriction()?;
1320                 // Emit diagnostic, but continue with public visibility.
1321             }
1322         }
1323
1324         Ok(Visibility { span: lo, kind: VisibilityKind::Public, tokens: None })
1325     }
1326
1327     /// Recovery for e.g. `pub(something) fn ...` or `struct X { pub(something) y: Z }`
1328     fn recover_incorrect_vis_restriction(&mut self) -> PResult<'a, ()> {
1329         self.bump(); // `(`
1330         let path = self.parse_path(PathStyle::Mod)?;
1331         self.expect(&token::CloseDelim(Delimiter::Parenthesis))?; // `)`
1332
1333         let msg = "incorrect visibility restriction";
1334         let suggestion = r##"some possible visibility restrictions are:
1335 `pub(crate)`: visible only on the current crate
1336 `pub(super)`: visible only in the current module's parent
1337 `pub(in path::to::module)`: visible only on the specified path"##;
1338
1339         let path_str = pprust::path_to_string(&path);
1340
1341         struct_span_err!(self.sess.span_diagnostic, path.span, E0704, "{}", msg)
1342             .help(suggestion)
1343             .span_suggestion(
1344                 path.span,
1345                 &format!("make this visible only to module `{}` with `in`", path_str),
1346                 format!("in {}", path_str),
1347                 Applicability::MachineApplicable,
1348             )
1349             .emit();
1350
1351         Ok(())
1352     }
1353
1354     /// Parses `extern string_literal?`.
1355     fn parse_extern(&mut self) -> Extern {
1356         if self.eat_keyword(kw::Extern) { Extern::from_abi(self.parse_abi()) } else { Extern::None }
1357     }
1358
1359     /// Parses a string literal as an ABI spec.
1360     fn parse_abi(&mut self) -> Option<StrLit> {
1361         match self.parse_str_lit() {
1362             Ok(str_lit) => Some(str_lit),
1363             Err(Some(lit)) => match lit.kind {
1364                 ast::LitKind::Err(_) => None,
1365                 _ => {
1366                     self.struct_span_err(lit.span, "non-string ABI literal")
1367                         .span_suggestion(
1368                             lit.span,
1369                             "specify the ABI with a string literal",
1370                             "\"C\"",
1371                             Applicability::MaybeIncorrect,
1372                         )
1373                         .emit();
1374                     None
1375                 }
1376             },
1377             Err(None) => None,
1378         }
1379     }
1380
1381     pub fn collect_tokens_no_attrs<R: HasAttrs + HasTokens>(
1382         &mut self,
1383         f: impl FnOnce(&mut Self) -> PResult<'a, R>,
1384     ) -> PResult<'a, R> {
1385         // The only reason to call `collect_tokens_no_attrs` is if you want tokens, so use
1386         // `ForceCollect::Yes`
1387         self.collect_tokens_trailing_token(
1388             AttrWrapper::empty(),
1389             ForceCollect::Yes,
1390             |this, _attrs| Ok((f(this)?, TrailingToken::None)),
1391         )
1392     }
1393
1394     /// `::{` or `::*`
1395     fn is_import_coupler(&mut self) -> bool {
1396         self.check(&token::ModSep)
1397             && self.look_ahead(1, |t| {
1398                 *t == token::OpenDelim(Delimiter::Brace) || *t == token::BinOp(token::Star)
1399             })
1400     }
1401
1402     pub fn clear_expected_tokens(&mut self) {
1403         self.expected_tokens.clear();
1404     }
1405 }
1406
1407 pub(crate) fn make_unclosed_delims_error(
1408     unmatched: UnmatchedBrace,
1409     sess: &ParseSess,
1410 ) -> Option<DiagnosticBuilder<'_, ErrorGuaranteed>> {
1411     // `None` here means an `Eof` was found. We already emit those errors elsewhere, we add them to
1412     // `unmatched_braces` only for error recovery in the `Parser`.
1413     let found_delim = unmatched.found_delim?;
1414     let span: MultiSpan = if let Some(sp) = unmatched.unclosed_span {
1415         vec![unmatched.found_span, sp].into()
1416     } else {
1417         unmatched.found_span.into()
1418     };
1419     let mut err = sess.span_diagnostic.struct_span_err(
1420         span,
1421         &format!(
1422             "mismatched closing delimiter: `{}`",
1423             pprust::token_kind_to_string(&token::CloseDelim(found_delim)),
1424         ),
1425     );
1426     err.span_label(unmatched.found_span, "mismatched closing delimiter");
1427     if let Some(sp) = unmatched.candidate_span {
1428         err.span_label(sp, "closing delimiter possibly meant for this");
1429     }
1430     if let Some(sp) = unmatched.unclosed_span {
1431         err.span_label(sp, "unclosed delimiter");
1432     }
1433     Some(err)
1434 }
1435
1436 pub fn emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedBrace>, sess: &ParseSess) {
1437     *sess.reached_eof.borrow_mut() |=
1438         unclosed_delims.iter().any(|unmatched_delim| unmatched_delim.found_delim.is_none());
1439     for unmatched in unclosed_delims.drain(..) {
1440         if let Some(mut e) = make_unclosed_delims_error(unmatched, sess) {
1441             e.emit();
1442         }
1443     }
1444 }
1445
1446 /// A helper struct used when building an `AttrAnnotatedTokenStream` from
1447 /// a `LazyTokenStream`. Both delimiter and non-delimited tokens
1448 /// are stored as `FlatToken::Token`. A vector of `FlatToken`s
1449 /// is then 'parsed' to build up an `AttrAnnotatedTokenStream` with nested
1450 /// `AttrAnnotatedTokenTree::Delimited` tokens
1451 #[derive(Debug, Clone)]
1452 pub enum FlatToken {
1453     /// A token - this holds both delimiter (e.g. '{' and '}')
1454     /// and non-delimiter tokens
1455     Token(Token),
1456     /// Holds the `AttributesData` for an AST node. The
1457     /// `AttributesData` is inserted directly into the
1458     /// constructed `AttrAnnotatedTokenStream` as
1459     /// an `AttrAnnotatedTokenTree::Attributes`
1460     AttrTarget(AttributesData),
1461     /// A special 'empty' token that is ignored during the conversion
1462     /// to an `AttrAnnotatedTokenStream`. This is used to simplify the
1463     /// handling of replace ranges.
1464     Empty,
1465 }
1466
1467 #[derive(Debug)]
1468 pub enum NtOrTt {
1469     Nt(Nonterminal),
1470     Tt(TokenTree),
1471 }