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