Auto merge of #88950 - Nadrieril:deconstruct-pat, r=oli-obk
Add an intermediate representation to exhaustiveness checking The exhaustiveness checking algorithm keeps deconstructing patterns into a `Constructor` and some `Fields`, but does so a bit all over the place. This PR introduces a new representation for patterns that already has that information, so we only compute it once at the start. I find this makes code easier to follow. In particular `DeconstructedPat::specialize` is a lot simpler than what happened before, and more closely matches the description of the algorithm. I'm also hoping this could help for the project of librarifying exhaustiveness for rust_analyzer since it decouples the algorithm from `rustc_middle::Pat`.
This commit is contained in:
commit
6df1d82869
10 changed files with 899 additions and 1000 deletions
|
@ -1,6 +1,6 @@
|
||||||
|
use super::deconstruct_pat::{Constructor, DeconstructedPat};
|
||||||
use super::usefulness::{
|
use super::usefulness::{
|
||||||
compute_match_usefulness, expand_pattern, is_wildcard, MatchArm, MatchCheckCtxt, Reachability,
|
compute_match_usefulness, MatchArm, MatchCheckCtxt, Reachability, UsefulnessReport,
|
||||||
UsefulnessReport,
|
|
||||||
};
|
};
|
||||||
use super::{PatCtxt, PatternError};
|
use super::{PatCtxt, PatternError};
|
||||||
|
|
||||||
|
@ -12,14 +12,12 @@ use rustc_hir::def::*;
|
||||||
use rustc_hir::def_id::DefId;
|
use rustc_hir::def_id::DefId;
|
||||||
use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
|
use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
|
||||||
use rustc_hir::{HirId, Pat};
|
use rustc_hir::{HirId, Pat};
|
||||||
use rustc_middle::thir::PatKind;
|
use rustc_middle::ty::{self, AdtDef, Ty, TyCtxt};
|
||||||
use rustc_middle::ty::{self, Ty, TyCtxt};
|
|
||||||
use rustc_session::lint::builtin::{
|
use rustc_session::lint::builtin::{
|
||||||
BINDINGS_WITH_VARIANT_NAME, IRREFUTABLE_LET_PATTERNS, UNREACHABLE_PATTERNS,
|
BINDINGS_WITH_VARIANT_NAME, IRREFUTABLE_LET_PATTERNS, UNREACHABLE_PATTERNS,
|
||||||
};
|
};
|
||||||
use rustc_session::Session;
|
use rustc_session::Session;
|
||||||
use rustc_span::{DesugaringKind, ExpnKind, Span};
|
use rustc_span::{DesugaringKind, ExpnKind, Span};
|
||||||
use std::slice;
|
|
||||||
|
|
||||||
crate fn check_match(tcx: TyCtxt<'_>, def_id: DefId) {
|
crate fn check_match(tcx: TyCtxt<'_>, def_id: DefId) {
|
||||||
let body_id = match def_id.as_local() {
|
let body_id = match def_id.as_local() {
|
||||||
|
@ -27,11 +25,12 @@ crate fn check_match(tcx: TyCtxt<'_>, def_id: DefId) {
|
||||||
Some(id) => tcx.hir().body_owned_by(tcx.hir().local_def_id_to_hir_id(id)),
|
Some(id) => tcx.hir().body_owned_by(tcx.hir().local_def_id_to_hir_id(id)),
|
||||||
};
|
};
|
||||||
|
|
||||||
|
let pattern_arena = TypedArena::default();
|
||||||
let mut visitor = MatchVisitor {
|
let mut visitor = MatchVisitor {
|
||||||
tcx,
|
tcx,
|
||||||
typeck_results: tcx.typeck_body(body_id),
|
typeck_results: tcx.typeck_body(body_id),
|
||||||
param_env: tcx.param_env(def_id),
|
param_env: tcx.param_env(def_id),
|
||||||
pattern_arena: TypedArena::default(),
|
pattern_arena: &pattern_arena,
|
||||||
};
|
};
|
||||||
visitor.visit_body(tcx.hir().body(body_id));
|
visitor.visit_body(tcx.hir().body(body_id));
|
||||||
}
|
}
|
||||||
|
@ -40,14 +39,14 @@ fn create_e0004(sess: &Session, sp: Span, error_message: String) -> DiagnosticBu
|
||||||
struct_span_err!(sess, sp, E0004, "{}", &error_message)
|
struct_span_err!(sess, sp, E0004, "{}", &error_message)
|
||||||
}
|
}
|
||||||
|
|
||||||
struct MatchVisitor<'a, 'tcx> {
|
struct MatchVisitor<'a, 'p, 'tcx> {
|
||||||
tcx: TyCtxt<'tcx>,
|
tcx: TyCtxt<'tcx>,
|
||||||
typeck_results: &'a ty::TypeckResults<'tcx>,
|
typeck_results: &'a ty::TypeckResults<'tcx>,
|
||||||
param_env: ty::ParamEnv<'tcx>,
|
param_env: ty::ParamEnv<'tcx>,
|
||||||
pattern_arena: TypedArena<super::Pat<'tcx>>,
|
pattern_arena: &'p TypedArena<DeconstructedPat<'p, 'tcx>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'tcx> Visitor<'tcx> for MatchVisitor<'_, 'tcx> {
|
impl<'tcx> Visitor<'tcx> for MatchVisitor<'_, '_, 'tcx> {
|
||||||
type Map = intravisit::ErasedMap<'tcx>;
|
type Map = intravisit::ErasedMap<'tcx>;
|
||||||
|
|
||||||
fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
|
fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
|
||||||
|
@ -113,31 +112,30 @@ impl PatCtxt<'_, '_> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'tcx> MatchVisitor<'_, 'tcx> {
|
impl<'p, 'tcx> MatchVisitor<'_, 'p, 'tcx> {
|
||||||
fn check_patterns(&self, pat: &Pat<'_>) {
|
fn check_patterns(&self, pat: &Pat<'_>) {
|
||||||
pat.walk_always(|pat| check_borrow_conflicts_in_at_patterns(self, pat));
|
pat.walk_always(|pat| check_borrow_conflicts_in_at_patterns(self, pat));
|
||||||
check_for_bindings_named_same_as_variants(self, pat);
|
check_for_bindings_named_same_as_variants(self, pat);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn lower_pattern<'p>(
|
fn lower_pattern(
|
||||||
&self,
|
&self,
|
||||||
cx: &mut MatchCheckCtxt<'p, 'tcx>,
|
cx: &mut MatchCheckCtxt<'p, 'tcx>,
|
||||||
pat: &'tcx hir::Pat<'tcx>,
|
pat: &'tcx hir::Pat<'tcx>,
|
||||||
have_errors: &mut bool,
|
have_errors: &mut bool,
|
||||||
) -> (&'p super::Pat<'tcx>, Ty<'tcx>) {
|
) -> &'p DeconstructedPat<'p, 'tcx> {
|
||||||
let mut patcx = PatCtxt::new(self.tcx, self.param_env, self.typeck_results);
|
let mut patcx = PatCtxt::new(self.tcx, self.param_env, self.typeck_results);
|
||||||
patcx.include_lint_checks();
|
patcx.include_lint_checks();
|
||||||
let pattern = patcx.lower_pattern(pat);
|
let pattern = patcx.lower_pattern(pat);
|
||||||
let pattern_ty = pattern.ty;
|
let pattern: &_ = cx.pattern_arena.alloc(DeconstructedPat::from_pat(cx, &pattern));
|
||||||
let pattern: &_ = cx.pattern_arena.alloc(expand_pattern(pattern));
|
|
||||||
if !patcx.errors.is_empty() {
|
if !patcx.errors.is_empty() {
|
||||||
*have_errors = true;
|
*have_errors = true;
|
||||||
patcx.report_inlining_errors();
|
patcx.report_inlining_errors();
|
||||||
}
|
}
|
||||||
(pattern, pattern_ty)
|
pattern
|
||||||
}
|
}
|
||||||
|
|
||||||
fn new_cx(&self, hir_id: HirId) -> MatchCheckCtxt<'_, 'tcx> {
|
fn new_cx(&self, hir_id: HirId) -> MatchCheckCtxt<'p, 'tcx> {
|
||||||
MatchCheckCtxt {
|
MatchCheckCtxt {
|
||||||
tcx: self.tcx,
|
tcx: self.tcx,
|
||||||
param_env: self.param_env,
|
param_env: self.param_env,
|
||||||
|
@ -149,8 +147,8 @@ impl<'tcx> MatchVisitor<'_, 'tcx> {
|
||||||
fn check_let(&mut self, pat: &'tcx hir::Pat<'tcx>, expr: &hir::Expr<'_>, span: Span) {
|
fn check_let(&mut self, pat: &'tcx hir::Pat<'tcx>, expr: &hir::Expr<'_>, span: Span) {
|
||||||
self.check_patterns(pat);
|
self.check_patterns(pat);
|
||||||
let mut cx = self.new_cx(expr.hir_id);
|
let mut cx = self.new_cx(expr.hir_id);
|
||||||
let tpat = self.lower_pattern(&mut cx, pat, &mut false).0;
|
let tpat = self.lower_pattern(&mut cx, pat, &mut false);
|
||||||
check_let_reachability(&mut cx, pat.hir_id, &tpat, span);
|
check_let_reachability(&mut cx, pat.hir_id, tpat, span);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn check_match(
|
fn check_match(
|
||||||
|
@ -166,8 +164,8 @@ impl<'tcx> MatchVisitor<'_, 'tcx> {
|
||||||
self.check_patterns(&arm.pat);
|
self.check_patterns(&arm.pat);
|
||||||
if let Some(hir::Guard::IfLet(ref pat, _)) = arm.guard {
|
if let Some(hir::Guard::IfLet(ref pat, _)) = arm.guard {
|
||||||
self.check_patterns(pat);
|
self.check_patterns(pat);
|
||||||
let tpat = self.lower_pattern(&mut cx, pat, &mut false).0;
|
let tpat = self.lower_pattern(&mut cx, pat, &mut false);
|
||||||
check_let_reachability(&mut cx, pat.hir_id, &tpat, tpat.span);
|
check_let_reachability(&mut cx, pat.hir_id, tpat, tpat.span());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -176,7 +174,7 @@ impl<'tcx> MatchVisitor<'_, 'tcx> {
|
||||||
let arms: Vec<_> = arms
|
let arms: Vec<_> = arms
|
||||||
.iter()
|
.iter()
|
||||||
.map(|hir::Arm { pat, guard, .. }| MatchArm {
|
.map(|hir::Arm { pat, guard, .. }| MatchArm {
|
||||||
pat: self.lower_pattern(&mut cx, pat, &mut have_errors).0,
|
pat: self.lower_pattern(&mut cx, pat, &mut have_errors),
|
||||||
hir_id: pat.hir_id,
|
hir_id: pat.hir_id,
|
||||||
has_guard: guard.is_some(),
|
has_guard: guard.is_some(),
|
||||||
})
|
})
|
||||||
|
@ -190,20 +188,16 @@ impl<'tcx> MatchVisitor<'_, 'tcx> {
|
||||||
let scrut_ty = self.typeck_results.expr_ty_adjusted(scrut);
|
let scrut_ty = self.typeck_results.expr_ty_adjusted(scrut);
|
||||||
let report = compute_match_usefulness(&cx, &arms, scrut.hir_id, scrut_ty);
|
let report = compute_match_usefulness(&cx, &arms, scrut.hir_id, scrut_ty);
|
||||||
|
|
||||||
report_arm_reachability(&cx, &report, |_, arm_span, arm_hir_id, catchall| {
|
match source {
|
||||||
match source {
|
hir::MatchSource::ForLoopDesugar | hir::MatchSource::Normal => {
|
||||||
hir::MatchSource::ForLoopDesugar | hir::MatchSource::Normal => {
|
report_arm_reachability(&cx, &report)
|
||||||
unreachable_pattern(cx.tcx, arm_span, arm_hir_id, catchall);
|
|
||||||
}
|
|
||||||
// Unreachable patterns in try and await expressions occur when one of
|
|
||||||
// the arms are an uninhabited type. Which is OK.
|
|
||||||
hir::MatchSource::AwaitDesugar | hir::MatchSource::TryDesugar => {}
|
|
||||||
}
|
}
|
||||||
});
|
// Unreachable patterns in try and await expressions occur when one of
|
||||||
|
// the arms are an uninhabited type. Which is OK.
|
||||||
|
hir::MatchSource::AwaitDesugar | hir::MatchSource::TryDesugar => {}
|
||||||
|
}
|
||||||
|
|
||||||
// Check if the match is exhaustive.
|
// Check if the match is exhaustive.
|
||||||
// Note: An empty match isn't the same as an empty matrix for diagnostics purposes,
|
|
||||||
// since an empty matrix can occur when there are arms, if those arms all have guards.
|
|
||||||
let is_empty_match = arms.is_empty();
|
let is_empty_match = arms.is_empty();
|
||||||
let witnesses = report.non_exhaustiveness_witnesses;
|
let witnesses = report.non_exhaustiveness_witnesses;
|
||||||
if !witnesses.is_empty() {
|
if !witnesses.is_empty() {
|
||||||
|
@ -214,7 +208,8 @@ impl<'tcx> MatchVisitor<'_, 'tcx> {
|
||||||
fn check_irrefutable(&self, pat: &'tcx Pat<'tcx>, origin: &str, sp: Option<Span>) {
|
fn check_irrefutable(&self, pat: &'tcx Pat<'tcx>, origin: &str, sp: Option<Span>) {
|
||||||
let mut cx = self.new_cx(pat.hir_id);
|
let mut cx = self.new_cx(pat.hir_id);
|
||||||
|
|
||||||
let (pattern, pattern_ty) = self.lower_pattern(&mut cx, pat, &mut false);
|
let pattern = self.lower_pattern(&mut cx, pat, &mut false);
|
||||||
|
let pattern_ty = pattern.ty();
|
||||||
let arms = vec![MatchArm { pat: pattern, hir_id: pat.hir_id, has_guard: false }];
|
let arms = vec![MatchArm { pat: pattern, hir_id: pat.hir_id, has_guard: false }];
|
||||||
let report = compute_match_usefulness(&cx, &arms, pat.hir_id, pattern_ty);
|
let report = compute_match_usefulness(&cx, &arms, pat.hir_id, pattern_ty);
|
||||||
|
|
||||||
|
@ -226,7 +221,7 @@ impl<'tcx> MatchVisitor<'_, 'tcx> {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
let joined_patterns = joined_uncovered_patterns(&witnesses);
|
let joined_patterns = joined_uncovered_patterns(&cx, &witnesses);
|
||||||
let mut err = struct_span_err!(
|
let mut err = struct_span_err!(
|
||||||
self.tcx.sess,
|
self.tcx.sess,
|
||||||
pat.span,
|
pat.span,
|
||||||
|
@ -302,7 +297,7 @@ fn const_not_var(
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn check_for_bindings_named_same_as_variants(cx: &MatchVisitor<'_, '_>, pat: &Pat<'_>) {
|
fn check_for_bindings_named_same_as_variants(cx: &MatchVisitor<'_, '_, '_>, pat: &Pat<'_>) {
|
||||||
pat.walk_always(|p| {
|
pat.walk_always(|p| {
|
||||||
if let hir::PatKind::Binding(_, _, ident, None) = p.kind {
|
if let hir::PatKind::Binding(_, _, ident, None) = p.kind {
|
||||||
if let Some(ty::BindByValue(hir::Mutability::Not)) =
|
if let Some(ty::BindByValue(hir::Mutability::Not)) =
|
||||||
|
@ -344,12 +339,11 @@ fn check_for_bindings_named_same_as_variants(cx: &MatchVisitor<'_, '_>, pat: &Pa
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Checks for common cases of "catchall" patterns that may not be intended as such.
|
/// Checks for common cases of "catchall" patterns that may not be intended as such.
|
||||||
fn pat_is_catchall(pat: &super::Pat<'_>) -> bool {
|
fn pat_is_catchall(pat: &DeconstructedPat<'_, '_>) -> bool {
|
||||||
use PatKind::*;
|
use Constructor::*;
|
||||||
match &*pat.kind {
|
match pat.ctor() {
|
||||||
Binding { subpattern: None, .. } => true,
|
Wildcard => true,
|
||||||
Binding { subpattern: Some(s), .. } | Deref { subpattern: s } => pat_is_catchall(s),
|
Single => pat.iter_fields().all(|pat| pat_is_catchall(pat)),
|
||||||
Leaf { subpatterns: s } => s.iter().all(|p| pat_is_catchall(&p.pattern)),
|
|
||||||
_ => false,
|
_ => false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -428,29 +422,16 @@ fn irrefutable_let_pattern(tcx: TyCtxt<'_>, id: HirId, span: Span) {
|
||||||
fn check_let_reachability<'p, 'tcx>(
|
fn check_let_reachability<'p, 'tcx>(
|
||||||
cx: &mut MatchCheckCtxt<'p, 'tcx>,
|
cx: &mut MatchCheckCtxt<'p, 'tcx>,
|
||||||
pat_id: HirId,
|
pat_id: HirId,
|
||||||
pat: &'p super::Pat<'tcx>,
|
pat: &'p DeconstructedPat<'p, 'tcx>,
|
||||||
span: Span,
|
span: Span,
|
||||||
) {
|
) {
|
||||||
let arms = [MatchArm { pat, hir_id: pat_id, has_guard: false }];
|
let arms = [MatchArm { pat, hir_id: pat_id, has_guard: false }];
|
||||||
let report = compute_match_usefulness(&cx, &arms, pat_id, pat.ty);
|
let report = compute_match_usefulness(&cx, &arms, pat_id, pat.ty());
|
||||||
|
|
||||||
report_arm_reachability(&cx, &report, |arm_index, arm_span, arm_hir_id, _| {
|
// Report if the pattern is unreachable, which can only occur when the type is uninhabited.
|
||||||
match let_source(cx.tcx, pat_id) {
|
// This also reports unreachable sub-patterns though, so we can't just replace it with an
|
||||||
LetSource::IfLet | LetSource::WhileLet => {
|
// `is_uninhabited` check.
|
||||||
match arm_index {
|
report_arm_reachability(&cx, &report);
|
||||||
// The arm with the user-specified pattern.
|
|
||||||
0 => unreachable_pattern(cx.tcx, arm_span, arm_hir_id, None),
|
|
||||||
// The arm with the wildcard pattern.
|
|
||||||
1 => irrefutable_let_pattern(cx.tcx, pat_id, arm_span),
|
|
||||||
_ => bug!(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
LetSource::IfLetGuard if arm_index == 0 => {
|
|
||||||
unreachable_pattern(cx.tcx, arm_span, arm_hir_id, None);
|
|
||||||
}
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
if report.non_exhaustiveness_witnesses.is_empty() {
|
if report.non_exhaustiveness_witnesses.is_empty() {
|
||||||
// The match is exhaustive, i.e. the `if let` pattern is irrefutable.
|
// The match is exhaustive, i.e. the `if let` pattern is irrefutable.
|
||||||
|
@ -459,18 +440,15 @@ fn check_let_reachability<'p, 'tcx>(
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Report unreachable arms, if any.
|
/// Report unreachable arms, if any.
|
||||||
fn report_arm_reachability<'p, 'tcx, F>(
|
fn report_arm_reachability<'p, 'tcx>(
|
||||||
cx: &MatchCheckCtxt<'p, 'tcx>,
|
cx: &MatchCheckCtxt<'p, 'tcx>,
|
||||||
report: &UsefulnessReport<'p, 'tcx>,
|
report: &UsefulnessReport<'p, 'tcx>,
|
||||||
unreachable: F,
|
) {
|
||||||
) where
|
|
||||||
F: Fn(usize, Span, HirId, Option<Span>),
|
|
||||||
{
|
|
||||||
use Reachability::*;
|
use Reachability::*;
|
||||||
let mut catchall = None;
|
let mut catchall = None;
|
||||||
for (arm_index, (arm, is_useful)) in report.arm_usefulness.iter().enumerate() {
|
for (arm, is_useful) in report.arm_usefulness.iter() {
|
||||||
match is_useful {
|
match is_useful {
|
||||||
Unreachable => unreachable(arm_index, arm.pat.span, arm.hir_id, catchall),
|
Unreachable => unreachable_pattern(cx.tcx, arm.pat.span(), arm.hir_id, catchall),
|
||||||
Reachable(unreachables) if unreachables.is_empty() => {}
|
Reachable(unreachables) if unreachables.is_empty() => {}
|
||||||
// The arm is reachable, but contains unreachable subpatterns (from or-patterns).
|
// The arm is reachable, but contains unreachable subpatterns (from or-patterns).
|
||||||
Reachable(unreachables) => {
|
Reachable(unreachables) => {
|
||||||
|
@ -483,7 +461,7 @@ fn report_arm_reachability<'p, 'tcx, F>(
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if !arm.has_guard && catchall.is_none() && pat_is_catchall(arm.pat) {
|
if !arm.has_guard && catchall.is_none() && pat_is_catchall(arm.pat) {
|
||||||
catchall = Some(arm.pat.span);
|
catchall = Some(arm.pat.span());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -493,7 +471,7 @@ fn non_exhaustive_match<'p, 'tcx>(
|
||||||
cx: &MatchCheckCtxt<'p, 'tcx>,
|
cx: &MatchCheckCtxt<'p, 'tcx>,
|
||||||
scrut_ty: Ty<'tcx>,
|
scrut_ty: Ty<'tcx>,
|
||||||
sp: Span,
|
sp: Span,
|
||||||
witnesses: Vec<super::Pat<'tcx>>,
|
witnesses: Vec<DeconstructedPat<'p, 'tcx>>,
|
||||||
is_empty_match: bool,
|
is_empty_match: bool,
|
||||||
) {
|
) {
|
||||||
let non_empty_enum = match scrut_ty.kind() {
|
let non_empty_enum = match scrut_ty.kind() {
|
||||||
|
@ -510,7 +488,7 @@ fn non_exhaustive_match<'p, 'tcx>(
|
||||||
format!("non-exhaustive patterns: type `{}` is non-empty", scrut_ty),
|
format!("non-exhaustive patterns: type `{}` is non-empty", scrut_ty),
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
let joined_patterns = joined_uncovered_patterns(&witnesses);
|
let joined_patterns = joined_uncovered_patterns(cx, &witnesses);
|
||||||
err = create_e0004(
|
err = create_e0004(
|
||||||
cx.tcx.sess,
|
cx.tcx.sess,
|
||||||
sp,
|
sp,
|
||||||
|
@ -537,7 +515,7 @@ fn non_exhaustive_match<'p, 'tcx>(
|
||||||
if (scrut_ty == cx.tcx.types.usize || scrut_ty == cx.tcx.types.isize)
|
if (scrut_ty == cx.tcx.types.usize || scrut_ty == cx.tcx.types.isize)
|
||||||
&& !is_empty_match
|
&& !is_empty_match
|
||||||
&& witnesses.len() == 1
|
&& witnesses.len() == 1
|
||||||
&& is_wildcard(&witnesses[0])
|
&& matches!(witnesses[0].ctor(), Constructor::NonExhaustive)
|
||||||
{
|
{
|
||||||
err.note(&format!(
|
err.note(&format!(
|
||||||
"`{}` does not have a fixed maximum value, \
|
"`{}` does not have a fixed maximum value, \
|
||||||
|
@ -560,33 +538,40 @@ fn non_exhaustive_match<'p, 'tcx>(
|
||||||
err.emit();
|
err.emit();
|
||||||
}
|
}
|
||||||
|
|
||||||
crate fn joined_uncovered_patterns(witnesses: &[super::Pat<'_>]) -> String {
|
crate fn joined_uncovered_patterns<'p, 'tcx>(
|
||||||
|
cx: &MatchCheckCtxt<'p, 'tcx>,
|
||||||
|
witnesses: &[DeconstructedPat<'p, 'tcx>],
|
||||||
|
) -> String {
|
||||||
const LIMIT: usize = 3;
|
const LIMIT: usize = 3;
|
||||||
|
let pat_to_str = |pat: &DeconstructedPat<'p, 'tcx>| pat.to_pat(cx).to_string();
|
||||||
match witnesses {
|
match witnesses {
|
||||||
[] => bug!(),
|
[] => bug!(),
|
||||||
[witness] => format!("`{}`", witness),
|
[witness] => format!("`{}`", witness.to_pat(cx)),
|
||||||
[head @ .., tail] if head.len() < LIMIT => {
|
[head @ .., tail] if head.len() < LIMIT => {
|
||||||
let head: Vec<_> = head.iter().map(<_>::to_string).collect();
|
let head: Vec<_> = head.iter().map(pat_to_str).collect();
|
||||||
format!("`{}` and `{}`", head.join("`, `"), tail)
|
format!("`{}` and `{}`", head.join("`, `"), tail.to_pat(cx))
|
||||||
}
|
}
|
||||||
_ => {
|
_ => {
|
||||||
let (head, tail) = witnesses.split_at(LIMIT);
|
let (head, tail) = witnesses.split_at(LIMIT);
|
||||||
let head: Vec<_> = head.iter().map(<_>::to_string).collect();
|
let head: Vec<_> = head.iter().map(pat_to_str).collect();
|
||||||
format!("`{}` and {} more", head.join("`, `"), tail.len())
|
format!("`{}` and {} more", head.join("`, `"), tail.len())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
crate fn pattern_not_covered_label(witnesses: &[super::Pat<'_>], joined_patterns: &str) -> String {
|
crate fn pattern_not_covered_label(
|
||||||
|
witnesses: &[DeconstructedPat<'_, '_>],
|
||||||
|
joined_patterns: &str,
|
||||||
|
) -> String {
|
||||||
format!("pattern{} {} not covered", rustc_errors::pluralize!(witnesses.len()), joined_patterns)
|
format!("pattern{} {} not covered", rustc_errors::pluralize!(witnesses.len()), joined_patterns)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Point at the definition of non-covered `enum` variants.
|
/// Point at the definition of non-covered `enum` variants.
|
||||||
fn adt_defined_here(
|
fn adt_defined_here<'p, 'tcx>(
|
||||||
cx: &MatchCheckCtxt<'_, '_>,
|
cx: &MatchCheckCtxt<'p, 'tcx>,
|
||||||
err: &mut DiagnosticBuilder<'_>,
|
err: &mut DiagnosticBuilder<'_>,
|
||||||
ty: Ty<'_>,
|
ty: Ty<'tcx>,
|
||||||
witnesses: &[super::Pat<'_>],
|
witnesses: &[DeconstructedPat<'p, 'tcx>],
|
||||||
) {
|
) {
|
||||||
let ty = ty.peel_refs();
|
let ty = ty.peel_refs();
|
||||||
if let ty::Adt(def, _) = ty.kind() {
|
if let ty::Adt(def, _) = ty.kind() {
|
||||||
|
@ -595,57 +580,42 @@ fn adt_defined_here(
|
||||||
}
|
}
|
||||||
|
|
||||||
if witnesses.len() < 4 {
|
if witnesses.len() < 4 {
|
||||||
for sp in maybe_point_at_variant(ty, &witnesses) {
|
for sp in maybe_point_at_variant(cx, def, witnesses.iter()) {
|
||||||
err.span_label(sp, "not covered");
|
err.span_label(sp, "not covered");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn maybe_point_at_variant(ty: Ty<'_>, patterns: &[super::Pat<'_>]) -> Vec<Span> {
|
fn maybe_point_at_variant<'a, 'p: 'a, 'tcx: 'a>(
|
||||||
|
cx: &MatchCheckCtxt<'p, 'tcx>,
|
||||||
|
def: &AdtDef,
|
||||||
|
patterns: impl Iterator<Item = &'a DeconstructedPat<'p, 'tcx>>,
|
||||||
|
) -> Vec<Span> {
|
||||||
|
use Constructor::*;
|
||||||
let mut covered = vec![];
|
let mut covered = vec![];
|
||||||
if let ty::Adt(def, _) = ty.kind() {
|
for pattern in patterns {
|
||||||
// Don't point at variants that have already been covered due to other patterns to avoid
|
if let Variant(variant_index) = pattern.ctor() {
|
||||||
// visual clutter.
|
if let ty::Adt(this_def, _) = pattern.ty().kind() {
|
||||||
for pattern in patterns {
|
if this_def.did != def.did {
|
||||||
use PatKind::{AscribeUserType, Deref, Leaf, Or, Variant};
|
continue;
|
||||||
match &*pattern.kind {
|
|
||||||
AscribeUserType { subpattern, .. } | Deref { subpattern } => {
|
|
||||||
covered.extend(maybe_point_at_variant(ty, slice::from_ref(&subpattern)));
|
|
||||||
}
|
}
|
||||||
Variant { adt_def, variant_index, subpatterns, .. } if adt_def.did == def.did => {
|
|
||||||
let sp = def.variants[*variant_index].ident.span;
|
|
||||||
if covered.contains(&sp) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
covered.push(sp);
|
|
||||||
|
|
||||||
let pats = subpatterns
|
|
||||||
.iter()
|
|
||||||
.map(|field_pattern| field_pattern.pattern.clone())
|
|
||||||
.collect::<Box<[_]>>();
|
|
||||||
covered.extend(maybe_point_at_variant(ty, &pats));
|
|
||||||
}
|
|
||||||
Leaf { subpatterns } => {
|
|
||||||
let pats = subpatterns
|
|
||||||
.iter()
|
|
||||||
.map(|field_pattern| field_pattern.pattern.clone())
|
|
||||||
.collect::<Box<[_]>>();
|
|
||||||
covered.extend(maybe_point_at_variant(ty, &pats));
|
|
||||||
}
|
|
||||||
Or { pats } => {
|
|
||||||
let pats = pats.iter().cloned().collect::<Box<[_]>>();
|
|
||||||
covered.extend(maybe_point_at_variant(ty, &pats));
|
|
||||||
}
|
|
||||||
_ => {}
|
|
||||||
}
|
}
|
||||||
|
let sp = def.variants[*variant_index].ident.span;
|
||||||
|
if covered.contains(&sp) {
|
||||||
|
// Don't point at variants that have already been covered due to other patterns to avoid
|
||||||
|
// visual clutter.
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
covered.push(sp);
|
||||||
}
|
}
|
||||||
|
covered.extend(maybe_point_at_variant(cx, def, pattern.iter_fields()));
|
||||||
}
|
}
|
||||||
covered
|
covered
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Check if a by-value binding is by-value. That is, check if the binding's type is not `Copy`.
|
/// Check if a by-value binding is by-value. That is, check if the binding's type is not `Copy`.
|
||||||
fn is_binding_by_move(cx: &MatchVisitor<'_, '_>, hir_id: HirId, span: Span) -> bool {
|
fn is_binding_by_move(cx: &MatchVisitor<'_, '_, '_>, hir_id: HirId, span: Span) -> bool {
|
||||||
!cx.typeck_results.node_type(hir_id).is_copy_modulo_regions(cx.tcx.at(span), cx.param_env)
|
!cx.typeck_results.node_type(hir_id).is_copy_modulo_regions(cx.tcx.at(span), cx.param_env)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -659,7 +629,7 @@ fn is_binding_by_move(cx: &MatchVisitor<'_, '_>, hir_id: HirId, span: Span) -> b
|
||||||
/// - `x @ Some(ref mut? y)`.
|
/// - `x @ Some(ref mut? y)`.
|
||||||
///
|
///
|
||||||
/// This analysis is *not* subsumed by NLL.
|
/// This analysis is *not* subsumed by NLL.
|
||||||
fn check_borrow_conflicts_in_at_patterns(cx: &MatchVisitor<'_, '_>, pat: &Pat<'_>) {
|
fn check_borrow_conflicts_in_at_patterns(cx: &MatchVisitor<'_, '_, '_>, pat: &Pat<'_>) {
|
||||||
// Extract `sub` in `binding @ sub`.
|
// Extract `sub` in `binding @ sub`.
|
||||||
let (name, sub) = match &pat.kind {
|
let (name, sub) = match &pat.kind {
|
||||||
hir::PatKind::Binding(.., name, Some(sub)) => (*name, sub),
|
hir::PatKind::Binding(.., name, Some(sub)) => (*name, sub),
|
||||||
|
|
File diff suppressed because it is too large
Load diff
|
@ -284,27 +284,22 @@ use self::ArmType::*;
|
||||||
use self::Usefulness::*;
|
use self::Usefulness::*;
|
||||||
|
|
||||||
use super::check_match::{joined_uncovered_patterns, pattern_not_covered_label};
|
use super::check_match::{joined_uncovered_patterns, pattern_not_covered_label};
|
||||||
use super::deconstruct_pat::{Constructor, Fields, SplitWildcard};
|
use super::deconstruct_pat::{Constructor, DeconstructedPat, Fields, SplitWildcard};
|
||||||
use super::{PatternFoldable, PatternFolder};
|
|
||||||
|
|
||||||
use rustc_data_structures::captures::Captures;
|
use rustc_data_structures::captures::Captures;
|
||||||
use rustc_data_structures::fx::FxHashMap;
|
|
||||||
|
|
||||||
use hir::def_id::DefId;
|
|
||||||
use hir::HirId;
|
|
||||||
use rustc_arena::TypedArena;
|
use rustc_arena::TypedArena;
|
||||||
use rustc_hir as hir;
|
use rustc_hir::def_id::DefId;
|
||||||
use rustc_middle::thir::{Pat, PatKind};
|
use rustc_hir::HirId;
|
||||||
use rustc_middle::ty::{self, Ty, TyCtxt};
|
use rustc_middle::ty::{self, Ty, TyCtxt};
|
||||||
use rustc_session::lint::builtin::NON_EXHAUSTIVE_OMITTED_PATTERNS;
|
use rustc_session::lint::builtin::NON_EXHAUSTIVE_OMITTED_PATTERNS;
|
||||||
use rustc_span::Span;
|
use rustc_span::{Span, DUMMY_SP};
|
||||||
|
|
||||||
use smallvec::{smallvec, SmallVec};
|
use smallvec::{smallvec, SmallVec};
|
||||||
use std::fmt;
|
use std::fmt;
|
||||||
use std::iter::{FromIterator, IntoIterator};
|
use std::iter::once;
|
||||||
use std::lazy::OnceCell;
|
|
||||||
|
|
||||||
crate struct MatchCheckCtxt<'a, 'tcx> {
|
crate struct MatchCheckCtxt<'p, 'tcx> {
|
||||||
crate tcx: TyCtxt<'tcx>,
|
crate tcx: TyCtxt<'tcx>,
|
||||||
/// The module in which the match occurs. This is necessary for
|
/// The module in which the match occurs. This is necessary for
|
||||||
/// checking inhabited-ness of types because whether a type is (visibly)
|
/// checking inhabited-ness of types because whether a type is (visibly)
|
||||||
|
@ -313,7 +308,7 @@ crate struct MatchCheckCtxt<'a, 'tcx> {
|
||||||
/// outside its module and should not be matchable with an empty match statement.
|
/// outside its module and should not be matchable with an empty match statement.
|
||||||
crate module: DefId,
|
crate module: DefId,
|
||||||
crate param_env: ty::ParamEnv<'tcx>,
|
crate param_env: ty::ParamEnv<'tcx>,
|
||||||
crate pattern_arena: &'a TypedArena<Pat<'tcx>>,
|
crate pattern_arena: &'p TypedArena<DeconstructedPat<'p, 'tcx>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a, 'tcx> MatchCheckCtxt<'a, 'tcx> {
|
impl<'a, 'tcx> MatchCheckCtxt<'a, 'tcx> {
|
||||||
|
@ -356,78 +351,20 @@ impl<'a, 'p, 'tcx> fmt::Debug for PatCtxt<'a, 'p, 'tcx> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
crate fn expand_pattern<'tcx>(pat: Pat<'tcx>) -> Pat<'tcx> {
|
|
||||||
LiteralExpander.fold_pattern(&pat)
|
|
||||||
}
|
|
||||||
|
|
||||||
struct LiteralExpander;
|
|
||||||
|
|
||||||
impl<'tcx> PatternFolder<'tcx> for LiteralExpander {
|
|
||||||
fn fold_pattern(&mut self, pat: &Pat<'tcx>) -> Pat<'tcx> {
|
|
||||||
debug!("fold_pattern {:?} {:?} {:?}", pat, pat.ty.kind(), pat.kind);
|
|
||||||
match (pat.ty.kind(), pat.kind.as_ref()) {
|
|
||||||
(_, PatKind::Binding { subpattern: Some(s), .. }) => s.fold_with(self),
|
|
||||||
(_, PatKind::AscribeUserType { subpattern: s, .. }) => s.fold_with(self),
|
|
||||||
(ty::Ref(_, t, _), PatKind::Constant { .. }) if t.is_str() => {
|
|
||||||
// Treat string literal patterns as deref patterns to a `str` constant, i.e.
|
|
||||||
// `&CONST`. This expands them like other const patterns. This could have been done
|
|
||||||
// in `const_to_pat`, but that causes issues with the rest of the matching code.
|
|
||||||
let mut new_pat = pat.super_fold_with(self);
|
|
||||||
// Make a fake const pattern of type `str` (instead of `&str`). That the carried
|
|
||||||
// constant value still knows it is of type `&str`.
|
|
||||||
new_pat.ty = t;
|
|
||||||
Pat {
|
|
||||||
kind: Box::new(PatKind::Deref { subpattern: new_pat }),
|
|
||||||
span: pat.span,
|
|
||||||
ty: pat.ty,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_ => pat.super_fold_with(self),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn is_wildcard(pat: &Pat<'_>) -> bool {
|
|
||||||
matches!(*pat.kind, PatKind::Binding { subpattern: None, .. } | PatKind::Wild)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn is_or_pat(pat: &Pat<'_>) -> bool {
|
|
||||||
matches!(*pat.kind, PatKind::Or { .. })
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Recursively expand this pattern into its subpatterns. Only useful for or-patterns.
|
|
||||||
fn expand_or_pat<'p, 'tcx>(pat: &'p Pat<'tcx>) -> Vec<&'p Pat<'tcx>> {
|
|
||||||
fn expand<'p, 'tcx>(pat: &'p Pat<'tcx>, vec: &mut Vec<&'p Pat<'tcx>>) {
|
|
||||||
if let PatKind::Or { pats } = pat.kind.as_ref() {
|
|
||||||
for pat in pats {
|
|
||||||
expand(pat, vec);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
vec.push(pat)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut pats = Vec::new();
|
|
||||||
expand(pat, &mut pats);
|
|
||||||
pats
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A row of a matrix. Rows of len 1 are very common, which is why `SmallVec[_; 2]`
|
/// A row of a matrix. Rows of len 1 are very common, which is why `SmallVec[_; 2]`
|
||||||
/// works well.
|
/// works well.
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
struct PatStack<'p, 'tcx> {
|
struct PatStack<'p, 'tcx> {
|
||||||
pats: SmallVec<[&'p Pat<'tcx>; 2]>,
|
pats: SmallVec<[&'p DeconstructedPat<'p, 'tcx>; 2]>,
|
||||||
/// Cache for the constructor of the head
|
|
||||||
head_ctor: OnceCell<Constructor<'tcx>>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'p, 'tcx> PatStack<'p, 'tcx> {
|
impl<'p, 'tcx> PatStack<'p, 'tcx> {
|
||||||
fn from_pattern(pat: &'p Pat<'tcx>) -> Self {
|
fn from_pattern(pat: &'p DeconstructedPat<'p, 'tcx>) -> Self {
|
||||||
Self::from_vec(smallvec![pat])
|
Self::from_vec(smallvec![pat])
|
||||||
}
|
}
|
||||||
|
|
||||||
fn from_vec(vec: SmallVec<[&'p Pat<'tcx>; 2]>) -> Self {
|
fn from_vec(vec: SmallVec<[&'p DeconstructedPat<'p, 'tcx>; 2]>) -> Self {
|
||||||
PatStack { pats: vec, head_ctor: OnceCell::new() }
|
PatStack { pats: vec }
|
||||||
}
|
}
|
||||||
|
|
||||||
fn is_empty(&self) -> bool {
|
fn is_empty(&self) -> bool {
|
||||||
|
@ -438,79 +375,56 @@ impl<'p, 'tcx> PatStack<'p, 'tcx> {
|
||||||
self.pats.len()
|
self.pats.len()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn head(&self) -> &'p Pat<'tcx> {
|
fn head(&self) -> &'p DeconstructedPat<'p, 'tcx> {
|
||||||
self.pats[0]
|
self.pats[0]
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
fn iter(&self) -> impl Iterator<Item = &DeconstructedPat<'p, 'tcx>> {
|
||||||
fn head_ctor<'a>(&'a self, cx: &MatchCheckCtxt<'p, 'tcx>) -> &'a Constructor<'tcx> {
|
|
||||||
self.head_ctor.get_or_init(|| Constructor::from_pat(cx, self.head()))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn iter(&self) -> impl Iterator<Item = &Pat<'tcx>> {
|
|
||||||
self.pats.iter().copied()
|
self.pats.iter().copied()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Recursively expand the first pattern into its subpatterns. Only useful if the pattern is an
|
// Recursively expand the first pattern into its subpatterns. Only useful if the pattern is an
|
||||||
// or-pattern. Panics if `self` is empty.
|
// or-pattern. Panics if `self` is empty.
|
||||||
fn expand_or_pat<'a>(&'a self) -> impl Iterator<Item = PatStack<'p, 'tcx>> + Captures<'a> {
|
fn expand_or_pat<'a>(&'a self) -> impl Iterator<Item = PatStack<'p, 'tcx>> + Captures<'a> {
|
||||||
expand_or_pat(self.head()).into_iter().map(move |pat| {
|
self.head().iter_fields().map(move |pat| {
|
||||||
let mut new_patstack = PatStack::from_pattern(pat);
|
let mut new_patstack = PatStack::from_pattern(pat);
|
||||||
new_patstack.pats.extend_from_slice(&self.pats[1..]);
|
new_patstack.pats.extend_from_slice(&self.pats[1..]);
|
||||||
new_patstack
|
new_patstack
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// This computes `S(self.head_ctor(), self)`. See top of the file for explanations.
|
/// This computes `S(self.head().ctor(), self)`. See top of the file for explanations.
|
||||||
///
|
///
|
||||||
/// Structure patterns with a partial wild pattern (Foo { a: 42, .. }) have their missing
|
/// Structure patterns with a partial wild pattern (Foo { a: 42, .. }) have their missing
|
||||||
/// fields filled with wild patterns.
|
/// fields filled with wild patterns.
|
||||||
///
|
///
|
||||||
/// This is roughly the inverse of `Constructor::apply`.
|
/// This is roughly the inverse of `Constructor::apply`.
|
||||||
fn pop_head_constructor(&self, ctor_wild_subpatterns: &Fields<'p, 'tcx>) -> PatStack<'p, 'tcx> {
|
fn pop_head_constructor(
|
||||||
|
&self,
|
||||||
|
cx: &MatchCheckCtxt<'p, 'tcx>,
|
||||||
|
ctor: &Constructor<'tcx>,
|
||||||
|
) -> PatStack<'p, 'tcx> {
|
||||||
// We pop the head pattern and push the new fields extracted from the arguments of
|
// We pop the head pattern and push the new fields extracted from the arguments of
|
||||||
// `self.head()`.
|
// `self.head()`.
|
||||||
let mut new_fields =
|
let mut new_fields: SmallVec<[_; 2]> = self.head().specialize(cx, ctor);
|
||||||
ctor_wild_subpatterns.replace_with_pattern_arguments(self.head()).into_patterns();
|
|
||||||
new_fields.extend_from_slice(&self.pats[1..]);
|
new_fields.extend_from_slice(&self.pats[1..]);
|
||||||
PatStack::from_vec(new_fields)
|
PatStack::from_vec(new_fields)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'p, 'tcx> Default for PatStack<'p, 'tcx> {
|
|
||||||
fn default() -> Self {
|
|
||||||
Self::from_vec(smallvec![])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'p, 'tcx> PartialEq for PatStack<'p, 'tcx> {
|
|
||||||
fn eq(&self, other: &Self) -> bool {
|
|
||||||
self.pats == other.pats
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'p, 'tcx> FromIterator<&'p Pat<'tcx>> for PatStack<'p, 'tcx> {
|
|
||||||
fn from_iter<T>(iter: T) -> Self
|
|
||||||
where
|
|
||||||
T: IntoIterator<Item = &'p Pat<'tcx>>,
|
|
||||||
{
|
|
||||||
Self::from_vec(iter.into_iter().collect())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Pretty-printing for matrix row.
|
/// Pretty-printing for matrix row.
|
||||||
impl<'p, 'tcx> fmt::Debug for PatStack<'p, 'tcx> {
|
impl<'p, 'tcx> fmt::Debug for PatStack<'p, 'tcx> {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
write!(f, "+")?;
|
write!(f, "+")?;
|
||||||
for pat in self.iter() {
|
for pat in self.iter() {
|
||||||
write!(f, " {} +", pat)?;
|
write!(f, " {:?} +", pat)?;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A 2D matrix.
|
/// A 2D matrix.
|
||||||
#[derive(Clone, PartialEq)]
|
#[derive(Clone)]
|
||||||
pub(super) struct Matrix<'p, 'tcx> {
|
pub(super) struct Matrix<'p, 'tcx> {
|
||||||
patterns: Vec<PatStack<'p, 'tcx>>,
|
patterns: Vec<PatStack<'p, 'tcx>>,
|
||||||
}
|
}
|
||||||
|
@ -528,7 +442,7 @@ impl<'p, 'tcx> Matrix<'p, 'tcx> {
|
||||||
/// Pushes a new row to the matrix. If the row starts with an or-pattern, this recursively
|
/// Pushes a new row to the matrix. If the row starts with an or-pattern, this recursively
|
||||||
/// expands it.
|
/// expands it.
|
||||||
fn push(&mut self, row: PatStack<'p, 'tcx>) {
|
fn push(&mut self, row: PatStack<'p, 'tcx>) {
|
||||||
if !row.is_empty() && is_or_pat(row.head()) {
|
if !row.is_empty() && row.head().is_or_pat() {
|
||||||
for row in row.expand_or_pat() {
|
for row in row.expand_or_pat() {
|
||||||
self.patterns.push(row);
|
self.patterns.push(row);
|
||||||
}
|
}
|
||||||
|
@ -538,38 +452,26 @@ impl<'p, 'tcx> Matrix<'p, 'tcx> {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Iterate over the first component of each row
|
/// Iterate over the first component of each row
|
||||||
fn heads<'a>(&'a self) -> impl Iterator<Item = &'a Pat<'tcx>> + Captures<'p> {
|
fn heads<'a>(
|
||||||
|
&'a self,
|
||||||
|
) -> impl Iterator<Item = &'p DeconstructedPat<'p, 'tcx>> + Clone + Captures<'a> {
|
||||||
self.patterns.iter().map(|r| r.head())
|
self.patterns.iter().map(|r| r.head())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Iterate over the first constructor of each row.
|
|
||||||
pub(super) fn head_ctors<'a>(
|
|
||||||
&'a self,
|
|
||||||
cx: &'a MatchCheckCtxt<'p, 'tcx>,
|
|
||||||
) -> impl Iterator<Item = &'a Constructor<'tcx>> + Captures<'p> + Clone {
|
|
||||||
self.patterns.iter().map(move |r| r.head_ctor(cx))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Iterate over the first constructor and the corresponding span of each row.
|
|
||||||
pub(super) fn head_ctors_and_spans<'a>(
|
|
||||||
&'a self,
|
|
||||||
cx: &'a MatchCheckCtxt<'p, 'tcx>,
|
|
||||||
) -> impl Iterator<Item = (&'a Constructor<'tcx>, Span)> + Captures<'p> {
|
|
||||||
self.patterns.iter().map(move |r| (r.head_ctor(cx), r.head().span))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// This computes `S(constructor, self)`. See top of the file for explanations.
|
/// This computes `S(constructor, self)`. See top of the file for explanations.
|
||||||
fn specialize_constructor(
|
fn specialize_constructor(
|
||||||
&self,
|
&self,
|
||||||
pcx: PatCtxt<'_, 'p, 'tcx>,
|
pcx: PatCtxt<'_, 'p, 'tcx>,
|
||||||
ctor: &Constructor<'tcx>,
|
ctor: &Constructor<'tcx>,
|
||||||
ctor_wild_subpatterns: &Fields<'p, 'tcx>,
|
|
||||||
) -> Matrix<'p, 'tcx> {
|
) -> Matrix<'p, 'tcx> {
|
||||||
self.patterns
|
let mut matrix = Matrix::empty();
|
||||||
.iter()
|
for row in &self.patterns {
|
||||||
.filter(|r| ctor.is_covered_by(pcx, r.head_ctor(pcx.cx)))
|
if ctor.is_covered_by(pcx, row.head().ctor()) {
|
||||||
.map(|r| r.pop_head_constructor(ctor_wild_subpatterns))
|
let new_row = row.pop_head_constructor(pcx.cx, ctor);
|
||||||
.collect()
|
matrix.push(new_row);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
matrix
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -588,7 +490,7 @@ impl<'p, 'tcx> fmt::Debug for Matrix<'p, 'tcx> {
|
||||||
|
|
||||||
let Matrix { patterns: m, .. } = self;
|
let Matrix { patterns: m, .. } = self;
|
||||||
let pretty_printed_matrix: Vec<Vec<String>> =
|
let pretty_printed_matrix: Vec<Vec<String>> =
|
||||||
m.iter().map(|row| row.iter().map(|pat| format!("{}", pat)).collect()).collect();
|
m.iter().map(|row| row.iter().map(|pat| format!("{:?}", pat)).collect()).collect();
|
||||||
|
|
||||||
let column_count = m.iter().map(|row| row.len()).next().unwrap_or(0);
|
let column_count = m.iter().map(|row| row.len()).next().unwrap_or(0);
|
||||||
assert!(m.iter().all(|row| row.len() == column_count));
|
assert!(m.iter().all(|row| row.len() == column_count));
|
||||||
|
@ -609,296 +511,40 @@ impl<'p, 'tcx> fmt::Debug for Matrix<'p, 'tcx> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'p, 'tcx> FromIterator<PatStack<'p, 'tcx>> for Matrix<'p, 'tcx> {
|
|
||||||
fn from_iter<T>(iter: T) -> Self
|
|
||||||
where
|
|
||||||
T: IntoIterator<Item = PatStack<'p, 'tcx>>,
|
|
||||||
{
|
|
||||||
let mut matrix = Matrix::empty();
|
|
||||||
for x in iter {
|
|
||||||
// Using `push` ensures we correctly expand or-patterns.
|
|
||||||
matrix.push(x);
|
|
||||||
}
|
|
||||||
matrix
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Given a pattern or a pattern-stack, this struct captures a set of its subpatterns. We use that
|
|
||||||
/// to track reachable sub-patterns arising from or-patterns. In the absence of or-patterns this
|
|
||||||
/// will always be either `Empty` (the whole pattern is unreachable) or `Full` (the whole pattern
|
|
||||||
/// is reachable). When there are or-patterns, some subpatterns may be reachable while others
|
|
||||||
/// aren't. In this case the whole pattern still counts as reachable, but we will lint the
|
|
||||||
/// unreachable subpatterns.
|
|
||||||
///
|
|
||||||
/// This supports a limited set of operations, so not all possible sets of subpatterns can be
|
|
||||||
/// represented. That's ok, we only want the ones that make sense for our usage.
|
|
||||||
///
|
|
||||||
/// What we're doing is illustrated by this:
|
|
||||||
/// ```
|
|
||||||
/// match (true, 0) {
|
|
||||||
/// (true, 0) => {}
|
|
||||||
/// (_, 1) => {}
|
|
||||||
/// (true | false, 0 | 1) => {}
|
|
||||||
/// }
|
|
||||||
/// ```
|
|
||||||
/// When we try the alternatives of the `true | false` or-pattern, the last `0` is reachable in the
|
|
||||||
/// `false` alternative but not the `true`. So overall it is reachable. By contrast, the last `1`
|
|
||||||
/// is not reachable in either alternative, so we want to signal this to the user.
|
|
||||||
/// Therefore we take the union of sets of reachable patterns coming from different alternatives in
|
|
||||||
/// order to figure out which subpatterns are overall reachable.
|
|
||||||
///
|
|
||||||
/// Invariant: we try to construct the smallest representation we can. In particular if
|
|
||||||
/// `self.is_empty()` we ensure that `self` is `Empty`, and same with `Full`. This is not important
|
|
||||||
/// for correctness currently.
|
|
||||||
#[derive(Debug, Clone)]
|
|
||||||
enum SubPatSet<'p, 'tcx> {
|
|
||||||
/// The empty set. This means the pattern is unreachable.
|
|
||||||
Empty,
|
|
||||||
/// The set containing the full pattern.
|
|
||||||
Full,
|
|
||||||
/// If the pattern is a pattern with a constructor or a pattern-stack, we store a set for each
|
|
||||||
/// of its subpatterns. Missing entries in the map are implicitly full, because that's the
|
|
||||||
/// common case.
|
|
||||||
Seq { subpats: FxHashMap<usize, SubPatSet<'p, 'tcx>> },
|
|
||||||
/// If the pattern is an or-pattern, we store a set for each of its alternatives. Missing
|
|
||||||
/// entries in the map are implicitly empty. Note: we always flatten nested or-patterns.
|
|
||||||
Alt {
|
|
||||||
subpats: FxHashMap<usize, SubPatSet<'p, 'tcx>>,
|
|
||||||
/// Counts the total number of alternatives in the pattern
|
|
||||||
alt_count: usize,
|
|
||||||
/// We keep the pattern around to retrieve spans.
|
|
||||||
pat: &'p Pat<'tcx>,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'p, 'tcx> SubPatSet<'p, 'tcx> {
|
|
||||||
fn full() -> Self {
|
|
||||||
SubPatSet::Full
|
|
||||||
}
|
|
||||||
fn empty() -> Self {
|
|
||||||
SubPatSet::Empty
|
|
||||||
}
|
|
||||||
|
|
||||||
fn is_empty(&self) -> bool {
|
|
||||||
match self {
|
|
||||||
SubPatSet::Empty => true,
|
|
||||||
SubPatSet::Full => false,
|
|
||||||
// If any subpattern in a sequence is unreachable, the whole pattern is unreachable.
|
|
||||||
SubPatSet::Seq { subpats } => subpats.values().any(|set| set.is_empty()),
|
|
||||||
// An or-pattern is reachable if any of its alternatives is.
|
|
||||||
SubPatSet::Alt { subpats, .. } => subpats.values().all(|set| set.is_empty()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn is_full(&self) -> bool {
|
|
||||||
match self {
|
|
||||||
SubPatSet::Empty => false,
|
|
||||||
SubPatSet::Full => true,
|
|
||||||
// The whole pattern is reachable only when all its alternatives are.
|
|
||||||
SubPatSet::Seq { subpats } => subpats.values().all(|sub_set| sub_set.is_full()),
|
|
||||||
// The whole or-pattern is reachable only when all its alternatives are.
|
|
||||||
SubPatSet::Alt { subpats, alt_count, .. } => {
|
|
||||||
subpats.len() == *alt_count && subpats.values().all(|set| set.is_full())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Union `self` with `other`, mutating `self`.
|
|
||||||
fn union(&mut self, other: Self) {
|
|
||||||
use SubPatSet::*;
|
|
||||||
// Union with full stays full; union with empty changes nothing.
|
|
||||||
if self.is_full() || other.is_empty() {
|
|
||||||
return;
|
|
||||||
} else if self.is_empty() {
|
|
||||||
*self = other;
|
|
||||||
return;
|
|
||||||
} else if other.is_full() {
|
|
||||||
*self = Full;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
match (&mut *self, other) {
|
|
||||||
(Seq { subpats: s_set }, Seq { subpats: mut o_set }) => {
|
|
||||||
s_set.retain(|i, s_sub_set| {
|
|
||||||
// Missing entries count as full.
|
|
||||||
let o_sub_set = o_set.remove(&i).unwrap_or(Full);
|
|
||||||
s_sub_set.union(o_sub_set);
|
|
||||||
// We drop full entries.
|
|
||||||
!s_sub_set.is_full()
|
|
||||||
});
|
|
||||||
// Everything left in `o_set` is missing from `s_set`, i.e. counts as full. Since
|
|
||||||
// unioning with full returns full, we can drop those entries.
|
|
||||||
}
|
|
||||||
(Alt { subpats: s_set, .. }, Alt { subpats: mut o_set, .. }) => {
|
|
||||||
s_set.retain(|i, s_sub_set| {
|
|
||||||
// Missing entries count as empty.
|
|
||||||
let o_sub_set = o_set.remove(&i).unwrap_or(Empty);
|
|
||||||
s_sub_set.union(o_sub_set);
|
|
||||||
// We drop empty entries.
|
|
||||||
!s_sub_set.is_empty()
|
|
||||||
});
|
|
||||||
// Everything left in `o_set` is missing from `s_set`, i.e. counts as empty. Since
|
|
||||||
// unioning with empty changes nothing, we can take those entries as is.
|
|
||||||
s_set.extend(o_set);
|
|
||||||
}
|
|
||||||
_ => bug!(),
|
|
||||||
}
|
|
||||||
|
|
||||||
if self.is_full() {
|
|
||||||
*self = Full;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns a list of the spans of the unreachable subpatterns. If `self` is empty (i.e. the
|
|
||||||
/// whole pattern is unreachable) we return `None`.
|
|
||||||
fn list_unreachable_spans(&self) -> Option<Vec<Span>> {
|
|
||||||
/// Panics if `set.is_empty()`.
|
|
||||||
fn fill_spans(set: &SubPatSet<'_, '_>, spans: &mut Vec<Span>) {
|
|
||||||
match set {
|
|
||||||
SubPatSet::Empty => bug!(),
|
|
||||||
SubPatSet::Full => {}
|
|
||||||
SubPatSet::Seq { subpats } => {
|
|
||||||
for (_, sub_set) in subpats {
|
|
||||||
fill_spans(sub_set, spans);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
SubPatSet::Alt { subpats, pat, alt_count, .. } => {
|
|
||||||
let expanded = expand_or_pat(pat);
|
|
||||||
for i in 0..*alt_count {
|
|
||||||
let sub_set = subpats.get(&i).unwrap_or(&SubPatSet::Empty);
|
|
||||||
if sub_set.is_empty() {
|
|
||||||
// Found an unreachable subpattern.
|
|
||||||
spans.push(expanded[i].span);
|
|
||||||
} else {
|
|
||||||
fill_spans(sub_set, spans);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if self.is_empty() {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
if self.is_full() {
|
|
||||||
// No subpatterns are unreachable.
|
|
||||||
return Some(Vec::new());
|
|
||||||
}
|
|
||||||
let mut spans = Vec::new();
|
|
||||||
fill_spans(self, &mut spans);
|
|
||||||
Some(spans)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// When `self` refers to a patstack that was obtained from specialization, after running
|
|
||||||
/// `unspecialize` it will refer to the original patstack before specialization.
|
|
||||||
fn unspecialize(self, arity: usize) -> Self {
|
|
||||||
use SubPatSet::*;
|
|
||||||
match self {
|
|
||||||
Full => Full,
|
|
||||||
Empty => Empty,
|
|
||||||
Seq { subpats } => {
|
|
||||||
// We gather the first `arity` subpatterns together and shift the remaining ones.
|
|
||||||
let mut new_subpats = FxHashMap::default();
|
|
||||||
let mut new_subpats_first_col = FxHashMap::default();
|
|
||||||
for (i, sub_set) in subpats {
|
|
||||||
if i < arity {
|
|
||||||
// The first `arity` indices are now part of the pattern in the first
|
|
||||||
// column.
|
|
||||||
new_subpats_first_col.insert(i, sub_set);
|
|
||||||
} else {
|
|
||||||
// Indices after `arity` are simply shifted
|
|
||||||
new_subpats.insert(i - arity + 1, sub_set);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// If `new_subpats_first_col` has no entries it counts as full, so we can omit it.
|
|
||||||
if !new_subpats_first_col.is_empty() {
|
|
||||||
new_subpats.insert(0, Seq { subpats: new_subpats_first_col });
|
|
||||||
}
|
|
||||||
Seq { subpats: new_subpats }
|
|
||||||
}
|
|
||||||
Alt { .. } => bug!(), // `self` is a patstack
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// When `self` refers to a patstack that was obtained from splitting an or-pattern, after
|
|
||||||
/// running `unspecialize` it will refer to the original patstack before splitting.
|
|
||||||
///
|
|
||||||
/// For example:
|
|
||||||
/// ```
|
|
||||||
/// match Some(true) {
|
|
||||||
/// Some(true) => {}
|
|
||||||
/// None | Some(true | false) => {}
|
|
||||||
/// }
|
|
||||||
/// ```
|
|
||||||
/// Here `None` would return the full set and `Some(true | false)` would return the set
|
|
||||||
/// containing `false`. After `unsplit_or_pat`, we want the set to contain `None` and `false`.
|
|
||||||
/// This is what this function does.
|
|
||||||
fn unsplit_or_pat(mut self, alt_id: usize, alt_count: usize, pat: &'p Pat<'tcx>) -> Self {
|
|
||||||
use SubPatSet::*;
|
|
||||||
if self.is_empty() {
|
|
||||||
return Empty;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Subpatterns coming from inside the or-pattern alternative itself, e.g. in `None | Some(0
|
|
||||||
// | 1)`.
|
|
||||||
let set_first_col = match &mut self {
|
|
||||||
Full => Full,
|
|
||||||
Seq { subpats } => subpats.remove(&0).unwrap_or(Full),
|
|
||||||
Empty => unreachable!(),
|
|
||||||
Alt { .. } => bug!(), // `self` is a patstack
|
|
||||||
};
|
|
||||||
let mut subpats_first_col = FxHashMap::default();
|
|
||||||
subpats_first_col.insert(alt_id, set_first_col);
|
|
||||||
let set_first_col = Alt { subpats: subpats_first_col, pat, alt_count };
|
|
||||||
|
|
||||||
let mut subpats = match self {
|
|
||||||
Full => FxHashMap::default(),
|
|
||||||
Seq { subpats } => subpats,
|
|
||||||
Empty => unreachable!(),
|
|
||||||
Alt { .. } => bug!(), // `self` is a patstack
|
|
||||||
};
|
|
||||||
subpats.insert(0, set_first_col);
|
|
||||||
Seq { subpats }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// This carries the results of computing usefulness, as described at the top of the file. When
|
/// This carries the results of computing usefulness, as described at the top of the file. When
|
||||||
/// checking usefulness of a match branch, we use the `NoWitnesses` variant, which also keeps track
|
/// checking usefulness of a match branch, we use the `NoWitnesses` variant, which also keeps track
|
||||||
/// of potential unreachable sub-patterns (in the presence of or-patterns). When checking
|
/// of potential unreachable sub-patterns (in the presence of or-patterns). When checking
|
||||||
/// exhaustiveness of a whole match, we use the `WithWitnesses` variant, which carries a list of
|
/// exhaustiveness of a whole match, we use the `WithWitnesses` variant, which carries a list of
|
||||||
/// witnesses of non-exhaustiveness when there are any.
|
/// witnesses of non-exhaustiveness when there are any.
|
||||||
/// Which variant to use is dictated by `ArmType`.
|
/// Which variant to use is dictated by `ArmType`.
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Debug)]
|
||||||
enum Usefulness<'p, 'tcx> {
|
enum Usefulness<'p, 'tcx> {
|
||||||
/// Carries a set of subpatterns that have been found to be reachable. If empty, this indicates
|
/// If we don't care about witnesses, simply remember if the pattern was useful.
|
||||||
/// the whole pattern is unreachable. If not, this indicates that the pattern is reachable but
|
NoWitnesses { useful: bool },
|
||||||
/// that some sub-patterns may be unreachable (due to or-patterns). In the absence of
|
|
||||||
/// or-patterns this will always be either `Empty` (the whole pattern is unreachable) or `Full`
|
|
||||||
/// (the whole pattern is reachable).
|
|
||||||
NoWitnesses(SubPatSet<'p, 'tcx>),
|
|
||||||
/// Carries a list of witnesses of non-exhaustiveness. If empty, indicates that the whole
|
/// Carries a list of witnesses of non-exhaustiveness. If empty, indicates that the whole
|
||||||
/// pattern is unreachable.
|
/// pattern is unreachable.
|
||||||
WithWitnesses(Vec<Witness<'tcx>>),
|
WithWitnesses(Vec<Witness<'p, 'tcx>>),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'p, 'tcx> Usefulness<'p, 'tcx> {
|
impl<'p, 'tcx> Usefulness<'p, 'tcx> {
|
||||||
fn new_useful(preference: ArmType) -> Self {
|
fn new_useful(preference: ArmType) -> Self {
|
||||||
match preference {
|
match preference {
|
||||||
|
// A single (empty) witness of reachability.
|
||||||
FakeExtraWildcard => WithWitnesses(vec![Witness(vec![])]),
|
FakeExtraWildcard => WithWitnesses(vec![Witness(vec![])]),
|
||||||
RealArm => NoWitnesses(SubPatSet::full()),
|
RealArm => NoWitnesses { useful: true },
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn new_not_useful(preference: ArmType) -> Self {
|
fn new_not_useful(preference: ArmType) -> Self {
|
||||||
match preference {
|
match preference {
|
||||||
FakeExtraWildcard => WithWitnesses(vec![]),
|
FakeExtraWildcard => WithWitnesses(vec![]),
|
||||||
RealArm => NoWitnesses(SubPatSet::empty()),
|
RealArm => NoWitnesses { useful: false },
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn is_useful(&self) -> bool {
|
fn is_useful(&self) -> bool {
|
||||||
match self {
|
match self {
|
||||||
Usefulness::NoWitnesses(set) => !set.is_empty(),
|
Usefulness::NoWitnesses { useful } => *useful,
|
||||||
Usefulness::WithWitnesses(witnesses) => !witnesses.is_empty(),
|
Usefulness::WithWitnesses(witnesses) => !witnesses.is_empty(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -909,33 +555,10 @@ impl<'p, 'tcx> Usefulness<'p, 'tcx> {
|
||||||
(WithWitnesses(_), WithWitnesses(o)) if o.is_empty() => {}
|
(WithWitnesses(_), WithWitnesses(o)) if o.is_empty() => {}
|
||||||
(WithWitnesses(s), WithWitnesses(o)) if s.is_empty() => *self = WithWitnesses(o),
|
(WithWitnesses(s), WithWitnesses(o)) if s.is_empty() => *self = WithWitnesses(o),
|
||||||
(WithWitnesses(s), WithWitnesses(o)) => s.extend(o),
|
(WithWitnesses(s), WithWitnesses(o)) => s.extend(o),
|
||||||
(NoWitnesses(s), NoWitnesses(o)) => s.union(o),
|
(NoWitnesses { useful: s_useful }, NoWitnesses { useful: o_useful }) => {
|
||||||
_ => unreachable!(),
|
*s_useful = *s_useful || o_useful
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// When trying several branches and each returns a `Usefulness`, we need to combine the
|
|
||||||
/// results together.
|
|
||||||
fn merge(pref: ArmType, usefulnesses: impl Iterator<Item = Self>) -> Self {
|
|
||||||
let mut ret = Self::new_not_useful(pref);
|
|
||||||
for u in usefulnesses {
|
|
||||||
ret.extend(u);
|
|
||||||
if let NoWitnesses(subpats) = &ret {
|
|
||||||
if subpats.is_full() {
|
|
||||||
// Once we reach the full set, more unions won't change the result.
|
|
||||||
return ret;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
_ => unreachable!(),
|
||||||
ret
|
|
||||||
}
|
|
||||||
|
|
||||||
/// After calculating the usefulness for a branch of an or-pattern, call this to make this
|
|
||||||
/// usefulness mergeable with those from the other branches.
|
|
||||||
fn unsplit_or_pat(self, alt_id: usize, alt_count: usize, pat: &'p Pat<'tcx>) -> Self {
|
|
||||||
match self {
|
|
||||||
NoWitnesses(subpats) => NoWitnesses(subpats.unsplit_or_pat(alt_id, alt_count, pat)),
|
|
||||||
WithWitnesses(_) => bug!(),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -947,10 +570,10 @@ impl<'p, 'tcx> Usefulness<'p, 'tcx> {
|
||||||
pcx: PatCtxt<'_, 'p, 'tcx>,
|
pcx: PatCtxt<'_, 'p, 'tcx>,
|
||||||
matrix: &Matrix<'p, 'tcx>, // used to compute missing ctors
|
matrix: &Matrix<'p, 'tcx>, // used to compute missing ctors
|
||||||
ctor: &Constructor<'tcx>,
|
ctor: &Constructor<'tcx>,
|
||||||
ctor_wild_subpatterns: &Fields<'p, 'tcx>,
|
|
||||||
) -> Self {
|
) -> Self {
|
||||||
match self {
|
match self {
|
||||||
WithWitnesses(witnesses) if witnesses.is_empty() => WithWitnesses(witnesses),
|
NoWitnesses { .. } => self,
|
||||||
|
WithWitnesses(ref witnesses) if witnesses.is_empty() => self,
|
||||||
WithWitnesses(witnesses) => {
|
WithWitnesses(witnesses) => {
|
||||||
let new_witnesses = if let Constructor::Missing { .. } = ctor {
|
let new_witnesses = if let Constructor::Missing { .. } = ctor {
|
||||||
// We got the special `Missing` constructor, so each of the missing constructors
|
// We got the special `Missing` constructor, so each of the missing constructors
|
||||||
|
@ -958,22 +581,18 @@ impl<'p, 'tcx> Usefulness<'p, 'tcx> {
|
||||||
let new_patterns = if pcx.is_non_exhaustive {
|
let new_patterns = if pcx.is_non_exhaustive {
|
||||||
// Here we don't want the user to try to list all variants, we want them to add
|
// Here we don't want the user to try to list all variants, we want them to add
|
||||||
// a wildcard, so we only suggest that.
|
// a wildcard, so we only suggest that.
|
||||||
vec![
|
vec![DeconstructedPat::wildcard(pcx.ty)]
|
||||||
Fields::wildcards(pcx, &Constructor::NonExhaustive)
|
|
||||||
.apply(pcx, &Constructor::NonExhaustive),
|
|
||||||
]
|
|
||||||
} else {
|
} else {
|
||||||
let mut split_wildcard = SplitWildcard::new(pcx);
|
let mut split_wildcard = SplitWildcard::new(pcx);
|
||||||
split_wildcard.split(pcx, matrix.head_ctors(pcx.cx));
|
split_wildcard.split(pcx, matrix.heads().map(DeconstructedPat::ctor));
|
||||||
// Construct for each missing constructor a "wild" version of this
|
// Construct for each missing constructor a "wild" version of this
|
||||||
// constructor, that matches everything that can be built with
|
// constructor, that matches everything that can be built with
|
||||||
// it. For example, if `ctor` is a `Constructor::Variant` for
|
// it. For example, if `ctor` is a `Constructor::Variant` for
|
||||||
// `Option::Some`, we get the pattern `Some(_)`.
|
// `Option::Some`, we get the pattern `Some(_)`.
|
||||||
split_wildcard
|
split_wildcard
|
||||||
.iter_missing(pcx)
|
.iter_missing(pcx)
|
||||||
.map(|missing_ctor| {
|
.cloned()
|
||||||
Fields::wildcards(pcx, missing_ctor).apply(pcx, missing_ctor)
|
.map(|missing_ctor| DeconstructedPat::wild_from_ctor(pcx, missing_ctor))
|
||||||
})
|
|
||||||
.collect()
|
.collect()
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -981,21 +600,25 @@ impl<'p, 'tcx> Usefulness<'p, 'tcx> {
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.flat_map(|witness| {
|
.flat_map(|witness| {
|
||||||
new_patterns.iter().map(move |pat| {
|
new_patterns.iter().map(move |pat| {
|
||||||
let mut witness = witness.clone();
|
Witness(
|
||||||
witness.0.push(pat.clone());
|
witness
|
||||||
witness
|
.0
|
||||||
|
.iter()
|
||||||
|
.chain(once(pat))
|
||||||
|
.map(DeconstructedPat::clone_and_forget_reachability)
|
||||||
|
.collect(),
|
||||||
|
)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
.collect()
|
.collect()
|
||||||
} else {
|
} else {
|
||||||
witnesses
|
witnesses
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|witness| witness.apply_constructor(pcx, &ctor, ctor_wild_subpatterns))
|
.map(|witness| witness.apply_constructor(pcx, &ctor))
|
||||||
.collect()
|
.collect()
|
||||||
};
|
};
|
||||||
WithWitnesses(new_witnesses)
|
WithWitnesses(new_witnesses)
|
||||||
}
|
}
|
||||||
NoWitnesses(subpats) => NoWitnesses(subpats.unspecialize(ctor_wild_subpatterns.len())),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1039,12 +662,12 @@ enum ArmType {
|
||||||
/// `Witness(vec![Pair(Some(_), true)])`
|
/// `Witness(vec![Pair(Some(_), true)])`
|
||||||
///
|
///
|
||||||
/// The final `Pair(Some(_), true)` is then the resulting witness.
|
/// The final `Pair(Some(_), true)` is then the resulting witness.
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Debug)]
|
||||||
crate struct Witness<'tcx>(Vec<Pat<'tcx>>);
|
crate struct Witness<'p, 'tcx>(Vec<DeconstructedPat<'p, 'tcx>>);
|
||||||
|
|
||||||
impl<'tcx> Witness<'tcx> {
|
impl<'p, 'tcx> Witness<'p, 'tcx> {
|
||||||
/// Asserts that the witness contains a single pattern, and returns it.
|
/// Asserts that the witness contains a single pattern, and returns it.
|
||||||
fn single_pattern(self) -> Pat<'tcx> {
|
fn single_pattern(self) -> DeconstructedPat<'p, 'tcx> {
|
||||||
assert_eq!(self.0.len(), 1);
|
assert_eq!(self.0.len(), 1);
|
||||||
self.0.into_iter().next().unwrap()
|
self.0.into_iter().next().unwrap()
|
||||||
}
|
}
|
||||||
|
@ -1062,17 +685,13 @@ impl<'tcx> Witness<'tcx> {
|
||||||
///
|
///
|
||||||
/// left_ty: struct X { a: (bool, &'static str), b: usize}
|
/// left_ty: struct X { a: (bool, &'static str), b: usize}
|
||||||
/// pats: [(false, "foo"), 42] => X { a: (false, "foo"), b: 42 }
|
/// pats: [(false, "foo"), 42] => X { a: (false, "foo"), b: 42 }
|
||||||
fn apply_constructor<'p>(
|
fn apply_constructor(mut self, pcx: PatCtxt<'_, 'p, 'tcx>, ctor: &Constructor<'tcx>) -> Self {
|
||||||
mut self,
|
|
||||||
pcx: PatCtxt<'_, 'p, 'tcx>,
|
|
||||||
ctor: &Constructor<'tcx>,
|
|
||||||
ctor_wild_subpatterns: &Fields<'p, 'tcx>,
|
|
||||||
) -> Self {
|
|
||||||
let pat = {
|
let pat = {
|
||||||
let len = self.0.len();
|
let len = self.0.len();
|
||||||
let arity = ctor_wild_subpatterns.len();
|
let arity = ctor.arity(pcx);
|
||||||
let pats = self.0.drain((len - arity)..).rev();
|
let pats = self.0.drain((len - arity)..).rev();
|
||||||
ctor_wild_subpatterns.replace_fields(pcx.cx, pats).apply(pcx, ctor)
|
let fields = Fields::from_iter(pcx.cx, pats);
|
||||||
|
DeconstructedPat::new(ctor.clone(), fields, pcx.ty, DUMMY_SP)
|
||||||
};
|
};
|
||||||
|
|
||||||
self.0.push(pat);
|
self.0.push(pat);
|
||||||
|
@ -1090,9 +709,9 @@ fn lint_non_exhaustive_omitted_patterns<'p, 'tcx>(
|
||||||
scrut_ty: Ty<'tcx>,
|
scrut_ty: Ty<'tcx>,
|
||||||
sp: Span,
|
sp: Span,
|
||||||
hir_id: HirId,
|
hir_id: HirId,
|
||||||
witnesses: Vec<Pat<'tcx>>,
|
witnesses: Vec<DeconstructedPat<'p, 'tcx>>,
|
||||||
) {
|
) {
|
||||||
let joined_patterns = joined_uncovered_patterns(&witnesses);
|
let joined_patterns = joined_uncovered_patterns(cx, &witnesses);
|
||||||
cx.tcx.struct_span_lint_hir(NON_EXHAUSTIVE_OMITTED_PATTERNS, hir_id, sp, |build| {
|
cx.tcx.struct_span_lint_hir(NON_EXHAUSTIVE_OMITTED_PATTERNS, hir_id, sp, |build| {
|
||||||
let mut lint = build.build("some variants are not matched explicitly");
|
let mut lint = build.build("some variants are not matched explicitly");
|
||||||
lint.span_label(sp, pattern_not_covered_label(&witnesses, &joined_patterns));
|
lint.span_label(sp, pattern_not_covered_label(&witnesses, &joined_patterns));
|
||||||
|
@ -1163,56 +782,52 @@ fn is_useful<'p, 'tcx>(
|
||||||
assert!(rows.iter().all(|r| r.len() == v.len()));
|
assert!(rows.iter().all(|r| r.len() == v.len()));
|
||||||
|
|
||||||
// FIXME(Nadrieril): Hack to work around type normalization issues (see #72476).
|
// FIXME(Nadrieril): Hack to work around type normalization issues (see #72476).
|
||||||
let ty = matrix.heads().next().map_or(v.head().ty, |r| r.ty);
|
let ty = matrix.heads().next().map_or(v.head().ty(), |r| r.ty());
|
||||||
let is_non_exhaustive = cx.is_foreign_non_exhaustive_enum(ty);
|
let is_non_exhaustive = cx.is_foreign_non_exhaustive_enum(ty);
|
||||||
let pcx = PatCtxt { cx, ty, span: v.head().span, is_top_level, is_non_exhaustive };
|
let pcx = PatCtxt { cx, ty, span: v.head().span(), is_top_level, is_non_exhaustive };
|
||||||
|
|
||||||
// If the first pattern is an or-pattern, expand it.
|
// If the first pattern is an or-pattern, expand it.
|
||||||
let ret = if is_or_pat(v.head()) {
|
let mut ret = Usefulness::new_not_useful(witness_preference);
|
||||||
|
if v.head().is_or_pat() {
|
||||||
debug!("expanding or-pattern");
|
debug!("expanding or-pattern");
|
||||||
let v_head = v.head();
|
|
||||||
let vs: Vec<_> = v.expand_or_pat().collect();
|
|
||||||
let alt_count = vs.len();
|
|
||||||
// We try each or-pattern branch in turn.
|
// We try each or-pattern branch in turn.
|
||||||
let mut matrix = matrix.clone();
|
let mut matrix = matrix.clone();
|
||||||
let usefulnesses = vs.into_iter().enumerate().map(|(i, v)| {
|
for v in v.expand_or_pat() {
|
||||||
let usefulness =
|
let usefulness =
|
||||||
is_useful(cx, &matrix, &v, witness_preference, hir_id, is_under_guard, false);
|
is_useful(cx, &matrix, &v, witness_preference, hir_id, is_under_guard, false);
|
||||||
|
ret.extend(usefulness);
|
||||||
// If pattern has a guard don't add it to the matrix.
|
// If pattern has a guard don't add it to the matrix.
|
||||||
if !is_under_guard {
|
if !is_under_guard {
|
||||||
// We push the already-seen patterns into the matrix in order to detect redundant
|
// We push the already-seen patterns into the matrix in order to detect redundant
|
||||||
// branches like `Some(_) | Some(0)`.
|
// branches like `Some(_) | Some(0)`.
|
||||||
matrix.push(v);
|
matrix.push(v);
|
||||||
}
|
}
|
||||||
usefulness.unsplit_or_pat(i, alt_count, v_head)
|
}
|
||||||
});
|
|
||||||
Usefulness::merge(witness_preference, usefulnesses)
|
|
||||||
} else {
|
} else {
|
||||||
let v_ctor = v.head_ctor(cx);
|
let v_ctor = v.head().ctor();
|
||||||
if let Constructor::IntRange(ctor_range) = &v_ctor {
|
if let Constructor::IntRange(ctor_range) = &v_ctor {
|
||||||
// Lint on likely incorrect range patterns (#63987)
|
// Lint on likely incorrect range patterns (#63987)
|
||||||
ctor_range.lint_overlapping_range_endpoints(
|
ctor_range.lint_overlapping_range_endpoints(
|
||||||
pcx,
|
pcx,
|
||||||
matrix.head_ctors_and_spans(cx),
|
matrix.heads(),
|
||||||
matrix.column_count().unwrap_or(0),
|
matrix.column_count().unwrap_or(0),
|
||||||
hir_id,
|
hir_id,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
// We split the head constructor of `v`.
|
// We split the head constructor of `v`.
|
||||||
let split_ctors = v_ctor.split(pcx, matrix.head_ctors(cx));
|
let split_ctors = v_ctor.split(pcx, matrix.heads().map(DeconstructedPat::ctor));
|
||||||
let is_non_exhaustive_and_wild = is_non_exhaustive && v_ctor.is_wildcard();
|
let is_non_exhaustive_and_wild = is_non_exhaustive && v_ctor.is_wildcard();
|
||||||
// For each constructor, we compute whether there's a value that starts with it that would
|
// For each constructor, we compute whether there's a value that starts with it that would
|
||||||
// witness the usefulness of `v`.
|
// witness the usefulness of `v`.
|
||||||
let start_matrix = &matrix;
|
let start_matrix = &matrix;
|
||||||
let usefulnesses = split_ctors.into_iter().map(|ctor| {
|
for ctor in split_ctors {
|
||||||
debug!("specialize({:?})", ctor);
|
debug!("specialize({:?})", ctor);
|
||||||
// We cache the result of `Fields::wildcards` because it is used a lot.
|
// We cache the result of `Fields::wildcards` because it is used a lot.
|
||||||
let ctor_wild_subpatterns = Fields::wildcards(pcx, &ctor);
|
let spec_matrix = start_matrix.specialize_constructor(pcx, &ctor);
|
||||||
let spec_matrix =
|
let v = v.pop_head_constructor(cx, &ctor);
|
||||||
start_matrix.specialize_constructor(pcx, &ctor, &ctor_wild_subpatterns);
|
|
||||||
let v = v.pop_head_constructor(&ctor_wild_subpatterns);
|
|
||||||
let usefulness =
|
let usefulness =
|
||||||
is_useful(cx, &spec_matrix, &v, witness_preference, hir_id, is_under_guard, false);
|
is_useful(cx, &spec_matrix, &v, witness_preference, hir_id, is_under_guard, false);
|
||||||
|
let usefulness = usefulness.apply_constructor(pcx, start_matrix, &ctor);
|
||||||
|
|
||||||
// When all the conditions are met we have a match with a `non_exhaustive` enum
|
// When all the conditions are met we have a match with a `non_exhaustive` enum
|
||||||
// that has the potential to trigger the `non_exhaustive_omitted_patterns` lint.
|
// that has the potential to trigger the `non_exhaustive_omitted_patterns` lint.
|
||||||
|
@ -1229,29 +844,31 @@ fn is_useful<'p, 'tcx>(
|
||||||
{
|
{
|
||||||
let patterns = {
|
let patterns = {
|
||||||
let mut split_wildcard = SplitWildcard::new(pcx);
|
let mut split_wildcard = SplitWildcard::new(pcx);
|
||||||
split_wildcard.split(pcx, matrix.head_ctors(pcx.cx));
|
split_wildcard.split(pcx, matrix.heads().map(DeconstructedPat::ctor));
|
||||||
// Construct for each missing constructor a "wild" version of this
|
// Construct for each missing constructor a "wild" version of this
|
||||||
// constructor, that matches everything that can be built with
|
// constructor, that matches everything that can be built with
|
||||||
// it. For example, if `ctor` is a `Constructor::Variant` for
|
// it. For example, if `ctor` is a `Constructor::Variant` for
|
||||||
// `Option::Some`, we get the pattern `Some(_)`.
|
// `Option::Some`, we get the pattern `Some(_)`.
|
||||||
split_wildcard
|
split_wildcard
|
||||||
.iter_missing(pcx)
|
.iter_missing(pcx)
|
||||||
// Filter out the `Constructor::NonExhaustive` variant it's meaningless
|
// Filter out the `NonExhaustive` because we want to list only real
|
||||||
// to our lint
|
// variants.
|
||||||
.filter(|c| !c.is_non_exhaustive())
|
.filter(|c| !c.is_non_exhaustive())
|
||||||
.map(|missing_ctor| {
|
.cloned()
|
||||||
Fields::wildcards(pcx, missing_ctor).apply(pcx, missing_ctor)
|
.map(|missing_ctor| DeconstructedPat::wild_from_ctor(pcx, missing_ctor))
|
||||||
})
|
|
||||||
.collect::<Vec<_>>()
|
.collect::<Vec<_>>()
|
||||||
};
|
};
|
||||||
|
|
||||||
lint_non_exhaustive_omitted_patterns(pcx.cx, pcx.ty, pcx.span, hir_id, patterns);
|
lint_non_exhaustive_omitted_patterns(pcx.cx, pcx.ty, pcx.span, hir_id, patterns);
|
||||||
}
|
}
|
||||||
|
|
||||||
usefulness.apply_constructor(pcx, start_matrix, &ctor, &ctor_wild_subpatterns)
|
ret.extend(usefulness);
|
||||||
});
|
}
|
||||||
Usefulness::merge(witness_preference, usefulnesses)
|
}
|
||||||
};
|
|
||||||
|
if ret.is_useful() {
|
||||||
|
v.head().set_reachable();
|
||||||
|
}
|
||||||
|
|
||||||
debug!(?ret);
|
debug!(?ret);
|
||||||
ret
|
ret
|
||||||
|
@ -1261,7 +878,7 @@ fn is_useful<'p, 'tcx>(
|
||||||
#[derive(Clone, Copy)]
|
#[derive(Clone, Copy)]
|
||||||
crate struct MatchArm<'p, 'tcx> {
|
crate struct MatchArm<'p, 'tcx> {
|
||||||
/// The pattern must have been lowered through `check_match::MatchVisitor::lower_pattern`.
|
/// The pattern must have been lowered through `check_match::MatchVisitor::lower_pattern`.
|
||||||
crate pat: &'p Pat<'tcx>,
|
crate pat: &'p DeconstructedPat<'p, 'tcx>,
|
||||||
crate hir_id: HirId,
|
crate hir_id: HirId,
|
||||||
crate has_guard: bool,
|
crate has_guard: bool,
|
||||||
}
|
}
|
||||||
|
@ -1283,7 +900,7 @@ crate struct UsefulnessReport<'p, 'tcx> {
|
||||||
crate arm_usefulness: Vec<(MatchArm<'p, 'tcx>, Reachability)>,
|
crate arm_usefulness: Vec<(MatchArm<'p, 'tcx>, Reachability)>,
|
||||||
/// If the match is exhaustive, this is empty. If not, this contains witnesses for the lack of
|
/// If the match is exhaustive, this is empty. If not, this contains witnesses for the lack of
|
||||||
/// exhaustiveness.
|
/// exhaustiveness.
|
||||||
crate non_exhaustiveness_witnesses: Vec<Pat<'tcx>>,
|
crate non_exhaustiveness_witnesses: Vec<DeconstructedPat<'p, 'tcx>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The entrypoint for the usefulness algorithm. Computes whether a match is exhaustive and which
|
/// The entrypoint for the usefulness algorithm. Computes whether a match is exhaustive and which
|
||||||
|
@ -1303,27 +920,25 @@ crate fn compute_match_usefulness<'p, 'tcx>(
|
||||||
.copied()
|
.copied()
|
||||||
.map(|arm| {
|
.map(|arm| {
|
||||||
let v = PatStack::from_pattern(arm.pat);
|
let v = PatStack::from_pattern(arm.pat);
|
||||||
let usefulness = is_useful(cx, &matrix, &v, RealArm, arm.hir_id, arm.has_guard, true);
|
is_useful(cx, &matrix, &v, RealArm, arm.hir_id, arm.has_guard, true);
|
||||||
if !arm.has_guard {
|
if !arm.has_guard {
|
||||||
matrix.push(v);
|
matrix.push(v);
|
||||||
}
|
}
|
||||||
let reachability = match usefulness {
|
let reachability = if arm.pat.is_reachable() {
|
||||||
NoWitnesses(subpats) if subpats.is_empty() => Reachability::Unreachable,
|
Reachability::Reachable(arm.pat.unreachable_spans())
|
||||||
NoWitnesses(subpats) => {
|
} else {
|
||||||
Reachability::Reachable(subpats.list_unreachable_spans().unwrap())
|
Reachability::Unreachable
|
||||||
}
|
|
||||||
WithWitnesses(..) => bug!(),
|
|
||||||
};
|
};
|
||||||
(arm, reachability)
|
(arm, reachability)
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
let wild_pattern = cx.pattern_arena.alloc(Pat::wildcard_from_ty(scrut_ty));
|
let wild_pattern = cx.pattern_arena.alloc(DeconstructedPat::wildcard(scrut_ty));
|
||||||
let v = PatStack::from_pattern(wild_pattern);
|
let v = PatStack::from_pattern(wild_pattern);
|
||||||
let usefulness = is_useful(cx, &matrix, &v, FakeExtraWildcard, scrut_hir_id, false, true);
|
let usefulness = is_useful(cx, &matrix, &v, FakeExtraWildcard, scrut_hir_id, false, true);
|
||||||
let non_exhaustiveness_witnesses = match usefulness {
|
let non_exhaustiveness_witnesses = match usefulness {
|
||||||
WithWitnesses(pats) => pats.into_iter().map(|w| w.single_pattern()).collect(),
|
WithWitnesses(pats) => pats.into_iter().map(|w| w.single_pattern()).collect(),
|
||||||
NoWitnesses(_) => bug!(),
|
NoWitnesses { .. } => bug!(),
|
||||||
};
|
};
|
||||||
UsefulnessReport { arm_usefulness, non_exhaustiveness_witnesses }
|
UsefulnessReport { arm_usefulness, non_exhaustiveness_witnesses }
|
||||||
}
|
}
|
||||||
|
|
|
@ -7,8 +7,11 @@ LL | FOO => {},
|
||||||
error: unreachable pattern
|
error: unreachable pattern
|
||||||
--> $DIR/issue-78057.rs:14:9
|
--> $DIR/issue-78057.rs:14:9
|
||||||
|
|
|
|
||||||
|
LL | FOO => {},
|
||||||
|
| --- matches any value
|
||||||
|
LL |
|
||||||
LL | _ => {}
|
LL | _ => {}
|
||||||
| ^
|
| ^ unreachable pattern
|
||||||
|
|
|
|
||||||
note: the lint level is defined here
|
note: the lint level is defined here
|
||||||
--> $DIR/issue-78057.rs:1:9
|
--> $DIR/issue-78057.rs:1:9
|
||||||
|
|
30
src/test/ui/pattern/usefulness/const-private-fields.rs
Normal file
30
src/test/ui/pattern/usefulness/const-private-fields.rs
Normal file
|
@ -0,0 +1,30 @@
|
||||||
|
// check-pass
|
||||||
|
//
|
||||||
|
// Check that we don't ignore private fields in usefulness checking
|
||||||
|
#![deny(unreachable_patterns)]
|
||||||
|
|
||||||
|
mod inner {
|
||||||
|
#[derive(PartialEq, Eq)]
|
||||||
|
pub struct PrivateField {
|
||||||
|
pub x: bool,
|
||||||
|
y: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub const FOO: PrivateField = PrivateField { x: true, y: true };
|
||||||
|
pub const BAR: PrivateField = PrivateField { x: true, y: false };
|
||||||
|
}
|
||||||
|
use inner::*;
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
match FOO {
|
||||||
|
FOO => {}
|
||||||
|
BAR => {}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
|
||||||
|
match FOO {
|
||||||
|
FOO => {}
|
||||||
|
PrivateField { x: true, .. } => {}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
|
@ -7,8 +7,11 @@ LL | FOO => {}
|
||||||
error: unreachable pattern
|
error: unreachable pattern
|
||||||
--> $DIR/consts-opaque.rs:32:9
|
--> $DIR/consts-opaque.rs:32:9
|
||||||
|
|
|
|
||||||
|
LL | FOO => {}
|
||||||
|
| --- matches any value
|
||||||
|
LL |
|
||||||
LL | _ => {} // should not be emitting unreachable warning
|
LL | _ => {} // should not be emitting unreachable warning
|
||||||
| ^
|
| ^ unreachable pattern
|
||||||
|
|
|
|
||||||
note: the lint level is defined here
|
note: the lint level is defined here
|
||||||
--> $DIR/consts-opaque.rs:6:9
|
--> $DIR/consts-opaque.rs:6:9
|
||||||
|
@ -25,8 +28,11 @@ LL | FOO_REF => {}
|
||||||
error: unreachable pattern
|
error: unreachable pattern
|
||||||
--> $DIR/consts-opaque.rs:39:9
|
--> $DIR/consts-opaque.rs:39:9
|
||||||
|
|
|
|
||||||
|
LL | FOO_REF => {}
|
||||||
|
| ------- matches any value
|
||||||
|
LL |
|
||||||
LL | Foo(_) => {} // should not be emitting unreachable warning
|
LL | Foo(_) => {} // should not be emitting unreachable warning
|
||||||
| ^^^^^^
|
| ^^^^^^ unreachable pattern
|
||||||
|
|
||||||
warning: to use a constant of type `Foo` in a pattern, `Foo` must be annotated with `#[derive(PartialEq, Eq)]`
|
warning: to use a constant of type `Foo` in a pattern, `Foo` must be annotated with `#[derive(PartialEq, Eq)]`
|
||||||
--> $DIR/consts-opaque.rs:45:9
|
--> $DIR/consts-opaque.rs:45:9
|
||||||
|
@ -70,15 +76,18 @@ LL | BAR => {}
|
||||||
error: unreachable pattern
|
error: unreachable pattern
|
||||||
--> $DIR/consts-opaque.rs:63:9
|
--> $DIR/consts-opaque.rs:63:9
|
||||||
|
|
|
|
||||||
|
LL | BAR => {}
|
||||||
|
| --- matches any value
|
||||||
|
LL |
|
||||||
LL | Bar => {} // should not be emitting unreachable warning
|
LL | Bar => {} // should not be emitting unreachable warning
|
||||||
| ^^^
|
| ^^^ unreachable pattern
|
||||||
|
|
||||||
error: unreachable pattern
|
error: unreachable pattern
|
||||||
--> $DIR/consts-opaque.rs:65:9
|
--> $DIR/consts-opaque.rs:65:9
|
||||||
|
|
|
|
||||||
LL | Bar => {} // should not be emitting unreachable warning
|
LL | BAR => {}
|
||||||
| --- matches any value
|
| --- matches any value
|
||||||
LL |
|
...
|
||||||
LL | _ => {}
|
LL | _ => {}
|
||||||
| ^ unreachable pattern
|
| ^ unreachable pattern
|
||||||
|
|
||||||
|
@ -97,14 +106,20 @@ LL | BAR => {} // should not be emitting unreachable warning
|
||||||
error: unreachable pattern
|
error: unreachable pattern
|
||||||
--> $DIR/consts-opaque.rs:72:9
|
--> $DIR/consts-opaque.rs:72:9
|
||||||
|
|
|
|
||||||
|
LL | BAR => {}
|
||||||
|
| --- matches any value
|
||||||
|
LL |
|
||||||
LL | BAR => {} // should not be emitting unreachable warning
|
LL | BAR => {} // should not be emitting unreachable warning
|
||||||
| ^^^
|
| ^^^ unreachable pattern
|
||||||
|
|
||||||
error: unreachable pattern
|
error: unreachable pattern
|
||||||
--> $DIR/consts-opaque.rs:75:9
|
--> $DIR/consts-opaque.rs:75:9
|
||||||
|
|
|
|
||||||
|
LL | BAR => {}
|
||||||
|
| --- matches any value
|
||||||
|
...
|
||||||
LL | _ => {} // should not be emitting unreachable warning
|
LL | _ => {} // should not be emitting unreachable warning
|
||||||
| ^
|
| ^ unreachable pattern
|
||||||
|
|
||||||
error: to use a constant of type `Baz` in a pattern, `Baz` must be annotated with `#[derive(PartialEq, Eq)]`
|
error: to use a constant of type `Baz` in a pattern, `Baz` must be annotated with `#[derive(PartialEq, Eq)]`
|
||||||
--> $DIR/consts-opaque.rs:80:9
|
--> $DIR/consts-opaque.rs:80:9
|
||||||
|
@ -115,14 +130,20 @@ LL | BAZ => {}
|
||||||
error: unreachable pattern
|
error: unreachable pattern
|
||||||
--> $DIR/consts-opaque.rs:82:9
|
--> $DIR/consts-opaque.rs:82:9
|
||||||
|
|
|
|
||||||
|
LL | BAZ => {}
|
||||||
|
| --- matches any value
|
||||||
|
LL |
|
||||||
LL | Baz::Baz1 => {} // should not be emitting unreachable warning
|
LL | Baz::Baz1 => {} // should not be emitting unreachable warning
|
||||||
| ^^^^^^^^^
|
| ^^^^^^^^^ unreachable pattern
|
||||||
|
|
||||||
error: unreachable pattern
|
error: unreachable pattern
|
||||||
--> $DIR/consts-opaque.rs:84:9
|
--> $DIR/consts-opaque.rs:84:9
|
||||||
|
|
|
|
||||||
|
LL | BAZ => {}
|
||||||
|
| --- matches any value
|
||||||
|
...
|
||||||
LL | _ => {}
|
LL | _ => {}
|
||||||
| ^
|
| ^ unreachable pattern
|
||||||
|
|
||||||
error: to use a constant of type `Baz` in a pattern, `Baz` must be annotated with `#[derive(PartialEq, Eq)]`
|
error: to use a constant of type `Baz` in a pattern, `Baz` must be annotated with `#[derive(PartialEq, Eq)]`
|
||||||
--> $DIR/consts-opaque.rs:90:9
|
--> $DIR/consts-opaque.rs:90:9
|
||||||
|
@ -133,8 +154,11 @@ LL | BAZ => {}
|
||||||
error: unreachable pattern
|
error: unreachable pattern
|
||||||
--> $DIR/consts-opaque.rs:92:9
|
--> $DIR/consts-opaque.rs:92:9
|
||||||
|
|
|
|
||||||
|
LL | BAZ => {}
|
||||||
|
| --- matches any value
|
||||||
|
LL |
|
||||||
LL | _ => {}
|
LL | _ => {}
|
||||||
| ^
|
| ^ unreachable pattern
|
||||||
|
|
||||||
error: to use a constant of type `Baz` in a pattern, `Baz` must be annotated with `#[derive(PartialEq, Eq)]`
|
error: to use a constant of type `Baz` in a pattern, `Baz` must be annotated with `#[derive(PartialEq, Eq)]`
|
||||||
--> $DIR/consts-opaque.rs:97:9
|
--> $DIR/consts-opaque.rs:97:9
|
||||||
|
@ -145,20 +169,28 @@ LL | BAZ => {}
|
||||||
error: unreachable pattern
|
error: unreachable pattern
|
||||||
--> $DIR/consts-opaque.rs:99:9
|
--> $DIR/consts-opaque.rs:99:9
|
||||||
|
|
|
|
||||||
|
LL | BAZ => {}
|
||||||
|
| --- matches any value
|
||||||
|
LL |
|
||||||
LL | Baz::Baz2 => {} // should not be emitting unreachable warning
|
LL | Baz::Baz2 => {} // should not be emitting unreachable warning
|
||||||
| ^^^^^^^^^
|
| ^^^^^^^^^ unreachable pattern
|
||||||
|
|
||||||
error: unreachable pattern
|
error: unreachable pattern
|
||||||
--> $DIR/consts-opaque.rs:101:9
|
--> $DIR/consts-opaque.rs:101:9
|
||||||
|
|
|
|
||||||
|
LL | BAZ => {}
|
||||||
|
| --- matches any value
|
||||||
|
...
|
||||||
LL | _ => {} // should not be emitting unreachable warning
|
LL | _ => {} // should not be emitting unreachable warning
|
||||||
| ^
|
| ^ unreachable pattern
|
||||||
|
|
||||||
error: unreachable pattern
|
error: unreachable pattern
|
||||||
--> $DIR/consts-opaque.rs:127:9
|
--> $DIR/consts-opaque.rs:127:9
|
||||||
|
|
|
|
||||||
|
LL | Wrap(_) => {}
|
||||||
|
| ------- matches any value
|
||||||
LL | WRAPQUUX => {} // detected unreachable because we do inspect the `Wrap` layer
|
LL | WRAPQUUX => {} // detected unreachable because we do inspect the `Wrap` layer
|
||||||
| ^^^^^^^^
|
| ^^^^^^^^ unreachable pattern
|
||||||
|
|
||||||
error: unreachable pattern
|
error: unreachable pattern
|
||||||
--> $DIR/consts-opaque.rs:141:9
|
--> $DIR/consts-opaque.rs:141:9
|
||||||
|
|
|
@ -133,8 +133,10 @@ LL | 5..15 => {},
|
||||||
error: unreachable pattern
|
error: unreachable pattern
|
||||||
--> $DIR/reachability.rs:83:9
|
--> $DIR/reachability.rs:83:9
|
||||||
|
|
|
|
||||||
|
LL | _ => {},
|
||||||
|
| - matches any value
|
||||||
LL | '\u{D7FF}'..='\u{E000}' => {},
|
LL | '\u{D7FF}'..='\u{E000}' => {},
|
||||||
| ^^^^^^^^^^^^^^^^^^^^^^^
|
| ^^^^^^^^^^^^^^^^^^^^^^^ unreachable pattern
|
||||||
|
|
||||||
error: unreachable pattern
|
error: unreachable pattern
|
||||||
--> $DIR/reachability.rs:104:9
|
--> $DIR/reachability.rs:104:9
|
||||||
|
|
|
@ -1,8 +1,8 @@
|
||||||
error[E0004]: non-exhaustive patterns: `Box(_, _)` not covered
|
error[E0004]: non-exhaustive patterns: `box _` not covered
|
||||||
--> $DIR/issue-3601.rs:30:44
|
--> $DIR/issue-3601.rs:30:44
|
||||||
|
|
|
|
||||||
LL | box NodeKind::Element(ed) => match ed.kind {
|
LL | box NodeKind::Element(ed) => match ed.kind {
|
||||||
| ^^^^^^^ pattern `Box(_, _)` not covered
|
| ^^^^^^^ pattern `box _` not covered
|
||||||
|
|
|
|
||||||
= help: ensure that all possible cases are being handled, possibly by adding wildcards or more match arms
|
= help: ensure that all possible cases are being handled, possibly by adding wildcards or more match arms
|
||||||
= note: the matched value is of type `Box<ElementKind>`
|
= note: the matched value is of type `Box<ElementKind>`
|
||||||
|
|
|
@ -0,0 +1,6 @@
|
||||||
|
// This used to ICE in exhaustiveness checking. Explanation here:
|
||||||
|
// https://github.com/rust-lang/rust/issues/82772#issuecomment-905946768
|
||||||
|
fn main() {
|
||||||
|
let Box { 1: _, .. }: Box<()>; //~ ERROR field `1` of
|
||||||
|
let Box { .. }: Box<()>;
|
||||||
|
}
|
|
@ -0,0 +1,9 @@
|
||||||
|
error[E0451]: field `1` of struct `Box` is private
|
||||||
|
--> $DIR/issue-82772-match-box-as-struct.rs:4:15
|
||||||
|
|
|
||||||
|
LL | let Box { 1: _, .. }: Box<()>;
|
||||||
|
| ^^^^ private field
|
||||||
|
|
||||||
|
error: aborting due to previous error
|
||||||
|
|
||||||
|
For more information about this error, try `rustc --explain E0451`.
|
Loading…
Add table
Add a link
Reference in a new issue