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;
14 use crate::hir::def_id::DefId;
16 use crate::traits::{self, Obligation, ObligationCause};
17 use crate::ty::{self, Ty, TyCtxt, TypeFoldable, Predicate, ToPredicate};
18 use crate::ty::subst::{Subst, InternalSubsts};
20 use std::iter::{self};
21 use syntax::ast::{self, Name};
24 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
25 pub enum ObjectSafetyViolation {
26 /// `Self: Sized` declared on the trait.
29 /// Supertrait reference references `Self` an in illegal location
30 /// (e.g., `trait Foo : Bar<Self>`).
33 /// Method has something illegal.
34 Method(ast::Name, MethodViolationCode),
37 AssociatedConst(ast::Name),
40 impl ObjectSafetyViolation {
41 pub fn error_msg(&self) -> Cow<'static, str> {
43 ObjectSafetyViolation::SizedSelf =>
44 "the trait cannot require that `Self : Sized`".into(),
45 ObjectSafetyViolation::SupertraitSelf =>
46 "the trait cannot use `Self` as a type parameter \
47 in the supertraits or where-clauses".into(),
48 ObjectSafetyViolation::Method(name, MethodViolationCode::StaticMethod) =>
49 format!("method `{}` has no receiver", name).into(),
50 ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelf) =>
51 format!("method `{}` references the `Self` type \
52 in its arguments or return type", name).into(),
53 ObjectSafetyViolation::Method(name,
54 MethodViolationCode::WhereClauseReferencesSelf(_)) =>
55 format!("method `{}` references the `Self` type in where clauses", name).into(),
56 ObjectSafetyViolation::Method(name, MethodViolationCode::Generic) =>
57 format!("method `{}` has generic type parameters", name).into(),
58 ObjectSafetyViolation::Method(name, MethodViolationCode::UndispatchableReceiver) =>
59 format!("method `{}`'s receiver cannot be dispatched on", name).into(),
60 ObjectSafetyViolation::AssociatedConst(name) =>
61 format!("the trait cannot contain associated consts like `{}`", name).into(),
66 /// Reasons a method might not be object-safe.
67 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
68 pub enum MethodViolationCode {
72 /// e.g., `fn foo(&self, x: Self)` or `fn foo(&self) -> Self`
75 /// e.g., `fn foo(&self) where Self: Clone`
76 WhereClauseReferencesSelf(Span),
78 /// e.g., `fn foo<A>()`
81 /// the method's receiver (`self` argument) can't be dispatched on
82 UndispatchableReceiver,
85 impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> {
87 /// Returns the object safety violations that affect
88 /// astconv -- currently, `Self` in supertraits. This is needed
89 /// because `object_safety_violations` can't be used during
91 pub fn astconv_object_safety_violations(self, trait_def_id: DefId)
92 -> Vec<ObjectSafetyViolation>
94 let violations = traits::supertrait_def_ids(self, trait_def_id)
95 .filter(|&def_id| self.predicates_reference_self(def_id, true))
96 .map(|_| ObjectSafetyViolation::SupertraitSelf)
99 debug!("astconv_object_safety_violations(trait_def_id={:?}) = {:?}",
106 pub fn object_safety_violations(self, trait_def_id: DefId)
107 -> Vec<ObjectSafetyViolation>
109 debug!("object_safety_violations: {:?}", trait_def_id);
111 traits::supertrait_def_ids(self, trait_def_id)
112 .flat_map(|def_id| self.object_safety_violations_for_trait(def_id))
116 fn object_safety_violations_for_trait(self, trait_def_id: DefId)
117 -> Vec<ObjectSafetyViolation>
119 // Check methods for violations.
120 let mut violations: Vec<_> = self.associated_items(trait_def_id)
121 .filter(|item| item.kind == ty::AssociatedKind::Method)
123 self.object_safety_violation_for_method(trait_def_id, &item)
124 .map(|code| ObjectSafetyViolation::Method(item.ident.name, code))
125 ).filter(|violation| {
126 if let ObjectSafetyViolation::Method(_,
127 MethodViolationCode::WhereClauseReferencesSelf(span)) = violation
129 // Using `CRATE_NODE_ID` is wrong, but it's hard to get a more precise id.
130 // It's also hard to get a use site span, so we use the method definition span.
132 lint::builtin::WHERE_CLAUSES_OBJECT_SAFETY,
135 &format!("the trait `{}` cannot be made into an object",
136 self.def_path_str(trait_def_id)),
137 &violation.error_msg());
144 // Check the trait itself.
145 if self.trait_has_sized_self(trait_def_id) {
146 violations.push(ObjectSafetyViolation::SizedSelf);
148 if self.predicates_reference_self(trait_def_id, false) {
149 violations.push(ObjectSafetyViolation::SupertraitSelf);
152 violations.extend(self.associated_items(trait_def_id)
153 .filter(|item| item.kind == ty::AssociatedKind::Const)
154 .map(|item| ObjectSafetyViolation::AssociatedConst(item.ident.name)));
156 debug!("object_safety_violations_for_trait(trait_def_id={:?}) = {:?}",
163 fn predicates_reference_self(
166 supertraits_only: bool) -> bool
168 let trait_ref = ty::Binder::dummy(ty::TraitRef::identity(self, trait_def_id));
169 let predicates = if supertraits_only {
170 self.super_predicates_of(trait_def_id)
172 self.predicates_of(trait_def_id)
177 .map(|(predicate, _)| predicate.subst_supertrait(self, &trait_ref))
180 ty::Predicate::Trait(ref data) => {
181 // In the case of a trait predicate, we can skip the "self" type.
182 data.skip_binder().input_types().skip(1).any(|t| t.has_self_ty())
184 ty::Predicate::Projection(ref data) => {
185 // And similarly for projections. This should be redundant with
186 // the previous check because any projection should have a
187 // matching `Trait` predicate with the same inputs, but we do
188 // the check to be safe.
190 // Note that we *do* allow projection *outputs* to contain
191 // `self` (i.e., `trait Foo: Bar<Output=Self::Result> { type Result; }`),
192 // we just require the user to specify *both* outputs
193 // in the object type (i.e., `dyn Foo<Output=(), Result=()>`).
195 // This is ALT2 in issue #56288, see that for discussion of the
196 // possible alternatives.
202 .any(|t| t.has_self_ty())
204 ty::Predicate::WellFormed(..) |
205 ty::Predicate::ObjectSafe(..) |
206 ty::Predicate::TypeOutlives(..) |
207 ty::Predicate::RegionOutlives(..) |
208 ty::Predicate::ClosureKind(..) |
209 ty::Predicate::Subtype(..) |
210 ty::Predicate::ConstEvaluatable(..) => {
217 fn trait_has_sized_self(self, trait_def_id: DefId) -> bool {
218 self.generics_require_sized_self(trait_def_id)
221 fn generics_require_sized_self(self, def_id: DefId) -> bool {
222 let sized_def_id = match self.lang_items().sized_trait() {
223 Some(def_id) => def_id,
224 None => { return false; /* No Sized trait, can't require it! */ }
227 // Search for a predicate like `Self : Sized` amongst the trait bounds.
228 let predicates = self.predicates_of(def_id);
229 let predicates = predicates.instantiate_identity(self).predicates;
230 elaborate_predicates(self, predicates)
231 .any(|predicate| match predicate {
232 ty::Predicate::Trait(ref trait_pred) if trait_pred.def_id() == sized_def_id => {
233 trait_pred.skip_binder().self_ty().is_self()
235 ty::Predicate::Projection(..) |
236 ty::Predicate::Trait(..) |
237 ty::Predicate::Subtype(..) |
238 ty::Predicate::RegionOutlives(..) |
239 ty::Predicate::WellFormed(..) |
240 ty::Predicate::ObjectSafe(..) |
241 ty::Predicate::ClosureKind(..) |
242 ty::Predicate::TypeOutlives(..) |
243 ty::Predicate::ConstEvaluatable(..) => {
250 /// Returns `Some(_)` if this method makes the containing trait not object safe.
251 fn object_safety_violation_for_method(self,
253 method: &ty::AssociatedItem)
254 -> Option<MethodViolationCode>
256 debug!("object_safety_violation_for_method({:?}, {:?})", trait_def_id, method);
257 // Any method that has a `Self : Sized` requisite is otherwise
258 // exempt from the regulations.
259 if self.generics_require_sized_self(method.def_id) {
263 self.virtual_call_violation_for_method(trait_def_id, method)
266 /// We say a method is *vtable safe* if it can be invoked on a trait
267 /// object. Note that object-safe traits can have some
268 /// non-vtable-safe methods, so long as they require `Self:Sized` or
269 /// otherwise ensure that they cannot be used when `Self=Trait`.
270 pub fn is_vtable_safe_method(self,
272 method: &ty::AssociatedItem)
275 debug!("is_vtable_safe_method({:?}, {:?})", trait_def_id, method);
276 // Any method that has a `Self : Sized` requisite can't be called.
277 if self.generics_require_sized_self(method.def_id) {
281 match self.virtual_call_violation_for_method(trait_def_id, method) {
282 None | Some(MethodViolationCode::WhereClauseReferencesSelf(_)) => true,
287 /// Returns `Some(_)` if this method cannot be called on a trait
288 /// object; this does not necessarily imply that the enclosing trait
289 /// is not object safe, because the method might have a where clause
291 fn virtual_call_violation_for_method(self,
293 method: &ty::AssociatedItem)
294 -> Option<MethodViolationCode>
296 // The method's first parameter must be named `self`
297 if !method.method_has_self_argument {
298 return Some(MethodViolationCode::StaticMethod);
301 let sig = self.fn_sig(method.def_id);
303 for input_ty in &sig.skip_binder().inputs()[1..] {
304 if self.contains_illegal_self_type_reference(trait_def_id, input_ty) {
305 return Some(MethodViolationCode::ReferencesSelf);
308 if self.contains_illegal_self_type_reference(trait_def_id, sig.output().skip_binder()) {
309 return Some(MethodViolationCode::ReferencesSelf);
312 // We can't monomorphize things like `fn foo<A>(...)`.
313 let own_counts = self.generics_of(method.def_id).own_counts();
314 if own_counts.types + own_counts.consts != 0 {
315 return Some(MethodViolationCode::Generic);
318 if self.predicates_of(method.def_id).predicates.iter()
319 // A trait object can't claim to live more than the concrete type,
320 // so outlives predicates will always hold.
322 .filter(|(p, _)| p.to_opt_type_outlives().is_none())
324 // Do a shallow visit so that `contains_illegal_self_type_reference`
325 // may apply it's custom visiting.
326 .visit_tys_shallow(|t| self.contains_illegal_self_type_reference(trait_def_id, t)) {
327 let span = self.def_span(method.def_id);
328 return Some(MethodViolationCode::WhereClauseReferencesSelf(span));
331 let receiver_ty = self.liberate_late_bound_regions(
333 &sig.map_bound(|sig| sig.inputs()[0]),
336 // until `unsized_locals` is fully implemented, `self: Self` can't be dispatched on.
337 // However, this is already considered object-safe. We allow it as a special case here.
338 // FIXME(mikeyhew) get rid of this `if` statement once `receiver_is_dispatchable` allows
339 // `Receiver: Unsize<Receiver[Self => dyn Trait]>`
340 if receiver_ty != self.mk_self_type() {
341 if !self.receiver_is_dispatchable(method, receiver_ty) {
342 return Some(MethodViolationCode::UndispatchableReceiver);
344 // sanity check to make sure the receiver actually has the layout of a pointer
346 use crate::ty::layout::Abi;
348 let param_env = self.param_env(method.def_id);
350 let abi_of_ty = |ty: Ty<'tcx>| -> &Abi {
351 match self.layout_of(param_env.and(ty)) {
352 Ok(layout) => &layout.abi,
354 "Error: {}\n while computing layout for type {:?}", err, ty
360 let unit_receiver_ty = self.receiver_for_self_ty(
361 receiver_ty, self.mk_unit(), method.def_id
364 match abi_of_ty(unit_receiver_ty) {
365 &Abi::Scalar(..) => (),
367 self.sess.delay_span_bug(
368 self.def_span(method.def_id),
370 "Receiver when Self = () should have a Scalar ABI, found {:?}",
377 let trait_object_ty = self.object_ty_for_trait(
378 trait_def_id, self.mk_region(ty::ReStatic)
381 // e.g., Rc<dyn Trait>
382 let trait_object_receiver = self.receiver_for_self_ty(
383 receiver_ty, trait_object_ty, method.def_id
386 match abi_of_ty(trait_object_receiver) {
387 &Abi::ScalarPair(..) => (),
389 self.sess.delay_span_bug(
390 self.def_span(method.def_id),
392 "Receiver when Self = {} should have a ScalarPair ABI, found {:?}",
404 /// Performs a type substitution to produce the version of receiver_ty when `Self = self_ty`
405 /// e.g., for receiver_ty = `Rc<Self>` and self_ty = `Foo`, returns `Rc<Foo>`.
406 fn receiver_for_self_ty(
407 self, receiver_ty: Ty<'tcx>, self_ty: Ty<'tcx>, method_def_id: DefId
409 debug!("receiver_for_self_ty({:?}, {:?}, {:?})", receiver_ty, self_ty, method_def_id);
410 let substs = InternalSubsts::for_item(self, method_def_id, |param, _| {
411 if param.index == 0 {
414 self.mk_param_from_def(param)
418 let result = receiver_ty.subst(self, substs);
419 debug!("receiver_for_self_ty({:?}, {:?}, {:?}) = {:?}",
420 receiver_ty, self_ty, method_def_id, result);
424 /// Creates the object type for the current trait. For example,
425 /// if the current trait is `Deref`, then this will be
426 /// `dyn Deref<Target = Self::Target> + 'static`.
427 fn object_ty_for_trait(self, trait_def_id: DefId, lifetime: ty::Region<'tcx>) -> Ty<'tcx> {
428 debug!("object_ty_for_trait: trait_def_id={:?}", trait_def_id);
430 let trait_ref = ty::TraitRef::identity(self, trait_def_id);
432 let trait_predicate = ty::ExistentialPredicate::Trait(
433 ty::ExistentialTraitRef::erase_self_ty(self, trait_ref)
436 let mut associated_types = traits::supertraits(self, ty::Binder::dummy(trait_ref))
437 .flat_map(|super_trait_ref| {
438 self.associated_items(super_trait_ref.def_id())
439 .map(move |item| (super_trait_ref, item))
441 .filter(|(_, item)| item.kind == ty::AssociatedKind::Type)
442 .collect::<Vec<_>>();
444 // existential predicates need to be in a specific order
445 associated_types.sort_by_cached_key(|(_, item)| self.def_path_hash(item.def_id));
447 let projection_predicates = associated_types.into_iter().map(|(super_trait_ref, item)| {
448 // We *can* get bound lifetimes here in cases like
449 // `trait MyTrait: for<'s> OtherTrait<&'s T, Output=bool>`.
451 // binder moved to (*)...
452 let super_trait_ref = super_trait_ref.skip_binder();
453 ty::ExistentialPredicate::Projection(ty::ExistentialProjection {
454 ty: self.mk_projection(item.def_id, super_trait_ref.substs),
455 item_def_id: item.def_id,
456 substs: super_trait_ref.substs,
460 let existential_predicates = self.mk_existential_predicates(
461 iter::once(trait_predicate).chain(projection_predicates)
464 let object_ty = self.mk_dynamic(
465 // (*) ... binder re-introduced here
466 ty::Binder::bind(existential_predicates),
470 debug!("object_ty_for_trait: object_ty=`{}`", object_ty);
475 /// Checks the method's receiver (the `self` argument) can be dispatched on when `Self` is a
476 /// trait object. We require that `DispatchableFromDyn` be implemented for the receiver type
477 /// in the following way:
478 /// - let `Receiver` be the type of the `self` argument, i.e `Self`, `&Self`, `Rc<Self>`,
479 /// - require the following bound:
482 /// Receiver[Self => T]: DispatchFromDyn<Receiver[Self => dyn Trait]>
485 /// where `Foo[X => Y]` means "the same type as `Foo`, but with `X` replaced with `Y`"
486 /// (substitution notation).
488 /// Some examples of receiver types and their required obligation:
489 /// - `&'a mut self` requires `&'a mut Self: DispatchFromDyn<&'a mut dyn Trait>`,
490 /// - `self: Rc<Self>` requires `Rc<Self>: DispatchFromDyn<Rc<dyn Trait>>`,
491 /// - `self: Pin<Box<Self>>` requires `Pin<Box<Self>>: DispatchFromDyn<Pin<Box<dyn Trait>>>`.
493 /// The only case where the receiver is not dispatchable, but is still a valid receiver
494 /// type (just not object-safe), is when there is more than one level of pointer indirection.
495 /// E.g., `self: &&Self`, `self: &Rc<Self>`, `self: Box<Box<Self>>`. In these cases, there
496 /// is no way, or at least no inexpensive way, to coerce the receiver from the version where
497 /// `Self = dyn Trait` to the version where `Self = T`, where `T` is the unknown erased type
498 /// contained by the trait object, because the object that needs to be coerced is behind
501 /// In practice, we cannot use `dyn Trait` explicitly in the obligation because it would result
502 /// in a new check that `Trait` is object safe, creating a cycle. So instead, we fudge a little
503 /// by introducing a new type parameter `U` such that `Self: Unsize<U>` and `U: Trait + ?Sized`,
504 /// and use `U` in place of `dyn Trait`. Written as a chalk-style query:
506 /// forall (U: Trait + ?Sized) {
507 /// if (Self: Unsize<U>) {
508 /// Receiver: DispatchFromDyn<Receiver[Self => U]>
512 /// for `self: &'a mut Self`, this means `&'a mut Self: DispatchFromDyn<&'a mut U>`
513 /// for `self: Rc<Self>`, this means `Rc<Self>: DispatchFromDyn<Rc<U>>`
514 /// for `self: Pin<Box<Self>>`, this means `Pin<Box<Self>>: DispatchFromDyn<Pin<Box<U>>>`
516 // FIXME(mikeyhew) when unsized receivers are implemented as part of unsized rvalues, add this
517 // fallback query: `Receiver: Unsize<Receiver[Self => U]>` to support receivers like
518 // `self: Wrapper<Self>`.
520 fn receiver_is_dispatchable(
522 method: &ty::AssociatedItem,
523 receiver_ty: Ty<'tcx>,
525 debug!("receiver_is_dispatchable: method = {:?}, receiver_ty = {:?}", method, receiver_ty);
527 let traits = (self.lang_items().unsize_trait(),
528 self.lang_items().dispatch_from_dyn_trait());
529 let (unsize_did, dispatch_from_dyn_did) = if let (Some(u), Some(cu)) = traits {
532 debug!("receiver_is_dispatchable: Missing Unsize or DispatchFromDyn traits");
536 // the type `U` in the query
537 // use a bogus type parameter to mimick a forall(U) query using u32::MAX for now.
538 // FIXME(mikeyhew) this is a total hack, and we should replace it when real forall queries
540 let unsized_self_ty: Ty<'tcx> = self.mk_ty_param(
542 Name::intern("RustaceansAreAwesome").as_interned_str(),
545 // `Receiver[Self => U]`
546 let unsized_receiver_ty = self.receiver_for_self_ty(
547 receiver_ty, unsized_self_ty, method.def_id
550 // create a modified param env, with `Self: Unsize<U>` and `U: Trait` added to caller bounds
551 // `U: ?Sized` is already implied here
553 let mut param_env = self.param_env(method.def_id);
556 let unsize_predicate = ty::TraitRef {
558 substs: self.mk_substs_trait(self.mk_self_type(), &[unsized_self_ty.into()]),
561 // U: Trait<Arg1, ..., ArgN>
562 let trait_predicate = {
563 let substs = InternalSubsts::for_item(
565 method.container.assert_trait(),
567 if param.index == 0 {
568 unsized_self_ty.into()
570 self.mk_param_from_def(param)
581 let caller_bounds: Vec<Predicate<'tcx>> = param_env.caller_bounds.iter().cloned()
582 .chain(iter::once(unsize_predicate))
583 .chain(iter::once(trait_predicate))
586 param_env.caller_bounds = self.intern_predicates(&caller_bounds);
591 // Receiver: DispatchFromDyn<Receiver[Self => U]>
593 let predicate = ty::TraitRef {
594 def_id: dispatch_from_dyn_did,
595 substs: self.mk_substs_trait(receiver_ty, &[unsized_receiver_ty.into()]),
599 ObligationCause::dummy(),
605 self.infer_ctxt().enter(|ref infcx| {
606 // the receiver is dispatchable iff the obligation holds
607 infcx.predicate_must_hold_modulo_regions(&obligation)
611 fn contains_illegal_self_type_reference(self,
616 // This is somewhat subtle. In general, we want to forbid
617 // references to `Self` in the argument and return types,
618 // since the value of `Self` is erased. However, there is one
619 // exception: it is ok to reference `Self` in order to access
620 // an associated type of the current trait, since we retain
621 // the value of those associated types in the object type
625 // trait SuperTrait {
629 // trait Trait : SuperTrait {
631 // fn foo(&self, x: Self) // bad
632 // fn foo(&self) -> Self // bad
633 // fn foo(&self) -> Option<Self> // bad
634 // fn foo(&self) -> Self::Y // OK, desugars to next example
635 // fn foo(&self) -> <Self as Trait>::Y // OK
636 // fn foo(&self) -> Self::X // OK, desugars to next example
637 // fn foo(&self) -> <Self as SuperTrait>::X // OK
641 // However, it is not as simple as allowing `Self` in a projected
642 // type, because there are illegal ways to use `Self` as well:
645 // trait Trait : SuperTrait {
647 // fn foo(&self) -> <Self as SomeOtherTrait>::X;
651 // Here we will not have the type of `X` recorded in the
652 // object type, and we cannot resolve `Self as SomeOtherTrait`
653 // without knowing what `Self` is.
655 let mut supertraits: Option<Vec<ty::PolyTraitRef<'tcx>>> = None;
656 let mut error = false;
659 ty::Param(ref param_ty) => {
660 if param_ty.is_self() {
664 false // no contained types to walk
667 ty::Projection(ref data) => {
668 // This is a projected type `<Foo as SomeTrait>::X`.
670 // Compute supertraits of current trait lazily.
671 if supertraits.is_none() {
672 let trait_ref = ty::Binder::bind(
673 ty::TraitRef::identity(self, trait_def_id),
675 supertraits = Some(traits::supertraits(self, trait_ref).collect());
678 // Determine whether the trait reference `Foo as
679 // SomeTrait` is in fact a supertrait of the
680 // current trait. In that case, this type is
681 // legal, because the type `X` will be specified
682 // in the object type. Note that we can just use
683 // direct equality here because all of these types
684 // are part of the formal parameter listing, and
685 // hence there should be no inference variables.
686 let projection_trait_ref = ty::Binder::bind(data.trait_ref(self));
687 let is_supertrait_of_current_trait =
688 supertraits.as_ref().unwrap().contains(&projection_trait_ref);
690 if is_supertrait_of_current_trait {
691 false // do not walk contained types, do not report error, do collect $200
693 true // DO walk contained types, POSSIBLY reporting an error
697 _ => true, // walk contained types, if any
705 pub(super) fn is_object_safe_provider<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
706 trait_def_id: DefId) -> bool {
707 tcx.object_safety_violations(trait_def_id).is_empty()