expr.rs - source (original) (raw)

rustc_parse/parser/

expr.rs

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