rustc_parse/parser/
pat.rs

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