Skip to main content

rustc_hir_typeck/
pat.rs

1use std::collections::hash_map::Entry::{Occupied, Vacant};
2use std::{assert_matches, cmp};
3
4use rustc_abi::FieldIdx;
5use rustc_ast as ast;
6use rustc_attr_ir::lang_items::LangItem;
7use rustc_data_structures::fx::FxHashMap;
8use rustc_errors::codes::*;
9use rustc_errors::{
10    Applicability, Diag, DiagCtxtHandle, Diagnostic, ErrorGuaranteed, Level, MultiSpan, pluralize,
11    struct_span_code_err,
12};
13use rustc_hir::def::{CtorKind, DefKind, Res};
14use rustc_hir::def_id::DefId;
15use rustc_hir::pat_util::EnumerateAndAdjustIterator;
16use rustc_hir::{
17    self as hir, BindingMode, ByRef, ExprKind, HirId, Mutability, Pat, PatExpr, PatExprKind,
18    PatKind, expr_needs_parens,
19};
20use rustc_hir_analysis::autoderef::report_autoderef_recursion_limit_error;
21use rustc_infer::infer::RegionVariableOrigin;
22use rustc_lint_defs::builtin::NON_EXHAUSTIVE_OMITTED_PATTERNS;
23use rustc_middle::traits::PatternOriginExpr;
24use rustc_middle::ty::{self, Pinnedness, Ty, TypeVisitableExt, Unnormalized};
25use rustc_session::diagnostics::feature_err;
26use rustc_span::edit_distance::find_best_match_for_name;
27use rustc_span::edition::Edition;
28use rustc_span::{BytePos, DUMMY_SP, Ident, Span, bug, kw, span_bug, sym};
29use rustc_trait_selection::infer::InferCtxtExt;
30use rustc_trait_selection::traits::{ObligationCause, ObligationCauseCode};
31use tracing::{debug, instrument, trace};
32use ty::VariantDef;
33use ty::adjustment::{PatAdjust, PatAdjustment};
34
35use crate::expectation::Expectation;
36use crate::gather_locals::DeclOrigin;
37use crate::{FnCtxt, diagnostics};
38
39const CANNOT_IMPLICITLY_DEREF_POINTER_TRAIT_OBJ: &str = "\
40This error indicates that a pointer to a trait type cannot be implicitly dereferenced by a \
41pattern. Every trait defines a type, but because the size of trait implementors isn't fixed, \
42this type has no compile-time size. Therefore, all accesses to trait types must be through \
43pointers. If you encounter this error you should try to avoid dereferencing the pointer.
44
45You can read more about trait objects in the Trait Objects section of the Reference: \
46https://doc.rust-lang.org/reference/types.html#trait-objects";
47
48fn is_number(text: &str) -> bool {
49    text.chars().all(|c: char| c.is_ascii_digit())
50}
51
52/// Information about the expected type at the top level of type checking a pattern.
53///
54/// **NOTE:** This is only for use by diagnostics. Do NOT use for type checking logic!
55#[derive(#[automatically_derived]impl<'tcx> ::core::marker::Copy for TopInfo<'tcx> { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl<'tcx>
    ::core::clone::TrivialClone for TopInfo<'tcx> {
}
#[automatically_derived]impl<'tcx> ::core::clone::Clone for TopInfo<'tcx> {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
        let _:
                ::core::clone::AssertParamIsClone<Option<&'tcx hir::Expr<'tcx>>>;
        let _: ::core::clone::AssertParamIsClone<Option<Span>>;
        let _: ::core::clone::AssertParamIsClone<HirId>;
        *self
    }
}Clone)]
56struct TopInfo<'tcx> {
57    /// The `expected` type at the top level of type checking a pattern.
58    expected: Ty<'tcx>,
59    /// Was the origin of the `span` from a scrutinee expression?
60    ///
61    /// Otherwise there is no scrutinee and it could be e.g. from the type of a formal parameter.
62    origin_expr: Option<&'tcx hir::Expr<'tcx>>,
63    /// The span giving rise to the `expected` type, if one could be provided.
64    ///
65    /// If `origin_expr` is `true`, then this is the span of the scrutinee as in:
66    ///
67    /// - `match scrutinee { ... }`
68    /// - `let _ = scrutinee;`
69    ///
70    /// This is used to point to add context in type errors.
71    /// In the following example, `span` corresponds to the `a + b` expression:
72    ///
73    /// ```text
74    /// error[E0308]: mismatched types
75    ///  --> src/main.rs:L:C
76    ///   |
77    /// L |    let temp: usize = match a + b {
78    ///   |                            ----- this expression has type `usize`
79    /// L |         Ok(num) => num,
80    ///   |         ^^^^^^^ expected `usize`, found enum `std::result::Result`
81    ///   |
82    ///   = note: expected type `usize`
83    ///              found type `std::result::Result<_, _>`
84    /// ```
85    span: Option<Span>,
86    /// The [`HirId`] of the top-level pattern.
87    hir_id: HirId,
88}
89
90#[derive(#[automatically_derived]impl<'tcx> ::core::marker::Copy for PatInfo<'tcx> { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl<'tcx>
    ::core::clone::TrivialClone for PatInfo<'tcx> {
}
#[automatically_derived]impl<'tcx> ::core::clone::Clone for PatInfo<'tcx> {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<ByRef>;
        let _: ::core::clone::AssertParamIsClone<PinnednessCap>;
        let _: ::core::clone::AssertParamIsClone<MutblCap>;
        let _: ::core::clone::AssertParamIsClone<TopInfo<'tcx>>;
        let _: ::core::clone::AssertParamIsClone<Option<DeclOrigin<'tcx>>>;
        let _: ::core::clone::AssertParamIsClone<u32>;
        *self
    }
}Clone)]
91struct PatInfo<'tcx> {
92    binding_mode: ByRef,
93    max_pinnedness: PinnednessCap,
94    max_ref_mutbl: MutblCap,
95    top_info: TopInfo<'tcx>,
96    decl_origin: Option<DeclOrigin<'tcx>>,
97
98    /// The depth of current pattern
99    current_depth: u32,
100}
101
102impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
103    fn pattern_cause(&self, ti: &TopInfo<'tcx>, cause_span: Span) -> ObligationCause<'tcx> {
104        // If origin_expr exists, then expected represents the type of origin_expr.
105        // If span also exists, then span == origin_expr.span (although it doesn't need to exist).
106        // In that case, we can peel away references from both and treat them
107        // as the same.
108        let origin_expr_info = ti.origin_expr.map(|mut cur_expr| {
109            let mut count = 0;
110
111            // cur_ty may have more layers of references than cur_expr.
112            // We can only make suggestions about cur_expr, however, so we'll
113            // use that as our condition for stopping.
114            while let ExprKind::AddrOf(.., inner) = &cur_expr.kind {
115                cur_expr = inner;
116                count += 1;
117            }
118
119            PatternOriginExpr {
120                peeled_span: cur_expr.span,
121                peeled_count: count,
122                peeled_prefix_suggestion_parentheses: expr_needs_parens(cur_expr),
123            }
124        });
125
126        let code = ObligationCauseCode::Pattern {
127            span: ti.span,
128            root_ty: ti.expected,
129            origin_expr: origin_expr_info,
130        };
131        self.cause(cause_span, code)
132    }
133
134    fn demand_eqtype_pat_diag(
135        &'a self,
136        cause_span: Span,
137        expected: Ty<'tcx>,
138        actual: Ty<'tcx>,
139        ti: &TopInfo<'tcx>,
140    ) -> Result<(), Diag<'a>> {
141        self.demand_eqtype_with_origin(&self.pattern_cause(ti, cause_span), expected, actual)
142            .map_err(|mut diag| {
143                if let Some(expr) = ti.origin_expr {
144                    self.suggest_fn_call(&mut diag, expr, expected, |output| {
145                        self.can_eq(self.param_env, output, actual)
146                    });
147                }
148                diag
149            })
150    }
151
152    fn demand_eqtype_pat(
153        &self,
154        cause_span: Span,
155        expected: Ty<'tcx>,
156        actual: Ty<'tcx>,
157        ti: &TopInfo<'tcx>,
158    ) -> Result<(), ErrorGuaranteed> {
159        self.demand_eqtype_pat_diag(cause_span, expected, actual, ti).map_err(|err| err.emit_err())
160    }
161}
162
163/// Mode for adjusting the expected type and binding mode.
164#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for AdjustMode {
}
#[automatically_derived]impl ::core::clone::Clone for AdjustMode {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<PeelKind>;
        *self
    }
}Clone, #[automatically_derived]impl ::core::marker::Copy for AdjustMode { }Copy, #[automatically_derived]impl ::core::fmt::Debug for AdjustMode {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Peel { kind: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Peel kind", &__self_0),
            Self::Pass => ::core::fmt::Formatter::write_str(f, "Pass"),
        }
    }
}Debug, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    AdjustMode {
}
#[automatically_derived]impl ::core::cmp::PartialEq for AdjustMode {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
                ::core::intrinsics::discriminant_value(other) &&
            match (self, other) {
                (Self::Peel { kind: __self_0 }, Self::Peel { kind: __arg1_0 })
                    => __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for AdjustMode {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<PeelKind>;
    }
}Eq)]
165enum AdjustMode {
166    /// Peel off all immediate reference types. If the `deref_patterns` feature is enabled, this
167    /// also peels smart pointer ADTs.
168    Peel { kind: PeelKind },
169    /// Pass on the input binding mode and expected type.
170    Pass,
171}
172
173/// Restrictions on what types to peel when adjusting the expected type and binding mode.
174#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for PeelKind {
}
#[automatically_derived]impl ::core::clone::Clone for PeelKind {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<Option<DefId>>;
        let _: ::core::clone::AssertParamIsClone<usize>;
        *self
    }
}Clone, #[automatically_derived]impl ::core::marker::Copy for PeelKind { }Copy, #[automatically_derived]impl ::core::fmt::Debug for PeelKind {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::ExplicitDerefPat =>
                ::core::fmt::Formatter::write_str(f, "ExplicitDerefPat"),
            Self::Implicit { until_adt: __self_0, pat_ref_layers: __self_1 }
                =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "Implicit until_adt pat_ref_layers", __self_0, &__self_1),
        }
    }
}Debug, #[automatically_derived]impl ::core::marker::StructuralPartialEq for PeelKind
    {
}
#[automatically_derived]impl ::core::cmp::PartialEq for PeelKind {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
                ::core::intrinsics::discriminant_value(other) &&
            match (self, other) {
                (Self::Implicit {
                    until_adt: __self_0, pat_ref_layers: __self_1 },
                    Self::Implicit {
                    until_adt: __arg1_0, pat_ref_layers: __arg1_1 }) =>
                    __self_0 == __arg1_0 && __self_1 == __arg1_1,
                _ => true,
            }
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for PeelKind {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<Option<DefId>>;
        let _: ::core::cmp::AssertParamIsEq<usize>;
    }
}Eq)]
175enum PeelKind {
176    /// Only peel reference types. This is used for explicit `deref!(_)` patterns, which dereference
177    /// any number of `&`/`&mut` references, plus a single smart pointer.
178    ExplicitDerefPat,
179    /// Implicitly peel references, and if `deref_patterns` is enabled, smart pointer ADTs.
180    Implicit {
181        /// The ADT the pattern is a constructor for, if applicable, so that we don't peel it. See
182        /// [`ResolvedPat`] for more information.
183        until_adt: Option<DefId>,
184        /// The number of references at the head of the pattern's type, so we can leave that many
185        /// untouched. This is `1` for string literals, and `0` for most patterns.
186        pat_ref_layers: usize,
187    },
188}
189
190impl AdjustMode {
191    const fn peel_until_adt(opt_adt_def: Option<DefId>) -> AdjustMode {
192        AdjustMode::Peel { kind: PeelKind::Implicit { until_adt: opt_adt_def, pat_ref_layers: 0 } }
193    }
194    const fn peel_all() -> AdjustMode {
195        AdjustMode::peel_until_adt(None)
196    }
197}
198
199/// `ref mut` bindings (explicit or match-ergonomics) are not allowed behind an `&` reference.
200/// Normally, the borrow checker enforces this, but for (currently experimental) match ergonomics,
201/// we track this when typing patterns for two purposes:
202///
203/// - For RFC 3627's Rule 3, when this would prevent us from binding with `ref mut`, we limit the
204///   default binding mode to be by shared `ref` when it would otherwise be `ref mut`.
205///
206/// - For RFC 3627's Rule 5, we allow `&` patterns to match against `&mut` references, treating them
207///   as if they were shared references. Since the scrutinee is mutable in this case, the borrow
208///   checker won't catch if we bind with `ref mut`, so we need to throw an error ourselves.
209#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for MutblCap {
}
#[automatically_derived]impl ::core::clone::Clone for MutblCap {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<Option<Span>>;
        *self
    }
}Clone, #[automatically_derived]impl ::core::marker::Copy for MutblCap { }Copy, #[automatically_derived]impl ::core::fmt::Debug for MutblCap {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Not => ::core::fmt::Formatter::write_str(f, "Not"),
            Self::WeaklyNot(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "WeaklyNot", &__self_0),
            Self::Mut => ::core::fmt::Formatter::write_str(f, "Mut"),
        }
    }
}Debug, #[automatically_derived]impl ::core::marker::StructuralPartialEq for MutblCap
    {
}
#[automatically_derived]impl ::core::cmp::PartialEq for MutblCap {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
                ::core::intrinsics::discriminant_value(other) &&
            match (self, other) {
                (Self::WeaklyNot(__self_0), Self::WeaklyNot(__arg1_0)) =>
                    __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for MutblCap {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<Option<Span>>;
    }
}Eq)]
210enum MutblCap {
211    /// Mutability restricted to immutable.
212    Not,
213
214    /// Mutability restricted to immutable, but only because of the pattern
215    /// (not the scrutinee type).
216    ///
217    /// The contained span, if present, points to an `&` pattern
218    /// that is the reason for the restriction,
219    /// and which will be reported in a diagnostic.
220    WeaklyNot(Option<Span>),
221
222    /// No restriction on mutability
223    Mut,
224}
225
226impl MutblCap {
227    #[must_use]
228    fn cap_to_weakly_not(self, span: Option<Span>) -> Self {
229        match self {
230            MutblCap::Not => MutblCap::Not,
231            _ => MutblCap::WeaklyNot(span),
232        }
233    }
234
235    #[must_use]
236    fn as_mutbl(self) -> Mutability {
237        match self {
238            MutblCap::Not | MutblCap::WeaklyNot(_) => Mutability::Not,
239            MutblCap::Mut => Mutability::Mut,
240        }
241    }
242}
243
244/// `ref` or `ref mut` bindings (not pinned, explicitly or match-ergonomics) are only allowed behind
245/// an `&pin` reference if the binding's type is `Unpin`.
246///
247/// Normally, the borrow checker enforces this (not implemented yet), but we track it here for better
248/// diagnostics.
249#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for PinnednessCap {
}
#[automatically_derived]impl ::core::clone::Clone for PinnednessCap {
    #[inline]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for PinnednessCap { }Copy, #[automatically_derived]impl ::core::fmt::Debug for PinnednessCap {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                PinnednessCap::Not => "Not",
                PinnednessCap::Pinned => "Pinned",
            })
    }
}Debug, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    PinnednessCap {
}
#[automatically_derived]impl ::core::cmp::PartialEq for PinnednessCap {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for PinnednessCap { }Eq)]
250enum PinnednessCap {
251    /// No restriction on pinnedness.
252    Not,
253    /// Pinnedness restricted to pinned.
254    Pinned,
255}
256
257/// Variations on RFC 3627's Rule 4: when do reference patterns match against inherited references?
258///
259/// "Inherited reference" designates the `&`/`&mut` types that arise from using match ergonomics, i.e.
260/// from matching a reference type with a non-reference pattern. E.g. when `Some(x)` matches on
261/// `&mut Option<&T>`, `x` gets type `&mut &T` and the outer `&mut` is considered "inherited".
262#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for InheritedRefMatchRule {
}
#[automatically_derived]impl ::core::clone::Clone for InheritedRefMatchRule {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<bool>;
        *self
    }
}Clone, #[automatically_derived]impl ::core::marker::Copy for InheritedRefMatchRule {
}Copy, #[automatically_derived]impl ::core::fmt::Debug for InheritedRefMatchRule {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::EatOuter =>
                ::core::fmt::Formatter::write_str(f, "EatOuter"),
            Self::EatInner =>
                ::core::fmt::Formatter::write_str(f, "EatInner"),
            Self::EatBoth { consider_inherited_ref: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "EatBoth consider_inherited_ref", &__self_0),
        }
    }
}Debug, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    InheritedRefMatchRule {
}
#[automatically_derived]impl ::core::cmp::PartialEq for InheritedRefMatchRule
    {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
                ::core::intrinsics::discriminant_value(other) &&
            match (self, other) {
                (Self::EatBoth { consider_inherited_ref: __self_0 },
                    Self::EatBoth { consider_inherited_ref: __arg1_0 }) =>
                    __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for InheritedRefMatchRule {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<bool>;
    }
}Eq)]
263enum InheritedRefMatchRule {
264    /// Reference patterns consume only the inherited reference if possible, regardless of whether
265    /// the underlying type being matched against is a reference type. If there is no inherited
266    /// reference, a reference will be consumed from the underlying type.
267    EatOuter,
268    /// Reference patterns consume only a reference from the underlying type if possible. If the
269    /// underlying type is not a reference type, the inherited reference will be consumed.
270    EatInner,
271    /// When the underlying type is a reference type, reference patterns consume both layers of
272    /// reference, i.e. they both reset the binding mode and consume the reference type.
273    EatBoth {
274        /// If `true`, an inherited reference will be considered when determining whether a reference
275        /// pattern matches a given type:
276        /// - If the underlying type is not a reference, a reference pattern may eat the inherited reference;
277        /// - If the underlying type is a reference, a reference pattern matches if it can eat either one
278        ///   of the underlying and inherited references. E.g. a `&mut` pattern is allowed if either the
279        ///   underlying type is `&mut` or the inherited reference is `&mut`.
280        ///
281        /// If `false`, a reference pattern is only matched against the underlying type.
282        /// This is `false` for stable Rust and `true` for both the `ref_pat_eat_one_layer_2024` and
283        /// `ref_pat_eat_one_layer_2024_structural` feature gates.
284        consider_inherited_ref: bool,
285    },
286}
287
288/// When checking patterns containing paths, we need to know the path's resolution to determine
289/// whether to apply match ergonomics and implicitly dereference the scrutinee. For instance, when
290/// the `deref_patterns` feature is enabled and we're matching against a scrutinee of type
291/// `Cow<'a, Option<u8>>`, we insert an implicit dereference to allow the pattern `Some(_)` to type,
292/// but we must not dereference it when checking the pattern `Cow::Borrowed(_)`.
293///
294/// `ResolvedPat` contains the information from resolution needed to determine match ergonomics
295/// adjustments, and to finish checking the pattern once we know its adjusted type.
296#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl<'tcx>
    ::core::clone::TrivialClone for ResolvedPat<'tcx> {
}
#[automatically_derived]impl<'tcx> ::core::clone::Clone for ResolvedPat<'tcx>
    {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
        let _: ::core::clone::AssertParamIsClone<ResolvedPatKind<'tcx>>;
        *self
    }
}Clone, #[automatically_derived]impl<'tcx> ::core::marker::Copy for ResolvedPat<'tcx>
    {
}Copy, #[automatically_derived]impl<'tcx> ::core::fmt::Debug for ResolvedPat<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "ResolvedPat ty kind", &self.ty, &&self.kind)
    }
}Debug)]
297struct ResolvedPat<'tcx> {
298    /// The type of the pattern, to be checked against the type of the scrutinee after peeling. This
299    /// is also used to avoid peeling the scrutinee's constructors (see the `Cow` example above).
300    ty: Ty<'tcx>,
301    kind: ResolvedPatKind<'tcx>,
302}
303
304#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl<'tcx>
    ::core::clone::TrivialClone for ResolvedPatKind<'tcx> {
}
#[automatically_derived]impl<'tcx> ::core::clone::Clone for
    ResolvedPatKind<'tcx> {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<Res>;
        let _:
                ::core::clone::AssertParamIsClone<&'tcx [hir::PathSegment<'tcx>]>;
        let _: ::core::clone::AssertParamIsClone<&'tcx VariantDef>;
        let _: ::core::clone::AssertParamIsClone<&'tcx VariantDef>;
        *self
    }
}Clone, #[automatically_derived]impl<'tcx> ::core::marker::Copy for
    ResolvedPatKind<'tcx> {
}Copy, #[automatically_derived]impl<'tcx> ::core::fmt::Debug for
    ResolvedPatKind<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Path { res: __self_0, pat_res: __self_1, segments: __self_2
                } =>
                ::core::fmt::Formatter::debug_struct_field3_finish(f,
                    "Path res pat_res segments", __self_0, __self_1, &__self_2),
            Self::Struct { variant: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Struct variant", &__self_0),
            Self::TupleStruct { res: __self_0, variant: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "TupleStruct res variant", __self_0, &__self_1),
        }
    }
}Debug)]
305enum ResolvedPatKind<'tcx> {
306    Path { res: Res, pat_res: Res, segments: &'tcx [hir::PathSegment<'tcx>] },
307    Struct { variant: &'tcx VariantDef },
308    TupleStruct { res: Res, variant: &'tcx VariantDef },
309}
310
311impl<'tcx> ResolvedPat<'tcx> {
312    fn adjust_mode(&self) -> AdjustMode {
313        if let ResolvedPatKind::Path { res, .. } = self.kind
314            && #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::Const | DefKind::AssocConst, _) => true,
    _ => false,
}matches!(res, Res::Def(DefKind::Const | DefKind::AssocConst, _))
315        {
316            // These constants can be of a reference type, e.g. `const X: &u8 = &0;`.
317            // Peeling the reference types too early will cause type checking failures.
318            // Although it would be possible to *also* peel the types of the constants too.
319            AdjustMode::Pass
320        } else {
321            // The remaining possible resolutions for path, struct, and tuple struct patterns are
322            // ADT constructors. As such, we may peel references freely, but we must not peel the
323            // ADT itself from the scrutinee if it's a smart pointer.
324            AdjustMode::peel_until_adt(self.ty.ty_adt_def().map(|adt| adt.did()))
325        }
326    }
327}
328
329impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
330    /// Experimental pattern feature: after matching against a shared reference, do we limit the
331    /// default binding mode in subpatterns to be `ref` when it would otherwise be `ref mut`?
332    /// This corresponds to Rule 3 of RFC 3627.
333    fn downgrade_mut_inside_shared(&self) -> bool {
334        // NB: RFC 3627 proposes stabilizing Rule 3 in all editions. If we adopt the same behavior
335        // across all editions, this may be removed.
336        self.tcx.features().ref_pat_eat_one_layer_2024_structural()
337    }
338
339    /// Experimental pattern feature: when do reference patterns match against inherited references?
340    /// This corresponds to variations on Rule 4 of RFC 3627.
341    fn ref_pat_matches_inherited_ref(&self, edition: Edition) -> InheritedRefMatchRule {
342        // NB: The particular rule used here is likely to differ across editions, so calls to this
343        // may need to become edition checks after match ergonomics stabilize.
344        if edition.at_least_rust_2024() {
345            if self.tcx.features().ref_pat_eat_one_layer_2024() {
346                InheritedRefMatchRule::EatOuter
347            } else if self.tcx.features().ref_pat_eat_one_layer_2024_structural() {
348                InheritedRefMatchRule::EatInner
349            } else {
350                // Currently, matching against an inherited ref on edition 2024 is an error.
351                // Use `EatBoth` as a fallback to be similar to stable Rust.
352                InheritedRefMatchRule::EatBoth { consider_inherited_ref: false }
353            }
354        } else {
355            InheritedRefMatchRule::EatBoth {
356                consider_inherited_ref: self.tcx.features().ref_pat_eat_one_layer_2024()
357                    || self.tcx.features().ref_pat_eat_one_layer_2024_structural(),
358            }
359        }
360    }
361
362    /// Experimental pattern feature: do `&` patterns match against `&mut` references, treating them
363    /// as if they were shared references? This corresponds to Rule 5 of RFC 3627.
364    fn ref_pat_matches_mut_ref(&self) -> bool {
365        // NB: RFC 3627 proposes stabilizing Rule 5 in all editions. If we adopt the same behavior
366        // across all editions, this may be removed.
367        self.tcx.features().ref_pat_eat_one_layer_2024()
368            || self.tcx.features().ref_pat_eat_one_layer_2024_structural()
369    }
370
371    /// Type check the given top level pattern against the `expected` type.
372    ///
373    /// If a `Some(span)` is provided and `origin_expr` holds,
374    /// then the `span` represents the scrutinee's span.
375    /// The scrutinee is found in e.g. `match scrutinee { ... }` and `let pat = scrutinee;`.
376    ///
377    /// Otherwise, `Some(span)` represents the span of a type expression
378    /// which originated the `expected` type.
379    pub(crate) fn check_pat_top(
380        &self,
381        pat: &'tcx Pat<'tcx>,
382        expected: Ty<'tcx>,
383        span: Option<Span>,
384        origin_expr: Option<&'tcx hir::Expr<'tcx>>,
385        decl_origin: Option<DeclOrigin<'tcx>>,
386    ) {
387        let top_info = TopInfo { expected, origin_expr, span, hir_id: pat.hir_id };
388        let pat_info = PatInfo {
389            binding_mode: ByRef::No,
390            max_pinnedness: PinnednessCap::Not,
391            max_ref_mutbl: MutblCap::Mut,
392            top_info,
393            decl_origin,
394            current_depth: 0,
395        };
396        self.check_pat(pat, expected, pat_info);
397    }
398
399    /// Type check the given `pat` against the `expected` type
400    /// with the provided `binding_mode` (default binding mode).
401    ///
402    /// Outside of this module, `check_pat_top` should always be used.
403    /// Conversely, inside this module, `check_pat_top` should never be used.
404    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("check_pat",
                                    "rustc_hir_typeck::pat", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/pat.rs"),
                                    ::tracing_core::__macro_support::Option::Some(404u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::pat"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("pat")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("pat");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("expected")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("expected");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&pat)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expected)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

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