rustc_hir_typeck/
pat.rs

1use std::cmp;
2use std::collections::hash_map::Entry::{Occupied, Vacant};
3
4use rustc_abi::FieldIdx;
5use rustc_ast as ast;
6use rustc_data_structures::fx::FxHashMap;
7use rustc_errors::codes::*;
8use rustc_errors::{
9    Applicability, Diag, ErrorGuaranteed, MultiSpan, pluralize, struct_span_code_err,
10};
11use rustc_hir::def::{CtorKind, DefKind, Res};
12use rustc_hir::def_id::DefId;
13use rustc_hir::pat_util::EnumerateAndAdjustIterator;
14use rustc_hir::{
15    self as hir, BindingMode, ByRef, ExprKind, HirId, LangItem, Mutability, Pat, PatExpr,
16    PatExprKind, PatKind, expr_needs_parens,
17};
18use rustc_hir_analysis::autoderef::report_autoderef_recursion_limit_error;
19use rustc_infer::infer::RegionVariableOrigin;
20use rustc_middle::traits::PatternOriginExpr;
21use rustc_middle::ty::{self, Ty, TypeVisitableExt};
22use rustc_middle::{bug, span_bug};
23use rustc_session::lint::builtin::NON_EXHAUSTIVE_OMITTED_PATTERNS;
24use rustc_session::parse::feature_err;
25use rustc_span::edit_distance::find_best_match_for_name;
26use rustc_span::edition::Edition;
27use rustc_span::source_map::Spanned;
28use rustc_span::{BytePos, DUMMY_SP, Ident, Span, kw, sym};
29use rustc_trait_selection::infer::InferCtxtExt;
30use rustc_trait_selection::traits::{ObligationCause, ObligationCauseCode};
31use tracing::{debug, instrument, trace};
32use ty::VariantDef;
33use ty::adjustment::{PatAdjust, PatAdjustment};
34
35use super::report_unexpected_variant_res;
36use crate::expectation::Expectation;
37use crate::gather_locals::DeclOrigin;
38use crate::{FnCtxt, errors};
39
40const CANNOT_IMPLICITLY_DEREF_POINTER_TRAIT_OBJ: &str = "\
41This error indicates that a pointer to a trait type cannot be implicitly dereferenced by a \
42pattern. Every trait defines a type, but because the size of trait implementors isn't fixed, \
43this type has no compile-time size. Therefore, all accesses to trait types must be through \
44pointers. If you encounter this error you should try to avoid dereferencing the pointer.
45
46You can read more about trait objects in the Trait Objects section of the Reference: \
47https://doc.rust-lang.org/reference/types.html#trait-objects";
48
49fn is_number(text: &str) -> bool {
50    text.chars().all(|c: char| c.is_ascii_digit())
51}
52
53/// Information about the expected type at the top level of type checking a pattern.
54///
55/// **NOTE:** This is only for use by diagnostics. Do NOT use for type checking logic!
56#[derive(Copy, Clone)]
57struct TopInfo<'tcx> {
58    /// The `expected` type at the top level of type checking a pattern.
59    expected: Ty<'tcx>,
60    /// Was the origin of the `span` from a scrutinee expression?
61    ///
62    /// Otherwise there is no scrutinee and it could be e.g. from the type of a formal parameter.
63    origin_expr: Option<&'tcx hir::Expr<'tcx>>,
64    /// The span giving rise to the `expected` type, if one could be provided.
65    ///
66    /// If `origin_expr` is `true`, then this is the span of the scrutinee as in:
67    ///
68    /// - `match scrutinee { ... }`
69    /// - `let _ = scrutinee;`
70    ///
71    /// This is used to point to add context in type errors.
72    /// In the following example, `span` corresponds to the `a + b` expression:
73    ///
74    /// ```text
75    /// error[E0308]: mismatched types
76    ///  --> src/main.rs:L:C
77    ///   |
78    /// L |    let temp: usize = match a + b {
79    ///   |                            ----- this expression has type `usize`
80    /// L |         Ok(num) => num,
81    ///   |         ^^^^^^^ expected `usize`, found enum `std::result::Result`
82    ///   |
83    ///   = note: expected type `usize`
84    ///              found type `std::result::Result<_, _>`
85    /// ```
86    span: Option<Span>,
87    /// The [`HirId`] of the top-level pattern.
88    hir_id: HirId,
89}
90
91#[derive(Copy, Clone)]
92struct PatInfo<'tcx> {
93    binding_mode: ByRef,
94    max_ref_mutbl: MutblCap,
95    top_info: TopInfo<'tcx>,
96    decl_origin: Option<DeclOrigin<'tcx>>,
97
98    /// The depth of current pattern
99    current_depth: u32,
100}
101
102impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
103    fn pattern_cause(&self, ti: &TopInfo<'tcx>, cause_span: Span) -> ObligationCause<'tcx> {
104        // If origin_expr exists, then expected represents the type of origin_expr.
105        // If span also exists, then span == origin_expr.span (although it doesn't need to exist).
106        // In that case, we can peel away references from both and treat them
107        // as the same.
108        let origin_expr_info = ti.origin_expr.map(|mut cur_expr| {
109            let mut count = 0;
110
111            // cur_ty may have more layers of references than cur_expr.
112            // We can only make suggestions about cur_expr, however, so we'll
113            // use that as our condition for stopping.
114            while let ExprKind::AddrOf(.., inner) = &cur_expr.kind {
115                cur_expr = inner;
116                count += 1;
117            }
118
119            PatternOriginExpr {
120                peeled_span: cur_expr.span,
121                peeled_count: count,
122                peeled_prefix_suggestion_parentheses: expr_needs_parens(cur_expr),
123            }
124        });
125
126        let code = ObligationCauseCode::Pattern {
127            span: ti.span,
128            root_ty: ti.expected,
129            origin_expr: origin_expr_info,
130        };
131        self.cause(cause_span, code)
132    }
133
134    fn demand_eqtype_pat_diag(
135        &'a self,
136        cause_span: Span,
137        expected: Ty<'tcx>,
138        actual: Ty<'tcx>,
139        ti: &TopInfo<'tcx>,
140    ) -> Result<(), Diag<'a>> {
141        self.demand_eqtype_with_origin(&self.pattern_cause(ti, cause_span), expected, actual)
142            .map_err(|mut diag| {
143                if let Some(expr) = ti.origin_expr {
144                    self.suggest_fn_call(&mut diag, expr, expected, |output| {
145                        self.can_eq(self.param_env, output, actual)
146                    });
147                }
148                diag
149            })
150    }
151
152    fn demand_eqtype_pat(
153        &self,
154        cause_span: Span,
155        expected: Ty<'tcx>,
156        actual: Ty<'tcx>,
157        ti: &TopInfo<'tcx>,
158    ) -> Result<(), ErrorGuaranteed> {
159        self.demand_eqtype_pat_diag(cause_span, expected, actual, ti).map_err(|err| err.emit())
160    }
161}
162
163/// Mode for adjusting the expected type and binding mode.
164#[derive(Clone, Copy, Debug, PartialEq, Eq)]
165enum AdjustMode {
166    /// Peel off all immediate reference types. If the `deref_patterns` feature is enabled, this
167    /// also peels smart pointer ADTs.
168    Peel { kind: PeelKind },
169    /// Pass on the input binding mode and expected type.
170    Pass,
171}
172
173/// Restrictions on what types to peel when adjusting the expected type and binding mode.
174#[derive(Clone, Copy, Debug, PartialEq, Eq)]
175enum PeelKind {
176    /// Only peel reference types. This is used for explicit `deref!(_)` patterns, which dereference
177    /// any number of `&`/`&mut` references, plus a single smart pointer.
178    ExplicitDerefPat,
179    /// Implicitly peel references, and if `deref_patterns` is enabled, smart pointer ADTs.
180    Implicit {
181        /// The ADT the pattern is a constructor for, if applicable, so that we don't peel it. See
182        /// [`ResolvedPat`] for more information.
183        until_adt: Option<DefId>,
184        /// The number of references at the head of the pattern's type, so we can leave that many
185        /// untouched. This is `1` for string literals, and `0` for most patterns.
186        pat_ref_layers: usize,
187    },
188}
189
190impl AdjustMode {
191    const fn peel_until_adt(opt_adt_def: Option<DefId>) -> AdjustMode {
192        AdjustMode::Peel { kind: PeelKind::Implicit { until_adt: opt_adt_def, pat_ref_layers: 0 } }
193    }
194    const fn peel_all() -> AdjustMode {
195        AdjustMode::peel_until_adt(None)
196    }
197}
198
199/// `ref mut` bindings (explicit or match-ergonomics) are not allowed behind an `&` reference.
200/// Normally, the borrow checker enforces this, but for (currently experimental) match ergonomics,
201/// we track this when typing patterns for two purposes:
202///
203/// - For RFC 3627's Rule 3, when this would prevent us from binding with `ref mut`, we limit the
204///   default binding mode to be by shared `ref` when it would otherwise be `ref mut`.
205///
206/// - For RFC 3627's Rule 5, we allow `&` patterns to match against `&mut` references, treating them
207///   as if they were shared references. Since the scrutinee is mutable in this case, the borrow
208///   checker won't catch if we bind with `ref mut`, so we need to throw an error ourselves.
209#[derive(Clone, Copy, Debug, PartialEq, Eq)]
210enum MutblCap {
211    /// Mutability restricted to immutable.
212    Not,
213
214    /// Mutability restricted to immutable, but only because of the pattern
215    /// (not the scrutinee type).
216    ///
217    /// The contained span, if present, points to an `&` pattern
218    /// that is the reason for the restriction,
219    /// and which will be reported in a diagnostic.
220    WeaklyNot(Option<Span>),
221
222    /// No restriction on mutability
223    Mut,
224}
225
226impl MutblCap {
227    #[must_use]
228    fn cap_to_weakly_not(self, span: Option<Span>) -> Self {
229        match self {
230            MutblCap::Not => MutblCap::Not,
231            _ => MutblCap::WeaklyNot(span),
232        }
233    }
234
235    #[must_use]
236    fn as_mutbl(self) -> Mutability {
237        match self {
238            MutblCap::Not | MutblCap::WeaklyNot(_) => Mutability::Not,
239            MutblCap::Mut => Mutability::Mut,
240        }
241    }
242}
243
244/// Variations on RFC 3627's Rule 4: when do reference patterns match against inherited references?
245///
246/// "Inherited reference" designates the `&`/`&mut` types that arise from using match ergonomics, i.e.
247/// from matching a reference type with a non-reference pattern. E.g. when `Some(x)` matches on
248/// `&mut Option<&T>`, `x` gets type `&mut &T` and the outer `&mut` is considered "inherited".
249#[derive(Clone, Copy, Debug, PartialEq, Eq)]
250enum InheritedRefMatchRule {
251    /// Reference patterns consume only the inherited reference if possible, regardless of whether
252    /// the underlying type being matched against is a reference type. If there is no inherited
253    /// reference, a reference will be consumed from the underlying type.
254    EatOuter,
255    /// Reference patterns consume only a reference from the underlying type if possible. If the
256    /// underlying type is not a reference type, the inherited reference will be consumed.
257    EatInner,
258    /// When the underlying type is a reference type, reference patterns consume both layers of
259    /// reference, i.e. they both reset the binding mode and consume the reference type.
260    EatBoth {
261        /// If `true`, an inherited reference will be considered when determining whether a reference
262        /// pattern matches a given type:
263        /// - If the underlying type is not a reference, a reference pattern may eat the inherited reference;
264        /// - If the underlying type is a reference, a reference pattern matches if it can eat either one
265        ///   of the underlying and inherited references. E.g. a `&mut` pattern is allowed if either the
266        ///   underlying type is `&mut` or the inherited reference is `&mut`.
267        ///
268        /// If `false`, a reference pattern is only matched against the underlying type.
269        /// This is `false` for stable Rust and `true` for both the `ref_pat_eat_one_layer_2024` and
270        /// `ref_pat_eat_one_layer_2024_structural` feature gates.
271        consider_inherited_ref: bool,
272    },
273}
274
275/// When checking patterns containing paths, we need to know the path's resolution to determine
276/// whether to apply match ergonomics and implicitly dereference the scrutinee. For instance, when
277/// the `deref_patterns` feature is enabled and we're matching against a scrutinee of type
278/// `Cow<'a, Option<u8>>`, we insert an implicit dereference to allow the pattern `Some(_)` to type,
279/// but we must not dereference it when checking the pattern `Cow::Borrowed(_)`.
280///
281/// `ResolvedPat` contains the information from resolution needed to determine match ergonomics
282/// adjustments, and to finish checking the pattern once we know its adjusted type.
283#[derive(Clone, Copy, Debug)]
284struct ResolvedPat<'tcx> {
285    /// The type of the pattern, to be checked against the type of the scrutinee after peeling. This
286    /// is also used to avoid peeling the scrutinee's constructors (see the `Cow` example above).
287    ty: Ty<'tcx>,
288    kind: ResolvedPatKind<'tcx>,
289}
290
291#[derive(Clone, Copy, Debug)]
292enum ResolvedPatKind<'tcx> {
293    Path { res: Res, pat_res: Res, segments: &'tcx [hir::PathSegment<'tcx>] },
294    Struct { variant: &'tcx VariantDef },
295    TupleStruct { res: Res, variant: &'tcx VariantDef },
296}
297
298impl<'tcx> ResolvedPat<'tcx> {
299    fn adjust_mode(&self) -> AdjustMode {
300        if let ResolvedPatKind::Path { res, .. } = self.kind
301            && matches!(res, Res::Def(DefKind::Const | DefKind::AssocConst, _))
302        {
303            // These constants can be of a reference type, e.g. `const X: &u8 = &0;`.
304            // Peeling the reference types too early will cause type checking failures.
305            // Although it would be possible to *also* peel the types of the constants too.
306            AdjustMode::Pass
307        } else {
308            // The remaining possible resolutions for path, struct, and tuple struct patterns are
309            // ADT constructors. As such, we may peel references freely, but we must not peel the
310            // ADT itself from the scrutinee if it's a smart pointer.
311            AdjustMode::peel_until_adt(self.ty.ty_adt_def().map(|adt| adt.did()))
312        }
313    }
314}
315
316impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
317    /// Experimental pattern feature: after matching against a shared reference, do we limit the
318    /// default binding mode in subpatterns to be `ref` when it would otherwise be `ref mut`?
319    /// This corresponds to Rule 3 of RFC 3627.
320    fn downgrade_mut_inside_shared(&self) -> bool {
321        // NB: RFC 3627 proposes stabilizing Rule 3 in all editions. If we adopt the same behavior
322        // across all editions, this may be removed.
323        self.tcx.features().ref_pat_eat_one_layer_2024_structural()
324    }
325
326    /// Experimental pattern feature: when do reference patterns match against inherited references?
327    /// This corresponds to variations on Rule 4 of RFC 3627.
328    fn ref_pat_matches_inherited_ref(&self, edition: Edition) -> InheritedRefMatchRule {
329        // NB: The particular rule used here is likely to differ across editions, so calls to this
330        // may need to become edition checks after match ergonomics stabilize.
331        if edition.at_least_rust_2024() {
332            if self.tcx.features().ref_pat_eat_one_layer_2024() {
333                InheritedRefMatchRule::EatOuter
334            } else if self.tcx.features().ref_pat_eat_one_layer_2024_structural() {
335                InheritedRefMatchRule::EatInner
336            } else {
337                // Currently, matching against an inherited ref on edition 2024 is an error.
338                // Use `EatBoth` as a fallback to be similar to stable Rust.
339                InheritedRefMatchRule::EatBoth { consider_inherited_ref: false }
340            }
341        } else {
342            InheritedRefMatchRule::EatBoth {
343                consider_inherited_ref: self.tcx.features().ref_pat_eat_one_layer_2024()
344                    || self.tcx.features().ref_pat_eat_one_layer_2024_structural(),
345            }
346        }
347    }
348
349    /// Experimental pattern feature: do `&` patterns match against `&mut` references, treating them
350    /// as if they were shared references? This corresponds to Rule 5 of RFC 3627.
351    fn ref_pat_matches_mut_ref(&self) -> bool {
352        // NB: RFC 3627 proposes stabilizing Rule 5 in all editions. If we adopt the same behavior
353        // across all editions, this may be removed.
354        self.tcx.features().ref_pat_eat_one_layer_2024()
355            || self.tcx.features().ref_pat_eat_one_layer_2024_structural()
356    }
357
358    /// Type check the given top level pattern against the `expected` type.
359    ///
360    /// If a `Some(span)` is provided and `origin_expr` holds,
361    /// then the `span` represents the scrutinee's span.
362    /// The scrutinee is found in e.g. `match scrutinee { ... }` and `let pat = scrutinee;`.
363    ///
364    /// Otherwise, `Some(span)` represents the span of a type expression
365    /// which originated the `expected` type.
366    pub(crate) fn check_pat_top(
367        &self,
368        pat: &'tcx Pat<'tcx>,
369        expected: Ty<'tcx>,
370        span: Option<Span>,
371        origin_expr: Option<&'tcx hir::Expr<'tcx>>,
372        decl_origin: Option<DeclOrigin<'tcx>>,
373    ) {
374        let top_info = TopInfo { expected, origin_expr, span, hir_id: pat.hir_id };
375        let pat_info = PatInfo {
376            binding_mode: ByRef::No,
377            max_ref_mutbl: MutblCap::Mut,
378            top_info,
379            decl_origin,
380            current_depth: 0,
381        };
382        self.check_pat(pat, expected, pat_info);
383    }
384
385    /// Type check the given `pat` against the `expected` type
386    /// with the provided `binding_mode` (default binding mode).
387    ///
388    /// Outside of this module, `check_pat_top` should always be used.
389    /// Conversely, inside this module, `check_pat_top` should never be used.
390    #[instrument(level = "debug", skip(self, pat_info))]
391    fn check_pat(&self, pat: &'tcx Pat<'tcx>, expected: Ty<'tcx>, pat_info: PatInfo<'tcx>) {
392        // For patterns containing paths, we need the path's resolution to determine whether to
393        // implicitly dereference the scrutinee before matching.
394        let opt_path_res = match pat.kind {
395            PatKind::Expr(PatExpr { kind: PatExprKind::Path(qpath), hir_id, span }) => {
396                Some(self.resolve_pat_path(*hir_id, *span, qpath))
397            }
398            PatKind::Struct(ref qpath, ..) => Some(self.resolve_pat_struct(pat, qpath)),
399            PatKind::TupleStruct(ref qpath, ..) => Some(self.resolve_pat_tuple_struct(pat, qpath)),
400            _ => None,
401        };
402        let adjust_mode = self.calc_adjust_mode(pat, opt_path_res);
403        let ty = self.check_pat_inner(pat, opt_path_res, adjust_mode, expected, pat_info);
404        self.write_ty(pat.hir_id, ty);
405
406        // If we implicitly inserted overloaded dereferences before matching, check the pattern to
407        // see if the dereferenced types need `DerefMut` bounds.
408        if let Some(derefed_tys) = self.typeck_results.borrow().pat_adjustments().get(pat.hir_id)
409            && derefed_tys.iter().any(|adjust| adjust.kind == PatAdjust::OverloadedDeref)
410        {
411            self.register_deref_mut_bounds_if_needed(
412                pat.span,
413                pat,
414                derefed_tys.iter().filter_map(|adjust| match adjust.kind {
415                    PatAdjust::OverloadedDeref => Some(adjust.source),
416                    PatAdjust::BuiltinDeref => None,
417                }),
418            );
419        }
420
421        // (note_1): In most of the cases where (note_1) is referenced
422        // (literals and constants being the exception), we relate types
423        // using strict equality, even though subtyping would be sufficient.
424        // There are a few reasons for this, some of which are fairly subtle
425        // and which cost me (nmatsakis) an hour or two debugging to remember,
426        // so I thought I'd write them down this time.
427        //
428        // 1. There is no loss of expressiveness here, though it does
429        // cause some inconvenience. What we are saying is that the type
430        // of `x` becomes *exactly* what is expected. This can cause unnecessary
431        // errors in some cases, such as this one:
432        //
433        // ```
434        // fn foo<'x>(x: &'x i32) {
435        //    let a = 1;
436        //    let mut z = x;
437        //    z = &a;
438        // }
439        // ```
440        //
441        // The reason we might get an error is that `z` might be
442        // assigned a type like `&'x i32`, and then we would have
443        // a problem when we try to assign `&a` to `z`, because
444        // the lifetime of `&a` (i.e., the enclosing block) is
445        // shorter than `'x`.
446        //
447        // HOWEVER, this code works fine. The reason is that the
448        // expected type here is whatever type the user wrote, not
449        // the initializer's type. In this case the user wrote
450        // nothing, so we are going to create a type variable `Z`.
451        // Then we will assign the type of the initializer (`&'x i32`)
452        // as a subtype of `Z`: `&'x i32 <: Z`. And hence we
453        // will instantiate `Z` as a type `&'0 i32` where `'0` is
454        // a fresh region variable, with the constraint that `'x : '0`.
455        // So basically we're all set.
456        //
457        // Note that there are two tests to check that this remains true
458        // (`regions-reassign-{match,let}-bound-pointer.rs`).
459        //
460        // 2. An outdated issue related to the old HIR borrowck. See the test
461        // `regions-relate-bound-regions-on-closures-to-inference-variables.rs`,
462    }
463
464    // Helper to avoid resolving the same path pattern several times.
465    fn check_pat_inner(
466        &self,
467        pat: &'tcx Pat<'tcx>,
468        opt_path_res: Option<Result<ResolvedPat<'tcx>, ErrorGuaranteed>>,
469        adjust_mode: AdjustMode,
470        expected: Ty<'tcx>,
471        pat_info: PatInfo<'tcx>,
472    ) -> Ty<'tcx> {
473        #[cfg(debug_assertions)]
474        if pat_info.binding_mode == ByRef::Yes(Mutability::Mut)
475            && pat_info.max_ref_mutbl != MutblCap::Mut
476            && self.downgrade_mut_inside_shared()
477        {
478            span_bug!(pat.span, "Pattern mutability cap violated!");
479        }
480
481        // Resolve type if needed.
482        let expected = if let AdjustMode::Peel { .. } = adjust_mode
483            && pat.default_binding_modes
484        {
485            self.try_structurally_resolve_type(pat.span, expected)
486        } else {
487            expected
488        };
489        let old_pat_info = pat_info;
490        let pat_info = PatInfo { current_depth: old_pat_info.current_depth + 1, ..old_pat_info };
491
492        match pat.kind {
493            // Peel off a `&` or `&mut` from the scrutinee type. See the examples in
494            // `tests/ui/rfcs/rfc-2005-default-binding-mode`.
495            _ if let AdjustMode::Peel { kind: peel_kind } = adjust_mode
496                && pat.default_binding_modes
497                && let ty::Ref(_, inner_ty, inner_mutability) = *expected.kind()
498                && self.should_peel_ref(peel_kind, expected) =>
499            {
500                debug!("inspecting {:?}", expected);
501
502                debug!("current discriminant is Ref, inserting implicit deref");
503                // Preserve the reference type. We'll need it later during THIR lowering.
504                self.typeck_results
505                    .borrow_mut()
506                    .pat_adjustments_mut()
507                    .entry(pat.hir_id)
508                    .or_default()
509                    .push(PatAdjustment { kind: PatAdjust::BuiltinDeref, source: expected });
510
511                let mut binding_mode = ByRef::Yes(match pat_info.binding_mode {
512                    // If default binding mode is by value, make it `ref` or `ref mut`
513                    // (depending on whether we observe `&` or `&mut`).
514                    ByRef::No |
515                    // When `ref mut`, stay a `ref mut` (on `&mut`) or downgrade to `ref` (on `&`).
516                    ByRef::Yes(Mutability::Mut) => inner_mutability,
517                    // Once a `ref`, always a `ref`.
518                    // This is because a `& &mut` cannot mutate the underlying value.
519                    ByRef::Yes(Mutability::Not) => Mutability::Not,
520                });
521
522                let mut max_ref_mutbl = pat_info.max_ref_mutbl;
523                if self.downgrade_mut_inside_shared() {
524                    binding_mode = binding_mode.cap_ref_mutability(max_ref_mutbl.as_mutbl());
525                }
526                if binding_mode == ByRef::Yes(Mutability::Not) {
527                    max_ref_mutbl = MutblCap::Not;
528                }
529                debug!("default binding mode is now {:?}", binding_mode);
530
531                // Use the old pat info to keep `current_depth` to its old value.
532                let new_pat_info = PatInfo { binding_mode, max_ref_mutbl, ..old_pat_info };
533                // Recurse with the new expected type.
534                self.check_pat_inner(pat, opt_path_res, adjust_mode, inner_ty, new_pat_info)
535            }
536            // If `deref_patterns` is enabled, peel a smart pointer from the scrutinee type. See the
537            // examples in `tests/ui/pattern/deref_patterns/`.
538            _ if self.tcx.features().deref_patterns()
539                && let AdjustMode::Peel { kind: peel_kind } = adjust_mode
540                && pat.default_binding_modes
541                && self.should_peel_smart_pointer(peel_kind, expected) =>
542            {
543                debug!("scrutinee ty {expected:?} is a smart pointer, inserting overloaded deref");
544                // The scrutinee is a smart pointer; implicitly dereference it. This adds a
545                // requirement that `expected: DerefPure`.
546                let mut inner_ty = self.deref_pat_target(pat.span, expected);
547                // Once we've checked `pat`, we'll add a `DerefMut` bound if it contains any
548                // `ref mut` bindings. See `Self::register_deref_mut_bounds_if_needed`.
549
550                let mut typeck_results = self.typeck_results.borrow_mut();
551                let mut pat_adjustments_table = typeck_results.pat_adjustments_mut();
552                let pat_adjustments = pat_adjustments_table.entry(pat.hir_id).or_default();
553                // We may reach the recursion limit if a user matches on a type `T` satisfying
554                // `T: Deref<Target = T>`; error gracefully in this case.
555                // FIXME(deref_patterns): If `deref_patterns` stabilizes, it may make sense to move
556                // this check out of this branch. Alternatively, this loop could be implemented with
557                // autoderef and this check removed. For now though, don't break code compiling on
558                // stable with lots of `&`s and a low recursion limit, if anyone's done that.
559                if self.tcx.recursion_limit().value_within_limit(pat_adjustments.len()) {
560                    // Preserve the smart pointer type for THIR lowering and closure upvar analysis.
561                    pat_adjustments
562                        .push(PatAdjustment { kind: PatAdjust::OverloadedDeref, source: expected });
563                } else {
564                    let guar = report_autoderef_recursion_limit_error(self.tcx, pat.span, expected);
565                    inner_ty = Ty::new_error(self.tcx, guar);
566                }
567                drop(typeck_results);
568
569                // Recurse, using the old pat info to keep `current_depth` to its old value.
570                // Peeling smart pointers does not update the default binding mode.
571                self.check_pat_inner(pat, opt_path_res, adjust_mode, inner_ty, old_pat_info)
572            }
573            PatKind::Missing | PatKind::Wild | PatKind::Err(_) => expected,
574            // We allow any type here; we ensure that the type is uninhabited during match checking.
575            PatKind::Never => expected,
576            PatKind::Expr(PatExpr { kind: PatExprKind::Path(_), hir_id, .. }) => {
577                let ty = match opt_path_res.unwrap() {
578                    Ok(ref pr) => {
579                        self.check_pat_path(pat.hir_id, pat.span, pr, expected, &pat_info.top_info)
580                    }
581                    Err(guar) => Ty::new_error(self.tcx, guar),
582                };
583                self.write_ty(*hir_id, ty);
584                ty
585            }
586            PatKind::Expr(lt) => self.check_pat_lit(pat.span, lt, expected, &pat_info.top_info),
587            PatKind::Range(lhs, rhs, _) => {
588                self.check_pat_range(pat.span, lhs, rhs, expected, &pat_info.top_info)
589            }
590            PatKind::Binding(ba, var_id, ident, sub) => {
591                self.check_pat_ident(pat, ba, var_id, ident, sub, expected, pat_info)
592            }
593            PatKind::TupleStruct(ref qpath, subpats, ddpos) => match opt_path_res.unwrap() {
594                Ok(ResolvedPat { ty, kind: ResolvedPatKind::TupleStruct { res, variant } }) => self
595                    .check_pat_tuple_struct(
596                        pat, qpath, subpats, ddpos, res, ty, variant, expected, pat_info,
597                    ),
598                Err(guar) => {
599                    let ty_err = Ty::new_error(self.tcx, guar);
600                    for subpat in subpats {
601                        self.check_pat(subpat, ty_err, pat_info);
602                    }
603                    ty_err
604                }
605                Ok(pr) => span_bug!(pat.span, "tuple struct pattern resolved to {pr:?}"),
606            },
607            PatKind::Struct(_, fields, has_rest_pat) => match opt_path_res.unwrap() {
608                Ok(ResolvedPat { ty, kind: ResolvedPatKind::Struct { variant } }) => self
609                    .check_pat_struct(
610                        pat,
611                        fields,
612                        has_rest_pat.is_some(),
613                        ty,
614                        variant,
615                        expected,
616                        pat_info,
617                    ),
618                Err(guar) => {
619                    let ty_err = Ty::new_error(self.tcx, guar);
620                    for field in fields {
621                        self.check_pat(field.pat, ty_err, pat_info);
622                    }
623                    ty_err
624                }
625                Ok(pr) => span_bug!(pat.span, "struct pattern resolved to {pr:?}"),
626            },
627            PatKind::Guard(pat, cond) => {
628                self.check_pat(pat, expected, pat_info);
629                self.check_expr_has_type_or_error(cond, self.tcx.types.bool, |_| {});
630                expected
631            }
632            PatKind::Or(pats) => {
633                for pat in pats {
634                    self.check_pat(pat, expected, pat_info);
635                }
636                expected
637            }
638            PatKind::Tuple(elements, ddpos) => {
639                self.check_pat_tuple(pat.span, elements, ddpos, expected, pat_info)
640            }
641            PatKind::Box(inner) => self.check_pat_box(pat.span, inner, expected, pat_info),
642            PatKind::Deref(inner) => self.check_pat_deref(pat.span, inner, expected, pat_info),
643            PatKind::Ref(inner, mutbl) => self.check_pat_ref(pat, inner, mutbl, expected, pat_info),
644            PatKind::Slice(before, slice, after) => {
645                self.check_pat_slice(pat.span, before, slice, after, expected, pat_info)
646            }
647        }
648    }
649
650    /// How should the binding mode and expected type be adjusted?
651    ///
652    /// When the pattern contains a path, `opt_path_res` must be `Some(path_res)`.
653    fn calc_adjust_mode(
654        &self,
655        pat: &'tcx Pat<'tcx>,
656        opt_path_res: Option<Result<ResolvedPat<'tcx>, ErrorGuaranteed>>,
657    ) -> AdjustMode {
658        match &pat.kind {
659            // Type checking these product-like types successfully always require
660            // that the expected type be of those types and not reference types.
661            PatKind::Tuple(..) | PatKind::Range(..) | PatKind::Slice(..) => AdjustMode::peel_all(),
662            // When checking an explicit deref pattern, only peel reference types.
663            // FIXME(deref_patterns): If box patterns and deref patterns need to coexist, box
664            // patterns may want `PeelKind::Implicit`, stopping on encountering a box.
665            PatKind::Box(_) | PatKind::Deref(_) => {
666                AdjustMode::Peel { kind: PeelKind::ExplicitDerefPat }
667            }
668            // A never pattern behaves somewhat like a literal or unit variant.
669            PatKind::Never => AdjustMode::peel_all(),
670            // For patterns with paths, how we peel the scrutinee depends on the path's resolution.
671            PatKind::Struct(..)
672            | PatKind::TupleStruct(..)
673            | PatKind::Expr(PatExpr { kind: PatExprKind::Path(_), .. }) => {
674                // If there was an error resolving the path, default to peeling everything.
675                opt_path_res.unwrap().map_or(AdjustMode::peel_all(), |pr| pr.adjust_mode())
676            }
677
678            // String and byte-string literals result in types `&str` and `&[u8]` respectively.
679            // All other literals result in non-reference types.
680            // As a result, we allow `if let 0 = &&0 {}` but not `if let "foo" = &&"foo" {}` unless
681            // `deref_patterns` is enabled.
682            PatKind::Expr(lt) => {
683                // Path patterns have already been handled, and inline const blocks currently
684                // aren't possible to write, so any handling for them would be untested.
685                if cfg!(debug_assertions)
686                    && self.tcx.features().deref_patterns()
687                    && !matches!(lt.kind, PatExprKind::Lit { .. })
688                {
689                    span_bug!(
690                        lt.span,
691                        "FIXME(deref_patterns): adjust mode unimplemented for {:?}",
692                        lt.kind
693                    );
694                }
695                // Call `resolve_vars_if_possible` here for inline const blocks.
696                let lit_ty = self.resolve_vars_if_possible(self.check_pat_expr_unadjusted(lt));
697                // If `deref_patterns` is enabled, allow `if let "foo" = &&"foo" {}`.
698                if self.tcx.features().deref_patterns() {
699                    let mut peeled_ty = lit_ty;
700                    let mut pat_ref_layers = 0;
701                    while let ty::Ref(_, inner_ty, mutbl) =
702                        *self.try_structurally_resolve_type(pat.span, peeled_ty).kind()
703                    {
704                        // We rely on references at the head of constants being immutable.
705                        debug_assert!(mutbl.is_not());
706                        pat_ref_layers += 1;
707                        peeled_ty = inner_ty;
708                    }
709                    AdjustMode::Peel {
710                        kind: PeelKind::Implicit { until_adt: None, pat_ref_layers },
711                    }
712                } else {
713                    if lit_ty.is_ref() { AdjustMode::Pass } else { AdjustMode::peel_all() }
714                }
715            }
716
717            // Ref patterns are complicated, we handle them in `check_pat_ref`.
718            PatKind::Ref(..)
719            // No need to do anything on a missing pattern.
720            | PatKind::Missing
721            // A `_` pattern works with any expected type, so there's no need to do anything.
722            | PatKind::Wild
723            // A malformed pattern doesn't have an expected type, so let's just accept any type.
724            | PatKind::Err(_)
725            // Bindings also work with whatever the expected type is,
726            // and moreover if we peel references off, that will give us the wrong binding type.
727            // Also, we can have a subpattern `binding @ pat`.
728            // Each side of the `@` should be treated independently (like with OR-patterns).
729            | PatKind::Binding(..)
730            // An OR-pattern just propagates to each individual alternative.
731            // This is maximally flexible, allowing e.g., `Some(mut x) | &Some(mut x)`.
732            // In that example, `Some(mut x)` results in `Peel` whereas `&Some(mut x)` in `Reset`.
733            | PatKind::Or(_)
734            // Like or-patterns, guard patterns just propagate to their subpatterns.
735            | PatKind::Guard(..) => AdjustMode::Pass,
736        }
737    }
738
739    /// Assuming `expected` is a reference type, determine whether to peel it before matching.
740    fn should_peel_ref(&self, peel_kind: PeelKind, mut expected: Ty<'tcx>) -> bool {
741        debug_assert!(expected.is_ref());
742        let pat_ref_layers = match peel_kind {
743            PeelKind::ExplicitDerefPat => 0,
744            PeelKind::Implicit { pat_ref_layers, .. } => pat_ref_layers,
745        };
746
747        // Most patterns don't have reference types, so we'll want to peel all references from the
748        // scrutinee before matching. To optimize for the common case, return early.
749        if pat_ref_layers == 0 {
750            return true;
751        }
752        debug_assert!(
753            self.tcx.features().deref_patterns(),
754            "Peeling for patterns with reference types is gated by `deref_patterns`."
755        );
756
757        // If the pattern has as many or more layers of reference as the expected type, we can match
758        // without peeling more, unless we find a smart pointer or `&mut` that we also need to peel.
759        // We don't treat `&` and `&mut` as interchangeable, but by peeling `&mut`s before matching,
760        // we can still, e.g., match on a `&mut str` with a string literal pattern. This is because
761        // string literal patterns may be used where `str` is expected.
762        let mut expected_ref_layers = 0;
763        while let ty::Ref(_, inner_ty, mutbl) = *expected.kind() {
764            if mutbl.is_mut() {
765                // Mutable references can't be in the final value of constants, thus they can't be
766                // at the head of their types, thus we should always peel `&mut`.
767                return true;
768            }
769            expected_ref_layers += 1;
770            expected = inner_ty;
771        }
772        pat_ref_layers < expected_ref_layers || self.should_peel_smart_pointer(peel_kind, expected)
773    }
774
775    /// Determine whether `expected` is a smart pointer type that should be peeled before matching.
776    fn should_peel_smart_pointer(&self, peel_kind: PeelKind, expected: Ty<'tcx>) -> bool {
777        // Explicit `deref!(_)` patterns match against smart pointers; don't peel in that case.
778        if let PeelKind::Implicit { until_adt, .. } = peel_kind
779            // For simplicity, only apply overloaded derefs if `expected` is a known ADT.
780            // FIXME(deref_patterns): we'll get better diagnostics for users trying to
781            // implicitly deref generics if we allow them here, but primitives, tuples, and
782            // inference vars definitely should be stopped. Figure out what makes most sense.
783            && let ty::Adt(scrutinee_adt, _) = *expected.kind()
784            // Don't peel if the pattern type already matches the scrutinee. E.g., stop here if
785            // matching on a `Cow<'a, T>` scrutinee with a `Cow::Owned(_)` pattern.
786            && until_adt != Some(scrutinee_adt.did())
787            // At this point, the pattern isn't able to match `expected` without peeling. Check
788            // that it implements `Deref` before assuming it's a smart pointer, to get a normal
789            // type error instead of a missing impl error if not. This only checks for `Deref`,
790            // not `DerefPure`: we require that too, but we want a trait error if it's missing.
791            && let Some(deref_trait) = self.tcx.lang_items().deref_trait()
792            && self.type_implements_trait(deref_trait, [expected], self.param_env).may_apply()
793        {
794            true
795        } else {
796            false
797        }
798    }
799
800    fn check_pat_expr_unadjusted(&self, lt: &'tcx hir::PatExpr<'tcx>) -> Ty<'tcx> {
801        let ty = match &lt.kind {
802            rustc_hir::PatExprKind::Lit { lit, negated } => {
803                let ty = self.check_expr_lit(lit, Expectation::NoExpectation);
804                if *negated {
805                    self.register_bound(
806                        ty,
807                        self.tcx.require_lang_item(LangItem::Neg, lt.span),
808                        ObligationCause::dummy_with_span(lt.span),
809                    );
810                }
811                ty
812            }
813            rustc_hir::PatExprKind::ConstBlock(c) => {
814                self.check_expr_const_block(c, Expectation::NoExpectation)
815            }
816            rustc_hir::PatExprKind::Path(qpath) => {
817                let (res, opt_ty, segments) =
818                    self.resolve_ty_and_res_fully_qualified_call(qpath, lt.hir_id, lt.span);
819                self.instantiate_value_path(segments, opt_ty, res, lt.span, lt.span, lt.hir_id).0
820            }
821        };
822        self.write_ty(lt.hir_id, ty);
823        ty
824    }
825
826    fn check_pat_lit(
827        &self,
828        span: Span,
829        lt: &hir::PatExpr<'tcx>,
830        expected: Ty<'tcx>,
831        ti: &TopInfo<'tcx>,
832    ) -> Ty<'tcx> {
833        // We've already computed the type above (when checking for a non-ref pat),
834        // so avoid computing it again.
835        let ty = self.node_ty(lt.hir_id);
836
837        // Byte string patterns behave the same way as array patterns
838        // They can denote both statically and dynamically-sized byte arrays.
839        // Additionally, when `deref_patterns` is enabled, byte string literal patterns may have
840        // types `[u8]` or `[u8; N]`, in order to type, e.g., `deref!(b"..."): Vec<u8>`.
841        let mut pat_ty = ty;
842        if let hir::PatExprKind::Lit {
843            lit: Spanned { node: ast::LitKind::ByteStr(..), .. }, ..
844        } = lt.kind
845        {
846            let tcx = self.tcx;
847            let expected = self.structurally_resolve_type(span, expected);
848            match *expected.kind() {
849                // Allow `b"...": &[u8]`
850                ty::Ref(_, inner_ty, _)
851                    if self.try_structurally_resolve_type(span, inner_ty).is_slice() =>
852                {
853                    trace!(?lt.hir_id.local_id, "polymorphic byte string lit");
854                    pat_ty = Ty::new_imm_ref(
855                        tcx,
856                        tcx.lifetimes.re_static,
857                        Ty::new_slice(tcx, tcx.types.u8),
858                    );
859                }
860                // Allow `b"...": [u8; 3]` for `deref_patterns`
861                ty::Array(..) if tcx.features().deref_patterns() => {
862                    pat_ty = match *ty.kind() {
863                        ty::Ref(_, inner_ty, _) => inner_ty,
864                        _ => span_bug!(span, "found byte string literal with non-ref type {ty:?}"),
865                    }
866                }
867                // Allow `b"...": [u8]` for `deref_patterns`
868                ty::Slice(..) if tcx.features().deref_patterns() => {
869                    pat_ty = Ty::new_slice(tcx, tcx.types.u8);
870                }
871                // Otherwise, `b"...": &[u8; 3]`
872                _ => {}
873            }
874        }
875
876        // When `deref_patterns` is enabled, in order to allow `deref!("..."): String`, we allow
877        // string literal patterns to have type `str`. This is accounted for when lowering to MIR.
878        if self.tcx.features().deref_patterns()
879            && let hir::PatExprKind::Lit {
880                lit: Spanned { node: ast::LitKind::Str(..), .. }, ..
881            } = lt.kind
882            && self.try_structurally_resolve_type(span, expected).is_str()
883        {
884            pat_ty = self.tcx.types.str_;
885        }
886
887        if self.tcx.features().string_deref_patterns()
888            && let hir::PatExprKind::Lit {
889                lit: Spanned { node: ast::LitKind::Str(..), .. }, ..
890            } = lt.kind
891        {
892            let tcx = self.tcx;
893            let expected = self.resolve_vars_if_possible(expected);
894            pat_ty = match expected.kind() {
895                ty::Adt(def, _) if tcx.is_lang_item(def.did(), LangItem::String) => expected,
896                ty::Str => Ty::new_static_str(tcx),
897                _ => pat_ty,
898            };
899        }
900
901        // Somewhat surprising: in this case, the subtyping relation goes the
902        // opposite way as the other cases. Actually what we really want is not
903        // a subtyping relation at all but rather that there exists a LUB
904        // (so that they can be compared). However, in practice, constants are
905        // always scalars or strings. For scalars subtyping is irrelevant,
906        // and for strings `ty` is type is `&'static str`, so if we say that
907        //
908        //     &'static str <: expected
909        //
910        // then that's equivalent to there existing a LUB.
911        let cause = self.pattern_cause(ti, span);
912        if let Err(err) = self.demand_suptype_with_origin(&cause, expected, pat_ty) {
913            err.emit();
914        }
915
916        pat_ty
917    }
918
919    fn check_pat_range(
920        &self,
921        span: Span,
922        lhs: Option<&'tcx hir::PatExpr<'tcx>>,
923        rhs: Option<&'tcx hir::PatExpr<'tcx>>,
924        expected: Ty<'tcx>,
925        ti: &TopInfo<'tcx>,
926    ) -> Ty<'tcx> {
927        let calc_side = |opt_expr: Option<&'tcx hir::PatExpr<'tcx>>| match opt_expr {
928            None => None,
929            Some(expr) => {
930                let ty = self.check_pat_expr_unadjusted(expr);
931                // Check that the end-point is possibly of numeric or char type.
932                // The early check here is not for correctness, but rather better
933                // diagnostics (e.g. when `&str` is being matched, `expected` will
934                // be peeled to `str` while ty here is still `&str`, if we don't
935                // err early here, a rather confusing unification error will be
936                // emitted instead).
937                let ty = self.try_structurally_resolve_type(expr.span, ty);
938                let fail =
939                    !(ty.is_numeric() || ty.is_char() || ty.is_ty_var() || ty.references_error());
940                Some((fail, ty, expr.span))
941            }
942        };
943        let mut lhs = calc_side(lhs);
944        let mut rhs = calc_side(rhs);
945
946        if let (Some((true, ..)), _) | (_, Some((true, ..))) = (lhs, rhs) {
947            // There exists a side that didn't meet our criteria that the end-point
948            // be of a numeric or char type, as checked in `calc_side` above.
949            let guar = self.emit_err_pat_range(span, lhs, rhs);
950            return Ty::new_error(self.tcx, guar);
951        }
952
953        // Unify each side with `expected`.
954        // Subtyping doesn't matter here, as the value is some kind of scalar.
955        let demand_eqtype = |x: &mut _, y| {
956            if let Some((ref mut fail, x_ty, x_span)) = *x
957                && let Err(mut err) = self.demand_eqtype_pat_diag(x_span, expected, x_ty, ti)
958            {
959                if let Some((_, y_ty, y_span)) = y {
960                    self.endpoint_has_type(&mut err, y_span, y_ty);
961                }
962                err.emit();
963                *fail = true;
964            }
965        };
966        demand_eqtype(&mut lhs, rhs);
967        demand_eqtype(&mut rhs, lhs);
968
969        if let (Some((true, ..)), _) | (_, Some((true, ..))) = (lhs, rhs) {
970            return Ty::new_misc_error(self.tcx);
971        }
972
973        // Find the unified type and check if it's of numeric or char type again.
974        // This check is needed if both sides are inference variables.
975        // We require types to be resolved here so that we emit inference failure
976        // rather than "_ is not a char or numeric".
977        let ty = self.structurally_resolve_type(span, expected);
978        if !(ty.is_numeric() || ty.is_char() || ty.references_error()) {
979            if let Some((ref mut fail, _, _)) = lhs {
980                *fail = true;
981            }
982            if let Some((ref mut fail, _, _)) = rhs {
983                *fail = true;
984            }
985            let guar = self.emit_err_pat_range(span, lhs, rhs);
986            return Ty::new_error(self.tcx, guar);
987        }
988        ty
989    }
990
991    fn endpoint_has_type(&self, err: &mut Diag<'_>, span: Span, ty: Ty<'_>) {
992        if !ty.references_error() {
993            err.span_label(span, format!("this is of type `{ty}`"));
994        }
995    }
996
997    fn emit_err_pat_range(
998        &self,
999        span: Span,
1000        lhs: Option<(bool, Ty<'tcx>, Span)>,
1001        rhs: Option<(bool, Ty<'tcx>, Span)>,
1002    ) -> ErrorGuaranteed {
1003        let span = match (lhs, rhs) {
1004            (Some((true, ..)), Some((true, ..))) => span,
1005            (Some((true, _, sp)), _) => sp,
1006            (_, Some((true, _, sp))) => sp,
1007            _ => span_bug!(span, "emit_err_pat_range: no side failed or exists but still error?"),
1008        };
1009        let mut err = struct_span_code_err!(
1010            self.dcx(),
1011            span,
1012            E0029,
1013            "only `char` and numeric types are allowed in range patterns"
1014        );
1015        let msg = |ty| {
1016            let ty = self.resolve_vars_if_possible(ty);
1017            format!("this is of type `{ty}` but it should be `char` or numeric")
1018        };
1019        let mut one_side_err = |first_span, first_ty, second: Option<(bool, Ty<'tcx>, Span)>| {
1020            err.span_label(first_span, msg(first_ty));
1021            if let Some((_, ty, sp)) = second {
1022                let ty = self.resolve_vars_if_possible(ty);
1023                self.endpoint_has_type(&mut err, sp, ty);
1024            }
1025        };
1026        match (lhs, rhs) {
1027            (Some((true, lhs_ty, lhs_sp)), Some((true, rhs_ty, rhs_sp))) => {
1028                err.span_label(lhs_sp, msg(lhs_ty));
1029                err.span_label(rhs_sp, msg(rhs_ty));
1030            }
1031            (Some((true, lhs_ty, lhs_sp)), rhs) => one_side_err(lhs_sp, lhs_ty, rhs),
1032            (lhs, Some((true, rhs_ty, rhs_sp))) => one_side_err(rhs_sp, rhs_ty, lhs),
1033            _ => span_bug!(span, "Impossible, verified above."),
1034        }
1035        if (lhs, rhs).references_error() {
1036            err.downgrade_to_delayed_bug();
1037        }
1038        if self.tcx.sess.teach(err.code.unwrap()) {
1039            err.note(
1040                "In a match expression, only numbers and characters can be matched \
1041                    against a range. This is because the compiler checks that the range \
1042                    is non-empty at compile-time, and is unable to evaluate arbitrary \
1043                    comparison functions. If you want to capture values of an orderable \
1044                    type between two end-points, you can use a guard.",
1045            );
1046        }
1047        err.emit()
1048    }
1049
1050    fn check_pat_ident(
1051        &self,
1052        pat: &'tcx Pat<'tcx>,
1053        user_bind_annot: BindingMode,
1054        var_id: HirId,
1055        ident: Ident,
1056        sub: Option<&'tcx Pat<'tcx>>,
1057        expected: Ty<'tcx>,
1058        pat_info: PatInfo<'tcx>,
1059    ) -> Ty<'tcx> {
1060        let PatInfo { binding_mode: def_br, top_info: ti, .. } = pat_info;
1061
1062        // Determine the binding mode...
1063        let bm = match user_bind_annot {
1064            BindingMode(ByRef::No, Mutability::Mut) if let ByRef::Yes(def_br_mutbl) = def_br => {
1065                // Only mention the experimental `mut_ref` feature if if we're in edition 2024 and
1066                // using other experimental matching features compatible with it.
1067                if pat.span.at_least_rust_2024()
1068                    && (self.tcx.features().ref_pat_eat_one_layer_2024()
1069                        || self.tcx.features().ref_pat_eat_one_layer_2024_structural())
1070                {
1071                    if !self.tcx.features().mut_ref() {
1072                        feature_err(
1073                            self.tcx.sess,
1074                            sym::mut_ref,
1075                            pat.span.until(ident.span),
1076                            "binding cannot be both mutable and by-reference",
1077                        )
1078                        .emit();
1079                    }
1080
1081                    BindingMode(def_br, Mutability::Mut)
1082                } else {
1083                    // `mut` resets the binding mode on edition <= 2021
1084                    self.add_rust_2024_migration_desugared_pat(
1085                        pat_info.top_info.hir_id,
1086                        pat,
1087                        't', // last char of `mut`
1088                        def_br_mutbl,
1089                    );
1090                    BindingMode(ByRef::No, Mutability::Mut)
1091                }
1092            }
1093            BindingMode(ByRef::No, mutbl) => BindingMode(def_br, mutbl),
1094            BindingMode(ByRef::Yes(user_br_mutbl), _) => {
1095                if let ByRef::Yes(def_br_mutbl) = def_br {
1096                    // `ref`/`ref mut` overrides the binding mode on edition <= 2021
1097                    self.add_rust_2024_migration_desugared_pat(
1098                        pat_info.top_info.hir_id,
1099                        pat,
1100                        match user_br_mutbl {
1101                            Mutability::Not => 'f', // last char of `ref`
1102                            Mutability::Mut => 't', // last char of `ref mut`
1103                        },
1104                        def_br_mutbl,
1105                    );
1106                }
1107                user_bind_annot
1108            }
1109        };
1110
1111        if bm.0 == ByRef::Yes(Mutability::Mut)
1112            && let MutblCap::WeaklyNot(and_pat_span) = pat_info.max_ref_mutbl
1113        {
1114            let mut err = struct_span_code_err!(
1115                self.dcx(),
1116                ident.span,
1117                E0596,
1118                "cannot borrow as mutable inside an `&` pattern"
1119            );
1120
1121            if let Some(span) = and_pat_span {
1122                err.span_suggestion(
1123                    span,
1124                    "replace this `&` with `&mut`",
1125                    "&mut ",
1126                    Applicability::MachineApplicable,
1127                );
1128            }
1129            err.emit();
1130        }
1131
1132        // ...and store it in a side table:
1133        self.typeck_results.borrow_mut().pat_binding_modes_mut().insert(pat.hir_id, bm);
1134
1135        debug!("check_pat_ident: pat.hir_id={:?} bm={:?}", pat.hir_id, bm);
1136
1137        let local_ty = self.local_ty(pat.span, pat.hir_id);
1138        let eq_ty = match bm.0 {
1139            ByRef::Yes(mutbl) => {
1140                // If the binding is like `ref x | ref mut x`,
1141                // then `x` is assigned a value of type `&M T` where M is the
1142                // mutability and T is the expected type.
1143                //
1144                // `x` is assigned a value of type `&M T`, hence `&M T <: typeof(x)`
1145                // is required. However, we use equality, which is stronger.
1146                // See (note_1) for an explanation.
1147                self.new_ref_ty(pat.span, mutbl, expected)
1148            }
1149            // Otherwise, the type of x is the expected type `T`.
1150            ByRef::No => expected, // As above, `T <: typeof(x)` is required, but we use equality, see (note_1).
1151        };
1152
1153        // We have a concrete type for the local, so we do not need to taint it and hide follow up errors *using* the local.
1154        let _ = self.demand_eqtype_pat(pat.span, eq_ty, local_ty, &ti);
1155
1156        // If there are multiple arms, make sure they all agree on
1157        // what the type of the binding `x` ought to be.
1158        if var_id != pat.hir_id {
1159            self.check_binding_alt_eq_ty(user_bind_annot, pat.span, var_id, local_ty, &ti);
1160        }
1161
1162        if let Some(p) = sub {
1163            self.check_pat(p, expected, pat_info);
1164        }
1165
1166        local_ty
1167    }
1168
1169    /// When a variable is bound several times in a `PatKind::Or`, it'll resolve all of the
1170    /// subsequent bindings of the same name to the first usage. Verify that all of these
1171    /// bindings have the same type by comparing them all against the type of that first pat.
1172    fn check_binding_alt_eq_ty(
1173        &self,
1174        ba: BindingMode,
1175        span: Span,
1176        var_id: HirId,
1177        ty: Ty<'tcx>,
1178        ti: &TopInfo<'tcx>,
1179    ) {
1180        let var_ty = self.local_ty(span, var_id);
1181        if let Err(mut err) = self.demand_eqtype_pat_diag(span, var_ty, ty, ti) {
1182            let var_ty = self.resolve_vars_if_possible(var_ty);
1183            let msg = format!("first introduced with type `{var_ty}` here");
1184            err.span_label(self.tcx.hir_span(var_id), msg);
1185            let in_match = self.tcx.hir_parent_iter(var_id).any(|(_, n)| {
1186                matches!(
1187                    n,
1188                    hir::Node::Expr(hir::Expr {
1189                        kind: hir::ExprKind::Match(.., hir::MatchSource::Normal),
1190                        ..
1191                    })
1192                )
1193            });
1194            let pre = if in_match { "in the same arm, " } else { "" };
1195            err.note(format!("{pre}a binding must have the same type in all alternatives"));
1196            self.suggest_adding_missing_ref_or_removing_ref(
1197                &mut err,
1198                span,
1199                var_ty,
1200                self.resolve_vars_if_possible(ty),
1201                ba,
1202            );
1203            err.emit();
1204        }
1205    }
1206
1207    fn suggest_adding_missing_ref_or_removing_ref(
1208        &self,
1209        err: &mut Diag<'_>,
1210        span: Span,
1211        expected: Ty<'tcx>,
1212        actual: Ty<'tcx>,
1213        ba: BindingMode,
1214    ) {
1215        match (expected.kind(), actual.kind(), ba) {
1216            (ty::Ref(_, inner_ty, _), _, BindingMode::NONE)
1217                if self.can_eq(self.param_env, *inner_ty, actual) =>
1218            {
1219                err.span_suggestion_verbose(
1220                    span.shrink_to_lo(),
1221                    "consider adding `ref`",
1222                    "ref ",
1223                    Applicability::MaybeIncorrect,
1224                );
1225            }
1226            (_, ty::Ref(_, inner_ty, _), BindingMode::REF)
1227                if self.can_eq(self.param_env, expected, *inner_ty) =>
1228            {
1229                err.span_suggestion_verbose(
1230                    span.with_hi(span.lo() + BytePos(4)),
1231                    "consider removing `ref`",
1232                    "",
1233                    Applicability::MaybeIncorrect,
1234                );
1235            }
1236            _ => (),
1237        }
1238    }
1239
1240    /// Precondition: pat is a `Ref(_)` pattern
1241    fn borrow_pat_suggestion(&self, err: &mut Diag<'_>, pat: &Pat<'_>) {
1242        let tcx = self.tcx;
1243        if let PatKind::Ref(inner, mutbl) = pat.kind
1244            && let PatKind::Binding(_, _, binding, ..) = inner.kind
1245        {
1246            let binding_parent = tcx.parent_hir_node(pat.hir_id);
1247            debug!(?inner, ?pat, ?binding_parent);
1248
1249            let mutability = match mutbl {
1250                ast::Mutability::Mut => "mut",
1251                ast::Mutability::Not => "",
1252            };
1253
1254            let mut_var_suggestion = 'block: {
1255                if mutbl.is_not() {
1256                    break 'block None;
1257                }
1258
1259                let ident_kind = match binding_parent {
1260                    hir::Node::Param(_) => "parameter",
1261                    hir::Node::LetStmt(_) => "variable",
1262                    hir::Node::Arm(_) => "binding",
1263
1264                    // Provide diagnostics only if the parent pattern is struct-like,
1265                    // i.e. where `mut binding` makes sense
1266                    hir::Node::Pat(Pat { kind, .. }) => match kind {
1267                        PatKind::Struct(..)
1268                        | PatKind::TupleStruct(..)
1269                        | PatKind::Or(..)
1270                        | PatKind::Guard(..)
1271                        | PatKind::Tuple(..)
1272                        | PatKind::Slice(..) => "binding",
1273
1274                        PatKind::Missing
1275                        | PatKind::Wild
1276                        | PatKind::Never
1277                        | PatKind::Binding(..)
1278                        | PatKind::Box(..)
1279                        | PatKind::Deref(_)
1280                        | PatKind::Ref(..)
1281                        | PatKind::Expr(..)
1282                        | PatKind::Range(..)
1283                        | PatKind::Err(_) => break 'block None,
1284                    },
1285
1286                    // Don't provide suggestions in other cases
1287                    _ => break 'block None,
1288                };
1289
1290                Some((
1291                    pat.span,
1292                    format!("to declare a mutable {ident_kind} use"),
1293                    format!("mut {binding}"),
1294                ))
1295            };
1296
1297            match binding_parent {
1298                // Check that there is explicit type (ie this is not a closure param with inferred type)
1299                // so we don't suggest moving something to the type that does not exist
1300                hir::Node::Param(hir::Param { ty_span, pat, .. }) if pat.span != *ty_span => {
1301                    err.multipart_suggestion_verbose(
1302                        format!("to take parameter `{binding}` by reference, move `&{mutability}` to the type"),
1303                        vec![
1304                            (pat.span.until(inner.span), "".to_owned()),
1305                            (ty_span.shrink_to_lo(), mutbl.ref_prefix_str().to_owned()),
1306                        ],
1307                        Applicability::MachineApplicable
1308                    );
1309
1310                    if let Some((sp, msg, sugg)) = mut_var_suggestion {
1311                        err.span_note(sp, format!("{msg}: `{sugg}`"));
1312                    }
1313                }
1314                hir::Node::Pat(pt) if let PatKind::TupleStruct(_, pat_arr, _) = pt.kind => {
1315                    for i in pat_arr.iter() {
1316                        if let PatKind::Ref(the_ref, _) = i.kind
1317                            && let PatKind::Binding(mt, _, ident, _) = the_ref.kind
1318                        {
1319                            let BindingMode(_, mtblty) = mt;
1320                            err.span_suggestion_verbose(
1321                                i.span,
1322                                format!("consider removing `&{mutability}` from the pattern"),
1323                                mtblty.prefix_str().to_string() + &ident.name.to_string(),
1324                                Applicability::MaybeIncorrect,
1325                            );
1326                        }
1327                    }
1328                    if let Some((sp, msg, sugg)) = mut_var_suggestion {
1329                        err.span_note(sp, format!("{msg}: `{sugg}`"));
1330                    }
1331                }
1332                hir::Node::Param(_) | hir::Node::Arm(_) | hir::Node::Pat(_) => {
1333                    // rely on match ergonomics or it might be nested `&&pat`
1334                    err.span_suggestion_verbose(
1335                        pat.span.until(inner.span),
1336                        format!("consider removing `&{mutability}` from the pattern"),
1337                        "",
1338                        Applicability::MaybeIncorrect,
1339                    );
1340
1341                    if let Some((sp, msg, sugg)) = mut_var_suggestion {
1342                        err.span_note(sp, format!("{msg}: `{sugg}`"));
1343                    }
1344                }
1345                _ if let Some((sp, msg, sugg)) = mut_var_suggestion => {
1346                    err.span_suggestion(sp, msg, sugg, Applicability::MachineApplicable);
1347                }
1348                _ => {} // don't provide suggestions in other cases #55175
1349            }
1350        }
1351    }
1352
1353    fn check_dereferenceable(
1354        &self,
1355        span: Span,
1356        expected: Ty<'tcx>,
1357        inner: &Pat<'_>,
1358    ) -> Result<(), ErrorGuaranteed> {
1359        if let PatKind::Binding(..) = inner.kind
1360            && let Some(pointee_ty) = self.shallow_resolve(expected).builtin_deref(true)
1361            && let ty::Dynamic(..) = pointee_ty.kind()
1362        {
1363            // This is "x = dyn SomeTrait" being reduced from
1364            // "let &x = &dyn SomeTrait" or "let box x = Box<dyn SomeTrait>", an error.
1365            let type_str = self.ty_to_string(expected);
1366            let mut err = struct_span_code_err!(
1367                self.dcx(),
1368                span,
1369                E0033,
1370                "type `{}` cannot be dereferenced",
1371                type_str
1372            );
1373            err.span_label(span, format!("type `{type_str}` cannot be dereferenced"));
1374            if self.tcx.sess.teach(err.code.unwrap()) {
1375                err.note(CANNOT_IMPLICITLY_DEREF_POINTER_TRAIT_OBJ);
1376            }
1377            return Err(err.emit());
1378        }
1379        Ok(())
1380    }
1381
1382    fn resolve_pat_struct(
1383        &self,
1384        pat: &'tcx Pat<'tcx>,
1385        qpath: &hir::QPath<'tcx>,
1386    ) -> Result<ResolvedPat<'tcx>, ErrorGuaranteed> {
1387        // Resolve the path and check the definition for errors.
1388        let (variant, pat_ty) = self.check_struct_path(qpath, pat.hir_id)?;
1389        Ok(ResolvedPat { ty: pat_ty, kind: ResolvedPatKind::Struct { variant } })
1390    }
1391
1392    fn check_pat_struct(
1393        &self,
1394        pat: &'tcx Pat<'tcx>,
1395        fields: &'tcx [hir::PatField<'tcx>],
1396        has_rest_pat: bool,
1397        pat_ty: Ty<'tcx>,
1398        variant: &'tcx VariantDef,
1399        expected: Ty<'tcx>,
1400        pat_info: PatInfo<'tcx>,
1401    ) -> Ty<'tcx> {
1402        // Type-check the path.
1403        let _ = self.demand_eqtype_pat(pat.span, expected, pat_ty, &pat_info.top_info);
1404
1405        // Type-check subpatterns.
1406        match self.check_struct_pat_fields(pat_ty, pat, variant, fields, has_rest_pat, pat_info) {
1407            Ok(()) => pat_ty,
1408            Err(guar) => Ty::new_error(self.tcx, guar),
1409        }
1410    }
1411
1412    fn resolve_pat_path(
1413        &self,
1414        path_id: HirId,
1415        span: Span,
1416        qpath: &'tcx hir::QPath<'_>,
1417    ) -> Result<ResolvedPat<'tcx>, ErrorGuaranteed> {
1418        let tcx = self.tcx;
1419
1420        let (res, opt_ty, segments) =
1421            self.resolve_ty_and_res_fully_qualified_call(qpath, path_id, span);
1422        match res {
1423            Res::Err => {
1424                let e =
1425                    self.dcx().span_delayed_bug(qpath.span(), "`Res::Err` but no error emitted");
1426                self.set_tainted_by_errors(e);
1427                return Err(e);
1428            }
1429            Res::Def(DefKind::AssocFn | DefKind::Ctor(_, CtorKind::Fn) | DefKind::Variant, _) => {
1430                let expected = "unit struct, unit variant or constant";
1431                let e = report_unexpected_variant_res(tcx, res, None, qpath, span, E0533, expected);
1432                return Err(e);
1433            }
1434            Res::SelfCtor(def_id) => {
1435                if let ty::Adt(adt_def, _) = *tcx.type_of(def_id).skip_binder().kind()
1436                    && adt_def.is_struct()
1437                    && let Some((CtorKind::Const, _)) = adt_def.non_enum_variant().ctor
1438                {
1439                    // Ok, we allow unit struct ctors in patterns only.
1440                } else {
1441                    let e = report_unexpected_variant_res(
1442                        tcx,
1443                        res,
1444                        None,
1445                        qpath,
1446                        span,
1447                        E0533,
1448                        "unit struct",
1449                    );
1450                    return Err(e);
1451                }
1452            }
1453            Res::Def(
1454                DefKind::Ctor(_, CtorKind::Const)
1455                | DefKind::Const
1456                | DefKind::AssocConst
1457                | DefKind::ConstParam,
1458                _,
1459            ) => {} // OK
1460            _ => bug!("unexpected pattern resolution: {:?}", res),
1461        }
1462
1463        // Find the type of the path pattern, for later checking.
1464        let (pat_ty, pat_res) =
1465            self.instantiate_value_path(segments, opt_ty, res, span, span, path_id);
1466        Ok(ResolvedPat { ty: pat_ty, kind: ResolvedPatKind::Path { res, pat_res, segments } })
1467    }
1468
1469    fn check_pat_path(
1470        &self,
1471        pat_id_for_diag: HirId,
1472        span: Span,
1473        resolved: &ResolvedPat<'tcx>,
1474        expected: Ty<'tcx>,
1475        ti: &TopInfo<'tcx>,
1476    ) -> Ty<'tcx> {
1477        if let Err(err) =
1478            self.demand_suptype_with_origin(&self.pattern_cause(ti, span), expected, resolved.ty)
1479        {
1480            self.emit_bad_pat_path(err, pat_id_for_diag, span, resolved);
1481        }
1482        resolved.ty
1483    }
1484
1485    fn maybe_suggest_range_literal(
1486        &self,
1487        e: &mut Diag<'_>,
1488        opt_def_id: Option<hir::def_id::DefId>,
1489        ident: Ident,
1490    ) -> bool {
1491        if let Some(def_id) = opt_def_id
1492            && let Some(hir::Node::Item(hir::Item {
1493                kind: hir::ItemKind::Const(_, _, _, body_id),
1494                ..
1495            })) = self.tcx.hir_get_if_local(def_id)
1496            && let hir::Node::Expr(expr) = self.tcx.hir_node(body_id.hir_id)
1497            && hir::is_range_literal(expr)
1498        {
1499            let span = self.tcx.hir_span(body_id.hir_id);
1500            if let Ok(snip) = self.tcx.sess.source_map().span_to_snippet(span) {
1501                e.span_suggestion_verbose(
1502                    ident.span,
1503                    "you may want to move the range into the match block",
1504                    snip,
1505                    Applicability::MachineApplicable,
1506                );
1507                return true;
1508            }
1509        }
1510        false
1511    }
1512
1513    fn emit_bad_pat_path(
1514        &self,
1515        mut e: Diag<'_>,
1516        hir_id: HirId,
1517        pat_span: Span,
1518        resolved_pat: &ResolvedPat<'tcx>,
1519    ) {
1520        let ResolvedPatKind::Path { res, pat_res, segments } = resolved_pat.kind else {
1521            span_bug!(pat_span, "unexpected resolution for path pattern: {resolved_pat:?}");
1522        };
1523
1524        if let Some(span) = self.tcx.hir_res_span(pat_res) {
1525            e.span_label(span, format!("{} defined here", res.descr()));
1526            if let [hir::PathSegment { ident, .. }] = segments {
1527                e.span_label(
1528                    pat_span,
1529                    format!(
1530                        "`{}` is interpreted as {} {}, not a new binding",
1531                        ident,
1532                        res.article(),
1533                        res.descr(),
1534                    ),
1535                );
1536                match self.tcx.parent_hir_node(hir_id) {
1537                    hir::Node::PatField(..) => {
1538                        e.span_suggestion_verbose(
1539                            ident.span.shrink_to_hi(),
1540                            "bind the struct field to a different name instead",
1541                            format!(": other_{}", ident.as_str().to_lowercase()),
1542                            Applicability::HasPlaceholders,
1543                        );
1544                    }
1545                    _ => {
1546                        let (type_def_id, item_def_id) = match resolved_pat.ty.kind() {
1547                            ty::Adt(def, _) => match res {
1548                                Res::Def(DefKind::Const, def_id) => (Some(def.did()), Some(def_id)),
1549                                _ => (None, None),
1550                            },
1551                            _ => (None, None),
1552                        };
1553
1554                        let is_range = matches!(
1555                            type_def_id.and_then(|id| self.tcx.as_lang_item(id)),
1556                            Some(
1557                                LangItem::Range
1558                                    | LangItem::RangeFrom
1559                                    | LangItem::RangeTo
1560                                    | LangItem::RangeFull
1561                                    | LangItem::RangeInclusiveStruct
1562                                    | LangItem::RangeToInclusive,
1563                            )
1564                        );
1565                        if is_range {
1566                            if !self.maybe_suggest_range_literal(&mut e, item_def_id, *ident) {
1567                                let msg = "constants only support matching by type, \
1568                                    if you meant to match against a range of values, \
1569                                    consider using a range pattern like `min ..= max` in the match block";
1570                                e.note(msg);
1571                            }
1572                        } else {
1573                            let msg = "introduce a new binding instead";
1574                            let sugg = format!("other_{}", ident.as_str().to_lowercase());
1575                            e.span_suggestion(
1576                                ident.span,
1577                                msg,
1578                                sugg,
1579                                Applicability::HasPlaceholders,
1580                            );
1581                        }
1582                    }
1583                };
1584            }
1585        }
1586        e.emit();
1587    }
1588
1589    fn resolve_pat_tuple_struct(
1590        &self,
1591        pat: &'tcx Pat<'tcx>,
1592        qpath: &'tcx hir::QPath<'tcx>,
1593    ) -> Result<ResolvedPat<'tcx>, ErrorGuaranteed> {
1594        let tcx = self.tcx;
1595        let report_unexpected_res = |res: Res| {
1596            let expected = "tuple struct or tuple variant";
1597            let e = report_unexpected_variant_res(tcx, res, None, qpath, pat.span, E0164, expected);
1598            Err(e)
1599        };
1600
1601        // Resolve the path and check the definition for errors.
1602        let (res, opt_ty, segments) =
1603            self.resolve_ty_and_res_fully_qualified_call(qpath, pat.hir_id, pat.span);
1604        if res == Res::Err {
1605            let e = self.dcx().span_delayed_bug(pat.span, "`Res::Err` but no error emitted");
1606            self.set_tainted_by_errors(e);
1607            return Err(e);
1608        }
1609
1610        // Type-check the path.
1611        let (pat_ty, res) =
1612            self.instantiate_value_path(segments, opt_ty, res, pat.span, pat.span, pat.hir_id);
1613        if !pat_ty.is_fn() {
1614            return report_unexpected_res(res);
1615        }
1616
1617        let variant = match res {
1618            Res::Err => {
1619                self.dcx().span_bug(pat.span, "`Res::Err` but no error emitted");
1620            }
1621            Res::Def(DefKind::AssocConst | DefKind::AssocFn, _) => {
1622                return report_unexpected_res(res);
1623            }
1624            Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) => tcx.expect_variant_res(res),
1625            _ => bug!("unexpected pattern resolution: {:?}", res),
1626        };
1627
1628        // Replace constructor type with constructed type for tuple struct patterns.
1629        let pat_ty = pat_ty.fn_sig(tcx).output();
1630        let pat_ty = pat_ty.no_bound_vars().expect("expected fn type");
1631
1632        Ok(ResolvedPat { ty: pat_ty, kind: ResolvedPatKind::TupleStruct { res, variant } })
1633    }
1634
1635    fn check_pat_tuple_struct(
1636        &self,
1637        pat: &'tcx Pat<'tcx>,
1638        qpath: &'tcx hir::QPath<'tcx>,
1639        subpats: &'tcx [Pat<'tcx>],
1640        ddpos: hir::DotDotPos,
1641        res: Res,
1642        pat_ty: Ty<'tcx>,
1643        variant: &'tcx VariantDef,
1644        expected: Ty<'tcx>,
1645        pat_info: PatInfo<'tcx>,
1646    ) -> Ty<'tcx> {
1647        let tcx = self.tcx;
1648        let on_error = |e| {
1649            for pat in subpats {
1650                self.check_pat(pat, Ty::new_error(tcx, e), pat_info);
1651            }
1652        };
1653
1654        // Type-check the tuple struct pattern against the expected type.
1655        let diag = self.demand_eqtype_pat_diag(pat.span, expected, pat_ty, &pat_info.top_info);
1656        let had_err = diag.map_err(|diag| diag.emit());
1657
1658        // Type-check subpatterns.
1659        if subpats.len() == variant.fields.len()
1660            || subpats.len() < variant.fields.len() && ddpos.as_opt_usize().is_some()
1661        {
1662            let ty::Adt(_, args) = pat_ty.kind() else {
1663                bug!("unexpected pattern type {:?}", pat_ty);
1664            };
1665            for (i, subpat) in subpats.iter().enumerate_and_adjust(variant.fields.len(), ddpos) {
1666                let field = &variant.fields[FieldIdx::from_usize(i)];
1667                let field_ty = self.field_ty(subpat.span, field, args);
1668                self.check_pat(subpat, field_ty, pat_info);
1669
1670                self.tcx.check_stability(
1671                    variant.fields[FieldIdx::from_usize(i)].did,
1672                    Some(subpat.hir_id),
1673                    subpat.span,
1674                    None,
1675                );
1676            }
1677            if let Err(e) = had_err {
1678                on_error(e);
1679                return Ty::new_error(tcx, e);
1680            }
1681        } else {
1682            let e = self.emit_err_pat_wrong_number_of_fields(
1683                pat.span,
1684                res,
1685                qpath,
1686                subpats,
1687                &variant.fields.raw,
1688                expected,
1689                had_err,
1690            );
1691            on_error(e);
1692            return Ty::new_error(tcx, e);
1693        }
1694        pat_ty
1695    }
1696
1697    fn emit_err_pat_wrong_number_of_fields(
1698        &self,
1699        pat_span: Span,
1700        res: Res,
1701        qpath: &hir::QPath<'_>,
1702        subpats: &'tcx [Pat<'tcx>],
1703        fields: &'tcx [ty::FieldDef],
1704        expected: Ty<'tcx>,
1705        had_err: Result<(), ErrorGuaranteed>,
1706    ) -> ErrorGuaranteed {
1707        let subpats_ending = pluralize!(subpats.len());
1708        let fields_ending = pluralize!(fields.len());
1709
1710        let subpat_spans = if subpats.is_empty() {
1711            vec![pat_span]
1712        } else {
1713            subpats.iter().map(|p| p.span).collect()
1714        };
1715        let last_subpat_span = *subpat_spans.last().unwrap();
1716        let res_span = self.tcx.def_span(res.def_id());
1717        let def_ident_span = self.tcx.def_ident_span(res.def_id()).unwrap_or(res_span);
1718        let field_def_spans = if fields.is_empty() {
1719            vec![res_span]
1720        } else {
1721            fields.iter().map(|f| f.ident(self.tcx).span).collect()
1722        };
1723        let last_field_def_span = *field_def_spans.last().unwrap();
1724
1725        let mut err = struct_span_code_err!(
1726            self.dcx(),
1727            MultiSpan::from_spans(subpat_spans),
1728            E0023,
1729            "this pattern has {} field{}, but the corresponding {} has {} field{}",
1730            subpats.len(),
1731            subpats_ending,
1732            res.descr(),
1733            fields.len(),
1734            fields_ending,
1735        );
1736        err.span_label(
1737            last_subpat_span,
1738            format!("expected {} field{}, found {}", fields.len(), fields_ending, subpats.len()),
1739        );
1740        if self.tcx.sess.source_map().is_multiline(qpath.span().between(last_subpat_span)) {
1741            err.span_label(qpath.span(), "");
1742        }
1743        if self.tcx.sess.source_map().is_multiline(def_ident_span.between(last_field_def_span)) {
1744            err.span_label(def_ident_span, format!("{} defined here", res.descr()));
1745        }
1746        for span in &field_def_spans[..field_def_spans.len() - 1] {
1747            err.span_label(*span, "");
1748        }
1749        err.span_label(
1750            last_field_def_span,
1751            format!("{} has {} field{}", res.descr(), fields.len(), fields_ending),
1752        );
1753
1754        // Identify the case `Some(x, y)` where the expected type is e.g. `Option<(T, U)>`.
1755        // More generally, the expected type wants a tuple variant with one field of an
1756        // N-arity-tuple, e.g., `V_i((p_0, .., p_N))`. Meanwhile, the user supplied a pattern
1757        // with the subpatterns directly in the tuple variant pattern, e.g., `V_i(p_0, .., p_N)`.
1758        let missing_parentheses = match (expected.kind(), fields, had_err) {
1759            // #67037: only do this if we could successfully type-check the expected type against
1760            // the tuple struct pattern. Otherwise the args could get out of range on e.g.,
1761            // `let P() = U;` where `P != U` with `struct Box<T>(T);`.
1762            (ty::Adt(_, args), [field], Ok(())) => {
1763                let field_ty = self.field_ty(pat_span, field, args);
1764                match field_ty.kind() {
1765                    ty::Tuple(fields) => fields.len() == subpats.len(),
1766                    _ => false,
1767                }
1768            }
1769            _ => false,
1770        };
1771        if missing_parentheses {
1772            let (left, right) = match subpats {
1773                // This is the zero case; we aim to get the "hi" part of the `QPath`'s
1774                // span as the "lo" and then the "hi" part of the pattern's span as the "hi".
1775                // This looks like:
1776                //
1777                // help: missing parentheses
1778                //   |
1779                // L |     let A(()) = A(());
1780                //   |          ^  ^
1781                [] => (qpath.span().shrink_to_hi(), pat_span),
1782                // Easy case. Just take the "lo" of the first sub-pattern and the "hi" of the
1783                // last sub-pattern. In the case of `A(x)` the first and last may coincide.
1784                // This looks like:
1785                //
1786                // help: missing parentheses
1787                //   |
1788                // L |     let A((x, y)) = A((1, 2));
1789                //   |           ^    ^
1790                [first, ..] => (first.span.shrink_to_lo(), subpats.last().unwrap().span),
1791            };
1792            err.multipart_suggestion(
1793                "missing parentheses",
1794                vec![(left, "(".to_string()), (right.shrink_to_hi(), ")".to_string())],
1795                Applicability::MachineApplicable,
1796            );
1797        } else if fields.len() > subpats.len() && pat_span != DUMMY_SP {
1798            let after_fields_span = pat_span.with_hi(pat_span.hi() - BytePos(1)).shrink_to_hi();
1799            let all_fields_span = match subpats {
1800                [] => after_fields_span,
1801                [field] => field.span,
1802                [first, .., last] => first.span.to(last.span),
1803            };
1804
1805            // Check if all the fields in the pattern are wildcards.
1806            let all_wildcards = subpats.iter().all(|pat| matches!(pat.kind, PatKind::Wild));
1807            let first_tail_wildcard =
1808                subpats.iter().enumerate().fold(None, |acc, (pos, pat)| match (acc, &pat.kind) {
1809                    (None, PatKind::Wild) => Some(pos),
1810                    (Some(_), PatKind::Wild) => acc,
1811                    _ => None,
1812                });
1813            let tail_span = match first_tail_wildcard {
1814                None => after_fields_span,
1815                Some(0) => subpats[0].span.to(after_fields_span),
1816                Some(pos) => subpats[pos - 1].span.shrink_to_hi().to(after_fields_span),
1817            };
1818
1819            // FIXME: heuristic-based suggestion to check current types for where to add `_`.
1820            let mut wildcard_sugg = vec!["_"; fields.len() - subpats.len()].join(", ");
1821            if !subpats.is_empty() {
1822                wildcard_sugg = String::from(", ") + &wildcard_sugg;
1823            }
1824
1825            err.span_suggestion_verbose(
1826                after_fields_span,
1827                "use `_` to explicitly ignore each field",
1828                wildcard_sugg,
1829                Applicability::MaybeIncorrect,
1830            );
1831
1832            // Only suggest `..` if more than one field is missing
1833            // or the pattern consists of all wildcards.
1834            if fields.len() - subpats.len() > 1 || all_wildcards {
1835                if subpats.is_empty() || all_wildcards {
1836                    err.span_suggestion_verbose(
1837                        all_fields_span,
1838                        "use `..` to ignore all fields",
1839                        "..",
1840                        Applicability::MaybeIncorrect,
1841                    );
1842                } else {
1843                    err.span_suggestion_verbose(
1844                        tail_span,
1845                        "use `..` to ignore the rest of the fields",
1846                        ", ..",
1847                        Applicability::MaybeIncorrect,
1848                    );
1849                }
1850            }
1851        }
1852
1853        err.emit()
1854    }
1855
1856    fn check_pat_tuple(
1857        &self,
1858        span: Span,
1859        elements: &'tcx [Pat<'tcx>],
1860        ddpos: hir::DotDotPos,
1861        expected: Ty<'tcx>,
1862        pat_info: PatInfo<'tcx>,
1863    ) -> Ty<'tcx> {
1864        let tcx = self.tcx;
1865        let mut expected_len = elements.len();
1866        if ddpos.as_opt_usize().is_some() {
1867            // Require known type only when `..` is present.
1868            if let ty::Tuple(tys) = self.structurally_resolve_type(span, expected).kind() {
1869                expected_len = tys.len();
1870            }
1871        }
1872        let max_len = cmp::max(expected_len, elements.len());
1873
1874        let element_tys_iter = (0..max_len).map(|_| self.next_ty_var(span));
1875        let element_tys = tcx.mk_type_list_from_iter(element_tys_iter);
1876        let pat_ty = Ty::new_tup(tcx, element_tys);
1877        if let Err(reported) = self.demand_eqtype_pat(span, expected, pat_ty, &pat_info.top_info) {
1878            // Walk subpatterns with an expected type of `err` in this case to silence
1879            // further errors being emitted when using the bindings. #50333
1880            let element_tys_iter = (0..max_len).map(|_| Ty::new_error(tcx, reported));
1881            for (_, elem) in elements.iter().enumerate_and_adjust(max_len, ddpos) {
1882                self.check_pat(elem, Ty::new_error(tcx, reported), pat_info);
1883            }
1884            Ty::new_tup_from_iter(tcx, element_tys_iter)
1885        } else {
1886            for (i, elem) in elements.iter().enumerate_and_adjust(max_len, ddpos) {
1887                self.check_pat(elem, element_tys[i], pat_info);
1888            }
1889            pat_ty
1890        }
1891    }
1892
1893    fn check_struct_pat_fields(
1894        &self,
1895        adt_ty: Ty<'tcx>,
1896        pat: &'tcx Pat<'tcx>,
1897        variant: &'tcx ty::VariantDef,
1898        fields: &'tcx [hir::PatField<'tcx>],
1899        has_rest_pat: bool,
1900        pat_info: PatInfo<'tcx>,
1901    ) -> Result<(), ErrorGuaranteed> {
1902        let tcx = self.tcx;
1903
1904        let ty::Adt(adt, args) = adt_ty.kind() else {
1905            span_bug!(pat.span, "struct pattern is not an ADT");
1906        };
1907
1908        // Index the struct fields' types.
1909        let field_map = variant
1910            .fields
1911            .iter_enumerated()
1912            .map(|(i, field)| (field.ident(self.tcx).normalize_to_macros_2_0(), (i, field)))
1913            .collect::<FxHashMap<_, _>>();
1914
1915        // Keep track of which fields have already appeared in the pattern.
1916        let mut used_fields = FxHashMap::default();
1917        let mut result = Ok(());
1918
1919        let mut inexistent_fields = vec![];
1920        // Typecheck each field.
1921        for field in fields {
1922            let span = field.span;
1923            let ident = tcx.adjust_ident(field.ident, variant.def_id);
1924            let field_ty = match used_fields.entry(ident) {
1925                Occupied(occupied) => {
1926                    let guar = self.error_field_already_bound(span, field.ident, *occupied.get());
1927                    result = Err(guar);
1928                    Ty::new_error(tcx, guar)
1929                }
1930                Vacant(vacant) => {
1931                    vacant.insert(span);
1932                    field_map
1933                        .get(&ident)
1934                        .map(|(i, f)| {
1935                            self.write_field_index(field.hir_id, *i);
1936                            self.tcx.check_stability(f.did, Some(field.hir_id), span, None);
1937                            self.field_ty(span, f, args)
1938                        })
1939                        .unwrap_or_else(|| {
1940                            inexistent_fields.push(field);
1941                            Ty::new_misc_error(tcx)
1942                        })
1943                }
1944            };
1945
1946            self.check_pat(field.pat, field_ty, pat_info);
1947        }
1948
1949        let mut unmentioned_fields = variant
1950            .fields
1951            .iter()
1952            .map(|field| (field, field.ident(self.tcx).normalize_to_macros_2_0()))
1953            .filter(|(_, ident)| !used_fields.contains_key(ident))
1954            .collect::<Vec<_>>();
1955
1956        let inexistent_fields_err = if !inexistent_fields.is_empty()
1957            && !inexistent_fields.iter().any(|field| field.ident.name == kw::Underscore)
1958        {
1959            // we don't care to report errors for a struct if the struct itself is tainted
1960            variant.has_errors()?;
1961            Some(self.error_inexistent_fields(
1962                adt.variant_descr(),
1963                &inexistent_fields,
1964                &mut unmentioned_fields,
1965                pat,
1966                variant,
1967                args,
1968            ))
1969        } else {
1970            None
1971        };
1972
1973        // Require `..` if struct has non_exhaustive attribute.
1974        let non_exhaustive = variant.field_list_has_applicable_non_exhaustive();
1975        if non_exhaustive && !has_rest_pat {
1976            self.error_foreign_non_exhaustive_spat(pat, adt.variant_descr(), fields.is_empty());
1977        }
1978
1979        let mut unmentioned_err = None;
1980        // Report an error if an incorrect number of fields was specified.
1981        if adt.is_union() {
1982            if fields.len() != 1 {
1983                self.dcx().emit_err(errors::UnionPatMultipleFields { span: pat.span });
1984            }
1985            if has_rest_pat {
1986                self.dcx().emit_err(errors::UnionPatDotDot { span: pat.span });
1987            }
1988        } else if !unmentioned_fields.is_empty() {
1989            let accessible_unmentioned_fields: Vec<_> = unmentioned_fields
1990                .iter()
1991                .copied()
1992                .filter(|(field, _)| self.is_field_suggestable(field, pat.hir_id, pat.span))
1993                .collect();
1994
1995            if !has_rest_pat {
1996                if accessible_unmentioned_fields.is_empty() {
1997                    unmentioned_err = Some(self.error_no_accessible_fields(pat, fields));
1998                } else {
1999                    unmentioned_err = Some(self.error_unmentioned_fields(
2000                        pat,
2001                        &accessible_unmentioned_fields,
2002                        accessible_unmentioned_fields.len() != unmentioned_fields.len(),
2003                        fields,
2004                    ));
2005                }
2006            } else if non_exhaustive && !accessible_unmentioned_fields.is_empty() {
2007                self.lint_non_exhaustive_omitted_patterns(
2008                    pat,
2009                    &accessible_unmentioned_fields,
2010                    adt_ty,
2011                )
2012            }
2013        }
2014        match (inexistent_fields_err, unmentioned_err) {
2015            (Some(i), Some(u)) => {
2016                if let Err(e) = self.error_tuple_variant_as_struct_pat(pat, fields, variant) {
2017                    // We don't want to show the nonexistent fields error when this was
2018                    // `Foo { a, b }` when it should have been `Foo(a, b)`.
2019                    i.delay_as_bug();
2020                    u.delay_as_bug();
2021                    Err(e)
2022                } else {
2023                    i.emit();
2024                    Err(u.emit())
2025                }
2026            }
2027            (None, Some(u)) => {
2028                if let Err(e) = self.error_tuple_variant_as_struct_pat(pat, fields, variant) {
2029                    u.delay_as_bug();
2030                    Err(e)
2031                } else {
2032                    Err(u.emit())
2033                }
2034            }
2035            (Some(err), None) => Err(err.emit()),
2036            (None, None) => {
2037                self.error_tuple_variant_index_shorthand(variant, pat, fields)?;
2038                result
2039            }
2040        }
2041    }
2042
2043    fn error_tuple_variant_index_shorthand(
2044        &self,
2045        variant: &VariantDef,
2046        pat: &'_ Pat<'_>,
2047        fields: &[hir::PatField<'_>],
2048    ) -> Result<(), ErrorGuaranteed> {
2049        // if this is a tuple struct, then all field names will be numbers
2050        // so if any fields in a struct pattern use shorthand syntax, they will
2051        // be invalid identifiers (for example, Foo { 0, 1 }).
2052        if let (Some(CtorKind::Fn), PatKind::Struct(qpath, field_patterns, ..)) =
2053            (variant.ctor_kind(), &pat.kind)
2054        {
2055            let has_shorthand_field_name = field_patterns.iter().any(|field| field.is_shorthand);
2056            if has_shorthand_field_name {
2057                let path = rustc_hir_pretty::qpath_to_string(&self.tcx, qpath);
2058                let mut err = struct_span_code_err!(
2059                    self.dcx(),
2060                    pat.span,
2061                    E0769,
2062                    "tuple variant `{path}` written as struct variant",
2063                );
2064                err.span_suggestion_verbose(
2065                    qpath.span().shrink_to_hi().to(pat.span.shrink_to_hi()),
2066                    "use the tuple variant pattern syntax instead",
2067                    format!("({})", self.get_suggested_tuple_struct_pattern(fields, variant)),
2068                    Applicability::MaybeIncorrect,
2069                );
2070                return Err(err.emit());
2071            }
2072        }
2073        Ok(())
2074    }
2075
2076    fn error_foreign_non_exhaustive_spat(&self, pat: &Pat<'_>, descr: &str, no_fields: bool) {
2077        let sess = self.tcx.sess;
2078        let sm = sess.source_map();
2079        let sp_brace = sm.end_point(pat.span);
2080        let sp_comma = sm.end_point(pat.span.with_hi(sp_brace.hi()));
2081        let sugg = if no_fields || sp_brace != sp_comma { ".. }" } else { ", .. }" };
2082
2083        struct_span_code_err!(
2084            self.dcx(),
2085            pat.span,
2086            E0638,
2087            "`..` required with {descr} marked as non-exhaustive",
2088        )
2089        .with_span_suggestion_verbose(
2090            sp_comma,
2091            "add `..` at the end of the field list to ignore all other fields",
2092            sugg,
2093            Applicability::MachineApplicable,
2094        )
2095        .emit();
2096    }
2097
2098    fn error_field_already_bound(
2099        &self,
2100        span: Span,
2101        ident: Ident,
2102        other_field: Span,
2103    ) -> ErrorGuaranteed {
2104        struct_span_code_err!(
2105            self.dcx(),
2106            span,
2107            E0025,
2108            "field `{}` bound multiple times in the pattern",
2109            ident
2110        )
2111        .with_span_label(span, format!("multiple uses of `{ident}` in pattern"))
2112        .with_span_label(other_field, format!("first use of `{ident}`"))
2113        .emit()
2114    }
2115
2116    fn error_inexistent_fields(
2117        &self,
2118        kind_name: &str,
2119        inexistent_fields: &[&hir::PatField<'tcx>],
2120        unmentioned_fields: &mut Vec<(&'tcx ty::FieldDef, Ident)>,
2121        pat: &'tcx Pat<'tcx>,
2122        variant: &ty::VariantDef,
2123        args: ty::GenericArgsRef<'tcx>,
2124    ) -> Diag<'a> {
2125        let tcx = self.tcx;
2126        let (field_names, t, plural) = if let [field] = inexistent_fields {
2127            (format!("a field named `{}`", field.ident), "this", "")
2128        } else {
2129            (
2130                format!(
2131                    "fields named {}",
2132                    inexistent_fields
2133                        .iter()
2134                        .map(|field| format!("`{}`", field.ident))
2135                        .collect::<Vec<String>>()
2136                        .join(", ")
2137                ),
2138                "these",
2139                "s",
2140            )
2141        };
2142        let spans = inexistent_fields.iter().map(|field| field.ident.span).collect::<Vec<_>>();
2143        let mut err = struct_span_code_err!(
2144            self.dcx(),
2145            spans,
2146            E0026,
2147            "{} `{}` does not have {}",
2148            kind_name,
2149            tcx.def_path_str(variant.def_id),
2150            field_names
2151        );
2152        if let Some(pat_field) = inexistent_fields.last() {
2153            err.span_label(
2154                pat_field.ident.span,
2155                format!(
2156                    "{} `{}` does not have {} field{}",
2157                    kind_name,
2158                    tcx.def_path_str(variant.def_id),
2159                    t,
2160                    plural
2161                ),
2162            );
2163
2164            if let [(field_def, field)] = unmentioned_fields.as_slice()
2165                && self.is_field_suggestable(field_def, pat.hir_id, pat.span)
2166            {
2167                let suggested_name =
2168                    find_best_match_for_name(&[field.name], pat_field.ident.name, None);
2169                if let Some(suggested_name) = suggested_name {
2170                    err.span_suggestion(
2171                        pat_field.ident.span,
2172                        "a field with a similar name exists",
2173                        suggested_name,
2174                        Applicability::MaybeIncorrect,
2175                    );
2176
2177                    // When we have a tuple struct used with struct we don't want to suggest using
2178                    // the (valid) struct syntax with numeric field names. Instead we want to
2179                    // suggest the expected syntax. We infer that this is the case by parsing the
2180                    // `Ident` into an unsized integer. The suggestion will be emitted elsewhere in
2181                    // `smart_resolve_context_dependent_help`.
2182                    if suggested_name.to_ident_string().parse::<usize>().is_err() {
2183                        // We don't want to throw `E0027` in case we have thrown `E0026` for them.
2184                        unmentioned_fields.retain(|&(_, x)| x.name != suggested_name);
2185                    }
2186                } else if inexistent_fields.len() == 1 {
2187                    match pat_field.pat.kind {
2188                        PatKind::Expr(_)
2189                            if !self.may_coerce(
2190                                self.typeck_results.borrow().node_type(pat_field.pat.hir_id),
2191                                self.field_ty(field.span, field_def, args),
2192                            ) => {}
2193                        _ => {
2194                            err.span_suggestion_short(
2195                                pat_field.ident.span,
2196                                format!(
2197                                    "`{}` has a field named `{}`",
2198                                    tcx.def_path_str(variant.def_id),
2199                                    field.name,
2200                                ),
2201                                field.name,
2202                                Applicability::MaybeIncorrect,
2203                            );
2204                        }
2205                    }
2206                }
2207            }
2208        }
2209        if tcx.sess.teach(err.code.unwrap()) {
2210            err.note(
2211                "This error indicates that a struct pattern attempted to \
2212                 extract a nonexistent field from a struct. Struct fields \
2213                 are identified by the name used before the colon : so struct \
2214                 patterns should resemble the declaration of the struct type \
2215                 being matched.\n\n\
2216                 If you are using shorthand field patterns but want to refer \
2217                 to the struct field by a different name, you should rename \
2218                 it explicitly.",
2219            );
2220        }
2221        err
2222    }
2223
2224    fn error_tuple_variant_as_struct_pat(
2225        &self,
2226        pat: &Pat<'_>,
2227        fields: &'tcx [hir::PatField<'tcx>],
2228        variant: &ty::VariantDef,
2229    ) -> Result<(), ErrorGuaranteed> {
2230        if let (Some(CtorKind::Fn), PatKind::Struct(qpath, pattern_fields, ..)) =
2231            (variant.ctor_kind(), &pat.kind)
2232        {
2233            let is_tuple_struct_match = !pattern_fields.is_empty()
2234                && pattern_fields.iter().map(|field| field.ident.name.as_str()).all(is_number);
2235            if is_tuple_struct_match {
2236                return Ok(());
2237            }
2238
2239            // we don't care to report errors for a struct if the struct itself is tainted
2240            variant.has_errors()?;
2241
2242            let path = rustc_hir_pretty::qpath_to_string(&self.tcx, qpath);
2243            let mut err = struct_span_code_err!(
2244                self.dcx(),
2245                pat.span,
2246                E0769,
2247                "tuple variant `{}` written as struct variant",
2248                path
2249            );
2250            let (sugg, appl) = if fields.len() == variant.fields.len() {
2251                (
2252                    self.get_suggested_tuple_struct_pattern(fields, variant),
2253                    Applicability::MachineApplicable,
2254                )
2255            } else {
2256                (
2257                    variant.fields.iter().map(|_| "_").collect::<Vec<&str>>().join(", "),
2258                    Applicability::MaybeIncorrect,
2259                )
2260            };
2261            err.span_suggestion_verbose(
2262                qpath.span().shrink_to_hi().to(pat.span.shrink_to_hi()),
2263                "use the tuple variant pattern syntax instead",
2264                format!("({sugg})"),
2265                appl,
2266            );
2267            return Err(err.emit());
2268        }
2269        Ok(())
2270    }
2271
2272    fn get_suggested_tuple_struct_pattern(
2273        &self,
2274        fields: &[hir::PatField<'_>],
2275        variant: &VariantDef,
2276    ) -> String {
2277        let variant_field_idents =
2278            variant.fields.iter().map(|f| f.ident(self.tcx)).collect::<Vec<Ident>>();
2279        fields
2280            .iter()
2281            .map(|field| {
2282                match self.tcx.sess.source_map().span_to_snippet(field.pat.span) {
2283                    Ok(f) => {
2284                        // Field names are numbers, but numbers
2285                        // are not valid identifiers
2286                        if variant_field_idents.contains(&field.ident) {
2287                            String::from("_")
2288                        } else {
2289                            f
2290                        }
2291                    }
2292                    Err(_) => rustc_hir_pretty::pat_to_string(&self.tcx, field.pat),
2293                }
2294            })
2295            .collect::<Vec<String>>()
2296            .join(", ")
2297    }
2298
2299    /// Returns a diagnostic reporting a struct pattern which is missing an `..` due to
2300    /// inaccessible fields.
2301    ///
2302    /// ```text
2303    /// error: pattern requires `..` due to inaccessible fields
2304    ///   --> src/main.rs:10:9
2305    ///    |
2306    /// LL |     let foo::Foo {} = foo::Foo::default();
2307    ///    |         ^^^^^^^^^^^
2308    ///    |
2309    /// help: add a `..`
2310    ///    |
2311    /// LL |     let foo::Foo { .. } = foo::Foo::default();
2312    ///    |                  ^^^^^^
2313    /// ```
2314    fn error_no_accessible_fields(
2315        &self,
2316        pat: &Pat<'_>,
2317        fields: &'tcx [hir::PatField<'tcx>],
2318    ) -> Diag<'a> {
2319        let mut err = self
2320            .dcx()
2321            .struct_span_err(pat.span, "pattern requires `..` due to inaccessible fields");
2322
2323        if let Some(field) = fields.last() {
2324            err.span_suggestion_verbose(
2325                field.span.shrink_to_hi(),
2326                "ignore the inaccessible and unused fields",
2327                ", ..",
2328                Applicability::MachineApplicable,
2329            );
2330        } else {
2331            let qpath_span = if let PatKind::Struct(qpath, ..) = &pat.kind {
2332                qpath.span()
2333            } else {
2334                bug!("`error_no_accessible_fields` called on non-struct pattern");
2335            };
2336
2337            // Shrink the span to exclude the `foo:Foo` in `foo::Foo { }`.
2338            let span = pat.span.with_lo(qpath_span.shrink_to_hi().hi());
2339            err.span_suggestion_verbose(
2340                span,
2341                "ignore the inaccessible and unused fields",
2342                " { .. }",
2343                Applicability::MachineApplicable,
2344            );
2345        }
2346        err
2347    }
2348
2349    /// Report that a pattern for a `#[non_exhaustive]` struct marked with `non_exhaustive_omitted_patterns`
2350    /// is not exhaustive enough.
2351    ///
2352    /// Nb: the partner lint for enums lives in `compiler/rustc_mir_build/src/thir/pattern/usefulness.rs`.
2353    fn lint_non_exhaustive_omitted_patterns(
2354        &self,
2355        pat: &Pat<'_>,
2356        unmentioned_fields: &[(&ty::FieldDef, Ident)],
2357        ty: Ty<'tcx>,
2358    ) {
2359        fn joined_uncovered_patterns(witnesses: &[&Ident]) -> String {
2360            const LIMIT: usize = 3;
2361            match witnesses {
2362                [] => {
2363                    unreachable!(
2364                        "expected an uncovered pattern, otherwise why are we emitting an error?"
2365                    )
2366                }
2367                [witness] => format!("`{witness}`"),
2368                [head @ .., tail] if head.len() < LIMIT => {
2369                    let head: Vec<_> = head.iter().map(<_>::to_string).collect();
2370                    format!("`{}` and `{}`", head.join("`, `"), tail)
2371                }
2372                _ => {
2373                    let (head, tail) = witnesses.split_at(LIMIT);
2374                    let head: Vec<_> = head.iter().map(<_>::to_string).collect();
2375                    format!("`{}` and {} more", head.join("`, `"), tail.len())
2376                }
2377            }
2378        }
2379        let joined_patterns = joined_uncovered_patterns(
2380            &unmentioned_fields.iter().map(|(_, i)| i).collect::<Vec<_>>(),
2381        );
2382
2383        self.tcx.node_span_lint(NON_EXHAUSTIVE_OMITTED_PATTERNS, pat.hir_id, pat.span, |lint| {
2384            lint.primary_message("some fields are not explicitly listed");
2385            lint.span_label(pat.span, format!("field{} {} not listed", rustc_errors::pluralize!(unmentioned_fields.len()), joined_patterns));
2386            lint.help(
2387                "ensure that all fields are mentioned explicitly by adding the suggested fields",
2388            );
2389            lint.note(format!(
2390                "the pattern is of type `{ty}` and the `non_exhaustive_omitted_patterns` attribute was found",
2391            ));
2392        });
2393    }
2394
2395    /// Returns a diagnostic reporting a struct pattern which does not mention some fields.
2396    ///
2397    /// ```text
2398    /// error[E0027]: pattern does not mention field `bar`
2399    ///   --> src/main.rs:15:9
2400    ///    |
2401    /// LL |     let foo::Foo {} = foo::Foo::new();
2402    ///    |         ^^^^^^^^^^^ missing field `bar`
2403    /// ```
2404    fn error_unmentioned_fields(
2405        &self,
2406        pat: &Pat<'_>,
2407        unmentioned_fields: &[(&ty::FieldDef, Ident)],
2408        have_inaccessible_fields: bool,
2409        fields: &'tcx [hir::PatField<'tcx>],
2410    ) -> Diag<'a> {
2411        let inaccessible = if have_inaccessible_fields { " and inaccessible fields" } else { "" };
2412        let field_names = if let [(_, field)] = unmentioned_fields {
2413            format!("field `{field}`{inaccessible}")
2414        } else {
2415            let fields = unmentioned_fields
2416                .iter()
2417                .map(|(_, name)| format!("`{name}`"))
2418                .collect::<Vec<String>>()
2419                .join(", ");
2420            format!("fields {fields}{inaccessible}")
2421        };
2422        let mut err = struct_span_code_err!(
2423            self.dcx(),
2424            pat.span,
2425            E0027,
2426            "pattern does not mention {}",
2427            field_names
2428        );
2429        err.span_label(pat.span, format!("missing {field_names}"));
2430        let len = unmentioned_fields.len();
2431        let (prefix, postfix, sp) = match fields {
2432            [] => match &pat.kind {
2433                PatKind::Struct(path, [], None) => {
2434                    (" { ", " }", path.span().shrink_to_hi().until(pat.span.shrink_to_hi()))
2435                }
2436                _ => return err,
2437            },
2438            [.., field] => {
2439                // Account for last field having a trailing comma or parse recovery at the tail of
2440                // the pattern to avoid invalid suggestion (#78511).
2441                let tail = field.span.shrink_to_hi().with_hi(pat.span.hi());
2442                match &pat.kind {
2443                    PatKind::Struct(..) => (", ", " }", tail),
2444                    _ => return err,
2445                }
2446            }
2447        };
2448        err.span_suggestion(
2449            sp,
2450            format!(
2451                "include the missing field{} in the pattern{}",
2452                pluralize!(len),
2453                if have_inaccessible_fields { " and ignore the inaccessible fields" } else { "" }
2454            ),
2455            format!(
2456                "{}{}{}{}",
2457                prefix,
2458                unmentioned_fields
2459                    .iter()
2460                    .map(|(_, name)| {
2461                        let field_name = name.to_string();
2462                        if is_number(&field_name) { format!("{field_name}: _") } else { field_name }
2463                    })
2464                    .collect::<Vec<_>>()
2465                    .join(", "),
2466                if have_inaccessible_fields { ", .." } else { "" },
2467                postfix,
2468            ),
2469            Applicability::MachineApplicable,
2470        );
2471        err.span_suggestion(
2472            sp,
2473            format!(
2474                "if you don't care about {these} missing field{s}, you can explicitly ignore {them}",
2475                these = pluralize!("this", len),
2476                s = pluralize!(len),
2477                them = if len == 1 { "it" } else { "them" },
2478            ),
2479            format!(
2480                "{}{}{}{}",
2481                prefix,
2482                unmentioned_fields
2483                    .iter()
2484                    .map(|(_, name)| {
2485                        let field_name = name.to_string();
2486                        format!("{field_name}: _")
2487                    })
2488                    .collect::<Vec<_>>()
2489                    .join(", "),
2490                if have_inaccessible_fields { ", .." } else { "" },
2491                postfix,
2492            ),
2493            Applicability::MachineApplicable,
2494        );
2495        err.span_suggestion(
2496            sp,
2497            "or always ignore missing fields here",
2498            format!("{prefix}..{postfix}"),
2499            Applicability::MachineApplicable,
2500        );
2501        err
2502    }
2503
2504    fn check_pat_box(
2505        &self,
2506        span: Span,
2507        inner: &'tcx Pat<'tcx>,
2508        expected: Ty<'tcx>,
2509        pat_info: PatInfo<'tcx>,
2510    ) -> Ty<'tcx> {
2511        let tcx = self.tcx;
2512        let (box_ty, inner_ty) = self
2513            .check_dereferenceable(span, expected, inner)
2514            .and_then(|()| {
2515                // Here, `demand::subtype` is good enough, but I don't
2516                // think any errors can be introduced by using `demand::eqtype`.
2517                let inner_ty = self.next_ty_var(inner.span);
2518                let box_ty = Ty::new_box(tcx, inner_ty);
2519                self.demand_eqtype_pat(span, expected, box_ty, &pat_info.top_info)?;
2520                Ok((box_ty, inner_ty))
2521            })
2522            .unwrap_or_else(|guar| {
2523                let err = Ty::new_error(tcx, guar);
2524                (err, err)
2525            });
2526        self.check_pat(inner, inner_ty, pat_info);
2527        box_ty
2528    }
2529
2530    fn check_pat_deref(
2531        &self,
2532        span: Span,
2533        inner: &'tcx Pat<'tcx>,
2534        expected: Ty<'tcx>,
2535        pat_info: PatInfo<'tcx>,
2536    ) -> Ty<'tcx> {
2537        let target_ty = self.deref_pat_target(span, expected);
2538        self.check_pat(inner, target_ty, pat_info);
2539        self.register_deref_mut_bounds_if_needed(span, inner, [expected]);
2540        expected
2541    }
2542
2543    fn deref_pat_target(&self, span: Span, source_ty: Ty<'tcx>) -> Ty<'tcx> {
2544        // Register a `DerefPure` bound, which is required by all `deref!()` pats.
2545        let tcx = self.tcx;
2546        self.register_bound(
2547            source_ty,
2548            tcx.require_lang_item(hir::LangItem::DerefPure, span),
2549            self.misc(span),
2550        );
2551        // The expected type for the deref pat's inner pattern is `<expected as Deref>::Target`.
2552        let target_ty = Ty::new_projection(
2553            tcx,
2554            tcx.require_lang_item(hir::LangItem::DerefTarget, span),
2555            [source_ty],
2556        );
2557        let target_ty = self.normalize(span, target_ty);
2558        self.try_structurally_resolve_type(span, target_ty)
2559    }
2560
2561    /// Check if the interior of a deref pattern (either explicit or implicit) has any `ref mut`
2562    /// bindings, which would require `DerefMut` to be emitted in MIR building instead of just
2563    /// `Deref`. We do this *after* checking the inner pattern, since we want to make sure to
2564    /// account for `ref mut` binding modes inherited from implicitly dereferencing `&mut` refs.
2565    fn register_deref_mut_bounds_if_needed(
2566        &self,
2567        span: Span,
2568        inner: &'tcx Pat<'tcx>,
2569        derefed_tys: impl IntoIterator<Item = Ty<'tcx>>,
2570    ) {
2571        if self.typeck_results.borrow().pat_has_ref_mut_binding(inner) {
2572            for mutably_derefed_ty in derefed_tys {
2573                self.register_bound(
2574                    mutably_derefed_ty,
2575                    self.tcx.require_lang_item(hir::LangItem::DerefMut, span),
2576                    self.misc(span),
2577                );
2578            }
2579        }
2580    }
2581
2582    // Precondition: Pat is Ref(inner)
2583    fn check_pat_ref(
2584        &self,
2585        pat: &'tcx Pat<'tcx>,
2586        inner: &'tcx Pat<'tcx>,
2587        pat_mutbl: Mutability,
2588        mut expected: Ty<'tcx>,
2589        mut pat_info: PatInfo<'tcx>,
2590    ) -> Ty<'tcx> {
2591        let tcx = self.tcx;
2592
2593        let pat_prefix_span =
2594            inner.span.find_ancestor_inside(pat.span).map(|end| pat.span.until(end));
2595
2596        let ref_pat_matches_mut_ref = self.ref_pat_matches_mut_ref();
2597        if ref_pat_matches_mut_ref && pat_mutbl == Mutability::Not {
2598            // If `&` patterns can match against mutable reference types (RFC 3627, Rule 5), we need
2599            // to prevent subpatterns from binding with `ref mut`. Subpatterns of a shared reference
2600            // pattern should have read-only access to the scrutinee, and the borrow checker won't
2601            // catch it in this case.
2602            pat_info.max_ref_mutbl = pat_info.max_ref_mutbl.cap_to_weakly_not(pat_prefix_span);
2603        }
2604
2605        expected = self.try_structurally_resolve_type(pat.span, expected);
2606        // Determine whether we're consuming an inherited reference and resetting the default
2607        // binding mode, based on edition and enabled experimental features.
2608        if let ByRef::Yes(inh_mut) = pat_info.binding_mode {
2609            match self.ref_pat_matches_inherited_ref(pat.span.edition()) {
2610                InheritedRefMatchRule::EatOuter => {
2611                    // ref pattern attempts to consume inherited reference
2612                    if pat_mutbl > inh_mut {
2613                        // Tried to match inherited `ref` with `&mut`
2614                        // NB: This assumes that `&` patterns can match against mutable references
2615                        // (RFC 3627, Rule 5). If we implement a pattern typing ruleset with Rule 4E
2616                        // but not Rule 5, we'll need to check that here.
2617                        debug_assert!(ref_pat_matches_mut_ref);
2618                        self.error_inherited_ref_mutability_mismatch(pat, pat_prefix_span);
2619                    }
2620
2621                    pat_info.binding_mode = ByRef::No;
2622                    self.typeck_results.borrow_mut().skipped_ref_pats_mut().insert(pat.hir_id);
2623                    self.check_pat(inner, expected, pat_info);
2624                    return expected;
2625                }
2626                InheritedRefMatchRule::EatInner => {
2627                    if let ty::Ref(_, _, r_mutbl) = *expected.kind()
2628                        && pat_mutbl <= r_mutbl
2629                    {
2630                        // Match against the reference type; don't consume the inherited ref.
2631                        // NB: The check for compatible pattern and ref type mutability assumes that
2632                        // `&` patterns can match against mutable references (RFC 3627, Rule 5). If
2633                        // we implement a pattern typing ruleset with Rule 4 (including the fallback
2634                        // to matching the inherited ref when the inner ref can't match) but not
2635                        // Rule 5, we'll need to check that here.
2636                        debug_assert!(ref_pat_matches_mut_ref);
2637                        // NB: For RFC 3627's Rule 3, we limit the default binding mode's ref
2638                        // mutability to `pat_info.max_ref_mutbl`. If we implement a pattern typing
2639                        // ruleset with Rule 4 but not Rule 3, we'll need to check that here.
2640                        debug_assert!(self.downgrade_mut_inside_shared());
2641                        let mutbl_cap = cmp::min(r_mutbl, pat_info.max_ref_mutbl.as_mutbl());
2642                        pat_info.binding_mode = pat_info.binding_mode.cap_ref_mutability(mutbl_cap);
2643                    } else {
2644                        // The reference pattern can't match against the expected type, so try
2645                        // matching against the inherited ref instead.
2646                        if pat_mutbl > inh_mut {
2647                            // We can't match an inherited shared reference with `&mut`.
2648                            // NB: This assumes that `&` patterns can match against mutable
2649                            // references (RFC 3627, Rule 5). If we implement a pattern typing
2650                            // ruleset with Rule 4 but not Rule 5, we'll need to check that here.
2651                            // FIXME(ref_pat_eat_one_layer_2024_structural): If we already tried
2652                            // matching the real reference, the error message should explain that
2653                            // falling back to the inherited reference didn't work. This should be
2654                            // the same error as the old-Edition version below.
2655                            debug_assert!(ref_pat_matches_mut_ref);
2656                            self.error_inherited_ref_mutability_mismatch(pat, pat_prefix_span);
2657                        }
2658
2659                        pat_info.binding_mode = ByRef::No;
2660                        self.typeck_results.borrow_mut().skipped_ref_pats_mut().insert(pat.hir_id);
2661                        self.check_pat(inner, expected, pat_info);
2662                        return expected;
2663                    }
2664                }
2665                InheritedRefMatchRule::EatBoth { consider_inherited_ref: true } => {
2666                    // Reset binding mode on old editions
2667                    pat_info.binding_mode = ByRef::No;
2668
2669                    if let ty::Ref(_, inner_ty, _) = *expected.kind() {
2670                        // Consume both the inherited and inner references.
2671                        if pat_mutbl.is_mut() && inh_mut.is_mut() {
2672                            // As a special case, a `&mut` reference pattern will be able to match
2673                            // against a reference type of any mutability if the inherited ref is
2674                            // mutable. Since this allows us to match against a shared reference
2675                            // type, we refer to this as "falling back" to matching the inherited
2676                            // reference, though we consume the real reference as well. We handle
2677                            // this here to avoid adding this case to the common logic below.
2678                            self.check_pat(inner, inner_ty, pat_info);
2679                            return expected;
2680                        } else {
2681                            // Otherwise, use the common logic below for matching the inner
2682                            // reference type.
2683                            // FIXME(ref_pat_eat_one_layer_2024_structural): If this results in a
2684                            // mutability mismatch, the error message should explain that falling
2685                            // back to the inherited reference didn't work. This should be the same
2686                            // error as the Edition 2024 version above.
2687                        }
2688                    } else {
2689                        // The expected type isn't a reference type, so only match against the
2690                        // inherited reference.
2691                        if pat_mutbl > inh_mut {
2692                            // We can't match a lone inherited shared reference with `&mut`.
2693                            self.error_inherited_ref_mutability_mismatch(pat, pat_prefix_span);
2694                        }
2695
2696                        self.typeck_results.borrow_mut().skipped_ref_pats_mut().insert(pat.hir_id);
2697                        self.check_pat(inner, expected, pat_info);
2698                        return expected;
2699                    }
2700                }
2701                InheritedRefMatchRule::EatBoth { consider_inherited_ref: false } => {
2702                    // Reset binding mode on stable Rust. This will be a type error below if
2703                    // `expected` is not a reference type.
2704                    pat_info.binding_mode = ByRef::No;
2705                    self.add_rust_2024_migration_desugared_pat(
2706                        pat_info.top_info.hir_id,
2707                        pat,
2708                        match pat_mutbl {
2709                            Mutability::Not => '&', // last char of `&`
2710                            Mutability::Mut => 't', // last char of `&mut`
2711                        },
2712                        inh_mut,
2713                    )
2714                }
2715            }
2716        }
2717
2718        let (ref_ty, inner_ty) = match self.check_dereferenceable(pat.span, expected, inner) {
2719            Ok(()) => {
2720                // `demand::subtype` would be good enough, but using `eqtype` turns
2721                // out to be equally general. See (note_1) for details.
2722
2723                // Take region, inner-type from expected type if we can,
2724                // to avoid creating needless variables. This also helps with
2725                // the bad interactions of the given hack detailed in (note_1).
2726                debug!("check_pat_ref: expected={:?}", expected);
2727                match *expected.kind() {
2728                    ty::Ref(_, r_ty, r_mutbl)
2729                        if (ref_pat_matches_mut_ref && r_mutbl >= pat_mutbl)
2730                            || r_mutbl == pat_mutbl =>
2731                    {
2732                        if r_mutbl == Mutability::Not {
2733                            pat_info.max_ref_mutbl = MutblCap::Not;
2734                        }
2735
2736                        (expected, r_ty)
2737                    }
2738
2739                    _ => {
2740                        let inner_ty = self.next_ty_var(inner.span);
2741                        let ref_ty = self.new_ref_ty(pat.span, pat_mutbl, inner_ty);
2742                        debug!("check_pat_ref: demanding {:?} = {:?}", expected, ref_ty);
2743                        let err = self.demand_eqtype_pat_diag(
2744                            pat.span,
2745                            expected,
2746                            ref_ty,
2747                            &pat_info.top_info,
2748                        );
2749
2750                        // Look for a case like `fn foo(&foo: u32)` and suggest
2751                        // `fn foo(foo: &u32)`
2752                        if let Err(mut err) = err {
2753                            self.borrow_pat_suggestion(&mut err, pat);
2754                            err.emit();
2755                        }
2756                        (ref_ty, inner_ty)
2757                    }
2758                }
2759            }
2760            Err(guar) => {
2761                let err = Ty::new_error(tcx, guar);
2762                (err, err)
2763            }
2764        };
2765
2766        self.check_pat(inner, inner_ty, pat_info);
2767        ref_ty
2768    }
2769
2770    /// Create a reference type with a fresh region variable.
2771    fn new_ref_ty(&self, span: Span, mutbl: Mutability, ty: Ty<'tcx>) -> Ty<'tcx> {
2772        let region = self.next_region_var(RegionVariableOrigin::PatternRegion(span));
2773        Ty::new_ref(self.tcx, region, ty, mutbl)
2774    }
2775
2776    fn error_inherited_ref_mutability_mismatch(
2777        &self,
2778        pat: &'tcx Pat<'tcx>,
2779        pat_prefix_span: Option<Span>,
2780    ) -> ErrorGuaranteed {
2781        let err_msg = "mismatched types";
2782        let err = if let Some(span) = pat_prefix_span {
2783            let mut err = self.dcx().struct_span_err(span, err_msg);
2784            err.code(E0308);
2785            err.note("cannot match inherited `&` with `&mut` pattern");
2786            err.span_suggestion_verbose(
2787                span,
2788                "replace this `&mut` pattern with `&`",
2789                "&",
2790                Applicability::MachineApplicable,
2791            );
2792            err
2793        } else {
2794            self.dcx().struct_span_err(pat.span, err_msg)
2795        };
2796        err.emit()
2797    }
2798
2799    fn try_resolve_slice_ty_to_array_ty(
2800        &self,
2801        before: &'tcx [Pat<'tcx>],
2802        slice: Option<&'tcx Pat<'tcx>>,
2803        span: Span,
2804    ) -> Option<Ty<'tcx>> {
2805        if slice.is_some() {
2806            return None;
2807        }
2808
2809        let tcx = self.tcx;
2810        let len = before.len();
2811        let inner_ty = self.next_ty_var(span);
2812
2813        Some(Ty::new_array(tcx, inner_ty, len.try_into().unwrap()))
2814    }
2815
2816    /// Used to determines whether we can infer the expected type in the slice pattern to be of type array.
2817    /// This is only possible if we're in an irrefutable pattern. If we were to allow this in refutable
2818    /// patterns we wouldn't e.g. report ambiguity in the following situation:
2819    ///
2820    /// ```ignore(rust)
2821    /// struct Zeroes;
2822    ///    const ARR: [usize; 2] = [0; 2];
2823    ///    const ARR2: [usize; 2] = [2; 2];
2824    ///
2825    ///    impl Into<&'static [usize; 2]> for Zeroes {
2826    ///        fn into(self) -> &'static [usize; 2] {
2827    ///            &ARR
2828    ///        }
2829    ///    }
2830    ///
2831    ///    impl Into<&'static [usize]> for Zeroes {
2832    ///        fn into(self) -> &'static [usize] {
2833    ///            &ARR2
2834    ///        }
2835    ///    }
2836    ///
2837    ///    fn main() {
2838    ///        let &[a, b]: &[usize] = Zeroes.into() else {
2839    ///           ..
2840    ///        };
2841    ///    }
2842    /// ```
2843    ///
2844    /// If we're in an irrefutable pattern we prefer the array impl candidate given that
2845    /// the slice impl candidate would be rejected anyway (if no ambiguity existed).
2846    fn pat_is_irrefutable(&self, decl_origin: Option<DeclOrigin<'_>>) -> bool {
2847        match decl_origin {
2848            Some(DeclOrigin::LocalDecl { els: None }) => true,
2849            Some(DeclOrigin::LocalDecl { els: Some(_) } | DeclOrigin::LetExpr) | None => false,
2850        }
2851    }
2852
2853    /// Type check a slice pattern.
2854    ///
2855    /// Syntactically, these look like `[pat_0, ..., pat_n]`.
2856    /// Semantically, we are type checking a pattern with structure:
2857    /// ```ignore (not-rust)
2858    /// [before_0, ..., before_n, (slice, after_0, ... after_n)?]
2859    /// ```
2860    /// The type of `slice`, if it is present, depends on the `expected` type.
2861    /// If `slice` is missing, then so is `after_i`.
2862    /// If `slice` is present, it can still represent 0 elements.
2863    fn check_pat_slice(
2864        &self,
2865        span: Span,
2866        before: &'tcx [Pat<'tcx>],
2867        slice: Option<&'tcx Pat<'tcx>>,
2868        after: &'tcx [Pat<'tcx>],
2869        expected: Ty<'tcx>,
2870        pat_info: PatInfo<'tcx>,
2871    ) -> Ty<'tcx> {
2872        let expected = self.try_structurally_resolve_type(span, expected);
2873
2874        // If the pattern is irrefutable and `expected` is an infer ty, we try to equate it
2875        // to an array if the given pattern allows it. See issue #76342
2876        if self.pat_is_irrefutable(pat_info.decl_origin) && expected.is_ty_var() {
2877            if let Some(resolved_arr_ty) =
2878                self.try_resolve_slice_ty_to_array_ty(before, slice, span)
2879            {
2880                debug!(?resolved_arr_ty);
2881                let _ = self.demand_eqtype(span, expected, resolved_arr_ty);
2882            }
2883        }
2884
2885        let expected = self.structurally_resolve_type(span, expected);
2886        debug!(?expected);
2887
2888        let (element_ty, opt_slice_ty, inferred) = match *expected.kind() {
2889            // An array, so we might have something like `let [a, b, c] = [0, 1, 2];`.
2890            ty::Array(element_ty, len) => {
2891                let min = before.len() as u64 + after.len() as u64;
2892                let (opt_slice_ty, expected) =
2893                    self.check_array_pat_len(span, element_ty, expected, slice, len, min);
2894                // `opt_slice_ty.is_none()` => `slice.is_none()`.
2895                // Note, though, that opt_slice_ty could be `Some(error_ty)`.
2896                assert!(opt_slice_ty.is_some() || slice.is_none());
2897                (element_ty, opt_slice_ty, expected)
2898            }
2899            ty::Slice(element_ty) => (element_ty, Some(expected), expected),
2900            // The expected type must be an array or slice, but was neither, so error.
2901            _ => {
2902                let guar = expected.error_reported().err().unwrap_or_else(|| {
2903                    self.error_expected_array_or_slice(span, expected, pat_info)
2904                });
2905                let err = Ty::new_error(self.tcx, guar);
2906                (err, Some(err), err)
2907            }
2908        };
2909
2910        // Type check all the patterns before `slice`.
2911        for elt in before {
2912            self.check_pat(elt, element_ty, pat_info);
2913        }
2914        // Type check the `slice`, if present, against its expected type.
2915        if let Some(slice) = slice {
2916            self.check_pat(slice, opt_slice_ty.unwrap(), pat_info);
2917        }
2918        // Type check the elements after `slice`, if present.
2919        for elt in after {
2920            self.check_pat(elt, element_ty, pat_info);
2921        }
2922        inferred
2923    }
2924
2925    /// Type check the length of an array pattern.
2926    ///
2927    /// Returns both the type of the variable length pattern (or `None`), and the potentially
2928    /// inferred array type. We only return `None` for the slice type if `slice.is_none()`.
2929    fn check_array_pat_len(
2930        &self,
2931        span: Span,
2932        element_ty: Ty<'tcx>,
2933        arr_ty: Ty<'tcx>,
2934        slice: Option<&'tcx Pat<'tcx>>,
2935        len: ty::Const<'tcx>,
2936        min_len: u64,
2937    ) -> (Option<Ty<'tcx>>, Ty<'tcx>) {
2938        let len = self.try_structurally_resolve_const(span, len).try_to_target_usize(self.tcx);
2939
2940        let guar = if let Some(len) = len {
2941            // Now we know the length...
2942            if slice.is_none() {
2943                // ...and since there is no variable-length pattern,
2944                // we require an exact match between the number of elements
2945                // in the array pattern and as provided by the matched type.
2946                if min_len == len {
2947                    return (None, arr_ty);
2948                }
2949
2950                self.error_scrutinee_inconsistent_length(span, min_len, len)
2951            } else if let Some(pat_len) = len.checked_sub(min_len) {
2952                // The variable-length pattern was there,
2953                // so it has an array type with the remaining elements left as its size...
2954                return (Some(Ty::new_array(self.tcx, element_ty, pat_len)), arr_ty);
2955            } else {
2956                // ...however, in this case, there were no remaining elements.
2957                // That is, the slice pattern requires more than the array type offers.
2958                self.error_scrutinee_with_rest_inconsistent_length(span, min_len, len)
2959            }
2960        } else if slice.is_none() {
2961            // We have a pattern with a fixed length,
2962            // which we can use to infer the length of the array.
2963            let updated_arr_ty = Ty::new_array(self.tcx, element_ty, min_len);
2964            self.demand_eqtype(span, updated_arr_ty, arr_ty);
2965            return (None, updated_arr_ty);
2966        } else {
2967            // We have a variable-length pattern and don't know the array length.
2968            // This happens if we have e.g.,
2969            // `let [a, b, ..] = arr` where `arr: [T; N]` where `const N: usize`.
2970            self.error_scrutinee_unfixed_length(span)
2971        };
2972
2973        // If we get here, we must have emitted an error.
2974        (Some(Ty::new_error(self.tcx, guar)), arr_ty)
2975    }
2976
2977    fn error_scrutinee_inconsistent_length(
2978        &self,
2979        span: Span,
2980        min_len: u64,
2981        size: u64,
2982    ) -> ErrorGuaranteed {
2983        struct_span_code_err!(
2984            self.dcx(),
2985            span,
2986            E0527,
2987            "pattern requires {} element{} but array has {}",
2988            min_len,
2989            pluralize!(min_len),
2990            size,
2991        )
2992        .with_span_label(span, format!("expected {} element{}", size, pluralize!(size)))
2993        .emit()
2994    }
2995
2996    fn error_scrutinee_with_rest_inconsistent_length(
2997        &self,
2998        span: Span,
2999        min_len: u64,
3000        size: u64,
3001    ) -> ErrorGuaranteed {
3002        struct_span_code_err!(
3003            self.dcx(),
3004            span,
3005            E0528,
3006            "pattern requires at least {} element{} but array has {}",
3007            min_len,
3008            pluralize!(min_len),
3009            size,
3010        )
3011        .with_span_label(
3012            span,
3013            format!("pattern cannot match array of {} element{}", size, pluralize!(size),),
3014        )
3015        .emit()
3016    }
3017
3018    fn error_scrutinee_unfixed_length(&self, span: Span) -> ErrorGuaranteed {
3019        struct_span_code_err!(
3020            self.dcx(),
3021            span,
3022            E0730,
3023            "cannot pattern-match on an array without a fixed length",
3024        )
3025        .emit()
3026    }
3027
3028    fn error_expected_array_or_slice(
3029        &self,
3030        span: Span,
3031        expected_ty: Ty<'tcx>,
3032        pat_info: PatInfo<'tcx>,
3033    ) -> ErrorGuaranteed {
3034        let PatInfo { top_info: ti, current_depth, .. } = pat_info;
3035
3036        let mut slice_pat_semantics = false;
3037        let mut as_deref = None;
3038        let mut slicing = None;
3039        if let ty::Ref(_, ty, _) = expected_ty.kind()
3040            && let ty::Array(..) | ty::Slice(..) = ty.kind()
3041        {
3042            slice_pat_semantics = true;
3043        } else if self
3044            .autoderef(span, expected_ty)
3045            .silence_errors()
3046            .any(|(ty, _)| matches!(ty.kind(), ty::Slice(..) | ty::Array(..)))
3047            && let Some(span) = ti.span
3048            && let Some(_) = ti.origin_expr
3049        {
3050            let resolved_ty = self.resolve_vars_if_possible(ti.expected);
3051            let (is_slice_or_array_or_vector, resolved_ty) =
3052                self.is_slice_or_array_or_vector(resolved_ty);
3053            match resolved_ty.kind() {
3054                ty::Adt(adt_def, _)
3055                    if self.tcx.is_diagnostic_item(sym::Option, adt_def.did())
3056                        || self.tcx.is_diagnostic_item(sym::Result, adt_def.did()) =>
3057                {
3058                    // Slicing won't work here, but `.as_deref()` might (issue #91328).
3059                    as_deref = Some(errors::AsDerefSuggestion { span: span.shrink_to_hi() });
3060                }
3061                _ => (),
3062            }
3063
3064            let is_top_level = current_depth <= 1;
3065            if is_slice_or_array_or_vector && is_top_level {
3066                slicing = Some(errors::SlicingSuggestion { span: span.shrink_to_hi() });
3067            }
3068        }
3069        self.dcx().emit_err(errors::ExpectedArrayOrSlice {
3070            span,
3071            ty: expected_ty,
3072            slice_pat_semantics,
3073            as_deref,
3074            slicing,
3075        })
3076    }
3077
3078    fn is_slice_or_array_or_vector(&self, ty: Ty<'tcx>) -> (bool, Ty<'tcx>) {
3079        match ty.kind() {
3080            ty::Adt(adt_def, _) if self.tcx.is_diagnostic_item(sym::Vec, adt_def.did()) => {
3081                (true, ty)
3082            }
3083            ty::Ref(_, ty, _) => self.is_slice_or_array_or_vector(*ty),
3084            ty::Slice(..) | ty::Array(..) => (true, ty),
3085            _ => (false, ty),
3086        }
3087    }
3088
3089    /// Record a pattern that's invalid under Rust 2024 match ergonomics, along with a problematic
3090    /// span, so that the pattern migration lint can desugar it during THIR construction.
3091    fn add_rust_2024_migration_desugared_pat(
3092        &self,
3093        pat_id: HirId,
3094        subpat: &'tcx Pat<'tcx>,
3095        final_char: char,
3096        def_br_mutbl: Mutability,
3097    ) {
3098        // Try to trim the span we're labeling to just the `&` or binding mode that's an issue.
3099        let from_expansion = subpat.span.from_expansion();
3100        let trimmed_span = if from_expansion {
3101            // If the subpattern is from an expansion, highlight the whole macro call instead.
3102            subpat.span
3103        } else {
3104            let trimmed = self.tcx.sess.source_map().span_through_char(subpat.span, final_char);
3105            // The edition of the trimmed span should be the same as `subpat.span`; this will be a
3106            // a hard error if the subpattern is of edition >= 2024. We set it manually to be sure:
3107            trimmed.with_ctxt(subpat.span.ctxt())
3108        };
3109
3110        let mut typeck_results = self.typeck_results.borrow_mut();
3111        let mut table = typeck_results.rust_2024_migration_desugared_pats_mut();
3112        // FIXME(ref_pat_eat_one_layer_2024): The migration diagnostic doesn't know how to track the
3113        // default binding mode in the presence of Rule 3 or Rule 5. As a consequence, the labels it
3114        // gives for default binding modes are wrong, as well as suggestions based on the default
3115        // binding mode. This keeps it from making those suggestions, as doing so could panic.
3116        let info = table.entry(pat_id).or_insert_with(|| ty::Rust2024IncompatiblePatInfo {
3117            primary_labels: Vec::new(),
3118            bad_modifiers: false,
3119            bad_ref_pats: false,
3120            suggest_eliding_modes: !self.tcx.features().ref_pat_eat_one_layer_2024()
3121                && !self.tcx.features().ref_pat_eat_one_layer_2024_structural(),
3122        });
3123
3124        let pat_kind = if let PatKind::Binding(user_bind_annot, _, _, _) = subpat.kind {
3125            info.bad_modifiers = true;
3126            // If the user-provided binding modifier doesn't match the default binding mode, we'll
3127            // need to suggest reference patterns, which can affect other bindings.
3128            // For simplicity, we opt to suggest making the pattern fully explicit.
3129            info.suggest_eliding_modes &=
3130                user_bind_annot == BindingMode(ByRef::Yes(def_br_mutbl), Mutability::Not);
3131            "binding modifier"
3132        } else {
3133            info.bad_ref_pats = true;
3134            // For simplicity, we don't try to suggest eliding reference patterns. Thus, we'll
3135            // suggest adding them instead, which can affect the types assigned to bindings.
3136            // As such, we opt to suggest making the pattern fully explicit.
3137            info.suggest_eliding_modes = false;
3138            "reference pattern"
3139        };
3140        // Only provide a detailed label if the problematic subpattern isn't from an expansion.
3141        // In the case that it's from a macro, we'll add a more detailed note in the emitter.
3142        let primary_label = if from_expansion {
3143            // We can't suggest eliding modifiers within expansions.
3144            info.suggest_eliding_modes = false;
3145            // NB: This wording assumes the only expansions that can produce problematic reference
3146            // patterns and bindings are macros. If a desugaring or AST pass is added that can do
3147            // so, we may want to inspect the span's source callee or macro backtrace.
3148            "occurs within macro expansion".to_owned()
3149        } else {
3150            let dbm_str = match def_br_mutbl {
3151                Mutability::Not => "ref",
3152                Mutability::Mut => "ref mut",
3153            };
3154            format!("{pat_kind} not allowed under `{dbm_str}` default binding mode")
3155        };
3156        info.primary_labels.push((trimmed_span, primary_label));
3157    }
3158}