Skip to main content

rustc_parse/parser/
expr.rs

1// ignore-tidy-file-filelength
2
3use core::mem;
4use core::ops::{Bound, ControlFlow};
5
6use ast::mut_visit::{self, MutVisitor};
7use ast::token::IdentKind;
8use ast::{ForLoopKind, MatchKind, Pat, Path, PathSegment, Recovered};
9use rustc_ast::token::{self, Delimiter, InvisibleOrigin, MetaVarKind, Token, TokenKind};
10use rustc_ast::util::case::Case;
11use rustc_ast::util::classify;
12use rustc_ast::util::parser::{AssocOp, ExprPrecedence, Fixity, prec_let_scrutinee_needs_par};
13use rustc_ast::visit::{Visitor, walk_expr};
14use rustc_ast::{
15    self as ast, AnonConst, Arm, AssignOp, AssignOpKind, AttrStyle, AttrVec, BinOp, BinOpKind,
16    BlockCheckMode, CaptureBy, ClosureBinder, CoroutineKind, DUMMY_NODE_ID, Expr, ExprField,
17    ExprKind, FnDecl, FnRetTy, ForLoop, Guard, Label, MacCall, MetaItemLit, Movability, Param,
18    RangeLimits, StmtKind, Ty, TyKind, UnOp, UnsafeBinderCastKind, YieldKind,
19};
20use rustc_ast_pretty::pprust;
21use rustc_errors::{Applicability, Diag, PResult, StashKey, Subdiagnostic};
22use rustc_lint_defs::builtin::BREAK_WITH_LABEL_AND_LOOP;
23use rustc_literal_escaper::unescape_char;
24use rustc_session::diagnostics::report_lit_error;
25use rustc_span::edition::Edition;
26use rustc_span::{BytePos, ErrorGuaranteed, Ident, Pos, Span, Spanned, Symbol, kw, respan, sym};
27use thin_vec::{ThinVec, thin_vec};
28use tracing::instrument;
29
30use super::diagnostics::SnapshotParser;
31use super::pat::{CommaRecoveryMode, Expected, RecoverColon, RecoverComma};
32use super::ty::{AllowPlus, RecoverQPath, RecoverReturnSign};
33use super::{
34    AttrWrapper, BlockMode, ClosureSpans, ExpTokenPair, ForceCollect, Parser, PathStyle,
35    Restrictions, SemiColonMode, SeqSep, TokenType, Trailing, UsePreAttrPos,
36};
37use crate::{exp, maybe_recover_from_interpolated_ty_qpath};
38
39pub(super) mod diagnostics;
40
41#[derive(#[automatically_derived]impl ::core::fmt::Debug for DestructuredFloat {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Single(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "Single", __self_0, &__self_1),
            Self::TrailingDot(__self_0, __self_1, __self_2) =>
                ::core::fmt::Formatter::debug_struct_field3_finish(f,
                    "TrailingDot", __self_0, __self_1, &__self_2),
            Self::MiddleDot(__self_0, __self_1, __self_2, __self_3, __self_4)
                =>
                ::core::fmt::Formatter::debug_struct_field5_finish(f,
                    "MiddleDot", __self_0, __self_1, __self_2, __self_3,
                    &__self_4),
            Self::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        self.parse_expr_res(Restrictions::empty())
59    }
60    #[inline]
61    pub fn parse_expr_in_let(&mut self) -> PResult<'a, Box<Expr>> {
62        self.current_closure.take();
63        self.parse_expr_res(Restrictions::IN_LET)
64    }
65    /// Parses an expression, forcing tokens to be collected.
66    pub fn parse_expr_force_collect(&mut self) -> PResult<'a, Box<Expr>> {
67        self.current_closure.take();
68
69        // If the expression is associative (e.g. `1 + 2`), then any preceding
70        // outer attribute actually belongs to the first inner sub-expression.
71        // In which case we must use the pre-attr pos to include the attribute
72        // in the collected tokens for the outer expression.
73        let pre_attr_pos = self.collect_pos();
74        let attrs = self.parse_outer_attributes()?;
75        self.collect_tokens(
76            Some(pre_attr_pos),
77            AttrWrapper::empty(),
78            ForceCollect::Yes,
79            |this, _empty_attrs| {
80                let (expr, is_assoc) =
81                    this.parse_expr_res_after_attrs(Restrictions::empty(), attrs)?;
82                let use_pre_attr_pos =
83                    if is_assoc { UsePreAttrPos::Yes } else { UsePreAttrPos::No };
84                Ok((expr, Trailing::No, use_pre_attr_pos))
85            },
86        )
87    }
88
89    pub fn parse_expr_anon_const(&mut self) -> PResult<'a, AnonConst> {
90        self.parse_expr().map(|value| AnonConst { id: DUMMY_NODE_ID, value })
91    }
92
93    /// Parses a sequence of expressions delimited by parentheses.
94    fn parse_expr_paren_seq(&mut self) -> PResult<'a, ThinVec<Box<Expr>>> {
95        self.parse_paren_comma_seq(Self::parse_expr).map(|(r, _)| r)
96    }
97
98    /// Parses an expression, subject to the given restrictions.
99    #[inline]
100    pub(super) fn parse_expr_res(&mut self, r: Restrictions) -> PResult<'a, Box<Expr>> {
101        let attrs = self.parse_outer_attributes()?;
102        self.parse_expr_res_after_attrs(r, attrs).map(|(expr, _)| expr)
103    }
104
105    /// Same as `parse_expr_res`, but with attributes already pre-parsed.
106    /// The `bool` in the return value indicates if it was an assoc expr, i.e. with an operator
107    /// followed by a subexpression (e.g. `1 + 2`).
108    #[inline]
109    pub(super) fn parse_expr_res_after_attrs(
110        &mut self,
111        r: Restrictions,
112        attrs: AttrWrapper,
113    ) -> PResult<'a, (Box<Expr>, bool)> {
114        self.with_res(r, |this| this.parse_expr_assoc_after_attrs(Bound::Unbounded, attrs))
115    }
116
117    /// Parses an associative expression with operators of at least `min_prec` precedence.
118    pub(super) fn parse_expr_assoc(
119        &mut self,
120        min_prec: Bound<ExprPrecedence>,
121    ) -> PResult<'a, Box<Expr>> {
122        let attrs = self.parse_outer_attributes()?;
123        self.parse_expr_assoc_after_attrs(min_prec, attrs).map(|(expr, _)| expr)
124    }
125
126    /// Same as `parse_expr_assoc`, but with attributes already pre-parsed.
127    /// The `bool` in the return value indicates if it was an assoc expr, i.e. with an operator
128    /// followed by a subexpression (e.g. `1 + 2`).
129    pub(super) fn parse_expr_assoc_after_attrs(
130        &mut self,
131        min_prec: Bound<ExprPrecedence>,
132        attrs: AttrWrapper,
133    ) -> PResult<'a, (Box<Expr>, bool)> {
134        let lhs = if self.token.is_range_separator() {
135            return self.parse_expr_prefix_range(attrs).map(|res| (res, false));
136        } else {
137            self.parse_expr_prefix(attrs)?
138        };
139        self.parse_expr_assoc_rest(min_prec, false, lhs)
140    }
141
142    /// Parses the rest of an associative expression (i.e. the part after the lhs) with operators
143    /// of at least `min_prec` precedence. The `bool` in the return value indicates if something
144    /// was actually parsed.
145    pub(super) fn parse_expr_assoc_rest(
146        &mut self,
147        min_prec: Bound<ExprPrecedence>,
148        starts_stmt: bool,
149        mut lhs: Box<Expr>,
150    ) -> PResult<'a, (Box<Expr>, bool)> {
151        let mut parsed_something = false;
152        if self.expr_is_complete(&lhs) && !self.recover_from_bin_op_after_complete_stmt_expr(&lhs) {
153            return Ok((lhs, parsed_something));
154        }
155
156        self.expected_token_types.insert(TokenType::Operator);
157        while let Some(op) = self.check_assoc_op() {
158            let lhs_span = self.interpolated_or_expr_span(&lhs);
159            let restrictions = if op.node.is_assign_like() {
160                self.restrictions & Restrictions::NO_STRUCT_LITERAL
161            } else {
162                self.restrictions
163            };
164            let prec = op.node.precedence();
165            if match min_prec {
166                Bound::Included(min_prec) => prec < min_prec,
167                Bound::Excluded(min_prec) => prec <= min_prec,
168                Bound::Unbounded => false,
169            } {
170                break;
171            }
172
173            self.reject_dotdotdot_expr_op();
174            self.reject_larrow_expr_op();
175
176            parsed_something = true;
177            self.bump();
178
179            if op.node.is_comparison()
180                && let Some(expr) = self.check_no_chained_comparison(&lhs, &op)?
181            {
182                return Ok((expr, parsed_something));
183            }
184
185            self.recover_from_strict_eq_op(op);
186            self.recover_from_diamond_ne_op();
187            self.recover_from_spaceship_cmp_op();
188            self.recover_from_postfix_inc_op(&lhs, starts_stmt)?;
189            self.recover_from_postfix_dec_op(&lhs, starts_stmt)?;
190
191            let min_prec = match op.node.fixity() {
192                Fixity::Right => Bound::Included(prec),
193                Fixity::Left | Fixity::None => Bound::Excluded(prec),
194            };
195
196            let finish_parsing_bin_op = |this: &mut Self| {
197                let rhs = this.with_res(restrictions - Restrictions::STMT_EXPR, |this| {
198                    this.parse_expr_assoc(min_prec)
199                })?;
200                let span = this.mk_expr_sp(&lhs, lhs_span, op.span, rhs.span);
201                Ok((rhs, span))
202            };
203
204            lhs = match op.node {
205                AssocOp::Binary(ast_op) => {
206                    let (rhs, span) = finish_parsing_bin_op(self)?;
207                    self.mk_expr(span, self.mk_binary(respan(op.span, ast_op), lhs, rhs))
208                }
209                AssocOp::AssignOp(aop) => {
210                    let (rhs, span) = finish_parsing_bin_op(self)?;
211                    self.mk_expr(span, self.mk_assign_op(respan(op.span, aop), lhs, rhs))
212                }
213                AssocOp::Assign => {
214                    let (rhs, span) = finish_parsing_bin_op(self)?;
215                    self.mk_expr(span, ExprKind::Assign(lhs, rhs, op.span))
216                }
217                AssocOp::Cast => self.parse_assoc_op_cast(lhs, lhs_span, op.span)?,
218                AssocOp::Range(limits) => self.parse_expr_range(min_prec, lhs, limits, op.span)?,
219            };
220
221            if let AssocOp::Range(_) = op.node {
222                break;
223            }
224        }
225
226        Ok((lhs, parsed_something))
227    }
228
229    /// Possibly translate the current token to an associative operator.
230    /// The method does not advance the current token.
231    pub(super) fn check_assoc_op(&self) -> Option<Spanned<AssocOp>> {
232        let op = AssocOp::from_token(&self.token);
233
234        // When parsing const expressions, stop parsing when encountering `>`.
235        if self.restrictions.contains(Restrictions::CONST_EXPR)
236            && let Some(op) = op
237            && let AssocOp::Binary(BinOpKind::Shr | BinOpKind::Gt | BinOpKind::Ge)
238            | AssocOp::AssignOp(AssignOpKind::ShrAssign) = op
239        {
240            return None;
241        }
242
243        // When recovering patterns as expressions, stop parsing when encountering an
244        // assignment `=`, an alternative `|`, or a range `..`.
245        if self.restrictions.contains(Restrictions::IS_PAT)
246            && let Some(op) = op
247            && let AssocOp::Assign
248            | AssocOp::AssignOp(_)
249            | AssocOp::Binary(BinOpKind::BitOr)
250            | AssocOp::Range(_) = op
251        {
252            return None;
253        }
254
255        if let Some(op) = op {
256            return Some(respan(self.token.span, op));
257        }
258
259        self.recover_from_alpha_logic_bin_op()
260    }
261
262    /// Checks if this expression is a successfully parsed statement.
263    fn expr_is_complete(&self, e: &Expr) -> bool {
264        self.restrictions.contains(Restrictions::STMT_EXPR) && classify::expr_is_complete(e)
265    }
266
267    /// Parses `x..y`, `x..=y`, and `x..`/`x..=`.
268    /// The other two variants are handled in `parse_prefix_range_expr` below.
269    fn parse_expr_range(
270        &mut self,
271        min_prec: Bound<ExprPrecedence>,
272        lhs: Box<Expr>,
273        limits: RangeLimits,
274        cur_op_span: Span,
275    ) -> PResult<'a, Box<Expr>> {
276        let rhs = if self.is_at_start_of_range_notation_rhs() {
277            let maybe_lt = self.token;
278            Some(
279                self.parse_expr_assoc(min_prec)
280                    .map_err(|err| self.maybe_err_dotdotlt_syntax(maybe_lt, err))?,
281            )
282        } else {
283            None
284        };
285        let rhs_span = rhs.as_ref().map_or(cur_op_span, |x| x.span);
286        let span = self.mk_expr_sp(&lhs, lhs.span, cur_op_span, rhs_span);
287        let range = self.mk_range(Some(lhs), rhs, limits);
288        Ok(self.mk_expr(span, range))
289    }
290
291    fn is_at_start_of_range_notation_rhs(&self) -> bool {
292        if self.token.can_begin_expr() {
293            // Parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
294            if self.token == token::OpenBrace {
295                return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
296            }
297            true
298        } else {
299            false
300        }
301    }
302
303    /// Parses prefix-forms of range notation: `..expr`, `..`, `..=expr`.
304    fn parse_expr_prefix_range(&mut self, attrs: AttrWrapper) -> PResult<'a, Box<Expr>> {
305        if !attrs.is_empty() {
306            let err = crate::diagnostics::DotDotRangeAttribute { span: self.token.span };
307            self.dcx().emit_err(err);
308        }
309
310        self.reject_dotdotdot_expr_op();
311
312        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!(
313            self.token.is_range_separator(),
314            "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
315            self.token
316        );
317
318        let limits = match self.token.kind {
319            token::DotDot => RangeLimits::HalfOpen,
320            _ => RangeLimits::Closed,
321        };
322        let op = AssocOp::from_token(&self.token);
323        self.collect_tokens_for_expr(AttrWrapper::empty(), |this, _empty_attrs| {
324            let lo = this.token.span;
325            let maybe_lt = this.look_ahead(1, |t| t.clone());
326            this.bump();
327            let (span, opt_end) = if this.is_at_start_of_range_notation_rhs() {
328                // RHS must be parsed with more associativity than the dots.
329                this.parse_expr_assoc(Bound::Excluded(op.unwrap().precedence()))
330                    .map(|expr| (lo.to(expr.span), Some(expr)))
331                    .map_err(|err| this.maybe_err_dotdotlt_syntax(maybe_lt, err))?
332            } else {
333                (lo, None)
334            };
335            let range = this.mk_range(None, opt_end, limits);
336            Ok(this.mk_expr(span, range))
337        })
338    }
339
340    /// Parses a prefix-unary-operator expr.
341    fn parse_expr_prefix(&mut self, attrs: AttrWrapper) -> PResult<'a, Box<Expr>> {
342        let lo = self.token.span;
343
344        // NOTE: When adding new unary operators, don't forget to adjust TokenKind::can_begin_expr.
345        let parse: fn(&mut Self, _) -> _ = match self.token.uninterpolate().kind {
346            token::Bang => |this, lo| this.parse_expr_unary(lo, UnOp::Not),
347            token::Minus => |this, lo| this.parse_expr_unary(lo, UnOp::Neg),
348            token::Star => |this, lo| this.parse_expr_unary(lo, UnOp::Deref),
349            token::And | token::AndAnd => |this, lo| this.parse_expr_borrow(lo),
350
351            token::Tilde => |this, lo| this.recover_from_tilde_bitwise_neg_op(lo),
352            token::Plus if self.look_ahead(1, |t| t.is_numeric_lit()) => {
353                return self.recover_from_leading_plus_on_expr_lit(lo);
354            }
355            token::Plus if self.look_ahead(1, |t| *t == token::Plus) => {
356                return self.recover_from_prefix_inc_op(attrs);
357            }
358            token::Ident(..) if self.is_mistaken_alpha_logic_un_op() => {
359                |this, lo| this.recover_from_alpha_logic_un_op(lo)
360            }
361
362            _ => return self.parse_expr_dot_or_call(attrs),
363        };
364
365        self.collect_tokens_for_expr(attrs, |this, attrs| {
366            let (hi, kind) = parse(this, lo)?;
367            Ok(this.mk_expr_with_attrs(lo.to(hi), kind, attrs))
368        })
369    }
370
371    fn parse_expr_prefix_common(&mut self, lo: Span) -> PResult<'a, (Span, Box<Expr>)> {
372        let attrs = self.parse_outer_attributes()?;
373        let expr = if self.token.is_range_separator() {
374            self.parse_expr_prefix_range(attrs)
375        } else {
376            self.parse_expr_prefix(attrs)
377        }?;
378        let span = self.interpolated_or_expr_span(&expr);
379        Ok((lo.to(span), expr))
380    }
381
382    fn parse_expr_unary(&mut self, lo: Span, op: UnOp) -> PResult<'a, (Span, ExprKind)> {
383        self.bump(); // `op`
384        let (span, expr) = self.parse_expr_prefix_common(lo)?;
385        Ok((span, self.mk_unary(op, expr)))
386    }
387
388    /// Returns the span of expr if it was not interpolated, or the span of the interpolated token.
389    fn interpolated_or_expr_span(&self, expr: &Expr) -> Span {
390        match self.prev_token.kind {
391            token::NtIdent(..) | token::NtLifetime(..) => self.prev_token.span,
392            token::CloseInvisible(InvisibleOrigin::MetaVar(_)) => {
393                // `expr.span` is the interpolated span, because invisible open
394                // and close delims both get marked with the same span, one
395                // that covers the entire thing between them. (See
396                // `rustc_expand::mbe::transcribe::transcribe`.)
397                self.prev_token.span
398            }
399            _ => expr.span,
400        }
401    }
402
403    fn parse_assoc_op_cast(
404        &mut self,
405        lhs: Box<Expr>,
406        lhs_span: Span,
407        op_span: Span,
408    ) -> PResult<'a, Box<Expr>> {
409        let mk_expr = |this: &mut Self, rhs: Box<Ty>| {
410            let span = this.mk_expr_sp(&lhs, lhs_span, op_span, rhs.span);
411            this.mk_expr(span, ExprKind::Cast(lhs, rhs))
412        };
413
414        // Save the state of the parser before parsing type normally, in case there is a
415        // LessThan comparison after this cast.
416        let parser_snapshot_before_type = self.clone();
417        let cast_expr = match self.parse_as_cast_ty() {
418            Ok(rhs) => mk_expr(self, rhs),
419            Err(type_err) => {
420                if !self.may_recover() {
421                    return Err(type_err);
422                }
423
424                // Rewind to before attempting to parse the type with generics, to recover
425                // from situations like `x as usize < y` in which we first tried to parse
426                // `usize < y` as a type with generic arguments.
427                let parser_snapshot_after_type = mem::replace(self, parser_snapshot_before_type);
428
429                match self.parse_path(PathStyle::Expr) {
430                    Ok(path) => {
431                        let span_after_type = parser_snapshot_after_type.token.span;
432                        let expr =
433                            mk_expr(self, self.mk_ty(path.span, TyKind::Path(None, path.clone())));
434
435                        let args_span = self.look_ahead(1, |t| t.span).to(span_after_type);
436                        match self.token.kind {
437                            token::Lt => self.dcx().emit_err(
438                                crate::diagnostics::ComparisonInterpretedAsGeneric {
439                                    comparison: self.token.span,
440                                    r#type: pprust::path_to_string(&path),
441                                    args: args_span,
442                                    suggestion:
443                                        crate::diagnostics::ComparisonInterpretedAsGenericSugg {
444                                            left: expr.span.shrink_to_lo(),
445                                            right: expr.span.shrink_to_hi(),
446                                        },
447                                },
448                            ),
449                            token::Shl => {
450                                self.dcx().emit_err(crate::diagnostics::ShiftInterpretedAsGeneric {
451                                    shift: self.token.span,
452                                    r#type: pprust::path_to_string(&path),
453                                    args: args_span,
454                                    suggestion: crate::diagnostics::ShiftInterpretedAsGenericSugg {
455                                        left: expr.span.shrink_to_lo(),
456                                        right: expr.span.shrink_to_hi(),
457                                    },
458                                })
459                            }
460                            _ => {
461                                // We can end up here even without `<` being the next token, for
462                                // example because `parse_ty_no_plus` returns `Err` on keywords,
463                                // but `parse_path` returns `Ok` on them due to error recovery.
464                                // Return original error and parser state.
465                                *self = parser_snapshot_after_type;
466                                return Err(type_err);
467                            }
468                        };
469
470                        // Successfully parsed the type path leaving a `<` yet to parse.
471                        type_err.cancel();
472
473                        // Keep `x as usize` as an expression in AST and continue parsing.
474                        expr
475                    }
476                    Err(path_err) => {
477                        // Couldn't parse as a path, return original error and parser state.
478                        path_err.cancel();
479                        *self = parser_snapshot_after_type;
480                        return Err(type_err);
481                    }
482                }
483            }
484        };
485
486        // Try to parse a postfix operator such as `.`, `?`, or index (`[]`)
487        // after a cast. If one is present, emit an error then return a valid
488        // parse tree; For something like `&x as T[0]` will be as if it was
489        // written `((&x) as T)[0]`.
490
491        let span = cast_expr.span;
492        let with_postfix = self.parse_expr_dot_or_call_with(AttrVec::new(), cast_expr, span)?;
493
494        // Check if an illegal postfix operator has been added after the cast.
495        // If the resulting expression is not a cast, it is an illegal postfix operator.
496        if !#[allow(non_exhaustive_omitted_patterns)] match with_postfix.kind {
    ExprKind::Cast(_, _) => true,
    _ => false,
}matches!(with_postfix.kind, ExprKind::Cast(_, _)) {
497            let kind = match with_postfix.kind {
498                ExprKind::Index(..) => "indexing",
499                ExprKind::Try(_) => "`?`",
500                ExprKind::Field(_, _) => "a field access",
501                ExprKind::MethodCall(_) => "a method call",
502                ExprKind::Call(_, _) => "a function call",
503                ExprKind::Await(_, _) => "`.await`",
504                ExprKind::Use(_, _) => "`.use`",
505                ExprKind::Yield(YieldKind::Postfix(_)) => "`.yield`",
506                ExprKind::Match(_, _, MatchKind::Postfix) => "a postfix match",
507                ExprKind::Err(_) => return Ok(with_postfix),
508                _ => {
    ::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)));
}unreachable!(
509                    "did not expect {:?} as an illegal postfix operator following cast",
510                    with_postfix.kind
511                ),
512            };
513            self.dcx()
514                .struct_span_err(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("cast cannot be followed by {0}",
                kind))
    })format!("cast cannot be followed by {kind}"))
515                .with_multipart_suggestion(
516                    "try surrounding the expression in parentheses",
517                    ::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![
518                        (span.shrink_to_lo(), "(".to_string()),
519                        (span.shrink_to_hi(), ")".to_string()),
520                    ],
521                    Applicability::MachineApplicable,
522                )
523                .emit();
524        };
525        Ok(with_postfix)
526    }
527
528    /// Parse `& mut? <expr>` or `& raw [ const | mut ] <expr>`.
529    fn parse_expr_borrow(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
530        self.expect_and()?;
531        let has_lifetime = self.token.is_lifetime() && self.look_ahead(1, |t| t != &token::Colon);
532        let lifetime = has_lifetime.then(|| self.expect_lifetime()); // For recovery, see below.
533        let (borrow_kind, mutbl) = self.parse_borrow_modifiers();
534        let (span, expr) = self.parse_expr_prefix_common(lo)?;
535        if let Some(lt) = lifetime {
536            self.error_remove_borrow_lifetime(span, lt.ident.span.until(expr.span));
537        }
538
539        // Add expected tokens if we parsed `&raw` as an expression.
540        // This will make sure we see "expected `const`, `mut`", and
541        // guides recovery in case we write `&raw expr`.
542        if borrow_kind == ast::BorrowKind::Ref
543            && mutbl == ast::Mutability::Not
544            && #[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)
545        {
546            self.expected_token_types.insert(TokenType::KwMut);
547            self.expected_token_types.insert(TokenType::KwConst);
548        }
549
550        Ok((span, ExprKind::AddrOf(borrow_kind, mutbl, expr)))
551    }
552
553    fn error_remove_borrow_lifetime(&self, span: Span, lt_span: Span) {
554        self.dcx().emit_err(crate::diagnostics::LifetimeInBorrowExpression {
555            span,
556            lifetime_span: lt_span,
557        });
558    }
559
560    /// Parse `mut?` or `[ raw | pin ] [ const | mut ]`.
561    fn parse_borrow_modifiers(&mut self) -> (ast::BorrowKind, ast::Mutability) {
562        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) {
563            // `raw [ const | mut ]`.
564            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));
565            if !found_raw { ::core::panicking::panic("assertion failed: found_raw") };assert!(found_raw);
566            let mutability = self.parse_mut_or_const().unwrap();
567            (ast::BorrowKind::Raw, mutability)
568        } else {
569            match self.parse_pin_and_mut() {
570                // `mut?`
571                (ast::Pinnedness::Not, mutbl) => (ast::BorrowKind::Ref, mutbl),
572                // `pin [ const | mut ]`.
573                // `pin` has been gated in `self.parse_pin_and_mut()` so we don't
574                // need to gate it here.
575                (ast::Pinnedness::Pinned, mutbl) => (ast::BorrowKind::Pin, mutbl),
576            }
577        }
578    }
579
580    /// Parses `a.b` or `a(13)` or `a[4]` or just `a`.
581    fn parse_expr_dot_or_call(&mut self, attrs: AttrWrapper) -> PResult<'a, Box<Expr>> {
582        self.collect_tokens_for_expr(attrs, |this, attrs| {
583            let base = this.parse_expr_bottom()?;
584            let span = this.interpolated_or_expr_span(&base);
585            this.parse_expr_dot_or_call_with(attrs, base, span)
586        })
587    }
588
589    pub(super) fn parse_expr_dot_or_call_with(
590        &mut self,
591        mut attrs: ast::AttrVec,
592        mut expr: Box<Expr>,
593        lo: Span,
594    ) -> PResult<'a, Box<Expr>> {
595        loop {
596            expr = if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Question,
    token_type: crate::parser::token_type::TokenType::Question,
}exp!(Question)) {
597                self.mk_expr(lo.to(self.prev_token.span), ExprKind::Try(expr))
598            } else if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Dot,
    token_type: crate::parser::token_type::TokenType::Dot,
}exp!(Dot)) {
599                self.parse_dot_suffix_expr(lo, expr)?
600            } else if let Some(expr) = self.recover_from_c_arrow_op(lo, &mut expr) {
601                expr?
602            } else if self.expr_is_complete(&expr) {
603                break;
604            } else if self.token == token::OpenParen {
605                self.parse_expr_fn_call(lo, expr)
606            } else if self.token == token::OpenBracket {
607                self.parse_expr_index(lo, expr)?
608            } else {
609                break;
610            };
611        }
612
613        // Stitch the list of outer attributes onto the return value. A little
614        // bit ugly, but the best way given the current code structure.
615        if !attrs.is_empty() {
616            mem::swap(&mut expr.attrs, &mut attrs);
617            expr.attrs.extend(attrs)
618        }
619
620        Ok(expr)
621    }
622
623    pub(super) fn parse_dot_suffix_expr(
624        &mut self,
625        lo: Span,
626        base: Box<Expr>,
627    ) -> PResult<'a, Box<Expr>> {
628        // At this point we've consumed something like `expr.` and `self.token` holds the token
629        // after the dot.
630        match self.token.uninterpolate().kind {
631            token::Ident(..) => self.parse_dot_suffix(base, lo),
632            token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) => {
633                let ident_span = self.token.span;
634                self.bump();
635                Ok(self.mk_expr_tuple_field_access(lo, ident_span, base, symbol, suffix))
636            }
637            token::Literal(token::Lit { kind: token::Float, symbol, suffix }) => {
638                Ok(match self.break_up_float(symbol, self.token.span) {
639                    // 1e2
640                    DestructuredFloat::Single(sym, _sp) => {
641                        // `foo.1e2`: a single complete dot access, fully consumed. We end up with
642                        // the `1e2` token in `self.prev_token` and the following token in
643                        // `self.token`.
644                        let ident_span = self.token.span;
645                        self.bump();
646                        self.mk_expr_tuple_field_access(lo, ident_span, base, sym, suffix)
647                    }
648                    // 1.
649                    DestructuredFloat::TrailingDot(sym, ident_span, dot_span) => {
650                        // `foo.1.`: a single complete dot access and the start of another.
651                        // We end up with the `sym` (`1`) token in `self.prev_token` and a dot in
652                        // `self.token`.
653                        if !suffix.is_none() {
    ::core::panicking::panic("assertion failed: suffix.is_none()")
};assert!(suffix.is_none());
654                        self.token = Token::new(token::Ident(sym, IdentKind::Normal), ident_span);
655                        self.bump_with((Token::new(token::Dot, dot_span), self.token_spacing));
656                        self.mk_expr_tuple_field_access(lo, ident_span, base, sym, None)
657                    }
658                    // 1.2 | 1.2e3
659                    DestructuredFloat::MiddleDot(
660                        sym1,
661                        ident1_span,
662                        _dot_span,
663                        sym2,
664                        ident2_span,
665                    ) => {
666                        // `foo.1.2` (or `foo.1.2e3`): two complete dot accesses. We end up with
667                        // the `sym2` (`2` or `2e3`) token in `self.prev_token` and the following
668                        // token in `self.token`.
669                        let next_token2 =
670                            Token::new(token::Ident(sym2, IdentKind::Normal), ident2_span);
671                        self.bump_with((next_token2, self.token_spacing));
672                        self.bump();
673                        let base1 =
674                            self.mk_expr_tuple_field_access(lo, ident1_span, base, sym1, None);
675                        self.mk_expr_tuple_field_access(lo, ident2_span, base1, sym2, suffix)
676                    }
677                    DestructuredFloat::Error => base,
678                })
679            }
680            _ => {
681                self.error_unexpected_after_dot();
682                Ok(base)
683            }
684        }
685    }
686
687    fn error_unexpected_after_dot(&self) {
688        let actual = super::token_descr(&self.token);
689        let span = self.token.span;
690        let sm = self.psess.source_map();
691        let (span, actual) = match (&self.token.kind, self.subparser_name) {
692            (token::Eof, Some(_)) if let Ok(snippet) = sm.span_to_snippet(sm.next_point(span)) => {
693                (span.shrink_to_hi(), ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", snippet))
    })format!("`{}`", snippet))
694            }
695            (token::CloseInvisible(InvisibleOrigin::MetaVar(_)), _) => {
696                // No need to report an error. This case will only occur when parsing a pasted
697                // metavariable, and we should have emitted an error when parsing the macro call in
698                // the first place. E.g. in this code:
699                // ```
700                // macro_rules! m { ($e:expr) => { $e }; }
701                //
702                // fn main() {
703                //     let f = 1;
704                //     m!(f.);
705                // }
706                // ```
707                // we'll get an error "unexpected token: `)` when parsing the `m!(f.)`, so we don't
708                // want to issue a second error when parsing the expansion `«f.»` (where `«`/`»`
709                // represent the invisible delimiters).
710                self.dcx().span_delayed_bug(span, "bad dot expr in metavariable");
711                return;
712            }
713            _ => (span, actual),
714        };
715        self.dcx().emit_err(crate::diagnostics::UnexpectedTokenAfterDot { span, actual });
716    }
717
718    /// We need an identifier or integer, but the next token is a float.
719    /// Break the float into components to extract the identifier or integer.
720    ///
721    /// See also [`TokenKind::break_two_token_op`] which does similar splitting of `>>` into `>`.
722    //
723    // FIXME: With current `TokenCursor` it's hard to break tokens into more than 2
724    //  parts unless those parts are processed immediately. `TokenCursor` should either
725    //  support pushing "future tokens" (would be also helpful to `break_and_eat`), or
726    //  we should break everything including floats into more basic proc-macro style
727    //  tokens in the lexer (probably preferable).
728    pub(super) fn break_up_float(&self, float: Symbol, span: Span) -> DestructuredFloat {
729        #[derive(#[automatically_derived]impl ::core::fmt::Debug for FloatComponent {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::IdentLike(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "IdentLike", &__self_0),
            Self::Punct(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f, "Punct",
                    &__self_0),
        }
    }
}Debug)]
730        enum FloatComponent {
731            IdentLike(String),
732            Punct(char),
733        }
734        use FloatComponent::*;
735
736        let float_str = float.as_str();
737        let mut components = Vec::new();
738        let mut ident_like = String::new();
739        for c in float_str.chars() {
740            if c == '_' || c.is_ascii_alphanumeric() {
741                ident_like.push(c);
742            } else if #[allow(non_exhaustive_omitted_patterns)] match c {
    '.' | '+' | '-' => true,
    _ => false,
}matches!(c, '.' | '+' | '-') {
743                if !ident_like.is_empty() {
744                    components.push(IdentLike(mem::take(&mut ident_like)));
745                }
746                components.push(Punct(c));
747            } else {
748                {
    ::core::panicking::panic_fmt(format_args!("unexpected character in a float token: {0:?}",
            c));
}panic!("unexpected character in a float token: {c:?}")
749            }
750        }
751        if !ident_like.is_empty() {
752            components.push(IdentLike(ident_like));
753        }
754
755        // With proc macros the span can refer to anything, the source may be too short,
756        // or too long, or non-ASCII. It only makes sense to break our span into components
757        // if its underlying text is identical to our float literal.
758        let can_take_span_apart =
759            || self.span_to_snippet(span).as_deref() == Ok(float_str).as_deref();
760
761        match &*components {
762            // 1e2
763            [IdentLike(i)] => DestructuredFloat::Single(Symbol::intern(i), span),
764            // 1.
765            [IdentLike(left), Punct('.')] => {
766                let (left_span, dot_span) = if can_take_span_apart() {
767                    let left_span = span.with_hi(span.lo() + BytePos::from_usize(left.len()));
768                    let dot_span = span.with_lo(left_span.hi());
769                    (left_span, dot_span)
770                } else {
771                    (span, span)
772                };
773                let left = Symbol::intern(left);
774                DestructuredFloat::TrailingDot(left, left_span, dot_span)
775            }
776            // 1.2 | 1.2e3
777            [IdentLike(left), Punct('.'), IdentLike(right)] => {
778                let (left_span, dot_span, right_span) = if can_take_span_apart() {
779                    let left_span = span.with_hi(span.lo() + BytePos::from_usize(left.len()));
780                    let dot_span =
781                        span.with_lo(left_span.hi()).with_hi(left_span.hi() + BytePos(1));
782                    let right_span = span.with_lo(dot_span.hi());
783                    (left_span, dot_span, right_span)
784                } else {
785                    (span, span, span)
786                };
787                let left = Symbol::intern(left);
788                let right = Symbol::intern(right);
789                DestructuredFloat::MiddleDot(left, left_span, dot_span, right, right_span)
790            }
791            // 1e+ | 1e- (recovered)
792            [IdentLike(_), Punct('+' | '-')] |
793            // 1e+2 | 1e-2
794            [IdentLike(_), Punct('+' | '-'), IdentLike(_)] |
795            // 1.2e+ | 1.2e-
796            [IdentLike(_), Punct('.'), IdentLike(_), Punct('+' | '-')] |
797            // 1.2e+3 | 1.2e-3
798            [IdentLike(_), Punct('.'), IdentLike(_), Punct('+' | '-'), IdentLike(_)] => {
799                // See the FIXME about `TokenCursor` above.
800                self.error_unexpected_after_dot();
801                DestructuredFloat::Error
802            }
803            _ => {
    ::core::panicking::panic_fmt(format_args!("unexpected components in a float token: {0:?}",
            components));
}panic!("unexpected components in a float token: {components:?}"),
804        }
805    }
806
807    /// Parse the field access used in offset_of, matched by `$(e:expr)+`.
808    /// Currently returns a list of idents. However, it should be possible in
809    /// future to also do array indices, which might be arbitrary expressions.
810    pub(crate) fn parse_floating_field_access(&mut self) -> PResult<'a, ThinVec<Ident>> {
811        let mut fields = ThinVec::new();
812        let mut trailing_dot = None;
813
814        loop {
815            // This is expected to use a metavariable $(args:expr)+, but the builtin syntax
816            // could be called directly. Calling `parse_expr` allows this function to only
817            // consider `Expr`s.
818            let expr = self.parse_expr()?;
819            let mut current = &expr;
820            let start_idx = fields.len();
821            loop {
822                match current.kind {
823                    ExprKind::Field(ref left, right) => {
824                        // Field access is read right-to-left.
825                        fields.insert(start_idx, right);
826                        trailing_dot = None;
827                        current = left;
828                    }
829                    // Parse this both to give helpful error messages and to
830                    // verify it can be done with this parser setup.
831                    ExprKind::Index(ref left, ref _right, span) => {
832                        self.dcx().emit_err(crate::diagnostics::ArrayIndexInOffsetOf(span));
833                        current = left;
834                    }
835                    ExprKind::Lit(token::Lit {
836                        kind: token::Float | token::Integer,
837                        symbol,
838                        suffix,
839                    }) => {
840                        if let Some(suffix) = suffix {
841                            self.dcx().emit_err(
842                                crate::diagnostics::InvalidLiteralSuffixOnTupleIndex {
843                                    span: current.span,
844                                    suffix,
845                                },
846                            );
847                        }
848                        match self.break_up_float(symbol, current.span) {
849                            // 1e2
850                            DestructuredFloat::Single(sym, sp) => {
851                                trailing_dot = None;
852                                fields.insert(start_idx, Ident::new(sym, sp));
853                            }
854                            // 1.
855                            DestructuredFloat::TrailingDot(sym, sym_span, dot_span) => {
856                                if !suffix.is_none() {
    ::core::panicking::panic("assertion failed: suffix.is_none()")
};assert!(suffix.is_none());
857                                trailing_dot = Some(dot_span);
858                                fields.insert(start_idx, Ident::new(sym, sym_span));
859                            }
860                            // 1.2 | 1.2e3
861                            DestructuredFloat::MiddleDot(
862                                symbol1,
863                                span1,
864                                _dot_span,
865                                symbol2,
866                                span2,
867                            ) => {
868                                trailing_dot = None;
869                                fields.insert(start_idx, Ident::new(symbol2, span2));
870                                fields.insert(start_idx, Ident::new(symbol1, span1));
871                            }
872                            DestructuredFloat::Error => {
873                                trailing_dot = None;
874                                fields.insert(start_idx, Ident::new(symbol, self.prev_token.span));
875                            }
876                        }
877                        break;
878                    }
879                    ExprKind::Path(None, Path { ref segments, .. }) => {
880                        match &segments[..] {
881                            [PathSegment { ident, args: None, .. }] => {
882                                trailing_dot = None;
883                                fields.insert(start_idx, *ident)
884                            }
885                            _ => {
886                                self.dcx()
887                                    .emit_err(crate::diagnostics::InvalidOffsetOf(current.span));
888                                break;
889                            }
890                        }
891                        break;
892                    }
893                    _ => {
894                        self.dcx().emit_err(crate::diagnostics::InvalidOffsetOf(current.span));
895                        break;
896                    }
897                }
898            }
899
900            if self.token.kind.close_delim().is_some() || self.token.kind == token::Comma {
901                break;
902            } else if trailing_dot.is_none() {
903                // This loop should only repeat if there is a trailing dot.
904                self.dcx().emit_err(crate::diagnostics::InvalidOffsetOf(self.token.span));
905                break;
906            }
907        }
908        if let Some(dot) = trailing_dot {
909            self.dcx().emit_err(crate::diagnostics::InvalidOffsetOf(dot));
910        }
911        Ok(fields.into_iter().collect())
912    }
913
914    fn mk_expr_tuple_field_access(
915        &self,
916        lo: Span,
917        ident_span: Span,
918        base: Box<Expr>,
919        field: Symbol,
920        suffix: Option<Symbol>,
921    ) -> Box<Expr> {
922        if let Some(suffix) = suffix {
923            self.dcx().emit_err(crate::diagnostics::InvalidLiteralSuffixOnTupleIndex {
924                span: ident_span,
925                suffix,
926            });
927        }
928        self.mk_expr(lo.to(ident_span), ExprKind::Field(base, Ident::new(field, ident_span)))
929    }
930
931    /// Parse a function call expression, `expr(...)`.
932    fn parse_expr_fn_call(&mut self, lo: Span, fun: Box<Expr>) -> Box<Expr> {
933        let snapshot = if self.token == token::OpenParen {
934            Some((self.create_snapshot_for_diagnostic(), fun.kind.clone()))
935        } else {
936            None
937        };
938        let open_paren = self.token.span;
939        let call_depth = self.token_cursor.depth();
940
941        let seq = match self.parse_expr_paren_seq() {
942            Ok(args) => Ok(self.mk_expr(lo.to(self.prev_token.span), self.mk_call(fun, args))),
943            Err(err)
944                if self.is_expected_raw_ref_mut() && self.token_cursor.depth() == call_depth =>
945            {
946                let guar = err.emit_err();
947                // Preserve the call expression so later passes can still diagnose the callee,
948                // while treating the malformed `&raw <expr>` argument as an error expression.
949                let args = self.recover_raw_ref_call_args(guar);
950                return self.mk_expr(lo.to(self.prev_token.span), self.mk_call(fun, args));
951            }
952            Err(err) => Err(err),
953        };
954        match self.maybe_recover_struct_lit_bad_delims(lo, open_paren, seq, snapshot) {
955            Ok(expr) => expr,
956            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),
957        }
958    }
959
960    fn recover_raw_ref_call_args(&mut self, guar: ErrorGuaranteed) -> ThinVec<Box<Expr>> {
961        let err_span = self.prev_token.span.to(self.token.span);
962        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)];
963        while !self.token.kind.is_close_delim_or_eof() {
964            if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma)) {
965                if !self.token.kind.is_close_delim_or_eof() {
966                    args.push(self.mk_expr_err(self.prev_token.span.shrink_to_hi(), guar));
967                }
968            } else {
969                self.parse_token_tree();
970            }
971        }
972        let _ = self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseParen,
    token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen));
973        args
974    }
975
976    /// If we encounter a parser state that looks like the user has written a `struct` literal with
977    /// parentheses instead of braces, recover the parser state and provide suggestions.
978    {}
#[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("/rustc-dev/739adecd444342128b4ef32cbbd8352856cb1651/compiler/rustc_parse/src/parser/expr.rs"),
                                    ::tracing_core::__macro_support::Option::Some(978u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_parse::parser::expr"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("lo")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("lo");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("open_paren")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("open_paren");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&lo)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&open_paren)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

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