]> git.lizzy.rs Git - rust.git/blob - src/librustc/traits/util.rs
nix syntax::errors & prefer rustc_errors over errors
[rust.git] / src / librustc / traits / util.rs
1 use rustc_errors::DiagnosticBuilder;
2 use rustc_span::Span;
3 use smallvec::SmallVec;
4
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;
9 use rustc_hir as hir;
10 use rustc_hir::def_id::DefId;
11
12 use super::{Normalized, Obligation, ObligationCause, PredicateObligation, SelectionContext};
13
14 fn anonymize_predicate<'tcx>(tcx: TyCtxt<'tcx>, pred: &ty::Predicate<'tcx>) -> ty::Predicate<'tcx> {
15     match *pred {
16         ty::Predicate::Trait(ref data) => {
17             ty::Predicate::Trait(tcx.anonymize_late_bound_regions(data))
18         }
19
20         ty::Predicate::RegionOutlives(ref data) => {
21             ty::Predicate::RegionOutlives(tcx.anonymize_late_bound_regions(data))
22         }
23
24         ty::Predicate::TypeOutlives(ref data) => {
25             ty::Predicate::TypeOutlives(tcx.anonymize_late_bound_regions(data))
26         }
27
28         ty::Predicate::Projection(ref data) => {
29             ty::Predicate::Projection(tcx.anonymize_late_bound_regions(data))
30         }
31
32         ty::Predicate::WellFormed(data) => ty::Predicate::WellFormed(data),
33
34         ty::Predicate::ObjectSafe(data) => ty::Predicate::ObjectSafe(data),
35
36         ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
37             ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind)
38         }
39
40         ty::Predicate::Subtype(ref data) => {
41             ty::Predicate::Subtype(tcx.anonymize_late_bound_regions(data))
42         }
43
44         ty::Predicate::ConstEvaluatable(def_id, substs) => {
45             ty::Predicate::ConstEvaluatable(def_id, substs)
46         }
47     }
48 }
49
50 struct PredicateSet<'tcx> {
51     tcx: TyCtxt<'tcx>,
52     set: FxHashSet<ty::Predicate<'tcx>>,
53 }
54
55 impl PredicateSet<'tcx> {
56     fn new(tcx: TyCtxt<'tcx>) -> Self {
57         Self { tcx: tcx, set: Default::default() }
58     }
59
60     fn insert(&mut self, pred: &ty::Predicate<'tcx>) -> bool {
61         // We have to be careful here because we want
62         //
63         //    for<'a> Foo<&'a int>
64         //
65         // and
66         //
67         //    for<'b> Foo<&'b int>
68         //
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))
72     }
73 }
74
75 impl<T: AsRef<ty::Predicate<'tcx>>> Extend<T> for PredicateSet<'tcx> {
76     fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
77         for pred in iter {
78             self.insert(pred.as_ref());
79         }
80     }
81 }
82
83 ///////////////////////////////////////////////////////////////////////////
84 // `Elaboration` iterator
85 ///////////////////////////////////////////////////////////////////////////
86
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>,
96 }
97
98 pub fn elaborate_trait_ref<'tcx>(
99     tcx: TyCtxt<'tcx>,
100     trait_ref: ty::PolyTraitRef<'tcx>,
101 ) -> Elaborator<'tcx> {
102     elaborate_predicates(tcx, vec![trait_ref.to_predicate()])
103 }
104
105 pub fn elaborate_trait_refs<'tcx>(
106     tcx: TyCtxt<'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)
111 }
112
113 pub fn elaborate_predicates<'tcx>(
114     tcx: TyCtxt<'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 }
120 }
121
122 impl Elaborator<'tcx> {
123     pub fn filter_to_traits(self) -> FilterToTraits<Self> {
124         FilterToTraits::new(self)
125     }
126
127     fn elaborate(&mut self, predicate: &ty::Predicate<'tcx>) {
128         let tcx = self.visited.tcx;
129         match *predicate {
130             ty::Predicate::Trait(ref data) => {
131                 // Get predicates declared on the trait.
132                 let predicates = tcx.super_predicates_of(data.def_id());
133
134                 let predicates = predicates
135                     .predicates
136                     .iter()
137                     .map(|(pred, _)| pred.subst_supertrait(tcx, &data.to_poly_trait_ref()));
138                 debug!("super_predicates: data={:?} predicates={:?}", data, predicates.clone());
139
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));
146
147                 self.stack.extend(predicates);
148             }
149             ty::Predicate::WellFormed(..) => {
150                 // Currently, we do not elaborate WF predicates,
151                 // although we easily could.
152             }
153             ty::Predicate::ObjectSafe(..) => {
154                 // Currently, we do not elaborate object-safe
155                 // predicates.
156             }
157             ty::Predicate::Subtype(..) => {
158                 // Currently, we do not "elaborate" predicates like `X <: Y`,
159                 // though conceivably we might.
160             }
161             ty::Predicate::Projection(..) => {
162                 // Nothing to elaborate in a projection predicate.
163             }
164             ty::Predicate::ClosureKind(..) => {
165                 // Nothing to elaborate when waiting for a closure's kind to be inferred.
166             }
167             ty::Predicate::ConstEvaluatable(..) => {
168                 // Currently, we do not elaborate const-evaluatable
169                 // predicates.
170             }
171             ty::Predicate::RegionOutlives(..) => {
172                 // Nothing to elaborate from `'a: 'b`.
173             }
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
179                 // `U: 'b`.
180                 //
181                 // We can basically ignore bound regions here. So for
182                 // example `for<'c> Foo<'a,'c>: 'b` can be elaborated to
183                 // `'a: 'b`.
184
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() {
192                     return;
193                 }
194
195                 let visited = &mut self.visited;
196                 let mut components = smallvec![];
197                 tcx.push_outlives_components(ty_max, &mut components);
198                 self.stack.extend(
199                     components
200                         .into_iter()
201                         .filter_map(|component| match component {
202                             Component::Region(r) => {
203                                 if r.is_late_bound() {
204                                     None
205                                 } else {
206                                     Some(ty::Predicate::RegionOutlives(ty::Binder::dummy(
207                                         ty::OutlivesPredicate(r, r_min),
208                                     )))
209                                 }
210                             }
211
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),
216                                 )))
217                             }
218
219                             Component::UnresolvedInferenceVariable(_) => None,
220
221                             Component::Projection(_) | 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 Iterator for Elaborator<'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<'tcx> = FilterToTraits<Elaborator<'tcx>>;
258
259 pub fn supertraits<'tcx>(
260     tcx: TyCtxt<'tcx>,
261     trait_ref: ty::PolyTraitRef<'tcx>,
262 ) -> Supertraits<'tcx> {
263     elaborate_trait_ref(tcx, trait_ref).filter_to_traits()
264 }
265
266 pub fn transitive_bounds<'tcx>(
267     tcx: TyCtxt<'tcx>,
268     bounds: impl Iterator<Item = ty::PolyTraitRef<'tcx>>,
269 ) -> Supertraits<'tcx> {
270     elaborate_trait_refs(tcx, bounds).filter_to_traits()
271 }
272
273 ///////////////////////////////////////////////////////////////////////////
274 // `TraitAliasExpander` iterator
275 ///////////////////////////////////////////////////////////////////////////
276
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> {
286     tcx: TyCtxt<'tcx>,
287     stack: Vec<TraitAliasExpansionInfo<'tcx>>,
288 }
289
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]>,
294 }
295
296 impl<'tcx> TraitAliasExpansionInfo<'tcx> {
297     fn new(trait_ref: ty::PolyTraitRef<'tcx>, span: Span) -> Self {
298         Self { path: smallvec![(trait_ref, span)] }
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(
304         &self,
305         diag: &mut DiagnosticBuilder<'_>,
306         top_label: &str,
307         use_desc: &str,
308     ) {
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));
313             }
314         }
315         diag.span_label(
316             self.bottom().1,
317             format!("trait alias used in trait object type ({})", use_desc),
318         );
319     }
320
321     pub fn trait_ref(&self) -> &ty::PolyTraitRef<'tcx> {
322         &self.top().0
323     }
324
325     pub fn top(&self) -> &(ty::PolyTraitRef<'tcx>, Span) {
326         self.path.last().unwrap()
327     }
328
329     pub fn bottom(&self) -> &(ty::PolyTraitRef<'tcx>, Span) {
330         self.path.first().unwrap()
331     }
332
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));
336
337         Self { path }
338     }
339 }
340
341 pub fn expand_trait_aliases<'tcx>(
342     tcx: TyCtxt<'tcx>,
343     trait_refs: impl IntoIterator<Item = (ty::PolyTraitRef<'tcx>, Span)>,
344 ) -> TraitAliasExpander<'tcx> {
345     let items: Vec<_> = trait_refs
346         .into_iter()
347         .map(|(trait_ref, span)| TraitAliasExpansionInfo::new(trait_ref, span))
348         .collect();
349     TraitAliasExpander { tcx, stack: items }
350 }
351
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
356     /// trait alias.
357     /// The return value indicates whether `item` should be yielded to the user.
358     fn expand(&mut self, item: &TraitAliasExpansionInfo<'tcx>) -> bool {
359         let tcx = self.tcx;
360         let trait_ref = item.trait_ref();
361         let pred = trait_ref.to_predicate();
362
363         debug!("expand_trait_aliases: trait_ref={:?}", trait_ref);
364
365         // Don't recurse if this bound is not a trait alias.
366         let is_alias = tcx.is_trait_alias(trait_ref.def_id());
367         if !is_alias {
368             return true;
369         }
370
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);
373         if item
374             .path
375             .iter()
376             .rev()
377             .skip(1)
378             .any(|(tr, _)| anonymize_predicate(tcx, &tr.to_predicate()) == anon_pred)
379         {
380             return false;
381         }
382
383         // Get components of trait alias.
384         let predicates = tcx.super_predicates_of(trait_ref.def_id());
385
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))
390         });
391         debug!("expand_trait_aliases: items={:?}", items.clone());
392
393         self.stack.extend(items);
394
395         false
396     }
397 }
398
399 impl<'tcx> Iterator for TraitAliasExpander<'tcx> {
400     type Item = TraitAliasExpansionInfo<'tcx>;
401
402     fn size_hint(&self) -> (usize, Option<usize>) {
403         (self.stack.len(), None)
404     }
405
406     fn next(&mut self) -> Option<TraitAliasExpansionInfo<'tcx>> {
407         while let Some(item) = self.stack.pop() {
408             if self.expand(&item) {
409                 return Some(item);
410             }
411         }
412         None
413     }
414 }
415
416 ///////////////////////////////////////////////////////////////////////////
417 // Iterator over def-IDs of supertraits
418 ///////////////////////////////////////////////////////////////////////////
419
420 pub struct SupertraitDefIds<'tcx> {
421     tcx: TyCtxt<'tcx>,
422     stack: Vec<DefId>,
423     visited: FxHashSet<DefId>,
424 }
425
426 pub fn supertrait_def_ids(tcx: TyCtxt<'_>, trait_def_id: DefId) -> SupertraitDefIds<'_> {
427     SupertraitDefIds {
428         tcx,
429         stack: vec![trait_def_id],
430         visited: Some(trait_def_id).into_iter().collect(),
431     }
432 }
433
434 impl Iterator for SupertraitDefIds<'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
443                 .predicates
444                 .iter()
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)),
448         );
449         Some(def_id)
450     }
451 }
452
453 ///////////////////////////////////////////////////////////////////////////
454 // Other
455 ///////////////////////////////////////////////////////////////////////////
456
457 /// A filter around an iterator of predicates that makes it yield up
458 /// just trait references.
459 pub struct FilterToTraits<I> {
460     base_iterator: I,
461 }
462
463 impl<I> FilterToTraits<I> {
464     fn new(base: I) -> FilterToTraits<I> {
465         FilterToTraits { base_iterator: base }
466     }
467 }
468
469 impl<'tcx, I: Iterator<Item = ty::Predicate<'tcx>>> Iterator for FilterToTraits<I> {
470     type Item = ty::PolyTraitRef<'tcx>;
471
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());
476             }
477         }
478         None
479     }
480
481     fn size_hint(&self) -> (usize, Option<usize>) {
482         let (_, upper) = self.base_iterator.size_hint();
483         (0, upper)
484     }
485 }
486
487 ///////////////////////////////////////////////////////////////////////////
488 // Other
489 ///////////////////////////////////////////////////////////////////////////
490
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>,
497     impl_def_id: DefId,
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);
504
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);
511
512     let impl_obligations: Vec<_> = impl_obligations
513         .into_iter()
514         .chain(normalization_obligations1)
515         .chain(normalization_obligations2)
516         .collect();
517
518     (impl_trait_ref, impl_obligations)
519 }
520
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);
529
530     generic_bounds
531         .predicates
532         .iter()
533         .map(|predicate| Obligation {
534             cause: cause.clone(),
535             recursion_depth,
536             param_env,
537             predicate: predicate.clone(),
538         })
539         .collect()
540 }
541
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() }
549 }
550
551 pub fn predicate_for_trait_def(
552     tcx: TyCtxt<'tcx>,
553     param_env: ty::ParamEnv<'tcx>,
554     cause: ObligationCause<'tcx>,
555     trait_def_id: DefId,
556     recursion_depth: usize,
557     self_ty: Ty<'tcx>,
558     params: &[GenericArg<'tcx>],
559 ) -> PredicateObligation<'tcx> {
560     let trait_ref =
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)
563 }
564
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
567 /// supertrait.
568 pub fn upcast_choices(
569     tcx: TyCtxt<'tcx>,
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.
575     }
576
577     supertraits(tcx, source_trait_ref).filter(|r| r.def_id() == target_trait_def_id).collect()
578 }
579
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 {
584     let mut entries = 0;
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 {
589             entries += 1;
590         }
591     }
592     entries
593 }
594
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>(
599     tcx: TyCtxt<'tcx>,
600     object: &super::VtableObjectData<'tcx, N>,
601     method_def_id: DefId,
602 ) -> usize {
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);
611             return entries;
612         }
613         if trait_item.kind == ty::AssocKind::Method {
614             entries += 1;
615         }
616     }
617
618     bug!("get_vtable_index_of_object_method: {:?} was not found", method_def_id);
619 }
620
621 pub fn closure_trait_ref_and_return_type(
622     tcx: TyCtxt<'tcx>,
623     fn_trait_def_id: DefId,
624     self_ty: Ty<'tcx>,
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()),
631     };
632     let trait_ref = ty::TraitRef {
633         def_id: fn_trait_def_id,
634         substs: tcx.mk_substs_trait(self_ty, &[arguments_tuple.into()]),
635     };
636     ty::Binder::bind((trait_ref, sig.skip_binder().output()))
637 }
638
639 pub fn generator_trait_ref_and_outputs(
640     tcx: TyCtxt<'tcx>,
641     fn_trait_def_id: DefId,
642     self_ty: Ty<'tcx>,
643     sig: ty::PolyGenSig<'tcx>,
644 ) -> ty::Binder<(ty::TraitRef<'tcx>, Ty<'tcx>, Ty<'tcx>)> {
645     let trait_ref =
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))
648 }
649
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) {
652         Some(hir_id) => {
653             let item = tcx.hir().expect_item(hir_id);
654             if let hir::ItemKind::Impl(_, _, defaultness, ..) = item.kind {
655                 defaultness.is_default()
656             } else {
657                 false
658             }
659         }
660         None => tcx.impl_defaultness(node_item_def_id).is_default(),
661     }
662 }
663
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())
666 }
667
668 pub enum TupleArgumentsFlag {
669     Yes,
670     No,
671 }