]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_parse/src/parser/mod.rs
Rollup merge of #96507 - TaKO8Ki:suggest-calling-associated-function, r=lcnr
[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, AstLike, AttrStyle, AttrVec, Const, CrateSugar, Extern};
29 use rustc_ast::{Async, Expr, ExprKind, MacArgs, MacArgsEq, MacDelimiter, Mutability, StrLit};
30 use rustc_ast::{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     /// Consumes a token 'tok' if it exists. Returns whether the given token was present.
551     pub fn eat(&mut self, tok: &TokenKind) -> bool {
552         let is_present = self.check(tok);
553         if is_present {
554             self.bump()
555         }
556         is_present
557     }
558
559     /// If the next token is the given keyword, returns `true` without eating it.
560     /// An expectation is also added for diagnostics purposes.
561     fn check_keyword(&mut self, kw: Symbol) -> bool {
562         self.expected_tokens.push(TokenType::Keyword(kw));
563         self.token.is_keyword(kw)
564     }
565
566     /// If the next token is the given keyword, eats it and returns `true`.
567     /// Otherwise, returns `false`. An expectation is also added for diagnostics purposes.
568     // Public for rustfmt usage.
569     pub fn eat_keyword(&mut self, kw: Symbol) -> bool {
570         if self.check_keyword(kw) {
571             self.bump();
572             true
573         } else {
574             false
575         }
576     }
577
578     fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool {
579         if self.token.is_keyword(kw) {
580             self.bump();
581             true
582         } else {
583             false
584         }
585     }
586
587     /// If the given word is not a keyword, signals an error.
588     /// If the next token is not the given word, signals an error.
589     /// Otherwise, eats it.
590     fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> {
591         if !self.eat_keyword(kw) { self.unexpected() } else { Ok(()) }
592     }
593
594     /// Is the given keyword `kw` followed by a non-reserved identifier?
595     fn is_kw_followed_by_ident(&self, kw: Symbol) -> bool {
596         self.token.is_keyword(kw) && self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
597     }
598
599     fn check_or_expected(&mut self, ok: bool, typ: TokenType) -> bool {
600         if ok {
601             true
602         } else {
603             self.expected_tokens.push(typ);
604             false
605         }
606     }
607
608     fn check_ident(&mut self) -> bool {
609         self.check_or_expected(self.token.is_ident(), TokenType::Ident)
610     }
611
612     fn check_path(&mut self) -> bool {
613         self.check_or_expected(self.token.is_path_start(), TokenType::Path)
614     }
615
616     fn check_type(&mut self) -> bool {
617         self.check_or_expected(self.token.can_begin_type(), TokenType::Type)
618     }
619
620     fn check_const_arg(&mut self) -> bool {
621         self.check_or_expected(self.token.can_begin_const_arg(), TokenType::Const)
622     }
623
624     fn check_inline_const(&self, dist: usize) -> bool {
625         self.is_keyword_ahead(dist, &[kw::Const])
626             && self.look_ahead(dist + 1, |t| match t.kind {
627                 token::Interpolated(ref nt) => matches!(**nt, token::NtBlock(..)),
628                 token::OpenDelim(Delimiter::Brace) => true,
629                 _ => false,
630             })
631     }
632
633     /// Checks to see if the next token is either `+` or `+=`.
634     /// Otherwise returns `false`.
635     fn check_plus(&mut self) -> bool {
636         self.check_or_expected(
637             self.token.is_like_plus(),
638             TokenType::Token(token::BinOp(token::Plus)),
639         )
640     }
641
642     /// Eats the expected token if it's present possibly breaking
643     /// compound tokens like multi-character operators in process.
644     /// Returns `true` if the token was eaten.
645     fn break_and_eat(&mut self, expected: TokenKind) -> bool {
646         if self.token.kind == expected {
647             self.bump();
648             return true;
649         }
650         match self.token.kind.break_two_token_op() {
651             Some((first, second)) if first == expected => {
652                 let first_span = self.sess.source_map().start_point(self.token.span);
653                 let second_span = self.token.span.with_lo(first_span.hi());
654                 self.token = Token::new(first, first_span);
655                 // Keep track of this token - if we end token capturing now,
656                 // we'll want to append this token to the captured stream.
657                 //
658                 // If we consume any additional tokens, then this token
659                 // is not needed (we'll capture the entire 'glued' token),
660                 // and `bump` will set this field to `None`
661                 self.token_cursor.break_last_token = true;
662                 // Use the spacing of the glued token as the spacing
663                 // of the unglued second token.
664                 self.bump_with((Token::new(second, second_span), self.token_spacing));
665                 true
666             }
667             _ => {
668                 self.expected_tokens.push(TokenType::Token(expected));
669                 false
670             }
671         }
672     }
673
674     /// Eats `+` possibly breaking tokens like `+=` in process.
675     fn eat_plus(&mut self) -> bool {
676         self.break_and_eat(token::BinOp(token::Plus))
677     }
678
679     /// Eats `&` possibly breaking tokens like `&&` in process.
680     /// Signals an error if `&` is not eaten.
681     fn expect_and(&mut self) -> PResult<'a, ()> {
682         if self.break_and_eat(token::BinOp(token::And)) { Ok(()) } else { self.unexpected() }
683     }
684
685     /// Eats `|` possibly breaking tokens like `||` in process.
686     /// Signals an error if `|` was not eaten.
687     fn expect_or(&mut self) -> PResult<'a, ()> {
688         if self.break_and_eat(token::BinOp(token::Or)) { Ok(()) } else { self.unexpected() }
689     }
690
691     /// Eats `<` possibly breaking tokens like `<<` in process.
692     fn eat_lt(&mut self) -> bool {
693         let ate = self.break_and_eat(token::Lt);
694         if ate {
695             // See doc comment for `unmatched_angle_bracket_count`.
696             self.unmatched_angle_bracket_count += 1;
697             self.max_angle_bracket_count += 1;
698             debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count);
699         }
700         ate
701     }
702
703     /// Eats `<` possibly breaking tokens like `<<` in process.
704     /// Signals an error if `<` was not eaten.
705     fn expect_lt(&mut self) -> PResult<'a, ()> {
706         if self.eat_lt() { Ok(()) } else { self.unexpected() }
707     }
708
709     /// Eats `>` possibly breaking tokens like `>>` in process.
710     /// Signals an error if `>` was not eaten.
711     fn expect_gt(&mut self) -> PResult<'a, ()> {
712         if self.break_and_eat(token::Gt) {
713             // See doc comment for `unmatched_angle_bracket_count`.
714             if self.unmatched_angle_bracket_count > 0 {
715                 self.unmatched_angle_bracket_count -= 1;
716                 debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count);
717             }
718             Ok(())
719         } else {
720             self.unexpected()
721         }
722     }
723
724     fn expect_any_with_type(&mut self, kets: &[&TokenKind], expect: TokenExpectType) -> bool {
725         kets.iter().any(|k| match expect {
726             TokenExpectType::Expect => self.check(k),
727             TokenExpectType::NoExpect => self.token == **k,
728         })
729     }
730
731     fn parse_seq_to_before_tokens<T>(
732         &mut self,
733         kets: &[&TokenKind],
734         sep: SeqSep,
735         expect: TokenExpectType,
736         mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
737     ) -> PResult<'a, (Vec<T>, bool /* trailing */, bool /* recovered */)> {
738         let mut first = true;
739         let mut recovered = false;
740         let mut trailing = false;
741         let mut v = vec![];
742         let unclosed_delims = !self.unclosed_delims.is_empty();
743
744         while !self.expect_any_with_type(kets, expect) {
745             if let token::CloseDelim(..) | token::Eof = self.token.kind {
746                 break;
747             }
748             if let Some(ref t) = sep.sep {
749                 if first {
750                     first = false;
751                 } else {
752                     match self.expect(t) {
753                         Ok(false) => {
754                             self.current_closure.take();
755                         }
756                         Ok(true) => {
757                             self.current_closure.take();
758                             recovered = true;
759                             break;
760                         }
761                         Err(mut expect_err) => {
762                             let sp = self.prev_token.span.shrink_to_hi();
763                             let token_str = pprust::token_kind_to_string(t);
764
765                             match self.current_closure.take() {
766                                 Some(closure_spans) if self.token.kind == TokenKind::Semi => {
767                                     // Finding a semicolon instead of a comma
768                                     // after a closure body indicates that the
769                                     // closure body may be a block but the user
770                                     // forgot to put braces around its
771                                     // statements.
772
773                                     self.recover_missing_braces_around_closure_body(
774                                         closure_spans,
775                                         expect_err,
776                                     )?;
777
778                                     continue;
779                                 }
780
781                                 _ => {
782                                     // Attempt to keep parsing if it was a similar separator.
783                                     if let Some(ref tokens) = t.similar_tokens() {
784                                         if tokens.contains(&self.token.kind) && !unclosed_delims {
785                                             self.bump();
786                                         }
787                                     }
788                                 }
789                             }
790
791                             // If this was a missing `@` in a binding pattern
792                             // bail with a suggestion
793                             // https://github.com/rust-lang/rust/issues/72373
794                             if self.prev_token.is_ident() && self.token.kind == token::DotDot {
795                                 let msg = format!(
796                                     "if you meant to bind the contents of \
797                                     the rest of the array pattern into `{}`, use `@`",
798                                     pprust::token_to_string(&self.prev_token)
799                                 );
800                                 expect_err
801                                     .span_suggestion_verbose(
802                                         self.prev_token.span.shrink_to_hi().until(self.token.span),
803                                         &msg,
804                                         " @ ",
805                                         Applicability::MaybeIncorrect,
806                                     )
807                                     .emit();
808                                 break;
809                             }
810
811                             // Attempt to keep parsing if it was an omitted separator.
812                             match f(self) {
813                                 Ok(t) => {
814                                     // Parsed successfully, therefore most probably the code only
815                                     // misses a separator.
816                                     expect_err
817                                         .span_suggestion_short(
818                                             sp,
819                                             &format!("missing `{}`", token_str),
820                                             token_str,
821                                             Applicability::MaybeIncorrect,
822                                         )
823                                         .emit();
824
825                                     v.push(t);
826                                     continue;
827                                 }
828                                 Err(e) => {
829                                     // Parsing failed, therefore it must be something more serious
830                                     // than just a missing separator.
831                                     expect_err.emit();
832
833                                     e.cancel();
834                                     break;
835                                 }
836                             }
837                         }
838                     }
839                 }
840             }
841             if sep.trailing_sep_allowed && self.expect_any_with_type(kets, expect) {
842                 trailing = true;
843                 break;
844             }
845
846             let t = f(self)?;
847             v.push(t);
848         }
849
850         Ok((v, trailing, recovered))
851     }
852
853     fn recover_missing_braces_around_closure_body(
854         &mut self,
855         closure_spans: ClosureSpans,
856         mut expect_err: DiagnosticBuilder<'_, ErrorGuaranteed>,
857     ) -> PResult<'a, ()> {
858         let initial_semicolon = self.token.span;
859
860         while self.eat(&TokenKind::Semi) {
861             let _ = self.parse_stmt(ForceCollect::Yes)?;
862         }
863
864         expect_err.set_primary_message(
865             "closure bodies that contain statements must be surrounded by braces",
866         );
867
868         let preceding_pipe_span = closure_spans.closing_pipe;
869         let following_token_span = self.token.span;
870
871         let mut first_note = MultiSpan::from(vec![initial_semicolon]);
872         first_note.push_span_label(
873             initial_semicolon,
874             "this `;` turns the preceding closure into a statement".to_string(),
875         );
876         first_note.push_span_label(
877             closure_spans.body,
878             "this expression is a statement because of the trailing semicolon".to_string(),
879         );
880         expect_err.span_note(first_note, "statement found outside of a block");
881
882         let mut second_note = MultiSpan::from(vec![closure_spans.whole_closure]);
883         second_note.push_span_label(
884             closure_spans.whole_closure,
885             "this is the parsed closure...".to_string(),
886         );
887         second_note.push_span_label(
888             following_token_span,
889             "...but likely you meant the closure to end here".to_string(),
890         );
891         expect_err.span_note(second_note, "the closure body may be incorrectly delimited");
892
893         expect_err.set_span(vec![preceding_pipe_span, following_token_span]);
894
895         let opening_suggestion_str = " {".to_string();
896         let closing_suggestion_str = "}".to_string();
897
898         expect_err.multipart_suggestion(
899             "try adding braces",
900             vec![
901                 (preceding_pipe_span.shrink_to_hi(), opening_suggestion_str),
902                 (following_token_span.shrink_to_lo(), closing_suggestion_str),
903             ],
904             Applicability::MaybeIncorrect,
905         );
906
907         expect_err.emit();
908
909         Ok(())
910     }
911
912     /// Parses a sequence, not including the closing delimiter. The function
913     /// `f` must consume tokens until reaching the next separator or
914     /// closing bracket.
915     fn parse_seq_to_before_end<T>(
916         &mut self,
917         ket: &TokenKind,
918         sep: SeqSep,
919         f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
920     ) -> PResult<'a, (Vec<T>, bool, bool)> {
921         self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
922     }
923
924     /// Parses a sequence, including the closing delimiter. The function
925     /// `f` must consume tokens until reaching the next separator or
926     /// closing bracket.
927     fn parse_seq_to_end<T>(
928         &mut self,
929         ket: &TokenKind,
930         sep: SeqSep,
931         f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
932     ) -> PResult<'a, (Vec<T>, bool /* trailing */)> {
933         let (val, trailing, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
934         if !recovered {
935             self.eat(ket);
936         }
937         Ok((val, trailing))
938     }
939
940     /// Parses a sequence, including the closing delimiter. The function
941     /// `f` must consume tokens until reaching the next separator or
942     /// closing bracket.
943     fn parse_unspanned_seq<T>(
944         &mut self,
945         bra: &TokenKind,
946         ket: &TokenKind,
947         sep: SeqSep,
948         f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
949     ) -> PResult<'a, (Vec<T>, bool)> {
950         self.expect(bra)?;
951         self.parse_seq_to_end(ket, sep, f)
952     }
953
954     fn parse_delim_comma_seq<T>(
955         &mut self,
956         delim: Delimiter,
957         f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
958     ) -> PResult<'a, (Vec<T>, bool)> {
959         self.parse_unspanned_seq(
960             &token::OpenDelim(delim),
961             &token::CloseDelim(delim),
962             SeqSep::trailing_allowed(token::Comma),
963             f,
964         )
965     }
966
967     fn parse_paren_comma_seq<T>(
968         &mut self,
969         f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
970     ) -> PResult<'a, (Vec<T>, bool)> {
971         self.parse_delim_comma_seq(Delimiter::Parenthesis, f)
972     }
973
974     /// Advance the parser by one token using provided token as the next one.
975     fn bump_with(&mut self, next: (Token, Spacing)) {
976         self.inlined_bump_with(next)
977     }
978
979     /// This always-inlined version should only be used on hot code paths.
980     #[inline(always)]
981     fn inlined_bump_with(&mut self, (next_token, next_spacing): (Token, Spacing)) {
982         // Update the current and previous tokens.
983         self.prev_token = mem::replace(&mut self.token, next_token);
984         self.token_spacing = next_spacing;
985
986         // Diagnostics.
987         self.expected_tokens.clear();
988     }
989
990     /// Advance the parser by one token.
991     pub fn bump(&mut self) {
992         // Note: destructuring here would give nicer code, but it was found in #96210 to be slower
993         // than `.0`/`.1` access.
994         let mut next = self.token_cursor.inlined_next(self.desugar_doc_comments);
995         self.token_cursor.num_next_calls += 1;
996         // We've retrieved an token from the underlying
997         // cursor, so we no longer need to worry about
998         // an unglued token. See `break_and_eat` for more details
999         self.token_cursor.break_last_token = false;
1000         if next.0.span.is_dummy() {
1001             // Tweak the location for better diagnostics, but keep syntactic context intact.
1002             let fallback_span = self.token.span;
1003             next.0.span = fallback_span.with_ctxt(next.0.span.ctxt());
1004         }
1005         debug_assert!(!matches!(
1006             next.0.kind,
1007             token::OpenDelim(Delimiter::Invisible) | token::CloseDelim(Delimiter::Invisible)
1008         ));
1009         self.inlined_bump_with(next)
1010     }
1011
1012     /// Look-ahead `dist` tokens of `self.token` and get access to that token there.
1013     /// When `dist == 0` then the current token is looked at.
1014     pub fn look_ahead<R>(&self, dist: usize, looker: impl FnOnce(&Token) -> R) -> R {
1015         if dist == 0 {
1016             return looker(&self.token);
1017         }
1018
1019         let frame = &self.token_cursor.frame;
1020         if let Some((delim, span)) = frame.delim_sp && delim != Delimiter::Invisible {
1021             let all_normal = (0..dist).all(|i| {
1022                 let token = frame.tree_cursor.look_ahead(i);
1023                 !matches!(token, Some(TokenTree::Delimited(_, Delimiter::Invisible, _)))
1024             });
1025             if all_normal {
1026                 return match frame.tree_cursor.look_ahead(dist - 1) {
1027                     Some(tree) => match tree {
1028                         TokenTree::Token(token) => looker(token),
1029                         TokenTree::Delimited(dspan, delim, _) => {
1030                             looker(&Token::new(token::OpenDelim(*delim), dspan.open))
1031                         }
1032                     },
1033                     None => looker(&Token::new(token::CloseDelim(delim), span.close)),
1034                 };
1035             }
1036         }
1037
1038         let mut cursor = self.token_cursor.clone();
1039         let mut i = 0;
1040         let mut token = Token::dummy();
1041         while i < dist {
1042             token = cursor.next(/* desugar_doc_comments */ false).0;
1043             if matches!(
1044                 token.kind,
1045                 token::OpenDelim(Delimiter::Invisible) | token::CloseDelim(Delimiter::Invisible)
1046             ) {
1047                 continue;
1048             }
1049             i += 1;
1050         }
1051         return looker(&token);
1052     }
1053
1054     /// Returns whether any of the given keywords are `dist` tokens ahead of the current one.
1055     fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool {
1056         self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw)))
1057     }
1058
1059     /// Parses asyncness: `async` or nothing.
1060     fn parse_asyncness(&mut self) -> Async {
1061         if self.eat_keyword(kw::Async) {
1062             let span = self.prev_token.uninterpolated_span();
1063             Async::Yes { span, closure_id: DUMMY_NODE_ID, return_impl_trait_id: DUMMY_NODE_ID }
1064         } else {
1065             Async::No
1066         }
1067     }
1068
1069     /// Parses unsafety: `unsafe` or nothing.
1070     fn parse_unsafety(&mut self) -> Unsafe {
1071         if self.eat_keyword(kw::Unsafe) {
1072             Unsafe::Yes(self.prev_token.uninterpolated_span())
1073         } else {
1074             Unsafe::No
1075         }
1076     }
1077
1078     /// Parses constness: `const` or nothing.
1079     fn parse_constness(&mut self) -> Const {
1080         // Avoid const blocks to be parsed as const items
1081         if self.look_ahead(1, |t| t != &token::OpenDelim(Delimiter::Brace))
1082             && self.eat_keyword(kw::Const)
1083         {
1084             Const::Yes(self.prev_token.uninterpolated_span())
1085         } else {
1086             Const::No
1087         }
1088     }
1089
1090     /// Parses inline const expressions.
1091     fn parse_const_block(&mut self, span: Span, pat: bool) -> PResult<'a, P<Expr>> {
1092         if pat {
1093             self.sess.gated_spans.gate(sym::inline_const_pat, span);
1094         } else {
1095             self.sess.gated_spans.gate(sym::inline_const, span);
1096         }
1097         self.eat_keyword(kw::Const);
1098         let (attrs, blk) = self.parse_inner_attrs_and_block()?;
1099         let anon_const = AnonConst {
1100             id: DUMMY_NODE_ID,
1101             value: self.mk_expr(blk.span, ExprKind::Block(blk, None), AttrVec::new()),
1102         };
1103         let blk_span = anon_const.value.span;
1104         Ok(self.mk_expr(span.to(blk_span), ExprKind::ConstBlock(anon_const), AttrVec::from(attrs)))
1105     }
1106
1107     /// Parses mutability (`mut` or nothing).
1108     fn parse_mutability(&mut self) -> Mutability {
1109         if self.eat_keyword(kw::Mut) { Mutability::Mut } else { Mutability::Not }
1110     }
1111
1112     /// Possibly parses mutability (`const` or `mut`).
1113     fn parse_const_or_mut(&mut self) -> Option<Mutability> {
1114         if self.eat_keyword(kw::Mut) {
1115             Some(Mutability::Mut)
1116         } else if self.eat_keyword(kw::Const) {
1117             Some(Mutability::Not)
1118         } else {
1119             None
1120         }
1121     }
1122
1123     fn parse_field_name(&mut self) -> PResult<'a, Ident> {
1124         if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) = self.token.kind
1125         {
1126             self.expect_no_suffix(self.token.span, "a tuple index", suffix);
1127             self.bump();
1128             Ok(Ident::new(symbol, self.prev_token.span))
1129         } else {
1130             self.parse_ident_common(true)
1131         }
1132     }
1133
1134     fn parse_mac_args(&mut self) -> PResult<'a, P<MacArgs>> {
1135         self.parse_mac_args_common(true).map(P)
1136     }
1137
1138     fn parse_attr_args(&mut self) -> PResult<'a, MacArgs> {
1139         self.parse_mac_args_common(false)
1140     }
1141
1142     fn parse_mac_args_common(&mut self, delimited_only: bool) -> PResult<'a, MacArgs> {
1143         Ok(
1144             if self.check(&token::OpenDelim(Delimiter::Parenthesis))
1145                 || self.check(&token::OpenDelim(Delimiter::Bracket))
1146                 || self.check(&token::OpenDelim(Delimiter::Brace))
1147             {
1148                 match self.parse_token_tree() {
1149                     TokenTree::Delimited(dspan, delim, tokens) =>
1150                     // We've confirmed above that there is a delimiter so unwrapping is OK.
1151                     {
1152                         MacArgs::Delimited(dspan, MacDelimiter::from_token(delim).unwrap(), tokens)
1153                     }
1154                     _ => unreachable!(),
1155                 }
1156             } else if !delimited_only {
1157                 if self.eat(&token::Eq) {
1158                     let eq_span = self.prev_token.span;
1159                     MacArgs::Eq(eq_span, MacArgsEq::Ast(self.parse_expr_force_collect()?))
1160                 } else {
1161                     MacArgs::Empty
1162                 }
1163             } else {
1164                 return self.unexpected();
1165             },
1166         )
1167     }
1168
1169     fn parse_or_use_outer_attributes(
1170         &mut self,
1171         already_parsed_attrs: Option<AttrWrapper>,
1172     ) -> PResult<'a, AttrWrapper> {
1173         if let Some(attrs) = already_parsed_attrs {
1174             Ok(attrs)
1175         } else {
1176             self.parse_outer_attributes()
1177         }
1178     }
1179
1180     /// Parses a single token tree from the input.
1181     pub(crate) fn parse_token_tree(&mut self) -> TokenTree {
1182         match self.token.kind {
1183             token::OpenDelim(..) => {
1184                 // Grab the tokens from this frame.
1185                 let frame = &self.token_cursor.frame;
1186                 let stream = frame.tree_cursor.stream.clone();
1187                 let (delim, span) = frame.delim_sp.unwrap();
1188
1189                 // Advance the token cursor through the entire delimited
1190                 // sequence. After getting the `OpenDelim` we are *within* the
1191                 // delimited sequence, i.e. at depth `d`. After getting the
1192                 // matching `CloseDelim` we are *after* the delimited sequence,
1193                 // i.e. at depth `d - 1`.
1194                 let target_depth = self.token_cursor.stack.len() - 1;
1195                 loop {
1196                     // Advance one token at a time, so `TokenCursor::next()`
1197                     // can capture these tokens if necessary.
1198                     self.bump();
1199                     if self.token_cursor.stack.len() == target_depth {
1200                         debug_assert!(matches!(self.token.kind, token::CloseDelim(_)));
1201                         break;
1202                     }
1203                 }
1204
1205                 // Consume close delimiter
1206                 self.bump();
1207                 TokenTree::Delimited(span, delim, stream)
1208             }
1209             token::CloseDelim(_) | token::Eof => unreachable!(),
1210             _ => {
1211                 self.bump();
1212                 TokenTree::Token(self.prev_token.clone())
1213             }
1214         }
1215     }
1216
1217     /// Parses a stream of tokens into a list of `TokenTree`s, up to EOF.
1218     pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
1219         let mut tts = Vec::new();
1220         while self.token != token::Eof {
1221             tts.push(self.parse_token_tree());
1222         }
1223         Ok(tts)
1224     }
1225
1226     pub fn parse_tokens(&mut self) -> TokenStream {
1227         let mut result = Vec::new();
1228         loop {
1229             match self.token.kind {
1230                 token::Eof | token::CloseDelim(..) => break,
1231                 _ => result.push(self.parse_token_tree().into()),
1232             }
1233         }
1234         TokenStream::new(result)
1235     }
1236
1237     /// Evaluates the closure with restrictions in place.
1238     ///
1239     /// Afters the closure is evaluated, restrictions are reset.
1240     fn with_res<T>(&mut self, res: Restrictions, f: impl FnOnce(&mut Self) -> T) -> T {
1241         let old = self.restrictions;
1242         self.restrictions = res;
1243         let res = f(self);
1244         self.restrictions = old;
1245         res
1246     }
1247
1248     fn is_crate_vis(&self) -> bool {
1249         self.token.is_keyword(kw::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
1250     }
1251
1252     /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`,
1253     /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`.
1254     /// If the following element can't be a tuple (i.e., it's a function definition), then
1255     /// it's not a tuple struct field), and the contents within the parentheses aren't valid,
1256     /// so emit a proper diagnostic.
1257     // Public for rustfmt usage.
1258     pub fn parse_visibility(&mut self, fbt: FollowedByType) -> PResult<'a, Visibility> {
1259         maybe_whole!(self, NtVis, |x| x.into_inner());
1260
1261         self.expected_tokens.push(TokenType::Keyword(kw::Crate));
1262         if self.is_crate_vis() {
1263             self.bump(); // `crate`
1264             self.sess.gated_spans.gate(sym::crate_visibility_modifier, self.prev_token.span);
1265             return Ok(Visibility {
1266                 span: self.prev_token.span,
1267                 kind: VisibilityKind::Crate(CrateSugar::JustCrate),
1268                 tokens: None,
1269             });
1270         }
1271
1272         if !self.eat_keyword(kw::Pub) {
1273             // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
1274             // keyword to grab a span from for inherited visibility; an empty span at the
1275             // beginning of the current token would seem to be the "Schelling span".
1276             return Ok(Visibility {
1277                 span: self.token.span.shrink_to_lo(),
1278                 kind: VisibilityKind::Inherited,
1279                 tokens: None,
1280             });
1281         }
1282         let lo = self.prev_token.span;
1283
1284         if self.check(&token::OpenDelim(Delimiter::Parenthesis)) {
1285             // We don't `self.bump()` the `(` yet because this might be a struct definition where
1286             // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
1287             // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
1288             // by the following tokens.
1289             if self.is_keyword_ahead(1, &[kw::Crate]) && self.look_ahead(2, |t| t != &token::ModSep)
1290             // account for `pub(crate::foo)`
1291             {
1292                 // Parse `pub(crate)`.
1293                 self.bump(); // `(`
1294                 self.bump(); // `crate`
1295                 self.expect(&token::CloseDelim(Delimiter::Parenthesis))?; // `)`
1296                 let vis = VisibilityKind::Crate(CrateSugar::PubCrate);
1297                 return Ok(Visibility {
1298                     span: lo.to(self.prev_token.span),
1299                     kind: vis,
1300                     tokens: None,
1301                 });
1302             } else if self.is_keyword_ahead(1, &[kw::In]) {
1303                 // Parse `pub(in path)`.
1304                 self.bump(); // `(`
1305                 self.bump(); // `in`
1306                 let path = self.parse_path(PathStyle::Mod)?; // `path`
1307                 self.expect(&token::CloseDelim(Delimiter::Parenthesis))?; // `)`
1308                 let vis = VisibilityKind::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
1309                 return Ok(Visibility {
1310                     span: lo.to(self.prev_token.span),
1311                     kind: vis,
1312                     tokens: None,
1313                 });
1314             } else if self.look_ahead(2, |t| t == &token::CloseDelim(Delimiter::Parenthesis))
1315                 && self.is_keyword_ahead(1, &[kw::Super, kw::SelfLower])
1316             {
1317                 // Parse `pub(self)` or `pub(super)`.
1318                 self.bump(); // `(`
1319                 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
1320                 self.expect(&token::CloseDelim(Delimiter::Parenthesis))?; // `)`
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 let FollowedByType::No = fbt {
1328                 // Provide this diagnostic if a type cannot follow;
1329                 // in particular, if this is not a tuple struct.
1330                 self.recover_incorrect_vis_restriction()?;
1331                 // Emit diagnostic, but continue with public visibility.
1332             }
1333         }
1334
1335         Ok(Visibility { span: lo, kind: VisibilityKind::Public, tokens: None })
1336     }
1337
1338     /// Recovery for e.g. `pub(something) fn ...` or `struct X { pub(something) y: Z }`
1339     fn recover_incorrect_vis_restriction(&mut self) -> PResult<'a, ()> {
1340         self.bump(); // `(`
1341         let path = self.parse_path(PathStyle::Mod)?;
1342         self.expect(&token::CloseDelim(Delimiter::Parenthesis))?; // `)`
1343
1344         let msg = "incorrect visibility restriction";
1345         let suggestion = r##"some possible visibility restrictions are:
1346 `pub(crate)`: visible only on the current crate
1347 `pub(super)`: visible only in the current module's parent
1348 `pub(in path::to::module)`: visible only on the specified path"##;
1349
1350         let path_str = pprust::path_to_string(&path);
1351
1352         struct_span_err!(self.sess.span_diagnostic, path.span, E0704, "{}", msg)
1353             .help(suggestion)
1354             .span_suggestion(
1355                 path.span,
1356                 &format!("make this visible only to module `{}` with `in`", path_str),
1357                 format!("in {}", path_str),
1358                 Applicability::MachineApplicable,
1359             )
1360             .emit();
1361
1362         Ok(())
1363     }
1364
1365     /// Parses `extern string_literal?`.
1366     fn parse_extern(&mut self) -> Extern {
1367         if self.eat_keyword(kw::Extern) { Extern::from_abi(self.parse_abi()) } else { Extern::None }
1368     }
1369
1370     /// Parses a string literal as an ABI spec.
1371     fn parse_abi(&mut self) -> Option<StrLit> {
1372         match self.parse_str_lit() {
1373             Ok(str_lit) => Some(str_lit),
1374             Err(Some(lit)) => match lit.kind {
1375                 ast::LitKind::Err(_) => None,
1376                 _ => {
1377                     self.struct_span_err(lit.span, "non-string ABI literal")
1378                         .span_suggestion(
1379                             lit.span,
1380                             "specify the ABI with a string literal",
1381                             "\"C\"".to_string(),
1382                             Applicability::MaybeIncorrect,
1383                         )
1384                         .emit();
1385                     None
1386                 }
1387             },
1388             Err(None) => None,
1389         }
1390     }
1391
1392     pub fn collect_tokens_no_attrs<R: AstLike>(
1393         &mut self,
1394         f: impl FnOnce(&mut Self) -> PResult<'a, R>,
1395     ) -> PResult<'a, R> {
1396         // The only reason to call `collect_tokens_no_attrs` is if you want tokens, so use
1397         // `ForceCollect::Yes`
1398         self.collect_tokens_trailing_token(
1399             AttrWrapper::empty(),
1400             ForceCollect::Yes,
1401             |this, _attrs| Ok((f(this)?, TrailingToken::None)),
1402         )
1403     }
1404
1405     /// `::{` or `::*`
1406     fn is_import_coupler(&mut self) -> bool {
1407         self.check(&token::ModSep)
1408             && self.look_ahead(1, |t| {
1409                 *t == token::OpenDelim(Delimiter::Brace) || *t == token::BinOp(token::Star)
1410             })
1411     }
1412
1413     pub fn clear_expected_tokens(&mut self) {
1414         self.expected_tokens.clear();
1415     }
1416 }
1417
1418 crate fn make_unclosed_delims_error(
1419     unmatched: UnmatchedBrace,
1420     sess: &ParseSess,
1421 ) -> Option<DiagnosticBuilder<'_, ErrorGuaranteed>> {
1422     // `None` here means an `Eof` was found. We already emit those errors elsewhere, we add them to
1423     // `unmatched_braces` only for error recovery in the `Parser`.
1424     let found_delim = unmatched.found_delim?;
1425     let span: MultiSpan = if let Some(sp) = unmatched.unclosed_span {
1426         vec![unmatched.found_span, sp].into()
1427     } else {
1428         unmatched.found_span.into()
1429     };
1430     let mut err = sess.span_diagnostic.struct_span_err(
1431         span,
1432         &format!(
1433             "mismatched closing delimiter: `{}`",
1434             pprust::token_kind_to_string(&token::CloseDelim(found_delim)),
1435         ),
1436     );
1437     err.span_label(unmatched.found_span, "mismatched closing delimiter");
1438     if let Some(sp) = unmatched.candidate_span {
1439         err.span_label(sp, "closing delimiter possibly meant for this");
1440     }
1441     if let Some(sp) = unmatched.unclosed_span {
1442         err.span_label(sp, "unclosed delimiter");
1443     }
1444     Some(err)
1445 }
1446
1447 pub fn emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedBrace>, sess: &ParseSess) {
1448     *sess.reached_eof.borrow_mut() |=
1449         unclosed_delims.iter().any(|unmatched_delim| unmatched_delim.found_delim.is_none());
1450     for unmatched in unclosed_delims.drain(..) {
1451         if let Some(mut e) = make_unclosed_delims_error(unmatched, sess) {
1452             e.emit();
1453         }
1454     }
1455 }
1456
1457 /// A helper struct used when building an `AttrAnnotatedTokenStream` from
1458 /// a `LazyTokenStream`. Both delimiter and non-delimited tokens
1459 /// are stored as `FlatToken::Token`. A vector of `FlatToken`s
1460 /// is then 'parsed' to build up an `AttrAnnotatedTokenStream` with nested
1461 /// `AttrAnnotatedTokenTree::Delimited` tokens
1462 #[derive(Debug, Clone)]
1463 pub enum FlatToken {
1464     /// A token - this holds both delimiter (e.g. '{' and '}')
1465     /// and non-delimiter tokens
1466     Token(Token),
1467     /// Holds the `AttributesData` for an AST node. The
1468     /// `AttributesData` is inserted directly into the
1469     /// constructed `AttrAnnotatedTokenStream` as
1470     /// an `AttrAnnotatedTokenTree::Attributes`
1471     AttrTarget(AttributesData),
1472     /// A special 'empty' token that is ignored during the conversion
1473     /// to an `AttrAnnotatedTokenStream`. This is used to simplify the
1474     /// handling of replace ranges.
1475     Empty,
1476 }
1477
1478 #[derive(Debug)]
1479 pub enum NtOrTt {
1480     Nt(Nonterminal),
1481     Tt(TokenTree),
1482 }