rustc_parse/parser/
expr.rs

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