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#![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
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    /// Whether to ensure the non-exhaustiveness witnesses we report for a complete set. This is
60    /// `false` by default to avoid some exponential blowup cases such as
61    /// <https://github.com/rust-lang/rust/issues/118437>.
62    fn exhaustive_witnesses(&self) -> bool {
63        false
64    }
65
66    /// The number of fields for this constructor.
67    fn ctor_arity(&self, ctor: &Constructor<Self>, ty: &Self::Ty) -> usize;
68
69    /// The types of the fields for this constructor. The result must contain `ctor_arity()` fields.
70    fn ctor_sub_tys(
71        &self,
72        ctor: &Constructor<Self>,
73        ty: &Self::Ty,
74    ) -> impl Iterator<Item = (Self::Ty, PrivateUninhabitedField)> + ExactSizeIterator;
75
76    /// The set of all the constructors for `ty`.
77    ///
78    /// This must follow the invariants of `ConstructorSet`
79    fn ctors_for_ty(&self, ty: &Self::Ty) -> Result<ConstructorSet<Self>, Self::Error>;
80
81    /// Write the name of the variant represented by `pat`. Used for the best-effort `Debug` impl of
82    /// `DeconstructedPat`. Only invoqued when `pat.ctor()` is `Struct | Variant(_) | UnionField`.
83    fn write_variant_name(
84        f: &mut fmt::Formatter<'_>,
85        ctor: &crate::constructor::Constructor<Self>,
86        ty: &Self::Ty,
87    ) -> fmt::Result;
88
89    /// Raise a bug.
90    fn bug(&self, fmt: fmt::Arguments<'_>) -> Self::Error;
91
92    /// Lint that the range `pat` overlapped with all the ranges in `overlaps_with`, where the range
93    /// they overlapped over is `overlaps_on`. We only detect singleton overlaps.
94    /// The default implementation does nothing.
95    fn lint_overlapping_range_endpoints(
96        &self,
97        _pat: &DeconstructedPat<Self>,
98        _overlaps_on: IntRange,
99        _overlaps_with: &[&DeconstructedPat<Self>],
100    ) {
101    }
102
103    /// The maximum pattern complexity limit was reached.
104    fn complexity_exceeded(&self) -> Result<(), Self::Error>;
105
106    /// Lint that there is a gap `gap` between `pat` and all of `gapped_with` such that the gap is
107    /// not matched by another range. If `gapped_with` is empty, then `gap` is `T::MAX`. We only
108    /// detect singleton gaps.
109    /// The default implementation does nothing.
110    fn lint_non_contiguous_range_endpoints(
111        &self,
112        _pat: &DeconstructedPat<Self>,
113        _gap: IntRange,
114        _gapped_with: &[&DeconstructedPat<Self>],
115    ) {
116    }
117
118    /// Check if we may need to perform additional deref-pattern-specific validation.
119    fn match_may_contain_deref_pats(&self) -> bool {
120        true
121    }
122
123    /// The current implementation of deref patterns requires that they can't match on the same
124    /// place as a normal constructor. Since this isn't caught by type-checking, we check it in the
125    /// `PatCx` before running the analysis. This reports an error if the check fails.
126    fn report_mixed_deref_pat_ctors(
127        &self,
128        deref_pat: &DeconstructedPat<Self>,
129        normal_pat: &DeconstructedPat<Self>,
130    ) -> Self::Error;
131}
132
133/// The arm of a match expression.
134#[derive(Debug)]
135pub struct MatchArm<'p, Cx: PatCx> {
136    pub pat: &'p DeconstructedPat<Cx>,
137    pub has_guard: bool,
138    pub arm_data: Cx::ArmData,
139}
140
141impl<'p, Cx: PatCx> Clone for MatchArm<'p, Cx> {
142    fn clone(&self) -> Self {
143        *self
144    }
145}
146
147impl<'p, Cx: PatCx> Copy for MatchArm<'p, Cx> {}