]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/outlives/implicit_infer.rs
Rollup merge of #58306 - GuillaumeGomez:crate-browser-history, r=QuietMisdreavus
[rust.git] / src / librustc_typeck / outlives / implicit_infer.rs
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;
8
9 use super::explicit::ExplicitPredicatesMap;
10 use super::utils::*;
11
12 /// Infer predicates for the items in the crate.
13 ///
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");
22
23     let mut predicates_added = true;
24
25     let mut global_inferred_outlives = FxHashMap::default();
26
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;
31
32         let mut visitor = InferVisitor {
33             tcx: tcx,
34             global_inferred_outlives: &mut global_inferred_outlives,
35             predicates_added: &mut predicates_added,
36             explicit_map: explicit_map,
37         };
38
39         // Visit all the crates and infer predicates
40         tcx.hir().krate().visit_all_item_likes(&mut visitor);
41     }
42
43     global_inferred_outlives
44 }
45
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>,
51 }
52
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);
56
57         debug!("InferVisitor::visit_item(item={:?})", item_did);
58
59         let node_id = self
60             .tcx
61             .hir()
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,
66             _ => bug!(),
67         };
68
69         let mut item_required_predicates = RequiredPredicates::default();
70         match item.node {
71             hir::ItemKind::Union(..) | hir::ItemKind::Enum(..) | hir::ItemKind::Struct(..) => {
72                 let adt_def = self.tcx.adt_def(item_did);
73
74                 // Iterate over all fields in item_did
75                 for field_def in adt_def.all_fields() {
76                     // Calculating the predicate requirements necessary
77                     // for item_did.
78                     //
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(
84                         self.tcx,
85                         field_ty,
86                         self.global_inferred_outlives,
87                         &mut item_required_predicates,
88                         &mut self.explicit_map,
89                     );
90                 }
91             }
92
93             _ => {}
94         };
95
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
101         // items.
102         let item_predicates_len: usize = self
103             .global_inferred_outlives
104             .get(&item_did)
105             .map(|p| p.len())
106             .unwrap_or(0);
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);
111         }
112     }
113
114     fn visit_trait_item(&mut self, _trait_item: &'tcx hir::TraitItem) {}
115
116     fn visit_impl_item(&mut self, _impl_item: &'tcx hir::ImplItem) {}
117 }
118
119 fn insert_required_predicates_to_be_wf<'tcx>(
120     tcx: TyCtxt<'_, 'tcx, 'tcx>,
121     field_ty: Ty<'tcx>,
122     global_inferred_outlives: &FxHashMap<DefId, RequiredPredicates<'tcx>>,
123     required_predicates: &mut RequiredPredicates<'tcx>,
124     explicit_map: &mut ExplicitPredicatesMap<'tcx>,
125 ) {
126     for ty in field_ty.walk() {
127         match ty.sty {
128             // The field is of type &'a T which means that we will have
129             // a predicate requirement of T: 'a (T outlives 'a).
130             //
131             // We also want to calculate potential predicates for the T
132             ty::Ref(region, rty, _) => {
133                 debug!("Ref");
134                 insert_outlives_predicate(tcx, rty.into(), region, required_predicates);
135             }
136
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
143                 //
144                 // Example 1:
145                 //
146                 //     struct Foo<'a, T> {
147                 //         field1: Bar<'a, T>
148                 //     }
149                 //
150                 //     struct Bar<'b, U> {
151                 //         field2: &'b U
152                 //     }
153                 //
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`.
160                 debug!("Adt");
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(
168                             tcx,
169                             predicate.0,
170                             predicate.1,
171                             required_predicates,
172                         );
173                     }
174                 }
175
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(
180                     tcx,
181                     &def.did,
182                     substs,
183                     required_predicates,
184                     explicit_map,
185                     IgnoreSelfTy(false),
186                 );
187             }
188
189             ty::Dynamic(obj, ..) => {
190                 // This corresponds to `dyn Trait<..>`. In this case, we should
191                 // use the explicit predicates as well.
192
193                 debug!("Dynamic");
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
204                     // Self type.
205                     let substs = ex_trait_ref
206                         .with_self_ty(tcx, tcx.types.usize)
207                         .skip_binder()
208                         .substs;
209                     check_explicit_predicates(
210                         tcx,
211                         &ex_trait_ref.skip_binder().def_id,
212                         substs,
213                         required_predicates,
214                         explicit_map,
215                         IgnoreSelfTy(true),
216                     );
217                 }
218             }
219
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(
225                     tcx,
226                     &tcx.associated_item(obj.item_def_id).container.id(),
227                     obj.substs,
228                     required_predicates,
229                     explicit_map,
230                     IgnoreSelfTy(false),
231                 );
232             }
233
234             _ => {}
235         }
236     }
237 }
238
239 #[derive(Debug)]
240 pub struct IgnoreSelfTy(bool);
241
242 /// We also have to check the explicit predicates
243 /// declared on the type.
244 ///
245 ///     struct Foo<'a, T> {
246 ///         field1: Bar<T>
247 ///     }
248 ///
249 ///     struct Bar<U> where U: 'static, U: Foo {
250 ///         ...
251 ///     }
252 ///
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>,
259     def_id: &DefId,
260     substs: &[Kind<'tcx>],
261     required_predicates: &mut RequiredPredicates<'tcx>,
262     explicit_map: &mut ExplicitPredicatesMap<'tcx>,
263     ignore_self_ty: IgnoreSelfTy,
264 ) {
265     debug!(
266         "check_explicit_predicates(def_id={:?}, \
267          substs={:?}, \
268          explicit_map={:?}, \
269          required_predicates={:?}, \
270          ignore_self_ty={:?})",
271         def_id,
272         substs,
273         explicit_map,
274         required_predicates,
275         ignore_self_ty,
276     );
277     let explicit_predicates = explicit_map.explicit_predicates_of(tcx, *def_id);
278
279     for outlives_predicate in explicit_predicates.iter() {
280         debug!("outlives_predicate = {:?}", &outlives_predicate);
281
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:
286         //
287         // ```
288         // trait Trait<'a, T> where Self: 'a  { .. }
289         // ```
290         //
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`:
294         //
295         // ```
296         // struct MyStruct<'x, X> { field: Box<dyn Trait<'x, X>> }
297         // ```
298         //
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`.
302         //
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.
308         //
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:
315         // 'b`.
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);
320                     continue;
321                 }
322             }
323         }
324
325         let predicate = outlives_predicate.subst(tcx, substs);
326         debug!("predicate = {:?}", &predicate);
327         insert_outlives_predicate(tcx, predicate.0.into(), predicate.1, required_predicates);
328     }
329 }