]> git.lizzy.rs Git - rust.git/blob - src/librustc/traits/util.rs
Rollup merge of #59432 - phansch:compiletest_docs, r=alexcrichton
[rust.git] / src / librustc / traits / util.rs
1 use crate::hir;
2 use crate::hir::def_id::DefId;
3 use crate::traits::specialize::specialization_graph::NodeItem;
4 use crate::ty::{self, Ty, TyCtxt, ToPredicate, ToPolyTraitRef};
5 use crate::ty::outlives::Component;
6 use crate::ty::subst::{Kind, Subst, SubstsRef};
7 use crate::util::nodemap::FxHashSet;
8
9 use super::{Obligation, ObligationCause, PredicateObligation, SelectionContext, Normalized};
10
11 fn anonymize_predicate<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
12                                        pred: &ty::Predicate<'tcx>)
13                                        -> ty::Predicate<'tcx> {
14     match *pred {
15         ty::Predicate::Trait(ref data) =>
16             ty::Predicate::Trait(tcx.anonymize_late_bound_regions(data)),
17
18         ty::Predicate::RegionOutlives(ref data) =>
19             ty::Predicate::RegionOutlives(tcx.anonymize_late_bound_regions(data)),
20
21         ty::Predicate::TypeOutlives(ref data) =>
22             ty::Predicate::TypeOutlives(tcx.anonymize_late_bound_regions(data)),
23
24         ty::Predicate::Projection(ref data) =>
25             ty::Predicate::Projection(tcx.anonymize_late_bound_regions(data)),
26
27         ty::Predicate::WellFormed(data) =>
28             ty::Predicate::WellFormed(data),
29
30         ty::Predicate::ObjectSafe(data) =>
31             ty::Predicate::ObjectSafe(data),
32
33         ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind) =>
34             ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind),
35
36         ty::Predicate::Subtype(ref data) =>
37             ty::Predicate::Subtype(tcx.anonymize_late_bound_regions(data)),
38
39         ty::Predicate::ConstEvaluatable(def_id, substs) =>
40             ty::Predicate::ConstEvaluatable(def_id, substs),
41     }
42 }
43
44
45 struct PredicateSet<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
46     tcx: TyCtxt<'a, 'gcx, 'tcx>,
47     set: FxHashSet<ty::Predicate<'tcx>>,
48 }
49
50 impl<'a, 'gcx, 'tcx> PredicateSet<'a, 'gcx, 'tcx> {
51     fn new(tcx: TyCtxt<'a, 'gcx, 'tcx>) -> PredicateSet<'a, 'gcx, 'tcx> {
52         PredicateSet { tcx: tcx, set: Default::default() }
53     }
54
55     fn insert(&mut self, pred: &ty::Predicate<'tcx>) -> bool {
56         // We have to be careful here because we want
57         //
58         //    for<'a> Foo<&'a int>
59         //
60         // and
61         //
62         //    for<'b> Foo<&'b int>
63         //
64         // to be considered equivalent. So normalize all late-bound
65         // regions before we throw things into the underlying set.
66         self.set.insert(anonymize_predicate(self.tcx, pred))
67     }
68 }
69
70 ///////////////////////////////////////////////////////////////////////////
71 // `Elaboration` iterator
72 ///////////////////////////////////////////////////////////////////////////
73
74 /// "Elaboration" is the process of identifying all the predicates that
75 /// are implied by a source predicate. Currently this basically means
76 /// walking the "supertraits" and other similar assumptions. For
77 /// example, if we know that `T : Ord`, the elaborator would deduce
78 /// that `T : PartialOrd` holds as well. Similarly, if we have `trait
79 /// Foo : 'static`, and we know that `T : Foo`, then we know that `T :
80 /// 'static`.
81 pub struct Elaborator<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
82     stack: Vec<ty::Predicate<'tcx>>,
83     visited: PredicateSet<'a, 'gcx, 'tcx>,
84 }
85
86 pub fn elaborate_trait_ref<'cx, 'gcx, 'tcx>(
87     tcx: TyCtxt<'cx, 'gcx, 'tcx>,
88     trait_ref: ty::PolyTraitRef<'tcx>)
89     -> Elaborator<'cx, 'gcx, 'tcx>
90 {
91     elaborate_predicates(tcx, vec![trait_ref.to_predicate()])
92 }
93
94 pub fn elaborate_trait_refs<'cx, 'gcx, 'tcx>(
95     tcx: TyCtxt<'cx, 'gcx, 'tcx>,
96     trait_refs: impl Iterator<Item = ty::PolyTraitRef<'tcx>>)
97     -> Elaborator<'cx, 'gcx, 'tcx>
98 {
99     let predicates = trait_refs.map(|trait_ref| trait_ref.to_predicate())
100                                .collect();
101     elaborate_predicates(tcx, predicates)
102 }
103
104 pub fn elaborate_predicates<'cx, 'gcx, 'tcx>(
105     tcx: TyCtxt<'cx, 'gcx, 'tcx>,
106     mut predicates: Vec<ty::Predicate<'tcx>>)
107     -> Elaborator<'cx, 'gcx, 'tcx>
108 {
109     let mut visited = PredicateSet::new(tcx);
110     predicates.retain(|pred| visited.insert(pred));
111     Elaborator { stack: predicates, visited: visited }
112 }
113
114 impl<'cx, 'gcx, 'tcx> Elaborator<'cx, 'gcx, 'tcx> {
115     pub fn filter_to_traits(self) -> FilterToTraits<Self> {
116         FilterToTraits::new(self)
117     }
118
119     fn push(&mut self, predicate: &ty::Predicate<'tcx>) {
120         let tcx = self.visited.tcx;
121         match *predicate {
122             ty::Predicate::Trait(ref data) => {
123                 // Predicates declared on the trait.
124                 let predicates = tcx.super_predicates_of(data.def_id());
125
126                 let mut predicates: Vec<_> =
127                     predicates.predicates
128                               .iter()
129                               .map(|(p, _)| p.subst_supertrait(tcx, &data.to_poly_trait_ref()))
130                               .collect();
131
132                 debug!("super_predicates: data={:?} predicates={:?}",
133                        data, predicates);
134
135                 // Only keep those bounds that we haven't already
136                 // seen.  This is necessary to prevent infinite
137                 // recursion in some cases.  One common case is when
138                 // people define `trait Sized: Sized { }` rather than `trait
139                 // Sized { }`.
140                 predicates.retain(|r| self.visited.insert(r));
141
142                 self.stack.extend(predicates);
143             }
144             ty::Predicate::WellFormed(..) => {
145                 // Currently, we do not elaborate WF predicates,
146                 // although we easily could.
147             }
148             ty::Predicate::ObjectSafe(..) => {
149                 // Currently, we do not elaborate object-safe
150                 // predicates.
151             }
152             ty::Predicate::Subtype(..) => {
153                 // Currently, we do not "elaborate" predicates like `X
154                 // <: Y`, though conceivably we might.
155             }
156             ty::Predicate::Projection(..) => {
157                 // Nothing to elaborate in a projection predicate.
158             }
159             ty::Predicate::ClosureKind(..) => {
160                 // Nothing to elaborate when waiting for a closure's kind to be inferred.
161             }
162             ty::Predicate::ConstEvaluatable(..) => {
163                 // Currently, we do not elaborate const-evaluatable
164                 // predicates.
165             }
166
167             ty::Predicate::RegionOutlives(..) => {
168                 // Nothing to elaborate from `'a: 'b`.
169             }
170
171             ty::Predicate::TypeOutlives(ref data) => {
172                 // We know that `T: 'a` for some type `T`. We can
173                 // often elaborate this. For example, if we know that
174                 // `[U]: 'a`, that implies that `U: 'a`. Similarly, if
175                 // we know `&'a U: 'b`, then we know that `'a: 'b` and
176                 // `U: 'b`.
177                 //
178                 // We can basically ignore bound regions here. So for
179                 // example `for<'c> Foo<'a,'c>: 'b` can be elaborated to
180                 // `'a: 'b`.
181
182                 // Ignore `for<'a> T: 'a` -- we might in the future
183                 // consider this as evidence that `T: 'static`, but
184                 // I'm a bit wary of such constructions and so for now
185                 // I want to be conservative. --nmatsakis
186                 let ty_max = data.skip_binder().0;
187                 let r_min = data.skip_binder().1;
188                 if r_min.is_late_bound() {
189                     return;
190                 }
191
192                 let visited = &mut self.visited;
193                 let mut components = smallvec![];
194                 tcx.push_outlives_components(ty_max, &mut components);
195                 self.stack.extend(
196                     components
197                        .into_iter()
198                        .filter_map(|component| match component {
199                            Component::Region(r) => if r.is_late_bound() {
200                                None
201                            } else {
202                                Some(ty::Predicate::RegionOutlives(
203                                    ty::Binder::dummy(ty::OutlivesPredicate(r, r_min))))
204                            },
205
206                            Component::Param(p) => {
207                                let ty = tcx.mk_ty_param(p.idx, p.name);
208                                Some(ty::Predicate::TypeOutlives(
209                                    ty::Binder::dummy(ty::OutlivesPredicate(ty, r_min))))
210                            },
211
212                            Component::UnresolvedInferenceVariable(_) => {
213                                None
214                            },
215
216                            Component::Projection(_) |
217                            Component::EscapingProjection(_) => {
218                                // We can probably do more here. This
219                                // corresponds to a case like `<T as
220                                // Foo<'a>>::U: 'b`.
221                                None
222                            },
223                        })
224                        .filter(|p| visited.insert(p)));
225             }
226         }
227     }
228 }
229
230 impl<'cx, 'gcx, 'tcx> Iterator for Elaborator<'cx, 'gcx, 'tcx> {
231     type Item = ty::Predicate<'tcx>;
232
233     fn size_hint(&self) -> (usize, Option<usize>) {
234         (self.stack.len(), None)
235     }
236
237     fn next(&mut self) -> Option<ty::Predicate<'tcx>> {
238         // Extract next item from top-most stack frame, if any.
239         let next_predicate = match self.stack.pop() {
240             Some(predicate) => predicate,
241             None => {
242                 // No more stack frames. Done.
243                 return None;
244             }
245         };
246         self.push(&next_predicate);
247         return Some(next_predicate);
248     }
249 }
250
251 ///////////////////////////////////////////////////////////////////////////
252 // Supertrait iterator
253 ///////////////////////////////////////////////////////////////////////////
254
255 pub type Supertraits<'cx, 'gcx, 'tcx> = FilterToTraits<Elaborator<'cx, 'gcx, 'tcx>>;
256
257 pub fn supertraits<'cx, 'gcx, 'tcx>(tcx: TyCtxt<'cx, 'gcx, 'tcx>,
258                                     trait_ref: ty::PolyTraitRef<'tcx>)
259                                     -> Supertraits<'cx, 'gcx, 'tcx>
260 {
261     elaborate_trait_ref(tcx, trait_ref).filter_to_traits()
262 }
263
264 pub fn transitive_bounds<'cx, 'gcx, 'tcx>(tcx: TyCtxt<'cx, 'gcx, 'tcx>,
265                                           bounds: impl Iterator<Item = ty::PolyTraitRef<'tcx>>)
266                                           -> Supertraits<'cx, 'gcx, 'tcx>
267 {
268     elaborate_trait_refs(tcx, bounds).filter_to_traits()
269 }
270
271 ///////////////////////////////////////////////////////////////////////////
272 // Iterator over def-ids of supertraits
273
274 pub struct SupertraitDefIds<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
275     tcx: TyCtxt<'a, 'gcx, 'tcx>,
276     stack: Vec<DefId>,
277     visited: FxHashSet<DefId>,
278 }
279
280 pub fn supertrait_def_ids<'cx, 'gcx, 'tcx>(tcx: TyCtxt<'cx, 'gcx, 'tcx>,
281                                            trait_def_id: DefId)
282                                            -> SupertraitDefIds<'cx, 'gcx, 'tcx>
283 {
284     SupertraitDefIds {
285         tcx,
286         stack: vec![trait_def_id],
287         visited: Some(trait_def_id).into_iter().collect(),
288     }
289 }
290
291 impl<'cx, 'gcx, 'tcx> Iterator for SupertraitDefIds<'cx, 'gcx, 'tcx> {
292     type Item = DefId;
293
294     fn next(&mut self) -> Option<DefId> {
295         let def_id = self.stack.pop()?;
296         let predicates = self.tcx.super_predicates_of(def_id);
297         let visited = &mut self.visited;
298         self.stack.extend(
299             predicates.predicates
300                       .iter()
301                       .filter_map(|(p, _)| p.to_opt_poly_trait_ref())
302                       .map(|t| t.def_id())
303                       .filter(|&super_def_id| visited.insert(super_def_id)));
304         Some(def_id)
305     }
306 }
307
308 ///////////////////////////////////////////////////////////////////////////
309 // Other
310 ///////////////////////////////////////////////////////////////////////////
311
312 /// A filter around an iterator of predicates that makes it yield up
313 /// just trait references.
314 pub struct FilterToTraits<I> {
315     base_iterator: I
316 }
317
318 impl<I> FilterToTraits<I> {
319     fn new(base: I) -> FilterToTraits<I> {
320         FilterToTraits { base_iterator: base }
321     }
322 }
323
324 impl<'tcx, I: Iterator<Item = ty::Predicate<'tcx>>> Iterator for FilterToTraits<I> {
325     type Item = ty::PolyTraitRef<'tcx>;
326
327     fn next(&mut self) -> Option<ty::PolyTraitRef<'tcx>> {
328         loop {
329             match self.base_iterator.next() {
330                 None => {
331                     return None;
332                 }
333                 Some(ty::Predicate::Trait(data)) => {
334                     return Some(data.to_poly_trait_ref());
335                 }
336                 Some(_) => {}
337             }
338         }
339     }
340
341     fn size_hint(&self) -> (usize, Option<usize>) {
342         let (_, upper) = self.base_iterator.size_hint();
343         (0, upper)
344     }
345 }
346
347 ///////////////////////////////////////////////////////////////////////////
348 // Other
349 ///////////////////////////////////////////////////////////////////////////
350
351 /// Instantiate all bound parameters of the impl with the given substs,
352 /// returning the resulting trait ref and all obligations that arise.
353 /// The obligations are closed under normalization.
354 pub fn impl_trait_ref_and_oblig<'a, 'gcx, 'tcx>(selcx: &mut SelectionContext<'a, 'gcx, 'tcx>,
355                                                 param_env: ty::ParamEnv<'tcx>,
356                                                 impl_def_id: DefId,
357                                                 impl_substs: SubstsRef<'tcx>,)
358                                                 -> (ty::TraitRef<'tcx>,
359                                                     Vec<PredicateObligation<'tcx>>)
360 {
361     let impl_trait_ref =
362         selcx.tcx().impl_trait_ref(impl_def_id).unwrap();
363     let impl_trait_ref =
364         impl_trait_ref.subst(selcx.tcx(), impl_substs);
365     let Normalized { value: impl_trait_ref, obligations: normalization_obligations1 } =
366         super::normalize(selcx, param_env, ObligationCause::dummy(), &impl_trait_ref);
367
368     let predicates = selcx.tcx().predicates_of(impl_def_id);
369     let predicates = predicates.instantiate(selcx.tcx(), impl_substs);
370     let Normalized { value: predicates, obligations: normalization_obligations2 } =
371         super::normalize(selcx, param_env, ObligationCause::dummy(), &predicates);
372     let impl_obligations =
373         predicates_for_generics(ObligationCause::dummy(), 0, param_env, &predicates);
374
375     let impl_obligations: Vec<_> =
376         impl_obligations.into_iter()
377         .chain(normalization_obligations1)
378         .chain(normalization_obligations2)
379         .collect();
380
381     (impl_trait_ref, impl_obligations)
382 }
383
384 /// See `super::obligations_for_generics`
385 pub fn predicates_for_generics<'tcx>(cause: ObligationCause<'tcx>,
386                                      recursion_depth: usize,
387                                      param_env: ty::ParamEnv<'tcx>,
388                                      generic_bounds: &ty::InstantiatedPredicates<'tcx>)
389                                      -> Vec<PredicateObligation<'tcx>>
390 {
391     debug!("predicates_for_generics(generic_bounds={:?})",
392            generic_bounds);
393
394     generic_bounds.predicates.iter().map(|predicate| {
395         Obligation { cause: cause.clone(),
396                      recursion_depth,
397                      param_env,
398                      predicate: predicate.clone() }
399     }).collect()
400 }
401
402 pub fn predicate_for_trait_ref<'tcx>(
403     cause: ObligationCause<'tcx>,
404     param_env: ty::ParamEnv<'tcx>,
405     trait_ref: ty::TraitRef<'tcx>,
406     recursion_depth: usize)
407     -> PredicateObligation<'tcx>
408 {
409     Obligation {
410         cause,
411         param_env,
412         recursion_depth,
413         predicate: trait_ref.to_predicate(),
414     }
415 }
416
417 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
418     pub fn predicate_for_trait_def(self,
419                                    param_env: ty::ParamEnv<'tcx>,
420                                    cause: ObligationCause<'tcx>,
421                                    trait_def_id: DefId,
422                                    recursion_depth: usize,
423                                    self_ty: Ty<'tcx>,
424                                    params: &[Kind<'tcx>])
425         -> PredicateObligation<'tcx>
426     {
427         let trait_ref = ty::TraitRef {
428             def_id: trait_def_id,
429             substs: self.mk_substs_trait(self_ty, params)
430         };
431         predicate_for_trait_ref(cause, param_env, trait_ref, recursion_depth)
432     }
433
434     /// Cast a trait reference into a reference to one of its super
435     /// traits; returns `None` if `target_trait_def_id` is not a
436     /// supertrait.
437     pub fn upcast_choices(self,
438                           source_trait_ref: ty::PolyTraitRef<'tcx>,
439                           target_trait_def_id: DefId)
440                           -> Vec<ty::PolyTraitRef<'tcx>>
441     {
442         if source_trait_ref.def_id() == target_trait_def_id {
443             return vec![source_trait_ref]; // shorcut the most common case
444         }
445
446         supertraits(self, source_trait_ref)
447             .filter(|r| r.def_id() == target_trait_def_id)
448             .collect()
449     }
450
451     /// Given a trait `trait_ref`, returns the number of vtable entries
452     /// that come from `trait_ref`, excluding its supertraits. Used in
453     /// computing the vtable base for an upcast trait of a trait object.
454     pub fn count_own_vtable_entries(self, trait_ref: ty::PolyTraitRef<'tcx>) -> usize {
455         let mut entries = 0;
456         // Count number of methods and add them to the total offset.
457         // Skip over associated types and constants.
458         for trait_item in self.associated_items(trait_ref.def_id()) {
459             if trait_item.kind == ty::AssociatedKind::Method {
460                 entries += 1;
461             }
462         }
463         entries
464     }
465
466     /// Given an upcast trait object described by `object`, returns the
467     /// index of the method `method_def_id` (which should be part of
468     /// `object.upcast_trait_ref`) within the vtable for `object`.
469     pub fn get_vtable_index_of_object_method<N>(self,
470                                                 object: &super::VtableObjectData<'tcx, N>,
471                                                 method_def_id: DefId) -> usize {
472         // Count number of methods preceding the one we are selecting and
473         // add them to the total offset.
474         // Skip over associated types and constants.
475         let mut entries = object.vtable_base;
476         for trait_item in self.associated_items(object.upcast_trait_ref.def_id()) {
477             if trait_item.def_id == method_def_id {
478                 // The item with the ID we were given really ought to be a method.
479                 assert_eq!(trait_item.kind, ty::AssociatedKind::Method);
480                 return entries;
481             }
482             if trait_item.kind == ty::AssociatedKind::Method {
483                 entries += 1;
484             }
485         }
486
487         bug!("get_vtable_index_of_object_method: {:?} was not found",
488              method_def_id);
489     }
490
491     pub fn closure_trait_ref_and_return_type(self,
492         fn_trait_def_id: DefId,
493         self_ty: Ty<'tcx>,
494         sig: ty::PolyFnSig<'tcx>,
495         tuple_arguments: TupleArgumentsFlag)
496         -> ty::Binder<(ty::TraitRef<'tcx>, Ty<'tcx>)>
497     {
498         let arguments_tuple = match tuple_arguments {
499             TupleArgumentsFlag::No => sig.skip_binder().inputs()[0],
500             TupleArgumentsFlag::Yes =>
501                 self.intern_tup(sig.skip_binder().inputs()),
502         };
503         let trait_ref = ty::TraitRef {
504             def_id: fn_trait_def_id,
505             substs: self.mk_substs_trait(self_ty, &[arguments_tuple.into()]),
506         };
507         ty::Binder::bind((trait_ref, sig.skip_binder().output()))
508     }
509
510     pub fn generator_trait_ref_and_outputs(self,
511         fn_trait_def_id: DefId,
512         self_ty: Ty<'tcx>,
513         sig: ty::PolyGenSig<'tcx>)
514         -> ty::Binder<(ty::TraitRef<'tcx>, Ty<'tcx>, Ty<'tcx>)>
515     {
516         let trait_ref = ty::TraitRef {
517             def_id: fn_trait_def_id,
518             substs: self.mk_substs_trait(self_ty, &[]),
519         };
520         ty::Binder::bind((trait_ref, sig.skip_binder().yield_ty, sig.skip_binder().return_ty))
521     }
522
523     pub fn impl_is_default(self, node_item_def_id: DefId) -> bool {
524         match self.hir().as_local_hir_id(node_item_def_id) {
525             Some(hir_id) => {
526                 let item = self.hir().expect_item_by_hir_id(hir_id);
527                 if let hir::ItemKind::Impl(_, _, defaultness, ..) = item.node {
528                     defaultness.is_default()
529                 } else {
530                     false
531                 }
532             }
533             None => {
534                 self.global_tcx()
535                     .impl_defaultness(node_item_def_id)
536                     .is_default()
537             }
538         }
539     }
540
541     pub fn impl_item_is_final(self, node_item: &NodeItem<hir::Defaultness>) -> bool {
542         node_item.item.is_final() && !self.impl_is_default(node_item.node.def_id())
543     }
544 }
545
546 pub enum TupleArgumentsFlag { Yes, No }