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