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            Pat::ConstBlock(expr) => {
534                self.infer_expr(expr, &Expectation::has_type(expected), ExprIsRead::Yes)
535            }
536        }
537    }
538
539    fn adjust_pat_info(&self, inner_mutability: Mutability, pat_info: PatInfo) -> PatInfo {
540        let mut binding_mode = match pat_info.binding_mode {
541            // If default binding mode is by value, make it `ref`, `ref mut`, `ref pin const`
542            // or `ref pin mut` (depending on whether we observe `&`, `&mut`, `&pin const` or
543            // `&pin mut`).
544            ByRef::No => ByRef::Yes(inner_mutability),
545            ByRef::Yes(mutability) => {
546                let mutability = match mutability {
547                    // When `ref mut`, stay a `ref mut` (on `&mut`) or downgrade to `ref` (on `&`).
548                    Mutability::Mut => inner_mutability,
549                    // Once a `ref`, always a `ref`.
550                    // This is because a `& &mut` cannot mutate the underlying value.
551                    Mutability::Not => Mutability::Not,
552                };
553                ByRef::Yes(mutability)
554            }
555        };
556
557        let PatInfo { mut max_ref_mutbl, .. } = pat_info;
558        if self.downgrade_mut_inside_shared() {
559            binding_mode = binding_mode.cap_ref_mutability(max_ref_mutbl.as_mutbl());
560        }
561        match binding_mode {
562            ByRef::Yes(Mutability::Not) => max_ref_mutbl = MutblCap::Not,
563            _ => {}
564        }
565        debug!("default binding mode is now {:?}", binding_mode);
566        PatInfo { binding_mode, max_ref_mutbl, ..pat_info }
567    }
568
569    fn check_deref_pattern(
570        &mut self,
571        pat: PatId,
572        opt_path_res: Option<Result<ResolvedPat<'db>, ()>>,
573        adjust_mode: AdjustMode,
574        expected: Ty<'db>,
575        mut inner_ty: Ty<'db>,
576        pat_adjust_kind: PatAdjust,
577        pat_info: PatInfo,
578    ) -> Ty<'db> {
579        debug_assert!(
580            !matches!(pat_adjust_kind, PatAdjust::BuiltinDeref),
581            "unexpected deref pattern for builtin reference type {expected:?}",
582        );
583
584        let pat_adjustments = self.result.pat_adjustments.entry(pat).or_default();
585        // We may reach the recursion limit if a user matches on a type `T` satisfying
586        // `T: Deref<Target = T>`; error gracefully in this case.
587        // FIXME(deref_patterns): If `deref_patterns` stabilizes, it may make sense to move
588        // this check out of this branch. Alternatively, this loop could be implemented with
589        // autoderef and this check removed. For now though, don't break code compiling on
590        // stable with lots of `&`s and a low recursion limit, if anyone's done that.
591        if pat_adjustments.len() < self.resolver.top_level_def_map().recursion_limit() as usize {
592            // Preserve the smart pointer type for THIR lowering and closure upvar analysis.
593            pat_adjustments.push(PatAdjustment { kind: pat_adjust_kind, source: expected.store() });
594        } else {
595            // FIXME: Emit an error.
596            inner_ty = self.types.types.error;
597        }
598
599        // Recurse, using the old pat info to keep `current_depth` to its old value.
600        // Peeling smart pointers does not update the default binding mode.
601        self.infer_pat_inner(pat, opt_path_res, adjust_mode, inner_ty, pat_info)
602    }
603
604    /// How should the binding mode and expected type be adjusted?
605    ///
606    /// When the pattern contains a path, `opt_path_res` must be `Some(path_res)`.
607    fn calc_adjust_mode(
608        &mut self,
609        pat_id: PatId,
610        pat: &Pat,
611        opt_path_res: Option<Result<ResolvedPat<'db>, ()>>,
612    ) -> AdjustMode {
613        match pat {
614            // Type checking these product-like types successfully always require
615            // that the expected type be of those types and not reference types.
616            Pat::Tuple { .. } | Pat::Range { .. } | Pat::Slice { .. } => AdjustMode::peel_all(),
617            // When checking an explicit deref pattern, only peel reference types.
618            // FIXME(deref_patterns): If box patterns and deref patterns need to coexist, box
619            // patterns may want `PeelKind::Implicit`, stopping on encountering a box.
620            Pat::Box { .. } | Pat::Deref { .. } => {
621                AdjustMode::Peel { kind: PeelKind::ExplicitDerefPat }
622            }
623            // A never pattern behaves somewhat like a literal or unit variant.
624            // Pat::Never => AdjustMode::peel_all(),
625            // For patterns with paths, how we peel the scrutinee depends on the path's resolution.
626            Pat::Record { .. }
627            | Pat::TupleStruct { .. }
628            | Pat::Path(_) => {
629                // If there was an error resolving the path, default to peeling everything.
630                opt_path_res.unwrap().map_or(AdjustMode::peel_all(), |pr| pr.adjust_mode())
631            }
632
633            // String and byte-string literals result in types `&str` and `&[u8]` respectively.
634            // All other literals result in non-reference types.
635            // As a result, we allow `if let 0 = &&0 {}` but not `if let "foo" = &&"foo" {}` unless
636            // `deref_patterns` is enabled.
637            &Pat::Lit(expr) | &Pat::ConstBlock(expr) => {
638                let lit_ty = self.infer_expr_pat_unadjusted(expr);
639                // Call `resolve_vars_if_possible` here for inline const blocks.
640                let lit_ty = self.infcx().resolve_vars_if_possible(lit_ty);
641                // If `deref_patterns` is enabled, allow `if let "foo" = &&"foo" {}`.
642                if self.features.deref_patterns {
643                    let mut peeled_ty = lit_ty;
644                    let mut pat_ref_layers = 0;
645                    while let TyKind::Ref(_, inner_ty, mutbl) =
646                        self.table.try_structurally_resolve_type(pat_id.into(), peeled_ty).kind()
647                    {
648                        // We rely on references at the head of constants being immutable.
649                        debug_assert!(mutbl.is_not());
650                        pat_ref_layers += 1;
651                        peeled_ty = inner_ty;
652                    }
653                    AdjustMode::Peel {
654                        kind: PeelKind::Implicit { until_adt: None, pat_ref_layers },
655                    }
656                } else {
657                    if lit_ty.is_ref() { AdjustMode::Pass } else { AdjustMode::peel_all() }
658                }
659            }
660
661            // Ref patterns are complicated, we handle them in `check_pat_ref`.
662            Pat::Ref { .. }
663            // No need to do anything on a missing pattern.
664            | Pat::Missing
665            // No need to do anything on a `NotNull` pattern, they are only allowed in type contexts.
666            | Pat::NotNull
667            // A `_`/`..` pattern works with any expected type, so there's no need to do anything.
668            | Pat::Wild | Pat::Rest
669            // Bindings also work with whatever the expected type is,
670            // and moreover if we peel references off, that will give us the wrong binding type.
671            // Also, we can have a subpattern `binding @ pat`.
672            // Each side of the `@` should be treated independently (like with OR-patterns).
673            | Pat::Bind { .. }
674            // `Pat::Expr(_)` inside assignments becomes a binding in rustc, therefore should be
675            // the same as `Pat::Bind`.
676            | Pat::Expr(_)
677            // An OR-pattern just propagates to each individual alternative.
678            // This is maximally flexible, allowing e.g., `Some(mut x) | &Some(mut x)`.
679            // In that example, `Some(mut x)` results in `Peel` whereas `&Some(mut x)` in `Reset`.
680            | Pat::Or(_)
681            // Like or-patterns, guard patterns just propagate to their subpatterns.
682            /* | Pat::Guard(..) */ => AdjustMode::Pass,
683        }
684    }
685
686    /// Assuming `expected` is a reference type, determine whether to peel it before matching.
687    fn should_peel_ref(&self, peel_kind: PeelKind, mut expected: Ty<'db>) -> bool {
688        debug_assert!(expected.is_ref());
689        let pat_ref_layers = match peel_kind {
690            PeelKind::ExplicitDerefPat => 0,
691            PeelKind::Implicit { pat_ref_layers, .. } => pat_ref_layers,
692        };
693
694        // Most patterns don't have reference types, so we'll want to peel all references from the
695        // scrutinee before matching. To optimize for the common case, return early.
696        if pat_ref_layers == 0 {
697            return true;
698        }
699        debug_assert!(
700            self.features.deref_patterns,
701            "Peeling for patterns with reference types is gated by `deref_patterns`."
702        );
703
704        // If the pattern has as many or more layers of reference as the expected type, we can match
705        // without peeling more, unless we find a smart pointer or `&mut` that we also need to peel.
706        // We don't treat `&` and `&mut` as interchangeable, but by peeling `&mut`s before matching,
707        // we can still, e.g., match on a `&mut str` with a string literal pattern. This is because
708        // string literal patterns may be used where `str` is expected.
709        let mut expected_ref_layers = 0;
710        while let TyKind::Ref(_, inner_ty, mutbl) = expected.kind() {
711            if mutbl.is_mut() {
712                // Mutable references can't be in the final value of constants, thus they can't be
713                // at the head of their types, thus we should always peel `&mut`.
714                return true;
715            }
716            expected_ref_layers += 1;
717            expected = inner_ty;
718        }
719        pat_ref_layers < expected_ref_layers || self.should_peel_smart_pointer(peel_kind, expected)
720    }
721
722    /// Determine whether `expected` is a smart pointer type that should be peeled before matching.
723    fn should_peel_smart_pointer(&self, peel_kind: PeelKind, expected: Ty<'db>) -> bool {
724        // Explicit `deref!(_)` patterns match against smart pointers; don't peel in that case.
725        if let PeelKind::Implicit { until_adt, .. } = peel_kind
726            // For simplicity, only apply overloaded derefs if `expected` is a known ADT.
727            // FIXME(deref_patterns): we'll get better diagnostics for users trying to
728            // implicitly deref generics if we allow them here, but primitives, tuples, and
729            // inference vars definitely should be stopped. Figure out what makes most sense.
730            && let TyKind::Adt(scrutinee_adt, _) = expected.kind()
731            // Don't peel if the pattern type already matches the scrutinee. E.g., stop here if
732            // matching on a `Cow<'a, T>` scrutinee with a `Cow::Owned(_)` pattern.
733            && until_adt != Some(scrutinee_adt.def_id())
734            // At this point, the pattern isn't able to match `expected` without peeling. Check
735            // that it implements `Deref` before assuming it's a smart pointer, to get a normal
736            // type error instead of a missing impl error if not. This only checks for `Deref`,
737            // not `DerefPure`: we require that too, but we want a trait error if it's missing.
738            && let Some(deref_trait) = self.lang_items.Deref
739            && self.infcx().type_implements_trait(deref_trait, [expected], self.table.param_env).may_apply()
740        {
741            true
742        } else {
743            false
744        }
745    }
746
747    fn infer_expr_pat_unadjusted(&mut self, expr: ExprId) -> Ty<'db> {
748        self.infer_expr_no_expect(expr, ExprIsRead::Yes)
749    }
750
751    fn infer_lit_pat(&mut self, expr: ExprId, expected: Ty<'db>) -> Ty<'db> {
752        let literal = match &self.store[expr] {
753            Expr::Literal(literal) => literal,
754            _ => panic!("expected a literal"),
755        };
756
757        // We've already computed the type above (when checking for a non-ref pat),
758        // so avoid computing it again.
759        let ty = self.expr_ty(expr);
760
761        // Byte string patterns behave the same way as array patterns
762        // They can denote both statically and dynamically-sized byte arrays.
763        // Additionally, when `deref_patterns` is enabled, byte string literal patterns may have
764        // types `[u8]` or `[u8; N]`, in order to type, e.g., `deref!(b"..."): Vec<u8>`.
765        let mut pat_ty = ty;
766        if matches!(literal, Literal::ByteString(_)) {
767            let expected = self.structurally_resolve_type(expr.into(), expected);
768            match expected.kind() {
769                // Allow `b"...": &[u8]`
770                TyKind::Ref(_, inner_ty, _)
771                    if self
772                        .table
773                        .try_structurally_resolve_type(expr.into(), inner_ty)
774                        .is_slice() =>
775                {
776                    trace!(?expr, "polymorphic byte string lit");
777                    pat_ty = self.types.types.static_u8_slice;
778                }
779                // Allow `b"...": [u8; 3]` for `deref_patterns`
780                TyKind::Array(..) if self.features.deref_patterns => {
781                    pat_ty = match ty.kind() {
782                        TyKind::Ref(_, inner_ty, _) => inner_ty,
783                        _ => panic!("found byte string literal with non-ref type {ty:?}"),
784                    }
785                }
786                // Allow `b"...": [u8]` for `deref_patterns`
787                TyKind::Slice(..) if self.features.deref_patterns => {
788                    pat_ty = self.types.types.u8_slice;
789                }
790                // Otherwise, `b"...": &[u8; 3]`
791                _ => {}
792            }
793        }
794
795        // When `deref_patterns` is enabled, in order to allow `deref!("..."): String`, we allow
796        // string literal patterns to have type `str`. This is accounted for when lowering to MIR.
797        if self.features.deref_patterns
798            && matches!(literal, Literal::String(_))
799            && self.table.try_structurally_resolve_type(expr.into(), expected).is_str()
800        {
801            pat_ty = self.types.types.str;
802        }
803
804        // Somewhat surprising: in this case, the subtyping relation goes the
805        // opposite way as the other cases. Actually what we really want is not
806        // a subtyping relation at all but rather that there exists a LUB
807        // (so that they can be compared). However, in practice, constants are
808        // always scalars or strings. For scalars subtyping is irrelevant,
809        // and for strings `ty` is type is `&'static str`, so if we say that
810        //
811        //     &'static str <: expected
812        //
813        // then that's equivalent to there existing a LUB.
814        _ = self.demand_suptype(expr.into(), expected, pat_ty);
815
816        pat_ty
817    }
818
819    fn infer_range_pat(
820        &mut self,
821        pat: PatId,
822        lhs_expr: Option<ExprId>,
823        rhs_expr: Option<ExprId>,
824        expected: Ty<'db>,
825    ) -> Ty<'db> {
826        let mut calc_side = |opt_expr: Option<ExprId>| match opt_expr {
827            None => None,
828            Some(expr) => {
829                let ty = self.infer_expr_pat_unadjusted(expr);
830                // Check that the end-point is possibly of numeric or char type.
831                // The early check here is not for correctness, but rather better
832                // diagnostics (e.g. when `&str` is being matched, `expected` will
833                // be peeled to `str` while ty here is still `&str`, if we don't
834                // err early here, a rather confusing unification error will be
835                // emitted instead).
836                let ty = self.table.try_structurally_resolve_type(expr.into(), ty);
837                let fail =
838                    !(ty.is_numeric() || ty.is_char() || ty.is_ty_var() || ty.references_error());
839                Some((fail, ty, expr))
840            }
841        };
842        let mut lhs = calc_side(lhs_expr);
843        let mut rhs = calc_side(rhs_expr);
844
845        if let (Some((true, ..)), _) | (_, Some((true, ..))) = (lhs, rhs) {
846            // There exists a side that didn't meet our criteria that the end-point
847            // be of a numeric or char type, as checked in `calc_side` above.
848            self.push_diagnostic(InferenceDiagnostic::InvalidRangePatType { pat });
849            return self.types.types.error;
850        }
851
852        // Unify each side with `expected`.
853        // Subtyping doesn't matter here, as the value is some kind of scalar.
854        let mut demand_eqtype = |x: &mut _| {
855            if let Some((_, x_ty, x_expr)) = *x {
856                _ = self.demand_eqtype(ExprOrPatIdPacked::from(x_expr), expected, x_ty);
857            }
858        };
859        demand_eqtype(&mut lhs);
860        demand_eqtype(&mut rhs);
861
862        if let (Some((true, ..)), _) | (_, Some((true, ..))) = (lhs, rhs) {
863            return self.types.types.error;
864        }
865
866        // Find the unified type and check if it's of numeric or char type again.
867        // This check is needed if both sides are inference variables.
868        // We require types to be resolved here so that we emit inference failure
869        // rather than "_ is not a char or numeric".
870        let ty = self.structurally_resolve_type(
871            lhs_expr.or(rhs_expr).map(ExprOrPatIdPacked::from).unwrap_or(pat.into()),
872            expected,
873        );
874        if !(ty.is_numeric() || ty.is_char() || ty.references_error()) {
875            // FIXME: Emit an error.
876            return self.types.types.error;
877        }
878        ty
879    }
880
881    fn infer_bind_pat(
882        &mut self,
883        pat: PatId,
884        var_id: BindingId,
885        sub: Option<PatId>,
886        expected: Ty<'db>,
887        pat_info: PatInfo,
888    ) -> Ty<'db> {
889        let PatInfo { binding_mode: def_br, .. } = pat_info;
890        let binding_data = &self.store[var_id];
891
892        // Determine the binding mode...
893        let user_bind_annot = BindingMode::from_annotation(binding_data.mode);
894        let bm = match user_bind_annot {
895            BindingMode(ByRef::No, Mutability::Mut) if let ByRef::Yes(_) = def_br => {
896                // Only mention the experimental `mut_ref` feature if we're in edition 2024 and
897                // using other experimental matching features compatible with it.
898                if self.edition.at_least_2024()
899                    && (self.features.ref_pat_eat_one_layer_2024
900                        || self.features.ref_pat_eat_one_layer_2024_structural)
901                {
902                    if !self.features.mut_ref {
903                        self.push_diagnostic(InferenceDiagnostic::MutableRefBinding { pat });
904                    }
905
906                    BindingMode(def_br, Mutability::Mut)
907                } else {
908                    // `mut` resets the binding mode on edition <= 2021
909                    BindingMode(ByRef::No, Mutability::Mut)
910                }
911            }
912            BindingMode(ByRef::No, mutbl) => BindingMode(def_br, mutbl),
913            BindingMode(ByRef::Yes(_), _) => user_bind_annot,
914        };
915
916        if matches!(bm.0, ByRef::Yes(Mutability::Mut))
917            && let MutblCap::WeaklyNot = pat_info.max_ref_mutbl
918        {
919            self.push_diagnostic(InferenceDiagnostic::MutRefInImmRefPat { pat });
920        }
921
922        // ...and store it in a side table:
923        self.result.binding_modes.insert(pat, bm);
924
925        debug!("check_pat_ident: pat.hir_id={:?} bm={:?}", pat, bm);
926
927        let local_ty = match bm.0 {
928            ByRef::Yes(mutbl) => {
929                // If the binding is like `ref x | ref mut x`,
930                // then `x` is assigned a value of type `&M T` where M is the
931                // mutability and T is the expected type.
932                //
933                // Under pin ergonomics, if the binding is like `ref pin const|mut x`,
934                // then `x` is assigned a value of type `&pin M T` where M is the
935                // mutability and T is the expected type.
936                //
937                // `x` is assigned a value of type `&M T`, hence `&M T <: typeof(x)`
938                // is required. However, we use equality, which is stronger.
939                // See (note_1) for an explanation.
940                self.new_ref_ty(pat.into(), mutbl, expected)
941            }
942            // Otherwise, the type of x is the expected type `T`.
943            ByRef::No => expected, // As above, `T <: typeof(x)` is required, but we use equality, see (note_1).
944        };
945
946        // We have a concrete type for the local, so we do not need to taint it and hide follow up errors *using* the local.
947        if let Some(existing_local_ty) = self.result.type_of_binding.get(var_id) {
948            // If there are multiple arms, make sure they all agree on
949            // what the type of the binding `x` ought to be.
950            _ = self.demand_eqtype(pat.into(), existing_local_ty.as_ref(), local_ty);
951        } else {
952            self.write_binding_ty(var_id, local_ty);
953        }
954
955        if let Some(p) = sub {
956            self.infer_pat(p, expected, pat_info);
957        }
958
959        local_ty
960    }
961
962    fn check_dereferenceable(
963        &mut self,
964        expected: Ty<'db>,
965        pat: PatId,
966        inner: PatId,
967    ) -> Result<(), ()> {
968        if let Pat::Bind { .. } = self.store[inner]
969            && let Some(pointee_ty) = self.shallow_resolve(expected).builtin_deref(true)
970            && let TyKind::Dynamic(..) = pointee_ty.kind()
971        {
972            // This is "x = dyn SomeTrait" being reduced from
973            // "let &x = &dyn SomeTrait" or "let box x = Box<dyn SomeTrait>", an error.
974            self.push_diagnostic(InferenceDiagnostic::CannotImplicitlyDerefTraitObject {
975                pat,
976                found: expected.store(),
977            });
978            return Err(());
979        }
980        Ok(())
981    }
982
983    fn resolve_record_pat(&mut self, pat: PatId, path: &Path) -> Result<ResolvedPat<'db>, ()> {
984        // Resolve the path and check the definition for errors.
985        let (pat_ty, Some(variant)) = self.resolve_variant(pat.into(), path, false) else {
986            return Err(());
987        };
988        self.write_variant_resolution(pat.into(), variant);
989        Ok(ResolvedPat { ty: pat_ty, kind: ResolvedPatKind::Struct { variant } })
990    }
991
992    fn infer_record_pat(
993        &mut self,
994        pat: PatId,
995        fields: &[RecordFieldPat],
996        has_rest_pat: bool,
997        pat_ty: Ty<'db>,
998        variant: VariantId,
999        expected: Ty<'db>,
1000        pat_info: PatInfo,
1001    ) -> Ty<'db> {
1002        // Type-check the path.
1003        let _ = self.demand_eqtype(pat.into(), expected, pat_ty);
1004
1005        // Type-check subpatterns.
1006        self.check_record_pat_fields(pat_ty, pat, variant, fields, has_rest_pat, pat_info);
1007        pat_ty
1008    }
1009
1010    fn resolve_pat_path(&mut self, pat: PatId, path: &Path) -> Result<ResolvedPat<'db>, ()> {
1011        let (res, pat_ty) = self.infer_path(path, pat.into()).ok_or(())?;
1012        match res {
1013            ValueNs::FunctionId(_)
1014            | ValueNs::GenericParam(_)
1015            | ValueNs::ImplSelf(_)
1016            | ValueNs::LocalBinding(_)
1017            | ValueNs::StaticId(_) => {
1018                // FIXME: Emit an error.
1019                return Err(());
1020            }
1021            ValueNs::ConstId(_) | ValueNs::EnumVariantId(_) | ValueNs::StructId(_) => {} // OK
1022        }
1023
1024        Ok(ResolvedPat { ty: pat_ty, kind: ResolvedPatKind::Path { res } })
1025    }
1026
1027    fn infer_pat_path(
1028        &mut self,
1029        pat: PatId,
1030        resolved: &ResolvedPat<'db>,
1031        expected: Ty<'db>,
1032    ) -> Ty<'db> {
1033        _ = self.demand_suptype(pat.into(), expected, resolved.ty);
1034        resolved.ty
1035    }
1036
1037    fn resolve_tuple_struct_pat(
1038        &mut self,
1039        pat: PatId,
1040        path: &Path,
1041    ) -> Result<ResolvedPat<'db>, ()> {
1042        // Resolve the path and check the definition for errors.
1043        let (pat_ty, Some(variant)) = self.resolve_variant(pat.into(), path, true) else {
1044            return Err(());
1045        };
1046        self.write_variant_resolution(pat.into(), variant);
1047        Ok(ResolvedPat { ty: pat_ty, kind: ResolvedPatKind::TupleStruct { variant } })
1048    }
1049
1050    fn infer_tuple_struct_pat(
1051        &mut self,
1052        pat: PatId,
1053        subpats: &[PatId],
1054        ddpos: Option<u32>,
1055        pat_ty: Ty<'db>,
1056        variant: VariantId,
1057        expected: Ty<'db>,
1058        pat_info: PatInfo,
1059    ) -> Ty<'db> {
1060        let interner = self.interner();
1061
1062        // Type-check the tuple struct pattern against the expected type.
1063        let had_err = self.demand_eqtype(pat.into(), expected, pat_ty);
1064
1065        let variant_fields = variant.fields(self.db);
1066        let variant_field_tys = self.db.field_types(variant);
1067        let TyKind::Adt(_, args) = pat_ty.kind() else {
1068            panic!("unexpected pattern type {:?}", pat_ty);
1069        };
1070        // Type-check subpatterns.
1071        if subpats.len() == variant_fields.len()
1072            || subpats.len() < variant_fields.len() && ddpos.is_some()
1073        {
1074            for (i, &subpat) in subpats.iter().enumerate_and_adjust(variant_fields.len(), ddpos) {
1075                let field_id = LocalFieldId::from_raw(la_arena::RawIdx::from_u32(i as u32));
1076                let field_ty =
1077                    variant_field_tys[field_id].ty().instantiate(interner, args).skip_norm_wip();
1078                self.infer_pat(subpat, field_ty, pat_info);
1079            }
1080            if let Err(()) = had_err {
1081                for &pat in subpats {
1082                    self.infer_pat(pat, self.types.types.error, pat_info);
1083                }
1084                return self.types.types.error;
1085            }
1086        } else {
1087            self.push_diagnostic(InferenceDiagnostic::MismatchedTupleStructPatArgCount {
1088                pat,
1089                expected: variant_fields.len(),
1090                found: subpats.len(),
1091            });
1092
1093            for (i, &pat) in subpats.iter().enumerate() {
1094                let field_id = LocalFieldId::from_raw(la_arena::RawIdx::from_u32(i as u32));
1095                let expected = match variant_field_tys.get(field_id) {
1096                    Some(field_ty) => field_ty.ty().instantiate(interner, args).skip_norm_wip(),
1097                    None => self.types.types.error,
1098                };
1099                self.infer_pat(pat, expected, pat_info);
1100            }
1101        }
1102        pat_ty
1103    }
1104
1105    fn infer_tuple_pat(
1106        &mut self,
1107        pat: PatId,
1108        elements: &[PatId],
1109        ddpos: Option<u32>,
1110        expected: Ty<'db>,
1111        pat_info: PatInfo,
1112    ) -> Ty<'db> {
1113        let interner = self.interner();
1114        let mut expected_len = elements.len();
1115        if ddpos.is_some() {
1116            // Require known type only when `..` is present.
1117            if let TyKind::Tuple(tys) = self.structurally_resolve_type(pat.into(), expected).kind()
1118            {
1119                expected_len = tys.len();
1120            }
1121        }
1122        let max_len = cmp::max(expected_len, elements.len());
1123
1124        let element_tys_iter = (0..max_len).map(|i| {
1125            self.table.next_ty_var(elements.get(i).copied().map(Span::PatId).unwrap_or(Span::Dummy))
1126        });
1127        let element_tys = Tys::new_from_iter(interner, element_tys_iter);
1128        let pat_ty = Ty::new(interner, TyKind::Tuple(element_tys));
1129        if self.demand_eqtype(pat.into(), expected, pat_ty).is_err() {
1130            let expected = if let TyKind::Tuple(tys) =
1131                self.table.try_structurally_resolve_type(Span::Dummy, expected).kind()
1132            {
1133                for (expected_var, found) in iter::zip(element_tys, tys) {
1134                    // Constrain the infer var so that the type mismatch error message, which contains it,
1135                    // will be better.
1136                    _ = self.demand_eqtype(pat.into(), expected_var, found);
1137                }
1138                tys
1139            } else {
1140                self.types.empty.tys
1141            };
1142            let expected = expected.iter().chain(iter::repeat(self.types.types.error));
1143            Ty::new_tup_from_iter(
1144                interner,
1145                iter::zip(expected, elements).map(|(expected, &elem)| {
1146                    self.infer_pat(elem, expected, pat_info);
1147                    self.result.type_of_pat_with_adjust(elem)
1148                }),
1149            )
1150        } else {
1151            for (i, &elem) in elements.iter().enumerate_and_adjust(max_len, ddpos) {
1152                self.infer_pat(elem, element_tys[i], pat_info);
1153            }
1154            pat_ty
1155        }
1156    }
1157
1158    fn check_record_pat_fields(
1159        &mut self,
1160        adt_ty: Ty<'db>,
1161        pat: PatId,
1162        variant: VariantId,
1163        fields: &[RecordFieldPat],
1164        has_rest_pat: bool,
1165        pat_info: PatInfo,
1166    ) {
1167        let interner = self.interner();
1168
1169        let TyKind::Adt(_, args) = adt_ty.kind() else {
1170            panic!("struct pattern is not an ADT");
1171        };
1172
1173        // Index the struct fields' types.
1174        let variant_fields = variant.fields(self.db);
1175        let field_map = variant_fields
1176            .fields()
1177            .iter()
1178            .map(|(i, field)| (field.name.clone(), i))
1179            .collect::<FxHashMap<_, _>>();
1180        let variant_field_tys = self.db.field_types(variant);
1181        let variant_fields_vis = VariantFields::field_visibilities(self.db, variant);
1182
1183        // Keep track of which fields have already appeared in the pattern.
1184        let mut used_fields = FxHashMap::default();
1185
1186        let mut inexistent_fields = vec![];
1187        // Typecheck each field.
1188        for (field_idx, field) in fields.iter().enumerate() {
1189            match used_fields.entry(field.name.clone()) {
1190                Occupied(_occupied) => {
1191                    self.push_diagnostic(InferenceDiagnostic::DuplicateField {
1192                        field: field.pat.into(),
1193                        variant,
1194                    });
1195                }
1196                Vacant(vacant) => {
1197                    vacant.insert(field_idx);
1198                }
1199            };
1200            let field_idx = field_map.get(&field.name).copied();
1201            let field_ty = match field_idx {
1202                Some(field_idx) => {
1203                    if !self.resolver.is_visible(self.db, variant_fields_vis[field_idx]) {
1204                        self.push_diagnostic(InferenceDiagnostic::NoSuchField {
1205                            field: field.pat.into(),
1206                            private: Some(field_idx),
1207                            variant,
1208                        });
1209                    }
1210
1211                    variant_field_tys[field_idx].ty().instantiate(interner, args).skip_norm_wip()
1212                }
1213                None => {
1214                    inexistent_fields.push(field);
1215                    self.types.types.error
1216                }
1217            };
1218
1219            self.infer_pat(field.pat, field_ty, pat_info);
1220        }
1221
1222        let unmentioned_fields = variant_fields
1223            .fields()
1224            .iter()
1225            .filter(|(_, field)| !used_fields.contains_key(&field.name))
1226            .collect::<Vec<_>>();
1227
1228        for inexistent_field in inexistent_fields {
1229            self.push_diagnostic(InferenceDiagnostic::NoSuchField {
1230                field: inexistent_field.pat.into(),
1231                private: None,
1232                variant,
1233            });
1234        }
1235
1236        // Require `..` if struct has non_exhaustive attribute.
1237        let non_exhaustive = self.has_applicable_non_exhaustive(variant.into());
1238        if non_exhaustive && !has_rest_pat {
1239            self.push_diagnostic(InferenceDiagnostic::NonExhaustiveRecordPat { pat, variant });
1240        }
1241
1242        // Report an error if an incorrect number of fields was specified.
1243        if matches!(variant, VariantId::UnionId(_)) {
1244            if fields.len() != 1 {
1245                self.push_diagnostic(InferenceDiagnostic::UnionPatMustHaveExactlyOneField { pat });
1246            }
1247            if has_rest_pat {
1248                self.push_diagnostic(InferenceDiagnostic::UnionPatHasRest { pat });
1249            }
1250        } else if !unmentioned_fields.is_empty() && !has_rest_pat {
1251            self.push_diagnostic(InferenceDiagnostic::RecordMissingFields {
1252                record: ExprOrPatId::PatId(pat),
1253                variant,
1254                missed_fields: unmentioned_fields.into_iter().map(|f| f.0).collect(),
1255            })
1256        }
1257    }
1258
1259    fn infer_box_pat(
1260        &mut self,
1261        pat: PatId,
1262        inner: PatId,
1263        expected: Ty<'db>,
1264        pat_info: PatInfo,
1265    ) -> Ty<'db> {
1266        let interner = self.interner();
1267        let (box_ty, inner_ty) = self
1268            .check_dereferenceable(expected, pat, inner)
1269            .map(|()| {
1270                // Here, `demand::subtype` is good enough, but I don't
1271                // think any errors can be introduced by using `demand::eqtype`.
1272                let inner_ty = self.table.next_ty_var(inner.into());
1273                let box_ty = Ty::new_box(interner, inner_ty);
1274                _ = self.demand_eqtype(pat.into(), expected, box_ty);
1275                (box_ty, inner_ty)
1276            })
1277            .unwrap_or_else(|()| {
1278                let err = self.types.types.error;
1279                (err, err)
1280            });
1281        self.infer_pat(inner, inner_ty, pat_info);
1282        box_ty
1283    }
1284
1285    fn infer_deref_pat(
1286        &mut self,
1287        pat: PatId,
1288        inner: PatId,
1289        expected: Ty<'db>,
1290        pat_info: PatInfo,
1291    ) -> Ty<'db> {
1292        let target_ty = self.deref_pat_target(pat, expected);
1293        self.infer_pat(inner, target_ty, pat_info);
1294        let infer_ok = self.register_deref_mut_bounds_if_needed(pat, inner, [expected]);
1295        self.table.register_infer_ok(infer_ok);
1296        expected
1297    }
1298
1299    fn deref_pat_target(&mut self, pat: PatId, source_ty: Ty<'db>) -> Ty<'db> {
1300        let (Some(deref_pure), Some(deref_target)) =
1301            (self.lang_items.DerefPure, self.lang_items.DerefTarget)
1302        else {
1303            return self.types.types.error;
1304        };
1305        // Register a `DerefPure` bound, which is required by all `deref!()` pats.
1306        let interner = self.interner();
1307        self.table.register_bound(source_ty, deref_pure, ObligationCause::new(pat));
1308        // The expected type for the deref pat's inner pattern is `<expected as Deref>::Target`.
1309        let target_ty = Ty::new_projection(interner, deref_target.into(), [source_ty]);
1310        self.table.try_structurally_resolve_type(pat.into(), target_ty)
1311    }
1312
1313    /// Check if the interior of a deref pattern (either explicit or implicit) has any `ref mut`
1314    /// bindings, which would require `DerefMut` to be emitted in MIR building instead of just
1315    /// `Deref`. We do this *after* checking the inner pattern, since we want to make sure to
1316    /// account for `ref mut` binding modes inherited from implicitly dereferencing `&mut` refs.
1317    fn register_deref_mut_bounds_if_needed(
1318        &self,
1319        pat: PatId,
1320        inner: PatId,
1321        derefed_tys: impl IntoIterator<Item = Ty<'db>>,
1322    ) -> InferOk<'db, ()> {
1323        let mut infer_ok = InferOk { value: (), obligations: Vec::new() };
1324        if self.pat_has_ref_mut_binding(inner) {
1325            let Some(deref_mut) = self.lang_items.DerefMut else { return infer_ok };
1326            let interner = self.interner();
1327            for mutably_derefed_ty in derefed_tys {
1328                infer_ok.obligations.push(Obligation::new(
1329                    interner,
1330                    ObligationCause::new(pat),
1331                    self.table.param_env,
1332                    TraitRef::new(interner, deref_mut.into(), [mutably_derefed_ty]),
1333                ));
1334            }
1335        }
1336        infer_ok
1337    }
1338
1339    /// Does the pattern recursively contain a `ref mut` binding in it?
1340    ///
1341    /// This is used to determined whether a `deref` pattern should emit a `Deref`
1342    /// or `DerefMut` call for its pattern scrutinee.
1343    ///
1344    /// This is computed from the typeck results since we want to make
1345    /// sure to apply any match-ergonomics adjustments, which we cannot
1346    /// determine from the HIR alone.
1347    pub(super) fn pat_has_ref_mut_binding(&self, pat: PatId) -> bool {
1348        let mut has_ref_mut = false;
1349        self.store.walk_pats(pat, &mut |pat| {
1350            if let Some(BindingMode(ByRef::Yes(Mutability::Mut), _)) =
1351                self.result.binding_modes.get(pat)
1352            {
1353                has_ref_mut = true;
1354            }
1355        });
1356        has_ref_mut
1357    }
1358
1359    // Precondition: Pat is Ref(inner)
1360    fn infer_ref_pat(
1361        &mut self,
1362        pat: PatId,
1363        inner: PatId,
1364        pat_mutbl: Mutability,
1365        mut expected: Ty<'db>,
1366        mut pat_info: PatInfo,
1367    ) -> Ty<'db> {
1368        let ref_pat_matches_mut_ref = self.ref_pat_matches_mut_ref();
1369        if ref_pat_matches_mut_ref && pat_mutbl == Mutability::Not {
1370            // If `&` patterns can match against mutable reference types (RFC 3627, Rule 5), we need
1371            // to prevent subpatterns from binding with `ref mut`. Subpatterns of a shared reference
1372            // pattern should have read-only access to the scrutinee, and the borrow checker won't
1373            // catch it in this case.
1374            pat_info.max_ref_mutbl = pat_info.max_ref_mutbl.cap_to_weakly_not();
1375        }
1376
1377        expected = self.table.try_structurally_resolve_type(pat.into(), expected);
1378        // Determine whether we're consuming an inherited reference and resetting the default
1379        // binding mode, based on edition and enabled experimental features.
1380        if let ByRef::Yes(inh_mut) = pat_info.binding_mode {
1381            match self.ref_pat_matches_inherited_ref(self.edition) {
1382                InheritedRefMatchRule::EatOuter => {
1383                    // ref pattern attempts to consume inherited reference
1384                    if pat_mutbl > inh_mut {
1385                        // Tried to match inherited `ref` with `&mut`
1386                        // NB: This assumes that `&` patterns can match against mutable references
1387                        // (RFC 3627, Rule 5). If we implement a pattern typing ruleset with Rule 4E
1388                        // but not Rule 5, we'll need to check that here.
1389                        debug_assert!(ref_pat_matches_mut_ref);
1390                        // FIXME: Emit an error.
1391                    }
1392
1393                    pat_info.binding_mode = ByRef::No;
1394                    self.result.skipped_ref_pats.insert(pat);
1395                    self.infer_pat(inner, expected, pat_info);
1396                    return expected;
1397                }
1398                InheritedRefMatchRule::EatInner => {
1399                    if let TyKind::Ref(_, _, r_mutbl) = expected.kind()
1400                        && pat_mutbl <= r_mutbl
1401                    {
1402                        // Match against the reference type; don't consume the inherited ref.
1403                        // NB: The check for compatible pattern and ref type mutability assumes that
1404                        // `&` patterns can match against mutable references (RFC 3627, Rule 5). If
1405                        // we implement a pattern typing ruleset with Rule 4 (including the fallback
1406                        // to matching the inherited ref when the inner ref can't match) but not
1407                        // Rule 5, we'll need to check that here.
1408                        debug_assert!(ref_pat_matches_mut_ref);
1409                        // NB: For RFC 3627's Rule 3, we limit the default binding mode's ref
1410                        // mutability to `pat_info.max_ref_mutbl`. If we implement a pattern typing
1411                        // ruleset with Rule 4 but not Rule 3, we'll need to check that here.
1412                        debug_assert!(self.downgrade_mut_inside_shared());
1413                        let mutbl_cap = cmp::min(r_mutbl, pat_info.max_ref_mutbl.as_mutbl());
1414                        pat_info.binding_mode = pat_info.binding_mode.cap_ref_mutability(mutbl_cap);
1415                    } else {
1416                        // The reference pattern can't match against the expected type, so try
1417                        // matching against the inherited ref instead.
1418                        if pat_mutbl > inh_mut {
1419                            // We can't match an inherited shared reference with `&mut`.
1420                            // NB: This assumes that `&` patterns can match against mutable
1421                            // references (RFC 3627, Rule 5). If we implement a pattern typing
1422                            // ruleset with Rule 4 but not Rule 5, we'll need to check that here.
1423                            // FIXME(ref_pat_eat_one_layer_2024_structural): If we already tried
1424                            // matching the real reference, the error message should explain that
1425                            // falling back to the inherited reference didn't work. This should be
1426                            // the same error as the old-Edition version below.
1427                            debug_assert!(ref_pat_matches_mut_ref);
1428                            // FIXME: Emit an error.
1429                        }
1430
1431                        pat_info.binding_mode = ByRef::No;
1432                        self.result.skipped_ref_pats.insert(pat);
1433                        self.infer_pat(inner, expected, pat_info);
1434                        return expected;
1435                    }
1436                }
1437                InheritedRefMatchRule::EatBoth { consider_inherited_ref: true } => {
1438                    // Reset binding mode on old editions
1439                    pat_info.binding_mode = ByRef::No;
1440
1441                    if let TyKind::Ref(_, inner_ty, _) = expected.kind() {
1442                        // Consume both the inherited and inner references.
1443                        if pat_mutbl.is_mut() && inh_mut.is_mut() {
1444                            // As a special case, a `&mut` reference pattern will be able to match
1445                            // against a reference type of any mutability if the inherited ref is
1446                            // mutable. Since this allows us to match against a shared reference
1447                            // type, we refer to this as "falling back" to matching the inherited
1448                            // reference, though we consume the real reference as well. We handle
1449                            // this here to avoid adding this case to the common logic below.
1450                            self.infer_pat(inner, inner_ty, pat_info);
1451                            return expected;
1452                        } else {
1453                            // Otherwise, use the common logic below for matching the inner
1454                            // reference type.
1455                            // FIXME(ref_pat_eat_one_layer_2024_structural): If this results in a
1456                            // mutability mismatch, the error message should explain that falling
1457                            // back to the inherited reference didn't work. This should be the same
1458                            // error as the Edition 2024 version above.
1459                        }
1460                    } else {
1461                        // The expected type isn't a reference type, so only match against the
1462                        // inherited reference.
1463                        if pat_mutbl > inh_mut {
1464                            // We can't match a lone inherited shared reference with `&mut`.
1465                            // FIXME: Emit an error.
1466                        }
1467
1468                        self.result.skipped_ref_pats.insert(pat);
1469                        self.infer_pat(inner, expected, pat_info);
1470                        return expected;
1471                    }
1472                }
1473                InheritedRefMatchRule::EatBoth { consider_inherited_ref: false } => {
1474                    // Reset binding mode on stable Rust. This will be a type error below if
1475                    // `expected` is not a reference type.
1476                    pat_info.binding_mode = ByRef::No;
1477                }
1478            }
1479        }
1480
1481        let (ref_ty, inner_ty) = match self.check_dereferenceable(expected, pat, inner) {
1482            Ok(()) => {
1483                // `demand::subtype` would be good enough, but using `eqtype` turns
1484                // out to be equally general. See (note_1) for details.
1485
1486                // Take region, inner-type from expected type if we can,
1487                // to avoid creating needless variables. This also helps with
1488                // the bad interactions of the given hack detailed in (note_1).
1489                debug!("check_pat_ref: expected={:?}", expected);
1490                match expected.as_reference() {
1491                    Some((r_ty, _, r_mutbl))
1492                        if ((ref_pat_matches_mut_ref && r_mutbl >= pat_mutbl)
1493                            || r_mutbl == pat_mutbl) =>
1494                    {
1495                        if r_mutbl == Mutability::Not {
1496                            pat_info.max_ref_mutbl = MutblCap::Not;
1497                        }
1498
1499                        (expected, r_ty)
1500                    }
1501                    _ => {
1502                        let inner_ty = self.table.next_ty_var(inner.into());
1503                        let ref_ty = self.new_ref_ty(inner.into(), pat_mutbl, inner_ty);
1504                        debug!("check_pat_ref: demanding {:?} = {:?}", expected, ref_ty);
1505                        _ = self.demand_eqtype(pat.into(), expected, ref_ty);
1506
1507                        (ref_ty, inner_ty)
1508                    }
1509                }
1510            }
1511            Err(()) => {
1512                let err = self.types.types.error;
1513                (err, err)
1514            }
1515        };
1516
1517        self.infer_pat(inner, inner_ty, pat_info);
1518        ref_ty
1519    }
1520
1521    /// Create a reference or pinned reference type with a fresh region variable.
1522    fn new_ref_ty(&self, span: Span, mutbl: Mutability, ty: Ty<'db>) -> Ty<'db> {
1523        let region = self.table.next_region_var(span);
1524        Ty::new_ref(self.interner(), region, ty, mutbl)
1525    }
1526
1527    fn try_resolve_slice_ty_to_array_ty(
1528        &self,
1529        before: &[PatId],
1530        slice: Option<PatId>,
1531        pat: PatId,
1532    ) -> Option<Ty<'db>> {
1533        if slice.is_some() {
1534            return None;
1535        }
1536
1537        let interner = self.interner();
1538        let len = before.len();
1539        let inner_ty = self.table.next_ty_var(pat.into());
1540
1541        Some(Ty::new_array(interner, inner_ty, len.try_into().unwrap()))
1542    }
1543
1544    /// Used to determines whether we can infer the expected type in the slice pattern to be of type array.
1545    /// This is only possible if we're in an irrefutable pattern. If we were to allow this in refutable
1546    /// patterns we wouldn't e.g. report ambiguity in the following situation:
1547    ///
1548    /// ```ignore(rust)
1549    /// struct Zeroes;
1550    ///    const ARR: [usize; 2] = [0; 2];
1551    ///    const ARR2: [usize; 2] = [2; 2];
1552    ///
1553    ///    impl Into<&'static [usize; 2]> for Zeroes {
1554    ///        fn into(self) -> &'static [usize; 2] {
1555    ///            &ARR
1556    ///        }
1557    ///    }
1558    ///
1559    ///    impl Into<&'static [usize]> for Zeroes {
1560    ///        fn into(self) -> &'static [usize] {
1561    ///            &ARR2
1562    ///        }
1563    ///    }
1564    ///
1565    ///    fn main() {
1566    ///        let &[a, b]: &[usize] = Zeroes.into() else {
1567    ///           ..
1568    ///        };
1569    ///    }
1570    /// ```
1571    ///
1572    /// If we're in an irrefutable pattern we prefer the array impl candidate given that
1573    /// the slice impl candidate would be rejected anyway (if no ambiguity existed).
1574    fn pat_is_irrefutable(&self, pat_origin: PatOrigin) -> bool {
1575        match pat_origin {
1576            PatOrigin::LetExpr | PatOrigin::MatchArm => false,
1577            PatOrigin::LetStmt { has_else } => !has_else,
1578            PatOrigin::DestructuringAssignment | PatOrigin::Param => true,
1579        }
1580    }
1581
1582    /// Type check a slice pattern.
1583    ///
1584    /// Syntactically, these look like `[pat_0, ..., pat_n]`.
1585    /// Semantically, we are type checking a pattern with structure:
1586    /// ```ignore (not-rust)
1587    /// [before_0, ..., before_n, (slice, after_0, ... after_n)?]
1588    /// ```
1589    /// The type of `slice`, if it is present, depends on the `expected` type.
1590    /// If `slice` is missing, then so is `after_i`.
1591    /// If `slice` is present, it can still represent 0 elements.
1592    fn infer_slice_pat(
1593        &mut self,
1594        pat: PatId,
1595        before: &[PatId],
1596        slice: Option<PatId>,
1597        after: &[PatId],
1598        expected: Ty<'db>,
1599        pat_info: PatInfo,
1600    ) -> Ty<'db> {
1601        let expected = self.table.try_structurally_resolve_type(pat.into(), expected);
1602
1603        // If the pattern is irrefutable and `expected` is an infer ty, we try to equate it
1604        // to an array if the given pattern allows it. See issue #76342
1605        if self.pat_is_irrefutable(pat_info.pat_origin)
1606            && expected.is_ty_var()
1607            && let Some(resolved_arr_ty) = self.try_resolve_slice_ty_to_array_ty(before, slice, pat)
1608        {
1609            debug!(?resolved_arr_ty);
1610            let _ = self.demand_eqtype(pat.into(), expected, resolved_arr_ty);
1611        }
1612
1613        let expected = self.structurally_resolve_type(pat.into(), expected);
1614        debug!(?expected);
1615
1616        let (element_ty, opt_slice_ty, inferred) = match expected.kind() {
1617            // An array, so we might have something like `let [a, b, c] = [0, 1, 2];`.
1618            TyKind::Array(element_ty, len) => {
1619                let min = before.len() as u64 + after.len() as u64;
1620                let (opt_slice_ty, expected) =
1621                    self.check_array_pat_len(pat, element_ty, expected, slice, len, min.into());
1622                // `opt_slice_ty.is_none()` => `slice.is_none()`.
1623                // Note, though, that opt_slice_ty could be `Some(error_ty)`.
1624                assert!(opt_slice_ty.is_some() || slice.is_none());
1625                (element_ty, opt_slice_ty, expected)
1626            }
1627            TyKind::Slice(element_ty) => (element_ty, Some(expected), expected),
1628            // The expected type must be an array or slice, but was neither, so error.
1629            _ => {
1630                self.push_diagnostic(InferenceDiagnostic::ExpectedArrayOrSlicePat {
1631                    pat,
1632                    found: expected.store(),
1633                });
1634                let err = self.types.types.error;
1635                (err, Some(err), err)
1636            }
1637        };
1638
1639        // Type check all the patterns before `slice`.
1640        for &elt in before {
1641            self.infer_pat(elt, element_ty, pat_info);
1642        }
1643        // Type check the `slice`, if present, against its expected type.
1644        if let Some(slice) = slice {
1645            self.infer_pat(slice, opt_slice_ty.unwrap(), pat_info);
1646        }
1647        // Type check the elements after `slice`, if present.
1648        for &elt in after {
1649            self.infer_pat(elt, element_ty, pat_info);
1650        }
1651        inferred
1652    }
1653
1654    /// Type check the length of an array pattern.
1655    ///
1656    /// Returns both the type of the variable length pattern (or `None`), and the potentially
1657    /// inferred array type. We only return `None` for the slice type if `slice.is_none()`.
1658    fn check_array_pat_len(
1659        &mut self,
1660        pat: PatId,
1661        element_ty: Ty<'db>,
1662        arr_ty: Ty<'db>,
1663        slice: Option<PatId>,
1664        len: Const<'db>,
1665        min_len: u128,
1666    ) -> (Option<Ty<'db>>, Ty<'db>) {
1667        let len = crate::consteval::try_const_usize(self.db, len);
1668
1669        if let Some(len) = len {
1670            // Now we know the length...
1671            if slice.is_none() {
1672                // ...and since there is no variable-length pattern,
1673                // we require an exact match between the number of elements
1674                // in the array pattern and as provided by the matched type.
1675                if min_len == len {
1676                    return (None, arr_ty);
1677                }
1678
1679                self.push_diagnostic(InferenceDiagnostic::MismatchedArrayPatLen {
1680                    pat,
1681                    expected: len,
1682                    found: min_len,
1683                    has_rest: false,
1684                });
1685            } else if let Some(pat_len) = len.checked_sub(min_len) {
1686                // The variable-length pattern was there,
1687                // so it has an array type with the remaining elements left as its size...
1688                return (Some(Ty::new_array(self.interner(), element_ty, pat_len)), arr_ty);
1689            } else {
1690                // ...however, in this case, there were no remaining elements.
1691                // That is, the slice pattern requires more than the array type offers.
1692                self.push_diagnostic(InferenceDiagnostic::MismatchedArrayPatLen {
1693                    pat,
1694                    expected: len,
1695                    found: min_len,
1696                    has_rest: true,
1697                });
1698            }
1699        } else if slice.is_none() {
1700            // We have a pattern with a fixed length,
1701            // which we can use to infer the length of the array.
1702            let updated_arr_ty = Ty::new_array(self.interner(), element_ty, min_len);
1703            _ = self.demand_eqtype(pat.into(), updated_arr_ty, arr_ty);
1704            return (None, updated_arr_ty);
1705        } else {
1706            // We have a variable-length pattern and don't know the array length.
1707            // This happens if we have e.g.,
1708            // `let [a, b, ..] = arr` where `arr: [T; N]` where `const N: usize`.
1709            self.push_diagnostic(InferenceDiagnostic::ArrayPatternWithoutFixedLength { pat });
1710        };
1711
1712        // If we get here, we must have emitted an error.
1713        (Some(self.types.types.error), arr_ty)
1714    }
1715
1716    fn infer_destructuring_assignment_expr(&mut self, expr: ExprId, expected: Ty<'db>) -> Ty<'db> {
1717        // LHS of assignment doesn't constitute reads.
1718        let expr_is_read = ExprIsRead::No;
1719        let lhs_ty = self.infer_expr_inner(expr, &Expectation::has_type(expected), expr_is_read);
1720        match self.coerce(expr, expected, lhs_ty, AllowTwoPhase::No, expr_is_read) {
1721            Ok(ty) => ty,
1722            Err(_) => {
1723                self.emit_type_mismatch(expr.into(), expected, lhs_ty);
1724                // `rhs_ty` is returned so no further type mismatches are
1725                // reported because of this mismatch.
1726                expected
1727            }
1728        }
1729    }
1730}