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