Skip to main content

rustc_parse/parser/
expr.rs

1// ignore-tidy-file-filelength
2
3use core::mem;
4use core::ops::{Bound, ControlFlow};
5
6use ast::mut_visit::{self, MutVisitor};
7use ast::token::IdentIsRaw;
8use ast::{CoroutineKind, ForLoopKind, GenBlockKind, MatchKind, Pat, Path, PathSegment, Recovered};
9use rustc_ast::token::{self, Delimiter, InvisibleOrigin, MetaVarKind, Token, TokenKind};
10use rustc_ast::util::case::Case;
11use rustc_ast::util::classify;
12use rustc_ast::util::parser::{AssocOp, ExprPrecedence, Fixity, prec_let_scrutinee_needs_par};
13use rustc_ast::visit::{Visitor, walk_expr};
14use rustc_ast::{
15    self as ast, AnonConst, Arm, AssignOp, AssignOpKind, AttrStyle, AttrVec, BinOp, BinOpKind,
16    BlockCheckMode, CaptureBy, ClosureBinder, DUMMY_NODE_ID, Expr, ExprField, ExprKind, FnDecl,
17    FnRetTy, ForLoop, Guard, Label, MacCall, MetaItemLit, Movability, Param, RangeLimits, StmtKind,
18    Ty, TyKind, UnOp, UnsafeBinderCastKind, YieldKind,
19};
20use rustc_ast_pretty::pprust;
21use rustc_data_structures::stack::ensure_sufficient_stack;
22use rustc_errors::{Applicability, Diag, PResult, StashKey, Subdiagnostic};
23use rustc_literal_escaper::unescape_char;
24use rustc_session::diagnostics::{ExprParenthesesNeeded, report_lit_error};
25use rustc_session::lint::builtin::BREAK_WITH_LABEL_AND_LOOP;
26use rustc_span::edition::Edition;
27use rustc_span::{BytePos, ErrorGuaranteed, Ident, Pos, Span, Spanned, Symbol, kw, respan, sym};
28use thin_vec::{ThinVec, thin_vec};
29use tracing::instrument;
30
31use super::diagnostics::SnapshotParser;
32use super::pat::{CommaRecoveryMode, Expected, RecoverColon, RecoverComma};
33use super::ty::{AllowPlus, RecoverQPath, RecoverReturnSign};
34use super::{
35    AttrWrapper, BlockMode, ClosureSpans, ExpTokenPair, ForceCollect, Parser, PathStyle,
36    Restrictions, SemiColonMode, SeqSep, TokenType, Trailing, UsePreAttrPos,
37};
38use crate::{diagnostics, exp, maybe_recover_from_interpolated_ty_qpath};
39
40#[derive(#[automatically_derived]
impl ::core::fmt::Debug for DestructuredFloat {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            DestructuredFloat::Single(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f, "Single",
                    __self_0, &__self_1),
            DestructuredFloat::TrailingDot(__self_0, __self_1, __self_2) =>
                ::core::fmt::Formatter::debug_tuple_field3_finish(f,
                    "TrailingDot", __self_0, __self_1, &__self_2),
            DestructuredFloat::MiddleDot(__self_0, __self_1, __self_2,
                __self_3, __self_4) =>
                ::core::fmt::Formatter::debug_tuple_field5_finish(f,
                    "MiddleDot", __self_0, __self_1, __self_2, __self_3,
                    &__self_4),
            DestructuredFloat::Error =>
                ::core::fmt::Formatter::write_str(f, "Error"),
        }
    }
}Debug)]
41pub(super) enum DestructuredFloat {
42    /// 1e2
43    Single(Symbol, Span),
44    /// 1.
45    TrailingDot(Symbol, Span, Span),
46    /// 1.2 | 1.2e3
47    MiddleDot(Symbol, Span, Span, Symbol, Span),
48    /// Invalid
49    Error,
50}
51
52impl<'a> Parser<'a> {
53    /// Parses an expression.
54    #[inline]
55    pub fn parse_expr(&mut self) -> PResult<'a, Box<Expr>> {
56        self.current_closure.take();
57
58        let attrs = self.parse_outer_attributes()?;
59        self.parse_expr_res(Restrictions::empty(), attrs).map(|res| res.0)
60    }
61
62    /// Parses an expression, forcing tokens to be collected.
63    pub fn parse_expr_force_collect(&mut self) -> PResult<'a, Box<Expr>> {
64        self.current_closure.take();
65
66        // If the expression is associative (e.g. `1 + 2`), then any preceding
67        // outer attribute actually belongs to the first inner sub-expression.
68        // In which case we must use the pre-attr pos to include the attribute
69        // in the collected tokens for the outer expression.
70        let pre_attr_pos = self.collect_pos();
71        let attrs = self.parse_outer_attributes()?;
72        self.collect_tokens(
73            Some(pre_attr_pos),
74            AttrWrapper::empty(),
75            ForceCollect::Yes,
76            |this, _empty_attrs| {
77                let (expr, is_assoc) = this.parse_expr_res(Restrictions::empty(), attrs)?;
78                let use_pre_attr_pos =
79                    if is_assoc { UsePreAttrPos::Yes } else { UsePreAttrPos::No };
80                Ok((expr, Trailing::No, use_pre_attr_pos))
81            },
82        )
83    }
84
85    pub fn parse_expr_anon_const(&mut self) -> PResult<'a, AnonConst> {
86        self.parse_expr().map(|value| AnonConst { id: DUMMY_NODE_ID, value })
87    }
88
89    fn parse_expr_catch_underscore(
90        &mut self,
91        restrictions: Restrictions,
92    ) -> PResult<'a, Box<Expr>> {
93        let attrs = self.parse_outer_attributes()?;
94        match self.parse_expr_res(restrictions, attrs) {
95            Ok((expr, _)) => Ok(expr),
96            Err(err) => match self.token.ident() {
97                Some((Ident { name: kw::Underscore, .. }, IdentIsRaw::No))
98                    if self.may_recover() && self.look_ahead(1, |t| t == &token::Comma) =>
99                {
100                    // Special-case handling of `foo(_, _, _)`
101                    let guar = err.emit();
102                    self.bump();
103                    Ok(self.mk_expr(self.prev_token.span, ExprKind::Err(guar)))
104                }
105                _ => Err(err),
106            },
107        }
108    }
109
110    /// Parses a sequence of expressions delimited by parentheses.
111    fn parse_expr_paren_seq(&mut self) -> PResult<'a, ThinVec<Box<Expr>>> {
112        self.parse_paren_comma_seq(|p| p.parse_expr_catch_underscore(Restrictions::empty()))
113            .map(|(r, _)| r)
114    }
115
116    /// Parses an expression, subject to the given restrictions.
117    #[inline]
118    pub(super) fn parse_expr_res(
119        &mut self,
120        r: Restrictions,
121        attrs: AttrWrapper,
122    ) -> PResult<'a, (Box<Expr>, bool)> {
123        self.with_res(r, |this| this.parse_expr_assoc_with(Bound::Unbounded, attrs))
124    }
125
126    /// Parses an associative expression with operators of at least `min_prec` precedence.
127    /// The `bool` in the return value indicates if it was an assoc expr, i.e. with an operator
128    /// followed by a subexpression (e.g. `1 + 2`).
129    pub(super) fn parse_expr_assoc_with(
130        &mut self,
131        min_prec: Bound<ExprPrecedence>,
132        attrs: AttrWrapper,
133    ) -> PResult<'a, (Box<Expr>, bool)> {
134        let lhs = if self.token.is_range_separator() {
135            return self.parse_expr_prefix_range(attrs).map(|res| (res, false));
136        } else {
137            self.parse_expr_prefix(attrs)?
138        };
139        self.parse_expr_assoc_rest_with(min_prec, false, lhs)
140    }
141
142    /// Parses the rest of an associative expression (i.e. the part after the lhs) with operators
143    /// of at least `min_prec` precedence. The `bool` in the return value indicates if something
144    /// was actually parsed.
145    pub(super) fn parse_expr_assoc_rest_with(
146        &mut self,
147        min_prec: Bound<ExprPrecedence>,
148        starts_stmt: bool,
149        mut lhs: Box<Expr>,
150    ) -> PResult<'a, (Box<Expr>, bool)> {
151        let mut parsed_something = false;
152        if !self.should_continue_as_assoc_expr(&lhs) {
153            return Ok((lhs, parsed_something));
154        }
155
156        self.expected_token_types.insert(TokenType::Operator);
157        while let Some(op) = self.check_assoc_op() {
158            let lhs_span = self.interpolated_or_expr_span(&lhs);
159            let cur_op_span = self.token.span;
160            let restrictions = if op.node.is_assign_like() {
161                self.restrictions & Restrictions::NO_STRUCT_LITERAL
162            } else {
163                self.restrictions
164            };
165            let prec = op.node.precedence();
166            if match min_prec {
167                Bound::Included(min_prec) => prec < min_prec,
168                Bound::Excluded(min_prec) => prec <= min_prec,
169                Bound::Unbounded => false,
170            } {
171                break;
172            }
173            // Check for deprecated `...` syntax
174            if self.token == token::DotDotDot && op.node == AssocOp::Range(RangeLimits::Closed) {
175                self.err_dotdotdot_syntax(self.token.span);
176            }
177
178            if self.token == token::LArrow {
179                self.err_larrow_operator(self.token.span);
180            }
181
182            parsed_something = true;
183            self.bump();
184            if op.node.is_comparison() {
185                if let Some(expr) = self.check_no_chained_comparison(&lhs, &op)? {
186                    return Ok((expr, parsed_something));
187                }
188            }
189
190            // Look for JS' `===` and `!==` and recover
191            if let AssocOp::Binary(bop @ BinOpKind::Eq | bop @ BinOpKind::Ne) = op.node
192                && self.token == token::Eq
193                && self.prev_token.span.hi() == self.token.span.lo()
194            {
195                let sp = op.span.to(self.token.span);
196                let sugg = bop.as_str().into();
197                let invalid = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}=", sugg))
    })format!("{sugg}=");
198                self.dcx().emit_err(diagnostics::InvalidComparisonOperator {
199                    span: sp,
200                    invalid: invalid.clone(),
201                    sub: diagnostics::InvalidComparisonOperatorSub::Correctable {
202                        span: sp,
203                        invalid,
204                        correct: sugg,
205                    },
206                });
207                self.bump();
208            }
209
210            // Look for PHP's `<>` and recover
211            if op.node == AssocOp::Binary(BinOpKind::Lt)
212                && self.token == token::Gt
213                && self.prev_token.span.hi() == self.token.span.lo()
214            {
215                let sp = op.span.to(self.token.span);
216                self.dcx().emit_err(diagnostics::InvalidComparisonOperator {
217                    span: sp,
218                    invalid: "<>".into(),
219                    sub: diagnostics::InvalidComparisonOperatorSub::Correctable {
220                        span: sp,
221                        invalid: "<>".into(),
222                        correct: "!=".into(),
223                    },
224                });
225                self.bump();
226            }
227
228            // Look for C++'s `<=>` and recover
229            if op.node == AssocOp::Binary(BinOpKind::Le)
230                && self.token == token::Gt
231                && self.prev_token.span.hi() == self.token.span.lo()
232            {
233                let sp = op.span.to(self.token.span);
234                self.dcx().emit_err(diagnostics::InvalidComparisonOperator {
235                    span: sp,
236                    invalid: "<=>".into(),
237                    sub: diagnostics::InvalidComparisonOperatorSub::Spaceship(sp),
238                });
239                self.bump();
240            }
241
242            if self.prev_token == token::Plus
243                && self.token == token::Plus
244                && self.prev_token.span.between(self.token.span).is_empty()
245            {
246                let op_span = self.prev_token.span.to(self.token.span);
247                // Eat the second `+`
248                self.bump();
249                lhs = self.recover_from_postfix_increment(lhs, op_span, starts_stmt)?;
250                continue;
251            }
252
253            if self.prev_token == token::Minus
254                && self.token == token::Minus
255                && self.prev_token.span.between(self.token.span).is_empty()
256                && !self.look_ahead(1, |tok| tok.can_begin_expr())
257            {
258                let op_span = self.prev_token.span.to(self.token.span);
259                // Eat the second `-`
260                self.bump();
261                lhs = self.recover_from_postfix_decrement(lhs, op_span, starts_stmt)?;
262                continue;
263            }
264
265            let op_span = op.span;
266            let op = op.node;
267            // Special cases:
268            if op == AssocOp::Cast {
269                lhs = self.parse_assoc_op_cast(lhs, lhs_span, op_span, ExprKind::Cast)?;
270                continue;
271            } else if let AssocOp::Range(limits) = op {
272                // If we didn't have to handle `x..`/`x..=`, it would be pretty easy to
273                // generalise it to the Fixity::None code.
274                lhs = self.parse_expr_range(prec, lhs, limits, cur_op_span)?;
275                break;
276            }
277
278            let min_prec = match op.fixity() {
279                Fixity::Right => Bound::Included(prec),
280                Fixity::Left | Fixity::None => Bound::Excluded(prec),
281            };
282            let (rhs, _) = self.with_res(restrictions - Restrictions::STMT_EXPR, |this| {
283                let attrs = this.parse_outer_attributes()?;
284                this.parse_expr_assoc_with(min_prec, attrs)
285            })?;
286
287            let span = self.mk_expr_sp(&lhs, lhs_span, op_span, rhs.span);
288            lhs = match op {
289                AssocOp::Binary(ast_op) => {
290                    let binary = self.mk_binary(respan(cur_op_span, ast_op), lhs, rhs);
291                    self.mk_expr(span, binary)
292                }
293                AssocOp::Assign => self.mk_expr(span, ExprKind::Assign(lhs, rhs, cur_op_span)),
294                AssocOp::AssignOp(aop) => {
295                    let aopexpr = self.mk_assign_op(respan(cur_op_span, aop), lhs, rhs);
296                    self.mk_expr(span, aopexpr)
297                }
298                AssocOp::Cast | AssocOp::Range(_) => {
299                    self.dcx().span_bug(span, "AssocOp should have been handled by special case")
300                }
301            };
302        }
303
304        Ok((lhs, parsed_something))
305    }
306
307    fn should_continue_as_assoc_expr(&mut self, lhs: &Expr) -> bool {
308        match (self.expr_is_complete(lhs), AssocOp::from_token(&self.token)) {
309            // Semi-statement forms are odd:
310            // See https://github.com/rust-lang/rust/issues/29071
311            (true, None) => false,
312            (false, _) => true, // Continue parsing the expression.
313            // An exhaustive check is done in the following block, but these are checked first
314            // because they *are* ambiguous but also reasonable looking incorrect syntax, so we
315            // want to keep their span info to improve diagnostics in these cases in a later stage.
316            (true, Some(AssocOp::Binary(
317                BinOpKind::Mul | // `{ 42 } *foo = bar;` or `{ 42 } * 3`
318                BinOpKind::Sub | // `{ 42 } -5`
319                BinOpKind::Add | // `{ 42 } + 42` (unary plus)
320                BinOpKind::And | // `{ 42 } &&x` (#61475) or `{ 42 } && if x { 1 } else { 0 }`
321                BinOpKind::Or | // `{ 42 } || 42` ("logical or" or closure)
322                BinOpKind::BitOr // `{ 42 } | 42` or `{ 42 } |x| 42`
323            ))) => {
324                // These cases are ambiguous and can't be identified in the parser alone.
325                //
326                // Bitwise AND is left out because guessing intent is hard. We can make
327                // suggestions based on the assumption that double-refs are rarely intentional,
328                // and closures are distinct enough that they don't get mixed up with their
329                // return value.
330                let sp = self.psess.source_map().start_point(self.token.span);
331                self.psess.ambiguous_block_expr_parse.borrow_mut().insert(sp, lhs.span);
332                false
333            }
334            (true, Some(op)) if !op.can_continue_expr_unambiguously() => false,
335            (true, Some(_)) => {
336                self.error_found_expr_would_be_stmt(lhs);
337                true
338            }
339        }
340    }
341
342    /// We've found an expression that would be parsed as a statement,
343    /// but the next token implies this should be parsed as an expression.
344    /// For example: `if let Some(x) = x { x } else { 0 } / 2`.
345    fn error_found_expr_would_be_stmt(&self, lhs: &Expr) {
346        self.dcx().emit_err(diagnostics::FoundExprWouldBeStmt {
347            span: self.token.span,
348            token: pprust::token_to_string(&self.token),
349            suggestion: ExprParenthesesNeeded::surrounding(lhs.span),
350        });
351    }
352
353    /// Possibly translate the current token to an associative operator.
354    /// The method does not advance the current token.
355    ///
356    /// Also performs recovery for `and` / `or` which are mistaken for `&&` and `||` respectively.
357    pub(super) fn check_assoc_op(&self) -> Option<Spanned<AssocOp>> {
358        let (op, span) = match (AssocOp::from_token(&self.token), self.token.ident()) {
359            // When parsing const expressions, stop parsing when encountering `>`.
360            (
361                Some(
362                    AssocOp::Binary(BinOpKind::Shr | BinOpKind::Gt | BinOpKind::Ge)
363                    | AssocOp::AssignOp(AssignOpKind::ShrAssign),
364                ),
365                _,
366            ) if self.restrictions.contains(Restrictions::CONST_EXPR) => {
367                return None;
368            }
369            // When recovering patterns as expressions, stop parsing when encountering an
370            // assignment `=`, an alternative `|`, or a range `..`.
371            (
372                Some(
373                    AssocOp::Assign
374                    | AssocOp::AssignOp(_)
375                    | AssocOp::Binary(BinOpKind::BitOr)
376                    | AssocOp::Range(_),
377                ),
378                _,
379            ) if self.restrictions.contains(Restrictions::IS_PAT) => {
380                return None;
381            }
382            (Some(op), _) => (op, self.token.span),
383            (None, Some((Ident { name: sym::and, span }, IdentIsRaw::No)))
384                if self.may_recover() =>
385            {
386                self.dcx().emit_err(diagnostics::InvalidLogicalOperator {
387                    span: self.token.span,
388                    incorrect: "and".into(),
389                    sub: diagnostics::InvalidLogicalOperatorSub::Conjunction(self.token.span),
390                });
391                (AssocOp::Binary(BinOpKind::And), span)
392            }
393            (None, Some((Ident { name: sym::or, span }, IdentIsRaw::No))) if self.may_recover() => {
394                self.dcx().emit_err(diagnostics::InvalidLogicalOperator {
395                    span: self.token.span,
396                    incorrect: "or".into(),
397                    sub: diagnostics::InvalidLogicalOperatorSub::Disjunction(self.token.span),
398                });
399                (AssocOp::Binary(BinOpKind::Or), span)
400            }
401            _ => return None,
402        };
403        Some(respan(span, op))
404    }
405
406    /// Checks if this expression is a successfully parsed statement.
407    fn expr_is_complete(&self, e: &Expr) -> bool {
408        self.restrictions.contains(Restrictions::STMT_EXPR) && classify::expr_is_complete(e)
409    }
410
411    /// Parses `x..y`, `x..=y`, and `x..`/`x..=`.
412    /// The other two variants are handled in `parse_prefix_range_expr` below.
413    fn parse_expr_range(
414        &mut self,
415        prec: ExprPrecedence,
416        lhs: Box<Expr>,
417        limits: RangeLimits,
418        cur_op_span: Span,
419    ) -> PResult<'a, Box<Expr>> {
420        let rhs = if self.is_at_start_of_range_notation_rhs() {
421            let maybe_lt = self.token;
422            let attrs = self.parse_outer_attributes()?;
423            Some(
424                self.parse_expr_assoc_with(Bound::Excluded(prec), attrs)
425                    .map_err(|err| self.maybe_err_dotdotlt_syntax(maybe_lt, err))?
426                    .0,
427            )
428        } else {
429            None
430        };
431        let rhs_span = rhs.as_ref().map_or(cur_op_span, |x| x.span);
432        let span = self.mk_expr_sp(&lhs, lhs.span, cur_op_span, rhs_span);
433        let range = self.mk_range(Some(lhs), rhs, limits);
434        Ok(self.mk_expr(span, range))
435    }
436
437    fn is_at_start_of_range_notation_rhs(&self) -> bool {
438        if self.token.can_begin_expr() {
439            // Parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
440            if self.token == token::OpenBrace {
441                return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
442            }
443            true
444        } else {
445            false
446        }
447    }
448
449    /// Parses prefix-forms of range notation: `..expr`, `..`, `..=expr`.
450    fn parse_expr_prefix_range(&mut self, attrs: AttrWrapper) -> PResult<'a, Box<Expr>> {
451        if !attrs.is_empty() {
452            let err = diagnostics::DotDotRangeAttribute { span: self.token.span };
453            self.dcx().emit_err(err);
454        }
455
456        // Check for deprecated `...` syntax.
457        if self.token == token::DotDotDot {
458            self.err_dotdotdot_syntax(self.token.span);
459        }
460
461        if true {
    if !self.token.is_range_separator() {
        {
            ::core::panicking::panic_fmt(format_args!("parse_prefix_range_expr: token {0:?} is not DotDot/DotDotEq",
                    self.token));
        }
    };
};debug_assert!(
462            self.token.is_range_separator(),
463            "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
464            self.token
465        );
466
467        let limits = match self.token.kind {
468            token::DotDot => RangeLimits::HalfOpen,
469            _ => RangeLimits::Closed,
470        };
471        let op = AssocOp::from_token(&self.token);
472        let attrs = self.parse_outer_attributes()?;
473        self.collect_tokens_for_expr(attrs, |this, attrs| {
474            let lo = this.token.span;
475            let maybe_lt = this.look_ahead(1, |t| t.clone());
476            this.bump();
477            let (span, opt_end) = if this.is_at_start_of_range_notation_rhs() {
478                // RHS must be parsed with more associativity than the dots.
479                let attrs = this.parse_outer_attributes()?;
480                this.parse_expr_assoc_with(Bound::Excluded(op.unwrap().precedence()), attrs)
481                    .map(|(x, _)| (lo.to(x.span), Some(x)))
482                    .map_err(|err| this.maybe_err_dotdotlt_syntax(maybe_lt, err))?
483            } else {
484                (lo, None)
485            };
486            let range = this.mk_range(None, opt_end, limits);
487            Ok(this.mk_expr_with_attrs(span, range, attrs))
488        })
489    }
490
491    /// Parses a prefix-unary-operator expr.
492    fn parse_expr_prefix(&mut self, attrs: AttrWrapper) -> PResult<'a, Box<Expr>> {
493        let lo = self.token.span;
494
495        macro_rules! make_it {
496            ($this:ident, $attrs:expr, |this, _| $body:expr) => {
497                $this.collect_tokens_for_expr($attrs, |$this, attrs| {
498                    let (hi, ex) = $body?;
499                    Ok($this.mk_expr_with_attrs(lo.to(hi), ex, attrs))
500                })
501            };
502        }
503
504        let this = self;
505
506        // Note: when adding new unary operators, don't forget to adjust TokenKind::can_begin_expr()
507        match this.token.uninterpolate().kind {
508            // `!expr`
509            token::Bang => this.collect_tokens_for_expr(attrs,
    |this, attrs|
        {
            let (hi, ex) = this.parse_expr_unary(lo, UnOp::Not)?;
            Ok(this.mk_expr_with_attrs(lo.to(hi), ex, attrs))
        })make_it!(this, attrs, |this, _| this.parse_expr_unary(lo, UnOp::Not)),
510            // `~expr`
511            token::Tilde => this.collect_tokens_for_expr(attrs,
    |this, attrs|
        {
            let (hi, ex) = this.recover_tilde_expr(lo)?;
            Ok(this.mk_expr_with_attrs(lo.to(hi), ex, attrs))
        })make_it!(this, attrs, |this, _| this.recover_tilde_expr(lo)),
512            // `-expr`
513            token::Minus => {
514                this.collect_tokens_for_expr(attrs,
    |this, attrs|
        {
            let (hi, ex) = this.parse_expr_unary(lo, UnOp::Neg)?;
            Ok(this.mk_expr_with_attrs(lo.to(hi), ex, attrs))
        })make_it!(this, attrs, |this, _| this.parse_expr_unary(lo, UnOp::Neg))
515            }
516            // `*expr`
517            token::Star => {
518                this.collect_tokens_for_expr(attrs,
    |this, attrs|
        {
            let (hi, ex) = this.parse_expr_unary(lo, UnOp::Deref)?;
            Ok(this.mk_expr_with_attrs(lo.to(hi), ex, attrs))
        })make_it!(this, attrs, |this, _| this.parse_expr_unary(lo, UnOp::Deref))
519            }
520            // `&expr` and `&&expr`
521            token::And | token::AndAnd => {
522                this.collect_tokens_for_expr(attrs,
    |this, attrs|
        {
            let (hi, ex) = this.parse_expr_borrow(lo)?;
            Ok(this.mk_expr_with_attrs(lo.to(hi), ex, attrs))
        })make_it!(this, attrs, |this, _| this.parse_expr_borrow(lo))
523            }
524            // `+lit`
525            token::Plus if this.look_ahead(1, |tok| tok.is_numeric_lit()) => {
526                let mut err = diagnostics::LeadingPlusNotSupported {
527                    span: lo,
528                    remove_plus: None,
529                    add_parentheses: None,
530                };
531
532                // a block on the LHS might have been intended to be an expression instead
533                if let Some(sp) = this.psess.ambiguous_block_expr_parse.borrow().get(&lo) {
534                    err.add_parentheses = Some(ExprParenthesesNeeded::surrounding(*sp));
535                } else {
536                    err.remove_plus = Some(lo);
537                }
538                this.dcx().emit_err(err);
539
540                this.bump();
541                let attrs = this.parse_outer_attributes()?;
542                this.parse_expr_prefix(attrs)
543            }
544            // Recover from `++x`:
545            token::Plus if this.look_ahead(1, |t| *t == token::Plus) => {
546                let starts_stmt =
547                    this.prev_token == token::Semi || this.prev_token == token::CloseBrace;
548                let pre_span = this.token.span.to(this.look_ahead(1, |t| t.span));
549                // Eat both `+`s.
550                this.bump();
551                this.bump();
552
553                let operand_expr = this.parse_expr_dot_or_call(attrs)?;
554                this.recover_from_prefix_increment(operand_expr, pre_span, starts_stmt)
555            }
556            token::Ident(..) if this.token.is_keyword(kw::Box) => {
557                this.collect_tokens_for_expr(attrs,
    |this, attrs|
        {
            let (hi, ex) = this.parse_expr_box(lo)?;
            Ok(this.mk_expr_with_attrs(lo.to(hi), ex, attrs))
        })make_it!(this, attrs, |this, _| this.parse_expr_box(lo))
558            }
559            token::Ident(..)
560                if this.token.is_keyword(kw::Move)
561                    && this.look_ahead(1, |t| *t == token::OpenParen) =>
562            {
563                this.collect_tokens_for_expr(attrs,
    |this, attrs|
        {
            let (hi, ex) = this.parse_expr_move(lo)?;
            Ok(this.mk_expr_with_attrs(lo.to(hi), ex, attrs))
        })make_it!(this, attrs, |this, _| this.parse_expr_move(lo))
564            }
565            token::Ident(..) if this.may_recover() && this.is_mistaken_not_ident_negation() => {
566                this.collect_tokens_for_expr(attrs,
    |this, attrs|
        {
            let (hi, ex) = this.recover_not_expr(lo)?;
            Ok(this.mk_expr_with_attrs(lo.to(hi), ex, attrs))
        })make_it!(this, attrs, |this, _| this.recover_not_expr(lo))
567            }
568            _ => return this.parse_expr_dot_or_call(attrs),
569        }
570    }
571
572    fn parse_expr_prefix_common(&mut self, lo: Span) -> PResult<'a, (Span, Box<Expr>)> {
573        self.bump();
574        let attrs = self.parse_outer_attributes()?;
575        let expr = if self.token.is_range_separator() {
576            self.parse_expr_prefix_range(attrs)
577        } else {
578            self.parse_expr_prefix(attrs)
579        }?;
580        let span = self.interpolated_or_expr_span(&expr);
581        Ok((lo.to(span), expr))
582    }
583
584    fn parse_expr_unary(&mut self, lo: Span, op: UnOp) -> PResult<'a, (Span, ExprKind)> {
585        let (span, expr) = self.parse_expr_prefix_common(lo)?;
586        Ok((span, self.mk_unary(op, expr)))
587    }
588
589    /// Recover on `~expr` in favor of `!expr`.
590    fn recover_tilde_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
591        self.dcx().emit_err(diagnostics::TildeAsUnaryOperator(lo));
592
593        self.parse_expr_unary(lo, UnOp::Not)
594    }
595
596    /// Parse `box expr` - this syntax has been removed, but we still parse this
597    /// for now to provide a more useful error
598    fn parse_expr_box(&mut self, box_kw: Span) -> PResult<'a, (Span, ExprKind)> {
599        let (span, expr) = self.parse_expr_prefix_common(box_kw)?;
600        // Make a multipart suggestion instead of `span_to_snippet` in case source isn't available
601        let box_kw_and_lo = box_kw.until(self.interpolated_or_expr_span(&expr));
602        let hi = span.shrink_to_hi();
603        let sugg = diagnostics::AddBoxNew { box_kw_and_lo, hi };
604        let guar = self.dcx().emit_err(diagnostics::BoxSyntaxRemoved { span, sugg });
605        Ok((span, ExprKind::Err(guar)))
606    }
607
608    fn parse_expr_move(&mut self, move_kw: Span) -> PResult<'a, (Span, ExprKind)> {
609        self.bump();
610        self.psess.gated_spans.gate(sym::move_expr, move_kw);
611        self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenParen,
    token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen))?;
612        let expr = self.parse_expr()?;
613        self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseParen,
    token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen))?;
614        let span = move_kw.to(self.prev_token.span);
615        Ok((span, ExprKind::Move(expr, move_kw)))
616    }
617
618    fn is_mistaken_not_ident_negation(&self) -> bool {
619        let token_cannot_continue_expr = |t: &Token| match t.uninterpolate().kind {
620            // These tokens can start an expression after `!`, but
621            // can't continue an expression after an ident
622            token::Ident(name, is_raw) => token::ident_can_begin_expr(name, t.span, is_raw),
623            token::Literal(..) | token::Pound => true,
624            _ => t.is_metavar_expr(),
625        };
626        self.token.is_ident_named(sym::not) && self.look_ahead(1, token_cannot_continue_expr)
627    }
628
629    /// Recover on `not expr` in favor of `!expr`.
630    fn recover_not_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
631        let negated_token = self.look_ahead(1, |t| *t);
632
633        let sub_diag = if negated_token.is_numeric_lit() {
634            diagnostics::NotAsNegationOperatorSub::SuggestNotBitwise
635        } else if negated_token.is_bool_lit() {
636            diagnostics::NotAsNegationOperatorSub::SuggestNotLogical
637        } else {
638            diagnostics::NotAsNegationOperatorSub::SuggestNotDefault
639        };
640
641        self.dcx().emit_err(diagnostics::NotAsNegationOperator {
642            negated: negated_token.span,
643            negated_desc: super::token_descr(&negated_token),
644            // Span the `not` plus trailing whitespace to avoid
645            // trailing whitespace after the `!` in our suggestion
646            sub: sub_diag(
647                self.psess.source_map().span_until_non_whitespace(lo.to(negated_token.span)),
648            ),
649        });
650
651        self.parse_expr_unary(lo, UnOp::Not)
652    }
653
654    /// Returns the span of expr if it was not interpolated, or the span of the interpolated token.
655    fn interpolated_or_expr_span(&self, expr: &Expr) -> Span {
656        match self.prev_token.kind {
657            token::NtIdent(..) | token::NtLifetime(..) => self.prev_token.span,
658            token::CloseInvisible(InvisibleOrigin::MetaVar(_)) => {
659                // `expr.span` is the interpolated span, because invisible open
660                // and close delims both get marked with the same span, one
661                // that covers the entire thing between them. (See
662                // `rustc_expand::mbe::transcribe::transcribe`.)
663                self.prev_token.span
664            }
665            _ => expr.span,
666        }
667    }
668
669    fn parse_assoc_op_cast(
670        &mut self,
671        lhs: Box<Expr>,
672        lhs_span: Span,
673        op_span: Span,
674        expr_kind: fn(Box<Expr>, Box<Ty>) -> ExprKind,
675    ) -> PResult<'a, Box<Expr>> {
676        let mk_expr = |this: &mut Self, lhs: Box<Expr>, rhs: Box<Ty>| {
677            this.mk_expr(this.mk_expr_sp(&lhs, lhs_span, op_span, rhs.span), expr_kind(lhs, rhs))
678        };
679
680        // Save the state of the parser before parsing type normally, in case there is a
681        // LessThan comparison after this cast.
682        let parser_snapshot_before_type = self.clone();
683        let cast_expr = match self.parse_as_cast_ty() {
684            Ok(rhs) => mk_expr(self, lhs, rhs),
685            Err(type_err) => {
686                if !self.may_recover() {
687                    return Err(type_err);
688                }
689
690                // Rewind to before attempting to parse the type with generics, to recover
691                // from situations like `x as usize < y` in which we first tried to parse
692                // `usize < y` as a type with generic arguments.
693                let parser_snapshot_after_type = mem::replace(self, parser_snapshot_before_type);
694
695                // Check for typo of `'a: loop { break 'a }` with a missing `'`.
696                match (&lhs.kind, &self.token.kind) {
697                    (
698                        // `foo: `
699                        ExprKind::Path(None, ast::Path { segments, .. }),
700                        token::Ident(kw::For | kw::Loop | kw::While, IdentIsRaw::No),
701                    ) if let [segment] = segments.as_slice() => {
702                        let snapshot = self.create_snapshot_for_diagnostic();
703                        let label = Label {
704                            ident: Ident::from_str_and_span(
705                                &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\'{0}", segment.ident))
    })format!("'{}", segment.ident),
706                                segment.ident.span,
707                            ),
708                        };
709                        match self.parse_expr_labeled(label, false) {
710                            Ok(expr) => {
711                                type_err.cancel();
712                                self.dcx().emit_err(diagnostics::MalformedLoopLabel {
713                                    span: label.ident.span,
714                                    suggestion: label.ident.span.shrink_to_lo(),
715                                });
716                                return Ok(expr);
717                            }
718                            Err(err) => {
719                                err.cancel();
720                                self.restore_snapshot(snapshot);
721                            }
722                        }
723                    }
724                    _ => {}
725                }
726
727                match self.parse_path(PathStyle::Expr) {
728                    Ok(path) => {
729                        let span_after_type = parser_snapshot_after_type.token.span;
730                        let expr = mk_expr(
731                            self,
732                            lhs,
733                            self.mk_ty(path.span, TyKind::Path(None, path.clone())),
734                        );
735
736                        let args_span = self.look_ahead(1, |t| t.span).to(span_after_type);
737                        match self.token.kind {
738                            token::Lt => {
739                                self.dcx().emit_err(diagnostics::ComparisonInterpretedAsGeneric {
740                                    comparison: self.token.span,
741                                    r#type: pprust::path_to_string(&path),
742                                    args: args_span,
743                                    suggestion: diagnostics::ComparisonInterpretedAsGenericSugg {
744                                        left: expr.span.shrink_to_lo(),
745                                        right: expr.span.shrink_to_hi(),
746                                    },
747                                })
748                            }
749                            token::Shl => {
750                                self.dcx().emit_err(diagnostics::ShiftInterpretedAsGeneric {
751                                    shift: self.token.span,
752                                    r#type: pprust::path_to_string(&path),
753                                    args: args_span,
754                                    suggestion: diagnostics::ShiftInterpretedAsGenericSugg {
755                                        left: expr.span.shrink_to_lo(),
756                                        right: expr.span.shrink_to_hi(),
757                                    },
758                                })
759                            }
760                            _ => {
761                                // We can end up here even without `<` being the next token, for
762                                // example because `parse_ty_no_plus` returns `Err` on keywords,
763                                // but `parse_path` returns `Ok` on them due to error recovery.
764                                // Return original error and parser state.
765                                *self = parser_snapshot_after_type;
766                                return Err(type_err);
767                            }
768                        };
769
770                        // Successfully parsed the type path leaving a `<` yet to parse.
771                        type_err.cancel();
772
773                        // Keep `x as usize` as an expression in AST and continue parsing.
774                        expr
775                    }
776                    Err(path_err) => {
777                        // Couldn't parse as a path, return original error and parser state.
778                        path_err.cancel();
779                        *self = parser_snapshot_after_type;
780                        return Err(type_err);
781                    }
782                }
783            }
784        };
785
786        // Try to parse a postfix operator such as `.`, `?`, or index (`[]`)
787        // after a cast. If one is present, emit an error then return a valid
788        // parse tree; For something like `&x as T[0]` will be as if it was
789        // written `((&x) as T)[0]`.
790
791        let span = cast_expr.span;
792
793        let with_postfix = self.parse_expr_dot_or_call_with(AttrVec::new(), cast_expr, span)?;
794
795        // Check if an illegal postfix operator has been added after the cast.
796        // If the resulting expression is not a cast, it is an illegal postfix operator.
797        if !#[allow(non_exhaustive_omitted_patterns)] match with_postfix.kind {
    ExprKind::Cast(_, _) => true,
    _ => false,
}matches!(with_postfix.kind, ExprKind::Cast(_, _)) {
798            let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("cast cannot be followed by {0}",
                match with_postfix.kind {
                    ExprKind::Index(..) => "indexing",
                    ExprKind::Try(_) => "`?`",
                    ExprKind::Field(_, _) => "a field access",
                    ExprKind::MethodCall(_) => "a method call",
                    ExprKind::Call(_, _) => "a function call",
                    ExprKind::Await(_, _) => "`.await`",
                    ExprKind::Use(_, _) => "`.use`",
                    ExprKind::Yield(YieldKind::Postfix(_)) => "`.yield`",
                    ExprKind::Match(_, _, MatchKind::Postfix) =>
                        "a postfix match",
                    ExprKind::Err(_) => return Ok(with_postfix),
                    _ => {
                        ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
                                format_args!("did not expect {0:?} as an illegal postfix operator following cast",
                                    with_postfix.kind)));
                    }
                }))
    })format!(
799                "cast cannot be followed by {}",
800                match with_postfix.kind {
801                    ExprKind::Index(..) => "indexing",
802                    ExprKind::Try(_) => "`?`",
803                    ExprKind::Field(_, _) => "a field access",
804                    ExprKind::MethodCall(_) => "a method call",
805                    ExprKind::Call(_, _) => "a function call",
806                    ExprKind::Await(_, _) => "`.await`",
807                    ExprKind::Use(_, _) => "`.use`",
808                    ExprKind::Yield(YieldKind::Postfix(_)) => "`.yield`",
809                    ExprKind::Match(_, _, MatchKind::Postfix) => "a postfix match",
810                    ExprKind::Err(_) => return Ok(with_postfix),
811                    _ => unreachable!(
812                        "did not expect {:?} as an illegal postfix operator following cast",
813                        with_postfix.kind
814                    ),
815                }
816            );
817            let mut err = self.dcx().struct_span_err(span, msg);
818
819            let suggest_parens = |err: &mut Diag<'_>| {
820                let suggestions = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(span.shrink_to_lo(), "(".to_string()),
                (span.shrink_to_hi(), ")".to_string())]))vec![
821                    (span.shrink_to_lo(), "(".to_string()),
822                    (span.shrink_to_hi(), ")".to_string()),
823                ];
824                err.multipart_suggestion(
825                    "try surrounding the expression in parentheses",
826                    suggestions,
827                    Applicability::MachineApplicable,
828                );
829            };
830
831            suggest_parens(&mut err);
832
833            err.emit();
834        };
835        Ok(with_postfix)
836    }
837
838    /// Parse `& mut? <expr>` or `& raw [ const | mut ] <expr>`.
839    fn parse_expr_borrow(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
840        self.expect_and()?;
841        let has_lifetime = self.token.is_lifetime() && self.look_ahead(1, |t| t != &token::Colon);
842        let lifetime = has_lifetime.then(|| self.expect_lifetime()); // For recovery, see below.
843        let (borrow_kind, mutbl) = self.parse_borrow_modifiers();
844        let attrs = self.parse_outer_attributes()?;
845        let expr = if self.token.is_range_separator() {
846            self.parse_expr_prefix_range(attrs)
847        } else {
848            self.parse_expr_prefix(attrs)
849        }?;
850        let hi = self.interpolated_or_expr_span(&expr);
851        let span = lo.to(hi);
852        if let Some(lt) = lifetime {
853            self.error_remove_borrow_lifetime(span, lt.ident.span.until(expr.span));
854        }
855
856        // Add expected tokens if we parsed `&raw` as an expression.
857        // This will make sure we see "expected `const`, `mut`", and
858        // guides recovery in case we write `&raw expr`.
859        if borrow_kind == ast::BorrowKind::Ref
860            && mutbl == ast::Mutability::Not
861            && #[allow(non_exhaustive_omitted_patterns)] match &expr.kind {
    ExprKind::Path(None, p) if *p == kw::Raw => true,
    _ => false,
}matches!(&expr.kind, ExprKind::Path(None, p) if *p == kw::Raw)
862        {
863            self.expected_token_types.insert(TokenType::KwMut);
864            self.expected_token_types.insert(TokenType::KwConst);
865        }
866
867        Ok((span, ExprKind::AddrOf(borrow_kind, mutbl, expr)))
868    }
869
870    fn error_remove_borrow_lifetime(&self, span: Span, lt_span: Span) {
871        self.dcx()
872            .emit_err(diagnostics::LifetimeInBorrowExpression { span, lifetime_span: lt_span });
873    }
874
875    /// Parse `mut?` or `[ raw | pin ] [ const | mut ]`.
876    fn parse_borrow_modifiers(&mut self) -> (ast::BorrowKind, ast::Mutability) {
877        if self.check_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Raw,
    token_type: crate::parser::token_type::TokenType::KwRaw,
}exp!(Raw)) && self.look_ahead(1, Token::is_mutability) {
878            // `raw [ const | mut ]`.
879            let found_raw = self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Raw,
    token_type: crate::parser::token_type::TokenType::KwRaw,
}exp!(Raw));
880            if !found_raw { ::core::panicking::panic("assertion failed: found_raw") };assert!(found_raw);
881            let mutability = self.parse_mut_or_const().unwrap();
882            (ast::BorrowKind::Raw, mutability)
883        } else {
884            match self.parse_pin_and_mut() {
885                // `mut?`
886                (ast::Pinnedness::Not, mutbl) => (ast::BorrowKind::Ref, mutbl),
887                // `pin [ const | mut ]`.
888                // `pin` has been gated in `self.parse_pin_and_mut()` so we don't
889                // need to gate it here.
890                (ast::Pinnedness::Pinned, mutbl) => (ast::BorrowKind::Pin, mutbl),
891            }
892        }
893    }
894
895    /// Parses `a.b` or `a(13)` or `a[4]` or just `a`.
896    fn parse_expr_dot_or_call(&mut self, attrs: AttrWrapper) -> PResult<'a, Box<Expr>> {
897        self.collect_tokens_for_expr(attrs, |this, attrs| {
898            let base = this.parse_expr_bottom()?;
899            let span = this.interpolated_or_expr_span(&base);
900            this.parse_expr_dot_or_call_with(attrs, base, span)
901        })
902    }
903
904    pub(super) fn parse_expr_dot_or_call_with(
905        &mut self,
906        mut attrs: ast::AttrVec,
907        mut e: Box<Expr>,
908        lo: Span,
909    ) -> PResult<'a, Box<Expr>> {
910        let mut res = ensure_sufficient_stack(|| {
911            loop {
912                let has_question =
913                    if self.prev_token == TokenKind::Ident(kw::Return, IdentIsRaw::No) {
914                        // We are using noexpect here because we don't expect a `?` directly after
915                        // a `return` which could be suggested otherwise.
916                        self.eat_noexpect(&token::Question)
917                    } else {
918                        self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Question,
    token_type: crate::parser::token_type::TokenType::Question,
}exp!(Question))
919                    };
920                if has_question {
921                    // `expr?`
922                    e = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Try(e));
923                    continue;
924                }
925                let has_dot = if self.prev_token == TokenKind::Ident(kw::Return, IdentIsRaw::No) {
926                    // We are using noexpect here because we don't expect a `.` directly after
927                    // a `return` which could be suggested otherwise.
928                    self.eat_noexpect(&token::Dot)
929                } else if self.token == TokenKind::RArrow && self.may_recover() {
930                    // Recovery for `expr->suffix`.
931                    self.bump();
932                    let span = self.prev_token.span;
933                    self.dcx().emit_err(diagnostics::ExprRArrowCall { span });
934                    true
935                } else {
936                    self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Dot,
    token_type: crate::parser::token_type::TokenType::Dot,
}exp!(Dot))
937                };
938                if has_dot {
939                    // expr.f
940                    e = self.parse_dot_suffix_expr(lo, e)?;
941                    continue;
942                }
943                if self.expr_is_complete(&e) {
944                    return Ok(e);
945                }
946                e = match self.token.kind {
947                    token::OpenParen => self.parse_expr_fn_call(lo, e),
948                    token::OpenBracket => self.parse_expr_index(lo, e)?,
949                    _ => return Ok(e),
950                }
951            }
952        });
953
954        // Stitch the list of outer attributes onto the return value. A little
955        // bit ugly, but the best way given the current code structure.
956        if !attrs.is_empty()
957            && let Ok(expr) = &mut res
958        {
959            mem::swap(&mut expr.attrs, &mut attrs);
960            expr.attrs.extend(attrs)
961        }
962        res
963    }
964
965    pub(super) fn parse_dot_suffix_expr(
966        &mut self,
967        lo: Span,
968        base: Box<Expr>,
969    ) -> PResult<'a, Box<Expr>> {
970        // At this point we've consumed something like `expr.` and `self.token` holds the token
971        // after the dot.
972        match self.token.uninterpolate().kind {
973            token::Ident(..) => self.parse_dot_suffix(base, lo),
974            token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) => {
975                let ident_span = self.token.span;
976                self.bump();
977                Ok(self.mk_expr_tuple_field_access(lo, ident_span, base, symbol, suffix))
978            }
979            token::Literal(token::Lit { kind: token::Float, symbol, suffix }) => {
980                Ok(match self.break_up_float(symbol, self.token.span) {
981                    // 1e2
982                    DestructuredFloat::Single(sym, _sp) => {
983                        // `foo.1e2`: a single complete dot access, fully consumed. We end up with
984                        // the `1e2` token in `self.prev_token` and the following token in
985                        // `self.token`.
986                        let ident_span = self.token.span;
987                        self.bump();
988                        self.mk_expr_tuple_field_access(lo, ident_span, base, sym, suffix)
989                    }
990                    // 1.
991                    DestructuredFloat::TrailingDot(sym, ident_span, dot_span) => {
992                        // `foo.1.`: a single complete dot access and the start of another.
993                        // We end up with the `sym` (`1`) token in `self.prev_token` and a dot in
994                        // `self.token`.
995                        if !suffix.is_none() {
    ::core::panicking::panic("assertion failed: suffix.is_none()")
};assert!(suffix.is_none());
996                        self.token = Token::new(token::Ident(sym, IdentIsRaw::No), ident_span);
997                        self.bump_with((Token::new(token::Dot, dot_span), self.token_spacing));
998                        self.mk_expr_tuple_field_access(lo, ident_span, base, sym, None)
999                    }
1000                    // 1.2 | 1.2e3
1001                    DestructuredFloat::MiddleDot(
1002                        sym1,
1003                        ident1_span,
1004                        _dot_span,
1005                        sym2,
1006                        ident2_span,
1007                    ) => {
1008                        // `foo.1.2` (or `foo.1.2e3`): two complete dot accesses. We end up with
1009                        // the `sym2` (`2` or `2e3`) token in `self.prev_token` and the following
1010                        // token in `self.token`.
1011                        let next_token2 =
1012                            Token::new(token::Ident(sym2, IdentIsRaw::No), ident2_span);
1013                        self.bump_with((next_token2, self.token_spacing));
1014                        self.bump();
1015                        let base1 =
1016                            self.mk_expr_tuple_field_access(lo, ident1_span, base, sym1, None);
1017                        self.mk_expr_tuple_field_access(lo, ident2_span, base1, sym2, suffix)
1018                    }
1019                    DestructuredFloat::Error => base,
1020                })
1021            }
1022            _ => {
1023                self.error_unexpected_after_dot();
1024                Ok(base)
1025            }
1026        }
1027    }
1028
1029    fn error_unexpected_after_dot(&self) {
1030        let actual = super::token_descr(&self.token);
1031        let span = self.token.span;
1032        let sm = self.psess.source_map();
1033        let (span, actual) = match (&self.token.kind, self.subparser_name) {
1034            (token::Eof, Some(_)) if let Ok(snippet) = sm.span_to_snippet(sm.next_point(span)) => {
1035                (span.shrink_to_hi(), ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", snippet))
    })format!("`{}`", snippet))
1036            }
1037            (token::CloseInvisible(InvisibleOrigin::MetaVar(_)), _) => {
1038                // No need to report an error. This case will only occur when parsing a pasted
1039                // metavariable, and we should have emitted an error when parsing the macro call in
1040                // the first place. E.g. in this code:
1041                // ```
1042                // macro_rules! m { ($e:expr) => { $e }; }
1043                //
1044                // fn main() {
1045                //     let f = 1;
1046                //     m!(f.);
1047                // }
1048                // ```
1049                // we'll get an error "unexpected token: `)` when parsing the `m!(f.)`, so we don't
1050                // want to issue a second error when parsing the expansion `«f.»` (where `«`/`»`
1051                // represent the invisible delimiters).
1052                self.dcx().span_delayed_bug(span, "bad dot expr in metavariable");
1053                return;
1054            }
1055            _ => (span, actual),
1056        };
1057        self.dcx().emit_err(diagnostics::UnexpectedTokenAfterDot { span, actual });
1058    }
1059
1060    /// We need an identifier or integer, but the next token is a float.
1061    /// Break the float into components to extract the identifier or integer.
1062    ///
1063    /// See also [`TokenKind::break_two_token_op`] which does similar splitting of `>>` into `>`.
1064    //
1065    // FIXME: With current `TokenCursor` it's hard to break tokens into more than 2
1066    //  parts unless those parts are processed immediately. `TokenCursor` should either
1067    //  support pushing "future tokens" (would be also helpful to `break_and_eat`), or
1068    //  we should break everything including floats into more basic proc-macro style
1069    //  tokens in the lexer (probably preferable).
1070    pub(super) fn break_up_float(&self, float: Symbol, span: Span) -> DestructuredFloat {
1071        #[derive(#[automatically_derived]
impl ::core::fmt::Debug for FloatComponent {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            FloatComponent::IdentLike(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "IdentLike", &__self_0),
            FloatComponent::Punct(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Punct",
                    &__self_0),
        }
    }
}Debug)]
1072        enum FloatComponent {
1073            IdentLike(String),
1074            Punct(char),
1075        }
1076        use FloatComponent::*;
1077
1078        let float_str = float.as_str();
1079        let mut components = Vec::new();
1080        let mut ident_like = String::new();
1081        for c in float_str.chars() {
1082            if c == '_' || c.is_ascii_alphanumeric() {
1083                ident_like.push(c);
1084            } else if #[allow(non_exhaustive_omitted_patterns)] match c {
    '.' | '+' | '-' => true,
    _ => false,
}matches!(c, '.' | '+' | '-') {
1085                if !ident_like.is_empty() {
1086                    components.push(IdentLike(mem::take(&mut ident_like)));
1087                }
1088                components.push(Punct(c));
1089            } else {
1090                {
    ::core::panicking::panic_fmt(format_args!("unexpected character in a float token: {0:?}",
            c));
}panic!("unexpected character in a float token: {c:?}")
1091            }
1092        }
1093        if !ident_like.is_empty() {
1094            components.push(IdentLike(ident_like));
1095        }
1096
1097        // With proc macros the span can refer to anything, the source may be too short,
1098        // or too long, or non-ASCII. It only makes sense to break our span into components
1099        // if its underlying text is identical to our float literal.
1100        let can_take_span_apart =
1101            || self.span_to_snippet(span).as_deref() == Ok(float_str).as_deref();
1102
1103        match &*components {
1104            // 1e2
1105            [IdentLike(i)] => DestructuredFloat::Single(Symbol::intern(i), span),
1106            // 1.
1107            [IdentLike(left), Punct('.')] => {
1108                let (left_span, dot_span) = if can_take_span_apart() {
1109                    let left_span = span.with_hi(span.lo() + BytePos::from_usize(left.len()));
1110                    let dot_span = span.with_lo(left_span.hi());
1111                    (left_span, dot_span)
1112                } else {
1113                    (span, span)
1114                };
1115                let left = Symbol::intern(left);
1116                DestructuredFloat::TrailingDot(left, left_span, dot_span)
1117            }
1118            // 1.2 | 1.2e3
1119            [IdentLike(left), Punct('.'), IdentLike(right)] => {
1120                let (left_span, dot_span, right_span) = if can_take_span_apart() {
1121                    let left_span = span.with_hi(span.lo() + BytePos::from_usize(left.len()));
1122                    let dot_span =
1123                        span.with_lo(left_span.hi()).with_hi(left_span.hi() + BytePos(1));
1124                    let right_span = span.with_lo(dot_span.hi());
1125                    (left_span, dot_span, right_span)
1126                } else {
1127                    (span, span, span)
1128                };
1129                let left = Symbol::intern(left);
1130                let right = Symbol::intern(right);
1131                DestructuredFloat::MiddleDot(left, left_span, dot_span, right, right_span)
1132            }
1133            // 1e+ | 1e- (recovered)
1134            [IdentLike(_), Punct('+' | '-')] |
1135            // 1e+2 | 1e-2
1136            [IdentLike(_), Punct('+' | '-'), IdentLike(_)] |
1137            // 1.2e+ | 1.2e-
1138            [IdentLike(_), Punct('.'), IdentLike(_), Punct('+' | '-')] |
1139            // 1.2e+3 | 1.2e-3
1140            [IdentLike(_), Punct('.'), IdentLike(_), Punct('+' | '-'), IdentLike(_)] => {
1141                // See the FIXME about `TokenCursor` above.
1142                self.error_unexpected_after_dot();
1143                DestructuredFloat::Error
1144            }
1145            _ => {
    ::core::panicking::panic_fmt(format_args!("unexpected components in a float token: {0:?}",
            components));
}panic!("unexpected components in a float token: {components:?}"),
1146        }
1147    }
1148
1149    /// Parse the field access used in offset_of, matched by `$(e:expr)+`.
1150    /// Currently returns a list of idents. However, it should be possible in
1151    /// future to also do array indices, which might be arbitrary expressions.
1152    pub(crate) fn parse_floating_field_access(&mut self) -> PResult<'a, ThinVec<Ident>> {
1153        let mut fields = ThinVec::new();
1154        let mut trailing_dot = None;
1155
1156        loop {
1157            // This is expected to use a metavariable $(args:expr)+, but the builtin syntax
1158            // could be called directly. Calling `parse_expr` allows this function to only
1159            // consider `Expr`s.
1160            let expr = self.parse_expr()?;
1161            let mut current = &expr;
1162            let start_idx = fields.len();
1163            loop {
1164                match current.kind {
1165                    ExprKind::Field(ref left, right) => {
1166                        // Field access is read right-to-left.
1167                        fields.insert(start_idx, right);
1168                        trailing_dot = None;
1169                        current = left;
1170                    }
1171                    // Parse this both to give helpful error messages and to
1172                    // verify it can be done with this parser setup.
1173                    ExprKind::Index(ref left, ref _right, span) => {
1174                        self.dcx().emit_err(diagnostics::ArrayIndexInOffsetOf(span));
1175                        current = left;
1176                    }
1177                    ExprKind::Lit(token::Lit {
1178                        kind: token::Float | token::Integer,
1179                        symbol,
1180                        suffix,
1181                    }) => {
1182                        if let Some(suffix) = suffix {
1183                            self.dcx().emit_err(diagnostics::InvalidLiteralSuffixOnTupleIndex {
1184                                span: current.span,
1185                                suffix,
1186                            });
1187                        }
1188                        match self.break_up_float(symbol, current.span) {
1189                            // 1e2
1190                            DestructuredFloat::Single(sym, sp) => {
1191                                trailing_dot = None;
1192                                fields.insert(start_idx, Ident::new(sym, sp));
1193                            }
1194                            // 1.
1195                            DestructuredFloat::TrailingDot(sym, sym_span, dot_span) => {
1196                                if !suffix.is_none() {
    ::core::panicking::panic("assertion failed: suffix.is_none()")
};assert!(suffix.is_none());
1197                                trailing_dot = Some(dot_span);
1198                                fields.insert(start_idx, Ident::new(sym, sym_span));
1199                            }
1200                            // 1.2 | 1.2e3
1201                            DestructuredFloat::MiddleDot(
1202                                symbol1,
1203                                span1,
1204                                _dot_span,
1205                                symbol2,
1206                                span2,
1207                            ) => {
1208                                trailing_dot = None;
1209                                fields.insert(start_idx, Ident::new(symbol2, span2));
1210                                fields.insert(start_idx, Ident::new(symbol1, span1));
1211                            }
1212                            DestructuredFloat::Error => {
1213                                trailing_dot = None;
1214                                fields.insert(start_idx, Ident::new(symbol, self.prev_token.span));
1215                            }
1216                        }
1217                        break;
1218                    }
1219                    ExprKind::Path(None, Path { ref segments, .. }) => {
1220                        match &segments[..] {
1221                            [PathSegment { ident, args: None, .. }] => {
1222                                trailing_dot = None;
1223                                fields.insert(start_idx, *ident)
1224                            }
1225                            _ => {
1226                                self.dcx().emit_err(diagnostics::InvalidOffsetOf(current.span));
1227                                break;
1228                            }
1229                        }
1230                        break;
1231                    }
1232                    _ => {
1233                        self.dcx().emit_err(diagnostics::InvalidOffsetOf(current.span));
1234                        break;
1235                    }
1236                }
1237            }
1238
1239            if self.token.kind.close_delim().is_some() || self.token.kind == token::Comma {
1240                break;
1241            } else if trailing_dot.is_none() {
1242                // This loop should only repeat if there is a trailing dot.
1243                self.dcx().emit_err(diagnostics::InvalidOffsetOf(self.token.span));
1244                break;
1245            }
1246        }
1247        if let Some(dot) = trailing_dot {
1248            self.dcx().emit_err(diagnostics::InvalidOffsetOf(dot));
1249        }
1250        Ok(fields.into_iter().collect())
1251    }
1252
1253    fn mk_expr_tuple_field_access(
1254        &self,
1255        lo: Span,
1256        ident_span: Span,
1257        base: Box<Expr>,
1258        field: Symbol,
1259        suffix: Option<Symbol>,
1260    ) -> Box<Expr> {
1261        if let Some(suffix) = suffix {
1262            self.dcx().emit_err(diagnostics::InvalidLiteralSuffixOnTupleIndex {
1263                span: ident_span,
1264                suffix,
1265            });
1266        }
1267        self.mk_expr(lo.to(ident_span), ExprKind::Field(base, Ident::new(field, ident_span)))
1268    }
1269
1270    /// Parse a function call expression, `expr(...)`.
1271    fn parse_expr_fn_call(&mut self, lo: Span, fun: Box<Expr>) -> Box<Expr> {
1272        let snapshot = if self.token == token::OpenParen {
1273            Some((self.create_snapshot_for_diagnostic(), fun.kind.clone()))
1274        } else {
1275            None
1276        };
1277        let open_paren = self.token.span;
1278        let call_depth = self.token_cursor.depth();
1279
1280        let seq = match self.parse_expr_paren_seq() {
1281            Ok(args) => Ok(self.mk_expr(lo.to(self.prev_token.span), self.mk_call(fun, args))),
1282            Err(err)
1283                if self.is_expected_raw_ref_mut() && self.token_cursor.depth() == call_depth =>
1284            {
1285                let guar = err.emit();
1286                // Preserve the call expression so later passes can still diagnose the callee,
1287                // while treating the malformed `&raw <expr>` argument as an error expression.
1288                let args = self.recover_raw_ref_call_args(guar);
1289                return self.mk_expr(lo.to(self.prev_token.span), self.mk_call(fun, args));
1290            }
1291            Err(err) => Err(err),
1292        };
1293        match self.maybe_recover_struct_lit_bad_delims(lo, open_paren, seq, snapshot) {
1294            Ok(expr) => expr,
1295            Err(err) => self.recover_seq_parse_error(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenParen,
    token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen), crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseParen,
    token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen), lo, err),
1296        }
1297    }
1298
1299    fn recover_raw_ref_call_args(&mut self, guar: ErrorGuaranteed) -> ThinVec<Box<Expr>> {
1300        let err_span = self.prev_token.span.to(self.token.span);
1301        let mut args = {
    let len = [()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(self.mk_expr_err(err_span, guar));
    vec
}thin_vec![self.mk_expr_err(err_span, guar)];
1302        while !self.token.kind.is_close_delim_or_eof() {
1303            if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma)) {
1304                if !self.token.kind.is_close_delim_or_eof() {
1305                    args.push(self.mk_expr_err(self.prev_token.span.shrink_to_hi(), guar));
1306                }
1307            } else {
1308                self.parse_token_tree();
1309            }
1310        }
1311        let _ = self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseParen,
    token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen));
1312        args
1313    }
1314
1315    /// If we encounter a parser state that looks like the user has written a `struct` literal with
1316    /// parentheses instead of braces, recover the parser state and provide suggestions.
1317    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("maybe_recover_struct_lit_bad_delims",
                                    "rustc_parse::parser::expr", ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_parse/src/parser/expr.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1317u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_parse::parser::expr"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("lo")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("lo");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("open_paren")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("open_paren");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&lo)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&open_paren)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: PResult<'a, Box<Expr>> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            match (self.may_recover(), seq, snapshot) {
                (true, Err(err),
                    Some((mut snapshot, ExprKind::Path(None, path)))) => {
                    snapshot.bump();
                    match snapshot.parse_struct_fields(path.clone(), false,
                            crate::parser::token_type::ExpTokenPair {
                                tok: rustc_ast::token::CloseParen,
                                token_type: crate::parser::token_type::TokenType::CloseParen,
                            }) {
                        Ok((fields, ..)) if
                            snapshot.eat(crate::parser::token_type::ExpTokenPair {
                                    tok: rustc_ast::token::CloseParen,
                                    token_type: crate::parser::token_type::TokenType::CloseParen,
                                }) => {
                            self.restore_snapshot(snapshot);
                            let close_paren = self.prev_token.span;
                            let span = lo.to(close_paren);
                            let fields: Vec<_> =
                                fields.into_iter().filter(|field|
                                            !field.is_shorthand).collect();
                            let guar =
                                if !fields.is_empty() &&
                                        self.span_to_snippet(close_paren).is_ok_and(|snippet|
                                                snippet == ")") {
                                    err.cancel();
                                    let type_str = pprust::path_to_string(&path);
                                    self.dcx().create_err(diagnostics::ParenthesesWithStructFields {
                                                span,
                                                braces_for_struct: diagnostics::BracesForStructLiteral {
                                                    first: open_paren,
                                                    second: close_paren,
                                                    r#type: type_str.clone(),
                                                },
                                                no_fields_for_fn: diagnostics::NoFieldsForFnCall {
                                                    r#type: type_str,
                                                    fields: fields.into_iter().map(|field|
                                                                field.span.until(field.expr.span)).collect(),
                                                },
                                            }).emit()
                                } else { err.emit() };
                            Ok(self.mk_expr_err(span, guar))
                        }
                        Ok(_) => Err(err),
                        Err(err2) => { err2.cancel(); Err(err) }
                    }
                }
                (_, seq, _) => seq,
            }
        }
    }
}#[instrument(skip(self, seq, snapshot), level = "trace")]
1318    fn maybe_recover_struct_lit_bad_delims(
1319        &mut self,
1320        lo: Span,
1321        open_paren: Span,
1322        seq: PResult<'a, Box<Expr>>,
1323        snapshot: Option<(SnapshotParser<'a>, ExprKind)>,
1324    ) -> PResult<'a, Box<Expr>> {
1325        match (self.may_recover(), seq, snapshot) {
1326            (true, Err(err), Some((mut snapshot, ExprKind::Path(None, path)))) => {
1327                snapshot.bump(); // `(`
1328                match snapshot.parse_struct_fields(path.clone(), false, exp!(CloseParen)) {
1329                    Ok((fields, ..)) if snapshot.eat(exp!(CloseParen)) => {
1330                        // We are certain we have `Enum::Foo(a: 3, b: 4)`, suggest
1331                        // `Enum::Foo { a: 3, b: 4 }` or `Enum::Foo(3, 4)`.
1332                        self.restore_snapshot(snapshot);
1333                        let close_paren = self.prev_token.span;
1334                        let span = lo.to(close_paren);
1335                        // filter shorthand fields
1336                        let fields: Vec<_> =
1337                            fields.into_iter().filter(|field| !field.is_shorthand).collect();
1338
1339                        let guar = if !fields.is_empty() &&
1340                            // `token.kind` should not be compared here.
1341                            // This is because the `snapshot.token.kind` is treated as the same as
1342                            // that of the open delim in `TokenTreesReader::parse_token_tree`, even
1343                            // if they are different.
1344                            self.span_to_snippet(close_paren).is_ok_and(|snippet| snippet == ")")
1345                        {
1346                            err.cancel();
1347                            let type_str = pprust::path_to_string(&path);
1348                            self.dcx()
1349                                .create_err(diagnostics::ParenthesesWithStructFields {
1350                                    span,
1351                                    braces_for_struct: diagnostics::BracesForStructLiteral {
1352                                        first: open_paren,
1353                                        second: close_paren,
1354                                        r#type: type_str.clone(),
1355                                    },
1356                                    no_fields_for_fn: diagnostics::NoFieldsForFnCall {
1357                                        r#type: type_str,
1358                                        fields: fields
1359                                            .into_iter()
1360                                            .map(|field| field.span.until(field.expr.span))
1361                                            .collect(),
1362                                    },
1363                                })
1364                                .emit()
1365                        } else {
1366                            err.emit()
1367                        };
1368                        Ok(self.mk_expr_err(span, guar))
1369                    }
1370                    Ok(_) => Err(err),
1371                    Err(err2) => {
1372                        err2.cancel();
1373                        Err(err)
1374                    }
1375                }
1376            }
1377            (_, seq, _) => seq,
1378        }
1379    }
1380
1381    /// Parse an indexing expression `expr[...]`.
1382    fn parse_expr_index(&mut self, lo: Span, base: Box<Expr>) -> PResult<'a, Box<Expr>> {
1383        let prev_span = self.prev_token.span;
1384        let open_delim_span = self.token.span;
1385        self.bump(); // `[`
1386        let index = self.parse_expr()?;
1387        self.suggest_missing_semicolon_before_array(prev_span, open_delim_span)?;
1388        self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseBracket,
    token_type: crate::parser::token_type::TokenType::CloseBracket,
}exp!(CloseBracket))?;
1389        Ok(self.mk_expr(
1390            lo.to(self.prev_token.span),
1391            self.mk_index(base, index, open_delim_span.to(self.prev_token.span)),
1392        ))
1393    }
1394
1395    /// Assuming we have just parsed `.`, continue parsing into an expression.
1396    fn parse_dot_suffix(&mut self, self_arg: Box<Expr>, lo: Span) -> PResult<'a, Box<Expr>> {
1397        if self.token_uninterpolated_span().at_least_rust_2018() && self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Await,
    token_type: crate::parser::token_type::TokenType::KwAwait,
}exp!(Await)) {
1398            return Ok(self.mk_await_expr(self_arg, lo));
1399        }
1400
1401        if self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Use,
    token_type: crate::parser::token_type::TokenType::KwUse,
}exp!(Use)) {
1402            let use_span = self.prev_token.span;
1403            self.psess.gated_spans.gate(sym::ergonomic_clones, use_span);
1404            return Ok(self.mk_use_expr(self_arg, lo));
1405        }
1406
1407        // Post-fix match
1408        if self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Match,
    token_type: crate::parser::token_type::TokenType::KwMatch,
}exp!(Match)) {
1409            let match_span = self.prev_token.span;
1410            self.psess.gated_spans.gate(sym::postfix_match, match_span);
1411            return self.parse_match_block(lo, match_span, self_arg, MatchKind::Postfix);
1412        }
1413
1414        // Parse a postfix `yield`.
1415        if self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Yield,
    token_type: crate::parser::token_type::TokenType::KwYield,
}exp!(Yield)) {
1416            let yield_span = self.prev_token.span;
1417            self.psess.gated_spans.gate(sym::yield_expr, yield_span);
1418            return Ok(
1419                self.mk_expr(lo.to(yield_span), ExprKind::Yield(YieldKind::Postfix(self_arg)))
1420            );
1421        }
1422
1423        let fn_span_lo = self.token.span;
1424        let mut seg = self.parse_path_segment(PathStyle::Expr, None)?;
1425        self.check_trailing_angle_brackets(&seg, &[crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenParen,
    token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen)]);
1426        self.check_turbofish_missing_angle_brackets(&mut seg);
1427
1428        if self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenParen,
    token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen)) {
1429            // Method call `expr.f()`
1430            let args = self.parse_expr_paren_seq()?;
1431            let fn_span = fn_span_lo.to(self.prev_token.span);
1432            let span = lo.to(self.prev_token.span);
1433            Ok(self.mk_expr(
1434                span,
1435                ExprKind::MethodCall(Box::new(ast::MethodCall {
1436                    seg,
1437                    receiver: self_arg,
1438                    args,
1439                    span: fn_span,
1440                })),
1441            ))
1442        } else {
1443            // Field access `expr.f`
1444            let span = lo.to(self.prev_token.span);
1445            if let Some(args) = seg.args {
1446                // See `StashKey::GenericInFieldExpr` for more info on why we stash this.
1447                self.dcx()
1448                    .create_err(diagnostics::FieldExpressionWithGeneric(args.span()))
1449                    .stash(seg.ident.span, StashKey::GenericInFieldExpr);
1450            }
1451
1452            Ok(self.mk_expr(span, ExprKind::Field(self_arg, seg.ident)))
1453        }
1454    }
1455
1456    /// At the bottom (top?) of the precedence hierarchy,
1457    /// Parses things like parenthesized exprs, macros, `return`, etc.
1458    ///
1459    /// N.B., this does not parse outer attributes, and is private because it only works
1460    /// correctly if called from `parse_expr_dot_or_call`.
1461    fn parse_expr_bottom(&mut self) -> PResult<'a, Box<Expr>> {
1462        if true && self.may_recover() &&
                let Some(mv_kind) = self.token.is_metavar_seq() &&
            let token::MetaVarKind::Ty { .. } = mv_kind &&
        self.check_noexpect_past_close_delim(&token::PathSep) {
    let ty =
        self.eat_metavar_seq(mv_kind,
                |this|
                    this.parse_ty_no_question_mark_recover()).expect("metavar seq ty");
    return self.maybe_recover_from_bad_qpath_stage_2(self.prev_token.span,
            ty);
};maybe_recover_from_interpolated_ty_qpath!(self, true);
1463
1464        let span = self.token.span;
1465        if let Some(expr) = self.eat_metavar_seq_with_matcher(
1466            |mv_kind| #[allow(non_exhaustive_omitted_patterns)] match mv_kind {
    MetaVarKind::Expr { .. } => true,
    _ => false,
}matches!(mv_kind, MetaVarKind::Expr { .. }),
1467            |this| {
1468                // Force collection (as opposed to just `parse_expr`) is required to avoid the
1469                // attribute duplication seen in #138478.
1470                let expr = this.parse_expr_force_collect();
1471                // FIXME(nnethercote) Sometimes with expressions we get a trailing comma, possibly
1472                // related to the FIXME in `collect_tokens_for_expr`. Examples are the multi-line
1473                // `assert_eq!` calls involving arguments annotated with `#[rustfmt::skip]` in
1474                // `compiler/rustc_index/src/bit_set/tests.rs`.
1475                if this.token.kind == token::Comma {
1476                    this.bump();
1477                }
1478                expr
1479            },
1480        ) {
1481            return Ok(expr);
1482        } else if let Some(lit) =
1483            self.eat_metavar_seq(MetaVarKind::Literal, |this| this.parse_literal_maybe_minus())
1484        {
1485            return Ok(lit);
1486        } else if let Some(block) =
1487            self.eat_metavar_seq(MetaVarKind::Block, |this| this.parse_block())
1488        {
1489            return Ok(self.mk_expr(span, ExprKind::Block(block, None)));
1490        } else if let Some(path) =
1491            self.eat_metavar_seq(MetaVarKind::Path, |this| this.parse_path(PathStyle::Type))
1492        {
1493            return Ok(self.mk_expr(span, ExprKind::Path(None, path)));
1494        }
1495
1496        // Outer attributes are already parsed and will be
1497        // added to the return value after the fact.
1498
1499        let restrictions = self.restrictions;
1500        self.with_res(restrictions - Restrictions::ALLOW_LET, |this| {
1501            // Note: adding new syntax here? Don't forget to adjust `TokenKind::can_begin_expr()`.
1502            let lo = this.token.span;
1503            if let token::Literal(_) = this.token.kind {
1504                // This match arm is a special-case of the `_` match arm below and
1505                // could be removed without changing functionality, but it's faster
1506                // to have it here, especially for programs with large constants.
1507                this.parse_expr_lit()
1508            } else if this.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenParen,
    token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen)) {
1509                this.parse_expr_tuple_parens(restrictions)
1510            } else if this.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenBrace,
    token_type: crate::parser::token_type::TokenType::OpenBrace,
}exp!(OpenBrace)) {
1511                if let Some(expr) = this.maybe_recover_bad_struct_literal_path(false)? {
1512                    return Ok(expr);
1513                }
1514                this.parse_expr_block(None, lo, BlockCheckMode::Default)
1515            } else if this.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Or,
    token_type: crate::parser::token_type::TokenType::Or,
}exp!(Or)) || this.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OrOr,
    token_type: crate::parser::token_type::TokenType::OrOr,
}exp!(OrOr)) {
1516                this.parse_expr_closure().map_err(|mut err| {
1517                    // If the input is something like `if a { 1 } else { 2 } | if a { 3 } else { 4 }`
1518                    // then suggest parens around the lhs.
1519                    if let Some(sp) = this.psess.ambiguous_block_expr_parse.borrow().get(&lo) {
1520                        err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp));
1521                    }
1522                    err
1523                })
1524            } else if this.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenBracket,
    token_type: crate::parser::token_type::TokenType::OpenBracket,
}exp!(OpenBracket)) {
1525                this.parse_expr_array_or_repeat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseBracket,
    token_type: crate::parser::token_type::TokenType::CloseBracket,
}exp!(CloseBracket))
1526            } else if this.is_builtin() {
1527                this.parse_expr_builtin()
1528            } else if this.check_path() {
1529                this.parse_expr_path_start()
1530            } else if this.check_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Move,
    token_type: crate::parser::token_type::TokenType::KwMove,
}exp!(Move))
1531                || this.check_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Use,
    token_type: crate::parser::token_type::TokenType::KwUse,
}exp!(Use))
1532                || this.check_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Static,
    token_type: crate::parser::token_type::TokenType::KwStatic,
}exp!(Static))
1533                || this.check_const_closure()
1534            {
1535                this.parse_expr_closure()
1536            } else if this.eat_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::If,
    token_type: crate::parser::token_type::TokenType::KwIf,
}exp!(If)) {
1537                this.parse_expr_if()
1538            } else if this.check_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::For,
    token_type: crate::parser::token_type::TokenType::KwFor,
}exp!(For)) {
1539                if this.choose_generics_over_qpath(1) {
1540                    this.parse_expr_closure()
1541                } else {
1542                    if !this.eat_keyword(crate::parser::token_type::ExpKeywordPair {
                kw: rustc_span::symbol::kw::For,
                token_type: crate::parser::token_type::TokenType::KwFor,
            }) {
    ::core::panicking::panic("assertion failed: this.eat_keyword(exp!(For))")
};assert!(this.eat_keyword(exp!(For)));
1543                    this.parse_expr_for(None, lo)
1544                }
1545            } else if this.eat_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::While,
    token_type: crate::parser::token_type::TokenType::KwWhile,
}exp!(While)) {
1546                this.parse_expr_while(None, lo)
1547            } else if let Some(label) = this.eat_label() {
1548                this.parse_expr_labeled(label, true)
1549            } else if this.eat_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Loop,
    token_type: crate::parser::token_type::TokenType::KwLoop,
}exp!(Loop)) {
1550                this.parse_expr_loop(None, lo).map_err(|mut err| {
1551                    err.span_label(lo, "while parsing this `loop` expression");
1552                    err
1553                })
1554            } else if this.eat_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Match,
    token_type: crate::parser::token_type::TokenType::KwMatch,
}exp!(Match)) {
1555                this.parse_expr_match().map_err(|mut err| {
1556                    err.span_label(lo, "while parsing this `match` expression");
1557                    err
1558                })
1559            } else if this.eat_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Unsafe,
    token_type: crate::parser::token_type::TokenType::KwUnsafe,
}exp!(Unsafe)) {
1560                this.parse_expr_block(None, lo, BlockCheckMode::Unsafe(ast::UserProvided)).map_err(
1561                    |mut err| {
1562                        err.span_label(lo, "while parsing this `unsafe` expression");
1563                        err
1564                    },
1565                )
1566            } else if this.check_inline_const(0) {
1567                this.parse_const_block(lo, false)
1568            } else if this.may_recover() && this.is_do_catch_block() {
1569                this.recover_do_catch()
1570            } else if this.is_try_block() {
1571                this.expect_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Try,
    token_type: crate::parser::token_type::TokenType::KwTry,
}exp!(Try))?;
1572                this.parse_try_block(lo)
1573            } else if this.eat_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Return,
    token_type: crate::parser::token_type::TokenType::KwReturn,
}exp!(Return)) {
1574                this.parse_expr_return()
1575            } else if this.eat_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Continue,
    token_type: crate::parser::token_type::TokenType::KwContinue,
}exp!(Continue)) {
1576                this.parse_expr_continue(lo)
1577            } else if this.eat_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Break,
    token_type: crate::parser::token_type::TokenType::KwBreak,
}exp!(Break)) {
1578                this.parse_expr_break()
1579            } else if this.eat_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Yield,
    token_type: crate::parser::token_type::TokenType::KwYield,
}exp!(Yield)) {
1580                this.parse_expr_yield()
1581            } else if this.is_do_yeet() {
1582                this.parse_expr_yeet()
1583            } else if this.eat_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Become,
    token_type: crate::parser::token_type::TokenType::KwBecome,
}exp!(Become)) {
1584                this.parse_expr_become()
1585            } else if this.check_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Let,
    token_type: crate::parser::token_type::TokenType::KwLet,
}exp!(Let)) {
1586                this.parse_expr_let(restrictions)
1587            } else if this.eat_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Underscore,
    token_type: crate::parser::token_type::TokenType::KwUnderscore,
}exp!(Underscore)) {
1588                if let Some(expr) = this.maybe_recover_bad_struct_literal_path(true)? {
1589                    return Ok(expr);
1590                }
1591                Ok(this.mk_expr(this.prev_token.span, ExprKind::Underscore))
1592            } else if this.token_uninterpolated_span().at_least_rust_2018() {
1593                // `Span::at_least_rust_2018()` is somewhat expensive; don't get it repeatedly.
1594                let at_async = this.check_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Async,
    token_type: crate::parser::token_type::TokenType::KwAsync,
}exp!(Async));
1595                // check for `gen {}` and `gen move {}`
1596                // or `async gen {}` and `async gen move {}`
1597                // FIXME: (async) gen closures aren't yet parsed.
1598                // FIXME(gen_blocks): Parse `gen async` and suggest swap
1599                if this.token_uninterpolated_span().at_least_rust_2024()
1600                    && this.is_gen_block(kw::Gen, at_async as usize)
1601                {
1602                    this.parse_gen_block()
1603                // Check for `async {` and `async move {`,
1604                } else if this.is_gen_block(kw::Async, 0) {
1605                    this.parse_gen_block()
1606                } else if at_async {
1607                    this.parse_expr_closure()
1608                } else if this.eat_keyword_noexpect(kw::Await) {
1609                    this.recover_incorrect_await_syntax(lo)
1610                } else {
1611                    this.parse_expr_lit()
1612                }
1613            } else {
1614                this.parse_expr_lit()
1615            }
1616        })
1617    }
1618
1619    fn parse_expr_lit(&mut self) -> PResult<'a, Box<Expr>> {
1620        let lo = self.token.span;
1621        match self.parse_opt_token_lit() {
1622            Some((token_lit, _)) => {
1623                let expr = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Lit(token_lit));
1624                self.maybe_recover_from_bad_qpath(expr)
1625            }
1626            None => self.try_macro_suggestion(),
1627        }
1628    }
1629
1630    fn parse_expr_tuple_parens(&mut self, restrictions: Restrictions) -> PResult<'a, Box<Expr>> {
1631        let lo = self.token.span;
1632        self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenParen,
    token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen))?;
1633        let (es, trailing_comma) = match self.parse_seq_to_end(
1634            crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseParen,
    token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen),
1635            SeqSep::trailing_allowed(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma)),
1636            |p| p.parse_expr_catch_underscore(restrictions.intersection(Restrictions::ALLOW_LET)),
1637        ) {
1638            Ok(x) => x,
1639            Err(err) => {
1640                return Ok(self.recover_seq_parse_error(
1641                    crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenParen,
    token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen),
1642                    crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseParen,
    token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen),
1643                    lo,
1644                    err,
1645                ));
1646            }
1647        };
1648        let kind = if es.len() == 1 && #[allow(non_exhaustive_omitted_patterns)] match trailing_comma {
    Trailing::No => true,
    _ => false,
}matches!(trailing_comma, Trailing::No) {
1649            // `(e)` is parenthesized `e`.
1650            ExprKind::Paren(es.into_iter().next().unwrap())
1651        } else {
1652            // `(e,)` is a tuple with only one field, `e`.
1653            ExprKind::Tup(es)
1654        };
1655        let expr = self.mk_expr(lo.to(self.prev_token.span), kind);
1656        self.maybe_recover_from_bad_qpath(expr)
1657    }
1658
1659    fn parse_expr_array_or_repeat(&mut self, close: ExpTokenPair) -> PResult<'a, Box<Expr>> {
1660        let lo = self.token.span;
1661        self.bump(); // `[` or other open delim
1662
1663        let kind = if self.eat(close) {
1664            // Empty vector
1665            ExprKind::Array(ThinVec::new())
1666        } else {
1667            // Non-empty vector
1668            let first_expr = self.parse_expr()?;
1669            if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Semi,
    token_type: crate::parser::token_type::TokenType::Semi,
}exp!(Semi)) {
1670                // Repeating array syntax: `[ 0; 512 ]`
1671                let count = self.parse_expr_anon_const()?;
1672                self.expect(close)?;
1673                ExprKind::Repeat(first_expr, count)
1674            } else if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma)) {
1675                // Vector with two or more elements.
1676                let sep = SeqSep::trailing_allowed(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma));
1677                let (mut exprs, _) = self.parse_seq_to_end(close, sep, |p| p.parse_expr())?;
1678                exprs.insert(0, first_expr);
1679                ExprKind::Array(exprs)
1680            } else {
1681                // Vector with one element
1682                self.expect(close)?;
1683                ExprKind::Array({
    let len = [()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(first_expr);
    vec
}thin_vec![first_expr])
1684            }
1685        };
1686        let expr = self.mk_expr(lo.to(self.prev_token.span), kind);
1687        self.maybe_recover_from_bad_qpath(expr)
1688    }
1689
1690    fn parse_expr_path_start(&mut self) -> PResult<'a, Box<Expr>> {
1691        let maybe_eq_tok = self.prev_token;
1692        let (qself, path) = if self.eat_lt() {
1693            let lt_span = self.prev_token.span;
1694            let (qself, path) = self.parse_qpath(PathStyle::Expr).map_err(|mut err| {
1695                // Suggests using '<=' if there is an error parsing qpath when the previous token
1696                // is an '=' token. Only emits suggestion if the '<' token and '=' token are
1697                // directly adjacent (i.e. '=<')
1698                if maybe_eq_tok == TokenKind::Eq && maybe_eq_tok.span.hi() == lt_span.lo() {
1699                    let eq_lt = maybe_eq_tok.span.to(lt_span);
1700                    err.span_suggestion(eq_lt, "did you mean", "<=", Applicability::Unspecified);
1701                }
1702                err
1703            })?;
1704            (Some(qself), path)
1705        } else {
1706            (None, self.parse_path(PathStyle::Expr)?)
1707        };
1708
1709        // `!`, as an operator, is prefix, so we know this isn't that.
1710        let (span, kind) = if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Bang,
    token_type: crate::parser::token_type::TokenType::Bang,
}exp!(Bang)) {
1711            // MACRO INVOCATION expression
1712            if qself.is_some() {
1713                self.dcx().emit_err(diagnostics::MacroInvocationWithQualifiedPath(path.span));
1714            }
1715            let lo = path.span;
1716            let mac = Box::new(MacCall { path, args: self.parse_delim_args()? });
1717            (lo.to(self.prev_token.span), ExprKind::MacCall(mac))
1718        } else if self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenBrace,
    token_type: crate::parser::token_type::TokenType::OpenBrace,
}exp!(OpenBrace))
1719            && let Some(expr) = self.maybe_parse_struct_expr(&qself, &path)
1720        {
1721            if qself.is_some() {
1722                self.psess.gated_spans.gate(sym::more_qualified_paths, path.span);
1723            }
1724            return expr;
1725        } else {
1726            (path.span, ExprKind::Path(qself, path))
1727        };
1728
1729        let expr = self.mk_expr(span, kind);
1730        self.maybe_recover_from_bad_qpath(expr)
1731    }
1732
1733    /// Parse `'label: $expr`. The label is already parsed.
1734    pub(super) fn parse_expr_labeled(
1735        &mut self,
1736        label_: Label,
1737        mut consume_colon: bool,
1738    ) -> PResult<'a, Box<Expr>> {
1739        let lo = label_.ident.span;
1740        let label = Some(label_);
1741        let ate_colon = self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Colon,
    token_type: crate::parser::token_type::TokenType::Colon,
}exp!(Colon));
1742        let tok_sp = self.token.span;
1743        let expr = if self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::While,
    token_type: crate::parser::token_type::TokenType::KwWhile,
}exp!(While)) {
1744            self.parse_expr_while(label, lo)
1745        } else if self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::For,
    token_type: crate::parser::token_type::TokenType::KwFor,
}exp!(For)) {
1746            self.parse_expr_for(label, lo)
1747        } else if self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Loop,
    token_type: crate::parser::token_type::TokenType::KwLoop,
}exp!(Loop)) {
1748            self.parse_expr_loop(label, lo)
1749        } else if self.check_noexpect(&token::OpenBrace) || self.token.is_metavar_block() {
1750            self.parse_expr_block(label, lo, BlockCheckMode::Default)
1751        } else if !ate_colon
1752            && self.may_recover()
1753            && (self.token.kind.close_delim().is_some() || self.token.is_punct())
1754            && could_be_unclosed_char_literal(label_.ident)
1755        {
1756            let (lit, _) =
1757                self.recover_unclosed_char(label_.ident, Parser::mk_token_lit_char, |self_| {
1758                    self_.dcx().create_err(diagnostics::UnexpectedTokenAfterLabel {
1759                        span: self_.token.span,
1760                        remove_label: None,
1761                        enclose_in_block: None,
1762                    })
1763                });
1764            consume_colon = false;
1765            Ok(self.mk_expr(lo, ExprKind::Lit(lit)))
1766        } else if !ate_colon
1767            && (self.check_noexpect(&TokenKind::Comma) || self.check_noexpect(&TokenKind::Gt))
1768        {
1769            // We're probably inside of a `Path<'a>` that needs a turbofish
1770            let guar = self.dcx().emit_err(diagnostics::UnexpectedTokenAfterLabel {
1771                span: self.token.span,
1772                remove_label: None,
1773                enclose_in_block: None,
1774            });
1775            consume_colon = false;
1776            Ok(self.mk_expr_err(lo, guar))
1777        } else {
1778            let mut err = diagnostics::UnexpectedTokenAfterLabel {
1779                span: self.token.span,
1780                remove_label: None,
1781                enclose_in_block: None,
1782            };
1783
1784            // Continue as an expression in an effort to recover on `'label: non_block_expr`.
1785            let expr = self.parse_expr().map(|expr| {
1786                let span = expr.span;
1787
1788                let found_labeled_breaks = {
1789                    struct FindLabeledBreaksVisitor;
1790
1791                    impl<'ast> Visitor<'ast> for FindLabeledBreaksVisitor {
1792                        type Result = ControlFlow<()>;
1793                        fn visit_expr(&mut self, ex: &'ast Expr) -> ControlFlow<()> {
1794                            if let ExprKind::Break(Some(_label), _) = ex.kind {
1795                                ControlFlow::Break(())
1796                            } else {
1797                                walk_expr(self, ex)
1798                            }
1799                        }
1800                    }
1801
1802                    FindLabeledBreaksVisitor.visit_expr(&expr).is_break()
1803                };
1804
1805                // Suggestion involves adding a labeled block.
1806                //
1807                // If there are no breaks that may use this label, suggest removing the label and
1808                // recover to the unmodified expression.
1809                if !found_labeled_breaks {
1810                    err.remove_label = Some(lo.until(span));
1811
1812                    return expr;
1813                }
1814
1815                err.enclose_in_block = Some(diagnostics::UnexpectedTokenAfterLabelSugg {
1816                    left: span.shrink_to_lo(),
1817                    right: span.shrink_to_hi(),
1818                });
1819
1820                // Replace `'label: non_block_expr` with `'label: {non_block_expr}` in order to suppress future errors about `break 'label`.
1821                let stmt = self.mk_stmt(span, StmtKind::Expr(expr));
1822                let blk = self.mk_block({
    let len = [()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(stmt);
    vec
}thin_vec![stmt], BlockCheckMode::Default, span);
1823                self.mk_expr(span, ExprKind::Block(blk, label))
1824            });
1825
1826            self.dcx().emit_err(err);
1827            expr
1828        }?;
1829
1830        if !ate_colon && consume_colon {
1831            self.dcx().emit_err(diagnostics::RequireColonAfterLabeledExpression {
1832                span: expr.span,
1833                label: lo,
1834                label_end: lo.between(tok_sp),
1835            });
1836        }
1837
1838        Ok(expr)
1839    }
1840
1841    /// Emit an error when a char is parsed as a lifetime or label because of a missing quote.
1842    pub(super) fn recover_unclosed_char<L>(
1843        &self,
1844        ident: Ident,
1845        mk_lit_char: impl FnOnce(Symbol, Span) -> L,
1846        err: impl FnOnce(&Self) -> Diag<'a>,
1847    ) -> L {
1848        if !could_be_unclosed_char_literal(ident) {
    ::core::panicking::panic("assertion failed: could_be_unclosed_char_literal(ident)")
};assert!(could_be_unclosed_char_literal(ident));
1849        self.dcx()
1850            .try_steal_modify_and_emit_err(ident.span, StashKey::LifetimeIsChar, |err| {
1851                err.span_suggestion_verbose(
1852                    ident.span.shrink_to_hi(),
1853                    "add `'` to close the char literal",
1854                    "'",
1855                    Applicability::MaybeIncorrect,
1856                );
1857            })
1858            .unwrap_or_else(|| {
1859                err(self)
1860                    .with_span_suggestion_verbose(
1861                        ident.span.shrink_to_hi(),
1862                        "add `'` to close the char literal",
1863                        "'",
1864                        Applicability::MaybeIncorrect,
1865                    )
1866                    .emit()
1867            });
1868        let name = ident.without_first_quote().name;
1869        mk_lit_char(name, ident.span)
1870    }
1871
1872    /// Recover on the syntax `do catch { ... }` suggesting `try { ... }` instead.
1873    fn recover_do_catch(&mut self) -> PResult<'a, Box<Expr>> {
1874        let lo = self.token.span;
1875
1876        self.bump(); // `do`
1877        self.bump(); // `catch`
1878
1879        let span = lo.to(self.prev_token.span);
1880        self.dcx().emit_err(diagnostics::DoCatchSyntaxRemoved { span });
1881
1882        self.parse_try_block(lo)
1883    }
1884
1885    /// Parse an expression if the token can begin one.
1886    fn parse_expr_opt(&mut self) -> PResult<'a, Option<Box<Expr>>> {
1887        Ok(if self.token.can_begin_expr() { Some(self.parse_expr()?) } else { None })
1888    }
1889
1890    /// Parse `"return" expr?`.
1891    fn parse_expr_return(&mut self) -> PResult<'a, Box<Expr>> {
1892        let lo = self.prev_token.span;
1893        let kind = ExprKind::Ret(self.parse_expr_opt()?);
1894        let expr = self.mk_expr(lo.to(self.prev_token.span), kind);
1895        self.maybe_recover_from_bad_qpath(expr)
1896    }
1897
1898    /// Parse `"do" "yeet" expr?`.
1899    fn parse_expr_yeet(&mut self) -> PResult<'a, Box<Expr>> {
1900        let lo = self.token.span;
1901
1902        self.bump(); // `do`
1903        self.bump(); // `yeet`
1904
1905        let kind = ExprKind::Yeet(self.parse_expr_opt()?);
1906
1907        let span = lo.to(self.prev_token.span);
1908        self.psess.gated_spans.gate(sym::yeet_expr, span);
1909        let expr = self.mk_expr(span, kind);
1910        self.maybe_recover_from_bad_qpath(expr)
1911    }
1912
1913    /// Parse `"become" expr`, with `"become"` token already eaten.
1914    fn parse_expr_become(&mut self) -> PResult<'a, Box<Expr>> {
1915        let lo = self.prev_token.span;
1916        let kind = ExprKind::Become(self.parse_expr()?);
1917        let span = lo.to(self.prev_token.span);
1918        self.psess.gated_spans.gate(sym::explicit_tail_calls, span);
1919        let expr = self.mk_expr(span, kind);
1920        self.maybe_recover_from_bad_qpath(expr)
1921    }
1922
1923    /// Parse `"break" (('label (:? expr)?) | expr?)` with `"break"` token already eaten.
1924    /// If the label is followed immediately by a `:` token, the label and `:` are
1925    /// parsed as part of the expression (i.e. a labeled loop). The language team has
1926    /// decided in #87026 to require parentheses as a visual aid to avoid confusion if
1927    /// the break expression of an unlabeled break is a labeled loop (as in
1928    /// `break 'lbl: loop {}`); a labeled break with an unlabeled loop as its value
1929    /// expression only gets a warning for compatibility reasons; and a labeled break
1930    /// with a labeled loop does not even get a warning because there is no ambiguity.
1931    fn parse_expr_break(&mut self) -> PResult<'a, Box<Expr>> {
1932        let lo = self.prev_token.span;
1933        let mut label = self.eat_label();
1934        let kind = if self.token == token::Colon
1935            && let Some(label) = label.take()
1936        {
1937            // The value expression can be a labeled loop, see issue #86948, e.g.:
1938            // `loop { break 'label: loop { break 'label 42; }; }`
1939            let lexpr = self.parse_expr_labeled(label, true)?;
1940            self.dcx().emit_err(diagnostics::LabeledLoopInBreak {
1941                span: lexpr.span,
1942                sub: diagnostics::WrapInParentheses::Expression {
1943                    left: lexpr.span.shrink_to_lo(),
1944                    right: lexpr.span.shrink_to_hi(),
1945                },
1946            });
1947            Some(lexpr)
1948        } else if self.token != token::OpenBrace
1949            || !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
1950        {
1951            let mut expr = self.parse_expr_opt()?;
1952            if let Some(expr) = &mut expr {
1953                if label.is_some()
1954                    && match &expr.kind {
1955                        ExprKind::While(_, _, None)
1956                        | ExprKind::ForLoop(ForLoop { label: None, .. })
1957                        | ExprKind::Loop(_, None, _) => true,
1958                        ExprKind::Block(block, None) => {
1959                            #[allow(non_exhaustive_omitted_patterns)] match block.rules {
    BlockCheckMode::Default => true,
    _ => false,
}matches!(block.rules, BlockCheckMode::Default)
1960                        }
1961                        _ => false,
1962                    }
1963                {
1964                    let span = expr.span;
1965                    self.psess.buffer_lint(
1966                        BREAK_WITH_LABEL_AND_LOOP,
1967                        lo.to(expr.span),
1968                        ast::CRATE_NODE_ID,
1969                        diagnostics::BreakWithLabelAndLoop {
1970                            sub: diagnostics::BreakWithLabelAndLoopSub {
1971                                left: span.shrink_to_lo(),
1972                                right: span.shrink_to_hi(),
1973                            },
1974                        },
1975                    );
1976                }
1977
1978                // Recover `break label aaaaa`
1979                if self.may_recover()
1980                    && let ExprKind::Path(None, p) = &expr.kind
1981                    && let [segment] = &*p.segments
1982                    && let &ast::PathSegment { ident, args: None, .. } = segment
1983                    && let Some(next) = self.parse_expr_opt()?
1984                {
1985                    label = Some(self.recover_ident_into_label(ident));
1986                    *expr = next;
1987                }
1988            }
1989
1990            expr
1991        } else {
1992            None
1993        };
1994        let expr = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Break(label, kind));
1995        self.maybe_recover_from_bad_qpath(expr)
1996    }
1997
1998    /// Parse `"continue" label?`.
1999    fn parse_expr_continue(&mut self, lo: Span) -> PResult<'a, Box<Expr>> {
2000        let mut label = self.eat_label();
2001
2002        // Recover `continue label` -> `continue 'label`
2003        if self.may_recover()
2004            && label.is_none()
2005            && let Some((ident, _)) = self.token.ident()
2006        {
2007            self.bump();
2008            label = Some(self.recover_ident_into_label(ident));
2009        }
2010
2011        let kind = ExprKind::Continue(label);
2012        Ok(self.mk_expr(lo.to(self.prev_token.span), kind))
2013    }
2014
2015    /// Parse `"yield" expr?`.
2016    fn parse_expr_yield(&mut self) -> PResult<'a, Box<Expr>> {
2017        let lo = self.prev_token.span;
2018        let kind = ExprKind::Yield(YieldKind::Prefix(self.parse_expr_opt()?));
2019        let span = lo.to(self.prev_token.span);
2020        self.psess.gated_spans.gate(sym::yield_expr, span);
2021        let expr = self.mk_expr(span, kind);
2022        self.maybe_recover_from_bad_qpath(expr)
2023    }
2024
2025    /// Parse `builtin # ident(args,*)`.
2026    fn parse_expr_builtin(&mut self) -> PResult<'a, Box<Expr>> {
2027        self.parse_builtin(|this, lo, ident| {
2028            Ok(match ident.name {
2029                sym::offset_of => Some(this.parse_expr_offset_of(lo)?),
2030                sym::type_ascribe => Some(this.parse_expr_type_ascribe(lo)?),
2031                sym::wrap_binder => {
2032                    Some(this.parse_expr_unsafe_binder_cast(lo, UnsafeBinderCastKind::Wrap)?)
2033                }
2034                sym::unwrap_binder => {
2035                    Some(this.parse_expr_unsafe_binder_cast(lo, UnsafeBinderCastKind::Unwrap)?)
2036                }
2037                _ => None,
2038            })
2039        })
2040    }
2041
2042    pub(crate) fn parse_builtin<T>(
2043        &mut self,
2044        parse: impl FnOnce(&mut Parser<'a>, Span, Ident) -> PResult<'a, Option<T>>,
2045    ) -> PResult<'a, T> {
2046        let lo = self.token.span;
2047
2048        self.bump(); // `builtin`
2049        self.bump(); // `#`
2050
2051        let Some((ident, IdentIsRaw::No)) = self.token.ident() else {
2052            let err =
2053                self.dcx().create_err(diagnostics::ExpectedBuiltinIdent { span: self.token.span });
2054            return Err(err);
2055        };
2056        self.psess.gated_spans.gate(sym::builtin_syntax, ident.span);
2057        self.bump();
2058
2059        self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenParen,
    token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen))?;
2060        let ret = if let Some(res) = parse(self, lo, ident)? {
2061            Ok(res)
2062        } else {
2063            let err = self.dcx().create_err(diagnostics::UnknownBuiltinConstruct {
2064                span: lo.to(ident.span),
2065                name: ident,
2066            });
2067            return Err(err);
2068        };
2069        self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseParen,
    token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen))?;
2070
2071        ret
2072    }
2073
2074    /// Built-in macro for `offset_of!` expressions.
2075    pub(crate) fn parse_expr_offset_of(&mut self, lo: Span) -> PResult<'a, Box<Expr>> {
2076        let container = self.parse_ty()?;
2077        self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma))?;
2078
2079        let fields = self.parse_floating_field_access()?;
2080        let trailing_comma = self.eat_noexpect(&TokenKind::Comma);
2081
2082        if let Err(mut e) = self.expect_one_of(&[], &[crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseParen,
    token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen)]) {
2083            if trailing_comma {
2084                e.note("unexpected third argument to offset_of");
2085            } else {
2086                e.note("offset_of expects dot-separated field and variant names");
2087            }
2088            e.emit();
2089        }
2090
2091        // Eat tokens until the macro call ends.
2092        if self.may_recover() {
2093            while !self.token.kind.is_close_delim_or_eof() {
2094                self.bump();
2095            }
2096        }
2097
2098        let span = lo.to(self.token.span);
2099        Ok(self.mk_expr(span, ExprKind::OffsetOf(container, fields)))
2100    }
2101
2102    /// Built-in macro for type ascription expressions.
2103    pub(crate) fn parse_expr_type_ascribe(&mut self, lo: Span) -> PResult<'a, Box<Expr>> {
2104        let expr = self.parse_expr()?;
2105        self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma))?;
2106        let ty = self.parse_ty()?;
2107        let span = lo.to(self.token.span);
2108        Ok(self.mk_expr(span, ExprKind::Type(expr, ty)))
2109    }
2110
2111    pub(crate) fn parse_expr_unsafe_binder_cast(
2112        &mut self,
2113        lo: Span,
2114        kind: UnsafeBinderCastKind,
2115    ) -> PResult<'a, Box<Expr>> {
2116        let expr = self.parse_expr()?;
2117        let ty = if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma)) { Some(self.parse_ty()?) } else { None };
2118        let span = lo.to(self.token.span);
2119        Ok(self.mk_expr(span, ExprKind::UnsafeBinderCast(kind, expr, ty)))
2120    }
2121
2122    /// Returns a string literal if the next token is a string literal.
2123    /// In case of error returns `Some(lit)` if the next token is a literal with a wrong kind,
2124    /// and returns `None` if the next token is not literal at all.
2125    pub fn parse_str_lit(&mut self) -> Result<ast::StrLit, Option<MetaItemLit>> {
2126        match self.parse_opt_meta_item_lit() {
2127            Some(lit) => match lit.kind {
2128                ast::LitKind::Str(symbol_unescaped, style) => Ok(ast::StrLit {
2129                    style,
2130                    symbol: lit.symbol,
2131                    suffix: lit.suffix,
2132                    span: lit.span,
2133                    symbol_unescaped,
2134                }),
2135                _ => Err(Some(lit)),
2136            },
2137            None => Err(None),
2138        }
2139    }
2140
2141    pub(crate) fn mk_token_lit_char(name: Symbol, span: Span) -> (token::Lit, Span) {
2142        (token::Lit { symbol: name, suffix: None, kind: token::Char }, span)
2143    }
2144
2145    fn mk_meta_item_lit_char(name: Symbol, span: Span) -> MetaItemLit {
2146        ast::MetaItemLit {
2147            symbol: name,
2148            suffix: None,
2149            kind: ast::LitKind::Char(name.as_str().chars().next().unwrap_or('_')),
2150            span,
2151        }
2152    }
2153
2154    fn handle_missing_lit<L>(
2155        &mut self,
2156        mk_lit_char: impl FnOnce(Symbol, Span) -> L,
2157    ) -> PResult<'a, L> {
2158        let token = self.token;
2159        let err = |self_: &Self| {
2160            let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("unexpected token: {0}",
                super::token_descr(&token)))
    })format!("unexpected token: {}", super::token_descr(&token));
2161            self_.dcx().struct_span_err(token.span, msg)
2162        };
2163        // On an error path, eagerly consider a lifetime to be an unclosed character lit, if that
2164        // makes sense.
2165        if let Some((ident, IdentIsRaw::No)) = self.token.lifetime()
2166            && could_be_unclosed_char_literal(ident)
2167        {
2168            let lt = self.expect_lifetime();
2169            Ok(self.recover_unclosed_char(lt.ident, mk_lit_char, err))
2170        } else {
2171            Err(err(self))
2172        }
2173    }
2174
2175    pub(super) fn parse_token_lit(&mut self) -> PResult<'a, (token::Lit, Span)> {
2176        self.parse_opt_token_lit()
2177            .ok_or(())
2178            .or_else(|()| self.handle_missing_lit(Parser::mk_token_lit_char))
2179    }
2180
2181    pub(super) fn parse_meta_item_lit(&mut self) -> PResult<'a, MetaItemLit> {
2182        self.parse_opt_meta_item_lit()
2183            .ok_or(())
2184            .or_else(|()| self.handle_missing_lit(Parser::mk_meta_item_lit_char))
2185    }
2186
2187    fn recover_after_dot(&mut self) {
2188        if self.token == token::Dot {
2189            // Attempt to recover `.4` as `0.4`. We don't currently have any syntax where
2190            // dot would follow an optional literal, so we do this unconditionally.
2191            let recovered = self.look_ahead(1, |next_token| {
2192                // If it's an integer that looks like a float, then recover as such.
2193                //
2194                // We will never encounter the exponent part of a floating
2195                // point literal here, since there's no use of the exponent
2196                // syntax that also constitutes a valid integer, so we need
2197                // not check for that.
2198                if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) =
2199                    next_token.kind
2200                    && suffix.is_none_or(|s| s == sym::f32 || s == sym::f64)
2201                    && symbol.as_str().chars().all(|c| c.is_numeric() || c == '_')
2202                    && self.token.span.hi() == next_token.span.lo()
2203                {
2204                    let s = String::from("0.") + symbol.as_str();
2205                    let kind = TokenKind::lit(token::Float, Symbol::intern(&s), suffix);
2206                    Some(Token::new(kind, self.token.span.to(next_token.span)))
2207                } else {
2208                    None
2209                }
2210            });
2211            if let Some(recovered) = recovered {
2212                self.dcx().emit_err(diagnostics::FloatLiteralRequiresIntegerPart {
2213                    span: recovered.span,
2214                    suggestion: recovered.span.shrink_to_lo(),
2215                });
2216                self.bump();
2217                self.token = recovered;
2218            }
2219        }
2220    }
2221
2222    /// Keep this in sync with `Token::can_begin_literal_maybe_minus` and
2223    /// `Lit::from_token` (excluding unary negation).
2224    pub fn eat_token_lit(&mut self) -> Option<token::Lit> {
2225        let check_expr = |expr: Box<Expr>| {
2226            if let ast::ExprKind::Lit(token_lit) = expr.kind {
2227                Some(token_lit)
2228            } else if let ast::ExprKind::Unary(UnOp::Neg, inner) = &expr.kind
2229                && let ast::Expr { kind: ast::ExprKind::Lit(_), .. } = **inner
2230            {
2231                None
2232            } else {
2233                {
    ::core::panicking::panic_fmt(format_args!("unexpected reparsed expr/literal: {0:?}",
            expr.kind));
};panic!("unexpected reparsed expr/literal: {:?}", expr.kind);
2234            }
2235        };
2236        match self.token.uninterpolate().kind {
2237            token::Ident(name, IdentIsRaw::No) if name.is_bool_lit() => {
2238                self.bump();
2239                Some(token::Lit::new(token::Bool, name, None))
2240            }
2241            token::Literal(token_lit) => {
2242                self.bump();
2243                Some(token_lit)
2244            }
2245            token::OpenInvisible(InvisibleOrigin::MetaVar(MetaVarKind::Literal)) => {
2246                let lit = self
2247                    .eat_metavar_seq(MetaVarKind::Literal, |this| this.parse_literal_maybe_minus())
2248                    .expect("metavar seq literal");
2249                check_expr(lit)
2250            }
2251            token::OpenInvisible(InvisibleOrigin::MetaVar(
2252                mv_kind @ MetaVarKind::Expr { can_begin_literal_maybe_minus: true, .. },
2253            )) => {
2254                let expr = self
2255                    .eat_metavar_seq(mv_kind, |this| this.parse_expr())
2256                    .expect("metavar seq expr");
2257                check_expr(expr)
2258            }
2259            _ => None,
2260        }
2261    }
2262
2263    /// Matches `lit = true | false | token_lit`.
2264    /// Returns `None` if the next token is not a literal.
2265    fn parse_opt_token_lit(&mut self) -> Option<(token::Lit, Span)> {
2266        self.recover_after_dot();
2267        let span = self.token.span;
2268        self.eat_token_lit().map(|token_lit| (token_lit, span))
2269    }
2270
2271    /// Matches `lit = true | false | token_lit`.
2272    /// Returns `None` if the next token is not a literal.
2273    fn parse_opt_meta_item_lit(&mut self) -> Option<MetaItemLit> {
2274        self.recover_after_dot();
2275        let span = self.token.span;
2276        let uninterpolated_span = self.token_uninterpolated_span();
2277        self.eat_token_lit().map(|token_lit| {
2278            match MetaItemLit::from_token_lit(token_lit, span) {
2279                Ok(lit) => lit,
2280                Err(err) => {
2281                    let guar = report_lit_error(&self.psess, err, token_lit, uninterpolated_span);
2282                    // Pack possible quotes and prefixes from the original literal into
2283                    // the error literal's symbol so they can be pretty-printed faithfully.
2284                    let suffixless_lit = token::Lit::new(token_lit.kind, token_lit.symbol, None);
2285                    let symbol = Symbol::intern(&suffixless_lit.to_string());
2286                    let token_lit = token::Lit::new(token::Err(guar), symbol, token_lit.suffix);
2287                    MetaItemLit::from_token_lit(token_lit, uninterpolated_span).unwrap()
2288                }
2289            }
2290        })
2291    }
2292
2293    /// Matches `'-' lit | lit` (cf. `ast_validation::AstValidator::check_expr_within_pat`).
2294    /// Keep this in sync with `Token::can_begin_literal_maybe_minus`.
2295    pub fn parse_literal_maybe_minus(&mut self) -> PResult<'a, Box<Expr>> {
2296        if let Some(expr) = self.eat_metavar_seq_with_matcher(
2297            |mv_kind| #[allow(non_exhaustive_omitted_patterns)] match mv_kind {
    MetaVarKind::Expr { .. } => true,
    _ => false,
}matches!(mv_kind, MetaVarKind::Expr { .. }),
2298            |this| {
2299                // FIXME(nnethercote) The `expr` case should only match if
2300                // `e` is an `ExprKind::Lit` or an `ExprKind::Unary` containing
2301                // an `UnOp::Neg` and an `ExprKind::Lit`, like how
2302                // `can_begin_literal_maybe_minus` works. But this method has
2303                // been over-accepting for a long time, and to make that change
2304                // here requires also changing some `parse_literal_maybe_minus`
2305                // call sites to accept additional expression kinds. E.g.
2306                // `ExprKind::Path` must be accepted when parsing range
2307                // patterns. That requires some care. So for now, we continue
2308                // being less strict here than we should be.
2309                this.parse_expr()
2310            },
2311        ) {
2312            return Ok(expr);
2313        } else if let Some(lit) =
2314            self.eat_metavar_seq(MetaVarKind::Literal, |this| this.parse_literal_maybe_minus())
2315        {
2316            return Ok(lit);
2317        }
2318
2319        let lo = self.token.span;
2320        let minus_present = self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Minus,
    token_type: crate::parser::token_type::TokenType::Minus,
}exp!(Minus));
2321        let (token_lit, span) = self.parse_token_lit()?;
2322        let expr = self.mk_expr(span, ExprKind::Lit(token_lit));
2323
2324        if minus_present {
2325            Ok(self.mk_expr(lo.to(self.prev_token.span), self.mk_unary(UnOp::Neg, expr)))
2326        } else {
2327            Ok(expr)
2328        }
2329    }
2330
2331    fn is_array_like_block(&mut self) -> bool {
2332        self.token.kind == TokenKind::OpenBrace
2333            && self
2334                .look_ahead(1, |t| #[allow(non_exhaustive_omitted_patterns)] match t.kind {
    TokenKind::Ident(..) | TokenKind::Literal(_) => true,
    _ => false,
}matches!(t.kind, TokenKind::Ident(..) | TokenKind::Literal(_)))
2335            && self.look_ahead(2, |t| t == &token::Comma)
2336            && self.look_ahead(3, |t| t.can_begin_expr())
2337    }
2338
2339    /// Emits a suggestion if it looks like the user meant an array but
2340    /// accidentally used braces, causing the code to be interpreted as a block
2341    /// expression.
2342    fn maybe_suggest_brackets_instead_of_braces(&mut self, lo: Span) -> Option<Box<Expr>> {
2343        let mut snapshot = self.create_snapshot_for_diagnostic();
2344        match snapshot.parse_expr_array_or_repeat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseBrace,
    token_type: crate::parser::token_type::TokenType::CloseBrace,
}exp!(CloseBrace)) {
2345            Ok(arr) => {
2346                let guar = self.dcx().emit_err(diagnostics::ArrayBracketsInsteadOfBraces {
2347                    span: arr.span,
2348                    sub: diagnostics::ArrayBracketsInsteadOfBracesSugg {
2349                        left: lo,
2350                        right: snapshot.prev_token.span,
2351                    },
2352                });
2353
2354                self.restore_snapshot(snapshot);
2355                Some(self.mk_expr_err(arr.span, guar))
2356            }
2357            Err(e) => {
2358                e.cancel();
2359                None
2360            }
2361        }
2362    }
2363
2364    fn suggest_missing_semicolon_before_array(
2365        &self,
2366        prev_span: Span,
2367        open_delim_span: Span,
2368    ) -> PResult<'a, ()> {
2369        if !self.may_recover() {
2370            return Ok(());
2371        }
2372
2373        if self.token == token::Comma {
2374            if !self.psess.source_map().is_multiline(prev_span.until(self.token.span)) {
2375                return Ok(());
2376            }
2377            let mut snapshot = self.create_snapshot_for_diagnostic();
2378            snapshot.bump();
2379            match snapshot.parse_seq_to_before_end(
2380                crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseBracket,
    token_type: crate::parser::token_type::TokenType::CloseBracket,
}exp!(CloseBracket),
2381                SeqSep::trailing_allowed(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma)),
2382                |p| p.parse_expr(),
2383            ) {
2384                Ok(_)
2385                    // When the close delim is `)`, `token.kind` is expected to be `token::CloseParen`,
2386                    // but the actual `token.kind` is `token::CloseBracket`.
2387                    // This is because the `token.kind` of the close delim is treated as the same as
2388                    // that of the open delim in `TokenTreesReader::parse_token_tree`, even if the delimiters of them are different.
2389                    // Therefore, `token.kind` should not be compared here.
2390                    if snapshot
2391                        .span_to_snippet(snapshot.token.span)
2392                        .is_ok_and(|snippet| snippet == "]") =>
2393                {
2394                    return Err(self.dcx().create_err(diagnostics::MissingSemicolonBeforeArray {
2395                        open_delim: open_delim_span,
2396                        semicolon: prev_span.shrink_to_hi(),
2397                    }));
2398                }
2399                Ok(_) => (),
2400                Err(err) => err.cancel(),
2401            }
2402        }
2403        Ok(())
2404    }
2405
2406    /// Parses a block or unsafe block.
2407    pub(super) fn parse_expr_block(
2408        &mut self,
2409        opt_label: Option<Label>,
2410        lo: Span,
2411        blk_mode: BlockCheckMode,
2412    ) -> PResult<'a, Box<Expr>> {
2413        if self.may_recover() && self.is_array_like_block() {
2414            if let Some(arr) = self.maybe_suggest_brackets_instead_of_braces(lo) {
2415                return Ok(arr);
2416            }
2417        }
2418
2419        if self.token.is_metavar_block() {
2420            self.dcx().emit_err(diagnostics::InvalidBlockMacroSegment {
2421                span: self.token.span,
2422                context: lo.to(self.token.span),
2423                wrap: diagnostics::WrapInExplicitBlock {
2424                    lo: self.token.span.shrink_to_lo(),
2425                    hi: self.token.span.shrink_to_hi(),
2426                },
2427            });
2428        }
2429
2430        let (attrs, blk) = self.parse_block_common(lo, blk_mode, None)?;
2431        Ok(self.mk_expr_with_attrs(blk.span, ExprKind::Block(blk, opt_label), attrs))
2432    }
2433
2434    /// Parse a block which takes no attributes and has no label
2435    fn parse_simple_block(&mut self) -> PResult<'a, Box<Expr>> {
2436        let blk = self.parse_block()?;
2437        Ok(self.mk_expr(blk.span, ExprKind::Block(blk, None)))
2438    }
2439
2440    /// Parses a closure expression (e.g., `move |args| expr`).
2441    fn parse_expr_closure(&mut self) -> PResult<'a, Box<Expr>> {
2442        let lo = self.token.span;
2443
2444        let before = self.prev_token;
2445        let binder = if self.check_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::For,
    token_type: crate::parser::token_type::TokenType::KwFor,
}exp!(For)) {
2446            let lo = self.token.span;
2447            let (bound_vars, _) = self.parse_higher_ranked_binder()?;
2448            let span = lo.to(self.prev_token.span);
2449
2450            self.psess.gated_spans.gate(sym::closure_lifetime_binder, span);
2451
2452            ClosureBinder::For { span, generic_params: bound_vars }
2453        } else {
2454            ClosureBinder::NotPresent
2455        };
2456
2457        let constness = self.parse_closure_constness();
2458
2459        let movability = if self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Static,
    token_type: crate::parser::token_type::TokenType::KwStatic,
}exp!(Static)) {
2460            self.psess.gated_spans.gate(sym::coroutines, self.prev_token.span);
2461            Movability::Static
2462        } else {
2463            Movability::Movable
2464        };
2465
2466        let coroutine_kind = if self.token_uninterpolated_span().at_least_rust_2018() {
2467            self.parse_coroutine_kind(Case::Sensitive)
2468        } else {
2469            None
2470        };
2471
2472        if let ClosureBinder::NotPresent = binder
2473            && coroutine_kind.is_some()
2474        {
2475            // coroutine closures and generators can have the same qualifiers, so we might end up
2476            // in here if there is a missing `|` but also no `{`. Adjust the expectations in that case.
2477            self.expected_token_types.insert(TokenType::OpenBrace);
2478        }
2479
2480        let capture_clause = self.parse_capture_clause()?;
2481        let (fn_decl, fn_arg_span) = self.parse_fn_block_decl()?;
2482        let decl_hi = self.prev_token.span;
2483        let mut body = match &fn_decl.output {
2484            // No return type.
2485            FnRetTy::Default(_) => {
2486                let restrictions =
2487                    self.restrictions - Restrictions::STMT_EXPR - Restrictions::ALLOW_LET;
2488                let prev = self.prev_token;
2489                let token = self.token;
2490                let attrs = self.parse_outer_attributes()?;
2491                match self.parse_expr_res(restrictions, attrs) {
2492                    Ok((expr, _)) => expr,
2493                    Err(err) => self.recover_closure_body(err, before, prev, token, lo, decl_hi)?,
2494                }
2495            }
2496            // Explicit return type (`->`) needs block `-> T { }`.
2497            FnRetTy::Ty(ty) => self.parse_closure_block_body(ty.span)?,
2498        };
2499
2500        match coroutine_kind {
2501            Some(CoroutineKind::Async { .. }) => {}
2502            Some(CoroutineKind::Gen { span, .. }) | Some(CoroutineKind::AsyncGen { span, .. }) => {
2503                // Feature-gate `gen ||` and `async gen ||` closures.
2504                // FIXME(gen_blocks): This perhaps should be a different gate.
2505                self.psess.gated_spans.gate(sym::gen_blocks, span);
2506            }
2507            None => {}
2508        }
2509
2510        if self.token == TokenKind::Semi
2511            && let Some((Delimiter::Parenthesis, _)) = self.token_cursor.parent_delim_and_span()
2512            && self.may_recover()
2513        {
2514            // It is likely that the closure body is a block but where the
2515            // braces have been removed. We will recover and eat the next
2516            // statements later in the parsing process.
2517            body = self.mk_expr_err(
2518                body.span,
2519                self.dcx().span_delayed_bug(body.span, "recovered a closure body as a block"),
2520            );
2521        }
2522
2523        let body_span = body.span;
2524
2525        let closure = self.mk_expr(
2526            lo.to(body.span),
2527            ExprKind::Closure(Box::new(ast::Closure {
2528                binder,
2529                capture_clause,
2530                constness,
2531                coroutine_kind,
2532                movability,
2533                fn_decl,
2534                body,
2535                fn_decl_span: lo.to(decl_hi),
2536                fn_arg_span,
2537            })),
2538        );
2539
2540        // Disable recovery for closure body
2541        let spans =
2542            ClosureSpans { whole_closure: closure.span, closing_pipe: decl_hi, body: body_span };
2543        self.current_closure = Some(spans);
2544
2545        Ok(closure)
2546    }
2547
2548    /// If an explicit return type is given, require a block to appear (RFC 968).
2549    fn parse_closure_block_body(&mut self, ret_span: Span) -> PResult<'a, Box<Expr>> {
2550        if self.may_recover()
2551            && self.token.can_begin_expr()
2552            && self.token.kind != TokenKind::OpenBrace
2553            && !self.token.is_metavar_block()
2554        {
2555            let snapshot = self.create_snapshot_for_diagnostic();
2556            let restrictions =
2557                self.restrictions - Restrictions::STMT_EXPR - Restrictions::ALLOW_LET;
2558            let tok = self.token.clone();
2559            match self.parse_expr_res(restrictions, AttrWrapper::empty()) {
2560                Ok((expr, _)) => {
2561                    let descr = super::token_descr(&tok);
2562                    let mut diag = self
2563                        .dcx()
2564                        .struct_span_err(tok.span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected `{{`, found {0}", descr))
    })format!("expected `{{`, found {descr}"));
2565                    diag.span_label(
2566                        ret_span,
2567                        "explicit return type requires closure body to be enclosed in braces",
2568                    );
2569                    diag.multipart_suggestion(
2570                        "wrap the expression in curly braces",
2571                        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(expr.span.shrink_to_lo(), "{ ".to_string()),
                (expr.span.shrink_to_hi(), " }".to_string())]))vec![
2572                            (expr.span.shrink_to_lo(), "{ ".to_string()),
2573                            (expr.span.shrink_to_hi(), " }".to_string()),
2574                        ],
2575                        Applicability::MachineApplicable,
2576                    );
2577                    diag.emit();
2578                    return Ok(expr);
2579                }
2580                Err(diag) => {
2581                    diag.cancel();
2582                    self.restore_snapshot(snapshot);
2583                }
2584            }
2585        }
2586
2587        let body_lo = self.token.span;
2588        self.parse_expr_block(None, body_lo, BlockCheckMode::Default)
2589    }
2590
2591    /// Parses an optional `move` or `use` prefix to a closure-like construct.
2592    fn parse_capture_clause(&mut self) -> PResult<'a, CaptureBy> {
2593        if self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Move,
    token_type: crate::parser::token_type::TokenType::KwMove,
}exp!(Move)) {
2594            let move_kw_span = self.prev_token.span;
2595            // Check for `move async` and recover
2596            if self.check_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Async,
    token_type: crate::parser::token_type::TokenType::KwAsync,
}exp!(Async)) {
2597                let move_async_span = self.token.span.with_lo(self.prev_token.span.data().lo);
2598                Err(self
2599                    .dcx()
2600                    .create_err(diagnostics::AsyncMoveOrderIncorrect { span: move_async_span }))
2601            } else {
2602                Ok(CaptureBy::Value { move_kw: move_kw_span })
2603            }
2604        } else if self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Use,
    token_type: crate::parser::token_type::TokenType::KwUse,
}exp!(Use)) {
2605            let use_kw_span = self.prev_token.span;
2606            self.psess.gated_spans.gate(sym::ergonomic_clones, use_kw_span);
2607            // Check for `use async` and recover
2608            if self.check_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Async,
    token_type: crate::parser::token_type::TokenType::KwAsync,
}exp!(Async)) {
2609                let use_async_span = self.token.span.with_lo(self.prev_token.span.data().lo);
2610                Err(self
2611                    .dcx()
2612                    .create_err(diagnostics::AsyncUseOrderIncorrect { span: use_async_span }))
2613            } else {
2614                Ok(CaptureBy::Use { use_kw: use_kw_span })
2615            }
2616        } else {
2617            Ok(CaptureBy::Ref)
2618        }
2619    }
2620
2621    /// Parses the `|arg, arg|` header of a closure.
2622    fn parse_fn_block_decl(&mut self) -> PResult<'a, (Box<FnDecl>, Span)> {
2623        let arg_start = self.token.span.lo();
2624
2625        let inputs = if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OrOr,
    token_type: crate::parser::token_type::TokenType::OrOr,
}exp!(OrOr)) {
2626            ThinVec::new()
2627        } else {
2628            self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Or,
    token_type: crate::parser::token_type::TokenType::Or,
}exp!(Or))?;
2629            let args = self
2630                .parse_seq_to_before_tokens(
2631                    &[crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Or,
    token_type: crate::parser::token_type::TokenType::Or,
}exp!(Or)],
2632                    &[&token::OrOr],
2633                    SeqSep::trailing_allowed(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma)),
2634                    |p| p.parse_fn_block_param(),
2635                )?
2636                .0;
2637            self.expect_or()?;
2638            args
2639        };
2640        let arg_span = self.prev_token.span.with_lo(arg_start);
2641        let output =
2642            self.parse_ret_ty(AllowPlus::Yes, RecoverQPath::Yes, RecoverReturnSign::Yes)?;
2643
2644        Ok((Box::new(FnDecl { inputs, output }), arg_span))
2645    }
2646
2647    /// Parses a parameter in a closure header (e.g., `|arg, arg|`).
2648    fn parse_fn_block_param(&mut self) -> PResult<'a, Param> {
2649        let lo = self.token.span;
2650        let attrs = self.parse_outer_attributes()?;
2651        self.collect_tokens(None, attrs, ForceCollect::No, |this, attrs| {
2652            let pat = Box::new(this.parse_pat_no_top_alt(Some(Expected::ParameterName), None)?);
2653            let ty = if this.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Colon,
    token_type: crate::parser::token_type::TokenType::Colon,
}exp!(Colon)) {
2654                this.parse_ty()?
2655            } else {
2656                this.mk_ty(pat.span, TyKind::Infer)
2657            };
2658
2659            Ok((
2660                Param {
2661                    attrs,
2662                    ty,
2663                    pat,
2664                    span: lo.to(this.prev_token.span),
2665                    id: DUMMY_NODE_ID,
2666                    is_placeholder: false,
2667                },
2668                Trailing::from(this.token == token::Comma),
2669                UsePreAttrPos::No,
2670            ))
2671        })
2672    }
2673
2674    /// Parses an `if` expression (`if` token already eaten).
2675    fn parse_expr_if(&mut self) -> PResult<'a, Box<Expr>> {
2676        let lo = self.prev_token.span;
2677        // Scoping code checks the top level edition of the `if`; let's match it here.
2678        // The `CondChecker` also checks the edition of the `let` itself, just to make sure.
2679        let let_chains_policy = LetChainsPolicy::EditionDependent { current_edition: lo.edition() };
2680        let cond = self.parse_expr_cond(let_chains_policy)?;
2681        self.parse_if_after_cond(lo, cond)
2682    }
2683
2684    fn parse_if_after_cond(&mut self, lo: Span, mut cond: Box<Expr>) -> PResult<'a, Box<Expr>> {
2685        let cond_span = cond.span;
2686        // Tries to interpret `cond` as either a missing expression if it's a block,
2687        // or as an unfinished expression if it's a binop and the RHS is a block.
2688        // We could probably add more recoveries here too...
2689        let mut recover_block_from_condition = |this: &mut Self| {
2690            let block = match &mut cond.kind {
2691                ExprKind::Binary(Spanned { span: binop_span, .. }, _, right)
2692                    if let ExprKind::Block(_, None) = right.kind =>
2693                {
2694                    let guar = this.dcx().emit_err(diagnostics::IfExpressionMissingThenBlock {
2695                        if_span: lo,
2696                        missing_then_block_sub:
2697                            diagnostics::IfExpressionMissingThenBlockSub::UnfinishedCondition(
2698                                cond_span.shrink_to_lo().to(*binop_span),
2699                            ),
2700                        let_else_sub: None,
2701                    });
2702                    std::mem::replace(right, this.mk_expr_err(binop_span.shrink_to_hi(), guar))
2703                }
2704                ExprKind::Block(_, None) => {
2705                    let guar = this.dcx().emit_err(diagnostics::IfExpressionMissingCondition {
2706                        if_span: lo.with_neighbor(cond.span).shrink_to_hi(),
2707                        block_span: self.psess.source_map().start_point(cond_span),
2708                    });
2709                    std::mem::replace(&mut cond, this.mk_expr_err(cond_span.shrink_to_hi(), guar))
2710                }
2711                _ => {
2712                    return None;
2713                }
2714            };
2715            if let ExprKind::Block(block, _) = &block.kind {
2716                Some(block.clone())
2717            } else {
2718                ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
2719            }
2720        };
2721        // Parse then block
2722        let thn = if self.token.is_keyword(kw::Else) {
2723            if let Some(block) = recover_block_from_condition(self) {
2724                block
2725            } else {
2726                let let_else_sub = #[allow(non_exhaustive_omitted_patterns)] match cond.kind {
    ExprKind::Let(..) => true,
    _ => false,
}matches!(cond.kind, ExprKind::Let(..))
2727                    .then(|| diagnostics::IfExpressionLetSomeSub { if_span: lo.until(cond_span) });
2728
2729                let guar = self.dcx().emit_err(diagnostics::IfExpressionMissingThenBlock {
2730                    if_span: lo,
2731                    missing_then_block_sub:
2732                        diagnostics::IfExpressionMissingThenBlockSub::AddThenBlock(
2733                            cond_span.shrink_to_hi(),
2734                        ),
2735                    let_else_sub,
2736                });
2737                self.mk_block_err(cond_span.shrink_to_hi(), guar)
2738            }
2739        } else {
2740            let attrs = self.parse_outer_attributes()?; // For recovery.
2741            let maybe_fatarrow = self.token;
2742            let block = if self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenBrace,
    token_type: crate::parser::token_type::TokenType::OpenBrace,
}exp!(OpenBrace)) {
2743                self.parse_block()?
2744            } else if let Some(block) = recover_block_from_condition(self) {
2745                block
2746            } else {
2747                self.error_on_extra_if(&cond)?;
2748                // Parse block, which will always fail, but we can add a nice note to the error
2749                self.parse_block().map_err(|mut err| {
2750                        if self.prev_token == token::Semi
2751                            && self.token == token::AndAnd
2752                            && let maybe_let = self.look_ahead(1, |t| t.clone())
2753                            && maybe_let.is_keyword(kw::Let)
2754                        {
2755                            err.span_suggestion(
2756                                self.prev_token.span,
2757                                "consider removing this semicolon to parse the `let` as part of the same chain",
2758                                "",
2759                                Applicability::MachineApplicable,
2760                            ).span_note(
2761                                self.token.span.to(maybe_let.span),
2762                                "you likely meant to continue parsing the let-chain starting here",
2763                            );
2764                        } else {
2765                            // Look for usages of '=>' where '>=' might be intended
2766                            if maybe_fatarrow == token::FatArrow {
2767                                err.span_suggestion(
2768                                    maybe_fatarrow.span,
2769                                    "you might have meant to write a \"greater than or equal to\" comparison",
2770                                    ">=",
2771                                    Applicability::MaybeIncorrect,
2772                                );
2773                            }
2774                            err.span_note(
2775                                cond_span,
2776                                "the `if` expression is missing a block after this condition",
2777                            );
2778                        }
2779                        err
2780                    })?
2781            };
2782            self.error_on_if_block_attrs(lo, false, block.span, attrs);
2783            block
2784        };
2785        let els = if self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Else,
    token_type: crate::parser::token_type::TokenType::KwElse,
}exp!(Else)) { Some(self.parse_expr_else()?) } else { None };
2786        Ok(self.mk_expr(lo.to(self.prev_token.span), ExprKind::If(cond, thn, els)))
2787    }
2788
2789    /// Parses the condition of a `if` or `while` expression.
2790    ///
2791    /// The specified `edition` in `let_chains_policy` should be that of the whole `if` construct,
2792    /// i.e. the same span we use to later decide whether the drop behaviour should be that of
2793    /// edition `..=2021` or that of `2024..`.
2794    // Public to use it for custom `if` expressions in rustfmt forks like https://github.com/tucant/rustfmt
2795    pub fn parse_expr_cond(
2796        &mut self,
2797        let_chains_policy: LetChainsPolicy,
2798    ) -> PResult<'a, Box<Expr>> {
2799        let attrs = self.parse_outer_attributes()?;
2800        let (mut cond, _) =
2801            self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL | Restrictions::ALLOW_LET, attrs)?;
2802
2803        let mut checker = CondChecker::new(self, let_chains_policy);
2804        checker.visit_expr(&mut cond);
2805        Ok(if let Some(guar) = checker.found_incorrect_let_chain {
2806            self.mk_expr_err(cond.span, guar)
2807        } else {
2808            cond
2809        })
2810    }
2811
2812    /// Parses a `let $pat = $expr` pseudo-expression.
2813    fn parse_expr_let(&mut self, restrictions: Restrictions) -> PResult<'a, Box<Expr>> {
2814        let recovered: Recovered = if !restrictions.contains(Restrictions::ALLOW_LET) {
2815            let err = diagnostics::ExpectedExpressionFoundLet {
2816                span: self.token.span,
2817                reason: diagnostics::ForbiddenLetReason::OtherForbidden,
2818                missing_let: None,
2819                comparison: None,
2820            };
2821            if self.prev_token == token::Or {
2822                // This was part of a closure, the that part of the parser recover.
2823                return Err(self.dcx().create_err(err));
2824            } else {
2825                Recovered::Yes(self.dcx().emit_err(err))
2826            }
2827        } else {
2828            Recovered::No
2829        };
2830        self.bump(); // Eat `let` token
2831        let lo = self.prev_token.span;
2832        let pat = self.parse_pat_no_top_guard(
2833            None,
2834            RecoverComma::Yes,
2835            RecoverColon::Yes,
2836            CommaRecoveryMode::LikelyTuple,
2837        )?;
2838        if self.token == token::EqEq {
2839            self.dcx().emit_err(diagnostics::ExpectedEqForLetExpr {
2840                span: self.token.span,
2841                sugg_span: self.token.span,
2842            });
2843            self.bump();
2844        } else {
2845            self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Eq,
    token_type: crate::parser::token_type::TokenType::Eq,
}exp!(Eq))?;
2846        }
2847        let attrs = self.parse_outer_attributes()?;
2848        let (expr, _) =
2849            self.parse_expr_assoc_with(Bound::Excluded(prec_let_scrutinee_needs_par()), attrs)?;
2850        let span = lo.to(expr.span);
2851        Ok(self.mk_expr(span, ExprKind::Let(Box::new(pat), expr, span, recovered)))
2852    }
2853
2854    /// Parses an `else { ... }` expression (`else` token already eaten).
2855    fn parse_expr_else(&mut self) -> PResult<'a, Box<Expr>> {
2856        let else_span = self.prev_token.span; // `else`
2857        let attrs = self.parse_outer_attributes()?; // For recovery.
2858        let expr = if self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::If,
    token_type: crate::parser::token_type::TokenType::KwIf,
}exp!(If)) {
2859            ensure_sufficient_stack(|| self.parse_expr_if())?
2860        } else if self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenBrace,
    token_type: crate::parser::token_type::TokenType::OpenBrace,
}exp!(OpenBrace)) {
2861            self.parse_simple_block()?
2862        } else {
2863            let snapshot = self.create_snapshot_for_diagnostic();
2864            let first_tok = super::token_descr(&self.token);
2865            let first_tok_span = self.token.span;
2866            match self.parse_expr() {
2867                Ok(cond)
2868                // Try to guess the difference between a "condition-like" vs
2869                // "statement-like" expression.
2870                //
2871                // We are seeing the following code, in which $cond is neither
2872                // ExprKind::Block nor ExprKind::If (the 2 cases wherein this
2873                // would be valid syntax).
2874                //
2875                //     if ... {
2876                //     } else $cond
2877                //
2878                // If $cond is "condition-like" such as ExprKind::Binary, we
2879                // want to suggest inserting `if`.
2880                //
2881                //     if ... {
2882                //     } else if a == b {
2883                //            ^^
2884                //     }
2885                //
2886                // We account for macro calls that were meant as conditions as well.
2887                //
2888                //     if ... {
2889                //     } else if macro! { foo bar } {
2890                //            ^^
2891                //     }
2892                //
2893                // If $cond is "statement-like" such as ExprKind::While then we
2894                // want to suggest wrapping in braces.
2895                //
2896                //     if ... {
2897                //     } else {
2898                //            ^
2899                //         while true {}
2900                //     }
2901                //     ^
2902                    if self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenBrace,
    token_type: crate::parser::token_type::TokenType::OpenBrace,
}exp!(OpenBrace))
2903                        && (classify::expr_requires_semi_to_be_stmt(&cond)
2904                            || #[allow(non_exhaustive_omitted_patterns)] match cond.kind {
    ExprKind::MacCall(..) => true,
    _ => false,
}matches!(cond.kind, ExprKind::MacCall(..)))
2905                    =>
2906                {
2907                    self.dcx().emit_err(diagnostics::ExpectedElseBlock {
2908                        first_tok_span,
2909                        first_tok,
2910                        else_span,
2911                        condition_start: cond.span.shrink_to_lo(),
2912                    });
2913                    self.parse_if_after_cond(cond.span.shrink_to_lo(), cond)?
2914                }
2915                Err(e) => {
2916                    e.cancel();
2917                    self.restore_snapshot(snapshot);
2918                    self.parse_simple_block()?
2919                },
2920                Ok(_) => {
2921                    self.restore_snapshot(snapshot);
2922                    self.parse_simple_block()?
2923                },
2924            }
2925        };
2926        self.error_on_if_block_attrs(else_span, true, expr.span, attrs);
2927        Ok(expr)
2928    }
2929
2930    fn error_on_if_block_attrs(
2931        &self,
2932        ctx_span: Span,
2933        is_ctx_else: bool,
2934        branch_span: Span,
2935        attrs: AttrWrapper,
2936    ) {
2937        if !attrs.is_empty()
2938            && let [x0 @ xn] | [x0, .., xn] = &*attrs.take_for_recovery(self.psess)
2939        {
2940            let attributes = x0.span.until(branch_span);
2941            let last = xn.span;
2942            let ctx = if is_ctx_else { "else" } else { "if" };
2943            self.dcx().emit_err(diagnostics::OuterAttributeNotAllowedOnIfElse {
2944                last,
2945                branch_span,
2946                ctx_span,
2947                ctx: ctx.to_string(),
2948                attributes,
2949            });
2950        }
2951    }
2952
2953    fn error_on_extra_if(&mut self, cond: &Box<Expr>) -> PResult<'a, ()> {
2954        if let ExprKind::Binary(Spanned { span: binop_span, node: binop }, _, right) = &cond.kind
2955            && let BinOpKind::And = binop
2956            && let ExprKind::If(cond, ..) = &right.kind
2957        {
2958            Err(self.dcx().create_err(diagnostics::UnexpectedIfWithIf(
2959                binop_span.shrink_to_hi().to(cond.span.shrink_to_lo()),
2960            )))
2961        } else {
2962            Ok(())
2963        }
2964    }
2965
2966    // Public to use it for custom `for` expressions in rustfmt forks like https://github.com/tucant/rustfmt
2967    pub fn parse_for_head(&mut self) -> PResult<'a, (Pat, Box<Expr>)> {
2968        let begin_paren = if self.token == token::OpenParen {
2969            // Record whether we are about to parse `for (`.
2970            // This is used below for recovery in case of `for ( $stuff ) $block`
2971            // in which case we will suggest `for $stuff $block`.
2972            let start_span = self.token.span;
2973            let left = self.prev_token.span.between(self.look_ahead(1, |t| t.span));
2974            Some((start_span, left))
2975        } else {
2976            None
2977        };
2978        // Try to parse the pattern `for ($PAT) in $EXPR`.
2979        let pat = match (
2980            self.parse_pat_allow_top_guard(
2981                None,
2982                RecoverComma::Yes,
2983                RecoverColon::Yes,
2984                CommaRecoveryMode::LikelyTuple,
2985            ),
2986            begin_paren,
2987        ) {
2988            (Ok(pat), _) => pat, // Happy path.
2989            (Err(err), Some((start_span, left))) if self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::In,
    token_type: crate::parser::token_type::TokenType::KwIn,
}exp!(In)) => {
2990                // We know for sure we have seen `for ($SOMETHING in`. In the happy path this would
2991                // happen right before the return of this method.
2992                let attrs = self.parse_outer_attributes()?;
2993                let (expr, _) = match self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, attrs) {
2994                    Ok(expr) => expr,
2995                    Err(expr_err) => {
2996                        // We don't know what followed the `in`, so cancel and bubble up the
2997                        // original error.
2998                        expr_err.cancel();
2999                        return Err(err);
3000                    }
3001                };
3002                return if self.token == token::CloseParen {
3003                    // We know for sure we have seen `for ($SOMETHING in $EXPR)`, so we recover the
3004                    // parser state and emit a targeted suggestion.
3005                    let span = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [start_span, self.token.span]))vec![start_span, self.token.span];
3006                    let right = self.prev_token.span.between(self.look_ahead(1, |t| t.span));
3007                    self.bump(); // )
3008                    err.cancel();
3009                    self.dcx().emit_err(diagnostics::ParenthesesInForHead {
3010                        span,
3011                        // With e.g. `for (x) in y)` this would replace `(x) in y)`
3012                        // with `x) in y)` which is syntactically invalid.
3013                        // However, this is prevented before we get here.
3014                        sugg: diagnostics::ParenthesesInForHeadSugg { left, right },
3015                    });
3016                    Ok((self.mk_pat(start_span.to(right), ast::PatKind::Wild), expr))
3017                } else {
3018                    Err(err) // Some other error, bubble up.
3019                };
3020            }
3021            (Err(err), _) => return Err(err), // Some other error, bubble up.
3022        };
3023        if !self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::In,
    token_type: crate::parser::token_type::TokenType::KwIn,
}exp!(In)) {
3024            self.error_missing_in_for_loop();
3025        }
3026        self.check_for_for_in_in_typo(self.prev_token.span);
3027        let attrs = self.parse_outer_attributes()?;
3028        let (expr, _) = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, attrs)?;
3029        Ok((pat, expr))
3030    }
3031
3032    /// Parses `for await? <src_pat> in <src_expr> <src_loop_block>` (`for` token already eaten).
3033    fn parse_expr_for(&mut self, opt_label: Option<Label>, lo: Span) -> PResult<'a, Box<Expr>> {
3034        let is_await =
3035            self.token_uninterpolated_span().at_least_rust_2018() && self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Await,
    token_type: crate::parser::token_type::TokenType::KwAwait,
}exp!(Await));
3036
3037        if is_await {
3038            self.psess.gated_spans.gate(sym::async_for_loop, self.prev_token.span);
3039        }
3040
3041        let kind = if is_await { ForLoopKind::ForAwait } else { ForLoopKind::For };
3042
3043        let (pat, expr) = self.parse_for_head()?;
3044        let pat = Box::new(pat);
3045        // Recover from missing expression in `for` loop
3046        if #[allow(non_exhaustive_omitted_patterns)] match expr.kind {
    ExprKind::Block(..) => true,
    _ => false,
}matches!(expr.kind, ExprKind::Block(..))
3047            && self.token.kind != token::OpenBrace
3048            && self.may_recover()
3049        {
3050            let guar = self.dcx().emit_err(diagnostics::MissingExpressionInForLoop {
3051                span: expr.span.shrink_to_lo(),
3052            });
3053            let err_expr = self.mk_expr(expr.span, ExprKind::Err(guar));
3054            let block = self.mk_block(::thin_vec::ThinVec::new()thin_vec![], BlockCheckMode::Default, self.prev_token.span);
3055            return Ok(self.mk_expr(
3056                lo.to(self.prev_token.span),
3057                ExprKind::ForLoop(Box::new(ForLoop {
3058                    pat,
3059                    iter: err_expr,
3060                    body: block,
3061                    label: opt_label,
3062                    kind,
3063                })),
3064            ));
3065        }
3066
3067        let (attrs, loop_block) = self.parse_inner_attrs_and_block(
3068            // Only suggest moving erroneous block label to the loop header
3069            // if there is not already a label there
3070            opt_label.is_none().then_some(lo),
3071        )?;
3072
3073        let kind = ExprKind::ForLoop(Box::new(ForLoop {
3074            pat,
3075            iter: expr,
3076            body: loop_block,
3077            label: opt_label,
3078            kind,
3079        }));
3080
3081        self.recover_loop_else("for", lo)?;
3082
3083        Ok(self.mk_expr_with_attrs(lo.to(self.prev_token.span), kind, attrs))
3084    }
3085
3086    /// Recovers from an `else` clause after a loop (`for...else`, `while...else`)
3087    fn recover_loop_else(&mut self, loop_kind: &'static str, loop_kw: Span) -> PResult<'a, ()> {
3088        if self.token.is_keyword(kw::Else) && self.may_recover() {
3089            let else_span = self.token.span;
3090            self.bump();
3091            let else_clause = self.parse_expr_else()?;
3092            self.dcx().emit_err(diagnostics::LoopElseNotSupported {
3093                span: else_span.to(else_clause.span),
3094                loop_kind,
3095                loop_kw,
3096            });
3097        }
3098        Ok(())
3099    }
3100
3101    fn error_missing_in_for_loop(&mut self) {
3102        let (span, sub) = if self.token.is_ident_named(sym::of) {
3103            // Possibly using JS syntax (#75311).
3104            let span = self.token.span;
3105            self.bump();
3106            (span, Some(diagnostics::MissingInInForLoopSub::InNotOf(span)))
3107        } else if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Eq,
    token_type: crate::parser::token_type::TokenType::Eq,
}exp!(Eq)) {
3108            let span = self.prev_token.span;
3109            (span, Some(diagnostics::MissingInInForLoopSub::InNotEq(span)))
3110        } else {
3111            let span = self.prev_token.span.between(self.token.span);
3112            let sub = (!self.for_loop_head_has_in())
3113                .then_some(diagnostics::MissingInInForLoopSub::AddIn(span));
3114            (span, sub)
3115        };
3116
3117        self.dcx().emit_err(diagnostics::MissingInInForLoop { span, sub });
3118    }
3119
3120    /// Whether the `for` loop header already contains an `in` before its body.
3121    /// If it does, the binding is malformed (e.g. `for i i in 0..10`) rather
3122    /// than missing `in`, so suggesting another `in` would just be invalid too.
3123    fn for_loop_head_has_in(&self) -> bool {
3124        let mut dist = 0;
3125        loop {
3126            let (is_in, is_end) = self.look_ahead(dist, |t| {
3127                (t.is_keyword(kw::In), #[allow(non_exhaustive_omitted_patterns)] match t.kind {
    token::OpenBrace | token::Eof => true,
    _ => false,
}matches!(t.kind, token::OpenBrace | token::Eof))
3128            });
3129            if is_in {
3130                return true;
3131            }
3132            if is_end {
3133                return false;
3134            }
3135            dist += 1;
3136        }
3137    }
3138
3139    /// Parses a `while` or `while let` expression (`while` token already eaten).
3140    fn parse_expr_while(&mut self, opt_label: Option<Label>, lo: Span) -> PResult<'a, Box<Expr>> {
3141        let policy = LetChainsPolicy::EditionDependent { current_edition: lo.edition() };
3142        let cond = self.parse_expr_cond(policy).map_err(|mut err| {
3143            err.span_label(lo, "while parsing the condition of this `while` expression");
3144            err
3145        })?;
3146        let (attrs, body) = self
3147            .parse_inner_attrs_and_block(
3148                // Only suggest moving erroneous block label to the loop header
3149                // if there is not already a label there
3150                opt_label.is_none().then_some(lo),
3151            )
3152            .map_err(|mut err| {
3153                err.span_label(lo, "while parsing the body of this `while` expression");
3154                err.span_label(cond.span, "this `while` condition successfully parsed");
3155                err
3156            })?;
3157
3158        self.recover_loop_else("while", lo)?;
3159
3160        Ok(self.mk_expr_with_attrs(
3161            lo.to(self.prev_token.span),
3162            ExprKind::While(cond, body, opt_label),
3163            attrs,
3164        ))
3165    }
3166
3167    /// Parses `loop { ... }` (`loop` token already eaten).
3168    fn parse_expr_loop(&mut self, opt_label: Option<Label>, lo: Span) -> PResult<'a, Box<Expr>> {
3169        let loop_span = self.prev_token.span;
3170        let (attrs, body) = self.parse_inner_attrs_and_block(
3171            // Only suggest moving erroneous block label to the loop header
3172            // if there is not already a label there
3173            opt_label.is_none().then_some(lo),
3174        )?;
3175        self.recover_loop_else("loop", lo)?;
3176        Ok(self.mk_expr_with_attrs(
3177            lo.to(self.prev_token.span),
3178            ExprKind::Loop(body, opt_label, loop_span),
3179            attrs,
3180        ))
3181    }
3182
3183    pub(crate) fn eat_label(&mut self) -> Option<Label> {
3184        if let Some((ident, is_raw)) = self.token.lifetime() {
3185            // Disallow `'fn`, but with a better error message than `expect_lifetime`.
3186            if is_raw == IdentIsRaw::No && ident.without_first_quote().is_reserved() {
3187                self.dcx().emit_err(diagnostics::KeywordLabel { span: ident.span });
3188            }
3189
3190            self.bump();
3191            Some(Label { ident })
3192        } else {
3193            None
3194        }
3195    }
3196
3197    /// Parses a `match ... { ... }` expression (`match` token already eaten).
3198    fn parse_expr_match(&mut self) -> PResult<'a, Box<Expr>> {
3199        let match_span = self.prev_token.span;
3200        let attrs = self.parse_outer_attributes()?;
3201        let (scrutinee, _) = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, attrs)?;
3202
3203        self.parse_match_block(match_span, match_span, scrutinee, MatchKind::Prefix)
3204    }
3205
3206    /// Parses the block of a `match expr { ... }` or a `expr.match { ... }`
3207    /// expression. This is after the match token and scrutinee are eaten
3208    fn parse_match_block(
3209        &mut self,
3210        lo: Span,
3211        match_span: Span,
3212        scrutinee: Box<Expr>,
3213        match_kind: MatchKind,
3214    ) -> PResult<'a, Box<Expr>> {
3215        if let Err(mut e) = self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenBrace,
    token_type: crate::parser::token_type::TokenType::OpenBrace,
}exp!(OpenBrace)) {
3216            if self.token == token::Semi {
3217                e.span_suggestion_short(
3218                    match_span,
3219                    "try removing this `match`",
3220                    "",
3221                    Applicability::MaybeIncorrect, // speculative
3222                );
3223            }
3224            if self.maybe_recover_unexpected_block_label(None) {
3225                e.cancel();
3226                self.bump();
3227            } else {
3228                return Err(e);
3229            }
3230        }
3231        let attrs = self.parse_inner_attributes()?;
3232
3233        let mut arms = ThinVec::new();
3234        while self.token != token::CloseBrace {
3235            match self.parse_arm() {
3236                Ok(arm) => arms.push(arm),
3237                Err(e) => {
3238                    // Recover by skipping to the end of the block.
3239                    let guar = e.emit();
3240                    self.recover_stmt();
3241                    let span = lo.to(self.token.span);
3242                    if self.token == token::CloseBrace {
3243                        self.bump();
3244                    }
3245                    // Always push at least one arm to make the match non-empty
3246                    arms.push(Arm {
3247                        attrs: Default::default(),
3248                        pat: Box::new(self.mk_pat(span, ast::PatKind::Err(guar))),
3249                        guard: None,
3250                        body: Some(self.mk_expr_err(span, guar)),
3251                        span,
3252                        id: DUMMY_NODE_ID,
3253                        is_placeholder: false,
3254                    });
3255                    return Ok(self.mk_expr_with_attrs(
3256                        span,
3257                        ExprKind::Match(scrutinee, arms, match_kind),
3258                        attrs,
3259                    ));
3260                }
3261            }
3262        }
3263        let hi = self.token.span;
3264        self.bump();
3265        Ok(self.mk_expr_with_attrs(lo.to(hi), ExprKind::Match(scrutinee, arms, match_kind), attrs))
3266    }
3267
3268    /// Attempt to recover from match arm body with statements and no surrounding braces.
3269    fn parse_arm_body_missing_braces(
3270        &mut self,
3271        first_expr: &Box<Expr>,
3272        arrow_span: Span,
3273    ) -> Option<(Span, ErrorGuaranteed)> {
3274        if self.token != token::Semi {
3275            return None;
3276        }
3277        let start_snapshot = self.create_snapshot_for_diagnostic();
3278        let semi_sp = self.token.span;
3279        self.bump(); // `;`
3280        let mut stmts =
3281            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [self.mk_stmt(first_expr.span,
                    ast::StmtKind::Expr(first_expr.clone()))]))vec![self.mk_stmt(first_expr.span, ast::StmtKind::Expr(first_expr.clone()))];
3282        let err = |this: &Parser<'_>, stmts: Vec<ast::Stmt>| {
3283            let span = stmts[0].span.to(stmts[stmts.len() - 1].span);
3284
3285            let guar = this.dcx().emit_err(diagnostics::MatchArmBodyWithoutBraces {
3286                statements: span,
3287                arrow: arrow_span,
3288                num_statements: stmts.len(),
3289                sub: if stmts.len() > 1 {
3290                    diagnostics::MatchArmBodyWithoutBracesSugg::AddBraces {
3291                        left: span.shrink_to_lo(),
3292                        right: span.shrink_to_hi(),
3293                        num_statements: stmts.len(),
3294                    }
3295                } else {
3296                    diagnostics::MatchArmBodyWithoutBracesSugg::UseComma { semicolon: semi_sp }
3297                },
3298            });
3299            (span, guar)
3300        };
3301        // We might have either a `,` -> `;` typo, or a block without braces. We need
3302        // a more subtle parsing strategy.
3303        loop {
3304            if self.token == token::CloseBrace {
3305                // We have reached the closing brace of the `match` expression.
3306                return Some(err(self, stmts));
3307            }
3308            if self.token == token::Comma {
3309                self.restore_snapshot(start_snapshot);
3310                return None;
3311            }
3312            let pre_pat_snapshot = self.create_snapshot_for_diagnostic();
3313            match self.parse_pat_no_top_alt(None, None) {
3314                Ok(_pat) => {
3315                    if self.token == token::FatArrow {
3316                        // Reached arm end.
3317                        self.restore_snapshot(pre_pat_snapshot);
3318                        return Some(err(self, stmts));
3319                    }
3320                }
3321                Err(err) => {
3322                    err.cancel();
3323                }
3324            }
3325
3326            self.restore_snapshot(pre_pat_snapshot);
3327            match self.parse_stmt_without_recovery(true, ForceCollect::No, false) {
3328                // Consume statements for as long as possible.
3329                Ok(Some(stmt)) => {
3330                    stmts.push(stmt);
3331                }
3332                Ok(None) => {
3333                    self.restore_snapshot(start_snapshot);
3334                    break;
3335                }
3336                // We couldn't parse either yet another statement missing it's
3337                // enclosing block nor the next arm's pattern or closing brace.
3338                Err(stmt_err) => {
3339                    stmt_err.cancel();
3340                    self.restore_snapshot(start_snapshot);
3341                    break;
3342                }
3343            }
3344        }
3345        None
3346    }
3347
3348    pub(super) fn parse_arm(&mut self) -> PResult<'a, Arm> {
3349        let attrs = self.parse_outer_attributes()?;
3350        self.collect_tokens(None, attrs, ForceCollect::No, |this, attrs| {
3351            let lo = this.token.span;
3352            let (pat, guard) = this.parse_match_arm_pat_and_guard()?;
3353            let pat = Box::new(pat);
3354
3355            let span_before_body = this.prev_token.span;
3356            let arm_body;
3357            let is_fat_arrow = this.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::FatArrow,
    token_type: crate::parser::token_type::TokenType::FatArrow,
}exp!(FatArrow));
3358            let is_almost_fat_arrow =
3359                TokenKind::FatArrow.similar_tokens().contains(&this.token.kind);
3360
3361            // this avoids the compiler saying that a `,` or `}` was expected even though
3362            // the pattern isn't a never pattern (and thus an arm body is required)
3363            let armless = (!is_fat_arrow && !is_almost_fat_arrow && pat.could_be_never_pattern())
3364                || #[allow(non_exhaustive_omitted_patterns)] match this.token.kind {
    token::Comma | token::CloseBrace => true,
    _ => false,
}matches!(this.token.kind, token::Comma | token::CloseBrace);
3365
3366            let mut result = if armless {
3367                // A pattern without a body, allowed for never patterns.
3368                arm_body = None;
3369                let span = lo.to(this.prev_token.span);
3370                this.expect_one_of(&[crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma)], &[crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseBrace,
    token_type: crate::parser::token_type::TokenType::CloseBrace,
}exp!(CloseBrace)]).map(|x| {
3371                    // Don't gate twice
3372                    if !pat.contains_never_pattern() {
3373                        this.psess.gated_spans.gate(sym::never_patterns, span);
3374                    }
3375                    x
3376                })
3377            } else {
3378                if let Err(mut err) = this.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::FatArrow,
    token_type: crate::parser::token_type::TokenType::FatArrow,
}exp!(FatArrow)) {
3379                    // We might have a `=>` -> `=` or `->` typo (issue #89396).
3380                    if is_almost_fat_arrow {
3381                        err.span_suggestion(
3382                            this.token.span,
3383                            "use a fat arrow to start a match arm",
3384                            "=>",
3385                            Applicability::MachineApplicable,
3386                        );
3387                        if #[allow(non_exhaustive_omitted_patterns)] match (&this.prev_token.kind,
        &this.token.kind) {
    (token::DotDotEq, token::Gt) => true,
    _ => false,
}matches!(
3388                            (&this.prev_token.kind, &this.token.kind),
3389                            (token::DotDotEq, token::Gt)
3390                        ) {
3391                            // `error_inclusive_range_match_arrow` handles cases like `0..=> {}`,
3392                            // so we suppress the error here
3393                            err.delay_as_bug();
3394                        } else {
3395                            err.emit();
3396                        }
3397                        this.bump();
3398                    } else {
3399                        return Err(err);
3400                    }
3401                }
3402                let arrow_span = this.prev_token.span;
3403                let arm_start_span = this.token.span;
3404
3405                let attrs = this.parse_outer_attributes()?;
3406                let (expr, _) =
3407                    this.parse_expr_res(Restrictions::STMT_EXPR, attrs).map_err(|mut err| {
3408                        err.span_label(arrow_span, "while parsing the `match` arm starting here");
3409                        err
3410                    })?;
3411
3412                let require_comma =
3413                    !classify::expr_is_complete(&expr) && this.token != token::CloseBrace;
3414
3415                if !require_comma {
3416                    arm_body = Some(expr);
3417                    // Eat a comma if it exists, though.
3418                    let _ = this.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma));
3419                    Ok(Recovered::No)
3420                } else if let Some((span, guar)) =
3421                    this.parse_arm_body_missing_braces(&expr, arrow_span)
3422                {
3423                    let body = this.mk_expr_err(span, guar);
3424                    arm_body = Some(body);
3425                    Ok(Recovered::Yes(guar))
3426                } else {
3427                    let expr_span = expr.span;
3428                    arm_body = Some(expr);
3429                    this.expect_one_of(&[crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma)], &[crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseBrace,
    token_type: crate::parser::token_type::TokenType::CloseBrace,
}exp!(CloseBrace)]).map_err(|mut err| {
3430                        if this.token == token::FatArrow {
3431                            let sm = this.psess.source_map();
3432                            if let Ok(expr_lines) = sm.span_to_lines(expr_span)
3433                                && let Ok(arm_start_lines) = sm.span_to_lines(arm_start_span)
3434                                && expr_lines.lines.len() == 2
3435                            {
3436                                if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col {
3437                                    // We check whether there's any trailing code in the parse span,
3438                                    // if there isn't, we very likely have the following:
3439                                    //
3440                                    // X |     &Y => "y"
3441                                    //   |        --    - missing comma
3442                                    //   |        |
3443                                    //   |        arrow_span
3444                                    // X |     &X => "x"
3445                                    //   |      - ^^ self.token.span
3446                                    //   |      |
3447                                    //   |      parsed until here as `"y" & X`
3448                                    err.span_suggestion_short(
3449                                        arm_start_span.shrink_to_hi(),
3450                                        "missing a comma here to end this `match` arm",
3451                                        ",",
3452                                        Applicability::MachineApplicable,
3453                                    );
3454                                } else if arm_start_lines.lines[0].end_col + rustc_span::CharPos(1)
3455                                    == expr_lines.lines[0].end_col
3456                                {
3457                                    // similar to the above, but we may typo a `.` or `/` at the end of the line
3458                                    let comma_span = arm_start_span
3459                                        .shrink_to_hi()
3460                                        .with_hi(arm_start_span.hi() + rustc_span::BytePos(1));
3461                                    if let Ok(res) = sm.span_to_snippet(comma_span)
3462                                        && (res == "." || res == "/")
3463                                    {
3464                                        err.span_suggestion_short(
3465                                            comma_span,
3466                                            "you might have meant to write a `,` to end this `match` arm",
3467                                            ",",
3468                                            Applicability::MachineApplicable,
3469                                        );
3470                                    }
3471                                }
3472                            }
3473                        } else {
3474                            err.span_label(
3475                                arrow_span,
3476                                "while parsing the `match` arm starting here",
3477                            );
3478                        }
3479                        err
3480                    })
3481                }
3482            };
3483
3484            let hi_span = arm_body.as_ref().map_or(span_before_body, |body| body.span);
3485            let arm_span = lo.to(hi_span);
3486
3487            // We want to recover:
3488            // X |     Some(_) => foo()
3489            //   |                     - missing comma
3490            // X |     None => "x"
3491            //   |     ^^^^ self.token.span
3492            // as well as:
3493            // X |     Some(!)
3494            //   |            - missing comma
3495            // X |     None => "x"
3496            //   |     ^^^^ self.token.span
3497            // But we musn't recover
3498            // X |     pat[0] => {}
3499            //   |        ^ self.token.span
3500            let recover_missing_comma = arm_body.is_some() || pat.could_be_never_pattern();
3501            if recover_missing_comma {
3502                result = result.or_else(|err| {
3503                    // FIXME(compiler-errors): We could also recover `; PAT =>` here
3504
3505                    // Try to parse a following `PAT =>`, if successful
3506                    // then we should recover.
3507                    let mut snapshot = this.create_snapshot_for_diagnostic();
3508                    let pattern_follows = snapshot
3509                        .parse_pat_no_top_guard(
3510                            None,
3511                            RecoverComma::Yes,
3512                            RecoverColon::Yes,
3513                            CommaRecoveryMode::EitherTupleOrPipe,
3514                        )
3515                        .map_err(|err| err.cancel())
3516                        .is_ok();
3517                    if pattern_follows && snapshot.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::FatArrow,
    token_type: crate::parser::token_type::TokenType::FatArrow,
}exp!(FatArrow)) {
3518                        err.cancel();
3519                        let guar = this.dcx().emit_err(diagnostics::MissingCommaAfterMatchArm {
3520                            span: arm_span.shrink_to_hi(),
3521                        });
3522                        return Ok(Recovered::Yes(guar));
3523                    }
3524                    Err(err)
3525                });
3526            }
3527            result?;
3528
3529            Ok((
3530                ast::Arm {
3531                    attrs,
3532                    pat,
3533                    guard,
3534                    body: arm_body,
3535                    span: arm_span,
3536                    id: DUMMY_NODE_ID,
3537                    is_placeholder: false,
3538                },
3539                Trailing::No,
3540                UsePreAttrPos::No,
3541            ))
3542        })
3543    }
3544
3545    pub(crate) fn eat_metavar_guard(&mut self) -> Option<Box<Guard>> {
3546        self.eat_metavar_seq(MetaVarKind::Guard, |this| {
3547            this.expect_match_arm_guard(ForceCollect::Yes)
3548        })
3549    }
3550
3551    fn parse_match_arm_guard(&mut self) -> PResult<'a, Option<Box<Guard>>> {
3552        if let Some(guard) = self.eat_metavar_guard() {
3553            return Ok(Some(guard));
3554        }
3555
3556        if !self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::If,
    token_type: crate::parser::token_type::TokenType::KwIf,
}exp!(If)) {
3557            // No match arm guard present.
3558            return Ok(None);
3559        }
3560        self.expect_match_arm_guard_cond(ForceCollect::No).map(Some)
3561    }
3562
3563    pub(crate) fn expect_match_arm_guard(
3564        &mut self,
3565        force_collect: ForceCollect,
3566    ) -> PResult<'a, Box<Guard>> {
3567        if let Some(guard) = self.eat_metavar_guard() {
3568            return Ok(guard);
3569        }
3570
3571        self.expect_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::If,
    token_type: crate::parser::token_type::TokenType::KwIf,
}exp!(If))?;
3572        self.expect_match_arm_guard_cond(force_collect)
3573    }
3574
3575    fn expect_match_arm_guard_cond(
3576        &mut self,
3577        force_collect: ForceCollect,
3578    ) -> PResult<'a, Box<Guard>> {
3579        let leading_if_span = self.prev_token.span;
3580
3581        let mut cond = self.parse_match_guard_condition(force_collect)?;
3582        let cond_span = cond.span;
3583
3584        CondChecker::new(self, LetChainsPolicy::AlwaysAllowed).visit_expr(&mut cond);
3585
3586        let guard = Guard { cond: *cond, span_with_leading_if: leading_if_span.to(cond_span) };
3587        Ok(Box::new(guard))
3588    }
3589
3590    fn parse_match_arm_pat_and_guard(&mut self) -> PResult<'a, (Pat, Option<Box<Guard>>)> {
3591        if self.token == token::OpenParen {
3592            let left = self.token.span;
3593            let pat = self.parse_pat_no_top_guard(
3594                None,
3595                RecoverComma::Yes,
3596                RecoverColon::Yes,
3597                CommaRecoveryMode::EitherTupleOrPipe,
3598            )?;
3599            if let ast::PatKind::Paren(subpat) = &pat.kind
3600                && let ast::PatKind::Guard(..) = &subpat.kind
3601            {
3602                // Detect and recover from `($pat if $cond) => $arm`.
3603                // FIXME(guard_patterns): convert this to a normal guard instead
3604                let span = pat.span;
3605                let ast::PatKind::Paren(subpat) = pat.kind else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
3606                let ast::PatKind::Guard(_, mut guard) = subpat.kind else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
3607                self.psess.gated_spans.ungate_last(sym::guard_patterns, guard.span());
3608                let mut checker = CondChecker::new(self, LetChainsPolicy::AlwaysAllowed);
3609                checker.visit_expr(&mut guard.cond);
3610
3611                let right = self.prev_token.span;
3612                self.dcx().emit_err(diagnostics::ParenthesesInMatchPat {
3613                    span: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [left, right]))vec![left, right],
3614                    sugg: diagnostics::ParenthesesInMatchPatSugg { left, right },
3615                });
3616
3617                if let Some(guar) = checker.found_incorrect_let_chain {
3618                    guard.cond = *self.mk_expr_err(guard.span(), guar);
3619                }
3620                Ok((self.mk_pat(span, ast::PatKind::Wild), Some(guard)))
3621            } else {
3622                Ok((pat, self.parse_match_arm_guard()?))
3623            }
3624        } else {
3625            // Regular parser flow:
3626            let pat = self.parse_pat_no_top_guard(
3627                None,
3628                RecoverComma::Yes,
3629                RecoverColon::Yes,
3630                CommaRecoveryMode::EitherTupleOrPipe,
3631            )?;
3632            Ok((pat, self.parse_match_arm_guard()?))
3633        }
3634    }
3635
3636    fn parse_match_guard_condition(
3637        &mut self,
3638        force_collect: ForceCollect,
3639    ) -> PResult<'a, Box<Expr>> {
3640        let attrs = self.parse_outer_attributes()?;
3641        let expr = self.collect_tokens(
3642            None,
3643            AttrWrapper::empty(),
3644            force_collect,
3645            |this, _empty_attrs| {
3646                match this
3647                    .parse_expr_res(Restrictions::ALLOW_LET | Restrictions::IN_IF_GUARD, attrs)
3648                {
3649                    Ok((expr, _)) => Ok((expr, Trailing::No, UsePreAttrPos::No)),
3650                    Err(mut err) => {
3651                        if this.prev_token == token::OpenBrace {
3652                            let sugg_sp = this.prev_token.span.shrink_to_lo();
3653                            // Consume everything within the braces, let's avoid further parse
3654                            // errors.
3655                            this.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
3656                            let msg =
3657                                "you might have meant to start a match arm after the match guard";
3658                            if this.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseBrace,
    token_type: crate::parser::token_type::TokenType::CloseBrace,
}exp!(CloseBrace)) {
3659                                let applicability = if this.token != token::FatArrow {
3660                                    // We have high confidence that we indeed didn't have a struct
3661                                    // literal in the match guard, but rather we had some operation
3662                                    // that ended in a path, immediately followed by a block that was
3663                                    // meant to be the match arm.
3664                                    Applicability::MachineApplicable
3665                                } else {
3666                                    Applicability::MaybeIncorrect
3667                                };
3668                                err.span_suggestion_verbose(sugg_sp, msg, "=> ", applicability);
3669                            }
3670                        }
3671                        Err(err)
3672                    }
3673                }
3674            },
3675        )?;
3676        Ok(expr)
3677    }
3678
3679    pub(crate) fn is_builtin(&self) -> bool {
3680        self.token.is_keyword(kw::Builtin) && self.look_ahead(1, |t| *t == token::Pound)
3681    }
3682
3683    /// Parses a `try {...}` or `try bikeshed Ty {...}` expression (`try` token already eaten).
3684    fn parse_try_block(&mut self, span_lo: Span) -> PResult<'a, Box<Expr>> {
3685        let annotation =
3686            if self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::sym::bikeshed,
    token_type: crate::parser::token_type::TokenType::SymBikeshed,
}exp!(Bikeshed)) { Some(self.parse_ty()?) } else { None };
3687
3688        let (attrs, body) = self.parse_inner_attrs_and_block(None)?;
3689        if self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Catch,
    token_type: crate::parser::token_type::TokenType::KwCatch,
}exp!(Catch)) {
3690            Err(self.dcx().create_err(diagnostics::CatchAfterTry { span: self.prev_token.span }))
3691        } else {
3692            let span = span_lo.to(body.span);
3693            let gate_sym =
3694                if annotation.is_none() { sym::try_blocks } else { sym::try_blocks_heterogeneous };
3695            self.psess.gated_spans.gate(gate_sym, span);
3696            Ok(self.mk_expr_with_attrs(span, ExprKind::TryBlock(body, annotation), attrs))
3697        }
3698    }
3699
3700    fn is_do_catch_block(&self) -> bool {
3701        self.token.is_keyword(kw::Do)
3702            && self.is_keyword_ahead(1, &[kw::Catch])
3703            && self.look_ahead(2, |t| *t == token::OpenBrace || t.is_metavar_block())
3704            && !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
3705    }
3706
3707    fn is_do_yeet(&self) -> bool {
3708        self.token.is_keyword(kw::Do) && self.is_keyword_ahead(1, &[kw::Yeet])
3709    }
3710
3711    fn is_try_block(&self) -> bool {
3712        self.token.is_keyword(kw::Try)
3713            && self.look_ahead(1, |t| {
3714                *t == token::OpenBrace
3715                    || t.is_metavar_block()
3716                    || t.kind == TokenKind::Ident(sym::bikeshed, IdentIsRaw::No)
3717            })
3718            && self.token_uninterpolated_span().at_least_rust_2018()
3719    }
3720
3721    /// Parses an `async move? {...}` or `gen move? {...}` expression.
3722    fn parse_gen_block(&mut self) -> PResult<'a, Box<Expr>> {
3723        let lo = self.token.span;
3724        let kind = if self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Async,
    token_type: crate::parser::token_type::TokenType::KwAsync,
}exp!(Async)) {
3725            if self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Gen,
    token_type: crate::parser::token_type::TokenType::KwGen,
}exp!(Gen)) { GenBlockKind::AsyncGen } else { GenBlockKind::Async }
3726        } else {
3727            if !self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
                kw: rustc_span::symbol::kw::Gen,
                token_type: crate::parser::token_type::TokenType::KwGen,
            }) {
    ::core::panicking::panic("assertion failed: self.eat_keyword(exp!(Gen))")
};assert!(self.eat_keyword(exp!(Gen)));
3728            GenBlockKind::Gen
3729        };
3730        match kind {
3731            GenBlockKind::Async => {
3732                // `async` blocks are stable
3733            }
3734            GenBlockKind::Gen | GenBlockKind::AsyncGen => {
3735                self.psess.gated_spans.gate(sym::gen_blocks, lo.to(self.prev_token.span));
3736            }
3737        }
3738        let capture_clause = self.parse_capture_clause()?;
3739        let decl_span = lo.to(self.prev_token.span);
3740        let (attrs, body) = self.parse_inner_attrs_and_block(None)?;
3741        let kind = ExprKind::Gen(capture_clause, body, kind, decl_span);
3742        Ok(self.mk_expr_with_attrs(lo.to(self.prev_token.span), kind, attrs))
3743    }
3744
3745    fn is_gen_block(&self, kw: Symbol, lookahead: usize) -> bool {
3746        self.is_keyword_ahead(lookahead, &[kw])
3747            && ((
3748                // `async move {`
3749                self.is_keyword_ahead(lookahead + 1, &[kw::Move, kw::Use])
3750                    && self.look_ahead(lookahead + 2, |t| {
3751                        *t == token::OpenBrace || t.is_metavar_block()
3752                    })
3753            ) || (
3754                // `async {`
3755                self.look_ahead(lookahead + 1, |t| *t == token::OpenBrace || t.is_metavar_block())
3756            ))
3757    }
3758
3759    pub(super) fn is_async_gen_block(&self) -> bool {
3760        self.token.is_keyword(kw::Async) && self.is_gen_block(kw::Gen, 1)
3761    }
3762
3763    fn is_likely_struct_lit(&self) -> bool {
3764        // `{ ident, ` and `{ ident: ` cannot start a block.
3765        self.look_ahead(1, |t| t.is_ident())
3766            && self.look_ahead(2, |t| t == &token::Comma || t == &token::Colon)
3767    }
3768
3769    fn maybe_parse_struct_expr(
3770        &mut self,
3771        qself: &Option<Box<ast::QSelf>>,
3772        path: &ast::Path,
3773    ) -> Option<PResult<'a, Box<Expr>>> {
3774        let struct_allowed = !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
3775        match (struct_allowed, self.is_likely_struct_lit()) {
3776            // A struct literal isn't expected and one is pretty much assured not to be present. The
3777            // only situation that isn't detected is when a struct with a single field was attempted
3778            // in a place where a struct literal wasn't expected, but regular parser errors apply.
3779            // Happy path.
3780            (false, false) => None,
3781            (true, _) => {
3782                // A struct is accepted here, try to parse it and rely on `parse_expr_struct` for
3783                // any kind of recovery. Happy path.
3784                if let Err(err) = self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenBrace,
    token_type: crate::parser::token_type::TokenType::OpenBrace,
}exp!(OpenBrace)) {
3785                    return Some(Err(err));
3786                }
3787                Some(self.parse_expr_struct(qself.clone(), path.clone(), true))
3788            }
3789            (false, true) => {
3790                // We have something like `match foo { bar,` or `match foo { bar:`, which means the
3791                // user might have meant to write a struct literal as part of the `match`
3792                // discriminant. This is done purely for error recovery.
3793                let snapshot = self.create_snapshot_for_diagnostic();
3794                if let Err(err) = self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenBrace,
    token_type: crate::parser::token_type::TokenType::OpenBrace,
}exp!(OpenBrace)) {
3795                    return Some(Err(err));
3796                }
3797                match self.parse_expr_struct(qself.clone(), path.clone(), false) {
3798                    Ok(expr) => {
3799                        // This is a struct literal, but we don't accept them here.
3800                        self.dcx().emit_err(diagnostics::StructLiteralNotAllowedHere {
3801                            span: expr.span,
3802                            sub: diagnostics::StructLiteralNotAllowedHereSugg {
3803                                left: path.span.shrink_to_lo(),
3804                                right: expr.span.shrink_to_hi(),
3805                            },
3806                        });
3807                        Some(Ok(expr))
3808                    }
3809                    Err(err) => {
3810                        // We couldn't parse a valid struct, rollback and let the parser emit an
3811                        // error elsewhere.
3812                        err.cancel();
3813                        self.restore_snapshot(snapshot);
3814                        None
3815                    }
3816                }
3817            }
3818        }
3819    }
3820
3821    fn maybe_recover_bad_struct_literal_path(
3822        &mut self,
3823        is_underscore_entry_point: bool,
3824    ) -> PResult<'a, Option<Box<Expr>>> {
3825        if self.may_recover()
3826            && self.check_noexpect(&token::OpenBrace)
3827            && (!self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
3828                && self.is_likely_struct_lit())
3829        {
3830            let span = if is_underscore_entry_point {
3831                self.prev_token.span
3832            } else {
3833                self.token.span.shrink_to_lo()
3834            };
3835
3836            self.bump(); // {
3837            let expr = self.parse_expr_struct(
3838                None,
3839                Path::from_ident(Ident::new(kw::Underscore, span)),
3840                false,
3841            )?;
3842
3843            let guar = if is_underscore_entry_point {
3844                self.dcx().create_err(diagnostics::StructLiteralPlaceholderPath { span }).emit()
3845            } else {
3846                self.dcx()
3847                    .create_err(diagnostics::StructLiteralWithoutPathLate {
3848                        span: expr.span,
3849                        suggestion_span: expr.span.shrink_to_lo(),
3850                    })
3851                    .emit()
3852            };
3853
3854            Ok(Some(self.mk_expr_err(expr.span, guar)))
3855        } else {
3856            Ok(None)
3857        }
3858    }
3859
3860    pub(super) fn parse_struct_fields(
3861        &mut self,
3862        pth: ast::Path,
3863        recover: bool,
3864        close: ExpTokenPair,
3865    ) -> PResult<
3866        'a,
3867        (
3868            ThinVec<ExprField>,
3869            ast::StructRest,
3870            Option<ErrorGuaranteed>, /* async blocks are forbidden in Rust 2015 */
3871        ),
3872    > {
3873        let mut fields = ThinVec::new();
3874        let mut base = ast::StructRest::None;
3875        let mut recovered_async = None;
3876        let in_if_guard = self.restrictions.contains(Restrictions::IN_IF_GUARD);
3877
3878        let async_block_err = |e: &mut Diag<'_>, span: Span| {
3879            diagnostics::AsyncBlockIn2015 { span }.add_to_diag(e);
3880            diagnostics::HelpUseLatestEdition::new().add_to_diag(e);
3881        };
3882
3883        while self.token != close.tok {
3884            if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::DotDot,
    token_type: crate::parser::token_type::TokenType::DotDot,
}exp!(DotDot)) || self.recover_struct_field_dots(&close.tok) {
3885                let exp_span = self.prev_token.span;
3886                // We permit `.. }` on the left-hand side of a destructuring assignment.
3887                if self.check(close) {
3888                    base = ast::StructRest::Rest(self.prev_token.span);
3889                    break;
3890                }
3891                match self.parse_expr() {
3892                    Ok(e) => base = ast::StructRest::Base(e),
3893                    Err(e) if recover => {
3894                        e.emit();
3895                        self.recover_stmt();
3896                    }
3897                    Err(e) => return Err(e),
3898                }
3899                self.recover_struct_comma_after_dotdot(exp_span);
3900                break;
3901            }
3902
3903            // Peek the field's ident before parsing its expr in order to emit better diagnostics.
3904            let peek = self
3905                .token
3906                .ident()
3907                .filter(|(ident, is_raw)| {
3908                    (!ident.is_reserved() || #[allow(non_exhaustive_omitted_patterns)] match is_raw {
    IdentIsRaw::Yes => true,
    _ => false,
}matches!(is_raw, IdentIsRaw::Yes))
3909                        && self.look_ahead(1, |tok| *tok == token::Colon)
3910                })
3911                .map(|(ident, _)| ident);
3912
3913            // We still want a field even if its expr didn't parse.
3914            let field_ident = |this: &Self, guar: ErrorGuaranteed| {
3915                peek.map(|ident| {
3916                    let span = ident.span;
3917                    ExprField {
3918                        ident,
3919                        span,
3920                        expr: this.mk_expr_err(span, guar),
3921                        is_shorthand: false,
3922                        attrs: AttrVec::new(),
3923                        id: DUMMY_NODE_ID,
3924                        is_placeholder: false,
3925                    }
3926                })
3927            };
3928
3929            let parsed_field = match self.parse_expr_field() {
3930                Ok(f) => Ok(f),
3931                Err(mut e) => {
3932                    if pth == kw::Async {
3933                        async_block_err(&mut e, pth.span);
3934                    } else {
3935                        e.span_label(pth.span, "while parsing this struct");
3936                    }
3937
3938                    if let Some((ident, _)) = self.token.ident()
3939                        && !self.token.is_reserved_ident()
3940                        && self.look_ahead(1, |t| {
3941                            AssocOp::from_token(t).is_some()
3942                                || #[allow(non_exhaustive_omitted_patterns)] match t.kind {
    token::OpenParen | token::OpenBracket | token::OpenBrace => true,
    _ => false,
}matches!(
3943                                    t.kind,
3944                                    token::OpenParen | token::OpenBracket | token::OpenBrace
3945                                )
3946                                || *t == token::Dot
3947                        })
3948                    {
3949                        // Looks like they tried to write a shorthand, complex expression,
3950                        // E.g.: `n + m`, `f(a)`, `a[i]`, `S { x: 3 }`, or `x.y`.
3951                        e.span_suggestion_verbose(
3952                            self.token.span.shrink_to_lo(),
3953                            "try naming a field",
3954                            &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: ", ident))
    })format!("{ident}: ",),
3955                            Applicability::MaybeIncorrect,
3956                        );
3957                    }
3958                    if in_if_guard && close.token_type == TokenType::CloseBrace {
3959                        return Err(e);
3960                    }
3961
3962                    if !recover {
3963                        return Err(e);
3964                    }
3965
3966                    let guar = e.emit();
3967                    if pth == kw::Async {
3968                        recovered_async = Some(guar);
3969                    }
3970
3971                    // If we encountered an error which we are recovering from, treat the struct
3972                    // as if it has a `..` in it, because we don’t know what fields the user
3973                    // might have *intended* it to have.
3974                    //
3975                    // This assignment will be overwritten if we actually parse a `..` later.
3976                    //
3977                    // (Note that this code is duplicated between here and below in comma parsing.
3978                    base = ast::StructRest::NoneWithError(guar);
3979
3980                    // If the next token is a comma, then try to parse
3981                    // what comes next as additional fields, rather than
3982                    // bailing out until next `}`.
3983                    if self.token != token::Comma {
3984                        self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
3985                        if self.token != token::Comma {
3986                            break;
3987                        }
3988                    }
3989
3990                    Err(guar)
3991                }
3992            };
3993
3994            let is_shorthand = parsed_field.as_ref().is_ok_and(|f| f.is_shorthand);
3995            // A shorthand field can be turned into a full field with `:`.
3996            // We should point this out.
3997            self.check_or_expected(!is_shorthand, TokenType::Colon);
3998
3999            match self.expect_one_of(&[crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma)], &[close]) {
4000                Ok(_) => {
4001                    if let Ok(f) = parsed_field.or_else(|guar| field_ident(self, guar).ok_or(guar))
4002                    {
4003                        // Only include the field if there's no parse error for the field name.
4004                        fields.push(f);
4005                    }
4006                }
4007                Err(mut e) => {
4008                    if pth == kw::Async {
4009                        async_block_err(&mut e, pth.span);
4010                    } else {
4011                        e.span_label(pth.span, "while parsing this struct");
4012                        if peek.is_some() {
4013                            e.span_suggestion(
4014                                self.prev_token.span.shrink_to_hi(),
4015                                "try adding a comma",
4016                                ",",
4017                                Applicability::MachineApplicable,
4018                            );
4019                        }
4020                    }
4021                    if !recover {
4022                        return Err(e);
4023                    }
4024                    let guar = e.emit();
4025                    if pth == kw::Async {
4026                        recovered_async = Some(guar);
4027                    } else if let Some(f) = field_ident(self, guar) {
4028                        fields.push(f);
4029                    }
4030
4031                    // See comment above on this same assignment inside of field parsing.
4032                    base = ast::StructRest::NoneWithError(guar);
4033
4034                    self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
4035                    let _ = self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma));
4036                }
4037            }
4038        }
4039        Ok((fields, base, recovered_async))
4040    }
4041
4042    /// Precondition: already parsed the '{'.
4043    pub(super) fn parse_expr_struct(
4044        &mut self,
4045        qself: Option<Box<ast::QSelf>>,
4046        pth: ast::Path,
4047        recover: bool,
4048    ) -> PResult<'a, Box<Expr>> {
4049        let lo = pth.span;
4050        let (fields, base, recovered_async) =
4051            self.parse_struct_fields(pth.clone(), recover, crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseBrace,
    token_type: crate::parser::token_type::TokenType::CloseBrace,
}exp!(CloseBrace))?;
4052        let span = lo.to(self.token.span);
4053        self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseBrace,
    token_type: crate::parser::token_type::TokenType::CloseBrace,
}exp!(CloseBrace))?;
4054        let expr = if let Some(guar) = recovered_async {
4055            ExprKind::Err(guar)
4056        } else {
4057            ExprKind::Struct(Box::new(ast::StructExpr { qself, path: pth, fields, rest: base }))
4058        };
4059        Ok(self.mk_expr(span, expr))
4060    }
4061
4062    fn recover_struct_comma_after_dotdot(&mut self, span: Span) {
4063        if self.token != token::Comma {
4064            return;
4065        }
4066        self.dcx().emit_err(diagnostics::CommaAfterBaseStruct {
4067            span: span.to(self.prev_token.span),
4068            comma: self.token.span,
4069        });
4070        self.recover_stmt();
4071    }
4072
4073    fn recover_struct_field_dots(&mut self, close: &TokenKind) -> bool {
4074        if !self.look_ahead(1, |t| t == close) && self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::DotDotDot,
    token_type: crate::parser::token_type::TokenType::DotDotDot,
}exp!(DotDotDot)) {
4075            // recover from typo of `...`, suggest `..`
4076            let span = self.prev_token.span;
4077            self.dcx().emit_err(diagnostics::MissingDotDot { token_span: span, sugg_span: span });
4078            return true;
4079        }
4080        false
4081    }
4082
4083    /// Converts an ident into 'label and emits an "expected a label, found an identifier" error.
4084    fn recover_ident_into_label(&mut self, ident: Ident) -> Label {
4085        // Convert `label` -> `'label`,
4086        // so that nameres doesn't complain about non-existing label
4087        let label = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\'{0}", ident.name))
    })format!("'{}", ident.name);
4088        let ident = Ident::new(Symbol::intern(&label), ident.span);
4089
4090        self.dcx().emit_err(diagnostics::ExpectedLabelFoundIdent {
4091            span: ident.span,
4092            start: ident.span.shrink_to_lo(),
4093        });
4094
4095        Label { ident }
4096    }
4097
4098    /// Parses `ident (COLON expr)?`.
4099    fn parse_expr_field(&mut self) -> PResult<'a, ExprField> {
4100        let attrs = self.parse_outer_attributes()?;
4101        self.recover_vcs_conflict_marker();
4102        self.collect_tokens(None, attrs, ForceCollect::No, |this, attrs| {
4103            let lo = this.token.span;
4104
4105            // Check if a colon exists one ahead. This means we're parsing a fieldname.
4106            let is_shorthand = !this.look_ahead(1, |t| t == &token::Colon || t == &token::Eq);
4107            // Proactively check whether parsing the field will be incorrect.
4108            let is_wrong = this.token.is_non_reserved_ident()
4109                && !this.look_ahead(1, |t| {
4110                    t == &token::Colon
4111                        || t == &token::Eq
4112                        || t == &token::Comma
4113                        || t == &token::CloseBrace
4114                        || t == &token::CloseParen
4115                });
4116            if is_wrong {
4117                return Err(this.dcx().create_err(diagnostics::ExpectedStructField {
4118                    span: this.look_ahead(1, |t| t.span),
4119                    ident_span: this.token.span,
4120                    token: pprust::token_to_string(&this.look_ahead(1, |t| *t)),
4121                }));
4122            }
4123            let (ident, expr) = if is_shorthand {
4124                // Mimic `x: x` for the `x` field shorthand.
4125                let ident = this.parse_ident_common(false)?;
4126                let path = ast::Path::from_ident(ident);
4127                (ident, this.mk_expr(ident.span, ExprKind::Path(None, path)))
4128            } else {
4129                let ident = this.parse_field_name()?;
4130                this.error_on_eq_field_init(ident);
4131                this.bump(); // `:`
4132                (ident, this.parse_expr()?)
4133            };
4134
4135            Ok((
4136                ast::ExprField {
4137                    ident,
4138                    span: lo.to(expr.span),
4139                    expr,
4140                    is_shorthand,
4141                    attrs,
4142                    id: DUMMY_NODE_ID,
4143                    is_placeholder: false,
4144                },
4145                Trailing::from(this.token == token::Comma),
4146                UsePreAttrPos::No,
4147            ))
4148        })
4149    }
4150
4151    /// Check for `=`. This means the source incorrectly attempts to
4152    /// initialize a field with an eq rather than a colon.
4153    fn error_on_eq_field_init(&self, field_name: Ident) {
4154        if self.token != token::Eq {
4155            return;
4156        }
4157
4158        self.dcx().emit_err(diagnostics::EqFieldInit {
4159            span: self.token.span,
4160            eq: field_name.span.shrink_to_hi().to(self.token.span),
4161        });
4162    }
4163
4164    fn err_dotdotdot_syntax(&self, span: Span) {
4165        self.dcx().emit_err(diagnostics::DotDotDot { span });
4166    }
4167
4168    fn err_larrow_operator(&self, span: Span) {
4169        self.dcx().emit_err(diagnostics::LeftArrowOperator { span });
4170    }
4171
4172    fn mk_assign_op(&self, assign_op: AssignOp, lhs: Box<Expr>, rhs: Box<Expr>) -> ExprKind {
4173        ExprKind::AssignOp(assign_op, lhs, rhs)
4174    }
4175
4176    fn mk_range(
4177        &mut self,
4178        start: Option<Box<Expr>>,
4179        end: Option<Box<Expr>>,
4180        limits: RangeLimits,
4181    ) -> ExprKind {
4182        if end.is_none() && limits == RangeLimits::Closed {
4183            let guar = self.inclusive_range_with_incorrect_end();
4184            ExprKind::Err(guar)
4185        } else {
4186            ExprKind::Range(start, end, limits)
4187        }
4188    }
4189
4190    fn mk_unary(&self, unop: UnOp, expr: Box<Expr>) -> ExprKind {
4191        ExprKind::Unary(unop, expr)
4192    }
4193
4194    fn mk_binary(&self, binop: BinOp, lhs: Box<Expr>, rhs: Box<Expr>) -> ExprKind {
4195        ExprKind::Binary(binop, lhs, rhs)
4196    }
4197
4198    fn mk_index(&self, expr: Box<Expr>, idx: Box<Expr>, brackets_span: Span) -> ExprKind {
4199        ExprKind::Index(expr, idx, brackets_span)
4200    }
4201
4202    fn mk_call(&self, f: Box<Expr>, args: ThinVec<Box<Expr>>) -> ExprKind {
4203        ExprKind::Call(f, args)
4204    }
4205
4206    fn mk_await_expr(&mut self, self_arg: Box<Expr>, lo: Span) -> Box<Expr> {
4207        let span = lo.to(self.prev_token.span);
4208        let await_expr = self.mk_expr(span, ExprKind::Await(self_arg, self.prev_token.span));
4209        self.recover_from_await_method_call();
4210        await_expr
4211    }
4212
4213    fn mk_use_expr(&mut self, self_arg: Box<Expr>, lo: Span) -> Box<Expr> {
4214        let span = lo.to(self.prev_token.span);
4215        let use_expr = self.mk_expr(span, ExprKind::Use(self_arg, self.prev_token.span));
4216        self.recover_from_use();
4217        use_expr
4218    }
4219
4220    pub(crate) fn mk_expr_with_attrs(
4221        &self,
4222        span: Span,
4223        kind: ExprKind,
4224        attrs: AttrVec,
4225    ) -> Box<Expr> {
4226        Box::new(Expr { kind, span, attrs, id: DUMMY_NODE_ID, tokens: None })
4227    }
4228
4229    pub(crate) fn mk_expr(&self, span: Span, kind: ExprKind) -> Box<Expr> {
4230        self.mk_expr_with_attrs(span, kind, AttrVec::new())
4231    }
4232
4233    pub(super) fn mk_expr_err(&self, span: Span, guar: ErrorGuaranteed) -> Box<Expr> {
4234        self.mk_expr(span, ExprKind::Err(guar))
4235    }
4236
4237    pub(crate) fn mk_unit_expr(&self, span: Span) -> Box<Expr> {
4238        self.mk_expr(span, ExprKind::Tup(Default::default()))
4239    }
4240
4241    pub(crate) fn mk_closure_expr(&self, span: Span, body: Box<Expr>) -> Box<Expr> {
4242        self.mk_expr(
4243            span,
4244            ast::ExprKind::Closure(Box::new(ast::Closure {
4245                binder: rustc_ast::ClosureBinder::NotPresent,
4246                constness: rustc_ast::Const::No,
4247                movability: rustc_ast::Movability::Movable,
4248                capture_clause: rustc_ast::CaptureBy::Ref,
4249                coroutine_kind: None,
4250                fn_decl: Box::new(rustc_ast::FnDecl {
4251                    inputs: Default::default(),
4252                    output: rustc_ast::FnRetTy::Default(span),
4253                }),
4254                fn_arg_span: span,
4255                fn_decl_span: span,
4256                body,
4257            })),
4258        )
4259    }
4260
4261    /// Create expression span ensuring the span of the parent node
4262    /// is larger than the span of lhs and rhs, including the attributes.
4263    fn mk_expr_sp(&self, lhs: &Box<Expr>, lhs_span: Span, op_span: Span, rhs_span: Span) -> Span {
4264        lhs.attrs
4265            .iter()
4266            .find(|a| a.style == AttrStyle::Outer)
4267            .map_or(lhs_span, |a| a.span)
4268            .to(op_span)
4269            .to(rhs_span)
4270    }
4271
4272    fn collect_tokens_for_expr(
4273        &mut self,
4274        attrs: AttrWrapper,
4275        f: impl FnOnce(&mut Self, ast::AttrVec) -> PResult<'a, Box<Expr>>,
4276    ) -> PResult<'a, Box<Expr>> {
4277        self.collect_tokens(None, attrs, ForceCollect::No, |this, attrs| {
4278            let res = f(this, attrs)?;
4279            let trailing = Trailing::from(
4280                this.restrictions.contains(Restrictions::STMT_EXPR)
4281                     && this.token == token::Semi
4282                // FIXME: pass an additional condition through from the place
4283                // where we know we need a comma, rather than assuming that
4284                // `#[attr] expr,` always captures a trailing comma.
4285                || this.token == token::Comma,
4286            );
4287            Ok((res, trailing, UsePreAttrPos::No))
4288        })
4289    }
4290}
4291
4292/// Could this lifetime/label be an unclosed char literal? For example, `'a`
4293/// could be, but `'abc` could not.
4294pub(crate) fn could_be_unclosed_char_literal(ident: Ident) -> bool {
4295    ident.name.as_str().starts_with('\'')
4296        && unescape_char(ident.without_first_quote().name.as_str()).is_ok()
4297}
4298
4299/// Whether let chains are allowed on all editions, or it's edition dependent (allowed only on
4300/// 2024 and later). In case of edition dependence, specify the currently present edition.
4301pub enum LetChainsPolicy {
4302    AlwaysAllowed,
4303    EditionDependent { current_edition: Edition },
4304}
4305
4306/// Visitor to check for invalid use of `ExprKind::Let` that can't
4307/// easily be caught in parsing. For example:
4308///
4309/// ```rust,ignore (example)
4310/// // Only know that the let isn't allowed once the `||` token is reached
4311/// if let Some(x) = y || true {}
4312/// // Only know that the let isn't allowed once the second `=` token is reached.
4313/// if let Some(x) = y && z = 1 {}
4314/// ```
4315struct CondChecker<'a> {
4316    parser: &'a Parser<'a>,
4317    let_chains_policy: LetChainsPolicy,
4318    depth: u32,
4319    forbid_let_reason: Option<diagnostics::ForbiddenLetReason>,
4320    missing_let: Option<diagnostics::MaybeMissingLet>,
4321    comparison: Option<diagnostics::MaybeComparison>,
4322    found_incorrect_let_chain: Option<ErrorGuaranteed>,
4323}
4324
4325impl<'a> CondChecker<'a> {
4326    fn new(parser: &'a Parser<'a>, let_chains_policy: LetChainsPolicy) -> Self {
4327        CondChecker {
4328            parser,
4329            forbid_let_reason: None,
4330            missing_let: None,
4331            comparison: None,
4332            let_chains_policy,
4333            found_incorrect_let_chain: None,
4334            depth: 0,
4335        }
4336    }
4337}
4338
4339impl MutVisitor for CondChecker<'_> {
4340    fn visit_expr(&mut self, e: &mut Expr) {
4341        self.depth += 1;
4342
4343        let span = e.span;
4344        match e.kind {
4345            ExprKind::Let(_, _, _, ref mut recovered @ Recovered::No) => {
4346                if let Some(reason) = self.forbid_let_reason {
4347                    let error = match reason {
4348                        diagnostics::ForbiddenLetReason::NotSupportedOr(or_span) => {
4349                            self.parser.dcx().emit_err(diagnostics::OrInLetChain { span: or_span })
4350                        }
4351                        _ => {
4352                            let guar = self.parser.dcx().emit_err(
4353                                diagnostics::ExpectedExpressionFoundLet {
4354                                    span,
4355                                    reason,
4356                                    missing_let: self.missing_let,
4357                                    comparison: self.comparison,
4358                                },
4359                            );
4360                            if let Some(_) = self.missing_let {
4361                                self.found_incorrect_let_chain = Some(guar);
4362                            }
4363                            guar
4364                        }
4365                    };
4366                    *recovered = Recovered::Yes(error);
4367                } else if self.depth > 1 {
4368                    // Top level `let` is always allowed; only gate chains
4369                    match self.let_chains_policy {
4370                        LetChainsPolicy::AlwaysAllowed => (),
4371                        LetChainsPolicy::EditionDependent { current_edition } => {
4372                            if !current_edition.at_least_rust_2024() || !span.at_least_rust_2024() {
4373                                self.parser.dcx().emit_err(diagnostics::LetChainPre2024 { span });
4374                            }
4375                        }
4376                    }
4377                }
4378            }
4379            ExprKind::Binary(Spanned { node: BinOpKind::And, .. }, _, _) => {
4380                mut_visit::walk_expr(self, e);
4381            }
4382            ExprKind::Binary(Spanned { node: BinOpKind::Or, span: or_span }, _, _)
4383                if let None | Some(diagnostics::ForbiddenLetReason::NotSupportedOr(_)) =
4384                    self.forbid_let_reason =>
4385            {
4386                let forbid_let_reason = self.forbid_let_reason;
4387                self.forbid_let_reason =
4388                    Some(diagnostics::ForbiddenLetReason::NotSupportedOr(or_span));
4389                mut_visit::walk_expr(self, e);
4390                self.forbid_let_reason = forbid_let_reason;
4391            }
4392            ExprKind::Paren(ref inner)
4393                if let None | Some(diagnostics::ForbiddenLetReason::NotSupportedParentheses(_)) =
4394                    self.forbid_let_reason =>
4395            {
4396                let forbid_let_reason = self.forbid_let_reason;
4397                self.forbid_let_reason =
4398                    Some(diagnostics::ForbiddenLetReason::NotSupportedParentheses(inner.span));
4399                mut_visit::walk_expr(self, e);
4400                self.forbid_let_reason = forbid_let_reason;
4401            }
4402            ExprKind::Assign(ref lhs, ref rhs, span) => {
4403                if let ExprKind::Call(_, _) = &lhs.kind {
4404                    fn get_path_from_rhs(e: &Expr) -> Option<(u32, &Path)> {
4405                        fn inner(e: &Expr, depth: u32) -> Option<(u32, &Path)> {
4406                            match &e.kind {
4407                                ExprKind::Binary(_, lhs, _) => inner(lhs, depth + 1),
4408                                ExprKind::Path(_, path) => Some((depth, path)),
4409                                _ => None,
4410                            }
4411                        }
4412
4413                        inner(e, 0)
4414                    }
4415
4416                    if let Some((depth, path)) = get_path_from_rhs(rhs) {
4417                        // For cases like if Some(_) = x && let Some(_) = y && let Some(_) = z
4418                        // This return let Some(_) = y expression
4419                        fn find_let_some(expr: &Expr) -> Option<&Expr> {
4420                            match &expr.kind {
4421                                ExprKind::Let(..) => Some(expr),
4422
4423                                ExprKind::Binary(op, lhs, rhs) if op.node == BinOpKind::And => {
4424                                    find_let_some(lhs).or_else(|| find_let_some(rhs))
4425                                }
4426
4427                                _ => None,
4428                            }
4429                        }
4430
4431                        let expr_span = lhs.span.to(path.span);
4432
4433                        if let Some(later_rhs) = find_let_some(rhs)
4434                            && depth > 0
4435                        {
4436                            let guar =
4437                                self.parser.dcx().emit_err(diagnostics::LetChainMissingLet {
4438                                    span: lhs.span,
4439                                    label_span: expr_span,
4440                                    rhs_span: later_rhs.span,
4441                                    sug_span: lhs.span.shrink_to_lo(),
4442                                });
4443
4444                            self.found_incorrect_let_chain = Some(guar);
4445                        }
4446                    }
4447                }
4448
4449                let forbid_let_reason = self.forbid_let_reason;
4450                self.forbid_let_reason = Some(diagnostics::ForbiddenLetReason::OtherForbidden);
4451                let missing_let = self.missing_let;
4452                if let ExprKind::Binary(_, _, rhs) = &lhs.kind
4453                    && let ExprKind::Path(_, _)
4454                    | ExprKind::Struct(_)
4455                    | ExprKind::Call(_, _)
4456                    | ExprKind::Array(_) = rhs.kind
4457                {
4458                    self.missing_let =
4459                        Some(diagnostics::MaybeMissingLet { span: rhs.span.shrink_to_lo() });
4460                }
4461                let comparison = self.comparison;
4462                self.comparison = Some(diagnostics::MaybeComparison { span: span.shrink_to_hi() });
4463                mut_visit::walk_expr(self, e);
4464                self.forbid_let_reason = forbid_let_reason;
4465                self.missing_let = missing_let;
4466                self.comparison = comparison;
4467            }
4468            ExprKind::Unary(_, _)
4469            | ExprKind::Await(_, _)
4470            | ExprKind::Move(_, _)
4471            | ExprKind::Use(_, _)
4472            | ExprKind::AssignOp(_, _, _)
4473            | ExprKind::Range(_, _, _)
4474            | ExprKind::Try(_)
4475            | ExprKind::AddrOf(_, _, _)
4476            | ExprKind::Binary(_, _, _)
4477            | ExprKind::Field(_, _)
4478            | ExprKind::Index(_, _, _)
4479            | ExprKind::Call(_, _)
4480            | ExprKind::MethodCall(_)
4481            | ExprKind::Tup(_)
4482            | ExprKind::Paren(_) => {
4483                let forbid_let_reason = self.forbid_let_reason;
4484                self.forbid_let_reason = Some(diagnostics::ForbiddenLetReason::OtherForbidden);
4485                mut_visit::walk_expr(self, e);
4486                self.forbid_let_reason = forbid_let_reason;
4487            }
4488            ExprKind::Cast(ref mut op, _)
4489            | ExprKind::Type(ref mut op, _)
4490            | ExprKind::UnsafeBinderCast(_, ref mut op, _) => {
4491                let forbid_let_reason = self.forbid_let_reason;
4492                self.forbid_let_reason = Some(diagnostics::ForbiddenLetReason::OtherForbidden);
4493                self.visit_expr(op);
4494                self.forbid_let_reason = forbid_let_reason;
4495            }
4496            ExprKind::Let(_, _, _, Recovered::Yes(_))
4497            | ExprKind::Array(_)
4498            | ExprKind::ConstBlock(_)
4499            | ExprKind::Lit(_)
4500            | ExprKind::If(_, _, _)
4501            | ExprKind::While(_, _, _)
4502            | ExprKind::ForLoop { .. }
4503            | ExprKind::Loop(_, _, _)
4504            | ExprKind::Match(_, _, _)
4505            | ExprKind::Closure(_)
4506            | ExprKind::Block(_, _)
4507            | ExprKind::Gen(_, _, _, _)
4508            | ExprKind::TryBlock(_, _)
4509            | ExprKind::Underscore
4510            | ExprKind::Path(_, _)
4511            | ExprKind::Break(_, _)
4512            | ExprKind::Continue(_)
4513            | ExprKind::Ret(_)
4514            | ExprKind::InlineAsm(_)
4515            | ExprKind::OffsetOf(_, _)
4516            | ExprKind::MacCall(_)
4517            | ExprKind::Struct(_)
4518            | ExprKind::Repeat(_, _)
4519            | ExprKind::Yield(_)
4520            | ExprKind::Yeet(_)
4521            | ExprKind::Become(_)
4522            | ExprKind::IncludedBytes(_)
4523            | ExprKind::FormatArgs(_)
4524            | ExprKind::Err(_)
4525            | ExprKind::DirectConstArg(_)
4526            | ExprKind::Dummy => {
4527                // These would forbid any let expressions they contain already.
4528            }
4529        }
4530        self.depth -= 1;
4531    }
4532}