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