rustc_hir_analysis/outlives/implicit_infer.rs
1use rustc_data_structures::fx::FxIndexMap;
2use rustc_hir::def::DefKind;
3use rustc_hir::def_id::DefId;
4use rustc_middle::ty::{self, GenericArg, GenericArgKind, Ty, TyCtxt};
5use rustc_span::Span;
6use tracing::debug;
7
8use super::explicit::ExplicitPredicatesMap;
9use super::utils::*;
10
11/// Infer predicates for the items in the crate.
12///
13/// `global_inferred_outlives`: this is initially the empty map that
14/// was generated by walking the items in the crate. This will
15/// now be filled with inferred predicates.
16pub(super) fn infer_predicates(
17 tcx: TyCtxt<'_>,
18) -> FxIndexMap<DefId, ty::EarlyBinder<'_, RequiredPredicates<'_>>> {
19 debug!("infer_predicates");
20
21 let mut explicit_map = ExplicitPredicatesMap::new();
22
23 let mut global_inferred_outlives = FxIndexMap::default();
24
25 // If new predicates were added then we need to re-calculate
26 // all crates since there could be new implied predicates.
27 for i in 0.. {
28 let mut predicates_added = vec![];
29
30 // Visit all the crates and infer predicates
31 for id in tcx.hir_free_items() {
32 let item_did = id.owner_id;
33
34 debug!("InferVisitor::visit_item(item={:?})", item_did);
35
36 let mut item_required_predicates = RequiredPredicates::default();
37 match tcx.def_kind(item_did) {
38 DefKind::Union | DefKind::Enum | DefKind::Struct => {
39 let adt_def = tcx.adt_def(item_did.to_def_id());
40
41 // Iterate over all fields in item_did
42 for field_def in adt_def.all_fields() {
43 // Calculating the predicate requirements necessary
44 // for item_did.
45 //
46 // For field of type &'a T (reference) or Adt
47 // (struct/enum/union) there will be outlive
48 // requirements for adt_def.
49 let field_ty = tcx.type_of(field_def.did).instantiate_identity();
50 let field_span = tcx.def_span(field_def.did);
51 insert_required_predicates_to_be_wf(
52 tcx,
53 field_ty,
54 field_span,
55 &global_inferred_outlives,
56 &mut item_required_predicates,
57 &mut explicit_map,
58 );
59 }
60 }
61
62 DefKind::TyAlias if tcx.type_alias_is_lazy(item_did) => {
63 insert_required_predicates_to_be_wf(
64 tcx,
65 tcx.type_of(item_did).instantiate_identity(),
66 tcx.def_span(item_did),
67 &global_inferred_outlives,
68 &mut item_required_predicates,
69 &mut explicit_map,
70 );
71 }
72
73 _ => {}
74 };
75
76 // If new predicates were added (`local_predicate_map` has more
77 // predicates than the `global_inferred_outlives`), the new predicates
78 // might result in implied predicates for their parent types.
79 // Therefore mark `predicates_added` as true and which will ensure
80 // we walk the crates again and re-calculate predicates for all
81 // items.
82 let item_predicates_len: usize = global_inferred_outlives
83 .get(&item_did.to_def_id())
84 .map_or(0, |p| p.as_ref().skip_binder().len());
85 if item_required_predicates.len() > item_predicates_len {
86 predicates_added.push(item_did);
87 global_inferred_outlives
88 .insert(item_did.to_def_id(), ty::EarlyBinder::bind(item_required_predicates));
89 }
90 }
91
92 if predicates_added.is_empty() {
93 // We've reached a fixed point.
94 break;
95 } else if !tcx.recursion_limit().value_within_limit(i) {
96 let msg = if let &[id] = &predicates_added[..] {
97 format!("overflow computing implied lifetime bounds for `{}`", tcx.def_path_str(id),)
98 } else {
99 "overflow computing implied lifetime bounds".to_string()
100 };
101 tcx.dcx()
102 .struct_span_fatal(
103 predicates_added.iter().map(|id| tcx.def_span(*id)).collect::<Vec<_>>(),
104 msg,
105 )
106 .emit();
107 }
108 }
109
110 global_inferred_outlives
111}
112
113fn insert_required_predicates_to_be_wf<'tcx>(
114 tcx: TyCtxt<'tcx>,
115 ty: Ty<'tcx>,
116 span: Span,
117 global_inferred_outlives: &FxIndexMap<DefId, ty::EarlyBinder<'tcx, RequiredPredicates<'tcx>>>,
118 required_predicates: &mut RequiredPredicates<'tcx>,
119 explicit_map: &mut ExplicitPredicatesMap<'tcx>,
120) {
121 for arg in ty.walk() {
122 let leaf_ty = match arg.unpack() {
123 GenericArgKind::Type(ty) => ty,
124
125 // No predicates from lifetimes or constants, except potentially
126 // constants' types, but `walk` will get to them as well.
127 GenericArgKind::Lifetime(_) | GenericArgKind::Const(_) => continue,
128 };
129
130 match *leaf_ty.kind() {
131 ty::Ref(region, rty, _) => {
132 // The type is `&'a T` which means that we will have
133 // a predicate requirement of `T: 'a` (`T` outlives `'a`).
134 //
135 // We also want to calculate potential predicates for the `T`.
136 debug!("Ref");
137 insert_outlives_predicate(tcx, rty.into(), region, span, required_predicates);
138 }
139
140 ty::Adt(def, args) => {
141 // For ADTs (structs/enums/unions), we check inferred and explicit predicates.
142 debug!("Adt");
143 check_inferred_predicates(
144 tcx,
145 def.did(),
146 args,
147 global_inferred_outlives,
148 required_predicates,
149 );
150 check_explicit_predicates(
151 tcx,
152 def.did(),
153 args,
154 required_predicates,
155 explicit_map,
156 None,
157 );
158 }
159
160 ty::Alias(ty::Free, alias) => {
161 // This corresponds to a type like `Type<'a, T>`.
162 // We check inferred and explicit predicates.
163 debug!("Free");
164 check_inferred_predicates(
165 tcx,
166 alias.def_id,
167 alias.args,
168 global_inferred_outlives,
169 required_predicates,
170 );
171 check_explicit_predicates(
172 tcx,
173 alias.def_id,
174 alias.args,
175 required_predicates,
176 explicit_map,
177 None,
178 );
179 }
180
181 ty::Dynamic(obj, ..) => {
182 // This corresponds to `dyn Trait<..>`. In this case, we should
183 // use the explicit predicates as well.
184 debug!("Dynamic");
185 if let Some(ex_trait_ref) = obj.principal() {
186 // Here, we are passing the type `usize` as a
187 // placeholder value with the function
188 // `with_self_ty`, since there is no concrete type
189 // `Self` for a `dyn Trait` at this
190 // stage. Therefore when checking explicit
191 // predicates in `check_explicit_predicates` we
192 // need to ignore checking the explicit_map for
193 // Self type.
194 let args = ex_trait_ref.with_self_ty(tcx, tcx.types.usize).skip_binder().args;
195 check_explicit_predicates(
196 tcx,
197 ex_trait_ref.skip_binder().def_id,
198 args,
199 required_predicates,
200 explicit_map,
201 Some(tcx.types.self_param),
202 );
203 }
204 }
205
206 ty::Alias(ty::Projection, alias) => {
207 // This corresponds to a type like `<() as Trait<'a, T>>::Type`.
208 // We only use the explicit predicates of the trait but
209 // not the ones of the associated type itself.
210 debug!("Projection");
211 check_explicit_predicates(
212 tcx,
213 tcx.parent(alias.def_id),
214 alias.args,
215 required_predicates,
216 explicit_map,
217 None,
218 );
219 }
220
221 // FIXME(inherent_associated_types): Use the explicit predicates from the parent impl.
222 ty::Alias(ty::Inherent, _) => {}
223
224 _ => {}
225 }
226 }
227}
228
229/// Check the explicit predicates declared on the type.
230///
231/// ### Example
232///
233/// ```ignore (illustrative)
234/// struct Outer<'a, T> {
235/// field: Inner<T>,
236/// }
237///
238/// struct Inner<U> where U: 'static, U: Outer {
239/// // ...
240/// }
241/// ```
242/// Here, we should fetch the explicit predicates, which
243/// will give us `U: 'static` and `U: Outer`. The latter we
244/// can ignore, but we will want to process `U: 'static`,
245/// applying the instantiation as above.
246fn check_explicit_predicates<'tcx>(
247 tcx: TyCtxt<'tcx>,
248 def_id: DefId,
249 args: &[GenericArg<'tcx>],
250 required_predicates: &mut RequiredPredicates<'tcx>,
251 explicit_map: &mut ExplicitPredicatesMap<'tcx>,
252 ignored_self_ty: Option<Ty<'tcx>>,
253) {
254 debug!(
255 "check_explicit_predicates(def_id={:?}, \
256 args={:?}, \
257 explicit_map={:?}, \
258 required_predicates={:?}, \
259 ignored_self_ty={:?})",
260 def_id, args, explicit_map, required_predicates, ignored_self_ty,
261 );
262 let explicit_predicates = explicit_map.explicit_predicates_of(tcx, def_id);
263
264 for (outlives_predicate, &span) in explicit_predicates.as_ref().skip_binder() {
265 debug!("outlives_predicate = {outlives_predicate:?}");
266
267 // Careful: If we are inferring the effects of a `dyn Trait<..>`
268 // type, then when we look up the predicates for `Trait`,
269 // we may find some that reference `Self`. e.g., perhaps the
270 // definition of `Trait` was:
271 //
272 // ```
273 // trait Trait<'a, T> where Self: 'a { .. }
274 // ```
275 //
276 // we want to ignore such predicates here, because
277 // there is no type parameter for them to affect. Consider
278 // a struct containing `dyn Trait`:
279 //
280 // ```
281 // struct MyStruct<'x, X> { field: Box<dyn Trait<'x, X>> }
282 // ```
283 //
284 // The `where Self: 'a` predicate refers to the *existential, hidden type*
285 // that is represented by the `dyn Trait`, not to the `X` type parameter
286 // (or any other generic parameter) declared on `MyStruct`.
287 //
288 // Note that we do this check for self **before** applying `args`. In the
289 // case that `args` come from a `dyn Trait` type, our caller will have
290 // included `Self = usize` as the value for `Self`. If we were
291 // to apply the args, and not filter this predicate, we might then falsely
292 // conclude that e.g., `X: 'x` was a reasonable inferred requirement.
293 //
294 // Another similar case is where we have an inferred
295 // requirement like `<Self as Trait>::Foo: 'b`. We presently
296 // ignore such requirements as well (cc #54467)-- though
297 // conceivably it might be better if we could extract the `Foo
298 // = X` binding from the object type (there must be such a
299 // binding) and thus infer an outlives requirement that `X:
300 // 'b`.
301 if let Some(self_ty) = ignored_self_ty
302 && let GenericArgKind::Type(ty) = outlives_predicate.0.unpack()
303 && ty.walk().any(|arg| arg == self_ty.into())
304 {
305 debug!("skipping self ty = {ty:?}");
306 continue;
307 }
308
309 let predicate = explicit_predicates.rebind(*outlives_predicate).instantiate(tcx, args);
310 debug!("predicate = {predicate:?}");
311 insert_outlives_predicate(tcx, predicate.0, predicate.1, span, required_predicates);
312 }
313}
314
315/// Check the inferred predicates declared on the type.
316///
317/// ### Example
318///
319/// ```ignore (illustrative)
320/// struct Outer<'a, T> {
321/// outer: Inner<'a, T>,
322/// }
323///
324/// struct Inner<'b, U> {
325/// inner: &'b U,
326/// }
327/// ```
328///
329/// Here, when processing the type of field `outer`, we would request the
330/// set of implicit predicates computed for `Inner` thus far. This will
331/// initially come back empty, but in next round we will get `U: 'b`.
332/// We then apply the instantiation `['b => 'a, U => T]` and thus get the
333/// requirement that `T: 'a` holds for `Outer`.
334fn check_inferred_predicates<'tcx>(
335 tcx: TyCtxt<'tcx>,
336 def_id: DefId,
337 args: ty::GenericArgsRef<'tcx>,
338 global_inferred_outlives: &FxIndexMap<DefId, ty::EarlyBinder<'tcx, RequiredPredicates<'tcx>>>,
339 required_predicates: &mut RequiredPredicates<'tcx>,
340) {
341 // Load the current set of inferred and explicit predicates from `global_inferred_outlives`
342 // and filter the ones that are `TypeOutlives`.
343
344 let Some(predicates) = global_inferred_outlives.get(&def_id) else {
345 return;
346 };
347
348 for (&predicate, &span) in predicates.as_ref().skip_binder() {
349 // `predicate` is `U: 'b` in the example above.
350 // So apply the instantiation to get `T: 'a`.
351 let ty::OutlivesPredicate(arg, region) =
352 predicates.rebind(predicate).instantiate(tcx, args);
353 insert_outlives_predicate(tcx, arg, region, span, required_predicates);
354 }
355}