]> git.proxmox.com Git - rustc.git/blob - compiler/rustc_parse/src/parser/mod.rs
New upstream version 1.49.0~beta.4+dfsg1
[rustc.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 Ok(self.mk_expr(span, ExprKind::ConstBlock(anon_const), AttrVec::new()))
877 }
878
879 /// Parses mutability (`mut` or nothing).
880 fn parse_mutability(&mut self) -> Mutability {
881 if self.eat_keyword(kw::Mut) { Mutability::Mut } else { Mutability::Not }
882 }
883
884 /// Possibly parses mutability (`const` or `mut`).
885 fn parse_const_or_mut(&mut self) -> Option<Mutability> {
886 if self.eat_keyword(kw::Mut) {
887 Some(Mutability::Mut)
888 } else if self.eat_keyword(kw::Const) {
889 Some(Mutability::Not)
890 } else {
891 None
892 }
893 }
894
895 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
896 if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) = self.token.kind
897 {
898 self.expect_no_suffix(self.token.span, "a tuple index", suffix);
899 self.bump();
900 Ok(Ident::new(symbol, self.prev_token.span))
901 } else {
902 self.parse_ident_common(false)
903 }
904 }
905
906 fn parse_mac_args(&mut self) -> PResult<'a, P<MacArgs>> {
907 self.parse_mac_args_common(true).map(P)
908 }
909
910 fn parse_attr_args(&mut self) -> PResult<'a, MacArgs> {
911 self.parse_mac_args_common(false)
912 }
913
914 fn parse_mac_args_common(&mut self, delimited_only: bool) -> PResult<'a, MacArgs> {
915 Ok(
916 if self.check(&token::OpenDelim(DelimToken::Paren))
917 || self.check(&token::OpenDelim(DelimToken::Bracket))
918 || self.check(&token::OpenDelim(DelimToken::Brace))
919 {
920 match self.parse_token_tree() {
921 TokenTree::Delimited(dspan, delim, tokens) =>
922 // We've confirmed above that there is a delimiter so unwrapping is OK.
923 {
924 MacArgs::Delimited(dspan, MacDelimiter::from_token(delim).unwrap(), tokens)
925 }
926 _ => unreachable!(),
927 }
928 } else if !delimited_only {
929 if self.eat(&token::Eq) {
930 let eq_span = self.prev_token.span;
931 let mut is_interpolated_expr = false;
932 if let token::Interpolated(nt) = &self.token.kind {
933 if let token::NtExpr(..) = **nt {
934 is_interpolated_expr = true;
935 }
936 }
937 let token_tree = if is_interpolated_expr {
938 // We need to accept arbitrary interpolated expressions to continue
939 // supporting things like `doc = $expr` that work on stable.
940 // Non-literal interpolated expressions are rejected after expansion.
941 self.parse_token_tree()
942 } else {
943 self.parse_unsuffixed_lit()?.token_tree()
944 };
945
946 MacArgs::Eq(eq_span, token_tree.into())
947 } else {
948 MacArgs::Empty
949 }
950 } else {
951 return self.unexpected();
952 },
953 )
954 }
955
956 fn parse_or_use_outer_attributes(
957 &mut self,
958 already_parsed_attrs: Option<AttrVec>,
959 ) -> PResult<'a, AttrVec> {
960 if let Some(attrs) = already_parsed_attrs {
961 Ok(attrs)
962 } else {
963 self.parse_outer_attributes().map(|a| a.into())
964 }
965 }
966
967 /// Parses a single token tree from the input.
968 pub(crate) fn parse_token_tree(&mut self) -> TokenTree {
969 match self.token.kind {
970 token::OpenDelim(..) => {
971 let depth = self.token_cursor.stack.len();
972
973 // We keep advancing the token cursor until we hit
974 // the matching `CloseDelim` token.
975 while !(depth == self.token_cursor.stack.len()
976 && matches!(self.token.kind, token::CloseDelim(_)))
977 {
978 // Advance one token at a time, so `TokenCursor::next()`
979 // can capture these tokens if necessary.
980 self.bump();
981 }
982 // We are still inside the frame corresponding
983 // to the delimited stream we captured, so grab
984 // the tokens from this frame.
985 let frame = &self.token_cursor.frame;
986 let stream = frame.tree_cursor.stream.clone();
987 let span = frame.span;
988 let delim = frame.delim;
989 // Consume close delimiter
990 self.bump();
991 TokenTree::Delimited(span, delim, stream)
992 }
993 token::CloseDelim(_) | token::Eof => unreachable!(),
994 _ => {
995 self.bump();
996 TokenTree::Token(self.prev_token.clone())
997 }
998 }
999 }
1000
1001 /// Parses a stream of tokens into a list of `TokenTree`s, up to EOF.
1002 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
1003 let mut tts = Vec::new();
1004 while self.token != token::Eof {
1005 tts.push(self.parse_token_tree());
1006 }
1007 Ok(tts)
1008 }
1009
1010 pub fn parse_tokens(&mut self) -> TokenStream {
1011 let mut result = Vec::new();
1012 loop {
1013 match self.token.kind {
1014 token::Eof | token::CloseDelim(..) => break,
1015 _ => result.push(self.parse_token_tree().into()),
1016 }
1017 }
1018 TokenStream::new(result)
1019 }
1020
1021 /// Evaluates the closure with restrictions in place.
1022 ///
1023 /// Afters the closure is evaluated, restrictions are reset.
1024 fn with_res<T>(&mut self, res: Restrictions, f: impl FnOnce(&mut Self) -> T) -> T {
1025 let old = self.restrictions;
1026 self.restrictions = res;
1027 let res = f(self);
1028 self.restrictions = old;
1029 res
1030 }
1031
1032 fn is_crate_vis(&self) -> bool {
1033 self.token.is_keyword(kw::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
1034 }
1035
1036 /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`,
1037 /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`.
1038 /// If the following element can't be a tuple (i.e., it's a function definition), then
1039 /// it's not a tuple struct field), and the contents within the parentheses isn't valid,
1040 /// so emit a proper diagnostic.
1041 // Public for rustfmt usage.
1042 pub fn parse_visibility(&mut self, fbt: FollowedByType) -> PResult<'a, Visibility> {
1043 maybe_whole!(self, NtVis, |x| x);
1044
1045 self.expected_tokens.push(TokenType::Keyword(kw::Crate));
1046 if self.is_crate_vis() {
1047 self.bump(); // `crate`
1048 self.sess.gated_spans.gate(sym::crate_visibility_modifier, self.prev_token.span);
1049 return Ok(Visibility {
1050 span: self.prev_token.span,
1051 kind: VisibilityKind::Crate(CrateSugar::JustCrate),
1052 tokens: None,
1053 });
1054 }
1055
1056 if !self.eat_keyword(kw::Pub) {
1057 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
1058 // keyword to grab a span from for inherited visibility; an empty span at the
1059 // beginning of the current token would seem to be the "Schelling span".
1060 return Ok(Visibility {
1061 span: self.token.span.shrink_to_lo(),
1062 kind: VisibilityKind::Inherited,
1063 tokens: None,
1064 });
1065 }
1066 let lo = self.prev_token.span;
1067
1068 if self.check(&token::OpenDelim(token::Paren)) {
1069 // We don't `self.bump()` the `(` yet because this might be a struct definition where
1070 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
1071 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
1072 // by the following tokens.
1073 if self.is_keyword_ahead(1, &[kw::Crate]) && self.look_ahead(2, |t| t != &token::ModSep)
1074 // account for `pub(crate::foo)`
1075 {
1076 // Parse `pub(crate)`.
1077 self.bump(); // `(`
1078 self.bump(); // `crate`
1079 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1080 let vis = VisibilityKind::Crate(CrateSugar::PubCrate);
1081 return Ok(Visibility {
1082 span: lo.to(self.prev_token.span),
1083 kind: vis,
1084 tokens: None,
1085 });
1086 } else if self.is_keyword_ahead(1, &[kw::In]) {
1087 // Parse `pub(in path)`.
1088 self.bump(); // `(`
1089 self.bump(); // `in`
1090 let path = self.parse_path(PathStyle::Mod)?; // `path`
1091 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1092 let vis = VisibilityKind::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
1093 return Ok(Visibility {
1094 span: lo.to(self.prev_token.span),
1095 kind: vis,
1096 tokens: None,
1097 });
1098 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren))
1099 && self.is_keyword_ahead(1, &[kw::Super, kw::SelfLower])
1100 {
1101 // Parse `pub(self)` or `pub(super)`.
1102 self.bump(); // `(`
1103 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
1104 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1105 let vis = VisibilityKind::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
1106 return Ok(Visibility {
1107 span: lo.to(self.prev_token.span),
1108 kind: vis,
1109 tokens: None,
1110 });
1111 } else if let FollowedByType::No = fbt {
1112 // Provide this diagnostic if a type cannot follow;
1113 // in particular, if this is not a tuple struct.
1114 self.recover_incorrect_vis_restriction()?;
1115 // Emit diagnostic, but continue with public visibility.
1116 }
1117 }
1118
1119 Ok(Visibility { span: lo, kind: VisibilityKind::Public, tokens: None })
1120 }
1121
1122 /// Recovery for e.g. `pub(something) fn ...` or `struct X { pub(something) y: Z }`
1123 fn recover_incorrect_vis_restriction(&mut self) -> PResult<'a, ()> {
1124 self.bump(); // `(`
1125 let path = self.parse_path(PathStyle::Mod)?;
1126 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1127
1128 let msg = "incorrect visibility restriction";
1129 let suggestion = r##"some possible visibility restrictions are:
1130 `pub(crate)`: visible only on the current crate
1131 `pub(super)`: visible only in the current module's parent
1132 `pub(in path::to::module)`: visible only on the specified path"##;
1133
1134 let path_str = pprust::path_to_string(&path);
1135
1136 struct_span_err!(self.sess.span_diagnostic, path.span, E0704, "{}", msg)
1137 .help(suggestion)
1138 .span_suggestion(
1139 path.span,
1140 &format!("make this visible only to module `{}` with `in`", path_str),
1141 format!("in {}", path_str),
1142 Applicability::MachineApplicable,
1143 )
1144 .emit();
1145
1146 Ok(())
1147 }
1148
1149 /// Parses `extern string_literal?`.
1150 fn parse_extern(&mut self) -> PResult<'a, Extern> {
1151 Ok(if self.eat_keyword(kw::Extern) {
1152 Extern::from_abi(self.parse_abi())
1153 } else {
1154 Extern::None
1155 })
1156 }
1157
1158 /// Parses a string literal as an ABI spec.
1159 fn parse_abi(&mut self) -> Option<StrLit> {
1160 match self.parse_str_lit() {
1161 Ok(str_lit) => Some(str_lit),
1162 Err(Some(lit)) => match lit.kind {
1163 ast::LitKind::Err(_) => None,
1164 _ => {
1165 self.struct_span_err(lit.span, "non-string ABI literal")
1166 .span_suggestion(
1167 lit.span,
1168 "specify the ABI with a string literal",
1169 "\"C\"".to_string(),
1170 Applicability::MaybeIncorrect,
1171 )
1172 .emit();
1173 None
1174 }
1175 },
1176 Err(None) => None,
1177 }
1178 }
1179
1180 /// Records all tokens consumed by the provided callback,
1181 /// including the current token. These tokens are collected
1182 /// into a `LazyTokenStream`, and returned along with the result
1183 /// of the callback. The returned `LazyTokenStream` will be `None`
1184 /// if not tokens were captured.
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 // We didn't capture any tokens
1207 let num_calls = self.token_cursor.num_next_calls - cursor_snapshot.num_next_calls;
1208 if num_calls == 0 {
1209 return Ok((ret, None));
1210 }
1211
1212 // Produces a `TokenStream` on-demand. Using `cursor_snapshot`
1213 // and `num_calls`, we can reconstruct the `TokenStream` seen
1214 // by the callback. This allows us to avoid producing a `TokenStream`
1215 // if it is never needed - for example, a captured `macro_rules!`
1216 // argument that is never passed to a proc macro.
1217 //
1218 // This also makes `Parser` very cheap to clone, since
1219 // there is no intermediate collection buffer to clone.
1220 struct LazyTokenStreamImpl {
1221 start_token: (Token, Spacing),
1222 cursor_snapshot: TokenCursor,
1223 num_calls: usize,
1224 desugar_doc_comments: bool,
1225 }
1226 impl CreateTokenStream for LazyTokenStreamImpl {
1227 fn create_token_stream(&self) -> TokenStream {
1228 // The token produced by the final call to `next` or `next_desugared`
1229 // was not actually consumed by the callback. The combination
1230 // of chaining the initial token and using `take` produces the desired
1231 // result - we produce an empty `TokenStream` if no calls were made,
1232 // and omit the final token otherwise.
1233 let mut cursor_snapshot = self.cursor_snapshot.clone();
1234 let tokens = std::iter::once(self.start_token.clone())
1235 .chain((0..self.num_calls).map(|_| {
1236 if self.desugar_doc_comments {
1237 cursor_snapshot.next_desugared()
1238 } else {
1239 cursor_snapshot.next()
1240 }
1241 }))
1242 .take(self.num_calls);
1243
1244 make_token_stream(tokens)
1245 }
1246 }
1247
1248 let lazy_impl = LazyTokenStreamImpl {
1249 start_token,
1250 cursor_snapshot,
1251 num_calls,
1252 desugar_doc_comments: self.desugar_doc_comments,
1253 };
1254 Ok((ret, Some(LazyTokenStream::new(lazy_impl))))
1255 }
1256
1257 /// `::{` or `::*`
1258 fn is_import_coupler(&mut self) -> bool {
1259 self.check(&token::ModSep)
1260 && self.look_ahead(1, |t| {
1261 *t == token::OpenDelim(token::Brace) || *t == token::BinOp(token::Star)
1262 })
1263 }
1264
1265 pub fn clear_expected_tokens(&mut self) {
1266 self.expected_tokens.clear();
1267 }
1268 }
1269
1270 crate fn make_unclosed_delims_error(
1271 unmatched: UnmatchedBrace,
1272 sess: &ParseSess,
1273 ) -> Option<DiagnosticBuilder<'_>> {
1274 // `None` here means an `Eof` was found. We already emit those errors elsewhere, we add them to
1275 // `unmatched_braces` only for error recovery in the `Parser`.
1276 let found_delim = unmatched.found_delim?;
1277 let mut err = sess.span_diagnostic.struct_span_err(
1278 unmatched.found_span,
1279 &format!(
1280 "mismatched closing delimiter: `{}`",
1281 pprust::token_kind_to_string(&token::CloseDelim(found_delim)),
1282 ),
1283 );
1284 err.span_label(unmatched.found_span, "mismatched closing delimiter");
1285 if let Some(sp) = unmatched.candidate_span {
1286 err.span_label(sp, "closing delimiter possibly meant for this");
1287 }
1288 if let Some(sp) = unmatched.unclosed_span {
1289 err.span_label(sp, "unclosed delimiter");
1290 }
1291 Some(err)
1292 }
1293
1294 pub fn emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedBrace>, sess: &ParseSess) {
1295 *sess.reached_eof.borrow_mut() |=
1296 unclosed_delims.iter().any(|unmatched_delim| unmatched_delim.found_delim.is_none());
1297 for unmatched in unclosed_delims.drain(..) {
1298 if let Some(mut e) = make_unclosed_delims_error(unmatched, sess) {
1299 e.emit();
1300 }
1301 }
1302 }
1303
1304 /// Converts a flattened iterator of tokens (including open and close delimiter tokens)
1305 /// into a `TokenStream`, creating a `TokenTree::Delimited` for each matching pair
1306 /// of open and close delims.
1307 fn make_token_stream(tokens: impl Iterator<Item = (Token, Spacing)>) -> TokenStream {
1308 #[derive(Debug)]
1309 struct FrameData {
1310 open: Span,
1311 inner: Vec<(TokenTree, Spacing)>,
1312 }
1313 let mut stack = vec![FrameData { open: DUMMY_SP, inner: vec![] }];
1314 for (token, spacing) in tokens {
1315 match token {
1316 Token { kind: TokenKind::OpenDelim(_), span } => {
1317 stack.push(FrameData { open: span, inner: vec![] });
1318 }
1319 Token { kind: TokenKind::CloseDelim(delim), span } => {
1320 let frame_data = stack.pop().expect("Token stack was empty!");
1321 let dspan = DelimSpan::from_pair(frame_data.open, span);
1322 let stream = TokenStream::new(frame_data.inner);
1323 let delimited = TokenTree::Delimited(dspan, delim, stream);
1324 stack
1325 .last_mut()
1326 .unwrap_or_else(|| panic!("Bottom token frame is missing for tokens!"))
1327 .inner
1328 .push((delimited, Spacing::Alone));
1329 }
1330 token => stack
1331 .last_mut()
1332 .expect("Bottom token frame is missing!")
1333 .inner
1334 .push((TokenTree::Token(token), spacing)),
1335 }
1336 }
1337 let final_buf = stack.pop().expect("Missing final buf!");
1338 assert!(stack.is_empty(), "Stack should be empty: final_buf={:?} stack={:?}", final_buf, stack);
1339 TokenStream::new(final_buf.inner)
1340 }