Skip to main content

rustc_parse/parser/
expr.rs

1// ignore-tidy-filelength
2
3use core::mem;
4use core::ops::{Bound, ControlFlow};
5
6use ast::mut_visit::{self, MutVisitor};
7use ast::token::IdentIsRaw;
8use ast::{CoroutineKind, ForLoopKind, GenBlockKind, MatchKind, Pat, Path, PathSegment, Recovered};
9use rustc_ast::token::{self, Delimiter, InvisibleOrigin, MetaVarKind, Token, TokenKind};
10use rustc_ast::tokenstream::TokenTree;
11use rustc_ast::util::case::Case;
12use rustc_ast::util::classify;
13use rustc_ast::util::parser::{AssocOp, ExprPrecedence, Fixity, prec_let_scrutinee_needs_par};
14use rustc_ast::visit::{Visitor, walk_expr};
15use rustc_ast::{
16    self as ast, AnonConst, Arm, AssignOp, AssignOpKind, AttrStyle, AttrVec, BinOp, BinOpKind,
17    BlockCheckMode, CaptureBy, ClosureBinder, DUMMY_NODE_ID, Expr, ExprField, ExprKind, FnDecl,
18    FnRetTy, Label, MacCall, MetaItemLit, MgcaDisambiguation, Movability, Param, RangeLimits,
19    StmtKind, Ty, TyKind, UnOp, UnsafeBinderCastKind, YieldKind,
20};
21use rustc_data_structures::stack::ensure_sufficient_stack;
22use rustc_errors::{Applicability, Diag, PResult, StashKey, Subdiagnostic};
23use rustc_literal_escaper::unescape_char;
24use rustc_session::errors::{ExprParenthesesNeeded, report_lit_error};
25use rustc_session::lint::BuiltinLintDiag;
26use rustc_session::lint::builtin::BREAK_WITH_LABEL_AND_LOOP;
27use rustc_span::edition::Edition;
28use rustc_span::source_map::{self, Spanned};
29use rustc_span::{BytePos, ErrorGuaranteed, Ident, Pos, Span, Symbol, kw, sym};
30use thin_vec::{ThinVec, thin_vec};
31use tracing::instrument;
32
33use super::diagnostics::SnapshotParser;
34use super::pat::{CommaRecoveryMode, Expected, RecoverColon, RecoverComma};
35use super::ty::{AllowPlus, RecoverQPath, RecoverReturnSign};
36use super::{
37    AttrWrapper, BlockMode, ClosureSpans, ExpTokenPair, ForceCollect, Parser, PathStyle,
38    Restrictions, SemiColonMode, SeqSep, TokenType, Trailing, UsePreAttrPos,
39};
40use crate::{errors, exp, maybe_recover_from_interpolated_ty_qpath};
41
42#[derive(#[automatically_derived]
impl ::core::fmt::Debug for DestructuredFloat {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            DestructuredFloat::Single(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f, "Single",
                    __self_0, &__self_1),
            DestructuredFloat::TrailingDot(__self_0, __self_1, __self_2) =>
                ::core::fmt::Formatter::debug_tuple_field3_finish(f,
                    "TrailingDot", __self_0, __self_1, &__self_2),
            DestructuredFloat::MiddleDot(__self_0, __self_1, __self_2,
                __self_3, __self_4) =>
                ::core::fmt::Formatter::debug_tuple_field5_finish(f,
                    "MiddleDot", __self_0, __self_1, __self_2, __self_3,
                    &__self_4),
            DestructuredFloat::Error =>
                ::core::fmt::Formatter::write_str(f, "Error"),
        }
    }
}Debug)]
43pub(super) enum DestructuredFloat {
44    /// 1e2
45    Single(Symbol, Span),
46    /// 1.
47    TrailingDot(Symbol, Span, Span),
48    /// 1.2 | 1.2e3
49    MiddleDot(Symbol, Span, Span, Symbol, Span),
50    /// Invalid
51    Error,
52}
53
54impl<'a> Parser<'a> {
55    /// Parses an expression.
56    #[inline]
57    pub fn parse_expr(&mut self) -> PResult<'a, Box<Expr>> {
58        self.current_closure.take();
59
60        let attrs = self.parse_outer_attributes()?;
61        self.parse_expr_res(Restrictions::empty(), attrs).map(|res| res.0)
62    }
63
64    /// Parses an expression, forcing tokens to be collected.
65    pub fn parse_expr_force_collect(&mut self) -> PResult<'a, Box<Expr>> {
66        self.current_closure.take();
67
68        // If the expression is associative (e.g. `1 + 2`), then any preceding
69        // outer attribute actually belongs to the first inner sub-expression.
70        // In which case we must use the pre-attr pos to include the attribute
71        // in the collected tokens for the outer expression.
72        let pre_attr_pos = self.collect_pos();
73        let attrs = self.parse_outer_attributes()?;
74        self.collect_tokens(
75            Some(pre_attr_pos),
76            AttrWrapper::empty(),
77            ForceCollect::Yes,
78            |this, _empty_attrs| {
79                let (expr, is_assoc) = this.parse_expr_res(Restrictions::empty(), attrs)?;
80                let use_pre_attr_pos =
81                    if is_assoc { UsePreAttrPos::Yes } else { UsePreAttrPos::No };
82                Ok((expr, Trailing::No, use_pre_attr_pos))
83            },
84        )
85    }
86
87    pub fn parse_expr_anon_const(
88        &mut self,
89        mgca_disambiguation: impl FnOnce(&Self, &Expr) -> MgcaDisambiguation,
90    ) -> PResult<'a, AnonConst> {
91        self.parse_expr().map(|value| AnonConst {
92            id: DUMMY_NODE_ID,
93            mgca_disambiguation: mgca_disambiguation(self, &value),
94            value,
95        })
96    }
97
98    fn parse_expr_catch_underscore(
99        &mut self,
100        restrictions: Restrictions,
101    ) -> PResult<'a, Box<Expr>> {
102        let attrs = self.parse_outer_attributes()?;
103        match self.parse_expr_res(restrictions, attrs) {
104            Ok((expr, _)) => Ok(expr),
105            Err(err) => match self.token.ident() {
106                Some((Ident { name: kw::Underscore, .. }, IdentIsRaw::No))
107                    if self.may_recover() && self.look_ahead(1, |t| t == &token::Comma) =>
108                {
109                    // Special-case handling of `foo(_, _, _)`
110                    let guar = err.emit();
111                    self.bump();
112                    Ok(self.mk_expr(self.prev_token.span, ExprKind::Err(guar)))
113                }
114                _ => Err(err),
115            },
116        }
117    }
118
119    /// Parses a sequence of expressions delimited by parentheses.
120    fn parse_expr_paren_seq(&mut self) -> PResult<'a, ThinVec<Box<Expr>>> {
121        self.parse_paren_comma_seq(|p| p.parse_expr_catch_underscore(Restrictions::empty()))
122            .map(|(r, _)| r)
123    }
124
125    /// Parses an expression, subject to the given restrictions.
126    #[inline]
127    pub(super) fn parse_expr_res(
128        &mut self,
129        r: Restrictions,
130        attrs: AttrWrapper,
131    ) -> PResult<'a, (Box<Expr>, bool)> {
132        self.with_res(r, |this| this.parse_expr_assoc_with(Bound::Unbounded, attrs))
133    }
134
135    /// Parses an associative expression with operators of at least `min_prec` precedence.
136    /// The `bool` in the return value indicates if it was an assoc expr, i.e. with an operator
137    /// followed by a subexpression (e.g. `1 + 2`).
138    pub(super) fn parse_expr_assoc_with(
139        &mut self,
140        min_prec: Bound<ExprPrecedence>,
141        attrs: AttrWrapper,
142    ) -> PResult<'a, (Box<Expr>, bool)> {
143        let lhs = if self.token.is_range_separator() {
144            return self.parse_expr_prefix_range(attrs).map(|res| (res, false));
145        } else {
146            self.parse_expr_prefix(attrs)?
147        };
148        self.parse_expr_assoc_rest_with(min_prec, false, lhs)
149    }
150
151    /// Parses the rest of an associative expression (i.e. the part after the lhs) with operators
152    /// of at least `min_prec` precedence. The `bool` in the return value indicates if something
153    /// was actually parsed.
154    pub(super) fn parse_expr_assoc_rest_with(
155        &mut self,
156        min_prec: Bound<ExprPrecedence>,
157        starts_stmt: bool,
158        mut lhs: Box<Expr>,
159    ) -> PResult<'a, (Box<Expr>, bool)> {
160        let mut parsed_something = false;
161        if !self.should_continue_as_assoc_expr(&lhs) {
162            return Ok((lhs, parsed_something));
163        }
164
165        self.expected_token_types.insert(TokenType::Operator);
166        while let Some(op) = self.check_assoc_op() {
167            let lhs_span = self.interpolated_or_expr_span(&lhs);
168            let cur_op_span = self.token.span;
169            let restrictions = if op.node.is_assign_like() {
170                self.restrictions & Restrictions::NO_STRUCT_LITERAL
171            } else {
172                self.restrictions
173            };
174            let prec = op.node.precedence();
175            if match min_prec {
176                Bound::Included(min_prec) => prec < min_prec,
177                Bound::Excluded(min_prec) => prec <= min_prec,
178                Bound::Unbounded => false,
179            } {
180                break;
181            }
182            // Check for deprecated `...` syntax
183            if self.token == token::DotDotDot && op.node == AssocOp::Range(RangeLimits::Closed) {
184                self.err_dotdotdot_syntax(self.token.span);
185            }
186
187            if self.token == token::LArrow {
188                self.err_larrow_operator(self.token.span);
189            }
190
191            parsed_something = true;
192            self.bump();
193            if op.node.is_comparison() {
194                if let Some(expr) = self.check_no_chained_comparison(&lhs, &op)? {
195                    return Ok((expr, parsed_something));
196                }
197            }
198
199            // Look for JS' `===` and `!==` and recover
200            if let AssocOp::Binary(bop @ BinOpKind::Eq | bop @ BinOpKind::Ne) = op.node
201                && self.token == token::Eq
202                && self.prev_token.span.hi() == self.token.span.lo()
203            {
204                let sp = op.span.to(self.token.span);
205                let sugg = bop.as_str().into();
206                let invalid = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}=", sugg))
    })format!("{sugg}=");
207                self.dcx().emit_err(errors::InvalidComparisonOperator {
208                    span: sp,
209                    invalid: invalid.clone(),
210                    sub: errors::InvalidComparisonOperatorSub::Correctable {
211                        span: sp,
212                        invalid,
213                        correct: sugg,
214                    },
215                });
216                self.bump();
217            }
218
219            // Look for PHP's `<>` and recover
220            if op.node == AssocOp::Binary(BinOpKind::Lt)
221                && self.token == token::Gt
222                && self.prev_token.span.hi() == self.token.span.lo()
223            {
224                let sp = op.span.to(self.token.span);
225                self.dcx().emit_err(errors::InvalidComparisonOperator {
226                    span: sp,
227                    invalid: "<>".into(),
228                    sub: errors::InvalidComparisonOperatorSub::Correctable {
229                        span: sp,
230                        invalid: "<>".into(),
231                        correct: "!=".into(),
232                    },
233                });
234                self.bump();
235            }
236
237            // Look for C++'s `<=>` and recover
238            if op.node == AssocOp::Binary(BinOpKind::Le)
239                && self.token == token::Gt
240                && self.prev_token.span.hi() == self.token.span.lo()
241            {
242                let sp = op.span.to(self.token.span);
243                self.dcx().emit_err(errors::InvalidComparisonOperator {
244                    span: sp,
245                    invalid: "<=>".into(),
246                    sub: errors::InvalidComparisonOperatorSub::Spaceship(sp),
247                });
248                self.bump();
249            }
250
251            if self.prev_token == token::Plus
252                && self.token == token::Plus
253                && self.prev_token.span.between(self.token.span).is_empty()
254            {
255                let op_span = self.prev_token.span.to(self.token.span);
256                // Eat the second `+`
257                self.bump();
258                lhs = self.recover_from_postfix_increment(lhs, op_span, starts_stmt)?;
259                continue;
260            }
261
262            if self.prev_token == token::Minus
263                && self.token == token::Minus
264                && self.prev_token.span.between(self.token.span).is_empty()
265                && !self.look_ahead(1, |tok| tok.can_begin_expr())
266            {
267                let op_span = self.prev_token.span.to(self.token.span);
268                // Eat the second `-`
269                self.bump();
270                lhs = self.recover_from_postfix_decrement(lhs, op_span, starts_stmt)?;
271                continue;
272            }
273
274            let op_span = op.span;
275            let op = op.node;
276            // Special cases:
277            if op == AssocOp::Cast {
278                lhs = self.parse_assoc_op_cast(lhs, lhs_span, op_span, ExprKind::Cast)?;
279                continue;
280            } else if let AssocOp::Range(limits) = op {
281                // If we didn't have to handle `x..`/`x..=`, it would be pretty easy to
282                // generalise it to the Fixity::None code.
283                lhs = self.parse_expr_range(prec, lhs, limits, cur_op_span)?;
284                break;
285            }
286
287            let min_prec = match op.fixity() {
288                Fixity::Right => Bound::Included(prec),
289                Fixity::Left | Fixity::None => Bound::Excluded(prec),
290            };
291            let (rhs, _) = self.with_res(restrictions - Restrictions::STMT_EXPR, |this| {
292                let attrs = this.parse_outer_attributes()?;
293                this.parse_expr_assoc_with(min_prec, attrs)
294            })?;
295
296            let span = self.mk_expr_sp(&lhs, lhs_span, op_span, rhs.span);
297            lhs = match op {
298                AssocOp::Binary(ast_op) => {
299                    let binary = self.mk_binary(source_map::respan(cur_op_span, ast_op), lhs, rhs);
300                    self.mk_expr(span, binary)
301                }
302                AssocOp::Assign => self.mk_expr(span, ExprKind::Assign(lhs, rhs, cur_op_span)),
303                AssocOp::AssignOp(aop) => {
304                    let aopexpr = self.mk_assign_op(source_map::respan(cur_op_span, aop), lhs, rhs);
305                    self.mk_expr(span, aopexpr)
306                }
307                AssocOp::Cast | AssocOp::Range(_) => {
308                    self.dcx().span_bug(span, "AssocOp should have been handled by special case")
309                }
310            };
311        }
312
313        Ok((lhs, parsed_something))
314    }
315
316    fn should_continue_as_assoc_expr(&mut self, lhs: &Expr) -> bool {
317        match (self.expr_is_complete(lhs), AssocOp::from_token(&self.token)) {
318            // Semi-statement forms are odd:
319            // See https://github.com/rust-lang/rust/issues/29071
320            (true, None) => false,
321            (false, _) => true, // Continue parsing the expression.
322            // An exhaustive check is done in the following block, but these are checked first
323            // because they *are* ambiguous but also reasonable looking incorrect syntax, so we
324            // want to keep their span info to improve diagnostics in these cases in a later stage.
325            (true, Some(AssocOp::Binary(
326                BinOpKind::Mul | // `{ 42 } *foo = bar;` or `{ 42 } * 3`
327                BinOpKind::Sub | // `{ 42 } -5`
328                BinOpKind::Add | // `{ 42 } + 42` (unary plus)
329                BinOpKind::And | // `{ 42 } &&x` (#61475) or `{ 42 } && if x { 1 } else { 0 }`
330                BinOpKind::Or | // `{ 42 } || 42` ("logical or" or closure)
331                BinOpKind::BitOr // `{ 42 } | 42` or `{ 42 } |x| 42`
332            ))) => {
333                // These cases are ambiguous and can't be identified in the parser alone.
334                //
335                // Bitwise AND is left out because guessing intent is hard. We can make
336                // suggestions based on the assumption that double-refs are rarely intentional,
337                // and closures are distinct enough that they don't get mixed up with their
338                // return value.
339                let sp = self.psess.source_map().start_point(self.token.span);
340                self.psess.ambiguous_block_expr_parse.borrow_mut().insert(sp, lhs.span);
341                false
342            }
343            (true, Some(op)) if !op.can_continue_expr_unambiguously() => false,
344            (true, Some(_)) => {
345                self.error_found_expr_would_be_stmt(lhs);
346                true
347            }
348        }
349    }
350
351    /// We've found an expression that would be parsed as a statement,
352    /// but the next token implies this should be parsed as an expression.
353    /// For example: `if let Some(x) = x { x } else { 0 } / 2`.
354    fn error_found_expr_would_be_stmt(&self, lhs: &Expr) {
355        self.dcx().emit_err(errors::FoundExprWouldBeStmt {
356            span: self.token.span,
357            token: self.token,
358            suggestion: ExprParenthesesNeeded::surrounding(lhs.span),
359        });
360    }
361
362    /// Possibly translate the current token to an associative operator.
363    /// The method does not advance the current token.
364    ///
365    /// Also performs recovery for `and` / `or` which are mistaken for `&&` and `||` respectively.
366    pub(super) fn check_assoc_op(&self) -> Option<Spanned<AssocOp>> {
367        let (op, span) = match (AssocOp::from_token(&self.token), self.token.ident()) {
368            // When parsing const expressions, stop parsing when encountering `>`.
369            (
370                Some(
371                    AssocOp::Binary(BinOpKind::Shr | BinOpKind::Gt | BinOpKind::Ge)
372                    | AssocOp::AssignOp(AssignOpKind::ShrAssign),
373                ),
374                _,
375            ) if self.restrictions.contains(Restrictions::CONST_EXPR) => {
376                return None;
377            }
378            // When recovering patterns as expressions, stop parsing when encountering an
379            // assignment `=`, an alternative `|`, or a range `..`.
380            (
381                Some(
382                    AssocOp::Assign
383                    | AssocOp::AssignOp(_)
384                    | AssocOp::Binary(BinOpKind::BitOr)
385                    | AssocOp::Range(_),
386                ),
387                _,
388            ) if self.restrictions.contains(Restrictions::IS_PAT) => {
389                return None;
390            }
391            (Some(op), _) => (op, self.token.span),
392            (None, Some((Ident { name: sym::and, span }, IdentIsRaw::No)))
393                if self.may_recover() =>
394            {
395                self.dcx().emit_err(errors::InvalidLogicalOperator {
396                    span: self.token.span,
397                    incorrect: "and".into(),
398                    sub: errors::InvalidLogicalOperatorSub::Conjunction(self.token.span),
399                });
400                (AssocOp::Binary(BinOpKind::And), span)
401            }
402            (None, Some((Ident { name: sym::or, span }, IdentIsRaw::No))) if self.may_recover() => {
403                self.dcx().emit_err(errors::InvalidLogicalOperator {
404                    span: self.token.span,
405                    incorrect: "or".into(),
406                    sub: errors::InvalidLogicalOperatorSub::Disjunction(self.token.span),
407                });
408                (AssocOp::Binary(BinOpKind::Or), span)
409            }
410            _ => return None,
411        };
412        Some(source_map::respan(span, op))
413    }
414
415    /// Checks if this expression is a successfully parsed statement.
416    fn expr_is_complete(&self, e: &Expr) -> bool {
417        self.restrictions.contains(Restrictions::STMT_EXPR) && classify::expr_is_complete(e)
418    }
419
420    /// Parses `x..y`, `x..=y`, and `x..`/`x..=`.
421    /// The other two variants are handled in `parse_prefix_range_expr` below.
422    fn parse_expr_range(
423        &mut self,
424        prec: ExprPrecedence,
425        lhs: Box<Expr>,
426        limits: RangeLimits,
427        cur_op_span: Span,
428    ) -> PResult<'a, Box<Expr>> {
429        let rhs = if self.is_at_start_of_range_notation_rhs() {
430            let maybe_lt = self.token;
431            let attrs = self.parse_outer_attributes()?;
432            Some(
433                self.parse_expr_assoc_with(Bound::Excluded(prec), attrs)
434                    .map_err(|err| self.maybe_err_dotdotlt_syntax(maybe_lt, err))?
435                    .0,
436            )
437        } else {
438            None
439        };
440        let rhs_span = rhs.as_ref().map_or(cur_op_span, |x| x.span);
441        let span = self.mk_expr_sp(&lhs, lhs.span, cur_op_span, rhs_span);
442        let range = self.mk_range(Some(lhs), rhs, limits);
443        Ok(self.mk_expr(span, range))
444    }
445
446    fn is_at_start_of_range_notation_rhs(&self) -> bool {
447        if self.token.can_begin_expr() {
448            // Parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
449            if self.token == token::OpenBrace {
450                return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
451            }
452            true
453        } else {
454            false
455        }
456    }
457
458    /// Parses prefix-forms of range notation: `..expr`, `..`, `..=expr`.
459    fn parse_expr_prefix_range(&mut self, attrs: AttrWrapper) -> PResult<'a, Box<Expr>> {
460        if !attrs.is_empty() {
461            let err = errors::DotDotRangeAttribute { span: self.token.span };
462            self.dcx().emit_err(err);
463        }
464
465        // Check for deprecated `...` syntax.
466        if self.token == token::DotDotDot {
467            self.err_dotdotdot_syntax(self.token.span);
468        }
469
470        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!(
471            self.token.is_range_separator(),
472            "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
473            self.token
474        );
475
476        let limits = match self.token.kind {
477            token::DotDot => RangeLimits::HalfOpen,
478            _ => RangeLimits::Closed,
479        };
480        let op = AssocOp::from_token(&self.token);
481        let attrs = self.parse_outer_attributes()?;
482        self.collect_tokens_for_expr(attrs, |this, attrs| {
483            let lo = this.token.span;
484            let maybe_lt = this.look_ahead(1, |t| t.clone());
485            this.bump();
486            let (span, opt_end) = if this.is_at_start_of_range_notation_rhs() {
487                // RHS must be parsed with more associativity than the dots.
488                let attrs = this.parse_outer_attributes()?;
489                this.parse_expr_assoc_with(Bound::Excluded(op.unwrap().precedence()), attrs)
490                    .map(|(x, _)| (lo.to(x.span), Some(x)))
491                    .map_err(|err| this.maybe_err_dotdotlt_syntax(maybe_lt, err))?
492            } else {
493                (lo, None)
494            };
495            let range = this.mk_range(None, opt_end, limits);
496            Ok(this.mk_expr_with_attrs(span, range, attrs))
497        })
498    }
499
500    /// Parses a prefix-unary-operator expr.
501    fn parse_expr_prefix(&mut self, attrs: AttrWrapper) -> PResult<'a, Box<Expr>> {
502        let lo = self.token.span;
503
504        macro_rules! make_it {
505            ($this:ident, $attrs:expr, |this, _| $body:expr) => {
506                $this.collect_tokens_for_expr($attrs, |$this, attrs| {
507                    let (hi, ex) = $body?;
508                    Ok($this.mk_expr_with_attrs(lo.to(hi), ex, attrs))
509                })
510            };
511        }
512
513        let this = self;
514
515        // Note: when adding new unary operators, don't forget to adjust TokenKind::can_begin_expr()
516        match this.token.uninterpolate().kind {
517            // `!expr`
518            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)),
519            // `~expr`
520            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)),
521            // `-expr`
522            token::Minus => {
523                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))
524            }
525            // `*expr`
526            token::Star => {
527                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))
528            }
529            // `&expr` and `&&expr`
530            token::And | token::AndAnd => {
531                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))
532            }
533            // `+lit`
534            token::Plus if this.look_ahead(1, |tok| tok.is_numeric_lit()) => {
535                let mut err = errors::LeadingPlusNotSupported {
536                    span: lo,
537                    remove_plus: None,
538                    add_parentheses: None,
539                };
540
541                // a block on the LHS might have been intended to be an expression instead
542                if let Some(sp) = this.psess.ambiguous_block_expr_parse.borrow().get(&lo) {
543                    err.add_parentheses = Some(ExprParenthesesNeeded::surrounding(*sp));
544                } else {
545                    err.remove_plus = Some(lo);
546                }
547                this.dcx().emit_err(err);
548
549                this.bump();
550                let attrs = this.parse_outer_attributes()?;
551                this.parse_expr_prefix(attrs)
552            }
553            // Recover from `++x`:
554            token::Plus if this.look_ahead(1, |t| *t == token::Plus) => {
555                let starts_stmt =
556                    this.prev_token == token::Semi || this.prev_token == token::CloseBrace;
557                let pre_span = this.token.span.to(this.look_ahead(1, |t| t.span));
558                // Eat both `+`s.
559                this.bump();
560                this.bump();
561
562                let operand_expr = this.parse_expr_dot_or_call(attrs)?;
563                this.recover_from_prefix_increment(operand_expr, pre_span, starts_stmt)
564            }
565            token::Ident(..) if this.token.is_keyword(kw::Box) => {
566                this.collect_tokens_for_expr(attrs,
    |this, attrs|
        {
            let (hi, ex) = this.parse_expr_box(lo)?;
            Ok(this.mk_expr_with_attrs(lo.to(hi), ex, attrs))
        })make_it!(this, attrs, |this, _| this.parse_expr_box(lo))
567            }
568            token::Ident(..) if this.may_recover() && this.is_mistaken_not_ident_negation() => {
569                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))
570            }
571            _ => return this.parse_expr_dot_or_call(attrs),
572        }
573    }
574
575    fn parse_expr_prefix_common(&mut self, lo: Span) -> PResult<'a, (Span, Box<Expr>)> {
576        self.bump();
577        let attrs = self.parse_outer_attributes()?;
578        let expr = if self.token.is_range_separator() {
579            self.parse_expr_prefix_range(attrs)
580        } else {
581            self.parse_expr_prefix(attrs)
582        }?;
583        let span = self.interpolated_or_expr_span(&expr);
584        Ok((lo.to(span), expr))
585    }
586
587    fn parse_expr_unary(&mut self, lo: Span, op: UnOp) -> PResult<'a, (Span, ExprKind)> {
588        let (span, expr) = self.parse_expr_prefix_common(lo)?;
589        Ok((span, self.mk_unary(op, expr)))
590    }
591
592    /// Recover on `~expr` in favor of `!expr`.
593    fn recover_tilde_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
594        self.dcx().emit_err(errors::TildeAsUnaryOperator(lo));
595
596        self.parse_expr_unary(lo, UnOp::Not)
597    }
598
599    /// Parse `box expr` - this syntax has been removed, but we still parse this
600    /// for now to provide a more useful error
601    fn parse_expr_box(&mut self, box_kw: Span) -> PResult<'a, (Span, ExprKind)> {
602        let (span, expr) = self.parse_expr_prefix_common(box_kw)?;
603        // Make a multipart suggestion instead of `span_to_snippet` in case source isn't available
604        let box_kw_and_lo = box_kw.until(self.interpolated_or_expr_span(&expr));
605        let hi = span.shrink_to_hi();
606        let sugg = errors::AddBoxNew { box_kw_and_lo, hi };
607        let guar = self.dcx().emit_err(errors::BoxSyntaxRemoved { span, sugg });
608        Ok((span, ExprKind::Err(guar)))
609    }
610
611    fn is_mistaken_not_ident_negation(&self) -> bool {
612        let token_cannot_continue_expr = |t: &Token| match t.uninterpolate().kind {
613            // These tokens can start an expression after `!`, but
614            // can't continue an expression after an ident
615            token::Ident(name, is_raw) => token::ident_can_begin_expr(name, t.span, is_raw),
616            token::Literal(..) | token::Pound => true,
617            _ => t.is_metavar_expr(),
618        };
619        self.token.is_ident_named(sym::not) && self.look_ahead(1, token_cannot_continue_expr)
620    }
621
622    /// Recover on `not expr` in favor of `!expr`.
623    fn recover_not_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
624        let negated_token = self.look_ahead(1, |t| *t);
625
626        let sub_diag = if negated_token.is_numeric_lit() {
627            errors::NotAsNegationOperatorSub::SuggestNotBitwise
628        } else if negated_token.is_bool_lit() {
629            errors::NotAsNegationOperatorSub::SuggestNotLogical
630        } else {
631            errors::NotAsNegationOperatorSub::SuggestNotDefault
632        };
633
634        self.dcx().emit_err(errors::NotAsNegationOperator {
635            negated: negated_token.span,
636            negated_desc: super::token_descr(&negated_token),
637            // Span the `not` plus trailing whitespace to avoid
638            // trailing whitespace after the `!` in our suggestion
639            sub: sub_diag(
640                self.psess.source_map().span_until_non_whitespace(lo.to(negated_token.span)),
641            ),
642        });
643
644        self.parse_expr_unary(lo, UnOp::Not)
645    }
646
647    /// Returns the span of expr if it was not interpolated, or the span of the interpolated token.
648    fn interpolated_or_expr_span(&self, expr: &Expr) -> Span {
649        match self.prev_token.kind {
650            token::NtIdent(..) | token::NtLifetime(..) => self.prev_token.span,
651            token::CloseInvisible(InvisibleOrigin::MetaVar(_)) => {
652                // `expr.span` is the interpolated span, because invisible open
653                // and close delims both get marked with the same span, one
654                // that covers the entire thing between them. (See
655                // `rustc_expand::mbe::transcribe::transcribe`.)
656                self.prev_token.span
657            }
658            _ => expr.span,
659        }
660    }
661
662    fn parse_assoc_op_cast(
663        &mut self,
664        lhs: Box<Expr>,
665        lhs_span: Span,
666        op_span: Span,
667        expr_kind: fn(Box<Expr>, Box<Ty>) -> ExprKind,
668    ) -> PResult<'a, Box<Expr>> {
669        let mk_expr = |this: &mut Self, lhs: Box<Expr>, rhs: Box<Ty>| {
670            this.mk_expr(this.mk_expr_sp(&lhs, lhs_span, op_span, rhs.span), expr_kind(lhs, rhs))
671        };
672
673        // Save the state of the parser before parsing type normally, in case there is a
674        // LessThan comparison after this cast.
675        let parser_snapshot_before_type = self.clone();
676        let cast_expr = match self.parse_as_cast_ty() {
677            Ok(rhs) => mk_expr(self, lhs, rhs),
678            Err(type_err) => {
679                if !self.may_recover() {
680                    return Err(type_err);
681                }
682
683                // Rewind to before attempting to parse the type with generics, to recover
684                // from situations like `x as usize < y` in which we first tried to parse
685                // `usize < y` as a type with generic arguments.
686                let parser_snapshot_after_type = mem::replace(self, parser_snapshot_before_type);
687
688                // Check for typo of `'a: loop { break 'a }` with a missing `'`.
689                match (&lhs.kind, &self.token.kind) {
690                    (
691                        // `foo: `
692                        ExprKind::Path(None, ast::Path { segments, .. }),
693                        token::Ident(kw::For | kw::Loop | kw::While, IdentIsRaw::No),
694                    ) if let [segment] = segments.as_slice() => {
695                        let snapshot = self.create_snapshot_for_diagnostic();
696                        let label = Label {
697                            ident: Ident::from_str_and_span(
698                                &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\'{0}", segment.ident))
    })format!("'{}", segment.ident),
699                                segment.ident.span,
700                            ),
701                        };
702                        match self.parse_expr_labeled(label, false) {
703                            Ok(expr) => {
704                                type_err.cancel();
705                                self.dcx().emit_err(errors::MalformedLoopLabel {
706                                    span: label.ident.span,
707                                    suggestion: label.ident.span.shrink_to_lo(),
708                                });
709                                return Ok(expr);
710                            }
711                            Err(err) => {
712                                err.cancel();
713                                self.restore_snapshot(snapshot);
714                            }
715                        }
716                    }
717                    _ => {}
718                }
719
720                match self.parse_path(PathStyle::Expr) {
721                    Ok(path) => {
722                        let span_after_type = parser_snapshot_after_type.token.span;
723                        let expr = mk_expr(
724                            self,
725                            lhs,
726                            self.mk_ty(path.span, TyKind::Path(None, path.clone())),
727                        );
728
729                        let args_span = self.look_ahead(1, |t| t.span).to(span_after_type);
730                        match self.token.kind {
731                            token::Lt => {
732                                self.dcx().emit_err(errors::ComparisonInterpretedAsGeneric {
733                                    comparison: self.token.span,
734                                    r#type: path,
735                                    args: args_span,
736                                    suggestion: errors::ComparisonInterpretedAsGenericSugg {
737                                        left: expr.span.shrink_to_lo(),
738                                        right: expr.span.shrink_to_hi(),
739                                    },
740                                })
741                            }
742                            token::Shl => self.dcx().emit_err(errors::ShiftInterpretedAsGeneric {
743                                shift: self.token.span,
744                                r#type: path,
745                                args: args_span,
746                                suggestion: errors::ShiftInterpretedAsGenericSugg {
747                                    left: expr.span.shrink_to_lo(),
748                                    right: expr.span.shrink_to_hi(),
749                                },
750                            }),
751                            _ => {
752                                // We can end up here even without `<` being the next token, for
753                                // example because `parse_ty_no_plus` returns `Err` on keywords,
754                                // but `parse_path` returns `Ok` on them due to error recovery.
755                                // Return original error and parser state.
756                                *self = parser_snapshot_after_type;
757                                return Err(type_err);
758                            }
759                        };
760
761                        // Successfully parsed the type path leaving a `<` yet to parse.
762                        type_err.cancel();
763
764                        // Keep `x as usize` as an expression in AST and continue parsing.
765                        expr
766                    }
767                    Err(path_err) => {
768                        // Couldn't parse as a path, return original error and parser state.
769                        path_err.cancel();
770                        *self = parser_snapshot_after_type;
771                        return Err(type_err);
772                    }
773                }
774            }
775        };
776
777        // Try to parse a postfix operator such as `.`, `?`, or index (`[]`)
778        // after a cast. If one is present, emit an error then return a valid
779        // parse tree; For something like `&x as T[0]` will be as if it was
780        // written `((&x) as T)[0]`.
781
782        let span = cast_expr.span;
783
784        let with_postfix = self.parse_expr_dot_or_call_with(AttrVec::new(), cast_expr, span)?;
785
786        // Check if an illegal postfix operator has been added after the cast.
787        // If the resulting expression is not a cast, it is an illegal postfix operator.
788        if !#[allow(non_exhaustive_omitted_patterns)] match with_postfix.kind {
    ExprKind::Cast(_, _) => true,
    _ => false,
}matches!(with_postfix.kind, ExprKind::Cast(_, _)) {
789            let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("cast cannot be followed by {0}",
                match with_postfix.kind {
                    ExprKind::Index(..) => "indexing",
                    ExprKind::Try(_) => "`?`",
                    ExprKind::Field(_, _) => "a field access",
                    ExprKind::MethodCall(_) => "a method call",
                    ExprKind::Call(_, _) => "a function call",
                    ExprKind::Await(_, _) => "`.await`",
                    ExprKind::Use(_, _) => "`.use`",
                    ExprKind::Yield(YieldKind::Postfix(_)) => "`.yield`",
                    ExprKind::Match(_, _, MatchKind::Postfix) =>
                        "a postfix match",
                    ExprKind::Err(_) => return Ok(with_postfix),
                    _ => {
                        ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
                                format_args!("did not expect {0:?} as an illegal postfix operator following cast",
                                    with_postfix.kind)));
                    }
                }))
    })format!(
790                "cast cannot be followed by {}",
791                match with_postfix.kind {
792                    ExprKind::Index(..) => "indexing",
793                    ExprKind::Try(_) => "`?`",
794                    ExprKind::Field(_, _) => "a field access",
795                    ExprKind::MethodCall(_) => "a method call",
796                    ExprKind::Call(_, _) => "a function call",
797                    ExprKind::Await(_, _) => "`.await`",
798                    ExprKind::Use(_, _) => "`.use`",
799                    ExprKind::Yield(YieldKind::Postfix(_)) => "`.yield`",
800                    ExprKind::Match(_, _, MatchKind::Postfix) => "a postfix match",
801                    ExprKind::Err(_) => return Ok(with_postfix),
802                    _ => unreachable!(
803                        "did not expect {:?} as an illegal postfix operator following cast",
804                        with_postfix.kind
805                    ),
806                }
807            );
808            let mut err = self.dcx().struct_span_err(span, msg);
809
810            let suggest_parens = |err: &mut Diag<'_>| {
811                let suggestions = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(span.shrink_to_lo(), "(".to_string()),
                (span.shrink_to_hi(), ")".to_string())]))vec![
812                    (span.shrink_to_lo(), "(".to_string()),
813                    (span.shrink_to_hi(), ")".to_string()),
814                ];
815                err.multipart_suggestion(
816                    "try surrounding the expression in parentheses",
817                    suggestions,
818                    Applicability::MachineApplicable,
819                );
820            };
821
822            suggest_parens(&mut err);
823
824            err.emit();
825        };
826        Ok(with_postfix)
827    }
828
829    /// Parse `& mut? <expr>` or `& raw [ const | mut ] <expr>`.
830    fn parse_expr_borrow(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
831        self.expect_and()?;
832        let has_lifetime = self.token.is_lifetime() && self.look_ahead(1, |t| t != &token::Colon);
833        let lifetime = has_lifetime.then(|| self.expect_lifetime()); // For recovery, see below.
834        let (borrow_kind, mutbl) = self.parse_borrow_modifiers();
835        let attrs = self.parse_outer_attributes()?;
836        let expr = if self.token.is_range_separator() {
837            self.parse_expr_prefix_range(attrs)
838        } else {
839            self.parse_expr_prefix(attrs)
840        }?;
841        let hi = self.interpolated_or_expr_span(&expr);
842        let span = lo.to(hi);
843        if let Some(lt) = lifetime {
844            self.error_remove_borrow_lifetime(span, lt.ident.span.until(expr.span));
845        }
846
847        // Add expected tokens if we parsed `&raw` as an expression.
848        // This will make sure we see "expected `const`, `mut`", and
849        // guides recovery in case we write `&raw expr`.
850        if borrow_kind == ast::BorrowKind::Ref
851            && mutbl == ast::Mutability::Not
852            && #[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)
853        {
854            self.expected_token_types.insert(TokenType::KwMut);
855            self.expected_token_types.insert(TokenType::KwConst);
856        }
857
858        Ok((span, ExprKind::AddrOf(borrow_kind, mutbl, expr)))
859    }
860
861    fn error_remove_borrow_lifetime(&self, span: Span, lt_span: Span) {
862        self.dcx().emit_err(errors::LifetimeInBorrowExpression { span, lifetime_span: lt_span });
863    }
864
865    /// Parse `mut?` or `[ raw | pin ] [ const | mut ]`.
866    fn parse_borrow_modifiers(&mut self) -> (ast::BorrowKind, ast::Mutability) {
867        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) {
868            // `raw [ const | mut ]`.
869            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));
870            if !found_raw { ::core::panicking::panic("assertion failed: found_raw") };assert!(found_raw);
871            let mutability = self.parse_const_or_mut().unwrap();
872            (ast::BorrowKind::Raw, mutability)
873        } else {
874            match self.parse_pin_and_mut() {
875                // `mut?`
876                (ast::Pinnedness::Not, mutbl) => (ast::BorrowKind::Ref, mutbl),
877                // `pin [ const | mut ]`.
878                // `pin` has been gated in `self.parse_pin_and_mut()` so we don't
879                // need to gate it here.
880                (ast::Pinnedness::Pinned, mutbl) => (ast::BorrowKind::Pin, mutbl),
881            }
882        }
883    }
884
885    /// Parses `a.b` or `a(13)` or `a[4]` or just `a`.
886    fn parse_expr_dot_or_call(&mut self, attrs: AttrWrapper) -> PResult<'a, Box<Expr>> {
887        self.collect_tokens_for_expr(attrs, |this, attrs| {
888            let base = this.parse_expr_bottom()?;
889            let span = this.interpolated_or_expr_span(&base);
890            this.parse_expr_dot_or_call_with(attrs, base, span)
891        })
892    }
893
894    pub(super) fn parse_expr_dot_or_call_with(
895        &mut self,
896        mut attrs: ast::AttrVec,
897        mut e: Box<Expr>,
898        lo: Span,
899    ) -> PResult<'a, Box<Expr>> {
900        let mut res = ensure_sufficient_stack(|| {
901            loop {
902                let has_question =
903                    if self.prev_token == TokenKind::Ident(kw::Return, IdentIsRaw::No) {
904                        // We are using noexpect here because we don't expect a `?` directly after
905                        // a `return` which could be suggested otherwise.
906                        self.eat_noexpect(&token::Question)
907                    } else {
908                        self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Question,
    token_type: crate::parser::token_type::TokenType::Question,
}exp!(Question))
909                    };
910                if has_question {
911                    // `expr?`
912                    e = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Try(e));
913                    continue;
914                }
915                let has_dot = if self.prev_token == TokenKind::Ident(kw::Return, IdentIsRaw::No) {
916                    // We are using noexpect here because we don't expect a `.` directly after
917                    // a `return` which could be suggested otherwise.
918                    self.eat_noexpect(&token::Dot)
919                } else if self.token == TokenKind::RArrow && self.may_recover() {
920                    // Recovery for `expr->suffix`.
921                    self.bump();
922                    let span = self.prev_token.span;
923                    self.dcx().emit_err(errors::ExprRArrowCall { span });
924                    true
925                } else {
926                    self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Dot,
    token_type: crate::parser::token_type::TokenType::Dot,
}exp!(Dot))
927                };
928                if has_dot {
929                    // expr.f
930                    e = self.parse_dot_suffix_expr(lo, e)?;
931                    continue;
932                }
933                if self.expr_is_complete(&e) {
934                    return Ok(e);
935                }
936                e = match self.token.kind {
937                    token::OpenParen => self.parse_expr_fn_call(lo, e),
938                    token::OpenBracket => self.parse_expr_index(lo, e)?,
939                    _ => return Ok(e),
940                }
941            }
942        });
943
944        // Stitch the list of outer attributes onto the return value. A little
945        // bit ugly, but the best way given the current code structure.
946        if !attrs.is_empty()
947            && let Ok(expr) = &mut res
948        {
949            mem::swap(&mut expr.attrs, &mut attrs);
950            expr.attrs.extend(attrs)
951        }
952        res
953    }
954
955    pub(super) fn parse_dot_suffix_expr(
956        &mut self,
957        lo: Span,
958        base: Box<Expr>,
959    ) -> PResult<'a, Box<Expr>> {
960        // At this point we've consumed something like `expr.` and `self.token` holds the token
961        // after the dot.
962        match self.token.uninterpolate().kind {
963            token::Ident(..) => self.parse_dot_suffix(base, lo),
964            token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) => {
965                let ident_span = self.token.span;
966                self.bump();
967                Ok(self.mk_expr_tuple_field_access(lo, ident_span, base, symbol, suffix))
968            }
969            token::Literal(token::Lit { kind: token::Float, symbol, suffix }) => {
970                Ok(match self.break_up_float(symbol, self.token.span) {
971                    // 1e2
972                    DestructuredFloat::Single(sym, _sp) => {
973                        // `foo.1e2`: a single complete dot access, fully consumed. We end up with
974                        // the `1e2` token in `self.prev_token` and the following token in
975                        // `self.token`.
976                        let ident_span = self.token.span;
977                        self.bump();
978                        self.mk_expr_tuple_field_access(lo, ident_span, base, sym, suffix)
979                    }
980                    // 1.
981                    DestructuredFloat::TrailingDot(sym, ident_span, dot_span) => {
982                        // `foo.1.`: a single complete dot access and the start of another.
983                        // We end up with the `sym` (`1`) token in `self.prev_token` and a dot in
984                        // `self.token`.
985                        if !suffix.is_none() {
    ::core::panicking::panic("assertion failed: suffix.is_none()")
};assert!(suffix.is_none());
986                        self.token = Token::new(token::Ident(sym, IdentIsRaw::No), ident_span);
987                        self.bump_with((Token::new(token::Dot, dot_span), self.token_spacing));
988                        self.mk_expr_tuple_field_access(lo, ident_span, base, sym, None)
989                    }
990                    // 1.2 | 1.2e3
991                    DestructuredFloat::MiddleDot(
992                        sym1,
993                        ident1_span,
994                        _dot_span,
995                        sym2,
996                        ident2_span,
997                    ) => {
998                        // `foo.1.2` (or `foo.1.2e3`): two complete dot accesses. We end up with
999                        // the `sym2` (`2` or `2e3`) token in `self.prev_token` and the following
1000                        // token in `self.token`.
1001                        let next_token2 =
1002                            Token::new(token::Ident(sym2, IdentIsRaw::No), ident2_span);
1003                        self.bump_with((next_token2, self.token_spacing));
1004                        self.bump();
1005                        let base1 =
1006                            self.mk_expr_tuple_field_access(lo, ident1_span, base, sym1, None);
1007                        self.mk_expr_tuple_field_access(lo, ident2_span, base1, sym2, suffix)
1008                    }
1009                    DestructuredFloat::Error => base,
1010                })
1011            }
1012            _ => {
1013                self.error_unexpected_after_dot();
1014                Ok(base)
1015            }
1016        }
1017    }
1018
1019    fn error_unexpected_after_dot(&self) {
1020        let actual = super::token_descr(&self.token);
1021        let span = self.token.span;
1022        let sm = self.psess.source_map();
1023        let (span, actual) = match (&self.token.kind, self.subparser_name) {
1024            (token::Eof, Some(_)) if let Ok(snippet) = sm.span_to_snippet(sm.next_point(span)) => {
1025                (span.shrink_to_hi(), ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", snippet))
    })format!("`{}`", snippet))
1026            }
1027            (token::CloseInvisible(InvisibleOrigin::MetaVar(_)), _) => {
1028                // No need to report an error. This case will only occur when parsing a pasted
1029                // metavariable, and we should have emitted an error when parsing the macro call in
1030                // the first place. E.g. in this code:
1031                // ```
1032                // macro_rules! m { ($e:expr) => { $e }; }
1033                //
1034                // fn main() {
1035                //     let f = 1;
1036                //     m!(f.);
1037                // }
1038                // ```
1039                // we'll get an error "unexpected token: `)` when parsing the `m!(f.)`, so we don't
1040                // want to issue a second error when parsing the expansion `«f.»` (where `«`/`»`
1041                // represent the invisible delimiters).
1042                self.dcx().span_delayed_bug(span, "bad dot expr in metavariable");
1043                return;
1044            }
1045            _ => (span, actual),
1046        };
1047        self.dcx().emit_err(errors::UnexpectedTokenAfterDot { span, actual });
1048    }
1049
1050    /// We need an identifier or integer, but the next token is a float.
1051    /// Break the float into components to extract the identifier or integer.
1052    ///
1053    /// See also [`TokenKind::break_two_token_op`] which does similar splitting of `>>` into `>`.
1054    //
1055    // FIXME: With current `TokenCursor` it's hard to break tokens into more than 2
1056    //  parts unless those parts are processed immediately. `TokenCursor` should either
1057    //  support pushing "future tokens" (would be also helpful to `break_and_eat`), or
1058    //  we should break everything including floats into more basic proc-macro style
1059    //  tokens in the lexer (probably preferable).
1060    pub(super) fn break_up_float(&self, float: Symbol, span: Span) -> DestructuredFloat {
1061        #[derive(#[automatically_derived]
impl ::core::fmt::Debug for FloatComponent {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            FloatComponent::IdentLike(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "IdentLike", &__self_0),
            FloatComponent::Punct(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Punct",
                    &__self_0),
        }
    }
}Debug)]
1062        enum FloatComponent {
1063            IdentLike(String),
1064            Punct(char),
1065        }
1066        use FloatComponent::*;
1067
1068        let float_str = float.as_str();
1069        let mut components = Vec::new();
1070        let mut ident_like = String::new();
1071        for c in float_str.chars() {
1072            if c == '_' || c.is_ascii_alphanumeric() {
1073                ident_like.push(c);
1074            } else if #[allow(non_exhaustive_omitted_patterns)] match c {
    '.' | '+' | '-' => true,
    _ => false,
}matches!(c, '.' | '+' | '-') {
1075                if !ident_like.is_empty() {
1076                    components.push(IdentLike(mem::take(&mut ident_like)));
1077                }
1078                components.push(Punct(c));
1079            } else {
1080                {
    ::core::panicking::panic_fmt(format_args!("unexpected character in a float token: {0:?}",
            c));
}panic!("unexpected character in a float token: {c:?}")
1081            }
1082        }
1083        if !ident_like.is_empty() {
1084            components.push(IdentLike(ident_like));
1085        }
1086
1087        // With proc macros the span can refer to anything, the source may be too short,
1088        // or too long, or non-ASCII. It only makes sense to break our span into components
1089        // if its underlying text is identical to our float literal.
1090        let can_take_span_apart =
1091            || self.span_to_snippet(span).as_deref() == Ok(float_str).as_deref();
1092
1093        match &*components {
1094            // 1e2
1095            [IdentLike(i)] => {
1096                DestructuredFloat::Single(Symbol::intern(i), span)
1097            }
1098            // 1.
1099            [IdentLike(left), Punct('.')] => {
1100                let (left_span, dot_span) = if can_take_span_apart() {
1101                    let left_span = span.with_hi(span.lo() + BytePos::from_usize(left.len()));
1102                    let dot_span = span.with_lo(left_span.hi());
1103                    (left_span, dot_span)
1104                } else {
1105                    (span, span)
1106                };
1107                let left = Symbol::intern(left);
1108                DestructuredFloat::TrailingDot(left, left_span, dot_span)
1109            }
1110            // 1.2 | 1.2e3
1111            [IdentLike(left), Punct('.'), IdentLike(right)] => {
1112                let (left_span, dot_span, right_span) = if can_take_span_apart() {
1113                    let left_span = span.with_hi(span.lo() + BytePos::from_usize(left.len()));
1114                    let dot_span = span.with_lo(left_span.hi()).with_hi(left_span.hi() + BytePos(1));
1115                    let right_span = span.with_lo(dot_span.hi());
1116                    (left_span, dot_span, right_span)
1117                } else {
1118                    (span, span, span)
1119                };
1120                let left = Symbol::intern(left);
1121                let right = Symbol::intern(right);
1122                DestructuredFloat::MiddleDot(left, left_span, dot_span, right, right_span)
1123            }
1124            // 1e+ | 1e- (recovered)
1125            [IdentLike(_), Punct('+' | '-')] |
1126            // 1e+2 | 1e-2
1127            [IdentLike(_), Punct('+' | '-'), IdentLike(_)] |
1128            // 1.2e+ | 1.2e-
1129            [IdentLike(_), Punct('.'), IdentLike(_), Punct('+' | '-')] |
1130            // 1.2e+3 | 1.2e-3
1131            [IdentLike(_), Punct('.'), IdentLike(_), Punct('+' | '-'), IdentLike(_)] => {
1132                // See the FIXME about `TokenCursor` above.
1133                self.error_unexpected_after_dot();
1134                DestructuredFloat::Error
1135            }
1136            _ => {
    ::core::panicking::panic_fmt(format_args!("unexpected components in a float token: {0:?}",
            components));
}panic!("unexpected components in a float token: {components:?}"),
1137        }
1138    }
1139
1140    /// Parse the field access used in offset_of, matched by `$(e:expr)+`.
1141    /// Currently returns a list of idents. However, it should be possible in
1142    /// future to also do array indices, which might be arbitrary expressions.
1143    fn parse_floating_field_access(&mut self) -> PResult<'a, Vec<Ident>> {
1144        let mut fields = Vec::new();
1145        let mut trailing_dot = None;
1146
1147        loop {
1148            // This is expected to use a metavariable $(args:expr)+, but the builtin syntax
1149            // could be called directly. Calling `parse_expr` allows this function to only
1150            // consider `Expr`s.
1151            let expr = self.parse_expr()?;
1152            let mut current = &expr;
1153            let start_idx = fields.len();
1154            loop {
1155                match current.kind {
1156                    ExprKind::Field(ref left, right) => {
1157                        // Field access is read right-to-left.
1158                        fields.insert(start_idx, right);
1159                        trailing_dot = None;
1160                        current = left;
1161                    }
1162                    // Parse this both to give helpful error messages and to
1163                    // verify it can be done with this parser setup.
1164                    ExprKind::Index(ref left, ref _right, span) => {
1165                        self.dcx().emit_err(errors::ArrayIndexInOffsetOf(span));
1166                        current = left;
1167                    }
1168                    ExprKind::Lit(token::Lit {
1169                        kind: token::Float | token::Integer,
1170                        symbol,
1171                        suffix,
1172                    }) => {
1173                        if let Some(suffix) = suffix {
1174                            self.dcx().emit_err(errors::InvalidLiteralSuffixOnTupleIndex {
1175                                span: current.span,
1176                                suffix,
1177                            });
1178                        }
1179                        match self.break_up_float(symbol, current.span) {
1180                            // 1e2
1181                            DestructuredFloat::Single(sym, sp) => {
1182                                trailing_dot = None;
1183                                fields.insert(start_idx, Ident::new(sym, sp));
1184                            }
1185                            // 1.
1186                            DestructuredFloat::TrailingDot(sym, sym_span, dot_span) => {
1187                                if !suffix.is_none() {
    ::core::panicking::panic("assertion failed: suffix.is_none()")
};assert!(suffix.is_none());
1188                                trailing_dot = Some(dot_span);
1189                                fields.insert(start_idx, Ident::new(sym, sym_span));
1190                            }
1191                            // 1.2 | 1.2e3
1192                            DestructuredFloat::MiddleDot(
1193                                symbol1,
1194                                span1,
1195                                _dot_span,
1196                                symbol2,
1197                                span2,
1198                            ) => {
1199                                trailing_dot = None;
1200                                fields.insert(start_idx, Ident::new(symbol2, span2));
1201                                fields.insert(start_idx, Ident::new(symbol1, span1));
1202                            }
1203                            DestructuredFloat::Error => {
1204                                trailing_dot = None;
1205                                fields.insert(start_idx, Ident::new(symbol, self.prev_token.span));
1206                            }
1207                        }
1208                        break;
1209                    }
1210                    ExprKind::Path(None, Path { ref segments, .. }) => {
1211                        match &segments[..] {
1212                            [PathSegment { ident, args: None, .. }] => {
1213                                trailing_dot = None;
1214                                fields.insert(start_idx, *ident)
1215                            }
1216                            _ => {
1217                                self.dcx().emit_err(errors::InvalidOffsetOf(current.span));
1218                                break;
1219                            }
1220                        }
1221                        break;
1222                    }
1223                    _ => {
1224                        self.dcx().emit_err(errors::InvalidOffsetOf(current.span));
1225                        break;
1226                    }
1227                }
1228            }
1229
1230            if self.token.kind.close_delim().is_some() || self.token.kind == token::Comma {
1231                break;
1232            } else if trailing_dot.is_none() {
1233                // This loop should only repeat if there is a trailing dot.
1234                self.dcx().emit_err(errors::InvalidOffsetOf(self.token.span));
1235                break;
1236            }
1237        }
1238        if let Some(dot) = trailing_dot {
1239            self.dcx().emit_err(errors::InvalidOffsetOf(dot));
1240        }
1241        Ok(fields.into_iter().collect())
1242    }
1243
1244    fn mk_expr_tuple_field_access(
1245        &self,
1246        lo: Span,
1247        ident_span: Span,
1248        base: Box<Expr>,
1249        field: Symbol,
1250        suffix: Option<Symbol>,
1251    ) -> Box<Expr> {
1252        if let Some(suffix) = suffix {
1253            self.dcx()
1254                .emit_err(errors::InvalidLiteralSuffixOnTupleIndex { span: ident_span, suffix });
1255        }
1256        self.mk_expr(lo.to(ident_span), ExprKind::Field(base, Ident::new(field, ident_span)))
1257    }
1258
1259    /// Parse a function call expression, `expr(...)`.
1260    fn parse_expr_fn_call(&mut self, lo: Span, fun: Box<Expr>) -> Box<Expr> {
1261        let snapshot = if self.token == token::OpenParen {
1262            Some((self.create_snapshot_for_diagnostic(), fun.kind.clone()))
1263        } else {
1264            None
1265        };
1266        let open_paren = self.token.span;
1267
1268        let seq = self
1269            .parse_expr_paren_seq()
1270            .map(|args| self.mk_expr(lo.to(self.prev_token.span), self.mk_call(fun, args)));
1271        match self.maybe_recover_struct_lit_bad_delims(lo, open_paren, seq, snapshot) {
1272            Ok(expr) => expr,
1273            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),
1274        }
1275    }
1276
1277    /// If we encounter a parser state that looks like the user has written a `struct` literal with
1278    /// parentheses instead of braces, recover the parser state and provide suggestions.
1279    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("maybe_recover_struct_lit_bad_delims",
                                    "rustc_parse::parser::expr", ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_parse/src/parser/expr.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1279u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_parse::parser::expr"),
                                    ::tracing_core::field::FieldSet::new(&["lo", "open_paren"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&lo)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&open_paren)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

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