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