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