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;
29 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
30 pub enum ObjectSafetyViolation {
31 /// Self : Sized declared on the trait
34 /// Supertrait reference references `Self` an in illegal location
35 /// (e.g. `trait Foo : Bar<Self>`)
38 /// Method has something illegal
39 Method(ast::Name, MethodViolationCode),
42 impl ObjectSafetyViolation {
43 pub fn error_msg(&self) -> Cow<'static, str> {
45 ObjectSafetyViolation::SizedSelf =>
46 "the trait cannot require that `Self : Sized`".into(),
47 ObjectSafetyViolation::SupertraitSelf =>
48 "the trait cannot use `Self` as a type parameter \
49 in the supertrait listing".into(),
50 ObjectSafetyViolation::Method(name, MethodViolationCode::StaticMethod) =>
51 format!("method `{}` has no receiver", name).into(),
52 ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelf) =>
53 format!("method `{}` references the `Self` type \
54 in its arguments or return type", name).into(),
55 ObjectSafetyViolation::Method(name, MethodViolationCode::Generic) =>
56 format!("method `{}` has generic type parameters", name).into(),
61 /// Reasons a method might not be object-safe.
62 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
63 pub enum MethodViolationCode {
67 /// e.g., `fn foo(&self, x: Self)` or `fn foo(&self) -> Self`
70 /// e.g., `fn foo<A>()`
74 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
75 pub fn is_object_safe(self, trait_def_id: DefId) -> bool {
76 // Because we query yes/no results frequently, we keep a cache:
77 let def = self.lookup_trait_def(trait_def_id);
79 let result = def.object_safety().unwrap_or_else(|| {
80 let result = self.object_safety_violations(trait_def_id).is_empty();
82 // Record just a yes/no result in the cache; this is what is
83 // queried most frequently. Note that this may overwrite a
84 // previous result, but always with the same thing.
85 def.set_object_safety(result);
90 debug!("is_object_safe({:?}) = {}", trait_def_id, result);
95 /// Returns the object safety violations that affect
96 /// astconv - currently, Self in supertraits. This is needed
97 /// because `object_safety_violations` can't be used during
99 pub fn astconv_object_safety_violations(self, trait_def_id: DefId)
100 -> Vec<ObjectSafetyViolation>
102 let mut violations = vec![];
104 for def_id in traits::supertrait_def_ids(self, trait_def_id) {
105 if self.predicates_reference_self(def_id, true) {
106 violations.push(ObjectSafetyViolation::SupertraitSelf);
110 debug!("astconv_object_safety_violations(trait_def_id={:?}) = {:?}",
117 pub fn object_safety_violations(self, trait_def_id: DefId)
118 -> Vec<ObjectSafetyViolation>
120 traits::supertrait_def_ids(self, trait_def_id)
121 .flat_map(|def_id| self.object_safety_violations_for_trait(def_id))
125 fn object_safety_violations_for_trait(self, trait_def_id: DefId)
126 -> Vec<ObjectSafetyViolation>
128 // Check methods for violations.
129 let mut violations: Vec<_> = self.associated_items(trait_def_id)
130 .filter(|item| item.kind == ty::AssociatedKind::Method)
132 self.object_safety_violation_for_method(trait_def_id, &item)
133 .map(|code| ObjectSafetyViolation::Method(item.name, code))
136 // Check the trait itself.
137 if self.trait_has_sized_self(trait_def_id) {
138 violations.push(ObjectSafetyViolation::SizedSelf);
140 if self.predicates_reference_self(trait_def_id, false) {
141 violations.push(ObjectSafetyViolation::SupertraitSelf);
144 debug!("object_safety_violations_for_trait(trait_def_id={:?}) = {:?}",
151 fn predicates_reference_self(
154 supertraits_only: bool) -> bool
156 let trait_ref = ty::Binder(ty::TraitRef {
157 def_id: trait_def_id,
158 substs: Substs::identity_for_item(self, trait_def_id)
160 let predicates = if supertraits_only {
161 self.item_super_predicates(trait_def_id)
163 self.item_predicates(trait_def_id)
168 .map(|predicate| predicate.subst_supertrait(self, &trait_ref))
171 ty::Predicate::Trait(ref data) => {
172 // In the case of a trait predicate, we can skip the "self" type.
173 data.skip_binder().input_types().skip(1).any(|t| t.has_self_ty())
175 ty::Predicate::Projection(..) |
176 ty::Predicate::WellFormed(..) |
177 ty::Predicate::ObjectSafe(..) |
178 ty::Predicate::TypeOutlives(..) |
179 ty::Predicate::RegionOutlives(..) |
180 ty::Predicate::ClosureKind(..) |
181 ty::Predicate::Equate(..) => {
188 fn trait_has_sized_self(self, trait_def_id: DefId) -> bool {
189 self.generics_require_sized_self(trait_def_id)
192 fn generics_require_sized_self(self, def_id: DefId) -> bool {
193 let sized_def_id = match self.lang_items.sized_trait() {
194 Some(def_id) => def_id,
195 None => { return false; /* No Sized trait, can't require it! */ }
198 // Search for a predicate like `Self : Sized` amongst the trait bounds.
199 let free_substs = self.construct_free_substs(def_id,
200 self.region_maps.node_extent(ast::DUMMY_NODE_ID));
201 let predicates = self.item_predicates(def_id);
202 let predicates = predicates.instantiate(self, free_substs).predicates;
203 elaborate_predicates(self, predicates)
206 ty::Predicate::Trait(ref trait_pred) if trait_pred.def_id() == sized_def_id => {
207 trait_pred.0.self_ty().is_self()
209 ty::Predicate::Projection(..) |
210 ty::Predicate::Trait(..) |
211 ty::Predicate::Equate(..) |
212 ty::Predicate::RegionOutlives(..) |
213 ty::Predicate::WellFormed(..) |
214 ty::Predicate::ObjectSafe(..) |
215 ty::Predicate::ClosureKind(..) |
216 ty::Predicate::TypeOutlives(..) => {
223 /// Returns `Some(_)` if this method makes the containing trait not object safe.
224 fn object_safety_violation_for_method(self,
226 method: &ty::AssociatedItem)
227 -> Option<MethodViolationCode>
229 // Any method that has a `Self : Sized` requisite is otherwise
230 // exempt from the regulations.
231 if self.generics_require_sized_self(method.def_id) {
235 self.virtual_call_violation_for_method(trait_def_id, method)
238 /// We say a method is *vtable safe* if it can be invoked on a trait
239 /// object. Note that object-safe traits can have some
240 /// non-vtable-safe methods, so long as they require `Self:Sized` or
241 /// otherwise ensure that they cannot be used when `Self=Trait`.
242 pub fn is_vtable_safe_method(self,
244 method: &ty::AssociatedItem)
247 // Any method that has a `Self : Sized` requisite can't be called.
248 if self.generics_require_sized_self(method.def_id) {
252 self.virtual_call_violation_for_method(trait_def_id, method).is_none()
255 /// Returns `Some(_)` if this method cannot be called on a trait
256 /// object; this does not necessarily imply that the enclosing trait
257 /// is not object safe, because the method might have a where clause
259 fn virtual_call_violation_for_method(self,
261 method: &ty::AssociatedItem)
262 -> Option<MethodViolationCode>
264 // The method's first parameter must be something that derefs (or
265 // autorefs) to `&self`. For now, we only accept `self`, `&self`
267 if !method.method_has_self_argument {
268 return Some(MethodViolationCode::StaticMethod);
271 // The `Self` type is erased, so it should not appear in list of
272 // arguments or return type apart from the receiver.
273 let ref sig = self.item_type(method.def_id).fn_sig();
274 for input_ty in &sig.skip_binder().inputs()[1..] {
275 if self.contains_illegal_self_type_reference(trait_def_id, input_ty) {
276 return Some(MethodViolationCode::ReferencesSelf);
279 if self.contains_illegal_self_type_reference(trait_def_id, sig.output().skip_binder()) {
280 return Some(MethodViolationCode::ReferencesSelf);
283 // We can't monomorphize things like `fn foo<A>(...)`.
284 if !self.item_generics(method.def_id).types.is_empty() {
285 return Some(MethodViolationCode::Generic);
291 fn contains_illegal_self_type_reference(self,
296 // This is somewhat subtle. In general, we want to forbid
297 // references to `Self` in the argument and return types,
298 // since the value of `Self` is erased. However, there is one
299 // exception: it is ok to reference `Self` in order to access
300 // an associated type of the current trait, since we retain
301 // the value of those associated types in the object type
305 // trait SuperTrait {
309 // trait Trait : SuperTrait {
311 // fn foo(&self, x: Self) // bad
312 // fn foo(&self) -> Self // bad
313 // fn foo(&self) -> Option<Self> // bad
314 // fn foo(&self) -> Self::Y // OK, desugars to next example
315 // fn foo(&self) -> <Self as Trait>::Y // OK
316 // fn foo(&self) -> Self::X // OK, desugars to next example
317 // fn foo(&self) -> <Self as SuperTrait>::X // OK
321 // However, it is not as simple as allowing `Self` in a projected
322 // type, because there are illegal ways to use `Self` as well:
325 // trait Trait : SuperTrait {
327 // fn foo(&self) -> <Self as SomeOtherTrait>::X;
331 // Here we will not have the type of `X` recorded in the
332 // object type, and we cannot resolve `Self as SomeOtherTrait`
333 // without knowing what `Self` is.
335 let mut supertraits: Option<Vec<ty::PolyTraitRef<'tcx>>> = None;
336 let mut error = false;
339 ty::TyParam(ref param_ty) => {
340 if param_ty.is_self() {
344 false // no contained types to walk
347 ty::TyProjection(ref data) => {
348 // This is a projected type `<Foo as SomeTrait>::X`.
350 // Compute supertraits of current trait lazily.
351 if supertraits.is_none() {
352 let trait_ref = ty::Binder(ty::TraitRef {
353 def_id: trait_def_id,
354 substs: Substs::identity_for_item(self, trait_def_id)
356 supertraits = Some(traits::supertraits(self, trait_ref).collect());
359 // Determine whether the trait reference `Foo as
360 // SomeTrait` is in fact a supertrait of the
361 // current trait. In that case, this type is
362 // legal, because the type `X` will be specified
363 // in the object type. Note that we can just use
364 // direct equality here because all of these types
365 // are part of the formal parameter listing, and
366 // hence there should be no inference variables.
367 let projection_trait_ref = ty::Binder(data.trait_ref.clone());
368 let is_supertrait_of_current_trait =
369 supertraits.as_ref().unwrap().contains(&projection_trait_ref);
371 if is_supertrait_of_current_trait {
372 false // do not walk contained types, do not report error, do collect $200
374 true // DO walk contained types, POSSIBLY reporting an error
378 _ => true, // walk contained types, if any