Skip to content

Commit 6bf028d

Browse files
committed
Use ty::BoundVar in more places.
There are lots of conversions between integers and `BoundVars`. Some of these are unavoidable, but by storing bound vars as `BoundVar` rather than `u32` in a few places (e.g. `BoundRegionKind::BrAnon`, `BoundTyKind::Anon`) we reduce the number of conversions. It's also good to store these values with the more informative type. The commit also impls `AddAssign<usize>` for newtypes, to allow incrementing. Some of the Chalk types (e.g. `BoundVar` and `Placeholder`) use `usize` for bound vars. If they were change then more conversions could be avoided, but this is difficult because `chalk_ir` is a module outside the compiler.
1 parent ca06df9 commit 6bf028d

File tree

20 files changed

+125
-132
lines changed

20 files changed

+125
-132
lines changed

compiler/rustc_hir_analysis/src/check/intrinsic.rs

+10-10
Original file line numberDiff line numberDiff line change
@@ -138,20 +138,20 @@ pub fn check_intrinsic_type(tcx: TyCtxt<'_>, it: &hir::ForeignItem<'_>) {
138138
let intrinsic_name = tcx.item_name(intrinsic_id);
139139
let name_str = intrinsic_name.as_str();
140140

141+
let var0 = ty::BoundVar::from_u32(0);
142+
let var1 = ty::BoundVar::from_u32(1);
141143
let bound_vars = tcx.mk_bound_variable_kinds(&[
142-
ty::BoundVariableKind::Region(ty::BrAnon(0, None)),
144+
ty::BoundVariableKind::Region(ty::BrAnon(var0, None)),
143145
ty::BoundVariableKind::Region(ty::BrEnv),
144146
]);
145147
let mk_va_list_ty = |mutbl| {
146148
tcx.lang_items().va_list().map(|did| {
147149
let region = tcx.mk_re_late_bound(
148150
ty::INNERMOST,
149-
ty::BoundRegion { var: ty::BoundVar::from_u32(0), kind: ty::BrAnon(0, None) },
150-
);
151-
let env_region = tcx.mk_re_late_bound(
152-
ty::INNERMOST,
153-
ty::BoundRegion { var: ty::BoundVar::from_u32(1), kind: ty::BrEnv },
151+
ty::BoundRegion { var: var0, kind: ty::BrAnon(var0, None) },
154152
);
153+
let env_region =
154+
tcx.mk_re_late_bound(ty::INNERMOST, ty::BoundRegion { var: var1, kind: ty::BrEnv });
155155
let va_list_ty = tcx.type_of(did).subst(tcx, &[region.into()]);
156156
(tcx.mk_ref(env_region, ty::TypeAndMut { ty: va_list_ty, mutbl }), va_list_ty)
157157
})
@@ -387,8 +387,8 @@ pub fn check_intrinsic_type(tcx: TyCtxt<'_>, it: &hir::ForeignItem<'_>) {
387387
);
388388
let discriminant_def_id = assoc_items[0];
389389

390-
let br =
391-
ty::BoundRegion { var: ty::BoundVar::from_u32(0), kind: ty::BrAnon(0, None) };
390+
let var = ty::BoundVar::from_u32(0);
391+
let br = ty::BoundRegion { var, kind: ty::BrAnon(var, None) };
392392
(
393393
1,
394394
vec![tcx.mk_imm_ref(tcx.mk_re_late_bound(ty::INNERMOST, br), param(0))],
@@ -440,8 +440,8 @@ pub fn check_intrinsic_type(tcx: TyCtxt<'_>, it: &hir::ForeignItem<'_>) {
440440
sym::nontemporal_store => (1, vec![tcx.mk_mut_ptr(param(0)), param(0)], tcx.mk_unit()),
441441

442442
sym::raw_eq => {
443-
let br =
444-
ty::BoundRegion { var: ty::BoundVar::from_u32(0), kind: ty::BrAnon(0, None) };
443+
let var = ty::BoundVar::from_u32(0);
444+
let br = ty::BoundRegion { var, kind: ty::BrAnon(var, None) };
445445
let param_ty = tcx.mk_imm_ref(tcx.mk_re_late_bound(ty::INNERMOST, br), param(0));
446446
(1, vec![param_ty; 2], tcx.types.bool)
447447
}

compiler/rustc_hir_typeck/src/generator_interior/mod.rs

+3-5
Original file line numberDiff line numberDiff line change
@@ -240,8 +240,8 @@ pub fn resolve_interior<'a, 'tcx>(
240240

241241
let mut counter = 0;
242242
let mut mk_bound_region = |span| {
243-
let kind = ty::BrAnon(counter, span);
244243
let var = ty::BoundVar::from_u32(counter);
244+
let kind = ty::BrAnon(var, span);
245245
counter += 1;
246246
ty::BoundRegion { var, kind }
247247
};
@@ -282,7 +282,6 @@ pub fn resolve_interior<'a, 'tcx>(
282282
.collect();
283283

284284
let mut bound_vars: SmallVec<[BoundVariableKind; 4]> = smallvec![];
285-
let mut counter = 0;
286285
// Optimization: If there is only one captured type, then we don't actually
287286
// need to fold and reindex (since the first type doesn't change).
288287
let type_causes = if captured_tys.len() > 0 {
@@ -293,13 +292,12 @@ pub fn resolve_interior<'a, 'tcx>(
293292
type_causes,
294293
FnMutDelegate {
295294
regions: &mut |br| {
295+
let var = ty::BoundVar::from_usize(bound_vars.len());
296296
let kind = match br.kind {
297-
ty::BrAnon(_, span) => ty::BrAnon(counter, span),
297+
ty::BrAnon(_, span) => ty::BrAnon(var, span),
298298
_ => br.kind,
299299
};
300-
let var = ty::BoundVar::from_usize(bound_vars.len());
301300
bound_vars.push(ty::BoundVariableKind::Region(kind));
302-
counter += 1;
303301
fcx.tcx.mk_re_late_bound(ty::INNERMOST, ty::BoundRegion { var, kind })
304302
},
305303
types: &mut |b| bug!("unexpected bound ty in binder: {b:?}"),

compiler/rustc_infer/src/errors/note_and_explain.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -90,9 +90,9 @@ impl<'a> DescriptionCtx<'a> {
9090
};
9191
me.span = Some(sp);
9292
}
93-
ty::BrAnon(idx, span) => {
93+
ty::BrAnon(var, span) => {
9494
me.kind = "anon_num_here";
95-
me.num_arg = idx+1;
95+
me.num_arg = var.as_u32() + 1;
9696
me.span = match span {
9797
Some(_) => span,
9898
None => Some(tcx.def_span(scope)),

compiler/rustc_infer/src/infer/canonical/canonicalizer.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -772,7 +772,7 @@ impl<'cx, 'tcx> Canonicalizer<'cx, 'tcx> {
772772
r: ty::Region<'tcx>,
773773
) -> ty::Region<'tcx> {
774774
let var = self.canonical_var(info, r.into());
775-
let br = ty::BoundRegion { var, kind: ty::BrAnon(var.as_u32(), None) };
775+
let br = ty::BoundRegion { var, kind: ty::BrAnon(var, None) };
776776
self.interner().mk_re_late_bound(self.binder_index, br)
777777
}
778778

compiler/rustc_infer/src/infer/error_reporting/mod.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -226,8 +226,8 @@ fn msg_span_from_early_bound_and_free_regions<'tcx>(
226226
};
227227
(text, sp)
228228
}
229-
ty::BrAnon(idx, span) => (
230-
format!("the anonymous lifetime #{} defined here", idx + 1),
229+
ty::BrAnon(var, span) => (
230+
format!("the anonymous lifetime #{} defined here", var.as_u32() + 1),
231231
match span {
232232
Some(span) => span,
233233
None => tcx.def_span(scope)

compiler/rustc_infer/src/infer/mod.rs

+11-10
Original file line numberDiff line numberDiff line change
@@ -2120,7 +2120,7 @@ fn replace_param_and_infer_substs_with_placeholder<'tcx>(
21202120
) -> SubstsRef<'tcx> {
21212121
struct ReplaceParamAndInferWithPlaceholder<'tcx> {
21222122
tcx: TyCtxt<'tcx>,
2123-
idx: u32,
2123+
var: ty::BoundVar,
21242124
}
21252125

21262126
impl<'tcx> TypeFolder<TyCtxt<'tcx>> for ReplaceParamAndInferWithPlaceholder<'tcx> {
@@ -2133,9 +2133,9 @@ fn replace_param_and_infer_substs_with_placeholder<'tcx>(
21332133
self.tcx.mk_placeholder(ty::PlaceholderType {
21342134
universe: ty::UniverseIndex::ROOT,
21352135
name: ty::BoundTyKind::Anon({
2136-
let idx = self.idx;
2137-
self.idx += 1;
2138-
idx
2136+
let var = self.var;
2137+
self.var += 1;
2138+
var
21392139
}),
21402140
})
21412141
} else {
@@ -2153,11 +2153,11 @@ fn replace_param_and_infer_substs_with_placeholder<'tcx>(
21532153
self.tcx.mk_const(
21542154
ty::PlaceholderConst {
21552155
universe: ty::UniverseIndex::ROOT,
2156-
name: ty::BoundVar::from_u32({
2157-
let idx = self.idx;
2158-
self.idx += 1;
2159-
idx
2160-
}),
2156+
name: {
2157+
let var = self.var;
2158+
self.var += 1;
2159+
var
2160+
},
21612161
},
21622162
ty,
21632163
)
@@ -2167,5 +2167,6 @@ fn replace_param_and_infer_substs_with_placeholder<'tcx>(
21672167
}
21682168
}
21692169

2170-
substs.fold_with(&mut ReplaceParamAndInferWithPlaceholder { tcx, idx: 0 })
2170+
substs
2171+
.fold_with(&mut ReplaceParamAndInferWithPlaceholder { tcx, var: ty::BoundVar::from_u32(0) })
21712172
}

compiler/rustc_macros/src/newtype.rs

+6
Original file line numberDiff line numberDiff line change
@@ -254,6 +254,12 @@ impl Parse for Newtype {
254254
}
255255
}
256256

257+
impl std::ops::AddAssign<usize> for #name {
258+
fn add_assign(&mut self, rhs: usize) {
259+
*self = Self::from_usize(self.as_usize() + rhs)
260+
}
261+
}
262+
257263
impl rustc_index::vec::Idx for #name {
258264
#[inline]
259265
fn new(value: usize) -> Self {

compiler/rustc_middle/src/infer/canonical.rs

+4-6
Original file line numberDiff line numberDiff line change
@@ -149,15 +149,15 @@ impl<'tcx> CanonicalVarInfo<'tcx> {
149149
}
150150
}
151151

152-
pub fn expect_anon_placeholder(self) -> u32 {
152+
pub fn expect_anon_placeholder(self) -> ty::BoundVar {
153153
match self.kind {
154154
CanonicalVarKind::Ty(_)
155155
| CanonicalVarKind::Region(_)
156156
| CanonicalVarKind::Const(_, _) => bug!("expected placeholder: {self:?}"),
157157

158158
CanonicalVarKind::PlaceholderRegion(placeholder) => placeholder.name.expect_anon(),
159159
CanonicalVarKind::PlaceholderTy(placeholder) => placeholder.name.expect_anon(),
160-
CanonicalVarKind::PlaceholderConst(placeholder, _) => placeholder.name.as_u32(),
160+
CanonicalVarKind::PlaceholderConst(placeholder, _) => placeholder.name,
161161
}
162162
}
163163
}
@@ -409,10 +409,8 @@ impl<'tcx> CanonicalVarValues<'tcx> {
409409
tcx.mk_bound(ty::INNERMOST, ty::BoundVar::from_usize(i).into()).into()
410410
}
411411
CanonicalVarKind::Region(_) | CanonicalVarKind::PlaceholderRegion(_) => {
412-
let br = ty::BoundRegion {
413-
var: ty::BoundVar::from_usize(i),
414-
kind: ty::BrAnon(i as u32, None),
415-
};
412+
let var = ty::BoundVar::from_usize(i);
413+
let br = ty::BoundRegion { var, kind: ty::BrAnon(var, None) };
416414
tcx.mk_re_late_bound(ty::INNERMOST, br).into()
417415
}
418416
CanonicalVarKind::Const(_, ty)

compiler/rustc_middle/src/mir/query.rs

+2-4
Original file line numberDiff line numberDiff line change
@@ -411,10 +411,8 @@ impl<'tcx> ClosureOutlivesSubjectTy<'tcx> {
411411
pub fn bind(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Self {
412412
let inner = tcx.fold_regions(ty, |r, depth| match r.kind() {
413413
ty::ReVar(vid) => {
414-
let br = ty::BoundRegion {
415-
var: ty::BoundVar::new(vid.index()),
416-
kind: ty::BrAnon(vid.as_u32(), None),
417-
};
414+
let var = ty::BoundVar::new(vid.index());
415+
let br = ty::BoundRegion { var, kind: ty::BrAnon(var, None) };
418416
tcx.mk_re_late_bound(depth, br)
419417
}
420418
_ => bug!("unexpected region in ClosureOutlivesSubjectTy: {r:?}"),

compiler/rustc_middle/src/ty/context.rs

+5-7
Original file line numberDiff line numberDiff line change
@@ -384,12 +384,10 @@ impl<'tcx> CommonLifetimes<'tcx> {
384384
.map(|i| {
385385
(0..NUM_PREINTERNED_RE_LATE_BOUNDS_V)
386386
.map(|v| {
387+
let var = ty::BoundVar::from_u32(v);
387388
mk(ty::ReLateBound(
388-
ty::DebruijnIndex::from(i),
389-
ty::BoundRegion {
390-
var: ty::BoundVar::from(v),
391-
kind: ty::BrAnon(v, None),
392-
},
389+
ty::DebruijnIndex::from_u32(i),
390+
ty::BoundRegion { var, kind: ty::BrAnon(var, None) },
393391
))
394392
})
395393
.collect()
@@ -2076,9 +2074,9 @@ impl<'tcx> TyCtxt<'tcx> {
20762074
) -> Region<'tcx> {
20772075
// Use a pre-interned one when possible.
20782076
if let ty::BoundRegion { var, kind: ty::BrAnon(v, None) } = bound_region
2079-
&& var.as_u32() == v
2077+
&& var == v
20802078
&& let Some(inner) = self.lifetimes.re_late_bounds.get(debruijn.as_usize())
2081-
&& let Some(re) = inner.get(v as usize).copied()
2079+
&& let Some(re) = inner.get(v.as_usize()).copied()
20822080
{
20832081
re
20842082
} else {

compiler/rustc_middle/src/ty/fold.rs

+2-6
Original file line numberDiff line numberDiff line change
@@ -379,9 +379,7 @@ impl<'tcx> TyCtxt<'tcx> {
379379
let index = entry.index();
380380
let var = ty::BoundVar::from_usize(index);
381381
let kind = entry
382-
.or_insert_with(|| {
383-
ty::BoundVariableKind::Region(ty::BrAnon(index as u32, None))
384-
})
382+
.or_insert_with(|| ty::BoundVariableKind::Region(ty::BrAnon(var, None)))
385383
.expect_region();
386384
let br = ty::BoundRegion { var, kind };
387385
self.tcx.mk_re_late_bound(ty::INNERMOST, br)
@@ -391,9 +389,7 @@ impl<'tcx> TyCtxt<'tcx> {
391389
let index = entry.index();
392390
let var = ty::BoundVar::from_usize(index);
393391
let kind = entry
394-
.or_insert_with(|| {
395-
ty::BoundVariableKind::Ty(ty::BoundTyKind::Anon(index as u32))
396-
})
392+
.or_insert_with(|| ty::BoundVariableKind::Ty(ty::BoundTyKind::Anon(var)))
397393
.expect_ty();
398394
self.tcx.mk_bound(ty::INNERMOST, BoundTy { var, kind })
399395
}

compiler/rustc_middle/src/ty/print/pretty.rs

+1-3
Original file line numberDiff line numberDiff line change
@@ -701,9 +701,7 @@ pub trait PrettyPrinter<'tcx>:
701701
ty::Error(_) => p!("[type error]"),
702702
ty::Param(ref param_ty) => p!(print(param_ty)),
703703
ty::Bound(debruijn, bound_ty) => match bound_ty.kind {
704-
ty::BoundTyKind::Anon(bv) => {
705-
self.pretty_print_bound_var(debruijn, ty::BoundVar::from_u32(bv))?
706-
}
704+
ty::BoundTyKind::Anon(bv) => self.pretty_print_bound_var(debruijn, bv)?,
707705
ty::BoundTyKind::Param(_, s) => match self.should_print_verbose() {
708706
true if debruijn == ty::INNERMOST => p!(write("^{}", s)),
709707
true => p!(write("^{}_{}", debruijn.index(), s)),

compiler/rustc_middle/src/ty/sty.rs

+6-6
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ pub struct FreeRegion {
6060
#[derive(HashStable)]
6161
pub enum BoundRegionKind {
6262
/// An anonymous region parameter for a given fn (&T)
63-
BrAnon(u32, Option<Span>),
63+
BrAnon(BoundVar, Option<Span>),
6464

6565
/// Named region parameters for functions (a in &'a T)
6666
///
@@ -108,12 +108,12 @@ impl BoundRegionKind {
108108
}
109109
}
110110

111-
pub fn expect_anon(&self) -> u32 {
111+
pub fn expect_anon(&self) -> BoundVar {
112112
match *self {
113113
BoundRegionKind::BrNamed(_, _) | BoundRegionKind::BrEnv => {
114114
bug!("expected anon region: {self:?}")
115115
}
116-
BoundRegionKind::BrAnon(idx, _) => idx,
116+
BoundRegionKind::BrAnon(var, _) => var,
117117
}
118118
}
119119
}
@@ -1529,12 +1529,12 @@ pub struct BoundTy {
15291529
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)]
15301530
#[derive(HashStable)]
15311531
pub enum BoundTyKind {
1532-
Anon(u32),
1532+
Anon(BoundVar),
15331533
Param(DefId, Symbol),
15341534
}
15351535

15361536
impl BoundTyKind {
1537-
pub fn expect_anon(self) -> u32 {
1537+
pub fn expect_anon(self) -> BoundVar {
15381538
match self {
15391539
BoundTyKind::Anon(i) => i,
15401540
_ => bug!(),
@@ -1544,7 +1544,7 @@ impl BoundTyKind {
15441544

15451545
impl From<BoundVar> for BoundTy {
15461546
fn from(var: BoundVar) -> Self {
1547-
BoundTy { var, kind: BoundTyKind::Anon(var.as_u32()) }
1547+
BoundTy { var, kind: BoundTyKind::Anon(var) }
15481548
}
15491549
}
15501550

compiler/rustc_symbol_mangling/src/v0.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -221,7 +221,7 @@ impl<'tcx> SymbolMangler<'tcx> {
221221
let lifetimes = regions
222222
.into_iter()
223223
.map(|br| match br {
224-
ty::BrAnon(i, _) => i,
224+
ty::BrAnon(var, _) => var.as_u32(),
225225
_ => bug!("symbol_names: non-anonymized region `{:?}` in `{:?}`", br, value),
226226
})
227227
.max()
@@ -338,9 +338,9 @@ impl<'tcx> Printer<'tcx> for &mut SymbolMangler<'tcx> {
338338

339339
// Late-bound lifetimes use indices starting at 1,
340340
// see `BinderLevel` for more details.
341-
ty::ReLateBound(debruijn, ty::BoundRegion { kind: ty::BrAnon(i, _), .. }) => {
341+
ty::ReLateBound(debruijn, ty::BoundRegion { kind: ty::BrAnon(var, _), .. }) => {
342342
let binder = &self.binders[self.binders.len() - 1 - debruijn.index()];
343-
let depth = binder.lifetime_depths.start + i;
343+
let depth = binder.lifetime_depths.start + var.as_u32();
344344

345345
1 + (self.binders.last().unwrap().lifetime_depths.end - 1 - depth)
346346
}

compiler/rustc_trait_selection/src/solve/canonicalize.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -257,7 +257,7 @@ impl<'tcx> TypeFolder<TyCtxt<'tcx>> for Canonicalizer<'_, 'tcx> {
257257
self.primitive_var_infos.push(CanonicalVarInfo { kind });
258258
var
259259
});
260-
let br = ty::BoundRegion { var, kind: BrAnon(var.as_u32(), None) };
260+
let br = ty::BoundRegion { var, kind: BrAnon(var, None) };
261261
self.interner().mk_re_late_bound(self.binder_index, br)
262262
}
263263

@@ -300,14 +300,14 @@ impl<'tcx> TypeFolder<TyCtxt<'tcx>> for Canonicalizer<'_, 'tcx> {
300300
ty::Placeholder(placeholder) => match self.canonicalize_mode {
301301
CanonicalizeMode::Input => CanonicalVarKind::PlaceholderTy(ty::Placeholder {
302302
universe: placeholder.universe,
303-
name: BoundTyKind::Anon(self.variables.len() as u32),
303+
name: BoundTyKind::Anon(ty::BoundVar::from_usize(self.variables.len())),
304304
}),
305305
CanonicalizeMode::Response { .. } => CanonicalVarKind::PlaceholderTy(placeholder),
306306
},
307307
ty::Param(_) => match self.canonicalize_mode {
308308
CanonicalizeMode::Input => CanonicalVarKind::PlaceholderTy(ty::Placeholder {
309309
universe: ty::UniverseIndex::ROOT,
310-
name: ty::BoundTyKind::Anon(self.variables.len() as u32),
310+
name: ty::BoundTyKind::Anon(ty::BoundVar::from(self.variables.len())),
311311
}),
312312
CanonicalizeMode::Response { .. } => bug!("param ty in response: {t:?}"),
313313
},
@@ -345,7 +345,7 @@ impl<'tcx> TypeFolder<TyCtxt<'tcx>> for Canonicalizer<'_, 'tcx> {
345345
var
346346
}),
347347
);
348-
let bt = ty::BoundTy { var, kind: BoundTyKind::Anon(var.index() as u32) };
348+
let bt = ty::BoundTy { var, kind: BoundTyKind::Anon(var) };
349349
self.interner().mk_bound(self.binder_index, bt)
350350
}
351351

compiler/rustc_trait_selection/src/solve/eval_ctxt/canonical.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -188,7 +188,7 @@ impl<'tcx> EvalCtxt<'_, 'tcx> {
188188
} else {
189189
// For placeholders which were already part of the input, we simply map this
190190
// universal bound variable back the placeholder of the input.
191-
original_values[info.expect_anon_placeholder() as usize]
191+
original_values[info.expect_anon_placeholder().as_usize()]
192192
}
193193
},
194194
));

0 commit comments

Comments
 (0)