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

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: PResult<'a, Box<Expr>> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            match (self.may_recover(), seq, snapshot) {
                (true, Err(err),
                    Some((mut snapshot, ExprKind::Path(None, path)))) => {
                    snapshot.bump();
                    match snapshot.parse_struct_fields(path.clone(), false,
                            crate::parser::token_type::ExpTokenPair {
                                tok: rustc_ast::token::CloseParen,
                                token_type: crate::parser::token_type::TokenType::CloseParen,
                            }) {
                        Ok((fields, ..)) if
                            snapshot.eat(crate::parser::token_type::ExpTokenPair {
                                    tok: rustc_ast::token::CloseParen,
                                    token_type: crate::parser::token_type::TokenType::CloseParen,
                                }) => {
                            self.restore_snapshot(snapshot);
                            let close_paren = self.prev_token.span;
                            let span = lo.to(close_paren);
                            let fields: Vec<_> =
                                fields.into_iter().filter(|field|
                                            !field.is_shorthand).collect();
                            let guar =
                                if !fields.is_empty() &&
                                        self.span_to_snippet(close_paren).is_ok_and(|snippet|
                                                snippet == ")") {
                                    err.cancel();
                                    self.dcx().create_err(errors::ParenthesesWithStructFields {
                                                span,
                                                braces_for_struct: errors::BracesForStructLiteral {
                                                    first: open_paren,
                                                    second: close_paren,
                                                    r#type: path.clone(),
                                                },
                                                no_fields_for_fn: errors::NoFieldsForFnCall {
                                                    r#type: path,
                                                    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")]
1278    fn maybe_recover_struct_lit_bad_delims(
1279        &mut self,
1280        lo: Span,
1281        open_paren: Span,
1282        seq: PResult<'a, Box<Expr>>,
1283        snapshot: Option<(SnapshotParser<'a>, ExprKind)>,
1284    ) -> PResult<'a, Box<Expr>> {
1285        match (self.may_recover(), seq, snapshot) {
1286            (true, Err(err), Some((mut snapshot, ExprKind::Path(None, path)))) => {
1287                snapshot.bump(); // `(`
1288                match snapshot.parse_struct_fields(path.clone(), false, exp!(CloseParen)) {
1289                    Ok((fields, ..)) if snapshot.eat(exp!(CloseParen)) => {
1290                        // We are certain we have `Enum::Foo(a: 3, b: 4)`, suggest
1291                        // `Enum::Foo { a: 3, b: 4 }` or `Enum::Foo(3, 4)`.
1292                        self.restore_snapshot(snapshot);
1293                        let close_paren = self.prev_token.span;
1294                        let span = lo.to(close_paren);
1295                        // filter shorthand fields
1296                        let fields: Vec<_> =
1297                            fields.into_iter().filter(|field| !field.is_shorthand).collect();
1298
1299                        let guar = if !fields.is_empty() &&
1300                            // `token.kind` should not be compared here.
1301                            // This is because the `snapshot.token.kind` is treated as the same as
1302                            // that of the open delim in `TokenTreesReader::parse_token_tree`, even
1303                            // if they are different.
1304                            self.span_to_snippet(close_paren).is_ok_and(|snippet| snippet == ")")
1305                        {
1306                            err.cancel();
1307                            self.dcx()
1308                                .create_err(errors::ParenthesesWithStructFields {
1309                                    span,
1310                                    braces_for_struct: errors::BracesForStructLiteral {
1311                                        first: open_paren,
1312                                        second: close_paren,
1313                                        r#type: path.clone(),
1314                                    },
1315                                    no_fields_for_fn: errors::NoFieldsForFnCall {
1316                                        r#type: path,
1317                                        fields: fields
1318                                            .into_iter()
1319                                            .map(|field| field.span.until(field.expr.span))
1320                                            .collect(),
1321                                    },
1322                                })
1323                                .emit()
1324                        } else {
1325                            err.emit()
1326                        };
1327                        Ok(self.mk_expr_err(span, guar))
1328                    }
1329                    Ok(_) => Err(err),
1330                    Err(err2) => {
1331                        err2.cancel();
1332                        Err(err)
1333                    }
1334                }
1335            }
1336            (_, seq, _) => seq,
1337        }
1338    }
1339
1340    /// Parse an indexing expression `expr[...]`.
1341    fn parse_expr_index(&mut self, lo: Span, base: Box<Expr>) -> PResult<'a, Box<Expr>> {
1342        let prev_span = self.prev_token.span;
1343        let open_delim_span = self.token.span;
1344        self.bump(); // `[`
1345        let index = self.parse_expr()?;
1346        self.suggest_missing_semicolon_before_array(prev_span, open_delim_span)?;
1347        self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseBracket,
    token_type: crate::parser::token_type::TokenType::CloseBracket,
}exp!(CloseBracket))?;
1348        Ok(self.mk_expr(
1349            lo.to(self.prev_token.span),
1350            self.mk_index(base, index, open_delim_span.to(self.prev_token.span)),
1351        ))
1352    }
1353
1354    /// Assuming we have just parsed `.`, continue parsing into an expression.
1355    fn parse_dot_suffix(&mut self, self_arg: Box<Expr>, lo: Span) -> PResult<'a, Box<Expr>> {
1356        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)) {
1357            return Ok(self.mk_await_expr(self_arg, lo));
1358        }
1359
1360        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)) {
1361            let use_span = self.prev_token.span;
1362            self.psess.gated_spans.gate(sym::ergonomic_clones, use_span);
1363            return Ok(self.mk_use_expr(self_arg, lo));
1364        }
1365
1366        // Post-fix match
1367        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)) {
1368            let match_span = self.prev_token.span;
1369            self.psess.gated_spans.gate(sym::postfix_match, match_span);
1370            return self.parse_match_block(lo, match_span, self_arg, MatchKind::Postfix);
1371        }
1372
1373        // Parse a postfix `yield`.
1374        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)) {
1375            let yield_span = self.prev_token.span;
1376            self.psess.gated_spans.gate(sym::yield_expr, yield_span);
1377            return Ok(
1378                self.mk_expr(lo.to(yield_span), ExprKind::Yield(YieldKind::Postfix(self_arg)))
1379            );
1380        }
1381
1382        let fn_span_lo = self.token.span;
1383        let mut seg = self.parse_path_segment(PathStyle::Expr, None)?;
1384        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)]);
1385        self.check_turbofish_missing_angle_brackets(&mut seg);
1386
1387        if self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenParen,
    token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen)) {
1388            // Method call `expr.f()`
1389            let args = self.parse_expr_paren_seq()?;
1390            let fn_span = fn_span_lo.to(self.prev_token.span);
1391            let span = lo.to(self.prev_token.span);
1392            Ok(self.mk_expr(
1393                span,
1394                ExprKind::MethodCall(Box::new(ast::MethodCall {
1395                    seg,
1396                    receiver: self_arg,
1397                    args,
1398                    span: fn_span,
1399                })),
1400            ))
1401        } else {
1402            // Field access `expr.f`
1403            let span = lo.to(self.prev_token.span);
1404            if let Some(args) = seg.args {
1405                // See `StashKey::GenericInFieldExpr` for more info on why we stash this.
1406                self.dcx()
1407                    .create_err(errors::FieldExpressionWithGeneric(args.span()))
1408                    .stash(seg.ident.span, StashKey::GenericInFieldExpr);
1409            }
1410
1411            Ok(self.mk_expr(span, ExprKind::Field(self_arg, seg.ident)))
1412        }
1413    }
1414
1415    /// At the bottom (top?) of the precedence hierarchy,
1416    /// Parses things like parenthesized exprs, macros, `return`, etc.
1417    ///
1418    /// N.B., this does not parse outer attributes, and is private because it only works
1419    /// correctly if called from `parse_expr_dot_or_call`.
1420    fn parse_expr_bottom(&mut self) -> PResult<'a, Box<Expr>> {
1421        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);
1422
1423        let span = self.token.span;
1424        if let Some(expr) = self.eat_metavar_seq_with_matcher(
1425            |mv_kind| #[allow(non_exhaustive_omitted_patterns)] match mv_kind {
    MetaVarKind::Expr { .. } => true,
    _ => false,
}matches!(mv_kind, MetaVarKind::Expr { .. }),
1426            |this| {
1427                // Force collection (as opposed to just `parse_expr`) is required to avoid the
1428                // attribute duplication seen in #138478.
1429                let expr = this.parse_expr_force_collect();
1430                // FIXME(nnethercote) Sometimes with expressions we get a trailing comma, possibly
1431                // related to the FIXME in `collect_tokens_for_expr`. Examples are the multi-line
1432                // `assert_eq!` calls involving arguments annotated with `#[rustfmt::skip]` in
1433                // `compiler/rustc_index/src/bit_set/tests.rs`.
1434                if this.token.kind == token::Comma {
1435                    this.bump();
1436                }
1437                expr
1438            },
1439        ) {
1440            return Ok(expr);
1441        } else if let Some(lit) =
1442            self.eat_metavar_seq(MetaVarKind::Literal, |this| this.parse_literal_maybe_minus())
1443        {
1444            return Ok(lit);
1445        } else if let Some(block) =
1446            self.eat_metavar_seq(MetaVarKind::Block, |this| this.parse_block())
1447        {
1448            return Ok(self.mk_expr(span, ExprKind::Block(block, None)));
1449        } else if let Some(path) =
1450            self.eat_metavar_seq(MetaVarKind::Path, |this| this.parse_path(PathStyle::Type))
1451        {
1452            return Ok(self.mk_expr(span, ExprKind::Path(None, path)));
1453        }
1454
1455        // Outer attributes are already parsed and will be
1456        // added to the return value after the fact.
1457
1458        let restrictions = self.restrictions;
1459        self.with_res(restrictions - Restrictions::ALLOW_LET, |this| {
1460            // Note: adding new syntax here? Don't forget to adjust `TokenKind::can_begin_expr()`.
1461            let lo = this.token.span;
1462            if let token::Literal(_) = this.token.kind {
1463                // This match arm is a special-case of the `_` match arm below and
1464                // could be removed without changing functionality, but it's faster
1465                // to have it here, especially for programs with large constants.
1466                this.parse_expr_lit()
1467            } else if this.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenParen,
    token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen)) {
1468                this.parse_expr_tuple_parens(restrictions)
1469            } else if this.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenBrace,
    token_type: crate::parser::token_type::TokenType::OpenBrace,
}exp!(OpenBrace)) {
1470                if let Some(expr) = this.maybe_recover_bad_struct_literal_path(false)? {
1471                    return Ok(expr);
1472                }
1473                this.parse_expr_block(None, lo, BlockCheckMode::Default)
1474            } 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)) {
1475                this.parse_expr_closure().map_err(|mut err| {
1476                    // If the input is something like `if a { 1 } else { 2 } | if a { 3 } else { 4 }`
1477                    // then suggest parens around the lhs.
1478                    if let Some(sp) = this.psess.ambiguous_block_expr_parse.borrow().get(&lo) {
1479                        err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp));
1480                    }
1481                    err
1482                })
1483            } else if this.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenBracket,
    token_type: crate::parser::token_type::TokenType::OpenBracket,
}exp!(OpenBracket)) {
1484                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))
1485            } else if this.is_builtin() {
1486                this.parse_expr_builtin()
1487            } else if this.check_path() {
1488                this.parse_expr_path_start()
1489            } 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))
1490                || this.check_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Use,
    token_type: crate::parser::token_type::TokenType::KwUse,
}exp!(Use))
1491                || this.check_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Static,
    token_type: crate::parser::token_type::TokenType::KwStatic,
}exp!(Static))
1492                || this.check_const_closure()
1493            {
1494                this.parse_expr_closure()
1495            } 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)) {
1496                this.parse_expr_if()
1497            } 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)) {
1498                if this.choose_generics_over_qpath(1) {
1499                    this.parse_expr_closure()
1500                } else {
1501                    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)));
1502                    this.parse_expr_for(None, lo)
1503                }
1504            } 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)) {
1505                this.parse_expr_while(None, lo)
1506            } else if let Some(label) = this.eat_label() {
1507                this.parse_expr_labeled(label, true)
1508            } 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)) {
1509                this.parse_expr_loop(None, lo).map_err(|mut err| {
1510                    err.span_label(lo, "while parsing this `loop` expression");
1511                    err
1512                })
1513            } 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)) {
1514                this.parse_expr_match().map_err(|mut err| {
1515                    err.span_label(lo, "while parsing this `match` expression");
1516                    err
1517                })
1518            } 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)) {
1519                this.parse_expr_block(None, lo, BlockCheckMode::Unsafe(ast::UserProvided)).map_err(
1520                    |mut err| {
1521                        err.span_label(lo, "while parsing this `unsafe` expression");
1522                        err
1523                    },
1524                )
1525            } else if this.check_inline_const(0) {
1526                this.parse_const_block(lo, false)
1527            } else if this.may_recover() && this.is_do_catch_block() {
1528                this.recover_do_catch()
1529            } else if this.is_try_block() {
1530                this.expect_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Try,
    token_type: crate::parser::token_type::TokenType::KwTry,
}exp!(Try))?;
1531                this.parse_try_block(lo)
1532            } 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)) {
1533                this.parse_expr_return()
1534            } 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)) {
1535                this.parse_expr_continue(lo)
1536            } 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)) {
1537                this.parse_expr_break()
1538            } 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)) {
1539                this.parse_expr_yield()
1540            } else if this.is_do_yeet() {
1541                this.parse_expr_yeet()
1542            } 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)) {
1543                this.parse_expr_become()
1544            } 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)) {
1545                this.parse_expr_let(restrictions)
1546            } 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)) {
1547                if let Some(expr) = this.maybe_recover_bad_struct_literal_path(true)? {
1548                    return Ok(expr);
1549                }
1550                Ok(this.mk_expr(this.prev_token.span, ExprKind::Underscore))
1551            } else if this.token_uninterpolated_span().at_least_rust_2018() {
1552                // `Span::at_least_rust_2018()` is somewhat expensive; don't get it repeatedly.
1553                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));
1554                // check for `gen {}` and `gen move {}`
1555                // or `async gen {}` and `async gen move {}`
1556                // FIXME: (async) gen closures aren't yet parsed.
1557                // FIXME(gen_blocks): Parse `gen async` and suggest swap
1558                if this.token_uninterpolated_span().at_least_rust_2024()
1559                    && this.is_gen_block(kw::Gen, at_async as usize)
1560                {
1561                    this.parse_gen_block()
1562                // Check for `async {` and `async move {`,
1563                } else if this.is_gen_block(kw::Async, 0) {
1564                    this.parse_gen_block()
1565                } else if at_async {
1566                    this.parse_expr_closure()
1567                } else if this.eat_keyword_noexpect(kw::Await) {
1568                    this.recover_incorrect_await_syntax(lo)
1569                } else {
1570                    this.parse_expr_lit()
1571                }
1572            } else {
1573                this.parse_expr_lit()
1574            }
1575        })
1576    }
1577
1578    fn parse_expr_lit(&mut self) -> PResult<'a, Box<Expr>> {
1579        let lo = self.token.span;
1580        match self.parse_opt_token_lit() {
1581            Some((token_lit, _)) => {
1582                let expr = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Lit(token_lit));
1583                self.maybe_recover_from_bad_qpath(expr)
1584            }
1585            None => self.try_macro_suggestion(),
1586        }
1587    }
1588
1589    fn parse_expr_tuple_parens(&mut self, restrictions: Restrictions) -> PResult<'a, Box<Expr>> {
1590        let lo = self.token.span;
1591        self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenParen,
    token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen))?;
1592        let (es, trailing_comma) = match self.parse_seq_to_end(
1593            crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseParen,
    token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen),
1594            SeqSep::trailing_allowed(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma)),
1595            |p| p.parse_expr_catch_underscore(restrictions.intersection(Restrictions::ALLOW_LET)),
1596        ) {
1597            Ok(x) => x,
1598            Err(err) => {
1599                return Ok(self.recover_seq_parse_error(
1600                    crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenParen,
    token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen),
1601                    crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseParen,
    token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen),
1602                    lo,
1603                    err,
1604                ));
1605            }
1606        };
1607        let kind = if es.len() == 1 && #[allow(non_exhaustive_omitted_patterns)] match trailing_comma {
    Trailing::No => true,
    _ => false,
}matches!(trailing_comma, Trailing::No) {
1608            // `(e)` is parenthesized `e`.
1609            ExprKind::Paren(es.into_iter().next().unwrap())
1610        } else {
1611            // `(e,)` is a tuple with only one field, `e`.
1612            ExprKind::Tup(es)
1613        };
1614        let expr = self.mk_expr(lo.to(self.prev_token.span), kind);
1615        self.maybe_recover_from_bad_qpath(expr)
1616    }
1617
1618    fn parse_expr_array_or_repeat(&mut self, close: ExpTokenPair) -> PResult<'a, Box<Expr>> {
1619        let lo = self.token.span;
1620        self.bump(); // `[` or other open delim
1621
1622        let kind = if self.eat(close) {
1623            // Empty vector
1624            ExprKind::Array(ThinVec::new())
1625        } else {
1626            // Non-empty vector
1627            let first_expr = self.parse_expr()?;
1628            if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Semi,
    token_type: crate::parser::token_type::TokenType::Semi,
}exp!(Semi)) {
1629                // Repeating array syntax: `[ 0; 512 ]`
1630                let count = self.parse_expr_anon_const(|_, _| MgcaDisambiguation::Direct)?;
1631                self.expect(close)?;
1632                ExprKind::Repeat(first_expr, count)
1633            } else if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma)) {
1634                // Vector with two or more elements.
1635                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));
1636                let (mut exprs, _) = self.parse_seq_to_end(close, sep, |p| p.parse_expr())?;
1637                exprs.insert(0, first_expr);
1638                ExprKind::Array(exprs)
1639            } else {
1640                // Vector with one element
1641                self.expect(close)?;
1642                ExprKind::Array({
    let len = [()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(first_expr);
    vec
}thin_vec![first_expr])
1643            }
1644        };
1645        let expr = self.mk_expr(lo.to(self.prev_token.span), kind);
1646        self.maybe_recover_from_bad_qpath(expr)
1647    }
1648
1649    fn parse_expr_path_start(&mut self) -> PResult<'a, Box<Expr>> {
1650        let maybe_eq_tok = self.prev_token;
1651        let (qself, path) = if self.eat_lt() {
1652            let lt_span = self.prev_token.span;
1653            let (qself, path) = self.parse_qpath(PathStyle::Expr).map_err(|mut err| {
1654                // Suggests using '<=' if there is an error parsing qpath when the previous token
1655                // is an '=' token. Only emits suggestion if the '<' token and '=' token are
1656                // directly adjacent (i.e. '=<')
1657                if maybe_eq_tok == TokenKind::Eq && maybe_eq_tok.span.hi() == lt_span.lo() {
1658                    let eq_lt = maybe_eq_tok.span.to(lt_span);
1659                    err.span_suggestion(eq_lt, "did you mean", "<=", Applicability::Unspecified);
1660                }
1661                err
1662            })?;
1663            (Some(qself), path)
1664        } else {
1665            (None, self.parse_path(PathStyle::Expr)?)
1666        };
1667
1668        // `!`, as an operator, is prefix, so we know this isn't that.
1669        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)) {
1670            // MACRO INVOCATION expression
1671            if qself.is_some() {
1672                self.dcx().emit_err(errors::MacroInvocationWithQualifiedPath(path.span));
1673            }
1674            let lo = path.span;
1675            let mac = Box::new(MacCall { path, args: self.parse_delim_args()? });
1676            (lo.to(self.prev_token.span), ExprKind::MacCall(mac))
1677        } else if self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenBrace,
    token_type: crate::parser::token_type::TokenType::OpenBrace,
}exp!(OpenBrace))
1678            && let Some(expr) = self.maybe_parse_struct_expr(&qself, &path)
1679        {
1680            if qself.is_some() {
1681                self.psess.gated_spans.gate(sym::more_qualified_paths, path.span);
1682            }
1683            return expr;
1684        } else {
1685            (path.span, ExprKind::Path(qself, path))
1686        };
1687
1688        let expr = self.mk_expr(span, kind);
1689        self.maybe_recover_from_bad_qpath(expr)
1690    }
1691
1692    /// Parse `'label: $expr`. The label is already parsed.
1693    pub(super) fn parse_expr_labeled(
1694        &mut self,
1695        label_: Label,
1696        mut consume_colon: bool,
1697    ) -> PResult<'a, Box<Expr>> {
1698        let lo = label_.ident.span;
1699        let label = Some(label_);
1700        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));
1701        let tok_sp = self.token.span;
1702        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)) {
1703            self.parse_expr_while(label, lo)
1704        } 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)) {
1705            self.parse_expr_for(label, lo)
1706        } 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)) {
1707            self.parse_expr_loop(label, lo)
1708        } else if self.check_noexpect(&token::OpenBrace) || self.token.is_metavar_block() {
1709            self.parse_expr_block(label, lo, BlockCheckMode::Default)
1710        } else if !ate_colon
1711            && self.may_recover()
1712            && (self.token.kind.close_delim().is_some() || self.token.is_punct())
1713            && could_be_unclosed_char_literal(label_.ident)
1714        {
1715            let (lit, _) =
1716                self.recover_unclosed_char(label_.ident, Parser::mk_token_lit_char, |self_| {
1717                    self_.dcx().create_err(errors::UnexpectedTokenAfterLabel {
1718                        span: self_.token.span,
1719                        remove_label: None,
1720                        enclose_in_block: None,
1721                    })
1722                });
1723            consume_colon = false;
1724            Ok(self.mk_expr(lo, ExprKind::Lit(lit)))
1725        } else if !ate_colon
1726            && (self.check_noexpect(&TokenKind::Comma) || self.check_noexpect(&TokenKind::Gt))
1727        {
1728            // We're probably inside of a `Path<'a>` that needs a turbofish
1729            let guar = self.dcx().emit_err(errors::UnexpectedTokenAfterLabel {
1730                span: self.token.span,
1731                remove_label: None,
1732                enclose_in_block: None,
1733            });
1734            consume_colon = false;
1735            Ok(self.mk_expr_err(lo, guar))
1736        } else {
1737            let mut err = errors::UnexpectedTokenAfterLabel {
1738                span: self.token.span,
1739                remove_label: None,
1740                enclose_in_block: None,
1741            };
1742
1743            // Continue as an expression in an effort to recover on `'label: non_block_expr`.
1744            let expr = self.parse_expr().map(|expr| {
1745                let span = expr.span;
1746
1747                let found_labeled_breaks = {
1748                    struct FindLabeledBreaksVisitor;
1749
1750                    impl<'ast> Visitor<'ast> for FindLabeledBreaksVisitor {
1751                        type Result = ControlFlow<()>;
1752                        fn visit_expr(&mut self, ex: &'ast Expr) -> ControlFlow<()> {
1753                            if let ExprKind::Break(Some(_label), _) = ex.kind {
1754                                ControlFlow::Break(())
1755                            } else {
1756                                walk_expr(self, ex)
1757                            }
1758                        }
1759                    }
1760
1761                    FindLabeledBreaksVisitor.visit_expr(&expr).is_break()
1762                };
1763
1764                // Suggestion involves adding a labeled block.
1765                //
1766                // If there are no breaks that may use this label, suggest removing the label and
1767                // recover to the unmodified expression.
1768                if !found_labeled_breaks {
1769                    err.remove_label = Some(lo.until(span));
1770
1771                    return expr;
1772                }
1773
1774                err.enclose_in_block = Some(errors::UnexpectedTokenAfterLabelSugg {
1775                    left: span.shrink_to_lo(),
1776                    right: span.shrink_to_hi(),
1777                });
1778
1779                // Replace `'label: non_block_expr` with `'label: {non_block_expr}` in order to suppress future errors about `break 'label`.
1780                let stmt = self.mk_stmt(span, StmtKind::Expr(expr));
1781                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);
1782                self.mk_expr(span, ExprKind::Block(blk, label))
1783            });
1784
1785            self.dcx().emit_err(err);
1786            expr
1787        }?;
1788
1789        if !ate_colon && consume_colon {
1790            self.dcx().emit_err(errors::RequireColonAfterLabeledExpression {
1791                span: expr.span,
1792                label: lo,
1793                label_end: lo.between(tok_sp),
1794            });
1795        }
1796
1797        Ok(expr)
1798    }
1799
1800    /// Emit an error when a char is parsed as a lifetime or label because of a missing quote.
1801    pub(super) fn recover_unclosed_char<L>(
1802        &self,
1803        ident: Ident,
1804        mk_lit_char: impl FnOnce(Symbol, Span) -> L,
1805        err: impl FnOnce(&Self) -> Diag<'a>,
1806    ) -> L {
1807        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));
1808        self.dcx()
1809            .try_steal_modify_and_emit_err(ident.span, StashKey::LifetimeIsChar, |err| {
1810                err.span_suggestion_verbose(
1811                    ident.span.shrink_to_hi(),
1812                    "add `'` to close the char literal",
1813                    "'",
1814                    Applicability::MaybeIncorrect,
1815                );
1816            })
1817            .unwrap_or_else(|| {
1818                err(self)
1819                    .with_span_suggestion_verbose(
1820                        ident.span.shrink_to_hi(),
1821                        "add `'` to close the char literal",
1822                        "'",
1823                        Applicability::MaybeIncorrect,
1824                    )
1825                    .emit()
1826            });
1827        let name = ident.without_first_quote().name;
1828        mk_lit_char(name, ident.span)
1829    }
1830
1831    /// Recover on the syntax `do catch { ... }` suggesting `try { ... }` instead.
1832    fn recover_do_catch(&mut self) -> PResult<'a, Box<Expr>> {
1833        let lo = self.token.span;
1834
1835        self.bump(); // `do`
1836        self.bump(); // `catch`
1837
1838        let span = lo.to(self.prev_token.span);
1839        self.dcx().emit_err(errors::DoCatchSyntaxRemoved { span });
1840
1841        self.parse_try_block(lo)
1842    }
1843
1844    /// Parse an expression if the token can begin one.
1845    fn parse_expr_opt(&mut self) -> PResult<'a, Option<Box<Expr>>> {
1846        Ok(if self.token.can_begin_expr() { Some(self.parse_expr()?) } else { None })
1847    }
1848
1849    /// Parse `"return" expr?`.
1850    fn parse_expr_return(&mut self) -> PResult<'a, Box<Expr>> {
1851        let lo = self.prev_token.span;
1852        let kind = ExprKind::Ret(self.parse_expr_opt()?);
1853        let expr = self.mk_expr(lo.to(self.prev_token.span), kind);
1854        self.maybe_recover_from_bad_qpath(expr)
1855    }
1856
1857    /// Parse `"do" "yeet" expr?`.
1858    fn parse_expr_yeet(&mut self) -> PResult<'a, Box<Expr>> {
1859        let lo = self.token.span;
1860
1861        self.bump(); // `do`
1862        self.bump(); // `yeet`
1863
1864        let kind = ExprKind::Yeet(self.parse_expr_opt()?);
1865
1866        let span = lo.to(self.prev_token.span);
1867        self.psess.gated_spans.gate(sym::yeet_expr, span);
1868        let expr = self.mk_expr(span, kind);
1869        self.maybe_recover_from_bad_qpath(expr)
1870    }
1871
1872    /// Parse `"become" expr`, with `"become"` token already eaten.
1873    fn parse_expr_become(&mut self) -> PResult<'a, Box<Expr>> {
1874        let lo = self.prev_token.span;
1875        let kind = ExprKind::Become(self.parse_expr()?);
1876        let span = lo.to(self.prev_token.span);
1877        self.psess.gated_spans.gate(sym::explicit_tail_calls, span);
1878        let expr = self.mk_expr(span, kind);
1879        self.maybe_recover_from_bad_qpath(expr)
1880    }
1881
1882    /// Parse `"break" (('label (:? expr)?) | expr?)` with `"break"` token already eaten.
1883    /// If the label is followed immediately by a `:` token, the label and `:` are
1884    /// parsed as part of the expression (i.e. a labeled loop). The language team has
1885    /// decided in #87026 to require parentheses as a visual aid to avoid confusion if
1886    /// the break expression of an unlabeled break is a labeled loop (as in
1887    /// `break 'lbl: loop {}`); a labeled break with an unlabeled loop as its value
1888    /// expression only gets a warning for compatibility reasons; and a labeled break
1889    /// with a labeled loop does not even get a warning because there is no ambiguity.
1890    fn parse_expr_break(&mut self) -> PResult<'a, Box<Expr>> {
1891        let lo = self.prev_token.span;
1892        let mut label = self.eat_label();
1893        let kind = if self.token == token::Colon
1894            && let Some(label) = label.take()
1895        {
1896            // The value expression can be a labeled loop, see issue #86948, e.g.:
1897            // `loop { break 'label: loop { break 'label 42; }; }`
1898            let lexpr = self.parse_expr_labeled(label, true)?;
1899            self.dcx().emit_err(errors::LabeledLoopInBreak {
1900                span: lexpr.span,
1901                sub: errors::WrapInParentheses::Expression {
1902                    left: lexpr.span.shrink_to_lo(),
1903                    right: lexpr.span.shrink_to_hi(),
1904                },
1905            });
1906            Some(lexpr)
1907        } else if self.token != token::OpenBrace
1908            || !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
1909        {
1910            let mut expr = self.parse_expr_opt()?;
1911            if let Some(expr) = &mut expr {
1912                if label.is_some()
1913                    && match &expr.kind {
1914                        ExprKind::While(_, _, None)
1915                        | ExprKind::ForLoop { label: None, .. }
1916                        | ExprKind::Loop(_, None, _) => true,
1917                        ExprKind::Block(block, None) => {
1918                            #[allow(non_exhaustive_omitted_patterns)] match block.rules {
    BlockCheckMode::Default => true,
    _ => false,
}matches!(block.rules, BlockCheckMode::Default)
1919                        }
1920                        _ => false,
1921                    }
1922                {
1923                    let span = expr.span;
1924                    self.psess.buffer_lint(
1925                        BREAK_WITH_LABEL_AND_LOOP,
1926                        lo.to(expr.span),
1927                        ast::CRATE_NODE_ID,
1928                        errors::BreakWithLabelAndLoop {
1929                            sub: errors::BreakWithLabelAndLoopSub {
1930                                left: span.shrink_to_lo(),
1931                                right: span.shrink_to_hi(),
1932                            },
1933                        },
1934                    );
1935                }
1936
1937                // Recover `break label aaaaa`
1938                if self.may_recover()
1939                    && let ExprKind::Path(None, p) = &expr.kind
1940                    && let [segment] = &*p.segments
1941                    && let &ast::PathSegment { ident, args: None, .. } = segment
1942                    && let Some(next) = self.parse_expr_opt()?
1943                {
1944                    label = Some(self.recover_ident_into_label(ident));
1945                    *expr = next;
1946                }
1947            }
1948
1949            expr
1950        } else {
1951            None
1952        };
1953        let expr = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Break(label, kind));
1954        self.maybe_recover_from_bad_qpath(expr)
1955    }
1956
1957    /// Parse `"continue" label?`.
1958    fn parse_expr_continue(&mut self, lo: Span) -> PResult<'a, Box<Expr>> {
1959        let mut label = self.eat_label();
1960
1961        // Recover `continue label` -> `continue 'label`
1962        if self.may_recover()
1963            && label.is_none()
1964            && let Some((ident, _)) = self.token.ident()
1965        {
1966            self.bump();
1967            label = Some(self.recover_ident_into_label(ident));
1968        }
1969
1970        let kind = ExprKind::Continue(label);
1971        Ok(self.mk_expr(lo.to(self.prev_token.span), kind))
1972    }
1973
1974    /// Parse `"yield" expr?`.
1975    fn parse_expr_yield(&mut self) -> PResult<'a, Box<Expr>> {
1976        let lo = self.prev_token.span;
1977        let kind = ExprKind::Yield(YieldKind::Prefix(self.parse_expr_opt()?));
1978        let span = lo.to(self.prev_token.span);
1979        self.psess.gated_spans.gate(sym::yield_expr, span);
1980        let expr = self.mk_expr(span, kind);
1981        self.maybe_recover_from_bad_qpath(expr)
1982    }
1983
1984    /// Parse `builtin # ident(args,*)`.
1985    fn parse_expr_builtin(&mut self) -> PResult<'a, Box<Expr>> {
1986        self.parse_builtin(|this, lo, ident| {
1987            Ok(match ident.name {
1988                sym::offset_of => Some(this.parse_expr_offset_of(lo)?),
1989                sym::type_ascribe => Some(this.parse_expr_type_ascribe(lo)?),
1990                sym::wrap_binder => {
1991                    Some(this.parse_expr_unsafe_binder_cast(lo, UnsafeBinderCastKind::Wrap)?)
1992                }
1993                sym::unwrap_binder => {
1994                    Some(this.parse_expr_unsafe_binder_cast(lo, UnsafeBinderCastKind::Unwrap)?)
1995                }
1996                _ => None,
1997            })
1998        })
1999    }
2000
2001    pub(crate) fn parse_builtin<T>(
2002        &mut self,
2003        parse: impl FnOnce(&mut Parser<'a>, Span, Ident) -> PResult<'a, Option<T>>,
2004    ) -> PResult<'a, T> {
2005        let lo = self.token.span;
2006
2007        self.bump(); // `builtin`
2008        self.bump(); // `#`
2009
2010        let Some((ident, IdentIsRaw::No)) = self.token.ident() else {
2011            let err = self.dcx().create_err(errors::ExpectedBuiltinIdent { span: self.token.span });
2012            return Err(err);
2013        };
2014        self.psess.gated_spans.gate(sym::builtin_syntax, ident.span);
2015        self.bump();
2016
2017        self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenParen,
    token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen))?;
2018        let ret = if let Some(res) = parse(self, lo, ident)? {
2019            Ok(res)
2020        } else {
2021            let err = self.dcx().create_err(errors::UnknownBuiltinConstruct {
2022                span: lo.to(ident.span),
2023                name: ident,
2024            });
2025            return Err(err);
2026        };
2027        self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseParen,
    token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen))?;
2028
2029        ret
2030    }
2031
2032    /// Built-in macro for `offset_of!` expressions.
2033    pub(crate) fn parse_expr_offset_of(&mut self, lo: Span) -> PResult<'a, Box<Expr>> {
2034        let container = self.parse_ty()?;
2035        self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma))?;
2036
2037        let fields = self.parse_floating_field_access()?;
2038        let trailing_comma = self.eat_noexpect(&TokenKind::Comma);
2039
2040        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)]) {
2041            if trailing_comma {
2042                e.note("unexpected third argument to offset_of");
2043            } else {
2044                e.note("offset_of expects dot-separated field and variant names");
2045            }
2046            e.emit();
2047        }
2048
2049        // Eat tokens until the macro call ends.
2050        if self.may_recover() {
2051            while !self.token.kind.is_close_delim_or_eof() {
2052                self.bump();
2053            }
2054        }
2055
2056        let span = lo.to(self.token.span);
2057        Ok(self.mk_expr(span, ExprKind::OffsetOf(container, fields)))
2058    }
2059
2060    /// Built-in macro for type ascription expressions.
2061    pub(crate) fn parse_expr_type_ascribe(&mut self, lo: Span) -> PResult<'a, Box<Expr>> {
2062        let expr = self.parse_expr()?;
2063        self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma))?;
2064        let ty = self.parse_ty()?;
2065        let span = lo.to(self.token.span);
2066        Ok(self.mk_expr(span, ExprKind::Type(expr, ty)))
2067    }
2068
2069    pub(crate) fn parse_expr_unsafe_binder_cast(
2070        &mut self,
2071        lo: Span,
2072        kind: UnsafeBinderCastKind,
2073    ) -> PResult<'a, Box<Expr>> {
2074        let expr = self.parse_expr()?;
2075        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 };
2076        let span = lo.to(self.token.span);
2077        Ok(self.mk_expr(span, ExprKind::UnsafeBinderCast(kind, expr, ty)))
2078    }
2079
2080    /// Returns a string literal if the next token is a string literal.
2081    /// In case of error returns `Some(lit)` if the next token is a literal with a wrong kind,
2082    /// and returns `None` if the next token is not literal at all.
2083    pub fn parse_str_lit(&mut self) -> Result<ast::StrLit, Option<MetaItemLit>> {
2084        match self.parse_opt_meta_item_lit() {
2085            Some(lit) => match lit.kind {
2086                ast::LitKind::Str(symbol_unescaped, style) => Ok(ast::StrLit {
2087                    style,
2088                    symbol: lit.symbol,
2089                    suffix: lit.suffix,
2090                    span: lit.span,
2091                    symbol_unescaped,
2092                }),
2093                _ => Err(Some(lit)),
2094            },
2095            None => Err(None),
2096        }
2097    }
2098
2099    pub(crate) fn mk_token_lit_char(name: Symbol, span: Span) -> (token::Lit, Span) {
2100        (token::Lit { symbol: name, suffix: None, kind: token::Char }, span)
2101    }
2102
2103    fn mk_meta_item_lit_char(name: Symbol, span: Span) -> MetaItemLit {
2104        ast::MetaItemLit {
2105            symbol: name,
2106            suffix: None,
2107            kind: ast::LitKind::Char(name.as_str().chars().next().unwrap_or('_')),
2108            span,
2109        }
2110    }
2111
2112    fn handle_missing_lit<L>(
2113        &mut self,
2114        mk_lit_char: impl FnOnce(Symbol, Span) -> L,
2115    ) -> PResult<'a, L> {
2116        let token = self.token;
2117        let err = |self_: &Self| {
2118            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));
2119            self_.dcx().struct_span_err(token.span, msg)
2120        };
2121        // On an error path, eagerly consider a lifetime to be an unclosed character lit, if that
2122        // makes sense.
2123        if let Some((ident, IdentIsRaw::No)) = self.token.lifetime()
2124            && could_be_unclosed_char_literal(ident)
2125        {
2126            let lt = self.expect_lifetime();
2127            Ok(self.recover_unclosed_char(lt.ident, mk_lit_char, err))
2128        } else {
2129            Err(err(self))
2130        }
2131    }
2132
2133    pub(super) fn parse_token_lit(&mut self) -> PResult<'a, (token::Lit, Span)> {
2134        self.parse_opt_token_lit()
2135            .ok_or(())
2136            .or_else(|()| self.handle_missing_lit(Parser::mk_token_lit_char))
2137    }
2138
2139    pub(super) fn parse_meta_item_lit(&mut self) -> PResult<'a, MetaItemLit> {
2140        self.parse_opt_meta_item_lit()
2141            .ok_or(())
2142            .or_else(|()| self.handle_missing_lit(Parser::mk_meta_item_lit_char))
2143    }
2144
2145    fn recover_after_dot(&mut self) {
2146        if self.token == token::Dot {
2147            // Attempt to recover `.4` as `0.4`. We don't currently have any syntax where
2148            // dot would follow an optional literal, so we do this unconditionally.
2149            let recovered = self.look_ahead(1, |next_token| {
2150                // If it's an integer that looks like a float, then recover as such.
2151                //
2152                // We will never encounter the exponent part of a floating
2153                // point literal here, since there's no use of the exponent
2154                // syntax that also constitutes a valid integer, so we need
2155                // not check for that.
2156                if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) =
2157                    next_token.kind
2158                    && suffix.is_none_or(|s| s == sym::f32 || s == sym::f64)
2159                    && symbol.as_str().chars().all(|c| c.is_numeric() || c == '_')
2160                    && self.token.span.hi() == next_token.span.lo()
2161                {
2162                    let s = String::from("0.") + symbol.as_str();
2163                    let kind = TokenKind::lit(token::Float, Symbol::intern(&s), suffix);
2164                    Some(Token::new(kind, self.token.span.to(next_token.span)))
2165                } else {
2166                    None
2167                }
2168            });
2169            if let Some(recovered) = recovered {
2170                self.dcx().emit_err(errors::FloatLiteralRequiresIntegerPart {
2171                    span: recovered.span,
2172                    suggestion: recovered.span.shrink_to_lo(),
2173                });
2174                self.bump();
2175                self.token = recovered;
2176            }
2177        }
2178    }
2179
2180    /// Keep this in sync with `Token::can_begin_literal_maybe_minus` and
2181    /// `Lit::from_token` (excluding unary negation).
2182    pub fn eat_token_lit(&mut self) -> Option<token::Lit> {
2183        let check_expr = |expr: Box<Expr>| {
2184            if let ast::ExprKind::Lit(token_lit) = expr.kind {
2185                Some(token_lit)
2186            } else if let ast::ExprKind::Unary(UnOp::Neg, inner) = &expr.kind
2187                && let ast::Expr { kind: ast::ExprKind::Lit(_), .. } = **inner
2188            {
2189                None
2190            } else {
2191                {
    ::core::panicking::panic_fmt(format_args!("unexpected reparsed expr/literal: {0:?}",
            expr.kind));
};panic!("unexpected reparsed expr/literal: {:?}", expr.kind);
2192            }
2193        };
2194        match self.token.uninterpolate().kind {
2195            token::Ident(name, IdentIsRaw::No) if name.is_bool_lit() => {
2196                self.bump();
2197                Some(token::Lit::new(token::Bool, name, None))
2198            }
2199            token::Literal(token_lit) => {
2200                self.bump();
2201                Some(token_lit)
2202            }
2203            token::OpenInvisible(InvisibleOrigin::MetaVar(MetaVarKind::Literal)) => {
2204                let lit = self
2205                    .eat_metavar_seq(MetaVarKind::Literal, |this| this.parse_literal_maybe_minus())
2206                    .expect("metavar seq literal");
2207                check_expr(lit)
2208            }
2209            token::OpenInvisible(InvisibleOrigin::MetaVar(
2210                mv_kind @ MetaVarKind::Expr { can_begin_literal_maybe_minus: true, .. },
2211            )) => {
2212                let expr = self
2213                    .eat_metavar_seq(mv_kind, |this| this.parse_expr())
2214                    .expect("metavar seq expr");
2215                check_expr(expr)
2216            }
2217            _ => None,
2218        }
2219    }
2220
2221    /// Matches `lit = true | false | token_lit`.
2222    /// Returns `None` if the next token is not a literal.
2223    fn parse_opt_token_lit(&mut self) -> Option<(token::Lit, Span)> {
2224        self.recover_after_dot();
2225        let span = self.token.span;
2226        self.eat_token_lit().map(|token_lit| (token_lit, span))
2227    }
2228
2229    /// Matches `lit = true | false | token_lit`.
2230    /// Returns `None` if the next token is not a literal.
2231    fn parse_opt_meta_item_lit(&mut self) -> Option<MetaItemLit> {
2232        self.recover_after_dot();
2233        let span = self.token.span;
2234        let uninterpolated_span = self.token_uninterpolated_span();
2235        self.eat_token_lit().map(|token_lit| {
2236            match MetaItemLit::from_token_lit(token_lit, span) {
2237                Ok(lit) => lit,
2238                Err(err) => {
2239                    let guar = report_lit_error(&self.psess, err, token_lit, uninterpolated_span);
2240                    // Pack possible quotes and prefixes from the original literal into
2241                    // the error literal's symbol so they can be pretty-printed faithfully.
2242                    let suffixless_lit = token::Lit::new(token_lit.kind, token_lit.symbol, None);
2243                    let symbol = Symbol::intern(&suffixless_lit.to_string());
2244                    let token_lit = token::Lit::new(token::Err(guar), symbol, token_lit.suffix);
2245                    MetaItemLit::from_token_lit(token_lit, uninterpolated_span).unwrap()
2246                }
2247            }
2248        })
2249    }
2250
2251    /// Matches `'-' lit | lit` (cf. `ast_validation::AstValidator::check_expr_within_pat`).
2252    /// Keep this in sync with `Token::can_begin_literal_maybe_minus`.
2253    pub fn parse_literal_maybe_minus(&mut self) -> PResult<'a, Box<Expr>> {
2254        if let Some(expr) = self.eat_metavar_seq_with_matcher(
2255            |mv_kind| #[allow(non_exhaustive_omitted_patterns)] match mv_kind {
    MetaVarKind::Expr { .. } => true,
    _ => false,
}matches!(mv_kind, MetaVarKind::Expr { .. }),
2256            |this| {
2257                // FIXME(nnethercote) The `expr` case should only match if
2258                // `e` is an `ExprKind::Lit` or an `ExprKind::Unary` containing
2259                // an `UnOp::Neg` and an `ExprKind::Lit`, like how
2260                // `can_begin_literal_maybe_minus` works. But this method has
2261                // been over-accepting for a long time, and to make that change
2262                // here requires also changing some `parse_literal_maybe_minus`
2263                // call sites to accept additional expression kinds. E.g.
2264                // `ExprKind::Path` must be accepted when parsing range
2265                // patterns. That requires some care. So for now, we continue
2266                // being less strict here than we should be.
2267                this.parse_expr()
2268            },
2269        ) {
2270            return Ok(expr);
2271        } else if let Some(lit) =
2272            self.eat_metavar_seq(MetaVarKind::Literal, |this| this.parse_literal_maybe_minus())
2273        {
2274            return Ok(lit);
2275        }
2276
2277        let lo = self.token.span;
2278        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));
2279        let (token_lit, span) = self.parse_token_lit()?;
2280        let expr = self.mk_expr(span, ExprKind::Lit(token_lit));
2281
2282        if minus_present {
2283            Ok(self.mk_expr(lo.to(self.prev_token.span), self.mk_unary(UnOp::Neg, expr)))
2284        } else {
2285            Ok(expr)
2286        }
2287    }
2288
2289    fn is_array_like_block(&mut self) -> bool {
2290        self.token.kind == TokenKind::OpenBrace
2291            && self
2292                .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(_)))
2293            && self.look_ahead(2, |t| t == &token::Comma)
2294            && self.look_ahead(3, |t| t.can_begin_expr())
2295    }
2296
2297    /// Emits a suggestion if it looks like the user meant an array but
2298    /// accidentally used braces, causing the code to be interpreted as a block
2299    /// expression.
2300    fn maybe_suggest_brackets_instead_of_braces(&mut self, lo: Span) -> Option<Box<Expr>> {
2301        let mut snapshot = self.create_snapshot_for_diagnostic();
2302        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)) {
2303            Ok(arr) => {
2304                let guar = self.dcx().emit_err(errors::ArrayBracketsInsteadOfBraces {
2305                    span: arr.span,
2306                    sub: errors::ArrayBracketsInsteadOfBracesSugg {
2307                        left: lo,
2308                        right: snapshot.prev_token.span,
2309                    },
2310                });
2311
2312                self.restore_snapshot(snapshot);
2313                Some(self.mk_expr_err(arr.span, guar))
2314            }
2315            Err(e) => {
2316                e.cancel();
2317                None
2318            }
2319        }
2320    }
2321
2322    fn suggest_missing_semicolon_before_array(
2323        &self,
2324        prev_span: Span,
2325        open_delim_span: Span,
2326    ) -> PResult<'a, ()> {
2327        if !self.may_recover() {
2328            return Ok(());
2329        }
2330
2331        if self.token == token::Comma {
2332            if !self.psess.source_map().is_multiline(prev_span.until(self.token.span)) {
2333                return Ok(());
2334            }
2335            let mut snapshot = self.create_snapshot_for_diagnostic();
2336            snapshot.bump();
2337            match snapshot.parse_seq_to_before_end(
2338                crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseBracket,
    token_type: crate::parser::token_type::TokenType::CloseBracket,
}exp!(CloseBracket),
2339                SeqSep::trailing_allowed(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma)),
2340                |p| p.parse_expr(),
2341            ) {
2342                Ok(_)
2343                    // When the close delim is `)`, `token.kind` is expected to be `token::CloseParen`,
2344                    // but the actual `token.kind` is `token::CloseBracket`.
2345                    // This is because the `token.kind` of the close delim is treated as the same as
2346                    // that of the open delim in `TokenTreesReader::parse_token_tree`, even if the delimiters of them are different.
2347                    // Therefore, `token.kind` should not be compared here.
2348                    if snapshot
2349                        .span_to_snippet(snapshot.token.span)
2350                        .is_ok_and(|snippet| snippet == "]") =>
2351                {
2352                    return Err(self.dcx().create_err(errors::MissingSemicolonBeforeArray {
2353                        open_delim: open_delim_span,
2354                        semicolon: prev_span.shrink_to_hi(),
2355                    }));
2356                }
2357                Ok(_) => (),
2358                Err(err) => err.cancel(),
2359            }
2360        }
2361        Ok(())
2362    }
2363
2364    /// Parses a block or unsafe block.
2365    pub(super) fn parse_expr_block(
2366        &mut self,
2367        opt_label: Option<Label>,
2368        lo: Span,
2369        blk_mode: BlockCheckMode,
2370    ) -> PResult<'a, Box<Expr>> {
2371        if self.may_recover() && self.is_array_like_block() {
2372            if let Some(arr) = self.maybe_suggest_brackets_instead_of_braces(lo) {
2373                return Ok(arr);
2374            }
2375        }
2376
2377        if self.token.is_metavar_block() {
2378            self.dcx().emit_err(errors::InvalidBlockMacroSegment {
2379                span: self.token.span,
2380                context: lo.to(self.token.span),
2381                wrap: errors::WrapInExplicitBlock {
2382                    lo: self.token.span.shrink_to_lo(),
2383                    hi: self.token.span.shrink_to_hi(),
2384                },
2385            });
2386        }
2387
2388        let (attrs, blk) = self.parse_block_common(lo, blk_mode, None)?;
2389        Ok(self.mk_expr_with_attrs(blk.span, ExprKind::Block(blk, opt_label), attrs))
2390    }
2391
2392    /// Parse a block which takes no attributes and has no label
2393    fn parse_simple_block(&mut self) -> PResult<'a, Box<Expr>> {
2394        let blk = self.parse_block()?;
2395        Ok(self.mk_expr(blk.span, ExprKind::Block(blk, None)))
2396    }
2397
2398    /// Parses a closure expression (e.g., `move |args| expr`).
2399    fn parse_expr_closure(&mut self) -> PResult<'a, Box<Expr>> {
2400        let lo = self.token.span;
2401
2402        let before = self.prev_token;
2403        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)) {
2404            let lo = self.token.span;
2405            let (bound_vars, _) = self.parse_higher_ranked_binder()?;
2406            let span = lo.to(self.prev_token.span);
2407
2408            self.psess.gated_spans.gate(sym::closure_lifetime_binder, span);
2409
2410            ClosureBinder::For { span, generic_params: bound_vars }
2411        } else {
2412            ClosureBinder::NotPresent
2413        };
2414
2415        let constness = self.parse_closure_constness();
2416
2417        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)) {
2418            self.psess.gated_spans.gate(sym::coroutines, self.prev_token.span);
2419            Movability::Static
2420        } else {
2421            Movability::Movable
2422        };
2423
2424        let coroutine_kind = if self.token_uninterpolated_span().at_least_rust_2018() {
2425            self.parse_coroutine_kind(Case::Sensitive)
2426        } else {
2427            None
2428        };
2429
2430        if let ClosureBinder::NotPresent = binder
2431            && coroutine_kind.is_some()
2432        {
2433            // coroutine closures and generators can have the same qualifiers, so we might end up
2434            // in here if there is a missing `|` but also no `{`. Adjust the expectations in that case.
2435            self.expected_token_types.insert(TokenType::OpenBrace);
2436        }
2437
2438        let capture_clause = self.parse_capture_clause()?;
2439        let (fn_decl, fn_arg_span) = self.parse_fn_block_decl()?;
2440        let decl_hi = self.prev_token.span;
2441        let mut body = match &fn_decl.output {
2442            // No return type.
2443            FnRetTy::Default(_) => {
2444                let restrictions =
2445                    self.restrictions - Restrictions::STMT_EXPR - Restrictions::ALLOW_LET;
2446                let prev = self.prev_token;
2447                let token = self.token;
2448                let attrs = self.parse_outer_attributes()?;
2449                match self.parse_expr_res(restrictions, attrs) {
2450                    Ok((expr, _)) => expr,
2451                    Err(err) => self.recover_closure_body(err, before, prev, token, lo, decl_hi)?,
2452                }
2453            }
2454            // Explicit return type (`->`) needs block `-> T { }`.
2455            FnRetTy::Ty(ty) => self.parse_closure_block_body(ty.span)?,
2456        };
2457
2458        match coroutine_kind {
2459            Some(CoroutineKind::Async { .. }) => {}
2460            Some(CoroutineKind::Gen { span, .. }) | Some(CoroutineKind::AsyncGen { span, .. }) => {
2461                // Feature-gate `gen ||` and `async gen ||` closures.
2462                // FIXME(gen_blocks): This perhaps should be a different gate.
2463                self.psess.gated_spans.gate(sym::gen_blocks, span);
2464            }
2465            None => {}
2466        }
2467
2468        if self.token == TokenKind::Semi
2469            && let Some(last) = self.token_cursor.stack.last()
2470            && let Some(TokenTree::Delimited(_, _, Delimiter::Parenthesis, _)) = last.curr()
2471            && self.may_recover()
2472        {
2473            // It is likely that the closure body is a block but where the
2474            // braces have been removed. We will recover and eat the next
2475            // statements later in the parsing process.
2476            body = self.mk_expr_err(
2477                body.span,
2478                self.dcx().span_delayed_bug(body.span, "recovered a closure body as a block"),
2479            );
2480        }
2481
2482        let body_span = body.span;
2483
2484        let closure = self.mk_expr(
2485            lo.to(body.span),
2486            ExprKind::Closure(Box::new(ast::Closure {
2487                binder,
2488                capture_clause,
2489                constness,
2490                coroutine_kind,
2491                movability,
2492                fn_decl,
2493                body,
2494                fn_decl_span: lo.to(decl_hi),
2495                fn_arg_span,
2496            })),
2497        );
2498
2499        // Disable recovery for closure body
2500        let spans =
2501            ClosureSpans { whole_closure: closure.span, closing_pipe: decl_hi, body: body_span };
2502        self.current_closure = Some(spans);
2503
2504        Ok(closure)
2505    }
2506
2507    /// If an explicit return type is given, require a block to appear (RFC 968).
2508    fn parse_closure_block_body(&mut self, ret_span: Span) -> PResult<'a, Box<Expr>> {
2509        if self.may_recover()
2510            && self.token.can_begin_expr()
2511            && self.token.kind != TokenKind::OpenBrace
2512            && !self.token.is_metavar_block()
2513        {
2514            let snapshot = self.create_snapshot_for_diagnostic();
2515            let restrictions =
2516                self.restrictions - Restrictions::STMT_EXPR - Restrictions::ALLOW_LET;
2517            let tok = self.token.clone();
2518            match self.parse_expr_res(restrictions, AttrWrapper::empty()) {
2519                Ok((expr, _)) => {
2520                    let descr = super::token_descr(&tok);
2521                    let mut diag = self
2522                        .dcx()
2523                        .struct_span_err(tok.span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected `{{`, found {0}", descr))
    })format!("expected `{{`, found {descr}"));
2524                    diag.span_label(
2525                        ret_span,
2526                        "explicit return type requires closure body to be enclosed in braces",
2527                    );
2528                    diag.multipart_suggestion(
2529                        "wrap the expression in curly braces",
2530                        ::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![
2531                            (expr.span.shrink_to_lo(), "{ ".to_string()),
2532                            (expr.span.shrink_to_hi(), " }".to_string()),
2533                        ],
2534                        Applicability::MachineApplicable,
2535                    );
2536                    diag.emit();
2537                    return Ok(expr);
2538                }
2539                Err(diag) => {
2540                    diag.cancel();
2541                    self.restore_snapshot(snapshot);
2542                }
2543            }
2544        }
2545
2546        let body_lo = self.token.span;
2547        self.parse_expr_block(None, body_lo, BlockCheckMode::Default)
2548    }
2549
2550    /// Parses an optional `move` or `use` prefix to a closure-like construct.
2551    fn parse_capture_clause(&mut self) -> PResult<'a, CaptureBy> {
2552        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)) {
2553            let move_kw_span = self.prev_token.span;
2554            // Check for `move async` and recover
2555            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)) {
2556                let move_async_span = self.token.span.with_lo(self.prev_token.span.data().lo);
2557                Err(self
2558                    .dcx()
2559                    .create_err(errors::AsyncMoveOrderIncorrect { span: move_async_span }))
2560            } else {
2561                Ok(CaptureBy::Value { move_kw: move_kw_span })
2562            }
2563        } 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)) {
2564            let use_kw_span = self.prev_token.span;
2565            self.psess.gated_spans.gate(sym::ergonomic_clones, use_kw_span);
2566            // Check for `use async` and recover
2567            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)) {
2568                let use_async_span = self.token.span.with_lo(self.prev_token.span.data().lo);
2569                Err(self.dcx().create_err(errors::AsyncUseOrderIncorrect { span: use_async_span }))
2570            } else {
2571                Ok(CaptureBy::Use { use_kw: use_kw_span })
2572            }
2573        } else {
2574            Ok(CaptureBy::Ref)
2575        }
2576    }
2577
2578    /// Parses the `|arg, arg|` header of a closure.
2579    fn parse_fn_block_decl(&mut self) -> PResult<'a, (Box<FnDecl>, Span)> {
2580        let arg_start = self.token.span.lo();
2581
2582        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)) {
2583            ThinVec::new()
2584        } else {
2585            self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Or,
    token_type: crate::parser::token_type::TokenType::Or,
}exp!(Or))?;
2586            let args = self
2587                .parse_seq_to_before_tokens(
2588                    &[crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Or,
    token_type: crate::parser::token_type::TokenType::Or,
}exp!(Or)],
2589                    &[&token::OrOr],
2590                    SeqSep::trailing_allowed(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma)),
2591                    |p| p.parse_fn_block_param(),
2592                )?
2593                .0;
2594            self.expect_or()?;
2595            args
2596        };
2597        let arg_span = self.prev_token.span.with_lo(arg_start);
2598        let output =
2599            self.parse_ret_ty(AllowPlus::Yes, RecoverQPath::Yes, RecoverReturnSign::Yes)?;
2600
2601        Ok((Box::new(FnDecl { inputs, output }), arg_span))
2602    }
2603
2604    /// Parses a parameter in a closure header (e.g., `|arg, arg|`).
2605    fn parse_fn_block_param(&mut self) -> PResult<'a, Param> {
2606        let lo = self.token.span;
2607        let attrs = self.parse_outer_attributes()?;
2608        self.collect_tokens(None, attrs, ForceCollect::No, |this, attrs| {
2609            let pat = Box::new(this.parse_pat_no_top_alt(Some(Expected::ParameterName), None)?);
2610            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)) {
2611                this.parse_ty()?
2612            } else {
2613                this.mk_ty(pat.span, TyKind::Infer)
2614            };
2615
2616            Ok((
2617                Param {
2618                    attrs,
2619                    ty,
2620                    pat,
2621                    span: lo.to(this.prev_token.span),
2622                    id: DUMMY_NODE_ID,
2623                    is_placeholder: false,
2624                },
2625                Trailing::from(this.token == token::Comma),
2626                UsePreAttrPos::No,
2627            ))
2628        })
2629    }
2630
2631    /// Parses an `if` expression (`if` token already eaten).
2632    fn parse_expr_if(&mut self) -> PResult<'a, Box<Expr>> {
2633        let lo = self.prev_token.span;
2634        // Scoping code checks the top level edition of the `if`; let's match it here.
2635        // The `CondChecker` also checks the edition of the `let` itself, just to make sure.
2636        let let_chains_policy = LetChainsPolicy::EditionDependent { current_edition: lo.edition() };
2637        let cond = self.parse_expr_cond(let_chains_policy)?;
2638        self.parse_if_after_cond(lo, cond)
2639    }
2640
2641    fn parse_if_after_cond(&mut self, lo: Span, mut cond: Box<Expr>) -> PResult<'a, Box<Expr>> {
2642        let cond_span = cond.span;
2643        // Tries to interpret `cond` as either a missing expression if it's a block,
2644        // or as an unfinished expression if it's a binop and the RHS is a block.
2645        // We could probably add more recoveries here too...
2646        let mut recover_block_from_condition = |this: &mut Self| {
2647            let block = match &mut cond.kind {
2648                ExprKind::Binary(Spanned { span: binop_span, .. }, _, right)
2649                    if let ExprKind::Block(_, None) = right.kind =>
2650                {
2651                    let guar = this.dcx().emit_err(errors::IfExpressionMissingThenBlock {
2652                        if_span: lo,
2653                        missing_then_block_sub:
2654                            errors::IfExpressionMissingThenBlockSub::UnfinishedCondition(
2655                                cond_span.shrink_to_lo().to(*binop_span),
2656                            ),
2657                        let_else_sub: None,
2658                    });
2659                    std::mem::replace(right, this.mk_expr_err(binop_span.shrink_to_hi(), guar))
2660                }
2661                ExprKind::Block(_, None) => {
2662                    let guar = this.dcx().emit_err(errors::IfExpressionMissingCondition {
2663                        if_span: lo.with_neighbor(cond.span).shrink_to_hi(),
2664                        block_span: self.psess.source_map().start_point(cond_span),
2665                    });
2666                    std::mem::replace(&mut cond, this.mk_expr_err(cond_span.shrink_to_hi(), guar))
2667                }
2668                _ => {
2669                    return None;
2670                }
2671            };
2672            if let ExprKind::Block(block, _) = &block.kind {
2673                Some(block.clone())
2674            } else {
2675                ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
2676            }
2677        };
2678        // Parse then block
2679        let thn = if self.token.is_keyword(kw::Else) {
2680            if let Some(block) = recover_block_from_condition(self) {
2681                block
2682            } else {
2683                let let_else_sub = #[allow(non_exhaustive_omitted_patterns)] match cond.kind {
    ExprKind::Let(..) => true,
    _ => false,
}matches!(cond.kind, ExprKind::Let(..))
2684                    .then(|| errors::IfExpressionLetSomeSub { if_span: lo.until(cond_span) });
2685
2686                let guar = self.dcx().emit_err(errors::IfExpressionMissingThenBlock {
2687                    if_span: lo,
2688                    missing_then_block_sub: errors::IfExpressionMissingThenBlockSub::AddThenBlock(
2689                        cond_span.shrink_to_hi(),
2690                    ),
2691                    let_else_sub,
2692                });
2693                self.mk_block_err(cond_span.shrink_to_hi(), guar)
2694            }
2695        } else {
2696            let attrs = self.parse_outer_attributes()?; // For recovery.
2697            let maybe_fatarrow = self.token;
2698            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)) {
2699                self.parse_block()?
2700            } else if let Some(block) = recover_block_from_condition(self) {
2701                block
2702            } else {
2703                self.error_on_extra_if(&cond)?;
2704                // Parse block, which will always fail, but we can add a nice note to the error
2705                self.parse_block().map_err(|mut err| {
2706                        if self.prev_token == token::Semi
2707                            && self.token == token::AndAnd
2708                            && let maybe_let = self.look_ahead(1, |t| t.clone())
2709                            && maybe_let.is_keyword(kw::Let)
2710                        {
2711                            err.span_suggestion(
2712                                self.prev_token.span,
2713                                "consider removing this semicolon to parse the `let` as part of the same chain",
2714                                "",
2715                                Applicability::MachineApplicable,
2716                            ).span_note(
2717                                self.token.span.to(maybe_let.span),
2718                                "you likely meant to continue parsing the let-chain starting here",
2719                            );
2720                        } else {
2721                            // Look for usages of '=>' where '>=' might be intended
2722                            if maybe_fatarrow == token::FatArrow {
2723                                err.span_suggestion(
2724                                    maybe_fatarrow.span,
2725                                    "you might have meant to write a \"greater than or equal to\" comparison",
2726                                    ">=",
2727                                    Applicability::MaybeIncorrect,
2728                                );
2729                            }
2730                            err.span_note(
2731                                cond_span,
2732                                "the `if` expression is missing a block after this condition",
2733                            );
2734                        }
2735                        err
2736                    })?
2737            };
2738            self.error_on_if_block_attrs(lo, false, block.span, attrs);
2739            block
2740        };
2741        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 };
2742        Ok(self.mk_expr(lo.to(self.prev_token.span), ExprKind::If(cond, thn, els)))
2743    }
2744
2745    /// Parses the condition of a `if` or `while` expression.
2746    ///
2747    /// The specified `edition` in `let_chains_policy` should be that of the whole `if` construct,
2748    /// i.e. the same span we use to later decide whether the drop behaviour should be that of
2749    /// edition `..=2021` or that of `2024..`.
2750    // Public to use it for custom `if` expressions in rustfmt forks like https://github.com/tucant/rustfmt
2751    pub fn parse_expr_cond(
2752        &mut self,
2753        let_chains_policy: LetChainsPolicy,
2754    ) -> PResult<'a, Box<Expr>> {
2755        let attrs = self.parse_outer_attributes()?;
2756        let (mut cond, _) =
2757            self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL | Restrictions::ALLOW_LET, attrs)?;
2758
2759        let mut checker = CondChecker::new(self, let_chains_policy);
2760        checker.visit_expr(&mut cond);
2761        Ok(if let Some(guar) = checker.found_incorrect_let_chain {
2762            self.mk_expr_err(cond.span, guar)
2763        } else {
2764            cond
2765        })
2766    }
2767
2768    /// Parses a `let $pat = $expr` pseudo-expression.
2769    fn parse_expr_let(&mut self, restrictions: Restrictions) -> PResult<'a, Box<Expr>> {
2770        let recovered: Recovered = if !restrictions.contains(Restrictions::ALLOW_LET) {
2771            let err = errors::ExpectedExpressionFoundLet {
2772                span: self.token.span,
2773                reason: errors::ForbiddenLetReason::OtherForbidden,
2774                missing_let: None,
2775                comparison: None,
2776            };
2777            if self.prev_token == token::Or {
2778                // This was part of a closure, the that part of the parser recover.
2779                return Err(self.dcx().create_err(err));
2780            } else {
2781                Recovered::Yes(self.dcx().emit_err(err))
2782            }
2783        } else {
2784            Recovered::No
2785        };
2786        self.bump(); // Eat `let` token
2787        let lo = self.prev_token.span;
2788        let pat = self.parse_pat_no_top_guard(
2789            None,
2790            RecoverComma::Yes,
2791            RecoverColon::Yes,
2792            CommaRecoveryMode::LikelyTuple,
2793        )?;
2794        if self.token == token::EqEq {
2795            self.dcx().emit_err(errors::ExpectedEqForLetExpr {
2796                span: self.token.span,
2797                sugg_span: self.token.span,
2798            });
2799            self.bump();
2800        } else {
2801            self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Eq,
    token_type: crate::parser::token_type::TokenType::Eq,
}exp!(Eq))?;
2802        }
2803        let attrs = self.parse_outer_attributes()?;
2804        let (expr, _) =
2805            self.parse_expr_assoc_with(Bound::Excluded(prec_let_scrutinee_needs_par()), attrs)?;
2806        let span = lo.to(expr.span);
2807        Ok(self.mk_expr(span, ExprKind::Let(Box::new(pat), expr, span, recovered)))
2808    }
2809
2810    /// Parses an `else { ... }` expression (`else` token already eaten).
2811    fn parse_expr_else(&mut self) -> PResult<'a, Box<Expr>> {
2812        let else_span = self.prev_token.span; // `else`
2813        let attrs = self.parse_outer_attributes()?; // For recovery.
2814        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)) {
2815            ensure_sufficient_stack(|| self.parse_expr_if())?
2816        } else if self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenBrace,
    token_type: crate::parser::token_type::TokenType::OpenBrace,
}exp!(OpenBrace)) {
2817            self.parse_simple_block()?
2818        } else {
2819            let snapshot = self.create_snapshot_for_diagnostic();
2820            let first_tok = super::token_descr(&self.token);
2821            let first_tok_span = self.token.span;
2822            match self.parse_expr() {
2823                Ok(cond)
2824                // Try to guess the difference between a "condition-like" vs
2825                // "statement-like" expression.
2826                //
2827                // We are seeing the following code, in which $cond is neither
2828                // ExprKind::Block nor ExprKind::If (the 2 cases wherein this
2829                // would be valid syntax).
2830                //
2831                //     if ... {
2832                //     } else $cond
2833                //
2834                // If $cond is "condition-like" such as ExprKind::Binary, we
2835                // want to suggest inserting `if`.
2836                //
2837                //     if ... {
2838                //     } else if a == b {
2839                //            ^^
2840                //     }
2841                //
2842                // We account for macro calls that were meant as conditions as well.
2843                //
2844                //     if ... {
2845                //     } else if macro! { foo bar } {
2846                //            ^^
2847                //     }
2848                //
2849                // If $cond is "statement-like" such as ExprKind::While then we
2850                // want to suggest wrapping in braces.
2851                //
2852                //     if ... {
2853                //     } else {
2854                //            ^
2855                //         while true {}
2856                //     }
2857                //     ^
2858                    if self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenBrace,
    token_type: crate::parser::token_type::TokenType::OpenBrace,
}exp!(OpenBrace))
2859                        && (classify::expr_requires_semi_to_be_stmt(&cond)
2860                            || #[allow(non_exhaustive_omitted_patterns)] match cond.kind {
    ExprKind::MacCall(..) => true,
    _ => false,
}matches!(cond.kind, ExprKind::MacCall(..)))
2861                    =>
2862                {
2863                    self.dcx().emit_err(errors::ExpectedElseBlock {
2864                        first_tok_span,
2865                        first_tok,
2866                        else_span,
2867                        condition_start: cond.span.shrink_to_lo(),
2868                    });
2869                    self.parse_if_after_cond(cond.span.shrink_to_lo(), cond)?
2870                }
2871                Err(e) => {
2872                    e.cancel();
2873                    self.restore_snapshot(snapshot);
2874                    self.parse_simple_block()?
2875                },
2876                Ok(_) => {
2877                    self.restore_snapshot(snapshot);
2878                    self.parse_simple_block()?
2879                },
2880            }
2881        };
2882        self.error_on_if_block_attrs(else_span, true, expr.span, attrs);
2883        Ok(expr)
2884    }
2885
2886    fn error_on_if_block_attrs(
2887        &self,
2888        ctx_span: Span,
2889        is_ctx_else: bool,
2890        branch_span: Span,
2891        attrs: AttrWrapper,
2892    ) {
2893        if !attrs.is_empty()
2894            && let [x0 @ xn] | [x0, .., xn] = &*attrs.take_for_recovery(self.psess)
2895        {
2896            let attributes = x0.span.until(branch_span);
2897            let last = xn.span;
2898            let ctx = if is_ctx_else { "else" } else { "if" };
2899            self.dcx().emit_err(errors::OuterAttributeNotAllowedOnIfElse {
2900                last,
2901                branch_span,
2902                ctx_span,
2903                ctx: ctx.to_string(),
2904                attributes,
2905            });
2906        }
2907    }
2908
2909    fn error_on_extra_if(&mut self, cond: &Box<Expr>) -> PResult<'a, ()> {
2910        if let ExprKind::Binary(Spanned { span: binop_span, node: binop }, _, right) = &cond.kind
2911            && let BinOpKind::And = binop
2912            && let ExprKind::If(cond, ..) = &right.kind
2913        {
2914            Err(self.dcx().create_err(errors::UnexpectedIfWithIf(
2915                binop_span.shrink_to_hi().to(cond.span.shrink_to_lo()),
2916            )))
2917        } else {
2918            Ok(())
2919        }
2920    }
2921
2922    // Public to use it for custom `for` expressions in rustfmt forks like https://github.com/tucant/rustfmt
2923    pub fn parse_for_head(&mut self) -> PResult<'a, (Pat, Box<Expr>)> {
2924        let begin_paren = if self.token == token::OpenParen {
2925            // Record whether we are about to parse `for (`.
2926            // This is used below for recovery in case of `for ( $stuff ) $block`
2927            // in which case we will suggest `for $stuff $block`.
2928            let start_span = self.token.span;
2929            let left = self.prev_token.span.between(self.look_ahead(1, |t| t.span));
2930            Some((start_span, left))
2931        } else {
2932            None
2933        };
2934        // Try to parse the pattern `for ($PAT) in $EXPR`.
2935        let pat = match (
2936            self.parse_pat_allow_top_guard(
2937                None,
2938                RecoverComma::Yes,
2939                RecoverColon::Yes,
2940                CommaRecoveryMode::LikelyTuple,
2941            ),
2942            begin_paren,
2943        ) {
2944            (Ok(pat), _) => pat, // Happy path.
2945            (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)) => {
2946                // We know for sure we have seen `for ($SOMETHING in`. In the happy path this would
2947                // happen right before the return of this method.
2948                let attrs = self.parse_outer_attributes()?;
2949                let (expr, _) = match self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, attrs) {
2950                    Ok(expr) => expr,
2951                    Err(expr_err) => {
2952                        // We don't know what followed the `in`, so cancel and bubble up the
2953                        // original error.
2954                        expr_err.cancel();
2955                        return Err(err);
2956                    }
2957                };
2958                return if self.token == token::CloseParen {
2959                    // We know for sure we have seen `for ($SOMETHING in $EXPR)`, so we recover the
2960                    // parser state and emit a targeted suggestion.
2961                    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];
2962                    let right = self.prev_token.span.between(self.look_ahead(1, |t| t.span));
2963                    self.bump(); // )
2964                    err.cancel();
2965                    self.dcx().emit_err(errors::ParenthesesInForHead {
2966                        span,
2967                        // With e.g. `for (x) in y)` this would replace `(x) in y)`
2968                        // with `x) in y)` which is syntactically invalid.
2969                        // However, this is prevented before we get here.
2970                        sugg: errors::ParenthesesInForHeadSugg { left, right },
2971                    });
2972                    Ok((self.mk_pat(start_span.to(right), ast::PatKind::Wild), expr))
2973                } else {
2974                    Err(err) // Some other error, bubble up.
2975                };
2976            }
2977            (Err(err), _) => return Err(err), // Some other error, bubble up.
2978        };
2979        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)) {
2980            self.error_missing_in_for_loop();
2981        }
2982        self.check_for_for_in_in_typo(self.prev_token.span);
2983        let attrs = self.parse_outer_attributes()?;
2984        let (expr, _) = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, attrs)?;
2985        Ok((pat, expr))
2986    }
2987
2988    /// Parses `for await? <src_pat> in <src_expr> <src_loop_block>` (`for` token already eaten).
2989    fn parse_expr_for(&mut self, opt_label: Option<Label>, lo: Span) -> PResult<'a, Box<Expr>> {
2990        let is_await =
2991            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));
2992
2993        if is_await {
2994            self.psess.gated_spans.gate(sym::async_for_loop, self.prev_token.span);
2995        }
2996
2997        let kind = if is_await { ForLoopKind::ForAwait } else { ForLoopKind::For };
2998
2999        let (pat, expr) = self.parse_for_head()?;
3000        let pat = Box::new(pat);
3001        // Recover from missing expression in `for` loop
3002        if #[allow(non_exhaustive_omitted_patterns)] match expr.kind {
    ExprKind::Block(..) => true,
    _ => false,
}matches!(expr.kind, ExprKind::Block(..))
3003            && self.token.kind != token::OpenBrace
3004            && self.may_recover()
3005        {
3006            let guar = self
3007                .dcx()
3008                .emit_err(errors::MissingExpressionInForLoop { span: expr.span.shrink_to_lo() });
3009            let err_expr = self.mk_expr(expr.span, ExprKind::Err(guar));
3010            let block = self.mk_block(::thin_vec::ThinVec::new()thin_vec![], BlockCheckMode::Default, self.prev_token.span);
3011            return Ok(self.mk_expr(
3012                lo.to(self.prev_token.span),
3013                ExprKind::ForLoop { pat, iter: err_expr, body: block, label: opt_label, kind },
3014            ));
3015        }
3016
3017        let (attrs, loop_block) = self.parse_inner_attrs_and_block(
3018            // Only suggest moving erroneous block label to the loop header
3019            // if there is not already a label there
3020            opt_label.is_none().then_some(lo),
3021        )?;
3022
3023        let kind = ExprKind::ForLoop { pat, iter: expr, body: loop_block, label: opt_label, kind };
3024
3025        self.recover_loop_else("for", lo)?;
3026
3027        Ok(self.mk_expr_with_attrs(lo.to(self.prev_token.span), kind, attrs))
3028    }
3029
3030    /// Recovers from an `else` clause after a loop (`for...else`, `while...else`)
3031    fn recover_loop_else(&mut self, loop_kind: &'static str, loop_kw: Span) -> PResult<'a, ()> {
3032        if self.token.is_keyword(kw::Else) && self.may_recover() {
3033            let else_span = self.token.span;
3034            self.bump();
3035            let else_clause = self.parse_expr_else()?;
3036            self.dcx().emit_err(errors::LoopElseNotSupported {
3037                span: else_span.to(else_clause.span),
3038                loop_kind,
3039                loop_kw,
3040            });
3041        }
3042        Ok(())
3043    }
3044
3045    fn error_missing_in_for_loop(&mut self) {
3046        let (span, sub): (_, fn(_) -> _) = if self.token.is_ident_named(sym::of) {
3047            // Possibly using JS syntax (#75311).
3048            let span = self.token.span;
3049            self.bump();
3050            (span, errors::MissingInInForLoopSub::InNotOf)
3051        } else if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Eq,
    token_type: crate::parser::token_type::TokenType::Eq,
}exp!(Eq)) {
3052            (self.prev_token.span, errors::MissingInInForLoopSub::InNotEq)
3053        } else {
3054            (self.prev_token.span.between(self.token.span), errors::MissingInInForLoopSub::AddIn)
3055        };
3056
3057        self.dcx().emit_err(errors::MissingInInForLoop { span, sub: sub(span) });
3058    }
3059
3060    /// Parses a `while` or `while let` expression (`while` token already eaten).
3061    fn parse_expr_while(&mut self, opt_label: Option<Label>, lo: Span) -> PResult<'a, Box<Expr>> {
3062        let policy = LetChainsPolicy::EditionDependent { current_edition: lo.edition() };
3063        let cond = self.parse_expr_cond(policy).map_err(|mut err| {
3064            err.span_label(lo, "while parsing the condition of this `while` expression");
3065            err
3066        })?;
3067        let (attrs, body) = self
3068            .parse_inner_attrs_and_block(
3069                // Only suggest moving erroneous block label to the loop header
3070                // if there is not already a label there
3071                opt_label.is_none().then_some(lo),
3072            )
3073            .map_err(|mut err| {
3074                err.span_label(lo, "while parsing the body of this `while` expression");
3075                err.span_label(cond.span, "this `while` condition successfully parsed");
3076                err
3077            })?;
3078
3079        self.recover_loop_else("while", lo)?;
3080
3081        Ok(self.mk_expr_with_attrs(
3082            lo.to(self.prev_token.span),
3083            ExprKind::While(cond, body, opt_label),
3084            attrs,
3085        ))
3086    }
3087
3088    /// Parses `loop { ... }` (`loop` token already eaten).
3089    fn parse_expr_loop(&mut self, opt_label: Option<Label>, lo: Span) -> PResult<'a, Box<Expr>> {
3090        let loop_span = self.prev_token.span;
3091        let (attrs, body) = self.parse_inner_attrs_and_block(
3092            // Only suggest moving erroneous block label to the loop header
3093            // if there is not already a label there
3094            opt_label.is_none().then_some(lo),
3095        )?;
3096        self.recover_loop_else("loop", lo)?;
3097        Ok(self.mk_expr_with_attrs(
3098            lo.to(self.prev_token.span),
3099            ExprKind::Loop(body, opt_label, loop_span),
3100            attrs,
3101        ))
3102    }
3103
3104    pub(crate) fn eat_label(&mut self) -> Option<Label> {
3105        if let Some((ident, is_raw)) = self.token.lifetime() {
3106            // Disallow `'fn`, but with a better error message than `expect_lifetime`.
3107            if is_raw == IdentIsRaw::No && ident.without_first_quote().is_reserved() {
3108                self.dcx().emit_err(errors::KeywordLabel { span: ident.span });
3109            }
3110
3111            self.bump();
3112            Some(Label { ident })
3113        } else {
3114            None
3115        }
3116    }
3117
3118    /// Parses a `match ... { ... }` expression (`match` token already eaten).
3119    fn parse_expr_match(&mut self) -> PResult<'a, Box<Expr>> {
3120        let match_span = self.prev_token.span;
3121        let attrs = self.parse_outer_attributes()?;
3122        let (scrutinee, _) = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, attrs)?;
3123
3124        self.parse_match_block(match_span, match_span, scrutinee, MatchKind::Prefix)
3125    }
3126
3127    /// Parses the block of a `match expr { ... }` or a `expr.match { ... }`
3128    /// expression. This is after the match token and scrutinee are eaten
3129    fn parse_match_block(
3130        &mut self,
3131        lo: Span,
3132        match_span: Span,
3133        scrutinee: Box<Expr>,
3134        match_kind: MatchKind,
3135    ) -> PResult<'a, Box<Expr>> {
3136        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)) {
3137            if self.token == token::Semi {
3138                e.span_suggestion_short(
3139                    match_span,
3140                    "try removing this `match`",
3141                    "",
3142                    Applicability::MaybeIncorrect, // speculative
3143                );
3144            }
3145            if self.maybe_recover_unexpected_block_label(None) {
3146                e.cancel();
3147                self.bump();
3148            } else {
3149                return Err(e);
3150            }
3151        }
3152        let attrs = self.parse_inner_attributes()?;
3153
3154        let mut arms = ThinVec::new();
3155        while self.token != token::CloseBrace {
3156            match self.parse_arm() {
3157                Ok(arm) => arms.push(arm),
3158                Err(e) => {
3159                    // Recover by skipping to the end of the block.
3160                    let guar = e.emit();
3161                    self.recover_stmt();
3162                    let span = lo.to(self.token.span);
3163                    if self.token == token::CloseBrace {
3164                        self.bump();
3165                    }
3166                    // Always push at least one arm to make the match non-empty
3167                    arms.push(Arm {
3168                        attrs: Default::default(),
3169                        pat: Box::new(self.mk_pat(span, ast::PatKind::Err(guar))),
3170                        guard: None,
3171                        body: Some(self.mk_expr_err(span, guar)),
3172                        span,
3173                        id: DUMMY_NODE_ID,
3174                        is_placeholder: false,
3175                    });
3176                    return Ok(self.mk_expr_with_attrs(
3177                        span,
3178                        ExprKind::Match(scrutinee, arms, match_kind),
3179                        attrs,
3180                    ));
3181                }
3182            }
3183        }
3184        let hi = self.token.span;
3185        self.bump();
3186        Ok(self.mk_expr_with_attrs(lo.to(hi), ExprKind::Match(scrutinee, arms, match_kind), attrs))
3187    }
3188
3189    /// Attempt to recover from match arm body with statements and no surrounding braces.
3190    fn parse_arm_body_missing_braces(
3191        &mut self,
3192        first_expr: &Box<Expr>,
3193        arrow_span: Span,
3194    ) -> Option<(Span, ErrorGuaranteed)> {
3195        if self.token != token::Semi {
3196            return None;
3197        }
3198        let start_snapshot = self.create_snapshot_for_diagnostic();
3199        let semi_sp = self.token.span;
3200        self.bump(); // `;`
3201        let mut stmts =
3202            ::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()))];
3203        let err = |this: &Parser<'_>, stmts: Vec<ast::Stmt>| {
3204            let span = stmts[0].span.to(stmts[stmts.len() - 1].span);
3205
3206            let guar = this.dcx().emit_err(errors::MatchArmBodyWithoutBraces {
3207                statements: span,
3208                arrow: arrow_span,
3209                num_statements: stmts.len(),
3210                sub: if stmts.len() > 1 {
3211                    errors::MatchArmBodyWithoutBracesSugg::AddBraces {
3212                        left: span.shrink_to_lo(),
3213                        right: span.shrink_to_hi(),
3214                        num_statements: stmts.len(),
3215                    }
3216                } else {
3217                    errors::MatchArmBodyWithoutBracesSugg::UseComma { semicolon: semi_sp }
3218                },
3219            });
3220            (span, guar)
3221        };
3222        // We might have either a `,` -> `;` typo, or a block without braces. We need
3223        // a more subtle parsing strategy.
3224        loop {
3225            if self.token == token::CloseBrace {
3226                // We have reached the closing brace of the `match` expression.
3227                return Some(err(self, stmts));
3228            }
3229            if self.token == token::Comma {
3230                self.restore_snapshot(start_snapshot);
3231                return None;
3232            }
3233            let pre_pat_snapshot = self.create_snapshot_for_diagnostic();
3234            match self.parse_pat_no_top_alt(None, None) {
3235                Ok(_pat) => {
3236                    if self.token == token::FatArrow {
3237                        // Reached arm end.
3238                        self.restore_snapshot(pre_pat_snapshot);
3239                        return Some(err(self, stmts));
3240                    }
3241                }
3242                Err(err) => {
3243                    err.cancel();
3244                }
3245            }
3246
3247            self.restore_snapshot(pre_pat_snapshot);
3248            match self.parse_stmt_without_recovery(true, ForceCollect::No, false) {
3249                // Consume statements for as long as possible.
3250                Ok(Some(stmt)) => {
3251                    stmts.push(stmt);
3252                }
3253                Ok(None) => {
3254                    self.restore_snapshot(start_snapshot);
3255                    break;
3256                }
3257                // We couldn't parse either yet another statement missing it's
3258                // enclosing block nor the next arm's pattern or closing brace.
3259                Err(stmt_err) => {
3260                    stmt_err.cancel();
3261                    self.restore_snapshot(start_snapshot);
3262                    break;
3263                }
3264            }
3265        }
3266        None
3267    }
3268
3269    pub(super) fn parse_arm(&mut self) -> PResult<'a, Arm> {
3270        let attrs = self.parse_outer_attributes()?;
3271        self.collect_tokens(None, attrs, ForceCollect::No, |this, attrs| {
3272            let lo = this.token.span;
3273            let (pat, guard) = this.parse_match_arm_pat_and_guard()?;
3274            let pat = Box::new(pat);
3275
3276            let span_before_body = this.prev_token.span;
3277            let arm_body;
3278            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));
3279            let is_almost_fat_arrow =
3280                TokenKind::FatArrow.similar_tokens().contains(&this.token.kind);
3281
3282            // this avoids the compiler saying that a `,` or `}` was expected even though
3283            // the pattern isn't a never pattern (and thus an arm body is required)
3284            let armless = (!is_fat_arrow && !is_almost_fat_arrow && pat.could_be_never_pattern())
3285                || #[allow(non_exhaustive_omitted_patterns)] match this.token.kind {
    token::Comma | token::CloseBrace => true,
    _ => false,
}matches!(this.token.kind, token::Comma | token::CloseBrace);
3286
3287            let mut result = if armless {
3288                // A pattern without a body, allowed for never patterns.
3289                arm_body = None;
3290                let span = lo.to(this.prev_token.span);
3291                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| {
3292                    // Don't gate twice
3293                    if !pat.contains_never_pattern() {
3294                        this.psess.gated_spans.gate(sym::never_patterns, span);
3295                    }
3296                    x
3297                })
3298            } else {
3299                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)) {
3300                    // We might have a `=>` -> `=` or `->` typo (issue #89396).
3301                    if is_almost_fat_arrow {
3302                        err.span_suggestion(
3303                            this.token.span,
3304                            "use a fat arrow to start a match arm",
3305                            "=>",
3306                            Applicability::MachineApplicable,
3307                        );
3308                        if #[allow(non_exhaustive_omitted_patterns)] match (&this.prev_token.kind,
        &this.token.kind) {
    (token::DotDotEq, token::Gt) => true,
    _ => false,
}matches!(
3309                            (&this.prev_token.kind, &this.token.kind),
3310                            (token::DotDotEq, token::Gt)
3311                        ) {
3312                            // `error_inclusive_range_match_arrow` handles cases like `0..=> {}`,
3313                            // so we suppress the error here
3314                            err.delay_as_bug();
3315                        } else {
3316                            err.emit();
3317                        }
3318                        this.bump();
3319                    } else {
3320                        return Err(err);
3321                    }
3322                }
3323                let arrow_span = this.prev_token.span;
3324                let arm_start_span = this.token.span;
3325
3326                let attrs = this.parse_outer_attributes()?;
3327                let (expr, _) =
3328                    this.parse_expr_res(Restrictions::STMT_EXPR, attrs).map_err(|mut err| {
3329                        err.span_label(arrow_span, "while parsing the `match` arm starting here");
3330                        err
3331                    })?;
3332
3333                let require_comma =
3334                    !classify::expr_is_complete(&expr) && this.token != token::CloseBrace;
3335
3336                if !require_comma {
3337                    arm_body = Some(expr);
3338                    // Eat a comma if it exists, though.
3339                    let _ = this.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma));
3340                    Ok(Recovered::No)
3341                } else if let Some((span, guar)) =
3342                    this.parse_arm_body_missing_braces(&expr, arrow_span)
3343                {
3344                    let body = this.mk_expr_err(span, guar);
3345                    arm_body = Some(body);
3346                    Ok(Recovered::Yes(guar))
3347                } else {
3348                    let expr_span = expr.span;
3349                    arm_body = Some(expr);
3350                    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| {
3351                        if this.token == token::FatArrow {
3352                            let sm = this.psess.source_map();
3353                            if let Ok(expr_lines) = sm.span_to_lines(expr_span)
3354                                && let Ok(arm_start_lines) = sm.span_to_lines(arm_start_span)
3355                                && expr_lines.lines.len() == 2
3356                            {
3357                                if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col {
3358                                    // We check whether there's any trailing code in the parse span,
3359                                    // if there isn't, we very likely have the following:
3360                                    //
3361                                    // X |     &Y => "y"
3362                                    //   |        --    - missing comma
3363                                    //   |        |
3364                                    //   |        arrow_span
3365                                    // X |     &X => "x"
3366                                    //   |      - ^^ self.token.span
3367                                    //   |      |
3368                                    //   |      parsed until here as `"y" & X`
3369                                    err.span_suggestion_short(
3370                                        arm_start_span.shrink_to_hi(),
3371                                        "missing a comma here to end this `match` arm",
3372                                        ",",
3373                                        Applicability::MachineApplicable,
3374                                    );
3375                                } else if arm_start_lines.lines[0].end_col + rustc_span::CharPos(1)
3376                                    == expr_lines.lines[0].end_col
3377                                {
3378                                    // similar to the above, but we may typo a `.` or `/` at the end of the line
3379                                    let comma_span = arm_start_span
3380                                        .shrink_to_hi()
3381                                        .with_hi(arm_start_span.hi() + rustc_span::BytePos(1));
3382                                    if let Ok(res) = sm.span_to_snippet(comma_span)
3383                                        && (res == "." || res == "/")
3384                                    {
3385                                        err.span_suggestion_short(
3386                                            comma_span,
3387                                            "you might have meant to write a `,` to end this `match` arm",
3388                                            ",",
3389                                            Applicability::MachineApplicable,
3390                                        );
3391                                    }
3392                                }
3393                            }
3394                        } else {
3395                            err.span_label(
3396                                arrow_span,
3397                                "while parsing the `match` arm starting here",
3398                            );
3399                        }
3400                        err
3401                    })
3402                }
3403            };
3404
3405            let hi_span = arm_body.as_ref().map_or(span_before_body, |body| body.span);
3406            let arm_span = lo.to(hi_span);
3407
3408            // We want to recover:
3409            // X |     Some(_) => foo()
3410            //   |                     - missing comma
3411            // X |     None => "x"
3412            //   |     ^^^^ self.token.span
3413            // as well as:
3414            // X |     Some(!)
3415            //   |            - missing comma
3416            // X |     None => "x"
3417            //   |     ^^^^ self.token.span
3418            // But we musn't recover
3419            // X |     pat[0] => {}
3420            //   |        ^ self.token.span
3421            let recover_missing_comma = arm_body.is_some() || pat.could_be_never_pattern();
3422            if recover_missing_comma {
3423                result = result.or_else(|err| {
3424                    // FIXME(compiler-errors): We could also recover `; PAT =>` here
3425
3426                    // Try to parse a following `PAT =>`, if successful
3427                    // then we should recover.
3428                    let mut snapshot = this.create_snapshot_for_diagnostic();
3429                    let pattern_follows = snapshot
3430                        .parse_pat_no_top_guard(
3431                            None,
3432                            RecoverComma::Yes,
3433                            RecoverColon::Yes,
3434                            CommaRecoveryMode::EitherTupleOrPipe,
3435                        )
3436                        .map_err(|err| err.cancel())
3437                        .is_ok();
3438                    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)) {
3439                        err.cancel();
3440                        let guar = this.dcx().emit_err(errors::MissingCommaAfterMatchArm {
3441                            span: arm_span.shrink_to_hi(),
3442                        });
3443                        return Ok(Recovered::Yes(guar));
3444                    }
3445                    Err(err)
3446                });
3447            }
3448            result?;
3449
3450            Ok((
3451                ast::Arm {
3452                    attrs,
3453                    pat,
3454                    guard,
3455                    body: arm_body,
3456                    span: arm_span,
3457                    id: DUMMY_NODE_ID,
3458                    is_placeholder: false,
3459                },
3460                Trailing::No,
3461                UsePreAttrPos::No,
3462            ))
3463        })
3464    }
3465
3466    pub(crate) fn eat_metavar_guard(&mut self) -> Option<Box<Guard>> {
3467        self.eat_metavar_seq_with_matcher(
3468            |mv_kind| #[allow(non_exhaustive_omitted_patterns)] match mv_kind {
    MetaVarKind::Guard => true,
    _ => false,
}matches!(mv_kind, MetaVarKind::Guard),
3469            |this| this.parse_match_arm_guard(),
3470        )
3471        .flatten()
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: 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}