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