]> git.lizzy.rs Git - rust.git/blob - src/librustc_parse/parser/mod.rs
Auto merge of #75071 - ssomers:btree_cleanup_5, r=Mark-Simulacrum
[rust.git] / src / librustc_parse / parser / mod.rs
1 pub mod attr;
2 mod diagnostics;
3 mod expr;
4 mod generics;
5 mod item;
6 mod nonterminal;
7 mod pat;
8 mod path;
9 mod stmt;
10 mod ty;
11
12 use crate::lexer::UnmatchedBrace;
13 use diagnostics::Error;
14 pub use path::PathStyle;
15
16 use log::debug;
17 use rustc_ast::ast::DUMMY_NODE_ID;
18 use rustc_ast::ast::{self, AttrStyle, AttrVec, Const, CrateSugar, Extern, Unsafe};
19 use rustc_ast::ast::{
20     Async, MacArgs, MacDelimiter, Mutability, StrLit, Visibility, VisibilityKind,
21 };
22 use rustc_ast::ptr::P;
23 use rustc_ast::token::{self, DelimToken, Token, TokenKind};
24 use rustc_ast::tokenstream::{self, DelimSpan, TokenStream, TokenTree, TreeAndJoint};
25 use rustc_ast_pretty::pprust;
26 use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder, FatalError, PResult};
27 use rustc_session::parse::ParseSess;
28 use rustc_span::source_map::{respan, Span, DUMMY_SP};
29 use rustc_span::symbol::{kw, sym, Ident, Symbol};
30
31 use std::{cmp, mem, slice};
32
33 bitflags::bitflags! {
34     struct Restrictions: u8 {
35         const STMT_EXPR         = 1 << 0;
36         const NO_STRUCT_LITERAL = 1 << 1;
37     }
38 }
39
40 #[derive(Clone, Copy, PartialEq, Debug)]
41 enum SemiColonMode {
42     Break,
43     Ignore,
44     Comma,
45 }
46
47 #[derive(Clone, Copy, PartialEq, Debug)]
48 enum BlockMode {
49     Break,
50     Ignore,
51 }
52
53 /// Like `maybe_whole_expr`, but for things other than expressions.
54 #[macro_export]
55 macro_rules! maybe_whole {
56     ($p:expr, $constructor:ident, |$x:ident| $e:expr) => {
57         if let token::Interpolated(nt) = &$p.token.kind {
58             if let token::$constructor(x) = &**nt {
59                 let $x = x.clone();
60                 $p.bump();
61                 return Ok($e);
62             }
63         }
64     };
65 }
66
67 /// If the next tokens are ill-formed `$ty::` recover them as `<$ty>::`.
68 #[macro_export]
69 macro_rules! maybe_recover_from_interpolated_ty_qpath {
70     ($self: expr, $allow_qpath_recovery: expr) => {
71         if $allow_qpath_recovery && $self.look_ahead(1, |t| t == &token::ModSep) {
72             if let token::Interpolated(nt) = &$self.token.kind {
73                 if let token::NtTy(ty) = &**nt {
74                     let ty = ty.clone();
75                     $self.bump();
76                     return $self.maybe_recover_from_bad_qpath_stage_2($self.prev_token.span, ty);
77                 }
78             }
79         }
80     };
81 }
82
83 #[derive(Clone)]
84 pub struct Parser<'a> {
85     pub sess: &'a ParseSess,
86     /// The current token.
87     pub token: Token,
88     /// The previous token.
89     pub prev_token: Token,
90     restrictions: Restrictions,
91     expected_tokens: Vec<TokenType>,
92     token_cursor: TokenCursor,
93     desugar_doc_comments: bool,
94     /// This field is used to keep track of how many left angle brackets we have seen. This is
95     /// required in order to detect extra leading left angle brackets (`<` characters) and error
96     /// appropriately.
97     ///
98     /// See the comments in the `parse_path_segment` function for more details.
99     unmatched_angle_bracket_count: u32,
100     max_angle_bracket_count: u32,
101     /// A list of all unclosed delimiters found by the lexer. If an entry is used for error recovery
102     /// it gets removed from here. Every entry left at the end gets emitted as an independent
103     /// error.
104     pub(super) unclosed_delims: Vec<UnmatchedBrace>,
105     last_unexpected_token_span: Option<Span>,
106     pub last_type_ascription: Option<(Span, bool /* likely path typo */)>,
107     /// If present, this `Parser` is not parsing Rust code but rather a macro call.
108     subparser_name: Option<&'static str>,
109 }
110
111 impl<'a> Drop for Parser<'a> {
112     fn drop(&mut self) {
113         emit_unclosed_delims(&mut self.unclosed_delims, &self.sess);
114     }
115 }
116
117 #[derive(Clone)]
118 struct TokenCursor {
119     frame: TokenCursorFrame,
120     stack: Vec<TokenCursorFrame>,
121     cur_token: Option<TreeAndJoint>,
122     collecting: Option<Collecting>,
123 }
124
125 #[derive(Clone)]
126 struct TokenCursorFrame {
127     delim: token::DelimToken,
128     span: DelimSpan,
129     open_delim: bool,
130     tree_cursor: tokenstream::Cursor,
131     close_delim: bool,
132 }
133
134 /// Used to track additional state needed by `collect_tokens`
135 #[derive(Clone, Debug)]
136 struct Collecting {
137     /// Holds the current tokens captured during the most
138     /// recent call to `collect_tokens`
139     buf: Vec<TreeAndJoint>,
140     /// The depth of the `TokenCursor` stack at the time
141     /// collection was started. When we encounter a `TokenTree::Delimited`,
142     /// we want to record the `TokenTree::Delimited` itself,
143     /// but *not* any of the inner tokens while we are inside
144     /// the new frame (this would cause us to record duplicate tokens).
145     ///
146     /// This `depth` fields tracks stack depth we are recording tokens.
147     /// Only tokens encountered at this depth will be recorded. See
148     /// `TokenCursor::next` for more details.
149     depth: usize,
150 }
151
152 impl TokenCursorFrame {
153     fn new(span: DelimSpan, delim: DelimToken, tts: &TokenStream) -> Self {
154         TokenCursorFrame {
155             delim,
156             span,
157             open_delim: delim == token::NoDelim,
158             tree_cursor: tts.clone().into_trees(),
159             close_delim: delim == token::NoDelim,
160         }
161     }
162 }
163
164 impl TokenCursor {
165     fn next(&mut self) -> Token {
166         loop {
167             let tree = if !self.frame.open_delim {
168                 self.frame.open_delim = true;
169                 TokenTree::open_tt(self.frame.span, self.frame.delim).into()
170             } else if let Some(tree) = self.frame.tree_cursor.next_with_joint() {
171                 tree
172             } else if !self.frame.close_delim {
173                 self.frame.close_delim = true;
174                 TokenTree::close_tt(self.frame.span, self.frame.delim).into()
175             } else if let Some(frame) = self.stack.pop() {
176                 self.frame = frame;
177                 continue;
178             } else {
179                 return Token::new(token::Eof, DUMMY_SP);
180             };
181
182             // Don't set an open delimiter as our current token - we want
183             // to leave it as the full `TokenTree::Delimited` from the previous
184             // iteration of this loop
185             if !matches!(tree.0, TokenTree::Token(Token { kind: TokenKind::OpenDelim(_), .. })) {
186                 self.cur_token = Some(tree.clone());
187             }
188
189             if let Some(collecting) = &mut self.collecting {
190                 if collecting.depth == self.stack.len() {
191                     debug!(
192                         "TokenCursor::next():  collected {:?} at depth {:?}",
193                         tree,
194                         self.stack.len()
195                     );
196                     collecting.buf.push(tree.clone())
197                 }
198             }
199
200             match tree.0 {
201                 TokenTree::Token(token) => return token,
202                 TokenTree::Delimited(sp, delim, tts) => {
203                     let frame = TokenCursorFrame::new(sp, delim, &tts);
204                     self.stack.push(mem::replace(&mut self.frame, frame));
205                 }
206             }
207         }
208     }
209
210     fn next_desugared(&mut self) -> Token {
211         let (data, attr_style, sp) = match self.next() {
212             Token { kind: token::DocComment(_, attr_style, data), span } => {
213                 (data, attr_style, span)
214             }
215             tok => return tok,
216         };
217
218         // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
219         // required to wrap the text.
220         let mut num_of_hashes = 0;
221         let mut count = 0;
222         for ch in data.as_str().chars() {
223             count = match ch {
224                 '"' => 1,
225                 '#' if count > 0 => count + 1,
226                 _ => 0,
227             };
228             num_of_hashes = cmp::max(num_of_hashes, count);
229         }
230
231         let delim_span = DelimSpan::from_single(sp);
232         let body = TokenTree::Delimited(
233             delim_span,
234             token::Bracket,
235             [
236                 TokenTree::token(token::Ident(sym::doc, false), sp),
237                 TokenTree::token(token::Eq, sp),
238                 TokenTree::token(TokenKind::lit(token::StrRaw(num_of_hashes), data, None), sp),
239             ]
240             .iter()
241             .cloned()
242             .collect::<TokenStream>(),
243         );
244
245         self.stack.push(mem::replace(
246             &mut self.frame,
247             TokenCursorFrame::new(
248                 delim_span,
249                 token::NoDelim,
250                 &if attr_style == AttrStyle::Inner {
251                     [TokenTree::token(token::Pound, sp), TokenTree::token(token::Not, sp), body]
252                         .iter()
253                         .cloned()
254                         .collect::<TokenStream>()
255                 } else {
256                     [TokenTree::token(token::Pound, sp), body]
257                         .iter()
258                         .cloned()
259                         .collect::<TokenStream>()
260                 },
261             ),
262         ));
263
264         self.next()
265     }
266 }
267
268 #[derive(Clone, PartialEq)]
269 enum TokenType {
270     Token(TokenKind),
271     Keyword(Symbol),
272     Operator,
273     Lifetime,
274     Ident,
275     Path,
276     Type,
277     Const,
278 }
279
280 impl TokenType {
281     fn to_string(&self) -> String {
282         match *self {
283             TokenType::Token(ref t) => format!("`{}`", pprust::token_kind_to_string(t)),
284             TokenType::Keyword(kw) => format!("`{}`", kw),
285             TokenType::Operator => "an operator".to_string(),
286             TokenType::Lifetime => "lifetime".to_string(),
287             TokenType::Ident => "identifier".to_string(),
288             TokenType::Path => "path".to_string(),
289             TokenType::Type => "type".to_string(),
290             TokenType::Const => "const".to_string(),
291         }
292     }
293 }
294
295 #[derive(Copy, Clone, Debug)]
296 enum TokenExpectType {
297     Expect,
298     NoExpect,
299 }
300
301 /// A sequence separator.
302 struct SeqSep {
303     /// The separator token.
304     sep: Option<TokenKind>,
305     /// `true` if a trailing separator is allowed.
306     trailing_sep_allowed: bool,
307 }
308
309 impl SeqSep {
310     fn trailing_allowed(t: TokenKind) -> SeqSep {
311         SeqSep { sep: Some(t), trailing_sep_allowed: true }
312     }
313
314     fn none() -> SeqSep {
315         SeqSep { sep: None, trailing_sep_allowed: false }
316     }
317 }
318
319 pub enum FollowedByType {
320     Yes,
321     No,
322 }
323
324 fn token_descr_opt(token: &Token) -> Option<&'static str> {
325     Some(match token.kind {
326         _ if token.is_special_ident() => "reserved identifier",
327         _ if token.is_used_keyword() => "keyword",
328         _ if token.is_unused_keyword() => "reserved keyword",
329         token::DocComment(..) => "doc comment",
330         _ => return None,
331     })
332 }
333
334 pub(super) fn token_descr(token: &Token) -> String {
335     let token_str = pprust::token_to_string(token);
336     match token_descr_opt(token) {
337         Some(prefix) => format!("{} `{}`", prefix, token_str),
338         _ => format!("`{}`", token_str),
339     }
340 }
341
342 impl<'a> Parser<'a> {
343     pub fn new(
344         sess: &'a ParseSess,
345         tokens: TokenStream,
346         desugar_doc_comments: bool,
347         subparser_name: Option<&'static str>,
348     ) -> Self {
349         let mut parser = Parser {
350             sess,
351             token: Token::dummy(),
352             prev_token: Token::dummy(),
353             restrictions: Restrictions::empty(),
354             expected_tokens: Vec::new(),
355             token_cursor: TokenCursor {
356                 frame: TokenCursorFrame::new(DelimSpan::dummy(), token::NoDelim, &tokens),
357                 stack: Vec::new(),
358                 cur_token: None,
359                 collecting: None,
360             },
361             desugar_doc_comments,
362             unmatched_angle_bracket_count: 0,
363             max_angle_bracket_count: 0,
364             unclosed_delims: Vec::new(),
365             last_unexpected_token_span: None,
366             last_type_ascription: None,
367             subparser_name,
368         };
369
370         // Make parser point to the first token.
371         parser.bump();
372
373         parser
374     }
375
376     fn next_tok(&mut self, fallback_span: Span) -> Token {
377         let mut next = if self.desugar_doc_comments {
378             self.token_cursor.next_desugared()
379         } else {
380             self.token_cursor.next()
381         };
382         if next.span.is_dummy() {
383             // Tweak the location for better diagnostics, but keep syntactic context intact.
384             next.span = fallback_span.with_ctxt(next.span.ctxt());
385         }
386         next
387     }
388
389     crate fn unexpected<T>(&mut self) -> PResult<'a, T> {
390         match self.expect_one_of(&[], &[]) {
391             Err(e) => Err(e),
392             // We can get `Ok(true)` from `recover_closing_delimiter`
393             // which is called in `expected_one_of_not_found`.
394             Ok(_) => FatalError.raise(),
395         }
396     }
397
398     /// Expects and consumes the token `t`. Signals an error if the next token is not `t`.
399     pub fn expect(&mut self, t: &TokenKind) -> PResult<'a, bool /* recovered */> {
400         if self.expected_tokens.is_empty() {
401             if self.token == *t {
402                 self.bump();
403                 Ok(false)
404             } else {
405                 self.unexpected_try_recover(t)
406             }
407         } else {
408             self.expect_one_of(slice::from_ref(t), &[])
409         }
410     }
411
412     /// Expect next token to be edible or inedible token.  If edible,
413     /// then consume it; if inedible, then return without consuming
414     /// anything.  Signal a fatal error if next token is unexpected.
415     pub fn expect_one_of(
416         &mut self,
417         edible: &[TokenKind],
418         inedible: &[TokenKind],
419     ) -> PResult<'a, bool /* recovered */> {
420         if edible.contains(&self.token.kind) {
421             self.bump();
422             Ok(false)
423         } else if inedible.contains(&self.token.kind) {
424             // leave it in the input
425             Ok(false)
426         } else if self.last_unexpected_token_span == Some(self.token.span) {
427             FatalError.raise();
428         } else {
429             self.expected_one_of_not_found(edible, inedible)
430         }
431     }
432
433     // Public for rustfmt usage.
434     pub fn parse_ident(&mut self) -> PResult<'a, Ident> {
435         self.parse_ident_common(true)
436     }
437
438     fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, Ident> {
439         match self.token.ident() {
440             Some((ident, is_raw)) => {
441                 if !is_raw && ident.is_reserved() {
442                     let mut err = self.expected_ident_found();
443                     if recover {
444                         err.emit();
445                     } else {
446                         return Err(err);
447                     }
448                 }
449                 self.bump();
450                 Ok(ident)
451             }
452             _ => Err(match self.prev_token.kind {
453                 TokenKind::DocComment(..) => {
454                     self.span_fatal_err(self.prev_token.span, Error::UselessDocComment)
455                 }
456                 _ => self.expected_ident_found(),
457             }),
458         }
459     }
460
461     /// Checks if the next token is `tok`, and returns `true` if so.
462     ///
463     /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
464     /// encountered.
465     fn check(&mut self, tok: &TokenKind) -> bool {
466         let is_present = self.token == *tok;
467         if !is_present {
468             self.expected_tokens.push(TokenType::Token(tok.clone()));
469         }
470         is_present
471     }
472
473     /// Consumes a token 'tok' if it exists. Returns whether the given token was present.
474     pub fn eat(&mut self, tok: &TokenKind) -> bool {
475         let is_present = self.check(tok);
476         if is_present {
477             self.bump()
478         }
479         is_present
480     }
481
482     /// If the next token is the given keyword, returns `true` without eating it.
483     /// An expectation is also added for diagnostics purposes.
484     fn check_keyword(&mut self, kw: Symbol) -> bool {
485         self.expected_tokens.push(TokenType::Keyword(kw));
486         self.token.is_keyword(kw)
487     }
488
489     /// If the next token is the given keyword, eats it and returns `true`.
490     /// Otherwise, returns `false`. An expectation is also added for diagnostics purposes.
491     // Public for rustfmt usage.
492     pub fn eat_keyword(&mut self, kw: Symbol) -> bool {
493         if self.check_keyword(kw) {
494             self.bump();
495             true
496         } else {
497             false
498         }
499     }
500
501     fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool {
502         if self.token.is_keyword(kw) {
503             self.bump();
504             true
505         } else {
506             false
507         }
508     }
509
510     /// If the given word is not a keyword, signals an error.
511     /// If the next token is not the given word, signals an error.
512     /// Otherwise, eats it.
513     fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> {
514         if !self.eat_keyword(kw) { self.unexpected() } else { Ok(()) }
515     }
516
517     /// Is the given keyword `kw` followed by a non-reserved identifier?
518     fn is_kw_followed_by_ident(&self, kw: Symbol) -> bool {
519         self.token.is_keyword(kw) && self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
520     }
521
522     fn check_or_expected(&mut self, ok: bool, typ: TokenType) -> bool {
523         if ok {
524             true
525         } else {
526             self.expected_tokens.push(typ);
527             false
528         }
529     }
530
531     fn check_ident(&mut self) -> bool {
532         self.check_or_expected(self.token.is_ident(), TokenType::Ident)
533     }
534
535     fn check_path(&mut self) -> bool {
536         self.check_or_expected(self.token.is_path_start(), TokenType::Path)
537     }
538
539     fn check_type(&mut self) -> bool {
540         self.check_or_expected(self.token.can_begin_type(), TokenType::Type)
541     }
542
543     fn check_const_arg(&mut self) -> bool {
544         self.check_or_expected(self.token.can_begin_const_arg(), TokenType::Const)
545     }
546
547     /// Checks to see if the next token is either `+` or `+=`.
548     /// Otherwise returns `false`.
549     fn check_plus(&mut self) -> bool {
550         self.check_or_expected(
551             self.token.is_like_plus(),
552             TokenType::Token(token::BinOp(token::Plus)),
553         )
554     }
555
556     /// Eats the expected token if it's present possibly breaking
557     /// compound tokens like multi-character operators in process.
558     /// Returns `true` if the token was eaten.
559     fn break_and_eat(&mut self, expected: TokenKind) -> bool {
560         if self.token.kind == expected {
561             self.bump();
562             return true;
563         }
564         match self.token.kind.break_two_token_op() {
565             Some((first, second)) if first == expected => {
566                 let first_span = self.sess.source_map().start_point(self.token.span);
567                 let second_span = self.token.span.with_lo(first_span.hi());
568                 self.token = Token::new(first, first_span);
569                 self.bump_with(Token::new(second, second_span));
570                 true
571             }
572             _ => {
573                 self.expected_tokens.push(TokenType::Token(expected));
574                 false
575             }
576         }
577     }
578
579     /// Eats `+` possibly breaking tokens like `+=` in process.
580     fn eat_plus(&mut self) -> bool {
581         self.break_and_eat(token::BinOp(token::Plus))
582     }
583
584     /// Eats `&` possibly breaking tokens like `&&` in process.
585     /// Signals an error if `&` is not eaten.
586     fn expect_and(&mut self) -> PResult<'a, ()> {
587         if self.break_and_eat(token::BinOp(token::And)) { Ok(()) } else { self.unexpected() }
588     }
589
590     /// Eats `|` possibly breaking tokens like `||` in process.
591     /// Signals an error if `|` was not eaten.
592     fn expect_or(&mut self) -> PResult<'a, ()> {
593         if self.break_and_eat(token::BinOp(token::Or)) { Ok(()) } else { self.unexpected() }
594     }
595
596     /// Eats `<` possibly breaking tokens like `<<` in process.
597     fn eat_lt(&mut self) -> bool {
598         let ate = self.break_and_eat(token::Lt);
599         if ate {
600             // See doc comment for `unmatched_angle_bracket_count`.
601             self.unmatched_angle_bracket_count += 1;
602             self.max_angle_bracket_count += 1;
603             debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count);
604         }
605         ate
606     }
607
608     /// Eats `<` possibly breaking tokens like `<<` in process.
609     /// Signals an error if `<` was not eaten.
610     fn expect_lt(&mut self) -> PResult<'a, ()> {
611         if self.eat_lt() { Ok(()) } else { self.unexpected() }
612     }
613
614     /// Eats `>` possibly breaking tokens like `>>` in process.
615     /// Signals an error if `>` was not eaten.
616     fn expect_gt(&mut self) -> PResult<'a, ()> {
617         if self.break_and_eat(token::Gt) {
618             // See doc comment for `unmatched_angle_bracket_count`.
619             if self.unmatched_angle_bracket_count > 0 {
620                 self.unmatched_angle_bracket_count -= 1;
621                 debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count);
622             }
623             Ok(())
624         } else {
625             self.unexpected()
626         }
627     }
628
629     fn expect_any_with_type(&mut self, kets: &[&TokenKind], expect: TokenExpectType) -> bool {
630         kets.iter().any(|k| match expect {
631             TokenExpectType::Expect => self.check(k),
632             TokenExpectType::NoExpect => self.token == **k,
633         })
634     }
635
636     fn parse_seq_to_before_tokens<T>(
637         &mut self,
638         kets: &[&TokenKind],
639         sep: SeqSep,
640         expect: TokenExpectType,
641         mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
642     ) -> PResult<'a, (Vec<T>, bool /* trailing */, bool /* recovered */)> {
643         let mut first = true;
644         let mut recovered = false;
645         let mut trailing = false;
646         let mut v = vec![];
647         while !self.expect_any_with_type(kets, expect) {
648             if let token::CloseDelim(..) | token::Eof = self.token.kind {
649                 break;
650             }
651             if let Some(ref t) = sep.sep {
652                 if first {
653                     first = false;
654                 } else {
655                     match self.expect(t) {
656                         Ok(false) => {}
657                         Ok(true) => {
658                             recovered = true;
659                             break;
660                         }
661                         Err(mut expect_err) => {
662                             let sp = self.prev_token.span.shrink_to_hi();
663                             let token_str = pprust::token_kind_to_string(t);
664
665                             // Attempt to keep parsing if it was a similar separator.
666                             if let Some(ref tokens) = t.similar_tokens() {
667                                 if tokens.contains(&self.token.kind) {
668                                     self.bump();
669                                 }
670                             }
671
672                             // If this was a missing `@` in a binding pattern
673                             // bail with a suggestion
674                             // https://github.com/rust-lang/rust/issues/72373
675                             if self.prev_token.is_ident() && self.token.kind == token::DotDot {
676                                 let msg = format!(
677                                     "if you meant to bind the contents of \
678                                     the rest of the array pattern into `{}`, use `@`",
679                                     pprust::token_to_string(&self.prev_token)
680                                 );
681                                 expect_err
682                                     .span_suggestion_verbose(
683                                         self.prev_token.span.shrink_to_hi().until(self.token.span),
684                                         &msg,
685                                         " @ ".to_string(),
686                                         Applicability::MaybeIncorrect,
687                                     )
688                                     .emit();
689                                 break;
690                             }
691
692                             // Attempt to keep parsing if it was an omitted separator.
693                             match f(self) {
694                                 Ok(t) => {
695                                     // Parsed successfully, therefore most probably the code only
696                                     // misses a separator.
697                                     expect_err
698                                         .span_suggestion_short(
699                                             self.sess.source_map().next_point(sp),
700                                             &format!("missing `{}`", token_str),
701                                             token_str,
702                                             Applicability::MaybeIncorrect,
703                                         )
704                                         .emit();
705
706                                     v.push(t);
707                                     continue;
708                                 }
709                                 Err(mut e) => {
710                                     // Parsing failed, therefore it must be something more serious
711                                     // than just a missing separator.
712                                     expect_err.emit();
713
714                                     e.cancel();
715                                     break;
716                                 }
717                             }
718                         }
719                     }
720                 }
721             }
722             if sep.trailing_sep_allowed && self.expect_any_with_type(kets, expect) {
723                 trailing = true;
724                 break;
725             }
726
727             let t = f(self)?;
728             v.push(t);
729         }
730
731         Ok((v, trailing, recovered))
732     }
733
734     /// Parses a sequence, not including the closing delimiter. The function
735     /// `f` must consume tokens until reaching the next separator or
736     /// closing bracket.
737     fn parse_seq_to_before_end<T>(
738         &mut self,
739         ket: &TokenKind,
740         sep: SeqSep,
741         f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
742     ) -> PResult<'a, (Vec<T>, bool, bool)> {
743         self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
744     }
745
746     /// Parses a sequence, including the closing delimiter. The function
747     /// `f` must consume tokens until reaching the next separator or
748     /// closing bracket.
749     fn parse_seq_to_end<T>(
750         &mut self,
751         ket: &TokenKind,
752         sep: SeqSep,
753         f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
754     ) -> PResult<'a, (Vec<T>, bool /* trailing */)> {
755         let (val, trailing, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
756         if !recovered {
757             self.eat(ket);
758         }
759         Ok((val, trailing))
760     }
761
762     /// Parses a sequence, including the closing delimiter. The function
763     /// `f` must consume tokens until reaching the next separator or
764     /// closing bracket.
765     fn parse_unspanned_seq<T>(
766         &mut self,
767         bra: &TokenKind,
768         ket: &TokenKind,
769         sep: SeqSep,
770         f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
771     ) -> PResult<'a, (Vec<T>, bool)> {
772         self.expect(bra)?;
773         self.parse_seq_to_end(ket, sep, f)
774     }
775
776     fn parse_delim_comma_seq<T>(
777         &mut self,
778         delim: DelimToken,
779         f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
780     ) -> PResult<'a, (Vec<T>, bool)> {
781         self.parse_unspanned_seq(
782             &token::OpenDelim(delim),
783             &token::CloseDelim(delim),
784             SeqSep::trailing_allowed(token::Comma),
785             f,
786         )
787     }
788
789     fn parse_paren_comma_seq<T>(
790         &mut self,
791         f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
792     ) -> PResult<'a, (Vec<T>, bool)> {
793         self.parse_delim_comma_seq(token::Paren, f)
794     }
795
796     /// Advance the parser by one token using provided token as the next one.
797     fn bump_with(&mut self, next_token: Token) {
798         // Bumping after EOF is a bad sign, usually an infinite loop.
799         if self.prev_token.kind == TokenKind::Eof {
800             let msg = "attempted to bump the parser past EOF (may be stuck in a loop)";
801             self.span_bug(self.token.span, msg);
802         }
803
804         // Update the current and previous tokens.
805         self.prev_token = mem::replace(&mut self.token, next_token);
806
807         // Diagnostics.
808         self.expected_tokens.clear();
809     }
810
811     /// Advance the parser by one token.
812     pub fn bump(&mut self) {
813         let next_token = self.next_tok(self.token.span);
814         self.bump_with(next_token);
815     }
816
817     /// Look-ahead `dist` tokens of `self.token` and get access to that token there.
818     /// When `dist == 0` then the current token is looked at.
819     pub fn look_ahead<R>(&self, dist: usize, looker: impl FnOnce(&Token) -> R) -> R {
820         if dist == 0 {
821             return looker(&self.token);
822         }
823
824         let frame = &self.token_cursor.frame;
825         looker(&match frame.tree_cursor.look_ahead(dist - 1) {
826             Some(tree) => match tree {
827                 TokenTree::Token(token) => token,
828                 TokenTree::Delimited(dspan, delim, _) => {
829                     Token::new(token::OpenDelim(delim), dspan.open)
830                 }
831             },
832             None => Token::new(token::CloseDelim(frame.delim), frame.span.close),
833         })
834     }
835
836     /// Returns whether any of the given keywords are `dist` tokens ahead of the current one.
837     fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool {
838         self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw)))
839     }
840
841     /// Parses asyncness: `async` or nothing.
842     fn parse_asyncness(&mut self) -> Async {
843         if self.eat_keyword(kw::Async) {
844             let span = self.prev_token.uninterpolated_span();
845             Async::Yes { span, closure_id: DUMMY_NODE_ID, return_impl_trait_id: DUMMY_NODE_ID }
846         } else {
847             Async::No
848         }
849     }
850
851     /// Parses unsafety: `unsafe` or nothing.
852     fn parse_unsafety(&mut self) -> Unsafe {
853         if self.eat_keyword(kw::Unsafe) {
854             Unsafe::Yes(self.prev_token.uninterpolated_span())
855         } else {
856             Unsafe::No
857         }
858     }
859
860     /// Parses constness: `const` or nothing.
861     fn parse_constness(&mut self) -> Const {
862         if self.eat_keyword(kw::Const) {
863             Const::Yes(self.prev_token.uninterpolated_span())
864         } else {
865             Const::No
866         }
867     }
868
869     /// Parses mutability (`mut` or nothing).
870     fn parse_mutability(&mut self) -> Mutability {
871         if self.eat_keyword(kw::Mut) { Mutability::Mut } else { Mutability::Not }
872     }
873
874     /// Possibly parses mutability (`const` or `mut`).
875     fn parse_const_or_mut(&mut self) -> Option<Mutability> {
876         if self.eat_keyword(kw::Mut) {
877             Some(Mutability::Mut)
878         } else if self.eat_keyword(kw::Const) {
879             Some(Mutability::Not)
880         } else {
881             None
882         }
883     }
884
885     fn parse_field_name(&mut self) -> PResult<'a, Ident> {
886         if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) = self.token.kind
887         {
888             self.expect_no_suffix(self.token.span, "a tuple index", suffix);
889             self.bump();
890             Ok(Ident::new(symbol, self.prev_token.span))
891         } else {
892             self.parse_ident_common(false)
893         }
894     }
895
896     fn parse_mac_args(&mut self) -> PResult<'a, P<MacArgs>> {
897         self.parse_mac_args_common(true).map(P)
898     }
899
900     fn parse_attr_args(&mut self) -> PResult<'a, MacArgs> {
901         self.parse_mac_args_common(false)
902     }
903
904     fn parse_mac_args_common(&mut self, delimited_only: bool) -> PResult<'a, MacArgs> {
905         Ok(
906             if self.check(&token::OpenDelim(DelimToken::Paren))
907                 || self.check(&token::OpenDelim(DelimToken::Bracket))
908                 || self.check(&token::OpenDelim(DelimToken::Brace))
909             {
910                 match self.parse_token_tree() {
911                     TokenTree::Delimited(dspan, delim, tokens) =>
912                     // We've confirmed above that there is a delimiter so unwrapping is OK.
913                     {
914                         MacArgs::Delimited(dspan, MacDelimiter::from_token(delim).unwrap(), tokens)
915                     }
916                     _ => unreachable!(),
917                 }
918             } else if !delimited_only {
919                 if self.eat(&token::Eq) {
920                     let eq_span = self.prev_token.span;
921                     let mut is_interpolated_expr = false;
922                     if let token::Interpolated(nt) = &self.token.kind {
923                         if let token::NtExpr(..) = **nt {
924                             is_interpolated_expr = true;
925                         }
926                     }
927                     let token_tree = if is_interpolated_expr {
928                         // We need to accept arbitrary interpolated expressions to continue
929                         // supporting things like `doc = $expr` that work on stable.
930                         // Non-literal interpolated expressions are rejected after expansion.
931                         self.parse_token_tree()
932                     } else {
933                         self.parse_unsuffixed_lit()?.token_tree()
934                     };
935
936                     MacArgs::Eq(eq_span, token_tree.into())
937                 } else {
938                     MacArgs::Empty
939                 }
940             } else {
941                 return self.unexpected();
942             },
943         )
944     }
945
946     fn parse_or_use_outer_attributes(
947         &mut self,
948         already_parsed_attrs: Option<AttrVec>,
949     ) -> PResult<'a, AttrVec> {
950         if let Some(attrs) = already_parsed_attrs {
951             Ok(attrs)
952         } else {
953             self.parse_outer_attributes().map(|a| a.into())
954         }
955     }
956
957     /// Parses a single token tree from the input.
958     pub(crate) fn parse_token_tree(&mut self) -> TokenTree {
959         match self.token.kind {
960             token::OpenDelim(..) => {
961                 let frame = mem::replace(
962                     &mut self.token_cursor.frame,
963                     self.token_cursor.stack.pop().unwrap(),
964                 );
965                 self.token = Token::new(TokenKind::CloseDelim(frame.delim), frame.span.close);
966                 self.bump();
967                 TokenTree::Delimited(frame.span, frame.delim, frame.tree_cursor.stream)
968             }
969             token::CloseDelim(_) | token::Eof => unreachable!(),
970             _ => {
971                 self.bump();
972                 TokenTree::Token(self.prev_token.clone())
973             }
974         }
975     }
976
977     /// Parses a stream of tokens into a list of `TokenTree`s, up to EOF.
978     pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
979         let mut tts = Vec::new();
980         while self.token != token::Eof {
981             tts.push(self.parse_token_tree());
982         }
983         Ok(tts)
984     }
985
986     pub fn parse_tokens(&mut self) -> TokenStream {
987         let mut result = Vec::new();
988         loop {
989             match self.token.kind {
990                 token::Eof | token::CloseDelim(..) => break,
991                 _ => result.push(self.parse_token_tree().into()),
992             }
993         }
994         TokenStream::new(result)
995     }
996
997     /// Evaluates the closure with restrictions in place.
998     ///
999     /// Afters the closure is evaluated, restrictions are reset.
1000     fn with_res<T>(&mut self, res: Restrictions, f: impl FnOnce(&mut Self) -> T) -> T {
1001         let old = self.restrictions;
1002         self.restrictions = res;
1003         let res = f(self);
1004         self.restrictions = old;
1005         res
1006     }
1007
1008     fn is_crate_vis(&self) -> bool {
1009         self.token.is_keyword(kw::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
1010     }
1011
1012     /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`,
1013     /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`.
1014     /// If the following element can't be a tuple (i.e., it's a function definition), then
1015     /// it's not a tuple struct field), and the contents within the parentheses isn't valid,
1016     /// so emit a proper diagnostic.
1017     pub(crate) fn parse_visibility(&mut self, fbt: FollowedByType) -> PResult<'a, Visibility> {
1018         maybe_whole!(self, NtVis, |x| x);
1019
1020         self.expected_tokens.push(TokenType::Keyword(kw::Crate));
1021         if self.is_crate_vis() {
1022             self.bump(); // `crate`
1023             self.sess.gated_spans.gate(sym::crate_visibility_modifier, self.prev_token.span);
1024             return Ok(respan(self.prev_token.span, VisibilityKind::Crate(CrateSugar::JustCrate)));
1025         }
1026
1027         if !self.eat_keyword(kw::Pub) {
1028             // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
1029             // keyword to grab a span from for inherited visibility; an empty span at the
1030             // beginning of the current token would seem to be the "Schelling span".
1031             return Ok(respan(self.token.span.shrink_to_lo(), VisibilityKind::Inherited));
1032         }
1033         let lo = self.prev_token.span;
1034
1035         if self.check(&token::OpenDelim(token::Paren)) {
1036             // We don't `self.bump()` the `(` yet because this might be a struct definition where
1037             // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
1038             // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
1039             // by the following tokens.
1040             if self.is_keyword_ahead(1, &[kw::Crate]) && self.look_ahead(2, |t| t != &token::ModSep)
1041             // account for `pub(crate::foo)`
1042             {
1043                 // Parse `pub(crate)`.
1044                 self.bump(); // `(`
1045                 self.bump(); // `crate`
1046                 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1047                 let vis = VisibilityKind::Crate(CrateSugar::PubCrate);
1048                 return Ok(respan(lo.to(self.prev_token.span), vis));
1049             } else if self.is_keyword_ahead(1, &[kw::In]) {
1050                 // Parse `pub(in path)`.
1051                 self.bump(); // `(`
1052                 self.bump(); // `in`
1053                 let path = self.parse_path(PathStyle::Mod)?; // `path`
1054                 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1055                 let vis = VisibilityKind::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
1056                 return Ok(respan(lo.to(self.prev_token.span), vis));
1057             } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren))
1058                 && self.is_keyword_ahead(1, &[kw::Super, kw::SelfLower])
1059             {
1060                 // Parse `pub(self)` or `pub(super)`.
1061                 self.bump(); // `(`
1062                 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
1063                 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1064                 let vis = VisibilityKind::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
1065                 return Ok(respan(lo.to(self.prev_token.span), vis));
1066             } else if let FollowedByType::No = fbt {
1067                 // Provide this diagnostic if a type cannot follow;
1068                 // in particular, if this is not a tuple struct.
1069                 self.recover_incorrect_vis_restriction()?;
1070                 // Emit diagnostic, but continue with public visibility.
1071             }
1072         }
1073
1074         Ok(respan(lo, VisibilityKind::Public))
1075     }
1076
1077     /// Recovery for e.g. `pub(something) fn ...` or `struct X { pub(something) y: Z }`
1078     fn recover_incorrect_vis_restriction(&mut self) -> PResult<'a, ()> {
1079         self.bump(); // `(`
1080         let path = self.parse_path(PathStyle::Mod)?;
1081         self.expect(&token::CloseDelim(token::Paren))?; // `)`
1082
1083         let msg = "incorrect visibility restriction";
1084         let suggestion = r##"some possible visibility restrictions are:
1085 `pub(crate)`: visible only on the current crate
1086 `pub(super)`: visible only in the current module's parent
1087 `pub(in path::to::module)`: visible only on the specified path"##;
1088
1089         let path_str = pprust::path_to_string(&path);
1090
1091         struct_span_err!(self.sess.span_diagnostic, path.span, E0704, "{}", msg)
1092             .help(suggestion)
1093             .span_suggestion(
1094                 path.span,
1095                 &format!("make this visible only to module `{}` with `in`", path_str),
1096                 format!("in {}", path_str),
1097                 Applicability::MachineApplicable,
1098             )
1099             .emit();
1100
1101         Ok(())
1102     }
1103
1104     /// Parses `extern string_literal?`.
1105     fn parse_extern(&mut self) -> PResult<'a, Extern> {
1106         Ok(if self.eat_keyword(kw::Extern) {
1107             Extern::from_abi(self.parse_abi())
1108         } else {
1109             Extern::None
1110         })
1111     }
1112
1113     /// Parses a string literal as an ABI spec.
1114     fn parse_abi(&mut self) -> Option<StrLit> {
1115         match self.parse_str_lit() {
1116             Ok(str_lit) => Some(str_lit),
1117             Err(Some(lit)) => match lit.kind {
1118                 ast::LitKind::Err(_) => None,
1119                 _ => {
1120                     self.struct_span_err(lit.span, "non-string ABI literal")
1121                         .span_suggestion(
1122                             lit.span,
1123                             "specify the ABI with a string literal",
1124                             "\"C\"".to_string(),
1125                             Applicability::MaybeIncorrect,
1126                         )
1127                         .emit();
1128                     None
1129                 }
1130             },
1131             Err(None) => None,
1132         }
1133     }
1134
1135     /// Records all tokens consumed by the provided callback,
1136     /// including the current token. These tokens are collected
1137     /// into a `TokenStream`, and returned along with the result
1138     /// of the callback.
1139     ///
1140     /// Note: If your callback consumes an opening delimiter
1141     /// (including the case where you call `collect_tokens`
1142     /// when the current token is an opening delimeter),
1143     /// you must also consume the corresponding closing delimiter.
1144     ///
1145     /// That is, you can consume
1146     /// `something ([{ }])` or `([{}])`, but not `([{}]`
1147     ///
1148     /// This restriction shouldn't be an issue in practice,
1149     /// since this function is used to record the tokens for
1150     /// a parsed AST item, which always has matching delimiters.
1151     pub fn collect_tokens<R>(
1152         &mut self,
1153         f: impl FnOnce(&mut Self) -> PResult<'a, R>,
1154     ) -> PResult<'a, (R, TokenStream)> {
1155         // Record all tokens we parse when parsing this item.
1156         let tokens: Vec<TreeAndJoint> = self.token_cursor.cur_token.clone().into_iter().collect();
1157         debug!("collect_tokens: starting with {:?}", tokens);
1158
1159         // We need special handling for the case where `collect_tokens` is called
1160         // on an opening delimeter (e.g. '('). At this point, we have already pushed
1161         // a new frame - however, we want to record the original `TokenTree::Delimited`,
1162         // for consistency with the case where we start recording one token earlier.
1163         // See `TokenCursor::next` to see how `cur_token` is set up.
1164         let prev_depth =
1165             if matches!(self.token_cursor.cur_token, Some((TokenTree::Delimited(..), _))) {
1166                 if self.token_cursor.stack.is_empty() {
1167                     // There is nothing below us in the stack that
1168                     // the function could consume, so the only thing it can legally
1169                     // capture is the entire contents of the current frame.
1170                     return Ok((f(self)?, TokenStream::new(tokens)));
1171                 }
1172                 // We have already recorded the full `TokenTree::Delimited` when we created
1173                 // our `tokens` vector at the start of this function. We are now inside
1174                 // a new frame corresponding to the `TokenTree::Delimited` we already recoreded.
1175                 // We don't want to record any of the tokens inside this frame, since they
1176                 // will be duplicates of the tokens nested inside the `TokenTree::Delimited`.
1177                 // Therefore, we set our recording depth to the *previous* frame. This allows
1178                 // us to record a sequence like: `(foo).bar()`: the `(foo)` will be recored
1179                 // as our initial `cur_token`, while the `.bar()` will be recored after we
1180                 // pop the `(foo)` frame.
1181                 self.token_cursor.stack.len() - 1
1182             } else {
1183                 self.token_cursor.stack.len()
1184             };
1185         let prev_collecting =
1186             self.token_cursor.collecting.replace(Collecting { buf: tokens, depth: prev_depth });
1187
1188         let ret = f(self);
1189
1190         let mut collected_tokens = if let Some(collecting) = self.token_cursor.collecting.take() {
1191             collecting.buf
1192         } else {
1193             let msg = "our vector went away?";
1194             debug!("collect_tokens: {}", msg);
1195             self.sess.span_diagnostic.delay_span_bug(self.token.span, &msg);
1196             // This can happen due to a bad interaction of two unrelated recovery mechanisms
1197             // with mismatched delimiters *and* recovery lookahead on the likely typo
1198             // `pub ident(` (#62895, different but similar to the case above).
1199             return Ok((ret?, TokenStream::default()));
1200         };
1201
1202         debug!("collect_tokens: got raw tokens {:?}", collected_tokens);
1203
1204         // If we're not at EOF our current token wasn't actually consumed by
1205         // `f`, but it'll still be in our list that we pulled out. In that case
1206         // put it back.
1207         let extra_token = if self.token != token::Eof { collected_tokens.pop() } else { None };
1208
1209         if let Some(mut collecting) = prev_collecting {
1210             // If we were previously collecting at the same depth,
1211             // then the previous call to `collect_tokens` needs to see
1212             // the tokens we just recorded.
1213             //
1214             // If we were previously recording at an lower `depth`,
1215             // then the previous `collect_tokens` call already recorded
1216             // this entire frame in the form of a `TokenTree::Delimited`,
1217             // so there is nothing else for us to do.
1218             if collecting.depth == prev_depth {
1219                 collecting.buf.extend(collected_tokens.iter().cloned());
1220                 collecting.buf.extend(extra_token);
1221                 debug!("collect_tokens: updating previous buf to {:?}", collecting);
1222             }
1223             self.token_cursor.collecting = Some(collecting)
1224         }
1225
1226         Ok((ret?, TokenStream::new(collected_tokens)))
1227     }
1228
1229     /// `::{` or `::*`
1230     fn is_import_coupler(&mut self) -> bool {
1231         self.check(&token::ModSep)
1232             && self.look_ahead(1, |t| {
1233                 *t == token::OpenDelim(token::Brace) || *t == token::BinOp(token::Star)
1234             })
1235     }
1236 }
1237
1238 crate fn make_unclosed_delims_error(
1239     unmatched: UnmatchedBrace,
1240     sess: &ParseSess,
1241 ) -> Option<DiagnosticBuilder<'_>> {
1242     // `None` here means an `Eof` was found. We already emit those errors elsewhere, we add them to
1243     // `unmatched_braces` only for error recovery in the `Parser`.
1244     let found_delim = unmatched.found_delim?;
1245     let mut err = sess.span_diagnostic.struct_span_err(
1246         unmatched.found_span,
1247         &format!(
1248             "mismatched closing delimiter: `{}`",
1249             pprust::token_kind_to_string(&token::CloseDelim(found_delim)),
1250         ),
1251     );
1252     err.span_label(unmatched.found_span, "mismatched closing delimiter");
1253     if let Some(sp) = unmatched.candidate_span {
1254         err.span_label(sp, "closing delimiter possibly meant for this");
1255     }
1256     if let Some(sp) = unmatched.unclosed_span {
1257         err.span_label(sp, "unclosed delimiter");
1258     }
1259     Some(err)
1260 }
1261
1262 pub fn emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedBrace>, sess: &ParseSess) {
1263     *sess.reached_eof.borrow_mut() |=
1264         unclosed_delims.iter().any(|unmatched_delim| unmatched_delim.found_delim.is_none());
1265     for unmatched in unclosed_delims.drain(..) {
1266         if let Some(mut e) = make_unclosed_delims_error(unmatched, sess) {
1267             e.emit();
1268         }
1269     }
1270 }