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::{Kind, Subst, Substs};
13 use ty::{self, Ty, TyCtxt, ToPredicate, ToPolyTraitRef};
14 use ty::outlives::Component;
15 use util::nodemap::FxHashSet;
17 use traits::specialize::specialization_graph::NodeItem;
19 use super::{Obligation, ObligationCause, PredicateObligation, SelectionContext, Normalized};
21 fn anonymize_predicate<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
22 pred: &ty::Predicate<'tcx>)
23 -> ty::Predicate<'tcx> {
25 ty::Predicate::Trait(ref data) =>
26 ty::Predicate::Trait(tcx.anonymize_late_bound_regions(data)),
28 ty::Predicate::RegionOutlives(ref data) =>
29 ty::Predicate::RegionOutlives(tcx.anonymize_late_bound_regions(data)),
31 ty::Predicate::TypeOutlives(ref data) =>
32 ty::Predicate::TypeOutlives(tcx.anonymize_late_bound_regions(data)),
34 ty::Predicate::Projection(ref data) =>
35 ty::Predicate::Projection(tcx.anonymize_late_bound_regions(data)),
37 ty::Predicate::WellFormed(data) =>
38 ty::Predicate::WellFormed(data),
40 ty::Predicate::ObjectSafe(data) =>
41 ty::Predicate::ObjectSafe(data),
43 ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind) =>
44 ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind),
46 ty::Predicate::Subtype(ref data) =>
47 ty::Predicate::Subtype(tcx.anonymize_late_bound_regions(data)),
49 ty::Predicate::ConstEvaluatable(def_id, substs) =>
50 ty::Predicate::ConstEvaluatable(def_id, substs),
55 struct PredicateSet<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
56 tcx: TyCtxt<'a, 'gcx, 'tcx>,
57 set: FxHashSet<ty::Predicate<'tcx>>,
60 impl<'a, 'gcx, 'tcx> PredicateSet<'a, 'gcx, 'tcx> {
61 fn new(tcx: TyCtxt<'a, 'gcx, 'tcx>) -> PredicateSet<'a, 'gcx, 'tcx> {
62 PredicateSet { tcx: tcx, set: FxHashSet() }
65 fn insert(&mut self, pred: &ty::Predicate<'tcx>) -> bool {
66 // We have to be careful here because we want
68 // for<'a> Foo<&'a int>
72 // for<'b> Foo<&'b int>
74 // to be considered equivalent. So normalize all late-bound
75 // regions before we throw things into the underlying set.
76 self.set.insert(anonymize_predicate(self.tcx, pred))
80 ///////////////////////////////////////////////////////////////////////////
81 // `Elaboration` iterator
82 ///////////////////////////////////////////////////////////////////////////
84 /// "Elaboration" is the process of identifying all the predicates that
85 /// are implied by a source predicate. Currently this basically means
86 /// walking the "supertraits" and other similar assumptions. For
87 /// example, if we know that `T : Ord`, the elaborator would deduce
88 /// that `T : PartialOrd` holds as well. Similarly, if we have `trait
89 /// Foo : 'static`, and we know that `T : Foo`, then we know that `T :
91 pub struct Elaborator<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
92 stack: Vec<ty::Predicate<'tcx>>,
93 visited: PredicateSet<'a, 'gcx, 'tcx>,
96 pub fn elaborate_trait_ref<'cx, 'gcx, 'tcx>(
97 tcx: TyCtxt<'cx, 'gcx, 'tcx>,
98 trait_ref: ty::PolyTraitRef<'tcx>)
99 -> Elaborator<'cx, 'gcx, 'tcx>
101 elaborate_predicates(tcx, vec![trait_ref.to_predicate()])
104 pub fn elaborate_trait_refs<'cx, 'gcx, 'tcx>(
105 tcx: TyCtxt<'cx, 'gcx, 'tcx>,
106 trait_refs: &[ty::PolyTraitRef<'tcx>])
107 -> Elaborator<'cx, 'gcx, 'tcx>
109 let predicates = trait_refs.iter()
110 .map(|trait_ref| trait_ref.to_predicate())
112 elaborate_predicates(tcx, predicates)
115 pub fn elaborate_predicates<'cx, 'gcx, 'tcx>(
116 tcx: TyCtxt<'cx, 'gcx, 'tcx>,
117 mut predicates: Vec<ty::Predicate<'tcx>>)
118 -> Elaborator<'cx, 'gcx, 'tcx>
120 let mut visited = PredicateSet::new(tcx);
121 predicates.retain(|pred| visited.insert(pred));
122 Elaborator { stack: predicates, visited: visited }
125 impl<'cx, 'gcx, 'tcx> Elaborator<'cx, 'gcx, 'tcx> {
126 pub fn filter_to_traits(self) -> FilterToTraits<Self> {
127 FilterToTraits::new(self)
130 fn push(&mut self, predicate: &ty::Predicate<'tcx>) {
131 let tcx = self.visited.tcx;
133 ty::Predicate::Trait(ref data) => {
134 // Predicates declared on the trait.
135 let predicates = tcx.super_predicates_of(data.def_id());
137 let mut predicates: Vec<_> =
138 predicates.predicates
140 .map(|p| p.subst_supertrait(tcx, &data.to_poly_trait_ref()))
143 debug!("super_predicates: data={:?} predicates={:?}",
146 // Only keep those bounds that we haven't already
147 // seen. This is necessary to prevent infinite
148 // recursion in some cases. One common case is when
149 // people define `trait Sized: Sized { }` rather than `trait
151 predicates.retain(|r| self.visited.insert(r));
153 self.stack.extend(predicates);
155 ty::Predicate::WellFormed(..) => {
156 // Currently, we do not elaborate WF predicates,
157 // although we easily could.
159 ty::Predicate::ObjectSafe(..) => {
160 // Currently, we do not elaborate object-safe
163 ty::Predicate::Subtype(..) => {
164 // Currently, we do not "elaborate" predicates like `X
165 // <: Y`, though conceivably we might.
167 ty::Predicate::Projection(..) => {
168 // Nothing to elaborate in a projection predicate.
170 ty::Predicate::ClosureKind(..) => {
171 // Nothing to elaborate when waiting for a closure's kind to be inferred.
173 ty::Predicate::ConstEvaluatable(..) => {
174 // Currently, we do not elaborate const-evaluatable
178 ty::Predicate::RegionOutlives(..) => {
179 // Nothing to elaborate from `'a: 'b`.
182 ty::Predicate::TypeOutlives(ref data) => {
183 // We know that `T: 'a` for some type `T`. We can
184 // often elaborate this. For example, if we know that
185 // `[U]: 'a`, that implies that `U: 'a`. Similarly, if
186 // we know `&'a U: 'b`, then we know that `'a: 'b` and
189 // We can basically ignore bound regions here. So for
190 // example `for<'c> Foo<'a,'c>: 'b` can be elaborated to
193 // Ignore `for<'a> T: 'a` -- we might in the future
194 // consider this as evidence that `T: 'static`, but
195 // I'm a bit wary of such constructions and so for now
196 // I want to be conservative. --nmatsakis
197 let ty_max = data.skip_binder().0;
198 let r_min = data.skip_binder().1;
199 if r_min.is_late_bound() {
203 let visited = &mut self.visited;
205 tcx.outlives_components(ty_max)
207 .filter_map(|component| match component {
208 Component::Region(r) => if r.is_late_bound() {
211 Some(ty::Predicate::RegionOutlives(
212 ty::Binder::dummy(ty::OutlivesPredicate(r, r_min))))
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))))
221 Component::UnresolvedInferenceVariable(_) => {
225 Component::Projection(_) |
226 Component::EscapingProjection(_) => {
227 // We can probably do more here. This
228 // corresponds to a case like `<T as
233 .filter(|p| visited.insert(p)));
239 impl<'cx, 'gcx, 'tcx> Iterator for Elaborator<'cx, 'gcx, 'tcx> {
240 type Item = ty::Predicate<'tcx>;
242 fn next(&mut self) -> Option<ty::Predicate<'tcx>> {
243 // Extract next item from top-most stack frame, if any.
244 let next_predicate = match self.stack.pop() {
245 Some(predicate) => predicate,
247 // No more stack frames. Done.
251 self.push(&next_predicate);
252 return Some(next_predicate);
256 ///////////////////////////////////////////////////////////////////////////
257 // Supertrait iterator
258 ///////////////////////////////////////////////////////////////////////////
260 pub type Supertraits<'cx, 'gcx, 'tcx> = FilterToTraits<Elaborator<'cx, 'gcx, 'tcx>>;
262 pub fn supertraits<'cx, 'gcx, 'tcx>(tcx: TyCtxt<'cx, 'gcx, 'tcx>,
263 trait_ref: ty::PolyTraitRef<'tcx>)
264 -> Supertraits<'cx, 'gcx, 'tcx>
266 elaborate_trait_ref(tcx, trait_ref).filter_to_traits()
269 pub fn transitive_bounds<'cx, 'gcx, 'tcx>(tcx: TyCtxt<'cx, 'gcx, 'tcx>,
270 bounds: &[ty::PolyTraitRef<'tcx>])
271 -> Supertraits<'cx, 'gcx, 'tcx>
273 elaborate_trait_refs(tcx, bounds).filter_to_traits()
276 ///////////////////////////////////////////////////////////////////////////
277 // Iterator over def-ids of supertraits
279 pub struct SupertraitDefIds<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
280 tcx: TyCtxt<'a, 'gcx, 'tcx>,
282 visited: FxHashSet<DefId>,
285 pub fn supertrait_def_ids<'cx, 'gcx, 'tcx>(tcx: TyCtxt<'cx, 'gcx, 'tcx>,
287 -> SupertraitDefIds<'cx, 'gcx, 'tcx>
291 stack: vec![trait_def_id],
292 visited: Some(trait_def_id).into_iter().collect(),
296 impl<'cx, 'gcx, 'tcx> Iterator for SupertraitDefIds<'cx, 'gcx, 'tcx> {
299 fn next(&mut self) -> Option<DefId> {
300 let def_id = match self.stack.pop() {
301 Some(def_id) => def_id,
302 None => { return None; }
305 let predicates = self.tcx.super_predicates_of(def_id);
306 let visited = &mut self.visited;
308 predicates.predicates
310 .filter_map(|p| p.to_opt_poly_trait_ref())
312 .filter(|&super_def_id| visited.insert(super_def_id)));
317 ///////////////////////////////////////////////////////////////////////////
319 ///////////////////////////////////////////////////////////////////////////
321 /// A filter around an iterator of predicates that makes it yield up
322 /// just trait references.
323 pub struct FilterToTraits<I> {
327 impl<I> FilterToTraits<I> {
328 fn new(base: I) -> FilterToTraits<I> {
329 FilterToTraits { base_iterator: base }
333 impl<'tcx,I:Iterator<Item=ty::Predicate<'tcx>>> Iterator for FilterToTraits<I> {
334 type Item = ty::PolyTraitRef<'tcx>;
336 fn next(&mut self) -> Option<ty::PolyTraitRef<'tcx>> {
338 match self.base_iterator.next() {
342 Some(ty::Predicate::Trait(data)) => {
343 return Some(data.to_poly_trait_ref());
351 fn size_hint(&self) -> (usize, Option<usize>) {
352 let (_, upper) = self.base_iterator.size_hint();
357 ///////////////////////////////////////////////////////////////////////////
359 ///////////////////////////////////////////////////////////////////////////
361 /// Instantiate all bound parameters of the impl with the given substs,
362 /// returning the resulting trait ref and all obligations that arise.
363 /// The obligations are closed under normalization.
364 pub fn impl_trait_ref_and_oblig<'a, 'gcx, 'tcx>(selcx: &mut SelectionContext<'a, 'gcx, 'tcx>,
365 param_env: ty::ParamEnv<'tcx>,
367 impl_substs: &Substs<'tcx>)
368 -> (ty::TraitRef<'tcx>,
369 Vec<PredicateObligation<'tcx>>)
372 selcx.tcx().impl_trait_ref(impl_def_id).unwrap();
374 impl_trait_ref.subst(selcx.tcx(), impl_substs);
375 let Normalized { value: impl_trait_ref, obligations: normalization_obligations1 } =
376 super::normalize(selcx, param_env, ObligationCause::dummy(), &impl_trait_ref);
378 let predicates = selcx.tcx().predicates_of(impl_def_id);
379 let predicates = predicates.instantiate(selcx.tcx(), impl_substs);
380 let Normalized { value: predicates, obligations: normalization_obligations2 } =
381 super::normalize(selcx, param_env, ObligationCause::dummy(), &predicates);
382 let impl_obligations =
383 predicates_for_generics(ObligationCause::dummy(), 0, param_env, &predicates);
385 let impl_obligations: Vec<_> =
386 impl_obligations.into_iter()
387 .chain(normalization_obligations1)
388 .chain(normalization_obligations2)
391 (impl_trait_ref, impl_obligations)
394 /// See `super::obligations_for_generics`
395 pub fn predicates_for_generics<'tcx>(cause: ObligationCause<'tcx>,
396 recursion_depth: usize,
397 param_env: ty::ParamEnv<'tcx>,
398 generic_bounds: &ty::InstantiatedPredicates<'tcx>)
399 -> Vec<PredicateObligation<'tcx>>
401 debug!("predicates_for_generics(generic_bounds={:?})",
404 generic_bounds.predicates.iter().map(|predicate| {
405 Obligation { cause: cause.clone(),
408 predicate: predicate.clone() }
412 pub fn predicate_for_trait_ref<'tcx>(
413 cause: ObligationCause<'tcx>,
414 param_env: ty::ParamEnv<'tcx>,
415 trait_ref: ty::TraitRef<'tcx>,
416 recursion_depth: usize)
417 -> PredicateObligation<'tcx>
423 predicate: trait_ref.to_predicate(),
427 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
428 pub fn predicate_for_trait_def(self,
429 param_env: ty::ParamEnv<'tcx>,
430 cause: ObligationCause<'tcx>,
432 recursion_depth: usize,
434 params: &[Kind<'tcx>])
435 -> PredicateObligation<'tcx>
437 let trait_ref = ty::TraitRef {
438 def_id: trait_def_id,
439 substs: self.mk_substs_trait(self_ty, params)
441 predicate_for_trait_ref(cause, param_env, trait_ref, recursion_depth)
444 /// Cast a trait reference into a reference to one of its super
445 /// traits; returns `None` if `target_trait_def_id` is not a
447 pub fn upcast_choices(self,
448 source_trait_ref: ty::PolyTraitRef<'tcx>,
449 target_trait_def_id: DefId)
450 -> Vec<ty::PolyTraitRef<'tcx>>
452 if source_trait_ref.def_id() == target_trait_def_id {
453 return vec![source_trait_ref]; // shorcut the most common case
456 supertraits(self, source_trait_ref)
457 .filter(|r| r.def_id() == target_trait_def_id)
461 /// Given a trait `trait_ref`, returns the number of vtable entries
462 /// that come from `trait_ref`, excluding its supertraits. Used in
463 /// computing the vtable base for an upcast trait of a trait object.
464 pub fn count_own_vtable_entries(self, trait_ref: ty::PolyTraitRef<'tcx>) -> usize {
466 // Count number of methods and add them to the total offset.
467 // Skip over associated types and constants.
468 for trait_item in self.associated_items(trait_ref.def_id()) {
469 if trait_item.kind == ty::AssociatedKind::Method {
476 /// Given an upcast trait object described by `object`, returns the
477 /// index of the method `method_def_id` (which should be part of
478 /// `object.upcast_trait_ref`) within the vtable for `object`.
479 pub fn get_vtable_index_of_object_method<N>(self,
480 object: &super::VtableObjectData<'tcx, N>,
481 method_def_id: DefId) -> usize {
482 // Count number of methods preceding the one we are selecting and
483 // add them to the total offset.
484 // Skip over associated types and constants.
485 let mut entries = object.vtable_base;
486 for trait_item in self.associated_items(object.upcast_trait_ref.def_id()) {
487 if trait_item.def_id == method_def_id {
488 // The item with the ID we were given really ought to be a method.
489 assert_eq!(trait_item.kind, ty::AssociatedKind::Method);
492 if trait_item.kind == ty::AssociatedKind::Method {
497 bug!("get_vtable_index_of_object_method: {:?} was not found",
501 pub fn closure_trait_ref_and_return_type(self,
502 fn_trait_def_id: DefId,
504 sig: ty::PolyFnSig<'tcx>,
505 tuple_arguments: TupleArgumentsFlag)
506 -> ty::Binder<(ty::TraitRef<'tcx>, Ty<'tcx>)>
508 let arguments_tuple = match tuple_arguments {
509 TupleArgumentsFlag::No => sig.skip_binder().inputs()[0],
510 TupleArgumentsFlag::Yes =>
511 self.intern_tup(sig.skip_binder().inputs()),
513 let trait_ref = ty::TraitRef {
514 def_id: fn_trait_def_id,
515 substs: self.mk_substs_trait(self_ty, &[arguments_tuple.into()]),
517 ty::Binder::bind((trait_ref, sig.skip_binder().output()))
520 pub fn generator_trait_ref_and_outputs(self,
521 fn_trait_def_id: DefId,
523 sig: ty::PolyGenSig<'tcx>)
524 -> ty::Binder<(ty::TraitRef<'tcx>, Ty<'tcx>, Ty<'tcx>)>
526 let trait_ref = ty::TraitRef {
527 def_id: fn_trait_def_id,
528 substs: self.mk_substs_trait(self_ty, &[]),
530 ty::Binder::bind((trait_ref, sig.skip_binder().yield_ty, sig.skip_binder().return_ty))
533 pub fn impl_is_default(self, node_item_def_id: DefId) -> bool {
534 match self.hir.as_local_node_id(node_item_def_id) {
536 let item = self.hir.expect_item(node_id);
537 if let hir::ItemKind::Impl(_, _, defaultness, ..) = item.node {
538 defaultness.is_default()
545 .impl_defaultness(node_item_def_id)
551 pub fn impl_item_is_final(self, node_item: &NodeItem<hir::Defaultness>) -> bool {
552 node_item.item.is_final() && !self.impl_is_default(node_item.node.def_id())
556 pub enum TupleArgumentsFlag { Yes, No }