Skip to content

Commit 74c3f5a

Browse files
committed
Auto merge of rust-lang#120324 - Nadrieril:remove-interior-mutability, r=compiler-errors
pattern_analysis: track usefulness without interior mutability Because of or-patterns, exhaustiveness needs to be able to lint if a sub-pattern is redundant, e.g. in `Some(_) | Some(true)`. So far the only sane solution I had found was interior mutability. This is a bit of an abstraction leak, and would become a footgun if we ever reused the same `DeconstructedPat`. This PR replaces interior mutability with an address-indexed hashmap, which is logically equivalent.
2 parents b381d3a + be29cd1 commit 74c3f5a

File tree

2 files changed

+86
-83
lines changed

2 files changed

+86
-83
lines changed

compiler/rustc_pattern_analysis/src/pat.rs

+25-53
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
//! As explained in [`crate::usefulness`], values and patterns are made from constructors applied to
22
//! fields. This file defines types that represent patterns in this way.
3-
use std::cell::Cell;
43
use std::fmt;
54

65
use smallvec::{smallvec, SmallVec};
@@ -10,12 +9,20 @@ use crate::TypeCx;
109

1110
use self::Constructor::*;
1211

12+
/// A globally unique id to distinguish patterns.
13+
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
14+
pub(crate) struct PatId(u32);
15+
impl PatId {
16+
fn new() -> Self {
17+
use std::sync::atomic::{AtomicU32, Ordering};
18+
static PAT_ID: AtomicU32 = AtomicU32::new(0);
19+
PatId(PAT_ID.fetch_add(1, Ordering::SeqCst))
20+
}
21+
}
22+
1323
/// Values and patterns can be represented as a constructor applied to some fields. This represents
14-
/// a pattern in this form.
15-
/// This also uses interior mutability to keep track of whether the pattern has been found reachable
16-
/// during analysis. For this reason they cannot be cloned.
17-
/// A `DeconstructedPat` will almost always come from user input; the only exception are some
18-
/// `Wildcard`s introduced during specialization.
24+
/// a pattern in this form. A `DeconstructedPat` will almost always come from user input; the only
25+
/// exception are some `Wildcard`s introduced during pattern lowering.
1926
///
2027
/// Note that the number of fields may not match the fields declared in the original struct/variant.
2128
/// This happens if a private or `non_exhaustive` field is uninhabited, because the code mustn't
@@ -28,19 +35,13 @@ pub struct DeconstructedPat<Cx: TypeCx> {
2835
/// Extra data to store in a pattern. `None` if the pattern is a wildcard that does not
2936
/// correspond to a user-supplied pattern.
3037
data: Option<Cx::PatData>,
31-
/// Whether removing this arm would change the behavior of the match expression.
32-
useful: Cell<bool>,
38+
/// Globally-unique id used to track usefulness at the level of subpatterns.
39+
pub(crate) uid: PatId,
3340
}
3441

3542
impl<Cx: TypeCx> DeconstructedPat<Cx> {
3643
pub fn wildcard(ty: Cx::Ty) -> Self {
37-
DeconstructedPat {
38-
ctor: Wildcard,
39-
fields: Vec::new(),
40-
ty,
41-
data: None,
42-
useful: Cell::new(false),
43-
}
44+
DeconstructedPat { ctor: Wildcard, fields: Vec::new(), ty, data: None, uid: PatId::new() }
4445
}
4546

4647
pub fn new(
@@ -49,7 +50,7 @@ impl<Cx: TypeCx> DeconstructedPat<Cx> {
4950
ty: Cx::Ty,
5051
data: Cx::PatData,
5152
) -> Self {
52-
DeconstructedPat { ctor, fields, ty, data: Some(data), useful: Cell::new(false) }
53+
DeconstructedPat { ctor, fields, ty, data: Some(data), uid: PatId::new() }
5354
}
5455

5556
pub(crate) fn is_or_pat(&self) -> bool {
@@ -107,39 +108,16 @@ impl<Cx: TypeCx> DeconstructedPat<Cx> {
107108
}
108109
}
109110

110-
/// We keep track for each pattern if it was ever useful during the analysis. This is used with
111-
/// `redundant_subpatterns` to report redundant subpatterns arising from or patterns.
112-
pub(crate) fn set_useful(&self) {
113-
self.useful.set(true)
114-
}
115-
pub(crate) fn is_useful(&self) -> bool {
116-
if self.useful.get() {
117-
true
118-
} else if self.is_or_pat() && self.iter_fields().any(|f| f.is_useful()) {
119-
// We always expand or patterns in the matrix, so we will never see the actual
120-
// or-pattern (the one with constructor `Or`) in the column. As such, it will not be
121-
// marked as useful itself, only its children will. We recover this information here.
122-
self.set_useful();
123-
true
124-
} else {
125-
false
111+
/// Walk top-down and call `it` in each place where a pattern occurs
112+
/// starting with the root pattern `walk` is called on. If `it` returns
113+
/// false then we will descend no further but siblings will be processed.
114+
pub fn walk<'a>(&'a self, it: &mut impl FnMut(&'a Self) -> bool) {
115+
if !it(self) {
116+
return;
126117
}
127-
}
128118

129-
/// Report the subpatterns that were not useful, if any.
130-
pub(crate) fn redundant_subpatterns(&self) -> Vec<&Self> {
131-
let mut subpats = Vec::new();
132-
self.collect_redundant_subpatterns(&mut subpats);
133-
subpats
134-
}
135-
fn collect_redundant_subpatterns<'a>(&'a self, subpats: &mut Vec<&'a Self>) {
136-
// We don't look at subpatterns if we already reported the whole pattern as redundant.
137-
if !self.is_useful() {
138-
subpats.push(self);
139-
} else {
140-
for p in self.iter_fields() {
141-
p.collect_redundant_subpatterns(subpats);
142-
}
119+
for p in self.iter_fields() {
120+
p.walk(it)
143121
}
144122
}
145123
}
@@ -284,12 +262,6 @@ impl<'p, Cx: TypeCx> PatOrWild<'p, Cx> {
284262
PatOrWild::Pat(pat) => pat.specialize(other_ctor, ctor_arity),
285263
}
286264
}
287-
288-
pub(crate) fn set_useful(&self) {
289-
if let PatOrWild::Pat(pat) = self {
290-
pat.set_useful()
291-
}
292-
}
293265
}
294266

295267
impl<'p, Cx: TypeCx> fmt::Debug for PatOrWild<'p, Cx> {

compiler/rustc_pattern_analysis/src/usefulness.rs

+61-30
Original file line numberDiff line numberDiff line change
@@ -466,13 +466,9 @@
466466
//! first pattern of a row in the matrix is an or-pattern, we expand it by duplicating the rest of
467467
//! the row as necessary. This is handled automatically in [`Matrix`].
468468
//!
469-
//! This makes usefulness tracking subtle, because we also want to compute whether an alternative
470-
//! of an or-pattern is redundant, e.g. in `Some(_) | Some(0)`. We track usefulness of each
471-
//! subpattern by interior mutability in [`DeconstructedPat`] with `set_useful`/`is_useful`.
472-
//!
473-
//! It's unfortunate that we have to use interior mutability, but believe me (Nadrieril), I have
474-
//! tried [other](https://github.com/rust-lang/rust/pull/80104)
475-
//! [solutions](https://github.com/rust-lang/rust/pull/80632) and nothing is remotely as simple.
469+
//! This makes usefulness tracking subtle, because we also want to compute whether an alternative of
470+
//! an or-pattern is redundant, e.g. in `Some(_) | Some(0)`. We therefore track usefulness of each
471+
//! subpattern of the match.
476472
//!
477473
//!
478474
//!
@@ -713,12 +709,13 @@
713709
//! I (Nadrieril) prefer to put new tests in `ui/pattern/usefulness` unless there's a specific
714710
//! reason not to, for example if they crucially depend on a particular feature like `or_patterns`.
715711
712+
use rustc_hash::FxHashSet;
716713
use rustc_index::bit_set::BitSet;
717714
use smallvec::{smallvec, SmallVec};
718715
use std::fmt;
719716

720717
use crate::constructor::{Constructor, ConstructorSet, IntRange};
721-
use crate::pat::{DeconstructedPat, PatOrWild, WitnessPat};
718+
use crate::pat::{DeconstructedPat, PatId, PatOrWild, WitnessPat};
722719
use crate::{Captures, MatchArm, TypeCx};
723720

724721
use self::ValidityConstraint::*;
@@ -731,16 +728,12 @@ pub fn ensure_sufficient_stack<R>(f: impl FnOnce() -> R) -> R {
731728
}
732729

733730
/// Context that provides information for usefulness checking.
734-
pub struct UsefulnessCtxt<'a, Cx: TypeCx> {
731+
struct UsefulnessCtxt<'a, Cx: TypeCx> {
735732
/// The context for type information.
736-
pub tycx: &'a Cx,
737-
}
738-
739-
impl<'a, Cx: TypeCx> Copy for UsefulnessCtxt<'a, Cx> {}
740-
impl<'a, Cx: TypeCx> Clone for UsefulnessCtxt<'a, Cx> {
741-
fn clone(&self) -> Self {
742-
Self { tycx: self.tycx }
743-
}
733+
tycx: &'a Cx,
734+
/// Collect the patterns found useful during usefulness checking. This is used to lint
735+
/// unreachable (sub)patterns.
736+
useful_subpatterns: FxHashSet<PatId>,
744737
}
745738

746739
/// Context that provides information local to a place under investigation.
@@ -1381,7 +1374,7 @@ impl<Cx: TypeCx> WitnessMatrix<Cx> {
13811374
/// We can however get false negatives because exhaustiveness does not explore all cases. See the
13821375
/// section on relevancy at the top of the file.
13831376
fn collect_overlapping_range_endpoints<'p, Cx: TypeCx>(
1384-
mcx: UsefulnessCtxt<'_, Cx>,
1377+
mcx: &mut UsefulnessCtxt<'_, Cx>,
13851378
overlap_range: IntRange,
13861379
matrix: &Matrix<'p, Cx>,
13871380
specialized_matrix: &Matrix<'p, Cx>,
@@ -1441,8 +1434,8 @@ fn collect_overlapping_range_endpoints<'p, Cx: TypeCx>(
14411434
/// The core of the algorithm.
14421435
///
14431436
/// This recursively computes witnesses of the non-exhaustiveness of `matrix` (if any). Also tracks
1444-
/// usefulness of each row in the matrix (in `row.useful`). We track usefulness of each
1445-
/// subpattern using interior mutability in `DeconstructedPat`.
1437+
/// usefulness of each row in the matrix (in `row.useful`). We track usefulness of each subpattern
1438+
/// in `mcx.useful_subpatterns`.
14461439
///
14471440
/// The input `Matrix` and the output `WitnessMatrix` together match the type exhaustively.
14481441
///
@@ -1454,7 +1447,7 @@ fn collect_overlapping_range_endpoints<'p, Cx: TypeCx>(
14541447
/// This is all explained at the top of the file.
14551448
#[instrument(level = "debug", skip(mcx), ret)]
14561449
fn compute_exhaustiveness_and_usefulness<'a, 'p, Cx: TypeCx>(
1457-
mcx: UsefulnessCtxt<'a, Cx>,
1450+
mcx: &mut UsefulnessCtxt<'a, Cx>,
14581451
matrix: &mut Matrix<'p, Cx>,
14591452
) -> Result<WitnessMatrix<Cx>, Cx::Error> {
14601453
debug_assert!(matrix.rows().all(|r| r.len() == matrix.column_count()));
@@ -1578,7 +1571,9 @@ fn compute_exhaustiveness_and_usefulness<'a, 'p, Cx: TypeCx>(
15781571
// Record usefulness in the patterns.
15791572
for row in matrix.rows() {
15801573
if row.useful {
1581-
row.head().set_useful();
1574+
if let PatOrWild::Pat(pat) = row.head() {
1575+
mcx.useful_subpatterns.insert(pat.uid);
1576+
}
15821577
}
15831578
}
15841579

@@ -1597,6 +1592,47 @@ pub enum Usefulness<'p, Cx: TypeCx> {
15971592
Redundant,
15981593
}
15991594

1595+
/// Report whether this pattern was found useful, and its subpatterns that were not useful if any.
1596+
fn collect_pattern_usefulness<'p, Cx: TypeCx>(
1597+
useful_subpatterns: &FxHashSet<PatId>,
1598+
pat: &'p DeconstructedPat<Cx>,
1599+
) -> Usefulness<'p, Cx> {
1600+
fn pat_is_useful<'p, Cx: TypeCx>(
1601+
useful_subpatterns: &FxHashSet<PatId>,
1602+
pat: &'p DeconstructedPat<Cx>,
1603+
) -> bool {
1604+
if useful_subpatterns.contains(&pat.uid) {
1605+
true
1606+
} else if pat.is_or_pat() && pat.iter_fields().any(|f| pat_is_useful(useful_subpatterns, f))
1607+
{
1608+
// We always expand or patterns in the matrix, so we will never see the actual
1609+
// or-pattern (the one with constructor `Or`) in the column. As such, it will not be
1610+
// marked as useful itself, only its children will. We recover this information here.
1611+
true
1612+
} else {
1613+
false
1614+
}
1615+
}
1616+
1617+
let mut redundant_subpats = Vec::new();
1618+
pat.walk(&mut |p| {
1619+
if pat_is_useful(useful_subpatterns, p) {
1620+
// The pattern is useful, so we recurse to find redundant subpatterns.
1621+
true
1622+
} else {
1623+
// The pattern is redundant.
1624+
redundant_subpats.push(p);
1625+
false // stop recursing
1626+
}
1627+
});
1628+
1629+
if pat_is_useful(useful_subpatterns, pat) {
1630+
Usefulness::Useful(redundant_subpats)
1631+
} else {
1632+
Usefulness::Redundant
1633+
}
1634+
}
1635+
16001636
/// The output of checking a match for exhaustiveness and arm usefulness.
16011637
pub struct UsefulnessReport<'p, Cx: TypeCx> {
16021638
/// For each arm of the input, whether that arm is useful after the arms above it.
@@ -1614,22 +1650,17 @@ pub fn compute_match_usefulness<'p, Cx: TypeCx>(
16141650
scrut_ty: Cx::Ty,
16151651
scrut_validity: ValidityConstraint,
16161652
) -> Result<UsefulnessReport<'p, Cx>, Cx::Error> {
1617-
let cx = UsefulnessCtxt { tycx };
1653+
let mut cx = UsefulnessCtxt { tycx, useful_subpatterns: FxHashSet::default() };
16181654
let mut matrix = Matrix::new(arms, scrut_ty, scrut_validity);
1619-
let non_exhaustiveness_witnesses = compute_exhaustiveness_and_usefulness(cx, &mut matrix)?;
1655+
let non_exhaustiveness_witnesses = compute_exhaustiveness_and_usefulness(&mut cx, &mut matrix)?;
16201656

16211657
let non_exhaustiveness_witnesses: Vec<_> = non_exhaustiveness_witnesses.single_column();
16221658
let arm_usefulness: Vec<_> = arms
16231659
.iter()
16241660
.copied()
16251661
.map(|arm| {
16261662
debug!(?arm);
1627-
// We warn when a pattern is not useful.
1628-
let usefulness = if arm.pat.is_useful() {
1629-
Usefulness::Useful(arm.pat.redundant_subpatterns())
1630-
} else {
1631-
Usefulness::Redundant
1632-
};
1663+
let usefulness = collect_pattern_usefulness(&cx.useful_subpatterns, arm.pat);
16331664
(arm, usefulness)
16341665
})
16351666
.collect();

0 commit comments

Comments
 (0)