Skip to main content

rustc_parse/parser/
expr.rs

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