1 // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
13 use rustc::hir::def_id::DefId;
14 use rustc::hir::itemlikevisit::ItemLikeVisitor;
15 use rustc::ty::subst::{Kind, Subst, UnpackedKind};
16 use rustc::ty::{self, Ty, TyCtxt};
17 use rustc::ty::fold::TypeFoldable;
18 use rustc::util::nodemap::FxHashMap;
20 use super::explicit::ExplicitPredicatesMap;
23 /// Infer predicates for the items in the crate.
25 /// global_inferred_outlives: this is initially the empty map that
26 /// was generated by walking the items in the crate. This will
27 /// now be filled with inferred predicates.
28 pub fn infer_predicates<'tcx>(
29 tcx: TyCtxt<'_, 'tcx, 'tcx>,
30 explicit_map: &mut ExplicitPredicatesMap<'tcx>,
31 ) -> FxHashMap<DefId, RequiredPredicates<'tcx>> {
32 debug!("infer_predicates");
34 let mut predicates_added = true;
36 let mut global_inferred_outlives = FxHashMap::default();
38 // If new predicates were added then we need to re-calculate
39 // all crates since there could be new implied predicates.
40 while predicates_added {
41 predicates_added = false;
43 let mut visitor = InferVisitor {
45 global_inferred_outlives: &mut global_inferred_outlives,
46 predicates_added: &mut predicates_added,
47 explicit_map: explicit_map,
50 // Visit all the crates and infer predicates
51 tcx.hir().krate().visit_all_item_likes(&mut visitor);
54 global_inferred_outlives
57 pub struct InferVisitor<'cx, 'tcx: 'cx> {
58 tcx: TyCtxt<'cx, 'tcx, 'tcx>,
59 global_inferred_outlives: &'cx mut FxHashMap<DefId, RequiredPredicates<'tcx>>,
60 predicates_added: &'cx mut bool,
61 explicit_map: &'cx mut ExplicitPredicatesMap<'tcx>,
64 impl<'cx, 'tcx> ItemLikeVisitor<'tcx> for InferVisitor<'cx, 'tcx> {
65 fn visit_item(&mut self, item: &hir::Item) {
66 let item_did = self.tcx.hir().local_def_id(item.id);
68 debug!("InferVisitor::visit_item(item={:?})", item_did);
73 .as_local_node_id(item_did)
74 .expect("expected local def-id");
75 let item = match self.tcx.hir().get(node_id) {
76 Node::Item(item) => item,
80 let mut item_required_predicates = RequiredPredicates::default();
82 hir::ItemKind::Union(..) | hir::ItemKind::Enum(..) | hir::ItemKind::Struct(..) => {
83 let adt_def = self.tcx.adt_def(item_did);
85 // Iterate over all fields in item_did
86 for field_def in adt_def.all_fields() {
87 // Calculating the predicate requirements necessary
90 // For field of type &'a T (reference) or Adt
91 // (struct/enum/union) there will be outlive
92 // requirements for adt_def.
93 let field_ty = self.tcx.type_of(field_def.did);
94 insert_required_predicates_to_be_wf(
97 self.global_inferred_outlives,
98 &mut item_required_predicates,
99 &mut self.explicit_map,
107 // If new predicates were added (`local_predicate_map` has more
108 // predicates than the `global_inferred_outlives`), the new predicates
109 // might result in implied predicates for their parent types.
110 // Therefore mark `predicates_added` as true and which will ensure
111 // we walk the crates again and re-calculate predicates for all
113 let item_predicates_len: usize = self
114 .global_inferred_outlives
118 if item_required_predicates.len() > item_predicates_len {
119 *self.predicates_added = true;
120 self.global_inferred_outlives
121 .insert(item_did, item_required_predicates);
125 fn visit_trait_item(&mut self, _trait_item: &'tcx hir::TraitItem) {}
127 fn visit_impl_item(&mut self, _impl_item: &'tcx hir::ImplItem) {}
130 fn insert_required_predicates_to_be_wf<'tcx>(
131 tcx: TyCtxt<'_, 'tcx, 'tcx>,
133 global_inferred_outlives: &FxHashMap<DefId, RequiredPredicates<'tcx>>,
134 required_predicates: &mut RequiredPredicates<'tcx>,
135 explicit_map: &mut ExplicitPredicatesMap<'tcx>,
137 for ty in field_ty.walk() {
139 // The field is of type &'a T which means that we will have
140 // a predicate requirement of T: 'a (T outlives 'a).
142 // We also want to calculate potential predicates for the T
143 ty::Ref(region, rty, _) => {
145 insert_outlives_predicate(tcx, rty.into(), region, required_predicates);
148 // For each Adt (struct/enum/union) type `Foo<'a, T>`, we
149 // can load the current set of inferred and explicit
150 // predicates from `global_inferred_outlives` and filter the
151 // ones that are TypeOutlives.
152 ty::Adt(def, substs) => {
153 // First check the inferred predicates
157 // struct Foo<'a, T> {
158 // field1: Bar<'a, T>
161 // struct Bar<'b, U> {
165 // Here, when processing the type of `field1`, we would
166 // request the set of implicit predicates computed for `Bar`
167 // thus far. This will initially come back empty, but in next
168 // round we will get `U: 'b`. We then apply the substitution
169 // `['b => 'a, U => T]` and thus get the requirement that `T:
170 // 'a` holds for `Foo`.
172 if let Some(unsubstituted_predicates) = global_inferred_outlives.get(&def.did) {
173 for unsubstituted_predicate in unsubstituted_predicates {
174 // `unsubstituted_predicate` is `U: 'b` in the
175 // example above. So apply the substitution to
176 // get `T: 'a` (or `predicate`):
177 let predicate = unsubstituted_predicate.subst(tcx, substs);
178 insert_outlives_predicate(
187 // Check if the type has any explicit predicates that need
188 // to be added to `required_predicates`
189 // let _: () = substs.region_at(0);
190 check_explicit_predicates(
200 ty::Dynamic(obj, ..) => {
201 // This corresponds to `dyn Trait<..>`. In this case, we should
202 // use the explicit predicates as well.
205 debug!("field_ty = {}", &field_ty);
206 debug!("ty in field = {}", &ty);
207 let ex_trait_ref = obj.principal();
208 // Here, we are passing the type `usize` as a
209 // placeholder value with the function
210 // `with_self_ty`, since there is no concrete type
211 // `Self` for a `dyn Trait` at this
212 // stage. Therefore when checking explicit
213 // predicates in `check_explicit_predicates` we
214 // need to ignore checking the explicit_map for
216 let substs = ex_trait_ref
217 .with_self_ty(tcx, tcx.types.usize)
220 check_explicit_predicates(
222 &ex_trait_ref.skip_binder().def_id,
230 ty::Projection(obj) => {
231 // This corresponds to `<T as Foo<'a>>::Bar`. In this case, we should use the
232 // explicit predicates as well.
233 debug!("Projection");
234 check_explicit_predicates(
236 &tcx.associated_item(obj.item_def_id).container.id(),
250 pub struct IgnoreSelfTy(bool);
252 /// We also have to check the explicit predicates
253 /// declared on the type.
255 /// struct Foo<'a, T> {
259 /// struct Bar<U> where U: 'static, U: Foo {
263 /// Here, we should fetch the explicit predicates, which
264 /// will give us `U: 'static` and `U: Foo`. The latter we
265 /// can ignore, but we will want to process `U: 'static`,
266 /// applying the substitution as above.
267 pub fn check_explicit_predicates<'tcx>(
268 tcx: TyCtxt<'_, 'tcx, 'tcx>,
270 substs: &[Kind<'tcx>],
271 required_predicates: &mut RequiredPredicates<'tcx>,
272 explicit_map: &mut ExplicitPredicatesMap<'tcx>,
273 ignore_self_ty: IgnoreSelfTy,
276 "check_explicit_predicates(def_id={:?}, \
279 required_predicates={:?}, \
280 ignore_self_ty={:?})",
287 let explicit_predicates = explicit_map.explicit_predicates_of(tcx, *def_id);
289 for outlives_predicate in explicit_predicates.iter() {
290 debug!("outlives_predicate = {:?}", &outlives_predicate);
292 // Careful: If we are inferring the effects of a `dyn Trait<..>`
293 // type, then when we look up the predicates for `Trait`,
294 // we may find some that reference `Self`. e.g., perhaps the
295 // definition of `Trait` was:
298 // trait Trait<'a, T> where Self: 'a { .. }
301 // we want to ignore such predicates here, because
302 // there is no type parameter for them to affect. Consider
303 // a struct containing `dyn Trait`:
306 // struct MyStruct<'x, X> { field: Box<dyn Trait<'x, X>> }
309 // The `where Self: 'a` predicate refers to the *existential, hidden type*
310 // that is represented by the `dyn Trait`, not to the `X` type parameter
311 // (or any other generic parameter) declared on `MyStruct`.
313 // Note that we do this check for self **before** applying `substs`. In the
314 // case that `substs` come from a `dyn Trait` type, our caller will have
315 // included `Self = usize` as the value for `Self`. If we were
316 // to apply the substs, and not filter this predicate, we might then falsely
317 // conclude that e.g., `X: 'x` was a reasonable inferred requirement.
319 // Another similar case is where we have a inferred
320 // requirement like `<Self as Trait>::Foo: 'b`. We presently
321 // ignore such requirements as well (cc #54467)-- though
322 // conceivably it might be better if we could extract the `Foo
323 // = X` binding from the object type (there must be such a
324 // binding) and thus infer an outlives requirement that `X:
326 if ignore_self_ty.0 {
327 if let UnpackedKind::Type(ty) = outlives_predicate.0.unpack() {
328 if ty.has_self_ty() {
329 debug!("skipping self ty = {:?}", &ty);
335 let predicate = outlives_predicate.subst(tcx, substs);
336 debug!("predicate = {:?}", &predicate);
337 insert_outlives_predicate(tcx, predicate.0.into(), predicate.1, required_predicates);