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