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