]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/outlives/implicit_infer.rs
Auto merge of #57304 - davidtwco:issue-57280, r=nikomatsakis
[rust.git] / src / librustc_typeck / outlives / implicit_infer.rs
1 use rustc::hir;
2 use hir::Node;
3 use rustc::hir::def_id::DefId;
4 use rustc::hir::itemlikevisit::ItemLikeVisitor;
5 use rustc::ty::subst::{Kind, Subst, UnpackedKind};
6 use rustc::ty::{self, Ty, TyCtxt};
7 use rustc::ty::fold::TypeFoldable;
8 use rustc::util::nodemap::FxHashMap;
9
10 use super::explicit::ExplicitPredicatesMap;
11 use super::utils::*;
12
13 /// Infer predicates for the items in the crate.
14 ///
15 /// global_inferred_outlives: this is initially the empty map that
16 ///     was generated by walking the items in the crate. This will
17 ///     now be filled with inferred predicates.
18 pub fn infer_predicates<'tcx>(
19     tcx: TyCtxt<'_, 'tcx, 'tcx>,
20     explicit_map: &mut ExplicitPredicatesMap<'tcx>,
21 ) -> FxHashMap<DefId, RequiredPredicates<'tcx>> {
22     debug!("infer_predicates");
23
24     let mut predicates_added = true;
25
26     let mut global_inferred_outlives = FxHashMap::default();
27
28     // If new predicates were added then we need to re-calculate
29     // all crates since there could be new implied predicates.
30     while predicates_added {
31         predicates_added = false;
32
33         let mut visitor = InferVisitor {
34             tcx: tcx,
35             global_inferred_outlives: &mut global_inferred_outlives,
36             predicates_added: &mut predicates_added,
37             explicit_map: explicit_map,
38         };
39
40         // Visit all the crates and infer predicates
41         tcx.hir().krate().visit_all_item_likes(&mut visitor);
42     }
43
44     global_inferred_outlives
45 }
46
47 pub struct InferVisitor<'cx, 'tcx: 'cx> {
48     tcx: TyCtxt<'cx, 'tcx, 'tcx>,
49     global_inferred_outlives: &'cx mut FxHashMap<DefId, RequiredPredicates<'tcx>>,
50     predicates_added: &'cx mut bool,
51     explicit_map: &'cx mut ExplicitPredicatesMap<'tcx>,
52 }
53
54 impl<'cx, 'tcx> ItemLikeVisitor<'tcx> for InferVisitor<'cx, 'tcx> {
55     fn visit_item(&mut self, item: &hir::Item) {
56         let item_did = self.tcx.hir().local_def_id(item.id);
57
58         debug!("InferVisitor::visit_item(item={:?})", item_did);
59
60         let node_id = self
61             .tcx
62             .hir()
63             .as_local_node_id(item_did)
64             .expect("expected local def-id");
65         let item = match self.tcx.hir().get(node_id) {
66             Node::Item(item) => item,
67             _ => bug!(),
68         };
69
70         let mut item_required_predicates = RequiredPredicates::default();
71         match item.node {
72             hir::ItemKind::Union(..) | hir::ItemKind::Enum(..) | hir::ItemKind::Struct(..) => {
73                 let adt_def = self.tcx.adt_def(item_did);
74
75                 // Iterate over all fields in item_did
76                 for field_def in adt_def.all_fields() {
77                     // Calculating the predicate requirements necessary
78                     // for item_did.
79                     //
80                     // For field of type &'a T (reference) or Adt
81                     // (struct/enum/union) there will be outlive
82                     // requirements for adt_def.
83                     let field_ty = self.tcx.type_of(field_def.did);
84                     insert_required_predicates_to_be_wf(
85                         self.tcx,
86                         field_ty,
87                         self.global_inferred_outlives,
88                         &mut item_required_predicates,
89                         &mut self.explicit_map,
90                     );
91                 }
92             }
93
94             _ => {}
95         };
96
97         // If new predicates were added (`local_predicate_map` has more
98         // predicates than the `global_inferred_outlives`), the new predicates
99         // might result in implied predicates for their parent types.
100         // Therefore mark `predicates_added` as true and which will ensure
101         // we walk the crates again and re-calculate predicates for all
102         // items.
103         let item_predicates_len: usize = self
104             .global_inferred_outlives
105             .get(&item_did)
106             .map(|p| p.len())
107             .unwrap_or(0);
108         if item_required_predicates.len() > item_predicates_len {
109             *self.predicates_added = true;
110             self.global_inferred_outlives
111                 .insert(item_did, item_required_predicates);
112         }
113     }
114
115     fn visit_trait_item(&mut self, _trait_item: &'tcx hir::TraitItem) {}
116
117     fn visit_impl_item(&mut self, _impl_item: &'tcx hir::ImplItem) {}
118 }
119
120 fn insert_required_predicates_to_be_wf<'tcx>(
121     tcx: TyCtxt<'_, 'tcx, 'tcx>,
122     field_ty: Ty<'tcx>,
123     global_inferred_outlives: &FxHashMap<DefId, RequiredPredicates<'tcx>>,
124     required_predicates: &mut RequiredPredicates<'tcx>,
125     explicit_map: &mut ExplicitPredicatesMap<'tcx>,
126 ) {
127     for ty in field_ty.walk() {
128         match ty.sty {
129             // The field is of type &'a T which means that we will have
130             // a predicate requirement of T: 'a (T outlives 'a).
131             //
132             // We also want to calculate potential predicates for the T
133             ty::Ref(region, rty, _) => {
134                 debug!("Ref");
135                 insert_outlives_predicate(tcx, rty.into(), region, required_predicates);
136             }
137
138             // For each Adt (struct/enum/union) type `Foo<'a, T>`, we
139             // can load the current set of inferred and explicit
140             // predicates from `global_inferred_outlives` and filter the
141             // ones that are TypeOutlives.
142             ty::Adt(def, substs) => {
143                 // First check the inferred predicates
144                 //
145                 // Example 1:
146                 //
147                 //     struct Foo<'a, T> {
148                 //         field1: Bar<'a, T>
149                 //     }
150                 //
151                 //     struct Bar<'b, U> {
152                 //         field2: &'b U
153                 //     }
154                 //
155                 // Here, when processing the type of `field1`, we would
156                 // request the set of implicit predicates computed for `Bar`
157                 // thus far. This will initially come back empty, but in next
158                 // round we will get `U: 'b`. We then apply the substitution
159                 // `['b => 'a, U => T]` and thus get the requirement that `T:
160                 // 'a` holds for `Foo`.
161                 debug!("Adt");
162                 if let Some(unsubstituted_predicates) = global_inferred_outlives.get(&def.did) {
163                     for unsubstituted_predicate in unsubstituted_predicates {
164                         // `unsubstituted_predicate` is `U: 'b` in the
165                         // example above.  So apply the substitution to
166                         // get `T: 'a` (or `predicate`):
167                         let predicate = unsubstituted_predicate.subst(tcx, substs);
168                         insert_outlives_predicate(
169                             tcx,
170                             predicate.0,
171                             predicate.1,
172                             required_predicates,
173                         );
174                     }
175                 }
176
177                 // Check if the type has any explicit predicates that need
178                 // to be added to `required_predicates`
179                 // let _: () = substs.region_at(0);
180                 check_explicit_predicates(
181                     tcx,
182                     &def.did,
183                     substs,
184                     required_predicates,
185                     explicit_map,
186                     IgnoreSelfTy(false),
187                 );
188             }
189
190             ty::Dynamic(obj, ..) => {
191                 // This corresponds to `dyn Trait<..>`. In this case, we should
192                 // use the explicit predicates as well.
193
194                 debug!("Dynamic");
195                 debug!("field_ty = {}", &field_ty);
196                 debug!("ty in field = {}", &ty);
197                 if let Some(ex_trait_ref) = obj.principal() {
198                     // Here, we are passing the type `usize` as a
199                     // placeholder value with the function
200                     // `with_self_ty`, since there is no concrete type
201                     // `Self` for a `dyn Trait` at this
202                     // stage. Therefore when checking explicit
203                     // predicates in `check_explicit_predicates` we
204                     // need to ignore checking the explicit_map for
205                     // Self type.
206                     let substs = ex_trait_ref
207                         .with_self_ty(tcx, tcx.types.usize)
208                         .skip_binder()
209                         .substs;
210                     check_explicit_predicates(
211                         tcx,
212                         &ex_trait_ref.skip_binder().def_id,
213                         substs,
214                         required_predicates,
215                         explicit_map,
216                         IgnoreSelfTy(true),
217                     );
218                 }
219             }
220
221             ty::Projection(obj) => {
222                 // This corresponds to `<T as Foo<'a>>::Bar`. In this case, we should use the
223                 // explicit predicates as well.
224                 debug!("Projection");
225                 check_explicit_predicates(
226                     tcx,
227                     &tcx.associated_item(obj.item_def_id).container.id(),
228                     obj.substs,
229                     required_predicates,
230                     explicit_map,
231                     IgnoreSelfTy(false),
232                 );
233             }
234
235             _ => {}
236         }
237     }
238 }
239
240 #[derive(Debug)]
241 pub struct IgnoreSelfTy(bool);
242
243 /// We also have to check the explicit predicates
244 /// declared on the type.
245 ///
246 ///     struct Foo<'a, T> {
247 ///         field1: Bar<T>
248 ///     }
249 ///
250 ///     struct Bar<U> where U: 'static, U: Foo {
251 ///         ...
252 ///     }
253 ///
254 /// Here, we should fetch the explicit predicates, which
255 /// will give us `U: 'static` and `U: Foo`. The latter we
256 /// can ignore, but we will want to process `U: 'static`,
257 /// applying the substitution as above.
258 pub fn check_explicit_predicates<'tcx>(
259     tcx: TyCtxt<'_, 'tcx, 'tcx>,
260     def_id: &DefId,
261     substs: &[Kind<'tcx>],
262     required_predicates: &mut RequiredPredicates<'tcx>,
263     explicit_map: &mut ExplicitPredicatesMap<'tcx>,
264     ignore_self_ty: IgnoreSelfTy,
265 ) {
266     debug!(
267         "check_explicit_predicates(def_id={:?}, \
268          substs={:?}, \
269          explicit_map={:?}, \
270          required_predicates={:?}, \
271          ignore_self_ty={:?})",
272         def_id,
273         substs,
274         explicit_map,
275         required_predicates,
276         ignore_self_ty,
277     );
278     let explicit_predicates = explicit_map.explicit_predicates_of(tcx, *def_id);
279
280     for outlives_predicate in explicit_predicates.iter() {
281         debug!("outlives_predicate = {:?}", &outlives_predicate);
282
283         // Careful: If we are inferring the effects of a `dyn Trait<..>`
284         // type, then when we look up the predicates for `Trait`,
285         // we may find some that reference `Self`. e.g., perhaps the
286         // definition of `Trait` was:
287         //
288         // ```
289         // trait Trait<'a, T> where Self: 'a  { .. }
290         // ```
291         //
292         // we want to ignore such predicates here, because
293         // there is no type parameter for them to affect. Consider
294         // a struct containing `dyn Trait`:
295         //
296         // ```
297         // struct MyStruct<'x, X> { field: Box<dyn Trait<'x, X>> }
298         // ```
299         //
300         // The `where Self: 'a` predicate refers to the *existential, hidden type*
301         // that is represented by the `dyn Trait`, not to the `X` type parameter
302         // (or any other generic parameter) declared on `MyStruct`.
303         //
304         // Note that we do this check for self **before** applying `substs`. In the
305         // case that `substs` come from a `dyn Trait` type, our caller will have
306         // included `Self = usize` as the value for `Self`. If we were
307         // to apply the substs, and not filter this predicate, we might then falsely
308         // conclude that e.g., `X: 'x` was a reasonable inferred requirement.
309         //
310         // Another similar case is where we have a inferred
311         // requirement like `<Self as Trait>::Foo: 'b`. We presently
312         // ignore such requirements as well (cc #54467)-- though
313         // conceivably it might be better if we could extract the `Foo
314         // = X` binding from the object type (there must be such a
315         // binding) and thus infer an outlives requirement that `X:
316         // 'b`.
317         if ignore_self_ty.0 {
318             if let UnpackedKind::Type(ty) = outlives_predicate.0.unpack() {
319                 if ty.has_self_ty() {
320                     debug!("skipping self ty = {:?}", &ty);
321                     continue;
322                 }
323             }
324         }
325
326         let predicate = outlives_predicate.subst(tcx, substs);
327         debug!("predicate = {:?}", &predicate);
328         insert_outlives_predicate(tcx, predicate.0.into(), predicate.1, required_predicates);
329     }
330 }