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