1 use super::diagnostics::{
2 CatchAfterTry, CommaAfterBaseStruct, DoCatchSyntaxRemoved, DotDotDot, EqFieldInit,
3 ExpectedElseBlock, ExpectedExpressionFoundLet, FieldExpressionWithGeneric,
4 FloatLiteralRequiresIntegerPart, IfExpressionMissingCondition, IfExpressionMissingThenBlock,
5 IfExpressionMissingThenBlockSub, InvalidBlockMacroSegment, InvalidComparisonOperator,
6 InvalidComparisonOperatorSub, InvalidLogicalOperator, InvalidLogicalOperatorSub,
7 LeftArrowOperator, LifetimeInBorrowExpression, MacroInvocationWithQualifiedPath,
8 MalformedLoopLabel, MissingInInForLoop, MissingInInForLoopSub, MissingSemicolonBeforeArray,
9 NotAsNegationOperator, OuterAttributeNotAllowedOnIfElse, RequireColonAfterLabeledExpression,
10 SnapshotParser, TildeAsUnaryOperator, UnexpectedTokenAfterLabel,
12 use super::pat::{CommaRecoveryMode, RecoverColon, RecoverComma, PARAM_EXPECTED};
13 use super::ty::{AllowPlus, RecoverQPath, RecoverReturnSign};
15 AttrWrapper, BlockMode, ClosureSpans, ForceCollect, Parser, PathStyle, Restrictions,
16 SemiColonMode, SeqSep, TokenExpectType, TokenType, TrailingToken,
18 use crate::maybe_recover_from_interpolated_ty_qpath;
19 use crate::parser::diagnostics::{
20 IntLiteralTooLarge, InvalidFloatLiteralSuffix, InvalidFloatLiteralWidth,
21 InvalidIntLiteralWidth, InvalidNumLiteralBasePrefix, InvalidNumLiteralSuffix,
22 MissingCommaAfterMatchArm,
26 use rustc_ast::ptr::P;
27 use rustc_ast::token::{self, Delimiter, Token, TokenKind};
28 use rustc_ast::tokenstream::Spacing;
29 use rustc_ast::util::classify;
30 use rustc_ast::util::literal::LitError;
31 use rustc_ast::util::parser::{prec_let_scrutinee_needs_par, AssocOp, Fixity};
32 use rustc_ast::visit::Visitor;
33 use rustc_ast::{self as ast, AttrStyle, AttrVec, CaptureBy, ExprField, Lit, UnOp, DUMMY_NODE_ID};
34 use rustc_ast::{AnonConst, BinOp, BinOpKind, FnDecl, FnRetTy, MacCall, Param, Ty, TyKind};
35 use rustc_ast::{Arm, Async, BlockCheckMode, Expr, ExprKind, Label, Movability, RangeLimits};
36 use rustc_ast::{ClosureBinder, StmtKind};
37 use rustc_ast_pretty::pprust;
38 use rustc_errors::{Applicability, Diagnostic, PResult};
39 use rustc_session::lint::builtin::BREAK_WITH_LABEL_AND_LOOP;
40 use rustc_session::lint::BuiltinLintDiagnostics;
41 use rustc_session::SessionDiagnostic;
42 use rustc_span::source_map::{self, Span, Spanned};
43 use rustc_span::symbol::{kw, sym, Ident, Symbol};
44 use rustc_span::{BytePos, Pos};
46 /// Possibly accepts an `token::Interpolated` expression (a pre-parsed expression
47 /// dropped into the token stream, which happens while parsing the result of
48 /// macro expansion). Placement of these is not as complex as I feared it would
49 /// be. The important thing is to make sure that lookahead doesn't balk at
50 /// `token::Interpolated` tokens.
51 macro_rules! maybe_whole_expr {
53 if let token::Interpolated(nt) = &$p.token.kind {
55 token::NtExpr(e) | token::NtLiteral(e) => {
60 token::NtPath(path) => {
61 let path = (**path).clone();
63 return Ok($p.mk_expr($p.prev_token.span, ExprKind::Path(None, path)));
65 token::NtBlock(block) => {
66 let block = block.clone();
68 return Ok($p.mk_expr($p.prev_token.span, ExprKind::Block(block, None)));
77 pub(super) enum LhsExpr {
79 AttributesParsed(AttrWrapper),
80 AlreadyParsed(P<Expr>),
83 impl From<Option<AttrWrapper>> for LhsExpr {
84 /// Converts `Some(attrs)` into `LhsExpr::AttributesParsed(attrs)`
85 /// and `None` into `LhsExpr::NotYetParsed`.
87 /// This conversion does not allocate.
88 fn from(o: Option<AttrWrapper>) -> Self {
89 if let Some(attrs) = o { LhsExpr::AttributesParsed(attrs) } else { LhsExpr::NotYetParsed }
93 impl From<P<Expr>> for LhsExpr {
94 /// Converts the `expr: P<Expr>` into `LhsExpr::AlreadyParsed(expr)`.
96 /// This conversion does not allocate.
97 fn from(expr: P<Expr>) -> Self {
98 LhsExpr::AlreadyParsed(expr)
102 impl<'a> Parser<'a> {
103 /// Parses an expression.
105 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
106 self.current_closure.take();
108 self.parse_expr_res(Restrictions::empty(), None)
111 /// Parses an expression, forcing tokens to be collected
112 pub fn parse_expr_force_collect(&mut self) -> PResult<'a, P<Expr>> {
113 self.collect_tokens_no_attrs(|this| this.parse_expr())
116 pub fn parse_anon_const_expr(&mut self) -> PResult<'a, AnonConst> {
117 self.parse_expr().map(|value| AnonConst { id: DUMMY_NODE_ID, value })
120 fn parse_expr_catch_underscore(&mut self) -> PResult<'a, P<Expr>> {
121 match self.parse_expr() {
122 Ok(expr) => Ok(expr),
123 Err(mut err) => match self.token.ident() {
124 Some((Ident { name: kw::Underscore, .. }, false))
125 if self.look_ahead(1, |t| t == &token::Comma) =>
127 // Special-case handling of `foo(_, _, _)`
130 Ok(self.mk_expr(self.prev_token.span, ExprKind::Err))
137 /// Parses a sequence of expressions delimited by parentheses.
138 fn parse_paren_expr_seq(&mut self) -> PResult<'a, Vec<P<Expr>>> {
139 self.parse_paren_comma_seq(|p| p.parse_expr_catch_underscore()).map(|(r, _)| r)
142 /// Parses an expression, subject to the given restrictions.
144 pub(super) fn parse_expr_res(
147 already_parsed_attrs: Option<AttrWrapper>,
148 ) -> PResult<'a, P<Expr>> {
149 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
152 /// Parses an associative expression.
154 /// This parses an expression accounting for associativity and precedence of the operators in
159 already_parsed_attrs: Option<AttrWrapper>,
160 ) -> PResult<'a, P<Expr>> {
161 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
164 /// Parses an associative expression with operators of at least `min_prec` precedence.
165 pub(super) fn parse_assoc_expr_with(
169 ) -> PResult<'a, P<Expr>> {
170 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
173 let attrs = match lhs {
174 LhsExpr::AttributesParsed(attrs) => Some(attrs),
177 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token.kind) {
178 return self.parse_prefix_range_expr(attrs);
180 self.parse_prefix_expr(attrs)?
183 let last_type_ascription_set = self.last_type_ascription.is_some();
185 if !self.should_continue_as_assoc_expr(&lhs) {
186 self.last_type_ascription = None;
190 self.expected_tokens.push(TokenType::Operator);
191 while let Some(op) = self.check_assoc_op() {
192 // Adjust the span for interpolated LHS to point to the `$lhs` token
193 // and not to what it refers to.
194 let lhs_span = match self.prev_token.kind {
195 TokenKind::Interpolated(..) => self.prev_token.span,
199 let cur_op_span = self.token.span;
200 let restrictions = if op.node.is_assign_like() {
201 self.restrictions & Restrictions::NO_STRUCT_LITERAL
205 let prec = op.node.precedence();
209 // Check for deprecated `...` syntax
210 if self.token == token::DotDotDot && op.node == AssocOp::DotDotEq {
211 self.err_dotdotdot_syntax(self.token.span);
214 if self.token == token::LArrow {
215 self.err_larrow_operator(self.token.span);
219 if op.node.is_comparison() {
220 if let Some(expr) = self.check_no_chained_comparison(&lhs, &op)? {
225 // Look for JS' `===` and `!==` and recover
226 if (op.node == AssocOp::Equal || op.node == AssocOp::NotEqual)
227 && self.token.kind == token::Eq
228 && self.prev_token.span.hi() == self.token.span.lo()
230 let sp = op.span.to(self.token.span);
231 let sugg = match op.node {
232 AssocOp::Equal => "==",
233 AssocOp::NotEqual => "!=",
237 let invalid = format!("{}=", &sugg);
238 self.sess.emit_err(InvalidComparisonOperator {
240 invalid: invalid.clone(),
241 sub: InvalidComparisonOperatorSub::Correctable {
250 // Look for PHP's `<>` and recover
251 if op.node == AssocOp::Less
252 && self.token.kind == token::Gt
253 && self.prev_token.span.hi() == self.token.span.lo()
255 let sp = op.span.to(self.token.span);
256 self.sess.emit_err(InvalidComparisonOperator {
258 invalid: "<>".into(),
259 sub: InvalidComparisonOperatorSub::Correctable {
261 invalid: "<>".into(),
262 correct: "!=".into(),
268 // Look for C++'s `<=>` and recover
269 if op.node == AssocOp::LessEqual
270 && self.token.kind == token::Gt
271 && self.prev_token.span.hi() == self.token.span.lo()
273 let sp = op.span.to(self.token.span);
274 self.sess.emit_err(InvalidComparisonOperator {
276 invalid: "<=>".into(),
277 sub: InvalidComparisonOperatorSub::Spaceship(sp),
282 if self.prev_token == token::BinOp(token::Plus)
283 && self.token == token::BinOp(token::Plus)
284 && self.prev_token.span.between(self.token.span).is_empty()
286 let op_span = self.prev_token.span.to(self.token.span);
287 // Eat the second `+`
289 lhs = self.recover_from_postfix_increment(lhs, op_span)?;
295 if op == AssocOp::As {
296 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
298 } else if op == AssocOp::Colon {
299 lhs = self.parse_assoc_op_ascribe(lhs, lhs_span)?;
301 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
302 // If we didn't have to handle `x..`/`x..=`, it would be pretty easy to
303 // generalise it to the Fixity::None code.
304 lhs = self.parse_range_expr(prec, lhs, op, cur_op_span)?;
308 let fixity = op.fixity();
309 let prec_adjustment = match fixity {
312 // We currently have no non-associative operators that are not handled above by
313 // the special cases. The code is here only for future convenience.
316 let rhs = self.with_res(restrictions - Restrictions::STMT_EXPR, |this| {
317 this.parse_assoc_expr_with(prec + prec_adjustment, LhsExpr::NotYetParsed)
320 let span = self.mk_expr_sp(&lhs, lhs_span, rhs.span);
333 | AssocOp::ShiftRight
339 | AssocOp::GreaterEqual => {
340 let ast_op = op.to_ast_binop().unwrap();
341 let binary = self.mk_binary(source_map::respan(cur_op_span, ast_op), lhs, rhs);
342 self.mk_expr(span, binary)
344 AssocOp::Assign => self.mk_expr(span, ExprKind::Assign(lhs, rhs, cur_op_span)),
345 AssocOp::AssignOp(k) => {
347 token::Plus => BinOpKind::Add,
348 token::Minus => BinOpKind::Sub,
349 token::Star => BinOpKind::Mul,
350 token::Slash => BinOpKind::Div,
351 token::Percent => BinOpKind::Rem,
352 token::Caret => BinOpKind::BitXor,
353 token::And => BinOpKind::BitAnd,
354 token::Or => BinOpKind::BitOr,
355 token::Shl => BinOpKind::Shl,
356 token::Shr => BinOpKind::Shr,
358 let aopexpr = self.mk_assign_op(source_map::respan(cur_op_span, aop), lhs, rhs);
359 self.mk_expr(span, aopexpr)
361 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
362 self.span_bug(span, "AssocOp should have been handled by special case")
366 if let Fixity::None = fixity {
370 if last_type_ascription_set {
371 self.last_type_ascription = None;
376 fn should_continue_as_assoc_expr(&mut self, lhs: &Expr) -> bool {
377 match (self.expr_is_complete(lhs), AssocOp::from_token(&self.token)) {
378 // Semi-statement forms are odd:
379 // See https://github.com/rust-lang/rust/issues/29071
380 (true, None) => false,
381 (false, _) => true, // Continue parsing the expression.
382 // An exhaustive check is done in the following block, but these are checked first
383 // because they *are* ambiguous but also reasonable looking incorrect syntax, so we
384 // want to keep their span info to improve diagnostics in these cases in a later stage.
385 (true, Some(AssocOp::Multiply)) | // `{ 42 } *foo = bar;` or `{ 42 } * 3`
386 (true, Some(AssocOp::Subtract)) | // `{ 42 } -5`
387 (true, Some(AssocOp::Add)) // `{ 42 } + 42
388 // If the next token is a keyword, then the tokens above *are* unambiguously incorrect:
389 // `if x { a } else { b } && if y { c } else { d }`
390 if !self.look_ahead(1, |t| t.is_used_keyword()) => {
391 // These cases are ambiguous and can't be identified in the parser alone.
392 let sp = self.sess.source_map().start_point(self.token.span);
393 self.sess.ambiguous_block_expr_parse.borrow_mut().insert(sp, lhs.span);
396 (true, Some(AssocOp::LAnd)) |
397 (true, Some(AssocOp::LOr)) |
398 (true, Some(AssocOp::BitOr)) => {
399 // `{ 42 } &&x` (#61475) or `{ 42 } && if x { 1 } else { 0 }`. Separated from the
400 // above due to #74233.
401 // These cases are ambiguous and can't be identified in the parser alone.
403 // Bitwise AND is left out because guessing intent is hard. We can make
404 // suggestions based on the assumption that double-refs are rarely intentional,
405 // and closures are distinct enough that they don't get mixed up with their
407 let sp = self.sess.source_map().start_point(self.token.span);
408 self.sess.ambiguous_block_expr_parse.borrow_mut().insert(sp, lhs.span);
411 (true, Some(ref op)) if !op.can_continue_expr_unambiguously() => false,
413 self.error_found_expr_would_be_stmt(lhs);
419 /// We've found an expression that would be parsed as a statement,
420 /// but the next token implies this should be parsed as an expression.
421 /// For example: `if let Some(x) = x { x } else { 0 } / 2`.
422 fn error_found_expr_would_be_stmt(&self, lhs: &Expr) {
423 let mut err = self.struct_span_err(
425 &format!("expected expression, found `{}`", pprust::token_to_string(&self.token),),
427 err.span_label(self.token.span, "expected expression");
428 self.sess.expr_parentheses_needed(&mut err, lhs.span);
432 /// Possibly translate the current token to an associative operator.
433 /// The method does not advance the current token.
435 /// Also performs recovery for `and` / `or` which are mistaken for `&&` and `||` respectively.
436 fn check_assoc_op(&self) -> Option<Spanned<AssocOp>> {
437 let (op, span) = match (AssocOp::from_token(&self.token), self.token.ident()) {
438 // When parsing const expressions, stop parsing when encountering `>`.
443 | AssocOp::GreaterEqual
444 | AssocOp::AssignOp(token::BinOpToken::Shr),
447 ) if self.restrictions.contains(Restrictions::CONST_EXPR) => {
450 (Some(op), _) => (op, self.token.span),
451 (None, Some((Ident { name: sym::and, span }, false))) => {
452 self.sess.emit_err(InvalidLogicalOperator {
453 span: self.token.span,
454 incorrect: "and".into(),
455 sub: InvalidLogicalOperatorSub::Conjunction(self.token.span),
457 (AssocOp::LAnd, span)
459 (None, Some((Ident { name: sym::or, span }, false))) => {
460 self.sess.emit_err(InvalidLogicalOperator {
461 span: self.token.span,
462 incorrect: "or".into(),
463 sub: InvalidLogicalOperatorSub::Disjunction(self.token.span),
469 Some(source_map::respan(span, op))
472 /// Checks if this expression is a successfully parsed statement.
473 fn expr_is_complete(&self, e: &Expr) -> bool {
474 self.restrictions.contains(Restrictions::STMT_EXPR)
475 && !classify::expr_requires_semi_to_be_stmt(e)
478 /// Parses `x..y`, `x..=y`, and `x..`/`x..=`.
479 /// The other two variants are handled in `parse_prefix_range_expr` below.
486 ) -> PResult<'a, P<Expr>> {
487 let rhs = if self.is_at_start_of_range_notation_rhs() {
488 Some(self.parse_assoc_expr_with(prec + 1, LhsExpr::NotYetParsed)?)
492 let rhs_span = rhs.as_ref().map_or(cur_op_span, |x| x.span);
493 let span = self.mk_expr_sp(&lhs, lhs.span, rhs_span);
495 if op == AssocOp::DotDot { RangeLimits::HalfOpen } else { RangeLimits::Closed };
496 let range = self.mk_range(Some(lhs), rhs, limits);
497 Ok(self.mk_expr(span, range))
500 fn is_at_start_of_range_notation_rhs(&self) -> bool {
501 if self.token.can_begin_expr() {
502 // Parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
503 if self.token == token::OpenDelim(Delimiter::Brace) {
504 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
512 /// Parses prefix-forms of range notation: `..expr`, `..`, `..=expr`.
513 fn parse_prefix_range_expr(&mut self, attrs: Option<AttrWrapper>) -> PResult<'a, P<Expr>> {
514 // Check for deprecated `...` syntax.
515 if self.token == token::DotDotDot {
516 self.err_dotdotdot_syntax(self.token.span);
520 [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token.kind),
521 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
525 let limits = match self.token.kind {
526 token::DotDot => RangeLimits::HalfOpen,
527 _ => RangeLimits::Closed,
529 let op = AssocOp::from_token(&self.token);
530 // FIXME: `parse_prefix_range_expr` is called when the current
531 // token is `DotDot`, `DotDotDot`, or `DotDotEq`. If we haven't already
532 // parsed attributes, then trying to parse them here will always fail.
533 // We should figure out how we want attributes on range expressions to work.
534 let attrs = self.parse_or_use_outer_attributes(attrs)?;
535 self.collect_tokens_for_expr(attrs, |this, attrs| {
536 let lo = this.token.span;
538 let (span, opt_end) = if this.is_at_start_of_range_notation_rhs() {
539 // RHS must be parsed with more associativity than the dots.
540 this.parse_assoc_expr_with(op.unwrap().precedence() + 1, LhsExpr::NotYetParsed)
541 .map(|x| (lo.to(x.span), Some(x)))?
545 let range = this.mk_range(None, opt_end, limits);
546 Ok(this.mk_expr_with_attrs(span, range, attrs))
550 /// Parses a prefix-unary-operator expr.
551 fn parse_prefix_expr(&mut self, attrs: Option<AttrWrapper>) -> PResult<'a, P<Expr>> {
552 let attrs = self.parse_or_use_outer_attributes(attrs)?;
553 let lo = self.token.span;
555 macro_rules! make_it {
556 ($this:ident, $attrs:expr, |this, _| $body:expr) => {
557 $this.collect_tokens_for_expr($attrs, |$this, attrs| {
558 let (hi, ex) = $body?;
559 Ok($this.mk_expr_with_attrs(lo.to(hi), ex, attrs))
566 // Note: when adding new unary operators, don't forget to adjust TokenKind::can_begin_expr()
567 match this.token.uninterpolate().kind {
568 token::Not => make_it!(this, attrs, |this, _| this.parse_unary_expr(lo, UnOp::Not)), // `!expr`
569 token::Tilde => make_it!(this, attrs, |this, _| this.recover_tilde_expr(lo)), // `~expr`
570 token::BinOp(token::Minus) => {
571 make_it!(this, attrs, |this, _| this.parse_unary_expr(lo, UnOp::Neg))
573 token::BinOp(token::Star) => {
574 make_it!(this, attrs, |this, _| this.parse_unary_expr(lo, UnOp::Deref))
576 token::BinOp(token::And) | token::AndAnd => {
577 make_it!(this, attrs, |this, _| this.parse_borrow_expr(lo))
579 token::BinOp(token::Plus) if this.look_ahead(1, |tok| tok.is_numeric_lit()) => {
580 let mut err = this.struct_span_err(lo, "leading `+` is not supported");
581 err.span_label(lo, "unexpected `+`");
583 // a block on the LHS might have been intended to be an expression instead
584 if let Some(sp) = this.sess.ambiguous_block_expr_parse.borrow().get(&lo) {
585 this.sess.expr_parentheses_needed(&mut err, *sp);
587 err.span_suggestion_verbose(
589 "try removing the `+`",
591 Applicability::MachineApplicable,
597 this.parse_prefix_expr(None)
599 // Recover from `++x`:
600 token::BinOp(token::Plus)
601 if this.look_ahead(1, |t| *t == token::BinOp(token::Plus)) =>
603 let prev_is_semi = this.prev_token == token::Semi;
604 let pre_span = this.token.span.to(this.look_ahead(1, |t| t.span));
609 let operand_expr = this.parse_dot_or_call_expr(Default::default())?;
610 this.recover_from_prefix_increment(operand_expr, pre_span, prev_is_semi)
612 token::Ident(..) if this.token.is_keyword(kw::Box) => {
613 make_it!(this, attrs, |this, _| this.parse_box_expr(lo))
615 token::Ident(..) if this.is_mistaken_not_ident_negation() => {
616 make_it!(this, attrs, |this, _| this.recover_not_expr(lo))
618 _ => return this.parse_dot_or_call_expr(Some(attrs)),
622 fn parse_prefix_expr_common(&mut self, lo: Span) -> PResult<'a, (Span, P<Expr>)> {
624 let expr = self.parse_prefix_expr(None);
625 let (span, expr) = self.interpolated_or_expr_span(expr)?;
626 Ok((lo.to(span), expr))
629 fn parse_unary_expr(&mut self, lo: Span, op: UnOp) -> PResult<'a, (Span, ExprKind)> {
630 let (span, expr) = self.parse_prefix_expr_common(lo)?;
631 Ok((span, self.mk_unary(op, expr)))
634 // Recover on `!` suggesting for bitwise negation instead.
635 fn recover_tilde_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
636 self.sess.emit_err(TildeAsUnaryOperator(lo));
638 self.parse_unary_expr(lo, UnOp::Not)
641 /// Parse `box expr`.
642 fn parse_box_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
643 let (span, expr) = self.parse_prefix_expr_common(lo)?;
644 self.sess.gated_spans.gate(sym::box_syntax, span);
645 Ok((span, ExprKind::Box(expr)))
648 fn is_mistaken_not_ident_negation(&self) -> bool {
649 let token_cannot_continue_expr = |t: &Token| match t.uninterpolate().kind {
650 // These tokens can start an expression after `!`, but
651 // can't continue an expression after an ident
652 token::Ident(name, is_raw) => token::ident_can_begin_expr(name, t.span, is_raw),
653 token::Literal(..) | token::Pound => true,
654 _ => t.is_whole_expr(),
656 self.token.is_ident_named(sym::not) && self.look_ahead(1, token_cannot_continue_expr)
659 /// Recover on `not expr` in favor of `!expr`.
660 fn recover_not_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
662 let negated_token = self.look_ahead(1, |t| t.clone());
663 self.sess.emit_err(NotAsNegationOperator {
664 negated: negated_token.span,
665 negated_desc: super::token_descr(&negated_token),
666 // Span the `not` plus trailing whitespace to avoid
667 // trailing whitespace after the `!` in our suggestion
668 not: self.sess.source_map().span_until_non_whitespace(lo.to(negated_token.span)),
672 self.parse_unary_expr(lo, UnOp::Not)
675 /// Returns the span of expr, if it was not interpolated or the span of the interpolated token.
676 fn interpolated_or_expr_span(
678 expr: PResult<'a, P<Expr>>,
679 ) -> PResult<'a, (Span, P<Expr>)> {
682 match self.prev_token.kind {
683 TokenKind::Interpolated(..) => self.prev_token.span,
691 fn parse_assoc_op_cast(
695 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind,
696 ) -> PResult<'a, P<Expr>> {
697 let mk_expr = |this: &mut Self, lhs: P<Expr>, rhs: P<Ty>| {
698 this.mk_expr(this.mk_expr_sp(&lhs, lhs_span, rhs.span), expr_kind(lhs, rhs))
701 // Save the state of the parser before parsing type normally, in case there is a
702 // LessThan comparison after this cast.
703 let parser_snapshot_before_type = self.clone();
704 let cast_expr = match self.parse_as_cast_ty() {
705 Ok(rhs) => mk_expr(self, lhs, rhs),
707 // Rewind to before attempting to parse the type with generics, to recover
708 // from situations like `x as usize < y` in which we first tried to parse
709 // `usize < y` as a type with generic arguments.
710 let parser_snapshot_after_type = mem::replace(self, parser_snapshot_before_type);
712 // Check for typo of `'a: loop { break 'a }` with a missing `'`.
713 match (&lhs.kind, &self.token.kind) {
716 ExprKind::Path(None, ast::Path { segments, .. }),
717 TokenKind::Ident(kw::For | kw::Loop | kw::While, false),
718 ) if segments.len() == 1 => {
719 let snapshot = self.create_snapshot_for_diagnostic();
721 ident: Ident::from_str_and_span(
722 &format!("'{}", segments[0].ident),
723 segments[0].ident.span,
726 match self.parse_labeled_expr(label, false) {
729 self.sess.emit_err(MalformedLoopLabel {
730 span: label.ident.span,
731 correct_label: label.ident,
737 self.restore_snapshot(snapshot);
744 match self.parse_path(PathStyle::Expr) {
746 let (op_noun, op_verb) = match self.token.kind {
747 token::Lt => ("comparison", "comparing"),
748 token::BinOp(token::Shl) => ("shift", "shifting"),
750 // We can end up here even without `<` being the next token, for
751 // example because `parse_ty_no_plus` returns `Err` on keywords,
752 // but `parse_path` returns `Ok` on them due to error recovery.
753 // Return original error and parser state.
754 *self = parser_snapshot_after_type;
755 return Err(type_err);
759 // Successfully parsed the type path leaving a `<` yet to parse.
762 // Report non-fatal diagnostics, keep `x as usize` as an expression
763 // in AST and continue parsing.
765 "`<` is interpreted as a start of generic arguments for `{}`, not a {}",
766 pprust::path_to_string(&path),
769 let span_after_type = parser_snapshot_after_type.token.span;
771 mk_expr(self, lhs, self.mk_ty(path.span, TyKind::Path(None, path)));
773 self.struct_span_err(self.token.span, &msg)
775 self.look_ahead(1, |t| t.span).to(span_after_type),
776 "interpreted as generic arguments",
778 .span_label(self.token.span, format!("not interpreted as {op_noun}"))
779 .multipart_suggestion(
780 &format!("try {op_verb} the cast value"),
782 (expr.span.shrink_to_lo(), "(".to_string()),
783 (expr.span.shrink_to_hi(), ")".to_string()),
785 Applicability::MachineApplicable,
792 // Couldn't parse as a path, return original error and parser state.
794 *self = parser_snapshot_after_type;
795 return Err(type_err);
801 self.parse_and_disallow_postfix_after_cast(cast_expr)
804 /// Parses a postfix operators such as `.`, `?`, or index (`[]`) after a cast,
805 /// then emits an error and returns the newly parsed tree.
806 /// The resulting parse tree for `&x as T[0]` has a precedence of `((&x) as T)[0]`.
807 fn parse_and_disallow_postfix_after_cast(
810 ) -> PResult<'a, P<Expr>> {
811 let span = cast_expr.span;
812 let (cast_kind, maybe_ascription_span) =
813 if let ExprKind::Type(ascripted_expr, _) = &cast_expr.kind {
814 ("type ascription", Some(ascripted_expr.span.shrink_to_hi().with_hi(span.hi())))
819 // Save the memory location of expr before parsing any following postfix operators.
820 // This will be compared with the memory location of the output expression.
821 // If they different we can assume we parsed another expression because the existing expression is not reallocated.
822 let addr_before = &*cast_expr as *const _ as usize;
823 let with_postfix = self.parse_dot_or_call_expr_with_(cast_expr, span)?;
824 let changed = addr_before != &*with_postfix as *const _ as usize;
826 // Check if an illegal postfix operator has been added after the cast.
827 // If the resulting expression is not a cast, or has a different memory location, it is an illegal postfix operator.
828 if !matches!(with_postfix.kind, ExprKind::Cast(_, _) | ExprKind::Type(_, _)) || changed {
830 "{cast_kind} cannot be followed by {}",
831 match with_postfix.kind {
832 ExprKind::Index(_, _) => "indexing",
833 ExprKind::Try(_) => "`?`",
834 ExprKind::Field(_, _) => "a field access",
835 ExprKind::MethodCall(_, _, _, _) => "a method call",
836 ExprKind::Call(_, _) => "a function call",
837 ExprKind::Await(_) => "`.await`",
838 ExprKind::Err => return Ok(with_postfix),
839 _ => unreachable!("parse_dot_or_call_expr_with_ shouldn't produce this"),
842 let mut err = self.struct_span_err(span, &msg);
844 let suggest_parens = |err: &mut Diagnostic| {
845 let suggestions = vec![
846 (span.shrink_to_lo(), "(".to_string()),
847 (span.shrink_to_hi(), ")".to_string()),
849 err.multipart_suggestion(
850 "try surrounding the expression in parentheses",
852 Applicability::MachineApplicable,
856 // If type ascription is "likely an error", the user will already be getting a useful
857 // help message, and doesn't need a second.
858 if self.last_type_ascription.map_or(false, |last_ascription| last_ascription.1) {
859 self.maybe_annotate_with_ascription(&mut err, false);
860 } else if let Some(ascription_span) = maybe_ascription_span {
861 let is_nightly = self.sess.unstable_features.is_nightly_build();
863 suggest_parens(&mut err);
868 "{}remove the type ascription",
869 if is_nightly { "alternatively, " } else { "" }
873 Applicability::MaybeIncorrect
875 Applicability::MachineApplicable
879 suggest_parens(&mut err);
886 fn parse_assoc_op_ascribe(&mut self, lhs: P<Expr>, lhs_span: Span) -> PResult<'a, P<Expr>> {
887 let maybe_path = self.could_ascription_be_path(&lhs.kind);
888 self.last_type_ascription = Some((self.prev_token.span, maybe_path));
889 let lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type)?;
890 self.sess.gated_spans.gate(sym::type_ascription, lhs.span);
894 /// Parse `& mut? <expr>` or `& raw [ const | mut ] <expr>`.
895 fn parse_borrow_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
897 let has_lifetime = self.token.is_lifetime() && self.look_ahead(1, |t| t != &token::Colon);
898 let lifetime = has_lifetime.then(|| self.expect_lifetime()); // For recovery, see below.
899 let (borrow_kind, mutbl) = self.parse_borrow_modifiers(lo);
900 let expr = self.parse_prefix_expr(None);
901 let (hi, expr) = self.interpolated_or_expr_span(expr)?;
902 let span = lo.to(hi);
903 if let Some(lt) = lifetime {
904 self.error_remove_borrow_lifetime(span, lt.ident.span);
906 Ok((span, ExprKind::AddrOf(borrow_kind, mutbl, expr)))
909 fn error_remove_borrow_lifetime(&self, span: Span, lt_span: Span) {
910 self.sess.emit_err(LifetimeInBorrowExpression { span, lifetime_span: lt_span });
913 /// Parse `mut?` or `raw [ const | mut ]`.
914 fn parse_borrow_modifiers(&mut self, lo: Span) -> (ast::BorrowKind, ast::Mutability) {
915 if self.check_keyword(kw::Raw) && self.look_ahead(1, Token::is_mutability) {
916 // `raw [ const | mut ]`.
917 let found_raw = self.eat_keyword(kw::Raw);
919 let mutability = self.parse_const_or_mut().unwrap();
920 self.sess.gated_spans.gate(sym::raw_ref_op, lo.to(self.prev_token.span));
921 (ast::BorrowKind::Raw, mutability)
924 (ast::BorrowKind::Ref, self.parse_mutability())
928 /// Parses `a.b` or `a(13)` or `a[4]` or just `a`.
929 fn parse_dot_or_call_expr(&mut self, attrs: Option<AttrWrapper>) -> PResult<'a, P<Expr>> {
930 let attrs = self.parse_or_use_outer_attributes(attrs)?;
931 self.collect_tokens_for_expr(attrs, |this, attrs| {
932 let base = this.parse_bottom_expr();
933 let (span, base) = this.interpolated_or_expr_span(base)?;
934 this.parse_dot_or_call_expr_with(base, span, attrs)
938 pub(super) fn parse_dot_or_call_expr_with(
942 mut attrs: ast::AttrVec,
943 ) -> PResult<'a, P<Expr>> {
944 // Stitch the list of outer attributes onto the return value.
945 // A little bit ugly, but the best way given the current code
947 let res = self.parse_dot_or_call_expr_with_(e0, lo);
948 if attrs.is_empty() {
952 expr.map(|mut expr| {
953 attrs.extend(expr.attrs);
961 fn parse_dot_or_call_expr_with_(&mut self, mut e: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
963 let has_question = if self.prev_token.kind == TokenKind::Ident(kw::Return, false) {
964 // we are using noexpect here because we don't expect a `?` directly after a `return`
965 // which could be suggested otherwise
966 self.eat_noexpect(&token::Question)
968 self.eat(&token::Question)
972 e = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Try(e));
975 let has_dot = if self.prev_token.kind == TokenKind::Ident(kw::Return, false) {
976 // we are using noexpect here because we don't expect a `.` directly after a `return`
977 // which could be suggested otherwise
978 self.eat_noexpect(&token::Dot)
980 self.eat(&token::Dot)
984 e = self.parse_dot_suffix_expr(lo, e)?;
987 if self.expr_is_complete(&e) {
990 e = match self.token.kind {
991 token::OpenDelim(Delimiter::Parenthesis) => self.parse_fn_call_expr(lo, e),
992 token::OpenDelim(Delimiter::Bracket) => self.parse_index_expr(lo, e)?,
998 fn look_ahead_type_ascription_as_field(&mut self) -> bool {
999 self.look_ahead(1, |t| t.is_ident())
1000 && self.look_ahead(2, |t| t == &token::Colon)
1001 && self.look_ahead(3, |t| t.can_begin_expr())
1004 fn parse_dot_suffix_expr(&mut self, lo: Span, base: P<Expr>) -> PResult<'a, P<Expr>> {
1005 match self.token.uninterpolate().kind {
1006 token::Ident(..) => self.parse_dot_suffix(base, lo),
1007 token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) => {
1008 Ok(self.parse_tuple_field_access_expr(lo, base, symbol, suffix, None))
1010 token::Literal(token::Lit { kind: token::Float, symbol, suffix }) => {
1011 Ok(self.parse_tuple_field_access_expr_float(lo, base, symbol, suffix))
1014 self.error_unexpected_after_dot();
1020 fn error_unexpected_after_dot(&self) {
1021 // FIXME Could factor this out into non_fatal_unexpected or something.
1022 let actual = pprust::token_to_string(&self.token);
1023 self.struct_span_err(self.token.span, &format!("unexpected token: `{actual}`")).emit();
1026 // We need an identifier or integer, but the next token is a float.
1027 // Break the float into components to extract the identifier or integer.
1028 // FIXME: With current `TokenCursor` it's hard to break tokens into more than 2
1029 // parts unless those parts are processed immediately. `TokenCursor` should either
1030 // support pushing "future tokens" (would be also helpful to `break_and_eat`), or
1031 // we should break everything including floats into more basic proc-macro style
1032 // tokens in the lexer (probably preferable).
1033 fn parse_tuple_field_access_expr_float(
1038 suffix: Option<Symbol>,
1041 enum FloatComponent {
1045 use FloatComponent::*;
1047 let float_str = float.as_str();
1048 let mut components = Vec::new();
1049 let mut ident_like = String::new();
1050 for c in float_str.chars() {
1051 if c == '_' || c.is_ascii_alphanumeric() {
1053 } else if matches!(c, '.' | '+' | '-') {
1054 if !ident_like.is_empty() {
1055 components.push(IdentLike(mem::take(&mut ident_like)));
1057 components.push(Punct(c));
1059 panic!("unexpected character in a float token: {:?}", c)
1062 if !ident_like.is_empty() {
1063 components.push(IdentLike(ident_like));
1066 // With proc macros the span can refer to anything, the source may be too short,
1067 // or too long, or non-ASCII. It only makes sense to break our span into components
1068 // if its underlying text is identical to our float literal.
1069 let span = self.token.span;
1070 let can_take_span_apart =
1071 || self.span_to_snippet(span).as_deref() == Ok(float_str).as_deref();
1073 match &*components {
1076 self.parse_tuple_field_access_expr(lo, base, Symbol::intern(&i), suffix, None)
1079 [IdentLike(i), Punct('.')] => {
1080 let (ident_span, dot_span) = if can_take_span_apart() {
1081 let (span, ident_len) = (span.data(), BytePos::from_usize(i.len()));
1082 let ident_span = span.with_hi(span.lo + ident_len);
1083 let dot_span = span.with_lo(span.lo + ident_len);
1084 (ident_span, dot_span)
1088 assert!(suffix.is_none());
1089 let symbol = Symbol::intern(&i);
1090 self.token = Token::new(token::Ident(symbol, false), ident_span);
1091 let next_token = (Token::new(token::Dot, dot_span), self.token_spacing);
1092 self.parse_tuple_field_access_expr(lo, base, symbol, None, Some(next_token))
1095 [IdentLike(i1), Punct('.'), IdentLike(i2)] => {
1096 let (ident1_span, dot_span, ident2_span) = if can_take_span_apart() {
1097 let (span, ident1_len) = (span.data(), BytePos::from_usize(i1.len()));
1098 let ident1_span = span.with_hi(span.lo + ident1_len);
1100 .with_lo(span.lo + ident1_len)
1101 .with_hi(span.lo + ident1_len + BytePos(1));
1102 let ident2_span = self.token.span.with_lo(span.lo + ident1_len + BytePos(1));
1103 (ident1_span, dot_span, ident2_span)
1107 let symbol1 = Symbol::intern(&i1);
1108 self.token = Token::new(token::Ident(symbol1, false), ident1_span);
1109 // This needs to be `Spacing::Alone` to prevent regressions.
1110 // See issue #76399 and PR #76285 for more details
1111 let next_token1 = (Token::new(token::Dot, dot_span), Spacing::Alone);
1113 self.parse_tuple_field_access_expr(lo, base, symbol1, None, Some(next_token1));
1114 let symbol2 = Symbol::intern(&i2);
1115 let next_token2 = Token::new(token::Ident(symbol2, false), ident2_span);
1116 self.bump_with((next_token2, self.token_spacing)); // `.`
1117 self.parse_tuple_field_access_expr(lo, base1, symbol2, suffix, None)
1119 // 1e+ | 1e- (recovered)
1120 [IdentLike(_), Punct('+' | '-')] |
1122 [IdentLike(_), Punct('+' | '-'), IdentLike(_)] |
1124 [IdentLike(_), Punct('.'), IdentLike(_), Punct('+' | '-')] |
1126 [IdentLike(_), Punct('.'), IdentLike(_), Punct('+' | '-'), IdentLike(_)] => {
1127 // See the FIXME about `TokenCursor` above.
1128 self.error_unexpected_after_dot();
1131 _ => panic!("unexpected components in a float token: {:?}", components),
1135 fn parse_tuple_field_access_expr(
1140 suffix: Option<Symbol>,
1141 next_token: Option<(Token, Spacing)>,
1144 Some(next_token) => self.bump_with(next_token),
1145 None => self.bump(),
1147 let span = self.prev_token.span;
1148 let field = ExprKind::Field(base, Ident::new(field, span));
1149 self.expect_no_suffix(span, "a tuple index", suffix);
1150 self.mk_expr(lo.to(span), field)
1153 /// Parse a function call expression, `expr(...)`.
1154 fn parse_fn_call_expr(&mut self, lo: Span, fun: P<Expr>) -> P<Expr> {
1155 let snapshot = if self.token.kind == token::OpenDelim(Delimiter::Parenthesis)
1156 && self.look_ahead_type_ascription_as_field()
1158 Some((self.create_snapshot_for_diagnostic(), fun.kind.clone()))
1162 let open_paren = self.token.span;
1165 .parse_paren_expr_seq()
1166 .map(|args| self.mk_expr(lo.to(self.prev_token.span), self.mk_call(fun, args)));
1168 self.maybe_recover_struct_lit_bad_delims(lo, open_paren, &mut seq, snapshot)
1172 self.recover_seq_parse_error(Delimiter::Parenthesis, lo, seq)
1175 /// If we encounter a parser state that looks like the user has written a `struct` literal with
1176 /// parentheses instead of braces, recover the parser state and provide suggestions.
1177 #[instrument(skip(self, seq, snapshot), level = "trace")]
1178 fn maybe_recover_struct_lit_bad_delims(
1182 seq: &mut PResult<'a, P<Expr>>,
1183 snapshot: Option<(SnapshotParser<'a>, ExprKind)>,
1184 ) -> Option<P<Expr>> {
1185 match (seq.as_mut(), snapshot) {
1186 (Err(err), Some((mut snapshot, ExprKind::Path(None, path)))) => {
1187 let name = pprust::path_to_string(&path);
1188 snapshot.bump(); // `(`
1189 match snapshot.parse_struct_fields(path, false, Delimiter::Parenthesis) {
1191 if snapshot.eat(&token::CloseDelim(Delimiter::Parenthesis)) =>
1193 // We are certain we have `Enum::Foo(a: 3, b: 4)`, suggest
1194 // `Enum::Foo { a: 3, b: 4 }` or `Enum::Foo(3, 4)`.
1195 self.restore_snapshot(snapshot);
1196 let close_paren = self.prev_token.span;
1197 let span = lo.to(self.prev_token.span);
1198 if !fields.is_empty() {
1199 let replacement_err = self.struct_span_err(
1201 "invalid `struct` delimiters or `fn` call arguments",
1203 mem::replace(err, replacement_err).cancel();
1205 err.multipart_suggestion(
1206 &format!("if `{name}` is a struct, use braces as delimiters"),
1208 (open_paren, " { ".to_string()),
1209 (close_paren, " }".to_string()),
1211 Applicability::MaybeIncorrect,
1213 err.multipart_suggestion(
1214 &format!("if `{name}` is a function, use the arguments directly"),
1217 .map(|field| (field.span.until(field.expr.span), String::new()))
1219 Applicability::MaybeIncorrect,
1225 return Some(self.mk_expr_err(span));
1238 /// Parse an indexing expression `expr[...]`.
1239 fn parse_index_expr(&mut self, lo: Span, base: P<Expr>) -> PResult<'a, P<Expr>> {
1240 let prev_span = self.prev_token.span;
1241 let open_delim_span = self.token.span;
1243 let index = self.parse_expr()?;
1244 self.suggest_missing_semicolon_before_array(prev_span, open_delim_span)?;
1245 self.expect(&token::CloseDelim(Delimiter::Bracket))?;
1246 Ok(self.mk_expr(lo.to(self.prev_token.span), self.mk_index(base, index)))
1249 /// Assuming we have just parsed `.`, continue parsing into an expression.
1250 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
1251 if self.token.uninterpolated_span().rust_2018() && self.eat_keyword(kw::Await) {
1252 return Ok(self.mk_await_expr(self_arg, lo));
1255 let fn_span_lo = self.token.span;
1256 let mut segment = self.parse_path_segment(PathStyle::Expr, None)?;
1257 self.check_trailing_angle_brackets(&segment, &[&token::OpenDelim(Delimiter::Parenthesis)]);
1258 self.check_turbofish_missing_angle_brackets(&mut segment);
1260 if self.check(&token::OpenDelim(Delimiter::Parenthesis)) {
1261 // Method call `expr.f()`
1262 let args = self.parse_paren_expr_seq()?;
1263 let fn_span = fn_span_lo.to(self.prev_token.span);
1264 let span = lo.to(self.prev_token.span);
1265 Ok(self.mk_expr(span, ExprKind::MethodCall(segment, self_arg, args, fn_span)))
1267 // Field access `expr.f`
1268 if let Some(args) = segment.args {
1269 self.sess.emit_err(FieldExpressionWithGeneric(args.span()));
1272 let span = lo.to(self.prev_token.span);
1273 Ok(self.mk_expr(span, ExprKind::Field(self_arg, segment.ident)))
1277 /// At the bottom (top?) of the precedence hierarchy,
1278 /// Parses things like parenthesized exprs, macros, `return`, etc.
1280 /// N.B., this does not parse outer attributes, and is private because it only works
1281 /// correctly if called from `parse_dot_or_call_expr()`.
1282 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
1283 maybe_recover_from_interpolated_ty_qpath!(self, true);
1284 maybe_whole_expr!(self);
1286 // Outer attributes are already parsed and will be
1287 // added to the return value after the fact.
1289 // Note: when adding new syntax here, don't forget to adjust `TokenKind::can_begin_expr()`.
1290 let lo = self.token.span;
1291 if let token::Literal(_) = self.token.kind {
1292 // This match arm is a special-case of the `_` match arm below and
1293 // could be removed without changing functionality, but it's faster
1294 // to have it here, especially for programs with large constants.
1295 self.parse_lit_expr()
1296 } else if self.check(&token::OpenDelim(Delimiter::Parenthesis)) {
1297 self.parse_tuple_parens_expr()
1298 } else if self.check(&token::OpenDelim(Delimiter::Brace)) {
1299 self.parse_block_expr(None, lo, BlockCheckMode::Default)
1300 } else if self.check(&token::BinOp(token::Or)) || self.check(&token::OrOr) {
1301 self.parse_closure_expr().map_err(|mut err| {
1302 // If the input is something like `if a { 1 } else { 2 } | if a { 3 } else { 4 }`
1303 // then suggest parens around the lhs.
1304 if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&lo) {
1305 self.sess.expr_parentheses_needed(&mut err, *sp);
1309 } else if self.check(&token::OpenDelim(Delimiter::Bracket)) {
1310 self.parse_array_or_repeat_expr(Delimiter::Bracket)
1311 } else if self.check_path() {
1312 self.parse_path_start_expr()
1313 } else if self.check_keyword(kw::Move) || self.check_keyword(kw::Static) {
1314 self.parse_closure_expr()
1315 } else if self.eat_keyword(kw::If) {
1316 self.parse_if_expr()
1317 } else if self.check_keyword(kw::For) {
1318 if self.choose_generics_over_qpath(1) {
1319 self.parse_closure_expr()
1321 assert!(self.eat_keyword(kw::For));
1322 self.parse_for_expr(None, self.prev_token.span)
1324 } else if self.eat_keyword(kw::While) {
1325 self.parse_while_expr(None, self.prev_token.span)
1326 } else if let Some(label) = self.eat_label() {
1327 self.parse_labeled_expr(label, true)
1328 } else if self.eat_keyword(kw::Loop) {
1329 let sp = self.prev_token.span;
1330 self.parse_loop_expr(None, self.prev_token.span).map_err(|mut err| {
1331 err.span_label(sp, "while parsing this `loop` expression");
1334 } else if self.eat_keyword(kw::Continue) {
1335 let kind = ExprKind::Continue(self.eat_label());
1336 Ok(self.mk_expr(lo.to(self.prev_token.span), kind))
1337 } else if self.eat_keyword(kw::Match) {
1338 let match_sp = self.prev_token.span;
1339 self.parse_match_expr().map_err(|mut err| {
1340 err.span_label(match_sp, "while parsing this `match` expression");
1343 } else if self.eat_keyword(kw::Unsafe) {
1344 let sp = self.prev_token.span;
1345 self.parse_block_expr(None, lo, BlockCheckMode::Unsafe(ast::UserProvided)).map_err(
1347 err.span_label(sp, "while parsing this `unsafe` expression");
1351 } else if self.check_inline_const(0) {
1352 self.parse_const_block(lo.to(self.token.span), false)
1353 } else if self.is_do_catch_block() {
1354 self.recover_do_catch()
1355 } else if self.is_try_block() {
1356 self.expect_keyword(kw::Try)?;
1357 self.parse_try_block(lo)
1358 } else if self.eat_keyword(kw::Return) {
1359 self.parse_return_expr()
1360 } else if self.eat_keyword(kw::Break) {
1361 self.parse_break_expr()
1362 } else if self.eat_keyword(kw::Yield) {
1363 self.parse_yield_expr()
1364 } else if self.is_do_yeet() {
1365 self.parse_yeet_expr()
1366 } else if self.check_keyword(kw::Let) {
1367 self.parse_let_expr()
1368 } else if self.eat_keyword(kw::Underscore) {
1369 Ok(self.mk_expr(self.prev_token.span, ExprKind::Underscore))
1370 } else if !self.unclosed_delims.is_empty() && self.check(&token::Semi) {
1371 // Don't complain about bare semicolons after unclosed braces
1372 // recovery in order to keep the error count down. Fixing the
1373 // delimiters will possibly also fix the bare semicolon found in
1374 // expression context. For example, silence the following error:
1376 // error: expected expression, found `;`
1380 // | ^ expected expression
1382 Ok(self.mk_expr_err(self.token.span))
1383 } else if self.token.uninterpolated_span().rust_2018() {
1384 // `Span::rust_2018()` is somewhat expensive; don't get it repeatedly.
1385 if self.check_keyword(kw::Async) {
1386 if self.is_async_block() {
1387 // Check for `async {` and `async move {`.
1388 self.parse_async_block()
1390 self.parse_closure_expr()
1392 } else if self.eat_keyword(kw::Await) {
1393 self.recover_incorrect_await_syntax(lo, self.prev_token.span)
1395 self.parse_lit_expr()
1398 self.parse_lit_expr()
1402 fn parse_lit_expr(&mut self) -> PResult<'a, P<Expr>> {
1403 let lo = self.token.span;
1404 match self.parse_opt_lit() {
1406 let expr = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Lit(literal));
1407 self.maybe_recover_from_bad_qpath(expr)
1409 None => self.try_macro_suggestion(),
1413 fn parse_tuple_parens_expr(&mut self) -> PResult<'a, P<Expr>> {
1414 let lo = self.token.span;
1415 self.expect(&token::OpenDelim(Delimiter::Parenthesis))?;
1416 let (es, trailing_comma) = match self.parse_seq_to_end(
1417 &token::CloseDelim(Delimiter::Parenthesis),
1418 SeqSep::trailing_allowed(token::Comma),
1419 |p| p.parse_expr_catch_underscore(),
1423 return Ok(self.recover_seq_parse_error(Delimiter::Parenthesis, lo, Err(err)));
1426 let kind = if es.len() == 1 && !trailing_comma {
1427 // `(e)` is parenthesized `e`.
1428 ExprKind::Paren(es.into_iter().next().unwrap())
1430 // `(e,)` is a tuple with only one field, `e`.
1433 let expr = self.mk_expr(lo.to(self.prev_token.span), kind);
1434 self.maybe_recover_from_bad_qpath(expr)
1437 fn parse_array_or_repeat_expr(&mut self, close_delim: Delimiter) -> PResult<'a, P<Expr>> {
1438 let lo = self.token.span;
1439 self.bump(); // `[` or other open delim
1441 let close = &token::CloseDelim(close_delim);
1442 let kind = if self.eat(close) {
1444 ExprKind::Array(Vec::new())
1447 let first_expr = self.parse_expr()?;
1448 if self.eat(&token::Semi) {
1449 // Repeating array syntax: `[ 0; 512 ]`
1450 let count = self.parse_anon_const_expr()?;
1451 self.expect(close)?;
1452 ExprKind::Repeat(first_expr, count)
1453 } else if self.eat(&token::Comma) {
1454 // Vector with two or more elements.
1455 let sep = SeqSep::trailing_allowed(token::Comma);
1456 let (remaining_exprs, _) = self.parse_seq_to_end(close, sep, |p| p.parse_expr())?;
1457 let mut exprs = vec![first_expr];
1458 exprs.extend(remaining_exprs);
1459 ExprKind::Array(exprs)
1461 // Vector with one element
1462 self.expect(close)?;
1463 ExprKind::Array(vec![first_expr])
1466 let expr = self.mk_expr(lo.to(self.prev_token.span), kind);
1467 self.maybe_recover_from_bad_qpath(expr)
1470 fn parse_path_start_expr(&mut self) -> PResult<'a, P<Expr>> {
1471 let (qself, path) = if self.eat_lt() {
1472 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
1475 (None, self.parse_path(PathStyle::Expr)?)
1478 // `!`, as an operator, is prefix, so we know this isn't that.
1479 let (span, kind) = if self.eat(&token::Not) {
1480 // MACRO INVOCATION expression
1481 if qself.is_some() {
1482 self.sess.emit_err(MacroInvocationWithQualifiedPath(path.span));
1485 let mac = P(MacCall {
1487 args: self.parse_mac_args()?,
1488 prior_type_ascription: self.last_type_ascription,
1490 (lo.to(self.prev_token.span), ExprKind::MacCall(mac))
1491 } else if self.check(&token::OpenDelim(Delimiter::Brace)) &&
1492 let Some(expr) = self.maybe_parse_struct_expr(qself.as_ref(), &path) {
1493 if qself.is_some() {
1494 self.sess.gated_spans.gate(sym::more_qualified_paths, path.span);
1498 (path.span, ExprKind::Path(qself, path))
1501 let expr = self.mk_expr(span, kind);
1502 self.maybe_recover_from_bad_qpath(expr)
1505 /// Parse `'label: $expr`. The label is already parsed.
1506 fn parse_labeled_expr(
1509 mut consume_colon: bool,
1510 ) -> PResult<'a, P<Expr>> {
1511 let lo = label.ident.span;
1512 let label = Some(label);
1513 let ate_colon = self.eat(&token::Colon);
1514 let expr = if self.eat_keyword(kw::While) {
1515 self.parse_while_expr(label, lo)
1516 } else if self.eat_keyword(kw::For) {
1517 self.parse_for_expr(label, lo)
1518 } else if self.eat_keyword(kw::Loop) {
1519 self.parse_loop_expr(label, lo)
1520 } else if self.check_noexpect(&token::OpenDelim(Delimiter::Brace))
1521 || self.token.is_whole_block()
1523 self.parse_block_expr(label, lo, BlockCheckMode::Default)
1524 } else if !ate_colon
1525 && (self.check_noexpect(&TokenKind::Comma) || self.check_noexpect(&TokenKind::Gt))
1527 // We're probably inside of a `Path<'a>` that needs a turbofish
1528 self.sess.emit_err(UnexpectedTokenAfterLabel(self.token.span));
1529 consume_colon = false;
1530 Ok(self.mk_expr_err(lo))
1532 // FIXME: use UnexpectedTokenAfterLabel, needs multipart suggestions
1533 let msg = "expected `while`, `for`, `loop` or `{` after a label";
1535 let mut err = self.struct_span_err(self.token.span, msg);
1536 err.span_label(self.token.span, msg);
1538 // Continue as an expression in an effort to recover on `'label: non_block_expr`.
1539 let expr = self.parse_expr().map(|expr| {
1540 let span = expr.span;
1542 let found_labeled_breaks = {
1543 struct FindLabeledBreaksVisitor(bool);
1545 impl<'ast> Visitor<'ast> for FindLabeledBreaksVisitor {
1546 fn visit_expr_post(&mut self, ex: &'ast Expr) {
1547 if let ExprKind::Break(Some(_label), _) = ex.kind {
1553 let mut vis = FindLabeledBreaksVisitor(false);
1554 vis.visit_expr(&expr);
1558 // Suggestion involves adding a (as of time of writing this, unstable) labeled block.
1560 // If there are no breaks that may use this label, suggest removing the label and
1561 // recover to the unmodified expression.
1562 if !found_labeled_breaks {
1563 let msg = "consider removing the label";
1564 err.span_suggestion_verbose(
1568 Applicability::MachineApplicable,
1574 let sugg_msg = "consider enclosing expression in a block";
1575 let suggestions = vec![
1576 (span.shrink_to_lo(), "{ ".to_owned()),
1577 (span.shrink_to_hi(), " }".to_owned()),
1580 err.multipart_suggestion_verbose(
1583 Applicability::MachineApplicable,
1586 // Replace `'label: non_block_expr` with `'label: {non_block_expr}` in order to suppress future errors about `break 'label`.
1587 let stmt = self.mk_stmt(span, StmtKind::Expr(expr));
1588 let blk = self.mk_block(vec![stmt], BlockCheckMode::Default, span);
1589 self.mk_expr(span, ExprKind::Block(blk, label))
1596 if !ate_colon && consume_colon {
1597 self.sess.emit_err(RequireColonAfterLabeledExpression {
1600 label_end: lo.shrink_to_hi(),
1607 /// Recover on the syntax `do catch { ... }` suggesting `try { ... }` instead.
1608 fn recover_do_catch(&mut self) -> PResult<'a, P<Expr>> {
1609 let lo = self.token.span;
1611 self.bump(); // `do`
1612 self.bump(); // `catch`
1614 let span = lo.to(self.prev_token.span);
1615 self.sess.emit_err(DoCatchSyntaxRemoved { span });
1617 self.parse_try_block(lo)
1620 /// Parse an expression if the token can begin one.
1621 fn parse_expr_opt(&mut self) -> PResult<'a, Option<P<Expr>>> {
1622 Ok(if self.token.can_begin_expr() { Some(self.parse_expr()?) } else { None })
1625 /// Parse `"return" expr?`.
1626 fn parse_return_expr(&mut self) -> PResult<'a, P<Expr>> {
1627 let lo = self.prev_token.span;
1628 let kind = ExprKind::Ret(self.parse_expr_opt()?);
1629 let expr = self.mk_expr(lo.to(self.prev_token.span), kind);
1630 self.maybe_recover_from_bad_qpath(expr)
1633 /// Parse `"do" "yeet" expr?`.
1634 fn parse_yeet_expr(&mut self) -> PResult<'a, P<Expr>> {
1635 let lo = self.token.span;
1637 self.bump(); // `do`
1638 self.bump(); // `yeet`
1640 let kind = ExprKind::Yeet(self.parse_expr_opt()?);
1642 let span = lo.to(self.prev_token.span);
1643 self.sess.gated_spans.gate(sym::yeet_expr, span);
1644 let expr = self.mk_expr(span, kind);
1645 self.maybe_recover_from_bad_qpath(expr)
1648 /// Parse `"break" (('label (:? expr)?) | expr?)` with `"break"` token already eaten.
1649 /// If the label is followed immediately by a `:` token, the label and `:` are
1650 /// parsed as part of the expression (i.e. a labeled loop). The language team has
1651 /// decided in #87026 to require parentheses as a visual aid to avoid confusion if
1652 /// the break expression of an unlabeled break is a labeled loop (as in
1653 /// `break 'lbl: loop {}`); a labeled break with an unlabeled loop as its value
1654 /// expression only gets a warning for compatibility reasons; and a labeled break
1655 /// with a labeled loop does not even get a warning because there is no ambiguity.
1656 fn parse_break_expr(&mut self) -> PResult<'a, P<Expr>> {
1657 let lo = self.prev_token.span;
1658 let mut label = self.eat_label();
1659 let kind = if label.is_some() && self.token == token::Colon {
1660 // The value expression can be a labeled loop, see issue #86948, e.g.:
1661 // `loop { break 'label: loop { break 'label 42; }; }`
1662 let lexpr = self.parse_labeled_expr(label.take().unwrap(), true)?;
1663 self.struct_span_err(
1665 "parentheses are required around this expression to avoid confusion with a labeled break expression",
1667 .multipart_suggestion(
1668 "wrap the expression in parentheses",
1670 (lexpr.span.shrink_to_lo(), "(".to_string()),
1671 (lexpr.span.shrink_to_hi(), ")".to_string()),
1673 Applicability::MachineApplicable,
1677 } else if self.token != token::OpenDelim(Delimiter::Brace)
1678 || !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
1680 let expr = self.parse_expr_opt()?;
1681 if let Some(ref expr) = expr {
1685 ExprKind::While(_, _, None)
1686 | ExprKind::ForLoop(_, _, _, None)
1687 | ExprKind::Loop(_, None)
1688 | ExprKind::Block(_, None)
1691 self.sess.buffer_lint_with_diagnostic(
1692 BREAK_WITH_LABEL_AND_LOOP,
1695 "this labeled break expression is easy to confuse with an unlabeled break with a labeled value expression",
1696 BuiltinLintDiagnostics::BreakWithLabelAndLoop(expr.span),
1704 let expr = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Break(label, kind));
1705 self.maybe_recover_from_bad_qpath(expr)
1708 /// Parse `"yield" expr?`.
1709 fn parse_yield_expr(&mut self) -> PResult<'a, P<Expr>> {
1710 let lo = self.prev_token.span;
1711 let kind = ExprKind::Yield(self.parse_expr_opt()?);
1712 let span = lo.to(self.prev_token.span);
1713 self.sess.gated_spans.gate(sym::generators, span);
1714 let expr = self.mk_expr(span, kind);
1715 self.maybe_recover_from_bad_qpath(expr)
1718 /// Returns a string literal if the next token is a string literal.
1719 /// In case of error returns `Some(lit)` if the next token is a literal with a wrong kind,
1720 /// and returns `None` if the next token is not literal at all.
1721 pub fn parse_str_lit(&mut self) -> Result<ast::StrLit, Option<Lit>> {
1722 match self.parse_opt_lit() {
1723 Some(lit) => match lit.kind {
1724 ast::LitKind::Str(symbol_unescaped, style) => Ok(ast::StrLit {
1726 symbol: lit.token_lit.symbol,
1727 suffix: lit.token_lit.suffix,
1731 _ => Err(Some(lit)),
1737 pub(super) fn parse_lit(&mut self) -> PResult<'a, Lit> {
1738 self.parse_opt_lit().ok_or_else(|| {
1739 if let token::Interpolated(inner) = &self.token.kind {
1740 let expr = match inner.as_ref() {
1741 token::NtExpr(expr) => Some(expr),
1742 token::NtLiteral(expr) => Some(expr),
1745 if let Some(expr) = expr {
1746 if matches!(expr.kind, ExprKind::Err) {
1749 .struct_span_err(self.token.span, "invalid interpolated expression");
1750 err.downgrade_to_delayed_bug();
1755 let msg = format!("unexpected token: {}", super::token_descr(&self.token));
1756 self.struct_span_err(self.token.span, &msg)
1760 /// Matches `lit = true | false | token_lit`.
1761 /// Returns `None` if the next token is not a literal.
1762 pub(super) fn parse_opt_lit(&mut self) -> Option<Lit> {
1763 let mut recovered = None;
1764 if self.token == token::Dot {
1765 // Attempt to recover `.4` as `0.4`. We don't currently have any syntax where
1766 // dot would follow an optional literal, so we do this unconditionally.
1767 recovered = self.look_ahead(1, |next_token| {
1768 if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) =
1771 if self.token.span.hi() == next_token.span.lo() {
1772 let s = String::from("0.") + symbol.as_str();
1773 let kind = TokenKind::lit(token::Float, Symbol::intern(&s), suffix);
1774 return Some(Token::new(kind, self.token.span.to(next_token.span)));
1779 if let Some(token) = &recovered {
1781 self.error_float_lits_must_have_int_part(&token);
1785 let token = recovered.as_ref().unwrap_or(&self.token);
1786 match Lit::from_token(token) {
1791 Err(LitError::NotLiteral) => None,
1793 let span = token.span;
1794 let token::Literal(lit) = token.kind else {
1798 self.report_lit_error(err, lit, span);
1799 // Pack possible quotes and prefixes from the original literal into
1800 // the error literal's symbol so they can be pretty-printed faithfully.
1801 let suffixless_lit = token::Lit::new(lit.kind, lit.symbol, None);
1802 let symbol = Symbol::intern(&suffixless_lit.to_string());
1803 let lit = token::Lit::new(token::Err, symbol, lit.suffix);
1804 Some(Lit::from_token_lit(lit, span).unwrap_or_else(|_| unreachable!()))
1809 fn error_float_lits_must_have_int_part(&self, token: &Token) {
1810 self.sess.emit_err(FloatLiteralRequiresIntegerPart {
1812 correct: pprust::token_to_string(token).into_owned(),
1816 fn report_lit_error(&self, err: LitError, lit: token::Lit, span: Span) {
1817 // Checks if `s` looks like i32 or u1234 etc.
1818 fn looks_like_width_suffix(first_chars: &[char], s: &str) -> bool {
1819 s.len() > 1 && s.starts_with(first_chars) && s[1..].chars().all(|c| c.is_ascii_digit())
1822 // Try to lowercase the prefix if it's a valid base prefix.
1823 fn fix_base_capitalisation(s: &str) -> Option<String> {
1824 if let Some(stripped) = s.strip_prefix('B') {
1825 Some(format!("0b{stripped}"))
1826 } else if let Some(stripped) = s.strip_prefix('O') {
1827 Some(format!("0o{stripped}"))
1828 } else if let Some(stripped) = s.strip_prefix('X') {
1829 Some(format!("0x{stripped}"))
1835 let token::Lit { kind, suffix, .. } = lit;
1837 // `NotLiteral` is not an error by itself, so we don't report
1838 // it and give the parser opportunity to try something else.
1839 LitError::NotLiteral => {}
1840 // `LexerError` *is* an error, but it was already reported
1841 // by lexer, so here we don't report it the second time.
1842 LitError::LexerError => {}
1843 LitError::InvalidSuffix => {
1844 self.expect_no_suffix(
1846 &format!("{} {} literal", kind.article(), kind.descr()),
1850 LitError::InvalidIntSuffix => {
1851 let suf = suffix.expect("suffix error with no suffix");
1852 let suf = suf.as_str();
1853 if looks_like_width_suffix(&['i', 'u'], &suf) {
1854 // If it looks like a width, try to be helpful.
1855 self.sess.emit_err(InvalidIntLiteralWidth { span, width: suf[1..].into() });
1856 } else if let Some(fixed) = fix_base_capitalisation(suf) {
1857 self.sess.emit_err(InvalidNumLiteralBasePrefix { span, fixed });
1859 self.sess.emit_err(InvalidNumLiteralSuffix { span, suffix: suf.to_string() });
1862 LitError::InvalidFloatSuffix => {
1863 let suf = suffix.expect("suffix error with no suffix");
1864 let suf = suf.as_str();
1865 if looks_like_width_suffix(&['f'], suf) {
1866 // If it looks like a width, try to be helpful.
1868 .emit_err(InvalidFloatLiteralWidth { span, width: suf[1..].to_string() });
1870 self.sess.emit_err(InvalidFloatLiteralSuffix { span, suffix: suf.to_string() });
1873 LitError::NonDecimalFloat(base) => {
1874 let descr = match base {
1875 16 => "hexadecimal",
1878 _ => unreachable!(),
1880 self.struct_span_err(span, &format!("{descr} float literal is not supported"))
1881 .span_label(span, "not supported")
1884 LitError::IntTooLarge => {
1885 self.sess.emit_err(IntLiteralTooLarge { span });
1890 pub(super) fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<Symbol>) {
1891 if let Some(suf) = suffix {
1892 let mut err = if kind == "a tuple index"
1893 && [sym::i32, sym::u32, sym::isize, sym::usize].contains(&suf)
1895 // #59553: warn instead of reject out of hand to allow the fix to percolate
1896 // through the ecosystem when people fix their macros
1900 .struct_span_warn(sp, &format!("suffixes on {kind} are invalid"));
1902 "`{}` is *temporarily* accepted on tuple index fields as it was \
1903 incorrectly accepted on stable for a few releases",
1907 "on proc macros, you'll want to use `syn::Index::from` or \
1908 `proc_macro::Literal::*_unsuffixed` for code that will desugar \
1909 to tuple field access",
1912 "see issue #60210 <https://github.com/rust-lang/rust/issues/60210> \
1913 for more information",
1917 self.struct_span_err(sp, &format!("suffixes on {kind} are invalid"))
1920 err.span_label(sp, format!("invalid suffix `{suf}`"));
1925 /// Matches `'-' lit | lit` (cf. `ast_validation::AstValidator::check_expr_within_pat`).
1926 /// Keep this in sync with `Token::can_begin_literal_maybe_minus`.
1927 pub fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1928 maybe_whole_expr!(self);
1930 let lo = self.token.span;
1931 let minus_present = self.eat(&token::BinOp(token::Minus));
1932 let lit = self.parse_lit()?;
1933 let expr = self.mk_expr(lit.span, ExprKind::Lit(lit));
1936 Ok(self.mk_expr(lo.to(self.prev_token.span), self.mk_unary(UnOp::Neg, expr)))
1942 fn is_array_like_block(&mut self) -> bool {
1943 self.look_ahead(1, |t| matches!(t.kind, TokenKind::Ident(..) | TokenKind::Literal(_)))
1944 && self.look_ahead(2, |t| t == &token::Comma)
1945 && self.look_ahead(3, |t| t.can_begin_expr())
1948 /// Emits a suggestion if it looks like the user meant an array but
1949 /// accidentally used braces, causing the code to be interpreted as a block
1951 fn maybe_suggest_brackets_instead_of_braces(&mut self, lo: Span) -> Option<P<Expr>> {
1952 let mut snapshot = self.create_snapshot_for_diagnostic();
1953 match snapshot.parse_array_or_repeat_expr(Delimiter::Brace) {
1955 let hi = snapshot.prev_token.span;
1956 self.struct_span_err(arr.span, "this is a block expression, not an array")
1957 .multipart_suggestion(
1958 "to make an array, use square brackets instead of curly braces",
1959 vec![(lo, "[".to_owned()), (hi, "]".to_owned())],
1960 Applicability::MaybeIncorrect,
1964 self.restore_snapshot(snapshot);
1965 Some(self.mk_expr_err(arr.span))
1974 fn suggest_missing_semicolon_before_array(
1977 open_delim_span: Span,
1978 ) -> PResult<'a, ()> {
1979 if self.token.kind == token::Comma {
1980 let mut snapshot = self.create_snapshot_for_diagnostic();
1982 match snapshot.parse_seq_to_before_end(
1983 &token::CloseDelim(Delimiter::Bracket),
1984 SeqSep::trailing_allowed(token::Comma),
1988 // When the close delim is `)`, `token.kind` is expected to be `token::CloseDelim(Delimiter::Parenthesis)`,
1989 // but the actual `token.kind` is `token::CloseDelim(Delimiter::Bracket)`.
1990 // This is because the `token.kind` of the close delim is treated as the same as
1991 // that of the open delim in `TokenTreesReader::parse_token_tree`, even if the delimiters of them are different.
1992 // Therefore, `token.kind` should not be compared here.
1994 .span_to_snippet(snapshot.token.span)
1995 .map_or(false, |snippet| snippet == "]") =>
1997 return Err(MissingSemicolonBeforeArray {
1998 open_delim: open_delim_span,
1999 semicolon: prev_span.shrink_to_hi(),
2000 }.into_diagnostic(&self.sess.span_diagnostic));
2003 Err(err) => err.cancel(),
2009 /// Parses a block or unsafe block.
2010 pub(super) fn parse_block_expr(
2012 opt_label: Option<Label>,
2014 blk_mode: BlockCheckMode,
2015 ) -> PResult<'a, P<Expr>> {
2016 if self.is_array_like_block() {
2017 if let Some(arr) = self.maybe_suggest_brackets_instead_of_braces(lo) {
2022 if self.token.is_whole_block() {
2023 self.sess.emit_err(InvalidBlockMacroSegment {
2024 span: self.token.span,
2025 context: lo.to(self.token.span),
2029 let (attrs, blk) = self.parse_block_common(lo, blk_mode)?;
2030 Ok(self.mk_expr_with_attrs(blk.span, ExprKind::Block(blk, opt_label), attrs))
2033 /// Parse a block which takes no attributes and has no label
2034 fn parse_simple_block(&mut self) -> PResult<'a, P<Expr>> {
2035 let blk = self.parse_block()?;
2036 Ok(self.mk_expr(blk.span, ExprKind::Block(blk, None)))
2039 /// Parses a closure expression (e.g., `move |args| expr`).
2040 fn parse_closure_expr(&mut self) -> PResult<'a, P<Expr>> {
2041 let lo = self.token.span;
2043 let binder = if self.check_keyword(kw::For) {
2044 let lo = self.token.span;
2045 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
2046 let span = lo.to(self.prev_token.span);
2048 self.sess.gated_spans.gate(sym::closure_lifetime_binder, span);
2050 ClosureBinder::For { span, generic_params: P::from_vec(lifetime_defs) }
2052 ClosureBinder::NotPresent
2056 if self.eat_keyword(kw::Static) { Movability::Static } else { Movability::Movable };
2058 let asyncness = if self.token.uninterpolated_span().rust_2018() {
2059 self.parse_asyncness()
2064 let capture_clause = self.parse_capture_clause()?;
2065 let decl = self.parse_fn_block_decl()?;
2066 let decl_hi = self.prev_token.span;
2067 let mut body = match decl.output {
2068 FnRetTy::Default(_) => {
2069 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
2070 self.parse_expr_res(restrictions, None)?
2073 // If an explicit return type is given, require a block to appear (RFC 968).
2074 let body_lo = self.token.span;
2075 self.parse_block_expr(None, body_lo, BlockCheckMode::Default)?
2079 if let Async::Yes { span, .. } = asyncness {
2080 // Feature-gate `async ||` closures.
2081 self.sess.gated_spans.gate(sym::async_closure, span);
2084 if self.token.kind == TokenKind::Semi
2085 && matches!(self.token_cursor.frame.delim_sp, Some((Delimiter::Parenthesis, _)))
2087 // It is likely that the closure body is a block but where the
2088 // braces have been removed. We will recover and eat the next
2089 // statements later in the parsing process.
2090 body = self.mk_expr_err(body.span);
2093 let body_span = body.span;
2095 let closure = self.mk_expr(
2108 // Disable recovery for closure body
2110 ClosureSpans { whole_closure: closure.span, closing_pipe: decl_hi, body: body_span };
2111 self.current_closure = Some(spans);
2116 /// Parses an optional `move` prefix to a closure-like construct.
2117 fn parse_capture_clause(&mut self) -> PResult<'a, CaptureBy> {
2118 if self.eat_keyword(kw::Move) {
2119 // Check for `move async` and recover
2120 if self.check_keyword(kw::Async) {
2121 let move_async_span = self.token.span.with_lo(self.prev_token.span.data().lo);
2122 Err(self.incorrect_move_async_order_found(move_async_span))
2124 Ok(CaptureBy::Value)
2131 /// Parses the `|arg, arg|` header of a closure.
2132 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
2133 let inputs = if self.eat(&token::OrOr) {
2136 self.expect(&token::BinOp(token::Or))?;
2138 .parse_seq_to_before_tokens(
2139 &[&token::BinOp(token::Or), &token::OrOr],
2140 SeqSep::trailing_allowed(token::Comma),
2141 TokenExpectType::NoExpect,
2142 |p| p.parse_fn_block_param(),
2149 self.parse_ret_ty(AllowPlus::Yes, RecoverQPath::Yes, RecoverReturnSign::Yes)?;
2151 Ok(P(FnDecl { inputs, output }))
2154 /// Parses a parameter in a closure header (e.g., `|arg, arg|`).
2155 fn parse_fn_block_param(&mut self) -> PResult<'a, Param> {
2156 let lo = self.token.span;
2157 let attrs = self.parse_outer_attributes()?;
2158 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
2159 let pat = this.parse_pat_no_top_alt(PARAM_EXPECTED)?;
2160 let ty = if this.eat(&token::Colon) {
2163 this.mk_ty(this.prev_token.span, TyKind::Infer)
2171 span: lo.to(this.prev_token.span),
2173 is_placeholder: false,
2175 TrailingToken::MaybeComma,
2180 /// Parses an `if` expression (`if` token already eaten).
2181 fn parse_if_expr(&mut self) -> PResult<'a, P<Expr>> {
2182 let lo = self.prev_token.span;
2183 let cond = self.parse_cond_expr()?;
2184 self.parse_if_after_cond(lo, cond)
2187 fn parse_if_after_cond(&mut self, lo: Span, mut cond: P<Expr>) -> PResult<'a, P<Expr>> {
2188 let cond_span = cond.span;
2189 // Tries to interpret `cond` as either a missing expression if it's a block,
2190 // or as an unfinished expression if it's a binop and the RHS is a block.
2191 // We could probably add more recoveries here too...
2192 let mut recover_block_from_condition = |this: &mut Self| {
2193 let block = match &mut cond.kind {
2194 ExprKind::Binary(Spanned { span: binop_span, .. }, _, right)
2195 if let ExprKind::Block(_, None) = right.kind => {
2196 self.sess.emit_err(IfExpressionMissingThenBlock {
2198 sub: IfExpressionMissingThenBlockSub::UnfinishedCondition(
2199 cond_span.shrink_to_lo().to(*binop_span)
2202 std::mem::replace(right, this.mk_expr_err(binop_span.shrink_to_hi()))
2204 ExprKind::Block(_, None) => {
2205 self.sess.emit_err(IfExpressionMissingCondition {
2206 if_span: self.sess.source_map().next_point(lo),
2207 block_span: self.sess.source_map().start_point(cond_span),
2209 std::mem::replace(&mut cond, this.mk_expr_err(cond_span.shrink_to_hi()))
2215 if let ExprKind::Block(block, _) = &block.kind {
2222 let thn = if self.token.is_keyword(kw::Else) {
2223 if let Some(block) = recover_block_from_condition(self) {
2226 self.sess.emit_err(IfExpressionMissingThenBlock {
2228 sub: IfExpressionMissingThenBlockSub::AddThenBlock(cond_span.shrink_to_hi()),
2230 self.mk_block_err(cond_span.shrink_to_hi())
2233 let attrs = self.parse_outer_attributes()?.take_for_recovery(); // For recovery.
2234 let block = if self.check(&token::OpenDelim(Delimiter::Brace)) {
2237 if let Some(block) = recover_block_from_condition(self) {
2240 // Parse block, which will always fail, but we can add a nice note to the error
2241 self.parse_block().map_err(|mut err| {
2244 "the `if` expression is missing a block after this condition",
2250 self.error_on_if_block_attrs(lo, false, block.span, &attrs);
2253 let els = if self.eat_keyword(kw::Else) { Some(self.parse_else_expr()?) } else { None };
2254 Ok(self.mk_expr(lo.to(self.prev_token.span), ExprKind::If(cond, thn, els)))
2257 /// Parses the condition of a `if` or `while` expression.
2258 fn parse_cond_expr(&mut self) -> PResult<'a, P<Expr>> {
2260 self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL | Restrictions::ALLOW_LET, None)?;
2262 if let ExprKind::Let(..) = cond.kind {
2263 // Remove the last feature gating of a `let` expression since it's stable.
2264 self.sess.gated_spans.ungate_last(sym::let_chains, cond.span);
2270 /// Parses a `let $pat = $expr` pseudo-expression.
2271 fn parse_let_expr(&mut self) -> PResult<'a, P<Expr>> {
2272 // This is a *approximate* heuristic that detects if `let` chains are
2273 // being parsed in the right position. It's approximate because it
2274 // doesn't deny all invalid `let` expressions, just completely wrong usages.
2275 let not_in_chain = !matches!(
2276 self.prev_token.kind,
2277 TokenKind::AndAnd | TokenKind::Ident(kw::If, _) | TokenKind::Ident(kw::While, _)
2279 if !self.restrictions.contains(Restrictions::ALLOW_LET) || not_in_chain {
2280 self.sess.emit_err(ExpectedExpressionFoundLet { span: self.token.span });
2283 self.bump(); // Eat `let` token
2284 let lo = self.prev_token.span;
2285 let pat = self.parse_pat_allow_top_alt(
2289 CommaRecoveryMode::LikelyTuple,
2291 self.expect(&token::Eq)?;
2292 let expr = self.with_res(self.restrictions | Restrictions::NO_STRUCT_LITERAL, |this| {
2293 this.parse_assoc_expr_with(1 + prec_let_scrutinee_needs_par(), None.into())
2295 let span = lo.to(expr.span);
2296 self.sess.gated_spans.gate(sym::let_chains, span);
2297 Ok(self.mk_expr(span, ExprKind::Let(pat, expr, span)))
2300 /// Parses an `else { ... }` expression (`else` token already eaten).
2301 fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
2302 let else_span = self.prev_token.span; // `else`
2303 let attrs = self.parse_outer_attributes()?.take_for_recovery(); // For recovery.
2304 let expr = if self.eat_keyword(kw::If) {
2305 self.parse_if_expr()?
2306 } else if self.check(&TokenKind::OpenDelim(Delimiter::Brace)) {
2307 self.parse_simple_block()?
2309 let snapshot = self.create_snapshot_for_diagnostic();
2310 let first_tok = super::token_descr(&self.token);
2311 let first_tok_span = self.token.span;
2312 match self.parse_expr() {
2314 // If it's not a free-standing expression, and is followed by a block,
2315 // then it's very likely the condition to an `else if`.
2316 if self.check(&TokenKind::OpenDelim(Delimiter::Brace))
2317 && classify::expr_requires_semi_to_be_stmt(&cond) =>
2319 self.sess.emit_err(ExpectedElseBlock {
2323 condition_start: cond.span.shrink_to_lo(),
2325 self.parse_if_after_cond(cond.span.shrink_to_lo(), cond)?
2329 self.restore_snapshot(snapshot);
2330 self.parse_simple_block()?
2333 self.restore_snapshot(snapshot);
2334 self.parse_simple_block()?
2338 self.error_on_if_block_attrs(else_span, true, expr.span, &attrs);
2342 fn error_on_if_block_attrs(
2347 attrs: &[ast::Attribute],
2349 let (attributes, last) = match attrs {
2351 [x0 @ xn] | [x0, .., xn] => (x0.span.to(xn.span), xn.span),
2353 let ctx = if is_ctx_else { "else" } else { "if" };
2354 self.sess.emit_err(OuterAttributeNotAllowedOnIfElse {
2358 ctx: ctx.to_string(),
2363 /// Parses `for <src_pat> in <src_expr> <src_loop_block>` (`for` token already eaten).
2364 fn parse_for_expr(&mut self, opt_label: Option<Label>, lo: Span) -> PResult<'a, P<Expr>> {
2365 // Record whether we are about to parse `for (`.
2366 // This is used below for recovery in case of `for ( $stuff ) $block`
2367 // in which case we will suggest `for $stuff $block`.
2368 let begin_paren = match self.token.kind {
2369 token::OpenDelim(Delimiter::Parenthesis) => Some(self.token.span),
2373 let pat = self.parse_pat_allow_top_alt(
2377 CommaRecoveryMode::LikelyTuple,
2379 if !self.eat_keyword(kw::In) {
2380 self.error_missing_in_for_loop();
2382 self.check_for_for_in_in_typo(self.prev_token.span);
2383 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
2385 let pat = self.recover_parens_around_for_head(pat, begin_paren);
2387 let (attrs, loop_block) = self.parse_inner_attrs_and_block()?;
2389 let kind = ExprKind::ForLoop(pat, expr, loop_block, opt_label);
2390 Ok(self.mk_expr_with_attrs(lo.to(self.prev_token.span), kind, attrs))
2393 fn error_missing_in_for_loop(&mut self) {
2394 let (span, sub): (_, fn(_) -> _) = if self.token.is_ident_named(sym::of) {
2395 // Possibly using JS syntax (#75311).
2396 let span = self.token.span;
2398 (span, MissingInInForLoopSub::InNotOf)
2400 (self.prev_token.span.between(self.token.span), MissingInInForLoopSub::AddIn)
2403 self.sess.emit_err(MissingInInForLoop { span, sub: sub(span) });
2406 /// Parses a `while` or `while let` expression (`while` token already eaten).
2407 fn parse_while_expr(&mut self, opt_label: Option<Label>, lo: Span) -> PResult<'a, P<Expr>> {
2408 let cond = self.parse_cond_expr().map_err(|mut err| {
2409 err.span_label(lo, "while parsing the condition of this `while` expression");
2412 let (attrs, body) = self.parse_inner_attrs_and_block().map_err(|mut err| {
2413 err.span_label(lo, "while parsing the body of this `while` expression");
2414 err.span_label(cond.span, "this `while` condition successfully parsed");
2417 Ok(self.mk_expr_with_attrs(
2418 lo.to(self.prev_token.span),
2419 ExprKind::While(cond, body, opt_label),
2424 /// Parses `loop { ... }` (`loop` token already eaten).
2425 fn parse_loop_expr(&mut self, opt_label: Option<Label>, lo: Span) -> PResult<'a, P<Expr>> {
2426 let (attrs, body) = self.parse_inner_attrs_and_block()?;
2427 Ok(self.mk_expr_with_attrs(
2428 lo.to(self.prev_token.span),
2429 ExprKind::Loop(body, opt_label),
2434 pub(crate) fn eat_label(&mut self) -> Option<Label> {
2435 self.token.lifetime().map(|ident| {
2441 /// Parses a `match ... { ... }` expression (`match` token already eaten).
2442 fn parse_match_expr(&mut self) -> PResult<'a, P<Expr>> {
2443 let match_span = self.prev_token.span;
2444 let lo = self.prev_token.span;
2445 let scrutinee = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
2446 if let Err(mut e) = self.expect(&token::OpenDelim(Delimiter::Brace)) {
2447 if self.token == token::Semi {
2448 e.span_suggestion_short(
2450 "try removing this `match`",
2452 Applicability::MaybeIncorrect, // speculative
2455 if self.maybe_recover_unexpected_block_label() {
2462 let attrs = self.parse_inner_attributes()?;
2464 let mut arms: Vec<Arm> = Vec::new();
2465 while self.token != token::CloseDelim(Delimiter::Brace) {
2466 match self.parse_arm() {
2467 Ok(arm) => arms.push(arm),
2469 // Recover by skipping to the end of the block.
2471 self.recover_stmt();
2472 let span = lo.to(self.token.span);
2473 if self.token == token::CloseDelim(Delimiter::Brace) {
2476 return Ok(self.mk_expr_with_attrs(
2478 ExprKind::Match(scrutinee, arms),
2484 let hi = self.token.span;
2486 Ok(self.mk_expr_with_attrs(lo.to(hi), ExprKind::Match(scrutinee, arms), attrs))
2489 /// Attempt to recover from match arm body with statements and no surrounding braces.
2490 fn parse_arm_body_missing_braces(
2492 first_expr: &P<Expr>,
2494 ) -> Option<P<Expr>> {
2495 if self.token.kind != token::Semi {
2498 let start_snapshot = self.create_snapshot_for_diagnostic();
2499 let semi_sp = self.token.span;
2502 vec![self.mk_stmt(first_expr.span, ast::StmtKind::Expr(first_expr.clone()))];
2503 let err = |this: &mut Parser<'_>, stmts: Vec<ast::Stmt>| {
2504 let span = stmts[0].span.to(stmts[stmts.len() - 1].span);
2505 let mut err = this.struct_span_err(span, "`match` arm body without braces");
2506 let (these, s, are) =
2507 if stmts.len() > 1 { ("these", "s", "are") } else { ("this", "", "is") };
2511 "{these} statement{s} {are} not surrounded by a body",
2517 err.span_label(arrow_span, "while parsing the `match` arm starting here");
2518 if stmts.len() > 1 {
2519 err.multipart_suggestion(
2520 &format!("surround the statement{s} with a body"),
2522 (span.shrink_to_lo(), "{ ".to_string()),
2523 (span.shrink_to_hi(), " }".to_string()),
2525 Applicability::MachineApplicable,
2528 err.span_suggestion(
2530 "use a comma to end a `match` arm expression",
2532 Applicability::MachineApplicable,
2536 this.mk_expr_err(span)
2538 // We might have either a `,` -> `;` typo, or a block without braces. We need
2539 // a more subtle parsing strategy.
2541 if self.token.kind == token::CloseDelim(Delimiter::Brace) {
2542 // We have reached the closing brace of the `match` expression.
2543 return Some(err(self, stmts));
2545 if self.token.kind == token::Comma {
2546 self.restore_snapshot(start_snapshot);
2549 let pre_pat_snapshot = self.create_snapshot_for_diagnostic();
2550 match self.parse_pat_no_top_alt(None) {
2552 if self.token.kind == token::FatArrow {
2554 self.restore_snapshot(pre_pat_snapshot);
2555 return Some(err(self, stmts));
2563 self.restore_snapshot(pre_pat_snapshot);
2564 match self.parse_stmt_without_recovery(true, ForceCollect::No) {
2565 // Consume statements for as long as possible.
2570 self.restore_snapshot(start_snapshot);
2573 // We couldn't parse either yet another statement missing it's
2574 // enclosing block nor the next arm's pattern or closing brace.
2577 self.restore_snapshot(start_snapshot);
2585 pub(super) fn parse_arm(&mut self) -> PResult<'a, Arm> {
2586 // Used to check the `let_chains` and `if_let_guard` features mostly by scanning
2588 fn check_let_expr(expr: &Expr) -> (bool, bool) {
2590 ExprKind::Binary(BinOp { node: BinOpKind::And, .. }, ref lhs, ref rhs) => {
2591 let lhs_rslt = check_let_expr(lhs);
2592 let rhs_rslt = check_let_expr(rhs);
2593 (lhs_rslt.0 || rhs_rslt.0, false)
2595 ExprKind::Let(..) => (true, true),
2599 let attrs = self.parse_outer_attributes()?;
2600 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
2601 let lo = this.token.span;
2602 let pat = this.parse_pat_allow_top_alt(
2606 CommaRecoveryMode::EitherTupleOrPipe,
2608 let guard = if this.eat_keyword(kw::If) {
2609 let if_span = this.prev_token.span;
2610 let cond = this.parse_expr_res(Restrictions::ALLOW_LET, None)?;
2611 let (has_let_expr, does_not_have_bin_op) = check_let_expr(&cond);
2613 if does_not_have_bin_op {
2614 // Remove the last feature gating of a `let` expression since it's stable.
2615 this.sess.gated_spans.ungate_last(sym::let_chains, cond.span);
2617 let span = if_span.to(cond.span);
2618 this.sess.gated_spans.gate(sym::if_let_guard, span);
2624 let arrow_span = this.token.span;
2625 if let Err(mut err) = this.expect(&token::FatArrow) {
2626 // We might have a `=>` -> `=` or `->` typo (issue #89396).
2627 if TokenKind::FatArrow
2629 .map_or(false, |similar_tokens| similar_tokens.contains(&this.token.kind))
2631 err.span_suggestion(
2633 "try using a fat arrow here",
2635 Applicability::MaybeIncorrect,
2643 let arm_start_span = this.token.span;
2645 let expr = this.parse_expr_res(Restrictions::STMT_EXPR, None).map_err(|mut err| {
2646 err.span_label(arrow_span, "while parsing the `match` arm starting here");
2650 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
2651 && this.token != token::CloseDelim(Delimiter::Brace);
2653 let hi = this.prev_token.span;
2656 let sm = this.sess.source_map();
2657 if let Some(body) = this.parse_arm_body_missing_braces(&expr, arrow_span) {
2658 let span = body.span;
2667 is_placeholder: false,
2669 TrailingToken::None,
2672 this.expect_one_of(&[token::Comma], &[token::CloseDelim(Delimiter::Brace)])
2673 .or_else(|mut err| {
2674 if this.token == token::FatArrow {
2675 if let Ok(expr_lines) = sm.span_to_lines(expr.span)
2676 && let Ok(arm_start_lines) = sm.span_to_lines(arm_start_span)
2677 && arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col
2678 && expr_lines.lines.len() == 2
2680 // We check whether there's any trailing code in the parse span,
2681 // if there isn't, we very likely have the following:
2684 // | -- - missing comma
2688 // | - ^^ self.token.span
2690 // | parsed until here as `"y" & X`
2691 err.span_suggestion_short(
2692 arm_start_span.shrink_to_hi(),
2693 "missing a comma here to end this `match` arm",
2695 Applicability::MachineApplicable,
2700 // FIXME(compiler-errors): We could also recover `; PAT =>` here
2702 // Try to parse a following `PAT =>`, if successful
2703 // then we should recover.
2704 let mut snapshot = this.create_snapshot_for_diagnostic();
2705 let pattern_follows = snapshot
2706 .parse_pat_allow_top_alt(
2710 CommaRecoveryMode::EitherTupleOrPipe,
2712 .map_err(|err| err.cancel())
2714 if pattern_follows && snapshot.check(&TokenKind::FatArrow) {
2716 this.sess.emit_err(MissingCommaAfterMatchArm {
2717 span: hi.shrink_to_hi(),
2722 err.span_label(arrow_span, "while parsing the `match` arm starting here");
2726 this.eat(&token::Comma);
2737 is_placeholder: false,
2739 TrailingToken::None,
2744 /// Parses a `try {...}` expression (`try` token already eaten).
2745 fn parse_try_block(&mut self, span_lo: Span) -> PResult<'a, P<Expr>> {
2746 let (attrs, body) = self.parse_inner_attrs_and_block()?;
2747 if self.eat_keyword(kw::Catch) {
2748 Err(CatchAfterTry { span: self.prev_token.span }
2749 .into_diagnostic(&self.sess.span_diagnostic))
2751 let span = span_lo.to(body.span);
2752 self.sess.gated_spans.gate(sym::try_blocks, span);
2753 Ok(self.mk_expr_with_attrs(span, ExprKind::TryBlock(body), attrs))
2757 fn is_do_catch_block(&self) -> bool {
2758 self.token.is_keyword(kw::Do)
2759 && self.is_keyword_ahead(1, &[kw::Catch])
2760 && self.look_ahead(2, |t| *t == token::OpenDelim(Delimiter::Brace))
2761 && !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
2764 fn is_do_yeet(&self) -> bool {
2765 self.token.is_keyword(kw::Do) && self.is_keyword_ahead(1, &[kw::Yeet])
2768 fn is_try_block(&self) -> bool {
2769 self.token.is_keyword(kw::Try)
2770 && self.look_ahead(1, |t| *t == token::OpenDelim(Delimiter::Brace))
2771 && self.token.uninterpolated_span().rust_2018()
2774 /// Parses an `async move? {...}` expression.
2775 fn parse_async_block(&mut self) -> PResult<'a, P<Expr>> {
2776 let lo = self.token.span;
2777 self.expect_keyword(kw::Async)?;
2778 let capture_clause = self.parse_capture_clause()?;
2779 let (attrs, body) = self.parse_inner_attrs_and_block()?;
2780 let kind = ExprKind::Async(capture_clause, DUMMY_NODE_ID, body);
2781 Ok(self.mk_expr_with_attrs(lo.to(self.prev_token.span), kind, attrs))
2784 fn is_async_block(&self) -> bool {
2785 self.token.is_keyword(kw::Async)
2788 self.is_keyword_ahead(1, &[kw::Move])
2789 && self.look_ahead(2, |t| *t == token::OpenDelim(Delimiter::Brace))
2792 self.look_ahead(1, |t| *t == token::OpenDelim(Delimiter::Brace))
2796 fn is_certainly_not_a_block(&self) -> bool {
2797 self.look_ahead(1, |t| t.is_ident())
2799 // `{ ident, ` cannot start a block.
2800 self.look_ahead(2, |t| t == &token::Comma)
2801 || self.look_ahead(2, |t| t == &token::Colon)
2803 // `{ ident: token, ` cannot start a block.
2804 self.look_ahead(4, |t| t == &token::Comma) ||
2805 // `{ ident: ` cannot start a block unless it's a type ascription `ident: Type`.
2806 self.look_ahead(3, |t| !t.can_begin_type())
2811 fn maybe_parse_struct_expr(
2813 qself: Option<&ast::QSelf>,
2815 ) -> Option<PResult<'a, P<Expr>>> {
2816 let struct_allowed = !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
2817 if struct_allowed || self.is_certainly_not_a_block() {
2818 if let Err(err) = self.expect(&token::OpenDelim(Delimiter::Brace)) {
2819 return Some(Err(err));
2821 let expr = self.parse_struct_expr(qself.cloned(), path.clone(), true);
2822 if let (Ok(expr), false) = (&expr, struct_allowed) {
2823 // This is a struct literal, but we don't can't accept them here.
2824 self.error_struct_lit_not_allowed_here(path.span, expr.span);
2831 fn error_struct_lit_not_allowed_here(&self, lo: Span, sp: Span) {
2832 self.struct_span_err(sp, "struct literals are not allowed here")
2833 .multipart_suggestion(
2834 "surround the struct literal with parentheses",
2835 vec![(lo.shrink_to_lo(), "(".to_string()), (sp.shrink_to_hi(), ")".to_string())],
2836 Applicability::MachineApplicable,
2841 pub(super) fn parse_struct_fields(
2845 close_delim: Delimiter,
2846 ) -> PResult<'a, (Vec<ExprField>, ast::StructRest, bool)> {
2847 let mut fields = Vec::new();
2848 let mut base = ast::StructRest::None;
2849 let mut recover_async = false;
2851 let mut async_block_err = |e: &mut Diagnostic, span: Span| {
2852 recover_async = true;
2853 e.span_label(span, "`async` blocks are only allowed in Rust 2018 or later");
2854 e.help_use_latest_edition();
2857 while self.token != token::CloseDelim(close_delim) {
2858 if self.eat(&token::DotDot) {
2859 let exp_span = self.prev_token.span;
2860 // We permit `.. }` on the left-hand side of a destructuring assignment.
2861 if self.check(&token::CloseDelim(close_delim)) {
2862 base = ast::StructRest::Rest(self.prev_token.span.shrink_to_hi());
2865 match self.parse_expr() {
2866 Ok(e) => base = ast::StructRest::Base(e),
2867 Err(mut e) if recover => {
2869 self.recover_stmt();
2871 Err(e) => return Err(e),
2873 self.recover_struct_comma_after_dotdot(exp_span);
2877 let recovery_field = self.find_struct_error_after_field_looking_code();
2878 let parsed_field = match self.parse_expr_field() {
2881 if pth == kw::Async {
2882 async_block_err(&mut e, pth.span);
2884 e.span_label(pth.span, "while parsing this struct");
2888 // If the next token is a comma, then try to parse
2889 // what comes next as additional fields, rather than
2890 // bailing out until next `}`.
2891 if self.token != token::Comma {
2892 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2893 if self.token != token::Comma {
2901 let is_shorthand = parsed_field.as_ref().map_or(false, |f| f.is_shorthand);
2902 // A shorthand field can be turned into a full field with `:`.
2903 // We should point this out.
2904 self.check_or_expected(!is_shorthand, TokenType::Token(token::Colon));
2906 match self.expect_one_of(&[token::Comma], &[token::CloseDelim(close_delim)]) {
2908 if let Some(f) = parsed_field.or(recovery_field) {
2909 // Only include the field if there's no parse error for the field name.
2914 if pth == kw::Async {
2915 async_block_err(&mut e, pth.span);
2917 e.span_label(pth.span, "while parsing this struct");
2918 if let Some(f) = recovery_field {
2921 self.prev_token.span.shrink_to_hi(),
2922 "try adding a comma",
2924 Applicability::MachineApplicable,
2926 } else if is_shorthand
2927 && (AssocOp::from_token(&self.token).is_some()
2928 || matches!(&self.token.kind, token::OpenDelim(_))
2929 || self.token.kind == token::Dot)
2931 // Looks like they tried to write a shorthand, complex expression.
2932 let ident = parsed_field.expect("is_shorthand implies Some").ident;
2934 ident.span.shrink_to_lo(),
2935 "try naming a field",
2936 &format!("{ident}: "),
2937 Applicability::HasPlaceholders,
2945 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2946 self.eat(&token::Comma);
2950 Ok((fields, base, recover_async))
2953 /// Precondition: already parsed the '{'.
2954 pub(super) fn parse_struct_expr(
2956 qself: Option<ast::QSelf>,
2959 ) -> PResult<'a, P<Expr>> {
2961 let (fields, base, recover_async) =
2962 self.parse_struct_fields(pth.clone(), recover, Delimiter::Brace)?;
2963 let span = lo.to(self.token.span);
2964 self.expect(&token::CloseDelim(Delimiter::Brace))?;
2965 let expr = if recover_async {
2968 ExprKind::Struct(P(ast::StructExpr { qself, path: pth, fields, rest: base }))
2970 Ok(self.mk_expr(span, expr))
2973 /// Use in case of error after field-looking code: `S { foo: () with a }`.
2974 fn find_struct_error_after_field_looking_code(&self) -> Option<ExprField> {
2975 match self.token.ident() {
2976 Some((ident, is_raw))
2977 if (is_raw || !ident.is_reserved())
2978 && self.look_ahead(1, |t| *t == token::Colon) =>
2980 Some(ast::ExprField {
2982 span: self.token.span,
2983 expr: self.mk_expr_err(self.token.span),
2984 is_shorthand: false,
2985 attrs: AttrVec::new(),
2987 is_placeholder: false,
2994 fn recover_struct_comma_after_dotdot(&mut self, span: Span) {
2995 if self.token != token::Comma {
2998 self.sess.emit_err(CommaAfterBaseStruct {
2999 span: span.to(self.prev_token.span),
3000 comma: self.token.span,
3002 self.recover_stmt();
3005 /// Parses `ident (COLON expr)?`.
3006 fn parse_expr_field(&mut self) -> PResult<'a, ExprField> {
3007 let attrs = self.parse_outer_attributes()?;
3008 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
3009 let lo = this.token.span;
3011 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3012 let is_shorthand = !this.look_ahead(1, |t| t == &token::Colon || t == &token::Eq);
3013 let (ident, expr) = if is_shorthand {
3014 // Mimic `x: x` for the `x` field shorthand.
3015 let ident = this.parse_ident_common(false)?;
3016 let path = ast::Path::from_ident(ident);
3017 (ident, this.mk_expr(ident.span, ExprKind::Path(None, path)))
3019 let ident = this.parse_field_name()?;
3020 this.error_on_eq_field_init(ident);
3022 (ident, this.parse_expr()?)
3028 span: lo.to(expr.span),
3033 is_placeholder: false,
3035 TrailingToken::MaybeComma,
3040 /// Check for `=`. This means the source incorrectly attempts to
3041 /// initialize a field with an eq rather than a colon.
3042 fn error_on_eq_field_init(&self, field_name: Ident) {
3043 if self.token != token::Eq {
3047 self.sess.emit_err(EqFieldInit {
3048 span: self.token.span,
3049 eq: field_name.span.shrink_to_hi().to(self.token.span),
3053 fn err_dotdotdot_syntax(&self, span: Span) {
3054 self.sess.emit_err(DotDotDot { span });
3057 fn err_larrow_operator(&self, span: Span) {
3058 self.sess.emit_err(LeftArrowOperator { span });
3061 fn mk_assign_op(&self, binop: BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ExprKind {
3062 ExprKind::AssignOp(binop, lhs, rhs)
3067 start: Option<P<Expr>>,
3068 end: Option<P<Expr>>,
3069 limits: RangeLimits,
3071 if end.is_none() && limits == RangeLimits::Closed {
3072 self.inclusive_range_with_incorrect_end(self.prev_token.span);
3075 ExprKind::Range(start, end, limits)
3079 fn mk_unary(&self, unop: UnOp, expr: P<Expr>) -> ExprKind {
3080 ExprKind::Unary(unop, expr)
3083 fn mk_binary(&self, binop: BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ExprKind {
3084 ExprKind::Binary(binop, lhs, rhs)
3087 fn mk_index(&self, expr: P<Expr>, idx: P<Expr>) -> ExprKind {
3088 ExprKind::Index(expr, idx)
3091 fn mk_call(&self, f: P<Expr>, args: Vec<P<Expr>>) -> ExprKind {
3092 ExprKind::Call(f, args)
3095 fn mk_await_expr(&mut self, self_arg: P<Expr>, lo: Span) -> P<Expr> {
3096 let span = lo.to(self.prev_token.span);
3097 let await_expr = self.mk_expr(span, ExprKind::Await(self_arg));
3098 self.recover_from_await_method_call();
3102 pub(crate) fn mk_expr_with_attrs(&self, span: Span, kind: ExprKind, attrs: AttrVec) -> P<Expr> {
3103 P(Expr { kind, span, attrs, id: DUMMY_NODE_ID, tokens: None })
3106 pub(crate) fn mk_expr(&self, span: Span, kind: ExprKind) -> P<Expr> {
3107 P(Expr { kind, span, attrs: AttrVec::new(), id: DUMMY_NODE_ID, tokens: None })
3110 pub(super) fn mk_expr_err(&self, span: Span) -> P<Expr> {
3111 self.mk_expr(span, ExprKind::Err)
3114 /// Create expression span ensuring the span of the parent node
3115 /// is larger than the span of lhs and rhs, including the attributes.
3116 fn mk_expr_sp(&self, lhs: &P<Expr>, lhs_span: Span, rhs_span: Span) -> Span {
3119 .find(|a| a.style == AttrStyle::Outer)
3120 .map_or(lhs_span, |a| a.span)
3124 fn collect_tokens_for_expr(
3127 f: impl FnOnce(&mut Self, ast::AttrVec) -> PResult<'a, P<Expr>>,
3128 ) -> PResult<'a, P<Expr>> {
3129 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
3130 let res = f(this, attrs)?;
3131 let trailing = if this.restrictions.contains(Restrictions::STMT_EXPR)
3132 && this.token.kind == token::Semi
3136 // FIXME - pass this through from the place where we know
3137 // we need a comma, rather than assuming that `#[attr] expr,`
3138 // always captures a trailing comma
3139 TrailingToken::MaybeComma