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