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