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};
22 use syntax::symbol::InternedString;
25 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
26 pub enum ObjectSafetyViolation {
27 /// `Self: Sized` declared on the trait.
30 /// Supertrait reference references `Self` an in illegal location
31 /// (e.g., `trait Foo : Bar<Self>`).
34 /// Method has something illegal.
35 Method(ast::Name, MethodViolationCode),
38 AssocConst(ast::Name),
41 impl ObjectSafetyViolation {
42 pub fn error_msg(&self) -> Cow<'static, str> {
44 ObjectSafetyViolation::SizedSelf =>
45 "the trait cannot require that `Self : Sized`".into(),
46 ObjectSafetyViolation::SupertraitSelf =>
47 "the trait cannot use `Self` as a type parameter \
48 in the supertraits or where-clauses".into(),
49 ObjectSafetyViolation::Method(name, MethodViolationCode::StaticMethod) =>
50 format!("method `{}` has no receiver", name).into(),
51 ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelf) =>
52 format!("method `{}` references the `Self` type \
53 in its arguments or return type", name).into(),
54 ObjectSafetyViolation::Method(name,
55 MethodViolationCode::WhereClauseReferencesSelf(_)) =>
56 format!("method `{}` references the `Self` type in where clauses", name).into(),
57 ObjectSafetyViolation::Method(name, MethodViolationCode::Generic) =>
58 format!("method `{}` has generic type parameters", name).into(),
59 ObjectSafetyViolation::Method(name, MethodViolationCode::UndispatchableReceiver) =>
60 format!("method `{}`'s receiver cannot be dispatched on", name).into(),
61 ObjectSafetyViolation::AssocConst(name) =>
62 format!("the trait cannot contain associated consts like `{}`", name).into(),
67 /// Reasons a method might not be object-safe.
68 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
69 pub enum MethodViolationCode {
73 /// e.g., `fn foo(&self, x: Self)` or `fn foo(&self) -> Self`
76 /// e.g., `fn foo(&self) where Self: Clone`
77 WhereClauseReferencesSelf(Span),
79 /// e.g., `fn foo<A>()`
82 /// the method's receiver (`self` argument) can't be dispatched on
83 UndispatchableReceiver,
86 impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> {
88 /// Returns the object safety violations that affect
89 /// astconv -- currently, `Self` in supertraits. This is needed
90 /// because `object_safety_violations` can't be used during
92 pub fn astconv_object_safety_violations(self, trait_def_id: DefId)
93 -> Vec<ObjectSafetyViolation>
95 let violations = traits::supertrait_def_ids(self, trait_def_id)
96 .filter(|&def_id| self.predicates_reference_self(def_id, true))
97 .map(|_| ObjectSafetyViolation::SupertraitSelf)
100 debug!("astconv_object_safety_violations(trait_def_id={:?}) = {:?}",
107 pub fn object_safety_violations(self, trait_def_id: DefId)
108 -> Vec<ObjectSafetyViolation>
110 debug!("object_safety_violations: {:?}", trait_def_id);
112 traits::supertrait_def_ids(self, trait_def_id)
113 .flat_map(|def_id| self.object_safety_violations_for_trait(def_id))
117 fn object_safety_violations_for_trait(self, trait_def_id: DefId)
118 -> Vec<ObjectSafetyViolation>
120 // Check methods for violations.
121 let mut violations: Vec<_> = self.associated_items(trait_def_id)
122 .filter(|item| item.kind == ty::AssocKind::Method)
124 self.object_safety_violation_for_method(trait_def_id, &item)
125 .map(|code| ObjectSafetyViolation::Method(item.ident.name, code))
126 ).filter(|violation| {
127 if let ObjectSafetyViolation::Method(_,
128 MethodViolationCode::WhereClauseReferencesSelf(span)) = violation
130 // Using `CRATE_NODE_ID` is wrong, but it's hard to get a more precise id.
131 // It's also hard to get a use site span, so we use the method definition span.
133 lint::builtin::WHERE_CLAUSES_OBJECT_SAFETY,
136 &format!("the trait `{}` cannot be made into an object",
137 self.def_path_str(trait_def_id)),
138 &violation.error_msg());
145 // Check the trait itself.
146 if self.trait_has_sized_self(trait_def_id) {
147 violations.push(ObjectSafetyViolation::SizedSelf);
149 if self.predicates_reference_self(trait_def_id, false) {
150 violations.push(ObjectSafetyViolation::SupertraitSelf);
153 violations.extend(self.associated_items(trait_def_id)
154 .filter(|item| item.kind == ty::AssocKind::Const)
155 .map(|item| ObjectSafetyViolation::AssocConst(item.ident.name)));
157 debug!("object_safety_violations_for_trait(trait_def_id={:?}) = {:?}",
164 fn predicates_reference_self(
167 supertraits_only: bool) -> bool
169 let trait_ref = ty::Binder::dummy(ty::TraitRef::identity(self, trait_def_id));
170 let predicates = if supertraits_only {
171 self.super_predicates_of(trait_def_id)
173 self.predicates_of(trait_def_id)
178 .map(|(predicate, _)| predicate.subst_supertrait(self, &trait_ref))
181 ty::Predicate::Trait(ref data) => {
182 // In the case of a trait predicate, we can skip the "self" type.
183 data.skip_binder().input_types().skip(1).any(|t| t.has_self_ty())
185 ty::Predicate::Projection(ref data) => {
186 // And similarly for projections. This should be redundant with
187 // the previous check because any projection should have a
188 // matching `Trait` predicate with the same inputs, but we do
189 // the check to be safe.
191 // Note that we *do* allow projection *outputs* to contain
192 // `self` (i.e., `trait Foo: Bar<Output=Self::Result> { type Result; }`),
193 // we just require the user to specify *both* outputs
194 // in the object type (i.e., `dyn Foo<Output=(), Result=()>`).
196 // This is ALT2 in issue #56288, see that for discussion of the
197 // possible alternatives.
203 .any(|t| t.has_self_ty())
205 ty::Predicate::WellFormed(..) |
206 ty::Predicate::ObjectSafe(..) |
207 ty::Predicate::TypeOutlives(..) |
208 ty::Predicate::RegionOutlives(..) |
209 ty::Predicate::ClosureKind(..) |
210 ty::Predicate::Subtype(..) |
211 ty::Predicate::ConstEvaluatable(..) => {
218 fn trait_has_sized_self(self, trait_def_id: DefId) -> bool {
219 self.generics_require_sized_self(trait_def_id)
222 fn generics_require_sized_self(self, def_id: DefId) -> bool {
223 let sized_def_id = match self.lang_items().sized_trait() {
224 Some(def_id) => def_id,
225 None => { return false; /* No Sized trait, can't require it! */ }
228 // Search for a predicate like `Self : Sized` amongst the trait bounds.
229 let predicates = self.predicates_of(def_id);
230 let predicates = predicates.instantiate_identity(self).predicates;
231 elaborate_predicates(self, predicates)
232 .any(|predicate| match predicate {
233 ty::Predicate::Trait(ref trait_pred) if trait_pred.def_id() == sized_def_id => {
234 trait_pred.skip_binder().self_ty().is_self()
236 ty::Predicate::Projection(..) |
237 ty::Predicate::Trait(..) |
238 ty::Predicate::Subtype(..) |
239 ty::Predicate::RegionOutlives(..) |
240 ty::Predicate::WellFormed(..) |
241 ty::Predicate::ObjectSafe(..) |
242 ty::Predicate::ClosureKind(..) |
243 ty::Predicate::TypeOutlives(..) |
244 ty::Predicate::ConstEvaluatable(..) => {
251 /// Returns `Some(_)` if this method makes the containing trait not object safe.
252 fn object_safety_violation_for_method(self,
254 method: &ty::AssocItem)
255 -> Option<MethodViolationCode>
257 debug!("object_safety_violation_for_method({:?}, {:?})", trait_def_id, method);
258 // Any method that has a `Self : Sized` requisite is otherwise
259 // exempt from the regulations.
260 if self.generics_require_sized_self(method.def_id) {
264 self.virtual_call_violation_for_method(trait_def_id, method)
267 /// We say a method is *vtable safe* if it can be invoked on a trait
268 /// object. Note that object-safe traits can have some
269 /// non-vtable-safe methods, so long as they require `Self:Sized` or
270 /// otherwise ensure that they cannot be used when `Self=Trait`.
271 pub fn is_vtable_safe_method(self,
273 method: &ty::AssocItem)
276 debug!("is_vtable_safe_method({:?}, {:?})", trait_def_id, method);
277 // Any method that has a `Self : Sized` requisite can't be called.
278 if self.generics_require_sized_self(method.def_id) {
282 match self.virtual_call_violation_for_method(trait_def_id, method) {
283 None | Some(MethodViolationCode::WhereClauseReferencesSelf(_)) => true,
288 /// Returns `Some(_)` if this method cannot be called on a trait
289 /// object; this does not necessarily imply that the enclosing trait
290 /// is not object safe, because the method might have a where clause
292 fn virtual_call_violation_for_method(self,
294 method: &ty::AssocItem)
295 -> Option<MethodViolationCode>
297 // The method's first parameter must be named `self`
298 if !method.method_has_self_argument {
299 return Some(MethodViolationCode::StaticMethod);
302 let sig = self.fn_sig(method.def_id);
304 for input_ty in &sig.skip_binder().inputs()[1..] {
305 if self.contains_illegal_self_type_reference(trait_def_id, input_ty) {
306 return Some(MethodViolationCode::ReferencesSelf);
309 if self.contains_illegal_self_type_reference(trait_def_id, sig.output().skip_binder()) {
310 return Some(MethodViolationCode::ReferencesSelf);
313 // We can't monomorphize things like `fn foo<A>(...)`.
314 let own_counts = self.generics_of(method.def_id).own_counts();
315 if own_counts.types + own_counts.consts != 0 {
316 return Some(MethodViolationCode::Generic);
319 if self.predicates_of(method.def_id).predicates.iter()
320 // A trait object can't claim to live more than the concrete type,
321 // so outlives predicates will always hold.
323 .filter(|(p, _)| p.to_opt_type_outlives().is_none())
325 // Do a shallow visit so that `contains_illegal_self_type_reference`
326 // may apply it's custom visiting.
327 .visit_tys_shallow(|t| self.contains_illegal_self_type_reference(trait_def_id, t)) {
328 let span = self.def_span(method.def_id);
329 return Some(MethodViolationCode::WhereClauseReferencesSelf(span));
332 let receiver_ty = self.liberate_late_bound_regions(
334 &sig.map_bound(|sig| sig.inputs()[0]),
337 // until `unsized_locals` is fully implemented, `self: Self` can't be dispatched on.
338 // However, this is already considered object-safe. We allow it as a special case here.
339 // FIXME(mikeyhew) get rid of this `if` statement once `receiver_is_dispatchable` allows
340 // `Receiver: Unsize<Receiver[Self => dyn Trait]>`
341 if receiver_ty != self.mk_self_type() {
342 if !self.receiver_is_dispatchable(method, receiver_ty) {
343 return Some(MethodViolationCode::UndispatchableReceiver);
345 // sanity check to make sure the receiver actually has the layout of a pointer
347 use crate::ty::layout::Abi;
349 let param_env = self.param_env(method.def_id);
351 let abi_of_ty = |ty: Ty<'tcx>| -> &Abi {
352 match self.layout_of(param_env.and(ty)) {
353 Ok(layout) => &layout.abi,
355 "Error: {}\n while computing layout for type {:?}", err, ty
361 let unit_receiver_ty = self.receiver_for_self_ty(
362 receiver_ty, self.mk_unit(), method.def_id
365 match abi_of_ty(unit_receiver_ty) {
366 &Abi::Scalar(..) => (),
368 self.sess.delay_span_bug(
369 self.def_span(method.def_id),
371 "Receiver when Self = () should have a Scalar ABI, found {:?}",
378 let trait_object_ty = self.object_ty_for_trait(
379 trait_def_id, self.mk_region(ty::ReStatic)
382 // e.g., Rc<dyn Trait>
383 let trait_object_receiver = self.receiver_for_self_ty(
384 receiver_ty, trait_object_ty, method.def_id
387 match abi_of_ty(trait_object_receiver) {
388 &Abi::ScalarPair(..) => (),
390 self.sess.delay_span_bug(
391 self.def_span(method.def_id),
393 "Receiver when Self = {} should have a ScalarPair ABI, found {:?}",
405 /// Performs a type substitution to produce the version of receiver_ty when `Self = self_ty`
406 /// e.g., for receiver_ty = `Rc<Self>` and self_ty = `Foo`, returns `Rc<Foo>`.
407 fn receiver_for_self_ty(
408 self, receiver_ty: Ty<'tcx>, self_ty: Ty<'tcx>, method_def_id: DefId
410 debug!("receiver_for_self_ty({:?}, {:?}, {:?})", receiver_ty, self_ty, method_def_id);
411 let substs = InternalSubsts::for_item(self, method_def_id, |param, _| {
412 if param.index == 0 {
415 self.mk_param_from_def(param)
419 let result = receiver_ty.subst(self, substs);
420 debug!("receiver_for_self_ty({:?}, {:?}, {:?}) = {:?}",
421 receiver_ty, self_ty, method_def_id, result);
425 /// Creates the object type for the current trait. For example,
426 /// if the current trait is `Deref`, then this will be
427 /// `dyn Deref<Target = Self::Target> + 'static`.
428 fn object_ty_for_trait(self, trait_def_id: DefId, lifetime: ty::Region<'tcx>) -> Ty<'tcx> {
429 debug!("object_ty_for_trait: trait_def_id={:?}", trait_def_id);
431 let trait_ref = ty::TraitRef::identity(self, trait_def_id);
433 let trait_predicate = ty::ExistentialPredicate::Trait(
434 ty::ExistentialTraitRef::erase_self_ty(self, trait_ref)
437 let mut associated_types = traits::supertraits(self, ty::Binder::dummy(trait_ref))
438 .flat_map(|super_trait_ref| {
439 self.associated_items(super_trait_ref.def_id())
440 .map(move |item| (super_trait_ref, item))
442 .filter(|(_, item)| item.kind == ty::AssocKind::Type)
443 .collect::<Vec<_>>();
445 // existential predicates need to be in a specific order
446 associated_types.sort_by_cached_key(|(_, item)| self.def_path_hash(item.def_id));
448 let projection_predicates = associated_types.into_iter().map(|(super_trait_ref, item)| {
449 // We *can* get bound lifetimes here in cases like
450 // `trait MyTrait: for<'s> OtherTrait<&'s T, Output=bool>`.
452 // binder moved to (*)...
453 let super_trait_ref = super_trait_ref.skip_binder();
454 ty::ExistentialPredicate::Projection(ty::ExistentialProjection {
455 ty: self.mk_projection(item.def_id, super_trait_ref.substs),
456 item_def_id: item.def_id,
457 substs: super_trait_ref.substs,
461 let existential_predicates = self.mk_existential_predicates(
462 iter::once(trait_predicate).chain(projection_predicates)
465 let object_ty = self.mk_dynamic(
466 // (*) ... binder re-introduced here
467 ty::Binder::bind(existential_predicates),
471 debug!("object_ty_for_trait: object_ty=`{}`", object_ty);
476 /// Checks the method's receiver (the `self` argument) can be dispatched on when `Self` is a
477 /// trait object. We require that `DispatchableFromDyn` be implemented for the receiver type
478 /// in the following way:
479 /// - let `Receiver` be the type of the `self` argument, i.e `Self`, `&Self`, `Rc<Self>`,
480 /// - require the following bound:
483 /// Receiver[Self => T]: DispatchFromDyn<Receiver[Self => dyn Trait]>
486 /// where `Foo[X => Y]` means "the same type as `Foo`, but with `X` replaced with `Y`"
487 /// (substitution notation).
489 /// Some examples of receiver types and their required obligation:
490 /// - `&'a mut self` requires `&'a mut Self: DispatchFromDyn<&'a mut dyn Trait>`,
491 /// - `self: Rc<Self>` requires `Rc<Self>: DispatchFromDyn<Rc<dyn Trait>>`,
492 /// - `self: Pin<Box<Self>>` requires `Pin<Box<Self>>: DispatchFromDyn<Pin<Box<dyn Trait>>>`.
494 /// The only case where the receiver is not dispatchable, but is still a valid receiver
495 /// type (just not object-safe), is when there is more than one level of pointer indirection.
496 /// E.g., `self: &&Self`, `self: &Rc<Self>`, `self: Box<Box<Self>>`. In these cases, there
497 /// is no way, or at least no inexpensive way, to coerce the receiver from the version where
498 /// `Self = dyn Trait` to the version where `Self = T`, where `T` is the unknown erased type
499 /// contained by the trait object, because the object that needs to be coerced is behind
502 /// In practice, we cannot use `dyn Trait` explicitly in the obligation because it would result
503 /// in a new check that `Trait` is object safe, creating a cycle. So instead, we fudge a little
504 /// by introducing a new type parameter `U` such that `Self: Unsize<U>` and `U: Trait + ?Sized`,
505 /// and use `U` in place of `dyn Trait`. Written as a chalk-style query:
507 /// forall (U: Trait + ?Sized) {
508 /// if (Self: Unsize<U>) {
509 /// Receiver: DispatchFromDyn<Receiver[Self => U]>
513 /// for `self: &'a mut Self`, this means `&'a mut Self: DispatchFromDyn<&'a mut U>`
514 /// for `self: Rc<Self>`, this means `Rc<Self>: DispatchFromDyn<Rc<U>>`
515 /// for `self: Pin<Box<Self>>`, this means `Pin<Box<Self>>: DispatchFromDyn<Pin<Box<U>>>`
517 // FIXME(mikeyhew) when unsized receivers are implemented as part of unsized rvalues, add this
518 // fallback query: `Receiver: Unsize<Receiver[Self => U]>` to support receivers like
519 // `self: Wrapper<Self>`.
521 fn receiver_is_dispatchable(
523 method: &ty::AssocItem,
524 receiver_ty: Ty<'tcx>,
526 debug!("receiver_is_dispatchable: method = {:?}, receiver_ty = {:?}", method, receiver_ty);
528 let traits = (self.lang_items().unsize_trait(),
529 self.lang_items().dispatch_from_dyn_trait());
530 let (unsize_did, dispatch_from_dyn_did) = if let (Some(u), Some(cu)) = traits {
533 debug!("receiver_is_dispatchable: Missing Unsize or DispatchFromDyn traits");
537 // the type `U` in the query
538 // use a bogus type parameter to mimick a forall(U) query using u32::MAX for now.
539 // FIXME(mikeyhew) this is a total hack, and we should replace it when real forall queries
541 let unsized_self_ty: Ty<'tcx> = self.mk_ty_param(
543 InternedString::intern("RustaceansAreAwesome"),
546 // `Receiver[Self => U]`
547 let unsized_receiver_ty = self.receiver_for_self_ty(
548 receiver_ty, unsized_self_ty, method.def_id
551 // create a modified param env, with `Self: Unsize<U>` and `U: Trait` added to caller bounds
552 // `U: ?Sized` is already implied here
554 let mut param_env = self.param_env(method.def_id);
557 let unsize_predicate = ty::TraitRef {
559 substs: self.mk_substs_trait(self.mk_self_type(), &[unsized_self_ty.into()]),
562 // U: Trait<Arg1, ..., ArgN>
563 let trait_predicate = {
564 let substs = InternalSubsts::for_item(
566 method.container.assert_trait(),
568 if param.index == 0 {
569 unsized_self_ty.into()
571 self.mk_param_from_def(param)
582 let caller_bounds: Vec<Predicate<'tcx>> = param_env.caller_bounds.iter().cloned()
583 .chain(iter::once(unsize_predicate))
584 .chain(iter::once(trait_predicate))
587 param_env.caller_bounds = self.intern_predicates(&caller_bounds);
592 // Receiver: DispatchFromDyn<Receiver[Self => U]>
594 let predicate = ty::TraitRef {
595 def_id: dispatch_from_dyn_did,
596 substs: self.mk_substs_trait(receiver_ty, &[unsized_receiver_ty.into()]),
600 ObligationCause::dummy(),
606 self.infer_ctxt().enter(|ref infcx| {
607 // the receiver is dispatchable iff the obligation holds
608 infcx.predicate_must_hold_modulo_regions(&obligation)
612 fn contains_illegal_self_type_reference(self,
617 // This is somewhat subtle. In general, we want to forbid
618 // references to `Self` in the argument and return types,
619 // since the value of `Self` is erased. However, there is one
620 // exception: it is ok to reference `Self` in order to access
621 // an associated type of the current trait, since we retain
622 // the value of those associated types in the object type
626 // trait SuperTrait {
630 // trait Trait : SuperTrait {
632 // fn foo(&self, x: Self) // bad
633 // fn foo(&self) -> Self // bad
634 // fn foo(&self) -> Option<Self> // bad
635 // fn foo(&self) -> Self::Y // OK, desugars to next example
636 // fn foo(&self) -> <Self as Trait>::Y // OK
637 // fn foo(&self) -> Self::X // OK, desugars to next example
638 // fn foo(&self) -> <Self as SuperTrait>::X // OK
642 // However, it is not as simple as allowing `Self` in a projected
643 // type, because there are illegal ways to use `Self` as well:
646 // trait Trait : SuperTrait {
648 // fn foo(&self) -> <Self as SomeOtherTrait>::X;
652 // Here we will not have the type of `X` recorded in the
653 // object type, and we cannot resolve `Self as SomeOtherTrait`
654 // without knowing what `Self` is.
656 let mut supertraits: Option<Vec<ty::PolyTraitRef<'tcx>>> = None;
657 let mut error = false;
660 ty::Param(ref param_ty) => {
661 if param_ty.is_self() {
665 false // no contained types to walk
668 ty::Projection(ref data) => {
669 // This is a projected type `<Foo as SomeTrait>::X`.
671 // Compute supertraits of current trait lazily.
672 if supertraits.is_none() {
673 let trait_ref = ty::Binder::bind(
674 ty::TraitRef::identity(self, trait_def_id),
676 supertraits = Some(traits::supertraits(self, trait_ref).collect());
679 // Determine whether the trait reference `Foo as
680 // SomeTrait` is in fact a supertrait of the
681 // current trait. In that case, this type is
682 // legal, because the type `X` will be specified
683 // in the object type. Note that we can just use
684 // direct equality here because all of these types
685 // are part of the formal parameter listing, and
686 // hence there should be no inference variables.
687 let projection_trait_ref = ty::Binder::bind(data.trait_ref(self));
688 let is_supertrait_of_current_trait =
689 supertraits.as_ref().unwrap().contains(&projection_trait_ref);
691 if is_supertrait_of_current_trait {
692 false // do not walk contained types, do not report error, do collect $200
694 true // DO walk contained types, POSSIBLY reporting an error
698 _ => true, // walk contained types, if any
706 pub(super) fn is_object_safe_provider<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
707 trait_def_id: DefId) -> bool {
708 tcx.object_safety_violations(trait_def_id).is_empty()