1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! "Object safety" refers to the ability for a trait to be converted
12 //! to an object. In general, traits may only be converted to an
13 //! object if all of their methods meet certain criteria. In particular,
16 //! - have a suitable receiver from which we can extract a vtable;
17 //! - not reference the erased type `Self` except for in this receiver;
18 //! - not have generic type parameters
20 use super::elaborate_predicates;
22 use hir::def_id::DefId;
24 use ty::{self, Ty, TyCtxt, TypeFoldable};
25 use ty::subst::Substs;
26 use ty::util::ExplicitSelf;
30 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
31 pub enum ObjectSafetyViolation {
32 /// Self : Sized declared on the trait
35 /// Supertrait reference references `Self` an in illegal location
36 /// (e.g. `trait Foo : Bar<Self>`)
39 /// Method has something illegal
40 Method(ast::Name, MethodViolationCode),
43 AssociatedConst(ast::Name),
46 impl ObjectSafetyViolation {
47 pub fn error_msg(&self) -> Cow<'static, str> {
49 ObjectSafetyViolation::SizedSelf =>
50 "the trait cannot require that `Self : Sized`".into(),
51 ObjectSafetyViolation::SupertraitSelf =>
52 "the trait cannot use `Self` as a type parameter \
53 in the supertraits or where-clauses".into(),
54 ObjectSafetyViolation::Method(name, MethodViolationCode::StaticMethod) =>
55 format!("method `{}` has no receiver", name).into(),
56 ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelf) =>
57 format!("method `{}` references the `Self` type \
58 in its arguments or return type", name).into(),
59 ObjectSafetyViolation::Method(name, MethodViolationCode::Generic) =>
60 format!("method `{}` has generic type parameters", name).into(),
61 ObjectSafetyViolation::Method(name, MethodViolationCode::NonStandardSelfType) =>
62 format!("method `{}` has a non-standard `self` type", name).into(),
63 ObjectSafetyViolation::AssociatedConst(name) =>
64 format!("the trait cannot contain associated consts like `{}`", name).into(),
69 /// Reasons a method might not be object-safe.
70 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
71 pub enum MethodViolationCode {
75 /// e.g., `fn foo(&self, x: Self)` or `fn foo(&self) -> Self`
78 /// e.g., `fn foo<A>()`
81 /// arbitrary `self` type, e.g. `self: Rc<Self>`
85 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, '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 mut violations = vec![];
96 for def_id in traits::supertrait_def_ids(self, trait_def_id) {
97 if self.predicates_reference_self(def_id, true) {
98 violations.push(ObjectSafetyViolation::SupertraitSelf);
102 debug!("astconv_object_safety_violations(trait_def_id={:?}) = {:?}",
109 pub fn object_safety_violations(self, trait_def_id: DefId)
110 -> Vec<ObjectSafetyViolation>
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::AssociatedKind::Method)
124 self.object_safety_violation_for_method(trait_def_id, &item)
125 .map(|code| ObjectSafetyViolation::Method(item.name, code))
128 // Check the trait itself.
129 if self.trait_has_sized_self(trait_def_id) {
130 violations.push(ObjectSafetyViolation::SizedSelf);
132 if self.predicates_reference_self(trait_def_id, false) {
133 violations.push(ObjectSafetyViolation::SupertraitSelf);
136 violations.extend(self.associated_items(trait_def_id)
137 .filter(|item| item.kind == ty::AssociatedKind::Const)
138 .map(|item| ObjectSafetyViolation::AssociatedConst(item.name)));
140 debug!("object_safety_violations_for_trait(trait_def_id={:?}) = {:?}",
147 fn predicates_reference_self(
150 supertraits_only: bool) -> bool
152 let trait_ref = ty::Binder::dummy(ty::TraitRef {
153 def_id: trait_def_id,
154 substs: Substs::identity_for_item(self, trait_def_id)
156 let predicates = if supertraits_only {
157 self.super_predicates_of(trait_def_id)
159 self.predicates_of(trait_def_id)
164 .map(|predicate| predicate.subst_supertrait(self, &trait_ref))
167 ty::Predicate::Trait(ref data) => {
168 // In the case of a trait predicate, we can skip the "self" type.
169 data.skip_binder().input_types().skip(1).any(|t| t.has_self_ty())
171 ty::Predicate::Projection(..) |
172 ty::Predicate::WellFormed(..) |
173 ty::Predicate::ObjectSafe(..) |
174 ty::Predicate::TypeOutlives(..) |
175 ty::Predicate::RegionOutlives(..) |
176 ty::Predicate::ClosureKind(..) |
177 ty::Predicate::Subtype(..) |
178 ty::Predicate::ConstEvaluatable(..) => {
185 fn trait_has_sized_self(self, trait_def_id: DefId) -> bool {
186 self.generics_require_sized_self(trait_def_id)
189 fn generics_require_sized_self(self, def_id: DefId) -> bool {
190 let sized_def_id = match self.lang_items().sized_trait() {
191 Some(def_id) => def_id,
192 None => { return false; /* No Sized trait, can't require it! */ }
195 // Search for a predicate like `Self : Sized` amongst the trait bounds.
196 let predicates = self.predicates_of(def_id);
197 let predicates = predicates.instantiate_identity(self).predicates;
198 elaborate_predicates(self, predicates)
201 ty::Predicate::Trait(ref trait_pred) if trait_pred.def_id() == sized_def_id => {
202 trait_pred.skip_binder().self_ty().is_self()
204 ty::Predicate::Projection(..) |
205 ty::Predicate::Trait(..) |
206 ty::Predicate::Subtype(..) |
207 ty::Predicate::RegionOutlives(..) |
208 ty::Predicate::WellFormed(..) |
209 ty::Predicate::ObjectSafe(..) |
210 ty::Predicate::ClosureKind(..) |
211 ty::Predicate::TypeOutlives(..) |
212 ty::Predicate::ConstEvaluatable(..) => {
219 /// Returns `Some(_)` if this method makes the containing trait not object safe.
220 fn object_safety_violation_for_method(self,
222 method: &ty::AssociatedItem)
223 -> Option<MethodViolationCode>
225 // Any method that has a `Self : Sized` requisite is otherwise
226 // exempt from the regulations.
227 if self.generics_require_sized_self(method.def_id) {
231 self.virtual_call_violation_for_method(trait_def_id, method)
234 /// We say a method is *vtable safe* if it can be invoked on a trait
235 /// object. Note that object-safe traits can have some
236 /// non-vtable-safe methods, so long as they require `Self:Sized` or
237 /// otherwise ensure that they cannot be used when `Self=Trait`.
238 pub fn is_vtable_safe_method(self,
240 method: &ty::AssociatedItem)
243 // Any method that has a `Self : Sized` requisite can't be called.
244 if self.generics_require_sized_self(method.def_id) {
248 self.virtual_call_violation_for_method(trait_def_id, method).is_none()
251 /// Returns `Some(_)` if this method cannot be called on a trait
252 /// object; this does not necessarily imply that the enclosing trait
253 /// is not object safe, because the method might have a where clause
255 fn virtual_call_violation_for_method(self,
257 method: &ty::AssociatedItem)
258 -> Option<MethodViolationCode>
260 // The method's first parameter must be something that derefs (or
261 // autorefs) to `&self`. For now, we only accept `self`, `&self`
263 if !method.method_has_self_argument {
264 return Some(MethodViolationCode::StaticMethod);
267 let sig = self.fn_sig(method.def_id);
269 let self_ty = self.mk_self_type();
270 let self_arg_ty = sig.skip_binder().inputs()[0];
271 if let ExplicitSelf::Other = ExplicitSelf::determine(self_arg_ty, |ty| ty == self_ty) {
272 return Some(MethodViolationCode::NonStandardSelfType);
275 // The `Self` type is erased, so it should not appear in list of
276 // arguments or return type apart from the receiver.
277 for input_ty in &sig.skip_binder().inputs()[1..] {
278 if self.contains_illegal_self_type_reference(trait_def_id, input_ty) {
279 return Some(MethodViolationCode::ReferencesSelf);
282 if self.contains_illegal_self_type_reference(trait_def_id, sig.output().skip_binder()) {
283 return Some(MethodViolationCode::ReferencesSelf);
286 // We can't monomorphize things like `fn foo<A>(...)`.
287 if self.generics_of(method.def_id).own_counts().types != 0 {
288 return Some(MethodViolationCode::Generic);
294 fn contains_illegal_self_type_reference(self,
299 // This is somewhat subtle. In general, we want to forbid
300 // references to `Self` in the argument and return types,
301 // since the value of `Self` is erased. However, there is one
302 // exception: it is ok to reference `Self` in order to access
303 // an associated type of the current trait, since we retain
304 // the value of those associated types in the object type
308 // trait SuperTrait {
312 // trait Trait : SuperTrait {
314 // fn foo(&self, x: Self) // bad
315 // fn foo(&self) -> Self // bad
316 // fn foo(&self) -> Option<Self> // bad
317 // fn foo(&self) -> Self::Y // OK, desugars to next example
318 // fn foo(&self) -> <Self as Trait>::Y // OK
319 // fn foo(&self) -> Self::X // OK, desugars to next example
320 // fn foo(&self) -> <Self as SuperTrait>::X // OK
324 // However, it is not as simple as allowing `Self` in a projected
325 // type, because there are illegal ways to use `Self` as well:
328 // trait Trait : SuperTrait {
330 // fn foo(&self) -> <Self as SomeOtherTrait>::X;
334 // Here we will not have the type of `X` recorded in the
335 // object type, and we cannot resolve `Self as SomeOtherTrait`
336 // without knowing what `Self` is.
338 let mut supertraits: Option<Vec<ty::PolyTraitRef<'tcx>>> = None;
339 let mut error = false;
342 ty::TyParam(ref param_ty) => {
343 if param_ty.is_self() {
347 false // no contained types to walk
350 ty::TyProjection(ref data) => {
351 // This is a projected type `<Foo as SomeTrait>::X`.
353 // Compute supertraits of current trait lazily.
354 if supertraits.is_none() {
355 let trait_ref = ty::Binder::bind(ty::TraitRef {
356 def_id: trait_def_id,
357 substs: Substs::identity_for_item(self, trait_def_id)
359 supertraits = Some(traits::supertraits(self, trait_ref).collect());
362 // Determine whether the trait reference `Foo as
363 // SomeTrait` is in fact a supertrait of the
364 // current trait. In that case, this type is
365 // legal, because the type `X` will be specified
366 // in the object type. Note that we can just use
367 // direct equality here because all of these types
368 // are part of the formal parameter listing, and
369 // hence there should be no inference variables.
370 let projection_trait_ref = ty::Binder::bind(data.trait_ref(self));
371 let is_supertrait_of_current_trait =
372 supertraits.as_ref().unwrap().contains(&projection_trait_ref);
374 if is_supertrait_of_current_trait {
375 false // do not walk contained types, do not report error, do collect $200
377 true // DO walk contained types, POSSIBLY reporting an error
381 _ => true, // walk contained types, if any
389 pub(super) fn is_object_safe_provider<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
390 trait_def_id: DefId) -> bool {
391 tcx.object_safety_violations(trait_def_id).is_empty()