Skip to content

Commit

Permalink
Lint against empty match on not-known-valid place
Browse files Browse the repository at this point in the history
  • Loading branch information
Nadrieril committed Dec 10, 2023
1 parent 7cc0ad8 commit de5f50b
Show file tree
Hide file tree
Showing 10 changed files with 475 additions and 28 deletions.
71 changes: 71 additions & 0 deletions compiler/rustc_lint_defs/src/builtin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ declare_lint_pass! {
DUPLICATE_MACRO_ATTRIBUTES,
ELIDED_LIFETIMES_IN_ASSOCIATED_CONSTANT,
ELIDED_LIFETIMES_IN_PATHS,
EMPTY_MATCH_ON_UNSAFE_PLACE,
EXPORTED_PRIVATE_DEPENDENCIES,
FFI_UNWIND_CALLS,
FORBIDDEN_LINT_GROUPS,
Expand Down Expand Up @@ -4019,6 +4020,76 @@ declare_lint! {
@feature_gate = sym::non_exhaustive_omitted_patterns_lint;
}

declare_lint! {
/// The `empty_match_on_unsafe_place` lint detects uses of `match ... {}` on an empty type where
/// the matched place could contain invalid data in a well-defined program. These matches are
/// considered exhaustive for backwards-compatibility, but they shouldn't be since a `_` arm
/// would be reachable.
///
/// This will become an error in the future.
///
/// ### Example
///
/// ```compile_fail
/// #![feature(min_exhaustive_patterns)]
/// enum Void {}
/// let ptr: *const Void = ...;
/// unsafe {
/// match *ptr {}
/// }
/// ```
///
/// This will produce:
///
/// ```text
/// warning: empty match on potentially-invalid data
/// --> $DIR/empty-types.rs:157:9
/// |
/// LL | match *ptr {}
/// | ^^^^^^^^^^^^^
/// |
/// note: this place can hold invalid data, which would make the match reachable
/// --> $DIR/empty-types.rs:157:15
/// |
/// LL | match *ptr {}
/// | ^^^^
/// = note: `#[warn(empty_match_on_unsafe_place)]` on by default
/// help: consider forcing a read of the value
/// |
/// LL | match { *ptr } {}
/// | + +
/// ```
///
/// ### Explanation
///
/// Some place expressions (namely pointer dereferences, union field accesses, and
/// (conservatively) reference dereferences) can hold invalid data without causing UB. For
/// example, the following is a well-defined program that prints "reachable!".
///
/// ```rust
/// #[derive(Copy, Clone)]
/// enum Void {}
/// union Uninit<T: Copy> {
/// value: T,
/// uninit: (),
/// }
/// unsafe {
/// let x: Uninit<Void> = Uninit { uninit: () };
/// match x.value {
/// _ => println!("reachable!"),
/// }
/// }
/// ```
///
/// Therefore when the matched place can hold invalid data, a match with no arm should not be
/// considered exhaustive. For backwards-compatibility we consider them exhaustive but warn with
/// this lint. It will become an error in the future.
pub EMPTY_MATCH_ON_UNSAFE_PLACE,
Warn,
"warn about empty matches on a place with potentially-invalid data",
@feature_gate = sym::min_exhaustive_patterns;
}

declare_lint! {
/// The `text_direction_codepoint_in_comment` lint detects Unicode codepoints in comments that
/// change the visual representation of text on screen in a way that does not correspond to
Expand Down
7 changes: 7 additions & 0 deletions compiler/rustc_mir_build/messages.ftl
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,13 @@ mir_build_deref_raw_pointer_requires_unsafe_unsafe_op_in_unsafe_fn_allowed =
.note = raw pointers may be null, dangling or unaligned; they can violate aliasing rules and cause data races: all of these are undefined behavior
.label = dereference of raw pointer
mir_build_empty_match_on_unsafe_place =
empty match on potentially-invalid data
.note = this place can hold invalid data, which would make the match reachable
mir_build_empty_match_on_unsafe_place_wrap_suggestion =
consider forcing a read of the value
mir_build_extern_static_requires_unsafe =
use of extern static is unsafe and requires unsafe block
.note = extern statics are not controlled by the Rust type system: invalid data, aliasing violations or data races will cause undefined behavior
Expand Down
21 changes: 21 additions & 0 deletions compiler/rustc_mir_build/src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -841,6 +841,27 @@ impl<'tcx> AddToDiagnostic for Overlap<'tcx> {
}
}

#[derive(LintDiagnostic)]
#[diag(mir_build_empty_match_on_unsafe_place)]
pub struct EmptyMatchOnUnsafePlace {
#[note]
pub scrut_span: Span,
#[subdiagnostic]
pub suggestion: EmptyMatchOnUnsafePlaceWrapSuggestion,
}

#[derive(Subdiagnostic)]
#[multipart_suggestion(
mir_build_empty_match_on_unsafe_place_wrap_suggestion,
applicability = "maybe-incorrect"
)]
pub struct EmptyMatchOnUnsafePlaceWrapSuggestion {
#[suggestion_part(code = "{{ ")]
pub scrut_start: Span,
#[suggestion_part(code = " }}")]
pub scrut_end: Span,
}

#[derive(LintDiagnostic)]
#[diag(mir_build_non_exhaustive_omitted_pattern)]
#[help]
Expand Down
49 changes: 39 additions & 10 deletions compiler/rustc_mir_build/src/thir/pattern/usefulness.rs
Original file line number Diff line number Diff line change
Expand Up @@ -557,8 +557,8 @@ use super::deconstruct_pat::{
WitnessPat,
};
use crate::errors::{
NonExhaustiveOmittedPattern, NonExhaustiveOmittedPatternLintOnArm, Overlap,
OverlappingRangeEndpoints, Uncovered,
EmptyMatchOnUnsafePlace, EmptyMatchOnUnsafePlaceWrapSuggestion, NonExhaustiveOmittedPattern,
NonExhaustiveOmittedPatternLintOnArm, Overlap, OverlappingRangeEndpoints, Uncovered,
};

use rustc_data_structures::captures::Captures;
Expand Down Expand Up @@ -1238,22 +1238,17 @@ fn compute_exhaustiveness_and_usefulness<'p, 'tcx>(

debug!("ty: {ty:?}");
let pcx = &PatCtxt { cx, ty, is_top_level };
let ctors_for_ty = ConstructorSet::for_ty(cx, ty);

// Whether the place/column we are inspecting is known to contain valid data.
let mut place_validity = matrix.place_validity[0];
if !pcx.cx.tcx.features().min_exhaustive_patterns
|| (is_top_level && matches!(ctors_for_ty, ConstructorSet::NoConstructors))
{
// For backwards compability we allow omitting some empty arms that we ideally shouldn't.
if cx.tcx.features().exhaustive_patterns {
// Under `exhaustive_patterns` we allow omitting empty arms even when they aren't redundant.
place_validity = place_validity.allow_omitting_side_effecting_arms();
}

// Analyze the constructors present in this column.
let ctors = matrix.heads().map(|p| p.ctor());
let split_set = ctors_for_ty.split(pcx, ctors);

// Decide what constructors to report.
let split_set = ConstructorSet::for_ty(cx, ty).split(pcx, ctors);
let all_missing = split_set.present.is_empty();

// Build the set of constructors we will specialize with. It must cover the whole type.
Expand Down Expand Up @@ -1578,6 +1573,40 @@ pub(crate) fn compute_match_usefulness<'p, 'tcx>(
arms: &[MatchArm<'p, 'tcx>],
scrut_ty: Ty<'tcx>,
) -> UsefulnessReport<'p, 'tcx> {
if !cx.known_valid_scrutinee && arms.iter().all(|arm| arm.has_guard) {
let is_directly_empty = match scrut_ty.kind() {
ty::Adt(def, ..) => {
def.is_enum()
&& def.variants().is_empty()
&& !cx.is_foreign_non_exhaustive_enum(scrut_ty)
}
ty::Never => true,
_ => false,
};
if is_directly_empty {
if cx.tcx.features().min_exhaustive_patterns {
cx.tcx.emit_spanned_lint(
lint::builtin::EMPTY_MATCH_ON_UNSAFE_PLACE,
cx.match_lint_level,
cx.whole_match_span.unwrap_or(cx.scrut_span),
EmptyMatchOnUnsafePlace {
scrut_span: cx.scrut_span,
suggestion: EmptyMatchOnUnsafePlaceWrapSuggestion {
scrut_start: cx.scrut_span.shrink_to_lo(),
scrut_end: cx.scrut_span.shrink_to_hi(),
},
},
);
}

// For backwards compability we allow an empty match in this case.
return UsefulnessReport {
arm_usefulness: Vec::new(),
non_exhaustiveness_witnesses: Vec::new(),
};
}
}

let scrut_validity = ValidityConstraint::from_bool(cx.known_valid_scrutinee);
let mut matrix = Matrix::new(cx, arms, scrut_ty, scrut_validity);
let non_exhaustiveness_witnesses = compute_exhaustiveness_and_usefulness(cx, &mut matrix, true);
Expand Down
Loading

0 comments on commit de5f50b

Please sign in to comment.