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