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