Skip to main content

rustc_parse/parser/
expr.rs

1// ignore-tidy-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::tokenstream::TokenTree;
11use rustc_ast::util::case::Case;
12use rustc_ast::util::classify;
13use rustc_ast::util::parser::{AssocOp, ExprPrecedence, Fixity, prec_let_scrutinee_needs_par};
14use rustc_ast::visit::{Visitor, walk_expr};
15use rustc_ast::{
16    self as ast, AnonConst, Arm, AssignOp, AssignOpKind, AttrStyle, AttrVec, BinOp, BinOpKind,
17    BlockCheckMode, CaptureBy, ClosureBinder, DUMMY_NODE_ID, Expr, ExprField, ExprKind, FnDecl,
18    FnRetTy, Guard, Label, MacCall, MetaItemLit, Movability, Param, RangeLimits, StmtKind, Ty,
19    TyKind, UnOp, UnsafeBinderCastKind, YieldKind,
20};
21use rustc_ast_pretty::pprust;
22use rustc_data_structures::stack::ensure_sufficient_stack;
23use rustc_errors::{Applicability, Diag, PResult, StashKey, Subdiagnostic};
24use rustc_literal_escaper::unescape_char;
25use rustc_session::errors::{ExprParenthesesNeeded, report_lit_error};
26use rustc_session::lint::builtin::BREAK_WITH_LABEL_AND_LOOP;
27use rustc_span::edition::Edition;
28use rustc_span::{BytePos, ErrorGuaranteed, Ident, Pos, Span, Spanned, Symbol, kw, respan, sym};
29use thin_vec::{ThinVec, thin_vec};
30use tracing::instrument;
31
32use super::diagnostics::SnapshotParser;
33use super::pat::{CommaRecoveryMode, Expected, RecoverColon, RecoverComma};
34use super::ty::{AllowPlus, RecoverQPath, RecoverReturnSign};
35use super::{
36    AttrWrapper, BlockMode, ClosureSpans, ExpTokenPair, ForceCollect, Parser, PathStyle,
37    Restrictions, SemiColonMode, SeqSep, TokenType, Trailing, UsePreAttrPos,
38};
39use crate::{diagnostics, exp, maybe_recover_from_interpolated_ty_qpath};
40
41#[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)]
42pub(super) enum DestructuredFloat {
43    /// 1e2
44    Single(Symbol, Span),
45    /// 1.
46    TrailingDot(Symbol, Span, Span),
47    /// 1.2 | 1.2e3
48    MiddleDot(Symbol, Span, Span, Symbol, Span),
49    /// Invalid
50    Error,
51}
52
53impl<'a> Parser<'a> {
54    /// Parses an expression.
55    #[inline]
56    pub fn parse_expr(&mut self) -> PResult<'a, Box<Expr>> {
57        self.current_closure.take();
58
59        let attrs = self.parse_outer_attributes()?;
60        self.parse_expr_res(Restrictions::empty(), attrs).map(|res| res.0)
61    }
62
63    /// Parses an expression, forcing tokens to be collected.
64    pub fn parse_expr_force_collect(&mut self) -> PResult<'a, Box<Expr>> {
65        self.current_closure.take();
66
67        // If the expression is associative (e.g. `1 + 2`), then any preceding
68        // outer attribute actually belongs to the first inner sub-expression.
69        // In which case we must use the pre-attr pos to include the attribute
70        // in the collected tokens for the outer expression.
71        let pre_attr_pos = self.collect_pos();
72        let attrs = self.parse_outer_attributes()?;
73        self.collect_tokens(
74            Some(pre_attr_pos),
75            AttrWrapper::empty(),
76            ForceCollect::Yes,
77            |this, _empty_attrs| {
78                let (expr, is_assoc) = this.parse_expr_res(Restrictions::empty(), attrs)?;
79                let use_pre_attr_pos =
80                    if is_assoc { UsePreAttrPos::Yes } else { UsePreAttrPos::No };
81                Ok((expr, Trailing::No, use_pre_attr_pos))
82            },
83        )
84    }
85
86    pub fn parse_expr_anon_const(&mut self) -> PResult<'a, AnonConst> {
87        self.parse_expr().map(|value| AnonConst { id: DUMMY_NODE_ID, value })
88    }
89
90    fn parse_expr_catch_underscore(
91        &mut self,
92        restrictions: Restrictions,
93    ) -> PResult<'a, Box<Expr>> {
94        let attrs = self.parse_outer_attributes()?;
95        match self.parse_expr_res(restrictions, attrs) {
96            Ok((expr, _)) => Ok(expr),
97            Err(err) => match self.token.ident() {
98                Some((Ident { name: kw::Underscore, .. }, IdentIsRaw::No))
99                    if self.may_recover() && self.look_ahead(1, |t| t == &token::Comma) =>
100                {
101                    // Special-case handling of `foo(_, _, _)`
102                    let guar = err.emit();
103                    self.bump();
104                    Ok(self.mk_expr(self.prev_token.span, ExprKind::Err(guar)))
105                }
106                _ => Err(err),
107            },
108        }
109    }
110
111    /// Parses a sequence of expressions delimited by parentheses.
112    fn parse_expr_paren_seq(&mut self) -> PResult<'a, ThinVec<Box<Expr>>> {
113        self.parse_paren_comma_seq(|p| p.parse_expr_catch_underscore(Restrictions::empty()))
114            .map(|(r, _)| r)
115    }
116
117    /// Parses an expression, subject to the given restrictions.
118    #[inline]
119    pub(super) fn parse_expr_res(
120        &mut self,
121        r: Restrictions,
122        attrs: AttrWrapper,
123    ) -> PResult<'a, (Box<Expr>, bool)> {
124        self.with_res(r, |this| this.parse_expr_assoc_with(Bound::Unbounded, attrs))
125    }
126
127    /// Parses an associative expression with operators of at least `min_prec` precedence.
128    /// The `bool` in the return value indicates if it was an assoc expr, i.e. with an operator
129    /// followed by a subexpression (e.g. `1 + 2`).
130    pub(super) fn parse_expr_assoc_with(
131        &mut self,
132        min_prec: Bound<ExprPrecedence>,
133        attrs: AttrWrapper,
134    ) -> PResult<'a, (Box<Expr>, bool)> {
135        let lhs = if self.token.is_range_separator() {
136            return self.parse_expr_prefix_range(attrs).map(|res| (res, false));
137        } else {
138            self.parse_expr_prefix(attrs)?
139        };
140        self.parse_expr_assoc_rest_with(min_prec, false, lhs)
141    }
142
143    /// Parses the rest of an associative expression (i.e. the part after the lhs) with operators
144    /// of at least `min_prec` precedence. The `bool` in the return value indicates if something
145    /// was actually parsed.
146    pub(super) fn parse_expr_assoc_rest_with(
147        &mut self,
148        min_prec: Bound<ExprPrecedence>,
149        starts_stmt: bool,
150        mut lhs: Box<Expr>,
151    ) -> PResult<'a, (Box<Expr>, bool)> {
152        let mut parsed_something = false;
153        if !self.should_continue_as_assoc_expr(&lhs) {
154            return Ok((lhs, parsed_something));
155        }
156
157        self.expected_token_types.insert(TokenType::Operator);
158        while let Some(op) = self.check_assoc_op() {
159            let lhs_span = self.interpolated_or_expr_span(&lhs);
160            let cur_op_span = self.token.span;
161            let restrictions = if op.node.is_assign_like() {
162                self.restrictions & Restrictions::NO_STRUCT_LITERAL
163            } else {
164                self.restrictions
165            };
166            let prec = op.node.precedence();
167            if match min_prec {
168                Bound::Included(min_prec) => prec < min_prec,
169                Bound::Excluded(min_prec) => prec <= min_prec,
170                Bound::Unbounded => false,
171            } {
172                break;
173            }
174            // Check for deprecated `...` syntax
175            if self.token == token::DotDotDot && op.node == AssocOp::Range(RangeLimits::Closed) {
176                self.err_dotdotdot_syntax(self.token.span);
177            }
178
179            if self.token == token::LArrow {
180                self.err_larrow_operator(self.token.span);
181            }
182
183            parsed_something = true;
184            self.bump();
185            if op.node.is_comparison() {
186                if let Some(expr) = self.check_no_chained_comparison(&lhs, &op)? {
187                    return Ok((expr, parsed_something));
188                }
189            }
190
191            // Look for JS' `===` and `!==` and recover
192            if let AssocOp::Binary(bop @ BinOpKind::Eq | bop @ BinOpKind::Ne) = op.node
193                && self.token == token::Eq
194                && self.prev_token.span.hi() == self.token.span.lo()
195            {
196                let sp = op.span.to(self.token.span);
197                let sugg = bop.as_str().into();
198                let invalid = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}=", sugg))
    })format!("{sugg}=");
199                self.dcx().emit_err(diagnostics::InvalidComparisonOperator {
200                    span: sp,
201                    invalid: invalid.clone(),
202                    sub: diagnostics::InvalidComparisonOperatorSub::Correctable {
203                        span: sp,
204                        invalid,
205                        correct: sugg,
206                    },
207                });
208                self.bump();
209            }
210
211            // Look for PHP's `<>` and recover
212            if op.node == AssocOp::Binary(BinOpKind::Lt)
213                && self.token == token::Gt
214                && self.prev_token.span.hi() == self.token.span.lo()
215            {
216                let sp = op.span.to(self.token.span);
217                self.dcx().emit_err(diagnostics::InvalidComparisonOperator {
218                    span: sp,
219                    invalid: "<>".into(),
220                    sub: diagnostics::InvalidComparisonOperatorSub::Correctable {
221                        span: sp,
222                        invalid: "<>".into(),
223                        correct: "!=".into(),
224                    },
225                });
226                self.bump();
227            }
228
229            // Look for C++'s `<=>` and recover
230            if op.node == AssocOp::Binary(BinOpKind::Le)
231                && self.token == token::Gt
232                && self.prev_token.span.hi() == self.token.span.lo()
233            {
234                let sp = op.span.to(self.token.span);
235                self.dcx().emit_err(diagnostics::InvalidComparisonOperator {
236                    span: sp,
237                    invalid: "<=>".into(),
238                    sub: diagnostics::InvalidComparisonOperatorSub::Spaceship(sp),
239                });
240                self.bump();
241            }
242
243            if self.prev_token == token::Plus
244                && self.token == token::Plus
245                && self.prev_token.span.between(self.token.span).is_empty()
246            {
247                let op_span = self.prev_token.span.to(self.token.span);
248                // Eat the second `+`
249                self.bump();
250                lhs = self.recover_from_postfix_increment(lhs, op_span, starts_stmt)?;
251                continue;
252            }
253
254            if self.prev_token == token::Minus
255                && self.token == token::Minus
256                && self.prev_token.span.between(self.token.span).is_empty()
257                && !self.look_ahead(1, |tok| tok.can_begin_expr())
258            {
259                let op_span = self.prev_token.span.to(self.token.span);
260                // Eat the second `-`
261                self.bump();
262                lhs = self.recover_from_postfix_decrement(lhs, op_span, starts_stmt)?;
263                continue;
264            }
265
266            let op_span = op.span;
267            let op = op.node;
268            // Special cases:
269            if op == AssocOp::Cast {
270                lhs = self.parse_assoc_op_cast(lhs, lhs_span, op_span, ExprKind::Cast)?;
271                continue;
272            } else if let AssocOp::Range(limits) = op {
273                // If we didn't have to handle `x..`/`x..=`, it would be pretty easy to
274                // generalise it to the Fixity::None code.
275                lhs = self.parse_expr_range(prec, lhs, limits, cur_op_span)?;
276                break;
277            }
278
279            let min_prec = match op.fixity() {
280                Fixity::Right => Bound::Included(prec),
281                Fixity::Left | Fixity::None => Bound::Excluded(prec),
282            };
283            let (rhs, _) = self.with_res(restrictions - Restrictions::STMT_EXPR, |this| {
284                let attrs = this.parse_outer_attributes()?;
285                this.parse_expr_assoc_with(min_prec, attrs)
286            })?;
287
288            let span = self.mk_expr_sp(&lhs, lhs_span, op_span, rhs.span);
289            lhs = match op {
290                AssocOp::Binary(ast_op) => {
291                    let binary = self.mk_binary(respan(cur_op_span, ast_op), lhs, rhs);
292                    self.mk_expr(span, binary)
293                }
294                AssocOp::Assign => self.mk_expr(span, ExprKind::Assign(lhs, rhs, cur_op_span)),
295                AssocOp::AssignOp(aop) => {
296                    let aopexpr = self.mk_assign_op(respan(cur_op_span, aop), lhs, rhs);
297                    self.mk_expr(span, aopexpr)
298                }
299                AssocOp::Cast | AssocOp::Range(_) => {
300                    self.dcx().span_bug(span, "AssocOp should have been handled by special case")
301                }
302            };
303        }
304
305        Ok((lhs, parsed_something))
306    }
307
308    fn should_continue_as_assoc_expr(&mut self, lhs: &Expr) -> bool {
309        match (self.expr_is_complete(lhs), AssocOp::from_token(&self.token)) {
310            // Semi-statement forms are odd:
311            // See https://github.com/rust-lang/rust/issues/29071
312            (true, None) => false,
313            (false, _) => true, // Continue parsing the expression.
314            // An exhaustive check is done in the following block, but these are checked first
315            // because they *are* ambiguous but also reasonable looking incorrect syntax, so we
316            // want to keep their span info to improve diagnostics in these cases in a later stage.
317            (true, Some(AssocOp::Binary(
318                BinOpKind::Mul | // `{ 42 } *foo = bar;` or `{ 42 } * 3`
319                BinOpKind::Sub | // `{ 42 } -5`
320                BinOpKind::Add | // `{ 42 } + 42` (unary plus)
321                BinOpKind::And | // `{ 42 } &&x` (#61475) or `{ 42 } && if x { 1 } else { 0 }`
322                BinOpKind::Or | // `{ 42 } || 42` ("logical or" or closure)
323                BinOpKind::BitOr // `{ 42 } | 42` or `{ 42 } |x| 42`
324            ))) => {
325                // These cases are ambiguous and can't be identified in the parser alone.
326                //
327                // Bitwise AND is left out because guessing intent is hard. We can make
328                // suggestions based on the assumption that double-refs are rarely intentional,
329                // and closures are distinct enough that they don't get mixed up with their
330                // return value.
331                let sp = self.psess.source_map().start_point(self.token.span);
332                self.psess.ambiguous_block_expr_parse.borrow_mut().insert(sp, lhs.span);
333                false
334            }
335            (true, Some(op)) if !op.can_continue_expr_unambiguously() => false,
336            (true, Some(_)) => {
337                self.error_found_expr_would_be_stmt(lhs);
338                true
339            }
340        }
341    }
342
343    /// We've found an expression that would be parsed as a statement,
344    /// but the next token implies this should be parsed as an expression.
345    /// For example: `if let Some(x) = x { x } else { 0 } / 2`.
346    fn error_found_expr_would_be_stmt(&self, lhs: &Expr) {
347        self.dcx().emit_err(diagnostics::FoundExprWouldBeStmt {
348            span: self.token.span,
349            token: pprust::token_to_string(&self.token),
350            suggestion: ExprParenthesesNeeded::surrounding(lhs.span),
351        });
352    }
353
354    /// Possibly translate the current token to an associative operator.
355    /// The method does not advance the current token.
356    ///
357    /// Also performs recovery for `and` / `or` which are mistaken for `&&` and `||` respectively.
358    pub(super) fn check_assoc_op(&self) -> Option<Spanned<AssocOp>> {
359        let (op, span) = match (AssocOp::from_token(&self.token), self.token.ident()) {
360            // When parsing const expressions, stop parsing when encountering `>`.
361            (
362                Some(
363                    AssocOp::Binary(BinOpKind::Shr | BinOpKind::Gt | BinOpKind::Ge)
364                    | AssocOp::AssignOp(AssignOpKind::ShrAssign),
365                ),
366                _,
367            ) if self.restrictions.contains(Restrictions::CONST_EXPR) => {
368                return None;
369            }
370            // When recovering patterns as expressions, stop parsing when encountering an
371            // assignment `=`, an alternative `|`, or a range `..`.
372            (
373                Some(
374                    AssocOp::Assign
375                    | AssocOp::AssignOp(_)
376                    | AssocOp::Binary(BinOpKind::BitOr)
377                    | AssocOp::Range(_),
378                ),
379                _,
380            ) if self.restrictions.contains(Restrictions::IS_PAT) => {
381                return None;
382            }
383            (Some(op), _) => (op, self.token.span),
384            (None, Some((Ident { name: sym::and, span }, IdentIsRaw::No)))
385                if self.may_recover() =>
386            {
387                self.dcx().emit_err(diagnostics::InvalidLogicalOperator {
388                    span: self.token.span,
389                    incorrect: "and".into(),
390                    sub: diagnostics::InvalidLogicalOperatorSub::Conjunction(self.token.span),
391                });
392                (AssocOp::Binary(BinOpKind::And), span)
393            }
394            (None, Some((Ident { name: sym::or, span }, IdentIsRaw::No))) if self.may_recover() => {
395                self.dcx().emit_err(diagnostics::InvalidLogicalOperator {
396                    span: self.token.span,
397                    incorrect: "or".into(),
398                    sub: diagnostics::InvalidLogicalOperatorSub::Disjunction(self.token.span),
399                });
400                (AssocOp::Binary(BinOpKind::Or), span)
401            }
402            _ => return None,
403        };
404        Some(respan(span, op))
405    }
406
407    /// Checks if this expression is a successfully parsed statement.
408    fn expr_is_complete(&self, e: &Expr) -> bool {
409        self.restrictions.contains(Restrictions::STMT_EXPR) && classify::expr_is_complete(e)
410    }
411
412    /// Parses `x..y`, `x..=y`, and `x..`/`x..=`.
413    /// The other two variants are handled in `parse_prefix_range_expr` below.
414    fn parse_expr_range(
415        &mut self,
416        prec: ExprPrecedence,
417        lhs: Box<Expr>,
418        limits: RangeLimits,
419        cur_op_span: Span,
420    ) -> PResult<'a, Box<Expr>> {
421        let rhs = if self.is_at_start_of_range_notation_rhs() {
422            let maybe_lt = self.token;
423            let attrs = self.parse_outer_attributes()?;
424            Some(
425                self.parse_expr_assoc_with(Bound::Excluded(prec), attrs)
426                    .map_err(|err| self.maybe_err_dotdotlt_syntax(maybe_lt, err))?
427                    .0,
428            )
429        } else {
430            None
431        };
432        let rhs_span = rhs.as_ref().map_or(cur_op_span, |x| x.span);
433        let span = self.mk_expr_sp(&lhs, lhs.span, cur_op_span, rhs_span);
434        let range = self.mk_range(Some(lhs), rhs, limits);
435        Ok(self.mk_expr(span, range))
436    }
437
438    fn is_at_start_of_range_notation_rhs(&self) -> bool {
439        if self.token.can_begin_expr() {
440            // Parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
441            if self.token == token::OpenBrace {
442                return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
443            }
444            true
445        } else {
446            false
447        }
448    }
449
450    /// Parses prefix-forms of range notation: `..expr`, `..`, `..=expr`.
451    fn parse_expr_prefix_range(&mut self, attrs: AttrWrapper) -> PResult<'a, Box<Expr>> {
452        if !attrs.is_empty() {
453            let err = diagnostics::DotDotRangeAttribute { span: self.token.span };
454            self.dcx().emit_err(err);
455        }
456
457        // Check for deprecated `...` syntax.
458        if self.token == token::DotDotDot {
459            self.err_dotdotdot_syntax(self.token.span);
460        }
461
462        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!(
463            self.token.is_range_separator(),
464            "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
465            self.token
466        );
467
468        let limits = match self.token.kind {
469            token::DotDot => RangeLimits::HalfOpen,
470            _ => RangeLimits::Closed,
471        };
472        let op = AssocOp::from_token(&self.token);
473        let attrs = self.parse_outer_attributes()?;
474        self.collect_tokens_for_expr(attrs, |this, attrs| {
475            let lo = this.token.span;
476            let maybe_lt = this.look_ahead(1, |t| t.clone());
477            this.bump();
478            let (span, opt_end) = if this.is_at_start_of_range_notation_rhs() {
479                // RHS must be parsed with more associativity than the dots.
480                let attrs = this.parse_outer_attributes()?;
481                this.parse_expr_assoc_with(Bound::Excluded(op.unwrap().precedence()), attrs)
482                    .map(|(x, _)| (lo.to(x.span), Some(x)))
483                    .map_err(|err| this.maybe_err_dotdotlt_syntax(maybe_lt, err))?
484            } else {
485                (lo, None)
486            };
487            let range = this.mk_range(None, opt_end, limits);
488            Ok(this.mk_expr_with_attrs(span, range, attrs))
489        })
490    }
491
492    /// Parses a prefix-unary-operator expr.
493    fn parse_expr_prefix(&mut self, attrs: AttrWrapper) -> PResult<'a, Box<Expr>> {
494        let lo = self.token.span;
495
496        macro_rules! make_it {
497            ($this:ident, $attrs:expr, |this, _| $body:expr) => {
498                $this.collect_tokens_for_expr($attrs, |$this, attrs| {
499                    let (hi, ex) = $body?;
500                    Ok($this.mk_expr_with_attrs(lo.to(hi), ex, attrs))
501                })
502            };
503        }
504
505        let this = self;
506
507        // Note: when adding new unary operators, don't forget to adjust TokenKind::can_begin_expr()
508        match this.token.uninterpolate().kind {
509            // `!expr`
510            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)),
511            // `~expr`
512            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)),
513            // `-expr`
514            token::Minus => {
515                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))
516            }
517            // `*expr`
518            token::Star => {
519                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))
520            }
521            // `&expr` and `&&expr`
522            token::And | token::AndAnd => {
523                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))
524            }
525            // `+lit`
526            token::Plus if this.look_ahead(1, |tok| tok.is_numeric_lit()) => {
527                let mut err = diagnostics::LeadingPlusNotSupported {
528                    span: lo,
529                    remove_plus: None,
530                    add_parentheses: None,
531                };
532
533                // a block on the LHS might have been intended to be an expression instead
534                if let Some(sp) = this.psess.ambiguous_block_expr_parse.borrow().get(&lo) {
535                    err.add_parentheses = Some(ExprParenthesesNeeded::surrounding(*sp));
536                } else {
537                    err.remove_plus = Some(lo);
538                }
539                this.dcx().emit_err(err);
540
541                this.bump();
542                let attrs = this.parse_outer_attributes()?;
543                this.parse_expr_prefix(attrs)
544            }
545            // Recover from `++x`:
546            token::Plus if this.look_ahead(1, |t| *t == token::Plus) => {
547                let starts_stmt =
548                    this.prev_token == token::Semi || this.prev_token == token::CloseBrace;
549                let pre_span = this.token.span.to(this.look_ahead(1, |t| t.span));
550                // Eat both `+`s.
551                this.bump();
552                this.bump();
553
554                let operand_expr = this.parse_expr_dot_or_call(attrs)?;
555                this.recover_from_prefix_increment(operand_expr, pre_span, starts_stmt)
556            }
557            token::Ident(..) if this.token.is_keyword(kw::Box) => {
558                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))
559            }
560            token::Ident(..)
561                if this.token.is_keyword(kw::Move)
562                    && this.look_ahead(1, |t| *t == token::OpenParen) =>
563            {
564                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))
565            }
566            token::Ident(..) if this.may_recover() && this.is_mistaken_not_ident_negation() => {
567                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))
568            }
569            _ => return this.parse_expr_dot_or_call(attrs),
570        }
571    }
572
573    fn parse_expr_prefix_common(&mut self, lo: Span) -> PResult<'a, (Span, Box<Expr>)> {
574        self.bump();
575        let attrs = self.parse_outer_attributes()?;
576        let expr = if self.token.is_range_separator() {
577            self.parse_expr_prefix_range(attrs)
578        } else {
579            self.parse_expr_prefix(attrs)
580        }?;
581        let span = self.interpolated_or_expr_span(&expr);
582        Ok((lo.to(span), expr))
583    }
584
585    fn parse_expr_unary(&mut self, lo: Span, op: UnOp) -> PResult<'a, (Span, ExprKind)> {
586        let (span, expr) = self.parse_expr_prefix_common(lo)?;
587        Ok((span, self.mk_unary(op, expr)))
588    }
589
590    /// Recover on `~expr` in favor of `!expr`.
591    fn recover_tilde_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
592        self.dcx().emit_err(diagnostics::TildeAsUnaryOperator(lo));
593
594        self.parse_expr_unary(lo, UnOp::Not)
595    }
596
597    /// Parse `box expr` - this syntax has been removed, but we still parse this
598    /// for now to provide a more useful error
599    fn parse_expr_box(&mut self, box_kw: Span) -> PResult<'a, (Span, ExprKind)> {
600        let (span, expr) = self.parse_expr_prefix_common(box_kw)?;
601        // Make a multipart suggestion instead of `span_to_snippet` in case source isn't available
602        let box_kw_and_lo = box_kw.until(self.interpolated_or_expr_span(&expr));
603        let hi = span.shrink_to_hi();
604        let sugg = diagnostics::AddBoxNew { box_kw_and_lo, hi };
605        let guar = self.dcx().emit_err(diagnostics::BoxSyntaxRemoved { span, sugg });
606        Ok((span, ExprKind::Err(guar)))
607    }
608
609    fn parse_expr_move(&mut self, move_kw: Span) -> PResult<'a, (Span, ExprKind)> {
610        self.bump();
611        self.psess.gated_spans.gate(sym::move_expr, move_kw);
612        self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenParen,
    token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen))?;
613        let expr = self.parse_expr()?;
614        self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseParen,
    token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen))?;
615        let span = move_kw.to(self.prev_token.span);
616        Ok((span, ExprKind::Move(expr, move_kw)))
617    }
618
619    fn is_mistaken_not_ident_negation(&self) -> bool {
620        let token_cannot_continue_expr = |t: &Token| match t.uninterpolate().kind {
621            // These tokens can start an expression after `!`, but
622            // can't continue an expression after an ident
623            token::Ident(name, is_raw) => token::ident_can_begin_expr(name, t.span, is_raw),
624            token::Literal(..) | token::Pound => true,
625            _ => t.is_metavar_expr(),
626        };
627        self.token.is_ident_named(sym::not) && self.look_ahead(1, token_cannot_continue_expr)
628    }
629
630    /// Recover on `not expr` in favor of `!expr`.
631    fn recover_not_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
632        let negated_token = self.look_ahead(1, |t| *t);
633
634        let sub_diag = if negated_token.is_numeric_lit() {
635            diagnostics::NotAsNegationOperatorSub::SuggestNotBitwise
636        } else if negated_token.is_bool_lit() {
637            diagnostics::NotAsNegationOperatorSub::SuggestNotLogical
638        } else {
639            diagnostics::NotAsNegationOperatorSub::SuggestNotDefault
640        };
641
642        self.dcx().emit_err(diagnostics::NotAsNegationOperator {
643            negated: negated_token.span,
644            negated_desc: super::token_descr(&negated_token),
645            // Span the `not` plus trailing whitespace to avoid
646            // trailing whitespace after the `!` in our suggestion
647            sub: sub_diag(
648                self.psess.source_map().span_until_non_whitespace(lo.to(negated_token.span)),
649            ),
650        });
651
652        self.parse_expr_unary(lo, UnOp::Not)
653    }
654
655    /// Returns the span of expr if it was not interpolated, or the span of the interpolated token.
656    fn interpolated_or_expr_span(&self, expr: &Expr) -> Span {
657        match self.prev_token.kind {
658            token::NtIdent(..) | token::NtLifetime(..) => self.prev_token.span,
659            token::CloseInvisible(InvisibleOrigin::MetaVar(_)) => {
660                // `expr.span` is the interpolated span, because invisible open
661                // and close delims both get marked with the same span, one
662                // that covers the entire thing between them. (See
663                // `rustc_expand::mbe::transcribe::transcribe`.)
664                self.prev_token.span
665            }
666            _ => expr.span,
667        }
668    }
669
670    fn parse_assoc_op_cast(
671        &mut self,
672        lhs: Box<Expr>,
673        lhs_span: Span,
674        op_span: Span,
675        expr_kind: fn(Box<Expr>, Box<Ty>) -> ExprKind,
676    ) -> PResult<'a, Box<Expr>> {
677        let mk_expr = |this: &mut Self, lhs: Box<Expr>, rhs: Box<Ty>| {
678            this.mk_expr(this.mk_expr_sp(&lhs, lhs_span, op_span, rhs.span), expr_kind(lhs, rhs))
679        };
680
681        // Save the state of the parser before parsing type normally, in case there is a
682        // LessThan comparison after this cast.
683        let parser_snapshot_before_type = self.clone();
684        let cast_expr = match self.parse_as_cast_ty() {
685            Ok(rhs) => mk_expr(self, lhs, rhs),
686            Err(type_err) => {
687                if !self.may_recover() {
688                    return Err(type_err);
689                }
690
691                // Rewind to before attempting to parse the type with generics, to recover
692                // from situations like `x as usize < y` in which we first tried to parse
693                // `usize < y` as a type with generic arguments.
694                let parser_snapshot_after_type = mem::replace(self, parser_snapshot_before_type);
695
696                // Check for typo of `'a: loop { break 'a }` with a missing `'`.
697                match (&lhs.kind, &self.token.kind) {
698                    (
699                        // `foo: `
700                        ExprKind::Path(None, ast::Path { segments, .. }),
701                        token::Ident(kw::For | kw::Loop | kw::While, IdentIsRaw::No),
702                    ) if let [segment] = segments.as_slice() => {
703                        let snapshot = self.create_snapshot_for_diagnostic();
704                        let label = Label {
705                            ident: Ident::from_str_and_span(
706                                &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\'{0}", segment.ident))
    })format!("'{}", segment.ident),
707                                segment.ident.span,
708                            ),
709                        };
710                        match self.parse_expr_labeled(label, false) {
711                            Ok(expr) => {
712                                type_err.cancel();
713                                self.dcx().emit_err(diagnostics::MalformedLoopLabel {
714                                    span: label.ident.span,
715                                    suggestion: label.ident.span.shrink_to_lo(),
716                                });
717                                return Ok(expr);
718                            }
719                            Err(err) => {
720                                err.cancel();
721                                self.restore_snapshot(snapshot);
722                            }
723                        }
724                    }
725                    _ => {}
726                }
727
728                match self.parse_path(PathStyle::Expr) {
729                    Ok(path) => {
730                        let span_after_type = parser_snapshot_after_type.token.span;
731                        let expr = mk_expr(
732                            self,
733                            lhs,
734                            self.mk_ty(path.span, TyKind::Path(None, path.clone())),
735                        );
736
737                        let args_span = self.look_ahead(1, |t| t.span).to(span_after_type);
738                        match self.token.kind {
739                            token::Lt => {
740                                self.dcx().emit_err(diagnostics::ComparisonInterpretedAsGeneric {
741                                    comparison: self.token.span,
742                                    r#type: pprust::path_to_string(&path),
743                                    args: args_span,
744                                    suggestion: diagnostics::ComparisonInterpretedAsGenericSugg {
745                                        left: expr.span.shrink_to_lo(),
746                                        right: expr.span.shrink_to_hi(),
747                                    },
748                                })
749                            }
750                            token::Shl => {
751                                self.dcx().emit_err(diagnostics::ShiftInterpretedAsGeneric {
752                                    shift: self.token.span,
753                                    r#type: pprust::path_to_string(&path),
754                                    args: args_span,
755                                    suggestion: diagnostics::ShiftInterpretedAsGenericSugg {
756                                        left: expr.span.shrink_to_lo(),
757                                        right: expr.span.shrink_to_hi(),
758                                    },
759                                })
760                            }
761                            _ => {
762                                // We can end up here even without `<` being the next token, for
763                                // example because `parse_ty_no_plus` returns `Err` on keywords,
764                                // but `parse_path` returns `Ok` on them due to error recovery.
765                                // Return original error and parser state.
766                                *self = parser_snapshot_after_type;
767                                return Err(type_err);
768                            }
769                        };
770
771                        // Successfully parsed the type path leaving a `<` yet to parse.
772                        type_err.cancel();
773
774                        // Keep `x as usize` as an expression in AST and continue parsing.
775                        expr
776                    }
777                    Err(path_err) => {
778                        // Couldn't parse as a path, return original error and parser state.
779                        path_err.cancel();
780                        *self = parser_snapshot_after_type;
781                        return Err(type_err);
782                    }
783                }
784            }
785        };
786
787        // Try to parse a postfix operator such as `.`, `?`, or index (`[]`)
788        // after a cast. If one is present, emit an error then return a valid
789        // parse tree; For something like `&x as T[0]` will be as if it was
790        // written `((&x) as T)[0]`.
791
792        let span = cast_expr.span;
793
794        let with_postfix = self.parse_expr_dot_or_call_with(AttrVec::new(), cast_expr, span)?;
795
796        // Check if an illegal postfix operator has been added after the cast.
797        // If the resulting expression is not a cast, it is an illegal postfix operator.
798        if !#[allow(non_exhaustive_omitted_patterns)] match with_postfix.kind {
    ExprKind::Cast(_, _) => true,
    _ => false,
}matches!(with_postfix.kind, ExprKind::Cast(_, _)) {
799            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!(
800                "cast cannot be followed by {}",
801                match with_postfix.kind {
802                    ExprKind::Index(..) => "indexing",
803                    ExprKind::Try(_) => "`?`",
804                    ExprKind::Field(_, _) => "a field access",
805                    ExprKind::MethodCall(_) => "a method call",
806                    ExprKind::Call(_, _) => "a function call",
807                    ExprKind::Await(_, _) => "`.await`",
808                    ExprKind::Use(_, _) => "`.use`",
809                    ExprKind::Yield(YieldKind::Postfix(_)) => "`.yield`",
810                    ExprKind::Match(_, _, MatchKind::Postfix) => "a postfix match",
811                    ExprKind::Err(_) => return Ok(with_postfix),
812                    _ => unreachable!(
813                        "did not expect {:?} as an illegal postfix operator following cast",
814                        with_postfix.kind
815                    ),
816                }
817            );
818            let mut err = self.dcx().struct_span_err(span, msg);
819
820            let suggest_parens = |err: &mut Diag<'_>| {
821                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![
822                    (span.shrink_to_lo(), "(".to_string()),
823                    (span.shrink_to_hi(), ")".to_string()),
824                ];
825                err.multipart_suggestion(
826                    "try surrounding the expression in parentheses",
827                    suggestions,
828                    Applicability::MachineApplicable,
829                );
830            };
831
832            suggest_parens(&mut err);
833
834            err.emit();
835        };
836        Ok(with_postfix)
837    }
838
839    /// Parse `& mut? <expr>` or `& raw [ const | mut ] <expr>`.
840    fn parse_expr_borrow(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
841        self.expect_and()?;
842        let has_lifetime = self.token.is_lifetime() && self.look_ahead(1, |t| t != &token::Colon);
843        let lifetime = has_lifetime.then(|| self.expect_lifetime()); // For recovery, see below.
844        let (borrow_kind, mutbl) = self.parse_borrow_modifiers();
845        let attrs = self.parse_outer_attributes()?;
846        let expr = if self.token.is_range_separator() {
847            self.parse_expr_prefix_range(attrs)
848        } else {
849            self.parse_expr_prefix(attrs)
850        }?;
851        let hi = self.interpolated_or_expr_span(&expr);
852        let span = lo.to(hi);
853        if let Some(lt) = lifetime {
854            self.error_remove_borrow_lifetime(span, lt.ident.span.until(expr.span));
855        }
856
857        // Add expected tokens if we parsed `&raw` as an expression.
858        // This will make sure we see "expected `const`, `mut`", and
859        // guides recovery in case we write `&raw expr`.
860        if borrow_kind == ast::BorrowKind::Ref
861            && mutbl == ast::Mutability::Not
862            && #[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)
863        {
864            self.expected_token_types.insert(TokenType::KwMut);
865            self.expected_token_types.insert(TokenType::KwConst);
866        }
867
868        Ok((span, ExprKind::AddrOf(borrow_kind, mutbl, expr)))
869    }
870
871    fn error_remove_borrow_lifetime(&self, span: Span, lt_span: Span) {
872        self.dcx()
873            .emit_err(diagnostics::LifetimeInBorrowExpression { span, lifetime_span: lt_span });
874    }
875
876    /// Parse `mut?` or `[ raw | pin ] [ const | mut ]`.
877    fn parse_borrow_modifiers(&mut self) -> (ast::BorrowKind, ast::Mutability) {
878        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) {
879            // `raw [ const | mut ]`.
880            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));
881            if !found_raw { ::core::panicking::panic("assertion failed: found_raw") };assert!(found_raw);
882            let mutability = self.parse_mut_or_const().unwrap();
883            (ast::BorrowKind::Raw, mutability)
884        } else {
885            match self.parse_pin_and_mut() {
886                // `mut?`
887                (ast::Pinnedness::Not, mutbl) => (ast::BorrowKind::Ref, mutbl),
888                // `pin [ const | mut ]`.
889                // `pin` has been gated in `self.parse_pin_and_mut()` so we don't
890                // need to gate it here.
891                (ast::Pinnedness::Pinned, mutbl) => (ast::BorrowKind::Pin, mutbl),
892            }
893        }
894    }
895
896    /// Parses `a.b` or `a(13)` or `a[4]` or just `a`.
897    fn parse_expr_dot_or_call(&mut self, attrs: AttrWrapper) -> PResult<'a, Box<Expr>> {
898        self.collect_tokens_for_expr(attrs, |this, attrs| {
899            let base = this.parse_expr_bottom()?;
900            let span = this.interpolated_or_expr_span(&base);
901            this.parse_expr_dot_or_call_with(attrs, base, span)
902        })
903    }
904
905    pub(super) fn parse_expr_dot_or_call_with(
906        &mut self,
907        mut attrs: ast::AttrVec,
908        mut e: Box<Expr>,
909        lo: Span,
910    ) -> PResult<'a, Box<Expr>> {
911        let mut res = ensure_sufficient_stack(|| {
912            loop {
913                let has_question =
914                    if self.prev_token == TokenKind::Ident(kw::Return, IdentIsRaw::No) {
915                        // We are using noexpect here because we don't expect a `?` directly after
916                        // a `return` which could be suggested otherwise.
917                        self.eat_noexpect(&token::Question)
918                    } else {
919                        self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Question,
    token_type: crate::parser::token_type::TokenType::Question,
}exp!(Question))
920                    };
921                if has_question {
922                    // `expr?`
923                    e = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Try(e));
924                    continue;
925                }
926                let has_dot = if self.prev_token == TokenKind::Ident(kw::Return, IdentIsRaw::No) {
927                    // We are using noexpect here because we don't expect a `.` directly after
928                    // a `return` which could be suggested otherwise.
929                    self.eat_noexpect(&token::Dot)
930                } else if self.token == TokenKind::RArrow && self.may_recover() {
931                    // Recovery for `expr->suffix`.
932                    self.bump();
933                    let span = self.prev_token.span;
934                    self.dcx().emit_err(diagnostics::ExprRArrowCall { span });
935                    true
936                } else {
937                    self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Dot,
    token_type: crate::parser::token_type::TokenType::Dot,
}exp!(Dot))
938                };
939                if has_dot {
940                    // expr.f
941                    e = self.parse_dot_suffix_expr(lo, e)?;
942                    continue;
943                }
944                if self.expr_is_complete(&e) {
945                    return Ok(e);
946                }
947                e = match self.token.kind {
948                    token::OpenParen => self.parse_expr_fn_call(lo, e),
949                    token::OpenBracket => self.parse_expr_index(lo, e)?,
950                    _ => return Ok(e),
951                }
952            }
953        });
954
955        // Stitch the list of outer attributes onto the return value. A little
956        // bit ugly, but the best way given the current code structure.
957        if !attrs.is_empty()
958            && let Ok(expr) = &mut res
959        {
960            mem::swap(&mut expr.attrs, &mut attrs);
961            expr.attrs.extend(attrs)
962        }
963        res
964    }
965
966    pub(super) fn parse_dot_suffix_expr(
967        &mut self,
968        lo: Span,
969        base: Box<Expr>,
970    ) -> PResult<'a, Box<Expr>> {
971        // At this point we've consumed something like `expr.` and `self.token` holds the token
972        // after the dot.
973        match self.token.uninterpolate().kind {
974            token::Ident(..) => self.parse_dot_suffix(base, lo),
975            token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) => {
976                let ident_span = self.token.span;
977                self.bump();
978                Ok(self.mk_expr_tuple_field_access(lo, ident_span, base, symbol, suffix))
979            }
980            token::Literal(token::Lit { kind: token::Float, symbol, suffix }) => {
981                Ok(match self.break_up_float(symbol, self.token.span) {
982                    // 1e2
983                    DestructuredFloat::Single(sym, _sp) => {
984                        // `foo.1e2`: a single complete dot access, fully consumed. We end up with
985                        // the `1e2` token in `self.prev_token` and the following token in
986                        // `self.token`.
987                        let ident_span = self.token.span;
988                        self.bump();
989                        self.mk_expr_tuple_field_access(lo, ident_span, base, sym, suffix)
990                    }
991                    // 1.
992                    DestructuredFloat::TrailingDot(sym, ident_span, dot_span) => {
993                        // `foo.1.`: a single complete dot access and the start of another.
994                        // We end up with the `sym` (`1`) token in `self.prev_token` and a dot in
995                        // `self.token`.
996                        if !suffix.is_none() {
    ::core::panicking::panic("assertion failed: suffix.is_none()")
};assert!(suffix.is_none());
997                        self.token = Token::new(token::Ident(sym, IdentIsRaw::No), ident_span);
998                        self.bump_with((Token::new(token::Dot, dot_span), self.token_spacing));
999                        self.mk_expr_tuple_field_access(lo, ident_span, base, sym, None)
1000                    }
1001                    // 1.2 | 1.2e3
1002                    DestructuredFloat::MiddleDot(
1003                        sym1,
1004                        ident1_span,
1005                        _dot_span,
1006                        sym2,
1007                        ident2_span,
1008                    ) => {
1009                        // `foo.1.2` (or `foo.1.2e3`): two complete dot accesses. We end up with
1010                        // the `sym2` (`2` or `2e3`) token in `self.prev_token` and the following
1011                        // token in `self.token`.
1012                        let next_token2 =
1013                            Token::new(token::Ident(sym2, IdentIsRaw::No), ident2_span);
1014                        self.bump_with((next_token2, self.token_spacing));
1015                        self.bump();
1016                        let base1 =
1017                            self.mk_expr_tuple_field_access(lo, ident1_span, base, sym1, None);
1018                        self.mk_expr_tuple_field_access(lo, ident2_span, base1, sym2, suffix)
1019                    }
1020                    DestructuredFloat::Error => base,
1021                })
1022            }
1023            _ => {
1024                self.error_unexpected_after_dot();
1025                Ok(base)
1026            }
1027        }
1028    }
1029
1030    fn error_unexpected_after_dot(&self) {
1031        let actual = super::token_descr(&self.token);
1032        let span = self.token.span;
1033        let sm = self.psess.source_map();
1034        let (span, actual) = match (&self.token.kind, self.subparser_name) {
1035            (token::Eof, Some(_)) if let Ok(snippet) = sm.span_to_snippet(sm.next_point(span)) => {
1036                (span.shrink_to_hi(), ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", snippet))
    })format!("`{}`", snippet))
1037            }
1038            (token::CloseInvisible(InvisibleOrigin::MetaVar(_)), _) => {
1039                // No need to report an error. This case will only occur when parsing a pasted
1040                // metavariable, and we should have emitted an error when parsing the macro call in
1041                // the first place. E.g. in this code:
1042                // ```
1043                // macro_rules! m { ($e:expr) => { $e }; }
1044                //
1045                // fn main() {
1046                //     let f = 1;
1047                //     m!(f.);
1048                // }
1049                // ```
1050                // we'll get an error "unexpected token: `)` when parsing the `m!(f.)`, so we don't
1051                // want to issue a second error when parsing the expansion `«f.»` (where `«`/`»`
1052                // represent the invisible delimiters).
1053                self.dcx().span_delayed_bug(span, "bad dot expr in metavariable");
1054                return;
1055            }
1056            _ => (span, actual),
1057        };
1058        self.dcx().emit_err(diagnostics::UnexpectedTokenAfterDot { span, actual });
1059    }
1060
1061    /// We need an identifier or integer, but the next token is a float.
1062    /// Break the float into components to extract the identifier or integer.
1063    ///
1064    /// See also [`TokenKind::break_two_token_op`] which does similar splitting of `>>` into `>`.
1065    //
1066    // FIXME: With current `TokenCursor` it's hard to break tokens into more than 2
1067    //  parts unless those parts are processed immediately. `TokenCursor` should either
1068    //  support pushing "future tokens" (would be also helpful to `break_and_eat`), or
1069    //  we should break everything including floats into more basic proc-macro style
1070    //  tokens in the lexer (probably preferable).
1071    pub(super) fn break_up_float(&self, float: Symbol, span: Span) -> DestructuredFloat {
1072        #[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)]
1073        enum FloatComponent {
1074            IdentLike(String),
1075            Punct(char),
1076        }
1077        use FloatComponent::*;
1078
1079        let float_str = float.as_str();
1080        let mut components = Vec::new();
1081        let mut ident_like = String::new();
1082        for c in float_str.chars() {
1083            if c == '_' || c.is_ascii_alphanumeric() {
1084                ident_like.push(c);
1085            } else if #[allow(non_exhaustive_omitted_patterns)] match c {
    '.' | '+' | '-' => true,
    _ => false,
}matches!(c, '.' | '+' | '-') {
1086                if !ident_like.is_empty() {
1087                    components.push(IdentLike(mem::take(&mut ident_like)));
1088                }
1089                components.push(Punct(c));
1090            } else {
1091                {
    ::core::panicking::panic_fmt(format_args!("unexpected character in a float token: {0:?}",
            c));
}panic!("unexpected character in a float token: {c:?}")
1092            }
1093        }
1094        if !ident_like.is_empty() {
1095            components.push(IdentLike(ident_like));
1096        }
1097
1098        // With proc macros the span can refer to anything, the source may be too short,
1099        // or too long, or non-ASCII. It only makes sense to break our span into components
1100        // if its underlying text is identical to our float literal.
1101        let can_take_span_apart =
1102            || self.span_to_snippet(span).as_deref() == Ok(float_str).as_deref();
1103
1104        match &*components {
1105            // 1e2
1106            [IdentLike(i)] => DestructuredFloat::Single(Symbol::intern(i), span),
1107            // 1.
1108            [IdentLike(left), Punct('.')] => {
1109                let (left_span, dot_span) = if can_take_span_apart() {
1110                    let left_span = span.with_hi(span.lo() + BytePos::from_usize(left.len()));
1111                    let dot_span = span.with_lo(left_span.hi());
1112                    (left_span, dot_span)
1113                } else {
1114                    (span, span)
1115                };
1116                let left = Symbol::intern(left);
1117                DestructuredFloat::TrailingDot(left, left_span, dot_span)
1118            }
1119            // 1.2 | 1.2e3
1120            [IdentLike(left), Punct('.'), IdentLike(right)] => {
1121                let (left_span, dot_span, right_span) = if can_take_span_apart() {
1122                    let left_span = span.with_hi(span.lo() + BytePos::from_usize(left.len()));
1123                    let dot_span =
1124                        span.with_lo(left_span.hi()).with_hi(left_span.hi() + BytePos(1));
1125                    let right_span = span.with_lo(dot_span.hi());
1126                    (left_span, dot_span, right_span)
1127                } else {
1128                    (span, span, span)
1129                };
1130                let left = Symbol::intern(left);
1131                let right = Symbol::intern(right);
1132                DestructuredFloat::MiddleDot(left, left_span, dot_span, right, right_span)
1133            }
1134            // 1e+ | 1e- (recovered)
1135            [IdentLike(_), Punct('+' | '-')] |
1136            // 1e+2 | 1e-2
1137            [IdentLike(_), Punct('+' | '-'), IdentLike(_)] |
1138            // 1.2e+ | 1.2e-
1139            [IdentLike(_), Punct('.'), IdentLike(_), Punct('+' | '-')] |
1140            // 1.2e+3 | 1.2e-3
1141            [IdentLike(_), Punct('.'), IdentLike(_), Punct('+' | '-'), IdentLike(_)] => {
1142                // See the FIXME about `TokenCursor` above.
1143                self.error_unexpected_after_dot();
1144                DestructuredFloat::Error
1145            }
1146            _ => {
    ::core::panicking::panic_fmt(format_args!("unexpected components in a float token: {0:?}",
            components));
}panic!("unexpected components in a float token: {components:?}"),
1147        }
1148    }
1149
1150    /// Parse the field access used in offset_of, matched by `$(e:expr)+`.
1151    /// Currently returns a list of idents. However, it should be possible in
1152    /// future to also do array indices, which might be arbitrary expressions.
1153    pub(crate) fn parse_floating_field_access(&mut self) -> PResult<'a, ThinVec<Ident>> {
1154        let mut fields = ThinVec::new();
1155        let mut trailing_dot = None;
1156
1157        loop {
1158            // This is expected to use a metavariable $(args:expr)+, but the builtin syntax
1159            // could be called directly. Calling `parse_expr` allows this function to only
1160            // consider `Expr`s.
1161            let expr = self.parse_expr()?;
1162            let mut current = &expr;
1163            let start_idx = fields.len();
1164            loop {
1165                match current.kind {
1166                    ExprKind::Field(ref left, right) => {
1167                        // Field access is read right-to-left.
1168                        fields.insert(start_idx, right);
1169                        trailing_dot = None;
1170                        current = left;
1171                    }
1172                    // Parse this both to give helpful error messages and to
1173                    // verify it can be done with this parser setup.
1174                    ExprKind::Index(ref left, ref _right, span) => {
1175                        self.dcx().emit_err(diagnostics::ArrayIndexInOffsetOf(span));
1176                        current = left;
1177                    }
1178                    ExprKind::Lit(token::Lit {
1179                        kind: token::Float | token::Integer,
1180                        symbol,
1181                        suffix,
1182                    }) => {
1183                        if let Some(suffix) = suffix {
1184                            self.dcx().emit_err(diagnostics::InvalidLiteralSuffixOnTupleIndex {
1185                                span: current.span,
1186                                suffix,
1187                            });
1188                        }
1189                        match self.break_up_float(symbol, current.span) {
1190                            // 1e2
1191                            DestructuredFloat::Single(sym, sp) => {
1192                                trailing_dot = None;
1193                                fields.insert(start_idx, Ident::new(sym, sp));
1194                            }
1195                            // 1.
1196                            DestructuredFloat::TrailingDot(sym, sym_span, dot_span) => {
1197                                if !suffix.is_none() {
    ::core::panicking::panic("assertion failed: suffix.is_none()")
};assert!(suffix.is_none());
1198                                trailing_dot = Some(dot_span);
1199                                fields.insert(start_idx, Ident::new(sym, sym_span));
1200                            }
1201                            // 1.2 | 1.2e3
1202                            DestructuredFloat::MiddleDot(
1203                                symbol1,
1204                                span1,
1205                                _dot_span,
1206                                symbol2,
1207                                span2,
1208                            ) => {
1209                                trailing_dot = None;
1210                                fields.insert(start_idx, Ident::new(symbol2, span2));
1211                                fields.insert(start_idx, Ident::new(symbol1, span1));
1212                            }
1213                            DestructuredFloat::Error => {
1214                                trailing_dot = None;
1215                                fields.insert(start_idx, Ident::new(symbol, self.prev_token.span));
1216                            }
1217                        }
1218                        break;
1219                    }
1220                    ExprKind::Path(None, Path { ref segments, .. }) => {
1221                        match &segments[..] {
1222                            [PathSegment { ident, args: None, .. }] => {
1223                                trailing_dot = None;
1224                                fields.insert(start_idx, *ident)
1225                            }
1226                            _ => {
1227                                self.dcx().emit_err(diagnostics::InvalidOffsetOf(current.span));
1228                                break;
1229                            }
1230                        }
1231                        break;
1232                    }
1233                    _ => {
1234                        self.dcx().emit_err(diagnostics::InvalidOffsetOf(current.span));
1235                        break;
1236                    }
1237                }
1238            }
1239
1240            if self.token.kind.close_delim().is_some() || self.token.kind == token::Comma {
1241                break;
1242            } else if trailing_dot.is_none() {
1243                // This loop should only repeat if there is a trailing dot.
1244                self.dcx().emit_err(diagnostics::InvalidOffsetOf(self.token.span));
1245                break;
1246            }
1247        }
1248        if let Some(dot) = trailing_dot {
1249            self.dcx().emit_err(diagnostics::InvalidOffsetOf(dot));
1250        }
1251        Ok(fields.into_iter().collect())
1252    }
1253
1254    fn mk_expr_tuple_field_access(
1255        &self,
1256        lo: Span,
1257        ident_span: Span,
1258        base: Box<Expr>,
1259        field: Symbol,
1260        suffix: Option<Symbol>,
1261    ) -> Box<Expr> {
1262        if let Some(suffix) = suffix {
1263            self.dcx().emit_err(diagnostics::InvalidLiteralSuffixOnTupleIndex {
1264                span: ident_span,
1265                suffix,
1266            });
1267        }
1268        self.mk_expr(lo.to(ident_span), ExprKind::Field(base, Ident::new(field, ident_span)))
1269    }
1270
1271    /// Parse a function call expression, `expr(...)`.
1272    fn parse_expr_fn_call(&mut self, lo: Span, fun: Box<Expr>) -> Box<Expr> {
1273        let snapshot = if self.token == token::OpenParen {
1274            Some((self.create_snapshot_for_diagnostic(), fun.kind.clone()))
1275        } else {
1276            None
1277        };
1278        let open_paren = self.token.span;
1279        let call_depth = self.token_cursor.stack.len();
1280
1281        let seq = match self.parse_expr_paren_seq() {
1282            Ok(args) => Ok(self.mk_expr(lo.to(self.prev_token.span), self.mk_call(fun, args))),
1283            Err(err)
1284                if self.is_expected_raw_ref_mut()
1285                    && self.token_cursor.stack.len() == call_depth =>
1286            {
1287                let guar = err.emit();
1288                // Preserve the call expression so later passes can still diagnose the callee,
1289                // while treating the malformed `&raw <expr>` argument as an error expression.
1290                let args = self.recover_raw_ref_call_args(guar);
1291                return self.mk_expr(lo.to(self.prev_token.span), self.mk_call(fun, args));
1292            }
1293            Err(err) => Err(err),
1294        };
1295        match self.maybe_recover_struct_lit_bad_delims(lo, open_paren, seq, snapshot) {
1296            Ok(expr) => expr,
1297            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),
1298        }
1299    }
1300
1301    fn recover_raw_ref_call_args(&mut self, guar: ErrorGuaranteed) -> ThinVec<Box<Expr>> {
1302        let err_span = self.prev_token.span.to(self.token.span);
1303        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)];
1304        while !self.token.kind.is_close_delim_or_eof() {
1305            if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma)) {
1306                if !self.token.kind.is_close_delim_or_eof() {
1307                    args.push(self.mk_expr_err(self.prev_token.span.shrink_to_hi(), guar));
1308                }
1309            } else {
1310                self.parse_token_tree();
1311            }
1312        }
1313        let _ = self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseParen,
    token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen));
1314        args
1315    }
1316
1317    /// If we encounter a parser state that looks like the user has written a `struct` literal with
1318    /// parentheses instead of braces, recover the parser state and provide suggestions.
1319    #[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(1319u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_parse::parser::expr"),
                                    ::tracing_core::field::FieldSet::new(&["lo", "open_paren"],
                                        ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&lo)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&open_paren)
                                                            as &dyn 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")]
1320    fn maybe_recover_struct_lit_bad_delims(
1321        &mut self,
1322        lo: Span,
1323        open_paren: Span,
1324        seq: PResult<'a, Box<Expr>>,
1325        snapshot: Option<(SnapshotParser<'a>, ExprKind)>,
1326    ) -> PResult<'a, Box<Expr>> {
1327        match (self.may_recover(), seq, snapshot) {
1328            (true, Err(err), Some((mut snapshot, ExprKind::Path(None, path)))) => {
1329                snapshot.bump(); // `(`
1330                match snapshot.parse_struct_fields(path.clone(), false, exp!(CloseParen)) {
1331                    Ok((fields, ..)) if snapshot.eat(exp!(CloseParen)) => {
1332                        // We are certain we have `Enum::Foo(a: 3, b: 4)`, suggest
1333                        // `Enum::Foo { a: 3, b: 4 }` or `Enum::Foo(3, 4)`.
1334                        self.restore_snapshot(snapshot);
1335                        let close_paren = self.prev_token.span;
1336                        let span = lo.to(close_paren);
1337                        // filter shorthand fields
1338                        let fields: Vec<_> =
1339                            fields.into_iter().filter(|field| !field.is_shorthand).collect();
1340
1341                        let guar = if !fields.is_empty() &&
1342                            // `token.kind` should not be compared here.
1343                            // This is because the `snapshot.token.kind` is treated as the same as
1344                            // that of the open delim in `TokenTreesReader::parse_token_tree`, even
1345                            // if they are different.
1346                            self.span_to_snippet(close_paren).is_ok_and(|snippet| snippet == ")")
1347                        {
1348                            err.cancel();
1349                            let type_str = pprust::path_to_string(&path);
1350                            self.dcx()
1351                                .create_err(diagnostics::ParenthesesWithStructFields {
1352                                    span,
1353                                    braces_for_struct: diagnostics::BracesForStructLiteral {
1354                                        first: open_paren,
1355                                        second: close_paren,
1356                                        r#type: type_str.clone(),
1357                                    },
1358                                    no_fields_for_fn: diagnostics::NoFieldsForFnCall {
1359                                        r#type: type_str,
1360                                        fields: fields
1361                                            .into_iter()
1362                                            .map(|field| field.span.until(field.expr.span))
1363                                            .collect(),
1364                                    },
1365                                })
1366                                .emit()
1367                        } else {
1368                            err.emit()
1369                        };
1370                        Ok(self.mk_expr_err(span, guar))
1371                    }
1372                    Ok(_) => Err(err),
1373                    Err(err2) => {
1374                        err2.cancel();
1375                        Err(err)
1376                    }
1377                }
1378            }
1379            (_, seq, _) => seq,
1380        }
1381    }
1382
1383    /// Parse an indexing expression `expr[...]`.
1384    fn parse_expr_index(&mut self, lo: Span, base: Box<Expr>) -> PResult<'a, Box<Expr>> {
1385        let prev_span = self.prev_token.span;
1386        let open_delim_span = self.token.span;
1387        self.bump(); // `[`
1388        let index = self.parse_expr()?;
1389        self.suggest_missing_semicolon_before_array(prev_span, open_delim_span)?;
1390        self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseBracket,
    token_type: crate::parser::token_type::TokenType::CloseBracket,
}exp!(CloseBracket))?;
1391        Ok(self.mk_expr(
1392            lo.to(self.prev_token.span),
1393            self.mk_index(base, index, open_delim_span.to(self.prev_token.span)),
1394        ))
1395    }
1396
1397    /// Assuming we have just parsed `.`, continue parsing into an expression.
1398    fn parse_dot_suffix(&mut self, self_arg: Box<Expr>, lo: Span) -> PResult<'a, Box<Expr>> {
1399        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)) {
1400            return Ok(self.mk_await_expr(self_arg, lo));
1401        }
1402
1403        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)) {
1404            let use_span = self.prev_token.span;
1405            self.psess.gated_spans.gate(sym::ergonomic_clones, use_span);
1406            return Ok(self.mk_use_expr(self_arg, lo));
1407        }
1408
1409        // Post-fix match
1410        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)) {
1411            let match_span = self.prev_token.span;
1412            self.psess.gated_spans.gate(sym::postfix_match, match_span);
1413            return self.parse_match_block(lo, match_span, self_arg, MatchKind::Postfix);
1414        }
1415
1416        // Parse a postfix `yield`.
1417        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)) {
1418            let yield_span = self.prev_token.span;
1419            self.psess.gated_spans.gate(sym::yield_expr, yield_span);
1420            return Ok(
1421                self.mk_expr(lo.to(yield_span), ExprKind::Yield(YieldKind::Postfix(self_arg)))
1422            );
1423        }
1424
1425        let fn_span_lo = self.token.span;
1426        let mut seg = self.parse_path_segment(PathStyle::Expr, None)?;
1427        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)]);
1428        self.check_turbofish_missing_angle_brackets(&mut seg);
1429
1430        if self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenParen,
    token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen)) {
1431            // Method call `expr.f()`
1432            let args = self.parse_expr_paren_seq()?;
1433            let fn_span = fn_span_lo.to(self.prev_token.span);
1434            let span = lo.to(self.prev_token.span);
1435            Ok(self.mk_expr(
1436                span,
1437                ExprKind::MethodCall(Box::new(ast::MethodCall {
1438                    seg,
1439                    receiver: self_arg,
1440                    args,
1441                    span: fn_span,
1442                })),
1443            ))
1444        } else {
1445            // Field access `expr.f`
1446            let span = lo.to(self.prev_token.span);
1447            if let Some(args) = seg.args {
1448                // See `StashKey::GenericInFieldExpr` for more info on why we stash this.
1449                self.dcx()
1450                    .create_err(diagnostics::FieldExpressionWithGeneric(args.span()))
1451                    .stash(seg.ident.span, StashKey::GenericInFieldExpr);
1452            }
1453
1454            Ok(self.mk_expr(span, ExprKind::Field(self_arg, seg.ident)))
1455        }
1456    }
1457
1458    /// At the bottom (top?) of the precedence hierarchy,
1459    /// Parses things like parenthesized exprs, macros, `return`, etc.
1460    ///
1461    /// N.B., this does not parse outer attributes, and is private because it only works
1462    /// correctly if called from `parse_expr_dot_or_call`.
1463    fn parse_expr_bottom(&mut self) -> PResult<'a, Box<Expr>> {
1464        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);
1465
1466        let span = self.token.span;
1467        if let Some(expr) = self.eat_metavar_seq_with_matcher(
1468            |mv_kind| #[allow(non_exhaustive_omitted_patterns)] match mv_kind {
    MetaVarKind::Expr { .. } => true,
    _ => false,
}matches!(mv_kind, MetaVarKind::Expr { .. }),
1469            |this| {
1470                // Force collection (as opposed to just `parse_expr`) is required to avoid the
1471                // attribute duplication seen in #138478.
1472                let expr = this.parse_expr_force_collect();
1473                // FIXME(nnethercote) Sometimes with expressions we get a trailing comma, possibly
1474                // related to the FIXME in `collect_tokens_for_expr`. Examples are the multi-line
1475                // `assert_eq!` calls involving arguments annotated with `#[rustfmt::skip]` in
1476                // `compiler/rustc_index/src/bit_set/tests.rs`.
1477                if this.token.kind == token::Comma {
1478                    this.bump();
1479                }
1480                expr
1481            },
1482        ) {
1483            return Ok(expr);
1484        } else if let Some(lit) =
1485            self.eat_metavar_seq(MetaVarKind::Literal, |this| this.parse_literal_maybe_minus())
1486        {
1487            return Ok(lit);
1488        } else if let Some(block) =
1489            self.eat_metavar_seq(MetaVarKind::Block, |this| this.parse_block())
1490        {
1491            return Ok(self.mk_expr(span, ExprKind::Block(block, None)));
1492        } else if let Some(path) =
1493            self.eat_metavar_seq(MetaVarKind::Path, |this| this.parse_path(PathStyle::Type))
1494        {
1495            return Ok(self.mk_expr(span, ExprKind::Path(None, path)));
1496        }
1497
1498        // Outer attributes are already parsed and will be
1499        // added to the return value after the fact.
1500
1501        let restrictions = self.restrictions;
1502        self.with_res(restrictions - Restrictions::ALLOW_LET, |this| {
1503            // Note: adding new syntax here? Don't forget to adjust `TokenKind::can_begin_expr()`.
1504            let lo = this.token.span;
1505            if let token::Literal(_) = this.token.kind {
1506                // This match arm is a special-case of the `_` match arm below and
1507                // could be removed without changing functionality, but it's faster
1508                // to have it here, especially for programs with large constants.
1509                this.parse_expr_lit()
1510            } else if this.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenParen,
    token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen)) {
1511                this.parse_expr_tuple_parens(restrictions)
1512            } else if this.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenBrace,
    token_type: crate::parser::token_type::TokenType::OpenBrace,
}exp!(OpenBrace)) {
1513                if let Some(expr) = this.maybe_recover_bad_struct_literal_path(false)? {
1514                    return Ok(expr);
1515                }
1516                this.parse_expr_block(None, lo, BlockCheckMode::Default)
1517            } 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)) {
1518                this.parse_expr_closure().map_err(|mut err| {
1519                    // If the input is something like `if a { 1 } else { 2 } | if a { 3 } else { 4 }`
1520                    // then suggest parens around the lhs.
1521                    if let Some(sp) = this.psess.ambiguous_block_expr_parse.borrow().get(&lo) {
1522                        err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp));
1523                    }
1524                    err
1525                })
1526            } else if this.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenBracket,
    token_type: crate::parser::token_type::TokenType::OpenBracket,
}exp!(OpenBracket)) {
1527                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))
1528            } else if this.is_builtin() {
1529                this.parse_expr_builtin()
1530            } else if this.check_path() {
1531                this.parse_expr_path_start()
1532            } 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))
1533                || this.check_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Use,
    token_type: crate::parser::token_type::TokenType::KwUse,
}exp!(Use))
1534                || this.check_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Static,
    token_type: crate::parser::token_type::TokenType::KwStatic,
}exp!(Static))
1535                || this.check_const_closure()
1536            {
1537                this.parse_expr_closure()
1538            } 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)) {
1539                this.parse_expr_if()
1540            } 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)) {
1541                if this.choose_generics_over_qpath(1) {
1542                    this.parse_expr_closure()
1543                } else {
1544                    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)));
1545                    this.parse_expr_for(None, lo)
1546                }
1547            } 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)) {
1548                this.parse_expr_while(None, lo)
1549            } else if let Some(label) = this.eat_label() {
1550                this.parse_expr_labeled(label, true)
1551            } 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)) {
1552                this.parse_expr_loop(None, lo).map_err(|mut err| {
1553                    err.span_label(lo, "while parsing this `loop` expression");
1554                    err
1555                })
1556            } 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)) {
1557                this.parse_expr_match().map_err(|mut err| {
1558                    err.span_label(lo, "while parsing this `match` expression");
1559                    err
1560                })
1561            } 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)) {
1562                this.parse_expr_block(None, lo, BlockCheckMode::Unsafe(ast::UserProvided)).map_err(
1563                    |mut err| {
1564                        err.span_label(lo, "while parsing this `unsafe` expression");
1565                        err
1566                    },
1567                )
1568            } else if this.check_inline_const(0) {
1569                this.parse_const_block(lo, false)
1570            } else if this.may_recover() && this.is_do_catch_block() {
1571                this.recover_do_catch()
1572            } else if this.is_try_block() {
1573                this.expect_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Try,
    token_type: crate::parser::token_type::TokenType::KwTry,
}exp!(Try))?;
1574                this.parse_try_block(lo)
1575            } 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)) {
1576                this.parse_expr_return()
1577            } 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)) {
1578                this.parse_expr_continue(lo)
1579            } 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)) {
1580                this.parse_expr_break()
1581            } 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)) {
1582                this.parse_expr_yield()
1583            } else if this.is_do_yeet() {
1584                this.parse_expr_yeet()
1585            } 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)) {
1586                this.parse_expr_become()
1587            } 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)) {
1588                this.parse_expr_let(restrictions)
1589            } 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)) {
1590                if let Some(expr) = this.maybe_recover_bad_struct_literal_path(true)? {
1591                    return Ok(expr);
1592                }
1593                Ok(this.mk_expr(this.prev_token.span, ExprKind::Underscore))
1594            } else if this.token_uninterpolated_span().at_least_rust_2018() {
1595                // `Span::at_least_rust_2018()` is somewhat expensive; don't get it repeatedly.
1596                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));
1597                // check for `gen {}` and `gen move {}`
1598                // or `async gen {}` and `async gen move {}`
1599                // FIXME: (async) gen closures aren't yet parsed.
1600                // FIXME(gen_blocks): Parse `gen async` and suggest swap
1601                if this.token_uninterpolated_span().at_least_rust_2024()
1602                    && this.is_gen_block(kw::Gen, at_async as usize)
1603                {
1604                    this.parse_gen_block()
1605                // Check for `async {` and `async move {`,
1606                } else if this.is_gen_block(kw::Async, 0) {
1607                    this.parse_gen_block()
1608                } else if at_async {
1609                    this.parse_expr_closure()
1610                } else if this.eat_keyword_noexpect(kw::Await) {
1611                    this.recover_incorrect_await_syntax(lo)
1612                } else {
1613                    this.parse_expr_lit()
1614                }
1615            } else {
1616                this.parse_expr_lit()
1617            }
1618        })
1619    }
1620
1621    fn parse_expr_lit(&mut self) -> PResult<'a, Box<Expr>> {
1622        let lo = self.token.span;
1623        match self.parse_opt_token_lit() {
1624            Some((token_lit, _)) => {
1625                let expr = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Lit(token_lit));
1626                self.maybe_recover_from_bad_qpath(expr)
1627            }
1628            None => self.try_macro_suggestion(),
1629        }
1630    }
1631
1632    fn parse_expr_tuple_parens(&mut self, restrictions: Restrictions) -> PResult<'a, Box<Expr>> {
1633        let lo = self.token.span;
1634        self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenParen,
    token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen))?;
1635        let (es, trailing_comma) = match self.parse_seq_to_end(
1636            crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseParen,
    token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen),
1637            SeqSep::trailing_allowed(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma)),
1638            |p| p.parse_expr_catch_underscore(restrictions.intersection(Restrictions::ALLOW_LET)),
1639        ) {
1640            Ok(x) => x,
1641            Err(err) => {
1642                return Ok(self.recover_seq_parse_error(
1643                    crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenParen,
    token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen),
1644                    crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseParen,
    token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen),
1645                    lo,
1646                    err,
1647                ));
1648            }
1649        };
1650        let kind = if es.len() == 1 && #[allow(non_exhaustive_omitted_patterns)] match trailing_comma {
    Trailing::No => true,
    _ => false,
}matches!(trailing_comma, Trailing::No) {
1651            // `(e)` is parenthesized `e`.
1652            ExprKind::Paren(es.into_iter().next().unwrap())
1653        } else {
1654            // `(e,)` is a tuple with only one field, `e`.
1655            ExprKind::Tup(es)
1656        };
1657        let expr = self.mk_expr(lo.to(self.prev_token.span), kind);
1658        self.maybe_recover_from_bad_qpath(expr)
1659    }
1660
1661    fn parse_expr_array_or_repeat(&mut self, close: ExpTokenPair) -> PResult<'a, Box<Expr>> {
1662        let lo = self.token.span;
1663        self.bump(); // `[` or other open delim
1664
1665        let kind = if self.eat(close) {
1666            // Empty vector
1667            ExprKind::Array(ThinVec::new())
1668        } else {
1669            // Non-empty vector
1670            let first_expr = self.parse_expr()?;
1671            if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Semi,
    token_type: crate::parser::token_type::TokenType::Semi,
}exp!(Semi)) {
1672                // Repeating array syntax: `[ 0; 512 ]`
1673                let count = self.parse_expr_anon_const()?;
1674                self.expect(close)?;
1675                ExprKind::Repeat(first_expr, count)
1676            } else if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma)) {
1677                // Vector with two or more elements.
1678                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));
1679                let (mut exprs, _) = self.parse_seq_to_end(close, sep, |p| p.parse_expr())?;
1680                exprs.insert(0, first_expr);
1681                ExprKind::Array(exprs)
1682            } else {
1683                // Vector with one element
1684                self.expect(close)?;
1685                ExprKind::Array({
    let len = [()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(first_expr);
    vec
}thin_vec![first_expr])
1686            }
1687        };
1688        let expr = self.mk_expr(lo.to(self.prev_token.span), kind);
1689        self.maybe_recover_from_bad_qpath(expr)
1690    }
1691
1692    fn parse_expr_path_start(&mut self) -> PResult<'a, Box<Expr>> {
1693        let maybe_eq_tok = self.prev_token;
1694        let (qself, path) = if self.eat_lt() {
1695            let lt_span = self.prev_token.span;
1696            let (qself, path) = self.parse_qpath(PathStyle::Expr).map_err(|mut err| {
1697                // Suggests using '<=' if there is an error parsing qpath when the previous token
1698                // is an '=' token. Only emits suggestion if the '<' token and '=' token are
1699                // directly adjacent (i.e. '=<')
1700                if maybe_eq_tok == TokenKind::Eq && maybe_eq_tok.span.hi() == lt_span.lo() {
1701                    let eq_lt = maybe_eq_tok.span.to(lt_span);
1702                    err.span_suggestion(eq_lt, "did you mean", "<=", Applicability::Unspecified);
1703                }
1704                err
1705            })?;
1706            (Some(qself), path)
1707        } else {
1708            (None, self.parse_path(PathStyle::Expr)?)
1709        };
1710
1711        // `!`, as an operator, is prefix, so we know this isn't that.
1712        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)) {
1713            // MACRO INVOCATION expression
1714            if qself.is_some() {
1715                self.dcx().emit_err(diagnostics::MacroInvocationWithQualifiedPath(path.span));
1716            }
1717            let lo = path.span;
1718            let mac = Box::new(MacCall { path, args: self.parse_delim_args()? });
1719            (lo.to(self.prev_token.span), ExprKind::MacCall(mac))
1720        } else if self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenBrace,
    token_type: crate::parser::token_type::TokenType::OpenBrace,
}exp!(OpenBrace))
1721            && let Some(expr) = self.maybe_parse_struct_expr(&qself, &path)
1722        {
1723            if qself.is_some() {
1724                self.psess.gated_spans.gate(sym::more_qualified_paths, path.span);
1725            }
1726            return expr;
1727        } else {
1728            (path.span, ExprKind::Path(qself, path))
1729        };
1730
1731        let expr = self.mk_expr(span, kind);
1732        self.maybe_recover_from_bad_qpath(expr)
1733    }
1734
1735    /// Parse `'label: $expr`. The label is already parsed.
1736    pub(super) fn parse_expr_labeled(
1737        &mut self,
1738        label_: Label,
1739        mut consume_colon: bool,
1740    ) -> PResult<'a, Box<Expr>> {
1741        let lo = label_.ident.span;
1742        let label = Some(label_);
1743        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));
1744        let tok_sp = self.token.span;
1745        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)) {
1746            self.parse_expr_while(label, lo)
1747        } 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)) {
1748            self.parse_expr_for(label, lo)
1749        } 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)) {
1750            self.parse_expr_loop(label, lo)
1751        } else if self.check_noexpect(&token::OpenBrace) || self.token.is_metavar_block() {
1752            self.parse_expr_block(label, lo, BlockCheckMode::Default)
1753        } else if !ate_colon
1754            && self.may_recover()
1755            && (self.token.kind.close_delim().is_some() || self.token.is_punct())
1756            && could_be_unclosed_char_literal(label_.ident)
1757        {
1758            let (lit, _) =
1759                self.recover_unclosed_char(label_.ident, Parser::mk_token_lit_char, |self_| {
1760                    self_.dcx().create_err(diagnostics::UnexpectedTokenAfterLabel {
1761                        span: self_.token.span,
1762                        remove_label: None,
1763                        enclose_in_block: None,
1764                    })
1765                });
1766            consume_colon = false;
1767            Ok(self.mk_expr(lo, ExprKind::Lit(lit)))
1768        } else if !ate_colon
1769            && (self.check_noexpect(&TokenKind::Comma) || self.check_noexpect(&TokenKind::Gt))
1770        {
1771            // We're probably inside of a `Path<'a>` that needs a turbofish
1772            let guar = self.dcx().emit_err(diagnostics::UnexpectedTokenAfterLabel {
1773                span: self.token.span,
1774                remove_label: None,
1775                enclose_in_block: None,
1776            });
1777            consume_colon = false;
1778            Ok(self.mk_expr_err(lo, guar))
1779        } else {
1780            let mut err = diagnostics::UnexpectedTokenAfterLabel {
1781                span: self.token.span,
1782                remove_label: None,
1783                enclose_in_block: None,
1784            };
1785
1786            // Continue as an expression in an effort to recover on `'label: non_block_expr`.
1787            let expr = self.parse_expr().map(|expr| {
1788                let span = expr.span;
1789
1790                let found_labeled_breaks = {
1791                    struct FindLabeledBreaksVisitor;
1792
1793                    impl<'ast> Visitor<'ast> for FindLabeledBreaksVisitor {
1794                        type Result = ControlFlow<()>;
1795                        fn visit_expr(&mut self, ex: &'ast Expr) -> ControlFlow<()> {
1796                            if let ExprKind::Break(Some(_label), _) = ex.kind {
1797                                ControlFlow::Break(())
1798                            } else {
1799                                walk_expr(self, ex)
1800                            }
1801                        }
1802                    }
1803
1804                    FindLabeledBreaksVisitor.visit_expr(&expr).is_break()
1805                };
1806
1807                // Suggestion involves adding a labeled block.
1808                //
1809                // If there are no breaks that may use this label, suggest removing the label and
1810                // recover to the unmodified expression.
1811                if !found_labeled_breaks {
1812                    err.remove_label = Some(lo.until(span));
1813
1814                    return expr;
1815                }
1816
1817                err.enclose_in_block = Some(diagnostics::UnexpectedTokenAfterLabelSugg {
1818                    left: span.shrink_to_lo(),
1819                    right: span.shrink_to_hi(),
1820                });
1821
1822                // Replace `'label: non_block_expr` with `'label: {non_block_expr}` in order to suppress future errors about `break 'label`.
1823                let stmt = self.mk_stmt(span, StmtKind::Expr(expr));
1824                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);
1825                self.mk_expr(span, ExprKind::Block(blk, label))
1826            });
1827
1828            self.dcx().emit_err(err);
1829            expr
1830        }?;
1831
1832        if !ate_colon && consume_colon {
1833            self.dcx().emit_err(diagnostics::RequireColonAfterLabeledExpression {
1834                span: expr.span,
1835                label: lo,
1836                label_end: lo.between(tok_sp),
1837            });
1838        }
1839
1840        Ok(expr)
1841    }
1842
1843    /// Emit an error when a char is parsed as a lifetime or label because of a missing quote.
1844    pub(super) fn recover_unclosed_char<L>(
1845        &self,
1846        ident: Ident,
1847        mk_lit_char: impl FnOnce(Symbol, Span) -> L,
1848        err: impl FnOnce(&Self) -> Diag<'a>,
1849    ) -> L {
1850        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));
1851        self.dcx()
1852            .try_steal_modify_and_emit_err(ident.span, StashKey::LifetimeIsChar, |err| {
1853                err.span_suggestion_verbose(
1854                    ident.span.shrink_to_hi(),
1855                    "add `'` to close the char literal",
1856                    "'",
1857                    Applicability::MaybeIncorrect,
1858                );
1859            })
1860            .unwrap_or_else(|| {
1861                err(self)
1862                    .with_span_suggestion_verbose(
1863                        ident.span.shrink_to_hi(),
1864                        "add `'` to close the char literal",
1865                        "'",
1866                        Applicability::MaybeIncorrect,
1867                    )
1868                    .emit()
1869            });
1870        let name = ident.without_first_quote().name;
1871        mk_lit_char(name, ident.span)
1872    }
1873
1874    /// Recover on the syntax `do catch { ... }` suggesting `try { ... }` instead.
1875    fn recover_do_catch(&mut self) -> PResult<'a, Box<Expr>> {
1876        let lo = self.token.span;
1877
1878        self.bump(); // `do`
1879        self.bump(); // `catch`
1880
1881        let span = lo.to(self.prev_token.span);
1882        self.dcx().emit_err(diagnostics::DoCatchSyntaxRemoved { span });
1883
1884        self.parse_try_block(lo)
1885    }
1886
1887    /// Parse an expression if the token can begin one.
1888    fn parse_expr_opt(&mut self) -> PResult<'a, Option<Box<Expr>>> {
1889        Ok(if self.token.can_begin_expr() { Some(self.parse_expr()?) } else { None })
1890    }
1891
1892    /// Parse `"return" expr?`.
1893    fn parse_expr_return(&mut self) -> PResult<'a, Box<Expr>> {
1894        let lo = self.prev_token.span;
1895        let kind = ExprKind::Ret(self.parse_expr_opt()?);
1896        let expr = self.mk_expr(lo.to(self.prev_token.span), kind);
1897        self.maybe_recover_from_bad_qpath(expr)
1898    }
1899
1900    /// Parse `"do" "yeet" expr?`.
1901    fn parse_expr_yeet(&mut self) -> PResult<'a, Box<Expr>> {
1902        let lo = self.token.span;
1903
1904        self.bump(); // `do`
1905        self.bump(); // `yeet`
1906
1907        let kind = ExprKind::Yeet(self.parse_expr_opt()?);
1908
1909        let span = lo.to(self.prev_token.span);
1910        self.psess.gated_spans.gate(sym::yeet_expr, span);
1911        let expr = self.mk_expr(span, kind);
1912        self.maybe_recover_from_bad_qpath(expr)
1913    }
1914
1915    /// Parse `"become" expr`, with `"become"` token already eaten.
1916    fn parse_expr_become(&mut self) -> PResult<'a, Box<Expr>> {
1917        let lo = self.prev_token.span;
1918        let kind = ExprKind::Become(self.parse_expr()?);
1919        let span = lo.to(self.prev_token.span);
1920        self.psess.gated_spans.gate(sym::explicit_tail_calls, span);
1921        let expr = self.mk_expr(span, kind);
1922        self.maybe_recover_from_bad_qpath(expr)
1923    }
1924
1925    /// Parse `"break" (('label (:? expr)?) | expr?)` with `"break"` token already eaten.
1926    /// If the label is followed immediately by a `:` token, the label and `:` are
1927    /// parsed as part of the expression (i.e. a labeled loop). The language team has
1928    /// decided in #87026 to require parentheses as a visual aid to avoid confusion if
1929    /// the break expression of an unlabeled break is a labeled loop (as in
1930    /// `break 'lbl: loop {}`); a labeled break with an unlabeled loop as its value
1931    /// expression only gets a warning for compatibility reasons; and a labeled break
1932    /// with a labeled loop does not even get a warning because there is no ambiguity.
1933    fn parse_expr_break(&mut self) -> PResult<'a, Box<Expr>> {
1934        let lo = self.prev_token.span;
1935        let mut label = self.eat_label();
1936        let kind = if self.token == token::Colon
1937            && let Some(label) = label.take()
1938        {
1939            // The value expression can be a labeled loop, see issue #86948, e.g.:
1940            // `loop { break 'label: loop { break 'label 42; }; }`
1941            let lexpr = self.parse_expr_labeled(label, true)?;
1942            self.dcx().emit_err(diagnostics::LabeledLoopInBreak {
1943                span: lexpr.span,
1944                sub: diagnostics::WrapInParentheses::Expression {
1945                    left: lexpr.span.shrink_to_lo(),
1946                    right: lexpr.span.shrink_to_hi(),
1947                },
1948            });
1949            Some(lexpr)
1950        } else if self.token != token::OpenBrace
1951            || !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
1952        {
1953            let mut expr = self.parse_expr_opt()?;
1954            if let Some(expr) = &mut expr {
1955                if label.is_some()
1956                    && match &expr.kind {
1957                        ExprKind::While(_, _, None)
1958                        | ExprKind::ForLoop { label: None, .. }
1959                        | ExprKind::Loop(_, None, _) => true,
1960                        ExprKind::Block(block, None) => {
1961                            #[allow(non_exhaustive_omitted_patterns)] match block.rules {
    BlockCheckMode::Default => true,
    _ => false,
}matches!(block.rules, BlockCheckMode::Default)
1962                        }
1963                        _ => false,
1964                    }
1965                {
1966                    let span = expr.span;
1967                    self.psess.buffer_lint(
1968                        BREAK_WITH_LABEL_AND_LOOP,
1969                        lo.to(expr.span),
1970                        ast::CRATE_NODE_ID,
1971                        diagnostics::BreakWithLabelAndLoop {
1972                            sub: diagnostics::BreakWithLabelAndLoopSub {
1973                                left: span.shrink_to_lo(),
1974                                right: span.shrink_to_hi(),
1975                            },
1976                        },
1977                    );
1978                }
1979
1980                // Recover `break label aaaaa`
1981                if self.may_recover()
1982                    && let ExprKind::Path(None, p) = &expr.kind
1983                    && let [segment] = &*p.segments
1984                    && let &ast::PathSegment { ident, args: None, .. } = segment
1985                    && let Some(next) = self.parse_expr_opt()?
1986                {
1987                    label = Some(self.recover_ident_into_label(ident));
1988                    *expr = next;
1989                }
1990            }
1991
1992            expr
1993        } else {
1994            None
1995        };
1996        let expr = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Break(label, kind));
1997        self.maybe_recover_from_bad_qpath(expr)
1998    }
1999
2000    /// Parse `"continue" label?`.
2001    fn parse_expr_continue(&mut self, lo: Span) -> PResult<'a, Box<Expr>> {
2002        let mut label = self.eat_label();
2003
2004        // Recover `continue label` -> `continue 'label`
2005        if self.may_recover()
2006            && label.is_none()
2007            && let Some((ident, _)) = self.token.ident()
2008        {
2009            self.bump();
2010            label = Some(self.recover_ident_into_label(ident));
2011        }
2012
2013        let kind = ExprKind::Continue(label);
2014        Ok(self.mk_expr(lo.to(self.prev_token.span), kind))
2015    }
2016
2017    /// Parse `"yield" expr?`.
2018    fn parse_expr_yield(&mut self) -> PResult<'a, Box<Expr>> {
2019        let lo = self.prev_token.span;
2020        let kind = ExprKind::Yield(YieldKind::Prefix(self.parse_expr_opt()?));
2021        let span = lo.to(self.prev_token.span);
2022        self.psess.gated_spans.gate(sym::yield_expr, span);
2023        let expr = self.mk_expr(span, kind);
2024        self.maybe_recover_from_bad_qpath(expr)
2025    }
2026
2027    /// Parse `builtin # ident(args,*)`.
2028    fn parse_expr_builtin(&mut self) -> PResult<'a, Box<Expr>> {
2029        self.parse_builtin(|this, lo, ident| {
2030            Ok(match ident.name {
2031                sym::offset_of => Some(this.parse_expr_offset_of(lo)?),
2032                sym::type_ascribe => Some(this.parse_expr_type_ascribe(lo)?),
2033                sym::wrap_binder => {
2034                    Some(this.parse_expr_unsafe_binder_cast(lo, UnsafeBinderCastKind::Wrap)?)
2035                }
2036                sym::unwrap_binder => {
2037                    Some(this.parse_expr_unsafe_binder_cast(lo, UnsafeBinderCastKind::Unwrap)?)
2038                }
2039                _ => None,
2040            })
2041        })
2042    }
2043
2044    pub(crate) fn parse_builtin<T>(
2045        &mut self,
2046        parse: impl FnOnce(&mut Parser<'a>, Span, Ident) -> PResult<'a, Option<T>>,
2047    ) -> PResult<'a, T> {
2048        let lo = self.token.span;
2049
2050        self.bump(); // `builtin`
2051        self.bump(); // `#`
2052
2053        let Some((ident, IdentIsRaw::No)) = self.token.ident() else {
2054            let err =
2055                self.dcx().create_err(diagnostics::ExpectedBuiltinIdent { span: self.token.span });
2056            return Err(err);
2057        };
2058        self.psess.gated_spans.gate(sym::builtin_syntax, ident.span);
2059        self.bump();
2060
2061        self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenParen,
    token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen))?;
2062        let ret = if let Some(res) = parse(self, lo, ident)? {
2063            Ok(res)
2064        } else {
2065            let err = self.dcx().create_err(diagnostics::UnknownBuiltinConstruct {
2066                span: lo.to(ident.span),
2067                name: ident,
2068            });
2069            return Err(err);
2070        };
2071        self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseParen,
    token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen))?;
2072
2073        ret
2074    }
2075
2076    /// Built-in macro for `offset_of!` expressions.
2077    pub(crate) fn parse_expr_offset_of(&mut self, lo: Span) -> PResult<'a, Box<Expr>> {
2078        let container = self.parse_ty()?;
2079        self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma))?;
2080
2081        let fields = self.parse_floating_field_access()?;
2082        let trailing_comma = self.eat_noexpect(&TokenKind::Comma);
2083
2084        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)]) {
2085            if trailing_comma {
2086                e.note("unexpected third argument to offset_of");
2087            } else {
2088                e.note("offset_of expects dot-separated field and variant names");
2089            }
2090            e.emit();
2091        }
2092
2093        // Eat tokens until the macro call ends.
2094        if self.may_recover() {
2095            while !self.token.kind.is_close_delim_or_eof() {
2096                self.bump();
2097            }
2098        }
2099
2100        let span = lo.to(self.token.span);
2101        Ok(self.mk_expr(span, ExprKind::OffsetOf(container, fields)))
2102    }
2103
2104    /// Built-in macro for type ascription expressions.
2105    pub(crate) fn parse_expr_type_ascribe(&mut self, lo: Span) -> PResult<'a, Box<Expr>> {
2106        let expr = self.parse_expr()?;
2107        self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma))?;
2108        let ty = self.parse_ty()?;
2109        let span = lo.to(self.token.span);
2110        Ok(self.mk_expr(span, ExprKind::Type(expr, ty)))
2111    }
2112
2113    pub(crate) fn parse_expr_unsafe_binder_cast(
2114        &mut self,
2115        lo: Span,
2116        kind: UnsafeBinderCastKind,
2117    ) -> PResult<'a, Box<Expr>> {
2118        let expr = self.parse_expr()?;
2119        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 };
2120        let span = lo.to(self.token.span);
2121        Ok(self.mk_expr(span, ExprKind::UnsafeBinderCast(kind, expr, ty)))
2122    }
2123
2124    /// Returns a string literal if the next token is a string literal.
2125    /// In case of error returns `Some(lit)` if the next token is a literal with a wrong kind,
2126    /// and returns `None` if the next token is not literal at all.
2127    pub fn parse_str_lit(&mut self) -> Result<ast::StrLit, Option<MetaItemLit>> {
2128        match self.parse_opt_meta_item_lit() {
2129            Some(lit) => match lit.kind {
2130                ast::LitKind::Str(symbol_unescaped, style) => Ok(ast::StrLit {
2131                    style,
2132                    symbol: lit.symbol,
2133                    suffix: lit.suffix,
2134                    span: lit.span,
2135                    symbol_unescaped,
2136                }),
2137                _ => Err(Some(lit)),
2138            },
2139            None => Err(None),
2140        }
2141    }
2142
2143    pub(crate) fn mk_token_lit_char(name: Symbol, span: Span) -> (token::Lit, Span) {
2144        (token::Lit { symbol: name, suffix: None, kind: token::Char }, span)
2145    }
2146
2147    fn mk_meta_item_lit_char(name: Symbol, span: Span) -> MetaItemLit {
2148        ast::MetaItemLit {
2149            symbol: name,
2150            suffix: None,
2151            kind: ast::LitKind::Char(name.as_str().chars().next().unwrap_or('_')),
2152            span,
2153        }
2154    }
2155
2156    fn handle_missing_lit<L>(
2157        &mut self,
2158        mk_lit_char: impl FnOnce(Symbol, Span) -> L,
2159    ) -> PResult<'a, L> {
2160        let token = self.token;
2161        let err = |self_: &Self| {
2162            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));
2163            self_.dcx().struct_span_err(token.span, msg)
2164        };
2165        // On an error path, eagerly consider a lifetime to be an unclosed character lit, if that
2166        // makes sense.
2167        if let Some((ident, IdentIsRaw::No)) = self.token.lifetime()
2168            && could_be_unclosed_char_literal(ident)
2169        {
2170            let lt = self.expect_lifetime();
2171            Ok(self.recover_unclosed_char(lt.ident, mk_lit_char, err))
2172        } else {
2173            Err(err(self))
2174        }
2175    }
2176
2177    pub(super) fn parse_token_lit(&mut self) -> PResult<'a, (token::Lit, Span)> {
2178        self.parse_opt_token_lit()
2179            .ok_or(())
2180            .or_else(|()| self.handle_missing_lit(Parser::mk_token_lit_char))
2181    }
2182
2183    pub(super) fn parse_meta_item_lit(&mut self) -> PResult<'a, MetaItemLit> {
2184        self.parse_opt_meta_item_lit()
2185            .ok_or(())
2186            .or_else(|()| self.handle_missing_lit(Parser::mk_meta_item_lit_char))
2187    }
2188
2189    fn recover_after_dot(&mut self) {
2190        if self.token == token::Dot {
2191            // Attempt to recover `.4` as `0.4`. We don't currently have any syntax where
2192            // dot would follow an optional literal, so we do this unconditionally.
2193            let recovered = self.look_ahead(1, |next_token| {
2194                // If it's an integer that looks like a float, then recover as such.
2195                //
2196                // We will never encounter the exponent part of a floating
2197                // point literal here, since there's no use of the exponent
2198                // syntax that also constitutes a valid integer, so we need
2199                // not check for that.
2200                if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) =
2201                    next_token.kind
2202                    && suffix.is_none_or(|s| s == sym::f32 || s == sym::f64)
2203                    && symbol.as_str().chars().all(|c| c.is_numeric() || c == '_')
2204                    && self.token.span.hi() == next_token.span.lo()
2205                {
2206                    let s = String::from("0.") + symbol.as_str();
2207                    let kind = TokenKind::lit(token::Float, Symbol::intern(&s), suffix);
2208                    Some(Token::new(kind, self.token.span.to(next_token.span)))
2209                } else {
2210                    None
2211                }
2212            });
2213            if let Some(recovered) = recovered {
2214                self.dcx().emit_err(diagnostics::FloatLiteralRequiresIntegerPart {
2215                    span: recovered.span,
2216                    suggestion: recovered.span.shrink_to_lo(),
2217                });
2218                self.bump();
2219                self.token = recovered;
2220            }
2221        }
2222    }
2223
2224    /// Keep this in sync with `Token::can_begin_literal_maybe_minus` and
2225    /// `Lit::from_token` (excluding unary negation).
2226    pub fn eat_token_lit(&mut self) -> Option<token::Lit> {
2227        let check_expr = |expr: Box<Expr>| {
2228            if let ast::ExprKind::Lit(token_lit) = expr.kind {
2229                Some(token_lit)
2230            } else if let ast::ExprKind::Unary(UnOp::Neg, inner) = &expr.kind
2231                && let ast::Expr { kind: ast::ExprKind::Lit(_), .. } = **inner
2232            {
2233                None
2234            } else {
2235                {
    ::core::panicking::panic_fmt(format_args!("unexpected reparsed expr/literal: {0:?}",
            expr.kind));
};panic!("unexpected reparsed expr/literal: {:?}", expr.kind);
2236            }
2237        };
2238        match self.token.uninterpolate().kind {
2239            token::Ident(name, IdentIsRaw::No) if name.is_bool_lit() => {
2240                self.bump();
2241                Some(token::Lit::new(token::Bool, name, None))
2242            }
2243            token::Literal(token_lit) => {
2244                self.bump();
2245                Some(token_lit)
2246            }
2247            token::OpenInvisible(InvisibleOrigin::MetaVar(MetaVarKind::Literal)) => {
2248                let lit = self
2249                    .eat_metavar_seq(MetaVarKind::Literal, |this| this.parse_literal_maybe_minus())
2250                    .expect("metavar seq literal");
2251                check_expr(lit)
2252            }
2253            token::OpenInvisible(InvisibleOrigin::MetaVar(
2254                mv_kind @ MetaVarKind::Expr { can_begin_literal_maybe_minus: true, .. },
2255            )) => {
2256                let expr = self
2257                    .eat_metavar_seq(mv_kind, |this| this.parse_expr())
2258                    .expect("metavar seq expr");
2259                check_expr(expr)
2260            }
2261            _ => None,
2262        }
2263    }
2264
2265    /// Matches `lit = true | false | token_lit`.
2266    /// Returns `None` if the next token is not a literal.
2267    fn parse_opt_token_lit(&mut self) -> Option<(token::Lit, Span)> {
2268        self.recover_after_dot();
2269        let span = self.token.span;
2270        self.eat_token_lit().map(|token_lit| (token_lit, span))
2271    }
2272
2273    /// Matches `lit = true | false | token_lit`.
2274    /// Returns `None` if the next token is not a literal.
2275    fn parse_opt_meta_item_lit(&mut self) -> Option<MetaItemLit> {
2276        self.recover_after_dot();
2277        let span = self.token.span;
2278        let uninterpolated_span = self.token_uninterpolated_span();
2279        self.eat_token_lit().map(|token_lit| {
2280            match MetaItemLit::from_token_lit(token_lit, span) {
2281                Ok(lit) => lit,
2282                Err(err) => {
2283                    let guar = report_lit_error(&self.psess, err, token_lit, uninterpolated_span);
2284                    // Pack possible quotes and prefixes from the original literal into
2285                    // the error literal's symbol so they can be pretty-printed faithfully.
2286                    let suffixless_lit = token::Lit::new(token_lit.kind, token_lit.symbol, None);
2287                    let symbol = Symbol::intern(&suffixless_lit.to_string());
2288                    let token_lit = token::Lit::new(token::Err(guar), symbol, token_lit.suffix);
2289                    MetaItemLit::from_token_lit(token_lit, uninterpolated_span).unwrap()
2290                }
2291            }
2292        })
2293    }
2294
2295    /// Matches `'-' lit | lit` (cf. `ast_validation::AstValidator::check_expr_within_pat`).
2296    /// Keep this in sync with `Token::can_begin_literal_maybe_minus`.
2297    pub fn parse_literal_maybe_minus(&mut self) -> PResult<'a, Box<Expr>> {
2298        if let Some(expr) = self.eat_metavar_seq_with_matcher(
2299            |mv_kind| #[allow(non_exhaustive_omitted_patterns)] match mv_kind {
    MetaVarKind::Expr { .. } => true,
    _ => false,
}matches!(mv_kind, MetaVarKind::Expr { .. }),
2300            |this| {
2301                // FIXME(nnethercote) The `expr` case should only match if
2302                // `e` is an `ExprKind::Lit` or an `ExprKind::Unary` containing
2303                // an `UnOp::Neg` and an `ExprKind::Lit`, like how
2304                // `can_begin_literal_maybe_minus` works. But this method has
2305                // been over-accepting for a long time, and to make that change
2306                // here requires also changing some `parse_literal_maybe_minus`
2307                // call sites to accept additional expression kinds. E.g.
2308                // `ExprKind::Path` must be accepted when parsing range
2309                // patterns. That requires some care. So for now, we continue
2310                // being less strict here than we should be.
2311                this.parse_expr()
2312            },
2313        ) {
2314            return Ok(expr);
2315        } else if let Some(lit) =
2316            self.eat_metavar_seq(MetaVarKind::Literal, |this| this.parse_literal_maybe_minus())
2317        {
2318            return Ok(lit);
2319        }
2320
2321        let lo = self.token.span;
2322        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));
2323        let (token_lit, span) = self.parse_token_lit()?;
2324        let expr = self.mk_expr(span, ExprKind::Lit(token_lit));
2325
2326        if minus_present {
2327            Ok(self.mk_expr(lo.to(self.prev_token.span), self.mk_unary(UnOp::Neg, expr)))
2328        } else {
2329            Ok(expr)
2330        }
2331    }
2332
2333    fn is_array_like_block(&mut self) -> bool {
2334        self.token.kind == TokenKind::OpenBrace
2335            && self
2336                .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(_)))
2337            && self.look_ahead(2, |t| t == &token::Comma)
2338            && self.look_ahead(3, |t| t.can_begin_expr())
2339    }
2340
2341    /// Emits a suggestion if it looks like the user meant an array but
2342    /// accidentally used braces, causing the code to be interpreted as a block
2343    /// expression.
2344    fn maybe_suggest_brackets_instead_of_braces(&mut self, lo: Span) -> Option<Box<Expr>> {
2345        let mut snapshot = self.create_snapshot_for_diagnostic();
2346        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)) {
2347            Ok(arr) => {
2348                let guar = self.dcx().emit_err(diagnostics::ArrayBracketsInsteadOfBraces {
2349                    span: arr.span,
2350                    sub: diagnostics::ArrayBracketsInsteadOfBracesSugg {
2351                        left: lo,
2352                        right: snapshot.prev_token.span,
2353                    },
2354                });
2355
2356                self.restore_snapshot(snapshot);
2357                Some(self.mk_expr_err(arr.span, guar))
2358            }
2359            Err(e) => {
2360                e.cancel();
2361                None
2362            }
2363        }
2364    }
2365
2366    fn suggest_missing_semicolon_before_array(
2367        &self,
2368        prev_span: Span,
2369        open_delim_span: Span,
2370    ) -> PResult<'a, ()> {
2371        if !self.may_recover() {
2372            return Ok(());
2373        }
2374
2375        if self.token == token::Comma {
2376            if !self.psess.source_map().is_multiline(prev_span.until(self.token.span)) {
2377                return Ok(());
2378            }
2379            let mut snapshot = self.create_snapshot_for_diagnostic();
2380            snapshot.bump();
2381            match snapshot.parse_seq_to_before_end(
2382                crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseBracket,
    token_type: crate::parser::token_type::TokenType::CloseBracket,
}exp!(CloseBracket),
2383                SeqSep::trailing_allowed(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma)),
2384                |p| p.parse_expr(),
2385            ) {
2386                Ok(_)
2387                    // When the close delim is `)`, `token.kind` is expected to be `token::CloseParen`,
2388                    // but the actual `token.kind` is `token::CloseBracket`.
2389                    // This is because the `token.kind` of the close delim is treated as the same as
2390                    // that of the open delim in `TokenTreesReader::parse_token_tree`, even if the delimiters of them are different.
2391                    // Therefore, `token.kind` should not be compared here.
2392                    if snapshot
2393                        .span_to_snippet(snapshot.token.span)
2394                        .is_ok_and(|snippet| snippet == "]") =>
2395                {
2396                    return Err(self.dcx().create_err(diagnostics::MissingSemicolonBeforeArray {
2397                        open_delim: open_delim_span,
2398                        semicolon: prev_span.shrink_to_hi(),
2399                    }));
2400                }
2401                Ok(_) => (),
2402                Err(err) => err.cancel(),
2403            }
2404        }
2405        Ok(())
2406    }
2407
2408    /// Parses a block or unsafe block.
2409    pub(super) fn parse_expr_block(
2410        &mut self,
2411        opt_label: Option<Label>,
2412        lo: Span,
2413        blk_mode: BlockCheckMode,
2414    ) -> PResult<'a, Box<Expr>> {
2415        if self.may_recover() && self.is_array_like_block() {
2416            if let Some(arr) = self.maybe_suggest_brackets_instead_of_braces(lo) {
2417                return Ok(arr);
2418            }
2419        }
2420
2421        if self.token.is_metavar_block() {
2422            self.dcx().emit_err(diagnostics::InvalidBlockMacroSegment {
2423                span: self.token.span,
2424                context: lo.to(self.token.span),
2425                wrap: diagnostics::WrapInExplicitBlock {
2426                    lo: self.token.span.shrink_to_lo(),
2427                    hi: self.token.span.shrink_to_hi(),
2428                },
2429            });
2430        }
2431
2432        let (attrs, blk) = self.parse_block_common(lo, blk_mode, None)?;
2433        Ok(self.mk_expr_with_attrs(blk.span, ExprKind::Block(blk, opt_label), attrs))
2434    }
2435
2436    /// Parse a block which takes no attributes and has no label
2437    fn parse_simple_block(&mut self) -> PResult<'a, Box<Expr>> {
2438        let blk = self.parse_block()?;
2439        Ok(self.mk_expr(blk.span, ExprKind::Block(blk, None)))
2440    }
2441
2442    /// Parses a closure expression (e.g., `move |args| expr`).
2443    fn parse_expr_closure(&mut self) -> PResult<'a, Box<Expr>> {
2444        let lo = self.token.span;
2445
2446        let before = self.prev_token;
2447        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)) {
2448            let lo = self.token.span;
2449            let (bound_vars, _) = self.parse_higher_ranked_binder()?;
2450            let span = lo.to(self.prev_token.span);
2451
2452            self.psess.gated_spans.gate(sym::closure_lifetime_binder, span);
2453
2454            ClosureBinder::For { span, generic_params: bound_vars }
2455        } else {
2456            ClosureBinder::NotPresent
2457        };
2458
2459        let constness = self.parse_closure_constness();
2460
2461        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)) {
2462            self.psess.gated_spans.gate(sym::coroutines, self.prev_token.span);
2463            Movability::Static
2464        } else {
2465            Movability::Movable
2466        };
2467
2468        let coroutine_kind = if self.token_uninterpolated_span().at_least_rust_2018() {
2469            self.parse_coroutine_kind(Case::Sensitive)
2470        } else {
2471            None
2472        };
2473
2474        if let ClosureBinder::NotPresent = binder
2475            && coroutine_kind.is_some()
2476        {
2477            // coroutine closures and generators can have the same qualifiers, so we might end up
2478            // in here if there is a missing `|` but also no `{`. Adjust the expectations in that case.
2479            self.expected_token_types.insert(TokenType::OpenBrace);
2480        }
2481
2482        let capture_clause = self.parse_capture_clause()?;
2483        let (fn_decl, fn_arg_span) = self.parse_fn_block_decl()?;
2484        let decl_hi = self.prev_token.span;
2485        let mut body = match &fn_decl.output {
2486            // No return type.
2487            FnRetTy::Default(_) => {
2488                let restrictions =
2489                    self.restrictions - Restrictions::STMT_EXPR - Restrictions::ALLOW_LET;
2490                let prev = self.prev_token;
2491                let token = self.token;
2492                let attrs = self.parse_outer_attributes()?;
2493                match self.parse_expr_res(restrictions, attrs) {
2494                    Ok((expr, _)) => expr,
2495                    Err(err) => self.recover_closure_body(err, before, prev, token, lo, decl_hi)?,
2496                }
2497            }
2498            // Explicit return type (`->`) needs block `-> T { }`.
2499            FnRetTy::Ty(ty) => self.parse_closure_block_body(ty.span)?,
2500        };
2501
2502        match coroutine_kind {
2503            Some(CoroutineKind::Async { .. }) => {}
2504            Some(CoroutineKind::Gen { span, .. }) | Some(CoroutineKind::AsyncGen { span, .. }) => {
2505                // Feature-gate `gen ||` and `async gen ||` closures.
2506                // FIXME(gen_blocks): This perhaps should be a different gate.
2507                self.psess.gated_spans.gate(sym::gen_blocks, span);
2508            }
2509            None => {}
2510        }
2511
2512        if self.token == TokenKind::Semi
2513            && let Some(last) = self.token_cursor.stack.last()
2514            && let Some(TokenTree::Delimited(_, _, Delimiter::Parenthesis, _)) = last.curr()
2515            && self.may_recover()
2516        {
2517            // It is likely that the closure body is a block but where the
2518            // braces have been removed. We will recover and eat the next
2519            // statements later in the parsing process.
2520            body = self.mk_expr_err(
2521                body.span,
2522                self.dcx().span_delayed_bug(body.span, "recovered a closure body as a block"),
2523            );
2524        }
2525
2526        let body_span = body.span;
2527
2528        let closure = self.mk_expr(
2529            lo.to(body.span),
2530            ExprKind::Closure(Box::new(ast::Closure {
2531                binder,
2532                capture_clause,
2533                constness,
2534                coroutine_kind,
2535                movability,
2536                fn_decl,
2537                body,
2538                fn_decl_span: lo.to(decl_hi),
2539                fn_arg_span,
2540            })),
2541        );
2542
2543        // Disable recovery for closure body
2544        let spans =
2545            ClosureSpans { whole_closure: closure.span, closing_pipe: decl_hi, body: body_span };
2546        self.current_closure = Some(spans);
2547
2548        Ok(closure)
2549    }
2550
2551    /// If an explicit return type is given, require a block to appear (RFC 968).
2552    fn parse_closure_block_body(&mut self, ret_span: Span) -> PResult<'a, Box<Expr>> {
2553        if self.may_recover()
2554            && self.token.can_begin_expr()
2555            && self.token.kind != TokenKind::OpenBrace
2556            && !self.token.is_metavar_block()
2557        {
2558            let snapshot = self.create_snapshot_for_diagnostic();
2559            let restrictions =
2560                self.restrictions - Restrictions::STMT_EXPR - Restrictions::ALLOW_LET;
2561            let tok = self.token.clone();
2562            match self.parse_expr_res(restrictions, AttrWrapper::empty()) {
2563                Ok((expr, _)) => {
2564                    let descr = super::token_descr(&tok);
2565                    let mut diag = self
2566                        .dcx()
2567                        .struct_span_err(tok.span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected `{{`, found {0}", descr))
    })format!("expected `{{`, found {descr}"));
2568                    diag.span_label(
2569                        ret_span,
2570                        "explicit return type requires closure body to be enclosed in braces",
2571                    );
2572                    diag.multipart_suggestion(
2573                        "wrap the expression in curly braces",
2574                        ::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![
2575                            (expr.span.shrink_to_lo(), "{ ".to_string()),
2576                            (expr.span.shrink_to_hi(), " }".to_string()),
2577                        ],
2578                        Applicability::MachineApplicable,
2579                    );
2580                    diag.emit();
2581                    return Ok(expr);
2582                }
2583                Err(diag) => {
2584                    diag.cancel();
2585                    self.restore_snapshot(snapshot);
2586                }
2587            }
2588        }
2589
2590        let body_lo = self.token.span;
2591        self.parse_expr_block(None, body_lo, BlockCheckMode::Default)
2592    }
2593
2594    /// Parses an optional `move` or `use` prefix to a closure-like construct.
2595    fn parse_capture_clause(&mut self) -> PResult<'a, CaptureBy> {
2596        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)) {
2597            let move_kw_span = self.prev_token.span;
2598            // Check for `move async` and recover
2599            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)) {
2600                let move_async_span = self.token.span.with_lo(self.prev_token.span.data().lo);
2601                Err(self
2602                    .dcx()
2603                    .create_err(diagnostics::AsyncMoveOrderIncorrect { span: move_async_span }))
2604            } else {
2605                Ok(CaptureBy::Value { move_kw: move_kw_span })
2606            }
2607        } 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)) {
2608            let use_kw_span = self.prev_token.span;
2609            self.psess.gated_spans.gate(sym::ergonomic_clones, use_kw_span);
2610            // Check for `use async` and recover
2611            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)) {
2612                let use_async_span = self.token.span.with_lo(self.prev_token.span.data().lo);
2613                Err(self
2614                    .dcx()
2615                    .create_err(diagnostics::AsyncUseOrderIncorrect { span: use_async_span }))
2616            } else {
2617                Ok(CaptureBy::Use { use_kw: use_kw_span })
2618            }
2619        } else {
2620            Ok(CaptureBy::Ref)
2621        }
2622    }
2623
2624    /// Parses the `|arg, arg|` header of a closure.
2625    fn parse_fn_block_decl(&mut self) -> PResult<'a, (Box<FnDecl>, Span)> {
2626        let arg_start = self.token.span.lo();
2627
2628        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)) {
2629            ThinVec::new()
2630        } else {
2631            self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Or,
    token_type: crate::parser::token_type::TokenType::Or,
}exp!(Or))?;
2632            let args = self
2633                .parse_seq_to_before_tokens(
2634                    &[crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Or,
    token_type: crate::parser::token_type::TokenType::Or,
}exp!(Or)],
2635                    &[&token::OrOr],
2636                    SeqSep::trailing_allowed(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma)),
2637                    |p| p.parse_fn_block_param(),
2638                )?
2639                .0;
2640            self.expect_or()?;
2641            args
2642        };
2643        let arg_span = self.prev_token.span.with_lo(arg_start);
2644        let output =
2645            self.parse_ret_ty(AllowPlus::Yes, RecoverQPath::Yes, RecoverReturnSign::Yes)?;
2646
2647        Ok((Box::new(FnDecl { inputs, output }), arg_span))
2648    }
2649
2650    /// Parses a parameter in a closure header (e.g., `|arg, arg|`).
2651    fn parse_fn_block_param(&mut self) -> PResult<'a, Param> {
2652        let lo = self.token.span;
2653        let attrs = self.parse_outer_attributes()?;
2654        self.collect_tokens(None, attrs, ForceCollect::No, |this, attrs| {
2655            let pat = Box::new(this.parse_pat_no_top_alt(Some(Expected::ParameterName), None)?);
2656            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)) {
2657                this.parse_ty()?
2658            } else {
2659                this.mk_ty(pat.span, TyKind::Infer)
2660            };
2661
2662            Ok((
2663                Param {
2664                    attrs,
2665                    ty,
2666                    pat,
2667                    span: lo.to(this.prev_token.span),
2668                    id: DUMMY_NODE_ID,
2669                    is_placeholder: false,
2670                },
2671                Trailing::from(this.token == token::Comma),
2672                UsePreAttrPos::No,
2673            ))
2674        })
2675    }
2676
2677    /// Parses an `if` expression (`if` token already eaten).
2678    fn parse_expr_if(&mut self) -> PResult<'a, Box<Expr>> {
2679        let lo = self.prev_token.span;
2680        // Scoping code checks the top level edition of the `if`; let's match it here.
2681        // The `CondChecker` also checks the edition of the `let` itself, just to make sure.
2682        let let_chains_policy = LetChainsPolicy::EditionDependent { current_edition: lo.edition() };
2683        let cond = self.parse_expr_cond(let_chains_policy)?;
2684        self.parse_if_after_cond(lo, cond)
2685    }
2686
2687    fn parse_if_after_cond(&mut self, lo: Span, mut cond: Box<Expr>) -> PResult<'a, Box<Expr>> {
2688        let cond_span = cond.span;
2689        // Tries to interpret `cond` as either a missing expression if it's a block,
2690        // or as an unfinished expression if it's a binop and the RHS is a block.
2691        // We could probably add more recoveries here too...
2692        let mut recover_block_from_condition = |this: &mut Self| {
2693            let block = match &mut cond.kind {
2694                ExprKind::Binary(Spanned { span: binop_span, .. }, _, right)
2695                    if let ExprKind::Block(_, None) = right.kind =>
2696                {
2697                    let guar = this.dcx().emit_err(diagnostics::IfExpressionMissingThenBlock {
2698                        if_span: lo,
2699                        missing_then_block_sub:
2700                            diagnostics::IfExpressionMissingThenBlockSub::UnfinishedCondition(
2701                                cond_span.shrink_to_lo().to(*binop_span),
2702                            ),
2703                        let_else_sub: None,
2704                    });
2705                    std::mem::replace(right, this.mk_expr_err(binop_span.shrink_to_hi(), guar))
2706                }
2707                ExprKind::Block(_, None) => {
2708                    let guar = this.dcx().emit_err(diagnostics::IfExpressionMissingCondition {
2709                        if_span: lo.with_neighbor(cond.span).shrink_to_hi(),
2710                        block_span: self.psess.source_map().start_point(cond_span),
2711                    });
2712                    std::mem::replace(&mut cond, this.mk_expr_err(cond_span.shrink_to_hi(), guar))
2713                }
2714                _ => {
2715                    return None;
2716                }
2717            };
2718            if let ExprKind::Block(block, _) = &block.kind {
2719                Some(block.clone())
2720            } else {
2721                ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
2722            }
2723        };
2724        // Parse then block
2725        let thn = if self.token.is_keyword(kw::Else) {
2726            if let Some(block) = recover_block_from_condition(self) {
2727                block
2728            } else {
2729                let let_else_sub = #[allow(non_exhaustive_omitted_patterns)] match cond.kind {
    ExprKind::Let(..) => true,
    _ => false,
}matches!(cond.kind, ExprKind::Let(..))
2730                    .then(|| diagnostics::IfExpressionLetSomeSub { if_span: lo.until(cond_span) });
2731
2732                let guar = self.dcx().emit_err(diagnostics::IfExpressionMissingThenBlock {
2733                    if_span: lo,
2734                    missing_then_block_sub:
2735                        diagnostics::IfExpressionMissingThenBlockSub::AddThenBlock(
2736                            cond_span.shrink_to_hi(),
2737                        ),
2738                    let_else_sub,
2739                });
2740                self.mk_block_err(cond_span.shrink_to_hi(), guar)
2741            }
2742        } else {
2743            let attrs = self.parse_outer_attributes()?; // For recovery.
2744            let maybe_fatarrow = self.token;
2745            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)) {
2746                self.parse_block()?
2747            } else if let Some(block) = recover_block_from_condition(self) {
2748                block
2749            } else {
2750                self.error_on_extra_if(&cond)?;
2751                // Parse block, which will always fail, but we can add a nice note to the error
2752                self.parse_block().map_err(|mut err| {
2753                        if self.prev_token == token::Semi
2754                            && self.token == token::AndAnd
2755                            && let maybe_let = self.look_ahead(1, |t| t.clone())
2756                            && maybe_let.is_keyword(kw::Let)
2757                        {
2758                            err.span_suggestion(
2759                                self.prev_token.span,
2760                                "consider removing this semicolon to parse the `let` as part of the same chain",
2761                                "",
2762                                Applicability::MachineApplicable,
2763                            ).span_note(
2764                                self.token.span.to(maybe_let.span),
2765                                "you likely meant to continue parsing the let-chain starting here",
2766                            );
2767                        } else {
2768                            // Look for usages of '=>' where '>=' might be intended
2769                            if maybe_fatarrow == token::FatArrow {
2770                                err.span_suggestion(
2771                                    maybe_fatarrow.span,
2772                                    "you might have meant to write a \"greater than or equal to\" comparison",
2773                                    ">=",
2774                                    Applicability::MaybeIncorrect,
2775                                );
2776                            }
2777                            err.span_note(
2778                                cond_span,
2779                                "the `if` expression is missing a block after this condition",
2780                            );
2781                        }
2782                        err
2783                    })?
2784            };
2785            self.error_on_if_block_attrs(lo, false, block.span, attrs);
2786            block
2787        };
2788        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 };
2789        Ok(self.mk_expr(lo.to(self.prev_token.span), ExprKind::If(cond, thn, els)))
2790    }
2791
2792    /// Parses the condition of a `if` or `while` expression.
2793    ///
2794    /// The specified `edition` in `let_chains_policy` should be that of the whole `if` construct,
2795    /// i.e. the same span we use to later decide whether the drop behaviour should be that of
2796    /// edition `..=2021` or that of `2024..`.
2797    // Public to use it for custom `if` expressions in rustfmt forks like https://github.com/tucant/rustfmt
2798    pub fn parse_expr_cond(
2799        &mut self,
2800        let_chains_policy: LetChainsPolicy,
2801    ) -> PResult<'a, Box<Expr>> {
2802        let attrs = self.parse_outer_attributes()?;
2803        let (mut cond, _) =
2804            self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL | Restrictions::ALLOW_LET, attrs)?;
2805
2806        let mut checker = CondChecker::new(self, let_chains_policy);
2807        checker.visit_expr(&mut cond);
2808        Ok(if let Some(guar) = checker.found_incorrect_let_chain {
2809            self.mk_expr_err(cond.span, guar)
2810        } else {
2811            cond
2812        })
2813    }
2814
2815    /// Parses a `let $pat = $expr` pseudo-expression.
2816    fn parse_expr_let(&mut self, restrictions: Restrictions) -> PResult<'a, Box<Expr>> {
2817        let recovered: Recovered = if !restrictions.contains(Restrictions::ALLOW_LET) {
2818            let err = diagnostics::ExpectedExpressionFoundLet {
2819                span: self.token.span,
2820                reason: diagnostics::ForbiddenLetReason::OtherForbidden,
2821                missing_let: None,
2822                comparison: None,
2823            };
2824            if self.prev_token == token::Or {
2825                // This was part of a closure, the that part of the parser recover.
2826                return Err(self.dcx().create_err(err));
2827            } else {
2828                Recovered::Yes(self.dcx().emit_err(err))
2829            }
2830        } else {
2831            Recovered::No
2832        };
2833        self.bump(); // Eat `let` token
2834        let lo = self.prev_token.span;
2835        let pat = self.parse_pat_no_top_guard(
2836            None,
2837            RecoverComma::Yes,
2838            RecoverColon::Yes,
2839            CommaRecoveryMode::LikelyTuple,
2840        )?;
2841        if self.token == token::EqEq {
2842            self.dcx().emit_err(diagnostics::ExpectedEqForLetExpr {
2843                span: self.token.span,
2844                sugg_span: self.token.span,
2845            });
2846            self.bump();
2847        } else {
2848            self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Eq,
    token_type: crate::parser::token_type::TokenType::Eq,
}exp!(Eq))?;
2849        }
2850        let attrs = self.parse_outer_attributes()?;
2851        let (expr, _) =
2852            self.parse_expr_assoc_with(Bound::Excluded(prec_let_scrutinee_needs_par()), attrs)?;
2853        let span = lo.to(expr.span);
2854        Ok(self.mk_expr(span, ExprKind::Let(Box::new(pat), expr, span, recovered)))
2855    }
2856
2857    /// Parses an `else { ... }` expression (`else` token already eaten).
2858    fn parse_expr_else(&mut self) -> PResult<'a, Box<Expr>> {
2859        let else_span = self.prev_token.span; // `else`
2860        let attrs = self.parse_outer_attributes()?; // For recovery.
2861        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)) {
2862            ensure_sufficient_stack(|| self.parse_expr_if())?
2863        } else if self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenBrace,
    token_type: crate::parser::token_type::TokenType::OpenBrace,
}exp!(OpenBrace)) {
2864            self.parse_simple_block()?
2865        } else {
2866            let snapshot = self.create_snapshot_for_diagnostic();
2867            let first_tok = super::token_descr(&self.token);
2868            let first_tok_span = self.token.span;
2869            match self.parse_expr() {
2870                Ok(cond)
2871                // Try to guess the difference between a "condition-like" vs
2872                // "statement-like" expression.
2873                //
2874                // We are seeing the following code, in which $cond is neither
2875                // ExprKind::Block nor ExprKind::If (the 2 cases wherein this
2876                // would be valid syntax).
2877                //
2878                //     if ... {
2879                //     } else $cond
2880                //
2881                // If $cond is "condition-like" such as ExprKind::Binary, we
2882                // want to suggest inserting `if`.
2883                //
2884                //     if ... {
2885                //     } else if a == b {
2886                //            ^^
2887                //     }
2888                //
2889                // We account for macro calls that were meant as conditions as well.
2890                //
2891                //     if ... {
2892                //     } else if macro! { foo bar } {
2893                //            ^^
2894                //     }
2895                //
2896                // If $cond is "statement-like" such as ExprKind::While then we
2897                // want to suggest wrapping in braces.
2898                //
2899                //     if ... {
2900                //     } else {
2901                //            ^
2902                //         while true {}
2903                //     }
2904                //     ^
2905                    if self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenBrace,
    token_type: crate::parser::token_type::TokenType::OpenBrace,
}exp!(OpenBrace))
2906                        && (classify::expr_requires_semi_to_be_stmt(&cond)
2907                            || #[allow(non_exhaustive_omitted_patterns)] match cond.kind {
    ExprKind::MacCall(..) => true,
    _ => false,
}matches!(cond.kind, ExprKind::MacCall(..)))
2908                    =>
2909                {
2910                    self.dcx().emit_err(diagnostics::ExpectedElseBlock {
2911                        first_tok_span,
2912                        first_tok,
2913                        else_span,
2914                        condition_start: cond.span.shrink_to_lo(),
2915                    });
2916                    self.parse_if_after_cond(cond.span.shrink_to_lo(), cond)?
2917                }
2918                Err(e) => {
2919                    e.cancel();
2920                    self.restore_snapshot(snapshot);
2921                    self.parse_simple_block()?
2922                },
2923                Ok(_) => {
2924                    self.restore_snapshot(snapshot);
2925                    self.parse_simple_block()?
2926                },
2927            }
2928        };
2929        self.error_on_if_block_attrs(else_span, true, expr.span, attrs);
2930        Ok(expr)
2931    }
2932
2933    fn error_on_if_block_attrs(
2934        &self,
2935        ctx_span: Span,
2936        is_ctx_else: bool,
2937        branch_span: Span,
2938        attrs: AttrWrapper,
2939    ) {
2940        if !attrs.is_empty()
2941            && let [x0 @ xn] | [x0, .., xn] = &*attrs.take_for_recovery(self.psess)
2942        {
2943            let attributes = x0.span.until(branch_span);
2944            let last = xn.span;
2945            let ctx = if is_ctx_else { "else" } else { "if" };
2946            self.dcx().emit_err(diagnostics::OuterAttributeNotAllowedOnIfElse {
2947                last,
2948                branch_span,
2949                ctx_span,
2950                ctx: ctx.to_string(),
2951                attributes,
2952            });
2953        }
2954    }
2955
2956    fn error_on_extra_if(&mut self, cond: &Box<Expr>) -> PResult<'a, ()> {
2957        if let ExprKind::Binary(Spanned { span: binop_span, node: binop }, _, right) = &cond.kind
2958            && let BinOpKind::And = binop
2959            && let ExprKind::If(cond, ..) = &right.kind
2960        {
2961            Err(self.dcx().create_err(diagnostics::UnexpectedIfWithIf(
2962                binop_span.shrink_to_hi().to(cond.span.shrink_to_lo()),
2963            )))
2964        } else {
2965            Ok(())
2966        }
2967    }
2968
2969    // Public to use it for custom `for` expressions in rustfmt forks like https://github.com/tucant/rustfmt
2970    pub fn parse_for_head(&mut self) -> PResult<'a, (Pat, Box<Expr>)> {
2971        let begin_paren = if self.token == token::OpenParen {
2972            // Record whether we are about to parse `for (`.
2973            // This is used below for recovery in case of `for ( $stuff ) $block`
2974            // in which case we will suggest `for $stuff $block`.
2975            let start_span = self.token.span;
2976            let left = self.prev_token.span.between(self.look_ahead(1, |t| t.span));
2977            Some((start_span, left))
2978        } else {
2979            None
2980        };
2981        // Try to parse the pattern `for ($PAT) in $EXPR`.
2982        let pat = match (
2983            self.parse_pat_allow_top_guard(
2984                None,
2985                RecoverComma::Yes,
2986                RecoverColon::Yes,
2987                CommaRecoveryMode::LikelyTuple,
2988            ),
2989            begin_paren,
2990        ) {
2991            (Ok(pat), _) => pat, // Happy path.
2992            (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)) => {
2993                // We know for sure we have seen `for ($SOMETHING in`. In the happy path this would
2994                // happen right before the return of this method.
2995                let attrs = self.parse_outer_attributes()?;
2996                let (expr, _) = match self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, attrs) {
2997                    Ok(expr) => expr,
2998                    Err(expr_err) => {
2999                        // We don't know what followed the `in`, so cancel and bubble up the
3000                        // original error.
3001                        expr_err.cancel();
3002                        return Err(err);
3003                    }
3004                };
3005                return if self.token == token::CloseParen {
3006                    // We know for sure we have seen `for ($SOMETHING in $EXPR)`, so we recover the
3007                    // parser state and emit a targeted suggestion.
3008                    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];
3009                    let right = self.prev_token.span.between(self.look_ahead(1, |t| t.span));
3010                    self.bump(); // )
3011                    err.cancel();
3012                    self.dcx().emit_err(diagnostics::ParenthesesInForHead {
3013                        span,
3014                        // With e.g. `for (x) in y)` this would replace `(x) in y)`
3015                        // with `x) in y)` which is syntactically invalid.
3016                        // However, this is prevented before we get here.
3017                        sugg: diagnostics::ParenthesesInForHeadSugg { left, right },
3018                    });
3019                    Ok((self.mk_pat(start_span.to(right), ast::PatKind::Wild), expr))
3020                } else {
3021                    Err(err) // Some other error, bubble up.
3022                };
3023            }
3024            (Err(err), _) => return Err(err), // Some other error, bubble up.
3025        };
3026        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)) {
3027            self.error_missing_in_for_loop();
3028        }
3029        self.check_for_for_in_in_typo(self.prev_token.span);
3030        let attrs = self.parse_outer_attributes()?;
3031        let (expr, _) = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, attrs)?;
3032        Ok((pat, expr))
3033    }
3034
3035    /// Parses `for await? <src_pat> in <src_expr> <src_loop_block>` (`for` token already eaten).
3036    fn parse_expr_for(&mut self, opt_label: Option<Label>, lo: Span) -> PResult<'a, Box<Expr>> {
3037        let is_await =
3038            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));
3039
3040        if is_await {
3041            self.psess.gated_spans.gate(sym::async_for_loop, self.prev_token.span);
3042        }
3043
3044        let kind = if is_await { ForLoopKind::ForAwait } else { ForLoopKind::For };
3045
3046        let (pat, expr) = self.parse_for_head()?;
3047        let pat = Box::new(pat);
3048        // Recover from missing expression in `for` loop
3049        if #[allow(non_exhaustive_omitted_patterns)] match expr.kind {
    ExprKind::Block(..) => true,
    _ => false,
}matches!(expr.kind, ExprKind::Block(..))
3050            && self.token.kind != token::OpenBrace
3051            && self.may_recover()
3052        {
3053            let guar = self.dcx().emit_err(diagnostics::MissingExpressionInForLoop {
3054                span: expr.span.shrink_to_lo(),
3055            });
3056            let err_expr = self.mk_expr(expr.span, ExprKind::Err(guar));
3057            let block = self.mk_block(::thin_vec::ThinVec::new()thin_vec![], BlockCheckMode::Default, self.prev_token.span);
3058            return Ok(self.mk_expr(
3059                lo.to(self.prev_token.span),
3060                ExprKind::ForLoop { pat, iter: err_expr, body: block, label: opt_label, kind },
3061            ));
3062        }
3063
3064        let (attrs, loop_block) = self.parse_inner_attrs_and_block(
3065            // Only suggest moving erroneous block label to the loop header
3066            // if there is not already a label there
3067            opt_label.is_none().then_some(lo),
3068        )?;
3069
3070        let kind = ExprKind::ForLoop { pat, iter: expr, body: loop_block, label: opt_label, kind };
3071
3072        self.recover_loop_else("for", lo)?;
3073
3074        Ok(self.mk_expr_with_attrs(lo.to(self.prev_token.span), kind, attrs))
3075    }
3076
3077    /// Recovers from an `else` clause after a loop (`for...else`, `while...else`)
3078    fn recover_loop_else(&mut self, loop_kind: &'static str, loop_kw: Span) -> PResult<'a, ()> {
3079        if self.token.is_keyword(kw::Else) && self.may_recover() {
3080            let else_span = self.token.span;
3081            self.bump();
3082            let else_clause = self.parse_expr_else()?;
3083            self.dcx().emit_err(diagnostics::LoopElseNotSupported {
3084                span: else_span.to(else_clause.span),
3085                loop_kind,
3086                loop_kw,
3087            });
3088        }
3089        Ok(())
3090    }
3091
3092    fn error_missing_in_for_loop(&mut self) {
3093        let (span, sub) = if self.token.is_ident_named(sym::of) {
3094            // Possibly using JS syntax (#75311).
3095            let span = self.token.span;
3096            self.bump();
3097            (span, Some(diagnostics::MissingInInForLoopSub::InNotOf(span)))
3098        } else if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Eq,
    token_type: crate::parser::token_type::TokenType::Eq,
}exp!(Eq)) {
3099            let span = self.prev_token.span;
3100            (span, Some(diagnostics::MissingInInForLoopSub::InNotEq(span)))
3101        } else {
3102            let span = self.prev_token.span.between(self.token.span);
3103            let sub = (!self.for_loop_head_has_in())
3104                .then_some(diagnostics::MissingInInForLoopSub::AddIn(span));
3105            (span, sub)
3106        };
3107
3108        self.dcx().emit_err(diagnostics::MissingInInForLoop { span, sub });
3109    }
3110
3111    /// Whether the `for` loop header already contains an `in` before its body.
3112    /// If it does, the binding is malformed (e.g. `for i i in 0..10`) rather
3113    /// than missing `in`, so suggesting another `in` would just be invalid too.
3114    fn for_loop_head_has_in(&self) -> bool {
3115        let mut dist = 0;
3116        loop {
3117            let (is_in, is_end) = self.look_ahead(dist, |t| {
3118                (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))
3119            });
3120            if is_in {
3121                return true;
3122            }
3123            if is_end {
3124                return false;
3125            }
3126            dist += 1;
3127        }
3128    }
3129
3130    /// Parses a `while` or `while let` expression (`while` token already eaten).
3131    fn parse_expr_while(&mut self, opt_label: Option<Label>, lo: Span) -> PResult<'a, Box<Expr>> {
3132        let policy = LetChainsPolicy::EditionDependent { current_edition: lo.edition() };
3133        let cond = self.parse_expr_cond(policy).map_err(|mut err| {
3134            err.span_label(lo, "while parsing the condition of this `while` expression");
3135            err
3136        })?;
3137        let (attrs, body) = self
3138            .parse_inner_attrs_and_block(
3139                // Only suggest moving erroneous block label to the loop header
3140                // if there is not already a label there
3141                opt_label.is_none().then_some(lo),
3142            )
3143            .map_err(|mut err| {
3144                err.span_label(lo, "while parsing the body of this `while` expression");
3145                err.span_label(cond.span, "this `while` condition successfully parsed");
3146                err
3147            })?;
3148
3149        self.recover_loop_else("while", lo)?;
3150
3151        Ok(self.mk_expr_with_attrs(
3152            lo.to(self.prev_token.span),
3153            ExprKind::While(cond, body, opt_label),
3154            attrs,
3155        ))
3156    }
3157
3158    /// Parses `loop { ... }` (`loop` token already eaten).
3159    fn parse_expr_loop(&mut self, opt_label: Option<Label>, lo: Span) -> PResult<'a, Box<Expr>> {
3160        let loop_span = self.prev_token.span;
3161        let (attrs, body) = self.parse_inner_attrs_and_block(
3162            // Only suggest moving erroneous block label to the loop header
3163            // if there is not already a label there
3164            opt_label.is_none().then_some(lo),
3165        )?;
3166        self.recover_loop_else("loop", lo)?;
3167        Ok(self.mk_expr_with_attrs(
3168            lo.to(self.prev_token.span),
3169            ExprKind::Loop(body, opt_label, loop_span),
3170            attrs,
3171        ))
3172    }
3173
3174    pub(crate) fn eat_label(&mut self) -> Option<Label> {
3175        if let Some((ident, is_raw)) = self.token.lifetime() {
3176            // Disallow `'fn`, but with a better error message than `expect_lifetime`.
3177            if is_raw == IdentIsRaw::No && ident.without_first_quote().is_reserved() {
3178                self.dcx().emit_err(diagnostics::KeywordLabel { span: ident.span });
3179            }
3180
3181            self.bump();
3182            Some(Label { ident })
3183        } else {
3184            None
3185        }
3186    }
3187
3188    /// Parses a `match ... { ... }` expression (`match` token already eaten).
3189    fn parse_expr_match(&mut self) -> PResult<'a, Box<Expr>> {
3190        let match_span = self.prev_token.span;
3191        let attrs = self.parse_outer_attributes()?;
3192        let (scrutinee, _) = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, attrs)?;
3193
3194        self.parse_match_block(match_span, match_span, scrutinee, MatchKind::Prefix)
3195    }
3196
3197    /// Parses the block of a `match expr { ... }` or a `expr.match { ... }`
3198    /// expression. This is after the match token and scrutinee are eaten
3199    fn parse_match_block(
3200        &mut self,
3201        lo: Span,
3202        match_span: Span,
3203        scrutinee: Box<Expr>,
3204        match_kind: MatchKind,
3205    ) -> PResult<'a, Box<Expr>> {
3206        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)) {
3207            if self.token == token::Semi {
3208                e.span_suggestion_short(
3209                    match_span,
3210                    "try removing this `match`",
3211                    "",
3212                    Applicability::MaybeIncorrect, // speculative
3213                );
3214            }
3215            if self.maybe_recover_unexpected_block_label(None) {
3216                e.cancel();
3217                self.bump();
3218            } else {
3219                return Err(e);
3220            }
3221        }
3222        let attrs = self.parse_inner_attributes()?;
3223
3224        let mut arms = ThinVec::new();
3225        while self.token != token::CloseBrace {
3226            match self.parse_arm() {
3227                Ok(arm) => arms.push(arm),
3228                Err(e) => {
3229                    // Recover by skipping to the end of the block.
3230                    let guar = e.emit();
3231                    self.recover_stmt();
3232                    let span = lo.to(self.token.span);
3233                    if self.token == token::CloseBrace {
3234                        self.bump();
3235                    }
3236                    // Always push at least one arm to make the match non-empty
3237                    arms.push(Arm {
3238                        attrs: Default::default(),
3239                        pat: Box::new(self.mk_pat(span, ast::PatKind::Err(guar))),
3240                        guard: None,
3241                        body: Some(self.mk_expr_err(span, guar)),
3242                        span,
3243                        id: DUMMY_NODE_ID,
3244                        is_placeholder: false,
3245                    });
3246                    return Ok(self.mk_expr_with_attrs(
3247                        span,
3248                        ExprKind::Match(scrutinee, arms, match_kind),
3249                        attrs,
3250                    ));
3251                }
3252            }
3253        }
3254        let hi = self.token.span;
3255        self.bump();
3256        Ok(self.mk_expr_with_attrs(lo.to(hi), ExprKind::Match(scrutinee, arms, match_kind), attrs))
3257    }
3258
3259    /// Attempt to recover from match arm body with statements and no surrounding braces.
3260    fn parse_arm_body_missing_braces(
3261        &mut self,
3262        first_expr: &Box<Expr>,
3263        arrow_span: Span,
3264    ) -> Option<(Span, ErrorGuaranteed)> {
3265        if self.token != token::Semi {
3266            return None;
3267        }
3268        let start_snapshot = self.create_snapshot_for_diagnostic();
3269        let semi_sp = self.token.span;
3270        self.bump(); // `;`
3271        let mut stmts =
3272            ::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()))];
3273        let err = |this: &Parser<'_>, stmts: Vec<ast::Stmt>| {
3274            let span = stmts[0].span.to(stmts[stmts.len() - 1].span);
3275
3276            let guar = this.dcx().emit_err(diagnostics::MatchArmBodyWithoutBraces {
3277                statements: span,
3278                arrow: arrow_span,
3279                num_statements: stmts.len(),
3280                sub: if stmts.len() > 1 {
3281                    diagnostics::MatchArmBodyWithoutBracesSugg::AddBraces {
3282                        left: span.shrink_to_lo(),
3283                        right: span.shrink_to_hi(),
3284                        num_statements: stmts.len(),
3285                    }
3286                } else {
3287                    diagnostics::MatchArmBodyWithoutBracesSugg::UseComma { semicolon: semi_sp }
3288                },
3289            });
3290            (span, guar)
3291        };
3292        // We might have either a `,` -> `;` typo, or a block without braces. We need
3293        // a more subtle parsing strategy.
3294        loop {
3295            if self.token == token::CloseBrace {
3296                // We have reached the closing brace of the `match` expression.
3297                return Some(err(self, stmts));
3298            }
3299            if self.token == token::Comma {
3300                self.restore_snapshot(start_snapshot);
3301                return None;
3302            }
3303            let pre_pat_snapshot = self.create_snapshot_for_diagnostic();
3304            match self.parse_pat_no_top_alt(None, None) {
3305                Ok(_pat) => {
3306                    if self.token == token::FatArrow {
3307                        // Reached arm end.
3308                        self.restore_snapshot(pre_pat_snapshot);
3309                        return Some(err(self, stmts));
3310                    }
3311                }
3312                Err(err) => {
3313                    err.cancel();
3314                }
3315            }
3316
3317            self.restore_snapshot(pre_pat_snapshot);
3318            match self.parse_stmt_without_recovery(true, ForceCollect::No, false) {
3319                // Consume statements for as long as possible.
3320                Ok(Some(stmt)) => {
3321                    stmts.push(stmt);
3322                }
3323                Ok(None) => {
3324                    self.restore_snapshot(start_snapshot);
3325                    break;
3326                }
3327                // We couldn't parse either yet another statement missing it's
3328                // enclosing block nor the next arm's pattern or closing brace.
3329                Err(stmt_err) => {
3330                    stmt_err.cancel();
3331                    self.restore_snapshot(start_snapshot);
3332                    break;
3333                }
3334            }
3335        }
3336        None
3337    }
3338
3339    pub(super) fn parse_arm(&mut self) -> PResult<'a, Arm> {
3340        let attrs = self.parse_outer_attributes()?;
3341        self.collect_tokens(None, attrs, ForceCollect::No, |this, attrs| {
3342            let lo = this.token.span;
3343            let (pat, guard) = this.parse_match_arm_pat_and_guard()?;
3344            let pat = Box::new(pat);
3345
3346            let span_before_body = this.prev_token.span;
3347            let arm_body;
3348            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));
3349            let is_almost_fat_arrow =
3350                TokenKind::FatArrow.similar_tokens().contains(&this.token.kind);
3351
3352            // this avoids the compiler saying that a `,` or `}` was expected even though
3353            // the pattern isn't a never pattern (and thus an arm body is required)
3354            let armless = (!is_fat_arrow && !is_almost_fat_arrow && pat.could_be_never_pattern())
3355                || #[allow(non_exhaustive_omitted_patterns)] match this.token.kind {
    token::Comma | token::CloseBrace => true,
    _ => false,
}matches!(this.token.kind, token::Comma | token::CloseBrace);
3356
3357            let mut result = if armless {
3358                // A pattern without a body, allowed for never patterns.
3359                arm_body = None;
3360                let span = lo.to(this.prev_token.span);
3361                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| {
3362                    // Don't gate twice
3363                    if !pat.contains_never_pattern() {
3364                        this.psess.gated_spans.gate(sym::never_patterns, span);
3365                    }
3366                    x
3367                })
3368            } else {
3369                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)) {
3370                    // We might have a `=>` -> `=` or `->` typo (issue #89396).
3371                    if is_almost_fat_arrow {
3372                        err.span_suggestion(
3373                            this.token.span,
3374                            "use a fat arrow to start a match arm",
3375                            "=>",
3376                            Applicability::MachineApplicable,
3377                        );
3378                        if #[allow(non_exhaustive_omitted_patterns)] match (&this.prev_token.kind,
        &this.token.kind) {
    (token::DotDotEq, token::Gt) => true,
    _ => false,
}matches!(
3379                            (&this.prev_token.kind, &this.token.kind),
3380                            (token::DotDotEq, token::Gt)
3381                        ) {
3382                            // `error_inclusive_range_match_arrow` handles cases like `0..=> {}`,
3383                            // so we suppress the error here
3384                            err.delay_as_bug();
3385                        } else {
3386                            err.emit();
3387                        }
3388                        this.bump();
3389                    } else {
3390                        return Err(err);
3391                    }
3392                }
3393                let arrow_span = this.prev_token.span;
3394                let arm_start_span = this.token.span;
3395
3396                let attrs = this.parse_outer_attributes()?;
3397                let (expr, _) =
3398                    this.parse_expr_res(Restrictions::STMT_EXPR, attrs).map_err(|mut err| {
3399                        err.span_label(arrow_span, "while parsing the `match` arm starting here");
3400                        err
3401                    })?;
3402
3403                let require_comma =
3404                    !classify::expr_is_complete(&expr) && this.token != token::CloseBrace;
3405
3406                if !require_comma {
3407                    arm_body = Some(expr);
3408                    // Eat a comma if it exists, though.
3409                    let _ = this.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma));
3410                    Ok(Recovered::No)
3411                } else if let Some((span, guar)) =
3412                    this.parse_arm_body_missing_braces(&expr, arrow_span)
3413                {
3414                    let body = this.mk_expr_err(span, guar);
3415                    arm_body = Some(body);
3416                    Ok(Recovered::Yes(guar))
3417                } else {
3418                    let expr_span = expr.span;
3419                    arm_body = Some(expr);
3420                    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| {
3421                        if this.token == token::FatArrow {
3422                            let sm = this.psess.source_map();
3423                            if let Ok(expr_lines) = sm.span_to_lines(expr_span)
3424                                && let Ok(arm_start_lines) = sm.span_to_lines(arm_start_span)
3425                                && expr_lines.lines.len() == 2
3426                            {
3427                                if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col {
3428                                    // We check whether there's any trailing code in the parse span,
3429                                    // if there isn't, we very likely have the following:
3430                                    //
3431                                    // X |     &Y => "y"
3432                                    //   |        --    - missing comma
3433                                    //   |        |
3434                                    //   |        arrow_span
3435                                    // X |     &X => "x"
3436                                    //   |      - ^^ self.token.span
3437                                    //   |      |
3438                                    //   |      parsed until here as `"y" & X`
3439                                    err.span_suggestion_short(
3440                                        arm_start_span.shrink_to_hi(),
3441                                        "missing a comma here to end this `match` arm",
3442                                        ",",
3443                                        Applicability::MachineApplicable,
3444                                    );
3445                                } else if arm_start_lines.lines[0].end_col + rustc_span::CharPos(1)
3446                                    == expr_lines.lines[0].end_col
3447                                {
3448                                    // similar to the above, but we may typo a `.` or `/` at the end of the line
3449                                    let comma_span = arm_start_span
3450                                        .shrink_to_hi()
3451                                        .with_hi(arm_start_span.hi() + rustc_span::BytePos(1));
3452                                    if let Ok(res) = sm.span_to_snippet(comma_span)
3453                                        && (res == "." || res == "/")
3454                                    {
3455                                        err.span_suggestion_short(
3456                                            comma_span,
3457                                            "you might have meant to write a `,` to end this `match` arm",
3458                                            ",",
3459                                            Applicability::MachineApplicable,
3460                                        );
3461                                    }
3462                                }
3463                            }
3464                        } else {
3465                            err.span_label(
3466                                arrow_span,
3467                                "while parsing the `match` arm starting here",
3468                            );
3469                        }
3470                        err
3471                    })
3472                }
3473            };
3474
3475            let hi_span = arm_body.as_ref().map_or(span_before_body, |body| body.span);
3476            let arm_span = lo.to(hi_span);
3477
3478            // We want to recover:
3479            // X |     Some(_) => foo()
3480            //   |                     - missing comma
3481            // X |     None => "x"
3482            //   |     ^^^^ self.token.span
3483            // as well as:
3484            // X |     Some(!)
3485            //   |            - missing comma
3486            // X |     None => "x"
3487            //   |     ^^^^ self.token.span
3488            // But we musn't recover
3489            // X |     pat[0] => {}
3490            //   |        ^ self.token.span
3491            let recover_missing_comma = arm_body.is_some() || pat.could_be_never_pattern();
3492            if recover_missing_comma {
3493                result = result.or_else(|err| {
3494                    // FIXME(compiler-errors): We could also recover `; PAT =>` here
3495
3496                    // Try to parse a following `PAT =>`, if successful
3497                    // then we should recover.
3498                    let mut snapshot = this.create_snapshot_for_diagnostic();
3499                    let pattern_follows = snapshot
3500                        .parse_pat_no_top_guard(
3501                            None,
3502                            RecoverComma::Yes,
3503                            RecoverColon::Yes,
3504                            CommaRecoveryMode::EitherTupleOrPipe,
3505                        )
3506                        .map_err(|err| err.cancel())
3507                        .is_ok();
3508                    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)) {
3509                        err.cancel();
3510                        let guar = this.dcx().emit_err(diagnostics::MissingCommaAfterMatchArm {
3511                            span: arm_span.shrink_to_hi(),
3512                        });
3513                        return Ok(Recovered::Yes(guar));
3514                    }
3515                    Err(err)
3516                });
3517            }
3518            result?;
3519
3520            Ok((
3521                ast::Arm {
3522                    attrs,
3523                    pat,
3524                    guard,
3525                    body: arm_body,
3526                    span: arm_span,
3527                    id: DUMMY_NODE_ID,
3528                    is_placeholder: false,
3529                },
3530                Trailing::No,
3531                UsePreAttrPos::No,
3532            ))
3533        })
3534    }
3535
3536    pub(crate) fn eat_metavar_guard(&mut self) -> Option<Box<Guard>> {
3537        self.eat_metavar_seq(MetaVarKind::Guard, |this| {
3538            this.expect_match_arm_guard(ForceCollect::Yes)
3539        })
3540    }
3541
3542    fn parse_match_arm_guard(&mut self) -> PResult<'a, Option<Box<Guard>>> {
3543        if let Some(guard) = self.eat_metavar_guard() {
3544            return Ok(Some(guard));
3545        }
3546
3547        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)) {
3548            // No match arm guard present.
3549            return Ok(None);
3550        }
3551        self.expect_match_arm_guard_cond(ForceCollect::No).map(Some)
3552    }
3553
3554    pub(crate) fn expect_match_arm_guard(
3555        &mut self,
3556        force_collect: ForceCollect,
3557    ) -> PResult<'a, Box<Guard>> {
3558        if let Some(guard) = self.eat_metavar_guard() {
3559            return Ok(guard);
3560        }
3561
3562        self.expect_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::If,
    token_type: crate::parser::token_type::TokenType::KwIf,
}exp!(If))?;
3563        self.expect_match_arm_guard_cond(force_collect)
3564    }
3565
3566    fn expect_match_arm_guard_cond(
3567        &mut self,
3568        force_collect: ForceCollect,
3569    ) -> PResult<'a, Box<Guard>> {
3570        let leading_if_span = self.prev_token.span;
3571
3572        let mut cond = self.parse_match_guard_condition(force_collect)?;
3573        let cond_span = cond.span;
3574
3575        CondChecker::new(self, LetChainsPolicy::AlwaysAllowed).visit_expr(&mut cond);
3576
3577        let guard = Guard { cond: *cond, span_with_leading_if: leading_if_span.to(cond_span) };
3578        Ok(Box::new(guard))
3579    }
3580
3581    fn parse_match_arm_pat_and_guard(&mut self) -> PResult<'a, (Pat, Option<Box<Guard>>)> {
3582        if self.token == token::OpenParen {
3583            let left = self.token.span;
3584            let pat = self.parse_pat_no_top_guard(
3585                None,
3586                RecoverComma::Yes,
3587                RecoverColon::Yes,
3588                CommaRecoveryMode::EitherTupleOrPipe,
3589            )?;
3590            if let ast::PatKind::Paren(subpat) = &pat.kind
3591                && let ast::PatKind::Guard(..) = &subpat.kind
3592            {
3593                // Detect and recover from `($pat if $cond) => $arm`.
3594                // FIXME(guard_patterns): convert this to a normal guard instead
3595                let span = pat.span;
3596                let ast::PatKind::Paren(subpat) = pat.kind else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
3597                let ast::PatKind::Guard(_, mut guard) = subpat.kind else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
3598                self.psess.gated_spans.ungate_last(sym::guard_patterns, guard.span());
3599                let mut checker = CondChecker::new(self, LetChainsPolicy::AlwaysAllowed);
3600                checker.visit_expr(&mut guard.cond);
3601
3602                let right = self.prev_token.span;
3603                self.dcx().emit_err(diagnostics::ParenthesesInMatchPat {
3604                    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],
3605                    sugg: diagnostics::ParenthesesInMatchPatSugg { left, right },
3606                });
3607
3608                if let Some(guar) = checker.found_incorrect_let_chain {
3609                    guard.cond = *self.mk_expr_err(guard.span(), guar);
3610                }
3611                Ok((self.mk_pat(span, ast::PatKind::Wild), Some(guard)))
3612            } else {
3613                Ok((pat, self.parse_match_arm_guard()?))
3614            }
3615        } else {
3616            // Regular parser flow:
3617            let pat = self.parse_pat_no_top_guard(
3618                None,
3619                RecoverComma::Yes,
3620                RecoverColon::Yes,
3621                CommaRecoveryMode::EitherTupleOrPipe,
3622            )?;
3623            Ok((pat, self.parse_match_arm_guard()?))
3624        }
3625    }
3626
3627    fn parse_match_guard_condition(
3628        &mut self,
3629        force_collect: ForceCollect,
3630    ) -> PResult<'a, Box<Expr>> {
3631        let attrs = self.parse_outer_attributes()?;
3632        let expr = self.collect_tokens(
3633            None,
3634            AttrWrapper::empty(),
3635            force_collect,
3636            |this, _empty_attrs| {
3637                match this
3638                    .parse_expr_res(Restrictions::ALLOW_LET | Restrictions::IN_IF_GUARD, attrs)
3639                {
3640                    Ok((expr, _)) => Ok((expr, Trailing::No, UsePreAttrPos::No)),
3641                    Err(mut err) => {
3642                        if this.prev_token == token::OpenBrace {
3643                            let sugg_sp = this.prev_token.span.shrink_to_lo();
3644                            // Consume everything within the braces, let's avoid further parse
3645                            // errors.
3646                            this.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
3647                            let msg =
3648                                "you might have meant to start a match arm after the match guard";
3649                            if this.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseBrace,
    token_type: crate::parser::token_type::TokenType::CloseBrace,
}exp!(CloseBrace)) {
3650                                let applicability = if this.token != token::FatArrow {
3651                                    // We have high confidence that we indeed didn't have a struct
3652                                    // literal in the match guard, but rather we had some operation
3653                                    // that ended in a path, immediately followed by a block that was
3654                                    // meant to be the match arm.
3655                                    Applicability::MachineApplicable
3656                                } else {
3657                                    Applicability::MaybeIncorrect
3658                                };
3659                                err.span_suggestion_verbose(sugg_sp, msg, "=> ", applicability);
3660                            }
3661                        }
3662                        Err(err)
3663                    }
3664                }
3665            },
3666        )?;
3667        Ok(expr)
3668    }
3669
3670    pub(crate) fn is_builtin(&self) -> bool {
3671        self.token.is_keyword(kw::Builtin) && self.look_ahead(1, |t| *t == token::Pound)
3672    }
3673
3674    /// Parses a `try {...}` or `try bikeshed Ty {...}` expression (`try` token already eaten).
3675    fn parse_try_block(&mut self, span_lo: Span) -> PResult<'a, Box<Expr>> {
3676        let annotation =
3677            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 };
3678
3679        let (attrs, body) = self.parse_inner_attrs_and_block(None)?;
3680        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)) {
3681            Err(self.dcx().create_err(diagnostics::CatchAfterTry { span: self.prev_token.span }))
3682        } else {
3683            let span = span_lo.to(body.span);
3684            let gate_sym =
3685                if annotation.is_none() { sym::try_blocks } else { sym::try_blocks_heterogeneous };
3686            self.psess.gated_spans.gate(gate_sym, span);
3687            Ok(self.mk_expr_with_attrs(span, ExprKind::TryBlock(body, annotation), attrs))
3688        }
3689    }
3690
3691    fn is_do_catch_block(&self) -> bool {
3692        self.token.is_keyword(kw::Do)
3693            && self.is_keyword_ahead(1, &[kw::Catch])
3694            && self.look_ahead(2, |t| *t == token::OpenBrace || t.is_metavar_block())
3695            && !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
3696    }
3697
3698    fn is_do_yeet(&self) -> bool {
3699        self.token.is_keyword(kw::Do) && self.is_keyword_ahead(1, &[kw::Yeet])
3700    }
3701
3702    fn is_try_block(&self) -> bool {
3703        self.token.is_keyword(kw::Try)
3704            && self.look_ahead(1, |t| {
3705                *t == token::OpenBrace
3706                    || t.is_metavar_block()
3707                    || t.kind == TokenKind::Ident(sym::bikeshed, IdentIsRaw::No)
3708            })
3709            && self.token_uninterpolated_span().at_least_rust_2018()
3710    }
3711
3712    /// Parses an `async move? {...}` or `gen move? {...}` expression.
3713    fn parse_gen_block(&mut self) -> PResult<'a, Box<Expr>> {
3714        let lo = self.token.span;
3715        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)) {
3716            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 }
3717        } else {
3718            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)));
3719            GenBlockKind::Gen
3720        };
3721        match kind {
3722            GenBlockKind::Async => {
3723                // `async` blocks are stable
3724            }
3725            GenBlockKind::Gen | GenBlockKind::AsyncGen => {
3726                self.psess.gated_spans.gate(sym::gen_blocks, lo.to(self.prev_token.span));
3727            }
3728        }
3729        let capture_clause = self.parse_capture_clause()?;
3730        let decl_span = lo.to(self.prev_token.span);
3731        let (attrs, body) = self.parse_inner_attrs_and_block(None)?;
3732        let kind = ExprKind::Gen(capture_clause, body, kind, decl_span);
3733        Ok(self.mk_expr_with_attrs(lo.to(self.prev_token.span), kind, attrs))
3734    }
3735
3736    fn is_gen_block(&self, kw: Symbol, lookahead: usize) -> bool {
3737        self.is_keyword_ahead(lookahead, &[kw])
3738            && ((
3739                // `async move {`
3740                self.is_keyword_ahead(lookahead + 1, &[kw::Move, kw::Use])
3741                    && self.look_ahead(lookahead + 2, |t| {
3742                        *t == token::OpenBrace || t.is_metavar_block()
3743                    })
3744            ) || (
3745                // `async {`
3746                self.look_ahead(lookahead + 1, |t| *t == token::OpenBrace || t.is_metavar_block())
3747            ))
3748    }
3749
3750    pub(super) fn is_async_gen_block(&self) -> bool {
3751        self.token.is_keyword(kw::Async) && self.is_gen_block(kw::Gen, 1)
3752    }
3753
3754    fn is_likely_struct_lit(&self) -> bool {
3755        // `{ ident, ` and `{ ident: ` cannot start a block.
3756        self.look_ahead(1, |t| t.is_ident())
3757            && self.look_ahead(2, |t| t == &token::Comma || t == &token::Colon)
3758    }
3759
3760    fn maybe_parse_struct_expr(
3761        &mut self,
3762        qself: &Option<Box<ast::QSelf>>,
3763        path: &ast::Path,
3764    ) -> Option<PResult<'a, Box<Expr>>> {
3765        let struct_allowed = !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
3766        match (struct_allowed, self.is_likely_struct_lit()) {
3767            // A struct literal isn't expected and one is pretty much assured not to be present. The
3768            // only situation that isn't detected is when a struct with a single field was attempted
3769            // in a place where a struct literal wasn't expected, but regular parser errors apply.
3770            // Happy path.
3771            (false, false) => None,
3772            (true, _) => {
3773                // A struct is accepted here, try to parse it and rely on `parse_expr_struct` for
3774                // any kind of recovery. Happy path.
3775                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)) {
3776                    return Some(Err(err));
3777                }
3778                Some(self.parse_expr_struct(qself.clone(), path.clone(), true))
3779            }
3780            (false, true) => {
3781                // We have something like `match foo { bar,` or `match foo { bar:`, which means the
3782                // user might have meant to write a struct literal as part of the `match`
3783                // discriminant. This is done purely for error recovery.
3784                let snapshot = self.create_snapshot_for_diagnostic();
3785                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)) {
3786                    return Some(Err(err));
3787                }
3788                match self.parse_expr_struct(qself.clone(), path.clone(), false) {
3789                    Ok(expr) => {
3790                        // This is a struct literal, but we don't accept them here.
3791                        self.dcx().emit_err(diagnostics::StructLiteralNotAllowedHere {
3792                            span: expr.span,
3793                            sub: diagnostics::StructLiteralNotAllowedHereSugg {
3794                                left: path.span.shrink_to_lo(),
3795                                right: expr.span.shrink_to_hi(),
3796                            },
3797                        });
3798                        Some(Ok(expr))
3799                    }
3800                    Err(err) => {
3801                        // We couldn't parse a valid struct, rollback and let the parser emit an
3802                        // error elsewhere.
3803                        err.cancel();
3804                        self.restore_snapshot(snapshot);
3805                        None
3806                    }
3807                }
3808            }
3809        }
3810    }
3811
3812    fn maybe_recover_bad_struct_literal_path(
3813        &mut self,
3814        is_underscore_entry_point: bool,
3815    ) -> PResult<'a, Option<Box<Expr>>> {
3816        if self.may_recover()
3817            && self.check_noexpect(&token::OpenBrace)
3818            && (!self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
3819                && self.is_likely_struct_lit())
3820        {
3821            let span = if is_underscore_entry_point {
3822                self.prev_token.span
3823            } else {
3824                self.token.span.shrink_to_lo()
3825            };
3826
3827            self.bump(); // {
3828            let expr = self.parse_expr_struct(
3829                None,
3830                Path::from_ident(Ident::new(kw::Underscore, span)),
3831                false,
3832            )?;
3833
3834            let guar = if is_underscore_entry_point {
3835                self.dcx().create_err(diagnostics::StructLiteralPlaceholderPath { span }).emit()
3836            } else {
3837                self.dcx()
3838                    .create_err(diagnostics::StructLiteralWithoutPathLate {
3839                        span: expr.span,
3840                        suggestion_span: expr.span.shrink_to_lo(),
3841                    })
3842                    .emit()
3843            };
3844
3845            Ok(Some(self.mk_expr_err(expr.span, guar)))
3846        } else {
3847            Ok(None)
3848        }
3849    }
3850
3851    pub(super) fn parse_struct_fields(
3852        &mut self,
3853        pth: ast::Path,
3854        recover: bool,
3855        close: ExpTokenPair,
3856    ) -> PResult<
3857        'a,
3858        (
3859            ThinVec<ExprField>,
3860            ast::StructRest,
3861            Option<ErrorGuaranteed>, /* async blocks are forbidden in Rust 2015 */
3862        ),
3863    > {
3864        let mut fields = ThinVec::new();
3865        let mut base = ast::StructRest::None;
3866        let mut recovered_async = None;
3867        let in_if_guard = self.restrictions.contains(Restrictions::IN_IF_GUARD);
3868
3869        let async_block_err = |e: &mut Diag<'_>, span: Span| {
3870            diagnostics::AsyncBlockIn2015 { span }.add_to_diag(e);
3871            diagnostics::HelpUseLatestEdition::new().add_to_diag(e);
3872        };
3873
3874        while self.token != close.tok {
3875            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) {
3876                let exp_span = self.prev_token.span;
3877                // We permit `.. }` on the left-hand side of a destructuring assignment.
3878                if self.check(close) {
3879                    base = ast::StructRest::Rest(self.prev_token.span);
3880                    break;
3881                }
3882                match self.parse_expr() {
3883                    Ok(e) => base = ast::StructRest::Base(e),
3884                    Err(e) if recover => {
3885                        e.emit();
3886                        self.recover_stmt();
3887                    }
3888                    Err(e) => return Err(e),
3889                }
3890                self.recover_struct_comma_after_dotdot(exp_span);
3891                break;
3892            }
3893
3894            // Peek the field's ident before parsing its expr in order to emit better diagnostics.
3895            let peek = self
3896                .token
3897                .ident()
3898                .filter(|(ident, is_raw)| {
3899                    (!ident.is_reserved() || #[allow(non_exhaustive_omitted_patterns)] match is_raw {
    IdentIsRaw::Yes => true,
    _ => false,
}matches!(is_raw, IdentIsRaw::Yes))
3900                        && self.look_ahead(1, |tok| *tok == token::Colon)
3901                })
3902                .map(|(ident, _)| ident);
3903
3904            // We still want a field even if its expr didn't parse.
3905            let field_ident = |this: &Self, guar: ErrorGuaranteed| {
3906                peek.map(|ident| {
3907                    let span = ident.span;
3908                    ExprField {
3909                        ident,
3910                        span,
3911                        expr: this.mk_expr_err(span, guar),
3912                        is_shorthand: false,
3913                        attrs: AttrVec::new(),
3914                        id: DUMMY_NODE_ID,
3915                        is_placeholder: false,
3916                    }
3917                })
3918            };
3919
3920            let parsed_field = match self.parse_expr_field() {
3921                Ok(f) => Ok(f),
3922                Err(mut e) => {
3923                    if pth == kw::Async {
3924                        async_block_err(&mut e, pth.span);
3925                    } else {
3926                        e.span_label(pth.span, "while parsing this struct");
3927                    }
3928
3929                    if let Some((ident, _)) = self.token.ident()
3930                        && !self.token.is_reserved_ident()
3931                        && self.look_ahead(1, |t| {
3932                            AssocOp::from_token(t).is_some()
3933                                || #[allow(non_exhaustive_omitted_patterns)] match t.kind {
    token::OpenParen | token::OpenBracket | token::OpenBrace => true,
    _ => false,
}matches!(
3934                                    t.kind,
3935                                    token::OpenParen | token::OpenBracket | token::OpenBrace
3936                                )
3937                                || *t == token::Dot
3938                        })
3939                    {
3940                        // Looks like they tried to write a shorthand, complex expression,
3941                        // E.g.: `n + m`, `f(a)`, `a[i]`, `S { x: 3 }`, or `x.y`.
3942                        e.span_suggestion_verbose(
3943                            self.token.span.shrink_to_lo(),
3944                            "try naming a field",
3945                            &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: ", ident))
    })format!("{ident}: ",),
3946                            Applicability::MaybeIncorrect,
3947                        );
3948                    }
3949                    if in_if_guard && close.token_type == TokenType::CloseBrace {
3950                        return Err(e);
3951                    }
3952
3953                    if !recover {
3954                        return Err(e);
3955                    }
3956
3957                    let guar = e.emit();
3958                    if pth == kw::Async {
3959                        recovered_async = Some(guar);
3960                    }
3961
3962                    // If we encountered an error which we are recovering from, treat the struct
3963                    // as if it has a `..` in it, because we don’t know what fields the user
3964                    // might have *intended* it to have.
3965                    //
3966                    // This assignment will be overwritten if we actually parse a `..` later.
3967                    //
3968                    // (Note that this code is duplicated between here and below in comma parsing.
3969                    base = ast::StructRest::NoneWithError(guar);
3970
3971                    // If the next token is a comma, then try to parse
3972                    // what comes next as additional fields, rather than
3973                    // bailing out until next `}`.
3974                    if self.token != token::Comma {
3975                        self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
3976                        if self.token != token::Comma {
3977                            break;
3978                        }
3979                    }
3980
3981                    Err(guar)
3982                }
3983            };
3984
3985            let is_shorthand = parsed_field.as_ref().is_ok_and(|f| f.is_shorthand);
3986            // A shorthand field can be turned into a full field with `:`.
3987            // We should point this out.
3988            self.check_or_expected(!is_shorthand, TokenType::Colon);
3989
3990            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]) {
3991                Ok(_) => {
3992                    if let Ok(f) = parsed_field.or_else(|guar| field_ident(self, guar).ok_or(guar))
3993                    {
3994                        // Only include the field if there's no parse error for the field name.
3995                        fields.push(f);
3996                    }
3997                }
3998                Err(mut e) => {
3999                    if pth == kw::Async {
4000                        async_block_err(&mut e, pth.span);
4001                    } else {
4002                        e.span_label(pth.span, "while parsing this struct");
4003                        if peek.is_some() {
4004                            e.span_suggestion(
4005                                self.prev_token.span.shrink_to_hi(),
4006                                "try adding a comma",
4007                                ",",
4008                                Applicability::MachineApplicable,
4009                            );
4010                        }
4011                    }
4012                    if !recover {
4013                        return Err(e);
4014                    }
4015                    let guar = e.emit();
4016                    if pth == kw::Async {
4017                        recovered_async = Some(guar);
4018                    } else if let Some(f) = field_ident(self, guar) {
4019                        fields.push(f);
4020                    }
4021
4022                    // See comment above on this same assignment inside of field parsing.
4023                    base = ast::StructRest::NoneWithError(guar);
4024
4025                    self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
4026                    let _ = self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma));
4027                }
4028            }
4029        }
4030        Ok((fields, base, recovered_async))
4031    }
4032
4033    /// Precondition: already parsed the '{'.
4034    pub(super) fn parse_expr_struct(
4035        &mut self,
4036        qself: Option<Box<ast::QSelf>>,
4037        pth: ast::Path,
4038        recover: bool,
4039    ) -> PResult<'a, Box<Expr>> {
4040        let lo = pth.span;
4041        let (fields, base, recovered_async) =
4042            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))?;
4043        let span = lo.to(self.token.span);
4044        self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseBrace,
    token_type: crate::parser::token_type::TokenType::CloseBrace,
}exp!(CloseBrace))?;
4045        let expr = if let Some(guar) = recovered_async {
4046            ExprKind::Err(guar)
4047        } else {
4048            ExprKind::Struct(Box::new(ast::StructExpr { qself, path: pth, fields, rest: base }))
4049        };
4050        Ok(self.mk_expr(span, expr))
4051    }
4052
4053    fn recover_struct_comma_after_dotdot(&mut self, span: Span) {
4054        if self.token != token::Comma {
4055            return;
4056        }
4057        self.dcx().emit_err(diagnostics::CommaAfterBaseStruct {
4058            span: span.to(self.prev_token.span),
4059            comma: self.token.span,
4060        });
4061        self.recover_stmt();
4062    }
4063
4064    fn recover_struct_field_dots(&mut self, close: &TokenKind) -> bool {
4065        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)) {
4066            // recover from typo of `...`, suggest `..`
4067            let span = self.prev_token.span;
4068            self.dcx().emit_err(diagnostics::MissingDotDot { token_span: span, sugg_span: span });
4069            return true;
4070        }
4071        false
4072    }
4073
4074    /// Converts an ident into 'label and emits an "expected a label, found an identifier" error.
4075    fn recover_ident_into_label(&mut self, ident: Ident) -> Label {
4076        // Convert `label` -> `'label`,
4077        // so that nameres doesn't complain about non-existing label
4078        let label = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\'{0}", ident.name))
    })format!("'{}", ident.name);
4079        let ident = Ident::new(Symbol::intern(&label), ident.span);
4080
4081        self.dcx().emit_err(diagnostics::ExpectedLabelFoundIdent {
4082            span: ident.span,
4083            start: ident.span.shrink_to_lo(),
4084        });
4085
4086        Label { ident }
4087    }
4088
4089    /// Parses `ident (COLON expr)?`.
4090    fn parse_expr_field(&mut self) -> PResult<'a, ExprField> {
4091        let attrs = self.parse_outer_attributes()?;
4092        self.recover_vcs_conflict_marker();
4093        self.collect_tokens(None, attrs, ForceCollect::No, |this, attrs| {
4094            let lo = this.token.span;
4095
4096            // Check if a colon exists one ahead. This means we're parsing a fieldname.
4097            let is_shorthand = !this.look_ahead(1, |t| t == &token::Colon || t == &token::Eq);
4098            // Proactively check whether parsing the field will be incorrect.
4099            let is_wrong = this.token.is_non_reserved_ident()
4100                && !this.look_ahead(1, |t| {
4101                    t == &token::Colon
4102                        || t == &token::Eq
4103                        || t == &token::Comma
4104                        || t == &token::CloseBrace
4105                        || t == &token::CloseParen
4106                });
4107            if is_wrong {
4108                return Err(this.dcx().create_err(diagnostics::ExpectedStructField {
4109                    span: this.look_ahead(1, |t| t.span),
4110                    ident_span: this.token.span,
4111                    token: pprust::token_to_string(&this.look_ahead(1, |t| *t)),
4112                }));
4113            }
4114            let (ident, expr) = if is_shorthand {
4115                // Mimic `x: x` for the `x` field shorthand.
4116                let ident = this.parse_ident_common(false)?;
4117                let path = ast::Path::from_ident(ident);
4118                (ident, this.mk_expr(ident.span, ExprKind::Path(None, path)))
4119            } else {
4120                let ident = this.parse_field_name()?;
4121                this.error_on_eq_field_init(ident);
4122                this.bump(); // `:`
4123                (ident, this.parse_expr()?)
4124            };
4125
4126            Ok((
4127                ast::ExprField {
4128                    ident,
4129                    span: lo.to(expr.span),
4130                    expr,
4131                    is_shorthand,
4132                    attrs,
4133                    id: DUMMY_NODE_ID,
4134                    is_placeholder: false,
4135                },
4136                Trailing::from(this.token == token::Comma),
4137                UsePreAttrPos::No,
4138            ))
4139        })
4140    }
4141
4142    /// Check for `=`. This means the source incorrectly attempts to
4143    /// initialize a field with an eq rather than a colon.
4144    fn error_on_eq_field_init(&self, field_name: Ident) {
4145        if self.token != token::Eq {
4146            return;
4147        }
4148
4149        self.dcx().emit_err(diagnostics::EqFieldInit {
4150            span: self.token.span,
4151            eq: field_name.span.shrink_to_hi().to(self.token.span),
4152        });
4153    }
4154
4155    fn err_dotdotdot_syntax(&self, span: Span) {
4156        self.dcx().emit_err(diagnostics::DotDotDot { span });
4157    }
4158
4159    fn err_larrow_operator(&self, span: Span) {
4160        self.dcx().emit_err(diagnostics::LeftArrowOperator { span });
4161    }
4162
4163    fn mk_assign_op(&self, assign_op: AssignOp, lhs: Box<Expr>, rhs: Box<Expr>) -> ExprKind {
4164        ExprKind::AssignOp(assign_op, lhs, rhs)
4165    }
4166
4167    fn mk_range(
4168        &mut self,
4169        start: Option<Box<Expr>>,
4170        end: Option<Box<Expr>>,
4171        limits: RangeLimits,
4172    ) -> ExprKind {
4173        if end.is_none() && limits == RangeLimits::Closed {
4174            let guar = self.inclusive_range_with_incorrect_end();
4175            ExprKind::Err(guar)
4176        } else {
4177            ExprKind::Range(start, end, limits)
4178        }
4179    }
4180
4181    fn mk_unary(&self, unop: UnOp, expr: Box<Expr>) -> ExprKind {
4182        ExprKind::Unary(unop, expr)
4183    }
4184
4185    fn mk_binary(&self, binop: BinOp, lhs: Box<Expr>, rhs: Box<Expr>) -> ExprKind {
4186        ExprKind::Binary(binop, lhs, rhs)
4187    }
4188
4189    fn mk_index(&self, expr: Box<Expr>, idx: Box<Expr>, brackets_span: Span) -> ExprKind {
4190        ExprKind::Index(expr, idx, brackets_span)
4191    }
4192
4193    fn mk_call(&self, f: Box<Expr>, args: ThinVec<Box<Expr>>) -> ExprKind {
4194        ExprKind::Call(f, args)
4195    }
4196
4197    fn mk_await_expr(&mut self, self_arg: Box<Expr>, lo: Span) -> Box<Expr> {
4198        let span = lo.to(self.prev_token.span);
4199        let await_expr = self.mk_expr(span, ExprKind::Await(self_arg, self.prev_token.span));
4200        self.recover_from_await_method_call();
4201        await_expr
4202    }
4203
4204    fn mk_use_expr(&mut self, self_arg: Box<Expr>, lo: Span) -> Box<Expr> {
4205        let span = lo.to(self.prev_token.span);
4206        let use_expr = self.mk_expr(span, ExprKind::Use(self_arg, self.prev_token.span));
4207        self.recover_from_use();
4208        use_expr
4209    }
4210
4211    pub(crate) fn mk_expr_with_attrs(
4212        &self,
4213        span: Span,
4214        kind: ExprKind,
4215        attrs: AttrVec,
4216    ) -> Box<Expr> {
4217        Box::new(Expr { kind, span, attrs, id: DUMMY_NODE_ID, tokens: None })
4218    }
4219
4220    pub(crate) fn mk_expr(&self, span: Span, kind: ExprKind) -> Box<Expr> {
4221        self.mk_expr_with_attrs(span, kind, AttrVec::new())
4222    }
4223
4224    pub(super) fn mk_expr_err(&self, span: Span, guar: ErrorGuaranteed) -> Box<Expr> {
4225        self.mk_expr(span, ExprKind::Err(guar))
4226    }
4227
4228    pub(crate) fn mk_unit_expr(&self, span: Span) -> Box<Expr> {
4229        self.mk_expr(span, ExprKind::Tup(Default::default()))
4230    }
4231
4232    pub(crate) fn mk_closure_expr(&self, span: Span, body: Box<Expr>) -> Box<Expr> {
4233        self.mk_expr(
4234            span,
4235            ast::ExprKind::Closure(Box::new(ast::Closure {
4236                binder: rustc_ast::ClosureBinder::NotPresent,
4237                constness: rustc_ast::Const::No,
4238                movability: rustc_ast::Movability::Movable,
4239                capture_clause: rustc_ast::CaptureBy::Ref,
4240                coroutine_kind: None,
4241                fn_decl: Box::new(rustc_ast::FnDecl {
4242                    inputs: Default::default(),
4243                    output: rustc_ast::FnRetTy::Default(span),
4244                }),
4245                fn_arg_span: span,
4246                fn_decl_span: span,
4247                body,
4248            })),
4249        )
4250    }
4251
4252    /// Create expression span ensuring the span of the parent node
4253    /// is larger than the span of lhs and rhs, including the attributes.
4254    fn mk_expr_sp(&self, lhs: &Box<Expr>, lhs_span: Span, op_span: Span, rhs_span: Span) -> Span {
4255        lhs.attrs
4256            .iter()
4257            .find(|a| a.style == AttrStyle::Outer)
4258            .map_or(lhs_span, |a| a.span)
4259            .to(op_span)
4260            .to(rhs_span)
4261    }
4262
4263    fn collect_tokens_for_expr(
4264        &mut self,
4265        attrs: AttrWrapper,
4266        f: impl FnOnce(&mut Self, ast::AttrVec) -> PResult<'a, Box<Expr>>,
4267    ) -> PResult<'a, Box<Expr>> {
4268        self.collect_tokens(None, attrs, ForceCollect::No, |this, attrs| {
4269            let res = f(this, attrs)?;
4270            let trailing = Trailing::from(
4271                this.restrictions.contains(Restrictions::STMT_EXPR)
4272                     && this.token == token::Semi
4273                // FIXME: pass an additional condition through from the place
4274                // where we know we need a comma, rather than assuming that
4275                // `#[attr] expr,` always captures a trailing comma.
4276                || this.token == token::Comma,
4277            );
4278            Ok((res, trailing, UsePreAttrPos::No))
4279        })
4280    }
4281}
4282
4283/// Could this lifetime/label be an unclosed char literal? For example, `'a`
4284/// could be, but `'abc` could not.
4285pub(crate) fn could_be_unclosed_char_literal(ident: Ident) -> bool {
4286    ident.name.as_str().starts_with('\'')
4287        && unescape_char(ident.without_first_quote().name.as_str()).is_ok()
4288}
4289
4290/// Whether let chains are allowed on all editions, or it's edition dependent (allowed only on
4291/// 2024 and later). In case of edition dependence, specify the currently present edition.
4292pub enum LetChainsPolicy {
4293    AlwaysAllowed,
4294    EditionDependent { current_edition: Edition },
4295}
4296
4297/// Visitor to check for invalid use of `ExprKind::Let` that can't
4298/// easily be caught in parsing. For example:
4299///
4300/// ```rust,ignore (example)
4301/// // Only know that the let isn't allowed once the `||` token is reached
4302/// if let Some(x) = y || true {}
4303/// // Only know that the let isn't allowed once the second `=` token is reached.
4304/// if let Some(x) = y && z = 1 {}
4305/// ```
4306struct CondChecker<'a> {
4307    parser: &'a Parser<'a>,
4308    let_chains_policy: LetChainsPolicy,
4309    depth: u32,
4310    forbid_let_reason: Option<diagnostics::ForbiddenLetReason>,
4311    missing_let: Option<diagnostics::MaybeMissingLet>,
4312    comparison: Option<diagnostics::MaybeComparison>,
4313    found_incorrect_let_chain: Option<ErrorGuaranteed>,
4314}
4315
4316impl<'a> CondChecker<'a> {
4317    fn new(parser: &'a Parser<'a>, let_chains_policy: LetChainsPolicy) -> Self {
4318        CondChecker {
4319            parser,
4320            forbid_let_reason: None,
4321            missing_let: None,
4322            comparison: None,
4323            let_chains_policy,
4324            found_incorrect_let_chain: None,
4325            depth: 0,
4326        }
4327    }
4328}
4329
4330impl MutVisitor for CondChecker<'_> {
4331    fn visit_expr(&mut self, e: &mut Expr) {
4332        self.depth += 1;
4333
4334        let span = e.span;
4335        match e.kind {
4336            ExprKind::Let(_, _, _, ref mut recovered @ Recovered::No) => {
4337                if let Some(reason) = self.forbid_let_reason {
4338                    let error = match reason {
4339                        diagnostics::ForbiddenLetReason::NotSupportedOr(or_span) => {
4340                            self.parser.dcx().emit_err(diagnostics::OrInLetChain { span: or_span })
4341                        }
4342                        _ => {
4343                            let guar = self.parser.dcx().emit_err(
4344                                diagnostics::ExpectedExpressionFoundLet {
4345                                    span,
4346                                    reason,
4347                                    missing_let: self.missing_let,
4348                                    comparison: self.comparison,
4349                                },
4350                            );
4351                            if let Some(_) = self.missing_let {
4352                                self.found_incorrect_let_chain = Some(guar);
4353                            }
4354                            guar
4355                        }
4356                    };
4357                    *recovered = Recovered::Yes(error);
4358                } else if self.depth > 1 {
4359                    // Top level `let` is always allowed; only gate chains
4360                    match self.let_chains_policy {
4361                        LetChainsPolicy::AlwaysAllowed => (),
4362                        LetChainsPolicy::EditionDependent { current_edition } => {
4363                            if !current_edition.at_least_rust_2024() || !span.at_least_rust_2024() {
4364                                self.parser.dcx().emit_err(diagnostics::LetChainPre2024 { span });
4365                            }
4366                        }
4367                    }
4368                }
4369            }
4370            ExprKind::Binary(Spanned { node: BinOpKind::And, .. }, _, _) => {
4371                mut_visit::walk_expr(self, e);
4372            }
4373            ExprKind::Binary(Spanned { node: BinOpKind::Or, span: or_span }, _, _)
4374                if let None | Some(diagnostics::ForbiddenLetReason::NotSupportedOr(_)) =
4375                    self.forbid_let_reason =>
4376            {
4377                let forbid_let_reason = self.forbid_let_reason;
4378                self.forbid_let_reason =
4379                    Some(diagnostics::ForbiddenLetReason::NotSupportedOr(or_span));
4380                mut_visit::walk_expr(self, e);
4381                self.forbid_let_reason = forbid_let_reason;
4382            }
4383            ExprKind::Paren(ref inner)
4384                if let None | Some(diagnostics::ForbiddenLetReason::NotSupportedParentheses(_)) =
4385                    self.forbid_let_reason =>
4386            {
4387                let forbid_let_reason = self.forbid_let_reason;
4388                self.forbid_let_reason =
4389                    Some(diagnostics::ForbiddenLetReason::NotSupportedParentheses(inner.span));
4390                mut_visit::walk_expr(self, e);
4391                self.forbid_let_reason = forbid_let_reason;
4392            }
4393            ExprKind::Assign(ref lhs, ref rhs, span) => {
4394                if let ExprKind::Call(_, _) = &lhs.kind {
4395                    fn get_path_from_rhs(e: &Expr) -> Option<(u32, &Path)> {
4396                        fn inner(e: &Expr, depth: u32) -> Option<(u32, &Path)> {
4397                            match &e.kind {
4398                                ExprKind::Binary(_, lhs, _) => inner(lhs, depth + 1),
4399                                ExprKind::Path(_, path) => Some((depth, path)),
4400                                _ => None,
4401                            }
4402                        }
4403
4404                        inner(e, 0)
4405                    }
4406
4407                    if let Some((depth, path)) = get_path_from_rhs(rhs) {
4408                        // For cases like if Some(_) = x && let Some(_) = y && let Some(_) = z
4409                        // This return let Some(_) = y expression
4410                        fn find_let_some(expr: &Expr) -> Option<&Expr> {
4411                            match &expr.kind {
4412                                ExprKind::Let(..) => Some(expr),
4413
4414                                ExprKind::Binary(op, lhs, rhs) if op.node == BinOpKind::And => {
4415                                    find_let_some(lhs).or_else(|| find_let_some(rhs))
4416                                }
4417
4418                                _ => None,
4419                            }
4420                        }
4421
4422                        let expr_span = lhs.span.to(path.span);
4423
4424                        if let Some(later_rhs) = find_let_some(rhs)
4425                            && depth > 0
4426                        {
4427                            let guar =
4428                                self.parser.dcx().emit_err(diagnostics::LetChainMissingLet {
4429                                    span: lhs.span,
4430                                    label_span: expr_span,
4431                                    rhs_span: later_rhs.span,
4432                                    sug_span: lhs.span.shrink_to_lo(),
4433                                });
4434
4435                            self.found_incorrect_let_chain = Some(guar);
4436                        }
4437                    }
4438                }
4439
4440                let forbid_let_reason = self.forbid_let_reason;
4441                self.forbid_let_reason = Some(diagnostics::ForbiddenLetReason::OtherForbidden);
4442                let missing_let = self.missing_let;
4443                if let ExprKind::Binary(_, _, rhs) = &lhs.kind
4444                    && let ExprKind::Path(_, _)
4445                    | ExprKind::Struct(_)
4446                    | ExprKind::Call(_, _)
4447                    | ExprKind::Array(_) = rhs.kind
4448                {
4449                    self.missing_let =
4450                        Some(diagnostics::MaybeMissingLet { span: rhs.span.shrink_to_lo() });
4451                }
4452                let comparison = self.comparison;
4453                self.comparison = Some(diagnostics::MaybeComparison { span: span.shrink_to_hi() });
4454                mut_visit::walk_expr(self, e);
4455                self.forbid_let_reason = forbid_let_reason;
4456                self.missing_let = missing_let;
4457                self.comparison = comparison;
4458            }
4459            ExprKind::Unary(_, _)
4460            | ExprKind::Await(_, _)
4461            | ExprKind::Move(_, _)
4462            | ExprKind::Use(_, _)
4463            | ExprKind::AssignOp(_, _, _)
4464            | ExprKind::Range(_, _, _)
4465            | ExprKind::Try(_)
4466            | ExprKind::AddrOf(_, _, _)
4467            | ExprKind::Binary(_, _, _)
4468            | ExprKind::Field(_, _)
4469            | ExprKind::Index(_, _, _)
4470            | ExprKind::Call(_, _)
4471            | ExprKind::MethodCall(_)
4472            | ExprKind::Tup(_)
4473            | ExprKind::Paren(_) => {
4474                let forbid_let_reason = self.forbid_let_reason;
4475                self.forbid_let_reason = Some(diagnostics::ForbiddenLetReason::OtherForbidden);
4476                mut_visit::walk_expr(self, e);
4477                self.forbid_let_reason = forbid_let_reason;
4478            }
4479            ExprKind::Cast(ref mut op, _)
4480            | ExprKind::Type(ref mut op, _)
4481            | ExprKind::UnsafeBinderCast(_, ref mut op, _) => {
4482                let forbid_let_reason = self.forbid_let_reason;
4483                self.forbid_let_reason = Some(diagnostics::ForbiddenLetReason::OtherForbidden);
4484                self.visit_expr(op);
4485                self.forbid_let_reason = forbid_let_reason;
4486            }
4487            ExprKind::Let(_, _, _, Recovered::Yes(_))
4488            | ExprKind::Array(_)
4489            | ExprKind::ConstBlock(_)
4490            | ExprKind::Lit(_)
4491            | ExprKind::If(_, _, _)
4492            | ExprKind::While(_, _, _)
4493            | ExprKind::ForLoop { .. }
4494            | ExprKind::Loop(_, _, _)
4495            | ExprKind::Match(_, _, _)
4496            | ExprKind::Closure(_)
4497            | ExprKind::Block(_, _)
4498            | ExprKind::Gen(_, _, _, _)
4499            | ExprKind::TryBlock(_, _)
4500            | ExprKind::Underscore
4501            | ExprKind::Path(_, _)
4502            | ExprKind::Break(_, _)
4503            | ExprKind::Continue(_)
4504            | ExprKind::Ret(_)
4505            | ExprKind::InlineAsm(_)
4506            | ExprKind::OffsetOf(_, _)
4507            | ExprKind::MacCall(_)
4508            | ExprKind::Struct(_)
4509            | ExprKind::Repeat(_, _)
4510            | ExprKind::Yield(_)
4511            | ExprKind::Yeet(_)
4512            | ExprKind::Become(_)
4513            | ExprKind::IncludedBytes(_)
4514            | ExprKind::FormatArgs(_)
4515            | ExprKind::Err(_)
4516            | ExprKind::DirectConstArg(_)
4517            | ExprKind::Dummy => {
4518                // These would forbid any let expressions they contain already.
4519            }
4520        }
4521        self.depth -= 1;
4522    }
4523}