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, ToPolyTraitRef, Ty, TyCtxt, TypeFoldable};
27 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
28 pub enum ObjectSafetyViolation {
29 /// Self : Sized declared on the trait
32 /// Supertrait reference references `Self` an in illegal location
33 /// (e.g. `trait Foo : Bar<Self>`)
36 /// Method has something illegal
37 Method(ast::Name, MethodViolationCode),
40 /// Reasons a method might not be object-safe.
41 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
42 pub enum MethodViolationCode {
46 /// e.g., `fn foo(&self, x: Self)` or `fn foo(&self) -> Self`
49 /// e.g., `fn foo<A>()`
53 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
54 pub fn is_object_safe(self, trait_def_id: DefId) -> bool {
55 // Because we query yes/no results frequently, we keep a cache:
56 let def = self.lookup_trait_def(trait_def_id);
58 let result = def.object_safety().unwrap_or_else(|| {
59 let result = self.object_safety_violations(trait_def_id).is_empty();
61 // Record just a yes/no result in the cache; this is what is
62 // queried most frequently. Note that this may overwrite a
63 // previous result, but always with the same thing.
64 def.set_object_safety(result);
69 debug!("is_object_safe({:?}) = {}", trait_def_id, result);
74 /// Returns the object safety violations that affect
75 /// astconv - currently, Self in supertraits. This is needed
76 /// because `object_safety_violations` can't be used during
78 pub fn astconv_object_safety_violations(self, trait_def_id: DefId)
79 -> Vec<ObjectSafetyViolation>
81 let mut violations = vec![];
83 if self.supertraits_reference_self(trait_def_id) {
84 violations.push(ObjectSafetyViolation::SupertraitSelf);
87 debug!("astconv_object_safety_violations(trait_def_id={:?}) = {:?}",
94 pub fn object_safety_violations(self, trait_def_id: DefId)
95 -> Vec<ObjectSafetyViolation>
97 traits::supertrait_def_ids(self, trait_def_id)
98 .flat_map(|def_id| self.object_safety_violations_for_trait(def_id))
102 fn object_safety_violations_for_trait(self, trait_def_id: DefId)
103 -> Vec<ObjectSafetyViolation>
105 // Check methods for violations.
106 let mut violations: Vec<_> = self.associated_items(trait_def_id)
107 .filter(|item| item.kind == ty::AssociatedKind::Method)
109 self.object_safety_violation_for_method(trait_def_id, &item)
110 .map(|code| ObjectSafetyViolation::Method(item.name, code))
113 // Check the trait itself.
114 if self.trait_has_sized_self(trait_def_id) {
115 violations.push(ObjectSafetyViolation::SizedSelf);
117 if self.supertraits_reference_self(trait_def_id) {
118 violations.push(ObjectSafetyViolation::SupertraitSelf);
121 debug!("object_safety_violations_for_trait(trait_def_id={:?}) = {:?}",
128 fn supertraits_reference_self(self, trait_def_id: DefId) -> bool {
129 let trait_def = self.lookup_trait_def(trait_def_id);
130 let trait_ref = trait_def.trait_ref.clone();
131 let trait_ref = trait_ref.to_poly_trait_ref();
132 let predicates = self.item_super_predicates(trait_def_id);
136 .map(|predicate| predicate.subst_supertrait(self, &trait_ref))
139 ty::Predicate::Trait(ref data) => {
140 // In the case of a trait predicate, we can skip the "self" type.
141 data.skip_binder().input_types().skip(1).any(|t| t.has_self_ty())
143 ty::Predicate::Projection(..) |
144 ty::Predicate::WellFormed(..) |
145 ty::Predicate::ObjectSafe(..) |
146 ty::Predicate::TypeOutlives(..) |
147 ty::Predicate::RegionOutlives(..) |
148 ty::Predicate::ClosureKind(..) |
149 ty::Predicate::Equate(..) => {
156 fn trait_has_sized_self(self, trait_def_id: DefId) -> bool {
157 self.generics_require_sized_self(trait_def_id)
160 fn generics_require_sized_self(self, def_id: DefId) -> bool {
161 let sized_def_id = match self.lang_items.sized_trait() {
162 Some(def_id) => def_id,
163 None => { return false; /* No Sized trait, can't require it! */ }
166 // Search for a predicate like `Self : Sized` amongst the trait bounds.
167 let free_substs = self.construct_free_substs(def_id,
168 self.region_maps.node_extent(ast::DUMMY_NODE_ID));
169 let predicates = self.item_predicates(def_id);
170 let predicates = predicates.instantiate(self, free_substs).predicates;
171 elaborate_predicates(self, predicates)
174 ty::Predicate::Trait(ref trait_pred) if trait_pred.def_id() == sized_def_id => {
175 trait_pred.0.self_ty().is_self()
177 ty::Predicate::Projection(..) |
178 ty::Predicate::Trait(..) |
179 ty::Predicate::Equate(..) |
180 ty::Predicate::RegionOutlives(..) |
181 ty::Predicate::WellFormed(..) |
182 ty::Predicate::ObjectSafe(..) |
183 ty::Predicate::ClosureKind(..) |
184 ty::Predicate::TypeOutlives(..) => {
191 /// Returns `Some(_)` if this method makes the containing trait not object safe.
192 fn object_safety_violation_for_method(self,
194 method: &ty::AssociatedItem)
195 -> Option<MethodViolationCode>
197 // Any method that has a `Self : Sized` requisite is otherwise
198 // exempt from the regulations.
199 if self.generics_require_sized_self(method.def_id) {
203 self.virtual_call_violation_for_method(trait_def_id, method)
206 /// We say a method is *vtable safe* if it can be invoked on a trait
207 /// object. Note that object-safe traits can have some
208 /// non-vtable-safe methods, so long as they require `Self:Sized` or
209 /// otherwise ensure that they cannot be used when `Self=Trait`.
210 pub fn is_vtable_safe_method(self,
212 method: &ty::AssociatedItem)
215 // Any method that has a `Self : Sized` requisite can't be called.
216 if self.generics_require_sized_self(method.def_id) {
220 self.virtual_call_violation_for_method(trait_def_id, method).is_none()
223 /// Returns `Some(_)` if this method cannot be called on a trait
224 /// object; this does not necessarily imply that the enclosing trait
225 /// is not object safe, because the method might have a where clause
227 fn virtual_call_violation_for_method(self,
229 method: &ty::AssociatedItem)
230 -> Option<MethodViolationCode>
232 // The method's first parameter must be something that derefs (or
233 // autorefs) to `&self`. For now, we only accept `self`, `&self`
235 if !method.method_has_self_argument {
236 return Some(MethodViolationCode::StaticMethod);
239 // The `Self` type is erased, so it should not appear in list of
240 // arguments or return type apart from the receiver.
241 let ref sig = self.item_type(method.def_id).fn_sig();
242 for &input_ty in &sig.0.inputs[1..] {
243 if self.contains_illegal_self_type_reference(trait_def_id, input_ty) {
244 return Some(MethodViolationCode::ReferencesSelf);
247 if self.contains_illegal_self_type_reference(trait_def_id, sig.0.output) {
248 return Some(MethodViolationCode::ReferencesSelf);
251 // We can't monomorphize things like `fn foo<A>(...)`.
252 if !self.item_generics(method.def_id).types.is_empty() {
253 return Some(MethodViolationCode::Generic);
259 fn contains_illegal_self_type_reference(self,
264 // This is somewhat subtle. In general, we want to forbid
265 // references to `Self` in the argument and return types,
266 // since the value of `Self` is erased. However, there is one
267 // exception: it is ok to reference `Self` in order to access
268 // an associated type of the current trait, since we retain
269 // the value of those associated types in the object type
273 // trait SuperTrait {
277 // trait Trait : SuperTrait {
279 // fn foo(&self, x: Self) // bad
280 // fn foo(&self) -> Self // bad
281 // fn foo(&self) -> Option<Self> // bad
282 // fn foo(&self) -> Self::Y // OK, desugars to next example
283 // fn foo(&self) -> <Self as Trait>::Y // OK
284 // fn foo(&self) -> Self::X // OK, desugars to next example
285 // fn foo(&self) -> <Self as SuperTrait>::X // OK
289 // However, it is not as simple as allowing `Self` in a projected
290 // type, because there are illegal ways to use `Self` as well:
293 // trait Trait : SuperTrait {
295 // fn foo(&self) -> <Self as SomeOtherTrait>::X;
299 // Here we will not have the type of `X` recorded in the
300 // object type, and we cannot resolve `Self as SomeOtherTrait`
301 // without knowing what `Self` is.
303 let mut supertraits: Option<Vec<ty::PolyTraitRef<'tcx>>> = None;
304 let mut error = false;
307 ty::TyParam(ref param_ty) => {
308 if param_ty.is_self() {
312 false // no contained types to walk
315 ty::TyProjection(ref data) => {
316 // This is a projected type `<Foo as SomeTrait>::X`.
318 // Compute supertraits of current trait lazily.
319 if supertraits.is_none() {
320 let trait_def = self.lookup_trait_def(trait_def_id);
321 let trait_ref = ty::Binder(trait_def.trait_ref.clone());
322 supertraits = Some(traits::supertraits(self, trait_ref).collect());
325 // Determine whether the trait reference `Foo as
326 // SomeTrait` is in fact a supertrait of the
327 // current trait. In that case, this type is
328 // legal, because the type `X` will be specified
329 // in the object type. Note that we can just use
330 // direct equality here because all of these types
331 // are part of the formal parameter listing, and
332 // hence there should be no inference variables.
333 let projection_trait_ref = ty::Binder(data.trait_ref.clone());
334 let is_supertrait_of_current_trait =
335 supertraits.as_ref().unwrap().contains(&projection_trait_ref);
337 if is_supertrait_of_current_trait {
338 false // do not walk contained types, do not report error, do collect $200
340 true // DO walk contained types, POSSIBLY reporting an error
344 _ => true, // walk contained types, if any