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};
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};
33 use std::{cmp, mem, slice};
36 struct Restrictions: u8 {
37 const STMT_EXPR = 1 << 0;
38 const NO_STRUCT_LITERAL = 1 << 1;
39 const CONST_EXPR = 1 << 2;
43 #[derive(Clone, Copy, PartialEq, Debug)]
50 #[derive(Clone, Copy, PartialEq, Debug)]
56 /// Like `maybe_whole_expr`, but for things other than expressions.
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 {
70 /// If the next tokens are ill-formed `$ty::` recover them as `<$ty>::`.
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 {
79 return $self.maybe_recover_from_bad_qpath_stage_2($self.prev_token.span, ty);
87 pub struct Parser<'a> {
88 pub sess: &'a ParseSess,
89 /// The current 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
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
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>,
120 impl<'a> Drop for Parser<'a> {
122 emit_unclosed_delims(&mut self.unclosed_delims, &self.sess);
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,
137 struct TokenCursorFrame {
138 delim: token::DelimToken,
141 tree_cursor: tokenstream::Cursor,
145 impl TokenCursorFrame {
146 fn new(span: DelimSpan, delim: DelimToken, tts: TokenStream) -> Self {
150 open_delim: delim == token::NoDelim,
151 tree_cursor: tts.into_trees(),
152 close_delim: delim == token::NoDelim,
158 fn next(&mut self) -> (Token, Spacing) {
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() {
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() {
172 (TokenTree::Token(Token::new(token::Eof, DUMMY_SP)), Spacing::Alone)
176 TokenTree::Token(token) => {
177 return (token, spacing);
179 TokenTree::Delimited(sp, delim, tts) => {
180 let frame = TokenCursorFrame::new(sp, delim, tts);
181 self.stack.push(mem::replace(&mut self.frame, frame));
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)
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;
199 for ch in data.as_str().chars() {
202 '#' if count > 0 => count + 1,
205 num_of_hashes = cmp::max(num_of_hashes, count);
208 let delim_span = DelimSpan::from_single(sp);
209 let body = TokenTree::Delimited(
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),
219 .collect::<TokenStream>(),
222 self.stack.push(mem::replace(
224 TokenCursorFrame::new(
227 if attr_style == AttrStyle::Inner {
228 [TokenTree::token(token::Pound, sp), TokenTree::token(token::Not, sp), body]
231 .collect::<TokenStream>()
233 [TokenTree::token(token::Pound, sp), body]
236 .collect::<TokenStream>()
245 #[derive(Clone, PartialEq)]
258 fn to_string(&self) -> String {
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(),
272 #[derive(Copy, Clone, Debug)]
273 enum TokenExpectType {
278 /// A sequence separator.
280 /// The separator token.
281 sep: Option<TokenKind>,
282 /// `true` if a trailing separator is allowed.
283 trailing_sep_allowed: bool,
287 fn trailing_allowed(t: TokenKind) -> SeqSep {
288 SeqSep { sep: Some(t), trailing_sep_allowed: true }
291 fn none() -> SeqSep {
292 SeqSep { sep: None, trailing_sep_allowed: false }
296 pub enum FollowedByType {
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",
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),
319 impl<'a> Parser<'a> {
323 desugar_doc_comments: bool,
324 subparser_name: Option<&'static str>,
326 let mut parser = Parser {
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),
337 desugar_doc_comments,
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,
348 // Make parser point to the first token.
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()
358 self.token_cursor.next()
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());
368 pub fn unexpected<T>(&mut self) -> PResult<'a, T> {
369 match self.expect_one_of(&[], &[]) {
371 // We can get `Ok(true)` from `recover_closing_delimiter`
372 // which is called in `expected_one_of_not_found`.
373 Ok(_) => FatalError.raise(),
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 {
384 self.unexpected_try_recover(t)
387 self.expect_one_of(slice::from_ref(t), &[])
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(
396 edible: &[TokenKind],
397 inedible: &[TokenKind],
398 ) -> PResult<'a, bool /* recovered */> {
399 if edible.contains(&self.token.kind) {
402 } else if inedible.contains(&self.token.kind) {
403 // leave it in the input
405 } else if self.last_unexpected_token_span == Some(self.token.span) {
408 self.expected_one_of_not_found(edible, inedible)
412 // Public for rustfmt usage.
413 pub fn parse_ident(&mut self) -> PResult<'a, Ident> {
414 self.parse_ident_common(true)
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();
431 _ => Err(match self.prev_token.kind {
432 TokenKind::DocComment(..) => {
433 self.span_fatal_err(self.prev_token.span, Error::UselessDocComment)
435 _ => self.expected_ident_found(),
440 /// Checks if the next token is `tok`, and returns `true` if so.
442 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
444 fn check(&mut self, tok: &TokenKind) -> bool {
445 let is_present = self.token == *tok;
447 self.expected_tokens.push(TokenType::Token(tok.clone()));
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);
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)
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) {
480 fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool {
481 if self.token.is_keyword(kw) {
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(()) }
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())
501 fn check_or_expected(&mut self, ok: bool, typ: TokenType) -> bool {
505 self.expected_tokens.push(typ);
510 fn check_ident(&mut self) -> bool {
511 self.check_or_expected(self.token.is_ident(), TokenType::Ident)
514 fn check_path(&mut self) -> bool {
515 self.check_or_expected(self.token.is_path_start(), TokenType::Path)
518 fn check_type(&mut self) -> bool {
519 self.check_or_expected(self.token.can_begin_type(), TokenType::Type)
522 fn check_const_arg(&mut self) -> bool {
523 self.check_or_expected(self.token.can_begin_const_arg(), TokenType::Const)
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,
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)),
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 {
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));
563 self.expected_tokens.push(TokenType::Token(expected));
569 /// Eats `+` possibly breaking tokens like `+=` in process.
570 fn eat_plus(&mut self) -> bool {
571 self.break_and_eat(token::BinOp(token::Plus))
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() }
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() }
586 /// Eats `<` possibly breaking tokens like `<<` in process.
587 fn eat_lt(&mut self) -> bool {
588 let ate = self.break_and_eat(token::Lt);
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);
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() }
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);
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,
626 fn parse_seq_to_before_tokens<T>(
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;
637 while !self.expect_any_with_type(kets, expect) {
638 if let token::CloseDelim(..) | token::Eof = self.token.kind {
641 if let Some(ref t) = sep.sep {
645 match self.expect(t) {
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);
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) {
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 {
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)
672 .span_suggestion_verbose(
673 self.prev_token.span.shrink_to_hi().until(self.token.span),
676 Applicability::MaybeIncorrect,
682 // Attempt to keep parsing if it was an omitted separator.
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) {
692 .span_suggestion_short(
694 &format!("missing `{}`", token_str),
696 Applicability::MaybeIncorrect,
704 // Parsing failed, therefore it must be something more serious
705 // than just a missing separator.
716 if sep.trailing_sep_allowed && self.expect_any_with_type(kets, expect) {
725 Ok((v, trailing, recovered))
728 /// Parses a sequence, not including the closing delimiter. The function
729 /// `f` must consume tokens until reaching the next separator or
731 fn parse_seq_to_before_end<T>(
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)
740 /// Parses a sequence, including the closing delimiter. The function
741 /// `f` must consume tokens until reaching the next separator or
743 fn parse_seq_to_end<T>(
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)?;
756 /// Parses a sequence, including the closing delimiter. The function
757 /// `f` must consume tokens until reaching the next separator or
759 fn parse_unspanned_seq<T>(
764 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
765 ) -> PResult<'a, (Vec<T>, bool)> {
767 self.parse_seq_to_end(ket, sep, f)
770 fn parse_delim_comma_seq<T>(
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),
783 fn parse_paren_comma_seq<T>(
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)
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);
798 // Update the current and previous tokens.
799 self.prev_token = mem::replace(&mut self.token, next_token);
800 self.token_spacing = next_spacing;
803 self.expected_tokens.clear();
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);
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 {
816 return looker(&self.token);
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))
827 None => looker(&Token::new(token::CloseDelim(frame.delim), frame.span.close)),
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)))
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 }
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())
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)
861 Const::Yes(self.prev_token.uninterpolated_span())
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 {
874 value: self.mk_expr(blk.span, ExprKind::Block(blk, None), AttrVec::new()),
876 let blk_span = anon_const.value.span;
877 Ok(self.mk_expr(span.to(blk_span), ExprKind::ConstBlock(anon_const), AttrVec::new()))
880 /// Parses mutability (`mut` or nothing).
881 fn parse_mutability(&mut self) -> Mutability {
882 if self.eat_keyword(kw::Mut) { Mutability::Mut } else { Mutability::Not }
885 /// Possibly parses mutability (`const` or `mut`).
886 fn parse_const_or_mut(&mut self) -> Option<Mutability> {
887 if self.eat_keyword(kw::Mut) {
888 Some(Mutability::Mut)
889 } else if self.eat_keyword(kw::Const) {
890 Some(Mutability::Not)
896 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
897 if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) = self.token.kind
899 self.expect_no_suffix(self.token.span, "a tuple index", suffix);
901 Ok(Ident::new(symbol, self.prev_token.span))
903 self.parse_ident_common(false)
907 fn parse_mac_args(&mut self) -> PResult<'a, P<MacArgs>> {
908 self.parse_mac_args_common(true).map(P)
911 fn parse_attr_args(&mut self) -> PResult<'a, MacArgs> {
912 self.parse_mac_args_common(false)
915 fn parse_mac_args_common(&mut self, delimited_only: bool) -> PResult<'a, MacArgs> {
917 if self.check(&token::OpenDelim(DelimToken::Paren))
918 || self.check(&token::OpenDelim(DelimToken::Bracket))
919 || self.check(&token::OpenDelim(DelimToken::Brace))
921 match self.parse_token_tree() {
922 TokenTree::Delimited(dspan, delim, tokens) =>
923 // We've confirmed above that there is a delimiter so unwrapping is OK.
925 MacArgs::Delimited(dspan, MacDelimiter::from_token(delim).unwrap(), tokens)
929 } else if !delimited_only {
930 if self.eat(&token::Eq) {
931 let eq_span = self.prev_token.span;
932 let mut is_interpolated_expr = false;
933 if let token::Interpolated(nt) = &self.token.kind {
934 if let token::NtExpr(..) = **nt {
935 is_interpolated_expr = true;
938 let token_tree = if is_interpolated_expr {
939 // We need to accept arbitrary interpolated expressions to continue
940 // supporting things like `doc = $expr` that work on stable.
941 // Non-literal interpolated expressions are rejected after expansion.
942 self.parse_token_tree()
944 self.parse_unsuffixed_lit()?.token_tree()
947 MacArgs::Eq(eq_span, token_tree.into())
952 return self.unexpected();
957 fn parse_or_use_outer_attributes(
959 already_parsed_attrs: Option<AttrVec>,
960 ) -> PResult<'a, AttrVec> {
961 if let Some(attrs) = already_parsed_attrs {
964 self.parse_outer_attributes().map(|a| a.into())
968 /// Parses a single token tree from the input.
969 pub(crate) fn parse_token_tree(&mut self) -> TokenTree {
970 match self.token.kind {
971 token::OpenDelim(..) => {
972 let depth = self.token_cursor.stack.len();
974 // We keep advancing the token cursor until we hit
975 // the matching `CloseDelim` token.
976 while !(depth == self.token_cursor.stack.len()
977 && matches!(self.token.kind, token::CloseDelim(_)))
979 // Advance one token at a time, so `TokenCursor::next()`
980 // can capture these tokens if necessary.
983 // We are still inside the frame corresponding
984 // to the delimited stream we captured, so grab
985 // the tokens from this frame.
986 let frame = &self.token_cursor.frame;
987 let stream = frame.tree_cursor.stream.clone();
988 let span = frame.span;
989 let delim = frame.delim;
990 // Consume close delimiter
992 TokenTree::Delimited(span, delim, stream)
994 token::CloseDelim(_) | token::Eof => unreachable!(),
997 TokenTree::Token(self.prev_token.clone())
1002 /// Parses a stream of tokens into a list of `TokenTree`s, up to EOF.
1003 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
1004 let mut tts = Vec::new();
1005 while self.token != token::Eof {
1006 tts.push(self.parse_token_tree());
1011 pub fn parse_tokens(&mut self) -> TokenStream {
1012 let mut result = Vec::new();
1014 match self.token.kind {
1015 token::Eof | token::CloseDelim(..) => break,
1016 _ => result.push(self.parse_token_tree().into()),
1019 TokenStream::new(result)
1022 /// Evaluates the closure with restrictions in place.
1024 /// Afters the closure is evaluated, restrictions are reset.
1025 fn with_res<T>(&mut self, res: Restrictions, f: impl FnOnce(&mut Self) -> T) -> T {
1026 let old = self.restrictions;
1027 self.restrictions = res;
1029 self.restrictions = old;
1033 fn is_crate_vis(&self) -> bool {
1034 self.token.is_keyword(kw::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
1037 /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`,
1038 /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`.
1039 /// If the following element can't be a tuple (i.e., it's a function definition), then
1040 /// it's not a tuple struct field), and the contents within the parentheses isn't valid,
1041 /// so emit a proper diagnostic.
1042 // Public for rustfmt usage.
1043 pub fn parse_visibility(&mut self, fbt: FollowedByType) -> PResult<'a, Visibility> {
1044 maybe_whole!(self, NtVis, |x| x);
1046 self.expected_tokens.push(TokenType::Keyword(kw::Crate));
1047 if self.is_crate_vis() {
1048 self.bump(); // `crate`
1049 self.sess.gated_spans.gate(sym::crate_visibility_modifier, self.prev_token.span);
1050 return Ok(Visibility {
1051 span: self.prev_token.span,
1052 kind: VisibilityKind::Crate(CrateSugar::JustCrate),
1057 if !self.eat_keyword(kw::Pub) {
1058 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
1059 // keyword to grab a span from for inherited visibility; an empty span at the
1060 // beginning of the current token would seem to be the "Schelling span".
1061 return Ok(Visibility {
1062 span: self.token.span.shrink_to_lo(),
1063 kind: VisibilityKind::Inherited,
1067 let lo = self.prev_token.span;
1069 if self.check(&token::OpenDelim(token::Paren)) {
1070 // We don't `self.bump()` the `(` yet because this might be a struct definition where
1071 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
1072 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
1073 // by the following tokens.
1074 if self.is_keyword_ahead(1, &[kw::Crate]) && self.look_ahead(2, |t| t != &token::ModSep)
1075 // account for `pub(crate::foo)`
1077 // Parse `pub(crate)`.
1079 self.bump(); // `crate`
1080 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1081 let vis = VisibilityKind::Crate(CrateSugar::PubCrate);
1082 return Ok(Visibility {
1083 span: lo.to(self.prev_token.span),
1087 } else if self.is_keyword_ahead(1, &[kw::In]) {
1088 // Parse `pub(in path)`.
1090 self.bump(); // `in`
1091 let path = self.parse_path(PathStyle::Mod)?; // `path`
1092 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1093 let vis = VisibilityKind::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
1094 return Ok(Visibility {
1095 span: lo.to(self.prev_token.span),
1099 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren))
1100 && self.is_keyword_ahead(1, &[kw::Super, kw::SelfLower])
1102 // Parse `pub(self)` or `pub(super)`.
1104 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
1105 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1106 let vis = VisibilityKind::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
1107 return Ok(Visibility {
1108 span: lo.to(self.prev_token.span),
1112 } else if let FollowedByType::No = fbt {
1113 // Provide this diagnostic if a type cannot follow;
1114 // in particular, if this is not a tuple struct.
1115 self.recover_incorrect_vis_restriction()?;
1116 // Emit diagnostic, but continue with public visibility.
1120 Ok(Visibility { span: lo, kind: VisibilityKind::Public, tokens: None })
1123 /// Recovery for e.g. `pub(something) fn ...` or `struct X { pub(something) y: Z }`
1124 fn recover_incorrect_vis_restriction(&mut self) -> PResult<'a, ()> {
1126 let path = self.parse_path(PathStyle::Mod)?;
1127 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1129 let msg = "incorrect visibility restriction";
1130 let suggestion = r##"some possible visibility restrictions are:
1131 `pub(crate)`: visible only on the current crate
1132 `pub(super)`: visible only in the current module's parent
1133 `pub(in path::to::module)`: visible only on the specified path"##;
1135 let path_str = pprust::path_to_string(&path);
1137 struct_span_err!(self.sess.span_diagnostic, path.span, E0704, "{}", msg)
1141 &format!("make this visible only to module `{}` with `in`", path_str),
1142 format!("in {}", path_str),
1143 Applicability::MachineApplicable,
1150 /// Parses `extern string_literal?`.
1151 fn parse_extern(&mut self) -> PResult<'a, Extern> {
1152 Ok(if self.eat_keyword(kw::Extern) {
1153 Extern::from_abi(self.parse_abi())
1159 /// Parses a string literal as an ABI spec.
1160 fn parse_abi(&mut self) -> Option<StrLit> {
1161 match self.parse_str_lit() {
1162 Ok(str_lit) => Some(str_lit),
1163 Err(Some(lit)) => match lit.kind {
1164 ast::LitKind::Err(_) => None,
1166 self.struct_span_err(lit.span, "non-string ABI literal")
1169 "specify the ABI with a string literal",
1170 "\"C\"".to_string(),
1171 Applicability::MaybeIncorrect,
1181 /// Records all tokens consumed by the provided callback,
1182 /// including the current token. These tokens are collected
1183 /// into a `LazyTokenStream`, and returned along with the result
1184 /// of the callback.
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.
1191 /// That is, you can consume
1192 /// `something ([{ }])` or `([{}])`, but not `([{}]`
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>(
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();
1206 // Produces a `TokenStream` on-demand. Using `cursor_snapshot`
1207 // and `num_calls`, we can reconstruct the `TokenStream` seen
1208 // by the callback. This allows us to avoid producing a `TokenStream`
1209 // if it is never needed - for example, a captured `macro_rules!`
1210 // argument that is never passed to a proc macro.
1211 // In practice token stream creation happens rarely compared to
1212 // calls to `collect_tokens` (see some statistics in #78736),
1213 // so we are doing as little up-front work as possible.
1215 // This also makes `Parser` very cheap to clone, since
1216 // there is no intermediate collection buffer to clone.
1218 struct LazyTokenStreamImpl {
1219 start_token: (Token, Spacing),
1220 cursor_snapshot: TokenCursor,
1222 desugar_doc_comments: bool,
1223 trailing_semi: bool,
1225 impl CreateTokenStream for LazyTokenStreamImpl {
1226 fn create_token_stream(&self) -> TokenStream {
1227 let mut num_calls = self.num_calls;
1228 if self.trailing_semi {
1231 // The token produced by the final call to `next` or `next_desugared`
1232 // was not actually consumed by the callback. The combination
1233 // of chaining the initial token and using `take` produces the desired
1234 // result - we produce an empty `TokenStream` if no calls were made,
1235 // and omit the final token otherwise.
1236 let mut cursor_snapshot = self.cursor_snapshot.clone();
1237 let tokens = std::iter::once(self.start_token.clone())
1238 .chain((0..num_calls).map(|_| {
1239 if self.desugar_doc_comments {
1240 cursor_snapshot.next_desugared()
1242 cursor_snapshot.next()
1247 make_token_stream(tokens)
1249 fn add_trailing_semi(&self) -> Box<dyn CreateTokenStream> {
1250 if self.trailing_semi {
1251 panic!("Called `add_trailing_semi` twice!");
1253 let mut new = self.clone();
1254 new.trailing_semi = true;
1259 let lazy_impl = LazyTokenStreamImpl {
1261 num_calls: self.token_cursor.num_next_calls - cursor_snapshot.num_next_calls,
1263 desugar_doc_comments: self.desugar_doc_comments,
1264 trailing_semi: false,
1266 Ok((ret, Some(LazyTokenStream::new(lazy_impl))))
1270 fn is_import_coupler(&mut self) -> bool {
1271 self.check(&token::ModSep)
1272 && self.look_ahead(1, |t| {
1273 *t == token::OpenDelim(token::Brace) || *t == token::BinOp(token::Star)
1277 pub fn clear_expected_tokens(&mut self) {
1278 self.expected_tokens.clear();
1282 crate fn make_unclosed_delims_error(
1283 unmatched: UnmatchedBrace,
1285 ) -> Option<DiagnosticBuilder<'_>> {
1286 // `None` here means an `Eof` was found. We already emit those errors elsewhere, we add them to
1287 // `unmatched_braces` only for error recovery in the `Parser`.
1288 let found_delim = unmatched.found_delim?;
1289 let mut err = sess.span_diagnostic.struct_span_err(
1290 unmatched.found_span,
1292 "mismatched closing delimiter: `{}`",
1293 pprust::token_kind_to_string(&token::CloseDelim(found_delim)),
1296 err.span_label(unmatched.found_span, "mismatched closing delimiter");
1297 if let Some(sp) = unmatched.candidate_span {
1298 err.span_label(sp, "closing delimiter possibly meant for this");
1300 if let Some(sp) = unmatched.unclosed_span {
1301 err.span_label(sp, "unclosed delimiter");
1306 pub fn emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedBrace>, sess: &ParseSess) {
1307 *sess.reached_eof.borrow_mut() |=
1308 unclosed_delims.iter().any(|unmatched_delim| unmatched_delim.found_delim.is_none());
1309 for unmatched in unclosed_delims.drain(..) {
1310 if let Some(mut e) = make_unclosed_delims_error(unmatched, sess) {
1316 /// Converts a flattened iterator of tokens (including open and close delimiter tokens)
1317 /// into a `TokenStream`, creating a `TokenTree::Delimited` for each matching pair
1318 /// of open and close delims.
1319 fn make_token_stream(tokens: impl Iterator<Item = (Token, Spacing)>) -> TokenStream {
1323 inner: Vec<(TokenTree, Spacing)>,
1325 let mut stack = vec![FrameData { open: DUMMY_SP, inner: vec![] }];
1326 for (token, spacing) in tokens {
1328 Token { kind: TokenKind::OpenDelim(_), span } => {
1329 stack.push(FrameData { open: span, inner: vec![] });
1331 Token { kind: TokenKind::CloseDelim(delim), span } => {
1332 let frame_data = stack.pop().expect("Token stack was empty!");
1333 let dspan = DelimSpan::from_pair(frame_data.open, span);
1334 let stream = TokenStream::new(frame_data.inner);
1335 let delimited = TokenTree::Delimited(dspan, delim, stream);
1338 .unwrap_or_else(|| panic!("Bottom token frame is missing for tokens!"))
1340 .push((delimited, Spacing::Alone));
1344 .expect("Bottom token frame is missing!")
1346 .push((TokenTree::Token(token), spacing)),
1349 let final_buf = stack.pop().expect("Missing final buf!");
1350 assert!(stack.is_empty(), "Stack should be empty: final_buf={:?} stack={:?}", final_buf, stack);
1351 TokenStream::new(final_buf.inner)