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