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_macros::Subdiagnostic;
25use rustc_session::errors::{ExprParenthesesNeeded, report_lit_error};
26use rustc_session::lint::BuiltinLintDiag;
27use rustc_session::lint::builtin::BREAK_WITH_LABEL_AND_LOOP;
28use rustc_span::edition::Edition;
29use rustc_span::source_map::{self, Spanned};
30use rustc_span::{BytePos, ErrorGuaranteed, Ident, Pos, Span, Symbol, kw, sym};
31use thin_vec::{ThinVec, thin_vec};
32use tracing::instrument;
33
34use super::diagnostics::SnapshotParser;
35use super::pat::{CommaRecoveryMode, Expected, RecoverColon, RecoverComma};
36use super::ty::{AllowPlus, RecoverQPath, RecoverReturnSign};
37use super::{
38    AttrWrapper, BlockMode, ClosureSpans, ExpTokenPair, ForceCollect, Parser, PathStyle,
39    Restrictions, SemiColonMode, SeqSep, TokenType, Trailing, UsePreAttrPos,
40};
41use crate::{errors, exp, maybe_recover_from_interpolated_ty_qpath};
42
43#[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)]
44pub(super) enum DestructuredFloat {
45    /// 1e2
46    Single(Symbol, Span),
47    /// 1.
48    TrailingDot(Symbol, Span, Span),
49    /// 1.2 | 1.2e3
50    MiddleDot(Symbol, Span, Span, Symbol, Span),
51    /// Invalid
52    Error,
53}
54
55impl<'a> Parser<'a> {
56    /// Parses an expression.
57    #[inline]
58    pub fn parse_expr(&mut self) -> PResult<'a, Box<Expr>> {
59        self.current_closure.take();
60
61        let attrs = self.parse_outer_attributes()?;
62        self.parse_expr_res(Restrictions::empty(), attrs).map(|res| res.0)
63    }
64
65    /// Parses an expression, forcing tokens to be collected.
66    pub fn parse_expr_force_collect(&mut self) -> PResult<'a, Box<Expr>> {
67        self.current_closure.take();
68
69        // If the expression is associative (e.g. `1 + 2`), then any preceding
70        // outer attribute actually belongs to the first inner sub-expression.
71        // In which case we must use the pre-attr pos to include the attribute
72        // in the collected tokens for the outer expression.
73        let pre_attr_pos = self.collect_pos();
74        let attrs = self.parse_outer_attributes()?;
75        self.collect_tokens(
76            Some(pre_attr_pos),
77            AttrWrapper::empty(),
78            ForceCollect::Yes,
79            |this, _empty_attrs| {
80                let (expr, is_assoc) = this.parse_expr_res(Restrictions::empty(), attrs)?;
81                let use_pre_attr_pos =
82                    if is_assoc { UsePreAttrPos::Yes } else { UsePreAttrPos::No };
83                Ok((expr, Trailing::No, use_pre_attr_pos))
84            },
85        )
86    }
87
88    pub fn parse_expr_anon_const(
89        &mut self,
90        mgca_disambiguation: impl FnOnce(&Self, &Expr) -> MgcaDisambiguation,
91    ) -> PResult<'a, AnonConst> {
92        self.parse_expr().map(|value| AnonConst {
93            id: DUMMY_NODE_ID,
94            mgca_disambiguation: mgca_disambiguation(self, &value),
95            value,
96        })
97    }
98
99    fn parse_expr_catch_underscore(
100        &mut self,
101        restrictions: Restrictions,
102    ) -> PResult<'a, Box<Expr>> {
103        let attrs = self.parse_outer_attributes()?;
104        match self.parse_expr_res(restrictions, attrs) {
105            Ok((expr, _)) => Ok(expr),
106            Err(err) => match self.token.ident() {
107                Some((Ident { name: kw::Underscore, .. }, IdentIsRaw::No))
108                    if self.may_recover() && self.look_ahead(1, |t| t == &token::Comma) =>
109                {
110                    // Special-case handling of `foo(_, _, _)`
111                    let guar = err.emit();
112                    self.bump();
113                    Ok(self.mk_expr(self.prev_token.span, ExprKind::Err(guar)))
114                }
115                _ => Err(err),
116            },
117        }
118    }
119
120    /// Parses a sequence of expressions delimited by parentheses.
121    fn parse_expr_paren_seq(&mut self) -> PResult<'a, ThinVec<Box<Expr>>> {
122        self.parse_paren_comma_seq(|p| p.parse_expr_catch_underscore(Restrictions::empty()))
123            .map(|(r, _)| r)
124    }
125
126    /// Parses an expression, subject to the given restrictions.
127    #[inline]
128    pub(super) fn parse_expr_res(
129        &mut self,
130        r: Restrictions,
131        attrs: AttrWrapper,
132    ) -> PResult<'a, (Box<Expr>, bool)> {
133        self.with_res(r, |this| this.parse_expr_assoc_with(Bound::Unbounded, attrs))
134    }
135
136    /// Parses an associative expression with operators of at least `min_prec` precedence.
137    /// The `bool` in the return value indicates if it was an assoc expr, i.e. with an operator
138    /// followed by a subexpression (e.g. `1 + 2`).
139    pub(super) fn parse_expr_assoc_with(
140        &mut self,
141        min_prec: Bound<ExprPrecedence>,
142        attrs: AttrWrapper,
143    ) -> PResult<'a, (Box<Expr>, bool)> {
144        let lhs = if self.token.is_range_separator() {
145            return self.parse_expr_prefix_range(attrs).map(|res| (res, false));
146        } else {
147            self.parse_expr_prefix(attrs)?
148        };
149        self.parse_expr_assoc_rest_with(min_prec, false, lhs)
150    }
151
152    /// Parses the rest of an associative expression (i.e. the part after the lhs) with operators
153    /// of at least `min_prec` precedence. The `bool` in the return value indicates if something
154    /// was actually parsed.
155    pub(super) fn parse_expr_assoc_rest_with(
156        &mut self,
157        min_prec: Bound<ExprPrecedence>,
158        starts_stmt: bool,
159        mut lhs: Box<Expr>,
160    ) -> PResult<'a, (Box<Expr>, bool)> {
161        let mut parsed_something = false;
162        if !self.should_continue_as_assoc_expr(&lhs) {
163            return Ok((lhs, parsed_something));
164        }
165
166        self.expected_token_types.insert(TokenType::Operator);
167        while let Some(op) = self.check_assoc_op() {
168            let lhs_span = self.interpolated_or_expr_span(&lhs);
169            let cur_op_span = self.token.span;
170            let restrictions = if op.node.is_assign_like() {
171                self.restrictions & Restrictions::NO_STRUCT_LITERAL
172            } else {
173                self.restrictions
174            };
175            let prec = op.node.precedence();
176            if match min_prec {
177                Bound::Included(min_prec) => prec < min_prec,
178                Bound::Excluded(min_prec) => prec <= min_prec,
179                Bound::Unbounded => false,
180            } {
181                break;
182            }
183            // Check for deprecated `...` syntax
184            if self.token == token::DotDotDot && op.node == AssocOp::Range(RangeLimits::Closed) {
185                self.err_dotdotdot_syntax(self.token.span);
186            }
187
188            if self.token == token::LArrow {
189                self.err_larrow_operator(self.token.span);
190            }
191
192            parsed_something = true;
193            self.bump();
194            if op.node.is_comparison() {
195                if let Some(expr) = self.check_no_chained_comparison(&lhs, &op)? {
196                    return Ok((expr, parsed_something));
197                }
198            }
199
200            // Look for JS' `===` and `!==` and recover
201            if let AssocOp::Binary(bop @ BinOpKind::Eq | bop @ BinOpKind::Ne) = op.node
202                && self.token == token::Eq
203                && self.prev_token.span.hi() == self.token.span.lo()
204            {
205                let sp = op.span.to(self.token.span);
206                let sugg = bop.as_str().into();
207                let invalid = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}=", sugg))
    })format!("{sugg}=");
208                self.dcx().emit_err(errors::InvalidComparisonOperator {
209                    span: sp,
210                    invalid: invalid.clone(),
211                    sub: errors::InvalidComparisonOperatorSub::Correctable {
212                        span: sp,
213                        invalid,
214                        correct: sugg,
215                    },
216                });
217                self.bump();
218            }
219
220            // Look for PHP's `<>` and recover
221            if op.node == AssocOp::Binary(BinOpKind::Lt)
222                && self.token == token::Gt
223                && self.prev_token.span.hi() == self.token.span.lo()
224            {
225                let sp = op.span.to(self.token.span);
226                self.dcx().emit_err(errors::InvalidComparisonOperator {
227                    span: sp,
228                    invalid: "<>".into(),
229                    sub: errors::InvalidComparisonOperatorSub::Correctable {
230                        span: sp,
231                        invalid: "<>".into(),
232                        correct: "!=".into(),
233                    },
234                });
235                self.bump();
236            }
237
238            // Look for C++'s `<=>` and recover
239            if op.node == AssocOp::Binary(BinOpKind::Le)
240                && self.token == token::Gt
241                && self.prev_token.span.hi() == self.token.span.lo()
242            {
243                let sp = op.span.to(self.token.span);
244                self.dcx().emit_err(errors::InvalidComparisonOperator {
245                    span: sp,
246                    invalid: "<=>".into(),
247                    sub: errors::InvalidComparisonOperatorSub::Spaceship(sp),
248                });
249                self.bump();
250            }
251
252            if self.prev_token == token::Plus
253                && self.token == token::Plus
254                && self.prev_token.span.between(self.token.span).is_empty()
255            {
256                let op_span = self.prev_token.span.to(self.token.span);
257                // Eat the second `+`
258                self.bump();
259                lhs = self.recover_from_postfix_increment(lhs, op_span, starts_stmt)?;
260                continue;
261            }
262
263            if self.prev_token == token::Minus
264                && self.token == token::Minus
265                && self.prev_token.span.between(self.token.span).is_empty()
266                && !self.look_ahead(1, |tok| tok.can_begin_expr())
267            {
268                let op_span = self.prev_token.span.to(self.token.span);
269                // Eat the second `-`
270                self.bump();
271                lhs = self.recover_from_postfix_decrement(lhs, op_span, starts_stmt)?;
272                continue;
273            }
274
275            let op_span = op.span;
276            let op = op.node;
277            // Special cases:
278            if op == AssocOp::Cast {
279                lhs = self.parse_assoc_op_cast(lhs, lhs_span, op_span, ExprKind::Cast)?;
280                continue;
281            } else if let AssocOp::Range(limits) = op {
282                // If we didn't have to handle `x..`/`x..=`, it would be pretty easy to
283                // generalise it to the Fixity::None code.
284                lhs = self.parse_expr_range(prec, lhs, limits, cur_op_span)?;
285                break;
286            }
287
288            let min_prec = match op.fixity() {
289                Fixity::Right => Bound::Included(prec),
290                Fixity::Left | Fixity::None => Bound::Excluded(prec),
291            };
292            let (rhs, _) = self.with_res(restrictions - Restrictions::STMT_EXPR, |this| {
293                let attrs = this.parse_outer_attributes()?;
294                this.parse_expr_assoc_with(min_prec, attrs)
295            })?;
296
297            let span = self.mk_expr_sp(&lhs, lhs_span, op_span, rhs.span);
298            lhs = match op {
299                AssocOp::Binary(ast_op) => {
300                    let binary = self.mk_binary(source_map::respan(cur_op_span, ast_op), lhs, rhs);
301                    self.mk_expr(span, binary)
302                }
303                AssocOp::Assign => self.mk_expr(span, ExprKind::Assign(lhs, rhs, cur_op_span)),
304                AssocOp::AssignOp(aop) => {
305                    let aopexpr = self.mk_assign_op(source_map::respan(cur_op_span, aop), lhs, rhs);
306                    self.mk_expr(span, aopexpr)
307                }
308                AssocOp::Cast | AssocOp::Range(_) => {
309                    self.dcx().span_bug(span, "AssocOp should have been handled by special case")
310                }
311            };
312        }
313
314        Ok((lhs, parsed_something))
315    }
316
317    fn should_continue_as_assoc_expr(&mut self, lhs: &Expr) -> bool {
318        match (self.expr_is_complete(lhs), AssocOp::from_token(&self.token)) {
319            // Semi-statement forms are odd:
320            // See https://github.com/rust-lang/rust/issues/29071
321            (true, None) => false,
322            (false, _) => true, // Continue parsing the expression.
323            // An exhaustive check is done in the following block, but these are checked first
324            // because they *are* ambiguous but also reasonable looking incorrect syntax, so we
325            // want to keep their span info to improve diagnostics in these cases in a later stage.
326            (true, Some(AssocOp::Binary(
327                BinOpKind::Mul | // `{ 42 } *foo = bar;` or `{ 42 } * 3`
328                BinOpKind::Sub | // `{ 42 } -5`
329                BinOpKind::Add | // `{ 42 } + 42` (unary plus)
330                BinOpKind::And | // `{ 42 } &&x` (#61475) or `{ 42 } && if x { 1 } else { 0 }`
331                BinOpKind::Or | // `{ 42 } || 42` ("logical or" or closure)
332                BinOpKind::BitOr // `{ 42 } | 42` or `{ 42 } |x| 42`
333            ))) => {
334                // These cases are ambiguous and can't be identified in the parser alone.
335                //
336                // Bitwise AND is left out because guessing intent is hard. We can make
337                // suggestions based on the assumption that double-refs are rarely intentional,
338                // and closures are distinct enough that they don't get mixed up with their
339                // return value.
340                let sp = self.psess.source_map().start_point(self.token.span);
341                self.psess.ambiguous_block_expr_parse.borrow_mut().insert(sp, lhs.span);
342                false
343            }
344            (true, Some(op)) if !op.can_continue_expr_unambiguously() => false,
345            (true, Some(_)) => {
346                self.error_found_expr_would_be_stmt(lhs);
347                true
348            }
349        }
350    }
351
352    /// We've found an expression that would be parsed as a statement,
353    /// but the next token implies this should be parsed as an expression.
354    /// For example: `if let Some(x) = x { x } else { 0 } / 2`.
355    fn error_found_expr_would_be_stmt(&self, lhs: &Expr) {
356        self.dcx().emit_err(errors::FoundExprWouldBeStmt {
357            span: self.token.span,
358            token: self.token,
359            suggestion: ExprParenthesesNeeded::surrounding(lhs.span),
360        });
361    }
362
363    /// Possibly translate the current token to an associative operator.
364    /// The method does not advance the current token.
365    ///
366    /// Also performs recovery for `and` / `or` which are mistaken for `&&` and `||` respectively.
367    pub(super) fn check_assoc_op(&self) -> Option<Spanned<AssocOp>> {
368        let (op, span) = match (AssocOp::from_token(&self.token), self.token.ident()) {
369            // When parsing const expressions, stop parsing when encountering `>`.
370            (
371                Some(
372                    AssocOp::Binary(BinOpKind::Shr | BinOpKind::Gt | BinOpKind::Ge)
373                    | AssocOp::AssignOp(AssignOpKind::ShrAssign),
374                ),
375                _,
376            ) if self.restrictions.contains(Restrictions::CONST_EXPR) => {
377                return None;
378            }
379            // When recovering patterns as expressions, stop parsing when encountering an
380            // assignment `=`, an alternative `|`, or a range `..`.
381            (
382                Some(
383                    AssocOp::Assign
384                    | AssocOp::AssignOp(_)
385                    | AssocOp::Binary(BinOpKind::BitOr)
386                    | AssocOp::Range(_),
387                ),
388                _,
389            ) if self.restrictions.contains(Restrictions::IS_PAT) => {
390                return None;
391            }
392            (Some(op), _) => (op, self.token.span),
393            (None, Some((Ident { name: sym::and, span }, IdentIsRaw::No)))
394                if self.may_recover() =>
395            {
396                self.dcx().emit_err(errors::InvalidLogicalOperator {
397                    span: self.token.span,
398                    incorrect: "and".into(),
399                    sub: errors::InvalidLogicalOperatorSub::Conjunction(self.token.span),
400                });
401                (AssocOp::Binary(BinOpKind::And), span)
402            }
403            (None, Some((Ident { name: sym::or, span }, IdentIsRaw::No))) if self.may_recover() => {
404                self.dcx().emit_err(errors::InvalidLogicalOperator {
405                    span: self.token.span,
406                    incorrect: "or".into(),
407                    sub: errors::InvalidLogicalOperatorSub::Disjunction(self.token.span),
408                });
409                (AssocOp::Binary(BinOpKind::Or), span)
410            }
411            _ => return None,
412        };
413        Some(source_map::respan(span, op))
414    }
415
416    /// Checks if this expression is a successfully parsed statement.
417    fn expr_is_complete(&self, e: &Expr) -> bool {
418        self.restrictions.contains(Restrictions::STMT_EXPR) && classify::expr_is_complete(e)
419    }
420
421    /// Parses `x..y`, `x..=y`, and `x..`/`x..=`.
422    /// The other two variants are handled in `parse_prefix_range_expr` below.
423    fn parse_expr_range(
424        &mut self,
425        prec: ExprPrecedence,
426        lhs: Box<Expr>,
427        limits: RangeLimits,
428        cur_op_span: Span,
429    ) -> PResult<'a, Box<Expr>> {
430        let rhs = if self.is_at_start_of_range_notation_rhs() {
431            let maybe_lt = self.token;
432            let attrs = self.parse_outer_attributes()?;
433            Some(
434                self.parse_expr_assoc_with(Bound::Excluded(prec), attrs)
435                    .map_err(|err| self.maybe_err_dotdotlt_syntax(maybe_lt, err))?
436                    .0,
437            )
438        } else {
439            None
440        };
441        let rhs_span = rhs.as_ref().map_or(cur_op_span, |x| x.span);
442        let span = self.mk_expr_sp(&lhs, lhs.span, cur_op_span, rhs_span);
443        let range = self.mk_range(Some(lhs), rhs, limits);
444        Ok(self.mk_expr(span, range))
445    }
446
447    fn is_at_start_of_range_notation_rhs(&self) -> bool {
448        if self.token.can_begin_expr() {
449            // Parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
450            if self.token == token::OpenBrace {
451                return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
452            }
453            true
454        } else {
455            false
456        }
457    }
458
459    /// Parses prefix-forms of range notation: `..expr`, `..`, `..=expr`.
460    fn parse_expr_prefix_range(&mut self, attrs: AttrWrapper) -> PResult<'a, Box<Expr>> {
461        if !attrs.is_empty() {
462            let err = errors::DotDotRangeAttribute { span: self.token.span };
463            self.dcx().emit_err(err);
464        }
465
466        // Check for deprecated `...` syntax.
467        if self.token == token::DotDotDot {
468            self.err_dotdotdot_syntax(self.token.span);
469        }
470
471        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!(
472            self.token.is_range_separator(),
473            "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
474            self.token
475        );
476
477        let limits = match self.token.kind {
478            token::DotDot => RangeLimits::HalfOpen,
479            _ => RangeLimits::Closed,
480        };
481        let op = AssocOp::from_token(&self.token);
482        let attrs = self.parse_outer_attributes()?;
483        self.collect_tokens_for_expr(attrs, |this, attrs| {
484            let lo = this.token.span;
485            let maybe_lt = this.look_ahead(1, |t| t.clone());
486            this.bump();
487            let (span, opt_end) = if this.is_at_start_of_range_notation_rhs() {
488                // RHS must be parsed with more associativity than the dots.
489                let attrs = this.parse_outer_attributes()?;
490                this.parse_expr_assoc_with(Bound::Excluded(op.unwrap().precedence()), attrs)
491                    .map(|(x, _)| (lo.to(x.span), Some(x)))
492                    .map_err(|err| this.maybe_err_dotdotlt_syntax(maybe_lt, err))?
493            } else {
494                (lo, None)
495            };
496            let range = this.mk_range(None, opt_end, limits);
497            Ok(this.mk_expr_with_attrs(span, range, attrs))
498        })
499    }
500
501    /// Parses a prefix-unary-operator expr.
502    fn parse_expr_prefix(&mut self, attrs: AttrWrapper) -> PResult<'a, Box<Expr>> {
503        let lo = self.token.span;
504
505        macro_rules! make_it {
506            ($this:ident, $attrs:expr, |this, _| $body:expr) => {
507                $this.collect_tokens_for_expr($attrs, |$this, attrs| {
508                    let (hi, ex) = $body?;
509                    Ok($this.mk_expr_with_attrs(lo.to(hi), ex, attrs))
510                })
511            };
512        }
513
514        let this = self;
515
516        // Note: when adding new unary operators, don't forget to adjust TokenKind::can_begin_expr()
517        match this.token.uninterpolate().kind {
518            // `!expr`
519            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)),
520            // `~expr`
521            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)),
522            // `-expr`
523            token::Minus => {
524                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))
525            }
526            // `*expr`
527            token::Star => {
528                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))
529            }
530            // `&expr` and `&&expr`
531            token::And | token::AndAnd => {
532                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))
533            }
534            // `+lit`
535            token::Plus if this.look_ahead(1, |tok| tok.is_numeric_lit()) => {
536                let mut err = errors::LeadingPlusNotSupported {
537                    span: lo,
538                    remove_plus: None,
539                    add_parentheses: None,
540                };
541
542                // a block on the LHS might have been intended to be an expression instead
543                if let Some(sp) = this.psess.ambiguous_block_expr_parse.borrow().get(&lo) {
544                    err.add_parentheses = Some(ExprParenthesesNeeded::surrounding(*sp));
545                } else {
546                    err.remove_plus = Some(lo);
547                }
548                this.dcx().emit_err(err);
549
550                this.bump();
551                let attrs = this.parse_outer_attributes()?;
552                this.parse_expr_prefix(attrs)
553            }
554            // Recover from `++x`:
555            token::Plus if this.look_ahead(1, |t| *t == token::Plus) => {
556                let starts_stmt =
557                    this.prev_token == token::Semi || this.prev_token == token::CloseBrace;
558                let pre_span = this.token.span.to(this.look_ahead(1, |t| t.span));
559                // Eat both `+`s.
560                this.bump();
561                this.bump();
562
563                let operand_expr = this.parse_expr_dot_or_call(attrs)?;
564                this.recover_from_prefix_increment(operand_expr, pre_span, starts_stmt)
565            }
566            token::Ident(..) if this.token.is_keyword(kw::Box) => {
567                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))
568            }
569            token::Ident(..) if this.may_recover() && this.is_mistaken_not_ident_negation() => {
570                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))
571            }
572            _ => return this.parse_expr_dot_or_call(attrs),
573        }
574    }
575
576    fn parse_expr_prefix_common(&mut self, lo: Span) -> PResult<'a, (Span, Box<Expr>)> {
577        self.bump();
578        let attrs = self.parse_outer_attributes()?;
579        let expr = if self.token.is_range_separator() {
580            self.parse_expr_prefix_range(attrs)
581        } else {
582            self.parse_expr_prefix(attrs)
583        }?;
584        let span = self.interpolated_or_expr_span(&expr);
585        Ok((lo.to(span), expr))
586    }
587
588    fn parse_expr_unary(&mut self, lo: Span, op: UnOp) -> PResult<'a, (Span, ExprKind)> {
589        let (span, expr) = self.parse_expr_prefix_common(lo)?;
590        Ok((span, self.mk_unary(op, expr)))
591    }
592
593    /// Recover on `~expr` in favor of `!expr`.
594    fn recover_tilde_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
595        self.dcx().emit_err(errors::TildeAsUnaryOperator(lo));
596
597        self.parse_expr_unary(lo, UnOp::Not)
598    }
599
600    /// Parse `box expr` - this syntax has been removed, but we still parse this
601    /// for now to provide a more useful error
602    fn parse_expr_box(&mut self, box_kw: Span) -> PResult<'a, (Span, ExprKind)> {
603        let (span, expr) = self.parse_expr_prefix_common(box_kw)?;
604        // Make a multipart suggestion instead of `span_to_snippet` in case source isn't available
605        let box_kw_and_lo = box_kw.until(self.interpolated_or_expr_span(&expr));
606        let hi = span.shrink_to_hi();
607        let sugg = errors::AddBoxNew { box_kw_and_lo, hi };
608        let guar = self.dcx().emit_err(errors::BoxSyntaxRemoved { span, sugg });
609        Ok((span, ExprKind::Err(guar)))
610    }
611
612    fn is_mistaken_not_ident_negation(&self) -> bool {
613        let token_cannot_continue_expr = |t: &Token| match t.uninterpolate().kind {
614            // These tokens can start an expression after `!`, but
615            // can't continue an expression after an ident
616            token::Ident(name, is_raw) => token::ident_can_begin_expr(name, t.span, is_raw),
617            token::Literal(..) | token::Pound => true,
618            _ => t.is_metavar_expr(),
619        };
620        self.token.is_ident_named(sym::not) && self.look_ahead(1, token_cannot_continue_expr)
621    }
622
623    /// Recover on `not expr` in favor of `!expr`.
624    fn recover_not_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> {
625        let negated_token = self.look_ahead(1, |t| *t);
626
627        let sub_diag = if negated_token.is_numeric_lit() {
628            errors::NotAsNegationOperatorSub::SuggestNotBitwise
629        } else if negated_token.is_bool_lit() {
630            errors::NotAsNegationOperatorSub::SuggestNotLogical
631        } else {
632            errors::NotAsNegationOperatorSub::SuggestNotDefault
633        };
634
635        self.dcx().emit_err(errors::NotAsNegationOperator {
636            negated: negated_token.span,
637            negated_desc: super::token_descr(&negated_token),
638            // Span the `not` plus trailing whitespace to avoid
639            // trailing whitespace after the `!` in our suggestion
640            sub: sub_diag(
641                self.psess.source_map().span_until_non_whitespace(lo.to(negated_token.span)),
642            ),
643        });
644
645        self.parse_expr_unary(lo, UnOp::Not)
646    }
647
648    /// Returns the span of expr if it was not interpolated, or the span of the interpolated token.
649    fn interpolated_or_expr_span(&self, expr: &Expr) -> Span {
650        match self.prev_token.kind {
651            token::NtIdent(..) | token::NtLifetime(..) => self.prev_token.span,
652            token::CloseInvisible(InvisibleOrigin::MetaVar(_)) => {
653                // `expr.span` is the interpolated span, because invisible open
654                // and close delims both get marked with the same span, one
655                // that covers the entire thing between them. (See
656                // `rustc_expand::mbe::transcribe::transcribe`.)
657                self.prev_token.span
658            }
659            _ => expr.span,
660        }
661    }
662
663    fn parse_assoc_op_cast(
664        &mut self,
665        lhs: Box<Expr>,
666        lhs_span: Span,
667        op_span: Span,
668        expr_kind: fn(Box<Expr>, Box<Ty>) -> ExprKind,
669    ) -> PResult<'a, Box<Expr>> {
670        let mk_expr = |this: &mut Self, lhs: Box<Expr>, rhs: Box<Ty>| {
671            this.mk_expr(this.mk_expr_sp(&lhs, lhs_span, op_span, rhs.span), expr_kind(lhs, rhs))
672        };
673
674        // Save the state of the parser before parsing type normally, in case there is a
675        // LessThan comparison after this cast.
676        let parser_snapshot_before_type = self.clone();
677        let cast_expr = match self.parse_as_cast_ty() {
678            Ok(rhs) => mk_expr(self, lhs, rhs),
679            Err(type_err) => {
680                if !self.may_recover() {
681                    return Err(type_err);
682                }
683
684                // Rewind to before attempting to parse the type with generics, to recover
685                // from situations like `x as usize < y` in which we first tried to parse
686                // `usize < y` as a type with generic arguments.
687                let parser_snapshot_after_type = mem::replace(self, parser_snapshot_before_type);
688
689                // Check for typo of `'a: loop { break 'a }` with a missing `'`.
690                match (&lhs.kind, &self.token.kind) {
691                    (
692                        // `foo: `
693                        ExprKind::Path(None, ast::Path { segments, .. }),
694                        token::Ident(kw::For | kw::Loop | kw::While, IdentIsRaw::No),
695                    ) if let [segment] = segments.as_slice() => {
696                        let snapshot = self.create_snapshot_for_diagnostic();
697                        let label = Label {
698                            ident: Ident::from_str_and_span(
699                                &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\'{0}", segment.ident))
    })format!("'{}", segment.ident),
700                                segment.ident.span,
701                            ),
702                        };
703                        match self.parse_expr_labeled(label, false) {
704                            Ok(expr) => {
705                                type_err.cancel();
706                                self.dcx().emit_err(errors::MalformedLoopLabel {
707                                    span: label.ident.span,
708                                    suggestion: label.ident.span.shrink_to_lo(),
709                                });
710                                return Ok(expr);
711                            }
712                            Err(err) => {
713                                err.cancel();
714                                self.restore_snapshot(snapshot);
715                            }
716                        }
717                    }
718                    _ => {}
719                }
720
721                match self.parse_path(PathStyle::Expr) {
722                    Ok(path) => {
723                        let span_after_type = parser_snapshot_after_type.token.span;
724                        let expr = mk_expr(
725                            self,
726                            lhs,
727                            self.mk_ty(path.span, TyKind::Path(None, path.clone())),
728                        );
729
730                        let args_span = self.look_ahead(1, |t| t.span).to(span_after_type);
731                        let suggestion = errors::ComparisonOrShiftInterpretedAsGenericSugg {
732                            left: expr.span.shrink_to_lo(),
733                            right: expr.span.shrink_to_hi(),
734                        };
735
736                        match self.token.kind {
737                            token::Lt => {
738                                self.dcx().emit_err(errors::ComparisonInterpretedAsGeneric {
739                                    comparison: self.token.span,
740                                    r#type: path,
741                                    args: args_span,
742                                    suggestion,
743                                })
744                            }
745                            token::Shl => self.dcx().emit_err(errors::ShiftInterpretedAsGeneric {
746                                shift: self.token.span,
747                                r#type: path,
748                                args: args_span,
749                                suggestion,
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 = <[_]>::into_vec(::alloc::boxed::box_new([(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)
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 = if self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Const,
    token_type: crate::parser::token_type::TokenType::KwConst,
}exp!(Const)) {
1632                    // While we could just disambiguate `Direct` from `AnonConst` by
1633                    // treating all const block exprs as `AnonConst`, that would
1634                    // complicate the DefCollector and likely all other visitors.
1635                    // So we strip the const blockiness and just store it as a block
1636                    // in the AST with the extra disambiguator on the AnonConst
1637                    self.parse_mgca_const_block(false)?
1638                } else {
1639                    self.parse_expr_anon_const(|this, expr| this.mgca_direct_lit_hack(expr))?
1640                };
1641                self.expect(close)?;
1642                ExprKind::Repeat(first_expr, count)
1643            } else if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma)) {
1644                // Vector with two or more elements.
1645                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));
1646                let (mut exprs, _) = self.parse_seq_to_end(close, sep, |p| p.parse_expr())?;
1647                exprs.insert(0, first_expr);
1648                ExprKind::Array(exprs)
1649            } else {
1650                // Vector with one element
1651                self.expect(close)?;
1652                ExprKind::Array({
    let len = [()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(first_expr);
    vec
}thin_vec![first_expr])
1653            }
1654        };
1655        let expr = self.mk_expr(lo.to(self.prev_token.span), kind);
1656        self.maybe_recover_from_bad_qpath(expr)
1657    }
1658
1659    fn parse_expr_path_start(&mut self) -> PResult<'a, Box<Expr>> {
1660        let maybe_eq_tok = self.prev_token;
1661        let (qself, path) = if self.eat_lt() {
1662            let lt_span = self.prev_token.span;
1663            let (qself, path) = self.parse_qpath(PathStyle::Expr).map_err(|mut err| {
1664                // Suggests using '<=' if there is an error parsing qpath when the previous token
1665                // is an '=' token. Only emits suggestion if the '<' token and '=' token are
1666                // directly adjacent (i.e. '=<')
1667                if maybe_eq_tok == TokenKind::Eq && maybe_eq_tok.span.hi() == lt_span.lo() {
1668                    let eq_lt = maybe_eq_tok.span.to(lt_span);
1669                    err.span_suggestion(eq_lt, "did you mean", "<=", Applicability::Unspecified);
1670                }
1671                err
1672            })?;
1673            (Some(qself), path)
1674        } else {
1675            (None, self.parse_path(PathStyle::Expr)?)
1676        };
1677
1678        // `!`, as an operator, is prefix, so we know this isn't that.
1679        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)) {
1680            // MACRO INVOCATION expression
1681            if qself.is_some() {
1682                self.dcx().emit_err(errors::MacroInvocationWithQualifiedPath(path.span));
1683            }
1684            let lo = path.span;
1685            let mac = Box::new(MacCall { path, args: self.parse_delim_args()? });
1686            (lo.to(self.prev_token.span), ExprKind::MacCall(mac))
1687        } else if self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenBrace,
    token_type: crate::parser::token_type::TokenType::OpenBrace,
}exp!(OpenBrace))
1688            && let Some(expr) = self.maybe_parse_struct_expr(&qself, &path)
1689        {
1690            if qself.is_some() {
1691                self.psess.gated_spans.gate(sym::more_qualified_paths, path.span);
1692            }
1693            return expr;
1694        } else {
1695            (path.span, ExprKind::Path(qself, path))
1696        };
1697
1698        let expr = self.mk_expr(span, kind);
1699        self.maybe_recover_from_bad_qpath(expr)
1700    }
1701
1702    /// Parse `'label: $expr`. The label is already parsed.
1703    pub(super) fn parse_expr_labeled(
1704        &mut self,
1705        label_: Label,
1706        mut consume_colon: bool,
1707    ) -> PResult<'a, Box<Expr>> {
1708        let lo = label_.ident.span;
1709        let label = Some(label_);
1710        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));
1711        let tok_sp = self.token.span;
1712        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)) {
1713            self.parse_expr_while(label, lo)
1714        } 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)) {
1715            self.parse_expr_for(label, lo)
1716        } 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)) {
1717            self.parse_expr_loop(label, lo)
1718        } else if self.check_noexpect(&token::OpenBrace) || self.token.is_metavar_block() {
1719            self.parse_expr_block(label, lo, BlockCheckMode::Default)
1720        } else if !ate_colon
1721            && self.may_recover()
1722            && (self.token.kind.close_delim().is_some() || self.token.is_punct())
1723            && could_be_unclosed_char_literal(label_.ident)
1724        {
1725            let (lit, _) =
1726                self.recover_unclosed_char(label_.ident, Parser::mk_token_lit_char, |self_| {
1727                    self_.dcx().create_err(errors::UnexpectedTokenAfterLabel {
1728                        span: self_.token.span,
1729                        remove_label: None,
1730                        enclose_in_block: None,
1731                    })
1732                });
1733            consume_colon = false;
1734            Ok(self.mk_expr(lo, ExprKind::Lit(lit)))
1735        } else if !ate_colon
1736            && (self.check_noexpect(&TokenKind::Comma) || self.check_noexpect(&TokenKind::Gt))
1737        {
1738            // We're probably inside of a `Path<'a>` that needs a turbofish
1739            let guar = self.dcx().emit_err(errors::UnexpectedTokenAfterLabel {
1740                span: self.token.span,
1741                remove_label: None,
1742                enclose_in_block: None,
1743            });
1744            consume_colon = false;
1745            Ok(self.mk_expr_err(lo, guar))
1746        } else {
1747            let mut err = errors::UnexpectedTokenAfterLabel {
1748                span: self.token.span,
1749                remove_label: None,
1750                enclose_in_block: None,
1751            };
1752
1753            // Continue as an expression in an effort to recover on `'label: non_block_expr`.
1754            let expr = self.parse_expr().map(|expr| {
1755                let span = expr.span;
1756
1757                let found_labeled_breaks = {
1758                    struct FindLabeledBreaksVisitor;
1759
1760                    impl<'ast> Visitor<'ast> for FindLabeledBreaksVisitor {
1761                        type Result = ControlFlow<()>;
1762                        fn visit_expr(&mut self, ex: &'ast Expr) -> ControlFlow<()> {
1763                            if let ExprKind::Break(Some(_label), _) = ex.kind {
1764                                ControlFlow::Break(())
1765                            } else {
1766                                walk_expr(self, ex)
1767                            }
1768                        }
1769                    }
1770
1771                    FindLabeledBreaksVisitor.visit_expr(&expr).is_break()
1772                };
1773
1774                // Suggestion involves adding a labeled block.
1775                //
1776                // If there are no breaks that may use this label, suggest removing the label and
1777                // recover to the unmodified expression.
1778                if !found_labeled_breaks {
1779                    err.remove_label = Some(lo.until(span));
1780
1781                    return expr;
1782                }
1783
1784                err.enclose_in_block = Some(errors::UnexpectedTokenAfterLabelSugg {
1785                    left: span.shrink_to_lo(),
1786                    right: span.shrink_to_hi(),
1787                });
1788
1789                // Replace `'label: non_block_expr` with `'label: {non_block_expr}` in order to suppress future errors about `break 'label`.
1790                let stmt = self.mk_stmt(span, StmtKind::Expr(expr));
1791                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);
1792                self.mk_expr(span, ExprKind::Block(blk, label))
1793            });
1794
1795            self.dcx().emit_err(err);
1796            expr
1797        }?;
1798
1799        if !ate_colon && consume_colon {
1800            self.dcx().emit_err(errors::RequireColonAfterLabeledExpression {
1801                span: expr.span,
1802                label: lo,
1803                label_end: lo.between(tok_sp),
1804            });
1805        }
1806
1807        Ok(expr)
1808    }
1809
1810    /// Emit an error when a char is parsed as a lifetime or label because of a missing quote.
1811    pub(super) fn recover_unclosed_char<L>(
1812        &self,
1813        ident: Ident,
1814        mk_lit_char: impl FnOnce(Symbol, Span) -> L,
1815        err: impl FnOnce(&Self) -> Diag<'a>,
1816    ) -> L {
1817        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));
1818        self.dcx()
1819            .try_steal_modify_and_emit_err(ident.span, StashKey::LifetimeIsChar, |err| {
1820                err.span_suggestion_verbose(
1821                    ident.span.shrink_to_hi(),
1822                    "add `'` to close the char literal",
1823                    "'",
1824                    Applicability::MaybeIncorrect,
1825                );
1826            })
1827            .unwrap_or_else(|| {
1828                err(self)
1829                    .with_span_suggestion_verbose(
1830                        ident.span.shrink_to_hi(),
1831                        "add `'` to close the char literal",
1832                        "'",
1833                        Applicability::MaybeIncorrect,
1834                    )
1835                    .emit()
1836            });
1837        let name = ident.without_first_quote().name;
1838        mk_lit_char(name, ident.span)
1839    }
1840
1841    /// Recover on the syntax `do catch { ... }` suggesting `try { ... }` instead.
1842    fn recover_do_catch(&mut self) -> PResult<'a, Box<Expr>> {
1843        let lo = self.token.span;
1844
1845        self.bump(); // `do`
1846        self.bump(); // `catch`
1847
1848        let span = lo.to(self.prev_token.span);
1849        self.dcx().emit_err(errors::DoCatchSyntaxRemoved { span });
1850
1851        self.parse_try_block(lo)
1852    }
1853
1854    /// Parse an expression if the token can begin one.
1855    fn parse_expr_opt(&mut self) -> PResult<'a, Option<Box<Expr>>> {
1856        Ok(if self.token.can_begin_expr() { Some(self.parse_expr()?) } else { None })
1857    }
1858
1859    /// Parse `"return" expr?`.
1860    fn parse_expr_return(&mut self) -> PResult<'a, Box<Expr>> {
1861        let lo = self.prev_token.span;
1862        let kind = ExprKind::Ret(self.parse_expr_opt()?);
1863        let expr = self.mk_expr(lo.to(self.prev_token.span), kind);
1864        self.maybe_recover_from_bad_qpath(expr)
1865    }
1866
1867    /// Parse `"do" "yeet" expr?`.
1868    fn parse_expr_yeet(&mut self) -> PResult<'a, Box<Expr>> {
1869        let lo = self.token.span;
1870
1871        self.bump(); // `do`
1872        self.bump(); // `yeet`
1873
1874        let kind = ExprKind::Yeet(self.parse_expr_opt()?);
1875
1876        let span = lo.to(self.prev_token.span);
1877        self.psess.gated_spans.gate(sym::yeet_expr, span);
1878        let expr = self.mk_expr(span, kind);
1879        self.maybe_recover_from_bad_qpath(expr)
1880    }
1881
1882    /// Parse `"become" expr`, with `"become"` token already eaten.
1883    fn parse_expr_become(&mut self) -> PResult<'a, Box<Expr>> {
1884        let lo = self.prev_token.span;
1885        let kind = ExprKind::Become(self.parse_expr()?);
1886        let span = lo.to(self.prev_token.span);
1887        self.psess.gated_spans.gate(sym::explicit_tail_calls, span);
1888        let expr = self.mk_expr(span, kind);
1889        self.maybe_recover_from_bad_qpath(expr)
1890    }
1891
1892    /// Parse `"break" (('label (:? expr)?) | expr?)` with `"break"` token already eaten.
1893    /// If the label is followed immediately by a `:` token, the label and `:` are
1894    /// parsed as part of the expression (i.e. a labeled loop). The language team has
1895    /// decided in #87026 to require parentheses as a visual aid to avoid confusion if
1896    /// the break expression of an unlabeled break is a labeled loop (as in
1897    /// `break 'lbl: loop {}`); a labeled break with an unlabeled loop as its value
1898    /// expression only gets a warning for compatibility reasons; and a labeled break
1899    /// with a labeled loop does not even get a warning because there is no ambiguity.
1900    fn parse_expr_break(&mut self) -> PResult<'a, Box<Expr>> {
1901        let lo = self.prev_token.span;
1902        let mut label = self.eat_label();
1903        let kind = if self.token == token::Colon
1904            && let Some(label) = label.take()
1905        {
1906            // The value expression can be a labeled loop, see issue #86948, e.g.:
1907            // `loop { break 'label: loop { break 'label 42; }; }`
1908            let lexpr = self.parse_expr_labeled(label, true)?;
1909            self.dcx().emit_err(errors::LabeledLoopInBreak {
1910                span: lexpr.span,
1911                sub: errors::WrapInParentheses::Expression {
1912                    left: lexpr.span.shrink_to_lo(),
1913                    right: lexpr.span.shrink_to_hi(),
1914                },
1915            });
1916            Some(lexpr)
1917        } else if self.token != token::OpenBrace
1918            || !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
1919        {
1920            let mut expr = self.parse_expr_opt()?;
1921            if let Some(expr) = &mut expr {
1922                if label.is_some()
1923                    && match &expr.kind {
1924                        ExprKind::While(_, _, None)
1925                        | ExprKind::ForLoop { label: None, .. }
1926                        | ExprKind::Loop(_, None, _) => true,
1927                        ExprKind::Block(block, None) => {
1928                            #[allow(non_exhaustive_omitted_patterns)] match block.rules {
    BlockCheckMode::Default => true,
    _ => false,
}matches!(block.rules, BlockCheckMode::Default)
1929                        }
1930                        _ => false,
1931                    }
1932                {
1933                    self.psess.buffer_lint(
1934                        BREAK_WITH_LABEL_AND_LOOP,
1935                        lo.to(expr.span),
1936                        ast::CRATE_NODE_ID,
1937                        BuiltinLintDiag::BreakWithLabelAndLoop(expr.span),
1938                    );
1939                }
1940
1941                // Recover `break label aaaaa`
1942                if self.may_recover()
1943                    && let ExprKind::Path(None, p) = &expr.kind
1944                    && let [segment] = &*p.segments
1945                    && let &ast::PathSegment { ident, args: None, .. } = segment
1946                    && let Some(next) = self.parse_expr_opt()?
1947                {
1948                    label = Some(self.recover_ident_into_label(ident));
1949                    *expr = next;
1950                }
1951            }
1952
1953            expr
1954        } else {
1955            None
1956        };
1957        let expr = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Break(label, kind));
1958        self.maybe_recover_from_bad_qpath(expr)
1959    }
1960
1961    /// Parse `"continue" label?`.
1962    fn parse_expr_continue(&mut self, lo: Span) -> PResult<'a, Box<Expr>> {
1963        let mut label = self.eat_label();
1964
1965        // Recover `continue label` -> `continue 'label`
1966        if self.may_recover()
1967            && label.is_none()
1968            && let Some((ident, _)) = self.token.ident()
1969        {
1970            self.bump();
1971            label = Some(self.recover_ident_into_label(ident));
1972        }
1973
1974        let kind = ExprKind::Continue(label);
1975        Ok(self.mk_expr(lo.to(self.prev_token.span), kind))
1976    }
1977
1978    /// Parse `"yield" expr?`.
1979    fn parse_expr_yield(&mut self) -> PResult<'a, Box<Expr>> {
1980        let lo = self.prev_token.span;
1981        let kind = ExprKind::Yield(YieldKind::Prefix(self.parse_expr_opt()?));
1982        let span = lo.to(self.prev_token.span);
1983        self.psess.gated_spans.gate(sym::yield_expr, span);
1984        let expr = self.mk_expr(span, kind);
1985        self.maybe_recover_from_bad_qpath(expr)
1986    }
1987
1988    /// Parse `builtin # ident(args,*)`.
1989    fn parse_expr_builtin(&mut self) -> PResult<'a, Box<Expr>> {
1990        self.parse_builtin(|this, lo, ident| {
1991            Ok(match ident.name {
1992                sym::offset_of => Some(this.parse_expr_offset_of(lo)?),
1993                sym::type_ascribe => Some(this.parse_expr_type_ascribe(lo)?),
1994                sym::wrap_binder => {
1995                    Some(this.parse_expr_unsafe_binder_cast(lo, UnsafeBinderCastKind::Wrap)?)
1996                }
1997                sym::unwrap_binder => {
1998                    Some(this.parse_expr_unsafe_binder_cast(lo, UnsafeBinderCastKind::Unwrap)?)
1999                }
2000                _ => None,
2001            })
2002        })
2003    }
2004
2005    pub(crate) fn parse_builtin<T>(
2006        &mut self,
2007        parse: impl FnOnce(&mut Parser<'a>, Span, Ident) -> PResult<'a, Option<T>>,
2008    ) -> PResult<'a, T> {
2009        let lo = self.token.span;
2010
2011        self.bump(); // `builtin`
2012        self.bump(); // `#`
2013
2014        let Some((ident, IdentIsRaw::No)) = self.token.ident() else {
2015            let err = self.dcx().create_err(errors::ExpectedBuiltinIdent { span: self.token.span });
2016            return Err(err);
2017        };
2018        self.psess.gated_spans.gate(sym::builtin_syntax, ident.span);
2019        self.bump();
2020
2021        self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenParen,
    token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen))?;
2022        let ret = if let Some(res) = parse(self, lo, ident)? {
2023            Ok(res)
2024        } else {
2025            let err = self.dcx().create_err(errors::UnknownBuiltinConstruct {
2026                span: lo.to(ident.span),
2027                name: ident,
2028            });
2029            return Err(err);
2030        };
2031        self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseParen,
    token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen))?;
2032
2033        ret
2034    }
2035
2036    /// Built-in macro for `offset_of!` expressions.
2037    pub(crate) fn parse_expr_offset_of(&mut self, lo: Span) -> PResult<'a, Box<Expr>> {
2038        let container = self.parse_ty()?;
2039        self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma))?;
2040
2041        let fields = self.parse_floating_field_access()?;
2042        let trailing_comma = self.eat_noexpect(&TokenKind::Comma);
2043
2044        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)]) {
2045            if trailing_comma {
2046                e.note("unexpected third argument to offset_of");
2047            } else {
2048                e.note("offset_of expects dot-separated field and variant names");
2049            }
2050            e.emit();
2051        }
2052
2053        // Eat tokens until the macro call ends.
2054        if self.may_recover() {
2055            while !self.token.kind.is_close_delim_or_eof() {
2056                self.bump();
2057            }
2058        }
2059
2060        let span = lo.to(self.token.span);
2061        Ok(self.mk_expr(span, ExprKind::OffsetOf(container, fields)))
2062    }
2063
2064    /// Built-in macro for type ascription expressions.
2065    pub(crate) fn parse_expr_type_ascribe(&mut self, lo: Span) -> PResult<'a, Box<Expr>> {
2066        let expr = self.parse_expr()?;
2067        self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma))?;
2068        let ty = self.parse_ty()?;
2069        let span = lo.to(self.token.span);
2070        Ok(self.mk_expr(span, ExprKind::Type(expr, ty)))
2071    }
2072
2073    pub(crate) fn parse_expr_unsafe_binder_cast(
2074        &mut self,
2075        lo: Span,
2076        kind: UnsafeBinderCastKind,
2077    ) -> PResult<'a, Box<Expr>> {
2078        let expr = self.parse_expr()?;
2079        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 };
2080        let span = lo.to(self.token.span);
2081        Ok(self.mk_expr(span, ExprKind::UnsafeBinderCast(kind, expr, ty)))
2082    }
2083
2084    /// Returns a string literal if the next token is a string literal.
2085    /// In case of error returns `Some(lit)` if the next token is a literal with a wrong kind,
2086    /// and returns `None` if the next token is not literal at all.
2087    pub fn parse_str_lit(&mut self) -> Result<ast::StrLit, Option<MetaItemLit>> {
2088        match self.parse_opt_meta_item_lit() {
2089            Some(lit) => match lit.kind {
2090                ast::LitKind::Str(symbol_unescaped, style) => Ok(ast::StrLit {
2091                    style,
2092                    symbol: lit.symbol,
2093                    suffix: lit.suffix,
2094                    span: lit.span,
2095                    symbol_unescaped,
2096                }),
2097                _ => Err(Some(lit)),
2098            },
2099            None => Err(None),
2100        }
2101    }
2102
2103    pub(crate) fn mk_token_lit_char(name: Symbol, span: Span) -> (token::Lit, Span) {
2104        (token::Lit { symbol: name, suffix: None, kind: token::Char }, span)
2105    }
2106
2107    fn mk_meta_item_lit_char(name: Symbol, span: Span) -> MetaItemLit {
2108        ast::MetaItemLit {
2109            symbol: name,
2110            suffix: None,
2111            kind: ast::LitKind::Char(name.as_str().chars().next().unwrap_or('_')),
2112            span,
2113        }
2114    }
2115
2116    fn handle_missing_lit<L>(
2117        &mut self,
2118        mk_lit_char: impl FnOnce(Symbol, Span) -> L,
2119    ) -> PResult<'a, L> {
2120        let token = self.token;
2121        let err = |self_: &Self| {
2122            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));
2123            self_.dcx().struct_span_err(token.span, msg)
2124        };
2125        // On an error path, eagerly consider a lifetime to be an unclosed character lit, if that
2126        // makes sense.
2127        if let Some((ident, IdentIsRaw::No)) = self.token.lifetime()
2128            && could_be_unclosed_char_literal(ident)
2129        {
2130            let lt = self.expect_lifetime();
2131            Ok(self.recover_unclosed_char(lt.ident, mk_lit_char, err))
2132        } else {
2133            Err(err(self))
2134        }
2135    }
2136
2137    pub(super) fn parse_token_lit(&mut self) -> PResult<'a, (token::Lit, Span)> {
2138        self.parse_opt_token_lit()
2139            .ok_or(())
2140            .or_else(|()| self.handle_missing_lit(Parser::mk_token_lit_char))
2141    }
2142
2143    pub(super) fn parse_meta_item_lit(&mut self) -> PResult<'a, MetaItemLit> {
2144        self.parse_opt_meta_item_lit()
2145            .ok_or(())
2146            .or_else(|()| self.handle_missing_lit(Parser::mk_meta_item_lit_char))
2147    }
2148
2149    fn recover_after_dot(&mut self) {
2150        if self.token == token::Dot {
2151            // Attempt to recover `.4` as `0.4`. We don't currently have any syntax where
2152            // dot would follow an optional literal, so we do this unconditionally.
2153            let recovered = self.look_ahead(1, |next_token| {
2154                // If it's an integer that looks like a float, then recover as such.
2155                //
2156                // We will never encounter the exponent part of a floating
2157                // point literal here, since there's no use of the exponent
2158                // syntax that also constitutes a valid integer, so we need
2159                // not check for that.
2160                if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) =
2161                    next_token.kind
2162                    && suffix.is_none_or(|s| s == sym::f32 || s == sym::f64)
2163                    && symbol.as_str().chars().all(|c| c.is_numeric() || c == '_')
2164                    && self.token.span.hi() == next_token.span.lo()
2165                {
2166                    let s = String::from("0.") + symbol.as_str();
2167                    let kind = TokenKind::lit(token::Float, Symbol::intern(&s), suffix);
2168                    Some(Token::new(kind, self.token.span.to(next_token.span)))
2169                } else {
2170                    None
2171                }
2172            });
2173            if let Some(recovered) = recovered {
2174                self.dcx().emit_err(errors::FloatLiteralRequiresIntegerPart {
2175                    span: recovered.span,
2176                    suggestion: recovered.span.shrink_to_lo(),
2177                });
2178                self.bump();
2179                self.token = recovered;
2180            }
2181        }
2182    }
2183
2184    /// Keep this in sync with `Token::can_begin_literal_maybe_minus` and
2185    /// `Lit::from_token` (excluding unary negation).
2186    pub fn eat_token_lit(&mut self) -> Option<token::Lit> {
2187        let check_expr = |expr: Box<Expr>| {
2188            if let ast::ExprKind::Lit(token_lit) = expr.kind {
2189                Some(token_lit)
2190            } else if let ast::ExprKind::Unary(UnOp::Neg, inner) = &expr.kind
2191                && let ast::Expr { kind: ast::ExprKind::Lit(_), .. } = **inner
2192            {
2193                None
2194            } else {
2195                {
    ::core::panicking::panic_fmt(format_args!("unexpected reparsed expr/literal: {0:?}",
            expr.kind));
};panic!("unexpected reparsed expr/literal: {:?}", expr.kind);
2196            }
2197        };
2198        match self.token.uninterpolate().kind {
2199            token::Ident(name, IdentIsRaw::No) if name.is_bool_lit() => {
2200                self.bump();
2201                Some(token::Lit::new(token::Bool, name, None))
2202            }
2203            token::Literal(token_lit) => {
2204                self.bump();
2205                Some(token_lit)
2206            }
2207            token::OpenInvisible(InvisibleOrigin::MetaVar(MetaVarKind::Literal)) => {
2208                let lit = self
2209                    .eat_metavar_seq(MetaVarKind::Literal, |this| this.parse_literal_maybe_minus())
2210                    .expect("metavar seq literal");
2211                check_expr(lit)
2212            }
2213            token::OpenInvisible(InvisibleOrigin::MetaVar(
2214                mv_kind @ MetaVarKind::Expr { can_begin_literal_maybe_minus: true, .. },
2215            )) => {
2216                let expr = self
2217                    .eat_metavar_seq(mv_kind, |this| this.parse_expr())
2218                    .expect("metavar seq expr");
2219                check_expr(expr)
2220            }
2221            _ => None,
2222        }
2223    }
2224
2225    /// Matches `lit = true | false | token_lit`.
2226    /// Returns `None` if the next token is not a literal.
2227    fn parse_opt_token_lit(&mut self) -> Option<(token::Lit, Span)> {
2228        self.recover_after_dot();
2229        let span = self.token.span;
2230        self.eat_token_lit().map(|token_lit| (token_lit, span))
2231    }
2232
2233    /// Matches `lit = true | false | token_lit`.
2234    /// Returns `None` if the next token is not a literal.
2235    fn parse_opt_meta_item_lit(&mut self) -> Option<MetaItemLit> {
2236        self.recover_after_dot();
2237        let span = self.token.span;
2238        let uninterpolated_span = self.token_uninterpolated_span();
2239        self.eat_token_lit().map(|token_lit| {
2240            match MetaItemLit::from_token_lit(token_lit, span) {
2241                Ok(lit) => lit,
2242                Err(err) => {
2243                    let guar = report_lit_error(&self.psess, err, token_lit, uninterpolated_span);
2244                    // Pack possible quotes and prefixes from the original literal into
2245                    // the error literal's symbol so they can be pretty-printed faithfully.
2246                    let suffixless_lit = token::Lit::new(token_lit.kind, token_lit.symbol, None);
2247                    let symbol = Symbol::intern(&suffixless_lit.to_string());
2248                    let token_lit = token::Lit::new(token::Err(guar), symbol, token_lit.suffix);
2249                    MetaItemLit::from_token_lit(token_lit, uninterpolated_span).unwrap()
2250                }
2251            }
2252        })
2253    }
2254
2255    /// Matches `'-' lit | lit` (cf. `ast_validation::AstValidator::check_expr_within_pat`).
2256    /// Keep this in sync with `Token::can_begin_literal_maybe_minus`.
2257    pub fn parse_literal_maybe_minus(&mut self) -> PResult<'a, Box<Expr>> {
2258        if let Some(expr) = self.eat_metavar_seq_with_matcher(
2259            |mv_kind| #[allow(non_exhaustive_omitted_patterns)] match mv_kind {
    MetaVarKind::Expr { .. } => true,
    _ => false,
}matches!(mv_kind, MetaVarKind::Expr { .. }),
2260            |this| {
2261                // FIXME(nnethercote) The `expr` case should only match if
2262                // `e` is an `ExprKind::Lit` or an `ExprKind::Unary` containing
2263                // an `UnOp::Neg` and an `ExprKind::Lit`, like how
2264                // `can_begin_literal_maybe_minus` works. But this method has
2265                // been over-accepting for a long time, and to make that change
2266                // here requires also changing some `parse_literal_maybe_minus`
2267                // call sites to accept additional expression kinds. E.g.
2268                // `ExprKind::Path` must be accepted when parsing range
2269                // patterns. That requires some care. So for now, we continue
2270                // being less strict here than we should be.
2271                this.parse_expr()
2272            },
2273        ) {
2274            return Ok(expr);
2275        } else if let Some(lit) =
2276            self.eat_metavar_seq(MetaVarKind::Literal, |this| this.parse_literal_maybe_minus())
2277        {
2278            return Ok(lit);
2279        }
2280
2281        let lo = self.token.span;
2282        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));
2283        let (token_lit, span) = self.parse_token_lit()?;
2284        let expr = self.mk_expr(span, ExprKind::Lit(token_lit));
2285
2286        if minus_present {
2287            Ok(self.mk_expr(lo.to(self.prev_token.span), self.mk_unary(UnOp::Neg, expr)))
2288        } else {
2289            Ok(expr)
2290        }
2291    }
2292
2293    fn is_array_like_block(&mut self) -> bool {
2294        self.token.kind == TokenKind::OpenBrace
2295            && self
2296                .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(_)))
2297            && self.look_ahead(2, |t| t == &token::Comma)
2298            && self.look_ahead(3, |t| t.can_begin_expr())
2299    }
2300
2301    /// Emits a suggestion if it looks like the user meant an array but
2302    /// accidentally used braces, causing the code to be interpreted as a block
2303    /// expression.
2304    fn maybe_suggest_brackets_instead_of_braces(&mut self, lo: Span) -> Option<Box<Expr>> {
2305        let mut snapshot = self.create_snapshot_for_diagnostic();
2306        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)) {
2307            Ok(arr) => {
2308                let guar = self.dcx().emit_err(errors::ArrayBracketsInsteadOfBraces {
2309                    span: arr.span,
2310                    sub: errors::ArrayBracketsInsteadOfBracesSugg {
2311                        left: lo,
2312                        right: snapshot.prev_token.span,
2313                    },
2314                });
2315
2316                self.restore_snapshot(snapshot);
2317                Some(self.mk_expr_err(arr.span, guar))
2318            }
2319            Err(e) => {
2320                e.cancel();
2321                None
2322            }
2323        }
2324    }
2325
2326    fn suggest_missing_semicolon_before_array(
2327        &self,
2328        prev_span: Span,
2329        open_delim_span: Span,
2330    ) -> PResult<'a, ()> {
2331        if !self.may_recover() {
2332            return Ok(());
2333        }
2334
2335        if self.token == token::Comma {
2336            if !self.psess.source_map().is_multiline(prev_span.until(self.token.span)) {
2337                return Ok(());
2338            }
2339            let mut snapshot = self.create_snapshot_for_diagnostic();
2340            snapshot.bump();
2341            match snapshot.parse_seq_to_before_end(
2342                crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseBracket,
    token_type: crate::parser::token_type::TokenType::CloseBracket,
}exp!(CloseBracket),
2343                SeqSep::trailing_allowed(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma)),
2344                |p| p.parse_expr(),
2345            ) {
2346                Ok(_)
2347                    // When the close delim is `)`, `token.kind` is expected to be `token::CloseParen`,
2348                    // but the actual `token.kind` is `token::CloseBracket`.
2349                    // This is because the `token.kind` of the close delim is treated as the same as
2350                    // that of the open delim in `TokenTreesReader::parse_token_tree`, even if the delimiters of them are different.
2351                    // Therefore, `token.kind` should not be compared here.
2352                    if snapshot
2353                        .span_to_snippet(snapshot.token.span)
2354                        .is_ok_and(|snippet| snippet == "]") =>
2355                {
2356                    return Err(self.dcx().create_err(errors::MissingSemicolonBeforeArray {
2357                        open_delim: open_delim_span,
2358                        semicolon: prev_span.shrink_to_hi(),
2359                    }));
2360                }
2361                Ok(_) => (),
2362                Err(err) => err.cancel(),
2363            }
2364        }
2365        Ok(())
2366    }
2367
2368    /// Parses a block or unsafe block.
2369    pub(super) fn parse_expr_block(
2370        &mut self,
2371        opt_label: Option<Label>,
2372        lo: Span,
2373        blk_mode: BlockCheckMode,
2374    ) -> PResult<'a, Box<Expr>> {
2375        if self.may_recover() && self.is_array_like_block() {
2376            if let Some(arr) = self.maybe_suggest_brackets_instead_of_braces(lo) {
2377                return Ok(arr);
2378            }
2379        }
2380
2381        if self.token.is_metavar_block() {
2382            self.dcx().emit_err(errors::InvalidBlockMacroSegment {
2383                span: self.token.span,
2384                context: lo.to(self.token.span),
2385                wrap: errors::WrapInExplicitBlock {
2386                    lo: self.token.span.shrink_to_lo(),
2387                    hi: self.token.span.shrink_to_hi(),
2388                },
2389            });
2390        }
2391
2392        let (attrs, blk) = self.parse_block_common(lo, blk_mode, None)?;
2393        Ok(self.mk_expr_with_attrs(blk.span, ExprKind::Block(blk, opt_label), attrs))
2394    }
2395
2396    /// Parse a block which takes no attributes and has no label
2397    fn parse_simple_block(&mut self) -> PResult<'a, Box<Expr>> {
2398        let blk = self.parse_block()?;
2399        Ok(self.mk_expr(blk.span, ExprKind::Block(blk, None)))
2400    }
2401
2402    /// Parses a closure expression (e.g., `move |args| expr`).
2403    fn parse_expr_closure(&mut self) -> PResult<'a, Box<Expr>> {
2404        let lo = self.token.span;
2405
2406        let before = self.prev_token;
2407        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)) {
2408            let lo = self.token.span;
2409            let (bound_vars, _) = self.parse_higher_ranked_binder()?;
2410            let span = lo.to(self.prev_token.span);
2411
2412            self.psess.gated_spans.gate(sym::closure_lifetime_binder, span);
2413
2414            ClosureBinder::For { span, generic_params: bound_vars }
2415        } else {
2416            ClosureBinder::NotPresent
2417        };
2418
2419        let constness = self.parse_closure_constness();
2420
2421        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)) {
2422            self.psess.gated_spans.gate(sym::coroutines, self.prev_token.span);
2423            Movability::Static
2424        } else {
2425            Movability::Movable
2426        };
2427
2428        let coroutine_kind = if self.token_uninterpolated_span().at_least_rust_2018() {
2429            self.parse_coroutine_kind(Case::Sensitive)
2430        } else {
2431            None
2432        };
2433
2434        if let ClosureBinder::NotPresent = binder
2435            && coroutine_kind.is_some()
2436        {
2437            // coroutine closures and generators can have the same qualifiers, so we might end up
2438            // in here if there is a missing `|` but also no `{`. Adjust the expectations in that case.
2439            self.expected_token_types.insert(TokenType::OpenBrace);
2440        }
2441
2442        let capture_clause = self.parse_capture_clause()?;
2443        let (fn_decl, fn_arg_span) = self.parse_fn_block_decl()?;
2444        let decl_hi = self.prev_token.span;
2445        let mut body = match &fn_decl.output {
2446            // No return type.
2447            FnRetTy::Default(_) => {
2448                let restrictions =
2449                    self.restrictions - Restrictions::STMT_EXPR - Restrictions::ALLOW_LET;
2450                let prev = self.prev_token;
2451                let token = self.token;
2452                let attrs = self.parse_outer_attributes()?;
2453                match self.parse_expr_res(restrictions, attrs) {
2454                    Ok((expr, _)) => expr,
2455                    Err(err) => self.recover_closure_body(err, before, prev, token, lo, decl_hi)?,
2456                }
2457            }
2458            // Explicit return type (`->`) needs block `-> T { }`.
2459            FnRetTy::Ty(ty) => self.parse_closure_block_body(ty.span)?,
2460        };
2461
2462        match coroutine_kind {
2463            Some(CoroutineKind::Async { .. }) => {}
2464            Some(CoroutineKind::Gen { span, .. }) | Some(CoroutineKind::AsyncGen { span, .. }) => {
2465                // Feature-gate `gen ||` and `async gen ||` closures.
2466                // FIXME(gen_blocks): This perhaps should be a different gate.
2467                self.psess.gated_spans.gate(sym::gen_blocks, span);
2468            }
2469            None => {}
2470        }
2471
2472        if self.token == TokenKind::Semi
2473            && let Some(last) = self.token_cursor.stack.last()
2474            && let Some(TokenTree::Delimited(_, _, Delimiter::Parenthesis, _)) = last.curr()
2475            && self.may_recover()
2476        {
2477            // It is likely that the closure body is a block but where the
2478            // braces have been removed. We will recover and eat the next
2479            // statements later in the parsing process.
2480            body = self.mk_expr_err(
2481                body.span,
2482                self.dcx().span_delayed_bug(body.span, "recovered a closure body as a block"),
2483            );
2484        }
2485
2486        let body_span = body.span;
2487
2488        let closure = self.mk_expr(
2489            lo.to(body.span),
2490            ExprKind::Closure(Box::new(ast::Closure {
2491                binder,
2492                capture_clause,
2493                constness,
2494                coroutine_kind,
2495                movability,
2496                fn_decl,
2497                body,
2498                fn_decl_span: lo.to(decl_hi),
2499                fn_arg_span,
2500            })),
2501        );
2502
2503        // Disable recovery for closure body
2504        let spans =
2505            ClosureSpans { whole_closure: closure.span, closing_pipe: decl_hi, body: body_span };
2506        self.current_closure = Some(spans);
2507
2508        Ok(closure)
2509    }
2510
2511    /// If an explicit return type is given, require a block to appear (RFC 968).
2512    fn parse_closure_block_body(&mut self, ret_span: Span) -> PResult<'a, Box<Expr>> {
2513        if self.may_recover()
2514            && self.token.can_begin_expr()
2515            && self.token.kind != TokenKind::OpenBrace
2516            && !self.token.is_metavar_block()
2517        {
2518            let snapshot = self.create_snapshot_for_diagnostic();
2519            let restrictions =
2520                self.restrictions - Restrictions::STMT_EXPR - Restrictions::ALLOW_LET;
2521            let tok = self.token.clone();
2522            match self.parse_expr_res(restrictions, AttrWrapper::empty()) {
2523                Ok((expr, _)) => {
2524                    let descr = super::token_descr(&tok);
2525                    let mut diag = self
2526                        .dcx()
2527                        .struct_span_err(tok.span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected `{{`, found {0}", descr))
    })format!("expected `{{`, found {descr}"));
2528                    diag.span_label(
2529                        ret_span,
2530                        "explicit return type requires closure body to be enclosed in braces",
2531                    );
2532                    diag.multipart_suggestion_verbose(
2533                        "wrap the expression in curly braces",
2534                        <[_]>::into_vec(::alloc::boxed::box_new([(expr.span.shrink_to_lo(),
                    "{ ".to_string()),
                (expr.span.shrink_to_hi(), " }".to_string())]))vec![
2535                            (expr.span.shrink_to_lo(), "{ ".to_string()),
2536                            (expr.span.shrink_to_hi(), " }".to_string()),
2537                        ],
2538                        Applicability::MachineApplicable,
2539                    );
2540                    diag.emit();
2541                    return Ok(expr);
2542                }
2543                Err(diag) => {
2544                    diag.cancel();
2545                    self.restore_snapshot(snapshot);
2546                }
2547            }
2548        }
2549
2550        let body_lo = self.token.span;
2551        self.parse_expr_block(None, body_lo, BlockCheckMode::Default)
2552    }
2553
2554    /// Parses an optional `move` or `use` prefix to a closure-like construct.
2555    fn parse_capture_clause(&mut self) -> PResult<'a, CaptureBy> {
2556        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)) {
2557            let move_kw_span = self.prev_token.span;
2558            // Check for `move async` and recover
2559            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)) {
2560                let move_async_span = self.token.span.with_lo(self.prev_token.span.data().lo);
2561                Err(self
2562                    .dcx()
2563                    .create_err(errors::AsyncMoveOrderIncorrect { span: move_async_span }))
2564            } else {
2565                Ok(CaptureBy::Value { move_kw: move_kw_span })
2566            }
2567        } 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)) {
2568            let use_kw_span = self.prev_token.span;
2569            self.psess.gated_spans.gate(sym::ergonomic_clones, use_kw_span);
2570            // Check for `use async` and recover
2571            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)) {
2572                let use_async_span = self.token.span.with_lo(self.prev_token.span.data().lo);
2573                Err(self.dcx().create_err(errors::AsyncUseOrderIncorrect { span: use_async_span }))
2574            } else {
2575                Ok(CaptureBy::Use { use_kw: use_kw_span })
2576            }
2577        } else {
2578            Ok(CaptureBy::Ref)
2579        }
2580    }
2581
2582    /// Parses the `|arg, arg|` header of a closure.
2583    fn parse_fn_block_decl(&mut self) -> PResult<'a, (Box<FnDecl>, Span)> {
2584        let arg_start = self.token.span.lo();
2585
2586        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)) {
2587            ThinVec::new()
2588        } else {
2589            self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Or,
    token_type: crate::parser::token_type::TokenType::Or,
}exp!(Or))?;
2590            let args = self
2591                .parse_seq_to_before_tokens(
2592                    &[crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Or,
    token_type: crate::parser::token_type::TokenType::Or,
}exp!(Or)],
2593                    &[&token::OrOr],
2594                    SeqSep::trailing_allowed(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma)),
2595                    |p| p.parse_fn_block_param(),
2596                )?
2597                .0;
2598            self.expect_or()?;
2599            args
2600        };
2601        let arg_span = self.prev_token.span.with_lo(arg_start);
2602        let output =
2603            self.parse_ret_ty(AllowPlus::Yes, RecoverQPath::Yes, RecoverReturnSign::Yes)?;
2604
2605        Ok((Box::new(FnDecl { inputs, output }), arg_span))
2606    }
2607
2608    /// Parses a parameter in a closure header (e.g., `|arg, arg|`).
2609    fn parse_fn_block_param(&mut self) -> PResult<'a, Param> {
2610        let lo = self.token.span;
2611        let attrs = self.parse_outer_attributes()?;
2612        self.collect_tokens(None, attrs, ForceCollect::No, |this, attrs| {
2613            let pat = Box::new(this.parse_pat_no_top_alt(Some(Expected::ParameterName), None)?);
2614            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)) {
2615                this.parse_ty()?
2616            } else {
2617                this.mk_ty(pat.span, TyKind::Infer)
2618            };
2619
2620            Ok((
2621                Param {
2622                    attrs,
2623                    ty,
2624                    pat,
2625                    span: lo.to(this.prev_token.span),
2626                    id: DUMMY_NODE_ID,
2627                    is_placeholder: false,
2628                },
2629                Trailing::from(this.token == token::Comma),
2630                UsePreAttrPos::No,
2631            ))
2632        })
2633    }
2634
2635    /// Parses an `if` expression (`if` token already eaten).
2636    fn parse_expr_if(&mut self) -> PResult<'a, Box<Expr>> {
2637        let lo = self.prev_token.span;
2638        // Scoping code checks the top level edition of the `if`; let's match it here.
2639        // The `CondChecker` also checks the edition of the `let` itself, just to make sure.
2640        let let_chains_policy = LetChainsPolicy::EditionDependent { current_edition: lo.edition() };
2641        let cond = self.parse_expr_cond(let_chains_policy)?;
2642        self.parse_if_after_cond(lo, cond)
2643    }
2644
2645    fn parse_if_after_cond(&mut self, lo: Span, mut cond: Box<Expr>) -> PResult<'a, Box<Expr>> {
2646        let cond_span = cond.span;
2647        // Tries to interpret `cond` as either a missing expression if it's a block,
2648        // or as an unfinished expression if it's a binop and the RHS is a block.
2649        // We could probably add more recoveries here too...
2650        let mut recover_block_from_condition = |this: &mut Self| {
2651            let block = match &mut cond.kind {
2652                ExprKind::Binary(Spanned { span: binop_span, .. }, _, right)
2653                    if let ExprKind::Block(_, None) = right.kind =>
2654                {
2655                    let guar = this.dcx().emit_err(errors::IfExpressionMissingThenBlock {
2656                        if_span: lo,
2657                        missing_then_block_sub:
2658                            errors::IfExpressionMissingThenBlockSub::UnfinishedCondition(
2659                                cond_span.shrink_to_lo().to(*binop_span),
2660                            ),
2661                        let_else_sub: None,
2662                    });
2663                    std::mem::replace(right, this.mk_expr_err(binop_span.shrink_to_hi(), guar))
2664                }
2665                ExprKind::Block(_, None) => {
2666                    let guar = this.dcx().emit_err(errors::IfExpressionMissingCondition {
2667                        if_span: lo.with_neighbor(cond.span).shrink_to_hi(),
2668                        block_span: self.psess.source_map().start_point(cond_span),
2669                    });
2670                    std::mem::replace(&mut cond, this.mk_expr_err(cond_span.shrink_to_hi(), guar))
2671                }
2672                _ => {
2673                    return None;
2674                }
2675            };
2676            if let ExprKind::Block(block, _) = &block.kind {
2677                Some(block.clone())
2678            } else {
2679                ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
2680            }
2681        };
2682        // Parse then block
2683        let thn = if self.token.is_keyword(kw::Else) {
2684            if let Some(block) = recover_block_from_condition(self) {
2685                block
2686            } else {
2687                let let_else_sub = #[allow(non_exhaustive_omitted_patterns)] match cond.kind {
    ExprKind::Let(..) => true,
    _ => false,
}matches!(cond.kind, ExprKind::Let(..))
2688                    .then(|| errors::IfExpressionLetSomeSub { if_span: lo.until(cond_span) });
2689
2690                let guar = self.dcx().emit_err(errors::IfExpressionMissingThenBlock {
2691                    if_span: lo,
2692                    missing_then_block_sub: errors::IfExpressionMissingThenBlockSub::AddThenBlock(
2693                        cond_span.shrink_to_hi(),
2694                    ),
2695                    let_else_sub,
2696                });
2697                self.mk_block_err(cond_span.shrink_to_hi(), guar)
2698            }
2699        } else {
2700            let attrs = self.parse_outer_attributes()?; // For recovery.
2701            let maybe_fatarrow = self.token;
2702            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)) {
2703                self.parse_block()?
2704            } else if let Some(block) = recover_block_from_condition(self) {
2705                block
2706            } else {
2707                self.error_on_extra_if(&cond)?;
2708                // Parse block, which will always fail, but we can add a nice note to the error
2709                self.parse_block().map_err(|mut err| {
2710                        if self.prev_token == token::Semi
2711                            && self.token == token::AndAnd
2712                            && let maybe_let = self.look_ahead(1, |t| t.clone())
2713                            && maybe_let.is_keyword(kw::Let)
2714                        {
2715                            err.span_suggestion(
2716                                self.prev_token.span,
2717                                "consider removing this semicolon to parse the `let` as part of the same chain",
2718                                "",
2719                                Applicability::MachineApplicable,
2720                            ).span_note(
2721                                self.token.span.to(maybe_let.span),
2722                                "you likely meant to continue parsing the let-chain starting here",
2723                            );
2724                        } else {
2725                            // Look for usages of '=>' where '>=' might be intended
2726                            if maybe_fatarrow == token::FatArrow {
2727                                err.span_suggestion(
2728                                    maybe_fatarrow.span,
2729                                    "you might have meant to write a \"greater than or equal to\" comparison",
2730                                    ">=",
2731                                    Applicability::MaybeIncorrect,
2732                                );
2733                            }
2734                            err.span_note(
2735                                cond_span,
2736                                "the `if` expression is missing a block after this condition",
2737                            );
2738                        }
2739                        err
2740                    })?
2741            };
2742            self.error_on_if_block_attrs(lo, false, block.span, attrs);
2743            block
2744        };
2745        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 };
2746        Ok(self.mk_expr(lo.to(self.prev_token.span), ExprKind::If(cond, thn, els)))
2747    }
2748
2749    /// Parses the condition of a `if` or `while` expression.
2750    ///
2751    /// The specified `edition` in `let_chains_policy` should be that of the whole `if` construct,
2752    /// i.e. the same span we use to later decide whether the drop behaviour should be that of
2753    /// edition `..=2021` or that of `2024..`.
2754    // Public to use it for custom `if` expressions in rustfmt forks like https://github.com/tucant/rustfmt
2755    pub fn parse_expr_cond(
2756        &mut self,
2757        let_chains_policy: LetChainsPolicy,
2758    ) -> PResult<'a, Box<Expr>> {
2759        let attrs = self.parse_outer_attributes()?;
2760        let (mut cond, _) =
2761            self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL | Restrictions::ALLOW_LET, attrs)?;
2762
2763        let mut checker = CondChecker::new(self, let_chains_policy);
2764        checker.visit_expr(&mut cond);
2765        Ok(if let Some(guar) = checker.found_incorrect_let_chain {
2766            self.mk_expr_err(cond.span, guar)
2767        } else {
2768            cond
2769        })
2770    }
2771
2772    /// Parses a `let $pat = $expr` pseudo-expression.
2773    fn parse_expr_let(&mut self, restrictions: Restrictions) -> PResult<'a, Box<Expr>> {
2774        let recovered = if !restrictions.contains(Restrictions::ALLOW_LET) {
2775            let err = errors::ExpectedExpressionFoundLet {
2776                span: self.token.span,
2777                reason: ForbiddenLetReason::OtherForbidden,
2778                missing_let: None,
2779                comparison: None,
2780            };
2781            if self.prev_token == token::Or {
2782                // This was part of a closure, the that part of the parser recover.
2783                return Err(self.dcx().create_err(err));
2784            } else {
2785                Recovered::Yes(self.dcx().emit_err(err))
2786            }
2787        } else {
2788            Recovered::No
2789        };
2790        self.bump(); // Eat `let` token
2791        let lo = self.prev_token.span;
2792        let pat = self.parse_pat_no_top_guard(
2793            None,
2794            RecoverComma::Yes,
2795            RecoverColon::Yes,
2796            CommaRecoveryMode::LikelyTuple,
2797        )?;
2798        if self.token == token::EqEq {
2799            self.dcx().emit_err(errors::ExpectedEqForLetExpr {
2800                span: self.token.span,
2801                sugg_span: self.token.span,
2802            });
2803            self.bump();
2804        } else {
2805            self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Eq,
    token_type: crate::parser::token_type::TokenType::Eq,
}exp!(Eq))?;
2806        }
2807        let attrs = self.parse_outer_attributes()?;
2808        let (expr, _) =
2809            self.parse_expr_assoc_with(Bound::Excluded(prec_let_scrutinee_needs_par()), attrs)?;
2810        let span = lo.to(expr.span);
2811        Ok(self.mk_expr(span, ExprKind::Let(Box::new(pat), expr, span, recovered)))
2812    }
2813
2814    /// Parses an `else { ... }` expression (`else` token already eaten).
2815    fn parse_expr_else(&mut self) -> PResult<'a, Box<Expr>> {
2816        let else_span = self.prev_token.span; // `else`
2817        let attrs = self.parse_outer_attributes()?; // For recovery.
2818        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)) {
2819            ensure_sufficient_stack(|| self.parse_expr_if())?
2820        } else if self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenBrace,
    token_type: crate::parser::token_type::TokenType::OpenBrace,
}exp!(OpenBrace)) {
2821            self.parse_simple_block()?
2822        } else {
2823            let snapshot = self.create_snapshot_for_diagnostic();
2824            let first_tok = super::token_descr(&self.token);
2825            let first_tok_span = self.token.span;
2826            match self.parse_expr() {
2827                Ok(cond)
2828                // Try to guess the difference between a "condition-like" vs
2829                // "statement-like" expression.
2830                //
2831                // We are seeing the following code, in which $cond is neither
2832                // ExprKind::Block nor ExprKind::If (the 2 cases wherein this
2833                // would be valid syntax).
2834                //
2835                //     if ... {
2836                //     } else $cond
2837                //
2838                // If $cond is "condition-like" such as ExprKind::Binary, we
2839                // want to suggest inserting `if`.
2840                //
2841                //     if ... {
2842                //     } else if a == b {
2843                //            ^^
2844                //     }
2845                //
2846                // We account for macro calls that were meant as conditions as well.
2847                //
2848                //     if ... {
2849                //     } else if macro! { foo bar } {
2850                //            ^^
2851                //     }
2852                //
2853                // If $cond is "statement-like" such as ExprKind::While then we
2854                // want to suggest wrapping in braces.
2855                //
2856                //     if ... {
2857                //     } else {
2858                //            ^
2859                //         while true {}
2860                //     }
2861                //     ^
2862                    if self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenBrace,
    token_type: crate::parser::token_type::TokenType::OpenBrace,
}exp!(OpenBrace))
2863                        && (classify::expr_requires_semi_to_be_stmt(&cond)
2864                            || #[allow(non_exhaustive_omitted_patterns)] match cond.kind {
    ExprKind::MacCall(..) => true,
    _ => false,
}matches!(cond.kind, ExprKind::MacCall(..)))
2865                    =>
2866                {
2867                    self.dcx().emit_err(errors::ExpectedElseBlock {
2868                        first_tok_span,
2869                        first_tok,
2870                        else_span,
2871                        condition_start: cond.span.shrink_to_lo(),
2872                    });
2873                    self.parse_if_after_cond(cond.span.shrink_to_lo(), cond)?
2874                }
2875                Err(e) => {
2876                    e.cancel();
2877                    self.restore_snapshot(snapshot);
2878                    self.parse_simple_block()?
2879                },
2880                Ok(_) => {
2881                    self.restore_snapshot(snapshot);
2882                    self.parse_simple_block()?
2883                },
2884            }
2885        };
2886        self.error_on_if_block_attrs(else_span, true, expr.span, attrs);
2887        Ok(expr)
2888    }
2889
2890    fn error_on_if_block_attrs(
2891        &self,
2892        ctx_span: Span,
2893        is_ctx_else: bool,
2894        branch_span: Span,
2895        attrs: AttrWrapper,
2896    ) {
2897        if !attrs.is_empty()
2898            && let [x0 @ xn] | [x0, .., xn] = &*attrs.take_for_recovery(self.psess)
2899        {
2900            let attributes = x0.span.until(branch_span);
2901            let last = xn.span;
2902            let ctx = if is_ctx_else { "else" } else { "if" };
2903            self.dcx().emit_err(errors::OuterAttributeNotAllowedOnIfElse {
2904                last,
2905                branch_span,
2906                ctx_span,
2907                ctx: ctx.to_string(),
2908                attributes,
2909            });
2910        }
2911    }
2912
2913    fn error_on_extra_if(&mut self, cond: &Box<Expr>) -> PResult<'a, ()> {
2914        if let ExprKind::Binary(Spanned { span: binop_span, node: binop }, _, right) = &cond.kind
2915            && let BinOpKind::And = binop
2916            && let ExprKind::If(cond, ..) = &right.kind
2917        {
2918            Err(self.dcx().create_err(errors::UnexpectedIfWithIf(
2919                binop_span.shrink_to_hi().to(cond.span.shrink_to_lo()),
2920            )))
2921        } else {
2922            Ok(())
2923        }
2924    }
2925
2926    // Public to use it for custom `for` expressions in rustfmt forks like https://github.com/tucant/rustfmt
2927    pub fn parse_for_head(&mut self) -> PResult<'a, (Pat, Box<Expr>)> {
2928        let begin_paren = if self.token == token::OpenParen {
2929            // Record whether we are about to parse `for (`.
2930            // This is used below for recovery in case of `for ( $stuff ) $block`
2931            // in which case we will suggest `for $stuff $block`.
2932            let start_span = self.token.span;
2933            let left = self.prev_token.span.between(self.look_ahead(1, |t| t.span));
2934            Some((start_span, left))
2935        } else {
2936            None
2937        };
2938        // Try to parse the pattern `for ($PAT) in $EXPR`.
2939        let pat = match (
2940            self.parse_pat_allow_top_guard(
2941                None,
2942                RecoverComma::Yes,
2943                RecoverColon::Yes,
2944                CommaRecoveryMode::LikelyTuple,
2945            ),
2946            begin_paren,
2947        ) {
2948            (Ok(pat), _) => pat, // Happy path.
2949            (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)) => {
2950                // We know for sure we have seen `for ($SOMETHING in`. In the happy path this would
2951                // happen right before the return of this method.
2952                let attrs = self.parse_outer_attributes()?;
2953                let (expr, _) = match self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, attrs) {
2954                    Ok(expr) => expr,
2955                    Err(expr_err) => {
2956                        // We don't know what followed the `in`, so cancel and bubble up the
2957                        // original error.
2958                        expr_err.cancel();
2959                        return Err(err);
2960                    }
2961                };
2962                return if self.token == token::CloseParen {
2963                    // We know for sure we have seen `for ($SOMETHING in $EXPR)`, so we recover the
2964                    // parser state and emit a targeted suggestion.
2965                    let span = <[_]>::into_vec(::alloc::boxed::box_new([start_span, self.token.span]))vec![start_span, self.token.span];
2966                    let right = self.prev_token.span.between(self.look_ahead(1, |t| t.span));
2967                    self.bump(); // )
2968                    err.cancel();
2969                    self.dcx().emit_err(errors::ParenthesesInForHead {
2970                        span,
2971                        // With e.g. `for (x) in y)` this would replace `(x) in y)`
2972                        // with `x) in y)` which is syntactically invalid.
2973                        // However, this is prevented before we get here.
2974                        sugg: errors::ParenthesesInForHeadSugg { left, right },
2975                    });
2976                    Ok((self.mk_pat(start_span.to(right), ast::PatKind::Wild), expr))
2977                } else {
2978                    Err(err) // Some other error, bubble up.
2979                };
2980            }
2981            (Err(err), _) => return Err(err), // Some other error, bubble up.
2982        };
2983        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)) {
2984            self.error_missing_in_for_loop();
2985        }
2986        self.check_for_for_in_in_typo(self.prev_token.span);
2987        let attrs = self.parse_outer_attributes()?;
2988        let (expr, _) = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, attrs)?;
2989        Ok((pat, expr))
2990    }
2991
2992    /// Parses `for await? <src_pat> in <src_expr> <src_loop_block>` (`for` token already eaten).
2993    fn parse_expr_for(&mut self, opt_label: Option<Label>, lo: Span) -> PResult<'a, Box<Expr>> {
2994        let is_await =
2995            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));
2996
2997        if is_await {
2998            self.psess.gated_spans.gate(sym::async_for_loop, self.prev_token.span);
2999        }
3000
3001        let kind = if is_await { ForLoopKind::ForAwait } else { ForLoopKind::For };
3002
3003        let (pat, expr) = self.parse_for_head()?;
3004        let pat = Box::new(pat);
3005        // Recover from missing expression in `for` loop
3006        if #[allow(non_exhaustive_omitted_patterns)] match expr.kind {
    ExprKind::Block(..) => true,
    _ => false,
}matches!(expr.kind, ExprKind::Block(..))
3007            && self.token.kind != token::OpenBrace
3008            && self.may_recover()
3009        {
3010            let guar = self
3011                .dcx()
3012                .emit_err(errors::MissingExpressionInForLoop { span: expr.span.shrink_to_lo() });
3013            let err_expr = self.mk_expr(expr.span, ExprKind::Err(guar));
3014            let block = self.mk_block(::thin_vec::ThinVec::new()thin_vec![], BlockCheckMode::Default, self.prev_token.span);
3015            return Ok(self.mk_expr(
3016                lo.to(self.prev_token.span),
3017                ExprKind::ForLoop { pat, iter: err_expr, body: block, label: opt_label, kind },
3018            ));
3019        }
3020
3021        let (attrs, loop_block) = self.parse_inner_attrs_and_block(
3022            // Only suggest moving erroneous block label to the loop header
3023            // if there is not already a label there
3024            opt_label.is_none().then_some(lo),
3025        )?;
3026
3027        let kind = ExprKind::ForLoop { pat, iter: expr, body: loop_block, label: opt_label, kind };
3028
3029        self.recover_loop_else("for", lo)?;
3030
3031        Ok(self.mk_expr_with_attrs(lo.to(self.prev_token.span), kind, attrs))
3032    }
3033
3034    /// Recovers from an `else` clause after a loop (`for...else`, `while...else`)
3035    fn recover_loop_else(&mut self, loop_kind: &'static str, loop_kw: Span) -> PResult<'a, ()> {
3036        if self.token.is_keyword(kw::Else) && self.may_recover() {
3037            let else_span = self.token.span;
3038            self.bump();
3039            let else_clause = self.parse_expr_else()?;
3040            self.dcx().emit_err(errors::LoopElseNotSupported {
3041                span: else_span.to(else_clause.span),
3042                loop_kind,
3043                loop_kw,
3044            });
3045        }
3046        Ok(())
3047    }
3048
3049    fn error_missing_in_for_loop(&mut self) {
3050        let (span, sub): (_, fn(_) -> _) = if self.token.is_ident_named(sym::of) {
3051            // Possibly using JS syntax (#75311).
3052            let span = self.token.span;
3053            self.bump();
3054            (span, errors::MissingInInForLoopSub::InNotOf)
3055        } else if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Eq,
    token_type: crate::parser::token_type::TokenType::Eq,
}exp!(Eq)) {
3056            (self.prev_token.span, errors::MissingInInForLoopSub::InNotEq)
3057        } else {
3058            (self.prev_token.span.between(self.token.span), errors::MissingInInForLoopSub::AddIn)
3059        };
3060
3061        self.dcx().emit_err(errors::MissingInInForLoop { span, sub: sub(span) });
3062    }
3063
3064    /// Parses a `while` or `while let` expression (`while` token already eaten).
3065    fn parse_expr_while(&mut self, opt_label: Option<Label>, lo: Span) -> PResult<'a, Box<Expr>> {
3066        let policy = LetChainsPolicy::EditionDependent { current_edition: lo.edition() };
3067        let cond = self.parse_expr_cond(policy).map_err(|mut err| {
3068            err.span_label(lo, "while parsing the condition of this `while` expression");
3069            err
3070        })?;
3071        let (attrs, body) = self
3072            .parse_inner_attrs_and_block(
3073                // Only suggest moving erroneous block label to the loop header
3074                // if there is not already a label there
3075                opt_label.is_none().then_some(lo),
3076            )
3077            .map_err(|mut err| {
3078                err.span_label(lo, "while parsing the body of this `while` expression");
3079                err.span_label(cond.span, "this `while` condition successfully parsed");
3080                err
3081            })?;
3082
3083        self.recover_loop_else("while", lo)?;
3084
3085        Ok(self.mk_expr_with_attrs(
3086            lo.to(self.prev_token.span),
3087            ExprKind::While(cond, body, opt_label),
3088            attrs,
3089        ))
3090    }
3091
3092    /// Parses `loop { ... }` (`loop` token already eaten).
3093    fn parse_expr_loop(&mut self, opt_label: Option<Label>, lo: Span) -> PResult<'a, Box<Expr>> {
3094        let loop_span = self.prev_token.span;
3095        let (attrs, body) = self.parse_inner_attrs_and_block(
3096            // Only suggest moving erroneous block label to the loop header
3097            // if there is not already a label there
3098            opt_label.is_none().then_some(lo),
3099        )?;
3100        self.recover_loop_else("loop", lo)?;
3101        Ok(self.mk_expr_with_attrs(
3102            lo.to(self.prev_token.span),
3103            ExprKind::Loop(body, opt_label, loop_span),
3104            attrs,
3105        ))
3106    }
3107
3108    pub(crate) fn eat_label(&mut self) -> Option<Label> {
3109        if let Some((ident, is_raw)) = self.token.lifetime() {
3110            // Disallow `'fn`, but with a better error message than `expect_lifetime`.
3111            if is_raw == IdentIsRaw::No && ident.without_first_quote().is_reserved() {
3112                self.dcx().emit_err(errors::KeywordLabel { span: ident.span });
3113            }
3114
3115            self.bump();
3116            Some(Label { ident })
3117        } else {
3118            None
3119        }
3120    }
3121
3122    /// Parses a `match ... { ... }` expression (`match` token already eaten).
3123    fn parse_expr_match(&mut self) -> PResult<'a, Box<Expr>> {
3124        let match_span = self.prev_token.span;
3125        let attrs = self.parse_outer_attributes()?;
3126        let (scrutinee, _) = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, attrs)?;
3127
3128        self.parse_match_block(match_span, match_span, scrutinee, MatchKind::Prefix)
3129    }
3130
3131    /// Parses the block of a `match expr { ... }` or a `expr.match { ... }`
3132    /// expression. This is after the match token and scrutinee are eaten
3133    fn parse_match_block(
3134        &mut self,
3135        lo: Span,
3136        match_span: Span,
3137        scrutinee: Box<Expr>,
3138        match_kind: MatchKind,
3139    ) -> PResult<'a, Box<Expr>> {
3140        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)) {
3141            if self.token == token::Semi {
3142                e.span_suggestion_short(
3143                    match_span,
3144                    "try removing this `match`",
3145                    "",
3146                    Applicability::MaybeIncorrect, // speculative
3147                );
3148            }
3149            if self.maybe_recover_unexpected_block_label(None) {
3150                e.cancel();
3151                self.bump();
3152            } else {
3153                return Err(e);
3154            }
3155        }
3156        let attrs = self.parse_inner_attributes()?;
3157
3158        let mut arms = ThinVec::new();
3159        while self.token != token::CloseBrace {
3160            match self.parse_arm() {
3161                Ok(arm) => arms.push(arm),
3162                Err(e) => {
3163                    // Recover by skipping to the end of the block.
3164                    let guar = e.emit();
3165                    self.recover_stmt();
3166                    let span = lo.to(self.token.span);
3167                    if self.token == token::CloseBrace {
3168                        self.bump();
3169                    }
3170                    // Always push at least one arm to make the match non-empty
3171                    arms.push(Arm {
3172                        attrs: Default::default(),
3173                        pat: Box::new(self.mk_pat(span, ast::PatKind::Err(guar))),
3174                        guard: None,
3175                        body: Some(self.mk_expr_err(span, guar)),
3176                        span,
3177                        id: DUMMY_NODE_ID,
3178                        is_placeholder: false,
3179                    });
3180                    return Ok(self.mk_expr_with_attrs(
3181                        span,
3182                        ExprKind::Match(scrutinee, arms, match_kind),
3183                        attrs,
3184                    ));
3185                }
3186            }
3187        }
3188        let hi = self.token.span;
3189        self.bump();
3190        Ok(self.mk_expr_with_attrs(lo.to(hi), ExprKind::Match(scrutinee, arms, match_kind), attrs))
3191    }
3192
3193    /// Attempt to recover from match arm body with statements and no surrounding braces.
3194    fn parse_arm_body_missing_braces(
3195        &mut self,
3196        first_expr: &Box<Expr>,
3197        arrow_span: Span,
3198    ) -> Option<(Span, ErrorGuaranteed)> {
3199        if self.token != token::Semi {
3200            return None;
3201        }
3202        let start_snapshot = self.create_snapshot_for_diagnostic();
3203        let semi_sp = self.token.span;
3204        self.bump(); // `;`
3205        let mut stmts =
3206            <[_]>::into_vec(::alloc::boxed::box_new([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()))];
3207        let err = |this: &Parser<'_>, stmts: Vec<ast::Stmt>| {
3208            let span = stmts[0].span.to(stmts[stmts.len() - 1].span);
3209
3210            let guar = this.dcx().emit_err(errors::MatchArmBodyWithoutBraces {
3211                statements: span,
3212                arrow: arrow_span,
3213                num_statements: stmts.len(),
3214                sub: if stmts.len() > 1 {
3215                    errors::MatchArmBodyWithoutBracesSugg::AddBraces {
3216                        left: span.shrink_to_lo(),
3217                        right: span.shrink_to_hi(),
3218                    }
3219                } else {
3220                    errors::MatchArmBodyWithoutBracesSugg::UseComma { semicolon: semi_sp }
3221                },
3222            });
3223            (span, guar)
3224        };
3225        // We might have either a `,` -> `;` typo, or a block without braces. We need
3226        // a more subtle parsing strategy.
3227        loop {
3228            if self.token == token::CloseBrace {
3229                // We have reached the closing brace of the `match` expression.
3230                return Some(err(self, stmts));
3231            }
3232            if self.token == token::Comma {
3233                self.restore_snapshot(start_snapshot);
3234                return None;
3235            }
3236            let pre_pat_snapshot = self.create_snapshot_for_diagnostic();
3237            match self.parse_pat_no_top_alt(None, None) {
3238                Ok(_pat) => {
3239                    if self.token == token::FatArrow {
3240                        // Reached arm end.
3241                        self.restore_snapshot(pre_pat_snapshot);
3242                        return Some(err(self, stmts));
3243                    }
3244                }
3245                Err(err) => {
3246                    err.cancel();
3247                }
3248            }
3249
3250            self.restore_snapshot(pre_pat_snapshot);
3251            match self.parse_stmt_without_recovery(true, ForceCollect::No, false) {
3252                // Consume statements for as long as possible.
3253                Ok(Some(stmt)) => {
3254                    stmts.push(stmt);
3255                }
3256                Ok(None) => {
3257                    self.restore_snapshot(start_snapshot);
3258                    break;
3259                }
3260                // We couldn't parse either yet another statement missing it's
3261                // enclosing block nor the next arm's pattern or closing brace.
3262                Err(stmt_err) => {
3263                    stmt_err.cancel();
3264                    self.restore_snapshot(start_snapshot);
3265                    break;
3266                }
3267            }
3268        }
3269        None
3270    }
3271
3272    pub(super) fn parse_arm(&mut self) -> PResult<'a, Arm> {
3273        let attrs = self.parse_outer_attributes()?;
3274        self.collect_tokens(None, attrs, ForceCollect::No, |this, attrs| {
3275            let lo = this.token.span;
3276            let (pat, guard) = this.parse_match_arm_pat_and_guard()?;
3277            let pat = Box::new(pat);
3278
3279            let span_before_body = this.prev_token.span;
3280            let arm_body;
3281            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));
3282            let is_almost_fat_arrow =
3283                TokenKind::FatArrow.similar_tokens().contains(&this.token.kind);
3284
3285            // this avoids the compiler saying that a `,` or `}` was expected even though
3286            // the pattern isn't a never pattern (and thus an arm body is required)
3287            let armless = (!is_fat_arrow && !is_almost_fat_arrow && pat.could_be_never_pattern())
3288                || #[allow(non_exhaustive_omitted_patterns)] match this.token.kind {
    token::Comma | token::CloseBrace => true,
    _ => false,
}matches!(this.token.kind, token::Comma | token::CloseBrace);
3289
3290            let mut result = if armless {
3291                // A pattern without a body, allowed for never patterns.
3292                arm_body = None;
3293                let span = lo.to(this.prev_token.span);
3294                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| {
3295                    // Don't gate twice
3296                    if !pat.contains_never_pattern() {
3297                        this.psess.gated_spans.gate(sym::never_patterns, span);
3298                    }
3299                    x
3300                })
3301            } else {
3302                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)) {
3303                    // We might have a `=>` -> `=` or `->` typo (issue #89396).
3304                    if is_almost_fat_arrow {
3305                        err.span_suggestion(
3306                            this.token.span,
3307                            "use a fat arrow to start a match arm",
3308                            "=>",
3309                            Applicability::MachineApplicable,
3310                        );
3311                        if #[allow(non_exhaustive_omitted_patterns)] match (&this.prev_token.kind,
        &this.token.kind) {
    (token::DotDotEq, token::Gt) => true,
    _ => false,
}matches!(
3312                            (&this.prev_token.kind, &this.token.kind),
3313                            (token::DotDotEq, token::Gt)
3314                        ) {
3315                            // `error_inclusive_range_match_arrow` handles cases like `0..=> {}`,
3316                            // so we suppress the error here
3317                            err.delay_as_bug();
3318                        } else {
3319                            err.emit();
3320                        }
3321                        this.bump();
3322                    } else {
3323                        return Err(err);
3324                    }
3325                }
3326                let arrow_span = this.prev_token.span;
3327                let arm_start_span = this.token.span;
3328
3329                let attrs = this.parse_outer_attributes()?;
3330                let (expr, _) =
3331                    this.parse_expr_res(Restrictions::STMT_EXPR, attrs).map_err(|mut err| {
3332                        err.span_label(arrow_span, "while parsing the `match` arm starting here");
3333                        err
3334                    })?;
3335
3336                let require_comma =
3337                    !classify::expr_is_complete(&expr) && this.token != token::CloseBrace;
3338
3339                if !require_comma {
3340                    arm_body = Some(expr);
3341                    // Eat a comma if it exists, though.
3342                    let _ = this.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma));
3343                    Ok(Recovered::No)
3344                } else if let Some((span, guar)) =
3345                    this.parse_arm_body_missing_braces(&expr, arrow_span)
3346                {
3347                    let body = this.mk_expr_err(span, guar);
3348                    arm_body = Some(body);
3349                    Ok(Recovered::Yes(guar))
3350                } else {
3351                    let expr_span = expr.span;
3352                    arm_body = Some(expr);
3353                    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| {
3354                        if this.token == token::FatArrow {
3355                            let sm = this.psess.source_map();
3356                            if let Ok(expr_lines) = sm.span_to_lines(expr_span)
3357                                && let Ok(arm_start_lines) = sm.span_to_lines(arm_start_span)
3358                                && expr_lines.lines.len() == 2
3359                            {
3360                                if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col {
3361                                    // We check whether there's any trailing code in the parse span,
3362                                    // if there isn't, we very likely have the following:
3363                                    //
3364                                    // X |     &Y => "y"
3365                                    //   |        --    - missing comma
3366                                    //   |        |
3367                                    //   |        arrow_span
3368                                    // X |     &X => "x"
3369                                    //   |      - ^^ self.token.span
3370                                    //   |      |
3371                                    //   |      parsed until here as `"y" & X`
3372                                    err.span_suggestion_short(
3373                                        arm_start_span.shrink_to_hi(),
3374                                        "missing a comma here to end this `match` arm",
3375                                        ",",
3376                                        Applicability::MachineApplicable,
3377                                    );
3378                                } else if arm_start_lines.lines[0].end_col + rustc_span::CharPos(1)
3379                                    == expr_lines.lines[0].end_col
3380                                {
3381                                    // similar to the above, but we may typo a `.` or `/` at the end of the line
3382                                    let comma_span = arm_start_span
3383                                        .shrink_to_hi()
3384                                        .with_hi(arm_start_span.hi() + rustc_span::BytePos(1));
3385                                    if let Ok(res) = sm.span_to_snippet(comma_span)
3386                                        && (res == "." || res == "/")
3387                                    {
3388                                        err.span_suggestion_short(
3389                                            comma_span,
3390                                            "you might have meant to write a `,` to end this `match` arm",
3391                                            ",",
3392                                            Applicability::MachineApplicable,
3393                                        );
3394                                    }
3395                                }
3396                            }
3397                        } else {
3398                            err.span_label(
3399                                arrow_span,
3400                                "while parsing the `match` arm starting here",
3401                            );
3402                        }
3403                        err
3404                    })
3405                }
3406            };
3407
3408            let hi_span = arm_body.as_ref().map_or(span_before_body, |body| body.span);
3409            let arm_span = lo.to(hi_span);
3410
3411            // We want to recover:
3412            // X |     Some(_) => foo()
3413            //   |                     - missing comma
3414            // X |     None => "x"
3415            //   |     ^^^^ self.token.span
3416            // as well as:
3417            // X |     Some(!)
3418            //   |            - missing comma
3419            // X |     None => "x"
3420            //   |     ^^^^ self.token.span
3421            // But we musn't recover
3422            // X |     pat[0] => {}
3423            //   |        ^ self.token.span
3424            let recover_missing_comma = arm_body.is_some() || pat.could_be_never_pattern();
3425            if recover_missing_comma {
3426                result = result.or_else(|err| {
3427                    // FIXME(compiler-errors): We could also recover `; PAT =>` here
3428
3429                    // Try to parse a following `PAT =>`, if successful
3430                    // then we should recover.
3431                    let mut snapshot = this.create_snapshot_for_diagnostic();
3432                    let pattern_follows = snapshot
3433                        .parse_pat_no_top_guard(
3434                            None,
3435                            RecoverComma::Yes,
3436                            RecoverColon::Yes,
3437                            CommaRecoveryMode::EitherTupleOrPipe,
3438                        )
3439                        .map_err(|err| err.cancel())
3440                        .is_ok();
3441                    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)) {
3442                        err.cancel();
3443                        let guar = this.dcx().emit_err(errors::MissingCommaAfterMatchArm {
3444                            span: arm_span.shrink_to_hi(),
3445                        });
3446                        return Ok(Recovered::Yes(guar));
3447                    }
3448                    Err(err)
3449                });
3450            }
3451            result?;
3452
3453            Ok((
3454                ast::Arm {
3455                    attrs,
3456                    pat,
3457                    guard,
3458                    body: arm_body,
3459                    span: arm_span,
3460                    id: DUMMY_NODE_ID,
3461                    is_placeholder: false,
3462                },
3463                Trailing::No,
3464                UsePreAttrPos::No,
3465            ))
3466        })
3467    }
3468
3469    fn parse_match_arm_guard(&mut self) -> PResult<'a, Option<Box<Expr>>> {
3470        // Used to check the `if_let_guard` feature mostly by scanning
3471        // `&&` tokens.
3472        fn has_let_expr(expr: &Expr) -> bool {
3473            match &expr.kind {
3474                ExprKind::Binary(BinOp { node: BinOpKind::And, .. }, lhs, rhs) => {
3475                    let lhs_rslt = has_let_expr(lhs);
3476                    let rhs_rslt = has_let_expr(rhs);
3477                    lhs_rslt || rhs_rslt
3478                }
3479                ExprKind::Let(..) => true,
3480                _ => false,
3481            }
3482        }
3483        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)) {
3484            // No match arm guard present.
3485            return Ok(None);
3486        }
3487
3488        let if_span = self.prev_token.span;
3489        let mut cond = self.parse_match_guard_condition()?;
3490
3491        let mut checker = CondChecker::new(self, LetChainsPolicy::AlwaysAllowed);
3492        checker.visit_expr(&mut cond);
3493
3494        if has_let_expr(&cond) {
3495            let span = if_span.to(cond.span);
3496            self.psess.gated_spans.gate(sym::if_let_guard, span);
3497        }
3498
3499        Ok(Some(if let Some(guar) = checker.found_incorrect_let_chain {
3500            self.mk_expr_err(cond.span, guar)
3501        } else {
3502            cond
3503        }))
3504    }
3505
3506    fn parse_match_arm_pat_and_guard(&mut self) -> PResult<'a, (Pat, Option<Box<Expr>>)> {
3507        if self.token == token::OpenParen {
3508            let left = self.token.span;
3509            let pat = self.parse_pat_no_top_guard(
3510                None,
3511                RecoverComma::Yes,
3512                RecoverColon::Yes,
3513                CommaRecoveryMode::EitherTupleOrPipe,
3514            )?;
3515            if let ast::PatKind::Paren(subpat) = &pat.kind
3516                && let ast::PatKind::Guard(..) = &subpat.kind
3517            {
3518                // Detect and recover from `($pat if $cond) => $arm`.
3519                // FIXME(guard_patterns): convert this to a normal guard instead
3520                let span = pat.span;
3521                let ast::PatKind::Paren(subpat) = pat.kind else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
3522                let ast::PatKind::Guard(_, mut cond) = subpat.kind else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
3523                self.psess.gated_spans.ungate_last(sym::guard_patterns, cond.span);
3524                let mut checker = CondChecker::new(self, LetChainsPolicy::AlwaysAllowed);
3525                checker.visit_expr(&mut cond);
3526
3527                let right = self.prev_token.span;
3528                self.dcx().emit_err(errors::ParenthesesInMatchPat {
3529                    span: <[_]>::into_vec(::alloc::boxed::box_new([left, right]))vec![left, right],
3530                    sugg: errors::ParenthesesInMatchPatSugg { left, right },
3531                });
3532
3533                Ok((
3534                    self.mk_pat(span, ast::PatKind::Wild),
3535                    (if let Some(guar) = checker.found_incorrect_let_chain {
3536                        Some(self.mk_expr_err(cond.span, guar))
3537                    } else {
3538                        Some(cond)
3539                    }),
3540                ))
3541            } else {
3542                Ok((pat, self.parse_match_arm_guard()?))
3543            }
3544        } else {
3545            // Regular parser flow:
3546            let pat = self.parse_pat_no_top_guard(
3547                None,
3548                RecoverComma::Yes,
3549                RecoverColon::Yes,
3550                CommaRecoveryMode::EitherTupleOrPipe,
3551            )?;
3552            Ok((pat, self.parse_match_arm_guard()?))
3553        }
3554    }
3555
3556    fn parse_match_guard_condition(&mut self) -> PResult<'a, Box<Expr>> {
3557        let attrs = self.parse_outer_attributes()?;
3558        match self.parse_expr_res(Restrictions::ALLOW_LET | Restrictions::IN_IF_GUARD, attrs) {
3559            Ok((expr, _)) => Ok(expr),
3560            Err(mut err) => {
3561                if self.prev_token == token::OpenBrace {
3562                    let sugg_sp = self.prev_token.span.shrink_to_lo();
3563                    // Consume everything within the braces, let's avoid further parse
3564                    // errors.
3565                    self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
3566                    let msg = "you might have meant to start a match arm after the match guard";
3567                    if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseBrace,
    token_type: crate::parser::token_type::TokenType::CloseBrace,
}exp!(CloseBrace)) {
3568                        let applicability = if self.token != token::FatArrow {
3569                            // We have high confidence that we indeed didn't have a struct
3570                            // literal in the match guard, but rather we had some operation
3571                            // that ended in a path, immediately followed by a block that was
3572                            // meant to be the match arm.
3573                            Applicability::MachineApplicable
3574                        } else {
3575                            Applicability::MaybeIncorrect
3576                        };
3577                        err.span_suggestion_verbose(sugg_sp, msg, "=> ", applicability);
3578                    }
3579                }
3580                Err(err)
3581            }
3582        }
3583    }
3584
3585    pub(crate) fn is_builtin(&self) -> bool {
3586        self.token.is_keyword(kw::Builtin) && self.look_ahead(1, |t| *t == token::Pound)
3587    }
3588
3589    /// Parses a `try {...}` or `try bikeshed Ty {...}` expression (`try` token already eaten).
3590    fn parse_try_block(&mut self, span_lo: Span) -> PResult<'a, Box<Expr>> {
3591        let annotation =
3592            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 };
3593
3594        let (attrs, body) = self.parse_inner_attrs_and_block(None)?;
3595        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)) {
3596            Err(self.dcx().create_err(errors::CatchAfterTry { span: self.prev_token.span }))
3597        } else {
3598            let span = span_lo.to(body.span);
3599            let gate_sym =
3600                if annotation.is_none() { sym::try_blocks } else { sym::try_blocks_heterogeneous };
3601            self.psess.gated_spans.gate(gate_sym, span);
3602            Ok(self.mk_expr_with_attrs(span, ExprKind::TryBlock(body, annotation), attrs))
3603        }
3604    }
3605
3606    fn is_do_catch_block(&self) -> bool {
3607        self.token.is_keyword(kw::Do)
3608            && self.is_keyword_ahead(1, &[kw::Catch])
3609            && self.look_ahead(2, |t| *t == token::OpenBrace || t.is_metavar_block())
3610            && !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
3611    }
3612
3613    fn is_do_yeet(&self) -> bool {
3614        self.token.is_keyword(kw::Do) && self.is_keyword_ahead(1, &[kw::Yeet])
3615    }
3616
3617    fn is_try_block(&self) -> bool {
3618        self.token.is_keyword(kw::Try)
3619            && self.look_ahead(1, |t| {
3620                *t == token::OpenBrace
3621                    || t.is_metavar_block()
3622                    || t.kind == TokenKind::Ident(sym::bikeshed, IdentIsRaw::No)
3623            })
3624            && self.token_uninterpolated_span().at_least_rust_2018()
3625    }
3626
3627    /// Parses an `async move? {...}` or `gen move? {...}` expression.
3628    fn parse_gen_block(&mut self) -> PResult<'a, Box<Expr>> {
3629        let lo = self.token.span;
3630        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)) {
3631            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 }
3632        } else {
3633            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)));
3634            GenBlockKind::Gen
3635        };
3636        match kind {
3637            GenBlockKind::Async => {
3638                // `async` blocks are stable
3639            }
3640            GenBlockKind::Gen | GenBlockKind::AsyncGen => {
3641                self.psess.gated_spans.gate(sym::gen_blocks, lo.to(self.prev_token.span));
3642            }
3643        }
3644        let capture_clause = self.parse_capture_clause()?;
3645        let decl_span = lo.to(self.prev_token.span);
3646        let (attrs, body) = self.parse_inner_attrs_and_block(None)?;
3647        let kind = ExprKind::Gen(capture_clause, body, kind, decl_span);
3648        Ok(self.mk_expr_with_attrs(lo.to(self.prev_token.span), kind, attrs))
3649    }
3650
3651    fn is_gen_block(&self, kw: Symbol, lookahead: usize) -> bool {
3652        self.is_keyword_ahead(lookahead, &[kw])
3653            && ((
3654                // `async move {`
3655                self.is_keyword_ahead(lookahead + 1, &[kw::Move, kw::Use])
3656                    && self.look_ahead(lookahead + 2, |t| {
3657                        *t == token::OpenBrace || t.is_metavar_block()
3658                    })
3659            ) || (
3660                // `async {`
3661                self.look_ahead(lookahead + 1, |t| *t == token::OpenBrace || t.is_metavar_block())
3662            ))
3663    }
3664
3665    pub(super) fn is_async_gen_block(&self) -> bool {
3666        self.token.is_keyword(kw::Async) && self.is_gen_block(kw::Gen, 1)
3667    }
3668
3669    fn is_likely_struct_lit(&self) -> bool {
3670        // `{ ident, ` and `{ ident: ` cannot start a block.
3671        self.look_ahead(1, |t| t.is_ident())
3672            && self.look_ahead(2, |t| t == &token::Comma || t == &token::Colon)
3673    }
3674
3675    fn maybe_parse_struct_expr(
3676        &mut self,
3677        qself: &Option<Box<ast::QSelf>>,
3678        path: &ast::Path,
3679    ) -> Option<PResult<'a, Box<Expr>>> {
3680        let struct_allowed = !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
3681        match (struct_allowed, self.is_likely_struct_lit()) {
3682            // A struct literal isn't expected and one is pretty much assured not to be present. The
3683            // only situation that isn't detected is when a struct with a single field was attempted
3684            // in a place where a struct literal wasn't expected, but regular parser errors apply.
3685            // Happy path.
3686            (false, false) => None,
3687            (true, _) => {
3688                // A struct is accepted here, try to parse it and rely on `parse_expr_struct` for
3689                // any kind of recovery. Happy path.
3690                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)) {
3691                    return Some(Err(err));
3692                }
3693                Some(self.parse_expr_struct(qself.clone(), path.clone(), true))
3694            }
3695            (false, true) => {
3696                // We have something like `match foo { bar,` or `match foo { bar:`, which means the
3697                // user might have meant to write a struct literal as part of the `match`
3698                // discriminant. This is done purely for error recovery.
3699                let snapshot = self.create_snapshot_for_diagnostic();
3700                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)) {
3701                    return Some(Err(err));
3702                }
3703                match self.parse_expr_struct(qself.clone(), path.clone(), false) {
3704                    Ok(expr) => {
3705                        // This is a struct literal, but we don't accept them here.
3706                        self.dcx().emit_err(errors::StructLiteralNotAllowedHere {
3707                            span: expr.span,
3708                            sub: errors::StructLiteralNotAllowedHereSugg {
3709                                left: path.span.shrink_to_lo(),
3710                                right: expr.span.shrink_to_hi(),
3711                            },
3712                        });
3713                        Some(Ok(expr))
3714                    }
3715                    Err(err) => {
3716                        // We couldn't parse a valid struct, rollback and let the parser emit an
3717                        // error elsewhere.
3718                        err.cancel();
3719                        self.restore_snapshot(snapshot);
3720                        None
3721                    }
3722                }
3723            }
3724        }
3725    }
3726
3727    fn maybe_recover_bad_struct_literal_path(
3728        &mut self,
3729        is_underscore_entry_point: bool,
3730    ) -> PResult<'a, Option<Box<Expr>>> {
3731        if self.may_recover()
3732            && self.check_noexpect(&token::OpenBrace)
3733            && (!self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
3734                && self.is_likely_struct_lit())
3735        {
3736            let span = if is_underscore_entry_point {
3737                self.prev_token.span
3738            } else {
3739                self.token.span.shrink_to_lo()
3740            };
3741
3742            self.bump(); // {
3743            let expr = self.parse_expr_struct(
3744                None,
3745                Path::from_ident(Ident::new(kw::Underscore, span)),
3746                false,
3747            )?;
3748
3749            let guar = if is_underscore_entry_point {
3750                self.dcx().create_err(errors::StructLiteralPlaceholderPath { span }).emit()
3751            } else {
3752                self.dcx()
3753                    .create_err(errors::StructLiteralWithoutPathLate {
3754                        span: expr.span,
3755                        suggestion_span: expr.span.shrink_to_lo(),
3756                    })
3757                    .emit()
3758            };
3759
3760            Ok(Some(self.mk_expr_err(expr.span, guar)))
3761        } else {
3762            Ok(None)
3763        }
3764    }
3765
3766    pub(super) fn parse_struct_fields(
3767        &mut self,
3768        pth: ast::Path,
3769        recover: bool,
3770        close: ExpTokenPair,
3771    ) -> PResult<
3772        'a,
3773        (
3774            ThinVec<ExprField>,
3775            ast::StructRest,
3776            Option<ErrorGuaranteed>, /* async blocks are forbidden in Rust 2015 */
3777        ),
3778    > {
3779        let mut fields = ThinVec::new();
3780        let mut base = ast::StructRest::None;
3781        let mut recovered_async = None;
3782        let in_if_guard = self.restrictions.contains(Restrictions::IN_IF_GUARD);
3783
3784        let async_block_err = |e: &mut Diag<'_>, span: Span| {
3785            errors::AsyncBlockIn2015 { span }.add_to_diag(e);
3786            errors::HelpUseLatestEdition::new().add_to_diag(e);
3787        };
3788
3789        while self.token != close.tok {
3790            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) {
3791                let exp_span = self.prev_token.span;
3792                // We permit `.. }` on the left-hand side of a destructuring assignment.
3793                if self.check(close) {
3794                    base = ast::StructRest::Rest(self.prev_token.span);
3795                    break;
3796                }
3797                match self.parse_expr() {
3798                    Ok(e) => base = ast::StructRest::Base(e),
3799                    Err(e) if recover => {
3800                        e.emit();
3801                        self.recover_stmt();
3802                    }
3803                    Err(e) => return Err(e),
3804                }
3805                self.recover_struct_comma_after_dotdot(exp_span);
3806                break;
3807            }
3808
3809            // Peek the field's ident before parsing its expr in order to emit better diagnostics.
3810            let peek = self
3811                .token
3812                .ident()
3813                .filter(|(ident, is_raw)| {
3814                    (!ident.is_reserved() || #[allow(non_exhaustive_omitted_patterns)] match is_raw {
    IdentIsRaw::Yes => true,
    _ => false,
}matches!(is_raw, IdentIsRaw::Yes))
3815                        && self.look_ahead(1, |tok| *tok == token::Colon)
3816                })
3817                .map(|(ident, _)| ident);
3818
3819            // We still want a field even if its expr didn't parse.
3820            let field_ident = |this: &Self, guar: ErrorGuaranteed| {
3821                peek.map(|ident| {
3822                    let span = ident.span;
3823                    ExprField {
3824                        ident,
3825                        span,
3826                        expr: this.mk_expr_err(span, guar),
3827                        is_shorthand: false,
3828                        attrs: AttrVec::new(),
3829                        id: DUMMY_NODE_ID,
3830                        is_placeholder: false,
3831                    }
3832                })
3833            };
3834
3835            let parsed_field = match self.parse_expr_field() {
3836                Ok(f) => Ok(f),
3837                Err(mut e) => {
3838                    if pth == kw::Async {
3839                        async_block_err(&mut e, pth.span);
3840                    } else {
3841                        e.span_label(pth.span, "while parsing this struct");
3842                    }
3843
3844                    if let Some((ident, _)) = self.token.ident()
3845                        && !self.token.is_reserved_ident()
3846                        && self.look_ahead(1, |t| {
3847                            AssocOp::from_token(t).is_some()
3848                                || #[allow(non_exhaustive_omitted_patterns)] match t.kind {
    token::OpenParen | token::OpenBracket | token::OpenBrace => true,
    _ => false,
}matches!(
3849                                    t.kind,
3850                                    token::OpenParen | token::OpenBracket | token::OpenBrace
3851                                )
3852                                || *t == token::Dot
3853                        })
3854                    {
3855                        // Looks like they tried to write a shorthand, complex expression,
3856                        // E.g.: `n + m`, `f(a)`, `a[i]`, `S { x: 3 }`, or `x.y`.
3857                        e.span_suggestion_verbose(
3858                            self.token.span.shrink_to_lo(),
3859                            "try naming a field",
3860                            &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: ", ident))
    })format!("{ident}: ",),
3861                            Applicability::MaybeIncorrect,
3862                        );
3863                    }
3864                    if in_if_guard && close.token_type == TokenType::CloseBrace {
3865                        return Err(e);
3866                    }
3867
3868                    if !recover {
3869                        return Err(e);
3870                    }
3871
3872                    let guar = e.emit();
3873                    if pth == kw::Async {
3874                        recovered_async = Some(guar);
3875                    }
3876
3877                    // If the next token is a comma, then try to parse
3878                    // what comes next as additional fields, rather than
3879                    // bailing out until next `}`.
3880                    if self.token != token::Comma {
3881                        self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
3882                        if self.token != token::Comma {
3883                            break;
3884                        }
3885                    }
3886
3887                    Err(guar)
3888                }
3889            };
3890
3891            let is_shorthand = parsed_field.as_ref().is_ok_and(|f| f.is_shorthand);
3892            // A shorthand field can be turned into a full field with `:`.
3893            // We should point this out.
3894            self.check_or_expected(!is_shorthand, TokenType::Colon);
3895
3896            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]) {
3897                Ok(_) => {
3898                    if let Ok(f) = parsed_field.or_else(|guar| field_ident(self, guar).ok_or(guar))
3899                    {
3900                        // Only include the field if there's no parse error for the field name.
3901                        fields.push(f);
3902                    }
3903                }
3904                Err(mut e) => {
3905                    if pth == kw::Async {
3906                        async_block_err(&mut e, pth.span);
3907                    } else {
3908                        e.span_label(pth.span, "while parsing this struct");
3909                        if peek.is_some() {
3910                            e.span_suggestion(
3911                                self.prev_token.span.shrink_to_hi(),
3912                                "try adding a comma",
3913                                ",",
3914                                Applicability::MachineApplicable,
3915                            );
3916                        }
3917                    }
3918                    if !recover {
3919                        return Err(e);
3920                    }
3921                    let guar = e.emit();
3922                    if pth == kw::Async {
3923                        recovered_async = Some(guar);
3924                    } else if let Some(f) = field_ident(self, guar) {
3925                        fields.push(f);
3926                    }
3927                    self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
3928                    let _ = self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma));
3929                }
3930            }
3931        }
3932        Ok((fields, base, recovered_async))
3933    }
3934
3935    /// Precondition: already parsed the '{'.
3936    pub(super) fn parse_expr_struct(
3937        &mut self,
3938        qself: Option<Box<ast::QSelf>>,
3939        pth: ast::Path,
3940        recover: bool,
3941    ) -> PResult<'a, Box<Expr>> {
3942        let lo = pth.span;
3943        let (fields, base, recovered_async) =
3944            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))?;
3945        let span = lo.to(self.token.span);
3946        self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseBrace,
    token_type: crate::parser::token_type::TokenType::CloseBrace,
}exp!(CloseBrace))?;
3947        let expr = if let Some(guar) = recovered_async {
3948            ExprKind::Err(guar)
3949        } else {
3950            ExprKind::Struct(Box::new(ast::StructExpr { qself, path: pth, fields, rest: base }))
3951        };
3952        Ok(self.mk_expr(span, expr))
3953    }
3954
3955    fn recover_struct_comma_after_dotdot(&mut self, span: Span) {
3956        if self.token != token::Comma {
3957            return;
3958        }
3959        self.dcx().emit_err(errors::CommaAfterBaseStruct {
3960            span: span.to(self.prev_token.span),
3961            comma: self.token.span,
3962        });
3963        self.recover_stmt();
3964    }
3965
3966    fn recover_struct_field_dots(&mut self, close: &TokenKind) -> bool {
3967        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)) {
3968            // recover from typo of `...`, suggest `..`
3969            let span = self.prev_token.span;
3970            self.dcx().emit_err(errors::MissingDotDot { token_span: span, sugg_span: span });
3971            return true;
3972        }
3973        false
3974    }
3975
3976    /// Converts an ident into 'label and emits an "expected a label, found an identifier" error.
3977    fn recover_ident_into_label(&mut self, ident: Ident) -> Label {
3978        // Convert `label` -> `'label`,
3979        // so that nameres doesn't complain about non-existing label
3980        let label = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\'{0}", ident.name))
    })format!("'{}", ident.name);
3981        let ident = Ident::new(Symbol::intern(&label), ident.span);
3982
3983        self.dcx().emit_err(errors::ExpectedLabelFoundIdent {
3984            span: ident.span,
3985            start: ident.span.shrink_to_lo(),
3986        });
3987
3988        Label { ident }
3989    }
3990
3991    /// Parses `ident (COLON expr)?`.
3992    fn parse_expr_field(&mut self) -> PResult<'a, ExprField> {
3993        let attrs = self.parse_outer_attributes()?;
3994        self.recover_vcs_conflict_marker();
3995        self.collect_tokens(None, attrs, ForceCollect::No, |this, attrs| {
3996            let lo = this.token.span;
3997
3998            // Check if a colon exists one ahead. This means we're parsing a fieldname.
3999            let is_shorthand = !this.look_ahead(1, |t| t == &token::Colon || t == &token::Eq);
4000            // Proactively check whether parsing the field will be incorrect.
4001            let is_wrong = this.token.is_non_reserved_ident()
4002                && !this.look_ahead(1, |t| {
4003                    t == &token::Colon
4004                        || t == &token::Eq
4005                        || t == &token::Comma
4006                        || t == &token::CloseBrace
4007                        || t == &token::CloseParen
4008                });
4009            if is_wrong {
4010                return Err(this.dcx().create_err(errors::ExpectedStructField {
4011                    span: this.look_ahead(1, |t| t.span),
4012                    ident_span: this.token.span,
4013                    token: this.look_ahead(1, |t| *t),
4014                }));
4015            }
4016            let (ident, expr) = if is_shorthand {
4017                // Mimic `x: x` for the `x` field shorthand.
4018                let ident = this.parse_ident_common(false)?;
4019                let path = ast::Path::from_ident(ident);
4020                (ident, this.mk_expr(ident.span, ExprKind::Path(None, path)))
4021            } else {
4022                let ident = this.parse_field_name()?;
4023                this.error_on_eq_field_init(ident);
4024                this.bump(); // `:`
4025                (ident, this.parse_expr()?)
4026            };
4027
4028            Ok((
4029                ast::ExprField {
4030                    ident,
4031                    span: lo.to(expr.span),
4032                    expr,
4033                    is_shorthand,
4034                    attrs,
4035                    id: DUMMY_NODE_ID,
4036                    is_placeholder: false,
4037                },
4038                Trailing::from(this.token == token::Comma),
4039                UsePreAttrPos::No,
4040            ))
4041        })
4042    }
4043
4044    /// Check for `=`. This means the source incorrectly attempts to
4045    /// initialize a field with an eq rather than a colon.
4046    fn error_on_eq_field_init(&self, field_name: Ident) {
4047        if self.token != token::Eq {
4048            return;
4049        }
4050
4051        self.dcx().emit_err(errors::EqFieldInit {
4052            span: self.token.span,
4053            eq: field_name.span.shrink_to_hi().to(self.token.span),
4054        });
4055    }
4056
4057    fn err_dotdotdot_syntax(&self, span: Span) {
4058        self.dcx().emit_err(errors::DotDotDot { span });
4059    }
4060
4061    fn err_larrow_operator(&self, span: Span) {
4062        self.dcx().emit_err(errors::LeftArrowOperator { span });
4063    }
4064
4065    fn mk_assign_op(&self, assign_op: AssignOp, lhs: Box<Expr>, rhs: Box<Expr>) -> ExprKind {
4066        ExprKind::AssignOp(assign_op, lhs, rhs)
4067    }
4068
4069    fn mk_range(
4070        &mut self,
4071        start: Option<Box<Expr>>,
4072        end: Option<Box<Expr>>,
4073        limits: RangeLimits,
4074    ) -> ExprKind {
4075        if end.is_none() && limits == RangeLimits::Closed {
4076            let guar = self.inclusive_range_with_incorrect_end();
4077            ExprKind::Err(guar)
4078        } else {
4079            ExprKind::Range(start, end, limits)
4080        }
4081    }
4082
4083    fn mk_unary(&self, unop: UnOp, expr: Box<Expr>) -> ExprKind {
4084        ExprKind::Unary(unop, expr)
4085    }
4086
4087    fn mk_binary(&self, binop: BinOp, lhs: Box<Expr>, rhs: Box<Expr>) -> ExprKind {
4088        ExprKind::Binary(binop, lhs, rhs)
4089    }
4090
4091    fn mk_index(&self, expr: Box<Expr>, idx: Box<Expr>, brackets_span: Span) -> ExprKind {
4092        ExprKind::Index(expr, idx, brackets_span)
4093    }
4094
4095    fn mk_call(&self, f: Box<Expr>, args: ThinVec<Box<Expr>>) -> ExprKind {
4096        ExprKind::Call(f, args)
4097    }
4098
4099    fn mk_await_expr(&mut self, self_arg: Box<Expr>, lo: Span) -> Box<Expr> {
4100        let span = lo.to(self.prev_token.span);
4101        let await_expr = self.mk_expr(span, ExprKind::Await(self_arg, self.prev_token.span));
4102        self.recover_from_await_method_call();
4103        await_expr
4104    }
4105
4106    fn mk_use_expr(&mut self, self_arg: Box<Expr>, lo: Span) -> Box<Expr> {
4107        let span = lo.to(self.prev_token.span);
4108        let use_expr = self.mk_expr(span, ExprKind::Use(self_arg, self.prev_token.span));
4109        self.recover_from_use();
4110        use_expr
4111    }
4112
4113    pub(crate) fn mk_expr_with_attrs(
4114        &self,
4115        span: Span,
4116        kind: ExprKind,
4117        attrs: AttrVec,
4118    ) -> Box<Expr> {
4119        Box::new(Expr { kind, span, attrs, id: DUMMY_NODE_ID, tokens: None })
4120    }
4121
4122    pub(crate) fn mk_expr(&self, span: Span, kind: ExprKind) -> Box<Expr> {
4123        self.mk_expr_with_attrs(span, kind, AttrVec::new())
4124    }
4125
4126    pub(super) fn mk_expr_err(&self, span: Span, guar: ErrorGuaranteed) -> Box<Expr> {
4127        self.mk_expr(span, ExprKind::Err(guar))
4128    }
4129
4130    pub(crate) fn mk_unit_expr(&self, span: Span) -> Box<Expr> {
4131        self.mk_expr(span, ExprKind::Tup(Default::default()))
4132    }
4133
4134    pub(crate) fn mk_closure_expr(&self, span: Span, body: Box<Expr>) -> Box<Expr> {
4135        self.mk_expr(
4136            span,
4137            ast::ExprKind::Closure(Box::new(ast::Closure {
4138                binder: rustc_ast::ClosureBinder::NotPresent,
4139                constness: rustc_ast::Const::No,
4140                movability: rustc_ast::Movability::Movable,
4141                capture_clause: rustc_ast::CaptureBy::Ref,
4142                coroutine_kind: None,
4143                fn_decl: Box::new(rustc_ast::FnDecl {
4144                    inputs: Default::default(),
4145                    output: rustc_ast::FnRetTy::Default(span),
4146                }),
4147                fn_arg_span: span,
4148                fn_decl_span: span,
4149                body,
4150            })),
4151        )
4152    }
4153
4154    /// Create expression span ensuring the span of the parent node
4155    /// is larger than the span of lhs and rhs, including the attributes.
4156    fn mk_expr_sp(&self, lhs: &Box<Expr>, lhs_span: Span, op_span: Span, rhs_span: Span) -> Span {
4157        lhs.attrs
4158            .iter()
4159            .find(|a| a.style == AttrStyle::Outer)
4160            .map_or(lhs_span, |a| a.span)
4161            .to(op_span)
4162            .to(rhs_span)
4163    }
4164
4165    fn collect_tokens_for_expr(
4166        &mut self,
4167        attrs: AttrWrapper,
4168        f: impl FnOnce(&mut Self, ast::AttrVec) -> PResult<'a, Box<Expr>>,
4169    ) -> PResult<'a, Box<Expr>> {
4170        self.collect_tokens(None, attrs, ForceCollect::No, |this, attrs| {
4171            let res = f(this, attrs)?;
4172            let trailing = Trailing::from(
4173                this.restrictions.contains(Restrictions::STMT_EXPR)
4174                     && this.token == token::Semi
4175                // FIXME: pass an additional condition through from the place
4176                // where we know we need a comma, rather than assuming that
4177                // `#[attr] expr,` always captures a trailing comma.
4178                || this.token == token::Comma,
4179            );
4180            Ok((res, trailing, UsePreAttrPos::No))
4181        })
4182    }
4183}
4184
4185/// Could this lifetime/label be an unclosed char literal? For example, `'a`
4186/// could be, but `'abc` could not.
4187pub(crate) fn could_be_unclosed_char_literal(ident: Ident) -> bool {
4188    ident.name.as_str().starts_with('\'')
4189        && unescape_char(ident.without_first_quote().name.as_str()).is_ok()
4190}
4191
4192/// Used to forbid `let` expressions in certain syntactic locations.
4193#[derive(#[automatically_derived]
impl ::core::clone::Clone for ForbiddenLetReason {
    #[inline]
    fn clone(&self) -> ForbiddenLetReason {
        let _: ::core::clone::AssertParamIsClone<Span>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for ForbiddenLetReason { }Copy, const _: () =
    {
        impl rustc_errors::Subdiagnostic for ForbiddenLetReason {
            fn add_to_diag<__G>(self, diag: &mut rustc_errors::Diag<'_, __G>)
                where __G: rustc_errors::EmissionGuarantee {
                match self {
                    ForbiddenLetReason::OtherForbidden => {}
                    ForbiddenLetReason::NotSupportedOr(__binding_0) => {
                        diag.store_args();
                        let __message =
                            diag.eagerly_translate(crate::fluent_generated::parse_not_supported_or);
                        diag.span_note(__binding_0, __message);
                        diag.restore_args();
                    }
                    ForbiddenLetReason::NotSupportedParentheses(__binding_0) =>
                        {
                        diag.store_args();
                        let __message =
                            diag.eagerly_translate(crate::fluent_generated::parse_not_supported_parentheses);
                        diag.span_note(__binding_0, __message);
                        diag.restore_args();
                    }
                }
            }
        }
    };Subdiagnostic)]
4194pub(crate) enum ForbiddenLetReason {
4195    /// `let` is not valid and the source environment is not important
4196    OtherForbidden,
4197    /// A let chain with the `||` operator
4198    #[note(parse_not_supported_or)]
4199    NotSupportedOr(#[primary_span] Span),
4200    /// A let chain with invalid parentheses
4201    ///
4202    /// For example, `let 1 = 1 && (expr && expr)` is allowed
4203    /// but `(let 1 = 1 && (let 1 = 1 && (let 1 = 1))) && let a = 1` is not
4204    #[note(parse_not_supported_parentheses)]
4205    NotSupportedParentheses(#[primary_span] Span),
4206}
4207
4208/// Whether let chains are allowed on all editions, or it's edition dependent (allowed only on
4209/// 2024 and later). In case of edition dependence, specify the currently present edition.
4210pub enum LetChainsPolicy {
4211    AlwaysAllowed,
4212    EditionDependent { current_edition: Edition },
4213}
4214
4215/// Visitor to check for invalid use of `ExprKind::Let` that can't
4216/// easily be caught in parsing. For example:
4217///
4218/// ```rust,ignore (example)
4219/// // Only know that the let isn't allowed once the `||` token is reached
4220/// if let Some(x) = y || true {}
4221/// // Only know that the let isn't allowed once the second `=` token is reached.
4222/// if let Some(x) = y && z = 1 {}
4223/// ```
4224struct CondChecker<'a> {
4225    parser: &'a Parser<'a>,
4226    let_chains_policy: LetChainsPolicy,
4227    depth: u32,
4228    forbid_let_reason: Option<ForbiddenLetReason>,
4229    missing_let: Option<errors::MaybeMissingLet>,
4230    comparison: Option<errors::MaybeComparison>,
4231    found_incorrect_let_chain: Option<ErrorGuaranteed>,
4232}
4233
4234impl<'a> CondChecker<'a> {
4235    fn new(parser: &'a Parser<'a>, let_chains_policy: LetChainsPolicy) -> Self {
4236        CondChecker {
4237            parser,
4238            forbid_let_reason: None,
4239            missing_let: None,
4240            comparison: None,
4241            let_chains_policy,
4242            found_incorrect_let_chain: None,
4243            depth: 0,
4244        }
4245    }
4246}
4247
4248impl MutVisitor for CondChecker<'_> {
4249    fn visit_expr(&mut self, e: &mut Expr) {
4250        self.depth += 1;
4251        use ForbiddenLetReason::*;
4252
4253        let span = e.span;
4254        match e.kind {
4255            ExprKind::Let(_, _, _, ref mut recovered @ Recovered::No) => {
4256                if let Some(reason) = self.forbid_let_reason {
4257                    let error = match reason {
4258                        NotSupportedOr(or_span) => {
4259                            self.parser.dcx().emit_err(errors::OrInLetChain { span: or_span })
4260                        }
4261                        _ => {
4262                            let guar =
4263                                self.parser.dcx().emit_err(errors::ExpectedExpressionFoundLet {
4264                                    span,
4265                                    reason,
4266                                    missing_let: self.missing_let,
4267                                    comparison: self.comparison,
4268                                });
4269                            if let Some(_) = self.missing_let {
4270                                self.found_incorrect_let_chain = Some(guar);
4271                            }
4272                            guar
4273                        }
4274                    };
4275                    *recovered = Recovered::Yes(error);
4276                } else if self.depth > 1 {
4277                    // Top level `let` is always allowed; only gate chains
4278                    match self.let_chains_policy {
4279                        LetChainsPolicy::AlwaysAllowed => (),
4280                        LetChainsPolicy::EditionDependent { current_edition } => {
4281                            if !current_edition.at_least_rust_2024() || !span.at_least_rust_2024() {
4282                                self.parser.dcx().emit_err(errors::LetChainPre2024 { span });
4283                            }
4284                        }
4285                    }
4286                }
4287            }
4288            ExprKind::Binary(Spanned { node: BinOpKind::And, .. }, _, _) => {
4289                mut_visit::walk_expr(self, e);
4290            }
4291            ExprKind::Binary(Spanned { node: BinOpKind::Or, span: or_span }, _, _)
4292                if let None | Some(NotSupportedOr(_)) = self.forbid_let_reason =>
4293            {
4294                let forbid_let_reason = self.forbid_let_reason;
4295                self.forbid_let_reason = Some(NotSupportedOr(or_span));
4296                mut_visit::walk_expr(self, e);
4297                self.forbid_let_reason = forbid_let_reason;
4298            }
4299            ExprKind::Paren(ref inner)
4300                if let None | Some(NotSupportedParentheses(_)) = self.forbid_let_reason =>
4301            {
4302                let forbid_let_reason = self.forbid_let_reason;
4303                self.forbid_let_reason = Some(NotSupportedParentheses(inner.span));
4304                mut_visit::walk_expr(self, e);
4305                self.forbid_let_reason = forbid_let_reason;
4306            }
4307            ExprKind::Assign(ref lhs, _, span) => {
4308                let forbid_let_reason = self.forbid_let_reason;
4309                self.forbid_let_reason = Some(OtherForbidden);
4310                let missing_let = self.missing_let;
4311                if let ExprKind::Binary(_, _, rhs) = &lhs.kind
4312                    && let ExprKind::Path(_, _)
4313                    | ExprKind::Struct(_)
4314                    | ExprKind::Call(_, _)
4315                    | ExprKind::Array(_) = rhs.kind
4316                {
4317                    self.missing_let =
4318                        Some(errors::MaybeMissingLet { span: rhs.span.shrink_to_lo() });
4319                }
4320                let comparison = self.comparison;
4321                self.comparison = Some(errors::MaybeComparison { span: span.shrink_to_hi() });
4322                mut_visit::walk_expr(self, e);
4323                self.forbid_let_reason = forbid_let_reason;
4324                self.missing_let = missing_let;
4325                self.comparison = comparison;
4326            }
4327            ExprKind::Unary(_, _)
4328            | ExprKind::Await(_, _)
4329            | ExprKind::Use(_, _)
4330            | ExprKind::AssignOp(_, _, _)
4331            | ExprKind::Range(_, _, _)
4332            | ExprKind::Try(_)
4333            | ExprKind::AddrOf(_, _, _)
4334            | ExprKind::Binary(_, _, _)
4335            | ExprKind::Field(_, _)
4336            | ExprKind::Index(_, _, _)
4337            | ExprKind::Call(_, _)
4338            | ExprKind::MethodCall(_)
4339            | ExprKind::Tup(_)
4340            | ExprKind::Paren(_) => {
4341                let forbid_let_reason = self.forbid_let_reason;
4342                self.forbid_let_reason = Some(OtherForbidden);
4343                mut_visit::walk_expr(self, e);
4344                self.forbid_let_reason = forbid_let_reason;
4345            }
4346            ExprKind::Cast(ref mut op, _)
4347            | ExprKind::Type(ref mut op, _)
4348            | ExprKind::UnsafeBinderCast(_, ref mut op, _) => {
4349                let forbid_let_reason = self.forbid_let_reason;
4350                self.forbid_let_reason = Some(OtherForbidden);
4351                self.visit_expr(op);
4352                self.forbid_let_reason = forbid_let_reason;
4353            }
4354            ExprKind::Let(_, _, _, Recovered::Yes(_))
4355            | ExprKind::Array(_)
4356            | ExprKind::ConstBlock(_)
4357            | ExprKind::Lit(_)
4358            | ExprKind::If(_, _, _)
4359            | ExprKind::While(_, _, _)
4360            | ExprKind::ForLoop { .. }
4361            | ExprKind::Loop(_, _, _)
4362            | ExprKind::Match(_, _, _)
4363            | ExprKind::Closure(_)
4364            | ExprKind::Block(_, _)
4365            | ExprKind::Gen(_, _, _, _)
4366            | ExprKind::TryBlock(_, _)
4367            | ExprKind::Underscore
4368            | ExprKind::Path(_, _)
4369            | ExprKind::Break(_, _)
4370            | ExprKind::Continue(_)
4371            | ExprKind::Ret(_)
4372            | ExprKind::InlineAsm(_)
4373            | ExprKind::OffsetOf(_, _)
4374            | ExprKind::MacCall(_)
4375            | ExprKind::Struct(_)
4376            | ExprKind::Repeat(_, _)
4377            | ExprKind::Yield(_)
4378            | ExprKind::Yeet(_)
4379            | ExprKind::Become(_)
4380            | ExprKind::IncludedBytes(_)
4381            | ExprKind::FormatArgs(_)
4382            | ExprKind::Err(_)
4383            | ExprKind::Dummy => {
4384                // These would forbid any let expressions they contain already.
4385            }
4386        }
4387        self.depth -= 1;
4388    }
4389}