1 use errors::DiagnosticBuilder;
2 use smallvec::SmallVec;
6 use crate::hir::def_id::DefId;
7 use crate::traits::specialize::specialization_graph::NodeItem;
8 use crate::ty::{self, Ty, TyCtxt, ToPredicate, ToPolyTraitRef};
9 use crate::ty::outlives::Component;
10 use crate::ty::subst::{Kind, Subst, SubstsRef};
11 use crate::util::nodemap::FxHashSet;
13 use super::{Obligation, ObligationCause, PredicateObligation, SelectionContext, Normalized};
15 fn anonymize_predicate<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
16 pred: &ty::Predicate<'tcx>)
17 -> ty::Predicate<'tcx> {
19 ty::Predicate::Trait(ref data) =>
20 ty::Predicate::Trait(tcx.anonymize_late_bound_regions(data)),
22 ty::Predicate::RegionOutlives(ref data) =>
23 ty::Predicate::RegionOutlives(tcx.anonymize_late_bound_regions(data)),
25 ty::Predicate::TypeOutlives(ref data) =>
26 ty::Predicate::TypeOutlives(tcx.anonymize_late_bound_regions(data)),
28 ty::Predicate::Projection(ref data) =>
29 ty::Predicate::Projection(tcx.anonymize_late_bound_regions(data)),
31 ty::Predicate::WellFormed(data) =>
32 ty::Predicate::WellFormed(data),
34 ty::Predicate::ObjectSafe(data) =>
35 ty::Predicate::ObjectSafe(data),
37 ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind) =>
38 ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind),
40 ty::Predicate::Subtype(ref data) =>
41 ty::Predicate::Subtype(tcx.anonymize_late_bound_regions(data)),
43 ty::Predicate::ConstEvaluatable(def_id, substs) =>
44 ty::Predicate::ConstEvaluatable(def_id, substs),
48 struct PredicateSet<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> {
49 tcx: TyCtxt<'a, 'gcx, 'tcx>,
50 set: FxHashSet<ty::Predicate<'tcx>>,
53 impl<'a, 'gcx, 'tcx> PredicateSet<'a, 'gcx, 'tcx> {
54 fn new(tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Self {
55 Self { tcx: tcx, set: Default::default() }
58 fn insert(&mut self, pred: &ty::Predicate<'tcx>) -> bool {
59 // We have to be careful here because we want
61 // for<'a> Foo<&'a int>
65 // for<'b> Foo<&'b int>
67 // to be considered equivalent. So normalize all late-bound
68 // regions before we throw things into the underlying set.
69 self.set.insert(anonymize_predicate(self.tcx, pred))
73 impl<'a, 'gcx, 'tcx, T: AsRef<ty::Predicate<'tcx>>> Extend<T> for PredicateSet<'a, 'gcx, 'tcx> {
74 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
76 self.insert(pred.as_ref());
81 ///////////////////////////////////////////////////////////////////////////
82 // `Elaboration` iterator
83 ///////////////////////////////////////////////////////////////////////////
85 /// "Elaboration" is the process of identifying all the predicates that
86 /// are implied by a source predicate. Currently this basically means
87 /// walking the "supertraits" and other similar assumptions. For example,
88 /// if we know that `T: Ord`, the elaborator would deduce that `T: PartialOrd`
89 /// holds as well. Similarly, if we have `trait Foo: 'static`, and we know that
90 /// `T: Foo`, then we know that `T: 'static`.
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: impl Iterator<Item = ty::PolyTraitRef<'tcx>>)
107 -> Elaborator<'cx, 'gcx, 'tcx>
109 let predicates = trait_refs.map(|trait_ref| trait_ref.to_predicate()).collect();
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 }
123 impl<'cx, 'gcx, 'tcx> Elaborator<'cx, 'gcx, 'tcx> {
124 pub fn filter_to_traits(self) -> FilterToTraits<Self> {
125 FilterToTraits::new(self)
128 fn elaborate(&mut self, predicate: &ty::Predicate<'tcx>) {
129 let tcx = self.visited.tcx;
131 ty::Predicate::Trait(ref data) => {
132 // Get predicates declared on the trait.
133 let predicates = tcx.super_predicates_of(data.def_id());
135 let predicates = predicates.predicates
137 .map(|(pred, _)| pred.subst_supertrait(tcx, &data.to_poly_trait_ref()));
138 debug!("super_predicates: data={:?} predicates={:?}",
139 data, predicates.clone());
141 // Only keep those bounds that we haven't already seen.
142 // This is necessary to prevent infinite recursion in some
143 // cases. One common case is when people define
144 // `trait Sized: Sized { }` rather than `trait Sized { }`.
145 let visited = &mut self.visited;
146 let predicates = predicates.filter(|pred| visited.insert(pred));
148 self.stack.extend(predicates);
150 ty::Predicate::WellFormed(..) => {
151 // Currently, we do not elaborate WF predicates,
152 // although we easily could.
154 ty::Predicate::ObjectSafe(..) => {
155 // Currently, we do not elaborate object-safe
158 ty::Predicate::Subtype(..) => {
159 // Currently, we do not "elaborate" predicates like `X <: Y`,
160 // though conceivably we might.
162 ty::Predicate::Projection(..) => {
163 // Nothing to elaborate in a projection predicate.
165 ty::Predicate::ClosureKind(..) => {
166 // Nothing to elaborate when waiting for a closure's kind to be inferred.
168 ty::Predicate::ConstEvaluatable(..) => {
169 // Currently, we do not elaborate const-evaluatable
172 ty::Predicate::RegionOutlives(..) => {
173 // Nothing to elaborate from `'a: 'b`.
175 ty::Predicate::TypeOutlives(ref data) => {
176 // We know that `T: 'a` for some type `T`. We can
177 // often elaborate this. For example, if we know that
178 // `[U]: 'a`, that implies that `U: 'a`. Similarly, if
179 // we know `&'a U: 'b`, then we know that `'a: 'b` and
182 // We can basically ignore bound regions here. So for
183 // example `for<'c> Foo<'a,'c>: 'b` can be elaborated to
186 // Ignore `for<'a> T: 'a` -- we might in the future
187 // consider this as evidence that `T: 'static`, but
188 // I'm a bit wary of such constructions and so for now
189 // I want to be conservative. --nmatsakis
190 let ty_max = data.skip_binder().0;
191 let r_min = data.skip_binder().1;
192 if r_min.is_late_bound() {
196 let visited = &mut self.visited;
197 let mut components = smallvec![];
198 tcx.push_outlives_components(ty_max, &mut components);
202 .filter_map(|component| match component {
203 Component::Region(r) => if r.is_late_bound() {
206 Some(ty::Predicate::RegionOutlives(
207 ty::Binder::dummy(ty::OutlivesPredicate(r, r_min))))
210 Component::Param(p) => {
211 let ty = tcx.mk_ty_param(p.index, p.name);
212 Some(ty::Predicate::TypeOutlives(
213 ty::Binder::dummy(ty::OutlivesPredicate(ty, r_min))))
216 Component::UnresolvedInferenceVariable(_) => {
220 Component::Projection(_) |
221 Component::EscapingProjection(_) => {
222 // We can probably do more here. This
223 // corresponds to a case like `<T as
228 .filter(|p| visited.insert(p))
235 impl<'cx, 'gcx, 'tcx> Iterator for Elaborator<'cx, 'gcx, 'tcx> {
236 type Item = ty::Predicate<'tcx>;
238 fn size_hint(&self) -> (usize, Option<usize>) {
239 (self.stack.len(), None)
242 fn next(&mut self) -> Option<ty::Predicate<'tcx>> {
243 // Extract next item from top-most stack frame, if any.
244 if let Some(pred) = self.stack.pop() {
245 self.elaborate(&pred);
253 ///////////////////////////////////////////////////////////////////////////
254 // Supertrait iterator
255 ///////////////////////////////////////////////////////////////////////////
257 pub type Supertraits<'cx, 'gcx, 'tcx> = FilterToTraits<Elaborator<'cx, 'gcx, 'tcx>>;
259 pub fn supertraits<'cx, 'gcx, 'tcx>(tcx: TyCtxt<'cx, 'gcx, 'tcx>,
260 trait_ref: ty::PolyTraitRef<'tcx>)
261 -> Supertraits<'cx, 'gcx, 'tcx> {
262 elaborate_trait_ref(tcx, trait_ref).filter_to_traits()
265 pub fn transitive_bounds<'cx, 'gcx, 'tcx>(tcx: TyCtxt<'cx, 'gcx, 'tcx>,
266 bounds: impl Iterator<Item = ty::PolyTraitRef<'tcx>>)
267 -> Supertraits<'cx, 'gcx, 'tcx> {
268 elaborate_trait_refs(tcx, bounds).filter_to_traits()
271 ///////////////////////////////////////////////////////////////////////////
272 // `TraitAliasExpander` iterator
273 ///////////////////////////////////////////////////////////////////////////
275 /// "Trait alias expansion" is the process of expanding a sequence of trait
276 /// references into another sequence by transitively following all trait
277 /// aliases. e.g. If you have bounds like `Foo + Send`, a trait alias
278 /// `trait Foo = Bar + Sync;`, and another trait alias
279 /// `trait Bar = Read + Write`, then the bounds would expand to
280 /// `Read + Write + Sync + Send`.
281 /// Expansion is done via a DFS (depth-first search), and the `visited` field
282 /// is used to avoid cycles.
283 pub struct TraitAliasExpander<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> {
284 tcx: TyCtxt<'a, 'gcx, 'tcx>,
285 stack: Vec<TraitAliasExpansionInfo<'tcx>>,
288 /// Stores information about the expansion of a trait via a path of zero or more trait aliases.
289 #[derive(Debug, Clone)]
290 pub struct TraitAliasExpansionInfo<'tcx> {
291 pub path: SmallVec<[(ty::PolyTraitRef<'tcx>, Span); 4]>,
294 impl<'tcx> TraitAliasExpansionInfo<'tcx> {
295 fn new(trait_ref: ty::PolyTraitRef<'tcx>, span: Span) -> Self {
297 path: smallvec![(trait_ref, span)]
301 /// Adds diagnostic labels to `diag` for the expansion path of a trait through all intermediate
303 pub fn label_with_exp_info(&self,
304 diag: &mut DiagnosticBuilder<'_>,
308 diag.span_label(self.top().1, top_label);
309 if self.path.len() > 1 {
310 for (_, sp) in self.path.iter().rev().skip(1).take(self.path.len() - 2) {
311 diag.span_label(*sp, format!("referenced here ({})", use_desc));
314 diag.span_label(self.bottom().1,
315 format!("trait alias used in trait object type ({})", use_desc));
318 pub fn trait_ref(&self) -> &ty::PolyTraitRef<'tcx> {
322 pub fn top(&self) -> &(ty::PolyTraitRef<'tcx>, Span) {
323 self.path.last().unwrap()
326 pub fn bottom(&self) -> &(ty::PolyTraitRef<'tcx>, Span) {
327 self.path.first().unwrap()
330 fn clone_and_push(&self, trait_ref: ty::PolyTraitRef<'tcx>, span: Span) -> Self {
331 let mut path = self.path.clone();
332 path.push((trait_ref, span));
340 pub fn expand_trait_aliases<'cx, 'gcx, 'tcx>(
341 tcx: TyCtxt<'cx, 'gcx, 'tcx>,
342 trait_refs: impl IntoIterator<Item = (ty::PolyTraitRef<'tcx>, Span)>
343 ) -> TraitAliasExpander<'cx, 'gcx, 'tcx> {
344 let items: Vec<_> = trait_refs
346 .map(|(trait_ref, span)| TraitAliasExpansionInfo::new(trait_ref, span))
348 TraitAliasExpander { tcx, stack: items }
351 impl<'cx, 'gcx, 'tcx> TraitAliasExpander<'cx, 'gcx, 'tcx> {
352 /// If `item` is a trait alias and its predicate has not yet been visited, then expands `item`
353 /// to the definition, pushes the resulting expansion onto `self.stack`, and returns `false`.
354 /// Otherwise, immediately returns `true` if `item` is a regular trait, or `false` if it is a
356 /// The return value indicates whether `item` should be yielded to the user.
357 fn expand(&mut self, item: &TraitAliasExpansionInfo<'tcx>) -> bool {
359 let trait_ref = item.trait_ref();
360 let pred = trait_ref.to_predicate();
362 debug!("expand_trait_aliases: trait_ref={:?}", trait_ref);
364 // Don't recurse if this bound is not a trait alias.
365 let is_alias = tcx.is_trait_alias(trait_ref.def_id());
370 // Don't recurse if this trait alias is already on the stack for the DFS search.
371 let anon_pred = anonymize_predicate(tcx, &pred);
372 if item.path.iter().rev().skip(1)
373 .any(|(tr, _)| anonymize_predicate(tcx, &tr.to_predicate()) == anon_pred) {
377 // Get components of trait alias.
378 let predicates = tcx.super_predicates_of(trait_ref.def_id());
380 let items = predicates.predicates
383 .filter_map(|(pred, span)| {
384 pred.subst_supertrait(tcx, &trait_ref)
385 .to_opt_poly_trait_ref()
386 .map(|trait_ref| item.clone_and_push(trait_ref, *span))
388 debug!("expand_trait_aliases: items={:?}", items.clone());
390 self.stack.extend(items);
396 impl<'cx, 'gcx, 'tcx> Iterator for TraitAliasExpander<'cx, 'gcx, 'tcx> {
397 type Item = TraitAliasExpansionInfo<'tcx>;
399 fn size_hint(&self) -> (usize, Option<usize>) {
400 (self.stack.len(), None)
403 fn next(&mut self) -> Option<TraitAliasExpansionInfo<'tcx>> {
404 while let Some(item) = self.stack.pop() {
405 if self.expand(&item) {
413 ///////////////////////////////////////////////////////////////////////////
414 // Iterator over def-IDs of supertraits
415 ///////////////////////////////////////////////////////////////////////////
417 pub struct SupertraitDefIds<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
418 tcx: TyCtxt<'a, 'gcx, 'tcx>,
420 visited: FxHashSet<DefId>,
423 pub fn supertrait_def_ids<'cx, 'gcx, 'tcx>(tcx: TyCtxt<'cx, 'gcx, 'tcx>,
425 -> SupertraitDefIds<'cx, 'gcx, 'tcx>
429 stack: vec![trait_def_id],
430 visited: Some(trait_def_id).into_iter().collect(),
434 impl<'cx, 'gcx, 'tcx> Iterator for SupertraitDefIds<'cx, 'gcx, 'tcx> {
437 fn next(&mut self) -> Option<DefId> {
438 let def_id = self.stack.pop()?;
439 let predicates = self.tcx.super_predicates_of(def_id);
440 let visited = &mut self.visited;
442 predicates.predicates
444 .filter_map(|(pred, _)| pred.to_opt_poly_trait_ref())
445 .map(|trait_ref| trait_ref.def_id())
446 .filter(|&super_def_id| visited.insert(super_def_id)));
451 ///////////////////////////////////////////////////////////////////////////
453 ///////////////////////////////////////////////////////////////////////////
455 /// A filter around an iterator of predicates that makes it yield up
456 /// just trait references.
457 pub struct FilterToTraits<I> {
461 impl<I> FilterToTraits<I> {
462 fn new(base: I) -> FilterToTraits<I> {
463 FilterToTraits { base_iterator: base }
467 impl<'tcx, I: Iterator<Item = ty::Predicate<'tcx>>> Iterator for FilterToTraits<I> {
468 type Item = ty::PolyTraitRef<'tcx>;
470 fn next(&mut self) -> Option<ty::PolyTraitRef<'tcx>> {
471 while let Some(pred) = self.base_iterator.next() {
472 if let ty::Predicate::Trait(data) = pred {
473 return Some(data.to_poly_trait_ref());
479 fn size_hint(&self) -> (usize, Option<usize>) {
480 let (_, upper) = self.base_iterator.size_hint();
485 ///////////////////////////////////////////////////////////////////////////
487 ///////////////////////////////////////////////////////////////////////////
489 /// Instantiate all bound parameters of the impl with the given substs,
490 /// returning the resulting trait ref and all obligations that arise.
491 /// The obligations are closed under normalization.
492 pub fn impl_trait_ref_and_oblig<'a, 'gcx, 'tcx>(selcx: &mut SelectionContext<'a, 'gcx, 'tcx>,
493 param_env: ty::ParamEnv<'tcx>,
495 impl_substs: SubstsRef<'tcx>,)
496 -> (ty::TraitRef<'tcx>,
497 Vec<PredicateObligation<'tcx>>)
500 selcx.tcx().impl_trait_ref(impl_def_id).unwrap();
502 impl_trait_ref.subst(selcx.tcx(), impl_substs);
503 let Normalized { value: impl_trait_ref, obligations: normalization_obligations1 } =
504 super::normalize(selcx, param_env, ObligationCause::dummy(), &impl_trait_ref);
506 let predicates = selcx.tcx().predicates_of(impl_def_id);
507 let predicates = predicates.instantiate(selcx.tcx(), impl_substs);
508 let Normalized { value: predicates, obligations: normalization_obligations2 } =
509 super::normalize(selcx, param_env, ObligationCause::dummy(), &predicates);
510 let impl_obligations =
511 predicates_for_generics(ObligationCause::dummy(), 0, param_env, &predicates);
513 let impl_obligations: Vec<_> =
514 impl_obligations.into_iter()
515 .chain(normalization_obligations1)
516 .chain(normalization_obligations2)
519 (impl_trait_ref, impl_obligations)
522 /// See `super::obligations_for_generics`
523 pub fn predicates_for_generics<'tcx>(cause: ObligationCause<'tcx>,
524 recursion_depth: usize,
525 param_env: ty::ParamEnv<'tcx>,
526 generic_bounds: &ty::InstantiatedPredicates<'tcx>)
527 -> Vec<PredicateObligation<'tcx>>
529 debug!("predicates_for_generics(generic_bounds={:?})",
532 generic_bounds.predicates.iter().map(|predicate| {
533 Obligation { cause: cause.clone(),
536 predicate: predicate.clone() }
540 pub fn predicate_for_trait_ref<'tcx>(
541 cause: ObligationCause<'tcx>,
542 param_env: ty::ParamEnv<'tcx>,
543 trait_ref: ty::TraitRef<'tcx>,
544 recursion_depth: usize)
545 -> PredicateObligation<'tcx>
551 predicate: trait_ref.to_predicate(),
555 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
556 pub fn predicate_for_trait_def(self,
557 param_env: ty::ParamEnv<'tcx>,
558 cause: ObligationCause<'tcx>,
560 recursion_depth: usize,
562 params: &[Kind<'tcx>])
563 -> PredicateObligation<'tcx>
565 let trait_ref = ty::TraitRef {
566 def_id: trait_def_id,
567 substs: self.mk_substs_trait(self_ty, params)
569 predicate_for_trait_ref(cause, param_env, trait_ref, recursion_depth)
572 /// Cast a trait reference into a reference to one of its super
573 /// traits; returns `None` if `target_trait_def_id` is not a
575 pub fn upcast_choices(self,
576 source_trait_ref: ty::PolyTraitRef<'tcx>,
577 target_trait_def_id: DefId)
578 -> Vec<ty::PolyTraitRef<'tcx>>
580 if source_trait_ref.def_id() == target_trait_def_id {
581 return vec![source_trait_ref]; // shorcut the most common case
584 supertraits(self, source_trait_ref)
585 .filter(|r| r.def_id() == target_trait_def_id)
589 /// Given a trait `trait_ref`, returns the number of vtable entries
590 /// that come from `trait_ref`, excluding its supertraits. Used in
591 /// computing the vtable base for an upcast trait of a trait object.
592 pub fn count_own_vtable_entries(self, trait_ref: ty::PolyTraitRef<'tcx>) -> usize {
594 // Count number of methods and add them to the total offset.
595 // Skip over associated types and constants.
596 for trait_item in self.associated_items(trait_ref.def_id()) {
597 if trait_item.kind == ty::AssocKind::Method {
604 /// Given an upcast trait object described by `object`, returns the
605 /// index of the method `method_def_id` (which should be part of
606 /// `object.upcast_trait_ref`) within the vtable for `object`.
607 pub fn get_vtable_index_of_object_method<N>(self,
608 object: &super::VtableObjectData<'tcx, N>,
609 method_def_id: DefId) -> usize {
610 // Count number of methods preceding the one we are selecting and
611 // add them to the total offset.
612 // Skip over associated types and constants.
613 let mut entries = object.vtable_base;
614 for trait_item in self.associated_items(object.upcast_trait_ref.def_id()) {
615 if trait_item.def_id == method_def_id {
616 // The item with the ID we were given really ought to be a method.
617 assert_eq!(trait_item.kind, ty::AssocKind::Method);
620 if trait_item.kind == ty::AssocKind::Method {
625 bug!("get_vtable_index_of_object_method: {:?} was not found",
629 pub fn closure_trait_ref_and_return_type(self,
630 fn_trait_def_id: DefId,
632 sig: ty::PolyFnSig<'tcx>,
633 tuple_arguments: TupleArgumentsFlag)
634 -> ty::Binder<(ty::TraitRef<'tcx>, Ty<'tcx>)>
636 let arguments_tuple = match tuple_arguments {
637 TupleArgumentsFlag::No => sig.skip_binder().inputs()[0],
638 TupleArgumentsFlag::Yes =>
639 self.intern_tup(sig.skip_binder().inputs()),
641 let trait_ref = ty::TraitRef {
642 def_id: fn_trait_def_id,
643 substs: self.mk_substs_trait(self_ty, &[arguments_tuple.into()]),
645 ty::Binder::bind((trait_ref, sig.skip_binder().output()))
648 pub fn generator_trait_ref_and_outputs(self,
649 fn_trait_def_id: DefId,
651 sig: ty::PolyGenSig<'tcx>)
652 -> ty::Binder<(ty::TraitRef<'tcx>, Ty<'tcx>, Ty<'tcx>)>
654 let trait_ref = ty::TraitRef {
655 def_id: fn_trait_def_id,
656 substs: self.mk_substs_trait(self_ty, &[]),
658 ty::Binder::bind((trait_ref, sig.skip_binder().yield_ty, sig.skip_binder().return_ty))
661 pub fn impl_is_default(self, node_item_def_id: DefId) -> bool {
662 match self.hir().as_local_hir_id(node_item_def_id) {
664 let item = self.hir().expect_item_by_hir_id(hir_id);
665 if let hir::ItemKind::Impl(_, _, defaultness, ..) = item.node {
666 defaultness.is_default()
673 .impl_defaultness(node_item_def_id)
679 pub fn impl_item_is_final(self, node_item: &NodeItem<hir::Defaultness>) -> bool {
680 node_item.item.is_final() && !self.impl_is_default(node_item.node.def_id())
684 pub enum TupleArgumentsFlag { Yes, No }