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