]> git.lizzy.rs Git - rust.git/blob - src/librustc/traits/object_safety.rs
Add riscv64gc-unknown-none-elf target
[rust.git] / src / librustc / traits / object_safety.rs
1 //! "Object safety" refers to the ability for a trait to be converted
2 //! to an object. In general, traits may only be converted to an
3 //! object if all of their methods meet certain criteria. In particular,
4 //! they must:
5 //!
6 //!   - have a suitable receiver from which we can extract a vtable and coerce to a "thin" version
7 //!     that doesn't contain the vtable;
8 //!   - not reference the erased type `Self` except for in this receiver;
9 //!   - not have generic type parameters
10
11 use super::elaborate_predicates;
12
13 use crate::hir::def_id::DefId;
14 use crate::lint;
15 use crate::traits::{self, Obligation, ObligationCause};
16 use crate::ty::{self, Ty, TyCtxt, TypeFoldable, Predicate, ToPredicate};
17 use crate::ty::subst::{Subst, Substs};
18 use std::borrow::Cow;
19 use std::iter::{self};
20 use syntax::ast::{self, Name};
21 use syntax_pos::Span;
22
23 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
24 pub enum ObjectSafetyViolation {
25     /// Self : Sized declared on the trait
26     SizedSelf,
27
28     /// Supertrait reference references `Self` an in illegal location
29     /// (e.g., `trait Foo : Bar<Self>`)
30     SupertraitSelf,
31
32     /// Method has something illegal
33     Method(ast::Name, MethodViolationCode),
34
35     /// Associated const
36     AssociatedConst(ast::Name),
37 }
38
39 impl ObjectSafetyViolation {
40     pub fn error_msg(&self) -> Cow<'static, str> {
41         match *self {
42             ObjectSafetyViolation::SizedSelf =>
43                 "the trait cannot require that `Self : Sized`".into(),
44             ObjectSafetyViolation::SupertraitSelf =>
45                 "the trait cannot use `Self` as a type parameter \
46                  in the supertraits or where-clauses".into(),
47             ObjectSafetyViolation::Method(name, MethodViolationCode::StaticMethod) =>
48                 format!("method `{}` has no receiver", name).into(),
49             ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelf) =>
50                 format!("method `{}` references the `Self` type \
51                          in its arguments or return type", name).into(),
52             ObjectSafetyViolation::Method(name,
53                                             MethodViolationCode::WhereClauseReferencesSelf(_)) =>
54                 format!("method `{}` references the `Self` type in where clauses", name).into(),
55             ObjectSafetyViolation::Method(name, MethodViolationCode::Generic) =>
56                 format!("method `{}` has generic type parameters", name).into(),
57             ObjectSafetyViolation::Method(name, MethodViolationCode::UndispatchableReceiver) =>
58                 format!("method `{}`'s receiver cannot be dispatched on", name).into(),
59             ObjectSafetyViolation::AssociatedConst(name) =>
60                 format!("the trait cannot contain associated consts like `{}`", name).into(),
61         }
62     }
63 }
64
65 /// Reasons a method might not be object-safe.
66 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
67 pub enum MethodViolationCode {
68     /// e.g., `fn foo()`
69     StaticMethod,
70
71     /// e.g., `fn foo(&self, x: Self)` or `fn foo(&self) -> Self`
72     ReferencesSelf,
73
74     /// e.g., `fn foo(&self) where Self: Clone`
75     WhereClauseReferencesSelf(Span),
76
77     /// e.g., `fn foo<A>()`
78     Generic,
79
80     /// the method's receiver (`self` argument) can't be dispatched on
81     UndispatchableReceiver,
82 }
83
84 impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> {
85
86     /// Returns the object safety violations that affect
87     /// astconv - currently, Self in supertraits. This is needed
88     /// because `object_safety_violations` can't be used during
89     /// type collection.
90     pub fn astconv_object_safety_violations(self, trait_def_id: DefId)
91                                             -> Vec<ObjectSafetyViolation>
92     {
93         let violations = traits::supertrait_def_ids(self, trait_def_id)
94             .filter(|&def_id| self.predicates_reference_self(def_id, true))
95             .map(|_| ObjectSafetyViolation::SupertraitSelf)
96             .collect();
97
98         debug!("astconv_object_safety_violations(trait_def_id={:?}) = {:?}",
99                trait_def_id,
100                violations);
101
102         violations
103     }
104
105     pub fn object_safety_violations(self, trait_def_id: DefId)
106                                     -> Vec<ObjectSafetyViolation>
107     {
108         debug!("object_safety_violations: {:?}", trait_def_id);
109
110         traits::supertrait_def_ids(self, trait_def_id)
111             .flat_map(|def_id| self.object_safety_violations_for_trait(def_id))
112             .collect()
113     }
114
115     fn object_safety_violations_for_trait(self, trait_def_id: DefId)
116                                           -> Vec<ObjectSafetyViolation>
117     {
118         // Check methods for violations.
119         let mut violations: Vec<_> = self.associated_items(trait_def_id)
120             .filter(|item| item.kind == ty::AssociatedKind::Method)
121             .filter_map(|item|
122                 self.object_safety_violation_for_method(trait_def_id, &item)
123                     .map(|code| ObjectSafetyViolation::Method(item.ident.name, code))
124             ).filter(|violation| {
125                 if let ObjectSafetyViolation::Method(_,
126                     MethodViolationCode::WhereClauseReferencesSelf(span)) = violation
127                 {
128                     // Using `CRATE_NODE_ID` is wrong, but it's hard to get a more precise id.
129                     // It's also hard to get a use site span, so we use the method definition span.
130                     self.lint_node_note(
131                         lint::builtin::WHERE_CLAUSES_OBJECT_SAFETY,
132                         ast::CRATE_NODE_ID,
133                         *span,
134                         &format!("the trait `{}` cannot be made into an object",
135                                  self.item_path_str(trait_def_id)),
136                         &violation.error_msg());
137                     false
138                 } else {
139                     true
140                 }
141             }).collect();
142
143         // Check the trait itself.
144         if self.trait_has_sized_self(trait_def_id) {
145             violations.push(ObjectSafetyViolation::SizedSelf);
146         }
147         if self.predicates_reference_self(trait_def_id, false) {
148             violations.push(ObjectSafetyViolation::SupertraitSelf);
149         }
150
151         violations.extend(self.associated_items(trait_def_id)
152             .filter(|item| item.kind == ty::AssociatedKind::Const)
153             .map(|item| ObjectSafetyViolation::AssociatedConst(item.ident.name)));
154
155         debug!("object_safety_violations_for_trait(trait_def_id={:?}) = {:?}",
156                trait_def_id,
157                violations);
158
159         violations
160     }
161
162     fn predicates_reference_self(
163         self,
164         trait_def_id: DefId,
165         supertraits_only: bool) -> bool
166     {
167         let trait_ref = ty::Binder::dummy(ty::TraitRef::identity(self, trait_def_id));
168         let predicates = if supertraits_only {
169             self.super_predicates_of(trait_def_id)
170         } else {
171             self.predicates_of(trait_def_id)
172         };
173         predicates
174             .predicates
175             .iter()
176             .map(|(predicate, _)| predicate.subst_supertrait(self, &trait_ref))
177             .any(|predicate| {
178                 match predicate {
179                     ty::Predicate::Trait(ref data) => {
180                         // In the case of a trait predicate, we can skip the "self" type.
181                         data.skip_binder().input_types().skip(1).any(|t| t.has_self_ty())
182                     }
183                     ty::Predicate::Projection(ref data) => {
184                         // And similarly for projections. This should be redundant with
185                         // the previous check because any projection should have a
186                         // matching `Trait` predicate with the same inputs, but we do
187                         // the check to be safe.
188                         //
189                         // Note that we *do* allow projection *outputs* to contain
190                         // `self` (i.e., `trait Foo: Bar<Output=Self::Result> { type Result; }`),
191                         // we just require the user to specify *both* outputs
192                         // in the object type (i.e., `dyn Foo<Output=(), Result=()>`).
193                         //
194                         // This is ALT2 in issue #56288, see that for discussion of the
195                         // possible alternatives.
196                         data.skip_binder()
197                             .projection_ty
198                             .trait_ref(self)
199                             .input_types()
200                             .skip(1)
201                             .any(|t| t.has_self_ty())
202                     }
203                     ty::Predicate::WellFormed(..) |
204                     ty::Predicate::ObjectSafe(..) |
205                     ty::Predicate::TypeOutlives(..) |
206                     ty::Predicate::RegionOutlives(..) |
207                     ty::Predicate::ClosureKind(..) |
208                     ty::Predicate::Subtype(..) |
209                     ty::Predicate::ConstEvaluatable(..) => {
210                         false
211                     }
212                 }
213             })
214     }
215
216     fn trait_has_sized_self(self, trait_def_id: DefId) -> bool {
217         self.generics_require_sized_self(trait_def_id)
218     }
219
220     fn generics_require_sized_self(self, def_id: DefId) -> bool {
221         let sized_def_id = match self.lang_items().sized_trait() {
222             Some(def_id) => def_id,
223             None => { return false; /* No Sized trait, can't require it! */ }
224         };
225
226         // Search for a predicate like `Self : Sized` amongst the trait bounds.
227         let predicates = self.predicates_of(def_id);
228         let predicates = predicates.instantiate_identity(self).predicates;
229         elaborate_predicates(self, predicates)
230             .any(|predicate| match predicate {
231                 ty::Predicate::Trait(ref trait_pred) if trait_pred.def_id() == sized_def_id => {
232                     trait_pred.skip_binder().self_ty().is_self()
233                 }
234                 ty::Predicate::Projection(..) |
235                 ty::Predicate::Trait(..) |
236                 ty::Predicate::Subtype(..) |
237                 ty::Predicate::RegionOutlives(..) |
238                 ty::Predicate::WellFormed(..) |
239                 ty::Predicate::ObjectSafe(..) |
240                 ty::Predicate::ClosureKind(..) |
241                 ty::Predicate::TypeOutlives(..) |
242                 ty::Predicate::ConstEvaluatable(..) => {
243                     false
244                 }
245             }
246         )
247     }
248
249     /// Returns `Some(_)` if this method makes the containing trait not object safe.
250     fn object_safety_violation_for_method(self,
251                                           trait_def_id: DefId,
252                                           method: &ty::AssociatedItem)
253                                           -> Option<MethodViolationCode>
254     {
255         debug!("object_safety_violation_for_method({:?}, {:?})", trait_def_id, method);
256         // Any method that has a `Self : Sized` requisite is otherwise
257         // exempt from the regulations.
258         if self.generics_require_sized_self(method.def_id) {
259             return None;
260         }
261
262         self.virtual_call_violation_for_method(trait_def_id, method)
263     }
264
265     /// We say a method is *vtable safe* if it can be invoked on a trait
266     /// object.  Note that object-safe traits can have some
267     /// non-vtable-safe methods, so long as they require `Self:Sized` or
268     /// otherwise ensure that they cannot be used when `Self=Trait`.
269     pub fn is_vtable_safe_method(self,
270                                  trait_def_id: DefId,
271                                  method: &ty::AssociatedItem)
272                                  -> bool
273     {
274         debug!("is_vtable_safe_method({:?}, {:?})", trait_def_id, method);
275         // Any method that has a `Self : Sized` requisite can't be called.
276         if self.generics_require_sized_self(method.def_id) {
277             return false;
278         }
279
280         match self.virtual_call_violation_for_method(trait_def_id, method) {
281             None | Some(MethodViolationCode::WhereClauseReferencesSelf(_)) => true,
282             Some(_) => false,
283         }
284     }
285
286     /// Returns `Some(_)` if this method cannot be called on a trait
287     /// object; this does not necessarily imply that the enclosing trait
288     /// is not object safe, because the method might have a where clause
289     /// `Self:Sized`.
290     fn virtual_call_violation_for_method(self,
291                                          trait_def_id: DefId,
292                                          method: &ty::AssociatedItem)
293                                          -> Option<MethodViolationCode>
294     {
295         // The method's first parameter must be named `self`
296         if !method.method_has_self_argument {
297             return Some(MethodViolationCode::StaticMethod);
298         }
299
300         let sig = self.fn_sig(method.def_id);
301
302         for input_ty in &sig.skip_binder().inputs()[1..] {
303             if self.contains_illegal_self_type_reference(trait_def_id, input_ty) {
304                 return Some(MethodViolationCode::ReferencesSelf);
305             }
306         }
307         if self.contains_illegal_self_type_reference(trait_def_id, sig.output().skip_binder()) {
308             return Some(MethodViolationCode::ReferencesSelf);
309         }
310
311         // We can't monomorphize things like `fn foo<A>(...)`.
312         if self.generics_of(method.def_id).own_counts().types != 0 {
313             return Some(MethodViolationCode::Generic);
314         }
315
316         if self.predicates_of(method.def_id).predicates.iter()
317                 // A trait object can't claim to live more than the concrete type,
318                 // so outlives predicates will always hold.
319                 .cloned()
320                 .filter(|(p, _)| p.to_opt_type_outlives().is_none())
321                 .collect::<Vec<_>>()
322                 // Do a shallow visit so that `contains_illegal_self_type_reference`
323                 // may apply it's custom visiting.
324                 .visit_tys_shallow(|t| self.contains_illegal_self_type_reference(trait_def_id, t)) {
325             let span = self.def_span(method.def_id);
326             return Some(MethodViolationCode::WhereClauseReferencesSelf(span));
327         }
328
329         let receiver_ty = self.liberate_late_bound_regions(
330             method.def_id,
331             &sig.map_bound(|sig| sig.inputs()[0]),
332         );
333
334         // until `unsized_locals` is fully implemented, `self: Self` can't be dispatched on.
335         // However, this is already considered object-safe. We allow it as a special case here.
336         // FIXME(mikeyhew) get rid of this `if` statement once `receiver_is_dispatchable` allows
337         // `Receiver: Unsize<Receiver[Self => dyn Trait]>`
338         if receiver_ty != self.mk_self_type() {
339             if !self.receiver_is_dispatchable(method, receiver_ty) {
340                 return Some(MethodViolationCode::UndispatchableReceiver);
341             } else {
342                 // sanity check to make sure the receiver actually has the layout of a pointer
343
344                 use crate::ty::layout::Abi;
345
346                 let param_env = self.param_env(method.def_id);
347
348                 let abi_of_ty = |ty: Ty<'tcx>| -> &Abi {
349                     match self.layout_of(param_env.and(ty)) {
350                         Ok(layout) => &layout.abi,
351                         Err(err) => bug!(
352                             "Error: {}\n while computing layout for type {:?}", err, ty
353                         )
354                     }
355                 };
356
357                 // e.g., Rc<()>
358                 let unit_receiver_ty = self.receiver_for_self_ty(
359                     receiver_ty, self.mk_unit(), method.def_id
360                 );
361
362                 match abi_of_ty(unit_receiver_ty) {
363                     &Abi::Scalar(..) => (),
364                     abi => {
365                         self.sess.delay_span_bug(
366                             self.def_span(method.def_id),
367                             &format!(
368                                 "Receiver when Self = () should have a Scalar ABI, found {:?}",
369                                 abi
370                             ),
371                         );
372                     }
373                 }
374
375                 let trait_object_ty = self.object_ty_for_trait(
376                     trait_def_id, self.mk_region(ty::ReStatic)
377                 );
378
379                 // e.g., Rc<dyn Trait>
380                 let trait_object_receiver = self.receiver_for_self_ty(
381                     receiver_ty, trait_object_ty, method.def_id
382                 );
383
384                 match abi_of_ty(trait_object_receiver) {
385                     &Abi::ScalarPair(..) => (),
386                     abi => {
387                         self.sess.delay_span_bug(
388                             self.def_span(method.def_id),
389                             &format!(
390                                 "Receiver when Self = {} should have a ScalarPair ABI, found {:?}",
391                                 trait_object_ty, abi
392                             ),
393                         );
394                     }
395                 }
396             }
397         }
398
399         None
400     }
401
402     /// performs a type substitution to produce the version of receiver_ty when `Self = self_ty`
403     /// e.g., for receiver_ty = `Rc<Self>` and self_ty = `Foo`, returns `Rc<Foo>`
404     fn receiver_for_self_ty(
405         self, receiver_ty: Ty<'tcx>, self_ty: Ty<'tcx>, method_def_id: DefId
406     ) -> Ty<'tcx> {
407         debug!("receiver_for_self_ty({:?}, {:?}, {:?})", receiver_ty, self_ty, method_def_id);
408         let substs = Substs::for_item(self, method_def_id, |param, _| {
409             if param.index == 0 {
410                 self_ty.into()
411             } else {
412                 self.mk_param_from_def(param)
413             }
414         });
415
416         let result = receiver_ty.subst(self, substs);
417         debug!("receiver_for_self_ty({:?}, {:?}, {:?}) = {:?}",
418                receiver_ty, self_ty, method_def_id, result);
419         result
420     }
421
422     /// creates the object type for the current trait. For example,
423     /// if the current trait is `Deref`, then this will be
424     /// `dyn Deref<Target=Self::Target> + 'static`
425     fn object_ty_for_trait(self, trait_def_id: DefId, lifetime: ty::Region<'tcx>) -> Ty<'tcx> {
426         debug!("object_ty_for_trait: trait_def_id={:?}", trait_def_id);
427
428         let trait_ref = ty::TraitRef::identity(self, trait_def_id);
429
430         let trait_predicate = ty::ExistentialPredicate::Trait(
431             ty::ExistentialTraitRef::erase_self_ty(self, trait_ref)
432         );
433
434         let mut associated_types = traits::supertraits(self, ty::Binder::dummy(trait_ref))
435             .flat_map(|super_trait_ref| {
436                 self.associated_items(super_trait_ref.def_id())
437                     .map(move |item| (super_trait_ref, item))
438             })
439             .filter(|(_, item)| item.kind == ty::AssociatedKind::Type)
440             .collect::<Vec<_>>();
441
442         // existential predicates need to be in a specific order
443         associated_types.sort_by_cached_key(|(_, item)| self.def_path_hash(item.def_id));
444
445         let projection_predicates = associated_types.into_iter().map(|(super_trait_ref, item)| {
446             // We *can* get bound lifetimes here in cases like
447             // `trait MyTrait: for<'s> OtherTrait<&'s T, Output=bool>`.
448             //
449             // binder moved to (*)...
450             let super_trait_ref = super_trait_ref.skip_binder();
451             ty::ExistentialPredicate::Projection(ty::ExistentialProjection {
452                 ty: self.mk_projection(item.def_id, super_trait_ref.substs),
453                 item_def_id: item.def_id,
454                 substs: super_trait_ref.substs,
455             })
456         });
457
458         let existential_predicates = self.mk_existential_predicates(
459             iter::once(trait_predicate).chain(projection_predicates)
460         );
461
462         let object_ty = self.mk_dynamic(
463             // (*) ... binder re-introduced here
464             ty::Binder::bind(existential_predicates),
465             lifetime,
466         );
467
468         debug!("object_ty_for_trait: object_ty=`{}`", object_ty);
469
470         object_ty
471     }
472
473     /// checks the method's receiver (the `self` argument) can be dispatched on when `Self` is a
474     /// trait object. We require that `DispatchableFromDyn` be implemented for the receiver type
475     /// in the following way:
476     /// - let `Receiver` be the type of the `self` argument, i.e `Self`, `&Self`, `Rc<Self>`
477     /// - require the following bound:
478     ///
479     ///        Receiver[Self => T]: DispatchFromDyn<Receiver[Self => dyn Trait]>
480     ///
481     ///    where `Foo[X => Y]` means "the same type as `Foo`, but with `X` replaced with `Y`"
482     ///   (substitution notation).
483     ///
484     /// some examples of receiver types and their required obligation
485     /// - `&'a mut self` requires `&'a mut Self: DispatchFromDyn<&'a mut dyn Trait>`
486     /// - `self: Rc<Self>` requires `Rc<Self>: DispatchFromDyn<Rc<dyn Trait>>`
487     /// - `self: Pin<Box<Self>>` requires `Pin<Box<Self>>: DispatchFromDyn<Pin<Box<dyn Trait>>>`
488     ///
489     /// The only case where the receiver is not dispatchable, but is still a valid receiver
490     /// type (just not object-safe), is when there is more than one level of pointer indirection.
491     /// e.g., `self: &&Self`, `self: &Rc<Self>`, `self: Box<Box<Self>>`. In these cases, there
492     /// is no way, or at least no inexpensive way, to coerce the receiver from the version where
493     /// `Self = dyn Trait` to the version where `Self = T`, where `T` is the unknown erased type
494     /// contained by the trait object, because the object that needs to be coerced is behind
495     /// a pointer.
496     ///
497     /// In practice, we cannot use `dyn Trait` explicitly in the obligation because it would result
498     /// in a new check that `Trait` is object safe, creating a cycle. So instead, we fudge a little
499     /// by introducing a new type parameter `U` such that `Self: Unsize<U>` and `U: Trait + ?Sized`,
500     /// and use `U` in place of `dyn Trait`. Written as a chalk-style query:
501     ///
502     ///     forall (U: Trait + ?Sized) {
503     ///         if (Self: Unsize<U>) {
504     ///             Receiver: DispatchFromDyn<Receiver[Self => U]>
505     ///         }
506     ///     }
507     ///
508     /// for `self: &'a mut Self`, this means `&'a mut Self: DispatchFromDyn<&'a mut U>`
509     /// for `self: Rc<Self>`, this means `Rc<Self>: DispatchFromDyn<Rc<U>>`
510     /// for `self: Pin<Box<Self>>`, this means `Pin<Box<Self>>: DispatchFromDyn<Pin<Box<U>>>`
511     //
512     // FIXME(mikeyhew) when unsized receivers are implemented as part of unsized rvalues, add this
513     // fallback query: `Receiver: Unsize<Receiver[Self => U]>` to support receivers like
514     // `self: Wrapper<Self>`.
515     #[allow(dead_code)]
516     fn receiver_is_dispatchable(
517         self,
518         method: &ty::AssociatedItem,
519         receiver_ty: Ty<'tcx>,
520     ) -> bool {
521         debug!("receiver_is_dispatchable: method = {:?}, receiver_ty = {:?}", method, receiver_ty);
522
523         let traits = (self.lang_items().unsize_trait(),
524                       self.lang_items().dispatch_from_dyn_trait());
525         let (unsize_did, dispatch_from_dyn_did) = if let (Some(u), Some(cu)) = traits {
526             (u, cu)
527         } else {
528             debug!("receiver_is_dispatchable: Missing Unsize or DispatchFromDyn traits");
529             return false;
530         };
531
532         // the type `U` in the query
533         // use a bogus type parameter to mimick a forall(U) query using u32::MAX for now.
534         // FIXME(mikeyhew) this is a total hack, and we should replace it when real forall queries
535         // are implemented
536         let unsized_self_ty: Ty<'tcx> = self.mk_ty_param(
537             ::std::u32::MAX,
538             Name::intern("RustaceansAreAwesome").as_interned_str(),
539         );
540
541         // `Receiver[Self => U]`
542         let unsized_receiver_ty = self.receiver_for_self_ty(
543             receiver_ty, unsized_self_ty, method.def_id
544         );
545
546         // create a modified param env, with `Self: Unsize<U>` and `U: Trait` added to caller bounds
547         // `U: ?Sized` is already implied here
548         let param_env = {
549             let mut param_env = self.param_env(method.def_id);
550
551             // Self: Unsize<U>
552             let unsize_predicate = ty::TraitRef {
553                 def_id: unsize_did,
554                 substs: self.mk_substs_trait(self.mk_self_type(), &[unsized_self_ty.into()]),
555             }.to_predicate();
556
557             // U: Trait<Arg1, ..., ArgN>
558             let trait_predicate = {
559                 let substs = Substs::for_item(self, method.container.assert_trait(), |param, _| {
560                     if param.index == 0 {
561                         unsized_self_ty.into()
562                     } else {
563                         self.mk_param_from_def(param)
564                     }
565                 });
566
567                 ty::TraitRef {
568                     def_id: unsize_did,
569                     substs,
570                 }.to_predicate()
571             };
572
573             let caller_bounds: Vec<Predicate<'tcx>> = param_env.caller_bounds.iter().cloned()
574                 .chain(iter::once(unsize_predicate))
575                 .chain(iter::once(trait_predicate))
576                 .collect();
577
578             param_env.caller_bounds = self.intern_predicates(&caller_bounds);
579
580             param_env
581         };
582
583         // Receiver: DispatchFromDyn<Receiver[Self => U]>
584         let obligation = {
585             let predicate = ty::TraitRef {
586                 def_id: dispatch_from_dyn_did,
587                 substs: self.mk_substs_trait(receiver_ty, &[unsized_receiver_ty.into()]),
588             }.to_predicate();
589
590             Obligation::new(
591                 ObligationCause::dummy(),
592                 param_env,
593                 predicate,
594             )
595         };
596
597         self.infer_ctxt().enter(|ref infcx| {
598             // the receiver is dispatchable iff the obligation holds
599             infcx.predicate_must_hold_modulo_regions(&obligation)
600         })
601     }
602
603     fn contains_illegal_self_type_reference(self,
604                                             trait_def_id: DefId,
605                                             ty: Ty<'tcx>)
606                                             -> bool
607     {
608         // This is somewhat subtle. In general, we want to forbid
609         // references to `Self` in the argument and return types,
610         // since the value of `Self` is erased. However, there is one
611         // exception: it is ok to reference `Self` in order to access
612         // an associated type of the current trait, since we retain
613         // the value of those associated types in the object type
614         // itself.
615         //
616         // ```rust
617         // trait SuperTrait {
618         //     type X;
619         // }
620         //
621         // trait Trait : SuperTrait {
622         //     type Y;
623         //     fn foo(&self, x: Self) // bad
624         //     fn foo(&self) -> Self // bad
625         //     fn foo(&self) -> Option<Self> // bad
626         //     fn foo(&self) -> Self::Y // OK, desugars to next example
627         //     fn foo(&self) -> <Self as Trait>::Y // OK
628         //     fn foo(&self) -> Self::X // OK, desugars to next example
629         //     fn foo(&self) -> <Self as SuperTrait>::X // OK
630         // }
631         // ```
632         //
633         // However, it is not as simple as allowing `Self` in a projected
634         // type, because there are illegal ways to use `Self` as well:
635         //
636         // ```rust
637         // trait Trait : SuperTrait {
638         //     ...
639         //     fn foo(&self) -> <Self as SomeOtherTrait>::X;
640         // }
641         // ```
642         //
643         // Here we will not have the type of `X` recorded in the
644         // object type, and we cannot resolve `Self as SomeOtherTrait`
645         // without knowing what `Self` is.
646
647         let mut supertraits: Option<Vec<ty::PolyTraitRef<'tcx>>> = None;
648         let mut error = false;
649         ty.maybe_walk(|ty| {
650             match ty.sty {
651                 ty::Param(ref param_ty) => {
652                     if param_ty.is_self() {
653                         error = true;
654                     }
655
656                     false // no contained types to walk
657                 }
658
659                 ty::Projection(ref data) => {
660                     // This is a projected type `<Foo as SomeTrait>::X`.
661
662                     // Compute supertraits of current trait lazily.
663                     if supertraits.is_none() {
664                         let trait_ref = ty::Binder::bind(
665                             ty::TraitRef::identity(self, trait_def_id),
666                         );
667                         supertraits = Some(traits::supertraits(self, trait_ref).collect());
668                     }
669
670                     // Determine whether the trait reference `Foo as
671                     // SomeTrait` is in fact a supertrait of the
672                     // current trait. In that case, this type is
673                     // legal, because the type `X` will be specified
674                     // in the object type.  Note that we can just use
675                     // direct equality here because all of these types
676                     // are part of the formal parameter listing, and
677                     // hence there should be no inference variables.
678                     let projection_trait_ref = ty::Binder::bind(data.trait_ref(self));
679                     let is_supertrait_of_current_trait =
680                         supertraits.as_ref().unwrap().contains(&projection_trait_ref);
681
682                     if is_supertrait_of_current_trait {
683                         false // do not walk contained types, do not report error, do collect $200
684                     } else {
685                         true // DO walk contained types, POSSIBLY reporting an error
686                     }
687                 }
688
689                 _ => true, // walk contained types, if any
690             }
691         });
692
693         error
694     }
695 }
696
697 pub(super) fn is_object_safe_provider<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
698                                                 trait_def_id: DefId) -> bool {
699     tcx.object_safety_violations(trait_def_id).is_empty()
700 }