1 use rustc_data_structures::fx::FxHashMap;
2 use rustc_hir::def::DefKind;
3 use rustc_hir::def_id::DefId;
4 use rustc_middle::ty::subst::{GenericArg, GenericArgKind, Subst};
5 use rustc_middle::ty::{self, EarlyBinder, Ty, TyCtxt};
8 use super::explicit::ExplicitPredicatesMap;
11 /// Infer predicates for the items in the crate.
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.
16 pub fn infer_predicates<'tcx>(
18 explicit_map: &mut ExplicitPredicatesMap<'tcx>,
19 ) -> FxHashMap<DefId, RequiredPredicates<'tcx>> {
20 debug!("infer_predicates");
22 let mut predicates_added = true;
24 let mut global_inferred_outlives = FxHashMap::default();
26 // If new predicates were added then we need to re-calculate
27 // all crates since there could be new implied predicates.
28 while predicates_added {
29 predicates_added = false;
31 // Visit all the crates and infer predicates
32 for id in tcx.hir().items() {
33 let item_did = id.def_id;
35 debug!("InferVisitor::visit_item(item={:?})", item_did);
37 let mut item_required_predicates = RequiredPredicates::default();
38 match tcx.def_kind(item_did) {
39 DefKind::Union | DefKind::Enum | DefKind::Struct => {
40 let adt_def = tcx.adt_def(item_did.to_def_id());
42 // Iterate over all fields in item_did
43 for field_def in adt_def.all_fields() {
44 // Calculating the predicate requirements necessary
47 // For field of type &'a T (reference) or Adt
48 // (struct/enum/union) there will be outlive
49 // requirements for adt_def.
50 let field_ty = tcx.type_of(field_def.did);
51 let field_span = tcx.def_span(field_def.did);
52 insert_required_predicates_to_be_wf(
56 &mut global_inferred_outlives,
57 &mut item_required_predicates,
66 // If new predicates were added (`local_predicate_map` has more
67 // predicates than the `global_inferred_outlives`), the new predicates
68 // might result in implied predicates for their parent types.
69 // Therefore mark `predicates_added` as true and which will ensure
70 // we walk the crates again and re-calculate predicates for all
72 let item_predicates_len: usize =
73 global_inferred_outlives.get(&item_did.to_def_id()).map_or(0, |p| p.len());
74 if item_required_predicates.len() > item_predicates_len {
75 predicates_added = true;
76 global_inferred_outlives.insert(item_did.to_def_id(), item_required_predicates);
81 global_inferred_outlives
84 fn insert_required_predicates_to_be_wf<'tcx>(
88 global_inferred_outlives: &FxHashMap<DefId, RequiredPredicates<'tcx>>,
89 required_predicates: &mut RequiredPredicates<'tcx>,
90 explicit_map: &mut ExplicitPredicatesMap<'tcx>,
92 for arg in field_ty.walk() {
93 let ty = match arg.unpack() {
94 GenericArgKind::Type(ty) => ty,
96 // No predicates from lifetimes or constants, except potentially
97 // constants' types, but `walk` will get to them as well.
98 GenericArgKind::Lifetime(_) | GenericArgKind::Const(_) => continue,
102 // The field is of type &'a T which means that we will have
103 // a predicate requirement of T: 'a (T outlives 'a).
105 // We also want to calculate potential predicates for the T
106 ty::Ref(region, rty, _) => {
108 insert_outlives_predicate(tcx, rty.into(), region, field_span, required_predicates);
111 // For each Adt (struct/enum/union) type `Foo<'a, T>`, we
112 // can load the current set of inferred and explicit
113 // predicates from `global_inferred_outlives` and filter the
114 // ones that are TypeOutlives.
115 ty::Adt(def, substs) => {
116 // First check the inferred predicates
120 // struct Foo<'a, T> {
121 // field1: Bar<'a, T>
124 // struct Bar<'b, U> {
128 // Here, when processing the type of `field1`, we would
129 // request the set of implicit predicates computed for `Bar`
130 // thus far. This will initially come back empty, but in next
131 // round we will get `U: 'b`. We then apply the substitution
132 // `['b => 'a, U => T]` and thus get the requirement that `T:
133 // 'a` holds for `Foo`.
135 if let Some(unsubstituted_predicates) = global_inferred_outlives.get(&def.did()) {
136 for (unsubstituted_predicate, &span) in unsubstituted_predicates {
137 // `unsubstituted_predicate` is `U: 'b` in the
138 // example above. So apply the substitution to
139 // get `T: 'a` (or `predicate`):
140 let predicate = EarlyBinder(*unsubstituted_predicate).subst(tcx, substs);
141 insert_outlives_predicate(
151 // Check if the type has any explicit predicates that need
152 // to be added to `required_predicates`
153 // let _: () = substs.region_at(0);
154 check_explicit_predicates(
164 ty::Dynamic(obj, ..) => {
165 // This corresponds to `dyn Trait<..>`. In this case, we should
166 // use the explicit predicates as well.
169 debug!("field_ty = {}", &field_ty);
170 debug!("ty in field = {}", &ty);
171 if let Some(ex_trait_ref) = obj.principal() {
172 // Here, we are passing the type `usize` as a
173 // placeholder value with the function
174 // `with_self_ty`, since there is no concrete type
175 // `Self` for a `dyn Trait` at this
176 // stage. Therefore when checking explicit
177 // predicates in `check_explicit_predicates` we
178 // need to ignore checking the explicit_map for
181 ex_trait_ref.with_self_ty(tcx, tcx.types.usize).skip_binder().substs;
182 check_explicit_predicates(
184 ex_trait_ref.skip_binder().def_id,
188 Some(tcx.types.self_param),
193 ty::Projection(obj) => {
194 // This corresponds to `<T as Foo<'a>>::Bar`. In this case, we should use the
195 // explicit predicates as well.
196 debug!("Projection");
197 check_explicit_predicates(
199 tcx.associated_item(obj.item_def_id).container.id(),
212 /// We also have to check the explicit predicates
213 /// declared on the type.
214 /// ```ignore (illustrative)
215 /// struct Foo<'a, T> {
219 /// struct Bar<U> where U: 'static, U: Foo {
223 /// Here, we should fetch the explicit predicates, which
224 /// will give us `U: 'static` and `U: Foo`. The latter we
225 /// can ignore, but we will want to process `U: 'static`,
226 /// applying the substitution as above.
227 pub fn check_explicit_predicates<'tcx>(
230 substs: &[GenericArg<'tcx>],
231 required_predicates: &mut RequiredPredicates<'tcx>,
232 explicit_map: &mut ExplicitPredicatesMap<'tcx>,
233 ignored_self_ty: Option<Ty<'tcx>>,
236 "check_explicit_predicates(def_id={:?}, \
239 required_predicates={:?}, \
240 ignored_self_ty={:?})",
241 def_id, substs, explicit_map, required_predicates, ignored_self_ty,
243 let explicit_predicates = explicit_map.explicit_predicates_of(tcx, def_id);
245 for (outlives_predicate, &span) in explicit_predicates {
246 debug!("outlives_predicate = {:?}", &outlives_predicate);
248 // Careful: If we are inferring the effects of a `dyn Trait<..>`
249 // type, then when we look up the predicates for `Trait`,
250 // we may find some that reference `Self`. e.g., perhaps the
251 // definition of `Trait` was:
254 // trait Trait<'a, T> where Self: 'a { .. }
257 // we want to ignore such predicates here, because
258 // there is no type parameter for them to affect. Consider
259 // a struct containing `dyn Trait`:
262 // struct MyStruct<'x, X> { field: Box<dyn Trait<'x, X>> }
265 // The `where Self: 'a` predicate refers to the *existential, hidden type*
266 // that is represented by the `dyn Trait`, not to the `X` type parameter
267 // (or any other generic parameter) declared on `MyStruct`.
269 // Note that we do this check for self **before** applying `substs`. In the
270 // case that `substs` come from a `dyn Trait` type, our caller will have
271 // included `Self = usize` as the value for `Self`. If we were
272 // to apply the substs, and not filter this predicate, we might then falsely
273 // conclude that e.g., `X: 'x` was a reasonable inferred requirement.
275 // Another similar case is where we have an inferred
276 // requirement like `<Self as Trait>::Foo: 'b`. We presently
277 // ignore such requirements as well (cc #54467)-- though
278 // conceivably it might be better if we could extract the `Foo
279 // = X` binding from the object type (there must be such a
280 // binding) and thus infer an outlives requirement that `X:
282 if let Some(self_ty) = ignored_self_ty
283 && let GenericArgKind::Type(ty) = outlives_predicate.0.unpack()
284 && ty.walk().any(|arg| arg == self_ty.into())
286 debug!("skipping self ty = {:?}", &ty);
290 let predicate = EarlyBinder(*outlives_predicate).subst(tcx, substs);
291 debug!("predicate = {:?}", &predicate);
292 insert_outlives_predicate(tcx, predicate.0, predicate.1, span, required_predicates);