rustc_parse/parser/
pat.rs

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