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#![cfg_attr(feature = "rustc", feature(let_chains))]
9#![warn(unreachable_pub)]
10// tidy-alphabetical-end
11
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    /// The number of fields for this constructor.
61    fn ctor_arity(&self, ctor: &Constructor<Self>, ty: &Self::Ty) -> usize;
62
63    /// The types of the fields for this constructor. The result must contain `ctor_arity()` fields.
64    fn ctor_sub_tys<'a>(
65        &'a self,
66        ctor: &'a Constructor<Self>,
67        ty: &'a Self::Ty,
68    ) -> impl Iterator<Item = (Self::Ty, PrivateUninhabitedField)> + ExactSizeIterator + Captures<'a>;
69
70    /// The set of all the constructors for `ty`.
71    ///
72    /// This must follow the invariants of `ConstructorSet`
73    fn ctors_for_ty(&self, ty: &Self::Ty) -> Result<ConstructorSet<Self>, Self::Error>;
74
75    /// Write the name of the variant represented by `pat`. Used for the best-effort `Debug` impl of
76    /// `DeconstructedPat`. Only invoqued when `pat.ctor()` is `Struct | Variant(_) | UnionField`.
77    fn write_variant_name(
78        f: &mut fmt::Formatter<'_>,
79        ctor: &crate::constructor::Constructor<Self>,
80        ty: &Self::Ty,
81    ) -> fmt::Result;
82
83    /// Raise a bug.
84    fn bug(&self, fmt: fmt::Arguments<'_>) -> Self::Error;
85
86    /// Lint that the range `pat` overlapped with all the ranges in `overlaps_with`, where the range
87    /// they overlapped over is `overlaps_on`. We only detect singleton overlaps.
88    /// The default implementation does nothing.
89    fn lint_overlapping_range_endpoints(
90        &self,
91        _pat: &DeconstructedPat<Self>,
92        _overlaps_on: IntRange,
93        _overlaps_with: &[&DeconstructedPat<Self>],
94    ) {
95    }
96
97    /// The maximum pattern complexity limit was reached.
98    fn complexity_exceeded(&self) -> Result<(), Self::Error>;
99
100    /// Lint that there is a gap `gap` between `pat` and all of `gapped_with` such that the gap is
101    /// not matched by another range. If `gapped_with` is empty, then `gap` is `T::MAX`. We only
102    /// detect singleton gaps.
103    /// The default implementation does nothing.
104    fn lint_non_contiguous_range_endpoints(
105        &self,
106        _pat: &DeconstructedPat<Self>,
107        _gap: IntRange,
108        _gapped_with: &[&DeconstructedPat<Self>],
109    ) {
110    }
111}
112
113/// The arm of a match expression.
114#[derive(Debug)]
115pub struct MatchArm<'p, Cx: PatCx> {
116    pub pat: &'p DeconstructedPat<Cx>,
117    pub has_guard: bool,
118    pub arm_data: Cx::ArmData,
119}
120
121impl<'p, Cx: PatCx> Clone for MatchArm<'p, Cx> {
122    fn clone(&self) -> Self {
123        Self { pat: self.pat, has_guard: self.has_guard, arm_data: self.arm_data }
124    }
125}
126
127impl<'p, Cx: PatCx> Copy for MatchArm<'p, Cx> {}