rustc_borrowck/
handle_placeholders.rs

1//! Logic for lowering higher-kinded outlives constraints
2//! (with placeholders and universes) and turn them into regular
3//! outlives constraints.
4
5use rustc_data_structures::frozen::Frozen;
6use rustc_data_structures::fx::FxIndexMap;
7use rustc_data_structures::graph::scc;
8use rustc_data_structures::graph::scc::Sccs;
9use rustc_index::IndexVec;
10use rustc_infer::infer::RegionVariableOrigin;
11use rustc_middle::mir::ConstraintCategory;
12use rustc_middle::ty::{RegionVid, UniverseIndex};
13use tracing::debug;
14
15use crate::constraints::{ConstraintSccIndex, OutlivesConstraintSet};
16use crate::consumers::OutlivesConstraint;
17use crate::diagnostics::UniverseInfo;
18use crate::member_constraints::MemberConstraintSet;
19use crate::region_infer::values::{LivenessValues, PlaceholderIndices};
20use crate::region_infer::{ConstraintSccs, RegionDefinition, Representative, TypeTest};
21use crate::ty::VarianceDiagInfo;
22use crate::type_check::free_region_relations::UniversalRegionRelations;
23use crate::type_check::{Locations, MirTypeckRegionConstraints};
24use crate::universal_regions::UniversalRegions;
25use crate::{BorrowckInferCtxt, NllRegionVariableOrigin};
26
27/// A set of outlives constraints after rewriting to remove
28/// higher-kinded constraints.
29pub(crate) struct LoweredConstraints<'tcx> {
30    pub(crate) constraint_sccs: Sccs<RegionVid, ConstraintSccIndex>,
31    pub(crate) definitions: Frozen<IndexVec<RegionVid, RegionDefinition<'tcx>>>,
32    pub(crate) scc_annotations: IndexVec<ConstraintSccIndex, RegionTracker>,
33    pub(crate) member_constraints: MemberConstraintSet<'tcx, RegionVid>,
34    pub(crate) outlives_constraints: Frozen<OutlivesConstraintSet<'tcx>>,
35    pub(crate) type_tests: Vec<TypeTest<'tcx>>,
36    pub(crate) liveness_constraints: LivenessValues,
37    pub(crate) universe_causes: FxIndexMap<UniverseIndex, UniverseInfo<'tcx>>,
38    pub(crate) placeholder_indices: PlaceholderIndices,
39}
40
41impl<'d, 'tcx, A: scc::Annotation> SccAnnotations<'d, 'tcx, A> {
42    pub(crate) fn init(definitions: &'d IndexVec<RegionVid, RegionDefinition<'tcx>>) -> Self {
43        Self { scc_to_annotation: IndexVec::new(), definitions }
44    }
45}
46
47/// A Visitor for SCC annotation construction.
48pub(crate) struct SccAnnotations<'d, 'tcx, A: scc::Annotation> {
49    pub(crate) scc_to_annotation: IndexVec<ConstraintSccIndex, A>,
50    definitions: &'d IndexVec<RegionVid, RegionDefinition<'tcx>>,
51}
52
53impl scc::Annotations<RegionVid> for SccAnnotations<'_, '_, RegionTracker> {
54    fn new(&self, element: RegionVid) -> RegionTracker {
55        RegionTracker::new(element, &self.definitions[element])
56    }
57
58    fn annotate_scc(&mut self, scc: ConstraintSccIndex, annotation: RegionTracker) {
59        let idx = self.scc_to_annotation.push(annotation);
60        assert!(idx == scc);
61    }
62
63    type Ann = RegionTracker;
64    type SccIdx = ConstraintSccIndex;
65}
66
67/// An annotation for region graph SCCs that tracks
68/// the values of its elements. This annotates a single SCC.
69#[derive(Copy, Debug, Clone)]
70pub(crate) struct RegionTracker {
71    /// The largest universe of a placeholder reached from this SCC.
72    /// This includes placeholders within this SCC.
73    max_placeholder_universe_reached: UniverseIndex,
74
75    /// The largest universe nameable from this SCC.
76    /// It is the smallest nameable universes of all
77    /// existential regions reachable from it.
78    max_nameable_universe: UniverseIndex,
79
80    /// The representative Region Variable Id for this SCC.
81    pub(crate) representative: Representative,
82}
83
84impl RegionTracker {
85    pub(crate) fn new(rvid: RegionVid, definition: &RegionDefinition<'_>) -> Self {
86        let placeholder_universe =
87            if matches!(definition.origin, NllRegionVariableOrigin::Placeholder(_)) {
88                definition.universe
89            } else {
90                UniverseIndex::ROOT
91            };
92
93        Self {
94            max_placeholder_universe_reached: placeholder_universe,
95            max_nameable_universe: definition.universe,
96            representative: Representative::new(rvid, definition),
97        }
98    }
99
100    /// The largest universe this SCC can name. It's the smallest
101    /// largest nameable uninverse of any reachable region.
102    pub(crate) fn max_nameable_universe(self) -> UniverseIndex {
103        self.max_nameable_universe
104    }
105
106    pub(crate) fn max_placeholder_universe_reached(self) -> UniverseIndex {
107        self.max_placeholder_universe_reached
108    }
109
110    fn merge_min_max_seen(&mut self, other: &Self) {
111        self.max_placeholder_universe_reached = std::cmp::max(
112            self.max_placeholder_universe_reached,
113            other.max_placeholder_universe_reached,
114        );
115
116        self.max_nameable_universe =
117            std::cmp::min(self.max_nameable_universe, other.max_nameable_universe);
118    }
119
120    /// Returns `true` if during the annotated SCC reaches a placeholder
121    /// with a universe larger than the smallest nameable universe of any
122    /// reachable existential region.
123    pub(crate) fn has_incompatible_universes(&self) -> bool {
124        self.max_nameable_universe().cannot_name(self.max_placeholder_universe_reached)
125    }
126
127    /// Determine if the tracked universes of the two SCCs are compatible.
128    pub(crate) fn universe_compatible_with(&self, other: Self) -> bool {
129        self.max_nameable_universe().can_name(other.max_nameable_universe())
130            || self.max_nameable_universe().can_name(other.max_placeholder_universe_reached)
131    }
132}
133
134impl scc::Annotation for RegionTracker {
135    fn merge_scc(mut self, other: Self) -> Self {
136        self.representative = self.representative.merge_scc(other.representative);
137        self.merge_min_max_seen(&other);
138        self
139    }
140
141    fn merge_reached(mut self, other: Self) -> Self {
142        // No update to in-component values, only add seen values.
143        self.merge_min_max_seen(&other);
144        self
145    }
146}
147
148/// Determines if the region variable definitions contain
149/// placeholders, and compute them for later use.
150fn region_definitions<'tcx>(
151    universal_regions: &UniversalRegions<'tcx>,
152    infcx: &BorrowckInferCtxt<'tcx>,
153) -> (Frozen<IndexVec<RegionVid, RegionDefinition<'tcx>>>, bool) {
154    let var_infos = infcx.get_region_var_infos();
155    // Create a RegionDefinition for each inference variable. This happens here because
156    // it allows us to sneak in a cheap check for placeholders. Otherwise, its proper home
157    // is in `RegionInferenceContext::new()`, probably.
158    let mut definitions = IndexVec::with_capacity(var_infos.len());
159    let mut has_placeholders = false;
160
161    for info in var_infos.iter() {
162        let origin = match info.origin {
163            RegionVariableOrigin::Nll(origin) => origin,
164            _ => NllRegionVariableOrigin::Existential { name: None },
165        };
166
167        let definition = RegionDefinition { origin, universe: info.universe, external_name: None };
168
169        has_placeholders |= matches!(origin, NllRegionVariableOrigin::Placeholder(_));
170        definitions.push(definition);
171    }
172
173    // Add external names from universal regions in fun function definitions.
174    // FIXME: this two-step method is annoying, but I don't know how to avoid it.
175    for (external_name, variable) in universal_regions.named_universal_regions_iter() {
176        debug!("region {:?} has external name {:?}", variable, external_name);
177        definitions[variable].external_name = Some(external_name);
178    }
179    (Frozen::freeze(definitions), has_placeholders)
180}
181
182/// This method handles placeholders by rewriting the constraint
183/// graph. For each strongly connected component in the constraint
184/// graph such that there is a series of constraints
185///    A: B: C: ... : X  where
186/// A contains a placeholder whose universe cannot be named by X,
187/// add a constraint that A: 'static. This is a safe upper bound
188/// in the face of borrow checker/trait solver limitations that will
189/// eventually go away.
190///
191/// For a more precise definition, see the documentation for
192/// [`RegionTracker`] and its methods!
193///
194/// This edge case used to be handled during constraint propagation.
195/// It was rewritten as part of the Polonius project with the goal of moving
196/// higher-kindedness concerns out of the path of the borrow checker,
197/// for two reasons:
198///
199/// 1. Implementing Polonius is difficult enough without also
200///     handling them.
201/// 2. The long-term goal is to handle higher-kinded concerns
202///     in the trait solver, where they belong. This avoids
203///     logic duplication and allows future trait solvers
204///     to compute better bounds than for example our
205///     "must outlive 'static" here.
206///
207/// This code is a stop-gap measure in preparation for the future trait solver.
208///
209/// Every constraint added by this method is an internal `IllegalUniverse` constraint.
210pub(crate) fn compute_sccs_applying_placeholder_outlives_constraints<'tcx>(
211    constraints: MirTypeckRegionConstraints<'tcx>,
212    universal_region_relations: &Frozen<UniversalRegionRelations<'tcx>>,
213    infcx: &BorrowckInferCtxt<'tcx>,
214) -> LoweredConstraints<'tcx> {
215    let universal_regions = &universal_region_relations.universal_regions;
216    let (definitions, has_placeholders) = region_definitions(universal_regions, infcx);
217
218    let MirTypeckRegionConstraints {
219        placeholder_indices,
220        placeholder_index_to_region: _,
221        liveness_constraints,
222        mut outlives_constraints,
223        member_constraints,
224        universe_causes,
225        type_tests,
226    } = constraints;
227
228    let fr_static = universal_regions.fr_static;
229    let compute_sccs =
230        |constraints: &OutlivesConstraintSet<'tcx>,
231         annotations: &mut SccAnnotations<'_, 'tcx, RegionTracker>| {
232            ConstraintSccs::new_with_annotation(
233                &constraints.graph(definitions.len()).region_graph(constraints, fr_static),
234                annotations,
235            )
236        };
237
238    let mut scc_annotations = SccAnnotations::init(&definitions);
239    let constraint_sccs = compute_sccs(&outlives_constraints, &mut scc_annotations);
240
241    // This code structure is a bit convoluted because it allows for a planned
242    // future change where the early return here has a different type of annotation
243    // that does much less work.
244    if !has_placeholders {
245        debug!("No placeholder regions found; skipping rewriting logic!");
246
247        return LoweredConstraints {
248            type_tests,
249            member_constraints,
250            constraint_sccs,
251            scc_annotations: scc_annotations.scc_to_annotation,
252            definitions,
253            outlives_constraints: Frozen::freeze(outlives_constraints),
254            liveness_constraints,
255            universe_causes,
256            placeholder_indices,
257        };
258    }
259    debug!("Placeholders present; activating placeholder handling logic!");
260
261    let added_constraints = rewrite_placeholder_outlives(
262        &constraint_sccs,
263        &scc_annotations,
264        fr_static,
265        &mut outlives_constraints,
266    );
267
268    let (constraint_sccs, scc_annotations) = if added_constraints {
269        let mut annotations = SccAnnotations::init(&definitions);
270
271        // We changed the constraint set and so must recompute SCCs.
272        // Optimisation opportunity: if we can add them incrementally (and that's
273        // possible because edges to 'static always only merge SCCs into 'static),
274        // we would potentially save a lot of work here.
275        (compute_sccs(&outlives_constraints, &mut annotations), annotations.scc_to_annotation)
276    } else {
277        // If we didn't add any back-edges; no more work needs doing
278        debug!("No constraints rewritten!");
279        (constraint_sccs, scc_annotations.scc_to_annotation)
280    };
281
282    LoweredConstraints {
283        constraint_sccs,
284        definitions,
285        scc_annotations,
286        member_constraints,
287        outlives_constraints: Frozen::freeze(outlives_constraints),
288        type_tests,
289        liveness_constraints,
290        universe_causes,
291        placeholder_indices,
292    }
293}
294
295fn rewrite_placeholder_outlives<'tcx>(
296    sccs: &Sccs<RegionVid, ConstraintSccIndex>,
297    annotations: &SccAnnotations<'_, '_, RegionTracker>,
298    fr_static: RegionVid,
299    outlives_constraints: &mut OutlivesConstraintSet<'tcx>,
300) -> bool {
301    // Changed to `true` if we added any constraints and need to
302    // recompute SCCs.
303    let mut added_constraints = false;
304
305    let annotations = &annotations.scc_to_annotation;
306
307    for scc in sccs.all_sccs() {
308        // No point in adding 'static: 'static!
309        // This micro-optimisation makes somewhat sense
310        // because static outlives *everything*.
311        if scc == sccs.scc(fr_static) {
312            continue;
313        }
314
315        let annotation = annotations[scc];
316
317        // If this SCC participates in a universe violation,
318        // e.g. if it reaches a region with a universe smaller than
319        // the largest region reached, add a requirement that it must
320        // outlive `'static`.
321        if annotation.has_incompatible_universes() {
322            // Optimisation opportunity: this will add more constraints than
323            // needed for correctness, since an SCC upstream of another with
324            // a universe violation will "infect" its downstream SCCs to also
325            // outlive static.
326            let scc_representative_outlives_static = OutlivesConstraint {
327                sup: annotation.representative.rvid(),
328                sub: fr_static,
329                category: ConstraintCategory::IllegalUniverse,
330                locations: Locations::All(rustc_span::DUMMY_SP),
331                span: rustc_span::DUMMY_SP,
332                variance_info: VarianceDiagInfo::None,
333                from_closure: false,
334            };
335            outlives_constraints.push(scc_representative_outlives_static);
336            added_constraints = true;
337            debug!("Added {:?}: 'static!", annotation.representative.rvid());
338        }
339    }
340    added_constraints
341}