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::hir::def_id::DefId;
15 use crate::traits::{self, Obligation, ObligationCause};
16 use crate::ty::{self, Ty, TyCtxt, TypeFoldable, Predicate, ToPredicate};
17 use crate::ty::subst::{Subst, Substs};
19 use std::iter::{self};
20 use syntax::ast::{self, Name};
23 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
24 pub enum ObjectSafetyViolation {
25 /// Self : Sized declared on the trait
28 /// Supertrait reference references `Self` an in illegal location
29 /// (e.g., `trait Foo : Bar<Self>`)
32 /// Method has something illegal
33 Method(ast::Name, MethodViolationCode),
36 AssociatedConst(ast::Name),
39 impl ObjectSafetyViolation {
40 pub fn error_msg(&self) -> Cow<'static, str> {
42 ObjectSafetyViolation::SizedSelf =>
43 "the trait cannot require that `Self : Sized`".into(),
44 ObjectSafetyViolation::SupertraitSelf =>
45 "the trait cannot use `Self` as a type parameter \
46 in the supertraits or where-clauses".into(),
47 ObjectSafetyViolation::Method(name, MethodViolationCode::StaticMethod) =>
48 format!("method `{}` has no receiver", name).into(),
49 ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelf) =>
50 format!("method `{}` references the `Self` type \
51 in its arguments or return type", name).into(),
52 ObjectSafetyViolation::Method(name,
53 MethodViolationCode::WhereClauseReferencesSelf(_)) =>
54 format!("method `{}` references the `Self` type in where clauses", name).into(),
55 ObjectSafetyViolation::Method(name, MethodViolationCode::Generic) =>
56 format!("method `{}` has generic type parameters", name).into(),
57 ObjectSafetyViolation::Method(name, MethodViolationCode::UndispatchableReceiver) =>
58 format!("method `{}`'s receiver cannot be dispatched on", name).into(),
59 ObjectSafetyViolation::AssociatedConst(name) =>
60 format!("the trait cannot contain associated consts like `{}`", name).into(),
65 /// Reasons a method might not be object-safe.
66 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
67 pub enum MethodViolationCode {
71 /// e.g., `fn foo(&self, x: Self)` or `fn foo(&self) -> Self`
74 /// e.g., `fn foo(&self) where Self: Clone`
75 WhereClauseReferencesSelf(Span),
77 /// e.g., `fn foo<A>()`
80 /// the method's receiver (`self` argument) can't be dispatched on
81 UndispatchableReceiver,
84 impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> {
86 /// Returns the object safety violations that affect
87 /// astconv - currently, Self in supertraits. This is needed
88 /// because `object_safety_violations` can't be used during
90 pub fn astconv_object_safety_violations(self, trait_def_id: DefId)
91 -> Vec<ObjectSafetyViolation>
93 let violations = traits::supertrait_def_ids(self, trait_def_id)
94 .filter(|&def_id| self.predicates_reference_self(def_id, true))
95 .map(|_| ObjectSafetyViolation::SupertraitSelf)
98 debug!("astconv_object_safety_violations(trait_def_id={:?}) = {:?}",
105 pub fn object_safety_violations(self, trait_def_id: DefId)
106 -> Vec<ObjectSafetyViolation>
108 debug!("object_safety_violations: {:?}", trait_def_id);
110 traits::supertrait_def_ids(self, trait_def_id)
111 .flat_map(|def_id| self.object_safety_violations_for_trait(def_id))
115 fn object_safety_violations_for_trait(self, trait_def_id: DefId)
116 -> Vec<ObjectSafetyViolation>
118 // Check methods for violations.
119 let mut violations: Vec<_> = self.associated_items(trait_def_id)
120 .filter(|item| item.kind == ty::AssociatedKind::Method)
122 self.object_safety_violation_for_method(trait_def_id, &item)
123 .map(|code| ObjectSafetyViolation::Method(item.ident.name, code))
124 ).filter(|violation| {
125 if let ObjectSafetyViolation::Method(_,
126 MethodViolationCode::WhereClauseReferencesSelf(span)) = violation
128 // Using `CRATE_NODE_ID` is wrong, but it's hard to get a more precise id.
129 // It's also hard to get a use site span, so we use the method definition span.
131 lint::builtin::WHERE_CLAUSES_OBJECT_SAFETY,
134 &format!("the trait `{}` cannot be made into an object",
135 self.item_path_str(trait_def_id)),
136 &violation.error_msg());
143 // Check the trait itself.
144 if self.trait_has_sized_self(trait_def_id) {
145 violations.push(ObjectSafetyViolation::SizedSelf);
147 if self.predicates_reference_self(trait_def_id, false) {
148 violations.push(ObjectSafetyViolation::SupertraitSelf);
151 violations.extend(self.associated_items(trait_def_id)
152 .filter(|item| item.kind == ty::AssociatedKind::Const)
153 .map(|item| ObjectSafetyViolation::AssociatedConst(item.ident.name)));
155 debug!("object_safety_violations_for_trait(trait_def_id={:?}) = {:?}",
162 fn predicates_reference_self(
165 supertraits_only: bool) -> bool
167 let trait_ref = ty::Binder::dummy(ty::TraitRef::identity(self, trait_def_id));
168 let predicates = if supertraits_only {
169 self.super_predicates_of(trait_def_id)
171 self.predicates_of(trait_def_id)
176 .map(|(predicate, _)| predicate.subst_supertrait(self, &trait_ref))
179 ty::Predicate::Trait(ref data) => {
180 // In the case of a trait predicate, we can skip the "self" type.
181 data.skip_binder().input_types().skip(1).any(|t| t.has_self_ty())
183 ty::Predicate::Projection(ref data) => {
184 // And similarly for projections. This should be redundant with
185 // the previous check because any projection should have a
186 // matching `Trait` predicate with the same inputs, but we do
187 // the check to be safe.
189 // Note that we *do* allow projection *outputs* to contain
190 // `self` (i.e., `trait Foo: Bar<Output=Self::Result> { type Result; }`),
191 // we just require the user to specify *both* outputs
192 // in the object type (i.e., `dyn Foo<Output=(), Result=()>`).
194 // This is ALT2 in issue #56288, see that for discussion of the
195 // possible alternatives.
201 .any(|t| t.has_self_ty())
203 ty::Predicate::WellFormed(..) |
204 ty::Predicate::ObjectSafe(..) |
205 ty::Predicate::TypeOutlives(..) |
206 ty::Predicate::RegionOutlives(..) |
207 ty::Predicate::ClosureKind(..) |
208 ty::Predicate::Subtype(..) |
209 ty::Predicate::ConstEvaluatable(..) => {
216 fn trait_has_sized_self(self, trait_def_id: DefId) -> bool {
217 self.generics_require_sized_self(trait_def_id)
220 fn generics_require_sized_self(self, def_id: DefId) -> bool {
221 let sized_def_id = match self.lang_items().sized_trait() {
222 Some(def_id) => def_id,
223 None => { return false; /* No Sized trait, can't require it! */ }
226 // Search for a predicate like `Self : Sized` amongst the trait bounds.
227 let predicates = self.predicates_of(def_id);
228 let predicates = predicates.instantiate_identity(self).predicates;
229 elaborate_predicates(self, predicates)
230 .any(|predicate| match predicate {
231 ty::Predicate::Trait(ref trait_pred) if trait_pred.def_id() == sized_def_id => {
232 trait_pred.skip_binder().self_ty().is_self()
234 ty::Predicate::Projection(..) |
235 ty::Predicate::Trait(..) |
236 ty::Predicate::Subtype(..) |
237 ty::Predicate::RegionOutlives(..) |
238 ty::Predicate::WellFormed(..) |
239 ty::Predicate::ObjectSafe(..) |
240 ty::Predicate::ClosureKind(..) |
241 ty::Predicate::TypeOutlives(..) |
242 ty::Predicate::ConstEvaluatable(..) => {
249 /// Returns `Some(_)` if this method makes the containing trait not object safe.
250 fn object_safety_violation_for_method(self,
252 method: &ty::AssociatedItem)
253 -> Option<MethodViolationCode>
255 debug!("object_safety_violation_for_method({:?}, {:?})", trait_def_id, method);
256 // Any method that has a `Self : Sized` requisite is otherwise
257 // exempt from the regulations.
258 if self.generics_require_sized_self(method.def_id) {
262 self.virtual_call_violation_for_method(trait_def_id, method)
265 /// We say a method is *vtable safe* if it can be invoked on a trait
266 /// object. Note that object-safe traits can have some
267 /// non-vtable-safe methods, so long as they require `Self:Sized` or
268 /// otherwise ensure that they cannot be used when `Self=Trait`.
269 pub fn is_vtable_safe_method(self,
271 method: &ty::AssociatedItem)
274 debug!("is_vtable_safe_method({:?}, {:?})", trait_def_id, method);
275 // Any method that has a `Self : Sized` requisite can't be called.
276 if self.generics_require_sized_self(method.def_id) {
280 match self.virtual_call_violation_for_method(trait_def_id, method) {
281 None | Some(MethodViolationCode::WhereClauseReferencesSelf(_)) => true,
286 /// Returns `Some(_)` if this method cannot be called on a trait
287 /// object; this does not necessarily imply that the enclosing trait
288 /// is not object safe, because the method might have a where clause
290 fn virtual_call_violation_for_method(self,
292 method: &ty::AssociatedItem)
293 -> Option<MethodViolationCode>
295 // The method's first parameter must be named `self`
296 if !method.method_has_self_argument {
297 return Some(MethodViolationCode::StaticMethod);
300 let sig = self.fn_sig(method.def_id);
302 for input_ty in &sig.skip_binder().inputs()[1..] {
303 if self.contains_illegal_self_type_reference(trait_def_id, input_ty) {
304 return Some(MethodViolationCode::ReferencesSelf);
307 if self.contains_illegal_self_type_reference(trait_def_id, sig.output().skip_binder()) {
308 return Some(MethodViolationCode::ReferencesSelf);
311 // We can't monomorphize things like `fn foo<A>(...)`.
312 if self.generics_of(method.def_id).own_counts().types != 0 {
313 return Some(MethodViolationCode::Generic);
316 if self.predicates_of(method.def_id).predicates.iter()
317 // A trait object can't claim to live more than the concrete type,
318 // so outlives predicates will always hold.
320 .filter(|(p, _)| p.to_opt_type_outlives().is_none())
322 // Do a shallow visit so that `contains_illegal_self_type_reference`
323 // may apply it's custom visiting.
324 .visit_tys_shallow(|t| self.contains_illegal_self_type_reference(trait_def_id, t)) {
325 let span = self.def_span(method.def_id);
326 return Some(MethodViolationCode::WhereClauseReferencesSelf(span));
329 let receiver_ty = self.liberate_late_bound_regions(
331 &sig.map_bound(|sig| sig.inputs()[0]),
334 // until `unsized_locals` is fully implemented, `self: Self` can't be dispatched on.
335 // However, this is already considered object-safe. We allow it as a special case here.
336 // FIXME(mikeyhew) get rid of this `if` statement once `receiver_is_dispatchable` allows
337 // `Receiver: Unsize<Receiver[Self => dyn Trait]>`
338 if receiver_ty != self.mk_self_type() {
339 if !self.receiver_is_dispatchable(method, receiver_ty) {
340 return Some(MethodViolationCode::UndispatchableReceiver);
342 // sanity check to make sure the receiver actually has the layout of a pointer
344 use crate::ty::layout::Abi;
346 let param_env = self.param_env(method.def_id);
348 let abi_of_ty = |ty: Ty<'tcx>| -> &Abi {
349 match self.layout_of(param_env.and(ty)) {
350 Ok(layout) => &layout.abi,
352 "Error: {}\n while computing layout for type {:?}", err, ty
358 let unit_receiver_ty = self.receiver_for_self_ty(
359 receiver_ty, self.mk_unit(), method.def_id
362 match abi_of_ty(unit_receiver_ty) {
363 &Abi::Scalar(..) => (),
365 self.sess.delay_span_bug(
366 self.def_span(method.def_id),
368 "Receiver when Self = () should have a Scalar ABI, found {:?}",
375 let trait_object_ty = self.object_ty_for_trait(
376 trait_def_id, self.mk_region(ty::ReStatic)
379 // e.g., Rc<dyn Trait>
380 let trait_object_receiver = self.receiver_for_self_ty(
381 receiver_ty, trait_object_ty, method.def_id
384 match abi_of_ty(trait_object_receiver) {
385 &Abi::ScalarPair(..) => (),
387 self.sess.delay_span_bug(
388 self.def_span(method.def_id),
390 "Receiver when Self = {} should have a ScalarPair ABI, found {:?}",
402 /// performs a type substitution to produce the version of receiver_ty when `Self = self_ty`
403 /// e.g., for receiver_ty = `Rc<Self>` and self_ty = `Foo`, returns `Rc<Foo>`
404 fn receiver_for_self_ty(
405 self, receiver_ty: Ty<'tcx>, self_ty: Ty<'tcx>, method_def_id: DefId
407 debug!("receiver_for_self_ty({:?}, {:?}, {:?})", receiver_ty, self_ty, method_def_id);
408 let substs = Substs::for_item(self, method_def_id, |param, _| {
409 if param.index == 0 {
412 self.mk_param_from_def(param)
416 let result = receiver_ty.subst(self, substs);
417 debug!("receiver_for_self_ty({:?}, {:?}, {:?}) = {:?}",
418 receiver_ty, self_ty, method_def_id, result);
422 /// creates the object type for the current trait. For example,
423 /// if the current trait is `Deref`, then this will be
424 /// `dyn Deref<Target=Self::Target> + 'static`
425 fn object_ty_for_trait(self, trait_def_id: DefId, lifetime: ty::Region<'tcx>) -> Ty<'tcx> {
426 debug!("object_ty_for_trait: trait_def_id={:?}", trait_def_id);
428 let trait_ref = ty::TraitRef::identity(self, trait_def_id);
430 let trait_predicate = ty::ExistentialPredicate::Trait(
431 ty::ExistentialTraitRef::erase_self_ty(self, trait_ref)
434 let mut associated_types = traits::supertraits(self, ty::Binder::dummy(trait_ref))
435 .flat_map(|super_trait_ref| {
436 self.associated_items(super_trait_ref.def_id())
437 .map(move |item| (super_trait_ref, item))
439 .filter(|(_, item)| item.kind == ty::AssociatedKind::Type)
440 .collect::<Vec<_>>();
442 // existential predicates need to be in a specific order
443 associated_types.sort_by_cached_key(|(_, item)| self.def_path_hash(item.def_id));
445 let projection_predicates = associated_types.into_iter().map(|(super_trait_ref, item)| {
446 // We *can* get bound lifetimes here in cases like
447 // `trait MyTrait: for<'s> OtherTrait<&'s T, Output=bool>`.
449 // binder moved to (*)...
450 let super_trait_ref = super_trait_ref.skip_binder();
451 ty::ExistentialPredicate::Projection(ty::ExistentialProjection {
452 ty: self.mk_projection(item.def_id, super_trait_ref.substs),
453 item_def_id: item.def_id,
454 substs: super_trait_ref.substs,
458 let existential_predicates = self.mk_existential_predicates(
459 iter::once(trait_predicate).chain(projection_predicates)
462 let object_ty = self.mk_dynamic(
463 // (*) ... binder re-introduced here
464 ty::Binder::bind(existential_predicates),
468 debug!("object_ty_for_trait: object_ty=`{}`", object_ty);
473 /// checks the method's receiver (the `self` argument) can be dispatched on when `Self` is a
474 /// trait object. We require that `DispatchableFromDyn` be implemented for the receiver type
475 /// in the following way:
476 /// - let `Receiver` be the type of the `self` argument, i.e `Self`, `&Self`, `Rc<Self>`
477 /// - require the following bound:
479 /// Receiver[Self => T]: DispatchFromDyn<Receiver[Self => dyn Trait]>
481 /// where `Foo[X => Y]` means "the same type as `Foo`, but with `X` replaced with `Y`"
482 /// (substitution notation).
484 /// some examples of receiver types and their required obligation
485 /// - `&'a mut self` requires `&'a mut Self: DispatchFromDyn<&'a mut dyn Trait>`
486 /// - `self: Rc<Self>` requires `Rc<Self>: DispatchFromDyn<Rc<dyn Trait>>`
487 /// - `self: Pin<Box<Self>>` requires `Pin<Box<Self>>: DispatchFromDyn<Pin<Box<dyn Trait>>>`
489 /// The only case where the receiver is not dispatchable, but is still a valid receiver
490 /// type (just not object-safe), is when there is more than one level of pointer indirection.
491 /// e.g., `self: &&Self`, `self: &Rc<Self>`, `self: Box<Box<Self>>`. In these cases, there
492 /// is no way, or at least no inexpensive way, to coerce the receiver from the version where
493 /// `Self = dyn Trait` to the version where `Self = T`, where `T` is the unknown erased type
494 /// contained by the trait object, because the object that needs to be coerced is behind
497 /// In practice, we cannot use `dyn Trait` explicitly in the obligation because it would result
498 /// in a new check that `Trait` is object safe, creating a cycle. So instead, we fudge a little
499 /// by introducing a new type parameter `U` such that `Self: Unsize<U>` and `U: Trait + ?Sized`,
500 /// and use `U` in place of `dyn Trait`. Written as a chalk-style query:
502 /// forall (U: Trait + ?Sized) {
503 /// if (Self: Unsize<U>) {
504 /// Receiver: DispatchFromDyn<Receiver[Self => U]>
508 /// for `self: &'a mut Self`, this means `&'a mut Self: DispatchFromDyn<&'a mut U>`
509 /// for `self: Rc<Self>`, this means `Rc<Self>: DispatchFromDyn<Rc<U>>`
510 /// for `self: Pin<Box<Self>>`, this means `Pin<Box<Self>>: DispatchFromDyn<Pin<Box<U>>>`
512 // FIXME(mikeyhew) when unsized receivers are implemented as part of unsized rvalues, add this
513 // fallback query: `Receiver: Unsize<Receiver[Self => U]>` to support receivers like
514 // `self: Wrapper<Self>`.
516 fn receiver_is_dispatchable(
518 method: &ty::AssociatedItem,
519 receiver_ty: Ty<'tcx>,
521 debug!("receiver_is_dispatchable: method = {:?}, receiver_ty = {:?}", method, receiver_ty);
523 let traits = (self.lang_items().unsize_trait(),
524 self.lang_items().dispatch_from_dyn_trait());
525 let (unsize_did, dispatch_from_dyn_did) = if let (Some(u), Some(cu)) = traits {
528 debug!("receiver_is_dispatchable: Missing Unsize or DispatchFromDyn traits");
532 // the type `U` in the query
533 // use a bogus type parameter to mimick a forall(U) query using u32::MAX for now.
534 // FIXME(mikeyhew) this is a total hack, and we should replace it when real forall queries
536 let unsized_self_ty: Ty<'tcx> = self.mk_ty_param(
538 Name::intern("RustaceansAreAwesome").as_interned_str(),
541 // `Receiver[Self => U]`
542 let unsized_receiver_ty = self.receiver_for_self_ty(
543 receiver_ty, unsized_self_ty, method.def_id
546 // create a modified param env, with `Self: Unsize<U>` and `U: Trait` added to caller bounds
547 // `U: ?Sized` is already implied here
549 let mut param_env = self.param_env(method.def_id);
552 let unsize_predicate = ty::TraitRef {
554 substs: self.mk_substs_trait(self.mk_self_type(), &[unsized_self_ty.into()]),
557 // U: Trait<Arg1, ..., ArgN>
558 let trait_predicate = {
559 let substs = Substs::for_item(self, method.container.assert_trait(), |param, _| {
560 if param.index == 0 {
561 unsized_self_ty.into()
563 self.mk_param_from_def(param)
573 let caller_bounds: Vec<Predicate<'tcx>> = param_env.caller_bounds.iter().cloned()
574 .chain(iter::once(unsize_predicate))
575 .chain(iter::once(trait_predicate))
578 param_env.caller_bounds = self.intern_predicates(&caller_bounds);
583 // Receiver: DispatchFromDyn<Receiver[Self => U]>
585 let predicate = ty::TraitRef {
586 def_id: dispatch_from_dyn_did,
587 substs: self.mk_substs_trait(receiver_ty, &[unsized_receiver_ty.into()]),
591 ObligationCause::dummy(),
597 self.infer_ctxt().enter(|ref infcx| {
598 // the receiver is dispatchable iff the obligation holds
599 infcx.predicate_must_hold_modulo_regions(&obligation)
603 fn contains_illegal_self_type_reference(self,
608 // This is somewhat subtle. In general, we want to forbid
609 // references to `Self` in the argument and return types,
610 // since the value of `Self` is erased. However, there is one
611 // exception: it is ok to reference `Self` in order to access
612 // an associated type of the current trait, since we retain
613 // the value of those associated types in the object type
617 // trait SuperTrait {
621 // trait Trait : SuperTrait {
623 // fn foo(&self, x: Self) // bad
624 // fn foo(&self) -> Self // bad
625 // fn foo(&self) -> Option<Self> // bad
626 // fn foo(&self) -> Self::Y // OK, desugars to next example
627 // fn foo(&self) -> <Self as Trait>::Y // OK
628 // fn foo(&self) -> Self::X // OK, desugars to next example
629 // fn foo(&self) -> <Self as SuperTrait>::X // OK
633 // However, it is not as simple as allowing `Self` in a projected
634 // type, because there are illegal ways to use `Self` as well:
637 // trait Trait : SuperTrait {
639 // fn foo(&self) -> <Self as SomeOtherTrait>::X;
643 // Here we will not have the type of `X` recorded in the
644 // object type, and we cannot resolve `Self as SomeOtherTrait`
645 // without knowing what `Self` is.
647 let mut supertraits: Option<Vec<ty::PolyTraitRef<'tcx>>> = None;
648 let mut error = false;
651 ty::Param(ref param_ty) => {
652 if param_ty.is_self() {
656 false // no contained types to walk
659 ty::Projection(ref data) => {
660 // This is a projected type `<Foo as SomeTrait>::X`.
662 // Compute supertraits of current trait lazily.
663 if supertraits.is_none() {
664 let trait_ref = ty::Binder::bind(
665 ty::TraitRef::identity(self, trait_def_id),
667 supertraits = Some(traits::supertraits(self, trait_ref).collect());
670 // Determine whether the trait reference `Foo as
671 // SomeTrait` is in fact a supertrait of the
672 // current trait. In that case, this type is
673 // legal, because the type `X` will be specified
674 // in the object type. Note that we can just use
675 // direct equality here because all of these types
676 // are part of the formal parameter listing, and
677 // hence there should be no inference variables.
678 let projection_trait_ref = ty::Binder::bind(data.trait_ref(self));
679 let is_supertrait_of_current_trait =
680 supertraits.as_ref().unwrap().contains(&projection_trait_ref);
682 if is_supertrait_of_current_trait {
683 false // do not walk contained types, do not report error, do collect $200
685 true // DO walk contained types, POSSIBLY reporting an error
689 _ => true, // walk contained types, if any
697 pub(super) fn is_object_safe_provider<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
698 trait_def_id: DefId) -> bool {
699 tcx.object_safety_violations(trait_def_id).is_empty()