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