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