1 use rustc::hir::{self, Node};
2 use rustc::hir::def_id::DefId;
3 use rustc::hir::itemlikevisit::ItemLikeVisitor;
4 use rustc::ty::subst::{Kind, Subst, UnpackedKind};
5 use rustc::ty::{self, Ty, TyCtxt};
6 use rustc::ty::fold::TypeFoldable;
7 use rustc::util::nodemap::FxHashMap;
9 use super::explicit::ExplicitPredicatesMap;
12 /// Infer predicates for the items in the crate.
14 /// `global_inferred_outlives`: this is initially the empty map that
15 /// was generated by walking the items in the crate. This will
16 /// now be filled with inferred predicates.
17 pub fn infer_predicates<'tcx>(
18 tcx: TyCtxt<'_, 'tcx, 'tcx>,
19 explicit_map: &mut ExplicitPredicatesMap<'tcx>,
20 ) -> FxHashMap<DefId, RequiredPredicates<'tcx>> {
21 debug!("infer_predicates");
23 let mut predicates_added = true;
25 let mut global_inferred_outlives = FxHashMap::default();
27 // If new predicates were added then we need to re-calculate
28 // all crates since there could be new implied predicates.
29 while predicates_added {
30 predicates_added = false;
32 let mut visitor = InferVisitor {
34 global_inferred_outlives: &mut global_inferred_outlives,
35 predicates_added: &mut predicates_added,
36 explicit_map: explicit_map,
39 // Visit all the crates and infer predicates
40 tcx.hir().krate().visit_all_item_likes(&mut visitor);
43 global_inferred_outlives
46 pub struct InferVisitor<'cx, 'tcx: 'cx> {
47 tcx: TyCtxt<'cx, 'tcx, 'tcx>,
48 global_inferred_outlives: &'cx mut FxHashMap<DefId, RequiredPredicates<'tcx>>,
49 predicates_added: &'cx mut bool,
50 explicit_map: &'cx mut ExplicitPredicatesMap<'tcx>,
53 impl<'cx, 'tcx> ItemLikeVisitor<'tcx> for InferVisitor<'cx, 'tcx> {
54 fn visit_item(&mut self, item: &hir::Item) {
55 let item_did = self.tcx.hir().local_def_id(item.id);
57 debug!("InferVisitor::visit_item(item={:?})", item_did);
62 .as_local_node_id(item_did)
63 .expect("expected local def-id");
64 let item = match self.tcx.hir().get(node_id) {
65 Node::Item(item) => item,
69 let mut item_required_predicates = RequiredPredicates::default();
71 hir::ItemKind::Union(..) | hir::ItemKind::Enum(..) | hir::ItemKind::Struct(..) => {
72 let adt_def = self.tcx.adt_def(item_did);
74 // Iterate over all fields in item_did
75 for field_def in adt_def.all_fields() {
76 // Calculating the predicate requirements necessary
79 // For field of type &'a T (reference) or Adt
80 // (struct/enum/union) there will be outlive
81 // requirements for adt_def.
82 let field_ty = self.tcx.type_of(field_def.did);
83 insert_required_predicates_to_be_wf(
86 self.global_inferred_outlives,
87 &mut item_required_predicates,
88 &mut self.explicit_map,
96 // If new predicates were added (`local_predicate_map` has more
97 // predicates than the `global_inferred_outlives`), the new predicates
98 // might result in implied predicates for their parent types.
99 // Therefore mark `predicates_added` as true and which will ensure
100 // we walk the crates again and re-calculate predicates for all
102 let item_predicates_len: usize = self
103 .global_inferred_outlives
107 if item_required_predicates.len() > item_predicates_len {
108 *self.predicates_added = true;
109 self.global_inferred_outlives
110 .insert(item_did, item_required_predicates);
114 fn visit_trait_item(&mut self, _trait_item: &'tcx hir::TraitItem) {}
116 fn visit_impl_item(&mut self, _impl_item: &'tcx hir::ImplItem) {}
119 fn insert_required_predicates_to_be_wf<'tcx>(
120 tcx: TyCtxt<'_, 'tcx, 'tcx>,
122 global_inferred_outlives: &FxHashMap<DefId, RequiredPredicates<'tcx>>,
123 required_predicates: &mut RequiredPredicates<'tcx>,
124 explicit_map: &mut ExplicitPredicatesMap<'tcx>,
126 for ty in field_ty.walk() {
128 // The field is of type &'a T which means that we will have
129 // a predicate requirement of T: 'a (T outlives 'a).
131 // We also want to calculate potential predicates for the T
132 ty::Ref(region, rty, _) => {
134 insert_outlives_predicate(tcx, rty.into(), region, required_predicates);
137 // For each Adt (struct/enum/union) type `Foo<'a, T>`, we
138 // can load the current set of inferred and explicit
139 // predicates from `global_inferred_outlives` and filter the
140 // ones that are TypeOutlives.
141 ty::Adt(def, substs) => {
142 // First check the inferred predicates
146 // struct Foo<'a, T> {
147 // field1: Bar<'a, T>
150 // struct Bar<'b, U> {
154 // Here, when processing the type of `field1`, we would
155 // request the set of implicit predicates computed for `Bar`
156 // thus far. This will initially come back empty, but in next
157 // round we will get `U: 'b`. We then apply the substitution
158 // `['b => 'a, U => T]` and thus get the requirement that `T:
159 // 'a` holds for `Foo`.
161 if let Some(unsubstituted_predicates) = global_inferred_outlives.get(&def.did) {
162 for unsubstituted_predicate in unsubstituted_predicates {
163 // `unsubstituted_predicate` is `U: 'b` in the
164 // example above. So apply the substitution to
165 // get `T: 'a` (or `predicate`):
166 let predicate = unsubstituted_predicate.subst(tcx, substs);
167 insert_outlives_predicate(
176 // Check if the type has any explicit predicates that need
177 // to be added to `required_predicates`
178 // let _: () = substs.region_at(0);
179 check_explicit_predicates(
189 ty::Dynamic(obj, ..) => {
190 // This corresponds to `dyn Trait<..>`. In this case, we should
191 // use the explicit predicates as well.
194 debug!("field_ty = {}", &field_ty);
195 debug!("ty in field = {}", &ty);
196 if let Some(ex_trait_ref) = obj.principal() {
197 // Here, we are passing the type `usize` as a
198 // placeholder value with the function
199 // `with_self_ty`, since there is no concrete type
200 // `Self` for a `dyn Trait` at this
201 // stage. Therefore when checking explicit
202 // predicates in `check_explicit_predicates` we
203 // need to ignore checking the explicit_map for
205 let substs = ex_trait_ref
206 .with_self_ty(tcx, tcx.types.usize)
209 check_explicit_predicates(
211 &ex_trait_ref.skip_binder().def_id,
220 ty::Projection(obj) => {
221 // This corresponds to `<T as Foo<'a>>::Bar`. In this case, we should use the
222 // explicit predicates as well.
223 debug!("Projection");
224 check_explicit_predicates(
226 &tcx.associated_item(obj.item_def_id).container.id(),
240 pub struct IgnoreSelfTy(bool);
242 /// We also have to check the explicit predicates
243 /// declared on the type.
245 /// struct Foo<'a, T> {
249 /// struct Bar<U> where U: 'static, U: Foo {
253 /// Here, we should fetch the explicit predicates, which
254 /// will give us `U: 'static` and `U: Foo`. The latter we
255 /// can ignore, but we will want to process `U: 'static`,
256 /// applying the substitution as above.
257 pub fn check_explicit_predicates<'tcx>(
258 tcx: TyCtxt<'_, 'tcx, 'tcx>,
260 substs: &[Kind<'tcx>],
261 required_predicates: &mut RequiredPredicates<'tcx>,
262 explicit_map: &mut ExplicitPredicatesMap<'tcx>,
263 ignore_self_ty: IgnoreSelfTy,
266 "check_explicit_predicates(def_id={:?}, \
269 required_predicates={:?}, \
270 ignore_self_ty={:?})",
277 let explicit_predicates = explicit_map.explicit_predicates_of(tcx, *def_id);
279 for outlives_predicate in explicit_predicates.iter() {
280 debug!("outlives_predicate = {:?}", &outlives_predicate);
282 // Careful: If we are inferring the effects of a `dyn Trait<..>`
283 // type, then when we look up the predicates for `Trait`,
284 // we may find some that reference `Self`. e.g., perhaps the
285 // definition of `Trait` was:
288 // trait Trait<'a, T> where Self: 'a { .. }
291 // we want to ignore such predicates here, because
292 // there is no type parameter for them to affect. Consider
293 // a struct containing `dyn Trait`:
296 // struct MyStruct<'x, X> { field: Box<dyn Trait<'x, X>> }
299 // The `where Self: 'a` predicate refers to the *existential, hidden type*
300 // that is represented by the `dyn Trait`, not to the `X` type parameter
301 // (or any other generic parameter) declared on `MyStruct`.
303 // Note that we do this check for self **before** applying `substs`. In the
304 // case that `substs` come from a `dyn Trait` type, our caller will have
305 // included `Self = usize` as the value for `Self`. If we were
306 // to apply the substs, and not filter this predicate, we might then falsely
307 // conclude that e.g., `X: 'x` was a reasonable inferred requirement.
309 // Another similar case is where we have a inferred
310 // requirement like `<Self as Trait>::Foo: 'b`. We presently
311 // ignore such requirements as well (cc #54467)-- though
312 // conceivably it might be better if we could extract the `Foo
313 // = X` binding from the object type (there must be such a
314 // binding) and thus infer an outlives requirement that `X:
316 if ignore_self_ty.0 {
317 if let UnpackedKind::Type(ty) = outlives_predicate.0.unpack() {
318 if ty.has_self_ty() {
319 debug!("skipping self ty = {:?}", &ty);
325 let predicate = outlives_predicate.subst(tcx, substs);
326 debug!("predicate = {:?}", &predicate);
327 insert_outlives_predicate(tcx, predicate.0.into(), predicate.1, required_predicates);