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.
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.
11 use hir::def_id::DefId;
12 use ty::subst::{Subst, Substs};
13 use ty::{self, Ty, TyCtxt, ToPredicate, ToPolyTraitRef};
14 use ty::outlives::Component;
15 use util::nodemap::FxHashSet;
17 use super::{Obligation, ObligationCause, PredicateObligation, SelectionContext, Normalized};
19 fn anonymize_predicate<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
20 pred: &ty::Predicate<'tcx>)
21 -> ty::Predicate<'tcx> {
23 ty::Predicate::Trait(ref data) =>
24 ty::Predicate::Trait(tcx.anonymize_late_bound_regions(data)),
26 ty::Predicate::Equate(ref data) =>
27 ty::Predicate::Equate(tcx.anonymize_late_bound_regions(data)),
29 ty::Predicate::RegionOutlives(ref data) =>
30 ty::Predicate::RegionOutlives(tcx.anonymize_late_bound_regions(data)),
32 ty::Predicate::TypeOutlives(ref data) =>
33 ty::Predicate::TypeOutlives(tcx.anonymize_late_bound_regions(data)),
35 ty::Predicate::Projection(ref data) =>
36 ty::Predicate::Projection(tcx.anonymize_late_bound_regions(data)),
38 ty::Predicate::WellFormed(data) =>
39 ty::Predicate::WellFormed(data),
41 ty::Predicate::ObjectSafe(data) =>
42 ty::Predicate::ObjectSafe(data),
44 ty::Predicate::ClosureKind(closure_def_id, kind) =>
45 ty::Predicate::ClosureKind(closure_def_id, kind),
47 ty::Predicate::Subtype(ref data) =>
48 ty::Predicate::Subtype(tcx.anonymize_late_bound_regions(data)),
53 struct PredicateSet<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
54 tcx: TyCtxt<'a, 'gcx, 'tcx>,
55 set: FxHashSet<ty::Predicate<'tcx>>,
58 impl<'a, 'gcx, 'tcx> PredicateSet<'a, 'gcx, 'tcx> {
59 fn new(tcx: TyCtxt<'a, 'gcx, 'tcx>) -> PredicateSet<'a, 'gcx, 'tcx> {
60 PredicateSet { tcx: tcx, set: FxHashSet() }
63 fn insert(&mut self, pred: &ty::Predicate<'tcx>) -> bool {
64 // We have to be careful here because we want
66 // for<'a> Foo<&'a int>
70 // for<'b> Foo<&'b int>
72 // to be considered equivalent. So normalize all late-bound
73 // regions before we throw things into the underlying set.
74 self.set.insert(anonymize_predicate(self.tcx, pred))
78 ///////////////////////////////////////////////////////////////////////////
79 // `Elaboration` iterator
80 ///////////////////////////////////////////////////////////////////////////
82 /// "Elaboration" is the process of identifying all the predicates that
83 /// are implied by a source predicate. Currently this basically means
84 /// walking the "supertraits" and other similar assumptions. For
85 /// example, if we know that `T : Ord`, the elaborator would deduce
86 /// that `T : PartialOrd` holds as well. Similarly, if we have `trait
87 /// Foo : 'static`, and we know that `T : Foo`, then we know that `T :
89 pub struct Elaborator<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
90 stack: Vec<ty::Predicate<'tcx>>,
91 visited: PredicateSet<'a, 'gcx, 'tcx>,
94 pub fn elaborate_trait_ref<'cx, 'gcx, 'tcx>(
95 tcx: TyCtxt<'cx, 'gcx, 'tcx>,
96 trait_ref: ty::PolyTraitRef<'tcx>)
97 -> Elaborator<'cx, 'gcx, 'tcx>
99 elaborate_predicates(tcx, vec![trait_ref.to_predicate()])
102 pub fn elaborate_trait_refs<'cx, 'gcx, 'tcx>(
103 tcx: TyCtxt<'cx, 'gcx, 'tcx>,
104 trait_refs: &[ty::PolyTraitRef<'tcx>])
105 -> Elaborator<'cx, 'gcx, 'tcx>
107 let predicates = trait_refs.iter()
108 .map(|trait_ref| trait_ref.to_predicate())
110 elaborate_predicates(tcx, predicates)
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>
118 let mut visited = PredicateSet::new(tcx);
119 predicates.retain(|pred| visited.insert(pred));
120 Elaborator { stack: predicates, visited: visited }
123 impl<'cx, 'gcx, 'tcx> Elaborator<'cx, 'gcx, 'tcx> {
124 pub fn filter_to_traits(self) -> FilterToTraits<Self> {
125 FilterToTraits::new(self)
128 fn push(&mut self, predicate: &ty::Predicate<'tcx>) {
129 let tcx = self.visited.tcx;
131 ty::Predicate::Trait(ref data) => {
132 // Predicates declared on the trait.
133 let predicates = tcx.item_super_predicates(data.def_id());
135 let mut predicates: Vec<_> =
136 predicates.predicates
138 .map(|p| p.subst_supertrait(tcx, &data.to_poly_trait_ref()))
141 debug!("super_predicates: data={:?} predicates={:?}",
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
149 predicates.retain(|r| self.visited.insert(r));
151 self.stack.extend(predicates);
153 ty::Predicate::WellFormed(..) => {
154 // Currently, we do not elaborate WF predicates,
155 // although we easily could.
157 ty::Predicate::ObjectSafe(..) => {
158 // Currently, we do not elaborate object-safe
161 ty::Predicate::Equate(..) => {
162 // Currently, we do not "elaborate" predicates like
163 // `X == Y`, though conceivably we might. For example,
164 // `&X == &Y` implies that `X == Y`.
166 ty::Predicate::Subtype(..) => {
167 // Currently, we do not "elaborate" predicates like `X
168 // <: Y`, though conceivably we might.
170 ty::Predicate::Projection(..) => {
171 // Nothing to elaborate in a projection predicate.
173 ty::Predicate::ClosureKind(..) => {
174 // Nothing to elaborate when waiting for a closure's kind to be inferred.
177 ty::Predicate::RegionOutlives(..) => {
178 // Nothing to elaborate from `'a: 'b`.
181 ty::Predicate::TypeOutlives(ref data) => {
182 // We know that `T: 'a` for some type `T`. We can
183 // often elaborate this. For example, if we know that
184 // `[U]: 'a`, that implies that `U: 'a`. Similarly, if
185 // we know `&'a U: 'b`, then we know that `'a: 'b` and
188 // We can basically ignore bound regions here. So for
189 // example `for<'c> Foo<'a,'c>: 'b` can be elaborated to
192 // Ignore `for<'a> T: 'a` -- we might in the future
193 // consider this as evidence that `T: 'static`, but
194 // I'm a bit wary of such constructions and so for now
195 // I want to be conservative. --nmatsakis
196 let ty_max = data.skip_binder().0;
197 let r_min = data.skip_binder().1;
198 if r_min.is_bound() {
202 let visited = &mut self.visited;
204 tcx.outlives_components(ty_max)
206 .filter_map(|component| match component {
207 Component::Region(r) => if r.is_bound() {
210 Some(ty::Predicate::RegionOutlives(
211 ty::Binder(ty::OutlivesPredicate(r, r_min))))
214 Component::Param(p) => {
215 let ty = tcx.mk_param(p.idx, p.name);
216 Some(ty::Predicate::TypeOutlives(
217 ty::Binder(ty::OutlivesPredicate(ty, r_min))))
220 Component::UnresolvedInferenceVariable(_) => {
224 Component::Projection(_) |
225 Component::EscapingProjection(_) => {
226 // We can probably do more here. This
227 // corresponds to a case like `<T as
232 .filter(|p| visited.insert(p)));
238 impl<'cx, 'gcx, 'tcx> Iterator for Elaborator<'cx, 'gcx, 'tcx> {
239 type Item = ty::Predicate<'tcx>;
241 fn next(&mut self) -> Option<ty::Predicate<'tcx>> {
242 // Extract next item from top-most stack frame, if any.
243 let next_predicate = match self.stack.pop() {
244 Some(predicate) => predicate,
246 // No more stack frames. Done.
250 self.push(&next_predicate);
251 return Some(next_predicate);
255 ///////////////////////////////////////////////////////////////////////////
256 // Supertrait iterator
257 ///////////////////////////////////////////////////////////////////////////
259 pub type Supertraits<'cx, 'gcx, 'tcx> = FilterToTraits<Elaborator<'cx, 'gcx, 'tcx>>;
261 pub fn supertraits<'cx, 'gcx, 'tcx>(tcx: TyCtxt<'cx, 'gcx, 'tcx>,
262 trait_ref: ty::PolyTraitRef<'tcx>)
263 -> Supertraits<'cx, 'gcx, 'tcx>
265 elaborate_trait_ref(tcx, trait_ref).filter_to_traits()
268 pub fn transitive_bounds<'cx, 'gcx, 'tcx>(tcx: TyCtxt<'cx, 'gcx, 'tcx>,
269 bounds: &[ty::PolyTraitRef<'tcx>])
270 -> Supertraits<'cx, 'gcx, 'tcx>
272 elaborate_trait_refs(tcx, bounds).filter_to_traits()
275 ///////////////////////////////////////////////////////////////////////////
276 // Iterator over def-ids of supertraits
278 pub struct SupertraitDefIds<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
279 tcx: TyCtxt<'a, 'gcx, 'tcx>,
281 visited: FxHashSet<DefId>,
284 pub fn supertrait_def_ids<'cx, 'gcx, 'tcx>(tcx: TyCtxt<'cx, 'gcx, 'tcx>,
286 -> SupertraitDefIds<'cx, 'gcx, 'tcx>
290 stack: vec![trait_def_id],
291 visited: Some(trait_def_id).into_iter().collect(),
295 impl<'cx, 'gcx, 'tcx> Iterator for SupertraitDefIds<'cx, 'gcx, 'tcx> {
298 fn next(&mut self) -> Option<DefId> {
299 let def_id = match self.stack.pop() {
300 Some(def_id) => def_id,
301 None => { return None; }
304 let predicates = self.tcx.item_super_predicates(def_id);
305 let visited = &mut self.visited;
307 predicates.predicates
309 .filter_map(|p| p.to_opt_poly_trait_ref())
311 .filter(|&super_def_id| visited.insert(super_def_id)));
316 ///////////////////////////////////////////////////////////////////////////
318 ///////////////////////////////////////////////////////////////////////////
320 /// A filter around an iterator of predicates that makes it yield up
321 /// just trait references.
322 pub struct FilterToTraits<I> {
326 impl<I> FilterToTraits<I> {
327 fn new(base: I) -> FilterToTraits<I> {
328 FilterToTraits { base_iterator: base }
332 impl<'tcx,I:Iterator<Item=ty::Predicate<'tcx>>> Iterator for FilterToTraits<I> {
333 type Item = ty::PolyTraitRef<'tcx>;
335 fn next(&mut self) -> Option<ty::PolyTraitRef<'tcx>> {
337 match self.base_iterator.next() {
341 Some(ty::Predicate::Trait(data)) => {
342 return Some(data.to_poly_trait_ref());
351 ///////////////////////////////////////////////////////////////////////////
353 ///////////////////////////////////////////////////////////////////////////
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>,
360 impl_substs: &Substs<'tcx>)
361 -> (ty::TraitRef<'tcx>,
362 Vec<PredicateObligation<'tcx>>)
365 selcx.tcx().impl_trait_ref(impl_def_id).unwrap();
367 impl_trait_ref.subst(selcx.tcx(), impl_substs);
368 let Normalized { value: impl_trait_ref, obligations: normalization_obligations1 } =
369 super::normalize(selcx, ObligationCause::dummy(), &impl_trait_ref);
371 let predicates = selcx.tcx().item_predicates(impl_def_id);
372 let predicates = predicates.instantiate(selcx.tcx(), impl_substs);
373 let Normalized { value: predicates, obligations: normalization_obligations2 } =
374 super::normalize(selcx, ObligationCause::dummy(), &predicates);
375 let impl_obligations =
376 predicates_for_generics(ObligationCause::dummy(), 0, &predicates);
378 let impl_obligations: Vec<_> =
379 impl_obligations.into_iter()
380 .chain(normalization_obligations1)
381 .chain(normalization_obligations2)
384 (impl_trait_ref, impl_obligations)
387 /// See `super::obligations_for_generics`
388 pub fn predicates_for_generics<'tcx>(cause: ObligationCause<'tcx>,
389 recursion_depth: usize,
390 generic_bounds: &ty::InstantiatedPredicates<'tcx>)
391 -> Vec<PredicateObligation<'tcx>>
393 debug!("predicates_for_generics(generic_bounds={:?})",
396 generic_bounds.predicates.iter().map(|predicate| {
397 Obligation { cause: cause.clone(),
398 recursion_depth: recursion_depth,
399 predicate: predicate.clone() }
403 pub fn predicate_for_trait_ref<'tcx>(
404 cause: ObligationCause<'tcx>,
405 trait_ref: ty::TraitRef<'tcx>,
406 recursion_depth: usize)
407 -> PredicateObligation<'tcx>
411 recursion_depth: recursion_depth,
412 predicate: trait_ref.to_predicate(),
416 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
417 pub fn predicate_for_trait_def(self,
418 cause: ObligationCause<'tcx>,
420 recursion_depth: usize,
422 ty_params: &[Ty<'tcx>])
423 -> PredicateObligation<'tcx>
425 let trait_ref = ty::TraitRef {
426 def_id: trait_def_id,
427 substs: self.mk_substs_trait(param_ty, ty_params)
429 predicate_for_trait_ref(cause, trait_ref, recursion_depth)
432 /// Cast a trait reference into a reference to one of its super
433 /// traits; returns `None` if `target_trait_def_id` is not a
435 pub fn upcast_choices(self,
436 source_trait_ref: ty::PolyTraitRef<'tcx>,
437 target_trait_def_id: DefId)
438 -> Vec<ty::PolyTraitRef<'tcx>>
440 if source_trait_ref.def_id() == target_trait_def_id {
441 return vec![source_trait_ref]; // shorcut the most common case
444 supertraits(self, source_trait_ref)
445 .filter(|r| r.def_id() == target_trait_def_id)
449 /// Given a trait `trait_ref`, returns the number of vtable entries
450 /// that come from `trait_ref`, excluding its supertraits. Used in
451 /// computing the vtable base for an upcast trait of a trait object.
452 pub fn count_own_vtable_entries(self, trait_ref: ty::PolyTraitRef<'tcx>) -> usize {
454 // Count number of methods and add them to the total offset.
455 // Skip over associated types and constants.
456 for trait_item in self.associated_items(trait_ref.def_id()) {
457 if trait_item.kind == ty::AssociatedKind::Method {
464 /// Given an upcast trait object described by `object`, returns the
465 /// index of the method `method_def_id` (which should be part of
466 /// `object.upcast_trait_ref`) within the vtable for `object`.
467 pub fn get_vtable_index_of_object_method<N>(self,
468 object: &super::VtableObjectData<'tcx, N>,
469 method_def_id: DefId) -> usize {
470 // Count number of methods preceding the one we are selecting and
471 // add them to the total offset.
472 // Skip over associated types and constants.
473 let mut entries = object.vtable_base;
474 for trait_item in self.associated_items(object.upcast_trait_ref.def_id()) {
475 if trait_item.def_id == method_def_id {
476 // The item with the ID we were given really ought to be a method.
477 assert_eq!(trait_item.kind, ty::AssociatedKind::Method);
480 if trait_item.kind == ty::AssociatedKind::Method {
485 bug!("get_vtable_index_of_object_method: {:?} was not found",
489 pub fn closure_trait_ref_and_return_type(self,
490 fn_trait_def_id: DefId,
492 sig: ty::PolyFnSig<'tcx>,
493 tuple_arguments: TupleArgumentsFlag)
494 -> ty::Binder<(ty::TraitRef<'tcx>, Ty<'tcx>)>
496 let arguments_tuple = match tuple_arguments {
497 TupleArgumentsFlag::No => sig.skip_binder().inputs()[0],
498 TupleArgumentsFlag::Yes =>
499 self.intern_tup(sig.skip_binder().inputs(), false),
501 let trait_ref = ty::TraitRef {
502 def_id: fn_trait_def_id,
503 substs: self.mk_substs_trait(self_ty, &[arguments_tuple]),
505 ty::Binder((trait_ref, sig.skip_binder().output()))
509 pub enum TupleArgumentsFlag { Yes, No }