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