rust/compiler/rustc_pattern_analysis/src/lib.rs

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

191 lines
6.1 KiB
Rust
Raw Normal View History

//! Analysis of patterns, notably match exhaustiveness checking.
pub mod constructor;
#[cfg(feature = "rustc")]
pub mod errors;
#[cfg(feature = "rustc")]
2023-12-11 09:40:31 +00:00
pub(crate) mod lints;
pub mod pat;
#[cfg(feature = "rustc")]
2023-12-11 19:15:52 +00:00
pub mod rustc;
pub mod usefulness;
#[macro_use]
extern crate tracing;
#[cfg(feature = "rustc")]
#[macro_use]
extern crate rustc_middle;
#[cfg(feature = "rustc")]
rustc_fluent_macro::fluent_messages! { "../messages.ftl" }
2023-12-11 09:40:31 +00:00
2023-12-11 19:01:02 +00:00
use std::fmt;
#[cfg(feature = "rustc")]
pub mod index {
// Faster version when the indices of variants are `0..variants.len()`.
pub use rustc_index::bit_set::BitSet as IdxSet;
pub use rustc_index::Idx;
pub use rustc_index::IndexVec as IdxContainer;
}
#[cfg(not(feature = "rustc"))]
pub mod index {
// Slower version when the indices of variants are something else.
pub trait Idx: Copy + PartialEq + Eq + std::hash::Hash {}
impl<T: Copy + PartialEq + Eq + std::hash::Hash> Idx for T {}
#[derive(Debug)]
pub struct IdxContainer<K, V>(pub rustc_hash::FxHashMap<K, V>);
impl<K: Idx, V> IdxContainer<K, V> {
pub fn len(&self) -> usize {
self.0.len()
}
pub fn iter_enumerated(&self) -> impl Iterator<Item = (K, &V)> {
self.0.iter().map(|(k, v)| (*k, v))
}
}
#[derive(Debug)]
pub struct IdxSet<T>(pub rustc_hash::FxHashSet<T>);
impl<T: Idx> IdxSet<T> {
pub fn new_empty(_len: usize) -> Self {
Self(Default::default())
}
pub fn contains(&self, elem: T) -> bool {
self.0.contains(&elem)
}
pub fn insert(&mut self, elem: T) {
self.0.insert(elem);
}
}
}
#[cfg(feature = "rustc")]
2023-12-11 09:40:31 +00:00
use rustc_middle::ty::Ty;
2024-01-07 20:20:16 +00:00
#[cfg(feature = "rustc")]
use rustc_span::ErrorGuaranteed;
2023-12-11 09:40:31 +00:00
use crate::constructor::{Constructor, ConstructorSet, IntRange};
#[cfg(feature = "rustc")]
use crate::lints::{lint_nonexhaustive_missing_variants, PatternColumn};
2023-12-11 09:40:31 +00:00
use crate::pat::DeconstructedPat;
#[cfg(feature = "rustc")]
2023-12-14 16:54:11 +00:00
use crate::rustc::RustcMatchCheckCtxt;
#[cfg(feature = "rustc")]
use crate::usefulness::{compute_match_usefulness, ValidityConstraint};
2023-12-11 09:40:31 +00:00
2023-12-15 15:53:29 +00:00
pub trait Captures<'a> {}
impl<'a, T: ?Sized> Captures<'a> for T {}
/// Context that provides type information about constructors.
///
/// Most of the crate is parameterized on a type that implements this trait.
pub trait TypeCx: Sized + fmt::Debug {
/// The type of a pattern.
2023-12-22 23:21:27 +00:00
type Ty: Clone + fmt::Debug;
2024-01-07 20:20:16 +00:00
/// Errors that can abort analysis.
type Error: fmt::Debug;
2023-12-11 19:45:34 +00:00
/// The index of an enum variant.
type VariantIdx: Clone + index::Idx + fmt::Debug;
2023-12-11 19:45:34 +00:00
/// A string literal
2023-12-11 19:01:02 +00:00
type StrLit: Clone + PartialEq + fmt::Debug;
2023-12-15 16:25:11 +00:00
/// Extra data to store in a match arm.
2023-12-11 19:45:34 +00:00
type ArmData: Copy + Clone + fmt::Debug;
/// Extra data to store in a pattern.
type PatData: Clone;
2023-12-11 19:01:02 +00:00
fn is_exhaustive_patterns_feature_on(&self) -> bool;
2024-01-18 18:22:44 +00:00
fn is_min_exhaustive_patterns_feature_on(&self) -> bool;
2023-12-11 19:01:02 +00:00
/// The number of fields for this constructor.
2023-12-22 23:21:27 +00:00
fn ctor_arity(&self, ctor: &Constructor<Self>, ty: &Self::Ty) -> usize;
2023-12-11 19:01:02 +00:00
/// The types of the fields for this constructor. The result must have a length of
/// `ctor_arity()`.
fn ctor_sub_tys<'a>(
&'a self,
ctor: &'a Constructor<Self>,
ty: &'a Self::Ty,
) -> impl Iterator<Item = Self::Ty> + ExactSizeIterator + Captures<'a>;
2023-12-11 19:01:02 +00:00
/// The set of all the constructors for `ty`.
///
/// This must follow the invariants of `ConstructorSet`
2023-12-22 23:21:27 +00:00
fn ctors_for_ty(&self, ty: &Self::Ty) -> Result<ConstructorSet<Self>, Self::Error>;
2023-12-11 19:01:02 +00:00
/// Write the name of the variant represented by `pat`. Used for the best-effort `Debug` impl of
/// `DeconstructedPat`. Only invoqued when `pat.ctor()` is `Struct | Variant(_) | UnionField`.
fn write_variant_name(
f: &mut fmt::Formatter<'_>,
pat: &crate::pat::DeconstructedPat<'_, Self>,
) -> fmt::Result;
2023-12-11 19:01:02 +00:00
/// Raise a bug.
fn bug(&self, fmt: fmt::Arguments<'_>) -> !;
/// Lint that the range `pat` overlapped with all the ranges in `overlaps_with`, where the range
/// they overlapped over is `overlaps_on`. We only detect singleton overlaps.
/// The default implementation does nothing.
fn lint_overlapping_range_endpoints(
&self,
_pat: &DeconstructedPat<'_, Self>,
_overlaps_on: IntRange,
_overlaps_with: &[&DeconstructedPat<'_, Self>],
) {
}
2023-12-11 19:01:02 +00:00
}
2023-12-15 15:53:29 +00:00
/// Context that provides information global to a match.
pub struct MatchCtxt<'a, Cx: TypeCx> {
2023-12-15 15:53:29 +00:00
/// The context for type information.
pub tycx: &'a Cx,
}
impl<'a, Cx: TypeCx> Clone for MatchCtxt<'a, Cx> {
fn clone(&self) -> Self {
Self { tycx: self.tycx }
}
}
impl<'a, Cx: TypeCx> Copy for MatchCtxt<'a, Cx> {}
2023-12-11 09:40:31 +00:00
/// The arm of a match expression.
#[derive(Debug)]
2023-12-15 16:25:11 +00:00
pub struct MatchArm<'p, Cx: TypeCx> {
2023-12-11 19:01:02 +00:00
pub pat: &'p DeconstructedPat<'p, Cx>,
2023-12-11 09:40:31 +00:00
pub has_guard: bool,
2023-12-11 19:45:34 +00:00
pub arm_data: Cx::ArmData,
2023-12-11 09:40:31 +00:00
}
impl<'p, Cx: TypeCx> Clone for MatchArm<'p, Cx> {
fn clone(&self) -> Self {
Self { pat: self.pat, has_guard: self.has_guard, arm_data: self.arm_data }
}
}
impl<'p, Cx: TypeCx> Copy for MatchArm<'p, Cx> {}
2023-12-11 09:40:31 +00:00
/// The entrypoint for this crate. Computes whether a match is exhaustive and which of its arms are
/// useful, and runs some lints.
#[cfg(feature = "rustc")]
2023-12-11 09:40:31 +00:00
pub fn analyze_match<'p, 'tcx>(
2023-12-15 15:53:29 +00:00
tycx: &RustcMatchCheckCtxt<'p, 'tcx>,
2023-12-11 19:15:52 +00:00
arms: &[rustc::MatchArm<'p, 'tcx>],
2023-12-11 09:40:31 +00:00
scrut_ty: Ty<'tcx>,
2024-01-07 20:20:16 +00:00
) -> Result<rustc::UsefulnessReport<'p, 'tcx>, ErrorGuaranteed> {
let scrut_ty = tycx.reveal_opaque_ty(scrut_ty);
2023-12-15 15:53:29 +00:00
let scrut_validity = ValidityConstraint::from_bool(tycx.known_valid_scrutinee);
let cx = MatchCtxt { tycx };
2023-12-15 15:53:29 +00:00
2024-01-07 20:20:16 +00:00
let report = compute_match_usefulness(cx, arms, scrut_ty, scrut_validity)?;
2023-12-11 09:40:31 +00:00
// Run the non_exhaustive_omitted_patterns lint. Only run on refutable patterns to avoid hitting
// `if let`s. Only run if the match is exhaustive otherwise the error is redundant.
2023-12-15 15:53:29 +00:00
if tycx.refutable && report.non_exhaustiveness_witnesses.is_empty() {
let pat_column = PatternColumn::new(arms);
2024-01-07 20:20:16 +00:00
lint_nonexhaustive_missing_variants(cx, arms, &pat_column, scrut_ty)?;
2023-12-11 09:40:31 +00:00
}
2024-01-07 20:20:16 +00:00
Ok(report)
2023-12-11 09:40:31 +00:00
}