]> git.lizzy.rs Git - rust.git/blob - src/librustc/traits/util.rs
Improve some compiletest documentation
[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 = match self.stack.pop() {
296             Some(def_id) => def_id,
297             None => { return None; }
298         };
299
300         let predicates = self.tcx.super_predicates_of(def_id);
301         let visited = &mut self.visited;
302         self.stack.extend(
303             predicates.predicates
304                       .iter()
305                       .filter_map(|(p, _)| p.to_opt_poly_trait_ref())
306                       .map(|t| t.def_id())
307                       .filter(|&super_def_id| visited.insert(super_def_id)));
308         Some(def_id)
309     }
310 }
311
312 ///////////////////////////////////////////////////////////////////////////
313 // Other
314 ///////////////////////////////////////////////////////////////////////////
315
316 /// A filter around an iterator of predicates that makes it yield up
317 /// just trait references.
318 pub struct FilterToTraits<I> {
319     base_iterator: I
320 }
321
322 impl<I> FilterToTraits<I> {
323     fn new(base: I) -> FilterToTraits<I> {
324         FilterToTraits { base_iterator: base }
325     }
326 }
327
328 impl<'tcx, I: Iterator<Item = ty::Predicate<'tcx>>> Iterator for FilterToTraits<I> {
329     type Item = ty::PolyTraitRef<'tcx>;
330
331     fn next(&mut self) -> Option<ty::PolyTraitRef<'tcx>> {
332         loop {
333             match self.base_iterator.next() {
334                 None => {
335                     return None;
336                 }
337                 Some(ty::Predicate::Trait(data)) => {
338                     return Some(data.to_poly_trait_ref());
339                 }
340                 Some(_) => {}
341             }
342         }
343     }
344
345     fn size_hint(&self) -> (usize, Option<usize>) {
346         let (_, upper) = self.base_iterator.size_hint();
347         (0, upper)
348     }
349 }
350
351 ///////////////////////////////////////////////////////////////////////////
352 // Other
353 ///////////////////////////////////////////////////////////////////////////
354
355 /// Instantiate all bound parameters of the impl with the given substs,
356 /// returning the resulting trait ref and all obligations that arise.
357 /// The obligations are closed under normalization.
358 pub fn impl_trait_ref_and_oblig<'a, 'gcx, 'tcx>(selcx: &mut SelectionContext<'a, 'gcx, 'tcx>,
359                                                 param_env: ty::ParamEnv<'tcx>,
360                                                 impl_def_id: DefId,
361                                                 impl_substs: SubstsRef<'tcx>,)
362                                                 -> (ty::TraitRef<'tcx>,
363                                                     Vec<PredicateObligation<'tcx>>)
364 {
365     let impl_trait_ref =
366         selcx.tcx().impl_trait_ref(impl_def_id).unwrap();
367     let impl_trait_ref =
368         impl_trait_ref.subst(selcx.tcx(), impl_substs);
369     let Normalized { value: impl_trait_ref, obligations: normalization_obligations1 } =
370         super::normalize(selcx, param_env, ObligationCause::dummy(), &impl_trait_ref);
371
372     let predicates = selcx.tcx().predicates_of(impl_def_id);
373     let predicates = predicates.instantiate(selcx.tcx(), impl_substs);
374     let Normalized { value: predicates, obligations: normalization_obligations2 } =
375         super::normalize(selcx, param_env, ObligationCause::dummy(), &predicates);
376     let impl_obligations =
377         predicates_for_generics(ObligationCause::dummy(), 0, param_env, &predicates);
378
379     let impl_obligations: Vec<_> =
380         impl_obligations.into_iter()
381         .chain(normalization_obligations1)
382         .chain(normalization_obligations2)
383         .collect();
384
385     (impl_trait_ref, impl_obligations)
386 }
387
388 /// See `super::obligations_for_generics`
389 pub fn predicates_for_generics<'tcx>(cause: ObligationCause<'tcx>,
390                                      recursion_depth: usize,
391                                      param_env: ty::ParamEnv<'tcx>,
392                                      generic_bounds: &ty::InstantiatedPredicates<'tcx>)
393                                      -> Vec<PredicateObligation<'tcx>>
394 {
395     debug!("predicates_for_generics(generic_bounds={:?})",
396            generic_bounds);
397
398     generic_bounds.predicates.iter().map(|predicate| {
399         Obligation { cause: cause.clone(),
400                      recursion_depth,
401                      param_env,
402                      predicate: predicate.clone() }
403     }).collect()
404 }
405
406 pub fn predicate_for_trait_ref<'tcx>(
407     cause: ObligationCause<'tcx>,
408     param_env: ty::ParamEnv<'tcx>,
409     trait_ref: ty::TraitRef<'tcx>,
410     recursion_depth: usize)
411     -> PredicateObligation<'tcx>
412 {
413     Obligation {
414         cause,
415         param_env,
416         recursion_depth,
417         predicate: trait_ref.to_predicate(),
418     }
419 }
420
421 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
422     pub fn predicate_for_trait_def(self,
423                                    param_env: ty::ParamEnv<'tcx>,
424                                    cause: ObligationCause<'tcx>,
425                                    trait_def_id: DefId,
426                                    recursion_depth: usize,
427                                    self_ty: Ty<'tcx>,
428                                    params: &[Kind<'tcx>])
429         -> PredicateObligation<'tcx>
430     {
431         let trait_ref = ty::TraitRef {
432             def_id: trait_def_id,
433             substs: self.mk_substs_trait(self_ty, params)
434         };
435         predicate_for_trait_ref(cause, param_env, trait_ref, recursion_depth)
436     }
437
438     /// Cast a trait reference into a reference to one of its super
439     /// traits; returns `None` if `target_trait_def_id` is not a
440     /// supertrait.
441     pub fn upcast_choices(self,
442                           source_trait_ref: ty::PolyTraitRef<'tcx>,
443                           target_trait_def_id: DefId)
444                           -> Vec<ty::PolyTraitRef<'tcx>>
445     {
446         if source_trait_ref.def_id() == target_trait_def_id {
447             return vec![source_trait_ref]; // shorcut the most common case
448         }
449
450         supertraits(self, source_trait_ref)
451             .filter(|r| r.def_id() == target_trait_def_id)
452             .collect()
453     }
454
455     /// Given a trait `trait_ref`, returns the number of vtable entries
456     /// that come from `trait_ref`, excluding its supertraits. Used in
457     /// computing the vtable base for an upcast trait of a trait object.
458     pub fn count_own_vtable_entries(self, trait_ref: ty::PolyTraitRef<'tcx>) -> usize {
459         let mut entries = 0;
460         // Count number of methods and add them to the total offset.
461         // Skip over associated types and constants.
462         for trait_item in self.associated_items(trait_ref.def_id()) {
463             if trait_item.kind == ty::AssociatedKind::Method {
464                 entries += 1;
465             }
466         }
467         entries
468     }
469
470     /// Given an upcast trait object described by `object`, returns the
471     /// index of the method `method_def_id` (which should be part of
472     /// `object.upcast_trait_ref`) within the vtable for `object`.
473     pub fn get_vtable_index_of_object_method<N>(self,
474                                                 object: &super::VtableObjectData<'tcx, N>,
475                                                 method_def_id: DefId) -> usize {
476         // Count number of methods preceding the one we are selecting and
477         // add them to the total offset.
478         // Skip over associated types and constants.
479         let mut entries = object.vtable_base;
480         for trait_item in self.associated_items(object.upcast_trait_ref.def_id()) {
481             if trait_item.def_id == method_def_id {
482                 // The item with the ID we were given really ought to be a method.
483                 assert_eq!(trait_item.kind, ty::AssociatedKind::Method);
484                 return entries;
485             }
486             if trait_item.kind == ty::AssociatedKind::Method {
487                 entries += 1;
488             }
489         }
490
491         bug!("get_vtable_index_of_object_method: {:?} was not found",
492              method_def_id);
493     }
494
495     pub fn closure_trait_ref_and_return_type(self,
496         fn_trait_def_id: DefId,
497         self_ty: Ty<'tcx>,
498         sig: ty::PolyFnSig<'tcx>,
499         tuple_arguments: TupleArgumentsFlag)
500         -> ty::Binder<(ty::TraitRef<'tcx>, Ty<'tcx>)>
501     {
502         let arguments_tuple = match tuple_arguments {
503             TupleArgumentsFlag::No => sig.skip_binder().inputs()[0],
504             TupleArgumentsFlag::Yes =>
505                 self.intern_tup(sig.skip_binder().inputs()),
506         };
507         let trait_ref = ty::TraitRef {
508             def_id: fn_trait_def_id,
509             substs: self.mk_substs_trait(self_ty, &[arguments_tuple.into()]),
510         };
511         ty::Binder::bind((trait_ref, sig.skip_binder().output()))
512     }
513
514     pub fn generator_trait_ref_and_outputs(self,
515         fn_trait_def_id: DefId,
516         self_ty: Ty<'tcx>,
517         sig: ty::PolyGenSig<'tcx>)
518         -> ty::Binder<(ty::TraitRef<'tcx>, Ty<'tcx>, Ty<'tcx>)>
519     {
520         let trait_ref = ty::TraitRef {
521             def_id: fn_trait_def_id,
522             substs: self.mk_substs_trait(self_ty, &[]),
523         };
524         ty::Binder::bind((trait_ref, sig.skip_binder().yield_ty, sig.skip_binder().return_ty))
525     }
526
527     pub fn impl_is_default(self, node_item_def_id: DefId) -> bool {
528         match self.hir().as_local_hir_id(node_item_def_id) {
529             Some(hir_id) => {
530                 let item = self.hir().expect_item_by_hir_id(hir_id);
531                 if let hir::ItemKind::Impl(_, _, defaultness, ..) = item.node {
532                     defaultness.is_default()
533                 } else {
534                     false
535                 }
536             }
537             None => {
538                 self.global_tcx()
539                     .impl_defaultness(node_item_def_id)
540                     .is_default()
541             }
542         }
543     }
544
545     pub fn impl_item_is_final(self, node_item: &NodeItem<hir::Defaultness>) -> bool {
546         node_item.item.is_final() && !self.impl_is_default(node_item.node.def_id())
547     }
548 }
549
550 pub enum TupleArgumentsFlag { Yes, No }