]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/outlives/implicit_infer.rs
Various minor/cosmetic improvements to code
[rust.git] / src / librustc_typeck / outlives / implicit_infer.rs
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.
4 //
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.
10
11 use rustc::hir;
12 use hir::Node;
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;
19
20 use super::explicit::ExplicitPredicatesMap;
21 use super::utils::*;
22
23 /// Infer predicates for the items in the crate.
24 ///
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");
33
34     let mut predicates_added = true;
35
36     let mut global_inferred_outlives = FxHashMap::default();
37
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;
42
43         let mut visitor = InferVisitor {
44             tcx: tcx,
45             global_inferred_outlives: &mut global_inferred_outlives,
46             predicates_added: &mut predicates_added,
47             explicit_map: explicit_map,
48         };
49
50         // Visit all the crates and infer predicates
51         tcx.hir().krate().visit_all_item_likes(&mut visitor);
52     }
53
54     global_inferred_outlives
55 }
56
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>,
62 }
63
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);
67
68         debug!("InferVisitor::visit_item(item={:?})", item_did);
69
70         let node_id = self
71             .tcx
72             .hir()
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,
77             _ => bug!(),
78         };
79
80         let mut item_required_predicates = RequiredPredicates::default();
81         match item.node {
82             hir::ItemKind::Union(..) | hir::ItemKind::Enum(..) | hir::ItemKind::Struct(..) => {
83                 let adt_def = self.tcx.adt_def(item_did);
84
85                 // Iterate over all fields in item_did
86                 for field_def in adt_def.all_fields() {
87                     // Calculating the predicate requirements necessary
88                     // for item_did.
89                     //
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(
95                         self.tcx,
96                         field_ty,
97                         self.global_inferred_outlives,
98                         &mut item_required_predicates,
99                         &mut self.explicit_map,
100                     );
101                 }
102             }
103
104             _ => {}
105         };
106
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
112         // items.
113         let item_predicates_len: usize = self
114             .global_inferred_outlives
115             .get(&item_did)
116             .map(|p| p.len())
117             .unwrap_or(0);
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);
122         }
123     }
124
125     fn visit_trait_item(&mut self, _trait_item: &'tcx hir::TraitItem) {}
126
127     fn visit_impl_item(&mut self, _impl_item: &'tcx hir::ImplItem) {}
128 }
129
130 fn insert_required_predicates_to_be_wf<'tcx>(
131     tcx: TyCtxt<'_, 'tcx, 'tcx>,
132     field_ty: Ty<'tcx>,
133     global_inferred_outlives: &FxHashMap<DefId, RequiredPredicates<'tcx>>,
134     required_predicates: &mut RequiredPredicates<'tcx>,
135     explicit_map: &mut ExplicitPredicatesMap<'tcx>,
136 ) {
137     for ty in field_ty.walk() {
138         match ty.sty {
139             // The field is of type &'a T which means that we will have
140             // a predicate requirement of T: 'a (T outlives 'a).
141             //
142             // We also want to calculate potential predicates for the T
143             ty::Ref(region, rty, _) => {
144                 debug!("Ref");
145                 insert_outlives_predicate(tcx, rty.into(), region, required_predicates);
146             }
147
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
154                 //
155                 // Example 1:
156                 //
157                 //     struct Foo<'a, T> {
158                 //         field1: Bar<'a, T>
159                 //     }
160                 //
161                 //     struct Bar<'b, U> {
162                 //         field2: &'b U
163                 //     }
164                 //
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`.
171                 debug!("Adt");
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(
179                             tcx,
180                             predicate.0,
181                             predicate.1,
182                             required_predicates,
183                         );
184                     }
185                 }
186
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(
191                     tcx,
192                     &def.did,
193                     substs,
194                     required_predicates,
195                     explicit_map,
196                     IgnoreSelfTy(false),
197                 );
198             }
199
200             ty::Dynamic(obj, ..) => {
201                 // This corresponds to `dyn Trait<..>`. In this case, we should
202                 // use the explicit predicates as well.
203
204                 debug!("Dynamic");
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
215                 // Self type.
216                 let substs = ex_trait_ref
217                     .with_self_ty(tcx, tcx.types.usize)
218                     .skip_binder()
219                     .substs;
220                 check_explicit_predicates(
221                     tcx,
222                     &ex_trait_ref.skip_binder().def_id,
223                     substs,
224                     required_predicates,
225                     explicit_map,
226                     IgnoreSelfTy(true),
227                 );
228             }
229
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(
235                     tcx,
236                     &tcx.associated_item(obj.item_def_id).container.id(),
237                     obj.substs,
238                     required_predicates,
239                     explicit_map,
240                     IgnoreSelfTy(false),
241                 );
242             }
243
244             _ => {}
245         }
246     }
247 }
248
249 #[derive(Debug)]
250 pub struct IgnoreSelfTy(bool);
251
252 /// We also have to check the explicit predicates
253 /// declared on the type.
254 ///
255 ///     struct Foo<'a, T> {
256 ///         field1: Bar<T>
257 ///     }
258 ///
259 ///     struct Bar<U> where U: 'static, U: Foo {
260 ///         ...
261 ///     }
262 ///
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>,
269     def_id: &DefId,
270     substs: &[Kind<'tcx>],
271     required_predicates: &mut RequiredPredicates<'tcx>,
272     explicit_map: &mut ExplicitPredicatesMap<'tcx>,
273     ignore_self_ty: IgnoreSelfTy,
274 ) {
275     debug!(
276         "check_explicit_predicates(def_id={:?}, \
277          substs={:?}, \
278          explicit_map={:?}, \
279          required_predicates={:?}, \
280          ignore_self_ty={:?})",
281         def_id,
282         substs,
283         explicit_map,
284         required_predicates,
285         ignore_self_ty,
286     );
287     let explicit_predicates = explicit_map.explicit_predicates_of(tcx, *def_id);
288
289     for outlives_predicate in explicit_predicates.iter() {
290         debug!("outlives_predicate = {:?}", &outlives_predicate);
291
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:
296         //
297         // ```
298         // trait Trait<'a, T> where Self: 'a  { .. }
299         // ```
300         //
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`:
304         //
305         // ```
306         // struct MyStruct<'x, X> { field: Box<dyn Trait<'x, X>> }
307         // ```
308         //
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`.
312         //
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.
318         //
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:
325         // 'b`.
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);
330                     continue;
331                 }
332             }
333         }
334
335         let predicate = outlives_predicate.subst(tcx, substs);
336         debug!("predicate = {:?}", &predicate);
337         insert_outlives_predicate(tcx, predicate.0.into(), predicate.1, required_predicates);
338     }
339 }