Skip to main content

rustc_pattern_analysis/
rustc.rs

1use std::cell::Cell;
2use std::fmt;
3use std::iter::once;
4
5use rustc_abi::{FIRST_VARIANT, FieldIdx, Integer, VariantIdx};
6use rustc_arena::DroplessArena;
7use rustc_hir::HirId;
8use rustc_hir::def_id::DefId;
9use rustc_index::{Idx, IndexVec};
10use rustc_middle::middle::stability::EvalResult;
11use rustc_middle::thir::{self, Pat, PatKind, PatRange, PatRangeBoundary};
12use rustc_middle::ty::layout::IntegerExt;
13use rustc_middle::ty::{
14    self, FieldDef, OpaqueTypeKey, ScalarInt, Ty, TyCtxt, TypeVisitableExt, VariantDef,
15};
16use rustc_middle::{bug, span_bug};
17use rustc_session::lint;
18use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span};
19
20use crate::constructor::Constructor::*;
21use crate::constructor::{
22    IntRange, MaybeInfiniteInt, OpaqueId, RangeEnd, Slice, SliceKind, VariantVisibility,
23};
24use crate::lints::lint_nonexhaustive_missing_variants;
25use crate::pat_column::PatternColumn;
26use crate::rustc::print::EnumInfo;
27use crate::usefulness::{PlaceValidity, compute_match_usefulness};
28use crate::{PatCx, PrivateUninhabitedField, errors};
29
30mod print;
31
32// Re-export rustc-specific versions of all these types.
33pub type Constructor<'p, 'tcx> = crate::constructor::Constructor<RustcPatCtxt<'p, 'tcx>>;
34pub type ConstructorSet<'p, 'tcx> = crate::constructor::ConstructorSet<RustcPatCtxt<'p, 'tcx>>;
35pub type DeconstructedPat<'p, 'tcx> = crate::pat::DeconstructedPat<RustcPatCtxt<'p, 'tcx>>;
36pub type MatchArm<'p, 'tcx> = crate::MatchArm<'p, RustcPatCtxt<'p, 'tcx>>;
37pub type RedundancyExplanation<'p, 'tcx> =
38    crate::usefulness::RedundancyExplanation<'p, RustcPatCtxt<'p, 'tcx>>;
39pub type Usefulness<'p, 'tcx> = crate::usefulness::Usefulness<'p, RustcPatCtxt<'p, 'tcx>>;
40pub type UsefulnessReport<'p, 'tcx> =
41    crate::usefulness::UsefulnessReport<'p, RustcPatCtxt<'p, 'tcx>>;
42pub type WitnessPat<'p, 'tcx> = crate::pat::WitnessPat<RustcPatCtxt<'p, 'tcx>>;
43
44/// A type which has gone through `cx.reveal_opaque_ty`, i.e. if it was opaque it was replaced by
45/// the hidden type if allowed in the current body. This ensures we consistently inspect the hidden
46/// types when we should.
47///
48/// Use `.inner()` or deref to get to the `Ty<'tcx>`.
49#[repr(transparent)]
50#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for RevealedTy<'tcx> {
    #[inline]
    fn clone(&self) -> RevealedTy<'tcx> {
        let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
        *self
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::marker::Copy for RevealedTy<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::cmp::PartialEq for RevealedTy<'tcx> {
    #[inline]
    fn eq(&self, other: &RevealedTy<'tcx>) -> bool { self.0 == other.0 }
}PartialEq, #[automatically_derived]
impl<'tcx> ::core::cmp::Eq for RevealedTy<'tcx> {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_receiver_is_total_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<Ty<'tcx>>;
    }
}Eq, #[automatically_derived]
impl<'tcx> ::core::hash::Hash for RevealedTy<'tcx> {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.0, state)
    }
}Hash)]
51pub struct RevealedTy<'tcx>(Ty<'tcx>);
52
53impl<'tcx> fmt::Display for RevealedTy<'tcx> {
54    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
55        self.0.fmt(fmt)
56    }
57}
58
59impl<'tcx> fmt::Debug for RevealedTy<'tcx> {
60    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
61        self.0.fmt(fmt)
62    }
63}
64
65impl<'tcx> std::ops::Deref for RevealedTy<'tcx> {
66    type Target = Ty<'tcx>;
67    fn deref(&self) -> &Self::Target {
68        &self.0
69    }
70}
71
72impl<'tcx> RevealedTy<'tcx> {
73    pub fn inner(self) -> Ty<'tcx> {
74        self.0
75    }
76}
77
78#[derive(#[automatically_derived]
impl<'p, 'tcx: 'p> ::core::clone::Clone for RustcPatCtxt<'p, 'tcx> {
    #[inline]
    fn clone(&self) -> RustcPatCtxt<'p, 'tcx> {
        RustcPatCtxt {
            tcx: ::core::clone::Clone::clone(&self.tcx),
            typeck_results: ::core::clone::Clone::clone(&self.typeck_results),
            module: ::core::clone::Clone::clone(&self.module),
            typing_env: ::core::clone::Clone::clone(&self.typing_env),
            dropless_arena: ::core::clone::Clone::clone(&self.dropless_arena),
            match_lint_level: ::core::clone::Clone::clone(&self.match_lint_level),
            whole_match_span: ::core::clone::Clone::clone(&self.whole_match_span),
            scrut_span: ::core::clone::Clone::clone(&self.scrut_span),
            refutable: ::core::clone::Clone::clone(&self.refutable),
            known_valid_scrutinee: ::core::clone::Clone::clone(&self.known_valid_scrutinee),
            internal_state: ::core::clone::Clone::clone(&self.internal_state),
        }
    }
}Clone)]
79pub struct RustcPatCtxt<'p, 'tcx: 'p> {
80    pub tcx: TyCtxt<'tcx>,
81    pub typeck_results: &'tcx ty::TypeckResults<'tcx>,
82    /// The module in which the match occurs. This is necessary for
83    /// checking inhabited-ness of types because whether a type is (visibly)
84    /// inhabited can depend on whether it was defined in the current module or
85    /// not. E.g., `struct Foo { _private: ! }` cannot be seen to be empty
86    /// outside its module and should not be matchable with an empty match statement.
87    pub module: DefId,
88    pub typing_env: ty::TypingEnv<'tcx>,
89    /// To allocate the result of `self.ctor_sub_tys()`
90    pub dropless_arena: &'p DroplessArena,
91    /// Lint level at the match.
92    pub match_lint_level: HirId,
93    /// The span of the whole match, if applicable.
94    pub whole_match_span: Option<Span>,
95    /// Span of the scrutinee.
96    pub scrut_span: Span,
97    /// Only produce `NON_EXHAUSTIVE_OMITTED_PATTERNS` lint on refutable patterns.
98    pub refutable: bool,
99    /// Whether the data at the scrutinee is known to be valid. This is false if the scrutinee comes
100    /// from a union field, a pointer deref, or a reference deref (pending opsem decisions).
101    pub known_valid_scrutinee: bool,
102    pub internal_state: RustcPatCtxtState,
103}
104
105/// Private fields of [`RustcPatCtxt`], separated out to permit record initialization syntax.
106#[derive(#[automatically_derived]
impl ::core::clone::Clone for RustcPatCtxtState {
    #[inline]
    fn clone(&self) -> RustcPatCtxtState {
        RustcPatCtxtState {
            has_lowered_deref_pat: ::core::clone::Clone::clone(&self.has_lowered_deref_pat),
        }
    }
}Clone, #[automatically_derived]
impl ::core::default::Default for RustcPatCtxtState {
    #[inline]
    fn default() -> RustcPatCtxtState {
        RustcPatCtxtState {
            has_lowered_deref_pat: ::core::default::Default::default(),
        }
    }
}Default)]
107pub struct RustcPatCtxtState {
108    /// Has a deref pattern been lowered? This is initialized to `false` and is updated by
109    /// [`RustcPatCtxt::lower_pat`] in order to avoid performing deref-pattern-specific validation
110    /// for everything containing patterns.
111    has_lowered_deref_pat: Cell<bool>,
112}
113
114impl<'p, 'tcx: 'p> fmt::Debug for RustcPatCtxt<'p, 'tcx> {
115    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
116        f.debug_struct("RustcPatCtxt").finish()
117    }
118}
119
120impl<'p, 'tcx: 'p> RustcPatCtxt<'p, 'tcx> {
121    /// Type inference occasionally gives us opaque types in places where corresponding patterns
122    /// have more specific types. To avoid inconsistencies as well as detect opaque uninhabited
123    /// types, we use the corresponding hidden type if possible.
124    // FIXME(#132279): This will be unnecessary once we have a TypingMode which supports revealing
125    // opaque types defined in a body.
126    #[inline]
127    pub fn reveal_opaque_ty(&self, ty: Ty<'tcx>) -> RevealedTy<'tcx> {
128        fn reveal_inner<'tcx>(cx: &RustcPatCtxt<'_, 'tcx>, ty: Ty<'tcx>) -> RevealedTy<'tcx> {
129            let ty::Alias(ty::Opaque, alias_ty) = *ty.kind() else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
130            if let Some(local_def_id) = alias_ty.def_id.as_local() {
131                let key = ty::OpaqueTypeKey { def_id: local_def_id, args: alias_ty.args };
132                if let Some(ty) = cx.reveal_opaque_key(key) {
133                    return RevealedTy(ty);
134                }
135            }
136            RevealedTy(ty)
137        }
138        if let ty::Alias(ty::Opaque, _) = ty.kind() {
139            reveal_inner(self, ty)
140        } else {
141            RevealedTy(ty)
142        }
143    }
144
145    /// Returns the hidden type corresponding to this key if the body under analysis is allowed to
146    /// know it.
147    fn reveal_opaque_key(&self, key: OpaqueTypeKey<'tcx>) -> Option<Ty<'tcx>> {
148        self.typeck_results
149            .hidden_types
150            .get(&key.def_id)
151            .map(|x| x.ty.instantiate(self.tcx, key.args))
152    }
153    // This can take a non-revealed `Ty` because it reveals opaques itself.
154    pub fn is_uninhabited(&self, ty: Ty<'tcx>) -> bool {
155        !ty.inhabited_predicate(self.tcx).apply_revealing_opaque(
156            self.tcx,
157            self.typing_env,
158            self.module,
159            &|key| self.reveal_opaque_key(key),
160        )
161    }
162
163    /// Returns whether the given type is an enum from another crate declared `#[non_exhaustive]`.
164    pub fn is_foreign_non_exhaustive_enum(&self, ty: RevealedTy<'tcx>) -> bool {
165        match ty.kind() {
166            ty::Adt(def, ..) => def.variant_list_has_applicable_non_exhaustive(),
167            _ => false,
168        }
169    }
170
171    /// Whether the range denotes the fictitious values before `isize::MIN` or after
172    /// `usize::MAX`/`isize::MAX` (see doc of [`IntRange::split`] for why these exist).
173    pub fn is_range_beyond_boundaries(&self, range: &IntRange, ty: RevealedTy<'tcx>) -> bool {
174        ty.is_ptr_sized_integral() && {
175            // The two invalid ranges are `NegInfinity..isize::MIN` (represented as
176            // `NegInfinity..0`), and `{u,i}size::MAX+1..PosInfinity`. `hoist_pat_range_bdy`
177            // converts `MAX+1` to `PosInfinity`, and we couldn't have `PosInfinity` in `range.lo`
178            // otherwise.
179            let lo = self.hoist_pat_range_bdy(range.lo, ty);
180            #[allow(non_exhaustive_omitted_patterns)] match lo {
    PatRangeBoundary::PosInfinity => true,
    _ => false,
}matches!(lo, PatRangeBoundary::PosInfinity)
181                || #[allow(non_exhaustive_omitted_patterns)] match range.hi {
    MaybeInfiniteInt::Finite(0) => true,
    _ => false,
}matches!(range.hi, MaybeInfiniteInt::Finite(0))
182        }
183    }
184
185    pub(crate) fn variant_sub_tys(
186        &self,
187        ty: RevealedTy<'tcx>,
188        variant: &'tcx VariantDef,
189    ) -> impl Iterator<Item = (&'tcx FieldDef, RevealedTy<'tcx>)> {
190        let ty::Adt(_, args) = ty.kind() else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
191        variant.fields.iter().map(move |field| {
192            let ty = field.ty(self.tcx, args);
193            // `field.ty()` doesn't normalize after instantiating.
194            let ty =
195                self.tcx.try_normalize_erasing_regions(self.typing_env, ty).unwrap_or_else(|e| {
196                    self.tcx.dcx().span_delayed_bug(
197                        self.scrut_span,
198                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Failed to normalize {0:?} in typing_env={1:?} while getting variant sub tys for {2:?}",
                e.get_type_for_failure(), self.typing_env, ty))
    })format!(
199                            "Failed to normalize {:?} in typing_env={:?} while getting variant sub tys for {ty:?}",
200                            e.get_type_for_failure(),
201                            self.typing_env,
202                        ),
203                    );
204                    ty
205                });
206            let ty = self.reveal_opaque_ty(ty);
207            (field, ty)
208        })
209    }
210
211    pub(crate) fn variant_index_for_adt(
212        ctor: &Constructor<'p, 'tcx>,
213        adt: ty::AdtDef<'tcx>,
214    ) -> VariantIdx {
215        match *ctor {
216            Variant(idx) => idx,
217            Struct | UnionField => {
218                if !!adt.is_enum() {
    ::core::panicking::panic("assertion failed: !adt.is_enum()")
};assert!(!adt.is_enum());
219                FIRST_VARIANT
220            }
221            _ => ::rustc_middle::util::bug::bug_fmt(format_args!("bad constructor {0:?} for adt {1:?}",
        ctor, adt))bug!("bad constructor {:?} for adt {:?}", ctor, adt),
222        }
223    }
224
225    /// Returns the types of the fields for a given constructor. The result must have a length of
226    /// `ctor.arity()`.
227    pub(crate) fn ctor_sub_tys(
228        &self,
229        ctor: &Constructor<'p, 'tcx>,
230        ty: RevealedTy<'tcx>,
231    ) -> impl Iterator<Item = (RevealedTy<'tcx>, PrivateUninhabitedField)> + ExactSizeIterator {
232        fn reveal_and_alloc<'a, 'tcx>(
233            cx: &'a RustcPatCtxt<'_, 'tcx>,
234            iter: impl Iterator<Item = Ty<'tcx>>,
235        ) -> &'a [(RevealedTy<'tcx>, PrivateUninhabitedField)] {
236            cx.dropless_arena.alloc_from_iter(
237                iter.map(|ty| cx.reveal_opaque_ty(ty))
238                    .map(|ty| (ty, PrivateUninhabitedField(false))),
239            )
240        }
241        let cx = self;
242        let slice = match ctor {
243            Struct | Variant(_) | UnionField => match ty.kind() {
244                ty::Tuple(fs) => reveal_and_alloc(cx, fs.iter()),
245                ty::Adt(adt, _) => {
246                    let variant = &adt.variant(RustcPatCtxt::variant_index_for_adt(&ctor, *adt));
247                    let tys = cx.variant_sub_tys(ty, variant).map(|(field, ty)| {
248                        let is_visible =
249                            adt.is_enum() || field.vis.is_accessible_from(cx.module, cx.tcx);
250                        let is_uninhabited = cx.is_uninhabited(*ty);
251                        let skip = is_uninhabited && !is_visible;
252                        (ty, PrivateUninhabitedField(skip))
253                    });
254                    cx.dropless_arena.alloc_from_iter(tys)
255                }
256                _ => ::rustc_middle::util::bug::bug_fmt(format_args!("Unexpected type for constructor `{0:?}`: {1:?}",
        ctor, ty))bug!("Unexpected type for constructor `{ctor:?}`: {ty:?}"),
257            },
258            Ref => match ty.kind() {
259                ty::Ref(_, rty, _) => reveal_and_alloc(cx, once(*rty)),
260                _ => ::rustc_middle::util::bug::bug_fmt(format_args!("Unexpected type for `Ref` constructor: {0:?}",
        ty))bug!("Unexpected type for `Ref` constructor: {ty:?}"),
261            },
262            Slice(slice) => match ty.builtin_index() {
263                Some(ty) => {
264                    let arity = slice.arity();
265                    reveal_and_alloc(cx, (0..arity).map(|_| ty))
266                }
267                None => ::rustc_middle::util::bug::bug_fmt(format_args!("bad slice pattern {0:?} {1:?}",
        ctor, ty))bug!("bad slice pattern {:?} {:?}", ctor, ty),
268            },
269            DerefPattern(pointee_ty) => reveal_and_alloc(cx, once(pointee_ty.inner())),
270            Bool(..) | IntRange(..) | F16Range(..) | F32Range(..) | F64Range(..)
271            | F128Range(..) | Str(..) | Opaque(..) | Never | NonExhaustive | Hidden | Missing
272            | PrivateUninhabited | Wildcard => &[],
273            Or => {
274                ::rustc_middle::util::bug::bug_fmt(format_args!("called `Fields::wildcards` on an `Or` ctor"))bug!("called `Fields::wildcards` on an `Or` ctor")
275            }
276        };
277        slice.iter().copied()
278    }
279
280    /// The number of fields for this constructor.
281    pub(crate) fn ctor_arity(&self, ctor: &Constructor<'p, 'tcx>, ty: RevealedTy<'tcx>) -> usize {
282        match ctor {
283            Struct | Variant(_) | UnionField => match ty.kind() {
284                ty::Tuple(fs) => fs.len(),
285                ty::Adt(adt, ..) => {
286                    let variant_idx = RustcPatCtxt::variant_index_for_adt(&ctor, *adt);
287                    adt.variant(variant_idx).fields.len()
288                }
289                _ => ::rustc_middle::util::bug::bug_fmt(format_args!("Unexpected type for constructor `{0:?}`: {1:?}",
        ctor, ty))bug!("Unexpected type for constructor `{ctor:?}`: {ty:?}"),
290            },
291            Ref | DerefPattern(_) => 1,
292            Slice(slice) => slice.arity(),
293            Bool(..) | IntRange(..) | F16Range(..) | F32Range(..) | F64Range(..)
294            | F128Range(..) | Str(..) | Opaque(..) | Never | NonExhaustive | Hidden | Missing
295            | PrivateUninhabited | Wildcard => 0,
296            Or => ::rustc_middle::util::bug::bug_fmt(format_args!("The `Or` constructor doesn\'t have a fixed arity"))bug!("The `Or` constructor doesn't have a fixed arity"),
297        }
298    }
299
300    /// Creates a set that represents all the constructors of `ty`.
301    ///
302    /// See [`crate::constructor`] for considerations of emptiness.
303    pub fn ctors_for_ty(
304        &self,
305        ty: RevealedTy<'tcx>,
306    ) -> Result<ConstructorSet<'p, 'tcx>, ErrorGuaranteed> {
307        let cx = self;
308        let make_uint_range = |start, end| {
309            IntRange::from_range(
310                MaybeInfiniteInt::new_finite_uint(start),
311                MaybeInfiniteInt::new_finite_uint(end),
312                RangeEnd::Included,
313            )
314        };
315        // Abort on type error.
316        ty.error_reported()?;
317        // This determines the set of all possible constructors for the type `ty`. For numbers,
318        // arrays and slices we use ranges and variable-length slices when appropriate.
319        Ok(match ty.kind() {
320            ty::Bool => ConstructorSet::Bool,
321            ty::Char => {
322                // The valid Unicode Scalar Value ranges.
323                ConstructorSet::Integers {
324                    range_1: make_uint_range('\u{0000}' as u128, '\u{D7FF}' as u128),
325                    range_2: Some(make_uint_range('\u{E000}' as u128, '\u{10FFFF}' as u128)),
326                }
327            }
328            &ty::Int(ity) => {
329                let range = if ty.is_ptr_sized_integral() {
330                    // The min/max values of `isize` are not allowed to be observed.
331                    IntRange {
332                        lo: MaybeInfiniteInt::NegInfinity,
333                        hi: MaybeInfiniteInt::PosInfinity,
334                    }
335                } else {
336                    let size = Integer::from_int_ty(&cx.tcx, ity).size().bits();
337                    let min = 1u128 << (size - 1);
338                    let max = min - 1;
339                    let min = MaybeInfiniteInt::new_finite_int(min, size);
340                    let max = MaybeInfiniteInt::new_finite_int(max, size);
341                    IntRange::from_range(min, max, RangeEnd::Included)
342                };
343                ConstructorSet::Integers { range_1: range, range_2: None }
344            }
345            &ty::Uint(uty) => {
346                let range = if ty.is_ptr_sized_integral() {
347                    // The max value of `usize` is not allowed to be observed.
348                    let lo = MaybeInfiniteInt::new_finite_uint(0);
349                    IntRange { lo, hi: MaybeInfiniteInt::PosInfinity }
350                } else {
351                    let size = Integer::from_uint_ty(&cx.tcx, uty).size();
352                    let max = size.truncate(u128::MAX);
353                    make_uint_range(0, max)
354                };
355                ConstructorSet::Integers { range_1: range, range_2: None }
356            }
357            ty::Slice(sub_ty) => ConstructorSet::Slice {
358                array_len: None,
359                subtype_is_empty: cx.is_uninhabited(*sub_ty),
360            },
361            ty::Array(sub_ty, len) => {
362                // We treat arrays of a constant but unknown length like slices.
363                ConstructorSet::Slice {
364                    array_len: len.try_to_target_usize(cx.tcx).map(|l| l as usize),
365                    subtype_is_empty: cx.is_uninhabited(*sub_ty),
366                }
367            }
368            ty::Adt(def, args) if def.is_enum() => {
369                let is_declared_nonexhaustive = cx.is_foreign_non_exhaustive_enum(ty);
370                if def.variants().is_empty() && !is_declared_nonexhaustive {
371                    ConstructorSet::NoConstructors
372                } else {
373                    let mut variants =
374                        IndexVec::from_elem(VariantVisibility::Visible, def.variants());
375                    for (idx, v) in def.variants().iter_enumerated() {
376                        let variant_def_id = def.variant(idx).def_id;
377                        // Visibly uninhabited variants.
378                        let is_inhabited = v
379                            .inhabited_predicate(cx.tcx, *def)
380                            .instantiate(cx.tcx, args)
381                            .apply_revealing_opaque(cx.tcx, cx.typing_env, cx.module, &|key| {
382                                cx.reveal_opaque_key(key)
383                            });
384                        // Variants that depend on a disabled unstable feature.
385                        let is_unstable = #[allow(non_exhaustive_omitted_patterns)] match cx.tcx.eval_stability(variant_def_id,
        None, DUMMY_SP, None) {
    EvalResult::Deny { .. } => true,
    _ => false,
}matches!(
386                            cx.tcx.eval_stability(variant_def_id, None, DUMMY_SP, None),
387                            EvalResult::Deny { .. }
388                        );
389                        // Foreign `#[doc(hidden)]` variants.
390                        let is_doc_hidden =
391                            cx.tcx.is_doc_hidden(variant_def_id) && !variant_def_id.is_local();
392                        let visibility = if !is_inhabited {
393                            // FIXME: handle empty+hidden
394                            VariantVisibility::Empty
395                        } else if is_unstable || is_doc_hidden {
396                            VariantVisibility::Hidden
397                        } else {
398                            VariantVisibility::Visible
399                        };
400                        variants[idx] = visibility;
401                    }
402
403                    ConstructorSet::Variants { variants, non_exhaustive: is_declared_nonexhaustive }
404                }
405            }
406            ty::Adt(def, _) if def.is_union() => ConstructorSet::Union,
407            ty::Adt(..) | ty::Tuple(..) => {
408                ConstructorSet::Struct { empty: cx.is_uninhabited(ty.inner()) }
409            }
410            ty::Ref(..) => ConstructorSet::Ref,
411            ty::Never => ConstructorSet::NoConstructors,
412            // This type is one for which we cannot list constructors, like `str` or `f64`.
413            // FIXME(Nadrieril): which of these are actually allowed?
414            ty::Float(_)
415            | ty::Str
416            | ty::Foreign(_)
417            | ty::RawPtr(_, _)
418            | ty::FnDef(_, _)
419            | ty::FnPtr(..)
420            | ty::Pat(_, _)
421            | ty::Dynamic(_, _)
422            | ty::Closure(..)
423            | ty::CoroutineClosure(..)
424            | ty::Coroutine(_, _)
425            | ty::UnsafeBinder(_)
426            | ty::Alias(_, _)
427            | ty::Param(_)
428            | ty::Error(_) => ConstructorSet::Unlistable,
429            ty::CoroutineWitness(_, _) | ty::Bound(_, _) | ty::Placeholder(_) | ty::Infer(_) => {
430                ::rustc_middle::util::bug::bug_fmt(format_args!("Encountered unexpected type in `ConstructorSet::for_ty`: {0:?}",
        ty))bug!("Encountered unexpected type in `ConstructorSet::for_ty`: {ty:?}")
431            }
432        })
433    }
434
435    pub(crate) fn lower_pat_range_bdy(
436        &self,
437        bdy: PatRangeBoundary<'tcx>,
438        ty: RevealedTy<'tcx>,
439    ) -> MaybeInfiniteInt {
440        match bdy {
441            PatRangeBoundary::NegInfinity => MaybeInfiniteInt::NegInfinity,
442            PatRangeBoundary::Finite(value) => {
443                let bits = value.to_leaf().to_bits_unchecked();
444                match *ty.kind() {
445                    ty::Int(ity) => {
446                        let size = Integer::from_int_ty(&self.tcx, ity).size().bits();
447                        MaybeInfiniteInt::new_finite_int(bits, size)
448                    }
449                    _ => MaybeInfiniteInt::new_finite_uint(bits),
450                }
451            }
452            PatRangeBoundary::PosInfinity => MaybeInfiniteInt::PosInfinity,
453        }
454    }
455
456    /// Note: the input patterns must have been lowered through
457    /// `rustc_mir_build::thir::pattern::check_match::MatchVisitor::lower_pattern`.
458    pub fn lower_pat(&self, pat: &'p Pat<'tcx>) -> DeconstructedPat<'p, 'tcx> {
459        let cx = self;
460        let ty = cx.reveal_opaque_ty(pat.ty);
461        let ctor;
462        let arity;
463        let fields: Vec<_>;
464        match &pat.kind {
465            PatKind::Binding { subpattern: Some(subpat), .. } => return self.lower_pat(subpat),
466            PatKind::Missing | PatKind::Binding { subpattern: None, .. } | PatKind::Wild => {
467                ctor = Wildcard;
468                fields = ::alloc::vec::Vec::new()vec![];
469                arity = 0;
470            }
471            PatKind::Deref { pin, subpattern } => {
472                fields = <[_]>::into_vec(::alloc::boxed::box_new([self.lower_pat(subpattern).at_index(0)]))vec![self.lower_pat(subpattern).at_index(0)];
473                arity = 1;
474                ctor = match (pin, ty.maybe_pinned_ref()) {
475                    (ty::Pinnedness::Not, Some((_, ty::Pinnedness::Not, _, _))) => Ref,
476                    (ty::Pinnedness::Pinned, Some((inner_ty, ty::Pinnedness::Pinned, _, _))) => {
477                        self.internal_state.has_lowered_deref_pat.set(true);
478                        DerefPattern(RevealedTy(inner_ty))
479                    }
480                    _ => ::rustc_middle::util::bug::span_bug_fmt(pat.span,
    format_args!("pattern has unexpected type: pat: {0:?}, ty: {1:?}",
        pat.kind, ty.inner()))span_bug!(
481                        pat.span,
482                        "pattern has unexpected type: pat: {:?}, ty: {:?}",
483                        pat.kind,
484                        ty.inner()
485                    ),
486                };
487            }
488            PatKind::DerefPattern { subpattern, .. } => {
489                // NB(deref_patterns): This assumes the deref pattern is matching on a trusted
490                // `DerefPure` type. If the `Deref` impl isn't trusted, exhaustiveness must take
491                // into account that multiple calls to deref may return different results. Hence
492                // multiple deref! patterns cannot be exhaustive together unless each is exhaustive
493                // by itself.
494                fields = <[_]>::into_vec(::alloc::boxed::box_new([self.lower_pat(subpattern).at_index(0)]))vec![self.lower_pat(subpattern).at_index(0)];
495                arity = 1;
496                ctor = DerefPattern(cx.reveal_opaque_ty(subpattern.ty));
497                self.internal_state.has_lowered_deref_pat.set(true);
498            }
499            PatKind::Leaf { subpatterns } | PatKind::Variant { subpatterns, .. } => {
500                match ty.kind() {
501                    ty::Tuple(fs) => {
502                        ctor = Struct;
503                        arity = fs.len();
504                        fields = subpatterns
505                            .iter()
506                            .map(|ipat| self.lower_pat(&ipat.pattern).at_index(ipat.field.index()))
507                            .collect();
508                    }
509                    ty::Adt(adt, _) => {
510                        ctor = match pat.kind {
511                            PatKind::Leaf { .. } if adt.is_union() => UnionField,
512                            PatKind::Leaf { .. } => Struct,
513                            PatKind::Variant { variant_index, .. } => Variant(variant_index),
514                            _ => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
515                        };
516                        let variant =
517                            &adt.variant(RustcPatCtxt::variant_index_for_adt(&ctor, *adt));
518                        arity = variant.fields.len();
519                        fields = subpatterns
520                            .iter()
521                            .map(|ipat| self.lower_pat(&ipat.pattern).at_index(ipat.field.index()))
522                            .collect();
523                    }
524                    _ => ::rustc_middle::util::bug::span_bug_fmt(pat.span,
    format_args!("pattern has unexpected type: pat: {0:?}, ty: {1}", pat.kind,
        ty.inner()))span_bug!(
525                        pat.span,
526                        "pattern has unexpected type: pat: {:?}, ty: {}",
527                        pat.kind,
528                        ty.inner()
529                    ),
530                }
531            }
532            PatKind::Constant { value } => {
533                match ty.kind() {
534                    ty::Bool => {
535                        ctor = Bool(value.try_to_bool().unwrap());
536                        fields = ::alloc::vec::Vec::new()vec![];
537                        arity = 0;
538                    }
539                    ty::Char | ty::Int(_) | ty::Uint(_) => {
540                        ctor = {
541                            let bits = value.to_leaf().to_bits_unchecked();
542                            let x = match *ty.kind() {
543                                ty::Int(ity) => {
544                                    let size = Integer::from_int_ty(&cx.tcx, ity).size().bits();
545                                    MaybeInfiniteInt::new_finite_int(bits, size)
546                                }
547                                _ => MaybeInfiniteInt::new_finite_uint(bits),
548                            };
549                            IntRange(IntRange::from_singleton(x))
550                        };
551                        fields = ::alloc::vec::Vec::new()vec![];
552                        arity = 0;
553                    }
554                    ty::Float(ty::FloatTy::F16) => {
555                        use rustc_apfloat::Float;
556                        let bits = value.to_leaf().to_u16();
557                        let value = rustc_apfloat::ieee::Half::from_bits(bits.into());
558                        ctor = F16Range(value, value, RangeEnd::Included);
559                        fields = ::alloc::vec::Vec::new()vec![];
560                        arity = 0;
561                    }
562                    ty::Float(ty::FloatTy::F32) => {
563                        use rustc_apfloat::Float;
564                        let bits = value.to_leaf().to_u32();
565                        let value = rustc_apfloat::ieee::Single::from_bits(bits.into());
566                        ctor = F32Range(value, value, RangeEnd::Included);
567                        fields = ::alloc::vec::Vec::new()vec![];
568                        arity = 0;
569                    }
570                    ty::Float(ty::FloatTy::F64) => {
571                        use rustc_apfloat::Float;
572                        let bits = value.to_leaf().to_u64();
573                        let value = rustc_apfloat::ieee::Double::from_bits(bits.into());
574                        ctor = F64Range(value, value, RangeEnd::Included);
575                        fields = ::alloc::vec::Vec::new()vec![];
576                        arity = 0;
577                    }
578                    ty::Float(ty::FloatTy::F128) => {
579                        use rustc_apfloat::Float;
580                        let bits = value.to_leaf().to_u128();
581                        let value = rustc_apfloat::ieee::Quad::from_bits(bits);
582                        ctor = F128Range(value, value, RangeEnd::Included);
583                        fields = ::alloc::vec::Vec::new()vec![];
584                        arity = 0;
585                    }
586                    ty::Str => {
587                        // For constant/literal patterns of type `&str`, the THIR
588                        // pattern is a `PatKind::Deref` of type `&str` wrapping a
589                        // `PatKind::Const` of type `str`.
590                        ctor = Str(*value);
591                        fields = ::alloc::vec::Vec::new()vec![];
592                        arity = 0;
593                    }
594                    // All constants that can be structurally matched have already been expanded
595                    // into the corresponding `Pat`s by `const_to_pat`. Constants that remain are
596                    // opaque.
597                    _ => {
598                        ctor = Opaque(OpaqueId::new());
599                        fields = ::alloc::vec::Vec::new()vec![];
600                        arity = 0;
601                    }
602                }
603            }
604            PatKind::Range(patrange) => {
605                let PatRange { lo, hi, end, .. } = patrange.as_ref();
606                let end = match end {
607                    rustc_hir::RangeEnd::Included => RangeEnd::Included,
608                    rustc_hir::RangeEnd::Excluded => RangeEnd::Excluded,
609                };
610                ctor = match ty.kind() {
611                    ty::Char | ty::Int(_) | ty::Uint(_) => {
612                        let lo = cx.lower_pat_range_bdy(*lo, ty);
613                        let hi = cx.lower_pat_range_bdy(*hi, ty);
614                        IntRange(IntRange::from_range(lo, hi, end))
615                    }
616                    ty::Float(fty) => {
617                        use rustc_apfloat::Float;
618                        let lo = lo.as_finite().map(|c| c.to_leaf().to_bits_unchecked());
619                        let hi = hi.as_finite().map(|c| c.to_leaf().to_bits_unchecked());
620                        match fty {
621                            ty::FloatTy::F16 => {
622                                use rustc_apfloat::ieee::Half;
623                                let lo = lo.map(Half::from_bits).unwrap_or(-Half::INFINITY);
624                                let hi = hi.map(Half::from_bits).unwrap_or(Half::INFINITY);
625                                F16Range(lo, hi, end)
626                            }
627                            ty::FloatTy::F32 => {
628                                use rustc_apfloat::ieee::Single;
629                                let lo = lo.map(Single::from_bits).unwrap_or(-Single::INFINITY);
630                                let hi = hi.map(Single::from_bits).unwrap_or(Single::INFINITY);
631                                F32Range(lo, hi, end)
632                            }
633                            ty::FloatTy::F64 => {
634                                use rustc_apfloat::ieee::Double;
635                                let lo = lo.map(Double::from_bits).unwrap_or(-Double::INFINITY);
636                                let hi = hi.map(Double::from_bits).unwrap_or(Double::INFINITY);
637                                F64Range(lo, hi, end)
638                            }
639                            ty::FloatTy::F128 => {
640                                use rustc_apfloat::ieee::Quad;
641                                let lo = lo.map(Quad::from_bits).unwrap_or(-Quad::INFINITY);
642                                let hi = hi.map(Quad::from_bits).unwrap_or(Quad::INFINITY);
643                                F128Range(lo, hi, end)
644                            }
645                        }
646                    }
647                    _ => ::rustc_middle::util::bug::span_bug_fmt(pat.span,
    format_args!("invalid type for range pattern: {0}", ty.inner()))span_bug!(pat.span, "invalid type for range pattern: {}", ty.inner()),
648                };
649                fields = ::alloc::vec::Vec::new()vec![];
650                arity = 0;
651            }
652            PatKind::Array { prefix, slice, suffix } | PatKind::Slice { prefix, slice, suffix } => {
653                let array_len = match ty.kind() {
654                    ty::Array(_, length) => Some(
655                        length
656                            .try_to_target_usize(cx.tcx)
657                            .expect("expected len of array pat to be definite")
658                            as usize,
659                    ),
660                    ty::Slice(_) => None,
661                    _ => ::rustc_middle::util::bug::span_bug_fmt(pat.span,
    format_args!("bad ty {0} for slice pattern", ty.inner()))span_bug!(pat.span, "bad ty {} for slice pattern", ty.inner()),
662                };
663                let kind = if slice.is_some() {
664                    SliceKind::VarLen(prefix.len(), suffix.len())
665                } else {
666                    SliceKind::FixedLen(prefix.len() + suffix.len())
667                };
668                ctor = Slice(Slice::new(array_len, kind));
669                fields = prefix
670                    .iter()
671                    .chain(suffix.iter())
672                    .map(|p| self.lower_pat(&*p))
673                    .enumerate()
674                    .map(|(i, p)| p.at_index(i))
675                    .collect();
676                arity = kind.arity();
677            }
678            PatKind::Or { .. } => {
679                ctor = Or;
680                let pats = expand_or_pat(pat);
681                fields = pats
682                    .into_iter()
683                    .map(|p| self.lower_pat(p))
684                    .enumerate()
685                    .map(|(i, p)| p.at_index(i))
686                    .collect();
687                arity = fields.len();
688            }
689            PatKind::Never => {
690                // A never pattern matches all the values of its type (namely none). Moreover it
691                // must be compatible with other constructors, since we can use `!` on a type like
692                // `Result<!, !>` which has other constructors. Hence we lower it as a wildcard.
693                ctor = Wildcard;
694                fields = ::alloc::vec::Vec::new()vec![];
695                arity = 0;
696            }
697            PatKind::Error(_) => {
698                ctor = Opaque(OpaqueId::new());
699                fields = ::alloc::vec::Vec::new()vec![];
700                arity = 0;
701            }
702        }
703        DeconstructedPat::new(ctor, fields, arity, ty, pat)
704    }
705
706    /// Convert back to a `thir::PatRangeBoundary` for diagnostic purposes.
707    /// Note: it is possible to get `isize/usize::MAX+1` here, as explained in the doc for
708    /// [`IntRange::split`]. This cannot be represented as a `Const`, so we represent it with
709    /// `PosInfinity`.
710    fn hoist_pat_range_bdy(
711        &self,
712        miint: MaybeInfiniteInt,
713        ty: RevealedTy<'tcx>,
714    ) -> PatRangeBoundary<'tcx> {
715        use MaybeInfiniteInt::*;
716        let tcx = self.tcx;
717        match miint {
718            NegInfinity => PatRangeBoundary::NegInfinity,
719            Finite(_) => {
720                let size = ty.primitive_size(tcx);
721                let bits = match *ty.kind() {
722                    ty::Int(_) => miint.as_finite_int(size.bits()).unwrap(),
723                    _ => miint.as_finite_uint().unwrap(),
724                };
725                match ScalarInt::try_from_uint(bits, size) {
726                    Some(scalar) => {
727                        let valtree = ty::ValTree::from_scalar_int(tcx, scalar);
728                        PatRangeBoundary::Finite(valtree)
729                    }
730                    // The value doesn't fit. Since `x >= 0` and 0 always encodes the minimum value
731                    // for a type, the problem isn't that the value is too small. So it must be too
732                    // large.
733                    None => PatRangeBoundary::PosInfinity,
734                }
735            }
736            PosInfinity => PatRangeBoundary::PosInfinity,
737        }
738    }
739
740    /// Prints an [`IntRange`] to a string for diagnostic purposes.
741    fn print_pat_range(&self, range: &IntRange, ty: RevealedTy<'tcx>) -> String {
742        use MaybeInfiniteInt::*;
743        let cx = self;
744        if #[allow(non_exhaustive_omitted_patterns)] match (range.lo, range.hi) {
    (NegInfinity, PosInfinity) => true,
    _ => false,
}matches!((range.lo, range.hi), (NegInfinity, PosInfinity)) {
745            "_".to_string()
746        } else if range.is_singleton() {
747            let lo = cx.hoist_pat_range_bdy(range.lo, ty);
748            let value = ty::Value { ty: ty.inner(), valtree: lo.as_finite().unwrap() };
749            value.to_string()
750        } else {
751            // We convert to an inclusive range for diagnostics.
752            let mut end = rustc_hir::RangeEnd::Included;
753            let mut lo = cx.hoist_pat_range_bdy(range.lo, ty);
754            if #[allow(non_exhaustive_omitted_patterns)] match lo {
    PatRangeBoundary::PosInfinity => true,
    _ => false,
}matches!(lo, PatRangeBoundary::PosInfinity) {
755                // The only reason to get `PosInfinity` here is the special case where
756                // `hoist_pat_range_bdy` found `{u,i}size::MAX+1`. So the range denotes the
757                // fictitious values after `{u,i}size::MAX` (see [`IntRange::split`] for why we do
758                // this). We show this to the user as `usize::MAX..` which is slightly incorrect but
759                // probably clear enough.
760                let max = ty.numeric_max_val(cx.tcx).unwrap();
761                let max = ty::ValTree::from_scalar_int(cx.tcx, max.try_to_scalar_int().unwrap());
762                lo = PatRangeBoundary::Finite(max);
763            }
764            let hi = if let Some(hi) = range.hi.minus_one() {
765                hi
766            } else {
767                // The range encodes `..ty::MIN`, so we can't convert it to an inclusive range.
768                end = rustc_hir::RangeEnd::Excluded;
769                range.hi
770            };
771            let hi = cx.hoist_pat_range_bdy(hi, ty);
772            PatRange { lo, hi, end, ty: ty.inner() }.to_string()
773        }
774    }
775
776    /// Prints a [`WitnessPat`] to an owned string, for diagnostic purposes.
777    ///
778    /// This panics for patterns that don't appear in diagnostics, like float ranges.
779    pub fn print_witness_pat(&self, pat: &WitnessPat<'p, 'tcx>) -> String {
780        let cx = self;
781        let print = |p| cx.print_witness_pat(p);
782        match pat.ctor() {
783            Bool(b) => b.to_string(),
784            Str(s) => s.to_string(),
785            IntRange(range) => return self.print_pat_range(range, *pat.ty()),
786            Struct | Variant(_) | UnionField => {
787                let enum_info = match *pat.ty().kind() {
788                    ty::Adt(adt_def, _) if adt_def.is_enum() => EnumInfo::Enum {
789                        adt_def,
790                        variant_index: RustcPatCtxt::variant_index_for_adt(pat.ctor(), adt_def),
791                    },
792                    ty::Adt(..) | ty::Tuple(..) => EnumInfo::NotEnum,
793                    _ => ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected ctor for type {0:?} {1:?}",
        pat.ctor(), *pat.ty()))bug!("unexpected ctor for type {:?} {:?}", pat.ctor(), *pat.ty()),
794                };
795
796                let subpatterns = pat
797                    .iter_fields()
798                    .enumerate()
799                    .map(|(i, pat)| print::FieldPat {
800                        field: FieldIdx::new(i),
801                        pattern: print(pat),
802                        is_wildcard: would_print_as_wildcard(cx.tcx, pat),
803                    })
804                    .collect::<Vec<_>>();
805
806                let mut s = String::new();
807                print::write_struct_like(
808                    &mut s,
809                    self.tcx,
810                    pat.ty().inner(),
811                    &enum_info,
812                    &subpatterns,
813                )
814                .unwrap();
815                s
816            }
817            Ref => {
818                let mut s = String::new();
819                print::write_ref_like(&mut s, pat.ty().inner(), &print(&pat.fields[0])).unwrap();
820                s
821            }
822            DerefPattern(_) if pat.ty().is_box() && !self.tcx.features().deref_patterns() => {
823                // FIXME(deref_patterns): Remove this special handling once `box_patterns` is gone.
824                // HACK(@dianne): `box _` syntax is exposed on stable in diagnostics, e.g. to
825                // witness non-exhaustiveness of `match Box::new(0) { Box { .. } if false => {} }`.
826                // To avoid changing diagnostics before deref pattern syntax is finalized, let's use
827                // `box _` syntax unless `deref_patterns` is enabled.
828                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("box {0}", print(&pat.fields[0])))
    })format!("box {}", print(&pat.fields[0]))
829            }
830            DerefPattern(_) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("deref!({0})",
                print(&pat.fields[0])))
    })format!("deref!({})", print(&pat.fields[0])),
831            Slice(slice) => {
832                let (prefix_len, has_dot_dot) = match slice.kind {
833                    SliceKind::FixedLen(len) => (len, false),
834                    SliceKind::VarLen(prefix_len, _) => (prefix_len, true),
835                };
836
837                let (mut prefix, mut suffix) = pat.fields.split_at(prefix_len);
838
839                // If the pattern contains a `..`, but is applied to values of statically-known
840                // length (arrays), then we can slightly simplify diagnostics by merging any
841                // adjacent wildcard patterns into the `..`: `[x, _, .., _, y]` => `[x, .., y]`.
842                // (This simplification isn't allowed for slice values, because in that case
843                // `[x, .., y]` would match some slices that `[x, _, .., _, y]` would not.)
844                if has_dot_dot && slice.array_len.is_some() {
845                    while let [rest @ .., last] = prefix
846                        && would_print_as_wildcard(cx.tcx, last)
847                    {
848                        prefix = rest;
849                    }
850                    while let [first, rest @ ..] = suffix
851                        && would_print_as_wildcard(cx.tcx, first)
852                    {
853                        suffix = rest;
854                    }
855                }
856
857                let prefix = prefix.iter().map(print).collect::<Vec<_>>();
858                let suffix = suffix.iter().map(print).collect::<Vec<_>>();
859
860                let mut s = String::new();
861                print::write_slice_like(&mut s, &prefix, has_dot_dot, &suffix).unwrap();
862                s
863            }
864            Never if self.tcx.features().never_patterns() => "!".to_string(),
865            Never | Wildcard | NonExhaustive | Hidden | PrivateUninhabited => "_".to_string(),
866            Missing { .. } => ::rustc_middle::util::bug::bug_fmt(format_args!("trying to convert a `Missing` constructor into a `Pat`; this is probably a bug,\n                `Missing` should have been processed in `apply_constructors`"))bug!(
867                "trying to convert a `Missing` constructor into a `Pat`; this is probably a bug,
868                `Missing` should have been processed in `apply_constructors`"
869            ),
870            F16Range(..) | F32Range(..) | F64Range(..) | F128Range(..) | Opaque(..) | Or => {
871                ::rustc_middle::util::bug::bug_fmt(format_args!("can\'t convert to pattern: {0:?}",
        pat))bug!("can't convert to pattern: {:?}", pat)
872            }
873        }
874    }
875}
876
877/// Returns `true` if the given pattern would be printed as a wildcard (`_`).
878fn would_print_as_wildcard(tcx: TyCtxt<'_>, p: &WitnessPat<'_, '_>) -> bool {
879    match p.ctor() {
880        Constructor::IntRange(IntRange {
881            lo: MaybeInfiniteInt::NegInfinity,
882            hi: MaybeInfiniteInt::PosInfinity,
883        })
884        | Constructor::Wildcard
885        | Constructor::NonExhaustive
886        | Constructor::Hidden
887        | Constructor::PrivateUninhabited => true,
888        Constructor::Never if !tcx.features().never_patterns() => true,
889        _ => false,
890    }
891}
892
893impl<'p, 'tcx: 'p> PatCx for RustcPatCtxt<'p, 'tcx> {
894    type Ty = RevealedTy<'tcx>;
895    type Error = ErrorGuaranteed;
896    type VariantIdx = VariantIdx;
897    type StrLit = ty::Value<'tcx>;
898    type ArmData = HirId;
899    type PatData = &'p Pat<'tcx>;
900
901    fn is_exhaustive_patterns_feature_on(&self) -> bool {
902        self.tcx.features().exhaustive_patterns()
903    }
904
905    fn ctor_arity(&self, ctor: &crate::constructor::Constructor<Self>, ty: &Self::Ty) -> usize {
906        self.ctor_arity(ctor, *ty)
907    }
908    fn ctor_sub_tys(
909        &self,
910        ctor: &crate::constructor::Constructor<Self>,
911        ty: &Self::Ty,
912    ) -> impl Iterator<Item = (Self::Ty, PrivateUninhabitedField)> + ExactSizeIterator {
913        self.ctor_sub_tys(ctor, *ty)
914    }
915    fn ctors_for_ty(
916        &self,
917        ty: &Self::Ty,
918    ) -> Result<crate::constructor::ConstructorSet<Self>, Self::Error> {
919        self.ctors_for_ty(*ty)
920    }
921
922    fn write_variant_name(
923        f: &mut fmt::Formatter<'_>,
924        ctor: &crate::constructor::Constructor<Self>,
925        ty: &Self::Ty,
926    ) -> fmt::Result {
927        if let ty::Adt(adt, _) = ty.kind() {
928            let variant = adt.variant(Self::variant_index_for_adt(ctor, *adt));
929            f.write_fmt(format_args!("{0}", variant.name))write!(f, "{}", variant.name)?;
930        }
931        Ok(())
932    }
933
934    fn bug(&self, fmt: fmt::Arguments<'_>) -> Self::Error {
935        ::rustc_middle::util::bug::span_bug_fmt(self.scrut_span,
    format_args!("{0}", fmt))span_bug!(self.scrut_span, "{}", fmt)
936    }
937
938    fn lint_overlapping_range_endpoints(
939        &self,
940        pat: &crate::pat::DeconstructedPat<Self>,
941        overlaps_on: IntRange,
942        overlaps_with: &[&crate::pat::DeconstructedPat<Self>],
943    ) {
944        let overlap_as_pat = self.print_pat_range(&overlaps_on, *pat.ty());
945        let overlaps: Vec<_> = overlaps_with
946            .iter()
947            .map(|pat| pat.data().span)
948            .map(|span| errors::Overlap { range: overlap_as_pat.to_string(), span })
949            .collect();
950        let pat_span = pat.data().span;
951        self.tcx.emit_node_span_lint(
952            lint::builtin::OVERLAPPING_RANGE_ENDPOINTS,
953            self.match_lint_level,
954            pat_span,
955            errors::OverlappingRangeEndpoints { overlap: overlaps, range: pat_span },
956        );
957    }
958
959    fn complexity_exceeded(&self) -> Result<(), Self::Error> {
960        let span = self.whole_match_span.unwrap_or(self.scrut_span);
961        Err(self.tcx.dcx().span_err(span, "reached pattern complexity limit"))
962    }
963
964    fn lint_non_contiguous_range_endpoints(
965        &self,
966        pat: &crate::pat::DeconstructedPat<Self>,
967        gap: IntRange,
968        gapped_with: &[&crate::pat::DeconstructedPat<Self>],
969    ) {
970        let &thir_pat = pat.data();
971        let thir::PatKind::Range(range) = &thir_pat.kind else { return };
972        // Only lint when the left range is an exclusive range.
973        if range.end != rustc_hir::RangeEnd::Excluded {
974            return;
975        }
976        // `pat` is an exclusive range like `lo..gap`. `gapped_with` contains ranges that start with
977        // `gap+1`.
978        let suggested_range: String = {
979            // Suggest `lo..=gap` instead.
980            let mut suggested_range = PatRange::clone(range);
981            suggested_range.end = rustc_hir::RangeEnd::Included;
982            suggested_range.to_string()
983        };
984        let gap_as_pat = self.print_pat_range(&gap, *pat.ty());
985        if gapped_with.is_empty() {
986            // If `gapped_with` is empty, `gap == T::MAX`.
987            self.tcx.emit_node_span_lint(
988                lint::builtin::NON_CONTIGUOUS_RANGE_ENDPOINTS,
989                self.match_lint_level,
990                thir_pat.span,
991                errors::ExclusiveRangeMissingMax {
992                    // Point at this range.
993                    first_range: thir_pat.span,
994                    // That's the gap that isn't covered.
995                    max: gap_as_pat,
996                    // Suggest `lo..=max` instead.
997                    suggestion: suggested_range,
998                },
999            );
1000        } else {
1001            self.tcx.emit_node_span_lint(
1002                lint::builtin::NON_CONTIGUOUS_RANGE_ENDPOINTS,
1003                self.match_lint_level,
1004                thir_pat.span,
1005                errors::ExclusiveRangeMissingGap {
1006                    // Point at this range.
1007                    first_range: thir_pat.span,
1008                    // That's the gap that isn't covered.
1009                    gap: gap_as_pat.to_string(),
1010                    // Suggest `lo..=gap` instead.
1011                    suggestion: suggested_range,
1012                    // All these ranges skipped over `gap` which we think is probably a
1013                    // mistake.
1014                    gap_with: gapped_with
1015                        .iter()
1016                        .map(|pat| errors::GappedRange {
1017                            span: pat.data().span,
1018                            gap: gap_as_pat.to_string(),
1019                            first_range: range.to_string(),
1020                        })
1021                        .collect(),
1022                },
1023            );
1024        }
1025    }
1026
1027    fn match_may_contain_deref_pats(&self) -> bool {
1028        self.internal_state.has_lowered_deref_pat.get()
1029    }
1030
1031    fn report_mixed_deref_pat_ctors(
1032        &self,
1033        deref_pat: &crate::pat::DeconstructedPat<Self>,
1034        normal_pat: &crate::pat::DeconstructedPat<Self>,
1035    ) -> Self::Error {
1036        let deref_pattern_label = deref_pat.data().span;
1037        let normal_constructor_label = normal_pat.data().span;
1038        self.tcx.dcx().emit_err(errors::MixedDerefPatternConstructors {
1039            spans: <[_]>::into_vec(::alloc::boxed::box_new([deref_pattern_label,
                normal_constructor_label]))vec![deref_pattern_label, normal_constructor_label],
1040            smart_pointer_ty: deref_pat.ty().inner(),
1041            deref_pattern_label,
1042            normal_constructor_label,
1043        })
1044    }
1045}
1046
1047/// Recursively expand this pattern into its subpatterns. Only useful for or-patterns.
1048fn expand_or_pat<'p, 'tcx>(pat: &'p Pat<'tcx>) -> Vec<&'p Pat<'tcx>> {
1049    fn expand<'p, 'tcx>(pat: &'p Pat<'tcx>, vec: &mut Vec<&'p Pat<'tcx>>) {
1050        if let PatKind::Or { pats } = &pat.kind {
1051            for pat in pats.iter() {
1052                expand(pat, vec);
1053            }
1054        } else {
1055            vec.push(pat)
1056        }
1057    }
1058
1059    let mut pats = Vec::new();
1060    expand(pat, &mut pats);
1061    pats
1062}
1063
1064/// The entrypoint for this crate. Computes whether a match is exhaustive and which of its arms are
1065/// useful, and runs some lints.
1066pub fn analyze_match<'p, 'tcx>(
1067    tycx: &RustcPatCtxt<'p, 'tcx>,
1068    arms: &[MatchArm<'p, 'tcx>],
1069    scrut_ty: Ty<'tcx>,
1070) -> Result<UsefulnessReport<'p, 'tcx>, ErrorGuaranteed> {
1071    let scrut_ty = tycx.reveal_opaque_ty(scrut_ty);
1072
1073    let scrut_validity = PlaceValidity::from_bool(tycx.known_valid_scrutinee);
1074    let report = compute_match_usefulness(
1075        tycx,
1076        arms,
1077        scrut_ty,
1078        scrut_validity,
1079        tycx.tcx.pattern_complexity_limit().0,
1080    )?;
1081
1082    // Run the non_exhaustive_omitted_patterns lint. Only run on refutable patterns to avoid hitting
1083    // `if let`s. Only run if the match is exhaustive otherwise the error is redundant.
1084    if tycx.refutable && report.non_exhaustiveness_witnesses.is_empty() {
1085        let pat_column = PatternColumn::new(arms);
1086        lint_nonexhaustive_missing_variants(tycx, arms, &pat_column, scrut_ty)?;
1087    }
1088
1089    Ok(report)
1090}