Add an error path to the algorithm

This commit is contained in:
Nadrieril 2024-01-07 21:20:16 +01:00
parent d8b44d2802
commit 07d5f19426
5 changed files with 40 additions and 28 deletions

View File

@ -430,7 +430,10 @@ impl<'p, 'tcx> MatchVisitor<'p, 'tcx> {
}
let scrut_ty = scrut.ty;
let report = analyze_match(&cx, &tarms, scrut_ty);
let Ok(report) = analyze_match(&cx, &tarms, scrut_ty).map_err(|err| self.error = Err(err))
else {
return;
};
match source {
// Don't report arm reachability of desugared `match $iter.into_iter() { iter => .. }`
@ -544,7 +547,7 @@ impl<'p, 'tcx> MatchVisitor<'p, 'tcx> {
let cx = self.new_cx(refutability, None, scrut, pat.span);
let pat = self.lower_pattern(&cx, pat)?;
let arms = [MatchArm { pat, arm_data: self.lint_level, has_guard: false }];
let report = analyze_match(&cx, &arms, pat.ty().inner());
let report = analyze_match(&cx, &arms, pat.ty().inner())?;
Ok((cx, report))
}

View File

@ -24,6 +24,8 @@ use std::fmt;
use rustc_index::Idx;
#[cfg(feature = "rustc")]
use rustc_middle::ty::Ty;
#[cfg(feature = "rustc")]
use rustc_span::ErrorGuaranteed;
use crate::constructor::{Constructor, ConstructorSet};
#[cfg(feature = "rustc")]
@ -52,6 +54,8 @@ impl<'a, T: ?Sized> Captures<'a> for T {}
pub trait TypeCx: Sized + fmt::Debug {
/// The type of a pattern.
type Ty: Copy + Clone + fmt::Debug; // FIXME: remove Copy
/// Errors that can abort analysis.
type Error: fmt::Debug;
/// The index of an enum variant.
type VariantIdx: Clone + Idx;
/// A string literal
@ -109,25 +113,25 @@ pub fn analyze_match<'p, 'tcx>(
tycx: &RustcMatchCheckCtxt<'p, 'tcx>,
arms: &[rustc::MatchArm<'p, 'tcx>],
scrut_ty: Ty<'tcx>,
) -> rustc::UsefulnessReport<'p, 'tcx> {
) -> Result<rustc::UsefulnessReport<'p, 'tcx>, ErrorGuaranteed> {
// Arena to store the extra wildcards we construct during analysis.
let wildcard_arena = tycx.pattern_arena;
let scrut_ty = tycx.reveal_opaque_ty(scrut_ty);
let scrut_validity = ValidityConstraint::from_bool(tycx.known_valid_scrutinee);
let cx = MatchCtxt { tycx, wildcard_arena };
let report = compute_match_usefulness(cx, arms, scrut_ty, scrut_validity);
let report = compute_match_usefulness(cx, arms, scrut_ty, scrut_validity)?;
let pat_column = PatternColumn::new(arms);
// Lint on ranges that overlap on their endpoints, which is likely a mistake.
lint_overlapping_range_endpoints(cx, &pat_column);
lint_overlapping_range_endpoints(cx, &pat_column)?;
// 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.
if tycx.refutable && report.non_exhaustiveness_witnesses.is_empty() {
lint_nonexhaustive_missing_variants(cx, arms, &pat_column, scrut_ty)
lint_nonexhaustive_missing_variants(cx, arms, &pat_column, scrut_ty)?;
}
report
Ok(report)
}

View File

@ -4,7 +4,7 @@ use rustc_data_structures::captures::Captures;
use rustc_middle::ty;
use rustc_session::lint;
use rustc_session::lint::builtin::NON_EXHAUSTIVE_OMITTED_PATTERNS;
use rustc_span::Span;
use rustc_span::{ErrorGuaranteed, Span};
use crate::constructor::{IntRange, MaybeInfiniteInt};
use crate::errors::{
@ -110,9 +110,9 @@ impl<'p, 'tcx> PatternColumn<'p, 'tcx> {
fn collect_nonexhaustive_missing_variants<'a, 'p, 'tcx>(
cx: MatchCtxt<'a, 'p, 'tcx>,
column: &PatternColumn<'p, 'tcx>,
) -> Vec<WitnessPat<'p, 'tcx>> {
) -> Result<Vec<WitnessPat<'p, 'tcx>>, ErrorGuaranteed> {
let Some(ty) = column.head_ty() else {
return Vec::new();
return Ok(Vec::new());
};
let pcx = &PlaceCtxt::new_dummy(cx, ty);
@ -121,7 +121,7 @@ fn collect_nonexhaustive_missing_variants<'a, 'p, 'tcx>(
// We can't consistently handle the case where no constructors are present (since this would
// require digging deep through any type in case there's a non_exhaustive enum somewhere),
// so for consistency we refuse to handle the top-level case, where we could handle it.
return vec![];
return Ok(Vec::new());
}
let mut witnesses = Vec::new();
@ -141,7 +141,7 @@ fn collect_nonexhaustive_missing_variants<'a, 'p, 'tcx>(
let wild_pat = WitnessPat::wild_from_ctor(pcx, ctor);
for (i, col_i) in specialized_columns.iter().enumerate() {
// Compute witnesses for each column.
let wits_for_col_i = collect_nonexhaustive_missing_variants(cx, col_i);
let wits_for_col_i = collect_nonexhaustive_missing_variants(cx, col_i)?;
// For each witness, we build a new pattern in the shape of `ctor(_, _, wit, _, _)`,
// adding enough wildcards to match `arity`.
for wit in wits_for_col_i {
@ -151,7 +151,7 @@ fn collect_nonexhaustive_missing_variants<'a, 'p, 'tcx>(
}
}
}
witnesses
Ok(witnesses)
}
pub(crate) fn lint_nonexhaustive_missing_variants<'a, 'p, 'tcx>(
@ -159,13 +159,13 @@ pub(crate) fn lint_nonexhaustive_missing_variants<'a, 'p, 'tcx>(
arms: &[MatchArm<'p, 'tcx>],
pat_column: &PatternColumn<'p, 'tcx>,
scrut_ty: RevealedTy<'tcx>,
) {
) -> Result<(), ErrorGuaranteed> {
let rcx: &RustcMatchCheckCtxt<'_, '_> = cx.tycx;
if !matches!(
rcx.tcx.lint_level_at_node(NON_EXHAUSTIVE_OMITTED_PATTERNS, rcx.match_lint_level).0,
rustc_session::lint::Level::Allow
) {
let witnesses = collect_nonexhaustive_missing_variants(cx, pat_column);
let witnesses = collect_nonexhaustive_missing_variants(cx, pat_column)?;
if !witnesses.is_empty() {
// Report that a match of a `non_exhaustive` enum marked with `non_exhaustive_omitted_patterns`
// is not exhaustive enough.
@ -204,6 +204,7 @@ pub(crate) fn lint_nonexhaustive_missing_variants<'a, 'p, 'tcx>(
}
}
}
Ok(())
}
/// Traverse the patterns to warn the user about ranges that overlap on their endpoints.
@ -211,9 +212,9 @@ pub(crate) fn lint_nonexhaustive_missing_variants<'a, 'p, 'tcx>(
pub(crate) fn lint_overlapping_range_endpoints<'a, 'p, 'tcx>(
cx: MatchCtxt<'a, 'p, 'tcx>,
column: &PatternColumn<'p, 'tcx>,
) {
) -> Result<(), ErrorGuaranteed> {
let Some(ty) = column.head_ty() else {
return;
return Ok(());
};
let pcx = &PlaceCtxt::new_dummy(cx, ty);
let rcx: &RustcMatchCheckCtxt<'_, '_> = cx.tycx;
@ -275,8 +276,9 @@ pub(crate) fn lint_overlapping_range_endpoints<'a, 'p, 'tcx>(
// Recurse into the fields.
for ctor in set.present {
for col in column.specialize(pcx, &ctor) {
lint_overlapping_range_endpoints(cx, &col);
lint_overlapping_range_endpoints(cx, &col)?;
}
}
}
Ok(())
}

View File

@ -13,6 +13,7 @@ use rustc_middle::mir::{self, Const};
use rustc_middle::thir::{FieldPat, Pat, PatKind, PatRange, PatRangeBoundary};
use rustc_middle::ty::layout::IntegerExt;
use rustc_middle::ty::{self, OpaqueTypeKey, Ty, TyCtxt, VariantDef};
use rustc_span::ErrorGuaranteed;
use rustc_span::{Span, DUMMY_SP};
use rustc_target::abi::{FieldIdx, Integer, VariantIdx, FIRST_VARIANT};
use smallvec::SmallVec;
@ -944,6 +945,7 @@ impl<'p, 'tcx> RustcMatchCheckCtxt<'p, 'tcx> {
impl<'p, 'tcx> TypeCx for RustcMatchCheckCtxt<'p, 'tcx> {
type Ty = RevealedTy<'tcx>;
type Error = ErrorGuaranteed;
type VariantIdx = VariantIdx;
type StrLit = Const<'tcx>;
type ArmData = HirId;

View File

@ -1341,14 +1341,14 @@ fn compute_exhaustiveness_and_usefulness<'a, 'p, Cx: TypeCx>(
mcx: MatchCtxt<'a, 'p, Cx>,
matrix: &mut Matrix<'p, Cx>,
is_top_level: bool,
) -> WitnessMatrix<Cx> {
) -> Result<WitnessMatrix<Cx>, Cx::Error> {
debug_assert!(matrix.rows().all(|r| r.len() == matrix.column_count()));
if !matrix.wildcard_row_is_relevant && matrix.rows().all(|r| !r.pats.relevant) {
// Here we know that nothing will contribute further to exhaustiveness or usefulness. This
// is purely an optimization: skipping this check doesn't affect correctness. See the top of
// the file for details.
return WitnessMatrix::empty();
return Ok(WitnessMatrix::empty());
}
let Some(ty) = matrix.head_ty() else {
@ -1360,16 +1360,16 @@ fn compute_exhaustiveness_and_usefulness<'a, 'p, Cx: TypeCx>(
// When there's an unguarded row, the match is exhaustive and any subsequent row is not
// useful.
if !row.is_under_guard {
return WitnessMatrix::empty();
return Ok(WitnessMatrix::empty());
}
}
// No (unguarded) rows, so the match is not exhaustive. We return a new witness unless
// irrelevant.
return if matrix.wildcard_row_is_relevant {
WitnessMatrix::unit_witness()
Ok(WitnessMatrix::unit_witness())
} else {
// We choose to not report anything here; see at the top for details.
WitnessMatrix::empty()
Ok(WitnessMatrix::empty())
};
};
@ -1422,7 +1422,7 @@ fn compute_exhaustiveness_and_usefulness<'a, 'p, Cx: TypeCx>(
let mut spec_matrix = matrix.specialize_constructor(pcx, &ctor, ctor_is_relevant);
let mut witnesses = ensure_sufficient_stack(|| {
compute_exhaustiveness_and_usefulness(mcx, &mut spec_matrix, false)
});
})?;
// Transform witnesses for `spec_matrix` into witnesses for `matrix`.
witnesses.apply_constructor(pcx, &missing_ctors, &ctor, report_individual_missing_ctors);
@ -1443,7 +1443,7 @@ fn compute_exhaustiveness_and_usefulness<'a, 'p, Cx: TypeCx>(
}
}
ret
Ok(ret)
}
/// Indicates whether or not a given arm is useful.
@ -1474,9 +1474,10 @@ pub fn compute_match_usefulness<'p, Cx: TypeCx>(
arms: &[MatchArm<'p, Cx>],
scrut_ty: Cx::Ty,
scrut_validity: ValidityConstraint,
) -> UsefulnessReport<'p, Cx> {
) -> Result<UsefulnessReport<'p, Cx>, Cx::Error> {
let mut matrix = Matrix::new(arms, scrut_ty, scrut_validity);
let non_exhaustiveness_witnesses = compute_exhaustiveness_and_usefulness(cx, &mut matrix, true);
let non_exhaustiveness_witnesses =
compute_exhaustiveness_and_usefulness(cx, &mut matrix, true)?;
let non_exhaustiveness_witnesses: Vec<_> = non_exhaustiveness_witnesses.single_column();
let arm_usefulness: Vec<_> = arms
@ -1493,5 +1494,5 @@ pub fn compute_match_usefulness<'p, Cx: TypeCx>(
(arm, usefulness)
})
.collect();
UsefulnessReport { arm_usefulness, non_exhaustiveness_witnesses }
Ok(UsefulnessReport { arm_usefulness, non_exhaustiveness_witnesses })
}