]> git.lizzy.rs Git - rust.git/blob - src/librustc_parse/parser/mod.rs
parser: Set previous and unnormalized tokens in couple more places
[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     pub 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         // Make parser point to the first token.
408         parser.bump();
409
410         if let Some(directory) = directory {
411             parser.directory = directory;
412         } else if !parser.token.span.is_dummy() {
413             if let Some(FileName::Real(path)) =
414                 &sess.source_map().lookup_char_pos(parser.token.span.lo()).file.unmapped_path
415             {
416                 if let Some(directory_path) = path.parent() {
417                     parser.directory.path = directory_path.to_path_buf();
418                 }
419             }
420         }
421
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, fallback_span: Span) -> 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 = fallback_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     // Interpolated identifier (`$i: ident`) and lifetime (`$l: lifetime`)
900     // tokens are replaced with usual identifier and lifetime tokens,
901     // so the former are never encountered during normal parsing.
902     fn normalize_token(token: &Token) -> Option<Token> {
903         match &token.kind {
904             token::Interpolated(nt) => match **nt {
905                 token::NtIdent(ident, is_raw) => {
906                     Some(Token::new(token::Ident(ident.name, is_raw), ident.span))
907                 }
908                 token::NtLifetime(ident) => {
909                     Some(Token::new(token::Lifetime(ident.name), ident.span))
910                 }
911                 _ => None,
912             },
913             _ => None,
914         }
915     }
916
917     /// Advance the parser by one token.
918     pub fn bump(&mut self) {
919         if self.prev_token.kind == TokenKind::Eof {
920             // Bumping after EOF is a bad sign, usually an infinite loop.
921             let msg = "attempted to bump the parser past EOF (may be stuck in a loop)";
922             self.span_bug(self.token.span, msg);
923         }
924
925         // Update the current and previous tokens.
926         self.prev_token = self.token.take();
927         self.unnormalized_prev_token = self.unnormalized_token.take();
928         self.token = self.next_tok(self.unnormalized_prev_token().span);
929         if let Some(normalized_token) = Self::normalize_token(&self.token) {
930             self.unnormalized_token = Some(mem::replace(&mut self.token, normalized_token));
931         }
932
933         // Update fields derived from the previous token.
934         self.prev_span = self.unnormalized_prev_token().span;
935
936         self.expected_tokens.clear();
937     }
938
939     /// Advances the parser using provided token as a next one. Use this when
940     /// consuming a part of a token. For example a single `<` from `<<`.
941     /// FIXME: this function sets the previous token data to some semi-nonsensical values
942     /// which kind of work because they are currently used in very limited ways in practice.
943     /// Correct token kinds and spans need to be calculated instead.
944     fn bump_with(&mut self, next: TokenKind, span: Span) {
945         // Update the current and previous tokens.
946         self.prev_token = self.token.take();
947         self.unnormalized_prev_token = self.unnormalized_token.take();
948         self.token = Token::new(next, span);
949         if let Some(normalized_token) = Self::normalize_token(&self.token) {
950             self.unnormalized_token = Some(mem::replace(&mut self.token, normalized_token));
951         }
952
953         // Update fields derived from the previous token.
954         self.prev_span = self.unnormalized_prev_token().span.with_hi(span.lo());
955
956         self.expected_tokens.clear();
957     }
958
959     /// Look-ahead `dist` tokens of `self.token` and get access to that token there.
960     /// When `dist == 0` then the current token is looked at.
961     pub fn look_ahead<R>(&self, dist: usize, looker: impl FnOnce(&Token) -> R) -> R {
962         if dist == 0 {
963             return looker(&self.token);
964         }
965
966         let frame = &self.token_cursor.frame;
967         looker(&match frame.tree_cursor.look_ahead(dist - 1) {
968             Some(tree) => match tree {
969                 TokenTree::Token(token) => token,
970                 TokenTree::Delimited(dspan, delim, _) => {
971                     Token::new(token::OpenDelim(delim), dspan.open)
972                 }
973             },
974             None => Token::new(token::CloseDelim(frame.delim), frame.span.close),
975         })
976     }
977
978     /// Returns whether any of the given keywords are `dist` tokens ahead of the current one.
979     fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool {
980         self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw)))
981     }
982
983     /// Parses asyncness: `async` or nothing.
984     fn parse_asyncness(&mut self) -> Async {
985         if self.eat_keyword(kw::Async) {
986             let span = self.prev_span;
987             Async::Yes { span, closure_id: DUMMY_NODE_ID, return_impl_trait_id: DUMMY_NODE_ID }
988         } else {
989             Async::No
990         }
991     }
992
993     /// Parses unsafety: `unsafe` or nothing.
994     fn parse_unsafety(&mut self) -> Unsafe {
995         if self.eat_keyword(kw::Unsafe) { Unsafe::Yes(self.prev_span) } else { Unsafe::No }
996     }
997
998     /// Parses constness: `const` or nothing.
999     fn parse_constness(&mut self) -> Const {
1000         if self.eat_keyword(kw::Const) { Const::Yes(self.prev_span) } else { Const::No }
1001     }
1002
1003     /// Parses mutability (`mut` or nothing).
1004     fn parse_mutability(&mut self) -> Mutability {
1005         if self.eat_keyword(kw::Mut) { Mutability::Mut } else { Mutability::Not }
1006     }
1007
1008     /// Possibly parses mutability (`const` or `mut`).
1009     fn parse_const_or_mut(&mut self) -> Option<Mutability> {
1010         if self.eat_keyword(kw::Mut) {
1011             Some(Mutability::Mut)
1012         } else if self.eat_keyword(kw::Const) {
1013             Some(Mutability::Not)
1014         } else {
1015             None
1016         }
1017     }
1018
1019     fn parse_field_name(&mut self) -> PResult<'a, Ident> {
1020         if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) = self.token.kind
1021         {
1022             self.expect_no_suffix(self.token.span, "a tuple index", suffix);
1023             self.bump();
1024             Ok(Ident::new(symbol, self.prev_span))
1025         } else {
1026             self.parse_ident_common(false)
1027         }
1028     }
1029
1030     fn parse_mac_args(&mut self) -> PResult<'a, P<MacArgs>> {
1031         self.parse_mac_args_common(true).map(P)
1032     }
1033
1034     fn parse_attr_args(&mut self) -> PResult<'a, MacArgs> {
1035         self.parse_mac_args_common(false)
1036     }
1037
1038     fn parse_mac_args_common(&mut self, delimited_only: bool) -> PResult<'a, MacArgs> {
1039         Ok(
1040             if self.check(&token::OpenDelim(DelimToken::Paren))
1041                 || self.check(&token::OpenDelim(DelimToken::Bracket))
1042                 || self.check(&token::OpenDelim(DelimToken::Brace))
1043             {
1044                 match self.parse_token_tree() {
1045                     TokenTree::Delimited(dspan, delim, tokens) =>
1046                     // We've confirmed above that there is a delimiter so unwrapping is OK.
1047                     {
1048                         MacArgs::Delimited(dspan, MacDelimiter::from_token(delim).unwrap(), tokens)
1049                     }
1050                     _ => unreachable!(),
1051                 }
1052             } else if !delimited_only {
1053                 if self.eat(&token::Eq) {
1054                     let eq_span = self.prev_span;
1055                     let mut is_interpolated_expr = false;
1056                     if let token::Interpolated(nt) = &self.token.kind {
1057                         if let token::NtExpr(..) = **nt {
1058                             is_interpolated_expr = true;
1059                         }
1060                     }
1061                     let token_tree = if is_interpolated_expr {
1062                         // We need to accept arbitrary interpolated expressions to continue
1063                         // supporting things like `doc = $expr` that work on stable.
1064                         // Non-literal interpolated expressions are rejected after expansion.
1065                         self.parse_token_tree()
1066                     } else {
1067                         self.parse_unsuffixed_lit()?.token_tree()
1068                     };
1069
1070                     MacArgs::Eq(eq_span, token_tree.into())
1071                 } else {
1072                     MacArgs::Empty
1073                 }
1074             } else {
1075                 return self.unexpected();
1076             },
1077         )
1078     }
1079
1080     fn parse_or_use_outer_attributes(
1081         &mut self,
1082         already_parsed_attrs: Option<AttrVec>,
1083     ) -> PResult<'a, AttrVec> {
1084         if let Some(attrs) = already_parsed_attrs {
1085             Ok(attrs)
1086         } else {
1087             self.parse_outer_attributes().map(|a| a.into())
1088         }
1089     }
1090
1091     /// Parses a single token tree from the input.
1092     pub fn parse_token_tree(&mut self) -> TokenTree {
1093         match self.token.kind {
1094             token::OpenDelim(..) => {
1095                 let frame = mem::replace(
1096                     &mut self.token_cursor.frame,
1097                     self.token_cursor.stack.pop().unwrap(),
1098                 );
1099                 self.token = Token::new(TokenKind::CloseDelim(frame.delim), frame.span.close);
1100                 self.unnormalized_token = None;
1101                 self.bump();
1102                 TokenTree::Delimited(frame.span, frame.delim, frame.tree_cursor.stream.into())
1103             }
1104             token::CloseDelim(_) | token::Eof => unreachable!(),
1105             _ => {
1106                 self.bump();
1107                 TokenTree::Token(self.prev_token.clone())
1108             }
1109         }
1110     }
1111
1112     /// Parses a stream of tokens into a list of `TokenTree`s, up to EOF.
1113     pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
1114         let mut tts = Vec::new();
1115         while self.token != token::Eof {
1116             tts.push(self.parse_token_tree());
1117         }
1118         Ok(tts)
1119     }
1120
1121     pub fn parse_tokens(&mut self) -> TokenStream {
1122         let mut result = Vec::new();
1123         loop {
1124             match self.token.kind {
1125                 token::Eof | token::CloseDelim(..) => break,
1126                 _ => result.push(self.parse_token_tree().into()),
1127             }
1128         }
1129         TokenStream::new(result)
1130     }
1131
1132     /// Evaluates the closure with restrictions in place.
1133     ///
1134     /// Afters the closure is evaluated, restrictions are reset.
1135     fn with_res<T>(&mut self, res: Restrictions, f: impl FnOnce(&mut Self) -> T) -> T {
1136         let old = self.restrictions;
1137         self.restrictions = res;
1138         let res = f(self);
1139         self.restrictions = old;
1140         res
1141     }
1142
1143     fn is_crate_vis(&self) -> bool {
1144         self.token.is_keyword(kw::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
1145     }
1146
1147     /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`,
1148     /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`.
1149     /// If the following element can't be a tuple (i.e., it's a function definition), then
1150     /// it's not a tuple struct field), and the contents within the parentheses isn't valid,
1151     /// so emit a proper diagnostic.
1152     pub fn parse_visibility(&mut self, fbt: FollowedByType) -> PResult<'a, Visibility> {
1153         maybe_whole!(self, NtVis, |x| x);
1154
1155         self.expected_tokens.push(TokenType::Keyword(kw::Crate));
1156         if self.is_crate_vis() {
1157             self.bump(); // `crate`
1158             self.sess.gated_spans.gate(sym::crate_visibility_modifier, self.prev_span);
1159             return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate)));
1160         }
1161
1162         if !self.eat_keyword(kw::Pub) {
1163             // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
1164             // keyword to grab a span from for inherited visibility; an empty span at the
1165             // beginning of the current token would seem to be the "Schelling span".
1166             return Ok(respan(self.token.span.shrink_to_lo(), VisibilityKind::Inherited));
1167         }
1168         let lo = self.prev_span;
1169
1170         if self.check(&token::OpenDelim(token::Paren)) {
1171             // We don't `self.bump()` the `(` yet because this might be a struct definition where
1172             // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
1173             // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
1174             // by the following tokens.
1175             if self.is_keyword_ahead(1, &[kw::Crate]) && self.look_ahead(2, |t| t != &token::ModSep)
1176             // account for `pub(crate::foo)`
1177             {
1178                 // Parse `pub(crate)`.
1179                 self.bump(); // `(`
1180                 self.bump(); // `crate`
1181                 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1182                 let vis = VisibilityKind::Crate(CrateSugar::PubCrate);
1183                 return Ok(respan(lo.to(self.prev_span), vis));
1184             } else if self.is_keyword_ahead(1, &[kw::In]) {
1185                 // Parse `pub(in path)`.
1186                 self.bump(); // `(`
1187                 self.bump(); // `in`
1188                 let path = self.parse_path(PathStyle::Mod)?; // `path`
1189                 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1190                 let vis = VisibilityKind::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
1191                 return Ok(respan(lo.to(self.prev_span), vis));
1192             } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren))
1193                 && self.is_keyword_ahead(1, &[kw::Super, kw::SelfLower])
1194             {
1195                 // Parse `pub(self)` or `pub(super)`.
1196                 self.bump(); // `(`
1197                 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
1198                 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1199                 let vis = VisibilityKind::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
1200                 return Ok(respan(lo.to(self.prev_span), vis));
1201             } else if let FollowedByType::No = fbt {
1202                 // Provide this diagnostic if a type cannot follow;
1203                 // in particular, if this is not a tuple struct.
1204                 self.recover_incorrect_vis_restriction()?;
1205                 // Emit diagnostic, but continue with public visibility.
1206             }
1207         }
1208
1209         Ok(respan(lo, VisibilityKind::Public))
1210     }
1211
1212     /// Recovery for e.g. `pub(something) fn ...` or `struct X { pub(something) y: Z }`
1213     fn recover_incorrect_vis_restriction(&mut self) -> PResult<'a, ()> {
1214         self.bump(); // `(`
1215         let path = self.parse_path(PathStyle::Mod)?;
1216         self.expect(&token::CloseDelim(token::Paren))?; // `)`
1217
1218         let msg = "incorrect visibility restriction";
1219         let suggestion = r##"some possible visibility restrictions are:
1220 `pub(crate)`: visible only on the current crate
1221 `pub(super)`: visible only in the current module's parent
1222 `pub(in path::to::module)`: visible only on the specified path"##;
1223
1224         let path_str = pprust::path_to_string(&path);
1225
1226         struct_span_err!(self.sess.span_diagnostic, path.span, E0704, "{}", msg)
1227             .help(suggestion)
1228             .span_suggestion(
1229                 path.span,
1230                 &format!("make this visible only to module `{}` with `in`", path_str),
1231                 format!("in {}", path_str),
1232                 Applicability::MachineApplicable,
1233             )
1234             .emit();
1235
1236         Ok(())
1237     }
1238
1239     /// Parses `extern string_literal?`.
1240     fn parse_extern(&mut self) -> PResult<'a, Extern> {
1241         Ok(if self.eat_keyword(kw::Extern) {
1242             Extern::from_abi(self.parse_abi())
1243         } else {
1244             Extern::None
1245         })
1246     }
1247
1248     /// Parses a string literal as an ABI spec.
1249     fn parse_abi(&mut self) -> Option<StrLit> {
1250         match self.parse_str_lit() {
1251             Ok(str_lit) => Some(str_lit),
1252             Err(Some(lit)) => match lit.kind {
1253                 ast::LitKind::Err(_) => None,
1254                 _ => {
1255                     self.struct_span_err(lit.span, "non-string ABI literal")
1256                         .span_suggestion(
1257                             lit.span,
1258                             "specify the ABI with a string literal",
1259                             "\"C\"".to_string(),
1260                             Applicability::MaybeIncorrect,
1261                         )
1262                         .emit();
1263                     None
1264                 }
1265             },
1266             Err(None) => None,
1267         }
1268     }
1269
1270     fn collect_tokens<R>(
1271         &mut self,
1272         f: impl FnOnce(&mut Self) -> PResult<'a, R>,
1273     ) -> PResult<'a, (R, TokenStream)> {
1274         // Record all tokens we parse when parsing this item.
1275         let mut tokens = Vec::new();
1276         let prev_collecting = match self.token_cursor.frame.last_token {
1277             LastToken::Collecting(ref mut list) => Some(mem::take(list)),
1278             LastToken::Was(ref mut last) => {
1279                 tokens.extend(last.take());
1280                 None
1281             }
1282         };
1283         self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
1284         let prev = self.token_cursor.stack.len();
1285         let ret = f(self);
1286         let last_token = if self.token_cursor.stack.len() == prev {
1287             &mut self.token_cursor.frame.last_token
1288         } else if self.token_cursor.stack.get(prev).is_none() {
1289             // This can happen due to a bad interaction of two unrelated recovery mechanisms with
1290             // mismatched delimiters *and* recovery lookahead on the likely typo `pub ident(`
1291             // (#62881).
1292             return Ok((ret?, TokenStream::default()));
1293         } else {
1294             &mut self.token_cursor.stack[prev].last_token
1295         };
1296
1297         // Pull out the tokens that we've collected from the call to `f` above.
1298         let mut collected_tokens = match *last_token {
1299             LastToken::Collecting(ref mut v) => mem::take(v),
1300             LastToken::Was(ref was) => {
1301                 let msg = format!("our vector went away? - found Was({:?})", was);
1302                 debug!("collect_tokens: {}", msg);
1303                 self.sess.span_diagnostic.delay_span_bug(self.token.span, &msg);
1304                 // This can happen due to a bad interaction of two unrelated recovery mechanisms
1305                 // with mismatched delimiters *and* recovery lookahead on the likely typo
1306                 // `pub ident(` (#62895, different but similar to the case above).
1307                 return Ok((ret?, TokenStream::default()));
1308             }
1309         };
1310
1311         // If we're not at EOF our current token wasn't actually consumed by
1312         // `f`, but it'll still be in our list that we pulled out. In that case
1313         // put it back.
1314         let extra_token = if self.token != token::Eof { collected_tokens.pop() } else { None };
1315
1316         // If we were previously collecting tokens, then this was a recursive
1317         // call. In that case we need to record all the tokens we collected in
1318         // our parent list as well. To do that we push a clone of our stream
1319         // onto the previous list.
1320         match prev_collecting {
1321             Some(mut list) => {
1322                 list.extend(collected_tokens.iter().cloned());
1323                 list.extend(extra_token);
1324                 *last_token = LastToken::Collecting(list);
1325             }
1326             None => {
1327                 *last_token = LastToken::Was(extra_token);
1328             }
1329         }
1330
1331         Ok((ret?, TokenStream::new(collected_tokens)))
1332     }
1333
1334     /// `::{` or `::*`
1335     fn is_import_coupler(&mut self) -> bool {
1336         self.check(&token::ModSep)
1337             && self.look_ahead(1, |t| {
1338                 *t == token::OpenDelim(token::Brace) || *t == token::BinOp(token::Star)
1339             })
1340     }
1341 }
1342
1343 crate fn make_unclosed_delims_error(
1344     unmatched: UnmatchedBrace,
1345     sess: &ParseSess,
1346 ) -> Option<DiagnosticBuilder<'_>> {
1347     // `None` here means an `Eof` was found. We already emit those errors elsewhere, we add them to
1348     // `unmatched_braces` only for error recovery in the `Parser`.
1349     let found_delim = unmatched.found_delim?;
1350     let mut err = sess.span_diagnostic.struct_span_err(
1351         unmatched.found_span,
1352         &format!(
1353             "mismatched closing delimiter: `{}`",
1354             pprust::token_kind_to_string(&token::CloseDelim(found_delim)),
1355         ),
1356     );
1357     err.span_label(unmatched.found_span, "mismatched closing delimiter");
1358     if let Some(sp) = unmatched.candidate_span {
1359         err.span_label(sp, "closing delimiter possibly meant for this");
1360     }
1361     if let Some(sp) = unmatched.unclosed_span {
1362         err.span_label(sp, "unclosed delimiter");
1363     }
1364     Some(err)
1365 }
1366
1367 pub fn emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedBrace>, sess: &ParseSess) {
1368     *sess.reached_eof.borrow_mut() |=
1369         unclosed_delims.iter().any(|unmatched_delim| unmatched_delim.found_delim.is_none());
1370     for unmatched in unclosed_delims.drain(..) {
1371         make_unclosed_delims_error(unmatched, sess).map(|mut e| {
1372             e.emit();
1373         });
1374     }
1375 }