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