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