Skip to main content

rustc_parse/parser/
pat.rs

1use std::ops::Bound;
2
3use rustc_ast::mut_visit::{self, MutVisitor};
4use rustc_ast::token::NtPatKind::*;
5use rustc_ast::token::{self, IdentKind, MetaVarKind, Token};
6use rustc_ast::util::parser::ExprPrecedence;
7use rustc_ast::visit::{self, Visitor};
8use rustc_ast::{
9    self as ast, Arm, AttrVec, BindingMode, ByRef, Expr, ExprKind, Guard, LocalKind, MacCall,
10    Mutability, Pat, PatField, PatFieldsRest, PatKind, Path, QSelf, RangeEnd, RangeSyntax, Stmt,
11    StmtKind, Ty,
12};
13use rustc_ast_pretty::pprust;
14use rustc_errors::{Applicability, Diag, DiagArgValue, PResult, StashKey};
15use rustc_span::{BytePos, ErrorGuaranteed, Ident, Span, Spanned, kw, respan, sym};
16use thin_vec::{ThinVec, thin_vec};
17
18use super::{ForceCollect, Parser, PathStyle, Restrictions, Trailing, UsePreAttrPos};
19use crate::diagnostics::{
20    self, AmbiguousRangePattern, AtDotDotInStructPattern, AtInStructPattern,
21    DotDotDotForRemainingFields, DotDotDotRangeToPatternNotAllowed, DotDotDotRestPattern,
22    EnumPatternInsteadOfIdentifier, ExpectedBindingLeftOfAt, ExpectedCommaAfterPatternField,
23    ExprParenthesesNeeded, GenericArgsInPatRequireTurbofishSyntax, InclusiveRangeExtraEquals,
24    InclusiveRangeMatchArrow, InclusiveRangeNoEnd, InvalidMutInPattern, ParenRangeSuggestion,
25    PatternOnWrongSideOfAt, RemoveLet, RepeatedMutInPattern, SwitchRefBoxOrder,
26    TopLevelOrPatternNotAllowed, TopLevelOrPatternNotAllowedSugg, TrailingVertNotAllowed,
27    TrailingVertSuggestion, UnexpectedExpressionInPattern, UnexpectedExpressionInPatternSugg,
28    UnexpectedLifetimeInPattern, UnexpectedParenInRangePat, UnexpectedParenInRangePatSugg,
29    UnexpectedVertVertBeforeFunctionParam, UnexpectedVertVertInPattern, WrapInParens,
30};
31use crate::parser::expr::{DestructuredFloat, could_be_unclosed_char_literal};
32use crate::{exp, maybe_recover_from_interpolated_ty_qpath};
33
34#[derive(#[automatically_derived]impl ::core::marker::StructuralPartialEq for Expected
    {
}
#[automatically_derived]impl ::core::cmp::PartialEq for Expected {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq, #[automatically_derived]impl ::core::marker::Copy for Expected { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for Expected {
}
#[automatically_derived]impl ::core::clone::Clone for Expected {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}Clone)]
35pub enum Expected {
36    ParameterName,
37    ArgumentName,
38    Identifier,
39    BindingPattern,
40}
41
42impl Expected {
43    // FIXME(#100717): migrate users of this to proper localization
44    fn to_string_or_fallback(expected: Option<Expected>) -> &'static str {
45        match expected {
46            Some(Expected::ParameterName) => "parameter name",
47            Some(Expected::ArgumentName) => "argument name",
48            Some(Expected::Identifier) => "identifier",
49            Some(Expected::BindingPattern) => "binding pattern",
50            None => "pattern",
51        }
52    }
53}
54
55const WHILE_PARSING_OR_MSG: &str = "while parsing this or-pattern starting here";
56
57/// Whether or not to recover a `,` when parsing or-patterns.
58#[derive(#[automatically_derived]impl ::core::marker::StructuralPartialEq for
    RecoverComma {
}
#[automatically_derived]impl ::core::cmp::PartialEq for RecoverComma {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq, #[automatically_derived]impl ::core::marker::Copy for RecoverComma { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for RecoverComma {
}
#[automatically_derived]impl ::core::clone::Clone for RecoverComma {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}Clone)]
59pub enum RecoverComma {
60    Yes,
61    No,
62}
63
64/// Whether or not to recover a `:` when parsing patterns that were meant to be paths.
65#[derive(#[automatically_derived]impl ::core::marker::StructuralPartialEq for
    RecoverColon {
}
#[automatically_derived]impl ::core::cmp::PartialEq for RecoverColon {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq, #[automatically_derived]impl ::core::marker::Copy for RecoverColon { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for RecoverColon {
}
#[automatically_derived]impl ::core::clone::Clone for RecoverColon {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}Clone)]
66pub enum RecoverColon {
67    Yes,
68    No,
69}
70
71/// Whether or not to recover a `a, b` when parsing patterns as `(a, b)` or that *and* `a | b`.
72#[derive(#[automatically_derived]impl ::core::marker::StructuralPartialEq for
    CommaRecoveryMode {
}
#[automatically_derived]impl ::core::cmp::PartialEq for CommaRecoveryMode {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq, #[automatically_derived]impl ::core::marker::Copy for CommaRecoveryMode { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for CommaRecoveryMode {
}
#[automatically_derived]impl ::core::clone::Clone for CommaRecoveryMode {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}Clone)]
73pub enum CommaRecoveryMode {
74    LikelyTuple,
75    EitherTupleOrPipe,
76}
77
78/// The result of `eat_or_separator`. We want to distinguish which case we are in to avoid
79/// emitting duplicate diagnostics.
80#[derive(#[automatically_derived]impl ::core::fmt::Debug for EatOrResult {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                EatOrResult::TrailingVert => "TrailingVert",
                EatOrResult::AteOr => "AteOr",
                EatOrResult::None => "None",
            })
    }
}Debug, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for EatOrResult {
}
#[automatically_derived]impl ::core::clone::Clone for EatOrResult {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for EatOrResult { }Copy)]
81enum EatOrResult {
82    /// We recovered from a trailing vert.
83    TrailingVert,
84    /// We ate an `|` (or `||` and recovered).
85    AteOr,
86    /// We did not eat anything (i.e. the current token is not `|` or `||`).
87    None,
88}
89
90/// The syntax location of a given pattern. Used for diagnostics.
91#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for PatternLocation {
}
#[automatically_derived]impl ::core::clone::Clone for PatternLocation {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for PatternLocation { }Copy)]
92pub enum PatternLocation {
93    LetBinding,
94    FunctionParameter,
95}
96
97impl<'a> Parser<'a> {
98    /// Parses a pattern.
99    ///
100    /// Corresponds to `Pattern` in RFC 3637 and admits guard patterns at the top level.
101    /// Used when parsing patterns in all cases where neither `PatternNoTopGuard` nor
102    /// `PatternNoTopAlt` (see below) are used.
103    pub fn parse_pat_allow_top_guard(
104        &mut self,
105        expected: Option<Expected>,
106        rc: RecoverComma,
107        ra: RecoverColon,
108        rt: CommaRecoveryMode,
109    ) -> PResult<'a, Pat> {
110        let pat = self.parse_pat_no_top_guard(expected, rc, ra, rt)?;
111
112        if self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::If,
    token_type: crate::parser::token_type::TokenType::KwIf,
}exp!(If)) {
113            let guard = if let Some(guard) = self.eat_metavar_guard() {
114                guard
115            } else {
116                let leading_if_span = self.prev_token.span;
117                let cond = self.parse_expr()?;
118                let cond_span = cond.span;
119                Box::new(Guard { cond: *cond, span_with_leading_if: leading_if_span.to(cond_span) })
120            };
121
122            self.psess.gated_spans.gate(sym::guard_patterns, guard.span_with_leading_if);
123            let span = pat.span.to(guard.span());
124            Ok(self.mk_pat(span, PatKind::Guard(Box::new(pat), guard)))
125        } else {
126            Ok(pat)
127        }
128    }
129
130    /// Parses a pattern.
131    ///
132    /// Corresponds to `PatternNoTopAlt` in RFC 3637 and does not admit or-patterns
133    /// or guard patterns at the top level. Used when parsing the parameters of lambda
134    /// expressions, functions, function pointers, and `pat_param` macro fragments.
135    pub fn parse_pat_no_top_alt(
136        &mut self,
137        expected: Option<Expected>,
138        syntax_loc: Option<PatternLocation>,
139    ) -> PResult<'a, Pat> {
140        self.parse_pat_with_range_pat(true, expected, syntax_loc)
141    }
142
143    /// Parses a pattern.
144    ///
145    /// Corresponds to `PatternNoTopGuard` in RFC 3637 and allows or-patterns, but not
146    /// guard patterns, at the top level. Used for parsing patterns in `pat` fragments (until
147    /// the next edition) and `let`, `if let`, and `while let` expressions.
148    ///
149    /// Note that after the FCP in <https://github.com/rust-lang/rust/issues/81415>,
150    /// a leading vert is allowed in nested or-patterns, too. This allows us to
151    /// simplify the grammar somewhat.
152    pub fn parse_pat_no_top_guard(
153        &mut self,
154        expected: Option<Expected>,
155        rc: RecoverComma,
156        ra: RecoverColon,
157        rt: CommaRecoveryMode,
158    ) -> PResult<'a, Pat> {
159        self.parse_pat_no_top_guard_inner(expected, rc, ra, rt, None).map(|(pat, _)| pat)
160    }
161
162    /// Returns the pattern and a bool indicating whether we recovered from a trailing vert (true =
163    /// recovered).
164    fn parse_pat_no_top_guard_inner(
165        &mut self,
166        expected: Option<Expected>,
167        rc: RecoverComma,
168        ra: RecoverColon,
169        rt: CommaRecoveryMode,
170        syntax_loc: Option<PatternLocation>,
171    ) -> PResult<'a, (Pat, bool)> {
172        // Keep track of whether we recovered from a trailing vert so that we can avoid duplicated
173        // suggestions (which bothers rustfix).
174        //
175        // Allow a '|' before the pats (RFCs 1925, 2530, and 2535).
176        let (leading_vert_span, mut trailing_vert) = match self.eat_or_separator(None) {
177            EatOrResult::AteOr => (Some(self.prev_token.span), false),
178            EatOrResult::TrailingVert => (None, true),
179            EatOrResult::None => (None, false),
180        };
181
182        // Parse the first pattern (`p_0`).
183        let mut first_pat = match self.parse_pat_no_top_alt(expected, syntax_loc) {
184            Ok(pat) => pat,
185            Err(err)
186                if self.token.is_reserved_ident()
187                    && !self.token.is_keyword(kw::In)
188                    && !self.token.is_keyword(kw::If) =>
189            {
190                err.emit();
191                self.bump();
192                self.mk_pat(self.token.span, PatKind::Wild)
193            }
194            Err(err) => return Err(err),
195        };
196        if rc == RecoverComma::Yes && !first_pat.could_be_never_pattern() {
197            self.maybe_recover_unexpected_comma(first_pat.span, rt)?;
198        }
199
200        // If the next token is not a `|`,
201        // this is not an or-pattern and we should exit here.
202        if !self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Or,
    token_type: crate::parser::token_type::TokenType::Or,
}exp!(Or)) && self.token != token::OrOr {
203            // If we parsed a leading `|` which should be gated,
204            // then we should really gate the leading `|`.
205            // This complicated procedure is done purely for diagnostics UX.
206
207            // Check if the user wrote `foo:bar` instead of `foo::bar`.
208            if ra == RecoverColon::Yes && token::Colon == self.token.kind {
209                first_pat = self.recover_colon_colon_in_pat_typo(first_pat, expected);
210            }
211
212            if let Some(leading_vert_span) = leading_vert_span {
213                // If there was a leading vert, treat this as an or-pattern. This improves
214                // diagnostics.
215                let span = leading_vert_span.to(self.prev_token.span);
216                return Ok((self.mk_pat(span, PatKind::Or({
    let len = [()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(first_pat);
    vec
}thin_vec![first_pat])), trailing_vert));
217            }
218
219            return Ok((first_pat, trailing_vert));
220        }
221
222        // Parse the patterns `p_1 | ... | p_n` where `n > 0`.
223        let lo = leading_vert_span.unwrap_or(first_pat.span);
224        let mut pats = {
    let len = [()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(first_pat);
    vec
}thin_vec![first_pat];
225        loop {
226            match self.eat_or_separator(Some(lo)) {
227                EatOrResult::AteOr => {}
228                EatOrResult::None => break,
229                EatOrResult::TrailingVert => {
230                    trailing_vert = true;
231                    break;
232                }
233            }
234            let pat = self.parse_pat_no_top_alt(expected, syntax_loc).map_err(|mut err| {
235                err.span_label(lo, WHILE_PARSING_OR_MSG);
236                err
237            })?;
238            if rc == RecoverComma::Yes && !pat.could_be_never_pattern() {
239                self.maybe_recover_unexpected_comma(pat.span, rt)?;
240            }
241            pats.push(pat);
242        }
243        let or_pattern_span = lo.to(self.prev_token.span);
244
245        Ok((self.mk_pat(or_pattern_span, PatKind::Or(pats)), trailing_vert))
246    }
247
248    /// Parse a pattern and (maybe) a `Colon` in positions where a pattern may be followed by a
249    /// type annotation (e.g. for `let` bindings or `fn` params).
250    ///
251    /// Generally, this corresponds to `pat_no_top_alt` followed by an optional `Colon`. It will
252    /// eat the `Colon` token if one is present.
253    ///
254    /// The return value represents the parsed pattern and `true` if a `Colon` was parsed (`false`
255    /// otherwise).
256    pub(super) fn parse_pat_before_ty(
257        &mut self,
258        expected: Option<Expected>,
259        rc: RecoverComma,
260        syntax_loc: PatternLocation,
261    ) -> PResult<'a, (Box<Pat>, bool)> {
262        // We use `parse_pat_allow_top_alt` regardless of whether we actually want top-level
263        // or-patterns so that we can detect when a user tries to use it. This allows us to print a
264        // better error message.
265        let (pat, trailing_vert) = self.parse_pat_no_top_guard_inner(
266            expected,
267            rc,
268            RecoverColon::No,
269            CommaRecoveryMode::LikelyTuple,
270            Some(syntax_loc),
271        )?;
272        let pat = Box::new(pat);
273        let colon = self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Colon,
    token_type: crate::parser::token_type::TokenType::Colon,
}exp!(Colon));
274
275        if let PatKind::Or(pats) = &pat.kind {
276            let span = pat.span;
277            let sub = if let [_] = &pats[..] {
278                let span = span.with_hi(span.lo() + BytePos(1));
279                Some(TopLevelOrPatternNotAllowedSugg::RemoveLeadingVert { span })
280            } else {
281                Some(TopLevelOrPatternNotAllowedSugg::WrapInParens {
282                    span,
283                    suggestion: WrapInParens { lo: span.shrink_to_lo(), hi: span.shrink_to_hi() },
284                })
285            };
286
287            let err = self.dcx().create_err(match syntax_loc {
288                PatternLocation::LetBinding => {
289                    TopLevelOrPatternNotAllowed::LetBinding { span, sub }
290                }
291                PatternLocation::FunctionParameter => {
292                    TopLevelOrPatternNotAllowed::FunctionParameter { span, sub }
293                }
294            });
295            if trailing_vert {
296                err.delay_as_bug();
297            } else {
298                err.emit();
299            }
300        }
301
302        Ok((pat, colon))
303    }
304
305    /// Parse the pattern for a function or function pointer parameter, followed by a colon.
306    ///
307    /// The return value represents the parsed pattern and `true` if a `Colon` was parsed (`false`
308    /// otherwise).
309    pub(super) fn parse_fn_param_pat_colon(&mut self) -> PResult<'a, (Box<Pat>, bool)> {
310        // In order to get good UX, we first recover in the case of a leading vert for an illegal
311        // top-level or-pat. Normally, this means recovering both `|` and `||`, but in this case,
312        // a leading `||` probably doesn't indicate an or-pattern attempt, so we handle that
313        // separately.
314        if let token::OrOr = self.token.kind {
315            self.dcx().emit_err(UnexpectedVertVertBeforeFunctionParam { span: self.token.span });
316            self.bump();
317        }
318
319        self.parse_pat_before_ty(
320            Some(Expected::ParameterName),
321            RecoverComma::No,
322            PatternLocation::FunctionParameter,
323        )
324    }
325
326    /// Eat the or-pattern `|` separator.
327    /// If instead a `||` token is encountered, recover and pretend we parsed `|`.
328    fn eat_or_separator(&mut self, lo: Option<Span>) -> EatOrResult {
329        if self.recover_trailing_vert(lo) {
330            EatOrResult::TrailingVert
331        } else if self.token.kind == token::OrOr {
332            // Found `||`; Recover and pretend we parsed `|`.
333            self.dcx().emit_err(UnexpectedVertVertInPattern { span: self.token.span, start: lo });
334            self.bump();
335            EatOrResult::AteOr
336        } else if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Or,
    token_type: crate::parser::token_type::TokenType::Or,
}exp!(Or)) {
337            EatOrResult::AteOr
338        } else {
339            EatOrResult::None
340        }
341    }
342
343    /// Recover if `|` or `||` is the current token and we have one of the
344    /// tokens `=>`, `if`, `=`, `:`, `;`, `,`, `]`, `)`, or `}` ahead of us.
345    ///
346    /// These tokens all indicate that we reached the end of the or-pattern
347    /// list and can now reliably say that the `|` was an illegal trailing vert.
348    /// Note that there are more tokens such as `@` for which we know that the `|`
349    /// is an illegal parse. However, the user's intent is less clear in that case.
350    fn recover_trailing_vert(&mut self, lo: Option<Span>) -> bool {
351        let is_end_ahead = self.look_ahead(1, |token| {
352            #[allow(non_exhaustive_omitted_patterns)] match &token.uninterpolate().kind {
    token::FatArrow |
        token::Ident(kw::If,
        token::IdentKind::Normal | token::IdentKind::ForcedKeyword) |
        token::Eq | token::Semi | token::Colon | token::Comma |
        token::CloseBracket | token::CloseParen | token::CloseBrace => true,
    _ => false,
}matches!(
353                &token.uninterpolate().kind,
354                token::FatArrow // e.g. `a | => 0,`.
355                | token::Ident(kw::If, token::IdentKind::Normal | token::IdentKind::ForcedKeyword) // e.g. `a | if expr`.
356                | token::Eq // e.g. `let a | = 0`.
357                | token::Semi // e.g. `let a |;`.
358                | token::Colon // e.g. `let a | :`.
359                | token::Comma // e.g. `let (a |,)`.
360                | token::CloseBracket // e.g. `let [a | ]`.
361                | token::CloseParen // e.g. `let (a | )`.
362                | token::CloseBrace // e.g. `let A { f: a | }`.
363            )
364        });
365        match (is_end_ahead, &self.token.kind) {
366            (true, token::Or | token::OrOr) => {
367                // A `|` or possibly `||` token shouldn't be here. Ban it.
368                let token = pprust::token_to_string(&self.token);
369                self.dcx().emit_err(TrailingVertNotAllowed {
370                    span: self.token.span,
371                    start: lo,
372                    suggestion: TrailingVertSuggestion {
373                        span: self.prev_token.span.shrink_to_hi().with_hi(self.token.span.hi()),
374                        token: token.clone(),
375                    },
376                    token,
377                    note_double_vert: self.token.kind == token::OrOr,
378                });
379                self.bump();
380                true
381            }
382            _ => false,
383        }
384    }
385
386    /// Ensures that the last parsed pattern (or pattern range bound) is not followed by an expression.
387    ///
388    /// `is_end_bound` indicates whether the last parsed thing was the end bound of a range pattern (see [`parse_pat_range_end`](Self::parse_pat_range_end))
389    /// in order to say "expected a pattern range bound" instead of "expected a pattern";
390    /// ```text
391    /// 0..=1 + 2
392    ///     ^^^^^
393    /// ```
394    /// Only the end bound is spanned in this case, and this function has no idea if there was a `..=` before `pat_span`, hence the parameter.
395    ///
396    /// This function returns `Some` if a trailing expression was recovered, and said expression's span.
397    #[must_use = "the pattern must be discarded as `PatKind::Err` if this function returns Some"]
398    fn maybe_recover_trailing_expr(
399        &mut self,
400        pat_span: Span,
401        is_end_bound: bool,
402    ) -> Option<(ErrorGuaranteed, Span)> {
403        if self.prev_token.is_keyword(kw::Underscore) || !self.may_recover() {
404            // Don't recover anything after an `_` or if recovery is disabled.
405            return None;
406        }
407
408        // Returns `true` iff `token` is an unsuffixed integer.
409        let is_one_tuple_index = |_: &Self, token: &Token| -> bool {
410            use token::{Lit, LitKind};
411
412            #[allow(non_exhaustive_omitted_patterns)] match token.kind {
    token::Literal(Lit { kind: LitKind::Integer, symbol: _, suffix: None }) =>
        true,
    _ => false,
}matches!(
413                token.kind,
414                token::Literal(Lit { kind: LitKind::Integer, symbol: _, suffix: None })
415            )
416        };
417
418        // Returns `true` iff `token` is an unsuffixed `x.y` float.
419        let is_two_tuple_indexes = |this: &Self, token: &Token| -> bool {
420            use token::{Lit, LitKind};
421
422            if let token::Literal(Lit { kind: LitKind::Float, symbol, suffix: None }) = token.kind
423                && let DestructuredFloat::MiddleDot(..) = this.break_up_float(symbol, token.span)
424            {
425                true
426            } else {
427                false
428            }
429        };
430
431        // Check for `.hello` or `.0`.
432        let has_dot_expr = self.check_noexpect(&token::Dot) // `.`
433            && self.look_ahead(1, |tok| {
434                tok.is_ident() // `hello`
435                || is_one_tuple_index(&self, &tok) // `0`
436                || is_two_tuple_indexes(&self, &tok) // `0.0`
437            });
438
439        // Check for operators.
440        // `|` is excluded as it is used in pattern alternatives and lambdas,
441        // `?` is included for error propagation,
442        // `[` is included for indexing operations,
443        // `[]` is excluded as `a[]` isn't an expression and should be recovered as `a, []` (cf. `tests/ui/parser/pat-lt-bracket-7.rs`),
444        // `as` is included for type casts
445        let has_trailing_operator = #[allow(non_exhaustive_omitted_patterns)] match self.token.kind {
    token::Plus | token::Minus | token::Star | token::Slash | token::Percent |
        token::Caret | token::And | token::Shl | token::Shr => true,
    _ => false,
}matches!(
446                self.token.kind,
447                token::Plus | token::Minus | token::Star | token::Slash | token::Percent
448                | token::Caret | token::And | token::Shl | token::Shr // excludes `Or`
449            )
450            || self.token == token::Question
451            || (self.token == token::OpenBracket
452                && self.look_ahead(1, |t| *t != token::CloseBracket)) // excludes `[]`
453            || self.token.is_keyword(kw::As);
454
455        if !has_dot_expr && !has_trailing_operator {
456            // Nothing to recover here.
457            return None;
458        }
459
460        // Let's try to parse an expression to emit a better diagnostic.
461        let mut snapshot = self.create_snapshot_for_diagnostic();
462        snapshot.restrictions.insert(Restrictions::IS_PAT);
463
464        // Parse `?`, `.f`, `(arg0, arg1, ...)` or `[expr]` until they've all been eaten.
465        let Ok(expr) = snapshot
466            .parse_expr_dot_or_call_with(
467                AttrVec::new(),
468                self.mk_expr(pat_span, ExprKind::Dummy), // equivalent to transforming the parsed pattern into an `Expr`
469                pat_span,
470            )
471            .map_err(|err| err.cancel())
472        else {
473            // We got a trailing method/operator, but that wasn't an expression.
474            return None;
475        };
476
477        // Parse an associative expression such as `+ expr`, `% expr`, ...
478        // Assignments, ranges and `|` are disabled by [`Restrictions::IS_PAT`].
479        let Ok((expr, _)) = snapshot
480            .parse_expr_assoc_rest(Bound::Unbounded, false, expr)
481            .map_err(|err| err.cancel())
482        else {
483            // We got a trailing method/operator, but that wasn't an expression.
484            return None;
485        };
486
487        // We got a valid expression.
488        self.restore_snapshot(snapshot);
489        self.restrictions.remove(Restrictions::IS_PAT);
490
491        let is_bound = is_end_bound
492            // is_start_bound: either `..` or `)..`
493            || self.token.is_range_separator()
494            || self.token == token::CloseParen
495                && self.look_ahead(1, Token::is_range_separator);
496
497        let span = expr.span;
498        let mut diag = self.dcx().create_err(UnexpectedExpressionInPattern { span, is_bound });
499        // The unexpected expr's precedence. Not used directly in the error message, but
500        // needed for the stashing of this error to work correctly. We store a `u32` rather
501        // than an `ExprPrecedence` to avoid having to impl `IntoDiagArg` for
502        // `ExprPrecedence`.
503        diag.arg("expr_precedence", expr.precedence() as u32);
504
505        Some((diag.stash(span, StashKey::ExprInPat).unwrap(), span))
506    }
507
508    /// Called by [`Parser::parse_stmt_without_recovery`], used to add statement-aware subdiagnostics to the errors stashed
509    /// by [`Parser::maybe_recover_trailing_expr`].
510    pub(super) fn maybe_augment_stashed_expr_in_pats_with_suggestions(&mut self, stmt: &Stmt) {
511        if self.dcx().has_errors().is_none() {
512            // No need to walk the statement if there's no stashed errors.
513            return;
514        }
515
516        struct PatVisitor<'a> {
517            /// `self`
518            parser: &'a Parser<'a>,
519            /// The freshly-parsed statement.
520            stmt: &'a Stmt,
521            /// The current match arm (for arm guard suggestions).
522            arm: Option<&'a Arm>,
523            /// The current struct field (for variable name suggestions).
524            field: Option<&'a PatField>,
525        }
526
527        impl<'a> PatVisitor<'a> {
528            /// Looks for stashed [`StashKey::ExprInPat`] errors in `stash_span`, and emit them with suggestions.
529            /// `stash_span` is contained in `expr_span`, the latter being larger in borrow patterns;
530            /// ```txt
531            /// &mut x.y
532            /// -----^^^ `stash_span`
533            /// |
534            /// `expr_span`
535            /// ```
536            /// `is_range_bound` is used to exclude arm guard suggestions in range pattern bounds.
537            fn maybe_add_suggestions_then_emit(
538                &self,
539                stash_span: Span,
540                expr_span: Span,
541                is_range_bound: bool,
542            ) {
543                self.parser.dcx().try_steal_modify_and_emit_err(
544                    stash_span,
545                    StashKey::ExprInPat,
546                    |err| {
547                        // Includes pre-pats (e.g. `&mut <err>`) in the diagnostic.
548                        err.span.replace(stash_span, expr_span);
549
550                        let sm = self.parser.psess.source_map();
551                        let stmt = self.stmt;
552                        let line_lo = sm.span_extend_to_line(stmt.span).shrink_to_lo();
553                        let indentation = sm.indentation_before(stmt.span).unwrap_or_default();
554                        let Ok(expr) = self.parser.span_to_snippet(expr_span) else {
555                            // FIXME: some suggestions don't actually need the snippet; see PR #123877's unresolved conversations.
556                            return;
557                        };
558
559                        if let StmtKind::Let(local) = &stmt.kind {
560                            match &local.kind {
561                                LocalKind::Decl | LocalKind::Init(_) => {
562                                    // It's kinda hard to guess what the user intended, so don't make suggestions.
563                                    return;
564                                }
565
566                                LocalKind::InitElse(_, _) => {}
567                            }
568                        }
569
570                        // help: use an arm guard `if val == expr`
571                        // FIXME(guard_patterns): suggest this regardless of a match arm.
572                        if let Some(arm) = &self.arm
573                            && !is_range_bound
574                        {
575                            let (ident, ident_span) = match self.field {
576                                Some(field) => {
577                                    (field.ident.to_string(), field.ident.span.to(expr_span))
578                                }
579                                None => ("val".to_owned(), expr_span),
580                            };
581
582                            // Are parentheses required around `expr`?
583                            // HACK: a neater way would be preferable.
584                            let expr = match &err.args["expr_precedence"] {
585                                DiagArgValue::Number(expr_precedence) => {
586                                    if *expr_precedence <= ExprPrecedence::Compare as i32 {
587                                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("({0})", expr))
    })format!("({expr})")
588                                    } else {
589                                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}", expr))
    })format!("{expr}")
590                                    }
591                                }
592                                _ => ::core::panicking::unreachable_default_msg()unreachable!(),
593                            };
594
595                            match &arm.guard {
596                                None => {
597                                    err.subdiagnostic(
598                                        UnexpectedExpressionInPatternSugg::CreateGuard {
599                                            ident_span,
600                                            pat_hi: arm.pat.span.shrink_to_hi(),
601                                            ident,
602                                            expr,
603                                        },
604                                    );
605                                }
606                                Some(guard) => {
607                                    // Are parentheses required around the old guard?
608                                    let wrap_guard =
609                                        guard.cond.precedence() <= ExprPrecedence::LAnd;
610
611                                    err.subdiagnostic(
612                                        UnexpectedExpressionInPatternSugg::UpdateGuard {
613                                            ident_span,
614                                            guard_lo: if wrap_guard {
615                                                Some(guard.span().shrink_to_lo())
616                                            } else {
617                                                None
618                                            },
619                                            guard_hi: guard.span().shrink_to_hi(),
620                                            guard_hi_paren: if wrap_guard { ")" } else { "" },
621                                            ident,
622                                            expr,
623                                        },
624                                    );
625                                }
626                            }
627                        }
628
629                        // help: extract the expr into a `const VAL: _ = expr`
630                        if !line_lo.overlaps(expr_span) {
631                            let ident = match self.field {
632                                Some(field) => field.ident.as_str().to_uppercase(),
633                                None => "VAL".to_owned(),
634                            };
635                            err.subdiagnostic(UnexpectedExpressionInPatternSugg::Const {
636                                stmt_lo: line_lo,
637                                ident_span: expr_span,
638                                expr,
639                                ident,
640                                indentation,
641                            });
642                        }
643                    },
644                );
645            }
646        }
647
648        impl<'a> Visitor<'a> for PatVisitor<'a> {
649            fn visit_arm(&mut self, a: &'a Arm) -> Self::Result {
650                self.arm = Some(a);
651                visit::walk_arm(self, a);
652                self.arm = None;
653            }
654
655            fn visit_pat_field(&mut self, fp: &'a PatField) -> Self::Result {
656                self.field = Some(fp);
657                visit::walk_pat_field(self, fp);
658                self.field = None;
659            }
660
661            fn visit_pat(&mut self, p: &'a Pat) -> Self::Result {
662                match &p.kind {
663                    // Base expression
664                    PatKind::Err(_) | PatKind::Expr(_) => {
665                        self.maybe_add_suggestions_then_emit(p.span, p.span, false)
666                    }
667
668                    // Sub-patterns
669                    // FIXME: this doesn't work with recursive subpats (`&mut &mut <err>`)
670                    PatKind::Ref(subpat, _, _)
671                        if #[allow(non_exhaustive_omitted_patterns)] match subpat.kind {
    PatKind::Err(_) | PatKind::Expr(_) => true,
    _ => false,
}matches!(subpat.kind, PatKind::Err(_) | PatKind::Expr(_)) =>
672                    {
673                        self.maybe_add_suggestions_then_emit(subpat.span, p.span, false)
674                    }
675
676                    // Sub-expressions
677                    PatKind::Range(start, end, _) => {
678                        if let Some(start) = start {
679                            self.maybe_add_suggestions_then_emit(start.span, start.span, true);
680                        }
681
682                        if let Some(end) = end {
683                            self.maybe_add_suggestions_then_emit(end.span, end.span, true);
684                        }
685                    }
686
687                    // Walk continuation
688                    _ => visit::walk_pat(self, p),
689                }
690            }
691        }
692
693        // Starts the visit.
694        PatVisitor { parser: self, stmt, arm: None, field: None }.visit_stmt(stmt);
695    }
696
697    fn eat_metavar_pat(&mut self) -> Option<Pat> {
698        // Must try both kinds of pattern nonterminals.
699        if let Some(pat) = self.eat_metavar_seq_with_matcher(
700            |mv_kind| #[allow(non_exhaustive_omitted_patterns)] match mv_kind {
    MetaVarKind::Pat(PatParam { .. }) => true,
    _ => false,
}matches!(mv_kind, MetaVarKind::Pat(PatParam { .. })),
701            |this| this.parse_pat_no_top_alt(None, None),
702        ) {
703            Some(pat)
704        } else if let Some(pat) = self.eat_metavar_seq(MetaVarKind::Pat(PatWithOr), |this| {
705            this.parse_pat_no_top_guard(
706                None,
707                RecoverComma::No,
708                RecoverColon::No,
709                CommaRecoveryMode::EitherTupleOrPipe,
710            )
711        }) {
712            Some(pat)
713        } else {
714            None
715        }
716    }
717
718    /// Parses a pattern, with a setting whether modern range patterns (e.g., `a..=b`, `a..b` are
719    /// allowed).
720    fn parse_pat_with_range_pat(
721        &mut self,
722        allow_range_pat: bool,
723        expected: Option<Expected>,
724        syntax_loc: Option<PatternLocation>,
725    ) -> PResult<'a, Pat> {
726        if true && self.may_recover() &&
                let Some(mv_kind) = self.token.is_metavar_seq() &&
            let token::MetaVarKind::Ty { .. } = mv_kind &&
        self.check_noexpect_past_close_delim(&token::PathSep) {
    let ty =
        self.eat_metavar_seq(mv_kind,
                |this|
                    this.parse_ty_no_question_mark_recover()).expect("metavar seq ty");
    return self.maybe_recover_from_bad_qpath_stage_2(self.prev_token.span,
            ty);
};maybe_recover_from_interpolated_ty_qpath!(self, true);
727
728        if let Some(pat) = self.eat_metavar_pat() {
729            return Ok(pat);
730        }
731
732        let mut lo = self.token.span;
733
734        if self.token.is_keyword(kw::Let)
735            && self.look_ahead(1, |tok| {
736                tok.can_begin_pattern(token::NtPatKind::PatParam { inferred: false })
737            })
738        {
739            self.bump();
740            // Trim extra space after the `let`
741            let span = lo.with_hi(self.token.span.lo());
742            self.dcx().emit_err(RemoveLet { span: lo, suggestion: span });
743            lo = self.token.span;
744        }
745
746        let pat = if self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::And,
    token_type: crate::parser::token_type::TokenType::And,
}exp!(And)) || self.token == token::AndAnd {
747            self.parse_pat_deref(expected)?
748        } else if self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenParen,
    token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen)) {
749            self.parse_pat_tuple_or_parens(syntax_loc)?
750        } else if self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenBracket,
    token_type: crate::parser::token_type::TokenType::OpenBracket,
}exp!(OpenBracket)) {
751            // Parse `[pat, pat,...]` as a slice pattern.
752            let (pats, _) =
753                self.parse_delim_comma_seq(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenBracket,
    token_type: crate::parser::token_type::TokenType::OpenBracket,
}exp!(OpenBracket), crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseBracket,
    token_type: crate::parser::token_type::TokenType::CloseBracket,
}exp!(CloseBracket), |p| {
754                    p.parse_pat_allow_top_guard(
755                        None,
756                        RecoverComma::No,
757                        RecoverColon::No,
758                        CommaRecoveryMode::EitherTupleOrPipe,
759                    )
760                })?;
761            PatKind::Slice(pats)
762        } else if self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::DotDot,
    token_type: crate::parser::token_type::TokenType::DotDot,
}exp!(DotDot)) && !self.is_pat_range_end_start(1) {
763            // A rest pattern `..`.
764            self.bump(); // `..`
765            PatKind::Rest
766        } else if self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::DotDotDot,
    token_type: crate::parser::token_type::TokenType::DotDotDot,
}exp!(DotDotDot)) && !self.is_pat_range_end_start(1) {
767            self.recover_dotdotdot_rest_pat(lo, expected)
768        } else if let Some(form) = self.parse_range_end() {
769            self.parse_pat_range_to(form)? // `..=X`, `...X`, or `..X`.
770        } else if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Bang,
    token_type: crate::parser::token_type::TokenType::Bang,
}exp!(Bang)) {
771            // Parse `!`
772            self.psess.gated_spans.gate(sym::never_patterns, self.prev_token.span);
773            PatKind::Never
774        } else if self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Underscore,
    token_type: crate::parser::token_type::TokenType::KwUnderscore,
}exp!(Underscore)) {
775            // Parse `_`
776            PatKind::Wild
777        } else if self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Mut,
    token_type: crate::parser::token_type::TokenType::KwMut,
}exp!(Mut)) {
778            self.parse_pat_ident_mut()?
779        } else if self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Ref,
    token_type: crate::parser::token_type::TokenType::KwRef,
}exp!(Ref)) {
780            if self.check_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Box,
    token_type: crate::parser::token_type::TokenType::KwBox,
}exp!(Box)) {
781                // Suggest `box ref`.
782                let span = self.prev_token.span.to(self.token.span);
783                self.bump();
784                self.dcx().emit_err(SwitchRefBoxOrder { span });
785            }
786            // Parse ref ident @ pat / ref mut ident @ pat / ref pin const|mut ident @ pat
787            let (pinned, mutbl) = self.parse_pin_and_mut();
788            self.parse_pat_ident(
789                BindingMode(ByRef::Yes(pinned, mutbl), Mutability::Not),
790                syntax_loc,
791            )?
792        } else if self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Box,
    token_type: crate::parser::token_type::TokenType::KwBox,
}exp!(Box)) {
793            self.parse_pat_box()?
794        } else if self.check_inline_const(0) {
795            // Parse `const pat`
796            let const_expr = self.parse_const_block(lo.to(self.token.span), true)?;
797
798            if let Some(re) = self.parse_range_end() {
799                self.parse_pat_range_begin_with(const_expr, re)?
800            } else {
801                PatKind::Expr(const_expr)
802            }
803        } else if self.eat_forced_keyword_noexpect(kw::Deref) {
804            self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenParen,
    token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen))?;
805            let pat = ast::PatKind::Deref(Box::new(self.parse_pat_allow_top_guard(
806                None,
807                RecoverComma::Yes,
808                RecoverColon::Yes,
809                CommaRecoveryMode::LikelyTuple,
810            )?));
811            self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseParen,
    token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen))?;
812            self.psess.gated_spans.gate(sym::internal_syntax, lo.to(self.token.span));
813            pat
814        }
815        // Don't eagerly error on semantically invalid tokens when matching
816        // declarative macros, as the input to those doesn't have to be
817        // semantically valid. For attribute/derive proc macros this is not the
818        // case, so doing the recovery for them is fine.
819        else if self.can_be_ident_pat()
820            || (self.is_lit_bad_ident().is_some() && self.may_recover())
821        {
822            // Parse `ident @ pat`
823            // This can give false positives and parse nullary enums,
824            // they are dealt with later in resolve.
825            self.parse_pat_ident(BindingMode::NONE, syntax_loc)?
826        } else if self.is_start_of_pat_with_path() {
827            // Parse pattern starting with a path
828            let (qself, path) = if self.eat_lt() {
829                // Parse a qualified path
830                let (qself, path) = self.parse_qpath(PathStyle::Pat)?;
831                (Some(qself), path)
832            } else {
833                // Parse an unqualified path
834                (None, self.parse_path(PathStyle::Pat)?)
835            };
836            let span = lo.to(self.prev_token.span);
837
838            if qself.is_none() && self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Bang,
    token_type: crate::parser::token_type::TokenType::Bang,
}exp!(Bang)) {
839                self.parse_pat_mac_invoc(path)?
840            } else if let Some(form) = self.parse_range_end() {
841                let begin = self.mk_expr(span, ExprKind::Path(qself, path));
842                self.parse_pat_range_begin_with(begin, form)?
843            } else if self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenBrace,
    token_type: crate::parser::token_type::TokenType::OpenBrace,
}exp!(OpenBrace)) {
844                self.parse_pat_struct(qself, path)?
845            } else if self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenParen,
    token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen)) {
846                self.parse_pat_tuple_struct(qself, path)?
847            } else {
848                match self.maybe_recover_trailing_expr(span, false) {
849                    Some((guar, _)) => PatKind::Err(guar),
850                    None => PatKind::Path(qself, path),
851                }
852            }
853        } else if let Some((lt, IdentKind::Normal)) = self.token.lifetime()
854            // In pattern position, we're totally fine with using "next token isn't colon"
855            // as a heuristic. We could probably just always try to recover if it's a lifetime,
856            // because we never have `'a: label {}` in a pattern position anyways, but it does
857            // keep us from suggesting something like `let 'a: Ty = ..` => `let 'a': Ty = ..`
858            && could_be_unclosed_char_literal(lt)
859            && !self.look_ahead(1, |token| token.kind == token::Colon)
860        {
861            // Recover a `'a` as a `'a'` literal
862            let lt = self.expect_lifetime();
863            let (lit, _) =
864                self.recover_unclosed_char(lt.ident, Parser::mk_token_lit_char, |self_| {
865                    let expected = Expected::to_string_or_fallback(expected);
866                    let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected {0}, found {1}", expected,
                super::token_descr(&self_.token)))
    })format!(
867                        "expected {}, found {}",
868                        expected,
869                        super::token_descr(&self_.token)
870                    );
871
872                    self_
873                        .dcx()
874                        .struct_span_err(self_.token.span, msg)
875                        .with_span_label(self_.token.span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected {0}", expected))
    })format!("expected {expected}"))
876                });
877            PatKind::Expr(self.mk_expr(lo, ExprKind::Lit(lit)))
878        } else {
879            // Try to parse everything else as literal with optional minus
880            match self.parse_literal_maybe_minus() {
881                Ok(begin) => {
882                    let begin = self
883                        .maybe_recover_trailing_expr(begin.span, false)
884                        .map(|(guar, sp)| self.mk_expr_err(sp, guar))
885                        .unwrap_or(begin);
886
887                    match self.parse_range_end() {
888                        Some(form) => self.parse_pat_range_begin_with(begin, form)?,
889                        None => PatKind::Expr(begin),
890                    }
891                }
892                Err(err) => return self.fatal_unexpected_non_pat(err, expected),
893            }
894        };
895
896        let mut pat = self.mk_pat(lo.to(self.prev_token.span), pat);
897
898        pat = self.maybe_recover_from_bad_qpath(pat)?;
899        if self.eat_noexpect(&token::At) {
900            pat = self.recover_intersection_pat(pat)?;
901        }
902
903        if !allow_range_pat {
904            self.ban_pat_range_if_ambiguous(&pat)
905        }
906
907        Ok(pat)
908    }
909
910    /// Recover from a typoed `...` pattern that was encountered
911    /// Ref: Issue #70388
912    fn recover_dotdotdot_rest_pat(&mut self, lo: Span, expected: Option<Expected>) -> PatKind {
913        // A typoed rest pattern `...`.
914        self.bump(); // `...`
915
916        if let Some(Expected::ParameterName) = expected {
917            // We have `...` in a closure argument, likely meant to be var-arg, which aren't
918            // supported in closures (#146489).
919            PatKind::Err(self.dcx().emit_err(DotDotDotRestPattern {
920                span: lo,
921                suggestion: None,
922                var_args: Some(()),
923            }))
924        } else {
925            // The user probably mistook `...` for a rest pattern `..`.
926            self.dcx().emit_err(DotDotDotRestPattern {
927                span: lo,
928                suggestion: Some(lo),
929                var_args: None,
930            });
931            PatKind::Rest
932        }
933    }
934
935    /// Try to recover the more general form `intersect ::= $pat_lhs @ $pat_rhs`.
936    ///
937    /// Allowed binding patterns generated by `binding ::= ref? mut? $ident @ $pat_rhs`
938    /// should already have been parsed by now at this point,
939    /// if the next token is `@` then we can try to parse the more general form.
940    ///
941    /// Consult `parse_pat_ident` for the `binding` grammar.
942    ///
943    /// The notion of intersection patterns are found in
944    /// e.g. [F#][and] where they are called AND-patterns.
945    ///
946    /// [and]: https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/pattern-matching
947    #[cold]
948    fn recover_intersection_pat(&mut self, lhs: Pat) -> PResult<'a, Pat> {
949        let mut rhs = self.parse_pat_no_top_alt(None, None)?;
950        let whole_span = lhs.span.to(rhs.span);
951
952        if let PatKind::Ident(_, _, sub @ None) = &mut rhs.kind {
953            // The user inverted the order, so help them fix that.
954            let lhs_span = lhs.span;
955            // Move the LHS into the RHS as a subpattern.
956            // The RHS is now the full pattern.
957            *sub = Some(Box::new(lhs));
958
959            self.dcx().emit_err(PatternOnWrongSideOfAt {
960                whole_span,
961                whole_pat: pprust::pat_to_string(&rhs),
962                pattern: lhs_span,
963                binding: rhs.span,
964            });
965        } else {
966            // The special case above doesn't apply so we may have e.g. `A(x) @ B(y)`.
967            rhs.kind = PatKind::Wild;
968            self.dcx().emit_err(ExpectedBindingLeftOfAt {
969                whole_span,
970                lhs: lhs.span,
971                rhs: rhs.span,
972            });
973        }
974
975        rhs.span = whole_span;
976        Ok(rhs)
977    }
978
979    /// Ban a range pattern if it has an ambiguous interpretation.
980    fn ban_pat_range_if_ambiguous(&self, pat: &Pat) {
981        match pat.kind {
982            PatKind::Range(
983                ..,
984                Spanned { node: RangeEnd::Included(RangeSyntax::DotDotDot), .. },
985            ) => return,
986            PatKind::Range(..) => {}
987            _ => return,
988        }
989
990        self.dcx().emit_err(AmbiguousRangePattern {
991            span: pat.span,
992            suggestion: ParenRangeSuggestion {
993                lo: pat.span.shrink_to_lo(),
994                hi: pat.span.shrink_to_hi(),
995            },
996        });
997    }
998
999    /// Parse `&pat` / `&mut pat` / `&pin const pat` / `&pin mut pat`.
1000    fn parse_pat_deref(&mut self, expected: Option<Expected>) -> PResult<'a, PatKind> {
1001        self.expect_and()?;
1002        if let Some((lifetime, _)) = self.token.lifetime() {
1003            self.bump(); // `'a`
1004
1005            self.dcx().emit_err(UnexpectedLifetimeInPattern {
1006                span: self.prev_token.span,
1007                symbol: lifetime.name,
1008                suggestion: self.prev_token.span.until(self.token.span),
1009            });
1010        }
1011
1012        let (pinned, mutbl) = self.parse_pin_and_mut();
1013        let subpat = self.parse_pat_with_range_pat(false, expected, None)?;
1014        Ok(PatKind::Ref(Box::new(subpat), pinned, mutbl))
1015    }
1016
1017    /// Parse a tuple or parenthesis pattern.
1018    fn parse_pat_tuple_or_parens(
1019        &mut self,
1020        syntax_loc: Option<PatternLocation>,
1021    ) -> PResult<'a, PatKind> {
1022        let open_paren = self.token.span;
1023
1024        // The index, the span of the `:` and the type of every element written
1025        // with an inline type annotation, which is invalid syntax. This is kept
1026        // out of the element patterns themselves so that the happy path doesn't
1027        // have to allocate for it.
1028        let mut tys: Vec<(usize, Span, Box<Ty>)> = Vec::new();
1029        let mut index = 0;
1030
1031        let (fields, trailing_comma) = self.parse_paren_comma_seq(|p| {
1032            let pat = p.parse_pat_allow_top_guard(
1033                None,
1034                RecoverComma::No,
1035                RecoverColon::No,
1036                CommaRecoveryMode::LikelyTuple,
1037            )?;
1038            // Recover from an inline `: <ty>` type annotation. We only do this
1039            // when there is whitespace after the colon, so that `(a:b)` keeps
1040            // the existing "maybe write a path separator here" (`a::b`)
1041            // suggestion, which is the more likely intent when the two are
1042            // written next to each other.
1043            if p.may_recover()
1044                && p.token == token::Colon
1045                && let colon = p.token.span
1046                && p.look_ahead(1, |next| next.span.lo() > colon.hi())
1047            {
1048                p.bump(); // eat the `:`
1049                tys.push((index, colon, p.parse_ty()?));
1050            }
1051            index += 1;
1052            Ok(pat)
1053        })?;
1054
1055        // If any element carried an inline type annotation then this is the
1056        // invalid `(a: bool, b: u8)` form; report it and suggest the correct
1057        // spelling where we can. Either way, continue on with the type
1058        // annotations stripped.
1059        if !tys.is_empty() {
1060            self.recover_tuple_pat_type_ascription(
1061                open_paren,
1062                &fields,
1063                &tys,
1064                trailing_comma,
1065                syntax_loc,
1066            );
1067        }
1068
1069        // Here, `(pat,)` is a tuple pattern.
1070        // For backward compatibility, `(..)` is a tuple pattern as well.
1071        let paren_pattern =
1072            fields.len() == 1 && !(#[allow(non_exhaustive_omitted_patterns)] match trailing_comma {
    Trailing::Yes => true,
    _ => false,
}matches!(trailing_comma, Trailing::Yes) || fields[0].is_rest());
1073
1074        let pat = if paren_pattern {
1075            let pat = fields.into_iter().next().unwrap();
1076            let close_paren = self.prev_token.span;
1077
1078            match &pat.kind {
1079                // recover ranges with parentheses around the `(start)..`
1080                PatKind::Expr(begin)
1081                    if self.may_recover()
1082                        && let Some(form) = self.parse_range_end() =>
1083                {
1084                    self.dcx().emit_err(UnexpectedParenInRangePat {
1085                        span: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [open_paren, close_paren]))vec![open_paren, close_paren],
1086                        sugg: UnexpectedParenInRangePatSugg {
1087                            start_span: open_paren,
1088                            end_span: close_paren,
1089                        },
1090                    });
1091
1092                    self.parse_pat_range_begin_with(begin.clone(), form)?
1093                }
1094                // recover ranges with parentheses around the `(start)..`
1095                PatKind::Err(guar)
1096                    if self.may_recover()
1097                        && let Some(form) = self.parse_range_end() =>
1098                {
1099                    self.dcx().emit_err(UnexpectedParenInRangePat {
1100                        span: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [open_paren, close_paren]))vec![open_paren, close_paren],
1101                        sugg: UnexpectedParenInRangePatSugg {
1102                            start_span: open_paren,
1103                            end_span: close_paren,
1104                        },
1105                    });
1106
1107                    self.parse_pat_range_begin_with(self.mk_expr_err(pat.span, *guar), form)?
1108                }
1109
1110                // (pat) with optional parentheses
1111                _ => PatKind::Paren(Box::new(pat)),
1112            }
1113        } else {
1114            PatKind::Tuple(fields)
1115        };
1116
1117        Ok(match self.maybe_recover_trailing_expr(open_paren.to(self.prev_token.span), false) {
1118            None => pat,
1119            Some((guar, _)) => PatKind::Err(guar),
1120        })
1121    }
1122
1123    /// Report a tuple or parenthesized pattern whose elements carry inline type
1124    /// annotations, e.g. `let (a: bool, b: u8) = ...;`. This is invalid syntax;
1125    /// the element types have to be written together as a tuple type after the
1126    /// pattern, i.e. `let (a, b): (bool, u8) = ...;`. `tys` are the annotations
1127    /// that were written, indexed into `fields`.
1128    fn recover_tuple_pat_type_ascription(
1129        &self,
1130        open_paren: Span,
1131        fields: &[Pat],
1132        tys: &[(usize, Span, Box<Ty>)],
1133        trailing_comma: Trailing,
1134        syntax_loc: Option<PatternLocation>,
1135    ) {
1136        let close_paren = self.prev_token.span;
1137
1138        // Point at every inline type annotation.
1139        let ty_spans: Vec<Span> = tys.iter().map(|(_, colon, ty)| colon.to(ty.span)).collect();
1140        // `(a: T)` is a parenthesized pattern rather than a one element tuple.
1141        let paren_pattern =
1142            fields.len() == 1 && #[allow(non_exhaustive_omitted_patterns)] match trailing_comma {
    Trailing::No => true,
    _ => false,
}matches!(trailing_comma, Trailing::No) && !fields[0].is_rest();
1143        let mut err = self.dcx().struct_span_err(
1144            ty_spans.clone(),
1145            if paren_pattern {
1146                "a parenthesized pattern cannot be given a type"
1147            } else {
1148                "the elements of a tuple pattern cannot be given types individually"
1149            },
1150        );
1151
1152        // Only the top level pattern of a `let` binding can be followed by a
1153        // type, so that's the only place where we know how the pattern should
1154        // have been written instead. Anywhere else (`match` arms, function
1155        // parameters, nested patterns) we just recover without a suggestion.
1156        if #[allow(non_exhaustive_omitted_patterns)] match syntax_loc {
    Some(PatternLocation::LetBinding) => true,
    _ => false,
}matches!(syntax_loc, Some(PatternLocation::LetBinding)) {
1157            if self.token == token::Colon {
1158                // The pattern is already followed by a type, as in
1159                // `let (a: bool, b): (_, u8) = ...;`. Merging that type with the
1160                // inline ones isn't always possible, so just suggest dropping
1161                // the inline ones.
1162                err.multipart_suggestion(
1163                    "remove the inline type annotations",
1164                    ty_spans.into_iter().map(|span| (span, String::new())).collect(),
1165                    Applicability::MaybeIncorrect,
1166                );
1167            } else if !fields.iter().any(|pat| pat.is_rest()) {
1168                // A rest pattern stands for any number of elements, so we can't
1169                // tell how many types the tuple type would have to list.
1170                self.suggest_tuple_pat_type(
1171                    &mut err,
1172                    open_paren,
1173                    close_paren,
1174                    fields,
1175                    tys,
1176                    paren_pattern,
1177                );
1178            }
1179        }
1180        err.emit();
1181    }
1182
1183    /// Suggest rewriting `(a: bool, b: u8)` as `(a, b): (bool, u8)`, moving the
1184    /// inline type annotations into a tuple type after the pattern.
1185    fn suggest_tuple_pat_type(
1186        &self,
1187        err: &mut Diag<'a>,
1188        open_paren: Span,
1189        close_paren: Span,
1190        fields: &[Pat],
1191        tys: &[(usize, Span, Box<Ty>)],
1192        paren_pattern: bool,
1193    ) {
1194        // Build the replacement from the source snippets. Elements without an
1195        // annotation get an inferred `_` type.
1196        let mut pat_snippets = Vec::with_capacity(fields.len());
1197        let mut ty_snippets = Vec::with_capacity(fields.len());
1198        let mut tys = tys.iter().peekable();
1199        for (index, pat) in fields.iter().enumerate() {
1200            let ty_snippet = match tys.next_if(|(i, ..)| *i == index) {
1201                Some((_, _, ty)) => self.span_to_snippet(ty.span),
1202                None => Ok("_".to_string()),
1203            };
1204            let (Ok(pat_snippet), Ok(ty_snippet)) = (self.span_to_snippet(pat.span), ty_snippet)
1205            else {
1206                // We can't rebuild the pattern from source, so don't suggest anything.
1207                return;
1208            };
1209            pat_snippets.push(pat_snippet);
1210            ty_snippets.push(ty_snippet);
1211        }
1212
1213        // The type of a parenthesized pattern isn't a tuple type. A one element
1214        // tuple on the other hand keeps its trailing comma on both sides.
1215        let (suggestion, msg) = if paren_pattern {
1216            (
1217                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("({0}): {1}", pat_snippets[0],
                ty_snippets[0]))
    })format!("({}): {}", pat_snippets[0], ty_snippets[0]),
1218                "write the type after the pattern",
1219            )
1220        } else {
1221            let trailing = if fields.len() == 1 { "," } else { "" };
1222            (
1223                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("({0}{2}): ({1}{2})",
                pat_snippets.join(", "), ty_snippets.join(", "), trailing))
    })format!(
1224                    "({}{trailing}): ({}{trailing})",
1225                    pat_snippets.join(", "),
1226                    ty_snippets.join(", ")
1227                ),
1228                "to annotate the types of a tuple's elements, write them as a tuple type after \
1229                 the pattern",
1230            )
1231        };
1232        err.span_suggestion_verbose(
1233            open_paren.to(close_paren),
1234            msg,
1235            suggestion,
1236            Applicability::MaybeIncorrect,
1237        );
1238    }
1239
1240    /// Parse a mutable binding with the `mut` token already eaten.
1241    fn parse_pat_ident_mut(&mut self) -> PResult<'a, PatKind> {
1242        let mut_span = self.prev_token.span;
1243
1244        self.recover_additional_muts();
1245
1246        let byref = self.parse_byref();
1247
1248        self.recover_additional_muts();
1249
1250        // Make sure we don't allow e.g. `let mut $p;` where `$p:pat`.
1251        if let Some(MetaVarKind::Pat(_)) = self.token.is_metavar_seq() {
1252            self.expected_ident_found_err().emit();
1253        }
1254
1255        // Parse the pattern we hope to be an identifier.
1256        let mut pat = self.parse_pat_no_top_alt(Some(Expected::Identifier), None)?;
1257
1258        // If we don't have `mut $ident (@ pat)?`, error.
1259        if let PatKind::Ident(BindingMode(br @ ByRef::No, m @ Mutability::Not), ..) = &mut pat.kind
1260        {
1261            // Don't recurse into the subpattern.
1262            // `mut` on the outer binding doesn't affect the inner bindings.
1263            *br = byref;
1264            *m = Mutability::Mut;
1265        } else {
1266            // Add `mut` to any binding in the parsed pattern.
1267            let changed_any_binding = Self::make_all_value_bindings_mutable(&mut pat);
1268            self.ban_mut_general_pat(mut_span, &pat, changed_any_binding);
1269        }
1270
1271        if #[allow(non_exhaustive_omitted_patterns)] match pat.kind {
    PatKind::Ident(BindingMode(ByRef::Yes(..), Mutability::Mut), ..) => true,
    _ => false,
}matches!(pat.kind, PatKind::Ident(BindingMode(ByRef::Yes(..), Mutability::Mut), ..)) {
1272            self.psess.gated_spans.gate(sym::mut_ref, pat.span);
1273        }
1274        Ok(pat.kind)
1275    }
1276
1277    /// Turn all by-value immutable bindings in a pattern into mutable bindings.
1278    /// Returns `true` if any change was made.
1279    fn make_all_value_bindings_mutable(pat: &mut Pat) -> bool {
1280        struct AddMut(bool);
1281        impl MutVisitor for AddMut {
1282            fn visit_pat(&mut self, pat: &mut Pat) {
1283                if let PatKind::Ident(BindingMode(ByRef::No, m @ Mutability::Not), ..) =
1284                    &mut pat.kind
1285                {
1286                    self.0 = true;
1287                    *m = Mutability::Mut;
1288                }
1289                mut_visit::walk_pat(self, pat);
1290            }
1291        }
1292
1293        let mut add_mut = AddMut(false);
1294        add_mut.visit_pat(pat);
1295        add_mut.0
1296    }
1297
1298    /// Error on `mut $pat` where `$pat` is not an ident.
1299    fn ban_mut_general_pat(&self, lo: Span, pat: &Pat, changed_any_binding: bool) {
1300        self.dcx().emit_err(if changed_any_binding {
1301            InvalidMutInPattern::NestedIdent {
1302                span: lo.to(pat.span),
1303                pat: pprust::pat_to_string(pat),
1304            }
1305        } else {
1306            InvalidMutInPattern::NonIdent { span: lo.until(pat.span) }
1307        });
1308    }
1309
1310    /// Eat any extraneous `mut`s and error + recover if we ate any.
1311    fn recover_additional_muts(&mut self) {
1312        let lo = self.token.span;
1313        while self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Mut,
    token_type: crate::parser::token_type::TokenType::KwMut,
}exp!(Mut)) {}
1314        if lo == self.token.span {
1315            return;
1316        }
1317
1318        let span = lo.to(self.prev_token.span);
1319        let suggestion = span.with_hi(self.token.span.lo());
1320        self.dcx().emit_err(RepeatedMutInPattern { span, suggestion });
1321    }
1322
1323    /// Parse macro invocation
1324    fn parse_pat_mac_invoc(&mut self, path: Path) -> PResult<'a, PatKind> {
1325        self.bump();
1326        let args = self.parse_delim_args()?;
1327        let mac = Box::new(MacCall { path, args });
1328        Ok(PatKind::MacCall(mac))
1329    }
1330
1331    fn fatal_unexpected_non_pat(
1332        &mut self,
1333        err: Diag<'a>,
1334        expected: Option<Expected>,
1335    ) -> PResult<'a, Pat> {
1336        err.cancel();
1337
1338        let expected = Expected::to_string_or_fallback(expected);
1339        let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected {0}, found {1}", expected,
                super::token_descr(&self.token)))
    })format!("expected {}, found {}", expected, super::token_descr(&self.token));
1340
1341        let mut err = self.dcx().struct_span_err(self.token.span, msg);
1342        err.span_label(self.token.span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected {0}", expected))
    })format!("expected {expected}"));
1343
1344        let sp = self.psess.source_map().start_point(self.token.span);
1345        if let Some(sp) = self.psess.complete_stmt_exprs_before_bin_op_lookalike.borrow().get(&sp) {
1346            err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp));
1347        }
1348
1349        Err(err)
1350    }
1351
1352    /// Parses the range pattern end form `".." | "..." | "..=" ;`.
1353    fn parse_range_end(&mut self) -> Option<Spanned<RangeEnd>> {
1354        let re = if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::DotDotDot,
    token_type: crate::parser::token_type::TokenType::DotDotDot,
}exp!(DotDotDot)) {
1355            RangeEnd::Included(RangeSyntax::DotDotDot)
1356        } else if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::DotDotEq,
    token_type: crate::parser::token_type::TokenType::DotDotEq,
}exp!(DotDotEq)) {
1357            RangeEnd::Included(RangeSyntax::DotDotEq)
1358        } else if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::DotDot,
    token_type: crate::parser::token_type::TokenType::DotDot,
}exp!(DotDot)) {
1359            RangeEnd::Excluded
1360        } else {
1361            return None;
1362        };
1363        Some(respan(self.prev_token.span, re))
1364    }
1365
1366    /// Parse a range pattern `$begin $form $end?` where `$form = ".." | "..." | "..=" ;`.
1367    /// `$begin $form` has already been parsed.
1368    fn parse_pat_range_begin_with(
1369        &mut self,
1370        begin: Box<Expr>,
1371        re: Spanned<RangeEnd>,
1372    ) -> PResult<'a, PatKind> {
1373        let end = if self.is_pat_range_end_start(0) {
1374            // Parsing e.g. `X..=Y`.
1375            Some(self.parse_pat_range_end()?)
1376        } else {
1377            // Parsing e.g. `X..`.
1378            if let RangeEnd::Included(_) = re.node {
1379                // FIXME(Centril): Consider semantic errors instead in `ast_validation`.
1380                self.inclusive_range_with_incorrect_end();
1381            }
1382            None
1383        };
1384        Ok(PatKind::Range(Some(begin), end, re))
1385    }
1386
1387    pub(super) fn inclusive_range_with_incorrect_end(&mut self) -> ErrorGuaranteed {
1388        let tok = &self.token;
1389        let span = self.prev_token.span;
1390        // If the user typed "..==" or "...=" instead of "..=", we want to give them
1391        // a specific error message telling them to use "..=".
1392        // If they typed "..=>", suggest they use ".. =>".
1393        // Otherwise, we assume that they meant to type a half open exclusive
1394        // range and give them an error telling them to do that instead.
1395        let no_space = tok.span.lo() == span.hi();
1396        match tok.kind {
1397            token::Eq if no_space => {
1398                let span_with_eq = span.to(tok.span);
1399
1400                // Ensure the user doesn't receive unhelpful unexpected token errors
1401                self.bump();
1402                if self.is_pat_range_end_start(0) {
1403                    let _ = self.parse_pat_range_end().map_err(|e| e.cancel());
1404                }
1405
1406                self.dcx().emit_err(InclusiveRangeExtraEquals { span: span_with_eq })
1407            }
1408            token::Gt if self.prev_token.kind == token::DotDotEq && no_space => {
1409                self.dcx().emit_err(InclusiveRangeMatchArrow { span, arrow: tok.span })
1410            }
1411            _ => self.dcx().emit_err(InclusiveRangeNoEnd { span }),
1412        }
1413    }
1414
1415    /// Parse a range-to pattern, `..X` or `..=X` where `X` remains to be parsed.
1416    ///
1417    /// The form `...X` is prohibited to reduce confusion with the potential
1418    /// expression syntax `...expr` for splatting in expressions.
1419    fn parse_pat_range_to(&mut self, mut re: Spanned<RangeEnd>) -> PResult<'a, PatKind> {
1420        let end = self.parse_pat_range_end()?;
1421        if let RangeEnd::Included(syn @ RangeSyntax::DotDotDot) = &mut re.node {
1422            *syn = RangeSyntax::DotDotEq;
1423            self.dcx().emit_err(DotDotDotRangeToPatternNotAllowed { span: re.span });
1424        }
1425        Ok(PatKind::Range(None, Some(end), re))
1426    }
1427
1428    /// Is the token `dist` away from the current suitable as the start of a range patterns end?
1429    fn is_pat_range_end_start(&self, dist: usize) -> bool {
1430        self.check_inline_const(dist)
1431            || self.look_ahead(dist, |t| {
1432                t.is_path_start() // e.g. `MY_CONST`;
1433                || *t == token::Dot // e.g. `.5` for recovery;
1434                || #[allow(non_exhaustive_omitted_patterns)] match t.kind {
    token::Literal(..) | token::Minus => true,
    _ => false,
}matches!(t.kind, token::Literal(..) | token::Minus)
1435                || t.is_bool_lit()
1436                || t.is_metavar_expr()
1437                || t.is_lifetime() // recover `'a` instead of `'a'`
1438                || (self.may_recover() // recover leading `(`
1439                    && *t == token::OpenParen
1440                    && self.look_ahead(dist + 1, |t| *t != token::OpenParen)
1441                    && self.is_pat_range_end_start(dist + 1))
1442            })
1443    }
1444
1445    /// Parse a range pattern end bound
1446    fn parse_pat_range_end(&mut self) -> PResult<'a, Box<Expr>> {
1447        // recover leading `(`
1448        let open_paren = (self.may_recover() && self.eat_noexpect(&token::OpenParen))
1449            .then_some(self.prev_token.span);
1450
1451        let bound = if self.check_inline_const(0) {
1452            self.parse_const_block(self.token.span, true)
1453        } else if self.check_path() {
1454            let lo = self.token.span;
1455            let (qself, path) = if self.eat_lt() {
1456                // Parse a qualified path
1457                let (qself, path) = self.parse_qpath(PathStyle::Pat)?;
1458                (Some(qself), path)
1459            } else {
1460                // Parse an unqualified path
1461                (None, self.parse_path(PathStyle::Pat)?)
1462            };
1463            let hi = self.prev_token.span;
1464            Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path)))
1465        } else {
1466            self.parse_literal_maybe_minus()
1467        }?;
1468
1469        let recovered = self.maybe_recover_trailing_expr(bound.span, true);
1470
1471        // recover trailing `)`
1472        if let Some(open_paren) = open_paren {
1473            self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseParen,
    token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen))?;
1474
1475            self.dcx().emit_err(UnexpectedParenInRangePat {
1476                span: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [open_paren, self.prev_token.span]))vec![open_paren, self.prev_token.span],
1477                sugg: UnexpectedParenInRangePatSugg {
1478                    start_span: open_paren,
1479                    end_span: self.prev_token.span,
1480                },
1481            });
1482        }
1483
1484        Ok(match recovered {
1485            Some((guar, sp)) => self.mk_expr_err(sp, guar),
1486            None => bound,
1487        })
1488    }
1489
1490    /// Is this the start of a pattern beginning with a path?
1491    fn is_start_of_pat_with_path(&mut self) -> bool {
1492        self.check_path()
1493        // Just for recovery (see `can_be_ident`).
1494        || self.token.is_ident() && !self.token.is_bool_lit() && !self.token.is_keyword(kw::In)
1495    }
1496
1497    /// Would `parse_pat_ident` be appropriate here?
1498    fn can_be_ident_pat(&mut self) -> bool {
1499        self.check_ident()
1500        && !self.token.is_bool_lit() // Avoid `true` or `false` as a binding as it is a literal.
1501        && !self.token.is_path_segment_keyword() // Avoid e.g. `Self` as it is a path.
1502        // Avoid `in`. Due to recovery in the list parser this messes with `for ( $pat in $expr )`.
1503        && !self.token.is_keyword(kw::In)
1504        // Try to do something more complex?
1505        && self.look_ahead(1, |t| !#[allow(non_exhaustive_omitted_patterns)] match t.kind {
    token::OpenParen | token::OpenBrace | token::DotDotDot | token::DotDotEq |
        token::DotDot | token::PathSep | token::Bang => true,
    _ => false,
}matches!(t.kind, token::OpenParen // A tuple struct pattern.
1506            | token::OpenBrace // A struct pattern.
1507            | token::DotDotDot | token::DotDotEq | token::DotDot // A range pattern.
1508            | token::PathSep // A tuple / struct variant pattern.
1509            | token::Bang)) // A macro expanding to a pattern.
1510    }
1511
1512    /// Parses `ident` or `ident @ pat`.
1513    /// Used by the copy foo and ref foo patterns to give a good
1514    /// error message when parsing mistakes like `ref foo(a, b)`.
1515    fn parse_pat_ident(
1516        &mut self,
1517        binding_annotation: BindingMode,
1518        syntax_loc: Option<PatternLocation>,
1519    ) -> PResult<'a, PatKind> {
1520        let ident = self.parse_ident_common(false)?;
1521
1522        if self.may_recover()
1523            && !#[allow(non_exhaustive_omitted_patterns)] match syntax_loc {
    Some(PatternLocation::FunctionParameter) => true,
    _ => false,
}matches!(syntax_loc, Some(PatternLocation::FunctionParameter))
1524            && self.check_noexpect(&token::Lt)
1525            && self.look_ahead(1, |t| t.can_begin_type())
1526        {
1527            return Err(self.dcx().create_err(GenericArgsInPatRequireTurbofishSyntax {
1528                span: self.token.span,
1529                suggest_turbofish: self.token.span.shrink_to_lo(),
1530            }));
1531        }
1532
1533        let sub = if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::At,
    token_type: crate::parser::token_type::TokenType::At,
}exp!(At)) {
1534            Some(Box::new(self.parse_pat_no_top_alt(Some(Expected::BindingPattern), None)?))
1535        } else {
1536            None
1537        };
1538
1539        // Just to be friendly, if they write something like `ref Some(i)`,
1540        // we end up here with `(` as the current token.
1541        // This shortly leads to a parse error. Note that if there is no explicit
1542        // binding mode then we do not end up here, because the lookahead
1543        // will direct us over to `parse_enum_variant()`.
1544        if self.token == token::OpenParen {
1545            return Err(self
1546                .dcx()
1547                .create_err(EnumPatternInsteadOfIdentifier { span: self.prev_token.span }));
1548        }
1549
1550        // Check for method calls after the `ident`,
1551        // but not `ident @ subpat` as `subpat` was already checked and `ident` continues with `@`.
1552
1553        let pat = if sub.is_none()
1554            && let Some((guar, _)) = self.maybe_recover_trailing_expr(ident.span, false)
1555        {
1556            PatKind::Err(guar)
1557        } else {
1558            PatKind::Ident(binding_annotation, ident, sub)
1559        };
1560        Ok(pat)
1561    }
1562
1563    /// Parse a struct ("record") pattern (e.g. `Foo { ... }` or `Foo::Bar { ... }`).
1564    fn parse_pat_struct(&mut self, qself: Option<Box<QSelf>>, path: Path) -> PResult<'a, PatKind> {
1565        if qself.is_some() {
1566            // Feature gate the use of qualified paths in patterns
1567            self.psess.gated_spans.gate(sym::more_qualified_paths, path.span);
1568        }
1569        self.bump();
1570        let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
1571            e.span_label(path.span, "while parsing the fields for this pattern");
1572            let guar = e.emit_err();
1573            self.recover_stmt();
1574            // When recovering, pretend we had `Foo { .. }`, to avoid cascading errors.
1575            (ThinVec::new(), PatFieldsRest::Recovered(guar))
1576        });
1577        self.bump();
1578        Ok(PatKind::Struct(qself, path, fields, etc))
1579    }
1580
1581    /// Parse tuple struct or tuple variant pattern (e.g. `Foo(...)` or `Foo::Bar(...)`).
1582    fn parse_pat_tuple_struct(
1583        &mut self,
1584        qself: Option<Box<QSelf>>,
1585        path: Path,
1586    ) -> PResult<'a, PatKind> {
1587        let (fields, _) = self.parse_paren_comma_seq(|p| {
1588            p.parse_pat_allow_top_guard(
1589                None,
1590                RecoverComma::No,
1591                RecoverColon::No,
1592                CommaRecoveryMode::EitherTupleOrPipe,
1593            )
1594        })?;
1595        if qself.is_some() {
1596            self.psess.gated_spans.gate(sym::more_qualified_paths, path.span);
1597        }
1598        Ok(PatKind::TupleStruct(qself, path, fields))
1599    }
1600
1601    /// Are we sure this could not possibly be the start of a pattern?
1602    ///
1603    /// Currently, this only accounts for tokens that can follow identifiers
1604    /// in patterns, but this can be extended as necessary.
1605    fn isnt_pattern_start(&self) -> bool {
1606        [
1607            token::Eq,
1608            token::Colon,
1609            token::Comma,
1610            token::Semi,
1611            token::At,
1612            token::OpenBrace,
1613            token::CloseBrace,
1614            token::CloseParen,
1615        ]
1616        .contains(&self.token.kind)
1617    }
1618
1619    // FIXME: remove this entirely eventually
1620    /// Parses the removed `box pat` syntax to provide a more helpful error message.
1621    fn parse_pat_box(&mut self) -> PResult<'a, PatKind> {
1622        let box_span = self.prev_token.span;
1623
1624        if self.isnt_pattern_start() {
1625            let descr = super::token_descr(&self.token);
1626            self.dcx().emit_err(diagnostics::BoxNotPat {
1627                span: self.token.span,
1628                kw: box_span,
1629                lo: box_span.shrink_to_lo(),
1630                descr,
1631            });
1632
1633            // We cannot use `parse_pat_ident()` since it will complain `box`
1634            // is not an identifier.
1635            let sub = if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::At,
    token_type: crate::parser::token_type::TokenType::At,
}exp!(At)) {
1636                Some(Box::new(self.parse_pat_no_top_alt(Some(Expected::BindingPattern), None)?))
1637            } else {
1638                None
1639            };
1640
1641            Ok(PatKind::Ident(BindingMode::NONE, Ident::new(kw::Box, box_span), sub))
1642        } else {
1643            let pat = Box::new(self.parse_pat_with_range_pat(false, None, None)?);
1644            let before_span = box_span.until(pat.span);
1645            self.dcx().emit_err(diagnostics::BoxPatsRemoved {
1646                span: box_span,
1647                sugg_deref_macro_call: diagnostics::UseDerefMacro {
1648                    field: None,
1649                    before: before_span,
1650                    after: pat.span.shrink_to_hi(),
1651                },
1652                sugg_removal: before_span,
1653            });
1654            // Treat the box pattern like a deref pattern to avoid lots of "value not found" errors.
1655            Ok(PatKind::Deref(pat))
1656        }
1657    }
1658
1659    /// Parses the fields of a struct-like pattern.
1660    fn parse_pat_fields(&mut self) -> PResult<'a, (ThinVec<PatField>, PatFieldsRest)> {
1661        let mut fields: ThinVec<PatField> = ThinVec::new();
1662        let mut etc = PatFieldsRest::None;
1663        let mut ate_comma = true;
1664        let mut delayed_err: Option<Diag<'a>> = None;
1665        let mut first_etc_and_maybe_comma_span = None;
1666        let mut last_non_comma_dotdot_span = None;
1667
1668        while self.token != token::CloseBrace {
1669            // check that a comma comes after every field
1670            if !ate_comma {
1671                let err = if self.token == token::At {
1672                    let prev_field = fields
1673                        .last()
1674                        .expect("Unreachable on first iteration, not empty otherwise")
1675                        .ident;
1676                    self.report_misplaced_at_in_struct_pat(prev_field)
1677                } else {
1678                    let mut err = self
1679                        .dcx()
1680                        .create_err(ExpectedCommaAfterPatternField { span: self.token.span });
1681                    self.recover_misplaced_pattern_modifiers(&fields, &mut err);
1682                    err
1683                };
1684                if let Some(delayed) = delayed_err {
1685                    delayed.emit();
1686                }
1687                return Err(err);
1688            }
1689            ate_comma = false;
1690
1691            if self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::DotDot,
    token_type: crate::parser::token_type::TokenType::DotDot,
}exp!(DotDot))
1692                || self.check_noexpect(&token::DotDotDot)
1693                || self.check_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Underscore,
    token_type: crate::parser::token_type::TokenType::KwUnderscore,
}exp!(Underscore))
1694            {
1695                etc = PatFieldsRest::Rest(self.token.span);
1696                let mut etc_sp = self.token.span;
1697                if first_etc_and_maybe_comma_span.is_none() {
1698                    if let Some(comma_tok) =
1699                        self.look_ahead(1, |&t| if t == token::Comma { Some(t) } else { None })
1700                    {
1701                        let nw_span = self
1702                            .psess
1703                            .source_map()
1704                            .span_extend_to_line(comma_tok.span)
1705                            .trim_start(comma_tok.span.shrink_to_lo())
1706                            .map(|s| self.psess.source_map().span_until_non_whitespace(s));
1707                        first_etc_and_maybe_comma_span = nw_span.map(|s| etc_sp.to(s));
1708                    } else {
1709                        first_etc_and_maybe_comma_span =
1710                            Some(self.psess.source_map().span_until_non_whitespace(etc_sp));
1711                    }
1712                }
1713
1714                self.recover_bad_dot_dot();
1715                self.bump(); // `..` || `...` || `_`
1716
1717                if self.token == token::CloseBrace {
1718                    break;
1719                }
1720                let token_str = super::token_descr(&self.token);
1721                let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected `}}`, found {0}",
                token_str))
    })format!("expected `}}`, found {token_str}");
1722                let mut err = self.dcx().struct_span_err(self.token.span, msg);
1723
1724                err.span_label(self.token.span, "expected `}`");
1725                let mut comma_sp = None;
1726                if self.token == token::Comma {
1727                    // Issue #49257
1728                    let nw_span =
1729                        self.psess.source_map().span_until_non_whitespace(self.token.span);
1730                    etc_sp = etc_sp.to(nw_span);
1731                    err.span_label(
1732                        etc_sp,
1733                        "`..` must be at the end and cannot have a trailing comma",
1734                    );
1735                    comma_sp = Some(self.token.span);
1736                    self.bump();
1737                    ate_comma = true;
1738                }
1739
1740                if self.token == token::CloseBrace {
1741                    // If the struct looks otherwise well formed, recover and continue.
1742                    if let Some(sp) = comma_sp {
1743                        err.span_suggestion_short(
1744                            sp,
1745                            "remove this comma",
1746                            "",
1747                            Applicability::MachineApplicable,
1748                        );
1749                    }
1750                    err.emit();
1751                    break;
1752                } else if self.token.is_ident() && ate_comma {
1753                    // Accept fields coming after `..,`.
1754                    // This way we avoid "pattern missing fields" errors afterwards.
1755                    // We delay this error until the end in order to have a span for a
1756                    // suggested fix.
1757                    if let Some(delayed_err) = delayed_err {
1758                        delayed_err.emit();
1759                        return Err(err);
1760                    } else {
1761                        delayed_err = Some(err);
1762                    }
1763                } else {
1764                    if let Some(err) = delayed_err {
1765                        err.emit();
1766                    }
1767                    return Err(err);
1768                }
1769            }
1770
1771            let attrs = match self.parse_outer_attributes() {
1772                Ok(attrs) => attrs,
1773                Err(err) => {
1774                    if let Some(delayed) = delayed_err {
1775                        delayed.emit();
1776                    }
1777                    return Err(err);
1778                }
1779            };
1780            let lo = self.token.span;
1781
1782            let field = self.collect_tokens(None, attrs, ForceCollect::No, |this, attrs| {
1783                let field = match this.parse_pat_field(lo, attrs) {
1784                    Ok(field) => Ok(field),
1785                    Err(err) => {
1786                        if let Some(delayed_err) = delayed_err.take() {
1787                            delayed_err.emit();
1788                        }
1789                        return Err(err);
1790                    }
1791                }?;
1792                ate_comma = this.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma));
1793
1794                last_non_comma_dotdot_span = Some(this.prev_token.span);
1795
1796                // We just ate a comma, so there's no need to capture a trailing token.
1797                Ok((field, Trailing::No, UsePreAttrPos::No))
1798            })?;
1799
1800            fields.push(field)
1801        }
1802
1803        if let Some(mut err) = delayed_err {
1804            if let Some(first_etc_span) = first_etc_and_maybe_comma_span {
1805                if self.prev_token == token::DotDot {
1806                    // We have `.., x, ..`.
1807                    err.multipart_suggestion(
1808                        "remove the starting `..`",
1809                        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(first_etc_span, String::new())]))vec![(first_etc_span, String::new())],
1810                        Applicability::MachineApplicable,
1811                    );
1812                } else if let Some(last_non_comma_dotdot_span) = last_non_comma_dotdot_span {
1813                    // We have `.., x`.
1814                    err.multipart_suggestion(
1815                        "move the `..` to the end of the field list",
1816                        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(first_etc_span, String::new()),
                (self.token.span.to(last_non_comma_dotdot_span.shrink_to_hi()),
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("{0} .. }}",
                                    if ate_comma { "" } else { "," }))
                        }))]))vec![
1817                            (first_etc_span, String::new()),
1818                            (
1819                                self.token.span.to(last_non_comma_dotdot_span.shrink_to_hi()),
1820                                format!("{} .. }}", if ate_comma { "" } else { "," }),
1821                            ),
1822                        ],
1823                        Applicability::MachineApplicable,
1824                    );
1825                }
1826            }
1827            err.emit();
1828        }
1829        Ok((fields, etc))
1830    }
1831
1832    fn report_misplaced_at_in_struct_pat(&self, prev_field: Ident) -> Diag<'a> {
1833        if true {
    {
        match (&self.token, &token::At) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    let kind = ::core::panicking::AssertKind::Eq;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val, ::core::option::Option::None);
                }
            }
        }
    };
};debug_assert_eq!(self.token, token::At);
1834        let span = prev_field.span.to(self.token.span);
1835        if let Some(dot_dot_span) =
1836            self.look_ahead(1, |t| if t == &token::DotDot { Some(t.span) } else { None })
1837        {
1838            self.dcx().create_err(AtDotDotInStructPattern {
1839                span: span.to(dot_dot_span),
1840                remove: span.until(dot_dot_span),
1841                ident: prev_field,
1842            })
1843        } else {
1844            self.dcx().create_err(AtInStructPattern { span })
1845        }
1846    }
1847
1848    /// If the user writes `S { ref field: name }` instead of `S { field: ref name }`, we suggest
1849    /// the correct code.
1850    fn recover_misplaced_pattern_modifiers(&self, fields: &ThinVec<PatField>, err: &mut Diag<'a>) {
1851        if let Some(last) = fields.last()
1852            && last.is_shorthand
1853            && let PatKind::Ident(binding, ident, None) = last.pat.kind
1854            && binding != BindingMode::NONE
1855            && self.token == token::Colon
1856            // We found `ref mut? ident:`, try to parse a `name,` or `name }`.
1857            && let Some(name_span) = self.look_ahead(1, |t| t.is_ident().then(|| t.span))
1858            && self.look_ahead(2, |t| {
1859                t == &token::Comma || t == &token::CloseBrace
1860            })
1861        {
1862            let span = last.pat.span.with_hi(ident.span.lo());
1863            // We have `S { ref field: name }` instead of `S { field: ref name }`
1864            err.multipart_suggestion(
1865                "the pattern modifiers belong after the `:`",
1866                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(span, String::new()),
                (name_span.shrink_to_lo(),
                    binding.prefix_str().to_string())]))vec![
1867                    (span, String::new()),
1868                    (name_span.shrink_to_lo(), binding.prefix_str().to_string()),
1869                ],
1870                Applicability::MachineApplicable,
1871            );
1872        }
1873    }
1874
1875    /// Recover on `...` or `_` as if it were `..` to avoid further errors.
1876    /// See issue #46718.
1877    fn recover_bad_dot_dot(&self) {
1878        if self.token == token::DotDot {
1879            return;
1880        }
1881
1882        let token_str = pprust::token_to_string(&self.token);
1883        self.dcx().emit_err(DotDotDotForRemainingFields { span: self.token.span, token_str });
1884    }
1885
1886    /// Parse a field in a struct pattern.
1887    ///
1888    /// ```ebnf
1889    /// PatField = FieldName ":" Pat | "mut"? ByRef? Ident
1890    /// ```
1891    fn parse_pat_field(&mut self, lo: Span, attrs: AttrVec) -> PResult<'a, PatField> {
1892        let hi;
1893        let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
1894            let fieldname = self.parse_field_name()?;
1895            self.bump();
1896            let pat = self.parse_pat_allow_top_guard(
1897                None,
1898                RecoverComma::No,
1899                RecoverColon::No,
1900                CommaRecoveryMode::EitherTupleOrPipe,
1901            )?;
1902            hi = pat.span;
1903            (pat, fieldname, false)
1904        } else {
1905            // FIXME: remove the recovery for parsing box patterrns entirely
1906            let is_box = if self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Box,
    token_type: crate::parser::token_type::TokenType::KwBox,
}exp!(Box)) {
1907                let span = self.prev_token.span;
1908                self.dcx().span_delayed_bug(span, "box patterns have been removed");
1909                Some(span)
1910            } else {
1911                None
1912            };
1913            let boxed_span = self.token.span;
1914            let mutability = self.parse_mutability();
1915            let by_ref = self.parse_byref();
1916
1917            let fieldname = self.parse_ident_common(false)?;
1918            hi = self.prev_token.span;
1919            let ann = BindingMode(by_ref, mutability);
1920            let fieldpat = self.mk_pat_ident(boxed_span.to(hi), ann, fieldname);
1921            if #[allow(non_exhaustive_omitted_patterns)] match fieldpat.kind {
    PatKind::Ident(BindingMode(ByRef::Yes(..), Mutability::Mut), ..) => true,
    _ => false,
}matches!(
1922                fieldpat.kind,
1923                PatKind::Ident(BindingMode(ByRef::Yes(..), Mutability::Mut), ..)
1924            ) {
1925                self.psess.gated_spans.gate(sym::mut_ref, fieldpat.span);
1926            }
1927            let subpat = if let Some(box_span) = is_box {
1928                let prefix_span = box_span.until(boxed_span);
1929
1930                self.dcx().emit_err(diagnostics::BoxPatsRemoved {
1931                    span: box_span,
1932                    sugg_deref_macro_call: diagnostics::UseDerefMacro {
1933                        field: Some((prefix_span, fieldname)),
1934                        before: boxed_span.shrink_to_lo(),
1935                        after: hi.shrink_to_hi(),
1936                    },
1937                    sugg_removal: prefix_span,
1938                });
1939
1940                self.mk_pat(lo.to(hi), PatKind::Deref(Box::new(fieldpat)))
1941            } else {
1942                fieldpat
1943            };
1944            (subpat, fieldname, true)
1945        };
1946
1947        Ok(PatField {
1948            ident: fieldname,
1949            pat: Box::new(subpat),
1950            is_shorthand,
1951            attrs,
1952            id: ast::DUMMY_NODE_ID,
1953            span: lo.to(hi),
1954            is_placeholder: false,
1955        })
1956    }
1957
1958    pub(super) fn mk_pat_ident(&self, span: Span, ann: BindingMode, ident: Ident) -> Pat {
1959        self.mk_pat(span, PatKind::Ident(ann, ident, None))
1960    }
1961
1962    pub(super) fn mk_pat(&self, span: Span, kind: PatKind) -> Pat {
1963        Pat { kind, span, id: ast::DUMMY_NODE_ID }
1964    }
1965}