Skip to content

Commit

Permalink
Explain why a given pattern is considered unreachable
Browse files Browse the repository at this point in the history
  • Loading branch information
Nadrieril committed Jul 21, 2024
1 parent e4fb790 commit 1b18b16
Show file tree
Hide file tree
Showing 50 changed files with 1,275 additions and 262 deletions.
5 changes: 4 additions & 1 deletion compiler/rustc_mir_build/messages.ftl
Original file line number Diff line number Diff line change
Expand Up @@ -327,7 +327,10 @@ mir_build_union_pattern = cannot use unions in constant patterns
mir_build_unreachable_pattern = unreachable pattern
.label = unreachable pattern
.catchall_label = matches any value
.unreachable_matches_no_values = this pattern matches no values because `{$ty}` is uninhabited
.unreachable_catchall = matches any value
.unreachable_covered_by_one = matches all the values already
.unreachable_covered_by_many = matches some of the same values
mir_build_unsafe_fn_safe_body = an unsafe function restricts its caller, but its body is safe by default
mir_build_unsafe_not_inherited = items do not inherit unsafety from separate enclosing items
Expand Down
30 changes: 28 additions & 2 deletions compiler/rustc_mir_build/src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -582,11 +582,37 @@ pub(crate) struct NonConstPath {

#[derive(LintDiagnostic)]
#[diag(mir_build_unreachable_pattern)]
pub(crate) struct UnreachablePattern {
pub(crate) struct UnreachablePattern<'tcx> {
#[label]
pub(crate) span: Option<Span>,
#[label(mir_build_catchall_label)]
#[subdiagnostic]
pub(crate) matches_no_values: Option<UnreachableMatchesNoValues<'tcx>>,
#[label(mir_build_unreachable_catchall)]
pub(crate) catchall: Option<Span>,
#[label(mir_build_unreachable_covered_by_one)]
pub(crate) covered_by_one: Option<Span>,
#[subdiagnostic]
pub(crate) covered_by_many: Option<UnreachableCoveredByMany>,
}

#[derive(Subdiagnostic)]
#[note(mir_build_unreachable_matches_no_values)]
pub(crate) struct UnreachableMatchesNoValues<'tcx> {
pub(crate) ty: Ty<'tcx>,
}

pub(crate) struct UnreachableCoveredByMany(pub(crate) Vec<Span>);

impl Subdiagnostic for UnreachableCoveredByMany {
fn add_to_diag_with<G: EmissionGuarantee, F: SubdiagMessageOp<G>>(
self,
diag: &mut Diag<'_, G>,
_f: &F,
) {
for span in self.0 {
diag.span_label(span, fluent::mir_build_unreachable_covered_by_many);
}
}
}

#[derive(Diagnostic)]
Expand Down
65 changes: 46 additions & 19 deletions compiler/rustc_mir_build/src/thir/pattern/check_match.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ use rustc_middle::ty::print::with_no_trimmed_paths;
use rustc_middle::ty::{self, AdtDef, Ty, TyCtxt};
use rustc_pattern_analysis::errors::Uncovered;
use rustc_pattern_analysis::rustc::{
Constructor, DeconstructedPat, MatchArm, RustcPatCtxt as PatCtxt, Usefulness, UsefulnessReport,
WitnessPat,
Constructor, DeconstructedPat, MatchArm, RedundancyExplanation, RustcPatCtxt as PatCtxt,
Usefulness, UsefulnessReport, WitnessPat,
};
use rustc_session::lint::builtin::{
BINDINGS_WITH_VARIANT_NAME, IRREFUTABLE_LET_PATTERNS, UNREACHABLE_PATTERNS,
Expand Down Expand Up @@ -409,9 +409,9 @@ impl<'p, 'tcx> MatchVisitor<'p, 'tcx> {
{
let mut redundant_subpats = redundant_subpats.clone();
// Emit lints in the order in which they occur in the file.
redundant_subpats.sort_unstable_by_key(|pat| pat.data().span);
for pat in redundant_subpats {
report_unreachable_pattern(cx, arm.arm_data, pat.data().span, None)
redundant_subpats.sort_unstable_by_key(|(pat, _)| pat.data().span);
for (pat, explanation) in redundant_subpats {
report_unreachable_pattern(cx, arm.arm_data, pat, &explanation)
}
}
}
Expand Down Expand Up @@ -910,26 +910,53 @@ fn report_irrefutable_let_patterns(
fn report_unreachable_pattern<'p, 'tcx>(
cx: &PatCtxt<'p, 'tcx>,
hir_id: HirId,
span: Span,
catchall: Option<Span>,
pat: &DeconstructedPat<'p, 'tcx>,
explanation: &RedundancyExplanation<'p, 'tcx>,
) {
cx.tcx.emit_node_span_lint(
UNREACHABLE_PATTERNS,
hir_id,
span,
UnreachablePattern { span: if catchall.is_some() { Some(span) } else { None }, catchall },
);
let pat_span = pat.data().span;
let mut lint = UnreachablePattern {
span: None,
matches_no_values: None,
catchall: None,
covered_by_one: None,
covered_by_many: None,
};
match explanation {
RedundancyExplanation::Empty => {
pat.walk(&mut |subpat| {
let ty = **subpat.ty();
if cx.is_uninhabited(ty) {
lint.matches_no_values = Some(UnreachableMatchesNoValues { ty });
false
} else {
true
}
});
}
RedundancyExplanation::CoveredBy(covering_pats) => {
lint.span = Some(pat_span); // Add a label to the pattern itself
if covering_pats.len() == 1 {
let covering_pat = covering_pats[0];
let covering_span = covering_pat.data().span;
if pat_is_catchall(covering_pat) {
lint.catchall = Some(covering_span);
} else {
lint.covered_by_one = Some(covering_span);
}
} else {
let covering_spans = covering_pats.iter().map(|p| p.data().span).collect();
lint.covered_by_many = Some(UnreachableCoveredByMany(covering_spans));
}
}
}
cx.tcx.emit_node_span_lint(UNREACHABLE_PATTERNS, hir_id, pat_span, lint);
}

/// Report unreachable arms, if any.
fn report_arm_reachability<'p, 'tcx>(cx: &PatCtxt<'p, 'tcx>, report: &UsefulnessReport<'p, 'tcx>) {
let mut catchall = None;
for (arm, is_useful) in report.arm_usefulness.iter() {
if matches!(is_useful, Usefulness::Redundant) {
report_unreachable_pattern(cx, arm.arm_data, arm.pat.data().span, catchall)
}
if !arm.has_guard && catchall.is_none() && pat_is_catchall(arm.pat) {
catchall = Some(arm.pat.data().span);
if let Usefulness::Redundant(explanation) = is_useful {
report_unreachable_pattern(cx, arm.arm_data, arm.pat, explanation)
}
}
}
Expand Down
17 changes: 16 additions & 1 deletion compiler/rustc_pattern_analysis/src/pat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use crate::{PatCx, PrivateUninhabitedField};
use self::Constructor::*;

/// A globally unique id to distinguish patterns.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub(crate) struct PatId(u32);
impl PatId {
fn new() -> Self {
Expand Down Expand Up @@ -147,6 +147,21 @@ impl<Cx: PatCx> fmt::Debug for DeconstructedPat<Cx> {
}
}

/// Delegate to `uid`.
impl<Cx: PatCx> PartialEq for DeconstructedPat<Cx> {
fn eq(&self, other: &Self) -> bool {
self.uid == other.uid
}
}
/// Delegate to `uid`.
impl<Cx: PatCx> Eq for DeconstructedPat<Cx> {}
/// Delegate to `uid`.
impl<Cx: PatCx> std::hash::Hash for DeconstructedPat<Cx> {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.uid.hash(state);
}
}

/// Represents either a pattern obtained from user input or a wildcard constructed during the
/// algorithm. Do not use `Wild` to represent a wildcard pattern comping from user input.
///
Expand Down
2 changes: 2 additions & 0 deletions compiler/rustc_pattern_analysis/src/rustc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ pub type Constructor<'p, 'tcx> = crate::constructor::Constructor<RustcPatCtxt<'p
pub type ConstructorSet<'p, 'tcx> = crate::constructor::ConstructorSet<RustcPatCtxt<'p, 'tcx>>;
pub type DeconstructedPat<'p, 'tcx> = crate::pat::DeconstructedPat<RustcPatCtxt<'p, 'tcx>>;
pub type MatchArm<'p, 'tcx> = crate::MatchArm<'p, RustcPatCtxt<'p, 'tcx>>;
pub type RedundancyExplanation<'p, 'tcx> =
crate::usefulness::RedundancyExplanation<'p, RustcPatCtxt<'p, 'tcx>>;
pub type Usefulness<'p, 'tcx> = crate::usefulness::Usefulness<'p, RustcPatCtxt<'p, 'tcx>>;
pub type UsefulnessReport<'p, 'tcx> =
crate::usefulness::UsefulnessReport<'p, RustcPatCtxt<'p, 'tcx>>;
Expand Down
Loading

0 comments on commit 1b18b16

Please sign in to comment.