Skip to main content

hir_ty/infer/
pat.rs

1//! Type inference for patterns.
2
3use std::{
4    cmp,
5    collections::hash_map::Entry::{Occupied, Vacant},
6    iter,
7};
8
9use hir_def::{
10    AdtId, LocalFieldId, VariantId,
11    expr_store::path::Path,
12    hir::{
13        BindingAnnotation, BindingId, Expr, ExprId, ExprOrPatId, ExprOrPatIdPacked, Literal, Pat,
14        PatId, RecordFieldPat,
15    },
16    resolver::ValueNs,
17    signatures::VariantFields,
18};
19use rustc_ast_ir::Mutability;
20use rustc_hash::FxHashMap;
21use rustc_type_ir::{
22    TypeVisitableExt as _,
23    inherent::{IntoKind as _, Ty as _},
24};
25use span::Edition;
26use tracing::{debug, instrument, trace};
27
28use crate::{
29    BindingMode, InferenceDiagnostic, Span,
30    infer::{
31        AllowTwoPhase, ByRef, Expectation, InferenceContext, PatAdjust, PatAdjustment,
32        expr::ExprIsRead,
33    },
34    next_solver::{
35        Const, TraitRef, Ty, TyKind, Tys,
36        infer::{
37            InferOk,
38            traits::{Obligation, ObligationCause},
39        },
40    },
41    utils::EnumerateAndAdjustIterator,
42};
43
44impl ByRef {
45    #[must_use]
46    fn cap_ref_mutability(mut self, mutbl: Mutability) -> Self {
47        if let ByRef::Yes(old_mutbl) = &mut self {
48            *old_mutbl = cmp::min(*old_mutbl, mutbl);
49        }
50        self
51    }
52}
53
54impl BindingMode {
55    fn from_annotation(annotation: BindingAnnotation) -> BindingMode {
56        match annotation {
57            BindingAnnotation::Unannotated => BindingMode(ByRef::No, Mutability::Not),
58            BindingAnnotation::Mutable => BindingMode(ByRef::No, Mutability::Mut),
59            BindingAnnotation::Ref => BindingMode(ByRef::Yes(Mutability::Not), Mutability::Not),
60            BindingAnnotation::RefMut => BindingMode(ByRef::Yes(Mutability::Mut), Mutability::Not),
61        }
62    }
63}
64
65#[derive(Clone, Copy, PartialEq, Eq)]
66pub(super) enum PatOrigin {
67    LetExpr,
68    LetStmt { has_else: bool },
69    Param,
70    MatchArm,
71    DestructuringAssignment,
72}
73
74impl PatOrigin {
75    fn default_binding_modes(self) -> bool {
76        self != PatOrigin::DestructuringAssignment
77    }
78}
79
80#[derive(Copy, Clone)]
81struct PatInfo {
82    binding_mode: ByRef,
83    max_ref_mutbl: MutblCap,
84    pat_origin: PatOrigin,
85}
86
87/// Mode for adjusting the expected type and binding mode.
88#[derive(Clone, Copy, Debug, PartialEq, Eq)]
89enum AdjustMode {
90    /// Peel off all immediate reference types. If the `deref_patterns` feature is enabled, this
91    /// also peels smart pointer ADTs.
92    Peel { kind: PeelKind },
93    /// Pass on the input binding mode and expected type.
94    Pass,
95}
96
97/// Restrictions on what types to peel when adjusting the expected type and binding mode.
98#[derive(Clone, Copy, Debug, PartialEq, Eq)]
99enum PeelKind {
100    /// Only peel reference types. This is used for explicit `deref!(_)` patterns, which dereference
101    /// any number of `&`/`&mut` references, plus a single smart pointer.
102    ExplicitDerefPat,
103    /// Implicitly peel references, and if `deref_patterns` is enabled, smart pointer ADTs.
104    Implicit {
105        /// The ADT the pattern is a constructor for, if applicable, so that we don't peel it. See
106        /// [`ResolvedPat`] for more information.
107        until_adt: Option<AdtId>,
108        /// The number of references at the head of the pattern's type, so we can leave that many
109        /// untouched. This is `1` for string literals, and `0` for most patterns.
110        pat_ref_layers: usize,
111    },
112}
113
114impl AdjustMode {
115    const fn peel_until_adt(opt_adt_def: Option<AdtId>) -> AdjustMode {
116        AdjustMode::Peel { kind: PeelKind::Implicit { until_adt: opt_adt_def, pat_ref_layers: 0 } }
117    }
118    const fn peel_all() -> AdjustMode {
119        AdjustMode::peel_until_adt(None)
120    }
121}
122
123/// `ref mut` bindings (explicit or match-ergonomics) are not allowed behind an `&` reference.
124/// Normally, the borrow checker enforces this, but for (currently experimental) match ergonomics,
125/// we track this when typing patterns for two purposes:
126///
127/// - For RFC 3627's Rule 3, when this would prevent us from binding with `ref mut`, we limit the
128///   default binding mode to be by shared `ref` when it would otherwise be `ref mut`.
129///
130/// - For RFC 3627's Rule 5, we allow `&` patterns to match against `&mut` references, treating them
131///   as if they were shared references. Since the scrutinee is mutable in this case, the borrow
132///   checker won't catch if we bind with `ref mut`, so we need to throw an error ourselves.
133#[derive(Clone, Copy, Debug, PartialEq, Eq)]
134enum MutblCap {
135    /// Mutability restricted to immutable.
136    Not,
137
138    /// Mutability restricted to immutable, but only because of the pattern
139    /// (not the scrutinee type).
140    ///
141    /// The contained span, if present, points to an `&` pattern
142    /// that is the reason for the restriction,
143    /// and which will be reported in a diagnostic.
144    WeaklyNot,
145
146    /// No restriction on mutability
147    Mut,
148}
149
150impl MutblCap {
151    #[must_use]
152    fn cap_to_weakly_not(self) -> Self {
153        match self {
154            MutblCap::Not => MutblCap::Not,
155            _ => MutblCap::WeaklyNot,
156        }
157    }
158
159    #[must_use]
160    fn as_mutbl(self) -> Mutability {
161        match self {
162            MutblCap::Not | MutblCap::WeaklyNot => Mutability::Not,
163            MutblCap::Mut => Mutability::Mut,
164        }
165    }
166}
167
168/// Variations on RFC 3627's Rule 4: when do reference patterns match against inherited references?
169///
170/// "Inherited reference" designates the `&`/`&mut` types that arise from using match ergonomics, i.e.
171/// from matching a reference type with a non-reference pattern. E.g. when `Some(x)` matches on
172/// `&mut Option<&T>`, `x` gets type `&mut &T` and the outer `&mut` is considered "inherited".
173#[derive(Clone, Copy, Debug, PartialEq, Eq)]
174enum InheritedRefMatchRule {
175    /// Reference patterns consume only the inherited reference if possible, regardless of whether
176    /// the underlying type being matched against is a reference type. If there is no inherited
177    /// reference, a reference will be consumed from the underlying type.
178    EatOuter,
179    /// Reference patterns consume only a reference from the underlying type if possible. If the
180    /// underlying type is not a reference type, the inherited reference will be consumed.
181    EatInner,
182    /// When the underlying type is a reference type, reference patterns consume both layers of
183    /// reference, i.e. they both reset the binding mode and consume the reference type.
184    EatBoth {
185        /// If `true`, an inherited reference will be considered when determining whether a reference
186        /// pattern matches a given type:
187        /// - If the underlying type is not a reference, a reference pattern may eat the inherited reference;
188        /// - If the underlying type is a reference, a reference pattern matches if it can eat either one
189        ///   of the underlying and inherited references. E.g. a `&mut` pattern is allowed if either the
190        ///   underlying type is `&mut` or the inherited reference is `&mut`.
191        ///
192        /// If `false`, a reference pattern is only matched against the underlying type.
193        /// This is `false` for stable Rust and `true` for both the `ref_pat_eat_one_layer_2024` and
194        /// `ref_pat_eat_one_layer_2024_structural` feature gates.
195        consider_inherited_ref: bool,
196    },
197}
198
199/// When checking patterns containing paths, we need to know the path's resolution to determine
200/// whether to apply match ergonomics and implicitly dereference the scrutinee. For instance, when
201/// the `deref_patterns` feature is enabled and we're matching against a scrutinee of type
202/// `Cow<'a, Option<u8>>`, we insert an implicit dereference to allow the pattern `Some(_)` to type,
203/// but we must not dereference it when checking the pattern `Cow::Borrowed(_)`.
204///
205/// `ResolvedPat` contains the information from resolution needed to determine match ergonomics
206/// adjustments, and to finish checking the pattern once we know its adjusted type.
207#[derive(Clone, Copy, Debug)]
208struct ResolvedPat<'db> {
209    /// The type of the pattern, to be checked against the type of the scrutinee after peeling. This
210    /// is also used to avoid peeling the scrutinee's constructors (see the `Cow` example above).
211    ty: Ty<'db>,
212    kind: ResolvedPatKind,
213}
214
215#[derive(Clone, Copy, Debug)]
216enum ResolvedPatKind {
217    Path { res: ValueNs },
218    Struct { variant: VariantId },
219    TupleStruct { variant: VariantId },
220}
221
222impl<'db> ResolvedPat<'db> {
223    fn adjust_mode(&self) -> AdjustMode {
224        if let ResolvedPatKind::Path { res, .. } = self.kind
225            && matches!(res, ValueNs::ConstId(_))
226        {
227            // These constants can be of a reference type, e.g. `const X: &u8 = &0;`.
228            // Peeling the reference types too early will cause type checking failures.
229            // Although it would be possible to *also* peel the types of the constants too.
230            AdjustMode::Pass
231        } else {
232            // The remaining possible resolutions for path, struct, and tuple struct patterns are
233            // ADT constructors. As such, we may peel references freely, but we must not peel the
234            // ADT itself from the scrutinee if it's a smart pointer.
235            AdjustMode::peel_until_adt(self.ty.as_adt().map(|(adt, _)| adt))
236        }
237    }
238}
239
240impl<'db> InferenceContext<'db> {
241    /// Experimental pattern feature: after matching against a shared reference, do we limit the
242    /// default binding mode in subpatterns to be `ref` when it would otherwise be `ref mut`?
243    /// This corresponds to Rule 3 of RFC 3627.
244    fn downgrade_mut_inside_shared(&self) -> bool {
245        // NB: RFC 3627 proposes stabilizing Rule 3 in all editions. If we adopt the same behavior
246        // across all editions, this may be removed.
247        self.features.ref_pat_eat_one_layer_2024_structural
248    }
249
250    /// Experimental pattern feature: when do reference patterns match against inherited references?
251    /// This corresponds to variations on Rule 4 of RFC 3627.
252    fn ref_pat_matches_inherited_ref(&self, edition: Edition) -> InheritedRefMatchRule {
253        // NB: The particular rule used here is likely to differ across editions, so calls to this
254        // may need to become edition checks after match ergonomics stabilize.
255        if edition.at_least_2024() {
256            if self.features.ref_pat_eat_one_layer_2024 {
257                InheritedRefMatchRule::EatOuter
258            } else if self.features.ref_pat_eat_one_layer_2024_structural {
259                InheritedRefMatchRule::EatInner
260            } else {
261                // Currently, matching against an inherited ref on edition 2024 is an error.
262                // Use `EatBoth` as a fallback to be similar to stable Rust.
263                InheritedRefMatchRule::EatBoth { consider_inherited_ref: false }
264            }
265        } else {
266            InheritedRefMatchRule::EatBoth {
267                consider_inherited_ref: self.features.ref_pat_eat_one_layer_2024
268                    || self.features.ref_pat_eat_one_layer_2024_structural,
269            }
270        }
271    }
272
273    /// Experimental pattern feature: do `&` patterns match against `&mut` references, treating them
274    /// as if they were shared references? This corresponds to Rule 5 of RFC 3627.
275    fn ref_pat_matches_mut_ref(&self) -> bool {
276        // NB: RFC 3627 proposes stabilizing Rule 5 in all editions. If we adopt the same behavior
277        // across all editions, this may be removed.
278        self.features.ref_pat_eat_one_layer_2024
279            || self.features.ref_pat_eat_one_layer_2024_structural
280    }
281
282    /// Type check the given top level pattern against the `expected` type.
283    ///
284    /// If a `Some(span)` is provided and `origin_expr` holds,
285    /// then the `span` represents the scrutinee's span.
286    /// The scrutinee is found in e.g. `match scrutinee { ... }` and `let pat = scrutinee;`.
287    ///
288    /// Otherwise, `Some(span)` represents the span of a type expression
289    /// which originated the `expected` type.
290    pub(super) fn infer_top_pat(&mut self, pat: PatId, expected: Ty<'db>, pat_origin: PatOrigin) {
291        let pat_info =
292            PatInfo { binding_mode: ByRef::No, max_ref_mutbl: MutblCap::Mut, pat_origin };
293        self.infer_pat(pat, expected, pat_info);
294    }
295
296    /// Type check the given `pat` against the `expected` type
297    /// with the provided `binding_mode` (default binding mode).
298    ///
299    /// Outside of this module, `check_pat_top` should always be used.
300    /// Conversely, inside this module, `check_pat_top` should never be used.
301    #[instrument(level = "debug", skip(self, pat_info))]
302    fn infer_pat(&mut self, pat_id: PatId, expected: Ty<'db>, pat_info: PatInfo) {
303        // For patterns containing paths, we need the path's resolution to determine whether to
304        // implicitly dereference the scrutinee before matching.
305        let pat = &self.store[pat_id];
306        let opt_path_res = match pat {
307            Pat::Path(path) => Some(self.resolve_pat_path(pat_id, path)),
308            Pat::Record { path, .. } => Some(self.resolve_record_pat(pat_id, path)),
309            Pat::TupleStruct { path, .. } => Some(self.resolve_tuple_struct_pat(pat_id, path)),
310            _ => None,
311        };
312        let adjust_mode = self.calc_adjust_mode(pat_id, pat, opt_path_res);
313        let ty = self.infer_pat_inner(pat_id, opt_path_res, adjust_mode, expected, pat_info);
314        let ty = self.insert_type_vars_shallow(ty);
315        self.write_pat_ty(pat_id, ty);
316
317        // If we implicitly inserted overloaded dereferences before matching check the pattern to
318        // see if the dereferenced types need `DerefMut` bounds.
319        if let Some(derefed_tys) = self.result.pat_adjustment(pat_id)
320            && derefed_tys.iter().any(|adjust| adjust.kind == PatAdjust::OverloadedDeref)
321        {
322            let infer_ok = self.register_deref_mut_bounds_if_needed(
323                pat_id,
324                pat_id,
325                derefed_tys.iter().filter_map(|adjust| match adjust.kind {
326                    PatAdjust::OverloadedDeref => Some(adjust.source.as_ref()),
327                    PatAdjust::BuiltinDeref => None,
328                }),
329            );
330            self.table.register_infer_ok(infer_ok);
331        }
332
333        // (note_1): In most of the cases where (note_1) is referenced
334        // (literals and constants being the exception), we relate types
335        // using strict equality, even though subtyping would be sufficient.
336        // There are a few reasons for this, some of which are fairly subtle
337        // and which cost me (nmatsakis) an hour or two debugging to remember,
338        // so I thought I'd write them down this time.
339        //
340        // 1. There is no loss of expressiveness here, though it does
341        // cause some inconvenience. What we are saying is that the type
342        // of `x` becomes *exactly* what is expected. This can cause unnecessary
343        // errors in some cases, such as this one:
344        //
345        // ```
346        // fn foo<'x>(x: &'x i32) {
347        //    let a = 1;
348        //    let mut z = x;
349        //    z = &a;
350        // }
351        // ```
352        //
353        // The reason we might get an error is that `z` might be
354        // assigned a type like `&'x i32`, and then we would have
355        // a problem when we try to assign `&a` to `z`, because
356        // the lifetime of `&a` (i.e., the enclosing block) is
357        // shorter than `'x`.
358        //
359        // HOWEVER, this code works fine. The reason is that the
360        // expected type here is whatever type the user wrote, not
361        // the initializer's type. In this case the user wrote
362        // nothing, so we are going to create a type variable `Z`.
363        // Then we will assign the type of the initializer (`&'x i32`)
364        // as a subtype of `Z`: `&'x i32 <: Z`. And hence we
365        // will instantiate `Z` as a type `&'0 i32` where `'0` is
366        // a fresh region variable, with the constraint that `'x : '0`.
367        // So basically we're all set.
368        //
369        // Note that there are two tests to check that this remains true
370        // (`regions-reassign-{match,let}-bound-pointer.rs`).
371        //
372        // 2. An outdated issue related to the old HIR borrowck. See the test
373        // `regions-relate-bound-regions-on-closures-to-inference-variables.rs`,
374    }
375
376    // Helper to avoid resolving the same path pattern several times.
377    fn infer_pat_inner(
378        &mut self,
379        pat: PatId,
380        opt_path_res: Option<Result<ResolvedPat<'db>, ()>>,
381        adjust_mode: AdjustMode,
382        expected: Ty<'db>,
383        pat_info: PatInfo,
384    ) -> Ty<'db> {
385        #[cfg(debug_assertions)]
386        if matches!(pat_info.binding_mode, ByRef::Yes(Mutability::Mut))
387            && pat_info.max_ref_mutbl != MutblCap::Mut
388            && self.downgrade_mut_inside_shared()
389        {
390            panic!("Pattern mutability cap violated!");
391        }
392
393        // Resolve type if needed.
394        let expected = if let AdjustMode::Peel { .. } = adjust_mode
395            && pat_info.pat_origin.default_binding_modes()
396        {
397            self.table.try_structurally_resolve_type(pat.into(), expected)
398        } else {
399            expected
400        };
401
402        match self.store[pat] {
403            // Peel off a `&` or `&mut`from the scrutinee type. See the examples in
404            // `tests/ui/rfcs/rfc-2005-default-binding-mode`.
405            _ if let AdjustMode::Peel { kind: peel_kind } = adjust_mode
406                && pat_info.pat_origin.default_binding_modes()
407                && let TyKind::Ref(_, inner_ty, inner_mutability) = expected.kind()
408                && self.should_peel_ref(peel_kind, expected) =>
409            {
410                debug!("inspecting {:?}", expected);
411
412                debug!("current discriminant is Ref, inserting implicit deref");
413                // Preserve the reference type. We'll need it later during THIR lowering.
414                self.result.pat_adjustments.entry(pat).or_default().push(PatAdjustment {
415                    kind: PatAdjust::BuiltinDeref,
416                    source: expected.store(),
417                });
418
419                // Use the old pat info to keep `current_depth` to its old value.
420                let new_pat_info = self.adjust_pat_info(inner_mutability, pat_info);
421
422                // Recurse with the new expected type.
423                self.infer_pat_inner(pat, opt_path_res, adjust_mode, inner_ty, new_pat_info)
424            }
425            // If `deref_patterns` is enabled, peel a smart pointer from the scrutinee type. See the
426            // examples in `tests/ui/pattern/deref_patterns/`.
427            _ if self.features.deref_patterns
428                && let AdjustMode::Peel { kind: peel_kind } = adjust_mode
429                && pat_info.pat_origin.default_binding_modes()
430                && self.should_peel_smart_pointer(peel_kind, expected) =>
431            {
432                debug!("scrutinee ty {expected:?} is a smart pointer, inserting pin deref");
433
434                // The scrutinee is a smart pointer; implicitly dereference it. This adds a
435                // requirement that `expected: DerefPure`.
436                let inner_ty = self.deref_pat_target(pat, expected);
437                // Once we've checked `pat`, we'll add a `DerefMut` bound if it contains any
438                // `ref mut` bindings. See `Self::register_deref_mut_bounds_if_needed`.
439
440                self.check_deref_pattern(
441                    pat,
442                    opt_path_res,
443                    adjust_mode,
444                    expected,
445                    inner_ty,
446                    PatAdjust::OverloadedDeref,
447                    pat_info,
448                )
449            }
450            Pat::Missing => self.types.types.error,
451            Pat::Wild | Pat::Rest | Pat::NotNull => expected,
452            // We allow any type here; we ensure that the type is uninhabited during match checking.
453            // Pat::Never => expected,
454            Pat::Path(_) => {
455                let ty = match opt_path_res.unwrap() {
456                    Ok(ref pr) => self.infer_pat_path(pat, pr, expected),
457                    Err(()) => self.types.types.error,
458                };
459                self.write_pat_ty(pat, ty);
460                ty
461            }
462            Pat::Lit(expr) => self.infer_lit_pat(expr, expected),
463            Pat::Range { start: lhs, end: rhs, .. } => {
464                self.infer_range_pat(pat, lhs, rhs, expected)
465            }
466            Pat::Bind { id: var_id, subpat } => {
467                self.infer_bind_pat(pat, var_id, subpat, expected, pat_info)
468            }
469            Pat::TupleStruct { args: ref subpats, ellipsis: ddpos, .. } => match opt_path_res
470                .unwrap()
471            {
472                Ok(ResolvedPat { ty, kind: ResolvedPatKind::TupleStruct { variant } }) => self
473                    .infer_tuple_struct_pat(pat, subpats, ddpos, ty, variant, expected, pat_info),
474                Err(()) => {
475                    let ty_err = self.types.types.error;
476                    for &subpat in subpats {
477                        self.infer_pat(subpat, ty_err, pat_info);
478                    }
479                    ty_err
480                }
481                Ok(pr) => panic!("tuple struct pattern resolved to {pr:?}"),
482            },
483            Pat::Record { args: ref fields, ellipsis: has_rest_pat, .. } => {
484                match opt_path_res.unwrap() {
485                    Ok(ResolvedPat { ty, kind: ResolvedPatKind::Struct { variant } }) => self
486                        .infer_record_pat(
487                            pat,
488                            fields,
489                            has_rest_pat,
490                            ty,
491                            variant,
492                            expected,
493                            pat_info,
494                        ),
495                    Err(()) => {
496                        let ty_err = self.types.types.error;
497                        for field in fields {
498                            self.infer_pat(field.pat, ty_err, pat_info);
499                        }
500                        ty_err
501                    }
502                    Ok(pr) => panic!("struct pattern resolved to {pr:?}"),
503                }
504            }
505            // Pat::Guard(pat, cond) => {
506            //     self.infer_pat(pat, expected, pat_info);
507            //     self.check_expr_has_type_or_error(cond, self.tcx.types.bool, |_| {});
508            //     expected
509            // }
510            Pat::Or(ref pats) => {
511                for &pat in pats {
512                    self.infer_pat(pat, expected, pat_info);
513                }
514                expected
515            }
516            Pat::Tuple { args: ref elements, ellipsis: ddpos } => {
517                self.infer_tuple_pat(pat, elements, ddpos, expected, pat_info)
518            }
519            Pat::Box { inner } => self.infer_box_pat(pat, inner, expected, pat_info),
520            Pat::Deref { inner } => self.infer_deref_pat(pat, inner, expected, pat_info),
521            // Pat::Deref(inner) => self.infer_deref_pat(pat.span, inner, expected, pat_info),
522            Pat::Ref { pat: inner, mutability: mutbl } => self.infer_ref_pat(
523                pat,
524                inner,
525                if mutbl.is_mut() { Mutability::Mut } else { Mutability::Not },
526                expected,
527                pat_info,
528            ),
529            Pat::Slice { prefix: ref before, slice, suffix: ref after } => {
530                self.infer_slice_pat(pat, before, slice, after, expected, pat_info)
531            }
532            Pat::Expr(expr) => self.infer_destructuring_assignment_expr(expr, expected),
533        }
534    }
535
536    fn adjust_pat_info(&self, inner_mutability: Mutability, pat_info: PatInfo) -> PatInfo {
537        let mut binding_mode = match pat_info.binding_mode {
538            // If default binding mode is by value, make it `ref`, `ref mut`, `ref pin const`
539            // or `ref pin mut` (depending on whether we observe `&`, `&mut`, `&pin const` or
540            // `&pin mut`).
541            ByRef::No => ByRef::Yes(inner_mutability),
542            ByRef::Yes(mutability) => {
543                let mutability = match mutability {
544                    // When `ref mut`, stay a `ref mut` (on `&mut`) or downgrade to `ref` (on `&`).
545                    Mutability::Mut => inner_mutability,
546                    // Once a `ref`, always a `ref`.
547                    // This is because a `& &mut` cannot mutate the underlying value.
548                    Mutability::Not => Mutability::Not,
549                };
550                ByRef::Yes(mutability)
551            }
552        };
553
554        let PatInfo { mut max_ref_mutbl, .. } = pat_info;
555        if self.downgrade_mut_inside_shared() {
556            binding_mode = binding_mode.cap_ref_mutability(max_ref_mutbl.as_mutbl());
557        }
558        match binding_mode {
559            ByRef::Yes(Mutability::Not) => max_ref_mutbl = MutblCap::Not,
560            _ => {}
561        }
562        debug!("default binding mode is now {:?}", binding_mode);
563        PatInfo { binding_mode, max_ref_mutbl, ..pat_info }
564    }
565
566    fn check_deref_pattern(
567        &mut self,
568        pat: PatId,
569        opt_path_res: Option<Result<ResolvedPat<'db>, ()>>,
570        adjust_mode: AdjustMode,
571        expected: Ty<'db>,
572        mut inner_ty: Ty<'db>,
573        pat_adjust_kind: PatAdjust,
574        pat_info: PatInfo,
575    ) -> Ty<'db> {
576        debug_assert!(
577            !matches!(pat_adjust_kind, PatAdjust::BuiltinDeref),
578            "unexpected deref pattern for builtin reference type {expected:?}",
579        );
580
581        let pat_adjustments = self.result.pat_adjustments.entry(pat).or_default();
582        // We may reach the recursion limit if a user matches on a type `T` satisfying
583        // `T: Deref<Target = T>`; error gracefully in this case.
584        // FIXME(deref_patterns): If `deref_patterns` stabilizes, it may make sense to move
585        // this check out of this branch. Alternatively, this loop could be implemented with
586        // autoderef and this check removed. For now though, don't break code compiling on
587        // stable with lots of `&`s and a low recursion limit, if anyone's done that.
588        if pat_adjustments.len() < self.resolver.top_level_def_map().recursion_limit() as usize {
589            // Preserve the smart pointer type for THIR lowering and closure upvar analysis.
590            pat_adjustments.push(PatAdjustment { kind: pat_adjust_kind, source: expected.store() });
591        } else {
592            // FIXME: Emit an error.
593            inner_ty = self.types.types.error;
594        }
595
596        // Recurse, using the old pat info to keep `current_depth` to its old value.
597        // Peeling smart pointers does not update the default binding mode.
598        self.infer_pat_inner(pat, opt_path_res, adjust_mode, inner_ty, pat_info)
599    }
600
601    /// How should the binding mode and expected type be adjusted?
602    ///
603    /// When the pattern contains a path, `opt_path_res` must be `Some(path_res)`.
604    fn calc_adjust_mode(
605        &mut self,
606        pat_id: PatId,
607        pat: &Pat,
608        opt_path_res: Option<Result<ResolvedPat<'db>, ()>>,
609    ) -> AdjustMode {
610        match pat {
611            // Type checking these product-like types successfully always require
612            // that the expected type be of those types and not reference types.
613            Pat::Tuple { .. } | Pat::Range { .. } | Pat::Slice { .. } => AdjustMode::peel_all(),
614            // When checking an explicit deref pattern, only peel reference types.
615            // FIXME(deref_patterns): If box patterns and deref patterns need to coexist, box
616            // patterns may want `PeelKind::Implicit`, stopping on encountering a box.
617            Pat::Box { .. } | Pat::Deref { .. } => {
618                AdjustMode::Peel { kind: PeelKind::ExplicitDerefPat }
619            }
620            // A never pattern behaves somewhat like a literal or unit variant.
621            // Pat::Never => AdjustMode::peel_all(),
622            // For patterns with paths, how we peel the scrutinee depends on the path's resolution.
623            Pat::Record { .. }
624            | Pat::TupleStruct { .. }
625            | Pat::Path(_) => {
626                // If there was an error resolving the path, default to peeling everything.
627                opt_path_res.unwrap().map_or(AdjustMode::peel_all(), |pr| pr.adjust_mode())
628            }
629
630            // String and byte-string literals result in types `&str` and `&[u8]` respectively.
631            // All other literals result in non-reference types.
632            // As a result, we allow `if let 0 = &&0 {}` but not `if let "foo" = &&"foo" {}` unless
633            // `deref_patterns` is enabled.
634            &Pat::Lit(expr) => {
635                let lit_ty = self.infer_expr_pat_unadjusted(expr);
636                let lit_ty = self.infcx().resolve_vars_if_possible(lit_ty);
637                // If `deref_patterns` is enabled, allow `if let "foo" = &&"foo" {}`.
638                if self.features.deref_patterns {
639                    let mut peeled_ty = lit_ty;
640                    let mut pat_ref_layers = 0;
641                    while let TyKind::Ref(_, inner_ty, mutbl) =
642                        self.table.try_structurally_resolve_type(pat_id.into(), peeled_ty).kind()
643                    {
644                        // We rely on references at the head of constants being immutable.
645                        debug_assert!(mutbl.is_not());
646                        pat_ref_layers += 1;
647                        peeled_ty = inner_ty;
648                    }
649                    AdjustMode::Peel {
650                        kind: PeelKind::Implicit { until_adt: None, pat_ref_layers },
651                    }
652                } else {
653                    if lit_ty.is_ref() { AdjustMode::Pass } else { AdjustMode::peel_all() }
654                }
655            }
656
657            // Ref patterns are complicated, we handle them in `check_pat_ref`.
658            Pat::Ref { .. }
659            // No need to do anything on a missing pattern.
660            | Pat::Missing
661            // No need to do anything on a `NotNull` pattern, they are only allowed in type contexts.
662            | Pat::NotNull
663            // A `_`/`..` pattern works with any expected type, so there's no need to do anything.
664            | Pat::Wild | Pat::Rest
665            // Bindings also work with whatever the expected type is,
666            // and moreover if we peel references off, that will give us the wrong binding type.
667            // Also, we can have a subpattern `binding @ pat`.
668            // Each side of the `@` should be treated independently (like with OR-patterns).
669            | Pat::Bind { .. }
670            // `Pat::Expr(_)` inside assignments becomes a binding in rustc, therefore should be
671            // the same as `Pat::Bind`.
672            | Pat::Expr(_)
673            // An OR-pattern just propagates to each individual alternative.
674            // This is maximally flexible, allowing e.g., `Some(mut x) | &Some(mut x)`.
675            // In that example, `Some(mut x)` results in `Peel` whereas `&Some(mut x)` in `Reset`.
676            | Pat::Or(_)
677            // Like or-patterns, guard patterns just propagate to their subpatterns.
678            /* | Pat::Guard(..) */ => AdjustMode::Pass,
679        }
680    }
681
682    /// Assuming `expected` is a reference type, determine whether to peel it before matching.
683    fn should_peel_ref(&self, peel_kind: PeelKind, mut expected: Ty<'db>) -> bool {
684        debug_assert!(expected.is_ref());
685        let pat_ref_layers = match peel_kind {
686            PeelKind::ExplicitDerefPat => 0,
687            PeelKind::Implicit { pat_ref_layers, .. } => pat_ref_layers,
688        };
689
690        // Most patterns don't have reference types, so we'll want to peel all references from the
691        // scrutinee before matching. To optimize for the common case, return early.
692        if pat_ref_layers == 0 {
693            return true;
694        }
695        debug_assert!(
696            self.features.deref_patterns,
697            "Peeling for patterns with reference types is gated by `deref_patterns`."
698        );
699
700        // If the pattern has as many or more layers of reference as the expected type, we can match
701        // without peeling more, unless we find a smart pointer or `&mut` that we also need to peel.
702        // We don't treat `&` and `&mut` as interchangeable, but by peeling `&mut`s before matching,
703        // we can still, e.g., match on a `&mut str` with a string literal pattern. This is because
704        // string literal patterns may be used where `str` is expected.
705        let mut expected_ref_layers = 0;
706        while let TyKind::Ref(_, inner_ty, mutbl) = expected.kind() {
707            if mutbl.is_mut() {
708                // Mutable references can't be in the final value of constants, thus they can't be
709                // at the head of their types, thus we should always peel `&mut`.
710                return true;
711            }
712            expected_ref_layers += 1;
713            expected = inner_ty;
714        }
715        pat_ref_layers < expected_ref_layers || self.should_peel_smart_pointer(peel_kind, expected)
716    }
717
718    /// Determine whether `expected` is a smart pointer type that should be peeled before matching.
719    fn should_peel_smart_pointer(&self, peel_kind: PeelKind, expected: Ty<'db>) -> bool {
720        // Explicit `deref!(_)` patterns match against smart pointers; don't peel in that case.
721        if let PeelKind::Implicit { until_adt, .. } = peel_kind
722            // For simplicity, only apply overloaded derefs if `expected` is a known ADT.
723            // FIXME(deref_patterns): we'll get better diagnostics for users trying to
724            // implicitly deref generics if we allow them here, but primitives, tuples, and
725            // inference vars definitely should be stopped. Figure out what makes most sense.
726            && let TyKind::Adt(scrutinee_adt, _) = expected.kind()
727            // Don't peel if the pattern type already matches the scrutinee. E.g., stop here if
728            // matching on a `Cow<'a, T>` scrutinee with a `Cow::Owned(_)` pattern.
729            && until_adt != Some(scrutinee_adt.def_id())
730            // At this point, the pattern isn't able to match `expected` without peeling. Check
731            // that it implements `Deref` before assuming it's a smart pointer, to get a normal
732            // type error instead of a missing impl error if not. This only checks for `Deref`,
733            // not `DerefPure`: we require that too, but we want a trait error if it's missing.
734            && let Some(deref_trait) = self.lang_items.Deref
735            && self.infcx().type_implements_trait(deref_trait, [expected], self.table.param_env).may_apply()
736        {
737            true
738        } else {
739            false
740        }
741    }
742
743    fn infer_expr_pat_unadjusted(&mut self, expr: ExprId) -> Ty<'db> {
744        self.infer_expr_no_expect(expr, ExprIsRead::Yes)
745    }
746
747    fn infer_lit_pat(&mut self, expr: ExprId, expected: Ty<'db>) -> Ty<'db> {
748        let literal = match &self.store[expr] {
749            Expr::Literal(literal) => literal,
750            _ => panic!("expected a literal"),
751        };
752
753        // We've already computed the type above (when checking for a non-ref pat),
754        // so avoid computing it again.
755        let ty = self.expr_ty(expr);
756
757        // Byte string patterns behave the same way as array patterns
758        // They can denote both statically and dynamically-sized byte arrays.
759        // Additionally, when `deref_patterns` is enabled, byte string literal patterns may have
760        // types `[u8]` or `[u8; N]`, in order to type, e.g., `deref!(b"..."): Vec<u8>`.
761        let mut pat_ty = ty;
762        if matches!(literal, Literal::ByteString(_)) {
763            let expected = self.structurally_resolve_type(expr.into(), expected);
764            match expected.kind() {
765                // Allow `b"...": &[u8]`
766                TyKind::Ref(_, inner_ty, _)
767                    if self
768                        .table
769                        .try_structurally_resolve_type(expr.into(), inner_ty)
770                        .is_slice() =>
771                {
772                    trace!(?expr, "polymorphic byte string lit");
773                    pat_ty = self.types.types.static_u8_slice;
774                }
775                // Allow `b"...": [u8; 3]` for `deref_patterns`
776                TyKind::Array(..) if self.features.deref_patterns => {
777                    pat_ty = match ty.kind() {
778                        TyKind::Ref(_, inner_ty, _) => inner_ty,
779                        _ => panic!("found byte string literal with non-ref type {ty:?}"),
780                    }
781                }
782                // Allow `b"...": [u8]` for `deref_patterns`
783                TyKind::Slice(..) if self.features.deref_patterns => {
784                    pat_ty = self.types.types.u8_slice;
785                }
786                // Otherwise, `b"...": &[u8; 3]`
787                _ => {}
788            }
789        }
790
791        // When `deref_patterns` is enabled, in order to allow `deref!("..."): String`, we allow
792        // string literal patterns to have type `str`. This is accounted for when lowering to MIR.
793        if self.features.deref_patterns
794            && matches!(literal, Literal::String(_))
795            && self.table.try_structurally_resolve_type(expr.into(), expected).is_str()
796        {
797            pat_ty = self.types.types.str;
798        }
799
800        // Somewhat surprising: in this case, the subtyping relation goes the
801        // opposite way as the other cases. Actually what we really want is not
802        // a subtyping relation at all but rather that there exists a LUB
803        // (so that they can be compared). However, in practice, constants are
804        // always scalars or strings. For scalars subtyping is irrelevant,
805        // and for strings `ty` is type is `&'static str`, so if we say that
806        //
807        //     &'static str <: expected
808        //
809        // then that's equivalent to there existing a LUB.
810        _ = self.demand_suptype(expr.into(), expected, pat_ty);
811
812        pat_ty
813    }
814
815    fn infer_range_pat(
816        &mut self,
817        pat: PatId,
818        lhs_expr: Option<ExprId>,
819        rhs_expr: Option<ExprId>,
820        expected: Ty<'db>,
821    ) -> Ty<'db> {
822        let mut calc_side = |opt_expr: Option<ExprId>| match opt_expr {
823            None => None,
824            Some(expr) => {
825                let ty = self.infer_expr_pat_unadjusted(expr);
826                // Check that the end-point is possibly of numeric or char type.
827                // The early check here is not for correctness, but rather better
828                // diagnostics (e.g. when `&str` is being matched, `expected` will
829                // be peeled to `str` while ty here is still `&str`, if we don't
830                // err early here, a rather confusing unification error will be
831                // emitted instead).
832                let ty = self.table.try_structurally_resolve_type(expr.into(), ty);
833                let fail =
834                    !(ty.is_numeric() || ty.is_char() || ty.is_ty_var() || ty.references_error());
835                Some((fail, ty, expr))
836            }
837        };
838        let mut lhs = calc_side(lhs_expr);
839        let mut rhs = calc_side(rhs_expr);
840
841        if let (Some((true, ..)), _) | (_, Some((true, ..))) = (lhs, rhs) {
842            // There exists a side that didn't meet our criteria that the end-point
843            // be of a numeric or char type, as checked in `calc_side` above.
844            self.push_diagnostic(InferenceDiagnostic::InvalidRangePatType { pat });
845            return self.types.types.error;
846        }
847
848        // Unify each side with `expected`.
849        // Subtyping doesn't matter here, as the value is some kind of scalar.
850        let mut demand_eqtype = |x: &mut _| {
851            if let Some((_, x_ty, x_expr)) = *x {
852                _ = self.demand_eqtype(ExprOrPatIdPacked::from(x_expr), expected, x_ty);
853            }
854        };
855        demand_eqtype(&mut lhs);
856        demand_eqtype(&mut rhs);
857
858        if let (Some((true, ..)), _) | (_, Some((true, ..))) = (lhs, rhs) {
859            return self.types.types.error;
860        }
861
862        // Find the unified type and check if it's of numeric or char type again.
863        // This check is needed if both sides are inference variables.
864        // We require types to be resolved here so that we emit inference failure
865        // rather than "_ is not a char or numeric".
866        let ty = self.structurally_resolve_type(
867            lhs_expr.or(rhs_expr).map(ExprOrPatIdPacked::from).unwrap_or(pat.into()),
868            expected,
869        );
870        if !(ty.is_numeric() || ty.is_char() || ty.references_error()) {
871            // FIXME: Emit an error.
872            return self.types.types.error;
873        }
874        ty
875    }
876
877    fn infer_bind_pat(
878        &mut self,
879        pat: PatId,
880        var_id: BindingId,
881        sub: Option<PatId>,
882        expected: Ty<'db>,
883        pat_info: PatInfo,
884    ) -> Ty<'db> {
885        let PatInfo { binding_mode: def_br, .. } = pat_info;
886        let binding_data = &self.store[var_id];
887
888        // Determine the binding mode...
889        let user_bind_annot = BindingMode::from_annotation(binding_data.mode);
890        let bm = match user_bind_annot {
891            BindingMode(ByRef::No, Mutability::Mut) if let ByRef::Yes(_) = def_br => {
892                // Only mention the experimental `mut_ref` feature if we're in edition 2024 and
893                // using other experimental matching features compatible with it.
894                if self.edition.at_least_2024()
895                    && (self.features.ref_pat_eat_one_layer_2024
896                        || self.features.ref_pat_eat_one_layer_2024_structural)
897                {
898                    if !self.features.mut_ref {
899                        self.push_diagnostic(InferenceDiagnostic::MutableRefBinding { pat });
900                    }
901
902                    BindingMode(def_br, Mutability::Mut)
903                } else {
904                    // `mut` resets the binding mode on edition <= 2021
905                    BindingMode(ByRef::No, Mutability::Mut)
906                }
907            }
908            BindingMode(ByRef::No, mutbl) => BindingMode(def_br, mutbl),
909            BindingMode(ByRef::Yes(_), _) => user_bind_annot,
910        };
911
912        if matches!(bm.0, ByRef::Yes(Mutability::Mut))
913            && let MutblCap::WeaklyNot = pat_info.max_ref_mutbl
914        {
915            self.push_diagnostic(InferenceDiagnostic::MutRefInImmRefPat { pat });
916        }
917
918        // ...and store it in a side table:
919        self.result.binding_modes.insert(pat, bm);
920
921        debug!("check_pat_ident: pat.hir_id={:?} bm={:?}", pat, bm);
922
923        let local_ty = match bm.0 {
924            ByRef::Yes(mutbl) => {
925                // If the binding is like `ref x | ref mut x`,
926                // then `x` is assigned a value of type `&M T` where M is the
927                // mutability and T is the expected type.
928                //
929                // Under pin ergonomics, if the binding is like `ref pin const|mut x`,
930                // then `x` is assigned a value of type `&pin M T` where M is the
931                // mutability and T is the expected type.
932                //
933                // `x` is assigned a value of type `&M T`, hence `&M T <: typeof(x)`
934                // is required. However, we use equality, which is stronger.
935                // See (note_1) for an explanation.
936                self.new_ref_ty(pat.into(), mutbl, expected)
937            }
938            // Otherwise, the type of x is the expected type `T`.
939            ByRef::No => expected, // As above, `T <: typeof(x)` is required, but we use equality, see (note_1).
940        };
941
942        // We have a concrete type for the local, so we do not need to taint it and hide follow up errors *using* the local.
943        if let Some(existing_local_ty) = self.result.type_of_binding.get(var_id) {
944            // If there are multiple arms, make sure they all agree on
945            // what the type of the binding `x` ought to be.
946            _ = self.demand_eqtype(pat.into(), existing_local_ty.as_ref(), local_ty);
947        } else {
948            self.write_binding_ty(var_id, local_ty);
949        }
950
951        if let Some(p) = sub {
952            self.infer_pat(p, expected, pat_info);
953        }
954
955        local_ty
956    }
957
958    fn check_dereferenceable(
959        &mut self,
960        expected: Ty<'db>,
961        pat: PatId,
962        inner: PatId,
963    ) -> Result<(), ()> {
964        if let Pat::Bind { .. } = self.store[inner]
965            && let Some(pointee_ty) = self.shallow_resolve(expected).builtin_deref(true)
966            && let TyKind::Dynamic(..) = pointee_ty.kind()
967        {
968            // This is "x = dyn SomeTrait" being reduced from
969            // "let &x = &dyn SomeTrait" or "let box x = Box<dyn SomeTrait>", an error.
970            self.push_diagnostic(InferenceDiagnostic::CannotImplicitlyDerefTraitObject {
971                pat,
972                found: expected.store(),
973            });
974            return Err(());
975        }
976        Ok(())
977    }
978
979    fn resolve_record_pat(&mut self, pat: PatId, path: &Path) -> Result<ResolvedPat<'db>, ()> {
980        // Resolve the path and check the definition for errors.
981        let (pat_ty, Some(variant)) = self.resolve_variant(pat.into(), path, false) else {
982            return Err(());
983        };
984        self.write_variant_resolution(pat.into(), variant);
985        Ok(ResolvedPat { ty: pat_ty, kind: ResolvedPatKind::Struct { variant } })
986    }
987
988    fn infer_record_pat(
989        &mut self,
990        pat: PatId,
991        fields: &[RecordFieldPat],
992        has_rest_pat: bool,
993        pat_ty: Ty<'db>,
994        variant: VariantId,
995        expected: Ty<'db>,
996        pat_info: PatInfo,
997    ) -> Ty<'db> {
998        // Type-check the path.
999        let _ = self.demand_eqtype(pat.into(), expected, pat_ty);
1000
1001        // Type-check subpatterns.
1002        self.check_record_pat_fields(pat_ty, pat, variant, fields, has_rest_pat, pat_info);
1003        pat_ty
1004    }
1005
1006    fn resolve_pat_path(&mut self, pat: PatId, path: &Path) -> Result<ResolvedPat<'db>, ()> {
1007        let (res, pat_ty) = self.infer_path(path, pat.into()).ok_or(())?;
1008        match res {
1009            ValueNs::FunctionId(_)
1010            | ValueNs::GenericParam(_)
1011            | ValueNs::ImplSelf(_)
1012            | ValueNs::LocalBinding(_)
1013            | ValueNs::StaticId(_) => {
1014                // FIXME: Emit an error.
1015                return Err(());
1016            }
1017            ValueNs::ConstId(_) | ValueNs::EnumVariantId(_) | ValueNs::StructId(_) => {} // OK
1018        }
1019
1020        Ok(ResolvedPat { ty: pat_ty, kind: ResolvedPatKind::Path { res } })
1021    }
1022
1023    fn infer_pat_path(
1024        &mut self,
1025        pat: PatId,
1026        resolved: &ResolvedPat<'db>,
1027        expected: Ty<'db>,
1028    ) -> Ty<'db> {
1029        _ = self.demand_suptype(pat.into(), expected, resolved.ty);
1030        resolved.ty
1031    }
1032
1033    fn resolve_tuple_struct_pat(
1034        &mut self,
1035        pat: PatId,
1036        path: &Path,
1037    ) -> Result<ResolvedPat<'db>, ()> {
1038        // Resolve the path and check the definition for errors.
1039        let (pat_ty, Some(variant)) = self.resolve_variant(pat.into(), path, true) else {
1040            return Err(());
1041        };
1042        self.write_variant_resolution(pat.into(), variant);
1043        Ok(ResolvedPat { ty: pat_ty, kind: ResolvedPatKind::TupleStruct { variant } })
1044    }
1045
1046    fn infer_tuple_struct_pat(
1047        &mut self,
1048        pat: PatId,
1049        subpats: &[PatId],
1050        ddpos: Option<u32>,
1051        pat_ty: Ty<'db>,
1052        variant: VariantId,
1053        expected: Ty<'db>,
1054        pat_info: PatInfo,
1055    ) -> Ty<'db> {
1056        let interner = self.interner();
1057
1058        // Type-check the tuple struct pattern against the expected type.
1059        let had_err = self.demand_eqtype(pat.into(), expected, pat_ty);
1060
1061        let variant_fields = variant.fields(self.db);
1062        let variant_field_tys = self.db.field_types(variant);
1063        let TyKind::Adt(_, args) = pat_ty.kind() else {
1064            panic!("unexpected pattern type {:?}", pat_ty);
1065        };
1066        // Type-check subpatterns.
1067        if subpats.len() == variant_fields.len()
1068            || subpats.len() < variant_fields.len() && ddpos.is_some()
1069        {
1070            for (i, &subpat) in subpats.iter().enumerate_and_adjust(variant_fields.len(), ddpos) {
1071                let field_id = LocalFieldId::from_raw(la_arena::RawIdx::from_u32(i as u32));
1072                let field_ty =
1073                    variant_field_tys[field_id].ty().instantiate(interner, args).skip_norm_wip();
1074                self.infer_pat(subpat, field_ty, pat_info);
1075            }
1076            if let Err(()) = had_err {
1077                for &pat in subpats {
1078                    self.infer_pat(pat, self.types.types.error, pat_info);
1079                }
1080                return self.types.types.error;
1081            }
1082        } else {
1083            self.push_diagnostic(InferenceDiagnostic::MismatchedTupleStructPatArgCount {
1084                pat,
1085                expected: variant_fields.len(),
1086                found: subpats.len(),
1087            });
1088
1089            for (i, &pat) in subpats.iter().enumerate() {
1090                let field_id = LocalFieldId::from_raw(la_arena::RawIdx::from_u32(i as u32));
1091                let expected = match variant_field_tys.get(field_id) {
1092                    Some(field_ty) => field_ty.ty().instantiate(interner, args).skip_norm_wip(),
1093                    None => self.types.types.error,
1094                };
1095                self.infer_pat(pat, expected, pat_info);
1096            }
1097        }
1098        pat_ty
1099    }
1100
1101    fn infer_tuple_pat(
1102        &mut self,
1103        pat: PatId,
1104        elements: &[PatId],
1105        ddpos: Option<u32>,
1106        expected: Ty<'db>,
1107        pat_info: PatInfo,
1108    ) -> Ty<'db> {
1109        let interner = self.interner();
1110        let mut expected_len = elements.len();
1111        if ddpos.is_some() {
1112            // Require known type only when `..` is present.
1113            if let TyKind::Tuple(tys) = self.structurally_resolve_type(pat.into(), expected).kind()
1114            {
1115                expected_len = tys.len();
1116            }
1117        }
1118        let max_len = cmp::max(expected_len, elements.len());
1119
1120        let element_tys_iter = (0..max_len).map(|i| {
1121            self.table.next_ty_var(elements.get(i).copied().map(Span::PatId).unwrap_or(Span::Dummy))
1122        });
1123        let element_tys = Tys::new_from_iter(interner, element_tys_iter);
1124        let pat_ty = Ty::new(interner, TyKind::Tuple(element_tys));
1125        if self.demand_eqtype(pat.into(), expected, pat_ty).is_err() {
1126            let expected = if let TyKind::Tuple(tys) =
1127                self.table.try_structurally_resolve_type(Span::Dummy, expected).kind()
1128            {
1129                for (expected_var, found) in iter::zip(element_tys, tys) {
1130                    // Constrain the infer var so that the type mismatch error message, which contains it,
1131                    // will be better.
1132                    _ = self.demand_eqtype(pat.into(), expected_var, found);
1133                }
1134                tys
1135            } else {
1136                self.types.empty.tys
1137            };
1138            let expected = expected.iter().chain(iter::repeat(self.types.types.error));
1139            Ty::new_tup_from_iter(
1140                interner,
1141                iter::zip(expected, elements).map(|(expected, &elem)| {
1142                    self.infer_pat(elem, expected, pat_info);
1143                    self.result.type_of_pat_with_adjust(elem)
1144                }),
1145            )
1146        } else {
1147            for (i, &elem) in elements.iter().enumerate_and_adjust(max_len, ddpos) {
1148                self.infer_pat(elem, element_tys[i], pat_info);
1149            }
1150            pat_ty
1151        }
1152    }
1153
1154    fn check_record_pat_fields(
1155        &mut self,
1156        adt_ty: Ty<'db>,
1157        pat: PatId,
1158        variant: VariantId,
1159        fields: &[RecordFieldPat],
1160        has_rest_pat: bool,
1161        pat_info: PatInfo,
1162    ) {
1163        let interner = self.interner();
1164
1165        let TyKind::Adt(_, args) = adt_ty.kind() else {
1166            panic!("struct pattern is not an ADT");
1167        };
1168
1169        // Index the struct fields' types.
1170        let variant_fields = variant.fields(self.db);
1171        let field_map = variant_fields
1172            .fields()
1173            .iter()
1174            .map(|(i, field)| (field.name.clone(), i))
1175            .collect::<FxHashMap<_, _>>();
1176        let variant_field_tys = self.db.field_types(variant);
1177        let variant_fields_vis = VariantFields::field_visibilities(self.db, variant);
1178
1179        // Keep track of which fields have already appeared in the pattern.
1180        let mut used_fields = FxHashMap::default();
1181
1182        let mut inexistent_fields = vec![];
1183        // Typecheck each field.
1184        for (field_idx, field) in fields.iter().enumerate() {
1185            match used_fields.entry(field.name.clone()) {
1186                Occupied(_occupied) => {
1187                    self.push_diagnostic(InferenceDiagnostic::DuplicateField {
1188                        field: field.pat.into(),
1189                        variant,
1190                    });
1191                }
1192                Vacant(vacant) => {
1193                    vacant.insert(field_idx);
1194                }
1195            };
1196            let field_idx = field_map.get(&field.name).copied();
1197            let field_ty = match field_idx {
1198                Some(field_idx) => {
1199                    if !self.resolver.is_visible(self.db, variant_fields_vis[field_idx]) {
1200                        self.push_diagnostic(InferenceDiagnostic::NoSuchField {
1201                            field: field.pat.into(),
1202                            private: Some(field_idx),
1203                            variant,
1204                        });
1205                    }
1206
1207                    variant_field_tys[field_idx].ty().instantiate(interner, args).skip_norm_wip()
1208                }
1209                None => {
1210                    inexistent_fields.push(field);
1211                    self.types.types.error
1212                }
1213            };
1214
1215            self.infer_pat(field.pat, field_ty, pat_info);
1216        }
1217
1218        let unmentioned_fields = variant_fields
1219            .fields()
1220            .iter()
1221            .filter(|(_, field)| !used_fields.contains_key(&field.name))
1222            .collect::<Vec<_>>();
1223
1224        for inexistent_field in inexistent_fields {
1225            self.push_diagnostic(InferenceDiagnostic::NoSuchField {
1226                field: inexistent_field.pat.into(),
1227                private: None,
1228                variant,
1229            });
1230        }
1231
1232        // Require `..` if struct has non_exhaustive attribute.
1233        let non_exhaustive = self.has_applicable_non_exhaustive(variant.into());
1234        if non_exhaustive && !has_rest_pat {
1235            self.push_diagnostic(InferenceDiagnostic::NonExhaustiveRecordPat { pat, variant });
1236        }
1237
1238        // Report an error if an incorrect number of fields was specified.
1239        if matches!(variant, VariantId::UnionId(_)) {
1240            if fields.len() != 1 {
1241                self.push_diagnostic(InferenceDiagnostic::UnionPatMustHaveExactlyOneField { pat });
1242            }
1243            if has_rest_pat {
1244                self.push_diagnostic(InferenceDiagnostic::UnionPatHasRest { pat });
1245            }
1246        } else if !unmentioned_fields.is_empty() && !has_rest_pat {
1247            self.push_diagnostic(InferenceDiagnostic::RecordMissingFields {
1248                record: ExprOrPatId::PatId(pat),
1249                variant,
1250                missed_fields: unmentioned_fields.into_iter().map(|f| f.0).collect(),
1251            })
1252        }
1253    }
1254
1255    fn infer_box_pat(
1256        &mut self,
1257        pat: PatId,
1258        inner: PatId,
1259        expected: Ty<'db>,
1260        pat_info: PatInfo,
1261    ) -> Ty<'db> {
1262        let interner = self.interner();
1263        let (box_ty, inner_ty) = self
1264            .check_dereferenceable(expected, pat, inner)
1265            .map(|()| {
1266                // Here, `demand::subtype` is good enough, but I don't
1267                // think any errors can be introduced by using `demand::eqtype`.
1268                let inner_ty = self.table.next_ty_var(inner.into());
1269                let box_ty = Ty::new_box(interner, inner_ty);
1270                _ = self.demand_eqtype(pat.into(), expected, box_ty);
1271                (box_ty, inner_ty)
1272            })
1273            .unwrap_or_else(|()| {
1274                let err = self.types.types.error;
1275                (err, err)
1276            });
1277        self.infer_pat(inner, inner_ty, pat_info);
1278        box_ty
1279    }
1280
1281    fn infer_deref_pat(
1282        &mut self,
1283        pat: PatId,
1284        inner: PatId,
1285        expected: Ty<'db>,
1286        pat_info: PatInfo,
1287    ) -> Ty<'db> {
1288        let target_ty = self.deref_pat_target(pat, expected);
1289        self.infer_pat(inner, target_ty, pat_info);
1290        let infer_ok = self.register_deref_mut_bounds_if_needed(pat, inner, [expected]);
1291        self.table.register_infer_ok(infer_ok);
1292        expected
1293    }
1294
1295    fn deref_pat_target(&mut self, pat: PatId, source_ty: Ty<'db>) -> Ty<'db> {
1296        let (Some(deref_pure), Some(deref_target)) =
1297            (self.lang_items.DerefPure, self.lang_items.DerefTarget)
1298        else {
1299            return self.types.types.error;
1300        };
1301        // Register a `DerefPure` bound, which is required by all `deref!()` pats.
1302        let interner = self.interner();
1303        self.table.register_bound(source_ty, deref_pure, ObligationCause::new(pat));
1304        // The expected type for the deref pat's inner pattern is `<expected as Deref>::Target`.
1305        let target_ty = Ty::new_projection(interner, deref_target.into(), [source_ty]);
1306        self.table.try_structurally_resolve_type(pat.into(), target_ty)
1307    }
1308
1309    /// Check if the interior of a deref pattern (either explicit or implicit) has any `ref mut`
1310    /// bindings, which would require `DerefMut` to be emitted in MIR building instead of just
1311    /// `Deref`. We do this *after* checking the inner pattern, since we want to make sure to
1312    /// account for `ref mut` binding modes inherited from implicitly dereferencing `&mut` refs.
1313    fn register_deref_mut_bounds_if_needed(
1314        &self,
1315        pat: PatId,
1316        inner: PatId,
1317        derefed_tys: impl IntoIterator<Item = Ty<'db>>,
1318    ) -> InferOk<'db, ()> {
1319        let mut infer_ok = InferOk { value: (), obligations: Vec::new() };
1320        if self.pat_has_ref_mut_binding(inner) {
1321            let Some(deref_mut) = self.lang_items.DerefMut else { return infer_ok };
1322            let interner = self.interner();
1323            for mutably_derefed_ty in derefed_tys {
1324                infer_ok.obligations.push(Obligation::new(
1325                    interner,
1326                    ObligationCause::new(pat),
1327                    self.table.param_env,
1328                    TraitRef::new(interner, deref_mut.into(), [mutably_derefed_ty]),
1329                ));
1330            }
1331        }
1332        infer_ok
1333    }
1334
1335    /// Does the pattern recursively contain a `ref mut` binding in it?
1336    ///
1337    /// This is used to determined whether a `deref` pattern should emit a `Deref`
1338    /// or `DerefMut` call for its pattern scrutinee.
1339    ///
1340    /// This is computed from the typeck results since we want to make
1341    /// sure to apply any match-ergonomics adjustments, which we cannot
1342    /// determine from the HIR alone.
1343    pub(super) fn pat_has_ref_mut_binding(&self, pat: PatId) -> bool {
1344        let mut has_ref_mut = false;
1345        self.store.walk_pats(pat, &mut |pat| {
1346            if let Some(BindingMode(ByRef::Yes(Mutability::Mut), _)) =
1347                self.result.binding_modes.get(pat)
1348            {
1349                has_ref_mut = true;
1350            }
1351        });
1352        has_ref_mut
1353    }
1354
1355    // Precondition: Pat is Ref(inner)
1356    fn infer_ref_pat(
1357        &mut self,
1358        pat: PatId,
1359        inner: PatId,
1360        pat_mutbl: Mutability,
1361        mut expected: Ty<'db>,
1362        mut pat_info: PatInfo,
1363    ) -> Ty<'db> {
1364        let ref_pat_matches_mut_ref = self.ref_pat_matches_mut_ref();
1365        if ref_pat_matches_mut_ref && pat_mutbl == Mutability::Not {
1366            // If `&` patterns can match against mutable reference types (RFC 3627, Rule 5), we need
1367            // to prevent subpatterns from binding with `ref mut`. Subpatterns of a shared reference
1368            // pattern should have read-only access to the scrutinee, and the borrow checker won't
1369            // catch it in this case.
1370            pat_info.max_ref_mutbl = pat_info.max_ref_mutbl.cap_to_weakly_not();
1371        }
1372
1373        expected = self.table.try_structurally_resolve_type(pat.into(), expected);
1374        // Determine whether we're consuming an inherited reference and resetting the default
1375        // binding mode, based on edition and enabled experimental features.
1376        if let ByRef::Yes(inh_mut) = pat_info.binding_mode {
1377            match self.ref_pat_matches_inherited_ref(self.edition) {
1378                InheritedRefMatchRule::EatOuter => {
1379                    // ref pattern attempts to consume inherited reference
1380                    if pat_mutbl > inh_mut {
1381                        // Tried to match inherited `ref` with `&mut`
1382                        // NB: This assumes that `&` patterns can match against mutable references
1383                        // (RFC 3627, Rule 5). If we implement a pattern typing ruleset with Rule 4E
1384                        // but not Rule 5, we'll need to check that here.
1385                        debug_assert!(ref_pat_matches_mut_ref);
1386                        // FIXME: Emit an error.
1387                    }
1388
1389                    pat_info.binding_mode = ByRef::No;
1390                    self.result.skipped_ref_pats.insert(pat);
1391                    self.infer_pat(inner, expected, pat_info);
1392                    return expected;
1393                }
1394                InheritedRefMatchRule::EatInner => {
1395                    if let TyKind::Ref(_, _, r_mutbl) = expected.kind()
1396                        && pat_mutbl <= r_mutbl
1397                    {
1398                        // Match against the reference type; don't consume the inherited ref.
1399                        // NB: The check for compatible pattern and ref type mutability assumes that
1400                        // `&` patterns can match against mutable references (RFC 3627, Rule 5). If
1401                        // we implement a pattern typing ruleset with Rule 4 (including the fallback
1402                        // to matching the inherited ref when the inner ref can't match) but not
1403                        // Rule 5, we'll need to check that here.
1404                        debug_assert!(ref_pat_matches_mut_ref);
1405                        // NB: For RFC 3627's Rule 3, we limit the default binding mode's ref
1406                        // mutability to `pat_info.max_ref_mutbl`. If we implement a pattern typing
1407                        // ruleset with Rule 4 but not Rule 3, we'll need to check that here.
1408                        debug_assert!(self.downgrade_mut_inside_shared());
1409                        let mutbl_cap = cmp::min(r_mutbl, pat_info.max_ref_mutbl.as_mutbl());
1410                        pat_info.binding_mode = pat_info.binding_mode.cap_ref_mutability(mutbl_cap);
1411                    } else {
1412                        // The reference pattern can't match against the expected type, so try
1413                        // matching against the inherited ref instead.
1414                        if pat_mutbl > inh_mut {
1415                            // We can't match an inherited shared reference with `&mut`.
1416                            // NB: This assumes that `&` patterns can match against mutable
1417                            // references (RFC 3627, Rule 5). If we implement a pattern typing
1418                            // ruleset with Rule 4 but not Rule 5, we'll need to check that here.
1419                            // FIXME(ref_pat_eat_one_layer_2024_structural): If we already tried
1420                            // matching the real reference, the error message should explain that
1421                            // falling back to the inherited reference didn't work. This should be
1422                            // the same error as the old-Edition version below.
1423                            debug_assert!(ref_pat_matches_mut_ref);
1424                            // FIXME: Emit an error.
1425                        }
1426
1427                        pat_info.binding_mode = ByRef::No;
1428                        self.result.skipped_ref_pats.insert(pat);
1429                        self.infer_pat(inner, expected, pat_info);
1430                        return expected;
1431                    }
1432                }
1433                InheritedRefMatchRule::EatBoth { consider_inherited_ref: true } => {
1434                    // Reset binding mode on old editions
1435                    pat_info.binding_mode = ByRef::No;
1436
1437                    if let TyKind::Ref(_, inner_ty, _) = expected.kind() {
1438                        // Consume both the inherited and inner references.
1439                        if pat_mutbl.is_mut() && inh_mut.is_mut() {
1440                            // As a special case, a `&mut` reference pattern will be able to match
1441                            // against a reference type of any mutability if the inherited ref is
1442                            // mutable. Since this allows us to match against a shared reference
1443                            // type, we refer to this as "falling back" to matching the inherited
1444                            // reference, though we consume the real reference as well. We handle
1445                            // this here to avoid adding this case to the common logic below.
1446                            self.infer_pat(inner, inner_ty, pat_info);
1447                            return expected;
1448                        } else {
1449                            // Otherwise, use the common logic below for matching the inner
1450                            // reference type.
1451                            // FIXME(ref_pat_eat_one_layer_2024_structural): If this results in a
1452                            // mutability mismatch, the error message should explain that falling
1453                            // back to the inherited reference didn't work. This should be the same
1454                            // error as the Edition 2024 version above.
1455                        }
1456                    } else {
1457                        // The expected type isn't a reference type, so only match against the
1458                        // inherited reference.
1459                        if pat_mutbl > inh_mut {
1460                            // We can't match a lone inherited shared reference with `&mut`.
1461                            // FIXME: Emit an error.
1462                        }
1463
1464                        self.result.skipped_ref_pats.insert(pat);
1465                        self.infer_pat(inner, expected, pat_info);
1466                        return expected;
1467                    }
1468                }
1469                InheritedRefMatchRule::EatBoth { consider_inherited_ref: false } => {
1470                    // Reset binding mode on stable Rust. This will be a type error below if
1471                    // `expected` is not a reference type.
1472                    pat_info.binding_mode = ByRef::No;
1473                }
1474            }
1475        }
1476
1477        let (ref_ty, inner_ty) = match self.check_dereferenceable(expected, pat, inner) {
1478            Ok(()) => {
1479                // `demand::subtype` would be good enough, but using `eqtype` turns
1480                // out to be equally general. See (note_1) for details.
1481
1482                // Take region, inner-type from expected type if we can,
1483                // to avoid creating needless variables. This also helps with
1484                // the bad interactions of the given hack detailed in (note_1).
1485                debug!("check_pat_ref: expected={:?}", expected);
1486                match expected.as_reference() {
1487                    Some((r_ty, _, r_mutbl))
1488                        if ((ref_pat_matches_mut_ref && r_mutbl >= pat_mutbl)
1489                            || r_mutbl == pat_mutbl) =>
1490                    {
1491                        if r_mutbl == Mutability::Not {
1492                            pat_info.max_ref_mutbl = MutblCap::Not;
1493                        }
1494
1495                        (expected, r_ty)
1496                    }
1497                    _ => {
1498                        let inner_ty = self.table.next_ty_var(inner.into());
1499                        let ref_ty = self.new_ref_ty(inner.into(), pat_mutbl, inner_ty);
1500                        debug!("check_pat_ref: demanding {:?} = {:?}", expected, ref_ty);
1501                        _ = self.demand_eqtype(pat.into(), expected, ref_ty);
1502
1503                        (ref_ty, inner_ty)
1504                    }
1505                }
1506            }
1507            Err(()) => {
1508                let err = self.types.types.error;
1509                (err, err)
1510            }
1511        };
1512
1513        self.infer_pat(inner, inner_ty, pat_info);
1514        ref_ty
1515    }
1516
1517    /// Create a reference or pinned reference type with a fresh region variable.
1518    fn new_ref_ty(&self, span: Span, mutbl: Mutability, ty: Ty<'db>) -> Ty<'db> {
1519        let region = self.table.next_region_var(span);
1520        Ty::new_ref(self.interner(), region, ty, mutbl)
1521    }
1522
1523    fn try_resolve_slice_ty_to_array_ty(
1524        &self,
1525        before: &[PatId],
1526        slice: Option<PatId>,
1527        pat: PatId,
1528    ) -> Option<Ty<'db>> {
1529        if slice.is_some() {
1530            return None;
1531        }
1532
1533        let interner = self.interner();
1534        let len = before.len();
1535        let inner_ty = self.table.next_ty_var(pat.into());
1536
1537        Some(Ty::new_array(interner, inner_ty, len.try_into().unwrap()))
1538    }
1539
1540    /// Used to determines whether we can infer the expected type in the slice pattern to be of type array.
1541    /// This is only possible if we're in an irrefutable pattern. If we were to allow this in refutable
1542    /// patterns we wouldn't e.g. report ambiguity in the following situation:
1543    ///
1544    /// ```ignore(rust)
1545    /// struct Zeroes;
1546    ///    const ARR: [usize; 2] = [0; 2];
1547    ///    const ARR2: [usize; 2] = [2; 2];
1548    ///
1549    ///    impl Into<&'static [usize; 2]> for Zeroes {
1550    ///        fn into(self) -> &'static [usize; 2] {
1551    ///            &ARR
1552    ///        }
1553    ///    }
1554    ///
1555    ///    impl Into<&'static [usize]> for Zeroes {
1556    ///        fn into(self) -> &'static [usize] {
1557    ///            &ARR2
1558    ///        }
1559    ///    }
1560    ///
1561    ///    fn main() {
1562    ///        let &[a, b]: &[usize] = Zeroes.into() else {
1563    ///           ..
1564    ///        };
1565    ///    }
1566    /// ```
1567    ///
1568    /// If we're in an irrefutable pattern we prefer the array impl candidate given that
1569    /// the slice impl candidate would be rejected anyway (if no ambiguity existed).
1570    fn pat_is_irrefutable(&self, pat_origin: PatOrigin) -> bool {
1571        match pat_origin {
1572            PatOrigin::LetExpr | PatOrigin::MatchArm => false,
1573            PatOrigin::LetStmt { has_else } => !has_else,
1574            PatOrigin::DestructuringAssignment | PatOrigin::Param => true,
1575        }
1576    }
1577
1578    /// Type check a slice pattern.
1579    ///
1580    /// Syntactically, these look like `[pat_0, ..., pat_n]`.
1581    /// Semantically, we are type checking a pattern with structure:
1582    /// ```ignore (not-rust)
1583    /// [before_0, ..., before_n, (slice, after_0, ... after_n)?]
1584    /// ```
1585    /// The type of `slice`, if it is present, depends on the `expected` type.
1586    /// If `slice` is missing, then so is `after_i`.
1587    /// If `slice` is present, it can still represent 0 elements.
1588    fn infer_slice_pat(
1589        &mut self,
1590        pat: PatId,
1591        before: &[PatId],
1592        slice: Option<PatId>,
1593        after: &[PatId],
1594        expected: Ty<'db>,
1595        pat_info: PatInfo,
1596    ) -> Ty<'db> {
1597        let expected = self.table.try_structurally_resolve_type(pat.into(), expected);
1598
1599        // If the pattern is irrefutable and `expected` is an infer ty, we try to equate it
1600        // to an array if the given pattern allows it. See issue #76342
1601        if self.pat_is_irrefutable(pat_info.pat_origin)
1602            && expected.is_ty_var()
1603            && let Some(resolved_arr_ty) = self.try_resolve_slice_ty_to_array_ty(before, slice, pat)
1604        {
1605            debug!(?resolved_arr_ty);
1606            let _ = self.demand_eqtype(pat.into(), expected, resolved_arr_ty);
1607        }
1608
1609        let expected = self.structurally_resolve_type(pat.into(), expected);
1610        debug!(?expected);
1611
1612        let (element_ty, opt_slice_ty, inferred) = match expected.kind() {
1613            // An array, so we might have something like `let [a, b, c] = [0, 1, 2];`.
1614            TyKind::Array(element_ty, len) => {
1615                let min = before.len() as u64 + after.len() as u64;
1616                let (opt_slice_ty, expected) =
1617                    self.check_array_pat_len(pat, element_ty, expected, slice, len, min);
1618                // `opt_slice_ty.is_none()` => `slice.is_none()`.
1619                // Note, though, that opt_slice_ty could be `Some(error_ty)`.
1620                assert!(opt_slice_ty.is_some() || slice.is_none());
1621                (element_ty, opt_slice_ty, expected)
1622            }
1623            TyKind::Slice(element_ty) => (element_ty, Some(expected), expected),
1624            // The expected type must be an array or slice, but was neither, so error.
1625            _ => {
1626                self.push_diagnostic(InferenceDiagnostic::ExpectedArrayOrSlicePat {
1627                    pat,
1628                    found: expected.store(),
1629                });
1630                let err = self.types.types.error;
1631                (err, Some(err), err)
1632            }
1633        };
1634
1635        // Type check all the patterns before `slice`.
1636        for &elt in before {
1637            self.infer_pat(elt, element_ty, pat_info);
1638        }
1639        // Type check the `slice`, if present, against its expected type.
1640        if let Some(slice) = slice {
1641            self.infer_pat(slice, opt_slice_ty.unwrap(), pat_info);
1642        }
1643        // Type check the elements after `slice`, if present.
1644        for &elt in after {
1645            self.infer_pat(elt, element_ty, pat_info);
1646        }
1647        inferred
1648    }
1649
1650    /// Type check the length of an array pattern.
1651    ///
1652    /// Returns both the type of the variable length pattern (or `None`), and the potentially
1653    /// inferred array type. We only return `None` for the slice type if `slice.is_none()`.
1654    fn check_array_pat_len(
1655        &mut self,
1656        pat: PatId,
1657        element_ty: Ty<'db>,
1658        arr_ty: Ty<'db>,
1659        slice: Option<PatId>,
1660        len: Const<'db>,
1661        min_len: u64,
1662    ) -> (Option<Ty<'db>>, Ty<'db>) {
1663        let len = self.table.try_structurally_resolve_const(pat.into(), len);
1664
1665        if let Some(len) = len.try_to_target_usize(self.data_layout()) {
1666            // Now we know the length...
1667            if slice.is_none() {
1668                // ...and since there is no variable-length pattern,
1669                // we require an exact match between the number of elements
1670                // in the array pattern and as provided by the matched type.
1671                if min_len == len {
1672                    return (None, arr_ty);
1673                }
1674
1675                self.push_diagnostic(InferenceDiagnostic::MismatchedArrayPatLen {
1676                    pat,
1677                    expected: len,
1678                    found: min_len,
1679                    has_rest: false,
1680                });
1681            } else if let Some(pat_len) = len.checked_sub(min_len) {
1682                // The variable-length pattern was there,
1683                // so it has an array type with the remaining elements left as its size...
1684                return (Some(Ty::new_array(self.interner(), element_ty, pat_len)), arr_ty);
1685            } else {
1686                // ...however, in this case, there were no remaining elements.
1687                // That is, the slice pattern requires more than the array type offers.
1688                self.push_diagnostic(InferenceDiagnostic::MismatchedArrayPatLen {
1689                    pat,
1690                    expected: len,
1691                    found: min_len,
1692                    has_rest: true,
1693                });
1694            }
1695        } else if slice.is_none() {
1696            // We have a pattern with a fixed length,
1697            // which we can use to infer the length of the array.
1698            let updated_arr_ty = Ty::new_array(self.interner(), element_ty, min_len);
1699            _ = self.demand_eqtype(pat.into(), updated_arr_ty, arr_ty);
1700            return (None, updated_arr_ty);
1701        } else if !len.is_error() {
1702            // We have a variable-length pattern and don't know the array length.
1703            // This happens if we have e.g.,
1704            // `let [a, b, ..] = arr` where `arr: [T; N]` where `const N: usize`.
1705            self.push_diagnostic(InferenceDiagnostic::ArrayPatternWithoutFixedLength { pat });
1706        };
1707
1708        // If we get here, we must have emitted an error.
1709        (Some(self.types.types.error), arr_ty)
1710    }
1711
1712    fn infer_destructuring_assignment_expr(&mut self, expr: ExprId, expected: Ty<'db>) -> Ty<'db> {
1713        // LHS of assignment doesn't constitute reads.
1714        let expr_is_read = ExprIsRead::No;
1715        let lhs_ty = self.infer_expr_inner(expr, &Expectation::has_type(expected), expr_is_read);
1716        match self.coerce(expr, expected, lhs_ty, AllowTwoPhase::No, expr_is_read) {
1717            Ok(ty) => ty,
1718            Err(_) => {
1719                self.emit_type_mismatch(expr.into(), expected, lhs_ty);
1720                // `rhs_ty` is returned so no further type mismatches are
1721                // reported because of this mismatch.
1722                expected
1723            }
1724        }
1725    }
1726}