Skip to content

Commit 3ad76f9

Browse files
committed
Disentangle the arena from MatchCheckCtxt
1 parent 081c3dc commit 3ad76f9

File tree

6 files changed

+140
-117
lines changed

6 files changed

+140
-117
lines changed

compiler/rustc_mir_build/src/thir/pattern/check_match.rs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use rustc_pattern_analysis::{analyze_match, MatchArm};
77

88
use crate::errors::*;
99

10-
use rustc_arena::TypedArena;
10+
use rustc_arena::{DroplessArena, TypedArena};
1111
use rustc_ast::Mutability;
1212
use rustc_data_structures::fx::FxIndexSet;
1313
use rustc_data_structures::stack::ensure_sufficient_stack;
@@ -31,13 +31,15 @@ pub(crate) fn check_match(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Result<(), Err
3131
let (thir, expr) = tcx.thir_body(def_id)?;
3232
let thir = thir.borrow();
3333
let pattern_arena = TypedArena::default();
34+
let dropless_arena = DroplessArena::default();
3435
let mut visitor = MatchVisitor {
3536
tcx,
3637
thir: &*thir,
3738
param_env: tcx.param_env(def_id),
3839
lint_level: tcx.local_def_id_to_hir_id(def_id),
3940
let_source: LetSource::None,
4041
pattern_arena: &pattern_arena,
42+
dropless_arena: &dropless_arena,
4143
error: Ok(()),
4244
};
4345
visitor.visit_expr(&thir[expr]);
@@ -82,6 +84,7 @@ struct MatchVisitor<'thir, 'p, 'tcx> {
8284
lint_level: HirId,
8385
let_source: LetSource,
8486
pattern_arena: &'p TypedArena<DeconstructedPat<'p, 'tcx>>,
87+
dropless_arena: &'p DroplessArena,
8588
/// Tracks if we encountered an error while checking this body. That the first function to
8689
/// report it stores it here. Some functions return `Result` to allow callers to short-circuit
8790
/// on error, but callers don't need to store it here again.
@@ -382,6 +385,7 @@ impl<'thir, 'p, 'tcx> MatchVisitor<'thir, 'p, 'tcx> {
382385
param_env: self.param_env,
383386
module: self.tcx.parent_module(self.lint_level).to_def_id(),
384387
pattern_arena: self.pattern_arena,
388+
dropless_arena: self.dropless_arena,
385389
match_lint_level: self.lint_level,
386390
whole_match_span,
387391
scrut_span,

compiler/rustc_pattern_analysis/src/cx.rs

Lines changed: 11 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
11
use std::fmt;
22
use std::iter::once;
33

4-
use rustc_arena::TypedArena;
4+
use rustc_arena::{DroplessArena, TypedArena};
55
use rustc_data_structures::captures::Captures;
66
use rustc_hir::def_id::DefId;
77
use rustc_hir::{HirId, RangeEnd};
88
use rustc_index::Idx;
99
use rustc_index::IndexVec;
1010
use rustc_middle::middle::stability::EvalResult;
11-
use rustc_middle::mir;
1211
use rustc_middle::mir::interpret::Scalar;
12+
use rustc_middle::mir::{self};
1313
use rustc_middle::thir::{FieldPat, Pat, PatKind, PatRange, PatRangeBoundary};
1414
use rustc_middle::ty::layout::IntegerExt;
1515
use rustc_middle::ty::{self, Ty, TyCtxt, VariantDef};
@@ -35,6 +35,7 @@ pub struct MatchCheckCtxt<'p, 'tcx> {
3535
pub module: DefId,
3636
pub param_env: ty::ParamEnv<'tcx>,
3737
pub pattern_arena: &'p TypedArena<DeconstructedPat<'p, 'tcx>>,
38+
pub dropless_arena: &'p DroplessArena,
3839
/// Lint level at the match.
3940
pub match_lint_level: HirId,
4041
/// The span of the whole match, if applicable.
@@ -67,14 +68,6 @@ impl<'p, 'tcx> MatchCheckCtxt<'p, 'tcx> {
6768
}
6869
}
6970

70-
pub(crate) fn alloc_wildcard_slice(
71-
&self,
72-
tys: impl IntoIterator<Item = Ty<'tcx>>,
73-
) -> &'p [DeconstructedPat<'p, 'tcx>] {
74-
self.pattern_arena
75-
.alloc_from_iter(tys.into_iter().map(|ty| DeconstructedPat::wildcard(ty, DUMMY_SP)))
76-
}
77-
7871
// In the cases of either a `#[non_exhaustive]` field list or a non-public field, we hide
7972
// uninhabited fields in order not to reveal the uninhabitedness of the whole variant.
8073
// This lists the fields we keep along with their types.
@@ -117,40 +110,36 @@ impl<'p, 'tcx> MatchCheckCtxt<'p, 'tcx> {
117110
}
118111
}
119112

120-
/// Creates a new list of wildcard fields for a given constructor. The result must have a length
121-
/// of `ctor.arity()`.
113+
/// Returns the types of the fields for a given constructor. The result must have a length of
114+
/// `ctor.arity()`.
122115
#[instrument(level = "trace", skip(self))]
123-
pub(crate) fn ctor_wildcard_fields(
124-
&self,
125-
ctor: &Constructor<'tcx>,
126-
ty: Ty<'tcx>,
127-
) -> &'p [DeconstructedPat<'p, 'tcx>] {
116+
pub(crate) fn ctor_sub_tys(&self, ctor: &Constructor<'tcx>, ty: Ty<'tcx>) -> &[Ty<'tcx>] {
128117
let cx = self;
129118
match ctor {
130119
Struct | Variant(_) | UnionField => match ty.kind() {
131-
ty::Tuple(fs) => cx.alloc_wildcard_slice(fs.iter()),
120+
ty::Tuple(fs) => cx.dropless_arena.alloc_from_iter(fs.iter()),
132121
ty::Adt(adt, args) => {
133122
if adt.is_box() {
134123
// The only legal patterns of type `Box` (outside `std`) are `_` and box
135124
// patterns. If we're here we can assume this is a box pattern.
136-
cx.alloc_wildcard_slice(once(args.type_at(0)))
125+
cx.dropless_arena.alloc_from_iter(once(args.type_at(0)))
137126
} else {
138127
let variant =
139128
&adt.variant(MatchCheckCtxt::variant_index_for_adt(&ctor, *adt));
140129
let tys = cx.list_variant_nonhidden_fields(ty, variant).map(|(_, ty)| ty);
141-
cx.alloc_wildcard_slice(tys)
130+
cx.dropless_arena.alloc_from_iter(tys)
142131
}
143132
}
144133
_ => bug!("Unexpected type for constructor `{ctor:?}`: {ty:?}"),
145134
},
146135
Ref => match ty.kind() {
147-
ty::Ref(_, rty, _) => cx.alloc_wildcard_slice(once(*rty)),
136+
ty::Ref(_, rty, _) => cx.dropless_arena.alloc_from_iter(once(*rty)),
148137
_ => bug!("Unexpected type for `Ref` constructor: {ty:?}"),
149138
},
150139
Slice(slice) => match *ty.kind() {
151140
ty::Slice(ty) | ty::Array(ty, _) => {
152141
let arity = slice.arity();
153-
cx.alloc_wildcard_slice((0..arity).map(|_| ty))
142+
cx.dropless_arena.alloc_from_iter((0..arity).map(|_| ty))
154143
}
155144
_ => bug!("bad slice pattern {:?} {:?}", ctor, ty),
156145
},

compiler/rustc_pattern_analysis/src/lib.rs

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -39,17 +39,19 @@ pub fn analyze_match<'p, 'tcx>(
3939
arms: &[MatchArm<'p, 'tcx>],
4040
scrut_ty: Ty<'tcx>,
4141
) -> UsefulnessReport<'p, 'tcx> {
42+
// Arena to store the extra wildcards we construct during analysis.
43+
let wildcard_arena = cx.pattern_arena;
4244
let pat_column = PatternColumn::new(arms);
4345

44-
let report = compute_match_usefulness(cx, arms, scrut_ty);
46+
let report = compute_match_usefulness(cx, arms, scrut_ty, wildcard_arena);
4547

4648
// Lint on ranges that overlap on their endpoints, which is likely a mistake.
47-
lint_overlapping_range_endpoints(cx, &pat_column);
49+
lint_overlapping_range_endpoints(cx, &pat_column, wildcard_arena);
4850

4951
// Run the non_exhaustive_omitted_patterns lint. Only run on refutable patterns to avoid hitting
5052
// `if let`s. Only run if the match is exhaustive otherwise the error is redundant.
5153
if cx.refutable && report.non_exhaustiveness_witnesses.is_empty() {
52-
lint_nonexhaustive_missing_variants(cx, arms, &pat_column, scrut_ty)
54+
lint_nonexhaustive_missing_variants(cx, arms, &pat_column, scrut_ty, wildcard_arena)
5355
}
5456

5557
report

compiler/rustc_pattern_analysis/src/lints.rs

Lines changed: 29 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
use rustc_arena::TypedArena;
12
use smallvec::SmallVec;
23

34
use rustc_data_structures::captures::Captures;
@@ -27,11 +28,11 @@ use crate::MatchArm;
2728
///
2829
/// This is not used in the main algorithm; only in lints.
2930
#[derive(Debug)]
30-
pub(crate) struct PatternColumn<'p, 'tcx> {
31-
patterns: Vec<&'p DeconstructedPat<'p, 'tcx>>,
31+
pub(crate) struct PatternColumn<'a, 'p, 'tcx> {
32+
patterns: Vec<&'a DeconstructedPat<'p, 'tcx>>,
3233
}
3334

34-
impl<'p, 'tcx> PatternColumn<'p, 'tcx> {
35+
impl<'a, 'p, 'tcx> PatternColumn<'a, 'p, 'tcx> {
3536
pub(crate) fn new(arms: &[MatchArm<'p, 'tcx>]) -> Self {
3637
let mut patterns = Vec::with_capacity(arms.len());
3738
for arm in arms {
@@ -71,7 +72,7 @@ impl<'p, 'tcx> PatternColumn<'p, 'tcx> {
7172
pcx.cx.ctors_for_ty(pcx.ty).split(pcx, column_ctors)
7273
}
7374

74-
fn iter<'a>(&'a self) -> impl Iterator<Item = &'p DeconstructedPat<'p, 'tcx>> + Captures<'a> {
75+
fn iter<'b>(&'b self) -> impl Iterator<Item = &'a DeconstructedPat<'p, 'tcx>> + Captures<'b> {
7576
self.patterns.iter().copied()
7677
}
7778

@@ -80,7 +81,14 @@ impl<'p, 'tcx> PatternColumn<'p, 'tcx> {
8081
/// This returns one column per field of the constructor. They usually all have the same length
8182
/// (the number of patterns in `self` that matched `ctor`), except that we expand or-patterns
8283
/// which may change the lengths.
83-
fn specialize(&self, pcx: &PatCtxt<'_, 'p, 'tcx>, ctor: &Constructor<'tcx>) -> Vec<Self> {
84+
fn specialize<'b>(
85+
&self,
86+
pcx: &'b PatCtxt<'_, 'p, 'tcx>,
87+
ctor: &Constructor<'tcx>,
88+
) -> Vec<PatternColumn<'b, 'p, 'tcx>>
89+
where
90+
'a: 'b,
91+
{
8492
let arity = ctor.arity(pcx);
8593
if arity == 0 {
8694
return Vec::new();
@@ -115,15 +123,16 @@ impl<'p, 'tcx> PatternColumn<'p, 'tcx> {
115123

116124
/// Traverse the patterns to collect any variants of a non_exhaustive enum that fail to be mentioned
117125
/// in a given column.
118-
#[instrument(level = "debug", skip(cx), ret)]
119-
fn collect_nonexhaustive_missing_variants<'p, 'tcx>(
126+
#[instrument(level = "debug", skip(cx, wildcard_arena), ret)]
127+
fn collect_nonexhaustive_missing_variants<'a, 'p, 'tcx>(
120128
cx: &MatchCheckCtxt<'p, 'tcx>,
121-
column: &PatternColumn<'p, 'tcx>,
129+
column: &PatternColumn<'a, 'p, 'tcx>,
130+
wildcard_arena: &TypedArena<DeconstructedPat<'p, 'tcx>>,
122131
) -> Vec<WitnessPat<'tcx>> {
123132
let Some(ty) = column.head_ty() else {
124133
return Vec::new();
125134
};
126-
let pcx = &PatCtxt::new_dummy(cx, ty);
135+
let pcx = &PatCtxt::new_dummy(cx, ty, wildcard_arena);
127136

128137
let set = column.analyze_ctors(pcx);
129138
if set.present.is_empty() {
@@ -150,7 +159,7 @@ fn collect_nonexhaustive_missing_variants<'p, 'tcx>(
150159
let wild_pat = WitnessPat::wild_from_ctor(pcx, ctor);
151160
for (i, col_i) in specialized_columns.iter().enumerate() {
152161
// Compute witnesses for each column.
153-
let wits_for_col_i = collect_nonexhaustive_missing_variants(cx, col_i);
162+
let wits_for_col_i = collect_nonexhaustive_missing_variants(cx, col_i, wildcard_arena);
154163
// For each witness, we build a new pattern in the shape of `ctor(_, _, wit, _, _)`,
155164
// adding enough wildcards to match `arity`.
156165
for wit in wits_for_col_i {
@@ -163,17 +172,18 @@ fn collect_nonexhaustive_missing_variants<'p, 'tcx>(
163172
witnesses
164173
}
165174

166-
pub(crate) fn lint_nonexhaustive_missing_variants<'p, 'tcx>(
175+
pub(crate) fn lint_nonexhaustive_missing_variants<'a, 'p, 'tcx>(
167176
cx: &MatchCheckCtxt<'p, 'tcx>,
168177
arms: &[MatchArm<'p, 'tcx>],
169-
pat_column: &PatternColumn<'p, 'tcx>,
178+
pat_column: &PatternColumn<'a, 'p, 'tcx>,
170179
scrut_ty: Ty<'tcx>,
180+
wildcard_arena: &TypedArena<DeconstructedPat<'p, 'tcx>>,
171181
) {
172182
if !matches!(
173183
cx.tcx.lint_level_at_node(NON_EXHAUSTIVE_OMITTED_PATTERNS, cx.match_lint_level).0,
174184
rustc_session::lint::Level::Allow
175185
) {
176-
let witnesses = collect_nonexhaustive_missing_variants(cx, pat_column);
186+
let witnesses = collect_nonexhaustive_missing_variants(cx, pat_column, wildcard_arena);
177187
if !witnesses.is_empty() {
178188
// Report that a match of a `non_exhaustive` enum marked with `non_exhaustive_omitted_patterns`
179189
// is not exhaustive enough.
@@ -215,15 +225,16 @@ pub(crate) fn lint_nonexhaustive_missing_variants<'p, 'tcx>(
215225
}
216226

217227
/// Traverse the patterns to warn the user about ranges that overlap on their endpoints.
218-
#[instrument(level = "debug", skip(cx))]
219-
pub(crate) fn lint_overlapping_range_endpoints<'p, 'tcx>(
228+
#[instrument(level = "debug", skip(cx, wildcard_arena))]
229+
pub(crate) fn lint_overlapping_range_endpoints<'a, 'p, 'tcx>(
220230
cx: &MatchCheckCtxt<'p, 'tcx>,
221-
column: &PatternColumn<'p, 'tcx>,
231+
column: &PatternColumn<'a, 'p, 'tcx>,
232+
wildcard_arena: &TypedArena<DeconstructedPat<'p, 'tcx>>,
222233
) {
223234
let Some(ty) = column.head_ty() else {
224235
return;
225236
};
226-
let pcx = &PatCtxt::new_dummy(cx, ty);
237+
let pcx = &PatCtxt::new_dummy(cx, ty, wildcard_arena);
227238

228239
let set = column.analyze_ctors(pcx);
229240

@@ -282,7 +293,7 @@ pub(crate) fn lint_overlapping_range_endpoints<'p, 'tcx>(
282293
// Recurse into the fields.
283294
for ctor in set.present {
284295
for col in column.specialize(pcx, &ctor) {
285-
lint_overlapping_range_endpoints(cx, &col);
296+
lint_overlapping_range_endpoints(cx, &col, wildcard_arena);
286297
}
287298
}
288299
}

compiler/rustc_pattern_analysis/src/pat.rs

Lines changed: 19 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ impl<'p, 'tcx> DeconstructedPat<'p, 'tcx> {
5353
matches!(self.ctor, Or)
5454
}
5555
/// Expand this (possibly-nested) or-pattern into its alternatives.
56-
pub(crate) fn flatten_or_pat(&'p self) -> SmallVec<[&'p Self; 1]> {
56+
pub(crate) fn flatten_or_pat(&self) -> SmallVec<[&Self; 1]> {
5757
if self.is_or_pat() {
5858
self.iter_fields().flat_map(|p| p.flatten_or_pat()).collect()
5959
} else {
@@ -80,25 +80,29 @@ impl<'p, 'tcx> DeconstructedPat<'p, 'tcx> {
8080
/// Specialize this pattern with a constructor.
8181
/// `other_ctor` can be different from `self.ctor`, but must be covered by it.
8282
pub(crate) fn specialize<'a>(
83-
&'a self,
84-
pcx: &PatCtxt<'_, 'p, 'tcx>,
83+
&self,
84+
pcx: &PatCtxt<'a, 'p, 'tcx>,
8585
other_ctor: &Constructor<'tcx>,
86-
) -> SmallVec<[&'p DeconstructedPat<'p, 'tcx>; 2]> {
86+
) -> SmallVec<[&'a DeconstructedPat<'p, 'tcx>; 2]> {
87+
let wildcard_sub_tys = || {
88+
let tys = pcx.cx.ctor_sub_tys(other_ctor, pcx.ty);
89+
tys.iter()
90+
.map(|ty| DeconstructedPat::wildcard(*ty, Span::default()))
91+
.map(|pat| pcx.wildcard_arena.alloc(pat) as &_)
92+
.collect()
93+
};
8794
match (&self.ctor, other_ctor) {
88-
(Wildcard, _) => {
89-
// We return a wildcard for each field of `other_ctor`.
90-
pcx.cx.ctor_wildcard_fields(other_ctor, pcx.ty).iter().collect()
91-
}
95+
// Return a wildcard for each field of `other_ctor`.
96+
(Wildcard, _) => wildcard_sub_tys(),
97+
// The only non-trivial case: two slices of different arity. `other_slice` is
98+
// guaranteed to have a larger arity, so we fill the middle part with enough
99+
// wildcards to reach the length of the new, larger slice.
92100
(
93101
&Slice(self_slice @ Slice { kind: SliceKind::VarLen(prefix, suffix), .. }),
94102
&Slice(other_slice),
95103
) if self_slice.arity() != other_slice.arity() => {
96-
// The only non-trivial case: two slices of different arity. `other_slice` is
97-
// guaranteed to have a larger arity, so we fill the middle part with enough
98-
// wildcards to reach the length of the new, larger slice.
99104
// Start with a slice of wildcards of the appropriate length.
100-
let mut fields: SmallVec<[_; 2]> =
101-
pcx.cx.ctor_wildcard_fields(other_ctor, pcx.ty).iter().collect();
105+
let mut fields: SmallVec<[_; 2]> = wildcard_sub_tys();
102106
// Fill in the fields from both ends.
103107
let new_arity = fields.len();
104108
for i in 0..prefix {
@@ -179,9 +183,8 @@ impl<'tcx> WitnessPat<'tcx> {
179183
/// For example, if `ctor` is a `Constructor::Variant` for `Option::Some`, we get the pattern
180184
/// `Some(_)`.
181185
pub(crate) fn wild_from_ctor(pcx: &PatCtxt<'_, '_, 'tcx>, ctor: Constructor<'tcx>) -> Self {
182-
let field_tys =
183-
pcx.cx.ctor_wildcard_fields(&ctor, pcx.ty).iter().map(|deco_pat| deco_pat.ty());
184-
let fields = field_tys.map(|ty| Self::wildcard(ty)).collect();
186+
let field_tys = pcx.cx.ctor_sub_tys(&ctor, pcx.ty);
187+
let fields = field_tys.iter().map(|ty| Self::wildcard(*ty)).collect();
185188
Self::new(ctor, fields, pcx.ty)
186189
}
187190

0 commit comments

Comments
 (0)