1 use super::diagnostics::SnapshotParser;
2 use super::pat::{CommaRecoveryMode, RecoverColon, RecoverComma, PARAM_EXPECTED};
3 use super::ty::{AllowPlus, RecoverQPath, RecoverReturnSign};
5 AttrWrapper, BlockMode, ClosureSpans, ForceCollect, Parser, PathStyle, Restrictions,
6 SemiColonMode, SeqSep, TokenExpectType, TokenType, TrailingToken,
8 use crate::maybe_recover_from_interpolated_ty_qpath;
11 use rustc_ast::ptr::P;
12 use rustc_ast::token::{self, Delimiter, Token, TokenKind};
13 use rustc_ast::tokenstream::Spacing;
14 use rustc_ast::util::classify;
15 use rustc_ast::util::literal::LitError;
16 use rustc_ast::util::parser::{prec_let_scrutinee_needs_par, AssocOp, Fixity};
17 use rustc_ast::visit::Visitor;
18 use rustc_ast::StmtKind;
19 use rustc_ast::{self as ast, AttrStyle, AttrVec, CaptureBy, ExprField, Lit, UnOp, DUMMY_NODE_ID};
20 use rustc_ast::{AnonConst, BinOp, BinOpKind, FnDecl, FnRetTy, MacCall, Param, Ty, TyKind};
21 use rustc_ast::{Arm, Async, BlockCheckMode, Expr, ExprKind, Label, Movability, RangeLimits};
22 use rustc_ast_pretty::pprust;
23 use rustc_data_structures::thin_vec::ThinVec;
24 use rustc_errors::{Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed, PResult};
25 use rustc_session::lint::builtin::BREAK_WITH_LABEL_AND_LOOP;
26 use rustc_session::lint::BuiltinLintDiagnostics;
27 use rustc_span::source_map::{self, Span, Spanned};
28 use rustc_span::symbol::{kw, sym, Ident, Symbol};
29 use rustc_span::{BytePos, Pos};
31 /// Possibly accepts an `token::Interpolated` expression (a pre-parsed expression
32 /// dropped into the token stream, which happens while parsing the result of
33 /// macro expansion). Placement of these is not as complex as I feared it would
34 /// be. The important thing is to make sure that lookahead doesn't balk at
35 /// `token::Interpolated` tokens.
36 macro_rules! maybe_whole_expr {
38 if let token::Interpolated(nt) = &$p.token.kind {
40 token::NtExpr(e) | token::NtLiteral(e) => {
45 token::NtPath(path) => {
46 let path = (**path).clone();
50 ExprKind::Path(None, path),
54 token::NtBlock(block) => {
55 let block = block.clone();
59 ExprKind::Block(block, None),
70 pub(super) enum LhsExpr {
72 AttributesParsed(AttrWrapper),
73 AlreadyParsed(P<Expr>),
76 impl From<Option<AttrWrapper>> for LhsExpr {
77 /// Converts `Some(attrs)` into `LhsExpr::AttributesParsed(attrs)`
78 /// and `None` into `LhsExpr::NotYetParsed`.
80 /// This conversion does not allocate.
81 fn from(o: Option<AttrWrapper>) -> Self {
82 if let Some(attrs) = o { LhsExpr::AttributesParsed(attrs) } else { LhsExpr::NotYetParsed }
86 impl From<P<Expr>> for LhsExpr {
87 /// Converts the `expr: P<Expr>` into `LhsExpr::AlreadyParsed(expr)`.
89 /// This conversion does not allocate.
90 fn from(expr: P<Expr>) -> Self {
91 LhsExpr::AlreadyParsed(expr)
96 /// Parses an expression.
98 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
99 self.current_closure.take();
101 self.parse_expr_res(Restrictions::empty(), None)
104 /// Parses an expression, forcing tokens to be collected
105 pub fn parse_expr_force_collect(&mut self) -> PResult<'a, P<Expr>> {
106 self.collect_tokens_no_attrs(|this| this.parse_expr())
109 pub fn parse_anon_const_expr(&mut self) -> PResult<'a, AnonConst> {
110 self.parse_expr().map(|value| AnonConst { id: DUMMY_NODE_ID, value })
113 fn parse_expr_catch_underscore(&mut self) -> PResult<'a, P<Expr>> {
114 match self.parse_expr() {
115 Ok(expr) => Ok(expr),
116 Err(mut err) => match self.token.ident() {
117 Some((Ident { name: kw::Underscore, .. }, false))
118 if self.look_ahead(1, |t| t == &token::Comma) =>
120 // Special-case handling of `foo(_, _, _)`
123 Ok(self.mk_expr(self.prev_token.span, ExprKind::Err, AttrVec::new()))
130 /// Parses a sequence of expressions delimited by parentheses.
131 fn parse_paren_expr_seq(&mut self) -> PResult<'a, Vec<P<Expr>>> {
132 self.parse_paren_comma_seq(|p| p.parse_expr_catch_underscore()).map(|(r, _)| r)
135 /// Parses an expression, subject to the given restrictions.
137 pub(super) fn parse_expr_res(
140 already_parsed_attrs: Option<AttrWrapper>,
141 ) -> PResult<'a, P<Expr>> {
142 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
145 /// Parses an associative expression.
147 /// This parses an expression accounting for associativity and precedence of the operators in
152 already_parsed_attrs: Option<AttrWrapper>,
153 ) -> PResult<'a, P<Expr>> {
154 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
157 /// Parses an associative expression with operators of at least `min_prec` precedence.
158 pub(super) fn parse_assoc_expr_with(
162 ) -> PResult<'a, P<Expr>> {
163 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
166 let attrs = match lhs {
167 LhsExpr::AttributesParsed(attrs) => Some(attrs),
170 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token.kind) {
171 return self.parse_prefix_range_expr(attrs);
173 self.parse_prefix_expr(attrs)?
176 let last_type_ascription_set = self.last_type_ascription.is_some();
178 if !self.should_continue_as_assoc_expr(&lhs) {
179 self.last_type_ascription = None;
183 self.expected_tokens.push(TokenType::Operator);
184 while let Some(op) = self.check_assoc_op() {
185 // Adjust the span for interpolated LHS to point to the `$lhs` token
186 // and not to what it refers to.
187 let lhs_span = match self.prev_token.kind {
188 TokenKind::Interpolated(..) => self.prev_token.span,
192 let cur_op_span = self.token.span;
193 let restrictions = if op.node.is_assign_like() {
194 self.restrictions & Restrictions::NO_STRUCT_LITERAL
198 let prec = op.node.precedence();
202 // Check for deprecated `...` syntax
203 if self.token == token::DotDotDot && op.node == AssocOp::DotDotEq {
204 self.err_dotdotdot_syntax(self.token.span);
207 if self.token == token::LArrow {
208 self.err_larrow_operator(self.token.span);
212 if op.node.is_comparison() {
213 if let Some(expr) = self.check_no_chained_comparison(&lhs, &op)? {
218 // Look for JS' `===` and `!==` and recover
219 if (op.node == AssocOp::Equal || op.node == AssocOp::NotEqual)
220 && self.token.kind == token::Eq
221 && self.prev_token.span.hi() == self.token.span.lo()
223 let sp = op.span.to(self.token.span);
224 let sugg = match op.node {
225 AssocOp::Equal => "==",
226 AssocOp::NotEqual => "!=",
229 self.struct_span_err(sp, &format!("invalid comparison operator `{sugg}=`"))
230 .span_suggestion_short(
232 &format!("`{s}=` is not a valid comparison operator, use `{s}`", s = sugg),
234 Applicability::MachineApplicable,
240 // Look for PHP's `<>` and recover
241 if op.node == AssocOp::Less
242 && self.token.kind == token::Gt
243 && self.prev_token.span.hi() == self.token.span.lo()
245 let sp = op.span.to(self.token.span);
246 self.struct_span_err(sp, "invalid comparison operator `<>`")
247 .span_suggestion_short(
249 "`<>` is not a valid comparison operator, use `!=`",
251 Applicability::MachineApplicable,
257 // Look for C++'s `<=>` and recover
258 if op.node == AssocOp::LessEqual
259 && self.token.kind == token::Gt
260 && self.prev_token.span.hi() == self.token.span.lo()
262 let sp = op.span.to(self.token.span);
263 self.struct_span_err(sp, "invalid comparison operator `<=>`")
266 "`<=>` is not a valid comparison operator, use `std::cmp::Ordering`",
272 if self.prev_token == token::BinOp(token::Plus)
273 && self.token == token::BinOp(token::Plus)
274 && self.prev_token.span.between(self.token.span).is_empty()
276 let op_span = self.prev_token.span.to(self.token.span);
277 // Eat the second `+`
279 lhs = self.recover_from_postfix_increment(lhs, op_span)?;
285 if op == AssocOp::As {
286 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
288 } else if op == AssocOp::Colon {
289 lhs = self.parse_assoc_op_ascribe(lhs, lhs_span)?;
291 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
292 // If we didn't have to handle `x..`/`x..=`, it would be pretty easy to
293 // generalise it to the Fixity::None code.
294 lhs = self.parse_range_expr(prec, lhs, op, cur_op_span)?;
298 let fixity = op.fixity();
299 let prec_adjustment = match fixity {
302 // We currently have no non-associative operators that are not handled above by
303 // the special cases. The code is here only for future convenience.
306 let rhs = self.with_res(restrictions - Restrictions::STMT_EXPR, |this| {
307 this.parse_assoc_expr_with(prec + prec_adjustment, LhsExpr::NotYetParsed)
310 let span = self.mk_expr_sp(&lhs, lhs_span, rhs.span);
323 | AssocOp::ShiftRight
329 | AssocOp::GreaterEqual => {
330 let ast_op = op.to_ast_binop().unwrap();
331 let binary = self.mk_binary(source_map::respan(cur_op_span, ast_op), lhs, rhs);
332 self.mk_expr(span, binary, AttrVec::new())
335 self.mk_expr(span, ExprKind::Assign(lhs, rhs, cur_op_span), AttrVec::new())
337 AssocOp::AssignOp(k) => {
339 token::Plus => BinOpKind::Add,
340 token::Minus => BinOpKind::Sub,
341 token::Star => BinOpKind::Mul,
342 token::Slash => BinOpKind::Div,
343 token::Percent => BinOpKind::Rem,
344 token::Caret => BinOpKind::BitXor,
345 token::And => BinOpKind::BitAnd,
346 token::Or => BinOpKind::BitOr,
347 token::Shl => BinOpKind::Shl,
348 token::Shr => BinOpKind::Shr,
350 let aopexpr = self.mk_assign_op(source_map::respan(cur_op_span, aop), lhs, rhs);
351 self.mk_expr(span, aopexpr, AttrVec::new())
353 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
354 self.span_bug(span, "AssocOp should have been handled by special case")
358 if let Fixity::None = fixity {
362 if last_type_ascription_set {
363 self.last_type_ascription = None;
368 fn should_continue_as_assoc_expr(&mut self, lhs: &Expr) -> bool {
369 match (self.expr_is_complete(lhs), AssocOp::from_token(&self.token)) {
370 // Semi-statement forms are odd:
371 // See https://github.com/rust-lang/rust/issues/29071
372 (true, None) => false,
373 (false, _) => true, // Continue parsing the expression.
374 // An exhaustive check is done in the following block, but these are checked first
375 // because they *are* ambiguous but also reasonable looking incorrect syntax, so we
376 // want to keep their span info to improve diagnostics in these cases in a later stage.
377 (true, Some(AssocOp::Multiply)) | // `{ 42 } *foo = bar;` or `{ 42 } * 3`
378 (true, Some(AssocOp::Subtract)) | // `{ 42 } -5`
379 (true, Some(AssocOp::Add)) // `{ 42 } + 42
380 // If the next token is a keyword, then the tokens above *are* unambiguously incorrect:
381 // `if x { a } else { b } && if y { c } else { d }`
382 if !self.look_ahead(1, |t| t.is_used_keyword()) => {
383 // These cases are ambiguous and can't be identified in the parser alone.
384 let sp = self.sess.source_map().start_point(self.token.span);
385 self.sess.ambiguous_block_expr_parse.borrow_mut().insert(sp, lhs.span);
388 (true, Some(AssocOp::LAnd)) |
389 (true, Some(AssocOp::LOr)) |
390 (true, Some(AssocOp::BitOr)) => {
391 // `{ 42 } &&x` (#61475) or `{ 42 } && if x { 1 } else { 0 }`. Separated from the
392 // above due to #74233.
393 // These cases are ambiguous and can't be identified in the parser alone.
395 // Bitwise AND is left out because guessing intent is hard. We can make
396 // suggestions based on the assumption that double-refs are rarely intentional,
397 // and closures are distinct enough that they don't get mixed up with their
399 let sp = self.sess.source_map().start_point(self.token.span);
400 self.sess.ambiguous_block_expr_parse.borrow_mut().insert(sp, lhs.span);
403 (true, Some(ref op)) if !op.can_continue_expr_unambiguously() => false,
405 self.error_found_expr_would_be_stmt(lhs);
411 /// We've found an expression that would be parsed as a statement,
412 /// but the next token implies this should be parsed as an expression.
413 /// For example: `if let Some(x) = x { x } else { 0 } / 2`.
414 fn error_found_expr_would_be_stmt(&self, lhs: &Expr) {
415 let mut err = self.struct_span_err(
417 &format!("expected expression, found `{}`", pprust::token_to_string(&self.token),),
419 err.span_label(self.token.span, "expected expression");
420 self.sess.expr_parentheses_needed(&mut err, lhs.span);
424 /// Possibly translate the current token to an associative operator.
425 /// The method does not advance the current token.
427 /// Also performs recovery for `and` / `or` which are mistaken for `&&` and `||` respectively.
428 fn check_assoc_op(&self) -> Option<Spanned<AssocOp>> {
429 let (op, span) = match (AssocOp::from_token(&self.token), self.token.ident()) {
430 // When parsing const expressions, stop parsing when encountering `>`.
435 | AssocOp::GreaterEqual
436 | AssocOp::AssignOp(token::BinOpToken::Shr),
439 ) if self.restrictions.contains(Restrictions::CONST_EXPR) => {
442 (Some(op), _) => (op, self.token.span),
443 (None, Some((Ident { name: sym::and, span }, false))) => {
444 self.error_bad_logical_op("and", "&&", "conjunction");
445 (AssocOp::LAnd, span)
447 (None, Some((Ident { name: sym::or, span }, false))) => {
448 self.error_bad_logical_op("or", "||", "disjunction");
453 Some(source_map::respan(span, op))
456 /// Error on `and` and `or` suggesting `&&` and `||` respectively.
457 fn error_bad_logical_op(&self, bad: &str, good: &str, english: &str) {
458 self.struct_span_err(self.token.span, &format!("`{bad}` is not a logical operator"))
459 .span_suggestion_short(
461 &format!("use `{good}` to perform logical {english}"),
463 Applicability::MachineApplicable,
465 .note("unlike in e.g., python and PHP, `&&` and `||` are used for logical operators")
469 /// Checks if this expression is a successfully parsed statement.
470 fn expr_is_complete(&self, e: &Expr) -> bool {
471 self.restrictions.contains(Restrictions::STMT_EXPR)
472 && !classify::expr_requires_semi_to_be_stmt(e)
475 /// Parses `x..y`, `x..=y`, and `x..`/`x..=`.
476 /// The other two variants are handled in `parse_prefix_range_expr` below.
483 ) -> PResult<'a, P<Expr>> {
484 let rhs = if self.is_at_start_of_range_notation_rhs() {
485 Some(self.parse_assoc_expr_with(prec + 1, LhsExpr::NotYetParsed)?)
489 let rhs_span = rhs.as_ref().map_or(cur_op_span, |x| x.span);
490 let span = self.mk_expr_sp(&lhs, lhs.span, rhs_span);
492 if op == AssocOp::DotDot { RangeLimits::HalfOpen } else { RangeLimits::Closed };
493 let range = self.mk_range(Some(lhs), rhs, limits);
494 Ok(self.mk_expr(span, range, AttrVec::new()))
497 fn is_at_start_of_range_notation_rhs(&self) -> bool {
498 if self.token.can_begin_expr() {
499 // Parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
500 if self.token == token::OpenDelim(Delimiter::Brace) {
501 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
509 /// Parses prefix-forms of range notation: `..expr`, `..`, `..=expr`.
510 fn parse_prefix_range_expr(&mut self, attrs: Option<AttrWrapper>) -> PResult<'a, P<Expr>> {
511 // Check for deprecated `...` syntax.
512 if self.token == token::DotDotDot {
513 self.err_dotdotdot_syntax(self.token.span);
517 [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token.kind),
518 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
522 let limits = match self.token.kind {
523 token::DotDot => RangeLimits::HalfOpen,
524 _ => RangeLimits::Closed,
526 let op = AssocOp::from_token(&self.token);
527 // FIXME: `parse_prefix_range_expr` is called when the current
528 // token is `DotDot`, `DotDotDot`, or `DotDotEq`. If we haven't already
529 // parsed attributes, then trying to parse them here will always fail.
530 // We should figure out how we want attributes on range expressions to work.
531 let attrs = self.parse_or_use_outer_attributes(attrs)?;
532 self.collect_tokens_for_expr(attrs, |this, attrs| {
533 let lo = this.token.span;
535 let (span, opt_end) = if this.is_at_start_of_range_notation_rhs() {
536 // RHS must be parsed with more associativity than the dots.
537 this.parse_assoc_expr_with(op.unwrap().precedence() + 1, LhsExpr::NotYetParsed)
538 .map(|x| (lo.to(x.span), Some(x)))?
542 let range = this.mk_range(None, opt_end, limits);
543 Ok(this.mk_expr(span, range, attrs.into()))
547 /// Parses a prefix-unary-operator expr.
548 fn parse_prefix_expr(&mut self, attrs: Option<AttrWrapper>) -> PResult<'a, P<Expr>> {
549 let attrs = self.parse_or_use_outer_attributes(attrs)?;
550 let lo = self.token.span;
552 macro_rules! make_it {
553 ($this:ident, $attrs:expr, |this, _| $body:expr) => {
554 $this.collect_tokens_for_expr($attrs, |$this, attrs| {
555 let (hi, ex) = $body?;
556 Ok($this.mk_expr(lo.to(hi), ex, attrs.into()))
563 // Note: when adding new unary operators, don't forget to adjust TokenKind::can_begin_expr()
564 match this.token.uninterpolate().kind {
565 token::Not => make_it!(this, attrs, |this, _| this.parse_unary_expr(lo, UnOp::Not)), // `!expr`
566 token::Tilde => make_it!(this, attrs, |this, _| this.recover_tilde_expr(lo)), // `~expr`
567 token::BinOp(token::Minus) => {
568 make_it!(this, attrs, |this, _| this.parse_unary_expr(lo, UnOp::Neg))
570 token::BinOp(token::Star) => {
571 make_it!(this, attrs, |this, _| this.parse_unary_expr(lo, UnOp::Deref))
573 token::BinOp(token::And) | token::AndAnd => {
574 make_it!(this, attrs, |this, _| this.parse_borrow_expr(lo))
576 token::BinOp(token::Plus) if this.look_ahead(1, |tok| tok.is_numeric_lit()) => {
577 let mut err = this.struct_span_err(lo, "leading `+` is not supported");
578 err.span_label(lo, "unexpected `+`");
580 // a block on the LHS might have been intended to be an expression instead
581 if let Some(sp) = this.sess.ambiguous_block_expr_parse.borrow().get(&lo) {
582 this.sess.expr_parentheses_needed(&mut err, *sp);
584 err.span_suggestion_verbose(
586 "try removing the `+`",
588 Applicability::MachineApplicable,
594 this.parse_prefix_expr(None)
596 // Recover from `++x`:
597 token::BinOp(token::Plus)
598 if this.look_ahead(1, |t| *t == token::BinOp(token::Plus)) =>
600 let prev_is_semi = this.prev_token == token::Semi;
601 let pre_span = this.token.span.to(this.look_ahead(1, |t| t.span));
606 let operand_expr = this.parse_dot_or_call_expr(Default::default())?;
607 this.recover_from_prefix_increment(operand_expr, pre_span, prev_is_semi)
609 token::Ident(..) if this.token.is_keyword(kw::Box) => {
610 make_it!(this, attrs, |this, _| this.parse_box_expr(lo))
612 token::Ident(..) if this.is_mistaken_not_ident_negation() => {
613 make_it!(this, attrs, |this, _| this.recover_not_expr(lo))
615 _ => return this.parse_dot_or_call_expr(Some(attrs)),
619 fn parse_prefix_expr_common(&mut self, lo: Span) -> PResult<'a, (Span, P<Expr>)> {
621 let expr = self.parse_prefix_expr(None);
622 let (span, expr) = self.interpolated_or_expr_span(expr)?;
623 Ok((lo.to(span), expr))
626 fn parse_unary_expr(&mut self, lo: Span, op: UnOp) -> PResult<'a, (Span, ExprKind)> {
627 let (span, expr) = self.parse_prefix_expr_common(lo)?;
628 Ok((span, self.mk_unary(op, expr)))
631 // Recover on `!` suggesting for bitwise negation instead.
632 fn recover_tilde_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
633 self.struct_span_err(lo, "`~` cannot be used as a unary operator")
634 .span_suggestion_short(
636 "use `!` to perform bitwise not",
638 Applicability::MachineApplicable,
642 self.parse_unary_expr(lo, UnOp::Not)
645 /// Parse `box expr`.
646 fn parse_box_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
647 let (span, expr) = self.parse_prefix_expr_common(lo)?;
648 self.sess.gated_spans.gate(sym::box_syntax, span);
649 Ok((span, ExprKind::Box(expr)))
652 fn is_mistaken_not_ident_negation(&self) -> bool {
653 let token_cannot_continue_expr = |t: &Token| match t.uninterpolate().kind {
654 // These tokens can start an expression after `!`, but
655 // can't continue an expression after an ident
656 token::Ident(name, is_raw) => token::ident_can_begin_expr(name, t.span, is_raw),
657 token::Literal(..) | token::Pound => true,
658 _ => t.is_whole_expr(),
660 self.token.is_ident_named(sym::not) && self.look_ahead(1, token_cannot_continue_expr)
663 /// Recover on `not expr` in favor of `!expr`.
664 fn recover_not_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
666 let not_token = self.look_ahead(1, |t| t.clone());
667 self.struct_span_err(
669 &format!("unexpected {} after identifier", super::token_descr(¬_token)),
671 .span_suggestion_short(
672 // Span the `not` plus trailing whitespace to avoid
673 // trailing whitespace after the `!` in our suggestion
674 self.sess.source_map().span_until_non_whitespace(lo.to(not_token.span)),
675 "use `!` to perform logical negation",
677 Applicability::MachineApplicable,
682 self.parse_unary_expr(lo, UnOp::Not)
685 /// Returns the span of expr, if it was not interpolated or the span of the interpolated token.
686 fn interpolated_or_expr_span(
688 expr: PResult<'a, P<Expr>>,
689 ) -> PResult<'a, (Span, P<Expr>)> {
692 match self.prev_token.kind {
693 TokenKind::Interpolated(..) => self.prev_token.span,
701 fn parse_assoc_op_cast(
705 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind,
706 ) -> PResult<'a, P<Expr>> {
707 let mk_expr = |this: &mut Self, lhs: P<Expr>, rhs: P<Ty>| {
709 this.mk_expr_sp(&lhs, lhs_span, rhs.span),
715 // Save the state of the parser before parsing type normally, in case there is a
716 // LessThan comparison after this cast.
717 let parser_snapshot_before_type = self.clone();
718 let cast_expr = match self.parse_as_cast_ty() {
719 Ok(rhs) => mk_expr(self, lhs, rhs),
721 // Rewind to before attempting to parse the type with generics, to recover
722 // from situations like `x as usize < y` in which we first tried to parse
723 // `usize < y` as a type with generic arguments.
724 let parser_snapshot_after_type = mem::replace(self, parser_snapshot_before_type);
726 // Check for typo of `'a: loop { break 'a }` with a missing `'`.
727 match (&lhs.kind, &self.token.kind) {
730 ExprKind::Path(None, ast::Path { segments, .. }),
731 TokenKind::Ident(kw::For | kw::Loop | kw::While, false),
732 ) if segments.len() == 1 => {
733 let snapshot = self.create_snapshot_for_diagnostic();
735 ident: Ident::from_str_and_span(
736 &format!("'{}", segments[0].ident),
737 segments[0].ident.span,
740 match self.parse_labeled_expr(label, AttrVec::new(), false) {
743 self.struct_span_err(label.ident.span, "malformed loop label")
746 "use the correct loop label format",
748 Applicability::MachineApplicable,
755 self.restore_snapshot(snapshot);
762 match self.parse_path(PathStyle::Expr) {
764 let (op_noun, op_verb) = match self.token.kind {
765 token::Lt => ("comparison", "comparing"),
766 token::BinOp(token::Shl) => ("shift", "shifting"),
768 // We can end up here even without `<` being the next token, for
769 // example because `parse_ty_no_plus` returns `Err` on keywords,
770 // but `parse_path` returns `Ok` on them due to error recovery.
771 // Return original error and parser state.
772 *self = parser_snapshot_after_type;
773 return Err(type_err);
777 // Successfully parsed the type path leaving a `<` yet to parse.
780 // Report non-fatal diagnostics, keep `x as usize` as an expression
781 // in AST and continue parsing.
783 "`<` is interpreted as a start of generic arguments for `{}`, not a {}",
784 pprust::path_to_string(&path),
787 let span_after_type = parser_snapshot_after_type.token.span;
789 mk_expr(self, lhs, self.mk_ty(path.span, TyKind::Path(None, path)));
791 self.struct_span_err(self.token.span, &msg)
793 self.look_ahead(1, |t| t.span).to(span_after_type),
794 "interpreted as generic arguments",
796 .span_label(self.token.span, format!("not interpreted as {op_noun}"))
797 .multipart_suggestion(
798 &format!("try {op_verb} the cast value"),
800 (expr.span.shrink_to_lo(), "(".to_string()),
801 (expr.span.shrink_to_hi(), ")".to_string()),
803 Applicability::MachineApplicable,
810 // Couldn't parse as a path, return original error and parser state.
812 *self = parser_snapshot_after_type;
813 return Err(type_err);
819 self.parse_and_disallow_postfix_after_cast(cast_expr)
822 /// Parses a postfix operators such as `.`, `?`, or index (`[]`) after a cast,
823 /// then emits an error and returns the newly parsed tree.
824 /// The resulting parse tree for `&x as T[0]` has a precedence of `((&x) as T)[0]`.
825 fn parse_and_disallow_postfix_after_cast(
828 ) -> PResult<'a, P<Expr>> {
829 let span = cast_expr.span;
830 let maybe_ascription_span = if let ExprKind::Type(ascripted_expr, _) = &cast_expr.kind {
831 Some(ascripted_expr.span.shrink_to_hi().with_hi(span.hi()))
836 // Save the memory location of expr before parsing any following postfix operators.
837 // This will be compared with the memory location of the output expression.
838 // If they different we can assume we parsed another expression because the existing expression is not reallocated.
839 let addr_before = &*cast_expr as *const _ as usize;
840 let with_postfix = self.parse_dot_or_call_expr_with_(cast_expr, span)?;
841 let changed = addr_before != &*with_postfix as *const _ as usize;
843 // Check if an illegal postfix operator has been added after the cast.
844 // If the resulting expression is not a cast, or has a different memory location, it is an illegal postfix operator.
845 if !matches!(with_postfix.kind, ExprKind::Cast(_, _) | ExprKind::Type(_, _)) || changed {
847 "casts cannot be followed by {}",
848 match with_postfix.kind {
849 ExprKind::Index(_, _) => "indexing",
850 ExprKind::Try(_) => "`?`",
851 ExprKind::Field(_, _) => "a field access",
852 ExprKind::MethodCall(_, _, _) => "a method call",
853 ExprKind::Call(_, _) => "a function call",
854 ExprKind::Await(_) => "`.await`",
855 ExprKind::Err => return Ok(with_postfix),
856 _ => unreachable!("parse_dot_or_call_expr_with_ shouldn't produce this"),
859 let mut err = self.struct_span_err(span, &msg);
861 let suggest_parens = |err: &mut DiagnosticBuilder<'_, _>| {
862 let suggestions = vec![
863 (span.shrink_to_lo(), "(".to_string()),
864 (span.shrink_to_hi(), ")".to_string()),
866 err.multipart_suggestion(
867 "try surrounding the expression in parentheses",
869 Applicability::MachineApplicable,
873 // If type ascription is "likely an error", the user will already be getting a useful
874 // help message, and doesn't need a second.
875 if self.last_type_ascription.map_or(false, |last_ascription| last_ascription.1) {
876 self.maybe_annotate_with_ascription(&mut err, false);
877 } else if let Some(ascription_span) = maybe_ascription_span {
878 let is_nightly = self.sess.unstable_features.is_nightly_build();
880 suggest_parens(&mut err);
885 "{}remove the type ascription",
886 if is_nightly { "alternatively, " } else { "" }
890 Applicability::MaybeIncorrect
892 Applicability::MachineApplicable
896 suggest_parens(&mut err);
903 fn parse_assoc_op_ascribe(&mut self, lhs: P<Expr>, lhs_span: Span) -> PResult<'a, P<Expr>> {
904 let maybe_path = self.could_ascription_be_path(&lhs.kind);
905 self.last_type_ascription = Some((self.prev_token.span, maybe_path));
906 let lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type)?;
907 self.sess.gated_spans.gate(sym::type_ascription, lhs.span);
911 /// Parse `& mut? <expr>` or `& raw [ const | mut ] <expr>`.
912 fn parse_borrow_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
914 let has_lifetime = self.token.is_lifetime() && self.look_ahead(1, |t| t != &token::Colon);
915 let lifetime = has_lifetime.then(|| self.expect_lifetime()); // For recovery, see below.
916 let (borrow_kind, mutbl) = self.parse_borrow_modifiers(lo);
917 let expr = self.parse_prefix_expr(None);
918 let (hi, expr) = self.interpolated_or_expr_span(expr)?;
919 let span = lo.to(hi);
920 if let Some(lt) = lifetime {
921 self.error_remove_borrow_lifetime(span, lt.ident.span);
923 Ok((span, ExprKind::AddrOf(borrow_kind, mutbl, expr)))
926 fn error_remove_borrow_lifetime(&self, span: Span, lt_span: Span) {
927 self.struct_span_err(span, "borrow expressions cannot be annotated with lifetimes")
928 .span_label(lt_span, "annotated with lifetime here")
931 "remove the lifetime annotation",
933 Applicability::MachineApplicable,
938 /// Parse `mut?` or `raw [ const | mut ]`.
939 fn parse_borrow_modifiers(&mut self, lo: Span) -> (ast::BorrowKind, ast::Mutability) {
940 if self.check_keyword(kw::Raw) && self.look_ahead(1, Token::is_mutability) {
941 // `raw [ const | mut ]`.
942 let found_raw = self.eat_keyword(kw::Raw);
944 let mutability = self.parse_const_or_mut().unwrap();
945 self.sess.gated_spans.gate(sym::raw_ref_op, lo.to(self.prev_token.span));
946 (ast::BorrowKind::Raw, mutability)
949 (ast::BorrowKind::Ref, self.parse_mutability())
953 /// Parses `a.b` or `a(13)` or `a[4]` or just `a`.
954 fn parse_dot_or_call_expr(&mut self, attrs: Option<AttrWrapper>) -> PResult<'a, P<Expr>> {
955 let attrs = self.parse_or_use_outer_attributes(attrs)?;
956 self.collect_tokens_for_expr(attrs, |this, attrs| {
957 let base = this.parse_bottom_expr();
958 let (span, base) = this.interpolated_or_expr_span(base)?;
959 this.parse_dot_or_call_expr_with(base, span, attrs)
963 pub(super) fn parse_dot_or_call_expr_with(
967 mut attrs: Vec<ast::Attribute>,
968 ) -> PResult<'a, P<Expr>> {
969 // Stitch the list of outer attributes onto the return value.
970 // A little bit ugly, but the best way given the current code
972 self.parse_dot_or_call_expr_with_(e0, lo).map(|expr| {
973 expr.map(|mut expr| {
974 attrs.extend::<Vec<_>>(expr.attrs.into());
975 expr.attrs = attrs.into();
981 fn parse_dot_or_call_expr_with_(&mut self, mut e: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
983 let has_question = if self.prev_token.kind == TokenKind::Ident(kw::Return, false) {
984 // we are using noexpect here because we don't expect a `?` directly after a `return`
985 // which could be suggested otherwise
986 self.eat_noexpect(&token::Question)
988 self.eat(&token::Question)
992 e = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Try(e), AttrVec::new());
995 let has_dot = if self.prev_token.kind == TokenKind::Ident(kw::Return, false) {
996 // we are using noexpect here because we don't expect a `.` directly after a `return`
997 // which could be suggested otherwise
998 self.eat_noexpect(&token::Dot)
1000 self.eat(&token::Dot)
1004 e = self.parse_dot_suffix_expr(lo, e)?;
1007 if self.expr_is_complete(&e) {
1010 e = match self.token.kind {
1011 token::OpenDelim(Delimiter::Parenthesis) => self.parse_fn_call_expr(lo, e),
1012 token::OpenDelim(Delimiter::Bracket) => self.parse_index_expr(lo, e)?,
1018 fn look_ahead_type_ascription_as_field(&mut self) -> bool {
1019 self.look_ahead(1, |t| t.is_ident())
1020 && self.look_ahead(2, |t| t == &token::Colon)
1021 && self.look_ahead(3, |t| t.can_begin_expr())
1024 fn parse_dot_suffix_expr(&mut self, lo: Span, base: P<Expr>) -> PResult<'a, P<Expr>> {
1025 match self.token.uninterpolate().kind {
1026 token::Ident(..) => self.parse_dot_suffix(base, lo),
1027 token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) => {
1028 Ok(self.parse_tuple_field_access_expr(lo, base, symbol, suffix, None))
1030 token::Literal(token::Lit { kind: token::Float, symbol, suffix }) => {
1031 Ok(self.parse_tuple_field_access_expr_float(lo, base, symbol, suffix))
1034 self.error_unexpected_after_dot();
1040 fn error_unexpected_after_dot(&self) {
1041 // FIXME Could factor this out into non_fatal_unexpected or something.
1042 let actual = pprust::token_to_string(&self.token);
1043 self.struct_span_err(self.token.span, &format!("unexpected token: `{actual}`")).emit();
1046 // We need an identifier or integer, but the next token is a float.
1047 // Break the float into components to extract the identifier or integer.
1048 // FIXME: With current `TokenCursor` it's hard to break tokens into more than 2
1049 // parts unless those parts are processed immediately. `TokenCursor` should either
1050 // support pushing "future tokens" (would be also helpful to `break_and_eat`), or
1051 // we should break everything including floats into more basic proc-macro style
1052 // tokens in the lexer (probably preferable).
1053 fn parse_tuple_field_access_expr_float(
1058 suffix: Option<Symbol>,
1061 enum FloatComponent {
1065 use FloatComponent::*;
1067 let float_str = float.as_str();
1068 let mut components = Vec::new();
1069 let mut ident_like = String::new();
1070 for c in float_str.chars() {
1071 if c == '_' || c.is_ascii_alphanumeric() {
1073 } else if matches!(c, '.' | '+' | '-') {
1074 if !ident_like.is_empty() {
1075 components.push(IdentLike(mem::take(&mut ident_like)));
1077 components.push(Punct(c));
1079 panic!("unexpected character in a float token: {:?}", c)
1082 if !ident_like.is_empty() {
1083 components.push(IdentLike(ident_like));
1086 // With proc macros the span can refer to anything, the source may be too short,
1087 // or too long, or non-ASCII. It only makes sense to break our span into components
1088 // if its underlying text is identical to our float literal.
1089 let span = self.token.span;
1090 let can_take_span_apart =
1091 || self.span_to_snippet(span).as_deref() == Ok(float_str).as_deref();
1093 match &*components {
1096 self.parse_tuple_field_access_expr(lo, base, Symbol::intern(&i), suffix, None)
1099 [IdentLike(i), Punct('.')] => {
1100 let (ident_span, dot_span) = if can_take_span_apart() {
1101 let (span, ident_len) = (span.data(), BytePos::from_usize(i.len()));
1102 let ident_span = span.with_hi(span.lo + ident_len);
1103 let dot_span = span.with_lo(span.lo + ident_len);
1104 (ident_span, dot_span)
1108 assert!(suffix.is_none());
1109 let symbol = Symbol::intern(&i);
1110 self.token = Token::new(token::Ident(symbol, false), ident_span);
1111 let next_token = (Token::new(token::Dot, dot_span), self.token_spacing);
1112 self.parse_tuple_field_access_expr(lo, base, symbol, None, Some(next_token))
1115 [IdentLike(i1), Punct('.'), IdentLike(i2)] => {
1116 let (ident1_span, dot_span, ident2_span) = if can_take_span_apart() {
1117 let (span, ident1_len) = (span.data(), BytePos::from_usize(i1.len()));
1118 let ident1_span = span.with_hi(span.lo + ident1_len);
1120 .with_lo(span.lo + ident1_len)
1121 .with_hi(span.lo + ident1_len + BytePos(1));
1122 let ident2_span = self.token.span.with_lo(span.lo + ident1_len + BytePos(1));
1123 (ident1_span, dot_span, ident2_span)
1127 let symbol1 = Symbol::intern(&i1);
1128 self.token = Token::new(token::Ident(symbol1, false), ident1_span);
1129 // This needs to be `Spacing::Alone` to prevent regressions.
1130 // See issue #76399 and PR #76285 for more details
1131 let next_token1 = (Token::new(token::Dot, dot_span), Spacing::Alone);
1133 self.parse_tuple_field_access_expr(lo, base, symbol1, None, Some(next_token1));
1134 let symbol2 = Symbol::intern(&i2);
1135 let next_token2 = Token::new(token::Ident(symbol2, false), ident2_span);
1136 self.bump_with((next_token2, self.token_spacing)); // `.`
1137 self.parse_tuple_field_access_expr(lo, base1, symbol2, suffix, None)
1139 // 1e+ | 1e- (recovered)
1140 [IdentLike(_), Punct('+' | '-')] |
1142 [IdentLike(_), Punct('+' | '-'), IdentLike(_)] |
1144 [IdentLike(_), Punct('.'), IdentLike(_), Punct('+' | '-')] |
1146 [IdentLike(_), Punct('.'), IdentLike(_), Punct('+' | '-'), IdentLike(_)] => {
1147 // See the FIXME about `TokenCursor` above.
1148 self.error_unexpected_after_dot();
1151 _ => panic!("unexpected components in a float token: {:?}", components),
1155 fn parse_tuple_field_access_expr(
1160 suffix: Option<Symbol>,
1161 next_token: Option<(Token, Spacing)>,
1164 Some(next_token) => self.bump_with(next_token),
1165 None => self.bump(),
1167 let span = self.prev_token.span;
1168 let field = ExprKind::Field(base, Ident::new(field, span));
1169 self.expect_no_suffix(span, "a tuple index", suffix);
1170 self.mk_expr(lo.to(span), field, AttrVec::new())
1173 /// Parse a function call expression, `expr(...)`.
1174 fn parse_fn_call_expr(&mut self, lo: Span, fun: P<Expr>) -> P<Expr> {
1175 let snapshot = if self.token.kind == token::OpenDelim(Delimiter::Parenthesis)
1176 && self.look_ahead_type_ascription_as_field()
1178 Some((self.create_snapshot_for_diagnostic(), fun.kind.clone()))
1182 let open_paren = self.token.span;
1184 let mut seq = self.parse_paren_expr_seq().map(|args| {
1185 self.mk_expr(lo.to(self.prev_token.span), self.mk_call(fun, args), AttrVec::new())
1188 self.maybe_recover_struct_lit_bad_delims(lo, open_paren, &mut seq, snapshot)
1192 self.recover_seq_parse_error(Delimiter::Parenthesis, lo, seq)
1195 /// If we encounter a parser state that looks like the user has written a `struct` literal with
1196 /// parentheses instead of braces, recover the parser state and provide suggestions.
1197 #[instrument(skip(self, seq, snapshot), level = "trace")]
1198 fn maybe_recover_struct_lit_bad_delims(
1202 seq: &mut PResult<'a, P<Expr>>,
1203 snapshot: Option<(SnapshotParser<'a>, ExprKind)>,
1204 ) -> Option<P<Expr>> {
1205 match (seq.as_mut(), snapshot) {
1206 (Err(err), Some((mut snapshot, ExprKind::Path(None, path)))) => {
1207 let name = pprust::path_to_string(&path);
1208 snapshot.bump(); // `(`
1209 match snapshot.parse_struct_fields(path, false, Delimiter::Parenthesis) {
1211 if snapshot.eat(&token::CloseDelim(Delimiter::Parenthesis)) =>
1213 // We are certain we have `Enum::Foo(a: 3, b: 4)`, suggest
1214 // `Enum::Foo { a: 3, b: 4 }` or `Enum::Foo(3, 4)`.
1215 self.restore_snapshot(snapshot);
1216 let close_paren = self.prev_token.span;
1217 let span = lo.to(self.prev_token.span);
1218 if !fields.is_empty() {
1219 let replacement_err = self.struct_span_err(
1221 "invalid `struct` delimiters or `fn` call arguments",
1223 mem::replace(err, replacement_err).cancel();
1225 err.multipart_suggestion(
1226 &format!("if `{name}` is a struct, use braces as delimiters"),
1228 (open_paren, " { ".to_string()),
1229 (close_paren, " }".to_string()),
1231 Applicability::MaybeIncorrect,
1233 err.multipart_suggestion(
1234 &format!("if `{name}` is a function, use the arguments directly"),
1237 .map(|field| (field.span.until(field.expr.span), String::new()))
1239 Applicability::MaybeIncorrect,
1245 return Some(self.mk_expr_err(span));
1258 /// Parse an indexing expression `expr[...]`.
1259 fn parse_index_expr(&mut self, lo: Span, base: P<Expr>) -> PResult<'a, P<Expr>> {
1261 let index = self.parse_expr()?;
1262 self.expect(&token::CloseDelim(Delimiter::Bracket))?;
1263 Ok(self.mk_expr(lo.to(self.prev_token.span), self.mk_index(base, index), AttrVec::new()))
1266 /// Assuming we have just parsed `.`, continue parsing into an expression.
1267 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
1268 if self.token.uninterpolated_span().rust_2018() && self.eat_keyword(kw::Await) {
1269 return Ok(self.mk_await_expr(self_arg, lo));
1272 let fn_span_lo = self.token.span;
1273 let mut segment = self.parse_path_segment(PathStyle::Expr, None)?;
1274 self.check_trailing_angle_brackets(&segment, &[&token::OpenDelim(Delimiter::Parenthesis)]);
1275 self.check_turbofish_missing_angle_brackets(&mut segment);
1277 if self.check(&token::OpenDelim(Delimiter::Parenthesis)) {
1278 // Method call `expr.f()`
1279 let mut args = self.parse_paren_expr_seq()?;
1280 args.insert(0, self_arg);
1282 let fn_span = fn_span_lo.to(self.prev_token.span);
1283 let span = lo.to(self.prev_token.span);
1284 Ok(self.mk_expr(span, ExprKind::MethodCall(segment, args, fn_span), AttrVec::new()))
1286 // Field access `expr.f`
1287 if let Some(args) = segment.args {
1288 self.struct_span_err(
1290 "field expressions cannot have generic arguments",
1295 let span = lo.to(self.prev_token.span);
1296 Ok(self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), AttrVec::new()))
1300 /// At the bottom (top?) of the precedence hierarchy,
1301 /// Parses things like parenthesized exprs, macros, `return`, etc.
1303 /// N.B., this does not parse outer attributes, and is private because it only works
1304 /// correctly if called from `parse_dot_or_call_expr()`.
1305 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
1306 maybe_recover_from_interpolated_ty_qpath!(self, true);
1307 maybe_whole_expr!(self);
1309 // Outer attributes are already parsed and will be
1310 // added to the return value after the fact.
1312 // Therefore, prevent sub-parser from parsing
1313 // attributes by giving them an empty "already-parsed" list.
1314 let attrs = AttrVec::new();
1316 // Note: when adding new syntax here, don't forget to adjust `TokenKind::can_begin_expr()`.
1317 let lo = self.token.span;
1318 if let token::Literal(_) = self.token.kind {
1319 // This match arm is a special-case of the `_` match arm below and
1320 // could be removed without changing functionality, but it's faster
1321 // to have it here, especially for programs with large constants.
1322 self.parse_lit_expr(attrs)
1323 } else if self.check(&token::OpenDelim(Delimiter::Parenthesis)) {
1324 self.parse_tuple_parens_expr(attrs)
1325 } else if self.check(&token::OpenDelim(Delimiter::Brace)) {
1326 self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs)
1327 } else if self.check(&token::BinOp(token::Or)) || self.check(&token::OrOr) {
1328 self.parse_closure_expr(attrs).map_err(|mut err| {
1329 // If the input is something like `if a { 1 } else { 2 } | if a { 3 } else { 4 }`
1330 // then suggest parens around the lhs.
1331 if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&lo) {
1332 self.sess.expr_parentheses_needed(&mut err, *sp);
1336 } else if self.check(&token::OpenDelim(Delimiter::Bracket)) {
1337 self.parse_array_or_repeat_expr(attrs, Delimiter::Bracket)
1338 } else if self.check_path() {
1339 self.parse_path_start_expr(attrs)
1340 } else if self.check_keyword(kw::Move) || self.check_keyword(kw::Static) {
1341 self.parse_closure_expr(attrs)
1342 } else if self.eat_keyword(kw::If) {
1343 self.parse_if_expr(attrs)
1344 } else if self.check_keyword(kw::For) {
1345 if self.choose_generics_over_qpath(1) {
1346 // NOTE(Centril, eddyb): DO NOT REMOVE! Beyond providing parser recovery,
1347 // this is an insurance policy in case we allow qpaths in (tuple-)struct patterns.
1348 // When `for <Foo as Bar>::Proj in $expr $block` is wanted,
1349 // you can disambiguate in favor of a pattern with `(...)`.
1350 self.recover_quantified_closure_expr(attrs)
1352 assert!(self.eat_keyword(kw::For));
1353 self.parse_for_expr(None, self.prev_token.span, attrs)
1355 } else if self.eat_keyword(kw::While) {
1356 self.parse_while_expr(None, self.prev_token.span, attrs)
1357 } else if let Some(label) = self.eat_label() {
1358 self.parse_labeled_expr(label, attrs, true)
1359 } else if self.eat_keyword(kw::Loop) {
1360 let sp = self.prev_token.span;
1361 self.parse_loop_expr(None, self.prev_token.span, attrs).map_err(|mut err| {
1362 err.span_label(sp, "while parsing this `loop` expression");
1365 } else if self.eat_keyword(kw::Continue) {
1366 let kind = ExprKind::Continue(self.eat_label());
1367 Ok(self.mk_expr(lo.to(self.prev_token.span), kind, attrs))
1368 } else if self.eat_keyword(kw::Match) {
1369 let match_sp = self.prev_token.span;
1370 self.parse_match_expr(attrs).map_err(|mut err| {
1371 err.span_label(match_sp, "while parsing this `match` expression");
1374 } else if self.eat_keyword(kw::Unsafe) {
1375 let sp = self.prev_token.span;
1376 self.parse_block_expr(None, lo, BlockCheckMode::Unsafe(ast::UserProvided), attrs)
1377 .map_err(|mut err| {
1378 err.span_label(sp, "while parsing this `unsafe` expression");
1381 } else if self.check_inline_const(0) {
1382 self.parse_const_block(lo.to(self.token.span), false)
1383 } else if self.is_do_catch_block() {
1384 self.recover_do_catch(attrs)
1385 } else if self.is_try_block() {
1386 self.expect_keyword(kw::Try)?;
1387 self.parse_try_block(lo, attrs)
1388 } else if self.eat_keyword(kw::Return) {
1389 self.parse_return_expr(attrs)
1390 } else if self.eat_keyword(kw::Break) {
1391 self.parse_break_expr(attrs)
1392 } else if self.eat_keyword(kw::Yield) {
1393 self.parse_yield_expr(attrs)
1394 } else if self.is_do_yeet() {
1395 self.parse_yeet_expr(attrs)
1396 } else if self.check_keyword(kw::Let) {
1397 self.manage_let_chains_context();
1399 self.parse_let_expr(attrs)
1400 } else if self.eat_keyword(kw::Underscore) {
1401 Ok(self.mk_expr(self.prev_token.span, ExprKind::Underscore, attrs))
1402 } else if !self.unclosed_delims.is_empty() && self.check(&token::Semi) {
1403 // Don't complain about bare semicolons after unclosed braces
1404 // recovery in order to keep the error count down. Fixing the
1405 // delimiters will possibly also fix the bare semicolon found in
1406 // expression context. For example, silence the following error:
1408 // error: expected expression, found `;`
1412 // | ^ expected expression
1414 Ok(self.mk_expr_err(self.token.span))
1415 } else if self.token.uninterpolated_span().rust_2018() {
1416 // `Span::rust_2018()` is somewhat expensive; don't get it repeatedly.
1417 if self.check_keyword(kw::Async) {
1418 if self.is_async_block() {
1419 // Check for `async {` and `async move {`.
1420 self.parse_async_block(attrs)
1422 self.parse_closure_expr(attrs)
1424 } else if self.eat_keyword(kw::Await) {
1425 self.recover_incorrect_await_syntax(lo, self.prev_token.span, attrs)
1427 self.parse_lit_expr(attrs)
1430 self.parse_lit_expr(attrs)
1434 fn parse_lit_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1435 let lo = self.token.span;
1436 match self.parse_opt_lit() {
1438 let expr = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Lit(literal), attrs);
1439 self.maybe_recover_from_bad_qpath(expr)
1441 None => self.try_macro_suggestion(),
1445 fn parse_tuple_parens_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1446 let lo = self.token.span;
1447 self.expect(&token::OpenDelim(Delimiter::Parenthesis))?;
1448 let (es, trailing_comma) = match self.parse_seq_to_end(
1449 &token::CloseDelim(Delimiter::Parenthesis),
1450 SeqSep::trailing_allowed(token::Comma),
1451 |p| p.parse_expr_catch_underscore(),
1455 return Ok(self.recover_seq_parse_error(Delimiter::Parenthesis, lo, Err(err)));
1458 let kind = if es.len() == 1 && !trailing_comma {
1459 // `(e)` is parenthesized `e`.
1460 ExprKind::Paren(es.into_iter().next().unwrap())
1462 // `(e,)` is a tuple with only one field, `e`.
1465 let expr = self.mk_expr(lo.to(self.prev_token.span), kind, attrs);
1466 self.maybe_recover_from_bad_qpath(expr)
1469 fn parse_array_or_repeat_expr(
1472 close_delim: Delimiter,
1473 ) -> PResult<'a, P<Expr>> {
1474 let lo = self.token.span;
1475 self.bump(); // `[` or other open delim
1477 let close = &token::CloseDelim(close_delim);
1478 let kind = if self.eat(close) {
1480 ExprKind::Array(Vec::new())
1483 let first_expr = self.parse_expr()?;
1484 if self.eat(&token::Semi) {
1485 // Repeating array syntax: `[ 0; 512 ]`
1486 let count = self.parse_anon_const_expr()?;
1487 self.expect(close)?;
1488 ExprKind::Repeat(first_expr, count)
1489 } else if self.eat(&token::Comma) {
1490 // Vector with two or more elements.
1491 let sep = SeqSep::trailing_allowed(token::Comma);
1492 let (remaining_exprs, _) = self.parse_seq_to_end(close, sep, |p| p.parse_expr())?;
1493 let mut exprs = vec![first_expr];
1494 exprs.extend(remaining_exprs);
1495 ExprKind::Array(exprs)
1497 // Vector with one element
1498 self.expect(close)?;
1499 ExprKind::Array(vec![first_expr])
1502 let expr = self.mk_expr(lo.to(self.prev_token.span), kind, attrs);
1503 self.maybe_recover_from_bad_qpath(expr)
1506 fn parse_path_start_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1507 let (qself, path) = if self.eat_lt() {
1508 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
1511 (None, self.parse_path(PathStyle::Expr)?)
1515 // `!`, as an operator, is prefix, so we know this isn't that.
1516 let (hi, kind) = if self.eat(&token::Not) {
1517 // MACRO INVOCATION expression
1518 if qself.is_some() {
1519 self.struct_span_err(path.span, "macros cannot use qualified paths").emit();
1523 args: self.parse_mac_args()?,
1524 prior_type_ascription: self.last_type_ascription,
1526 (self.prev_token.span, ExprKind::MacCall(mac))
1527 } else if self.check(&token::OpenDelim(Delimiter::Brace)) {
1528 if let Some(expr) = self.maybe_parse_struct_expr(qself.as_ref(), &path, &attrs) {
1529 if qself.is_some() {
1530 self.sess.gated_spans.gate(sym::more_qualified_paths, path.span);
1534 (path.span, ExprKind::Path(qself, path))
1537 (path.span, ExprKind::Path(qself, path))
1540 let expr = self.mk_expr(lo.to(hi), kind, attrs);
1541 self.maybe_recover_from_bad_qpath(expr)
1544 /// Parse `'label: $expr`. The label is already parsed.
1545 fn parse_labeled_expr(
1549 mut consume_colon: bool,
1550 ) -> PResult<'a, P<Expr>> {
1551 let lo = label.ident.span;
1552 let label = Some(label);
1553 let ate_colon = self.eat(&token::Colon);
1554 let expr = if self.eat_keyword(kw::While) {
1555 self.parse_while_expr(label, lo, attrs)
1556 } else if self.eat_keyword(kw::For) {
1557 self.parse_for_expr(label, lo, attrs)
1558 } else if self.eat_keyword(kw::Loop) {
1559 self.parse_loop_expr(label, lo, attrs)
1560 } else if self.check_noexpect(&token::OpenDelim(Delimiter::Brace))
1561 || self.token.is_whole_block()
1563 self.parse_block_expr(label, lo, BlockCheckMode::Default, attrs)
1564 } else if !ate_colon
1565 && (self.check_noexpect(&TokenKind::Comma) || self.check_noexpect(&TokenKind::Gt))
1567 // We're probably inside of a `Path<'a>` that needs a turbofish
1568 let msg = "expected `while`, `for`, `loop` or `{` after a label";
1569 self.struct_span_err(self.token.span, msg).span_label(self.token.span, msg).emit();
1570 consume_colon = false;
1571 Ok(self.mk_expr_err(lo))
1573 let msg = "expected `while`, `for`, `loop` or `{` after a label";
1575 let mut err = self.struct_span_err(self.token.span, msg);
1576 err.span_label(self.token.span, msg);
1578 // Continue as an expression in an effort to recover on `'label: non_block_expr`.
1579 let expr = self.parse_expr().map(|expr| {
1580 let span = expr.span;
1582 let found_labeled_breaks = {
1583 struct FindLabeledBreaksVisitor(bool);
1585 impl<'ast> Visitor<'ast> for FindLabeledBreaksVisitor {
1586 fn visit_expr_post(&mut self, ex: &'ast Expr) {
1587 if let ExprKind::Break(Some(_label), _) = ex.kind {
1593 let mut vis = FindLabeledBreaksVisitor(false);
1594 vis.visit_expr(&expr);
1598 // Suggestion involves adding a (as of time of writing this, unstable) labeled block.
1600 // If there are no breaks that may use this label, suggest removing the label and
1601 // recover to the unmodified expression.
1602 if !found_labeled_breaks {
1603 let msg = "consider removing the label";
1604 err.span_suggestion_verbose(
1608 Applicability::MachineApplicable,
1614 let sugg_msg = "consider enclosing expression in a block";
1615 let suggestions = vec![
1616 (span.shrink_to_lo(), "{ ".to_owned()),
1617 (span.shrink_to_hi(), " }".to_owned()),
1620 err.multipart_suggestion_verbose(
1623 Applicability::MachineApplicable,
1626 // Replace `'label: non_block_expr` with `'label: {non_block_expr}` in order to supress future errors about `break 'label`.
1627 let stmt = self.mk_stmt(span, StmtKind::Expr(expr));
1628 let blk = self.mk_block(vec![stmt], BlockCheckMode::Default, span);
1629 self.mk_expr(span, ExprKind::Block(blk, label), ThinVec::new())
1636 if !ate_colon && consume_colon {
1637 self.error_labeled_expr_must_be_followed_by_colon(lo, expr.span);
1643 fn error_labeled_expr_must_be_followed_by_colon(&self, lo: Span, span: Span) {
1644 self.struct_span_err(span, "labeled expression must be followed by `:`")
1645 .span_label(lo, "the label")
1646 .span_suggestion_short(
1648 "add `:` after the label",
1650 Applicability::MachineApplicable,
1652 .note("labels are used before loops and blocks, allowing e.g., `break 'label` to them")
1656 /// Recover on the syntax `do catch { ... }` suggesting `try { ... }` instead.
1657 fn recover_do_catch(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1658 let lo = self.token.span;
1660 self.bump(); // `do`
1661 self.bump(); // `catch`
1663 let span_dc = lo.to(self.prev_token.span);
1664 self.struct_span_err(span_dc, "found removed `do catch` syntax")
1667 "replace with the new syntax",
1669 Applicability::MachineApplicable,
1671 .note("following RFC #2388, the new non-placeholder syntax is `try`")
1674 self.parse_try_block(lo, attrs)
1677 /// Parse an expression if the token can begin one.
1678 fn parse_expr_opt(&mut self) -> PResult<'a, Option<P<Expr>>> {
1679 Ok(if self.token.can_begin_expr() { Some(self.parse_expr()?) } else { None })
1682 /// Parse `"return" expr?`.
1683 fn parse_return_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1684 let lo = self.prev_token.span;
1685 let kind = ExprKind::Ret(self.parse_expr_opt()?);
1686 let expr = self.mk_expr(lo.to(self.prev_token.span), kind, attrs);
1687 self.maybe_recover_from_bad_qpath(expr)
1690 /// Parse `"do" "yeet" expr?`.
1691 fn parse_yeet_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1692 let lo = self.token.span;
1694 self.bump(); // `do`
1695 self.bump(); // `yeet`
1697 let kind = ExprKind::Yeet(self.parse_expr_opt()?);
1699 let span = lo.to(self.prev_token.span);
1700 self.sess.gated_spans.gate(sym::yeet_expr, span);
1701 let expr = self.mk_expr(span, kind, attrs);
1702 self.maybe_recover_from_bad_qpath(expr)
1705 /// Parse `"break" (('label (:? expr)?) | expr?)` with `"break"` token already eaten.
1706 /// If the label is followed immediately by a `:` token, the label and `:` are
1707 /// parsed as part of the expression (i.e. a labeled loop). The language team has
1708 /// decided in #87026 to require parentheses as a visual aid to avoid confusion if
1709 /// the break expression of an unlabeled break is a labeled loop (as in
1710 /// `break 'lbl: loop {}`); a labeled break with an unlabeled loop as its value
1711 /// expression only gets a warning for compatibility reasons; and a labeled break
1712 /// with a labeled loop does not even get a warning because there is no ambiguity.
1713 fn parse_break_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1714 let lo = self.prev_token.span;
1715 let mut label = self.eat_label();
1716 let kind = if label.is_some() && self.token == token::Colon {
1717 // The value expression can be a labeled loop, see issue #86948, e.g.:
1718 // `loop { break 'label: loop { break 'label 42; }; }`
1719 let lexpr = self.parse_labeled_expr(label.take().unwrap(), AttrVec::new(), true)?;
1720 self.struct_span_err(
1722 "parentheses are required around this expression to avoid confusion with a labeled break expression",
1724 .multipart_suggestion(
1725 "wrap the expression in parentheses",
1727 (lexpr.span.shrink_to_lo(), "(".to_string()),
1728 (lexpr.span.shrink_to_hi(), ")".to_string()),
1730 Applicability::MachineApplicable,
1734 } else if self.token != token::OpenDelim(Delimiter::Brace)
1735 || !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
1737 let expr = self.parse_expr_opt()?;
1738 if let Some(ref expr) = expr {
1742 ExprKind::While(_, _, None)
1743 | ExprKind::ForLoop(_, _, _, None)
1744 | ExprKind::Loop(_, None)
1745 | ExprKind::Block(_, None)
1748 self.sess.buffer_lint_with_diagnostic(
1749 BREAK_WITH_LABEL_AND_LOOP,
1752 "this labeled break expression is easy to confuse with an unlabeled break with a labeled value expression",
1753 BuiltinLintDiagnostics::BreakWithLabelAndLoop(expr.span),
1761 let expr = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Break(label, kind), attrs);
1762 self.maybe_recover_from_bad_qpath(expr)
1765 /// Parse `"yield" expr?`.
1766 fn parse_yield_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
1767 let lo = self.prev_token.span;
1768 let kind = ExprKind::Yield(self.parse_expr_opt()?);
1769 let span = lo.to(self.prev_token.span);
1770 self.sess.gated_spans.gate(sym::generators, span);
1771 let expr = self.mk_expr(span, kind, attrs);
1772 self.maybe_recover_from_bad_qpath(expr)
1775 /// Returns a string literal if the next token is a string literal.
1776 /// In case of error returns `Some(lit)` if the next token is a literal with a wrong kind,
1777 /// and returns `None` if the next token is not literal at all.
1778 pub fn parse_str_lit(&mut self) -> Result<ast::StrLit, Option<Lit>> {
1779 match self.parse_opt_lit() {
1780 Some(lit) => match lit.kind {
1781 ast::LitKind::Str(symbol_unescaped, style) => Ok(ast::StrLit {
1783 symbol: lit.token.symbol,
1784 suffix: lit.token.suffix,
1788 _ => Err(Some(lit)),
1794 pub(super) fn parse_lit(&mut self) -> PResult<'a, Lit> {
1795 self.parse_opt_lit().ok_or_else(|| {
1796 if let token::Interpolated(inner) = &self.token.kind {
1797 let expr = match inner.as_ref() {
1798 token::NtExpr(expr) => Some(expr),
1799 token::NtLiteral(expr) => Some(expr),
1802 if let Some(expr) = expr {
1803 if matches!(expr.kind, ExprKind::Err) {
1806 .struct_span_err(self.token.span, "invalid interpolated expression");
1807 err.downgrade_to_delayed_bug();
1812 let msg = format!("unexpected token: {}", super::token_descr(&self.token));
1813 self.struct_span_err(self.token.span, &msg)
1817 /// Matches `lit = true | false | token_lit`.
1818 /// Returns `None` if the next token is not a literal.
1819 pub(super) fn parse_opt_lit(&mut self) -> Option<Lit> {
1820 let mut recovered = None;
1821 if self.token == token::Dot {
1822 // Attempt to recover `.4` as `0.4`. We don't currently have any syntax where
1823 // dot would follow an optional literal, so we do this unconditionally.
1824 recovered = self.look_ahead(1, |next_token| {
1825 if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) =
1828 if self.token.span.hi() == next_token.span.lo() {
1829 let s = String::from("0.") + symbol.as_str();
1830 let kind = TokenKind::lit(token::Float, Symbol::intern(&s), suffix);
1831 return Some(Token::new(kind, self.token.span.to(next_token.span)));
1836 if let Some(token) = &recovered {
1838 self.error_float_lits_must_have_int_part(&token);
1842 let token = recovered.as_ref().unwrap_or(&self.token);
1843 match Lit::from_token(token) {
1848 Err(LitError::NotLiteral) => None,
1850 let span = token.span;
1851 let token::Literal(lit) = token.kind else {
1855 self.report_lit_error(err, lit, span);
1856 // Pack possible quotes and prefixes from the original literal into
1857 // the error literal's symbol so they can be pretty-printed faithfully.
1858 let suffixless_lit = token::Lit::new(lit.kind, lit.symbol, None);
1859 let symbol = Symbol::intern(&suffixless_lit.to_string());
1860 let lit = token::Lit::new(token::Err, symbol, lit.suffix);
1861 Some(Lit::from_lit_token(lit, span).unwrap_or_else(|_| unreachable!()))
1866 fn error_float_lits_must_have_int_part(&self, token: &Token) {
1867 self.struct_span_err(token.span, "float literals must have an integer part")
1870 "must have an integer part",
1871 pprust::token_to_string(token),
1872 Applicability::MachineApplicable,
1877 fn report_lit_error(&self, err: LitError, lit: token::Lit, span: Span) {
1878 // Checks if `s` looks like i32 or u1234 etc.
1879 fn looks_like_width_suffix(first_chars: &[char], s: &str) -> bool {
1880 s.len() > 1 && s.starts_with(first_chars) && s[1..].chars().all(|c| c.is_ascii_digit())
1883 // Try to lowercase the prefix if it's a valid base prefix.
1884 fn fix_base_capitalisation(s: &str) -> Option<String> {
1885 if let Some(stripped) = s.strip_prefix('B') {
1886 Some(format!("0b{stripped}"))
1887 } else if let Some(stripped) = s.strip_prefix('O') {
1888 Some(format!("0o{stripped}"))
1889 } else if let Some(stripped) = s.strip_prefix('X') {
1890 Some(format!("0x{stripped}"))
1896 let token::Lit { kind, suffix, .. } = lit;
1898 // `NotLiteral` is not an error by itself, so we don't report
1899 // it and give the parser opportunity to try something else.
1900 LitError::NotLiteral => {}
1901 // `LexerError` *is* an error, but it was already reported
1902 // by lexer, so here we don't report it the second time.
1903 LitError::LexerError => {}
1904 LitError::InvalidSuffix => {
1905 self.expect_no_suffix(
1907 &format!("{} {} literal", kind.article(), kind.descr()),
1911 LitError::InvalidIntSuffix => {
1912 let suf = suffix.expect("suffix error with no suffix");
1913 let suf = suf.as_str();
1914 if looks_like_width_suffix(&['i', 'u'], &suf) {
1915 // If it looks like a width, try to be helpful.
1916 let msg = format!("invalid width `{}` for integer literal", &suf[1..]);
1917 self.struct_span_err(span, &msg)
1918 .help("valid widths are 8, 16, 32, 64 and 128")
1920 } else if let Some(fixed) = fix_base_capitalisation(suf) {
1921 let msg = "invalid base prefix for number literal";
1923 self.struct_span_err(span, msg)
1924 .note("base prefixes (`0xff`, `0b1010`, `0o755`) are lowercase")
1927 "try making the prefix lowercase",
1929 Applicability::MaybeIncorrect,
1933 let msg = format!("invalid suffix `{suf}` for number literal");
1934 self.struct_span_err(span, &msg)
1935 .span_label(span, format!("invalid suffix `{suf}`"))
1936 .help("the suffix must be one of the numeric types (`u32`, `isize`, `f32`, etc.)")
1940 LitError::InvalidFloatSuffix => {
1941 let suf = suffix.expect("suffix error with no suffix");
1942 let suf = suf.as_str();
1943 if looks_like_width_suffix(&['f'], suf) {
1944 // If it looks like a width, try to be helpful.
1945 let msg = format!("invalid width `{}` for float literal", &suf[1..]);
1946 self.struct_span_err(span, &msg).help("valid widths are 32 and 64").emit();
1948 let msg = format!("invalid suffix `{suf}` for float literal");
1949 self.struct_span_err(span, &msg)
1950 .span_label(span, format!("invalid suffix `{suf}`"))
1951 .help("valid suffixes are `f32` and `f64`")
1955 LitError::NonDecimalFloat(base) => {
1956 let descr = match base {
1957 16 => "hexadecimal",
1960 _ => unreachable!(),
1962 self.struct_span_err(span, &format!("{descr} float literal is not supported"))
1963 .span_label(span, "not supported")
1966 LitError::IntTooLarge => {
1967 self.struct_span_err(span, "integer literal is too large").emit();
1972 pub(super) fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<Symbol>) {
1973 if let Some(suf) = suffix {
1974 let mut err = if kind == "a tuple index"
1975 && [sym::i32, sym::u32, sym::isize, sym::usize].contains(&suf)
1977 // #59553: warn instead of reject out of hand to allow the fix to percolate
1978 // through the ecosystem when people fix their macros
1982 .struct_span_warn(sp, &format!("suffixes on {kind} are invalid"));
1984 "`{}` is *temporarily* accepted on tuple index fields as it was \
1985 incorrectly accepted on stable for a few releases",
1989 "on proc macros, you'll want to use `syn::Index::from` or \
1990 `proc_macro::Literal::*_unsuffixed` for code that will desugar \
1991 to tuple field access",
1994 "see issue #60210 <https://github.com/rust-lang/rust/issues/60210> \
1995 for more information",
1999 self.struct_span_err(sp, &format!("suffixes on {kind} are invalid"))
2002 err.span_label(sp, format!("invalid suffix `{suf}`"));
2007 /// Matches `'-' lit | lit` (cf. `ast_validation::AstValidator::check_expr_within_pat`).
2008 /// Keep this in sync with `Token::can_begin_literal_maybe_minus`.
2009 pub fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
2010 maybe_whole_expr!(self);
2012 let lo = self.token.span;
2013 let minus_present = self.eat(&token::BinOp(token::Minus));
2014 let lit = self.parse_lit()?;
2015 let expr = self.mk_expr(lit.span, ExprKind::Lit(lit), AttrVec::new());
2019 lo.to(self.prev_token.span),
2020 self.mk_unary(UnOp::Neg, expr),
2028 fn is_array_like_block(&mut self) -> bool {
2029 self.look_ahead(1, |t| matches!(t.kind, TokenKind::Ident(..) | TokenKind::Literal(_)))
2030 && self.look_ahead(2, |t| t == &token::Comma)
2031 && self.look_ahead(3, |t| t.can_begin_expr())
2034 /// Emits a suggestion if it looks like the user meant an array but
2035 /// accidentally used braces, causing the code to be interpreted as a block
2037 fn maybe_suggest_brackets_instead_of_braces(
2041 ) -> Option<P<Expr>> {
2042 let mut snapshot = self.create_snapshot_for_diagnostic();
2043 match snapshot.parse_array_or_repeat_expr(attrs, Delimiter::Brace) {
2045 let hi = snapshot.prev_token.span;
2046 self.struct_span_err(arr.span, "this is a block expression, not an array")
2047 .multipart_suggestion(
2048 "to make an array, use square brackets instead of curly braces",
2049 vec![(lo, "[".to_owned()), (hi, "]".to_owned())],
2050 Applicability::MaybeIncorrect,
2054 self.restore_snapshot(snapshot);
2055 Some(self.mk_expr_err(arr.span))
2064 /// Parses a block or unsafe block.
2065 pub(super) fn parse_block_expr(
2067 opt_label: Option<Label>,
2069 blk_mode: BlockCheckMode,
2071 ) -> PResult<'a, P<Expr>> {
2072 if self.is_array_like_block() {
2073 if let Some(arr) = self.maybe_suggest_brackets_instead_of_braces(lo, attrs.clone()) {
2078 if let Some(label) = opt_label {
2079 self.sess.gated_spans.gate(sym::label_break_value, label.ident.span);
2082 if self.token.is_whole_block() {
2083 self.struct_span_err(self.token.span, "cannot use a `block` macro fragment here")
2084 .span_label(lo.to(self.token.span), "the `block` fragment is within this context")
2088 let (inner_attrs, blk) = self.parse_block_common(lo, blk_mode)?;
2089 attrs.extend(inner_attrs);
2090 Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs))
2093 /// Parse a block which takes no attributes and has no label
2094 fn parse_simple_block(&mut self) -> PResult<'a, P<Expr>> {
2095 let blk = self.parse_block()?;
2096 Ok(self.mk_expr(blk.span, ExprKind::Block(blk, None), AttrVec::new()))
2099 /// Recover on an explicitly quantified closure expression, e.g., `for<'a> |x: &'a u8| *x + 1`.
2100 fn recover_quantified_closure_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
2101 let lo = self.token.span;
2102 let _ = self.parse_late_bound_lifetime_defs()?;
2103 let span_for = lo.to(self.prev_token.span);
2104 let closure = self.parse_closure_expr(attrs)?;
2106 self.struct_span_err(span_for, "cannot introduce explicit parameters for a closure")
2107 .span_label(closure.span, "the parameters are attached to this closure")
2110 "remove the parameters",
2112 Applicability::MachineApplicable,
2116 Ok(self.mk_expr_err(lo.to(closure.span)))
2119 /// Parses a closure expression (e.g., `move |args| expr`).
2120 fn parse_closure_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
2121 let lo = self.token.span;
2124 if self.eat_keyword(kw::Static) { Movability::Static } else { Movability::Movable };
2126 let asyncness = if self.token.uninterpolated_span().rust_2018() {
2127 self.parse_asyncness()
2132 let capture_clause = self.parse_capture_clause()?;
2133 let decl = self.parse_fn_block_decl()?;
2134 let decl_hi = self.prev_token.span;
2135 let mut body = match decl.output {
2136 FnRetTy::Default(_) => {
2137 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
2138 self.parse_expr_res(restrictions, None)?
2141 // If an explicit return type is given, require a block to appear (RFC 968).
2142 let body_lo = self.token.span;
2143 self.parse_block_expr(None, body_lo, BlockCheckMode::Default, AttrVec::new())?
2147 if let Async::Yes { span, .. } = asyncness {
2148 // Feature-gate `async ||` closures.
2149 self.sess.gated_spans.gate(sym::async_closure, span);
2152 if self.token.kind == TokenKind::Semi
2153 && matches!(self.token_cursor.frame.delim_sp, Some((Delimiter::Parenthesis, _)))
2155 // It is likely that the closure body is a block but where the
2156 // braces have been removed. We will recover and eat the next
2157 // statements later in the parsing process.
2158 body = self.mk_expr_err(body.span);
2161 let body_span = body.span;
2163 let closure = self.mk_expr(
2165 ExprKind::Closure(capture_clause, asyncness, movability, decl, body, lo.to(decl_hi)),
2169 // Disable recovery for closure body
2171 ClosureSpans { whole_closure: closure.span, closing_pipe: decl_hi, body: body_span };
2172 self.current_closure = Some(spans);
2177 /// Parses an optional `move` prefix to a closure-like construct.
2178 fn parse_capture_clause(&mut self) -> PResult<'a, CaptureBy> {
2179 if self.eat_keyword(kw::Move) {
2180 // Check for `move async` and recover
2181 if self.check_keyword(kw::Async) {
2182 let move_async_span = self.token.span.with_lo(self.prev_token.span.data().lo);
2183 Err(self.incorrect_move_async_order_found(move_async_span))
2185 Ok(CaptureBy::Value)
2192 /// Parses the `|arg, arg|` header of a closure.
2193 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
2194 let inputs = if self.eat(&token::OrOr) {
2197 self.expect(&token::BinOp(token::Or))?;
2199 .parse_seq_to_before_tokens(
2200 &[&token::BinOp(token::Or), &token::OrOr],
2201 SeqSep::trailing_allowed(token::Comma),
2202 TokenExpectType::NoExpect,
2203 |p| p.parse_fn_block_param(),
2210 self.parse_ret_ty(AllowPlus::Yes, RecoverQPath::Yes, RecoverReturnSign::Yes)?;
2212 Ok(P(FnDecl { inputs, output }))
2215 /// Parses a parameter in a closure header (e.g., `|arg, arg|`).
2216 fn parse_fn_block_param(&mut self) -> PResult<'a, Param> {
2217 let lo = self.token.span;
2218 let attrs = self.parse_outer_attributes()?;
2219 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
2220 let pat = this.parse_pat_no_top_alt(PARAM_EXPECTED)?;
2221 let ty = if this.eat(&token::Colon) {
2224 this.mk_ty(this.prev_token.span, TyKind::Infer)
2229 attrs: attrs.into(),
2232 span: lo.to(this.token.span),
2234 is_placeholder: false,
2236 TrailingToken::MaybeComma,
2241 /// Parses an `if` expression (`if` token already eaten).
2242 fn parse_if_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
2243 let lo = self.prev_token.span;
2244 let cond = self.parse_cond_expr()?;
2246 self.parse_if_after_cond(attrs, lo, cond)
2249 fn parse_if_after_cond(
2254 ) -> PResult<'a, P<Expr>> {
2255 let cond_span = cond.span;
2256 // Tries to interpret `cond` as either a missing expression if it's a block,
2257 // or as an unfinished expression if it's a binop and the RHS is a block.
2258 // We could probably add more recoveries here too...
2259 let mut recover_block_from_condition = |this: &mut Self| {
2260 let block = match &mut cond.kind {
2261 ExprKind::Binary(Spanned { span: binop_span, .. }, _, right)
2262 if let ExprKind::Block(_, None) = right.kind => {
2263 this.error_missing_if_then_block(lo, cond_span.shrink_to_lo().to(*binop_span), true).emit();
2264 std::mem::replace(right, this.mk_expr_err(binop_span.shrink_to_hi()))
2266 ExprKind::Block(_, None) => {
2267 this.error_missing_if_cond(lo, cond_span).emit();
2268 std::mem::replace(&mut cond, this.mk_expr_err(cond_span.shrink_to_hi()))
2274 if let ExprKind::Block(block, _) = &block.kind {
2281 let thn = if self.token.is_keyword(kw::Else) {
2282 if let Some(block) = recover_block_from_condition(self) {
2285 self.error_missing_if_then_block(lo, cond_span, false).emit();
2286 self.mk_block_err(cond_span.shrink_to_hi())
2289 let attrs = self.parse_outer_attributes()?.take_for_recovery(); // For recovery.
2290 let block = if self.check(&token::OpenDelim(Delimiter::Brace)) {
2293 if let Some(block) = recover_block_from_condition(self) {
2296 // Parse block, which will always fail, but we can add a nice note to the error
2297 self.parse_block().map_err(|mut err| {
2300 "the `if` expression is missing a block after this condition",
2306 self.error_on_if_block_attrs(lo, false, block.span, &attrs);
2309 let els = if self.eat_keyword(kw::Else) { Some(self.parse_else_expr()?) } else { None };
2310 Ok(self.mk_expr(lo.to(self.prev_token.span), ExprKind::If(cond, thn, els), attrs))
2313 fn error_missing_if_then_block(
2317 is_unfinished: bool,
2318 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
2319 let mut err = self.struct_span_err(
2321 "this `if` expression is missing a block after the condition",
2324 err.span_help(cond_span, "this binary operation is possibly unfinished");
2326 err.span_help(cond_span.shrink_to_hi(), "add a block here");
2331 fn error_missing_if_cond(
2335 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
2336 let next_span = self.sess.source_map().next_point(lo);
2337 let mut err = self.struct_span_err(next_span, "missing condition for `if` expression");
2338 err.span_label(next_span, "expected condition here");
2340 self.sess.source_map().start_point(span),
2341 "if this block is the condition of the `if` expression, then it must be followed by another block"
2346 /// Parses the condition of a `if` or `while` expression.
2347 fn parse_cond_expr(&mut self) -> PResult<'a, P<Expr>> {
2348 let cond = self.with_let_management(true, |local_self| {
2349 local_self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)
2352 if let ExprKind::Let(..) = cond.kind {
2353 // Remove the last feature gating of a `let` expression since it's stable.
2354 self.sess.gated_spans.ungate_last(sym::let_chains, cond.span);
2360 // Checks if `let` is in an invalid position like `let x = let y = 1;` or
2361 // if the current `let` is in a let_chains context but nested in another
2362 // expression like `if let Some(_) = _opt && [1, 2, 3][let _ = ()] = 1`.
2364 // This method expects that the current token is `let`.
2365 fn manage_let_chains_context(&mut self) {
2366 debug_assert!(matches!(self.token.kind, TokenKind::Ident(kw::Let, _)));
2367 let is_in_a_let_chains_context_but_nested_in_other_expr = self.let_expr_allowed
2369 self.prev_token.kind,
2371 | TokenKind::CloseDelim(Delimiter::Brace)
2372 | TokenKind::Ident(kw::If, _)
2373 | TokenKind::Ident(kw::While, _)
2375 if !self.let_expr_allowed || is_in_a_let_chains_context_but_nested_in_other_expr {
2376 self.struct_span_err(self.token.span, "expected expression, found `let` statement")
2381 /// Parses a `let $pat = $expr` pseudo-expression.
2382 /// The `let` token has already been eaten.
2383 fn parse_let_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> {
2384 let lo = self.prev_token.span;
2385 let pat = self.parse_pat_allow_top_alt(
2389 CommaRecoveryMode::LikelyTuple,
2391 self.expect(&token::Eq)?;
2392 let expr = self.with_res(self.restrictions | Restrictions::NO_STRUCT_LITERAL, |this| {
2393 this.parse_assoc_expr_with(1 + prec_let_scrutinee_needs_par(), None.into())
2395 let span = lo.to(expr.span);
2396 self.sess.gated_spans.gate(sym::let_chains, span);
2397 Ok(self.mk_expr(span, ExprKind::Let(pat, expr, span), attrs))
2400 /// Parses an `else { ... }` expression (`else` token already eaten).
2401 fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
2402 let else_span = self.prev_token.span; // `else`
2403 let attrs = self.parse_outer_attributes()?.take_for_recovery(); // For recovery.
2404 let expr = if self.eat_keyword(kw::If) {
2405 self.parse_if_expr(AttrVec::new())?
2406 } else if self.check(&TokenKind::OpenDelim(Delimiter::Brace)) {
2407 self.parse_simple_block()?
2409 let snapshot = self.create_snapshot_for_diagnostic();
2410 let first_tok = super::token_descr(&self.token);
2411 let first_tok_span = self.token.span;
2412 match self.parse_expr() {
2414 // If it's not a free-standing expression, and is followed by a block,
2415 // then it's very likely the condition to an `else if`.
2416 if self.check(&TokenKind::OpenDelim(Delimiter::Brace))
2417 && classify::expr_requires_semi_to_be_stmt(&cond) =>
2419 self.struct_span_err(first_tok_span, format!("expected `{{`, found {first_tok}"))
2420 .span_label(else_span, "expected an `if` or a block after this `else`")
2422 cond.span.shrink_to_lo(),
2423 "add an `if` if this is the condition of a chained `else if` statement",
2425 Applicability::MaybeIncorrect,
2428 self.parse_if_after_cond(AttrVec::new(), cond.span.shrink_to_lo(), cond)?
2432 self.restore_snapshot(snapshot);
2433 self.parse_simple_block()?
2436 self.restore_snapshot(snapshot);
2437 self.parse_simple_block()?
2441 self.error_on_if_block_attrs(else_span, true, expr.span, &attrs);
2445 fn error_on_if_block_attrs(
2450 attrs: &[ast::Attribute],
2452 let (span, last) = match attrs {
2454 [x0 @ xn] | [x0, .., xn] => (x0.span.to(xn.span), xn.span),
2456 let ctx = if is_ctx_else { "else" } else { "if" };
2457 self.struct_span_err(last, "outer attributes are not allowed on `if` and `else` branches")
2458 .span_label(branch_span, "the attributes are attached to this branch")
2459 .span_label(ctx_span, format!("the branch belongs to this `{ctx}`"))
2460 .span_suggestion(span, "remove the attributes", "", Applicability::MachineApplicable)
2464 /// Parses `for <src_pat> in <src_expr> <src_loop_block>` (`for` token already eaten).
2467 opt_label: Option<Label>,
2470 ) -> PResult<'a, P<Expr>> {
2471 // Record whether we are about to parse `for (`.
2472 // This is used below for recovery in case of `for ( $stuff ) $block`
2473 // in which case we will suggest `for $stuff $block`.
2474 let begin_paren = match self.token.kind {
2475 token::OpenDelim(Delimiter::Parenthesis) => Some(self.token.span),
2479 let pat = self.parse_pat_allow_top_alt(
2483 CommaRecoveryMode::LikelyTuple,
2485 if !self.eat_keyword(kw::In) {
2486 self.error_missing_in_for_loop();
2488 self.check_for_for_in_in_typo(self.prev_token.span);
2489 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
2491 let pat = self.recover_parens_around_for_head(pat, begin_paren);
2493 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
2494 attrs.extend(iattrs);
2496 let kind = ExprKind::ForLoop(pat, expr, loop_block, opt_label);
2497 Ok(self.mk_expr(lo.to(self.prev_token.span), kind, attrs))
2500 fn error_missing_in_for_loop(&mut self) {
2501 let (span, msg, sugg) = if self.token.is_ident_named(sym::of) {
2502 // Possibly using JS syntax (#75311).
2503 let span = self.token.span;
2505 (span, "try using `in` here instead", "in")
2507 (self.prev_token.span.between(self.token.span), "try adding `in` here", " in ")
2509 self.struct_span_err(span, "missing `in` in `for` loop")
2510 .span_suggestion_short(
2514 // Has been misleading, at least in the past (closed Issue #48492).
2515 Applicability::MaybeIncorrect,
2520 /// Parses a `while` or `while let` expression (`while` token already eaten).
2521 fn parse_while_expr(
2523 opt_label: Option<Label>,
2526 ) -> PResult<'a, P<Expr>> {
2527 let cond = self.parse_cond_expr().map_err(|mut err| {
2528 err.span_label(lo, "while parsing the condition of this `while` expression");
2531 let (iattrs, body) = self.parse_inner_attrs_and_block().map_err(|mut err| {
2532 err.span_label(lo, "while parsing the body of this `while` expression");
2533 err.span_label(cond.span, "this `while` condition successfully parsed");
2536 attrs.extend(iattrs);
2537 Ok(self.mk_expr(lo.to(self.prev_token.span), ExprKind::While(cond, body, opt_label), attrs))
2540 /// Parses `loop { ... }` (`loop` token already eaten).
2543 opt_label: Option<Label>,
2546 ) -> PResult<'a, P<Expr>> {
2547 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
2548 attrs.extend(iattrs);
2549 Ok(self.mk_expr(lo.to(self.prev_token.span), ExprKind::Loop(body, opt_label), attrs))
2552 pub(crate) fn eat_label(&mut self) -> Option<Label> {
2553 self.token.lifetime().map(|ident| {
2559 /// Parses a `match ... { ... }` expression (`match` token already eaten).
2560 fn parse_match_expr(&mut self, mut attrs: AttrVec) -> PResult<'a, P<Expr>> {
2561 let match_span = self.prev_token.span;
2562 let lo = self.prev_token.span;
2563 let scrutinee = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
2564 if let Err(mut e) = self.expect(&token::OpenDelim(Delimiter::Brace)) {
2565 if self.token == token::Semi {
2566 e.span_suggestion_short(
2568 "try removing this `match`",
2570 Applicability::MaybeIncorrect, // speculative
2573 if self.maybe_recover_unexpected_block_label() {
2580 attrs.extend(self.parse_inner_attributes()?);
2582 let mut arms: Vec<Arm> = Vec::new();
2583 while self.token != token::CloseDelim(Delimiter::Brace) {
2584 match self.parse_arm() {
2585 Ok(arm) => arms.push(arm),
2587 // Recover by skipping to the end of the block.
2589 self.recover_stmt();
2590 let span = lo.to(self.token.span);
2591 if self.token == token::CloseDelim(Delimiter::Brace) {
2594 return Ok(self.mk_expr(span, ExprKind::Match(scrutinee, arms), attrs));
2598 let hi = self.token.span;
2600 Ok(self.mk_expr(lo.to(hi), ExprKind::Match(scrutinee, arms), attrs))
2603 /// Attempt to recover from match arm body with statements and no surrounding braces.
2604 fn parse_arm_body_missing_braces(
2606 first_expr: &P<Expr>,
2608 ) -> Option<P<Expr>> {
2609 if self.token.kind != token::Semi {
2612 let start_snapshot = self.create_snapshot_for_diagnostic();
2613 let semi_sp = self.token.span;
2616 vec![self.mk_stmt(first_expr.span, ast::StmtKind::Expr(first_expr.clone()))];
2617 let err = |this: &mut Parser<'_>, stmts: Vec<ast::Stmt>| {
2618 let span = stmts[0].span.to(stmts[stmts.len() - 1].span);
2619 let mut err = this.struct_span_err(span, "`match` arm body without braces");
2620 let (these, s, are) =
2621 if stmts.len() > 1 { ("these", "s", "are") } else { ("this", "", "is") };
2625 "{these} statement{s} {are} not surrounded by a body",
2631 err.span_label(arrow_span, "while parsing the `match` arm starting here");
2632 if stmts.len() > 1 {
2633 err.multipart_suggestion(
2634 &format!("surround the statement{s} with a body"),
2636 (span.shrink_to_lo(), "{ ".to_string()),
2637 (span.shrink_to_hi(), " }".to_string()),
2639 Applicability::MachineApplicable,
2642 err.span_suggestion(
2644 "use a comma to end a `match` arm expression",
2646 Applicability::MachineApplicable,
2650 this.mk_expr_err(span)
2652 // We might have either a `,` -> `;` typo, or a block without braces. We need
2653 // a more subtle parsing strategy.
2655 if self.token.kind == token::CloseDelim(Delimiter::Brace) {
2656 // We have reached the closing brace of the `match` expression.
2657 return Some(err(self, stmts));
2659 if self.token.kind == token::Comma {
2660 self.restore_snapshot(start_snapshot);
2663 let pre_pat_snapshot = self.create_snapshot_for_diagnostic();
2664 match self.parse_pat_no_top_alt(None) {
2666 if self.token.kind == token::FatArrow {
2668 self.restore_snapshot(pre_pat_snapshot);
2669 return Some(err(self, stmts));
2677 self.restore_snapshot(pre_pat_snapshot);
2678 match self.parse_stmt_without_recovery(true, ForceCollect::No) {
2679 // Consume statements for as long as possible.
2684 self.restore_snapshot(start_snapshot);
2687 // We couldn't parse either yet another statement missing it's
2688 // enclosing block nor the next arm's pattern or closing brace.
2691 self.restore_snapshot(start_snapshot);
2699 pub(super) fn parse_arm(&mut self) -> PResult<'a, Arm> {
2700 // Used to check the `let_chains` and `if_let_guard` features mostly by scaning
2702 fn check_let_expr(expr: &Expr) -> (bool, bool) {
2704 ExprKind::Binary(_, ref lhs, ref rhs) => {
2705 let lhs_rslt = check_let_expr(lhs);
2706 let rhs_rslt = check_let_expr(rhs);
2707 (lhs_rslt.0 || rhs_rslt.0, false)
2709 ExprKind::Let(..) => (true, true),
2713 let attrs = self.parse_outer_attributes()?;
2714 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
2715 let lo = this.token.span;
2716 let pat = this.parse_pat_allow_top_alt(
2720 CommaRecoveryMode::EitherTupleOrPipe,
2722 let guard = if this.eat_keyword(kw::If) {
2723 let if_span = this.prev_token.span;
2724 let cond = this.with_let_management(true, |local_this| local_this.parse_expr())?;
2725 let (has_let_expr, does_not_have_bin_op) = check_let_expr(&cond);
2727 if does_not_have_bin_op {
2728 // Remove the last feature gating of a `let` expression since it's stable.
2729 this.sess.gated_spans.ungate_last(sym::let_chains, cond.span);
2731 let span = if_span.to(cond.span);
2732 this.sess.gated_spans.gate(sym::if_let_guard, span);
2738 let arrow_span = this.token.span;
2739 if let Err(mut err) = this.expect(&token::FatArrow) {
2740 // We might have a `=>` -> `=` or `->` typo (issue #89396).
2741 if TokenKind::FatArrow
2743 .map_or(false, |similar_tokens| similar_tokens.contains(&this.token.kind))
2745 err.span_suggestion(
2747 "try using a fat arrow here",
2749 Applicability::MaybeIncorrect,
2757 let arm_start_span = this.token.span;
2759 let expr = this.parse_expr_res(Restrictions::STMT_EXPR, None).map_err(|mut err| {
2760 err.span_label(arrow_span, "while parsing the `match` arm starting here");
2764 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
2765 && this.token != token::CloseDelim(Delimiter::Brace);
2767 let hi = this.prev_token.span;
2770 let sm = this.sess.source_map();
2771 if let Some(body) = this.parse_arm_body_missing_braces(&expr, arrow_span) {
2772 let span = body.span;
2775 attrs: attrs.into(),
2781 is_placeholder: false,
2783 TrailingToken::None,
2786 this.expect_one_of(&[token::Comma], &[token::CloseDelim(Delimiter::Brace)])
2787 .or_else(|mut err| {
2788 if this.token == token::FatArrow {
2789 if let Ok(expr_lines) = sm.span_to_lines(expr.span)
2790 && let Ok(arm_start_lines) = sm.span_to_lines(arm_start_span)
2791 && arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col
2792 && expr_lines.lines.len() == 2
2794 // We check whether there's any trailing code in the parse span,
2795 // if there isn't, we very likely have the following:
2798 // | -- - missing comma
2802 // | - ^^ self.token.span
2804 // | parsed until here as `"y" & X`
2805 err.span_suggestion_short(
2806 arm_start_span.shrink_to_hi(),
2807 "missing a comma here to end this `match` arm",
2809 Applicability::MachineApplicable,
2814 // FIXME(compiler-errors): We could also recover `; PAT =>` here
2816 // Try to parse a following `PAT =>`, if successful
2817 // then we should recover.
2818 let mut snapshot = this.create_snapshot_for_diagnostic();
2819 let pattern_follows = snapshot
2820 .parse_pat_allow_top_alt(
2824 CommaRecoveryMode::EitherTupleOrPipe,
2826 .map_err(|err| err.cancel())
2828 if pattern_follows && snapshot.check(&TokenKind::FatArrow) {
2830 this.struct_span_err(
2832 "expected `,` following `match` arm",
2836 "missing a comma here to end this `match` arm",
2838 Applicability::MachineApplicable,
2844 err.span_label(arrow_span, "while parsing the `match` arm starting here");
2848 this.eat(&token::Comma);
2853 attrs: attrs.into(),
2859 is_placeholder: false,
2861 TrailingToken::None,
2866 /// Parses a `try {...}` expression (`try` token already eaten).
2867 fn parse_try_block(&mut self, span_lo: Span, mut attrs: AttrVec) -> PResult<'a, P<Expr>> {
2868 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
2869 attrs.extend(iattrs);
2870 if self.eat_keyword(kw::Catch) {
2871 let mut error = self.struct_span_err(
2872 self.prev_token.span,
2873 "keyword `catch` cannot follow a `try` block",
2875 error.help("try using `match` on the result of the `try` block instead");
2879 let span = span_lo.to(body.span);
2880 self.sess.gated_spans.gate(sym::try_blocks, span);
2881 Ok(self.mk_expr(span, ExprKind::TryBlock(body), attrs))
2885 fn is_do_catch_block(&self) -> bool {
2886 self.token.is_keyword(kw::Do)
2887 && self.is_keyword_ahead(1, &[kw::Catch])
2888 && self.look_ahead(2, |t| *t == token::OpenDelim(Delimiter::Brace))
2889 && !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
2892 fn is_do_yeet(&self) -> bool {
2893 self.token.is_keyword(kw::Do) && self.is_keyword_ahead(1, &[kw::Yeet])
2896 fn is_try_block(&self) -> bool {
2897 self.token.is_keyword(kw::Try)
2898 && self.look_ahead(1, |t| *t == token::OpenDelim(Delimiter::Brace))
2899 && self.token.uninterpolated_span().rust_2018()
2902 /// Parses an `async move? {...}` expression.
2903 fn parse_async_block(&mut self, mut attrs: AttrVec) -> PResult<'a, P<Expr>> {
2904 let lo = self.token.span;
2905 self.expect_keyword(kw::Async)?;
2906 let capture_clause = self.parse_capture_clause()?;
2907 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
2908 attrs.extend(iattrs);
2909 let kind = ExprKind::Async(capture_clause, DUMMY_NODE_ID, body);
2910 Ok(self.mk_expr(lo.to(self.prev_token.span), kind, attrs))
2913 fn is_async_block(&self) -> bool {
2914 self.token.is_keyword(kw::Async)
2917 self.is_keyword_ahead(1, &[kw::Move])
2918 && self.look_ahead(2, |t| *t == token::OpenDelim(Delimiter::Brace))
2921 self.look_ahead(1, |t| *t == token::OpenDelim(Delimiter::Brace))
2925 fn is_certainly_not_a_block(&self) -> bool {
2926 self.look_ahead(1, |t| t.is_ident())
2928 // `{ ident, ` cannot start a block.
2929 self.look_ahead(2, |t| t == &token::Comma)
2930 || self.look_ahead(2, |t| t == &token::Colon)
2932 // `{ ident: token, ` cannot start a block.
2933 self.look_ahead(4, |t| t == &token::Comma) ||
2934 // `{ ident: ` cannot start a block unless it's a type ascription `ident: Type`.
2935 self.look_ahead(3, |t| !t.can_begin_type())
2940 fn maybe_parse_struct_expr(
2942 qself: Option<&ast::QSelf>,
2945 ) -> Option<PResult<'a, P<Expr>>> {
2946 let struct_allowed = !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
2947 if struct_allowed || self.is_certainly_not_a_block() {
2948 if let Err(err) = self.expect(&token::OpenDelim(Delimiter::Brace)) {
2949 return Some(Err(err));
2951 let expr = self.parse_struct_expr(qself.cloned(), path.clone(), attrs.clone(), true);
2952 if let (Ok(expr), false) = (&expr, struct_allowed) {
2953 // This is a struct literal, but we don't can't accept them here.
2954 self.error_struct_lit_not_allowed_here(path.span, expr.span);
2961 fn error_struct_lit_not_allowed_here(&self, lo: Span, sp: Span) {
2962 self.struct_span_err(sp, "struct literals are not allowed here")
2963 .multipart_suggestion(
2964 "surround the struct literal with parentheses",
2965 vec![(lo.shrink_to_lo(), "(".to_string()), (sp.shrink_to_hi(), ")".to_string())],
2966 Applicability::MachineApplicable,
2971 pub(super) fn parse_struct_fields(
2975 close_delim: Delimiter,
2976 ) -> PResult<'a, (Vec<ExprField>, ast::StructRest, bool)> {
2977 let mut fields = Vec::new();
2978 let mut base = ast::StructRest::None;
2979 let mut recover_async = false;
2981 let mut async_block_err = |e: &mut Diagnostic, span: Span| {
2982 recover_async = true;
2983 e.span_label(span, "`async` blocks are only allowed in Rust 2018 or later");
2984 e.help_use_latest_edition();
2987 while self.token != token::CloseDelim(close_delim) {
2988 if self.eat(&token::DotDot) {
2989 let exp_span = self.prev_token.span;
2990 // We permit `.. }` on the left-hand side of a destructuring assignment.
2991 if self.check(&token::CloseDelim(close_delim)) {
2992 base = ast::StructRest::Rest(self.prev_token.span.shrink_to_hi());
2995 match self.parse_expr() {
2996 Ok(e) => base = ast::StructRest::Base(e),
2997 Err(mut e) if recover => {
2999 self.recover_stmt();
3001 Err(e) => return Err(e),
3003 self.recover_struct_comma_after_dotdot(exp_span);
3007 let recovery_field = self.find_struct_error_after_field_looking_code();
3008 let parsed_field = match self.parse_expr_field() {
3011 if pth == kw::Async {
3012 async_block_err(&mut e, pth.span);
3014 e.span_label(pth.span, "while parsing this struct");
3018 // If the next token is a comma, then try to parse
3019 // what comes next as additional fields, rather than
3020 // bailing out until next `}`.
3021 if self.token != token::Comma {
3022 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
3023 if self.token != token::Comma {
3031 let is_shorthand = parsed_field.as_ref().map_or(false, |f| f.is_shorthand);
3032 // A shorthand field can be turned into a full field with `:`.
3033 // We should point this out.
3034 self.check_or_expected(!is_shorthand, TokenType::Token(token::Colon));
3036 match self.expect_one_of(&[token::Comma], &[token::CloseDelim(close_delim)]) {
3038 if let Some(f) = parsed_field.or(recovery_field) {
3039 // Only include the field if there's no parse error for the field name.
3044 if pth == kw::Async {
3045 async_block_err(&mut e, pth.span);
3047 e.span_label(pth.span, "while parsing this struct");
3048 if let Some(f) = recovery_field {
3051 self.prev_token.span.shrink_to_hi(),
3052 "try adding a comma",
3054 Applicability::MachineApplicable,
3056 } else if is_shorthand
3057 && (AssocOp::from_token(&self.token).is_some()
3058 || matches!(&self.token.kind, token::OpenDelim(_))
3059 || self.token.kind == token::Dot)
3061 // Looks like they tried to write a shorthand, complex expression.
3062 let ident = parsed_field.expect("is_shorthand implies Some").ident;
3064 ident.span.shrink_to_lo(),
3065 "try naming a field",
3066 &format!("{ident}: "),
3067 Applicability::HasPlaceholders,
3075 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
3076 self.eat(&token::Comma);
3080 Ok((fields, base, recover_async))
3083 /// Precondition: already parsed the '{'.
3084 pub(super) fn parse_struct_expr(
3086 qself: Option<ast::QSelf>,
3090 ) -> PResult<'a, P<Expr>> {
3092 let (fields, base, recover_async) =
3093 self.parse_struct_fields(pth.clone(), recover, Delimiter::Brace)?;
3094 let span = lo.to(self.token.span);
3095 self.expect(&token::CloseDelim(Delimiter::Brace))?;
3096 let expr = if recover_async {
3099 ExprKind::Struct(P(ast::StructExpr { qself, path: pth, fields, rest: base }))
3101 Ok(self.mk_expr(span, expr, attrs))
3104 /// Use in case of error after field-looking code: `S { foo: () with a }`.
3105 fn find_struct_error_after_field_looking_code(&self) -> Option<ExprField> {
3106 match self.token.ident() {
3107 Some((ident, is_raw))
3108 if (is_raw || !ident.is_reserved())
3109 && self.look_ahead(1, |t| *t == token::Colon) =>
3111 Some(ast::ExprField {
3113 span: self.token.span,
3114 expr: self.mk_expr_err(self.token.span),
3115 is_shorthand: false,
3116 attrs: AttrVec::new(),
3118 is_placeholder: false,
3125 fn recover_struct_comma_after_dotdot(&mut self, span: Span) {
3126 if self.token != token::Comma {
3129 self.struct_span_err(
3130 span.to(self.prev_token.span),
3131 "cannot use a comma after the base struct",
3133 .span_suggestion_short(
3135 "remove this comma",
3137 Applicability::MachineApplicable,
3139 .note("the base struct must always be the last field")
3141 self.recover_stmt();
3144 /// Parses `ident (COLON expr)?`.
3145 fn parse_expr_field(&mut self) -> PResult<'a, ExprField> {
3146 let attrs = self.parse_outer_attributes()?;
3147 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
3148 let lo = this.token.span;
3150 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3151 let is_shorthand = !this.look_ahead(1, |t| t == &token::Colon || t == &token::Eq);
3152 let (ident, expr) = if is_shorthand {
3153 // Mimic `x: x` for the `x` field shorthand.
3154 let ident = this.parse_ident_common(false)?;
3155 let path = ast::Path::from_ident(ident);
3156 (ident, this.mk_expr(ident.span, ExprKind::Path(None, path), AttrVec::new()))
3158 let ident = this.parse_field_name()?;
3159 this.error_on_eq_field_init(ident);
3161 (ident, this.parse_expr()?)
3167 span: lo.to(expr.span),
3170 attrs: attrs.into(),
3172 is_placeholder: false,
3174 TrailingToken::MaybeComma,
3179 /// Check for `=`. This means the source incorrectly attempts to
3180 /// initialize a field with an eq rather than a colon.
3181 fn error_on_eq_field_init(&self, field_name: Ident) {
3182 if self.token != token::Eq {
3186 self.struct_span_err(self.token.span, "expected `:`, found `=`")
3188 field_name.span.shrink_to_hi().to(self.token.span),
3189 "replace equals symbol with a colon",
3191 Applicability::MachineApplicable,
3196 fn err_dotdotdot_syntax(&self, span: Span) {
3197 self.struct_span_err(span, "unexpected token: `...`")
3200 "use `..` for an exclusive range",
3202 Applicability::MaybeIncorrect,
3206 "or `..=` for an inclusive range",
3208 Applicability::MaybeIncorrect,
3213 fn err_larrow_operator(&self, span: Span) {
3214 self.struct_span_err(span, "unexpected token: `<-`")
3217 "if you meant to write a comparison against a negative value, add a \
3218 space in between `<` and `-`",
3220 Applicability::MaybeIncorrect,
3225 fn mk_assign_op(&self, binop: BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ExprKind {
3226 ExprKind::AssignOp(binop, lhs, rhs)
3231 start: Option<P<Expr>>,
3232 end: Option<P<Expr>>,
3233 limits: RangeLimits,
3235 if end.is_none() && limits == RangeLimits::Closed {
3236 self.inclusive_range_with_incorrect_end(self.prev_token.span);
3239 ExprKind::Range(start, end, limits)
3243 fn mk_unary(&self, unop: UnOp, expr: P<Expr>) -> ExprKind {
3244 ExprKind::Unary(unop, expr)
3247 fn mk_binary(&self, binop: BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ExprKind {
3248 ExprKind::Binary(binop, lhs, rhs)
3251 fn mk_index(&self, expr: P<Expr>, idx: P<Expr>) -> ExprKind {
3252 ExprKind::Index(expr, idx)
3255 fn mk_call(&self, f: P<Expr>, args: Vec<P<Expr>>) -> ExprKind {
3256 ExprKind::Call(f, args)
3259 fn mk_await_expr(&mut self, self_arg: P<Expr>, lo: Span) -> P<Expr> {
3260 let span = lo.to(self.prev_token.span);
3261 let await_expr = self.mk_expr(span, ExprKind::Await(self_arg), AttrVec::new());
3262 self.recover_from_await_method_call();
3266 pub(crate) fn mk_expr(&self, span: Span, kind: ExprKind, attrs: AttrVec) -> P<Expr> {
3267 P(Expr { kind, span, attrs, id: DUMMY_NODE_ID, tokens: None })
3270 pub(super) fn mk_expr_err(&self, span: Span) -> P<Expr> {
3271 self.mk_expr(span, ExprKind::Err, AttrVec::new())
3274 /// Create expression span ensuring the span of the parent node
3275 /// is larger than the span of lhs and rhs, including the attributes.
3276 fn mk_expr_sp(&self, lhs: &P<Expr>, lhs_span: Span, rhs_span: Span) -> Span {
3279 .find(|a| a.style == AttrStyle::Outer)
3280 .map_or(lhs_span, |a| a.span)
3284 fn collect_tokens_for_expr(
3287 f: impl FnOnce(&mut Self, Vec<ast::Attribute>) -> PResult<'a, P<Expr>>,
3288 ) -> PResult<'a, P<Expr>> {
3289 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
3290 let res = f(this, attrs)?;
3291 let trailing = if this.restrictions.contains(Restrictions::STMT_EXPR)
3292 && this.token.kind == token::Semi
3296 // FIXME - pass this through from the place where we know
3297 // we need a comma, rather than assuming that `#[attr] expr,`
3298 // always captures a trailing comma
3299 TrailingToken::MaybeComma
3305 // Calls `f` with the internal `let_expr_allowed` set to `let_expr_allowed` and then
3306 // sets the internal `let_expr_allowed` back to its original value.
3307 fn with_let_management<T>(
3309 let_expr_allowed: bool,
3310 f: impl FnOnce(&mut Self) -> T,
3312 let last_let_expr_allowed = mem::replace(&mut self.let_expr_allowed, let_expr_allowed);
3314 self.let_expr_allowed = last_let_expr_allowed;