1 use rustc_errors::DiagnosticBuilder;
3 use smallvec::SmallVec;
5 use crate::ty::outlives::Component;
6 use crate::ty::subst::{GenericArg, Subst, SubstsRef};
7 use crate::ty::{self, ToPolyTraitRef, ToPredicate, Ty, TyCtxt};
8 use rustc_data_structures::fx::FxHashSet;
10 use rustc_hir::def_id::DefId;
12 use super::{Normalized, Obligation, ObligationCause, PredicateObligation, SelectionContext};
14 fn anonymize_predicate<'tcx>(tcx: TyCtxt<'tcx>, pred: &ty::Predicate<'tcx>) -> ty::Predicate<'tcx> {
16 ty::Predicate::Trait(ref data) => {
17 ty::Predicate::Trait(tcx.anonymize_late_bound_regions(data))
20 ty::Predicate::RegionOutlives(ref data) => {
21 ty::Predicate::RegionOutlives(tcx.anonymize_late_bound_regions(data))
24 ty::Predicate::TypeOutlives(ref data) => {
25 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))
32 ty::Predicate::WellFormed(data) => ty::Predicate::WellFormed(data),
34 ty::Predicate::ObjectSafe(data) => ty::Predicate::ObjectSafe(data),
36 ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
37 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))
44 ty::Predicate::ConstEvaluatable(def_id, substs) => {
45 ty::Predicate::ConstEvaluatable(def_id, substs)
50 struct PredicateSet<'tcx> {
52 set: FxHashSet<ty::Predicate<'tcx>>,
55 impl PredicateSet<'tcx> {
56 fn new(tcx: TyCtxt<'tcx>) -> Self {
57 Self { tcx: tcx, set: Default::default() }
60 fn insert(&mut self, pred: &ty::Predicate<'tcx>) -> bool {
61 // We have to be careful here because we want
63 // for<'a> Foo<&'a int>
67 // for<'b> Foo<&'b int>
69 // to be considered equivalent. So normalize all late-bound
70 // regions before we throw things into the underlying set.
71 self.set.insert(anonymize_predicate(self.tcx, pred))
75 impl<T: AsRef<ty::Predicate<'tcx>>> Extend<T> for PredicateSet<'tcx> {
76 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
78 self.insert(pred.as_ref());
83 ///////////////////////////////////////////////////////////////////////////
84 // `Elaboration` iterator
85 ///////////////////////////////////////////////////////////////////////////
87 /// "Elaboration" is the process of identifying all the predicates that
88 /// are implied by a source predicate. Currently, this basically means
89 /// walking the "supertraits" and other similar assumptions. For example,
90 /// if we know that `T: Ord`, the elaborator would deduce that `T: PartialOrd`
91 /// holds as well. Similarly, if we have `trait Foo: 'static`, and we know that
92 /// `T: Foo`, then we know that `T: 'static`.
93 pub struct Elaborator<'tcx> {
94 stack: Vec<ty::Predicate<'tcx>>,
95 visited: PredicateSet<'tcx>,
98 pub fn elaborate_trait_ref<'tcx>(
100 trait_ref: ty::PolyTraitRef<'tcx>,
101 ) -> Elaborator<'tcx> {
102 elaborate_predicates(tcx, vec![trait_ref.to_predicate()])
105 pub fn elaborate_trait_refs<'tcx>(
107 trait_refs: impl Iterator<Item = ty::PolyTraitRef<'tcx>>,
108 ) -> Elaborator<'tcx> {
109 let predicates = trait_refs.map(|trait_ref| trait_ref.to_predicate()).collect();
110 elaborate_predicates(tcx, predicates)
113 pub fn elaborate_predicates<'tcx>(
115 mut predicates: Vec<ty::Predicate<'tcx>>,
116 ) -> Elaborator<'tcx> {
117 let mut visited = PredicateSet::new(tcx);
118 predicates.retain(|pred| visited.insert(pred));
119 Elaborator { stack: predicates, visited }
122 impl Elaborator<'tcx> {
123 pub fn filter_to_traits(self) -> FilterToTraits<Self> {
124 FilterToTraits::new(self)
127 fn elaborate(&mut self, predicate: &ty::Predicate<'tcx>) {
128 let tcx = self.visited.tcx;
130 ty::Predicate::Trait(ref data) => {
131 // Get predicates declared on the trait.
132 let predicates = tcx.super_predicates_of(data.def_id());
134 let predicates = predicates
137 .map(|(pred, _)| pred.subst_supertrait(tcx, &data.to_poly_trait_ref()));
138 debug!("super_predicates: data={:?} predicates={:?}", data, predicates.clone());
140 // Only keep those bounds that we haven't already seen.
141 // This is necessary to prevent infinite recursion in some
142 // cases. One common case is when people define
143 // `trait Sized: Sized { }` rather than `trait Sized { }`.
144 let visited = &mut self.visited;
145 let predicates = predicates.filter(|pred| visited.insert(pred));
147 self.stack.extend(predicates);
149 ty::Predicate::WellFormed(..) => {
150 // Currently, we do not elaborate WF predicates,
151 // although we easily could.
153 ty::Predicate::ObjectSafe(..) => {
154 // Currently, we do not elaborate object-safe
157 ty::Predicate::Subtype(..) => {
158 // Currently, we do not "elaborate" predicates like `X <: Y`,
159 // though conceivably we might.
161 ty::Predicate::Projection(..) => {
162 // Nothing to elaborate in a projection predicate.
164 ty::Predicate::ClosureKind(..) => {
165 // Nothing to elaborate when waiting for a closure's kind to be inferred.
167 ty::Predicate::ConstEvaluatable(..) => {
168 // Currently, we do not elaborate const-evaluatable
171 ty::Predicate::RegionOutlives(..) => {
172 // Nothing to elaborate from `'a: 'b`.
174 ty::Predicate::TypeOutlives(ref data) => {
175 // We know that `T: 'a` for some type `T`. We can
176 // often elaborate this. For example, if we know that
177 // `[U]: 'a`, that implies that `U: 'a`. Similarly, if
178 // we know `&'a U: 'b`, then we know that `'a: 'b` and
181 // We can basically ignore bound regions here. So for
182 // example `for<'c> Foo<'a,'c>: 'b` can be elaborated to
185 // Ignore `for<'a> T: 'a` -- we might in the future
186 // consider this as evidence that `T: 'static`, but
187 // I'm a bit wary of such constructions and so for now
188 // I want to be conservative. --nmatsakis
189 let ty_max = data.skip_binder().0;
190 let r_min = data.skip_binder().1;
191 if r_min.is_late_bound() {
195 let visited = &mut self.visited;
196 let mut components = smallvec![];
197 tcx.push_outlives_components(ty_max, &mut components);
201 .filter_map(|component| match component {
202 Component::Region(r) => {
203 if r.is_late_bound() {
206 Some(ty::Predicate::RegionOutlives(ty::Binder::dummy(
207 ty::OutlivesPredicate(r, r_min),
212 Component::Param(p) => {
213 let ty = tcx.mk_ty_param(p.index, p.name);
214 Some(ty::Predicate::TypeOutlives(ty::Binder::dummy(
215 ty::OutlivesPredicate(ty, r_min),
219 Component::UnresolvedInferenceVariable(_) => None,
221 Component::Projection(_) | 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 Iterator for Elaborator<'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<'tcx> = FilterToTraits<Elaborator<'tcx>>;
259 pub fn supertraits<'tcx>(
261 trait_ref: ty::PolyTraitRef<'tcx>,
262 ) -> Supertraits<'tcx> {
263 elaborate_trait_ref(tcx, trait_ref).filter_to_traits()
266 pub fn transitive_bounds<'tcx>(
268 bounds: impl Iterator<Item = ty::PolyTraitRef<'tcx>>,
269 ) -> Supertraits<'tcx> {
270 elaborate_trait_refs(tcx, bounds).filter_to_traits()
273 ///////////////////////////////////////////////////////////////////////////
274 // `TraitAliasExpander` iterator
275 ///////////////////////////////////////////////////////////////////////////
277 /// "Trait alias expansion" is the process of expanding a sequence of trait
278 /// references into another sequence by transitively following all trait
279 /// aliases. e.g. If you have bounds like `Foo + Send`, a trait alias
280 /// `trait Foo = Bar + Sync;`, and another trait alias
281 /// `trait Bar = Read + Write`, then the bounds would expand to
282 /// `Read + Write + Sync + Send`.
283 /// Expansion is done via a DFS (depth-first search), and the `visited` field
284 /// is used to avoid cycles.
285 pub struct TraitAliasExpander<'tcx> {
287 stack: Vec<TraitAliasExpansionInfo<'tcx>>,
290 /// Stores information about the expansion of a trait via a path of zero or more trait aliases.
291 #[derive(Debug, Clone)]
292 pub struct TraitAliasExpansionInfo<'tcx> {
293 pub path: SmallVec<[(ty::PolyTraitRef<'tcx>, Span); 4]>,
296 impl<'tcx> TraitAliasExpansionInfo<'tcx> {
297 fn new(trait_ref: ty::PolyTraitRef<'tcx>, span: Span) -> Self {
298 Self { 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(
305 diag: &mut DiagnosticBuilder<'_>,
309 diag.span_label(self.top().1, top_label);
310 if self.path.len() > 1 {
311 for (_, sp) in self.path.iter().rev().skip(1).take(self.path.len() - 2) {
312 diag.span_label(*sp, format!("referenced here ({})", use_desc));
317 format!("trait alias used in trait object type ({})", use_desc),
321 pub fn trait_ref(&self) -> &ty::PolyTraitRef<'tcx> {
325 pub fn top(&self) -> &(ty::PolyTraitRef<'tcx>, Span) {
326 self.path.last().unwrap()
329 pub fn bottom(&self) -> &(ty::PolyTraitRef<'tcx>, Span) {
330 self.path.first().unwrap()
333 fn clone_and_push(&self, trait_ref: ty::PolyTraitRef<'tcx>, span: Span) -> Self {
334 let mut path = self.path.clone();
335 path.push((trait_ref, span));
341 pub fn expand_trait_aliases<'tcx>(
343 trait_refs: impl IntoIterator<Item = (ty::PolyTraitRef<'tcx>, Span)>,
344 ) -> TraitAliasExpander<'tcx> {
345 let items: Vec<_> = trait_refs
347 .map(|(trait_ref, span)| TraitAliasExpansionInfo::new(trait_ref, span))
349 TraitAliasExpander { tcx, stack: items }
352 impl<'tcx> TraitAliasExpander<'tcx> {
353 /// If `item` is a trait alias and its predicate has not yet been visited, then expands `item`
354 /// to the definition, pushes the resulting expansion onto `self.stack`, and returns `false`.
355 /// Otherwise, immediately returns `true` if `item` is a regular trait, or `false` if it is a
357 /// The return value indicates whether `item` should be yielded to the user.
358 fn expand(&mut self, item: &TraitAliasExpansionInfo<'tcx>) -> bool {
360 let trait_ref = item.trait_ref();
361 let pred = trait_ref.to_predicate();
363 debug!("expand_trait_aliases: trait_ref={:?}", trait_ref);
365 // Don't recurse if this bound is not a trait alias.
366 let is_alias = tcx.is_trait_alias(trait_ref.def_id());
371 // Don't recurse if this trait alias is already on the stack for the DFS search.
372 let anon_pred = anonymize_predicate(tcx, &pred);
378 .any(|(tr, _)| anonymize_predicate(tcx, &tr.to_predicate()) == anon_pred)
383 // Get components of trait alias.
384 let predicates = tcx.super_predicates_of(trait_ref.def_id());
386 let items = predicates.predicates.iter().rev().filter_map(|(pred, span)| {
387 pred.subst_supertrait(tcx, &trait_ref)
388 .to_opt_poly_trait_ref()
389 .map(|trait_ref| item.clone_and_push(trait_ref, *span))
391 debug!("expand_trait_aliases: items={:?}", items.clone());
393 self.stack.extend(items);
399 impl<'tcx> Iterator for TraitAliasExpander<'tcx> {
400 type Item = TraitAliasExpansionInfo<'tcx>;
402 fn size_hint(&self) -> (usize, Option<usize>) {
403 (self.stack.len(), None)
406 fn next(&mut self) -> Option<TraitAliasExpansionInfo<'tcx>> {
407 while let Some(item) = self.stack.pop() {
408 if self.expand(&item) {
416 ///////////////////////////////////////////////////////////////////////////
417 // Iterator over def-IDs of supertraits
418 ///////////////////////////////////////////////////////////////////////////
420 pub struct SupertraitDefIds<'tcx> {
423 visited: FxHashSet<DefId>,
426 pub fn supertrait_def_ids(tcx: TyCtxt<'_>, trait_def_id: DefId) -> SupertraitDefIds<'_> {
429 stack: vec![trait_def_id],
430 visited: Some(trait_def_id).into_iter().collect(),
434 impl Iterator for SupertraitDefIds<'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;
445 .filter_map(|(pred, _)| pred.to_opt_poly_trait_ref())
446 .map(|trait_ref| trait_ref.def_id())
447 .filter(|&super_def_id| visited.insert(super_def_id)),
453 ///////////////////////////////////////////////////////////////////////////
455 ///////////////////////////////////////////////////////////////////////////
457 /// A filter around an iterator of predicates that makes it yield up
458 /// just trait references.
459 pub struct FilterToTraits<I> {
463 impl<I> FilterToTraits<I> {
464 fn new(base: I) -> FilterToTraits<I> {
465 FilterToTraits { base_iterator: base }
469 impl<'tcx, I: Iterator<Item = ty::Predicate<'tcx>>> Iterator for FilterToTraits<I> {
470 type Item = ty::PolyTraitRef<'tcx>;
472 fn next(&mut self) -> Option<ty::PolyTraitRef<'tcx>> {
473 while let Some(pred) = self.base_iterator.next() {
474 if let ty::Predicate::Trait(data) = pred {
475 return Some(data.to_poly_trait_ref());
481 fn size_hint(&self) -> (usize, Option<usize>) {
482 let (_, upper) = self.base_iterator.size_hint();
487 ///////////////////////////////////////////////////////////////////////////
489 ///////////////////////////////////////////////////////////////////////////
491 /// Instantiate all bound parameters of the impl with the given substs,
492 /// returning the resulting trait ref and all obligations that arise.
493 /// The obligations are closed under normalization.
494 pub fn impl_trait_ref_and_oblig<'a, 'tcx>(
495 selcx: &mut SelectionContext<'a, 'tcx>,
496 param_env: ty::ParamEnv<'tcx>,
498 impl_substs: SubstsRef<'tcx>,
499 ) -> (ty::TraitRef<'tcx>, Vec<PredicateObligation<'tcx>>) {
500 let impl_trait_ref = selcx.tcx().impl_trait_ref(impl_def_id).unwrap();
501 let impl_trait_ref = impl_trait_ref.subst(selcx.tcx(), impl_substs);
502 let Normalized { value: impl_trait_ref, obligations: normalization_obligations1 } =
503 super::normalize(selcx, param_env, ObligationCause::dummy(), &impl_trait_ref);
505 let predicates = selcx.tcx().predicates_of(impl_def_id);
506 let predicates = predicates.instantiate(selcx.tcx(), impl_substs);
507 let Normalized { value: predicates, obligations: normalization_obligations2 } =
508 super::normalize(selcx, param_env, ObligationCause::dummy(), &predicates);
509 let impl_obligations =
510 predicates_for_generics(ObligationCause::dummy(), 0, param_env, &predicates);
512 let impl_obligations: Vec<_> = impl_obligations
514 .chain(normalization_obligations1)
515 .chain(normalization_obligations2)
518 (impl_trait_ref, impl_obligations)
521 /// See [`super::obligations_for_generics`].
522 pub fn predicates_for_generics<'tcx>(
523 cause: ObligationCause<'tcx>,
524 recursion_depth: usize,
525 param_env: ty::ParamEnv<'tcx>,
526 generic_bounds: &ty::InstantiatedPredicates<'tcx>,
527 ) -> Vec<PredicateObligation<'tcx>> {
528 debug!("predicates_for_generics(generic_bounds={:?})", generic_bounds);
533 .map(|predicate| Obligation {
534 cause: cause.clone(),
537 predicate: predicate.clone(),
542 pub fn predicate_for_trait_ref<'tcx>(
543 cause: ObligationCause<'tcx>,
544 param_env: ty::ParamEnv<'tcx>,
545 trait_ref: ty::TraitRef<'tcx>,
546 recursion_depth: usize,
547 ) -> PredicateObligation<'tcx> {
548 Obligation { cause, param_env, recursion_depth, predicate: trait_ref.to_predicate() }
551 pub fn predicate_for_trait_def(
553 param_env: ty::ParamEnv<'tcx>,
554 cause: ObligationCause<'tcx>,
556 recursion_depth: usize,
558 params: &[GenericArg<'tcx>],
559 ) -> PredicateObligation<'tcx> {
561 ty::TraitRef { def_id: trait_def_id, substs: tcx.mk_substs_trait(self_ty, params) };
562 predicate_for_trait_ref(cause, param_env, trait_ref, recursion_depth)
565 /// Casts a trait reference into a reference to one of its super
566 /// traits; returns `None` if `target_trait_def_id` is not a
568 pub fn upcast_choices(
570 source_trait_ref: ty::PolyTraitRef<'tcx>,
571 target_trait_def_id: DefId,
572 ) -> Vec<ty::PolyTraitRef<'tcx>> {
573 if source_trait_ref.def_id() == target_trait_def_id {
574 return vec![source_trait_ref]; // Shortcut the most common case.
577 supertraits(tcx, source_trait_ref).filter(|r| r.def_id() == target_trait_def_id).collect()
580 /// Given a trait `trait_ref`, returns the number of vtable entries
581 /// that come from `trait_ref`, excluding its supertraits. Used in
582 /// computing the vtable base for an upcast trait of a trait object.
583 pub fn count_own_vtable_entries(tcx: TyCtxt<'tcx>, trait_ref: ty::PolyTraitRef<'tcx>) -> usize {
585 // Count number of methods and add them to the total offset.
586 // Skip over associated types and constants.
587 for trait_item in tcx.associated_items(trait_ref.def_id()) {
588 if trait_item.kind == ty::AssocKind::Method {
595 /// Given an upcast trait object described by `object`, returns the
596 /// index of the method `method_def_id` (which should be part of
597 /// `object.upcast_trait_ref`) within the vtable for `object`.
598 pub fn get_vtable_index_of_object_method<N>(
600 object: &super::VtableObjectData<'tcx, N>,
601 method_def_id: DefId,
603 // Count number of methods preceding the one we are selecting and
604 // add them to the total offset.
605 // Skip over associated types and constants.
606 let mut entries = object.vtable_base;
607 for trait_item in tcx.associated_items(object.upcast_trait_ref.def_id()) {
608 if trait_item.def_id == method_def_id {
609 // The item with the ID we were given really ought to be a method.
610 assert_eq!(trait_item.kind, ty::AssocKind::Method);
613 if trait_item.kind == ty::AssocKind::Method {
618 bug!("get_vtable_index_of_object_method: {:?} was not found", method_def_id);
621 pub fn closure_trait_ref_and_return_type(
623 fn_trait_def_id: DefId,
625 sig: ty::PolyFnSig<'tcx>,
626 tuple_arguments: TupleArgumentsFlag,
627 ) -> ty::Binder<(ty::TraitRef<'tcx>, Ty<'tcx>)> {
628 let arguments_tuple = match tuple_arguments {
629 TupleArgumentsFlag::No => sig.skip_binder().inputs()[0],
630 TupleArgumentsFlag::Yes => tcx.intern_tup(sig.skip_binder().inputs()),
632 let trait_ref = ty::TraitRef {
633 def_id: fn_trait_def_id,
634 substs: tcx.mk_substs_trait(self_ty, &[arguments_tuple.into()]),
636 ty::Binder::bind((trait_ref, sig.skip_binder().output()))
639 pub fn generator_trait_ref_and_outputs(
641 fn_trait_def_id: DefId,
643 sig: ty::PolyGenSig<'tcx>,
644 ) -> ty::Binder<(ty::TraitRef<'tcx>, Ty<'tcx>, Ty<'tcx>)> {
646 ty::TraitRef { def_id: fn_trait_def_id, substs: tcx.mk_substs_trait(self_ty, &[]) };
647 ty::Binder::bind((trait_ref, sig.skip_binder().yield_ty, sig.skip_binder().return_ty))
650 pub fn impl_is_default(tcx: TyCtxt<'_>, node_item_def_id: DefId) -> bool {
651 match tcx.hir().as_local_hir_id(node_item_def_id) {
653 let item = tcx.hir().expect_item(hir_id);
654 if let hir::ItemKind::Impl(_, _, defaultness, ..) = item.kind {
655 defaultness.is_default()
660 None => tcx.impl_defaultness(node_item_def_id).is_default(),
664 pub fn impl_item_is_final(tcx: TyCtxt<'_>, assoc_item: &ty::AssocItem) -> bool {
665 assoc_item.defaultness.is_final() && !impl_is_default(tcx, assoc_item.container.id())
668 pub enum TupleArgumentsFlag {