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