rustc_borrowck/type_check/
free_region_relations.rs1use rustc_data_structures::frozen::Frozen;
2use rustc_data_structures::transitive_relation::{TransitiveRelation, TransitiveRelationBuilder};
3use rustc_hir::def::DefKind;
4use rustc_infer::infer::canonical::QueryRegionConstraints;
5use rustc_infer::infer::outlives;
6use rustc_infer::infer::outlives::env::RegionBoundPairs;
7use rustc_infer::infer::region_constraints::GenericKind;
8use rustc_infer::traits::query::type_op::DeeplyNormalize;
9use rustc_middle::mir::ConstraintCategory;
10use rustc_middle::traits::query::OutlivesBound;
11use rustc_middle::ty::{self, RegionVid, Ty, TypeVisitableExt};
12use rustc_span::{ErrorGuaranteed, Span};
13use rustc_trait_selection::traits::query::type_op::{self, TypeOp};
14use tracing::{debug, instrument};
15use type_op::TypeOpOutput;
16
17use crate::BorrowckInferCtxt;
18use crate::type_check::{Locations, MirTypeckRegionConstraints, constraint_conversion};
19use crate::universal_regions::UniversalRegions;
20
21#[derive(Debug)]
22#[derive(Clone)] pub(crate) struct UniversalRegionRelations<'tcx> {
24 pub(crate) universal_regions: UniversalRegions<'tcx>,
25
26 outlives: TransitiveRelation<RegionVid>,
30
31 inverse_outlives: TransitiveRelation<RegionVid>,
36}
37
38type NormalizedInputsAndOutput<'tcx> = Vec<Ty<'tcx>>;
43
44pub(crate) struct CreateResult<'tcx> {
45 pub(crate) universal_region_relations: Frozen<UniversalRegionRelations<'tcx>>,
46 pub(crate) region_bound_pairs: Frozen<RegionBoundPairs<'tcx>>,
47 pub(crate) known_type_outlives_obligations: Frozen<Vec<ty::PolyTypeOutlivesPredicate<'tcx>>>,
48 pub(crate) normalized_inputs_and_output: NormalizedInputsAndOutput<'tcx>,
49}
50
51pub(crate) fn create<'tcx>(
52 infcx: &BorrowckInferCtxt<'tcx>,
53 universal_regions: UniversalRegions<'tcx>,
54 constraints: &mut MirTypeckRegionConstraints<'tcx>,
55) -> CreateResult<'tcx> {
56 UniversalRegionRelationsBuilder {
57 infcx,
58 constraints,
59 universal_regions,
60 region_bound_pairs: Default::default(),
61 outlives: Default::default(),
62 inverse_outlives: Default::default(),
63 }
64 .create()
65}
66
67impl UniversalRegionRelations<'_> {
68 pub(crate) fn postdom_upper_bound(&self, fr1: RegionVid, fr2: RegionVid) -> RegionVid {
74 assert!(self.universal_regions.is_universal_region(fr1));
75 assert!(self.universal_regions.is_universal_region(fr2));
76 self.inverse_outlives
77 .postdom_upper_bound(fr1, fr2)
78 .unwrap_or(self.universal_regions.fr_static)
79 }
80
81 pub(crate) fn non_local_upper_bounds(&self, fr: RegionVid) -> Vec<RegionVid> {
87 debug!("non_local_upper_bound(fr={:?})", fr);
88 let res = self.non_local_bounds(&self.inverse_outlives, fr);
89 assert!(!res.is_empty(), "can't find an upper bound!?");
90 res
91 }
92
93 pub(crate) fn non_local_lower_bounds(&self, fr: RegionVid) -> Vec<RegionVid> {
99 debug!("non_local_lower_bound(fr={:?})", fr);
100 self.non_local_bounds(&self.outlives, fr)
101 }
102
103 fn non_local_bounds(
107 &self,
108 relation: &TransitiveRelation<RegionVid>,
109 fr0: RegionVid,
110 ) -> Vec<RegionVid> {
111 assert!(self.universal_regions.is_universal_region(fr0));
114
115 let mut external_parents = vec![];
116
117 let mut queue = vec![relation.minimal_scc_representative(fr0)];
118
119 while let Some(fr) = queue.pop() {
122 if !self.universal_regions.is_local_free_region(fr) {
123 external_parents.push(fr);
124 continue;
125 }
126
127 queue.extend(relation.parents(fr));
128 }
129
130 debug!("non_local_bound: external_parents={:?}", external_parents);
131
132 external_parents
133 }
134
135 pub(crate) fn outlives(&self, fr1: RegionVid, fr2: RegionVid) -> bool {
139 self.outlives.contains(fr1, fr2)
140 }
141
142 pub(crate) fn equal(&self, fr1: RegionVid, fr2: RegionVid) -> bool {
146 self.outlives.contains(fr1, fr2) && self.outlives.contains(fr2, fr1)
147 }
148
149 pub(crate) fn regions_outlived_by(&self, fr1: RegionVid) -> Vec<RegionVid> {
152 self.outlives.reachable_from(fr1)
153 }
154
155 pub(crate) fn known_outlives(&self) -> impl Iterator<Item = (RegionVid, RegionVid)> {
157 self.outlives.base_edges()
158 }
159}
160
161struct UniversalRegionRelationsBuilder<'a, 'tcx> {
162 infcx: &'a BorrowckInferCtxt<'tcx>,
163 universal_regions: UniversalRegions<'tcx>,
164 constraints: &'a mut MirTypeckRegionConstraints<'tcx>,
165
166 outlives: TransitiveRelationBuilder<RegionVid>,
168 inverse_outlives: TransitiveRelationBuilder<RegionVid>,
169 region_bound_pairs: RegionBoundPairs<'tcx>,
170}
171
172impl<'tcx> UniversalRegionRelationsBuilder<'_, 'tcx> {
173 fn relate_universal_regions(&mut self, fr_a: RegionVid, fr_b: RegionVid) {
176 debug!("relate_universal_regions: fr_a={:?} outlives fr_b={:?}", fr_a, fr_b);
177 self.outlives.add(fr_a, fr_b);
178 self.inverse_outlives.add(fr_b, fr_a);
179 }
180
181 #[instrument(level = "debug", skip(self))]
182 pub(crate) fn create(mut self) -> CreateResult<'tcx> {
183 let tcx = self.infcx.tcx;
184 let defining_ty_def_id = self.universal_regions.defining_ty.def_id().expect_local();
185 let span = tcx.def_span(defining_ty_def_id);
186
187 let param_env = self.infcx.param_env;
190 self.add_outlives_bounds(outlives::explicit_outlives_bounds(param_env));
191
192 let fr_static = self.universal_regions.fr_static;
197 let fr_fn_body = self.universal_regions.fr_fn_body;
198 for fr in self.universal_regions.universal_regions_iter() {
199 debug!("build: relating free region {:?} to itself and to 'static", fr);
200 self.relate_universal_regions(fr, fr);
201 self.relate_universal_regions(fr_static, fr);
202 self.relate_universal_regions(fr, fr_fn_body);
203 }
204
205 let mut constraints = vec![];
207 let mut known_type_outlives_obligations = vec![];
208 for bound in param_env.caller_bounds() {
209 if let Some(outlives) = bound.as_type_outlives_clause() {
210 self.normalize_and_push_type_outlives_obligation(
211 outlives,
212 span,
213 &mut known_type_outlives_obligations,
214 &mut constraints,
215 );
216 };
217 }
218
219 let unnormalized_input_output_tys = self
220 .universal_regions
221 .unnormalized_input_tys
222 .iter()
223 .cloned()
224 .chain(Some(self.universal_regions.unnormalized_output_ty));
225
226 let mut normalized_inputs_and_output =
235 Vec::with_capacity(self.universal_regions.unnormalized_input_tys.len() + 1);
236 for ty in unnormalized_input_output_tys {
237 debug!("build: input_or_output={:?}", ty);
238 let constraints_unnorm = self.add_implied_bounds(ty, span);
241 if let Some(c) = constraints_unnorm {
242 constraints.push(c)
243 }
244 let TypeOpOutput { output: norm_ty, constraints: constraints_normalize, .. } =
245 param_env
246 .and(DeeplyNormalize { value: ty })
247 .fully_perform(self.infcx, self.infcx.root_def_id, span)
248 .unwrap_or_else(|guar| TypeOpOutput {
249 output: Ty::new_error(self.infcx.tcx, guar),
250 constraints: None,
251 error_info: None,
252 });
253 if let Some(c) = constraints_normalize {
254 constraints.push(c)
255 }
256
257 if ty != norm_ty {
270 let constraints_norm = self.add_implied_bounds(norm_ty, span);
271 if let Some(c) = constraints_norm {
272 constraints.push(c)
273 }
274 }
275
276 normalized_inputs_and_output.push(norm_ty);
277 }
278
279 if matches!(tcx.def_kind(defining_ty_def_id), DefKind::AssocFn | DefKind::AssocConst) {
281 for &(ty, _) in tcx.assumed_wf_types(tcx.local_parent(defining_ty_def_id)) {
282 let result: Result<_, ErrorGuaranteed> = param_env
283 .and(DeeplyNormalize { value: ty })
284 .fully_perform(self.infcx, self.infcx.root_def_id, span);
285 let Ok(TypeOpOutput { output: norm_ty, constraints: c, .. }) = result else {
286 continue;
287 };
288
289 constraints.extend(c);
290
291 let c = self.add_implied_bounds(norm_ty, span);
294 constraints.extend(c);
295 }
296 }
297
298 for c in constraints {
299 constraint_conversion::ConstraintConversion::new(
300 self.infcx,
301 &self.universal_regions,
302 &self.region_bound_pairs,
303 &known_type_outlives_obligations,
304 Locations::All(span),
305 span,
306 ConstraintCategory::Internal,
307 self.constraints,
308 )
309 .convert_all(c);
310 }
311
312 CreateResult {
313 universal_region_relations: Frozen::freeze(UniversalRegionRelations {
314 universal_regions: self.universal_regions,
315 outlives: self.outlives.freeze(),
316 inverse_outlives: self.inverse_outlives.freeze(),
317 }),
318 known_type_outlives_obligations: Frozen::freeze(known_type_outlives_obligations),
319 region_bound_pairs: Frozen::freeze(self.region_bound_pairs),
320 normalized_inputs_and_output,
321 }
322 }
323
324 fn normalize_and_push_type_outlives_obligation(
325 &self,
326 mut outlives: ty::PolyTypeOutlivesPredicate<'tcx>,
327 span: Span,
328 known_type_outlives_obligations: &mut Vec<ty::PolyTypeOutlivesPredicate<'tcx>>,
329 constraints: &mut Vec<&QueryRegionConstraints<'tcx>>,
330 ) {
331 if self.infcx.next_trait_solver() {
333 let Ok(TypeOpOutput {
334 output: normalized_outlives,
335 constraints: constraints_normalize,
336 error_info: _,
337 }) = self.infcx.param_env.and(DeeplyNormalize { value: outlives }).fully_perform(
338 self.infcx,
339 self.infcx.root_def_id,
340 span,
341 )
342 else {
343 self.infcx.dcx().delayed_bug(format!("could not normalize {outlives:?}"));
344 return;
345 };
346 outlives = normalized_outlives;
347 if let Some(c) = constraints_normalize {
348 constraints.push(c);
349 }
350 }
351
352 known_type_outlives_obligations.push(outlives);
353 }
354
355 #[instrument(level = "debug", skip(self))]
360 fn add_implied_bounds(
361 &mut self,
362 ty: Ty<'tcx>,
363 span: Span,
364 ) -> Option<&'tcx QueryRegionConstraints<'tcx>> {
365 let TypeOpOutput { output: bounds, constraints, .. } = self
366 .infcx
367 .param_env
368 .and(type_op::ImpliedOutlivesBounds { ty })
369 .fully_perform(self.infcx, self.infcx.root_def_id, span)
370 .map_err(|_: ErrorGuaranteed| debug!("failed to compute implied bounds {:?}", ty))
371 .ok()?;
372 debug!(?bounds, ?constraints);
373 let bounds = bounds.into_iter().filter(|bound| !bound.has_placeholders());
376 self.add_outlives_bounds(bounds);
377 constraints
378 }
379
380 fn add_outlives_bounds<I>(&mut self, outlives_bounds: I)
384 where
385 I: IntoIterator<Item = OutlivesBound<'tcx>>,
386 {
387 for outlives_bound in outlives_bounds {
388 debug!("add_outlives_bounds(bound={:?})", outlives_bound);
389
390 match outlives_bound {
391 OutlivesBound::RegionSubRegion(r1, r2) => {
392 let r1 = self.universal_regions.to_region_vid(r1);
394 let r2 = self.universal_regions.to_region_vid(r2);
395 self.relate_universal_regions(r2, r1);
396 }
397
398 OutlivesBound::RegionSubParam(r_a, param_b) => {
399 self.region_bound_pairs
400 .insert(ty::OutlivesPredicate(GenericKind::Param(param_b), r_a));
401 }
402
403 OutlivesBound::RegionSubAlias(r_a, alias_b) => {
404 self.region_bound_pairs
405 .insert(ty::OutlivesPredicate(GenericKind::Alias(alias_b), r_a));
406 }
407 }
408 }
409 }
410}