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(rustc::diagnostic_outside_of_impl)]
7#![allow(rustc::untranslatable_diagnostic)]
8#![allow(unused_crate_dependencies)]
9// tidy-alphabetical-end
10
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
22#[cfg(feature = "rustc")]
23rustc_fluent_macro::fluent_messages! { "../messages.ftl" }
24
25use std::fmt;
26
27pub use rustc_index::{Idx, IndexVec}; // re-exported to avoid rustc_index version issues
28
29use crate::constructor::{Constructor, ConstructorSet, IntRange};
30use crate::pat::DeconstructedPat;
31
32pub trait Captures<'a> {}
33impl<'a, T: ?Sized> Captures<'a> for T {}
34
35/// `bool` newtype that indicates whether this is a privately uninhabited field that we should skip
36/// during analysis.
37#[derive(Copy, Clone, Debug, PartialEq, Eq)]
38pub struct PrivateUninhabitedField(pub bool);
39
40/// Context that provides type information about constructors.
41///
42/// Most of the crate is parameterized on a type that implements this trait.
43pub trait PatCx: Sized + fmt::Debug {
44    /// The type of a pattern.
45    type Ty: Clone + fmt::Debug;
46    /// Errors that can abort analysis.
47    type Error: fmt::Debug;
48    /// The index of an enum variant.
49    type VariantIdx: Clone + Idx + fmt::Debug;
50    /// A string literal
51    type StrLit: Clone + PartialEq + fmt::Debug;
52    /// Extra data to store in a match arm.
53    type ArmData: Copy + Clone + fmt::Debug;
54    /// Extra data to store in a pattern.
55    type PatData: Clone;
56
57    fn is_exhaustive_patterns_feature_on(&self) -> bool;
58
59    /// The number of fields for this constructor.
60    fn ctor_arity(&self, ctor: &Constructor<Self>, ty: &Self::Ty) -> usize;
61
62    /// The types of the fields for this constructor. The result must contain `ctor_arity()` fields.
63    fn ctor_sub_tys(
64        &self,
65        ctor: &Constructor<Self>,
66        ty: &Self::Ty,
67    ) -> impl Iterator<Item = (Self::Ty, PrivateUninhabitedField)> + ExactSizeIterator;
68
69    /// The set of all the constructors for `ty`.
70    ///
71    /// This must follow the invariants of `ConstructorSet`
72    fn ctors_for_ty(&self, ty: &Self::Ty) -> Result<ConstructorSet<Self>, Self::Error>;
73
74    /// Write the name of the variant represented by `pat`. Used for the best-effort `Debug` impl of
75    /// `DeconstructedPat`. Only invoqued when `pat.ctor()` is `Struct | Variant(_) | UnionField`.
76    fn write_variant_name(
77        f: &mut fmt::Formatter<'_>,
78        ctor: &crate::constructor::Constructor<Self>,
79        ty: &Self::Ty,
80    ) -> fmt::Result;
81
82    /// Raise a bug.
83    fn bug(&self, fmt: fmt::Arguments<'_>) -> Self::Error;
84
85    /// Lint that the range `pat` overlapped with all the ranges in `overlaps_with`, where the range
86    /// they overlapped over is `overlaps_on`. We only detect singleton overlaps.
87    /// The default implementation does nothing.
88    fn lint_overlapping_range_endpoints(
89        &self,
90        _pat: &DeconstructedPat<Self>,
91        _overlaps_on: IntRange,
92        _overlaps_with: &[&DeconstructedPat<Self>],
93    ) {
94    }
95
96    /// The maximum pattern complexity limit was reached.
97    fn complexity_exceeded(&self) -> Result<(), Self::Error>;
98
99    /// Lint that there is a gap `gap` between `pat` and all of `gapped_with` such that the gap is
100    /// not matched by another range. If `gapped_with` is empty, then `gap` is `T::MAX`. We only
101    /// detect singleton gaps.
102    /// The default implementation does nothing.
103    fn lint_non_contiguous_range_endpoints(
104        &self,
105        _pat: &DeconstructedPat<Self>,
106        _gap: IntRange,
107        _gapped_with: &[&DeconstructedPat<Self>],
108    ) {
109    }
110}
111
112/// The arm of a match expression.
113#[derive(Debug)]
114pub struct MatchArm<'p, Cx: PatCx> {
115    pub pat: &'p DeconstructedPat<Cx>,
116    pub has_guard: bool,
117    pub arm_data: Cx::ArmData,
118}
119
120impl<'p, Cx: PatCx> Clone for MatchArm<'p, Cx> {
121    fn clone(&self) -> Self {
122        Self { pat: self.pat, has_guard: self.has_guard, arm_data: self.arm_data }
123    }
124}
125
126impl<'p, Cx: PatCx> Copy for MatchArm<'p, Cx> {}