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