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