Skip to content

Commit 1397a4f

Browse files
committed
Auto merge of rust-lang#130227 - amandasystems:remove-placeholders-completely, r=<try>
[WIP] Remove placeholders completely This PR does shotgun surgery on borrowck to remove all special handling of placeholders, completely replacing them with a preprocessing step that rewrites placeholder leaks into constraints, removing constraint propagation of placeholders and all logic used to detect placeholder violations during error reporting. This finishes what rust-lang#123720 started. The new method works like this: 1. during SCC construction, some information about SCC membership and reachability is retained 2. just after SCC construction, a constraint `r - (from: to_invalid) - > 'static` is added when `r` is the representative of an SCC and 1. that SCC either has had its universe shrunk because it reaches a region with a smaller one (in which case `to_invalid` is the smallest-universed region it reaches), or if it reaches a region with a too large universe that isn't part of the SCC (in which case `to_invalid` is the region with a too large universe). In either case, `from` is also `r`. 2. some region `reaches` in `r`'s SCC reaches another placeholder, `reached`, in which case the added constraint is `r -> (reaches: reached) 'static`. Through clever choice of defaults (chosing minimum elements), `reached` will be `r` if at all possible. When tracing errors for diagnostics one of these special constraints along a path are treated much like a HTTP redirect: if we are explaining `from: to` and reach an edge with `reaches: invalid` we stop the search and start following `reaches: invalid` instead. When doing this the implicit edges `x: 'static` for every region `x` are ignored, since the search would otherwise be able to cheat by going through 'static and re-find the same edge again. A bunch of optimisations are possible: - ~~Conservatively add constraints, e.g. one per SCC. May worsen error tracing!~~ - as a final pass, allow fusing the annotations for the SCC after adding the extra constraints to remove unnecessary information and save memory. This could be done cheaply since we already iterate over the entire set of SCCs. - currently, if constraints are added the entire set of SCCs are recomputed. This is of course rather wasteful, and we could do better. Especially since SCCs are added in dependency order. This would require a fully separate SCC module since the dynamic SCC combo we'd need now shares almost no properties with regular SCC computation. Given that this is meant to be a temporary work-around, that seems like too much work. There are a bunch of rather nice bonuses: - We now don't need to expose region indices in `MirTypeckRegionConstraints` to the entire crate. The only entry point is `placeholder_region()` so correctness of the indices is now guaranteed - A lot of things that were previously iterations over lists is now a single lookup - The constraint graph search functions are simple and at least one of them can now take a proper region as target rather than a predicate function. The only case that needs the predicate argument to `find_constraint_path_to()` is `find_sub_region_live_at()`, which may or may not be possible to work around. r​? nikomatsakis
2 parents 8dd5cd0 + e489ff2 commit 1397a4f

File tree

13 files changed

+472
-483
lines changed

13 files changed

+472
-483
lines changed

compiler/rustc_borrowck/src/constraints/graph.rs

+15-5
Original file line numberDiff line numberDiff line change
@@ -106,15 +106,17 @@ impl<D: ConstraintGraphDirection> ConstraintGraph<D> {
106106
}
107107

108108
/// Given a region `R`, iterate over all constraints `R: R1`.
109+
/// if `static_region` is `None`, do not yield implicit
110+
/// `'static -> a` edges.
109111
pub(crate) fn outgoing_edges<'a, 'tcx>(
110112
&'a self,
111113
region_sup: RegionVid,
112114
constraints: &'a OutlivesConstraintSet<'tcx>,
113-
static_region: RegionVid,
115+
static_region: Option<RegionVid>,
114116
) -> Edges<'a, 'tcx, D> {
115117
//if this is the `'static` region and the graph's direction is normal,
116118
//then setup the Edges iterator to return all regions #53178
117-
if region_sup == static_region && D::is_normal() {
119+
if Some(region_sup) == static_region && D::is_normal() {
118120
Edges {
119121
graph: self,
120122
constraints,
@@ -135,7 +137,7 @@ pub(crate) struct Edges<'a, 'tcx, D: ConstraintGraphDirection> {
135137
constraints: &'a OutlivesConstraintSet<'tcx>,
136138
pointer: Option<OutlivesConstraintIndex>,
137139
next_static_idx: Option<usize>,
138-
static_region: RegionVid,
140+
static_region: Option<RegionVid>,
139141
}
140142

141143
impl<'a, 'tcx, D: ConstraintGraphDirection> Iterator for Edges<'a, 'tcx, D> {
@@ -153,8 +155,12 @@ impl<'a, 'tcx, D: ConstraintGraphDirection> Iterator for Edges<'a, 'tcx, D> {
153155
Some(next_static_idx + 1)
154156
};
155157

158+
let Some(static_region) = self.static_region else {
159+
return None;
160+
};
161+
156162
Some(OutlivesConstraint {
157-
sup: self.static_region,
163+
sup: static_region,
158164
sub: next_static_idx.into(),
159165
locations: Locations::All(DUMMY_SP),
160166
span: DUMMY_SP,
@@ -194,7 +200,11 @@ impl<'a, 'tcx, D: ConstraintGraphDirection> RegionGraph<'a, 'tcx, D> {
194200
/// there exists a constraint `R: R1`.
195201
pub(crate) fn outgoing_regions(&self, region_sup: RegionVid) -> Successors<'a, 'tcx, D> {
196202
Successors {
197-
edges: self.constraint_graph.outgoing_edges(region_sup, self.set, self.static_region),
203+
edges: self.constraint_graph.outgoing_edges(
204+
region_sup,
205+
self.set,
206+
Some(self.static_region),
207+
),
198208
}
199209
}
200210
}

compiler/rustc_borrowck/src/constraints/mod.rs

+91-29
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
use std::fmt;
22
use std::ops::Index;
33

4+
use rustc_data_structures::fx::FxHashSet;
45
use rustc_index::{IndexSlice, IndexVec};
6+
use rustc_infer::infer::NllRegionVariableOrigin;
57
use rustc_middle::mir::ConstraintCategory;
68
use rustc_middle::ty::{RegionVid, TyCtxt, VarianceDiagInfo};
79
use rustc_span::Span;
@@ -69,6 +71,27 @@ impl<'tcx> OutlivesConstraintSet<'tcx> {
6971
})
7072
}
7173

74+
/// There is a placeholder violation; add a requirement
75+
/// that some SCC outlive static and explain which region
76+
/// reaching which other region caused that.
77+
fn add_placeholder_violation_constraint(
78+
&mut self,
79+
outlives_static: RegionVid,
80+
blame_from: RegionVid,
81+
blame_to: RegionVid,
82+
fr_static: RegionVid,
83+
) {
84+
self.push(OutlivesConstraint {
85+
sup: outlives_static,
86+
sub: fr_static,
87+
category: ConstraintCategory::IllegalPlaceholder(blame_from, blame_to),
88+
locations: Locations::All(rustc_span::DUMMY_SP),
89+
span: rustc_span::DUMMY_SP,
90+
variance_info: VarianceDiagInfo::None,
91+
from_closure: false,
92+
});
93+
}
94+
7295
/// This method handles Universe errors by rewriting the constraint
7396
/// graph. For each strongly connected component in the constraint
7497
/// graph such that there is a series of constraints
@@ -79,7 +102,7 @@ impl<'tcx> OutlivesConstraintSet<'tcx> {
79102
/// eventually go away.
80103
///
81104
/// For a more precise definition, see the documentation for
82-
/// [`RegionTracker::has_incompatible_universes()`].
105+
/// [`RegionTracker`] and its methods!.
83106
///
84107
/// This edge case used to be handled during constraint propagation
85108
/// by iterating over the strongly connected components in the constraint
@@ -112,44 +135,83 @@ impl<'tcx> OutlivesConstraintSet<'tcx> {
112135
let fr_static = universal_regions.fr_static;
113136
let sccs = self.compute_sccs(fr_static, definitions);
114137

115-
// Changed to `true` if we added any constraints to `self` and need to
116-
// recompute SCCs.
117-
let mut added_constraints = false;
138+
// Is this SCC already outliving static directly or transitively?
139+
let mut outlives_static = FxHashSet::default();
118140

119-
for scc in sccs.all_sccs() {
120-
// No point in adding 'static: 'static!
121-
// This micro-optimisation makes somewhat sense
122-
// because static outlives *everything*.
141+
for (scc, annotation) in sccs.all_annotations() {
123142
if scc == sccs.scc(fr_static) {
143+
// No use adding 'static: 'static.
124144
continue;
125145
}
126146

127-
let annotation = sccs.annotation(scc);
128-
129-
// If this SCC participates in a universe violation,
147+
// If this SCC participates in a universe violation
130148
// e.g. if it reaches a region with a universe smaller than
131149
// the largest region reached, add a requirement that it must
132-
// outlive `'static`.
133-
if annotation.has_incompatible_universes() {
134-
// Optimisation opportunity: this will add more constraints than
135-
// needed for correctness, since an SCC upstream of another with
136-
// a universe violation will "infect" its downstream SCCs to also
137-
// outlive static.
138-
added_constraints = true;
139-
let scc_representative_outlives_static = OutlivesConstraint {
140-
sup: annotation.representative,
141-
sub: fr_static,
142-
category: ConstraintCategory::IllegalUniverse,
143-
locations: Locations::All(rustc_span::DUMMY_SP),
144-
span: rustc_span::DUMMY_SP,
145-
variance_info: VarianceDiagInfo::None,
146-
from_closure: false,
147-
};
148-
self.push(scc_representative_outlives_static);
150+
// outlive `'static`. Here we get to know which reachable region
151+
// caused the violation.
152+
if let Some(to) = annotation.universe_violation() {
153+
outlives_static.insert(scc);
154+
self.add_placeholder_violation_constraint(
155+
annotation.representative,
156+
annotation.representative,
157+
to,
158+
fr_static,
159+
);
160+
}
161+
}
162+
163+
// Note: it's possible to sort this iterator by SCC and get dependency order,
164+
// which makes it easy to only add only one constraint per future cycle.
165+
// However, this worsens diagnostics and requires iterating over
166+
// all successors to determine if we outlive static transitively,
167+
// a cost you pay even if you have no placeholders.
168+
let placeholders_and_sccs =
169+
definitions.iter_enumerated().filter_map(|(rvid, definition)| {
170+
if matches!(definition.origin, NllRegionVariableOrigin::Placeholder { .. }) {
171+
Some((sccs.scc(rvid), rvid))
172+
} else {
173+
None
174+
}
175+
});
176+
177+
// The second kind of violation: a placeholder reaching another placeholder.
178+
for (scc, rvid) in placeholders_and_sccs {
179+
let annotation = sccs.annotation(scc);
180+
181+
if sccs.scc(fr_static) == scc || outlives_static.contains(&scc) {
182+
debug!("{:?} already outlives (or is) static", annotation.representative);
183+
continue;
149184
}
185+
186+
// Unwrap safety: since this is our SCC it must contain us, which is
187+
// at worst min AND max, but it has at least one or there is a bug.
188+
let min = annotation.min_reachable_placeholder.unwrap();
189+
let max = annotation.max_reachable_placeholder.unwrap();
190+
191+
// Good path: Nothing to see here, at least no other placeholders!
192+
if min == max {
193+
continue;
194+
}
195+
196+
// Bad path: figure out who we illegally reached.
197+
// Note that this will prefer the representative if it is a
198+
// placeholder, since the representative has the smallest index!
199+
let other_placeholder = if min != rvid { min } else { max };
200+
201+
debug!(
202+
"Placeholder {rvid:?} of SCC {scc:?} reaches other placeholder {other_placeholder:?}"
203+
);
204+
outlives_static.insert(scc);
205+
self.add_placeholder_violation_constraint(
206+
annotation.representative,
207+
rvid,
208+
other_placeholder,
209+
fr_static,
210+
);
150211
}
151212

152-
if added_constraints {
213+
if !outlives_static.is_empty() {
214+
debug!("The following SCCs had :'static constraints added: {:?}", outlives_static);
153215
// We changed the constraint set and so must recompute SCCs.
154216
self.compute_sccs(fr_static, definitions)
155217
} else {

compiler/rustc_borrowck/src/diagnostics/bound_region_errors.rs

+3-15
Original file line numberDiff line numberDiff line change
@@ -181,24 +181,12 @@ trait TypeOpInfo<'tcx> {
181181
bound: placeholder.bound,
182182
});
183183

184-
let error_region =
185-
if let RegionElement::PlaceholderRegion(error_placeholder) = error_element {
186-
let adjusted_universe =
187-
error_placeholder.universe.as_u32().checked_sub(base_universe.as_u32());
188-
adjusted_universe.map(|adjusted| {
189-
ty::Region::new_placeholder(tcx, ty::Placeholder {
190-
universe: adjusted.into(),
191-
bound: error_placeholder.bound,
192-
})
193-
})
194-
} else {
195-
None
196-
};
197-
198184
debug!(?placeholder_region);
199185

186+
// FIXME: this is obviously weird; this whole argument now does nothing and maybe
187+
// it should?
200188
let span = cause.span;
201-
let nice_error = self.nice_error(mbcx, cause, placeholder_region, error_region);
189+
let nice_error = self.nice_error(mbcx, cause, placeholder_region, None);
202190

203191
debug!(?nice_error);
204192

compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -488,7 +488,7 @@ impl<'tcx> MirBorrowckCtxt<'_, '_, 'tcx> {
488488
let (blame_constraint, extra_info) = self.regioncx.best_blame_constraint(
489489
borrow_region,
490490
NllRegionVariableOrigin::FreeRegion,
491-
|r| self.regioncx.provides_universal_region(r, borrow_region, outlived_region),
491+
outlived_region,
492492
);
493493
let BlameConstraint { category, from_closure, cause, .. } = blame_constraint;
494494

compiler/rustc_borrowck/src/diagnostics/region_errors.rs

+25-43
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ impl<'tcx> ConstraintDescription for ConstraintCategory<'tcx> {
6161
| ConstraintCategory::Boring
6262
| ConstraintCategory::BoringNoLocation
6363
| ConstraintCategory::Internal
64-
| ConstraintCategory::IllegalUniverse => "",
64+
| ConstraintCategory::IllegalPlaceholder(..) => "",
6565
}
6666
}
6767
}
@@ -206,52 +206,35 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
206206
&self,
207207
diag: &mut Diag<'_>,
208208
lower_bound: RegionVid,
209-
) {
209+
) -> Option<()> {
210210
let mut suggestions = vec![];
211211
let hir = self.infcx.tcx.hir();
212212

213-
// find generic associated types in the given region 'lower_bound'
214-
let gat_id_and_generics = self
215-
.regioncx
216-
.placeholders_contained_in(lower_bound)
217-
.map(|placeholder| {
218-
if let Some(id) = placeholder.bound.kind.get_id()
219-
&& let Some(placeholder_id) = id.as_local()
220-
&& let gat_hir_id = self.infcx.tcx.local_def_id_to_hir_id(placeholder_id)
221-
&& let Some(generics_impl) = self
222-
.infcx
223-
.tcx
224-
.parent_hir_node(self.infcx.tcx.parent_hir_id(gat_hir_id))
225-
.generics()
226-
{
227-
Some((gat_hir_id, generics_impl))
228-
} else {
229-
None
230-
}
231-
})
232-
.collect::<Vec<_>>();
233-
debug!(?gat_id_and_generics);
234-
235213
// find higher-ranked trait bounds bounded to the generic associated types
214+
let scc = self.regioncx.constraint_sccs().scc(lower_bound);
215+
let placeholder: ty::PlaceholderRegion = self.regioncx.placeholder_representative(scc)?;
216+
let placeholder_id = placeholder.bound.kind.get_id()?.as_local()?;
217+
let gat_hir_id = self.infcx.tcx.local_def_id_to_hir_id(placeholder_id);
218+
let generics_impl =
219+
self.infcx.tcx.parent_hir_node(self.infcx.tcx.parent_hir_id(gat_hir_id)).generics()?;
220+
236221
let mut hrtb_bounds = vec![];
237-
gat_id_and_generics.iter().flatten().for_each(|(gat_hir_id, generics)| {
238-
for pred in generics.predicates {
239-
let BoundPredicate(WhereBoundPredicate { bound_generic_params, bounds, .. }) = pred
240-
else {
241-
continue;
242-
};
243-
if bound_generic_params
244-
.iter()
245-
.rfind(|bgp| self.infcx.tcx.local_def_id_to_hir_id(bgp.def_id) == *gat_hir_id)
246-
.is_some()
247-
{
248-
for bound in *bounds {
249-
hrtb_bounds.push(bound);
250-
}
222+
223+
for pred in generics_impl.predicates {
224+
let BoundPredicate(WhereBoundPredicate { bound_generic_params, bounds, .. }) = pred
225+
else {
226+
continue;
227+
};
228+
if bound_generic_params
229+
.iter()
230+
.rfind(|bgp| self.infcx.tcx.local_def_id_to_hir_id(bgp.def_id) == gat_hir_id)
231+
.is_some()
232+
{
233+
for bound in *bounds {
234+
hrtb_bounds.push(bound);
251235
}
252236
}
253-
});
254-
debug!(?hrtb_bounds);
237+
}
255238

256239
hrtb_bounds.iter().for_each(|bound| {
257240
let Trait(PolyTraitRef { trait_ref, span: trait_span, .. }, _) = bound else {
@@ -300,6 +283,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
300283
Applicability::MaybeIncorrect,
301284
);
302285
}
286+
Some(())
303287
}
304288

305289
/// Produces nice borrowck error diagnostics for all the errors collected in `nll_errors`.
@@ -446,9 +430,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
446430
debug!("report_region_error(fr={:?}, outlived_fr={:?})", fr, outlived_fr);
447431

448432
let (blame_constraint, extra_info) =
449-
self.regioncx.best_blame_constraint(fr, fr_origin, |r| {
450-
self.regioncx.provides_universal_region(r, fr, outlived_fr)
451-
});
433+
self.regioncx.best_blame_constraint(fr, fr_origin, outlived_fr);
452434
let BlameConstraint { category, cause, variance_info, .. } = blame_constraint;
453435

454436
debug!("report_region_error: category={:?} {:?} {:?}", category, cause, variance_info);

compiler/rustc_borrowck/src/nll.rs

+1-4
Original file line numberDiff line numberDiff line change
@@ -122,15 +122,13 @@ pub(crate) fn compute_regions<'a, 'tcx>(
122122
// base constraints generated by the type-check.
123123
let var_origins = infcx.get_region_var_origins();
124124
let MirTypeckRegionConstraints {
125-
placeholder_indices,
126-
placeholder_index_to_region: _,
127125
liveness_constraints,
128126
mut outlives_constraints,
129127
mut member_constraints,
130128
universe_causes,
131129
type_tests,
130+
..
132131
} = constraints;
133-
let placeholder_indices = Rc::new(placeholder_indices);
134132

135133
// If requested, emit legacy polonius facts.
136134
polonius::emit_facts(
@@ -158,7 +156,6 @@ pub(crate) fn compute_regions<'a, 'tcx>(
158156
infcx,
159157
var_origins,
160158
universal_regions,
161-
placeholder_indices,
162159
universal_region_relations,
163160
outlives_constraints,
164161
member_constraints,

compiler/rustc_borrowck/src/region_infer/graphviz.rs

+3
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,9 @@ use rustc_middle::ty::UniverseIndex;
1212
use super::*;
1313

1414
fn render_outlives_constraint(constraint: &OutlivesConstraint<'_>) -> String {
15+
if let ConstraintCategory::IllegalPlaceholder(from, to) = constraint.category {
16+
return format!("b/c {from:?}: {to:?}");
17+
}
1518
match constraint.locations {
1619
Locations::All(_) => "All(...)".to_string(),
1720
Locations::Single(loc) => format!("{loc:?}"),

0 commit comments

Comments
 (0)