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