Skip to main content

rustc_pattern_analysis/
lib.rs

1//! Analysis of patterns, notably match exhaustiveness checking. The main entrypoint for this crate
2//! is [`usefulness::compute_match_usefulness`]. For rustc-specific types and entrypoints, see the
3//! [`rustc`] module.
4
5// tidy-alphabetical-start
6#![allow(unused_crate_dependencies)]
7#![cfg_attr(feature = "rustc", feature(if_let_guard))]
8// tidy-alphabetical-end
9
10pub(crate) mod checks;
11pub mod constructor;
12#[cfg(feature = "rustc")]
13pub mod errors;
14#[cfg(feature = "rustc")]
15pub(crate) mod lints;
16pub mod pat;
17pub mod pat_column;
18#[cfg(feature = "rustc")]
19pub mod rustc;
20pub mod usefulness;
21
22use std::fmt;
23
24pub use rustc_index::{Idx, IndexVec}; // re-exported to avoid rustc_index version issues
25
26use crate::constructor::{Constructor, ConstructorSet, IntRange};
27use crate::pat::DeconstructedPat;
28
29pub trait Captures<'a> {}
30impl<'a, T: ?Sized> Captures<'a> for T {}
31
32/// `bool` newtype that indicates whether this is a privately uninhabited field that we should skip
33/// during analysis.
34#[derive(#[automatically_derived]
impl ::core::marker::Copy for PrivateUninhabitedField { }Copy, #[automatically_derived]
impl ::core::clone::Clone for PrivateUninhabitedField {
    #[inline]
    fn clone(&self) -> PrivateUninhabitedField {
        let _: ::core::clone::AssertParamIsClone<bool>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for PrivateUninhabitedField {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_tuple_field1_finish(f,
            "PrivateUninhabitedField", &&self.0)
    }
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for PrivateUninhabitedField {
    #[inline]
    fn eq(&self, other: &PrivateUninhabitedField) -> bool {
        self.0 == other.0
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for PrivateUninhabitedField {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_receiver_is_total_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<bool>;
    }
}Eq)]
35pub struct PrivateUninhabitedField(pub bool);
36
37/// Context that provides type information about constructors.
38///
39/// Most of the crate is parameterized on a type that implements this trait.
40pub trait PatCx: Sized + fmt::Debug {
41    /// The type of a pattern.
42    type Ty: Clone + fmt::Debug;
43    /// Errors that can abort analysis.
44    type Error: fmt::Debug;
45    /// The index of an enum variant.
46    type VariantIdx: Clone + Idx + fmt::Debug;
47    /// A string literal
48    type StrLit: Clone + PartialEq + fmt::Debug;
49    /// Extra data to store in a match arm.
50    type ArmData: Copy + Clone + fmt::Debug;
51    /// Extra data to store in a pattern.
52    type PatData: Clone;
53
54    fn is_exhaustive_patterns_feature_on(&self) -> bool;
55
56    /// Whether to ensure the non-exhaustiveness witnesses we report for a complete set. This is
57    /// `false` by default to avoid some exponential blowup cases such as
58    /// <https://github.com/rust-lang/rust/issues/118437>.
59    fn exhaustive_witnesses(&self) -> bool {
60        false
61    }
62
63    /// The number of fields for this constructor.
64    fn ctor_arity(&self, ctor: &Constructor<Self>, ty: &Self::Ty) -> usize;
65
66    /// The types of the fields for this constructor. The result must contain `ctor_arity()` fields.
67    fn ctor_sub_tys(
68        &self,
69        ctor: &Constructor<Self>,
70        ty: &Self::Ty,
71    ) -> impl Iterator<Item = (Self::Ty, PrivateUninhabitedField)> + ExactSizeIterator;
72
73    /// The set of all the constructors for `ty`.
74    ///
75    /// This must follow the invariants of `ConstructorSet`
76    fn ctors_for_ty(&self, ty: &Self::Ty) -> Result<ConstructorSet<Self>, Self::Error>;
77
78    /// Write the name of the variant represented by `pat`. Used for the best-effort `Debug` impl of
79    /// `DeconstructedPat`. Only invoqued when `pat.ctor()` is `Struct | Variant(_) | UnionField`.
80    fn write_variant_name(
81        f: &mut fmt::Formatter<'_>,
82        ctor: &crate::constructor::Constructor<Self>,
83        ty: &Self::Ty,
84    ) -> fmt::Result;
85
86    /// Raise a bug.
87    fn bug(&self, fmt: fmt::Arguments<'_>) -> Self::Error;
88
89    /// Lint that the range `pat` overlapped with all the ranges in `overlaps_with`, where the range
90    /// they overlapped over is `overlaps_on`. We only detect singleton overlaps.
91    /// The default implementation does nothing.
92    fn lint_overlapping_range_endpoints(
93        &self,
94        _pat: &DeconstructedPat<Self>,
95        _overlaps_on: IntRange,
96        _overlaps_with: &[&DeconstructedPat<Self>],
97    ) {
98    }
99
100    /// The maximum pattern complexity limit was reached.
101    fn complexity_exceeded(&self) -> Result<(), Self::Error>;
102
103    /// Lint that there is a gap `gap` between `pat` and all of `gapped_with` such that the gap is
104    /// not matched by another range. If `gapped_with` is empty, then `gap` is `T::MAX`. We only
105    /// detect singleton gaps.
106    /// The default implementation does nothing.
107    fn lint_non_contiguous_range_endpoints(
108        &self,
109        _pat: &DeconstructedPat<Self>,
110        _gap: IntRange,
111        _gapped_with: &[&DeconstructedPat<Self>],
112    ) {
113    }
114
115    /// Check if we may need to perform additional deref-pattern-specific validation.
116    fn match_may_contain_deref_pats(&self) -> bool {
117        true
118    }
119
120    /// The current implementation of deref patterns requires that they can't match on the same
121    /// place as a normal constructor. Since this isn't caught by type-checking, we check it in the
122    /// `PatCx` before running the analysis. This reports an error if the check fails.
123    fn report_mixed_deref_pat_ctors(
124        &self,
125        deref_pat: &DeconstructedPat<Self>,
126        normal_pat: &DeconstructedPat<Self>,
127    ) -> Self::Error;
128}
129
130/// The arm of a match expression.
131#[derive(#[automatically_derived]
impl<'p, Cx: ::core::fmt::Debug + PatCx> ::core::fmt::Debug for
    MatchArm<'p, Cx> where Cx::ArmData: ::core::fmt::Debug {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f, "MatchArm",
            "pat", &self.pat, "has_guard", &self.has_guard, "arm_data",
            &&self.arm_data)
    }
}Debug)]
132pub struct MatchArm<'p, Cx: PatCx> {
133    pub pat: &'p DeconstructedPat<Cx>,
134    pub has_guard: bool,
135    pub arm_data: Cx::ArmData,
136}
137
138impl<'p, Cx: PatCx> Clone for MatchArm<'p, Cx> {
139    fn clone(&self) -> Self {
140        *self
141    }
142}
143
144impl<'p, Cx: PatCx> Copy for MatchArm<'p, Cx> {}