Skip to main content

rustc_parse/parser/
expr.rs

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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