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