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