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