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;
9 use super::{Obligation, ObligationCause, PredicateObligation, SelectionContext, Normalized};
11 fn anonymize_predicate<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
12 pred: &ty::Predicate<'tcx>)
13 -> ty::Predicate<'tcx> {
15 ty::Predicate::Trait(ref data) =>
16 ty::Predicate::Trait(tcx.anonymize_late_bound_regions(data)),
18 ty::Predicate::RegionOutlives(ref data) =>
19 ty::Predicate::RegionOutlives(tcx.anonymize_late_bound_regions(data)),
21 ty::Predicate::TypeOutlives(ref data) =>
22 ty::Predicate::TypeOutlives(tcx.anonymize_late_bound_regions(data)),
24 ty::Predicate::Projection(ref data) =>
25 ty::Predicate::Projection(tcx.anonymize_late_bound_regions(data)),
27 ty::Predicate::WellFormed(data) =>
28 ty::Predicate::WellFormed(data),
30 ty::Predicate::ObjectSafe(data) =>
31 ty::Predicate::ObjectSafe(data),
33 ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind) =>
34 ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind),
36 ty::Predicate::Subtype(ref data) =>
37 ty::Predicate::Subtype(tcx.anonymize_late_bound_regions(data)),
39 ty::Predicate::ConstEvaluatable(def_id, substs) =>
40 ty::Predicate::ConstEvaluatable(def_id, substs),
45 struct PredicateSet<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
46 tcx: TyCtxt<'a, 'gcx, 'tcx>,
47 set: FxHashSet<ty::Predicate<'tcx>>,
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() }
55 fn insert(&mut self, pred: &ty::Predicate<'tcx>) -> bool {
56 // We have to be careful here because we want
58 // for<'a> Foo<&'a int>
62 // for<'b> Foo<&'b int>
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))
70 ///////////////////////////////////////////////////////////////////////////
71 // `Elaboration` iterator
72 ///////////////////////////////////////////////////////////////////////////
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 :
81 pub struct Elaborator<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
82 stack: Vec<ty::Predicate<'tcx>>,
83 visited: PredicateSet<'a, 'gcx, 'tcx>,
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>
91 elaborate_predicates(tcx, vec![trait_ref.to_predicate()])
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>
99 let predicates = trait_refs.map(|trait_ref| trait_ref.to_predicate())
101 elaborate_predicates(tcx, predicates)
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>
109 let mut visited = PredicateSet::new(tcx);
110 predicates.retain(|pred| visited.insert(pred));
111 Elaborator { stack: predicates, visited: visited }
114 impl<'cx, 'gcx, 'tcx> Elaborator<'cx, 'gcx, 'tcx> {
115 pub fn filter_to_traits(self) -> FilterToTraits<Self> {
116 FilterToTraits::new(self)
119 fn push(&mut self, predicate: &ty::Predicate<'tcx>) {
120 let tcx = self.visited.tcx;
122 ty::Predicate::Trait(ref data) => {
123 // Predicates declared on the trait.
124 let predicates = tcx.super_predicates_of(data.def_id());
126 let mut predicates: Vec<_> =
127 predicates.predicates
129 .map(|(p, _)| p.subst_supertrait(tcx, &data.to_poly_trait_ref()))
132 debug!("super_predicates: data={:?} predicates={:?}",
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
140 predicates.retain(|r| self.visited.insert(r));
142 self.stack.extend(predicates);
144 ty::Predicate::WellFormed(..) => {
145 // Currently, we do not elaborate WF predicates,
146 // although we easily could.
148 ty::Predicate::ObjectSafe(..) => {
149 // Currently, we do not elaborate object-safe
152 ty::Predicate::Subtype(..) => {
153 // Currently, we do not "elaborate" predicates like `X
154 // <: Y`, though conceivably we might.
156 ty::Predicate::Projection(..) => {
157 // Nothing to elaborate in a projection predicate.
159 ty::Predicate::ClosureKind(..) => {
160 // Nothing to elaborate when waiting for a closure's kind to be inferred.
162 ty::Predicate::ConstEvaluatable(..) => {
163 // Currently, we do not elaborate const-evaluatable
167 ty::Predicate::RegionOutlives(..) => {
168 // Nothing to elaborate from `'a: 'b`.
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
178 // We can basically ignore bound regions here. So for
179 // example `for<'c> Foo<'a,'c>: 'b` can be elaborated to
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() {
192 let visited = &mut self.visited;
193 let mut components = smallvec![];
194 tcx.push_outlives_components(ty_max, &mut components);
198 .filter_map(|component| match component {
199 Component::Region(r) => if r.is_late_bound() {
202 Some(ty::Predicate::RegionOutlives(
203 ty::Binder::dummy(ty::OutlivesPredicate(r, r_min))))
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))))
212 Component::UnresolvedInferenceVariable(_) => {
216 Component::Projection(_) |
217 Component::EscapingProjection(_) => {
218 // We can probably do more here. This
219 // corresponds to a case like `<T as
224 .filter(|p| visited.insert(p)));
230 impl<'cx, 'gcx, 'tcx> Iterator for Elaborator<'cx, 'gcx, 'tcx> {
231 type Item = ty::Predicate<'tcx>;
233 fn size_hint(&self) -> (usize, Option<usize>) {
234 (self.stack.len(), None)
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,
242 // No more stack frames. Done.
246 self.push(&next_predicate);
247 return Some(next_predicate);
251 ///////////////////////////////////////////////////////////////////////////
252 // Supertrait iterator
253 ///////////////////////////////////////////////////////////////////////////
255 pub type Supertraits<'cx, 'gcx, 'tcx> = FilterToTraits<Elaborator<'cx, 'gcx, 'tcx>>;
257 pub fn supertraits<'cx, 'gcx, 'tcx>(tcx: TyCtxt<'cx, 'gcx, 'tcx>,
258 trait_ref: ty::PolyTraitRef<'tcx>)
259 -> Supertraits<'cx, 'gcx, 'tcx>
261 elaborate_trait_ref(tcx, trait_ref).filter_to_traits()
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>
268 elaborate_trait_refs(tcx, bounds).filter_to_traits()
271 ///////////////////////////////////////////////////////////////////////////
272 // Iterator over def-ids of supertraits
274 pub struct SupertraitDefIds<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
275 tcx: TyCtxt<'a, 'gcx, 'tcx>,
277 visited: FxHashSet<DefId>,
280 pub fn supertrait_def_ids<'cx, 'gcx, 'tcx>(tcx: TyCtxt<'cx, 'gcx, 'tcx>,
282 -> SupertraitDefIds<'cx, 'gcx, 'tcx>
286 stack: vec![trait_def_id],
287 visited: Some(trait_def_id).into_iter().collect(),
291 impl<'cx, 'gcx, 'tcx> Iterator for SupertraitDefIds<'cx, 'gcx, 'tcx> {
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;
299 predicates.predicates
301 .filter_map(|(p, _)| p.to_opt_poly_trait_ref())
303 .filter(|&super_def_id| visited.insert(super_def_id)));
308 ///////////////////////////////////////////////////////////////////////////
310 ///////////////////////////////////////////////////////////////////////////
312 /// A filter around an iterator of predicates that makes it yield up
313 /// just trait references.
314 pub struct FilterToTraits<I> {
318 impl<I> FilterToTraits<I> {
319 fn new(base: I) -> FilterToTraits<I> {
320 FilterToTraits { base_iterator: base }
324 impl<'tcx, I: Iterator<Item = ty::Predicate<'tcx>>> Iterator for FilterToTraits<I> {
325 type Item = ty::PolyTraitRef<'tcx>;
327 fn next(&mut self) -> Option<ty::PolyTraitRef<'tcx>> {
329 match self.base_iterator.next() {
333 Some(ty::Predicate::Trait(data)) => {
334 return Some(data.to_poly_trait_ref());
341 fn size_hint(&self) -> (usize, Option<usize>) {
342 let (_, upper) = self.base_iterator.size_hint();
347 ///////////////////////////////////////////////////////////////////////////
349 ///////////////////////////////////////////////////////////////////////////
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>,
357 impl_substs: SubstsRef<'tcx>,)
358 -> (ty::TraitRef<'tcx>,
359 Vec<PredicateObligation<'tcx>>)
362 selcx.tcx().impl_trait_ref(impl_def_id).unwrap();
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);
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);
375 let impl_obligations: Vec<_> =
376 impl_obligations.into_iter()
377 .chain(normalization_obligations1)
378 .chain(normalization_obligations2)
381 (impl_trait_ref, impl_obligations)
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>>
391 debug!("predicates_for_generics(generic_bounds={:?})",
394 generic_bounds.predicates.iter().map(|predicate| {
395 Obligation { cause: cause.clone(),
398 predicate: predicate.clone() }
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>
413 predicate: trait_ref.to_predicate(),
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>,
422 recursion_depth: usize,
424 params: &[Kind<'tcx>])
425 -> PredicateObligation<'tcx>
427 let trait_ref = ty::TraitRef {
428 def_id: trait_def_id,
429 substs: self.mk_substs_trait(self_ty, params)
431 predicate_for_trait_ref(cause, param_env, trait_ref, recursion_depth)
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
437 pub fn upcast_choices(self,
438 source_trait_ref: ty::PolyTraitRef<'tcx>,
439 target_trait_def_id: DefId)
440 -> Vec<ty::PolyTraitRef<'tcx>>
442 if source_trait_ref.def_id() == target_trait_def_id {
443 return vec![source_trait_ref]; // shorcut the most common case
446 supertraits(self, source_trait_ref)
447 .filter(|r| r.def_id() == target_trait_def_id)
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 {
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 {
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);
482 if trait_item.kind == ty::AssociatedKind::Method {
487 bug!("get_vtable_index_of_object_method: {:?} was not found",
491 pub fn closure_trait_ref_and_return_type(self,
492 fn_trait_def_id: DefId,
494 sig: ty::PolyFnSig<'tcx>,
495 tuple_arguments: TupleArgumentsFlag)
496 -> ty::Binder<(ty::TraitRef<'tcx>, Ty<'tcx>)>
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()),
503 let trait_ref = ty::TraitRef {
504 def_id: fn_trait_def_id,
505 substs: self.mk_substs_trait(self_ty, &[arguments_tuple.into()]),
507 ty::Binder::bind((trait_ref, sig.skip_binder().output()))
510 pub fn generator_trait_ref_and_outputs(self,
511 fn_trait_def_id: DefId,
513 sig: ty::PolyGenSig<'tcx>)
514 -> ty::Binder<(ty::TraitRef<'tcx>, Ty<'tcx>, Ty<'tcx>)>
516 let trait_ref = ty::TraitRef {
517 def_id: fn_trait_def_id,
518 substs: self.mk_substs_trait(self_ty, &[]),
520 ty::Binder::bind((trait_ref, sig.skip_binder().yield_ty, sig.skip_binder().return_ty))
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) {
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()
535 .impl_defaultness(node_item_def_id)
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())
546 pub enum TupleArgumentsFlag { Yes, No }