Skip to main content

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