1 use super::pat::{RecoverColon, RecoverComma, PARAM_EXPECTED};
2 use super::ty::{AllowPlus, RecoverQPath, RecoverReturnSign};
4 AttrWrapper, BlockMode, ClosureSpans, ForceCollect, Parser, PathStyle, Restrictions, TokenType,
6 use super::{SemiColonMode, SeqSep, TokenExpectType, TrailingToken};
7 use crate::maybe_recover_from_interpolated_ty_qpath;
9 use ast::token::DelimToken;
10 use rustc_ast::ptr::P;
11 use rustc_ast::token::{self, Token, TokenKind};
12 use rustc_ast::tokenstream::Spacing;
13 use rustc_ast::util::classify;
14 use rustc_ast::util::literal::LitError;
15 use rustc_ast::util::parser::{prec_let_scrutinee_needs_par, AssocOp, Fixity};
16 use rustc_ast::{self as ast, AttrStyle, AttrVec, CaptureBy, ExprField, Lit, UnOp, DUMMY_NODE_ID};
17 use rustc_ast::{AnonConst, BinOp, BinOpKind, FnDecl, FnRetTy, MacCall, Param, Ty, TyKind};
18 use rustc_ast::{Arm, Async, BlockCheckMode, Expr, ExprKind, Label, Movability, RangeLimits};
19 use rustc_ast_pretty::pprust;
20 use rustc_errors::{Applicability, DiagnosticBuilder, PResult};
21 use rustc_session::lint::builtin::BREAK_WITH_LABEL_AND_LOOP;
22 use rustc_session::lint::BuiltinLintDiagnostics;
23 use rustc_span::edition::LATEST_STABLE_EDITION;
24 use rustc_span::source_map::{self, Span, Spanned};
25 use rustc_span::symbol::{kw, sym, Ident, Symbol};
26 use rustc_span::{BytePos, Pos};
29 /// Possibly accepts an `token::Interpolated` expression (a pre-parsed expression
30 /// dropped into the token stream, which happens while parsing the result of
31 /// macro expansion). Placement of these is not as complex as I feared it would
32 /// be. The important thing is to make sure that lookahead doesn't balk at
33 /// `token::Interpolated` tokens.
34 macro_rules! maybe_whole_expr {
36 if let token::Interpolated(nt) = &$p.token.kind {
38 token::NtExpr(e) | token::NtLiteral(e) => {
43 token::NtPath(path) => {
44 let path = path.clone();
48 ExprKind::Path(None, path),
52 token::NtBlock(block) => {
53 let block = block.clone();
57 ExprKind::Block(block, None),
68 pub(super) enum LhsExpr {
70 AttributesParsed(AttrWrapper),
71 AlreadyParsed(P<Expr>),
74 impl From<Option<AttrWrapper>> for LhsExpr {
75 /// Converts `Some(attrs)` into `LhsExpr::AttributesParsed(attrs)`
76 /// and `None` into `LhsExpr::NotYetParsed`.
78 /// This conversion does not allocate.
79 fn from(o: Option<AttrWrapper>) -> Self {
80 if let Some(attrs) = o { LhsExpr::AttributesParsed(attrs) } else { LhsExpr::NotYetParsed }
84 impl From<P<Expr>> for LhsExpr {
85 /// Converts the `expr: P<Expr>` into `LhsExpr::AlreadyParsed(expr)`.
87 /// This conversion does not allocate.
88 fn from(expr: P<Expr>) -> Self {
89 LhsExpr::AlreadyParsed(expr)
94 /// Parses an expression.
96 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
97 self.current_closure.take();
99 self.parse_expr_res(Restrictions::empty(), None)
102 /// Parses an expression, forcing tokens to be collected
103 pub fn parse_expr_force_collect(&mut self) -> PResult<'a, P<Expr>> {
104 self.collect_tokens_no_attrs(|this| this.parse_expr())
107 pub fn parse_anon_const_expr(&mut self) -> PResult<'a, AnonConst> {
108 self.parse_expr().map(|value| AnonConst { id: DUMMY_NODE_ID, value })
111 fn parse_expr_catch_underscore(&mut self) -> PResult<'a, P<Expr>> {
112 match self.parse_expr() {
113 Ok(expr) => Ok(expr),
114 Err(mut err) => match self.token.ident() {
115 Some((Ident { name: kw::Underscore, .. }, false))
116 if self.look_ahead(1, |t| t == &token::Comma) =>
118 // Special-case handling of `foo(_, _, _)`
121 Ok(self.mk_expr(self.prev_token.span, ExprKind::Err, AttrVec::new()))
128 /// Parses a sequence of expressions delimited by parentheses.
129 fn parse_paren_expr_seq(&mut self) -> PResult<'a, Vec<P<Expr>>> {
130 self.parse_paren_comma_seq(|p| p.parse_expr_catch_underscore()).map(|(r, _)| r)
133 /// Parses an expression, subject to the given restrictions.
135 pub(super) fn parse_expr_res(
138 already_parsed_attrs: Option<AttrWrapper>,
139 ) -> PResult<'a, P<Expr>> {
140 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
143 /// Parses an associative expression.
145 /// This parses an expression accounting for associativity and precedence of the operators in
150 already_parsed_attrs: Option<AttrWrapper>,
151 ) -> PResult<'a, P<Expr>> {
152 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
155 /// Parses an associative expression with operators of at least `min_prec` precedence.
156 pub(super) fn parse_assoc_expr_with(
160 ) -> PResult<'a, P<Expr>> {
161 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
164 let attrs = match lhs {
165 LhsExpr::AttributesParsed(attrs) => Some(attrs),
168 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token.kind) {
169 return self.parse_prefix_range_expr(attrs);
171 self.parse_prefix_expr(attrs)?
174 let last_type_ascription_set = self.last_type_ascription.is_some();
176 if !self.should_continue_as_assoc_expr(&lhs) {
177 self.last_type_ascription = None;
181 self.expected_tokens.push(TokenType::Operator);
182 while let Some(op) = self.check_assoc_op() {
183 // Adjust the span for interpolated LHS to point to the `$lhs` token
184 // and not to what it refers to.
185 let lhs_span = match self.prev_token.kind {
186 TokenKind::Interpolated(..) => self.prev_token.span,
190 let cur_op_span = self.token.span;
191 let restrictions = if op.node.is_assign_like() {
192 self.restrictions & Restrictions::NO_STRUCT_LITERAL
196 let prec = op.node.precedence();
200 // Check for deprecated `...` syntax
201 if self.token == token::DotDotDot && op.node == AssocOp::DotDotEq {
202 self.err_dotdotdot_syntax(self.token.span);
205 if self.token == token::LArrow {
206 self.err_larrow_operator(self.token.span);
210 if op.node.is_comparison() {
211 if let Some(expr) = self.check_no_chained_comparison(&lhs, &op)? {
216 if (op.node == AssocOp::Equal || op.node == AssocOp::NotEqual)
217 && self.token.kind == token::Eq
218 && self.prev_token.span.hi() == self.token.span.lo()
220 // Look for JS' `===` and `!==` and recover 😇
221 let sp = op.span.to(self.token.span);
222 let sugg = match op.node {
223 AssocOp::Equal => "==",
224 AssocOp::NotEqual => "!=",
227 self.struct_span_err(sp, &format!("invalid comparison operator `{}=`", sugg))
228 .span_suggestion_short(
230 &format!("`{s}=` is not a valid comparison operator, use `{s}`", s = sugg),
232 Applicability::MachineApplicable,
240 if op == AssocOp::As {
241 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
243 } else if op == AssocOp::Colon {
244 lhs = self.parse_assoc_op_ascribe(lhs, lhs_span)?;
246 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
247 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
248 // generalise it to the Fixity::None code.
249 lhs = self.parse_range_expr(prec, lhs, op, cur_op_span)?;
253 let fixity = op.fixity();
254 let prec_adjustment = match fixity {
257 // We currently have no non-associative operators that are not handled above by
258 // the special cases. The code is here only for future convenience.
261 let rhs = self.with_res(restrictions - Restrictions::STMT_EXPR, |this| {
262 this.parse_assoc_expr_with(prec + prec_adjustment, LhsExpr::NotYetParsed)
265 let span = self.mk_expr_sp(&lhs, lhs_span, rhs.span);
278 | AssocOp::ShiftRight
284 | AssocOp::GreaterEqual => {
285 let ast_op = op.to_ast_binop().unwrap();
286 let binary = self.mk_binary(source_map::respan(cur_op_span, ast_op), lhs, rhs);
287 self.mk_expr(span, binary, AttrVec::new())
290 self.mk_expr(span, ExprKind::Assign(lhs, rhs, cur_op_span), AttrVec::new())
292 AssocOp::AssignOp(k) => {
294 token::Plus => BinOpKind::Add,
295 token::Minus => BinOpKind::Sub,
296 token::Star => BinOpKind::Mul,
297 token::Slash => BinOpKind::Div,
298 token::Percent => BinOpKind::Rem,
299 token::Caret => BinOpKind::BitXor,
300 token::And => BinOpKind::BitAnd,
301 token::Or => BinOpKind::BitOr,
302 token::Shl => BinOpKind::Shl,
303 token::Shr => BinOpKind::Shr,
305 let aopexpr = self.mk_assign_op(source_map::respan(cur_op_span, aop), lhs, rhs);
306 self.mk_expr(span, aopexpr, AttrVec::new())
308 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
309 self.span_bug(span, "AssocOp should have been handled by special case")
313 if let Fixity::None = fixity {
317 if last_type_ascription_set {
318 self.last_type_ascription = None;
323 fn should_continue_as_assoc_expr(&mut self, lhs: &Expr) -> bool {
324 match (self.expr_is_complete(lhs), AssocOp::from_token(&self.token)) {
325 // Semi-statement forms are odd:
326 // See https://github.com/rust-lang/rust/issues/29071
327 (true, None) => false,
328 (false, _) => true, // Continue parsing the expression.
329 // An exhaustive check is done in the following block, but these are checked first
330 // because they *are* ambiguous but also reasonable looking incorrect syntax, so we
331 // want to keep their span info to improve diagnostics in these cases in a later stage.
332 (true, Some(AssocOp::Multiply)) | // `{ 42 } *foo = bar;` or `{ 42 } * 3`
333 (true, Some(AssocOp::Subtract)) | // `{ 42 } -5`
334 (true, Some(AssocOp::Add)) // `{ 42 } + 42
335 // If the next token is a keyword, then the tokens above *are* unambiguously incorrect:
336 // `if x { a } else { b } && if y { c } else { d }`
337 if !self.look_ahead(1, |t| t.is_used_keyword()) => {
338 // These cases are ambiguous and can't be identified in the parser alone.
339 let sp = self.sess.source_map().start_point(self.token.span);
340 self.sess.ambiguous_block_expr_parse.borrow_mut().insert(sp, lhs.span);
343 (true, Some(AssocOp::LAnd)) => {
344 // `{ 42 } &&x` (#61475) or `{ 42 } && if x { 1 } else { 0 }`. Separated from the
345 // above due to #74233.
346 // These cases are ambiguous and can't be identified in the parser alone.
347 let sp = self.sess.source_map().start_point(self.token.span);
348 self.sess.ambiguous_block_expr_parse.borrow_mut().insert(sp, lhs.span);
351 (true, Some(ref op)) if !op.can_continue_expr_unambiguously() => false,
353 self.error_found_expr_would_be_stmt(lhs);
359 /// We've found an expression that would be parsed as a statement,
360 /// but the next token implies this should be parsed as an expression.
361 /// For example: `if let Some(x) = x { x } else { 0 } / 2`.
362 fn error_found_expr_would_be_stmt(&self, lhs: &Expr) {
363 let mut err = self.struct_span_err(
365 &format!("expected expression, found `{}`", pprust::token_to_string(&self.token),),
367 err.span_label(self.token.span, "expected expression");
368 self.sess.expr_parentheses_needed(&mut err, lhs.span);
372 /// Possibly translate the current token to an associative operator.
373 /// The method does not advance the current token.
375 /// Also performs recovery for `and` / `or` which are mistaken for `&&` and `||` respectively.
376 fn check_assoc_op(&self) -> Option<Spanned<AssocOp>> {
377 let (op, span) = match (AssocOp::from_token(&self.token), self.token.ident()) {
378 // When parsing const expressions, stop parsing when encountering `>`.
383 | AssocOp::GreaterEqual
384 | AssocOp::AssignOp(token::BinOpToken::Shr),
387 ) if self.restrictions.contains(Restrictions::CONST_EXPR) => {
390 (Some(op), _) => (op, self.token.span),
391 (None, Some((Ident { name: sym::and, span }, false))) => {
392 self.error_bad_logical_op("and", "&&", "conjunction");
393 (AssocOp::LAnd, span)
395 (None, Some((Ident { name: sym::or, span }, false))) => {
396 self.error_bad_logical_op("or", "||", "disjunction");
401 Some(source_map::respan(span, op))
404 /// Error on `and` and `or` suggesting `&&` and `||` respectively.
405 fn error_bad_logical_op(&self, bad: &str, good: &str, english: &str) {
406 self.struct_span_err(self.token.span, &format!("`{}` is not a logical operator", bad))
407 .span_suggestion_short(
409 &format!("use `{}` to perform logical {}", good, english),
411 Applicability::MachineApplicable,
413 .note("unlike in e.g., python and PHP, `&&` and `||` are used for logical operators")
417 /// Checks if this expression is a successfully parsed statement.
418 fn expr_is_complete(&self, e: &Expr) -> bool {
419 self.restrictions.contains(Restrictions::STMT_EXPR)
420 && !classify::expr_requires_semi_to_be_stmt(e)
423 /// Parses `x..y`, `x..=y`, and `x..`/`x..=`.
424 /// The other two variants are handled in `parse_prefix_range_expr` below.
431 ) -> PResult<'a, P<Expr>> {
432 let rhs = if self.is_at_start_of_range_notation_rhs() {
433 Some(self.parse_assoc_expr_with(prec + 1, LhsExpr::NotYetParsed)?)
437 let rhs_span = rhs.as_ref().map_or(cur_op_span, |x| x.span);
438 let span = self.mk_expr_sp(&lhs, lhs.span, rhs_span);
440 if op == AssocOp::DotDot { RangeLimits::HalfOpen } else { RangeLimits::Closed };
441 let range = self.mk_range(Some(lhs), rhs, limits);
442 Ok(self.mk_expr(span, range, AttrVec::new()))
445 fn is_at_start_of_range_notation_rhs(&self) -> bool {
446 if self.token.can_begin_expr() {
447 // Parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
448 if self.token == token::OpenDelim(token::Brace) {
449 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
457 /// Parses prefix-forms of range notation: `..expr`, `..`, `..=expr`.
458 fn parse_prefix_range_expr(&mut self, attrs: Option<AttrWrapper>) -> PResult<'a, P<Expr>> {
459 // Check for deprecated `...` syntax.
460 if self.token == token::DotDotDot {
461 self.err_dotdotdot_syntax(self.token.span);
465 [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token.kind),
466 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
470 let limits = match self.token.kind {
471 token::DotDot => RangeLimits::HalfOpen,
472 _ => RangeLimits::Closed,
474 let op = AssocOp::from_token(&self.token);
475 // FIXME: `parse_prefix_range_expr` is called when the current
476 // token is `DotDot`, `DotDotDot`, or `DotDotEq`. If we haven't already
477 // parsed attributes, then trying to parse them here will always fail.
478 // We should figure out how we want attributes on range expressions to work.
479 let attrs = self.parse_or_use_outer_attributes(attrs)?;
480 self.collect_tokens_for_expr(attrs, |this, attrs| {
481 let lo = this.token.span;
483 let (span, opt_end) = if this.is_at_start_of_range_notation_rhs() {
484 // RHS must be parsed with more associativity than the dots.
485 this.parse_assoc_expr_with(op.unwrap().precedence() + 1, LhsExpr::NotYetParsed)
486 .map(|x| (lo.to(x.span), Some(x)))?
490 let range = this.mk_range(None, opt_end, limits);
491 Ok(this.mk_expr(span, range, attrs.into()))
495 /// Parses a prefix-unary-operator expr.
496 fn parse_prefix_expr(&mut self, attrs: Option<AttrWrapper>) -> PResult<'a, P<Expr>> {
497 let attrs = self.parse_or_use_outer_attributes(attrs)?;
498 let lo = self.token.span;
500 macro_rules! make_it {
501 ($this:ident, $attrs:expr, |this, _| $body:expr) => {
502 $this.collect_tokens_for_expr($attrs, |$this, attrs| {
503 let (hi, ex) = $body?;
504 Ok($this.mk_expr(lo.to(hi), ex, attrs.into()))
511 // Note: when adding new unary operators, don't forget to adjust TokenKind::can_begin_expr()
512 match this.token.uninterpolate().kind {
513 token::Not => make_it!(this, attrs, |this, _| this.parse_unary_expr(lo, UnOp::Not)), // `!expr`
514 token::Tilde => make_it!(this, attrs, |this, _| this.recover_tilde_expr(lo)), // `~expr`
515 token::BinOp(token::Minus) => {
516 make_it!(this, attrs, |this, _| this.parse_unary_expr(lo, UnOp::Neg))
518 token::BinOp(token::Star) => {
519 make_it!(this, attrs, |this, _| this.parse_unary_expr(lo, UnOp::Deref))
521 token::BinOp(token::And) | token::AndAnd => {
522 make_it!(this, attrs, |this, _| this.parse_borrow_expr(lo))
524 token::BinOp(token::Plus) if this.look_ahead(1, |tok| tok.is_numeric_lit()) => {
525 let mut err = this.struct_span_err(lo, "leading `+` is not supported");
526 err.span_label(lo, "unexpected `+`");
528 // a block on the LHS might have been intended to be an expression instead
529 if let Some(sp) = this.sess.ambiguous_block_expr_parse.borrow().get(&lo) {
530 this.sess.expr_parentheses_needed(&mut err, *sp);
532 err.span_suggestion_verbose(
534 "try removing the `+`",
536 Applicability::MachineApplicable,
542 this.parse_prefix_expr(None)
544 token::Ident(..) if this.token.is_keyword(kw::Box) => {
545 make_it!(this, attrs, |this, _| this.parse_box_expr(lo))
547 token::Ident(..) if this.is_mistaken_not_ident_negation() => {
548 make_it!(this, attrs, |this, _| this.recover_not_expr(lo))
550 _ => return this.parse_dot_or_call_expr(Some(attrs)),
554 fn parse_prefix_expr_common(&mut self, lo: Span) -> PResult<'a, (Span, P<Expr>)> {
556 let expr = self.parse_prefix_expr(None);
557 let (span, expr) = self.interpolated_or_expr_span(expr)?;
558 Ok((lo.to(span), expr))
561 fn parse_unary_expr(&mut self, lo: Span, op: UnOp) -> PResult<'a, (Span, ExprKind)> {
562 let (span, expr) = self.parse_prefix_expr_common(lo)?;
563 Ok((span, self.mk_unary(op, expr)))
566 // Recover on `!` suggesting for bitwise negation instead.
567 fn recover_tilde_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
568 self.struct_span_err(lo, "`~` cannot be used as a unary operator")
569 .span_suggestion_short(
571 "use `!` to perform bitwise not",
573 Applicability::MachineApplicable,
577 self.parse_unary_expr(lo, UnOp::Not)
580 /// Parse `box expr`.
581 fn parse_box_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
582 let (span, expr) = self.parse_prefix_expr_common(lo)?;
583 self.sess.gated_spans.gate(sym::box_syntax, span);
584 Ok((span, ExprKind::Box(expr)))
587 fn is_mistaken_not_ident_negation(&self) -> bool {
588 let token_cannot_continue_expr = |t: &Token| match t.uninterpolate().kind {
589 // These tokens can start an expression after `!`, but
590 // can't continue an expression after an ident
591 token::Ident(name, is_raw) => token::ident_can_begin_expr(name, t.span, is_raw),
592 token::Literal(..) | token::Pound => true,
593 _ => t.is_whole_expr(),
595 self.token.is_ident_named(sym::not) && self.look_ahead(1, token_cannot_continue_expr)
598 /// Recover on `not expr` in favor of `!expr`.
599 fn recover_not_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
601 let not_token = self.look_ahead(1, |t| t.clone());
602 self.struct_span_err(
604 &format!("unexpected {} after identifier", super::token_descr(¬_token)),
606 .span_suggestion_short(
607 // Span the `not` plus trailing whitespace to avoid
608 // trailing whitespace after the `!` in our suggestion
609 self.sess.source_map().span_until_non_whitespace(lo.to(not_token.span)),
610 "use `!` to perform logical negation",
612 Applicability::MachineApplicable,
617 self.parse_unary_expr(lo, UnOp::Not)
620 /// Returns the span of expr, if it was not interpolated or the span of the interpolated token.
621 fn interpolated_or_expr_span(
623 expr: PResult<'a, P<Expr>>,
624 ) -> PResult<'a, (Span, P<Expr>)> {
627 match self.prev_token.kind {
628 TokenKind::Interpolated(..) => self.prev_token.span,
636 fn parse_assoc_op_cast(
640 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind,
641 ) -> PResult<'a, P<Expr>> {
642 let mk_expr = |this: &mut Self, lhs: P<Expr>, rhs: P<Ty>| {
644 this.mk_expr_sp(&lhs, lhs_span, rhs.span),
650 // Save the state of the parser before parsing type normally, in case there is a
651 // LessThan comparison after this cast.
652 let parser_snapshot_before_type = self.clone();
653 let cast_expr = match self.parse_ty_no_plus() {
654 Ok(rhs) => mk_expr(self, lhs, rhs),
655 Err(mut type_err) => {
656 // Rewind to before attempting to parse the type with generics, to recover
657 // from situations like `x as usize < y` in which we first tried to parse
658 // `usize < y` as a type with generic arguments.
659 let parser_snapshot_after_type = mem::replace(self, parser_snapshot_before_type);
661 // Check for typo of `'a: loop { break 'a }` with a missing `'`.
662 match (&lhs.kind, &self.token.kind) {
665 ExprKind::Path(None, ast::Path { segments, .. }),
666 TokenKind::Ident(kw::For | kw::Loop | kw::While, false),
667 ) if segments.len() == 1 => {
668 let snapshot = self.clone();
670 ident: Ident::from_str_and_span(
671 &format!("'{}", segments[0].ident),
672 segments[0].ident.span,
675 match self.parse_labeled_expr(label, AttrVec::new(), false) {
678 self.struct_span_err(label.ident.span, "malformed loop label")
681 "use the correct loop label format",
682 label.ident.to_string(),
683 Applicability::MachineApplicable,
697 match self.parse_path(PathStyle::Expr) {
699 let (op_noun, op_verb) = match self.token.kind {
700 token::Lt => ("comparison", "comparing"),
701 token::BinOp(token::Shl) => ("shift", "shifting"),
703 // We can end up here even without `<` being the next token, for
704 // example because `parse_ty_no_plus` returns `Err` on keywords,
705 // but `parse_path` returns `Ok` on them due to error recovery.
706 // Return original error and parser state.
707 *self = parser_snapshot_after_type;
708 return Err(type_err);
712 // Successfully parsed the type path leaving a `<` yet to parse.
715 // Report non-fatal diagnostics, keep `x as usize` as an expression
716 // in AST and continue parsing.
718 "`<` is interpreted as a start of generic arguments for `{}`, not a {}",
719 pprust::path_to_string(&path),
722 let span_after_type = parser_snapshot_after_type.token.span;
724 mk_expr(self, lhs, self.mk_ty(path.span, TyKind::Path(None, path)));
726 self.struct_span_err(self.token.span, &msg)
728 self.look_ahead(1, |t| t.span).to(span_after_type),
729 "interpreted as generic arguments",
731 .span_label(self.token.span, format!("not interpreted as {}", op_noun))
732 .multipart_suggestion(
733 &format!("try {} the cast value", op_verb),
735 (expr.span.shrink_to_lo(), "(".to_string()),
736 (expr.span.shrink_to_hi(), ")".to_string()),
738 Applicability::MachineApplicable,
744 Err(mut path_err) => {
745 // Couldn't parse as a path, return original error and parser state.
747 *self = parser_snapshot_after_type;
748 return Err(type_err);
754 self.parse_and_disallow_postfix_after_cast(cast_expr)
757 /// Parses a postfix operators such as `.`, `?`, or index (`[]`) after a cast,
758 /// then emits an error and returns the newly parsed tree.
759 /// The resulting parse tree for `&x as T[0]` has a precedence of `((&x) as T)[0]`.
760 fn parse_and_disallow_postfix_after_cast(
763 ) -> PResult<'a, P<Expr>> {
764 // Save the memory location of expr before parsing any following postfix operators.
765 // This will be compared with the memory location of the output expression.
766 // If they different we can assume we parsed another expression because the existing expression is not reallocated.
767 let addr_before = &*cast_expr as *const _ as usize;
768 let span = cast_expr.span;
769 let with_postfix = self.parse_dot_or_call_expr_with_(cast_expr, span)?;
770 let changed = addr_before != &*with_postfix as *const _ as usize;
772 // Check if an illegal postfix operator has been added after the cast.
773 // If the resulting expression is not a cast, or has a different memory location, it is an illegal postfix operator.
774 if !matches!(with_postfix.kind, ExprKind::Cast(_, _) | ExprKind::Type(_, _)) || changed {
776 "casts cannot be followed by {}",
777 match with_postfix.kind {
778 ExprKind::Index(_, _) => "indexing",
779 ExprKind::Try(_) => "?",
780 ExprKind::Field(_, _) => "a field access",
781 ExprKind::MethodCall(_, _, _) => "a method call",
782 ExprKind::Call(_, _) => "a function call",
783 ExprKind::Await(_) => "`.await`",
784 ExprKind::Err => return Ok(with_postfix),
785 _ => unreachable!("parse_dot_or_call_expr_with_ shouldn't produce this"),
788 let mut err = self.struct_span_err(span, &msg);
789 // If type ascription is "likely an error", the user will already be getting a useful
790 // help message, and doesn't need a second.
791 if self.last_type_ascription.map_or(false, |last_ascription| last_ascription.1) {
792 self.maybe_annotate_with_ascription(&mut err, false);
794 let suggestions = vec![
795 (span.shrink_to_lo(), "(".to_string()),
796 (span.shrink_to_hi(), ")".to_string()),
798 err.multipart_suggestion(
799 "try surrounding the expression in parentheses",
801 Applicability::MachineApplicable,
809 fn parse_assoc_op_ascribe(&mut self, lhs: P<Expr>, lhs_span: Span) -> PResult<'a, P<Expr>> {
810 let maybe_path = self.could_ascription_be_path(&lhs.kind);
811 self.last_type_ascription = Some((self.prev_token.span, maybe_path));
812 let lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type)?;
813 self.sess.gated_spans.gate(sym::type_ascription, lhs.span);
817 /// Parse `& mut? <expr>` or `& raw [ const | mut ] <expr>`.
818 fn parse_borrow_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
820 let has_lifetime = self.token.is_lifetime() && self.look_ahead(1, |t| t != &token::Colon);
821 let lifetime = has_lifetime.then(|| self.expect_lifetime()); // For recovery, see below.
822 let (borrow_kind, mutbl) = self.parse_borrow_modifiers(lo);
823 let expr = self.parse_prefix_expr(None);
824 let (hi, expr) = self.interpolated_or_expr_span(expr)?;
825 let span = lo.to(hi);
826 if let Some(lt) = lifetime {
827 self.error_remove_borrow_lifetime(span, lt.ident.span);
829 Ok((span, ExprKind::AddrOf(borrow_kind, mutbl, expr)))
832 fn error_remove_borrow_lifetime(&self, span: Span, lt_span: Span) {
833 self.struct_span_err(span, "borrow expressions cannot be annotated with lifetimes")
834 .span_label(lt_span, "annotated with lifetime here")
837 "remove the lifetime annotation",
839 Applicability::MachineApplicable,
844 /// Parse `mut?` or `raw [ const | mut ]`.
845 fn parse_borrow_modifiers(&mut self, lo: Span) -> (ast::BorrowKind, ast::Mutability) {
846 if self.check_keyword(kw::Raw) && self.look_ahead(1, Token::is_mutability) {
847 // `raw [ const | mut ]`.
848 let found_raw = self.eat_keyword(kw::Raw);
850 let mutability = self.parse_const_or_mut().unwrap();
851 self.sess.gated_spans.gate(sym::raw_ref_op, lo.to(self.prev_token.span));
852 (ast::BorrowKind::Raw, mutability)
855 (ast::BorrowKind::Ref, self.parse_mutability())
859 /// Parses `a.b` or `a(13)` or `a[4]` or just `a`.
860 fn parse_dot_or_call_expr(&mut self, attrs: Option<AttrWrapper>) -> PResult<'a, P<Expr>> {
861 let attrs = self.parse_or_use_outer_attributes(attrs)?;
862 self.collect_tokens_for_expr(attrs, |this, attrs| {
863 let base = this.parse_bottom_expr();
864 let (span, base) = this.interpolated_or_expr_span(base)?;
865 this.parse_dot_or_call_expr_with(base, span, attrs)
869 pub(super) fn parse_dot_or_call_expr_with(
873 mut attrs: Vec<ast::Attribute>,
874 ) -> PResult<'a, P<Expr>> {
875 // Stitch the list of outer attributes onto the return value.
876 // A little bit ugly, but the best way given the current code
878 self.parse_dot_or_call_expr_with_(e0, lo).map(|expr| {
879 expr.map(|mut expr| {
880 attrs.extend::<Vec<_>>(expr.attrs.into());
881 expr.attrs = attrs.into();
887 fn parse_dot_or_call_expr_with_(&mut self, mut e: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
889 if self.eat(&token::Question) {
891 e = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Try(e), AttrVec::new());
894 if self.eat(&token::Dot) {
896 e = self.parse_dot_suffix_expr(lo, e)?;
899 if self.expr_is_complete(&e) {
902 e = match self.token.kind {
903 token::OpenDelim(token::Paren) => self.parse_fn_call_expr(lo, e),
904 token::OpenDelim(token::Bracket) => self.parse_index_expr(lo, e)?,
910 fn parse_dot_suffix_expr(&mut self, lo: Span, base: P<Expr>) -> PResult<'a, P<Expr>> {
911 match self.token.uninterpolate().kind {
912 token::Ident(..) => self.parse_dot_suffix(base, lo),
913 token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) => {
914 Ok(self.parse_tuple_field_access_expr(lo, base, symbol, suffix, None))
916 token::Literal(token::Lit { kind: token::Float, symbol, suffix }) => {
917 Ok(self.parse_tuple_field_access_expr_float(lo, base, symbol, suffix))
920 self.error_unexpected_after_dot();
926 fn error_unexpected_after_dot(&self) {
927 // FIXME Could factor this out into non_fatal_unexpected or something.
928 let actual = pprust::token_to_string(&self.token);
929 self.struct_span_err(self.token.span, &format!("unexpected token: `{}`", actual)).emit();
932 // We need an identifier or integer, but the next token is a float.
933 // Break the float into components to extract the identifier or integer.
934 // FIXME: With current `TokenCursor` it's hard to break tokens into more than 2
935 // parts unless those parts are processed immediately. `TokenCursor` should either
936 // support pushing "future tokens" (would be also helpful to `break_and_eat`), or
937 // we should break everything including floats into more basic proc-macro style
938 // tokens in the lexer (probably preferable).
939 fn parse_tuple_field_access_expr_float(
944 suffix: Option<Symbol>,
947 enum FloatComponent {
951 use FloatComponent::*;
953 let float_str = float.as_str();
954 let mut components = Vec::new();
955 let mut ident_like = String::new();
956 for c in float_str.chars() {
957 if c == '_' || c.is_ascii_alphanumeric() {
959 } else if matches!(c, '.' | '+' | '-') {
960 if !ident_like.is_empty() {
961 components.push(IdentLike(mem::take(&mut ident_like)));
963 components.push(Punct(c));
965 panic!("unexpected character in a float token: {:?}", c)
968 if !ident_like.is_empty() {
969 components.push(IdentLike(ident_like));
972 // With proc macros the span can refer to anything, the source may be too short,
973 // or too long, or non-ASCII. It only makes sense to break our span into components
974 // if its underlying text is identical to our float literal.
975 let span = self.token.span;
976 let can_take_span_apart =
977 || self.span_to_snippet(span).as_deref() == Ok(float_str).as_deref();
982 self.parse_tuple_field_access_expr(lo, base, Symbol::intern(&i), suffix, None)
985 [IdentLike(i), Punct('.')] => {
986 let (ident_span, dot_span) = if can_take_span_apart() {
987 let (span, ident_len) = (span.data(), BytePos::from_usize(i.len()));
988 let ident_span = span.with_hi(span.lo + ident_len);
989 let dot_span = span.with_lo(span.lo + ident_len);
990 (ident_span, dot_span)
994 assert!(suffix.is_none());
995 let symbol = Symbol::intern(&i);
996 self.token = Token::new(token::Ident(symbol, false), ident_span);
997 let next_token = (Token::new(token::Dot, dot_span), self.token_spacing);
998 self.parse_tuple_field_access_expr(lo, base, symbol, None, Some(next_token))
1001 [IdentLike(i1), Punct('.'), IdentLike(i2)] => {
1002 let (ident1_span, dot_span, ident2_span) = if can_take_span_apart() {
1003 let (span, ident1_len) = (span.data(), BytePos::from_usize(i1.len()));
1004 let ident1_span = span.with_hi(span.lo + ident1_len);
1006 .with_lo(span.lo + ident1_len)
1007 .with_hi(span.lo + ident1_len + BytePos(1));
1008 let ident2_span = self.token.span.with_lo(span.lo + ident1_len + BytePos(1));
1009 (ident1_span, dot_span, ident2_span)
1013 let symbol1 = Symbol::intern(&i1);
1014 self.token = Token::new(token::Ident(symbol1, false), ident1_span);
1015 // This needs to be `Spacing::Alone` to prevent regressions.
1016 // See issue #76399 and PR #76285 for more details
1017 let next_token1 = (Token::new(token::Dot, dot_span), Spacing::Alone);
1019 self.parse_tuple_field_access_expr(lo, base, symbol1, None, Some(next_token1));
1020 let symbol2 = Symbol::intern(&i2);
1021 let next_token2 = Token::new(token::Ident(symbol2, false), ident2_span);
1022 self.bump_with((next_token2, self.token_spacing)); // `.`
1023 self.parse_tuple_field_access_expr(lo, base1, symbol2, suffix, None)
1025 // 1e+ | 1e- (recovered)
1026 [IdentLike(_), Punct('+' | '-')] |
1028 [IdentLike(_), Punct('+' | '-'), IdentLike(_)] |
1030 [IdentLike(_), Punct('.'), IdentLike(_), Punct('+' | '-'), IdentLike(_)] => {
1031 // See the FIXME about `TokenCursor` above.
1032 self.error_unexpected_after_dot();
1035 _ => panic!("unexpected components in a float token: {:?}", components),
1039 fn parse_tuple_field_access_expr(
1044 suffix: Option<Symbol>,
1045 next_token: Option<(Token, Spacing)>,
1048 Some(next_token) => self.bump_with(next_token),
1049 None => self.bump(),
1051 let span = self.prev_token.span;
1052 let field = ExprKind::Field(base, Ident::new(field, span));
1053 self.expect_no_suffix(span, "a tuple index", suffix);
1054 self.mk_expr(lo.to(span), field, AttrVec::new())
1057 /// Parse a function call expression, `expr(...)`.
1058 fn parse_fn_call_expr(&mut self, lo: Span, fun: P<Expr>) -> P<Expr> {
1059 let seq = self.parse_paren_expr_seq().map(|args| {
1060 self.mk_expr(lo.to(self.prev_token.span), self.mk_call(fun, args), AttrVec::new())
1062 self.recover_seq_parse_error(token::Paren, lo, seq)
1065 /// Parse an indexing expression `expr[...]`.
1066 fn parse_index_expr(&mut self, lo: Span, base: P<Expr>) -> PResult<'a, P<Expr>> {
1068 let index = self.parse_expr()?;
1069 self.expect(&token::CloseDelim(token::Bracket))?;
1070 Ok(self.mk_expr(lo.to(self.prev_token.span), self.mk_index(base, index), AttrVec::new()))
1073 /// Assuming we have just parsed `.`, continue parsing into an expression.
1074 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
1075 if self.token.uninterpolated_span().rust_2018() && self.eat_keyword(kw::Await) {
1076 return Ok(self.mk_await_expr(self_arg, lo));
1079 let fn_span_lo = self.token.span;
1080 let mut segment = self.parse_path_segment(PathStyle::Expr)?;
1081 self.check_trailing_angle_brackets(&segment, &[&token::OpenDelim(token::Paren)]);
1082 self.check_turbofish_missing_angle_brackets(&mut segment);
1084 if self.check(&token::OpenDelim(token::Paren)) {
1085 // Method call `expr.f()`
1086 let mut args = self.parse_paren_expr_seq()?;
1087 args.insert(0, self_arg);
1089 let fn_span = fn_span_lo.to(self.prev_token.span);
1090 let span = lo.to(self.prev_token.span);
1091 Ok(self.mk_expr(span, ExprKind::MethodCall(segment, args, fn_span), AttrVec::new()))
1093 // Field access `expr.f`
1094 if let Some(args) = segment.args {
1095 self.struct_span_err(
1097 "field expressions cannot have generic arguments",
1102 let span = lo.to(self.prev_token.span);
1103 Ok(self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), AttrVec::new()))
1107 /// At the bottom (top?) of the precedence hierarchy,
1108 /// Parses things like parenthesized exprs, macros, `return`, etc.
1110 /// N.B., this does not parse outer attributes, and is private because it only works
1111 /// correctly if called from `parse_dot_or_call_expr()`.
1112 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
1113 maybe_recover_from_interpolated_ty_qpath!(self, true);
1114 maybe_whole_expr!(self);
1116 // Outer attributes are already parsed and will be
1117 // added to the return value after the fact.
1119 // Therefore, prevent sub-parser from parsing
1120 // attributes by giving them an empty "already-parsed" list.
1121 let attrs = AttrVec::new();
1123 // Note: when adding new syntax here, don't forget to adjust `TokenKind::can_begin_expr()`.
1124 let lo = self.token.span;
1125 if let token::Literal(_) = self.token.kind {
1126 // This match arm is a special-case of the `_` match arm below and
1127 // could be removed without changing functionality, but it's faster
1128 // to have it here, especially for programs with large constants.
1129 self.parse_lit_expr(attrs)
1130 } else if self.check(&token::OpenDelim(token::Paren)) {
1131 self.parse_tuple_parens_expr(attrs)
1132 } else if self.check(&token::OpenDelim(token::Brace)) {
1133 self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs)
1134 } else if self.check(&token::BinOp(token::Or)) || self.check(&token::OrOr) {
1135 self.parse_closure_expr(attrs)
1136 } else if self.check(&token::OpenDelim(token::Bracket)) {
1137 self.parse_array_or_repeat_expr(attrs)
1138 } else if self.check_path() {
1139 self.parse_path_start_expr(attrs)
1140 } else if self.check_keyword(kw::Move) || self.check_keyword(kw::Static) {
1141 self.parse_closure_expr(attrs)
1142 } else if self.eat_keyword(kw::If) {
1143 self.parse_if_expr(attrs)
1144 } else if self.check_keyword(kw::For) {
1145 if self.choose_generics_over_qpath(1) {
1146 // NOTE(Centril, eddyb): DO NOT REMOVE! Beyond providing parser recovery,
1147 // this is an insurance policy in case we allow qpaths in (tuple-)struct patterns.
1148 // When `for <Foo as Bar>::Proj in $expr $block` is wanted,
1149 // you can disambiguate in favor of a pattern with `(...)`.
1150 self.recover_quantified_closure_expr(attrs)
1152 assert!(self.eat_keyword(kw::For));
1153 self.parse_for_expr(None, self.prev_token.span, attrs)
1155 } else if self.eat_keyword(kw::While) {
1156 self.parse_while_expr(None, self.prev_token.span, attrs)
1157 } else if let Some(label) = self.eat_label() {
1158 self.parse_labeled_expr(label, attrs, true)
1159 } else if self.eat_keyword(kw::Loop) {
1160 self.parse_loop_expr(None, self.prev_token.span, attrs)
1161 } else if self.eat_keyword(kw::Continue) {
1162 let kind = ExprKind::Continue(self.eat_label());
1163 Ok(self.mk_expr(lo.to(self.prev_token.span), kind, attrs))
1164 } else if self.eat_keyword(kw::Match) {
1165 let match_sp = self.prev_token.span;
1166 self.parse_match_expr(attrs).map_err(|mut err| {
1167 err.span_label(match_sp, "while parsing this match expression");
1170 } else if self.eat_keyword(kw::Unsafe) {
1171 self.parse_block_expr(None, lo, BlockCheckMode::Unsafe(ast::UserProvided), attrs)
1172 } else if self.check_inline_const(0) {
1173 self.parse_const_block(lo.to(self.token.span))
1174 } else if self.is_do_catch_block() {
1175 self.recover_do_catch(attrs)
1176 } else if self.is_try_block() {
1177 self.expect_keyword(kw::Try)?;
1178 self.parse_try_block(lo, attrs)
1179 } else if self.eat_keyword(kw::Return) {
1180 self.parse_return_expr(attrs)
1181 } else if self.eat_keyword(kw::Break) {
1182 self.parse_break_expr(attrs)
1183 } else if self.eat_keyword(kw::Yield) {
1184 self.parse_yield_expr(attrs)
1185 } else if self.eat_keyword(kw::Let) {
1186 self.parse_let_expr(attrs)
1187 } else if self.eat_keyword(kw::Underscore) {
1188 self.sess.gated_spans.gate(sym::destructuring_assignment, self.prev_token.span);
1189 Ok(self.mk_expr(self.prev_token.span, ExprKind::Underscore, attrs))
1190 } else if !self.unclosed_delims.is_empty() && self.check(&token::Semi) {
1191 // Don't complain about bare semicolons after unclosed braces
1192 // recovery in order to keep the error count down. Fixing the
1193 // delimiters will possibly also fix the bare semicolon found in
1194 // expression context. For example, silence the following error:
1196 // error: expected expression, found `;`
1200 // | ^ expected expression
1202 Ok(self.mk_expr_err(self.token.span))
1203 } else if self.token.uninterpolated_span().rust_2018() {
1204 // `Span::rust_2018()` is somewhat expensive; don't get it repeatedly.
1205 if self.check_keyword(kw::Async) {
1206 if self.is_async_block() {
1207 // Check for `async {` and `async move {`.
1208 self.parse_async_block(attrs)
1210 self.parse_closure_expr(attrs)
1212 } else if self.eat_keyword(kw::Await) {
1213 self.recover_incorrect_await_syntax(lo, self.prev_token.span, attrs)
1215 self.parse_lit_expr(attrs)
1218 self.parse_lit_expr(attrs)
1222 fn parse_lit_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1223 let lo = self.token.span;
1224 match self.parse_opt_lit() {
1226 let expr = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Lit(literal), attrs);
1227 self.maybe_recover_from_bad_qpath(expr, true)
1229 None => self.try_macro_suggestion(),
1233 fn parse_tuple_parens_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1234 let lo = self.token.span;
1235 self.expect(&token::OpenDelim(token::Paren))?;
1236 let (es, trailing_comma) = match self.parse_seq_to_end(
1237 &token::CloseDelim(token::Paren),
1238 SeqSep::trailing_allowed(token::Comma),
1239 |p| p.parse_expr_catch_underscore(),
1242 Err(err) => return Ok(self.recover_seq_parse_error(token::Paren, lo, Err(err))),
1244 let kind = if es.len() == 1 && !trailing_comma {
1245 // `(e)` is parenthesized `e`.
1246 ExprKind::Paren(es.into_iter().next().unwrap())
1248 // `(e,)` is a tuple with only one field, `e`.
1251 let expr = self.mk_expr(lo.to(self.prev_token.span), kind, attrs);
1252 self.maybe_recover_from_bad_qpath(expr, true)
1255 fn parse_array_or_repeat_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1256 let lo = self.token.span;
1259 let close = &token::CloseDelim(token::Bracket);
1260 let kind = if self.eat(close) {
1262 ExprKind::Array(Vec::new())
1265 let first_expr = self.parse_expr()?;
1266 if self.eat(&token::Semi) {
1267 // Repeating array syntax: `[ 0; 512 ]`
1268 let count = self.parse_anon_const_expr()?;
1269 self.expect(close)?;
1270 ExprKind::Repeat(first_expr, count)
1271 } else if self.eat(&token::Comma) {
1272 // Vector with two or more elements.
1273 let sep = SeqSep::trailing_allowed(token::Comma);
1274 let (remaining_exprs, _) = self.parse_seq_to_end(close, sep, |p| p.parse_expr())?;
1275 let mut exprs = vec![first_expr];
1276 exprs.extend(remaining_exprs);
1277 ExprKind::Array(exprs)
1279 // Vector with one element
1280 self.expect(close)?;
1281 ExprKind::Array(vec![first_expr])
1284 let expr = self.mk_expr(lo.to(self.prev_token.span), kind, attrs);
1285 self.maybe_recover_from_bad_qpath(expr, true)
1288 fn parse_path_start_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1289 let (qself, path) = if self.eat_lt() {
1290 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
1293 (None, self.parse_path(PathStyle::Expr)?)
1297 // `!`, as an operator, is prefix, so we know this isn't that.
1298 let (hi, kind) = if self.eat(&token::Not) {
1299 // MACRO INVOCATION expression
1300 if qself.is_some() {
1301 self.struct_span_err(path.span, "macros cannot use qualified paths").emit();
1305 args: self.parse_mac_args()?,
1306 prior_type_ascription: self.last_type_ascription,
1308 (self.prev_token.span, ExprKind::MacCall(mac))
1309 } else if self.check(&token::OpenDelim(token::Brace)) {
1310 if let Some(expr) = self.maybe_parse_struct_expr(qself.as_ref(), &path, &attrs) {
1311 if qself.is_some() {
1312 self.sess.gated_spans.gate(sym::more_qualified_paths, path.span);
1316 (path.span, ExprKind::Path(qself, path))
1319 (path.span, ExprKind::Path(qself, path))
1322 let expr = self.mk_expr(lo.to(hi), kind, attrs);
1323 self.maybe_recover_from_bad_qpath(expr, true)
1326 /// Parse `'label: $expr`. The label is already parsed.
1327 fn parse_labeled_expr(
1331 consume_colon: bool,
1332 ) -> PResult<'a, P<Expr>> {
1333 let lo = label.ident.span;
1334 let label = Some(label);
1335 let ate_colon = self.eat(&token::Colon);
1336 let expr = if self.eat_keyword(kw::While) {
1337 self.parse_while_expr(label, lo, attrs)
1338 } else if self.eat_keyword(kw::For) {
1339 self.parse_for_expr(label, lo, attrs)
1340 } else if self.eat_keyword(kw::Loop) {
1341 self.parse_loop_expr(label, lo, attrs)
1342 } else if self.check(&token::OpenDelim(token::Brace)) || self.token.is_whole_block() {
1343 self.parse_block_expr(label, lo, BlockCheckMode::Default, attrs)
1345 let msg = "expected `while`, `for`, `loop` or `{` after a label";
1346 self.struct_span_err(self.token.span, msg).span_label(self.token.span, msg).emit();
1347 // Continue as an expression in an effort to recover on `'label: non_block_expr`.
1351 if !ate_colon && consume_colon {
1352 self.error_labeled_expr_must_be_followed_by_colon(lo, expr.span);
1358 fn error_labeled_expr_must_be_followed_by_colon(&self, lo: Span, span: Span) {
1359 self.struct_span_err(span, "labeled expression must be followed by `:`")
1360 .span_label(lo, "the label")
1361 .span_suggestion_short(
1363 "add `:` after the label",
1365 Applicability::MachineApplicable,
1367 .note("labels are used before loops and blocks, allowing e.g., `break 'label` to them")
1371 /// Recover on the syntax `do catch { ... }` suggesting `try { ... }` instead.
1372 fn recover_do_catch(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1373 let lo = self.token.span;
1375 self.bump(); // `do`
1376 self.bump(); // `catch`
1378 let span_dc = lo.to(self.prev_token.span);
1379 self.struct_span_err(span_dc, "found removed `do catch` syntax")
1382 "replace with the new syntax",
1384 Applicability::MachineApplicable,
1386 .note("following RFC #2388, the new non-placeholder syntax is `try`")
1389 self.parse_try_block(lo, attrs)
1392 /// Parse an expression if the token can begin one.
1393 fn parse_expr_opt(&mut self) -> PResult<'a, Option<P<Expr>>> {
1394 Ok(if self.token.can_begin_expr() { Some(self.parse_expr()?) } else { None })
1397 /// Parse `"return" expr?`.
1398 fn parse_return_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1399 let lo = self.prev_token.span;
1400 let kind = ExprKind::Ret(self.parse_expr_opt()?);
1401 let expr = self.mk_expr(lo.to(self.prev_token.span), kind, attrs);
1402 self.maybe_recover_from_bad_qpath(expr, true)
1405 /// Parse `"break" (('label (:? expr)?) | expr?)` with `"break"` token already eaten.
1406 /// If the label is followed immediately by a `:` token, the label and `:` are
1407 /// parsed as part of the expression (i.e. a labeled loop). The language team has
1408 /// decided in #87026 to require parentheses as a visual aid to avoid confusion if
1409 /// the break expression of an unlabeled break is a labeled loop (as in
1410 /// `break 'lbl: loop {}`); a labeled break with an unlabeled loop as its value
1411 /// expression only gets a warning for compatibility reasons; and a labeled break
1412 /// with a labeled loop does not even get a warning because there is no ambiguity.
1413 fn parse_break_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1414 let lo = self.prev_token.span;
1415 let mut label = self.eat_label();
1416 let kind = if label.is_some() && self.token == token::Colon {
1417 // The value expression can be a labeled loop, see issue #86948, e.g.:
1418 // `loop { break 'label: loop { break 'label 42; }; }`
1419 let lexpr = self.parse_labeled_expr(label.take().unwrap(), AttrVec::new(), true)?;
1420 self.struct_span_err(
1422 "parentheses are required around this expression to avoid confusion with a labeled break expression",
1424 .multipart_suggestion(
1425 "wrap the expression in parentheses",
1427 (lexpr.span.shrink_to_lo(), "(".to_string()),
1428 (lexpr.span.shrink_to_hi(), ")".to_string()),
1430 Applicability::MachineApplicable,
1434 } else if self.token != token::OpenDelim(token::Brace)
1435 || !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
1437 let expr = self.parse_expr_opt()?;
1438 if let Some(ref expr) = expr {
1442 ExprKind::While(_, _, None)
1443 | ExprKind::ForLoop(_, _, _, None)
1444 | ExprKind::Loop(_, None)
1445 | ExprKind::Block(_, None)
1448 self.sess.buffer_lint_with_diagnostic(
1449 BREAK_WITH_LABEL_AND_LOOP,
1452 "this labeled break expression is easy to confuse with an unlabeled break with a labeled value expression",
1453 BuiltinLintDiagnostics::BreakWithLabelAndLoop(expr.span),
1461 let expr = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Break(label, kind), attrs);
1462 self.maybe_recover_from_bad_qpath(expr, true)
1465 /// Parse `"yield" expr?`.
1466 fn parse_yield_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1467 let lo = self.prev_token.span;
1468 let kind = ExprKind::Yield(self.parse_expr_opt()?);
1469 let span = lo.to(self.prev_token.span);
1470 self.sess.gated_spans.gate(sym::generators, span);
1471 let expr = self.mk_expr(span, kind, attrs);
1472 self.maybe_recover_from_bad_qpath(expr, true)
1475 /// Returns a string literal if the next token is a string literal.
1476 /// In case of error returns `Some(lit)` if the next token is a literal with a wrong kind,
1477 /// and returns `None` if the next token is not literal at all.
1478 pub fn parse_str_lit(&mut self) -> Result<ast::StrLit, Option<Lit>> {
1479 match self.parse_opt_lit() {
1480 Some(lit) => match lit.kind {
1481 ast::LitKind::Str(symbol_unescaped, style) => Ok(ast::StrLit {
1483 symbol: lit.token.symbol,
1484 suffix: lit.token.suffix,
1488 _ => Err(Some(lit)),
1494 pub(super) fn parse_lit(&mut self) -> PResult<'a, Lit> {
1495 self.parse_opt_lit().ok_or_else(|| {
1496 let msg = format!("unexpected token: {}", super::token_descr(&self.token));
1497 self.struct_span_err(self.token.span, &msg)
1501 /// Matches `lit = true | false | token_lit`.
1502 /// Returns `None` if the next token is not a literal.
1503 pub(super) fn parse_opt_lit(&mut self) -> Option<Lit> {
1504 let mut recovered = None;
1505 if self.token == token::Dot {
1506 // Attempt to recover `.4` as `0.4`. We don't currently have any syntax where
1507 // dot would follow an optional literal, so we do this unconditionally.
1508 recovered = self.look_ahead(1, |next_token| {
1509 if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) =
1512 if self.token.span.hi() == next_token.span.lo() {
1513 let s = String::from("0.") + &symbol.as_str();
1514 let kind = TokenKind::lit(token::Float, Symbol::intern(&s), suffix);
1515 return Some(Token::new(kind, self.token.span.to(next_token.span)));
1520 if let Some(token) = &recovered {
1522 self.error_float_lits_must_have_int_part(&token);
1526 let token = recovered.as_ref().unwrap_or(&self.token);
1527 match Lit::from_token(token) {
1532 Err(LitError::NotLiteral) => None,
1534 let span = token.span;
1535 let lit = match token.kind {
1536 token::Literal(lit) => lit,
1537 _ => unreachable!(),
1540 self.report_lit_error(err, lit, span);
1541 // Pack possible quotes and prefixes from the original literal into
1542 // the error literal's symbol so they can be pretty-printed faithfully.
1543 let suffixless_lit = token::Lit::new(lit.kind, lit.symbol, None);
1544 let symbol = Symbol::intern(&suffixless_lit.to_string());
1545 let lit = token::Lit::new(token::Err, symbol, lit.suffix);
1546 Some(Lit::from_lit_token(lit, span).unwrap_or_else(|_| unreachable!()))
1551 fn error_float_lits_must_have_int_part(&self, token: &Token) {
1552 self.struct_span_err(token.span, "float literals must have an integer part")
1555 "must have an integer part",
1556 pprust::token_to_string(token).into(),
1557 Applicability::MachineApplicable,
1562 fn report_lit_error(&self, err: LitError, lit: token::Lit, span: Span) {
1563 // Checks if `s` looks like i32 or u1234 etc.
1564 fn looks_like_width_suffix(first_chars: &[char], s: &str) -> bool {
1565 s.len() > 1 && s.starts_with(first_chars) && s[1..].chars().all(|c| c.is_ascii_digit())
1568 let token::Lit { kind, suffix, .. } = lit;
1570 // `NotLiteral` is not an error by itself, so we don't report
1571 // it and give the parser opportunity to try something else.
1572 LitError::NotLiteral => {}
1573 // `LexerError` *is* an error, but it was already reported
1574 // by lexer, so here we don't report it the second time.
1575 LitError::LexerError => {}
1576 LitError::InvalidSuffix => {
1577 self.expect_no_suffix(
1579 &format!("{} {} literal", kind.article(), kind.descr()),
1583 LitError::InvalidIntSuffix => {
1584 let suf = suffix.expect("suffix error with no suffix").as_str();
1585 if looks_like_width_suffix(&['i', 'u'], &suf) {
1586 // If it looks like a width, try to be helpful.
1587 let msg = format!("invalid width `{}` for integer literal", &suf[1..]);
1588 self.struct_span_err(span, &msg)
1589 .help("valid widths are 8, 16, 32, 64 and 128")
1592 let msg = format!("invalid suffix `{}` for number literal", suf);
1593 self.struct_span_err(span, &msg)
1594 .span_label(span, format!("invalid suffix `{}`", suf))
1595 .help("the suffix must be one of the numeric types (`u32`, `isize`, `f32`, etc.)")
1599 LitError::InvalidFloatSuffix => {
1600 let suf = suffix.expect("suffix error with no suffix").as_str();
1601 if looks_like_width_suffix(&['f'], &suf) {
1602 // If it looks like a width, try to be helpful.
1603 let msg = format!("invalid width `{}` for float literal", &suf[1..]);
1604 self.struct_span_err(span, &msg).help("valid widths are 32 and 64").emit();
1606 let msg = format!("invalid suffix `{}` for float literal", suf);
1607 self.struct_span_err(span, &msg)
1608 .span_label(span, format!("invalid suffix `{}`", suf))
1609 .help("valid suffixes are `f32` and `f64`")
1613 LitError::NonDecimalFloat(base) => {
1614 let descr = match base {
1615 16 => "hexadecimal",
1618 _ => unreachable!(),
1620 self.struct_span_err(span, &format!("{} float literal is not supported", descr))
1621 .span_label(span, "not supported")
1624 LitError::IntTooLarge => {
1625 self.struct_span_err(span, "integer literal is too large").emit();
1630 pub(super) fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<Symbol>) {
1631 if let Some(suf) = suffix {
1632 let mut err = if kind == "a tuple index"
1633 && [sym::i32, sym::u32, sym::isize, sym::usize].contains(&suf)
1635 // #59553: warn instead of reject out of hand to allow the fix to percolate
1636 // through the ecosystem when people fix their macros
1640 .struct_span_warn(sp, &format!("suffixes on {} are invalid", kind));
1642 "`{}` is *temporarily* accepted on tuple index fields as it was \
1643 incorrectly accepted on stable for a few releases",
1647 "on proc macros, you'll want to use `syn::Index::from` or \
1648 `proc_macro::Literal::*_unsuffixed` for code that will desugar \
1649 to tuple field access",
1652 "see issue #60210 <https://github.com/rust-lang/rust/issues/60210> \
1653 for more information",
1657 self.struct_span_err(sp, &format!("suffixes on {} are invalid", kind))
1659 err.span_label(sp, format!("invalid suffix `{}`", suf));
1664 /// Matches `'-' lit | lit` (cf. `ast_validation::AstValidator::check_expr_within_pat`).
1665 /// Keep this in sync with `Token::can_begin_literal_maybe_minus`.
1666 pub fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1667 maybe_whole_expr!(self);
1669 let lo = self.token.span;
1670 let minus_present = self.eat(&token::BinOp(token::Minus));
1671 let lit = self.parse_lit()?;
1672 let expr = self.mk_expr(lit.span, ExprKind::Lit(lit), AttrVec::new());
1676 lo.to(self.prev_token.span),
1677 self.mk_unary(UnOp::Neg, expr),
1685 /// Parses a block or unsafe block.
1686 pub(super) fn parse_block_expr(
1688 opt_label: Option<Label>,
1690 blk_mode: BlockCheckMode,
1692 ) -> PResult<'a, P<Expr>> {
1693 if let Some(label) = opt_label {
1694 self.sess.gated_spans.gate(sym::label_break_value, label.ident.span);
1697 if self.token.is_whole_block() {
1698 self.struct_span_err(self.token.span, "cannot use a `block` macro fragment here")
1699 .span_label(lo.to(self.token.span), "the `block` fragment is within this context")
1703 let (inner_attrs, blk) = self.parse_block_common(lo, blk_mode)?;
1704 attrs.extend(inner_attrs);
1705 Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs))
1708 /// Recover on an explicitly quantified closure expression, e.g., `for<'a> |x: &'a u8| *x + 1`.
1709 fn recover_quantified_closure_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1710 let lo = self.token.span;
1711 let _ = self.parse_late_bound_lifetime_defs()?;
1712 let span_for = lo.to(self.prev_token.span);
1713 let closure = self.parse_closure_expr(attrs)?;
1715 self.struct_span_err(span_for, "cannot introduce explicit parameters for a closure")
1716 .span_label(closure.span, "the parameters are attached to this closure")
1719 "remove the parameters",
1721 Applicability::MachineApplicable,
1725 Ok(self.mk_expr_err(lo.to(closure.span)))
1728 /// Parses a closure expression (e.g., `move |args| expr`).
1729 fn parse_closure_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1730 let lo = self.token.span;
1733 if self.eat_keyword(kw::Static) { Movability::Static } else { Movability::Movable };
1735 let asyncness = if self.token.uninterpolated_span().rust_2018() {
1736 self.parse_asyncness()
1741 let capture_clause = self.parse_capture_clause()?;
1742 let decl = self.parse_fn_block_decl()?;
1743 let decl_hi = self.prev_token.span;
1744 let mut body = match decl.output {
1745 FnRetTy::Default(_) => {
1746 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
1747 self.parse_expr_res(restrictions, None)?
1750 // If an explicit return type is given, require a block to appear (RFC 968).
1751 let body_lo = self.token.span;
1752 self.parse_block_expr(None, body_lo, BlockCheckMode::Default, AttrVec::new())?
1756 if let Async::Yes { span, .. } = asyncness {
1757 // Feature-gate `async ||` closures.
1758 self.sess.gated_spans.gate(sym::async_closure, span);
1761 if self.token.kind == TokenKind::Semi && self.token_cursor.frame.delim == DelimToken::Paren
1763 // It is likely that the closure body is a block but where the
1764 // braces have been removed. We will recover and eat the next
1765 // statements later in the parsing process.
1766 body = self.mk_expr_err(body.span);
1769 let body_span = body.span;
1771 let closure = self.mk_expr(
1773 ExprKind::Closure(capture_clause, asyncness, movability, decl, body, lo.to(decl_hi)),
1777 // Disable recovery for closure body
1779 ClosureSpans { whole_closure: closure.span, closing_pipe: decl_hi, body: body_span };
1780 self.current_closure = Some(spans);
1785 /// Parses an optional `move` prefix to a closure-like construct.
1786 fn parse_capture_clause(&mut self) -> PResult<'a, CaptureBy> {
1787 if self.eat_keyword(kw::Move) {
1788 // Check for `move async` and recover
1789 if self.check_keyword(kw::Async) {
1790 let move_async_span = self.token.span.with_lo(self.prev_token.span.data().lo);
1791 Err(self.incorrect_move_async_order_found(move_async_span))
1793 Ok(CaptureBy::Value)
1800 /// Parses the `|arg, arg|` header of a closure.
1801 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
1802 let inputs = if self.eat(&token::OrOr) {
1805 self.expect(&token::BinOp(token::Or))?;
1807 .parse_seq_to_before_tokens(
1808 &[&token::BinOp(token::Or), &token::OrOr],
1809 SeqSep::trailing_allowed(token::Comma),
1810 TokenExpectType::NoExpect,
1811 |p| p.parse_fn_block_param(),
1818 self.parse_ret_ty(AllowPlus::Yes, RecoverQPath::Yes, RecoverReturnSign::Yes)?;
1820 Ok(P(FnDecl { inputs, output }))
1823 /// Parses a parameter in a closure header (e.g., `|arg, arg|`).
1824 fn parse_fn_block_param(&mut self) -> PResult<'a, Param> {
1825 let lo = self.token.span;
1826 let attrs = self.parse_outer_attributes()?;
1827 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
1828 let pat = this.parse_pat_no_top_alt(PARAM_EXPECTED)?;
1829 let ty = if this.eat(&token::Colon) {
1832 this.mk_ty(this.prev_token.span, TyKind::Infer)
1837 attrs: attrs.into(),
1840 span: lo.to(this.token.span),
1842 is_placeholder: false,
1844 TrailingToken::MaybeComma,
1849 /// Parses an `if` expression (`if` token already eaten).
1850 fn parse_if_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1851 let lo = self.prev_token.span;
1852 let cond = self.parse_cond_expr()?;
1854 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
1855 // verify that the last statement is either an implicit return (no `;`) or an explicit
1856 // return. This won't catch blocks with an explicit `return`, but that would be caught by
1857 // the dead code lint.
1858 let thn = if self.eat_keyword(kw::Else) || !cond.returns() {
1859 self.error_missing_if_cond(lo, cond.span)
1861 let attrs = self.parse_outer_attributes()?.take_for_recovery(); // For recovery.
1862 let not_block = self.token != token::OpenDelim(token::Brace);
1863 let block = self.parse_block().map_err(|mut err| {
1865 err.span_label(lo, "this `if` expression has a condition, but no block");
1866 if let ExprKind::Binary(_, _, ref right) = cond.kind {
1867 if let ExprKind::Block(_, _) = right.kind {
1868 err.help("maybe you forgot the right operand of the condition?");
1874 self.error_on_if_block_attrs(lo, false, block.span, &attrs);
1877 let els = if self.eat_keyword(kw::Else) { Some(self.parse_else_expr()?) } else { None };
1878 Ok(self.mk_expr(lo.to(self.prev_token.span), ExprKind::If(cond, thn, els), attrs))
1881 fn error_missing_if_cond(&self, lo: Span, span: Span) -> P<ast::Block> {
1882 let sp = self.sess.source_map().next_point(lo);
1883 self.struct_span_err(sp, "missing condition for `if` expression")
1884 .span_label(sp, "expected if condition here")
1886 self.mk_block_err(span)
1889 /// Parses the condition of a `if` or `while` expression.
1890 fn parse_cond_expr(&mut self) -> PResult<'a, P<Expr>> {
1891 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
1893 if let ExprKind::Let(..) = cond.kind {
1894 // Remove the last feature gating of a `let` expression since it's stable.
1895 self.sess.gated_spans.ungate_last(sym::let_chains, cond.span);
1901 /// Parses a `let $pat = $expr` pseudo-expression.
1902 /// The `let` token has already been eaten.
1903 fn parse_let_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1904 let lo = self.prev_token.span;
1905 let pat = self.parse_pat_allow_top_alt(None, RecoverComma::Yes, RecoverColon::Yes)?;
1906 self.expect(&token::Eq)?;
1907 let expr = self.with_res(self.restrictions | Restrictions::NO_STRUCT_LITERAL, |this| {
1908 this.parse_assoc_expr_with(1 + prec_let_scrutinee_needs_par(), None.into())
1910 let span = lo.to(expr.span);
1911 self.sess.gated_spans.gate(sym::let_chains, span);
1912 Ok(self.mk_expr(span, ExprKind::Let(pat, expr, span), attrs))
1915 /// Parses an `else { ... }` expression (`else` token already eaten).
1916 fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
1917 let ctx_span = self.prev_token.span; // `else`
1918 let attrs = self.parse_outer_attributes()?.take_for_recovery(); // For recovery.
1919 let expr = if self.eat_keyword(kw::If) {
1920 self.parse_if_expr(AttrVec::new())?
1922 let blk = self.parse_block()?;
1923 self.mk_expr(blk.span, ExprKind::Block(blk, None), AttrVec::new())
1925 self.error_on_if_block_attrs(ctx_span, true, expr.span, &attrs);
1929 fn error_on_if_block_attrs(
1934 attrs: &[ast::Attribute],
1936 let (span, last) = match attrs {
1938 [x0 @ xn] | [x0, .., xn] => (x0.span.to(xn.span), xn.span),
1940 let ctx = if is_ctx_else { "else" } else { "if" };
1941 self.struct_span_err(last, "outer attributes are not allowed on `if` and `else` branches")
1942 .span_label(branch_span, "the attributes are attached to this branch")
1943 .span_label(ctx_span, format!("the branch belongs to this `{}`", ctx))
1946 "remove the attributes",
1948 Applicability::MachineApplicable,
1953 /// Parses `for <src_pat> in <src_expr> <src_loop_block>` (`for` token already eaten).
1956 opt_label: Option<Label>,
1959 ) -> PResult<'a, P<Expr>> {
1960 // Record whether we are about to parse `for (`.
1961 // This is used below for recovery in case of `for ( $stuff ) $block`
1962 // in which case we will suggest `for $stuff $block`.
1963 let begin_paren = match self.token.kind {
1964 token::OpenDelim(token::Paren) => Some(self.token.span),
1968 let pat = self.parse_pat_allow_top_alt(None, RecoverComma::Yes, RecoverColon::Yes)?;
1969 if !self.eat_keyword(kw::In) {
1970 self.error_missing_in_for_loop();
1972 self.check_for_for_in_in_typo(self.prev_token.span);
1973 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
1975 let pat = self.recover_parens_around_for_head(pat, &expr, begin_paren);
1977 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
1978 attrs.extend(iattrs);
1980 let kind = ExprKind::ForLoop(pat, expr, loop_block, opt_label);
1981 Ok(self.mk_expr(lo.to(self.prev_token.span), kind, attrs))
1984 fn error_missing_in_for_loop(&mut self) {
1985 let (span, msg, sugg) = if self.token.is_ident_named(sym::of) {
1986 // Possibly using JS syntax (#75311).
1987 let span = self.token.span;
1989 (span, "try using `in` here instead", "in")
1991 (self.prev_token.span.between(self.token.span), "try adding `in` here", " in ")
1993 self.struct_span_err(span, "missing `in` in `for` loop")
1994 .span_suggestion_short(
1998 // Has been misleading, at least in the past (closed Issue #48492).
1999 Applicability::MaybeIncorrect,
2004 /// Parses a `while` or `while let` expression (`while` token already eaten).
2005 fn parse_while_expr(
2007 opt_label: Option<Label>,
2010 ) -> PResult<'a, P<Expr>> {
2011 let cond = self.parse_cond_expr()?;
2012 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
2013 attrs.extend(iattrs);
2014 Ok(self.mk_expr(lo.to(self.prev_token.span), ExprKind::While(cond, body, opt_label), attrs))
2017 /// Parses `loop { ... }` (`loop` token already eaten).
2020 opt_label: Option<Label>,
2023 ) -> PResult<'a, P<Expr>> {
2024 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
2025 attrs.extend(iattrs);
2026 Ok(self.mk_expr(lo.to(self.prev_token.span), ExprKind::Loop(body, opt_label), attrs))
2029 fn eat_label(&mut self) -> Option<Label> {
2030 self.token.lifetime().map(|ident| {
2036 /// Parses a `match ... { ... }` expression (`match` token already eaten).
2037 fn parse_match_expr(&mut self, mut attrs: AttrVec) -> PResult<'a, P<Expr>> {
2038 let match_span = self.prev_token.span;
2039 let lo = self.prev_token.span;
2040 let scrutinee = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
2041 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
2042 if self.token == token::Semi {
2043 e.span_suggestion_short(
2045 "try removing this `match`",
2047 Applicability::MaybeIncorrect, // speculative
2052 attrs.extend(self.parse_inner_attributes()?);
2054 let mut arms: Vec<Arm> = Vec::new();
2055 while self.token != token::CloseDelim(token::Brace) {
2056 match self.parse_arm() {
2057 Ok(arm) => arms.push(arm),
2059 // Recover by skipping to the end of the block.
2061 self.recover_stmt();
2062 let span = lo.to(self.token.span);
2063 if self.token == token::CloseDelim(token::Brace) {
2066 return Ok(self.mk_expr(span, ExprKind::Match(scrutinee, arms), attrs));
2070 let hi = self.token.span;
2072 Ok(self.mk_expr(lo.to(hi), ExprKind::Match(scrutinee, arms), attrs))
2075 /// Attempt to recover from match arm body with statements and no surrounding braces.
2076 fn parse_arm_body_missing_braces(
2078 first_expr: &P<Expr>,
2080 ) -> Option<P<Expr>> {
2081 if self.token.kind != token::Semi {
2084 let start_snapshot = self.clone();
2085 let semi_sp = self.token.span;
2088 vec![self.mk_stmt(first_expr.span, ast::StmtKind::Expr(first_expr.clone()))];
2089 let err = |this: &mut Parser<'_>, stmts: Vec<ast::Stmt>| {
2090 let span = stmts[0].span.to(stmts[stmts.len() - 1].span);
2091 let mut err = this.struct_span_err(span, "`match` arm body without braces");
2092 let (these, s, are) =
2093 if stmts.len() > 1 { ("these", "s", "are") } else { ("this", "", "is") };
2097 "{these} statement{s} {are} not surrounded by a body",
2103 err.span_label(arrow_span, "while parsing the `match` arm starting here");
2104 if stmts.len() > 1 {
2105 err.multipart_suggestion(
2106 &format!("surround the statement{} with a body", s),
2108 (span.shrink_to_lo(), "{ ".to_string()),
2109 (span.shrink_to_hi(), " }".to_string()),
2111 Applicability::MachineApplicable,
2114 err.span_suggestion(
2116 "use a comma to end a `match` arm expression",
2118 Applicability::MachineApplicable,
2122 this.mk_expr_err(span)
2124 // We might have either a `,` -> `;` typo, or a block without braces. We need
2125 // a more subtle parsing strategy.
2127 if self.token.kind == token::CloseDelim(token::Brace) {
2128 // We have reached the closing brace of the `match` expression.
2129 return Some(err(self, stmts));
2131 if self.token.kind == token::Comma {
2132 *self = start_snapshot;
2135 let pre_pat_snapshot = self.clone();
2136 match self.parse_pat_no_top_alt(None) {
2138 if self.token.kind == token::FatArrow {
2140 *self = pre_pat_snapshot;
2141 return Some(err(self, stmts));
2149 *self = pre_pat_snapshot;
2150 match self.parse_stmt_without_recovery(true, ForceCollect::No) {
2151 // Consume statements for as long as possible.
2156 *self = start_snapshot;
2159 // We couldn't parse either yet another statement missing it's
2160 // enclosing block nor the next arm's pattern or closing brace.
2161 Err(mut stmt_err) => {
2163 *self = start_snapshot;
2171 pub(super) fn parse_arm(&mut self) -> PResult<'a, Arm> {
2172 let attrs = self.parse_outer_attributes()?;
2173 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
2174 let lo = this.token.span;
2175 let pat = this.parse_pat_allow_top_alt(None, RecoverComma::Yes, RecoverColon::Yes)?;
2176 let guard = if this.eat_keyword(kw::If) {
2177 let if_span = this.prev_token.span;
2178 let cond = this.parse_expr()?;
2179 if let ExprKind::Let(..) = cond.kind {
2180 // Remove the last feature gating of a `let` expression since it's stable.
2181 this.sess.gated_spans.ungate_last(sym::let_chains, cond.span);
2182 let span = if_span.to(cond.span);
2183 this.sess.gated_spans.gate(sym::if_let_guard, span);
2189 let arrow_span = this.token.span;
2190 this.expect(&token::FatArrow)?;
2191 let arm_start_span = this.token.span;
2193 let expr = this.parse_expr_res(Restrictions::STMT_EXPR, None).map_err(|mut err| {
2194 err.span_label(arrow_span, "while parsing the `match` arm starting here");
2198 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
2199 && this.token != token::CloseDelim(token::Brace);
2201 let hi = this.prev_token.span;
2204 let sm = this.sess.source_map();
2205 if let Some(body) = this.parse_arm_body_missing_braces(&expr, arrow_span) {
2206 let span = body.span;
2209 attrs: attrs.into(),
2215 is_placeholder: false,
2217 TrailingToken::None,
2220 this.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)]).map_err(
2222 match (sm.span_to_lines(expr.span), sm.span_to_lines(arm_start_span)) {
2223 (Ok(ref expr_lines), Ok(ref arm_start_lines))
2224 if arm_start_lines.lines[0].end_col
2225 == expr_lines.lines[0].end_col
2226 && expr_lines.lines.len() == 2
2227 && this.token == token::FatArrow =>
2229 // We check whether there's any trailing code in the parse span,
2230 // if there isn't, we very likely have the following:
2233 // | -- - missing comma
2237 // | - ^^ self.token.span
2239 // | parsed until here as `"y" & X`
2240 err.span_suggestion_short(
2241 arm_start_span.shrink_to_hi(),
2242 "missing a comma here to end this `match` arm",
2244 Applicability::MachineApplicable,
2250 "while parsing the `match` arm starting here",
2258 this.eat(&token::Comma);
2263 attrs: attrs.into(),
2269 is_placeholder: false,
2271 TrailingToken::None,
2276 /// Parses a `try {...}` expression (`try` token already eaten).
2277 fn parse_try_block(&mut self, span_lo: Span, mut attrs: AttrVec) -> PResult<'a, P<Expr>> {
2278 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
2279 attrs.extend(iattrs);
2280 if self.eat_keyword(kw::Catch) {
2281 let mut error = self.struct_span_err(
2282 self.prev_token.span,
2283 "keyword `catch` cannot follow a `try` block",
2285 error.help("try using `match` on the result of the `try` block instead");
2289 let span = span_lo.to(body.span);
2290 self.sess.gated_spans.gate(sym::try_blocks, span);
2291 Ok(self.mk_expr(span, ExprKind::TryBlock(body), attrs))
2295 fn is_do_catch_block(&self) -> bool {
2296 self.token.is_keyword(kw::Do)
2297 && self.is_keyword_ahead(1, &[kw::Catch])
2298 && self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
2299 && !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
2302 fn is_try_block(&self) -> bool {
2303 self.token.is_keyword(kw::Try)
2304 && self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
2305 && self.token.uninterpolated_span().rust_2018()
2308 /// Parses an `async move? {...}` expression.
2309 fn parse_async_block(&mut self, mut attrs: AttrVec) -> PResult<'a, P<Expr>> {
2310 let lo = self.token.span;
2311 self.expect_keyword(kw::Async)?;
2312 let capture_clause = self.parse_capture_clause()?;
2313 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
2314 attrs.extend(iattrs);
2315 let kind = ExprKind::Async(capture_clause, DUMMY_NODE_ID, body);
2316 Ok(self.mk_expr(lo.to(self.prev_token.span), kind, attrs))
2319 fn is_async_block(&self) -> bool {
2320 self.token.is_keyword(kw::Async)
2323 self.is_keyword_ahead(1, &[kw::Move])
2324 && self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
2327 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
2331 fn is_certainly_not_a_block(&self) -> bool {
2332 self.look_ahead(1, |t| t.is_ident())
2334 // `{ ident, ` cannot start a block.
2335 self.look_ahead(2, |t| t == &token::Comma)
2336 || self.look_ahead(2, |t| t == &token::Colon)
2338 // `{ ident: token, ` cannot start a block.
2339 self.look_ahead(4, |t| t == &token::Comma) ||
2340 // `{ ident: ` cannot start a block unless it's a type ascription `ident: Type`.
2341 self.look_ahead(3, |t| !t.can_begin_type())
2346 fn maybe_parse_struct_expr(
2348 qself: Option<&ast::QSelf>,
2351 ) -> Option<PResult<'a, P<Expr>>> {
2352 let struct_allowed = !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
2353 if struct_allowed || self.is_certainly_not_a_block() {
2354 if let Err(err) = self.expect(&token::OpenDelim(token::Brace)) {
2355 return Some(Err(err));
2357 let expr = self.parse_struct_expr(qself.cloned(), path.clone(), attrs.clone(), true);
2358 if let (Ok(expr), false) = (&expr, struct_allowed) {
2359 // This is a struct literal, but we don't can't accept them here.
2360 self.error_struct_lit_not_allowed_here(path.span, expr.span);
2367 fn error_struct_lit_not_allowed_here(&self, lo: Span, sp: Span) {
2368 self.struct_span_err(sp, "struct literals are not allowed here")
2369 .multipart_suggestion(
2370 "surround the struct literal with parentheses",
2371 vec![(lo.shrink_to_lo(), "(".to_string()), (sp.shrink_to_hi(), ")".to_string())],
2372 Applicability::MachineApplicable,
2377 /// Precondition: already parsed the '{'.
2378 pub(super) fn parse_struct_expr(
2380 qself: Option<ast::QSelf>,
2384 ) -> PResult<'a, P<Expr>> {
2385 let mut fields = Vec::new();
2386 let mut base = ast::StructRest::None;
2387 let mut recover_async = false;
2389 let mut async_block_err = |e: &mut DiagnosticBuilder<'_>, span: Span| {
2390 recover_async = true;
2391 e.span_label(span, "`async` blocks are only allowed in Rust 2018 or later");
2392 e.help(&format!("set `edition = \"{}\"` in `Cargo.toml`", LATEST_STABLE_EDITION));
2393 e.note("for more on editions, read https://doc.rust-lang.org/edition-guide");
2396 while self.token != token::CloseDelim(token::Brace) {
2397 if self.eat(&token::DotDot) {
2398 let exp_span = self.prev_token.span;
2399 // We permit `.. }` on the left-hand side of a destructuring assignment.
2400 if self.check(&token::CloseDelim(token::Brace)) {
2401 self.sess.gated_spans.gate(sym::destructuring_assignment, self.prev_token.span);
2402 base = ast::StructRest::Rest(self.prev_token.span.shrink_to_hi());
2405 match self.parse_expr() {
2406 Ok(e) => base = ast::StructRest::Base(e),
2407 Err(mut e) if recover => {
2409 self.recover_stmt();
2411 Err(e) => return Err(e),
2413 self.recover_struct_comma_after_dotdot(exp_span);
2417 let recovery_field = self.find_struct_error_after_field_looking_code();
2418 let parsed_field = match self.parse_expr_field() {
2421 if pth == kw::Async {
2422 async_block_err(&mut e, pth.span);
2424 e.span_label(pth.span, "while parsing this struct");
2428 // If the next token is a comma, then try to parse
2429 // what comes next as additional fields, rather than
2430 // bailing out until next `}`.
2431 if self.token != token::Comma {
2432 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2433 if self.token != token::Comma {
2441 match self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)]) {
2443 if let Some(f) = parsed_field.or(recovery_field) {
2444 // Only include the field if there's no parse error for the field name.
2449 if pth == kw::Async {
2450 async_block_err(&mut e, pth.span);
2452 e.span_label(pth.span, "while parsing this struct");
2453 if let Some(f) = recovery_field {
2456 self.prev_token.span.shrink_to_hi(),
2457 "try adding a comma",
2459 Applicability::MachineApplicable,
2467 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2468 self.eat(&token::Comma);
2473 let span = pth.span.to(self.token.span);
2474 self.expect(&token::CloseDelim(token::Brace))?;
2475 let expr = if recover_async {
2478 ExprKind::Struct(P(ast::StructExpr { qself, path: pth, fields, rest: base }))
2480 Ok(self.mk_expr(span, expr, attrs))
2483 /// Use in case of error after field-looking code: `S { foo: () with a }`.
2484 fn find_struct_error_after_field_looking_code(&self) -> Option<ExprField> {
2485 match self.token.ident() {
2486 Some((ident, is_raw))
2487 if (is_raw || !ident.is_reserved())
2488 && self.look_ahead(1, |t| *t == token::Colon) =>
2490 Some(ast::ExprField {
2492 span: self.token.span,
2493 expr: self.mk_expr_err(self.token.span),
2494 is_shorthand: false,
2495 attrs: AttrVec::new(),
2497 is_placeholder: false,
2504 fn recover_struct_comma_after_dotdot(&mut self, span: Span) {
2505 if self.token != token::Comma {
2508 self.struct_span_err(
2509 span.to(self.prev_token.span),
2510 "cannot use a comma after the base struct",
2512 .span_suggestion_short(
2514 "remove this comma",
2516 Applicability::MachineApplicable,
2518 .note("the base struct must always be the last field")
2520 self.recover_stmt();
2523 /// Parses `ident (COLON expr)?`.
2524 fn parse_expr_field(&mut self) -> PResult<'a, ExprField> {
2525 let attrs = self.parse_outer_attributes()?;
2526 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
2527 let lo = this.token.span;
2529 // Check if a colon exists one ahead. This means we're parsing a fieldname.
2530 let is_shorthand = !this.look_ahead(1, |t| t == &token::Colon || t == &token::Eq);
2531 let (ident, expr) = if is_shorthand {
2532 // Mimic `x: x` for the `x` field shorthand.
2533 let ident = this.parse_ident_common(false)?;
2534 let path = ast::Path::from_ident(ident);
2535 (ident, this.mk_expr(ident.span, ExprKind::Path(None, path), AttrVec::new()))
2537 let ident = this.parse_field_name()?;
2538 this.error_on_eq_field_init(ident);
2540 (ident, this.parse_expr()?)
2546 span: lo.to(expr.span),
2549 attrs: attrs.into(),
2551 is_placeholder: false,
2553 TrailingToken::MaybeComma,
2558 /// Check for `=`. This means the source incorrectly attempts to
2559 /// initialize a field with an eq rather than a colon.
2560 fn error_on_eq_field_init(&self, field_name: Ident) {
2561 if self.token != token::Eq {
2565 self.struct_span_err(self.token.span, "expected `:`, found `=`")
2567 field_name.span.shrink_to_hi().to(self.token.span),
2568 "replace equals symbol with a colon",
2570 Applicability::MachineApplicable,
2575 fn err_dotdotdot_syntax(&self, span: Span) {
2576 self.struct_span_err(span, "unexpected token: `...`")
2579 "use `..` for an exclusive range",
2581 Applicability::MaybeIncorrect,
2585 "or `..=` for an inclusive range",
2587 Applicability::MaybeIncorrect,
2592 fn err_larrow_operator(&self, span: Span) {
2593 self.struct_span_err(span, "unexpected token: `<-`")
2596 "if you meant to write a comparison against a negative value, add a \
2597 space in between `<` and `-`",
2599 Applicability::MaybeIncorrect,
2604 fn mk_assign_op(&self, binop: BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ExprKind {
2605 ExprKind::AssignOp(binop, lhs, rhs)
2610 start: Option<P<Expr>>,
2611 end: Option<P<Expr>>,
2612 limits: RangeLimits,
2614 if end.is_none() && limits == RangeLimits::Closed {
2615 self.inclusive_range_with_incorrect_end(self.prev_token.span);
2618 ExprKind::Range(start, end, limits)
2622 fn mk_unary(&self, unop: UnOp, expr: P<Expr>) -> ExprKind {
2623 ExprKind::Unary(unop, expr)
2626 fn mk_binary(&self, binop: BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ExprKind {
2627 ExprKind::Binary(binop, lhs, rhs)
2630 fn mk_index(&self, expr: P<Expr>, idx: P<Expr>) -> ExprKind {
2631 ExprKind::Index(expr, idx)
2634 fn mk_call(&self, f: P<Expr>, args: Vec<P<Expr>>) -> ExprKind {
2635 ExprKind::Call(f, args)
2638 fn mk_await_expr(&mut self, self_arg: P<Expr>, lo: Span) -> P<Expr> {
2639 let span = lo.to(self.prev_token.span);
2640 let await_expr = self.mk_expr(span, ExprKind::Await(self_arg), AttrVec::new());
2641 self.recover_from_await_method_call();
2645 crate fn mk_expr(&self, span: Span, kind: ExprKind, attrs: AttrVec) -> P<Expr> {
2646 P(Expr { kind, span, attrs, id: DUMMY_NODE_ID, tokens: None })
2649 pub(super) fn mk_expr_err(&self, span: Span) -> P<Expr> {
2650 self.mk_expr(span, ExprKind::Err, AttrVec::new())
2653 /// Create expression span ensuring the span of the parent node
2654 /// is larger than the span of lhs and rhs, including the attributes.
2655 fn mk_expr_sp(&self, lhs: &P<Expr>, lhs_span: Span, rhs_span: Span) -> Span {
2658 .find(|a| a.style == AttrStyle::Outer)
2659 .map_or(lhs_span, |a| a.span)
2663 fn collect_tokens_for_expr(
2666 f: impl FnOnce(&mut Self, Vec<ast::Attribute>) -> PResult<'a, P<Expr>>,
2667 ) -> PResult<'a, P<Expr>> {
2668 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
2669 let res = f(this, attrs)?;
2670 let trailing = if this.restrictions.contains(Restrictions::STMT_EXPR)
2671 && this.token.kind == token::Semi
2675 // FIXME - pass this through from the place where we know
2676 // we need a comma, rather than assuming that `#[attr] expr,`
2677 // always captures a trailing comma
2678 TrailingToken::MaybeComma