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