Skip to main content

rustc_parse/parser/
expr.rs

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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