Skip to content

Commit a4079b2

Browse files
committed
Auto merge of rust-lang#133961 - lcnr:borrowck-cleanup, r=jackh726
cleanup region handling: add `LateParamRegionKind` The second commit is to enable a split between `BoundRegionKind` and `LateParamRegionKind`, by avoiding `BoundRegionKind` where it isn't necessary. The third comment then adds `LateParamRegionKind` to avoid having the same late-param region for separate bound regions. This fixes rust-lang#124021. r? `@compiler-errors`
2 parents bab18a5 + 4d5aaa0 commit a4079b2

File tree

23 files changed

+194
-66
lines changed

23 files changed

+194
-66
lines changed

compiler/rustc_borrowck/src/diagnostics/region_errors.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -188,7 +188,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
188188
/// Returns `true` if a closure is inferred to be an `FnMut` closure.
189189
fn is_closure_fn_mut(&self, fr: RegionVid) -> bool {
190190
if let Some(ty::ReLateParam(late_param)) = self.to_error_region(fr).as_deref()
191-
&& let ty::BoundRegionKind::ClosureEnv = late_param.bound_region
191+
&& let ty::LateParamRegionKind::ClosureEnv = late_param.kind
192192
&& let DefiningTy::Closure(_, args) = self.regioncx.universal_regions().defining_ty
193193
{
194194
return args.as_closure().kind() == ty::ClosureKind::FnMut;

compiler/rustc_borrowck/src/diagnostics/region_name.rs

+6-6
Original file line numberDiff line numberDiff line change
@@ -299,17 +299,17 @@ impl<'tcx> MirBorrowckCtxt<'_, '_, 'tcx> {
299299
Some(RegionName { name: kw::StaticLifetime, source: RegionNameSource::Static })
300300
}
301301

302-
ty::ReLateParam(late_param) => match late_param.bound_region {
303-
ty::BoundRegionKind::Named(region_def_id, name) => {
302+
ty::ReLateParam(late_param) => match late_param.kind {
303+
ty::LateParamRegionKind::Named(region_def_id, name) => {
304304
// Get the span to point to, even if we don't use the name.
305305
let span = tcx.hir().span_if_local(region_def_id).unwrap_or(DUMMY_SP);
306306
debug!(
307307
"bound region named: {:?}, is_named: {:?}",
308308
name,
309-
late_param.bound_region.is_named()
309+
late_param.kind.is_named()
310310
);
311311

312-
if late_param.bound_region.is_named() {
312+
if late_param.kind.is_named() {
313313
// A named region that is actually named.
314314
Some(RegionName {
315315
name,
@@ -331,7 +331,7 @@ impl<'tcx> MirBorrowckCtxt<'_, '_, 'tcx> {
331331
}
332332
}
333333

334-
ty::BoundRegionKind::ClosureEnv => {
334+
ty::LateParamRegionKind::ClosureEnv => {
335335
let def_ty = self.regioncx.universal_regions().defining_ty;
336336

337337
let closure_kind = match def_ty {
@@ -368,7 +368,7 @@ impl<'tcx> MirBorrowckCtxt<'_, '_, 'tcx> {
368368
})
369369
}
370370

371-
ty::BoundRegionKind::Anon => None,
371+
ty::LateParamRegionKind::Anon(_) => None,
372372
},
373373

374374
ty::ReBound(..)

compiler/rustc_borrowck/src/region_infer/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -2230,7 +2230,7 @@ impl<'tcx> RegionDefinition<'tcx> {
22302230
fn new(universe: ty::UniverseIndex, rv_origin: RegionVariableOrigin) -> Self {
22312231
// Create a new region definition. Note that, for free
22322232
// regions, the `external_name` field gets updated later in
2233-
// `init_universal_regions`.
2233+
// `init_free_and_bound_regions`.
22342234

22352235
let origin = match rv_origin {
22362236
RegionVariableOrigin::Nll(origin) => origin,

compiler/rustc_borrowck/src/universal_regions.rs

+10-8
Original file line numberDiff line numberDiff line change
@@ -842,8 +842,9 @@ impl<'tcx> BorrowckInferCtxt<'tcx> {
842842
{
843843
let (value, _map) = self.tcx.instantiate_bound_regions(value, |br| {
844844
debug!(?br);
845+
let kind = ty::LateParamRegionKind::from_bound(br.var, br.kind);
845846
let liberated_region =
846-
ty::Region::new_late_param(self.tcx, all_outlive_scope.to_def_id(), br.kind);
847+
ty::Region::new_late_param(self.tcx, all_outlive_scope.to_def_id(), kind);
847848
let region_vid = {
848849
let name = match br.kind.get_name() {
849850
Some(name) => name,
@@ -941,12 +942,13 @@ fn for_each_late_bound_region_in_item<'tcx>(
941942
return;
942943
}
943944

944-
for bound_var in tcx.late_bound_vars(tcx.local_def_id_to_hir_id(mir_def_id)) {
945-
let ty::BoundVariableKind::Region(bound_region) = bound_var else {
946-
continue;
947-
};
948-
let liberated_region =
949-
ty::Region::new_late_param(tcx, mir_def_id.to_def_id(), bound_region);
950-
f(liberated_region);
945+
for (idx, bound_var) in
946+
tcx.late_bound_vars(tcx.local_def_id_to_hir_id(mir_def_id)).iter().enumerate()
947+
{
948+
if let ty::BoundVariableKind::Region(kind) = bound_var {
949+
let kind = ty::LateParamRegionKind::from_bound(ty::BoundVar::from_usize(idx), kind);
950+
let liberated_region = ty::Region::new_late_param(tcx, mir_def_id.to_def_id(), kind);
951+
f(liberated_region);
952+
}
951953
}
952954
}

compiler/rustc_hir_analysis/src/check/compare_impl_item.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -430,12 +430,12 @@ fn compare_method_predicate_entailment<'tcx>(
430430
Ok(())
431431
}
432432

433-
struct RemapLateBound<'a, 'tcx> {
433+
struct RemapLateParam<'a, 'tcx> {
434434
tcx: TyCtxt<'tcx>,
435-
mapping: &'a FxIndexMap<ty::BoundRegionKind, ty::BoundRegionKind>,
435+
mapping: &'a FxIndexMap<ty::LateParamRegionKind, ty::LateParamRegionKind>,
436436
}
437437

438-
impl<'tcx> TypeFolder<TyCtxt<'tcx>> for RemapLateBound<'_, 'tcx> {
438+
impl<'tcx> TypeFolder<TyCtxt<'tcx>> for RemapLateParam<'_, 'tcx> {
439439
fn cx(&self) -> TyCtxt<'tcx> {
440440
self.tcx
441441
}
@@ -445,7 +445,7 @@ impl<'tcx> TypeFolder<TyCtxt<'tcx>> for RemapLateBound<'_, 'tcx> {
445445
ty::Region::new_late_param(
446446
self.tcx,
447447
fr.scope,
448-
self.mapping.get(&fr.bound_region).copied().unwrap_or(fr.bound_region),
448+
self.mapping.get(&fr.kind).copied().unwrap_or(fr.kind),
449449
)
450450
} else {
451451
r

compiler/rustc_hir_analysis/src/check/compare_impl_item/refine.rs

+8-3
Original file line numberDiff line numberDiff line change
@@ -289,19 +289,24 @@ fn report_mismatched_rpitit_signature<'tcx>(
289289
tcx.fn_sig(trait_m_def_id).skip_binder().bound_vars(),
290290
tcx.fn_sig(impl_m_def_id).skip_binder().bound_vars(),
291291
)
292-
.filter_map(|(impl_bv, trait_bv)| {
292+
.enumerate()
293+
.filter_map(|(idx, (impl_bv, trait_bv))| {
293294
if let ty::BoundVariableKind::Region(impl_bv) = impl_bv
294295
&& let ty::BoundVariableKind::Region(trait_bv) = trait_bv
295296
{
296-
Some((impl_bv, trait_bv))
297+
let var = ty::BoundVar::from_usize(idx);
298+
Some((
299+
ty::LateParamRegionKind::from_bound(var, impl_bv),
300+
ty::LateParamRegionKind::from_bound(var, trait_bv),
301+
))
297302
} else {
298303
None
299304
}
300305
})
301306
.collect();
302307

303308
let mut return_ty =
304-
trait_m_sig.output().fold_with(&mut super::RemapLateBound { tcx, mapping: &mapping });
309+
trait_m_sig.output().fold_with(&mut super::RemapLateParam { tcx, mapping: &mapping });
305310

306311
if tcx.asyncness(impl_m_def_id).is_async() && tcx.asyncness(trait_m_def_id).is_async() {
307312
let ty::Alias(ty::Projection, future_ty) = return_ty.kind() else {

compiler/rustc_hir_analysis/src/check/wfcheck.rs

+4-1
Original file line numberDiff line numberDiff line change
@@ -2339,8 +2339,11 @@ fn lint_redundant_lifetimes<'tcx>(
23392339
);
23402340
// If we are in a function, add its late-bound lifetimes too.
23412341
if matches!(def_kind, DefKind::Fn | DefKind::AssocFn) {
2342-
for var in tcx.fn_sig(owner_id).instantiate_identity().bound_vars() {
2342+
for (idx, var) in
2343+
tcx.fn_sig(owner_id).instantiate_identity().bound_vars().iter().enumerate()
2344+
{
23432345
let ty::BoundVariableKind::Region(kind) = var else { continue };
2346+
let kind = ty::LateParamRegionKind::from_bound(ty::BoundVar::from_usize(idx), kind);
23442347
lifetimes.push(ty::Region::new_late_param(tcx, owner_id.to_def_id(), kind));
23452348
}
23462349
}

compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -355,7 +355,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
355355
ty::Region::new_late_param(
356356
tcx,
357357
scope.to_def_id(),
358-
ty::BoundRegionKind::Named(id.to_def_id(), name),
358+
ty::LateParamRegionKind::Named(id.to_def_id(), name),
359359
)
360360

361361
// (*) -- not late-bound, won't change

compiler/rustc_lint/src/impl_trait_overcaptures.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -325,7 +325,7 @@ where
325325
ParamKind::Free(def_id, name) => ty::Region::new_late_param(
326326
self.tcx,
327327
self.parent_def_id.to_def_id(),
328-
ty::BoundRegionKind::Named(def_id, name),
328+
ty::LateParamRegionKind::Named(def_id, name),
329329
),
330330
// Totally ignore late bound args from binders.
331331
ParamKind::Late => return true,
@@ -475,7 +475,7 @@ fn extract_def_id_from_arg<'tcx>(
475475
)
476476
| ty::ReLateParam(ty::LateParamRegion {
477477
scope: _,
478-
bound_region: ty::BoundRegionKind::Named(def_id, ..),
478+
kind: ty::LateParamRegionKind::Named(def_id, ..),
479479
}) => def_id,
480480
_ => unreachable!(),
481481
},
@@ -544,7 +544,7 @@ impl<'tcx> TypeRelation<TyCtxt<'tcx>> for FunctionalVariances<'tcx> {
544544
)
545545
| ty::ReLateParam(ty::LateParamRegion {
546546
scope: _,
547-
bound_region: ty::BoundRegionKind::Named(def_id, ..),
547+
kind: ty::LateParamRegionKind::Named(def_id, ..),
548548
}) => def_id,
549549
_ => {
550550
return Ok(a);

compiler/rustc_middle/src/ty/context.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -3091,7 +3091,7 @@ impl<'tcx> TyCtxt<'tcx> {
30913091
return ty::Region::new_late_param(
30923092
self,
30933093
new_parent.to_def_id(),
3094-
ty::BoundRegionKind::Named(
3094+
ty::LateParamRegionKind::Named(
30953095
lbv.to_def_id(),
30963096
self.item_name(lbv.to_def_id()),
30973097
),

compiler/rustc_middle/src/ty/fold.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -270,7 +270,8 @@ impl<'tcx> TyCtxt<'tcx> {
270270
T: TypeFoldable<TyCtxt<'tcx>>,
271271
{
272272
self.instantiate_bound_regions_uncached(value, |br| {
273-
ty::Region::new_late_param(self, all_outlive_scope, br.kind)
273+
let kind = ty::LateParamRegionKind::from_bound(br.var, br.kind);
274+
ty::Region::new_late_param(self, all_outlive_scope, kind)
274275
})
275276
}
276277

compiler/rustc_middle/src/ty/mod.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,8 @@ pub use self::predicate::{
8383
TypeOutlivesPredicate,
8484
};
8585
pub use self::region::{
86-
BoundRegion, BoundRegionKind, EarlyParamRegion, LateParamRegion, Region, RegionKind, RegionVid,
86+
BoundRegion, BoundRegionKind, EarlyParamRegion, LateParamRegion, LateParamRegionKind, Region,
87+
RegionKind, RegionVid,
8788
};
8889
pub use self::rvalue_scopes::RvalueScopes;
8990
pub use self::sty::{

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

+7-2
Original file line numberDiff line numberDiff line change
@@ -2374,8 +2374,8 @@ impl<'tcx> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx> {
23742374
match *region {
23752375
ty::ReEarlyParam(ref data) => data.has_name(),
23762376

2377+
ty::ReLateParam(ty::LateParamRegion { kind, .. }) => kind.is_named(),
23772378
ty::ReBound(_, ty::BoundRegion { kind: br, .. })
2378-
| ty::ReLateParam(ty::LateParamRegion { bound_region: br, .. })
23792379
| ty::RePlaceholder(ty::Placeholder {
23802380
bound: ty::BoundRegion { kind: br, .. }, ..
23812381
}) => {
@@ -2448,8 +2448,13 @@ impl<'tcx> FmtPrinter<'_, 'tcx> {
24482448
return Ok(());
24492449
}
24502450
}
2451+
ty::ReLateParam(ty::LateParamRegion { kind, .. }) => {
2452+
if let Some(name) = kind.get_name() {
2453+
p!(write("{}", name));
2454+
return Ok(());
2455+
}
2456+
}
24512457
ty::ReBound(_, ty::BoundRegion { kind: br, .. })
2452-
| ty::ReLateParam(ty::LateParamRegion { bound_region: br, .. })
24532458
| ty::RePlaceholder(ty::Placeholder {
24542459
bound: ty::BoundRegion { kind: br, .. }, ..
24552460
}) => {

compiler/rustc_middle/src/ty/region.rs

+73-8
Original file line numberDiff line numberDiff line change
@@ -69,9 +69,10 @@ impl<'tcx> Region<'tcx> {
6969
pub fn new_late_param(
7070
tcx: TyCtxt<'tcx>,
7171
scope: DefId,
72-
bound_region: ty::BoundRegionKind,
72+
kind: LateParamRegionKind,
7373
) -> Region<'tcx> {
74-
tcx.intern_region(ty::ReLateParam(ty::LateParamRegion { scope, bound_region }))
74+
let data = LateParamRegion { scope, kind };
75+
tcx.intern_region(ty::ReLateParam(data))
7576
}
7677

7778
#[inline]
@@ -124,8 +125,8 @@ impl<'tcx> Region<'tcx> {
124125
match kind {
125126
ty::ReEarlyParam(region) => Region::new_early_param(tcx, region),
126127
ty::ReBound(debruijn, region) => Region::new_bound(tcx, debruijn, region),
127-
ty::ReLateParam(ty::LateParamRegion { scope, bound_region }) => {
128-
Region::new_late_param(tcx, scope, bound_region)
128+
ty::ReLateParam(ty::LateParamRegion { scope, kind }) => {
129+
Region::new_late_param(tcx, scope, kind)
129130
}
130131
ty::ReStatic => tcx.lifetimes.re_static,
131132
ty::ReVar(vid) => Region::new_var(tcx, vid),
@@ -165,7 +166,7 @@ impl<'tcx> Region<'tcx> {
165166
match *self {
166167
ty::ReEarlyParam(ebr) => Some(ebr.name),
167168
ty::ReBound(_, br) => br.kind.get_name(),
168-
ty::ReLateParam(fr) => fr.bound_region.get_name(),
169+
ty::ReLateParam(fr) => fr.kind.get_name(),
169170
ty::ReStatic => Some(kw::StaticLifetime),
170171
ty::RePlaceholder(placeholder) => placeholder.bound.kind.get_name(),
171172
_ => None,
@@ -187,7 +188,7 @@ impl<'tcx> Region<'tcx> {
187188
match *self {
188189
ty::ReEarlyParam(ebr) => ebr.has_name(),
189190
ty::ReBound(_, br) => br.kind.is_named(),
190-
ty::ReLateParam(fr) => fr.bound_region.is_named(),
191+
ty::ReLateParam(fr) => fr.kind.is_named(),
191192
ty::ReStatic => true,
192193
ty::ReVar(..) => false,
193194
ty::RePlaceholder(placeholder) => placeholder.bound.kind.is_named(),
@@ -310,7 +311,7 @@ impl<'tcx> Region<'tcx> {
310311
Some(tcx.generics_of(binding_item).region_param(ebr, tcx).def_id)
311312
}
312313
ty::ReLateParam(ty::LateParamRegion {
313-
bound_region: ty::BoundRegionKind::Named(def_id, _),
314+
kind: ty::LateParamRegionKind::Named(def_id, _),
314315
..
315316
}) => Some(def_id),
316317
_ => None,
@@ -358,7 +359,71 @@ impl std::fmt::Debug for EarlyParamRegion {
358359
/// different parameters apart.
359360
pub struct LateParamRegion {
360361
pub scope: DefId,
361-
pub bound_region: BoundRegionKind,
362+
pub kind: LateParamRegionKind,
363+
}
364+
365+
/// When liberating bound regions, we map their [`BoundRegionKind`]
366+
/// to this as we need to track the index of anonymous regions. We
367+
/// otherwise end up liberating multiple bound regions to the same
368+
/// late-bound region.
369+
#[derive(Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, Copy)]
370+
#[derive(HashStable)]
371+
pub enum LateParamRegionKind {
372+
/// An anonymous region parameter for a given fn (&T)
373+
///
374+
/// Unlike [`BoundRegionKind::Anon`], this tracks the index of the
375+
/// liberated bound region.
376+
///
377+
/// We should ideally never liberate anonymous regions, but do so for the
378+
/// sake of diagnostics in `FnCtxt::sig_of_closure_with_expectation`.
379+
Anon(u32),
380+
381+
/// Named region parameters for functions (a in &'a T)
382+
///
383+
/// The `DefId` is needed to distinguish free regions in
384+
/// the event of shadowing.
385+
Named(DefId, Symbol),
386+
387+
/// Anonymous region for the implicit env pointer parameter
388+
/// to a closure
389+
ClosureEnv,
390+
}
391+
392+
impl LateParamRegionKind {
393+
pub fn from_bound(var: BoundVar, br: BoundRegionKind) -> LateParamRegionKind {
394+
match br {
395+
BoundRegionKind::Anon => LateParamRegionKind::Anon(var.as_u32()),
396+
BoundRegionKind::Named(def_id, name) => LateParamRegionKind::Named(def_id, name),
397+
BoundRegionKind::ClosureEnv => LateParamRegionKind::ClosureEnv,
398+
}
399+
}
400+
401+
pub fn is_named(&self) -> bool {
402+
match *self {
403+
LateParamRegionKind::Named(_, name) => {
404+
name != kw::UnderscoreLifetime && name != kw::Empty
405+
}
406+
_ => false,
407+
}
408+
}
409+
410+
pub fn get_name(&self) -> Option<Symbol> {
411+
if self.is_named() {
412+
match *self {
413+
LateParamRegionKind::Named(_, name) => return Some(name),
414+
_ => unreachable!(),
415+
}
416+
}
417+
418+
None
419+
}
420+
421+
pub fn get_id(&self) -> Option<DefId> {
422+
match *self {
423+
LateParamRegionKind::Named(id, _) => Some(id),
424+
_ => None,
425+
}
426+
}
362427
}
363428

364429
#[derive(Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, Copy)]

compiler/rustc_middle/src/ty/structural_impls.rs

+17-1
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,23 @@ impl fmt::Debug for ty::BoundRegionKind {
7777

7878
impl fmt::Debug for ty::LateParamRegion {
7979
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
80-
write!(f, "ReLateParam({:?}, {:?})", self.scope, self.bound_region)
80+
write!(f, "ReLateParam({:?}, {:?})", self.scope, self.kind)
81+
}
82+
}
83+
84+
impl fmt::Debug for ty::LateParamRegionKind {
85+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
86+
match *self {
87+
ty::LateParamRegionKind::Anon(idx) => write!(f, "BrAnon({idx})"),
88+
ty::LateParamRegionKind::Named(did, name) => {
89+
if did.is_crate_root() {
90+
write!(f, "BrNamed({name})")
91+
} else {
92+
write!(f, "BrNamed({did:?}, {name})")
93+
}
94+
}
95+
ty::LateParamRegionKind::ClosureEnv => write!(f, "BrEnv"),
96+
}
8197
}
8298
}
8399

0 commit comments

Comments
 (0)