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