1 use super::diagnostics::SnapshotParser;
2 use super::pat::{CommaRecoveryMode, RecoverColon, RecoverComma, PARAM_EXPECTED};
3 use super::ty::{AllowPlus, RecoverQPath, RecoverReturnSign};
5 AttrWrapper, BlockMode, ClosureSpans, ForceCollect, Parser, PathStyle, Restrictions,
6 SemiColonMode, SeqSep, TokenExpectType, TokenType, TrailingToken,
9 ArrayBracketsInsteadOfSpaces, ArrayBracketsInsteadOfSpacesSugg, AsyncMoveOrderIncorrect,
10 BinaryFloatLiteralNotSupported, BracesForStructLiteral, CatchAfterTry, CommaAfterBaseStruct,
11 ComparisonInterpretedAsGeneric, ComparisonOrShiftInterpretedAsGenericSugg,
12 DoCatchSyntaxRemoved, DotDotDot, EqFieldInit, ExpectedElseBlock, ExpectedExpressionFoundLet,
13 FieldExpressionWithGeneric, FloatLiteralRequiresIntegerPart, FoundExprWouldBeStmt,
14 HexadecimalFloatLiteralNotSupported, IfExpressionMissingCondition,
15 IfExpressionMissingThenBlock, IfExpressionMissingThenBlockSub, IntLiteralTooLarge,
16 InvalidBlockMacroSegment, InvalidComparisonOperator, InvalidComparisonOperatorSub,
17 InvalidFloatLiteralSuffix, InvalidFloatLiteralWidth, InvalidIntLiteralWidth,
18 InvalidInterpolatedExpression, InvalidLiteralSuffix, InvalidLiteralSuffixOnTupleIndex,
19 InvalidLogicalOperator, InvalidLogicalOperatorSub, InvalidNumLiteralBasePrefix,
20 InvalidNumLiteralSuffix, LabeledLoopInBreak, LeadingPlusNotSupported, LeftArrowOperator,
21 LifetimeInBorrowExpression, MacroInvocationWithQualifiedPath, MalformedLoopLabel,
22 MatchArmBodyWithoutBraces, MatchArmBodyWithoutBracesSugg, MissingCommaAfterMatchArm,
23 MissingInInForLoop, MissingInInForLoopSub, MissingSemicolonBeforeArray, NoFieldsForFnCall,
24 NotAsNegationOperator, NotAsNegationOperatorSub, OctalFloatLiteralNotSupported,
25 OuterAttributeNotAllowedOnIfElse, ParenthesesWithStructFields,
26 RequireColonAfterLabeledExpression, ShiftInterpretedAsGeneric, StructLiteralNotAllowedHere,
27 StructLiteralNotAllowedHereSugg, TildeAsUnaryOperator, UnexpectedTokenAfterLabel,
28 UnexpectedTokenAfterLabelSugg, WrapExpressionInParentheses,
30 use crate::maybe_recover_from_interpolated_ty_qpath;
33 use rustc_ast::ptr::P;
34 use rustc_ast::token::{self, Delimiter, Token, TokenKind};
35 use rustc_ast::tokenstream::Spacing;
36 use rustc_ast::util::classify;
37 use rustc_ast::util::literal::LitError;
38 use rustc_ast::util::parser::{prec_let_scrutinee_needs_par, AssocOp, Fixity};
39 use rustc_ast::visit::Visitor;
40 use rustc_ast::{self as ast, AttrStyle, AttrVec, CaptureBy, ExprField, Lit, UnOp, DUMMY_NODE_ID};
41 use rustc_ast::{AnonConst, BinOp, BinOpKind, FnDecl, FnRetTy, MacCall, Param, Ty, TyKind};
42 use rustc_ast::{Arm, Async, BlockCheckMode, Expr, ExprKind, Label, Movability, RangeLimits};
43 use rustc_ast::{ClosureBinder, StmtKind};
44 use rustc_ast_pretty::pprust;
45 use rustc_errors::IntoDiagnostic;
46 use rustc_errors::{Applicability, Diagnostic, PResult};
47 use rustc_session::errors::ExprParenthesesNeeded;
48 use rustc_session::lint::builtin::BREAK_WITH_LABEL_AND_LOOP;
49 use rustc_session::lint::BuiltinLintDiagnostics;
50 use rustc_span::source_map::{self, Span, Spanned};
51 use rustc_span::symbol::{kw, sym, Ident, Symbol};
52 use rustc_span::{BytePos, Pos};
54 /// Possibly accepts an `token::Interpolated` expression (a pre-parsed expression
55 /// dropped into the token stream, which happens while parsing the result of
56 /// macro expansion). Placement of these is not as complex as I feared it would
57 /// be. The important thing is to make sure that lookahead doesn't balk at
58 /// `token::Interpolated` tokens.
59 macro_rules! maybe_whole_expr {
61 if let token::Interpolated(nt) = &$p.token.kind {
63 token::NtExpr(e) | token::NtLiteral(e) => {
68 token::NtPath(path) => {
69 let path = (**path).clone();
71 return Ok($p.mk_expr($p.prev_token.span, ExprKind::Path(None, path)));
73 token::NtBlock(block) => {
74 let block = block.clone();
76 return Ok($p.mk_expr($p.prev_token.span, ExprKind::Block(block, None)));
85 pub(super) enum LhsExpr {
87 AttributesParsed(AttrWrapper),
88 AlreadyParsed(P<Expr>),
91 impl From<Option<AttrWrapper>> for LhsExpr {
92 /// Converts `Some(attrs)` into `LhsExpr::AttributesParsed(attrs)`
93 /// and `None` into `LhsExpr::NotYetParsed`.
95 /// This conversion does not allocate.
96 fn from(o: Option<AttrWrapper>) -> Self {
97 if let Some(attrs) = o { LhsExpr::AttributesParsed(attrs) } else { LhsExpr::NotYetParsed }
101 impl From<P<Expr>> for LhsExpr {
102 /// Converts the `expr: P<Expr>` into `LhsExpr::AlreadyParsed(expr)`.
104 /// This conversion does not allocate.
105 fn from(expr: P<Expr>) -> Self {
106 LhsExpr::AlreadyParsed(expr)
110 impl<'a> Parser<'a> {
111 /// Parses an expression.
113 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
114 self.current_closure.take();
116 self.parse_expr_res(Restrictions::empty(), None)
119 /// Parses an expression, forcing tokens to be collected
120 pub fn parse_expr_force_collect(&mut self) -> PResult<'a, P<Expr>> {
121 self.collect_tokens_no_attrs(|this| this.parse_expr())
124 pub fn parse_anon_const_expr(&mut self) -> PResult<'a, AnonConst> {
125 self.parse_expr().map(|value| AnonConst { id: DUMMY_NODE_ID, value })
128 fn parse_expr_catch_underscore(&mut self) -> PResult<'a, P<Expr>> {
129 match self.parse_expr() {
130 Ok(expr) => Ok(expr),
131 Err(mut err) => match self.token.ident() {
132 Some((Ident { name: kw::Underscore, .. }, false))
133 if self.look_ahead(1, |t| t == &token::Comma) =>
135 // Special-case handling of `foo(_, _, _)`
138 Ok(self.mk_expr(self.prev_token.span, ExprKind::Err))
145 /// Parses a sequence of expressions delimited by parentheses.
146 fn parse_paren_expr_seq(&mut self) -> PResult<'a, Vec<P<Expr>>> {
147 self.parse_paren_comma_seq(|p| p.parse_expr_catch_underscore()).map(|(r, _)| r)
150 /// Parses an expression, subject to the given restrictions.
152 pub(super) fn parse_expr_res(
155 already_parsed_attrs: Option<AttrWrapper>,
156 ) -> PResult<'a, P<Expr>> {
157 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
160 /// Parses an associative expression.
162 /// This parses an expression accounting for associativity and precedence of the operators in
167 already_parsed_attrs: Option<AttrWrapper>,
168 ) -> PResult<'a, P<Expr>> {
169 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
172 /// Parses an associative expression with operators of at least `min_prec` precedence.
173 pub(super) fn parse_assoc_expr_with(
177 ) -> PResult<'a, P<Expr>> {
178 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
181 let attrs = match lhs {
182 LhsExpr::AttributesParsed(attrs) => Some(attrs),
185 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token.kind) {
186 return self.parse_prefix_range_expr(attrs);
188 self.parse_prefix_expr(attrs)?
191 let last_type_ascription_set = self.last_type_ascription.is_some();
193 if !self.should_continue_as_assoc_expr(&lhs) {
194 self.last_type_ascription = None;
198 self.expected_tokens.push(TokenType::Operator);
199 while let Some(op) = self.check_assoc_op() {
200 // Adjust the span for interpolated LHS to point to the `$lhs` token
201 // and not to what it refers to.
202 let lhs_span = match self.prev_token.kind {
203 TokenKind::Interpolated(..) => self.prev_token.span,
207 let cur_op_span = self.token.span;
208 let restrictions = if op.node.is_assign_like() {
209 self.restrictions & Restrictions::NO_STRUCT_LITERAL
213 let prec = op.node.precedence();
217 // Check for deprecated `...` syntax
218 if self.token == token::DotDotDot && op.node == AssocOp::DotDotEq {
219 self.err_dotdotdot_syntax(self.token.span);
222 if self.token == token::LArrow {
223 self.err_larrow_operator(self.token.span);
227 if op.node.is_comparison() {
228 if let Some(expr) = self.check_no_chained_comparison(&lhs, &op)? {
233 // Look for JS' `===` and `!==` and recover
234 if (op.node == AssocOp::Equal || op.node == AssocOp::NotEqual)
235 && self.token.kind == token::Eq
236 && self.prev_token.span.hi() == self.token.span.lo()
238 let sp = op.span.to(self.token.span);
239 let sugg = match op.node {
240 AssocOp::Equal => "==",
241 AssocOp::NotEqual => "!=",
245 let invalid = format!("{}=", &sugg);
246 self.sess.emit_err(InvalidComparisonOperator {
248 invalid: invalid.clone(),
249 sub: InvalidComparisonOperatorSub::Correctable {
258 // Look for PHP's `<>` and recover
259 if op.node == AssocOp::Less
260 && self.token.kind == token::Gt
261 && self.prev_token.span.hi() == self.token.span.lo()
263 let sp = op.span.to(self.token.span);
264 self.sess.emit_err(InvalidComparisonOperator {
266 invalid: "<>".into(),
267 sub: InvalidComparisonOperatorSub::Correctable {
269 invalid: "<>".into(),
270 correct: "!=".into(),
276 // Look for C++'s `<=>` and recover
277 if op.node == AssocOp::LessEqual
278 && self.token.kind == token::Gt
279 && self.prev_token.span.hi() == self.token.span.lo()
281 let sp = op.span.to(self.token.span);
282 self.sess.emit_err(InvalidComparisonOperator {
284 invalid: "<=>".into(),
285 sub: InvalidComparisonOperatorSub::Spaceship(sp),
290 if self.prev_token == token::BinOp(token::Plus)
291 && self.token == token::BinOp(token::Plus)
292 && self.prev_token.span.between(self.token.span).is_empty()
294 let op_span = self.prev_token.span.to(self.token.span);
295 // Eat the second `+`
297 lhs = self.recover_from_postfix_increment(lhs, op_span)?;
303 if op == AssocOp::As {
304 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
306 } else if op == AssocOp::Colon {
307 lhs = self.parse_assoc_op_ascribe(lhs, lhs_span)?;
309 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
310 // If we didn't have to handle `x..`/`x..=`, it would be pretty easy to
311 // generalise it to the Fixity::None code.
312 lhs = self.parse_range_expr(prec, lhs, op, cur_op_span)?;
316 let fixity = op.fixity();
317 let prec_adjustment = match fixity {
320 // We currently have no non-associative operators that are not handled above by
321 // the special cases. The code is here only for future convenience.
324 let rhs = self.with_res(restrictions - Restrictions::STMT_EXPR, |this| {
325 this.parse_assoc_expr_with(prec + prec_adjustment, LhsExpr::NotYetParsed)
328 let span = self.mk_expr_sp(&lhs, lhs_span, rhs.span);
341 | AssocOp::ShiftRight
347 | AssocOp::GreaterEqual => {
348 let ast_op = op.to_ast_binop().unwrap();
349 let binary = self.mk_binary(source_map::respan(cur_op_span, ast_op), lhs, rhs);
350 self.mk_expr(span, binary)
352 AssocOp::Assign => self.mk_expr(span, ExprKind::Assign(lhs, rhs, cur_op_span)),
353 AssocOp::AssignOp(k) => {
355 token::Plus => BinOpKind::Add,
356 token::Minus => BinOpKind::Sub,
357 token::Star => BinOpKind::Mul,
358 token::Slash => BinOpKind::Div,
359 token::Percent => BinOpKind::Rem,
360 token::Caret => BinOpKind::BitXor,
361 token::And => BinOpKind::BitAnd,
362 token::Or => BinOpKind::BitOr,
363 token::Shl => BinOpKind::Shl,
364 token::Shr => BinOpKind::Shr,
366 let aopexpr = self.mk_assign_op(source_map::respan(cur_op_span, aop), lhs, rhs);
367 self.mk_expr(span, aopexpr)
369 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
370 self.span_bug(span, "AssocOp should have been handled by special case")
374 if let Fixity::None = fixity {
378 if last_type_ascription_set {
379 self.last_type_ascription = None;
384 fn should_continue_as_assoc_expr(&mut self, lhs: &Expr) -> bool {
385 match (self.expr_is_complete(lhs), AssocOp::from_token(&self.token)) {
386 // Semi-statement forms are odd:
387 // See https://github.com/rust-lang/rust/issues/29071
388 (true, None) => false,
389 (false, _) => true, // Continue parsing the expression.
390 // An exhaustive check is done in the following block, but these are checked first
391 // because they *are* ambiguous but also reasonable looking incorrect syntax, so we
392 // want to keep their span info to improve diagnostics in these cases in a later stage.
393 (true, Some(AssocOp::Multiply)) | // `{ 42 } *foo = bar;` or `{ 42 } * 3`
394 (true, Some(AssocOp::Subtract)) | // `{ 42 } -5`
395 (true, Some(AssocOp::Add)) // `{ 42 } + 42
396 // If the next token is a keyword, then the tokens above *are* unambiguously incorrect:
397 // `if x { a } else { b } && if y { c } else { d }`
398 if !self.look_ahead(1, |t| t.is_used_keyword()) => {
399 // These cases are ambiguous and can't be identified in the parser alone.
400 let sp = self.sess.source_map().start_point(self.token.span);
401 self.sess.ambiguous_block_expr_parse.borrow_mut().insert(sp, lhs.span);
404 (true, Some(AssocOp::LAnd)) |
405 (true, Some(AssocOp::LOr)) |
406 (true, Some(AssocOp::BitOr)) => {
407 // `{ 42 } &&x` (#61475) or `{ 42 } && if x { 1 } else { 0 }`. Separated from the
408 // above due to #74233.
409 // These cases are ambiguous and can't be identified in the parser alone.
411 // Bitwise AND is left out because guessing intent is hard. We can make
412 // suggestions based on the assumption that double-refs are rarely intentional,
413 // and closures are distinct enough that they don't get mixed up with their
415 let sp = self.sess.source_map().start_point(self.token.span);
416 self.sess.ambiguous_block_expr_parse.borrow_mut().insert(sp, lhs.span);
419 (true, Some(ref op)) if !op.can_continue_expr_unambiguously() => false,
421 self.error_found_expr_would_be_stmt(lhs);
427 /// We've found an expression that would be parsed as a statement,
428 /// but the next token implies this should be parsed as an expression.
429 /// For example: `if let Some(x) = x { x } else { 0 } / 2`.
430 fn error_found_expr_would_be_stmt(&self, lhs: &Expr) {
431 self.sess.emit_err(FoundExprWouldBeStmt {
432 span: self.token.span,
433 token: self.token.clone(),
434 suggestion: ExprParenthesesNeeded::surrounding(lhs.span),
438 /// Possibly translate the current token to an associative operator.
439 /// The method does not advance the current token.
441 /// Also performs recovery for `and` / `or` which are mistaken for `&&` and `||` respectively.
442 fn check_assoc_op(&self) -> Option<Spanned<AssocOp>> {
443 let (op, span) = match (AssocOp::from_token(&self.token), self.token.ident()) {
444 // When parsing const expressions, stop parsing when encountering `>`.
449 | AssocOp::GreaterEqual
450 | AssocOp::AssignOp(token::BinOpToken::Shr),
453 ) if self.restrictions.contains(Restrictions::CONST_EXPR) => {
456 (Some(op), _) => (op, self.token.span),
457 (None, Some((Ident { name: sym::and, span }, false))) => {
458 self.sess.emit_err(InvalidLogicalOperator {
459 span: self.token.span,
460 incorrect: "and".into(),
461 sub: InvalidLogicalOperatorSub::Conjunction(self.token.span),
463 (AssocOp::LAnd, span)
465 (None, Some((Ident { name: sym::or, span }, false))) => {
466 self.sess.emit_err(InvalidLogicalOperator {
467 span: self.token.span,
468 incorrect: "or".into(),
469 sub: InvalidLogicalOperatorSub::Disjunction(self.token.span),
475 Some(source_map::respan(span, op))
478 /// Checks if this expression is a successfully parsed statement.
479 fn expr_is_complete(&self, e: &Expr) -> bool {
480 self.restrictions.contains(Restrictions::STMT_EXPR)
481 && !classify::expr_requires_semi_to_be_stmt(e)
484 /// Parses `x..y`, `x..=y`, and `x..`/`x..=`.
485 /// The other two variants are handled in `parse_prefix_range_expr` below.
492 ) -> PResult<'a, P<Expr>> {
493 let rhs = if self.is_at_start_of_range_notation_rhs() {
494 Some(self.parse_assoc_expr_with(prec + 1, LhsExpr::NotYetParsed)?)
498 let rhs_span = rhs.as_ref().map_or(cur_op_span, |x| x.span);
499 let span = self.mk_expr_sp(&lhs, lhs.span, rhs_span);
501 if op == AssocOp::DotDot { RangeLimits::HalfOpen } else { RangeLimits::Closed };
502 let range = self.mk_range(Some(lhs), rhs, limits);
503 Ok(self.mk_expr(span, range))
506 fn is_at_start_of_range_notation_rhs(&self) -> bool {
507 if self.token.can_begin_expr() {
508 // Parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
509 if self.token == token::OpenDelim(Delimiter::Brace) {
510 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
518 /// Parses prefix-forms of range notation: `..expr`, `..`, `..=expr`.
519 fn parse_prefix_range_expr(&mut self, attrs: Option<AttrWrapper>) -> PResult<'a, P<Expr>> {
520 // Check for deprecated `...` syntax.
521 if self.token == token::DotDotDot {
522 self.err_dotdotdot_syntax(self.token.span);
526 [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token.kind),
527 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
531 let limits = match self.token.kind {
532 token::DotDot => RangeLimits::HalfOpen,
533 _ => RangeLimits::Closed,
535 let op = AssocOp::from_token(&self.token);
536 // FIXME: `parse_prefix_range_expr` is called when the current
537 // token is `DotDot`, `DotDotDot`, or `DotDotEq`. If we haven't already
538 // parsed attributes, then trying to parse them here will always fail.
539 // We should figure out how we want attributes on range expressions to work.
540 let attrs = self.parse_or_use_outer_attributes(attrs)?;
541 self.collect_tokens_for_expr(attrs, |this, attrs| {
542 let lo = this.token.span;
544 let (span, opt_end) = if this.is_at_start_of_range_notation_rhs() {
545 // RHS must be parsed with more associativity than the dots.
546 this.parse_assoc_expr_with(op.unwrap().precedence() + 1, LhsExpr::NotYetParsed)
547 .map(|x| (lo.to(x.span), Some(x)))?
551 let range = this.mk_range(None, opt_end, limits);
552 Ok(this.mk_expr_with_attrs(span, range, attrs))
556 /// Parses a prefix-unary-operator expr.
557 fn parse_prefix_expr(&mut self, attrs: Option<AttrWrapper>) -> PResult<'a, P<Expr>> {
558 let attrs = self.parse_or_use_outer_attributes(attrs)?;
559 let lo = self.token.span;
561 macro_rules! make_it {
562 ($this:ident, $attrs:expr, |this, _| $body:expr) => {
563 $this.collect_tokens_for_expr($attrs, |$this, attrs| {
564 let (hi, ex) = $body?;
565 Ok($this.mk_expr_with_attrs(lo.to(hi), ex, attrs))
572 // Note: when adding new unary operators, don't forget to adjust TokenKind::can_begin_expr()
573 match this.token.uninterpolate().kind {
574 token::Not => make_it!(this, attrs, |this, _| this.parse_unary_expr(lo, UnOp::Not)), // `!expr`
575 token::Tilde => make_it!(this, attrs, |this, _| this.recover_tilde_expr(lo)), // `~expr`
576 token::BinOp(token::Minus) => {
577 make_it!(this, attrs, |this, _| this.parse_unary_expr(lo, UnOp::Neg))
579 token::BinOp(token::Star) => {
580 make_it!(this, attrs, |this, _| this.parse_unary_expr(lo, UnOp::Deref))
582 token::BinOp(token::And) | token::AndAnd => {
583 make_it!(this, attrs, |this, _| this.parse_borrow_expr(lo))
585 token::BinOp(token::Plus) if this.look_ahead(1, |tok| tok.is_numeric_lit()) => {
587 LeadingPlusNotSupported { span: lo, remove_plus: None, add_parentheses: None };
589 // a block on the LHS might have been intended to be an expression instead
590 if let Some(sp) = this.sess.ambiguous_block_expr_parse.borrow().get(&lo) {
591 err.add_parentheses = Some(ExprParenthesesNeeded::surrounding(*sp));
593 err.remove_plus = Some(lo);
595 this.sess.emit_err(err);
598 this.parse_prefix_expr(None)
600 // Recover from `++x`:
601 token::BinOp(token::Plus)
602 if this.look_ahead(1, |t| *t == token::BinOp(token::Plus)) =>
604 let prev_is_semi = this.prev_token == token::Semi;
605 let pre_span = this.token.span.to(this.look_ahead(1, |t| t.span));
610 let operand_expr = this.parse_dot_or_call_expr(Default::default())?;
611 this.recover_from_prefix_increment(operand_expr, pre_span, prev_is_semi)
613 token::Ident(..) if this.token.is_keyword(kw::Box) => {
614 make_it!(this, attrs, |this, _| this.parse_box_expr(lo))
616 token::Ident(..) if this.is_mistaken_not_ident_negation() => {
617 make_it!(this, attrs, |this, _| this.recover_not_expr(lo))
619 _ => return this.parse_dot_or_call_expr(Some(attrs)),
623 fn parse_prefix_expr_common(&mut self, lo: Span) -> PResult<'a, (Span, P<Expr>)> {
625 let expr = self.parse_prefix_expr(None);
626 let (span, expr) = self.interpolated_or_expr_span(expr)?;
627 Ok((lo.to(span), expr))
630 fn parse_unary_expr(&mut self, lo: Span, op: UnOp) -> PResult<'a, (Span, ExprKind)> {
631 let (span, expr) = self.parse_prefix_expr_common(lo)?;
632 Ok((span, self.mk_unary(op, expr)))
635 // Recover on `!` suggesting for bitwise negation instead.
636 fn recover_tilde_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
637 self.sess.emit_err(TildeAsUnaryOperator(lo));
639 self.parse_unary_expr(lo, UnOp::Not)
642 /// Parse `box expr`.
643 fn parse_box_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
644 let (span, expr) = self.parse_prefix_expr_common(lo)?;
645 self.sess.gated_spans.gate(sym::box_syntax, span);
646 Ok((span, ExprKind::Box(expr)))
649 fn is_mistaken_not_ident_negation(&self) -> bool {
650 let token_cannot_continue_expr = |t: &Token| match t.uninterpolate().kind {
651 // These tokens can start an expression after `!`, but
652 // can't continue an expression after an ident
653 token::Ident(name, is_raw) => token::ident_can_begin_expr(name, t.span, is_raw),
654 token::Literal(..) | token::Pound => true,
655 _ => t.is_whole_expr(),
657 self.token.is_ident_named(sym::not) && self.look_ahead(1, token_cannot_continue_expr)
660 /// Recover on `not expr` in favor of `!expr`.
661 fn recover_not_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
663 let negated_token = self.look_ahead(1, |t| t.clone());
665 let sub_diag = if negated_token.is_numeric_lit() {
666 NotAsNegationOperatorSub::SuggestNotBitwise
667 } else if negated_token.is_bool_lit() {
668 NotAsNegationOperatorSub::SuggestNotLogical
670 NotAsNegationOperatorSub::SuggestNotDefault
673 self.sess.emit_err(NotAsNegationOperator {
674 negated: negated_token.span,
675 negated_desc: super::token_descr(&negated_token),
676 // Span the `not` plus trailing whitespace to avoid
677 // trailing whitespace after the `!` in our suggestion
679 self.sess.source_map().span_until_non_whitespace(lo.to(negated_token.span)),
684 self.parse_unary_expr(lo, UnOp::Not)
687 /// Returns the span of expr, if it was not interpolated or the span of the interpolated token.
688 fn interpolated_or_expr_span(
690 expr: PResult<'a, P<Expr>>,
691 ) -> PResult<'a, (Span, P<Expr>)> {
694 match self.prev_token.kind {
695 TokenKind::Interpolated(..) => self.prev_token.span,
703 fn parse_assoc_op_cast(
707 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind,
708 ) -> PResult<'a, P<Expr>> {
709 let mk_expr = |this: &mut Self, lhs: P<Expr>, rhs: P<Ty>| {
710 this.mk_expr(this.mk_expr_sp(&lhs, lhs_span, rhs.span), expr_kind(lhs, rhs))
713 // Save the state of the parser before parsing type normally, in case there is a
714 // LessThan comparison after this cast.
715 let parser_snapshot_before_type = self.clone();
716 let cast_expr = match self.parse_as_cast_ty() {
717 Ok(rhs) => mk_expr(self, lhs, rhs),
719 // Rewind to before attempting to parse the type with generics, to recover
720 // from situations like `x as usize < y` in which we first tried to parse
721 // `usize < y` as a type with generic arguments.
722 let parser_snapshot_after_type = mem::replace(self, parser_snapshot_before_type);
724 // Check for typo of `'a: loop { break 'a }` with a missing `'`.
725 match (&lhs.kind, &self.token.kind) {
728 ExprKind::Path(None, ast::Path { segments, .. }),
729 TokenKind::Ident(kw::For | kw::Loop | kw::While, false),
730 ) if segments.len() == 1 => {
731 let snapshot = self.create_snapshot_for_diagnostic();
733 ident: Ident::from_str_and_span(
734 &format!("'{}", segments[0].ident),
735 segments[0].ident.span,
738 match self.parse_labeled_expr(label, false) {
741 self.sess.emit_err(MalformedLoopLabel {
742 span: label.ident.span,
743 correct_label: label.ident,
749 self.restore_snapshot(snapshot);
756 match self.parse_path(PathStyle::Expr) {
758 let span_after_type = parser_snapshot_after_type.token.span;
762 self.mk_ty(path.span, TyKind::Path(None, path.clone())),
765 let args_span = self.look_ahead(1, |t| t.span).to(span_after_type);
766 let suggestion = ComparisonOrShiftInterpretedAsGenericSugg {
767 left: expr.span.shrink_to_lo(),
768 right: expr.span.shrink_to_hi(),
771 match self.token.kind {
772 token::Lt => self.sess.emit_err(ComparisonInterpretedAsGeneric {
773 comparison: self.token.span,
778 token::BinOp(token::Shl) => {
779 self.sess.emit_err(ShiftInterpretedAsGeneric {
780 shift: self.token.span,
787 // We can end up here even without `<` being the next token, for
788 // example because `parse_ty_no_plus` returns `Err` on keywords,
789 // but `parse_path` returns `Ok` on them due to error recovery.
790 // Return original error and parser state.
791 *self = parser_snapshot_after_type;
792 return Err(type_err);
796 // Successfully parsed the type path leaving a `<` yet to parse.
799 // Keep `x as usize` as an expression in AST and continue parsing.
803 // Couldn't parse as a path, return original error and parser state.
805 *self = parser_snapshot_after_type;
806 return Err(type_err);
812 self.parse_and_disallow_postfix_after_cast(cast_expr)
815 /// Parses a postfix operators such as `.`, `?`, or index (`[]`) after a cast,
816 /// then emits an error and returns the newly parsed tree.
817 /// The resulting parse tree for `&x as T[0]` has a precedence of `((&x) as T)[0]`.
818 fn parse_and_disallow_postfix_after_cast(
821 ) -> PResult<'a, P<Expr>> {
822 let span = cast_expr.span;
823 let (cast_kind, maybe_ascription_span) =
824 if let ExprKind::Type(ascripted_expr, _) = &cast_expr.kind {
825 ("type ascription", Some(ascripted_expr.span.shrink_to_hi().with_hi(span.hi())))
830 // Save the memory location of expr before parsing any following postfix operators.
831 // This will be compared with the memory location of the output expression.
832 // If they different we can assume we parsed another expression because the existing expression is not reallocated.
833 let addr_before = &*cast_expr as *const _ as usize;
834 let with_postfix = self.parse_dot_or_call_expr_with_(cast_expr, span)?;
835 let changed = addr_before != &*with_postfix as *const _ as usize;
837 // Check if an illegal postfix operator has been added after the cast.
838 // If the resulting expression is not a cast, or has a different memory location, it is an illegal postfix operator.
839 if !matches!(with_postfix.kind, ExprKind::Cast(_, _) | ExprKind::Type(_, _)) || changed {
841 "{cast_kind} cannot be followed by {}",
842 match with_postfix.kind {
843 ExprKind::Index(_, _) => "indexing",
844 ExprKind::Try(_) => "`?`",
845 ExprKind::Field(_, _) => "a field access",
846 ExprKind::MethodCall(_, _, _, _) => "a method call",
847 ExprKind::Call(_, _) => "a function call",
848 ExprKind::Await(_) => "`.await`",
849 ExprKind::Err => return Ok(with_postfix),
850 _ => unreachable!("parse_dot_or_call_expr_with_ shouldn't produce this"),
853 let mut err = self.struct_span_err(span, &msg);
855 let suggest_parens = |err: &mut Diagnostic| {
856 let suggestions = vec![
857 (span.shrink_to_lo(), "(".to_string()),
858 (span.shrink_to_hi(), ")".to_string()),
860 err.multipart_suggestion(
861 "try surrounding the expression in parentheses",
863 Applicability::MachineApplicable,
867 // If type ascription is "likely an error", the user will already be getting a useful
868 // help message, and doesn't need a second.
869 if self.last_type_ascription.map_or(false, |last_ascription| last_ascription.1) {
870 self.maybe_annotate_with_ascription(&mut err, false);
871 } else if let Some(ascription_span) = maybe_ascription_span {
872 let is_nightly = self.sess.unstable_features.is_nightly_build();
874 suggest_parens(&mut err);
879 "{}remove the type ascription",
880 if is_nightly { "alternatively, " } else { "" }
884 Applicability::MaybeIncorrect
886 Applicability::MachineApplicable
890 suggest_parens(&mut err);
897 fn parse_assoc_op_ascribe(&mut self, lhs: P<Expr>, lhs_span: Span) -> PResult<'a, P<Expr>> {
898 let maybe_path = self.could_ascription_be_path(&lhs.kind);
899 self.last_type_ascription = Some((self.prev_token.span, maybe_path));
900 let lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type)?;
901 self.sess.gated_spans.gate(sym::type_ascription, lhs.span);
905 /// Parse `& mut? <expr>` or `& raw [ const | mut ] <expr>`.
906 fn parse_borrow_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
908 let has_lifetime = self.token.is_lifetime() && self.look_ahead(1, |t| t != &token::Colon);
909 let lifetime = has_lifetime.then(|| self.expect_lifetime()); // For recovery, see below.
910 let (borrow_kind, mutbl) = self.parse_borrow_modifiers(lo);
911 let expr = self.parse_prefix_expr(None);
912 let (hi, expr) = self.interpolated_or_expr_span(expr)?;
913 let span = lo.to(hi);
914 if let Some(lt) = lifetime {
915 self.error_remove_borrow_lifetime(span, lt.ident.span);
917 Ok((span, ExprKind::AddrOf(borrow_kind, mutbl, expr)))
920 fn error_remove_borrow_lifetime(&self, span: Span, lt_span: Span) {
921 self.sess.emit_err(LifetimeInBorrowExpression { span, lifetime_span: lt_span });
924 /// Parse `mut?` or `raw [ const | mut ]`.
925 fn parse_borrow_modifiers(&mut self, lo: Span) -> (ast::BorrowKind, ast::Mutability) {
926 if self.check_keyword(kw::Raw) && self.look_ahead(1, Token::is_mutability) {
927 // `raw [ const | mut ]`.
928 let found_raw = self.eat_keyword(kw::Raw);
930 let mutability = self.parse_const_or_mut().unwrap();
931 self.sess.gated_spans.gate(sym::raw_ref_op, lo.to(self.prev_token.span));
932 (ast::BorrowKind::Raw, mutability)
935 (ast::BorrowKind::Ref, self.parse_mutability())
939 /// Parses `a.b` or `a(13)` or `a[4]` or just `a`.
940 fn parse_dot_or_call_expr(&mut self, attrs: Option<AttrWrapper>) -> PResult<'a, P<Expr>> {
941 let attrs = self.parse_or_use_outer_attributes(attrs)?;
942 self.collect_tokens_for_expr(attrs, |this, attrs| {
943 let base = this.parse_bottom_expr();
944 let (span, base) = this.interpolated_or_expr_span(base)?;
945 this.parse_dot_or_call_expr_with(base, span, attrs)
949 pub(super) fn parse_dot_or_call_expr_with(
953 mut attrs: ast::AttrVec,
954 ) -> PResult<'a, P<Expr>> {
955 // Stitch the list of outer attributes onto the return value.
956 // A little bit ugly, but the best way given the current code
958 let res = self.parse_dot_or_call_expr_with_(e0, lo);
959 if attrs.is_empty() {
963 expr.map(|mut expr| {
964 attrs.extend(expr.attrs);
972 fn parse_dot_or_call_expr_with_(&mut self, mut e: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
974 let has_question = if self.prev_token.kind == TokenKind::Ident(kw::Return, false) {
975 // we are using noexpect here because we don't expect a `?` directly after a `return`
976 // which could be suggested otherwise
977 self.eat_noexpect(&token::Question)
979 self.eat(&token::Question)
983 e = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Try(e));
986 let has_dot = if self.prev_token.kind == TokenKind::Ident(kw::Return, false) {
987 // we are using noexpect here because we don't expect a `.` directly after a `return`
988 // which could be suggested otherwise
989 self.eat_noexpect(&token::Dot)
991 self.eat(&token::Dot)
995 e = self.parse_dot_suffix_expr(lo, e)?;
998 if self.expr_is_complete(&e) {
1001 e = match self.token.kind {
1002 token::OpenDelim(Delimiter::Parenthesis) => self.parse_fn_call_expr(lo, e),
1003 token::OpenDelim(Delimiter::Bracket) => self.parse_index_expr(lo, e)?,
1009 fn look_ahead_type_ascription_as_field(&mut self) -> bool {
1010 self.look_ahead(1, |t| t.is_ident())
1011 && self.look_ahead(2, |t| t == &token::Colon)
1012 && self.look_ahead(3, |t| t.can_begin_expr())
1015 fn parse_dot_suffix_expr(&mut self, lo: Span, base: P<Expr>) -> PResult<'a, P<Expr>> {
1016 match self.token.uninterpolate().kind {
1017 token::Ident(..) => self.parse_dot_suffix(base, lo),
1018 token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) => {
1019 Ok(self.parse_tuple_field_access_expr(lo, base, symbol, suffix, None))
1021 token::Literal(token::Lit { kind: token::Float, symbol, suffix }) => {
1022 Ok(self.parse_tuple_field_access_expr_float(lo, base, symbol, suffix))
1025 self.error_unexpected_after_dot();
1031 fn error_unexpected_after_dot(&self) {
1032 // FIXME Could factor this out into non_fatal_unexpected or something.
1033 let actual = pprust::token_to_string(&self.token);
1034 self.struct_span_err(self.token.span, &format!("unexpected token: `{actual}`")).emit();
1037 // We need an identifier or integer, but the next token is a float.
1038 // Break the float into components to extract the identifier or integer.
1039 // FIXME: With current `TokenCursor` it's hard to break tokens into more than 2
1040 // parts unless those parts are processed immediately. `TokenCursor` should either
1041 // support pushing "future tokens" (would be also helpful to `break_and_eat`), or
1042 // we should break everything including floats into more basic proc-macro style
1043 // tokens in the lexer (probably preferable).
1044 fn parse_tuple_field_access_expr_float(
1049 suffix: Option<Symbol>,
1052 enum FloatComponent {
1056 use FloatComponent::*;
1058 let float_str = float.as_str();
1059 let mut components = Vec::new();
1060 let mut ident_like = String::new();
1061 for c in float_str.chars() {
1062 if c == '_' || c.is_ascii_alphanumeric() {
1064 } else if matches!(c, '.' | '+' | '-') {
1065 if !ident_like.is_empty() {
1066 components.push(IdentLike(mem::take(&mut ident_like)));
1068 components.push(Punct(c));
1070 panic!("unexpected character in a float token: {:?}", c)
1073 if !ident_like.is_empty() {
1074 components.push(IdentLike(ident_like));
1077 // With proc macros the span can refer to anything, the source may be too short,
1078 // or too long, or non-ASCII. It only makes sense to break our span into components
1079 // if its underlying text is identical to our float literal.
1080 let span = self.token.span;
1081 let can_take_span_apart =
1082 || self.span_to_snippet(span).as_deref() == Ok(float_str).as_deref();
1084 match &*components {
1087 self.parse_tuple_field_access_expr(lo, base, Symbol::intern(&i), suffix, None)
1090 [IdentLike(i), Punct('.')] => {
1091 let (ident_span, dot_span) = if can_take_span_apart() {
1092 let (span, ident_len) = (span.data(), BytePos::from_usize(i.len()));
1093 let ident_span = span.with_hi(span.lo + ident_len);
1094 let dot_span = span.with_lo(span.lo + ident_len);
1095 (ident_span, dot_span)
1099 assert!(suffix.is_none());
1100 let symbol = Symbol::intern(&i);
1101 self.token = Token::new(token::Ident(symbol, false), ident_span);
1102 let next_token = (Token::new(token::Dot, dot_span), self.token_spacing);
1103 self.parse_tuple_field_access_expr(lo, base, symbol, None, Some(next_token))
1106 [IdentLike(i1), Punct('.'), IdentLike(i2)] => {
1107 let (ident1_span, dot_span, ident2_span) = if can_take_span_apart() {
1108 let (span, ident1_len) = (span.data(), BytePos::from_usize(i1.len()));
1109 let ident1_span = span.with_hi(span.lo + ident1_len);
1111 .with_lo(span.lo + ident1_len)
1112 .with_hi(span.lo + ident1_len + BytePos(1));
1113 let ident2_span = self.token.span.with_lo(span.lo + ident1_len + BytePos(1));
1114 (ident1_span, dot_span, ident2_span)
1118 let symbol1 = Symbol::intern(&i1);
1119 self.token = Token::new(token::Ident(symbol1, false), ident1_span);
1120 // This needs to be `Spacing::Alone` to prevent regressions.
1121 // See issue #76399 and PR #76285 for more details
1122 let next_token1 = (Token::new(token::Dot, dot_span), Spacing::Alone);
1124 self.parse_tuple_field_access_expr(lo, base, symbol1, None, Some(next_token1));
1125 let symbol2 = Symbol::intern(&i2);
1126 let next_token2 = Token::new(token::Ident(symbol2, false), ident2_span);
1127 self.bump_with((next_token2, self.token_spacing)); // `.`
1128 self.parse_tuple_field_access_expr(lo, base1, symbol2, suffix, None)
1130 // 1e+ | 1e- (recovered)
1131 [IdentLike(_), Punct('+' | '-')] |
1133 [IdentLike(_), Punct('+' | '-'), IdentLike(_)] |
1135 [IdentLike(_), Punct('.'), IdentLike(_), Punct('+' | '-')] |
1137 [IdentLike(_), Punct('.'), IdentLike(_), Punct('+' | '-'), IdentLike(_)] => {
1138 // See the FIXME about `TokenCursor` above.
1139 self.error_unexpected_after_dot();
1142 _ => panic!("unexpected components in a float token: {:?}", components),
1146 fn parse_tuple_field_access_expr(
1151 suffix: Option<Symbol>,
1152 next_token: Option<(Token, Spacing)>,
1155 Some(next_token) => self.bump_with(next_token),
1156 None => self.bump(),
1158 let span = self.prev_token.span;
1159 let field = ExprKind::Field(base, Ident::new(field, span));
1160 if let Some(suffix) = suffix {
1161 self.expect_no_tuple_index_suffix(span, suffix);
1163 self.mk_expr(lo.to(span), field)
1166 /// Parse a function call expression, `expr(...)`.
1167 fn parse_fn_call_expr(&mut self, lo: Span, fun: P<Expr>) -> P<Expr> {
1168 let snapshot = if self.token.kind == token::OpenDelim(Delimiter::Parenthesis)
1169 && self.look_ahead_type_ascription_as_field()
1171 Some((self.create_snapshot_for_diagnostic(), fun.kind.clone()))
1175 let open_paren = self.token.span;
1178 .parse_paren_expr_seq()
1179 .map(|args| self.mk_expr(lo.to(self.prev_token.span), self.mk_call(fun, args)));
1181 self.maybe_recover_struct_lit_bad_delims(lo, open_paren, &mut seq, snapshot)
1185 self.recover_seq_parse_error(Delimiter::Parenthesis, lo, seq)
1188 /// If we encounter a parser state that looks like the user has written a `struct` literal with
1189 /// parentheses instead of braces, recover the parser state and provide suggestions.
1190 #[instrument(skip(self, seq, snapshot), level = "trace")]
1191 fn maybe_recover_struct_lit_bad_delims(
1195 seq: &mut PResult<'a, P<Expr>>,
1196 snapshot: Option<(SnapshotParser<'a>, ExprKind)>,
1197 ) -> Option<P<Expr>> {
1198 match (seq.as_mut(), snapshot) {
1199 (Err(err), Some((mut snapshot, ExprKind::Path(None, path)))) => {
1200 snapshot.bump(); // `(`
1201 match snapshot.parse_struct_fields(path.clone(), false, Delimiter::Parenthesis) {
1203 if snapshot.eat(&token::CloseDelim(Delimiter::Parenthesis)) =>
1205 // We are certain we have `Enum::Foo(a: 3, b: 4)`, suggest
1206 // `Enum::Foo { a: 3, b: 4 }` or `Enum::Foo(3, 4)`.
1207 self.restore_snapshot(snapshot);
1208 let close_paren = self.prev_token.span;
1209 let span = lo.to(self.prev_token.span);
1210 if !fields.is_empty() {
1211 let mut replacement_err = ParenthesesWithStructFields {
1214 braces_for_struct: BracesForStructLiteral {
1216 second: close_paren,
1218 no_fields_for_fn: NoFieldsForFnCall {
1221 .map(|field| field.span.until(field.expr.span))
1225 .into_diagnostic(&self.sess.span_diagnostic);
1226 replacement_err.emit();
1228 let old_err = mem::replace(err, replacement_err);
1233 return Some(self.mk_expr_err(span));
1246 /// Parse an indexing expression `expr[...]`.
1247 fn parse_index_expr(&mut self, lo: Span, base: P<Expr>) -> PResult<'a, P<Expr>> {
1248 let prev_span = self.prev_token.span;
1249 let open_delim_span = self.token.span;
1251 let index = self.parse_expr()?;
1252 self.suggest_missing_semicolon_before_array(prev_span, open_delim_span)?;
1253 self.expect(&token::CloseDelim(Delimiter::Bracket))?;
1254 Ok(self.mk_expr(lo.to(self.prev_token.span), self.mk_index(base, index)))
1257 /// Assuming we have just parsed `.`, continue parsing into an expression.
1258 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
1259 if self.token.uninterpolated_span().rust_2018() && self.eat_keyword(kw::Await) {
1260 return Ok(self.mk_await_expr(self_arg, lo));
1263 let fn_span_lo = self.token.span;
1264 let mut segment = self.parse_path_segment(PathStyle::Expr, None)?;
1265 self.check_trailing_angle_brackets(&segment, &[&token::OpenDelim(Delimiter::Parenthesis)]);
1266 self.check_turbofish_missing_angle_brackets(&mut segment);
1268 if self.check(&token::OpenDelim(Delimiter::Parenthesis)) {
1269 // Method call `expr.f()`
1270 let args = self.parse_paren_expr_seq()?;
1271 let fn_span = fn_span_lo.to(self.prev_token.span);
1272 let span = lo.to(self.prev_token.span);
1273 Ok(self.mk_expr(span, ExprKind::MethodCall(segment, self_arg, args, fn_span)))
1275 // Field access `expr.f`
1276 if let Some(args) = segment.args {
1277 self.sess.emit_err(FieldExpressionWithGeneric(args.span()));
1280 let span = lo.to(self.prev_token.span);
1281 Ok(self.mk_expr(span, ExprKind::Field(self_arg, segment.ident)))
1285 /// At the bottom (top?) of the precedence hierarchy,
1286 /// Parses things like parenthesized exprs, macros, `return`, etc.
1288 /// N.B., this does not parse outer attributes, and is private because it only works
1289 /// correctly if called from `parse_dot_or_call_expr()`.
1290 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
1291 maybe_recover_from_interpolated_ty_qpath!(self, true);
1292 maybe_whole_expr!(self);
1294 // Outer attributes are already parsed and will be
1295 // added to the return value after the fact.
1297 // Note: when adding new syntax here, don't forget to adjust `TokenKind::can_begin_expr()`.
1298 let lo = self.token.span;
1299 if let token::Literal(_) = self.token.kind {
1300 // This match arm is a special-case of the `_` match arm below and
1301 // could be removed without changing functionality, but it's faster
1302 // to have it here, especially for programs with large constants.
1303 self.parse_lit_expr()
1304 } else if self.check(&token::OpenDelim(Delimiter::Parenthesis)) {
1305 self.parse_tuple_parens_expr()
1306 } else if self.check(&token::OpenDelim(Delimiter::Brace)) {
1307 self.parse_block_expr(None, lo, BlockCheckMode::Default)
1308 } else if self.check(&token::BinOp(token::Or)) || self.check(&token::OrOr) {
1309 self.parse_closure_expr().map_err(|mut err| {
1310 // If the input is something like `if a { 1 } else { 2 } | if a { 3 } else { 4 }`
1311 // then suggest parens around the lhs.
1312 if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&lo) {
1313 err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp));
1317 } else if self.check(&token::OpenDelim(Delimiter::Bracket)) {
1318 self.parse_array_or_repeat_expr(Delimiter::Bracket)
1319 } else if self.check_path() {
1320 self.parse_path_start_expr()
1321 } else if self.check_keyword(kw::Move) || self.check_keyword(kw::Static) {
1322 self.parse_closure_expr()
1323 } else if self.eat_keyword(kw::If) {
1324 self.parse_if_expr()
1325 } else if self.check_keyword(kw::For) {
1326 if self.choose_generics_over_qpath(1) {
1327 self.parse_closure_expr()
1329 assert!(self.eat_keyword(kw::For));
1330 self.parse_for_expr(None, self.prev_token.span)
1332 } else if self.eat_keyword(kw::While) {
1333 self.parse_while_expr(None, self.prev_token.span)
1334 } else if let Some(label) = self.eat_label() {
1335 self.parse_labeled_expr(label, true)
1336 } else if self.eat_keyword(kw::Loop) {
1337 let sp = self.prev_token.span;
1338 self.parse_loop_expr(None, self.prev_token.span).map_err(|mut err| {
1339 err.span_label(sp, "while parsing this `loop` expression");
1342 } else if self.eat_keyword(kw::Continue) {
1343 let kind = ExprKind::Continue(self.eat_label());
1344 Ok(self.mk_expr(lo.to(self.prev_token.span), kind))
1345 } else if self.eat_keyword(kw::Match) {
1346 let match_sp = self.prev_token.span;
1347 self.parse_match_expr().map_err(|mut err| {
1348 err.span_label(match_sp, "while parsing this `match` expression");
1351 } else if self.eat_keyword(kw::Unsafe) {
1352 let sp = self.prev_token.span;
1353 self.parse_block_expr(None, lo, BlockCheckMode::Unsafe(ast::UserProvided)).map_err(
1355 err.span_label(sp, "while parsing this `unsafe` expression");
1359 } else if self.check_inline_const(0) {
1360 self.parse_const_block(lo.to(self.token.span), false)
1361 } else if self.is_do_catch_block() {
1362 self.recover_do_catch()
1363 } else if self.is_try_block() {
1364 self.expect_keyword(kw::Try)?;
1365 self.parse_try_block(lo)
1366 } else if self.eat_keyword(kw::Return) {
1367 self.parse_return_expr()
1368 } else if self.eat_keyword(kw::Break) {
1369 self.parse_break_expr()
1370 } else if self.eat_keyword(kw::Yield) {
1371 self.parse_yield_expr()
1372 } else if self.is_do_yeet() {
1373 self.parse_yeet_expr()
1374 } else if self.check_keyword(kw::Let) {
1375 self.parse_let_expr()
1376 } else if self.eat_keyword(kw::Underscore) {
1377 Ok(self.mk_expr(self.prev_token.span, ExprKind::Underscore))
1378 } else if !self.unclosed_delims.is_empty() && self.check(&token::Semi) {
1379 // Don't complain about bare semicolons after unclosed braces
1380 // recovery in order to keep the error count down. Fixing the
1381 // delimiters will possibly also fix the bare semicolon found in
1382 // expression context. For example, silence the following error:
1384 // error: expected expression, found `;`
1388 // | ^ expected expression
1390 Ok(self.mk_expr_err(self.token.span))
1391 } else if self.token.uninterpolated_span().rust_2018() {
1392 // `Span::rust_2018()` is somewhat expensive; don't get it repeatedly.
1393 if self.check_keyword(kw::Async) {
1394 if self.is_async_block() {
1395 // Check for `async {` and `async move {`.
1396 self.parse_async_block()
1398 self.parse_closure_expr()
1400 } else if self.eat_keyword(kw::Await) {
1401 self.recover_incorrect_await_syntax(lo, self.prev_token.span)
1403 self.parse_lit_expr()
1406 self.parse_lit_expr()
1410 fn parse_lit_expr(&mut self) -> PResult<'a, P<Expr>> {
1411 let lo = self.token.span;
1412 match self.parse_opt_lit() {
1414 let expr = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Lit(literal));
1415 self.maybe_recover_from_bad_qpath(expr)
1417 None => self.try_macro_suggestion(),
1421 fn parse_tuple_parens_expr(&mut self) -> PResult<'a, P<Expr>> {
1422 let lo = self.token.span;
1423 self.expect(&token::OpenDelim(Delimiter::Parenthesis))?;
1424 let (es, trailing_comma) = match self.parse_seq_to_end(
1425 &token::CloseDelim(Delimiter::Parenthesis),
1426 SeqSep::trailing_allowed(token::Comma),
1427 |p| p.parse_expr_catch_underscore(),
1431 return Ok(self.recover_seq_parse_error(Delimiter::Parenthesis, lo, Err(err)));
1434 let kind = if es.len() == 1 && !trailing_comma {
1435 // `(e)` is parenthesized `e`.
1436 ExprKind::Paren(es.into_iter().next().unwrap())
1438 // `(e,)` is a tuple with only one field, `e`.
1441 let expr = self.mk_expr(lo.to(self.prev_token.span), kind);
1442 self.maybe_recover_from_bad_qpath(expr)
1445 fn parse_array_or_repeat_expr(&mut self, close_delim: Delimiter) -> PResult<'a, P<Expr>> {
1446 let lo = self.token.span;
1447 self.bump(); // `[` or other open delim
1449 let close = &token::CloseDelim(close_delim);
1450 let kind = if self.eat(close) {
1452 ExprKind::Array(Vec::new())
1455 let first_expr = self.parse_expr()?;
1456 if self.eat(&token::Semi) {
1457 // Repeating array syntax: `[ 0; 512 ]`
1458 let count = self.parse_anon_const_expr()?;
1459 self.expect(close)?;
1460 ExprKind::Repeat(first_expr, count)
1461 } else if self.eat(&token::Comma) {
1462 // Vector with two or more elements.
1463 let sep = SeqSep::trailing_allowed(token::Comma);
1464 let (remaining_exprs, _) = self.parse_seq_to_end(close, sep, |p| p.parse_expr())?;
1465 let mut exprs = vec![first_expr];
1466 exprs.extend(remaining_exprs);
1467 ExprKind::Array(exprs)
1469 // Vector with one element
1470 self.expect(close)?;
1471 ExprKind::Array(vec![first_expr])
1474 let expr = self.mk_expr(lo.to(self.prev_token.span), kind);
1475 self.maybe_recover_from_bad_qpath(expr)
1478 fn parse_path_start_expr(&mut self) -> PResult<'a, P<Expr>> {
1479 let (qself, path) = if self.eat_lt() {
1480 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
1483 (None, self.parse_path(PathStyle::Expr)?)
1486 // `!`, as an operator, is prefix, so we know this isn't that.
1487 let (span, kind) = if self.eat(&token::Not) {
1488 // MACRO INVOCATION expression
1489 if qself.is_some() {
1490 self.sess.emit_err(MacroInvocationWithQualifiedPath(path.span));
1493 let mac = P(MacCall {
1495 args: self.parse_mac_args()?,
1496 prior_type_ascription: self.last_type_ascription,
1498 (lo.to(self.prev_token.span), ExprKind::MacCall(mac))
1499 } else if self.check(&token::OpenDelim(Delimiter::Brace)) &&
1500 let Some(expr) = self.maybe_parse_struct_expr(qself.as_ref(), &path) {
1501 if qself.is_some() {
1502 self.sess.gated_spans.gate(sym::more_qualified_paths, path.span);
1506 (path.span, ExprKind::Path(qself, path))
1509 let expr = self.mk_expr(span, kind);
1510 self.maybe_recover_from_bad_qpath(expr)
1513 /// Parse `'label: $expr`. The label is already parsed.
1514 fn parse_labeled_expr(
1517 mut consume_colon: bool,
1518 ) -> PResult<'a, P<Expr>> {
1519 let lo = label.ident.span;
1520 let label = Some(label);
1521 let ate_colon = self.eat(&token::Colon);
1522 let expr = if self.eat_keyword(kw::While) {
1523 self.parse_while_expr(label, lo)
1524 } else if self.eat_keyword(kw::For) {
1525 self.parse_for_expr(label, lo)
1526 } else if self.eat_keyword(kw::Loop) {
1527 self.parse_loop_expr(label, lo)
1528 } else if self.check_noexpect(&token::OpenDelim(Delimiter::Brace))
1529 || self.token.is_whole_block()
1531 self.parse_block_expr(label, lo, BlockCheckMode::Default)
1532 } else if !ate_colon
1533 && (self.check_noexpect(&TokenKind::Comma) || self.check_noexpect(&TokenKind::Gt))
1535 // We're probably inside of a `Path<'a>` that needs a turbofish
1536 self.sess.emit_err(UnexpectedTokenAfterLabel {
1537 span: self.token.span,
1539 enclose_in_block: None,
1541 consume_colon = false;
1542 Ok(self.mk_expr_err(lo))
1544 let mut err = UnexpectedTokenAfterLabel {
1545 span: self.token.span,
1547 enclose_in_block: None,
1550 // Continue as an expression in an effort to recover on `'label: non_block_expr`.
1551 let expr = self.parse_expr().map(|expr| {
1552 let span = expr.span;
1554 let found_labeled_breaks = {
1555 struct FindLabeledBreaksVisitor(bool);
1557 impl<'ast> Visitor<'ast> for FindLabeledBreaksVisitor {
1558 fn visit_expr_post(&mut self, ex: &'ast Expr) {
1559 if let ExprKind::Break(Some(_label), _) = ex.kind {
1565 let mut vis = FindLabeledBreaksVisitor(false);
1566 vis.visit_expr(&expr);
1570 // Suggestion involves adding a (as of time of writing this, unstable) labeled block.
1572 // If there are no breaks that may use this label, suggest removing the label and
1573 // recover to the unmodified expression.
1574 if !found_labeled_breaks {
1575 err.remove_label = Some(lo.until(span));
1580 err.enclose_in_block = Some(UnexpectedTokenAfterLabelSugg {
1581 left: span.shrink_to_lo(),
1582 right: span.shrink_to_hi(),
1585 // Replace `'label: non_block_expr` with `'label: {non_block_expr}` in order to suppress future errors about `break 'label`.
1586 let stmt = self.mk_stmt(span, StmtKind::Expr(expr));
1587 let blk = self.mk_block(vec![stmt], BlockCheckMode::Default, span);
1588 self.mk_expr(span, ExprKind::Block(blk, label))
1591 self.sess.emit_err(err);
1595 if !ate_colon && consume_colon {
1596 self.sess.emit_err(RequireColonAfterLabeledExpression {
1599 label_end: lo.shrink_to_hi(),
1606 /// Recover on the syntax `do catch { ... }` suggesting `try { ... }` instead.
1607 fn recover_do_catch(&mut self) -> PResult<'a, P<Expr>> {
1608 let lo = self.token.span;
1610 self.bump(); // `do`
1611 self.bump(); // `catch`
1613 let span = lo.to(self.prev_token.span);
1614 self.sess.emit_err(DoCatchSyntaxRemoved { span });
1616 self.parse_try_block(lo)
1619 /// Parse an expression if the token can begin one.
1620 fn parse_expr_opt(&mut self) -> PResult<'a, Option<P<Expr>>> {
1621 Ok(if self.token.can_begin_expr() { Some(self.parse_expr()?) } else { None })
1624 /// Parse `"return" expr?`.
1625 fn parse_return_expr(&mut self) -> PResult<'a, P<Expr>> {
1626 let lo = self.prev_token.span;
1627 let kind = ExprKind::Ret(self.parse_expr_opt()?);
1628 let expr = self.mk_expr(lo.to(self.prev_token.span), kind);
1629 self.maybe_recover_from_bad_qpath(expr)
1632 /// Parse `"do" "yeet" expr?`.
1633 fn parse_yeet_expr(&mut self) -> PResult<'a, P<Expr>> {
1634 let lo = self.token.span;
1636 self.bump(); // `do`
1637 self.bump(); // `yeet`
1639 let kind = ExprKind::Yeet(self.parse_expr_opt()?);
1641 let span = lo.to(self.prev_token.span);
1642 self.sess.gated_spans.gate(sym::yeet_expr, span);
1643 let expr = self.mk_expr(span, kind);
1644 self.maybe_recover_from_bad_qpath(expr)
1647 /// Parse `"break" (('label (:? expr)?) | expr?)` with `"break"` token already eaten.
1648 /// If the label is followed immediately by a `:` token, the label and `:` are
1649 /// parsed as part of the expression (i.e. a labeled loop). The language team has
1650 /// decided in #87026 to require parentheses as a visual aid to avoid confusion if
1651 /// the break expression of an unlabeled break is a labeled loop (as in
1652 /// `break 'lbl: loop {}`); a labeled break with an unlabeled loop as its value
1653 /// expression only gets a warning for compatibility reasons; and a labeled break
1654 /// with a labeled loop does not even get a warning because there is no ambiguity.
1655 fn parse_break_expr(&mut self) -> PResult<'a, P<Expr>> {
1656 let lo = self.prev_token.span;
1657 let mut label = self.eat_label();
1658 let kind = if label.is_some() && self.token == token::Colon {
1659 // The value expression can be a labeled loop, see issue #86948, e.g.:
1660 // `loop { break 'label: loop { break 'label 42; }; }`
1661 let lexpr = self.parse_labeled_expr(label.take().unwrap(), true)?;
1662 self.sess.emit_err(LabeledLoopInBreak {
1664 sub: WrapExpressionInParentheses {
1665 left: lexpr.span.shrink_to_lo(),
1666 right: lexpr.span.shrink_to_hi(),
1670 } else if self.token != token::OpenDelim(Delimiter::Brace)
1671 || !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
1673 let expr = self.parse_expr_opt()?;
1674 if let Some(ref expr) = expr {
1678 ExprKind::While(_, _, None)
1679 | ExprKind::ForLoop(_, _, _, None)
1680 | ExprKind::Loop(_, None)
1681 | ExprKind::Block(_, None)
1684 self.sess.buffer_lint_with_diagnostic(
1685 BREAK_WITH_LABEL_AND_LOOP,
1688 "this labeled break expression is easy to confuse with an unlabeled break with a labeled value expression",
1689 BuiltinLintDiagnostics::BreakWithLabelAndLoop(expr.span),
1697 let expr = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Break(label, kind));
1698 self.maybe_recover_from_bad_qpath(expr)
1701 /// Parse `"yield" expr?`.
1702 fn parse_yield_expr(&mut self) -> PResult<'a, P<Expr>> {
1703 let lo = self.prev_token.span;
1704 let kind = ExprKind::Yield(self.parse_expr_opt()?);
1705 let span = lo.to(self.prev_token.span);
1706 self.sess.gated_spans.gate(sym::generators, span);
1707 let expr = self.mk_expr(span, kind);
1708 self.maybe_recover_from_bad_qpath(expr)
1711 /// Returns a string literal if the next token is a string literal.
1712 /// In case of error returns `Some(lit)` if the next token is a literal with a wrong kind,
1713 /// and returns `None` if the next token is not literal at all.
1714 pub fn parse_str_lit(&mut self) -> Result<ast::StrLit, Option<Lit>> {
1715 match self.parse_opt_lit() {
1716 Some(lit) => match lit.kind {
1717 ast::LitKind::Str(symbol_unescaped, style) => Ok(ast::StrLit {
1719 symbol: lit.token_lit.symbol,
1720 suffix: lit.token_lit.suffix,
1724 _ => Err(Some(lit)),
1730 pub(super) fn parse_lit(&mut self) -> PResult<'a, Lit> {
1731 self.parse_opt_lit().ok_or_else(|| {
1732 if let token::Interpolated(inner) = &self.token.kind {
1733 let expr = match inner.as_ref() {
1734 token::NtExpr(expr) => Some(expr),
1735 token::NtLiteral(expr) => Some(expr),
1738 if let Some(expr) = expr {
1739 if matches!(expr.kind, ExprKind::Err) {
1740 let mut err = InvalidInterpolatedExpression { span: self.token.span }
1741 .into_diagnostic(&self.sess.span_diagnostic);
1742 err.downgrade_to_delayed_bug();
1747 let msg = format!("unexpected token: {}", super::token_descr(&self.token));
1748 self.struct_span_err(self.token.span, &msg)
1752 /// Matches `lit = true | false | token_lit`.
1753 /// Returns `None` if the next token is not a literal.
1754 pub(super) fn parse_opt_lit(&mut self) -> Option<Lit> {
1755 let mut recovered = None;
1756 if self.token == token::Dot {
1757 // Attempt to recover `.4` as `0.4`. We don't currently have any syntax where
1758 // dot would follow an optional literal, so we do this unconditionally.
1759 recovered = self.look_ahead(1, |next_token| {
1760 if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) =
1763 if self.token.span.hi() == next_token.span.lo() {
1764 let s = String::from("0.") + symbol.as_str();
1765 let kind = TokenKind::lit(token::Float, Symbol::intern(&s), suffix);
1766 return Some(Token::new(kind, self.token.span.to(next_token.span)));
1771 if let Some(token) = &recovered {
1773 self.sess.emit_err(FloatLiteralRequiresIntegerPart {
1775 correct: pprust::token_to_string(token).into_owned(),
1780 let token = recovered.as_ref().unwrap_or(&self.token);
1781 match Lit::from_token(token) {
1786 Err(LitError::NotLiteral) => None,
1788 let span = token.span;
1789 let token::Literal(lit) = token.kind else {
1793 self.report_lit_error(err, lit, span);
1794 // Pack possible quotes and prefixes from the original literal into
1795 // the error literal's symbol so they can be pretty-printed faithfully.
1796 let suffixless_lit = token::Lit::new(lit.kind, lit.symbol, None);
1797 let symbol = Symbol::intern(&suffixless_lit.to_string());
1798 let lit = token::Lit::new(token::Err, symbol, lit.suffix);
1799 Some(Lit::from_token_lit(lit, span).unwrap_or_else(|_| unreachable!()))
1804 fn report_lit_error(&self, err: LitError, lit: token::Lit, span: Span) {
1805 // Checks if `s` looks like i32 or u1234 etc.
1806 fn looks_like_width_suffix(first_chars: &[char], s: &str) -> bool {
1807 s.len() > 1 && s.starts_with(first_chars) && s[1..].chars().all(|c| c.is_ascii_digit())
1810 // Try to lowercase the prefix if it's a valid base prefix.
1811 fn fix_base_capitalisation(s: &str) -> Option<String> {
1812 if let Some(stripped) = s.strip_prefix('B') {
1813 Some(format!("0b{stripped}"))
1814 } else if let Some(stripped) = s.strip_prefix('O') {
1815 Some(format!("0o{stripped}"))
1816 } else if let Some(stripped) = s.strip_prefix('X') {
1817 Some(format!("0x{stripped}"))
1823 let token::Lit { kind, suffix, .. } = lit;
1825 // `NotLiteral` is not an error by itself, so we don't report
1826 // it and give the parser opportunity to try something else.
1827 LitError::NotLiteral => {}
1828 // `LexerError` *is* an error, but it was already reported
1829 // by lexer, so here we don't report it the second time.
1830 LitError::LexerError => {}
1831 LitError::InvalidSuffix => {
1832 if let Some(suffix) = suffix {
1833 self.sess.emit_err(InvalidLiteralSuffix {
1835 kind: format!("{}", kind.descr()),
1840 LitError::InvalidIntSuffix => {
1841 let suf = suffix.expect("suffix error with no suffix");
1842 let suf = suf.as_str();
1843 if looks_like_width_suffix(&['i', 'u'], &suf) {
1844 // If it looks like a width, try to be helpful.
1845 self.sess.emit_err(InvalidIntLiteralWidth { span, width: suf[1..].into() });
1846 } else if let Some(fixed) = fix_base_capitalisation(suf) {
1847 self.sess.emit_err(InvalidNumLiteralBasePrefix { span, fixed });
1849 self.sess.emit_err(InvalidNumLiteralSuffix { span, suffix: suf.to_string() });
1852 LitError::InvalidFloatSuffix => {
1853 let suf = suffix.expect("suffix error with no suffix");
1854 let suf = suf.as_str();
1855 if looks_like_width_suffix(&['f'], suf) {
1856 // If it looks like a width, try to be helpful.
1858 .emit_err(InvalidFloatLiteralWidth { span, width: suf[1..].to_string() });
1860 self.sess.emit_err(InvalidFloatLiteralSuffix { span, suffix: suf.to_string() });
1863 LitError::NonDecimalFloat(base) => {
1865 16 => self.sess.emit_err(HexadecimalFloatLiteralNotSupported { span }),
1866 8 => self.sess.emit_err(OctalFloatLiteralNotSupported { span }),
1867 2 => self.sess.emit_err(BinaryFloatLiteralNotSupported { span }),
1868 _ => unreachable!(),
1871 LitError::IntTooLarge => {
1872 self.sess.emit_err(IntLiteralTooLarge { span });
1877 pub(super) fn expect_no_tuple_index_suffix(&self, span: Span, suffix: Symbol) {
1878 if [sym::i32, sym::u32, sym::isize, sym::usize].contains(&suffix) {
1879 // #59553: warn instead of reject out of hand to allow the fix to percolate
1880 // through the ecosystem when people fix their macros
1881 self.sess.emit_warning(InvalidLiteralSuffixOnTupleIndex {
1884 exception: Some(()),
1887 self.sess.emit_err(InvalidLiteralSuffixOnTupleIndex { span, suffix, exception: None });
1891 /// Matches `'-' lit | lit` (cf. `ast_validation::AstValidator::check_expr_within_pat`).
1892 /// Keep this in sync with `Token::can_begin_literal_maybe_minus`.
1893 pub fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1894 maybe_whole_expr!(self);
1896 let lo = self.token.span;
1897 let minus_present = self.eat(&token::BinOp(token::Minus));
1898 let lit = self.parse_lit()?;
1899 let expr = self.mk_expr(lit.span, ExprKind::Lit(lit));
1902 Ok(self.mk_expr(lo.to(self.prev_token.span), self.mk_unary(UnOp::Neg, expr)))
1908 fn is_array_like_block(&mut self) -> bool {
1909 self.look_ahead(1, |t| matches!(t.kind, TokenKind::Ident(..) | TokenKind::Literal(_)))
1910 && self.look_ahead(2, |t| t == &token::Comma)
1911 && self.look_ahead(3, |t| t.can_begin_expr())
1914 /// Emits a suggestion if it looks like the user meant an array but
1915 /// accidentally used braces, causing the code to be interpreted as a block
1917 fn maybe_suggest_brackets_instead_of_braces(&mut self, lo: Span) -> Option<P<Expr>> {
1918 let mut snapshot = self.create_snapshot_for_diagnostic();
1919 match snapshot.parse_array_or_repeat_expr(Delimiter::Brace) {
1921 self.sess.emit_err(ArrayBracketsInsteadOfSpaces {
1923 sub: ArrayBracketsInsteadOfSpacesSugg {
1925 right: snapshot.prev_token.span,
1929 self.restore_snapshot(snapshot);
1930 Some(self.mk_expr_err(arr.span))
1939 fn suggest_missing_semicolon_before_array(
1942 open_delim_span: Span,
1943 ) -> PResult<'a, ()> {
1944 if self.token.kind == token::Comma {
1945 if !self.sess.source_map().is_multiline(prev_span.until(self.token.span)) {
1948 let mut snapshot = self.create_snapshot_for_diagnostic();
1950 match snapshot.parse_seq_to_before_end(
1951 &token::CloseDelim(Delimiter::Bracket),
1952 SeqSep::trailing_allowed(token::Comma),
1956 // When the close delim is `)`, `token.kind` is expected to be `token::CloseDelim(Delimiter::Parenthesis)`,
1957 // but the actual `token.kind` is `token::CloseDelim(Delimiter::Bracket)`.
1958 // This is because the `token.kind` of the close delim is treated as the same as
1959 // that of the open delim in `TokenTreesReader::parse_token_tree`, even if the delimiters of them are different.
1960 // Therefore, `token.kind` should not be compared here.
1962 .span_to_snippet(snapshot.token.span)
1963 .map_or(false, |snippet| snippet == "]") =>
1965 return Err(MissingSemicolonBeforeArray {
1966 open_delim: open_delim_span,
1967 semicolon: prev_span.shrink_to_hi(),
1968 }.into_diagnostic(&self.sess.span_diagnostic));
1971 Err(err) => err.cancel(),
1977 /// Parses a block or unsafe block.
1978 pub(super) fn parse_block_expr(
1980 opt_label: Option<Label>,
1982 blk_mode: BlockCheckMode,
1983 ) -> PResult<'a, P<Expr>> {
1984 if self.is_array_like_block() {
1985 if let Some(arr) = self.maybe_suggest_brackets_instead_of_braces(lo) {
1990 if self.token.is_whole_block() {
1991 self.sess.emit_err(InvalidBlockMacroSegment {
1992 span: self.token.span,
1993 context: lo.to(self.token.span),
1997 let (attrs, blk) = self.parse_block_common(lo, blk_mode)?;
1998 Ok(self.mk_expr_with_attrs(blk.span, ExprKind::Block(blk, opt_label), attrs))
2001 /// Parse a block which takes no attributes and has no label
2002 fn parse_simple_block(&mut self) -> PResult<'a, P<Expr>> {
2003 let blk = self.parse_block()?;
2004 Ok(self.mk_expr(blk.span, ExprKind::Block(blk, None)))
2007 /// Parses a closure expression (e.g., `move |args| expr`).
2008 fn parse_closure_expr(&mut self) -> PResult<'a, P<Expr>> {
2009 let lo = self.token.span;
2011 let binder = if self.check_keyword(kw::For) {
2012 let lo = self.token.span;
2013 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
2014 let span = lo.to(self.prev_token.span);
2016 self.sess.gated_spans.gate(sym::closure_lifetime_binder, span);
2018 ClosureBinder::For { span, generic_params: P::from_vec(lifetime_defs) }
2020 ClosureBinder::NotPresent
2024 if self.eat_keyword(kw::Static) { Movability::Static } else { Movability::Movable };
2026 let asyncness = if self.token.uninterpolated_span().rust_2018() {
2027 self.parse_asyncness()
2032 let capture_clause = self.parse_capture_clause()?;
2033 let decl = self.parse_fn_block_decl()?;
2034 let decl_hi = self.prev_token.span;
2035 let mut body = match decl.output {
2036 FnRetTy::Default(_) => {
2037 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
2038 self.parse_expr_res(restrictions, None)?
2041 // If an explicit return type is given, require a block to appear (RFC 968).
2042 let body_lo = self.token.span;
2043 self.parse_block_expr(None, body_lo, BlockCheckMode::Default)?
2047 if let Async::Yes { span, .. } = asyncness {
2048 // Feature-gate `async ||` closures.
2049 self.sess.gated_spans.gate(sym::async_closure, span);
2052 if self.token.kind == TokenKind::Semi
2053 && matches!(self.token_cursor.frame.delim_sp, Some((Delimiter::Parenthesis, _)))
2055 // It is likely that the closure body is a block but where the
2056 // braces have been removed. We will recover and eat the next
2057 // statements later in the parsing process.
2058 body = self.mk_expr_err(body.span);
2061 let body_span = body.span;
2063 let closure = self.mk_expr(
2076 // Disable recovery for closure body
2078 ClosureSpans { whole_closure: closure.span, closing_pipe: decl_hi, body: body_span };
2079 self.current_closure = Some(spans);
2084 /// Parses an optional `move` prefix to a closure-like construct.
2085 fn parse_capture_clause(&mut self) -> PResult<'a, CaptureBy> {
2086 if self.eat_keyword(kw::Move) {
2087 // Check for `move async` and recover
2088 if self.check_keyword(kw::Async) {
2089 let move_async_span = self.token.span.with_lo(self.prev_token.span.data().lo);
2090 Err(AsyncMoveOrderIncorrect { span: move_async_span }
2091 .into_diagnostic(&self.sess.span_diagnostic))
2093 Ok(CaptureBy::Value)
2100 /// Parses the `|arg, arg|` header of a closure.
2101 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
2102 let inputs = if self.eat(&token::OrOr) {
2105 self.expect(&token::BinOp(token::Or))?;
2107 .parse_seq_to_before_tokens(
2108 &[&token::BinOp(token::Or), &token::OrOr],
2109 SeqSep::trailing_allowed(token::Comma),
2110 TokenExpectType::NoExpect,
2111 |p| p.parse_fn_block_param(),
2118 self.parse_ret_ty(AllowPlus::Yes, RecoverQPath::Yes, RecoverReturnSign::Yes)?;
2120 Ok(P(FnDecl { inputs, output }))
2123 /// Parses a parameter in a closure header (e.g., `|arg, arg|`).
2124 fn parse_fn_block_param(&mut self) -> PResult<'a, Param> {
2125 let lo = self.token.span;
2126 let attrs = self.parse_outer_attributes()?;
2127 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
2128 let pat = this.parse_pat_no_top_alt(PARAM_EXPECTED)?;
2129 let ty = if this.eat(&token::Colon) {
2132 this.mk_ty(this.prev_token.span, TyKind::Infer)
2140 span: lo.to(this.prev_token.span),
2142 is_placeholder: false,
2144 TrailingToken::MaybeComma,
2149 /// Parses an `if` expression (`if` token already eaten).
2150 fn parse_if_expr(&mut self) -> PResult<'a, P<Expr>> {
2151 let lo = self.prev_token.span;
2152 let cond = self.parse_cond_expr()?;
2153 self.parse_if_after_cond(lo, cond)
2156 fn parse_if_after_cond(&mut self, lo: Span, mut cond: P<Expr>) -> PResult<'a, P<Expr>> {
2157 let cond_span = cond.span;
2158 // Tries to interpret `cond` as either a missing expression if it's a block,
2159 // or as an unfinished expression if it's a binop and the RHS is a block.
2160 // We could probably add more recoveries here too...
2161 let mut recover_block_from_condition = |this: &mut Self| {
2162 let block = match &mut cond.kind {
2163 ExprKind::Binary(Spanned { span: binop_span, .. }, _, right)
2164 if let ExprKind::Block(_, None) = right.kind => {
2165 self.sess.emit_err(IfExpressionMissingThenBlock {
2167 sub: IfExpressionMissingThenBlockSub::UnfinishedCondition(
2168 cond_span.shrink_to_lo().to(*binop_span)
2171 std::mem::replace(right, this.mk_expr_err(binop_span.shrink_to_hi()))
2173 ExprKind::Block(_, None) => {
2174 self.sess.emit_err(IfExpressionMissingCondition {
2175 if_span: self.sess.source_map().next_point(lo),
2176 block_span: self.sess.source_map().start_point(cond_span),
2178 std::mem::replace(&mut cond, this.mk_expr_err(cond_span.shrink_to_hi()))
2184 if let ExprKind::Block(block, _) = &block.kind {
2191 let thn = if self.token.is_keyword(kw::Else) {
2192 if let Some(block) = recover_block_from_condition(self) {
2195 self.sess.emit_err(IfExpressionMissingThenBlock {
2197 sub: IfExpressionMissingThenBlockSub::AddThenBlock(cond_span.shrink_to_hi()),
2199 self.mk_block_err(cond_span.shrink_to_hi())
2202 let attrs = self.parse_outer_attributes()?.take_for_recovery(); // For recovery.
2203 let block = if self.check(&token::OpenDelim(Delimiter::Brace)) {
2206 if let Some(block) = recover_block_from_condition(self) {
2209 // Parse block, which will always fail, but we can add a nice note to the error
2210 self.parse_block().map_err(|mut err| {
2213 "the `if` expression is missing a block after this condition",
2219 self.error_on_if_block_attrs(lo, false, block.span, &attrs);
2222 let els = if self.eat_keyword(kw::Else) { Some(self.parse_else_expr()?) } else { None };
2223 Ok(self.mk_expr(lo.to(self.prev_token.span), ExprKind::If(cond, thn, els)))
2226 /// Parses the condition of a `if` or `while` expression.
2227 fn parse_cond_expr(&mut self) -> PResult<'a, P<Expr>> {
2229 self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL | Restrictions::ALLOW_LET, None)?;
2231 if let ExprKind::Let(..) = cond.kind {
2232 // Remove the last feature gating of a `let` expression since it's stable.
2233 self.sess.gated_spans.ungate_last(sym::let_chains, cond.span);
2239 /// Parses a `let $pat = $expr` pseudo-expression.
2240 fn parse_let_expr(&mut self) -> PResult<'a, P<Expr>> {
2241 // This is a *approximate* heuristic that detects if `let` chains are
2242 // being parsed in the right position. It's approximate because it
2243 // doesn't deny all invalid `let` expressions, just completely wrong usages.
2244 let not_in_chain = !matches!(
2245 self.prev_token.kind,
2246 TokenKind::AndAnd | TokenKind::Ident(kw::If, _) | TokenKind::Ident(kw::While, _)
2248 if !self.restrictions.contains(Restrictions::ALLOW_LET) || not_in_chain {
2249 self.sess.emit_err(ExpectedExpressionFoundLet { span: self.token.span });
2252 self.bump(); // Eat `let` token
2253 let lo = self.prev_token.span;
2254 let pat = self.parse_pat_allow_top_alt(
2258 CommaRecoveryMode::LikelyTuple,
2260 self.expect(&token::Eq)?;
2261 let expr = self.with_res(self.restrictions | Restrictions::NO_STRUCT_LITERAL, |this| {
2262 this.parse_assoc_expr_with(1 + prec_let_scrutinee_needs_par(), None.into())
2264 let span = lo.to(expr.span);
2265 self.sess.gated_spans.gate(sym::let_chains, span);
2266 Ok(self.mk_expr(span, ExprKind::Let(pat, expr, span)))
2269 /// Parses an `else { ... }` expression (`else` token already eaten).
2270 fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
2271 let else_span = self.prev_token.span; // `else`
2272 let attrs = self.parse_outer_attributes()?.take_for_recovery(); // For recovery.
2273 let expr = if self.eat_keyword(kw::If) {
2274 self.parse_if_expr()?
2275 } else if self.check(&TokenKind::OpenDelim(Delimiter::Brace)) {
2276 self.parse_simple_block()?
2278 let snapshot = self.create_snapshot_for_diagnostic();
2279 let first_tok = super::token_descr(&self.token);
2280 let first_tok_span = self.token.span;
2281 match self.parse_expr() {
2283 // If it's not a free-standing expression, and is followed by a block,
2284 // then it's very likely the condition to an `else if`.
2285 if self.check(&TokenKind::OpenDelim(Delimiter::Brace))
2286 && classify::expr_requires_semi_to_be_stmt(&cond) =>
2288 self.sess.emit_err(ExpectedElseBlock {
2292 condition_start: cond.span.shrink_to_lo(),
2294 self.parse_if_after_cond(cond.span.shrink_to_lo(), cond)?
2298 self.restore_snapshot(snapshot);
2299 self.parse_simple_block()?
2302 self.restore_snapshot(snapshot);
2303 self.parse_simple_block()?
2307 self.error_on_if_block_attrs(else_span, true, expr.span, &attrs);
2311 fn error_on_if_block_attrs(
2316 attrs: &[ast::Attribute],
2318 let (attributes, last) = match attrs {
2320 [x0 @ xn] | [x0, .., xn] => (x0.span.to(xn.span), xn.span),
2322 let ctx = if is_ctx_else { "else" } else { "if" };
2323 self.sess.emit_err(OuterAttributeNotAllowedOnIfElse {
2327 ctx: ctx.to_string(),
2332 /// Parses `for <src_pat> in <src_expr> <src_loop_block>` (`for` token already eaten).
2333 fn parse_for_expr(&mut self, opt_label: Option<Label>, lo: Span) -> PResult<'a, P<Expr>> {
2334 // Record whether we are about to parse `for (`.
2335 // This is used below for recovery in case of `for ( $stuff ) $block`
2336 // in which case we will suggest `for $stuff $block`.
2337 let begin_paren = match self.token.kind {
2338 token::OpenDelim(Delimiter::Parenthesis) => Some(self.token.span),
2342 let pat = self.parse_pat_allow_top_alt(
2346 CommaRecoveryMode::LikelyTuple,
2348 if !self.eat_keyword(kw::In) {
2349 self.error_missing_in_for_loop();
2351 self.check_for_for_in_in_typo(self.prev_token.span);
2352 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
2354 let pat = self.recover_parens_around_for_head(pat, begin_paren);
2356 let (attrs, loop_block) = self.parse_inner_attrs_and_block()?;
2358 let kind = ExprKind::ForLoop(pat, expr, loop_block, opt_label);
2359 Ok(self.mk_expr_with_attrs(lo.to(self.prev_token.span), kind, attrs))
2362 fn error_missing_in_for_loop(&mut self) {
2363 let (span, sub): (_, fn(_) -> _) = if self.token.is_ident_named(sym::of) {
2364 // Possibly using JS syntax (#75311).
2365 let span = self.token.span;
2367 (span, MissingInInForLoopSub::InNotOf)
2369 (self.prev_token.span.between(self.token.span), MissingInInForLoopSub::AddIn)
2372 self.sess.emit_err(MissingInInForLoop { span, sub: sub(span) });
2375 /// Parses a `while` or `while let` expression (`while` token already eaten).
2376 fn parse_while_expr(&mut self, opt_label: Option<Label>, lo: Span) -> PResult<'a, P<Expr>> {
2377 let cond = self.parse_cond_expr().map_err(|mut err| {
2378 err.span_label(lo, "while parsing the condition of this `while` expression");
2381 let (attrs, body) = self.parse_inner_attrs_and_block().map_err(|mut err| {
2382 err.span_label(lo, "while parsing the body of this `while` expression");
2383 err.span_label(cond.span, "this `while` condition successfully parsed");
2386 Ok(self.mk_expr_with_attrs(
2387 lo.to(self.prev_token.span),
2388 ExprKind::While(cond, body, opt_label),
2393 /// Parses `loop { ... }` (`loop` token already eaten).
2394 fn parse_loop_expr(&mut self, opt_label: Option<Label>, lo: Span) -> PResult<'a, P<Expr>> {
2395 let (attrs, body) = self.parse_inner_attrs_and_block()?;
2396 Ok(self.mk_expr_with_attrs(
2397 lo.to(self.prev_token.span),
2398 ExprKind::Loop(body, opt_label),
2403 pub(crate) fn eat_label(&mut self) -> Option<Label> {
2404 self.token.lifetime().map(|ident| {
2410 /// Parses a `match ... { ... }` expression (`match` token already eaten).
2411 fn parse_match_expr(&mut self) -> PResult<'a, P<Expr>> {
2412 let match_span = self.prev_token.span;
2413 let lo = self.prev_token.span;
2414 let scrutinee = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
2415 if let Err(mut e) = self.expect(&token::OpenDelim(Delimiter::Brace)) {
2416 if self.token == token::Semi {
2417 e.span_suggestion_short(
2419 "try removing this `match`",
2421 Applicability::MaybeIncorrect, // speculative
2424 if self.maybe_recover_unexpected_block_label() {
2431 let attrs = self.parse_inner_attributes()?;
2433 let mut arms: Vec<Arm> = Vec::new();
2434 while self.token != token::CloseDelim(Delimiter::Brace) {
2435 match self.parse_arm() {
2436 Ok(arm) => arms.push(arm),
2438 // Recover by skipping to the end of the block.
2440 self.recover_stmt();
2441 let span = lo.to(self.token.span);
2442 if self.token == token::CloseDelim(Delimiter::Brace) {
2445 return Ok(self.mk_expr_with_attrs(
2447 ExprKind::Match(scrutinee, arms),
2453 let hi = self.token.span;
2455 Ok(self.mk_expr_with_attrs(lo.to(hi), ExprKind::Match(scrutinee, arms), attrs))
2458 /// Attempt to recover from match arm body with statements and no surrounding braces.
2459 fn parse_arm_body_missing_braces(
2461 first_expr: &P<Expr>,
2463 ) -> Option<P<Expr>> {
2464 if self.token.kind != token::Semi {
2467 let start_snapshot = self.create_snapshot_for_diagnostic();
2468 let semi_sp = self.token.span;
2471 vec![self.mk_stmt(first_expr.span, ast::StmtKind::Expr(first_expr.clone()))];
2472 let err = |this: &Parser<'_>, stmts: Vec<ast::Stmt>| {
2473 let span = stmts[0].span.to(stmts[stmts.len() - 1].span);
2475 this.sess.emit_err(MatchArmBodyWithoutBraces {
2478 num_statements: stmts.len(),
2479 sub: if stmts.len() > 1 {
2480 MatchArmBodyWithoutBracesSugg::AddBraces {
2481 left: span.shrink_to_lo(),
2482 right: span.shrink_to_hi(),
2485 MatchArmBodyWithoutBracesSugg::UseComma { semicolon: semi_sp }
2488 this.mk_expr_err(span)
2490 // We might have either a `,` -> `;` typo, or a block without braces. We need
2491 // a more subtle parsing strategy.
2493 if self.token.kind == token::CloseDelim(Delimiter::Brace) {
2494 // We have reached the closing brace of the `match` expression.
2495 return Some(err(self, stmts));
2497 if self.token.kind == token::Comma {
2498 self.restore_snapshot(start_snapshot);
2501 let pre_pat_snapshot = self.create_snapshot_for_diagnostic();
2502 match self.parse_pat_no_top_alt(None) {
2504 if self.token.kind == token::FatArrow {
2506 self.restore_snapshot(pre_pat_snapshot);
2507 return Some(err(self, stmts));
2515 self.restore_snapshot(pre_pat_snapshot);
2516 match self.parse_stmt_without_recovery(true, ForceCollect::No) {
2517 // Consume statements for as long as possible.
2522 self.restore_snapshot(start_snapshot);
2525 // We couldn't parse either yet another statement missing it's
2526 // enclosing block nor the next arm's pattern or closing brace.
2529 self.restore_snapshot(start_snapshot);
2537 pub(super) fn parse_arm(&mut self) -> PResult<'a, Arm> {
2538 // Used to check the `let_chains` and `if_let_guard` features mostly by scanning
2540 fn check_let_expr(expr: &Expr) -> (bool, bool) {
2542 ExprKind::Binary(BinOp { node: BinOpKind::And, .. }, ref lhs, ref rhs) => {
2543 let lhs_rslt = check_let_expr(lhs);
2544 let rhs_rslt = check_let_expr(rhs);
2545 (lhs_rslt.0 || rhs_rslt.0, false)
2547 ExprKind::Let(..) => (true, true),
2551 let attrs = self.parse_outer_attributes()?;
2552 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
2553 let lo = this.token.span;
2554 let pat = this.parse_pat_allow_top_alt(
2558 CommaRecoveryMode::EitherTupleOrPipe,
2560 let guard = if this.eat_keyword(kw::If) {
2561 let if_span = this.prev_token.span;
2562 let cond = this.parse_expr_res(Restrictions::ALLOW_LET, None)?;
2563 let (has_let_expr, does_not_have_bin_op) = check_let_expr(&cond);
2565 if does_not_have_bin_op {
2566 // Remove the last feature gating of a `let` expression since it's stable.
2567 this.sess.gated_spans.ungate_last(sym::let_chains, cond.span);
2569 let span = if_span.to(cond.span);
2570 this.sess.gated_spans.gate(sym::if_let_guard, span);
2576 let arrow_span = this.token.span;
2577 if let Err(mut err) = this.expect(&token::FatArrow) {
2578 // We might have a `=>` -> `=` or `->` typo (issue #89396).
2579 if TokenKind::FatArrow
2581 .map_or(false, |similar_tokens| similar_tokens.contains(&this.token.kind))
2583 err.span_suggestion(
2585 "try using a fat arrow here",
2587 Applicability::MaybeIncorrect,
2595 let arm_start_span = this.token.span;
2597 let expr = this.parse_expr_res(Restrictions::STMT_EXPR, None).map_err(|mut err| {
2598 err.span_label(arrow_span, "while parsing the `match` arm starting here");
2602 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
2603 && this.token != token::CloseDelim(Delimiter::Brace);
2605 let hi = this.prev_token.span;
2608 let sm = this.sess.source_map();
2609 if let Some(body) = this.parse_arm_body_missing_braces(&expr, arrow_span) {
2610 let span = body.span;
2619 is_placeholder: false,
2621 TrailingToken::None,
2624 this.expect_one_of(&[token::Comma], &[token::CloseDelim(Delimiter::Brace)])
2625 .or_else(|mut err| {
2626 if this.token == token::FatArrow {
2627 if let Ok(expr_lines) = sm.span_to_lines(expr.span)
2628 && let Ok(arm_start_lines) = sm.span_to_lines(arm_start_span)
2629 && arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col
2630 && expr_lines.lines.len() == 2
2632 // We check whether there's any trailing code in the parse span,
2633 // if there isn't, we very likely have the following:
2636 // | -- - missing comma
2640 // | - ^^ self.token.span
2642 // | parsed until here as `"y" & X`
2643 err.span_suggestion_short(
2644 arm_start_span.shrink_to_hi(),
2645 "missing a comma here to end this `match` arm",
2647 Applicability::MachineApplicable,
2652 // FIXME(compiler-errors): We could also recover `; PAT =>` here
2654 // Try to parse a following `PAT =>`, if successful
2655 // then we should recover.
2656 let mut snapshot = this.create_snapshot_for_diagnostic();
2657 let pattern_follows = snapshot
2658 .parse_pat_allow_top_alt(
2662 CommaRecoveryMode::EitherTupleOrPipe,
2664 .map_err(|err| err.cancel())
2666 if pattern_follows && snapshot.check(&TokenKind::FatArrow) {
2668 this.sess.emit_err(MissingCommaAfterMatchArm {
2669 span: hi.shrink_to_hi(),
2674 err.span_label(arrow_span, "while parsing the `match` arm starting here");
2678 this.eat(&token::Comma);
2689 is_placeholder: false,
2691 TrailingToken::None,
2696 /// Parses a `try {...}` expression (`try` token already eaten).
2697 fn parse_try_block(&mut self, span_lo: Span) -> PResult<'a, P<Expr>> {
2698 let (attrs, body) = self.parse_inner_attrs_and_block()?;
2699 if self.eat_keyword(kw::Catch) {
2700 Err(CatchAfterTry { span: self.prev_token.span }
2701 .into_diagnostic(&self.sess.span_diagnostic))
2703 let span = span_lo.to(body.span);
2704 self.sess.gated_spans.gate(sym::try_blocks, span);
2705 Ok(self.mk_expr_with_attrs(span, ExprKind::TryBlock(body), attrs))
2709 fn is_do_catch_block(&self) -> bool {
2710 self.token.is_keyword(kw::Do)
2711 && self.is_keyword_ahead(1, &[kw::Catch])
2712 && self.look_ahead(2, |t| *t == token::OpenDelim(Delimiter::Brace))
2713 && !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
2716 fn is_do_yeet(&self) -> bool {
2717 self.token.is_keyword(kw::Do) && self.is_keyword_ahead(1, &[kw::Yeet])
2720 fn is_try_block(&self) -> bool {
2721 self.token.is_keyword(kw::Try)
2722 && self.look_ahead(1, |t| *t == token::OpenDelim(Delimiter::Brace))
2723 && self.token.uninterpolated_span().rust_2018()
2726 /// Parses an `async move? {...}` expression.
2727 fn parse_async_block(&mut self) -> PResult<'a, P<Expr>> {
2728 let lo = self.token.span;
2729 self.expect_keyword(kw::Async)?;
2730 let capture_clause = self.parse_capture_clause()?;
2731 let (attrs, body) = self.parse_inner_attrs_and_block()?;
2732 let kind = ExprKind::Async(capture_clause, DUMMY_NODE_ID, body);
2733 Ok(self.mk_expr_with_attrs(lo.to(self.prev_token.span), kind, attrs))
2736 fn is_async_block(&self) -> bool {
2737 self.token.is_keyword(kw::Async)
2740 self.is_keyword_ahead(1, &[kw::Move])
2741 && self.look_ahead(2, |t| *t == token::OpenDelim(Delimiter::Brace))
2744 self.look_ahead(1, |t| *t == token::OpenDelim(Delimiter::Brace))
2748 fn is_certainly_not_a_block(&self) -> bool {
2749 self.look_ahead(1, |t| t.is_ident())
2751 // `{ ident, ` cannot start a block.
2752 self.look_ahead(2, |t| t == &token::Comma)
2753 || self.look_ahead(2, |t| t == &token::Colon)
2755 // `{ ident: token, ` cannot start a block.
2756 self.look_ahead(4, |t| t == &token::Comma) ||
2757 // `{ ident: ` cannot start a block unless it's a type ascription `ident: Type`.
2758 self.look_ahead(3, |t| !t.can_begin_type())
2763 fn maybe_parse_struct_expr(
2765 qself: Option<&ast::QSelf>,
2767 ) -> Option<PResult<'a, P<Expr>>> {
2768 let struct_allowed = !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
2769 if struct_allowed || self.is_certainly_not_a_block() {
2770 if let Err(err) = self.expect(&token::OpenDelim(Delimiter::Brace)) {
2771 return Some(Err(err));
2773 let expr = self.parse_struct_expr(qself.cloned(), path.clone(), true);
2774 if let (Ok(expr), false) = (&expr, struct_allowed) {
2775 // This is a struct literal, but we don't can't accept them here.
2776 self.sess.emit_err(StructLiteralNotAllowedHere {
2778 sub: StructLiteralNotAllowedHereSugg {
2779 left: path.span.shrink_to_lo(),
2780 right: expr.span.shrink_to_hi(),
2789 pub(super) fn parse_struct_fields(
2793 close_delim: Delimiter,
2794 ) -> PResult<'a, (Vec<ExprField>, ast::StructRest, bool)> {
2795 let mut fields = Vec::new();
2796 let mut base = ast::StructRest::None;
2797 let mut recover_async = false;
2799 let mut async_block_err = |e: &mut Diagnostic, span: Span| {
2800 recover_async = true;
2801 e.span_label(span, "`async` blocks are only allowed in Rust 2018 or later");
2802 e.help_use_latest_edition();
2805 while self.token != token::CloseDelim(close_delim) {
2806 if self.eat(&token::DotDot) {
2807 let exp_span = self.prev_token.span;
2808 // We permit `.. }` on the left-hand side of a destructuring assignment.
2809 if self.check(&token::CloseDelim(close_delim)) {
2810 base = ast::StructRest::Rest(self.prev_token.span.shrink_to_hi());
2813 match self.parse_expr() {
2814 Ok(e) => base = ast::StructRest::Base(e),
2815 Err(mut e) if recover => {
2817 self.recover_stmt();
2819 Err(e) => return Err(e),
2821 self.recover_struct_comma_after_dotdot(exp_span);
2825 let recovery_field = self.find_struct_error_after_field_looking_code();
2826 let parsed_field = match self.parse_expr_field() {
2829 if pth == kw::Async {
2830 async_block_err(&mut e, pth.span);
2832 e.span_label(pth.span, "while parsing this struct");
2836 // If the next token is a comma, then try to parse
2837 // what comes next as additional fields, rather than
2838 // bailing out until next `}`.
2839 if self.token != token::Comma {
2840 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2841 if self.token != token::Comma {
2849 let is_shorthand = parsed_field.as_ref().map_or(false, |f| f.is_shorthand);
2850 // A shorthand field can be turned into a full field with `:`.
2851 // We should point this out.
2852 self.check_or_expected(!is_shorthand, TokenType::Token(token::Colon));
2854 match self.expect_one_of(&[token::Comma], &[token::CloseDelim(close_delim)]) {
2856 if let Some(f) = parsed_field.or(recovery_field) {
2857 // Only include the field if there's no parse error for the field name.
2862 if pth == kw::Async {
2863 async_block_err(&mut e, pth.span);
2865 e.span_label(pth.span, "while parsing this struct");
2866 if let Some(f) = recovery_field {
2869 self.prev_token.span.shrink_to_hi(),
2870 "try adding a comma",
2872 Applicability::MachineApplicable,
2874 } else if is_shorthand
2875 && (AssocOp::from_token(&self.token).is_some()
2876 || matches!(&self.token.kind, token::OpenDelim(_))
2877 || self.token.kind == token::Dot)
2879 // Looks like they tried to write a shorthand, complex expression.
2880 let ident = parsed_field.expect("is_shorthand implies Some").ident;
2882 ident.span.shrink_to_lo(),
2883 "try naming a field",
2884 &format!("{ident}: "),
2885 Applicability::HasPlaceholders,
2893 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2894 self.eat(&token::Comma);
2898 Ok((fields, base, recover_async))
2901 /// Precondition: already parsed the '{'.
2902 pub(super) fn parse_struct_expr(
2904 qself: Option<ast::QSelf>,
2907 ) -> PResult<'a, P<Expr>> {
2909 let (fields, base, recover_async) =
2910 self.parse_struct_fields(pth.clone(), recover, Delimiter::Brace)?;
2911 let span = lo.to(self.token.span);
2912 self.expect(&token::CloseDelim(Delimiter::Brace))?;
2913 let expr = if recover_async {
2916 ExprKind::Struct(P(ast::StructExpr { qself, path: pth, fields, rest: base }))
2918 Ok(self.mk_expr(span, expr))
2921 /// Use in case of error after field-looking code: `S { foo: () with a }`.
2922 fn find_struct_error_after_field_looking_code(&self) -> Option<ExprField> {
2923 match self.token.ident() {
2924 Some((ident, is_raw))
2925 if (is_raw || !ident.is_reserved())
2926 && self.look_ahead(1, |t| *t == token::Colon) =>
2928 Some(ast::ExprField {
2930 span: self.token.span,
2931 expr: self.mk_expr_err(self.token.span),
2932 is_shorthand: false,
2933 attrs: AttrVec::new(),
2935 is_placeholder: false,
2942 fn recover_struct_comma_after_dotdot(&mut self, span: Span) {
2943 if self.token != token::Comma {
2946 self.sess.emit_err(CommaAfterBaseStruct {
2947 span: span.to(self.prev_token.span),
2948 comma: self.token.span,
2950 self.recover_stmt();
2953 /// Parses `ident (COLON expr)?`.
2954 fn parse_expr_field(&mut self) -> PResult<'a, ExprField> {
2955 let attrs = self.parse_outer_attributes()?;
2956 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
2957 let lo = this.token.span;
2959 // Check if a colon exists one ahead. This means we're parsing a fieldname.
2960 let is_shorthand = !this.look_ahead(1, |t| t == &token::Colon || t == &token::Eq);
2961 let (ident, expr) = if is_shorthand {
2962 // Mimic `x: x` for the `x` field shorthand.
2963 let ident = this.parse_ident_common(false)?;
2964 let path = ast::Path::from_ident(ident);
2965 (ident, this.mk_expr(ident.span, ExprKind::Path(None, path)))
2967 let ident = this.parse_field_name()?;
2968 this.error_on_eq_field_init(ident);
2970 (ident, this.parse_expr()?)
2976 span: lo.to(expr.span),
2981 is_placeholder: false,
2983 TrailingToken::MaybeComma,
2988 /// Check for `=`. This means the source incorrectly attempts to
2989 /// initialize a field with an eq rather than a colon.
2990 fn error_on_eq_field_init(&self, field_name: Ident) {
2991 if self.token != token::Eq {
2995 self.sess.emit_err(EqFieldInit {
2996 span: self.token.span,
2997 eq: field_name.span.shrink_to_hi().to(self.token.span),
3001 fn err_dotdotdot_syntax(&self, span: Span) {
3002 self.sess.emit_err(DotDotDot { span });
3005 fn err_larrow_operator(&self, span: Span) {
3006 self.sess.emit_err(LeftArrowOperator { span });
3009 fn mk_assign_op(&self, binop: BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ExprKind {
3010 ExprKind::AssignOp(binop, lhs, rhs)
3015 start: Option<P<Expr>>,
3016 end: Option<P<Expr>>,
3017 limits: RangeLimits,
3019 if end.is_none() && limits == RangeLimits::Closed {
3020 self.inclusive_range_with_incorrect_end(self.prev_token.span);
3023 ExprKind::Range(start, end, limits)
3027 fn mk_unary(&self, unop: UnOp, expr: P<Expr>) -> ExprKind {
3028 ExprKind::Unary(unop, expr)
3031 fn mk_binary(&self, binop: BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ExprKind {
3032 ExprKind::Binary(binop, lhs, rhs)
3035 fn mk_index(&self, expr: P<Expr>, idx: P<Expr>) -> ExprKind {
3036 ExprKind::Index(expr, idx)
3039 fn mk_call(&self, f: P<Expr>, args: Vec<P<Expr>>) -> ExprKind {
3040 ExprKind::Call(f, args)
3043 fn mk_await_expr(&mut self, self_arg: P<Expr>, lo: Span) -> P<Expr> {
3044 let span = lo.to(self.prev_token.span);
3045 let await_expr = self.mk_expr(span, ExprKind::Await(self_arg));
3046 self.recover_from_await_method_call();
3050 pub(crate) fn mk_expr_with_attrs(&self, span: Span, kind: ExprKind, attrs: AttrVec) -> P<Expr> {
3051 P(Expr { kind, span, attrs, id: DUMMY_NODE_ID, tokens: None })
3054 pub(crate) fn mk_expr(&self, span: Span, kind: ExprKind) -> P<Expr> {
3055 P(Expr { kind, span, attrs: AttrVec::new(), id: DUMMY_NODE_ID, tokens: None })
3058 pub(super) fn mk_expr_err(&self, span: Span) -> P<Expr> {
3059 self.mk_expr(span, ExprKind::Err)
3062 /// Create expression span ensuring the span of the parent node
3063 /// is larger than the span of lhs and rhs, including the attributes.
3064 fn mk_expr_sp(&self, lhs: &P<Expr>, lhs_span: Span, rhs_span: Span) -> Span {
3067 .find(|a| a.style == AttrStyle::Outer)
3068 .map_or(lhs_span, |a| a.span)
3072 fn collect_tokens_for_expr(
3075 f: impl FnOnce(&mut Self, ast::AttrVec) -> PResult<'a, P<Expr>>,
3076 ) -> PResult<'a, P<Expr>> {
3077 self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| {
3078 let res = f(this, attrs)?;
3079 let trailing = if this.restrictions.contains(Restrictions::STMT_EXPR)
3080 && this.token.kind == token::Semi
3084 // FIXME - pass this through from the place where we know
3085 // we need a comma, rather than assuming that `#[attr] expr,`
3086 // always captures a trailing comma
3087 TrailingToken::MaybeComma