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