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