Skip to main content

rustc_parse/parser/
expr.rs

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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