13 use crate::lexer::UnmatchedBrace;
14 pub use attr_wrapper::AttrWrapper;
15 pub use diagnostics::AttemptLocalParseRecovery;
16 use diagnostics::Error;
17 pub use pat::{RecoverColon, RecoverComma};
18 pub use path::PathStyle;
20 use rustc_ast::ptr::P;
21 use rustc_ast::token::{self, DelimToken, Token, TokenKind};
22 use rustc_ast::tokenstream::AttributesData;
23 use rustc_ast::tokenstream::{self, DelimSpan, Spacing};
24 use rustc_ast::tokenstream::{TokenStream, TokenTree};
25 use rustc_ast::AttrId;
26 use rustc_ast::DUMMY_NODE_ID;
27 use rustc_ast::{self as ast, AnonConst, AstLike, AttrStyle, AttrVec, Const, CrateSugar, Extern};
28 use rustc_ast::{Async, Expr, ExprKind, MacArgs, MacDelimiter, Mutability, StrLit, Unsafe};
29 use rustc_ast::{Visibility, VisibilityKind};
30 use rustc_ast_pretty::pprust;
31 use rustc_data_structures::fx::FxHashMap;
32 use rustc_data_structures::sync::Lrc;
33 use rustc_errors::PResult;
34 use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder, FatalError};
35 use rustc_session::parse::ParseSess;
36 use rustc_span::source_map::{MultiSpan, Span, DUMMY_SP};
37 use rustc_span::symbol::{kw, sym, Ident, Symbol};
41 use std::{cmp, mem, slice};
44 struct Restrictions: u8 {
45 const STMT_EXPR = 1 << 0;
46 const NO_STRUCT_LITERAL = 1 << 1;
47 const CONST_EXPR = 1 << 2;
51 #[derive(Clone, Copy, PartialEq, Debug)]
58 #[derive(Clone, Copy, PartialEq, Debug)]
64 /// Whether or not we should force collection of tokens for an AST node,
65 /// regardless of whether or not it has attributes
66 #[derive(Clone, Copy, PartialEq)]
67 pub enum ForceCollect {
72 #[derive(Debug, Eq, PartialEq)]
73 pub enum TrailingToken {
76 /// If the trailing token is a comma, then capture it
77 /// Otherwise, ignore the trailing token
81 /// Like `maybe_whole_expr`, but for things other than expressions.
83 macro_rules! maybe_whole {
84 ($p:expr, $constructor:ident, |$x:ident| $e:expr) => {
85 if let token::Interpolated(nt) = &$p.token.kind {
86 if let token::$constructor(x) = &**nt {
95 /// If the next tokens are ill-formed `$ty::` recover them as `<$ty>::`.
97 macro_rules! maybe_recover_from_interpolated_ty_qpath {
98 ($self: expr, $allow_qpath_recovery: expr) => {
99 if $allow_qpath_recovery && $self.look_ahead(1, |t| t == &token::ModSep) {
100 if let token::Interpolated(nt) = &$self.token.kind {
101 if let token::NtTy(ty) = &**nt {
104 return $self.maybe_recover_from_bad_qpath_stage_2($self.prev_token.span, ty);
112 pub struct Parser<'a> {
113 pub sess: &'a ParseSess,
114 /// The current token.
116 /// The spacing for the current token
117 pub token_spacing: Spacing,
118 /// The previous token.
119 pub prev_token: Token,
120 pub capture_cfg: bool,
121 restrictions: Restrictions,
122 expected_tokens: Vec<TokenType>,
123 // Important: This must only be advanced from `next_tok`
124 // to ensure that `token_cursor.num_next_calls` is updated properly
125 token_cursor: TokenCursor,
126 desugar_doc_comments: bool,
127 /// This field is used to keep track of how many left angle brackets we have seen. This is
128 /// required in order to detect extra leading left angle brackets (`<` characters) and error
131 /// See the comments in the `parse_path_segment` function for more details.
132 unmatched_angle_bracket_count: u32,
133 max_angle_bracket_count: u32,
134 /// A list of all unclosed delimiters found by the lexer. If an entry is used for error recovery
135 /// it gets removed from here. Every entry left at the end gets emitted as an independent
137 pub(super) unclosed_delims: Vec<UnmatchedBrace>,
138 last_unexpected_token_span: Option<Span>,
139 /// Span pointing at the `:` for the last type ascription the parser has seen, and whether it
140 /// looked like it could have been a mistyped path or literal `Option:Some(42)`).
141 pub last_type_ascription: Option<(Span, bool /* likely path typo */)>,
142 /// If present, this `Parser` is not parsing Rust code but rather a macro call.
143 subparser_name: Option<&'static str>,
144 capture_state: CaptureState,
147 /// Indicates a range of tokens that should be replaced by
148 /// the tokens in the provided vector. This is used in two
149 /// places during token collection:
151 /// 1. During the parsing of an AST node that may have a `#[derive]`
152 /// attribute, we parse a nested AST node that has `#[cfg]` or `#[cfg_attr]`
153 /// In this case, we use a `ReplaceRange` to replace the entire inner AST node
154 /// with `FlatToken::AttrTarget`, allowing us to perform eager cfg-expansion
155 /// on an `AttrAnnotatedTokenStream`
157 /// 2. When we parse an inner attribute while collecting tokens. We
158 /// remove inner attributes from the token stream entirely, and
159 /// instead track them through the `attrs` field on the AST node.
160 /// This allows us to easily manipulate them (for example, removing
161 /// the first macro inner attribute to invoke a proc-macro).
162 /// When create a `TokenStream`, the inner attributes get inserted
163 /// into the proper place in the token stream.
164 pub type ReplaceRange = (Range<u32>, Vec<(FlatToken, Spacing)>);
166 /// Controls how we capture tokens. Capturing can be expensive,
167 /// so we try to avoid performing capturing in cases where
168 /// we will never need an `AttrAnnotatedTokenStream`
169 #[derive(Copy, Clone)]
171 /// We aren't performing any capturing - this is the default mode.
173 /// We are capturing tokens
178 struct CaptureState {
179 capturing: Capturing,
180 replace_ranges: Vec<ReplaceRange>,
181 inner_attr_ranges: FxHashMap<AttrId, ReplaceRange>,
184 impl<'a> Drop for Parser<'a> {
186 emit_unclosed_delims(&mut self.unclosed_delims, &self.sess);
192 frame: TokenCursorFrame,
193 stack: Vec<TokenCursorFrame>,
194 desugar_doc_comments: bool,
195 // Counts the number of calls to `next` or `next_desugared`,
196 // depending on whether `desugar_doc_comments` is set.
197 num_next_calls: usize,
198 // During parsing, we may sometimes need to 'unglue' a
199 // glued token into two component tokens
200 // (e.g. '>>' into '>' and '>), so that the parser
201 // can consume them one at a time. This process
202 // bypasses the normal capturing mechanism
203 // (e.g. `num_next_calls` will not be incremented),
204 // since the 'unglued' tokens due not exist in
205 // the original `TokenStream`.
207 // If we end up consuming both unglued tokens,
208 // then this is not an issue - we'll end up
209 // capturing the single 'glued' token.
211 // However, in certain circumstances, we may
212 // want to capture just the first 'unglued' token.
213 // For example, capturing the `Vec<u8>`
214 // in `Option<Vec<u8>>` requires us to unglue
215 // the trailing `>>` token. The `break_last_token`
216 // field is used to track this token - it gets
217 // appended to the captured stream when
218 // we evaluate a `LazyTokenStream`
219 break_last_token: bool,
223 struct TokenCursorFrame {
224 delim: token::DelimToken,
227 tree_cursor: tokenstream::Cursor,
231 impl TokenCursorFrame {
232 fn new(span: DelimSpan, delim: DelimToken, tts: TokenStream) -> Self {
237 tree_cursor: tts.into_trees(),
244 fn next(&mut self) -> (Token, Spacing) {
246 let (tree, spacing) = if !self.frame.open_delim {
247 self.frame.open_delim = true;
248 TokenTree::open_tt(self.frame.span, self.frame.delim).into()
249 } else if let Some(tree) = self.frame.tree_cursor.next_with_spacing() {
251 } else if !self.frame.close_delim {
252 self.frame.close_delim = true;
253 TokenTree::close_tt(self.frame.span, self.frame.delim).into()
254 } else if let Some(frame) = self.stack.pop() {
258 (TokenTree::Token(Token::new(token::Eof, DUMMY_SP)), Spacing::Alone)
262 TokenTree::Token(token) => {
263 return (token, spacing);
265 TokenTree::Delimited(sp, delim, tts) => {
266 let frame = TokenCursorFrame::new(sp, delim, tts);
267 self.stack.push(mem::replace(&mut self.frame, frame));
273 fn next_desugared(&mut self) -> (Token, Spacing) {
274 let (data, attr_style, sp) = match self.next() {
275 (Token { kind: token::DocComment(_, attr_style, data), span }, _) => {
276 (data, attr_style, span)
281 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
282 // required to wrap the text.
283 let mut num_of_hashes = 0;
285 for ch in data.as_str().chars() {
288 '#' if count > 0 => count + 1,
291 num_of_hashes = cmp::max(num_of_hashes, count);
294 let delim_span = DelimSpan::from_single(sp);
295 let body = TokenTree::Delimited(
299 TokenTree::token(token::Ident(sym::doc, false), sp),
300 TokenTree::token(token::Eq, sp),
301 TokenTree::token(TokenKind::lit(token::StrRaw(num_of_hashes), data, None), sp),
305 .collect::<TokenStream>(),
308 self.stack.push(mem::replace(
310 TokenCursorFrame::new(
313 if attr_style == AttrStyle::Inner {
314 [TokenTree::token(token::Pound, sp), TokenTree::token(token::Not, sp), body]
317 .collect::<TokenStream>()
319 [TokenTree::token(token::Pound, sp), body]
322 .collect::<TokenStream>()
331 #[derive(Debug, Clone, PartialEq)]
344 fn to_string(&self) -> String {
346 TokenType::Token(ref t) => format!("`{}`", pprust::token_kind_to_string(t)),
347 TokenType::Keyword(kw) => format!("`{}`", kw),
348 TokenType::Operator => "an operator".to_string(),
349 TokenType::Lifetime => "lifetime".to_string(),
350 TokenType::Ident => "identifier".to_string(),
351 TokenType::Path => "path".to_string(),
352 TokenType::Type => "type".to_string(),
353 TokenType::Const => "a const expression".to_string(),
358 #[derive(Copy, Clone, Debug)]
359 enum TokenExpectType {
364 /// A sequence separator.
366 /// The separator token.
367 sep: Option<TokenKind>,
368 /// `true` if a trailing separator is allowed.
369 trailing_sep_allowed: bool,
373 fn trailing_allowed(t: TokenKind) -> SeqSep {
374 SeqSep { sep: Some(t), trailing_sep_allowed: true }
377 fn none() -> SeqSep {
378 SeqSep { sep: None, trailing_sep_allowed: false }
382 pub enum FollowedByType {
387 fn token_descr_opt(token: &Token) -> Option<&'static str> {
388 Some(match token.kind {
389 _ if token.is_special_ident() => "reserved identifier",
390 _ if token.is_used_keyword() => "keyword",
391 _ if token.is_unused_keyword() => "reserved keyword",
392 token::DocComment(..) => "doc comment",
397 pub(super) fn token_descr(token: &Token) -> String {
398 let token_str = pprust::token_to_string(token);
399 match token_descr_opt(token) {
400 Some(prefix) => format!("{} `{}`", prefix, token_str),
401 _ => format!("`{}`", token_str),
405 impl<'a> Parser<'a> {
409 desugar_doc_comments: bool,
410 subparser_name: Option<&'static str>,
412 let mut start_frame = TokenCursorFrame::new(DelimSpan::dummy(), token::NoDelim, tokens);
413 start_frame.open_delim = true;
414 start_frame.close_delim = true;
416 let mut parser = Parser {
418 token: Token::dummy(),
419 token_spacing: Spacing::Alone,
420 prev_token: Token::dummy(),
422 restrictions: Restrictions::empty(),
423 expected_tokens: Vec::new(),
424 token_cursor: TokenCursor {
428 desugar_doc_comments,
429 break_last_token: false,
431 desugar_doc_comments,
432 unmatched_angle_bracket_count: 0,
433 max_angle_bracket_count: 0,
434 unclosed_delims: Vec::new(),
435 last_unexpected_token_span: None,
436 last_type_ascription: None,
438 capture_state: CaptureState {
439 capturing: Capturing::No,
440 replace_ranges: Vec::new(),
441 inner_attr_ranges: Default::default(),
445 // Make parser point to the first token.
451 fn next_tok(&mut self, fallback_span: Span) -> (Token, Spacing) {
453 let (mut next, spacing) = if self.desugar_doc_comments {
454 self.token_cursor.next_desugared()
456 self.token_cursor.next()
458 self.token_cursor.num_next_calls += 1;
459 // We've retrieved an token from the underlying
460 // cursor, so we no longer need to worry about
461 // an unglued token. See `break_and_eat` for more details
462 self.token_cursor.break_last_token = false;
463 if next.span.is_dummy() {
464 // Tweak the location for better diagnostics, but keep syntactic context intact.
465 next.span = fallback_span.with_ctxt(next.span.ctxt());
469 token::OpenDelim(token::NoDelim) | token::CloseDelim(token::NoDelim)
473 return (next, spacing);
477 pub fn unexpected<T>(&mut self) -> PResult<'a, T> {
478 match self.expect_one_of(&[], &[]) {
480 // We can get `Ok(true)` from `recover_closing_delimiter`
481 // which is called in `expected_one_of_not_found`.
482 Ok(_) => FatalError.raise(),
486 /// Expects and consumes the token `t`. Signals an error if the next token is not `t`.
487 pub fn expect(&mut self, t: &TokenKind) -> PResult<'a, bool /* recovered */> {
488 if self.expected_tokens.is_empty() {
489 if self.token == *t {
493 self.unexpected_try_recover(t)
496 self.expect_one_of(slice::from_ref(t), &[])
500 /// Expect next token to be edible or inedible token. If edible,
501 /// then consume it; if inedible, then return without consuming
502 /// anything. Signal a fatal error if next token is unexpected.
503 pub fn expect_one_of(
505 edible: &[TokenKind],
506 inedible: &[TokenKind],
507 ) -> PResult<'a, bool /* recovered */> {
508 if edible.contains(&self.token.kind) {
511 } else if inedible.contains(&self.token.kind) {
512 // leave it in the input
514 } else if self.last_unexpected_token_span == Some(self.token.span) {
517 self.expected_one_of_not_found(edible, inedible)
521 // Public for rustfmt usage.
522 pub fn parse_ident(&mut self) -> PResult<'a, Ident> {
523 self.parse_ident_common(true)
526 fn ident_or_err(&mut self) -> PResult<'a, (Ident, /* is_raw */ bool)> {
527 self.token.ident().ok_or_else(|| match self.prev_token.kind {
528 TokenKind::DocComment(..) => {
529 self.span_err(self.prev_token.span, Error::UselessDocComment)
531 _ => self.expected_ident_found(),
535 fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, Ident> {
536 let (ident, is_raw) = self.ident_or_err()?;
537 if !is_raw && ident.is_reserved() {
538 let mut err = self.expected_ident_found();
549 /// Checks if the next token is `tok`, and returns `true` if so.
551 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
553 fn check(&mut self, tok: &TokenKind) -> bool {
554 let is_present = self.token == *tok;
556 self.expected_tokens.push(TokenType::Token(tok.clone()));
561 /// Consumes a token 'tok' if it exists. Returns whether the given token was present.
562 pub fn eat(&mut self, tok: &TokenKind) -> bool {
563 let is_present = self.check(tok);
570 /// If the next token is the given keyword, returns `true` without eating it.
571 /// An expectation is also added for diagnostics purposes.
572 fn check_keyword(&mut self, kw: Symbol) -> bool {
573 self.expected_tokens.push(TokenType::Keyword(kw));
574 self.token.is_keyword(kw)
577 /// If the next token is the given keyword, eats it and returns `true`.
578 /// Otherwise, returns `false`. An expectation is also added for diagnostics purposes.
579 // Public for rustfmt usage.
580 pub fn eat_keyword(&mut self, kw: Symbol) -> bool {
581 if self.check_keyword(kw) {
589 fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool {
590 if self.token.is_keyword(kw) {
598 /// If the given word is not a keyword, signals an error.
599 /// If the next token is not the given word, signals an error.
600 /// Otherwise, eats it.
601 fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> {
602 if !self.eat_keyword(kw) { self.unexpected() } else { Ok(()) }
605 /// Is the given keyword `kw` followed by a non-reserved identifier?
606 fn is_kw_followed_by_ident(&self, kw: Symbol) -> bool {
607 self.token.is_keyword(kw) && self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
610 fn check_or_expected(&mut self, ok: bool, typ: TokenType) -> bool {
614 self.expected_tokens.push(typ);
619 fn check_ident(&mut self) -> bool {
620 self.check_or_expected(self.token.is_ident(), TokenType::Ident)
623 fn check_path(&mut self) -> bool {
624 self.check_or_expected(self.token.is_path_start(), TokenType::Path)
627 fn check_type(&mut self) -> bool {
628 self.check_or_expected(self.token.can_begin_type(), TokenType::Type)
631 fn check_const_arg(&mut self) -> bool {
632 self.check_or_expected(self.token.can_begin_const_arg(), TokenType::Const)
635 fn check_inline_const(&self, dist: usize) -> bool {
636 self.is_keyword_ahead(dist, &[kw::Const])
637 && self.look_ahead(dist + 1, |t| match t.kind {
638 token::Interpolated(ref nt) => matches!(**nt, token::NtBlock(..)),
639 token::OpenDelim(DelimToken::Brace) => true,
644 /// Checks to see if the next token is either `+` or `+=`.
645 /// Otherwise returns `false`.
646 fn check_plus(&mut self) -> bool {
647 self.check_or_expected(
648 self.token.is_like_plus(),
649 TokenType::Token(token::BinOp(token::Plus)),
653 /// Eats the expected token if it's present possibly breaking
654 /// compound tokens like multi-character operators in process.
655 /// Returns `true` if the token was eaten.
656 fn break_and_eat(&mut self, expected: TokenKind) -> bool {
657 if self.token.kind == expected {
661 match self.token.kind.break_two_token_op() {
662 Some((first, second)) if first == expected => {
663 let first_span = self.sess.source_map().start_point(self.token.span);
664 let second_span = self.token.span.with_lo(first_span.hi());
665 self.token = Token::new(first, first_span);
666 // Keep track of this token - if we end token capturing now,
667 // we'll want to append this token to the captured stream.
669 // If we consume any additional tokens, then this token
670 // is not needed (we'll capture the entire 'glued' token),
671 // and `next_tok` will set this field to `None`
672 self.token_cursor.break_last_token = true;
673 // Use the spacing of the glued token as the spacing
674 // of the unglued second token.
675 self.bump_with((Token::new(second, second_span), self.token_spacing));
679 self.expected_tokens.push(TokenType::Token(expected));
685 /// Eats `+` possibly breaking tokens like `+=` in process.
686 fn eat_plus(&mut self) -> bool {
687 self.break_and_eat(token::BinOp(token::Plus))
690 /// Eats `&` possibly breaking tokens like `&&` in process.
691 /// Signals an error if `&` is not eaten.
692 fn expect_and(&mut self) -> PResult<'a, ()> {
693 if self.break_and_eat(token::BinOp(token::And)) { Ok(()) } else { self.unexpected() }
696 /// Eats `|` possibly breaking tokens like `||` in process.
697 /// Signals an error if `|` was not eaten.
698 fn expect_or(&mut self) -> PResult<'a, ()> {
699 if self.break_and_eat(token::BinOp(token::Or)) { Ok(()) } else { self.unexpected() }
702 /// Eats `<` possibly breaking tokens like `<<` in process.
703 fn eat_lt(&mut self) -> bool {
704 let ate = self.break_and_eat(token::Lt);
706 // See doc comment for `unmatched_angle_bracket_count`.
707 self.unmatched_angle_bracket_count += 1;
708 self.max_angle_bracket_count += 1;
709 debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count);
714 /// Eats `<` possibly breaking tokens like `<<` in process.
715 /// Signals an error if `<` was not eaten.
716 fn expect_lt(&mut self) -> PResult<'a, ()> {
717 if self.eat_lt() { Ok(()) } else { self.unexpected() }
720 /// Eats `>` possibly breaking tokens like `>>` in process.
721 /// Signals an error if `>` was not eaten.
722 fn expect_gt(&mut self) -> PResult<'a, ()> {
723 if self.break_and_eat(token::Gt) {
724 // See doc comment for `unmatched_angle_bracket_count`.
725 if self.unmatched_angle_bracket_count > 0 {
726 self.unmatched_angle_bracket_count -= 1;
727 debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count);
735 fn expect_any_with_type(&mut self, kets: &[&TokenKind], expect: TokenExpectType) -> bool {
736 kets.iter().any(|k| match expect {
737 TokenExpectType::Expect => self.check(k),
738 TokenExpectType::NoExpect => self.token == **k,
742 fn parse_seq_to_before_tokens<T>(
746 expect: TokenExpectType,
747 mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
748 ) -> PResult<'a, (Vec<T>, bool /* trailing */, bool /* recovered */)> {
749 let mut first = true;
750 let mut recovered = false;
751 let mut trailing = false;
753 let unclosed_delims = !self.unclosed_delims.is_empty();
755 while !self.expect_any_with_type(kets, expect) {
756 if let token::CloseDelim(..) | token::Eof = self.token.kind {
759 if let Some(ref t) = sep.sep {
763 match self.expect(t) {
769 Err(mut expect_err) => {
770 let sp = self.prev_token.span.shrink_to_hi();
771 let token_str = pprust::token_kind_to_string(t);
773 // Attempt to keep parsing if it was a similar separator.
774 if let Some(ref tokens) = t.similar_tokens() {
775 if tokens.contains(&self.token.kind) && !unclosed_delims {
780 // If this was a missing `@` in a binding pattern
781 // bail with a suggestion
782 // https://github.com/rust-lang/rust/issues/72373
783 if self.prev_token.is_ident() && self.token.kind == token::DotDot {
785 "if you meant to bind the contents of \
786 the rest of the array pattern into `{}`, use `@`",
787 pprust::token_to_string(&self.prev_token)
790 .span_suggestion_verbose(
791 self.prev_token.span.shrink_to_hi().until(self.token.span),
794 Applicability::MaybeIncorrect,
800 // Attempt to keep parsing if it was an omitted separator.
803 // Parsed successfully, therefore most probably the code only
804 // misses a separator.
806 .span_suggestion_short(
808 &format!("missing `{}`", token_str),
810 Applicability::MaybeIncorrect,
818 // Parsing failed, therefore it must be something more serious
819 // than just a missing separator.
830 if sep.trailing_sep_allowed && self.expect_any_with_type(kets, expect) {
839 Ok((v, trailing, recovered))
842 /// Parses a sequence, not including the closing delimiter. The function
843 /// `f` must consume tokens until reaching the next separator or
845 fn parse_seq_to_before_end<T>(
849 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
850 ) -> PResult<'a, (Vec<T>, bool, bool)> {
851 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
854 /// Parses a sequence, including the closing delimiter. The function
855 /// `f` must consume tokens until reaching the next separator or
857 fn parse_seq_to_end<T>(
861 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
862 ) -> PResult<'a, (Vec<T>, bool /* trailing */)> {
863 let (val, trailing, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
870 /// Parses a sequence, including the closing delimiter. The function
871 /// `f` must consume tokens until reaching the next separator or
873 fn parse_unspanned_seq<T>(
878 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
879 ) -> PResult<'a, (Vec<T>, bool)> {
881 self.parse_seq_to_end(ket, sep, f)
884 fn parse_delim_comma_seq<T>(
887 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
888 ) -> PResult<'a, (Vec<T>, bool)> {
889 self.parse_unspanned_seq(
890 &token::OpenDelim(delim),
891 &token::CloseDelim(delim),
892 SeqSep::trailing_allowed(token::Comma),
897 fn parse_paren_comma_seq<T>(
899 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
900 ) -> PResult<'a, (Vec<T>, bool)> {
901 self.parse_delim_comma_seq(token::Paren, f)
904 /// Advance the parser by one token using provided token as the next one.
905 fn bump_with(&mut self, (next_token, next_spacing): (Token, Spacing)) {
906 // Bumping after EOF is a bad sign, usually an infinite loop.
907 if self.prev_token.kind == TokenKind::Eof {
908 let msg = "attempted to bump the parser past EOF (may be stuck in a loop)";
909 self.span_bug(self.token.span, msg);
912 // Update the current and previous tokens.
913 self.prev_token = mem::replace(&mut self.token, next_token);
914 self.token_spacing = next_spacing;
917 self.expected_tokens.clear();
920 /// Advance the parser by one token.
921 pub fn bump(&mut self) {
922 let next_token = self.next_tok(self.token.span);
923 self.bump_with(next_token);
926 /// Look-ahead `dist` tokens of `self.token` and get access to that token there.
927 /// When `dist == 0` then the current token is looked at.
928 pub fn look_ahead<R>(&self, dist: usize, looker: impl FnOnce(&Token) -> R) -> R {
930 return looker(&self.token);
933 let frame = &self.token_cursor.frame;
934 if frame.delim != DelimToken::NoDelim {
935 let all_normal = (0..dist).all(|i| {
936 let token = frame.tree_cursor.look_ahead(i);
937 !matches!(token, Some(TokenTree::Delimited(_, DelimToken::NoDelim, _)))
940 return match frame.tree_cursor.look_ahead(dist - 1) {
941 Some(tree) => match tree {
942 TokenTree::Token(token) => looker(token),
943 TokenTree::Delimited(dspan, delim, _) => {
944 looker(&Token::new(token::OpenDelim(*delim), dspan.open))
947 None => looker(&Token::new(token::CloseDelim(frame.delim), frame.span.close)),
952 let mut cursor = self.token_cursor.clone();
954 let mut token = Token::dummy();
956 token = cursor.next().0;
959 token::OpenDelim(token::NoDelim) | token::CloseDelim(token::NoDelim)
965 return looker(&token);
968 /// Returns whether any of the given keywords are `dist` tokens ahead of the current one.
969 fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool {
970 self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw)))
973 /// Parses asyncness: `async` or nothing.
974 fn parse_asyncness(&mut self) -> Async {
975 if self.eat_keyword(kw::Async) {
976 let span = self.prev_token.uninterpolated_span();
977 Async::Yes { span, closure_id: DUMMY_NODE_ID, return_impl_trait_id: DUMMY_NODE_ID }
983 /// Parses unsafety: `unsafe` or nothing.
984 fn parse_unsafety(&mut self) -> Unsafe {
985 if self.eat_keyword(kw::Unsafe) {
986 Unsafe::Yes(self.prev_token.uninterpolated_span())
992 /// Parses constness: `const` or nothing.
993 fn parse_constness(&mut self) -> Const {
994 // Avoid const blocks to be parsed as const items
995 if self.look_ahead(1, |t| t != &token::OpenDelim(DelimToken::Brace))
996 && self.eat_keyword(kw::Const)
998 Const::Yes(self.prev_token.uninterpolated_span())
1004 /// Parses inline const expressions.
1005 fn parse_const_block(&mut self, span: Span) -> PResult<'a, P<Expr>> {
1006 self.sess.gated_spans.gate(sym::inline_const, span);
1007 self.eat_keyword(kw::Const);
1008 let blk = self.parse_block()?;
1009 let anon_const = AnonConst {
1011 value: self.mk_expr(blk.span, ExprKind::Block(blk, None), AttrVec::new()),
1013 let blk_span = anon_const.value.span;
1014 Ok(self.mk_expr(span.to(blk_span), ExprKind::ConstBlock(anon_const), AttrVec::new()))
1017 /// Parses mutability (`mut` or nothing).
1018 fn parse_mutability(&mut self) -> Mutability {
1019 if self.eat_keyword(kw::Mut) { Mutability::Mut } else { Mutability::Not }
1022 /// Possibly parses mutability (`const` or `mut`).
1023 fn parse_const_or_mut(&mut self) -> Option<Mutability> {
1024 if self.eat_keyword(kw::Mut) {
1025 Some(Mutability::Mut)
1026 } else if self.eat_keyword(kw::Const) {
1027 Some(Mutability::Not)
1033 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
1034 if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) = self.token.kind
1036 self.expect_no_suffix(self.token.span, "a tuple index", suffix);
1038 Ok(Ident::new(symbol, self.prev_token.span))
1040 self.parse_ident_common(true)
1044 fn parse_mac_args(&mut self) -> PResult<'a, P<MacArgs>> {
1045 self.parse_mac_args_common(true).map(P)
1048 fn parse_attr_args(&mut self) -> PResult<'a, MacArgs> {
1049 self.parse_mac_args_common(false)
1052 fn parse_mac_args_common(&mut self, delimited_only: bool) -> PResult<'a, MacArgs> {
1054 if self.check(&token::OpenDelim(DelimToken::Paren))
1055 || self.check(&token::OpenDelim(DelimToken::Bracket))
1056 || self.check(&token::OpenDelim(DelimToken::Brace))
1058 match self.parse_token_tree() {
1059 TokenTree::Delimited(dspan, delim, tokens) =>
1060 // We've confirmed above that there is a delimiter so unwrapping is OK.
1062 MacArgs::Delimited(dspan, MacDelimiter::from_token(delim).unwrap(), tokens)
1064 _ => unreachable!(),
1066 } else if !delimited_only {
1067 if self.eat(&token::Eq) {
1068 let eq_span = self.prev_token.span;
1070 // Collect tokens because they are used during lowering to HIR.
1071 let expr = self.parse_expr_force_collect()?;
1072 let span = expr.span;
1074 let token_kind = token::Interpolated(Lrc::new(token::NtExpr(expr)));
1075 MacArgs::Eq(eq_span, Token::new(token_kind, span))
1080 return self.unexpected();
1085 fn parse_or_use_outer_attributes(
1087 already_parsed_attrs: Option<AttrWrapper>,
1088 ) -> PResult<'a, AttrWrapper> {
1089 if let Some(attrs) = already_parsed_attrs {
1092 self.parse_outer_attributes()
1096 /// Parses a single token tree from the input.
1097 pub(crate) fn parse_token_tree(&mut self) -> TokenTree {
1098 match self.token.kind {
1099 token::OpenDelim(..) => {
1100 let depth = self.token_cursor.stack.len();
1102 // We keep advancing the token cursor until we hit
1103 // the matching `CloseDelim` token.
1104 while !(depth == self.token_cursor.stack.len()
1105 && matches!(self.token.kind, token::CloseDelim(_)))
1107 // Advance one token at a time, so `TokenCursor::next()`
1108 // can capture these tokens if necessary.
1111 // We are still inside the frame corresponding
1112 // to the delimited stream we captured, so grab
1113 // the tokens from this frame.
1114 let frame = &self.token_cursor.frame;
1115 let stream = frame.tree_cursor.stream.clone();
1116 let span = frame.span;
1117 let delim = frame.delim;
1118 // Consume close delimiter
1120 TokenTree::Delimited(span, delim, stream)
1122 token::CloseDelim(_) | token::Eof => unreachable!(),
1125 TokenTree::Token(self.prev_token.clone())
1130 /// Parses a stream of tokens into a list of `TokenTree`s, up to EOF.
1131 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
1132 let mut tts = Vec::new();
1133 while self.token != token::Eof {
1134 tts.push(self.parse_token_tree());
1139 pub fn parse_tokens(&mut self) -> TokenStream {
1140 let mut result = Vec::new();
1142 match self.token.kind {
1143 token::Eof | token::CloseDelim(..) => break,
1144 _ => result.push(self.parse_token_tree().into()),
1147 TokenStream::new(result)
1150 /// Evaluates the closure with restrictions in place.
1152 /// Afters the closure is evaluated, restrictions are reset.
1153 fn with_res<T>(&mut self, res: Restrictions, f: impl FnOnce(&mut Self) -> T) -> T {
1154 let old = self.restrictions;
1155 self.restrictions = res;
1157 self.restrictions = old;
1161 fn is_crate_vis(&self) -> bool {
1162 self.token.is_keyword(kw::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
1165 /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`,
1166 /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`.
1167 /// If the following element can't be a tuple (i.e., it's a function definition), then
1168 /// it's not a tuple struct field), and the contents within the parentheses isn't valid,
1169 /// so emit a proper diagnostic.
1170 // Public for rustfmt usage.
1171 pub fn parse_visibility(&mut self, fbt: FollowedByType) -> PResult<'a, Visibility> {
1172 maybe_whole!(self, NtVis, |x| x);
1174 self.expected_tokens.push(TokenType::Keyword(kw::Crate));
1175 if self.is_crate_vis() {
1176 self.bump(); // `crate`
1177 self.sess.gated_spans.gate(sym::crate_visibility_modifier, self.prev_token.span);
1178 return Ok(Visibility {
1179 span: self.prev_token.span,
1180 kind: VisibilityKind::Crate(CrateSugar::JustCrate),
1185 if !self.eat_keyword(kw::Pub) {
1186 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
1187 // keyword to grab a span from for inherited visibility; an empty span at the
1188 // beginning of the current token would seem to be the "Schelling span".
1189 return Ok(Visibility {
1190 span: self.token.span.shrink_to_lo(),
1191 kind: VisibilityKind::Inherited,
1195 let lo = self.prev_token.span;
1197 if self.check(&token::OpenDelim(token::Paren)) {
1198 // We don't `self.bump()` the `(` yet because this might be a struct definition where
1199 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
1200 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
1201 // by the following tokens.
1202 if self.is_keyword_ahead(1, &[kw::Crate]) && self.look_ahead(2, |t| t != &token::ModSep)
1203 // account for `pub(crate::foo)`
1205 // Parse `pub(crate)`.
1207 self.bump(); // `crate`
1208 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1209 let vis = VisibilityKind::Crate(CrateSugar::PubCrate);
1210 return Ok(Visibility {
1211 span: lo.to(self.prev_token.span),
1215 } else if self.is_keyword_ahead(1, &[kw::In]) {
1216 // Parse `pub(in path)`.
1218 self.bump(); // `in`
1219 let path = self.parse_path(PathStyle::Mod)?; // `path`
1220 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1221 let vis = VisibilityKind::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
1222 return Ok(Visibility {
1223 span: lo.to(self.prev_token.span),
1227 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren))
1228 && self.is_keyword_ahead(1, &[kw::Super, kw::SelfLower])
1230 // Parse `pub(self)` or `pub(super)`.
1232 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
1233 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1234 let vis = VisibilityKind::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
1235 return Ok(Visibility {
1236 span: lo.to(self.prev_token.span),
1240 } else if let FollowedByType::No = fbt {
1241 // Provide this diagnostic if a type cannot follow;
1242 // in particular, if this is not a tuple struct.
1243 self.recover_incorrect_vis_restriction()?;
1244 // Emit diagnostic, but continue with public visibility.
1248 Ok(Visibility { span: lo, kind: VisibilityKind::Public, tokens: None })
1251 /// Recovery for e.g. `pub(something) fn ...` or `struct X { pub(something) y: Z }`
1252 fn recover_incorrect_vis_restriction(&mut self) -> PResult<'a, ()> {
1254 let path = self.parse_path(PathStyle::Mod)?;
1255 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1257 let msg = "incorrect visibility restriction";
1258 let suggestion = r##"some possible visibility restrictions are:
1259 `pub(crate)`: visible only on the current crate
1260 `pub(super)`: visible only in the current module's parent
1261 `pub(in path::to::module)`: visible only on the specified path"##;
1263 let path_str = pprust::path_to_string(&path);
1265 struct_span_err!(self.sess.span_diagnostic, path.span, E0704, "{}", msg)
1269 &format!("make this visible only to module `{}` with `in`", path_str),
1270 format!("in {}", path_str),
1271 Applicability::MachineApplicable,
1278 /// Parses `extern string_literal?`.
1279 fn parse_extern(&mut self) -> Extern {
1280 if self.eat_keyword(kw::Extern) { Extern::from_abi(self.parse_abi()) } else { Extern::None }
1283 /// Parses a string literal as an ABI spec.
1284 fn parse_abi(&mut self) -> Option<StrLit> {
1285 match self.parse_str_lit() {
1286 Ok(str_lit) => Some(str_lit),
1287 Err(Some(lit)) => match lit.kind {
1288 ast::LitKind::Err(_) => None,
1290 self.struct_span_err(lit.span, "non-string ABI literal")
1293 "specify the ABI with a string literal",
1294 "\"C\"".to_string(),
1295 Applicability::MaybeIncorrect,
1305 pub fn collect_tokens_no_attrs<R: AstLike>(
1307 f: impl FnOnce(&mut Self) -> PResult<'a, R>,
1308 ) -> PResult<'a, R> {
1309 // The only reason to call `collect_tokens_no_attrs` is if you want tokens, so use
1310 // `ForceCollect::Yes`
1311 self.collect_tokens_trailing_token(
1312 AttrWrapper::empty(),
1314 |this, _attrs| Ok((f(this)?, TrailingToken::None)),
1319 fn is_import_coupler(&mut self) -> bool {
1320 self.check(&token::ModSep)
1321 && self.look_ahead(1, |t| {
1322 *t == token::OpenDelim(token::Brace) || *t == token::BinOp(token::Star)
1326 pub fn clear_expected_tokens(&mut self) {
1327 self.expected_tokens.clear();
1331 crate fn make_unclosed_delims_error(
1332 unmatched: UnmatchedBrace,
1334 ) -> Option<DiagnosticBuilder<'_>> {
1335 // `None` here means an `Eof` was found. We already emit those errors elsewhere, we add them to
1336 // `unmatched_braces` only for error recovery in the `Parser`.
1337 let found_delim = unmatched.found_delim?;
1338 let span: MultiSpan = if let Some(sp) = unmatched.unclosed_span {
1339 vec![unmatched.found_span, sp].into()
1341 unmatched.found_span.into()
1343 let mut err = sess.span_diagnostic.struct_span_err(
1346 "mismatched closing delimiter: `{}`",
1347 pprust::token_kind_to_string(&token::CloseDelim(found_delim)),
1350 err.span_label(unmatched.found_span, "mismatched closing delimiter");
1351 if let Some(sp) = unmatched.candidate_span {
1352 err.span_label(sp, "closing delimiter possibly meant for this");
1354 if let Some(sp) = unmatched.unclosed_span {
1355 err.span_label(sp, "unclosed delimiter");
1360 pub fn emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedBrace>, sess: &ParseSess) {
1361 *sess.reached_eof.borrow_mut() |=
1362 unclosed_delims.iter().any(|unmatched_delim| unmatched_delim.found_delim.is_none());
1363 for unmatched in unclosed_delims.drain(..) {
1364 if let Some(mut e) = make_unclosed_delims_error(unmatched, sess) {
1370 /// A helper struct used when building an `AttrAnnotatedTokenStream` from
1371 /// a `LazyTokenStream`. Both delimiter and non-delimited tokens
1372 /// are stored as `FlatToken::Token`. A vector of `FlatToken`s
1373 /// is then 'parsed' to build up an `AttrAnnotatedTokenStream` with nested
1374 /// `AttrAnnotatedTokenTree::Delimited` tokens
1375 #[derive(Debug, Clone)]
1376 pub enum FlatToken {
1377 /// A token - this holds both delimiter (e.g. '{' and '}')
1378 /// and non-delimiter tokens
1380 /// Holds the `AttributesData` for an AST node. The
1381 /// `AttributesData` is inserted directly into the
1382 /// constructed `AttrAnnotatedTokenStream` as
1383 /// an `AttrAnnotatedTokenTree::Attributes`
1384 AttrTarget(AttributesData),
1385 /// A special 'empty' token that is ignored during the conversion
1386 /// to an `AttrAnnotatedTokenStream`. This is used to simplify the
1387 /// handling of replace ranges.