]> git.lizzy.rs Git - rust.git/blob - src/librustc/traits/util.rs
Rollup merge of #61024 - petrochenkov:proctest, r=nikomatsakis
[rust.git] / src / librustc / traits / util.rs
1 use errors::DiagnosticBuilder;
2 use smallvec::SmallVec;
3 use syntax_pos::Span;
4
5 use crate::hir;
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;
12
13 use super::{Obligation, ObligationCause, PredicateObligation, SelectionContext, Normalized};
14
15 fn anonymize_predicate<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
16                                        pred: &ty::Predicate<'tcx>)
17                                        -> ty::Predicate<'tcx> {
18     match *pred {
19         ty::Predicate::Trait(ref data) =>
20             ty::Predicate::Trait(tcx.anonymize_late_bound_regions(data)),
21
22         ty::Predicate::RegionOutlives(ref data) =>
23             ty::Predicate::RegionOutlives(tcx.anonymize_late_bound_regions(data)),
24
25         ty::Predicate::TypeOutlives(ref data) =>
26             ty::Predicate::TypeOutlives(tcx.anonymize_late_bound_regions(data)),
27
28         ty::Predicate::Projection(ref data) =>
29             ty::Predicate::Projection(tcx.anonymize_late_bound_regions(data)),
30
31         ty::Predicate::WellFormed(data) =>
32             ty::Predicate::WellFormed(data),
33
34         ty::Predicate::ObjectSafe(data) =>
35             ty::Predicate::ObjectSafe(data),
36
37         ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind) =>
38             ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind),
39
40         ty::Predicate::Subtype(ref data) =>
41             ty::Predicate::Subtype(tcx.anonymize_late_bound_regions(data)),
42
43         ty::Predicate::ConstEvaluatable(def_id, substs) =>
44             ty::Predicate::ConstEvaluatable(def_id, substs),
45     }
46 }
47
48 struct PredicateSet<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> {
49     tcx: TyCtxt<'a, 'gcx, 'tcx>,
50     set: FxHashSet<ty::Predicate<'tcx>>,
51 }
52
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() }
56     }
57
58     fn insert(&mut self, pred: &ty::Predicate<'tcx>) -> bool {
59         // We have to be careful here because we want
60         //
61         //    for<'a> Foo<&'a int>
62         //
63         // and
64         //
65         //    for<'b> Foo<&'b int>
66         //
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))
70     }
71 }
72
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) {
75         for pred in iter {
76             self.insert(pred.as_ref());
77         }
78     }
79 }
80
81 ///////////////////////////////////////////////////////////////////////////
82 // `Elaboration` iterator
83 ///////////////////////////////////////////////////////////////////////////
84
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>,
94 }
95
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>
100 {
101     elaborate_predicates(tcx, vec![trait_ref.to_predicate()])
102 }
103
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>
108 {
109     let predicates = trait_refs.map(|trait_ref| trait_ref.to_predicate()).collect();
110     elaborate_predicates(tcx, predicates)
111 }
112
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>
117 {
118     let mut visited = PredicateSet::new(tcx);
119     predicates.retain(|pred| visited.insert(pred));
120     Elaborator { stack: predicates, visited }
121 }
122
123 impl<'cx, 'gcx, 'tcx> Elaborator<'cx, 'gcx, 'tcx> {
124     pub fn filter_to_traits(self) -> FilterToTraits<Self> {
125         FilterToTraits::new(self)
126     }
127
128     fn elaborate(&mut self, predicate: &ty::Predicate<'tcx>) {
129         let tcx = self.visited.tcx;
130         match *predicate {
131             ty::Predicate::Trait(ref data) => {
132                 // Get predicates declared on the trait.
133                 let predicates = tcx.super_predicates_of(data.def_id());
134
135                 let predicates = predicates.predicates
136                     .iter()
137                     .map(|(pred, _)| pred.subst_supertrait(tcx, &data.to_poly_trait_ref()));
138                 debug!("super_predicates: data={:?} predicates={:?}",
139                        data, predicates.clone());
140
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));
147
148                 self.stack.extend(predicates);
149             }
150             ty::Predicate::WellFormed(..) => {
151                 // Currently, we do not elaborate WF predicates,
152                 // although we easily could.
153             }
154             ty::Predicate::ObjectSafe(..) => {
155                 // Currently, we do not elaborate object-safe
156                 // predicates.
157             }
158             ty::Predicate::Subtype(..) => {
159                 // Currently, we do not "elaborate" predicates like `X <: Y`,
160                 // though conceivably we might.
161             }
162             ty::Predicate::Projection(..) => {
163                 // Nothing to elaborate in a projection predicate.
164             }
165             ty::Predicate::ClosureKind(..) => {
166                 // Nothing to elaborate when waiting for a closure's kind to be inferred.
167             }
168             ty::Predicate::ConstEvaluatable(..) => {
169                 // Currently, we do not elaborate const-evaluatable
170                 // predicates.
171             }
172             ty::Predicate::RegionOutlives(..) => {
173                 // Nothing to elaborate from `'a: 'b`.
174             }
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
180                 // `U: 'b`.
181                 //
182                 // We can basically ignore bound regions here. So for
183                 // example `for<'c> Foo<'a,'c>: 'b` can be elaborated to
184                 // `'a: 'b`.
185
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() {
193                     return;
194                 }
195
196                 let visited = &mut self.visited;
197                 let mut components = smallvec![];
198                 tcx.push_outlives_components(ty_max, &mut components);
199                 self.stack.extend(
200                     components
201                         .into_iter()
202                         .filter_map(|component| match component {
203                             Component::Region(r) => if r.is_late_bound() {
204                                 None
205                             } else {
206                                 Some(ty::Predicate::RegionOutlives(
207                                     ty::Binder::dummy(ty::OutlivesPredicate(r, r_min))))
208                             }
209
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))))
214                             }
215
216                             Component::UnresolvedInferenceVariable(_) => {
217                                 None
218                             }
219
220                             Component::Projection(_) |
221                             Component::EscapingProjection(_) => {
222                                 // We can probably do more here. This
223                                 // corresponds to a case like `<T as
224                                 // Foo<'a>>::U: 'b`.
225                                 None
226                             }
227                         })
228                         .filter(|p| visited.insert(p))
229                 );
230             }
231         }
232     }
233 }
234
235 impl<'cx, 'gcx, 'tcx> Iterator for Elaborator<'cx, 'gcx, 'tcx> {
236     type Item = ty::Predicate<'tcx>;
237
238     fn size_hint(&self) -> (usize, Option<usize>) {
239         (self.stack.len(), None)
240     }
241
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);
246             Some(pred)
247         } else {
248             None
249         }
250     }
251 }
252
253 ///////////////////////////////////////////////////////////////////////////
254 // Supertrait iterator
255 ///////////////////////////////////////////////////////////////////////////
256
257 pub type Supertraits<'cx, 'gcx, 'tcx> = FilterToTraits<Elaborator<'cx, 'gcx, 'tcx>>;
258
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()
263 }
264
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()
269 }
270
271 ///////////////////////////////////////////////////////////////////////////
272 // `TraitAliasExpander` iterator
273 ///////////////////////////////////////////////////////////////////////////
274
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>>,
286 }
287
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]>,
292 }
293
294 impl<'tcx> TraitAliasExpansionInfo<'tcx> {
295     fn new(trait_ref: ty::PolyTraitRef<'tcx>, span: Span) -> Self {
296         Self {
297             path: smallvec![(trait_ref, span)]
298         }
299     }
300
301     /// Adds diagnostic labels to `diag` for the expansion path of a trait through all intermediate
302     /// trait aliases.
303     pub fn label_with_exp_info(&self,
304         diag: &mut DiagnosticBuilder<'_>,
305         top_label: &str,
306         use_desc: &str
307     ) {
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));
312             }
313         }
314         diag.span_label(self.bottom().1,
315             format!("trait alias used in trait object type ({})", use_desc));
316     }
317
318     pub fn trait_ref(&self) -> &ty::PolyTraitRef<'tcx> {
319         &self.top().0
320     }
321
322     pub fn top(&self) -> &(ty::PolyTraitRef<'tcx>, Span) {
323         self.path.last().unwrap()
324     }
325
326     pub fn bottom(&self) -> &(ty::PolyTraitRef<'tcx>, Span) {
327         self.path.first().unwrap()
328     }
329
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));
333
334         Self {
335             path
336         }
337     }
338 }
339
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
345         .into_iter()
346         .map(|(trait_ref, span)| TraitAliasExpansionInfo::new(trait_ref, span))
347         .collect();
348     TraitAliasExpander { tcx, stack: items }
349 }
350
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
355     /// trait alias.
356     /// The return value indicates whether `item` should be yielded to the user.
357     fn expand(&mut self, item: &TraitAliasExpansionInfo<'tcx>) -> bool {
358         let tcx = self.tcx;
359         let trait_ref = item.trait_ref();
360         let pred = trait_ref.to_predicate();
361
362         debug!("expand_trait_aliases: trait_ref={:?}", trait_ref);
363
364         // Don't recurse if this bound is not a trait alias.
365         let is_alias = tcx.is_trait_alias(trait_ref.def_id());
366         if !is_alias {
367             return true;
368         }
369
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) {
374             return false;
375         }
376
377         // Get components of trait alias.
378         let predicates = tcx.super_predicates_of(trait_ref.def_id());
379
380         let items = predicates.predicates
381             .iter()
382             .rev()
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))
387             });
388         debug!("expand_trait_aliases: items={:?}", items.clone());
389
390         self.stack.extend(items);
391
392         false
393     }
394 }
395
396 impl<'cx, 'gcx, 'tcx> Iterator for TraitAliasExpander<'cx, 'gcx, 'tcx> {
397     type Item = TraitAliasExpansionInfo<'tcx>;
398
399     fn size_hint(&self) -> (usize, Option<usize>) {
400         (self.stack.len(), None)
401     }
402
403     fn next(&mut self) -> Option<TraitAliasExpansionInfo<'tcx>> {
404         while let Some(item) = self.stack.pop() {
405             if self.expand(&item) {
406                 return Some(item);
407             }
408         }
409         None
410     }
411 }
412
413 ///////////////////////////////////////////////////////////////////////////
414 // Iterator over def-IDs of supertraits
415 ///////////////////////////////////////////////////////////////////////////
416
417 pub struct SupertraitDefIds<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
418     tcx: TyCtxt<'a, 'gcx, 'tcx>,
419     stack: Vec<DefId>,
420     visited: FxHashSet<DefId>,
421 }
422
423 pub fn supertrait_def_ids<'cx, 'gcx, 'tcx>(tcx: TyCtxt<'cx, 'gcx, 'tcx>,
424                                            trait_def_id: DefId)
425                                            -> SupertraitDefIds<'cx, 'gcx, 'tcx>
426 {
427     SupertraitDefIds {
428         tcx,
429         stack: vec![trait_def_id],
430         visited: Some(trait_def_id).into_iter().collect(),
431     }
432 }
433
434 impl<'cx, 'gcx, 'tcx> Iterator for SupertraitDefIds<'cx, 'gcx, 'tcx> {
435     type Item = DefId;
436
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;
441         self.stack.extend(
442             predicates.predicates
443                       .iter()
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)));
447         Some(def_id)
448     }
449 }
450
451 ///////////////////////////////////////////////////////////////////////////
452 // Other
453 ///////////////////////////////////////////////////////////////////////////
454
455 /// A filter around an iterator of predicates that makes it yield up
456 /// just trait references.
457 pub struct FilterToTraits<I> {
458     base_iterator: I
459 }
460
461 impl<I> FilterToTraits<I> {
462     fn new(base: I) -> FilterToTraits<I> {
463         FilterToTraits { base_iterator: base }
464     }
465 }
466
467 impl<'tcx, I: Iterator<Item = ty::Predicate<'tcx>>> Iterator for FilterToTraits<I> {
468     type Item = ty::PolyTraitRef<'tcx>;
469
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());
474             }
475         }
476         None
477     }
478
479     fn size_hint(&self) -> (usize, Option<usize>) {
480         let (_, upper) = self.base_iterator.size_hint();
481         (0, upper)
482     }
483 }
484
485 ///////////////////////////////////////////////////////////////////////////
486 // Other
487 ///////////////////////////////////////////////////////////////////////////
488
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>,
494                                                 impl_def_id: DefId,
495                                                 impl_substs: SubstsRef<'tcx>,)
496                                                 -> (ty::TraitRef<'tcx>,
497                                                     Vec<PredicateObligation<'tcx>>)
498 {
499     let impl_trait_ref =
500         selcx.tcx().impl_trait_ref(impl_def_id).unwrap();
501     let impl_trait_ref =
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);
505
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);
512
513     let impl_obligations: Vec<_> =
514         impl_obligations.into_iter()
515         .chain(normalization_obligations1)
516         .chain(normalization_obligations2)
517         .collect();
518
519     (impl_trait_ref, impl_obligations)
520 }
521
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>>
528 {
529     debug!("predicates_for_generics(generic_bounds={:?})",
530            generic_bounds);
531
532     generic_bounds.predicates.iter().map(|predicate| {
533         Obligation { cause: cause.clone(),
534                      recursion_depth,
535                      param_env,
536                      predicate: predicate.clone() }
537     }).collect()
538 }
539
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>
546 {
547     Obligation {
548         cause,
549         param_env,
550         recursion_depth,
551         predicate: trait_ref.to_predicate(),
552     }
553 }
554
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>,
559                                    trait_def_id: DefId,
560                                    recursion_depth: usize,
561                                    self_ty: Ty<'tcx>,
562                                    params: &[Kind<'tcx>])
563         -> PredicateObligation<'tcx>
564     {
565         let trait_ref = ty::TraitRef {
566             def_id: trait_def_id,
567             substs: self.mk_substs_trait(self_ty, params)
568         };
569         predicate_for_trait_ref(cause, param_env, trait_ref, recursion_depth)
570     }
571
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
574     /// supertrait.
575     pub fn upcast_choices(self,
576                           source_trait_ref: ty::PolyTraitRef<'tcx>,
577                           target_trait_def_id: DefId)
578                           -> Vec<ty::PolyTraitRef<'tcx>>
579     {
580         if source_trait_ref.def_id() == target_trait_def_id {
581             return vec![source_trait_ref]; // shorcut the most common case
582         }
583
584         supertraits(self, source_trait_ref)
585             .filter(|r| r.def_id() == target_trait_def_id)
586             .collect()
587     }
588
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 {
593         let mut entries = 0;
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 {
598                 entries += 1;
599             }
600         }
601         entries
602     }
603
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);
618                 return entries;
619             }
620             if trait_item.kind == ty::AssocKind::Method {
621                 entries += 1;
622             }
623         }
624
625         bug!("get_vtable_index_of_object_method: {:?} was not found",
626              method_def_id);
627     }
628
629     pub fn closure_trait_ref_and_return_type(self,
630         fn_trait_def_id: DefId,
631         self_ty: Ty<'tcx>,
632         sig: ty::PolyFnSig<'tcx>,
633         tuple_arguments: TupleArgumentsFlag)
634         -> ty::Binder<(ty::TraitRef<'tcx>, Ty<'tcx>)>
635     {
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()),
640         };
641         let trait_ref = ty::TraitRef {
642             def_id: fn_trait_def_id,
643             substs: self.mk_substs_trait(self_ty, &[arguments_tuple.into()]),
644         };
645         ty::Binder::bind((trait_ref, sig.skip_binder().output()))
646     }
647
648     pub fn generator_trait_ref_and_outputs(self,
649         fn_trait_def_id: DefId,
650         self_ty: Ty<'tcx>,
651         sig: ty::PolyGenSig<'tcx>)
652         -> ty::Binder<(ty::TraitRef<'tcx>, Ty<'tcx>, Ty<'tcx>)>
653     {
654         let trait_ref = ty::TraitRef {
655             def_id: fn_trait_def_id,
656             substs: self.mk_substs_trait(self_ty, &[]),
657         };
658         ty::Binder::bind((trait_ref, sig.skip_binder().yield_ty, sig.skip_binder().return_ty))
659     }
660
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) {
663             Some(hir_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()
667                 } else {
668                     false
669                 }
670             }
671             None => {
672                 self.global_tcx()
673                     .impl_defaultness(node_item_def_id)
674                     .is_default()
675             }
676         }
677     }
678
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())
681     }
682 }
683
684 pub enum TupleArgumentsFlag { Yes, No }