]> git.lizzy.rs Git - rust.git/blob - src/librustc/traits/object_safety.rs
Rollup merge of #67822 - wesleywiser:revert_67676, r=oli-obk
[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::subst::{InternalSubsts, Subst};
18 use crate::ty::{self, Predicate, ToPredicate, Ty, TyCtxt, TypeFoldable};
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 impl<'tcx> TyCtxt<'tcx> {
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         self,
118         trait_def_id: DefId,
119     ) -> Vec<ObjectSafetyViolation> {
120         debug_assert!(self.generics_of(trait_def_id).has_self);
121         let violations = traits::supertrait_def_ids(self, trait_def_id)
122             .filter(|&def_id| self.predicates_reference_self(def_id, true))
123             .map(|_| ObjectSafetyViolation::SupertraitSelf)
124             .collect();
125
126         debug!(
127             "astconv_object_safety_violations(trait_def_id={:?}) = {:?}",
128             trait_def_id, violations
129         );
130
131         violations
132     }
133
134     pub fn object_safety_violations(self, trait_def_id: DefId) -> Vec<ObjectSafetyViolation> {
135         debug_assert!(self.generics_of(trait_def_id).has_self);
136         debug!("object_safety_violations: {:?}", trait_def_id);
137
138         traits::supertrait_def_ids(self, trait_def_id)
139             .flat_map(|def_id| self.object_safety_violations_for_trait(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(self, trait_def_id: DefId, method: &ty::AssocItem) -> bool {
148         debug_assert!(self.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 self.generics_require_sized_self(method.def_id) {
152             return false;
153         }
154
155         match self.virtual_call_violation_for_method(trait_def_id, method) {
156             None | Some(MethodViolationCode::WhereClauseReferencesSelf) => true,
157             Some(_) => false,
158         }
159     }
160
161     fn object_safety_violations_for_trait(self, trait_def_id: DefId) -> Vec<ObjectSafetyViolation> {
162         // Check methods for violations.
163         let mut violations: Vec<_> = self
164             .associated_items(trait_def_id)
165             .filter(|item| item.kind == ty::AssocKind::Method)
166             .filter_map(|item| {
167                 self.object_safety_violation_for_method(trait_def_id, &item).map(|code| {
168                     ObjectSafetyViolation::Method(item.ident.name, code, item.ident.span)
169                 })
170             })
171             .filter(|violation| {
172                 if let ObjectSafetyViolation::Method(
173                     _,
174                     MethodViolationCode::WhereClauseReferencesSelf,
175                     span,
176                 ) = violation
177                 {
178                     // Using `CRATE_NODE_ID` is wrong, but it's hard to get a more precise id.
179                     // It's also hard to get a use site span, so we use the method definition span.
180                     self.lint_node_note(
181                         lint::builtin::WHERE_CLAUSES_OBJECT_SAFETY,
182                         hir::CRATE_HIR_ID,
183                         *span,
184                         &format!(
185                             "the trait `{}` cannot be made into an object",
186                             self.def_path_str(trait_def_id)
187                         ),
188                         &violation.error_msg(),
189                     );
190                     false
191                 } else {
192                     true
193                 }
194             })
195             .collect();
196
197         // Check the trait itself.
198         if self.trait_has_sized_self(trait_def_id) {
199             violations.push(ObjectSafetyViolation::SizedSelf);
200         }
201         if self.predicates_reference_self(trait_def_id, false) {
202             violations.push(ObjectSafetyViolation::SupertraitSelf);
203         }
204
205         violations.extend(
206             self.associated_items(trait_def_id)
207                 .filter(|item| item.kind == ty::AssocKind::Const)
208                 .map(|item| ObjectSafetyViolation::AssocConst(item.ident.name, item.ident.span)),
209         );
210
211         debug!(
212             "object_safety_violations_for_trait(trait_def_id={:?}) = {:?}",
213             trait_def_id, violations
214         );
215
216         violations
217     }
218
219     fn predicates_reference_self(self, trait_def_id: DefId, supertraits_only: bool) -> bool {
220         let trait_ref = ty::Binder::dummy(ty::TraitRef::identity(self, trait_def_id));
221         let predicates = if supertraits_only {
222             self.super_predicates_of(trait_def_id)
223         } else {
224             self.predicates_of(trait_def_id)
225         };
226         let self_ty = self.types.self_param;
227         let has_self_ty = |t: Ty<'tcx>| t.walk().any(|t| t == self_ty);
228         predicates
229             .predicates
230             .iter()
231             .map(|(predicate, _)| predicate.subst_supertrait(self, &trait_ref))
232             .any(|predicate| {
233                 match predicate {
234                     ty::Predicate::Trait(ref data) => {
235                         // In the case of a trait predicate, we can skip the "self" type.
236                         data.skip_binder().input_types().skip(1).any(has_self_ty)
237                     }
238                     ty::Predicate::Projection(ref data) => {
239                         // And similarly for projections. This should be redundant with
240                         // the previous check because any projection should have a
241                         // matching `Trait` predicate with the same inputs, but we do
242                         // the check to be safe.
243                         //
244                         // Note that we *do* allow projection *outputs* to contain
245                         // `self` (i.e., `trait Foo: Bar<Output=Self::Result> { type Result; }`),
246                         // we just require the user to specify *both* outputs
247                         // in the object type (i.e., `dyn Foo<Output=(), Result=()>`).
248                         //
249                         // This is ALT2 in issue #56288, see that for discussion of the
250                         // possible alternatives.
251                         data.skip_binder()
252                             .projection_ty
253                             .trait_ref(self)
254                             .input_types()
255                             .skip(1)
256                             .any(has_self_ty)
257                     }
258                     ty::Predicate::WellFormed(..)
259                     | ty::Predicate::ObjectSafe(..)
260                     | ty::Predicate::TypeOutlives(..)
261                     | ty::Predicate::RegionOutlives(..)
262                     | ty::Predicate::ClosureKind(..)
263                     | ty::Predicate::Subtype(..)
264                     | ty::Predicate::ConstEvaluatable(..) => false,
265                 }
266             })
267     }
268
269     fn trait_has_sized_self(self, trait_def_id: DefId) -> bool {
270         self.generics_require_sized_self(trait_def_id)
271     }
272
273     fn generics_require_sized_self(self, def_id: DefId) -> bool {
274         let sized_def_id = match self.lang_items().sized_trait() {
275             Some(def_id) => def_id,
276             None => {
277                 return false; /* No Sized trait, can't require it! */
278             }
279         };
280
281         // Search for a predicate like `Self : Sized` amongst the trait bounds.
282         let predicates = self.predicates_of(def_id);
283         let predicates = predicates.instantiate_identity(self).predicates;
284         elaborate_predicates(self, predicates).any(|predicate| match predicate {
285             ty::Predicate::Trait(ref trait_pred) => {
286                 trait_pred.def_id() == sized_def_id
287                     && 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         self,
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 self.generics_require_sized_self(method.def_id) {
310             return None;
311         }
312
313         self.virtual_call_violation_for_method(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(
321         self,
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 = self.fn_sig(method.def_id);
331
332         for input_ty in &sig.skip_binder().inputs()[1..] {
333             if self.contains_illegal_self_type_reference(trait_def_id, input_ty) {
334                 return Some(MethodViolationCode::ReferencesSelf);
335             }
336         }
337         if self.contains_illegal_self_type_reference(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 = self.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 self
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| self.contains_illegal_self_type_reference(trait_def_id, t))
359         {
360             return Some(MethodViolationCode::WhereClauseReferencesSelf);
361         }
362
363         let receiver_ty =
364             self.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 != self.types.self_param {
371             if !self.receiver_is_dispatchable(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 = self.param_env(method.def_id);
379
380                 let abi_of_ty = |ty: Ty<'tcx>| -> &Abi {
381                     match self.layout_of(param_env.and(ty)) {
382                         Ok(layout) => &layout.abi,
383                         Err(err) => {
384                             bug!("error: {}\n while computing layout for type {:?}", err, ty)
385                         }
386                     }
387                 };
388
389                 // e.g., `Rc<()>`
390                 let unit_receiver_ty =
391                     self.receiver_for_self_ty(receiver_ty, self.mk_unit(), method.def_id);
392
393                 match abi_of_ty(unit_receiver_ty) {
394                     &Abi::Scalar(..) => (),
395                     abi => {
396                         self.sess.delay_span_bug(
397                             self.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                     self.object_ty_for_trait(trait_def_id, self.mk_region(ty::ReStatic));
408
409                 // e.g., `Rc<dyn Trait>`
410                 let trait_object_receiver =
411                     self.receiver_for_self_ty(receiver_ty, trait_object_ty, method.def_id);
412
413                 match abi_of_ty(trait_object_receiver) {
414                     &Abi::ScalarPair(..) => (),
415                     abi => {
416                         self.sess.delay_span_bug(
417                             self.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(
435         self,
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(self, method_def_id, |param, _| {
442             if param.index == 0 { self_ty.into() } else { self.mk_param_from_def(param) }
443         });
444
445         let result = receiver_ty.subst(self, 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(self, trait_def_id: DefId, lifetime: ty::Region<'tcx>) -> Ty<'tcx> {
457         debug!("object_ty_for_trait: trait_def_id={:?}", trait_def_id);
458
459         let trait_ref = ty::TraitRef::identity(self, trait_def_id);
460
461         let trait_predicate = ty::ExistentialPredicate::Trait(
462             ty::ExistentialTraitRef::erase_self_ty(self, trait_ref),
463         );
464
465         let mut associated_types = traits::supertraits(self, ty::Binder::dummy(trait_ref))
466             .flat_map(|super_trait_ref| {
467                 self.associated_items(super_trait_ref.def_id())
468                     .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)| self.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: self.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 = self
490             .mk_existential_predicates(iter::once(trait_predicate).chain(projection_predicates));
491
492         let object_ty = self.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(self, method: &ty::AssocItem, receiver_ty: Ty<'tcx>) -> bool {
551         debug!("receiver_is_dispatchable: method = {:?}, receiver_ty = {:?}", method, receiver_ty);
552
553         let traits =
554             (self.lang_items().unsize_trait(), self.lang_items().dispatch_from_dyn_trait());
555         let (unsize_did, dispatch_from_dyn_did) = if let (Some(u), Some(cu)) = traits {
556             (u, cu)
557         } else {
558             debug!("receiver_is_dispatchable: Missing Unsize or DispatchFromDyn traits");
559             return false;
560         };
561
562         // the type `U` in the query
563         // use a bogus type parameter to mimick a forall(U) query using u32::MAX for now.
564         // FIXME(mikeyhew) this is a total hack. Once object_safe_for_dispatch is stabilized, we can
565         // replace this with `dyn Trait`
566         let unsized_self_ty: Ty<'tcx> =
567             self.mk_ty_param(::std::u32::MAX, Symbol::intern("RustaceansAreAwesome"));
568
569         // `Receiver[Self => U]`
570         let unsized_receiver_ty =
571             self.receiver_for_self_ty(receiver_ty, unsized_self_ty, method.def_id);
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             }
583             .to_predicate();
584
585             // U: Trait<Arg1, ..., ArgN>
586             let trait_predicate = {
587                 let substs =
588                     InternalSubsts::for_item(self, method.container.assert_trait(), |param, _| {
589                         if param.index == 0 {
590                             unsized_self_ty.into()
591                         } else {
592                             self.mk_param_from_def(param)
593                         }
594                     });
595
596                 ty::TraitRef { def_id: unsize_did, substs }.to_predicate()
597             };
598
599             let caller_bounds: Vec<Predicate<'tcx>> = param_env
600                 .caller_bounds
601                 .iter()
602                 .cloned()
603                 .chain(iter::once(unsize_predicate))
604                 .chain(iter::once(trait_predicate))
605                 .collect();
606
607             param_env.caller_bounds = self.intern_predicates(&caller_bounds);
608
609             param_env
610         };
611
612         // Receiver: DispatchFromDyn<Receiver[Self => U]>
613         let obligation = {
614             let predicate = ty::TraitRef {
615                 def_id: dispatch_from_dyn_did,
616                 substs: self.mk_substs_trait(receiver_ty, &[unsized_receiver_ty.into()]),
617             }
618             .to_predicate();
619
620             Obligation::new(ObligationCause::dummy(), param_env, predicate)
621         };
622
623         self.infer_ctxt().enter(|ref infcx| {
624             // the receiver is dispatchable iff the obligation holds
625             infcx.predicate_must_hold_modulo_regions(&obligation)
626         })
627     }
628
629     fn contains_illegal_self_type_reference(self, trait_def_id: DefId, ty: Ty<'tcx>) -> bool {
630         // This is somewhat subtle. In general, we want to forbid
631         // references to `Self` in the argument and return types,
632         // since the value of `Self` is erased. However, there is one
633         // exception: it is ok to reference `Self` in order to access
634         // an associated type of the current trait, since we retain
635         // the value of those associated types in the object type
636         // itself.
637         //
638         // ```rust
639         // trait SuperTrait {
640         //     type X;
641         // }
642         //
643         // trait Trait : SuperTrait {
644         //     type Y;
645         //     fn foo(&self, x: Self) // bad
646         //     fn foo(&self) -> Self // bad
647         //     fn foo(&self) -> Option<Self> // bad
648         //     fn foo(&self) -> Self::Y // OK, desugars to next example
649         //     fn foo(&self) -> <Self as Trait>::Y // OK
650         //     fn foo(&self) -> Self::X // OK, desugars to next example
651         //     fn foo(&self) -> <Self as SuperTrait>::X // OK
652         // }
653         // ```
654         //
655         // However, it is not as simple as allowing `Self` in a projected
656         // type, because there are illegal ways to use `Self` as well:
657         //
658         // ```rust
659         // trait Trait : SuperTrait {
660         //     ...
661         //     fn foo(&self) -> <Self as SomeOtherTrait>::X;
662         // }
663         // ```
664         //
665         // Here we will not have the type of `X` recorded in the
666         // object type, and we cannot resolve `Self as SomeOtherTrait`
667         // without knowing what `Self` is.
668
669         let mut supertraits: Option<Vec<ty::PolyTraitRef<'tcx>>> = None;
670         let mut error = false;
671         let self_ty = self.types.self_param;
672         ty.maybe_walk(|ty| {
673             match ty.kind {
674                 ty::Param(_) => {
675                     if ty == self_ty {
676                         error = true;
677                     }
678
679                     false // no contained types to walk
680                 }
681
682                 ty::Projection(ref data) => {
683                     // This is a projected type `<Foo as SomeTrait>::X`.
684
685                     // Compute supertraits of current trait lazily.
686                     if supertraits.is_none() {
687                         let trait_ref =
688                             ty::Binder::bind(ty::TraitRef::identity(self, trait_def_id));
689                         supertraits = Some(traits::supertraits(self, trait_ref).collect());
690                     }
691
692                     // Determine whether the trait reference `Foo as
693                     // SomeTrait` is in fact a supertrait of the
694                     // current trait. In that case, this type is
695                     // legal, because the type `X` will be specified
696                     // in the object type.  Note that we can just use
697                     // direct equality here because all of these types
698                     // are part of the formal parameter listing, and
699                     // hence there should be no inference variables.
700                     let projection_trait_ref = ty::Binder::bind(data.trait_ref(self));
701                     let is_supertrait_of_current_trait =
702                         supertraits.as_ref().unwrap().contains(&projection_trait_ref);
703
704                     if is_supertrait_of_current_trait {
705                         false // do not walk contained types, do not report error, do collect $200
706                     } else {
707                         true // DO walk contained types, POSSIBLY reporting an error
708                     }
709                 }
710
711                 _ => true, // walk contained types, if any
712             }
713         });
714
715         error
716     }
717 }
718
719 pub(super) fn is_object_safe_provider(tcx: TyCtxt<'_>, trait_def_id: DefId) -> bool {
720     tcx.object_safety_violations(trait_def_id).is_empty()
721 }