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