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