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,
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.
11 use super::elaborate_predicates;
13 use crate::traits::{self, Obligation, ObligationCause};
14 use crate::ty::subst::{InternalSubsts, Subst};
15 use crate::ty::{self, Predicate, ToPredicate, Ty, TyCtxt, TypeFoldable, WithConstness};
16 use rustc_errors::Applicability;
18 use rustc_hir::def_id::DefId;
19 use rustc_session::lint::builtin::WHERE_CLAUSES_OBJECT_SAFETY;
20 use rustc_span::symbol::Symbol;
21 use rustc_span::{Span, DUMMY_SP};
22 use smallvec::{smallvec, SmallVec};
26 use std::iter::{self};
28 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
29 pub enum ObjectSafetyViolation {
30 /// `Self: Sized` declared on the trait.
31 SizedSelf(SmallVec<[Span; 1]>),
33 /// Supertrait reference references `Self` an in illegal location
34 /// (e.g., `trait Foo : Bar<Self>`).
35 SupertraitSelf(SmallVec<[Span; 1]>),
37 /// Method has something illegal.
38 Method(ast::Name, MethodViolationCode, Span),
41 AssocConst(ast::Name, Span),
44 impl ObjectSafetyViolation {
45 pub fn error_msg(&self) -> Cow<'static, str> {
47 ObjectSafetyViolation::SizedSelf(_) => "it requires `Self: Sized`".into(),
48 ObjectSafetyViolation::SupertraitSelf(ref spans) => {
49 if spans.iter().any(|sp| *sp != DUMMY_SP) {
50 "it uses `Self` as a type parameter in this".into()
52 "it cannot use `Self` as a type parameter in a supertrait or `where`-clause"
56 ObjectSafetyViolation::Method(name, MethodViolationCode::StaticMethod(_), _) => {
57 format!("associated function `{}` has no `self` parameter", name).into()
59 ObjectSafetyViolation::Method(
61 MethodViolationCode::ReferencesSelfInput(_),
63 ) => format!("method `{}` references the `Self` type in its parameters", name).into(),
64 ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfInput(_), _) => {
65 format!("method `{}` references the `Self` type in this parameter", name).into()
67 ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfOutput, _) => {
68 format!("method `{}` references the `Self` type in its return type", name).into()
70 ObjectSafetyViolation::Method(
72 MethodViolationCode::WhereClauseReferencesSelf,
75 format!("method `{}` references the `Self` type in its `where` clause", name).into()
77 ObjectSafetyViolation::Method(name, MethodViolationCode::Generic, _) => {
78 format!("method `{}` has generic type parameters", name).into()
80 ObjectSafetyViolation::Method(name, MethodViolationCode::UndispatchableReceiver, _) => {
81 format!("method `{}`'s `self` parameter cannot be dispatched on", name).into()
83 ObjectSafetyViolation::AssocConst(name, DUMMY_SP) => {
84 format!("it contains associated `const` `{}`", name).into()
86 ObjectSafetyViolation::AssocConst(..) => "it contains this associated `const`".into(),
90 pub fn solution(&self) -> Option<(String, Option<(String, Span)>)> {
92 ObjectSafetyViolation::SizedSelf(_) | ObjectSafetyViolation::SupertraitSelf(_) => {
95 ObjectSafetyViolation::Method(name, MethodViolationCode::StaticMethod(sugg), _) => (
97 "consider turning `{}` into a method by giving it a `&self` argument or \
98 constraining it so it does not apply to trait objects",
101 sugg.map(|(sugg, sp)| (sugg.to_string(), sp)),
103 ObjectSafetyViolation::Method(
105 MethodViolationCode::UndispatchableReceiver,
108 format!("consider changing method `{}`'s `self` parameter to be `&self`", name)
110 Some(("&Self".to_string(), span)),
112 ObjectSafetyViolation::AssocConst(name, _)
113 | ObjectSafetyViolation::Method(name, ..) => {
114 (format!("consider moving `{}` to another trait", name), None)
119 pub fn spans(&self) -> SmallVec<[Span; 1]> {
120 // When `span` comes from a separate crate, it'll be `DUMMY_SP`. Treat it as `None` so
121 // diagnostics use a `note` instead of a `span_label`.
123 ObjectSafetyViolation::SupertraitSelf(spans)
124 | ObjectSafetyViolation::SizedSelf(spans) => spans.clone(),
125 ObjectSafetyViolation::AssocConst(_, span)
126 | ObjectSafetyViolation::Method(_, _, span)
127 if *span != DUMMY_SP =>
136 /// Reasons a method might not be object-safe.
137 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
138 pub enum MethodViolationCode {
140 StaticMethod(Option<(&'static str, Span)>),
142 /// e.g., `fn foo(&self, x: Self)`
143 ReferencesSelfInput(usize),
145 /// e.g., `fn foo(&self) -> Self`
146 ReferencesSelfOutput,
148 /// e.g., `fn foo(&self) where Self: Clone`
149 WhereClauseReferencesSelf,
151 /// e.g., `fn foo<A>()`
154 /// the method's receiver (`self` argument) can't be dispatched on
155 UndispatchableReceiver,
158 /// Returns the object safety violations that affect
159 /// astconv -- currently, `Self` in supertraits. This is needed
160 /// because `object_safety_violations` can't be used during
162 pub fn astconv_object_safety_violations(
165 ) -> Vec<ObjectSafetyViolation> {
166 debug_assert!(tcx.generics_of(trait_def_id).has_self);
167 let violations = traits::supertrait_def_ids(tcx, trait_def_id)
168 .map(|def_id| predicates_reference_self(tcx, def_id, true))
169 .filter(|spans| !spans.is_empty())
170 .map(|spans| ObjectSafetyViolation::SupertraitSelf(spans))
173 debug!("astconv_object_safety_violations(trait_def_id={:?}) = {:?}", trait_def_id, violations);
178 pub fn object_safety_violations(
181 ) -> Vec<ObjectSafetyViolation> {
182 debug_assert!(tcx.generics_of(trait_def_id).has_self);
183 debug!("object_safety_violations: {:?}", trait_def_id);
185 traits::supertrait_def_ids(tcx, trait_def_id)
186 .flat_map(|def_id| object_safety_violations_for_trait(tcx, def_id))
190 /// We say a method is *vtable safe* if it can be invoked on a trait
191 /// object. Note that object-safe traits can have some
192 /// non-vtable-safe methods, so long as they require `Self: Sized` or
193 /// otherwise ensure that they cannot be used when `Self = Trait`.
194 pub fn is_vtable_safe_method(tcx: TyCtxt<'_>, trait_def_id: DefId, method: &ty::AssocItem) -> bool {
195 debug_assert!(tcx.generics_of(trait_def_id).has_self);
196 debug!("is_vtable_safe_method({:?}, {:?})", trait_def_id, method);
197 // Any method that has a `Self: Sized` bound cannot be called.
198 if generics_require_sized_self(tcx, method.def_id) {
202 match virtual_call_violation_for_method(tcx, trait_def_id, method) {
203 None | Some(MethodViolationCode::WhereClauseReferencesSelf) => true,
208 fn object_safety_violations_for_trait(
211 ) -> Vec<ObjectSafetyViolation> {
212 // Check methods for violations.
213 let mut violations: Vec<_> = tcx
214 .associated_items(trait_def_id)
216 .filter(|item| item.kind == ty::AssocKind::Method)
218 object_safety_violation_for_method(tcx, trait_def_id, &item)
219 .map(|(code, span)| ObjectSafetyViolation::Method(item.ident.name, code, span))
221 .filter(|violation| {
222 if let ObjectSafetyViolation::Method(
224 MethodViolationCode::WhereClauseReferencesSelf,
228 // Using `CRATE_NODE_ID` is wrong, but it's hard to get a more precise id.
229 // It's also hard to get a use site span, so we use the method definition span.
230 tcx.struct_span_lint_hir(
231 WHERE_CLAUSES_OBJECT_SAFETY,
235 let mut err = lint.build(&format!(
236 "the trait `{}` cannot be made into an object",
237 tcx.def_path_str(trait_def_id)
239 let node = tcx.hir().get_if_local(trait_def_id);
240 let msg = if let Some(hir::Node::Item(item)) = node {
243 "this trait cannot be made into an object...",
245 format!("...because {}", violation.error_msg())
248 "the trait cannot be made into an object because {}",
249 violation.error_msg()
252 err.span_label(*span, &msg);
253 match (node, violation.solution()) {
254 (Some(_), Some((note, None))) => {
257 (Some(_), Some((note, Some((sugg, span))))) => {
262 Applicability::MachineApplicable,
265 // Only provide the help if its a local trait, otherwise it's not actionable.
278 // Check the trait itself.
279 if trait_has_sized_self(tcx, trait_def_id) {
280 // We don't want to include the requirement from `Sized` itself to be `Sized` in the list.
281 let spans = get_sized_bounds(tcx, trait_def_id);
282 violations.push(ObjectSafetyViolation::SizedSelf(spans));
284 let spans = predicates_reference_self(tcx, trait_def_id, false);
285 if !spans.is_empty() {
286 violations.push(ObjectSafetyViolation::SupertraitSelf(spans));
290 tcx.associated_items(trait_def_id)
292 .filter(|item| item.kind == ty::AssocKind::Const)
293 .map(|item| ObjectSafetyViolation::AssocConst(item.ident.name, item.ident.span)),
297 "object_safety_violations_for_trait(trait_def_id={:?}) = {:?}",
298 trait_def_id, violations
304 fn get_sized_bounds(tcx: TyCtxt<'_>, trait_def_id: DefId) -> SmallVec<[Span; 1]> {
306 .get_if_local(trait_def_id)
307 .and_then(|node| match node {
308 hir::Node::Item(hir::Item {
309 kind: hir::ItemKind::Trait(.., generics, bounds, _),
318 hir::WherePredicate::BoundPredicate(pred)
319 if pred.bounded_ty.hir_id.owner_def_id() == trait_def_id =>
321 // Fetch spans for trait bounds that are Sized:
322 // `trait T where Self: Pred`
323 Some(pred.bounds.iter().filter_map(|b| match b {
324 hir::GenericBound::Trait(
326 hir::TraitBoundModifier::None,
327 ) if trait_has_sized_self(
329 trait_ref.trait_ref.trait_def_id(),
341 .chain(bounds.iter().filter_map(|b| match b {
342 hir::GenericBound::Trait(trait_ref, hir::TraitBoundModifier::None)
343 if trait_has_sized_self(tcx, trait_ref.trait_ref.trait_def_id()) =>
345 // Fetch spans for supertraits that are `Sized`: `trait T: Super`
350 .collect::<SmallVec<[Span; 1]>>(),
354 .unwrap_or_else(SmallVec::new)
357 fn predicates_reference_self(
360 supertraits_only: bool,
361 ) -> SmallVec<[Span; 1]> {
362 let trait_ref = ty::Binder::dummy(ty::TraitRef::identity(tcx, trait_def_id));
363 let predicates = if supertraits_only {
364 tcx.super_predicates_of(trait_def_id)
366 tcx.predicates_of(trait_def_id)
368 let self_ty = tcx.types.self_param;
369 let has_self_ty = |t: Ty<'_>| t.walk().any(|t| t == self_ty);
373 .map(|(predicate, sp)| (predicate.subst_supertrait(tcx, &trait_ref), sp))
374 .filter_map(|(predicate, &sp)| {
376 ty::Predicate::Trait(ref data, _) => {
377 // In the case of a trait predicate, we can skip the "self" type.
378 if data.skip_binder().input_types().skip(1).any(has_self_ty) {
384 ty::Predicate::Projection(ref data) => {
385 // And similarly for projections. This should be redundant with
386 // the previous check because any projection should have a
387 // matching `Trait` predicate with the same inputs, but we do
388 // the check to be safe.
390 // Note that we *do* allow projection *outputs* to contain
391 // `self` (i.e., `trait Foo: Bar<Output=Self::Result> { type Result; }`),
392 // we just require the user to specify *both* outputs
393 // in the object type (i.e., `dyn Foo<Output=(), Result=()>`).
395 // This is ALT2 in issue #56288, see that for discussion of the
396 // possible alternatives.
410 ty::Predicate::WellFormed(..)
411 | ty::Predicate::ObjectSafe(..)
412 | ty::Predicate::TypeOutlives(..)
413 | ty::Predicate::RegionOutlives(..)
414 | ty::Predicate::ClosureKind(..)
415 | ty::Predicate::Subtype(..)
416 | ty::Predicate::ConstEvaluatable(..) => None,
422 fn trait_has_sized_self(tcx: TyCtxt<'_>, trait_def_id: DefId) -> bool {
423 generics_require_sized_self(tcx, trait_def_id)
426 fn generics_require_sized_self(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
427 let sized_def_id = match tcx.lang_items().sized_trait() {
428 Some(def_id) => def_id,
430 return false; /* No Sized trait, can't require it! */
434 // Search for a predicate like `Self : Sized` amongst the trait bounds.
435 let predicates = tcx.predicates_of(def_id);
436 let predicates = predicates.instantiate_identity(tcx).predicates;
437 elaborate_predicates(tcx, predicates).any(|predicate| match predicate {
438 ty::Predicate::Trait(ref trait_pred, _) => {
439 trait_pred.def_id() == sized_def_id && trait_pred.skip_binder().self_ty().is_param(0)
441 ty::Predicate::Projection(..)
442 | ty::Predicate::Subtype(..)
443 | ty::Predicate::RegionOutlives(..)
444 | ty::Predicate::WellFormed(..)
445 | ty::Predicate::ObjectSafe(..)
446 | ty::Predicate::ClosureKind(..)
447 | ty::Predicate::TypeOutlives(..)
448 | ty::Predicate::ConstEvaluatable(..) => false,
452 /// Returns `Some(_)` if this method makes the containing trait not object safe.
453 fn object_safety_violation_for_method(
456 method: &ty::AssocItem,
457 ) -> Option<(MethodViolationCode, Span)> {
458 debug!("object_safety_violation_for_method({:?}, {:?})", trait_def_id, method);
459 // Any method that has a `Self : Sized` requisite is otherwise
460 // exempt from the regulations.
461 if generics_require_sized_self(tcx, method.def_id) {
465 let violation = virtual_call_violation_for_method(tcx, trait_def_id, method);
466 // Get an accurate span depending on the violation.
468 let node = tcx.hir().get_if_local(method.def_id);
469 let span = match (v, node) {
470 (MethodViolationCode::ReferencesSelfInput(arg), Some(node)) => node
472 .and_then(|decl| decl.inputs.get(arg + 1))
473 .map_or(method.ident.span, |arg| arg.span),
474 (MethodViolationCode::UndispatchableReceiver, Some(node)) => node
476 .and_then(|decl| decl.inputs.get(0))
477 .map_or(method.ident.span, |arg| arg.span),
478 (MethodViolationCode::ReferencesSelfOutput, Some(node)) => {
479 node.fn_decl().map_or(method.ident.span, |decl| decl.output.span())
481 _ => method.ident.span,
487 /// Returns `Some(_)` if this method cannot be called on a trait
488 /// object; this does not necessarily imply that the enclosing trait
489 /// is not object safe, because the method might have a where clause
491 fn virtual_call_violation_for_method<'tcx>(
494 method: &ty::AssocItem,
495 ) -> Option<MethodViolationCode> {
496 // The method's first parameter must be named `self`
497 if !method.method_has_self_argument {
498 // We'll attempt to provide a structured suggestion for `Self: Sized`.
500 tcx.hir().get_if_local(method.def_id).as_ref().and_then(|node| node.generics()).map(
501 |generics| match generics.where_clause.predicates {
502 [] => (" where Self: Sized", generics.where_clause.span),
503 [.., pred] => (", Self: Sized", pred.span().shrink_to_hi()),
506 return Some(MethodViolationCode::StaticMethod(sugg));
509 let sig = tcx.fn_sig(method.def_id);
511 for (i, input_ty) in sig.skip_binder().inputs()[1..].iter().enumerate() {
512 if contains_illegal_self_type_reference(tcx, trait_def_id, input_ty) {
513 return Some(MethodViolationCode::ReferencesSelfInput(i));
516 if contains_illegal_self_type_reference(tcx, trait_def_id, sig.output().skip_binder()) {
517 return Some(MethodViolationCode::ReferencesSelfOutput);
520 // We can't monomorphize things like `fn foo<A>(...)`.
521 let own_counts = tcx.generics_of(method.def_id).own_counts();
522 if own_counts.types + own_counts.consts != 0 {
523 return Some(MethodViolationCode::Generic);
527 .predicates_of(method.def_id)
530 // A trait object can't claim to live more than the concrete type,
531 // so outlives predicates will always hold.
533 .filter(|(p, _)| p.to_opt_type_outlives().is_none())
535 // Do a shallow visit so that `contains_illegal_self_type_reference`
536 // may apply it's custom visiting.
537 .visit_tys_shallow(|t| contains_illegal_self_type_reference(tcx, trait_def_id, t))
539 return Some(MethodViolationCode::WhereClauseReferencesSelf);
543 tcx.liberate_late_bound_regions(method.def_id, &sig.map_bound(|sig| sig.inputs()[0]));
545 // Until `unsized_locals` is fully implemented, `self: Self` can't be dispatched on.
546 // However, this is already considered object-safe. We allow it as a special case here.
547 // FIXME(mikeyhew) get rid of this `if` statement once `receiver_is_dispatchable` allows
548 // `Receiver: Unsize<Receiver[Self => dyn Trait]>`.
549 if receiver_ty != tcx.types.self_param {
550 if !receiver_is_dispatchable(tcx, method, receiver_ty) {
551 return Some(MethodViolationCode::UndispatchableReceiver);
553 // Do sanity check to make sure the receiver actually has the layout of a pointer.
555 use crate::ty::layout::Abi;
557 let param_env = tcx.param_env(method.def_id);
559 let abi_of_ty = |ty: Ty<'tcx>| -> &Abi {
560 match tcx.layout_of(param_env.and(ty)) {
561 Ok(layout) => &layout.abi,
562 Err(err) => bug!("error: {}\n while computing layout for type {:?}", err, ty),
567 let unit_receiver_ty =
568 receiver_for_self_ty(tcx, receiver_ty, tcx.mk_unit(), method.def_id);
570 match abi_of_ty(unit_receiver_ty) {
571 &Abi::Scalar(..) => (),
573 tcx.sess.delay_span_bug(
574 tcx.def_span(method.def_id),
576 "receiver when `Self = ()` should have a Scalar ABI; found {:?}",
583 let trait_object_ty =
584 object_ty_for_trait(tcx, trait_def_id, tcx.mk_region(ty::ReStatic));
586 // e.g., `Rc<dyn Trait>`
587 let trait_object_receiver =
588 receiver_for_self_ty(tcx, receiver_ty, trait_object_ty, method.def_id);
590 match abi_of_ty(trait_object_receiver) {
591 &Abi::ScalarPair(..) => (),
593 tcx.sess.delay_span_bug(
594 tcx.def_span(method.def_id),
596 "receiver when `Self = {}` should have a ScalarPair ABI; \
609 /// Performs a type substitution to produce the version of `receiver_ty` when `Self = self_ty`.
610 /// For example, for `receiver_ty = Rc<Self>` and `self_ty = Foo`, returns `Rc<Foo>`.
611 fn receiver_for_self_ty<'tcx>(
613 receiver_ty: Ty<'tcx>,
615 method_def_id: DefId,
617 debug!("receiver_for_self_ty({:?}, {:?}, {:?})", receiver_ty, self_ty, method_def_id);
618 let substs = InternalSubsts::for_item(tcx, method_def_id, |param, _| {
619 if param.index == 0 { self_ty.into() } else { tcx.mk_param_from_def(param) }
622 let result = receiver_ty.subst(tcx, substs);
624 "receiver_for_self_ty({:?}, {:?}, {:?}) = {:?}",
625 receiver_ty, self_ty, method_def_id, result
630 /// Creates the object type for the current trait. For example,
631 /// if the current trait is `Deref`, then this will be
632 /// `dyn Deref<Target = Self::Target> + 'static`.
633 fn object_ty_for_trait<'tcx>(
636 lifetime: ty::Region<'tcx>,
638 debug!("object_ty_for_trait: trait_def_id={:?}", trait_def_id);
640 let trait_ref = ty::TraitRef::identity(tcx, trait_def_id);
642 let trait_predicate =
643 ty::ExistentialPredicate::Trait(ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref));
645 let mut associated_types = traits::supertraits(tcx, ty::Binder::dummy(trait_ref))
646 .flat_map(|super_trait_ref| {
647 tcx.associated_items(super_trait_ref.def_id())
649 .map(move |item| (super_trait_ref, item))
651 .filter(|(_, item)| item.kind == ty::AssocKind::Type)
652 .collect::<Vec<_>>();
654 // existential predicates need to be in a specific order
655 associated_types.sort_by_cached_key(|(_, item)| tcx.def_path_hash(item.def_id));
657 let projection_predicates = associated_types.into_iter().map(|(super_trait_ref, item)| {
658 // We *can* get bound lifetimes here in cases like
659 // `trait MyTrait: for<'s> OtherTrait<&'s T, Output=bool>`.
661 // binder moved to (*)...
662 let super_trait_ref = super_trait_ref.skip_binder();
663 ty::ExistentialPredicate::Projection(ty::ExistentialProjection {
664 ty: tcx.mk_projection(item.def_id, super_trait_ref.substs),
665 item_def_id: item.def_id,
666 substs: super_trait_ref.substs,
670 let existential_predicates =
671 tcx.mk_existential_predicates(iter::once(trait_predicate).chain(projection_predicates));
673 let object_ty = tcx.mk_dynamic(
674 // (*) ... binder re-introduced here
675 ty::Binder::bind(existential_predicates),
679 debug!("object_ty_for_trait: object_ty=`{}`", object_ty);
684 /// Checks the method's receiver (the `self` argument) can be dispatched on when `Self` is a
685 /// trait object. We require that `DispatchableFromDyn` be implemented for the receiver type
686 /// in the following way:
687 /// - let `Receiver` be the type of the `self` argument, i.e `Self`, `&Self`, `Rc<Self>`,
688 /// - require the following bound:
691 /// Receiver[Self => T]: DispatchFromDyn<Receiver[Self => dyn Trait]>
694 /// where `Foo[X => Y]` means "the same type as `Foo`, but with `X` replaced with `Y`"
695 /// (substitution notation).
697 /// Some examples of receiver types and their required obligation:
698 /// - `&'a mut self` requires `&'a mut Self: DispatchFromDyn<&'a mut dyn Trait>`,
699 /// - `self: Rc<Self>` requires `Rc<Self>: DispatchFromDyn<Rc<dyn Trait>>`,
700 /// - `self: Pin<Box<Self>>` requires `Pin<Box<Self>>: DispatchFromDyn<Pin<Box<dyn Trait>>>`.
702 /// The only case where the receiver is not dispatchable, but is still a valid receiver
703 /// type (just not object-safe), is when there is more than one level of pointer indirection.
704 /// E.g., `self: &&Self`, `self: &Rc<Self>`, `self: Box<Box<Self>>`. In these cases, there
705 /// is no way, or at least no inexpensive way, to coerce the receiver from the version where
706 /// `Self = dyn Trait` to the version where `Self = T`, where `T` is the unknown erased type
707 /// contained by the trait object, because the object that needs to be coerced is behind
710 /// In practice, we cannot use `dyn Trait` explicitly in the obligation because it would result
711 /// in a new check that `Trait` is object safe, creating a cycle (until object_safe_for_dispatch
712 /// is stabilized, see tracking issue https://github.com/rust-lang/rust/issues/43561).
713 /// Instead, we fudge a little by introducing a new type parameter `U` such that
714 /// `Self: Unsize<U>` and `U: Trait + ?Sized`, and use `U` in place of `dyn Trait`.
715 /// Written as a chalk-style query:
717 /// forall (U: Trait + ?Sized) {
718 /// if (Self: Unsize<U>) {
719 /// Receiver: DispatchFromDyn<Receiver[Self => U]>
723 /// for `self: &'a mut Self`, this means `&'a mut Self: DispatchFromDyn<&'a mut U>`
724 /// for `self: Rc<Self>`, this means `Rc<Self>: DispatchFromDyn<Rc<U>>`
725 /// for `self: Pin<Box<Self>>`, this means `Pin<Box<Self>>: DispatchFromDyn<Pin<Box<U>>>`
727 // FIXME(mikeyhew) when unsized receivers are implemented as part of unsized rvalues, add this
728 // fallback query: `Receiver: Unsize<Receiver[Self => U]>` to support receivers like
729 // `self: Wrapper<Self>`.
731 fn receiver_is_dispatchable<'tcx>(
733 method: &ty::AssocItem,
734 receiver_ty: Ty<'tcx>,
736 debug!("receiver_is_dispatchable: method = {:?}, receiver_ty = {:?}", method, receiver_ty);
738 let traits = (tcx.lang_items().unsize_trait(), tcx.lang_items().dispatch_from_dyn_trait());
739 let (unsize_did, dispatch_from_dyn_did) = if let (Some(u), Some(cu)) = traits {
742 debug!("receiver_is_dispatchable: Missing Unsize or DispatchFromDyn traits");
746 // the type `U` in the query
747 // use a bogus type parameter to mimick a forall(U) query using u32::MAX for now.
748 // FIXME(mikeyhew) this is a total hack. Once object_safe_for_dispatch is stabilized, we can
749 // replace this with `dyn Trait`
750 let unsized_self_ty: Ty<'tcx> =
751 tcx.mk_ty_param(::std::u32::MAX, Symbol::intern("RustaceansAreAwesome"));
753 // `Receiver[Self => U]`
754 let unsized_receiver_ty =
755 receiver_for_self_ty(tcx, receiver_ty, unsized_self_ty, method.def_id);
757 // create a modified param env, with `Self: Unsize<U>` and `U: Trait` added to caller bounds
758 // `U: ?Sized` is already implied here
760 let mut param_env = tcx.param_env(method.def_id);
763 let unsize_predicate = ty::TraitRef {
765 substs: tcx.mk_substs_trait(tcx.types.self_param, &[unsized_self_ty.into()]),
770 // U: Trait<Arg1, ..., ArgN>
771 let trait_predicate = {
773 InternalSubsts::for_item(tcx, method.container.assert_trait(), |param, _| {
774 if param.index == 0 {
775 unsized_self_ty.into()
777 tcx.mk_param_from_def(param)
781 ty::TraitRef { def_id: unsize_did, substs }.without_const().to_predicate()
784 let caller_bounds: Vec<Predicate<'tcx>> = param_env
788 .chain(iter::once(unsize_predicate))
789 .chain(iter::once(trait_predicate))
792 param_env.caller_bounds = tcx.intern_predicates(&caller_bounds);
797 // Receiver: DispatchFromDyn<Receiver[Self => U]>
799 let predicate = ty::TraitRef {
800 def_id: dispatch_from_dyn_did,
801 substs: tcx.mk_substs_trait(receiver_ty, &[unsized_receiver_ty.into()]),
806 Obligation::new(ObligationCause::dummy(), param_env, predicate)
809 tcx.infer_ctxt().enter(|ref infcx| {
810 // the receiver is dispatchable iff the obligation holds
811 infcx.predicate_must_hold_modulo_regions(&obligation)
815 fn contains_illegal_self_type_reference<'tcx>(
820 // This is somewhat subtle. In general, we want to forbid
821 // references to `Self` in the argument and return types,
822 // since the value of `Self` is erased. However, there is one
823 // exception: it is ok to reference `Self` in order to access
824 // an associated type of the current trait, since we retain
825 // the value of those associated types in the object type
829 // trait SuperTrait {
833 // trait Trait : SuperTrait {
835 // fn foo(&self, x: Self) // bad
836 // fn foo(&self) -> Self // bad
837 // fn foo(&self) -> Option<Self> // bad
838 // fn foo(&self) -> Self::Y // OK, desugars to next example
839 // fn foo(&self) -> <Self as Trait>::Y // OK
840 // fn foo(&self) -> Self::X // OK, desugars to next example
841 // fn foo(&self) -> <Self as SuperTrait>::X // OK
845 // However, it is not as simple as allowing `Self` in a projected
846 // type, because there are illegal ways to use `Self` as well:
849 // trait Trait : SuperTrait {
851 // fn foo(&self) -> <Self as SomeOtherTrait>::X;
855 // Here we will not have the type of `X` recorded in the
856 // object type, and we cannot resolve `Self as SomeOtherTrait`
857 // without knowing what `Self` is.
859 let mut supertraits: Option<Vec<ty::PolyTraitRef<'tcx>>> = None;
860 let mut error = false;
861 let self_ty = tcx.types.self_param;
869 false // no contained types to walk
872 ty::Projection(ref data) => {
873 // This is a projected type `<Foo as SomeTrait>::X`.
875 // Compute supertraits of current trait lazily.
876 if supertraits.is_none() {
877 let trait_ref = ty::Binder::bind(ty::TraitRef::identity(tcx, trait_def_id));
878 supertraits = Some(traits::supertraits(tcx, trait_ref).collect());
881 // Determine whether the trait reference `Foo as
882 // SomeTrait` is in fact a supertrait of the
883 // current trait. In that case, this type is
884 // legal, because the type `X` will be specified
885 // in the object type. Note that we can just use
886 // direct equality here because all of these types
887 // are part of the formal parameter listing, and
888 // hence there should be no inference variables.
889 let projection_trait_ref = ty::Binder::bind(data.trait_ref(tcx));
890 let is_supertrait_of_current_trait =
891 supertraits.as_ref().unwrap().contains(&projection_trait_ref);
893 if is_supertrait_of_current_trait {
894 false // do not walk contained types, do not report error, do collect $200
896 true // DO walk contained types, POSSIBLY reporting an error
900 _ => true, // walk contained types, if any
907 pub(super) fn is_object_safe_provider(tcx: TyCtxt<'_>, trait_def_id: DefId) -> bool {
908 object_safety_violations(tcx, trait_def_id).is_empty()