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;
28 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
29 pub enum ObjectSafetyViolation {
30 /// Self : Sized declared on the trait
33 /// Supertrait reference references `Self` an in illegal location
34 /// (e.g. `trait Foo : Bar<Self>`)
37 /// Method has something illegal
38 Method(ast::Name, MethodViolationCode),
41 /// Reasons a method might not be object-safe.
42 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
43 pub enum MethodViolationCode {
47 /// e.g., `fn foo(&self, x: Self)` or `fn foo(&self) -> Self`
50 /// e.g., `fn foo<A>()`
54 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
55 pub fn is_object_safe(self, trait_def_id: DefId) -> bool {
56 // Because we query yes/no results frequently, we keep a cache:
57 let def = self.lookup_trait_def(trait_def_id);
59 let result = def.object_safety().unwrap_or_else(|| {
60 let result = self.object_safety_violations(trait_def_id).is_empty();
62 // Record just a yes/no result in the cache; this is what is
63 // queried most frequently. Note that this may overwrite a
64 // previous result, but always with the same thing.
65 def.set_object_safety(result);
70 debug!("is_object_safe({:?}) = {}", trait_def_id, result);
75 /// Returns the object safety violations that affect
76 /// astconv - currently, Self in supertraits. This is needed
77 /// because `object_safety_violations` can't be used during
79 pub fn astconv_object_safety_violations(self, trait_def_id: DefId)
80 -> Vec<ObjectSafetyViolation>
82 let mut violations = vec![];
84 for def_id in traits::supertrait_def_ids(self, trait_def_id) {
85 if self.predicates_reference_self(def_id, true) {
86 violations.push(ObjectSafetyViolation::SupertraitSelf);
90 debug!("astconv_object_safety_violations(trait_def_id={:?}) = {:?}",
97 pub fn object_safety_violations(self, trait_def_id: DefId)
98 -> Vec<ObjectSafetyViolation>
100 traits::supertrait_def_ids(self, trait_def_id)
101 .flat_map(|def_id| self.object_safety_violations_for_trait(def_id))
105 fn object_safety_violations_for_trait(self, trait_def_id: DefId)
106 -> Vec<ObjectSafetyViolation>
108 // Check methods for violations.
109 let mut violations: Vec<_> = self.associated_items(trait_def_id)
110 .filter(|item| item.kind == ty::AssociatedKind::Method)
112 self.object_safety_violation_for_method(trait_def_id, &item)
113 .map(|code| ObjectSafetyViolation::Method(item.name, code))
116 // Check the trait itself.
117 if self.trait_has_sized_self(trait_def_id) {
118 violations.push(ObjectSafetyViolation::SizedSelf);
120 if self.predicates_reference_self(trait_def_id, false) {
121 violations.push(ObjectSafetyViolation::SupertraitSelf);
124 debug!("object_safety_violations_for_trait(trait_def_id={:?}) = {:?}",
131 fn predicates_reference_self(
134 supertraits_only: bool) -> bool
136 let trait_ref = ty::Binder(ty::TraitRef {
137 def_id: trait_def_id,
138 substs: Substs::identity_for_item(self, trait_def_id)
140 let predicates = if supertraits_only {
141 self.item_super_predicates(trait_def_id)
143 self.item_predicates(trait_def_id)
148 .map(|predicate| predicate.subst_supertrait(self, &trait_ref))
151 ty::Predicate::Trait(ref data) => {
152 // In the case of a trait predicate, we can skip the "self" type.
153 data.skip_binder().input_types().skip(1).any(|t| t.has_self_ty())
155 ty::Predicate::Projection(..) |
156 ty::Predicate::WellFormed(..) |
157 ty::Predicate::ObjectSafe(..) |
158 ty::Predicate::TypeOutlives(..) |
159 ty::Predicate::RegionOutlives(..) |
160 ty::Predicate::ClosureKind(..) |
161 ty::Predicate::Equate(..) => {
168 fn trait_has_sized_self(self, trait_def_id: DefId) -> bool {
169 self.generics_require_sized_self(trait_def_id)
172 fn generics_require_sized_self(self, def_id: DefId) -> bool {
173 let sized_def_id = match self.lang_items.sized_trait() {
174 Some(def_id) => def_id,
175 None => { return false; /* No Sized trait, can't require it! */ }
178 // Search for a predicate like `Self : Sized` amongst the trait bounds.
179 let free_substs = self.construct_free_substs(def_id,
180 self.region_maps.node_extent(ast::DUMMY_NODE_ID));
181 let predicates = self.item_predicates(def_id);
182 let predicates = predicates.instantiate(self, free_substs).predicates;
183 elaborate_predicates(self, predicates)
186 ty::Predicate::Trait(ref trait_pred) if trait_pred.def_id() == sized_def_id => {
187 trait_pred.0.self_ty().is_self()
189 ty::Predicate::Projection(..) |
190 ty::Predicate::Trait(..) |
191 ty::Predicate::Equate(..) |
192 ty::Predicate::RegionOutlives(..) |
193 ty::Predicate::WellFormed(..) |
194 ty::Predicate::ObjectSafe(..) |
195 ty::Predicate::ClosureKind(..) |
196 ty::Predicate::TypeOutlives(..) => {
203 /// Returns `Some(_)` if this method makes the containing trait not object safe.
204 fn object_safety_violation_for_method(self,
206 method: &ty::AssociatedItem)
207 -> Option<MethodViolationCode>
209 // Any method that has a `Self : Sized` requisite is otherwise
210 // exempt from the regulations.
211 if self.generics_require_sized_self(method.def_id) {
215 self.virtual_call_violation_for_method(trait_def_id, method)
218 /// We say a method is *vtable safe* if it can be invoked on a trait
219 /// object. Note that object-safe traits can have some
220 /// non-vtable-safe methods, so long as they require `Self:Sized` or
221 /// otherwise ensure that they cannot be used when `Self=Trait`.
222 pub fn is_vtable_safe_method(self,
224 method: &ty::AssociatedItem)
227 // Any method that has a `Self : Sized` requisite can't be called.
228 if self.generics_require_sized_self(method.def_id) {
232 self.virtual_call_violation_for_method(trait_def_id, method).is_none()
235 /// Returns `Some(_)` if this method cannot be called on a trait
236 /// object; this does not necessarily imply that the enclosing trait
237 /// is not object safe, because the method might have a where clause
239 fn virtual_call_violation_for_method(self,
241 method: &ty::AssociatedItem)
242 -> Option<MethodViolationCode>
244 // The method's first parameter must be something that derefs (or
245 // autorefs) to `&self`. For now, we only accept `self`, `&self`
247 if !method.method_has_self_argument {
248 return Some(MethodViolationCode::StaticMethod);
251 // The `Self` type is erased, so it should not appear in list of
252 // arguments or return type apart from the receiver.
253 let ref sig = self.item_type(method.def_id).fn_sig();
254 for input_ty in &sig.skip_binder().inputs()[1..] {
255 if self.contains_illegal_self_type_reference(trait_def_id, input_ty) {
256 return Some(MethodViolationCode::ReferencesSelf);
259 if self.contains_illegal_self_type_reference(trait_def_id, sig.output().skip_binder()) {
260 return Some(MethodViolationCode::ReferencesSelf);
263 // We can't monomorphize things like `fn foo<A>(...)`.
264 if !self.item_generics(method.def_id).types.is_empty() {
265 return Some(MethodViolationCode::Generic);
271 fn contains_illegal_self_type_reference(self,
276 // This is somewhat subtle. In general, we want to forbid
277 // references to `Self` in the argument and return types,
278 // since the value of `Self` is erased. However, there is one
279 // exception: it is ok to reference `Self` in order to access
280 // an associated type of the current trait, since we retain
281 // the value of those associated types in the object type
285 // trait SuperTrait {
289 // trait Trait : SuperTrait {
291 // fn foo(&self, x: Self) // bad
292 // fn foo(&self) -> Self // bad
293 // fn foo(&self) -> Option<Self> // bad
294 // fn foo(&self) -> Self::Y // OK, desugars to next example
295 // fn foo(&self) -> <Self as Trait>::Y // OK
296 // fn foo(&self) -> Self::X // OK, desugars to next example
297 // fn foo(&self) -> <Self as SuperTrait>::X // OK
301 // However, it is not as simple as allowing `Self` in a projected
302 // type, because there are illegal ways to use `Self` as well:
305 // trait Trait : SuperTrait {
307 // fn foo(&self) -> <Self as SomeOtherTrait>::X;
311 // Here we will not have the type of `X` recorded in the
312 // object type, and we cannot resolve `Self as SomeOtherTrait`
313 // without knowing what `Self` is.
315 let mut supertraits: Option<Vec<ty::PolyTraitRef<'tcx>>> = None;
316 let mut error = false;
319 ty::TyParam(ref param_ty) => {
320 if param_ty.is_self() {
324 false // no contained types to walk
327 ty::TyProjection(ref data) => {
328 // This is a projected type `<Foo as SomeTrait>::X`.
330 // Compute supertraits of current trait lazily.
331 if supertraits.is_none() {
332 let trait_ref = ty::Binder(ty::TraitRef {
333 def_id: trait_def_id,
334 substs: Substs::identity_for_item(self, trait_def_id)
336 supertraits = Some(traits::supertraits(self, trait_ref).collect());
339 // Determine whether the trait reference `Foo as
340 // SomeTrait` is in fact a supertrait of the
341 // current trait. In that case, this type is
342 // legal, because the type `X` will be specified
343 // in the object type. Note that we can just use
344 // direct equality here because all of these types
345 // are part of the formal parameter listing, and
346 // hence there should be no inference variables.
347 let projection_trait_ref = ty::Binder(data.trait_ref.clone());
348 let is_supertrait_of_current_trait =
349 supertraits.as_ref().unwrap().contains(&projection_trait_ref);
351 if is_supertrait_of_current_trait {
352 false // do not walk contained types, do not report error, do collect $200
354 true // DO walk contained types, POSSIBLY reporting an error
358 _ => true, // walk contained types, if any