12 use crate::lexer::UnmatchedBrace;
13 pub use diagnostics::AttemptLocalParseRecovery;
14 use diagnostics::Error;
15 pub use path::PathStyle;
17 use rustc_ast::ptr::P;
18 use rustc_ast::token::{self, DelimToken, Token, TokenKind};
19 use rustc_ast::tokenstream::{self, DelimSpan, LazyTokenStream, Spacing};
20 use rustc_ast::tokenstream::{CreateTokenStream, TokenStream, TokenTree, TreeAndSpacing};
21 use rustc_ast::DUMMY_NODE_ID;
22 use rustc_ast::{self as ast, AnonConst, AttrStyle, AttrVec, Const, CrateSugar, Extern, Unsafe};
23 use rustc_ast::{Async, Expr, ExprKind, MacArgs, MacDelimiter, Mutability, StrLit};
24 use rustc_ast::{Visibility, VisibilityKind};
25 use rustc_ast_pretty::pprust;
26 use rustc_data_structures::sync::Lrc;
27 use rustc_errors::PResult;
28 use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder, FatalError};
29 use rustc_session::parse::ParseSess;
30 use rustc_span::source_map::{Span, DUMMY_SP};
31 use rustc_span::symbol::{kw, sym, Ident, Symbol};
34 use std::{cmp, mem, slice};
37 struct Restrictions: u8 {
38 const STMT_EXPR = 1 << 0;
39 const NO_STRUCT_LITERAL = 1 << 1;
40 const CONST_EXPR = 1 << 2;
44 #[derive(Clone, Copy, PartialEq, Debug)]
51 #[derive(Clone, Copy, PartialEq, Debug)]
57 /// Like `maybe_whole_expr`, but for things other than expressions.
59 macro_rules! maybe_whole {
60 ($p:expr, $constructor:ident, |$x:ident| $e:expr) => {
61 if let token::Interpolated(nt) = &$p.token.kind {
62 if let token::$constructor(x) = &**nt {
71 /// If the next tokens are ill-formed `$ty::` recover them as `<$ty>::`.
73 macro_rules! maybe_recover_from_interpolated_ty_qpath {
74 ($self: expr, $allow_qpath_recovery: expr) => {
75 if $allow_qpath_recovery && $self.look_ahead(1, |t| t == &token::ModSep) {
76 if let token::Interpolated(nt) = &$self.token.kind {
77 if let token::NtTy(ty) = &**nt {
80 return $self.maybe_recover_from_bad_qpath_stage_2($self.prev_token.span, ty);
88 pub struct Parser<'a> {
89 pub sess: &'a ParseSess,
90 /// The current token.
92 /// The spacing for the current token
93 pub token_spacing: Spacing,
94 /// The previous token.
95 pub prev_token: Token,
96 restrictions: Restrictions,
97 expected_tokens: Vec<TokenType>,
98 // Important: This must only be advanced from `next_tok`
99 // to ensure that `token_cursor.num_next_calls` is updated properly
100 token_cursor: TokenCursor,
101 desugar_doc_comments: bool,
102 /// This field is used to keep track of how many left angle brackets we have seen. This is
103 /// required in order to detect extra leading left angle brackets (`<` characters) and error
106 /// See the comments in the `parse_path_segment` function for more details.
107 unmatched_angle_bracket_count: u32,
108 max_angle_bracket_count: u32,
109 /// A list of all unclosed delimiters found by the lexer. If an entry is used for error recovery
110 /// it gets removed from here. Every entry left at the end gets emitted as an independent
112 pub(super) unclosed_delims: Vec<UnmatchedBrace>,
113 last_unexpected_token_span: Option<Span>,
114 /// Span pointing at the `:` for the last type ascription the parser has seen, and whether it
115 /// looked like it could have been a mistyped path or literal `Option:Some(42)`).
116 pub last_type_ascription: Option<(Span, bool /* likely path typo */)>,
117 /// If present, this `Parser` is not parsing Rust code but rather a macro call.
118 subparser_name: Option<&'static str>,
121 impl<'a> Drop for Parser<'a> {
123 emit_unclosed_delims(&mut self.unclosed_delims, &self.sess);
129 frame: TokenCursorFrame,
130 stack: Vec<TokenCursorFrame>,
131 desugar_doc_comments: bool,
132 // Counts the number of calls to `next` or `next_desugared`,
133 // depending on whether `desugar_doc_comments` is set.
134 num_next_calls: usize,
135 // During parsing, we may sometimes need to 'unglue' a
136 // glued token into two component tokens
137 // (e.g. '>>' into '>' and '>), so that the parser
138 // can consume them one at a time. This process
139 // bypasses the normal capturing mechanism
140 // (e.g. `num_next_calls` will not be incremented),
141 // since the 'unglued' tokens due not exist in
142 // the original `TokenStream`.
144 // If we end up consuming both unglued tokens,
145 // then this is not an issue - we'll end up
146 // capturing the single 'glued' token.
148 // However, in certain circumstances, we may
149 // want to capture just the first 'unglued' token.
150 // For example, capturing the `Vec<u8>`
151 // in `Option<Vec<u8>>` requires us to unglue
152 // the trailing `>>` token. The `append_unglued_token`
153 // field is used to track this token - it gets
154 // appended to the captured stream when
155 // we evaluate a `LazyTokenStream`
156 append_unglued_token: Option<TreeAndSpacing>,
160 struct TokenCursorFrame {
161 delim: token::DelimToken,
164 tree_cursor: tokenstream::Cursor,
168 impl TokenCursorFrame {
169 fn new(span: DelimSpan, delim: DelimToken, tts: TokenStream) -> Self {
173 open_delim: delim == token::NoDelim,
174 tree_cursor: tts.into_trees(),
175 close_delim: delim == token::NoDelim,
181 fn next(&mut self) -> (Token, Spacing) {
183 let (tree, spacing) = if !self.frame.open_delim {
184 self.frame.open_delim = true;
185 TokenTree::open_tt(self.frame.span, self.frame.delim).into()
186 } else if let Some(tree) = self.frame.tree_cursor.next_with_spacing() {
188 } else if !self.frame.close_delim {
189 self.frame.close_delim = true;
190 TokenTree::close_tt(self.frame.span, self.frame.delim).into()
191 } else if let Some(frame) = self.stack.pop() {
195 (TokenTree::Token(Token::new(token::Eof, DUMMY_SP)), Spacing::Alone)
199 TokenTree::Token(token) => {
200 return (token, spacing);
202 TokenTree::Delimited(sp, delim, tts) => {
203 let frame = TokenCursorFrame::new(sp, delim, tts);
204 self.stack.push(mem::replace(&mut self.frame, frame));
210 fn next_desugared(&mut self) -> (Token, Spacing) {
211 let (data, attr_style, sp) = match self.next() {
212 (Token { kind: token::DocComment(_, attr_style, data), span }, _) => {
213 (data, attr_style, span)
218 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
219 // required to wrap the text.
220 let mut num_of_hashes = 0;
222 for ch in data.as_str().chars() {
225 '#' if count > 0 => count + 1,
228 num_of_hashes = cmp::max(num_of_hashes, count);
231 let delim_span = DelimSpan::from_single(sp);
232 let body = TokenTree::Delimited(
236 TokenTree::token(token::Ident(sym::doc, false), sp),
237 TokenTree::token(token::Eq, sp),
238 TokenTree::token(TokenKind::lit(token::StrRaw(num_of_hashes), data, None), sp),
242 .collect::<TokenStream>(),
245 self.stack.push(mem::replace(
247 TokenCursorFrame::new(
250 if attr_style == AttrStyle::Inner {
251 [TokenTree::token(token::Pound, sp), TokenTree::token(token::Not, sp), body]
254 .collect::<TokenStream>()
256 [TokenTree::token(token::Pound, sp), body]
259 .collect::<TokenStream>()
268 #[derive(Clone, PartialEq)]
281 fn to_string(&self) -> String {
283 TokenType::Token(ref t) => format!("`{}`", pprust::token_kind_to_string(t)),
284 TokenType::Keyword(kw) => format!("`{}`", kw),
285 TokenType::Operator => "an operator".to_string(),
286 TokenType::Lifetime => "lifetime".to_string(),
287 TokenType::Ident => "identifier".to_string(),
288 TokenType::Path => "path".to_string(),
289 TokenType::Type => "type".to_string(),
290 TokenType::Const => "a const expression".to_string(),
295 #[derive(Copy, Clone, Debug)]
296 enum TokenExpectType {
301 /// A sequence separator.
303 /// The separator token.
304 sep: Option<TokenKind>,
305 /// `true` if a trailing separator is allowed.
306 trailing_sep_allowed: bool,
310 fn trailing_allowed(t: TokenKind) -> SeqSep {
311 SeqSep { sep: Some(t), trailing_sep_allowed: true }
314 fn none() -> SeqSep {
315 SeqSep { sep: None, trailing_sep_allowed: false }
319 pub enum FollowedByType {
324 fn token_descr_opt(token: &Token) -> Option<&'static str> {
325 Some(match token.kind {
326 _ if token.is_special_ident() => "reserved identifier",
327 _ if token.is_used_keyword() => "keyword",
328 _ if token.is_unused_keyword() => "reserved keyword",
329 token::DocComment(..) => "doc comment",
334 pub(super) fn token_descr(token: &Token) -> String {
335 let token_str = pprust::token_to_string(token);
336 match token_descr_opt(token) {
337 Some(prefix) => format!("{} `{}`", prefix, token_str),
338 _ => format!("`{}`", token_str),
342 impl<'a> Parser<'a> {
346 desugar_doc_comments: bool,
347 subparser_name: Option<&'static str>,
349 let mut parser = Parser {
351 token: Token::dummy(),
352 token_spacing: Spacing::Alone,
353 prev_token: Token::dummy(),
354 restrictions: Restrictions::empty(),
355 expected_tokens: Vec::new(),
356 token_cursor: TokenCursor {
357 frame: TokenCursorFrame::new(DelimSpan::dummy(), token::NoDelim, tokens),
360 desugar_doc_comments,
361 append_unglued_token: None,
363 desugar_doc_comments,
364 unmatched_angle_bracket_count: 0,
365 max_angle_bracket_count: 0,
366 unclosed_delims: Vec::new(),
367 last_unexpected_token_span: None,
368 last_type_ascription: None,
372 // Make parser point to the first token.
378 fn next_tok(&mut self, fallback_span: Span) -> (Token, Spacing) {
379 let (mut next, spacing) = if self.desugar_doc_comments {
380 self.token_cursor.next_desugared()
382 self.token_cursor.next()
384 self.token_cursor.num_next_calls += 1;
385 // We've retrieved an token from the underlying
386 // cursor, so we no longer need to worry about
387 // an unglued token. See `break_and_eat` for more details
388 self.token_cursor.append_unglued_token = None;
389 if next.span.is_dummy() {
390 // Tweak the location for better diagnostics, but keep syntactic context intact.
391 next.span = fallback_span.with_ctxt(next.span.ctxt());
396 pub fn unexpected<T>(&mut self) -> PResult<'a, T> {
397 match self.expect_one_of(&[], &[]) {
399 // We can get `Ok(true)` from `recover_closing_delimiter`
400 // which is called in `expected_one_of_not_found`.
401 Ok(_) => FatalError.raise(),
405 /// Expects and consumes the token `t`. Signals an error if the next token is not `t`.
406 pub fn expect(&mut self, t: &TokenKind) -> PResult<'a, bool /* recovered */> {
407 if self.expected_tokens.is_empty() {
408 if self.token == *t {
412 self.unexpected_try_recover(t)
415 self.expect_one_of(slice::from_ref(t), &[])
419 /// Expect next token to be edible or inedible token. If edible,
420 /// then consume it; if inedible, then return without consuming
421 /// anything. Signal a fatal error if next token is unexpected.
422 pub fn expect_one_of(
424 edible: &[TokenKind],
425 inedible: &[TokenKind],
426 ) -> PResult<'a, bool /* recovered */> {
427 if edible.contains(&self.token.kind) {
430 } else if inedible.contains(&self.token.kind) {
431 // leave it in the input
433 } else if self.last_unexpected_token_span == Some(self.token.span) {
436 self.expected_one_of_not_found(edible, inedible)
440 // Public for rustfmt usage.
441 pub fn parse_ident(&mut self) -> PResult<'a, Ident> {
442 self.parse_ident_common(true)
445 fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, Ident> {
446 match self.token.ident() {
447 Some((ident, is_raw)) => {
448 if !is_raw && ident.is_reserved() {
449 let mut err = self.expected_ident_found();
459 _ => Err(match self.prev_token.kind {
460 TokenKind::DocComment(..) => {
461 self.span_fatal_err(self.prev_token.span, Error::UselessDocComment)
463 _ => self.expected_ident_found(),
468 /// Checks if the next token is `tok`, and returns `true` if so.
470 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
472 fn check(&mut self, tok: &TokenKind) -> bool {
473 let is_present = self.token == *tok;
475 self.expected_tokens.push(TokenType::Token(tok.clone()));
480 /// Consumes a token 'tok' if it exists. Returns whether the given token was present.
481 pub fn eat(&mut self, tok: &TokenKind) -> bool {
482 let is_present = self.check(tok);
489 /// If the next token is the given keyword, returns `true` without eating it.
490 /// An expectation is also added for diagnostics purposes.
491 fn check_keyword(&mut self, kw: Symbol) -> bool {
492 self.expected_tokens.push(TokenType::Keyword(kw));
493 self.token.is_keyword(kw)
496 /// If the next token is the given keyword, eats it and returns `true`.
497 /// Otherwise, returns `false`. An expectation is also added for diagnostics purposes.
498 // Public for rustfmt usage.
499 pub fn eat_keyword(&mut self, kw: Symbol) -> bool {
500 if self.check_keyword(kw) {
508 fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool {
509 if self.token.is_keyword(kw) {
517 /// If the given word is not a keyword, signals an error.
518 /// If the next token is not the given word, signals an error.
519 /// Otherwise, eats it.
520 fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> {
521 if !self.eat_keyword(kw) { self.unexpected() } else { Ok(()) }
524 /// Is the given keyword `kw` followed by a non-reserved identifier?
525 fn is_kw_followed_by_ident(&self, kw: Symbol) -> bool {
526 self.token.is_keyword(kw) && self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
529 fn check_or_expected(&mut self, ok: bool, typ: TokenType) -> bool {
533 self.expected_tokens.push(typ);
538 fn check_ident(&mut self) -> bool {
539 self.check_or_expected(self.token.is_ident(), TokenType::Ident)
542 fn check_path(&mut self) -> bool {
543 self.check_or_expected(self.token.is_path_start(), TokenType::Path)
546 fn check_type(&mut self) -> bool {
547 self.check_or_expected(self.token.can_begin_type(), TokenType::Type)
550 fn check_const_arg(&mut self) -> bool {
551 self.check_or_expected(self.token.can_begin_const_arg(), TokenType::Const)
554 fn check_inline_const(&self, dist: usize) -> bool {
555 self.is_keyword_ahead(dist, &[kw::Const])
556 && self.look_ahead(dist + 1, |t| match t.kind {
557 token::Interpolated(ref nt) => matches!(**nt, token::NtBlock(..)),
558 token::OpenDelim(DelimToken::Brace) => true,
563 /// Checks to see if the next token is either `+` or `+=`.
564 /// Otherwise returns `false`.
565 fn check_plus(&mut self) -> bool {
566 self.check_or_expected(
567 self.token.is_like_plus(),
568 TokenType::Token(token::BinOp(token::Plus)),
572 /// Eats the expected token if it's present possibly breaking
573 /// compound tokens like multi-character operators in process.
574 /// Returns `true` if the token was eaten.
575 fn break_and_eat(&mut self, expected: TokenKind) -> bool {
576 if self.token.kind == expected {
580 match self.token.kind.break_two_token_op() {
581 Some((first, second)) if first == expected => {
582 let first_span = self.sess.source_map().start_point(self.token.span);
583 let second_span = self.token.span.with_lo(first_span.hi());
584 self.token = Token::new(first, first_span);
585 // Keep track of this token - if we end token capturing now,
586 // we'll want to append this token to the captured stream.
588 // If we consume any additional tokens, then this token
589 // is not needed (we'll capture the entire 'glued' token),
590 // and `next_tok` will set this field to `None`
591 self.token_cursor.append_unglued_token =
592 Some((TokenTree::Token(self.token.clone()), Spacing::Alone));
593 // Use the spacing of the glued token as the spacing
594 // of the unglued second token.
595 self.bump_with((Token::new(second, second_span), self.token_spacing));
599 self.expected_tokens.push(TokenType::Token(expected));
605 /// Eats `+` possibly breaking tokens like `+=` in process.
606 fn eat_plus(&mut self) -> bool {
607 self.break_and_eat(token::BinOp(token::Plus))
610 /// Eats `&` possibly breaking tokens like `&&` in process.
611 /// Signals an error if `&` is not eaten.
612 fn expect_and(&mut self) -> PResult<'a, ()> {
613 if self.break_and_eat(token::BinOp(token::And)) { Ok(()) } else { self.unexpected() }
616 /// Eats `|` possibly breaking tokens like `||` in process.
617 /// Signals an error if `|` was not eaten.
618 fn expect_or(&mut self) -> PResult<'a, ()> {
619 if self.break_and_eat(token::BinOp(token::Or)) { Ok(()) } else { self.unexpected() }
622 /// Eats `<` possibly breaking tokens like `<<` in process.
623 fn eat_lt(&mut self) -> bool {
624 let ate = self.break_and_eat(token::Lt);
626 // See doc comment for `unmatched_angle_bracket_count`.
627 self.unmatched_angle_bracket_count += 1;
628 self.max_angle_bracket_count += 1;
629 debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count);
634 /// Eats `<` possibly breaking tokens like `<<` in process.
635 /// Signals an error if `<` was not eaten.
636 fn expect_lt(&mut self) -> PResult<'a, ()> {
637 if self.eat_lt() { Ok(()) } else { self.unexpected() }
640 /// Eats `>` possibly breaking tokens like `>>` in process.
641 /// Signals an error if `>` was not eaten.
642 fn expect_gt(&mut self) -> PResult<'a, ()> {
643 if self.break_and_eat(token::Gt) {
644 // See doc comment for `unmatched_angle_bracket_count`.
645 if self.unmatched_angle_bracket_count > 0 {
646 self.unmatched_angle_bracket_count -= 1;
647 debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count);
655 fn expect_any_with_type(&mut self, kets: &[&TokenKind], expect: TokenExpectType) -> bool {
656 kets.iter().any(|k| match expect {
657 TokenExpectType::Expect => self.check(k),
658 TokenExpectType::NoExpect => self.token == **k,
662 fn parse_seq_to_before_tokens<T>(
666 expect: TokenExpectType,
667 mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
668 ) -> PResult<'a, (Vec<T>, bool /* trailing */, bool /* recovered */)> {
669 let mut first = true;
670 let mut recovered = false;
671 let mut trailing = false;
673 while !self.expect_any_with_type(kets, expect) {
674 if let token::CloseDelim(..) | token::Eof = self.token.kind {
677 if let Some(ref t) = sep.sep {
681 match self.expect(t) {
687 Err(mut expect_err) => {
688 let sp = self.prev_token.span.shrink_to_hi();
689 let token_str = pprust::token_kind_to_string(t);
691 // Attempt to keep parsing if it was a similar separator.
692 if let Some(ref tokens) = t.similar_tokens() {
693 if tokens.contains(&self.token.kind) {
698 // If this was a missing `@` in a binding pattern
699 // bail with a suggestion
700 // https://github.com/rust-lang/rust/issues/72373
701 if self.prev_token.is_ident() && self.token.kind == token::DotDot {
703 "if you meant to bind the contents of \
704 the rest of the array pattern into `{}`, use `@`",
705 pprust::token_to_string(&self.prev_token)
708 .span_suggestion_verbose(
709 self.prev_token.span.shrink_to_hi().until(self.token.span),
712 Applicability::MaybeIncorrect,
718 // Attempt to keep parsing if it was an omitted separator.
721 // Parsed successfully, therefore most probably the code only
722 // misses a separator.
723 let mut exp_span = self.sess.source_map().next_point(sp);
724 if self.sess.source_map().is_multiline(exp_span) {
728 .span_suggestion_short(
730 &format!("missing `{}`", token_str),
732 Applicability::MaybeIncorrect,
740 // Parsing failed, therefore it must be something more serious
741 // than just a missing separator.
752 if sep.trailing_sep_allowed && self.expect_any_with_type(kets, expect) {
761 Ok((v, trailing, recovered))
764 /// Parses a sequence, not including the closing delimiter. The function
765 /// `f` must consume tokens until reaching the next separator or
767 fn parse_seq_to_before_end<T>(
771 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
772 ) -> PResult<'a, (Vec<T>, bool, bool)> {
773 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
776 /// Parses a sequence, including the closing delimiter. The function
777 /// `f` must consume tokens until reaching the next separator or
779 fn parse_seq_to_end<T>(
783 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
784 ) -> PResult<'a, (Vec<T>, bool /* trailing */)> {
785 let (val, trailing, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
792 /// Parses a sequence, including the closing delimiter. The function
793 /// `f` must consume tokens until reaching the next separator or
795 fn parse_unspanned_seq<T>(
800 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
801 ) -> PResult<'a, (Vec<T>, bool)> {
803 self.parse_seq_to_end(ket, sep, f)
806 fn parse_delim_comma_seq<T>(
809 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
810 ) -> PResult<'a, (Vec<T>, bool)> {
811 self.parse_unspanned_seq(
812 &token::OpenDelim(delim),
813 &token::CloseDelim(delim),
814 SeqSep::trailing_allowed(token::Comma),
819 fn parse_paren_comma_seq<T>(
821 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
822 ) -> PResult<'a, (Vec<T>, bool)> {
823 self.parse_delim_comma_seq(token::Paren, f)
826 /// Advance the parser by one token using provided token as the next one.
827 fn bump_with(&mut self, (next_token, next_spacing): (Token, Spacing)) {
828 // Bumping after EOF is a bad sign, usually an infinite loop.
829 if self.prev_token.kind == TokenKind::Eof {
830 let msg = "attempted to bump the parser past EOF (may be stuck in a loop)";
831 self.span_bug(self.token.span, msg);
834 // Update the current and previous tokens.
835 self.prev_token = mem::replace(&mut self.token, next_token);
836 self.token_spacing = next_spacing;
839 self.expected_tokens.clear();
842 /// Advance the parser by one token.
843 pub fn bump(&mut self) {
844 let next_token = self.next_tok(self.token.span);
845 self.bump_with(next_token);
848 /// Look-ahead `dist` tokens of `self.token` and get access to that token there.
849 /// When `dist == 0` then the current token is looked at.
850 pub fn look_ahead<R>(&self, dist: usize, looker: impl FnOnce(&Token) -> R) -> R {
852 return looker(&self.token);
855 let frame = &self.token_cursor.frame;
856 match frame.tree_cursor.look_ahead(dist - 1) {
857 Some(tree) => match tree {
858 TokenTree::Token(token) => looker(token),
859 TokenTree::Delimited(dspan, delim, _) => {
860 looker(&Token::new(token::OpenDelim(*delim), dspan.open))
863 None => looker(&Token::new(token::CloseDelim(frame.delim), frame.span.close)),
867 /// Returns whether any of the given keywords are `dist` tokens ahead of the current one.
868 fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool {
869 self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw)))
872 /// Parses asyncness: `async` or nothing.
873 fn parse_asyncness(&mut self) -> Async {
874 if self.eat_keyword(kw::Async) {
875 let span = self.prev_token.uninterpolated_span();
876 Async::Yes { span, closure_id: DUMMY_NODE_ID, return_impl_trait_id: DUMMY_NODE_ID }
882 /// Parses unsafety: `unsafe` or nothing.
883 fn parse_unsafety(&mut self) -> Unsafe {
884 if self.eat_keyword(kw::Unsafe) {
885 Unsafe::Yes(self.prev_token.uninterpolated_span())
891 /// Parses constness: `const` or nothing.
892 fn parse_constness(&mut self) -> Const {
893 // Avoid const blocks to be parsed as const items
894 if self.look_ahead(1, |t| t != &token::OpenDelim(DelimToken::Brace))
895 && self.eat_keyword(kw::Const)
897 Const::Yes(self.prev_token.uninterpolated_span())
903 /// Parses inline const expressions.
904 fn parse_const_block(&mut self, span: Span) -> PResult<'a, P<Expr>> {
905 self.sess.gated_spans.gate(sym::inline_const, span);
906 self.eat_keyword(kw::Const);
907 let blk = self.parse_block()?;
908 let anon_const = AnonConst {
910 value: self.mk_expr(blk.span, ExprKind::Block(blk, None), AttrVec::new()),
912 let blk_span = anon_const.value.span;
913 Ok(self.mk_expr(span.to(blk_span), ExprKind::ConstBlock(anon_const), AttrVec::new()))
916 /// Parses mutability (`mut` or nothing).
917 fn parse_mutability(&mut self) -> Mutability {
918 if self.eat_keyword(kw::Mut) { Mutability::Mut } else { Mutability::Not }
921 /// Possibly parses mutability (`const` or `mut`).
922 fn parse_const_or_mut(&mut self) -> Option<Mutability> {
923 if self.eat_keyword(kw::Mut) {
924 Some(Mutability::Mut)
925 } else if self.eat_keyword(kw::Const) {
926 Some(Mutability::Not)
932 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
933 if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) = self.token.kind
935 self.expect_no_suffix(self.token.span, "a tuple index", suffix);
937 Ok(Ident::new(symbol, self.prev_token.span))
939 self.parse_ident_common(false)
943 fn parse_mac_args(&mut self) -> PResult<'a, P<MacArgs>> {
944 self.parse_mac_args_common(true).map(P)
947 fn parse_attr_args(&mut self) -> PResult<'a, MacArgs> {
948 self.parse_mac_args_common(false)
951 fn parse_mac_args_common(&mut self, delimited_only: bool) -> PResult<'a, MacArgs> {
953 if self.check(&token::OpenDelim(DelimToken::Paren))
954 || self.check(&token::OpenDelim(DelimToken::Bracket))
955 || self.check(&token::OpenDelim(DelimToken::Brace))
957 match self.parse_token_tree() {
958 TokenTree::Delimited(dspan, delim, tokens) =>
959 // We've confirmed above that there is a delimiter so unwrapping is OK.
961 MacArgs::Delimited(dspan, MacDelimiter::from_token(delim).unwrap(), tokens)
965 } else if !delimited_only {
966 if self.eat(&token::Eq) {
967 let eq_span = self.prev_token.span;
968 let mut is_interpolated_expr = false;
969 if let token::Interpolated(nt) = &self.token.kind {
970 if let token::NtExpr(..) = **nt {
971 is_interpolated_expr = true;
975 // The value here is never passed to macros as tokens by itself (not as a part
976 // of the whole attribute), so we don't collect tokens here. If this changes,
977 // then token will need to be collected. One catch here is that we are using
978 // a nonterminal for keeping the expression, but this nonterminal should not
979 // be wrapped into a group when converting to token stream.
980 let expr = self.parse_expr()?;
981 let span = expr.span;
984 // Not gated to supporte things like `doc = $expr` that work on stable.
985 _ if is_interpolated_expr => {}
986 ExprKind::Lit(lit) if lit.kind.is_unsuffixed() => {}
987 _ => self.sess.gated_spans.gate(sym::extended_key_value_attributes, span),
990 let token = token::Interpolated(Lrc::new(token::NtExpr(expr)));
991 MacArgs::Eq(eq_span, TokenTree::token(token, span).into())
996 return self.unexpected();
1001 fn parse_or_use_outer_attributes(
1003 already_parsed_attrs: Option<AttrVec>,
1004 ) -> PResult<'a, AttrVec> {
1005 if let Some(attrs) = already_parsed_attrs {
1008 self.parse_outer_attributes().map(|a| a.into())
1012 /// Parses a single token tree from the input.
1013 pub(crate) fn parse_token_tree(&mut self) -> TokenTree {
1014 match self.token.kind {
1015 token::OpenDelim(..) => {
1016 let depth = self.token_cursor.stack.len();
1018 // We keep advancing the token cursor until we hit
1019 // the matching `CloseDelim` token.
1020 while !(depth == self.token_cursor.stack.len()
1021 && matches!(self.token.kind, token::CloseDelim(_)))
1023 // Advance one token at a time, so `TokenCursor::next()`
1024 // can capture these tokens if necessary.
1027 // We are still inside the frame corresponding
1028 // to the delimited stream we captured, so grab
1029 // the tokens from this frame.
1030 let frame = &self.token_cursor.frame;
1031 let stream = frame.tree_cursor.stream.clone();
1032 let span = frame.span;
1033 let delim = frame.delim;
1034 // Consume close delimiter
1036 TokenTree::Delimited(span, delim, stream)
1038 token::CloseDelim(_) | token::Eof => unreachable!(),
1041 TokenTree::Token(self.prev_token.clone())
1046 /// Parses a stream of tokens into a list of `TokenTree`s, up to EOF.
1047 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
1048 let mut tts = Vec::new();
1049 while self.token != token::Eof {
1050 tts.push(self.parse_token_tree());
1055 pub fn parse_tokens(&mut self) -> TokenStream {
1056 let mut result = Vec::new();
1058 match self.token.kind {
1059 token::Eof | token::CloseDelim(..) => break,
1060 _ => result.push(self.parse_token_tree().into()),
1063 TokenStream::new(result)
1066 /// Evaluates the closure with restrictions in place.
1068 /// Afters the closure is evaluated, restrictions are reset.
1069 fn with_res<T>(&mut self, res: Restrictions, f: impl FnOnce(&mut Self) -> T) -> T {
1070 let old = self.restrictions;
1071 self.restrictions = res;
1073 self.restrictions = old;
1077 fn is_crate_vis(&self) -> bool {
1078 self.token.is_keyword(kw::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
1081 /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`,
1082 /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`.
1083 /// If the following element can't be a tuple (i.e., it's a function definition), then
1084 /// it's not a tuple struct field), and the contents within the parentheses isn't valid,
1085 /// so emit a proper diagnostic.
1086 // Public for rustfmt usage.
1087 pub fn parse_visibility(&mut self, fbt: FollowedByType) -> PResult<'a, Visibility> {
1088 maybe_whole!(self, NtVis, |x| x);
1090 self.expected_tokens.push(TokenType::Keyword(kw::Crate));
1091 if self.is_crate_vis() {
1092 self.bump(); // `crate`
1093 self.sess.gated_spans.gate(sym::crate_visibility_modifier, self.prev_token.span);
1094 return Ok(Visibility {
1095 span: self.prev_token.span,
1096 kind: VisibilityKind::Crate(CrateSugar::JustCrate),
1101 if !self.eat_keyword(kw::Pub) {
1102 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
1103 // keyword to grab a span from for inherited visibility; an empty span at the
1104 // beginning of the current token would seem to be the "Schelling span".
1105 return Ok(Visibility {
1106 span: self.token.span.shrink_to_lo(),
1107 kind: VisibilityKind::Inherited,
1111 let lo = self.prev_token.span;
1113 if self.check(&token::OpenDelim(token::Paren)) {
1114 // We don't `self.bump()` the `(` yet because this might be a struct definition where
1115 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
1116 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
1117 // by the following tokens.
1118 if self.is_keyword_ahead(1, &[kw::Crate]) && self.look_ahead(2, |t| t != &token::ModSep)
1119 // account for `pub(crate::foo)`
1121 // Parse `pub(crate)`.
1123 self.bump(); // `crate`
1124 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1125 let vis = VisibilityKind::Crate(CrateSugar::PubCrate);
1126 return Ok(Visibility {
1127 span: lo.to(self.prev_token.span),
1131 } else if self.is_keyword_ahead(1, &[kw::In]) {
1132 // Parse `pub(in path)`.
1134 self.bump(); // `in`
1135 let path = self.parse_path(PathStyle::Mod)?; // `path`
1136 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1137 let vis = VisibilityKind::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
1138 return Ok(Visibility {
1139 span: lo.to(self.prev_token.span),
1143 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren))
1144 && self.is_keyword_ahead(1, &[kw::Super, kw::SelfLower])
1146 // Parse `pub(self)` or `pub(super)`.
1148 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
1149 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1150 let vis = VisibilityKind::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
1151 return Ok(Visibility {
1152 span: lo.to(self.prev_token.span),
1156 } else if let FollowedByType::No = fbt {
1157 // Provide this diagnostic if a type cannot follow;
1158 // in particular, if this is not a tuple struct.
1159 self.recover_incorrect_vis_restriction()?;
1160 // Emit diagnostic, but continue with public visibility.
1164 Ok(Visibility { span: lo, kind: VisibilityKind::Public, tokens: None })
1167 /// Recovery for e.g. `pub(something) fn ...` or `struct X { pub(something) y: Z }`
1168 fn recover_incorrect_vis_restriction(&mut self) -> PResult<'a, ()> {
1170 let path = self.parse_path(PathStyle::Mod)?;
1171 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1173 let msg = "incorrect visibility restriction";
1174 let suggestion = r##"some possible visibility restrictions are:
1175 `pub(crate)`: visible only on the current crate
1176 `pub(super)`: visible only in the current module's parent
1177 `pub(in path::to::module)`: visible only on the specified path"##;
1179 let path_str = pprust::path_to_string(&path);
1181 struct_span_err!(self.sess.span_diagnostic, path.span, E0704, "{}", msg)
1185 &format!("make this visible only to module `{}` with `in`", path_str),
1186 format!("in {}", path_str),
1187 Applicability::MachineApplicable,
1194 /// Parses `extern string_literal?`.
1195 fn parse_extern(&mut self) -> PResult<'a, Extern> {
1196 Ok(if self.eat_keyword(kw::Extern) {
1197 Extern::from_abi(self.parse_abi())
1203 /// Parses a string literal as an ABI spec.
1204 fn parse_abi(&mut self) -> Option<StrLit> {
1205 match self.parse_str_lit() {
1206 Ok(str_lit) => Some(str_lit),
1207 Err(Some(lit)) => match lit.kind {
1208 ast::LitKind::Err(_) => None,
1210 self.struct_span_err(lit.span, "non-string ABI literal")
1213 "specify the ABI with a string literal",
1214 "\"C\"".to_string(),
1215 Applicability::MaybeIncorrect,
1225 /// Records all tokens consumed by the provided callback,
1226 /// including the current token. These tokens are collected
1227 /// into a `LazyTokenStream`, and returned along with the result
1228 /// of the callback.
1230 /// Note: If your callback consumes an opening delimiter
1231 /// (including the case where you call `collect_tokens`
1232 /// when the current token is an opening delimeter),
1233 /// you must also consume the corresponding closing delimiter.
1235 /// That is, you can consume
1236 /// `something ([{ }])` or `([{}])`, but not `([{}]`
1238 /// This restriction shouldn't be an issue in practice,
1239 /// since this function is used to record the tokens for
1240 /// a parsed AST item, which always has matching delimiters.
1241 pub fn collect_tokens<R>(
1243 f: impl FnOnce(&mut Self) -> PResult<'a, R>,
1244 ) -> PResult<'a, (R, Option<LazyTokenStream>)> {
1245 let start_token = (self.token.clone(), self.token_spacing);
1246 let cursor_snapshot = self.token_cursor.clone();
1250 // Produces a `TokenStream` on-demand. Using `cursor_snapshot`
1251 // and `num_calls`, we can reconstruct the `TokenStream` seen
1252 // by the callback. This allows us to avoid producing a `TokenStream`
1253 // if it is never needed - for example, a captured `macro_rules!`
1254 // argument that is never passed to a proc macro.
1255 // In practice token stream creation happens rarely compared to
1256 // calls to `collect_tokens` (see some statistics in #78736),
1257 // so we are doing as little up-front work as possible.
1259 // This also makes `Parser` very cheap to clone, since
1260 // there is no intermediate collection buffer to clone.
1262 struct LazyTokenStreamImpl {
1263 start_token: (Token, Spacing),
1264 cursor_snapshot: TokenCursor,
1266 desugar_doc_comments: bool,
1267 trailing_semi: bool,
1268 append_unglued_token: Option<TreeAndSpacing>,
1270 impl CreateTokenStream for LazyTokenStreamImpl {
1271 fn create_token_stream(&self) -> TokenStream {
1272 let mut num_calls = self.num_calls;
1273 if self.trailing_semi {
1276 // The token produced by the final call to `next` or `next_desugared`
1277 // was not actually consumed by the callback. The combination
1278 // of chaining the initial token and using `take` produces the desired
1279 // result - we produce an empty `TokenStream` if no calls were made,
1280 // and omit the final token otherwise.
1281 let mut cursor_snapshot = self.cursor_snapshot.clone();
1282 let tokens = std::iter::once(self.start_token.clone())
1283 .chain((0..num_calls).map(|_| {
1284 if self.desugar_doc_comments {
1285 cursor_snapshot.next_desugared()
1287 cursor_snapshot.next()
1292 make_token_stream(tokens, self.append_unglued_token.clone())
1294 fn add_trailing_semi(&self) -> Box<dyn CreateTokenStream> {
1295 if self.trailing_semi {
1296 panic!("Called `add_trailing_semi` twice!");
1298 if self.append_unglued_token.is_some() {
1300 "Cannot call `add_trailing_semi` when we have an unglued token {:?}",
1301 self.append_unglued_token
1304 let mut new = self.clone();
1305 new.trailing_semi = true;
1310 let lazy_impl = LazyTokenStreamImpl {
1312 num_calls: self.token_cursor.num_next_calls - cursor_snapshot.num_next_calls,
1314 desugar_doc_comments: self.desugar_doc_comments,
1315 trailing_semi: false,
1316 append_unglued_token: self.token_cursor.append_unglued_token.clone(),
1318 Ok((ret, Some(LazyTokenStream::new(lazy_impl))))
1322 fn is_import_coupler(&mut self) -> bool {
1323 self.check(&token::ModSep)
1324 && self.look_ahead(1, |t| {
1325 *t == token::OpenDelim(token::Brace) || *t == token::BinOp(token::Star)
1329 pub fn clear_expected_tokens(&mut self) {
1330 self.expected_tokens.clear();
1334 crate fn make_unclosed_delims_error(
1335 unmatched: UnmatchedBrace,
1337 ) -> Option<DiagnosticBuilder<'_>> {
1338 // `None` here means an `Eof` was found. We already emit those errors elsewhere, we add them to
1339 // `unmatched_braces` only for error recovery in the `Parser`.
1340 let found_delim = unmatched.found_delim?;
1341 let mut err = sess.span_diagnostic.struct_span_err(
1342 unmatched.found_span,
1344 "mismatched closing delimiter: `{}`",
1345 pprust::token_kind_to_string(&token::CloseDelim(found_delim)),
1348 err.span_label(unmatched.found_span, "mismatched closing delimiter");
1349 if let Some(sp) = unmatched.candidate_span {
1350 err.span_label(sp, "closing delimiter possibly meant for this");
1352 if let Some(sp) = unmatched.unclosed_span {
1353 err.span_label(sp, "unclosed delimiter");
1358 pub fn emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedBrace>, sess: &ParseSess) {
1359 *sess.reached_eof.borrow_mut() |=
1360 unclosed_delims.iter().any(|unmatched_delim| unmatched_delim.found_delim.is_none());
1361 for unmatched in unclosed_delims.drain(..) {
1362 if let Some(mut e) = make_unclosed_delims_error(unmatched, sess) {
1368 /// Converts a flattened iterator of tokens (including open and close delimiter tokens)
1369 /// into a `TokenStream`, creating a `TokenTree::Delimited` for each matching pair
1370 /// of open and close delims.
1371 fn make_token_stream(
1372 tokens: impl Iterator<Item = (Token, Spacing)>,
1373 append_unglued_token: Option<TreeAndSpacing>,
1378 inner: Vec<(TokenTree, Spacing)>,
1380 let mut stack = vec![FrameData { open: DUMMY_SP, inner: vec![] }];
1381 for (token, spacing) in tokens {
1383 Token { kind: TokenKind::OpenDelim(_), span } => {
1384 stack.push(FrameData { open: span, inner: vec![] });
1386 Token { kind: TokenKind::CloseDelim(delim), span } => {
1387 let frame_data = stack.pop().expect("Token stack was empty!");
1388 let dspan = DelimSpan::from_pair(frame_data.open, span);
1389 let stream = TokenStream::new(frame_data.inner);
1390 let delimited = TokenTree::Delimited(dspan, delim, stream);
1393 .unwrap_or_else(|| panic!("Bottom token frame is missing for tokens!"))
1395 .push((delimited, Spacing::Alone));
1400 .expect("Bottom token frame is missing!")
1402 .push((TokenTree::Token(token), spacing));
1406 let mut final_buf = stack.pop().expect("Missing final buf!");
1407 final_buf.inner.extend(append_unglued_token);
1408 assert!(stack.is_empty(), "Stack should be empty: final_buf={:?} stack={:?}", final_buf, stack);
1409 TokenStream::new(final_buf.inner)